Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion .github/workflows/token-vault-validation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,15 @@ jobs:
node-version: 22
- name: Validate Worker and password utility
run: node security/token-vault/scripts/check-source.mjs
- name: Run Worker smoke tests
- name: Validate D1 schema
run: |
node --input-type=module <<'NODE'
import { DatabaseSync } from 'node:sqlite';
import { readFileSync } from 'node:fs';
const db = new DatabaseSync(':memory:');
db.exec(readFileSync('security/token-vault/schema.sql', 'utf8'));
db.close();
console.log('D1-compatible schema syntax passed.');
NODE
- name: Run Worker smoke and integration tests
run: node --test security/token-vault/tests/*.test.mjs
82 changes: 56 additions & 26 deletions security/token-vault/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,49 +4,79 @@ 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_<one-time-key>

For an approved reveal grant:

POST /api/agent/tokens/<token-id>/reveal
Authorization: Bearer oca_<one-time-key>

## 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.


Schema validation is executed against an in-memory SQLite database in CI before the Worker integration suite.
29 changes: 29 additions & 0 deletions security/token-vault/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ CREATE TABLE IF NOT EXISTS vault_tokens (
id TEXT PRIMARY KEY,
label TEXT NOT NULL,
provider TEXT NOT NULL,
project_id TEXT NOT NULL DEFAULT 'ocodejs-core',
ciphertext TEXT NOT NULL,
iv TEXT NOT NULL,
created_by TEXT NOT NULL,
Expand Down Expand Up @@ -45,3 +46,31 @@ CREATE TABLE IF NOT EXISTS audit_events (

INSERT OR IGNORE INTO identities (id, subject, role)
VALUES ('bootstrap-token-admin', 'TOKEN', 'owner');

CREATE TABLE IF NOT EXISTS agent_credentials (
id TEXT PRIMARY KEY,
subject TEXT NOT NULL UNIQUE,
key_hash TEXT NOT NULL UNIQUE,
active INTEGER NOT NULL DEFAULT 1,
expires_at INTEGER,
last_used_at TEXT,
created_by TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
FOREIGN KEY(subject) REFERENCES identities(subject),
FOREIGN KEY(created_by) REFERENCES identities(subject)
);

CREATE TABLE IF NOT EXISTS agent_project_grants (
agent_id TEXT NOT NULL,
project_id TEXT NOT NULL,
permission TEXT NOT NULL CHECK (permission IN ('metadata','reveal')),
created_by TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
PRIMARY KEY(agent_id, project_id),
FOREIGN KEY(agent_id) REFERENCES agent_credentials(id) ON DELETE CASCADE,
FOREIGN KEY(created_by) REFERENCES identities(subject)
);

CREATE INDEX IF NOT EXISTS idx_vault_tokens_project ON vault_tokens(project_id);
CREATE INDEX IF NOT EXISTS idx_agent_credentials_key_hash ON agent_credentials(key_hash);
CREATE INDEX IF NOT EXISTS idx_agent_grants_project ON agent_project_grants(project_id, permission);
8 changes: 8 additions & 0 deletions security/token-vault/scripts/check-source.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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'"));
Loading
Loading