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
| Concept | Rule |
|---|---|
| Token scope | Always bound to one projects row |
| Environment | development | staging | production (lowercase exact) |
| Member attribution | project_tokens.issued_for_member_id (portal member id) |
| Acting staff | Assertion sub (must be in staff_roles) |
| Optional claim | member_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
environmentand optionalenvironment_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:
environmentis required (signed body field)environment_idis optionalissued_for_member_id = claims.member_id ?? claims.sub- Request body may include
member_id. If both claim and body setmember_id, they must be equal or Core returns403 member_mismatch - Existing assertions without
member_idkeep working (issued_for_member_idfalls back tosub)
On token.rotate:
- New token always keeps the old token’s
environment environment_idis inherited; if body sends one and stored isnull→ set it; if stored is non-null and differs →400 environment_change_not_allowed- If body sends
environmentdifferent from the token’s →400 environment_change_not_allowed(same value is OK) issued_for_member_idis 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>, orX-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.
| Setting | Local | Production |
|---|---|---|
ADMIN_ASSERTION_ISSUER | http://localhost:3000 (wrangler [vars]) | admin.ziteox.com |
ADMIN_ASSERTION_PUBLIC_KEYS | kid dev-1 → Ed25519 public key | Monthly kids, e.g. admin-2026-11 |
iss: exact string compare againstADMIN_ASSERTION_ISSUER. Mismatch →401 assertion_invalid(iss mismatch). Missing/empty var → fail closed500 assertion_issuer_not_configured.kid: must be present inADMIN_ASSERTION_PUBLIC_KEYS. Rotate by adding a new kid (e.g.admin-2026-12) and removing the old one when ready. Local stays ondev-1.
JWS claims
| Claim | Required | Notes |
|---|---|---|
iss | yes | Must equal ADMIN_ASSERTION_ISSUER exactly |
aud | yes | Must be core |
sub | yes | Acting staff user id (in staff_roles) |
aal | yes | Must be aal2 |
jti | yes | Unique; replay → 401 assertion_replay |
iat / exp | yes | Max TTL 60s; clock skew ±30s |
action | yes | Must match the route’s expected action |
params_hash | yes | SHA-256 hex of canonical JSON params |
member_id | no | Portal member the action is for |
What params_hash covers
Canonical JSON = UTF-8 JSON with object keys sorted recursively, then SHA-256 hex.
| Method | Signed params |
|---|---|
| POST | The JSON request body (as sent) |
| GET | Path (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_requestafter that.GET /v1/admin/portal-projects/:portal_project_id→{"portal_project_id":"<path value as sent>"}. No query params — any query →400 invalid_requestafter assertion verify. Invalid uuid →400after verify.GET /v1/admin/members/:memberId/tokenswith 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/auditwith no query →{}(Worker defaultslimitto 50)GET /v1/admin/audit?limit=n→{"limit":n}wherenis the integer as sent (JSON number). Values >200 are capped to 200 for the SQLLIMIT, butparams_hashcovers the value as sent.GET /v1/admin/auditwith any subset oftoken_id,project_id,environment,action,outcome,before,limit→ signed object is exactly those query params (same types:limit/beforeas JSON numbers, others as strings). Unknown query keys →400 invalid_requestafter assertion verify. Tampered/added/removed param →401 assertion_invalid.POST /v1/admin/tokens→ full issue body (including requiredenvironment, optionalenvironment_id/member_id)
Role matrix
| role | project.create | project.list | project.update | project.link_status | token.issue | token.rotate | token.revoke | vault.seal | audit.read | member.tokens.list |
|---|---|---|---|---|---|---|---|---|---|---|
forge_admin | yes | yes | yes | yes | yes | yes | yes | yes | yes | yes |
forge_operator | no | yes | no | yes | yes | yes | no | no | yes | yes |
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_idmust equal:memberIdelse403 member_mismatch - Self unless
forge_admin: if the caller’sstaff_rolesrole is notforge_adminand assertionsub≠:memberId→403 member_mismatch.member_idis the Ziteox Account auth user uuid (same id space assub). - Roles:
forge_adminandforge_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
| Route | Action |
|---|---|
GET /v1/admin/projects | project.list (includes allowed_environments, portal_project_id; optional ?portal_project_id= lookup) |
GET /v1/admin/portal-projects/:portal_project_id | project.link_status — portal→Core link + tokens (v1.7; see below) |
PUT /v1/admin/portal-projects/:portal_project_id | project.ensure — idempotent auto-link (v1.7; see below) |
PATCH /v1/admin/projects/:key | project.update — set/clear portal_project_id (forge_admin only) |
POST /v1/admin/secrets | vault.seal — optional environment (default production); must be in project allowed_environments |
GET /v1/admin/audit | audit.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
| Role | Visibility |
|---|---|
forge_admin | All events |
forge_operator | Only 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)
| Param | Signed as | Rule |
|---|---|---|
token_id | string | Exact match |
project_id | string | Exact match |
environment | string | development | staging | production |
action | string | Exact match, or prefix match when the value ends with . (e.g. token. → token.issue, token.rotate, …). LIKE wildcards (%, _, \) in the value are escaped. |
outcome | string | ok | error | denied |
before | number | Cursor: rows with id < before, ordered id DESC |
limit | number | Default 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.
| Action | When | token_id | Typical meta keys |
|---|---|---|---|
token.issue | Issue ok | New token id | last4, scopes, issued_for_member_id, environment, environment_id |
token.rotate | Rotate ok (primary) | New token id | rotated_from (old id), last4, overlap_until, issued_for_member_id, environment, environment_id |
token.rotate | Rotate ok (companion) | Old token id | replaced_by (new id), environment — so filtering by the old key still shows the link |
token.revoke | Revoke ok / denied | Target token | revoked_at / reason, environment |
token.auth | Auth denial | Set when token known; null when unknown/malformed | reason (token_revoked, token_expired, project_disabled, token_invalid, project_mismatch, environment_mismatch, …), optional route / env fields |
npm.packument / npm.tarball | Allow or deny | Set when auth resolved | package, version?, reason?, upstream_status?, via?, hop? |
files.read / tree.read | Allow | Caller token | path, ref, count?, environment |
vault.resolve | Allow | Caller token | label, last4, environment |
publish.create | Allow / deny | Caller token | branch, pr_number?, file_count?, reason?, environment |
scope_denied | Path/capability deny | Caller token | path / 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)
| Code | HTTP | When |
|---|---|---|
assertion_invalid | 401 | Missing assertion; params_hash mismatch (tampered/extra/missing signed param) |
invalid_request | 400 | Unknown query key; bad outcome / non-integer before/limit; bad environment (after assertion verify) |
not_found | 404 | Operator 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 listAuditLinking 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).
| Operation | Route / action | Roles | Signed params |
|---|---|---|---|
| Create with optional link | POST /v1/admin/projects · project.create | forge_admin | Full body (may include portal_project_id) |
| Update / clear link | PATCH /v1/admin/projects/:key · project.update | forge_admin only | {"project_key":"<path key>","portal_project_id":"<uuid>"|null} |
| Lookup by portal id | GET /v1/admin/projects?portal_project_id=<value> · project.list | forge_admin + forge_operator | {"portal_project_id":"<value as sent>"} (no query → {} full list) |
| Link status + tokens | GET /v1/admin/portal-projects/:id · project.link_status | forge_admin + forge_operator | {"portal_project_id":"<path as sent>"} (v1.7; no query) |
| Ensure / auto-link | PUT /v1/admin/portal-projects/:id · project.ensure | forge_admin + forge_operator | Body {"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):
| Event | Action | Meta |
|---|---|---|
| Create (always) | project.create | includes portal_project_id (string | null) |
| Create when set | project.portal_link | {portal_project_id_old:null, portal_project_id_new, via:"create"} |
| PATCH same value | project.update | {changed:false} |
| null → X | project.portal_link | {portal_project_id_old:null, portal_project_id_new:X} |
| X → null | project.portal_unlink | {portal_project_id_old:X, portal_project_id_new:null} |
| X → Y | project.portal_relink | {portal_project_id_old:X, portal_project_id_new:Y} |
| Denied link | project.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 unlinkPortal → Core link status + auto-link (v1.7)
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 status | PUT ensure | |
|---|---|---|
| Route | GET /v1/admin/portal-projects/:portal_project_id | PUT /v1/admin/portal-projects/:portal_project_id |
| Action | project.link_status | project.ensure |
| Signed | {"portal_project_id":"<path as sent>"} | Body as sent (see below) |
| Query | None (any query → 400 after verify) | N/A (JSON body) |
Role rules
| Role | project.link_status | project.ensure | Notes |
|---|---|---|---|
forge_admin | yes | yes | Sees all tokens on linked responses |
forge_operator | yes | yes | Tokens scoped like v1.6 audit (created_by / issued_for_member_id = sub) |
| Other / no staff role | 403 role_denied | 403 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).
GET — link status
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):
revokedifrevoked_atis set- else
expiredifexpires_at <= nowor (replaced_byset and overlap ended: missingoverlap_untiloroverlap_until <= now) - 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) — PortalProjectLinkResponse — 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.
PUT — ensure / auto-link
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)
| Field | Required | Rule |
|---|---|---|
portal_project_id | yes | Must equal path value; mismatch → 400 invalid_request |
name | yes | String; trimmed length 1..120; used as project label |
owner_user_id | no | Non-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(noproject.auto_linkaudit for the loser). - Unique
keycollision → 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)
| Outcome | Action | Notes |
|---|---|---|
| Create | project.auto_link ok | meta { portal_project_id, key, source:"auto" } |
| No-op ensure (already linked) | (none) | Avoid noise on every portal page view |
| Rate-limited | project.ensure denied | meta { 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
- On portal project create, call
ensurePortalProject(id, { name })(or tolerate lazy ensure later). - On first project page view, if
getPortalProject(id)returnslinked:false, call ensure (operators must be able to). - Remove the manual “Link to Core” button from the normal UX.
- 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)
| Code | HTTP | When |
|---|---|---|
assertion_invalid | 401 | Missing assertion; params_hash mismatch |
invalid_request | 400 | Bad uuid; GET query params; body/path mismatch; bad/unknown body fields |
role_denied | 403 | No staff role, or role cannot perform the action |
rate_limited | 429 | Too many project.auto_link creates for this actor in 60s |
key_generation_exhausted | 503 | Could 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)
| Code | HTTP | When |
|---|---|---|
assertion_invalid / assertion_replay | 401 | Missing/bad/replayed assertion; iss mismatch; params_hash mismatch |
assertion_issuer_not_configured | 500 | ADMIN_ASSERTION_ISSUER missing or empty |
action_mismatch | 403 | JWS action ≠ route expectation |
member_mismatch | 403 | Claim / body / path member ids disagree, or non-admin listing another member |
project_mismatch | 403 | X-Ziteox-Project or body project_key ≠ token project |
environment_mismatch | 403 | X-Ziteox-Environment ≠ token environment |
invalid_request | 400 | Missing/empty/non-JSON/non-object admin POST/PATCH body; other field validation |
invalid_environment | 400 | Bad enum, or environment not in project allowed_environments |
environment_change_not_allowed | 400 | Rotate tried to change environment / non-null environment_id |
role_denied | 403 | Staff role cannot perform action |
aal_too_low | 403 | aal ≠ aal2 |
not_found | 404 | Unknown project / token / secret (incl. wrong environment) |
portal_project_already_linked | 409 | portal_project_id already on another Core project |
rate_limited | 429 | Too many project.ensure creates for this actor (60s window) |
key_generation_exhausted | 503 | Auto-link could not allocate a unique project key |
invalid_scope | 400 | Bad scope string, or packages:read mixed with other scopes |
scope_exceeds_project | 403 | Issue/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
v1.7 — Portal → Core link status + auto-link
GET /v1/admin/portal-projects/:portal_project_id·project.link_status: linked project + tokens (orlinked:false/project:null/tokens:[]); project includessource.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.updatestay admin-only. Subjects with no staff role →403 role_denied. - Rate limit:
CORE_ENSURE_RATE_PER_MIN(default 10) creates/min/actor viaproject.auto_linkaudit; 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.ensuredenied{reason:"rate_limited"}. - Migration
0010_project_source.sql:projects.sourcemanual|auto(DEFAULTmanual). Local key-collision hook:CORE_ENSURE_KEY_SUFFIXonly whenCORE_ENVislocal|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)(+ aliasgetPortalProjectLink),admin.ensurePortalProject(id, { name })→PortalProjectEnsureResult; project types includesource.- Backfill:
pnpm backfill:portal-links <file.json>(dry-run default;--applylocalhost-only unless--allow-remote+--assertion-key-file).
v1.6 — Per-key audit trail
GET /v1/admin/audit: filters (token_id,project_id,environment,actionwith prefix-when-endswith-.,outcome), cursor pagination (before/next_before), limit default 50 capped at 200, every query param inparams_hash, unknown params → 400.- Role scoping on the same endpoint:
forge_adminall;forge_operatoronly own-issued / attributed tokens (created_byorissued_for_member_id); foreigntoken_id→ 404. - Per-key coverage:
token_idon issue/rotate/revoke/npm/files/tree/vault/publish/scope_denied and known-tokentoken.authdenials; rotate usesmeta.rotated_from(+ companionmeta.replaced_byon the old id). - Throttled
last_used_aton successful auth; already returned on member token list. @ziteox/core-client:admin.listAudit(query)→{ events, next_before }(auditkept as alias).
v1.5 — Portal project linking
projects.portal_project_id,project.update, lookup viaproject.list?portal_project_id=.