diff --git a/.github/workflows/token-vault-validation.yml b/.github/workflows/token-vault-validation.yml new file mode 100644 index 0000000..67ca2a8 --- /dev/null +++ b/.github/workflows/token-vault-validation.yml @@ -0,0 +1,28 @@ +name: Token Vault validation + +on: + pull_request: + paths: + - "security/token-vault/**" + - ".github/workflows/token-vault-validation.yml" + push: + branches: [main] + paths: + - "security/token-vault/**" + - ".github/workflows/token-vault-validation.yml" + +permissions: + contents: read + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Validate Worker and password utility + run: node security/token-vault/scripts/check-source.mjs + - name: Run Worker smoke tests + run: node --test security/token-vault/tests/*.test.mjs diff --git a/security/token-vault/README.md b/security/token-vault/README.md index c38c8bb..9bdc727 100644 --- a/security/token-vault/README.md +++ b/security/token-vault/README.md @@ -1,50 +1,52 @@ # OCode.js Token Vault -A private credential-management service for OCode.js projects. This directory is an application source package, not a place to store actual credentials. +A private credential-management service for OCode.js projects. This source package contains no live credentials. -## Security model +## Current implementation -- The bootstrap account identifier is fixed to `TOKEN`; the login screen asks only for a password. -- The bootstrap password is configured as a Cloudflare Worker secret in PBKDF2-SHA-256 format. It is never committed. -- Do not use a password that has been pasted into chat, source control, screenshots, or logs. The password mentioned in the project request is considered exposed and must be replaced with a new, unique password before deployment. -- Token values are encrypted server-side with AES-256-GCM before D1 storage. The encryption key is a separate Worker secret. -- Session cookies are HttpOnly, Secure, SameSite=Strict, signed with a separate secret, and expire. -- Token plaintext is returned only from an explicit reveal endpoint to roles `owner` and `security_admin`; every reveal is audited. -- Developer and AI-agent roles receive metadata / masked values by default, never plaintext. -- Login attempts are rate-limited in D1. Responses do not disclose whether an account exists. -- No token is ever placed in browser storage, HTML, client-side JavaScript, URL parameters, logs, or repository files. +- 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. +- 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. +- 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. ## Required Cloudflare resources -- Workers runtime for the API and static frontend. -- D1 database using `schema.sql`. +- Cloudflare Worker runtime. +- D1 database created from `schema.sql`. +- D1 binding named `DB`. - Worker secrets: `BOOTSTRAP_PASSWORD_HASH`, `SESSION_SIGNING_KEY`, `TOKEN_ENCRYPTION_KEY`. -- Bind D1 as `DB`. -Generate a password hash outside the repository using PBKDF2-SHA-256 (minimum 310,000 iterations), then set the resulting `salt:hash` value as `BOOTSTRAP_PASSWORD_HASH`. Generate independent random 32-byte values for the signing and encryption keys. Never reuse the same key for multiple purposes. +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. -## Roles +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. -| Role | Browse metadata | Create / rotate | Reveal plaintext | Manage members | -|---|---:|---:|---:|---:| -| owner | Yes | Yes | Yes | Yes | -| security_admin | Yes | Yes | Yes | Limited | -| developer | Yes | Request only | No | No | -| ai_agent | Scoped metadata | Scoped request only | No | No | -| auditor | Audit metadata | No | No | No | +## Roles and current limitations -The bootstrap `TOKEN` identity is the initial owner. Additional identities must be provisioned by an owner through a future audited admin workflow; never share the bootstrap password with developers or agents. +| Role | Browse metadata | Create / reveal / delete | +|---|---:|---:| +| owner | Yes | Yes | +| security_admin | Yes | Yes | +| developer | Yes | No | +| ai_agent | Yes | No | +| auditor | Yes | 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. ## API - `POST /api/login` — password-only bootstrap login. -- `POST /api/logout` — clear session. -- `GET /api/me` — current role. -- `GET /api/tokens` — metadata and masked token values. -- `POST /api/tokens` — encrypt and store a token. -- `POST /api/tokens/:id/reveal` — privileged reveal with audit record. -- `DELETE /api/tokens/:id` — privileged delete with audit record. +- `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. -## Deployment status +## Validation and deployment -This is a staging implementation proposal in the OCode.js control repository. It has not been deployed and does not contain any live secrets. Protect the eventual hostname with Cloudflare Access as an additional identity/network gate, and keep the Worker API private to the intended application origin. +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. diff --git a/security/token-vault/scripts/check-source.mjs b/security/token-vault/scripts/check-source.mjs new file mode 100644 index 0000000..ee6c792 --- /dev/null +++ b/security/token-vault/scripts/check-source.mjs @@ -0,0 +1,35 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const root = new URL("../", import.meta.url); +const workerPath = fileURLToPath(new URL("src/worker.js", root)); +const schemaPath = fileURLToPath(new URL("schema.sql", root)); +const passwordPath = fileURLToPath(new URL("scripts/hash-password.mjs", root)); +const worker = readFileSync(workerPath, "utf8"); +const schema = readFileSync(schemaPath, "utf8"); +const passwordScript = readFileSync(passwordPath, "utf8"); + +for (const path of [workerPath, passwordPath]) { + const result = spawnSync(process.execPath, ["--check", path], { encoding: "utf8" }); + assert.equal(result.status, 0, result.stderr || "Node syntax check failed: " + path); +} +for (const marker of [ + "origin === new URL(req.url).origin", + 'crypto.subtle.verify("HMAC"', + 'SameSite=Strict', + "i.role", + "AES-GCM", + 'rateLimit(req, env, "login")', + 'rateLimit(req, env, "reveal")', + 'path === "/vault"', + '"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"); +assert.ok(schema.includes("CREATE TABLE IF NOT EXISTS sessions")); +assert.ok(schema.includes("CREATE TABLE IF NOT EXISTS audit_events")); +assert.ok(passwordScript.includes("code === 13 || code === 10"), "Password utility must finish on Enter"); +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."); diff --git a/security/token-vault/scripts/hash-password.mjs b/security/token-vault/scripts/hash-password.mjs index db93656..d2795f1 100644 --- a/security/token-vault/scripts/hash-password.mjs +++ b/security/token-vault/scripts/hash-password.mjs @@ -5,28 +5,47 @@ if (!stdin.isTTY || !stdin.setRawMode) { console.error("Run in an interactive terminal so the password can be entered without echo."); process.exit(1); } -stdout.write("New unique vault password (hidden): "); + +stdout.write("New unique vault password (hidden, minimum 16 characters): "); stdin.setRawMode(true); stdin.resume(); stdin.setEncoding("utf8"); + let password = ""; -stdin.on("data", (chunk) => { +let finished = false; + +function finish() { + if (finished) return; + finished = true; + stdin.setRawMode(false); + stdin.pause(); + if (password.length < 16) { + password = ""; + stdout.write("\nPassword must contain at least 16 characters. No hash was generated.\n"); + process.exitCode = 1; + return; + } + const salt = randomBytes(16); + const derived = pbkdf2Sync(password, salt, 310000, 32, "sha256"); + password = ""; + stdout.write("\nPBKDF2-SHA256 salt:hash (store only as Worker secret):\n"); + stdout.write(salt.toString("base64") + ":" + derived.toString("base64") + "\n"); +} + +stdin.on("data", chunk => { for (const char of chunk) { - if (char === "\\u0003") { - stdout.write("\\nCancelled.\\n"); + const code = char.charCodeAt(0); + if (code === 3) { + password = ""; + stdin.setRawMode(false); + stdout.write("\nCancelled.\n"); process.exit(130); } - if (char === "\\r" || char === "\\n") { - stdin.setRawMode(false); - stdin.pause(); - const salt = randomBytes(16); - const hash = pbkdf2Sync(password, salt, 310000, 32, "sha256"); - stdout.write("\\nPBKDF2-SHA256 salt:hash (store only as Worker secret):\\n"); - stdout.write(`${salt.toString("base64")}:${hash.toString("base64")}\\n`); - password = ""; + if (code === 13 || code === 10) { + finish(); return; } - if (char === "\\u007f" || char === "\\b") password = password.slice(0, -1); - else password += char; + if (code === 127 || code === 8) password = password.slice(0, -1); + else if (code >= 32) password += char; } }); diff --git a/security/token-vault/src/worker.js b/security/token-vault/src/worker.js index 18f3a79..ce35bee 100644 --- a/security/token-vault/src/worker.js +++ b/security/token-vault/src/worker.js @@ -1,137 +1,189 @@ -const SESSION_TTL = 8 * 60 * 60; +const SESSION_TTL = 4 * 60 * 60; +const WINDOW = 900; +const LIMITS = { login: 8, reveal: 20 }; const PRIVILEGED = new Set(["owner", "security_admin"]); -const encoder = new TextEncoder(); +const enc = new TextEncoder(); -function json(data, status = 200, headers = {}) { - return new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...headers } }); -} -function b64(bytes) { return btoa(String.fromCharCode(...new Uint8Array(bytes))); } -function unb64(value) { return Uint8Array.from(atob(value), c => c.charCodeAt(0)); } -async function digest(value) { return b64(await crypto.subtle.digest("SHA-256", encoder.encode(value))); } -async function hmacKey(secret) { return crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); } -async function signSession(value, secret) { const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret), encoder.encode(value)); return value + "." + b64(sig); } -async function verifySession(value, secret) { - if (!value || !value.includes(".")) return null; - const [id, signature] = value.split("."); - const expected = await crypto.subtle.sign("HMAC", await hmacKey(secret), encoder.encode(id)); - const a = unb64(signature), b = new Uint8Array(expected); - if (a.length !== b.length || !a.every((v, i) => v === b[i])) return null; - return id; +function headers(extra = {}) { + return { + "x-content-type-options": "nosniff", + "x-frame-options": "DENY", + "referrer-policy": "no-referrer", + "permissions-policy": "camera=(), microphone=(), geolocation=()", + "content-security-policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'", + "cache-control": "no-store, max-age=0", + ...extra + }; +} +function json(data, status = 200, extra = {}) { + return new Response(JSON.stringify(data), { status, headers: headers({ "content-type": "application/json; charset=utf-8", ...extra }) }); +} +function page(body) { + return new Response(body, { headers: headers({ "content-type": "text/html; charset=utf-8" }) }); +} +function b64(bytes) { + return btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, ""); +} +function unb64(value) { + if (typeof value !== "string" || !/^[A-Za-z0-9+/_-]+={0,2}$/.test(value)) throw Error("bad encoding"); + const raw = value.replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/g, ""); + const s = raw + "=".repeat((4 - raw.length % 4) % 4); + return Uint8Array.from(atob(s), c => c.charCodeAt(0)); +} +async function hash(value) { return b64(await crypto.subtle.digest("SHA-256", enc.encode(value))); } +async function hmac(secret, usage) { + return crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [usage]); +} +async function sign(id, secret) { + return id + "." + b64(await crypto.subtle.sign("HMAC", await hmac(secret, "sign"), enc.encode(id))); +} +async function verify(value, secret) { + if (!value || value.length > 256) return null; + const parts = value.split("."); + if (parts.length !== 2 || !/^[A-Za-z0-9_-]{40,64}$/.test(parts[0])) return null; + try { + return await crypto.subtle.verify("HMAC", await hmac(secret, "verify"), unb64(parts[1]), enc.encode(parts[0])) ? parts[0] : null; + } catch { return null; } } async function verifyPassword(password, encoded) { - if (!encoded || !encoded.includes(":")) return false; - const [salt, expected] = encoded.split(":"); - const material = await crypto.subtle.importKey("raw", encoder.encode(password), "PBKDF2", false, ["deriveBits"]); - const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", salt: unb64(salt), iterations: 310000, hash: "SHA-256" }, material, 256); - const actual = new Uint8Array(bits), target = unb64(expected); - return actual.length === target.length && actual.every((v, i) => v === target[i]); -} -function cookie(value, maxAge) { return `oc_token_session=${value}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=${maxAge}`; } -function getCookie(request) { - const raw = request.headers.get("cookie") || ""; - return raw.split(";").map(v => v.trim()).find(v => v.startsWith("oc_token_session="))?.slice("oc_token_session=".length) || ""; -} -function sameOrigin(request) { - const origin = request.headers.get("origin"); - return !origin || origin === new URL(request.url).origin; + if (typeof encoded !== "string" || encoded.length > 256) return false; + const parts = encoded.split(":"); + if (parts.length !== 2) return false; + try { + const salt = unb64(parts[0]), expected = unb64(parts[1]); + if (salt.length !== 16 || expected.length !== 32) return false; + const material = await crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, ["deriveBits"]); + const actual = new Uint8Array(await crypto.subtle.deriveBits({ name: "PBKDF2", salt, iterations: 310000, hash: "SHA-256" }, material, 256)); + return actual.length === expected.length && actual.every((v, i) => v === expected[i]); + } catch { return false; } +} +function cookie(value, age) { + return "oc_token_session=" + value + "; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=" + age; +} +function cookieValue(req) { + return (req.headers.get("cookie") || "").split(";").map(x => x.trim()) + .find(x => x.startsWith("oc_token_session="))?.slice(17) || ""; +} +function sameOrigin(req) { + const origin = req.headers.get("origin"), site = req.headers.get("sec-fetch-site"); + return !!origin && origin === new URL(req.url).origin && (!site || site === "same-origin" || site === "none"); +} +function configured(env) { + if (!env.DB || !env.BOOTSTRAP_PASSWORD_HASH || !env.SESSION_SIGNING_KEY || !env.TOKEN_ENCRYPTION_KEY) throw Error("not configured"); + if (env.SESSION_SIGNING_KEY.length < 32 || unb64(env.TOKEN_ENCRYPTION_KEY).length !== 32) throw Error("invalid keys"); } 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 session(request, env) { - const id = await verifySession(getCookie(request), env.SESSION_SIGNING_KEY); +async function currentUser(req, env) { + const id = await verify(cookieValue(req), env.SESSION_SIGNING_KEY); if (!id) return null; - const row = await env.DB.prepare("SELECT s.subject,s.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 digest(id)).first(); - if (!row || !row.active || row.expires_at < Math.floor(Date.now() / 1000)) 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 }; } -async function encryptionKey(env) { +async function key(env) { return crypto.subtle.importKey("raw", unb64(env.TOKEN_ENCRYPTION_KEY), "AES-GCM", false, ["encrypt", "decrypt"]); } -async function rateLimit(request, env) { - const ip = request.headers.get("cf-connecting-ip") || "unknown"; - const bucket = await digest(ip + "|" + new URL(request.url).pathname); +async function rateLimit(req, env, action) { + const bucket = await hash(action + "|" + (req.headers.get("cf-connecting-ip") || "unknown")); const now = Math.floor(Date.now() / 1000); const row = await env.DB.prepare("SELECT attempts,window_started FROM login_attempts WHERE bucket=?").bind(bucket).first(); - if (row && now - row.window_started < 900 && row.attempts >= 8) return false; - if (!row || now - row.window_started >= 900) { + if (row && now - row.window_started < WINDOW && row.attempts >= LIMITS[action]) return { ok: false, bucket }; + if (!row || now - row.window_started >= WINDOW) { await env.DB.prepare("INSERT OR REPLACE INTO login_attempts(bucket,attempts,window_started) VALUES(?,?,?)").bind(bucket, 1, now).run(); } else { await env.DB.prepare("UPDATE login_attempts SET attempts=attempts+1 WHERE bucket=?").bind(bucket).run(); } - return true; + return { ok: true, bucket }; } -async function login(request, env) { - if (!sameOrigin(request)) return json({ error: "Forbidden" }, 403); - if (!await rateLimit(request, env)) return json({ error: "Too many attempts" }, 429); - let body; - try { body = await request.json(); } catch { return json({ error: "Invalid request" }, 400); } +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…
'; +async function login(req, env) { + if (!sameOrigin(req)) return json({ error: "Forbidden" }, 403); + const limit = await rateLimit(req, env, "login"); + if (!limit.ok) return json({ error: "Too many attempts" }, 429); + let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } const password = typeof body.password === "string" ? body.password : ""; - const ok = password.length >= 12 && await verifyPassword(password, env.BOOTSTRAP_PASSWORD_HASH); - if (!ok) { + if (password.length < 12 || password.length > 1024 || !await verifyPassword(password, env.BOOTSTRAP_PASSWORD_HASH)) { await audit(env, "TOKEN", "login", null, "denied"); return json({ error: "Unauthorized" }, 401); } const identity = await env.DB.prepare("SELECT subject,role,active FROM identities WHERE subject='TOKEN'").first(); - if (!identity?.active || identity.role !== "owner") return json({ error: "Bootstrap identity disabled" }, 403); + if (!identity?.active || identity.role !== "owner") return json({ error: "Unauthorized" }, 401); + await env.DB.prepare("DELETE FROM login_attempts WHERE bucket=?").bind(limit.bucket).run(); const id = b64(crypto.getRandomValues(new Uint8Array(32))); const expiry = Math.floor(Date.now() / 1000) + SESSION_TTL; - await env.DB.prepare("INSERT INTO sessions(id_hash,subject,role,expires_at) VALUES(?,?,?,?)") - .bind(await digest(id), identity.subject, identity.role, expiry).run(); + await env.DB.prepare("INSERT INTO sessions(id_hash,subject,role,expires_at) VALUES(?,?,?,?)").bind(await hash(id), identity.subject, identity.role, expiry).run(); await audit(env, "TOKEN", "login", null); - return json({ ok: true }, 200, { "set-cookie": cookie(await signSession(id, env.SESSION_SIGNING_KEY), SESSION_TTL) }); -} -async function handle(request, env) { - const url = new URL(request.url), path = url.pathname; - if (request.method === "POST" && path === "/api/login") return login(request, env); - if (request.method === "POST" && path === "/api/logout") { - if (!sameOrigin(request)) return json({ error: "Forbidden" }, 403); - const user = await session(request, env), id = await verifySession(getCookie(request), env.SESSION_SIGNING_KEY); - if (id) await env.DB.prepare("UPDATE sessions SET revoked=1 WHERE id_hash=?").bind(await digest(id)).run(); + return json({ ok: true }, 200, { "set-cookie": cookie(await sign(id, env.SESSION_SIGNING_KEY), SESSION_TTL) }); +} +async function route(req, env) { + const path = new URL(req.url).pathname; + if (req.method === "GET" && (path === "/" || path === "/login")) return page(LOGIN_HTML); + if ((req.method === "POST" || req.method === "DELETE") && !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); + } + 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); + 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) }); } - const user = await session(request, env); + const user = await currentUser(req, env); if (!user) return json({ error: "Unauthorized" }, 401); - if (request.method === "GET" && path === "/api/me") return json({ subject: user.subject, role: user.role }); - if (request.method === "GET" && path === "/api/tokens") { - const rows = await env.DB.prepare("SELECT id,label,provider,created_at,rotated_at FROM vault_tokens ORDER BY created_at DESC").all(); + if (req.method === "GET" && path === "/api/me") return json({ subject: user.subject, role: user.role }); + if (req.method === "GET" && path === "/api/tokens") { + const rows = await env.DB.prepare("SELECT id,label,provider,created_at,rotated_at FROM vault_tokens ORDER BY created_at DESC LIMIT 200").all(); return json({ tokens: rows.results }); } - if (request.method === "POST" && path === "/api/tokens") { + if (req.method === "POST" && path === "/api/tokens") { if (!PRIVILEGED.has(user.role)) return json({ error: "Forbidden" }, 403); - if (!sameOrigin(request)) return json({ error: "Forbidden" }, 403); - let body; - try { body = await request.json(); } catch { return json({ error: "Invalid request" }, 400); } - if (typeof body.label !== "string" || typeof body.provider !== "string" || typeof body.value !== "string" || body.value.length < 8 || body.value.length > 8192) return json({ error: "Invalid token record" }, 400); + let body; try { body = await req.json(); } catch { return json({ error: "Invalid request" }, 400); } + if (typeof body.label !== "string" || !body.label.trim() || typeof body.provider !== "string" || !body.provider.trim() || + typeof body.value !== "string" || body.value.length < 8 || body.value.length > 8192) return json({ error: "Invalid token record" }, 400); const iv = crypto.getRandomValues(new Uint8Array(12)); - const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await encryptionKey(env), encoder.encode(body.value)); + const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await key(env), enc.encode(body.value)); const id = crypto.randomUUID(); await env.DB.prepare("INSERT INTO vault_tokens(id,label,provider,ciphertext,iv,created_by) VALUES(?,?,?,?,?,?)") - .bind(id, body.label.slice(0, 100), body.provider.slice(0, 80), b64(ciphertext), b64(iv), user.subject).run(); + .bind(id, body.label.trim().slice(0, 100), body.provider.trim().slice(0, 80), b64(ciphertext), b64(iv), user.subject).run(); await audit(env, user.subject, "token.create", id); return json({ id }, 201); } const reveal = path.match(/^\/api\/tokens\/([0-9a-f-]+)\/reveal$/i); - if (request.method === "POST" && reveal) { + if (req.method === "POST" && reveal) { if (!PRIVILEGED.has(user.role)) return json({ error: "Forbidden" }, 403); - if (!sameOrigin(request)) return json({ error: "Forbidden" }, 403); + const limit = await rateLimit(req, env, "reveal"); + if (!limit.ok) return json({ error: "Too many reveal attempts" }, 429); const row = await env.DB.prepare("SELECT ciphertext,iv FROM vault_tokens WHERE id=?").bind(reveal[1]).first(); - if (!row) return json({ error: "Not found" }, 404); - const clear = await crypto.subtle.decrypt({ name: "AES-GCM", iv: unb64(row.iv) }, await encryptionKey(env), unb64(row.ciphertext)); - await audit(env, user.subject, "token.reveal", reveal[1]); - return json({ value: new TextDecoder().decode(clear) }); + if (!row) { await audit(env, user.subject, "token.reveal", reveal[1], "not_found"); return json({ error: "Not found" }, 404); } + try { + const clear = await crypto.subtle.decrypt({ name: "AES-GCM", iv: unb64(row.iv) }, await key(env), unb64(row.ciphertext)); + await audit(env, user.subject, "token.reveal", reveal[1]); + return json({ value: new TextDecoder().decode(clear) }); + } catch { + await audit(env, user.subject, "token.reveal", reveal[1], "decrypt_failed"); + return json({ error: "Unable to reveal credential" }, 500); + } } const remove = path.match(/^\/api\/tokens\/([0-9a-f-]+)$/i); - if (request.method === "DELETE" && remove) { + if (req.method === "DELETE" && remove) { if (!PRIVILEGED.has(user.role)) return json({ error: "Forbidden" }, 403); - if (!sameOrigin(request)) return json({ error: "Forbidden" }, 403); - await env.DB.prepare("DELETE FROM vault_tokens WHERE id=?").bind(remove[1]).run(); - await audit(env, user.subject, "token.delete", remove[1]); + const result = await env.DB.prepare("DELETE FROM vault_tokens WHERE id=?").bind(remove[1]).run(); + await audit(env, user.subject, "token.delete", remove[1], result.meta?.changes ? "success" : "not_found"); return json({ ok: true }); } return json({ error: "Not found" }, 404); } -export default { fetch: handle }; +export default { + async fetch(req, env) { + try { return await route(req, env); } + catch { return json({ error: "Vault temporarily unavailable" }, 503); } + } +}; diff --git a/security/token-vault/tests/worker.test.mjs b/security/token-vault/tests/worker.test.mjs new file mode 100644 index 0000000..588eea3 --- /dev/null +++ b/security/token-vault/tests/worker.test.mjs @@ -0,0 +1,53 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import worker from "../src/worker.js"; + +test("login screen is served without exposing a vault session", async () => { + const response = await worker.fetch(new Request("https://vault.example/"), {}); + assert.equal(response.status, 200); + assert.match(response.headers.get("content-type"), /text\/html/); + assert.equal(response.headers.get("cache-control"), "no-store, max-age=0"); + assert.equal(response.headers.get("x-frame-options"), "DENY"); + assert.match(await response.text(), /MASTER PASSWORD/); +}); + +test("vault route fails closed until Cloudflare bindings and secrets exist", async () => { + const response = await worker.fetch(new Request("https://vault.example/vault"), {}); + assert.equal(response.status, 503); + assert.equal(response.headers.get("cache-control"), "no-store, max-age=0"); +}); + +test("state-changing requests without an Origin header are rejected", async () => { + const response = await worker.fetch(new Request("https://vault.example/api/login", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ password: "not-a-real-password" }) + }), {}); + assert.equal(response.status, 403); +}); + +test("cross-origin login requests are rejected before secret checks", async () => { + const response = await worker.fetch(new Request("https://vault.example/api/login", { + method: "POST", + headers: { + origin: "https://attacker.example", + "sec-fetch-site": "cross-site", + "content-type": "application/json" + }, + body: JSON.stringify({ password: "not-a-real-password" }) + }), {}); + assert.equal(response.status, 403); +}); + +test("same-origin login fails closed when secrets are not configured", async () => { + const response = await worker.fetch(new Request("https://vault.example/api/login", { + method: "POST", + headers: { + origin: "https://vault.example", + "sec-fetch-site": "same-origin", + "content-type": "application/json" + }, + body: JSON.stringify({ password: "not-a-real-password" }) + }), {}); + assert.equal(response.status, 503); +});