Core

Admin portal integration

Per-project, per-environment tokens issued on behalf of a member, member_id assertions, and the member token list API.

Admin portal integration

The admin portal (team-member side of a Ziteox account) registers Core projects and issues per-project tokens on behalf of a member. There is never one member token that spans projects, and never a shared project key. The portal shows one screen that lists that member’s tokens across all their projects (optionally filtered by environment).

Model

ConceptRule
Token scopeAlways bound to one projects row
Environmentdevelopment | staging | production (lowercase exact)
Member attributionproject_tokens.issued_for_member_id (portal member id)
Acting staffAssertion sub (must be in staff_roles)
Optional claimmember_id — portal member the action is for

Environments

  • Enum is exact lowercase: development, staging, production. Anything else → 400 invalid_environment.
  • Projects carry allowed_environments (JSON array). Default on create (and migration backfill): all three. Issue/seal must use an environment in that set.
  • Each token has required environment and optional environment_id (portal environment uuid, ≤128 chars, opaque to Core — linking only).
  • Secrets are unique per (project_id, environment, label) — the same label may exist in each environment.
  • There is no shared project key and no reveal endpoint.

On token.issue:

  • environment is required (signed body field)
  • environment_id is optional
  • issued_for_member_id = claims.member_id ?? claims.sub
  • Request body may include member_id. If both claim and body set member_id, they must be equal or Core returns 403 member_mismatch
  • Existing assertions without member_id keep working (issued_for_member_id falls back to sub)

On token.rotate:

  • New token always keeps the old token’s environment
  • environment_id is inherited; if body sends one and stored is null → set it; if stored is non-null and differs → 400 environment_change_not_allowed
  • If body sends environment different from the token’s → 400 environment_change_not_allowed (same value is OK)
  • issued_for_member_id is inherited; overlap stays 24h

Plaintext zxcore_… is returned exactly once, in the issue/rotate response only — never in list, whoami, or audit.

Defaults (pass 7): legacy tokens/secrets from migrations before 0004_environments.sql are backfilled to production. vault.seal defaults environment to production when omitted. The SQL DEFAULT 'production' on project_tokens.environment / vault exists only for that backfill — application inserts must always send an explicit environment.

Assertion header

Send the compact JWS as either:

  • Authorization: Bearer <jws>, or
  • X-Ziteox-Assertion: <jws>

Project tokens (zxcore_…) are rejected on the management plane.

JWS header

{ "alg": "EdDSA", "kid": "<pinned-key-id>" }

Key pinning (kid + iss)

Core pins assertion trust locally — no remote JWKS at request time.

SettingLocalProduction
ADMIN_ASSERTION_ISSUERhttp://localhost:3000 (wrangler [vars])admin.ziteox.com
ADMIN_ASSERTION_PUBLIC_KEYSkid dev-1 → Ed25519 public keyMonthly kids, e.g. admin-2026-11
  • iss: exact string compare against ADMIN_ASSERTION_ISSUER. Mismatch → 401 assertion_invalid (iss mismatch). Missing/empty var → fail closed 500 assertion_issuer_not_configured.
  • kid: must be present in ADMIN_ASSERTION_PUBLIC_KEYS. Rotate by adding a new kid (e.g. admin-2026-12) and removing the old one when ready. Local stays on dev-1.

JWS claims

ClaimRequiredNotes
issyesMust equal ADMIN_ASSERTION_ISSUER exactly
audyesMust be core
subyesActing staff user id (in staff_roles)
aalyesMust be aal2
jtiyesUnique; replay → 401 assertion_replay
iat / expyesMax TTL 60s; clock skew ±30s
actionyesMust match the route’s expected action
params_hashyesSHA-256 hex of canonical JSON params
member_idnoPortal member the action is for

What params_hash covers

Canonical JSON = UTF-8 JSON with object keys sorted recursively, then SHA-256 hex.

MethodSigned params
POSTThe JSON request body (as sent)
GETPath (and optional query) params as a JSON object — not an empty body

