From c86e773bdf818c813bb0ac01b59d44128e2ada3f Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:06:45 +0700 Subject: [PATCH 01/10] feat(token-vault): add Cloudflare Access staff identity and owner member controls --- security/token-vault/src/worker.js | 95 ++++++++++++++++++++++++++---- 1 file changed, 82 insertions(+), 13 deletions(-) diff --git a/security/token-vault/src/worker.js b/security/token-vault/src/worker.js index 5d1a849..33808c4 100644 --- a/security/token-vault/src/worker.js +++ b/security/token-vault/src/worker.js @@ -76,13 +76,20 @@ async function audit(env, actor, action, resource, outcome = "success") { await env.DB.prepare("INSERT INTO audit_events(id,actor,action,resource_id,outcome) VALUES(?,?,?,?,?)") .bind(crypto.randomUUID(), actor, action, resource || null, outcome).run(); } -async function currentUser(req, env) { +async function currentUser(req, env, ctx) { const id = await verify(cookieValue(req), env.SESSION_SIGNING_KEY); if (!id) return null; const row = await env.DB.prepare("SELECT s.subject,i.role,s.expires_at,i.active FROM sessions s JOIN identities i ON i.subject=s.subject WHERE s.id_hash=? AND s.revoked=0") .bind(await hash(id)).first(); - if (!row || !row.active || row.expires_at <= Math.floor(Date.now() / 1000)) return null; - return { subject: row.subject, role: row.role }; + if (row && row.active && row.expires_at > Math.floor(Date.now() / 1000)) return { subject: row.subject, role: row.role, auth: "session" }; + if (ctx?.access && typeof ctx.access.getIdentity === "function") { + const identity = await ctx.access.getIdentity(); + const email = typeof identity?.email === "string" ? identity.email.trim().toLowerCase() : ""; + if (!email || email.length > 254) return null; + const member = await env.DB.prepare("SELECT subject,role,active FROM identities WHERE subject=?").bind(email).first(); + if (member?.active) return { subject: member.subject, role: member.role, auth: "cloudflare-access" }; + } + return null; } async function key(env) { return crypto.subtle.importKey("raw", unb64(env.TOKEN_ENCRYPTION_KEY), "AES-GCM", false, ["encrypt", "decrypt"]); @@ -141,20 +148,28 @@ async function login(req, env) { await audit(env, "TOKEN", "login", null); return json({ ok: true }, 200, { "set-cookie": cookie(await sign(id, env.SESSION_SIGNING_KEY), SESSION_TTL) }); } -async function route(req, env) { +async function route(req, env, ctx) { const path = new URL(req.url).pathname; - if (req.method === "GET" && (path === "/" || path === "/login")) return page(LOGIN_HTML); - if (path.startsWith("/api/agent/")) { + const isAgentApi = path.startsWith("/api/agent/"); + if (env.ACCESS_REQUIRED === "true" && !isAgentApi && !ctx?.access) return json({ error: "Cloudflare Access authentication required" }, 403); + if (req.method === "GET" && (path === "/" || path === "/login")) { + if (ctx?.access) { + configured(env); + if (await currentUser(req, env, ctx)) return Response.redirect(new URL("/vault", req.url), 303); + } + return page(LOGIN_HTML); + } + if (isAgentApi) { if (req.headers.has("origin")) return json({ error: "Forbidden" }, 403); - } else if ((req.method === "POST" || req.method === "DELETE") && !sameOrigin(req)) return json({ error: "Forbidden" }, 403); + } else if (["POST", "PATCH", "DELETE"].includes(req.method) && !sameOrigin(req)) return json({ error: "Forbidden" }, 403); if (req.method === "GET" && path === "/vault") { configured(env); - return await currentUser(req, env) ? page(VAULT_HTML) : Response.redirect(new URL("/", req.url), 303); + return await currentUser(req, env, ctx) ? page(VAULT_HTML) : Response.redirect(new URL("/", req.url), 303); } configured(env); if (req.method === "POST" && path === "/api/login") return login(req, env); if (req.method === "POST" && path === "/api/logout") { - const user = await currentUser(req, env), id = await verify(cookieValue(req), env.SESSION_SIGNING_KEY); + const user = await currentUser(req, env, ctx), id = await verify(cookieValue(req), env.SESSION_SIGNING_KEY); if (id) await env.DB.prepare("UPDATE sessions SET revoked=1 WHERE id_hash=?").bind(await hash(id)).run(); if (user) await audit(env, user.subject, "logout", null); return json({ ok: true }, 200, { "set-cookie": cookie("", 0) }); @@ -195,9 +210,63 @@ async function route(req, env) { } return json({ error: "Not found" }, 404); } - const user = await currentUser(req, env); + const user = await currentUser(req, env, ctx); if (!user) return json({ error: "Unauthorized" }, 401); - if (req.method === "GET" && path === "/api/me") return json({ subject: user.subject, role: user.role }); + if (req.method === "GET" && path === "/api/me") return json({ subject: user.subject, role: user.role, auth: user.auth || "session" }); + + if (req.method === "GET" && path === "/api/members") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + const rows = await env.DB.prepare( + "SELECT subject,role,active FROM identities WHERE subject<>'TOKEN' AND role<>'ai_agent' ORDER BY subject" + ).all(); + return json({ members: rows.results }); + } + if (req.method === "POST" && path === "/api/members") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } + const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : ""; + const role = body.role; + if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) || email.length > 254 || + !["security_admin", "developer", "auditor"].includes(role)) { + return json({ error: "Invalid member email or role" }, 400); + } + try { + await env.DB.prepare("INSERT INTO identities(id,subject,role,active) VALUES(?,?,?,1)") + .bind(crypto.randomUUID(), email, role).run(); + } catch { + return json({ error: "Member already exists or could not be created" }, 409); + } + await audit(env, user.subject, "member.create", email); + return json({ ok: true, email, role }, 201); + } + const memberPath = path.match(/^\\/api\\/members\\/(.+)$/); + if (memberPath && req.method === "PATCH") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + const email = decodeURIComponent(memberPath[1]).trim().toLowerCase(); + let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } + if (email === "TOKEN" || !["security_admin", "developer", "auditor"].includes(body.role)) { + return json({ error: "Invalid member role" }, 400); + } + const result = await env.DB.prepare("UPDATE identities SET role=? WHERE subject=? AND role<>'ai_agent'") + .bind(body.role, email).run(); + if (!result.meta?.changes) return json({ error: "Member not found" }, 404); + await audit(env, user.subject, "member.role.update", email); + return json({ ok: true }); + } + if (memberPath && req.method === "DELETE") { + if (user.role !== "owner") return json({ error: "Forbidden" }, 403); + const email = decodeURIComponent(memberPath[1]).trim().toLowerCase(); + if (email === "TOKEN") return json({ error: "Cannot revoke bootstrap owner" }, 400); + const result = await env.DB.batch([ + env.DB.prepare("UPDATE identities SET active=0 WHERE subject=? AND role<>'ai_agent'").bind(email), + env.DB.prepare("UPDATE sessions SET revoked=1 WHERE subject=?").bind(email) + ]); + const check = await env.DB.prepare("SELECT active FROM identities WHERE subject=?").bind(email).first(); + if (!check) return json({ error: "Member not found" }, 404); + await audit(env, user.subject, "member.revoke", email); + return json({ ok: true, active: !!check.active }); + } + if (req.method === "GET" && path === "/api/agents") { if (user.role !== "owner") return json({ error: "Forbidden" }, 403); @@ -313,8 +382,8 @@ async function route(req, env) { return json({ error: "Not found" }, 404); } export default { - async fetch(req, env) { - try { return await route(req, env); } + async fetch(req, env, ctx) { + try { return await route(req, env, ctx); } catch { return json({ error: "Vault temporarily unavailable" }, 503); } } }; From fa7195b92adfb12af7497a48381a818070f97d9f Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:06:58 +0700 Subject: [PATCH 02/10] fix(token-vault): correct staff route matchers and prevent agent identity revocation via member API --- security/token-vault/src/worker.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/security/token-vault/src/worker.js b/security/token-vault/src/worker.js index 33808c4..9815503 100644 --- a/security/token-vault/src/worker.js +++ b/security/token-vault/src/worker.js @@ -226,7 +226,7 @@ async function route(req, env, ctx) { let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : ""; const role = body.role; - if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) || email.length > 254 || + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || email.length > 254 || !["security_admin", "developer", "auditor"].includes(role)) { return json({ error: "Invalid member email or role" }, 400); } @@ -239,7 +239,7 @@ async function route(req, env, ctx) { await audit(env, user.subject, "member.create", email); return json({ ok: true, email, role }, 201); } - const memberPath = path.match(/^\\/api\\/members\\/(.+)$/); + const memberPath = path.match(/^\/api\/members\/(.+)$/); if (memberPath && req.method === "PATCH") { if (user.role !== "owner") return json({ error: "Forbidden" }, 403); const email = decodeURIComponent(memberPath[1]).trim().toLowerCase(); @@ -257,14 +257,14 @@ async function route(req, env, ctx) { if (user.role !== "owner") return json({ error: "Forbidden" }, 403); const email = decodeURIComponent(memberPath[1]).trim().toLowerCase(); if (email === "TOKEN") return json({ error: "Cannot revoke bootstrap owner" }, 400); - const result = await env.DB.batch([ - env.DB.prepare("UPDATE identities SET active=0 WHERE subject=? AND role<>'ai_agent'").bind(email), + const check = await env.DB.prepare("SELECT active,role FROM identities WHERE subject=?").bind(email).first(); + if (!check || check.role === "ai_agent") return json({ error: "Member not found" }, 404); + await env.DB.batch([ + env.DB.prepare("UPDATE identities SET active=0 WHERE subject=?").bind(email), env.DB.prepare("UPDATE sessions SET revoked=1 WHERE subject=?").bind(email) ]); - const check = await env.DB.prepare("SELECT active FROM identities WHERE subject=?").bind(email).first(); - if (!check) return json({ error: "Member not found" }, 404); await audit(env, user.subject, "member.revoke", email); - return json({ ok: true, active: !!check.active }); + return json({ ok: true, active: false }); } From 3d82371bf9bfffb3e6c99167486da66767e88fac Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:07:07 +0700 Subject: [PATCH 03/10] test(token-vault): verify Cloudflare Access staff role mapping and least privilege --- .../token-vault/tests/agent-scope.test.mjs | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/security/token-vault/tests/agent-scope.test.mjs b/security/token-vault/tests/agent-scope.test.mjs index 1d3dd40..08dddb3 100644 --- a/security/token-vault/tests/agent-scope.test.mjs +++ b/security/token-vault/tests/agent-scope.test.mjs @@ -128,3 +128,44 @@ test("AI agent grants isolate projects and reveal permission, and revocation wor const afterRevoke = await call("/api/agent/tokens?project_id=project-alpha", env, { headers: bearer }); assert.equal(afterRevoke.status, 401); }); + + +test("Cloudflare Access maps only provisioned staff identities to their assigned roles", async () => { + const { env, password } = makeEnv(); + env.ACCESS_REQUIRED = "true"; + const login = await call("/api/login", env, { + method: "POST", headers: browserHeaders(), body: { password } + }); + assert.equal(login.status, 200); + const cookie = login.headers.get("set-cookie").split(";")[0]; + + const addMember = await call("/api/members", env, { + method: "POST", + headers: browserHeaders(cookie), + body: { email: "dev@example.com", role: "developer" } + }); + assert.equal(addMember.status, 201); + + const accessContext = { access: { getIdentity: async () => ({ email: "DEV@example.com" }) } }; + const staffMe = await worker.fetch(new Request("https://vault.example/api/me"), env, accessContext); + assert.equal(staffMe.status, 200); + assert.deepEqual(await staffMe.json(), { + subject: "dev@example.com", + role: "developer", + auth: "cloudflare-access" + }); + + const deniedWrite = await worker.fetch(new Request("https://vault.example/api/tokens", { + method: "POST", + headers: browserHeaders(), + body: JSON.stringify({ label: "test", provider: "test", project_id: "project-alpha", value: "some-secret-value" }) + }), env, accessContext); + assert.equal(deniedWrite.status, 403); + + const unprovisioned = { access: { getIdentity: async () => ({ email: "unknown@example.com" }) } }; + const unknown = await worker.fetch(new Request("https://vault.example/api/me"), env, unprovisioned); + assert.equal(unknown.status, 401); + + const noAccess = await worker.fetch(new Request("https://vault.example/"), env); + assert.equal(noAccess.status, 403); +}); From 747008e3453d0f96d4ccf88b6dbd3fd96673df8c Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:07:16 +0700 Subject: [PATCH 04/10] feat(token-vault): add owner-only authorized personnel management UI --- security/token-vault/src/worker.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/security/token-vault/src/worker.js b/security/token-vault/src/worker.js index 9815503..6ecda8d 100644 --- a/security/token-vault/src/worker.js +++ b/security/token-vault/src/worker.js @@ -128,7 +128,7 @@ function validProject(value) { return typeof value === "string" && /^[a-z0-9][a-z0-9._-]{1,63}$/.test(value); } const LOGIN_HTML = 'OCode.js · Token Vault
OCODE.JS / SECURITY

Token Vault

Protected credential workspace

'; -const VAULT_HTML = 'OCode.js · Vault
OCode.js / TOKEN VAULT
Checking session…

Credential workspace

Encrypted storage · Explicit reveal · Audited access

Register credential
Security

Secrets are encrypted before storage. Reveal is restricted to privileged roles. Revealed values are cleared after 15 seconds.

Stored credentials
Loading…
'; +const VAULT_HTML = 'OCode.js · Vault
OCode.js / TOKEN VAULT
Checking session…

Credential workspace

Encrypted storage · Explicit reveal · Audited access

Register credential
Security

Secrets are encrypted before storage. Reveal is restricted to privileged roles. Revealed values are cleared after 15 seconds.

Stored credentials
Loading…
'; async function login(req, env) { if (!sameOrigin(req)) return json({ error: "Forbidden" }, 403); const limit = await rateLimit(req, env, "login"); From e698eb8a5affbeefe011a82adc59e6c8d12adef3 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:07:24 +0700 Subject: [PATCH 05/10] docs(token-vault): document Cloudflare Access staff provisioning and enforcement --- security/token-vault/README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/security/token-vault/README.md b/security/token-vault/README.md index 3ed17d4..5ddf798 100644 --- a/security/token-vault/README.md +++ b/security/token-vault/README.md @@ -42,6 +42,8 @@ For an approved reveal grant: - D1 database created from schema.sql. - D1 binding named DB. - Worker secrets: BOOTSTRAP_PASSWORD_HASH, SESSION_SIGNING_KEY, TOKEN_ENCRYPTION_KEY. +- Worker variable: ACCESS_REQUIRED=true before staging/production exposure. +- Cloudflare Access Self-hosted application for the Worker hostname, with Allow policies restricted to approved staff identity emails or groups. Do not add a public bypass policy. 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. @@ -57,7 +59,7 @@ The encryption key is expected as Base64 or Base64URL encoding of exactly 32 ran | ai_agent | Project-scoped | Project-granted reveal only | No | | auditor | Yes | No | No | -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. +Staff use Cloudflare Access SSO. An owner provisions each staff email and assigns security_admin, developer, or auditor; the email from ctx.access.getIdentity() must match an active D1 identity. Set ACCESS_REQUIRED=true on the Worker before exposure. This also blocks direct workers.dev access for browser/human routes; the independent bearer-key agent API remains protected by its own project-scoped credentials. The TOKEN password remains the bootstrap owner login and is never shared with staff or agents. ## API @@ -68,6 +70,9 @@ The bootstrap TOKEN identity is currently the only human login. Individual staff - 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/members, POST /api/members — owner-only personnel inventory and Access email provisioning. +- PATCH /api/members/:email — update staff role. +- DELETE /api/members/:email — disable staff identity and revoke sessions. - 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. @@ -80,3 +85,5 @@ Run node security/token-vault/scripts/check-source.mjs for source validation and Schema validation is executed against an in-memory SQLite database in CI before the Worker integration suite. + +Cloudflare Workers exposes authenticated Access identity through ctx.access; the Worker uses the verified email claim and then checks the matching active D1 identity before assigning application permissions. See the official Cloudflare Workers Access integration guide: https://developers.cloudflare.com/workers/configuration/cloudflare-access/. From 16f2239253345afb581db61a46c8c5c691686300 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:07:35 +0700 Subject: [PATCH 06/10] test(token-vault): cover Access-protected staff provisioning and role enforcement --- .../token-vault/tests/agent-scope.test.mjs | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/security/token-vault/tests/agent-scope.test.mjs b/security/token-vault/tests/agent-scope.test.mjs index 08dddb3..40d9de7 100644 --- a/security/token-vault/tests/agent-scope.test.mjs +++ b/security/token-vault/tests/agent-scope.test.mjs @@ -169,3 +169,43 @@ test("Cloudflare Access maps only provisioned staff identities to their assigned const noAccess = await worker.fetch(new Request("https://vault.example/"), env); assert.equal(noAccess.status, 403); }); + + +test("owner provisions personnel and Cloudflare Access enforces the assigned role", async () => { + const { env, password } = makeEnv(); + env.ACCESS_REQUIRED = "true"; + const accessContext = { access: { getIdentity: async () => ({ email: "owner-operator@example.com" }) } }; + const login = await worker.fetch(new Request("https://vault.example/api/login", { + method: "POST", + headers: browserHeaders(), + body: JSON.stringify({ password }) + }), env, accessContext); + assert.equal(login.status, 200); + const cookie = login.headers.get("set-cookie").split(";")[0]; + + const createMember = await worker.fetch(new Request("https://vault.example/api/members", { + method: "POST", + headers: browserHeaders(cookie), + body: JSON.stringify({ email: "developer@example.com", role: "developer" }) + }), env, accessContext); + assert.equal(createMember.status, 201); + + const staffContext = { access: { getIdentity: async () => ({ email: "DEVELOPER@example.com" }) } }; + const me = await worker.fetch(new Request("https://vault.example/api/me"), env, staffContext); + assert.equal(me.status, 200); + assert.deepEqual(await me.json(), { + subject: "developer@example.com", + role: "developer", + auth: "cloudflare-access" + }); + + const forbidden = await worker.fetch(new Request("https://vault.example/api/tokens", { + method: "POST", + headers: browserHeaders(), + body: JSON.stringify({ label: "forbidden", provider: "test", project_id: "project-a", value: "not-a-real-secret" }) + }), env, staffContext); + assert.equal(forbidden.status, 403); + + const noAccess = await worker.fetch(new Request("https://vault.example/"), env); + assert.equal(noAccess.status, 403); +}); From 65450cb83b33efc17164ca7a5ce55c1fb11acde4 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:07:37 +0700 Subject: [PATCH 07/10] test(token-vault): assert Cloudflare Access staff gates --- security/token-vault/scripts/check-source.mjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/security/token-vault/scripts/check-source.mjs b/security/token-vault/scripts/check-source.mjs index 468b5b8..54c4b1d 100644 --- a/security/token-vault/scripts/check-source.mjs +++ b/security/token-vault/scripts/check-source.mjs @@ -28,6 +28,9 @@ for (const marker of [ "agent_project_grants", "agent.token.reveal", "validProject(projectId)", + "ctx.access.getIdentity", + "ACCESS_REQUIRED", + "/api/members", '"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"); From 4d9bbaf0092d70425eef58a1ba7803b967f93013 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:08:09 +0700 Subject: [PATCH 08/10] test(token-vault): remove obsolete Access test that omitted runtime context --- .../token-vault/tests/agent-scope.test.mjs | 41 ------------------- 1 file changed, 41 deletions(-) diff --git a/security/token-vault/tests/agent-scope.test.mjs b/security/token-vault/tests/agent-scope.test.mjs index 40d9de7..1b8cff8 100644 --- a/security/token-vault/tests/agent-scope.test.mjs +++ b/security/token-vault/tests/agent-scope.test.mjs @@ -130,47 +130,6 @@ test("AI agent grants isolate projects and reveal permission, and revocation wor }); -test("Cloudflare Access maps only provisioned staff identities to their assigned roles", async () => { - const { env, password } = makeEnv(); - env.ACCESS_REQUIRED = "true"; - const login = await call("/api/login", env, { - method: "POST", headers: browserHeaders(), body: { password } - }); - assert.equal(login.status, 200); - const cookie = login.headers.get("set-cookie").split(";")[0]; - - const addMember = await call("/api/members", env, { - method: "POST", - headers: browserHeaders(cookie), - body: { email: "dev@example.com", role: "developer" } - }); - assert.equal(addMember.status, 201); - - const accessContext = { access: { getIdentity: async () => ({ email: "DEV@example.com" }) } }; - const staffMe = await worker.fetch(new Request("https://vault.example/api/me"), env, accessContext); - assert.equal(staffMe.status, 200); - assert.deepEqual(await staffMe.json(), { - subject: "dev@example.com", - role: "developer", - auth: "cloudflare-access" - }); - - const deniedWrite = await worker.fetch(new Request("https://vault.example/api/tokens", { - method: "POST", - headers: browserHeaders(), - body: JSON.stringify({ label: "test", provider: "test", project_id: "project-alpha", value: "some-secret-value" }) - }), env, accessContext); - assert.equal(deniedWrite.status, 403); - - const unprovisioned = { access: { getIdentity: async () => ({ email: "unknown@example.com" }) } }; - const unknown = await worker.fetch(new Request("https://vault.example/api/me"), env, unprovisioned); - assert.equal(unknown.status, 401); - - const noAccess = await worker.fetch(new Request("https://vault.example/"), env); - assert.equal(noAccess.status, 403); -}); - - test("owner provisions personnel and Cloudflare Access enforces the assigned role", async () => { const { env, password } = makeEnv(); env.ACCESS_REQUIRED = "true"; From f4b73ce8debdfb3e6a46a82d3d69fe5031b27009 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:08:35 +0700 Subject: [PATCH 09/10] fix(token-vault): resolve Cloudflare Access identities when no session cookie exists --- security/token-vault/src/worker.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/security/token-vault/src/worker.js b/security/token-vault/src/worker.js index 6ecda8d..14053d2 100644 --- a/security/token-vault/src/worker.js +++ b/security/token-vault/src/worker.js @@ -78,10 +78,11 @@ async function audit(env, actor, action, resource, outcome = "success") { } async function currentUser(req, env, ctx) { const id = await verify(cookieValue(req), env.SESSION_SIGNING_KEY); - if (!id) return null; - const row = await env.DB.prepare("SELECT s.subject,i.role,s.expires_at,i.active FROM sessions s JOIN identities i ON i.subject=s.subject WHERE s.id_hash=? AND s.revoked=0") - .bind(await hash(id)).first(); - if (row && row.active && row.expires_at > Math.floor(Date.now() / 1000)) return { subject: row.subject, role: row.role, auth: "session" }; + if (id) { + const row = await env.DB.prepare("SELECT s.subject,i.role,s.expires_at,i.active FROM sessions s JOIN identities i ON i.subject=s.subject WHERE s.id_hash=? AND s.revoked=0") + .bind(await hash(id)).first(); + if (row && row.active && row.expires_at > Math.floor(Date.now() / 1000)) return { subject: row.subject, role: row.role, auth: "session" }; + } if (ctx?.access && typeof ctx.access.getIdentity === "function") { const identity = await ctx.access.getIdentity(); const email = typeof identity?.email === "string" ? identity.email.trim().toLowerCase() : ""; From eb8ca3bd71a720f60baf0d96e0253727a2a21985 Mon Sep 17 00:00:00 2001 From: zskbot <241179063+zskbot@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:08:43 +0700 Subject: [PATCH 10/10] docs(token-vault): note active Access identity checks --- security/token-vault/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/security/token-vault/README.md b/security/token-vault/README.md index 5ddf798..2a5f6b5 100644 --- a/security/token-vault/README.md +++ b/security/token-vault/README.md @@ -87,3 +87,5 @@ Run node security/token-vault/scripts/check-source.mjs for source validation and Schema validation is executed against an in-memory SQLite database in CI before the Worker integration suite. Cloudflare Workers exposes authenticated Access identity through ctx.access; the Worker uses the verified email claim and then checks the matching active D1 identity before assigning application permissions. See the official Cloudflare Workers Access integration guide: https://developers.cloudflare.com/workers/configuration/cloudflare-access/. + +Staff Access identity is checked against the active D1 identity record on every authenticated request.