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 3fb39879cfee121d375fa748df343509f75e53b4 Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 00:52:07 +0700
Subject: [PATCH 04/10] docs(token-vault): document hardened flow and remaining
access-control gaps
---
security/token-vault/README.md | 66 +++++++++++++++++-----------------
1 file changed, 34 insertions(+), 32 deletions(-)
diff --git a/security/token-vault/README.md b/security/token-vault/README.md
index c38c8bb..1f33772 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. 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 c4ace3dab128e4e4d27b598826a578e1a3b9ba28 Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 00:52:49 +0700
Subject: [PATCH 05/10] fix(token-vault): repair hidden password input and
enforce stronger bootstrap password
---
.../token-vault/scripts/hash-password.mjs | 47 +++++++++++++------
1 file changed, 33 insertions(+), 14 deletions(-)
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;
}
});
From 889e2d84876f0c10ac983a2de6868cb1cfa69a9b Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 00:52:52 +0700
Subject: [PATCH 06/10] test(token-vault): add source security and syntax
validation
---
security/token-vault/scripts/check-source.mjs | 35 +++++++++++++++++++
1 file changed, 35 insertions(+)
create mode 100644 security/token-vault/scripts/check-source.mjs
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.");
From 755560f532778c22e01de1bad30ae1acd5f3637f Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 00:52:54 +0700
Subject: [PATCH 07/10] ci(token-vault): validate worker security invariants
---
.github/workflows/token-vault-validation.yml | 26 ++++++++++++++++++++
1 file changed, 26 insertions(+)
create mode 100644 .github/workflows/token-vault-validation.yml
diff --git a/.github/workflows/token-vault-validation.yml b/.github/workflows/token-vault-validation.yml
new file mode 100644
index 0000000..4f93ff0
--- /dev/null
+++ b/.github/workflows/token-vault-validation.yml
@@ -0,0 +1,26 @@
+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
From d2f4b5ab677908d0ee84b5ef7ab64cdcda9fc544 Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 00:54:34 +0700
Subject: [PATCH 08/10] test(token-vault): add worker security smoke tests
---
security/token-vault/tests/worker.test.mjs | 53 ++++++++++++++++++++++
1 file changed, 53 insertions(+)
create mode 100644 security/token-vault/tests/worker.test.mjs
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);
+});
From 97ac93c1552f07b5e56550b546b41d79034206e5 Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 00:54:39 +0700
Subject: [PATCH 09/10] ci(token-vault): run Worker smoke tests
---
.github/workflows/token-vault-validation.yml | 2 ++
1 file changed, 2 insertions(+)
diff --git a/.github/workflows/token-vault-validation.yml b/.github/workflows/token-vault-validation.yml
index 4f93ff0..67ca2a8 100644
--- a/.github/workflows/token-vault-validation.yml
+++ b/.github/workflows/token-vault-validation.yml
@@ -24,3 +24,5 @@ jobs:
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
From 4b01542b409f310517be554c33929e086f550d94 Mon Sep 17 00:00:00 2001
From: zskbot <241179063+zskbot@users.noreply.github.com>
Date: Sun, 8 Nov 2026 00:55:44 +0700
Subject: [PATCH 10/10] docs(token-vault): document Worker smoke-test command
---
security/token-vault/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/security/token-vault/README.md b/security/token-vault/README.md
index 1f33772..9bdc727 100644
--- a/security/token-vault/README.md
+++ b/security/token-vault/README.md
@@ -49,4 +49,4 @@ The current API only bootstraps the `TOKEN` owner identity. It does **not yet**
## Validation and deployment
-Run `node security/token-vault/scripts/check-source.mjs` for source validation. 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.