Examples:

  • GET /v1/admin/projects → {}
  • GET /v1/admin/projects?portal_project_id=<value> → {"portal_project_id":"<value>"} where <value> is the query string as sent. Assertion is verified first; invalid uuid → 400 invalid_request after that.
  • GET /v1/admin/portal-projects/:portal_project_id → {"portal_project_id":"<path value as sent>"}. No query params — any query → 400 invalid_request after assertion verify. Invalid uuid → 400 after verify.
  • GET /v1/admin/members/:memberId/tokens with no query → {"member_id":"<memberId>"}
  • Same route with ?include_revoked=false → {"include_revoked":false,"member_id":"<memberId>"}
  • Same route with ?environment=development → {"environment":"development","member_id":"<memberId>"}
  • Both query params → keys sorted together (e.g. environment, include_revoked, member_id)
  • GET /v1/admin/audit with no query → {} (Worker defaults limit to 50)
  • GET /v1/admin/audit?limit=n → {"limit":n} where n is the integer as sent (JSON number). Values >200 are capped to 200 for the SQL LIMIT, but params_hash covers the value as sent.
  • GET /v1/admin/audit with any subset of token_id, project_id, environment, action, outcome, before, limit → signed object is exactly those query params (same types: limit/before as JSON numbers, others as strings). Unknown query keys → 400 invalid_request after assertion verify. Tampered/added/removed param → 401 assertion_invalid.
  • POST /v1/admin/tokens → full issue body (including required environment, optional environment_id / member_id)

Role matrix

roleproject.createproject.listproject.updateproject.link_statustoken.issuetoken.rotatetoken.revokevault.sealaudit.readmember.tokens.list
forge_adminyesyesyesyesyesyesyesyesyesyes
forge_operatornoyesnoyesyesyesnonoyesyes

Management endpoints

POST /v1/admin/projects — project.create

Request:

{
  "key": "portal-a",
  "label": "Portal A",
  "owner_user_id": "user_staff",
  "allowed_scopes": ["read:packages/ui/**", "read:secrets/**"],
  "allowed_environments": ["development", "staging", "production"],
  "portal_project_id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
}

allowed_environments is optional: non-empty subset of the enum, deduped; default all three. Returned on create and list.

Optional portal_project_id: canonical lowercase uuid, or null/absent. Duplicate → 409 portal_project_already_linked (message does not name the other Core project). Response includes portal_project_id (string | null).

If allowed_scopes omits packages:read, Core appends it before storing (project ceiling only). Tokens still need packages:read requested explicitly and alone — see below.

POST /v1/admin/tokens — token.issue

Request:

{
  "project_key": "portal-a",
  "label": "ci",
  "scopes": ["read:packages/ui/**"],
  "ttl_days": 90,
  "member_id": "m_123",
  "environment": "development",
  "environment_id": "portal-env-uuid"
}

environment is required. If not in the project’s allowed_environments → 400 invalid_environment. environment_id optional (string ≤128 chars else 400 invalid_request).

packages:read is opt-in and exclusive. If scopes includes packages:read with any other scope → 400 invalid_scope. Package-install tokens must send scopes: ["packages:read"] alone. The Portal must not put packages:read in its “all of the project’s allowed scopes” default when the user picks none — leave it out of that default and request it only when minting a dedicated install token.

Response 201 (plaintext once):

{
  "id": "…",
  "token": "zxcore_…",
  "last4": "a1b2",
  "expires_at": "…",
  "grants": ["read:packages/ui/**"],
  "issued_for_member_id": "m_123",
  "environment": "development",
  "environment_id": "portal-env-uuid"
}

POST /v1/admin/tokens/:id/rotate — token.rotate

Optional body fields: scopes, ttl_days, label, project_key, environment, environment_id.
If project_key is present and the token belongs to a different project → 403 project_mismatch.
Changing environment (or a non-null environment_id) → 400 environment_change_not_allowed.
When scopes is sent explicitly, the same packages:read-alone rule applies (400 invalid_scope if mixed). Omitting scopes inherits the previous grants (already exclusive).

