@byok-sdk/cloud 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/crypto/web-crypto.ts","../src/auth/tokens.ts","../src/auth/verify.ts","../src/auth/plane.ts","../src/capabilities.ts","../src/errors.ts","../src/activity.ts","../src/coordination.ts","../src/auth/bearer.ts","../src/tenant-stores.ts","../src/handlers/shared.ts","../src/handlers/blobs.ts","../src/handlers/capabilities.ts","../src/handlers/auth.ts","../src/handlers/events.ts","../src/approval-timeline.ts","../src/board-projection.ts","../src/inbound.ts","../src/handlers/messages.ts","../src/handlers/board.ts","../src/handlers/presence.ts","../src/handlers/skill-packs.ts","../src/auth/device-proof.ts","../src/truth/contract.ts","../src/truth/errors.ts","../src/handlers/truth.ts","../src/router/registry.ts","../src/terminal-result.ts","../src/cloud.ts","../src/stores/in-memory/rate-limiter.ts","../src/stores/in-memory/blobs.ts","../src/stores/in-memory/device-directory.ts","../src/stores/in-memory/dedup.ts","../src/stores/in-memory/nonces.ts","../src/stores/in-memory/pairing-codes.ts","../src/stores/in-memory/receipts.ts","../src/stores/in-memory/proof-receipts.ts","../src/stores/in-memory/task-attempts.ts","../src/stores/in-memory/activity.ts","../src/stores/in-memory/approval-timeline.ts","../src/stores/in-memory/index.ts","../src/composition/in-memory.ts","../src/coordination-client.ts","../src/stores/ports.ts","../src/stores/ports-contract.ts"],"names":["tenantId","z","response","tenantKey","isCoreConflictError","isCoreError","principalTenant","isTenantId","unauthorized","contentHash","STORAGE_ERROR_CODES","STORAGE_ERROR_HTTP_STATUS","decodeEnvelope","envelope","encodeEnvelope","nonce","BOARD_STATUSES","hasCapability","BYOK_BOARD_PATH","BYOK_BOARD_STREAM_PATH"],"mappings":";;;;;;;;;AAWA,IAAM,qBAAA,GAAwB,kCAAA;AAE9B,IAAM,UAAA,GAAa,kBAAA;AAEZ,SAA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cAAc,CAAA;AAAA,EAC9C,QAAA,EAAU,CAAC,QAAA,EAAU,KAAK,CAAA;AAAA,EAC1B,aAAA,EAAe,CAAC,QAAA,EAAU,KAAK,CAAA;AAAA;AAAA;AAAA;AAAA,EAI/B,KAAA,EAAO,CAAC,cAAA,EAAgB,eAAA,EAAiB,gBAAgB,CAAA;AAAA,EACzD,WAAA,EAAa,CAAC,SAAS;AACzB;AAGO,IAAM,qBAAA,GAAkE;AAAA,EAC7E,QAAA,EAAU,eAAA;AAAA,EACV,SAAA,EAAW,uBAAA;AAAA,EACX,OAAA,EAAS,iBAAA;AAAA,EACT,YAAA,EAAc,kBAAA;AAAA,EACd,MAAA,EAAQ,YAAA;AAAA,EACR,KAAA,EAAO,mBAAA;AAAA,EACP,KAAA,EAAO,kBAAA;AAAA,EACP,QAAA,EAAU,qBAAA;AAAA,EACV,aAAA,EAAe,0BAAA;AAAA,EACf,KAAA,EAAO,gBAAA;AAAA,EACP,WAAA,EAAa;AACf","file":"index.js","sourcesContent":["/**\n * The reference {@link CloudCrypto}, built entirely on the WebCrypto API that\n * Node >=20, Cloudflare Workers, and Deno all expose as `globalThis.crypto`.\n *\n * No `node:crypto`, no dependency: the point of the port is that a hosted\n * composition stays runtime-neutral, and an adapter that reached for a Node\n * built-in here would make that claim false for the default composition.\n */\nimport type { CloudCrypto } from './port';\n\n/** Short, human-typeable pairing code alphabet — no `0/O`, no `1/I` (mirrors the reference server's). */\nconst PAIRING_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';\n\nconst HEX_DIGITS = '0123456789abcdef';\n\nexport function base64UrlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\n/**\n * Decode base64url. Returns `undefined` rather than throwing for input that\n * is not base64url at all — every caller here is verifying attacker-supplied\n * material, where \"not decodable\" and \"does not verify\" must be the same\n * answer.\n */\nexport function base64UrlDecode(value: string): Uint8Array | undefined {\n const padded = value.replaceAll('-', '+').replaceAll('_', '/');\n try {\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n } catch {\n return undefined;\n }\n}\n\nfunction toHex(bytes: Uint8Array): string {\n let out = '';\n for (const byte of bytes) {\n out += HEX_DIGITS[(byte >> 4) & 0xf];\n out += HEX_DIGITS[byte & 0xf];\n }\n return out;\n}\n\n/**\n * WebCrypto's own types are derived from the runtime's `globalThis.crypto`\n * rather than named directly: `CryptoKey`/`SubtleCrypto`/`KeyUsage` are DOM\n * lib globals, and this package compiles without the DOM lib (a Workers build\n * has no DOM either). Deriving keeps the types exact without pulling in a\n * `node:` import or widening `lib`.\n */\nexport type SubtleCryptoLike = typeof globalThis.crypto.subtle;\nexport type CryptoKeyLike = Awaited<ReturnType<SubtleCryptoLike['importKey']>>;\nexport type KeyUsageLike = Parameters<SubtleCryptoLike['importKey']>[4][number];\n\nfunction subtle(): SubtleCryptoLike {\n const webCrypto = globalThis.crypto;\n if (webCrypto?.subtle === undefined) {\n throw new Error('@byok-sdk/cloud requires a WebCrypto implementation on globalThis.crypto');\n }\n return webCrypto.subtle;\n}\n\nexport function createWebCrypto(): CloudCrypto {\n return {\n randomUuid(): string {\n return globalThis.crypto.randomUUID();\n },\n\n randomToken(byteLength: number): string {\n return base64UrlEncode(globalThis.crypto.getRandomValues(new Uint8Array(byteLength)));\n },\n\n randomPairingCode(length: number): string {\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(length));\n let out = '';\n for (const byte of bytes) {\n out += PAIRING_CODE_ALPHABET[byte % PAIRING_CODE_ALPHABET.length];\n }\n return out;\n },\n\n async verifyEd25519(\n publicKeyBase64Url: string,\n message: string | Uint8Array,\n signature: string,\n ): Promise<boolean> {\n const signatureBytes = base64UrlDecode(signature);\n if (signatureBytes === undefined) return false;\n try {\n const key = await subtle().importKey(\n 'jwk',\n { kty: 'OKP', crv: 'Ed25519', x: publicKeyBase64Url },\n { name: 'Ed25519' },\n false,\n ['verify'],\n );\n const messageBytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;\n return await subtle().verify({ name: 'Ed25519' }, key, signatureBytes, messageBytes);\n } catch {\n // A key that will not import is a key that cannot have signed this —\n // same answer as a bad signature, with no distinguishing error.\n return false;\n }\n },\n\n async hmacSha256(secret: Uint8Array, message: string): Promise<string> {\n const key = await subtle().importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n const signature = await subtle().sign('HMAC', key, new TextEncoder().encode(message));\n return base64UrlEncode(new Uint8Array(signature));\n },\n\n async sha256(data: Uint8Array): Promise<string> {\n const digest = await subtle().digest('SHA-256', data);\n return `sha256:${toHex(new Uint8Array(digest))}`;\n },\n\n timingSafeEqual(left: string, right: string): boolean {\n const leftBytes = base64UrlDecode(left);\n const rightBytes = base64UrlDecode(right);\n if (leftBytes === undefined || rightBytes === undefined) return false;\n if (leftBytes.length !== rightBytes.length) return false;\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= (leftBytes[index] ?? 0) ^ (rightBytes[index] ?? 0);\n }\n return diff === 0;\n },\n };\n}\n","/**\n * Access tokens for the hosted device surface (docs/protocol.md §6).\n *\n * The token carries the identity TRIPLE — `(deviceId, tenantId, productId)` —\n * and all three legs are lookup keys, never authority: `authenticateBearer`\n * (`bearer.ts`) resolves them against the device directory and answers with\n * the ROW's identity. A token missing a leg is not a partially usable token;\n * it is not a token this deployment minted.\n *\n * {@link TokenSigner} is a port for the same reason `@byok-sdk/server` made it\n * one: a SaaS with an org-wide asymmetric signer or a KMS swaps its own in.\n * The reference implementation below is HS256 over a caller-supplied secret,\n * built on WebCrypto so the package stays runtime-neutral (no `jose`, no\n * `node:crypto`).\n */\nimport type { Clock } from '@byok-sdk/core';\nimport {\n base64UrlDecode,\n base64UrlEncode,\n type CryptoKeyLike,\n type KeyUsageLike,\n} from '../crypto/web-crypto';\n\n/** Access tokens are ~1h, matching the reference server (docs/protocol.md §6.1/§6.2). */\nexport const ACCESS_TOKEN_TTL_SECONDS = 60 * 60;\n\nexport interface AccessTokenClaims {\n readonly deviceId: string;\n /** Unbranded on the wire: the value is only a lookup key until a device row vouches for it. */\n readonly tenantId: string;\n readonly productId: string;\n}\n\nexport interface TokenSigner {\n sign(claims: AccessTokenClaims, expiresInSeconds: number): Promise<string>;\n /** Claims for a valid, unexpired token, or `undefined` for invalid/expired/malformed — no reason is ever reported. */\n verify(token: string): Promise<AccessTokenClaims | undefined>;\n}\n\ninterface TokenPayload {\n readonly deviceId: unknown;\n readonly tenantId: unknown;\n readonly productId: unknown;\n readonly exp: unknown;\n}\n\nfunction encodeSegment(value: unknown): string {\n return base64UrlEncode(new TextEncoder().encode(JSON.stringify(value)));\n}\n\n/**\n * HS256 JWT signer over `secret`.\n *\n * `clock` is injected rather than read off `Date.now()` so expiry is testable\n * and so the whole package keeps a single notion of \"now\" (the same one the\n * stores use for TTLs).\n */\nexport function createHmacTokenSigner(secret: Uint8Array, clock: Clock): TokenSigner {\n async function signingKey(usage: KeyUsageLike): Promise<CryptoKeyLike> {\n return globalThis.crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);\n }\n\n async function signature(signingInput: string): Promise<string> {\n const key = await signingKey('sign');\n const bytes = await globalThis.crypto.subtle.sign('HMAC', key, new TextEncoder().encode(signingInput));\n return base64UrlEncode(new Uint8Array(bytes));\n }\n\n return {\n async sign(claims, expiresInSeconds) {\n const issuedAt = Math.floor(clock.now().getTime() / 1000);\n const header = encodeSegment({ alg: 'HS256', typ: 'JWT' });\n const payload = encodeSegment({\n deviceId: claims.deviceId,\n tenantId: claims.tenantId,\n productId: claims.productId,\n iat: issuedAt,\n exp: issuedAt + expiresInSeconds,\n });\n const signingInput = `${header}.${payload}`;\n return `${signingInput}.${await signature(signingInput)}`;\n },\n\n async verify(token) {\n const parts = token.split('.');\n if (parts.length !== 3) return undefined;\n const [header, payload, provided] = parts as [string, string, string];\n\n const key = await signingKey('verify');\n const providedBytes = base64UrlDecode(provided);\n if (providedBytes === undefined) return undefined;\n const ok = await globalThis.crypto.subtle.verify(\n 'HMAC',\n key,\n providedBytes,\n new TextEncoder().encode(`${header}.${payload}`),\n );\n if (!ok) return undefined;\n\n const headerBytes = base64UrlDecode(header);\n const payloadBytes = base64UrlDecode(payload);\n if (headerBytes === undefined || payloadBytes === undefined) return undefined;\n\n let decodedHeader: unknown;\n let decodedPayload: TokenPayload;\n try {\n decodedHeader = JSON.parse(new TextDecoder().decode(headerBytes));\n decodedPayload = JSON.parse(new TextDecoder().decode(payloadBytes)) as TokenPayload;\n } catch {\n return undefined;\n }\n\n const alg = (decodedHeader as { alg?: unknown } | null)?.alg;\n if (alg !== 'HS256') return undefined;\n\n const { deviceId, tenantId, productId, exp } = decodedPayload;\n if (typeof deviceId !== 'string' || typeof tenantId !== 'string' || typeof productId !== 'string') {\n return undefined;\n }\n if (typeof exp !== 'number' || clock.now().getTime() / 1000 >= exp) return undefined;\n\n return { deviceId, tenantId, productId };\n },\n };\n}\n","/**\n * The one nonce-signature check on the hosted surface (docs/protocol.md §6.2).\n *\n * S1 (GAP-004): a device signs `byok-nonce-v1\\n` + nonce, never the bare\n * nonce. The device key is a long-lived identity key that later planes (S6\n * device proof) also sign structured messages with; without a domain tag, a\n * signature produced for one purpose is a valid signature for another.\n *\n * Applying the domain HERE rather than at the call site is the point: there\n * is exactly one place that decides what a device signature over a nonce\n * means, so no route can be written that accepts the undomained form. There\n * is deliberately no dual mode and no grace window — a device on the old\n * encoding re-pairs.\n *\n * The domain literal itself lives in `@byok-sdk/core` (`src/pairing.ts`): the\n * daemon must not be able to tell self-hosted from hosted, and three copies\n * each commented as byte-identical to the other two were a drift hazard, not a\n * design. Importing the constant from the package all three ends already depend\n * on is not the same as importing the server — parity of *behavior* is still\n * asserted by behavior tests, and this package still has no `@byok-sdk/server`\n * edge. Re-exported so this module's public surface is unchanged.\n */\nimport { NONCE_SIGNING_DOMAIN } from '@byok-sdk/core';\nimport type { CloudCrypto } from '../crypto/port';\n\nexport { NONCE_SIGNING_DOMAIN } from '@byok-sdk/core';\n\nexport function verifyNonceSignature(\n crypto: CloudCrypto,\n devicePublicKey: string,\n nonce: string,\n signature: string,\n): Promise<boolean> {\n // `CloudCrypto.verifyEd25519` takes the message as a string and encodes it as\n // UTF-8 itself, so the concatenation happens here rather than through core's\n // `nonceSigningBytes` — same bytes, one encoding step instead of two.\n return crypto.verifyEd25519(devicePublicKey, NONCE_SIGNING_DOMAIN + nonce, signature);\n}\n","/**\n * The auth plane: everything the three pre-tenant routes (`/byok/pair`,\n * `/byok/challenge`, `/byok/token`) need, and nothing else.\n *\n * Those three routes cannot take a {@link TenantStores} facade — they run\n * BEFORE a principal exists, which is exactly why they are the surface where a\n * tenant boundary is easiest to lose. So instead of handing them naked stores\n * and trusting each handler to pass the right tenant, this module owns every\n * tenant-carrying call they make and hands back operations that name no tenant\n * at all:\n *\n * - a pairing code redeems into a REGISTERED device row in one step, so the\n * claims never sit in handler scope as a tenant a handler could substitute;\n * - a device resolves to a row (the pre-tenant lookup, §6.2's pinned wire\n * contract), and unknown/revoked collapse to one answer;\n * - nonce issue/validate/consume and token minting take that ROW, so the\n * tenant they act on is the row's, by construction.\n */\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { CloudCrypto } from '../crypto/port';\nimport type { CloudStores, DeviceRecord, PairingCodeInfo } from '../stores/ports';\nimport { ACCESS_TOKEN_TTL_SECONDS, type TokenSigner } from './tokens';\nimport { verifyNonceSignature } from './verify';\n\n/** ~10min, matching the reference server's pairing-code lifetime. */\nexport const PAIRING_CODE_TTL_MS = 10 * 60 * 1000;\n\nconst PAIRING_CODE_LENGTH = 8;\n\n/** The paired identity key is the first and only proof key in S6. */\nexport const DEVICE_IDENTITY_PROOF_KEY_ID = 'identity';\nexport const DEVICE_IDENTITY_PROOF_KEY_EPOCH = 0;\n\nexport interface PairInput {\n readonly pairingCode: string;\n readonly deviceName: string;\n readonly devicePublicKey: string;\n}\n\nexport interface MintedAccessToken {\n readonly accessToken: string;\n readonly expiresAt: string;\n}\n\nexport interface AuthPlane {\n /** Host control plane: mint a single-use code carrying the tenant/product a device will land in. */\n createPairingCode(tenant: TenantId, input: { readonly productId: string; readonly ttlMs?: number }): Promise<PairingCodeInfo>;\n /**\n * Redeem a code and register the device it pairs, in one step. `undefined`\n * for a code that is unknown, expired, or already used — one answer for all\n * three. Single-use redemption is what makes this exclusive: a second\n * redeem never reaches the row write.\n */\n redeemAndRegister(input: PairInput): Promise<DeviceRecord | undefined>;\n /** The pre-tenant device lookup §6.2's wire contract forces. `undefined` for unknown AND revoked alike — no existence oracle. */\n resolveDevice(deviceId: string): Promise<DeviceRecord | undefined>;\n issueNonce(device: DeviceRecord): Promise<string>;\n validateNonce(device: DeviceRecord, nonce: string): Promise<boolean>;\n /** Burn the nonce. Called only on a fully verified request (§6.2). */\n consumeNonce(device: DeviceRecord, nonce: string): Promise<void>;\n /** Domain-separated (`byok-nonce-v1\\n`) — see `verify.ts`. A raw signature over the bare nonce is invalid, with no second accepted form. */\n verifySignature(device: DeviceRecord, nonce: string, signature: string): Promise<boolean>;\n mintAccessToken(device: DeviceRecord): Promise<MintedAccessToken>;\n}\n\nexport interface AuthPlaneDeps {\n readonly stores: CloudStores;\n readonly crypto: CloudCrypto;\n readonly clock: Clock;\n readonly tokenSigner: TokenSigner;\n readonly accessTokenTtlSeconds?: number;\n}\n\nexport function createAuthPlane(deps: AuthPlaneDeps): AuthPlane {\n const { stores, crypto, clock, tokenSigner } = deps;\n const ttlSeconds = deps.accessTokenTtlSeconds ?? ACCESS_TOKEN_TTL_SECONDS;\n\n return {\n async createPairingCode(tenant, input) {\n const expiresAt = new Date(clock.now().getTime() + (input.ttlMs ?? PAIRING_CODE_TTL_MS)).toISOString();\n return stores.pairingCodes.issue(tenant, {\n code: crypto.randomPairingCode(PAIRING_CODE_LENGTH),\n productId: input.productId,\n expiresAt,\n });\n },\n\n async redeemAndRegister(input) {\n const claims = await stores.pairingCodes.redeem(input.pairingCode);\n if (claims === undefined) return undefined;\n // The redeemed code's claims are the ONLY source of the device's\n // tenant/product — `PairRequest` carries neither, so a device can never\n // choose where it lands.\n return stores.devices.register(claims.tenantId, {\n productId: claims.productId,\n deviceId: `dev_${crypto.randomUuid()}`,\n deviceName: input.deviceName,\n devicePublicKey: input.devicePublicKey,\n proofKeyId: DEVICE_IDENTITY_PROOF_KEY_ID,\n proofKeyEpoch: DEVICE_IDENTITY_PROOF_KEY_EPOCH,\n });\n },\n\n async resolveDevice(deviceId) {\n const device = await stores.devices.resolveByDeviceId(deviceId);\n if (device === undefined || device.revoked) return undefined;\n return device;\n },\n\n issueNonce(device) {\n return stores.nonces.issue(device.tenantId, device.deviceId);\n },\n\n validateNonce(device, nonce) {\n return stores.nonces.validate(device.tenantId, device.deviceId, nonce);\n },\n\n consumeNonce(device, nonce) {\n return stores.nonces.markUsed(device.tenantId, nonce);\n },\n\n verifySignature(device, nonce, signature) {\n return verifyNonceSignature(crypto, device.devicePublicKey, nonce, signature);\n },\n\n async mintAccessToken(device) {\n const accessToken = await tokenSigner.sign(\n { deviceId: device.deviceId, tenantId: device.tenantId, productId: device.productId },\n ttlSeconds,\n );\n return {\n accessToken,\n expiresAt: new Date(clock.now().getTime() + ttlSeconds * 1000).toISOString(),\n };\n },\n };\n}\n","/**\n * The hosted capability declaration (ADR-010).\n *\n * A client learns what a deployment supports by READING a declaration, never\n * by probing an endpoint and interpreting 404/405/501. `@byok-sdk/core` owns the\n * declaration shape and the `hasCapability`/`assertCapability` enforcement\n * point; what lives here is the hosted vocabulary and the mapping from a\n * capability name to the routes that provide it.\n *\n * `GET /byok/capabilities` is a hosted-only route: it is not part of the\n * frozen device wire contract, `@byok-sdk/protocol` is untouched by it, and the\n * daemon does not consume it yet (that lands in a later slice). What it\n * already does here is drive route selection — a deployment that does not\n * declare `blobs.presigned` does not mount the grant routes at all, and one\n * that does not declare `blobs.contentproxy` does not mount the two `/content`\n * routes, so the declaration and the surface cannot disagree.\n */\nimport { CapabilityDeclarationSchema, hasCapability, type CapabilityDeclaration } from '@byok-sdk/core';\n\n/** The hosted capability vocabulary this package knows how to serve. */\nexport const CLOUD_CAPABILITIES = {\n /** `GET /byok/events` long-poll receive (§8). */\n eventsLongPoll: 'events.longpoll',\n /** `POST /byok/messages` batched send (§8.2). */\n messagesBatch: 'messages.batch',\n /** The three bearer-authed blob routes: reserve/grant, explicit finalize, committed-only download (§7). */\n blobsPresigned: 'blobs.presigned',\n /**\n * The two presigned `/byok/blobs/:id/content` routes — cloud carrying the\n * bytes itself.\n *\n * Split out of `blobs.presigned` because it was one capability describing two\n * separable facts. A composition whose bytes live in object storage mints\n * grants (`blobs.presigned`) but has no byte-proxy path at all, and saying so\n * by declaration is ADR-010's whole posture: a client reads what a deployment\n * serves, it never probes a `/content` route and interprets the status code.\n *\n * Spelled all-lowercase because core's declaration schema pins capability\n * names to `/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/` — the same reason the sibling\n * above reads `events.longpoll` and not `events.longPoll`.\n */\n blobsContentProxy: 'blobs.contentproxy',\n /** Board list/claim/unclaim/status routes. Polling is first-class under this declaration. */\n boardCoordination: 'board.coordination',\n /** Additional SSE transport for the same board read model. */\n boardSse: 'board.sse',\n /** Device-scoped five-level presence publication. */\n presenceHints: 'presence.hints',\n /** Bounded task activity batch publication. */\n activityTail: 'activity.tail',\n /** Request-bound device proof record manifest/read/write surface (S6). */\n truthRecords: 'truth.records',\n /**\n * Tenant-scoped skill pack distribution: the manifest list plus the per-file\n * content route a paired device installs from.\n *\n * Hosted HTTP on purpose. A pack is DECLARATIVE CONTENT a device pulls after\n * reading this declaration — not a message — so `@byok-sdk/protocol` gains\n * nothing from it and the frozen v1 envelope stays untouched. Composition-\n * bound like `truth.records`: a deployment that declares it without supplying\n * a `SkillPackStore` is refused at construction rather than publishing two\n * routes it would then 404.\n */\n skillPacks: 'skills.pack',\n} as const;\n\nexport type CloudCapability = (typeof CLOUD_CAPABILITIES)[keyof typeof CLOUD_CAPABILITIES];\n\n/** The wire DTO for `GET /byok/capabilities` — core's shape, bound to a cloud-owned route. */\nexport const CapabilitiesResponseSchema = CapabilityDeclarationSchema;\nexport type CapabilitiesResponse = CapabilityDeclaration;\n\nexport interface FullCapabilityDeclarationOptions {\n /**\n * Composition-bound capabilities require an explicit application authority.\n * `truth.records` is omitted by default because the standard in-memory\n * composition cannot truthfully promise a cross-store atomic commit.\n */\n readonly includeTruthRecords?: boolean;\n /**\n * `skills.pack` is omitted for the same reason: the standard composition is\n * given no `SkillPackStore`, and a default-on declaration would make every\n * existing deployment refuse to construct.\n */\n readonly includeSkillPacks?: boolean;\n}\n\n/** Every capability the standard composition can serve, plus explicitly wired composition-bound ones. */\nexport function fullCapabilityDeclaration(\n version = 1,\n options: FullCapabilityDeclarationOptions = {},\n): CapabilityDeclaration {\n return {\n schema: 'byok-capabilities-v1',\n version,\n capabilities: Object.values(CLOUD_CAPABILITIES).filter((capability) => {\n if (capability === CLOUD_CAPABILITIES.truthRecords) return options.includeTruthRecords === true;\n if (capability === CLOUD_CAPABILITIES.skillPacks) return options.includeSkillPacks === true;\n return true;\n }),\n };\n}\n\nexport function declares(declaration: CapabilityDeclaration, capability: CloudCapability): boolean {\n return hasCapability(declaration, capability);\n}\n","/**\n * The one error taxonomy for `@byok-sdk/cloud`.\n *\n * Same idiom as `@byok-sdk/core`'s `errors.ts`: one class, code-based branching,\n * so a composition maps failures onto HTTP with a code table instead of an\n * `instanceof` chain. Cloud does not re-export core's codes — a cloud error is\n * about the hosted surface (a store contract the composition broke, a\n * declaration the host mis-configured), and core errors travel up unchanged.\n */\n\nexport const CLOUD_ERROR_CODES = {\n /** A pairing code that is unknown, expired, or already redeemed (§6.1). */\n pairing_code_invalid: 'pairing_code_invalid',\n /** The composition handed a device row whose tenant is not a mintable `TenantId`. */\n device_tenant_invalid: 'device_tenant_invalid',\n /**\n * The mailbox committed a row `seq` that disagrees with the delivery `seq`\n * its body factory baked into the envelope. Loud rather than silent: those\n * two numbers ARE the daemon's redelivery cursor.\n */\n mailbox_seq_mismatch: 'mailbox_seq_mismatch',\n /** A capability declaration the host supplied that core refused. */\n capability_declaration_invalid: 'capability_declaration_invalid',\n /**\n * The declaration names a capability this composition cannot serve, so the\n * deployment would publish a surface it does not have (ADR-010).\n *\n * Construction-time and fatal. A client learns what a deployment supports by\n * READING the declaration and is entitled to act on it without probing, so a\n * declaration that over-states is not a degraded deployment — it is a\n * deployment whose one honest interface lies.\n */\n capability_over_declared: 'capability_over_declared',\n /** Host-supplied board labels or coordination input exceeded the explicit contract. */\n coordination_input_invalid: 'coordination_input_invalid',\n /**\n * A terminal receipt whose stored body is not a terminal envelope — either\n * undecodable or a non-terminal type. Whatever wrote that row broke the\n * receipt-store contract, so the typed read model fails closed instead of\n * projecting a best-effort shape.\n */\n terminal_receipt_unreadable: 'terminal_receipt_unreadable',\n /** A progress/activity batch exceeded the configured event or byte ceiling. */\n activity_batch_too_large: 'activity_batch_too_large',\n} as const;\n\nexport type CloudErrorCode = (typeof CLOUD_ERROR_CODES)[keyof typeof CLOUD_ERROR_CODES];\n\nexport class ByokCloudError extends Error {\n public readonly code: CloudErrorCode;\n\n constructor(code: CloudErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ByokCloudError';\n this.code = code;\n }\n}\n\nexport function isCloudError(value: unknown, code?: CloudErrorCode): value is ByokCloudError {\n if (!(value instanceof ByokCloudError)) return false;\n return code === undefined || value.code === code;\n}\n","import { tenantKey, type TenantId } from '@byok-sdk/core';\nimport { AgentEventOrUnknownSchema, type AgentEventOrUnknown } from '@byok-sdk/protocol';\nimport { z } from 'zod';\nimport { ByokCloudError } from './errors';\n\nexport const DEFAULT_ACTIVITY_CAPACITY = 50;\n\nconst ActivityTaskIdSchema = z.string().min(1).max(200);\nconst SourceEnvelopeIdSchema = z\n .string()\n .max(200)\n .regex(/\\S/, 'sourceEnvelopeId must not be blank');\n\nexport const ActivityAppendRequestSchema = z.object({\n taskId: ActivityTaskIdSchema,\n sourceEnvelopeId: SourceEnvelopeIdSchema,\n batchSeq: z.number().int().nonnegative(),\n events: z.array(AgentEventOrUnknownSchema).min(1),\n dropped: z.number().int().nonnegative(),\n});\n\nexport const TimelineEventSchema = z.object({\n taskId: ActivityTaskIdSchema,\n sourceEnvelopeId: SourceEnvelopeIdSchema,\n batchSeq: z.number().int().nonnegative(),\n eventIndex: z.number().int().nonnegative(),\n receivedAt: z.iso.datetime(),\n event: AgentEventOrUnknownSchema,\n});\n\nexport type TimelineEvent = Readonly<z.infer<typeof TimelineEventSchema>>;\n\nexport interface ActivityCursor {\n readonly batchSeq: number;\n readonly eventIndex: number;\n}\n\nexport interface ActivityTail {\n readonly tenantId: TenantId;\n readonly taskId: string;\n readonly entries: readonly TimelineEvent[];\n readonly cursor?: ActivityCursor;\n readonly dropped: number;\n readonly capacity: number;\n readonly expiresAt: string;\n}\n\nexport interface ActivityAppendInput {\n readonly taskId: string;\n readonly sourceEnvelopeId: string;\n readonly batchSeq: number;\n readonly events: readonly AgentEventOrUnknown[];\n readonly dropped: number;\n readonly ttlMs: number;\n readonly capacity?: number;\n}\n\nexport interface ActivityStore {\n append(tenant: TenantId, input: ActivityAppendInput): Promise<ActivityTail>;\n read(tenant: TenantId, taskId: string): Promise<ActivityTail | undefined>;\n}\n\nexport function validateActivityAppend(input: ActivityAppendInput): number {\n if (!Number.isFinite(input.ttlMs) || input.ttlMs <= 0) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Activity ttl must be a positive number of milliseconds, received ${String(input.ttlMs)}.`,\n );\n }\n const capacity = input.capacity ?? DEFAULT_ACTIVITY_CAPACITY;\n if (!Number.isSafeInteger(capacity) || capacity <= 0) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Activity capacity must be a positive integer, received ${String(capacity)}.`,\n );\n }\n const parsed = ActivityAppendRequestSchema.safeParse(input);\n if (!parsed.success) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Activity batches require stable source identity, order, at least one valid event, and a non-negative dropped count.',\n );\n }\n return capacity;\n}\n\nexport function projectTimelineEvents(\n input: ActivityAppendInput,\n receivedAt: string,\n): readonly TimelineEvent[] {\n return input.events.map((event, eventIndex) =>\n TimelineEventSchema.parse({\n taskId: input.taskId,\n sourceEnvelopeId: input.sourceEnvelopeId,\n batchSeq: input.batchSeq,\n eventIndex,\n receivedAt,\n event,\n }),\n );\n}\n\nexport function parseTimelineEvents(value: unknown): readonly TimelineEvent[] {\n return z.array(TimelineEventSchema).parse(value) as readonly TimelineEvent[];\n}\n\nexport function compareTimelineEvents(left: TimelineEvent, right: TimelineEvent): number {\n return left.batchSeq - right.batchSeq || left.eventIndex - right.eventIndex;\n}\n\nexport function activityCursor(\n entries: readonly TimelineEvent[],\n): ActivityCursor | undefined {\n const last = entries.at(-1);\n return last === undefined ? undefined : { batchSeq: last.batchSeq, eventIndex: last.eventIndex };\n}\n\nexport function activityTailKey(tenant: TenantId, taskId: string): string {\n return tenantKey(tenant, taskId);\n}\n","import type { AgentEventOrUnknown } from '@byok-sdk/protocol';\nimport {\n DEFAULT_ACTIVITY_CAPACITY,\n validateActivityAppend,\n type ActivityAppendInput,\n type ActivityTail,\n} from './activity';\nimport { ByokCloudError } from './errors';\nimport type { TenantBoundActivity } from './tenant-stores';\n\nexport const DEFAULT_BOARD_CHANNEL_MAX_BYTES = 128;\nexport const DEFAULT_BOARD_TITLE_MAX_BYTES = 512;\nexport const DEFAULT_ACTIVITY_MAX_EVENTS = 50;\nexport const DEFAULT_ACTIVITY_MAX_BYTES = 64 * 1024;\nexport { DEFAULT_ACTIVITY_CAPACITY } from './activity';\nexport const DEFAULT_ACTIVITY_TTL_MS = 10 * 60_000;\nexport const DEFAULT_PRESENCE_TTL_MS = 90_000;\nexport const DEFAULT_PRESENCE_MINIMUM_INTERVAL_MS = 5_000;\nexport const DEFAULT_PRESENCE_DETAIL_MAX_BYTES = 512;\n\nconst encoder = new TextEncoder();\n\nexport interface ActivityBounds {\n readonly maxEvents: number;\n readonly maxBytes: number;\n readonly capacity: number;\n readonly ttlMs: number;\n}\n\nexport const DEFAULT_ACTIVITY_BOUNDS: ActivityBounds = {\n maxEvents: DEFAULT_ACTIVITY_MAX_EVENTS,\n maxBytes: DEFAULT_ACTIVITY_MAX_BYTES,\n capacity: DEFAULT_ACTIVITY_CAPACITY,\n ttlMs: DEFAULT_ACTIVITY_TTL_MS,\n};\n\nexport function assertBoardLabels(\n channel: string,\n title: string,\n limits: { readonly channelMaxBytes: number; readonly titleMaxBytes: number },\n): void {\n if (channel.length === 0 || encoder.encode(channel).length > limits.channelMaxBytes) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Board channel must contain 1..${limits.channelMaxBytes} UTF-8 bytes.`,\n );\n }\n if (title.length === 0 || encoder.encode(title).length > limits.titleMaxBytes) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Board title must contain 1..${limits.titleMaxBytes} UTF-8 bytes.`,\n );\n }\n}\n\nexport function validateActivityEvents(\n events: readonly AgentEventOrUnknown[],\n dropped: number,\n bounds: ActivityBounds,\n): void {\n if (!Number.isSafeInteger(dropped) || dropped < 0) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Activity dropped must be a non-negative integer.',\n );\n }\n if (events.length === 0 || events.length > bounds.maxEvents) {\n throw new ByokCloudError(\n 'activity_batch_too_large',\n `Activity batch must contain 1..${bounds.maxEvents} events.`,\n );\n }\n const encoded = JSON.stringify(events);\n if (encoder.encode(encoded).length > bounds.maxBytes) {\n throw new ByokCloudError(\n 'activity_batch_too_large',\n `Activity batch exceeds ${bounds.maxBytes} UTF-8 bytes.`,\n );\n }\n}\n\nexport function validateActivityBatch(\n input: Omit<ActivityAppendInput, 'ttlMs' | 'capacity'>,\n bounds: ActivityBounds,\n): void {\n validateActivityEvents(input.events, input.dropped, bounds);\n validateActivityAppend({ ...input, ttlMs: bounds.ttlMs, capacity: bounds.capacity });\n}\n\nexport async function appendActivityEvents(\n activity: TenantBoundActivity,\n input: {\n readonly taskId: string;\n readonly sourceEnvelopeId: string;\n readonly batchSeq: number;\n readonly events: readonly AgentEventOrUnknown[];\n readonly dropped: number;\n },\n bounds: ActivityBounds,\n): Promise<ActivityTail> {\n validateActivityBatch(input, bounds);\n return activity.append({\n taskId: input.taskId,\n sourceEnvelopeId: input.sourceEnvelopeId,\n batchSeq: input.batchSeq,\n events: input.events,\n dropped: input.dropped,\n ttlMs: bounds.ttlMs,\n capacity: bounds.capacity,\n });\n}\n","/**\n * The single bearer check every device-facing route shares.\n *\n * S1 shape, reproduced exactly: the token's `(tenantId, deviceId, productId)`\n * are LOOKUP KEYS, and the ROW that comes back is the authority. A token for a\n * device that no longer exists, one whose tenant does not own that device, one\n * whose product disagrees with the row, one for a revoked device, an expired\n * token, and a malformed tenant id in the claims all fail identically here and\n * are indistinguishable to the caller. There is deliberately no \"which of\n * those was it\" signal to hand back, so no route can turn a 401 into a\n * cross-tenant existence oracle.\n *\n * The returned {@link DevicePrincipal} is core's, carrying a minted\n * `TenantId` — which is what makes it the only legal input to\n * `tenantStoresFor` (`../tenant-stores.ts`).\n */\nimport { isTenantId, tenantId, type DevicePrincipal } from '@byok-sdk/core';\nimport type { DeviceDirectory } from '../stores/ports';\nimport type { TokenSigner } from './tokens';\n\nexport interface BearerAuthDeps {\n readonly tokenSigner: TokenSigner;\n readonly devices: DeviceDirectory;\n}\n\nexport function extractBearerToken(header: string | undefined): string | undefined {\n if (header === undefined) return undefined;\n const match = /^Bearer\\s+(.+)$/i.exec(header);\n return match?.[1];\n}\n\nexport async function authenticateBearer(\n header: string | undefined,\n deps: BearerAuthDeps,\n): Promise<DevicePrincipal | undefined> {\n const token = extractBearerToken(header);\n if (token === undefined) return undefined;\n\n const claims = await deps.tokenSigner.verify(token);\n if (claims === undefined) return undefined;\n // The claim is a bare string until it is minted; a tenant id that core would\n // refuse is simply not a tenant this deployment ever issued a token for.\n if (!isTenantId(claims.tenantId)) return undefined;\n\n const device = await deps.devices.get(tenantId(claims.tenantId), claims.deviceId);\n if (device === undefined || device.revoked) return undefined;\n if (device.productId !== claims.productId) return undefined;\n\n return {\n kind: 'device',\n tenantId: device.tenantId,\n productId: device.productId,\n deviceId: device.deviceId,\n };\n}\n","/**\n * Layer 2 of the six-layer isolation model (§12.6.2) — the tenant-closed\n * facade a handler actually receives.\n *\n * `@byok-sdk/core`'s `stores.ts` deliberately left this undefined: it is shaped by\n * how handlers are written, and the first handlers live here. This is that\n * shape, and the two properties it exists to enforce are:\n *\n * 1. **It can only be built from an authenticated principal.** {@link\n * tenantStoresFor} is the only constructor, and its first parameter is a\n * `Principal` — a value that only `authenticateBearer` (`auth/bearer.ts`)\n * mints, and only from a device ROW. There is no path from a device-supplied\n * string to a facade.\n * 2. **No handler ever passes a `TenantId` again.** Every method below has the\n * tenant pre-applied, so a handler cannot read `principal.tenantId` off one\n * principal and hand a different tenant to a store. Grep the handler tree\n * for `TenantId` and you will not find one — asserted by\n * `src/__tests__/constraints.test.ts`.\n *\n * The three pre-tenant store methods (`resolveByDeviceId`, `redeem`, the\n * presigned blob calls) are deliberately absent from this surface: a\n * device-facing handler must not be able to reach them.\n */\nimport {\n principalTenant,\n type BoardClaimInput,\n type BoardItem,\n type BoardItemInput,\n type BoardListQuery,\n type BoardPage,\n type BoardStatusUpdateInput,\n type BoardUnclaimInput,\n type CoreStores,\n type MailboxAdvanceCursorInput,\n type MailboxAppendInput,\n type MailboxCursorState,\n type MailboxMessage,\n type MailboxPage,\n type MailboxReadQuery,\n type Principal,\n type PresenceHint,\n type PresenceHintInput,\n type StorageFinalizeInput,\n type StorageFinalizeResult,\n type StorageReservation,\n type StorageReservationInput,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { ActivityAppendInput, ActivityTail } from './activity';\nimport type {\n ApprovalTimelineAppendInput,\n ApprovalTimelineTail,\n} from './approval-timeline';\nimport type {\n BlobObservation,\n CloudStores,\n DeviceRecord,\n RequestReceipt,\n TaskAttempt,\n TaskAttemptStatus,\n} from './stores/ports';\n\nexport interface TenantBoundMailbox {\n append(input: MailboxAppendInput): Promise<MailboxMessage>;\n /** Pure read. Never advances the cursor — the daemon's next poll is the only ack. */\n readAfter(query: MailboxReadQuery): Promise<MailboxPage>;\n advanceCursor(input: MailboxAdvanceCursorInput): Promise<MailboxCursorState>;\n readCursor(deviceId: string): Promise<MailboxCursorState>;\n}\n\nexport interface TenantBoundBoard {\n create(input: BoardItemInput): Promise<BoardItem>;\n get(itemId: string): Promise<BoardItem | undefined>;\n list(query: BoardListQuery): Promise<BoardPage>;\n claim(input: BoardClaimInput): Promise<BoardItem>;\n unclaim(input: BoardUnclaimInput): Promise<BoardItem>;\n updateStatus(input: BoardStatusUpdateInput): Promise<BoardItem>;\n}\n\nexport interface TenantBoundPresence {\n publish(input: PresenceHintInput): Promise<PresenceHint>;\n read(deviceId: string): Promise<PresenceHint | undefined>;\n list(): Promise<readonly PresenceHint[]>;\n}\n\nexport interface TenantBoundActivity {\n append(input: ActivityAppendInput): Promise<ActivityTail>;\n read(taskId: string): Promise<ActivityTail | undefined>;\n}\n\nexport interface TenantBoundApprovalTimeline {\n append(input: ApprovalTimelineAppendInput): Promise<ApprovalTimelineTail>;\n read(taskId: string): Promise<ApprovalTimelineTail | undefined>;\n}\n\nexport interface TenantBoundDevices {\n get(deviceId: string): Promise<DeviceRecord | undefined>;\n list(): Promise<readonly DeviceRecord[]>;\n revoke(deviceId: string): Promise<void>;\n}\n\nexport interface TenantBoundTaskAttempts {\n open(input: { readonly taskId: string; readonly deviceId: string }): Promise<TaskAttempt>;\n get(taskId: string): Promise<TaskAttempt | undefined>;\n claim(input: { readonly taskId: string; readonly deviceId: string }): Promise<TaskAttempt | undefined>;\n recordStatus(input: { readonly taskId: string; readonly status: TaskAttemptStatus }): Promise<TaskAttempt | undefined>;\n}\n\nexport interface TenantBoundDedup {\n checkAndRecord(deviceId: string, envelopeId: string): Promise<boolean>;\n}\n\nexport interface TenantBoundReceipts {\n record(input: { readonly key: string; readonly body: string }): Promise<{\n readonly receipt: RequestReceipt;\n readonly created: boolean;\n }>;\n get(key: string): Promise<RequestReceipt | undefined>;\n}\n\nexport interface TenantBoundBlobs {\n createUpload(reservation: StorageReservation): Promise<{ readonly blobId: string; readonly uploadUrl: string }>;\n observeUpload(blobId: string, reservation: StorageReservation): Promise<BlobObservation | undefined>;\n getDownloadUrl(blobId: string): Promise<string | undefined>;\n}\n\nexport interface TenantBoundQuota {\n readReservation(reservationId: string): Promise<StorageReservation | undefined>;\n reserve(input: StorageReservationInput): Promise<StorageReservation>;\n finalizeReservation(input: StorageFinalizeInput): Promise<StorageFinalizeResult>;\n abortReservation(reservationId: string): Promise<StorageReservation>;\n}\n\nexport interface TenantBoundRateLimiter {\n consume(deviceId: string): Promise<boolean>;\n}\n\nexport interface TenantStores {\n readonly tenant: TenantId;\n readonly principal: Principal;\n readonly mailbox: TenantBoundMailbox;\n readonly board: TenantBoundBoard;\n readonly presence: TenantBoundPresence;\n readonly activity: TenantBoundActivity;\n readonly approvals: TenantBoundApprovalTimeline;\n readonly devices: TenantBoundDevices;\n readonly tasks: TenantBoundTaskAttempts;\n readonly dedup: TenantBoundDedup;\n readonly receipts: TenantBoundReceipts;\n readonly blobs: TenantBoundBlobs;\n readonly quota: TenantBoundQuota;\n readonly rateLimiter: TenantBoundRateLimiter;\n}\n\n/** Every naked store a composition supplies. Only {@link tenantStoresFor} reads this. */\nexport interface CloudRootStores {\n readonly core: CoreStores;\n readonly cloud: CloudStores;\n}\n\nexport function tenantStoresFor(principal: Principal, root: CloudRootStores): TenantStores {\n const tenant = principalTenant(principal);\n const { core, cloud } = root;\n\n return {\n tenant,\n principal,\n mailbox: {\n append: (input) => core.mailbox.append(tenant, input),\n readAfter: (query) => core.mailbox.readAfter(tenant, query),\n advanceCursor: (input) => core.mailbox.advanceCursor(tenant, input),\n readCursor: (deviceId) => core.mailbox.readCursor(tenant, deviceId),\n },\n board: {\n create: (input) => core.board.create(tenant, input),\n get: (itemId) => core.board.get(tenant, itemId),\n list: (query) => core.board.list(tenant, query),\n claim: (input) => core.board.claim(tenant, input),\n unclaim: (input) => core.board.unclaim(tenant, input),\n updateStatus: (input) => core.board.updateStatus(tenant, input),\n },\n presence: {\n publish: (input) => core.presence.publish(tenant, input),\n read: (deviceId) => core.presence.read(tenant, deviceId),\n list: () => core.presence.list(tenant),\n },\n activity: {\n append: (input) => cloud.activity.append(tenant, input),\n read: (taskId) => cloud.activity.read(tenant, taskId),\n },\n approvals: {\n append: (input) => cloud.approvals.append(tenant, input),\n read: (taskId) => cloud.approvals.read(tenant, taskId),\n },\n devices: {\n get: (deviceId) => cloud.devices.get(tenant, deviceId),\n list: () => cloud.devices.list(tenant),\n revoke: (deviceId) => cloud.devices.revoke(tenant, deviceId),\n },\n tasks: {\n open: (input) => cloud.tasks.open(tenant, input),\n get: (taskId) => cloud.tasks.get(tenant, taskId),\n claim: (input) => cloud.tasks.claim(tenant, input),\n recordStatus: (input) => cloud.tasks.recordStatus(tenant, input),\n },\n dedup: {\n checkAndRecord: (deviceId, envelopeId) => cloud.dedup.checkAndRecord(tenant, deviceId, envelopeId),\n },\n receipts: {\n record: (input) => cloud.receipts.record(tenant, input),\n get: (key) => cloud.receipts.get(tenant, key),\n },\n blobs: {\n createUpload: (reservation) => cloud.blobs.createUpload(tenant, reservation),\n observeUpload: (blobId, reservation) => cloud.blobs.observeUpload(tenant, blobId, reservation),\n getDownloadUrl: (blobId) => cloud.blobs.getDownloadUrl(tenant, blobId),\n },\n quota: {\n readReservation: (reservationId) => core.quota.readReservation(tenant, reservationId),\n reserve: (input) => core.quota.reserve(tenant, input),\n finalizeReservation: (input) => core.quota.finalizeReservation(tenant, input),\n abortReservation: (reservationId) => core.quota.abortReservation(tenant, reservationId),\n },\n rateLimiter: {\n consume: (deviceId) => cloud.rateLimiter.consume(tenant, deviceId),\n },\n };\n}\n","/**\n * The two things every device-facing handler starts from: a tolerant JSON body\n * read, and the bearer -> principal -> tenant-closed-facade step.\n *\n * Once {@link authenticateDevice} has answered, a handler holds a\n * `TenantStores` and a `DevicePrincipal` and never sees a `TenantId` again.\n */\nimport type { Context } from 'hono';\nimport type { DevicePrincipal } from '@byok-sdk/core';\nimport { authenticateBearer, type BearerAuthDeps } from '../auth/bearer';\nimport { tenantStoresFor, type CloudRootStores, type TenantStores } from '../tenant-stores';\n\n/** Every error response on this surface is `{ error }` — the same shape the reference server uses. */\nexport interface ErrorBody {\n readonly error: string;\n}\n\nexport async function readJsonBody(c: Context): Promise<unknown> {\n try {\n return await c.req.json();\n } catch {\n return undefined;\n }\n}\n\nexport interface DeviceRouteDeps {\n readonly bearer: BearerAuthDeps;\n readonly root: CloudRootStores;\n}\n\nexport interface AuthenticatedDeviceContext {\n readonly device: DevicePrincipal;\n readonly stores: TenantStores;\n}\n\n/**\n * `undefined` means \"answer 401\" — and it means that for a missing header, a\n * forged token, an expired token, a revoked device, a product mismatch, and a\n * token whose tenant does not own the device, indistinguishably.\n */\nexport async function authenticateDevice(\n c: Context,\n deps: DeviceRouteDeps,\n): Promise<AuthenticatedDeviceContext | undefined> {\n const device = await authenticateBearer(c.req.header('authorization'), deps.bearer);\n if (device === undefined) return undefined;\n return { device, stores: tenantStoresFor(device, deps.root) };\n}\n","/**\n * Blob flows (§7).\n *\n * Two route classes on purpose: `POST /byok/blobs` and `GET\n * /byok/blobs/:id/url` are bearer-authed and therefore tenant-closed (a\n * download URL is minted only for a blob the caller's own tenant owns, and a\n * foreign blob is indistinguishable from a missing one); the two `/content`\n * routes are presigned, because they are meant to be hit directly — by a\n * browser, by a `PUT` from a daemon that holds only the signed URL — with no\n * JWT in scope at all. The HMAC signature over the blob id plus its expiry IS\n * the credential there, which is why those two carry the `presigned` class in\n * the route inventory rather than being lumped in with the device routes.\n *\n * The split runs all the way down: the bearer-authed pair reaches blobs only\n * through the tenant facade and never holds a naked store, and the presigned\n * pair holds only a {@link BlobContentProxy} and no bearer deps. A composition\n * without a proxy does not mount them (`cloud.ts`).\n */\nimport type { Context } from 'hono';\nimport { z } from 'zod';\nimport {\n CreateBlobRequestSchema,\n type BlobDownloadUrlResponse,\n type CreateBlobResponse,\n} from '@byok-sdk/protocol';\nimport {\n STORAGE_ERROR_CODES,\n STORAGE_ERROR_HTTP_STATUS,\n contentHash,\n isCoreError,\n type StorageErrorCode,\n} from '@byok-sdk/core';\nimport type { BlobContentProxy } from '../stores/ports';\nimport { authenticateDevice, readJsonBody, type DeviceRouteDeps } from './shared';\n\n/** The three bearer-authed routes: everything they touch goes through the tenant facade. */\nexport interface BlobRouteDeps extends DeviceRouteDeps {\n readonly maxBlobSizeBytes: number;\n}\n\n/** Reservation and presign grants deliberately share one expiry horizon. */\nexport const BLOB_RESERVATION_TTL_MS = 15 * 60 * 1000;\n\n/**\n * The two presigned routes. No bearer deps at all — there is no principal to\n * build a facade from, and the proxy is the only thing they need.\n */\nexport interface BlobContentRouteDeps {\n readonly contentProxy: BlobContentProxy;\n}\n\n/**\n * The presigned query contract. Cloud-owned (the wire DTO package covers\n * request/response BODIES, not URL signing), and validated rather than\n * hand-parsed so a non-numeric `exp` is a failed verification instead of a\n * `NaN` comparison that quietly answers `false` for the wrong reason.\n */\nconst SignedUrlQuerySchema = z.object({\n sig: z.string().min(1),\n exp: z.coerce.number().finite(),\n});\n\nexport function createBlobHandler(deps: BlobRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n\n const parsed = CreateBlobRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'size, contentType, and contentHash are required' }, 400);\n if (parsed.data.size > deps.maxBlobSizeBytes) {\n return c.json({ error: `blob exceeds max size of ${deps.maxBlobSizeBytes} bytes` }, 413);\n }\n\n const reservationId = idempotencyKey(c);\n if (reservationId === undefined) {\n return c.json({ error: 'Idempotency-Key header is required' }, 400);\n }\n\n try {\n const reservation = await authenticated.stores.quota.reserve({\n reservationId,\n kind: 'object',\n expectedBytes: BigInt(parsed.data.size),\n contentHash: contentHash(parsed.data.contentHash),\n contentType: parsed.data.contentType,\n ttlMs: BLOB_RESERVATION_TTL_MS,\n });\n try {\n const { blobId, uploadUrl } = await authenticated.stores.blobs.createUpload(reservation);\n const response: CreateBlobResponse = { blobId, uploadUrl };\n return c.json(response, 200);\n } catch (error) {\n // Preserve the grant failure as the client-facing authority. Cleanup\n // is best-effort here; admission reaps an abandoned hold after TTL if\n // the store is concurrently unavailable.\n await authenticated.stores.quota.abortReservation(reservationId).catch(() => undefined);\n const rendered = renderStorageError(c, error);\n if (rendered !== undefined) return rendered;\n throw error;\n }\n } catch (error) {\n const rendered = renderStorageError(c, error);\n if (rendered !== undefined) return rendered;\n throw error;\n }\n };\n}\n\nexport function finalizeBlobHandler(deps: BlobRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n\n const reservationId = idempotencyKey(c);\n if (reservationId === undefined) {\n return c.json({ error: 'Idempotency-Key header is required' }, 400);\n }\n\n try {\n const reservation = await authenticated.stores.quota.readReservation(reservationId);\n if (reservation === undefined) {\n return c.json({ error: 'storage_reservation_not_found' }, 404);\n }\n const blobId = c.req.param('id') ?? '';\n const observed = await authenticated.stores.blobs.observeUpload(\n blobId,\n reservation,\n );\n if (observed === undefined) {\n await authenticated.stores.quota.abortReservation(reservationId);\n return c.json({ error: 'storage_integrity_mismatch' }, 422);\n }\n\n await authenticated.stores.quota.finalizeReservation({\n reservationId,\n ...observed,\n });\n return c.body(null, 204);\n } catch (error) {\n const rendered = renderStorageError(c, error);\n if (rendered !== undefined) return rendered;\n throw error;\n }\n };\n}\n\nexport function blobDownloadUrlHandler(deps: BlobRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n\n const downloadUrl = await authenticated.stores.blobs.getDownloadUrl(c.req.param('id') ?? '');\n if (downloadUrl === undefined) return c.json({ error: 'blob not found' }, 404);\n\n const response: BlobDownloadUrlResponse = { downloadUrl };\n return c.json(response, 200);\n };\n}\n\nexport function blobUploadContentHandler(deps: BlobContentRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const blobId = c.req.param('id') ?? '';\n const query = SignedUrlQuerySchema.safeParse({ sig: c.req.query('sig'), exp: c.req.query('exp') });\n if (!query.success || !(await deps.contentProxy.verifySignedUrl(blobId, 'put', query.data.sig, query.data.exp))) {\n return c.json({ error: 'invalid or expired signature' }, 401);\n }\n\n const result = await deps.contentProxy.writeContent(blobId, new Uint8Array(await c.req.arrayBuffer()));\n if (!result.ok) return c.json({ error: result.reason }, 422);\n return c.body(null, 204);\n };\n}\n\nexport function blobDownloadContentHandler(deps: BlobContentRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const blobId = c.req.param('id') ?? '';\n const query = SignedUrlQuerySchema.safeParse({ sig: c.req.query('sig'), exp: c.req.query('exp') });\n if (!query.success || !(await deps.contentProxy.verifySignedUrl(blobId, 'get', query.data.sig, query.data.exp))) {\n return c.json({ error: 'invalid or expired signature' }, 401);\n }\n\n const content = await deps.contentProxy.readContent(blobId);\n if (content === undefined) return c.json({ error: 'blob not found' }, 404);\n return c.body(new Uint8Array(content.data), 200, { 'content-type': content.contentType });\n };\n}\n\nfunction idempotencyKey(c: Context): string | undefined {\n const value = c.req.header('Idempotency-Key');\n if (value === undefined || value.length === 0 || value.length > 200) return undefined;\n return value;\n}\n\nfunction renderStorageError(c: Context, error: unknown): Response | undefined {\n if (!isCoreError(error)) return undefined;\n if ((STORAGE_ERROR_CODES as readonly string[]).includes(error.code)) {\n const code = error.code as StorageErrorCode;\n return c.json({ error: code }, STORAGE_ERROR_HTTP_STATUS[code]);\n }\n if (error.code === 'storage_reservation_not_found' || error.code === 'object_not_found') {\n return c.json({ error: error.code }, 404);\n }\n if (error.code === 'storage_entitlement_missing' || error.code === 'object_state_invalid') {\n return c.json({ error: error.code }, 409);\n }\n if (error.code === 'content_hash_invalid') {\n return c.json({ error: error.code }, 400);\n }\n return undefined;\n}\n","/**\n * `GET /byok/capabilities` — the declaration route (ADR-010).\n *\n * Public by design: a client has to be able to read what a deployment supports\n * before it holds a credential, and the declaration is a deployment-level\n * fact, not a tenant-level one. Nothing tenant-scoped may ever be added to\n * this response for exactly that reason.\n */\nimport type { Context } from 'hono';\nimport type { CapabilityDeclaration } from '@byok-sdk/core';\n\nexport interface CapabilitiesRouteDeps {\n readonly declaration: CapabilityDeclaration;\n}\n\nexport function capabilitiesHandler(deps: CapabilitiesRouteDeps) {\n return async (c: Context): Promise<Response> => c.json(deps.declaration, 200);\n}\n","/**\n * Auth v2 (docs/protocol.md §6): pair, challenge, token.\n *\n * Byte-for-byte the same request/response DTOs the daemon already speaks,\n * because they come from `@byok-sdk/protocol` rather than from a hosted copy of\n * them. The behavior differences a hosted surface DOES make are two, both\n * narrowing:\n *\n * - a pairing code that is unknown, expired, or already used gets one 401 with\n * one message (the reference server names the reason);\n * - an unknown device and a revoked device were already indistinguishable on\n * the reference server, and stay so here.\n */\nimport type { Context } from 'hono';\nimport {\n ChallengeRequestSchema,\n PairRequestSchema,\n TokenRequestSchema,\n type ChallengeResponse,\n type PairResponse,\n type TokenResponse,\n} from '@byok-sdk/protocol';\nimport type { AuthPlane } from '../auth/plane';\nimport { readJsonBody } from './shared';\n\nexport interface AuthRouteDeps {\n readonly auth: AuthPlane;\n}\n\nexport function pairHandler(deps: AuthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const parsed = PairRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) {\n return c.json({ error: 'pairingCode, deviceName, and devicePublicKey are required strings' }, 400);\n }\n\n const device = await deps.auth.redeemAndRegister(parsed.data);\n if (device === undefined) return c.json({ error: 'invalid pairing code' }, 401);\n\n const { accessToken, expiresAt } = await deps.auth.mintAccessToken(device);\n const response: PairResponse = { deviceId: device.deviceId, accessToken, refreshHint: expiresAt };\n return c.json(response, 200);\n };\n}\n\nexport function challengeHandler(deps: AuthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const parsed = ChallengeRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'deviceId is required' }, 400);\n\n // Pre-tenant by construction: `ChallengeRequest` is the pinned wire\n // contract and carries only a deviceId, so the ROW is what tells this\n // deployment which tenant the device belongs to.\n const device = await deps.auth.resolveDevice(parsed.data.deviceId);\n if (device === undefined) return c.json({ error: 'unknown or revoked device' }, 401);\n\n const response: ChallengeResponse = { nonce: await deps.auth.issueNonce(device) };\n return c.json(response, 200);\n };\n}\n\nexport function tokenHandler(deps: AuthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const parsed = TokenRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'deviceId, nonce, and signature are required' }, 400);\n const { deviceId, nonce, signature } = parsed.data;\n\n const device = await deps.auth.resolveDevice(deviceId);\n if (device === undefined) return c.json({ error: 'unknown or revoked device' }, 401);\n\n if (!(await deps.auth.validateNonce(device, nonce))) {\n return c.json({ error: 'invalid, expired, or already-used nonce' }, 401);\n }\n // Domain-separated (`byok-nonce-v1\\n`, `auth/verify.ts`): a raw signature\n // over the bare nonce is invalid here, with no second accepted form.\n if (!(await deps.auth.verifySignature(device, nonce, signature))) {\n return c.json({ error: 'invalid signature' }, 401);\n }\n // Burn the nonce only on a fully verified success (§6.2) — an invalid\n // signature attempt does not consume the legitimate device's nonce.\n await deps.auth.consumeNonce(device, nonce);\n\n const { accessToken, expiresAt } = await deps.auth.mintAccessToken(device);\n const response: TokenResponse = { accessToken, expiresAt };\n return c.json(response, 200);\n };\n}\n","/**\n * `GET /byok/events?cursor=N` — the long-poll receive half (§8).\n *\n * Three properties the daemon's transport depends on, reproduced against the\n * core mailbox rather than an in-process outbox:\n *\n * - **Reading is not acknowledging.** `readAfter` never moves the cursor. The\n * ONLY ack is the cursor the daemon brings back on its NEXT poll, after it\n * has durably processed what it was handed — which is why the ack below\n * happens before the read, against the incoming `cursor`, and why a poll\n * that hands back the same cursor replays the same page forever.\n * - **The ack is monotonic.** A cursor at or below what the device already\n * acked carries no new information and is not an ack attempt; only a\n * strictly higher one advances. The store's own\n * `mailbox_cursor_regression` guard stays the authority on going backwards\n * (asserted directly in `src/__tests__/mailbox-cursor.test.ts`).\n * - **The hold.** An empty poll is held open instead of answered immediately,\n * so an idle daemon is not a busy-loop. The hold is a bounded re-read, not a\n * registered waiter: a waiter map is exactly the cross-request state a\n * stateless handler may not keep (S3.5 boxes 14-15), and a second cloud\n * instance would not see it anyway.\n */\nimport type { Context } from 'hono';\nimport { decodeEnvelope, type Envelope, type EventsPollResponse } from '@byok-sdk/protocol';\nimport { authenticateDevice, type DeviceRouteDeps } from './shared';\n\n/** Protocol features this cloud build accepts from a long-poll daemon. */\nconst CLOUD_PROTOCOL_CAPABILITIES = ['result-document'];\n\nexport interface EventsRouteDeps extends DeviceRouteDeps {\n /** How long an empty poll is held open, ms. */\n readonly longPollHoldMs: number;\n /** How often the mailbox is re-read while holding, ms. */\n readonly longPollIntervalMs: number;\n /** Max rows per response. */\n readonly pageLimit: number;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function eventsHandler(deps: EventsRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const { device, stores } = authenticated;\n\n const cursorRaw = c.req.query('cursor');\n let cursor = 0;\n if (cursorRaw !== undefined) {\n const parsedCursor = Number(cursorRaw);\n if (!Number.isInteger(parsedCursor) || parsedCursor < 0) return c.json({ error: 'invalid cursor' }, 400);\n cursor = parsedCursor;\n }\n\n const acked = await stores.mailbox.readCursor(device.deviceId);\n if (cursor > acked.ackedSeq) {\n await stores.mailbox.advanceCursor({ deviceId: device.deviceId, ackedSeq: cursor });\n }\n\n const attempts = Math.max(1, Math.ceil(deps.longPollHoldMs / deps.longPollIntervalMs));\n for (let attempt = 0; attempt < attempts; attempt += 1) {\n const page = await stores.mailbox.readAfter({\n deviceId: device.deviceId,\n afterSeq: cursor,\n limit: deps.pageLimit,\n });\n if (page.messages.length > 0) {\n const events: Envelope[] = page.messages.map((message) => decodeEnvelope(message.body));\n const response: EventsPollResponse = {\n events,\n cursor: page.nextSeq,\n capabilities: CLOUD_PROTOCOL_CAPABILITIES,\n };\n return c.json(response, 200);\n }\n if (attempt < attempts - 1) await sleep(deps.longPollIntervalMs);\n }\n\n const response: EventsPollResponse = {\n events: [],\n cursor,\n capabilities: CLOUD_PROTOCOL_CAPABILITIES,\n };\n return c.json(response, 200);\n };\n}\n","import { tenantKey, type TenantId } from '@byok-sdk/core';\nimport { z } from 'zod';\nimport { ByokCloudError } from './errors';\n\nexport const DEFAULT_APPROVAL_TIMELINE_CAPACITY = 50;\nexport const DEFAULT_APPROVAL_TIMELINE_TTL_MS = 10 * 60 * 1_000;\nexport const APPROVAL_SUMMARY_MAX_BYTES = 16 * 1_024;\n\nconst NonBlankIdSchema = z.string().max(200).regex(/\\S/, 'value must not be blank');\nconst TaskIdSchema = z.string().min(1).max(200);\n\nexport const ApprovalTimelineEventSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('approval_requested'),\n summary: z.string(),\n approvalId: NonBlankIdSchema.optional(),\n }),\n z.object({\n type: z.literal('approval_resolved'),\n approvalId: NonBlankIdSchema,\n decision: z.enum(['approve', 'reject']),\n resolvedBy: z.enum(['local']),\n at: z.iso.datetime({ offset: true }),\n }),\n]);\n\nexport type ApprovalTimelineEvent = Readonly<z.infer<typeof ApprovalTimelineEventSchema>>;\n\nexport const ApprovalObservationSchema = z.object({\n taskId: TaskIdSchema,\n sourceEnvelopeId: NonBlankIdSchema,\n revision: z.number().int().positive(),\n receivedAt: z.iso.datetime(),\n event: ApprovalTimelineEventSchema,\n});\n\nexport type ApprovalObservation = Readonly<z.infer<typeof ApprovalObservationSchema>>;\n\nexport interface ApprovalTimelineTail {\n readonly tenantId: TenantId;\n readonly taskId: string;\n readonly entries: readonly ApprovalObservation[];\n readonly cursor?: number;\n readonly dropped: number;\n readonly capacity: number;\n readonly expiresAt: string;\n}\n\nexport interface ApprovalTimelineAppendInput {\n readonly taskId: string;\n readonly sourceEnvelopeId: string;\n readonly event: ApprovalTimelineEvent;\n readonly ttlMs?: number;\n readonly capacity?: number;\n}\n\nexport interface ApprovalTimelineStore {\n append(tenant: TenantId, input: ApprovalTimelineAppendInput): Promise<ApprovalTimelineTail>;\n read(tenant: TenantId, taskId: string): Promise<ApprovalTimelineTail | undefined>;\n}\n\nexport interface ValidatedApprovalTimelineAppend {\n readonly capacity: number;\n readonly ttlMs: number;\n readonly event: ApprovalTimelineEvent;\n}\n\nexport function validateApprovalTimelineAppend(\n input: ApprovalTimelineAppendInput,\n): ValidatedApprovalTimelineAppend {\n const capacity = input.capacity ?? DEFAULT_APPROVAL_TIMELINE_CAPACITY;\n const ttlMs = input.ttlMs ?? DEFAULT_APPROVAL_TIMELINE_TTL_MS;\n if (!Number.isSafeInteger(capacity) || capacity <= 0) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Approval timeline capacity must be a positive integer, received ${String(capacity)}.`,\n );\n }\n if (!Number.isFinite(ttlMs) || ttlMs <= 0) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Approval timeline ttl must be a positive number of milliseconds, received ${String(ttlMs)}.`,\n );\n }\n const parsed = z\n .object({\n taskId: TaskIdSchema,\n sourceEnvelopeId: NonBlankIdSchema,\n event: ApprovalTimelineEventSchema,\n })\n .safeParse(input);\n if (!parsed.success) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Approval observations require stable source identity and a valid native lifecycle event.',\n );\n }\n if (\n parsed.data.event.type === 'approval_requested' &&\n new TextEncoder().encode(parsed.data.event.summary).byteLength > APPROVAL_SUMMARY_MAX_BYTES\n ) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Approval summary exceeds ${APPROVAL_SUMMARY_MAX_BYTES} UTF-8 bytes.`,\n );\n }\n return { capacity, ttlMs, event: parsed.data.event };\n}\n\nexport function approvalTimelineKey(tenant: TenantId, taskId: string): string {\n return tenantKey(tenant, taskId);\n}\n\nexport function parseApprovalObservations(value: unknown): readonly ApprovalObservation[] {\n return z.array(ApprovalObservationSchema).parse(value) as readonly ApprovalObservation[];\n}\n\nexport function approvalTimelineCursor(\n entries: readonly ApprovalObservation[],\n): number | undefined {\n return entries.at(-1)?.revision;\n}\n","import { isCoreConflictError } from '@byok-sdk/core';\nimport type { TenantBoundBoard } from './tenant-stores';\n\n/**\n * One-way projection from an already accepted terminal fact into coordination.\n *\n * This module deliberately knows no wire message type or execution-state\n * vocabulary. It can only CAS an existing coordination row one step toward\n * review, and a concurrent board decision wins without retry or overwrite.\n */\nexport async function projectTerminalToReview(board: TenantBoundBoard, taskId: string): Promise<void> {\n const item = await board.get(taskId);\n if (item === undefined || item.status !== 'in_progress') return;\n try {\n await board.updateStatus({\n itemId: taskId,\n expectedStatus: 'in_progress',\n status: 'in_review',\n });\n } catch (caught) {\n if (isCoreConflictError(caught)) return;\n throw caught;\n }\n}\n","/**\n * The single inbound choke point for every daemon -> cloud envelope.\n *\n * The reference server runs this gate inside a live `ConnectionHub`; here it\n * is a pure function over a tenant-closed facade, so the same order holds with\n * no connection, no session, and no cross-request state:\n *\n * 0. **rate limit** — one token per inbound envelope, debited BEFORE anything\n * else, so a flood of garbage-typed envelopes costs the same budget as a\n * flood of well-formed ones. S3a's reference limiter allows everything; the\n * seam is what matters at this position.\n * 1. **type-allow** — only `DAEMON_TO_SERVER_TYPES` may pass. A server ->\n * daemon type arriving inbound, or anything unrecognized, is rejected\n * before it is dispatched or counted accepted.\n * 2. **ownership** — an envelope for a task already owned by a DIFFERENT\n * device is dropped, never force-failed: force-failing on an authz mismatch\n * would let an attacker who merely guesses a `taskId` kill the real owner's\n * task. A task with no owner yet, or that this tenant does not have at all,\n * is not rejected here — the store's own no-op-on-missing behavior covers\n * the latter, and it covers it per tenant, so a guessed id from another\n * tenant writes nothing anywhere.\n * 3. **dedup** — an envelope id already seen from this device is a no-op. The\n * wire is at-least-once (§9); this makes processing at-most-once.\n * 4. **apply** — the lifecycle write.\n *\n * A duplicate is still a wire-level success (§8.2): it just did not re-run\n * anything. Only `rejected`/`rate_limited` are excluded from `accepted`.\n */\nimport {\n DAEMON_TO_SERVER_TYPES,\n encodeEnvelope,\n type Envelope,\n type MessageType,\n} from '@byok-sdk/protocol';\nimport {\n validateActivityBatch,\n appendActivityEvents,\n DEFAULT_ACTIVITY_BOUNDS,\n type ActivityBounds,\n} from './coordination';\nimport {\n validateApprovalTimelineAppend,\n type ApprovalTimelineAppendInput,\n} from './approval-timeline';\nimport { isCloudError } from './errors';\nimport { projectTerminalToReview } from './board-projection';\nimport type { TenantStores } from './tenant-stores';\n\nexport type InboundOutcome = 'accepted' | 'duplicate' | 'rejected' | 'rate_limited';\n\n/** Receipt key a task's terminal is recorded under — the idempotency seam S3b's journal will share. */\nexport function terminalReceiptKey(taskId: string): string {\n return `task:${taskId}:terminal`;\n}\n\nexport async function handleInboundEnvelope(\n stores: TenantStores,\n deviceId: string,\n envelope: Envelope,\n activityBounds: ActivityBounds = DEFAULT_ACTIVITY_BOUNDS,\n): Promise<InboundOutcome> {\n if (!(await stores.rateLimiter.consume(deviceId))) return 'rate_limited';\n\n if (!(DAEMON_TO_SERVER_TYPES as readonly MessageType[]).includes(envelope.type)) return 'rejected';\n\n const taskId = envelope.task_id;\n // Every `DAEMON_TO_SERVER_TYPES` member requires `task_id` at the schema\n // level; this is the defensive restatement, not a second contract.\n if (taskId === undefined) return 'rejected';\n\n const attempt = await stores.tasks.get(taskId);\n if (attempt?.ownerDeviceId !== undefined && attempt.ownerDeviceId !== deviceId) return 'rejected';\n\n if (envelope.type === 'task.progress' && envelope.payload.events.length > 0) {\n try {\n validateActivityBatch(\n {\n taskId,\n sourceEnvelopeId: envelope.id,\n batchSeq: envelope.payload.seq,\n events: envelope.payload.events,\n dropped: 0,\n },\n activityBounds,\n );\n } catch (caught) {\n if (\n isCloudError(caught, 'activity_batch_too_large') ||\n isCloudError(caught, 'coordination_input_invalid')\n ) {\n return 'rejected';\n }\n throw caught;\n }\n }\n\n const approvalInput = approvalTimelineAppendInput(taskId, envelope);\n if (approvalInput !== undefined) {\n try {\n validateApprovalTimelineAppend(approvalInput);\n } catch (caught) {\n if (isCloudError(caught, 'coordination_input_invalid')) return 'rejected';\n throw caught;\n }\n }\n\n if (await stores.dedup.checkAndRecord(deviceId, envelope.id)) return 'duplicate';\n\n await applyLifecycle(stores, deviceId, taskId, envelope, activityBounds);\n return 'accepted';\n}\n\n/**\n * The lifecycle half. Deliberately thin: S3a records ownership, the coarse\n * attempt status, the terminal receipt, and bounded activity/approval\n * observations. Artifacts are accepted and carried, but the durable record of\n * what a task *produced* belongs to the truth and board planes (S5/S6) and to\n * S3b's journal — not to a map in this package.\n */\nasync function applyLifecycle(\n stores: TenantStores,\n deviceId: string,\n taskId: string,\n envelope: Envelope,\n activityBounds: ActivityBounds,\n): Promise<void> {\n switch (envelope.type) {\n case 'task.claim':\n await stores.tasks.claim({ taskId, deviceId });\n return;\n case 'task.started':\n await stores.tasks.recordStatus({ taskId, status: 'running' });\n return;\n case 'task.decline':\n await stores.tasks.recordStatus({ taskId, status: 'failed' });\n return;\n case 'task.progress':\n if (envelope.payload.events.length > 0) {\n await appendActivityEvents(\n stores.activity,\n {\n taskId,\n sourceEnvelopeId: envelope.id,\n batchSeq: envelope.payload.seq,\n events: envelope.payload.events,\n dropped: 0,\n },\n activityBounds,\n );\n }\n return;\n case 'task.await_approval':\n await stores.approvals.append(approvalTimelineAppendInput(taskId, envelope)!);\n return;\n case 'task.approval_resolved':\n await stores.approvals.append(approvalTimelineAppendInput(taskId, envelope)!);\n return;\n case 'task.complete':\n await recordTerminal(stores, taskId, envelope, 'complete');\n return;\n case 'task.fail':\n await recordTerminal(stores, taskId, envelope, 'failed');\n return;\n case 'task.cancelled':\n await recordTerminal(stores, taskId, envelope, 'cancelled');\n return;\n default:\n return;\n }\n}\n\nfunction approvalTimelineAppendInput(\n taskId: string,\n envelope: Envelope,\n): ApprovalTimelineAppendInput | undefined {\n switch (envelope.type) {\n case 'task.await_approval':\n return {\n taskId,\n sourceEnvelopeId: envelope.id,\n event: {\n type: 'approval_requested',\n summary: envelope.payload.summary,\n ...(envelope.payload.approvalId === undefined\n ? {}\n : { approvalId: envelope.payload.approvalId }),\n },\n };\n case 'task.approval_resolved':\n return {\n taskId,\n sourceEnvelopeId: envelope.id,\n event: {\n type: 'approval_resolved',\n approvalId: envelope.payload.approvalId,\n decision: envelope.payload.decision,\n resolvedBy: envelope.payload.resolvedBy,\n at: envelope.payload.at,\n },\n };\n default:\n return undefined;\n }\n}\n\n/**\n * First terminal wins (§12.6.4: 不覆写第一份事实). A retried terminal — same\n * task, new envelope id, so dedup does not catch it — records nothing new and\n * leaves the attempt status where the first one put it.\n *\n * What gets stored is `encodeEnvelope(envelope)`: the canonical v1 encoding of\n * the envelope this gate already zod-parsed, NOT the device's original byte\n * sequence. The two are semantically identical by the frozen codec's own\n * round-trip guarantee, but they are not necessarily byte-identical (key\n * order, whitespace, and any field the schema drops are the parser's call, not\n * the device's) — so this receipt is evidence of the first terminal FACT, not\n * a byte-faithful capture of the first terminal REQUEST. S3b's local journal\n * is where the device's own bytes are kept.\n */\nasync function recordTerminal(\n stores: TenantStores,\n taskId: string,\n envelope: Envelope,\n status: 'complete' | 'failed' | 'cancelled',\n): Promise<void> {\n const { created } = await stores.receipts.record({\n key: terminalReceiptKey(taskId),\n body: encodeEnvelope(envelope),\n });\n if (!created) return;\n await stores.tasks.recordStatus({ taskId, status });\n await projectTerminalToReview(stores.board, taskId);\n}\n","/**\n * `POST /byok/messages` — the long-poll send half (§8.2).\n *\n * A device long-polling for cloud -> daemon traffic has no live socket to\n * carry its own outbound envelopes; this batches them over authed HTTP. Every\n * envelope goes through the same gate (`../inbound.ts`) in the same order, so\n * claim/progress/complete behave identically no matter which transport carried\n * them.\n *\n * The batch stays tolerant at the schema level — one malformed envelope must\n * not 400 the whole request — so only a structurally invalid `Envelope` or an\n * oversized batch (`MAX_MESSAGES_PER_BATCH`) fails the request outright.\n *\n * Rate limiting is per REQUEST, not per envelope: the moment any envelope\n * comes back `rate_limited`, the rest of the batch is abandoned (its bucket is\n * empty, so every remaining envelope would limit too) and the WHOLE request\n * answers 429. Envelopes processed earlier in the same batch already took\n * effect — there are no rollback semantics here — which is safe because every\n * `task.*` type is idempotent (§9): a client that retries the same batch gets\n * `duplicate` for whatever already landed.\n */\nimport type { Context } from 'hono';\nimport { MessagesSendRequestSchema, type MessagesSendResponse } from '@byok-sdk/protocol';\nimport { handleInboundEnvelope } from '../inbound';\nimport type { ActivityBounds } from '../coordination';\nimport { authenticateDevice, readJsonBody, type DeviceRouteDeps } from './shared';\n\nexport interface MessagesRouteDeps extends DeviceRouteDeps {\n readonly activityBounds: ActivityBounds;\n}\n\nexport function messagesHandler(deps: MessagesRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const { device, stores } = authenticated;\n\n const parsed = MessagesSendRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'messages must be an array of envelopes' }, 400);\n\n let accepted = 0;\n let rejected = 0;\n for (const envelope of parsed.data.messages) {\n const outcome = await handleInboundEnvelope(\n stores,\n device.deviceId,\n envelope,\n deps.activityBounds,\n );\n if (outcome === 'rate_limited') return c.json({ error: 'rate limit exceeded' }, 429);\n // A duplicate is still a wire-level success (§8.2/§9's idempotency\n // window) — it just did not re-run a handler. Only a gate rejection\n // (wrong-direction type, or an ownership mismatch) is excluded.\n if (outcome === 'rejected') rejected += 1;\n else accepted += 1;\n }\n\n // `rejected` is additive and omitted entirely when zero, so a batch with\n // nothing rejected keeps the `{ accepted }` shape callers depend on.\n const response: MessagesSendResponse = rejected > 0 ? { accepted, rejected } : { accepted };\n return c.json(response, 200);\n };\n}\n","import {\n BOARD_STATUSES,\n isCoreConflictError,\n isCoreError,\n type BoardItem,\n type BoardListQuery,\n type BoardPage,\n} from '@byok-sdk/core';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\nimport { authenticateDevice, readJsonBody, type DeviceRouteDeps } from './shared';\n\nexport const DEFAULT_BOARD_PAGE_LIMIT = 50;\nexport const DEFAULT_BOARD_STREAM_QUERY_INTERVAL_MS = 5_000;\nexport const DEFAULT_BOARD_STREAM_HEARTBEAT_INTERVAL_MS = 15_000;\nexport const DEFAULT_BOARD_STREAM_RECONCILIATION_INTERVAL_MS = 120_000;\n\nexport interface BoardRouteDeps extends DeviceRouteDeps {\n readonly pageLimit: number;\n}\n\nexport interface BoardStreamRouteDeps extends BoardRouteDeps {\n readonly queryIntervalMs: number;\n readonly heartbeatIntervalMs: number;\n readonly reconciliationIntervalMs: number;\n}\n\nconst ClaimBodySchema = z.object({ expectedStatus: z.enum(BOARD_STATUSES).optional() });\nconst StatusBodySchema = z.object({\n expectedStatus: z.enum(BOARD_STATUSES),\n status: z.enum(BOARD_STATUSES),\n});\n\nfunction parseNonNegativeInteger(value: string | undefined): number | undefined {\n if (value === undefined) return 0;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction parsePositiveInteger(value: string | undefined, fallback: number): number | undefined {\n if (value === undefined) return fallback;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nfunction boardQuery(c: Context, pageLimit: number): BoardListQuery | undefined {\n const afterSeq = parseNonNegativeInteger(c.req.query('since'));\n const limit = parsePositiveInteger(c.req.query('limit'), pageLimit);\n const statusRaw = c.req.query('status');\n if (afterSeq === undefined || limit === undefined || limit > pageLimit) return undefined;\n if (statusRaw !== undefined && !BOARD_STATUSES.includes(statusRaw as (typeof BOARD_STATUSES)[number])) {\n return undefined;\n }\n return {\n afterSeq,\n limit,\n ...(c.req.query('channel') === undefined ? {} : { channel: c.req.query('channel') }),\n ...(statusRaw === undefined ? {} : { status: statusRaw as (typeof BOARD_STATUSES)[number] }),\n };\n}\n\nexport function boardListHandler(deps: BoardRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const query = boardQuery(c, deps.pageLimit);\n if (query === undefined) return c.json({ error: 'invalid board query' }, 400);\n return c.json(await authenticated.stores.board.list(query), 200);\n };\n}\n\nexport function boardClaimHandler(deps: DeviceRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const parsed = ClaimBodySchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'invalid claim body' }, 400);\n const itemId = c.req.param('id');\n if (itemId === undefined || itemId.length === 0) return c.json({ error: 'invalid board item id' }, 400);\n try {\n const item = await authenticated.stores.board.claim({\n itemId,\n holderId: authenticated.device.deviceId,\n ...(parsed.data.expectedStatus === undefined\n ? {}\n : { expectedStatus: parsed.data.expectedStatus }),\n });\n return c.json(item, 200);\n } catch (caught) {\n return boardFailure(c, caught);\n }\n };\n}\n\nexport function boardUnclaimHandler(deps: DeviceRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const itemId = c.req.param('id');\n if (itemId === undefined || itemId.length === 0) return c.json({ error: 'invalid board item id' }, 400);\n try {\n return c.json(\n await authenticated.stores.board.unclaim({\n itemId,\n holderId: authenticated.device.deviceId,\n }),\n 200,\n );\n } catch (caught) {\n return boardFailure(c, caught);\n }\n };\n}\n\nexport function boardStatusHandler(deps: DeviceRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const parsed = StatusBodySchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'invalid status body' }, 400);\n const itemId = c.req.param('id');\n if (itemId === undefined || itemId.length === 0) return c.json({ error: 'invalid board item id' }, 400);\n if (parsed.data.status === 'done') {\n return c.json({ error: 'done requires host review acceptance' }, 403);\n }\n try {\n return c.json(\n await authenticated.stores.board.updateStatus({\n itemId,\n expectedStatus: parsed.data.expectedStatus,\n status: parsed.data.status,\n holderId: authenticated.device.deviceId,\n }),\n 200,\n );\n } catch (caught) {\n return boardFailure(c, caught);\n }\n };\n}\n\nexport function boardStreamHandler(deps: BoardStreamRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const firstAuth = await authenticateDevice(c, deps);\n if (firstAuth === undefined) return c.json({ error: 'unauthorized' }, 401);\n const query = boardQuery(c, deps.pageLimit);\n if (query === undefined) return c.json({ error: 'invalid board query' }, 400);\n\n const querySince = query.afterSeq ?? 0;\n const headerRaw = c.req.header('last-event-id');\n const headerSince = headerRaw === undefined ? undefined : parseNonNegativeInteger(headerRaw);\n if (headerRaw !== undefined && headerSince === undefined) {\n return c.json({ error: 'invalid Last-Event-ID' }, 400);\n }\n if (headerSince !== undefined && c.req.query('since') !== undefined && headerSince !== querySince) {\n return c.json({ error: 'conflicting stream cursors' }, 400);\n }\n\n let stopped = false;\n const stopController = new AbortController();\n const signal = c.req.raw.signal;\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n const onAbort = () => {\n stopped = true;\n stopController.abort();\n closeController(controller);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n void pumpBoardStream(\n controller,\n c,\n deps,\n { ...query, afterSeq: headerSince ?? querySince },\n () => stopped || signal.aborted,\n stopController.signal,\n ).finally(() => {\n stopped = true;\n stopController.abort();\n signal.removeEventListener('abort', onAbort);\n closeController(controller);\n });\n },\n cancel() {\n stopped = true;\n stopController.abort();\n },\n });\n\n return new Response(stream, {\n status: 200,\n headers: {\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n 'content-type': 'text/event-stream; charset=utf-8',\n },\n });\n };\n}\n\nasync function pumpBoardStream(\n controller: ReadableStreamDefaultController<Uint8Array>,\n c: Context,\n deps: BoardStreamRouteDeps,\n initialQuery: BoardListQuery,\n isStopped: () => boolean,\n stopSignal: AbortSignal,\n): Promise<void> {\n let cursor = initialQuery.afterSeq ?? 0;\n let lastHeartbeat = performance.now();\n let lastReconcile = performance.now();\n while (!isStopped()) {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return;\n\n const page = await authenticated.stores.board.list({ ...initialQuery, afterSeq: cursor });\n for (const item of page.items) {\n enqueue(controller, `event: board\\nid: ${item.boardSeq}\\ndata: ${JSON.stringify(item)}\\n\\n`);\n cursor = item.boardSeq;\n }\n if (page.hasMore) continue;\n\n const now = performance.now();\n if (now - lastReconcile >= deps.reconciliationIntervalMs) {\n enqueue(controller, `event: reconcile\\ndata: ${JSON.stringify({ since: 0 })}\\n\\n`);\n lastReconcile = now;\n }\n if (now - lastHeartbeat >= deps.heartbeatIntervalMs) {\n enqueue(controller, ': heartbeat\\n\\n');\n lastHeartbeat = now;\n }\n await abortableSleep(deps.queryIntervalMs, stopSignal);\n }\n}\n\nfunction enqueue(controller: ReadableStreamDefaultController<Uint8Array>, value: string): void {\n try {\n controller.enqueue(new TextEncoder().encode(value));\n } catch {\n // The request abort/cancel path owns closure. A closed controller is terminal.\n }\n}\n\nfunction closeController(controller: ReadableStreamDefaultController<Uint8Array>): void {\n try {\n controller.close();\n } catch {\n // Already closed by the peer or the pump.\n }\n}\n\nasync function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {\n if (signal.aborted) return;\n await new Promise<void>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const finish = () => {\n if (timer !== undefined) clearTimeout(timer);\n signal.removeEventListener('abort', finish);\n resolve();\n };\n timer = setTimeout(finish, ms);\n signal.addEventListener('abort', finish, { once: true });\n if (signal.aborted) finish();\n });\n}\n\nfunction boardFailure(c: Context, caught: unknown): Response {\n if (isCoreConflictError<BoardItem>(caught)) {\n const holder = caught.current.assignee;\n return c.json(\n {\n error: caught.code,\n current: caught.current,\n observedAt: caught.observedAt,\n ...(holder === undefined ? {} : { holder: { ...holder, observedAt: caught.observedAt } }),\n },\n 409,\n );\n }\n if (isCoreError(caught, 'board_item_not_found')) return c.json({ error: caught.code }, 404);\n if (isCoreError(caught, 'board_not_held')) return c.json({ error: caught.code }, 409);\n throw caught;\n}\n\nexport type BoardPollResponse = BoardPage;\n","import { isCoreError, PRESENCE_LEVELS } from '@byok-sdk/core';\nimport { ConfiguredToolsetsSchema } from '@byok-sdk/protocol';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\nimport { appendActivityEvents, type ActivityBounds } from '../coordination';\nimport { ActivityAppendRequestSchema } from '../activity';\nimport { isCloudError } from '../errors';\nimport { authenticateDevice, readJsonBody, type DeviceRouteDeps } from './shared';\n\nexport interface PresenceRouteDeps extends DeviceRouteDeps {\n readonly ttlMs: number;\n readonly minimumIntervalMs: number;\n readonly detailMaxBytes: number;\n}\n\nexport interface ActivityRouteDeps extends DeviceRouteDeps {\n readonly bounds: ActivityBounds;\n}\n\nconst PresenceBodySchema = z.object({\n level: z.enum(PRESENCE_LEVELS),\n detail: z.string().optional(),\n configuredToolsets: ConfiguredToolsetsSchema.optional(),\n});\n\nexport function presencePublishHandler(deps: PresenceRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const parsed = PresenceBodySchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'invalid presence body' }, 400);\n if (\n parsed.data.detail !== undefined &&\n new TextEncoder().encode(parsed.data.detail).length > deps.detailMaxBytes\n ) {\n return c.json({ error: 'presence detail too large' }, 413);\n }\n try {\n return c.json(\n await authenticated.stores.presence.publish({\n deviceId: authenticated.device.deviceId,\n level: parsed.data.level,\n ...(parsed.data.detail === undefined ? {} : { detail: parsed.data.detail }),\n ...(parsed.data.configuredToolsets === undefined\n ? {}\n : { configuredToolsets: parsed.data.configuredToolsets }),\n ttlMs: deps.ttlMs,\n minimumIntervalMs: deps.minimumIntervalMs,\n }),\n 200,\n );\n } catch (caught) {\n if (isCoreError(caught, 'hint_rate_limited')) {\n return c.json({ error: caught.code }, 429);\n }\n throw caught;\n }\n };\n}\n\nexport function activityAppendHandler(deps: ActivityRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const parsed = ActivityAppendRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'invalid activity body' }, 400);\n try {\n return c.json(\n await appendActivityEvents(authenticated.stores.activity, parsed.data, deps.bounds),\n 200,\n );\n } catch (caught) {\n if (isCloudError(caught, 'activity_batch_too_large')) {\n return c.json({ error: caught.code }, 413);\n }\n if (isCloudError(caught, 'coordination_input_invalid')) {\n return c.json({ error: caught.code }, 400);\n }\n throw caught;\n }\n };\n}\n","/**\n * `GET /byok/skill-packs` and `GET /byok/skill-packs/:name/files/:path` — the\n * hosted half of the skill-pack delivery channel.\n *\n * Two device-class reads, and nothing else. There is no publish route here on\n * purpose: a device is a CONSUMER of packs, and a device-bearer-authed write\n * would let any paired device in a tenant publish content to every other device\n * in it. Publication is a host control-plane action against the store directly,\n * exactly as board item creation is.\n *\n * Both routes answer 404 for a pack this tenant does not have — the same answer\n * a name that never existed anywhere gets — so the surface is not a\n * cross-tenant existence oracle. The store is tenant-first, so that property\n * comes from the lookup key rather than from a comparison a handler could\n * forget.\n *\n * Bytes travel as UTF-8 text inside JSON. A pack carries Markdown, YAML and\n * static text; there is no archive to unpack and no binary channel to\n * negotiate, which is the same reason the manifest has no exec surface — the\n * format cannot express the thing we do not want it to express.\n */\nimport { principalTenant, type SkillPackStore } from '@byok-sdk/core';\nimport type { Context } from 'hono';\nimport { authenticateBearer, type BearerAuthDeps } from '../auth/bearer';\n\n/** Rows per `GET /byok/skill-packs` response. A tenant's pack catalogue is small by design. */\nexport const DEFAULT_SKILL_PACK_PAGE_LIMIT = 50;\n\nexport interface SkillPackRouteDeps {\n readonly bearer: BearerAuthDeps;\n readonly skillPacks: SkillPackStore;\n readonly pageLimit: number;\n}\n\nexport function skillPackListHandler(deps: SkillPackRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const device = await authenticateBearer(c.req.header('authorization'), deps.bearer);\n if (device === undefined) return unauthorized(c);\n\n const packs = await deps.skillPacks.list(principalTenant(device), { limit: deps.pageLimit });\n return c.json({ packs }, 200);\n };\n}\n\nexport function skillPackFileHandler(deps: SkillPackRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const device = await authenticateBearer(c.req.header('authorization'), deps.bearer);\n if (device === undefined) return unauthorized(c);\n\n const name = c.req.param('name');\n const path = c.req.param('path');\n if (name === undefined || path === undefined) return notFound(c);\n\n // No path normalization, no resolution, no decoding step of our own: the\n // store answers only for a path its own manifest declares, and those paths\n // passed core's path rule at publish time. A handler that \"cleaned up\" a\n // requested path would be inventing a second, weaker authority over what a\n // pack contains.\n const file = await deps.skillPacks.readFile(principalTenant(device), name, path);\n if (file === undefined) return notFound(c);\n return c.json(file, 200);\n };\n}\n\nfunction unauthorized(c: Context): Response {\n return c.json({ error: 'unauthorized' }, 401);\n}\n\nfunction notFound(c: Context): Response {\n return c.json({ error: 'skill_pack_not_found' }, 404);\n}\n","import {\n deviceProofSigningInput,\n isTenantId,\n parseDeviceProofEnvelope,\n tenantId,\n type Clock,\n type DevicePrincipal,\n type DeviceProofEnvelopeV1,\n} from '@byok-sdk/core';\nimport type { CloudCrypto } from '../crypto/port';\nimport type { DeviceDirectory } from '../stores/ports';\n\nexport const DEFAULT_DEVICE_PROOF_CLOCK_SKEW_MS = 60_000;\nexport const MAX_DEVICE_PROOF_CLOCK_SKEW_MS = 5 * 60_000;\nexport const DEFAULT_DEVICE_PROOF_MAX_LIFETIME_MS = 5 * 60_000;\nexport const MAX_DEVICE_PROOF_MAX_LIFETIME_MS = 15 * 60_000;\n\nexport interface DeviceProofRequestBinding {\n readonly method: string;\n readonly path: string;\n readonly operation: string;\n readonly resource: string;\n readonly body: Uint8Array;\n}\n\nexport interface DeviceProofAuthDeps {\n readonly devices: DeviceDirectory;\n readonly crypto: CloudCrypto;\n readonly clock: Clock;\n readonly clockSkewMs?: number;\n readonly maxLifetimeMs?: number;\n}\n\nexport interface AuthenticatedDeviceProof {\n /** Row-derived principal; no protected claim is re-used as authority. */\n readonly device: DevicePrincipal;\n readonly requestId: string;\n readonly operation: string;\n readonly resource: string;\n readonly bodySha256: string;\n readonly bodySize: bigint;\n readonly keyId: string;\n readonly keyEpoch: number;\n}\n\nfunction validBound(value: number, maximum: number): boolean {\n return Number.isSafeInteger(value) && value >= 0 && value <= maximum;\n}\n\nfunction parseInstant(value: string): number | undefined {\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction timeBindingIsValid(\n envelope: DeviceProofEnvelopeV1,\n now: number,\n clockSkewMs: number,\n maxLifetimeMs: number,\n): boolean {\n const issuedAt = parseInstant(envelope.protected.issuedAt);\n if (issuedAt === undefined) return false;\n if (issuedAt < now - clockSkewMs || issuedAt > now + clockSkewMs) return false;\n\n const expiry = envelope.protected.expiresAt;\n if (expiry === undefined) return true;\n const expiresAt = parseInstant(expiry);\n if (expiresAt === undefined || expiresAt < issuedAt) return false;\n if (expiresAt - issuedAt > maxLifetimeMs) return false;\n return now <= expiresAt + clockSkewMs;\n}\n\n/**\n * Authenticate a request-bound proof. Every rejected state is `undefined`, so\n * a route has one 401 response for malformed input, row misses, revocation,\n * stale epochs, binding changes, clock failures and bad signatures.\n */\nexport async function authenticateDeviceProof(\n input: unknown,\n request: DeviceProofRequestBinding,\n deps: DeviceProofAuthDeps,\n): Promise<AuthenticatedDeviceProof | undefined> {\n const clockSkewMs = deps.clockSkewMs ?? DEFAULT_DEVICE_PROOF_CLOCK_SKEW_MS;\n const maxLifetimeMs = deps.maxLifetimeMs ?? DEFAULT_DEVICE_PROOF_MAX_LIFETIME_MS;\n if (!validBound(clockSkewMs, MAX_DEVICE_PROOF_CLOCK_SKEW_MS)) return undefined;\n if (!validBound(maxLifetimeMs, MAX_DEVICE_PROOF_MAX_LIFETIME_MS)) return undefined;\n\n let envelope: DeviceProofEnvelopeV1;\n try {\n envelope = parseDeviceProofEnvelope(input);\n } catch {\n return undefined;\n }\n const claims = envelope.protected;\n\n if (claims.operation !== request.operation || claims.resource !== request.resource) {\n return undefined;\n }\n if (claims.operationId !== undefined) return undefined;\n if (claims.method !== request.method || claims.path !== request.path) return undefined;\n if (claims.bodySize !== request.body.byteLength) return undefined;\n if ((await deps.crypto.sha256(request.body)) !== claims.bodySha256) return undefined;\n\n if (!isTenantId(claims.tenantId)) return undefined;\n const row = await deps.devices.get(tenantId(claims.tenantId), claims.deviceId);\n if (row === undefined || row.revoked) return undefined;\n if (row.productId !== claims.productId) return undefined;\n if (row.proofKeyId !== claims.keyId || row.proofKeyEpoch !== claims.keyEpoch) {\n return undefined;\n }\n\n if (!timeBindingIsValid(envelope, deps.clock.now().getTime(), clockSkewMs, maxLifetimeMs)) {\n return undefined;\n }\n const verified = await deps.crypto.verifyEd25519(\n row.devicePublicKey,\n deviceProofSigningInput(claims),\n envelope.signature,\n );\n if (!verified) return undefined;\n\n return {\n device: {\n kind: 'device',\n tenantId: row.tenantId,\n productId: row.productId,\n deviceId: row.deviceId,\n },\n requestId: claims.requestId,\n operation: claims.operation,\n resource: claims.resource,\n bodySha256: claims.bodySha256,\n bodySize: BigInt(claims.bodySize),\n keyId: row.proofKeyId,\n keyEpoch: row.proofKeyEpoch,\n };\n}\n","import type {\n ContentHash,\n TenantId,\n TruthBodyRef,\n TruthManifestEntry,\n TruthManifestQuery,\n TruthRecord,\n TruthRecordKind,\n TruthRecordSelector,\n} from '@byok-sdk/core';\nimport { z } from 'zod';\n\nexport const TRUTH_RECORD_CAPABILITY = 'truth.records';\nexport const TRUTH_INLINE_CONTENT_TYPE = 'application/vnd.byok.truth+utf8';\nexport const TRUTH_REQUEST_ID_MAX_LENGTH = 120;\nexport const TRUTH_RECORD_KEY_MAX_LENGTH = 200;\nexport const TRUTH_LABEL_MAX_LENGTH = 200;\nexport const TRUTH_BATCH_MAX_RECORDS = 32;\nexport const TRUTH_MANIFEST_MAX_LIMIT = 100;\n\nconst CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\nconst RECORD_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;\n\nexport const TruthRecordKeySchema = z\n .string()\n .min(1)\n .max(TRUTH_RECORD_KEY_MAX_LENGTH)\n .regex(RECORD_KEY_PATTERN)\n .refine((value) => value !== '.' && value !== '..');\n\nexport const TruthBodyInputSchema = z.discriminatedUnion('kind', [\n z.strictObject({\n kind: z.literal('inline'),\n content: z.string(),\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n }),\n z.strictObject({\n kind: z.literal('object'),\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n byteSize: z.number().int().nonnegative().safe(),\n }),\n]);\n\nconst SnapshotCandidateSchema = z.strictObject({\n kind: z.enum(['profile', 'memory']),\n recordKey: TruthRecordKeySchema,\n expectedRev: z.number().int().nonnegative().safe(),\n body: TruthBodyInputSchema,\n label: z.string().max(TRUTH_LABEL_MAX_LENGTH).optional(),\n});\n\nexport const TruthWriteRequestSchema = z.strictObject({\n expectedRev: z.number().int().nonnegative().safe().optional(),\n body: TruthBodyInputSchema,\n label: z.string().max(TRUTH_LABEL_MAX_LENGTH).optional(),\n snapshots: z.array(SnapshotCandidateSchema).max(TRUTH_BATCH_MAX_RECORDS - 1).optional(),\n});\n\nexport type TruthBodyInput = z.infer<typeof TruthBodyInputSchema>;\nexport type TruthWriteRequest = z.infer<typeof TruthWriteRequestSchema>;\n\nexport type PreparedTruthWrite =\n | {\n readonly kind: 'task.terminal';\n readonly recordKey: string;\n readonly contentHash: ContentHash;\n readonly byteSize: bigint;\n readonly body: TruthBodyRef;\n readonly label?: string;\n }\n | {\n readonly kind: 'profile' | 'memory';\n readonly recordKey: string;\n readonly expectedRev: number;\n readonly contentHash: ContentHash;\n readonly byteSize: bigint;\n readonly body: TruthBodyRef;\n readonly label?: string;\n };\n\nexport interface TruthCommitInput {\n readonly deviceId: string;\n readonly requestId: string;\n readonly operation: string;\n readonly resource: string;\n readonly proofBodySha256: string;\n readonly proofBodySize: bigint;\n readonly writes: readonly [PreparedTruthWrite, ...PreparedTruthWrite[]];\n}\n\nexport interface TruthRecordMetadata {\n readonly kind: TruthRecordKind;\n readonly recordKey: string;\n readonly rev: number;\n readonly contentHash: string;\n readonly byteSize: number;\n readonly label?: string;\n readonly updatedAt: string;\n}\n\nexport const TruthRecordMetadataSchema = z.strictObject({\n kind: z.enum(['task.terminal', 'profile', 'memory']),\n recordKey: TruthRecordKeySchema,\n rev: z.number().int().positive().safe(),\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n byteSize: z.number().int().nonnegative().safe(),\n label: z.string().max(TRUTH_LABEL_MAX_LENGTH).optional(),\n updatedAt: z.string().datetime({ offset: true }),\n});\n\nexport interface TruthCommitResponse {\n readonly primary: TruthRecordMetadata;\n readonly snapshots: readonly TruthRecordMetadata[];\n}\n\nexport const TruthCommitResponseSchema = z.strictObject({\n primary: TruthRecordMetadataSchema,\n snapshots: z.array(TruthRecordMetadataSchema).max(TRUTH_BATCH_MAX_RECORDS - 1),\n});\n\nexport interface TruthCommitResult {\n readonly response: TruthCommitResponse;\n readonly replayed: boolean;\n}\n\nexport interface TruthCommitter {\n commit(tenant: TenantId, input: TruthCommitInput): Promise<TruthCommitResult>;\n getRecord(tenant: TenantId, selector: TruthRecordSelector): Promise<TruthRecord | undefined>;\n listManifest(\n tenant: TenantId,\n query: TruthManifestQuery,\n ): Promise<readonly TruthManifestEntry[]>;\n}\n\n/**\n * Object download grant authority for truth bodies. The input is the canonical\n * content hash stored in `TruthBodyRef`, never an opaque upload id.\n */\nexport interface TruthObjectDownloads {\n getDownloadUrl(tenant: TenantId, hash: ContentHash): Promise<string | undefined>;\n}\n\nexport function truthRecordMetadata(record: TruthRecord): TruthRecordMetadata {\n const byteSize = Number(record.byteSize);\n if (!Number.isSafeInteger(byteSize)) throw new Error('truth record byte size exceeds JSON range');\n return {\n kind: record.kind,\n recordKey: record.recordKey,\n rev: record.rev,\n contentHash: record.contentHash,\n byteSize,\n ...(record.label === undefined ? {} : { label: record.label }),\n updatedAt: record.writtenAt,\n };\n}\n\nexport function truthManifestMetadata(entry: TruthManifestEntry): TruthRecordMetadata {\n const byteSize = Number(entry.byteSize);\n if (!Number.isSafeInteger(byteSize)) throw new Error('truth manifest byte size exceeds JSON range');\n return {\n kind: entry.kind,\n recordKey: entry.recordKey,\n rev: entry.rev,\n contentHash: entry.contentHash,\n byteSize,\n ...(entry.label === undefined ? {} : { label: entry.label }),\n updatedAt: entry.updatedAt,\n };\n}\n","export const TRUTH_COMMIT_ERROR_CODES = [\n 'proof_request_conflict',\n 'truth_object_not_committed',\n] as const;\n\nexport type TruthCommitErrorCode = (typeof TRUTH_COMMIT_ERROR_CODES)[number];\n\nexport class TruthCommitError extends Error {\n readonly code: TruthCommitErrorCode;\n readonly current?: unknown;\n\n constructor(code: TruthCommitErrorCode, message: string, current?: unknown) {\n super(message);\n this.name = 'TruthCommitError';\n this.code = code;\n this.current = current;\n }\n}\n\nexport function isTruthCommitError(value: unknown): value is TruthCommitError {\n return value instanceof TruthCommitError;\n}\n","import {\n DEVICE_PROOF_HEADER,\n STORAGE_ERROR_CODES,\n STORAGE_ERROR_HTTP_STATUS,\n TRUTH_RECORD_KINDS,\n contentHash,\n isCoreConflictError,\n isCoreError,\n principalTenant,\n type DevicePrincipal,\n type StorageErrorCode,\n type TruthManifestQuery,\n type TruthRecord,\n type TruthRecordKind,\n} from '@byok-sdk/core';\nimport type { Context } from 'hono';\nimport { authenticateDeviceProof, type DeviceProofAuthDeps } from '../auth/device-proof';\nimport {\n TRUTH_MANIFEST_MAX_LIMIT,\n TruthRecordKeySchema,\n TruthWriteRequestSchema,\n truthManifestMetadata,\n truthRecordMetadata,\n type PreparedTruthWrite,\n type TruthBodyInput,\n type TruthCommitInput,\n type TruthCommitter,\n type TruthObjectDownloads,\n type TruthRecordMetadata,\n} from '../truth/contract';\nimport { isTruthCommitError } from '../truth/errors';\n\n// Re-exported from core (single source of truth for the wire header); still\n// part of this module's public surface for callers importing it from cloud.\nexport { DEVICE_PROOF_HEADER };\nexport const DEFAULT_MAX_TRUTH_REQUEST_BYTES = 2 * 1024 * 1024;\nexport const MAX_DEVICE_PROOF_HEADER_BYTES = 16 * 1024;\n\nconst EMPTY_BODY = new Uint8Array();\nconst RECORD_PREFIX_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;\n\nexport interface TruthRouteDeps {\n readonly proof: DeviceProofAuthDeps;\n readonly truth: TruthCommitter;\n readonly objectDownloads: TruthObjectDownloads;\n readonly maxRequestBytes: number;\n}\n\ninterface ProofContext {\n readonly device: DevicePrincipal;\n readonly requestId: string;\n readonly operation: string;\n readonly resource: string;\n readonly bodySha256: string;\n readonly bodySize: bigint;\n}\n\nexport function truthManifestHandler(deps: TruthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateTruthRequest(c, deps, {\n body: EMPTY_BODY,\n operation: 'truth.list',\n resource: 'records',\n });\n if (authenticated === undefined) return unauthorized(c);\n\n const query = manifestQuery(c);\n if (query === undefined) return c.json({ error: 'invalid truth manifest query' }, 400);\n const records = await deps.truth.listManifest(principalTenant(authenticated.device), query);\n return c.json({ records: records.map(truthManifestMetadata) }, 200);\n };\n}\n\nexport function truthGetHandler(deps: TruthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const resource = rawRecordResource(c);\n const authenticated = await authenticateTruthRequest(c, deps, {\n body: EMPTY_BODY,\n operation: 'truth.read',\n resource,\n });\n if (authenticated === undefined) return unauthorized(c);\n const selector = recordSelector(c);\n if (selector === undefined) return c.json({ error: 'invalid truth record selector' }, 400);\n\n const record = await deps.truth.getRecord(principalTenant(authenticated.device), selector);\n if (record === undefined) return c.json({ error: 'truth_record_not_found' }, 404);\n const metadata = truthRecordMetadata(record);\n if (record.body.kind === 'inline') {\n return c.json({ ...metadata, body: { kind: 'inline', content: record.body.body } }, 200);\n }\n\n const downloadUrl = await deps.objectDownloads.getDownloadUrl(\n principalTenant(authenticated.device),\n record.body.hash,\n );\n if (downloadUrl === undefined) return c.json({ error: 'object_not_found' }, 404);\n return c.json({ ...metadata, body: { kind: 'object', downloadUrl } }, 200);\n };\n}\n\nexport function truthPutHandler(deps: TruthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const body = await readBoundedBody(c, deps.maxRequestBytes);\n if (body === 'too_large') return c.json({ error: 'truth request body too large' }, 413);\n if (body === undefined) return c.json({ error: 'invalid truth request body' }, 400);\n\n const authenticated = await authenticateTruthRequest(c, deps, {\n body,\n operation: 'truth.write',\n resource: rawRecordResource(c),\n });\n if (authenticated === undefined) return unauthorized(c);\n const selector = recordSelector(c);\n if (selector === undefined) return c.json({ error: 'invalid truth record selector' }, 400);\n\n const parsedJson = parseJsonBytes(body);\n const parsed = TruthWriteRequestSchema.safeParse(parsedJson);\n if (!parsed.success) return c.json({ error: 'invalid truth write request' }, 400);\n const writes = prepareWrites(selector.kind, selector.recordKey, parsed.data);\n if (writes === undefined) return c.json({ error: 'invalid truth write model' }, 400);\n\n const input: TruthCommitInput = {\n deviceId: authenticated.device.deviceId,\n requestId: authenticated.requestId,\n operation: authenticated.operation,\n resource: authenticated.resource,\n proofBodySha256: authenticated.bodySha256,\n proofBodySize: authenticated.bodySize,\n writes,\n };\n try {\n const result = await deps.truth.commit(principalTenant(authenticated.device), input);\n return c.json(result.response, 200, { 'x-byok-replayed': result.replayed ? 'true' : 'false' });\n } catch (caught) {\n return truthFailure(c, caught);\n }\n };\n}\n\nfunction recordSelector(\n c: Context,\n): { readonly kind: TruthRecordKind; readonly recordKey: string } | undefined {\n const kind = c.req.param('kind');\n const recordKey = c.req.param('key');\n if (!TRUTH_RECORD_KINDS.includes(kind as TruthRecordKind)) return undefined;\n const parsedKey = TruthRecordKeySchema.safeParse(recordKey);\n if (!parsedKey.success) return undefined;\n return { kind: kind as TruthRecordKind, recordKey: parsedKey.data };\n}\n\nfunction rawRecordResource(c: Context): string {\n return `${c.req.param('kind') ?? ''}/${c.req.param('key') ?? ''}`;\n}\n\nfunction manifestQuery(c: Context): TruthManifestQuery | undefined {\n const url = new URL(c.req.url);\n for (const key of url.searchParams.keys()) {\n if (\n (key !== 'kind' && key !== 'prefix' && key !== 'limit') ||\n url.searchParams.getAll(key).length !== 1\n ) {\n return undefined;\n }\n }\n const kind = url.searchParams.get('kind') ?? undefined;\n if (kind !== undefined && !TRUTH_RECORD_KINDS.includes(kind as TruthRecordKind)) return undefined;\n const keyPrefix = url.searchParams.get('prefix') ?? undefined;\n if (\n keyPrefix !== undefined &&\n (keyPrefix.length === 0 || keyPrefix.length > 200 || !RECORD_PREFIX_PATTERN.test(keyPrefix))\n ) {\n return undefined;\n }\n const limitRaw = url.searchParams.get('limit') ?? undefined;\n const limit = limitRaw === undefined ? TRUTH_MANIFEST_MAX_LIMIT : Number(limitRaw);\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > TRUTH_MANIFEST_MAX_LIMIT) return undefined;\n return {\n ...(kind === undefined ? {} : { kind: kind as TruthRecordKind }),\n ...(keyPrefix === undefined ? {} : { keyPrefix }),\n limit,\n };\n}\n\nfunction prepareWrites(\n kind: TruthRecordKind,\n recordKey: string,\n request: ReturnType<typeof TruthWriteRequestSchema.parse>,\n): readonly [PreparedTruthWrite, ...PreparedTruthWrite[]] | undefined {\n if (kind === 'task.terminal') {\n if (request.expectedRev !== undefined) return undefined;\n } else if (request.expectedRev === undefined || request.snapshots !== undefined) {\n return undefined;\n }\n\n const primary = prepareWrite(kind, recordKey, request.body, request.expectedRev, request.label);\n const snapshots = (request.snapshots ?? []).map((snapshot) =>\n prepareWrite(\n snapshot.kind,\n snapshot.recordKey,\n snapshot.body,\n snapshot.expectedRev,\n snapshot.label,\n ),\n );\n return [primary, ...snapshots];\n}\n\nfunction prepareWrite(\n kind: TruthRecordKind,\n recordKey: string,\n input: TruthBodyInput,\n expectedRev: number | undefined,\n label: string | undefined,\n): PreparedTruthWrite {\n const hash = contentHash(input.contentHash);\n const body =\n input.kind === 'inline'\n ? ({ kind: 'inline', body: input.content } as const)\n : ({ kind: 'object', hash } as const);\n const byteSize =\n input.kind === 'inline'\n ? BigInt(new TextEncoder().encode(input.content).byteLength)\n : BigInt(input.byteSize);\n if (kind === 'task.terminal') {\n return { kind, recordKey, contentHash: hash, byteSize, body, ...(label === undefined ? {} : { label }) };\n }\n if (expectedRev === undefined) throw new Error('snapshot expectedRev was not validated');\n return {\n kind,\n recordKey,\n expectedRev,\n contentHash: hash,\n byteSize,\n body,\n ...(label === undefined ? {} : { label }),\n };\n}\n\nasync function authenticateTruthRequest(\n c: Context,\n deps: TruthRouteDeps,\n request: { readonly body: Uint8Array; readonly operation: string; readonly resource: string },\n): Promise<ProofContext | undefined> {\n const proof = decodeProofHeader(c.req.header(DEVICE_PROOF_HEADER));\n if (proof === undefined) return undefined;\n const url = new URL(c.req.url);\n return authenticateDeviceProof(\n proof,\n {\n method: c.req.method,\n path: `${url.pathname}${url.search}`,\n operation: request.operation,\n resource: request.resource,\n body: request.body,\n },\n deps.proof,\n );\n}\n\nfunction decodeProofHeader(value: string | undefined): unknown | undefined {\n if (value === undefined || value.length === 0 || value.length > MAX_DEVICE_PROOF_HEADER_BYTES) {\n return undefined;\n }\n if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1) return undefined;\n try {\n const padded = value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (value.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));\n return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));\n } catch {\n return undefined;\n }\n}\n\nasync function readBoundedBody(\n c: Context,\n maximum: number,\n): Promise<Uint8Array | 'too_large' | undefined> {\n const length = c.req.header('content-length');\n if (length !== undefined) {\n const parsed = Number(length);\n if (!Number.isSafeInteger(parsed) || parsed < 0) return undefined;\n if (parsed > maximum) return 'too_large';\n }\n try {\n const bytes = new Uint8Array(await c.req.arrayBuffer());\n return bytes.byteLength > maximum ? 'too_large' : bytes;\n } catch {\n return undefined;\n }\n}\n\nfunction parseJsonBytes(bytes: Uint8Array): unknown | undefined {\n try {\n return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));\n } catch {\n return undefined;\n }\n}\n\nfunction unauthorized(c: Context): Response {\n return c.json({ error: 'unauthorized' }, 401);\n}\n\nfunction truthFailure(c: Context, caught: unknown): Response {\n if (isCoreConflictError<TruthRecord | undefined>(caught)) {\n const current: TruthRecordMetadata | null =\n caught.current === undefined ? null : truthRecordMetadata(caught.current);\n return c.json({ error: caught.code, current, observedAt: caught.observedAt }, 409);\n }\n if (isTruthCommitError(caught)) {\n return c.json({ error: caught.code, ...(caught.current === undefined ? {} : { current: caught.current }) }, 409);\n }\n if (isCoreError(caught)) {\n if ((STORAGE_ERROR_CODES as readonly string[]).includes(caught.code)) {\n const code = caught.code as StorageErrorCode;\n return c.json({ error: code }, STORAGE_ERROR_HTTP_STATUS[code]);\n }\n if (caught.code === 'storage_entitlement_missing' || caught.code === 'object_state_invalid') {\n return c.json({ error: caught.code }, 409);\n }\n if (caught.code === 'content_hash_invalid') return c.json({ error: caught.code }, 400);\n }\n throw caught;\n}\n","/**\n * The route inventory (sprint I1).\n *\n * Isolation review starts by asking \"what routes exist, and what does each one\n * require?\" — a question that is only answerable if the answer cannot drift\n * from what is actually mounted. So mounting goes through {@link\n * CloudRouteRegistry.register} and nowhere else: the registry owns the Hono\n * app, hands out no reference to it that could be mounted on directly, and\n * records a class for every route as it goes.\n *\n * `src/__tests__/route-inventory.test.ts` closes that loop in BOTH directions\n * against Hono's own `app.routes` table: a mounted route missing from the\n * inventory fails the suite, and an inventoried route that never reached the\n * router fails it too. A route whose class is not one of {@link ROUTE_CLASSES}\n * cannot be registered at all.\n */\nimport { Hono, type Context } from 'hono';\n\n/**\n * What a route requires of its caller. Not a description of the handler's\n * work — a description of the credential it is authenticated by, which is the\n * thing an isolation review has to enumerate:\n *\n * - `device` — a bearer access token; resolves to a `DevicePrincipal` and a\n * tenant-closed facade.\n * - `proof` — a request-bound Ed25519 device proof; tenant/product/key\n * authority comes from the current device row, not protected claims.\n * - `presigned` — no principal at all; an HMAC signature over the resource id\n * plus an expiry IS the credential (§7's two `/content` routes).\n * - `public` — deliberately unauthenticated; must expose nothing tenant-scoped.\n */\nexport const ROUTE_CLASSES = ['device', 'proof', 'presigned', 'public'] as const;\nexport type RouteClass = (typeof ROUTE_CLASSES)[number];\n\nexport const ROUTE_METHODS = ['GET', 'POST', 'PUT'] as const;\nexport type RouteMethod = (typeof ROUTE_METHODS)[number];\n\nexport interface RouteDescriptor {\n readonly method: RouteMethod;\n readonly path: string;\n readonly class: RouteClass;\n}\n\nexport type CloudRouteHandler = (c: Context) => Response | Promise<Response>;\n\nexport function routeKey(route: { readonly method: string; readonly path: string }): string {\n return `${route.method} ${route.path}`;\n}\n\nexport class CloudRouteRegistry {\n readonly #app = new Hono();\n readonly #routes: RouteDescriptor[] = [];\n\n register(descriptor: RouteDescriptor, handler: CloudRouteHandler): void {\n if (!(ROUTE_CLASSES as readonly string[]).includes(descriptor.class)) {\n throw new Error(`Route ${routeKey(descriptor)} has no valid isolation class`);\n }\n if (!(ROUTE_METHODS as readonly string[]).includes(descriptor.method)) {\n throw new Error(`Route ${routeKey(descriptor)} uses an unsupported method`);\n }\n if (this.#routes.some((existing) => routeKey(existing) === routeKey(descriptor))) {\n throw new Error(`Route ${routeKey(descriptor)} is already registered`);\n }\n this.#routes.push(descriptor);\n this.#app.on(descriptor.method, descriptor.path, handler);\n }\n\n /** The inventory, in registration order. */\n get routes(): readonly RouteDescriptor[] {\n return this.#routes;\n }\n\n /** What the router actually mounted, read back off Hono itself — the other half of the I1 comparison. */\n get mounted(): readonly { readonly method: string; readonly path: string }[] {\n return this.#app.routes.map((route) => ({ method: route.method, path: route.path }));\n }\n\n get fetch(): (request: Request, ...rest: unknown[]) => Response | Promise<Response> {\n return this.#app.fetch as (request: Request, ...rest: unknown[]) => Response | Promise<Response>;\n }\n}\n","import { decodeEnvelope, type BlobRef, type Envelope } from '@byok-sdk/protocol';\nimport { ByokCloudError } from './errors';\nimport type { RequestReceipt } from './stores/ports';\n\n/**\n * The typed terminal read model — the hosted counterpart of the embedded\n * coordinator's `TaskResult`, projected off the receipt the inbound gate\n * stores. Every field is copied verbatim from the payload the gate already\n * zod-parsed before storing (`recordTerminal`, `inbound.ts`); this projection\n * neither re-validates nor synthesizes one.\n */\nexport interface TerminalResult {\n readonly taskId: string;\n readonly state: 'complete' | 'failed' | 'cancelled';\n readonly summary?: string;\n readonly sessionRef?: string;\n readonly artifactRefs?: readonly BlobRef[];\n /**\n * The product's structured terminal result, verbatim `task.complete.document`.\n * Absent — key missing, never null — when the daemon sent none, which covers\n * both a legacy pre-`result-document` build and a daemon with no\n * `resultDocument` extractor.\n */\n readonly document?: unknown;\n readonly reason?: string;\n readonly retryable?: boolean;\n /** When the receipt store wrote the terminal fact — the first one, by its own first-write-wins rule. */\n readonly recordedAt: string;\n}\n\n/**\n * Pure projection of a terminal receipt onto {@link TerminalResult}. `taskId`\n * names the task the receipt was read for (the receipt's key carries it, its\n * body does not); `recordedAt` is the receipt store's write time.\n *\n * Fail closed on anything but a terminal envelope: the stored body is\n * `encodeEnvelope` of what the inbound gate accepted, so an undecodable body\n * or a non-terminal type means the receipt-store contract itself broke — an\n * error, never a best-effort shape.\n */\nexport function projectTerminalResult(taskId: string, receipt: RequestReceipt): TerminalResult {\n let envelope: Envelope;\n try {\n envelope = decodeEnvelope(receipt.body);\n } catch (cause) {\n throw new ByokCloudError(\n 'terminal_receipt_unreadable',\n `The terminal receipt for task ${taskId} holds a body that is not a decodable envelope.`,\n { cause },\n );\n }\n switch (envelope.type) {\n case 'task.complete':\n return {\n taskId,\n state: 'complete',\n summary: envelope.payload.summary,\n sessionRef: envelope.payload.sessionRef,\n ...(envelope.payload.artifactRefs !== undefined\n ? { artifactRefs: envelope.payload.artifactRefs }\n : {}),\n ...(envelope.payload.document !== undefined ? { document: envelope.payload.document } : {}),\n recordedAt: receipt.recordedAt,\n };\n case 'task.fail':\n return {\n taskId,\n state: 'failed',\n reason: envelope.payload.reason,\n ...(envelope.payload.retryable !== undefined\n ? { retryable: envelope.payload.retryable }\n : {}),\n recordedAt: receipt.recordedAt,\n };\n case 'task.cancelled':\n return {\n taskId,\n state: 'cancelled',\n ...(envelope.payload.reason !== undefined ? { reason: envelope.payload.reason } : {}),\n recordedAt: receipt.recordedAt,\n };\n default:\n throw new ByokCloudError(\n 'terminal_receipt_unreadable',\n `The terminal receipt for task ${taskId} holds a ${envelope.type} envelope, which is not a terminal type.`,\n );\n }\n}\n","/**\n * `createByokCloud` — the hosted device surface, assembled.\n *\n * What this is NOT: an embedded coordinator. There is no `TaskHandle`, no\n * connection registry, no per-task object that a host holds onto. Sprint 0.1's\n * non-goal is explicit about that — the embedded `TaskHandle` must not become\n * the hosted API — so the host's control-plane input is a function\n * ({@link ByokCloud.enqueueOffer}) and its read model is a store query\n * ({@link ByokCloud.readTaskAttempt}).\n *\n * Every route is stateless in the strict sense: it resolves a principal from\n * the request, binds stores to that principal's tenant, and returns. Nothing\n * survives the response but what a store wrote. The one shape that would\n * quietly undo that — a Running/session map — is asserted absent by\n * `src/__tests__/constraints.test.ts`.\n */\nimport {\n contentHash,\n parseCapabilityDeclaration,\n type BoardItem,\n type BoardItemInput,\n type BoardListQuery,\n type BoardPage,\n type CapabilityDeclaration,\n type Clock,\n type ControlPlanePrincipal,\n type CoreStores,\n type PresenceHint,\n type SkillPackStore,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { ActivityTail } from './activity';\nimport type { ApprovalTimelineTail } from './approval-timeline';\nimport {\n BYOK_ACTIVITY_PATH,\n BYOK_BLOB_CONTENT_ROUTE,\n BYOK_BLOB_FINALIZE_ROUTE,\n BYOK_BLOB_URL_ROUTE,\n BYOK_BLOBS_PATH,\n BYOK_BOARD_CLAIM_ROUTE,\n BYOK_BOARD_PATH,\n BYOK_BOARD_STATUS_ROUTE,\n BYOK_BOARD_STREAM_PATH,\n BYOK_BOARD_UNCLAIM_ROUTE,\n BYOK_CAPABILITIES_PATH,\n BYOK_CHALLENGE_PATH,\n BYOK_EVENTS_PATH,\n BYOK_MESSAGES_PATH,\n BYOK_PAIR_PATH,\n BYOK_PRESENCE_PATH,\n BYOK_RECORD_ROUTE,\n BYOK_RECORDS_PATH,\n BYOK_SKILL_PACK_FILE_ROUTE,\n BYOK_SKILL_PACKS_PATH,\n BYOK_TOKEN_PATH,\n createEnvelope,\n decodeEnvelope,\n encodeEnvelope,\n type Envelope,\n type TaskOfferPayload,\n type TaskOfferWithToolsetsPayload,\n} from '@byok-sdk/protocol';\nimport { createAuthPlane, type AuthPlane } from './auth/plane';\nimport type { TokenSigner } from './auth/tokens';\nimport { CLOUD_CAPABILITIES, declares } from './capabilities';\nimport {\n assertBoardLabels,\n DEFAULT_ACTIVITY_CAPACITY,\n DEFAULT_ACTIVITY_MAX_BYTES,\n DEFAULT_ACTIVITY_MAX_EVENTS,\n DEFAULT_ACTIVITY_TTL_MS,\n DEFAULT_BOARD_CHANNEL_MAX_BYTES,\n DEFAULT_BOARD_TITLE_MAX_BYTES,\n DEFAULT_PRESENCE_DETAIL_MAX_BYTES,\n DEFAULT_PRESENCE_MINIMUM_INTERVAL_MS,\n DEFAULT_PRESENCE_TTL_MS,\n type ActivityBounds,\n} from './coordination';\nimport type { CloudCrypto } from './crypto/port';\nimport { ByokCloudError } from './errors';\nimport {\n blobDownloadContentHandler,\n blobDownloadUrlHandler,\n blobUploadContentHandler,\n createBlobHandler,\n finalizeBlobHandler,\n} from './handlers/blobs';\nimport { capabilitiesHandler } from './handlers/capabilities';\nimport { challengeHandler, pairHandler, tokenHandler } from './handlers/auth';\nimport { eventsHandler } from './handlers/events';\nimport { messagesHandler } from './handlers/messages';\nimport {\n boardClaimHandler,\n boardListHandler,\n boardStatusHandler,\n boardStreamHandler,\n boardUnclaimHandler,\n DEFAULT_BOARD_PAGE_LIMIT,\n DEFAULT_BOARD_STREAM_HEARTBEAT_INTERVAL_MS,\n DEFAULT_BOARD_STREAM_QUERY_INTERVAL_MS,\n DEFAULT_BOARD_STREAM_RECONCILIATION_INTERVAL_MS,\n} from './handlers/board';\nimport { activityAppendHandler, presencePublishHandler } from './handlers/presence';\nimport {\n DEFAULT_SKILL_PACK_PAGE_LIMIT,\n skillPackFileHandler,\n skillPackListHandler,\n} from './handlers/skill-packs';\nimport {\n DEFAULT_MAX_TRUTH_REQUEST_BYTES,\n truthGetHandler,\n truthManifestHandler,\n truthPutHandler,\n} from './handlers/truth';\nimport { CloudRouteRegistry, type RouteDescriptor } from './router/registry';\nimport { terminalReceiptKey } from './inbound';\nimport type {\n BlobContentProxy,\n CloudStores,\n DeviceRecord,\n PairingCodeInfo,\n RequestReceipt,\n TaskAttempt,\n} from './stores/ports';\nimport { projectTerminalResult, type TerminalResult } from './terminal-result';\nimport { tenantStoresFor, type CloudRootStores } from './tenant-stores';\nimport type { TruthCommitter, TruthObjectDownloads } from './truth/contract';\n\n/** Matches the reference server's ceiling (§7). */\nexport const DEFAULT_MAX_BLOB_SIZE_BYTES = 100 * 1024 * 1024;\n/** Matches the reference server's hold (§8). */\nexport const DEFAULT_LONG_POLL_HOLD_MS = 50_000;\n/** How often a held poll re-reads the mailbox. */\nexport const DEFAULT_LONG_POLL_INTERVAL_MS = 250;\n/** Rows per `GET /byok/events` response. */\nexport const DEFAULT_EVENTS_PAGE_LIMIT = 50;\n\nexport interface ByokCloudOptions {\n readonly core: CoreStores;\n readonly cloud: CloudStores;\n /**\n * Byte proxying for the two `/byok/blobs/:id/content` routes. OPTIONAL, and\n * absent is a first-class answer: a composition backed by object storage\n * hands the device a presigned URL to the object store and never carries a\n * byte, so it has nothing to supply here. Supplying it is necessary but not\n * sufficient for the routes to exist — the deployment must also declare\n * `blobs.contentproxy` (ADR-010).\n */\n readonly blobContentProxy?: BlobContentProxy;\n /** Atomic proof receipt + truth/reference/accounting authority for S6 routes. */\n readonly truthCommitter?: TruthCommitter;\n /** Content-hash keyed object GET grants for object-backed truth bodies. */\n readonly truthObjectDownloads?: TruthObjectDownloads;\n /**\n * Tenant-scoped skill pack catalogue. OPTIONAL, and absent is a first-class\n * answer: a deployment that distributes no declarative content supplies\n * nothing here and declares no `skills.pack`. Supplying it is necessary but\n * not sufficient for the routes to exist — the deployment must also declare\n * the capability (ADR-010), the same asymmetry the byte proxy above has.\n */\n readonly skillPacks?: SkillPackStore;\n readonly crypto: CloudCrypto;\n readonly tokenSigner: TokenSigner;\n readonly clock: Clock;\n /** What this deployment serves (ADR-010). Routes are mounted from it, so it can never over-declare. */\n readonly capabilities: CapabilityDeclaration;\n /** Recorded on the control-plane principal every host-side call is made under. */\n readonly operatorId?: string;\n readonly maxBlobSizeBytes?: number;\n readonly longPollHoldMs?: number;\n readonly longPollIntervalMs?: number;\n readonly eventsPageLimit?: number;\n readonly accessTokenTtlSeconds?: number;\n readonly boardPageLimit?: number;\n readonly boardStreamQueryIntervalMs?: number;\n readonly boardStreamHeartbeatIntervalMs?: number;\n readonly boardStreamReconciliationIntervalMs?: number;\n readonly boardChannelMaxBytes?: number;\n readonly boardTitleMaxBytes?: number;\n readonly presenceTtlMs?: number;\n readonly presenceMinimumIntervalMs?: number;\n readonly presenceDetailMaxBytes?: number;\n readonly activityMaxEvents?: number;\n readonly activityMaxBytes?: number;\n readonly activityCapacity?: number;\n readonly activityTtlMs?: number;\n readonly maxTruthRequestBytes?: number;\n readonly skillPackPageLimit?: number;\n}\n\nexport interface EnqueueOfferInput {\n /** Supply one to make the enqueue addressable by the host's own id; otherwise cloud mints one. */\n readonly taskId?: string;\n readonly payload: TaskOfferPayload;\n}\n\nexport interface EnqueueToolsetOfferInput {\n /** Supply one to make the enqueue addressable by the host's own id; otherwise cloud mints one. */\n readonly taskId?: string;\n /** Strict control payload containing logical ids only; executable MCP definitions are not part of this type. */\n readonly payload: TaskOfferWithToolsetsPayload;\n}\n\nexport interface EnqueuedOffer {\n readonly taskId: string;\n /** The per-(tenant, device) delivery seq — the daemon's redelivery cursor position for this envelope. */\n readonly seq: number;\n readonly envelope: Envelope;\n readonly attempt: TaskAttempt;\n}\n\nexport interface ByokCloud {\n /** WHATWG fetch handler — mount on `@hono/node-server`, a Worker, or Deno. */\n readonly fetch: (request: Request, ...rest: unknown[]) => Response | Promise<Response>;\n /** The I1 route inventory: every mounted route and the credential class it requires. */\n readonly routes: readonly RouteDescriptor[];\n /**\n * What the router ACTUALLY holds, read back off the router itself. Exposed\n * so the I1 matrix can close in both directions: an inventory is only\n * evidence if a route mounted some other way would show up here without a\n * matching entry in {@link routes}.\n */\n readonly mountedRoutes: readonly { readonly method: string; readonly path: string }[];\n readonly capabilities: CapabilityDeclaration;\n /** Host control plane: mint a single-use pairing code for a tenant/product. */\n createPairingCode(tenant: TenantId, input: { readonly productId: string; readonly ttlMs?: number }): Promise<PairingCodeInfo>;\n /** Host control plane: hand a device a frozen-v1 `task.offer`. The hosted replacement for `dispatch()` — a function, not a handle. */\n enqueueOffer(tenant: TenantId, deviceId: string, input: EnqueueOfferInput): Promise<EnqueuedOffer>;\n /** Host control plane: enqueue the additive fail-closed offer variant that requires local MCP toolsets. */\n enqueueToolsetOffer(tenant: TenantId, deviceId: string, input: EnqueueToolsetOfferInput): Promise<EnqueuedOffer>;\n readTaskAttempt(tenant: TenantId, taskId: string): Promise<TaskAttempt | undefined>;\n /** The recorded terminal for a task — the first one, re-encoded canonically under the frozen v1 codec (see `recordTerminal`, `inbound.ts`: the stored body is `encodeEnvelope` of the zod-parsed envelope, not the device's original byte sequence). */\n readTerminalReceipt(tenant: TenantId, taskId: string): Promise<RequestReceipt | undefined>;\n /**\n * Host control plane: the same first terminal, decoded into the typed read\n * model ({@link TerminalResult}) so a host reads result fields, not envelope\n * prose. `undefined` ONLY means no terminal fact is recorded yet:\n * first-terminal-wins is inherited from the receipt store\n * ({@link ByokCloud.readTerminalReceipt} reads the same row), and a declined\n * task records no terminal at all — use {@link ByokCloud.readTaskAttempt}\n * for that attempt status. An absent `document` covers both a legacy\n * pre-`result-document` daemon build and a daemon with no `resultDocument`\n * extractor; a receipt whose body is not a terminal envelope throws rather\n * than returning a best-effort shape.\n */\n readTaskResult(tenant: TenantId, taskId: string): Promise<TerminalResult | undefined>;\n listDevices(tenant: TenantId): Promise<readonly DeviceRecord[]>;\n revokeDevice(tenant: TenantId, deviceId: string): Promise<void>;\n /** Host control plane: create a board row from explicit producer labels. */\n createBoardItem(tenant: TenantId, input: BoardItemInput): Promise<BoardItem>;\n listBoardItems(tenant: TenantId, query: BoardListQuery): Promise<BoardPage>;\n /** Human review authority. Device routes cannot produce `done`. */\n acceptBoardItem(tenant: TenantId, itemId: string): Promise<BoardItem>;\n listPresence(tenant: TenantId): Promise<readonly PresenceHint[]>;\n readActivity(tenant: TenantId, taskId: string): Promise<ActivityTail | undefined>;\n readApprovalTimeline(\n tenant: TenantId,\n taskId: string,\n ): Promise<ApprovalTimelineTail | undefined>;\n}\n\nexport function createByokCloud(options: ByokCloudOptions): ByokCloud {\n const declaration = parseDeclaration(options.capabilities);\n assertNoOverDeclaration(\n declaration,\n options.blobContentProxy,\n options.truthCommitter,\n options.truthObjectDownloads,\n options.skillPacks,\n );\n const root: CloudRootStores = { core: options.core, cloud: options.cloud };\n const auth: AuthPlane = createAuthPlane({\n stores: options.cloud,\n crypto: options.crypto,\n clock: options.clock,\n tokenSigner: options.tokenSigner,\n ...(options.accessTokenTtlSeconds !== undefined\n ? { accessTokenTtlSeconds: options.accessTokenTtlSeconds }\n : {}),\n });\n\n const deviceRouteDeps = {\n root,\n bearer: { tokenSigner: options.tokenSigner, devices: options.cloud.devices },\n };\n\n const registry = new CloudRouteRegistry();\n const activityBounds: ActivityBounds = {\n maxEvents: options.activityMaxEvents ?? DEFAULT_ACTIVITY_MAX_EVENTS,\n maxBytes: options.activityMaxBytes ?? DEFAULT_ACTIVITY_MAX_BYTES,\n capacity: options.activityCapacity ?? DEFAULT_ACTIVITY_CAPACITY,\n ttlMs: options.activityTtlMs ?? DEFAULT_ACTIVITY_TTL_MS,\n };\n\n // Auth v2 (§6) — always mounted: without pairing there is no deployment.\n registry.register({ method: 'POST', path: BYOK_PAIR_PATH, class: 'public' }, pairHandler({ auth }));\n registry.register({ method: 'POST', path: BYOK_CHALLENGE_PATH, class: 'public' }, challengeHandler({ auth }));\n registry.register({ method: 'POST', path: BYOK_TOKEN_PATH, class: 'public' }, tokenHandler({ auth }));\n\n // ADR-010 — the declaration itself is always readable; a client that cannot\n // read it has no way to learn anything else without probing status codes.\n registry.register(\n { method: 'GET', path: BYOK_CAPABILITIES_PATH, class: 'public' },\n capabilitiesHandler({ declaration }),\n );\n\n if (declares(declaration, CLOUD_CAPABILITIES.eventsLongPoll)) {\n registry.register(\n { method: 'GET', path: BYOK_EVENTS_PATH, class: 'device' },\n eventsHandler({\n ...deviceRouteDeps,\n longPollHoldMs: options.longPollHoldMs ?? DEFAULT_LONG_POLL_HOLD_MS,\n longPollIntervalMs: options.longPollIntervalMs ?? DEFAULT_LONG_POLL_INTERVAL_MS,\n pageLimit: options.eventsPageLimit ?? DEFAULT_EVENTS_PAGE_LIMIT,\n }),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.messagesBatch)) {\n registry.register(\n { method: 'POST', path: BYOK_MESSAGES_PATH, class: 'device' },\n messagesHandler({ ...deviceRouteDeps, activityBounds }),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.boardCoordination)) {\n const boardDeps = {\n ...deviceRouteDeps,\n pageLimit: options.boardPageLimit ?? DEFAULT_BOARD_PAGE_LIMIT,\n };\n registry.register({ method: 'GET', path: BYOK_BOARD_PATH, class: 'device' }, boardListHandler(boardDeps));\n registry.register(\n { method: 'POST', path: BYOK_BOARD_CLAIM_ROUTE, class: 'device' },\n boardClaimHandler(deviceRouteDeps),\n );\n registry.register(\n { method: 'POST', path: BYOK_BOARD_UNCLAIM_ROUTE, class: 'device' },\n boardUnclaimHandler(deviceRouteDeps),\n );\n registry.register(\n { method: 'POST', path: BYOK_BOARD_STATUS_ROUTE, class: 'device' },\n boardStatusHandler(deviceRouteDeps),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.boardSse)) {\n registry.register(\n { method: 'GET', path: BYOK_BOARD_STREAM_PATH, class: 'device' },\n boardStreamHandler({\n ...deviceRouteDeps,\n pageLimit: options.boardPageLimit ?? DEFAULT_BOARD_PAGE_LIMIT,\n queryIntervalMs: options.boardStreamQueryIntervalMs ?? DEFAULT_BOARD_STREAM_QUERY_INTERVAL_MS,\n heartbeatIntervalMs:\n options.boardStreamHeartbeatIntervalMs ?? DEFAULT_BOARD_STREAM_HEARTBEAT_INTERVAL_MS,\n reconciliationIntervalMs:\n options.boardStreamReconciliationIntervalMs ??\n DEFAULT_BOARD_STREAM_RECONCILIATION_INTERVAL_MS,\n }),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.presenceHints)) {\n registry.register(\n { method: 'PUT', path: BYOK_PRESENCE_PATH, class: 'device' },\n presencePublishHandler({\n ...deviceRouteDeps,\n ttlMs: options.presenceTtlMs ?? DEFAULT_PRESENCE_TTL_MS,\n minimumIntervalMs:\n options.presenceMinimumIntervalMs ?? DEFAULT_PRESENCE_MINIMUM_INTERVAL_MS,\n detailMaxBytes: options.presenceDetailMaxBytes ?? DEFAULT_PRESENCE_DETAIL_MAX_BYTES,\n }),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.activityTail)) {\n registry.register(\n { method: 'POST', path: BYOK_ACTIVITY_PATH, class: 'device' },\n activityAppendHandler({ ...deviceRouteDeps, bounds: activityBounds }),\n );\n }\n\n const truthCommitter = options.truthCommitter;\n const truthObjectDownloads = options.truthObjectDownloads;\n if (\n truthCommitter !== undefined &&\n truthObjectDownloads !== undefined &&\n declares(declaration, CLOUD_CAPABILITIES.truthRecords)\n ) {\n const truthDeps = {\n proof: {\n devices: options.cloud.devices,\n crypto: options.crypto,\n clock: options.clock,\n },\n truth: truthCommitter,\n objectDownloads: truthObjectDownloads,\n maxRequestBytes: options.maxTruthRequestBytes ?? DEFAULT_MAX_TRUTH_REQUEST_BYTES,\n };\n registry.register(\n { method: 'GET', path: BYOK_RECORDS_PATH, class: 'proof' },\n truthManifestHandler(truthDeps),\n );\n registry.register(\n { method: 'GET', path: BYOK_RECORD_ROUTE, class: 'proof' },\n truthGetHandler(truthDeps),\n );\n registry.register(\n { method: 'PUT', path: BYOK_RECORD_ROUTE, class: 'proof' },\n truthPutHandler(truthDeps),\n );\n }\n\n // Skill packs: both conditions, same asymmetry as the byte proxy below.\n // Declared-without-a-store is fatal (above); supplied-without-a-declaration\n // is a silent no-mount, which is how a deployment rolls the channel out or\n // back without ever telling a client something false.\n const skillPacks = options.skillPacks;\n if (skillPacks !== undefined && declares(declaration, CLOUD_CAPABILITIES.skillPacks)) {\n const skillPackDeps = {\n bearer: deviceRouteDeps.bearer,\n skillPacks,\n pageLimit: options.skillPackPageLimit ?? DEFAULT_SKILL_PACK_PAGE_LIMIT,\n };\n registry.register(\n { method: 'GET', path: BYOK_SKILL_PACKS_PATH, class: 'device' },\n skillPackListHandler(skillPackDeps),\n );\n registry.register(\n { method: 'GET', path: BYOK_SKILL_PACK_FILE_ROUTE, class: 'device' },\n skillPackFileHandler(skillPackDeps),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.blobsPresigned)) {\n const blobDeps = {\n ...deviceRouteDeps,\n maxBlobSizeBytes: options.maxBlobSizeBytes ?? DEFAULT_MAX_BLOB_SIZE_BYTES,\n };\n registry.register({ method: 'POST', path: BYOK_BLOBS_PATH, class: 'device' }, createBlobHandler(blobDeps));\n registry.register({ method: 'POST', path: BYOK_BLOB_FINALIZE_ROUTE, class: 'device' }, finalizeBlobHandler(blobDeps));\n registry.register({ method: 'GET', path: BYOK_BLOB_URL_ROUTE, class: 'device' }, blobDownloadUrlHandler(blobDeps));\n }\n\n // Byte proxying: BOTH conditions, and neither is inferred from the other.\n // There is no third state: a composition either carries bytes or it does not.\n //\n // The two halves fail differently, and the asymmetry is the point.\n //\n // DECLARED WITHOUT A PROXY is fatal, above. A declaration is the ONE thing a\n // client is entitled to trust without probing (ADR-010), so a deployment\n // publishing `blobs.contentproxy` it cannot serve does not degrade to \"two\n // missing routes\" — it tells every client something false and then answers\n // 404 to the client that believed it. Not mounting the routes is what an\n // honest composition does with a capability it lacks; the dishonesty is in\n // still announcing it, and the announcement is unconditional.\n //\n // SUPPLIED WITHOUT A DECLARATION is not fatal, and stays a silent no-mount.\n // The deployment's declaration is then merely narrower than its parts, which\n // is how a capability gets rolled out or rolled back: a host with a proxy\n // wired up but the capability withheld serves exactly what it declares. The\n // client is told less than the truth, never more, and no route exists that a\n // client could only discover by probing.\n const contentProxy = options.blobContentProxy;\n if (contentProxy !== undefined && declares(declaration, CLOUD_CAPABILITIES.blobsContentProxy)) {\n const contentDeps = { contentProxy };\n registry.register(\n { method: 'PUT', path: BYOK_BLOB_CONTENT_ROUTE, class: 'presigned' },\n blobUploadContentHandler(contentDeps),\n );\n registry.register(\n { method: 'GET', path: BYOK_BLOB_CONTENT_ROUTE, class: 'presigned' },\n blobDownloadContentHandler(contentDeps),\n );\n }\n\n // Task approval is deliberately absent, exactly as it is on the reference\n // server: every route above is authenticated by a DEVICE's own credential,\n // and a device-bearer-authed approval route would let any validly paired\n // device approve any task in its tenant. Approval is an operator action and\n // belongs to the host's own control-plane surface.\n\n const operatorId = options.operatorId ?? 'host';\n\n function controlPlane(tenant: TenantId): ControlPlanePrincipal {\n return { kind: 'control-plane', tenantId: tenant, operatorId };\n }\n\n async function enqueueTaskEnvelope(\n tenant: TenantId,\n deviceId: string,\n requestedTaskId: string | undefined,\n buildEnvelope: (taskId: string, seq: number, messageId: string) => Envelope,\n ): Promise<EnqueuedOffer> {\n const stores = tenantStoresFor(controlPlane(tenant), root);\n const taskId = requestedTaskId ?? `task_${options.crypto.randomUuid()}`;\n const messageId = options.crypto.randomUuid();\n\n const message = await stores.mailbox.append({\n deviceId,\n messageId,\n materialize: async (seq) => {\n // Core stays protocol-free: the mailbox reserves the one authoritative\n // delivery number, then asks this producer to build opaque bytes while\n // allocation and insertion are still serialized per device.\n const envelope = buildEnvelope(taskId, seq, messageId);\n const body = encodeEnvelope(envelope);\n const bytes = new TextEncoder().encode(body);\n return {\n body,\n bodyHash: contentHash(await options.crypto.sha256(bytes)),\n byteSize: BigInt(bytes.length),\n };\n },\n });\n const envelope = decodeEnvelope(message.body);\n if (envelope.seq !== message.seq) {\n throw new ByokCloudError(\n 'mailbox_seq_mismatch',\n `Mailbox stored offer seq ${String(envelope.seq)} at row ${message.seq}; the daemon's redelivery cursor would be wrong.`,\n );\n }\n\n const attempt = await stores.tasks.open({ taskId, deviceId });\n return { taskId, seq: message.seq, envelope, attempt };\n }\n\n return {\n fetch: registry.fetch,\n routes: registry.routes,\n mountedRoutes: registry.mounted,\n capabilities: declaration,\n\n createPairingCode(tenant, input) {\n return auth.createPairingCode(tenant, input);\n },\n\n async enqueueOffer(tenant, deviceId, input) {\n return enqueueTaskEnvelope(tenant, deviceId, input.taskId, (taskId, seq, messageId) =>\n createEnvelope('task.offer', input.payload, { id: messageId, taskId, seq }),\n );\n },\n\n async enqueueToolsetOffer(tenant, deviceId, input) {\n return enqueueTaskEnvelope(tenant, deviceId, input.taskId, (taskId, seq, messageId) =>\n createEnvelope('task.offer_with_toolsets', input.payload, { id: messageId, taskId, seq }),\n );\n },\n\n readTaskAttempt(tenant, taskId) {\n return tenantStoresFor(controlPlane(tenant), root).tasks.get(taskId);\n },\n\n readTerminalReceipt(tenant, taskId) {\n return tenantStoresFor(controlPlane(tenant), root).receipts.get(terminalReceiptKey(taskId));\n },\n\n async readTaskResult(tenant, taskId) {\n const receipt = await tenantStoresFor(controlPlane(tenant), root).receipts.get(\n terminalReceiptKey(taskId),\n );\n return receipt === undefined ? undefined : projectTerminalResult(taskId, receipt);\n },\n\n listDevices(tenant) {\n return tenantStoresFor(controlPlane(tenant), root).devices.list();\n },\n\n revokeDevice(tenant, deviceId) {\n return tenantStoresFor(controlPlane(tenant), root).devices.revoke(deviceId);\n },\n\n createBoardItem(tenant, input) {\n assertBoardLabels(input.channel, input.title, {\n channelMaxBytes: options.boardChannelMaxBytes ?? DEFAULT_BOARD_CHANNEL_MAX_BYTES,\n titleMaxBytes: options.boardTitleMaxBytes ?? DEFAULT_BOARD_TITLE_MAX_BYTES,\n });\n return tenantStoresFor(controlPlane(tenant), root).board.create(input);\n },\n\n listBoardItems(tenant, query) {\n return tenantStoresFor(controlPlane(tenant), root).board.list(query);\n },\n\n acceptBoardItem(tenant, itemId) {\n return tenantStoresFor(controlPlane(tenant), root).board.updateStatus({\n itemId,\n expectedStatus: 'in_review',\n status: 'done',\n });\n },\n\n listPresence(tenant) {\n return tenantStoresFor(controlPlane(tenant), root).presence.list();\n },\n\n readActivity(tenant, taskId) {\n return tenantStoresFor(controlPlane(tenant), root).activity.read(taskId);\n },\n\n readApprovalTimeline(tenant, taskId) {\n return tenantStoresFor(controlPlane(tenant), root).approvals.read(taskId);\n },\n };\n}\n\n/**\n * Fail closed on a declaration this composition's parts cannot back.\n *\n * Route mounting alone cannot enforce this: `GET /byok/capabilities` serves the\n * declaration verbatim and is mounted unconditionally, so a deployment that\n * declares `blobs.contentproxy` without a proxy publishes the capability and\n * 404s both routes. Refusing at construction is the only placement where the\n * deployment cannot exist in that state — the alternative, sanitizing the\n * declaration down to what got mounted, would make the running surface a second\n * authority over what the host said it was deploying.\n */\nfunction assertNoOverDeclaration(\n declaration: CapabilityDeclaration,\n contentProxy: BlobContentProxy | undefined,\n truthCommitter: TruthCommitter | undefined,\n truthObjectDownloads: TruthObjectDownloads | undefined,\n skillPacks: SkillPackStore | undefined,\n): void {\n if (\n declares(declaration, CLOUD_CAPABILITIES.boardSse) &&\n !declares(declaration, CLOUD_CAPABILITIES.boardCoordination)\n ) {\n throw new ByokCloudError(\n 'capability_over_declared',\n `${CLOUD_CAPABILITIES.boardSse} requires ${CLOUD_CAPABILITIES.boardCoordination}; without polling, reconciliation and declared fallback cannot be served.`,\n );\n }\n if (contentProxy === undefined && declares(declaration, CLOUD_CAPABILITIES.blobsContentProxy)) {\n throw new ByokCloudError(\n 'capability_over_declared',\n `This deployment declares ${CLOUD_CAPABILITIES.blobsContentProxy} but was given no BlobContentProxy, so both /byok/blobs/:id/content routes would be published and unserved.`,\n );\n }\n if (truthCommitter === undefined && declares(declaration, CLOUD_CAPABILITIES.truthRecords)) {\n throw new ByokCloudError(\n 'capability_over_declared',\n `This deployment declares ${CLOUD_CAPABILITIES.truthRecords} but was given no atomic TruthCommitter.`,\n );\n }\n if (truthObjectDownloads === undefined && declares(declaration, CLOUD_CAPABILITIES.truthRecords)) {\n throw new ByokCloudError(\n 'capability_over_declared',\n `This deployment declares ${CLOUD_CAPABILITIES.truthRecords} but was given no content-hash keyed TruthObjectDownloads authority.`,\n );\n }\n if (skillPacks === undefined && declares(declaration, CLOUD_CAPABILITIES.skillPacks)) {\n throw new ByokCloudError(\n 'capability_over_declared',\n `This deployment declares ${CLOUD_CAPABILITIES.skillPacks} but was given no SkillPackStore, so both /byok/skill-packs routes would be published and unserved.`,\n );\n }\n}\n\nfunction parseDeclaration(declaration: CapabilityDeclaration): CapabilityDeclaration {\n try {\n return parseCapabilityDeclaration(declaration);\n } catch (cause) {\n throw new ByokCloudError(\n 'capability_declaration_invalid',\n 'The capability declaration this deployment was configured with is not a valid ADR-010 declaration.',\n { cause },\n );\n }\n}\n","/**\n * The reference {@link InboundRateLimiter}: allow-all.\n *\n * S3a's job is to put the seam at gate position 0 — before the type-allow\n * check — not to invent a limiter policy. A hosted deployment's real budget\n * lives at its edge; when it arrives it plugs in here and the gate order does\n * not move.\n */\nimport type { TenantId } from '@byok-sdk/core';\nimport type { InboundRateLimiter } from '../ports';\n\nexport class AllowAllRateLimiter implements InboundRateLimiter {\n async consume(_tenant: TenantId, _deviceId: string): Promise<boolean> {\n return true;\n }\n}\n","/**\n * The in-memory blob pair: metadata and bytes in process memory, HMAC-signed\n * expiring URLs (docs/protocol.md §7).\n *\n * TWO objects, one shared record map, because the contract they satisfy is two\n * things: {@link CloudBlobStore} is the tenant-first port every composition\n * owes, and {@link BlobContentProxy} is the optional byte-carrying half. The\n * in-memory composition is the one that supplies both — it has nowhere else to\n * put bytes — which is why hosted-in-memory behavior is byte-for-byte what it\n * was before the split.\n *\n * They cannot be one object: the port's method inventory is contract data\n * (`CLOUD_PORT_METHODS`) and `@byok-sdk/conformance` asserts a composition's blob\n * store implements EXACTLY the two declared methods. An object carrying all\n * six would fail that assertion, which is the point — the suite is what keeps\n * the narrowed port narrow.\n *\n * The presigned URL form — `/byok/blobs/<id>/content?sig=&exp=` — is the\n * relative shape the daemon's blob client already resolves against its server\n * base, so a hosted deployment is indistinguishable from a self-hosted one on\n * this route too.\n *\n * Tenancy: `createUpload` records the owning tenant and reservation while\n * `observeUpload`/`getDownloadUrl` refuse any other, so the three bearer routes are\n * tenant-closed. The two `/content` routes are presigned by construction and\n * have no principal at all — the signature over the blob id IS the credential\n * (same posture as the reference server, §7).\n */\nimport { ByokCoreError, type Clock, type ContentHash, type ObjectStore, type StorageReservation, type TenantId } from '@byok-sdk/core';\nimport { byokBlobContentPath } from '@byok-sdk/protocol';\nimport type { CloudCrypto } from '../../crypto/port';\nimport type {\n BlobContent,\n BlobContentProxy,\n BlobObservation,\n BlobWriteResult,\n CloudBlobStore,\n} from '../ports';\n\n/** How long a presigned upload/download URL stays valid. */\nexport const BLOB_URL_TTL_MS = 15 * 60 * 1000;\n\nconst SIGNING_SECRET_BYTES = 32;\n\ninterface BlobRecord {\n readonly tenantId: TenantId;\n readonly reservationId: string;\n readonly contentHash: ContentHash;\n readonly byteSize: bigint;\n readonly contentType: string;\n uploaded: boolean;\n data?: Uint8Array;\n}\n\nexport interface InMemoryBlobStoreOptions {\n readonly urlTtlMs?: number;\n}\n\n/**\n * The state both halves read, and the only thing they share.\n *\n * Module-private on purpose: it is not a port, and nothing outside this file\n * should be able to reach a blob record without going through one of the two\n * contracts above.\n */\nclass InMemoryBlobRegistry {\n readonly blobs = new Map<string, BlobRecord>();\n readonly reservationBlobs = new Map<string, string>();\n readonly clock: Clock;\n readonly crypto: CloudCrypto;\n readonly secret: Uint8Array;\n readonly urlTtlMs: number;\n\n constructor(clock: Clock, crypto: CloudCrypto, options: InMemoryBlobStoreOptions) {\n this.clock = clock;\n this.crypto = crypto;\n this.secret = globalThis.crypto.getRandomValues(new Uint8Array(SIGNING_SECRET_BYTES));\n this.urlTtlMs = options.urlTtlMs ?? BLOB_URL_TTL_MS;\n }\n\n async signUrl(blobId: string, action: 'put' | 'get'): Promise<string> {\n const exp = this.clock.now().getTime() + this.urlTtlMs;\n const sig = await this.computeSig(blobId, action, exp);\n return `${byokBlobContentPath(blobId)}?sig=${sig}&exp=${exp}`;\n }\n\n computeSig(blobId: string, action: 'put' | 'get', exp: number): Promise<string> {\n return this.crypto.hmacSha256(this.secret, `${blobId}:${action}:${exp}`);\n }\n}\n\n/** The narrowed port: tenant-first grants, no bytes. */\nexport class InMemoryCloudBlobStore implements CloudBlobStore {\n readonly #registry: InMemoryBlobRegistry;\n readonly #objects: ObjectStore;\n\n constructor(registry: InMemoryBlobRegistry, objects: ObjectStore) {\n this.#registry = registry;\n this.#objects = objects;\n }\n\n async createUpload(tenant: TenantId, reservation: StorageReservation): Promise<{ blobId: string; uploadUrl: string }> {\n assertReservedObject(tenant, reservation);\n const reservationKey = `${tenant}\\u0000${reservation.reservationId}`;\n const existingBlobId = this.#registry.reservationBlobs.get(reservationKey);\n if (existingBlobId !== undefined) {\n const manifest = await this.#objects.get(tenant, reservation.contentHash);\n if (manifest?.state === 'committed') {\n throw new ByokCoreError(\n 'object_state_invalid',\n `Object ${reservation.contentHash} is already committed and immutable.`,\n );\n }\n return { blobId: existingBlobId, uploadUrl: await this.#registry.signUrl(existingBlobId, 'put') };\n }\n\n const entry = await this.#objects.putManifest(tenant, {\n hash: reservation.contentHash,\n byteSize: reservation.expectedBytes,\n contentType: reservation.contentType,\n });\n if (\n entry.byteSize !== reservation.expectedBytes ||\n entry.contentType !== reservation.contentType\n ) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Object ${reservation.contentHash} already binds a different storage declaration.`,\n );\n }\n if (entry.state === 'committed') {\n throw new ByokCoreError(\n 'object_state_invalid',\n `Object ${reservation.contentHash} is already committed and immutable.`,\n );\n }\n\n const blobId = `blob_${this.#registry.crypto.randomUuid()}`;\n this.#registry.blobs.set(blobId, {\n tenantId: tenant,\n reservationId: reservation.reservationId,\n contentHash: reservation.contentHash,\n byteSize: reservation.expectedBytes,\n contentType: reservation.contentType,\n uploaded: false,\n });\n this.#registry.reservationBlobs.set(reservationKey, blobId);\n return { blobId, uploadUrl: await this.#registry.signUrl(blobId, 'put') };\n }\n\n async observeUpload(\n tenant: TenantId,\n blobId: string,\n reservation: StorageReservation,\n ): Promise<BlobObservation | undefined> {\n const record = this.#registry.blobs.get(blobId);\n if (\n record === undefined ||\n record.tenantId !== tenant ||\n reservation.tenantId !== tenant ||\n record.reservationId !== reservation.reservationId ||\n record.contentHash !== reservation.contentHash ||\n !record.uploaded\n ) {\n return undefined;\n }\n return {\n observedByteSize: BigInt(record.data?.length ?? 0),\n observedContentType: record.contentType,\n };\n }\n\n async getDownloadUrl(tenant: TenantId, blobId: string): Promise<string | undefined> {\n const record = this.#registry.blobs.get(blobId);\n // Another tenant's blob and a blob that does not exist answer identically.\n if (record === undefined || record.tenantId !== tenant || !record.uploaded) return undefined;\n const manifest = await this.#objects.get(tenant, record.contentHash);\n if (manifest?.state !== 'committed') return undefined;\n return this.#registry.signUrl(blobId, 'get');\n }\n}\n\n/** The optional half: the bytes this composition has nowhere else to put. */\nexport class InMemoryBlobContentProxy implements BlobContentProxy {\n readonly #registry: InMemoryBlobRegistry;\n\n constructor(registry: InMemoryBlobRegistry) {\n this.#registry = registry;\n }\n\n async verifySignedUrl(blobId: string, action: 'put' | 'get', sig: string, exp: number): Promise<boolean> {\n if (!Number.isFinite(exp) || this.#registry.clock.now().getTime() > exp) return false;\n const expected = await this.#registry.computeSig(blobId, action, exp);\n return this.#registry.crypto.timingSafeEqual(expected, sig);\n }\n\n async writeContent(blobId: string, data: Uint8Array): Promise<BlobWriteResult> {\n const record = this.#registry.blobs.get(blobId);\n if (record === undefined) return { ok: false, reason: 'unknown blobId' };\n if (BigInt(data.length) !== record.byteSize) {\n return { ok: false, reason: `size mismatch: declared ${String(record.byteSize)}, received ${data.length}` };\n }\n const actualHash = await this.#registry.crypto.sha256(data);\n if (actualHash !== record.contentHash) {\n return { ok: false, reason: 'contentHash mismatch' };\n }\n record.data = data;\n record.uploaded = true;\n return { ok: true };\n }\n\n async readContent(blobId: string): Promise<BlobContent | undefined> {\n const record = this.#registry.blobs.get(blobId);\n if (record === undefined || !record.uploaded || record.data === undefined) return undefined;\n return { data: record.data, contentType: record.contentType };\n }\n}\n\n/** Both halves over one registry. The only way to obtain either. */\nexport interface InMemoryBlobs {\n readonly blobs: CloudBlobStore;\n readonly contentProxy: BlobContentProxy;\n}\n\nexport function createInMemoryBlobs(\n clock: Clock,\n crypto: CloudCrypto,\n objects: ObjectStore,\n options: InMemoryBlobStoreOptions = {},\n): InMemoryBlobs {\n const registry = new InMemoryBlobRegistry(clock, crypto, options);\n return {\n blobs: new InMemoryCloudBlobStore(registry, objects),\n contentProxy: new InMemoryBlobContentProxy(registry),\n };\n}\n\nfunction assertReservedObject(tenant: TenantId, reservation: StorageReservation): void {\n if (\n reservation.tenantId === tenant &&\n reservation.kind === 'object' &&\n reservation.state === 'reserved' &&\n reservation.expectedBytes >= 0n\n ) {\n return;\n }\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n 'An upload grant requires a reserved object reservation owned by this tenant.',\n );\n}\n","/**\n * In-memory {@link DeviceDirectory}.\n *\n * Rows live under a `(tenant, deviceId)` composite key, so a cross-tenant read\n * is not \"denied\" — it addresses a different key space and finds nothing\n * (§12.6.2 layer 3). The pre-tenant index below holds the SAME record objects,\n * so a revocation applied through the composite key is immediately visible to\n * `/byok/challenge` and `/byok/token` with no second copy to keep in sync.\n */\nimport { tenantKey, type TenantId } from '@byok-sdk/core';\nimport type { DeviceDirectory, DeviceRecord, DeviceRegistration } from '../ports';\n\nexport class InMemoryDeviceDirectory implements DeviceDirectory {\n readonly #byTenant = new Map<string, DeviceRecord>();\n readonly #byDeviceId = new Map<string, string>();\n\n async register(tenant: TenantId, input: DeviceRegistration): Promise<DeviceRecord> {\n const record: DeviceRecord = {\n tenantId: tenant,\n productId: input.productId,\n deviceId: input.deviceId,\n deviceName: input.deviceName,\n devicePublicKey: input.devicePublicKey,\n proofKeyId: input.proofKeyId,\n proofKeyEpoch: input.proofKeyEpoch,\n revoked: false,\n };\n const key = tenantKey(tenant, record.deviceId);\n this.#byTenant.set(key, record);\n this.#byDeviceId.set(record.deviceId, key);\n return record;\n }\n\n async get(tenant: TenantId, deviceId: string): Promise<DeviceRecord | undefined> {\n return this.#byTenant.get(tenantKey(tenant, deviceId));\n }\n\n async revoke(tenant: TenantId, deviceId: string): Promise<void> {\n const key = tenantKey(tenant, deviceId);\n const record = this.#byTenant.get(key);\n if (record === undefined) return;\n this.#byTenant.set(key, { ...record, revoked: true });\n }\n\n async list(tenant: TenantId): Promise<readonly DeviceRecord[]> {\n const prefix = tenantKey(tenant, '');\n return [...this.#byTenant.entries()]\n .filter(([key]) => key.startsWith(prefix))\n .map(([, record]) => record);\n }\n\n async resolveByDeviceId(deviceId: string): Promise<DeviceRecord | undefined> {\n const key = this.#byDeviceId.get(deviceId);\n return key === undefined ? undefined : this.#byTenant.get(key);\n }\n}\n","/**\n * In-memory {@link InboundDedupStore} (N3).\n *\n * A bounded ring per (tenant, device), not an unbounded set: the wire is\n * at-least-once (§9), so this makes processing at-most-once without letting a\n * chatty device grow memory without limit. Check-and-record is one call, so a\n * composition cannot accidentally split it into a racy read-then-write.\n */\nimport { tenantKey, type TenantId } from '@byok-sdk/core';\nimport type { InboundDedupStore } from '../ports';\n\n/** Ids retained per device. Same order of magnitude as the reference server's ring. */\nexport const DEDUP_RING_CAPACITY = 1024;\n\nexport class InMemoryInboundDedupStore implements InboundDedupStore {\n readonly #rings = new Map<string, Set<string>>();\n readonly #capacity: number;\n\n constructor(capacity: number = DEDUP_RING_CAPACITY) {\n this.#capacity = capacity;\n }\n\n async checkAndRecord(tenant: TenantId, deviceId: string, envelopeId: string): Promise<boolean> {\n const key = tenantKey(tenant, deviceId);\n let ring = this.#rings.get(key);\n if (ring === undefined) {\n ring = new Set<string>();\n this.#rings.set(key, ring);\n }\n if (ring.has(envelopeId)) return true;\n ring.add(envelopeId);\n if (ring.size > this.#capacity) {\n const oldest = ring.values().next().value;\n if (oldest !== undefined) ring.delete(oldest);\n }\n return false;\n }\n}\n","/**\n * In-memory {@link NonceStore}: single-use challenge nonces, ~5min TTL\n * (docs/protocol.md §6.2).\n *\n * A nonce is bound to the (tenant, device) it was issued for, so a nonce\n * issued to one tenant's device is not validatable by another's even if the\n * value leaks.\n */\nimport { tenantKey, type Clock, type TenantId } from '@byok-sdk/core';\nimport type { CloudCrypto } from '../../crypto/port';\nimport type { NonceStore } from '../ports';\n\n/** ~5min, matching the reference server (docs/protocol.md §6.2). */\nexport const NONCE_TTL_MS = 5 * 60 * 1000;\n\nconst NONCE_BYTES = 24;\n\ninterface NonceRecord {\n readonly owner: string;\n readonly expiresAtMs: number;\n used: boolean;\n}\n\nexport class InMemoryNonceStore implements NonceStore {\n readonly #nonces = new Map<string, NonceRecord>();\n readonly #clock: Clock;\n readonly #crypto: CloudCrypto;\n readonly #ttlMs: number;\n\n constructor(clock: Clock, crypto: CloudCrypto, ttlMs: number = NONCE_TTL_MS) {\n this.#clock = clock;\n this.#crypto = crypto;\n this.#ttlMs = ttlMs;\n }\n\n /** Number of records currently held (post-sweep). Test-facing only. */\n get size(): number {\n return this.#nonces.size;\n }\n\n async issue(tenant: TenantId, deviceId: string): Promise<string> {\n const nowMs = this.#clock.now().getTime();\n // A long-lived deployment never calls a sweep on a timer, so issue sweeps\n // inline — same posture as the reference server's `NonceStore`.\n for (const [nonce, record] of this.#nonces) {\n if (record.used || record.expiresAtMs <= nowMs) this.#nonces.delete(nonce);\n }\n const nonce = this.#crypto.randomToken(NONCE_BYTES);\n this.#nonces.set(nonce, {\n owner: tenantKey(tenant, deviceId),\n expiresAtMs: nowMs + this.#ttlMs,\n used: false,\n });\n return nonce;\n }\n\n async validate(tenant: TenantId, deviceId: string, nonce: string): Promise<boolean> {\n const record = this.#nonces.get(nonce);\n if (record === undefined) return false;\n if (record.used) return false;\n if (record.owner !== tenantKey(tenant, deviceId)) return false;\n return this.#clock.now().getTime() <= record.expiresAtMs;\n }\n\n async markUsed(tenant: TenantId, nonce: string): Promise<void> {\n const record = this.#nonces.get(nonce);\n if (record === undefined) return;\n if (!record.owner.startsWith(tenantKey(tenant, ''))) return;\n record.used = true;\n }\n}\n","/**\n * In-memory {@link PairingCodeStore}: single-use codes bound to the tenant and\n * product they were minted for.\n *\n * `redeem` answers `undefined` for unknown, expired, and already-used alike.\n * The reference server distinguishes those three in its 401 text; a hosted,\n * multi-tenant surface deliberately does not — the code is a bearer credential\n * addressable across every tenant, and \"already used\" versus \"never existed\"\n * is exactly the difference an attacker enumerating codes would pay for.\n */\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type {\n PairingCodeClaims,\n PairingCodeInfo,\n PairingCodeIssueInput,\n PairingCodeStore,\n} from '../ports';\n\ninterface PairingCodeRecord {\n readonly claims: PairingCodeClaims;\n readonly expiresAtMs: number;\n used: boolean;\n}\n\nexport class InMemoryPairingCodeStore implements PairingCodeStore {\n readonly #codes = new Map<string, PairingCodeRecord>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async issue(tenant: TenantId, input: PairingCodeIssueInput): Promise<PairingCodeInfo> {\n this.#codes.set(input.code, {\n claims: { tenantId: tenant, productId: input.productId },\n expiresAtMs: new Date(input.expiresAt).getTime(),\n used: false,\n });\n return { code: input.code, expiresAt: input.expiresAt };\n }\n\n async redeem(code: string): Promise<PairingCodeClaims | undefined> {\n const record = this.#codes.get(code);\n if (record === undefined) return undefined;\n if (record.used) return undefined;\n if (this.#clock.now().getTime() > record.expiresAtMs) return undefined;\n record.used = true;\n return record.claims;\n }\n}\n","/**\n * In-memory {@link RequestReceiptStore}: first write wins.\n *\n * The terminal a device reports is a fact, and a retry of the same terminal\n * (the wire is at-least-once) must not overwrite the first one — `created:\n * false` is how the caller learns it was a replay rather than a new fact.\n */\nimport { tenantKey, type Clock, type TenantId } from '@byok-sdk/core';\nimport type { RequestReceipt, RequestReceiptStore } from '../ports';\n\nexport class InMemoryRequestReceiptStore implements RequestReceiptStore {\n readonly #receipts = new Map<string, RequestReceipt>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async record(\n tenant: TenantId,\n input: { key: string; body: string },\n ): Promise<{ receipt: RequestReceipt; created: boolean }> {\n const key = tenantKey(tenant, input.key);\n const existing = this.#receipts.get(key);\n if (existing !== undefined) return { receipt: existing, created: false };\n const receipt: RequestReceipt = {\n tenantId: tenant,\n key: input.key,\n body: input.body,\n recordedAt: this.#clock.now().toISOString(),\n };\n this.#receipts.set(key, receipt);\n return { receipt, created: true };\n }\n\n async get(tenant: TenantId, key: string): Promise<RequestReceipt | undefined> {\n return this.#receipts.get(tenantKey(tenant, key));\n }\n}\n","import { tenantKey, type Clock, type TenantId } from '@byok-sdk/core';\nimport type {\n ProofRequestReceipt,\n ProofRequestReceiptInput,\n ProofRequestReceiptStore,\n} from '../ports';\n\nexport class InMemoryProofRequestReceiptStore implements ProofRequestReceiptStore {\n readonly #receipts = new Map<string, ProofRequestReceipt>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async record(\n tenant: TenantId,\n input: ProofRequestReceiptInput,\n ): Promise<{ readonly receipt: ProofRequestReceipt; readonly created: boolean }> {\n const key = tenantKey(tenant, input.deviceId, input.requestId);\n const existing = this.#receipts.get(key);\n if (existing !== undefined) return { receipt: existing, created: false };\n const receipt: ProofRequestReceipt = {\n tenantId: tenant,\n ...input,\n recordedAt: this.#clock.now().toISOString(),\n };\n this.#receipts.set(key, receipt);\n return { receipt, created: true };\n }\n\n async get(\n tenant: TenantId,\n deviceId: string,\n requestId: string,\n ): Promise<ProofRequestReceipt | undefined> {\n return this.#receipts.get(tenantKey(tenant, deviceId, requestId));\n }\n}\n","/**\n * In-memory {@link TaskAttemptStore} — the ownership authority the inbound\n * gate reads (N2).\n *\n * Two deliberate no-ops:\n *\n * - `claim` on a task this tenant never offered writes nothing. A device that\n * guesses a taskId must not be able to conjure a row (and, cross-tenant,\n * must not leave a trace in the tenant it guessed into).\n * - `recordStatus` on an unknown task writes nothing, mirroring the reference\n * server's per-type handlers, whose behavior on a missing record is a no-op\n * rather than a rejection.\n *\n * Ownership is first-claim-wins and never transfers: reassigning an owner is\n * the one operation that would make the gate's cross-device assertion\n * unfalsifiable.\n */\nimport { tenantKey, type Clock, type TenantId } from '@byok-sdk/core';\nimport type { TaskAttempt, TaskAttemptStatus, TaskAttemptStore } from '../ports';\n\nexport class InMemoryTaskAttemptStore implements TaskAttemptStore {\n readonly #attempts = new Map<string, TaskAttempt>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async open(tenant: TenantId, input: { taskId: string; deviceId: string }): Promise<TaskAttempt> {\n const key = tenantKey(tenant, input.taskId);\n const existing = this.#attempts.get(key);\n if (existing !== undefined) return existing;\n const attempt: TaskAttempt = {\n tenantId: tenant,\n taskId: input.taskId,\n deviceId: input.deviceId,\n status: 'offered',\n updatedAt: this.#now(),\n };\n this.#attempts.set(key, attempt);\n return attempt;\n }\n\n async get(tenant: TenantId, taskId: string): Promise<TaskAttempt | undefined> {\n return this.#attempts.get(tenantKey(tenant, taskId));\n }\n\n async claim(tenant: TenantId, input: { taskId: string; deviceId: string }): Promise<TaskAttempt | undefined> {\n const key = tenantKey(tenant, input.taskId);\n const existing = this.#attempts.get(key);\n if (existing === undefined) return undefined;\n if (existing.ownerDeviceId !== undefined) return existing;\n const claimed: TaskAttempt = {\n ...existing,\n ownerDeviceId: input.deviceId,\n status: 'claimed',\n updatedAt: this.#now(),\n };\n this.#attempts.set(key, claimed);\n return claimed;\n }\n\n async recordStatus(\n tenant: TenantId,\n input: { taskId: string; status: TaskAttemptStatus },\n ): Promise<TaskAttempt | undefined> {\n const key = tenantKey(tenant, input.taskId);\n const existing = this.#attempts.get(key);\n if (existing === undefined) return undefined;\n const updated: TaskAttempt = { ...existing, status: input.status, updatedAt: this.#now() };\n this.#attempts.set(key, updated);\n return updated;\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","import type { Clock, TenantId } from '@byok-sdk/core';\nimport { ByokCloudError } from '../../errors';\nimport {\n activityCursor,\n activityTailKey,\n compareTimelineEvents,\n projectTimelineEvents,\n validateActivityAppend,\n type ActivityAppendInput,\n type ActivityStore,\n type ActivityTail,\n} from '../../activity';\n\nexport class InMemoryActivityStore implements ActivityStore {\n readonly #tails = new Map<string, ActivityTail>();\n\n constructor(private readonly clock: Clock) {}\n\n async append(tenant: TenantId, input: ActivityAppendInput): Promise<ActivityTail> {\n const capacity = validateActivityAppend(input);\n const now = this.clock.now();\n const receivedAt = now.toISOString();\n const key = activityTailKey(tenant, input.taskId);\n const existing = this.#tails.get(key);\n const live = existing !== undefined && receivedAt < existing.expiresAt ? existing : undefined;\n const incoming = projectTimelineEvents(input, receivedAt);\n for (const next of incoming) {\n const collision = live?.entries.find(\n (entry) =>\n entry.batchSeq === next.batchSeq &&\n entry.eventIndex === next.eventIndex &&\n entry.sourceEnvelopeId !== next.sourceEnvelopeId,\n );\n if (collision !== undefined) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Activity order key (${next.batchSeq}, ${next.eventIndex}) already belongs to another source envelope.`,\n );\n }\n }\n const allEntries = [...(live?.entries ?? []), ...incoming].sort(compareTimelineEvents);\n const evicted = Math.max(allEntries.length - capacity, 0);\n const entries = allEntries.slice(evicted);\n const cursor = activityCursor(entries);\n const tail: ActivityTail = {\n tenantId: tenant,\n taskId: input.taskId,\n entries,\n ...(cursor === undefined ? {} : { cursor }),\n dropped: (live?.dropped ?? 0) + input.dropped + evicted,\n capacity,\n expiresAt: new Date(now.getTime() + input.ttlMs).toISOString(),\n };\n this.#tails.set(key, tail);\n return tail;\n }\n\n async read(tenant: TenantId, taskId: string): Promise<ActivityTail | undefined> {\n const key = activityTailKey(tenant, taskId);\n const tail = this.#tails.get(key);\n if (tail === undefined) return undefined;\n if (this.clock.now().toISOString() >= tail.expiresAt) {\n this.#tails.delete(key);\n return undefined;\n }\n return tail;\n }\n}\n","import type { Clock, TenantId } from '@byok-sdk/core';\nimport { ByokCloudError } from '../../errors';\nimport {\n ApprovalObservationSchema,\n approvalTimelineCursor,\n approvalTimelineKey,\n validateApprovalTimelineAppend,\n type ApprovalTimelineAppendInput,\n type ApprovalTimelineStore,\n type ApprovalTimelineTail,\n} from '../../approval-timeline';\n\nexport class InMemoryApprovalTimelineStore implements ApprovalTimelineStore {\n readonly #tails = new Map<string, ApprovalTimelineTail>();\n\n constructor(private readonly clock: Clock) {}\n\n async append(\n tenant: TenantId,\n input: ApprovalTimelineAppendInput,\n ): Promise<ApprovalTimelineTail> {\n const { capacity, ttlMs, event } = validateApprovalTimelineAppend(input);\n const now = this.clock.now();\n const receivedAt = now.toISOString();\n const key = approvalTimelineKey(tenant, input.taskId);\n const existing = this.#tails.get(key);\n const live = existing !== undefined && receivedAt < existing.expiresAt ? existing : undefined;\n if (live !== undefined) {\n const duplicate = live.entries.find(\n (entry) => entry.sourceEnvelopeId === input.sourceEnvelopeId,\n );\n if (duplicate !== undefined) {\n if (JSON.stringify(duplicate.event) !== JSON.stringify(event)) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Approval source envelope identity already belongs to another lifecycle event.',\n );\n }\n return live;\n }\n }\n\n const revision = (live?.cursor ?? 0) + 1;\n const observation = ApprovalObservationSchema.parse({\n taskId: input.taskId,\n sourceEnvelopeId: input.sourceEnvelopeId,\n revision,\n receivedAt,\n event,\n });\n const allEntries = [...(live?.entries ?? []), observation];\n const evicted = Math.max(allEntries.length - capacity, 0);\n const entries = allEntries.slice(evicted);\n const tail: ApprovalTimelineTail = {\n tenantId: tenant,\n taskId: input.taskId,\n entries,\n cursor: approvalTimelineCursor(entries),\n dropped: (live?.dropped ?? 0) + evicted,\n capacity,\n expiresAt: new Date(now.getTime() + ttlMs).toISOString(),\n };\n this.#tails.set(key, tail);\n return tail;\n }\n\n async read(tenant: TenantId, taskId: string): Promise<ApprovalTimelineTail | undefined> {\n const key = approvalTimelineKey(tenant, taskId);\n const tail = this.#tails.get(key);\n if (tail === undefined) return undefined;\n if (this.clock.now().toISOString() >= tail.expiresAt) {\n this.#tails.delete(key);\n return undefined;\n }\n return tail;\n }\n}\n","/**\n * The in-memory reference implementation of every cloud-local port.\n *\n * Same posture as `@byok-sdk/core`'s: a reference, not a production store. What it\n * guarantees is that the behavior the handler suites assert is achievable\n * without a database — which is what makes those same assertions meaningful\n * when a durable composition (S3b's journal, S4A's schema) runs them later.\n */\nimport type { Clock, ObjectStore } from '@byok-sdk/core';\nimport type { CloudCrypto } from '../../crypto/port';\nimport type { BlobContentProxy, CloudStores } from '../ports';\nimport { AllowAllRateLimiter } from './rate-limiter';\nimport { createInMemoryBlobs } from './blobs';\nimport { InMemoryDeviceDirectory } from './device-directory';\nimport { InMemoryInboundDedupStore } from './dedup';\nimport { InMemoryNonceStore } from './nonces';\nimport { InMemoryPairingCodeStore } from './pairing-codes';\nimport { InMemoryRequestReceiptStore } from './receipts';\nimport { InMemoryProofRequestReceiptStore } from './proof-receipts';\nimport { InMemoryTaskAttemptStore } from './task-attempts';\nimport { InMemoryActivityStore } from './activity';\nimport { InMemoryApprovalTimelineStore } from './approval-timeline';\n\nexport { AllowAllRateLimiter } from './rate-limiter';\nexport {\n BLOB_URL_TTL_MS,\n InMemoryBlobContentProxy,\n InMemoryCloudBlobStore,\n createInMemoryBlobs,\n} from './blobs';\nexport type { InMemoryBlobs, InMemoryBlobStoreOptions } from './blobs';\nexport { DEDUP_RING_CAPACITY, InMemoryInboundDedupStore } from './dedup';\nexport { InMemoryDeviceDirectory } from './device-directory';\nexport { InMemoryNonceStore, NONCE_TTL_MS } from './nonces';\nexport { InMemoryPairingCodeStore } from './pairing-codes';\nexport { InMemoryRequestReceiptStore } from './receipts';\nexport { InMemoryProofRequestReceiptStore } from './proof-receipts';\nexport { InMemoryTaskAttemptStore } from './task-attempts';\nexport { InMemoryActivityStore } from './activity';\nexport { InMemoryApprovalTimelineStore } from './approval-timeline';\n\n/**\n * The port bundle plus the byte proxy, in the shape `createInMemoryCoreStores`\n * already uses: the composition is an object with a `stores` field, not the\n * bundle itself.\n *\n * `blobContentProxy` sits BESIDE `stores` rather than inside it because it is\n * not a port — `createByokCloud` takes it as its own optional input, and a\n * composition that cannot carry bytes simply has none to hand over.\n */\nexport interface InMemoryCloudComposition {\n readonly stores: CloudStores;\n readonly blobContentProxy: BlobContentProxy;\n}\n\nexport function createInMemoryCloudStores(\n clock: Clock,\n crypto: CloudCrypto,\n objects: ObjectStore,\n): InMemoryCloudComposition {\n const blobs = createInMemoryBlobs(clock, crypto, objects);\n return {\n stores: {\n activity: new InMemoryActivityStore(clock),\n approvals: new InMemoryApprovalTimelineStore(clock),\n devices: new InMemoryDeviceDirectory(),\n pairingCodes: new InMemoryPairingCodeStore(clock),\n nonces: new InMemoryNonceStore(clock, crypto),\n dedup: new InMemoryInboundDedupStore(),\n tasks: new InMemoryTaskAttemptStore(clock),\n receipts: new InMemoryRequestReceiptStore(clock),\n proofReceipts: new InMemoryProofRequestReceiptStore(clock),\n blobs: blobs.blobs,\n rateLimiter: new AllowAllRateLimiter(),\n },\n blobContentProxy: blobs.contentProxy,\n };\n}\n","/**\n * The in-memory composition: core's reference stores plus cloud's, wired into\n * a working {@link ByokCloud}.\n *\n * This is what the handler suites and the client-side end-to-end test run\n * against, and it is the honest demonstration of the S3 claim — the daemon\n * cannot tell this from `@byok-sdk/server`, and nothing in the path needs a\n * database to prove it.\n */\nimport {\n createInMemoryCoreStores,\n type CapabilityDeclaration,\n type Clock,\n type CoreStores,\n type SkillPackStore,\n} from '@byok-sdk/core';\nimport { createHmacTokenSigner, type TokenSigner } from '../auth/tokens';\nimport { fullCapabilityDeclaration } from '../capabilities';\nimport { createWebCrypto } from '../crypto/web-crypto';\nimport type { CloudCrypto } from '../crypto/port';\nimport { createByokCloud, type ByokCloud } from '../cloud';\nimport { createInMemoryCloudStores } from '../stores/in-memory/index';\nimport type { BlobContentProxy, CloudStores } from '../stores/ports';\nimport type { TruthCommitter, TruthObjectDownloads } from '../truth/contract';\n\nconst TOKEN_SECRET_BYTES = 32;\n\n/**\n * Real time by default, deliberately.\n *\n * Core's in-memory reference defaults to a FROZEN clock so TTL conformance is\n * deterministic. A composition serving a real daemon cannot: the daemon\n * compares the `expiresAt` it is handed against its own wall clock and would\n * treat every token from a clock stuck in the past as already expired. A test\n * that needs deterministic TTLs injects a mutable clock here instead.\n */\nfunction systemClock(): Clock {\n return { now: () => new Date() };\n}\n\nexport interface InMemoryByokCloudOptions {\n readonly clock?: Clock;\n readonly crypto?: CloudCrypto;\n readonly tokenSigner?: TokenSigner;\n readonly capabilities?: CapabilityDeclaration;\n readonly operatorId?: string;\n readonly maxBlobSizeBytes?: number;\n readonly longPollHoldMs?: number;\n readonly longPollIntervalMs?: number;\n readonly eventsPageLimit?: number;\n readonly accessTokenTtlSeconds?: number;\n readonly boardPageLimit?: number;\n readonly boardStreamQueryIntervalMs?: number;\n readonly boardStreamHeartbeatIntervalMs?: number;\n readonly boardStreamReconciliationIntervalMs?: number;\n readonly boardChannelMaxBytes?: number;\n readonly boardTitleMaxBytes?: number;\n readonly presenceTtlMs?: number;\n readonly presenceMinimumIntervalMs?: number;\n readonly presenceDetailMaxBytes?: number;\n readonly activityMaxEvents?: number;\n readonly activityMaxBytes?: number;\n readonly activityCapacity?: number;\n readonly activityTtlMs?: number;\n /** Test/host supplied atomic truth authority; never synthesized from sequential stores. */\n readonly truthCommitter?: TruthCommitter;\n readonly truthObjectDownloads?: TruthObjectDownloads;\n readonly maxTruthRequestBytes?: number;\n /**\n * Host/test supplied skill pack catalogue. Absent by default, and\n * `fullCapabilityDeclaration()` withholds `skills.pack` to match — a\n * composition that declared a channel it has no store for would be refused at\n * construction, which would break every existing in-memory deployment.\n */\n readonly skillPacks?: SkillPackStore;\n readonly skillPackPageLimit?: number;\n}\n\nexport interface InMemoryByokCloud {\n readonly cloud: ByokCloud;\n /** The naked stores, for a host that wants to inspect or seed state directly. */\n readonly core: CoreStores;\n readonly stores: CloudStores;\n /** The byte proxy the two `/content` routes were mounted on. */\n readonly blobContentProxy: BlobContentProxy;\n readonly clock: Clock;\n readonly crypto: CloudCrypto;\n}\n\nexport function createInMemoryByokCloud(options: InMemoryByokCloudOptions = {}): InMemoryByokCloud {\n const clock = options.clock ?? systemClock();\n const crypto = options.crypto ?? createWebCrypto();\n const core = createInMemoryCoreStores({ clock }).stores;\n const { stores, blobContentProxy } = createInMemoryCloudStores(clock, crypto, core.objects);\n const tokenSigner =\n options.tokenSigner ??\n createHmacTokenSigner(globalThis.crypto.getRandomValues(new Uint8Array(TOKEN_SECRET_BYTES)), clock);\n\n const cloud = createByokCloud({\n core,\n cloud: stores,\n // This composition has nowhere else to put bytes, so it supplies the proxy\n // and `fullCapabilityDeclaration()` declares `blobs.contentproxy`. That\n // pairing is what keeps hosted-in-memory behavior identical to what it was\n // before the port narrowed.\n blobContentProxy,\n crypto,\n tokenSigner,\n clock,\n capabilities: options.capabilities ?? fullCapabilityDeclaration(),\n ...(options.truthCommitter === undefined ? {} : { truthCommitter: options.truthCommitter }),\n ...(options.truthObjectDownloads === undefined\n ? {}\n : { truthObjectDownloads: options.truthObjectDownloads }),\n ...(options.operatorId !== undefined ? { operatorId: options.operatorId } : {}),\n ...(options.maxBlobSizeBytes !== undefined ? { maxBlobSizeBytes: options.maxBlobSizeBytes } : {}),\n ...(options.longPollHoldMs !== undefined ? { longPollHoldMs: options.longPollHoldMs } : {}),\n ...(options.longPollIntervalMs !== undefined ? { longPollIntervalMs: options.longPollIntervalMs } : {}),\n ...(options.eventsPageLimit !== undefined ? { eventsPageLimit: options.eventsPageLimit } : {}),\n ...(options.accessTokenTtlSeconds !== undefined\n ? { accessTokenTtlSeconds: options.accessTokenTtlSeconds }\n : {}),\n ...(options.boardPageLimit === undefined ? {} : { boardPageLimit: options.boardPageLimit }),\n ...(options.boardStreamQueryIntervalMs === undefined\n ? {}\n : { boardStreamQueryIntervalMs: options.boardStreamQueryIntervalMs }),\n ...(options.boardStreamHeartbeatIntervalMs === undefined\n ? {}\n : { boardStreamHeartbeatIntervalMs: options.boardStreamHeartbeatIntervalMs }),\n ...(options.boardStreamReconciliationIntervalMs === undefined\n ? {}\n : { boardStreamReconciliationIntervalMs: options.boardStreamReconciliationIntervalMs }),\n ...(options.boardChannelMaxBytes === undefined\n ? {}\n : { boardChannelMaxBytes: options.boardChannelMaxBytes }),\n ...(options.boardTitleMaxBytes === undefined\n ? {}\n : { boardTitleMaxBytes: options.boardTitleMaxBytes }),\n ...(options.presenceTtlMs === undefined ? {} : { presenceTtlMs: options.presenceTtlMs }),\n ...(options.presenceMinimumIntervalMs === undefined\n ? {}\n : { presenceMinimumIntervalMs: options.presenceMinimumIntervalMs }),\n ...(options.presenceDetailMaxBytes === undefined\n ? {}\n : { presenceDetailMaxBytes: options.presenceDetailMaxBytes }),\n ...(options.activityMaxEvents === undefined ? {} : { activityMaxEvents: options.activityMaxEvents }),\n ...(options.activityMaxBytes === undefined ? {} : { activityMaxBytes: options.activityMaxBytes }),\n ...(options.activityCapacity === undefined ? {} : { activityCapacity: options.activityCapacity }),\n ...(options.activityTtlMs === undefined ? {} : { activityTtlMs: options.activityTtlMs }),\n ...(options.maxTruthRequestBytes === undefined\n ? {}\n : { maxTruthRequestBytes: options.maxTruthRequestBytes }),\n ...(options.skillPacks === undefined ? {} : { skillPacks: options.skillPacks }),\n ...(options.skillPackPageLimit === undefined\n ? {}\n : { skillPackPageLimit: options.skillPackPageLimit }),\n });\n\n return { cloud, core, stores, blobContentProxy, clock, crypto };\n}\n","import {\n BOARD_STATUSES,\n assertCapability,\n hasCapability,\n type CapabilityDeclaration,\n} from '@byok-sdk/core';\nimport { BYOK_BOARD_PATH, BYOK_BOARD_STREAM_PATH } from '@byok-sdk/protocol';\nimport { z } from 'zod';\nimport { CLOUD_CAPABILITIES } from './capabilities';\n\nconst BoardFeedItemSchema = z.object({\n tenantId: z.string(),\n itemId: z.string(),\n channel: z.string(),\n title: z.string(),\n status: z.enum(BOARD_STATUSES),\n assignee: z\n .object({ holderId: z.string(), heldSince: z.string() })\n .optional(),\n boardSeq: z.number().int().nonnegative(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\n\nconst BoardFeedPageSchema = z.object({\n items: z.array(BoardFeedItemSchema),\n nextSeq: z.number().int().nonnegative(),\n hasMore: z.boolean(),\n});\n\nexport type BoardFeedItem = z.infer<typeof BoardFeedItemSchema>;\nexport type BoardFeedPage = z.infer<typeof BoardFeedPageSchema>;\nexport type BoardFeedMode = 'sse' | 'poll';\nexport type BoardFeedRead =\n | { readonly type: 'board'; readonly item: BoardFeedItem }\n | { readonly type: 'reconcile' }\n | { readonly type: 'poll'; readonly page: BoardFeedPage };\n\nexport class BoardFeedRetryableError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'BoardFeedRetryableError';\n }\n}\n\nexport class BoardFeedStoppedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BoardFeedStoppedError';\n }\n}\n\nexport interface BoardFeedClientOptions {\n readonly baseUrl: string | URL;\n readonly accessToken: string;\n readonly capabilities: CapabilityDeclaration;\n readonly fetch?: typeof globalThis.fetch;\n readonly idleWatchdogMs?: number;\n}\n\n/**\n * One board feed consumer with a declaration-fixed transport.\n *\n * The mode is selected once from ADR-010 data. A temporary SSE 5xx or idle\n * watchdog expiry raises {@link BoardFeedRetryableError}; it never mutates the\n * mode to polling. A caller retries the same instance and therefore the same\n * declared transport. Polling exists only when `board.sse` was absent from the\n * declaration in the first place.\n */\nexport class BoardFeedClient {\n readonly mode: BoardFeedMode;\n readonly #base: URL;\n readonly #accessToken: string;\n readonly #fetch: typeof globalThis.fetch;\n readonly #idleWatchdogMs: number;\n\n constructor(options: BoardFeedClientOptions) {\n assertCapability(options.capabilities, CLOUD_CAPABILITIES.boardCoordination);\n this.mode = hasCapability(options.capabilities, CLOUD_CAPABILITIES.boardSse) ? 'sse' : 'poll';\n this.#base = new URL(options.baseUrl);\n this.#accessToken = options.accessToken;\n this.#fetch = options.fetch ?? globalThis.fetch;\n this.#idleWatchdogMs = options.idleWatchdogMs ?? 30_000;\n }\n\n async readOnce(afterSeq: number, signal?: AbortSignal): Promise<BoardFeedRead> {\n if (!Number.isSafeInteger(afterSeq) || afterSeq < 0) {\n throw new TypeError('afterSeq must be a non-negative safe integer.');\n }\n return this.mode === 'sse'\n ? this.#readSseOnce(afterSeq, signal)\n : this.#readPollOnce(afterSeq, signal);\n }\n\n async #readPollOnce(afterSeq: number, signal?: AbortSignal): Promise<BoardFeedRead> {\n const url = new URL(BYOK_BOARD_PATH, this.#base);\n url.searchParams.set('since', String(afterSeq));\n const response = await this.#fetch(url, {\n headers: { authorization: `Bearer ${this.#accessToken}` },\n ...(signal === undefined ? {} : { signal }),\n });\n assertBoardResponse(response, 'poll');\n return { type: 'poll', page: BoardFeedPageSchema.parse(await response.json()) };\n }\n\n async #readSseOnce(afterSeq: number, signal?: AbortSignal): Promise<BoardFeedRead> {\n const url = new URL(BYOK_BOARD_STREAM_PATH, this.#base);\n const response = await this.#fetch(url, {\n headers: {\n accept: 'text/event-stream',\n authorization: `Bearer ${this.#accessToken}`,\n 'last-event-id': String(afterSeq),\n },\n ...(signal === undefined ? {} : { signal }),\n });\n assertBoardResponse(response, 'SSE');\n if (response.body === null) throw new BoardFeedRetryableError('Board SSE response had no body.');\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n while (true) {\n const chunk = await readWithWatchdog(reader, this.#idleWatchdogMs);\n if (chunk.done) throw new BoardFeedRetryableError('Board SSE ended before the next event.');\n buffer += decoder.decode(chunk.value, { stream: true }).replaceAll('\\r\\n', '\\n');\n let boundary = buffer.indexOf('\\n\\n');\n while (boundary >= 0) {\n const frame = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n const parsed = parseSseFrame(frame);\n if (parsed !== undefined) return parsed;\n boundary = buffer.indexOf('\\n\\n');\n }\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n }\n}\n\nfunction assertBoardResponse(response: Response, transport: 'poll' | 'SSE'): void {\n if (response.status === 401) {\n throw new BoardFeedStoppedError('Board credential is no longer valid.');\n }\n if (response.ok) return;\n if (response.status >= 500) {\n throw new BoardFeedRetryableError(`Board ${transport} failed with HTTP ${response.status}.`);\n }\n throw new BoardFeedStoppedError(\n `Board ${transport} failed permanently with HTTP ${response.status}.`,\n );\n}\n\nasync function readWithWatchdog(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n timeoutMs: number,\n) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n reader.read(),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new BoardFeedRetryableError('Board SSE idle watchdog expired.')),\n timeoutMs,\n );\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\nfunction parseSseFrame(frame: string): BoardFeedRead | undefined {\n if (frame.length === 0 || frame.startsWith(':')) return undefined;\n let event = 'message';\n const data: string[] = [];\n for (const line of frame.split('\\n')) {\n if (line.startsWith('event:')) event = line.slice('event:'.length).trimStart();\n if (line.startsWith('data:')) data.push(line.slice('data:'.length).trimStart());\n }\n if (event === 'reconcile') return { type: 'reconcile' };\n if (event !== 'board') return undefined;\n if (data.length === 0) throw new SyntaxError('Board SSE board event had no data.');\n return { type: 'board', item: BoardFeedItemSchema.parse(JSON.parse(data.join('\\n'))) };\n}\n","/**\n * The cloud-local store ports.\n *\n * `@byok-sdk/core` owns the platform ports every composition shares (mailbox,\n * board, truth, objects, quota). These are the ones only a HOSTED device\n * surface needs — the auth plane and the task-attempt bookkeeping the device\n * routes read. S2 deliberately kept them out of core: they are hosted-surface\n * concerns, and S4A's schema work is the right moment to decide their durable\n * home. Cloud owning them keeps this slice additive and revertible.\n *\n * Two rules, same as core's (`stores.ts`):\n *\n * 1. **Async.** Every method returns a `Promise`, so a SQL or KV composition\n * can implement the same contract the in-memory reference does.\n * 2. **Tenant-first.** Every method's first parameter is a required\n * `TenantId` — with exactly two documented exceptions below, each of\n * which is pre-tenant *by construction* because the credential it is\n * handed is itself what resolves the tenant.\n *\n * The two exceptions:\n *\n * - {@link DeviceDirectory.resolveByDeviceId} — `POST /byok/challenge` and\n * `POST /byok/token` carry only a deviceId (the pinned wire contract), and\n * the row is what tells the deployment which tenant to mint for.\n * - {@link PairingCodeStore.redeem} — the code IS the tenant lookup; it was\n * minted against a tenant that only the host's control plane knew.\n *\n * Neither is reachable through {@link TenantStores} (see `tenant-stores.ts`),\n * so a device-facing handler cannot call them.\n *\n * The byte-proxy trio that used to be a third pre-tenant exception is no\n * longer part of this bundle at all: it moved to {@link BlobContentProxy},\n * an OPTIONAL composition input rather than a {@link CloudStores} member,\n * because a composition backed by object storage physically cannot proxy\n * bytes (see the blobs section below).\n */\nimport type { StorageReservation, TenantId } from '@byok-sdk/core';\nimport type { ActivityStore } from '../activity';\nimport type { ApprovalTimelineStore } from '../approval-timeline';\n\n// ---------------------------------------------------------------------------\n// Device directory (S1's `DeviceRegistry`, tenant-first)\n// ---------------------------------------------------------------------------\n\nexport interface DeviceRecord {\n readonly tenantId: TenantId;\n readonly productId: string;\n readonly deviceId: string;\n readonly deviceName: string;\n /** Ed25519 public key, base64url-encoded (JWK `x` form). */\n readonly devicePublicKey: string;\n /** Proof key identity stored on the row; verifier claims never supply a default. */\n readonly proofKeyId: string;\n /** Current proof signing-key rotation generation. */\n readonly proofKeyEpoch: number;\n readonly revoked: boolean;\n}\n\n/** Everything `POST /byok/pair` knows at registration time. `tenantId` is the store's first parameter; `revoked` is the store's own to set. */\nexport interface DeviceRegistration {\n readonly productId: string;\n readonly deviceId: string;\n readonly deviceName: string;\n readonly devicePublicKey: string;\n readonly proofKeyId: string;\n readonly proofKeyEpoch: number;\n}\n\nexport interface DeviceDirectory {\n register(tenant: TenantId, input: DeviceRegistration): Promise<DeviceRecord>;\n /** The row `tenant` owns under `deviceId` — `undefined` including when the device exists under a DIFFERENT tenant. */\n get(tenant: TenantId, deviceId: string): Promise<DeviceRecord | undefined>;\n revoke(tenant: TenantId, deviceId: string): Promise<void>;\n list(tenant: TenantId): Promise<readonly DeviceRecord[]>;\n /** Pre-tenant. Two callers only: `POST /byok/challenge` and `POST /byok/token`. Never exposed through the tenant facade. */\n resolveByDeviceId(deviceId: string): Promise<DeviceRecord | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Pairing codes (S1's `PairingManager`, tenant-first mint)\n// ---------------------------------------------------------------------------\n\n/**\n * The identity a pairing code carries. Minted out-of-band by the host's own\n * auth/device-flow UI — the only party that knows which tenant a human is\n * acting for. Deliberately NOT a wire field: `PairRequest` has no tenant of\n * its own, so a device can never name the tenant it lands in.\n */\nexport interface PairingCodeClaims {\n readonly tenantId: TenantId;\n readonly productId: string;\n}\n\nexport interface PairingCodeInfo {\n readonly code: string;\n /** Canonical ISO-8601 UTC instant. */\n readonly expiresAt: string;\n}\n\nexport interface PairingCodeIssueInput {\n readonly code: string;\n readonly productId: string;\n readonly expiresAt: string;\n}\n\nexport interface PairingCodeStore {\n issue(tenant: TenantId, input: PairingCodeIssueInput): Promise<PairingCodeInfo>;\n /**\n * Validate and CONSUME a code, returning the claims it was minted with, or\n * `undefined` when it is unknown, expired, or already used — one answer for\n * all three, so a redeem attempt is never an existence oracle. Single-use is\n * what makes the caller's \"redeem, then register the device row\" sequence\n * exclusive: a second redeem can never reach the registration step.\n */\n redeem(code: string): Promise<PairingCodeClaims | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Challenge nonces\n// ---------------------------------------------------------------------------\n\nexport interface NonceStore {\n issue(tenant: TenantId, deviceId: string): Promise<string>;\n /** `true` iff the nonce exists for this (tenant, device), is unexpired, and has not been consumed. Never mutates. */\n validate(tenant: TenantId, deviceId: string, nonce: string): Promise<boolean>;\n /** Consume the nonce. Called only after every other check on the request has passed. */\n markUsed(tenant: TenantId, nonce: string): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Inbound envelope dedup (N3)\n// ---------------------------------------------------------------------------\n\nexport interface InboundDedupStore {\n /**\n * `true` when `envelopeId` was already seen for this (tenant, device);\n * otherwise records it and returns `false`. Bounded per device — the wire is\n * at-least-once (§9); this makes processing at-most-once without an\n * unbounded set.\n */\n checkAndRecord(tenant: TenantId, deviceId: string, envelopeId: string): Promise<boolean>;\n}\n\n// ---------------------------------------------------------------------------\n// Task attempts — the ownership authority the inbound gate reads (N2)\n// ---------------------------------------------------------------------------\n\nexport const TASK_ATTEMPT_STATUSES = [\n 'offered',\n 'claimed',\n 'running',\n 'complete',\n 'failed',\n 'cancelled',\n] as const;\nexport type TaskAttemptStatus = (typeof TASK_ATTEMPT_STATUSES)[number];\n\nexport interface TaskAttempt {\n readonly tenantId: TenantId;\n readonly taskId: string;\n /** The device the offer was addressed to. */\n readonly deviceId: string;\n /** Set by `task.claim`, and only by the first one. Until then the task has no owner and the gate lets any of this tenant's devices through, matching the reference server. */\n readonly ownerDeviceId?: string;\n readonly status: TaskAttemptStatus;\n readonly updatedAt: string;\n}\n\nexport interface TaskAttemptStore {\n /** Called when an offer is enqueued: records the pending attempt with no owner yet. */\n open(tenant: TenantId, input: { readonly taskId: string; readonly deviceId: string }): Promise<TaskAttempt>;\n get(tenant: TenantId, taskId: string): Promise<TaskAttempt | undefined>;\n /** First claim wins the ownership; a later claim by the same device is idempotent. No-op (returns `undefined`) for a task this tenant never offered. */\n claim(tenant: TenantId, input: { readonly taskId: string; readonly deviceId: string }): Promise<TaskAttempt | undefined>;\n /** Record a lifecycle transition. No-op (returns `undefined`) for an unknown task — same shape as the reference server's per-type handlers. */\n recordStatus(\n tenant: TenantId,\n input: { readonly taskId: string; readonly status: TaskAttemptStatus },\n ): Promise<TaskAttempt | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Request receipts — the terminal idempotency seam\n// ---------------------------------------------------------------------------\n\nexport interface RequestReceipt {\n readonly tenantId: TenantId;\n readonly key: string;\n /** Opaque payload the caller recorded — for terminals, the encoded envelope. */\n readonly body: string;\n readonly recordedAt: string;\n}\n\nexport interface RequestReceiptStore {\n /**\n * Record a receipt under `key`, or return the existing one untouched.\n * `created` is `false` for a replay — the FIRST terminal is the fact\n * (§12.6.4: 不覆写第一份事实), and a retry of the same terminal must not\n * overwrite it.\n */\n record(\n tenant: TenantId,\n input: { readonly key: string; readonly body: string },\n ): Promise<{ readonly receipt: RequestReceipt; readonly created: boolean }>;\n get(tenant: TenantId, key: string): Promise<RequestReceipt | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Device-proof request receipts — request-bound replay authority (S6)\n// ---------------------------------------------------------------------------\n\nexport interface ProofRequestReceipt {\n readonly tenantId: TenantId;\n readonly deviceId: string;\n readonly requestId: string;\n readonly operation: string;\n readonly resource: string;\n readonly bodySha256: string;\n readonly bodySize: bigint;\n readonly responseStatus: number;\n readonly responseBody: string;\n readonly recordedAt: string;\n}\n\nexport type ProofRequestReceiptInput = Omit<\n ProofRequestReceipt,\n 'tenantId' | 'recordedAt'\n>;\n\n/**\n * First-result-wins replay store. The application layer compares every stored\n * binding before returning an exact replay; a reused request id with any\n * different binding is a conflict, never a second write.\n */\nexport interface ProofRequestReceiptStore {\n record(\n tenant: TenantId,\n input: ProofRequestReceiptInput,\n ): Promise<{ readonly receipt: ProofRequestReceipt; readonly created: boolean }>;\n get(\n tenant: TenantId,\n deviceId: string,\n requestId: string,\n ): Promise<ProofRequestReceipt | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Blobs (§7)\n// ---------------------------------------------------------------------------\n\nexport interface BlobDeclaration {\n readonly size: number;\n readonly contentType: string;\n /** Canonical `sha256:<64 lowercase hex>` — the schema rejected anything else before this store sees it. */\n readonly contentHash: string;\n}\n\n/** What object-store metadata can actually observe at finalize (ADR-024). */\nexport interface BlobObservation {\n readonly observedByteSize: bigint;\n readonly observedContentType: string;\n}\n\nexport type BlobWriteResult = { readonly ok: true } | { readonly ok: false; readonly reason: string };\n\nexport interface BlobContent {\n readonly data: Uint8Array;\n readonly contentType: string;\n}\n\n/**\n * The capability-minting half of blobs: what EVERY composition can honestly\n * provide, whoever holds the bytes.\n *\n * Both methods are tenant-first, and both are reachable through {@link\n * TenantStores}. There is no pre-tenant method left on this port — see\n * {@link BlobContentProxy} for where the other three went and why.\n */\nexport interface CloudBlobStore {\n /** Mint only from an already-admitted object reservation. */\n createUpload(tenant: TenantId, reservation: StorageReservation): Promise<{ readonly blobId: string; readonly uploadUrl: string }>;\n /** Observe existence/size/type while proving this blob belongs to this reservation. */\n observeUpload(tenant: TenantId, blobId: string, reservation: StorageReservation): Promise<BlobObservation | undefined>;\n /** A presigned GET URL for a blob THIS tenant owns that has finished uploading; `undefined` otherwise — including for another tenant's blob. */\n getDownloadUrl(tenant: TenantId, blobId: string): Promise<string | undefined>;\n}\n\n/**\n * The byte-proxying half: an OPTIONAL composition input, not a port.\n *\n * These three serve the two `/byok/blobs/:id/content` routes, which exist\n * because the in-memory and self-hosted compositions have nowhere else to put\n * bytes — cloud has to carry them. A composition whose bytes live in object\n * storage (S3/R2) hands the device a presigned URL to the object store itself\n * and never sees a byte, so it cannot implement these at all.\n *\n * That is why this is a separate interface supplied at composition time rather\n * than a member of {@link CloudStores}: \"this deployment cannot proxy bytes\"\n * becomes a type-level fact (the proxy is simply absent) instead of three\n * methods that throw. The alternatives were both anti-patterns — a conformance\n * suite that skips three methods for one composition is a subset waiver, and\n * one that asserts a typed rejection proves nothing\n * (docs/researches/s4a-dataplane-design.md §6).\n *\n * All three are pre-tenant by construction: the `/content` routes are\n * presigned, not bearer-authed, so there is no principal in scope at all and\n * the HMAC signature over the blob id is the whole credential. They stay off\n * {@link TenantStores} for the same reason the two exceptions above do.\n *\n * A deployment supplying a proxy must also declare `blobs.contentproxy`\n * (ADR-010): the routes mount on proxy-presence AND declaration, never on\n * either alone.\n */\nexport interface BlobContentProxy {\n verifySignedUrl(blobId: string, action: 'put' | 'get', sig: string, exp: number): Promise<boolean>;\n writeContent(blobId: string, data: Uint8Array): Promise<BlobWriteResult>;\n readContent(blobId: string): Promise<BlobContent | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Inbound rate limiting (M4 Phase 4 part A's seam)\n// ---------------------------------------------------------------------------\n\n/**\n * Step 0 of the inbound gate. S3a ships an allow-all reference (a hosted\n * deployment's real limiter is edge/infra work, not handler work) — what\n * matters now is that the SEAM sits at gate position 0, before the type-allow\n * check, so a flood of garbage-typed envelopes costs the same budget as a\n * flood of well-formed ones once a real limiter is plugged in.\n */\nexport interface InboundRateLimiter {\n consume(tenant: TenantId, deviceId: string): Promise<boolean>;\n}\n\n// ---------------------------------------------------------------------------\n// The bundle a composition supplies\n// ---------------------------------------------------------------------------\n\n/**\n * All-or-nothing: a composition supplies every port here or it is not a\n * composition. {@link BlobContentProxy} is deliberately absent — it is an\n * optional input to `createByokCloud`, not a port, precisely so that the\n * bundle can stay all-or-nothing while byte proxying stays optional.\n */\nexport interface CloudStores {\n readonly activity: ActivityStore;\n readonly approvals: ApprovalTimelineStore;\n readonly devices: DeviceDirectory;\n readonly pairingCodes: PairingCodeStore;\n readonly nonces: NonceStore;\n readonly dedup: InboundDedupStore;\n readonly tasks: TaskAttemptStore;\n readonly receipts: RequestReceiptStore;\n readonly proofReceipts: ProofRequestReceiptStore;\n readonly blobs: CloudBlobStore;\n readonly rateLimiter: InboundRateLimiter;\n}\n\n/** Names of every port in {@link CloudStores}, in contract order. */\nexport const CLOUD_STORE_NAMES = [\n 'activity',\n 'approvals',\n 'devices',\n 'pairingCodes',\n 'nonces',\n 'dedup',\n 'tasks',\n 'receipts',\n 'proofReceipts',\n 'blobs',\n 'rateLimiter',\n] as const;\n\nexport type CloudStoreName = (typeof CLOUD_STORE_NAMES)[number];\n","/**\n * The declared method inventory of every cloud-local port.\n *\n * The exact counterpart of `@byok-sdk/core`'s `ports-contract.ts`, and it exists\n * for the same reason: the table says what a port IS, so it has to be readable\n * by every enforcer without any of them owning it. `@byok-sdk/conformance` asserts\n * live compositions against it; a durable adapter (`@byok-sdk/cloud-dataplane`) is\n * written against it.\n *\n * This module adds data and nothing else. It does not re-declare, re-shape, or\n * re-interpret a single line of `ports.ts` — that file stays the authority for\n * what the methods mean, and stayed byte-identical through S4A-a.\n *\n * Adding a port method means editing this table, which is the point: a port\n * grows by contract, not by whichever composition needed something.\n */\nimport type { CloudStoreName } from './ports';\n\nexport const CLOUD_PORT_METHODS: Readonly<Record<CloudStoreName, readonly string[]>> = {\n activity: ['append', 'read'],\n approvals: ['append', 'read'],\n devices: ['register', 'get', 'revoke', 'list', 'resolveByDeviceId'],\n pairingCodes: ['issue', 'redeem'],\n nonces: ['issue', 'validate', 'markUsed'],\n dedup: ['checkAndRecord'],\n tasks: ['open', 'get', 'claim', 'recordStatus'],\n receipts: ['record', 'get'],\n proofReceipts: ['record', 'get'],\n // Three methods, not six: the byte-proxy trio moved to `BlobContentProxy`,\n // which is a composition input rather than a port and therefore has no row\n // in this table (docs/researches/s4a-dataplane-design.md §6).\n blobs: ['createUpload', 'observeUpload', 'getDownloadUrl'],\n rateLimiter: ['consume'],\n};\n\n/** The interface each port name is declared as, for a source-side scan. */\nexport const CLOUD_PORT_INTERFACES: Readonly<Record<CloudStoreName, string>> = {\n activity: 'ActivityStore',\n approvals: 'ApprovalTimelineStore',\n devices: 'DeviceDirectory',\n pairingCodes: 'PairingCodeStore',\n nonces: 'NonceStore',\n dedup: 'InboundDedupStore',\n tasks: 'TaskAttemptStore',\n receipts: 'RequestReceiptStore',\n proofReceipts: 'ProofRequestReceiptStore',\n blobs: 'CloudBlobStore',\n rateLimiter: 'InboundRateLimiter',\n};\n"]}
1
+ {"version":3,"sources":["../src/crypto/web-crypto.ts","../src/auth/tokens.ts","../src/auth/verify.ts","../src/auth/plane.ts","../src/capabilities.ts","../src/errors.ts","../src/activity.ts","../src/coordination.ts","../src/auth/bearer.ts","../src/tenant-stores.ts","../src/handlers/shared.ts","../src/handlers/blobs.ts","../src/handlers/capabilities.ts","../src/handlers/auth.ts","../src/handlers/events.ts","../src/approval-timeline.ts","../src/board-projection.ts","../src/inbound.ts","../src/handlers/messages.ts","../src/handlers/board.ts","../src/handlers/presence.ts","../src/handlers/skill-packs.ts","../src/auth/device-proof.ts","../src/truth/contract.ts","../src/truth/errors.ts","../src/handlers/truth.ts","../src/router/registry.ts","../src/terminal-result.ts","../src/cloud.ts","../src/stores/in-memory/rate-limiter.ts","../src/stores/in-memory/blobs.ts","../src/stores/in-memory/device-directory.ts","../src/stores/in-memory/dedup.ts","../src/stores/in-memory/nonces.ts","../src/stores/in-memory/pairing-codes.ts","../src/stores/in-memory/receipts.ts","../src/stores/in-memory/proof-receipts.ts","../src/stores/in-memory/task-attempts.ts","../src/stores/in-memory/activity.ts","../src/stores/in-memory/approval-timeline.ts","../src/stores/in-memory/index.ts","../src/composition/in-memory.ts","../src/auth/device-assertion.ts","../src/coordination-client.ts","../src/stores/ports.ts","../src/stores/ports-contract.ts"],"names":["tenantId","z","response","tenantKey","isCoreConflictError","isCoreError","principalTenant","isTenantId","unauthorized","contentHash","STORAGE_ERROR_CODES","STORAGE_ERROR_HTTP_STATUS","decodeEnvelope","envelope","encodeEnvelope","nonce","BOARD_STATUSES","hasCapability","BYOK_BOARD_PATH","BYOK_BOARD_STREAM_PATH"],"mappings":";;;;;;;;;AAWA,IAAM,qBAAA,GAAwB,kCAAA;AAE9B,IAAM,UAAA,GAAa,kBAAA;AAEZ,SAAS,gBAAgB,KAAA,EAA2B;AACzD,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,EAAO,MAAA,IAAU,MAAA,CAAO,aAAa,IAAI,CAAA;AAC5D,EAAA,OAAO,IAAA,CAAK,MAAM,CAAA,CAAE,UAAA,CAAW,GAAA,EAAK,GAAG,CAAA,CAAE,UAAA,CAAW,GAAA,EAAK,GAAG,CAAA,CAAE,UAAA,CAAW,KAAK,EAAE,CAAA;AAClF;AAQO,SAAS,gBAAgB,KAAA,EAAuC;AACrE,EAAA,MAAM,MAAA,GAAS,MAAM,UAAA,CAAW,GAAA,EAAK,GAAG,CAAA,CAAE,UAAA,CAAW,KAAK,GAAG,CAAA;AAC7D,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,KAAK,MAAM,CAAA;AAC1B,IAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,MAAA,CAAO,MAAM,CAAA;AAC1C,IAAA,KAAA,IAAS,KAAA,GAAQ,CAAA,EAAG,KAAA,GAAQ,MAAA,CAAO,MAAA,EAAQ,KAAA,IAAS,CAAA,EAAG,KAAA,CAAM,KAAK,CAAA,GAAI,MAAA,CAAO,UAAA,CAAW,KAAK,CAAA;AAC7F,IAAA,OAAO,KAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAEA,SAAS,MAAM,KAAA,EAA2B;AACxC,EAAA,IAAI,GAAA,G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,EAAU,CAAC,QAAA,EAAU,KAAK,CAAA;AAAA,EAC1B,aAAA,EAAe,CAAC,QAAA,EAAU,KAAK,CAAA;AAAA;AAAA;AAAA;AAAA,EAI/B,KAAA,EAAO,CAAC,cAAA,EAAgB,eAAA,EAAiB,gBAAgB,CAAA;AAAA,EACzD,WAAA,EAAa,CAAC,SAAS;AACzB;AAGO,IAAM,qBAAA,GAAkE;AAAA,EAC7E,QAAA,EAAU,eAAA;AAAA,EACV,SAAA,EAAW,uBAAA;AAAA,EACX,OAAA,EAAS,iBAAA;AAAA,EACT,YAAA,EAAc,kBAAA;AAAA,EACd,MAAA,EAAQ,YAAA;AAAA,EACR,KAAA,EAAO,mBAAA;AAAA,EACP,KAAA,EAAO,kBAAA;AAAA,EACP,QAAA,EAAU,qBAAA;AAAA,EACV,aAAA,EAAe,0BAAA;AAAA,EACf,KAAA,EAAO,gBAAA;AAAA,EACP,WAAA,EAAa;AACf","file":"index.js","sourcesContent":["/**\n * The reference {@link CloudCrypto}, built entirely on the WebCrypto API that\n * Node >=20, Cloudflare Workers, and Deno all expose as `globalThis.crypto`.\n *\n * No `node:crypto`, no dependency: the point of the port is that a hosted\n * composition stays runtime-neutral, and an adapter that reached for a Node\n * built-in here would make that claim false for the default composition.\n */\nimport type { CloudCrypto } from './port';\n\n/** Short, human-typeable pairing code alphabet — no `0/O`, no `1/I` (mirrors the reference server's). */\nconst PAIRING_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';\n\nconst HEX_DIGITS = '0123456789abcdef';\n\nexport function base64UrlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\n/**\n * Decode base64url. Returns `undefined` rather than throwing for input that\n * is not base64url at all — every caller here is verifying attacker-supplied\n * material, where \"not decodable\" and \"does not verify\" must be the same\n * answer.\n */\nexport function base64UrlDecode(value: string): Uint8Array | undefined {\n const padded = value.replaceAll('-', '+').replaceAll('_', '/');\n try {\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n } catch {\n return undefined;\n }\n}\n\nfunction toHex(bytes: Uint8Array): string {\n let out = '';\n for (const byte of bytes) {\n out += HEX_DIGITS[(byte >> 4) & 0xf];\n out += HEX_DIGITS[byte & 0xf];\n }\n return out;\n}\n\n/**\n * WebCrypto's own types are derived from the runtime's `globalThis.crypto`\n * rather than named directly: `CryptoKey`/`SubtleCrypto`/`KeyUsage` are DOM\n * lib globals, and this package compiles without the DOM lib (a Workers build\n * has no DOM either). Deriving keeps the types exact without pulling in a\n * `node:` import or widening `lib`.\n */\nexport type SubtleCryptoLike = typeof globalThis.crypto.subtle;\nexport type CryptoKeyLike = Awaited<ReturnType<SubtleCryptoLike['importKey']>>;\nexport type KeyUsageLike = Parameters<SubtleCryptoLike['importKey']>[4][number];\n\nfunction subtle(): SubtleCryptoLike {\n const webCrypto = globalThis.crypto;\n if (webCrypto?.subtle === undefined) {\n throw new Error('@byok-sdk/cloud requires a WebCrypto implementation on globalThis.crypto');\n }\n return webCrypto.subtle;\n}\n\nexport function createWebCrypto(): CloudCrypto {\n return {\n randomUuid(): string {\n return globalThis.crypto.randomUUID();\n },\n\n randomToken(byteLength: number): string {\n return base64UrlEncode(globalThis.crypto.getRandomValues(new Uint8Array(byteLength)));\n },\n\n randomPairingCode(length: number): string {\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(length));\n let out = '';\n for (const byte of bytes) {\n out += PAIRING_CODE_ALPHABET[byte % PAIRING_CODE_ALPHABET.length];\n }\n return out;\n },\n\n async verifyEd25519(\n publicKeyBase64Url: string,\n message: string | Uint8Array,\n signature: string,\n ): Promise<boolean> {\n const signatureBytes = base64UrlDecode(signature);\n if (signatureBytes === undefined) return false;\n try {\n const key = await subtle().importKey(\n 'jwk',\n { kty: 'OKP', crv: 'Ed25519', x: publicKeyBase64Url },\n { name: 'Ed25519' },\n false,\n ['verify'],\n );\n const messageBytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;\n return await subtle().verify({ name: 'Ed25519' }, key, signatureBytes, messageBytes);\n } catch {\n // A key that will not import is a key that cannot have signed this —\n // same answer as a bad signature, with no distinguishing error.\n return false;\n }\n },\n\n async hmacSha256(secret: Uint8Array, message: string): Promise<string> {\n const key = await subtle().importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n const signature = await subtle().sign('HMAC', key, new TextEncoder().encode(message));\n return base64UrlEncode(new Uint8Array(signature));\n },\n\n async sha256(data: Uint8Array): Promise<string> {\n const digest = await subtle().digest('SHA-256', data);\n return `sha256:${toHex(new Uint8Array(digest))}`;\n },\n\n timingSafeEqual(left: string, right: string): boolean {\n const leftBytes = base64UrlDecode(left);\n const rightBytes = base64UrlDecode(right);\n if (leftBytes === undefined || rightBytes === undefined) return false;\n if (leftBytes.length !== rightBytes.length) return false;\n let diff = 0;\n for (let index = 0; index < leftBytes.length; index += 1) {\n diff |= (leftBytes[index] ?? 0) ^ (rightBytes[index] ?? 0);\n }\n return diff === 0;\n },\n };\n}\n","/**\n * Access tokens for the hosted device surface (docs/protocol.md §6).\n *\n * The token carries the identity TRIPLE — `(deviceId, tenantId, productId)` —\n * and all three legs are lookup keys, never authority: `authenticateBearer`\n * (`bearer.ts`) resolves them against the device directory and answers with\n * the ROW's identity. A token missing a leg is not a partially usable token;\n * it is not a token this deployment minted.\n *\n * {@link TokenSigner} is a port for the same reason `@byok-sdk/server` made it\n * one: a SaaS with an org-wide asymmetric signer or a KMS swaps its own in.\n * The reference implementation below is HS256 over a caller-supplied secret,\n * built on WebCrypto so the package stays runtime-neutral (no `jose`, no\n * `node:crypto`).\n */\nimport type { Clock } from '@byok-sdk/core';\nimport {\n base64UrlDecode,\n base64UrlEncode,\n type CryptoKeyLike,\n type KeyUsageLike,\n} from '../crypto/web-crypto';\n\n/** Access tokens are ~1h, matching the reference server (docs/protocol.md §6.1/§6.2). */\nexport const ACCESS_TOKEN_TTL_SECONDS = 60 * 60;\n\nexport interface AccessTokenClaims {\n readonly deviceId: string;\n /** Unbranded on the wire: the value is only a lookup key until a device row vouches for it. */\n readonly tenantId: string;\n readonly productId: string;\n}\n\nexport interface TokenSigner {\n sign(claims: AccessTokenClaims, expiresInSeconds: number): Promise<string>;\n /** Claims for a valid, unexpired token, or `undefined` for invalid/expired/malformed — no reason is ever reported. */\n verify(token: string): Promise<AccessTokenClaims | undefined>;\n}\n\ninterface TokenPayload {\n readonly deviceId: unknown;\n readonly tenantId: unknown;\n readonly productId: unknown;\n readonly exp: unknown;\n}\n\nfunction encodeSegment(value: unknown): string {\n return base64UrlEncode(new TextEncoder().encode(JSON.stringify(value)));\n}\n\n/**\n * HS256 JWT signer over `secret`.\n *\n * `clock` is injected rather than read off `Date.now()` so expiry is testable\n * and so the whole package keeps a single notion of \"now\" (the same one the\n * stores use for TTLs).\n */\nexport function createHmacTokenSigner(secret: Uint8Array, clock: Clock): TokenSigner {\n async function signingKey(usage: KeyUsageLike): Promise<CryptoKeyLike> {\n return globalThis.crypto.subtle.importKey('raw', secret, { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);\n }\n\n async function signature(signingInput: string): Promise<string> {\n const key = await signingKey('sign');\n const bytes = await globalThis.crypto.subtle.sign('HMAC', key, new TextEncoder().encode(signingInput));\n return base64UrlEncode(new Uint8Array(bytes));\n }\n\n return {\n async sign(claims, expiresInSeconds) {\n const issuedAt = Math.floor(clock.now().getTime() / 1000);\n const header = encodeSegment({ alg: 'HS256', typ: 'JWT' });\n const payload = encodeSegment({\n deviceId: claims.deviceId,\n tenantId: claims.tenantId,\n productId: claims.productId,\n iat: issuedAt,\n exp: issuedAt + expiresInSeconds,\n });\n const signingInput = `${header}.${payload}`;\n return `${signingInput}.${await signature(signingInput)}`;\n },\n\n async verify(token) {\n const parts = token.split('.');\n if (parts.length !== 3) return undefined;\n const [header, payload, provided] = parts as [string, string, string];\n\n const key = await signingKey('verify');\n const providedBytes = base64UrlDecode(provided);\n if (providedBytes === undefined) return undefined;\n const ok = await globalThis.crypto.subtle.verify(\n 'HMAC',\n key,\n providedBytes,\n new TextEncoder().encode(`${header}.${payload}`),\n );\n if (!ok) return undefined;\n\n const headerBytes = base64UrlDecode(header);\n const payloadBytes = base64UrlDecode(payload);\n if (headerBytes === undefined || payloadBytes === undefined) return undefined;\n\n let decodedHeader: unknown;\n let decodedPayload: TokenPayload;\n try {\n decodedHeader = JSON.parse(new TextDecoder().decode(headerBytes));\n decodedPayload = JSON.parse(new TextDecoder().decode(payloadBytes)) as TokenPayload;\n } catch {\n return undefined;\n }\n\n const alg = (decodedHeader as { alg?: unknown } | null)?.alg;\n if (alg !== 'HS256') return undefined;\n\n const { deviceId, tenantId, productId, exp } = decodedPayload;\n if (typeof deviceId !== 'string' || typeof tenantId !== 'string' || typeof productId !== 'string') {\n return undefined;\n }\n if (typeof exp !== 'number' || clock.now().getTime() / 1000 >= exp) return undefined;\n\n return { deviceId, tenantId, productId };\n },\n };\n}\n","/**\n * The one nonce-signature check on the hosted surface (docs/protocol.md §6.2).\n *\n * S1 (GAP-004): a device signs `byok-nonce-v1\\n` + nonce, never the bare\n * nonce. The device key is a long-lived identity key that later planes (S6\n * device proof) also sign structured messages with; without a domain tag, a\n * signature produced for one purpose is a valid signature for another.\n *\n * Applying the domain HERE rather than at the call site is the point: there\n * is exactly one place that decides what a device signature over a nonce\n * means, so no route can be written that accepts the undomained form. There\n * is deliberately no dual mode and no grace window — a device on the old\n * encoding re-pairs.\n *\n * The domain literal itself lives in `@byok-sdk/core` (`src/pairing.ts`): the\n * daemon must not be able to tell self-hosted from hosted, and three copies\n * each commented as byte-identical to the other two were a drift hazard, not a\n * design. Importing the constant from the package all three ends already depend\n * on is not the same as importing the server — parity of *behavior* is still\n * asserted by behavior tests, and this package still has no `@byok-sdk/server`\n * edge. Re-exported so this module's public surface is unchanged.\n */\nimport { NONCE_SIGNING_DOMAIN } from '@byok-sdk/core';\nimport type { CloudCrypto } from '../crypto/port';\n\nexport { NONCE_SIGNING_DOMAIN } from '@byok-sdk/core';\n\nexport function verifyNonceSignature(\n crypto: CloudCrypto,\n devicePublicKey: string,\n nonce: string,\n signature: string,\n): Promise<boolean> {\n // `CloudCrypto.verifyEd25519` takes the message as a string and encodes it as\n // UTF-8 itself, so the concatenation happens here rather than through core's\n // `nonceSigningBytes` — same bytes, one encoding step instead of two.\n return crypto.verifyEd25519(devicePublicKey, NONCE_SIGNING_DOMAIN + nonce, signature);\n}\n","/**\n * The auth plane: everything the three pre-tenant routes (`/byok/pair`,\n * `/byok/challenge`, `/byok/token`) need, and nothing else.\n *\n * Those three routes cannot take a {@link TenantStores} facade — they run\n * BEFORE a principal exists, which is exactly why they are the surface where a\n * tenant boundary is easiest to lose. So instead of handing them naked stores\n * and trusting each handler to pass the right tenant, this module owns every\n * tenant-carrying call they make and hands back operations that name no tenant\n * at all:\n *\n * - a pairing code redeems into a REGISTERED device row in one step, so the\n * claims never sit in handler scope as a tenant a handler could substitute;\n * - a device resolves to a row (the pre-tenant lookup, §6.2's pinned wire\n * contract), and unknown/revoked collapse to one answer;\n * - nonce issue/validate/consume and token minting take that ROW, so the\n * tenant they act on is the row's, by construction.\n */\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type { CloudCrypto } from '../crypto/port';\nimport type { CloudStores, DeviceRecord, PairingCodeInfo } from '../stores/ports';\nimport { ACCESS_TOKEN_TTL_SECONDS, type TokenSigner } from './tokens';\nimport { verifyNonceSignature } from './verify';\n\n/** ~10min, matching the reference server's pairing-code lifetime. */\nexport const PAIRING_CODE_TTL_MS = 10 * 60 * 1000;\n\nconst PAIRING_CODE_LENGTH = 8;\n\n/** The paired identity key is the first and only proof key in S6. */\nexport const DEVICE_IDENTITY_PROOF_KEY_ID = 'identity';\nexport const DEVICE_IDENTITY_PROOF_KEY_EPOCH = 0;\n\nexport interface PairInput {\n readonly pairingCode: string;\n readonly deviceName: string;\n readonly devicePublicKey: string;\n}\n\nexport interface MintedAccessToken {\n readonly accessToken: string;\n readonly expiresAt: string;\n}\n\nexport interface AuthPlane {\n /** Host control plane: mint a single-use code carrying the tenant/product a device will land in. */\n createPairingCode(tenant: TenantId, input: { readonly productId: string; readonly ttlMs?: number }): Promise<PairingCodeInfo>;\n /**\n * Redeem a code and register the device it pairs, in one step. `undefined`\n * for a code that is unknown, expired, or already used — one answer for all\n * three. Single-use redemption is what makes this exclusive: a second\n * redeem never reaches the row write.\n */\n redeemAndRegister(input: PairInput): Promise<DeviceRecord | undefined>;\n /** The pre-tenant device lookup §6.2's wire contract forces. `undefined` for unknown AND revoked alike — no existence oracle. */\n resolveDevice(deviceId: string): Promise<DeviceRecord | undefined>;\n issueNonce(device: DeviceRecord): Promise<string>;\n validateNonce(device: DeviceRecord, nonce: string): Promise<boolean>;\n /** Burn the nonce. Called only on a fully verified request (§6.2). */\n consumeNonce(device: DeviceRecord, nonce: string): Promise<void>;\n /** Domain-separated (`byok-nonce-v1\\n`) — see `verify.ts`. A raw signature over the bare nonce is invalid, with no second accepted form. */\n verifySignature(device: DeviceRecord, nonce: string, signature: string): Promise<boolean>;\n mintAccessToken(device: DeviceRecord): Promise<MintedAccessToken>;\n}\n\nexport interface AuthPlaneDeps {\n readonly stores: CloudStores;\n readonly crypto: CloudCrypto;\n readonly clock: Clock;\n readonly tokenSigner: TokenSigner;\n readonly accessTokenTtlSeconds?: number;\n}\n\nexport function createAuthPlane(deps: AuthPlaneDeps): AuthPlane {\n const { stores, crypto, clock, tokenSigner } = deps;\n const ttlSeconds = deps.accessTokenTtlSeconds ?? ACCESS_TOKEN_TTL_SECONDS;\n\n return {\n async createPairingCode(tenant, input) {\n const expiresAt = new Date(clock.now().getTime() + (input.ttlMs ?? PAIRING_CODE_TTL_MS)).toISOString();\n return stores.pairingCodes.issue(tenant, {\n code: crypto.randomPairingCode(PAIRING_CODE_LENGTH),\n productId: input.productId,\n expiresAt,\n });\n },\n\n async redeemAndRegister(input) {\n const claims = await stores.pairingCodes.redeem(input.pairingCode);\n if (claims === undefined) return undefined;\n // The redeemed code's claims are the ONLY source of the device's\n // tenant/product — `PairRequest` carries neither, so a device can never\n // choose where it lands.\n return stores.devices.register(claims.tenantId, {\n productId: claims.productId,\n deviceId: `dev_${crypto.randomUuid()}`,\n deviceName: input.deviceName,\n devicePublicKey: input.devicePublicKey,\n proofKeyId: DEVICE_IDENTITY_PROOF_KEY_ID,\n proofKeyEpoch: DEVICE_IDENTITY_PROOF_KEY_EPOCH,\n });\n },\n\n async resolveDevice(deviceId) {\n const device = await stores.devices.resolveByDeviceId(deviceId);\n if (device === undefined || device.revoked) return undefined;\n return device;\n },\n\n issueNonce(device) {\n return stores.nonces.issue(device.tenantId, device.deviceId);\n },\n\n validateNonce(device, nonce) {\n return stores.nonces.validate(device.tenantId, device.deviceId, nonce);\n },\n\n consumeNonce(device, nonce) {\n return stores.nonces.markUsed(device.tenantId, nonce);\n },\n\n verifySignature(device, nonce, signature) {\n return verifyNonceSignature(crypto, device.devicePublicKey, nonce, signature);\n },\n\n async mintAccessToken(device) {\n const accessToken = await tokenSigner.sign(\n { deviceId: device.deviceId, tenantId: device.tenantId, productId: device.productId },\n ttlSeconds,\n );\n return {\n accessToken,\n expiresAt: new Date(clock.now().getTime() + ttlSeconds * 1000).toISOString(),\n };\n },\n };\n}\n","/**\n * The hosted capability declaration (ADR-010).\n *\n * A client learns what a deployment supports by READING a declaration, never\n * by probing an endpoint and interpreting 404/405/501. `@byok-sdk/core` owns the\n * declaration shape and the `hasCapability`/`assertCapability` enforcement\n * point; what lives here is the hosted vocabulary and the mapping from a\n * capability name to the routes that provide it.\n *\n * `GET /byok/capabilities` is a hosted-only route: it is not part of the\n * frozen device wire contract, `@byok-sdk/protocol` is untouched by it, and the\n * daemon does not consume it yet (that lands in a later slice). What it\n * already does here is drive route selection — a deployment that does not\n * declare `blobs.presigned` does not mount the grant routes at all, and one\n * that does not declare `blobs.contentproxy` does not mount the two `/content`\n * routes, so the declaration and the surface cannot disagree.\n */\nimport { CapabilityDeclarationSchema, hasCapability, type CapabilityDeclaration } from '@byok-sdk/core';\n\n/** The hosted capability vocabulary this package knows how to serve. */\nexport const CLOUD_CAPABILITIES = {\n /** `GET /byok/events` long-poll receive (§8). */\n eventsLongPoll: 'events.longpoll',\n /** `POST /byok/messages` batched send (§8.2). */\n messagesBatch: 'messages.batch',\n /** The three bearer-authed blob routes: reserve/grant, explicit finalize, committed-only download (§7). */\n blobsPresigned: 'blobs.presigned',\n /**\n * The two presigned `/byok/blobs/:id/content` routes — cloud carrying the\n * bytes itself.\n *\n * Split out of `blobs.presigned` because it was one capability describing two\n * separable facts. A composition whose bytes live in object storage mints\n * grants (`blobs.presigned`) but has no byte-proxy path at all, and saying so\n * by declaration is ADR-010's whole posture: a client reads what a deployment\n * serves, it never probes a `/content` route and interprets the status code.\n *\n * Spelled all-lowercase because core's declaration schema pins capability\n * names to `/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/` — the same reason the sibling\n * above reads `events.longpoll` and not `events.longPoll`.\n */\n blobsContentProxy: 'blobs.contentproxy',\n /** Board list/claim/unclaim/status routes. Polling is first-class under this declaration. */\n boardCoordination: 'board.coordination',\n /** Additional SSE transport for the same board read model. */\n boardSse: 'board.sse',\n /** Device-scoped five-level presence publication. */\n presenceHints: 'presence.hints',\n /** Bounded task activity batch publication. */\n activityTail: 'activity.tail',\n /** Request-bound device proof record manifest/read/write surface (S6). */\n truthRecords: 'truth.records',\n /**\n * Tenant-scoped skill pack distribution: the manifest list plus the per-file\n * content route a paired device installs from.\n *\n * Hosted HTTP on purpose. A pack is DECLARATIVE CONTENT a device pulls after\n * reading this declaration — not a message — so `@byok-sdk/protocol` gains\n * nothing from it and the frozen v1 envelope stays untouched. Composition-\n * bound like `truth.records`: a deployment that declares it without supplying\n * a `SkillPackStore` is refused at construction rather than publishing two\n * routes it would then 404.\n */\n skillPacks: 'skills.pack',\n} as const;\n\nexport type CloudCapability = (typeof CLOUD_CAPABILITIES)[keyof typeof CLOUD_CAPABILITIES];\n\n/** The wire DTO for `GET /byok/capabilities` — core's shape, bound to a cloud-owned route. */\nexport const CapabilitiesResponseSchema = CapabilityDeclarationSchema;\nexport type CapabilitiesResponse = CapabilityDeclaration;\n\nexport interface FullCapabilityDeclarationOptions {\n /**\n * Composition-bound capabilities require an explicit application authority.\n * `truth.records` is omitted by default because the standard in-memory\n * composition cannot truthfully promise a cross-store atomic commit.\n */\n readonly includeTruthRecords?: boolean;\n /**\n * `skills.pack` is omitted for the same reason: the standard composition is\n * given no `SkillPackStore`, and a default-on declaration would make every\n * existing deployment refuse to construct.\n */\n readonly includeSkillPacks?: boolean;\n}\n\n/** Every capability the standard composition can serve, plus explicitly wired composition-bound ones. */\nexport function fullCapabilityDeclaration(\n version = 1,\n options: FullCapabilityDeclarationOptions = {},\n): CapabilityDeclaration {\n return {\n schema: 'byok-capabilities-v1',\n version,\n capabilities: Object.values(CLOUD_CAPABILITIES).filter((capability) => {\n if (capability === CLOUD_CAPABILITIES.truthRecords) return options.includeTruthRecords === true;\n if (capability === CLOUD_CAPABILITIES.skillPacks) return options.includeSkillPacks === true;\n return true;\n }),\n };\n}\n\nexport function declares(declaration: CapabilityDeclaration, capability: CloudCapability): boolean {\n return hasCapability(declaration, capability);\n}\n","/**\n * The one error taxonomy for `@byok-sdk/cloud`.\n *\n * Same idiom as `@byok-sdk/core`'s `errors.ts`: one class, code-based branching,\n * so a composition maps failures onto HTTP with a code table instead of an\n * `instanceof` chain. Cloud does not re-export core's codes — a cloud error is\n * about the hosted surface (a store contract the composition broke, a\n * declaration the host mis-configured), and core errors travel up unchanged.\n */\n\nexport const CLOUD_ERROR_CODES = {\n /** A pairing code that is unknown, expired, or already redeemed (§6.1). */\n pairing_code_invalid: 'pairing_code_invalid',\n /** The composition handed a device row whose tenant is not a mintable `TenantId`. */\n device_tenant_invalid: 'device_tenant_invalid',\n /**\n * The mailbox committed a row `seq` that disagrees with the delivery `seq`\n * its body factory baked into the envelope. Loud rather than silent: those\n * two numbers ARE the daemon's redelivery cursor.\n */\n mailbox_seq_mismatch: 'mailbox_seq_mismatch',\n /** A capability declaration the host supplied that core refused. */\n capability_declaration_invalid: 'capability_declaration_invalid',\n /**\n * The declaration names a capability this composition cannot serve, so the\n * deployment would publish a surface it does not have (ADR-010).\n *\n * Construction-time and fatal. A client learns what a deployment supports by\n * READING the declaration and is entitled to act on it without probing, so a\n * declaration that over-states is not a degraded deployment — it is a\n * deployment whose one honest interface lies.\n */\n capability_over_declared: 'capability_over_declared',\n /** Host-supplied board labels or coordination input exceeded the explicit contract. */\n coordination_input_invalid: 'coordination_input_invalid',\n /**\n * A terminal receipt whose stored body is not a terminal envelope — either\n * undecodable or a non-terminal type. Whatever wrote that row broke the\n * receipt-store contract, so the typed read model fails closed instead of\n * projecting a best-effort shape.\n */\n terminal_receipt_unreadable: 'terminal_receipt_unreadable',\n /** A progress/activity batch exceeded the configured event or byte ceiling. */\n activity_batch_too_large: 'activity_batch_too_large',\n} as const;\n\nexport type CloudErrorCode = (typeof CLOUD_ERROR_CODES)[keyof typeof CLOUD_ERROR_CODES];\n\nexport class ByokCloudError extends Error {\n public readonly code: CloudErrorCode;\n\n constructor(code: CloudErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ByokCloudError';\n this.code = code;\n }\n}\n\nexport function isCloudError(value: unknown, code?: CloudErrorCode): value is ByokCloudError {\n if (!(value instanceof ByokCloudError)) return false;\n return code === undefined || value.code === code;\n}\n","import { tenantKey, type TenantId } from '@byok-sdk/core';\nimport { AgentEventOrUnknownSchema, type AgentEventOrUnknown } from '@byok-sdk/protocol';\nimport { z } from 'zod';\nimport { ByokCloudError } from './errors';\n\nexport const DEFAULT_ACTIVITY_CAPACITY = 50;\n\nconst ActivityTaskIdSchema = z.string().min(1).max(200);\nconst SourceEnvelopeIdSchema = z\n .string()\n .max(200)\n .regex(/\\S/, 'sourceEnvelopeId must not be blank');\n\nexport const ActivityAppendRequestSchema = z.object({\n taskId: ActivityTaskIdSchema,\n sourceEnvelopeId: SourceEnvelopeIdSchema,\n batchSeq: z.number().int().nonnegative(),\n events: z.array(AgentEventOrUnknownSchema).min(1),\n dropped: z.number().int().nonnegative(),\n});\n\nexport const TimelineEventSchema = z.object({\n taskId: ActivityTaskIdSchema,\n sourceEnvelopeId: SourceEnvelopeIdSchema,\n batchSeq: z.number().int().nonnegative(),\n eventIndex: z.number().int().nonnegative(),\n receivedAt: z.iso.datetime(),\n event: AgentEventOrUnknownSchema,\n});\n\nexport type TimelineEvent = Readonly<z.infer<typeof TimelineEventSchema>>;\n\nexport interface ActivityCursor {\n readonly batchSeq: number;\n readonly eventIndex: number;\n}\n\nexport interface ActivityTail {\n readonly tenantId: TenantId;\n readonly taskId: string;\n readonly entries: readonly TimelineEvent[];\n readonly cursor?: ActivityCursor;\n readonly dropped: number;\n readonly capacity: number;\n readonly expiresAt: string;\n}\n\nexport interface ActivityAppendInput {\n readonly taskId: string;\n readonly sourceEnvelopeId: string;\n readonly batchSeq: number;\n readonly events: readonly AgentEventOrUnknown[];\n readonly dropped: number;\n readonly ttlMs: number;\n readonly capacity?: number;\n}\n\nexport interface ActivityStore {\n append(tenant: TenantId, input: ActivityAppendInput): Promise<ActivityTail>;\n read(tenant: TenantId, taskId: string): Promise<ActivityTail | undefined>;\n}\n\nexport function validateActivityAppend(input: ActivityAppendInput): number {\n if (!Number.isFinite(input.ttlMs) || input.ttlMs <= 0) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Activity ttl must be a positive number of milliseconds, received ${String(input.ttlMs)}.`,\n );\n }\n const capacity = input.capacity ?? DEFAULT_ACTIVITY_CAPACITY;\n if (!Number.isSafeInteger(capacity) || capacity <= 0) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Activity capacity must be a positive integer, received ${String(capacity)}.`,\n );\n }\n const parsed = ActivityAppendRequestSchema.safeParse(input);\n if (!parsed.success) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Activity batches require stable source identity, order, at least one valid event, and a non-negative dropped count.',\n );\n }\n return capacity;\n}\n\nexport function projectTimelineEvents(\n input: ActivityAppendInput,\n receivedAt: string,\n): readonly TimelineEvent[] {\n return input.events.map((event, eventIndex) =>\n TimelineEventSchema.parse({\n taskId: input.taskId,\n sourceEnvelopeId: input.sourceEnvelopeId,\n batchSeq: input.batchSeq,\n eventIndex,\n receivedAt,\n event,\n }),\n );\n}\n\nexport function parseTimelineEvents(value: unknown): readonly TimelineEvent[] {\n return z.array(TimelineEventSchema).parse(value) as readonly TimelineEvent[];\n}\n\nexport function compareTimelineEvents(left: TimelineEvent, right: TimelineEvent): number {\n return left.batchSeq - right.batchSeq || left.eventIndex - right.eventIndex;\n}\n\nexport function activityCursor(\n entries: readonly TimelineEvent[],\n): ActivityCursor | undefined {\n const last = entries.at(-1);\n return last === undefined ? undefined : { batchSeq: last.batchSeq, eventIndex: last.eventIndex };\n}\n\nexport function activityTailKey(tenant: TenantId, taskId: string): string {\n return tenantKey(tenant, taskId);\n}\n","import type { AgentEventOrUnknown } from '@byok-sdk/protocol';\nimport {\n DEFAULT_ACTIVITY_CAPACITY,\n validateActivityAppend,\n type ActivityAppendInput,\n type ActivityTail,\n} from './activity';\nimport { ByokCloudError } from './errors';\nimport type { TenantBoundActivity } from './tenant-stores';\n\nexport const DEFAULT_BOARD_CHANNEL_MAX_BYTES = 128;\nexport const DEFAULT_BOARD_TITLE_MAX_BYTES = 512;\nexport const DEFAULT_ACTIVITY_MAX_EVENTS = 50;\nexport const DEFAULT_ACTIVITY_MAX_BYTES = 64 * 1024;\nexport { DEFAULT_ACTIVITY_CAPACITY } from './activity';\nexport const DEFAULT_ACTIVITY_TTL_MS = 10 * 60_000;\nexport const DEFAULT_PRESENCE_TTL_MS = 90_000;\nexport const DEFAULT_PRESENCE_MINIMUM_INTERVAL_MS = 5_000;\nexport const DEFAULT_PRESENCE_DETAIL_MAX_BYTES = 512;\n\nconst encoder = new TextEncoder();\n\nexport interface ActivityBounds {\n readonly maxEvents: number;\n readonly maxBytes: number;\n readonly capacity: number;\n readonly ttlMs: number;\n}\n\nexport const DEFAULT_ACTIVITY_BOUNDS: ActivityBounds = {\n maxEvents: DEFAULT_ACTIVITY_MAX_EVENTS,\n maxBytes: DEFAULT_ACTIVITY_MAX_BYTES,\n capacity: DEFAULT_ACTIVITY_CAPACITY,\n ttlMs: DEFAULT_ACTIVITY_TTL_MS,\n};\n\nexport function assertBoardLabels(\n channel: string,\n title: string,\n limits: { readonly channelMaxBytes: number; readonly titleMaxBytes: number },\n): void {\n if (channel.length === 0 || encoder.encode(channel).length > limits.channelMaxBytes) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Board channel must contain 1..${limits.channelMaxBytes} UTF-8 bytes.`,\n );\n }\n if (title.length === 0 || encoder.encode(title).length > limits.titleMaxBytes) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Board title must contain 1..${limits.titleMaxBytes} UTF-8 bytes.`,\n );\n }\n}\n\nexport function validateActivityEvents(\n events: readonly AgentEventOrUnknown[],\n dropped: number,\n bounds: ActivityBounds,\n): void {\n if (!Number.isSafeInteger(dropped) || dropped < 0) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Activity dropped must be a non-negative integer.',\n );\n }\n if (events.length === 0 || events.length > bounds.maxEvents) {\n throw new ByokCloudError(\n 'activity_batch_too_large',\n `Activity batch must contain 1..${bounds.maxEvents} events.`,\n );\n }\n const encoded = JSON.stringify(events);\n if (encoder.encode(encoded).length > bounds.maxBytes) {\n throw new ByokCloudError(\n 'activity_batch_too_large',\n `Activity batch exceeds ${bounds.maxBytes} UTF-8 bytes.`,\n );\n }\n}\n\nexport function validateActivityBatch(\n input: Omit<ActivityAppendInput, 'ttlMs' | 'capacity'>,\n bounds: ActivityBounds,\n): void {\n validateActivityEvents(input.events, input.dropped, bounds);\n validateActivityAppend({ ...input, ttlMs: bounds.ttlMs, capacity: bounds.capacity });\n}\n\nexport async function appendActivityEvents(\n activity: TenantBoundActivity,\n input: {\n readonly taskId: string;\n readonly sourceEnvelopeId: string;\n readonly batchSeq: number;\n readonly events: readonly AgentEventOrUnknown[];\n readonly dropped: number;\n },\n bounds: ActivityBounds,\n): Promise<ActivityTail> {\n validateActivityBatch(input, bounds);\n return activity.append({\n taskId: input.taskId,\n sourceEnvelopeId: input.sourceEnvelopeId,\n batchSeq: input.batchSeq,\n events: input.events,\n dropped: input.dropped,\n ttlMs: bounds.ttlMs,\n capacity: bounds.capacity,\n });\n}\n","/**\n * The single bearer check every device-facing route shares.\n *\n * S1 shape, reproduced exactly: the token's `(tenantId, deviceId, productId)`\n * are LOOKUP KEYS, and the ROW that comes back is the authority. A token for a\n * device that no longer exists, one whose tenant does not own that device, one\n * whose product disagrees with the row, one for a revoked device, an expired\n * token, and a malformed tenant id in the claims all fail identically here and\n * are indistinguishable to the caller. There is deliberately no \"which of\n * those was it\" signal to hand back, so no route can turn a 401 into a\n * cross-tenant existence oracle.\n *\n * The returned {@link DevicePrincipal} is core's, carrying a minted\n * `TenantId` — which is what makes it the only legal input to\n * `tenantStoresFor` (`../tenant-stores.ts`).\n */\nimport { isTenantId, tenantId, type DevicePrincipal } from '@byok-sdk/core';\nimport type { DeviceDirectory } from '../stores/ports';\nimport type { TokenSigner } from './tokens';\n\nexport interface BearerAuthDeps {\n readonly tokenSigner: TokenSigner;\n readonly devices: DeviceDirectory;\n}\n\nexport function extractBearerToken(header: string | undefined): string | undefined {\n if (header === undefined) return undefined;\n const match = /^Bearer\\s+(.+)$/i.exec(header);\n return match?.[1];\n}\n\nexport async function authenticateBearer(\n header: string | undefined,\n deps: BearerAuthDeps,\n): Promise<DevicePrincipal | undefined> {\n const token = extractBearerToken(header);\n if (token === undefined) return undefined;\n\n const claims = await deps.tokenSigner.verify(token);\n if (claims === undefined) return undefined;\n // The claim is a bare string until it is minted; a tenant id that core would\n // refuse is simply not a tenant this deployment ever issued a token for.\n if (!isTenantId(claims.tenantId)) return undefined;\n\n const device = await deps.devices.get(tenantId(claims.tenantId), claims.deviceId);\n if (device === undefined || device.revoked) return undefined;\n if (device.productId !== claims.productId) return undefined;\n\n return {\n kind: 'device',\n tenantId: device.tenantId,\n productId: device.productId,\n deviceId: device.deviceId,\n };\n}\n","/**\n * Layer 2 of the six-layer isolation model (§12.6.2) — the tenant-closed\n * facade a handler actually receives.\n *\n * `@byok-sdk/core`'s `stores.ts` deliberately left this undefined: it is shaped by\n * how handlers are written, and the first handlers live here. This is that\n * shape, and the two properties it exists to enforce are:\n *\n * 1. **It can only be built from an authenticated principal.** {@link\n * tenantStoresFor} is the only constructor, and its first parameter is a\n * `Principal` — a value that only `authenticateBearer` (`auth/bearer.ts`)\n * mints, and only from a device ROW. There is no path from a device-supplied\n * string to a facade.\n * 2. **No handler ever passes a `TenantId` again.** Every method below has the\n * tenant pre-applied, so a handler cannot read `principal.tenantId` off one\n * principal and hand a different tenant to a store. Grep the handler tree\n * for `TenantId` and you will not find one — asserted by\n * `src/__tests__/constraints.test.ts`.\n *\n * The three pre-tenant store methods (`resolveByDeviceId`, `redeem`, the\n * presigned blob calls) are deliberately absent from this surface: a\n * device-facing handler must not be able to reach them.\n */\nimport {\n principalTenant,\n type BoardClaimInput,\n type BoardItem,\n type BoardItemInput,\n type BoardListQuery,\n type BoardPage,\n type BoardStatusUpdateInput,\n type BoardUnclaimInput,\n type CoreStores,\n type MailboxAdvanceCursorInput,\n type MailboxAppendInput,\n type MailboxCursorState,\n type MailboxMessage,\n type MailboxPage,\n type MailboxReadQuery,\n type Principal,\n type PresenceHint,\n type PresenceHintInput,\n type StorageFinalizeInput,\n type StorageFinalizeResult,\n type StorageReservation,\n type StorageReservationInput,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { ActivityAppendInput, ActivityTail } from './activity';\nimport type {\n ApprovalTimelineAppendInput,\n ApprovalTimelineTail,\n} from './approval-timeline';\nimport type {\n BlobObservation,\n CloudStores,\n DeviceRecord,\n RequestReceipt,\n TaskAttempt,\n TaskAttemptStatus,\n} from './stores/ports';\n\nexport interface TenantBoundMailbox {\n append(input: MailboxAppendInput): Promise<MailboxMessage>;\n /** Pure read. Never advances the cursor — the daemon's next poll is the only ack. */\n readAfter(query: MailboxReadQuery): Promise<MailboxPage>;\n advanceCursor(input: MailboxAdvanceCursorInput): Promise<MailboxCursorState>;\n readCursor(deviceId: string): Promise<MailboxCursorState>;\n}\n\nexport interface TenantBoundBoard {\n create(input: BoardItemInput): Promise<BoardItem>;\n get(itemId: string): Promise<BoardItem | undefined>;\n list(query: BoardListQuery): Promise<BoardPage>;\n claim(input: BoardClaimInput): Promise<BoardItem>;\n unclaim(input: BoardUnclaimInput): Promise<BoardItem>;\n updateStatus(input: BoardStatusUpdateInput): Promise<BoardItem>;\n}\n\nexport interface TenantBoundPresence {\n publish(input: PresenceHintInput): Promise<PresenceHint>;\n read(deviceId: string): Promise<PresenceHint | undefined>;\n list(): Promise<readonly PresenceHint[]>;\n}\n\nexport interface TenantBoundActivity {\n append(input: ActivityAppendInput): Promise<ActivityTail>;\n read(taskId: string): Promise<ActivityTail | undefined>;\n}\n\nexport interface TenantBoundApprovalTimeline {\n append(input: ApprovalTimelineAppendInput): Promise<ApprovalTimelineTail>;\n read(taskId: string): Promise<ApprovalTimelineTail | undefined>;\n}\n\nexport interface TenantBoundDevices {\n get(deviceId: string): Promise<DeviceRecord | undefined>;\n list(): Promise<readonly DeviceRecord[]>;\n revoke(deviceId: string): Promise<void>;\n}\n\nexport interface TenantBoundTaskAttempts {\n open(input: { readonly taskId: string; readonly deviceId: string }): Promise<TaskAttempt>;\n get(taskId: string): Promise<TaskAttempt | undefined>;\n claim(input: { readonly taskId: string; readonly deviceId: string }): Promise<TaskAttempt | undefined>;\n recordStatus(input: { readonly taskId: string; readonly status: TaskAttemptStatus }): Promise<TaskAttempt | undefined>;\n}\n\nexport interface TenantBoundDedup {\n checkAndRecord(deviceId: string, envelopeId: string): Promise<boolean>;\n}\n\nexport interface TenantBoundReceipts {\n record(input: { readonly key: string; readonly body: string }): Promise<{\n readonly receipt: RequestReceipt;\n readonly created: boolean;\n }>;\n get(key: string): Promise<RequestReceipt | undefined>;\n}\n\nexport interface TenantBoundBlobs {\n createUpload(reservation: StorageReservation): Promise<{ readonly blobId: string; readonly uploadUrl: string }>;\n observeUpload(blobId: string, reservation: StorageReservation): Promise<BlobObservation | undefined>;\n getDownloadUrl(blobId: string): Promise<string | undefined>;\n}\n\nexport interface TenantBoundQuota {\n readReservation(reservationId: string): Promise<StorageReservation | undefined>;\n reserve(input: StorageReservationInput): Promise<StorageReservation>;\n finalizeReservation(input: StorageFinalizeInput): Promise<StorageFinalizeResult>;\n abortReservation(reservationId: string): Promise<StorageReservation>;\n}\n\nexport interface TenantBoundRateLimiter {\n consume(deviceId: string): Promise<boolean>;\n}\n\nexport interface TenantStores {\n readonly tenant: TenantId;\n readonly principal: Principal;\n readonly mailbox: TenantBoundMailbox;\n readonly board: TenantBoundBoard;\n readonly presence: TenantBoundPresence;\n readonly activity: TenantBoundActivity;\n readonly approvals: TenantBoundApprovalTimeline;\n readonly devices: TenantBoundDevices;\n readonly tasks: TenantBoundTaskAttempts;\n readonly dedup: TenantBoundDedup;\n readonly receipts: TenantBoundReceipts;\n readonly blobs: TenantBoundBlobs;\n readonly quota: TenantBoundQuota;\n readonly rateLimiter: TenantBoundRateLimiter;\n}\n\n/** Every naked store a composition supplies. Only {@link tenantStoresFor} reads this. */\nexport interface CloudRootStores {\n readonly core: CoreStores;\n readonly cloud: CloudStores;\n}\n\nexport function tenantStoresFor(principal: Principal, root: CloudRootStores): TenantStores {\n const tenant = principalTenant(principal);\n const { core, cloud } = root;\n\n return {\n tenant,\n principal,\n mailbox: {\n append: (input) => core.mailbox.append(tenant, input),\n readAfter: (query) => core.mailbox.readAfter(tenant, query),\n advanceCursor: (input) => core.mailbox.advanceCursor(tenant, input),\n readCursor: (deviceId) => core.mailbox.readCursor(tenant, deviceId),\n },\n board: {\n create: (input) => core.board.create(tenant, input),\n get: (itemId) => core.board.get(tenant, itemId),\n list: (query) => core.board.list(tenant, query),\n claim: (input) => core.board.claim(tenant, input),\n unclaim: (input) => core.board.unclaim(tenant, input),\n updateStatus: (input) => core.board.updateStatus(tenant, input),\n },\n presence: {\n publish: (input) => core.presence.publish(tenant, input),\n read: (deviceId) => core.presence.read(tenant, deviceId),\n list: () => core.presence.list(tenant),\n },\n activity: {\n append: (input) => cloud.activity.append(tenant, input),\n read: (taskId) => cloud.activity.read(tenant, taskId),\n },\n approvals: {\n append: (input) => cloud.approvals.append(tenant, input),\n read: (taskId) => cloud.approvals.read(tenant, taskId),\n },\n devices: {\n get: (deviceId) => cloud.devices.get(tenant, deviceId),\n list: () => cloud.devices.list(tenant),\n revoke: (deviceId) => cloud.devices.revoke(tenant, deviceId),\n },\n tasks: {\n open: (input) => cloud.tasks.open(tenant, input),\n get: (taskId) => cloud.tasks.get(tenant, taskId),\n claim: (input) => cloud.tasks.claim(tenant, input),\n recordStatus: (input) => cloud.tasks.recordStatus(tenant, input),\n },\n dedup: {\n checkAndRecord: (deviceId, envelopeId) => cloud.dedup.checkAndRecord(tenant, deviceId, envelopeId),\n },\n receipts: {\n record: (input) => cloud.receipts.record(tenant, input),\n get: (key) => cloud.receipts.get(tenant, key),\n },\n blobs: {\n createUpload: (reservation) => cloud.blobs.createUpload(tenant, reservation),\n observeUpload: (blobId, reservation) => cloud.blobs.observeUpload(tenant, blobId, reservation),\n getDownloadUrl: (blobId) => cloud.blobs.getDownloadUrl(tenant, blobId),\n },\n quota: {\n readReservation: (reservationId) => core.quota.readReservation(tenant, reservationId),\n reserve: (input) => core.quota.reserve(tenant, input),\n finalizeReservation: (input) => core.quota.finalizeReservation(tenant, input),\n abortReservation: (reservationId) => core.quota.abortReservation(tenant, reservationId),\n },\n rateLimiter: {\n consume: (deviceId) => cloud.rateLimiter.consume(tenant, deviceId),\n },\n };\n}\n","/**\n * The two things every device-facing handler starts from: a tolerant JSON body\n * read, and the bearer -> principal -> tenant-closed-facade step.\n *\n * Once {@link authenticateDevice} has answered, a handler holds a\n * `TenantStores` and a `DevicePrincipal` and never sees a `TenantId` again.\n */\nimport type { Context } from 'hono';\nimport type { DevicePrincipal } from '@byok-sdk/core';\nimport { authenticateBearer, type BearerAuthDeps } from '../auth/bearer';\nimport { tenantStoresFor, type CloudRootStores, type TenantStores } from '../tenant-stores';\n\n/** Every error response on this surface is `{ error }` — the same shape the reference server uses. */\nexport interface ErrorBody {\n readonly error: string;\n}\n\nexport async function readJsonBody(c: Context): Promise<unknown> {\n try {\n return await c.req.json();\n } catch {\n return undefined;\n }\n}\n\nexport interface DeviceRouteDeps {\n readonly bearer: BearerAuthDeps;\n readonly root: CloudRootStores;\n}\n\nexport interface AuthenticatedDeviceContext {\n readonly device: DevicePrincipal;\n readonly stores: TenantStores;\n}\n\n/**\n * `undefined` means \"answer 401\" — and it means that for a missing header, a\n * forged token, an expired token, a revoked device, a product mismatch, and a\n * token whose tenant does not own the device, indistinguishably.\n */\nexport async function authenticateDevice(\n c: Context,\n deps: DeviceRouteDeps,\n): Promise<AuthenticatedDeviceContext | undefined> {\n const device = await authenticateBearer(c.req.header('authorization'), deps.bearer);\n if (device === undefined) return undefined;\n return { device, stores: tenantStoresFor(device, deps.root) };\n}\n","/**\n * Blob flows (§7).\n *\n * Two route classes on purpose: `POST /byok/blobs` and `GET\n * /byok/blobs/:id/url` are bearer-authed and therefore tenant-closed (a\n * download URL is minted only for a blob the caller's own tenant owns, and a\n * foreign blob is indistinguishable from a missing one); the two `/content`\n * routes are presigned, because they are meant to be hit directly — by a\n * browser, by a `PUT` from a daemon that holds only the signed URL — with no\n * JWT in scope at all. The HMAC signature over the blob id plus its expiry IS\n * the credential there, which is why those two carry the `presigned` class in\n * the route inventory rather than being lumped in with the device routes.\n *\n * The split runs all the way down: the bearer-authed pair reaches blobs only\n * through the tenant facade and never holds a naked store, and the presigned\n * pair holds only a {@link BlobContentProxy} and no bearer deps. A composition\n * without a proxy does not mount them (`cloud.ts`).\n */\nimport type { Context } from 'hono';\nimport { z } from 'zod';\nimport {\n CreateBlobRequestSchema,\n type BlobDownloadUrlResponse,\n type CreateBlobResponse,\n} from '@byok-sdk/protocol';\nimport {\n STORAGE_ERROR_CODES,\n STORAGE_ERROR_HTTP_STATUS,\n contentHash,\n isCoreError,\n type StorageErrorCode,\n} from '@byok-sdk/core';\nimport type { BlobContentProxy } from '../stores/ports';\nimport { authenticateDevice, readJsonBody, type DeviceRouteDeps } from './shared';\n\n/** The three bearer-authed routes: everything they touch goes through the tenant facade. */\nexport interface BlobRouteDeps extends DeviceRouteDeps {\n readonly maxBlobSizeBytes: number;\n}\n\n/** Reservation and presign grants deliberately share one expiry horizon. */\nexport const BLOB_RESERVATION_TTL_MS = 15 * 60 * 1000;\n\n/**\n * The two presigned routes. No bearer deps at all — there is no principal to\n * build a facade from, and the proxy is the only thing they need.\n */\nexport interface BlobContentRouteDeps {\n readonly contentProxy: BlobContentProxy;\n}\n\n/**\n * The presigned query contract. Cloud-owned (the wire DTO package covers\n * request/response BODIES, not URL signing), and validated rather than\n * hand-parsed so a non-numeric `exp` is a failed verification instead of a\n * `NaN` comparison that quietly answers `false` for the wrong reason.\n */\nconst SignedUrlQuerySchema = z.object({\n sig: z.string().min(1),\n exp: z.coerce.number().finite(),\n});\n\nexport function createBlobHandler(deps: BlobRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n\n const parsed = CreateBlobRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'size, contentType, and contentHash are required' }, 400);\n if (parsed.data.size > deps.maxBlobSizeBytes) {\n return c.json({ error: `blob exceeds max size of ${deps.maxBlobSizeBytes} bytes` }, 413);\n }\n\n const reservationId = idempotencyKey(c);\n if (reservationId === undefined) {\n return c.json({ error: 'Idempotency-Key header is required' }, 400);\n }\n\n try {\n const reservation = await authenticated.stores.quota.reserve({\n reservationId,\n kind: 'object',\n expectedBytes: BigInt(parsed.data.size),\n contentHash: contentHash(parsed.data.contentHash),\n contentType: parsed.data.contentType,\n ttlMs: BLOB_RESERVATION_TTL_MS,\n });\n try {\n const { blobId, uploadUrl } = await authenticated.stores.blobs.createUpload(reservation);\n const response: CreateBlobResponse = { blobId, uploadUrl };\n return c.json(response, 200);\n } catch (error) {\n // Preserve the grant failure as the client-facing authority. Cleanup\n // is best-effort here; admission reaps an abandoned hold after TTL if\n // the store is concurrently unavailable.\n await authenticated.stores.quota.abortReservation(reservationId).catch(() => undefined);\n const rendered = renderStorageError(c, error);\n if (rendered !== undefined) return rendered;\n throw error;\n }\n } catch (error) {\n const rendered = renderStorageError(c, error);\n if (rendered !== undefined) return rendered;\n throw error;\n }\n };\n}\n\nexport function finalizeBlobHandler(deps: BlobRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n\n const reservationId = idempotencyKey(c);\n if (reservationId === undefined) {\n return c.json({ error: 'Idempotency-Key header is required' }, 400);\n }\n\n try {\n const reservation = await authenticated.stores.quota.readReservation(reservationId);\n if (reservation === undefined) {\n return c.json({ error: 'storage_reservation_not_found' }, 404);\n }\n const blobId = c.req.param('id') ?? '';\n const observed = await authenticated.stores.blobs.observeUpload(\n blobId,\n reservation,\n );\n if (observed === undefined) {\n await authenticated.stores.quota.abortReservation(reservationId);\n return c.json({ error: 'storage_integrity_mismatch' }, 422);\n }\n\n await authenticated.stores.quota.finalizeReservation({\n reservationId,\n ...observed,\n });\n return c.body(null, 204);\n } catch (error) {\n const rendered = renderStorageError(c, error);\n if (rendered !== undefined) return rendered;\n throw error;\n }\n };\n}\n\nexport function blobDownloadUrlHandler(deps: BlobRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n\n const downloadUrl = await authenticated.stores.blobs.getDownloadUrl(c.req.param('id') ?? '');\n if (downloadUrl === undefined) return c.json({ error: 'blob not found' }, 404);\n\n const response: BlobDownloadUrlResponse = { downloadUrl };\n return c.json(response, 200);\n };\n}\n\nexport function blobUploadContentHandler(deps: BlobContentRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const blobId = c.req.param('id') ?? '';\n const query = SignedUrlQuerySchema.safeParse({ sig: c.req.query('sig'), exp: c.req.query('exp') });\n if (!query.success || !(await deps.contentProxy.verifySignedUrl(blobId, 'put', query.data.sig, query.data.exp))) {\n return c.json({ error: 'invalid or expired signature' }, 401);\n }\n\n const result = await deps.contentProxy.writeContent(blobId, new Uint8Array(await c.req.arrayBuffer()));\n if (!result.ok) return c.json({ error: result.reason }, 422);\n return c.body(null, 204);\n };\n}\n\nexport function blobDownloadContentHandler(deps: BlobContentRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const blobId = c.req.param('id') ?? '';\n const query = SignedUrlQuerySchema.safeParse({ sig: c.req.query('sig'), exp: c.req.query('exp') });\n if (!query.success || !(await deps.contentProxy.verifySignedUrl(blobId, 'get', query.data.sig, query.data.exp))) {\n return c.json({ error: 'invalid or expired signature' }, 401);\n }\n\n const content = await deps.contentProxy.readContent(blobId);\n if (content === undefined) return c.json({ error: 'blob not found' }, 404);\n return c.body(new Uint8Array(content.data), 200, { 'content-type': content.contentType });\n };\n}\n\nfunction idempotencyKey(c: Context): string | undefined {\n const value = c.req.header('Idempotency-Key');\n if (value === undefined || value.length === 0 || value.length > 200) return undefined;\n return value;\n}\n\nfunction renderStorageError(c: Context, error: unknown): Response | undefined {\n if (!isCoreError(error)) return undefined;\n if ((STORAGE_ERROR_CODES as readonly string[]).includes(error.code)) {\n const code = error.code as StorageErrorCode;\n return c.json({ error: code }, STORAGE_ERROR_HTTP_STATUS[code]);\n }\n if (error.code === 'storage_reservation_not_found' || error.code === 'object_not_found') {\n return c.json({ error: error.code }, 404);\n }\n if (error.code === 'storage_entitlement_missing' || error.code === 'object_state_invalid') {\n return c.json({ error: error.code }, 409);\n }\n if (error.code === 'content_hash_invalid') {\n return c.json({ error: error.code }, 400);\n }\n return undefined;\n}\n","/**\n * `GET /byok/capabilities` — the declaration route (ADR-010).\n *\n * Public by design: a client has to be able to read what a deployment supports\n * before it holds a credential, and the declaration is a deployment-level\n * fact, not a tenant-level one. Nothing tenant-scoped may ever be added to\n * this response for exactly that reason.\n */\nimport type { Context } from 'hono';\nimport type { CapabilityDeclaration } from '@byok-sdk/core';\n\nexport interface CapabilitiesRouteDeps {\n readonly declaration: CapabilityDeclaration;\n}\n\nexport function capabilitiesHandler(deps: CapabilitiesRouteDeps) {\n return async (c: Context): Promise<Response> => c.json(deps.declaration, 200);\n}\n","/**\n * Auth v2 (docs/protocol.md §6): pair, challenge, token.\n *\n * Byte-for-byte the same request/response DTOs the daemon already speaks,\n * because they come from `@byok-sdk/protocol` rather than from a hosted copy of\n * them. The behavior differences a hosted surface DOES make are two, both\n * narrowing:\n *\n * - a pairing code that is unknown, expired, or already used gets one 401 with\n * one message (the reference server names the reason);\n * - an unknown device and a revoked device were already indistinguishable on\n * the reference server, and stay so here.\n */\nimport type { Context } from 'hono';\nimport {\n ChallengeRequestSchema,\n PairRequestSchema,\n TokenRequestSchema,\n type ChallengeResponse,\n type PairResponse,\n type TokenResponse,\n} from '@byok-sdk/protocol';\nimport type { AuthPlane } from '../auth/plane';\nimport { readJsonBody } from './shared';\n\nexport interface AuthRouteDeps {\n readonly auth: AuthPlane;\n}\n\nexport function pairHandler(deps: AuthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const parsed = PairRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) {\n return c.json({ error: 'pairingCode, deviceName, and devicePublicKey are required strings' }, 400);\n }\n\n const device = await deps.auth.redeemAndRegister(parsed.data);\n if (device === undefined) return c.json({ error: 'invalid pairing code' }, 401);\n\n const { accessToken, expiresAt } = await deps.auth.mintAccessToken(device);\n const response: PairResponse = { deviceId: device.deviceId, accessToken, refreshHint: expiresAt };\n return c.json(response, 200);\n };\n}\n\nexport function challengeHandler(deps: AuthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const parsed = ChallengeRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'deviceId is required' }, 400);\n\n // Pre-tenant by construction: `ChallengeRequest` is the pinned wire\n // contract and carries only a deviceId, so the ROW is what tells this\n // deployment which tenant the device belongs to.\n const device = await deps.auth.resolveDevice(parsed.data.deviceId);\n if (device === undefined) return c.json({ error: 'unknown or revoked device' }, 401);\n\n const response: ChallengeResponse = { nonce: await deps.auth.issueNonce(device) };\n return c.json(response, 200);\n };\n}\n\nexport function tokenHandler(deps: AuthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const parsed = TokenRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'deviceId, nonce, and signature are required' }, 400);\n const { deviceId, nonce, signature } = parsed.data;\n\n const device = await deps.auth.resolveDevice(deviceId);\n if (device === undefined) return c.json({ error: 'unknown or revoked device' }, 401);\n\n if (!(await deps.auth.validateNonce(device, nonce))) {\n return c.json({ error: 'invalid, expired, or already-used nonce' }, 401);\n }\n // Domain-separated (`byok-nonce-v1\\n`, `auth/verify.ts`): a raw signature\n // over the bare nonce is invalid here, with no second accepted form.\n if (!(await deps.auth.verifySignature(device, nonce, signature))) {\n return c.json({ error: 'invalid signature' }, 401);\n }\n // Burn the nonce only on a fully verified success (§6.2) — an invalid\n // signature attempt does not consume the legitimate device's nonce.\n await deps.auth.consumeNonce(device, nonce);\n\n const { accessToken, expiresAt } = await deps.auth.mintAccessToken(device);\n const response: TokenResponse = { accessToken, expiresAt };\n return c.json(response, 200);\n };\n}\n","/**\n * `GET /byok/events?cursor=N` — the long-poll receive half (§8).\n *\n * Three properties the daemon's transport depends on, reproduced against the\n * core mailbox rather than an in-process outbox:\n *\n * - **Reading is not acknowledging.** `readAfter` never moves the cursor. The\n * ONLY ack is the cursor the daemon brings back on its NEXT poll, after it\n * has durably processed what it was handed — which is why the ack below\n * happens before the read, against the incoming `cursor`, and why a poll\n * that hands back the same cursor replays the same page forever.\n * - **The ack is monotonic.** A cursor at or below what the device already\n * acked carries no new information and is not an ack attempt; only a\n * strictly higher one advances. The store's own\n * `mailbox_cursor_regression` guard stays the authority on going backwards\n * (asserted directly in `src/__tests__/mailbox-cursor.test.ts`).\n * - **The hold.** An empty poll is held open instead of answered immediately,\n * so an idle daemon is not a busy-loop. The hold is a bounded re-read, not a\n * registered waiter: a waiter map is exactly the cross-request state a\n * stateless handler may not keep (S3.5 boxes 14-15), and a second cloud\n * instance would not see it anyway.\n */\nimport type { Context } from 'hono';\nimport { decodeEnvelope, type Envelope, type EventsPollResponse } from '@byok-sdk/protocol';\nimport { authenticateDevice, type DeviceRouteDeps } from './shared';\n\n/** Protocol features this cloud build accepts from a long-poll daemon. */\nconst CLOUD_PROTOCOL_CAPABILITIES = ['result-document'];\n\nexport interface EventsRouteDeps extends DeviceRouteDeps {\n /** How long an empty poll is held open, ms. */\n readonly longPollHoldMs: number;\n /** How often the mailbox is re-read while holding, ms. */\n readonly longPollIntervalMs: number;\n /** Max rows per response. */\n readonly pageLimit: number;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function eventsHandler(deps: EventsRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const { device, stores } = authenticated;\n\n const cursorRaw = c.req.query('cursor');\n let cursor = 0;\n if (cursorRaw !== undefined) {\n const parsedCursor = Number(cursorRaw);\n if (!Number.isInteger(parsedCursor) || parsedCursor < 0) return c.json({ error: 'invalid cursor' }, 400);\n cursor = parsedCursor;\n }\n\n const acked = await stores.mailbox.readCursor(device.deviceId);\n if (cursor > acked.ackedSeq) {\n await stores.mailbox.advanceCursor({ deviceId: device.deviceId, ackedSeq: cursor });\n }\n\n const attempts = Math.max(1, Math.ceil(deps.longPollHoldMs / deps.longPollIntervalMs));\n for (let attempt = 0; attempt < attempts; attempt += 1) {\n const page = await stores.mailbox.readAfter({\n deviceId: device.deviceId,\n afterSeq: cursor,\n limit: deps.pageLimit,\n });\n if (page.messages.length > 0) {\n const events: Envelope[] = page.messages.map((message) => decodeEnvelope(message.body));\n const response: EventsPollResponse = {\n events,\n cursor: page.nextSeq,\n capabilities: CLOUD_PROTOCOL_CAPABILITIES,\n };\n return c.json(response, 200);\n }\n if (attempt < attempts - 1) await sleep(deps.longPollIntervalMs);\n }\n\n const response: EventsPollResponse = {\n events: [],\n cursor,\n capabilities: CLOUD_PROTOCOL_CAPABILITIES,\n };\n return c.json(response, 200);\n };\n}\n","import { tenantKey, type TenantId } from '@byok-sdk/core';\nimport { z } from 'zod';\nimport { ByokCloudError } from './errors';\n\nexport const DEFAULT_APPROVAL_TIMELINE_CAPACITY = 50;\nexport const DEFAULT_APPROVAL_TIMELINE_TTL_MS = 10 * 60 * 1_000;\nexport const APPROVAL_SUMMARY_MAX_BYTES = 16 * 1_024;\n\nconst NonBlankIdSchema = z.string().max(200).regex(/\\S/, 'value must not be blank');\nconst TaskIdSchema = z.string().min(1).max(200);\n\nexport const ApprovalTimelineEventSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('approval_requested'),\n summary: z.string(),\n approvalId: NonBlankIdSchema.optional(),\n }),\n z.object({\n type: z.literal('approval_resolved'),\n approvalId: NonBlankIdSchema,\n decision: z.enum(['approve', 'reject']),\n resolvedBy: z.enum(['local']),\n at: z.iso.datetime({ offset: true }),\n }),\n]);\n\nexport type ApprovalTimelineEvent = Readonly<z.infer<typeof ApprovalTimelineEventSchema>>;\n\nexport const ApprovalObservationSchema = z.object({\n taskId: TaskIdSchema,\n sourceEnvelopeId: NonBlankIdSchema,\n revision: z.number().int().positive(),\n receivedAt: z.iso.datetime(),\n event: ApprovalTimelineEventSchema,\n});\n\nexport type ApprovalObservation = Readonly<z.infer<typeof ApprovalObservationSchema>>;\n\nexport interface ApprovalTimelineTail {\n readonly tenantId: TenantId;\n readonly taskId: string;\n readonly entries: readonly ApprovalObservation[];\n readonly cursor?: number;\n readonly dropped: number;\n readonly capacity: number;\n readonly expiresAt: string;\n}\n\nexport interface ApprovalTimelineAppendInput {\n readonly taskId: string;\n readonly sourceEnvelopeId: string;\n readonly event: ApprovalTimelineEvent;\n readonly ttlMs?: number;\n readonly capacity?: number;\n}\n\nexport interface ApprovalTimelineStore {\n append(tenant: TenantId, input: ApprovalTimelineAppendInput): Promise<ApprovalTimelineTail>;\n read(tenant: TenantId, taskId: string): Promise<ApprovalTimelineTail | undefined>;\n}\n\nexport interface ValidatedApprovalTimelineAppend {\n readonly capacity: number;\n readonly ttlMs: number;\n readonly event: ApprovalTimelineEvent;\n}\n\nexport function validateApprovalTimelineAppend(\n input: ApprovalTimelineAppendInput,\n): ValidatedApprovalTimelineAppend {\n const capacity = input.capacity ?? DEFAULT_APPROVAL_TIMELINE_CAPACITY;\n const ttlMs = input.ttlMs ?? DEFAULT_APPROVAL_TIMELINE_TTL_MS;\n if (!Number.isSafeInteger(capacity) || capacity <= 0) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Approval timeline capacity must be a positive integer, received ${String(capacity)}.`,\n );\n }\n if (!Number.isFinite(ttlMs) || ttlMs <= 0) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Approval timeline ttl must be a positive number of milliseconds, received ${String(ttlMs)}.`,\n );\n }\n const parsed = z\n .object({\n taskId: TaskIdSchema,\n sourceEnvelopeId: NonBlankIdSchema,\n event: ApprovalTimelineEventSchema,\n })\n .safeParse(input);\n if (!parsed.success) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Approval observations require stable source identity and a valid native lifecycle event.',\n );\n }\n if (\n parsed.data.event.type === 'approval_requested' &&\n new TextEncoder().encode(parsed.data.event.summary).byteLength > APPROVAL_SUMMARY_MAX_BYTES\n ) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Approval summary exceeds ${APPROVAL_SUMMARY_MAX_BYTES} UTF-8 bytes.`,\n );\n }\n return { capacity, ttlMs, event: parsed.data.event };\n}\n\nexport function approvalTimelineKey(tenant: TenantId, taskId: string): string {\n return tenantKey(tenant, taskId);\n}\n\nexport function parseApprovalObservations(value: unknown): readonly ApprovalObservation[] {\n return z.array(ApprovalObservationSchema).parse(value) as readonly ApprovalObservation[];\n}\n\nexport function approvalTimelineCursor(\n entries: readonly ApprovalObservation[],\n): number | undefined {\n return entries.at(-1)?.revision;\n}\n","import { isCoreConflictError } from '@byok-sdk/core';\nimport type { TenantBoundBoard } from './tenant-stores';\n\n/**\n * One-way projection from an already accepted terminal fact into coordination.\n *\n * This module deliberately knows no wire message type or execution-state\n * vocabulary. It can only CAS an existing coordination row one step toward\n * review, and a concurrent board decision wins without retry or overwrite.\n */\nexport async function projectTerminalToReview(board: TenantBoundBoard, taskId: string): Promise<void> {\n const item = await board.get(taskId);\n if (item === undefined || item.status !== 'in_progress') return;\n try {\n await board.updateStatus({\n itemId: taskId,\n expectedStatus: 'in_progress',\n status: 'in_review',\n });\n } catch (caught) {\n if (isCoreConflictError(caught)) return;\n throw caught;\n }\n}\n","/**\n * The single inbound choke point for every daemon -> cloud envelope.\n *\n * The reference server runs this gate inside a live `ConnectionHub`; here it\n * is a pure function over a tenant-closed facade, so the same order holds with\n * no connection, no session, and no cross-request state:\n *\n * 0. **rate limit** — one token per inbound envelope, debited BEFORE anything\n * else, so a flood of garbage-typed envelopes costs the same budget as a\n * flood of well-formed ones. S3a's reference limiter allows everything; the\n * seam is what matters at this position.\n * 1. **type-allow** — only `DAEMON_TO_SERVER_TYPES` may pass. A server ->\n * daemon type arriving inbound, or anything unrecognized, is rejected\n * before it is dispatched or counted accepted.\n * 2. **ownership** — an envelope for a task already owned by a DIFFERENT\n * device is dropped, never force-failed: force-failing on an authz mismatch\n * would let an attacker who merely guesses a `taskId` kill the real owner's\n * task. A task with no owner yet, or that this tenant does not have at all,\n * is not rejected here — the store's own no-op-on-missing behavior covers\n * the latter, and it covers it per tenant, so a guessed id from another\n * tenant writes nothing anywhere.\n * 3. **dedup** — an envelope id already seen from this device is a no-op. The\n * wire is at-least-once (§9); this makes processing at-most-once.\n * 4. **apply** — the lifecycle write.\n *\n * A duplicate is still a wire-level success (§8.2): it just did not re-run\n * anything. Only `rejected`/`rate_limited` are excluded from `accepted`.\n */\nimport {\n DAEMON_TO_SERVER_TYPES,\n encodeEnvelope,\n type Envelope,\n type MessageType,\n} from '@byok-sdk/protocol';\nimport {\n validateActivityBatch,\n appendActivityEvents,\n DEFAULT_ACTIVITY_BOUNDS,\n type ActivityBounds,\n} from './coordination';\nimport {\n validateApprovalTimelineAppend,\n type ApprovalTimelineAppendInput,\n} from './approval-timeline';\nimport { isCloudError } from './errors';\nimport { projectTerminalToReview } from './board-projection';\nimport type { TenantStores } from './tenant-stores';\n\nexport type InboundOutcome = 'accepted' | 'duplicate' | 'rejected' | 'rate_limited';\n\n/** Receipt key a task's terminal is recorded under — the idempotency seam S3b's journal will share. */\nexport function terminalReceiptKey(taskId: string): string {\n return `task:${taskId}:terminal`;\n}\n\nexport async function handleInboundEnvelope(\n stores: TenantStores,\n deviceId: string,\n envelope: Envelope,\n activityBounds: ActivityBounds = DEFAULT_ACTIVITY_BOUNDS,\n): Promise<InboundOutcome> {\n if (!(await stores.rateLimiter.consume(deviceId))) return 'rate_limited';\n\n if (!(DAEMON_TO_SERVER_TYPES as readonly MessageType[]).includes(envelope.type)) return 'rejected';\n\n const taskId = envelope.task_id;\n // Every `DAEMON_TO_SERVER_TYPES` member requires `task_id` at the schema\n // level; this is the defensive restatement, not a second contract.\n if (taskId === undefined) return 'rejected';\n\n const attempt = await stores.tasks.get(taskId);\n if (attempt?.ownerDeviceId !== undefined && attempt.ownerDeviceId !== deviceId) return 'rejected';\n\n if (envelope.type === 'task.progress' && envelope.payload.events.length > 0) {\n try {\n validateActivityBatch(\n {\n taskId,\n sourceEnvelopeId: envelope.id,\n batchSeq: envelope.payload.seq,\n events: envelope.payload.events,\n dropped: 0,\n },\n activityBounds,\n );\n } catch (caught) {\n if (\n isCloudError(caught, 'activity_batch_too_large') ||\n isCloudError(caught, 'coordination_input_invalid')\n ) {\n return 'rejected';\n }\n throw caught;\n }\n }\n\n const approvalInput = approvalTimelineAppendInput(taskId, envelope);\n if (approvalInput !== undefined) {\n try {\n validateApprovalTimelineAppend(approvalInput);\n } catch (caught) {\n if (isCloudError(caught, 'coordination_input_invalid')) return 'rejected';\n throw caught;\n }\n }\n\n if (await stores.dedup.checkAndRecord(deviceId, envelope.id)) return 'duplicate';\n\n await applyLifecycle(stores, deviceId, taskId, envelope, activityBounds);\n return 'accepted';\n}\n\n/**\n * The lifecycle half. Deliberately thin: S3a records ownership, the coarse\n * attempt status, the terminal receipt, and bounded activity/approval\n * observations. Artifacts are accepted and carried, but the durable record of\n * what a task *produced* belongs to the truth and board planes (S5/S6) and to\n * S3b's journal — not to a map in this package.\n */\nasync function applyLifecycle(\n stores: TenantStores,\n deviceId: string,\n taskId: string,\n envelope: Envelope,\n activityBounds: ActivityBounds,\n): Promise<void> {\n switch (envelope.type) {\n case 'task.claim':\n await stores.tasks.claim({ taskId, deviceId });\n return;\n case 'task.started':\n await stores.tasks.recordStatus({ taskId, status: 'running' });\n return;\n case 'task.decline':\n await stores.tasks.recordStatus({ taskId, status: 'failed' });\n return;\n case 'task.progress':\n if (envelope.payload.events.length > 0) {\n await appendActivityEvents(\n stores.activity,\n {\n taskId,\n sourceEnvelopeId: envelope.id,\n batchSeq: envelope.payload.seq,\n events: envelope.payload.events,\n dropped: 0,\n },\n activityBounds,\n );\n }\n return;\n case 'task.await_approval':\n await stores.approvals.append(approvalTimelineAppendInput(taskId, envelope)!);\n return;\n case 'task.approval_resolved':\n await stores.approvals.append(approvalTimelineAppendInput(taskId, envelope)!);\n return;\n case 'task.complete':\n await recordTerminal(stores, taskId, envelope, 'complete');\n return;\n case 'task.fail':\n await recordTerminal(stores, taskId, envelope, 'failed');\n return;\n case 'task.cancelled':\n await recordTerminal(stores, taskId, envelope, 'cancelled');\n return;\n default:\n return;\n }\n}\n\nfunction approvalTimelineAppendInput(\n taskId: string,\n envelope: Envelope,\n): ApprovalTimelineAppendInput | undefined {\n switch (envelope.type) {\n case 'task.await_approval':\n return {\n taskId,\n sourceEnvelopeId: envelope.id,\n event: {\n type: 'approval_requested',\n summary: envelope.payload.summary,\n ...(envelope.payload.approvalId === undefined\n ? {}\n : { approvalId: envelope.payload.approvalId }),\n },\n };\n case 'task.approval_resolved':\n return {\n taskId,\n sourceEnvelopeId: envelope.id,\n event: {\n type: 'approval_resolved',\n approvalId: envelope.payload.approvalId,\n decision: envelope.payload.decision,\n resolvedBy: envelope.payload.resolvedBy,\n at: envelope.payload.at,\n },\n };\n default:\n return undefined;\n }\n}\n\n/**\n * First terminal wins (§12.6.4: 不覆写第一份事实). A retried terminal — same\n * task, new envelope id, so dedup does not catch it — records nothing new and\n * leaves the attempt status where the first one put it.\n *\n * What gets stored is `encodeEnvelope(envelope)`: the canonical v1 encoding of\n * the envelope this gate already zod-parsed, NOT the device's original byte\n * sequence. The two are semantically identical by the frozen codec's own\n * round-trip guarantee, but they are not necessarily byte-identical (key\n * order, whitespace, and any field the schema drops are the parser's call, not\n * the device's) — so this receipt is evidence of the first terminal FACT, not\n * a byte-faithful capture of the first terminal REQUEST. S3b's local journal\n * is where the device's own bytes are kept.\n */\nasync function recordTerminal(\n stores: TenantStores,\n taskId: string,\n envelope: Envelope,\n status: 'complete' | 'failed' | 'cancelled',\n): Promise<void> {\n const { created } = await stores.receipts.record({\n key: terminalReceiptKey(taskId),\n body: encodeEnvelope(envelope),\n });\n if (!created) return;\n await stores.tasks.recordStatus({ taskId, status });\n await projectTerminalToReview(stores.board, taskId);\n}\n","/**\n * `POST /byok/messages` — the long-poll send half (§8.2).\n *\n * A device long-polling for cloud -> daemon traffic has no live socket to\n * carry its own outbound envelopes; this batches them over authed HTTP. Every\n * envelope goes through the same gate (`../inbound.ts`) in the same order, so\n * claim/progress/complete behave identically no matter which transport carried\n * them.\n *\n * The batch stays tolerant at the schema level — one malformed envelope must\n * not 400 the whole request — so only a structurally invalid `Envelope` or an\n * oversized batch (`MAX_MESSAGES_PER_BATCH`) fails the request outright.\n *\n * Rate limiting is per REQUEST, not per envelope: the moment any envelope\n * comes back `rate_limited`, the rest of the batch is abandoned (its bucket is\n * empty, so every remaining envelope would limit too) and the WHOLE request\n * answers 429. Envelopes processed earlier in the same batch already took\n * effect — there are no rollback semantics here — which is safe because every\n * `task.*` type is idempotent (§9): a client that retries the same batch gets\n * `duplicate` for whatever already landed.\n */\nimport type { Context } from 'hono';\nimport { MessagesSendRequestSchema, type MessagesSendResponse } from '@byok-sdk/protocol';\nimport { handleInboundEnvelope } from '../inbound';\nimport type { ActivityBounds } from '../coordination';\nimport { authenticateDevice, readJsonBody, type DeviceRouteDeps } from './shared';\n\nexport interface MessagesRouteDeps extends DeviceRouteDeps {\n readonly activityBounds: ActivityBounds;\n}\n\nexport function messagesHandler(deps: MessagesRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const { device, stores } = authenticated;\n\n const parsed = MessagesSendRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'messages must be an array of envelopes' }, 400);\n\n let accepted = 0;\n let rejected = 0;\n for (const envelope of parsed.data.messages) {\n const outcome = await handleInboundEnvelope(\n stores,\n device.deviceId,\n envelope,\n deps.activityBounds,\n );\n if (outcome === 'rate_limited') return c.json({ error: 'rate limit exceeded' }, 429);\n // A duplicate is still a wire-level success (§8.2/§9's idempotency\n // window) — it just did not re-run a handler. Only a gate rejection\n // (wrong-direction type, or an ownership mismatch) is excluded.\n if (outcome === 'rejected') rejected += 1;\n else accepted += 1;\n }\n\n // `rejected` is additive and omitted entirely when zero, so a batch with\n // nothing rejected keeps the `{ accepted }` shape callers depend on.\n const response: MessagesSendResponse = rejected > 0 ? { accepted, rejected } : { accepted };\n return c.json(response, 200);\n };\n}\n","import {\n BOARD_STATUSES,\n isCoreConflictError,\n isCoreError,\n type BoardItem,\n type BoardListQuery,\n type BoardPage,\n} from '@byok-sdk/core';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\nimport { authenticateDevice, readJsonBody, type DeviceRouteDeps } from './shared';\n\nexport const DEFAULT_BOARD_PAGE_LIMIT = 50;\nexport const DEFAULT_BOARD_STREAM_QUERY_INTERVAL_MS = 5_000;\nexport const DEFAULT_BOARD_STREAM_HEARTBEAT_INTERVAL_MS = 15_000;\nexport const DEFAULT_BOARD_STREAM_RECONCILIATION_INTERVAL_MS = 120_000;\n\nexport interface BoardRouteDeps extends DeviceRouteDeps {\n readonly pageLimit: number;\n}\n\nexport interface BoardStreamRouteDeps extends BoardRouteDeps {\n readonly queryIntervalMs: number;\n readonly heartbeatIntervalMs: number;\n readonly reconciliationIntervalMs: number;\n}\n\nconst ClaimBodySchema = z.object({ expectedStatus: z.enum(BOARD_STATUSES).optional() });\nconst StatusBodySchema = z.object({\n expectedStatus: z.enum(BOARD_STATUSES),\n status: z.enum(BOARD_STATUSES),\n});\n\nfunction parseNonNegativeInteger(value: string | undefined): number | undefined {\n if (value === undefined) return 0;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction parsePositiveInteger(value: string | undefined, fallback: number): number | undefined {\n if (value === undefined) return fallback;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nfunction boardQuery(c: Context, pageLimit: number): BoardListQuery | undefined {\n const afterSeq = parseNonNegativeInteger(c.req.query('since'));\n const limit = parsePositiveInteger(c.req.query('limit'), pageLimit);\n const statusRaw = c.req.query('status');\n if (afterSeq === undefined || limit === undefined || limit > pageLimit) return undefined;\n if (statusRaw !== undefined && !BOARD_STATUSES.includes(statusRaw as (typeof BOARD_STATUSES)[number])) {\n return undefined;\n }\n return {\n afterSeq,\n limit,\n ...(c.req.query('channel') === undefined ? {} : { channel: c.req.query('channel') }),\n ...(statusRaw === undefined ? {} : { status: statusRaw as (typeof BOARD_STATUSES)[number] }),\n };\n}\n\nexport function boardListHandler(deps: BoardRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const query = boardQuery(c, deps.pageLimit);\n if (query === undefined) return c.json({ error: 'invalid board query' }, 400);\n return c.json(await authenticated.stores.board.list(query), 200);\n };\n}\n\nexport function boardClaimHandler(deps: DeviceRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const parsed = ClaimBodySchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'invalid claim body' }, 400);\n const itemId = c.req.param('id');\n if (itemId === undefined || itemId.length === 0) return c.json({ error: 'invalid board item id' }, 400);\n try {\n const item = await authenticated.stores.board.claim({\n itemId,\n holderId: authenticated.device.deviceId,\n ...(parsed.data.expectedStatus === undefined\n ? {}\n : { expectedStatus: parsed.data.expectedStatus }),\n });\n return c.json(item, 200);\n } catch (caught) {\n return boardFailure(c, caught);\n }\n };\n}\n\nexport function boardUnclaimHandler(deps: DeviceRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const itemId = c.req.param('id');\n if (itemId === undefined || itemId.length === 0) return c.json({ error: 'invalid board item id' }, 400);\n try {\n return c.json(\n await authenticated.stores.board.unclaim({\n itemId,\n holderId: authenticated.device.deviceId,\n }),\n 200,\n );\n } catch (caught) {\n return boardFailure(c, caught);\n }\n };\n}\n\nexport function boardStatusHandler(deps: DeviceRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const parsed = StatusBodySchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'invalid status body' }, 400);\n const itemId = c.req.param('id');\n if (itemId === undefined || itemId.length === 0) return c.json({ error: 'invalid board item id' }, 400);\n if (parsed.data.status === 'done') {\n return c.json({ error: 'done requires host review acceptance' }, 403);\n }\n try {\n return c.json(\n await authenticated.stores.board.updateStatus({\n itemId,\n expectedStatus: parsed.data.expectedStatus,\n status: parsed.data.status,\n holderId: authenticated.device.deviceId,\n }),\n 200,\n );\n } catch (caught) {\n return boardFailure(c, caught);\n }\n };\n}\n\nexport function boardStreamHandler(deps: BoardStreamRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const firstAuth = await authenticateDevice(c, deps);\n if (firstAuth === undefined) return c.json({ error: 'unauthorized' }, 401);\n const query = boardQuery(c, deps.pageLimit);\n if (query === undefined) return c.json({ error: 'invalid board query' }, 400);\n\n const querySince = query.afterSeq ?? 0;\n const headerRaw = c.req.header('last-event-id');\n const headerSince = headerRaw === undefined ? undefined : parseNonNegativeInteger(headerRaw);\n if (headerRaw !== undefined && headerSince === undefined) {\n return c.json({ error: 'invalid Last-Event-ID' }, 400);\n }\n if (headerSince !== undefined && c.req.query('since') !== undefined && headerSince !== querySince) {\n return c.json({ error: 'conflicting stream cursors' }, 400);\n }\n\n let stopped = false;\n const stopController = new AbortController();\n const signal = c.req.raw.signal;\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n const onAbort = () => {\n stopped = true;\n stopController.abort();\n closeController(controller);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n void pumpBoardStream(\n controller,\n c,\n deps,\n { ...query, afterSeq: headerSince ?? querySince },\n () => stopped || signal.aborted,\n stopController.signal,\n ).finally(() => {\n stopped = true;\n stopController.abort();\n signal.removeEventListener('abort', onAbort);\n closeController(controller);\n });\n },\n cancel() {\n stopped = true;\n stopController.abort();\n },\n });\n\n return new Response(stream, {\n status: 200,\n headers: {\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n 'content-type': 'text/event-stream; charset=utf-8',\n },\n });\n };\n}\n\nasync function pumpBoardStream(\n controller: ReadableStreamDefaultController<Uint8Array>,\n c: Context,\n deps: BoardStreamRouteDeps,\n initialQuery: BoardListQuery,\n isStopped: () => boolean,\n stopSignal: AbortSignal,\n): Promise<void> {\n let cursor = initialQuery.afterSeq ?? 0;\n let lastHeartbeat = performance.now();\n let lastReconcile = performance.now();\n while (!isStopped()) {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return;\n\n const page = await authenticated.stores.board.list({ ...initialQuery, afterSeq: cursor });\n for (const item of page.items) {\n enqueue(controller, `event: board\\nid: ${item.boardSeq}\\ndata: ${JSON.stringify(item)}\\n\\n`);\n cursor = item.boardSeq;\n }\n if (page.hasMore) continue;\n\n const now = performance.now();\n if (now - lastReconcile >= deps.reconciliationIntervalMs) {\n enqueue(controller, `event: reconcile\\ndata: ${JSON.stringify({ since: 0 })}\\n\\n`);\n lastReconcile = now;\n }\n if (now - lastHeartbeat >= deps.heartbeatIntervalMs) {\n enqueue(controller, ': heartbeat\\n\\n');\n lastHeartbeat = now;\n }\n await abortableSleep(deps.queryIntervalMs, stopSignal);\n }\n}\n\nfunction enqueue(controller: ReadableStreamDefaultController<Uint8Array>, value: string): void {\n try {\n controller.enqueue(new TextEncoder().encode(value));\n } catch {\n // The request abort/cancel path owns closure. A closed controller is terminal.\n }\n}\n\nfunction closeController(controller: ReadableStreamDefaultController<Uint8Array>): void {\n try {\n controller.close();\n } catch {\n // Already closed by the peer or the pump.\n }\n}\n\nasync function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {\n if (signal.aborted) return;\n await new Promise<void>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const finish = () => {\n if (timer !== undefined) clearTimeout(timer);\n signal.removeEventListener('abort', finish);\n resolve();\n };\n timer = setTimeout(finish, ms);\n signal.addEventListener('abort', finish, { once: true });\n if (signal.aborted) finish();\n });\n}\n\nfunction boardFailure(c: Context, caught: unknown): Response {\n if (isCoreConflictError<BoardItem>(caught)) {\n const holder = caught.current.assignee;\n return c.json(\n {\n error: caught.code,\n current: caught.current,\n observedAt: caught.observedAt,\n ...(holder === undefined ? {} : { holder: { ...holder, observedAt: caught.observedAt } }),\n },\n 409,\n );\n }\n if (isCoreError(caught, 'board_item_not_found')) return c.json({ error: caught.code }, 404);\n if (isCoreError(caught, 'board_not_held')) return c.json({ error: caught.code }, 409);\n throw caught;\n}\n\nexport type BoardPollResponse = BoardPage;\n","import { isCoreError, PRESENCE_LEVELS } from '@byok-sdk/core';\nimport { ConfiguredToolsetsSchema } from '@byok-sdk/protocol';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\nimport { appendActivityEvents, type ActivityBounds } from '../coordination';\nimport { ActivityAppendRequestSchema } from '../activity';\nimport { isCloudError } from '../errors';\nimport { authenticateDevice, readJsonBody, type DeviceRouteDeps } from './shared';\n\nexport interface PresenceRouteDeps extends DeviceRouteDeps {\n readonly ttlMs: number;\n readonly minimumIntervalMs: number;\n readonly detailMaxBytes: number;\n}\n\nexport interface ActivityRouteDeps extends DeviceRouteDeps {\n readonly bounds: ActivityBounds;\n}\n\nconst PresenceBodySchema = z.object({\n level: z.enum(PRESENCE_LEVELS),\n detail: z.string().optional(),\n configuredToolsets: ConfiguredToolsetsSchema.optional(),\n});\n\nexport function presencePublishHandler(deps: PresenceRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const parsed = PresenceBodySchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'invalid presence body' }, 400);\n if (\n parsed.data.detail !== undefined &&\n new TextEncoder().encode(parsed.data.detail).length > deps.detailMaxBytes\n ) {\n return c.json({ error: 'presence detail too large' }, 413);\n }\n try {\n return c.json(\n await authenticated.stores.presence.publish({\n deviceId: authenticated.device.deviceId,\n level: parsed.data.level,\n ...(parsed.data.detail === undefined ? {} : { detail: parsed.data.detail }),\n ...(parsed.data.configuredToolsets === undefined\n ? {}\n : { configuredToolsets: parsed.data.configuredToolsets }),\n ttlMs: deps.ttlMs,\n minimumIntervalMs: deps.minimumIntervalMs,\n }),\n 200,\n );\n } catch (caught) {\n if (isCoreError(caught, 'hint_rate_limited')) {\n return c.json({ error: caught.code }, 429);\n }\n throw caught;\n }\n };\n}\n\nexport function activityAppendHandler(deps: ActivityRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateDevice(c, deps);\n if (authenticated === undefined) return c.json({ error: 'unauthorized' }, 401);\n const parsed = ActivityAppendRequestSchema.safeParse(await readJsonBody(c));\n if (!parsed.success) return c.json({ error: 'invalid activity body' }, 400);\n try {\n return c.json(\n await appendActivityEvents(authenticated.stores.activity, parsed.data, deps.bounds),\n 200,\n );\n } catch (caught) {\n if (isCloudError(caught, 'activity_batch_too_large')) {\n return c.json({ error: caught.code }, 413);\n }\n if (isCloudError(caught, 'coordination_input_invalid')) {\n return c.json({ error: caught.code }, 400);\n }\n throw caught;\n }\n };\n}\n","/**\n * `GET /byok/skill-packs` and `GET /byok/skill-packs/:name/files/:path` — the\n * hosted half of the skill-pack delivery channel.\n *\n * Two device-class reads, and nothing else. There is no publish route here on\n * purpose: a device is a CONSUMER of packs, and a device-bearer-authed write\n * would let any paired device in a tenant publish content to every other device\n * in it. Publication is a host control-plane action against the store directly,\n * exactly as board item creation is.\n *\n * Both routes answer 404 for a pack this tenant does not have — the same answer\n * a name that never existed anywhere gets — so the surface is not a\n * cross-tenant existence oracle. The store is tenant-first, so that property\n * comes from the lookup key rather than from a comparison a handler could\n * forget.\n *\n * Bytes travel as UTF-8 text inside JSON. A pack carries Markdown, YAML and\n * static text; there is no archive to unpack and no binary channel to\n * negotiate, which is the same reason the manifest has no exec surface — the\n * format cannot express the thing we do not want it to express.\n */\nimport { principalTenant, type SkillPackStore } from '@byok-sdk/core';\nimport type { Context } from 'hono';\nimport { authenticateBearer, type BearerAuthDeps } from '../auth/bearer';\n\n/** Rows per `GET /byok/skill-packs` response. A tenant's pack catalogue is small by design. */\nexport const DEFAULT_SKILL_PACK_PAGE_LIMIT = 50;\n\nexport interface SkillPackRouteDeps {\n readonly bearer: BearerAuthDeps;\n readonly skillPacks: SkillPackStore;\n readonly pageLimit: number;\n}\n\nexport function skillPackListHandler(deps: SkillPackRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const device = await authenticateBearer(c.req.header('authorization'), deps.bearer);\n if (device === undefined) return unauthorized(c);\n\n const packs = await deps.skillPacks.list(principalTenant(device), { limit: deps.pageLimit });\n return c.json({ packs }, 200);\n };\n}\n\nexport function skillPackFileHandler(deps: SkillPackRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const device = await authenticateBearer(c.req.header('authorization'), deps.bearer);\n if (device === undefined) return unauthorized(c);\n\n const name = c.req.param('name');\n const path = c.req.param('path');\n if (name === undefined || path === undefined) return notFound(c);\n\n // No path normalization, no resolution, no decoding step of our own: the\n // store answers only for a path its own manifest declares, and those paths\n // passed core's path rule at publish time. A handler that \"cleaned up\" a\n // requested path would be inventing a second, weaker authority over what a\n // pack contains.\n const file = await deps.skillPacks.readFile(principalTenant(device), name, path);\n if (file === undefined) return notFound(c);\n return c.json(file, 200);\n };\n}\n\nfunction unauthorized(c: Context): Response {\n return c.json({ error: 'unauthorized' }, 401);\n}\n\nfunction notFound(c: Context): Response {\n return c.json({ error: 'skill_pack_not_found' }, 404);\n}\n","import {\n deviceProofSigningInput,\n isTenantId,\n parseDeviceProofEnvelope,\n tenantId,\n type Clock,\n type DevicePrincipal,\n type DeviceProofEnvelopeV1,\n} from '@byok-sdk/core';\nimport type { CloudCrypto } from '../crypto/port';\nimport type { DeviceDirectory } from '../stores/ports';\n\nexport const DEFAULT_DEVICE_PROOF_CLOCK_SKEW_MS = 60_000;\nexport const MAX_DEVICE_PROOF_CLOCK_SKEW_MS = 5 * 60_000;\nexport const DEFAULT_DEVICE_PROOF_MAX_LIFETIME_MS = 5 * 60_000;\nexport const MAX_DEVICE_PROOF_MAX_LIFETIME_MS = 15 * 60_000;\n\nexport interface DeviceProofRequestBinding {\n readonly method: string;\n readonly path: string;\n readonly operation: string;\n readonly resource: string;\n readonly body: Uint8Array;\n}\n\nexport interface DeviceProofAuthDeps {\n readonly devices: DeviceDirectory;\n readonly crypto: CloudCrypto;\n readonly clock: Clock;\n readonly clockSkewMs?: number;\n readonly maxLifetimeMs?: number;\n}\n\nexport interface AuthenticatedDeviceProof {\n /** Row-derived principal; no protected claim is re-used as authority. */\n readonly device: DevicePrincipal;\n readonly requestId: string;\n readonly operation: string;\n readonly resource: string;\n readonly bodySha256: string;\n readonly bodySize: bigint;\n readonly keyId: string;\n readonly keyEpoch: number;\n}\n\nfunction validBound(value: number, maximum: number): boolean {\n return Number.isSafeInteger(value) && value >= 0 && value <= maximum;\n}\n\nfunction parseInstant(value: string): number | undefined {\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction timeBindingIsValid(\n envelope: DeviceProofEnvelopeV1,\n now: number,\n clockSkewMs: number,\n maxLifetimeMs: number,\n): boolean {\n const issuedAt = parseInstant(envelope.protected.issuedAt);\n if (issuedAt === undefined) return false;\n if (issuedAt < now - clockSkewMs || issuedAt > now + clockSkewMs) return false;\n\n const expiry = envelope.protected.expiresAt;\n if (expiry === undefined) return true;\n const expiresAt = parseInstant(expiry);\n if (expiresAt === undefined || expiresAt < issuedAt) return false;\n if (expiresAt - issuedAt > maxLifetimeMs) return false;\n return now <= expiresAt + clockSkewMs;\n}\n\n/**\n * Authenticate a request-bound proof. Every rejected state is `undefined`, so\n * a route has one 401 response for malformed input, row misses, revocation,\n * stale epochs, binding changes, clock failures and bad signatures.\n */\nexport async function authenticateDeviceProof(\n input: unknown,\n request: DeviceProofRequestBinding,\n deps: DeviceProofAuthDeps,\n): Promise<AuthenticatedDeviceProof | undefined> {\n const clockSkewMs = deps.clockSkewMs ?? DEFAULT_DEVICE_PROOF_CLOCK_SKEW_MS;\n const maxLifetimeMs = deps.maxLifetimeMs ?? DEFAULT_DEVICE_PROOF_MAX_LIFETIME_MS;\n if (!validBound(clockSkewMs, MAX_DEVICE_PROOF_CLOCK_SKEW_MS)) return undefined;\n if (!validBound(maxLifetimeMs, MAX_DEVICE_PROOF_MAX_LIFETIME_MS)) return undefined;\n\n let envelope: DeviceProofEnvelopeV1;\n try {\n envelope = parseDeviceProofEnvelope(input);\n } catch {\n return undefined;\n }\n const claims = envelope.protected;\n\n if (claims.operation !== request.operation || claims.resource !== request.resource) {\n return undefined;\n }\n if (claims.operationId !== undefined) return undefined;\n if (claims.method !== request.method || claims.path !== request.path) return undefined;\n if (claims.bodySize !== request.body.byteLength) return undefined;\n if ((await deps.crypto.sha256(request.body)) !== claims.bodySha256) return undefined;\n\n if (!isTenantId(claims.tenantId)) return undefined;\n const row = await deps.devices.get(tenantId(claims.tenantId), claims.deviceId);\n if (row === undefined || row.revoked) return undefined;\n if (row.productId !== claims.productId) return undefined;\n if (row.proofKeyId !== claims.keyId || row.proofKeyEpoch !== claims.keyEpoch) {\n return undefined;\n }\n\n if (!timeBindingIsValid(envelope, deps.clock.now().getTime(), clockSkewMs, maxLifetimeMs)) {\n return undefined;\n }\n const verified = await deps.crypto.verifyEd25519(\n row.devicePublicKey,\n deviceProofSigningInput(claims),\n envelope.signature,\n );\n if (!verified) return undefined;\n\n return {\n device: {\n kind: 'device',\n tenantId: row.tenantId,\n productId: row.productId,\n deviceId: row.deviceId,\n },\n requestId: claims.requestId,\n operation: claims.operation,\n resource: claims.resource,\n bodySha256: claims.bodySha256,\n bodySize: BigInt(claims.bodySize),\n keyId: row.proofKeyId,\n keyEpoch: row.proofKeyEpoch,\n };\n}\n","import type {\n ContentHash,\n TenantId,\n TruthBodyRef,\n TruthManifestEntry,\n TruthManifestQuery,\n TruthRecord,\n TruthRecordKind,\n TruthRecordSelector,\n} from '@byok-sdk/core';\nimport { z } from 'zod';\n\nexport const TRUTH_RECORD_CAPABILITY = 'truth.records';\nexport const TRUTH_INLINE_CONTENT_TYPE = 'application/vnd.byok.truth+utf8';\nexport const TRUTH_REQUEST_ID_MAX_LENGTH = 120;\nexport const TRUTH_RECORD_KEY_MAX_LENGTH = 200;\nexport const TRUTH_LABEL_MAX_LENGTH = 200;\nexport const TRUTH_BATCH_MAX_RECORDS = 32;\nexport const TRUTH_MANIFEST_MAX_LIMIT = 100;\n\nconst CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\nconst RECORD_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;\n\nexport const TruthRecordKeySchema = z\n .string()\n .min(1)\n .max(TRUTH_RECORD_KEY_MAX_LENGTH)\n .regex(RECORD_KEY_PATTERN)\n .refine((value) => value !== '.' && value !== '..');\n\nexport const TruthBodyInputSchema = z.discriminatedUnion('kind', [\n z.strictObject({\n kind: z.literal('inline'),\n content: z.string(),\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n }),\n z.strictObject({\n kind: z.literal('object'),\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n byteSize: z.number().int().nonnegative().safe(),\n }),\n]);\n\nconst SnapshotCandidateSchema = z.strictObject({\n kind: z.enum(['profile', 'memory']),\n recordKey: TruthRecordKeySchema,\n expectedRev: z.number().int().nonnegative().safe(),\n body: TruthBodyInputSchema,\n label: z.string().max(TRUTH_LABEL_MAX_LENGTH).optional(),\n});\n\nexport const TruthWriteRequestSchema = z.strictObject({\n expectedRev: z.number().int().nonnegative().safe().optional(),\n body: TruthBodyInputSchema,\n label: z.string().max(TRUTH_LABEL_MAX_LENGTH).optional(),\n snapshots: z.array(SnapshotCandidateSchema).max(TRUTH_BATCH_MAX_RECORDS - 1).optional(),\n});\n\nexport type TruthBodyInput = z.infer<typeof TruthBodyInputSchema>;\nexport type TruthWriteRequest = z.infer<typeof TruthWriteRequestSchema>;\n\nexport type PreparedTruthWrite =\n | {\n readonly kind: 'task.terminal';\n readonly recordKey: string;\n readonly contentHash: ContentHash;\n readonly byteSize: bigint;\n readonly body: TruthBodyRef;\n readonly label?: string;\n }\n | {\n readonly kind: 'profile' | 'memory';\n readonly recordKey: string;\n readonly expectedRev: number;\n readonly contentHash: ContentHash;\n readonly byteSize: bigint;\n readonly body: TruthBodyRef;\n readonly label?: string;\n };\n\nexport interface TruthCommitInput {\n readonly deviceId: string;\n readonly requestId: string;\n readonly operation: string;\n readonly resource: string;\n readonly proofBodySha256: string;\n readonly proofBodySize: bigint;\n readonly writes: readonly [PreparedTruthWrite, ...PreparedTruthWrite[]];\n}\n\nexport interface TruthRecordMetadata {\n readonly kind: TruthRecordKind;\n readonly recordKey: string;\n readonly rev: number;\n readonly contentHash: string;\n readonly byteSize: number;\n readonly label?: string;\n readonly updatedAt: string;\n}\n\nexport const TruthRecordMetadataSchema = z.strictObject({\n kind: z.enum(['task.terminal', 'profile', 'memory']),\n recordKey: TruthRecordKeySchema,\n rev: z.number().int().positive().safe(),\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n byteSize: z.number().int().nonnegative().safe(),\n label: z.string().max(TRUTH_LABEL_MAX_LENGTH).optional(),\n updatedAt: z.string().datetime({ offset: true }),\n});\n\nexport interface TruthCommitResponse {\n readonly primary: TruthRecordMetadata;\n readonly snapshots: readonly TruthRecordMetadata[];\n}\n\nexport const TruthCommitResponseSchema = z.strictObject({\n primary: TruthRecordMetadataSchema,\n snapshots: z.array(TruthRecordMetadataSchema).max(TRUTH_BATCH_MAX_RECORDS - 1),\n});\n\nexport interface TruthCommitResult {\n readonly response: TruthCommitResponse;\n readonly replayed: boolean;\n}\n\nexport interface TruthCommitter {\n commit(tenant: TenantId, input: TruthCommitInput): Promise<TruthCommitResult>;\n getRecord(tenant: TenantId, selector: TruthRecordSelector): Promise<TruthRecord | undefined>;\n listManifest(\n tenant: TenantId,\n query: TruthManifestQuery,\n ): Promise<readonly TruthManifestEntry[]>;\n}\n\n/**\n * Object download grant authority for truth bodies. The input is the canonical\n * content hash stored in `TruthBodyRef`, never an opaque upload id.\n */\nexport interface TruthObjectDownloads {\n getDownloadUrl(tenant: TenantId, hash: ContentHash): Promise<string | undefined>;\n}\n\nexport function truthRecordMetadata(record: TruthRecord): TruthRecordMetadata {\n const byteSize = Number(record.byteSize);\n if (!Number.isSafeInteger(byteSize)) throw new Error('truth record byte size exceeds JSON range');\n return {\n kind: record.kind,\n recordKey: record.recordKey,\n rev: record.rev,\n contentHash: record.contentHash,\n byteSize,\n ...(record.label === undefined ? {} : { label: record.label }),\n updatedAt: record.writtenAt,\n };\n}\n\nexport function truthManifestMetadata(entry: TruthManifestEntry): TruthRecordMetadata {\n const byteSize = Number(entry.byteSize);\n if (!Number.isSafeInteger(byteSize)) throw new Error('truth manifest byte size exceeds JSON range');\n return {\n kind: entry.kind,\n recordKey: entry.recordKey,\n rev: entry.rev,\n contentHash: entry.contentHash,\n byteSize,\n ...(entry.label === undefined ? {} : { label: entry.label }),\n updatedAt: entry.updatedAt,\n };\n}\n","export const TRUTH_COMMIT_ERROR_CODES = [\n 'proof_request_conflict',\n 'truth_object_not_committed',\n] as const;\n\nexport type TruthCommitErrorCode = (typeof TRUTH_COMMIT_ERROR_CODES)[number];\n\nexport class TruthCommitError extends Error {\n readonly code: TruthCommitErrorCode;\n readonly current?: unknown;\n\n constructor(code: TruthCommitErrorCode, message: string, current?: unknown) {\n super(message);\n this.name = 'TruthCommitError';\n this.code = code;\n this.current = current;\n }\n}\n\nexport function isTruthCommitError(value: unknown): value is TruthCommitError {\n return value instanceof TruthCommitError;\n}\n","import {\n DEVICE_PROOF_HEADER,\n STORAGE_ERROR_CODES,\n STORAGE_ERROR_HTTP_STATUS,\n TRUTH_RECORD_KINDS,\n contentHash,\n isCoreConflictError,\n isCoreError,\n principalTenant,\n type DevicePrincipal,\n type StorageErrorCode,\n type TruthManifestQuery,\n type TruthRecord,\n type TruthRecordKind,\n} from '@byok-sdk/core';\nimport type { Context } from 'hono';\nimport { authenticateDeviceProof, type DeviceProofAuthDeps } from '../auth/device-proof';\nimport {\n TRUTH_MANIFEST_MAX_LIMIT,\n TruthRecordKeySchema,\n TruthWriteRequestSchema,\n truthManifestMetadata,\n truthRecordMetadata,\n type PreparedTruthWrite,\n type TruthBodyInput,\n type TruthCommitInput,\n type TruthCommitter,\n type TruthObjectDownloads,\n type TruthRecordMetadata,\n} from '../truth/contract';\nimport { isTruthCommitError } from '../truth/errors';\n\n// Re-exported from core (single source of truth for the wire header); still\n// part of this module's public surface for callers importing it from cloud.\nexport { DEVICE_PROOF_HEADER };\nexport const DEFAULT_MAX_TRUTH_REQUEST_BYTES = 2 * 1024 * 1024;\nexport const MAX_DEVICE_PROOF_HEADER_BYTES = 16 * 1024;\n\nconst EMPTY_BODY = new Uint8Array();\nconst RECORD_PREFIX_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;\n\nexport interface TruthRouteDeps {\n readonly proof: DeviceProofAuthDeps;\n readonly truth: TruthCommitter;\n readonly objectDownloads: TruthObjectDownloads;\n readonly maxRequestBytes: number;\n}\n\ninterface ProofContext {\n readonly device: DevicePrincipal;\n readonly requestId: string;\n readonly operation: string;\n readonly resource: string;\n readonly bodySha256: string;\n readonly bodySize: bigint;\n}\n\nexport function truthManifestHandler(deps: TruthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const authenticated = await authenticateTruthRequest(c, deps, {\n body: EMPTY_BODY,\n operation: 'truth.list',\n resource: 'records',\n });\n if (authenticated === undefined) return unauthorized(c);\n\n const query = manifestQuery(c);\n if (query === undefined) return c.json({ error: 'invalid truth manifest query' }, 400);\n const records = await deps.truth.listManifest(principalTenant(authenticated.device), query);\n return c.json({ records: records.map(truthManifestMetadata) }, 200);\n };\n}\n\nexport function truthGetHandler(deps: TruthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const resource = rawRecordResource(c);\n const authenticated = await authenticateTruthRequest(c, deps, {\n body: EMPTY_BODY,\n operation: 'truth.read',\n resource,\n });\n if (authenticated === undefined) return unauthorized(c);\n const selector = recordSelector(c);\n if (selector === undefined) return c.json({ error: 'invalid truth record selector' }, 400);\n\n const record = await deps.truth.getRecord(principalTenant(authenticated.device), selector);\n if (record === undefined) return c.json({ error: 'truth_record_not_found' }, 404);\n const metadata = truthRecordMetadata(record);\n if (record.body.kind === 'inline') {\n return c.json({ ...metadata, body: { kind: 'inline', content: record.body.body } }, 200);\n }\n\n const downloadUrl = await deps.objectDownloads.getDownloadUrl(\n principalTenant(authenticated.device),\n record.body.hash,\n );\n if (downloadUrl === undefined) return c.json({ error: 'object_not_found' }, 404);\n return c.json({ ...metadata, body: { kind: 'object', downloadUrl } }, 200);\n };\n}\n\nexport function truthPutHandler(deps: TruthRouteDeps) {\n return async (c: Context): Promise<Response> => {\n const body = await readBoundedBody(c, deps.maxRequestBytes);\n if (body === 'too_large') return c.json({ error: 'truth request body too large' }, 413);\n if (body === undefined) return c.json({ error: 'invalid truth request body' }, 400);\n\n const authenticated = await authenticateTruthRequest(c, deps, {\n body,\n operation: 'truth.write',\n resource: rawRecordResource(c),\n });\n if (authenticated === undefined) return unauthorized(c);\n const selector = recordSelector(c);\n if (selector === undefined) return c.json({ error: 'invalid truth record selector' }, 400);\n\n const parsedJson = parseJsonBytes(body);\n const parsed = TruthWriteRequestSchema.safeParse(parsedJson);\n if (!parsed.success) return c.json({ error: 'invalid truth write request' }, 400);\n const writes = prepareWrites(selector.kind, selector.recordKey, parsed.data);\n if (writes === undefined) return c.json({ error: 'invalid truth write model' }, 400);\n\n const input: TruthCommitInput = {\n deviceId: authenticated.device.deviceId,\n requestId: authenticated.requestId,\n operation: authenticated.operation,\n resource: authenticated.resource,\n proofBodySha256: authenticated.bodySha256,\n proofBodySize: authenticated.bodySize,\n writes,\n };\n try {\n const result = await deps.truth.commit(principalTenant(authenticated.device), input);\n return c.json(result.response, 200, { 'x-byok-replayed': result.replayed ? 'true' : 'false' });\n } catch (caught) {\n return truthFailure(c, caught);\n }\n };\n}\n\nfunction recordSelector(\n c: Context,\n): { readonly kind: TruthRecordKind; readonly recordKey: string } | undefined {\n const kind = c.req.param('kind');\n const recordKey = c.req.param('key');\n if (!TRUTH_RECORD_KINDS.includes(kind as TruthRecordKind)) return undefined;\n const parsedKey = TruthRecordKeySchema.safeParse(recordKey);\n if (!parsedKey.success) return undefined;\n return { kind: kind as TruthRecordKind, recordKey: parsedKey.data };\n}\n\nfunction rawRecordResource(c: Context): string {\n return `${c.req.param('kind') ?? ''}/${c.req.param('key') ?? ''}`;\n}\n\nfunction manifestQuery(c: Context): TruthManifestQuery | undefined {\n const url = new URL(c.req.url);\n for (const key of url.searchParams.keys()) {\n if (\n (key !== 'kind' && key !== 'prefix' && key !== 'limit') ||\n url.searchParams.getAll(key).length !== 1\n ) {\n return undefined;\n }\n }\n const kind = url.searchParams.get('kind') ?? undefined;\n if (kind !== undefined && !TRUTH_RECORD_KINDS.includes(kind as TruthRecordKind)) return undefined;\n const keyPrefix = url.searchParams.get('prefix') ?? undefined;\n if (\n keyPrefix !== undefined &&\n (keyPrefix.length === 0 || keyPrefix.length > 200 || !RECORD_PREFIX_PATTERN.test(keyPrefix))\n ) {\n return undefined;\n }\n const limitRaw = url.searchParams.get('limit') ?? undefined;\n const limit = limitRaw === undefined ? TRUTH_MANIFEST_MAX_LIMIT : Number(limitRaw);\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > TRUTH_MANIFEST_MAX_LIMIT) return undefined;\n return {\n ...(kind === undefined ? {} : { kind: kind as TruthRecordKind }),\n ...(keyPrefix === undefined ? {} : { keyPrefix }),\n limit,\n };\n}\n\nfunction prepareWrites(\n kind: TruthRecordKind,\n recordKey: string,\n request: ReturnType<typeof TruthWriteRequestSchema.parse>,\n): readonly [PreparedTruthWrite, ...PreparedTruthWrite[]] | undefined {\n if (kind === 'task.terminal') {\n if (request.expectedRev !== undefined) return undefined;\n } else if (request.expectedRev === undefined || request.snapshots !== undefined) {\n return undefined;\n }\n\n const primary = prepareWrite(kind, recordKey, request.body, request.expectedRev, request.label);\n const snapshots = (request.snapshots ?? []).map((snapshot) =>\n prepareWrite(\n snapshot.kind,\n snapshot.recordKey,\n snapshot.body,\n snapshot.expectedRev,\n snapshot.label,\n ),\n );\n return [primary, ...snapshots];\n}\n\nfunction prepareWrite(\n kind: TruthRecordKind,\n recordKey: string,\n input: TruthBodyInput,\n expectedRev: number | undefined,\n label: string | undefined,\n): PreparedTruthWrite {\n const hash = contentHash(input.contentHash);\n const body =\n input.kind === 'inline'\n ? ({ kind: 'inline', body: input.content } as const)\n : ({ kind: 'object', hash } as const);\n const byteSize =\n input.kind === 'inline'\n ? BigInt(new TextEncoder().encode(input.content).byteLength)\n : BigInt(input.byteSize);\n if (kind === 'task.terminal') {\n return { kind, recordKey, contentHash: hash, byteSize, body, ...(label === undefined ? {} : { label }) };\n }\n if (expectedRev === undefined) throw new Error('snapshot expectedRev was not validated');\n return {\n kind,\n recordKey,\n expectedRev,\n contentHash: hash,\n byteSize,\n body,\n ...(label === undefined ? {} : { label }),\n };\n}\n\nasync function authenticateTruthRequest(\n c: Context,\n deps: TruthRouteDeps,\n request: { readonly body: Uint8Array; readonly operation: string; readonly resource: string },\n): Promise<ProofContext | undefined> {\n const proof = decodeProofHeader(c.req.header(DEVICE_PROOF_HEADER));\n if (proof === undefined) return undefined;\n const url = new URL(c.req.url);\n return authenticateDeviceProof(\n proof,\n {\n method: c.req.method,\n path: `${url.pathname}${url.search}`,\n operation: request.operation,\n resource: request.resource,\n body: request.body,\n },\n deps.proof,\n );\n}\n\nfunction decodeProofHeader(value: string | undefined): unknown | undefined {\n if (value === undefined || value.length === 0 || value.length > MAX_DEVICE_PROOF_HEADER_BYTES) {\n return undefined;\n }\n if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1) return undefined;\n try {\n const padded = value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (value.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));\n return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));\n } catch {\n return undefined;\n }\n}\n\nasync function readBoundedBody(\n c: Context,\n maximum: number,\n): Promise<Uint8Array | 'too_large' | undefined> {\n const length = c.req.header('content-length');\n if (length !== undefined) {\n const parsed = Number(length);\n if (!Number.isSafeInteger(parsed) || parsed < 0) return undefined;\n if (parsed > maximum) return 'too_large';\n }\n try {\n const bytes = new Uint8Array(await c.req.arrayBuffer());\n return bytes.byteLength > maximum ? 'too_large' : bytes;\n } catch {\n return undefined;\n }\n}\n\nfunction parseJsonBytes(bytes: Uint8Array): unknown | undefined {\n try {\n return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));\n } catch {\n return undefined;\n }\n}\n\nfunction unauthorized(c: Context): Response {\n return c.json({ error: 'unauthorized' }, 401);\n}\n\nfunction truthFailure(c: Context, caught: unknown): Response {\n if (isCoreConflictError<TruthRecord | undefined>(caught)) {\n const current: TruthRecordMetadata | null =\n caught.current === undefined ? null : truthRecordMetadata(caught.current);\n return c.json({ error: caught.code, current, observedAt: caught.observedAt }, 409);\n }\n if (isTruthCommitError(caught)) {\n return c.json({ error: caught.code, ...(caught.current === undefined ? {} : { current: caught.current }) }, 409);\n }\n if (isCoreError(caught)) {\n if ((STORAGE_ERROR_CODES as readonly string[]).includes(caught.code)) {\n const code = caught.code as StorageErrorCode;\n return c.json({ error: code }, STORAGE_ERROR_HTTP_STATUS[code]);\n }\n if (caught.code === 'storage_entitlement_missing' || caught.code === 'object_state_invalid') {\n return c.json({ error: caught.code }, 409);\n }\n if (caught.code === 'content_hash_invalid') return c.json({ error: caught.code }, 400);\n }\n throw caught;\n}\n","/**\n * The route inventory (sprint I1).\n *\n * Isolation review starts by asking \"what routes exist, and what does each one\n * require?\" — a question that is only answerable if the answer cannot drift\n * from what is actually mounted. So mounting goes through {@link\n * CloudRouteRegistry.register} and nowhere else: the registry owns the Hono\n * app, hands out no reference to it that could be mounted on directly, and\n * records a class for every route as it goes.\n *\n * `src/__tests__/route-inventory.test.ts` closes that loop in BOTH directions\n * against Hono's own `app.routes` table: a mounted route missing from the\n * inventory fails the suite, and an inventoried route that never reached the\n * router fails it too. A route whose class is not one of {@link ROUTE_CLASSES}\n * cannot be registered at all.\n */\nimport { Hono, type Context } from 'hono';\n\n/**\n * What a route requires of its caller. Not a description of the handler's\n * work — a description of the credential it is authenticated by, which is the\n * thing an isolation review has to enumerate:\n *\n * - `device` — a bearer access token; resolves to a `DevicePrincipal` and a\n * tenant-closed facade.\n * - `proof` — a request-bound Ed25519 device proof; tenant/product/key\n * authority comes from the current device row, not protected claims.\n * - `presigned` — no principal at all; an HMAC signature over the resource id\n * plus an expiry IS the credential (§7's two `/content` routes).\n * - `public` — deliberately unauthenticated; must expose nothing tenant-scoped.\n */\nexport const ROUTE_CLASSES = ['device', 'proof', 'presigned', 'public'] as const;\nexport type RouteClass = (typeof ROUTE_CLASSES)[number];\n\nexport const ROUTE_METHODS = ['GET', 'POST', 'PUT'] as const;\nexport type RouteMethod = (typeof ROUTE_METHODS)[number];\n\nexport interface RouteDescriptor {\n readonly method: RouteMethod;\n readonly path: string;\n readonly class: RouteClass;\n}\n\nexport type CloudRouteHandler = (c: Context) => Response | Promise<Response>;\n\nexport function routeKey(route: { readonly method: string; readonly path: string }): string {\n return `${route.method} ${route.path}`;\n}\n\nexport class CloudRouteRegistry {\n readonly #app = new Hono();\n readonly #routes: RouteDescriptor[] = [];\n\n register(descriptor: RouteDescriptor, handler: CloudRouteHandler): void {\n if (!(ROUTE_CLASSES as readonly string[]).includes(descriptor.class)) {\n throw new Error(`Route ${routeKey(descriptor)} has no valid isolation class`);\n }\n if (!(ROUTE_METHODS as readonly string[]).includes(descriptor.method)) {\n throw new Error(`Route ${routeKey(descriptor)} uses an unsupported method`);\n }\n if (this.#routes.some((existing) => routeKey(existing) === routeKey(descriptor))) {\n throw new Error(`Route ${routeKey(descriptor)} is already registered`);\n }\n this.#routes.push(descriptor);\n this.#app.on(descriptor.method, descriptor.path, handler);\n }\n\n /** The inventory, in registration order. */\n get routes(): readonly RouteDescriptor[] {\n return this.#routes;\n }\n\n /** What the router actually mounted, read back off Hono itself — the other half of the I1 comparison. */\n get mounted(): readonly { readonly method: string; readonly path: string }[] {\n return this.#app.routes.map((route) => ({ method: route.method, path: route.path }));\n }\n\n get fetch(): (request: Request, ...rest: unknown[]) => Response | Promise<Response> {\n return this.#app.fetch as (request: Request, ...rest: unknown[]) => Response | Promise<Response>;\n }\n}\n","import { decodeEnvelope, type BlobRef, type Envelope } from '@byok-sdk/protocol';\nimport { ByokCloudError } from './errors';\nimport type { RequestReceipt } from './stores/ports';\n\n/**\n * The typed terminal read model — the hosted counterpart of the embedded\n * coordinator's `TaskResult`, projected off the receipt the inbound gate\n * stores. Every field is copied verbatim from the payload the gate already\n * zod-parsed before storing (`recordTerminal`, `inbound.ts`); this projection\n * neither re-validates nor synthesizes one.\n */\nexport interface TerminalResult {\n readonly taskId: string;\n readonly state: 'complete' | 'failed' | 'cancelled';\n readonly summary?: string;\n readonly sessionRef?: string;\n readonly artifactRefs?: readonly BlobRef[];\n /**\n * The product's structured terminal result, verbatim `task.complete.document`.\n * Absent — key missing, never null — when the daemon sent none, which covers\n * both a legacy pre-`result-document` build and a daemon with no\n * `resultDocument` extractor.\n */\n readonly document?: unknown;\n readonly reason?: string;\n readonly retryable?: boolean;\n /** When the receipt store wrote the terminal fact — the first one, by its own first-write-wins rule. */\n readonly recordedAt: string;\n}\n\n/**\n * Pure projection of a terminal receipt onto {@link TerminalResult}. `taskId`\n * names the task the receipt was read for (the receipt's key carries it, its\n * body does not); `recordedAt` is the receipt store's write time.\n *\n * Fail closed on anything but a terminal envelope: the stored body is\n * `encodeEnvelope` of what the inbound gate accepted, so an undecodable body\n * or a non-terminal type means the receipt-store contract itself broke — an\n * error, never a best-effort shape.\n */\nexport function projectTerminalResult(taskId: string, receipt: RequestReceipt): TerminalResult {\n let envelope: Envelope;\n try {\n envelope = decodeEnvelope(receipt.body);\n } catch (cause) {\n throw new ByokCloudError(\n 'terminal_receipt_unreadable',\n `The terminal receipt for task ${taskId} holds a body that is not a decodable envelope.`,\n { cause },\n );\n }\n switch (envelope.type) {\n case 'task.complete':\n return {\n taskId,\n state: 'complete',\n summary: envelope.payload.summary,\n sessionRef: envelope.payload.sessionRef,\n ...(envelope.payload.artifactRefs !== undefined\n ? { artifactRefs: envelope.payload.artifactRefs }\n : {}),\n ...(envelope.payload.document !== undefined ? { document: envelope.payload.document } : {}),\n recordedAt: receipt.recordedAt,\n };\n case 'task.fail':\n return {\n taskId,\n state: 'failed',\n reason: envelope.payload.reason,\n ...(envelope.payload.retryable !== undefined\n ? { retryable: envelope.payload.retryable }\n : {}),\n recordedAt: receipt.recordedAt,\n };\n case 'task.cancelled':\n return {\n taskId,\n state: 'cancelled',\n ...(envelope.payload.reason !== undefined ? { reason: envelope.payload.reason } : {}),\n recordedAt: receipt.recordedAt,\n };\n default:\n throw new ByokCloudError(\n 'terminal_receipt_unreadable',\n `The terminal receipt for task ${taskId} holds a ${envelope.type} envelope, which is not a terminal type.`,\n );\n }\n}\n","/**\n * `createByokCloud` — the hosted device surface, assembled.\n *\n * What this is NOT: an embedded coordinator. There is no `TaskHandle`, no\n * connection registry, no per-task object that a host holds onto. Sprint 0.1's\n * non-goal is explicit about that — the embedded `TaskHandle` must not become\n * the hosted API — so the host's control-plane input is a function\n * ({@link ByokCloud.enqueueOffer}) and its read model is a store query\n * ({@link ByokCloud.readTaskAttempt}).\n *\n * Every route is stateless in the strict sense: it resolves a principal from\n * the request, binds stores to that principal's tenant, and returns. Nothing\n * survives the response but what a store wrote. The one shape that would\n * quietly undo that — a Running/session map — is asserted absent by\n * `src/__tests__/constraints.test.ts`.\n */\nimport {\n contentHash,\n parseCapabilityDeclaration,\n type BoardItem,\n type BoardItemInput,\n type BoardListQuery,\n type BoardPage,\n type CapabilityDeclaration,\n type Clock,\n type ControlPlanePrincipal,\n type CoreStores,\n type PresenceHint,\n type SkillPackStore,\n type TenantId,\n} from '@byok-sdk/core';\nimport type { ActivityTail } from './activity';\nimport type { ApprovalTimelineTail } from './approval-timeline';\nimport {\n BYOK_ACTIVITY_PATH,\n BYOK_BLOB_CONTENT_ROUTE,\n BYOK_BLOB_FINALIZE_ROUTE,\n BYOK_BLOB_URL_ROUTE,\n BYOK_BLOBS_PATH,\n BYOK_BOARD_CLAIM_ROUTE,\n BYOK_BOARD_PATH,\n BYOK_BOARD_STATUS_ROUTE,\n BYOK_BOARD_STREAM_PATH,\n BYOK_BOARD_UNCLAIM_ROUTE,\n BYOK_CAPABILITIES_PATH,\n BYOK_CHALLENGE_PATH,\n BYOK_EVENTS_PATH,\n BYOK_MESSAGES_PATH,\n BYOK_PAIR_PATH,\n BYOK_PRESENCE_PATH,\n BYOK_RECORD_ROUTE,\n BYOK_RECORDS_PATH,\n BYOK_SKILL_PACK_FILE_ROUTE,\n BYOK_SKILL_PACKS_PATH,\n BYOK_TOKEN_PATH,\n createEnvelope,\n decodeEnvelope,\n encodeEnvelope,\n type Envelope,\n type TaskOfferPayload,\n type TaskOfferWithToolsetsPayload,\n} from '@byok-sdk/protocol';\nimport { createAuthPlane, type AuthPlane } from './auth/plane';\nimport type { TokenSigner } from './auth/tokens';\nimport { CLOUD_CAPABILITIES, declares } from './capabilities';\nimport {\n assertBoardLabels,\n DEFAULT_ACTIVITY_CAPACITY,\n DEFAULT_ACTIVITY_MAX_BYTES,\n DEFAULT_ACTIVITY_MAX_EVENTS,\n DEFAULT_ACTIVITY_TTL_MS,\n DEFAULT_BOARD_CHANNEL_MAX_BYTES,\n DEFAULT_BOARD_TITLE_MAX_BYTES,\n DEFAULT_PRESENCE_DETAIL_MAX_BYTES,\n DEFAULT_PRESENCE_MINIMUM_INTERVAL_MS,\n DEFAULT_PRESENCE_TTL_MS,\n type ActivityBounds,\n} from './coordination';\nimport type { CloudCrypto } from './crypto/port';\nimport { ByokCloudError } from './errors';\nimport {\n blobDownloadContentHandler,\n blobDownloadUrlHandler,\n blobUploadContentHandler,\n createBlobHandler,\n finalizeBlobHandler,\n} from './handlers/blobs';\nimport { capabilitiesHandler } from './handlers/capabilities';\nimport { challengeHandler, pairHandler, tokenHandler } from './handlers/auth';\nimport { eventsHandler } from './handlers/events';\nimport { messagesHandler } from './handlers/messages';\nimport {\n boardClaimHandler,\n boardListHandler,\n boardStatusHandler,\n boardStreamHandler,\n boardUnclaimHandler,\n DEFAULT_BOARD_PAGE_LIMIT,\n DEFAULT_BOARD_STREAM_HEARTBEAT_INTERVAL_MS,\n DEFAULT_BOARD_STREAM_QUERY_INTERVAL_MS,\n DEFAULT_BOARD_STREAM_RECONCILIATION_INTERVAL_MS,\n} from './handlers/board';\nimport { activityAppendHandler, presencePublishHandler } from './handlers/presence';\nimport {\n DEFAULT_SKILL_PACK_PAGE_LIMIT,\n skillPackFileHandler,\n skillPackListHandler,\n} from './handlers/skill-packs';\nimport {\n DEFAULT_MAX_TRUTH_REQUEST_BYTES,\n truthGetHandler,\n truthManifestHandler,\n truthPutHandler,\n} from './handlers/truth';\nimport { CloudRouteRegistry, type RouteDescriptor } from './router/registry';\nimport { terminalReceiptKey } from './inbound';\nimport type {\n BlobContentProxy,\n CloudStores,\n DeviceRecord,\n PairingCodeInfo,\n RequestReceipt,\n TaskAttempt,\n} from './stores/ports';\nimport { projectTerminalResult, type TerminalResult } from './terminal-result';\nimport { tenantStoresFor, type CloudRootStores } from './tenant-stores';\nimport type { TruthCommitter, TruthObjectDownloads } from './truth/contract';\n\n/** Matches the reference server's ceiling (§7). */\nexport const DEFAULT_MAX_BLOB_SIZE_BYTES = 100 * 1024 * 1024;\n/** Matches the reference server's hold (§8). */\nexport const DEFAULT_LONG_POLL_HOLD_MS = 50_000;\n/** How often a held poll re-reads the mailbox. */\nexport const DEFAULT_LONG_POLL_INTERVAL_MS = 250;\n/** Rows per `GET /byok/events` response. */\nexport const DEFAULT_EVENTS_PAGE_LIMIT = 50;\n\nexport interface ByokCloudOptions {\n readonly core: CoreStores;\n readonly cloud: CloudStores;\n /**\n * Byte proxying for the two `/byok/blobs/:id/content` routes. OPTIONAL, and\n * absent is a first-class answer: a composition backed by object storage\n * hands the device a presigned URL to the object store and never carries a\n * byte, so it has nothing to supply here. Supplying it is necessary but not\n * sufficient for the routes to exist — the deployment must also declare\n * `blobs.contentproxy` (ADR-010).\n */\n readonly blobContentProxy?: BlobContentProxy;\n /** Atomic proof receipt + truth/reference/accounting authority for S6 routes. */\n readonly truthCommitter?: TruthCommitter;\n /** Content-hash keyed object GET grants for object-backed truth bodies. */\n readonly truthObjectDownloads?: TruthObjectDownloads;\n /**\n * Tenant-scoped skill pack catalogue. OPTIONAL, and absent is a first-class\n * answer: a deployment that distributes no declarative content supplies\n * nothing here and declares no `skills.pack`. Supplying it is necessary but\n * not sufficient for the routes to exist — the deployment must also declare\n * the capability (ADR-010), the same asymmetry the byte proxy above has.\n */\n readonly skillPacks?: SkillPackStore;\n readonly crypto: CloudCrypto;\n readonly tokenSigner: TokenSigner;\n readonly clock: Clock;\n /** What this deployment serves (ADR-010). Routes are mounted from it, so it can never over-declare. */\n readonly capabilities: CapabilityDeclaration;\n /** Recorded on the control-plane principal every host-side call is made under. */\n readonly operatorId?: string;\n readonly maxBlobSizeBytes?: number;\n readonly longPollHoldMs?: number;\n readonly longPollIntervalMs?: number;\n readonly eventsPageLimit?: number;\n readonly accessTokenTtlSeconds?: number;\n readonly boardPageLimit?: number;\n readonly boardStreamQueryIntervalMs?: number;\n readonly boardStreamHeartbeatIntervalMs?: number;\n readonly boardStreamReconciliationIntervalMs?: number;\n readonly boardChannelMaxBytes?: number;\n readonly boardTitleMaxBytes?: number;\n readonly presenceTtlMs?: number;\n readonly presenceMinimumIntervalMs?: number;\n readonly presenceDetailMaxBytes?: number;\n readonly activityMaxEvents?: number;\n readonly activityMaxBytes?: number;\n readonly activityCapacity?: number;\n readonly activityTtlMs?: number;\n readonly maxTruthRequestBytes?: number;\n readonly skillPackPageLimit?: number;\n}\n\nexport interface EnqueueOfferInput {\n /** Supply one to make the enqueue addressable by the host's own id; otherwise cloud mints one. */\n readonly taskId?: string;\n readonly payload: TaskOfferPayload;\n}\n\nexport interface EnqueueToolsetOfferInput {\n /** Supply one to make the enqueue addressable by the host's own id; otherwise cloud mints one. */\n readonly taskId?: string;\n /** Strict control payload containing logical ids only; executable MCP definitions are not part of this type. */\n readonly payload: TaskOfferWithToolsetsPayload;\n}\n\nexport interface EnqueuedOffer {\n readonly taskId: string;\n /** The per-(tenant, device) delivery seq — the daemon's redelivery cursor position for this envelope. */\n readonly seq: number;\n readonly envelope: Envelope;\n readonly attempt: TaskAttempt;\n}\n\nexport interface ByokCloud {\n /** WHATWG fetch handler — mount on `@hono/node-server`, a Worker, or Deno. */\n readonly fetch: (request: Request, ...rest: unknown[]) => Response | Promise<Response>;\n /** The I1 route inventory: every mounted route and the credential class it requires. */\n readonly routes: readonly RouteDescriptor[];\n /**\n * What the router ACTUALLY holds, read back off the router itself. Exposed\n * so the I1 matrix can close in both directions: an inventory is only\n * evidence if a route mounted some other way would show up here without a\n * matching entry in {@link routes}.\n */\n readonly mountedRoutes: readonly { readonly method: string; readonly path: string }[];\n readonly capabilities: CapabilityDeclaration;\n /** Host control plane: mint a single-use pairing code for a tenant/product. */\n createPairingCode(tenant: TenantId, input: { readonly productId: string; readonly ttlMs?: number }): Promise<PairingCodeInfo>;\n /** Host control plane: hand a device a frozen-v1 `task.offer`. The hosted replacement for `dispatch()` — a function, not a handle. */\n enqueueOffer(tenant: TenantId, deviceId: string, input: EnqueueOfferInput): Promise<EnqueuedOffer>;\n /** Host control plane: enqueue the additive fail-closed offer variant that requires local MCP toolsets. */\n enqueueToolsetOffer(tenant: TenantId, deviceId: string, input: EnqueueToolsetOfferInput): Promise<EnqueuedOffer>;\n readTaskAttempt(tenant: TenantId, taskId: string): Promise<TaskAttempt | undefined>;\n /** The recorded terminal for a task — the first one, re-encoded canonically under the frozen v1 codec (see `recordTerminal`, `inbound.ts`: the stored body is `encodeEnvelope` of the zod-parsed envelope, not the device's original byte sequence). */\n readTerminalReceipt(tenant: TenantId, taskId: string): Promise<RequestReceipt | undefined>;\n /**\n * Host control plane: the same first terminal, decoded into the typed read\n * model ({@link TerminalResult}) so a host reads result fields, not envelope\n * prose. `undefined` ONLY means no terminal fact is recorded yet:\n * first-terminal-wins is inherited from the receipt store\n * ({@link ByokCloud.readTerminalReceipt} reads the same row), and a declined\n * task records no terminal at all — use {@link ByokCloud.readTaskAttempt}\n * for that attempt status. An absent `document` covers both a legacy\n * pre-`result-document` daemon build and a daemon with no `resultDocument`\n * extractor; a receipt whose body is not a terminal envelope throws rather\n * than returning a best-effort shape.\n */\n readTaskResult(tenant: TenantId, taskId: string): Promise<TerminalResult | undefined>;\n listDevices(tenant: TenantId): Promise<readonly DeviceRecord[]>;\n revokeDevice(tenant: TenantId, deviceId: string): Promise<void>;\n /** Host control plane: create a board row from explicit producer labels. */\n createBoardItem(tenant: TenantId, input: BoardItemInput): Promise<BoardItem>;\n listBoardItems(tenant: TenantId, query: BoardListQuery): Promise<BoardPage>;\n /** Human review authority. Device routes cannot produce `done`. */\n acceptBoardItem(tenant: TenantId, itemId: string): Promise<BoardItem>;\n listPresence(tenant: TenantId): Promise<readonly PresenceHint[]>;\n readActivity(tenant: TenantId, taskId: string): Promise<ActivityTail | undefined>;\n readApprovalTimeline(\n tenant: TenantId,\n taskId: string,\n ): Promise<ApprovalTimelineTail | undefined>;\n}\n\nexport function createByokCloud(options: ByokCloudOptions): ByokCloud {\n const declaration = parseDeclaration(options.capabilities);\n assertNoOverDeclaration(\n declaration,\n options.blobContentProxy,\n options.truthCommitter,\n options.truthObjectDownloads,\n options.skillPacks,\n );\n const root: CloudRootStores = { core: options.core, cloud: options.cloud };\n const auth: AuthPlane = createAuthPlane({\n stores: options.cloud,\n crypto: options.crypto,\n clock: options.clock,\n tokenSigner: options.tokenSigner,\n ...(options.accessTokenTtlSeconds !== undefined\n ? { accessTokenTtlSeconds: options.accessTokenTtlSeconds }\n : {}),\n });\n\n const deviceRouteDeps = {\n root,\n bearer: { tokenSigner: options.tokenSigner, devices: options.cloud.devices },\n };\n\n const registry = new CloudRouteRegistry();\n const activityBounds: ActivityBounds = {\n maxEvents: options.activityMaxEvents ?? DEFAULT_ACTIVITY_MAX_EVENTS,\n maxBytes: options.activityMaxBytes ?? DEFAULT_ACTIVITY_MAX_BYTES,\n capacity: options.activityCapacity ?? DEFAULT_ACTIVITY_CAPACITY,\n ttlMs: options.activityTtlMs ?? DEFAULT_ACTIVITY_TTL_MS,\n };\n\n // Auth v2 (§6) — always mounted: without pairing there is no deployment.\n registry.register({ method: 'POST', path: BYOK_PAIR_PATH, class: 'public' }, pairHandler({ auth }));\n registry.register({ method: 'POST', path: BYOK_CHALLENGE_PATH, class: 'public' }, challengeHandler({ auth }));\n registry.register({ method: 'POST', path: BYOK_TOKEN_PATH, class: 'public' }, tokenHandler({ auth }));\n\n // ADR-010 — the declaration itself is always readable; a client that cannot\n // read it has no way to learn anything else without probing status codes.\n registry.register(\n { method: 'GET', path: BYOK_CAPABILITIES_PATH, class: 'public' },\n capabilitiesHandler({ declaration }),\n );\n\n if (declares(declaration, CLOUD_CAPABILITIES.eventsLongPoll)) {\n registry.register(\n { method: 'GET', path: BYOK_EVENTS_PATH, class: 'device' },\n eventsHandler({\n ...deviceRouteDeps,\n longPollHoldMs: options.longPollHoldMs ?? DEFAULT_LONG_POLL_HOLD_MS,\n longPollIntervalMs: options.longPollIntervalMs ?? DEFAULT_LONG_POLL_INTERVAL_MS,\n pageLimit: options.eventsPageLimit ?? DEFAULT_EVENTS_PAGE_LIMIT,\n }),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.messagesBatch)) {\n registry.register(\n { method: 'POST', path: BYOK_MESSAGES_PATH, class: 'device' },\n messagesHandler({ ...deviceRouteDeps, activityBounds }),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.boardCoordination)) {\n const boardDeps = {\n ...deviceRouteDeps,\n pageLimit: options.boardPageLimit ?? DEFAULT_BOARD_PAGE_LIMIT,\n };\n registry.register({ method: 'GET', path: BYOK_BOARD_PATH, class: 'device' }, boardListHandler(boardDeps));\n registry.register(\n { method: 'POST', path: BYOK_BOARD_CLAIM_ROUTE, class: 'device' },\n boardClaimHandler(deviceRouteDeps),\n );\n registry.register(\n { method: 'POST', path: BYOK_BOARD_UNCLAIM_ROUTE, class: 'device' },\n boardUnclaimHandler(deviceRouteDeps),\n );\n registry.register(\n { method: 'POST', path: BYOK_BOARD_STATUS_ROUTE, class: 'device' },\n boardStatusHandler(deviceRouteDeps),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.boardSse)) {\n registry.register(\n { method: 'GET', path: BYOK_BOARD_STREAM_PATH, class: 'device' },\n boardStreamHandler({\n ...deviceRouteDeps,\n pageLimit: options.boardPageLimit ?? DEFAULT_BOARD_PAGE_LIMIT,\n queryIntervalMs: options.boardStreamQueryIntervalMs ?? DEFAULT_BOARD_STREAM_QUERY_INTERVAL_MS,\n heartbeatIntervalMs:\n options.boardStreamHeartbeatIntervalMs ?? DEFAULT_BOARD_STREAM_HEARTBEAT_INTERVAL_MS,\n reconciliationIntervalMs:\n options.boardStreamReconciliationIntervalMs ??\n DEFAULT_BOARD_STREAM_RECONCILIATION_INTERVAL_MS,\n }),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.presenceHints)) {\n registry.register(\n { method: 'PUT', path: BYOK_PRESENCE_PATH, class: 'device' },\n presencePublishHandler({\n ...deviceRouteDeps,\n ttlMs: options.presenceTtlMs ?? DEFAULT_PRESENCE_TTL_MS,\n minimumIntervalMs:\n options.presenceMinimumIntervalMs ?? DEFAULT_PRESENCE_MINIMUM_INTERVAL_MS,\n detailMaxBytes: options.presenceDetailMaxBytes ?? DEFAULT_PRESENCE_DETAIL_MAX_BYTES,\n }),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.activityTail)) {\n registry.register(\n { method: 'POST', path: BYOK_ACTIVITY_PATH, class: 'device' },\n activityAppendHandler({ ...deviceRouteDeps, bounds: activityBounds }),\n );\n }\n\n const truthCommitter = options.truthCommitter;\n const truthObjectDownloads = options.truthObjectDownloads;\n if (\n truthCommitter !== undefined &&\n truthObjectDownloads !== undefined &&\n declares(declaration, CLOUD_CAPABILITIES.truthRecords)\n ) {\n const truthDeps = {\n proof: {\n devices: options.cloud.devices,\n crypto: options.crypto,\n clock: options.clock,\n },\n truth: truthCommitter,\n objectDownloads: truthObjectDownloads,\n maxRequestBytes: options.maxTruthRequestBytes ?? DEFAULT_MAX_TRUTH_REQUEST_BYTES,\n };\n registry.register(\n { method: 'GET', path: BYOK_RECORDS_PATH, class: 'proof' },\n truthManifestHandler(truthDeps),\n );\n registry.register(\n { method: 'GET', path: BYOK_RECORD_ROUTE, class: 'proof' },\n truthGetHandler(truthDeps),\n );\n registry.register(\n { method: 'PUT', path: BYOK_RECORD_ROUTE, class: 'proof' },\n truthPutHandler(truthDeps),\n );\n }\n\n // Skill packs: both conditions, same asymmetry as the byte proxy below.\n // Declared-without-a-store is fatal (above); supplied-without-a-declaration\n // is a silent no-mount, which is how a deployment rolls the channel out or\n // back without ever telling a client something false.\n const skillPacks = options.skillPacks;\n if (skillPacks !== undefined && declares(declaration, CLOUD_CAPABILITIES.skillPacks)) {\n const skillPackDeps = {\n bearer: deviceRouteDeps.bearer,\n skillPacks,\n pageLimit: options.skillPackPageLimit ?? DEFAULT_SKILL_PACK_PAGE_LIMIT,\n };\n registry.register(\n { method: 'GET', path: BYOK_SKILL_PACKS_PATH, class: 'device' },\n skillPackListHandler(skillPackDeps),\n );\n registry.register(\n { method: 'GET', path: BYOK_SKILL_PACK_FILE_ROUTE, class: 'device' },\n skillPackFileHandler(skillPackDeps),\n );\n }\n\n if (declares(declaration, CLOUD_CAPABILITIES.blobsPresigned)) {\n const blobDeps = {\n ...deviceRouteDeps,\n maxBlobSizeBytes: options.maxBlobSizeBytes ?? DEFAULT_MAX_BLOB_SIZE_BYTES,\n };\n registry.register({ method: 'POST', path: BYOK_BLOBS_PATH, class: 'device' }, createBlobHandler(blobDeps));\n registry.register({ method: 'POST', path: BYOK_BLOB_FINALIZE_ROUTE, class: 'device' }, finalizeBlobHandler(blobDeps));\n registry.register({ method: 'GET', path: BYOK_BLOB_URL_ROUTE, class: 'device' }, blobDownloadUrlHandler(blobDeps));\n }\n\n // Byte proxying: BOTH conditions, and neither is inferred from the other.\n // There is no third state: a composition either carries bytes or it does not.\n //\n // The two halves fail differently, and the asymmetry is the point.\n //\n // DECLARED WITHOUT A PROXY is fatal, above. A declaration is the ONE thing a\n // client is entitled to trust without probing (ADR-010), so a deployment\n // publishing `blobs.contentproxy` it cannot serve does not degrade to \"two\n // missing routes\" — it tells every client something false and then answers\n // 404 to the client that believed it. Not mounting the routes is what an\n // honest composition does with a capability it lacks; the dishonesty is in\n // still announcing it, and the announcement is unconditional.\n //\n // SUPPLIED WITHOUT A DECLARATION is not fatal, and stays a silent no-mount.\n // The deployment's declaration is then merely narrower than its parts, which\n // is how a capability gets rolled out or rolled back: a host with a proxy\n // wired up but the capability withheld serves exactly what it declares. The\n // client is told less than the truth, never more, and no route exists that a\n // client could only discover by probing.\n const contentProxy = options.blobContentProxy;\n if (contentProxy !== undefined && declares(declaration, CLOUD_CAPABILITIES.blobsContentProxy)) {\n const contentDeps = { contentProxy };\n registry.register(\n { method: 'PUT', path: BYOK_BLOB_CONTENT_ROUTE, class: 'presigned' },\n blobUploadContentHandler(contentDeps),\n );\n registry.register(\n { method: 'GET', path: BYOK_BLOB_CONTENT_ROUTE, class: 'presigned' },\n blobDownloadContentHandler(contentDeps),\n );\n }\n\n // Task approval is deliberately absent, exactly as it is on the reference\n // server: every route above is authenticated by a DEVICE's own credential,\n // and a device-bearer-authed approval route would let any validly paired\n // device approve any task in its tenant. Approval is an operator action and\n // belongs to the host's own control-plane surface.\n\n const operatorId = options.operatorId ?? 'host';\n\n function controlPlane(tenant: TenantId): ControlPlanePrincipal {\n return { kind: 'control-plane', tenantId: tenant, operatorId };\n }\n\n async function enqueueTaskEnvelope(\n tenant: TenantId,\n deviceId: string,\n requestedTaskId: string | undefined,\n buildEnvelope: (taskId: string, seq: number, messageId: string) => Envelope,\n ): Promise<EnqueuedOffer> {\n const stores = tenantStoresFor(controlPlane(tenant), root);\n const taskId = requestedTaskId ?? `task_${options.crypto.randomUuid()}`;\n const messageId = options.crypto.randomUuid();\n\n const message = await stores.mailbox.append({\n deviceId,\n messageId,\n materialize: async (seq) => {\n // Core stays protocol-free: the mailbox reserves the one authoritative\n // delivery number, then asks this producer to build opaque bytes while\n // allocation and insertion are still serialized per device.\n const envelope = buildEnvelope(taskId, seq, messageId);\n const body = encodeEnvelope(envelope);\n const bytes = new TextEncoder().encode(body);\n return {\n body,\n bodyHash: contentHash(await options.crypto.sha256(bytes)),\n byteSize: BigInt(bytes.length),\n };\n },\n });\n const envelope = decodeEnvelope(message.body);\n if (envelope.seq !== message.seq) {\n throw new ByokCloudError(\n 'mailbox_seq_mismatch',\n `Mailbox stored offer seq ${String(envelope.seq)} at row ${message.seq}; the daemon's redelivery cursor would be wrong.`,\n );\n }\n\n const attempt = await stores.tasks.open({ taskId, deviceId });\n return { taskId, seq: message.seq, envelope, attempt };\n }\n\n return {\n fetch: registry.fetch,\n routes: registry.routes,\n mountedRoutes: registry.mounted,\n capabilities: declaration,\n\n createPairingCode(tenant, input) {\n return auth.createPairingCode(tenant, input);\n },\n\n async enqueueOffer(tenant, deviceId, input) {\n return enqueueTaskEnvelope(tenant, deviceId, input.taskId, (taskId, seq, messageId) =>\n createEnvelope('task.offer', input.payload, { id: messageId, taskId, seq }),\n );\n },\n\n async enqueueToolsetOffer(tenant, deviceId, input) {\n return enqueueTaskEnvelope(tenant, deviceId, input.taskId, (taskId, seq, messageId) =>\n createEnvelope('task.offer_with_toolsets', input.payload, { id: messageId, taskId, seq }),\n );\n },\n\n readTaskAttempt(tenant, taskId) {\n return tenantStoresFor(controlPlane(tenant), root).tasks.get(taskId);\n },\n\n readTerminalReceipt(tenant, taskId) {\n return tenantStoresFor(controlPlane(tenant), root).receipts.get(terminalReceiptKey(taskId));\n },\n\n async readTaskResult(tenant, taskId) {\n const receipt = await tenantStoresFor(controlPlane(tenant), root).receipts.get(\n terminalReceiptKey(taskId),\n );\n return receipt === undefined ? undefined : projectTerminalResult(taskId, receipt);\n },\n\n listDevices(tenant) {\n return tenantStoresFor(controlPlane(tenant), root).devices.list();\n },\n\n revokeDevice(tenant, deviceId) {\n return tenantStoresFor(controlPlane(tenant), root).devices.revoke(deviceId);\n },\n\n createBoardItem(tenant, input) {\n assertBoardLabels(input.channel, input.title, {\n channelMaxBytes: options.boardChannelMaxBytes ?? DEFAULT_BOARD_CHANNEL_MAX_BYTES,\n titleMaxBytes: options.boardTitleMaxBytes ?? DEFAULT_BOARD_TITLE_MAX_BYTES,\n });\n return tenantStoresFor(controlPlane(tenant), root).board.create(input);\n },\n\n listBoardItems(tenant, query) {\n return tenantStoresFor(controlPlane(tenant), root).board.list(query);\n },\n\n acceptBoardItem(tenant, itemId) {\n return tenantStoresFor(controlPlane(tenant), root).board.updateStatus({\n itemId,\n expectedStatus: 'in_review',\n status: 'done',\n });\n },\n\n listPresence(tenant) {\n return tenantStoresFor(controlPlane(tenant), root).presence.list();\n },\n\n readActivity(tenant, taskId) {\n return tenantStoresFor(controlPlane(tenant), root).activity.read(taskId);\n },\n\n readApprovalTimeline(tenant, taskId) {\n return tenantStoresFor(controlPlane(tenant), root).approvals.read(taskId);\n },\n };\n}\n\n/**\n * Fail closed on a declaration this composition's parts cannot back.\n *\n * Route mounting alone cannot enforce this: `GET /byok/capabilities` serves the\n * declaration verbatim and is mounted unconditionally, so a deployment that\n * declares `blobs.contentproxy` without a proxy publishes the capability and\n * 404s both routes. Refusing at construction is the only placement where the\n * deployment cannot exist in that state — the alternative, sanitizing the\n * declaration down to what got mounted, would make the running surface a second\n * authority over what the host said it was deploying.\n */\nfunction assertNoOverDeclaration(\n declaration: CapabilityDeclaration,\n contentProxy: BlobContentProxy | undefined,\n truthCommitter: TruthCommitter | undefined,\n truthObjectDownloads: TruthObjectDownloads | undefined,\n skillPacks: SkillPackStore | undefined,\n): void {\n if (\n declares(declaration, CLOUD_CAPABILITIES.boardSse) &&\n !declares(declaration, CLOUD_CAPABILITIES.boardCoordination)\n ) {\n throw new ByokCloudError(\n 'capability_over_declared',\n `${CLOUD_CAPABILITIES.boardSse} requires ${CLOUD_CAPABILITIES.boardCoordination}; without polling, reconciliation and declared fallback cannot be served.`,\n );\n }\n if (contentProxy === undefined && declares(declaration, CLOUD_CAPABILITIES.blobsContentProxy)) {\n throw new ByokCloudError(\n 'capability_over_declared',\n `This deployment declares ${CLOUD_CAPABILITIES.blobsContentProxy} but was given no BlobContentProxy, so both /byok/blobs/:id/content routes would be published and unserved.`,\n );\n }\n if (truthCommitter === undefined && declares(declaration, CLOUD_CAPABILITIES.truthRecords)) {\n throw new ByokCloudError(\n 'capability_over_declared',\n `This deployment declares ${CLOUD_CAPABILITIES.truthRecords} but was given no atomic TruthCommitter.`,\n );\n }\n if (truthObjectDownloads === undefined && declares(declaration, CLOUD_CAPABILITIES.truthRecords)) {\n throw new ByokCloudError(\n 'capability_over_declared',\n `This deployment declares ${CLOUD_CAPABILITIES.truthRecords} but was given no content-hash keyed TruthObjectDownloads authority.`,\n );\n }\n if (skillPacks === undefined && declares(declaration, CLOUD_CAPABILITIES.skillPacks)) {\n throw new ByokCloudError(\n 'capability_over_declared',\n `This deployment declares ${CLOUD_CAPABILITIES.skillPacks} but was given no SkillPackStore, so both /byok/skill-packs routes would be published and unserved.`,\n );\n }\n}\n\nfunction parseDeclaration(declaration: CapabilityDeclaration): CapabilityDeclaration {\n try {\n return parseCapabilityDeclaration(declaration);\n } catch (cause) {\n throw new ByokCloudError(\n 'capability_declaration_invalid',\n 'The capability declaration this deployment was configured with is not a valid ADR-010 declaration.',\n { cause },\n );\n }\n}\n","/**\n * The reference {@link InboundRateLimiter}: allow-all.\n *\n * S3a's job is to put the seam at gate position 0 — before the type-allow\n * check — not to invent a limiter policy. A hosted deployment's real budget\n * lives at its edge; when it arrives it plugs in here and the gate order does\n * not move.\n */\nimport type { TenantId } from '@byok-sdk/core';\nimport type { InboundRateLimiter } from '../ports';\n\nexport class AllowAllRateLimiter implements InboundRateLimiter {\n async consume(_tenant: TenantId, _deviceId: string): Promise<boolean> {\n return true;\n }\n}\n","/**\n * The in-memory blob pair: metadata and bytes in process memory, HMAC-signed\n * expiring URLs (docs/protocol.md §7).\n *\n * TWO objects, one shared record map, because the contract they satisfy is two\n * things: {@link CloudBlobStore} is the tenant-first port every composition\n * owes, and {@link BlobContentProxy} is the optional byte-carrying half. The\n * in-memory composition is the one that supplies both — it has nowhere else to\n * put bytes — which is why hosted-in-memory behavior is byte-for-byte what it\n * was before the split.\n *\n * They cannot be one object: the port's method inventory is contract data\n * (`CLOUD_PORT_METHODS`) and `@byok-sdk/conformance` asserts a composition's blob\n * store implements EXACTLY the two declared methods. An object carrying all\n * six would fail that assertion, which is the point — the suite is what keeps\n * the narrowed port narrow.\n *\n * The presigned URL form — `/byok/blobs/<id>/content?sig=&exp=` — is the\n * relative shape the daemon's blob client already resolves against its server\n * base, so a hosted deployment is indistinguishable from a self-hosted one on\n * this route too.\n *\n * Tenancy: `createUpload` records the owning tenant and reservation while\n * `observeUpload`/`getDownloadUrl` refuse any other, so the three bearer routes are\n * tenant-closed. The two `/content` routes are presigned by construction and\n * have no principal at all — the signature over the blob id IS the credential\n * (same posture as the reference server, §7).\n */\nimport { ByokCoreError, type Clock, type ContentHash, type ObjectStore, type StorageReservation, type TenantId } from '@byok-sdk/core';\nimport { byokBlobContentPath } from '@byok-sdk/protocol';\nimport type { CloudCrypto } from '../../crypto/port';\nimport type {\n BlobContent,\n BlobContentProxy,\n BlobObservation,\n BlobWriteResult,\n CloudBlobStore,\n} from '../ports';\n\n/** How long a presigned upload/download URL stays valid. */\nexport const BLOB_URL_TTL_MS = 15 * 60 * 1000;\n\nconst SIGNING_SECRET_BYTES = 32;\n\ninterface BlobRecord {\n readonly tenantId: TenantId;\n readonly reservationId: string;\n readonly contentHash: ContentHash;\n readonly byteSize: bigint;\n readonly contentType: string;\n uploaded: boolean;\n data?: Uint8Array;\n}\n\nexport interface InMemoryBlobStoreOptions {\n readonly urlTtlMs?: number;\n}\n\n/**\n * The state both halves read, and the only thing they share.\n *\n * Module-private on purpose: it is not a port, and nothing outside this file\n * should be able to reach a blob record without going through one of the two\n * contracts above.\n */\nclass InMemoryBlobRegistry {\n readonly blobs = new Map<string, BlobRecord>();\n readonly reservationBlobs = new Map<string, string>();\n readonly clock: Clock;\n readonly crypto: CloudCrypto;\n readonly secret: Uint8Array;\n readonly urlTtlMs: number;\n\n constructor(clock: Clock, crypto: CloudCrypto, options: InMemoryBlobStoreOptions) {\n this.clock = clock;\n this.crypto = crypto;\n this.secret = globalThis.crypto.getRandomValues(new Uint8Array(SIGNING_SECRET_BYTES));\n this.urlTtlMs = options.urlTtlMs ?? BLOB_URL_TTL_MS;\n }\n\n async signUrl(blobId: string, action: 'put' | 'get'): Promise<string> {\n const exp = this.clock.now().getTime() + this.urlTtlMs;\n const sig = await this.computeSig(blobId, action, exp);\n return `${byokBlobContentPath(blobId)}?sig=${sig}&exp=${exp}`;\n }\n\n computeSig(blobId: string, action: 'put' | 'get', exp: number): Promise<string> {\n return this.crypto.hmacSha256(this.secret, `${blobId}:${action}:${exp}`);\n }\n}\n\n/** The narrowed port: tenant-first grants, no bytes. */\nexport class InMemoryCloudBlobStore implements CloudBlobStore {\n readonly #registry: InMemoryBlobRegistry;\n readonly #objects: ObjectStore;\n\n constructor(registry: InMemoryBlobRegistry, objects: ObjectStore) {\n this.#registry = registry;\n this.#objects = objects;\n }\n\n async createUpload(tenant: TenantId, reservation: StorageReservation): Promise<{ blobId: string; uploadUrl: string }> {\n assertReservedObject(tenant, reservation);\n const reservationKey = `${tenant}\\u0000${reservation.reservationId}`;\n const existingBlobId = this.#registry.reservationBlobs.get(reservationKey);\n if (existingBlobId !== undefined) {\n const manifest = await this.#objects.get(tenant, reservation.contentHash);\n if (manifest?.state === 'committed') {\n throw new ByokCoreError(\n 'object_state_invalid',\n `Object ${reservation.contentHash} is already committed and immutable.`,\n );\n }\n return { blobId: existingBlobId, uploadUrl: await this.#registry.signUrl(existingBlobId, 'put') };\n }\n\n const entry = await this.#objects.putManifest(tenant, {\n hash: reservation.contentHash,\n byteSize: reservation.expectedBytes,\n contentType: reservation.contentType,\n });\n if (\n entry.byteSize !== reservation.expectedBytes ||\n entry.contentType !== reservation.contentType\n ) {\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n `Object ${reservation.contentHash} already binds a different storage declaration.`,\n );\n }\n if (entry.state === 'committed') {\n throw new ByokCoreError(\n 'object_state_invalid',\n `Object ${reservation.contentHash} is already committed and immutable.`,\n );\n }\n\n const blobId = `blob_${this.#registry.crypto.randomUuid()}`;\n this.#registry.blobs.set(blobId, {\n tenantId: tenant,\n reservationId: reservation.reservationId,\n contentHash: reservation.contentHash,\n byteSize: reservation.expectedBytes,\n contentType: reservation.contentType,\n uploaded: false,\n });\n this.#registry.reservationBlobs.set(reservationKey, blobId);\n return { blobId, uploadUrl: await this.#registry.signUrl(blobId, 'put') };\n }\n\n async observeUpload(\n tenant: TenantId,\n blobId: string,\n reservation: StorageReservation,\n ): Promise<BlobObservation | undefined> {\n const record = this.#registry.blobs.get(blobId);\n if (\n record === undefined ||\n record.tenantId !== tenant ||\n reservation.tenantId !== tenant ||\n record.reservationId !== reservation.reservationId ||\n record.contentHash !== reservation.contentHash ||\n !record.uploaded\n ) {\n return undefined;\n }\n return {\n observedByteSize: BigInt(record.data?.length ?? 0),\n observedContentType: record.contentType,\n };\n }\n\n async getDownloadUrl(tenant: TenantId, blobId: string): Promise<string | undefined> {\n const record = this.#registry.blobs.get(blobId);\n // Another tenant's blob and a blob that does not exist answer identically.\n if (record === undefined || record.tenantId !== tenant || !record.uploaded) return undefined;\n const manifest = await this.#objects.get(tenant, record.contentHash);\n if (manifest?.state !== 'committed') return undefined;\n return this.#registry.signUrl(blobId, 'get');\n }\n}\n\n/** The optional half: the bytes this composition has nowhere else to put. */\nexport class InMemoryBlobContentProxy implements BlobContentProxy {\n readonly #registry: InMemoryBlobRegistry;\n\n constructor(registry: InMemoryBlobRegistry) {\n this.#registry = registry;\n }\n\n async verifySignedUrl(blobId: string, action: 'put' | 'get', sig: string, exp: number): Promise<boolean> {\n if (!Number.isFinite(exp) || this.#registry.clock.now().getTime() > exp) return false;\n const expected = await this.#registry.computeSig(blobId, action, exp);\n return this.#registry.crypto.timingSafeEqual(expected, sig);\n }\n\n async writeContent(blobId: string, data: Uint8Array): Promise<BlobWriteResult> {\n const record = this.#registry.blobs.get(blobId);\n if (record === undefined) return { ok: false, reason: 'unknown blobId' };\n if (BigInt(data.length) !== record.byteSize) {\n return { ok: false, reason: `size mismatch: declared ${String(record.byteSize)}, received ${data.length}` };\n }\n const actualHash = await this.#registry.crypto.sha256(data);\n if (actualHash !== record.contentHash) {\n return { ok: false, reason: 'contentHash mismatch' };\n }\n record.data = data;\n record.uploaded = true;\n return { ok: true };\n }\n\n async readContent(blobId: string): Promise<BlobContent | undefined> {\n const record = this.#registry.blobs.get(blobId);\n if (record === undefined || !record.uploaded || record.data === undefined) return undefined;\n return { data: record.data, contentType: record.contentType };\n }\n}\n\n/** Both halves over one registry. The only way to obtain either. */\nexport interface InMemoryBlobs {\n readonly blobs: CloudBlobStore;\n readonly contentProxy: BlobContentProxy;\n}\n\nexport function createInMemoryBlobs(\n clock: Clock,\n crypto: CloudCrypto,\n objects: ObjectStore,\n options: InMemoryBlobStoreOptions = {},\n): InMemoryBlobs {\n const registry = new InMemoryBlobRegistry(clock, crypto, options);\n return {\n blobs: new InMemoryCloudBlobStore(registry, objects),\n contentProxy: new InMemoryBlobContentProxy(registry),\n };\n}\n\nfunction assertReservedObject(tenant: TenantId, reservation: StorageReservation): void {\n if (\n reservation.tenantId === tenant &&\n reservation.kind === 'object' &&\n reservation.state === 'reserved' &&\n reservation.expectedBytes >= 0n\n ) {\n return;\n }\n throw new ByokCoreError(\n 'storage_integrity_mismatch',\n 'An upload grant requires a reserved object reservation owned by this tenant.',\n );\n}\n","/**\n * In-memory {@link DeviceDirectory}.\n *\n * Rows live under a `(tenant, deviceId)` composite key, so a cross-tenant read\n * is not \"denied\" — it addresses a different key space and finds nothing\n * (§12.6.2 layer 3). The pre-tenant index below holds the SAME record objects,\n * so a revocation applied through the composite key is immediately visible to\n * `/byok/challenge` and `/byok/token` with no second copy to keep in sync.\n */\nimport { tenantKey, type TenantId } from '@byok-sdk/core';\nimport type { DeviceDirectory, DeviceRecord, DeviceRegistration } from '../ports';\n\nexport class InMemoryDeviceDirectory implements DeviceDirectory {\n readonly #byTenant = new Map<string, DeviceRecord>();\n readonly #byDeviceId = new Map<string, string>();\n\n async register(tenant: TenantId, input: DeviceRegistration): Promise<DeviceRecord> {\n const record: DeviceRecord = {\n tenantId: tenant,\n productId: input.productId,\n deviceId: input.deviceId,\n deviceName: input.deviceName,\n devicePublicKey: input.devicePublicKey,\n proofKeyId: input.proofKeyId,\n proofKeyEpoch: input.proofKeyEpoch,\n revoked: false,\n };\n const key = tenantKey(tenant, record.deviceId);\n this.#byTenant.set(key, record);\n this.#byDeviceId.set(record.deviceId, key);\n return record;\n }\n\n async get(tenant: TenantId, deviceId: string): Promise<DeviceRecord | undefined> {\n return this.#byTenant.get(tenantKey(tenant, deviceId));\n }\n\n async revoke(tenant: TenantId, deviceId: string): Promise<void> {\n const key = tenantKey(tenant, deviceId);\n const record = this.#byTenant.get(key);\n if (record === undefined) return;\n this.#byTenant.set(key, { ...record, revoked: true });\n }\n\n async list(tenant: TenantId): Promise<readonly DeviceRecord[]> {\n const prefix = tenantKey(tenant, '');\n return [...this.#byTenant.entries()]\n .filter(([key]) => key.startsWith(prefix))\n .map(([, record]) => record);\n }\n\n async resolveByDeviceId(deviceId: string): Promise<DeviceRecord | undefined> {\n const key = this.#byDeviceId.get(deviceId);\n return key === undefined ? undefined : this.#byTenant.get(key);\n }\n}\n","/**\n * In-memory {@link InboundDedupStore} (N3).\n *\n * A bounded ring per (tenant, device), not an unbounded set: the wire is\n * at-least-once (§9), so this makes processing at-most-once without letting a\n * chatty device grow memory without limit. Check-and-record is one call, so a\n * composition cannot accidentally split it into a racy read-then-write.\n */\nimport { tenantKey, type TenantId } from '@byok-sdk/core';\nimport type { InboundDedupStore } from '../ports';\n\n/** Ids retained per device. Same order of magnitude as the reference server's ring. */\nexport const DEDUP_RING_CAPACITY = 1024;\n\nexport class InMemoryInboundDedupStore implements InboundDedupStore {\n readonly #rings = new Map<string, Set<string>>();\n readonly #capacity: number;\n\n constructor(capacity: number = DEDUP_RING_CAPACITY) {\n this.#capacity = capacity;\n }\n\n async checkAndRecord(tenant: TenantId, deviceId: string, envelopeId: string): Promise<boolean> {\n const key = tenantKey(tenant, deviceId);\n let ring = this.#rings.get(key);\n if (ring === undefined) {\n ring = new Set<string>();\n this.#rings.set(key, ring);\n }\n if (ring.has(envelopeId)) return true;\n ring.add(envelopeId);\n if (ring.size > this.#capacity) {\n const oldest = ring.values().next().value;\n if (oldest !== undefined) ring.delete(oldest);\n }\n return false;\n }\n}\n","/**\n * In-memory {@link NonceStore}: single-use challenge nonces, ~5min TTL\n * (docs/protocol.md §6.2).\n *\n * A nonce is bound to the (tenant, device) it was issued for, so a nonce\n * issued to one tenant's device is not validatable by another's even if the\n * value leaks.\n */\nimport { tenantKey, type Clock, type TenantId } from '@byok-sdk/core';\nimport type { CloudCrypto } from '../../crypto/port';\nimport type { NonceStore } from '../ports';\n\n/** ~5min, matching the reference server (docs/protocol.md §6.2). */\nexport const NONCE_TTL_MS = 5 * 60 * 1000;\n\nconst NONCE_BYTES = 24;\n\ninterface NonceRecord {\n readonly owner: string;\n readonly expiresAtMs: number;\n used: boolean;\n}\n\nexport class InMemoryNonceStore implements NonceStore {\n readonly #nonces = new Map<string, NonceRecord>();\n readonly #clock: Clock;\n readonly #crypto: CloudCrypto;\n readonly #ttlMs: number;\n\n constructor(clock: Clock, crypto: CloudCrypto, ttlMs: number = NONCE_TTL_MS) {\n this.#clock = clock;\n this.#crypto = crypto;\n this.#ttlMs = ttlMs;\n }\n\n /** Number of records currently held (post-sweep). Test-facing only. */\n get size(): number {\n return this.#nonces.size;\n }\n\n async issue(tenant: TenantId, deviceId: string): Promise<string> {\n const nowMs = this.#clock.now().getTime();\n // A long-lived deployment never calls a sweep on a timer, so issue sweeps\n // inline — same posture as the reference server's `NonceStore`.\n for (const [nonce, record] of this.#nonces) {\n if (record.used || record.expiresAtMs <= nowMs) this.#nonces.delete(nonce);\n }\n const nonce = this.#crypto.randomToken(NONCE_BYTES);\n this.#nonces.set(nonce, {\n owner: tenantKey(tenant, deviceId),\n expiresAtMs: nowMs + this.#ttlMs,\n used: false,\n });\n return nonce;\n }\n\n async validate(tenant: TenantId, deviceId: string, nonce: string): Promise<boolean> {\n const record = this.#nonces.get(nonce);\n if (record === undefined) return false;\n if (record.used) return false;\n if (record.owner !== tenantKey(tenant, deviceId)) return false;\n return this.#clock.now().getTime() <= record.expiresAtMs;\n }\n\n async markUsed(tenant: TenantId, nonce: string): Promise<void> {\n const record = this.#nonces.get(nonce);\n if (record === undefined) return;\n if (!record.owner.startsWith(tenantKey(tenant, ''))) return;\n record.used = true;\n }\n}\n","/**\n * In-memory {@link PairingCodeStore}: single-use codes bound to the tenant and\n * product they were minted for.\n *\n * `redeem` answers `undefined` for unknown, expired, and already-used alike.\n * The reference server distinguishes those three in its 401 text; a hosted,\n * multi-tenant surface deliberately does not — the code is a bearer credential\n * addressable across every tenant, and \"already used\" versus \"never existed\"\n * is exactly the difference an attacker enumerating codes would pay for.\n */\nimport type { Clock, TenantId } from '@byok-sdk/core';\nimport type {\n PairingCodeClaims,\n PairingCodeInfo,\n PairingCodeIssueInput,\n PairingCodeStore,\n} from '../ports';\n\ninterface PairingCodeRecord {\n readonly claims: PairingCodeClaims;\n readonly expiresAtMs: number;\n used: boolean;\n}\n\nexport class InMemoryPairingCodeStore implements PairingCodeStore {\n readonly #codes = new Map<string, PairingCodeRecord>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async issue(tenant: TenantId, input: PairingCodeIssueInput): Promise<PairingCodeInfo> {\n this.#codes.set(input.code, {\n claims: { tenantId: tenant, productId: input.productId },\n expiresAtMs: new Date(input.expiresAt).getTime(),\n used: false,\n });\n return { code: input.code, expiresAt: input.expiresAt };\n }\n\n async redeem(code: string): Promise<PairingCodeClaims | undefined> {\n const record = this.#codes.get(code);\n if (record === undefined) return undefined;\n if (record.used) return undefined;\n if (this.#clock.now().getTime() > record.expiresAtMs) return undefined;\n record.used = true;\n return record.claims;\n }\n}\n","/**\n * In-memory {@link RequestReceiptStore}: first write wins.\n *\n * The terminal a device reports is a fact, and a retry of the same terminal\n * (the wire is at-least-once) must not overwrite the first one — `created:\n * false` is how the caller learns it was a replay rather than a new fact.\n */\nimport { tenantKey, type Clock, type TenantId } from '@byok-sdk/core';\nimport type { RequestReceipt, RequestReceiptStore } from '../ports';\n\nexport class InMemoryRequestReceiptStore implements RequestReceiptStore {\n readonly #receipts = new Map<string, RequestReceipt>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async record(\n tenant: TenantId,\n input: { key: string; body: string },\n ): Promise<{ receipt: RequestReceipt; created: boolean }> {\n const key = tenantKey(tenant, input.key);\n const existing = this.#receipts.get(key);\n if (existing !== undefined) return { receipt: existing, created: false };\n const receipt: RequestReceipt = {\n tenantId: tenant,\n key: input.key,\n body: input.body,\n recordedAt: this.#clock.now().toISOString(),\n };\n this.#receipts.set(key, receipt);\n return { receipt, created: true };\n }\n\n async get(tenant: TenantId, key: string): Promise<RequestReceipt | undefined> {\n return this.#receipts.get(tenantKey(tenant, key));\n }\n}\n","import { tenantKey, type Clock, type TenantId } from '@byok-sdk/core';\nimport type {\n ProofRequestReceipt,\n ProofRequestReceiptInput,\n ProofRequestReceiptStore,\n} from '../ports';\n\nexport class InMemoryProofRequestReceiptStore implements ProofRequestReceiptStore {\n readonly #receipts = new Map<string, ProofRequestReceipt>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async record(\n tenant: TenantId,\n input: ProofRequestReceiptInput,\n ): Promise<{ readonly receipt: ProofRequestReceipt; readonly created: boolean }> {\n const key = tenantKey(tenant, input.deviceId, input.requestId);\n const existing = this.#receipts.get(key);\n if (existing !== undefined) return { receipt: existing, created: false };\n const receipt: ProofRequestReceipt = {\n tenantId: tenant,\n ...input,\n recordedAt: this.#clock.now().toISOString(),\n };\n this.#receipts.set(key, receipt);\n return { receipt, created: true };\n }\n\n async get(\n tenant: TenantId,\n deviceId: string,\n requestId: string,\n ): Promise<ProofRequestReceipt | undefined> {\n return this.#receipts.get(tenantKey(tenant, deviceId, requestId));\n }\n}\n","/**\n * In-memory {@link TaskAttemptStore} — the ownership authority the inbound\n * gate reads (N2).\n *\n * Two deliberate no-ops:\n *\n * - `claim` on a task this tenant never offered writes nothing. A device that\n * guesses a taskId must not be able to conjure a row (and, cross-tenant,\n * must not leave a trace in the tenant it guessed into).\n * - `recordStatus` on an unknown task writes nothing, mirroring the reference\n * server's per-type handlers, whose behavior on a missing record is a no-op\n * rather than a rejection.\n *\n * Ownership is first-claim-wins and never transfers: reassigning an owner is\n * the one operation that would make the gate's cross-device assertion\n * unfalsifiable.\n */\nimport { tenantKey, type Clock, type TenantId } from '@byok-sdk/core';\nimport type { TaskAttempt, TaskAttemptStatus, TaskAttemptStore } from '../ports';\n\nexport class InMemoryTaskAttemptStore implements TaskAttemptStore {\n readonly #attempts = new Map<string, TaskAttempt>();\n readonly #clock: Clock;\n\n constructor(clock: Clock) {\n this.#clock = clock;\n }\n\n async open(tenant: TenantId, input: { taskId: string; deviceId: string }): Promise<TaskAttempt> {\n const key = tenantKey(tenant, input.taskId);\n const existing = this.#attempts.get(key);\n if (existing !== undefined) return existing;\n const attempt: TaskAttempt = {\n tenantId: tenant,\n taskId: input.taskId,\n deviceId: input.deviceId,\n status: 'offered',\n updatedAt: this.#now(),\n };\n this.#attempts.set(key, attempt);\n return attempt;\n }\n\n async get(tenant: TenantId, taskId: string): Promise<TaskAttempt | undefined> {\n return this.#attempts.get(tenantKey(tenant, taskId));\n }\n\n async claim(tenant: TenantId, input: { taskId: string; deviceId: string }): Promise<TaskAttempt | undefined> {\n const key = tenantKey(tenant, input.taskId);\n const existing = this.#attempts.get(key);\n if (existing === undefined) return undefined;\n if (existing.ownerDeviceId !== undefined) return existing;\n const claimed: TaskAttempt = {\n ...existing,\n ownerDeviceId: input.deviceId,\n status: 'claimed',\n updatedAt: this.#now(),\n };\n this.#attempts.set(key, claimed);\n return claimed;\n }\n\n async recordStatus(\n tenant: TenantId,\n input: { taskId: string; status: TaskAttemptStatus },\n ): Promise<TaskAttempt | undefined> {\n const key = tenantKey(tenant, input.taskId);\n const existing = this.#attempts.get(key);\n if (existing === undefined) return undefined;\n const updated: TaskAttempt = { ...existing, status: input.status, updatedAt: this.#now() };\n this.#attempts.set(key, updated);\n return updated;\n }\n\n #now(): string {\n return this.#clock.now().toISOString();\n }\n}\n","import type { Clock, TenantId } from '@byok-sdk/core';\nimport { ByokCloudError } from '../../errors';\nimport {\n activityCursor,\n activityTailKey,\n compareTimelineEvents,\n projectTimelineEvents,\n validateActivityAppend,\n type ActivityAppendInput,\n type ActivityStore,\n type ActivityTail,\n} from '../../activity';\n\nexport class InMemoryActivityStore implements ActivityStore {\n readonly #tails = new Map<string, ActivityTail>();\n\n constructor(private readonly clock: Clock) {}\n\n async append(tenant: TenantId, input: ActivityAppendInput): Promise<ActivityTail> {\n const capacity = validateActivityAppend(input);\n const now = this.clock.now();\n const receivedAt = now.toISOString();\n const key = activityTailKey(tenant, input.taskId);\n const existing = this.#tails.get(key);\n const live = existing !== undefined && receivedAt < existing.expiresAt ? existing : undefined;\n const incoming = projectTimelineEvents(input, receivedAt);\n for (const next of incoming) {\n const collision = live?.entries.find(\n (entry) =>\n entry.batchSeq === next.batchSeq &&\n entry.eventIndex === next.eventIndex &&\n entry.sourceEnvelopeId !== next.sourceEnvelopeId,\n );\n if (collision !== undefined) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n `Activity order key (${next.batchSeq}, ${next.eventIndex}) already belongs to another source envelope.`,\n );\n }\n }\n const allEntries = [...(live?.entries ?? []), ...incoming].sort(compareTimelineEvents);\n const evicted = Math.max(allEntries.length - capacity, 0);\n const entries = allEntries.slice(evicted);\n const cursor = activityCursor(entries);\n const tail: ActivityTail = {\n tenantId: tenant,\n taskId: input.taskId,\n entries,\n ...(cursor === undefined ? {} : { cursor }),\n dropped: (live?.dropped ?? 0) + input.dropped + evicted,\n capacity,\n expiresAt: new Date(now.getTime() + input.ttlMs).toISOString(),\n };\n this.#tails.set(key, tail);\n return tail;\n }\n\n async read(tenant: TenantId, taskId: string): Promise<ActivityTail | undefined> {\n const key = activityTailKey(tenant, taskId);\n const tail = this.#tails.get(key);\n if (tail === undefined) return undefined;\n if (this.clock.now().toISOString() >= tail.expiresAt) {\n this.#tails.delete(key);\n return undefined;\n }\n return tail;\n }\n}\n","import type { Clock, TenantId } from '@byok-sdk/core';\nimport { ByokCloudError } from '../../errors';\nimport {\n ApprovalObservationSchema,\n approvalTimelineCursor,\n approvalTimelineKey,\n validateApprovalTimelineAppend,\n type ApprovalTimelineAppendInput,\n type ApprovalTimelineStore,\n type ApprovalTimelineTail,\n} from '../../approval-timeline';\n\nexport class InMemoryApprovalTimelineStore implements ApprovalTimelineStore {\n readonly #tails = new Map<string, ApprovalTimelineTail>();\n\n constructor(private readonly clock: Clock) {}\n\n async append(\n tenant: TenantId,\n input: ApprovalTimelineAppendInput,\n ): Promise<ApprovalTimelineTail> {\n const { capacity, ttlMs, event } = validateApprovalTimelineAppend(input);\n const now = this.clock.now();\n const receivedAt = now.toISOString();\n const key = approvalTimelineKey(tenant, input.taskId);\n const existing = this.#tails.get(key);\n const live = existing !== undefined && receivedAt < existing.expiresAt ? existing : undefined;\n if (live !== undefined) {\n const duplicate = live.entries.find(\n (entry) => entry.sourceEnvelopeId === input.sourceEnvelopeId,\n );\n if (duplicate !== undefined) {\n if (JSON.stringify(duplicate.event) !== JSON.stringify(event)) {\n throw new ByokCloudError(\n 'coordination_input_invalid',\n 'Approval source envelope identity already belongs to another lifecycle event.',\n );\n }\n return live;\n }\n }\n\n const revision = (live?.cursor ?? 0) + 1;\n const observation = ApprovalObservationSchema.parse({\n taskId: input.taskId,\n sourceEnvelopeId: input.sourceEnvelopeId,\n revision,\n receivedAt,\n event,\n });\n const allEntries = [...(live?.entries ?? []), observation];\n const evicted = Math.max(allEntries.length - capacity, 0);\n const entries = allEntries.slice(evicted);\n const tail: ApprovalTimelineTail = {\n tenantId: tenant,\n taskId: input.taskId,\n entries,\n cursor: approvalTimelineCursor(entries),\n dropped: (live?.dropped ?? 0) + evicted,\n capacity,\n expiresAt: new Date(now.getTime() + ttlMs).toISOString(),\n };\n this.#tails.set(key, tail);\n return tail;\n }\n\n async read(tenant: TenantId, taskId: string): Promise<ApprovalTimelineTail | undefined> {\n const key = approvalTimelineKey(tenant, taskId);\n const tail = this.#tails.get(key);\n if (tail === undefined) return undefined;\n if (this.clock.now().toISOString() >= tail.expiresAt) {\n this.#tails.delete(key);\n return undefined;\n }\n return tail;\n }\n}\n","/**\n * The in-memory reference implementation of every cloud-local port.\n *\n * Same posture as `@byok-sdk/core`'s: a reference, not a production store. What it\n * guarantees is that the behavior the handler suites assert is achievable\n * without a database — which is what makes those same assertions meaningful\n * when a durable composition (S3b's journal, S4A's schema) runs them later.\n */\nimport type { Clock, ObjectStore } from '@byok-sdk/core';\nimport type { CloudCrypto } from '../../crypto/port';\nimport type { BlobContentProxy, CloudStores } from '../ports';\nimport { AllowAllRateLimiter } from './rate-limiter';\nimport { createInMemoryBlobs } from './blobs';\nimport { InMemoryDeviceDirectory } from './device-directory';\nimport { InMemoryInboundDedupStore } from './dedup';\nimport { InMemoryNonceStore } from './nonces';\nimport { InMemoryPairingCodeStore } from './pairing-codes';\nimport { InMemoryRequestReceiptStore } from './receipts';\nimport { InMemoryProofRequestReceiptStore } from './proof-receipts';\nimport { InMemoryTaskAttemptStore } from './task-attempts';\nimport { InMemoryActivityStore } from './activity';\nimport { InMemoryApprovalTimelineStore } from './approval-timeline';\n\nexport { AllowAllRateLimiter } from './rate-limiter';\nexport {\n BLOB_URL_TTL_MS,\n InMemoryBlobContentProxy,\n InMemoryCloudBlobStore,\n createInMemoryBlobs,\n} from './blobs';\nexport type { InMemoryBlobs, InMemoryBlobStoreOptions } from './blobs';\nexport { DEDUP_RING_CAPACITY, InMemoryInboundDedupStore } from './dedup';\nexport { InMemoryDeviceDirectory } from './device-directory';\nexport { InMemoryNonceStore, NONCE_TTL_MS } from './nonces';\nexport { InMemoryPairingCodeStore } from './pairing-codes';\nexport { InMemoryRequestReceiptStore } from './receipts';\nexport { InMemoryProofRequestReceiptStore } from './proof-receipts';\nexport { InMemoryTaskAttemptStore } from './task-attempts';\nexport { InMemoryActivityStore } from './activity';\nexport { InMemoryApprovalTimelineStore } from './approval-timeline';\n\n/**\n * The port bundle plus the byte proxy, in the shape `createInMemoryCoreStores`\n * already uses: the composition is an object with a `stores` field, not the\n * bundle itself.\n *\n * `blobContentProxy` sits BESIDE `stores` rather than inside it because it is\n * not a port — `createByokCloud` takes it as its own optional input, and a\n * composition that cannot carry bytes simply has none to hand over.\n */\nexport interface InMemoryCloudComposition {\n readonly stores: CloudStores;\n readonly blobContentProxy: BlobContentProxy;\n}\n\nexport function createInMemoryCloudStores(\n clock: Clock,\n crypto: CloudCrypto,\n objects: ObjectStore,\n): InMemoryCloudComposition {\n const blobs = createInMemoryBlobs(clock, crypto, objects);\n return {\n stores: {\n activity: new InMemoryActivityStore(clock),\n approvals: new InMemoryApprovalTimelineStore(clock),\n devices: new InMemoryDeviceDirectory(),\n pairingCodes: new InMemoryPairingCodeStore(clock),\n nonces: new InMemoryNonceStore(clock, crypto),\n dedup: new InMemoryInboundDedupStore(),\n tasks: new InMemoryTaskAttemptStore(clock),\n receipts: new InMemoryRequestReceiptStore(clock),\n proofReceipts: new InMemoryProofRequestReceiptStore(clock),\n blobs: blobs.blobs,\n rateLimiter: new AllowAllRateLimiter(),\n },\n blobContentProxy: blobs.contentProxy,\n };\n}\n","/**\n * The in-memory composition: core's reference stores plus cloud's, wired into\n * a working {@link ByokCloud}.\n *\n * This is what the handler suites and the client-side end-to-end test run\n * against, and it is the honest demonstration of the S3 claim — the daemon\n * cannot tell this from `@byok-sdk/server`, and nothing in the path needs a\n * database to prove it.\n */\nimport {\n createInMemoryCoreStores,\n type CapabilityDeclaration,\n type Clock,\n type CoreStores,\n type SkillPackStore,\n} from '@byok-sdk/core';\nimport { createHmacTokenSigner, type TokenSigner } from '../auth/tokens';\nimport { fullCapabilityDeclaration } from '../capabilities';\nimport { createWebCrypto } from '../crypto/web-crypto';\nimport type { CloudCrypto } from '../crypto/port';\nimport { createByokCloud, type ByokCloud } from '../cloud';\nimport { createInMemoryCloudStores } from '../stores/in-memory/index';\nimport type { BlobContentProxy, CloudStores } from '../stores/ports';\nimport type { TruthCommitter, TruthObjectDownloads } from '../truth/contract';\n\nconst TOKEN_SECRET_BYTES = 32;\n\n/**\n * Real time by default, deliberately.\n *\n * Core's in-memory reference defaults to a FROZEN clock so TTL conformance is\n * deterministic. A composition serving a real daemon cannot: the daemon\n * compares the `expiresAt` it is handed against its own wall clock and would\n * treat every token from a clock stuck in the past as already expired. A test\n * that needs deterministic TTLs injects a mutable clock here instead.\n */\nfunction systemClock(): Clock {\n return { now: () => new Date() };\n}\n\nexport interface InMemoryByokCloudOptions {\n readonly clock?: Clock;\n readonly crypto?: CloudCrypto;\n readonly tokenSigner?: TokenSigner;\n readonly capabilities?: CapabilityDeclaration;\n readonly operatorId?: string;\n readonly maxBlobSizeBytes?: number;\n readonly longPollHoldMs?: number;\n readonly longPollIntervalMs?: number;\n readonly eventsPageLimit?: number;\n readonly accessTokenTtlSeconds?: number;\n readonly boardPageLimit?: number;\n readonly boardStreamQueryIntervalMs?: number;\n readonly boardStreamHeartbeatIntervalMs?: number;\n readonly boardStreamReconciliationIntervalMs?: number;\n readonly boardChannelMaxBytes?: number;\n readonly boardTitleMaxBytes?: number;\n readonly presenceTtlMs?: number;\n readonly presenceMinimumIntervalMs?: number;\n readonly presenceDetailMaxBytes?: number;\n readonly activityMaxEvents?: number;\n readonly activityMaxBytes?: number;\n readonly activityCapacity?: number;\n readonly activityTtlMs?: number;\n /** Test/host supplied atomic truth authority; never synthesized from sequential stores. */\n readonly truthCommitter?: TruthCommitter;\n readonly truthObjectDownloads?: TruthObjectDownloads;\n readonly maxTruthRequestBytes?: number;\n /**\n * Host/test supplied skill pack catalogue. Absent by default, and\n * `fullCapabilityDeclaration()` withholds `skills.pack` to match — a\n * composition that declared a channel it has no store for would be refused at\n * construction, which would break every existing in-memory deployment.\n */\n readonly skillPacks?: SkillPackStore;\n readonly skillPackPageLimit?: number;\n}\n\nexport interface InMemoryByokCloud {\n readonly cloud: ByokCloud;\n /** The naked stores, for a host that wants to inspect or seed state directly. */\n readonly core: CoreStores;\n readonly stores: CloudStores;\n /** The byte proxy the two `/content` routes were mounted on. */\n readonly blobContentProxy: BlobContentProxy;\n readonly clock: Clock;\n readonly crypto: CloudCrypto;\n}\n\nexport function createInMemoryByokCloud(options: InMemoryByokCloudOptions = {}): InMemoryByokCloud {\n const clock = options.clock ?? systemClock();\n const crypto = options.crypto ?? createWebCrypto();\n const core = createInMemoryCoreStores({ clock }).stores;\n const { stores, blobContentProxy } = createInMemoryCloudStores(clock, crypto, core.objects);\n const tokenSigner =\n options.tokenSigner ??\n createHmacTokenSigner(globalThis.crypto.getRandomValues(new Uint8Array(TOKEN_SECRET_BYTES)), clock);\n\n const cloud = createByokCloud({\n core,\n cloud: stores,\n // This composition has nowhere else to put bytes, so it supplies the proxy\n // and `fullCapabilityDeclaration()` declares `blobs.contentproxy`. That\n // pairing is what keeps hosted-in-memory behavior identical to what it was\n // before the port narrowed.\n blobContentProxy,\n crypto,\n tokenSigner,\n clock,\n capabilities: options.capabilities ?? fullCapabilityDeclaration(),\n ...(options.truthCommitter === undefined ? {} : { truthCommitter: options.truthCommitter }),\n ...(options.truthObjectDownloads === undefined\n ? {}\n : { truthObjectDownloads: options.truthObjectDownloads }),\n ...(options.operatorId !== undefined ? { operatorId: options.operatorId } : {}),\n ...(options.maxBlobSizeBytes !== undefined ? { maxBlobSizeBytes: options.maxBlobSizeBytes } : {}),\n ...(options.longPollHoldMs !== undefined ? { longPollHoldMs: options.longPollHoldMs } : {}),\n ...(options.longPollIntervalMs !== undefined ? { longPollIntervalMs: options.longPollIntervalMs } : {}),\n ...(options.eventsPageLimit !== undefined ? { eventsPageLimit: options.eventsPageLimit } : {}),\n ...(options.accessTokenTtlSeconds !== undefined\n ? { accessTokenTtlSeconds: options.accessTokenTtlSeconds }\n : {}),\n ...(options.boardPageLimit === undefined ? {} : { boardPageLimit: options.boardPageLimit }),\n ...(options.boardStreamQueryIntervalMs === undefined\n ? {}\n : { boardStreamQueryIntervalMs: options.boardStreamQueryIntervalMs }),\n ...(options.boardStreamHeartbeatIntervalMs === undefined\n ? {}\n : { boardStreamHeartbeatIntervalMs: options.boardStreamHeartbeatIntervalMs }),\n ...(options.boardStreamReconciliationIntervalMs === undefined\n ? {}\n : { boardStreamReconciliationIntervalMs: options.boardStreamReconciliationIntervalMs }),\n ...(options.boardChannelMaxBytes === undefined\n ? {}\n : { boardChannelMaxBytes: options.boardChannelMaxBytes }),\n ...(options.boardTitleMaxBytes === undefined\n ? {}\n : { boardTitleMaxBytes: options.boardTitleMaxBytes }),\n ...(options.presenceTtlMs === undefined ? {} : { presenceTtlMs: options.presenceTtlMs }),\n ...(options.presenceMinimumIntervalMs === undefined\n ? {}\n : { presenceMinimumIntervalMs: options.presenceMinimumIntervalMs }),\n ...(options.presenceDetailMaxBytes === undefined\n ? {}\n : { presenceDetailMaxBytes: options.presenceDetailMaxBytes }),\n ...(options.activityMaxEvents === undefined ? {} : { activityMaxEvents: options.activityMaxEvents }),\n ...(options.activityMaxBytes === undefined ? {} : { activityMaxBytes: options.activityMaxBytes }),\n ...(options.activityCapacity === undefined ? {} : { activityCapacity: options.activityCapacity }),\n ...(options.activityTtlMs === undefined ? {} : { activityTtlMs: options.activityTtlMs }),\n ...(options.maxTruthRequestBytes === undefined\n ? {}\n : { maxTruthRequestBytes: options.maxTruthRequestBytes }),\n ...(options.skillPacks === undefined ? {} : { skillPacks: options.skillPacks }),\n ...(options.skillPackPageLimit === undefined\n ? {}\n : { skillPackPageLimit: options.skillPackPageLimit }),\n });\n\n return { cloud, core, stores, blobContentProxy, clock, crypto };\n}\n","import {\n authenticateDeviceAssertion,\n type AuthenticatedDeviceAssertion,\n type Clock,\n type DeviceAssertionExpectedBinding,\n type DeviceAssertionReplayAuthority,\n} from '@byok-sdk/core';\nimport type { CloudCrypto } from '../crypto/port';\nimport type { DeviceDirectory } from '../stores/ports';\n\nexport interface HostedDeviceAssertionAuthDeps {\n readonly devices: DeviceDirectory;\n readonly crypto: CloudCrypto;\n readonly replay: DeviceAssertionReplayAuthority;\n readonly clock: Clock;\n readonly expected: DeviceAssertionExpectedBinding;\n readonly maxLifetimeMs?: number;\n}\n\n/**\n * Hosted composition for an assertion exchange endpoint. The returned\n * principal is current device-directory authority; the assertion is consumed\n * before success is returned. Connector sessions minted afterward remain\n * host-owned and are never represented by this short-lived credential.\n */\nexport function authenticateHostedDeviceAssertion(\n input: unknown,\n deps: HostedDeviceAssertionAuthDeps,\n): Promise<AuthenticatedDeviceAssertion | undefined> {\n return authenticateDeviceAssertion(input, {\n verifier: {\n verify: ({ publicKey, signingInput, signature }) =>\n deps.crypto.verifyEd25519(publicKey, signingInput, signature),\n },\n lookupDevice: async (deviceId) => {\n const row = await deps.devices.resolveByDeviceId(deviceId);\n if (row === undefined) return undefined;\n return {\n tenantId: row.tenantId,\n productId: row.productId,\n deviceId: row.deviceId,\n publicKeyJwkX: row.devicePublicKey,\n revoked: row.revoked,\n };\n },\n replay: deps.replay,\n expected: deps.expected,\n now: deps.clock.now(),\n ...(deps.maxLifetimeMs === undefined ? {} : { maxLifetimeMs: deps.maxLifetimeMs }),\n });\n}\n","import {\n BOARD_STATUSES,\n assertCapability,\n hasCapability,\n type CapabilityDeclaration,\n} from '@byok-sdk/core';\nimport { BYOK_BOARD_PATH, BYOK_BOARD_STREAM_PATH } from '@byok-sdk/protocol';\nimport { z } from 'zod';\nimport { CLOUD_CAPABILITIES } from './capabilities';\n\nconst BoardFeedItemSchema = z.object({\n tenantId: z.string(),\n itemId: z.string(),\n channel: z.string(),\n title: z.string(),\n status: z.enum(BOARD_STATUSES),\n assignee: z\n .object({ holderId: z.string(), heldSince: z.string() })\n .optional(),\n boardSeq: z.number().int().nonnegative(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\n\nconst BoardFeedPageSchema = z.object({\n items: z.array(BoardFeedItemSchema),\n nextSeq: z.number().int().nonnegative(),\n hasMore: z.boolean(),\n});\n\nexport type BoardFeedItem = z.infer<typeof BoardFeedItemSchema>;\nexport type BoardFeedPage = z.infer<typeof BoardFeedPageSchema>;\nexport type BoardFeedMode = 'sse' | 'poll';\nexport type BoardFeedRead =\n | { readonly type: 'board'; readonly item: BoardFeedItem }\n | { readonly type: 'reconcile' }\n | { readonly type: 'poll'; readonly page: BoardFeedPage };\n\nexport class BoardFeedRetryableError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'BoardFeedRetryableError';\n }\n}\n\nexport class BoardFeedStoppedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BoardFeedStoppedError';\n }\n}\n\nexport interface BoardFeedClientOptions {\n readonly baseUrl: string | URL;\n readonly accessToken: string;\n readonly capabilities: CapabilityDeclaration;\n readonly fetch?: typeof globalThis.fetch;\n readonly idleWatchdogMs?: number;\n}\n\n/**\n * One board feed consumer with a declaration-fixed transport.\n *\n * The mode is selected once from ADR-010 data. A temporary SSE 5xx or idle\n * watchdog expiry raises {@link BoardFeedRetryableError}; it never mutates the\n * mode to polling. A caller retries the same instance and therefore the same\n * declared transport. Polling exists only when `board.sse` was absent from the\n * declaration in the first place.\n */\nexport class BoardFeedClient {\n readonly mode: BoardFeedMode;\n readonly #base: URL;\n readonly #accessToken: string;\n readonly #fetch: typeof globalThis.fetch;\n readonly #idleWatchdogMs: number;\n\n constructor(options: BoardFeedClientOptions) {\n assertCapability(options.capabilities, CLOUD_CAPABILITIES.boardCoordination);\n this.mode = hasCapability(options.capabilities, CLOUD_CAPABILITIES.boardSse) ? 'sse' : 'poll';\n this.#base = new URL(options.baseUrl);\n this.#accessToken = options.accessToken;\n this.#fetch = options.fetch ?? globalThis.fetch;\n this.#idleWatchdogMs = options.idleWatchdogMs ?? 30_000;\n }\n\n async readOnce(afterSeq: number, signal?: AbortSignal): Promise<BoardFeedRead> {\n if (!Number.isSafeInteger(afterSeq) || afterSeq < 0) {\n throw new TypeError('afterSeq must be a non-negative safe integer.');\n }\n return this.mode === 'sse'\n ? this.#readSseOnce(afterSeq, signal)\n : this.#readPollOnce(afterSeq, signal);\n }\n\n async #readPollOnce(afterSeq: number, signal?: AbortSignal): Promise<BoardFeedRead> {\n const url = new URL(BYOK_BOARD_PATH, this.#base);\n url.searchParams.set('since', String(afterSeq));\n const response = await this.#fetch(url, {\n headers: { authorization: `Bearer ${this.#accessToken}` },\n ...(signal === undefined ? {} : { signal }),\n });\n assertBoardResponse(response, 'poll');\n return { type: 'poll', page: BoardFeedPageSchema.parse(await response.json()) };\n }\n\n async #readSseOnce(afterSeq: number, signal?: AbortSignal): Promise<BoardFeedRead> {\n const url = new URL(BYOK_BOARD_STREAM_PATH, this.#base);\n const response = await this.#fetch(url, {\n headers: {\n accept: 'text/event-stream',\n authorization: `Bearer ${this.#accessToken}`,\n 'last-event-id': String(afterSeq),\n },\n ...(signal === undefined ? {} : { signal }),\n });\n assertBoardResponse(response, 'SSE');\n if (response.body === null) throw new BoardFeedRetryableError('Board SSE response had no body.');\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n while (true) {\n const chunk = await readWithWatchdog(reader, this.#idleWatchdogMs);\n if (chunk.done) throw new BoardFeedRetryableError('Board SSE ended before the next event.');\n buffer += decoder.decode(chunk.value, { stream: true }).replaceAll('\\r\\n', '\\n');\n let boundary = buffer.indexOf('\\n\\n');\n while (boundary >= 0) {\n const frame = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n const parsed = parseSseFrame(frame);\n if (parsed !== undefined) return parsed;\n boundary = buffer.indexOf('\\n\\n');\n }\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n }\n}\n\nfunction assertBoardResponse(response: Response, transport: 'poll' | 'SSE'): void {\n if (response.status === 401) {\n throw new BoardFeedStoppedError('Board credential is no longer valid.');\n }\n if (response.ok) return;\n if (response.status >= 500) {\n throw new BoardFeedRetryableError(`Board ${transport} failed with HTTP ${response.status}.`);\n }\n throw new BoardFeedStoppedError(\n `Board ${transport} failed permanently with HTTP ${response.status}.`,\n );\n}\n\nasync function readWithWatchdog(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n timeoutMs: number,\n) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n reader.read(),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new BoardFeedRetryableError('Board SSE idle watchdog expired.')),\n timeoutMs,\n );\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\nfunction parseSseFrame(frame: string): BoardFeedRead | undefined {\n if (frame.length === 0 || frame.startsWith(':')) return undefined;\n let event = 'message';\n const data: string[] = [];\n for (const line of frame.split('\\n')) {\n if (line.startsWith('event:')) event = line.slice('event:'.length).trimStart();\n if (line.startsWith('data:')) data.push(line.slice('data:'.length).trimStart());\n }\n if (event === 'reconcile') return { type: 'reconcile' };\n if (event !== 'board') return undefined;\n if (data.length === 0) throw new SyntaxError('Board SSE board event had no data.');\n return { type: 'board', item: BoardFeedItemSchema.parse(JSON.parse(data.join('\\n'))) };\n}\n","/**\n * The cloud-local store ports.\n *\n * `@byok-sdk/core` owns the platform ports every composition shares (mailbox,\n * board, truth, objects, quota). These are the ones only a HOSTED device\n * surface needs — the auth plane and the task-attempt bookkeeping the device\n * routes read. S2 deliberately kept them out of core: they are hosted-surface\n * concerns, and S4A's schema work is the right moment to decide their durable\n * home. Cloud owning them keeps this slice additive and revertible.\n *\n * Two rules, same as core's (`stores.ts`):\n *\n * 1. **Async.** Every method returns a `Promise`, so a SQL or KV composition\n * can implement the same contract the in-memory reference does.\n * 2. **Tenant-first.** Every method's first parameter is a required\n * `TenantId` — with exactly two documented exceptions below, each of\n * which is pre-tenant *by construction* because the credential it is\n * handed is itself what resolves the tenant.\n *\n * The two exceptions:\n *\n * - {@link DeviceDirectory.resolveByDeviceId} — `POST /byok/challenge` and\n * `POST /byok/token` carry only a deviceId (the pinned wire contract), and\n * the row is what tells the deployment which tenant to mint for.\n * - {@link PairingCodeStore.redeem} — the code IS the tenant lookup; it was\n * minted against a tenant that only the host's control plane knew.\n *\n * Neither is reachable through {@link TenantStores} (see `tenant-stores.ts`),\n * so a device-facing handler cannot call them.\n *\n * The byte-proxy trio that used to be a third pre-tenant exception is no\n * longer part of this bundle at all: it moved to {@link BlobContentProxy},\n * an OPTIONAL composition input rather than a {@link CloudStores} member,\n * because a composition backed by object storage physically cannot proxy\n * bytes (see the blobs section below).\n */\nimport type { StorageReservation, TenantId } from '@byok-sdk/core';\nimport type { ActivityStore } from '../activity';\nimport type { ApprovalTimelineStore } from '../approval-timeline';\n\n// ---------------------------------------------------------------------------\n// Device directory (S1's `DeviceRegistry`, tenant-first)\n// ---------------------------------------------------------------------------\n\nexport interface DeviceRecord {\n readonly tenantId: TenantId;\n readonly productId: string;\n readonly deviceId: string;\n readonly deviceName: string;\n /** Ed25519 public key, base64url-encoded (JWK `x` form). */\n readonly devicePublicKey: string;\n /** Proof key identity stored on the row; verifier claims never supply a default. */\n readonly proofKeyId: string;\n /** Current proof signing-key rotation generation. */\n readonly proofKeyEpoch: number;\n readonly revoked: boolean;\n}\n\n/** Everything `POST /byok/pair` knows at registration time. `tenantId` is the store's first parameter; `revoked` is the store's own to set. */\nexport interface DeviceRegistration {\n readonly productId: string;\n readonly deviceId: string;\n readonly deviceName: string;\n readonly devicePublicKey: string;\n readonly proofKeyId: string;\n readonly proofKeyEpoch: number;\n}\n\nexport interface DeviceDirectory {\n register(tenant: TenantId, input: DeviceRegistration): Promise<DeviceRecord>;\n /** The row `tenant` owns under `deviceId` — `undefined` including when the device exists under a DIFFERENT tenant. */\n get(tenant: TenantId, deviceId: string): Promise<DeviceRecord | undefined>;\n revoke(tenant: TenantId, deviceId: string): Promise<void>;\n list(tenant: TenantId): Promise<readonly DeviceRecord[]>;\n /** Pre-tenant. Two callers only: `POST /byok/challenge` and `POST /byok/token`. Never exposed through the tenant facade. */\n resolveByDeviceId(deviceId: string): Promise<DeviceRecord | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Pairing codes (S1's `PairingManager`, tenant-first mint)\n// ---------------------------------------------------------------------------\n\n/**\n * The identity a pairing code carries. Minted out-of-band by the host's own\n * auth/device-flow UI — the only party that knows which tenant a human is\n * acting for. Deliberately NOT a wire field: `PairRequest` has no tenant of\n * its own, so a device can never name the tenant it lands in.\n */\nexport interface PairingCodeClaims {\n readonly tenantId: TenantId;\n readonly productId: string;\n}\n\nexport interface PairingCodeInfo {\n readonly code: string;\n /** Canonical ISO-8601 UTC instant. */\n readonly expiresAt: string;\n}\n\nexport interface PairingCodeIssueInput {\n readonly code: string;\n readonly productId: string;\n readonly expiresAt: string;\n}\n\nexport interface PairingCodeStore {\n issue(tenant: TenantId, input: PairingCodeIssueInput): Promise<PairingCodeInfo>;\n /**\n * Validate and CONSUME a code, returning the claims it was minted with, or\n * `undefined` when it is unknown, expired, or already used — one answer for\n * all three, so a redeem attempt is never an existence oracle. Single-use is\n * what makes the caller's \"redeem, then register the device row\" sequence\n * exclusive: a second redeem can never reach the registration step.\n */\n redeem(code: string): Promise<PairingCodeClaims | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Challenge nonces\n// ---------------------------------------------------------------------------\n\nexport interface NonceStore {\n issue(tenant: TenantId, deviceId: string): Promise<string>;\n /** `true` iff the nonce exists for this (tenant, device), is unexpired, and has not been consumed. Never mutates. */\n validate(tenant: TenantId, deviceId: string, nonce: string): Promise<boolean>;\n /** Consume the nonce. Called only after every other check on the request has passed. */\n markUsed(tenant: TenantId, nonce: string): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// Inbound envelope dedup (N3)\n// ---------------------------------------------------------------------------\n\nexport interface InboundDedupStore {\n /**\n * `true` when `envelopeId` was already seen for this (tenant, device);\n * otherwise records it and returns `false`. Bounded per device — the wire is\n * at-least-once (§9); this makes processing at-most-once without an\n * unbounded set.\n */\n checkAndRecord(tenant: TenantId, deviceId: string, envelopeId: string): Promise<boolean>;\n}\n\n// ---------------------------------------------------------------------------\n// Task attempts — the ownership authority the inbound gate reads (N2)\n// ---------------------------------------------------------------------------\n\nexport const TASK_ATTEMPT_STATUSES = [\n 'offered',\n 'claimed',\n 'running',\n 'complete',\n 'failed',\n 'cancelled',\n] as const;\nexport type TaskAttemptStatus = (typeof TASK_ATTEMPT_STATUSES)[number];\n\nexport interface TaskAttempt {\n readonly tenantId: TenantId;\n readonly taskId: string;\n /** The device the offer was addressed to. */\n readonly deviceId: string;\n /** Set by `task.claim`, and only by the first one. Until then the task has no owner and the gate lets any of this tenant's devices through, matching the reference server. */\n readonly ownerDeviceId?: string;\n readonly status: TaskAttemptStatus;\n readonly updatedAt: string;\n}\n\nexport interface TaskAttemptStore {\n /** Called when an offer is enqueued: records the pending attempt with no owner yet. */\n open(tenant: TenantId, input: { readonly taskId: string; readonly deviceId: string }): Promise<TaskAttempt>;\n get(tenant: TenantId, taskId: string): Promise<TaskAttempt | undefined>;\n /** First claim wins the ownership; a later claim by the same device is idempotent. No-op (returns `undefined`) for a task this tenant never offered. */\n claim(tenant: TenantId, input: { readonly taskId: string; readonly deviceId: string }): Promise<TaskAttempt | undefined>;\n /** Record a lifecycle transition. No-op (returns `undefined`) for an unknown task — same shape as the reference server's per-type handlers. */\n recordStatus(\n tenant: TenantId,\n input: { readonly taskId: string; readonly status: TaskAttemptStatus },\n ): Promise<TaskAttempt | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Request receipts — the terminal idempotency seam\n// ---------------------------------------------------------------------------\n\nexport interface RequestReceipt {\n readonly tenantId: TenantId;\n readonly key: string;\n /** Opaque payload the caller recorded — for terminals, the encoded envelope. */\n readonly body: string;\n readonly recordedAt: string;\n}\n\nexport interface RequestReceiptStore {\n /**\n * Record a receipt under `key`, or return the existing one untouched.\n * `created` is `false` for a replay — the FIRST terminal is the fact\n * (§12.6.4: 不覆写第一份事实), and a retry of the same terminal must not\n * overwrite it.\n */\n record(\n tenant: TenantId,\n input: { readonly key: string; readonly body: string },\n ): Promise<{ readonly receipt: RequestReceipt; readonly created: boolean }>;\n get(tenant: TenantId, key: string): Promise<RequestReceipt | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Device-proof request receipts — request-bound replay authority (S6)\n// ---------------------------------------------------------------------------\n\nexport interface ProofRequestReceipt {\n readonly tenantId: TenantId;\n readonly deviceId: string;\n readonly requestId: string;\n readonly operation: string;\n readonly resource: string;\n readonly bodySha256: string;\n readonly bodySize: bigint;\n readonly responseStatus: number;\n readonly responseBody: string;\n readonly recordedAt: string;\n}\n\nexport type ProofRequestReceiptInput = Omit<\n ProofRequestReceipt,\n 'tenantId' | 'recordedAt'\n>;\n\n/**\n * First-result-wins replay store. The application layer compares every stored\n * binding before returning an exact replay; a reused request id with any\n * different binding is a conflict, never a second write.\n */\nexport interface ProofRequestReceiptStore {\n record(\n tenant: TenantId,\n input: ProofRequestReceiptInput,\n ): Promise<{ readonly receipt: ProofRequestReceipt; readonly created: boolean }>;\n get(\n tenant: TenantId,\n deviceId: string,\n requestId: string,\n ): Promise<ProofRequestReceipt | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Blobs (§7)\n// ---------------------------------------------------------------------------\n\nexport interface BlobDeclaration {\n readonly size: number;\n readonly contentType: string;\n /** Canonical `sha256:<64 lowercase hex>` — the schema rejected anything else before this store sees it. */\n readonly contentHash: string;\n}\n\n/** What object-store metadata can actually observe at finalize (ADR-024). */\nexport interface BlobObservation {\n readonly observedByteSize: bigint;\n readonly observedContentType: string;\n}\n\nexport type BlobWriteResult = { readonly ok: true } | { readonly ok: false; readonly reason: string };\n\nexport interface BlobContent {\n readonly data: Uint8Array;\n readonly contentType: string;\n}\n\n/**\n * The capability-minting half of blobs: what EVERY composition can honestly\n * provide, whoever holds the bytes.\n *\n * Both methods are tenant-first, and both are reachable through {@link\n * TenantStores}. There is no pre-tenant method left on this port — see\n * {@link BlobContentProxy} for where the other three went and why.\n */\nexport interface CloudBlobStore {\n /** Mint only from an already-admitted object reservation. */\n createUpload(tenant: TenantId, reservation: StorageReservation): Promise<{ readonly blobId: string; readonly uploadUrl: string }>;\n /** Observe existence/size/type while proving this blob belongs to this reservation. */\n observeUpload(tenant: TenantId, blobId: string, reservation: StorageReservation): Promise<BlobObservation | undefined>;\n /** A presigned GET URL for a blob THIS tenant owns that has finished uploading; `undefined` otherwise — including for another tenant's blob. */\n getDownloadUrl(tenant: TenantId, blobId: string): Promise<string | undefined>;\n}\n\n/**\n * The byte-proxying half: an OPTIONAL composition input, not a port.\n *\n * These three serve the two `/byok/blobs/:id/content` routes, which exist\n * because the in-memory and self-hosted compositions have nowhere else to put\n * bytes — cloud has to carry them. A composition whose bytes live in object\n * storage (S3/R2) hands the device a presigned URL to the object store itself\n * and never sees a byte, so it cannot implement these at all.\n *\n * That is why this is a separate interface supplied at composition time rather\n * than a member of {@link CloudStores}: \"this deployment cannot proxy bytes\"\n * becomes a type-level fact (the proxy is simply absent) instead of three\n * methods that throw. The alternatives were both anti-patterns — a conformance\n * suite that skips three methods for one composition is a subset waiver, and\n * one that asserts a typed rejection proves nothing\n * (docs/researches/s4a-dataplane-design.md §6).\n *\n * All three are pre-tenant by construction: the `/content` routes are\n * presigned, not bearer-authed, so there is no principal in scope at all and\n * the HMAC signature over the blob id is the whole credential. They stay off\n * {@link TenantStores} for the same reason the two exceptions above do.\n *\n * A deployment supplying a proxy must also declare `blobs.contentproxy`\n * (ADR-010): the routes mount on proxy-presence AND declaration, never on\n * either alone.\n */\nexport interface BlobContentProxy {\n verifySignedUrl(blobId: string, action: 'put' | 'get', sig: string, exp: number): Promise<boolean>;\n writeContent(blobId: string, data: Uint8Array): Promise<BlobWriteResult>;\n readContent(blobId: string): Promise<BlobContent | undefined>;\n}\n\n// ---------------------------------------------------------------------------\n// Inbound rate limiting (M4 Phase 4 part A's seam)\n// ---------------------------------------------------------------------------\n\n/**\n * Step 0 of the inbound gate. S3a ships an allow-all reference (a hosted\n * deployment's real limiter is edge/infra work, not handler work) — what\n * matters now is that the SEAM sits at gate position 0, before the type-allow\n * check, so a flood of garbage-typed envelopes costs the same budget as a\n * flood of well-formed ones once a real limiter is plugged in.\n */\nexport interface InboundRateLimiter {\n consume(tenant: TenantId, deviceId: string): Promise<boolean>;\n}\n\n// ---------------------------------------------------------------------------\n// The bundle a composition supplies\n// ---------------------------------------------------------------------------\n\n/**\n * All-or-nothing: a composition supplies every port here or it is not a\n * composition. {@link BlobContentProxy} is deliberately absent — it is an\n * optional input to `createByokCloud`, not a port, precisely so that the\n * bundle can stay all-or-nothing while byte proxying stays optional.\n */\nexport interface CloudStores {\n readonly activity: ActivityStore;\n readonly approvals: ApprovalTimelineStore;\n readonly devices: DeviceDirectory;\n readonly pairingCodes: PairingCodeStore;\n readonly nonces: NonceStore;\n readonly dedup: InboundDedupStore;\n readonly tasks: TaskAttemptStore;\n readonly receipts: RequestReceiptStore;\n readonly proofReceipts: ProofRequestReceiptStore;\n readonly blobs: CloudBlobStore;\n readonly rateLimiter: InboundRateLimiter;\n}\n\n/** Names of every port in {@link CloudStores}, in contract order. */\nexport const CLOUD_STORE_NAMES = [\n 'activity',\n 'approvals',\n 'devices',\n 'pairingCodes',\n 'nonces',\n 'dedup',\n 'tasks',\n 'receipts',\n 'proofReceipts',\n 'blobs',\n 'rateLimiter',\n] as const;\n\nexport type CloudStoreName = (typeof CLOUD_STORE_NAMES)[number];\n","/**\n * The declared method inventory of every cloud-local port.\n *\n * The exact counterpart of `@byok-sdk/core`'s `ports-contract.ts`, and it exists\n * for the same reason: the table says what a port IS, so it has to be readable\n * by every enforcer without any of them owning it. `@byok-sdk/conformance` asserts\n * live compositions against it; a durable adapter (`@byok-sdk/cloud-dataplane`) is\n * written against it.\n *\n * This module adds data and nothing else. It does not re-declare, re-shape, or\n * re-interpret a single line of `ports.ts` — that file stays the authority for\n * what the methods mean, and stayed byte-identical through S4A-a.\n *\n * Adding a port method means editing this table, which is the point: a port\n * grows by contract, not by whichever composition needed something.\n */\nimport type { CloudStoreName } from './ports';\n\nexport const CLOUD_PORT_METHODS: Readonly<Record<CloudStoreName, readonly string[]>> = {\n activity: ['append', 'read'],\n approvals: ['append', 'read'],\n devices: ['register', 'get', 'revoke', 'list', 'resolveByDeviceId'],\n pairingCodes: ['issue', 'redeem'],\n nonces: ['issue', 'validate', 'markUsed'],\n dedup: ['checkAndRecord'],\n tasks: ['open', 'get', 'claim', 'recordStatus'],\n receipts: ['record', 'get'],\n proofReceipts: ['record', 'get'],\n // Three methods, not six: the byte-proxy trio moved to `BlobContentProxy`,\n // which is a composition input rather than a port and therefore has no row\n // in this table (docs/researches/s4a-dataplane-design.md §6).\n blobs: ['createUpload', 'observeUpload', 'getDownloadUrl'],\n rateLimiter: ['consume'],\n};\n\n/** The interface each port name is declared as, for a source-side scan. */\nexport const CLOUD_PORT_INTERFACES: Readonly<Record<CloudStoreName, string>> = {\n activity: 'ActivityStore',\n approvals: 'ApprovalTimelineStore',\n devices: 'DeviceDirectory',\n pairingCodes: 'PairingCodeStore',\n nonces: 'NonceStore',\n dedup: 'InboundDedupStore',\n tasks: 'TaskAttemptStore',\n receipts: 'RequestReceiptStore',\n proofReceipts: 'ProofRequestReceiptStore',\n blobs: 'CloudBlobStore',\n rateLimiter: 'InboundRateLimiter',\n};\n"]}