Secrets are encrypted before storage. Reveal is restricted to privileged roles. Revealed values are cleared after 15 seconds.
AI Agent access · Owner onlyStored credentials
Loading…
';
async function login(req, env) {
if (!sameOrigin(req)) return json({ error: "Forbidden" }, 403);
const limit = await rateLimit(req, env, "login");
From 313b00ad293c971f2eb1d0e84ff807a84a6105ba Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 01:00:24 +0700
Subject: [PATCH 05/13] test(token-vault): verify agent API origin and
bearer-key gates
---
security/token-vault/tests/worker.test.mjs | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/security/token-vault/tests/worker.test.mjs b/security/token-vault/tests/worker.test.mjs
index 588eea3..750d3d7 100644
--- a/security/token-vault/tests/worker.test.mjs
+++ b/security/token-vault/tests/worker.test.mjs
@@ -51,3 +51,21 @@ test("same-origin login fails closed when secrets are not configured", async ()
}), {});
assert.equal(response.status, 503);
});
+
+test("agent API rejects requests that carry a browser Origin header", async () => {
+ const response = await worker.fetch(new Request("https://vault.example/api/agent/tokens?project_id=ocodejs-core", {
+ headers: { origin: "https://vault.example" }
+ }), {});
+ assert.equal(response.status, 403);
+});
+
+test("agent API requires an independent bearer credential", async () => {
+ const env = {
+ DB: { prepare() { throw new Error("DB must not be queried without a bearer key"); } },
+ BOOTSTRAP_PASSWORD_HASH: "configured",
+ SESSION_SIGNING_KEY: "s".repeat(32),
+ TOKEN_ENCRYPTION_KEY: Buffer.alloc(32).toString("base64")
+ };
+ const response = await worker.fetch(new Request("https://vault.example/api/agent/tokens?project_id=ocodejs-core"), env);
+ assert.equal(response.status, 401);
+});
From 9d197f0d0fb1ec031e2cf902f46002e15306e12c Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 01:00:27 +0700
Subject: [PATCH 06/13] test(token-vault): validate agent scope security
invariants
---
security/token-vault/scripts/check-source.mjs | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/security/token-vault/scripts/check-source.mjs b/security/token-vault/scripts/check-source.mjs
index ee6c792..468b5b8 100644
--- a/security/token-vault/scripts/check-source.mjs
+++ b/security/token-vault/scripts/check-source.mjs
@@ -24,6 +24,10 @@ for (const marker of [
'rateLimit(req, env, "login")',
'rateLimit(req, env, "reveal")',
'path === "/vault"',
+ "authenticateAgent",
+ "agent_project_grants",
+ "agent.token.reveal",
+ "validProject(projectId)",
'"cache-control": "no-store, max-age=0"'
]) assert.ok(worker.includes(marker), "Missing security invariant: " + marker);
assert.ok(!worker.includes("!origin ||"), "Missing Origin must not be accepted");
@@ -33,3 +37,7 @@ assert.ok(passwordScript.includes("code === 13 || code === 10"), "Password utili
assert.ok(passwordScript.includes("password.length < 16"), "Bootstrap password must be at least 16 chars");
assert.ok(!/sk-[A-Za-z0-9]{20,}/.test(worker + passwordScript), "Possible hard-coded provider token");
console.log("Token Vault source validation passed.");
+
+assert.ok(schema.includes("CREATE TABLE IF NOT EXISTS agent_credentials"));
+assert.ok(schema.includes("CREATE TABLE IF NOT EXISTS agent_project_grants"));
+assert.ok(schema.includes("project_id TEXT NOT NULL DEFAULT 'ocodejs-core'"));
From 88f1194db0864c25bf2a2aae4523f7c8c61971cc Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 01:00:44 +0700
Subject: [PATCH 07/13] docs(token-vault): document scoped AI agent credentials
and project grants
---
security/token-vault/README.md | 79 +++++++++++++++++++++++-----------
1 file changed, 53 insertions(+), 26 deletions(-)
diff --git a/security/token-vault/README.md b/security/token-vault/README.md
index 9bdc727..36dfca9 100644
--- a/security/token-vault/README.md
+++ b/security/token-vault/README.md
@@ -4,49 +4,76 @@ A private credential-management service for OCode.js projects. This source packa
## Current implementation
-- Bootstrap identity is fixed to `TOKEN`; the sign-in screen asks for a password only.
-- Password verification uses PBKDF2-SHA-256 with 310,000 iterations. The verifier is configured as Worker secret `BOOTSTRAP_PASSWORD_HASH`.
+- Bootstrap identity is fixed to TOKEN; the sign-in screen asks for a password only.
+- Password verification uses PBKDF2-SHA-256 with 310,000 iterations. The verifier is configured as Worker secret BOOTSTRAP_PASSWORD_HASH.
- Token values are encrypted server-side with AES-256-GCM and a fresh 96-bit IV before D1 storage.
+- Each token is assigned a project ID (default: ocodejs-core).
- Session cookies are Secure, HttpOnly, SameSite=Strict, signed with a separate key, and expire after four hours. Server-side revocation is supported.
-- State-changing browser requests require an exact same-origin `Origin` and reject cross-site Fetch Metadata.
+- State-changing browser requests require an exact same-origin Origin and reject cross-site Fetch Metadata.
- Login and reveal operations have IP-based D1 rate limits. Authentication responses do not reveal whether an identity exists.
-- The Worker sends no-store and browser security headers. Session role is read from the current identity row, not copied from an old session snapshot.
-- The Worker currently serves its password-only login and credential inventory UI at `/` and `/vault`.
-- Token reveal is explicit, audited, and restricted to `owner` and `security_admin`. The dashboard clears a revealed value after 15 seconds.
+- The Worker sends no-store and browser security headers. Session role is read from the current identity row on every request.
+- The Worker serves its password-only login and credential inventory UI at / and /vault.
+- Token reveal is explicit, audited, and restricted to owner and security_admin. The dashboard clears a revealed value after 15 seconds.
+
+## AI Agent access
+
+Owners can issue a unique machine credential for each agent. The raw API key is shown only once; D1 stores only its SHA-256 hash. Keys expire after 1–365 days (90 days by default) and can be revoked.
+
+Each agent receives explicit per-project grants:
+
+- metadata: list credential metadata for that project.
+- reveal: list metadata and reveal token values for that project.
+
+An agent cannot enumerate other projects, use the human session cookie, or call the browser login. Agent endpoints reject requests carrying an Origin header and require a bearer key. Every successful agent reveal is audited. Never grant an agent a human owner or security_admin role.
+
+Example machine API:
+
+ GET /api/agent/tokens?project_id=ocodejs-core
+ Authorization: Bearer oca_
+
+For an approved reveal grant:
+
+ POST /api/agent/tokens//reveal
+ Authorization: Bearer oca_
## Required Cloudflare resources
- Cloudflare Worker runtime.
-- D1 database created from `schema.sql`.
-- D1 binding named `DB`.
-- Worker secrets: `BOOTSTRAP_PASSWORD_HASH`, `SESSION_SIGNING_KEY`, `TOKEN_ENCRYPTION_KEY`.
+- D1 database created from schema.sql.
+- D1 binding named DB.
+- Worker secrets: BOOTSTRAP_PASSWORD_HASH, SESSION_SIGNING_KEY, TOKEN_ENCRYPTION_KEY.
-Generate a new unique password locally with the hidden-input utility in `scripts/hash-password.mjs`. Store only its output as `BOOTSTRAP_PASSWORD_HASH`. Generate independent random 32-byte signing and encryption keys; store them as Worker secrets. The password previously supplied in chat is exposed and must never be used.
+Generate a new unique password locally with the hidden-input utility in scripts/hash-password.mjs. Store only its output as BOOTSTRAP_PASSWORD_HASH. Generate independent random 32-byte signing and encryption keys; store them as Worker secrets. The password previously supplied in chat is exposed and must never be used.
The encryption key is expected as Base64 or Base64URL encoding of exactly 32 random bytes. The signing key must be at least 32 characters. Do not reuse key material across purposes.
## Roles and current limitations
-| Role | Browse metadata | Create / reveal / delete |
-|---|---:|---:|
-| owner | Yes | Yes |
-| security_admin | Yes | Yes |
-| developer | Yes | No |
-| ai_agent | Yes | No |
-| auditor | Yes | No |
+| Role | Browse metadata | Create / reveal / delete | Manage AI agents |
+|---|---:|---:|---:|
+| owner | Yes | Yes | Yes |
+| security_admin | Yes | Yes | No |
+| developer | Yes | No | No |
+| ai_agent | Project-scoped | Project-granted reveal only | No |
+| auditor | Yes | No | No |
-The current API only bootstraps the `TOKEN` owner identity. It does **not yet** provision staff identities, issue scoped AI-agent grants, or provide a safe token-broker/proxy for agents. Do not grant an agent a human administrator role. The next security milestone is individual identity provisioning plus project-scoped capabilities and audited approval. Until then, AI-agent and staff access is not enabled.
+The bootstrap TOKEN identity is currently the only human login. Individual staff SSO/identity provisioning is not implemented in this milestone. AI Agent credentials are independent, project-scoped machine identities; do not share the bootstrap password with agents or staff.
## API
-- `POST /api/login` — password-only bootstrap login.
-- `POST /api/logout` — revoke the current session.
-- `GET /api/me` — current identity and role.
-- `GET /api/tokens` — credential metadata only.
-- `POST /api/tokens` — encrypt and store a credential.
-- `POST /api/tokens/:id/reveal` — privileged reveal with audit event.
-- `DELETE /api/tokens/:id` — privileged deletion with audit event.
+- POST /api/login — password-only bootstrap login.
+- POST /api/logout — revoke the current session.
+- GET /api/me — current identity and role.
+- GET /api/tokens — credential metadata.
+- POST /api/tokens — encrypt and store a project-scoped credential.
+- POST /api/tokens/:id/reveal — privileged human reveal with audit event.
+- DELETE /api/tokens/:id — privileged deletion with audit event.
+- GET /api/agents, POST /api/agents — owner-only agent inventory and one-time key issuance.
+- GET/POST /api/agents/:subject/grants — owner-only project grants.
+- DELETE /api/agents/:subject — revoke an agent.
+- GET /api/agent/tokens?project_id=... — agent metadata within granted project.
+- POST /api/agent/tokens/:id/reveal — agent reveal only with an explicit reveal grant.
## Validation and deployment
-Run `node security/token-vault/scripts/check-source.mjs` for source validation and `node --test security/token-vault/tests/*.test.mjs` for Worker smoke tests. This repository change is not a deployment. No Worker, D1 database, Access policy, secrets, or live tokens have been created or configured. Keep the service behind Cloudflare Access before any staging exposure.
+Run node security/token-vault/scripts/check-source.mjs for source validation and node --test security/token-vault/tests/*.test.mjs for Worker smoke tests. This repository change is not a deployment. No Worker, D1 database, Access policy, secrets, or live tokens have been created or configured. Keep the service behind Cloudflare Access before any staging exposure.
From 81c300306803f4056038cad8753791bb2c6bfca4 Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 01:01:33 +0700
Subject: [PATCH 08/13] fix(token-vault): align bootstrap password policy and
throttle agent reveals
---
security/token-vault/src/worker.js | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/security/token-vault/src/worker.js b/security/token-vault/src/worker.js
index eee4664..20d358c 100644
--- a/security/token-vault/src/worker.js
+++ b/security/token-vault/src/worker.js
@@ -120,7 +120,7 @@ async function agentGrant(env, agentId, projectId) {
function validProject(value) {
return typeof value === "string" && /^[a-z0-9][a-z0-9._-]{1,63}$/.test(value);
}
-const LOGIN_HTML = 'OCode.js · Token VaultOCODE.JS / SECURITY