Response includes a new plaintext token, inherited issued_for_member_id, environment, and environment_id.

POST /v1/admin/tokens/:id/revoke — token.revoke

Optional body: { "project_key": "…" } with the same binding check as rotate.

Revoke stays forge_admin only — decided by Laki on 2026-11-01 (no member self-revoke; forge_operator cannot revoke). Audit row records the token’s environment.

GET /v1/admin/members/:memberId/tokens — member.tokens.list

  • Assertion action = member.tokens.list
  • Claim member_id must equal :memberId else 403 member_mismatch
  • Self unless forge_admin: if the caller’s staff_roles role is not forge_admin and assertion sub ≠ :memberId → 403 member_mismatch. member_id is the Ziteox Account auth user uuid (same id space as sub).
  • Roles: forge_admin and forge_operator (operator may list own tokens only)
  • Query include_revoked=true|false (default true when omitted). If the query param is present, it is part of the signed params object (see above).
  • Optional query environment= (validated enum). When sent, included in the signed params object.

Response 200:

{
  "member_id": "m_123",
  "projects": [
    {
      "project": { "id": "…", "key": "demo-a", "label": "Demo A", "status": "active" },
      "tokens": [
        {
          "id": "…",
          "project_id": "…",
          "project_key": "demo-a",
          "project_label": "Demo A",
          "label": "ci",
          "hint": "zxcore_…a1b2",
          "token_prefix": "zxcore_",
          "last4": "a1b2",
          "scopes": ["read:packages/ui/**"],
          "status": "active",
          "created_at": "…",
          "expires_at": "…",
          "overlap_until": null,
          "replaced_by": null,
          "revoked_at": null,
          "last_used_at": null,
          "environment": "development",
          "environment_id": "portal-env-uuid"
        }
      ]
    }
  ]
}

status is one of active | overlap | expired | revoked.

The list never returns token_hash, plaintext tokens, or a hash key. Each successful list writes one audit row: action member.tokens.list, actor staff (sub), meta { member_id, project_count, token_count, environment } (filter value when set).

Other management routes

RouteAction
GET /v1/admin/projectsproject.list (includes allowed_environments, portal_project_id; optional ?portal_project_id= lookup)
GET /v1/admin/portal-projects/:portal_project_idproject.link_status — portal→Core link + tokens (v1.7; see below)
PUT /v1/admin/portal-projects/:portal_project_idproject.ensure — idempotent auto-link (v1.7; see below)
PATCH /v1/admin/projects/:keyproject.update — set/clear portal_project_id (forge_admin only)
POST /v1/admin/secretsvault.seal — optional environment (default production); must be in project allowed_environments
GET /v1/admin/auditaudit.read — per-key audit feed (v1.6; see below)

Per-key audit feed (v1.6)

Single endpoint: GET /v1/admin/audit · action audit.read. No dedicated /v1/admin/tokens/:id/audit — role scoping on this feed keeps one contract and avoids leaking whether a foreign token id exists.

Role rules

RoleVisibility
forge_adminAll events
forge_operatorOnly events whose token_id is in project_tokens where created_by = sub or issued_for_member_id = sub (tokens the operator issued, or tokens issued for them). Events with token_id NULL (staff/system rows) are not visible. Passing a token_id outside that set → 404 not_found (same as unknown id — no existence leak).

Why created_by or issued_for_member_id: created_by is the issuing staff sub; issued_for_member_id is the portal member the key was minted for. Operators need both — keys they minted for a client, and keys minted for their own member id.

Query params (all optional; each sent key must be in params_hash)

ParamSigned asRule
token_idstringExact match
project_idstringExact match
environmentstringdevelopment | staging | production
actionstringExact match, or prefix match when the value ends with . (e.g. token. → token.issue, token.rotate, …). LIKE wildcards (%, _, \) in the value are escaped.
outcomestringok | error | denied
beforenumberCursor: rows with id < before, ordered id DESC
limitnumberDefault 50; max effective 200 (capped, not rejected). params_hash still covers the uncapped value as sent.

