|
| 1 | +import { DurableObject } from 'cloudflare:workers'; |
| 2 | +import { drizzle } from 'drizzle-orm/durable-sqlite'; |
| 3 | +import { migrate } from 'drizzle-orm/durable-sqlite/migrator'; |
| 4 | +import { eq } from 'drizzle-orm'; |
| 5 | +import { sandbox_tokens } from '../db/sandbox-registry-schema'; |
| 6 | +import migrations from '../../drizzle/sandbox-registry/migrations'; |
| 7 | + |
| 8 | +/** Prefix makes accidental-leak grepping easy ("kilo sandbox key"). */ |
| 9 | +export const SANDBOX_TOKEN_PREFIX = 'ksk_'; |
| 10 | +/** 24 bytes → 32 base64url chars. ~192 bits entropy. */ |
| 11 | +const TOKEN_RANDOM_BYTES = 24; |
| 12 | + |
| 13 | +const SANDBOX_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/; |
| 14 | + |
| 15 | +export type MintTokenResult = { |
| 16 | + /** Plaintext token — shown to the admin once, never retrievable again. */ |
| 17 | + token: string; |
| 18 | + /** SHA-256 hex of the token — safe to log / return from list endpoints. */ |
| 19 | + tokenHash: string; |
| 20 | +}; |
| 21 | + |
| 22 | +export function isValidSandboxId(sandboxId: string): boolean { |
| 23 | + return SANDBOX_ID_PATTERN.test(sandboxId); |
| 24 | +} |
| 25 | + |
| 26 | +function bytesToHex(bytes: Uint8Array): string { |
| 27 | + let s = ''; |
| 28 | + for (const b of bytes) { |
| 29 | + s += b.toString(16).padStart(2, '0'); |
| 30 | + } |
| 31 | + return s; |
| 32 | +} |
| 33 | + |
| 34 | +function base64urlEncode(bytes: Uint8Array): string { |
| 35 | + let s = ''; |
| 36 | + for (const b of bytes) { |
| 37 | + s += String.fromCharCode(b); |
| 38 | + } |
| 39 | + return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); |
| 40 | +} |
| 41 | + |
| 42 | +export async function hashToken(token: string): Promise<string> { |
| 43 | + const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token)); |
| 44 | + return bytesToHex(new Uint8Array(digest)); |
| 45 | +} |
| 46 | + |
| 47 | +function generateToken(): string { |
| 48 | + const bytes = new Uint8Array(TOKEN_RANDOM_BYTES); |
| 49 | + crypto.getRandomValues(bytes); |
| 50 | + return `${SANDBOX_TOKEN_PREFIX}${base64urlEncode(bytes)}`; |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * Singleton DO that owns the per-sandbox API token registry. |
| 55 | + * |
| 56 | + * All instances are keyed by a fixed name ("registry") — this is a single |
| 57 | + * point of contention for every authenticated bot request. If/when kilo-chat |
| 58 | + * outgrows a single DO's throughput, shard by token-hash prefix. |
| 59 | + */ |
| 60 | +export class SandboxRegistryDO extends DurableObject<Env> { |
| 61 | + private db; |
| 62 | + |
| 63 | + constructor(ctx: DurableObjectState, env: Env) { |
| 64 | + super(ctx, env); |
| 65 | + this.db = drizzle(ctx.storage, { logger: false }); |
| 66 | + void ctx.blockConcurrencyWhile(() => migrate(this.db, migrations)); |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * Mint a fresh token for `sandboxId`. If a token already exists for this |
| 71 | + * sandbox it is atomically replaced — the old token stops working |
| 72 | + * immediately. The plaintext token is returned only here. |
| 73 | + * |
| 74 | + * Callers MUST validate `sandboxId` via `isValidSandboxId` at the admin |
| 75 | + * boundary. This method does not re-validate — throwing from a DO RPC |
| 76 | + * method leaves miniflare's storage isolation in a bad state during tests. |
| 77 | + */ |
| 78 | + async mintToken(sandboxId: string): Promise<MintTokenResult> { |
| 79 | + const token = generateToken(); |
| 80 | + const tokenHash = await hashToken(token); |
| 81 | + this.db.delete(sandbox_tokens).where(eq(sandbox_tokens.sandbox_id, sandboxId)).run(); |
| 82 | + this.db |
| 83 | + .insert(sandbox_tokens) |
| 84 | + .values({ |
| 85 | + token_hash: tokenHash, |
| 86 | + sandbox_id: sandboxId, |
| 87 | + created_at: Date.now(), |
| 88 | + }) |
| 89 | + .run(); |
| 90 | + return { token, tokenHash }; |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Resolve a plaintext token to its sandbox. Returns `null` for unknown or |
| 95 | + * malformed tokens. Hot-path auth lookup — kept index-only (SHA-256 hash). |
| 96 | + */ |
| 97 | + async lookupSandbox(token: string): Promise<string | null> { |
| 98 | + if (!token.startsWith(SANDBOX_TOKEN_PREFIX)) return null; |
| 99 | + const tokenHash = await hashToken(token); |
| 100 | + const row = this.db |
| 101 | + .select() |
| 102 | + .from(sandbox_tokens) |
| 103 | + .where(eq(sandbox_tokens.token_hash, tokenHash)) |
| 104 | + .get(); |
| 105 | + return row?.sandbox_id ?? null; |
| 106 | + } |
| 107 | + |
| 108 | + /** Revoke the token for `sandboxId`. Returns true if a row was deleted. */ |
| 109 | + revokeSandbox(sandboxId: string): boolean { |
| 110 | + const existing = this.db |
| 111 | + .select() |
| 112 | + .from(sandbox_tokens) |
| 113 | + .where(eq(sandbox_tokens.sandbox_id, sandboxId)) |
| 114 | + .get(); |
| 115 | + if (!existing) return false; |
| 116 | + this.db.delete(sandbox_tokens).where(eq(sandbox_tokens.sandbox_id, sandboxId)).run(); |
| 117 | + return true; |
| 118 | + } |
| 119 | +} |
0 commit comments