@happyvertical/smrt-vault-relay 0.0.0-stage → 0.60.17
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/AGENTS.md +51 -0
- package/CLAUDE.md +1 -0
- package/LICENSE +7 -0
- package/README.md +364 -2
- package/dist/auth.d.ts +66 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/chunks/server-0ITpMTMD.js +2358 -0
- package/dist/chunks/server-0ITpMTMD.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +43 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +86 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/encoding.d.ts +20 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/lease-store.d.ts +108 -0
- package/dist/lease-store.d.ts.map +1 -0
- package/dist/lease.d.ts +60 -0
- package/dist/lease.d.ts.map +1 -0
- package/dist/manifest.json +15 -0
- package/dist/metadata-store.d.ts +212 -0
- package/dist/metadata-store.d.ts.map +1 -0
- package/dist/node-server.d.ts +14 -0
- package/dist/node-server.d.ts.map +1 -0
- package/dist/object-store.d.ts +60 -0
- package/dist/object-store.d.ts.map +1 -0
- package/dist/relay.d.ts +268 -0
- package/dist/relay.d.ts.map +1 -0
- package/dist/server.d.ts +46 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/smrt-knowledge.json +73 -0
- package/dist/smrt-knowledge.okf.md +56 -0
- package/package.json +54 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-0ITpMTMD.js","names":[],"sources":["../../src/encoding.ts","../../src/auth.ts","../../src/config.ts","../../src/lease.ts","../../src/lease-store.ts","../../src/metadata-store.ts","../../src/node-server.ts","../../src/object-store.ts","../../src/relay.ts","../../src/server.ts"],"sourcesContent":["/**\n * Identifier shapes and byte encodings shared by the relay and its client\n * helper. Every identifier that reaches SQL, an object key, or a log line is\n * checked here first, so a hostile header can never become a path segment or\n * an unbounded string.\n */\nimport { createHash } from 'node:crypto';\n\n/** Account and device identifiers: an opaque, URL-safe token. */\nconst IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;\n/** Request nonce: 16 to 64 base64url characters (at least 96 bits). */\nconst NONCE = /^[A-Za-z0-9_-]{16,64}$/;\nconst SHA256_HEX = /^[0-9a-f]{64}$/;\nconst BASE64URL = /^[A-Za-z0-9_-]+$/;\nconst UPLOAD_ID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\n\n/** SHA-256 of the empty body, the content hash of a bodiless request. */\nexport const EMPTY_SHA256 = createHash('sha256').digest('hex');\n\nexport function isIdentifier(value: unknown): value is string {\n return typeof value === 'string' && IDENTIFIER.test(value);\n}\n\nexport function isNonce(value: unknown): value is string {\n return typeof value === 'string' && NONCE.test(value);\n}\n\nexport function isSha256Hex(value: unknown): value is string {\n return typeof value === 'string' && SHA256_HEX.test(value);\n}\n\nexport function isUploadId(value: unknown): value is string {\n return typeof value === 'string' && UPLOAD_ID.test(value);\n}\n\nexport function sha256Hex(data: Uint8Array | string): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * The account's storage and log handle: a hash, so object keys and log lines\n * never carry the account identifier itself.\n */\nexport function accountHandle(accountId: string): string {\n return sha256Hex(`smrt-vault-relay:account:${accountId}`);\n}\n\nexport function encodeBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** Strict base64url decode; `null` for anything not canonical base64url. */\nexport function decodeBase64Url(value: string): Uint8Array | null {\n if (!BASE64URL.test(value)) return null;\n const bytes = Buffer.from(value, 'base64url');\n if (bytes.toString('base64url') !== value) return null;\n return new Uint8Array(bytes);\n}\n\n/** Parse a non-negative safe integer written in canonical decimal. */\nexport function parseCanonicalInteger(value: string): number | null {\n if (!/^(0|[1-9][0-9]{0,15})$/.test(value)) return null;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) ? parsed : null;\n}\n\n/** Coerce a database integer (BIGINT may arrive as a string) to a safe number. */\nexport function toSafeInteger(value: unknown, field: string): number {\n const parsed =\n typeof value === 'number'\n ? value\n : typeof value === 'bigint'\n ? Number(value)\n : typeof value === 'string'\n ? Number(value)\n : Number.NaN;\n if (!Number.isSafeInteger(parsed)) {\n throw new Error(`vault relay: ${field} is not a safe integer`);\n }\n return parsed;\n}\n","/**\n * Device-signature request authentication (protocol `smrt-vault-relay-v1`).\n *\n * A device signs every request with its Ed25519 key. The signed string binds\n * the method, path and query, the claimed account and device, a timestamp, a\n * single-use nonce, and the SHA-256 of the exact request body:\n *\n * ```text\n * smrt-vault-relay-v1\n * <METHOD>\n * <path and query, exactly as sent>\n * <account id>\n * <device id>\n * <timestamp, unix milliseconds>\n * <nonce>\n * <body sha256, lowercase hex>\n * ```\n *\n * The relay accepts the signature only from a key registered and active for\n * that account and device, within the clock-skew window, with a nonce it has\n * not seen, and with a body whose digest matches. It derives nothing about\n * identity from blob content.\n */\nimport {\n createPrivateKey,\n createPublicKey,\n type KeyObject,\n sign,\n verify,\n} from 'node:crypto';\nimport {\n decodeBase64Url,\n encodeBase64Url,\n isIdentifier,\n isNonce,\n isSha256Hex,\n parseCanonicalInteger,\n} from './encoding.js';\n\nexport const SIGNATURE_PROTOCOL = 'smrt-vault-relay-v1';\n\nexport const HEADER_ACCOUNT = 'x-vault-account';\nexport const HEADER_DEVICE = 'x-vault-device';\nexport const HEADER_TIMESTAMP = 'x-vault-timestamp';\nexport const HEADER_NONCE = 'x-vault-nonce';\nexport const HEADER_CONTENT_SHA256 = 'x-vault-content-sha256';\nexport const HEADER_SIGNATURE = 'x-vault-signature';\n\nconst ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');\nconst ED25519_PKCS8_PREFIX = Buffer.from(\n '302e020100300506032b657004220420',\n 'hex',\n);\n\nexport interface SignedRequestFields {\n method: string;\n /** Path plus query string exactly as sent, e.g. `/v1/snapshots?x=1`. */\n pathAndQuery: string;\n accountId: string;\n deviceId: string;\n timestamp: number;\n nonce: string;\n contentSha256: string;\n}\n\n/** The exact byte string a device signs. */\nexport function canonicalRequest(fields: SignedRequestFields): Buffer {\n return Buffer.from(\n [\n SIGNATURE_PROTOCOL,\n fields.method.toUpperCase(),\n fields.pathAndQuery,\n fields.accountId,\n fields.deviceId,\n String(fields.timestamp),\n fields.nonce,\n fields.contentSha256,\n ].join('\\n'),\n 'utf8',\n );\n}\n\n/** Import a raw 32-byte Ed25519 public key (base64url). */\nexport function importDevicePublicKey(encoded: string): KeyObject | null {\n const raw = decodeBase64Url(encoded);\n if (raw?.length !== 32) return null;\n try {\n return createPublicKey({\n key: Buffer.concat([ED25519_SPKI_PREFIX, raw]),\n format: 'der',\n type: 'spki',\n });\n } catch {\n return null;\n }\n}\n\n/** Raw 32-byte public key of an Ed25519 key object, base64url. */\nexport function exportDevicePublicKey(key: KeyObject): string {\n const der = key.export({ format: 'der', type: 'spki' });\n return encodeBase64Url(der.subarray(der.length - 32));\n}\n\n/** Build an Ed25519 private key object from a raw 32-byte seed. */\nexport function importDevicePrivateKey(seed: Uint8Array): KeyObject {\n if (seed.length !== 32) {\n throw new Error('vault relay: an Ed25519 seed is 32 bytes');\n }\n return createPrivateKey({\n key: Buffer.concat([ED25519_PKCS8_PREFIX, Buffer.from(seed)]),\n format: 'der',\n type: 'pkcs8',\n });\n}\n\n/**\n * Client helper: the headers that authenticate one request. The caller\n * supplies a fresh random nonce and the SHA-256 of the exact body it sends.\n */\nexport function signRelayRequest(\n fields: SignedRequestFields,\n privateKey: KeyObject,\n): Record<string, string> {\n const signature = sign(null, canonicalRequest(fields), privateKey);\n return {\n [HEADER_ACCOUNT]: fields.accountId,\n [HEADER_DEVICE]: fields.deviceId,\n [HEADER_TIMESTAMP]: String(fields.timestamp),\n [HEADER_NONCE]: fields.nonce,\n [HEADER_CONTENT_SHA256]: fields.contentSha256,\n [HEADER_SIGNATURE]: encodeBase64Url(signature),\n };\n}\n\nexport interface ParsedSignature {\n fields: SignedRequestFields;\n signature: Uint8Array;\n}\n\n/**\n * Read and shape-check the signature headers; `null` when any is missing or\n * malformed. Does not verify the signature.\n */\nexport function parseSignatureHeaders(\n method: string,\n pathAndQuery: string,\n headers: Headers,\n): ParsedSignature | null {\n const accountId = headers.get(HEADER_ACCOUNT);\n const deviceId = headers.get(HEADER_DEVICE);\n const timestampText = headers.get(HEADER_TIMESTAMP);\n const nonce = headers.get(HEADER_NONCE);\n const contentSha256 = headers.get(HEADER_CONTENT_SHA256);\n const signatureText = headers.get(HEADER_SIGNATURE);\n if (\n !isIdentifier(accountId) ||\n !isIdentifier(deviceId) ||\n !isNonce(nonce) ||\n !isSha256Hex(contentSha256) ||\n timestampText === null ||\n signatureText === null ||\n signatureText.length > 128\n ) {\n return null;\n }\n const timestamp = parseCanonicalInteger(timestampText);\n const signature = decodeBase64Url(signatureText);\n if (timestamp === null || !signature || signature.length !== 64) {\n return null;\n }\n return {\n fields: {\n method,\n pathAndQuery,\n accountId,\n deviceId,\n timestamp,\n nonce,\n contentSha256,\n },\n signature,\n };\n}\n\n/** Verify an Ed25519 signature over the canonical request. */\nexport function verifySignature(\n parsed: ParsedSignature,\n publicKey: KeyObject,\n): boolean {\n try {\n return verify(\n null,\n canonicalRequest(parsed.fields),\n publicKey,\n parsed.signature,\n );\n } catch {\n return false;\n }\n}\n","/**\n * Relay policy: per-account quotas, retention, and request bounds.\n *\n * Quotas and retention are owner decisions and have no defaults. The request\n * bounds are technical limits with defaults that match the snapshot format.\n */\n\n/** Hard ceiling on one chunk, whatever the configuration says. */\nexport const MAX_CHUNK_BYTES_CEILING = 64 * 1024 * 1024;\n/** Default chunk bound: one 8 MiB v1 vault envelope plus framing headroom. */\nexport const DEFAULT_MAX_CHUNK_BYTES = 8 * 1024 * 1024 + 64 * 1024;\n/** Object keys allow at most six decimal digits for the chunk index. */\nexport const MAX_CHUNKS_PER_SNAPSHOT = 999_999;\nexport const DEFAULT_UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;\nexport const DEFAULT_MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;\n/**\n * How far above the account's sequence high-water mark one upload may begin\n * or commit. Sequences are chosen by the device, and a commit raises the mark\n * permanently, so an unbounded jump (one commit at 2^53-1) would make every\n * later upload `stale_sequence`. A device that makes a backup every few\n * minutes needs a few thousand sequences in a decade; 1000 per step leaves\n * room for a device that skipped sequences while offline. An owner decision\n * may raise it with `VAULT_RELAY_MAX_SEQUENCE_JUMP`.\n */\nexport const DEFAULT_MAX_SEQUENCE_JUMP = 1000;\n/** Default primary-writer lease lifetime (#4805). */\nexport const DEFAULT_LEASE_TTL_MS = 5 * 60 * 1000;\n/** Bounds of the configured lease lifetime. */\nexport const MIN_CONFIGURED_LEASE_TTL_MS = 30 * 1000;\nexport const MAX_CONFIGURED_LEASE_TTL_MS = 60 * 60 * 1000;\n/**\n * Default time a lapsed account's snapshots stay restorable, measured from the\n * moment the relay first observed the `backup.vault` entitlement as lapsed\n * (#4819). An owner decision (90 days), configurable per deployment.\n */\nexport const DEFAULT_LAPSE_RETENTION_DAYS = 90;\n/** Upper bound of the configured lapse window (ten years). */\nexport const MAX_LAPSE_RETENTION_DAYS = 3650;\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** Upper bound of a JSON request body (begin upload, device registration). */\nexport const MAX_JSON_BODY_BYTES = 4096;\n\nexport interface VaultRelayQuota {\n /** Bytes per account, counting committed snapshots and pending uploads. */\n maxBytes: number;\n /** Snapshots per account, counting pending uploads. */\n maxSnapshots: number;\n}\n\nexport interface VaultRelayRetention {\n /** Always keep this many newest committed snapshots (at least 1). */\n keepLast: number;\n /** Also keep committed snapshots younger than this many milliseconds. */\n keepWithinMs: number;\n /**\n * Days a lapsed account stays restorable (list, latest, download, abort)\n * after the lapse is first observed; afterwards the operator sweep may\n * delete its snapshots. Default 90.\n */\n lapseRetentionDays: number;\n /** `lapseRetentionDays` in milliseconds. */\n lapseRetentionMs: number;\n}\n\nexport interface VaultRelayLimits {\n maxChunkBytes: number;\n uploadTtlMs: number;\n maxClockSkewMs: number;\n /** Largest `sequence - highWaterSequence` a begin or commit may carry. */\n maxSequenceJump: number;\n /** Primary-writer lease lifetime; holders renew before it lapses. */\n leaseTtlMs: number;\n}\n\nexport interface VaultRelayPolicy {\n quota: VaultRelayQuota;\n retention: VaultRelayRetention;\n limits: VaultRelayLimits;\n}\n\nexport interface VaultRelayPolicyInput {\n quota: VaultRelayQuota;\n retention: Omit<\n VaultRelayRetention,\n 'lapseRetentionDays' | 'lapseRetentionMs'\n > & { lapseRetentionDays?: number };\n limits?: Partial<VaultRelayLimits>;\n}\n\nfunction positiveInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(`vault relay: ${name} must be a positive integer`);\n }\n return value;\n}\n\nfunction nonNegativeInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`vault relay: ${name} must be a non-negative integer`);\n }\n return value;\n}\n\nfunction lapseRetention(days: number | undefined): {\n lapseRetentionDays: number;\n lapseRetentionMs: number;\n} {\n const lapseRetentionDays = positiveInteger(\n days ?? DEFAULT_LAPSE_RETENTION_DAYS,\n 'retention.lapseRetentionDays',\n );\n if (lapseRetentionDays > MAX_LAPSE_RETENTION_DAYS) {\n throw new Error(\n `vault relay: retention.lapseRetentionDays may not exceed ${MAX_LAPSE_RETENTION_DAYS}`,\n );\n }\n return { lapseRetentionDays, lapseRetentionMs: lapseRetentionDays * DAY_MS };\n}\n\n/**\n * Validate and complete a policy. Retention must leave room for one upload\n * under the snapshot quota, or steady-state accounts could never back up.\n */\nexport function resolvePolicy(input: VaultRelayPolicyInput): VaultRelayPolicy {\n const quota = {\n maxBytes: positiveInteger(input.quota.maxBytes, 'quota.maxBytes'),\n maxSnapshots: positiveInteger(\n input.quota.maxSnapshots,\n 'quota.maxSnapshots',\n ),\n };\n const retention = {\n keepLast: positiveInteger(input.retention.keepLast, 'retention.keepLast'),\n keepWithinMs: nonNegativeInteger(\n input.retention.keepWithinMs,\n 'retention.keepWithinMs',\n ),\n ...lapseRetention(input.retention.lapseRetentionDays),\n };\n if (retention.keepLast >= quota.maxSnapshots) {\n throw new Error(\n 'vault relay: retention.keepLast must be below quota.maxSnapshots so a new upload fits',\n );\n }\n const limits = {\n maxChunkBytes: positiveInteger(\n input.limits?.maxChunkBytes ?? DEFAULT_MAX_CHUNK_BYTES,\n 'limits.maxChunkBytes',\n ),\n uploadTtlMs: positiveInteger(\n input.limits?.uploadTtlMs ?? DEFAULT_UPLOAD_TTL_MS,\n 'limits.uploadTtlMs',\n ),\n maxClockSkewMs: positiveInteger(\n input.limits?.maxClockSkewMs ?? DEFAULT_MAX_CLOCK_SKEW_MS,\n 'limits.maxClockSkewMs',\n ),\n maxSequenceJump: positiveInteger(\n input.limits?.maxSequenceJump ?? DEFAULT_MAX_SEQUENCE_JUMP,\n 'limits.maxSequenceJump',\n ),\n leaseTtlMs: positiveInteger(\n input.limits?.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS,\n 'limits.leaseTtlMs',\n ),\n };\n if (\n limits.leaseTtlMs < MIN_CONFIGURED_LEASE_TTL_MS ||\n limits.leaseTtlMs > MAX_CONFIGURED_LEASE_TTL_MS\n ) {\n throw new Error(\n 'vault relay: limits.leaseTtlMs must be between 30 seconds and 1 hour',\n );\n }\n if (limits.maxChunkBytes > MAX_CHUNK_BYTES_CEILING) {\n throw new Error(\n `vault relay: limits.maxChunkBytes may not exceed ${MAX_CHUNK_BYTES_CEILING}`,\n );\n }\n return { quota, retention, limits };\n}\n","/**\n * Primary-writer lease decisions (#4805). The relay maps these results to\n * HTTP; every state change is a single conditional statement in\n * {@link VaultRelayLeaseStore}. Expiry uses the relay clock only.\n */\nimport type { LeaseGrant, VaultRelayLeaseStore } from './lease-store.js';\n\n/** Smallest lease a client may request, in milliseconds. */\nexport const MIN_LEASE_TTL_MS = 30_000;\n\n/** Why a lease or publish request was refused. */\nexport type LeaseRefusal =\n | {\n error: 'must_restore_first';\n headSequence: number;\n latestSequence: number;\n }\n | { error: 'lease_held'; holder: string; expiresAt: number }\n | { error: 'publish_in_progress'; headSequence: number }\n | { error: 'lease_lost' };\n\n/** Public lease state. The fencing token is never part of it. */\nexport interface LeaseStatus {\n holder: string | null;\n expiresAt: number | null;\n headSequence: number;\n latestCommittedSequence: number;\n /** The head's upload never committed; acquire accepts the latest instead. */\n headIsHole: boolean;\n}\n\nexport type LeaseResult =\n | { ok: true; grant: LeaseGrant }\n | { ok: false; refusal: LeaseRefusal };\n\nexport class LeaseService {\n private readonly store: VaultRelayLeaseStore;\n private readonly ttlMs: number;\n\n constructor(store: VaultRelayLeaseStore, ttlMs: number) {\n this.store = store;\n this.ttlMs = ttlMs;\n }\n\n /** The granted lifetime: the policy TTL, or a shorter one the client asks. */\n private lifetime(requestedMs: number | undefined): number {\n if (requestedMs === undefined) return this.ttlMs;\n return Math.min(this.ttlMs, Math.max(MIN_LEASE_TTL_MS, requestedMs));\n }\n\n async status(accountId: string, now: number): Promise<LeaseStatus> {\n await this.store.ensureLease(accountId);\n const lease = await this.store.getLease(accountId);\n const latest = await this.store.latestCommittedSequence(accountId);\n const head = lease?.headSequence ?? latest;\n const headStatus =\n head === 0\n ? 'committed'\n : await this.store.snapshotStatusAt(accountId, head);\n const live =\n lease?.holderDeviceId !== null &&\n lease?.holderDeviceId !== undefined &&\n lease.expiresAt > now;\n return {\n holder: live ? (lease?.holderDeviceId ?? null) : null,\n expiresAt: live ? (lease?.expiresAt ?? null) : null,\n headSequence: head,\n latestCommittedSequence: latest,\n headIsHole: headStatus === null,\n };\n }\n\n /** Explain a refused acquire or publish from the current row. */\n private async refusal(\n accountId: string,\n deviceId: string,\n now: number,\n ): Promise<LeaseRefusal> {\n const lease = await this.store.getLease(accountId);\n const latest = await this.store.latestCommittedSequence(accountId);\n const head = lease?.headSequence ?? latest;\n if (\n lease?.holderDeviceId &&\n lease.holderDeviceId !== deviceId &&\n lease.expiresAt > now\n ) {\n return {\n error: 'lease_held',\n holder: lease.holderDeviceId,\n expiresAt: lease.expiresAt,\n };\n }\n if ((await this.store.snapshotStatusAt(accountId, head)) === 'pending') {\n return { error: 'publish_in_progress', headSequence: head };\n }\n return {\n error: 'must_restore_first',\n headSequence: head,\n latestSequence: latest,\n };\n }\n\n async acquire(\n accountId: string,\n deviceId: string,\n baseSequence: number,\n requestedTtlMs: number | undefined,\n now: number,\n ): Promise<LeaseResult> {\n await this.store.ensureLease(accountId);\n const grant = await this.store.acquire(\n accountId,\n deviceId,\n baseSequence,\n now,\n now + this.lifetime(requestedTtlMs),\n );\n if (grant) return { ok: true, grant };\n return { ok: false, refusal: await this.refusal(accountId, deviceId, now) };\n }\n\n async renew(\n accountId: string,\n deviceId: string,\n fencingToken: number,\n requestedTtlMs: number | undefined,\n now: number,\n ): Promise<LeaseResult> {\n const grant = await this.store.renew(\n accountId,\n deviceId,\n fencingToken,\n now,\n now + this.lifetime(requestedTtlMs),\n );\n if (grant) return { ok: true, grant };\n return { ok: false, refusal: { error: 'lease_lost' } };\n }\n\n async release(\n accountId: string,\n deviceId: string,\n fencingToken: number,\n ): Promise<void> {\n await this.store.release(accountId, deviceId, fencingToken);\n }\n\n /**\n * Begin-time admission (advisory; the commit-time head advance enforces).\n * `null` admits the upload.\n */\n async admitUpload(\n accountId: string,\n deviceId: string,\n fencingToken: number,\n sequence: number,\n now: number,\n ): Promise<LeaseRefusal | null> {\n await this.store.ensureLease(accountId);\n if (\n await this.store.holds(accountId, deviceId, fencingToken, sequence, now)\n ) {\n return null;\n }\n // A device that does not hold the lease must restore before writing,\n // whoever holds it now (#4805: one structured refusal for publishes).\n return this.mustRestore(accountId);\n }\n\n /** The `must_restore_first` answer for a publish that lost its lease. */\n async mustRestore(accountId: string): Promise<LeaseRefusal> {\n const lease = await this.store.getLease(accountId);\n const latest = await this.store.latestCommittedSequence(accountId);\n return {\n error: 'must_restore_first',\n headSequence: lease?.headSequence ?? latest,\n latestSequence: latest,\n };\n }\n}\n","/**\n * Primary-writer lease (#4805): one row per account naming the device that\n * may publish, a fencing token, and the account's head sequence.\n *\n * `head_sequence` is the sequence the account's data line is at. Only the\n * lease holder advances it (at commit, before the snapshot is published), so\n * holding a current token means the holder's local root is at the head. Every\n * lease decision is one conditional statement on this row, which serializes\n * acquire, renew, release, revoke and the commit-time head advance on SQLite\n * and PostgreSQL alike.\n *\n * A *hole* is a head whose upload never committed (aborted or expired after\n * the head advanced). Committed snapshots at or above the head, and the latest\n * committed snapshot, can never be deleted (see\n * {@link VaultRelayLeaseStore.deleteCommittedBelowHead}), so a missing row at\n * the head is always a hole, and acquire then accepts the latest committed\n * sequence as the base.\n */\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { toSafeInteger } from './encoding.js';\nimport type { SnapshotRecord } from './metadata-store.js';\n\nexport const VAULT_RELAY_LEASE_TABLES = [\n 'vault_relay_leases',\n 'vault_relay_upload_fences',\n] as const;\n\nconst SCHEMA_LEASES_V1 = [\n `CREATE TABLE IF NOT EXISTS vault_relay_leases (\n account_id TEXT PRIMARY KEY,\n holder_device_id TEXT,\n fencing_token BIGINT NOT NULL DEFAULT 0,\n head_sequence BIGINT NOT NULL DEFAULT 0,\n expires_at BIGINT NOT NULL DEFAULT 0,\n acquired_at BIGINT\n )`,\n `CREATE TABLE IF NOT EXISTS vault_relay_upload_fences (\n upload_id TEXT PRIMARY KEY,\n account_id TEXT NOT NULL,\n fencing_token BIGINT NOT NULL\n )`,\n];\n\n/**\n * Create the lease tables. Idempotent; run from the deployment's migration\n * step together with `migrateVaultRelayV1`.\n */\nexport async function migrateVaultRelayLeasesV1(\n db: DatabaseInterface,\n): Promise<void> {\n for (const statement of SCHEMA_LEASES_V1) {\n await db.query(statement);\n }\n}\n\n/** Current lease state of one account. */\nexport interface LeaseRecord {\n accountId: string;\n holderDeviceId: string | null;\n fencingToken: number;\n headSequence: number;\n expiresAt: number;\n}\n\n/** A granted or renewed lease. */\nexport interface LeaseGrant {\n fencingToken: number;\n expiresAt: number;\n headSequence: number;\n}\n\ntype Row = Record<string, unknown>;\n\nfunction leaseFromRow(row: Row): LeaseRecord {\n return {\n accountId: String(row.account_id),\n holderDeviceId:\n row.holder_device_id === null || row.holder_device_id === undefined\n ? null\n : String(row.holder_device_id),\n fencingToken: toSafeInteger(row.fencing_token, 'fencing_token'),\n headSequence: toSafeInteger(row.head_sequence, 'head_sequence'),\n expiresAt: toSafeInteger(row.expires_at, 'expires_at'),\n };\n}\n\nconst HEAD_ROW = `SELECT 1 FROM vault_relay_snapshots s\n WHERE s.account_id = vault_relay_leases.account_id\n AND s.sequence = vault_relay_leases.head_sequence`;\nconst LATEST_COMMITTED = `SELECT COALESCE(MAX(c.sequence), 0)\n FROM vault_relay_snapshots c\n WHERE c.account_id = vault_relay_leases.account_id\n AND c.status = 'committed'`;\n\n/** Typed access to the lease tables. */\nexport class VaultRelayLeaseStore {\n readonly db: DatabaseInterface;\n\n constructor(db: DatabaseInterface) {\n this.db = db;\n }\n\n /**\n * Create the account's lease row if missing, with no holder and the head at\n * the account's published high-water mark (publishing always needs the\n * lease, so no upload can be in flight before the row exists). When the\n * newest published snapshots were deleted before the lease existed, the\n * head is then a hole and acquire accepts the latest committed base.\n */\n async ensureLease(accountId: string): Promise<void> {\n await this.db.query(\n `INSERT INTO vault_relay_leases\n (account_id, holder_device_id, fencing_token, head_sequence, expires_at, acquired_at)\n SELECT ?, NULL, 0,\n COALESCE((SELECT high_water_sequence FROM vault_relay_accounts\n WHERE account_id = ?), 0),\n 0, NULL\n WHERE 1 = 1\n ON CONFLICT (account_id) DO NOTHING`,\n accountId,\n accountId,\n );\n }\n\n async getLease(accountId: string): Promise<LeaseRecord | null> {\n const found = await this.db.query(\n `SELECT account_id, holder_device_id, fencing_token, head_sequence, expires_at\n FROM vault_relay_leases WHERE account_id = ?`,\n accountId,\n );\n return found.rows[0] ? leaseFromRow(found.rows[0]) : null;\n }\n\n /** Latest committed sequence of the account (0 when none). */\n async latestCommittedSequence(accountId: string): Promise<number> {\n const found = await this.db.query(\n `SELECT COALESCE(MAX(sequence), 0) AS latest FROM vault_relay_snapshots\n WHERE account_id = ? AND status = 'committed'`,\n accountId,\n );\n return toSafeInteger(found.rows[0]?.latest ?? 0, 'latest');\n }\n\n /** Status of the snapshot row at `sequence`, or `null` when none exists. */\n async snapshotStatusAt(\n accountId: string,\n sequence: number,\n ): Promise<SnapshotRecord['status'] | null> {\n const found = await this.db.query(\n 'SELECT status FROM vault_relay_snapshots WHERE account_id = ? AND sequence = ?',\n accountId,\n sequence,\n );\n const status = found.rows[0]?.status;\n if (status === undefined) return null;\n return status === 'committed' ? 'committed' : 'pending';\n }\n\n /**\n * Grant the lease to `deviceId`, in one statement, when it is free, expired\n * or already this device's, and the device's `baseSequence` is the head:\n * either the head itself with no publish in flight, or, for a hole, the\n * latest committed sequence. Every grant increments the fencing token, so a\n * re-acquire also fences an earlier process on the same device.\n */\n async acquire(\n accountId: string,\n deviceId: string,\n baseSequence: number,\n now: number,\n expiresAt: number,\n ): Promise<LeaseGrant | null> {\n const updated = await this.db.query(\n `UPDATE vault_relay_leases\n SET holder_device_id = ?, fencing_token = fencing_token + 1,\n expires_at = ?, acquired_at = ?\n WHERE account_id = ?\n AND (holder_device_id IS NULL OR holder_device_id = ? OR expires_at <= ?)\n AND EXISTS (SELECT 1 FROM vault_relay_devices d\n WHERE d.account_id = vault_relay_leases.account_id\n AND d.device_id = ? AND d.status = 'active')\n AND (\n (head_sequence = ?\n AND NOT EXISTS (${HEAD_ROW} AND s.status = 'pending'))\n OR\n (NOT EXISTS (${HEAD_ROW})\n AND ? = (${LATEST_COMMITTED}))\n )\n RETURNING fencing_token, expires_at, head_sequence`,\n deviceId,\n expiresAt,\n now,\n accountId,\n deviceId,\n now,\n deviceId,\n baseSequence,\n baseSequence,\n );\n const row = updated.rows[0];\n if (!row) return null;\n return {\n fencingToken: toSafeInteger(row.fencing_token, 'fencing_token'),\n expiresAt: toSafeInteger(row.expires_at, 'expires_at'),\n headSequence: toSafeInteger(row.head_sequence, 'head_sequence'),\n };\n }\n\n /** Extend an unexpired lease held by this device with this exact token. */\n async renew(\n accountId: string,\n deviceId: string,\n fencingToken: number,\n now: number,\n expiresAt: number,\n ): Promise<LeaseGrant | null> {\n const updated = await this.db.query(\n `UPDATE vault_relay_leases SET expires_at = ?\n WHERE account_id = ? AND holder_device_id = ? AND fencing_token = ?\n AND expires_at > ?\n RETURNING fencing_token, expires_at, head_sequence`,\n expiresAt,\n accountId,\n deviceId,\n fencingToken,\n now,\n );\n const row = updated.rows[0];\n if (!row) return null;\n return {\n fencingToken: toSafeInteger(row.fencing_token, 'fencing_token'),\n expiresAt: toSafeInteger(row.expires_at, 'expires_at'),\n headSequence: toSafeInteger(row.head_sequence, 'head_sequence'),\n };\n }\n\n /** Give up the lease; only the holder with the current token can. */\n async release(\n accountId: string,\n deviceId: string,\n fencingToken: number,\n ): Promise<boolean> {\n const updated = await this.db.query(\n `UPDATE vault_relay_leases SET holder_device_id = NULL, expires_at = 0\n WHERE account_id = ? AND holder_device_id = ? AND fencing_token = ?\n RETURNING account_id`,\n accountId,\n deviceId,\n fencingToken,\n );\n return updated.rows.length === 1;\n }\n\n /**\n * Clear a lease held by a revoked device and bump the token, so nothing\n * recorded under the old token can publish. Run after the revocation.\n */\n async clearHolder(accountId: string, deviceId: string): Promise<void> {\n await this.db.query(\n `UPDATE vault_relay_leases\n SET holder_device_id = NULL, expires_at = 0,\n fencing_token = fencing_token + 1\n WHERE account_id = ? AND holder_device_id = ?`,\n accountId,\n deviceId,\n );\n }\n\n /**\n * Advisory begin-time check: this device holds an unexpired lease with this\n * token and `sequence` is above the head. Begin is several statements, so\n * only {@link advanceHead} at commit enforces the lease.\n */\n async holds(\n accountId: string,\n deviceId: string,\n fencingToken: number,\n sequence: number,\n now: number,\n ): Promise<boolean> {\n const found = await this.db.query(\n `SELECT 1 AS ok FROM vault_relay_leases\n WHERE account_id = ? AND holder_device_id = ? AND fencing_token = ?\n AND expires_at > ? AND head_sequence < ?`,\n accountId,\n deviceId,\n fencingToken,\n now,\n sequence,\n );\n return found.rows.length === 1;\n }\n\n /**\n * Move the head to `sequence` for a pending upload, in one statement: only\n * the holder with the token recorded at begin, only while the upload is\n * still pending, and only forward under an unexpired lease. A head already\n * at `sequence` (a commit retried after the relay failed between the head\n * advance and the publish) is accepted without the expiry check: nobody\n * else can have acquired while that upload is pending at the head.\n */\n async advanceHead(\n accountId: string,\n deviceId: string,\n uploadId: string,\n fencingToken: number,\n sequence: number,\n now: number,\n ): Promise<boolean> {\n const updated = await this.db.query(\n `UPDATE vault_relay_leases SET head_sequence = ?\n WHERE account_id = ? AND holder_device_id = ? AND fencing_token = ?\n AND EXISTS (SELECT 1 FROM vault_relay_snapshots\n WHERE account_id = ? AND upload_id = ?\n AND sequence = ? AND status = 'pending')\n AND ((expires_at > ? AND head_sequence < ?) OR head_sequence = ?)\n RETURNING head_sequence`,\n sequence,\n accountId,\n deviceId,\n fencingToken,\n accountId,\n uploadId,\n sequence,\n now,\n sequence,\n sequence,\n );\n return updated.rows.length === 1;\n }\n\n // Upload fences ----------------------------------------------------------\n\n async recordFence(\n accountId: string,\n uploadId: string,\n fencingToken: number,\n ): Promise<void> {\n await this.db.query(\n `INSERT INTO vault_relay_upload_fences (upload_id, account_id, fencing_token)\n VALUES (?, ?, ?)`,\n uploadId,\n accountId,\n fencingToken,\n );\n }\n\n async getFence(accountId: string, uploadId: string): Promise<number | null> {\n const found = await this.db.query(\n `SELECT fencing_token FROM vault_relay_upload_fences\n WHERE account_id = ? AND upload_id = ?`,\n accountId,\n uploadId,\n );\n const row = found.rows[0];\n return row ? toSafeInteger(row.fencing_token, 'fencing_token') : null;\n }\n\n async deleteFence(uploadId: string): Promise<void> {\n await this.db.query(\n 'DELETE FROM vault_relay_upload_fences WHERE upload_id = ?',\n uploadId,\n );\n }\n\n /**\n * Operator reset of the account's high-water mark (the one way the head\n * moves back): the head becomes the latest committed sequence that remains\n * and the holder is cleared with a bumped token, so nothing recorded under\n * the old position can publish and the next acquire starts from the\n * restored head.\n */\n async resetHead(accountId: string): Promise<void> {\n await this.db.query(\n `UPDATE vault_relay_leases\n SET head_sequence = COALESCE((SELECT MAX(sequence)\n FROM vault_relay_snapshots\n WHERE account_id = ?\n AND status = 'committed'), 0),\n holder_device_id = NULL, expires_at = 0,\n fencing_token = fencing_token + 1\n WHERE account_id = ?`,\n accountId,\n accountId,\n );\n }\n\n /**\n * Delete a committed snapshot only when it is below the head and below the\n * latest committed snapshot, in one statement. The head never moves back,\n * so a stale read can only refuse more. Returns the row when removed.\n */\n async deleteCommittedBelowHead(\n accountId: string,\n uploadId: string,\n ): Promise<SnapshotRecord | null> {\n const deleted = await this.db.query(\n `DELETE FROM vault_relay_snapshots\n WHERE account_id = ? AND upload_id = ? AND status = 'committed'\n AND sequence < (SELECT head_sequence FROM vault_relay_leases\n WHERE account_id = ?)\n AND sequence < (SELECT MAX(sequence) FROM vault_relay_snapshots\n WHERE account_id = ? AND status = 'committed')\n RETURNING account_id, sequence, upload_id, device_id, status, byte_size,\n chunk_size, chunk_count, sha256, created_at, committed_at`,\n accountId,\n uploadId,\n accountId,\n accountId,\n );\n const row = deleted.rows[0];\n if (!row) return null;\n return {\n accountId: String(row.account_id),\n sequence: toSafeInteger(row.sequence, 'sequence'),\n uploadId: String(row.upload_id),\n deviceId: String(row.device_id),\n status: 'committed',\n byteSize: toSafeInteger(row.byte_size, 'byte_size'),\n chunkSize: toSafeInteger(row.chunk_size, 'chunk_size'),\n chunkCount: toSafeInteger(row.chunk_count, 'chunk_count'),\n sha256: String(row.sha256),\n createdAt: toSafeInteger(row.created_at, 'created_at'),\n committedAt:\n row.committed_at === null || row.committed_at === undefined\n ? null\n : toSafeInteger(row.committed_at, 'committed_at'),\n };\n }\n}\n","/**\n * Relay metadata in the service database: accounts (sequence high-water mark\n * and quota counters), registered device keys, consumed request nonces,\n * snapshot rows, and per-chunk rows. Content is never stored here, only\n * sizes, dates, sequences, and ciphertext SHA-256 digests.\n *\n * Every state change that guards a security property is one conditional\n * statement, so it holds on SQLite and PostgreSQL without an explicit\n * transaction: quota reservation (`used + n <= max`), sequence advance\n * (`high_water <= sequence`), publish (`status = 'pending'`), and nonce\n * consumption (primary-key insert). Counter updates that follow a delete can\n * be lost on a crash; they only ever over-count, which denies rather than\n * grants, and {@link VaultRelayStore.reconcileUsage} repairs them.\n */\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { toSafeInteger } from './encoding.js';\n\nexport const VAULT_RELAY_TABLES = [\n 'vault_relay_accounts',\n 'vault_relay_devices',\n 'vault_relay_nonces',\n 'vault_relay_snapshots',\n 'vault_relay_chunks',\n 'vault_relay_supersessions',\n 'vault_relay_lapses',\n 'vault_relay_audit',\n] as const;\n\nconst SCHEMA_V1 = [\n `CREATE TABLE IF NOT EXISTS vault_relay_accounts (\n account_id TEXT PRIMARY KEY,\n high_water_sequence BIGINT NOT NULL DEFAULT 0,\n used_bytes BIGINT NOT NULL DEFAULT 0,\n used_snapshots BIGINT NOT NULL DEFAULT 0,\n created_at BIGINT NOT NULL\n )`,\n `CREATE TABLE IF NOT EXISTS vault_relay_devices (\n account_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n public_key TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('active', 'revoked')),\n registered_at BIGINT NOT NULL,\n revoked_at BIGINT,\n PRIMARY KEY (account_id, device_id)\n )`,\n `CREATE TABLE IF NOT EXISTS vault_relay_nonces (\n account_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n nonce TEXT NOT NULL,\n expires_at BIGINT NOT NULL,\n PRIMARY KEY (account_id, device_id, nonce)\n )`,\n `CREATE INDEX IF NOT EXISTS vault_relay_nonces_expiry\n ON vault_relay_nonces (expires_at)`,\n `CREATE TABLE IF NOT EXISTS vault_relay_snapshots (\n account_id TEXT NOT NULL,\n sequence BIGINT NOT NULL CHECK (sequence > 0),\n upload_id TEXT NOT NULL UNIQUE,\n device_id TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('pending', 'committed')),\n byte_size BIGINT NOT NULL CHECK (byte_size > 0),\n chunk_size BIGINT NOT NULL CHECK (chunk_size > 0),\n chunk_count INTEGER NOT NULL CHECK (chunk_count > 0),\n sha256 TEXT NOT NULL,\n created_at BIGINT NOT NULL,\n committed_at BIGINT,\n PRIMARY KEY (account_id, sequence)\n )`,\n `CREATE INDEX IF NOT EXISTS vault_relay_snapshots_pending\n ON vault_relay_snapshots (status, created_at)`,\n `CREATE TABLE IF NOT EXISTS vault_relay_chunks (\n upload_id TEXT NOT NULL,\n chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),\n byte_size BIGINT NOT NULL CHECK (byte_size > 0),\n sha256 TEXT NOT NULL,\n object_id TEXT NOT NULL,\n PRIMARY KEY (upload_id, chunk_index)\n )`,\n `CREATE TABLE IF NOT EXISTS vault_relay_supersessions (\n account_id TEXT PRIMARY KEY,\n superseded_by TEXT NOT NULL,\n superseded_at BIGINT NOT NULL\n )`,\n // Lapse bookkeeping (#4819). New tables rather than a new column on\n // vault_relay_accounts, so the migration is a plain CREATE IF NOT EXISTS on\n // SQLite and PostgreSQL and needs no ALTER on a live table.\n `CREATE TABLE IF NOT EXISTS vault_relay_lapses (\n account_id TEXT PRIMARY KEY,\n lapsed_at BIGINT NOT NULL,\n swept_at BIGINT\n )`,\n `CREATE INDEX IF NOT EXISTS vault_relay_lapses_due\n ON vault_relay_lapses (swept_at, lapsed_at)`,\n // Append-only operator audit trail. Code only ever INSERTs into it.\n `CREATE TABLE IF NOT EXISTS vault_relay_audit (\n audit_id TEXT PRIMARY KEY,\n occurred_at BIGINT NOT NULL,\n action TEXT NOT NULL,\n operator TEXT NOT NULL,\n account_handle TEXT NOT NULL,\n snapshots BIGINT NOT NULL DEFAULT 0,\n bytes BIGINT NOT NULL DEFAULT 0,\n detail TEXT\n )`,\n `CREATE INDEX IF NOT EXISTS vault_relay_audit_at\n ON vault_relay_audit (occurred_at)`,\n];\n\n/**\n * Create the relay tables. Idempotent (`IF NOT EXISTS`); run it from the\n * deployment's migration step, never from request handling. Works on SQLite\n * and PostgreSQL.\n */\nexport async function migrateVaultRelayV1(\n db: DatabaseInterface,\n): Promise<void> {\n for (const statement of SCHEMA_V1) {\n await db.query(statement);\n }\n}\n\nexport type DeviceStatus = 'active' | 'revoked';\n\nexport interface DeviceRecord {\n accountId: string;\n deviceId: string;\n /** Raw Ed25519 public key, base64url. */\n publicKey: string;\n status: DeviceStatus;\n registeredAt: number;\n revokedAt: number | null;\n}\n\nexport type SnapshotStatus = 'pending' | 'committed';\n\nexport interface SnapshotRecord {\n accountId: string;\n sequence: number;\n uploadId: string;\n deviceId: string;\n status: SnapshotStatus;\n byteSize: number;\n /** Size of every chunk but the last, which holds the remainder. */\n chunkSize: number;\n chunkCount: number;\n sha256: string;\n createdAt: number;\n committedAt: number | null;\n}\n\nexport interface ChunkRecord {\n index: number;\n byteSize: number;\n sha256: string;\n /** Random id of the stored object attempt this row points at. */\n objectId: string;\n}\n\nexport interface AccountUsage {\n accountId: string;\n highWaterSequence: number;\n usedBytes: number;\n usedSnapshots: number;\n}\n\nexport type RegisterDeviceResult = 'registered' | 'unchanged' | 'conflict';\n\n/** An account the account layer replaced with a new one (#4817). */\nexport interface SupersessionRecord {\n accountId: string;\n supersededBy: string;\n supersededAt: number;\n}\n\n/**\n * When the relay first observed an account's `backup.vault` entitlement as\n * lapsed (#4819); `sweptAt` is set once the operator sweep deleted its data.\n */\nexport interface LapseRecord {\n accountId: string;\n lapsedAt: number;\n sweptAt: number | null;\n}\n\n/** One append-only operator audit record. */\nexport interface AuditEntry {\n id: string;\n at: number;\n action: string;\n operator: string;\n /** Hashed account handle, never the account id. */\n accountHandle: string;\n snapshots: number;\n bytes: number;\n detail: string | null;\n}\n\ntype Row = Record<string, unknown>;\n\nfunction lapseFromRow(row: Row): LapseRecord {\n return {\n accountId: String(row.account_id),\n lapsedAt: toSafeInteger(row.lapsed_at, 'lapsed_at'),\n sweptAt:\n row.swept_at === null || row.swept_at === undefined\n ? null\n : toSafeInteger(row.swept_at, 'swept_at'),\n };\n}\n\nfunction deviceFromRow(row: Row): DeviceRecord {\n return {\n accountId: String(row.account_id),\n deviceId: String(row.device_id),\n publicKey: String(row.public_key),\n status: row.status === 'active' ? 'active' : 'revoked',\n registeredAt: toSafeInteger(row.registered_at, 'registered_at'),\n revokedAt:\n row.revoked_at === null || row.revoked_at === undefined\n ? null\n : toSafeInteger(row.revoked_at, 'revoked_at'),\n };\n}\n\nfunction snapshotFromRow(row: Row): SnapshotRecord {\n return {\n accountId: String(row.account_id),\n sequence: toSafeInteger(row.sequence, 'sequence'),\n uploadId: String(row.upload_id),\n deviceId: String(row.device_id),\n status: row.status === 'committed' ? 'committed' : 'pending',\n byteSize: toSafeInteger(row.byte_size, 'byte_size'),\n chunkSize: toSafeInteger(row.chunk_size, 'chunk_size'),\n chunkCount: toSafeInteger(row.chunk_count, 'chunk_count'),\n sha256: String(row.sha256),\n createdAt: toSafeInteger(row.created_at, 'created_at'),\n committedAt:\n row.committed_at === null || row.committed_at === undefined\n ? null\n : toSafeInteger(row.committed_at, 'committed_at'),\n };\n}\n\nfunction chunkFromRow(row: Row): ChunkRecord {\n return {\n index: toSafeInteger(row.chunk_index, 'chunk_index'),\n byteSize: toSafeInteger(row.byte_size, 'byte_size'),\n sha256: String(row.sha256),\n objectId: String(row.object_id),\n };\n}\n\nconst SNAPSHOT_COLUMNS =\n 'account_id, sequence, upload_id, device_id, status, byte_size, chunk_size, chunk_count, sha256, created_at, committed_at';\n\n/** Typed access to the relay tables. */\nexport class VaultRelayStore {\n readonly db: DatabaseInterface;\n\n constructor(db: DatabaseInterface) {\n this.db = db;\n }\n\n /** Names of relay tables that do not exist (empty when migrated). */\n async missingTables(): Promise<string[]> {\n const missing: string[] = [];\n for (const table of VAULT_RELAY_TABLES) {\n if (!(await this.db.tableExists(table))) missing.push(table);\n }\n return missing;\n }\n\n async ensureAccount(accountId: string, now: number): Promise<void> {\n await this.db.query(\n `INSERT INTO vault_relay_accounts\n (account_id, high_water_sequence, used_bytes, used_snapshots, created_at)\n VALUES (?, 0, 0, 0, ?)\n ON CONFLICT (account_id) DO NOTHING`,\n accountId,\n now,\n );\n }\n\n async getUsage(accountId: string): Promise<AccountUsage | null> {\n const found = await this.db.query(\n `SELECT account_id, high_water_sequence, used_bytes, used_snapshots\n FROM vault_relay_accounts WHERE account_id = ?`,\n accountId,\n );\n const row = found.rows[0];\n if (!row) return null;\n return {\n accountId: String(row.account_id),\n highWaterSequence: toSafeInteger(\n row.high_water_sequence,\n 'high_water_sequence',\n ),\n usedBytes: toSafeInteger(row.used_bytes, 'used_bytes'),\n usedSnapshots: toSafeInteger(row.used_snapshots, 'used_snapshots'),\n };\n }\n\n // Devices -------------------------------------------------------------\n\n async registerDevice(\n accountId: string,\n deviceId: string,\n publicKey: string,\n now: number,\n ): Promise<RegisterDeviceResult> {\n const inserted = await this.db.query(\n `INSERT INTO vault_relay_devices\n (account_id, device_id, public_key, status, registered_at, revoked_at)\n VALUES (?, ?, ?, 'active', ?, NULL)\n ON CONFLICT (account_id, device_id) DO NOTHING\n RETURNING device_id`,\n accountId,\n deviceId,\n publicKey,\n now,\n );\n if (inserted.rows.length === 1) return 'registered';\n const existing = await this.getDevice(accountId, deviceId);\n // A device id is never reused: a revoked id, or the same id with a\n // different key, is a conflict, not a silent re-activation.\n return existing?.status === 'active' && existing.publicKey === publicKey\n ? 'unchanged'\n : 'conflict';\n }\n\n async revokeDevice(\n accountId: string,\n deviceId: string,\n now: number,\n ): Promise<boolean> {\n const updated = await this.db.query(\n `UPDATE vault_relay_devices SET status = 'revoked', revoked_at = ?\n WHERE account_id = ? AND device_id = ? AND status = 'active'\n RETURNING device_id`,\n now,\n accountId,\n deviceId,\n );\n return updated.rows.length === 1;\n }\n\n async getDevice(\n accountId: string,\n deviceId: string,\n ): Promise<DeviceRecord | null> {\n const found = await this.db.query(\n `SELECT account_id, device_id, public_key, status, registered_at, revoked_at\n FROM vault_relay_devices WHERE account_id = ? AND device_id = ?`,\n accountId,\n deviceId,\n );\n return found.rows[0] ? deviceFromRow(found.rows[0]) : null;\n }\n\n async listDevices(accountId: string): Promise<DeviceRecord[]> {\n const found = await this.db.query(\n `SELECT account_id, device_id, public_key, status, registered_at, revoked_at\n FROM vault_relay_devices WHERE account_id = ? ORDER BY registered_at, device_id`,\n accountId,\n );\n return found.rows.map(deviceFromRow);\n }\n\n // Supersession -----------------------------------------------------------\n\n async getSupersession(accountId: string): Promise<SupersessionRecord | null> {\n const found = await this.db.query(\n `SELECT account_id, superseded_by, superseded_at\n FROM vault_relay_supersessions WHERE account_id = ?`,\n accountId,\n );\n const row = found.rows[0];\n return row\n ? {\n accountId: String(row.account_id),\n supersededBy: String(row.superseded_by),\n supersededAt: toSafeInteger(row.superseded_at, 'superseded_at'),\n }\n : null;\n }\n\n /**\n * Record that `accountId` is replaced by `supersededBy`. One conditional\n * insert: an existing record for the same target is `unchanged`, for\n * another target a `conflict`; it is never overwritten.\n */\n async setSupersession(\n accountId: string,\n supersededBy: string,\n now: number,\n ): Promise<'superseded' | 'unchanged' | 'conflict'> {\n const inserted = await this.db.query(\n `INSERT INTO vault_relay_supersessions\n (account_id, superseded_by, superseded_at)\n VALUES (?, ?, ?)\n ON CONFLICT (account_id) DO NOTHING\n RETURNING account_id`,\n accountId,\n supersededBy,\n now,\n );\n if (inserted.rows.length === 1) return 'superseded';\n const existing = await this.getSupersession(accountId);\n return existing?.supersededBy === supersededBy ? 'unchanged' : 'conflict';\n }\n\n /** True when some account was replaced by `accountId`. */\n async isSupersessionTarget(accountId: string): Promise<boolean> {\n const found = await this.db.query(\n `SELECT account_id FROM vault_relay_supersessions\n WHERE superseded_by = ? LIMIT 1`,\n accountId,\n );\n return found.rows.length > 0;\n }\n\n async clearSupersession(accountId: string): Promise<boolean> {\n const removed = await this.db.query(\n `DELETE FROM vault_relay_supersessions WHERE account_id = ?\n RETURNING account_id`,\n accountId,\n );\n return removed.rows.length === 1;\n }\n\n async countActiveDevices(accountId: string): Promise<number> {\n const found = await this.db.query(\n `SELECT COUNT(*) AS active FROM vault_relay_devices\n WHERE account_id = ? AND status = 'active'`,\n accountId,\n );\n return toSafeInteger(found.rows[0]?.active ?? 0, 'active');\n }\n\n // Lapse and audit (#4819) -------------------------------------------------\n\n async getLapse(accountId: string): Promise<LapseRecord | null> {\n const found = await this.db.query(\n `SELECT account_id, lapsed_at, swept_at\n FROM vault_relay_lapses WHERE account_id = ?`,\n accountId,\n );\n return found.rows[0] ? lapseFromRow(found.rows[0]) : null;\n }\n\n /**\n * Record the first observation of a lapse. One conditional insert: a lapse\n * already recorded keeps its original time, so the window never slides.\n */\n async recordLapse(accountId: string, now: number): Promise<LapseRecord> {\n await this.db.query(\n `INSERT INTO vault_relay_lapses (account_id, lapsed_at, swept_at)\n VALUES (?, ?, NULL)\n ON CONFLICT (account_id) DO NOTHING`,\n accountId,\n now,\n );\n return (\n (await this.getLapse(accountId)) ?? {\n accountId,\n lapsedAt: now,\n sweptAt: null,\n }\n );\n }\n\n /** Forget a lapse (the entitlement is active again); `true` if one existed. */\n async clearLapse(accountId: string): Promise<boolean> {\n const removed = await this.db.query(\n `DELETE FROM vault_relay_lapses WHERE account_id = ?\n RETURNING account_id`,\n accountId,\n );\n return removed.rows.length === 1;\n }\n\n /** Mark a lapse swept, once; `false` when it was swept or cleared. */\n async markLapseSwept(accountId: string, now: number): Promise<boolean> {\n const updated = await this.db.query(\n `UPDATE vault_relay_lapses SET swept_at = ?\n WHERE account_id = ? AND swept_at IS NULL\n RETURNING account_id`,\n now,\n accountId,\n );\n return updated.rows.length === 1;\n }\n\n /** Unswept lapses recorded at or before `cutoff`, oldest first. */\n async listDueLapses(cutoff: number, limit: number): Promise<LapseRecord[]> {\n const found = await this.db.query(\n `SELECT account_id, lapsed_at, swept_at FROM vault_relay_lapses\n WHERE swept_at IS NULL AND lapsed_at <= ?\n ORDER BY lapsed_at, account_id LIMIT ?`,\n cutoff,\n limit,\n );\n return found.rows.map(lapseFromRow);\n }\n\n /** True when the account holds at least one committed snapshot. */\n async hasCommitted(accountId: string): Promise<boolean> {\n const found = await this.db.query(\n `SELECT 1 AS present FROM vault_relay_snapshots\n WHERE account_id = ? AND status = 'committed' LIMIT 1`,\n accountId,\n );\n return found.rows.length > 0;\n }\n\n /**\n * Accounts above `afterAccountId` (ordered) that hold a committed snapshot\n * and have no lapse record: the candidates for the sweep's discovery pass.\n */\n async listUnrecordedAccounts(\n afterAccountId: string,\n limit: number,\n ): Promise<string[]> {\n const found = await this.db.query(\n `SELECT s.account_id FROM vault_relay_snapshots AS s\n WHERE s.status = 'committed' AND s.account_id > ?\n AND NOT EXISTS (\n SELECT 1 FROM vault_relay_lapses AS l\n WHERE l.account_id = s.account_id)\n GROUP BY s.account_id\n ORDER BY s.account_id LIMIT ?`,\n afterAccountId,\n limit,\n );\n return found.rows.map((row) => String(row.account_id));\n }\n\n /** Append an audit record. The audit table is never updated or deleted. */\n async appendAudit(entry: AuditEntry): Promise<void> {\n await this.db.query(\n `INSERT INTO vault_relay_audit\n (audit_id, occurred_at, action, operator, account_handle, snapshots, bytes, detail)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n entry.id,\n entry.at,\n entry.action,\n entry.operator,\n entry.accountHandle,\n entry.snapshots,\n entry.bytes,\n entry.detail,\n );\n }\n\n /** Newest audit records first. */\n async listAudit(limit: number): Promise<AuditEntry[]> {\n const found = await this.db.query(\n `SELECT audit_id, occurred_at, action, operator, account_handle, snapshots, bytes, detail\n FROM vault_relay_audit ORDER BY occurred_at DESC, audit_id LIMIT ?`,\n limit,\n );\n return found.rows.map((row) => ({\n id: String(row.audit_id),\n at: toSafeInteger(row.occurred_at, 'occurred_at'),\n action: String(row.action),\n operator: String(row.operator),\n accountHandle: String(row.account_handle),\n snapshots: toSafeInteger(row.snapshots, 'snapshots'),\n bytes: toSafeInteger(row.bytes, 'bytes'),\n detail:\n row.detail === null || row.detail === undefined\n ? null\n : String(row.detail),\n }));\n }\n\n // Nonces --------------------------------------------------------------\n\n /** Record a nonce; `false` when it was already used (a replay). */\n async consumeNonce(\n accountId: string,\n deviceId: string,\n nonce: string,\n expiresAt: number,\n ): Promise<boolean> {\n const inserted = await this.db.query(\n `INSERT INTO vault_relay_nonces (account_id, device_id, nonce, expires_at)\n VALUES (?, ?, ?, ?)\n ON CONFLICT (account_id, device_id, nonce) DO NOTHING\n RETURNING nonce`,\n accountId,\n deviceId,\n nonce,\n expiresAt,\n );\n return inserted.rows.length === 1;\n }\n\n async pruneNonces(now: number): Promise<void> {\n await this.db.query(\n 'DELETE FROM vault_relay_nonces WHERE expires_at < ?',\n now,\n );\n }\n\n // Quota counters ---------------------------------------------------------\n\n /** Reserve bytes and one snapshot slot; `false` when it would exceed quota. */\n async reserve(\n accountId: string,\n bytes: number,\n maxBytes: number,\n maxSnapshots: number,\n ): Promise<boolean> {\n const updated = await this.db.query(\n `UPDATE vault_relay_accounts\n SET used_bytes = used_bytes + ?, used_snapshots = used_snapshots + 1\n WHERE account_id = ?\n AND used_bytes + ? <= ?\n AND used_snapshots + 1 <= ?\n RETURNING account_id`,\n bytes,\n accountId,\n bytes,\n maxBytes,\n maxSnapshots,\n );\n return updated.rows.length === 1;\n }\n\n async release(accountId: string, bytes: number): Promise<void> {\n await this.db.query(\n `UPDATE vault_relay_accounts\n SET used_bytes = CASE WHEN used_bytes >= ? THEN used_bytes - ? ELSE 0 END,\n used_snapshots = CASE WHEN used_snapshots >= 1 THEN used_snapshots - 1 ELSE 0 END\n WHERE account_id = ?`,\n bytes,\n bytes,\n accountId,\n );\n }\n\n /** Recompute the quota counters from the snapshot rows, in one statement. */\n async reconcileUsage(accountId: string): Promise<void> {\n await this.db.query(\n `UPDATE vault_relay_accounts SET\n used_bytes = (SELECT COALESCE(SUM(byte_size), 0)\n FROM vault_relay_snapshots WHERE account_id = ?),\n used_snapshots = (SELECT COUNT(*)\n FROM vault_relay_snapshots WHERE account_id = ?)\n WHERE account_id = ?`,\n accountId,\n accountId,\n accountId,\n );\n }\n\n // Snapshots --------------------------------------------------------------\n\n /**\n * Insert a pending snapshot. `false` when the sequence already exists or is\n * at or below the account's high-water mark (it was published before, even\n * if since deleted).\n */\n async createPending(record: {\n accountId: string;\n sequence: number;\n uploadId: string;\n deviceId: string;\n byteSize: number;\n chunkSize: number;\n chunkCount: number;\n sha256: string;\n createdAt: number;\n }): Promise<boolean> {\n const inserted = await this.db.query(\n `INSERT INTO vault_relay_snapshots\n (${SNAPSHOT_COLUMNS})\n SELECT ?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?, NULL\n WHERE NOT EXISTS (\n SELECT 1 FROM vault_relay_accounts\n WHERE account_id = ? AND high_water_sequence >= ?)\n ON CONFLICT DO NOTHING\n RETURNING upload_id`,\n record.accountId,\n record.sequence,\n record.uploadId,\n record.deviceId,\n record.byteSize,\n record.chunkSize,\n record.chunkCount,\n record.sha256,\n record.createdAt,\n record.accountId,\n record.sequence,\n );\n return inserted.rows.length === 1;\n }\n\n async getByUpload(\n accountId: string,\n uploadId: string,\n ): Promise<SnapshotRecord | null> {\n const found = await this.db.query(\n `SELECT ${SNAPSHOT_COLUMNS} FROM vault_relay_snapshots\n WHERE account_id = ? AND upload_id = ?`,\n accountId,\n uploadId,\n );\n return found.rows[0] ? snapshotFromRow(found.rows[0]) : null;\n }\n\n async getCommitted(\n accountId: string,\n sequence: number,\n ): Promise<SnapshotRecord | null> {\n const found = await this.db.query(\n `SELECT ${SNAPSHOT_COLUMNS} FROM vault_relay_snapshots\n WHERE account_id = ? AND sequence = ? AND status = 'committed'`,\n accountId,\n sequence,\n );\n return found.rows[0] ? snapshotFromRow(found.rows[0]) : null;\n }\n\n async latestCommitted(accountId: string): Promise<SnapshotRecord | null> {\n const found = await this.db.query(\n `SELECT ${SNAPSHOT_COLUMNS} FROM vault_relay_snapshots\n WHERE account_id = ? AND status = 'committed'\n ORDER BY sequence DESC LIMIT 1`,\n accountId,\n );\n return found.rows[0] ? snapshotFromRow(found.rows[0]) : null;\n }\n\n /** Every snapshot of the account, newest sequence first. */\n async listSnapshots(\n accountId: string,\n status?: SnapshotStatus,\n ): Promise<SnapshotRecord[]> {\n const found = status\n ? await this.db.query(\n `SELECT ${SNAPSHOT_COLUMNS} FROM vault_relay_snapshots\n WHERE account_id = ? AND status = ? ORDER BY sequence DESC`,\n accountId,\n status,\n )\n : await this.db.query(\n `SELECT ${SNAPSHOT_COLUMNS} FROM vault_relay_snapshots\n WHERE account_id = ? ORDER BY sequence DESC`,\n accountId,\n );\n return found.rows.map(snapshotFromRow);\n }\n\n /** Pending uploads created before `cutoff`, across accounts. */\n async stalePending(cutoff: number, limit: number): Promise<SnapshotRecord[]> {\n const found = await this.db.query(\n `SELECT ${SNAPSHOT_COLUMNS} FROM vault_relay_snapshots\n WHERE status = 'pending' AND created_at < ?\n ORDER BY created_at LIMIT ?`,\n cutoff,\n limit,\n );\n return found.rows.map(snapshotFromRow);\n }\n\n /**\n * Raise the account's sequence high-water mark to `sequence`. Fails when a\n * higher sequence is already published, so a stale upload can never become\n * latest and an old sequence can never be republished, and when `sequence`\n * is more than `maxJump` above the mark, so one commit can never push the\n * mark out of reach of every later upload.\n */\n async advanceHighWater(\n accountId: string,\n sequence: number,\n maxJump: number,\n ): Promise<boolean> {\n const updated = await this.db.query(\n `UPDATE vault_relay_accounts SET high_water_sequence = ?\n WHERE account_id = ? AND high_water_sequence <= ?\n AND ? - high_water_sequence <= ?\n RETURNING account_id`,\n sequence,\n accountId,\n sequence,\n sequence,\n maxJump,\n );\n return updated.rows.length === 1;\n }\n\n /**\n * Operator reset: lower the high-water mark to `sequence`, only while the\n * mark is not already below it and no snapshot row (pending or committed)\n * sits above it, so the mark never ends up beneath a stored sequence.\n */\n async resetHighWater(accountId: string, sequence: number): Promise<boolean> {\n const updated = await this.db.query(\n `UPDATE vault_relay_accounts SET high_water_sequence = ?\n WHERE account_id = ? AND high_water_sequence >= ?\n AND NOT EXISTS (\n SELECT 1 FROM vault_relay_snapshots\n WHERE account_id = ? AND sequence > ?)\n RETURNING account_id`,\n sequence,\n accountId,\n sequence,\n accountId,\n sequence,\n );\n return updated.rows.length === 1;\n }\n\n /** Publish a pending upload; `false` when it is not pending any more. */\n async markCommitted(\n accountId: string,\n uploadId: string,\n now: number,\n ): Promise<boolean> {\n const updated = await this.db.query(\n `UPDATE vault_relay_snapshots SET status = 'committed', committed_at = ?\n WHERE account_id = ? AND upload_id = ? AND status = 'pending'\n RETURNING upload_id`,\n now,\n accountId,\n uploadId,\n );\n return updated.rows.length === 1;\n }\n\n /**\n * Delete the snapshot row only while it still has `status`, so removing a\n * pending upload can never delete a snapshot that was published meanwhile.\n * Returns the row when this call removed it.\n */\n async deleteSnapshotRow(\n accountId: string,\n uploadId: string,\n status: SnapshotStatus,\n ): Promise<SnapshotRecord | null> {\n const deleted = await this.db.query(\n `DELETE FROM vault_relay_snapshots\n WHERE account_id = ? AND upload_id = ? AND status = ?\n RETURNING ${SNAPSHOT_COLUMNS}`,\n accountId,\n uploadId,\n status,\n );\n return deleted.rows[0] ? snapshotFromRow(deleted.rows[0]) : null;\n }\n\n /**\n * Delete a committed snapshot row only while another committed snapshot of\n * the account remains, in one statement. Returns the row when this call\n * removed it, `null` when it is gone or is the account's last committed\n * snapshot. Two devices deleting the final two snapshots at the same\n * instant can still both pass on PostgreSQL (each sees the other), which\n * the device API accepts as a residual risk; retention never goes through\n * here and always keeps at least one.\n */\n async deleteCommittedUnlessLast(\n accountId: string,\n uploadId: string,\n ): Promise<SnapshotRecord | null> {\n const deleted = await this.db.query(\n `DELETE FROM vault_relay_snapshots\n WHERE account_id = ? AND upload_id = ? AND status = 'committed'\n AND EXISTS (\n SELECT 1 FROM vault_relay_snapshots AS other\n WHERE other.account_id = ? AND other.status = 'committed'\n AND other.upload_id <> ?)\n RETURNING ${SNAPSHOT_COLUMNS}`,\n accountId,\n uploadId,\n accountId,\n uploadId,\n );\n return deleted.rows[0] ? snapshotFromRow(deleted.rows[0]) : null;\n }\n\n // Chunks -----------------------------------------------------------------\n\n /**\n * Record a stored chunk object, only while its upload is still pending for\n * the account and only if the index has no object yet. Returns `false`\n * otherwise; the caller then removes the object it wrote, so a late write\n * after an abort, expiry, or commit leaves nothing behind.\n */\n async addChunk(\n accountId: string,\n uploadId: string,\n chunk: ChunkRecord,\n ): Promise<boolean> {\n const inserted = await this.db.query(\n `INSERT INTO vault_relay_chunks\n (upload_id, chunk_index, byte_size, sha256, object_id)\n SELECT ?, ?, ?, ?, ?\n WHERE EXISTS (\n SELECT 1 FROM vault_relay_snapshots\n WHERE account_id = ? AND upload_id = ? AND status = 'pending')\n ON CONFLICT (upload_id, chunk_index) DO NOTHING\n RETURNING chunk_index`,\n uploadId,\n chunk.index,\n chunk.byteSize,\n chunk.sha256,\n chunk.objectId,\n accountId,\n uploadId,\n );\n return inserted.rows.length === 1;\n }\n\n async listChunks(uploadId: string): Promise<ChunkRecord[]> {\n const found = await this.db.query(\n `SELECT chunk_index, byte_size, sha256, object_id FROM vault_relay_chunks\n WHERE upload_id = ? ORDER BY chunk_index`,\n uploadId,\n );\n return found.rows.map(chunkFromRow);\n }\n\n async getChunk(uploadId: string, index: number): Promise<ChunkRecord | null> {\n const found = await this.db.query(\n `SELECT chunk_index, byte_size, sha256, object_id FROM vault_relay_chunks\n WHERE upload_id = ? AND chunk_index = ?`,\n uploadId,\n index,\n );\n return found.rows[0] ? chunkFromRow(found.rows[0]) : null;\n }\n\n /** Delete one recorded chunk attempt; `true` when this call removed it. */\n async deleteChunkAttempt(\n uploadId: string,\n index: number,\n objectId: string,\n ): Promise<boolean> {\n const deleted = await this.db.query(\n `DELETE FROM vault_relay_chunks\n WHERE upload_id = ? AND chunk_index = ? AND object_id = ?\n RETURNING chunk_index`,\n uploadId,\n index,\n objectId,\n );\n return deleted.rows.length === 1;\n }\n\n /** Delete every chunk row of an upload; returns the removed rows. */\n async deleteChunks(uploadId: string): Promise<ChunkRecord[]> {\n const deleted = await this.db.query(\n `DELETE FROM vault_relay_chunks WHERE upload_id = ?\n RETURNING chunk_index, byte_size, sha256, object_id`,\n uploadId,\n );\n return deleted.rows.map(chunkFromRow);\n }\n}\n","/**\n * Node `http` adapter for the relay's fetch-style handlers. The request URL is\n * built from the request target on a fixed origin, so the Host header never\n * influences routing or the signed path.\n */\nimport {\n createServer,\n type IncomingMessage,\n type Server,\n type ServerResponse,\n} from 'node:http';\nimport { Readable } from 'node:stream';\n\nexport type FetchHandler = (request: Request) => Promise<Response>;\n\nconst ORIGIN = 'http://vault-relay.invalid';\n\nfunction toRequest(req: IncomingMessage): Request {\n const headers = new Headers();\n for (const [name, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n headers.set(name, Array.isArray(value) ? value.join(', ') : value);\n }\n const method = (req.method ?? 'GET').toUpperCase();\n // Only a request that declares a body gets one: clients send no\n // Content-Length on a bodiless DELETE or POST, and such a request must\n // reach the handler with `body === null`, not as an unsized stream.\n const length = req.headers['content-length'];\n const hasBody =\n method !== 'GET' &&\n method !== 'HEAD' &&\n ((length !== undefined && length !== '0') ||\n req.headers['transfer-encoding'] !== undefined);\n return new Request(`${ORIGIN}${req.url ?? '/'}`, {\n method,\n headers,\n ...(hasBody\n ? {\n body: Readable.toWeb(req) as ReadableStream<Uint8Array>,\n duplex: 'half',\n }\n : {}),\n } as RequestInit);\n}\n\nasync function writeResponse(\n response: Response,\n res: ServerResponse,\n): Promise<void> {\n const headers: Record<string, string> = {};\n response.headers.forEach((value, name) => {\n headers[name] = value;\n });\n const body =\n response.body === null ? null : Buffer.from(await response.arrayBuffer());\n if (body && headers['content-length'] === undefined) {\n headers['content-length'] = String(body.length);\n }\n res.writeHead(response.status, headers);\n res.end(body ?? undefined);\n}\n\nexport interface NodeServerOptions {\n /** Whole-request deadline in milliseconds (slow-body protection). */\n requestTimeoutMs?: number;\n}\n\n/** Create (not start) an HTTP server around a fetch-style handler. */\nexport function createRelayHttpServer(\n handler: FetchHandler,\n options: NodeServerOptions = {},\n): Server {\n const server = createServer(async (req, res) => {\n try {\n const response = await handler(toRequest(req));\n await writeResponse(response, res);\n } catch {\n if (!res.headersSent) {\n res.writeHead(500, { 'content-type': 'application/json' });\n }\n res.end('{\"error\":\"internal_error\"}');\n }\n });\n server.requestTimeout = options.requestTimeoutMs ?? 120_000;\n server.headersTimeout = 30_000;\n return server;\n}\n","/**\n * Ciphertext object storage. The relay stores opaque chunk bytes under keys it\n * derives itself (`v1/<account handle>/<upload id>/<chunk index>.<object id>`,\n * the object id random per write attempt, so no write can replace an object a\n * commit already verified); no client string ever becomes part of a key. {@link assertObjectKey} enforces that\n * shape at the store boundary as a second line of defence against path\n * traversal.\n */\nimport { randomUUID } from 'node:crypto';\nimport {\n mkdir,\n readdir,\n readFile,\n rename,\n rm,\n rmdir,\n writeFile,\n} from 'node:fs/promises';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport type {\n FilesystemInterface,\n GetFilesystemOptions,\n} from '@happyvertical/files';\n\nconst OBJECT_KEY =\n /^v1\\/[0-9a-f]{64}\\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\/(0|[1-9][0-9]{0,5})\\.[0-9a-f]{32}$/;\n/** Build the object key of one stored attempt of one chunk of one upload. */\nexport function chunkObjectKey(\n accountHandle: string,\n uploadId: string,\n index: number,\n objectId: string,\n): string {\n const key = `v1/${accountHandle}/${uploadId}/${index}.${objectId}`;\n assertObjectKey(key);\n return key;\n}\n\n/** Throw unless `key` is a relay-derived chunk key. */\nexport function assertObjectKey(key: string): void {\n if (!OBJECT_KEY.test(key)) {\n throw new Error('vault relay: invalid object key');\n }\n}\n\n/** Storage for opaque ciphertext chunks. */\nexport interface VaultObjectStore {\n /** Store `data` under `key`, replacing any previous object atomically. */\n put(key: string, data: Uint8Array): Promise<void>;\n /** The stored bytes, or `null` when the object does not exist. */\n get(key: string): Promise<Uint8Array | null>;\n /** Remove one object; a missing object is not an error. */\n delete(key: string): Promise<void>;\n /** Readiness probe: resolves when the store is reachable. */\n check(): Promise<void>;\n}\n\n/**\n * Filesystem store for tests and single-node development. Writes go to a\n * temporary sibling and are renamed into place, so a reader never sees a\n * partially written chunk.\n */\nexport class FilesystemObjectStore implements VaultObjectStore {\n private readonly root: string;\n\n constructor(root: string) {\n this.root = resolve(root);\n }\n\n private pathFor(key: string): string {\n assertObjectKey(key);\n const path = resolve(this.root, ...key.split('/'));\n const rel = relative(this.root, path);\n if (rel.startsWith('..') || rel.includes(`..${sep}`) || rel === '') {\n throw new Error('vault relay: object key escapes the store root');\n }\n return path;\n }\n\n async put(key: string, data: Uint8Array): Promise<void> {\n const path = this.pathFor(key);\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n const temp = join(dirname(path), `.tmp-${randomUUID()}`);\n try {\n await writeFile(temp, data, { mode: 0o600, flag: 'wx' });\n await rename(temp, path);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n try {\n return new Uint8Array(await readFile(this.pathFor(key)));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw error;\n }\n }\n\n async delete(key: string): Promise<void> {\n const path = this.pathFor(key);\n await rm(path, { force: true });\n // Remove the upload directory once it is empty; ignore anything else.\n try {\n const dir = dirname(path);\n if ((await readdir(dir)).length === 0) await rmdir(dir);\n } catch {\n // Best effort only.\n }\n }\n\n async check(): Promise<void> {\n await mkdir(this.root, { recursive: true, mode: 0o700 });\n }\n}\n\n/**\n * Adapter over an `@happyvertical/files` filesystem. With the S3 provider it\n * stores chunks in an S3-compatible bucket such as Garage.\n */\nexport class FilesObjectStore implements VaultObjectStore {\n private readonly filesystem: FilesystemInterface;\n private readonly isNotFound: (error: unknown) => boolean;\n\n constructor(\n filesystem: FilesystemInterface,\n isNotFound: (error: unknown) => boolean = defaultIsNotFound,\n ) {\n this.filesystem = filesystem;\n this.isNotFound = isNotFound;\n }\n\n async put(key: string, data: Uint8Array): Promise<void> {\n assertObjectKey(key);\n await this.filesystem.write(key, Buffer.from(data));\n }\n\n async get(key: string): Promise<Uint8Array | null> {\n assertObjectKey(key);\n try {\n const content = await this.filesystem.read(key, { raw: true });\n return typeof content === 'string'\n ? new Uint8Array(Buffer.from(content, 'binary'))\n : new Uint8Array(content);\n } catch (error) {\n if (this.isNotFound(error)) return null;\n throw error;\n }\n }\n\n async delete(key: string): Promise<void> {\n assertObjectKey(key);\n try {\n await this.filesystem.delete(key);\n } catch (error) {\n if (!this.isNotFound(error)) throw error;\n }\n }\n\n async check(): Promise<void> {\n // A lookup of a key that never exists: proves reachability and\n // credentials (a denied request throws) without listing any content.\n await this.filesystem.exists('v1/readiness-probe');\n }\n}\n\nfunction defaultIsNotFound(error: unknown): boolean {\n return error instanceof Error && error.name === 'FileNotFoundError';\n}\n\n/** S3-compatible bucket settings; credentials come from the environment. */\nexport interface S3ObjectStoreOptions {\n bucket: string;\n region: string;\n endpoint: string;\n accessKeyId: string;\n secretAccessKey: string;\n /** Garage needs path-style addressing; defaults to `true`. */\n forcePathStyle?: boolean;\n}\n\n/**\n * Open an S3-compatible store (Garage in deployment). The files SDK is loaded\n * on demand so library consumers that only use the filesystem store never\n * import the AWS client.\n */\nexport async function createS3ObjectStore(\n options: S3ObjectStoreOptions,\n): Promise<FilesObjectStore> {\n const files = await import('@happyvertical/files');\n const settings: GetFilesystemOptions = {\n type: 's3',\n bucket: options.bucket,\n region: options.region,\n endpoint: options.endpoint,\n accessKeyId: options.accessKeyId,\n secretAccessKey: options.secretAccessKey,\n forcePathStyle: options.forcePathStyle ?? true,\n };\n const filesystem = await files.getFilesystem(settings);\n return new FilesObjectStore(\n filesystem,\n (error) => error instanceof files.FileNotFoundError,\n );\n}\n","/**\n * The blind snapshot relay: a per-account, versioned store of encrypted\n * snapshot blobs. It never parses, decrypts, or validates blob content and\n * holds no key material; it sees sizes, dates, sequences, and ciphertext\n * digests only.\n *\n * Two fetch-style handlers:\n * - {@link VaultRelay.handle} serves devices. Every `/v1` route requires a\n * device signature and then the `backup.vault` entitlement.\n * - {@link VaultRelay.handleAdmin} serves the operator and the account layer\n * (bearer token): device registration and revocation, sizes and dates,\n * usage repair, and the expiry sweep. Serve it on a private listener.\n */\nimport {\n createHash,\n randomBytes,\n randomUUID,\n timingSafeEqual,\n} from 'node:crypto';\nimport {\n FEATURE_BACKUP_VAULT,\n type FeatureGrantSource,\n type FeatureResolver,\n FeatureUnavailableError,\n requireFeature,\n} from '@happyvertical/smrt-features';\nimport {\n importDevicePublicKey,\n parseSignatureHeaders,\n verifySignature,\n} from './auth.js';\nimport {\n MAX_CHUNKS_PER_SNAPSHOT,\n MAX_JSON_BODY_BYTES,\n resolvePolicy,\n type VaultRelayPolicy,\n type VaultRelayPolicyInput,\n} from './config.js';\nimport {\n accountHandle,\n EMPTY_SHA256,\n isIdentifier,\n isSha256Hex,\n isUploadId,\n parseCanonicalInteger,\n sha256Hex,\n} from './encoding.js';\nimport { type LeaseRefusal, LeaseService } from './lease.js';\nimport {\n VAULT_RELAY_LEASE_TABLES,\n VaultRelayLeaseStore,\n} from './lease-store.js';\nimport type {\n AccountUsage,\n DeviceRecord,\n LapseRecord,\n SnapshotRecord,\n VaultRelayStore,\n} from './metadata-store.js';\nimport { chunkObjectKey, type VaultObjectStore } from './object-store.js';\n\n/** Structured log sink. Fields never carry blob bytes or secrets. */\nexport interface VaultRelayLogger {\n info(event: string, fields?: Record<string, string | number | boolean>): void;\n warn(event: string, fields?: Record<string, string | number | boolean>): void;\n error(\n event: string,\n fields?: Record<string, string | number | boolean>,\n ): void;\n}\n\n/** JSON-lines logger on stdout/stderr. */\nexport const jsonLineLogger: VaultRelayLogger = {\n info: (event, fields) =>\n process.stdout.write(\n `${JSON.stringify({ level: 'info', event, ...fields })}\\n`,\n ),\n warn: (event, fields) =>\n process.stdout.write(\n `${JSON.stringify({ level: 'warn', event, ...fields })}\\n`,\n ),\n error: (event, fields) =>\n process.stderr.write(\n `${JSON.stringify({ level: 'error', event, ...fields })}\\n`,\n ),\n};\n\n/** How the relay resolves an account's `backup.vault` entitlement. */\nexport interface VaultRelayEntitlements {\n /** Feature resolver over the platform's feature and subscription data. */\n resolver: Pick<FeatureResolver, 'explain' | 'findGrantingPlan'>;\n /**\n * Request-scoped plan grant source (for example a fresh\n * `SubscriptionFeatureSource`). Omitted means the resolver's own source.\n */\n grantSource?: () =>\n | FeatureGrantSource\n | null\n | undefined\n | Promise<FeatureGrantSource | null | undefined>;\n /**\n * Tenant whose entitlements govern the account. Defaults to the account id\n * itself: a relay account is a hosted SMRT tenant.\n */\n tenantForAccount?: (accountId: string) => string;\n}\n\nexport interface VaultRelayOptions {\n store: VaultRelayStore;\n /** Primary-writer lease store; defaults to one over `store.db`. */\n leaseStore?: VaultRelayLeaseStore;\n objects: VaultObjectStore;\n entitlements: VaultRelayEntitlements;\n policy: VaultRelayPolicyInput;\n /**\n * Operator bearer token for {@link VaultRelay.handleAdmin}. Only its hash is\n * retained. Without it every admin route answers 404.\n */\n adminToken?: string;\n logger?: VaultRelayLogger;\n now?: () => number;\n}\n\n/** Operator view of one account: sizes, dates, and device state, no content. */\nexport interface OperatorAccountView {\n usage: AccountUsage | null;\n snapshots: Array<{\n sequence: number;\n status: SnapshotRecord['status'];\n byteSize: number;\n chunkCount: number;\n sha256: string;\n createdAt: string;\n committedAt: string | null;\n }>;\n devices: Array<{\n deviceId: string;\n status: DeviceRecord['status'];\n registeredAt: string;\n revokedAt: string | null;\n }>;\n /** The account that replaced this one (#4817), if the account layer set it. */\n supersededBy: string | null;\n /** When the lapse was first observed (#4819); null while entitled. */\n lapsedAt: string | null;\n /** End of the post-lapse restore window; the sweep may delete after it. */\n lapseRetentionEndsAt: string | null;\n}\n\n/** Options of {@link VaultRelay.sweepLapsedAccounts}. */\nexport interface LapseSweepOptions {\n /** Operator identity recorded in the audit trail (required). */\n operator: string;\n /** Report what would be deleted; change and audit nothing. */\n dryRun?: boolean;\n /** Accounts handled per phase in this run (default 10, at most 100). */\n limit?: number;\n /** `nextCursor` of the previous run, to continue the discovery pass. */\n cursor?: string;\n now?: number;\n}\n\n/** One account a lapse sweep deleted (or, in a dry run, would delete). */\nexport interface LapseSweepAccount {\n /** Hashed handle, never the account id. */\n account: string;\n lapsedAt: string;\n retentionEndedAt: string;\n snapshots: number;\n bytes: number;\n}\n\nexport interface LapseSweepResult {\n dryRun: boolean;\n operator: string;\n /** Accounts newly found lapsed by the discovery pass. */\n discovered: number;\n swept: LapseSweepAccount[];\n skipped: Array<{ account: string; reason: string }>;\n /** Pass as `cursor` to continue the discovery pass; null when finished. */\n nextCursor: string | null;\n /** More accounts were due than `limit`; run again. */\n more: boolean;\n}\n\nclass RelayError extends Error {\n readonly status: number;\n readonly code: string;\n readonly detail: Record<string, unknown> | undefined;\n\n constructor(status: number, code: string, detail?: Record<string, unknown>) {\n super(code);\n this.status = status;\n this.code = code;\n this.detail = detail;\n }\n}\n\nconst NONCE_PRUNE_INTERVAL_MS = 60_000;\nconst SWEEP_BATCH = 100;\nconst DEFAULT_LAPSE_SWEEP_ACCOUNTS = 10;\nconst MAX_LAPSE_SWEEP_ACCOUNTS = 100;\nconst OPERATOR_LABEL = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$/;\n\nfunction json(\n status: number,\n body: unknown,\n headers: Record<string, string> = {},\n): Response {\n return new Response(status === 204 ? null : JSON.stringify(body), {\n status,\n headers: {\n 'content-type': 'application/json',\n 'cache-control': 'no-store',\n ...headers,\n },\n });\n}\n\nfunction errorResponse(error: RelayError): Response {\n return json(error.status, { error: error.code, ...error.detail });\n}\n\n/** Content-Length as a safe integer, `null` when absent, error when bad. */\nfunction declaredLength(request: Request): number | null {\n const header = request.headers.get('content-length');\n if (header === null) return null;\n const parsed = parseCanonicalInteger(header.trim());\n if (parsed === null) throw new RelayError(400, 'invalid_content_length');\n return parsed;\n}\n\n/**\n * Read the request body into one buffer of at most `max` bytes, allocated up\n * front from the declared length. Bodies without a Content-Length, or longer\n * than declared, are refused before anything beyond `max` is buffered.\n */\nasync function readBoundedBody(\n request: Request,\n max: number,\n exact?: number,\n): Promise<Uint8Array> {\n const length = declaredLength(request);\n if (length === null) {\n if (request.body === null) return new Uint8Array(0);\n throw new RelayError(411, 'length_required');\n }\n if (length > max) throw new RelayError(413, 'body_too_large');\n if (exact !== undefined && length !== exact) {\n throw new RelayError(400, 'unexpected_body_length', { expected: exact });\n }\n const buffer = new Uint8Array(length);\n if (request.body === null) {\n if (length !== 0) throw new RelayError(400, 'body_length_mismatch');\n return buffer;\n }\n let offset = 0;\n const reader = request.body.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (offset + value.length > length) {\n throw new RelayError(400, 'body_length_mismatch');\n }\n buffer.set(value, offset);\n offset += value.length;\n }\n } finally {\n reader.releaseLock();\n }\n if (offset !== length) throw new RelayError(400, 'body_length_mismatch');\n return buffer;\n}\n\nfunction parseJsonObject(bytes: Uint8Array): Record<string, unknown> {\n try {\n const value = JSON.parse(Buffer.from(bytes).toString('utf8'));\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n } catch {\n // fall through\n }\n throw new RelayError(400, 'invalid_json');\n}\n\nfunction positiveSafeInteger(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {\n throw new RelayError(400, 'invalid_request', { field });\n }\n return value;\n}\n\nfunction nonNegativeSafeInteger(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new RelayError(400, 'invalid_request', { field });\n }\n return value;\n}\n\n/** Optional `ttlSeconds` of a lease request, in milliseconds. */\nfunction requestedTtlMs(input: Record<string, unknown>): number | undefined {\n if (input.ttlSeconds === undefined) return undefined;\n return positiveSafeInteger(input.ttlSeconds, 'ttlSeconds') * 1000;\n}\n\nfunction refusalError(refusal: LeaseRefusal): RelayError {\n const { error, ...detail } = refusal;\n return new RelayError(409, error, detail);\n}\n\nfunction iso(ms: number): string {\n return new Date(ms).toISOString();\n}\n\nfunction snapshotView(record: SnapshotRecord) {\n return {\n sequence: record.sequence,\n byteSize: record.byteSize,\n chunkSize: record.chunkSize,\n chunkCount: record.chunkCount,\n sha256: record.sha256,\n deviceId: record.deviceId,\n createdAt: iso(record.createdAt),\n committedAt: record.committedAt === null ? null : iso(record.committedAt),\n };\n}\n\nfunction expectedChunkBytes(record: SnapshotRecord, index: number): number {\n return index < record.chunkCount - 1\n ? record.chunkSize\n : record.byteSize - record.chunkSize * (record.chunkCount - 1);\n}\n\ntype DeviceRoute =\n | { name: 'lease-status' }\n | { name: 'lease-acquire' }\n | { name: 'lease-renew' }\n | { name: 'lease-release' }\n | { name: 'list' }\n | { name: 'latest' }\n | { name: 'snapshot'; sequence: number }\n | { name: 'chunk'; sequence: number; index: number }\n | { name: 'begin' }\n | { name: 'upload-chunk'; uploadId: string; index: number }\n | { name: 'commit'; uploadId: string }\n | { name: 'abort'; uploadId: string };\n\nconst SEQUENCE = '(0|[1-9][0-9]{0,15})';\nconst INDEX = '(0|[1-9][0-9]{0,5})';\nconst UPLOAD = '([0-9a-f-]{36})';\n\nconst SNAPSHOT_PATH = new RegExp(`^/v1/snapshots/${SEQUENCE}$`);\nconst SNAPSHOT_CHUNK_PATH = new RegExp(\n `^/v1/snapshots/${SEQUENCE}/chunks/${INDEX}$`,\n);\nconst UPLOAD_CHUNK_PATH = new RegExp(`^/v1/uploads/${UPLOAD}/chunks/${INDEX}$`);\nconst UPLOAD_COMMIT_PATH = new RegExp(`^/v1/uploads/${UPLOAD}/commit$`);\nconst UPLOAD_PATH = new RegExp(`^/v1/uploads/${UPLOAD}$`);\n\nfunction only(\n method: string,\n allowed: readonly string[],\n route: DeviceRoute,\n): DeviceRoute | null {\n return allowed.includes(method) ? route : null;\n}\n\nfunction matchDeviceRoute(method: string, path: string): DeviceRoute | null {\n if (path === '/v1/lease') {\n return only(method, ['GET'], { name: 'lease-status' });\n }\n if (path === '/v1/lease/acquire') {\n return only(method, ['POST'], { name: 'lease-acquire' });\n }\n if (path === '/v1/lease/renew') {\n return only(method, ['POST'], { name: 'lease-renew' });\n }\n if (path === '/v1/lease/release') {\n return only(method, ['POST'], { name: 'lease-release' });\n }\n if (path === '/v1/snapshots') return only(method, ['GET'], { name: 'list' });\n if (path === '/v1/snapshots/latest') {\n return only(method, ['GET'], { name: 'latest' });\n }\n if (path === '/v1/uploads') return only(method, ['POST'], { name: 'begin' });\n\n const snapshot = SNAPSHOT_PATH.exec(path);\n if (snapshot) {\n const sequence = Number(snapshot[1]);\n if (!Number.isSafeInteger(sequence)) return null;\n return only(method, ['GET', 'DELETE'], { name: 'snapshot', sequence });\n }\n const chunk = SNAPSHOT_CHUNK_PATH.exec(path);\n if (chunk) {\n const sequence = Number(chunk[1]);\n if (!Number.isSafeInteger(sequence)) return null;\n return only(method, ['GET'], {\n name: 'chunk',\n sequence,\n index: Number(chunk[2]),\n });\n }\n const uploadChunk = UPLOAD_CHUNK_PATH.exec(path);\n if (uploadChunk) {\n if (!isUploadId(uploadChunk[1])) return null;\n return only(method, ['PUT'], {\n name: 'upload-chunk',\n uploadId: uploadChunk[1],\n index: Number(uploadChunk[2]),\n });\n }\n const commit = UPLOAD_COMMIT_PATH.exec(path);\n if (commit) {\n if (!isUploadId(commit[1])) return null;\n return only(method, ['POST'], { name: 'commit', uploadId: commit[1] });\n }\n const upload = UPLOAD_PATH.exec(path);\n if (upload) {\n if (!isUploadId(upload[1])) return null;\n return only(method, ['DELETE'], { name: 'abort', uploadId: upload[1] });\n }\n return null;\n}\n\n/**\n * Routes that publish or change stored data. A lapsed entitlement refuses\n * only these (#4819); listing, `latest`, downloads, aborting an upload and\n * the lease routes (restore-latest holds the lease while it downloads) stay\n * open for the retention window.\n */\nfunction isWriteRoute(route: DeviceRoute, method: string): boolean {\n return (\n route.name === 'begin' ||\n route.name === 'upload-chunk' ||\n route.name === 'commit' ||\n (route.name === 'snapshot' && method.toUpperCase() === 'DELETE')\n );\n}\n\ninterface AuthenticatedDevice {\n accountId: string;\n deviceId: string;\n handle: string;\n contentSha256: string;\n}\n\nexport class VaultRelay {\n readonly policy: VaultRelayPolicy;\n private readonly store: VaultRelayStore;\n private readonly leaseStore: VaultRelayLeaseStore;\n private readonly leases: LeaseService;\n private readonly objects: VaultObjectStore;\n private readonly entitlements: VaultRelayEntitlements;\n private readonly adminTokenHash: Buffer | null;\n private readonly logger: VaultRelayLogger;\n private readonly now: () => number;\n private lastNoncePrune = 0;\n\n constructor(options: VaultRelayOptions) {\n this.policy = resolvePolicy(options.policy);\n this.store = options.store;\n this.leaseStore =\n options.leaseStore ?? new VaultRelayLeaseStore(options.store.db);\n this.leases = new LeaseService(\n this.leaseStore,\n this.policy.limits.leaseTtlMs,\n );\n this.objects = options.objects;\n this.entitlements = options.entitlements;\n if (options.adminToken !== undefined && options.adminToken.length < 32) {\n throw new Error(\n 'vault relay: the admin token must be at least 32 characters',\n );\n }\n this.adminTokenHash = options.adminToken\n ? createHash('sha256').update(options.adminToken).digest()\n : null;\n this.logger = options.logger ?? jsonLineLogger;\n this.now = options.now ?? Date.now;\n }\n\n // Health ------------------------------------------------------------------\n\n /** Readiness: schema migrated and object store reachable. */\n async ready(): Promise<{ ready: boolean; reason?: string }> {\n try {\n const missing = await this.store.missingTables();\n for (const table of VAULT_RELAY_LEASE_TABLES) {\n if (!(await this.store.db.tableExists(table))) missing.push(table);\n }\n if (missing.length > 0) return { ready: false, reason: 'schema_missing' };\n await this.objects.check();\n return { ready: true };\n } catch (error) {\n this.logger.warn('readiness_failed', {\n error: error instanceof Error ? error.name : 'unknown',\n });\n return { ready: false, reason: 'dependency_unavailable' };\n }\n }\n\n private async health(path: string): Promise<Response | null> {\n if (path === '/healthz') return json(200, { status: 'ok' });\n if (path === '/readyz') {\n const result = await this.ready();\n return json(result.ready ? 200 : 503, {\n status: result.ready ? 'ready' : 'not_ready',\n ...(result.reason ? { reason: result.reason } : {}),\n });\n }\n return null;\n }\n\n // Device API --------------------------------------------------------------\n\n /** Device-facing handler (public listener). */\n async handle(request: Request): Promise<Response> {\n const started = this.now();\n const url = new URL(request.url);\n const method = request.method.toUpperCase();\n let route: DeviceRoute | null = null;\n let handle: string | undefined;\n let response: Response;\n try {\n if (method === 'GET') {\n const health = await this.health(url.pathname);\n if (health) return health;\n }\n route = matchDeviceRoute(method, url.pathname);\n if (!route) throw new RelayError(404, 'not_found');\n const device = await this.authenticate(\n request,\n method,\n `${url.pathname}${url.search}`,\n );\n handle = device.handle;\n await this.refuseSuperseded(route, request.method, device.accountId);\n await this.gateEntitlement(route, request.method, device.accountId);\n response = await this.dispatch(route, request, device);\n } catch (error) {\n response = this.toErrorResponse(error, handle);\n }\n this.logger.info('request', {\n route: route?.name ?? 'unmatched',\n method,\n status: response.status,\n ms: this.now() - started,\n ...(handle ? { account: handle } : {}),\n });\n return response;\n }\n\n private toErrorResponse(error: unknown, handle?: string): Response {\n if (error instanceof RelayError) return errorResponse(error);\n if (error instanceof FeatureUnavailableError) return error.toResponse();\n this.logger.error('request_failed', {\n error: error instanceof Error ? error.name : 'unknown',\n ...(handle ? { account: handle } : {}),\n });\n return json(500, { error: 'internal_error' });\n }\n\n private async authenticate(\n request: Request,\n method: string,\n pathAndQuery: string,\n ): Promise<AuthenticatedDevice> {\n const parsed = parseSignatureHeaders(method, pathAndQuery, request.headers);\n // One answer for every authentication failure: no oracle for which\n // accounts or devices exist, or whether a device was revoked.\n const denied = new RelayError(401, 'unauthorized');\n if (!parsed) throw denied;\n const now = this.now();\n const skew = this.policy.limits.maxClockSkewMs;\n if (Math.abs(now - parsed.fields.timestamp) > skew) throw denied;\n const device = await this.store.getDevice(\n parsed.fields.accountId,\n parsed.fields.deviceId,\n );\n if (device?.status !== 'active') throw denied;\n const key = importDevicePublicKey(device.publicKey);\n if (!key || !verifySignature(parsed, key)) throw denied;\n await this.pruneNoncesIfDue(now);\n const fresh = await this.store.consumeNonce(\n parsed.fields.accountId,\n parsed.fields.deviceId,\n parsed.fields.nonce,\n parsed.fields.timestamp + skew + 1,\n );\n if (!fresh) throw denied;\n return {\n accountId: parsed.fields.accountId,\n deviceId: parsed.fields.deviceId,\n handle: accountHandle(parsed.fields.accountId),\n contentSha256: parsed.fields.contentSha256,\n };\n }\n\n /**\n * An account the account layer replaced (#4817) takes no new writes and\n * offers no snapshot to restore-latest: its devices would publish into a\n * data line nobody follows, and a restore would hand back the old vault.\n * Lease status answers it too: that refusal is how a device proves, before\n * it follows the new account, that the old one was replaced. What only\n * removes state (lease release, aborting an upload) and reads by explicit\n * sequence stay open. The refusal names no other\n * account: the client never follows the relay to a new account.\n */\n private async refuseSuperseded(\n route: DeviceRoute,\n method: string,\n accountId: string,\n ): Promise<void> {\n const open =\n route.name === 'lease-release' ||\n route.name === 'abort' ||\n route.name === 'chunk' ||\n (route.name === 'snapshot' && method.toUpperCase() === 'GET');\n if (open) return;\n if (await this.store.getSupersession(accountId)) {\n throw new RelayError(409, 'account_superseded');\n }\n }\n\n private async pruneNoncesIfDue(now: number): Promise<void> {\n if (now - this.lastNoncePrune < NONCE_PRUNE_INTERVAL_MS) return;\n this.lastNoncePrune = now;\n await this.store.pruneNonces(now);\n }\n\n /**\n * The `backup.vault` check, resolved server-side for the account's tenant:\n * `null` when granted, the structured denial otherwise. A lookup that\n * cannot complete fails closed (`503`).\n */\n private async checkEntitlement(\n accountId: string,\n ): Promise<FeatureUnavailableError | null> {\n const tenantId =\n this.entitlements.tenantForAccount?.(accountId) ?? accountId;\n try {\n const grantSource = this.entitlements.grantSource\n ? await this.entitlements.grantSource()\n : undefined;\n await requireFeature(FEATURE_BACKUP_VAULT, {\n resolver: this.entitlements.resolver,\n tenantId,\n ...(grantSource !== undefined ? { grantSource } : {}),\n });\n return null;\n } catch (error) {\n if (error instanceof FeatureUnavailableError) return error;\n // Fail closed: an entitlement lookup that cannot complete denies.\n this.logger.error('entitlement_check_failed', {\n error: error instanceof Error ? error.name : 'unknown',\n account: accountHandle(accountId),\n });\n throw new RelayError(503, 'entitlement_unavailable');\n }\n }\n\n /**\n * Gate a device route on `backup.vault` (#4819). An entitled account clears\n * any recorded lapse. A denied account that holds committed snapshots is\n * *lapsed*: the relay records when it first saw that, refuses the write\n * routes with `402 entitlement_lapsed`, and keeps the read routes open\n * until the retention window after the lapse has passed, then answers\n * `410 retention_expired`. Any other denial (never entitled, operator\n * disabled) is the original `403`.\n */\n private async gateEntitlement(\n route: DeviceRoute,\n method: string,\n accountId: string,\n ): Promise<void> {\n const denial = await this.checkEntitlement(accountId);\n if (!denial) {\n if (await this.store.getLapse(accountId)) {\n await this.store.clearLapse(accountId);\n this.logger.info('entitlement_restored', {\n account: accountHandle(accountId),\n });\n }\n return;\n }\n const lapse = await this.observeLapse(accountId, denial);\n if (!lapse) throw denial;\n const detail = this.lapseDetail(lapse);\n if (isWriteRoute(route, method)) {\n throw new RelayError(402, 'entitlement_lapsed', detail);\n }\n if (this.now() >= lapse.lapsedAt + this.policy.retention.lapseRetentionMs) {\n throw new RelayError(410, 'retention_expired', detail);\n }\n }\n\n /**\n * The lapse record of a denied account, created on first observation. Only\n * an upgrade-required denial of an account with data counts as a lapse.\n */\n private async observeLapse(\n accountId: string,\n denial: FeatureUnavailableError,\n ): Promise<LapseRecord | null> {\n if (denial.code !== 'feature_upgrade_required') return null;\n const existing = await this.store.getLapse(accountId);\n if (existing) return existing;\n if (!(await this.store.hasCommitted(accountId))) return null;\n const recorded = await this.store.recordLapse(accountId, this.now());\n this.logger.warn('entitlement_lapsed', {\n account: accountHandle(accountId),\n });\n return recorded;\n }\n\n private lapseDetail(lapse: LapseRecord): Record<string, unknown> {\n return {\n lapsedAt: iso(lapse.lapsedAt),\n restoreAvailableUntil: iso(\n lapse.lapsedAt + this.policy.retention.lapseRetentionMs,\n ),\n };\n }\n\n /** Reject a body on a route that takes none, and bind the empty digest. */\n private async requireEmptyBody(\n request: Request,\n device: AuthenticatedDevice,\n ): Promise<void> {\n const body = await readBoundedBody(request, 0);\n if (body.length !== 0) throw new RelayError(400, 'unexpected_body');\n if (device.contentSha256 !== EMPTY_SHA256) {\n throw new RelayError(400, 'content_digest_mismatch');\n }\n }\n\n /** A bounded JSON body whose digest is the signed one. */\n private async readJson(\n request: Request,\n device: AuthenticatedDevice,\n ): Promise<Record<string, unknown>> {\n const body = await readBoundedBody(request, MAX_JSON_BODY_BYTES);\n if (sha256Hex(body) !== device.contentSha256) {\n throw new RelayError(400, 'content_digest_mismatch');\n }\n return parseJsonObject(body);\n }\n\n private async dispatchLease(\n route: DeviceRoute,\n request: Request,\n device: AuthenticatedDevice,\n ): Promise<Response> {\n const now = this.now();\n if (route.name === 'lease-status') {\n await this.requireEmptyBody(request, device);\n const status = await this.leases.status(device.accountId, now);\n return json(200, {\n ...status,\n expiresAt: status.expiresAt === null ? null : iso(status.expiresAt),\n });\n }\n const input = await this.readJson(request, device);\n if (route.name === 'lease-acquire') {\n const result = await this.leases.acquire(\n device.accountId,\n device.deviceId,\n nonNegativeSafeInteger(input.baseSequence, 'baseSequence'),\n requestedTtlMs(input),\n now,\n );\n if (!result.ok) throw refusalError(result.refusal);\n return json(200, {\n fencingToken: result.grant.fencingToken,\n expiresAt: iso(result.grant.expiresAt),\n ttlMs: result.grant.expiresAt - now,\n headSequence: result.grant.headSequence,\n });\n }\n const fencingToken = positiveSafeInteger(\n input.fencingToken,\n 'fencingToken',\n );\n if (route.name === 'lease-renew') {\n const result = await this.leases.renew(\n device.accountId,\n device.deviceId,\n fencingToken,\n requestedTtlMs(input),\n now,\n );\n if (!result.ok) throw refusalError(result.refusal);\n return json(200, {\n fencingToken: result.grant.fencingToken,\n expiresAt: iso(result.grant.expiresAt),\n ttlMs: result.grant.expiresAt - now,\n headSequence: result.grant.headSequence,\n });\n }\n await this.leases.release(device.accountId, device.deviceId, fencingToken);\n return json(204, null);\n }\n\n private async dispatch(\n route: DeviceRoute,\n request: Request,\n device: AuthenticatedDevice,\n ): Promise<Response> {\n switch (route.name) {\n case 'lease-status':\n case 'lease-acquire':\n case 'lease-renew':\n case 'lease-release':\n return this.dispatchLease(route, request, device);\n case 'list': {\n await this.requireEmptyBody(request, device);\n const snapshots = await this.store.listSnapshots(\n device.accountId,\n 'committed',\n );\n return json(200, { snapshots: snapshots.map(snapshotView) });\n }\n case 'latest': {\n await this.requireEmptyBody(request, device);\n const latest = await this.store.latestCommitted(device.accountId);\n if (!latest) throw new RelayError(404, 'no_snapshot');\n return json(200, snapshotView(latest));\n }\n case 'snapshot': {\n await this.requireEmptyBody(request, device);\n const record = await this.store.getCommitted(\n device.accountId,\n route.sequence,\n );\n if (!record) throw new RelayError(404, 'no_snapshot');\n if (request.method.toUpperCase() === 'DELETE') {\n return this.deleteSnapshotForDevice(record, device);\n }\n return json(200, snapshotView(record));\n }\n case 'chunk':\n await this.requireEmptyBody(request, device);\n return this.downloadChunk(device, route.sequence, route.index);\n case 'begin':\n return this.beginUpload(request, device);\n case 'upload-chunk':\n return this.uploadChunk(request, device, route.uploadId, route.index);\n case 'commit':\n await this.requireEmptyBody(request, device);\n return this.commitUpload(device, route.uploadId);\n case 'abort': {\n await this.requireEmptyBody(request, device);\n const record = await this.store.getByUpload(\n device.accountId,\n route.uploadId,\n );\n if (record?.status !== 'pending') {\n throw new RelayError(404, 'no_upload');\n }\n await this.removeSnapshot(record, device.handle, 'pending');\n return json(204, null);\n }\n }\n }\n\n private async beginUpload(\n request: Request,\n device: AuthenticatedDevice,\n ): Promise<Response> {\n const input = await this.readJson(request, device);\n const sequence = positiveSafeInteger(input.sequence, 'sequence');\n const fencingToken = positiveSafeInteger(\n input.fencingToken,\n 'fencingToken',\n );\n const byteSize = positiveSafeInteger(input.byteSize, 'byteSize');\n const chunkSize = positiveSafeInteger(input.chunkSize, 'chunkSize');\n if (!isSha256Hex(input.sha256)) {\n throw new RelayError(400, 'invalid_request', { field: 'sha256' });\n }\n const { quota, limits } = this.policy;\n if (chunkSize > limits.maxChunkBytes) {\n throw new RelayError(413, 'chunk_too_large', {\n maxChunkBytes: limits.maxChunkBytes,\n });\n }\n if (byteSize > quota.maxBytes) {\n throw new RelayError(413, 'quota_exceeded', {\n maxBytes: quota.maxBytes,\n maxSnapshots: quota.maxSnapshots,\n });\n }\n const chunkCount = Math.ceil(byteSize / chunkSize);\n if (chunkCount > MAX_CHUNKS_PER_SNAPSHOT) {\n throw new RelayError(400, 'too_many_chunks');\n }\n\n const now = this.now();\n await this.store.ensureAccount(device.accountId, now);\n await this.sweepExpired(now);\n const usage = await this.store.getUsage(device.accountId);\n if (usage && sequence <= usage.highWaterSequence) {\n throw new RelayError(409, 'stale_sequence', {\n highWaterSequence: usage.highWaterSequence,\n });\n }\n // The device picks the sequence and a commit raises the mark for good, so\n // bound the step before reserving anything.\n this.assertSequenceStep(sequence, usage?.highWaterSequence ?? 0);\n // Divergence detection: only the lease holder, at the head, may publish.\n const refused = await this.leases.admitUpload(\n device.accountId,\n device.deviceId,\n fencingToken,\n sequence,\n now,\n );\n if (refused) throw refusalError(refused);\n // Reserve before inserting, so a failure in between can only over-count.\n const reserved = await this.store.reserve(\n device.accountId,\n byteSize,\n quota.maxBytes,\n quota.maxSnapshots,\n );\n if (!reserved) {\n throw new RelayError(413, 'quota_exceeded', {\n maxBytes: quota.maxBytes,\n maxSnapshots: quota.maxSnapshots,\n });\n }\n const uploadId = randomUUID();\n const created = await this.store.createPending({\n accountId: device.accountId,\n sequence,\n uploadId,\n deviceId: device.deviceId,\n byteSize,\n chunkSize,\n chunkCount,\n sha256: input.sha256,\n createdAt: now,\n });\n if (!created) {\n await this.store.release(device.accountId, byteSize);\n const latest = await this.store.getUsage(device.accountId);\n if (latest && sequence <= latest.highWaterSequence) {\n throw new RelayError(409, 'stale_sequence', {\n highWaterSequence: latest.highWaterSequence,\n });\n }\n throw new RelayError(409, 'sequence_exists');\n }\n await this.leaseStore.recordFence(device.accountId, uploadId, fencingToken);\n return json(201, {\n uploadId,\n sequence,\n byteSize,\n chunkSize,\n chunkCount,\n expiresAt: iso(now + limits.uploadTtlMs),\n });\n }\n\n /**\n * A sequence may not jump more than `maxSequenceJump` above the account's\n * high-water mark. Without the bound, one commit at the largest safe\n * integer would make every later upload `stale_sequence` with no way back\n * short of editing the database.\n */\n private assertSequenceStep(sequence: number, highWater: number): void {\n const { maxSequenceJump } = this.policy.limits;\n if (sequence - highWater > maxSequenceJump) {\n throw new RelayError(400, 'sequence_too_far', {\n highWaterSequence: highWater,\n maxSequenceJump,\n });\n }\n }\n\n private async pendingUpload(\n device: AuthenticatedDevice,\n uploadId: string,\n ): Promise<SnapshotRecord> {\n const record = await this.store.getByUpload(device.accountId, uploadId);\n if (record?.status !== 'pending') {\n throw new RelayError(404, 'no_upload');\n }\n if (this.now() - record.createdAt > this.policy.limits.uploadTtlMs) {\n await this.removeSnapshot(record, device.handle, 'pending');\n throw new RelayError(404, 'no_upload');\n }\n return record;\n }\n\n private async uploadChunk(\n request: Request,\n device: AuthenticatedDevice,\n uploadId: string,\n index: number,\n ): Promise<Response> {\n const record = await this.pendingUpload(device, uploadId);\n if (index >= record.chunkCount) throw new RelayError(404, 'no_chunk');\n const expected = expectedChunkBytes(record, index);\n const body = await readBoundedBody(\n request,\n this.policy.limits.maxChunkBytes,\n expected,\n );\n const digest = sha256Hex(body);\n if (digest !== device.contentSha256) {\n throw new RelayError(400, 'content_digest_mismatch');\n }\n // Each attempt gets its own object; the row insert below decides which\n // attempt counts, and only while the upload is still pending.\n const objectId = randomBytes(16).toString('hex');\n const key = chunkObjectKey(device.handle, record.uploadId, index, objectId);\n await this.objects.put(key, body);\n const added = await this.store.addChunk(device.accountId, record.uploadId, {\n index,\n byteSize: body.length,\n sha256: digest,\n objectId,\n });\n if (added) {\n // On PostgreSQL the insert's pending check takes no lock, so a removal\n // can commit while the insert is in flight and miss this row. Re-check:\n // either the remover saw the row, or this check sees the upload gone\n // and cleans up, so the object is never left outside quota.\n const parent = await this.store.getByUpload(\n device.accountId,\n record.uploadId,\n );\n if (!parent) {\n if (\n await this.store.deleteChunkAttempt(record.uploadId, index, objectId)\n ) {\n await this.deleteObject(key, device.handle);\n }\n throw new RelayError(404, 'no_upload');\n }\n } else {\n await this.deleteObject(key, device.handle);\n const existing = await this.store.getChunk(record.uploadId, index);\n const current = await this.store.getByUpload(\n device.accountId,\n record.uploadId,\n );\n // A retry of the same bytes is idempotent; anything else is refused.\n if (existing?.sha256 !== digest || current?.status !== 'pending') {\n throw new RelayError(\n current?.status === 'pending' ? 409 : 404,\n current?.status === 'pending' ? 'chunk_exists' : 'no_upload',\n );\n }\n }\n return json(200, { index, byteSize: body.length, sha256: digest });\n }\n\n private async commitUpload(\n device: AuthenticatedDevice,\n uploadId: string,\n ): Promise<Response> {\n const record = await this.pendingUpload(device, uploadId);\n const chunks = await this.store.listChunks(record.uploadId);\n const complete =\n chunks.length === record.chunkCount &&\n chunks.every(\n (chunk, position) =>\n chunk.index === position &&\n chunk.byteSize === expectedChunkBytes(record, position),\n );\n if (!complete) throw new RelayError(409, 'incomplete_upload');\n\n // Hash the stored ciphertext, one bounded chunk at a time.\n const whole = createHash('sha256');\n for (const chunk of chunks) {\n const bytes = await this.objects.get(\n chunkObjectKey(\n device.handle,\n record.uploadId,\n chunk.index,\n chunk.objectId,\n ),\n );\n if (!bytes || sha256Hex(bytes) !== chunk.sha256) {\n throw new RelayError(409, 'incomplete_upload');\n }\n whole.update(bytes);\n }\n if (whole.digest('hex') !== record.sha256) {\n throw new RelayError(422, 'snapshot_digest_mismatch');\n }\n\n // Advance the lease head first, conditional on the holder, the token\n // recorded at begin, and the upload still pending. A publish that lost\n // its lease is refused and discarded: the device must restore first.\n const leaseNow = this.now();\n const fence = await this.leaseStore.getFence(\n device.accountId,\n record.uploadId,\n );\n if (leaseNow - record.createdAt > this.policy.limits.uploadTtlMs) {\n await this.removeSnapshot(record, device.handle, 'pending');\n throw new RelayError(404, 'no_upload');\n }\n if (\n fence === null ||\n !(await this.leaseStore.advanceHead(\n device.accountId,\n device.deviceId,\n record.uploadId,\n fence,\n record.sequence,\n leaseNow,\n ))\n ) {\n const refusal = await this.leases.mustRestore(device.accountId);\n await this.removeSnapshot(record, device.handle, 'pending');\n throw refusalError(refusal);\n }\n\n if (\n !(await this.store.advanceHighWater(\n device.accountId,\n record.sequence,\n this.policy.limits.maxSequenceJump,\n ))\n ) {\n await this.removeSnapshot(record, device.handle, 'pending');\n const latest = await this.store.getUsage(device.accountId);\n if (latest && record.sequence > latest.highWaterSequence) {\n this.assertSequenceStep(record.sequence, latest.highWaterSequence);\n }\n throw new RelayError(409, 'stale_sequence');\n }\n const now = this.now();\n if (\n !(await this.store.markCommitted(device.accountId, record.uploadId, now))\n ) {\n throw new RelayError(409, 'no_upload');\n }\n await this.leaseStore.deleteFence(record.uploadId);\n await this.applyRetention(device.accountId, device.handle, now);\n const committed = await this.store.getCommitted(\n device.accountId,\n record.sequence,\n );\n return json(\n 201,\n committed ? snapshotView(committed) : { sequence: record.sequence },\n );\n }\n\n /**\n * Device-initiated delete. The account's last committed snapshot is never\n * removable from the device API: a compromised or mistaken device would\n * otherwise erase the only restorable copy. The refusal and every removal\n * are audited by device and sequence; the operator can still act through\n * the admin listener.\n */\n private async deleteSnapshotForDevice(\n record: SnapshotRecord,\n device: AuthenticatedDevice,\n ): Promise<Response> {\n // Below the head and below the latest committed snapshot only (#4805): the\n // head and the last committed snapshot are never deletable here.\n const removed = await this.leaseStore.deleteCommittedBelowHead(\n record.accountId,\n record.uploadId,\n );\n if (!removed) {\n const stillThere = await this.store.getCommitted(\n record.accountId,\n record.sequence,\n );\n if (!stillThere) throw new RelayError(404, 'no_snapshot');\n // Two refusals, one rule (the snapshot is the latest committed one and\n // the lease head): the account's only committed snapshot is\n // `last_snapshot`; the newest of several is `head_snapshot`. Both are\n // audited, and a device or client can tell them apart.\n const committed = await this.store.listSnapshots(\n record.accountId,\n 'committed',\n );\n const sole = committed.length <= 1;\n this.logger.warn('snapshot_delete_refused', {\n account: device.handle,\n device: device.deviceId,\n sequence: record.sequence,\n reason: sole ? 'last_committed' : 'head',\n });\n throw new RelayError(409, sole ? 'last_snapshot' : 'head_snapshot', {\n sequence: record.sequence,\n });\n }\n await this.discardRemoved(removed, device.handle);\n this.logger.info('snapshot_deleted', {\n account: device.handle,\n device: device.deviceId,\n sequence: removed.sequence,\n });\n return json(204, null);\n }\n\n private async downloadChunk(\n device: AuthenticatedDevice,\n sequence: number,\n index: number,\n ): Promise<Response> {\n const record = await this.store.getCommitted(device.accountId, sequence);\n if (!record) throw new RelayError(404, 'no_snapshot');\n const chunk = await this.store.getChunk(record.uploadId, index);\n if (!chunk) throw new RelayError(404, 'no_chunk');\n const bytes = await this.objects.get(\n chunkObjectKey(device.handle, record.uploadId, index, chunk.objectId),\n );\n if (!bytes || sha256Hex(bytes) !== chunk.sha256) {\n this.logger.error('stored_chunk_unreadable', {\n account: device.handle,\n sequence,\n index,\n });\n throw new RelayError(500, 'storage_integrity');\n }\n return new Response(bytes, {\n status: 200,\n headers: {\n 'content-type': 'application/octet-stream',\n 'content-length': String(bytes.length),\n 'cache-control': 'no-store',\n 'x-vault-chunk-sha256': chunk.sha256,\n },\n });\n }\n\n // Retention and cleanup ----------------------------------------------------\n\n /**\n * Remove a snapshot or upload while it still has `status`: the row first (so\n * it can never be listed or served half-deleted, and a concurrent publish\n * or abort cannot be undone), then counters, then chunk rows and objects.\n */\n private async removeSnapshot(\n record: SnapshotRecord,\n handle: string,\n status: SnapshotRecord['status'],\n ): Promise<boolean> {\n const removed = await this.store.deleteSnapshotRow(\n record.accountId,\n record.uploadId,\n status,\n );\n if (!removed) return false;\n await this.discardRemoved(removed, handle);\n return true;\n }\n\n /** Counters, fence, chunk rows and objects of a snapshot row already deleted. */\n private async discardRemoved(\n removed: SnapshotRecord,\n handle: string,\n ): Promise<void> {\n await this.store.release(removed.accountId, removed.byteSize);\n await this.leaseStore.deleteFence(removed.uploadId);\n const chunks = await this.store.deleteChunks(removed.uploadId);\n for (const chunk of chunks) {\n await this.deleteObject(\n chunkObjectKey(handle, removed.uploadId, chunk.index, chunk.objectId),\n handle,\n );\n }\n }\n\n private async deleteObject(key: string, handle: string): Promise<void> {\n try {\n await this.objects.delete(key);\n } catch (error) {\n this.logger.warn('object_delete_failed', {\n account: handle,\n error: error instanceof Error ? error.name : 'unknown',\n });\n }\n }\n\n /** Keep the newest `keepLast` committed snapshots plus any within the window. */\n private async applyRetention(\n accountId: string,\n handle: string,\n now: number,\n ): Promise<void> {\n const { keepLast, keepWithinMs } = this.policy.retention;\n const committed = await this.store.listSnapshots(accountId, 'committed');\n for (const [position, record] of committed.entries()) {\n if (position < keepLast) continue;\n const age = now - (record.committedAt ?? record.createdAt);\n if (age <= keepWithinMs) continue;\n await this.removeSnapshot(record, handle, 'committed');\n }\n }\n\n /** Abort pending uploads older than the upload TTL; returns how many. */\n async sweepExpired(now: number = this.now()): Promise<number> {\n const stale = await this.store.stalePending(\n now - this.policy.limits.uploadTtlMs,\n SWEEP_BATCH,\n );\n for (const record of stale) {\n await this.removeSnapshot(\n record,\n accountHandle(record.accountId),\n 'pending',\n );\n }\n await this.store.pruneNonces(now);\n return stale.length;\n }\n\n // Lapse sweep (#4819) -----------------------------------------------------\n\n /**\n * Operator sweep of lapsed accounts. Two bounded phases per run:\n *\n * 1. *Discovery* walks accounts that hold committed snapshots but have no\n * lapse record (`cursor`/`nextCursor` resume it) and records those whose\n * entitlement is lapsed, so an account whose devices never call again\n * still starts its window.\n * 2. *Deletion* takes lapses whose window (`lapseRetentionDays` from the\n * first observation) has elapsed, re-checks the entitlement, and deletes\n * the account's snapshots through the normal removal path. An account\n * that is entitled again has its lapse cleared and keeps its data.\n *\n * Every account deleted gets a `lapse_sweep_started` audit record (what is\n * about to go) before anything is removed and a `lapse_sweep_completed`\n * record (what went) after, so a crash leaves the intent on record and the\n * next run finishes the job. A dry run changes and audits nothing.\n */\n async sweepLapsedAccounts(\n options: LapseSweepOptions,\n ): Promise<LapseSweepResult> {\n const operator = options.operator;\n if (\n typeof operator !== 'string' ||\n operator.length < 1 ||\n operator.length > 128\n ) {\n throw new RelayError(400, 'invalid_request', { field: 'operator' });\n }\n const limit = options.limit ?? DEFAULT_LAPSE_SWEEP_ACCOUNTS;\n if (\n !Number.isSafeInteger(limit) ||\n limit < 1 ||\n limit > MAX_LAPSE_SWEEP_ACCOUNTS\n ) {\n throw new RelayError(400, 'invalid_request', { field: 'limit' });\n }\n const cursor = options.cursor ?? '';\n if (cursor !== '' && !isIdentifier(cursor)) {\n throw new RelayError(400, 'invalid_request', { field: 'cursor' });\n }\n const dryRun = options.dryRun === true;\n const now = options.now ?? this.now();\n const retentionMs = this.policy.retention.lapseRetentionMs;\n const result: LapseSweepResult = {\n dryRun,\n operator,\n discovered: 0,\n swept: [],\n skipped: [],\n nextCursor: null,\n more: false,\n };\n\n const unrecorded = await this.store.listUnrecordedAccounts(cursor, limit);\n for (const accountId of unrecorded) {\n try {\n const denial = await this.checkEntitlement(accountId);\n if (denial?.code !== 'feature_upgrade_required') continue;\n if (!dryRun) await this.store.recordLapse(accountId, now);\n result.discovered += 1;\n } catch {\n result.skipped.push({\n account: accountHandle(accountId),\n reason: 'entitlement_unavailable',\n });\n }\n }\n if (unrecorded.length === limit) {\n result.nextCursor = unrecorded[unrecorded.length - 1] ?? null;\n }\n\n const due = await this.store.listDueLapses(now - retentionMs, limit);\n result.more = due.length === limit;\n for (const lapse of due) {\n const handle = accountHandle(lapse.accountId);\n let denial: FeatureUnavailableError | null;\n try {\n denial = await this.checkEntitlement(lapse.accountId);\n } catch {\n result.skipped.push({\n account: handle,\n reason: 'entitlement_unavailable',\n });\n continue;\n }\n if (!denial) {\n if (!dryRun) await this.store.clearLapse(lapse.accountId);\n result.skipped.push({ account: handle, reason: 'entitled' });\n continue;\n }\n if (denial.code !== 'feature_upgrade_required') {\n result.skipped.push({ account: handle, reason: 'not_lapsed' });\n continue;\n }\n const records = await this.store.listSnapshots(lapse.accountId);\n const planned = {\n account: handle,\n lapsedAt: iso(lapse.lapsedAt),\n retentionEndedAt: iso(lapse.lapsedAt + retentionMs),\n snapshots: records.length,\n bytes: records.reduce((total, record) => total + record.byteSize, 0),\n };\n if (dryRun) {\n result.swept.push(planned);\n continue;\n }\n await this.audit('lapse_sweep_started', operator, handle, planned, now);\n let removedSnapshots = 0;\n let removedBytes = 0;\n for (const record of records) {\n if (await this.removeSnapshot(record, handle, record.status)) {\n removedSnapshots += 1;\n removedBytes += record.byteSize;\n }\n }\n await this.store.markLapseSwept(lapse.accountId, this.now());\n const done = {\n ...planned,\n snapshots: removedSnapshots,\n bytes: removedBytes,\n };\n await this.audit(\n 'lapse_sweep_completed',\n operator,\n handle,\n done,\n this.now(),\n );\n this.logger.warn('lapse_swept', {\n account: handle,\n snapshots: removedSnapshots,\n bytes: removedBytes,\n });\n result.swept.push(done);\n }\n return result;\n }\n\n private async audit(\n action: string,\n operator: string,\n handle: string,\n summary: { snapshots: number; bytes: number } & Record<string, unknown>,\n at: number,\n ): Promise<void> {\n const { snapshots, bytes, ...rest } = summary;\n await this.store.appendAudit({\n id: randomUUID(),\n at,\n action,\n operator,\n accountHandle: handle,\n snapshots,\n bytes,\n detail: JSON.stringify(rest),\n });\n }\n\n // Account-layer hooks ------------------------------------------------------\n\n /**\n * Register a device's Ed25519 public key (raw 32 bytes, base64url) for an\n * account. Idempotent for the same key; a revoked device id or a different\n * key under an existing id is a conflict.\n */\n async registerDevice(\n accountId: string,\n deviceId: string,\n publicKey: string,\n ): Promise<'registered' | 'unchanged' | 'conflict'> {\n if (!isIdentifier(accountId) || !isIdentifier(deviceId)) {\n throw new Error('vault relay: invalid account or device id');\n }\n if (!importDevicePublicKey(publicKey)) {\n throw new Error('vault relay: invalid Ed25519 public key');\n }\n const now = this.now();\n await this.store.ensureAccount(accountId, now);\n return this.store.registerDevice(accountId, deviceId, publicKey, now);\n }\n\n /** Revoke a device; its signatures fail from the next request on. */\n async revokeDevice(accountId: string, deviceId: string): Promise<boolean> {\n if (!isIdentifier(accountId) || !isIdentifier(deviceId)) return false;\n const revoked = await this.store.revokeDevice(\n accountId,\n deviceId,\n this.now(),\n );\n // After the revocation, so an acquire racing it cannot keep the lease;\n // the token bump fences anything recorded under the old token.\n await this.leaseStore.clearHolder(accountId, deviceId);\n return revoked;\n }\n\n /**\n * Operator reset of an account's sequence high-water mark, for an account\n * whose mark was pushed out of reach (every later upload is\n * `stale_sequence`). The new mark must not be above the current one. Any\n * snapshot or pending upload above it is refused with its sequence listed,\n * unless `removeSnapshotsAbove` is set, in which case those rows and their\n * objects are deleted first. Every call that changes anything is logged with\n * the previous mark, the new mark, and the removed sequences.\n */\n async resetHighWater(\n accountId: string,\n highWaterSequence: number,\n options: { removeSnapshotsAbove?: boolean } = {},\n ): Promise<{\n previous: number;\n highWaterSequence: number;\n removed: number[];\n }> {\n if (!isIdentifier(accountId)) throw new RelayError(404, 'not_found');\n if (!Number.isSafeInteger(highWaterSequence) || highWaterSequence < 0) {\n throw new RelayError(400, 'invalid_request', {\n field: 'highWaterSequence',\n });\n }\n const usage = await this.store.getUsage(accountId);\n if (!usage) throw new RelayError(404, 'no_account');\n if (highWaterSequence > usage.highWaterSequence) {\n throw new RelayError(409, 'not_a_reset', {\n highWaterSequence: usage.highWaterSequence,\n });\n }\n const handle = accountHandle(accountId);\n const above = (await this.store.listSnapshots(accountId)).filter(\n (record) => record.sequence > highWaterSequence,\n );\n if (above.length > 0 && options.removeSnapshotsAbove !== true) {\n throw new RelayError(409, 'snapshots_above_high_water', {\n sequences: above.map((record) => record.sequence),\n });\n }\n for (const record of above) {\n await this.removeSnapshot(record, handle, record.status);\n }\n if (above.length > 0) {\n // The rows are gone whether or not the mark moves below: audit them\n // before `high_water_changed` can end the call.\n this.logger.warn('high_water_reset_removed', {\n account: handle,\n removed: above.length,\n removedSequences: above.map((record) => record.sequence).join(','),\n });\n }\n if (!(await this.store.resetHighWater(accountId, highWaterSequence))) {\n // A snapshot appeared above the new mark, or the mark moved: nothing\n // was reset, so the operator can look again.\n throw new RelayError(409, 'high_water_changed');\n }\n // The lease head follows the mark down, or the next acquire (which must\n // name the head) and publish (which must exceed it) could never succeed.\n await this.leaseStore.resetHead(accountId);\n this.logger.warn('high_water_reset', {\n account: handle,\n previous: usage.highWaterSequence,\n to: highWaterSequence,\n removed: above.length,\n removedSequences: above.map((record) => record.sequence).join(','),\n });\n return {\n previous: usage.highWaterSequence,\n highWaterSequence,\n removed: above.map((record) => record.sequence),\n };\n }\n\n /**\n * Mark `accountId` replaced by `supersededBy` (#4817), for the account\n * layer once it has provisioned the new account and registered a device in\n * it. Admin only: no device route can set or clear it, so a stolen device\n * cannot silence or redirect an account. The old account's snapshots stay\n * in place (readable by explicit sequence); it takes no new writes and\n * offers nothing to restore-latest. Idempotent for the same target.\n */\n async supersedeAccount(\n accountId: string,\n supersededBy: string,\n ): Promise<'superseded' | 'unchanged'> {\n if (!isIdentifier(accountId)) throw new RelayError(404, 'not_found');\n if (!isIdentifier(supersededBy) || supersededBy === accountId) {\n throw new RelayError(400, 'invalid_request', { field: 'supersededBy' });\n }\n if (!(await this.store.getUsage(accountId))) {\n throw new RelayError(404, 'no_account');\n }\n // The replacement must already be usable, and must not itself be\n // replaced, nor may the replaced account be someone's replacement (no\n // chains, so no cycles).\n if (await this.store.isSupersessionTarget(accountId)) {\n throw new RelayError(409, 'account_is_target');\n }\n if ((await this.store.countActiveDevices(supersededBy)) < 1) {\n throw new RelayError(409, 'target_not_ready');\n }\n if (await this.store.getSupersession(supersededBy)) {\n throw new RelayError(409, 'target_superseded');\n }\n const result = await this.store.setSupersession(\n accountId,\n supersededBy,\n this.now(),\n );\n if (result === 'conflict') throw new RelayError(409, 'already_superseded');\n if (result === 'superseded') {\n this.logger.warn('account_superseded', {\n account: accountHandle(accountId),\n supersededBy: accountHandle(supersededBy),\n });\n }\n return result;\n }\n\n /** Undo {@link supersedeAccount}, for an operator mistake. */\n async clearSupersession(accountId: string): Promise<boolean> {\n if (!isIdentifier(accountId)) return false;\n const cleared = await this.store.clearSupersession(accountId);\n if (cleared) {\n this.logger.warn('account_supersession_cleared', {\n account: accountHandle(accountId),\n });\n }\n return cleared;\n }\n\n /** Sizes, dates, and device state for one account; never content. */\n async operatorView(accountId: string): Promise<OperatorAccountView> {\n const [usage, snapshots, devices, supersession, lapse] = await Promise.all([\n this.store.getUsage(accountId),\n this.store.listSnapshots(accountId),\n this.store.listDevices(accountId),\n this.store.getSupersession(accountId),\n this.store.getLapse(accountId),\n ]);\n return {\n usage,\n lapsedAt: lapse ? iso(lapse.lapsedAt) : null,\n lapseRetentionEndsAt: lapse\n ? iso(lapse.lapsedAt + this.policy.retention.lapseRetentionMs)\n : null,\n supersededBy: supersession?.supersededBy ?? null,\n snapshots: snapshots.map((record) => ({\n sequence: record.sequence,\n status: record.status,\n byteSize: record.byteSize,\n chunkCount: record.chunkCount,\n sha256: record.sha256,\n createdAt: iso(record.createdAt),\n committedAt:\n record.committedAt === null ? null : iso(record.committedAt),\n })),\n devices: devices.map((device) => ({\n deviceId: device.deviceId,\n status: device.status,\n registeredAt: iso(device.registeredAt),\n revokedAt: device.revokedAt === null ? null : iso(device.revokedAt),\n })),\n };\n }\n\n // Admin API ---------------------------------------------------------------\n\n private adminAuthorized(request: Request): boolean {\n if (!this.adminTokenHash) return false;\n const header = request.headers.get('authorization') ?? '';\n const match = /^Bearer ([^\\s]{1,512})$/.exec(header);\n if (!match) return false;\n const presented = createHash('sha256').update(match[1]).digest();\n return timingSafeEqual(presented, this.adminTokenHash);\n }\n\n /** Operator and account-layer handler (private listener). */\n async handleAdmin(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const method = request.method.toUpperCase();\n const path = url.pathname;\n let status = 500;\n try {\n if (method === 'GET') {\n const health = await this.health(path);\n if (health) return health;\n }\n if (!this.adminTokenHash) throw new RelayError(404, 'not_found');\n if (!this.adminAuthorized(request)) {\n throw new RelayError(401, 'unauthorized');\n }\n const response = await this.dispatchAdmin(method, path, request);\n status = response.status;\n return response;\n } catch (error) {\n const response = this.toErrorResponse(error);\n status = response.status;\n return response;\n } finally {\n this.logger.info('admin_request', { method, status });\n }\n }\n\n /**\n * Operator identity for the audit trail: the optional `x-vault-operator`\n * label the caller states, plus a fingerprint of the admin token that\n * authenticated the request (a hash prefix, never the token).\n */\n private operatorIdentity(request: Request): string {\n const fingerprint = `token:${this.adminTokenHash?.toString('hex').slice(0, 12) ?? 'none'}`;\n const label = request.headers.get('x-vault-operator');\n if (label === null) return fingerprint;\n if (!OPERATOR_LABEL.test(label)) {\n throw new RelayError(400, 'invalid_request', {\n field: 'x-vault-operator',\n });\n }\n return `${label}/${fingerprint}`;\n }\n\n private async adminLapseSweep(request: Request): Promise<LapseSweepResult> {\n const operator = this.operatorIdentity(request);\n const bytes = await readBoundedBody(request, MAX_JSON_BODY_BYTES);\n const input = bytes.length === 0 ? {} : parseJsonObject(bytes);\n if (input.dryRun !== undefined && typeof input.dryRun !== 'boolean') {\n throw new RelayError(400, 'invalid_request', { field: 'dryRun' });\n }\n if (input.limit !== undefined && typeof input.limit !== 'number') {\n throw new RelayError(400, 'invalid_request', { field: 'limit' });\n }\n if (input.cursor !== undefined && typeof input.cursor !== 'string') {\n throw new RelayError(400, 'invalid_request', { field: 'cursor' });\n }\n return this.sweepLapsedAccounts({\n operator,\n dryRun: input.dryRun === true,\n ...(input.limit !== undefined ? { limit: input.limit } : {}),\n ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),\n });\n }\n\n private async dispatchAdmin(\n method: string,\n path: string,\n request: Request,\n ): Promise<Response> {\n if (path === '/admin/v1/sweep' && method === 'POST') {\n return json(200, { expired: await this.sweepExpired() });\n }\n if (path === '/admin/v1/lapse-sweep' && method === 'POST') {\n return json(200, await this.adminLapseSweep(request));\n }\n let m = /^\\/admin\\/v1\\/accounts\\/([^/]+)$/.exec(path);\n if (m && method === 'GET') {\n if (!isIdentifier(m[1])) throw new RelayError(404, 'not_found');\n return json(200, await this.operatorView(m[1]));\n }\n m = /^\\/admin\\/v1\\/accounts\\/([^/]+)\\/reconcile$/.exec(path);\n if (m && method === 'POST') {\n if (!isIdentifier(m[1])) throw new RelayError(404, 'not_found');\n await this.store.reconcileUsage(m[1]);\n return json(200, { usage: await this.store.getUsage(m[1]) });\n }\n m = /^\\/admin\\/v1\\/accounts\\/([^/]+)\\/high-water$/.exec(path);\n if (m && method === 'POST') {\n if (!isIdentifier(m[1])) throw new RelayError(404, 'not_found');\n const input = parseJsonObject(\n await readBoundedBody(request, MAX_JSON_BODY_BYTES),\n );\n if (\n input.removeSnapshotsAbove !== undefined &&\n typeof input.removeSnapshotsAbove !== 'boolean'\n ) {\n throw new RelayError(400, 'invalid_request', {\n field: 'removeSnapshotsAbove',\n });\n }\n return json(\n 200,\n await this.resetHighWater(m[1], input.highWaterSequence as number, {\n removeSnapshotsAbove: input.removeSnapshotsAbove === true,\n }),\n );\n }\n m = /^\\/admin\\/v1\\/accounts\\/([^/]+)\\/superseded-by$/.exec(path);\n if (m && (method === 'PUT' || method === 'DELETE')) {\n if (!isIdentifier(m[1])) throw new RelayError(404, 'not_found');\n if (method === 'DELETE') {\n if (!(await this.clearSupersession(m[1]))) {\n throw new RelayError(404, 'no_supersession');\n }\n return json(204, null);\n }\n const input = parseJsonObject(\n await readBoundedBody(request, MAX_JSON_BODY_BYTES),\n );\n if (typeof input.supersededBy !== 'string') {\n throw new RelayError(400, 'invalid_request', {\n field: 'supersededBy',\n });\n }\n const result = await this.supersedeAccount(m[1], input.supersededBy);\n return json(result === 'superseded' ? 201 : 200, { result });\n }\n m = /^\\/admin\\/v1\\/accounts\\/([^/]+)\\/devices\\/([^/]+)$/.exec(path);\n if (m) {\n const [, accountId, deviceId] = m;\n if (!isIdentifier(accountId) || !isIdentifier(deviceId)) {\n throw new RelayError(404, 'not_found');\n }\n if (method === 'PUT') {\n const input = parseJsonObject(\n await readBoundedBody(request, MAX_JSON_BODY_BYTES),\n );\n if (\n typeof input.publicKey !== 'string' ||\n !importDevicePublicKey(input.publicKey)\n ) {\n throw new RelayError(400, 'invalid_request', { field: 'publicKey' });\n }\n const result = await this.registerDevice(\n accountId,\n deviceId,\n input.publicKey,\n );\n if (result === 'conflict') throw new RelayError(409, 'device_conflict');\n return json(result === 'registered' ? 201 : 200, { result });\n }\n if (method === 'DELETE') {\n const revoked = await this.revokeDevice(accountId, deviceId);\n if (!revoked) throw new RelayError(404, 'no_active_device');\n return json(204, null);\n }\n }\n throw new RelayError(404, 'not_found');\n }\n}\n","/**\n * Deployment entry: environment configuration, database and object-store\n * wiring, and the two listeners. Quotas, retention, bucket, and database\n * locations are owner inputs with no defaults; a missing value stops startup.\n */\nimport type { Server } from 'node:http';\nimport { FeatureResolver } from '@happyvertical/smrt-features';\nimport { SubscriptionFeatureSource } from '@happyvertical/smrt-subscriptions';\nimport { type DatabaseInterface, getDatabase } from '@happyvertical/sql';\nimport type { VaultRelayPolicyInput } from './config.js';\nimport { migrateVaultRelayLeasesV1 } from './lease-store.js';\nimport { migrateVaultRelayV1, VaultRelayStore } from './metadata-store.js';\nimport { createRelayHttpServer } from './node-server.js';\nimport {\n createS3ObjectStore,\n FilesystemObjectStore,\n type S3ObjectStoreOptions,\n type VaultObjectStore,\n} from './object-store.js';\nimport { jsonLineLogger, VaultRelay } from './relay.js';\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\nexport type VaultRelayStorageConfig =\n | { kind: 'filesystem'; path: string }\n | ({ kind: 's3' } & S3ObjectStoreOptions);\n\nexport interface VaultRelayServerConfig {\n databaseUrl: string;\n entitlementsDatabaseUrl: string;\n storage: VaultRelayStorageConfig;\n policy: VaultRelayPolicyInput;\n port: number;\n adminPort: number;\n adminToken?: string;\n}\n\n/** Thrown for configuration errors; the message names variables, not values. */\nexport class VaultRelayConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'VaultRelayConfigError';\n }\n}\n\ntype Env = Record<string, string | undefined>;\n\nfunction required(env: Env, name: string): string {\n const value = env[name]?.trim();\n if (!value) throw new VaultRelayConfigError(`${name} is required`);\n return value;\n}\n\nfunction integer(env: Env, name: string, fallback?: number): number {\n const raw = env[name]?.trim();\n if (!raw) {\n if (fallback === undefined) {\n throw new VaultRelayConfigError(`${name} is required`);\n }\n return fallback;\n }\n if (!/^[0-9]{1,16}$/.test(raw) || !Number.isSafeInteger(Number(raw))) {\n throw new VaultRelayConfigError(`${name} must be a non-negative integer`);\n }\n return Number(raw);\n}\n\n/** Read the server configuration from environment variables. */\nexport function loadServerConfig(\n env: Env = process.env,\n): VaultRelayServerConfig {\n const kind = required(env, 'VAULT_RELAY_STORAGE');\n let storage: VaultRelayStorageConfig;\n if (kind === 'filesystem') {\n storage = { kind, path: required(env, 'VAULT_RELAY_STORAGE_PATH') };\n } else if (kind === 's3') {\n storage = {\n kind,\n bucket: required(env, 'VAULT_RELAY_S3_BUCKET'),\n endpoint: required(env, 'VAULT_RELAY_S3_ENDPOINT'),\n region: required(env, 'VAULT_RELAY_S3_REGION'),\n accessKeyId: required(env, 'VAULT_RELAY_S3_ACCESS_KEY_ID'),\n secretAccessKey: required(env, 'VAULT_RELAY_S3_SECRET_ACCESS_KEY'),\n };\n } else {\n throw new VaultRelayConfigError(\n 'VAULT_RELAY_STORAGE must be \"filesystem\" or \"s3\"',\n );\n }\n const adminToken = env.VAULT_RELAY_ADMIN_TOKEN?.trim();\n return {\n databaseUrl: required(env, 'VAULT_RELAY_DATABASE_URL'),\n entitlementsDatabaseUrl: required(\n env,\n 'VAULT_RELAY_ENTITLEMENTS_DATABASE_URL',\n ),\n storage,\n policy: {\n quota: {\n maxBytes: integer(env, 'VAULT_RELAY_QUOTA_MAX_BYTES'),\n maxSnapshots: integer(env, 'VAULT_RELAY_QUOTA_MAX_SNAPSHOTS'),\n },\n retention: {\n keepLast: integer(env, 'VAULT_RELAY_RETENTION_KEEP_LAST'),\n keepWithinMs:\n integer(env, 'VAULT_RELAY_RETENTION_KEEP_WITHIN_DAYS') * DAY_MS,\n ...(env.VAULT_RELAY_LAPSE_RETENTION_DAYS\n ? {\n lapseRetentionDays: integer(\n env,\n 'VAULT_RELAY_LAPSE_RETENTION_DAYS',\n ),\n }\n : {}),\n },\n limits: {\n ...(env.VAULT_RELAY_MAX_CHUNK_BYTES\n ? { maxChunkBytes: integer(env, 'VAULT_RELAY_MAX_CHUNK_BYTES') }\n : {}),\n ...(env.VAULT_RELAY_UPLOAD_TTL_SECONDS\n ? {\n uploadTtlMs:\n integer(env, 'VAULT_RELAY_UPLOAD_TTL_SECONDS') * 1000,\n }\n : {}),\n ...(env.VAULT_RELAY_LEASE_TTL_SECONDS\n ? { leaseTtlMs: integer(env, 'VAULT_RELAY_LEASE_TTL_SECONDS') * 1000 }\n : {}),\n ...(env.VAULT_RELAY_MAX_CLOCK_SKEW_SECONDS\n ? {\n maxClockSkewMs:\n integer(env, 'VAULT_RELAY_MAX_CLOCK_SKEW_SECONDS') * 1000,\n }\n : {}),\n ...(env.VAULT_RELAY_MAX_SEQUENCE_JUMP\n ? {\n maxSequenceJump: integer(env, 'VAULT_RELAY_MAX_SEQUENCE_JUMP'),\n }\n : {}),\n },\n },\n port: integer(env, 'VAULT_RELAY_PORT', 8080),\n adminPort: integer(env, 'VAULT_RELAY_ADMIN_PORT', 8081),\n ...(adminToken ? { adminToken } : {}),\n };\n}\n\n/** Open a database from a `postgres://`/`postgresql://` URL or a SQLite path. */\nexport async function openRelayDatabase(\n url: string,\n): Promise<DatabaseInterface> {\n if (/^postgres(ql)?:\\/\\//.test(url)) {\n return getDatabase({ type: 'postgres', url });\n }\n return getDatabase({ type: 'sqlite', url });\n}\n\nasync function openObjectStore(\n storage: VaultRelayStorageConfig,\n): Promise<VaultObjectStore> {\n if (storage.kind === 'filesystem') {\n return new FilesystemObjectStore(storage.path);\n }\n const { kind: _kind, ...options } = storage;\n return createS3ObjectStore(options);\n}\n\n/** Apply the relay schema (the deployment migration step). */\nexport async function runMigrations(\n config: Pick<VaultRelayServerConfig, 'databaseUrl'>,\n): Promise<void> {\n const db = await openRelayDatabase(config.databaseUrl);\n try {\n await migrateVaultRelayV1(db);\n await migrateVaultRelayLeasesV1(db);\n } finally {\n await db.close?.();\n }\n}\n\nexport interface RunningVaultRelay {\n relay: VaultRelay;\n server: Server;\n adminServer: Server | null;\n close(): Promise<void>;\n}\n\n/** Build the relay from configuration and start both listeners. */\nexport async function startVaultRelayServer(\n config: VaultRelayServerConfig,\n): Promise<RunningVaultRelay> {\n const db = await openRelayDatabase(config.databaseUrl);\n const entitlementsDb =\n config.entitlementsDatabaseUrl === config.databaseUrl\n ? db\n : await openRelayDatabase(config.entitlementsDatabaseUrl);\n const resolver = new FeatureResolver({ db: entitlementsDb });\n const relay = new VaultRelay({\n store: new VaultRelayStore(db),\n objects: await openObjectStore(config.storage),\n entitlements: {\n resolver,\n // One grant source per request, so a plan change applies immediately.\n grantSource: () =>\n SubscriptionFeatureSource.create({ db: entitlementsDb }),\n },\n policy: config.policy,\n ...(config.adminToken ? { adminToken: config.adminToken } : {}),\n logger: jsonLineLogger,\n });\n\n const server = createRelayHttpServer((request) => relay.handle(request));\n await new Promise<void>((resolve) => server.listen(config.port, resolve));\n let adminServer: Server | null = null;\n if (config.adminToken) {\n adminServer = createRelayHttpServer((request) =>\n relay.handleAdmin(request),\n );\n await new Promise<void>((resolve) =>\n adminServer?.listen(config.adminPort, resolve),\n );\n }\n const sweep = setInterval(() => {\n relay.sweepExpired().catch((error: unknown) => {\n jsonLineLogger.warn('sweep_failed', {\n error: error instanceof Error ? error.name : 'unknown',\n });\n });\n }, 60_000);\n sweep.unref();\n jsonLineLogger.info('started', {\n port: config.port,\n admin: adminServer !== null,\n storage: config.storage.kind,\n });\n\n return {\n relay,\n server,\n adminServer,\n async close() {\n clearInterval(sweep);\n await new Promise<void>((resolve) => server.close(() => resolve()));\n if (adminServer) {\n await new Promise<void>((resolve) =>\n adminServer?.close(() => resolve()),\n );\n }\n if (entitlementsDb !== db) await entitlementsDb.close?.();\n await db.close?.();\n },\n };\n}\n"],"mappings":";;;;;;;;;AASA,IAAM,aAAa;AAEnB,IAAM,QAAQ;AACd,IAAM,aAAa;AACnB,IAA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YACnC,MAAM,YAAY,OAAO,CAC3B;EACA,MAAM,IAAI,SAAe,YACvB,aAAa,OAAO,OAAO,WAAW,OAAO,CAC/C;CACF;CACA,MAAM,QAAQ,kBAAkB;EAC9B,MAAM,aAAa,CAAA,CAAE,OAAO,UAAmB;GAC7C,eAAe,KAAK,gBAAgB,EAClC,OAAO,iBAAiB,QAAQ,MAAM,OAAO,UAC/C,CAAC;EACH,CAAC;CACH,GAAG,GAAM;CACT,MAAM,MAAM;CACZ,eAAe,KAAK,WAAW;EAC7B,MAAM,OAAO;EACb,OAAO,gBAAgB;EACvB,SAAS,OAAO,QAAQ;CAC1B,CAAC;CAED,OAAO;EACL;EACA;EACA;EACA,MAAM,QAAQ;GACZ,cAAc,KAAK;GACnB,MAAM,IAAI,SAAe,YAAY,OAAO,YAAY,QAAQ,CAAC,CAAC;GAClE,IAAI,aACF,MAAM,IAAI,SAAe,YACvB,aAAa,YAAY,QAAQ,CAAC,CACpC;GAEF,IAAI,mBAAmB,IAAI,MAAM,eAAe,QAAQ;GACxD,MAAM,GAAG,QAAQ;EACnB;CACF;AACF"}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { a as startVaultRelayServer, i as runMigrations, n as loadServerConfig } from "./chunks/server-0ITpMTMD.js";
|
|
2
|
+
//#region src/cli.ts
|
|
3
|
+
async function main(argv) {
|
|
4
|
+
const command = argv[0];
|
|
5
|
+
if (command === "migrate") {
|
|
6
|
+
const databaseUrl = process.env.VAULT_RELAY_DATABASE_URL?.trim();
|
|
7
|
+
if (!databaseUrl) {
|
|
8
|
+
process.stderr.write("VAULT_RELAY_DATABASE_URL is required\n");
|
|
9
|
+
return 2;
|
|
10
|
+
}
|
|
11
|
+
await runMigrations({ databaseUrl });
|
|
12
|
+
process.stdout.write("{\"level\":\"info\",\"event\":\"migrated\"}\n");
|
|
13
|
+
return 0;
|
|
14
|
+
}
|
|
15
|
+
if (command === "serve") {
|
|
16
|
+
const running = await startVaultRelayServer(loadServerConfig());
|
|
17
|
+
const stop = () => {
|
|
18
|
+
running.close().then(() => process.exit(0), () => process.exit(1));
|
|
19
|
+
};
|
|
20
|
+
process.once("SIGTERM", stop);
|
|
21
|
+
process.once("SIGINT", stop);
|
|
22
|
+
return -1;
|
|
23
|
+
}
|
|
24
|
+
process.stderr.write("usage: smrt-vault-relay <serve|migrate>\n");
|
|
25
|
+
return 2;
|
|
26
|
+
}
|
|
27
|
+
main(process.argv.slice(2)).then((code) => {
|
|
28
|
+
if (code >= 0) process.exit(code);
|
|
29
|
+
}, (error) => {
|
|
30
|
+
const name = error instanceof Error ? error.name : "Error";
|
|
31
|
+
const message = error instanceof Error && error.name === "VaultRelayConfigError" ? error.message : "startup failed";
|
|
32
|
+
process.stderr.write(`${JSON.stringify({
|
|
33
|
+
level: "error",
|
|
34
|
+
event: "fatal",
|
|
35
|
+
error: name,
|
|
36
|
+
message
|
|
37
|
+
})}
|
|
38
|
+
`);
|
|
39
|
+
process.exit(1);
|
|
40
|
+
});
|
|
41
|
+
//#endregion
|
|
42
|
+
|
|
43
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["/**\n * Container entry point: `node dist/cli.js serve` or `node dist/cli.js migrate`.\n * Configuration comes from the environment (see the package README). Errors\n * print the variable name only, never a value.\n */\nimport {\n loadServerConfig,\n runMigrations,\n startVaultRelayServer,\n} from './server.js';\n\nasync function main(argv: string[]): Promise<number> {\n const command = argv[0];\n if (command === 'migrate') {\n const databaseUrl = process.env.VAULT_RELAY_DATABASE_URL?.trim();\n if (!databaseUrl) {\n process.stderr.write('VAULT_RELAY_DATABASE_URL is required\\n');\n return 2;\n }\n await runMigrations({ databaseUrl });\n process.stdout.write('{\"level\":\"info\",\"event\":\"migrated\"}\\n');\n return 0;\n }\n if (command === 'serve') {\n const running = await startVaultRelayServer(loadServerConfig());\n const stop = () => {\n running.close().then(\n () => process.exit(0),\n () => process.exit(1),\n );\n };\n process.once('SIGTERM', stop);\n process.once('SIGINT', stop);\n return -1;\n }\n process.stderr.write('usage: smrt-vault-relay <serve|migrate>\\n');\n return 2;\n}\n\nmain(process.argv.slice(2)).then(\n (code) => {\n if (code >= 0) process.exit(code);\n },\n (error: unknown) => {\n const name = error instanceof Error ? error.name : 'Error';\n const message =\n error instanceof Error && error.name === 'VaultRelayConfigError'\n ? error.message\n : 'startup failed';\n process.stderr.write(\n `${JSON.stringify({ level: 'error', event: 'fatal', error: name, message })}\\n`,\n );\n process.exit(1);\n },\n);\n"],"mappings":";;AAWA,eAAe,KAAK,MAAiC;CACnD,MAAM,UAAU,KAAK;CACrB,IAAI,YAAY,WAAW;EACzB,MAAM,cAAc,QAAQ,IAAI,0BAA0B,KAAK;EAC/D,IAAI,CAAC,aAAa;GAChB,QAAQ,OAAO,MAAM,wCAAwC;GAC7D,OAAO;EACT;EACA,MAAM,cAAc,EAAE,YAAY,CAAC;EACnC,QAAQ,OAAO,MAAM,+CAAuC;EAC5D,OAAO;CACT;CACA,IAAI,YAAY,SAAS;EACvB,MAAM,UAAU,MAAM,sBAAsB,iBAAiB,CAAC;EAC9D,MAAM,aAAa;GACjB,QAAQ,MAAM,CAAA,CAAE,WACR,QAAQ,KAAK,CAAC,SACd,QAAQ,KAAK,CAAC,CACtB;EACF;EACA,QAAQ,KAAK,WAAW,IAAI;EAC5B,QAAQ,KAAK,UAAU,IAAI;EAC3B,OAAO;CACT;CACA,QAAQ,OAAO,MAAM,2CAA2C;CAChE,OAAO;AACT;AAEA,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAA,CAAE,MACzB,SAAS;CACR,IAAI,QAAQ,GAAG,QAAQ,KAAK,IAAI;AAClC,IACC,UAAmB;CAClB,MAAM,OAAO,iBAAiB,QAAQ,MAAM,OAAO;CACnD,MAAM,UACJ,iBAAiB,SAAS,MAAM,SAAS,0BACrC,MAAM,UACN;CACN,QAAQ,OAAO,MACb,GAAG,KAAK,UAAU;EAAE,OAAO;EAAS,OAAO;EAAS,OAAO;EAAM;CAAQ,CAAC,EAAC;CAC7E;CACA,QAAQ,KAAK,CAAC;AAChB,CACF"}
|