Validation order: assertion presence first (unsigned → 401), then verify params_hash, then unknown keys / bad values → 400 invalid_request.

Response

{
  "events": [
    {
      "id": 42,
      "action": "token.issue",
      "actor_kind": "staff",
      "actor_user_id": "dev-admin",
      "project_id": "…",
      "token_id": "…",
      "outcome": "ok",
      "meta": {
        "last4": "a1b2",
        "scopes": ["read:packages/ui/**"],
        "issued_for_member_id": "m_123",
        "environment": "production",
        "environment_id": null
      },
      "created_at": "2026-11-01T12:00:00.000Z",
      "environment": "production"
    }
  ],
  "next_before": 30
}

Pagination: fetch limit+1 rows. If more exist, next_before is the id of the last event on this page; otherwise null. Pass it as before on the next call. No duplicates across pages when walking next_before.

Per-key event list (token_id + typical meta keys)

Never log secrets, raw tokens, hashes, or plaintext. meta stays small.

ActionWhentoken_idTypical meta keys
token.issueIssue okNew token idlast4, scopes, issued_for_member_id, environment, environment_id
token.rotateRotate ok (primary)New token idrotated_from (old id), last4, overlap_until, issued_for_member_id, environment, environment_id
token.rotateRotate ok (companion)Old token idreplaced_by (new id), environment — so filtering by the old key still shows the link
token.revokeRevoke ok / deniedTarget tokenrevoked_at / reason, environment
token.authAuth denialSet when token known; null when unknown/malformedreason (token_revoked, token_expired, project_disabled, token_invalid, project_mismatch, environment_mismatch, …), optional route / env fields
npm.packument / npm.tarballAllow or denySet when auth resolvedpackage, version?, reason?, upstream_status?, via?, hop?
files.read / tree.readAllowCaller tokenpath, ref, count?, environment
vault.resolveAllowCaller tokenlabel, last4, environment
publish.createAllow / denyCaller tokenbranch, pr_number?, file_count?, reason?, environment
scope_deniedPath/capability denyCaller tokenpath / label, grant_action, environment

Indexes: migration 0009_audit_indexes.sql adds (token_id, id), (project_id, id), (actor_user_id, id), (action, id).

last_used_at

Successful project-token auth updates project_tokens.last_used_at, throttled to at most once per ~5 minutes (UPDATE … WHERE last_used_at IS NULL OR last_used_at < throttle). Exposed on GET /v1/admin/members/:memberId/tokens as tokens[].last_used_at.

Error codes (audit-specific)

CodeHTTPWhen
assertion_invalid401Missing assertion; params_hash mismatch (tampered/extra/missing signed param)
invalid_request400Unknown query key; bad outcome / non-integer before/limit; bad environment (after assertion verify)
not_found404Operator asked for a token_id outside their issued/attributed set

Client

const { events, next_before } = await admin.listAudit({
  token_id: "…",
  action: "token.",
  limit: 50,
});
// admin.audit(query) remains an alias of listAudit

Linking portal projects (v1.5)

Portal stores its own project id; Core stores that id on the Core projects row so the portal can resolve portal project → Core project (at most one Core project per portal id).

OperationRoute / actionRolesSigned params
Create with optional linkPOST /v1/admin/projects · project.createforge_adminFull body (may include portal_project_id)
Update / clear linkPATCH /v1/admin/projects/:key · project.updateforge_admin only{"project_key":"<path key>","portal_project_id":"<uuid>"|null}
Lookup by portal idGET /v1/admin/projects?portal_project_id=<value> · project.listforge_admin + forge_operator{"portal_project_id":"<value as sent>"} (no query → {} full list)
Link status + tokensGET /v1/admin/portal-projects/:id · project.link_statusforge_admin + forge_operator{"portal_project_id":"<path as sent>"} (v1.7; no query)
Ensure / auto-linkPUT /v1/admin/portal-projects/:id · project.ensureforge_admin + forge_operatorBody {"portal_project_id","name",…} (v1.7)

