import { reportHandledError } from '#worker/outbound/typed-failure.ts' /** * Read grants for R2-stored Wasm in CLI `--local` package graphs. A graph * names such a module by sha256 plus a grant it signed after the caller's * imports passed their access checks, so a hash alone never reads a private * binary. A grant is a bearer capability for one binary until it expires. */ import { base64UrlToBytes, bytesToBase64Url, } from '@kody-internal/shared/base64.ts' import { z } from 'zod' import { isolateMemoByKey } from '#worker/isolate-memo.ts' const grantPrefix = 'kwg1.' // Matches the package binding lifetime: one graph serves one local run. const grantLifetimeMs = 24 * 60 * 60 * 1000 const signingInfo = new TextEncoder().encode( 'kody/local-execute-package-wasm-grant/v1', ) const grantPayloadSchema = z.object({ sha: z.string().regex(/^[0-9a-f]{64}$/), org: z.string().min(1), actor: z.string().min(1).nullable(), exp: z.number(), }) const signingKey: (secretStoreKey: string) => Promise = isolateMemoByKey(async (secretStoreKey) => { const base = await crypto.subtle.importKey( 'raw', new TextEncoder().encode(secretStoreKey), 'HKDF', false, ['deriveKey'], ) return await crypto.subtle.deriveKey( { name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: signingInfo, }, base, { name: 'HMAC', hash: 'SHA-256', length: 256 }, false, ['sign', 'verify'], ) }) export async function signLocalExecuteWasmGrant(input: { env: Pick sha256: string subject: { org: string; actor: string | null } now?: number }) { const payload: z.infer = { sha: input.sha256, org: input.subject.org, actor: input.subject.actor, exp: (input.now ?? Date.now()) + grantLifetimeMs, } const body = bytesToBase64Url( new TextEncoder().encode(JSON.stringify(payload)), ) const signature = await crypto.subtle.sign( 'HMAC', await signingKey(input.env.SECRET_STORE_KEY), new TextEncoder().encode(body), ) return `${grantPrefix}${body}.${bytesToBase64Url(new Uint8Array(signature))}` } /** True when `token` is an unexpired grant this origin signed for `sha256`. */ export async function verifyLocalExecuteWasmGrant(input: { env: Pick token: string | null sha256: string now?: number }): Promise { const token = input.token?.trim() ?? '' if (!token.startsWith(grantPrefix)) return false const [body, signature, extra] = token.slice(grantPrefix.length).split('.') if (!body || !signature || extra !== undefined) return false try { const valid = await crypto.subtle.verify( 'HMAC', await signingKey(input.env.SECRET_STORE_KEY), base64UrlToBytes(signature), new TextEncoder().encode(body), ) if (!valid) return false const grant = grantPayloadSchema.safeParse( JSON.parse(new TextDecoder().decode(base64UrlToBytes(body))), ) return ( grant.success && grant.data.sha === input.sha256 && grant.data.exp > (input.now ?? Date.now()) ) } catch (error) { reportHandledError('verify-local-execute-wasm-grant-verify', error) return false } }