portal_project_id validation: canonical lowercase uuid only (8-4-4-4-12 hex). Uppercase, braces, missing hyphens, wrong length, or non-string → 400 invalid_request (“portal_project_id must be a canonical lowercase uuid”). On GET lookup, assertion is verified before uuid validation (missing/bad assertion → 401, not 400). On PATCH: assertion presence is checked first (missing → 401), then the body must be a JSON object (missing/empty/non-JSON/non-object → 400 invalid_request), then the assertion is verified against the body as sent. Body project_key must equal the path key; any other body field → 400 invalid_request. The field must be present (null = unlink).

Conflicts: linking an id already on another Core project → 409 portal_project_already_linked (“portal_project_id is already linked to another Core project”) — response must not include the other project’s id/key. Key collisions on create stay 409 conflict.

Audit (meta keys avoid forbidden secret-shaped names):

EventActionMeta
Create (always)project.createincludes portal_project_id (string | null)
Create when setproject.portal_link{portal_project_id_old:null, portal_project_id_new, via:"create"}
PATCH same valueproject.update{changed:false}
null → Xproject.portal_link{portal_project_id_old:null, portal_project_id_new:X}
X → nullproject.portal_unlink{portal_project_id_old:X, portal_project_id_new:null}
X → Yproject.portal_relink{portal_project_id_old:X, portal_project_id_new:Y}
Denied linkproject.portal_link outcome denied{reason:"portal_project_already_linked", portal_project_id_new:Y}

PATCH response 200 is the full project row (same shape as list): id, key, label, owner_user_id, status, allowed_scopes, allowed_environments, portal_project_id, source, created_at, updated_at, disabled_at. Lookup miss → 200 { "projects": [] } (0 or 1 rows on hit). Project source is manual (admin create) or auto (portal ensure).

Client helpers: admin.updateProject(key, { portal_project_id }), admin.findProjectByPortalId(uuid) (returns the project or null), admin.getPortalProject(uuid) / alias getPortalProjectLink (v1.7 — link + tokens), admin.ensurePortalProject(uuid, { name }) (v1.7 — auto-link).

Examples:

await admin.createProject({
  key: "portal-a",
  label: "Portal A",
  owner_user_id: "user_staff",
  allowed_scopes: ["read:packages/ui/**"],
  portal_project_id: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
});

await admin.updateProject("portal-a", { portal_project_id: null }); // unlink
const linked = await admin.findProjectByPortalId("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee");
// linked === null after unlink

Two routes share the portal project id path. Prefer these over project.list?portal_project_id= when the portal needs tokens and/or lazy ensure.

GET link statusPUT ensure
RouteGET /v1/admin/portal-projects/:portal_project_idPUT /v1/admin/portal-projects/:portal_project_id
Actionproject.link_statusproject.ensure
Signed{"portal_project_id":"<path as sent>"}Body as sent (see below)
QueryNone (any query → 400 after verify)N/A (JSON body)

Role rules

Roleproject.link_statusproject.ensureNotes
forge_adminyesyesSees all tokens on linked responses
forge_operatoryesyesTokens scoped like v1.6 audit (created_by / issued_for_member_id = sub)
Other / no staff role403 role_denied403 role_denied

Why operators may ensure: the portal signs as the acting staff member; lazy-ensure on project page view must work for operators. Ensure only creates a defaults-only project linked to that exact portal_project_id (source=auto) and never relinks/overrides an existing link — while project.create / project.update stay admin-only (manual create, repair PATCH).

Validation order: assertion presence (unsigned → 401) → verify params_hash → reject query params → canonical uuid (bad → 400).

Token status derivation

active | revoked | expired (no separate overlap — during the rotate overlap window the old token stays active, matching auth acceptance):

  1. revoked if revoked_at is set
  2. else expired if expires_at <= now or (replaced_by set and overlap ended: missing overlap_until or overlap_until <= now)
  3. else active

Tokens ordered by created_at DESC. Scopes from token_grants via formatScope. Response never includes token_hash, plaintext, or secret-shaped fields.

Request

# Signed params_hash covers {"portal_project_id":"<uuid as in path>"}
curl -sS -H "X-Ziteox-Assertion: $JWS" \
  "$CORE/v1/admin/portal-projects/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
const link = await admin.getPortalProject(
  "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
);
// alias: admin.getPortalProjectLink(id) — PortalProjectLink

Response — linked

{
  "linked": true,
  "project": {
    "id": "…",
    "key": "portal-a",
    "label": "Portal A",
    "status": "active",
    "portal_project_id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "source": "manual"
  },
  "tokens": [
    {
      "id": "…",
      "last4": "a1b2",
      "environment": "development",
      "scopes": ["read:packages/ui/**"],
      "status": "active",
      "created_at": "…",
      "expires_at": "…",
      "last_used_at": null,
      "created_by": "dev-admin",
      "issued_for_member_id": "m_123",
      "label": "ci"
    }
  ]
}

replaced_by is included only when set. source is manual or auto.

Response — not linked

{
  "linked": false,
  "project": null,
  "tokens": []
}

Audit (GET)

Successful read writes project.link_status, actor staff (sub), project_id when linked, meta { portal_project_id, linked, token_count } — no secrets.

Validation order: assertion presence (401) → body parse via readJsonObjectBody (missing/empty/non-JSON/non-object → 400) → verify assertion over body as sent (tampered → 401) → validate fields (400).

Request body (exactly what is signed)

FieldRequiredRule
portal_project_idyesMust equal path value; mismatch → 400 invalid_request
nameyesString; trimmed length 1..120; used as project label
owner_user_idnoNon-empty string; default = assertion sub

Unknown keys → 400 invalid_request.

# Signed params_hash covers the JSON body exactly as sent
curl -sS -X PUT -H "X-Ziteox-Assertion: $JWS" -H "Content-Type: application/json" \
  -d '{"portal_project_id":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","name":"Acme Portal"}' \
  "$CORE/v1/admin/portal-projects/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
const ensured = await admin.ensurePortalProject(
  "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
  { name: "Acme Portal" },
);
// PortalProjectEnsureResult — PortalProjectLink & { created: boolean }

Response — created (201)

{
  "created": true,
  "linked": true,
  "project": {
    "id": "…",
    "key": "acme-portal-a1b2c3",
    "label": "Acme Portal",
    "status": "active",
    "portal_project_id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "source": "auto"
  },
  "tokens": []
}

Key = slugify(name) (lowercase a-z0-9-, collapse dashes, trim, max ~40, fallback project) + - + 6-char base36 suffix. Defaults: allowed_scopes: ["packages:read"], allowed_environments: ["development","staging","production"] (same environment default as omitted create; packages:read like migration 0007).

Response — already linked (200)

Same shape as GET link status plus created: false (role-scoped tokens). Does not count toward the ensure rate limit.

{
  "created": false,
  "linked": true,
  "project": {
    "id": "…",
    "key": "acme-portal-a1b2c3",
    "label": "Acme Portal",
    "status": "active",
    "portal_project_id": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "source": "auto"
  },
  "tokens": []
}

Races

  • Insert loses on unique portal_project_id (0008) → re-read winner → 200 created:false (no project.auto_link audit for the loser).
  • Unique key collision → regenerate suffix and retry (up to 5); exhausted → 503 key_generation_exhausted.

Collision test hook (local/e2e only): when CORE_ENV is local or e2e and CORE_ENSURE_KEY_SUFFIX is set, the first auto-key attempt uses that fixed suffix so e2e can pre-create a colliding key. Later attempts always use random. Ignored in production even if the var is set.

Rate limit

Per actor (assertion sub): max CORE_ENSURE_RATE_PER_MIN creates per rolling 60s (default 10), counted from audit_events where action='project.auto_link' AND actor_user_id=sub AND created_at > now-60s (index 0009 on (actor_user_id,id) helps). Exceeded → 429 rate_limited. Already-linked reads are not counted.

Audit (PUT)

OutcomeActionNotes
Createproject.auto_link okmeta { portal_project_id, key, source:"auto" }
No-op ensure (already linked)(none)Avoid noise on every portal page view
Rate-limitedproject.ensure deniedmeta { reason:"rate_limited", portal_project_id }

Migration 0010

apps/core/migrations/0010_project_source.sql — additive:

ALTER TABLE projects ADD COLUMN source TEXT NOT NULL DEFAULT 'manual'
  CHECK (source IN ('manual', 'auto'));

No seed data. Existing rows → manual. Auto-ensure inserts source='auto'. All project responses (create, list, update, GET link status, ensure) include source.

Portal integration steps

  1. On portal project create, call ensurePortalProject(id, { name }) (or tolerate lazy ensure later).
  2. On first project page view, if getPortalProject(id) returns linked:false, call ensure (operators must be able to).
  3. Remove the manual “Link to Core” button from the normal UX.
  4. Keep admin-only PATCH /v1/admin/projects/:key (project.update) for repair (relink / unlink) — operators cannot PATCH.

Local backfill (no portal DB): pnpm backfill:portal-links <entries.json> (dry-run default; --apply against localhost; non-localhost requires --allow-remote + --assertion-key-file).

Error codes (v1.7)

CodeHTTPWhen
assertion_invalid401Missing assertion; params_hash mismatch
invalid_request400Bad uuid; GET query params; body/path mismatch; bad/unknown body fields
role_denied403No staff role, or role cannot perform the action
rate_limited429Too many project.auto_link creates for this actor in 60s
key_generation_exhausted503Could not allocate a unique project key after retries

Project + environment binding (data plane)

  • Optional X-Ziteox-Project: <project_key>. If present and ≠ token project → 403 project_mismatch (audited as denied).
  • Optional X-Ziteox-Environment: <environment>. Invalid enum → 400 invalid_environment. Present and ≠ token environment → 403 environment_mismatch (audited like project_mismatch).

@ziteox/core-client’s createCoreClient({ projectKey?, environment? }) sends these headers when given.

GET /v1/whoami returns environment and environment_id.

Secrets are project- and environment-scoped: a development token reading a label that only exists in production gets 404 not_found (never ciphertext/plaintext). Cross-project reads are the same 404.

Files/tree/publish (mock GitHub) do not branch on environment beyond recording it on the audit row.

Error codes (portal-relevant)

CodeHTTPWhen
assertion_invalid / assertion_replay401Missing/bad/replayed assertion; iss mismatch; params_hash mismatch
assertion_issuer_not_configured500ADMIN_ASSERTION_ISSUER missing or empty
action_mismatch403JWS action ≠ route expectation
member_mismatch403Claim / body / path member ids disagree, or non-admin listing another member
project_mismatch403X-Ziteox-Project or body project_key ≠ token project
environment_mismatch403X-Ziteox-Environment ≠ token environment
invalid_request400Missing/empty/non-JSON/non-object admin POST/PATCH body; other field validation
invalid_environment400Bad enum, or environment not in project allowed_environments
environment_change_not_allowed400Rotate tried to change environment / non-null environment_id
role_denied403Staff role cannot perform action
aal_too_low403aal ≠ aal2
not_found404Unknown project / token / secret (incl. wrong environment)
portal_project_already_linked409portal_project_id already on another Core project
rate_limited429Too many project.ensure creates for this actor (60s window)
key_generation_exhausted503Auto-link could not allocate a unique project key
invalid_scope400Bad scope string, or packages:read mixed with other scopes
scope_exceeds_project403Issue/rotate scopes outside project ceiling

Client helpers

import { createCoreAdminClient, createCoreClient } from "@ziteox/core-client";
import { createEd25519AssertionSigner } from "@ziteox/core-client/admin-signer";

const signAssertion = createEd25519AssertionSigner({
  kid: "…",
  privateKey: jwk,
  sub: "staff_user",
  iss: "http://localhost:3000", // prod: admin.ziteox.com
});

const admin = createCoreAdminClient({ baseUrl, signAssertion });

await admin.issueToken(
  {
    project_key: "portal-a",
    scopes: ["read:packages/ui/**"],
    member_id: "m_123",
    environment: "development",
    environment_id: "portal-env-uuid",
  },
  { memberId: "m_123" },
);

const list = await admin.listMemberTokens("m_123", { environment: "development" });
// list: MemberTokenList — projects[].tokens: MemberTokenSummary[]

const link = await admin.getPortalProject("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee");
// link: PortalProjectLink — linked + project (incl. source) + PortalLinkedToken[]
// admin.getPortalProjectLink(id) remains an alias

const ensured = await admin.ensurePortalProject(
  "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
  { name: "Acme Portal" },
);
// ensured: PortalProjectEnsureResult — { created, linked, project, tokens }

await admin.rotateToken(id, {}, { projectKey: "portal-a" });
await admin.revokeToken(id, {}, { projectKey: "portal-a" });
await admin.sealSecret({
  project_key: "portal-a",
  label: "api_key",
  value: "…",
  environment: "development",
});

const data = createCoreClient({
  baseUrl,
  token: "zxcore_…",
  projectKey: "portal-a",
  environment: "development",
});

signAssertion(action, params, { memberId? }) adds the optional member_id claim when provided. iss is required on the signer and must match Core’s ADMIN_ASSERTION_ISSUER.

Changelog

  • GET /v1/admin/portal-projects/:portal_project_id · project.link_status: linked project + tokens (or linked:false / project:null / tokens:[]); project includes source.
  • PUT /v1/admin/portal-projects/:portal_project_id · project.ensure: idempotent auto-link (201 created:true / 200 created:false); defaults-only project (source=auto, packages:read + all environments); race-safe; rate-limited.
  • Roles: both staff roles for GET + ensure (operators need lazy page-view ensure); project.create / project.update stay admin-only. Subjects with no staff role → 403 role_denied.
  • Rate limit: CORE_ENSURE_RATE_PER_MIN (default 10) creates/min/actor via project.auto_link audit; already-linked ensures not counted → 429 rate_limited.
  • Audit: create → project.auto_link {portal_project_id,key,source:"auto"}; no-op ensure → no audit; rate denial → project.ensure denied {reason:"rate_limited"}.
  • Migration 0010_project_source.sql: projects.source manual|auto (DEFAULT manual). Local key-collision hook: CORE_ENSURE_KEY_SUFFIX only when CORE_ENV is local|e2e.
  • Portal UX: call ensure on create + lazily when GET says linked:false; remove manual Link button; PATCH link stays admin-only for repair.
  • @ziteox/core-client: admin.getPortalProject(id) (+ alias getPortalProjectLink), admin.ensurePortalProject(id, { name }) → PortalProjectEnsureResult; project types include source.
  • Backfill: pnpm backfill:portal-links <file.json> (dry-run default; --apply localhost-only unless --allow-remote + --assertion-key-file).

v1.6 — Per-key audit trail

  • GET /v1/admin/audit: filters (token_id, project_id, environment, action with prefix-when-endswith-., outcome), cursor pagination (before / next_before), limit default 50 capped at 200, every query param in params_hash, unknown params → 400.
  • Role scoping on the same endpoint: forge_admin all; forge_operator only own-issued / attributed tokens (created_by or issued_for_member_id); foreign token_id → 404.
  • Per-key coverage: token_id on issue/rotate/revoke/npm/files/tree/vault/publish/scope_denied and known-token token.auth denials; rotate uses meta.rotated_from (+ companion meta.replaced_by on the old id).
  • Throttled last_used_at on successful auth; already returned on member token list.
  • @ziteox/core-client: admin.listAudit(query) → { events, next_before } (audit kept as alias).

v1.5 — Portal project linking

  • projects.portal_project_id, project.update, lookup via project.list?portal_project_id=.