@xyo-network/event-kit-node 2.2.0 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node/index.mjs +4 -4
- package/dist/node/index.mjs.map +2 -2
- package/dist/node/runtime.mjs +2 -2
- package/dist/node/runtime.mjs.map +2 -2
- package/package.json +24 -24
package/dist/node/index.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/bestEffortSnapshotWorker.ts", "../../src/filesystemCursorStore.ts", "../../src/filesystemDurability.ts", "../../src/filesystemJson.ts", "../../src/privateSqlite.ts", "../../src/filesystemPublisherOutbox.ts", "../../src/filesystemWakeInbox.ts", "../../src/filesystemWakeQueue.ts", "../../src/receiverAuthority.ts", "../../src/filesystemEventKitReplayCheckpointStore.ts", "../../src/filesystemFinalizedStatementPublicationJournal.ts", "../../src/filesystemHandshakeMutationIntentStore.ts", "../../src/handshakeMutationIntent.ts", "../../src/filesystemPublisherEncryptionKeyStore.ts", "../../src/filesystemPublisherEndpointChallengeStore.ts", "../../src/handshakeClients.ts", "../../src/receiverMigration.ts", "../../src/receiverMigrationInventory.ts", "../../src/receiverMigrationSnapshot.ts", "../../src/runtime/boundedFetch.ts", "../../src/runtime/abort.ts", "../../src/runtime/handshakeDiscovery.ts", "../../src/runtime/httpsTransport.ts", "../../src/runtime/sources.ts", "../../src/runtime/publisherRuntime.ts", "../../src/runtime/publisherDeliveryState.ts", "../../src/runtime/sourceSigner.ts", "../../src/runtime/restGateway.ts", "../../src/runtime/sqliteHandshakeStores.ts", "../../src/runtime/sqlitePublisherState.ts", "../../src/sqliteBestEffortInbox.ts", "../../src/sqliteWakeQueue.ts"],
|
|
4
|
-
"sourcesContent": ["import { canonicalJson, wakeSourcesEqual } from '@xyo-network/event-kit-protocol'\nimport {\n HashZod, NonnegativeJsonSafeIntegerZod, WakeSourceZod,\n} from '@xyo-network/event-kit-schemas'\n\nimport type {\n BestEffortWorkerLease, PersistentBestEffortInbox, VerifiedBestEffortSnapshot,\n} from './bestEffortTypes.ts'\n\n/** The port must enforce the byte bound while reading and independently verify source identity/finality/content. */\nexport interface BestEffortSnapshotSource<TSnapshot, TValue> {\n readCurrent(input: {\n readonly maxBytes: number\n readonly signal: AbortSignal\n readonly source: BestEffortWorkerLease['binding']['source']\n }): Promise<TSnapshot>\n verifySnapshot(input: {\n readonly signal: AbortSignal\n readonly snapshot: TSnapshot\n readonly source: BestEffortWorkerLease['binding']['source']\n }): Promise<VerifiedBestEffortSnapshot<TValue>>\n}\n\n/**\n * Host-owned effect/checkpoint commit. The host must atomically reject older\n * binding/fence commits and make repeats safe through idempotence or its effect\n * journal/checkpoint transaction. A process can die after this commit and before\n * inbox completion, so it can be repeated. `lease.isCurrent()` is advisory and\n * cannot replace the app's own atomic fence/effect commit.\n * dapp-kit consumers implement this through their effect journal/checkpoint,\n * rather than an independent app engine in Event Kit.\n */\nexport interface BestEffortSnapshotApplication<TValue> {\n commitSnapshot(input: {\n readonly lease: BestEffortWorkerLease\n readonly snapshot: VerifiedBestEffortSnapshot<TValue>\n }): Promise<void>\n}\n\nexport interface BestEffortSnapshotWorkerOptions<TSnapshot, TValue> {\n readonly application: BestEffortSnapshotApplication<TValue>\n readonly inbox: PersistentBestEffortInbox\n readonly leaseSeconds?: number\n readonly maxSnapshotBytes: number\n readonly nowSeconds?: () => number\n readonly source: BestEffortSnapshotSource<TSnapshot, TValue>\n}\n\nexport interface BestEffortSnapshotWorker {\n /** Run at startup and periodically; durable scanning, not callbacks, chooses work. */\n runOnce(signal?: AbortSignal): Promise<'idle' | 'completed' | 'superseded'>\n}\n\n/** A bounded observer worker; no full-history replay or public-ingress app execution. */\nexport function createBestEffortSnapshotWorker<TSnapshot, TValue>(\n options: BestEffortSnapshotWorkerOptions<TSnapshot, TValue>,\n): BestEffortSnapshotWorker {\n if (!Number.isSafeInteger(options.maxSnapshotBytes) || options.maxSnapshotBytes < 1)\n throw new TypeError('Invalid bounded snapshot byte limit')\n const nowSeconds = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const leaseSeconds = options.leaseSeconds ?? 60\n if (!Number.isSafeInteger(leaseSeconds) || leaseSeconds < 1)\n throw new TypeError('Invalid Best Effort worker lease lifetime')\n\n async function processSnapshot(lease: BestEffortWorkerLease, signal: AbortSignal): Promise<'completed' | 'superseded'> {\n const source = lease.binding.source\n const observed = await options.source.readCurrent({\n source, signal, maxBytes: options.maxSnapshotBytes,\n })\n signal.throwIfAborted()\n const snapshot = await options.source.verifySnapshot({\n source, signal, snapshot: observed,\n })\n signal.throwIfAborted()\n WakeSourceZod.parse(snapshot.source)\n NonnegativeJsonSafeIntegerZod.parse(snapshot.position)\n if (snapshot.hash !== undefined) HashZod.parse(snapshot.hash)\n if (!wakeSourcesEqual(source, snapshot.source)\n || (source.kind !== 'utc-interval' && snapshot.hash === undefined))\n throw new TypeError('Independent snapshot does not match its pinned source')\n if (Buffer.byteLength(canonicalJson(snapshot.value), 'utf8') > options.maxSnapshotBytes)\n throw new RangeError('Independent snapshot exceeds its configured byte bound')\n const previous = lease.previousSnapshot\n if (previous !== undefined && (snapshot.position < previous.position\n || (snapshot.position === previous.position && snapshot.hash !== previous.hash)))\n throw new TypeError('Independent snapshot regressed or changed at the committed position')\n if (!await lease.isCurrent()) return 'superseded'\n await options.application.commitSnapshot({ lease, snapshot })\n signal.throwIfAborted()\n return await lease.complete(snapshot) ? 'completed' : 'superseded'\n }\n\n return {\n async runOnce(inputSignal) {\n const controller = new AbortController()\n const signal = inputSignal ?? controller.signal\n signal.throwIfAborted()\n const now = nowSeconds()\n await options.inbox.recoverExpired(now)\n const lease = await options.inbox.claim({ nowSeconds: now, leaseSeconds })\n if (lease === undefined) return 'idle'\n let failed = false\n let failure: unknown\n let releaseFailed = false\n let releaseFailure: unknown\n let result: 'completed' | 'superseded' = 'superseded'\n try {\n result = await processSnapshot(lease, signal)\n } catch (error) {\n failed = true\n failure = error\n }\n try {\n await lease.release()\n } catch (error) {\n releaseFailed = true\n releaseFailure = error\n }\n if (failed && releaseFailed)\n throw new AggregateError([failure, releaseFailure], 'Best Effort snapshot work failed and its lease release also failed', { cause: failure })\n if (failed) throw failure\n if (releaseFailed) throw releaseFailure\n return result\n },\n }\n}\n", "import { lstat } from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type { PublisherCursorStore } from '@xyo-network/event-kit-actor'\nimport { NonnegativeJsonSafeIntegerZod } from '@xyo-network/event-kit-schemas'\nimport { z } from 'zod'\n\nimport { ensureDurableDirectory, syncDirectory } from './filesystemDurability.ts'\nimport { readJsonFileStrict, replaceJsonFile } from './filesystemJson.ts'\nimport { checkPrivateStoreFile, ensurePrivateDirectory } from './privateSqlite.ts'\n\nexport interface FilesystemCursorStoreOptions {\n /** Absolute or relative path to the cursor JSON file. */\n readonly path: string\n}\n\nconst CursorFileZod = z.strictObject({ lastProcessedBlock: NonnegativeJsonSafeIntegerZod })\n\n/**\n * Persists the publisher cursor as `{ \"lastProcessedBlock\": number }` on disk.\n */\nexport function createFilesystemCursorStore(\n options: FilesystemCursorStoreOptions,\n): PublisherCursorStore {\n const filePath = PATH.resolve(options.path)\n const directory = PATH.dirname(filePath)\n return {\n async load(): Promise<number | undefined> {\n if (!await existingPrivateDirectory(directory)) return undefined\n checkPrivateStoreFile(filePath)\n const raw = await readJsonFileStrict(filePath)\n if (raw === undefined) return undefined\n const cursor = CursorFileZod.parse(raw)\n // Finish a previous replacement whose directory flush failed before\n // exposing its checkpoint as the authority for fresh publisher work.\n await syncDirectory(directory)\n return cursor.lastProcessedBlock\n },\n async save(lastProcessedBlock: number): Promise<void> {\n const body = CursorFileZod.parse({ lastProcessedBlock })\n await ensureDurableDirectory(directory, 0o700)\n ensurePrivateDirectory(directory)\n checkPrivateStoreFile(filePath)\n await replaceJsonFile(filePath, body, { mode: 0o600, directoryMode: 0o700 })\n },\n }\n}\n\nasync function existingPrivateDirectory(directory: string) {\n try {\n await lstat(directory)\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') return false\n throw error\n }\n ensurePrivateDirectory(directory)\n return true\n}\n", "import { mkdir, open } from 'node:fs/promises'\nimport PATH from 'node:path'\n\n/** Writes and fsyncs `body` so the bytes survive a crash before the caller publishes it. */\nexport async function writeDurableFile(path: string, body: string, mode?: number): Promise<void> {\n const handle = await open(path, 'w', mode)\n try {\n await handle.writeFile(body, 'utf8')\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n\n/** Creates a directory tree and fsyncs each new entry through its previously existing parent. */\nexport async function ensureDurableDirectory(path: string, mode?: number): Promise<void> {\n const directory = PATH.resolve(path)\n const firstCreated = await mkdir(directory, { mode, recursive: true })\n if (firstCreated === undefined) return\n\n const existingParent = PATH.dirname(PATH.resolve(firstCreated))\n let cursor = directory\n while (true) {\n await syncDirectory(cursor)\n if (cursor === existingParent) return\n const parent = PATH.dirname(cursor)\n if (parent === cursor) throw new Error('Created directory is not below its reported existing parent')\n cursor = parent\n }\n}\n\n/**\n * Fsyncs a directory so a published entry survives power loss. Only explicit\n * platform/filesystem \"directory sync unsupported\" errors are non-fatal;\n * missing paths, permission failures, and I/O errors remain hard failures.\n */\nexport async function syncDirectory(path: string): Promise<void> {\n let handle\n try {\n handle = await open(path, 'r')\n await handle.sync()\n } catch (error) {\n if (!isUnsupportedDirectorySync(error)) throw error\n } finally {\n await handle?.close()\n }\n}\n\nfunction isUnsupportedDirectorySync(error: unknown): boolean {\n const code = errorCode(error)\n return code === 'EISDIR' || code === 'EINVAL' || code === 'ENOTSUP' || code === 'EOPNOTSUPP'\n}\n\nfunction errorCode(error: unknown): unknown {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as { code?: unknown }).code\n : undefined\n}\n", "import { randomBytes } from 'node:crypto'\nimport {\n link, open, rename, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport {\n ensureDurableDirectory,\n syncDirectory,\n writeDurableFile,\n} from './filesystemDurability.ts'\n\nexport interface FilesystemJsonWriteOptions {\n readonly directoryMode?: number\n readonly mode?: number\n}\n\nexport async function readJsonFileStrict(path: string): Promise<unknown> {\n let handle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return undefined\n throw error\n }\n try {\n return JSON.parse(await handle.readFile('utf8'), reviveJson) as unknown\n } finally { await handle.close() }\n}\n\n/** Atomically replaces one JSON file after its new bytes have reached disk. */\nexport async function replaceJsonFile(\n path: string,\n value: unknown,\n options: FilesystemJsonWriteOptions = {},\n): Promise<void> {\n const directory = PATH.dirname(path)\n await ensureDurableDirectory(directory, options.directoryMode)\n const tempPath = PATH.join(directory, `.${PATH.basename(path)}.${process.pid}.${suffix()}.tmp`)\n try {\n await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n await rename(tempPath, path)\n await syncDirectory(directory)\n } catch (error) {\n await unlinkIfMissing(tempPath)\n throw error\n }\n}\n\n/**\n * Publishes immutable JSON with an exclusive hard link. Returns `false` when\n * another process already owns the destination.\n */\nexport async function publishJsonFile(\n path: string,\n value: unknown,\n options: FilesystemJsonWriteOptions = {},\n): Promise<boolean> {\n const directory = PATH.dirname(path)\n await ensureDurableDirectory(directory, options.directoryMode)\n const tempPath = PATH.join(directory, `.${PATH.basename(path)}.${process.pid}.${suffix()}.tmp`)\n try {\n await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n await link(tempPath, path)\n await syncDirectory(directory)\n return true\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw error\n } finally {\n await unlinkIfMissing(tempPath)\n }\n}\n\nfunction suffix(): string {\n return randomBytes(8).toString('hex')\n}\n\nexport function stringifyJson(value: unknown): string {\n return JSON.stringify(value, replaceJsonValue)\n}\n\nfunction replaceJsonValue(_key: string, candidate: unknown): unknown {\n return typeof candidate === 'bigint'\n ? { $eventKitBigInt: candidate.toString() }\n : candidate\n}\n\nfunction reviveJson(_key: string, candidate: unknown): unknown {\n return typeof candidate === 'object'\n && candidate !== null\n && Object.keys(candidate).length === 1\n && '$eventKitBigInt' in candidate\n && typeof candidate.$eventKitBigInt === 'string'\n && /^(?:0|[1-9][0-9]*)$/u.test(candidate.$eventKitBigInt)\n ? BigInt(candidate.$eventKitBigInt)\n : candidate\n}\n\nasync function unlinkIfMissing(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') throw error\n }\n}\n\nfunction errorCode(error: unknown): unknown {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as { code?: unknown }).code\n : undefined\n}\n", "import {\n closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync,\n} from 'node:fs'\nimport PATH from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nexport class LegacyReceiverStoreError extends Error {\n override readonly name = 'LegacyReceiverStoreError'\n constructor(path: string) {\n super(`Receiver store requires explicit offline migration: ${path}`)\n }\n}\n\n/** Only the store's own directory is created/checked; unrelated parents are not chmodded. */\nexport function ensurePrivateDirectory(path: string): void {\n const created = mkdirSync(path, { recursive: true, mode: 0o700 })\n const info = lstatSync(path)\n if (!info.isDirectory() || info.isSymbolicLink() || (info.mode & 0o077) !== 0\n || (process.getuid !== undefined && info.uid !== process.getuid())) {\n throw new Error(`Receiver directory must be owned and private (0700): ${path}`)\n }\n if (created === undefined) return\n const existingParent = PATH.dirname(PATH.resolve(created))\n let cursor = PATH.resolve(path)\n for (;;) {\n syncPrivateDirectory(cursor)\n if (cursor === existingParent) break\n cursor = PATH.dirname(cursor)\n }\n}\n\nfunction syncPrivateDirectory(path: string): void {\n let descriptor: number | undefined\n try {\n descriptor = openSync(path, 'r')\n fsyncSync(descriptor)\n } catch (error) {\n const code = typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined\n if (!['EISDIR', 'EINVAL', 'ENOTSUP', 'EOPNOTSUPP'].includes(String(code))) throw error\n } finally { if (descriptor !== undefined) closeSync(descriptor) }\n}\n\nexport function checkPrivateStoreFile(path: string, create = false): void {\n let descriptor: number\n try {\n descriptor = openSync(path, (create ? constants.O_RDWR : constants.O_RDONLY) | constants.O_NOFOLLOW\n | (create ? constants.O_CREAT : 0), 0o600)\n } catch (error) {\n if (!create && typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') return\n throw error\n }\n try {\n const info = fstatSync(descriptor)\n if (!info.isFile() || (info.mode & 0o077) !== 0\n || (process.getuid !== undefined && info.uid !== process.getuid())) {\n throw new Error(`Receiver file must be owned and private (0600): ${path}`)\n }\n } finally { closeSync(descriptor) }\n}\n\nexport interface PrivateSqliteOptions {\n readonly format: string\n readonly path: string\n}\n\nfunction initializeDatabase(database: DatabaseSync, file: string, format: string): void {\n database.exec('PRAGMA busy_timeout=100')\n const tables = database.prepare(\"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\").all()\n if (tables.length > 0 && tables.every(row => row.name !== 'eventkit_store')) throw new LegacyReceiverStoreError(file)\n if (tables.some(row => row.name === 'eventkit_store')) {\n const columns = database.prepare('PRAGMA table_info(eventkit_store)').all()\n if (columns.every(row => row.name !== 'initialized')) throw new LegacyReceiverStoreError(file)\n const priorFormat = database.prepare('SELECT format FROM eventkit_store WHERE id=1').get()\n if (priorFormat?.format !== format) throw new Error('Receiver store format/namespace mismatch')\n }\n database.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;')\n database.exec('BEGIN IMMEDIATE')\n try {\n database.exec('CREATE TABLE IF NOT EXISTS eventkit_store (id INTEGER PRIMARY KEY CHECK(id=1), format TEXT NOT NULL, initialized INTEGER NOT NULL DEFAULT 0)')\n const prior = database.prepare('SELECT format FROM eventkit_store WHERE id=1').get()\n if (prior !== undefined && prior.format !== format) throw new Error('Receiver store format/namespace mismatch')\n database.prepare('INSERT OR IGNORE INTO eventkit_store(id,format) VALUES(1,?)').run(format)\n database.exec('COMMIT')\n } catch (error) {\n database.exec('ROLLBACK')\n throw error\n }\n}\n\n/** A synchronous commit boundary; no callback may await filesystem/network work. */\nexport function openPrivateSqlite(options: PrivateSqliteOptions) {\n const file = options.path === ':memory:' ? options.path : PATH.resolve(options.path)\n if (file !== ':memory:') {\n ensurePrivateDirectory(PATH.dirname(file))\n checkPrivateStoreFile(file, true)\n checkPrivateStoreFile(`${file}-wal`)\n checkPrivateStoreFile(`${file}-shm`)\n checkPrivateStoreFile(`${file}-journal`)\n }\n const database = new DatabaseSync(file)\n let closed = false\n try {\n initializeDatabase(database, file, options.format)\n if (file !== ':memory:') {\n checkPrivateStoreFile(file)\n checkPrivateStoreFile(`${file}-wal`)\n checkPrivateStoreFile(`${file}-shm`)\n syncPrivateDirectory(PATH.dirname(file))\n }\n } catch (error) {\n database.close()\n throw error\n }\n return {\n database,\n transaction<T>(work: () => T): T {\n if (closed) throw new Error('Receiver store is closed')\n database.exec('BEGIN IMMEDIATE')\n try {\n const result = work()\n if (result !== null && (typeof result === 'object' || typeof result === 'function') && 'then' in result) {\n throw new TypeError('Receiver transactions must be synchronous')\n }\n database.exec('COMMIT')\n return result\n } catch (error) {\n database.exec('ROLLBACK')\n throw error\n }\n },\n close(): void {\n if (closed) return\n database.close()\n closed = true\n },\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport {\n lstat, rename, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type { PendingWake, PublisherOutbox } from '@xyo-network/event-kit-actor'\nimport { WakeEnvelopeSchema, WakeEnvelopeZod } from '@xyo-network/event-kit-schemas'\n\nimport {\n ensureDurableDirectory,\n syncDirectory,\n writeDurableFile,\n} from './filesystemDurability.ts'\nimport { readJsonFileStrict } from './filesystemJson.ts'\nimport { checkPrivateStoreFile, ensurePrivateDirectory } from './privateSqlite.ts'\n\nexport interface FilesystemPublisherOutboxOptions {\n /** Absolute or relative path to the pending-wake JSON file. */\n readonly path: string\n}\n\n/**\n * Durable single-slot publisher outbox.\n *\n * The publisher emits at most one wake per pass, so one slot is enough: the\n * entry is written before the first delivery attempt and cleared only after the\n * cursor advances. A crash in between leaves it on disk, and the next pass\n * retries the same `wakeId`/`issuedAt` \u2014 and therefore the same `eventHash` \u2014\n * under a freshly minted JWT.\n */\nexport function createFilesystemPublisherOutbox(\n options: FilesystemPublisherOutboxOptions,\n): PublisherOutbox {\n const filePath = PATH.resolve(options.path)\n const directory = PATH.dirname(filePath)\n\n return {\n async clear(): Promise<void> {\n if (!await existingPrivateDirectory(directory)) return\n checkPrivateStoreFile(filePath)\n let removed = false\n try {\n await unlink(filePath)\n removed = true\n } catch (error) {\n if (!isNotFound(error)) throw error\n }\n // Sync even an already-absent slot so a retry after a failed sync can\n // finish the original deletion. A missing parent is empty on cold start.\n try {\n await syncDirectory(directory)\n } catch (error) {\n if (removed || !isNotFound(error)) throw error\n }\n },\n\n async load(): Promise<PendingWake | undefined> {\n if (!await existingPrivateDirectory(directory)) return undefined\n checkPrivateStoreFile(filePath)\n const raw = await readJsonFileStrict(filePath)\n if (raw === undefined) return undefined\n const pending = validatePendingWake(raw)\n // A previous save may have renamed successfully before directory sync\n // failed. Finish publishing that exact commitment before allowing retry.\n await syncDirectory(directory)\n return pending\n },\n\n async save(pending: PendingWake): Promise<void> {\n validatePendingWake(pending)\n await ensureDurableDirectory(directory, 0o700)\n ensurePrivateDirectory(directory)\n checkPrivateStoreFile(filePath)\n // Write-then-rename so a crash mid-write cannot leave a partial entry.\n // `rename` is sound here: one writer, and replacing the slot is intended.\n const tempPath = `${filePath}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`\n try {\n await writeDurableFile(tempPath, `${JSON.stringify(pending)}\\n`, 0o600)\n await rename(tempPath, filePath)\n } catch (error) {\n try {\n await unlink(tempPath)\n } catch {\n // An ignored temporary file cannot replace the retained commitment;\n // preserve the original write/publication failure if cleanup fails.\n }\n throw error\n }\n await syncDirectory(directory)\n },\n }\n}\n\n/** The durable envelope schema validates every field of the retained commitment. */\nfunction validatePendingWake(raw: unknown): PendingWake {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)\n || 'schema' in raw || 'deliveryMode' in raw) {\n throw new Error('Invalid pending wake record')\n }\n WakeEnvelopeZod.parse({\n ...raw, schema: WakeEnvelopeSchema, deliveryMode: 'durable',\n })\n // Parsing is validation only: retain the exact persisted commitment fields.\n return raw as PendingWake\n}\n\nfunction isNotFound(error: unknown): boolean {\n return typeof error === 'object'\n && error !== null\n && 'code' in error\n && (error as { code?: unknown }).code === 'ENOENT'\n}\n\nasync function existingPrivateDirectory(directory: string) {\n try {\n await lstat(directory)\n } catch (error) {\n if (isNotFound(error)) return false\n throw error\n }\n ensurePrivateDirectory(directory)\n return true\n}\n", "import { existsSync, readdirSync } from 'node:fs'\nimport PATH from 'node:path'\n\nimport type { AtomicWakeInbox } from '@xyo-network/event-kit-protocol'\n\nimport type { FilesystemWakeQueue } from './filesystemWakeQueue.ts'\nimport { filesystemReceiverAuthority } from './filesystemWakeQueue.ts'\nimport { ensurePrivateDirectory, LegacyReceiverStoreError } from './privateSqlite.ts'\n\nexport interface FilesystemWakeInboxOptions {\n readonly path: string\n /** Must be the coordinated queue created by createFilesystemWakeQueue. */\n readonly queue: FilesystemWakeQueue\n}\nexport interface FilesystemWakeInbox extends AtomicWakeInbox {\n pruneExpiredTokens(nowSeconds: number): Promise<number>\n}\n/** Both identity indexes, stable receipt and exact work share the queue's transaction. */\nexport function createFilesystemWakeInbox(options: FilesystemWakeInboxOptions): FilesystemWakeInbox {\n const root = PATH.resolve(options.path)\n if (['tokens', 'wakes'].some((name) => {\n const directory = PATH.join(root, name)\n return existsSync(directory) && readdirSync(directory).length > 0\n })) throw new LegacyReceiverStoreError(root)\n ensurePrivateDirectory(root)\n const authority = filesystemReceiverAuthority(options.queue)\n return {\n resolveAttempt: authority.inbox.resolveAttempt,\n async commitAuthorized(input) {\n const committed = await authority.inbox.commitAuthorized(input)\n if ('receipt' in committed) await options.queue.repairRow(authority.receiptQueueId(committed.receipt))\n return committed\n },\n pruneExpiredTokens: async nowSeconds => authority.pruneExpiredTokens(nowSeconds),\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport { existsSync, readdirSync } from 'node:fs'\nimport {\n link, open, readdir, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type { WakeQueue } from '@xyo-network/event-kit-protocol'\nimport { parseAdmittedWake, StaleWakeLeaseError } from '@xyo-network/event-kit-protocol'\n\nimport {\n ensureDurableDirectory, syncDirectory, writeDurableFile,\n} from './filesystemDurability.ts'\nimport {\n checkPrivateStoreFile, ensurePrivateDirectory, LegacyReceiverStoreError,\n} from './privateSqlite.ts'\nimport type { ReceiverAuthority, ReceiverQueueRow } from './receiverAuthority.ts'\nimport { openReceiverAuthority } from './receiverAuthority.ts'\n\nexport {\n ensureDurableDirectory, syncDirectory, writeDurableFile,\n}\n\nexport interface FilesystemWakeQueueOptions {\n /** Private directory; receiver.sqlite owns state, JSON files are projections. */\n readonly path: string\n}\nexport interface FilesystemWakeQueue extends WakeQueue {\n close(): void\n repairProjections(): Promise<void>\n repairRow(id: number): Promise<void>\n}\nconst authorities = new WeakMap<FilesystemWakeQueue, ReceiverAuthority>()\nexport function filesystemReceiverAuthority(queue: FilesystemWakeQueue): ReceiverAuthority {\n const authority = authorities.get(queue)\n if (authority === undefined) throw new TypeError('Filesystem inbox requires its coordinated filesystem receiver queue')\n return authority\n}\n\n/** Filesystem-facing receiver with one SQLite admission/lease/completion authority. */\nexport function createFilesystemWakeQueue(options: FilesystemWakeQueueOptions): FilesystemWakeQueue {\n const root = PATH.resolve(options.path)\n const file = PATH.join(root, 'receiver.sqlite')\n if (!existsSync(file) && ['pending', 'inflight', 'tmp'].some((name) => {\n const directory = PATH.join(root, name)\n return existsSync(directory) && readdirSync(directory).length > 0\n })) throw new LegacyReceiverStoreError(root)\n ensurePrivateDirectory(root)\n const pendingDir = PATH.join(root, 'pending')\n const inflightDir = PATH.join(root, 'inflight')\n const tempDir = PATH.join(root, 'tmp')\n for (const directory of [pendingDir, inflightDir, tempDir]) ensurePrivateDirectory(directory)\n const authority = openReceiverAuthority(file)\n\n async function publishProjection(path: string, body: string): Promise<void> {\n // Immutable committed bodies do not need another tempfile/fsync on each lease.\n // Projections may be regenerated from database authority after publication loss.\n if (existsSync(path)) {\n checkPrivateStoreFile(path)\n return\n }\n const temporary = PATH.join(tempDir, `${randomBytes(16).toString('hex')}.json`)\n await writeDurableFile(temporary, body, 0o600)\n try {\n try {\n await link(temporary, path)\n } catch (error) { if (!hasCode(error, 'EEXIST')) throw error }\n await syncDirectory(PATH.dirname(path))\n } finally { await unlinkIfMissing(temporary) }\n }\n async function validateProjection(row: ReceiverQueueRow): Promise<void> {\n if (row.body === null) throw new Error('Receiver work has no committed body')\n const path = PATH.join(pendingDir, `${row.id}.json`)\n checkPrivateStoreFile(path)\n let raw = await readJsonFile<unknown>(path)\n if (raw === undefined) {\n await publishProjection(path, row.body)\n checkPrivateStoreFile(path)\n raw = await readJsonFile<unknown>(path)\n }\n checkPrivateStoreFile(path)\n const projected = await parseAdmittedWake(raw)\n if (JSON.stringify(projected) !== row.body) throw new Error('Filesystem projection differs from committed receiver work')\n }\n async function repairRow(id: number): Promise<void> {\n const row = authority.currentRow(id)\n if (row === undefined) throw new Error('Receiver work record vanished')\n if (row.state === 'completed') {\n await unlinkIfMissing(PATH.join(pendingDir, `${id}.json`))\n } else {\n if (row.body === null) throw new Error('Active receiver work is corrupt')\n await publishProjection(PATH.join(pendingDir, `${id}.json`), row.body)\n if (row.state === 'inflight' && row.lease_token !== null) {\n await publishProjection(PATH.join(inflightDir, `${id}-${row.lease_token}.json`), row.body)\n }\n }\n await syncDirectory(pendingDir)\n }\n async function repairProjections(): Promise<void> {\n for (const row of authority.rows()) {\n if (row.body === null) throw new Error('Active receiver work is corrupt')\n await publishProjection(PATH.join(pendingDir, `${row.id}.json`), row.body)\n if (row.state === 'inflight' && row.lease_token !== null) {\n await publishProjection(PATH.join(inflightDir, `${row.id}-${row.lease_token}.json`), row.body)\n }\n }\n for (const name of await readdir(pendingDir)) {\n const match = /^(\\d+)\\.json$/u.exec(name)\n if (match !== null && authority.currentRow(Number(match[1]))?.state === 'completed') await unlinkIfMissing(PATH.join(pendingDir, name))\n }\n for (const name of await readdir(inflightDir)) {\n const match = /^(\\d+)-([0-9a-f]{32})\\.json$/u.exec(name)\n if (match !== null && authority.currentRow(Number(match[1]))?.lease_token !== match[2]) await unlinkIfMissing(PATH.join(inflightDir, name))\n }\n await syncDirectory(pendingDir)\n await syncDirectory(inflightDir)\n }\n const queue: FilesystemWakeQueue = {\n async append(wake) {\n const id = await authority.append(wake)\n await repairRow(id)\n },\n async claim() {\n const leased = await authority.claim(validateProjection)\n if (leased === undefined) return\n try {\n await repairRow(leased.id)\n if (authority.currentRow(leased.id)?.lease_token !== leased.token) throw new StaleWakeLeaseError()\n } catch (error) {\n try {\n await leased.release()\n } catch (releaseError) {\n throw new AggregateError([error, releaseError], 'Claim projection failed and its lease could not be released', { cause: releaseError })\n }\n throw error\n }\n return {\n wake: leased.wake,\n async ack() {\n await leased.ack()\n await unlinkIfMissing(PATH.join(inflightDir, `${leased.id}-${leased.token}.json`))\n await repairRow(leased.id)\n await syncDirectory(inflightDir)\n },\n async release() {\n await leased.release()\n await unlinkIfMissing(PATH.join(inflightDir, `${leased.id}-${leased.token}.json`))\n await repairRow(leased.id)\n await syncDirectory(inflightDir)\n },\n }\n },\n pendingCount: authority.queue.pendingCount,\n async recoverInflight(options) {\n const moved = await authority.queue.recoverInflight(options)\n await repairProjections()\n return moved\n },\n close: authority.close,\n repairProjections,\n repairRow,\n }\n authorities.set(queue, authority)\n return queue\n}\n\n/** Only open-time absence means an empty optional record. */\nexport async function readJsonFile<T>(path: string): Promise<T | undefined> {\n let handle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (hasCode(error, 'ENOENT')) return undefined\n throw error\n }\n try {\n if ((await handle.stat()).size > 65_536) throw new RangeError('Receiver JSON record exceeds its 64 KiB bound')\n return JSON.parse(await handle.readFile('utf8')) as T\n } finally { await handle.close() }\n}\nasync function unlinkIfMissing(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) { if (!hasCode(error, 'ENOENT')) throw error }\n}\nfunction hasCode(error: unknown, code: string): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && error.code === code\n}\n", "import { Buffer } from 'node:buffer'\nimport { createHash, randomBytes } from 'node:crypto'\n\nimport type {\n AdmittedWake, AtomicWakeInbox, LeasedWake, RecoverInflightOptions,\n WakeAdmissionAttempt, WakeAdmissionReceipt, WakeAttemptResolution, WakeQueue,\n} from '@xyo-network/event-kit-protocol'\nimport { parseAdmittedWake, StaleWakeLeaseError } from '@xyo-network/event-kit-protocol'\nimport {\n HashZod, NonnegativeJsonSafeIntegerZod, NormalizedAddressZod, WakeIdZod, WakeJwtAudienceZod, WakeJwtIdZod,\n} from '@xyo-network/event-kit-schemas'\n\nimport { openPrivateSqlite } from './privateSqlite.ts'\n\nexport interface ReceiverQueueRow {\n readonly body: string | null\n readonly id: number\n readonly lease_token: string | null\n readonly state: 'pending' | 'inflight' | 'completed'\n readonly terminal_operation: 'ack' | 'release' | null\n readonly terminal_token: string | null\n}\n\nexport function receiverIdentity(parts: readonly string[]): string {\n return createHash('sha256').update(JSON.stringify(parts)).digest('hex')\n}\n\nfunction validateAttempt(attempt: WakeAdmissionAttempt): void {\n WakeJwtAudienceZod.parse(attempt.audience)\n NormalizedAddressZod.parse(attempt.publisher)\n WakeIdZod.parse(attempt.wakeId)\n WakeJwtIdZod.parse(attempt.jwtId)\n HashZod.parse(attempt.eventHash)\n NonnegativeJsonSafeIntegerZod.parse(attempt.retainJwtUntil)\n}\n\nfunction boundedBody(wake: AdmittedWake): string {\n const body = JSON.stringify(wake)\n if (Buffer.byteLength(body, 'utf8') > 65_536) throw new RangeError('Receiver work exceeds its 64 KiB bound')\n return body\n}\n\nfunction sameValues(pairs: readonly (readonly [unknown, unknown])[]): boolean {\n return pairs.every(([actual, expected]) => actual === expected)\n}\n\nfunction validateQueueState(row: ReceiverQueueRow): void {\n if (!Number.isSafeInteger(row.id) || row.id < 1) throw new Error('Invalid persisted queue identity')\n if (row.state === 'completed') {\n if (row.body !== null || row.lease_token !== null || row.terminal_operation !== 'ack'\n || row.terminal_token === null || !/^[0-9a-f]{32}$/u.test(row.terminal_token)) throw new Error('Invalid persisted completion state')\n return\n }\n if (typeof row.body !== 'string') throw new Error('Active receiver work has no bounded body')\n if (row.state === 'pending' && row.lease_token === null) return\n if (row.state === 'inflight' && row.lease_token !== null && /^[0-9a-f]{32}$/u.test(row.lease_token)) return\n throw new Error('Invalid persisted lease state')\n}\n\n/** One durable authority for admission, queue transitions and completion. */\nexport function openReceiverAuthority(path: string) {\n const owner = openPrivateSqlite({ path, format: 'event-kit-receiver' })\n const database = owner.database\n const transaction = <T>(work: () => T): T => owner.transaction(work)\n const requiredTables = ['receiver_queue', 'receiver_wakes', 'receiver_tokens']\n try {\n transaction(() => {\n const existingTables = new Set(database.prepare(\"SELECT name FROM sqlite_master WHERE type='table'\").all().map(row => row.name))\n const initialized = database.prepare('SELECT initialized FROM eventkit_store WHERE id=1').get()?.initialized\n if ((initialized !== 0 && initialized !== 1)\n || (initialized === 1 && requiredTables.some(name => !existingTables.has(name)))\n || (initialized === 0 && requiredTables.some(name => existingTables.has(name)))) {\n throw new Error('Incomplete persisted receiver schema; refusing to recreate admission/completion history')\n }\n if (initialized === 1) return\n database.exec(`\n CREATE TABLE IF NOT EXISTS receiver_queue (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n body TEXT,\n state TEXT NOT NULL CHECK(state IN ('pending','inflight','completed')),\n lease_token TEXT,\n terminal_token TEXT,\n terminal_operation TEXT,\n CHECK ((state='inflight' AND lease_token IS NOT NULL) OR (state!='inflight' AND lease_token IS NULL))\n );\n CREATE INDEX IF NOT EXISTS receiver_pending ON receiver_queue(state,id);\n CREATE TABLE IF NOT EXISTS receiver_wakes (\n identity TEXT PRIMARY KEY,\n audience TEXT NOT NULL, publisher TEXT NOT NULL, wake_id TEXT NOT NULL,\n event_hash TEXT NOT NULL, receipt TEXT NOT NULL, authorization TEXT NOT NULL,\n queue_id INTEGER NOT NULL UNIQUE REFERENCES receiver_queue(id)\n );\n CREATE TABLE IF NOT EXISTS receiver_tokens (\n identity TEXT PRIMARY KEY, wake_identity TEXT NOT NULL REFERENCES receiver_wakes(identity),\n event_hash TEXT NOT NULL, wake_id TEXT NOT NULL, retain_until INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS receiver_token_expiry ON receiver_tokens(retain_until);\n `)\n database.prepare('UPDATE eventkit_store SET initialized=1 WHERE id=1').run()\n })\n } catch (error) {\n owner.close()\n throw error\n }\n const boundedRow = `id,state,lease_token,terminal_token,terminal_operation,\n CASE WHEN length(CAST(body AS BLOB)) <= 65536 THEN body ELSE NULL END AS body`\n const pending = database.prepare(`SELECT ${boundedRow} FROM receiver_queue WHERE state='pending' ORDER BY id LIMIT 1`)\n const getRow = database.prepare(`SELECT ${boundedRow} FROM receiver_queue WHERE id=?`)\n const insert = database.prepare(\"INSERT INTO receiver_queue(body,state) VALUES(?,'pending')\")\n const count = database.prepare(\"SELECT COUNT(*) AS total FROM receiver_queue WHERE state='pending'\")\n const wakeKey = (attempt: WakeAdmissionAttempt) => receiverIdentity([attempt.audience, attempt.publisher, attempt.wakeId])\n const tokenKey = (attempt: WakeAdmissionAttempt) => receiverIdentity([attempt.audience, attempt.publisher, attempt.jwtId])\n\n function validateAssociation(row: ReceiverQueueRow, wake?: AdmittedWake): void {\n validateQueueState(row)\n const record = database.prepare('SELECT * FROM receiver_wakes WHERE queue_id=?').get(row.id)\n if (record === undefined) return\n const receipt = JSON.parse(String(record.receipt)) as WakeAdmissionReceipt\n const receiptMatches = sameValues([\n [record.identity, receiverIdentity([String(record.audience), String(record.publisher), String(record.wake_id)])],\n [receipt.id, record.identity],\n [receipt.audience, record.audience],\n [receipt.publisher, record.publisher],\n [receipt.wakeId, record.wake_id],\n [receipt.eventHash, record.event_hash],\n ])\n const wakeMatches = wake === undefined || sameValues([\n [wake.audience, record.audience],\n [wake.publisher, record.publisher],\n [wake.wakeId, record.wake_id],\n [wake.eventHash, record.event_hash],\n ])\n if (!receiptMatches || !wakeMatches) throw new Error('Queued body does not match its admitted identity/receipt')\n }\n async function preparedWork(attempt: WakeAdmissionAttempt): Promise<{ readonly body: string | null; readonly id: number } | undefined> {\n const record = database.prepare('SELECT queue_id FROM receiver_wakes WHERE identity=?').get(wakeKey(attempt))\n if (record === undefined) return undefined\n const row = currentRow(Number(record.queue_id))\n if (row === undefined) throw new Error('Receiver receipt has no work/completion record')\n const wake = row.body === null ? undefined : await parseAdmittedWake(JSON.parse(row.body) as unknown)\n validateAssociation(row, wake)\n return { id: row.id, body: row.body }\n }\n class WorkChanged extends Error {}\n async function validatedTransaction<T>(attempt: WakeAdmissionAttempt, work: (prepared: Awaited<ReturnType<typeof preparedWork>>) => T): Promise<T> {\n for (let tries = 0; tries < 4; tries++) {\n const prepared = await preparedWork(attempt)\n try {\n return transaction(() => work(prepared))\n } catch (error) { if (!(error instanceof WorkChanged)) throw error }\n }\n throw new Error('Receiver work changed during validation; retry admission')\n }\n\n function resolve(attempt: WakeAdmissionAttempt, prepared: Awaited<ReturnType<typeof preparedWork>>): WakeAttemptResolution {\n const token = database.prepare('SELECT * FROM receiver_tokens WHERE identity=?').get(tokenKey(attempt))\n if (token !== undefined && (token.event_hash !== attempt.eventHash || token.wake_id !== attempt.wakeId)) return { kind: 'jwt-id-collision' }\n const record = database.prepare('SELECT * FROM receiver_wakes WHERE identity=?').get(wakeKey(attempt))\n if (record === undefined) {\n if (token !== undefined) throw new Error('Receiver token points to missing admitted work')\n return { kind: 'new' }\n }\n if (record.event_hash !== attempt.eventHash) return { kind: 'wake-id-collision' }\n const receipt = JSON.parse(String(record.receipt)) as WakeAdmissionReceipt\n if (!sameValues([\n [receipt.id, wakeKey(attempt)],\n [receipt.eventHash, attempt.eventHash],\n [receipt.publisher, attempt.publisher],\n [receipt.audience, attempt.audience],\n [receipt.wakeId, attempt.wakeId],\n ])) {\n throw new Error('Receiver receipt does not match its identity')\n }\n const row = currentRow(Number(record.queue_id))\n if (row === undefined) throw new Error('Receiver receipt has no pending/completed work record')\n validateAssociation(row)\n if (row.state !== 'completed' && (prepared?.id !== row.id || prepared.body !== row.body)) throw new WorkChanged()\n if (token !== undefined && (token.wake_identity !== record.identity || !Number.isSafeInteger(token.retain_until) || Number(token.retain_until) < 0)) {\n throw new Error('Persisted token does not match its admitted work')\n }\n database.prepare(`INSERT INTO receiver_tokens(identity,wake_identity,event_hash,wake_id,retain_until) VALUES(?,?,?,?,?)\n ON CONFLICT(identity) DO UPDATE SET retain_until=MAX(retain_until,excluded.retain_until)`)\n .run(tokenKey(attempt), wakeKey(attempt), attempt.eventHash, attempt.wakeId, attempt.retainJwtUntil)\n return { kind: 'duplicate', receipt }\n }\n\n const inbox: AtomicWakeInbox = {\n async resolveAttempt(attempt) {\n validateAttempt(attempt)\n return await validatedTransaction(attempt, prepared => resolve(attempt, prepared))\n },\n async commitAuthorized(input) {\n validateAttempt(input.attempt)\n const wake = await parseAdmittedWake(input.wake)\n const { attempt, grant } = input\n if (attempt.audience !== wake.audience || attempt.publisher !== wake.publisher || attempt.wakeId !== wake.wakeId\n || attempt.eventHash !== wake.eventHash || attempt.jwtId !== wake.jti\n || grant.grant.authorizationKind !== 'activated-subscription'\n || grant.grant.target !== wake.publisher || grant.grant.deploymentId !== wake.deploymentId\n || grant.grant.queueId !== wake.queueId || grant.grant.filterHash !== wake.event.filterHash\n || grant.grant.authorizationChainId !== wake.event.authorizationChainId || wake.event.deliveryMode !== 'durable') {\n throw new TypeError('Authorized admission does not match its exact wake/identity binding')\n }\n return await validatedTransaction(attempt, (prepared) => {\n const previous = resolve(attempt, prepared)\n if (previous.kind !== 'new') return previous\n const receipt: WakeAdmissionReceipt = Object.freeze({\n audience: attempt.audience,\n eventHash: attempt.eventHash,\n id: wakeKey(attempt),\n publisher: attempt.publisher,\n wakeId: attempt.wakeId,\n })\n const row = insert.run(boundedBody(wake))\n database.prepare('INSERT INTO receiver_wakes(identity,audience,publisher,wake_id,event_hash,receipt,authorization,queue_id) VALUES(?,?,?,?,?,?,?,?)')\n .run(\n wakeKey(attempt),\n attempt.audience,\n attempt.publisher,\n attempt.wakeId,\n attempt.eventHash,\n JSON.stringify(receipt),\n JSON.stringify(grant),\n row.lastInsertRowid,\n )\n database.prepare('INSERT INTO receiver_tokens(identity,wake_identity,event_hash,wake_id,retain_until) VALUES(?,?,?,?,?)')\n .run(tokenKey(attempt), wakeKey(attempt), attempt.eventHash, attempt.wakeId, attempt.retainJwtUntil)\n return { kind: 'enqueued' as const, receipt }\n })\n },\n }\n\n function currentRow(id: number): ReceiverQueueRow | undefined {\n return getRow.get(id) as unknown as ReceiverQueueRow | undefined\n }\n function rows(): readonly ReceiverQueueRow[] {\n return database.prepare(`SELECT ${boundedRow} FROM receiver_queue WHERE state!='completed' ORDER BY id`).all() as unknown as ReceiverQueueRow[]\n }\n function finish(id: number, token: string, operation: 'ack' | 'release'): void {\n transaction(() => {\n const row = currentRow(id)\n if (row?.terminal_token === token && row.terminal_operation === operation) return\n if (row?.state !== 'inflight' || row.lease_token !== token) throw new StaleWakeLeaseError()\n if (operation === 'ack') database.prepare(`UPDATE receiver_queue\n SET state='completed',body=NULL,lease_token=NULL,terminal_token=?,terminal_operation='ack'\n WHERE id=? AND lease_token=?`).run(token, id, token)\n else database.prepare(`UPDATE receiver_queue\n SET state='pending',lease_token=NULL,terminal_token=?,terminal_operation='release'\n WHERE id=? AND lease_token=?`).run(token, id, token)\n })\n }\n async function claim(validate?: (row: ReceiverQueueRow) => Promise<void>): Promise<(LeasedWake & { readonly id: number; readonly token: string }) | undefined> {\n for (;;) {\n const row = pending.get() as unknown as ReceiverQueueRow | undefined\n if (row === undefined) return undefined\n if (typeof row.body !== 'string') throw new Error('Pending receiver work has no body')\n const wake = await parseAdmittedWake(JSON.parse(row.body) as unknown)\n validateAssociation(row, wake)\n await validate?.(row)\n const token = randomBytes(16).toString('hex')\n const won = transaction(() => database.prepare(`UPDATE receiver_queue SET state='inflight',lease_token=?\n WHERE id=? AND state='pending' AND body=?`).run(token, row.id, row.body).changes === 1)\n if (!won) continue\n let completed: 'ack' | 'release' | undefined\n const complete = (operation: 'ack' | 'release') => {\n if (completed !== undefined) {\n if (completed !== operation) throw new StaleWakeLeaseError()\n return\n }\n finish(row.id, token, operation)\n completed = operation\n }\n return {\n id: row.id,\n token,\n wake,\n async ack() { complete('ack') },\n async release() { complete('release') },\n }\n }\n }\n const queue: WakeQueue = {\n async append(wake) {\n const parsed = await parseAdmittedWake(wake)\n transaction(() => insert.run(boundedBody(parsed)))\n },\n claim: () => claim(),\n pendingCount: async () => Number(count.get()?.total),\n async recoverInflight(options: RecoverInflightOptions) {\n if (options?.consumersStopped !== true) throw new TypeError('Recovery requires all consumers to be stopped')\n return transaction(() => Number(database.prepare(\"UPDATE receiver_queue SET state='pending',lease_token=NULL WHERE state='inflight'\").run().changes))\n },\n }\n return {\n queue,\n inbox,\n database,\n claim,\n currentRow,\n rows,\n async append(wake: AdmittedWake): Promise<number> {\n const parsed = await parseAdmittedWake(wake)\n return transaction(() => Number(insert.run(boundedBody(parsed)).lastInsertRowid))\n },\n receiptQueueId(receipt: WakeAdmissionReceipt): number {\n const row = database.prepare('SELECT queue_id FROM receiver_wakes WHERE identity=?').get(receipt.id)\n if (row === undefined) throw new Error('Committed receipt has no work/completion record')\n return Number(row.queue_id)\n },\n close: () => owner.close(),\n pruneExpiredTokens(nowSeconds: number): number {\n NonnegativeJsonSafeIntegerZod.parse(nowSeconds)\n return transaction(() => Number(database.prepare('DELETE FROM receiver_tokens WHERE retain_until<=?').run(nowSeconds).changes))\n },\n }\n}\n\nexport type ReceiverAuthority = ReturnType<typeof openReceiverAuthority>\n", "import PATH from 'node:path'\n\nimport type {\n EventKitReplayCheckpoint,\n EventKitReplayCheckpointStore,\n} from '@xyo-network/event-kit-statement-graph'\n\nimport { readJsonFileStrict, replaceJsonFile } from './filesystemJson.ts'\n\nexport interface FilesystemEventKitReplayCheckpointStoreOptions {\n /** JSON file atomically replaced after every committed replay block. */\n readonly path: string\n}\n\n/** Single-process durable replay checkpoint store with crash-atomic replacement. */\nexport function createFilesystemEventKitReplayCheckpointStore(\n options: FilesystemEventKitReplayCheckpointStoreOptions,\n): EventKitReplayCheckpointStore {\n const path = PATH.resolve(options.path)\n let tail: Promise<unknown> = Promise.resolve()\n\n return {\n async load(): Promise<unknown> {\n await tail\n return await readJsonFileStrict(path)\n },\n\n async save(checkpoint: EventKitReplayCheckpoint): Promise<void> {\n const previous = tail\n const save = (async () => {\n await previous\n await replaceJsonFile(path, checkpoint)\n })()\n tail = (async () => {\n try {\n await save\n } catch {\n return false\n }\n })()\n await save\n },\n }\n}\n", "import { createHash } from 'node:crypto'\nimport PATH from 'node:path'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type {\n FinalizedStatementPublicationIntent,\n FinalizedStatementPublicationJournal,\n FinalizedStatementPublicationRecord,\n} from '@xyo-network/event-kit-xl1'\n\nimport {\n publishJsonFile, readJsonFileStrict, stringifyJson,\n} from './filesystemJson.ts'\n\nconst PublicationPhases = [\n 'signed',\n 'content-written',\n 'content-verified',\n 'broadcast',\n 'included',\n 'finalized',\n] as const satisfies readonly FinalizedStatementPublicationRecord['phase'][]\n\nconst PublicationPhaseSet = new Set<FinalizedStatementPublicationRecord['phase']>(PublicationPhases)\n\nexport interface FilesystemFinalizedStatementPublicationJournalOptions {\n /** Directory receiving immutable intent-bound publication phase records. */\n readonly path: string\n}\n\nfunction sameStrings(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n\nfunction assertIntentShape(intent: FinalizedStatementPublicationIntent): void {\n if (typeof intent.operationId !== 'string' || intent.operationId.length === 0 || intent.operationId.length > 256) {\n throw new TypeError('publication operationId must be a nonempty string of at most 256 characters')\n }\n if (!/^[0-9a-f]{40}$/u.test(intent.source)) {\n throw new TypeError('publication source must be a canonical 20-byte lowercase hexadecimal address')\n }\n if (!/^[0-9a-f]{40}$/u.test(intent.chainId)) {\n throw new TypeError('publication chainId must be a canonical 20-byte lowercase hexadecimal chain id')\n }\n if ([...intent.eventHashes, ...intent.attachmentHashes].some(hash => !/^[0-9a-f]{64}$/u.test(hash))) {\n throw new TypeError('publication intent hashes must be 32-byte lowercase hexadecimal')\n }\n}\n\nfunction sameIntent(\n left: FinalizedStatementPublicationIntent,\n right: FinalizedStatementPublicationIntent,\n): boolean {\n return left.operationId === right.operationId\n && left.source === right.source\n && left.chainId === right.chainId\n && sameStrings(left.eventHashes, right.eventHashes)\n && sameStrings(left.attachmentHashes, right.attachmentHashes)\n}\n\nfunction intentFromRecord(record: FinalizedStatementPublicationRecord): FinalizedStatementPublicationIntent {\n return {\n attachmentHashes: record.attachmentHashes,\n chainId: record.chainId,\n eventHashes: record.eventHashes,\n operationId: record.operationId,\n source: record.source,\n }\n}\n\nfunction publicationDirectory(root: string, intent: FinalizedStatementPublicationIntent): string {\n const key = createHash('sha256')\n .update(stringifyJson({\n chainId: intent.chainId, operationId: intent.operationId, source: intent.source,\n }))\n .digest('hex')\n return PATH.join(root, key)\n}\n\nfunction asPublicationRecord(value: unknown, path: string): FinalizedStatementPublicationRecord {\n if (typeof value !== 'object' || value === null) throw new Error(`malformed publication journal record at ${path}`)\n const record = value as FinalizedStatementPublicationRecord\n if (!PublicationPhaseSet.has(record.phase)) throw new Error(`unknown publication phase at ${path}`)\n return record\n}\n\nfunction assertBoundRecord(\n record: FinalizedStatementPublicationRecord,\n intent: FinalizedStatementPublicationIntent,\n signed: FinalizedStatementPublicationRecord,\n): void {\n if (!sameIntent(intentFromRecord(record), intent)) throw new Error('publication journal intent collision')\n if (!isDeepStrictEqual(record.evidence, signed.evidence)) {\n throw new Error('publication journal evidence collision')\n }\n}\n\n/**\n * Crash-safe append-only publication journal.\n *\n * The first `signed` record atomically binds a source/operation id to exact\n * ordered event and attachment hashes plus one signed transaction. Repeated\n * identical phases are idempotent; every collision fails closed.\n */\nexport function createFilesystemFinalizedStatementPublicationJournal(\n options: FilesystemFinalizedStatementPublicationJournalOptions,\n): FinalizedStatementPublicationJournal {\n const root = PATH.resolve(options.path)\n\n return {\n async load(intent: FinalizedStatementPublicationIntent): Promise<FinalizedStatementPublicationRecord | undefined> {\n assertIntentShape(intent)\n const directory = publicationDirectory(root, intent)\n const intentPath = PATH.join(directory, 'intent.json')\n const rawSigned = await readJsonFileStrict(intentPath)\n if (rawSigned === undefined) return undefined\n const signed = asPublicationRecord(rawSigned, intentPath)\n if (signed.phase !== 'signed') throw new Error(`publication intent record is not signed at ${intentPath}`)\n assertBoundRecord(signed, intent, signed)\n\n let latest = signed\n for (const phase of PublicationPhases.slice(1)) {\n const path = PATH.join(directory, `${phase}.json`)\n const rawRecord = await readJsonFileStrict(path)\n if (rawRecord === undefined) continue\n const record = asPublicationRecord(rawRecord, path)\n if (record.phase !== phase) throw new Error(`publication phase/path mismatch at ${path}`)\n assertBoundRecord(record, intent, signed)\n latest = record\n }\n return latest\n },\n async save(record: FinalizedStatementPublicationRecord): Promise<void> {\n const intent = intentFromRecord(record)\n assertIntentShape(intent)\n if (!/^[0-9a-f]{64}$/u.test(record.evidence.transactionHash)) {\n throw new TypeError('publication transaction hash must be 32-byte lowercase hex')\n }\n if (!PublicationPhaseSet.has(record.phase)) throw new TypeError('unknown publication phase')\n const directory = publicationDirectory(root, intent)\n const intentPath = PATH.join(directory, 'intent.json')\n\n if (record.phase === 'signed') {\n if (await publishJsonFile(intentPath, record)) return\n const existing = asPublicationRecord(await readJsonFileStrict(intentPath), intentPath)\n if (!isDeepStrictEqual(existing, record)) {\n if (!sameIntent(intentFromRecord(existing), intent)) throw new Error('publication journal intent collision')\n throw new Error('publication journal evidence collision')\n }\n return\n }\n\n const rawSigned = await readJsonFileStrict(intentPath)\n if (rawSigned === undefined) throw new Error('publication journal must bind signed evidence first')\n const signed = asPublicationRecord(rawSigned, intentPath)\n if (signed.phase !== 'signed') throw new Error(`publication intent record is not signed at ${intentPath}`)\n assertBoundRecord(record, intent, signed)\n\n const path = PATH.join(directory, `${record.phase}.json`)\n if (await publishJsonFile(path, record)) return\n\n const existing = asPublicationRecord(await readJsonFileStrict(path), path)\n if (!isDeepStrictEqual(existing, record)) {\n throw new Error(`publication journal collision at ${record.operationId}/${record.phase}`)\n }\n },\n }\n}\n", "import { stat } from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport { publishJsonFile, readJsonFileStrict } from './filesystemJson.ts'\nimport type {\n HandshakeMutationIntent,\n HandshakeMutationIntentLookup,\n HandshakeMutationIntentStore,\n} from './handshakeMutationIntent.ts'\nimport {\n assertSameIntentBinding,\n parseHandshakeMutationIntent,\n parseHandshakeMutationIntentLookup,\n} from './handshakeMutationIntent.ts'\n\nexport interface FilesystemHandshakeMutationIntentStoreOptions {\n /** Directory containing immutable source/kind/operation intent records. */\n readonly path: string\n}\n\n/**\n * Atomic first-writer-wins persistence for exact handshake mutation artifacts.\n * Every record is private because publisher service intents contain HPKE private\n * keys; subscription records still contain ciphertext only, never plaintext.\n */\nexport function createFilesystemHandshakeMutationIntentStore(\n options: FilesystemHandshakeMutationIntentStoreOptions,\n): HandshakeMutationIntentStore {\n const root = PATH.resolve(options.path)\n\n function pathFor(rawLookup: HandshakeMutationIntentLookup): string {\n const lookup = parseHandshakeMutationIntentLookup(rawLookup)\n return PATH.join(\n root,\n lookup.chainId,\n lookup.publisher,\n lookup.source,\n lookup.kind,\n `${lookup.operationId}.json`,\n )\n }\n\n async function readIntent(\n lookup: HandshakeMutationIntentLookup,\n ): Promise<HandshakeMutationIntent | undefined> {\n const path = pathFor(lookup)\n const raw = await readJsonFileStrict(path)\n if (raw === undefined) return undefined\n const intent = await parseHandshakeMutationIntent(raw)\n const parsedLookup = parseHandshakeMutationIntentLookup(lookup)\n if (intent.chainId !== parsedLookup.chainId\n || intent.kind !== parsedLookup.kind\n || intent.operationId !== parsedLookup.operationId\n || intent.publisher !== parsedLookup.publisher\n || intent.source !== parsedLookup.source) {\n throw new Error('handshake mutation intent does not match its immutable path')\n }\n const metadata = await stat(path)\n if ((metadata.mode & 0o077) !== 0) throw new Error('handshake mutation intent permissions are too broad')\n return intent\n }\n\n return {\n get: async lookup => await readIntent(parseHandshakeMutationIntentLookup(lookup)),\n\n async getOrCreate(rawIntent) {\n const proposed = await parseHandshakeMutationIntent(rawIntent) as typeof rawIntent\n const path = pathFor(proposed)\n const created = await publishJsonFile(path, proposed, { directoryMode: 0o700, mode: 0o600 })\n const winner = await readIntent(proposed)\n if (winner === undefined) throw new Error('handshake mutation intent winner vanished')\n assertSameIntentBinding(winner, proposed)\n return Object.freeze({\n disposition: created ? 'created' as const : 'resumed' as const,\n intent: winner as typeof rawIntent,\n })\n },\n }\n}\n", "import {\n canonicalJsonBytes,\n handshakeObjectHash,\n} from '@xyo-network/event-kit-protocol'\nimport type {\n ChainId,\n Hash,\n NormalizedAddress,\n} from '@xyo-network/event-kit-schemas'\nimport {\n Base64Url32BytesZod,\n ChainIdZod,\n EncryptedWakeSubscriptionZod,\n EndpointChallengeResponseZod,\n EndpointChallengeZod,\n HandshakeIdZod,\n HashZod,\n NormalizedAddressZod,\n PublisherEncryptionKeyRevocationZod,\n PublisherEncryptionKeyZod,\n PublisherServiceRevocationZod,\n PublisherServiceZod,\n WakeGrantObjectZod,\n WakeGrantRevocationZod,\n WakeSubscriptionAcceptanceZod,\n WakeSubscriptionRevocationZod,\n} from '@xyo-network/event-kit-schemas'\nimport { z } from 'zod'\n\nexport const HandshakeMutationIntentKinds = [\n 'publisher-encryption-key-retire',\n 'publisher-service-publish',\n 'publisher-service-retire',\n 'publisher-service-rotate-key',\n 'publisher-subscription-accept',\n 'subscriber-grant-revoke',\n 'subscriber-subscription-revoke',\n 'subscriber-subscription-subscribe',\n] as const\n\nexport type HandshakeMutationIntentKind = typeof HandshakeMutationIntentKinds[number]\nexport type HandshakeMutationIntentDisposition = 'created' | 'resumed'\n\nconst HandshakeMutationIntentKindZod = z.enum(HandshakeMutationIntentKinds)\nconst HandshakeMutationOperationIdZod = z.union([HandshakeIdZod, HashZod])\nconst WakeSubscriptionPrivateKeyZod = z.strictObject({\n encryptionKey: HashZod,\n keyId: HandshakeIdZod,\n privateKey: Base64Url32BytesZod,\n})\n\nconst IntentBaseFields = {\n chainId: ChainIdZod,\n operationId: HandshakeMutationOperationIdZod,\n publisher: NormalizedAddressZod,\n requestFingerprint: HashZod,\n source: NormalizedAddressZod,\n version: z.literal(1),\n} as const\n\nconst PublisherServicePublishIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('publisher-service-publish'),\n operationId: HandshakeIdZod,\n encryptionKey: PublisherEncryptionKeyZod,\n privateKey: WakeSubscriptionPrivateKeyZod,\n service: PublisherServiceZod,\n})\n\nconst PublisherServiceRotateKeyIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('publisher-service-rotate-key'),\n operationId: HandshakeIdZod,\n encryptionKey: PublisherEncryptionKeyZod,\n privateKey: WakeSubscriptionPrivateKeyZod,\n selectedKey: HashZod,\n selectedService: HashZod,\n service: PublisherServiceZod,\n})\n\nconst SubscriberSubscriptionIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('subscriber-subscription-subscribe'),\n operationId: HandshakeIdZod,\n encryptionKey: PublisherEncryptionKeyZod,\n grant: WakeGrantObjectZod,\n selectedKey: HashZod,\n selectedService: HashZod,\n service: PublisherServiceZod,\n subscription: EncryptedWakeSubscriptionZod,\n})\n\nconst PublisherAcceptanceIntentZod = z.strictObject({\n ...IntentBaseFields,\n acceptance: WakeSubscriptionAcceptanceZod,\n challenge: EndpointChallengeZod,\n kind: z.literal('publisher-subscription-accept'),\n operationId: HashZod,\n response: EndpointChallengeResponseZod,\n})\n\nconst PublisherServiceRetireIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('publisher-service-retire'),\n operationId: HashZod,\n revocation: PublisherServiceRevocationZod,\n})\n\nconst PublisherEncryptionKeyRetireIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('publisher-encryption-key-retire'),\n operationId: HashZod,\n revocation: PublisherEncryptionKeyRevocationZod,\n})\n\nconst SubscriberGrantRevokeIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('subscriber-grant-revoke'),\n operationId: HashZod,\n revocation: WakeGrantRevocationZod,\n})\n\nconst SubscriberSubscriptionRevokeIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('subscriber-subscription-revoke'),\n operationId: HashZod,\n revocation: WakeSubscriptionRevocationZod,\n})\n\nexport const HandshakeMutationIntentZod = z.discriminatedUnion('kind', [\n PublisherEncryptionKeyRetireIntentZod,\n PublisherServicePublishIntentZod,\n PublisherServiceRetireIntentZod,\n PublisherServiceRotateKeyIntentZod,\n PublisherAcceptanceIntentZod,\n SubscriberGrantRevokeIntentZod,\n SubscriberSubscriptionRevokeIntentZod,\n SubscriberSubscriptionIntentZod,\n])\n\nexport type HandshakeMutationIntent = z.infer<typeof HandshakeMutationIntentZod>\nexport type PublisherServicePublishIntent = z.infer<typeof PublisherServicePublishIntentZod>\nexport type PublisherServiceRotateKeyIntent = z.infer<typeof PublisherServiceRotateKeyIntentZod>\nexport type SubscriberSubscriptionIntent = z.infer<typeof SubscriberSubscriptionIntentZod>\nexport type PublisherAcceptanceIntent = z.infer<typeof PublisherAcceptanceIntentZod>\nexport type PublisherServiceRetireIntent = z.infer<typeof PublisherServiceRetireIntentZod>\nexport type PublisherEncryptionKeyRetireIntent = z.infer<typeof PublisherEncryptionKeyRetireIntentZod>\nexport type SubscriberGrantRevokeIntent = z.infer<typeof SubscriberGrantRevokeIntentZod>\nexport type SubscriberSubscriptionRevokeIntent = z.infer<typeof SubscriberSubscriptionRevokeIntentZod>\n\nexport interface HandshakeMutationIntentLookup {\n readonly chainId: ChainId\n readonly kind: HandshakeMutationIntentKind\n readonly operationId: string\n readonly publisher: NormalizedAddress\n readonly source: NormalizedAddress\n}\n\nexport interface HandshakeMutationIntentResolution<TIntent extends HandshakeMutationIntent = HandshakeMutationIntent> {\n readonly disposition: HandshakeMutationIntentDisposition\n readonly intent: TIntent\n}\n\n/** Durable, first-writer-wins boundary for exact logical handshake mutations. */\nexport interface HandshakeMutationIntentStore {\n get(lookup: HandshakeMutationIntentLookup): Promise<HandshakeMutationIntent | undefined>\n getOrCreate<TIntent extends HandshakeMutationIntent>(\n intent: TIntent,\n ): Promise<HandshakeMutationIntentResolution<TIntent>>\n}\n\n/** Stable error for reuse of one operation ID with different request or chain context. */\nexport class HandshakeMutationIntentConflictError extends Error {\n constructor(message = 'Handshake mutation operation ID is already bound to different intent') {\n super(message)\n this.name = 'HandshakeMutationIntentConflictError'\n }\n}\n\n/** SHA-256 over the canonical private/public caller-input representation. */\nexport async function handshakeMutationRequestFingerprint(value: unknown): Promise<Hash> {\n const canonical = canonicalJsonBytes(value)\n const digestInput = new Uint8Array(canonical.byteLength)\n digestInput.set(canonical)\n const digest = await globalThis.crypto.subtle.digest('SHA-256', digestInput)\n const hex = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')\n return HashZod.parse(hex)\n}\n\nexport function parseHandshakeMutationIntentLookup(value: HandshakeMutationIntentLookup): HandshakeMutationIntentLookup {\n return Object.freeze({\n chainId: ChainIdZod.parse(value.chainId),\n kind: HandshakeMutationIntentKindZod.parse(value.kind),\n operationId: HandshakeMutationOperationIdZod.parse(value.operationId),\n publisher: NormalizedAddressZod.parse(value.publisher),\n source: NormalizedAddressZod.parse(value.source),\n })\n}\n\n/** Strictly validates an intent and recomputes every canonical object binding. */\nexport async function parseHandshakeMutationIntent(value: unknown): Promise<HandshakeMutationIntent> {\n const intent = HandshakeMutationIntentZod.parse(value)\n await assertIntentIntegrity(intent)\n return Object.freeze(intent)\n}\n\n/** In-memory first-writer-wins adapter for focused tests and ephemeral composition. */\nexport function createMemoryHandshakeMutationIntentStore(): HandshakeMutationIntentStore {\n const intents = new Map<string, HandshakeMutationIntent>()\n return {\n async get(rawLookup) {\n const lookup = parseHandshakeMutationIntentLookup(rawLookup)\n return intents.get(intentLookupKey(lookup))\n },\n async getOrCreate(rawIntent) {\n const proposed = await parseHandshakeMutationIntent(rawIntent) as typeof rawIntent\n const key = intentLookupKey(proposed)\n const existing = intents.get(key)\n if (existing === undefined) {\n intents.set(key, proposed)\n return Object.freeze({ disposition: 'created' as const, intent: proposed })\n }\n assertSameIntentBinding(existing, proposed)\n return Object.freeze({ disposition: 'resumed' as const, intent: existing as typeof rawIntent })\n },\n }\n}\n\nexport function intentLookupKey(lookup: HandshakeMutationIntentLookup): string {\n const parsed = parseHandshakeMutationIntentLookup(lookup)\n return [parsed.chainId, parsed.publisher, parsed.source, parsed.kind, parsed.operationId].join('/')\n}\n\nexport function assertSameIntentBinding(left: HandshakeMutationIntent, right: HandshakeMutationIntent): void {\n const shared = left.version === right.version\n && left.chainId === right.chainId\n && left.kind === right.kind\n && left.operationId === right.operationId\n && left.publisher === right.publisher\n && left.source === right.source\n && left.requestFingerprint === right.requestFingerprint\n const bothRotate = left.kind === 'publisher-service-rotate-key'\n && right.kind === 'publisher-service-rotate-key'\n const bothSubscribe = left.kind === 'subscriber-subscription-subscribe'\n && right.kind === 'subscriber-subscription-subscribe'\n const selected = bothRotate || bothSubscribe\n ? left.selectedService === right.selectedService && left.selectedKey === right.selectedKey\n : !('selectedService' in left) && !('selectedService' in right)\n if (!shared || !selected) throw new HandshakeMutationIntentConflictError()\n}\n\nasync function assertIntentIntegrity(intent: HandshakeMutationIntent): Promise<void> {\n if (intent.kind.startsWith('publisher-') && intent.source !== intent.publisher) {\n throw new TypeError('Publisher mutation intent source must equal publisher')\n }\n if (intent.kind === 'publisher-service-publish' || intent.kind === 'publisher-service-rotate-key') {\n await assertPublisherServiceIntent(intent)\n return\n }\n if (intent.kind === 'subscriber-subscription-subscribe') {\n await assertSubscriberSubscriptionIntent(intent)\n return\n }\n if (intent.kind === 'publisher-subscription-accept') {\n await assertPublisherAcceptanceIntent(intent)\n return\n }\n await assertRevocationIntent(intent)\n}\n\nasync function assertPublisherServiceIntent(\n intent: PublisherServicePublishIntent | PublisherServiceRotateKeyIntent,\n): Promise<void> {\n const keyHash = await handshakeObjectHash(intent.encryptionKey)\n if (intent.privateKey.encryptionKey !== keyHash\n || intent.privateKey.keyId !== intent.encryptionKey.keyId\n || intent.service.preferredEncryptionKey !== keyHash\n || intent.service.encryptionKeys.length !== 1\n || intent.service.encryptionKeys[0] !== keyHash) {\n throw new TypeError('Publisher service mutation intent has inconsistent encryption-key artifacts')\n }\n if (intent.kind === 'publisher-service-publish') {\n if (intent.service.revision !== 1 || intent.service.supersedes !== undefined) {\n throw new TypeError('Publisher service root intent must contain a root service revision')\n }\n } else if (intent.service.supersedes !== intent.selectedService || intent.service.revision <= 1) {\n throw new TypeError('Publisher service rotation intent does not extend its selected service')\n }\n}\n\nasync function assertSubscriberSubscriptionIntent(intent: SubscriberSubscriptionIntent): Promise<void> {\n const [keyHash, serviceHash, grantHash] = await Promise.all([\n handshakeObjectHash(intent.encryptionKey),\n handshakeObjectHash(intent.service),\n handshakeObjectHash(intent.grant),\n ])\n if (keyHash !== intent.selectedKey\n || serviceHash !== intent.selectedService\n || intent.service.preferredEncryptionKey !== keyHash\n || !intent.service.encryptionKeys.includes(keyHash)\n || intent.grant.publisher !== intent.publisher\n || intent.subscription.publisher !== intent.publisher\n || intent.subscription.service !== serviceHash\n || intent.subscription.encryptionKey !== keyHash\n || intent.subscription.keyId !== intent.encryptionKey.keyId\n || intent.subscription.grant !== grantHash) {\n throw new TypeError('Subscriber subscription intent has inconsistent public artifacts')\n }\n}\n\nasync function assertPublisherAcceptanceIntent(intent: PublisherAcceptanceIntent): Promise<void> {\n const [challengeHash, responseHash] = await Promise.all([\n handshakeObjectHash(intent.challenge),\n handshakeObjectHash(intent.response),\n ])\n if (challengeHash !== intent.operationId\n || intent.challenge.publisher !== intent.publisher\n || intent.response.challenge !== challengeHash\n || intent.acceptance.challenge !== challengeHash\n || intent.acceptance.response !== responseHash\n || intent.acceptance.service !== intent.challenge.service\n || intent.acceptance.encryptionKey !== intent.challenge.encryptionKey\n || intent.acceptance.grant !== intent.challenge.grant\n || intent.acceptance.subscription !== intent.challenge.subscription) {\n throw new TypeError('Publisher acceptance intent has inconsistent public artifacts')\n }\n}\n\nasync function assertRevocationIntent(\n intent:\n | PublisherEncryptionKeyRetireIntent\n | PublisherServiceRetireIntent\n | SubscriberGrantRevokeIntent\n | SubscriberSubscriptionRevokeIntent,\n): Promise<void> {\n const target = intent.kind === 'publisher-encryption-key-retire'\n ? intent.revocation.key\n : intent.kind === 'publisher-service-retire'\n ? intent.revocation.service\n : intent.kind === 'subscriber-grant-revoke'\n ? intent.revocation.grant\n : intent.revocation.subscription\n if (target !== intent.operationId) {\n throw new TypeError('Handshake revocation intent has inconsistent target binding')\n }\n}\n", "import { stat } from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type {\n PublisherEncryptionKeyLookup,\n PublisherEncryptionKeyStore,\n WakeSubscriptionPrivateKey,\n} from '@xyo-network/event-kit-protocol'\nimport {\n Base64Url32BytesZod,\n HandshakeIdZod,\n HashZod,\n NormalizedAddressZod,\n} from '@xyo-network/event-kit-schemas'\n\nimport {\n publishJsonFile, readJsonFileStrict, stringifyJson,\n} from './filesystemJson.ts'\n\nexport interface FilesystemPublisherEncryptionKeyStoreOptions {\n /** Directory containing immutable publisher-scoped private-key records. */\n readonly path: string\n}\n\nexport interface PutPublisherEncryptionPrivateKeyInput {\n readonly key: WakeSubscriptionPrivateKey\n readonly publisher: string\n}\n\nexport interface FilesystemPublisherEncryptionKeyStore extends PublisherEncryptionKeyStore {\n putPrivateKey: (input: PutPublisherEncryptionPrivateKeyInput) => Promise<'duplicate' | 'stored'>\n}\n\ninterface PrivateKeyRecord extends WakeSubscriptionPrivateKey {\n readonly publisher: string\n}\n\n/** Immutable, exact-key filesystem custody for dedicated HPKE private keys. */\nexport function createFilesystemPublisherEncryptionKeyStore(\n options: FilesystemPublisherEncryptionKeyStoreOptions,\n): FilesystemPublisherEncryptionKeyStore {\n const root = PATH.resolve(options.path)\n\n function parseLookup(lookup: PublisherEncryptionKeyLookup): PublisherEncryptionKeyLookup {\n return {\n encryptionKey: HashZod.parse(lookup.encryptionKey),\n keyId: HandshakeIdZod.parse(lookup.keyId),\n publisher: NormalizedAddressZod.parse(lookup.publisher),\n }\n }\n\n function pathFor(lookup: PublisherEncryptionKeyLookup): string {\n return PATH.join(root, lookup.publisher, `${lookup.encryptionKey}-${lookup.keyId}.json`)\n }\n\n function keyIdPath(lookup: PublisherEncryptionKeyLookup): string {\n return PATH.join(root, lookup.publisher, 'key-ids', `${lookup.keyId}.json`)\n }\n\n async function readRecord(lookup: PublisherEncryptionKeyLookup): Promise<PrivateKeyRecord | undefined> {\n const path = pathFor(lookup)\n const raw = await readJsonFileStrict(path)\n if (raw === undefined) return undefined\n const parsed = parsePrivateKeyRecord(raw)\n if (\n parsed.publisher !== lookup.publisher\n || parsed.encryptionKey !== lookup.encryptionKey\n || parsed.keyId !== lookup.keyId\n ) throw new Error('publisher encryption-key record does not match its immutable path')\n const keyIdRecord = parseKeyIdRecord(await readJsonFileStrict(keyIdPath(lookup)))\n if (\n keyIdRecord.publisher !== lookup.publisher\n || keyIdRecord.encryptionKey !== lookup.encryptionKey\n || keyIdRecord.keyId !== lookup.keyId\n ) throw new Error('publisher encryption-key keyId index does not match its immutable path')\n const metadata = await stat(path)\n if ((metadata.mode & 0o077) !== 0) throw new Error('publisher encryption-key record permissions are too broad')\n return parsed\n }\n\n return {\n async getPrivateKey(rawLookup): Promise<WakeSubscriptionPrivateKey | undefined> {\n const lookup = parseLookup(rawLookup)\n const record = await readRecord(lookup)\n if (record === undefined) return undefined\n return Object.freeze({\n encryptionKey: record.encryptionKey,\n keyId: record.keyId,\n privateKey: record.privateKey,\n })\n },\n\n async putPrivateKey(input): Promise<'duplicate' | 'stored'> {\n const record = parsePrivateKeyRecord({ ...input.key, publisher: input.publisher })\n const lookup = parseLookup(record)\n const path = pathFor(lookup)\n const keyIdRecord = {\n encryptionKey: record.encryptionKey,\n keyId: record.keyId,\n publisher: record.publisher,\n }\n if (!await publishJsonFile(\n keyIdPath(lookup),\n keyIdRecord,\n { directoryMode: 0o700, mode: 0o600 },\n )) {\n const existingKeyId = parseKeyIdRecord(await readJsonFileStrict(keyIdPath(lookup)))\n if (stringifyJson(existingKeyId) !== stringifyJson(keyIdRecord)) {\n throw new Error(`publisher encryption-key keyId collision for ${record.keyId}`)\n }\n }\n if (await publishJsonFile(path, record, { directoryMode: 0o700, mode: 0o600 })) return 'stored'\n const existing = await readRecord(lookup)\n if (stringifyJson(existing) !== stringifyJson(record)) {\n throw new Error(`publisher encryption-key collision for ${record.encryptionKey}/${record.keyId}`)\n }\n return 'duplicate'\n },\n }\n}\n\nfunction parseKeyIdRecord(value: unknown): Omit<PrivateKeyRecord, 'privateKey'> {\n if (typeof value !== 'object' || value === null) throw new TypeError('invalid publisher encryption-key keyId record')\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).toSorted()\n if (keys.join('|') !== 'encryptionKey|keyId|publisher') {\n throw new TypeError('invalid publisher encryption-key keyId record shape')\n }\n return {\n encryptionKey: HashZod.parse(record.encryptionKey),\n keyId: HandshakeIdZod.parse(record.keyId),\n publisher: NormalizedAddressZod.parse(record.publisher),\n }\n}\n\nfunction parsePrivateKeyRecord(value: unknown): PrivateKeyRecord {\n if (typeof value !== 'object' || value === null) throw new TypeError('invalid publisher encryption-key record')\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).toSorted()\n if (keys.join('|') !== 'encryptionKey|keyId|privateKey|publisher') {\n throw new TypeError('invalid publisher encryption-key record shape')\n }\n return {\n encryptionKey: HashZod.parse(record.encryptionKey),\n keyId: HandshakeIdZod.parse(record.keyId),\n privateKey: Base64Url32BytesZod.parse(record.privateKey),\n publisher: NormalizedAddressZod.parse(record.publisher),\n }\n}\n", "import PATH from 'node:path'\n\nimport type {\n BeginPublisherEndpointChallengeAttemptResult,\n CompletePublisherEndpointChallengeResult,\n PublisherEndpointChallengeRecord,\n PublisherEndpointChallengeStore,\n} from '@xyo-network/event-kit-protocol'\nimport { endpointChallengeHash } from '@xyo-network/event-kit-protocol'\nimport {\n ChallengeNonceZod,\n EndpointChallengeZod,\n HashZod,\n} from '@xyo-network/event-kit-schemas'\n\nimport {\n publishJsonFile, readJsonFileStrict, stringifyJson,\n} from './filesystemJson.ts'\n\nexport interface FilesystemPublisherEndpointChallengeStoreOptions {\n /** Directory containing immutable issued/attempted/verified state records. */\n readonly path: string\n}\n\ntype ChallengeState = PublisherEndpointChallengeRecord['state']\n\n/**\n * Cross-process, one-attempt challenge state using exclusive immutable files.\n * Each transition is a new hard-link publication; no process overwrites a\n * competing winner and a crash cannot expose a partial state record.\n */\nexport function createFilesystemPublisherEndpointChallengeStore(\n options: FilesystemPublisherEndpointChallengeStoreOptions,\n): PublisherEndpointChallengeStore {\n const root = PATH.resolve(options.path)\n\n function statePath(challengeHash: string, state: ChallengeState): string {\n return PATH.join(root, challengeHash, `${state}.json`)\n }\n\n function noncePath(nonce: string): string {\n return PATH.join(root, 'nonces', `${nonce}.json`)\n }\n\n async function readState(challengeHash: string, state: ChallengeState): Promise<PublisherEndpointChallengeRecord | undefined> {\n const raw = await readJsonFileStrict(statePath(challengeHash, state))\n if (raw === undefined) return undefined\n const record = await parseChallengeRecord(raw, state)\n if (record.challengeHash !== challengeHash) throw new Error('challenge record does not match its immutable path')\n return record\n }\n\n async function current(challengeHash: string): Promise<PublisherEndpointChallengeRecord | undefined> {\n return await readState(challengeHash, 'verified')\n ?? await readState(challengeHash, 'attempted')\n ?? await readState(challengeHash, 'issued')\n }\n\n async function publish(record: PublisherEndpointChallengeRecord): Promise<boolean> {\n return await publishJsonFile(\n statePath(record.challengeHash, record.state),\n record,\n { directoryMode: 0o700, mode: 0o600 },\n )\n }\n\n return {\n async beginAttempt(input): Promise<BeginPublisherEndpointChallengeAttemptResult> {\n const challengeHash = HashZod.parse(input.challengeHash)\n requireTime(input.nowSeconds)\n const observed = await current(challengeHash)\n if (observed === undefined) return { kind: 'missing' }\n if (observed.state === 'verified') return { kind: 'verified', record: observed }\n if (observed.state === 'attempted') return { kind: 'already-attempted', record: observed }\n if (!isLive(observed, input.nowSeconds)) return { kind: 'expired', record: observed }\n\n const attempted: PublisherEndpointChallengeRecord = { ...observed, state: 'attempted' }\n if (await publish(attempted)) return { kind: 'started', record: attempted }\n const winner = await current(challengeHash)\n if (winner === undefined) throw new Error('challenge attempt winner vanished')\n return ({ kind: winner.state === 'verified' ? 'verified' : 'already-attempted', record: winner })\n },\n\n async completeVerified(input): Promise<CompletePublisherEndpointChallengeResult> {\n const challengeHash = HashZod.parse(input.challengeHash)\n const responseHash = HashZod.parse(input.responseHash)\n requireTime(input.nowSeconds)\n const observed = await current(challengeHash)\n if (observed === undefined) return { kind: 'missing' }\n if (observed.state === 'verified') {\n return ({ kind: observed.responseHash === responseHash ? 'duplicate' : 'collision', record: observed })\n }\n if (observed.state !== 'attempted') return { kind: 'not-attempted', record: observed }\n if (!isLive(observed, input.nowSeconds)) return { kind: 'expired', record: observed }\n\n const verified: PublisherEndpointChallengeRecord = {\n ...observed,\n responseHash,\n state: 'verified',\n }\n if (await publish(verified)) return { kind: 'verified', record: verified }\n const winner = await readState(challengeHash, 'verified')\n if (winner === undefined) throw new Error('verified challenge winner vanished')\n return ({ kind: winner.responseHash === responseHash ? 'duplicate' : 'collision', record: winner })\n },\n\n get: async (rawHash): Promise<PublisherEndpointChallengeRecord | undefined> => await current(HashZod.parse(rawHash)),\n\n async issue(input) {\n const challenge = EndpointChallengeZod.parse(input.challenge)\n const challengeHash = HashZod.parse(input.challengeHash)\n if (await endpointChallengeHash(challenge) !== challengeHash) return { kind: 'collision' }\n const nonceRecord = { challengeHash, nonce: challenge.nonce }\n if (!await publishJsonFile(\n noncePath(challenge.nonce),\n nonceRecord,\n { directoryMode: 0o700, mode: 0o600 },\n )) {\n const existingNonce = parseNonceRecord(await readJsonFileStrict(noncePath(challenge.nonce)))\n if (existingNonce.nonce !== challenge.nonce || existingNonce.challengeHash !== challengeHash) {\n return { kind: 'collision' }\n }\n }\n const issued: PublisherEndpointChallengeRecord = {\n challenge, challengeHash, state: 'issued',\n }\n if (await publish(issued)) return { kind: 'issued', record: issued }\n const existing = await current(challengeHash)\n if (existing === undefined) throw new Error('issued challenge winner vanished')\n return sameChallenge(existing, issued)\n ? { kind: 'duplicate', record: existing }\n : { kind: 'collision' }\n },\n }\n}\n\nfunction parseNonceRecord(value: unknown): { readonly challengeHash: string; readonly nonce: string } {\n if (typeof value !== 'object' || value === null) throw new TypeError('invalid endpoint-challenge nonce record')\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).toSorted()\n if (keys.join('|') !== 'challengeHash|nonce') throw new TypeError('invalid endpoint-challenge nonce record shape')\n return {\n challengeHash: HashZod.parse(record.challengeHash),\n nonce: ChallengeNonceZod.parse(record.nonce),\n }\n}\n\nasync function parseChallengeRecord(\n value: unknown,\n expectedState: ChallengeState,\n): Promise<PublisherEndpointChallengeRecord> {\n if (typeof value !== 'object' || value === null) throw new TypeError('invalid endpoint-challenge record')\n const record = value as Record<string, unknown>\n const state = record.state\n if (state !== expectedState) throw new Error('endpoint-challenge record state does not match its path')\n const challenge = EndpointChallengeZod.parse(record.challenge)\n const challengeHash = HashZod.parse(record.challengeHash)\n if (await endpointChallengeHash(challenge) !== challengeHash) throw new Error('endpoint-challenge record hash mismatch')\n if (expectedState === 'verified') {\n return {\n challenge, challengeHash, responseHash: HashZod.parse(record.responseHash), state: expectedState,\n }\n }\n if (record.responseHash !== undefined) throw new TypeError('unverified challenge record contains a response hash')\n return {\n challenge, challengeHash, state: expectedState,\n }\n}\n\nfunction sameChallenge(\n left: PublisherEndpointChallengeRecord,\n right: PublisherEndpointChallengeRecord,\n): boolean {\n return left.challengeHash === right.challengeHash\n && stringifyJson(left.challenge) === stringifyJson(right.challenge)\n}\n\nfunction isLive(record: PublisherEndpointChallengeRecord, nowSeconds: number): boolean {\n return record.challenge.issuedAt <= nowSeconds && nowSeconds < record.challenge.expiresAt\n}\n\nfunction requireTime(value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new TypeError('nowSeconds must be a nonnegative safe integer')\n}\n", "/* eslint-disable max-lines -- Phase 3 keeps the closely coupled public handshake facade in one auditable module. */\nimport type {\n CompletePublisherEndpointChallengeApiResult,\n HashedHandshakeObject,\n PublisherEncryptionKeyStore,\n PublisherEndpointChallengeStore,\n PublisherSubscriptionCandidate,\n PublisherSubscriptionValidationFailureReason,\n WakeSubscriptionPrivateKey,\n} from '@xyo-network/event-kit-protocol'\nimport {\n beginPublisherEndpointChallengeAttempt,\n canonicalJson,\n completePublisherEndpointChallenge,\n createEncryptedWakeSubscription,\n createPublisherEncryptionKeyRevocation,\n createPublisherService,\n createPublisherServiceRevocation,\n createWakeGrant,\n createWakeGrantRevocation,\n createWakeSubscriptionPlaintext,\n createWakeSubscriptionRevocation,\n endpointChallengeMatchesPublisherContext,\n generatePublisherEncryptionKey,\n handshakeObjectHash,\n issuePublisherEndpointChallenge,\n validateAndDecryptPublisherSubscription,\n withHandshakeObjectHash,\n} from '@xyo-network/event-kit-protocol'\nimport type {\n Base64Url32Bytes,\n BestEffortDeliveryPolicy,\n ChainId,\n EncryptedWakeSubscription,\n EndpointChallenge,\n EndpointChallengeResponse,\n HandshakeId,\n Hash,\n NormalizedAddress,\n PublisherEncryptionKey,\n PublisherService,\n WakeDeliveryMode,\n WakeGrantObject,\n WakeSource,\n WakeSubscriptionAcceptance,\n WakeSubscriptionPlaintext,\n} from '@xyo-network/event-kit-schemas'\nimport {\n ChainIdZod, HandshakeIdZod, HashZod, normalizeAddress, NormalizedAddressZod,\n} from '@xyo-network/event-kit-schemas'\nimport type {\n EventKitHandshakeReadModel,\n FinalizedEventKitReplayController,\n FinalizedSubscriptionTuple,\n PublisherAcceptanceCandidate,\n PublisherAcceptanceCandidateDiscovery,\n PublisherHandshakeView,\n PublisherServiceDiscovery,\n PublisherServiceDiscoveryFailure,\n PublisherSubscriptionView,\n ReplayBlockedState,\n SubscriberSubscriptionLookup,\n SubscriberSubscriptionLookupSuccess,\n} from '@xyo-network/event-kit-statement-graph'\nimport { createEventKitHandshakeReadModel } from '@xyo-network/event-kit-statement-graph'\nimport type {\n EventKitChainIdViewer, EventKitNetworkSession, HandshakePublicationResult, HandshakePublicationTransport, PublishPublisherEncryptionKeyRevocationOptions,\n} from '@xyo-network/event-kit-xl1'\nimport {\n assertEventKitNetworkSession,\n publishPublisherEncryptionKeyRevocation,\n publishPublisherService,\n publishPublisherServiceRevocation,\n publishWakeGrantRevocation,\n publishWakeSubscription,\n publishWakeSubscriptionAcceptance,\n publishWakeSubscriptionRevocation,\n} from '@xyo-network/event-kit-xl1'\n\nimport type {\n HandshakeMutationIntent,\n HandshakeMutationIntentDisposition,\n HandshakeMutationIntentKind,\n HandshakeMutationIntentStore,\n PublisherAcceptanceIntent,\n PublisherServicePublishIntent,\n PublisherServiceRotateKeyIntent,\n SubscriberSubscriptionIntent,\n} from './handshakeMutationIntent.ts'\nimport { HandshakeMutationIntentConflictError, handshakeMutationRequestFingerprint } from './handshakeMutationIntent.ts'\nexport type EventKitHandshakeClientErrorCode\n = 'candidate-ambiguous'\n | 'candidate-not-found'\n | 'challenge-context-invalid'\n | 'challenge-not-found'\n | 'challenge-rejected'\n | 'identity-mismatch'\n | 'key-mismatch'\n | 'key-custody-failed'\n | 'mutation-intent-conflict'\n | 'mutation-intent-unavailable'\n | 'projection-blocked'\n | 'projection-stale'\n | 'service-already-exists'\n | 'service-root-requires-fresh-id'\n | 'service-mismatch'\n | 'service-unavailable'\n | 'subscription-invalid'\n | 'subscription-not-found'\n/** Stable, machine-readable failure raised before an unsafe handshake mutation. */\nexport class EventKitHandshakeClientError extends Error {\n readonly code: EventKitHandshakeClientErrorCode\n constructor(code: EventKitHandshakeClientErrorCode, message: string) {\n super(message)\n this.name = 'EventKitHandshakeClientError'\n this.code = code\n }\n}\nexport interface SynchronizedEventKitHandshakeSnapshot {\n readonly blocked?: ReplayBlockedState\n readonly finalizedHead: number\n readonly indexedThrough: number | null\n readonly readModel: EventKitHandshakeReadModel\n}\n/**\n * A publisher-scoped finalized projection. Every call creates a fresh read\n * model after replay synchronization; callers never retain a stale viewer.\n */\nexport interface SynchronizedEventKitHandshakeReader {\n readonly chainId: ChainId\n readonly publisher: NormalizedAddress\n sync(): Promise<SynchronizedEventKitHandshakeSnapshot>\n}\nexport interface CreateSynchronizedEventKitHandshakeReaderOptions {\n /** Live chain identity port; checked both before and after every replay sync. */\n readonly chain: EventKitChainIdViewer\n readonly publisher: string\n readonly replay: FinalizedEventKitReplayController\n readonly session: EventKitNetworkSession\n}\n/** Compose finalized replay with the public Statement Graph handshake model. */\nexport function createSynchronizedEventKitHandshakeReader(options: CreateSynchronizedEventKitHandshakeReaderOptions): SynchronizedEventKitHandshakeReader {\n const publisher = NormalizedAddressZod.parse(options.publisher)\n const chainId = ChainIdZod.parse(options.session.chainId)\n function assertIdentity(): void {\n const checkpoint = options.replay.snapshot()\n if (checkpoint.chainId !== chainId\n || checkpoint.network !== options.session.network\n || checkpoint.publisher !== publisher) {\n throw new EventKitHandshakeClientError('identity-mismatch', 'Finalized replay identity does not match the pinned Event Kit network and publisher')\n }\n }\n return Object.freeze({\n chainId,\n publisher,\n async sync(): Promise<SynchronizedEventKitHandshakeSnapshot> {\n await assertEventKitNetworkSession(options.session, options.chain)\n assertIdentity()\n const status = await options.replay.sync()\n await assertEventKitNetworkSession(options.session, options.chain)\n assertIdentity()\n return Object.freeze({\n ...(status.blocked === undefined ? {} : { blocked: status.blocked }),\n finalizedHead: status.finalizedHead,\n indexedThrough: status.indexedThrough,\n readModel: createEventKitHandshakeReadModel({\n body: hash => options.replay.body(hash),\n viewer: options.replay.viewer(),\n }),\n })\n },\n })\n}\nexport interface EventKitHandshakePublicationPort {\n readonly chainId: ChainId\n publishPublisherEncryptionKeyRevocation(input: Pick<PublishPublisherEncryptionKeyRevocationOptions, 'revocation'> & {\n readonly operationId: string\n }): Promise<HandshakePublicationResult>\n publishPublisherService(input: {\n readonly encryptionKeys: readonly PublisherEncryptionKey[]\n readonly operationId: string\n readonly service: PublisherService\n }): Promise<HandshakePublicationResult>\n publishPublisherServiceRevocation(input: {\n readonly operationId: string\n readonly revocation: ReturnType<typeof createPublisherServiceRevocation>\n }): Promise<HandshakePublicationResult>\n publishWakeGrantRevocation(input: {\n readonly operationId: string\n readonly publisher: NormalizedAddress\n readonly revocation: ReturnType<typeof createWakeGrantRevocation>\n }): Promise<HandshakePublicationResult>\n publishWakeSubscription(input: {\n readonly encryptionKey: PublisherEncryptionKey\n readonly grant: WakeGrantObject\n readonly operationId: string\n readonly service: PublisherService\n readonly subscription: EncryptedWakeSubscription\n }): Promise<HandshakePublicationResult>\n publishWakeSubscriptionAcceptance(input: {\n readonly acceptance: WakeSubscriptionAcceptance\n readonly challenge: EndpointChallenge\n readonly operationId: string\n readonly response: EndpointChallengeResponse\n }): Promise<HandshakePublicationResult>\n publishWakeSubscriptionRevocation(input: {\n readonly operationId: string\n readonly publisher: NormalizedAddress\n readonly revocation: ReturnType<typeof createWakeSubscriptionRevocation>\n }): Promise<HandshakePublicationResult>\n /** Canonical address that will sign the next publication. */\n source(): Promise<NormalizedAddress>\n}\n/** Bind all XL1 writes to one chain-pinned, Mainnet-interlocked transport. */\nexport function createEventKitHandshakePublicationPort(transport: HandshakePublicationTransport): EventKitHandshakePublicationPort {\n const chainId = ChainIdZod.parse(transport.session.chainId)\n const port: EventKitHandshakePublicationPort = {\n chainId,\n publishPublisherEncryptionKeyRevocation: async input => await publishPublisherEncryptionKeyRevocation({ ...transport, ...input }),\n publishPublisherService: async input => await publishPublisherService({ ...transport, ...input }),\n publishPublisherServiceRevocation: async input => await publishPublisherServiceRevocation({ ...transport, ...input }),\n publishWakeGrantRevocation: async input => await publishWakeGrantRevocation({ ...transport, ...input }),\n publishWakeSubscription: async input => await publishWakeSubscription({ ...transport, ...input }),\n publishWakeSubscriptionAcceptance: async input => await publishWakeSubscriptionAcceptance({ ...transport, ...input }),\n publishWakeSubscriptionRevocation: async input => await publishWakeSubscriptionRevocation({ ...transport, ...input }),\n async source(): Promise<NormalizedAddress> {\n const raw = String(await transport.signer.address())\n const normalized = NormalizedAddressZod.parse(normalizeAddress(raw))\n if (raw !== normalized) {\n throw new EventKitHandshakeClientError('identity-mismatch', 'XL1 publication signer address is not canonical lowercase hexadecimal without 0x')\n }\n return normalized\n },\n }\n return Object.freeze(port)\n}\nexport interface PublisherEncryptionKeyCustody extends PublisherEncryptionKeyStore {\n /** Must durably retain the exact private key before resolving. */\n putPrivateKey(input: {\n readonly key: WakeSubscriptionPrivateKey\n readonly publisher: string\n }): Promise<'duplicate' | 'stored'>\n}\nexport interface PublishPublisherServiceInput {\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly deliveryMode: WakeDeliveryMode\n readonly expiresAtBlock?: number\n readonly maxPositionsPerWake: number\n readonly maxSubscriptionLifetimeBlocks: number\n readonly operationId: HandshakeId\n readonly sources: readonly WakeSource[]\n readonly validFromBlock?: number\n}\nexport interface RotatePublisherEncryptionKeyInput {\n readonly expiresAtBlock?: number\n readonly keyExpiresAtBlock?: number\n readonly maxPositionsPerWake?: number\n readonly maxSubscriptionLifetimeBlocks?: number\n readonly operationId: HandshakeId\n /** Exact currently selected service object hash expected by the operator. */\n readonly service: string\n readonly validFromBlock?: number\n}\nexport interface PublisherServicePublicationResult {\n readonly encryptionKey: HashedHandshakeObject<PublisherEncryptionKey>\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly keyCustody: 'duplicate' | 'stored'\n readonly operationId: HandshakeId\n readonly publication: HandshakePublicationResult\n readonly service: HashedHandshakeObject<PublisherService>\n}\nexport interface PublisherServiceRetirementResult {\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly operationId: Hash\n readonly publication: HandshakePublicationResult\n readonly revocation: HashedHandshakeObject<ReturnType<typeof createPublisherServiceRevocation>>\n readonly service: Hash\n}\nexport interface PublisherKeyRetirementResult {\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly key: Hash\n readonly operationId: Hash\n readonly publication: HandshakePublicationResult\n readonly revocation: HashedHandshakeObject<ReturnType<typeof createPublisherEncryptionKeyRevocation>>\n}\nexport interface PublisherSubscriptionSelector {\n readonly subscriber: string\n /** Optional exact object hash; when omitted, exactly one candidate must exist for the stable identity. */\n readonly subscription?: string\n readonly subscriptionId?: string\n}\nexport interface IssuePublisherChallengeInput extends PublisherSubscriptionSelector {\n readonly issuedAt: number\n readonly lifetimeSeconds?: number\n}\nexport interface IssuedPublisherChallenge {\n readonly challenge: EndpointChallenge\n readonly challengeHash: Hash\n readonly disposition: 'duplicate' | 'issued'\n readonly subscriber: NormalizedAddress\n readonly subscription: Hash\n}\n/** Decrypted routing data. It is required for the outbound call and MUST NOT be logged as evidence. */\nexport interface PublisherChallengeDeliveryTarget {\n readonly audience: string\n readonly endpoint: string\n}\nexport type BeginPublisherChallengeResult = {\n readonly challenge: EndpointChallenge\n readonly challengeHash: Hash\n readonly kind: 'started'\n readonly subscriber: NormalizedAddress\n readonly subscription: Hash\n readonly target: PublisherChallengeDeliveryTarget\n} | {\n readonly kind: 'already-attempted' | 'expired' | 'missing' | 'verified'\n}\nexport interface CompletePublisherChallengeInput {\n readonly challengeHash: string\n /** Publisher-local Unix clock, sampled inside the client at the proof-decision boundary. */\n readonly nowSeconds: () => number\n readonly response: EndpointChallengeResponse\n /** Expected Claim source, independently supplied by the caller. */\n readonly subscriber: string\n /** Expected encrypted-subscription object hash, independently supplied by the caller. */\n readonly subscription: string\n}\nexport type PublisherAcceptanceReconciliation = {\n readonly finalizedHead: number\n readonly indexedThrough: number\n readonly lifecycle: PublisherSubscriptionView\n readonly status: 'active' | 'not-active'\n} | {\n readonly finalizedHead: number\n readonly indexedThrough: number\n readonly status: 'not-found'\n} | {\n readonly finalizedHead?: number\n readonly indexedThrough?: number | null\n readonly reason: 'ambiguous-lifecycle' | 'projection-blocked' | 'projection-stale' | 'publication-not-indexed' | 'synchronization-failed' | PublisherServiceDiscoveryFailure['reason']\n readonly status: 'unavailable'\n}\n/** A finalized acceptance publication plus its best-effort post-finality lifecycle reconciliation. */\nexport interface PublisherAcceptancePublicationResult {\n readonly acceptance: HashedHandshakeObject<WakeSubscriptionAcceptance>\n readonly challenge: Hash\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly operationId: Hash\n readonly publication: HandshakePublicationResult\n readonly reconciliation: PublisherAcceptanceReconciliation\n readonly response: Hash\n readonly subscriber: NormalizedAddress\n readonly subscription: Hash\n}\nexport interface PublisherHandshakeClient {\n acceptanceCandidates(selector?: Partial<PublisherSubscriptionSelector>): Promise<PublisherAcceptanceCandidateDiscovery>\n beginChallenge(input: {\n readonly challengeHash: string\n readonly nowSeconds: () => number\n }): Promise<BeginPublisherChallengeResult>\n completeChallengeAndAccept(input: CompletePublisherChallengeInput): Promise<PublisherAcceptancePublicationResult>\n issueChallenge(input: IssuePublisherChallengeInput): Promise<IssuedPublisherChallenge>\n key(): Promise<PublisherServiceDiscovery>\n publishService(input: PublishPublisherServiceInput): Promise<PublisherServicePublicationResult>\n retireEncryptionKey(key: string): Promise<PublisherKeyRetirementResult>\n retireService(service: string): Promise<PublisherServiceRetirementResult>\n rotateEncryptionKey(input: RotatePublisherEncryptionKeyInput): Promise<PublisherServicePublicationResult>\n service(): Promise<PublisherServiceDiscovery>\n subscriptions(): Promise<PublisherHandshakeView>\n}\nexport interface CreatePublisherHandshakeClientOptions {\n readonly challenges: PublisherEndpointChallengeStore\n readonly intents: HandshakeMutationIntentStore\n readonly keys: PublisherEncryptionKeyCustody\n readonly publication: EventKitHandshakePublicationPort\n readonly reader: SynchronizedEventKitHandshakeReader\n readonly serviceId?: string\n}\ninterface ResolvedPublisherCandidate {\n readonly candidate: PublisherAcceptanceCandidate\n readonly validated: Extract<Awaited<ReturnType<typeof validateAndDecryptPublisherSubscription>>, {\n readonly ok: true\n }>\n}\nfunction nextBlock(head: number): number {\n if (!Number.isSafeInteger(head) || head < 0 || head === Number.MAX_SAFE_INTEGER) {\n throw new RangeError('finalized head cannot advance to a JSON-safe block number')\n }\n return head + 1\n}\nfunction samplePublisherClock(nowSeconds: () => number): number {\n const sampled = nowSeconds()\n if (!Number.isSafeInteger(sampled) || sampled < 0) {\n throw new EventKitHandshakeClientError('challenge-rejected', 'Publisher clock must return a nonnegative JSON-safe Unix second')\n }\n return sampled\n}\nfunction readySnapshot(snapshot: SynchronizedEventKitHandshakeSnapshot): SynchronizedEventKitHandshakeSnapshot {\n if (snapshot.blocked !== undefined) {\n throw new EventKitHandshakeClientError('projection-blocked', 'Finalized handshake replay is blocked')\n }\n if (snapshot.indexedThrough !== snapshot.finalizedHead) {\n throw new EventKitHandshakeClientError('projection-stale', 'Finalized handshake replay is not caught up')\n }\n return snapshot\n}\nfunction serviceQuery(reader: SynchronizedEventKitHandshakeReader, snapshot: SynchronizedEventKitHandshakeSnapshot, serviceId?: HandshakeId) {\n return {\n chainId: reader.chainId,\n finalizedHead: snapshot.finalizedHead,\n publisher: reader.publisher,\n ...(serviceId === undefined ? {} : { serviceId }),\n }\n}\nfunction requireService(discovery: PublisherServiceDiscovery): Extract<PublisherServiceDiscovery, {\n readonly ok: true\n}> {\n if (!discovery.ok) {\n throw new EventKitHandshakeClientError('service-unavailable', `Publisher service is unavailable: ${discovery.reason}`)\n }\n return discovery\n}\nfunction requireExpectedService(discovery: Extract<PublisherServiceDiscovery, {\n readonly ok: true\n}>, expected: string): Hash {\n const expectedHash = HashZod.parse(expected)\n if (discovery.service.objectHash !== expectedHash) {\n throw new EventKitHandshakeClientError('service-mismatch', 'Currently selected publisher service does not match the expected object hash')\n }\n return expectedHash\n}\nfunction assertPublicationIdentity(publication: EventKitHandshakePublicationPort, reader: SynchronizedEventKitHandshakeReader): void {\n if (publication.chainId !== reader.chainId) {\n throw new EventKitHandshakeClientError('identity-mismatch', 'Publication transport chain ID does not match the synchronized handshake reader')\n }\n}\nasync function assertPublicationSource(publication: EventKitHandshakePublicationPort, expected: NormalizedAddress): Promise<void> {\n if (await publication.source() !== expected) {\n throw new EventKitHandshakeClientError('identity-mismatch', 'Publication signer does not match the required handshake Claim source')\n }\n}\ntype IntentOfKind<TKind extends HandshakeMutationIntentKind> = Extract<HandshakeMutationIntent, {\n readonly kind: TKind\n}>\nfunction intentLookup<TKind extends HandshakeMutationIntentKind>(reader: SynchronizedEventKitHandshakeReader, kind: TKind, operationId: string, source: NormalizedAddress) {\n return {\n chainId: reader.chainId,\n kind,\n operationId,\n publisher: reader.publisher,\n source,\n }\n}\nfunction mutationIntentError(error: unknown): EventKitHandshakeClientError {\n return error instanceof HandshakeMutationIntentConflictError\n ? new EventKitHandshakeClientError('mutation-intent-conflict', error.message)\n : new EventKitHandshakeClientError('mutation-intent-unavailable', 'Handshake mutation intent storage is unavailable or invalid')\n}\nasync function loadMutationIntent<TKind extends HandshakeMutationIntentKind>(\n store: HandshakeMutationIntentStore,\n reader: SynchronizedEventKitHandshakeReader,\n kind: TKind,\n operationId: string,\n source: NormalizedAddress,\n requestFingerprint: Hash,\n): Promise<IntentOfKind<TKind> | undefined> {\n try {\n const existing = await store.get(intentLookup(reader, kind, operationId, source))\n if (existing === undefined)\n return undefined\n if (existing.kind !== kind || existing.requestFingerprint !== requestFingerprint) {\n throw new HandshakeMutationIntentConflictError()\n }\n return existing as IntentOfKind<TKind>\n } catch (error) {\n throw mutationIntentError(error)\n }\n}\nasync function persistMutationIntent<TIntent extends HandshakeMutationIntent>(store: HandshakeMutationIntentStore, intent: TIntent): Promise<{\n readonly disposition: HandshakeMutationIntentDisposition\n readonly intent: TIntent\n}> {\n try {\n return await store.getOrCreate(intent)\n } catch (error) {\n throw mutationIntentError(error)\n }\n}\nasync function publisherServiceRequestFingerprint(input: PublishPublisherServiceInput): Promise<Hash> {\n return await handshakeMutationRequestFingerprint({\n deliveryMode: input.deliveryMode,\n bestEffort: input.bestEffort ?? null,\n expiresAtBlock: input.expiresAtBlock ?? null,\n maxPositionsPerWake: input.maxPositionsPerWake,\n sources: input.sources,\n maxSubscriptionLifetimeBlocks: input.maxSubscriptionLifetimeBlocks,\n validFromBlock: input.validFromBlock ?? null,\n })\n}\nasync function publisherRotationRequestFingerprint(input: RotatePublisherEncryptionKeyInput): Promise<Hash> {\n return await handshakeMutationRequestFingerprint({\n expiresAtBlock: input.expiresAtBlock ?? null,\n keyExpiresAtBlock: input.keyExpiresAtBlock ?? null,\n maxPositionsPerWake: input.maxPositionsPerWake ?? null,\n maxSubscriptionLifetimeBlocks: input.maxSubscriptionLifetimeBlocks ?? null,\n service: HashZod.parse(input.service),\n validFromBlock: input.validFromBlock ?? null,\n })\n}\nasync function subscriberSubscriptionRequestFingerprint(input: SubscribeToPublisherInput): Promise<Hash> {\n return await handshakeMutationRequestFingerprint({\n deliveryMode: input.deliveryMode,\n bestEffort: input.bestEffort ?? null,\n audience: input.audience,\n challengeSecret: input.challengeSecret,\n deploymentId: input.deploymentId,\n endpoint: input.endpoint,\n expiresAtBlock: input.expiresAtBlock,\n grantId: input.grantId ?? null,\n source: input.source,\n fromPosition: input.fromPosition,\n maxPositionsPerWake: input.maxPositionsPerWake ?? null,\n queueId: input.queueId ?? null,\n revision: input.revision ?? null,\n subscriptionId: input.subscriptionId ?? null,\n supersedes: input.supersedes ?? null,\n })\n}\nasync function exactMutationRequestFingerprint(value: unknown): Promise<Hash> {\n return await handshakeMutationRequestFingerprint(value)\n}\nfunction protocolCandidate(reader: SynchronizedEventKitHandshakeReader, discovery: Extract<PublisherAcceptanceCandidateDiscovery, {\n readonly ok: true\n}>, candidate: PublisherAcceptanceCandidate, keys: PublisherEncryptionKeyStore): PublisherSubscriptionCandidate {\n return {\n chainId: reader.chainId,\n finalizedHead: discovery.finalizedHead,\n grant: {\n body: candidate.tuple.grant.body,\n objectHash: HashZod.parse(candidate.tuple.grant.objectHash),\n },\n key: {\n body: candidate.key.body,\n objectHash: HashZod.parse(candidate.key.objectHash),\n },\n keys,\n publisher: reader.publisher,\n service: {\n body: candidate.tuple.service.body,\n objectHash: HashZod.parse(candidate.tuple.service.objectHash),\n },\n subscriber: NormalizedAddressZod.parse(candidate.subscriber),\n subscription: {\n body: candidate.tuple.subscription.body,\n objectHash: HashZod.parse(candidate.tuple.subscription.objectHash),\n },\n tupleBlock: candidate.tuple.tupleEvent.block,\n tupleObjectHashes: [\n HashZod.parse(candidate.tuple.service.objectHash),\n HashZod.parse(candidate.tuple.grant.objectHash),\n HashZod.parse(candidate.tuple.subscription.objectHash),\n ],\n tupleSubject: reader.publisher,\n }\n}\nfunction validationError(reason: PublisherSubscriptionValidationFailureReason): EventKitHandshakeClientError {\n return new EventKitHandshakeClientError('subscription-invalid', `Publisher subscription candidate failed validation: ${reason}`)\n}\nfunction challengeError(result: CompletePublisherEndpointChallengeApiResult): EventKitHandshakeClientError {\n const reason = result.ok ? 'unknown' : result.reason\n return new EventKitHandshakeClientError('challenge-rejected', `Endpoint challenge was rejected: ${reason}`)\n}\n/** Publisher-side handshake orchestration shared by automation, CLI, and the resident runtime. */\nexport function createPublisherHandshakeClient(options: CreatePublisherHandshakeClientOptions): PublisherHandshakeClient {\n assertPublicationIdentity(options.publication, options.reader)\n const serviceId = options.serviceId === undefined ? undefined : HandshakeIdZod.parse(options.serviceId)\n async function snapshot(): Promise<SynchronizedEventKitHandshakeSnapshot> {\n return readySnapshot(await options.reader.sync())\n }\n async function discovery(current: SynchronizedEventKitHandshakeSnapshot): Promise<PublisherServiceDiscovery> {\n return await current.readModel.discoverPublisherService(serviceQuery(options.reader, current, serviceId))\n }\n async function candidateDiscovery(selector: Partial<PublisherSubscriptionSelector> = {}): Promise<PublisherAcceptanceCandidateDiscovery> {\n const current = await snapshot()\n return await current.readModel.acceptanceCandidates({\n ...serviceQuery(options.reader, current, serviceId),\n ...(selector.subscriber === undefined\n ? {}\n : { subscriber: NormalizedAddressZod.parse(selector.subscriber) }),\n ...(selector.subscriptionId === undefined\n ? {}\n : { subscriptionId: HandshakeIdZod.parse(selector.subscriptionId) }),\n })\n }\n async function resolveCandidate(selector: PublisherSubscriptionSelector): Promise<ResolvedPublisherCandidate> {\n const found = await candidateDiscovery(selector)\n if (!found.ok)\n throw new EventKitHandshakeClientError('service-unavailable', `Publisher service is unavailable: ${found.reason}`)\n const subscriber = NormalizedAddressZod.parse(selector.subscriber)\n const subscription = selector.subscription === undefined ? undefined : HashZod.parse(selector.subscription)\n const candidates = found.candidates.filter(candidate => candidate.subscriber === subscriber\n && (subscription === undefined || candidate.tuple.subscription.objectHash === subscription))\n if (candidates.length === 0) {\n throw new EventKitHandshakeClientError('candidate-not-found', 'No exact finalized acceptance candidate was found')\n }\n if (candidates.length !== 1) {\n throw new EventKitHandshakeClientError('candidate-ambiguous', 'More than one finalized acceptance candidate matched')\n }\n const candidate = candidates[0]\n const validated = await validateAndDecryptPublisherSubscription(protocolCandidate(options.reader, found, candidate, options.keys))\n if (!validated.ok)\n throw validationError(validated.reason)\n return { candidate, validated }\n }\n async function candidateForChallenge(challenge: EndpointChallenge): Promise<ResolvedPublisherCandidate> {\n const resolved = await resolveCandidate({\n subscriber: challenge.subscriber,\n subscription: challenge.subscription,\n })\n if (!endpointChallengeMatchesPublisherContext(challenge, resolved.validated.context)) {\n throw new EventKitHandshakeClientError('challenge-context-invalid', 'Endpoint challenge does not match the current finalized subscription candidate')\n }\n return resolved\n }\n async function reconcileAcceptance(acceptance: Hash, publication: HandshakePublicationResult, subscriber: NormalizedAddress, subscription: Hash): Promise<PublisherAcceptanceReconciliation> {\n let current: SynchronizedEventKitHandshakeSnapshot\n try {\n current = await options.reader.sync()\n } catch {\n return Object.freeze({ reason: 'synchronization-failed', status: 'unavailable' as const })\n }\n if (current.blocked !== undefined) {\n return Object.freeze({\n finalizedHead: current.finalizedHead,\n indexedThrough: current.indexedThrough,\n reason: 'projection-blocked' as const,\n status: 'unavailable' as const,\n })\n }\n if (current.indexedThrough !== current.finalizedHead) {\n return Object.freeze({\n finalizedHead: current.finalizedHead,\n indexedThrough: current.indexedThrough,\n reason: 'projection-stale' as const,\n status: 'unavailable' as const,\n })\n }\n if (current.finalizedHead < publication.finalizedBlock) {\n return Object.freeze({\n finalizedHead: current.finalizedHead,\n indexedThrough: current.indexedThrough,\n reason: 'publication-not-indexed' as const,\n status: 'unavailable' as const,\n })\n }\n let view: PublisherHandshakeView\n try {\n view = await current.readModel.publisher(serviceQuery(options.reader, current, serviceId))\n } catch {\n return Object.freeze({\n finalizedHead: current.finalizedHead,\n indexedThrough: current.indexedThrough,\n reason: 'synchronization-failed' as const,\n status: 'unavailable' as const,\n })\n }\n if (!view.ok) {\n return Object.freeze({\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n reason: view.reason,\n status: 'unavailable' as const,\n })\n }\n const matches = view.subscriptions.filter(item => item.subscriber === subscriber\n && item.tuples.some(tuple => tuple.subscription.objectHash === subscription))\n if (matches.length === 0) {\n return Object.freeze({\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n status: 'not-found' as const,\n })\n }\n if (matches.length !== 1) {\n return Object.freeze({\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n reason: 'ambiguous-lifecycle' as const,\n status: 'unavailable' as const,\n })\n }\n const lifecycle = matches[0]\n const active = lifecycle.state === 'active'\n && lifecycle.selectedSubscription === subscription\n && lifecycle.acceptance?.objectHash === acceptance\n return Object.freeze({\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n lifecycle,\n status: active ? 'active' as const : 'not-active' as const,\n })\n }\n async function publishAcceptanceIntent(intent: PublisherAcceptanceIntent, intentDisposition: HandshakeMutationIntentDisposition): Promise<PublisherAcceptancePublicationResult> {\n const [acceptanceHash, responseHash] = await Promise.all([\n handshakeObjectHash(intent.acceptance),\n handshakeObjectHash(intent.response),\n ])\n const publication = await options.publication.publishWakeSubscriptionAcceptance({\n acceptance: intent.acceptance,\n challenge: intent.challenge,\n operationId: intent.operationId,\n response: intent.response,\n })\n const reconciliation = await reconcileAcceptance(acceptanceHash, publication, intent.challenge.subscriber, intent.challenge.subscription)\n return Object.freeze({\n acceptance: Object.freeze({ body: intent.acceptance, objectHash: acceptanceHash }),\n challenge: intent.acceptance.challenge,\n intentDisposition,\n operationId: intent.operationId,\n publication,\n reconciliation,\n response: responseHash,\n subscriber: intent.challenge.subscriber,\n subscription: intent.challenge.subscription,\n })\n }\n async function publishPublisherServiceIntent(\n intent: PublisherServicePublishIntent | PublisherServiceRotateKeyIntent,\n intentDisposition: HandshakeMutationIntentDisposition,\n ): Promise<PublisherServicePublicationResult> {\n let keyCustody: 'duplicate' | 'stored'\n try {\n keyCustody = await options.keys.putPrivateKey({\n key: intent.privateKey,\n publisher: options.reader.publisher,\n })\n } catch {\n throw new EventKitHandshakeClientError('key-custody-failed', 'Publisher encryption private key was not durably retained; publication was not attempted')\n }\n const [keyHash, serviceHash] = await Promise.all([\n handshakeObjectHash(intent.encryptionKey),\n handshakeObjectHash(intent.service),\n ])\n const publication = await options.publication.publishPublisherService({\n encryptionKeys: [intent.encryptionKey],\n operationId: intent.operationId,\n service: intent.service,\n })\n return Object.freeze({\n encryptionKey: Object.freeze({ body: intent.encryptionKey, objectHash: keyHash }),\n intentDisposition,\n keyCustody,\n operationId: intent.operationId,\n publication,\n service: Object.freeze({ body: intent.service, objectHash: serviceHash }),\n })\n }\n const client: PublisherHandshakeClient = {\n async acceptanceCandidates(selector = {}) {\n const found = await candidateDiscovery(selector)\n if (!found.ok || selector.subscription === undefined)\n return found\n const subscription = HashZod.parse(selector.subscription)\n return Object.freeze({\n ...found,\n candidates: found.candidates.filter(candidate => candidate.tuple.subscription.objectHash === subscription),\n })\n },\n async beginChallenge(input): Promise<BeginPublisherChallengeResult> {\n const challengeHash = HashZod.parse(input.challengeHash)\n const record = await options.challenges.get(challengeHash)\n if (record === undefined)\n return { kind: 'missing' }\n const resolved = await candidateForChallenge(record.challenge)\n const begun = await beginPublisherEndpointChallengeAttempt({\n challengeHash,\n nowSeconds: samplePublisherClock(input.nowSeconds),\n store: options.challenges,\n })\n if (begun.kind !== 'started') {\n if (begun.kind === 'store-invalid' || begun.kind === 'store-unavailable') {\n throw new EventKitHandshakeClientError('challenge-rejected', `Endpoint challenge store failed: ${begun.kind}`)\n }\n return { kind: begun.kind }\n }\n return Object.freeze({\n challenge: begun.record.challenge,\n challengeHash,\n kind: 'started' as const,\n subscriber: resolved.validated.context.subscriber,\n subscription: resolved.validated.context.subscription,\n target: Object.freeze({\n audience: resolved.validated.plaintext.audience,\n endpoint: resolved.validated.plaintext.endpoint,\n }),\n })\n },\n async completeChallengeAndAccept(input): Promise<PublisherAcceptancePublicationResult> {\n await assertPublicationSource(options.publication, options.reader.publisher)\n const challengeHash = HashZod.parse(input.challengeHash)\n const subscriber = NormalizedAddressZod.parse(input.subscriber)\n const subscription = HashZod.parse(input.subscription)\n const record = await options.challenges.get(challengeHash)\n if (record === undefined) {\n throw new EventKitHandshakeClientError('challenge-not-found', 'Endpoint challenge was not found')\n }\n if (record.challenge.subscriber !== subscriber\n || record.challenge.subscription !== subscription) {\n throw new EventKitHandshakeClientError('challenge-context-invalid', 'Stored endpoint challenge does not match the caller expected subscriber and subscription')\n }\n const responseHash = await handshakeObjectHash(input.response)\n const requestFingerprint = await exactMutationRequestFingerprint({\n challengeHash,\n responseHash,\n subscriber,\n subscription,\n })\n const existing = await loadMutationIntent(options.intents, options.reader, 'publisher-subscription-accept', challengeHash, options.reader.publisher, requestFingerprint)\n if (existing !== undefined) {\n if (record.state !== 'verified' || record.responseHash !== responseHash) {\n throw new EventKitHandshakeClientError('mutation-intent-conflict', 'Acceptance intent does not match the durable verified challenge decision')\n }\n return await publishAcceptanceIntent(existing, 'resumed')\n }\n const resolved = await candidateForChallenge(record.challenge)\n const completed = await completePublisherEndpointChallenge({\n challenge: record.challenge,\n nowSeconds: samplePublisherClock(input.nowSeconds),\n response: input.response,\n store: options.challenges,\n subscription: resolved.validated,\n })\n if (!completed.ok)\n throw challengeError(completed)\n const concurrentlyPersisted = await loadMutationIntent(options.intents, options.reader, 'publisher-subscription-accept', challengeHash, options.reader.publisher, requestFingerprint)\n if (concurrentlyPersisted !== undefined)\n return await publishAcceptanceIntent(concurrentlyPersisted, 'resumed')\n // This second replay is intentional: challenge success is not acceptance\n // eligibility. Recheck every finalized lifecycle edge immediately before\n // constructing and publishing the acceptance transaction.\n let current: ResolvedPublisherCandidate\n try {\n current = await candidateForChallenge(record.challenge)\n } catch (error) {\n const recovered = await loadMutationIntent(options.intents, options.reader, 'publisher-subscription-accept', challengeHash, options.reader.publisher, requestFingerprint)\n if (recovered !== undefined)\n return await publishAcceptanceIntent(recovered, 'resumed')\n throw error\n }\n if (!endpointChallengeMatchesPublisherContext(record.challenge, current.validated.context)) {\n throw new EventKitHandshakeClientError('challenge-context-invalid', 'Endpoint challenge candidate changed before acceptance publication')\n }\n const resolvedIntent = await persistMutationIntent(options.intents, {\n acceptance: completed.acceptance,\n chainId: options.reader.chainId,\n challenge: record.challenge,\n kind: 'publisher-subscription-accept',\n operationId: challengeHash,\n publisher: options.reader.publisher,\n requestFingerprint,\n response: input.response,\n source: options.reader.publisher,\n version: 1,\n })\n return await publishAcceptanceIntent(resolvedIntent.intent, resolvedIntent.disposition)\n },\n async issueChallenge(input): Promise<IssuedPublisherChallenge> {\n const resolved = await resolveCandidate(input)\n const issued = await issuePublisherEndpointChallenge({\n issuedAt: input.issuedAt,\n ...(input.lifetimeSeconds === undefined ? {} : { lifetimeSeconds: input.lifetimeSeconds }),\n store: options.challenges,\n subscription: resolved.validated,\n })\n if (!issued.ok) {\n throw new EventKitHandshakeClientError('challenge-rejected', `Endpoint challenge issue failed: ${issued.reason}`)\n }\n return Object.freeze({\n challenge: issued.challenge,\n challengeHash: issued.challengeHash,\n disposition: issued.disposition,\n subscriber: resolved.validated.context.subscriber,\n subscription: resolved.validated.context.subscription,\n })\n },\n async key(): Promise<PublisherServiceDiscovery> {\n const current = await options.reader.sync()\n return await current.readModel.discoverPublisherService(serviceQuery(options.reader, current, serviceId))\n },\n async publishService(input): Promise<PublisherServicePublicationResult> {\n await assertPublicationSource(options.publication, options.reader.publisher)\n if (serviceId !== undefined) {\n throw new EventKitHandshakeClientError('service-root-requires-fresh-id', 'Root service publication requires an unconfigured client so a fresh serviceId is generated')\n }\n const operationId = HandshakeIdZod.parse(input.operationId)\n const requestFingerprint = await publisherServiceRequestFingerprint(input)\n const priorIntent = await loadMutationIntent(options.intents, options.reader, 'publisher-service-publish', operationId, options.reader.publisher, requestFingerprint)\n if (priorIntent !== undefined)\n return await publishPublisherServiceIntent(priorIntent, 'resumed')\n const current = await snapshot()\n const existing = await discovery(current)\n if (existing.ok) {\n throw new EventKitHandshakeClientError('service-already-exists', 'An active publisher service already exists; rotate its key to publish a successor')\n }\n if (existing.reason !== 'service-not-found') {\n throw new EventKitHandshakeClientError('service-unavailable', `Cannot declare service: ${existing.reason}`)\n }\n const validFromBlock = input.validFromBlock ?? nextBlock(current.finalizedHead)\n const generated = await generatePublisherEncryptionKey({ validFromBlock })\n const serviceInput = {\n encryptionKeys: [generated.descriptorHash],\n ...(input.expiresAtBlock === undefined ? {} : { expiresAtBlock: input.expiresAtBlock }),\n maxSubscriptionLifetimeBlocks: input.maxSubscriptionLifetimeBlocks,\n preferredEncryptionKey: generated.descriptorHash,\n validFromBlock,\n }\n const service = createPublisherService({\n deliveryMode: input.deliveryMode,\n ...(input.bestEffort === undefined ? {} : { bestEffort: input.bestEffort }),\n ...serviceInput,\n authorizationChainId: options.reader.chainId,\n sources: input.sources,\n maxPositionsPerWake: input.maxPositionsPerWake,\n })\n const resolvedIntent = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n encryptionKey: generated.descriptor,\n kind: 'publisher-service-publish',\n operationId,\n privateKey: generated.privateKey,\n publisher: options.reader.publisher,\n requestFingerprint,\n service,\n source: options.reader.publisher,\n version: 1,\n })\n return await publishPublisherServiceIntent(resolvedIntent.intent, resolvedIntent.disposition)\n },\n async retireEncryptionKey(key): Promise<PublisherKeyRetirementResult> {\n await assertPublicationSource(options.publication, options.reader.publisher)\n const keyHash = HashZod.parse(key)\n const requestFingerprint = await exactMutationRequestFingerprint({ key: keyHash })\n let resolvedIntent = await loadMutationIntent(options.intents, options.reader, 'publisher-encryption-key-retire', keyHash, options.reader.publisher, requestFingerprint)\n let intentDisposition: HandshakeMutationIntentDisposition = 'resumed'\n if (resolvedIntent === undefined) {\n const current = await snapshot()\n const selected = requireService(await discovery(current))\n if (selected.key.objectHash !== keyHash\n || !selected.service.body.encryptionKeys.includes(keyHash)\n || selected.service.body.preferredEncryptionKey !== keyHash) {\n throw new EventKitHandshakeClientError('key-mismatch', 'Encryption key does not match the exact current preferred descriptor evidence')\n }\n const persisted = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n kind: 'publisher-encryption-key-retire',\n operationId: keyHash,\n publisher: options.reader.publisher,\n requestFingerprint,\n revocation: createPublisherEncryptionKeyRevocation(keyHash),\n source: options.reader.publisher,\n version: 1,\n })\n resolvedIntent = persisted.intent\n intentDisposition = persisted.disposition\n }\n const revocation = await withHandshakeObjectHash(resolvedIntent.revocation)\n const publication = await options.publication.publishPublisherEncryptionKeyRevocation({\n operationId: keyHash,\n revocation: resolvedIntent.revocation,\n })\n return Object.freeze({\n intentDisposition,\n key: keyHash,\n operationId: keyHash,\n publication,\n revocation,\n })\n },\n async retireService(expectedService): Promise<PublisherServiceRetirementResult> {\n await assertPublicationSource(options.publication, options.reader.publisher)\n const service = HashZod.parse(expectedService)\n const requestFingerprint = await exactMutationRequestFingerprint({ service })\n let resolvedIntent = await loadMutationIntent(options.intents, options.reader, 'publisher-service-retire', service, options.reader.publisher, requestFingerprint)\n let intentDisposition: HandshakeMutationIntentDisposition = 'resumed'\n if (resolvedIntent === undefined) {\n const current = await snapshot()\n const selected = requireService(await discovery(current))\n requireExpectedService(selected, service)\n const persisted = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n kind: 'publisher-service-retire',\n operationId: service,\n publisher: options.reader.publisher,\n requestFingerprint,\n revocation: createPublisherServiceRevocation(service),\n source: options.reader.publisher,\n version: 1,\n })\n resolvedIntent = persisted.intent\n intentDisposition = persisted.disposition\n }\n const revocation = await withHandshakeObjectHash(resolvedIntent.revocation)\n const publication = await options.publication.publishPublisherServiceRevocation({\n operationId: service,\n revocation: resolvedIntent.revocation,\n })\n return Object.freeze({\n intentDisposition,\n operationId: service,\n publication,\n revocation,\n service,\n })\n },\n async rotateEncryptionKey(input): Promise<PublisherServicePublicationResult> {\n await assertPublicationSource(options.publication, options.reader.publisher)\n const operationId = HandshakeIdZod.parse(input.operationId)\n const requestFingerprint = await publisherRotationRequestFingerprint(input)\n const priorIntent = await loadMutationIntent(options.intents, options.reader, 'publisher-service-rotate-key', operationId, options.reader.publisher, requestFingerprint)\n if (priorIntent !== undefined)\n return await publishPublisherServiceIntent(priorIntent, 'resumed')\n const current = await snapshot()\n const selected = requireService(await discovery(current))\n requireExpectedService(selected, input.service)\n const validFromBlock = input.validFromBlock ?? nextBlock(current.finalizedHead)\n const generated = await generatePublisherEncryptionKey({\n ...(input.keyExpiresAtBlock === undefined ? {} : { expiresAtBlock: input.keyExpiresAtBlock }),\n validFromBlock,\n })\n const serviceInput = {\n encryptionKeys: [generated.descriptorHash],\n ...(input.expiresAtBlock === undefined\n ? selected.service.body.expiresAtBlock === undefined\n ? {}\n : { expiresAtBlock: selected.service.body.expiresAtBlock }\n : { expiresAtBlock: input.expiresAtBlock }),\n maxSubscriptionLifetimeBlocks: input.maxSubscriptionLifetimeBlocks\n ?? selected.service.body.limits.maxSubscriptionLifetimeBlocks,\n preferredEncryptionKey: generated.descriptorHash,\n revision: selected.service.body.revision + 1,\n serviceId: selected.service.body.serviceId,\n supersedes: HashZod.parse(selected.service.objectHash),\n validFromBlock,\n }\n const service = createPublisherService({\n deliveryMode: selected.service.body.deliveryMode,\n ...(selected.service.body.bestEffort === undefined ? {} : { bestEffort: selected.service.body.bestEffort }),\n ...serviceInput,\n authorizationChainId: options.reader.chainId,\n sources: selected.service.body.events.map(event => event.source),\n maxPositionsPerWake: input.maxPositionsPerWake ?? selected.service.body.limits.maxPositionsPerWake,\n })\n const resolvedIntent = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n encryptionKey: generated.descriptor,\n kind: 'publisher-service-rotate-key',\n operationId,\n privateKey: generated.privateKey,\n publisher: options.reader.publisher,\n requestFingerprint,\n selectedKey: HashZod.parse(selected.key.objectHash),\n selectedService: HashZod.parse(selected.service.objectHash),\n service,\n source: options.reader.publisher,\n version: 1,\n })\n return await publishPublisherServiceIntent(resolvedIntent.intent, resolvedIntent.disposition)\n },\n async service(): Promise<PublisherServiceDiscovery> {\n const current = await options.reader.sync()\n return await current.readModel.discoverPublisherService(serviceQuery(options.reader, current, serviceId))\n },\n async subscriptions(): Promise<PublisherHandshakeView> {\n const current = await options.reader.sync()\n return await current.readModel.publisher(serviceQuery(options.reader, current, serviceId))\n },\n }\n return Object.freeze(client)\n}\nexport interface CreateSubscriberHandshakeClientOptions {\n readonly intents: HandshakeMutationIntentStore\n readonly publication: EventKitHandshakePublicationPort\n readonly reader: SynchronizedEventKitHandshakeReader\n readonly serviceId?: string\n readonly subscriber: string\n}\nexport interface SubscribeToPublisherInput {\n readonly audience: string\n readonly bestEffort?: BestEffortDeliveryPolicy\n /** Subscriber-owned secret already provisioned at the endpoint; it is never returned or published. */\n readonly challengeSecret: Base64Url32Bytes\n readonly deliveryMode: WakeDeliveryMode\n readonly deploymentId: string\n readonly endpoint: string\n readonly expiresAtBlock: number\n readonly fromPosition: number\n readonly grantId?: string\n readonly maxPositionsPerWake?: number\n readonly operationId: HandshakeId\n readonly queueId?: string | null\n readonly revision?: number\n readonly source: WakeSource\n readonly subscriptionId?: HandshakeId\n readonly supersedes?: Hash\n}\nexport interface SubscriberSubscriptionPublicationResult {\n readonly grant: HashedHandshakeObject<WakeGrantObject>\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly operationId: HandshakeId\n readonly publication: HandshakePublicationResult\n readonly service: Hash\n readonly subscription: HashedHandshakeObject<EncryptedWakeSubscription>\n}\nexport interface SubscriberSubscriptionRevocationResult {\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly operationId: Hash\n readonly publication: HandshakePublicationResult\n readonly revocation: HashedHandshakeObject<ReturnType<typeof createWakeSubscriptionRevocation>>\n readonly subscription: Hash\n}\nexport interface SubscriberGrantRevocationResult {\n readonly grant: Hash\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly operationId: Hash\n readonly publication: HandshakePublicationResult\n readonly revocation: HashedHandshakeObject<ReturnType<typeof createWakeGrantRevocation>>\n}\nexport interface SubscriberHandshakeClient {\n revokeGrant(grant: string): Promise<SubscriberGrantRevocationResult>\n revokeSubscription(subscription: string): Promise<SubscriberSubscriptionRevocationResult>\n service(): Promise<PublisherServiceDiscovery>\n subscribe(input: SubscribeToPublisherInput): Promise<SubscriberSubscriptionPublicationResult>\n subscription(subscription: string): Promise<SubscriberExactSubscriptionLookup>\n subscriptions(subscriptionId?: string): Promise<SubscriberSubscriptionLookup>\n}\nexport interface SubscriberExactSubscriptionLookupSuccess {\n readonly found: true\n readonly lifecycle: PublisherSubscriptionView\n readonly lookup: SubscriberSubscriptionLookupSuccess\n readonly ok: true\n readonly tuple: FinalizedSubscriptionTuple\n}\nexport interface SubscriberExactSubscriptionLookupNotFound {\n readonly found: false\n readonly lookup: SubscriberSubscriptionLookupSuccess\n readonly ok: true\n}\nexport type SubscriberExactSubscriptionLookup = PublisherServiceDiscoveryFailure | SubscriberExactSubscriptionLookupNotFound | SubscriberExactSubscriptionLookupSuccess\nfunction tupleHashes(view: Extract<SubscriberSubscriptionLookup, {\n readonly ok: true\n}>): {\n readonly grants: ReadonlySet<string>\n readonly subscriptions: ReadonlySet<string>\n} {\n const tuples = view.subscriptions.flatMap(subscription => subscription.tuples)\n return {\n grants: new Set(tuples.map(tuple => tuple.grant.objectHash)),\n subscriptions: new Set(tuples.map(tuple => tuple.subscription.objectHash)),\n }\n}\n/** Subscriber-side discovery, encryption, exact tuple publication, and revocation. */\nexport function createSubscriberHandshakeClient(options: CreateSubscriberHandshakeClientOptions): SubscriberHandshakeClient {\n assertPublicationIdentity(options.publication, options.reader)\n const subscriber = NormalizedAddressZod.parse(options.subscriber)\n const serviceId = options.serviceId === undefined ? undefined : HandshakeIdZod.parse(options.serviceId)\n async function snapshot(): Promise<SynchronizedEventKitHandshakeSnapshot> {\n return readySnapshot(await options.reader.sync())\n }\n async function serviceAt(current: SynchronizedEventKitHandshakeSnapshot) {\n return requireService(await current.readModel.discoverPublisherService(serviceQuery(options.reader, current, serviceId)))\n }\n async function lookup(subscriptionId?: string): Promise<SubscriberSubscriptionLookup> {\n const current = await options.reader.sync()\n return await lookupAt(current, subscriptionId)\n }\n async function lookupAt(current: SynchronizedEventKitHandshakeSnapshot, subscriptionId?: string): Promise<SubscriberSubscriptionLookup> {\n return await current.readModel.subscriber({\n ...serviceQuery(options.reader, current, serviceId),\n subscriber,\n ...(subscriptionId === undefined ? {} : { subscriptionId: HandshakeIdZod.parse(subscriptionId) }),\n })\n }\n async function validateRevision(current: SynchronizedEventKitHandshakeSnapshot, input: SubscribeToPublisherInput): Promise<void> {\n const revision = input.revision ?? 1\n if (revision === 1) {\n if (input.supersedes !== undefined) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Subscription revision 1 must not declare supersedes')\n }\n if (input.subscriptionId === undefined)\n return\n const view = await lookupAt(current, input.subscriptionId)\n if (!view.ok) {\n throw new EventKitHandshakeClientError('service-unavailable', `Cannot validate subscription identity: ${view.reason}`)\n }\n if (view.subscriptions.some(item => item.subscriptionId === input.subscriptionId)) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Subscription revision 1 would duplicate an existing finalized stable identity')\n }\n return\n }\n if (input.subscriptionId === undefined || input.supersedes === undefined) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'A replacement subscription requires subscriptionId and supersedes')\n }\n const view = await lookupAt(current, input.subscriptionId)\n if (!view.ok) {\n throw new EventKitHandshakeClientError('service-unavailable', `Cannot validate subscription revision: ${view.reason}`)\n }\n const lifecycles = view.subscriptions.filter(item => item.subscriptionId === input.subscriptionId)\n if (lifecycles.length !== 1) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Replacement subscription does not resolve one finalized stable identity')\n }\n if (lifecycles[0].state === 'rejected') {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Replacement subscription cannot extend a rejected finalized revision chain')\n }\n const highestRevision = Math.max(...lifecycles[0].tuples.map(tuple => tuple.subscription.body.revision))\n const latest = lifecycles[0].tuples.filter(tuple => tuple.subscription.body.revision === highestRevision)\n if (latest.length !== 1\n || revision !== highestRevision + 1\n || latest[0].subscription.objectHash !== input.supersedes) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Replacement subscription revision and supersedes must extend the exact finalized chain tip')\n }\n }\n async function publishSubscriberSubscriptionIntent(intent: SubscriberSubscriptionIntent, intentDisposition: HandshakeMutationIntentDisposition): Promise<SubscriberSubscriptionPublicationResult> {\n const [grantHash, subscriptionHash] = await Promise.all([\n handshakeObjectHash(intent.grant),\n handshakeObjectHash(intent.subscription),\n ])\n const publication = await options.publication.publishWakeSubscription({\n encryptionKey: intent.encryptionKey,\n grant: intent.grant,\n operationId: intent.operationId,\n service: intent.service,\n subscription: intent.subscription,\n })\n return Object.freeze({\n grant: Object.freeze({ body: intent.grant, objectHash: grantHash }),\n intentDisposition,\n operationId: intent.operationId,\n publication,\n service: intent.selectedService,\n subscription: Object.freeze({ body: intent.subscription, objectHash: subscriptionHash }),\n })\n }\n const client: SubscriberHandshakeClient = {\n async revokeGrant(grant): Promise<SubscriberGrantRevocationResult> {\n await assertPublicationSource(options.publication, subscriber)\n const grantHash = HashZod.parse(grant)\n const requestFingerprint = await exactMutationRequestFingerprint({ grant: grantHash })\n let resolvedIntent = await loadMutationIntent(options.intents, options.reader, 'subscriber-grant-revoke', grantHash, subscriber, requestFingerprint)\n let intentDisposition: HandshakeMutationIntentDisposition = 'resumed'\n if (resolvedIntent === undefined) {\n const current = await snapshot()\n const view = await current.readModel.subscriber({ ...serviceQuery(options.reader, current, serviceId), subscriber })\n if (!view.ok || !tupleHashes(view).grants.has(grantHash)) {\n throw new EventKitHandshakeClientError('subscription-not-found', 'Grant is not present in this subscriber finalization view')\n }\n const persisted = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n kind: 'subscriber-grant-revoke',\n operationId: grantHash,\n publisher: options.reader.publisher,\n requestFingerprint,\n revocation: createWakeGrantRevocation(grantHash),\n source: subscriber,\n version: 1,\n })\n resolvedIntent = persisted.intent\n intentDisposition = persisted.disposition\n }\n const revocation = await withHandshakeObjectHash(resolvedIntent.revocation)\n const publication = await options.publication.publishWakeGrantRevocation({\n operationId: grantHash,\n publisher: options.reader.publisher,\n revocation: resolvedIntent.revocation,\n })\n return Object.freeze({\n grant: grantHash,\n intentDisposition,\n operationId: grantHash,\n publication,\n revocation,\n })\n },\n async revokeSubscription(subscription): Promise<SubscriberSubscriptionRevocationResult> {\n await assertPublicationSource(options.publication, subscriber)\n const subscriptionHash = HashZod.parse(subscription)\n const requestFingerprint = await exactMutationRequestFingerprint({ subscription: subscriptionHash })\n let resolvedIntent = await loadMutationIntent(options.intents, options.reader, 'subscriber-subscription-revoke', subscriptionHash, subscriber, requestFingerprint)\n let intentDisposition: HandshakeMutationIntentDisposition = 'resumed'\n if (resolvedIntent === undefined) {\n const current = await snapshot()\n const view = await current.readModel.subscriber({ ...serviceQuery(options.reader, current, serviceId), subscriber })\n if (!view.ok || !tupleHashes(view).subscriptions.has(subscriptionHash)) {\n throw new EventKitHandshakeClientError('subscription-not-found', 'Subscription is not present in this subscriber finalization view')\n }\n const persisted = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n kind: 'subscriber-subscription-revoke',\n operationId: subscriptionHash,\n publisher: options.reader.publisher,\n requestFingerprint,\n revocation: createWakeSubscriptionRevocation(subscriptionHash),\n source: subscriber,\n version: 1,\n })\n resolvedIntent = persisted.intent\n intentDisposition = persisted.disposition\n }\n const revocation = await withHandshakeObjectHash(resolvedIntent.revocation)\n const publication = await options.publication.publishWakeSubscriptionRevocation({\n operationId: subscriptionHash,\n publisher: options.reader.publisher,\n revocation: resolvedIntent.revocation,\n })\n return Object.freeze({\n intentDisposition,\n operationId: subscriptionHash,\n publication,\n revocation,\n subscription: subscriptionHash,\n })\n },\n async service(): Promise<PublisherServiceDiscovery> {\n const current = await options.reader.sync()\n return await current.readModel.discoverPublisherService(serviceQuery(options.reader, current, serviceId))\n },\n async subscription(subscription): Promise<SubscriberExactSubscriptionLookup> {\n const subscriptionHash = HashZod.parse(subscription)\n const current = await options.reader.sync()\n const view = await lookupAt(current)\n if (!view.ok)\n return view\n const matches = view.subscriptions.flatMap(lifecycle => lifecycle.tuples\n .filter(tuple => tuple.subscription.objectHash === subscriptionHash)\n .map(tuple => ({ lifecycle, tuple })))\n if (matches.length > 1) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Exact subscription hash appears more than once in the subscriber view')\n }\n if (matches.length === 0)\n return Object.freeze({\n found: false, lookup: view, ok: true,\n })\n return Object.freeze({\n found: true,\n lifecycle: matches[0].lifecycle,\n lookup: view,\n ok: true,\n tuple: matches[0].tuple,\n })\n },\n async subscribe(input): Promise<SubscriberSubscriptionPublicationResult> {\n await assertPublicationSource(options.publication, subscriber)\n const operationId = HandshakeIdZod.parse(input.operationId)\n const requestFingerprint = await subscriberSubscriptionRequestFingerprint(input)\n const priorIntent = await loadMutationIntent(options.intents, options.reader, 'subscriber-subscription-subscribe', operationId, subscriber, requestFingerprint)\n if (priorIntent !== undefined)\n return await publishSubscriberSubscriptionIntent(priorIntent, 'resumed')\n const current = await snapshot()\n const selected = await serviceAt(current)\n if (input.expiresAtBlock - current.finalizedHead <= 3) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Requested subscription expiry must leave finalized blocks for tuple publication, acceptance, and activation')\n }\n await validateRevision(current, input)\n const maximum = selected.service.body.limits.maxPositionsPerWake\n const maxPositionsPerWake = input.maxPositionsPerWake ?? maximum\n if (maxPositionsPerWake > maximum) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Requested maxPositionsPerWake exceeds the selected publisher service limit')\n }\n if (input.expiresAtBlock > current.finalizedHead + selected.service.body.limits.maxSubscriptionLifetimeBlocks) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Requested subscription expiry exceeds the selected publisher service lifetime limit')\n }\n const grant = createWakeGrant({\n deploymentId: input.deploymentId,\n ...(input.grantId === undefined ? {} : { grantId: input.grantId }),\n publisher: options.reader.publisher,\n ...(input.queueId === undefined || input.queueId === null ? {} : { queueId: input.queueId }),\n })\n const grantHash = await handshakeObjectHash(grant)\n const plaintext = subscriberPlaintext(selected.service.body, input, maxPositionsPerWake)\n const subscriptionInput = {\n chainId: options.reader.chainId,\n expiresAtBlock: input.expiresAtBlock,\n grant: grantHash,\n publisher: options.reader.publisher,\n publisherKey: {\n encryptionKey: HashZod.parse(selected.key.objectHash),\n keyId: selected.key.body.keyId,\n publicKey: selected.key.body.publicKey,\n },\n ...(input.revision === undefined ? {} : { revision: input.revision }),\n service: HashZod.parse(selected.service.objectHash),\n subscriber,\n ...(input.subscriptionId === undefined ? {} : { subscriptionId: input.subscriptionId }),\n ...(input.supersedes === undefined ? {} : { supersedes: input.supersedes }),\n }\n const subscription = await createEncryptedWakeSubscription({ ...subscriptionInput, plaintext })\n const resolvedIntent = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n encryptionKey: selected.key.body,\n grant,\n kind: 'subscriber-subscription-subscribe',\n operationId,\n publisher: options.reader.publisher,\n requestFingerprint,\n selectedKey: HashZod.parse(selected.key.objectHash),\n selectedService: HashZod.parse(selected.service.objectHash),\n service: selected.service.body,\n source: subscriber,\n subscription,\n version: 1,\n })\n return await publishSubscriberSubscriptionIntent(resolvedIntent.intent, resolvedIntent.disposition)\n },\n subscriptions: async (subscriptionId): Promise<SubscriberSubscriptionLookup> => await lookup(subscriptionId),\n }\n return Object.freeze(client)\n}\n\nfunction subscriberPlaintext(service: PublisherService, input: SubscribeToPublisherInput, maxPositionsPerWake: number): WakeSubscriptionPlaintext {\n if (input.deliveryMode !== service.deliveryMode || canonicalJson(input.bestEffort ?? null) !== canonicalJson(service.bestEffort ?? null))\n throw new Error('Requested delivery terms do not match exact selected service')\n const plaintextInput = {\n audience: input.audience,\n challengeSecret: input.challengeSecret,\n deploymentId: input.deploymentId,\n endpoint: input.endpoint,\n queueId: input.queueId,\n }\n const source = input.source\n if (service.events.every(event => canonicalJson(event.source) !== canonicalJson(source))) {\n throw new Error('Requested source is not advertised by the selected service')\n }\n return createWakeSubscriptionPlaintext({\n deliveryMode: input.deliveryMode,\n ...(input.bestEffort === undefined ? {} : { bestEffort: input.bestEffort }),\n ...plaintextInput,\n source,\n fromPosition: input.fromPosition,\n maxPositionsPerWake,\n })\n}\n", "import { randomBytes } from 'node:crypto'\nimport {\n link, lstat, mkdir, mkdtemp, open, realpath, rm, unlink,\n} from 'node:fs/promises'\nimport OS from 'node:os'\nimport PATH from 'node:path'\n\nimport type { AdmittedWake } from '@xyo-network/event-kit-protocol'\nimport {\n HashZod, NormalizedAddressZod, WakeIdZod, WakeJwtAudienceZod,\n} from '@xyo-network/event-kit-schemas'\n\nimport { syncDirectory } from './filesystemDurability.ts'\nimport { ensurePrivateDirectory } from './privateSqlite.ts'\nimport { openReceiverAuthority, receiverIdentity } from './receiverAuthority.ts'\nimport { inventoryReceiverMigration } from './receiverMigrationInventory.ts'\nimport { snapshotMigrationSource, verifyMigrationSource } from './receiverMigrationSnapshot.ts'\nimport type {\n ReceiverMigrationEntry, ReceiverMigrationFile, ReceiverMigrationOptions, ReceiverMigrationPlan, ReceiverMigrationReport,\n} from './receiverMigrationTypes.ts'\n\nexport type {\n FilesystemReceiverMigrationSource, ReceiverMigrationFile, ReceiverMigrationIssue,\n ReceiverMigrationOptions, ReceiverMigrationReport, ReceiverMigrationReview, ReceiverMigrationSource,\n SqliteQueueMigrationSource,\n} from './receiverMigrationTypes.ts'\n\nconst rollback = 'restore-backup-only-before-new-writers-resume; after-that-repair-forward; reverse-migration-unsupported' as const\n\nasync function outsideSource(source: string, destination: string): Promise<string> {\n let parent = PATH.dirname(PATH.resolve(destination))\n const suffix = [PATH.basename(destination)]\n let canonicalParent: string\n for (;;) {\n try {\n canonicalParent = await realpath(parent)\n break\n } catch (error) {\n if (typeof error !== 'object' || error === null || !('code' in error) || error.code !== 'ENOENT') throw error\n suffix.unshift(PATH.basename(parent))\n parent = PATH.dirname(parent)\n }\n }\n const resolved = PATH.join(canonicalParent, ...suffix)\n if (resolved === source || resolved.startsWith(`${source}${PATH.sep}`)) throw new TypeError('Migration output must be outside the source store')\n return resolved\n}\n\nasync function writeReport(path: string, report: ReceiverMigrationReport): Promise<void> {\n const file = await open(path, 'wx', 0o600)\n try {\n await file.writeFile(`${JSON.stringify(report, null, 2)}\\n`)\n await file.sync()\n } finally {\n await file.close()\n }\n await syncDirectory(PATH.dirname(path))\n}\n\nfunction importEntries(database: ReturnType<typeof openReceiverAuthority>['database'], entries: readonly ReceiverMigrationEntry[]): void {\n database.exec('BEGIN IMMEDIATE')\n try {\n for (const entry of entries) {\n // New terminal marker attests to the reviewed migration decision; it does\n // not reconstruct any historical consumer lease or unrecorded ack.\n const terminalToken = entry.state === 'completed' ? randomBytes(16).toString('hex') : null\n const result = database.prepare('INSERT INTO receiver_queue(body,state,terminal_token,terminal_operation) VALUES(?,?,?,?)')\n .run(entry.state === 'completed' ? null : JSON.stringify(entry.wake), entry.state, terminalToken, terminalToken === null ? null : 'ack')\n if (entry.receipt === undefined) continue // Explicit standalone queue; no invented admission.\n const receipt = entry.receipt\n database.prepare('INSERT INTO receiver_wakes(identity,audience,publisher,wake_id,event_hash,receipt,authorization,queue_id) VALUES(?,?,?,?,?,?,?,?)')\n .run(\n receipt.id,\n receipt.audience,\n receipt.publisher,\n receipt.wakeId,\n receipt.eventHash,\n JSON.stringify(receipt),\n JSON.stringify({\n kind: 'legacy-migration',\n evidence: entry.evidence,\n artifacts: entry.paths,\n freshAuthorization: false,\n ...(terminalToken === null ? {} : { completion: { kind: 'reviewed-migration-decision', terminalToken } }),\n }),\n result.lastInsertRowid,\n )\n for (const token of entry.tokens) {\n database.prepare('INSERT INTO receiver_tokens(identity,wake_identity,event_hash,wake_id,retain_until) VALUES(?,?,?,?,?)')\n .run(receiverIdentity([token.audience, token.publisher, token.jwtId]), receipt.id, token.eventHash, token.wakeId, token.retainJwtUntil)\n }\n }\n database.exec('COMMIT')\n } catch (error) {\n database.exec('ROLLBACK')\n throw error\n }\n}\n\nasync function publishMigratedStore(target: string, entries: readonly ReceiverMigrationEntry[], verifySource: () => Promise<void>): Promise<void> {\n ensurePrivateDirectory(PATH.dirname(target))\n const staging = PATH.join(PATH.dirname(target), `.receiver-migration-${randomBytes(8).toString('hex')}`)\n await mkdir(staging, { mode: 0o700 })\n const file = PATH.join(staging, 'receiver.sqlite')\n try {\n const receiver = openReceiverAuthority(file)\n try {\n importEntries(receiver.database, entries)\n receiver.database.exec('PRAGMA wal_checkpoint(TRUNCATE)')\n } finally {\n receiver.close()\n }\n await verifySource()\n // Exclusive publication never overwrites a pre-existing receiver.\n await link(file, target)\n await syncDirectory(PATH.dirname(target))\n await unlink(file)\n } finally {\n await rm(staging, { recursive: true, force: true })\n }\n}\n\ninterface MigrationLocations {\n readonly backupPath?: string\n readonly sourcePath: string\n readonly targetPath?: string\n}\n\nasync function prepareLocations(options: ReceiverMigrationOptions): Promise<MigrationLocations> {\n if (options?.consumersStopped !== true) throw new TypeError('Migration requires every source writer and consumer to be stopped')\n if (!['filesystem', 'sqlite-queue'].includes(options.source.kind)) throw new TypeError('Unknown receiver migration source format')\n if (options.source.kind === 'sqlite-queue' && options.source.scope !== 'queue-only') throw new TypeError('SQLite queue migration requires explicit queue-only scope')\n const sourcePath = await realpath(options.source.path)\n if (!(await lstat(options.source.path)).isDirectory()) throw new TypeError('Migration source must be an owned store directory')\n const backupPath = options.backupPath === undefined ? undefined : await outsideSource(sourcePath, options.backupPath)\n const targetPath = options.targetPath === undefined ? undefined : await outsideSource(sourcePath, options.targetPath)\n if (!options.dryRun && (backupPath === undefined || targetPath === undefined)) throw new TypeError('Execution requires distinct backupPath and targetPath')\n if (backupPath !== undefined && targetPath !== undefined\n && (targetPath === backupPath || targetPath.startsWith(`${backupPath}${PATH.sep}`) || backupPath.startsWith(`${targetPath}${PATH.sep}`))) {\n throw new TypeError('Backup and target paths must be separate')\n }\n return {\n backupPath, sourcePath, targetPath,\n }\n}\n\nasync function prepareCopy(options: ReceiverMigrationOptions, paths: MigrationLocations, scratch: string): Promise<readonly ReceiverMigrationFile[]> {\n if (options.dryRun) return await snapshotMigrationSource(paths.sourcePath, PATH.join(scratch, 'source'))\n await mkdir(PATH.dirname(paths.backupPath!), { recursive: true, mode: 0o700 })\n await mkdir(paths.backupPath!, { mode: 0o700 })\n const files = await snapshotMigrationSource(paths.sourcePath, PATH.join(paths.backupPath!, 'source'))\n await syncDirectory(paths.backupPath!)\n await snapshotMigrationSource(PATH.join(paths.backupPath!, 'source'), PATH.join(scratch, 'source'))\n return files\n}\n\nfunction migrationReport(\n paths: MigrationLocations,\n files: readonly ReceiverMigrationFile[],\n plan: ReceiverMigrationPlan,\n options: ReceiverMigrationOptions,\n): ReceiverMigrationReport {\n const dryRun = options.dryRun === true\n const ready = plan.unknown.length === 0\n return {\n ...(paths.backupPath === undefined || dryRun ? {} : { backupPath: paths.backupPath }),\n completedIdentities: plan.entries.filter(entry => entry.state === 'completed').length,\n executed: ready && !dryRun,\n files,\n pendingIdentities: plan.entries.filter(entry => entry.state === 'pending').length,\n quarantined: plan.quarantined,\n ready,\n reviews: (options.reviews ?? []).map(review => ({\n action: review.action,\n evidence: review.evidence,\n identity: review.identity,\n ...(review.queueOrder === undefined ? {} : { queueOrder: review.queueOrder }),\n })),\n rollback,\n selected: plan.entries.map(entry => ({\n ...(entry.state === 'completed' ? { completionProvenance: 'Fresh reviewed migration tombstone; no historical lease or ack inferred' as const } : {}),\n eventHash: entry.receipt?.eventHash ?? entry.wake?.eventHash,\n identity: entry.identity,\n paths: entry.paths,\n ...(entry.queueOrder === undefined ? {} : { queueOrder: entry.queueOrder }),\n state: entry.state,\n })),\n sourceBytes: files.reduce((total, file) => total + file.bytes, 0),\n sourcePath: paths.sourcePath,\n sourceUnchanged: true,\n tokenRecords: plan.entries.reduce((total, entry) => total + entry.tokens.length, 0),\n unknown: plan.unknown,\n ...(paths.targetPath === undefined || dryRun ? {} : { targetPath: paths.targetPath }),\n }\n}\n\n/** Offline copy-only migration. Unknown history blocks target publication. */\nexport async function migrateReceiverStore(options: ReceiverMigrationOptions): Promise<ReceiverMigrationReport> {\n const paths = await prepareLocations(options)\n const scratch = await mkdtemp(PATH.join(OS.tmpdir(), 'event-kit-receiver-migration-'))\n try {\n const files = await prepareCopy(options, paths, scratch)\n const verify = async () => {\n await verifyMigrationSource(paths.sourcePath, files)\n }\n await verify()\n const plan = await inventoryReceiverMigration(options.source, PATH.join(scratch, 'source'), files, options.reviews ?? [])\n if (!options.dryRun) await writeReport(PATH.join(paths.backupPath!, 'migration-plan.json'), { ...migrationReport(paths, files, plan, options), executed: false })\n if (plan.unknown.length === 0 && !options.dryRun) await publishMigratedStore(paths.targetPath!, plan.entries, verify)\n await verify()\n const report = migrationReport(paths, files, plan, options)\n if (!options.dryRun) await writeReport(PATH.join(paths.backupPath!, 'migration-report.json'), report)\n return report\n } finally {\n await rm(scratch, { recursive: true, force: true })\n }\n}\n\nexport interface LegacyIdOnlyReducerCheckpoint {\n readonly appliedWakeIds: readonly string[]\n readonly lastProcessedPosition: number\n}\nexport interface MigratedReducerCheckpoint {\n readonly appliedWakes: readonly Pick<AdmittedWake, 'audience' | 'eventHash' | 'publisher' | 'wakeId'>[]\n readonly lastProcessedPosition: number\n}\n\n/** Requires one externally established exact scoped hash mapping for every historical ID. */\nexport function migrateIdOnlyReducerCheckpoint(\n checkpoint: LegacyIdOnlyReducerCheckpoint,\n mappings: MigratedReducerCheckpoint['appliedWakes'],\n): MigratedReducerCheckpoint {\n if (!Number.isSafeInteger(checkpoint.lastProcessedPosition) || checkpoint.lastProcessedPosition < -1) throw new TypeError('Invalid historical checkpoint position')\n const ids = new Set(checkpoint.appliedWakeIds.map(id => WakeIdZod.parse(id)))\n const records = new Map<string, MigratedReducerCheckpoint['appliedWakes'][number]>()\n for (const mapping of mappings) {\n const record = {\n audience: WakeJwtAudienceZod.parse(mapping.audience),\n eventHash: HashZod.parse(mapping.eventHash),\n publisher: NormalizedAddressZod.parse(mapping.publisher),\n wakeId: WakeIdZod.parse(mapping.wakeId),\n }\n if (!ids.has(record.wakeId) || records.has(record.wakeId)) throw new TypeError('Checkpoint mapping is extraneous or ambiguous')\n records.set(record.wakeId, record)\n }\n if (records.size !== ids.size) throw new TypeError('Every historical wake ID requires an exact scoped hash mapping')\n return { appliedWakes: [...ids].map(id => records.get(id)!), lastProcessedPosition: checkpoint.lastProcessedPosition }\n}\n", "import { readFile } from 'node:fs/promises'\nimport PATH from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nimport type { AdmittedWake, WakeAdmissionReceipt } from '@xyo-network/event-kit-protocol'\nimport { parseAdmittedWake } from '@xyo-network/event-kit-protocol'\nimport {\n HashZod, NonnegativeJsonSafeIntegerZod, NormalizedAddressZod, WakeIdZod, WakeJwtAudienceZod, WakeJwtIdZod,\n} from '@xyo-network/event-kit-schemas'\nimport { z } from 'zod'\n\nimport { receiverIdentity } from './receiverAuthority.ts'\nimport { migrationRelativePath } from './receiverMigrationSnapshot.ts'\nimport type {\n FilesystemReceiverMigrationSource, LegacyMigrationToken, ReceiverMigrationEntry, ReceiverMigrationFile, ReceiverMigrationIssue,\n ReceiverMigrationPlan, ReceiverMigrationQueueOrder, ReceiverMigrationReview, ReceiverMigrationSource, SqliteQueueMigrationSource,\n} from './receiverMigrationTypes.ts'\n\nconst ReceiptZod = z.strictObject({\n audience: WakeJwtAudienceZod, eventHash: HashZod, id: HashZod, publisher: NormalizedAddressZod, wakeId: WakeIdZod,\n})\nconst recordShape = {\n audience: WakeJwtAudienceZod, eventHash: HashZod, publisher: NormalizedAddressZod, receipt: ReceiptZod, wakeId: WakeIdZod,\n}\nconst WakeRecordZod = z.strictObject(recordShape)\nconst TokenRecordZod = z.strictObject({\n ...recordShape, jwtId: WakeJwtIdZod, retainJwtUntil: NonnegativeJsonSafeIntegerZod,\n})\ntype LegacyWakeRecord = z.infer<typeof WakeRecordZod>\n\ninterface Group {\n readonly bodies: { readonly order: Exclude<ReceiverMigrationQueueOrder, { readonly kind: 'reviewed-after-known' }>; readonly path: string; readonly wake: AdmittedWake }[]\n readonly identity: string\n readonly paths: Set<string>\n readonly queueOnly: boolean\n readonly reasons: string[]\n readonly receipts: LegacyWakeRecord[]\n readonly tokens: LegacyMigrationToken[]\n}\n\nexport function validateMigrationReceipt(receipt: WakeAdmissionReceipt): WakeAdmissionReceipt {\n const parsed = ReceiptZod.parse(receipt)\n if (parsed.id !== receiverIdentity([parsed.audience, parsed.publisher, parsed.wakeId])) throw new TypeError('Legacy receipt ID does not match its scoped identity')\n return parsed\n}\n\nfunction validateRecord(record: LegacyWakeRecord): void {\n const receipt = validateMigrationReceipt(record.receipt)\n if (receipt.audience !== record.audience || receipt.publisher !== record.publisher\n || receipt.wakeId !== record.wakeId || receipt.eventHash !== record.eventHash) {\n throw new TypeError('Legacy receipt does not match its record')\n }\n}\n\nfunction scope(value: Pick<AdmittedWake, 'audience' | 'publisher' | 'wakeId'>): string {\n return receiverIdentity([value.audience, value.publisher, value.wakeId])\n}\n\nfunction issue(group: Group, reason: string): ReceiverMigrationIssue {\n return {\n identity: group.identity, paths: [...group.paths], reason,\n }\n}\n\nfunction admissionIssue(group: Group, receipt: WakeAdmissionReceipt | undefined, wake: AdmittedWake | undefined, review?: ReceiverMigrationReview): ReceiverMigrationIssue | undefined {\n if (receipt?.id !== group.identity) return issue(group, 'Admission receipt is missing or disagrees with reviewed identity')\n if (review?.action !== 'completed' && (wake === undefined || scope(wake) !== group.identity || wake.eventHash !== receipt.eventHash)) {\n return issue(group, 'Receipt has no exact validated pending body; completion remains unknown')\n }\n if (group.tokens.some(token => token.eventHash !== receipt.eventHash || JSON.stringify(token.receipt) !== JSON.stringify(receipt))) {\n return issue(group, 'Token history conflicts with the reviewed receipt')\n }\n return review === undefined && (group.reasons.length > 0 || group.receipts.some(record => record.eventHash !== receipt.eventHash)\n || group.bodies.some(body => body.wake.eventHash !== receipt.eventHash))\n ? issue(group, 'Legacy body/receipt mappings disagree; explicit review is required')\n : undefined\n}\n\nfunction queueIssue(\n group: Group,\n receipt: WakeAdmissionReceipt | undefined,\n wake: AdmittedWake | undefined,\n review?: ReceiverMigrationReview,\n): ReceiverMigrationIssue | undefined {\n return group.reasons.length > 0 || wake === undefined || receipt !== undefined || review?.action === 'completed'\n ? issue(group, 'Standalone queue migration cannot infer receipt or completion history')\n : undefined\n}\n\nasync function selectEntry(group: Group, review?: ReceiverMigrationReview): Promise<ReceiverMigrationEntry | ReceiverMigrationIssue> {\n const receipt = review?.receipt === undefined ? group.receipts[0]?.receipt : validateMigrationReceipt(review.receipt)\n const wake = review?.wake === undefined\n ? group.bodies.find(body => receipt === undefined || body.wake.eventHash === receipt.eventHash)?.wake\n : await parseAdmittedWake(review.wake)\n const invalid = group.queueOnly ? queueIssue(group, receipt, wake, review) : admissionIssue(group, receipt, wake, review)\n if (invalid !== undefined) return invalid\n const queueOrder = review?.action === 'completed' ? undefined : selectQueueOrder(group, wake!, review)\n return queueOrder !== undefined && !('kind' in queueOrder) ? queueOrder : migrationEntry(group, receipt, wake, queueOrder, review)\n}\n\nfunction migrationEntry(\n group: Group,\n receipt: WakeAdmissionReceipt | undefined,\n wake: AdmittedWake | undefined,\n queueOrder: ReceiverMigrationQueueOrder | undefined,\n review?: ReceiverMigrationReview,\n): ReceiverMigrationEntry {\n return {\n evidence: review?.evidence ?? 'Exact validated legacy receipt and pending/inflight body; no fresh grant inferred',\n identity: group.identity,\n paths: [...group.paths],\n ...(receipt === undefined ? {} : { receipt }),\n ...(queueOrder === undefined ? {} : { queueOrder }),\n state: review?.action === 'completed' ? 'completed' : 'pending',\n tokens: group.tokens,\n ...(wake === undefined ? {} : { wake }),\n }\n}\n\nfunction compareQueueOrder(left: ReceiverMigrationQueueOrder, right: ReceiverMigrationQueueOrder): number {\n if (left.kind === 'reviewed-after-known') return right.kind === 'reviewed-after-known' ? 0 : 1\n if (right.kind === 'reviewed-after-known') return -1\n if (left.kind === 'sqlite-row-id' && right.kind === 'sqlite-row-id') return left.id - right.id\n if (left.kind === 'filesystem-entry-name' && right.kind === 'filesystem-entry-name') {\n // Match the legacy queue's default Array.toSorted() comparison exactly.\n return left.name < right.name ? -1 : left.name > right.name ? 1 : 0\n }\n throw new TypeError('Migration cannot combine unrelated source queue orders')\n}\n\nfunction selectQueueOrder(group: Group, wake: AdmittedWake, review?: ReceiverMigrationReview): ReceiverMigrationQueueOrder | ReceiverMigrationIssue {\n const matches = group.bodies.filter(body => body.wake.eventHash === wake.eventHash)\n .toSorted((left, right) => compareQueueOrder(left.order, right.order))\n const original = matches[0]?.order\n if (original !== undefined) return review?.queueOrder === undefined ? original : issue(group, 'Reviewed placement cannot override a matching original queue reference')\n return review?.queueOrder === undefined\n ? issue(group, 'Original queue order is unknown; an explicit after-known placement review is required')\n : { kind: 'reviewed-after-known', evidence: review.queueOrder.evidence }\n}\n\nfunction compareEntries(left: ReceiverMigrationEntry, right: ReceiverMigrationEntry): number {\n if (left.state === 'completed') return right.state === 'completed' ? 0 : 1\n return right.state === 'completed' ? -1 : compareQueueOrder(left.queueOrder!, right.queueOrder!)\n}\n\ninterface Collector {\n readonly groupFor: (identity: string, path: string, queueOnly?: boolean) => Group\n readonly groups: Map<string, Group>\n readonly invalid: (path: string, reason: string) => void\n readonly recognized: Set<string>\n}\n\nfunction createCollector(): Collector {\n const groups = new Map<string, Group>()\n const groupFor = (identity: string, path: string, queueOnly = false): Group => {\n let group = groups.get(identity)\n if (group === undefined) {\n group = {\n identity, paths: new Set(), bodies: [], receipts: [], reasons: [], tokens: [], queueOnly,\n }\n groups.set(identity, group)\n }\n group.paths.add(path)\n return group\n }\n return {\n groups,\n groupFor,\n recognized: new Set(),\n invalid(path, reason) { groupFor(`artifact:${path}`, path).reasons.push(reason) },\n }\n}\n\nfunction filesystemKind(queueRelative: string, inboxRelative: string): 'body' | 'receipt' | 'token' | undefined {\n if (/^(pending|inflight)\\/[\\w.-]+\\.json$/.test(queueRelative)) return 'body'\n if (/^wakes\\/[a-f0-9]{64}\\.json$/.test(inboxRelative)) return 'receipt'\n return /^tokens\\/[a-f0-9]{64}\\.json$/.test(inboxRelative) ? 'token' : undefined\n}\n\nasync function readFilesystemRecord(collector: Collector, absolute: string, path: string, kind: 'body' | 'receipt' | 'token'): Promise<void> {\n const raw: unknown = JSON.parse(await readFile(absolute, 'utf8'))\n if (kind === 'body') {\n const wake = await parseAdmittedWake(raw)\n collector.groupFor(scope(wake), path).bodies.push({\n order: {\n kind: 'filesystem-entry-name', name: PATH.basename(path), path,\n },\n path,\n wake,\n })\n return\n }\n const record = kind === 'receipt' ? WakeRecordZod.parse(raw) : TokenRecordZod.parse(raw)\n validateRecord(record)\n const key = kind === 'receipt' ? scope(record) : receiverIdentity([record.audience, record.publisher, (record as LegacyMigrationToken).jwtId])\n if (PATH.basename(path) !== `${key}.json`) throw new TypeError('Legacy record filename disagrees with identity')\n const group = collector.groupFor(scope(record), path)\n if (kind === 'receipt') group.receipts.push(record)\n else group.tokens.push(record as LegacyMigrationToken)\n}\n\nasync function scanFilesystem(source: FilesystemReceiverMigrationSource, root: string, files: readonly ReceiverMigrationFile[], collector: Collector): Promise<void> {\n const queueRoot = migrationRelativePath(root, source.queueDirectory)\n const inboxRoot = migrationRelativePath(root, source.inboxDirectory)\n for (const file of files) {\n const absolute = PATH.join(root, file.path)\n const kind = filesystemKind(PATH.relative(queueRoot, absolute), PATH.relative(inboxRoot, absolute))\n if (kind === undefined) continue\n collector.recognized.add(file.path)\n try {\n await readFilesystemRecord(collector, absolute, file.path, kind)\n } catch {\n collector.invalid(file.path, 'Malformed, corrupt, or incorrectly bound legacy record; exact bytes archived')\n }\n }\n}\n\nasync function scanSqlite(source: SqliteQueueMigrationSource, root: string, collector: Collector): Promise<void> {\n if (source.scope !== 'queue-only') throw new TypeError('SQLite queue migration requires explicit queue-only scope')\n const file = migrationRelativePath(root, source.databaseFile)\n for (const name of [source.databaseFile, `${source.databaseFile}-wal`, `${source.databaseFile}-shm`, `${source.databaseFile}-journal`]) collector.recognized.add(PATH.normalize(name))\n const database = new DatabaseSync(file, { readOnly: true })\n try {\n const tables = database.prepare(\"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\").all()\n if (tables.length !== 1 || tables[0]?.name !== 'wake_queue') throw new TypeError('Expected a legacy queue-only SQLite store')\n for (const row of database.prepare('SELECT id,body,state FROM wake_queue ORDER BY id').all()) {\n const path = `${source.databaseFile}#wake_queue/${String(row.id)}`\n try {\n if (typeof row.id !== 'number' || !Number.isSafeInteger(row.id)\n || typeof row.body !== 'string' || (row.state !== 'pending' && row.state !== 'inflight')) throw new TypeError('Invalid legacy queue row')\n const wake = await parseAdmittedWake(JSON.parse(row.body) as unknown)\n collector.groupFor(`queue:${String(row.id)}`, path, true).bodies.push({\n order: {\n kind: 'sqlite-row-id', id: row.id, path,\n },\n path,\n wake,\n })\n } catch {\n collector.invalid(path, 'Invalid legacy SQLite queue row; exact database bytes archived')\n }\n }\n } finally {\n database.close()\n }\n}\n\n/** Inspects a disposable private copy only. Originals and exact-byte backups are never opened by SQLite. */\nexport async function inventoryReceiverMigration(\n source: ReceiverMigrationSource,\n copiedRoot: string,\n files: readonly ReceiverMigrationFile[],\n reviews: readonly ReceiverMigrationReview[],\n): Promise<ReceiverMigrationPlan> {\n const collector = createCollector()\n if (source.kind === 'filesystem') await scanFilesystem(source, copiedRoot, files, collector)\n else await scanSqlite(source, copiedRoot, collector)\n for (const file of files) {\n if (!collector.recognized.has(file.path)) collector.invalid(file.path, 'Unclassified source artifact; explicit review or quarantine is required')\n }\n return await finalizeGroups(collector.groups, reviews)\n}\n\nfunction reviewMap(groups: ReadonlyMap<string, Group>, reviews: readonly ReceiverMigrationReview[]): ReadonlyMap<string, ReceiverMigrationReview> {\n const reviewed = new Map<string, ReceiverMigrationReview>()\n for (const review of reviews) {\n if (!['pending', 'completed', 'quarantine'].includes(review.action)\n || review.evidence.trim().length === 0 || reviewed.has(review.identity)) throw new TypeError('Reviews require unique identities, an explicit action and external evidence references')\n if (!groups.has(review.identity)) throw new TypeError('Review does not correspond to an inventoried identity')\n if (review.queueOrder !== undefined && (review.action !== 'pending' || review.queueOrder.kind !== 'after-known'\n || review.queueOrder.evidence.trim().length === 0)) throw new TypeError('Queue placement requires a pending review, after-known choice and separate placement evidence')\n reviewed.set(review.identity, review)\n }\n return reviewed\n}\n\nasync function finalizeGroups(groups: ReadonlyMap<string, Group>, reviews: readonly ReceiverMigrationReview[]): Promise<ReceiverMigrationPlan> {\n const reviewed = reviewMap(groups, reviews)\n const entries: ReceiverMigrationEntry[] = []\n const quarantined: ReceiverMigrationIssue[] = []\n const unknown: ReceiverMigrationIssue[] = []\n for (const group of groups.values()) {\n const review = reviewed.get(group.identity)\n if (review?.action === 'quarantine') {\n quarantined.push(issue(group, review.evidence))\n continue\n }\n if (group.identity.startsWith('artifact:')) {\n unknown.push(issue(group, group.reasons.join('; ')))\n continue\n }\n const selected = await selectEntry(group, review)\n if ('reason' in selected) unknown.push(selected)\n else {\n entries.push(selected)\n const rejectedBodies = group.bodies.filter(body => selected.receipt !== undefined && body.wake.eventHash !== selected.receipt.eventHash)\n if (rejectedBodies.length > 0) quarantined.push({\n identity: `reviewed-conflicts:${group.identity}`,\n paths: rejectedBodies.map(body => body.path),\n reason: 'Reviewed mapping excluded conflicting bodies; exact bytes remain in the backup',\n })\n }\n }\n return {\n entries: entries.toSorted(compareEntries), quarantined, unknown,\n }\n}\n", "import { createHash } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport {\n lstat, mkdir, open, readdir,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport { syncDirectory } from './filesystemDurability.ts'\nimport type { ReceiverMigrationFile } from './receiverMigrationTypes.ts'\n\n/** Refuse symlinks and escaping configuration rather than following other stores. */\nexport function migrationRelativePath(root: string, relative: string): string {\n if (PATH.isAbsolute(relative)) throw new TypeError('Migration store paths must be relative')\n const resolved = PATH.resolve(root, relative)\n if (resolved !== root && !resolved.startsWith(`${root}${PATH.sep}`)) throw new TypeError('Migration path escapes its source store')\n return resolved\n}\n\nasync function readExact(path: string): Promise<{ bytes: Buffer; mode: number }> {\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)\n try {\n const before = await file.stat()\n if (!before.isFile()) throw new TypeError('Migration source must contain ordinary files only')\n const bytes = await file.readFile()\n const after = await file.stat()\n if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino) {\n throw new Error('Migration source changed while being copied')\n }\n return { bytes, mode: before.mode & 0o777 }\n } finally {\n await file.close()\n }\n}\n\nexport async function snapshotMigrationSource(root: string, destination?: string): Promise<readonly ReceiverMigrationFile[]> {\n const files: ReceiverMigrationFile[] = []\n async function visit(relative: string): Promise<void> {\n const source = PATH.join(root, relative)\n const info = await lstat(source)\n if (info.isSymbolicLink()) throw new TypeError('Migration source symlinks are unsupported')\n if (info.isDirectory()) {\n if (destination !== undefined) await mkdir(PATH.join(destination, relative), { mode: 0o700 })\n for (const child of (await readdir(source)).toSorted()) await visit(PATH.join(relative, child))\n if (destination !== undefined) await syncDirectory(PATH.join(destination, relative))\n return\n }\n const { bytes, mode } = await readExact(source)\n files.push({\n bytes: bytes.length, mode, path: relative, sha256: createHash('sha256').update(bytes).digest('hex'),\n })\n if (destination === undefined) return\n const target = await open(PATH.join(destination, relative), 'wx', 0o600)\n try {\n await target.writeFile(bytes)\n await target.sync()\n } finally {\n await target.close()\n }\n }\n await visit('')\n return files\n}\n\nexport async function verifyMigrationSource(root: string, files: readonly ReceiverMigrationFile[]): Promise<void> {\n const current = await snapshotMigrationSource(root)\n if (JSON.stringify(current) !== JSON.stringify(files)) throw new Error('Migration source changed; stop every owner and repeat on a new copy')\n}\n", "import { Buffer } from 'node:buffer'\n\nimport type { FetchGetUrlFunc } from 'ethers'\n\nimport { publisherAbortScope } from './abort.ts'\nexport interface BoundedPublisherFetchOptions {\n readonly maxConcurrency?: number\n readonly maxResponseBytes?: number\n readonly requestTimeoutMs?: number\n readonly signal?: AbortSignal\n}\n/** Per-instance SDK transport: aborts the real request, including its body, without changing global fetch. */\nexport function createBoundedPublisherFetch(options: BoundedPublisherFetchOptions = {}) {\n const owner = new AbortController()\n const timeout = options.requestTimeoutMs ?? 10_000\n const maximum = options.maxResponseBytes ?? 16 * 1024 * 1024\n const concurrency = options.maxConcurrency ?? 16\n if (!Number.isSafeInteger(timeout) || timeout < 100 || timeout > 60_000\n || !Number.isSafeInteger(maximum) || maximum < 1 || maximum > 64 * 1024 * 1024\n || !Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 64)\n throw new Error('Invalid publisher fetch limits')\n const active = new Set<Promise<Response>>()\n const nativeFetch = globalThis.fetch.bind(globalThis)\n const fetchFn: typeof globalThis.fetch = (input, init) => {\n if (active.size >= concurrency)\n return Promise.reject(new Error('Publisher HTTP concurrency limit exceeded'))\n const operation = (async () => {\n const signals = [owner.signal,\n ...(options.signal === undefined ? [] : [options.signal]),\n ...(init?.signal == null ? [] : [init.signal]),\n ...(input instanceof Request ? [input.signal] : [])]\n const scope = publisherAbortScope(signals, timeout)\n try {\n scope.signal.throwIfAborted()\n const response = await nativeFetch(input, {\n ...init, redirect: 'error', signal: scope.signal,\n })\n if (response.body === null)\n return response\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done)\n break\n const bytes: unknown = chunk.value\n if (!(bytes instanceof Uint8Array)) throw new Error('Publisher HTTP body returned a non-byte chunk')\n size += bytes.byteLength\n if (size > maximum) {\n await reader.cancel()\n throw new Error('Publisher HTTP body exceeds its bound')\n }\n chunks.push(bytes)\n }\n } finally {\n reader.releaseLock()\n }\n const headers = new Headers(response.headers)\n headers.delete('content-encoding')\n headers.delete('transfer-encoding')\n headers.set('content-length', String(size))\n return new Response(Buffer.concat(chunks), {\n status: response.status, statusText: response.statusText, headers,\n })\n } finally {\n scope.dispose()\n }\n })()\n active.add(operation)\n void operation.then(() => active.delete(operation), () => active.delete(operation))\n return operation\n }\n return {\n fetchFn,\n async close() {\n owner.abort()\n await Promise.allSettled(active)\n },\n get activeRequests() {\n return active.size\n },\n }\n}\n\n/** Ethers' documented per-request HTTP hook, without its unbounded Node body reader. */\nexport function createBoundedPublisherEthersTransport(options: BoundedPublisherFetchOptions = {}) {\n const bounded = createBoundedPublisherFetch(options)\n const getUrl: FetchGetUrlFunc = async (request, cancellation) => {\n const controller = new AbortController()\n cancellation?.addListener(() => controller.abort())\n cancellation?.checkSignal()\n const response = await bounded.fetchFn(request.url, {\n body: request.body === null ? undefined : Buffer.from(request.body),\n headers: request.headers,\n method: request.method,\n signal: controller.signal,\n })\n return {\n body: new Uint8Array(await response.arrayBuffer()),\n headers: Object.fromEntries(response.headers),\n statusCode: response.status,\n statusMessage: response.statusText,\n }\n }\n return {\n getUrl,\n async close() { await bounded.close() },\n get activeRequests() { return bounded.activeRequests },\n }\n}\n", "import { clearTimeout, setTimeout } from 'node:timers'\n\n/** Own every listener/timer used by a bounded operation; disposal is mandatory. */\nexport function publisherAbortScope(signals: readonly AbortSignal[], timeoutMs?: number) {\n const controller = new AbortController()\n const abort = () => controller.abort()\n const timer = timeoutMs === undefined ? undefined : setTimeout(abort, timeoutMs)\n timer?.unref()\n for (const signal of signals) {\n if (signal.aborted) controller.abort()\n else signal.addEventListener('abort', abort, { once: true })\n }\n return {\n signal: controller.signal,\n dispose() {\n if (timer !== undefined) clearTimeout(timer)\n for (const signal of signals) signal.removeEventListener('abort', abort)\n },\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport { decryptWakeSubscription, sourceWakeFilterHash } from '@xyo-network/event-kit-protocol'\nimport type {\n BestEffortDeliveryPolicy, EndpointChallengeResponse, WakeDeliveryMode,\n} from '@xyo-network/event-kit-schemas'\nimport { EndpointChallengeResponseZod } from '@xyo-network/event-kit-schemas'\nimport type { FinalizedSubscriptionTuple } from '@xyo-network/event-kit-statement-graph'\n\nimport type { PublisherEncryptionKeyCustody, PublisherHandshakeClient } from '../handshakeClients.ts'\nimport { publisherAbortScope } from './abort.ts'\nimport type { PublisherHttpsTransport } from './httpsTransport.ts'\nimport type {\n PublisherRuntimeDiscovery, PublisherRuntimeDiscoveryStatus, PublisherRuntimeSubscription,\n} from './publisherRuntime.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\ninterface PendingChallenge {\n readonly challengeHash: string\n readonly expiresAt: number\n readonly response?: EndpointChallengeResponse\n readonly subscriber: string\n readonly subscription: string\n}\n/** Real D005 lifecycle discovery. Off-chain configuration never grants delivery authority. */\nexport function createPublisherHandshakeDiscovery(options: {\n readonly authorizationChainId: string\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly client: PublisherHandshakeClient\n readonly deliveryMode?: WakeDeliveryMode\n readonly keys: PublisherEncryptionKeyCustody\n readonly maxSubscriptions?: number\n readonly nowSeconds?: () => number\n readonly publisher: string\n readonly serviceHash?: string\n readonly state: SqlitePublisherState\n readonly transport: PublisherHttpsTransport\n}): PublisherRuntimeDiscovery {\n const clock = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const owner = new AbortController()\n let accepting: Promise<void> | undefined\n let viewing: ReturnType<PublisherHandshakeClient['subscriptions']> | undefined\n let status: PublisherRuntimeDiscoveryStatus = {\n authorizationChainId: options.authorizationChainId,\n keyLoaded: false,\n activeKeyIds: [],\n pendingSubscriptions: 0,\n rejectedSubscriptions: 0,\n challengeFailures: 0,\n }\n function selectedTuple(tuple: FinalizedSubscriptionTuple): boolean {\n return (options.serviceHash === undefined || tuple.service.objectHash === options.serviceHash)\n && (options.deliveryMode === undefined || tuple.service.body.deliveryMode === options.deliveryMode)\n && (options.deliveryMode === undefined || tuple.subscription.body.deliveryMode === options.deliveryMode)\n && (options.deliveryMode === undefined || isDeepStrictEqual(tuple.service.body.bestEffort, options.bestEffort))\n }\n async function activeView(signal: AbortSignal) {\n signal.throwIfAborted()\n // A timed-out caller does not create a second SDK replay while the first\n // remains in flight. The configured REST transport aborts actual reads.\n viewing ??= (async () => {\n try {\n return await options.client.subscriptions()\n } finally {\n viewing = undefined\n }\n })()\n const view = await viewing\n signal.throwIfAborted()\n if (!view.ok || view.indexedThrough !== view.finalizedHead)\n throw new Error('Publisher subscription view is unavailable or stale')\n status = {\n ...status,\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n pendingSubscriptions: view.subscriptions.filter(item => item.state === 'pending' && item.tuples.some(selectedTuple)).length,\n rejectedSubscriptions: view.rejections.length,\n }\n return view\n }\n async function acceptCandidate(subscriber: string, subscription: string, signal: AbortSignal) {\n try {\n let pending = options.state.get<PendingChallenge>('outbound-challenges', subscription)\n if (pending !== undefined && pending.response === undefined && clock() >= pending.expiresAt)\n pending = undefined\n if (pending === undefined) {\n const issued = await options.client.issueChallenge({\n issuedAt: clock(), lifetimeSeconds: 300, subscriber: subscriber, subscription,\n })\n pending = {\n challengeHash: issued.challengeHash, subscriber: subscriber, subscription, expiresAt: issued.challenge.expiresAt,\n }\n options.state.set('outbound-challenges', subscription, pending)\n }\n if (pending.response === undefined) {\n const begun = await options.client.beginChallenge({ challengeHash: pending.challengeHash, nowSeconds: clock })\n if (begun.kind !== 'started')\n return\n signal.throwIfAborted()\n const response = await options.transport.post(begun.target.endpoint, begun.challenge, signal)\n if (response.status !== 200)\n throw new Error('Endpoint challenge was rejected')\n pending = { ...pending, response: EndpointChallengeResponseZod.parse(response.body) }\n options.state.set('outbound-challenges', subscription, pending)\n }\n signal.throwIfAborted()\n const response = pending.response\n if (response === undefined)\n throw new Error('Endpoint proof is unavailable')\n await options.client.completeChallengeAndAccept({\n ...pending, response, nowSeconds: clock,\n })\n } catch {\n if (signal.aborted)\n return\n const failures = options.state.get<number>('challenge-failures', subscription) ?? 0\n options.state.set('challenge-failures', subscription, failures + 1)\n const pending = options.state.get<PendingChallenge>('outbound-challenges', subscription)\n if (pending !== undefined && clock() >= pending.expiresAt)\n options.state.remove('outbound-challenges', subscription)\n }\n }\n\n async function accept(signal: AbortSignal) {\n signal.throwIfAborted()\n const now = clock()\n if (now < (options.state.get<number>('challenge-rate', 'next-pass') ?? 0))\n return\n options.state.set('challenge-rate', 'next-pass', now + 10)\n const found = await options.client.acceptanceCandidates()\n if (!found.ok)\n throw new Error('Publisher acceptance candidates are unavailable')\n const offset = options.state.get<number>('challenge-rate', 'offset') ?? 0\n const candidates = found.candidates.filter(candidate => selectedTuple(candidate.tuple))\n let attempted = 0\n // Bound inspected candidates and rotate the starting point: four failed\n // candidates must not permanently prevent the fifth from being challenged.\n for (let index = 0; index < Math.min(candidates.length, 128) && attempted < 4; index += 1) {\n const candidate = candidates[(offset + index) % candidates.length]\n if (candidate === undefined)\n break\n options.state.set('challenge-rate', 'offset', (offset + index + 1) % candidates.length)\n const next = options.state.get<number>('challenge-controller-rate', candidate.subscriber) ?? 0\n if (now < next)\n continue\n options.state.set('challenge-controller-rate', candidate.subscriber, now + 30)\n attempted += 1\n signal.throwIfAborted()\n await acceptCandidate(candidate.subscriber, candidate.tuple.subscription.objectHash, signal)\n }\n }\n async function loadScopedKeys(view: Extract<Awaited<ReturnType<PublisherHandshakeClient['subscriptions']>>, { ok: true }>, active: typeof view.subscriptions) {\n const scopedKeys = active.flatMap(item => item.tuples.filter(tuple => tuple.subscription.objectHash === item.selectedSubscription).map(tuple => ({\n encryptionKey: tuple.subscription.body.encryptionKey, keyId: tuple.subscription.body.keyId, publisher: options.publisher,\n })))\n if (view.hasCurrentAdvertisement && (options.serviceHash === undefined || view.service.objectHash === options.serviceHash)\n && (options.deliveryMode === undefined || view.service.body.deliveryMode === options.deliveryMode)) {\n scopedKeys.push({\n encryptionKey: view.key.objectHash, keyId: view.key.body.keyId, publisher: options.publisher,\n })\n }\n const loadedKeys = await Promise.all(scopedKeys.map(async key => await options.keys.getPrivateKey(key)))\n status = {\n ...status,\n keyLoaded: scopedKeys.length > 0 && loadedKeys.every(key => key !== undefined),\n activeKeyIds: [...new Set(scopedKeys.map(key => key.keyId))],\n }\n }\n return {\n async discover(signal) {\n const view = await activeView(signal)\n const active = view.subscriptions.filter(item => item.state === 'active' && item.tuples.some(tuple => tuple.subscription.objectHash === item.selectedSubscription && selectedTuple(tuple)))\n await loadScopedKeys(view, active)\n if (active.length > (options.maxSubscriptions ?? 64))\n throw new Error('Publisher active subscription limit exceeded')\n const subscriptions: PublisherRuntimeSubscription[] = []\n for (const lifecycle of active) {\n if (lifecycle.state !== 'active' || lifecycle.activeFromBlock === undefined)\n continue\n try {\n const tuple = lifecycle.tuples.find(item => item.subscription.objectHash === lifecycle.selectedSubscription)\n if (tuple === undefined || !selectedTuple(tuple))\n throw new Error('Active publisher subscription has no selected tuple')\n const encrypted = tuple.subscription.body\n if (encrypted.chainId !== options.authorizationChainId)\n throw new Error('Subscription authorization chain mismatch')\n const publisherKey = await options.keys.getPrivateKey({\n encryptionKey: encrypted.encryptionKey, keyId: encrypted.keyId, publisher: options.publisher,\n })\n if (publisherKey === undefined)\n throw new Error('Subscription encryption key is unavailable')\n const plaintext = await decryptWakeSubscription({\n publisherKey, subscriber: tuple.subscriber, subscription: encrypted,\n })\n options.transport.assertAllowed(plaintext.endpoint)\n subscriptions.push({\n subscriptionHash: tuple.subscription.objectHash,\n serviceHash: tuple.service.objectHash,\n deliveryMode: plaintext.filter.deliveryMode,\n ...(plaintext.filter.bestEffort === undefined ? {} : { bestEffort: plaintext.filter.bestEffort }),\n authorizationChainId: options.authorizationChainId,\n controller: tuple.subscriber,\n audience: plaintext.audience,\n endpoint: plaintext.endpoint,\n deploymentId: plaintext.deploymentId,\n ...(plaintext.queueId === null ? {} : { queueId: plaintext.queueId }),\n source: plaintext.filter.source,\n fromPosition: plaintext.filter.fromPosition,\n maxPositionsPerWake: plaintext.filter.maxPositionsPerWake,\n filterHash: await sourceWakeFilterHash(plaintext.filter),\n })\n } catch {\n // A malformed or locally disallowed endpoint cannot stop independent\n // accepted subscribers. Durable pending work remains until a fresh\n // authoritative check proves the subscription is inactive.\n status = { ...status, rejectedSubscriptions: status.rejectedSubscriptions + 1 }\n }\n }\n return subscriptions\n },\n async isActive(subscription, signal) {\n const view = await activeView(signal)\n return view.subscriptions.some(item => item.state === 'active' && item.selectedSubscription === subscription.subscriptionHash\n && item.tuples.some(tuple => tuple.subscription.objectHash === subscription.subscriptionHash && tuple.subscriber === subscription.controller && selectedTuple(tuple)))\n },\n async acceptPending(signal) {\n // A slow finality operation is shared across passes; timeout does not\n // spawn another acceptance/signing operation against the same state.\n if (accepting === undefined) {\n const scope = publisherAbortScope([owner.signal, signal])\n accepting = (async () => {\n try {\n await accept(scope.signal)\n } finally {\n scope.dispose()\n accepting = undefined\n }\n })()\n }\n await accepting\n },\n async close() {\n await Promise.allSettled([accepting, viewing].filter(item => item !== undefined))\n },\n status: () => ({ ...status, challengeFailures: options.state.entries<number>('challenge-failures').reduce((sum, item) => sum + item.value, 0) }),\n }\n}\n", "import { Buffer } from 'node:buffer'\nimport { lookup } from 'node:dns/promises'\nimport { request } from 'node:https'\nimport { BlockList, isIP } from 'node:net'\n\nimport { z } from 'zod'\n\nimport { publisherAbortScope } from './abort.ts'\nimport { boundedPublisherOperation } from './sources.ts'\nconst OptionsZod = z.strictObject({\n allowedEndpoints: z.array(z.url()).min(1).max(64),\n endpointHeaders: z.array(z.strictObject({\n endpoint: z.url(),\n headers: z.strictObject({ 'x-vercel-protection-bypass': z.string().min(1).max(4096).regex(/^[\\u{21}-\\u{7E}]+$/u) }),\n })).max(64).default([]),\n maxResponseBytes: z.number().int().min(1).max(1_048_576).default(65_536),\n requestTimeoutMs: z.number().int().min(100).max(60_000).default(10_000),\n})\nexport interface PublisherHttpsTransportOptions {\n /** Exact public HTTPS destinations approved by the operator, including their path. */\n readonly allowedEndpoints: readonly string[]\n /** Private operator-provisioned Vercel automation credential, bound to one exact destination. */\n readonly endpointHeaders?: readonly { readonly endpoint: string; readonly headers: Readonly<Record<string, string>> }[]\n readonly maxResponseBytes?: number\n readonly requestTimeoutMs?: number\n}\nexport interface PublisherHttpsResponse {\n readonly body: unknown\n readonly retryAfterMs?: number\n readonly status: number\n}\nexport interface PublisherHttpsTransport {\n assertAllowed(endpoint: string): void\n post(endpoint: string, body: unknown, signal: AbortSignal, jwt?: string): Promise<PublisherHttpsResponse>\n}\nconst NON_PUBLIC_IPV4_SUBNETS = [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.0.0.0', 24],\n ['192.0.2.0', 24],\n ['192.88.99.0', 24],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['198.51.100.0', 24],\n ['203.0.113.0', 24],\n ['224.0.0.0', 4],\n ['240.0.0.0', 4],\n] as const\nconst NON_PUBLIC_IPV6_SUBNETS = [\n ['2001::', 23], ['2001:db8::', 32], ['2002::', 16], ['3fff::', 20],\n] as const\n\ninterface PublisherAddressPolicy {\n readonly globalIpv6: BlockList\n readonly nonPublicIpv4: BlockList\n readonly nonPublicIpv6: BlockList\n}\n\nlet publisherAddressPolicy: PublisherAddressPolicy | undefined\n\nfunction loadPublisherAddressPolicy(): PublisherAddressPolicy {\n if (publisherAddressPolicy !== undefined) return publisherAddressPolicy\n const nonPublicIpv4 = new BlockList()\n for (const [address, prefix] of NON_PUBLIC_IPV4_SUBNETS) {\n nonPublicIpv4.addSubnet(address, prefix, 'ipv4')\n }\n const globalIpv6 = new BlockList()\n globalIpv6.addSubnet('2000::', 3, 'ipv6')\n const nonPublicIpv6 = new BlockList()\n for (const [address, prefix] of NON_PUBLIC_IPV6_SUBNETS) {\n nonPublicIpv6.addSubnet(address, prefix, 'ipv6')\n }\n publisherAddressPolicy = {\n globalIpv6, nonPublicIpv4, nonPublicIpv6,\n }\n return publisherAddressPolicy\n}\n\n/** Conservative public-unicast policy, with numeric subnet checks for every IPv6 spelling. */\nexport function isPublicPublisherAddress(address: string): boolean {\n const policy = loadPublisherAddressPolicy()\n return isIP(address) === 4\n ? !policy.nonPublicIpv4.check(address, 'ipv4')\n : isIP(address) === 6 && policy.globalIpv6.check(address, 'ipv6') && !policy.nonPublicIpv6.check(address, 'ipv6')\n}\nexport function createPublisherHttpsTransport(input: PublisherHttpsTransportOptions): PublisherHttpsTransport {\n const parsed = OptionsZod.safeParse(input)\n if (!parsed.success) throw new Error('Invalid publisher HTTPS transport configuration')\n const options = parsed.data\n const allowed = new Set(options.allowedEndpoints.map((endpoint) => {\n const url = new URL(endpoint)\n if (url.href !== endpoint || url.protocol !== 'https:' || (url.port !== '' && url.port !== '443')\n || url.username !== '' || url.password !== '' || url.hash !== '')\n throw new Error('Publisher destinations must be canonical public HTTPS URLs on port 443')\n const literal = url.hostname.replaceAll(/^\\[|\\]$/gu, '')\n if (isIP(literal) !== 0 && !isPublicPublisherAddress(literal))\n throw new Error('Publisher destination is not public')\n if (url.hostname === 'localhost' || url.hostname.endsWith('.localhost') || url.hostname.endsWith('.local'))\n throw new Error('Publisher destination is not public')\n return endpoint\n }))\n const assertAllowed = (endpoint: string) => {\n if (!allowed.has(endpoint))\n throw new Error('Publisher destination is not explicitly allowed')\n }\n const endpointHeaders = new Map<string, Readonly<Record<string, string>>>()\n for (const entry of options.endpointHeaders) {\n assertAllowed(entry.endpoint)\n if (endpointHeaders.has(entry.endpoint)) throw new Error('Duplicate publisher endpoint header configuration')\n endpointHeaders.set(entry.endpoint, entry.headers)\n }\n return {\n assertAllowed,\n async post(endpoint, body, signal, jwt) {\n assertAllowed(endpoint)\n signal.throwIfAborted()\n const url = new URL(endpoint)\n const scope = publisherAbortScope([signal], options.requestTimeoutMs)\n const combined = scope.signal\n try {\n const addresses = await boundedPublisherOperation(lookup(url.hostname.replaceAll(/^\\[|\\]$/gu, ''), { all: true, verbatim: true }), combined, options.requestTimeoutMs)\n combined.throwIfAborted()\n if (addresses.length === 0 || addresses.some(item => !isPublicPublisherAddress(item.address)))\n throw new Error('Publisher DNS answer includes a non-public address')\n const selected = addresses[0]\n if (selected === undefined)\n throw new Error('Publisher DNS lookup was empty')\n const encoded = Buffer.from(JSON.stringify(body))\n if (encoded.byteLength > 65_536)\n throw new Error('Publisher request body is too large')\n return await new Promise<PublisherHttpsResponse>((resolve, reject) => {\n const call = request(url, {\n agent: false,\n headers: {\n ...endpointHeaders.get(endpoint),\n 'content-length': encoded.byteLength,\n 'content-type': 'application/json',\n ...(jwt === undefined ? {} : { authorization: `Bearer ${jwt}` }),\n },\n lookup(_hostname, lookupOptions, callback) {\n // Pin the validated DNS answer for this connection; TLS still validates\n // the original hostname. No second resolver can rebind to a private IP.\n if (lookupOptions.all)\n callback(null, [{ address: selected.address, family: selected.family }])\n else\n callback(null, selected.address, selected.family)\n },\n method: 'POST',\n rejectUnauthorized: true,\n signal: combined,\n }, (response) => {\n const status = response.statusCode ?? 500\n if (status >= 300 && status < 400) {\n response.destroy()\n reject(new Error('Publisher HTTPS redirects are forbidden'))\n return\n }\n let size = 0\n const chunks: Buffer[] = []\n response.on('data', (chunk: Buffer) => {\n size += chunk.byteLength\n if (size > options.maxResponseBytes) {\n response.destroy()\n reject(new Error('Publisher HTTPS response is too large'))\n } else\n chunks.push(chunk)\n })\n response.on('error', () => reject(new Error('Publisher HTTPS response failed')))\n response.on('end', () => {\n try {\n const responseBody: unknown = size === 0 ? null : JSON.parse(Buffer.concat(chunks).toString('utf8'))\n const retry = Number(response.headers['retry-after'])\n resolve({\n status, body: responseBody, ...(Number.isFinite(retry) && retry > 0 ? { retryAfterMs: Math.min(retry * 1000, 3_600_000) } : {}),\n })\n } catch {\n reject(new Error('Publisher HTTPS response is not JSON'))\n }\n })\n })\n call.on('error', () => reject(new Error('Publisher HTTPS request failed')))\n call.end(encoded)\n })\n } finally {\n scope.dispose()\n }\n },\n }\n}\n", "import { createHash } from 'node:crypto'\n\nimport { canonicalJson } from '@xyo-network/event-kit-protocol'\nimport type { WakeSource } from '@xyo-network/event-kit-schemas'\nimport { completedUtcIntervalPosition, WakeSourceZod } from '@xyo-network/event-kit-schemas'\nimport { PayloadBuilder } from '@xyo-network/sdk'\nimport type { XyoGateway } from '@xyo-network/xl1-sdk'\nimport { asXL1BlockNumber } from '@xyo-network/xl1-sdk'\nimport { FetchRequest, JsonRpcProvider } from 'ethers'\n\nimport { publisherAbortScope } from './abort.ts'\nimport { createBoundedPublisherEthersTransport } from './boundedFetch.ts'\nexport interface PublisherSourceHead {\n readonly hash?: string\n readonly position: number\n}\nexport interface PublisherSourceReader {\n readonly source: WakeSource\n close?(): void | Promise<void>\n head(signal: AbortSignal): Promise<PublisherSourceHead>\n}\nexport function publisherSourceKey(source: WakeSource): string {\n return createHash('sha256').update(canonicalJson(WakeSourceZod.parse(source))).digest('hex')\n}\nexport async function boundedPublisherOperation<T>(operation: Promise<T>, signal: AbortSignal, timeoutMs = 10_000): Promise<T> {\n const scope = publisherAbortScope([signal], timeoutMs)\n const combined = scope.signal\n let rejectAbort: (() => void) | undefined\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = () => reject(new Error('Publisher operation aborted or timed out'))\n combined.addEventListener('abort', rejectAbort, { once: true })\n })\n try {\n combined.throwIfAborted()\n return await Promise.race([operation, aborted])\n } finally {\n if (rejectAbort !== undefined)\n combined.removeEventListener('abort', rejectAbort)\n scope.dispose()\n }\n}\ntype GatewayViewer = NonNullable<XyoGateway['connection']['viewer']>\nexport function createXl1PublisherSource(options: {\n readonly source: Extract<WakeSource, {\n kind: 'xl1-finalized'\n }>\n readonly viewer: Pick<GatewayViewer, 'block' | 'chainId' | 'finalization'>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'xl1-finalized')\n throw new Error('Expected an XL1 finalized source')\n return {\n source,\n async head(signal) {\n const chainId = String(await boundedPublisherOperation(Promise.resolve(options.viewer.chainId()), signal))\n if (chainId !== source.chainId)\n throw new Error('XL1 source chain identity changed')\n const position = Number(await boundedPublisherOperation(Promise.resolve(options.viewer.finalization.headNumber()), signal))\n if (!Number.isSafeInteger(position) || position < 0)\n throw new Error('XL1 finalized head is invalid')\n const block = await boundedPublisherOperation(Promise.resolve(options.viewer.block.blockByNumber(asXL1BlockNumber(position, true))), signal)\n if (block?.[0].block !== position || !/^[0-9a-f]{64}$/u.test(block[0]._hash)) {\n throw new Error('XL1 finalized head block is unavailable or inconsistent')\n }\n if (String(block[0].chain) !== source.chainId || await PayloadBuilder.hash(block[0]) !== block[0]._hash) {\n throw new Error('XL1 finalized head block chain or hash is inconsistent')\n }\n return { position, hash: block[0]._hash }\n },\n }\n}\nexport function createEthereumFinalizedPublisherSource(options: {\n readonly requestTimeoutMs?: number\n readonly rpcUrl: string\n readonly source: Extract<WakeSource, {\n kind: 'ethereum-finalized'\n }>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'ethereum-finalized')\n throw new Error('Expected an Ethereum finalized source')\n const { chainId, genesisHash } = source\n const url = new URL(options.rpcUrl)\n if (url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.hash !== '') {\n throw new Error('Ethereum source RPC must use HTTPS without URL credentials or fragments')\n }\n const connection = new FetchRequest(url.href)\n connection.timeout = options.requestTimeoutMs ?? 10_000\n const transport = createBoundedPublisherEthersTransport({\n requestTimeoutMs: options.requestTimeoutMs, maxResponseBytes: 2 * 1024 * 1024, maxConcurrency: 8,\n })\n connection.getUrlFunc = transport.getUrl\n connection.setThrottleParams({ maxAttempts: 1 })\n const provider = new JsonRpcProvider(connection, undefined, { batchMaxCount: 1, cacheTimeout: -1 })\n let reading: Promise<PublisherSourceHead> | undefined\n let closed = false\n let closing: Promise<void> | undefined\n const close = () => closing ??= (async () => {\n closed = true\n provider.destroy()\n await transport.close()\n })()\n const onAbort = () => {\n void close()\n }\n async function read() {\n const requests = [provider.getNetwork(), provider.getBlock(0), provider.getBlock('finalized')] as const\n // A failing sibling request cannot release the single-flight slot while\n // another request still owns a connection or a bounded response body.\n try {\n const [network, genesis, block] = await Promise.all(requests)\n if (network.chainId.toString() !== chainId || genesis?.hash?.slice(2).toLowerCase() !== genesisHash) {\n throw new Error('Ethereum source chain identity mismatch')\n }\n if (block?.hash === null || block === null || !/^0x[0-9a-fA-F]{64}$/u.test(block.hash)\n || !Number.isSafeInteger(block.number) || block.number < 0) throw new Error('Ethereum finalized head is unavailable')\n return { position: block.number, hash: block.hash.slice(2).toLowerCase() }\n } catch (error) {\n await Promise.allSettled(requests)\n throw error\n }\n }\n return {\n source,\n close,\n async head(signal) {\n signal.throwIfAborted()\n if (closed) throw new Error('Ethereum source is closed')\n signal.addEventListener('abort', onAbort, { once: true })\n reading ??= (async () => {\n try {\n return await read()\n } finally {\n reading = undefined\n }\n })()\n try {\n return await boundedPublisherOperation(reading, signal, options.requestTimeoutMs ?? 10_000)\n } finally {\n signal.removeEventListener('abort', onAbort)\n }\n },\n }\n}\n\nexport function createUtcIntervalPublisherSource(options: {\n readonly nowSeconds?: () => number\n readonly source: Extract<WakeSource, {\n kind: 'utc-interval'\n }>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'utc-interval')\n throw new Error('Expected a UTC interval source')\n const nowSeconds = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n return {\n source,\n async head(signal) {\n signal.throwIfAborted()\n const now = nowSeconds()\n if (!Number.isSafeInteger(now) || now < 0)\n throw new Error('UTC interval clock is invalid')\n return { position: completedUtcIntervalPosition(source, now) ?? -1 }\n },\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport type { PeriodicActorParams, PeriodicPassContext } from '@ariestools/actor'\nimport { createMemoryLocator, PeriodicActor } from '@ariestools/actor'\nimport { creatable } from '@ariestools/sdk'\nimport { BestEffortAdmissionAcknowledgmentZod } from '@xyo-network/event-kit-protocol'\nimport type {\n BestEffortDeliveryPolicy, WakeDeliveryMode, WakeEnvelope, WakeSource,\n} from '@xyo-network/event-kit-schemas'\nimport { BestEffortDeliveryPolicyZod, WakeDeliveryModeZod } from '@xyo-network/event-kit-schemas'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { publisherAbortScope } from './abort.ts'\nimport type { PublisherHttpsTransport } from './httpsTransport.ts'\nimport type { DeliveryState } from './publisherDeliveryState.ts'\nimport {\n assertDeliveryState, DeliveryResponseError, failedDelivery, makeEvent, prepareBestEffortDelivery,\n} from './publisherDeliveryState.ts'\nimport type { PublisherSourceHead, PublisherSourceReader } from './sources.ts'\nimport { boundedPublisherOperation, publisherSourceKey } from './sources.ts'\nimport { createAccountSourceWakeSigner } from './sourceSigner.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\nexport interface PublisherRuntimeSubscription {\n readonly audience: string\n readonly authorizationChainId: string\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly controller: string\n readonly deliveryMode: WakeDeliveryMode\n readonly deploymentId: string\n readonly endpoint: string\n readonly filterHash: string\n readonly fromPosition: number\n readonly maxPositionsPerWake: number\n readonly queueId?: string\n readonly serviceHash?: string\n readonly source: WakeSource\n readonly subscriptionHash: string\n}\n/** Discovery MUST return only current finalized, accepted subscriptions. */\nexport interface PublisherRuntimeDiscovery {\n acceptPending?(signal: AbortSignal): Promise<void>\n close?(): Promise<void>\n discover(signal: AbortSignal): Promise<readonly PublisherRuntimeSubscription[]>\n /** Re-check the exact current revision before each attempt, including retries. */\n isActive(subscription: PublisherRuntimeSubscription, signal: AbortSignal): Promise<boolean>\n status?(): PublisherRuntimeDiscoveryStatus\n}\nexport interface PublisherRuntimeDiscoveryStatus {\n readonly activeKeyIds: readonly string[]\n readonly authorizationChainId: string\n readonly challengeFailures: number\n readonly finalizedHead?: number\n readonly indexedThrough?: number\n readonly keyLoaded: boolean\n readonly pendingSubscriptions: number\n readonly rejectedSubscriptions: number\n}\nfunction activationReady(status?: PublisherRuntimeDiscoveryStatus): boolean {\n return (status?.keyLoaded ?? true) && (status?.pendingSubscriptions ?? 0) === 0\n}\n\nexport interface PersistentEventPublisherOptions {\n readonly account: AccountInstance\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly concurrency?: number\n readonly deliveryMode: WakeDeliveryMode\n readonly discovery: PublisherRuntimeDiscovery\n readonly intervalMs?: number\n readonly maxSubscriptions?: number\n readonly nowSeconds?: () => number\n readonly publisher: string\n readonly requestTimeoutMs?: number\n /** Optional immutable operator pin; mismatches fail readiness without revoking subscriptions. */\n readonly serviceHash?: string\n readonly sources: readonly PublisherSourceReader[]\n readonly state: SqlitePublisherState\n readonly transport: PublisherHttpsTransport\n}\nexport interface PersistentEventPublisherStatus {\n readonly abandoned: number\n readonly activeSubscriptions: number\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly clockHealthy: boolean\n readonly degraded: boolean\n readonly delivered: number\n readonly deliveryMode: WakeDeliveryMode\n readonly failures: number\n readonly handshake?: PublisherRuntimeDiscoveryStatus\n readonly lastError?: string\n readonly passes: number\n readonly pendingDeliveries: number\n readonly publisher: string\n readonly ready: boolean\n readonly running: boolean\n readonly sources: readonly {\n readonly hash?: string\n readonly id: string\n readonly position: number\n }[]\n readonly subscriptions: readonly {\n readonly attempts?: number\n readonly cursor: number\n readonly failures: number\n readonly id: string\n /** Best Effort admission target is not a contiguous source prefix. */\n readonly lastAdmissionTarget?: number\n readonly lastHintAt?: number\n readonly pending: boolean\n readonly state: string\n }[]\n readonly superseded: number\n readonly totalAttempts: number\n}\nexport interface PersistentEventPublisher {\n runOnce(): Promise<void>\n start(): Promise<void>\n status(): PersistentEventPublisherStatus\n stop(): Promise<void>\n}\ninterface RuntimeActorParams extends PeriodicActorParams {\n readonly tick: (signal: AbortSignal) => Promise<void>\n}\n@creatable()\nclass PublisherRuntimeActor extends PeriodicActor<RuntimeActorParams> {\n protected override async runPass(context: PeriodicPassContext): Promise<void> {\n await this.params.tick(context.signal)\n }\n}\nconst TimingZod = z.object({\n concurrency: z.number().int().min(1).max(32).default(4),\n intervalMs: z.number().int().min(100).max(60_000).default(1000),\n maxSubscriptions: z.number().int().min(1).max(1024).default(64),\n requestTimeoutMs: z.number().int().min(100).max(60_000).default(10_000),\n})\n\nfunction runtimeSettings(options: PersistentEventPublisherOptions) {\n const deliveryMode = WakeDeliveryModeZod.parse(options.deliveryMode)\n const bestEffort = options.bestEffort === undefined ? undefined : BestEffortDeliveryPolicyZod.parse(options.bestEffort)\n if ((deliveryMode === 'best-effort') !== (bestEffort !== undefined)) throw new TypeError('Explicit delivery mode requires its exact policy')\n return {\n bestEffort,\n deliveryMode,\n deliveryNamespace: deliveryMode === 'best-effort' ? 'best-effort-deliveries' : 'deliveries',\n timing: TimingZod.parse(options),\n }\n}\nexport async function createPersistentEventPublisherRuntime(options: PersistentEventPublisherOptions): Promise<PersistentEventPublisher> {\n const {\n bestEffort, deliveryMode, deliveryNamespace, timing,\n } = runtimeSettings(options)\n if (options.sources.length < 1 || options.sources.length > 16)\n throw new Error('Publisher requires between one and sixteen bounded sources')\n const clock = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const signer = createAccountSourceWakeSigner({\n account: options.account, publisher: options.publisher, nowSeconds: clock,\n })\n const sourceReaders = new Map(options.sources.map(reader => [publisherSourceKey(reader.source), reader]))\n if (sourceReaders.size !== options.sources.length)\n throw new Error('Duplicate publisher source identity')\n const state = options.state\n const existingMode = state.get<string>('metadata', 'runtime-delivery-mode')\n if (existingMode !== undefined && existingMode !== deliveryMode) throw new Error('Publisher state delivery mode mismatch; preserve custody and use an explicitly qualified state binding')\n state.set('metadata', 'runtime-delivery-mode', deliveryMode)\n const abort = new AbortController()\n const seenThisProcess = new Set<string>()\n let running = false\n let ready = false\n let clockHealthy = true\n let passes = 0\n let lastError: string | undefined\n let sourcesHealthy = false\n let stop: Promise<void> | undefined\n const timed = <T>(promise: Promise<T>, signal: AbortSignal) => boundedPublisherOperation(promise, signal, timing.requestTimeoutMs)\n function loadDelivery(subscription: PublisherRuntimeSubscription, now: number): DeliveryState {\n if (subscription.deliveryMode !== deliveryMode || !isDeepStrictEqual(subscription.bestEffort, bestEffort))\n throw new Error('Subscription delivery mode or policy disagrees with runtime')\n if (deliveryMode === 'best-effort' && (subscription.maxPositionsPerWake !== 1 || subscription.serviceHash === undefined)) throw new Error('Best Effort requires point range')\n if (options.serviceHash !== undefined && subscription.serviceHash !== options.serviceHash)\n throw new Error('Subscription does not match the configured exact service descriptor')\n const key = subscription.subscriptionHash\n if (deliveryMode === 'best-effort' && state.get(deliveryNamespace, key) === undefined\n && state.entries(deliveryNamespace).length >= timing.maxSubscriptions) throw new Error('Best Effort state capacity exceeded; live records are not evicted')\n let record = state.get<DeliveryState>(deliveryNamespace, key)\n if (record === undefined) {\n makeEvent(subscription, subscription.fromPosition, subscription.fromPosition, now, '0'.repeat(32))\n if (!Number.isSafeInteger(subscription.maxPositionsPerWake) || subscription.maxPositionsPerWake < 1 || subscription.maxPositionsPerWake > 4096) {\n throw new Error('Invalid source range budget')\n }\n record = {\n subscription, cursor: subscription.fromPosition - 1, delivered: 0, failures: 0, nextAttemptMs: 0, state: 'active',\n }\n state.set(deliveryNamespace, key, record)\n }\n assertDeliveryState(record, subscription)\n return record\n }\n\n function prepareDelivery(record: DeliveryState, now: number, heads: ReadonlyMap<string, PublisherSourceHead | Error>) {\n if (deliveryMode === 'best-effort' && bestEffort !== undefined) {\n const first = !seenThisProcess.has(record.subscription.subscriptionHash)\n const head = heads.get(publisherSourceKey(record.subscription.source))\n if (head !== undefined && !(head instanceof Error) && head.position >= record.subscription.fromPosition)\n seenThisProcess.add(record.subscription.subscriptionHash)\n return prepareBestEffortDelivery({\n bestEffort, first, heads, now, record, state,\n })\n }\n if (record.pending !== undefined) return { ...record, pending: record.pending }\n const subscription = record.subscription\n const head = heads.get(publisherSourceKey(subscription.source))\n if (head === undefined || head instanceof Error) throw new Error('Configured source is unavailable')\n if (head.position <= record.cursor) return\n const fromPosition = record.cursor + 1\n const pending = makeEvent(subscription, fromPosition, Math.min(head.position, fromPosition + subscription.maxPositionsPerWake - 1), now)\n const prepared = { ...record, pending }\n state.transaction(() => {\n const logicalKey = JSON.stringify([subscription.subscriptionHash, pending.fromPosition, pending.toPosition])\n if (!state.insert('delivery-events', logicalKey, pending)) throw new Error('Publisher logical range already exists outside its contiguous cursor')\n state.set(deliveryNamespace, subscription.subscriptionHash, prepared)\n })\n return prepared\n }\n\n async function stillActive(record: DeliveryState, signal: AbortSignal): Promise<boolean> {\n if (await timed(options.discovery.isActive(record.subscription, signal), signal)) return true\n state.set(deliveryNamespace, record.subscription.subscriptionHash, {\n ...record, pending: undefined, state: 'cancelled',\n })\n return false\n }\n\n function acknowledgeBestEffort(record: DeliveryState & { readonly pending: WakeEnvelope }, body: unknown, eventHash: string, signal: AbortSignal, now: number) {\n const { pending, subscription } = record\n const acknowledgment = BestEffortAdmissionAcknowledgmentZod.safeParse(body)\n if (!acknowledgment.success || acknowledgment.data.eventHash !== eventHash || acknowledgment.data.wakeId !== pending.wakeId\n || acknowledgment.data.expiresAt !== pending.issuedAt + (bestEffort?.maxHintAgeSeconds ?? 0) + 60\n || acknowledgment.data.acceptedAt < pending.issuedAt - 60 || acknowledgment.data.acceptedAt > now + 60)\n throw new Error('Publisher did not receive a matching finite acknowledgment')\n signal.throwIfAborted()\n state.set(deliveryNamespace, subscription.subscriptionHash, {\n subscription,\n cursor: pending.toPosition,\n delivered: record.delivered + 1,\n failures: 0,\n attempts: 0,\n superseded: record.superseded ?? 0,\n abandoned: record.abandoned ?? 0,\n totalAttempts: (record.totalAttempts ?? 0) + 1,\n lastNotifiedAt: now,\n lastHintAt: pending.issuedAt,\n lastHintTarget: pending.toPosition,\n nextAttemptMs: 0,\n state: 'active',\n } satisfies DeliveryState)\n }\n\n async function sendDelivery(record: DeliveryState & { readonly pending: WakeEnvelope }, signal: AbortSignal, now: number) {\n const { pending, subscription } = record\n signal.throwIfAborted()\n const signed = await signer.sign(pending, subscription.audience)\n signal.throwIfAborted()\n const attempt = deliveryMode === 'best-effort' ? record.attempts ?? 0 : state.get<{ count: number }>('delivery-attempts', pending.wakeId)?.count ?? 0\n if (deliveryMode === 'best-effort') state.set(deliveryNamespace, subscription.subscriptionHash, {\n ...record, attempts: attempt + 1, totalAttempts: (record.totalAttempts ?? 0) + 1,\n })\n else state.set('delivery-attempts', pending.wakeId, {\n count: attempt + 1, startedAt: now, status: 'in-flight',\n })\n const response = await options.transport.post(subscription.endpoint, signed.event, signal, signed.jwt)\n if (deliveryMode === 'durable') state.set('delivery-attempts', pending.wakeId, {\n count: attempt + 1, startedAt: now, status: response.status,\n })\n if (response.status !== 200 && response.status !== 202) throw new DeliveryResponseError(response.status, response.retryAfterMs)\n if (deliveryMode === 'best-effort') {\n acknowledgeBestEffort(record, response.body, signed.eventHash, signal, now)\n return\n }\n const receipt = z.object({ receiptId: z.string().min(1), wakeId: z.literal(pending.wakeId) }).safeParse(response.body)\n if (!receipt.success) throw new Error('Publisher admission did not return a matching durable receipt')\n signal.throwIfAborted()\n // Receipt, contiguous cursor, and outbox clear commit together. A lost\n // response or death before this transaction reuses the exact pending body.\n state.transaction(() => {\n state.set('delivery-receipts', pending.wakeId, { receiptId: receipt.data.receiptId, receivedAt: now })\n state.set(deliveryNamespace, subscription.subscriptionHash, {\n subscription,\n cursor: pending.toPosition,\n delivered: record.delivered + 1,\n failures: 0,\n nextAttemptMs: 0,\n state: 'active',\n } satisfies DeliveryState)\n })\n }\n\n async function deliver(subscription: PublisherRuntimeSubscription, signal: AbortSignal, now: number, heads: ReadonlyMap<string, PublisherSourceHead | Error>) {\n let record = loadDelivery(subscription, now)\n if (deliveryMode === 'durable' && (record.state !== 'active' || record.nextAttemptMs > now * 1000)) return\n try {\n if (!await stillActive(record, signal)) return\n options.transport.assertAllowed(subscription.endpoint)\n if (!sourceReaders.has(publisherSourceKey(subscription.source))) throw new Error('Subscription source is not configured')\n const prepared = prepareDelivery(record, now, heads)\n if (prepared === undefined) return\n record = prepared\n if (record.nextAttemptMs > now * 1000) return\n // Reconcile once more after observing source progress, before every attempt.\n if (!await stillActive(record, signal)) return\n await sendDelivery(prepared, signal, now)\n } catch (error) {\n if (signal.aborted) return\n state.set(\n deliveryNamespace,\n subscription.subscriptionHash,\n failedDelivery(record, state.get<DeliveryState>(deliveryNamespace, subscription.subscriptionHash), deliveryMode, error, now),\n )\n }\n }\n async function readSources(signal: AbortSignal): Promise<ReadonlyMap<string, PublisherSourceHead | Error>> {\n const heads = new Map<string, PublisherSourceHead | Error>()\n const results = await Promise.allSettled([...sourceReaders].map(async ([key, reader]) => {\n const head = await timed(reader.head(signal), signal)\n if (!Number.isSafeInteger(head.position) || head.position < -1)\n throw new Error('Source head is invalid')\n const previous = state.get<PublisherSourceHead>('source-heads', key)\n if (previous !== undefined && (head.position < previous.position || (head.position === previous.position && head.hash !== previous.hash))) {\n throw new Error('Finalized source regressed or changed hash')\n }\n signal.throwIfAborted()\n state.set('source-heads', key, head)\n heads.set(key, head)\n }))\n sourcesHealthy = results.every(item => item.status === 'fulfilled')\n // All rejections are inspected; delivery sees an unavailable source without\n // exposing provider URLs or allowing one source to deny another service.\n for (const [index, result] of results.entries())\n if (result.status === 'rejected') {\n const key = sourceReaders.keys().toArray()[index]\n if (key !== undefined)\n heads.set(key, new Error('Source read failed'))\n }\n return heads\n }\n async function reconcileDeliveries(subscriptions: readonly PublisherRuntimeSubscription[], signal: AbortSignal) {\n if (subscriptions.length > timing.maxSubscriptions) throw new Error('Publisher subscription limit exceeded')\n const active = new Set(subscriptions.map(subscription => subscription.subscriptionHash))\n if (active.size !== subscriptions.length) throw new Error('Duplicate subscription identity')\n const unavailable = state.entries<DeliveryState>(deliveryNamespace).filter(item => !active.has(item.key) && item.value.state !== 'cancelled')\n let available = true\n for (let offset = 0; offset < unavailable.length; offset += timing.concurrency) {\n signal.throwIfAborted()\n const results = await Promise.allSettled(unavailable.slice(offset, offset + timing.concurrency).map(async ({ key, value }) => {\n const stillAuthorized = await timed(options.discovery.isActive(value.subscription, signal), signal)\n if (!stillAuthorized) state.set(deliveryNamespace, key, {\n ...value, pending: undefined, state: 'cancelled',\n })\n return stillAuthorized\n }))\n // Local key loss, endpoint policy, or a failed replay cannot revoke a\n // finalized subscription. Preserve its exact pending body for restoration.\n available = available && results.every(result => result.status === 'fulfilled' && !result.value)\n }\n return available\n }\n\n async function tick(actorSignal: AbortSignal) {\n const scope = publisherAbortScope([abort.signal, actorSignal])\n const signal = scope.signal\n try {\n signal.throwIfAborted()\n const now = clock()\n const prior = state.get<number>('runtime', 'highest-wall-clock') ?? 0\n clockHealthy = Number.isSafeInteger(now) && now >= prior\n if (!clockHealthy)\n throw new Error('Publisher clock moved backwards')\n state.set('runtime', 'highest-wall-clock', now)\n const subscriptions = await timed(options.discovery.discover(signal), signal)\n const subscriptionsAvailable = await reconcileDeliveries(subscriptions, signal)\n const heads = await readSources(signal)\n for (let offset = 0; offset < subscriptions.length; offset += timing.concurrency) {\n signal.throwIfAborted()\n const outcomes = await Promise.allSettled(subscriptions.slice(offset, offset + timing.concurrency).map(subscription => deliver(subscription, signal, now, heads)))\n const failed = outcomes.find(result => result.status === 'rejected')\n if (failed?.status === 'rejected')\n throw failed.reason\n }\n // Challenge/finality work is bounded and occurs after already-active\n // subscribers, so a new or broken subscriber cannot starve delivery.\n if (options.discovery.acceptPending !== undefined)\n await timed(options.discovery.acceptPending(signal), signal)\n const discoveryStatus = options.discovery.status?.()\n ready = subscriptionsAvailable && sourcesHealthy && activationReady(discoveryStatus)\n lastError = subscriptionsAvailable ? undefined : 'publisher-subscription-unavailable'\n passes += 1\n } catch (error) {\n ready = false\n lastError = clockHealthy ? 'publisher-pass-failed' : 'publisher-clock-unhealthy'\n if (!signal.aborted)\n throw error\n } finally {\n scope.dispose()\n }\n }\n const actor = await PublisherRuntimeActor.create({\n locator: createMemoryLocator({}), intervalMs: timing.intervalMs, firstRun: 'immediate', readiness: 'immediate', tick,\n })\n return {\n async start() {\n if (stop !== undefined)\n throw new Error('Publisher is stopped')\n if (running) {\n return\n }\n\n await actor.start()\n running = true\n },\n async runOnce() {\n if (stop !== undefined)\n throw new Error('Publisher is stopped')\n await actor.runOnce()\n },\n stop: () => stop ??= (async () => {\n abort.abort()\n const failures: unknown[] = []\n try {\n await actor.stop()\n } catch (error) {\n failures.push(error)\n }\n try {\n await options.discovery.close?.()\n } catch (error) {\n failures.push(error)\n }\n for (const source of options.sources)\n try {\n await source.close?.()\n } catch (error) {\n failures.push(error)\n }\n running = false\n ready = false\n if (failures.length > 0)\n throw new AggregateError(failures, 'Publisher runtime shutdown failed')\n })(),\n status() {\n const deliveries = state.entries<DeliveryState>(deliveryNamespace).map(item => item.value)\n return {\n running,\n deliveryMode,\n ...(bestEffort === undefined ? {} : { bestEffort: Object.freeze({ ...bestEffort }) }),\n superseded: deliveries.reduce((sum, item) => sum + (item.superseded ?? 0), 0),\n abandoned: deliveries.reduce((sum, item) => sum + (item.abandoned ?? 0), 0),\n totalAttempts: deliveries.reduce((sum, item) => sum + (item.totalAttempts ?? 0), 0),\n ready: running && ready,\n clockHealthy,\n degraded: !ready || deliveries.some(item => item.state !== 'cancelled' && item.failures > 0),\n publisher: options.publisher,\n activeSubscriptions: deliveries.filter(item => item.state === 'active').length,\n pendingDeliveries: deliveries.filter(item => item.pending !== undefined).length,\n delivered: deliveries.reduce((sum, item) => sum + item.delivered, 0),\n failures: deliveries.reduce((sum, item) => sum + item.failures, 0),\n passes,\n ...(lastError === undefined ? {} : { lastError }),\n ...(options.discovery.status === undefined ? {} : { handshake: options.discovery.status() }),\n sources: state.entries<PublisherSourceHead>('source-heads').filter(item => sourceReaders.has(item.key)).map(item => ({ id: item.key, ...item.value })),\n subscriptions: state.entries<DeliveryState>(deliveryNamespace).map(item => ({\n id: item.key,\n cursor: item.value.cursor,\n ...(deliveryMode === 'best-effort'\n ? {\n ...(item.value.cursor < item.value.subscription.fromPosition ? {} : { lastAdmissionTarget: item.value.cursor }),\n attempts: item.value.attempts ?? 0,\n lastHintAt: item.value.lastHintAt,\n }\n : {}),\n state: item.value.state,\n pending: item.value.pending !== undefined,\n failures: item.value.failures,\n })),\n }\n },\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { BestEffortDeliveryPolicy, WakeEnvelope } from '@xyo-network/event-kit-schemas'\nimport { WakeEnvelopeSchema, WakeEnvelopeZod } from '@xyo-network/event-kit-schemas'\n\nimport type { PublisherRuntimeSubscription } from './publisherRuntime.ts'\nimport type { PublisherSourceHead } from './sources.ts'\nimport { publisherSourceKey } from './sources.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\n\nexport interface DeliveryState {\n readonly abandoned?: number\n readonly attempts?: number\n readonly cursor: number\n readonly delivered: number\n readonly failures: number\n readonly lastError?: string\n readonly lastHintAt?: number\n readonly lastHintTarget?: number\n readonly lastNotifiedAt?: number\n readonly nextAttemptMs: number\n readonly pending?: WakeEnvelope\n readonly state: 'active' | 'blocked' | 'cancelled'\n readonly subscription: PublisherRuntimeSubscription\n readonly superseded?: number\n readonly totalAttempts?: number\n}\nexport function assertDeliveryState(record: DeliveryState, subscription: PublisherRuntimeSubscription): void {\n if (!isDeepStrictEqual(record.subscription, subscription))\n throw new Error('Subscription revision changed without a new identity')\n if (!Number.isSafeInteger(record.cursor) || record.cursor < subscription.fromPosition - 1\n || [record.delivered, record.failures, record.nextAttemptMs].some(value => !(Number.isSafeInteger(value) && value >= 0))\n || [record.attempts, record.superseded, record.abandoned, record.totalAttempts, record.lastHintAt, record.lastNotifiedAt, record.lastHintTarget]\n .some(value => value !== undefined && !(Number.isSafeInteger(value) && value >= 0))\n || !['active', 'blocked', 'cancelled'].includes(record.state))\n throw new Error('Persisted publisher delivery state is invalid')\n if (record.pending === undefined) return\n const pending = WakeEnvelopeZod.parse(record.pending)\n if ((subscription.deliveryMode === 'durable' && pending.fromPosition !== record.cursor + 1)\n || pending.deliveryMode !== subscription.deliveryMode || pending.toPosition - pending.fromPosition + 1 > subscription.maxPositionsPerWake\n || pending.authorizationChainId !== subscription.authorizationChainId || pending.deploymentId !== subscription.deploymentId\n || pending.queueId !== subscription.queueId || pending.filterHash !== subscription.filterHash\n || !isDeepStrictEqual(pending.source, subscription.source))\n throw new Error('Persisted publisher outbox binding is invalid')\n}\nexport function makeEvent(subscription: PublisherRuntimeSubscription, fromPosition: number, toPosition: number, now: number, wakeId = randomBytes(16).toString('hex')) {\n return WakeEnvelopeZod.parse({\n schema: WakeEnvelopeSchema,\n authorizationChainId: subscription.authorizationChainId,\n deliveryMode: subscription.deliveryMode,\n deploymentId: subscription.deploymentId,\n filterHash: subscription.filterHash,\n fromPosition,\n issuedAt: now,\n source: subscription.source,\n toPosition,\n wakeId,\n ...(subscription.queueId === undefined ? {} : { queueId: subscription.queueId }),\n })\n}\n\nexport class DeliveryResponseError extends Error {\n readonly retryAfterMs?: number\n readonly status: number\n constructor(status: number, retryAfterMs?: number) {\n super('Publisher admission failed')\n this.status = status\n this.retryAfterMs = retryAfterMs\n }\n\n get retryable() {\n return this.status === 408 || this.status === 429 || this.status >= 500\n }\n}\n\nexport function prepareBestEffortDelivery(options: {\n readonly bestEffort: BestEffortDeliveryPolicy\n readonly first: boolean\n readonly heads: ReadonlyMap<string, PublisherSourceHead | Error>\n readonly now: number\n readonly record: DeliveryState\n readonly state: SqlitePublisherState\n}) {\n const {\n bestEffort, first, heads, now, record, state,\n } = options\n const subscription = record.subscription\n const head = heads.get(publisherSourceKey(subscription.source))\n const prior = record.pending\n const expired = isHintExpired(record, now, bestEffort)\n if (head === undefined || head instanceof Error || head.position < subscription.fromPosition) {\n if (prior !== undefined && !expired) return { ...record, pending: prior }\n if (prior !== undefined) state.set('best-effort-deliveries', subscription.subscriptionHash, {\n ...record, pending: undefined, abandoned: (record.abandoned ?? 0) + 1,\n })\n return\n }\n const refresh = refreshDue(record, now, bestEffort)\n if (freshHintRequired(record, head.position, first, refresh, expired)) {\n const pending = makeEvent(subscription, head.position, head.position, now)\n const prepared = {\n ...record,\n pending,\n attempts: 0,\n lastHintAt: now,\n lastHintTarget: head.position,\n superseded: (record.superseded ?? 0) + (prior !== undefined && !expired ? 1 : 0),\n abandoned: (record.abandoned ?? 0) + (expired ? 1 : 0),\n nextAttemptMs: 0,\n state: 'active' as const,\n }\n state.set('best-effort-deliveries', subscription.subscriptionHash, prepared)\n return prepared\n }\n if (expired) state.set('best-effort-deliveries', subscription.subscriptionHash, {\n ...record, pending: undefined, abandoned: (record.abandoned ?? 0) + 1,\n })\n return prior === undefined || expired ? undefined : { ...record, pending: prior }\n}\n\nfunction isHintExpired(record: DeliveryState, now: number, policy: BestEffortDeliveryPolicy): boolean {\n return record.pending !== undefined && (now > record.pending.issuedAt + policy.maxHintAgeSeconds || (record.attempts ?? 0) >= policy.maxAttempts)\n}\nfunction refreshDue(record: DeliveryState, now: number, policy: BestEffortDeliveryPolicy): boolean {\n return now - (record.lastHintAt ?? record.lastNotifiedAt ?? 0) >= policy.refreshIntervalSeconds\n}\nfunction freshHintRequired(record: DeliveryState, head: number, first: boolean, refresh: boolean, expired: boolean): boolean {\n return first || head > (record.pending?.toPosition ?? record.lastHintTarget ?? record.cursor) || (refresh && (record.pending === undefined || expired))\n}\nexport function failedDelivery(record: DeliveryState, current: DeliveryState | undefined, mode: string, error: unknown, now: number): DeliveryState {\n const bestEffort = mode === 'best-effort'\n const wait = error instanceof DeliveryResponseError && error.retryAfterMs !== undefined\n ? error.retryAfterMs\n : Math.min(300_000, 1000 * (2 ** Math.min(record.failures, 8)))\n return {\n ...record,\n failures: record.failures + 1,\n totalAttempts: bestEffort ? current?.totalAttempts ?? record.totalAttempts ?? 0 : record.totalAttempts,\n attempts: bestEffort ? current?.attempts ?? record.attempts ?? 0 : record.attempts,\n state: !bestEffort && error instanceof DeliveryResponseError && !error.retryable ? 'blocked' : 'active',\n nextAttemptMs: now * 1000 + Math.min(3_600_000, wait),\n lastError: 'delivery-failed',\n }\n}\n", "import { randomBytes } from 'node:crypto'\n\nimport type { WakeEnvelope } from '@xyo-network/event-kit-schemas'\nimport {\n NormalizedAddressZod, WakeEnvelopeZod, WakeJwtSchema,\n} from '@xyo-network/event-kit-schemas'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport { PayloadBuilder } from '@xyo-network/sdk'\n/** The wallet-JWT profile commits to the complete strict source-aware body. */\nexport function createAccountSourceWakeSigner(options: {\n readonly account: AccountInstance\n readonly nowSeconds?: () => number\n readonly publisher: string\n}) {\n const publisher = NormalizedAddressZod.parse(options.publisher)\n if (String(options.account.address).replace(/^0x/u, '').toLowerCase() !== publisher)\n throw new Error('Publisher signing account mismatch')\n return {\n async sign(input: WakeEnvelope, audience: string) {\n const event = WakeEnvelopeZod.parse(input)\n const eventHash = await PayloadBuilder.dataHash(event)\n const now = options.nowSeconds?.() ?? Math.floor(Date.now() / 1000)\n if (!Number.isSafeInteger(now) || now < 0)\n throw new Error('Publisher signing clock is invalid')\n const { token: jwt } = await options.account.signJwt({\n audience,\n claims: { eventHash, jti: randomBytes(16).toString('hex') },\n now,\n schema: WakeJwtSchema,\n ttl: 60,\n })\n return {\n event, eventHash, jwt, publisher,\n }\n },\n }\n}\n", "import { FetchJsonClient } from '@ariestools/sdk'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport type {\n GatewaySession, XyoGateway, XyoGatewayRunner,\n} from '@xyo-network/xl1-sdk'\nimport {\n baseConfigFactoryLocator, basicRestRunnerLocator, basicRestViewerLocator, creatableProvider,\n releaseProviderFactoryLocator, RestDataLakeRunner, RestDataLakeViewer, XyoGatewayMoniker, XyoGatewayRunnerMoniker,\n} from '@xyo-network/xl1-sdk'\nexport interface PublisherRestGatewayOptions {\n readonly chainStateUrl: string\n readonly fetchFn: typeof globalThis.fetch\n readonly finalizedUrl: string\n readonly indexUrl?: string\n readonly rpcUrl: string\n}\n/** Owned public SDK REST gateway; only the optional mutation runner uses RPC. */\nexport function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account: AccountInstance\n}): Promise<GatewaySession<XyoGatewayRunner>>\nexport function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account?: undefined\n}): Promise<GatewaySession<XyoGateway>>\nexport async function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account?: AccountInstance\n}): Promise<GatewaySession<XyoGateway | XyoGatewayRunner>> {\n const rest = {\n finalized: { type: 'rest' as const, baseUrl: options.finalizedUrl },\n chainState: { type: 'rest' as const, baseUrl: options.chainStateUrl },\n index: { type: 'rest' as const, baseUrl: options.indexUrl ?? options.finalizedUrl },\n }\n const locator = options.account === undefined\n ? await basicRestViewerLocator('event-kit-publisher-read', rest, undefined, { fetchFn: options.fetchFn, primeCaches: 'off' })\n : await basicRestRunnerLocator('event-kit-publisher-write', rest, undefined, {\n fetchFn: options.fetchFn, primeCaches: 'off', rpcUrl: options.rpcUrl, signerAccount: options.account,\n })\n try {\n const gateway = options.account === undefined\n ? await locator.getInstance<XyoGateway>(XyoGatewayMoniker)\n : await locator.getInstance<XyoGatewayRunner>(XyoGatewayRunnerMoniker)\n let stopping: Promise<void> | undefined\n return Object.freeze({ gateway, stop: () => stopping ??= releaseProviderFactoryLocator(locator) })\n } catch (error) {\n await releaseProviderFactoryLocator(locator)\n throw error\n }\n}\n@creatableProvider()\nclass BoundedRestDataLakeViewer extends RestDataLakeViewer {\n override get client() {\n if (this.context.fetchFn === undefined)\n throw new Error('Publisher datalake requires its bounded fetch transport')\n return new FetchJsonClient({ fetcher: this.context.fetchFn })\n }\n}\n@creatableProvider()\nclass BoundedRestDataLakeRunner extends RestDataLakeRunner {\n override get client() {\n if (this.context.fetchFn === undefined)\n throw new Error('Publisher datalake requires its bounded fetch transport')\n return new FetchJsonClient({ fetcher: this.context.fetchFn })\n }\n}\n/** Keeps SDK datalake methods and response semantics, overriding only its per-instance HTTP client. */\nexport async function openPublisherDataLake(options: {\n readonly fetchFn: typeof globalThis.fetch\n readonly url: string\n readonly writable: boolean\n}) {\n const locator = await baseConfigFactoryLocator({\n connections: { 'event-kit-lake': { type: 'rest', baseUrl: options.url } },\n providerBindings: { DataLakeViewer: { connection: 'event-kit-lake' }, DataLakeRunner: { connection: 'event-kit-lake' } },\n })\n locator.context.fetchFn = options.fetchFn\n locator.register(BoundedRestDataLakeViewer.factory<BoundedRestDataLakeViewer>(BoundedRestDataLakeViewer.dependencies))\n if (options.writable)\n locator.register(BoundedRestDataLakeRunner.factory<BoundedRestDataLakeRunner>(BoundedRestDataLakeRunner.dependencies))\n locator.freeze()\n try {\n const reader = await locator.getInstance<BoundedRestDataLakeViewer>(BoundedRestDataLakeViewer.defaultMoniker)\n const writer = options.writable ? await locator.getInstance<BoundedRestDataLakeRunner>(BoundedRestDataLakeRunner.defaultMoniker) : undefined\n return {\n reader, writer, async close() { await releaseProviderFactoryLocator(locator) },\n }\n } catch (error) {\n await releaseProviderFactoryLocator(locator)\n throw error\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport type { PublisherEndpointChallengeRecord, PublisherEndpointChallengeStore } from '@xyo-network/event-kit-protocol'\nimport { endpointChallengeHash } from '@xyo-network/event-kit-protocol'\nimport {\n Base64Url32BytesZod, EndpointChallengeZod, HandshakeIdZod, HashZod, NormalizedAddressZod,\n} from '@xyo-network/event-kit-schemas'\nimport type { EventKitReplayCheckpointStore } from '@xyo-network/event-kit-statement-graph'\nimport type {\n FinalizedStatementPublicationIntent, FinalizedStatementPublicationJournal, FinalizedStatementPublicationRecord,\n} from '@xyo-network/event-kit-xl1'\nimport { z } from 'zod'\n\nimport type { PublisherEncryptionKeyCustody } from '../handshakeClients.ts'\nimport type { HandshakeMutationIntent, HandshakeMutationIntentStore } from '../handshakeMutationIntent.ts'\nimport {\n assertSameIntentBinding, intentLookupKey, parseHandshakeMutationIntent,\n} from '../handshakeMutationIntent.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\n\nconst KeyZod = z.strictObject({\n encryptionKey: HashZod, keyId: HandshakeIdZod, privateKey: Base64Url32BytesZod, publisher: NormalizedAddressZod,\n})\nconst phases = ['signed', 'content-written', 'content-verified', 'broadcast', 'included', 'finalized'] as const\n\nfunction requireTime(value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new Error('Publisher clock is invalid')\n}\n\nfunction samePublicationIntent(left: FinalizedStatementPublicationIntent, right: FinalizedStatementPublicationIntent): boolean {\n return left.chainId === right.chainId && left.source === right.source && left.operationId === right.operationId\n && isDeepStrictEqual(left.eventHashes, right.eventHashes) && isDeepStrictEqual(left.attachmentHashes, right.attachmentHashes)\n}\n\nfunction publicationKey(intent: FinalizedStatementPublicationIntent): string {\n if (!/^[0-9a-f]{40}$/u.test(intent.chainId) || !/^[0-9a-f]{40}$/u.test(intent.source)\n || intent.operationId.length === 0 || intent.operationId.length > 256\n || [...intent.eventHashes, ...intent.attachmentHashes].some(hash => !HashZod.safeParse(hash).success)) {\n throw new Error('Invalid publication intent')\n }\n return JSON.stringify([intent.chainId, intent.source, intent.operationId])\n}\n\n/** All handshake durability uses the same single-owner SQLite authority as delivery. */\nexport function createSqlitePublisherHandshakeStores(state: SqlitePublisherState, options: { readonly replayNamespace?: string } = {}): {\n readonly challenges: PublisherEndpointChallengeStore\n readonly intents: HandshakeMutationIntentStore\n readonly journal: FinalizedStatementPublicationJournal\n readonly keys: PublisherEncryptionKeyCustody\n readonly replay: EventKitReplayCheckpointStore\n} {\n const replayKey = options.replayNamespace === undefined ? 'checkpoint' : `checkpoint:${z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/u).parse(options.replayNamespace)}`\n const replay: EventKitReplayCheckpointStore = {\n load: async () => state.get('replay', replayKey),\n async save(checkpoint) { state.set('replay', replayKey, checkpoint) },\n }\n const intents: HandshakeMutationIntentStore = {\n async get(lookup) {\n const value = state.get('intents', intentLookupKey(lookup))\n return value === undefined ? undefined : await parseHandshakeMutationIntent(value)\n },\n async getOrCreate(raw) {\n const proposed = await parseHandshakeMutationIntent(raw) as typeof raw\n return state.transaction(() => {\n const key = intentLookupKey(proposed)\n const winner = state.get<HandshakeMutationIntent>('intents', key)\n if (winner !== undefined) {\n assertSameIntentBinding(winner, proposed)\n return { disposition: 'resumed' as const, intent: winner as typeof raw }\n }\n state.set('intents', key, proposed)\n return { disposition: 'created' as const, intent: proposed }\n })\n },\n }\n const keys: PublisherEncryptionKeyCustody = {\n async getPrivateKey(input) {\n const key = `${NormalizedAddressZod.parse(input.publisher)}:${HandshakeIdZod.parse(input.keyId)}`\n const raw = state.get('encryption-keys', key)\n if (raw === undefined) return\n const record = KeyZod.parse(raw)\n if (record.encryptionKey !== HashZod.parse(input.encryptionKey)) throw new Error('Encryption key identity mismatch')\n const { publisher: _publisher, ...privateKey } = record\n return privateKey\n },\n async putPrivateKey(input) {\n const record = KeyZod.parse({ ...input.key, publisher: input.publisher })\n return state.transaction(() => {\n const key = `${record.publisher}:${record.keyId}`\n const prior = state.get('encryption-keys', key)\n if (prior !== undefined) {\n if (!isDeepStrictEqual(prior, record)) throw new Error('Encryption key collision')\n return 'duplicate'\n }\n state.set('encryption-keys', key, record)\n return 'stored'\n })\n },\n }\n const current = (hash: string) => state.get<PublisherEndpointChallengeRecord>('challenges', HashZod.parse(hash))\n const live = (record: PublisherEndpointChallengeRecord, now: number) => record.challenge.issuedAt <= now && now < record.challenge.expiresAt\n const challenges: PublisherEndpointChallengeStore = {\n get: async hash => current(hash),\n async issue(input) {\n const challenge = EndpointChallengeZod.parse(input.challenge)\n const hash = HashZod.parse(input.challengeHash)\n if (await endpointChallengeHash(challenge) !== hash) return { kind: 'collision' }\n return state.transaction(() => {\n const priorNonce = state.get<string>('challenge-nonces', challenge.nonce)\n if (priorNonce !== undefined && priorNonce !== hash) return { kind: 'collision' as const }\n const prior = current(hash)\n if (prior !== undefined) return isDeepStrictEqual(prior.challenge, challenge)\n ? { kind: 'duplicate' as const, record: prior }\n : { kind: 'collision' as const }\n const record: PublisherEndpointChallengeRecord = {\n challenge, challengeHash: hash, state: 'issued',\n }\n state.set('challenge-nonces', challenge.nonce, hash)\n state.set('challenges', hash, record)\n return { kind: 'issued' as const, record }\n })\n },\n async beginAttempt(input) {\n requireTime(input.nowSeconds)\n return state.transaction(() => {\n const record = current(input.challengeHash)\n if (record === undefined) return { kind: 'missing' as const }\n if (record.state === 'verified') return { kind: 'verified' as const, record }\n if (record.state === 'attempted') return { kind: 'already-attempted' as const, record }\n if (!live(record, input.nowSeconds)) return { kind: 'expired' as const, record }\n const attempted: PublisherEndpointChallengeRecord = { ...record, state: 'attempted' }\n state.set('challenges', input.challengeHash, attempted)\n return { kind: 'started' as const, record: attempted }\n })\n },\n async completeVerified(input) {\n requireTime(input.nowSeconds)\n const responseHash = HashZod.parse(input.responseHash)\n return state.transaction(() => {\n const record = current(input.challengeHash)\n if (record === undefined) return { kind: 'missing' as const }\n if (record.state === 'verified') return { kind: record.responseHash === responseHash ? 'duplicate' as const : 'collision' as const, record }\n if (record.state !== 'attempted') return { kind: 'not-attempted' as const, record }\n if (!live(record, input.nowSeconds)) return { kind: 'expired' as const, record }\n const verified: PublisherEndpointChallengeRecord = {\n ...record, responseHash, state: 'verified',\n }\n state.set('challenges', input.challengeHash, verified)\n return { kind: 'verified' as const, record: verified }\n })\n },\n }\n const journal: FinalizedStatementPublicationJournal = {\n async load(intent) {\n const key = publicationKey(intent)\n const signed = state.get<FinalizedStatementPublicationRecord>('publication:signed', key)\n if (signed === undefined) return\n if (!samePublicationIntent(signed, intent)) throw new Error('Publication intent collision')\n let latest = signed\n for (const phase of phases) {\n const record = state.get<FinalizedStatementPublicationRecord>(`publication:${phase}`, key)\n if (record === undefined) continue\n if (record.phase !== phase || !samePublicationIntent(record, intent) || !isDeepStrictEqual(record.evidence, signed.evidence)) {\n throw new Error('Publication evidence collision')\n }\n latest = record\n }\n return latest\n },\n async save(record) {\n const key = publicationKey(record)\n HashZod.parse(record.evidence.transactionHash)\n if (!phases.includes(record.phase)) throw new Error('Unknown publication phase')\n state.transaction(() => {\n const signed = state.get<FinalizedStatementPublicationRecord>('publication:signed', key)\n if (signed === undefined && record.phase !== 'signed') throw new Error('Publication must bind signed evidence first')\n if (signed !== undefined && (!samePublicationIntent(signed, record) || !isDeepStrictEqual(signed.evidence, record.evidence))) {\n throw new Error('Publication intent or evidence collision')\n }\n const namespace = `publication:${record.phase}`\n const prior = state.get(namespace, key)\n if (prior !== undefined && !isDeepStrictEqual(prior, record)) throw new Error('Publication phase collision')\n if (prior === undefined) state.set(namespace, key, record)\n })\n },\n }\n return {\n challenges, intents, journal, keys, replay,\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport {\n lstat, mkdir, open,\n} from 'node:fs/promises'\nimport { hostname } from 'node:os'\nimport PATH from 'node:path'\n\nimport { stringifyJson } from '../filesystemJson.ts'\nexport interface SqlitePublisherStateOptions {\n /** Immutable chain/publisher binding. A database must never silently change owners. */\n readonly identity: string\n readonly path: string\n}\ninterface JsonRow {\n readonly value: string\n}\ninterface OwnerRow {\n readonly host: string\n readonly pid: number\n readonly token: string\n}\n/** Single-process SQLite authority for publisher checkpoints, custody and delivery records. */\nexport interface SqlitePublisherState {\n readonly path: string\n close(): void\n entries<T>(namespace: string): readonly {\n readonly key: string\n readonly value: T\n }[]\n get<T>(namespace: string, key: string): T | undefined\n insert(namespace: string, key: string, value: unknown): boolean\n remove(namespace: string, key: string): void\n set(namespace: string, key: string, value: unknown): void\n transaction<T>(work: () => T): T\n}\nfunction decode<T>(value: string): T {\n return JSON.parse(value, (_key, candidate: unknown) => {\n return typeof candidate === 'object' && candidate !== null && Object.keys(candidate).length === 1\n && '$eventKitBigInt' in candidate && typeof candidate.$eventKitBigInt === 'string'\n && /^(?:0|[1-9][0-9]*)$/u.test(candidate.$eventKitBigInt)\n ? BigInt(candidate.$eventKitBigInt)\n : candidate\n }) as T\n}\nfunction processExists(pid: number): boolean {\n if (!Number.isSafeInteger(pid) || pid < 1)\n throw new Error('Invalid publisher owner record')\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ESRCH')\n return false\n return true\n }\n}\nexport async function openSqlitePublisherState(options: SqlitePublisherStateOptions): Promise<SqlitePublisherState> {\n if (options.path === ':memory:' || options.identity.length === 0)\n throw new Error('Persistent publisher needs a file and an identity')\n const path = PATH.resolve(options.path)\n const directory = PATH.dirname(path)\n await mkdir(directory, { recursive: true, mode: 0o700 })\n const metadata = await lstat(directory)\n if (!metadata.isDirectory() || (metadata.mode & 0o077) !== 0)\n throw new Error('Publisher state directory must be a real directory with 0700 permissions')\n const file = await open(path, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW, 0o600)\n try {\n const metadata = await file.stat()\n if (!metadata.isFile() || (metadata.mode & 0o077) !== 0)\n throw new Error('Publisher database permissions must be 0600')\n await file.sync()\n } finally {\n await file.close()\n }\n const { DatabaseSync } = await import('node:sqlite')\n const database = new DatabaseSync(path)\n const token = randomBytes(16).toString('hex')\n let closed = false\n let inTransaction = false\n const transaction = <T>(work: () => T): T => {\n if (closed)\n throw new Error('Publisher state is closed')\n if (inTransaction)\n return work()\n database.exec('BEGIN IMMEDIATE')\n inTransaction = true\n try {\n const result = work()\n if (result instanceof Promise)\n throw new Error('Publisher state transactions must be synchronous')\n database.exec('COMMIT')\n return result\n } catch (error) {\n database.exec('ROLLBACK')\n throw error\n } finally {\n inTransaction = false\n }\n }\n try {\n database.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = FULL;\n PRAGMA busy_timeout = 5000;\n CREATE TABLE IF NOT EXISTS publisher_records (namespace TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY(namespace, key));\n CREATE TABLE IF NOT EXISTS publisher_owner (id INTEGER PRIMARY KEY CHECK(id = 1), host TEXT NOT NULL, pid INTEGER NOT NULL, token TEXT NOT NULL);\n `)\n transaction(() => {\n const prior = database.prepare('SELECT host, pid, token FROM publisher_owner WHERE id = 1').get() as OwnerRow | undefined\n if (prior !== undefined && (prior.host !== hostname() || processExists(prior.pid))) {\n throw new Error('Publisher database already has an active owner; a shared or multi-host database is not supported')\n }\n const binding = database.prepare('SELECT value FROM publisher_records WHERE namespace = ? AND key = ?').get('metadata', 'identity') as JsonRow | undefined\n if (binding !== undefined && decode(binding.value) !== options.identity)\n throw new Error('Publisher database identity mismatch')\n database.prepare('INSERT OR IGNORE INTO publisher_records(namespace,key,value) VALUES (?,?,?)').run('metadata', 'identity', stringifyJson(options.identity))\n database.prepare('INSERT OR REPLACE INTO publisher_owner(id,host,pid,token) VALUES (1,?,?,?)').run(hostname(), process.pid, token)\n })\n } catch (error) {\n database.close()\n throw error\n }\n const read = database.prepare('SELECT value FROM publisher_records WHERE namespace = ? AND key = ?')\n const list = database.prepare('SELECT key, value FROM publisher_records WHERE namespace = ? ORDER BY key')\n const write = database.prepare('INSERT INTO publisher_records(namespace,key,value) VALUES (?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET value = excluded.value')\n const insert = database.prepare('INSERT OR IGNORE INTO publisher_records(namespace,key,value) VALUES (?,?,?)')\n const remove = database.prepare('DELETE FROM publisher_records WHERE namespace = ? AND key = ?')\n const assertOpen = () => {\n if (closed)\n throw new Error('Publisher state is closed')\n }\n return {\n path,\n get<T>(namespace: string, key: string): T | undefined {\n assertOpen()\n const row = read.get(namespace, key) as JsonRow | undefined\n return row === undefined ? undefined : decode<T>(row.value)\n },\n entries<T>(namespace: string) {\n assertOpen()\n return (list.all(namespace) as {\n key: string\n value: string\n }[]).map(row => ({ key: row.key, value: decode<T>(row.value) }))\n },\n set(namespace, key, value) {\n assertOpen()\n write.run(namespace, key, stringifyJson(value))\n },\n insert(namespace, key, value) {\n assertOpen()\n return insert.run(namespace, key, stringifyJson(value)).changes === 1\n },\n remove(namespace, key) {\n assertOpen()\n remove.run(namespace, key)\n },\n transaction,\n close() {\n if (closed)\n return\n transaction(() => {\n database.prepare('DELETE FROM publisher_owner WHERE id = 1 AND token = ?').run(token)\n })\n database.close()\n closed = true\n },\n }\n}\n", "import { createHash, randomBytes } from 'node:crypto'\n\nimport type { BestEffortAuthorizedAdmission, BestEffortCommitResult } from '@xyo-network/event-kit-protocol'\nimport {\n canonicalJson, commitBestEffortSecurity, createBestEffortSecurityState, parseAdmittedWake,\n parseBestEffortSecurityState, wakeSourceHash,\n} from '@xyo-network/event-kit-protocol'\nimport {\n ChainIdZod, DeploymentIdZod, HashZod, NonnegativeJsonSafeIntegerZod, NormalizedAddressZod,\n WakeJwtAudienceZod, WakeSourceZod,\n} from '@xyo-network/event-kit-schemas'\nimport { z } from 'zod'\n\nimport type {\n BestEffortConsumerBinding, BestEffortDirtyTarget, BestEffortWorkerLease, PersistentBestEffortInbox,\n} from './bestEffortTypes.ts'\nimport { openPrivateSqlite } from './privateSqlite.ts'\n\nexport interface SqliteBestEffortInboxOptions {\n /** An immutable host application/consumer identifier. Do not share with Durable Delivery. */\n readonly consumerId: string\n /** Finite per-index replay capacity; unexpired records are never evicted. */\n readonly maxSecurityRecords: number\n /** Finite exact binding capacity, including retained completed targets. */\n readonly maxTargets?: number\n readonly nowSeconds?: () => number\n readonly path: string\n /** Acceleration only. Failure is repaired by durable scanning or a matching duplicate. */\n readonly requestWork?: (target: BestEffortDirtyTarget) => void | Promise<void>\n}\n\nconst BindingZod = z.strictObject({\n audience: WakeJwtAudienceZod,\n authorizationChainId: ChainIdZod,\n consumerId: z.string().min(1).max(255),\n controller: NormalizedAddressZod,\n deploymentId: DeploymentIdZod,\n filterHash: HashZod,\n publisher: NormalizedAddressZod,\n queueId: z.string().min(1).max(255).optional(),\n source: WakeSourceZod,\n subscriptionHash: HashZod,\n})\nconst SnapshotPositionZod = z.strictObject({\n position: NonnegativeJsonSafeIntegerZod,\n hash: HashZod.optional(),\n})\nconst TargetZod = z.strictObject({\n binding: BindingZod,\n completedGeneration: NonnegativeJsonSafeIntegerZod,\n generation: NonnegativeJsonSafeIntegerZod,\n id: HashZod,\n requestedPosition: NonnegativeJsonSafeIntegerZod,\n fence: NonnegativeJsonSafeIntegerZod,\n previousSnapshot: SnapshotPositionZod.optional(),\n lease: z.strictObject({\n expiresAt: NonnegativeJsonSafeIntegerZod,\n token: z.string().regex(/^[0-9a-f]{32}$/u),\n }).optional(),\n}).refine(\n target => target.generation > 0 && target.completedGeneration <= target.generation\n && (target.lease === undefined || (target.fence > 0 && target.generation > target.completedGeneration))\n && (target.previousSnapshot === undefined || target.binding.source.kind === 'utc-interval' || target.previousSnapshot.hash !== undefined),\n 'Invalid Best Effort dirty generation',\n)\ntype StoredTarget = z.infer<typeof TargetZod>\nconst CatalogZod = z.strictObject({\n id: HashZod,\n binding: z.string(),\n target_hash: HashZod,\n fence: NonnegativeJsonSafeIntegerZod,\n generation: NonnegativeJsonSafeIntegerZod,\n}).refine(record => record.generation > 0, 'Invalid Best Effort catalog generation')\ntype TargetCatalog = z.infer<typeof CatalogZod>\n\nfunction bindingId(binding: BestEffortConsumerBinding) {\n return createHash('sha256').update(canonicalJson(binding)).digest('hex')\n}\nfunction targetHash(body: string) {\n return createHash('sha256').update(body).digest('hex')\n}\nfunction parseCatalog(value: unknown): TargetCatalog {\n const record = CatalogZod.parse(value)\n const binding = BindingZod.parse(JSON.parse(record.binding))\n if (record.id !== bindingId(binding) || record.binding !== canonicalJson(binding))\n throw new TypeError('Persisted Best Effort catalog changed exact binding')\n return record\n}\nfunction parseTarget(body: unknown, expectedId: string): StoredTarget {\n if (typeof body !== 'string') throw new TypeError('Malformed persisted Best Effort target')\n const parsed = TargetZod.parse(JSON.parse(body))\n if (parsed.id !== expectedId || bindingId(parsed.binding) !== expectedId)\n throw new TypeError('Persisted Best Effort target changed exact scope')\n return parsed\n}\nfunction publicTarget(target: StoredTarget): BestEffortDirtyTarget {\n return {\n binding: target.binding,\n completedGeneration: target.completedGeneration,\n generation: target.generation,\n id: target.id,\n requestedPosition: target.requestedPosition,\n }\n}\nfunction increment(value: number) {\n if (!Number.isSafeInteger(value + 1)) throw new RangeError('Best Effort fence/generation exhausted')\n return value + 1\n}\n\n/**\n * SQLite co-commits security, receive-clock high water and dirty generation in\n * one writer transaction. Only the Best Effort namespace is decoded. No callback\n * or external queue participates in the durability boundary.\n */\nexport async function createSqliteBestEffortInbox(options: SqliteBestEffortInboxOptions): Promise<PersistentBestEffortInbox> {\n const consumerId = z.string().min(1).max(255).parse(options.consumerId)\n const maxTargets = options.maxTargets ?? 1024\n if (!Number.isSafeInteger(options.maxSecurityRecords) || options.maxSecurityRecords < 1 || options.maxSecurityRecords > 65_536)\n throw new TypeError('Invalid finite Best Effort security capacity')\n if (!Number.isSafeInteger(maxTargets) || maxTargets < 1 || maxTargets > 65_536)\n throw new TypeError('Invalid finite Best Effort target capacity')\n const nowSeconds = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const connection = openPrivateSqlite({ path: options.path, format: 'event-kit-best-effort-inbox' })\n const { database } = connection\n const transaction = <T>(work: () => T): T => connection.transaction(work)\n try {\n const settings = canonicalJson({\n consumerId, maxSecurityRecords: options.maxSecurityRecords, maxTargets,\n })\n transaction(() => {\n const marker = database.prepare('SELECT initialized FROM eventkit_store WHERE id = 1').get()\n if (marker?.initialized !== 0 && marker?.initialized !== 1)\n throw new TypeError('Invalid Best Effort store initialization authority')\n const tables = database.prepare(\"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\").all()\n const names = new Set(tables.map(row => row.name))\n if (marker.initialized === 1) {\n if (['best_effort_security', 'best_effort_targets', 'best_effort_settings', 'best_effort_catalog'].some(name => !names.has(name)))\n throw new TypeError('Initialized Best Effort store lost authoritative tables; restore its custody before reopening')\n const previous = database.prepare('SELECT body FROM best_effort_settings WHERE id = 1').get()\n if (previous === undefined) throw new TypeError('Missing immutable Best Effort store settings')\n if (previous.body !== settings) throw new TypeError('Best Effort store consumer or capacity binding changed')\n return\n }\n\n if (tables.some(row => row.name !== 'eventkit_store'))\n throw new TypeError('Uninitialized Best Effort bootstrap contains unexpected custody')\n database.exec(`\n CREATE TABLE best_effort_security (id INTEGER PRIMARY KEY CHECK (id = 1), body TEXT NOT NULL);\n CREATE TABLE best_effort_targets (id TEXT PRIMARY KEY, body TEXT NOT NULL);\n CREATE TABLE best_effort_settings (id INTEGER PRIMARY KEY CHECK (id = 1), body TEXT NOT NULL, catalog_count INTEGER NOT NULL);\n CREATE TABLE best_effort_catalog (id TEXT PRIMARY KEY, binding TEXT NOT NULL, target_hash TEXT NOT NULL, fence INTEGER NOT NULL, generation INTEGER NOT NULL);\n `)\n database.prepare('INSERT INTO best_effort_settings (id, body, catalog_count) VALUES (1, ?, 0)').run(settings)\n database.prepare('INSERT INTO best_effort_security (id, body) VALUES (1, ?)')\n .run(JSON.stringify(createBestEffortSecurityState()))\n database.prepare('UPDATE eventkit_store SET initialized = 1 WHERE id = 1').run()\n })\n const readSecurity = () => {\n const row = database.prepare('SELECT body FROM best_effort_security WHERE id = 1').get()\n if (typeof row?.body !== 'string') throw new TypeError('Missing persisted Best Effort security state')\n const parsed = parseBestEffortSecurityState(JSON.parse(row.body))\n if (parsed.jwtRecords.length > options.maxSecurityRecords || parsed.wakeRecords.length > options.maxSecurityRecords)\n throw new TypeError('Persisted Best Effort security exceeds its configured bound')\n return parsed\n }\n const readCatalog = (id: string) => {\n const row = database.prepare('SELECT id, binding, target_hash, fence, generation FROM best_effort_catalog WHERE id = ?').get(id)\n return row === undefined ? undefined : parseCatalog(row)\n }\n const verifiedTarget = (body: unknown, catalog: TargetCatalog): StoredTarget => {\n const target = parseTarget(body, catalog.id)\n if (target.binding.consumerId !== consumerId) throw new TypeError('Persisted Best Effort target changed consumer')\n if (typeof body !== 'string' || catalog.target_hash !== targetHash(body)\n || catalog.binding !== canonicalJson(target.binding) || catalog.fence !== target.fence || catalog.generation !== target.generation)\n throw new TypeError('Persisted Best Effort target differs from its permanent catalog authority')\n return target\n }\n const readTargets = () => {\n const setting = database.prepare('SELECT catalog_count FROM best_effort_settings WHERE id = 1').get()\n const expectedCount = NonnegativeJsonSafeIntegerZod.parse(setting?.catalog_count)\n if (expectedCount > maxTargets) throw new TypeError('Persisted Best Effort catalog capacity exceeded')\n const catalogs = database.prepare('SELECT id, binding, target_hash, fence, generation FROM best_effort_catalog ORDER BY id').all()\n .map(parseCatalog)\n const rows = database.prepare('SELECT id, body FROM best_effort_targets ORDER BY id').all()\n if (catalogs.length !== expectedCount || rows.length !== expectedCount)\n throw new TypeError('Persisted Best Effort binding catalog lost authoritative target custody')\n const byId = new Map(catalogs.map(catalog => [catalog.id, catalog]))\n return rows.map((row) => {\n if (typeof row.id !== 'string') throw new TypeError('Malformed persisted Best Effort target identity')\n const catalog = byId.get(row.id)\n if (catalog === undefined) throw new TypeError('Persisted Best Effort target lost permanent binding custody')\n return verifiedTarget(row.body, catalog)\n })\n }\n const readTarget = (id: string) => {\n const row = database.prepare('SELECT body FROM best_effort_targets WHERE id = ?').get(id)\n const catalog = readCatalog(id)\n if (row === undefined && catalog === undefined) return\n if (row === undefined || catalog === undefined)\n throw new TypeError('Persisted Best Effort binding lost its authoritative target/catalog custody')\n return verifiedTarget(row.body, catalog)\n }\n const saveTarget = (target: StoredTarget) => {\n const catalog = readCatalog(target.id)\n const body = JSON.stringify(target)\n const binding = canonicalJson(target.binding)\n if (catalog === undefined) {\n if (database.prepare('SELECT id FROM best_effort_targets WHERE id = ?').get(target.id) !== undefined)\n throw new TypeError('Existing Best Effort target lost its permanent binding catalog')\n database.prepare('INSERT INTO best_effort_catalog (id, binding, target_hash, fence, generation) VALUES (?, ?, ?, ?, ?)')\n .run(target.id, binding, targetHash(body), target.fence, target.generation)\n database.prepare('UPDATE best_effort_settings SET catalog_count = catalog_count + 1 WHERE id = 1').run()\n } else {\n if (catalog.binding !== binding || target.fence < catalog.fence || target.generation < catalog.generation)\n throw new TypeError('Best Effort target mutation would regress permanent binding authority')\n database.prepare('UPDATE best_effort_catalog SET target_hash = ?, fence = ?, generation = ? WHERE id = ?')\n .run(targetHash(body), target.fence, target.generation, target.id)\n }\n database.prepare('INSERT INTO best_effort_targets (id, body) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET body = excluded.body')\n .run(target.id, body)\n }\n transaction(() => {\n const security = readSecurity()\n const targets = readTargets()\n if (security.jwtRecords.length > options.maxSecurityRecords || security.wakeRecords.length > options.maxSecurityRecords\n || targets.length > maxTargets || targets.some(target => target.binding.consumerId !== consumerId))\n throw new TypeError('Persisted Best Effort state exceeds its exact bound')\n })\n\n async function requestWork(target: StoredTarget) {\n if (target.generation === target.completedGeneration || options.requestWork === undefined) return false\n try {\n await options.requestWork(publicTarget(target))\n return true\n } catch {\n // Durable dirty state, not callback success, determines admitted work.\n return false\n }\n }\n const currentTarget = (captured: StoredTarget): StoredTarget | undefined => {\n const current = readTarget(captured.id)\n const now = NonnegativeJsonSafeIntegerZod.parse(nowSeconds())\n return current?.lease?.token === captured.lease?.token && current?.fence === captured.fence\n && current?.generation === captured.generation && current.lease !== undefined\n && current.lease.expiresAt > now\n ? current\n : undefined\n }\n\n return {\n async commitAuthorized(input: BestEffortAuthorizedAdmission): Promise<BestEffortCommitResult> {\n input = structuredClone(input)\n const wake = await parseAdmittedWake(input.wake)\n const grant = input.grant.grant\n if (grant.authorizationKind !== 'activated-subscription'\n || grant.target !== wake.publisher || grant.authorizationChainId !== wake.event.authorizationChainId\n || grant.deploymentId !== wake.deploymentId || grant.filterHash !== wake.event.filterHash\n || grant.queueId !== wake.queueId || grant.sourceHash !== await wakeSourceHash(wake.event.source))\n throw new TypeError('Best Effort grant does not match its exact admitted profile')\n const binding = BindingZod.parse({\n consumerId,\n audience: wake.audience,\n authorizationChainId: wake.event.authorizationChainId,\n controller: grant.controller,\n deploymentId: wake.deploymentId,\n filterHash: wake.event.filterHash,\n publisher: wake.publisher,\n source: wake.event.source,\n subscriptionHash: grant.subscriptionHash,\n ...(wake.queueId === undefined ? {} : { queueId: wake.queueId }),\n })\n const id = bindingId(binding)\n const committed = transaction(() => {\n const authority = { security: readSecurity(), targets: readTargets() }\n const next = commitBestEffortSecurity(authority.security, { ...input, wake }, options.maxSecurityRecords)\n if (next.result.kind !== 'accepted' && next.result.kind !== 'duplicate') return { result: next.result }\n const previous = authority.targets.find(target => target.id === id)\n if (previous === undefined && next.result.kind === 'duplicate')\n throw new TypeError('Persisted duplicate lost its authoritative Best Effort target')\n if (previous === undefined && authority.targets.length >= maxTargets)\n return { result: { kind: 'capacity-exceeded' } as const }\n const target: StoredTarget = previous === undefined\n ? {\n binding, id, completedGeneration: 0, generation: 1, fence: 0, requestedPosition: wake.toPosition,\n }\n : next.result.kind === 'duplicate'\n ? previous\n : {\n ...previous,\n generation: increment(previous.generation),\n requestedPosition: Math.max(previous.requestedPosition, wake.toPosition),\n }\n database.prepare('UPDATE best_effort_security SET body = ? WHERE id = 1').run(JSON.stringify(next.state))\n saveTarget(target)\n return { result: next.result, target }\n })\n if (committed.target !== undefined) await requestWork(committed.target)\n return committed.result\n },\n dirtyTargets: async () => transaction(() => readTargets().filter(target => target.generation > target.completedGeneration).map(publicTarget)),\n async repairDirty() {\n let failed = 0\n let scheduled = 0\n const targets = transaction(() => readTargets())\n for (const target of targets) {\n if (options.requestWork === undefined || target.generation === target.completedGeneration) continue\n if (await requestWork(target)) scheduled += 1\n else failed += 1\n }\n return { failed, scheduled }\n },\n async recoverExpired(now) {\n NonnegativeJsonSafeIntegerZod.parse(now)\n return transaction(() => {\n let recovered = 0\n for (const target of readTargets()) {\n if (target.lease === undefined || target.lease.expiresAt > now) continue\n saveTarget({ ...target, lease: undefined })\n recovered += 1\n }\n return recovered\n })\n },\n async claim(input): Promise<BestEffortWorkerLease | undefined> {\n NonnegativeJsonSafeIntegerZod.parse(input.nowSeconds)\n if (!Number.isSafeInteger(input.leaseSeconds) || input.leaseSeconds < 1\n || !Number.isSafeInteger(input.nowSeconds + input.leaseSeconds))\n throw new TypeError('Invalid Best Effort worker lease lifetime')\n const captured = transaction(() => {\n const target = readTargets().find(item => item.generation > item.completedGeneration && item.lease === undefined)\n if (target === undefined) return\n const claimed: StoredTarget = {\n ...target,\n fence: increment(target.fence),\n lease: { token: randomBytes(16).toString('hex'), expiresAt: input.nowSeconds + input.leaseSeconds },\n }\n saveTarget(claimed)\n return claimed\n })\n if (captured?.lease === undefined) return undefined\n return {\n ...publicTarget(captured),\n fence: captured.fence,\n leaseToken: captured.lease.token,\n ...(captured.previousSnapshot === undefined ? {} : { previousSnapshot: captured.previousSnapshot }),\n isCurrent: async () => transaction(() => currentTarget(captured) !== undefined),\n async complete(snapshot) {\n const position = SnapshotPositionZod.parse({ position: snapshot.position, ...(snapshot.hash === undefined ? {} : { hash: snapshot.hash }) })\n return transaction(() => {\n const current = currentTarget(captured)\n if (current === undefined) return false\n if (current.binding.source.kind !== 'utc-interval' && position.hash === undefined)\n throw new TypeError('Finalized snapshot completion requires its verified hash')\n const previous = current.previousSnapshot\n if (previous !== undefined && (position.position < previous.position\n || (position.position === previous.position && position.hash !== previous.hash)))\n throw new TypeError('Best Effort completion regressed its committed snapshot')\n saveTarget({\n ...current, completedGeneration: current.generation, previousSnapshot: position, lease: undefined,\n })\n return true\n })\n },\n async release() {\n transaction(() => {\n const current = readTarget(captured.id)\n if (current?.lease?.token === captured.lease?.token && current?.fence === captured.fence)\n saveTarget({ ...current, lease: undefined })\n })\n },\n }\n },\n close: () => connection.close(),\n }\n } catch (error) {\n connection.close()\n throw error\n }\n}\n", "import type { WakeQueue } from '@xyo-network/event-kit-protocol'\n\nimport { openReceiverAuthority } from './receiverAuthority.ts'\n\nexport interface SqliteWakeQueueOptions { readonly path: string }\nexport interface SqliteWakeQueue extends WakeQueue { close(): void }\n\n/** FULL/WAL queue; old unfenced databases require explicit offline migration. */\nexport async function createSqliteWakeQueue(options: SqliteWakeQueueOptions): Promise<SqliteWakeQueue> {\n const authority = openReceiverAuthority(options.path)\n return { ...authority.queue, close: authority.close }\n}\n\n/** Atomic production composition: identities and work live in one database. */\nexport async function createSqliteWakeReceiver(options: SqliteWakeQueueOptions) {\n const authority = openReceiverAuthority(options.path)\n return {\n queue: authority.queue,\n inbox: authority.inbox,\n close: authority.close,\n pruneExpiredTokens: async (nowSeconds: number) => authority.pruneExpiredTokens(nowSeconds),\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;AAAA,SAAS,eAAe,wBAAwB;AAChD;AAAA,EACE;AAAA,EAAS;AAAA,EAA+B;AAAA,OACnC;AAmDA,SAAS,+BACd,SAC0B;AAC1B,MAAI,CAAC,OAAO,cAAc,QAAQ,gBAAgB,KAAK,QAAQ,mBAAmB;AAChF,UAAM,IAAI,UAAU,qCAAqC;AAC3D,QAAM,aAAa,QAAQ,eAAe,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAC5E,QAAM,eAAe,QAAQ,gBAAgB;AAC7C,MAAI,CAAC,OAAO,cAAc,YAAY,KAAK,eAAe;AACxD,UAAM,IAAI,UAAU,2CAA2C;AAEjE,iBAAe,gBAAgB,OAA8B,QAA0D;AACrH,UAAM,SAAS,MAAM,QAAQ;AAC7B,UAAM,WAAW,MAAM,QAAQ,OAAO,YAAY;AAAA,MAChD;AAAA,MAAQ;AAAA,MAAQ,UAAU,QAAQ;AAAA,IACpC,CAAC;AACD,WAAO,eAAe;AACtB,UAAM,WAAW,MAAM,QAAQ,OAAO,eAAe;AAAA,MACnD;AAAA,MAAQ;AAAA,MAAQ,UAAU;AAAA,IAC5B,CAAC;AACD,WAAO,eAAe;AACtB,kBAAc,MAAM,SAAS,MAAM;AACnC,kCAA8B,MAAM,SAAS,QAAQ;AACrD,QAAI,SAAS,SAAS,OAAW,SAAQ,MAAM,SAAS,IAAI;AAC5D,QAAI,CAAC,iBAAiB,QAAQ,SAAS,MAAM,KACvC,OAAO,SAAS,kBAAkB,SAAS,SAAS;AACxD,YAAM,IAAI,UAAU,uDAAuD;AAC7E,QAAI,OAAO,WAAW,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;AACzB,kBAAI,aAAa,WAAc,SAAS,WAAW,SAAS,YACtD,SAAS,aAAa,SAAS,YAAY,SAAS,SAAS,SAAS;AAC1E,sBAAM,IAAI,UAAU,yDAAyD;AAC/E,yBAAW;AAAA,gBACT,GAAG;AAAA,gBAAS,qBAAqB,QAAQ;AAAA,gBAAY,kBAAkB;AAAA,gBAAU,OAAO;AAAA,cAC1F,CAAC;AACD,qBAAO;AAAA,YACT,CAAC;AAAA,UACH;AAAA,UACA,MAAM,UAAU;AACd,wBAAY,MAAM;AAChB,oBAAM,UAAU,WAAW,SAAS,EAAE;AACtC,kBAAI,SAAS,OAAO,UAAU,SAAS,OAAO,SAAS,SAAS,UAAU,SAAS;AACjF,2BAAW,EAAE,GAAG,SAAS,OAAO,OAAU,CAAC;AAAA,YAC/C,CAAC;AAAA,UACH;AAAA,QACF;AAAA,MACF;AAAA,MACA,OAAO,MAAM,WAAW,MAAM;AAAA,IAChC;AAAA,EACF,SAAS,OAAO;AACd,eAAW,MAAM;AACjB,UAAM;AAAA,EACR;AACF;;;AClXA,eAAsB,sBAAsB,SAA2D;AACrG,QAAM,YAAY,sBAAsB,QAAQ,IAAI;AACpD,SAAO,EAAE,GAAG,UAAU,OAAO,OAAO,UAAU,MAAM;AACtD;AAGA,eAAsB,yBAAyB,SAAiC;AAC9E,QAAM,YAAY,sBAAsB,QAAQ,IAAI;AACpD,SAAO;AAAA,IACL,OAAO,UAAU;AAAA,IACjB,OAAO,UAAU;AAAA,IACjB,OAAO,UAAU;AAAA,IACjB,oBAAoB,OAAO,eAAuB,UAAU,mBAAmB,UAAU;AAAA,EAC3F;AACF;",
|
|
4
|
+
"sourcesContent": ["import { canonicalJson, wakeSourcesEqual } from '@xyo-network/event-kit-protocol'\nimport {\n HashZod, NonnegativeJsonSafeIntegerZod, WakeSourceZod,\n} from '@xyo-network/event-kit-schemas'\n\nimport type {\n BestEffortWorkerLease, PersistentBestEffortInbox, VerifiedBestEffortSnapshot,\n} from './bestEffortTypes.ts'\n\n/** The port must enforce the byte bound while reading and independently verify source identity/finality/content. */\nexport interface BestEffortSnapshotSource<TSnapshot, TValue> {\n readCurrent(input: {\n readonly maxBytes: number\n readonly signal: AbortSignal\n readonly source: BestEffortWorkerLease['binding']['source']\n }): Promise<TSnapshot>\n verifySnapshot(input: {\n readonly signal: AbortSignal\n readonly snapshot: TSnapshot\n readonly source: BestEffortWorkerLease['binding']['source']\n }): Promise<VerifiedBestEffortSnapshot<TValue>>\n}\n\n/**\n * Host-owned effect/checkpoint commit. The host must atomically reject older\n * binding/fence commits and make repeats safe through idempotence or its effect\n * journal/checkpoint transaction. A process can die after this commit and before\n * inbox completion, so it can be repeated. `lease.isCurrent()` is advisory and\n * cannot replace the app's own atomic fence/effect commit.\n * dapp-kit consumers implement this through their effect journal/checkpoint,\n * rather than an independent app engine in Event Kit.\n */\nexport interface BestEffortSnapshotApplication<TValue> {\n commitSnapshot(input: {\n readonly lease: BestEffortWorkerLease\n readonly snapshot: VerifiedBestEffortSnapshot<TValue>\n }): Promise<void>\n}\n\nexport interface BestEffortSnapshotWorkerOptions<TSnapshot, TValue> {\n readonly application: BestEffortSnapshotApplication<TValue>\n readonly inbox: PersistentBestEffortInbox\n readonly leaseSeconds?: number\n readonly maxSnapshotBytes: number\n readonly nowSeconds?: () => number\n readonly source: BestEffortSnapshotSource<TSnapshot, TValue>\n}\n\nexport interface BestEffortSnapshotWorker {\n /** Run at startup and periodically; durable scanning, not callbacks, chooses work. */\n runOnce(signal?: AbortSignal): Promise<'idle' | 'completed' | 'superseded'>\n}\n\n/** A bounded observer worker; no full-history replay or public-ingress app execution. */\nexport function createBestEffortSnapshotWorker<TSnapshot, TValue>(\n options: BestEffortSnapshotWorkerOptions<TSnapshot, TValue>,\n): BestEffortSnapshotWorker {\n if (!Number.isSafeInteger(options.maxSnapshotBytes) || options.maxSnapshotBytes < 1)\n throw new TypeError('Invalid bounded snapshot byte limit')\n const nowSeconds = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const leaseSeconds = options.leaseSeconds ?? 60\n if (!Number.isSafeInteger(leaseSeconds) || leaseSeconds < 1)\n throw new TypeError('Invalid Best Effort worker lease lifetime')\n\n async function processSnapshot(lease: BestEffortWorkerLease, signal: AbortSignal): Promise<'completed' | 'superseded'> {\n const source = lease.binding.source\n const observed = await options.source.readCurrent({\n source, signal, maxBytes: options.maxSnapshotBytes,\n })\n signal.throwIfAborted()\n const snapshot = await options.source.verifySnapshot({\n source, signal, snapshot: observed,\n })\n signal.throwIfAborted()\n WakeSourceZod.parse(snapshot.source)\n NonnegativeJsonSafeIntegerZod.parse(snapshot.position)\n if (snapshot.hash !== undefined) HashZod.parse(snapshot.hash)\n if (!wakeSourcesEqual(source, snapshot.source)\n || (source.kind !== 'utc-interval' && snapshot.hash === undefined))\n throw new TypeError('Independent snapshot does not match its pinned source')\n if (Buffer.byteLength(canonicalJson(snapshot.value), 'utf8') > options.maxSnapshotBytes)\n throw new RangeError('Independent snapshot exceeds its configured byte bound')\n const previous = lease.previousSnapshot\n if (previous !== undefined && (snapshot.position < previous.position\n || (snapshot.position === previous.position && snapshot.hash !== previous.hash)))\n throw new TypeError('Independent snapshot regressed or changed at the committed position')\n if (!await lease.isCurrent()) return 'superseded'\n await options.application.commitSnapshot({ lease, snapshot })\n signal.throwIfAborted()\n return await lease.complete(snapshot) ? 'completed' : 'superseded'\n }\n\n return {\n async runOnce(inputSignal) {\n const controller = new AbortController()\n const signal = inputSignal ?? controller.signal\n signal.throwIfAborted()\n const now = nowSeconds()\n await options.inbox.recoverExpired(now)\n const lease = await options.inbox.claim({ nowSeconds: now, leaseSeconds })\n if (lease === undefined) return 'idle'\n let failed = false\n let failure: unknown\n let releaseFailed = false\n let releaseFailure: unknown\n let result: 'completed' | 'superseded' = 'superseded'\n try {\n result = await processSnapshot(lease, signal)\n } catch (error) {\n failed = true\n failure = error\n }\n try {\n await lease.release()\n } catch (error) {\n releaseFailed = true\n releaseFailure = error\n }\n if (failed && releaseFailed)\n throw new AggregateError([failure, releaseFailure], 'Best Effort snapshot work failed and its lease release also failed', { cause: failure })\n if (failed) throw failure\n if (releaseFailed) throw releaseFailure\n return result\n },\n }\n}\n", "import { lstat } from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type { PublisherCursorStore } from '@xyo-network/event-kit-actor'\nimport { NonnegativeJsonSafeIntegerZod } from '@xyo-network/event-kit-schemas'\nimport { z } from 'zod'\n\nimport { ensureDurableDirectory, syncDirectory } from './filesystemDurability.ts'\nimport { readJsonFileStrict, replaceJsonFile } from './filesystemJson.ts'\nimport { checkPrivateStoreFile, ensurePrivateDirectory } from './privateSqlite.ts'\n\nexport interface FilesystemCursorStoreOptions {\n /** Absolute or relative path to the cursor JSON file. */\n readonly path: string\n}\n\nconst CursorFileZod = z.strictObject({ lastProcessedBlock: NonnegativeJsonSafeIntegerZod })\n\n/**\n * Persists the publisher cursor as `{ \"lastProcessedBlock\": number }` on disk.\n */\nexport function createFilesystemCursorStore(\n options: FilesystemCursorStoreOptions,\n): PublisherCursorStore {\n const filePath = PATH.resolve(options.path)\n const directory = PATH.dirname(filePath)\n return {\n async load(): Promise<number | undefined> {\n if (!await existingPrivateDirectory(directory)) return undefined\n checkPrivateStoreFile(filePath)\n const raw = await readJsonFileStrict(filePath)\n if (raw === undefined) return undefined\n const cursor = CursorFileZod.parse(raw)\n // Finish a previous replacement whose directory flush failed before\n // exposing its checkpoint as the authority for fresh publisher work.\n await syncDirectory(directory)\n return cursor.lastProcessedBlock\n },\n async save(lastProcessedBlock: number): Promise<void> {\n const body = CursorFileZod.parse({ lastProcessedBlock })\n await ensureDurableDirectory(directory, 0o700)\n ensurePrivateDirectory(directory)\n checkPrivateStoreFile(filePath)\n await replaceJsonFile(filePath, body, { mode: 0o600, directoryMode: 0o700 })\n },\n }\n}\n\nasync function existingPrivateDirectory(directory: string) {\n try {\n await lstat(directory)\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') return false\n throw error\n }\n ensurePrivateDirectory(directory)\n return true\n}\n", "import { mkdir, open } from 'node:fs/promises'\nimport PATH from 'node:path'\n\n/** Writes and fsyncs `body` so the bytes survive a crash before the caller publishes it. */\nexport async function writeDurableFile(path: string, body: string, mode?: number): Promise<void> {\n const handle = await open(path, 'w', mode)\n try {\n await handle.writeFile(body, 'utf8')\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n\n/** Creates a directory tree and fsyncs each new entry through its previously existing parent. */\nexport async function ensureDurableDirectory(path: string, mode?: number): Promise<void> {\n const directory = PATH.resolve(path)\n const firstCreated = await mkdir(directory, { mode, recursive: true })\n if (firstCreated === undefined) return\n\n const existingParent = PATH.dirname(PATH.resolve(firstCreated))\n let cursor = directory\n while (true) {\n await syncDirectory(cursor)\n if (cursor === existingParent) return\n const parent = PATH.dirname(cursor)\n if (parent === cursor) throw new Error('Created directory is not below its reported existing parent')\n cursor = parent\n }\n}\n\n/**\n * Fsyncs a directory so a published entry survives power loss. Only explicit\n * platform/filesystem \"directory sync unsupported\" errors are non-fatal;\n * missing paths, permission failures, and I/O errors remain hard failures.\n */\nexport async function syncDirectory(path: string): Promise<void> {\n let handle\n try {\n handle = await open(path, 'r')\n await handle.sync()\n } catch (error) {\n if (!isUnsupportedDirectorySync(error)) throw error\n } finally {\n await handle?.close()\n }\n}\n\nfunction isUnsupportedDirectorySync(error: unknown): boolean {\n const code = errorCode(error)\n return code === 'EISDIR' || code === 'EINVAL' || code === 'ENOTSUP' || code === 'EOPNOTSUPP'\n}\n\nfunction errorCode(error: unknown): unknown {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as { code?: unknown }).code\n : undefined\n}\n", "import { randomBytes } from 'node:crypto'\nimport {\n link, open, rename, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport {\n ensureDurableDirectory,\n syncDirectory,\n writeDurableFile,\n} from './filesystemDurability.ts'\n\nexport interface FilesystemJsonWriteOptions {\n readonly directoryMode?: number\n readonly mode?: number\n}\n\nexport async function readJsonFileStrict(path: string): Promise<unknown> {\n let handle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return undefined\n throw error\n }\n try {\n return JSON.parse(await handle.readFile('utf8'), reviveJson) as unknown\n } finally { await handle.close() }\n}\n\n/** Atomically replaces one JSON file after its new bytes have reached disk. */\nexport async function replaceJsonFile(\n path: string,\n value: unknown,\n options: FilesystemJsonWriteOptions = {},\n): Promise<void> {\n const directory = PATH.dirname(path)\n await ensureDurableDirectory(directory, options.directoryMode)\n const tempPath = PATH.join(directory, `.${PATH.basename(path)}.${process.pid}.${suffix()}.tmp`)\n try {\n await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n await rename(tempPath, path)\n await syncDirectory(directory)\n } catch (error) {\n await unlinkIfMissing(tempPath)\n throw error\n }\n}\n\n/**\n * Publishes immutable JSON with an exclusive hard link. Returns `false` when\n * another process already owns the destination.\n */\nexport async function publishJsonFile(\n path: string,\n value: unknown,\n options: FilesystemJsonWriteOptions = {},\n): Promise<boolean> {\n const directory = PATH.dirname(path)\n await ensureDurableDirectory(directory, options.directoryMode)\n const tempPath = PATH.join(directory, `.${PATH.basename(path)}.${process.pid}.${suffix()}.tmp`)\n try {\n await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n await link(tempPath, path)\n await syncDirectory(directory)\n return true\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw error\n } finally {\n await unlinkIfMissing(tempPath)\n }\n}\n\nfunction suffix(): string {\n return randomBytes(8).toString('hex')\n}\n\nexport function stringifyJson(value: unknown): string {\n return JSON.stringify(value, replaceJsonValue)\n}\n\nfunction replaceJsonValue(_key: string, candidate: unknown): unknown {\n return typeof candidate === 'bigint'\n ? { $eventKitBigInt: candidate.toString() }\n : candidate\n}\n\nfunction reviveJson(_key: string, candidate: unknown): unknown {\n return typeof candidate === 'object'\n && candidate !== null\n && Object.keys(candidate).length === 1\n && '$eventKitBigInt' in candidate\n && typeof candidate.$eventKitBigInt === 'string'\n && /^(?:0|[1-9][0-9]*)$/u.test(candidate.$eventKitBigInt)\n ? BigInt(candidate.$eventKitBigInt)\n : candidate\n}\n\nasync function unlinkIfMissing(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') throw error\n }\n}\n\nfunction errorCode(error: unknown): unknown {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as { code?: unknown }).code\n : undefined\n}\n", "import {\n closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync,\n} from 'node:fs'\nimport PATH from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nexport class LegacyReceiverStoreError extends Error {\n override readonly name = 'LegacyReceiverStoreError'\n constructor(path: string) {\n super(`Receiver store requires explicit offline migration: ${path}`)\n }\n}\n\n/** Only the store's own directory is created/checked; unrelated parents are not chmodded. */\nexport function ensurePrivateDirectory(path: string): void {\n const created = mkdirSync(path, { recursive: true, mode: 0o700 })\n const info = lstatSync(path)\n if (!info.isDirectory() || info.isSymbolicLink() || (info.mode & 0o077) !== 0\n || (process.getuid !== undefined && info.uid !== process.getuid())) {\n throw new Error(`Receiver directory must be owned and private (0700): ${path}`)\n }\n if (created === undefined) return\n const existingParent = PATH.dirname(PATH.resolve(created))\n let cursor = PATH.resolve(path)\n for (;;) {\n syncPrivateDirectory(cursor)\n if (cursor === existingParent) break\n cursor = PATH.dirname(cursor)\n }\n}\n\nfunction syncPrivateDirectory(path: string): void {\n let descriptor: number | undefined\n try {\n descriptor = openSync(path, 'r')\n fsyncSync(descriptor)\n } catch (error) {\n const code = typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined\n if (!['EISDIR', 'EINVAL', 'ENOTSUP', 'EOPNOTSUPP'].includes(String(code))) throw error\n } finally { if (descriptor !== undefined) closeSync(descriptor) }\n}\n\nexport function checkPrivateStoreFile(path: string, create = false): void {\n let descriptor: number\n try {\n descriptor = openSync(path, (create ? constants.O_RDWR : constants.O_RDONLY) | constants.O_NOFOLLOW\n | (create ? constants.O_CREAT : 0), 0o600)\n } catch (error) {\n if (!create && typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') return\n throw error\n }\n try {\n const info = fstatSync(descriptor)\n if (!info.isFile() || (info.mode & 0o077) !== 0\n || (process.getuid !== undefined && info.uid !== process.getuid())) {\n throw new Error(`Receiver file must be owned and private (0600): ${path}`)\n }\n } finally { closeSync(descriptor) }\n}\n\nexport interface PrivateSqliteOptions {\n readonly format: string\n readonly path: string\n}\n\nfunction initializeDatabase(database: DatabaseSync, file: string, format: string): void {\n database.exec('PRAGMA busy_timeout=100')\n const tables = database.prepare(\"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\").all()\n if (tables.length > 0 && tables.every(row => row.name !== 'eventkit_store')) throw new LegacyReceiverStoreError(file)\n if (tables.some(row => row.name === 'eventkit_store')) {\n const columns = database.prepare('PRAGMA table_info(eventkit_store)').all()\n if (columns.every(row => row.name !== 'initialized')) throw new LegacyReceiverStoreError(file)\n const priorFormat = database.prepare('SELECT format FROM eventkit_store WHERE id=1').get()\n if (priorFormat?.format !== format) throw new Error('Receiver store format/namespace mismatch')\n }\n database.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;')\n database.exec('BEGIN IMMEDIATE')\n try {\n database.exec('CREATE TABLE IF NOT EXISTS eventkit_store (id INTEGER PRIMARY KEY CHECK(id=1), format TEXT NOT NULL, initialized INTEGER NOT NULL DEFAULT 0)')\n const prior = database.prepare('SELECT format FROM eventkit_store WHERE id=1').get()\n if (prior !== undefined && prior.format !== format) throw new Error('Receiver store format/namespace mismatch')\n database.prepare('INSERT OR IGNORE INTO eventkit_store(id,format) VALUES(1,?)').run(format)\n database.exec('COMMIT')\n } catch (error) {\n database.exec('ROLLBACK')\n throw error\n }\n}\n\n/** A synchronous commit boundary; no callback may await filesystem/network work. */\nexport function openPrivateSqlite(options: PrivateSqliteOptions) {\n const file = options.path === ':memory:' ? options.path : PATH.resolve(options.path)\n if (file !== ':memory:') {\n ensurePrivateDirectory(PATH.dirname(file))\n checkPrivateStoreFile(file, true)\n checkPrivateStoreFile(`${file}-wal`)\n checkPrivateStoreFile(`${file}-shm`)\n checkPrivateStoreFile(`${file}-journal`)\n }\n const database = new DatabaseSync(file)\n let closed = false\n try {\n initializeDatabase(database, file, options.format)\n if (file !== ':memory:') {\n checkPrivateStoreFile(file)\n checkPrivateStoreFile(`${file}-wal`)\n checkPrivateStoreFile(`${file}-shm`)\n syncPrivateDirectory(PATH.dirname(file))\n }\n } catch (error) {\n database.close()\n throw error\n }\n return {\n database,\n transaction<T>(work: () => T): T {\n if (closed) throw new Error('Receiver store is closed')\n database.exec('BEGIN IMMEDIATE')\n try {\n const result = work()\n if (result !== null && (typeof result === 'object' || typeof result === 'function') && 'then' in result) {\n throw new TypeError('Receiver transactions must be synchronous')\n }\n database.exec('COMMIT')\n return result\n } catch (error) {\n database.exec('ROLLBACK')\n throw error\n }\n },\n close(): void {\n if (closed) return\n database.close()\n closed = true\n },\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport {\n lstat, rename, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type { PendingWake, PublisherOutbox } from '@xyo-network/event-kit-actor'\nimport { WakeEnvelopeSchema, WakeEnvelopeZod } from '@xyo-network/event-kit-schemas'\n\nimport {\n ensureDurableDirectory,\n syncDirectory,\n writeDurableFile,\n} from './filesystemDurability.ts'\nimport { readJsonFileStrict } from './filesystemJson.ts'\nimport { checkPrivateStoreFile, ensurePrivateDirectory } from './privateSqlite.ts'\n\nexport interface FilesystemPublisherOutboxOptions {\n /** Absolute or relative path to the pending-wake JSON file. */\n readonly path: string\n}\n\n/**\n * Durable single-slot publisher outbox.\n *\n * The publisher emits at most one wake per pass, so one slot is enough: the\n * entry is written before the first delivery attempt and cleared only after the\n * cursor advances. A crash in between leaves it on disk, and the next pass\n * retries the same `wakeId`/`issuedAt` \u2014 and therefore the same `eventHash` \u2014\n * under a freshly minted JWT.\n */\nexport function createFilesystemPublisherOutbox(\n options: FilesystemPublisherOutboxOptions,\n): PublisherOutbox {\n const filePath = PATH.resolve(options.path)\n const directory = PATH.dirname(filePath)\n\n return {\n async clear(): Promise<void> {\n if (!await existingPrivateDirectory(directory)) return\n checkPrivateStoreFile(filePath)\n let removed = false\n try {\n await unlink(filePath)\n removed = true\n } catch (error) {\n if (!isNotFound(error)) throw error\n }\n // Sync even an already-absent slot so a retry after a failed sync can\n // finish the original deletion. A missing parent is empty on cold start.\n try {\n await syncDirectory(directory)\n } catch (error) {\n if (removed || !isNotFound(error)) throw error\n }\n },\n\n async load(): Promise<PendingWake | undefined> {\n if (!await existingPrivateDirectory(directory)) return undefined\n checkPrivateStoreFile(filePath)\n const raw = await readJsonFileStrict(filePath)\n if (raw === undefined) return undefined\n const pending = validatePendingWake(raw)\n // A previous save may have renamed successfully before directory sync\n // failed. Finish publishing that exact commitment before allowing retry.\n await syncDirectory(directory)\n return pending\n },\n\n async save(pending: PendingWake): Promise<void> {\n validatePendingWake(pending)\n await ensureDurableDirectory(directory, 0o700)\n ensurePrivateDirectory(directory)\n checkPrivateStoreFile(filePath)\n // Write-then-rename so a crash mid-write cannot leave a partial entry.\n // `rename` is sound here: one writer, and replacing the slot is intended.\n const tempPath = `${filePath}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`\n try {\n await writeDurableFile(tempPath, `${JSON.stringify(pending)}\\n`, 0o600)\n await rename(tempPath, filePath)\n } catch (error) {\n try {\n await unlink(tempPath)\n } catch {\n // An ignored temporary file cannot replace the retained commitment;\n // preserve the original write/publication failure if cleanup fails.\n }\n throw error\n }\n await syncDirectory(directory)\n },\n }\n}\n\n/** The durable envelope schema validates every field of the retained commitment. */\nfunction validatePendingWake(raw: unknown): PendingWake {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)\n || 'schema' in raw || 'deliveryMode' in raw) {\n throw new Error('Invalid pending wake record')\n }\n WakeEnvelopeZod.parse({\n ...raw, schema: WakeEnvelopeSchema, deliveryMode: 'durable',\n })\n // Parsing is validation only: retain the exact persisted commitment fields.\n return raw as PendingWake\n}\n\nfunction isNotFound(error: unknown): boolean {\n return typeof error === 'object'\n && error !== null\n && 'code' in error\n && (error as { code?: unknown }).code === 'ENOENT'\n}\n\nasync function existingPrivateDirectory(directory: string) {\n try {\n await lstat(directory)\n } catch (error) {\n if (isNotFound(error)) return false\n throw error\n }\n ensurePrivateDirectory(directory)\n return true\n}\n", "import { existsSync, readdirSync } from 'node:fs'\nimport PATH from 'node:path'\n\nimport type { AtomicWakeInbox } from '@xyo-network/event-kit-protocol'\n\nimport type { FilesystemWakeQueue } from './filesystemWakeQueue.ts'\nimport { filesystemReceiverAuthority } from './filesystemWakeQueue.ts'\nimport { ensurePrivateDirectory, LegacyReceiverStoreError } from './privateSqlite.ts'\n\nexport interface FilesystemWakeInboxOptions {\n readonly path: string\n /** Must be the coordinated queue created by createFilesystemWakeQueue. */\n readonly queue: FilesystemWakeQueue\n}\nexport interface FilesystemWakeInbox extends AtomicWakeInbox {\n pruneExpiredTokens(nowSeconds: number): Promise<number>\n}\n/** Both identity indexes, stable receipt and exact work share the queue's transaction. */\nexport function createFilesystemWakeInbox(options: FilesystemWakeInboxOptions): FilesystemWakeInbox {\n const root = PATH.resolve(options.path)\n if (['tokens', 'wakes'].some((name) => {\n const directory = PATH.join(root, name)\n return existsSync(directory) && readdirSync(directory).length > 0\n })) throw new LegacyReceiverStoreError(root)\n ensurePrivateDirectory(root)\n const authority = filesystemReceiverAuthority(options.queue)\n return {\n resolveAttempt: authority.inbox.resolveAttempt,\n async commitAuthorized(input) {\n const committed = await authority.inbox.commitAuthorized(input)\n if ('receipt' in committed) await options.queue.repairRow(authority.receiptQueueId(committed.receipt))\n return committed\n },\n pruneExpiredTokens: async nowSeconds => authority.pruneExpiredTokens(nowSeconds),\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport { existsSync, readdirSync } from 'node:fs'\nimport {\n link, open, readdir, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type { WakeQueue } from '@xyo-network/event-kit-protocol'\nimport { parseAdmittedWake, StaleWakeLeaseError } from '@xyo-network/event-kit-protocol'\n\nimport {\n ensureDurableDirectory, syncDirectory, writeDurableFile,\n} from './filesystemDurability.ts'\nimport {\n checkPrivateStoreFile, ensurePrivateDirectory, LegacyReceiverStoreError,\n} from './privateSqlite.ts'\nimport type { ReceiverAuthority, ReceiverQueueRow } from './receiverAuthority.ts'\nimport { openReceiverAuthority } from './receiverAuthority.ts'\n\nexport {\n ensureDurableDirectory, syncDirectory, writeDurableFile,\n}\n\nexport interface FilesystemWakeQueueOptions {\n /** Private directory; receiver.sqlite owns state, JSON files are projections. */\n readonly path: string\n}\nexport interface FilesystemWakeQueue extends WakeQueue {\n close(): void\n repairProjections(): Promise<void>\n repairRow(id: number): Promise<void>\n}\nconst authorities = new WeakMap<FilesystemWakeQueue, ReceiverAuthority>()\nexport function filesystemReceiverAuthority(queue: FilesystemWakeQueue): ReceiverAuthority {\n const authority = authorities.get(queue)\n if (authority === undefined) throw new TypeError('Filesystem inbox requires its coordinated filesystem receiver queue')\n return authority\n}\n\n/** Filesystem-facing receiver with one SQLite admission/lease/completion authority. */\nexport function createFilesystemWakeQueue(options: FilesystemWakeQueueOptions): FilesystemWakeQueue {\n const root = PATH.resolve(options.path)\n const file = PATH.join(root, 'receiver.sqlite')\n if (!existsSync(file) && ['pending', 'inflight', 'tmp'].some((name) => {\n const directory = PATH.join(root, name)\n return existsSync(directory) && readdirSync(directory).length > 0\n })) throw new LegacyReceiverStoreError(root)\n ensurePrivateDirectory(root)\n const pendingDir = PATH.join(root, 'pending')\n const inflightDir = PATH.join(root, 'inflight')\n const tempDir = PATH.join(root, 'tmp')\n for (const directory of [pendingDir, inflightDir, tempDir]) ensurePrivateDirectory(directory)\n const authority = openReceiverAuthority(file)\n\n async function publishProjection(path: string, body: string): Promise<void> {\n // Immutable committed bodies do not need another tempfile/fsync on each lease.\n // Projections may be regenerated from database authority after publication loss.\n if (existsSync(path)) {\n checkPrivateStoreFile(path)\n return\n }\n const temporary = PATH.join(tempDir, `${randomBytes(16).toString('hex')}.json`)\n await writeDurableFile(temporary, body, 0o600)\n try {\n try {\n await link(temporary, path)\n } catch (error) { if (!hasCode(error, 'EEXIST')) throw error }\n await syncDirectory(PATH.dirname(path))\n } finally { await unlinkIfMissing(temporary) }\n }\n async function validateProjection(row: ReceiverQueueRow): Promise<void> {\n if (row.body === null) throw new Error('Receiver work has no committed body')\n const path = PATH.join(pendingDir, `${row.id}.json`)\n checkPrivateStoreFile(path)\n let raw = await readJsonFile<unknown>(path)\n if (raw === undefined) {\n await publishProjection(path, row.body)\n checkPrivateStoreFile(path)\n raw = await readJsonFile<unknown>(path)\n }\n checkPrivateStoreFile(path)\n const projected = await parseAdmittedWake(raw)\n if (JSON.stringify(projected) !== row.body) throw new Error('Filesystem projection differs from committed receiver work')\n }\n async function repairRow(id: number): Promise<void> {\n const row = authority.currentRow(id)\n if (row === undefined) throw new Error('Receiver work record vanished')\n if (row.state === 'completed') {\n await unlinkIfMissing(PATH.join(pendingDir, `${id}.json`))\n } else {\n if (row.body === null) throw new Error('Active receiver work is corrupt')\n await publishProjection(PATH.join(pendingDir, `${id}.json`), row.body)\n if (row.state === 'inflight' && row.lease_token !== null) {\n await publishProjection(PATH.join(inflightDir, `${id}-${row.lease_token}.json`), row.body)\n }\n }\n await syncDirectory(pendingDir)\n }\n async function repairProjections(): Promise<void> {\n for (const row of authority.rows()) {\n if (row.body === null) throw new Error('Active receiver work is corrupt')\n await publishProjection(PATH.join(pendingDir, `${row.id}.json`), row.body)\n if (row.state === 'inflight' && row.lease_token !== null) {\n await publishProjection(PATH.join(inflightDir, `${row.id}-${row.lease_token}.json`), row.body)\n }\n }\n for (const name of await readdir(pendingDir)) {\n const match = /^(\\d+)\\.json$/u.exec(name)\n if (match !== null && authority.currentRow(Number(match[1]))?.state === 'completed') await unlinkIfMissing(PATH.join(pendingDir, name))\n }\n for (const name of await readdir(inflightDir)) {\n const match = /^(\\d+)-([0-9a-f]{32})\\.json$/u.exec(name)\n if (match !== null && authority.currentRow(Number(match[1]))?.lease_token !== match[2]) await unlinkIfMissing(PATH.join(inflightDir, name))\n }\n await syncDirectory(pendingDir)\n await syncDirectory(inflightDir)\n }\n const queue: FilesystemWakeQueue = {\n async append(wake) {\n const id = await authority.append(wake)\n await repairRow(id)\n },\n async claim() {\n const leased = await authority.claim(validateProjection)\n if (leased === undefined) return\n try {\n await repairRow(leased.id)\n if (authority.currentRow(leased.id)?.lease_token !== leased.token) throw new StaleWakeLeaseError()\n } catch (error) {\n try {\n await leased.release()\n } catch (releaseError) {\n throw new AggregateError([error, releaseError], 'Claim projection failed and its lease could not be released', { cause: releaseError })\n }\n throw error\n }\n return {\n wake: leased.wake,\n async ack() {\n await leased.ack()\n await unlinkIfMissing(PATH.join(inflightDir, `${leased.id}-${leased.token}.json`))\n await repairRow(leased.id)\n await syncDirectory(inflightDir)\n },\n async release() {\n await leased.release()\n await unlinkIfMissing(PATH.join(inflightDir, `${leased.id}-${leased.token}.json`))\n await repairRow(leased.id)\n await syncDirectory(inflightDir)\n },\n }\n },\n pendingCount: authority.queue.pendingCount,\n async recoverInflight(options) {\n const moved = await authority.queue.recoverInflight(options)\n await repairProjections()\n return moved\n },\n close: authority.close,\n repairProjections,\n repairRow,\n }\n authorities.set(queue, authority)\n return queue\n}\n\n/** Only open-time absence means an empty optional record. */\nexport async function readJsonFile<T>(path: string): Promise<T | undefined> {\n let handle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (hasCode(error, 'ENOENT')) return undefined\n throw error\n }\n try {\n if ((await handle.stat()).size > 65_536) throw new RangeError('Receiver JSON record exceeds its 64 KiB bound')\n return JSON.parse(await handle.readFile('utf8')) as T\n } finally { await handle.close() }\n}\nasync function unlinkIfMissing(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) { if (!hasCode(error, 'ENOENT')) throw error }\n}\nfunction hasCode(error: unknown, code: string): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && error.code === code\n}\n", "import { Buffer } from 'node:buffer'\nimport { createHash, randomBytes } from 'node:crypto'\n\nimport type {\n AdmittedWake, AtomicWakeInbox, LeasedWake, RecoverInflightOptions,\n WakeAdmissionAttempt, WakeAdmissionReceipt, WakeAttemptResolution, WakeQueue,\n} from '@xyo-network/event-kit-protocol'\nimport { parseAdmittedWake, StaleWakeLeaseError } from '@xyo-network/event-kit-protocol'\nimport {\n HashZod, NonnegativeJsonSafeIntegerZod, NormalizedAddressZod, WakeIdZod, WakeJwtAudienceZod, WakeJwtIdZod,\n} from '@xyo-network/event-kit-schemas'\n\nimport { openPrivateSqlite } from './privateSqlite.ts'\n\nexport interface ReceiverQueueRow {\n readonly body: string | null\n readonly id: number\n readonly lease_token: string | null\n readonly state: 'pending' | 'inflight' | 'completed'\n readonly terminal_operation: 'ack' | 'release' | null\n readonly terminal_token: string | null\n}\n\nexport function receiverIdentity(parts: readonly string[]): string {\n return createHash('sha256').update(JSON.stringify(parts)).digest('hex')\n}\n\nfunction validateAttempt(attempt: WakeAdmissionAttempt): void {\n WakeJwtAudienceZod.parse(attempt.audience)\n NormalizedAddressZod.parse(attempt.publisher)\n WakeIdZod.parse(attempt.wakeId)\n WakeJwtIdZod.parse(attempt.jwtId)\n HashZod.parse(attempt.eventHash)\n NonnegativeJsonSafeIntegerZod.parse(attempt.retainJwtUntil)\n}\n\nfunction boundedBody(wake: AdmittedWake): string {\n const body = JSON.stringify(wake)\n if (Buffer.byteLength(body, 'utf8') > 65_536) throw new RangeError('Receiver work exceeds its 64 KiB bound')\n return body\n}\n\nfunction sameValues(pairs: readonly (readonly [unknown, unknown])[]): boolean {\n return pairs.every(([actual, expected]) => actual === expected)\n}\n\nfunction validateQueueState(row: ReceiverQueueRow): void {\n if (!Number.isSafeInteger(row.id) || row.id < 1) throw new Error('Invalid persisted queue identity')\n if (row.state === 'completed') {\n if (row.body !== null || row.lease_token !== null || row.terminal_operation !== 'ack'\n || row.terminal_token === null || !/^[0-9a-f]{32}$/u.test(row.terminal_token)) throw new Error('Invalid persisted completion state')\n return\n }\n if (typeof row.body !== 'string') throw new TypeError('Active receiver work has no bounded body')\n if (row.state === 'pending' && row.lease_token === null) return\n if (row.state === 'inflight' && row.lease_token !== null && /^[0-9a-f]{32}$/u.test(row.lease_token)) return\n throw new Error('Invalid persisted lease state')\n}\n\n/** One durable authority for admission, queue transitions and completion. */\nexport function openReceiverAuthority(path: string) {\n const owner = openPrivateSqlite({ path, format: 'event-kit-receiver' })\n const database = owner.database\n const transaction = <T>(work: () => T): T => owner.transaction(work)\n const requiredTables = ['receiver_queue', 'receiver_wakes', 'receiver_tokens']\n try {\n transaction(() => {\n const existingTables = new Set(database.prepare(\"SELECT name FROM sqlite_master WHERE type='table'\").all().map(row => row.name))\n const initialized = database.prepare('SELECT initialized FROM eventkit_store WHERE id=1').get()?.initialized\n if ((initialized !== 0 && initialized !== 1)\n || (initialized === 1 && requiredTables.some(name => !existingTables.has(name)))\n || (initialized === 0 && requiredTables.some(name => existingTables.has(name)))) {\n throw new Error('Incomplete persisted receiver schema; refusing to recreate admission/completion history')\n }\n if (initialized === 1) return\n database.exec(`\n CREATE TABLE IF NOT EXISTS receiver_queue (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n body TEXT,\n state TEXT NOT NULL CHECK(state IN ('pending','inflight','completed')),\n lease_token TEXT,\n terminal_token TEXT,\n terminal_operation TEXT,\n CHECK ((state='inflight' AND lease_token IS NOT NULL) OR (state!='inflight' AND lease_token IS NULL))\n );\n CREATE INDEX IF NOT EXISTS receiver_pending ON receiver_queue(state,id);\n CREATE TABLE IF NOT EXISTS receiver_wakes (\n identity TEXT PRIMARY KEY,\n audience TEXT NOT NULL, publisher TEXT NOT NULL, wake_id TEXT NOT NULL,\n event_hash TEXT NOT NULL, receipt TEXT NOT NULL, authorization TEXT NOT NULL,\n queue_id INTEGER NOT NULL UNIQUE REFERENCES receiver_queue(id)\n );\n CREATE TABLE IF NOT EXISTS receiver_tokens (\n identity TEXT PRIMARY KEY, wake_identity TEXT NOT NULL REFERENCES receiver_wakes(identity),\n event_hash TEXT NOT NULL, wake_id TEXT NOT NULL, retain_until INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS receiver_token_expiry ON receiver_tokens(retain_until);\n `)\n database.prepare('UPDATE eventkit_store SET initialized=1 WHERE id=1').run()\n })\n } catch (error) {\n owner.close()\n throw error\n }\n const boundedRow = `id,state,lease_token,terminal_token,terminal_operation,\n CASE WHEN length(CAST(body AS BLOB)) <= 65536 THEN body ELSE NULL END AS body`\n const pending = database.prepare(`SELECT ${boundedRow} FROM receiver_queue WHERE state='pending' ORDER BY id LIMIT 1`)\n const getRow = database.prepare(`SELECT ${boundedRow} FROM receiver_queue WHERE id=?`)\n const insert = database.prepare(\"INSERT INTO receiver_queue(body,state) VALUES(?,'pending')\")\n const count = database.prepare(\"SELECT COUNT(*) AS total FROM receiver_queue WHERE state='pending'\")\n const wakeKey = (attempt: WakeAdmissionAttempt) => receiverIdentity([attempt.audience, attempt.publisher, attempt.wakeId])\n const tokenKey = (attempt: WakeAdmissionAttempt) => receiverIdentity([attempt.audience, attempt.publisher, attempt.jwtId])\n\n function validateAssociation(row: ReceiverQueueRow, wake?: AdmittedWake): void {\n validateQueueState(row)\n const record = database.prepare('SELECT * FROM receiver_wakes WHERE queue_id=?').get(row.id)\n if (record === undefined) return\n const receipt = JSON.parse(String(record.receipt)) as WakeAdmissionReceipt\n const receiptMatches = sameValues([\n [record.identity, receiverIdentity([String(record.audience), String(record.publisher), String(record.wake_id)])],\n [receipt.id, record.identity],\n [receipt.audience, record.audience],\n [receipt.publisher, record.publisher],\n [receipt.wakeId, record.wake_id],\n [receipt.eventHash, record.event_hash],\n ])\n const wakeMatches = wake === undefined || sameValues([\n [wake.audience, record.audience],\n [wake.publisher, record.publisher],\n [wake.wakeId, record.wake_id],\n [wake.eventHash, record.event_hash],\n ])\n if (!receiptMatches || !wakeMatches) throw new Error('Queued body does not match its admitted identity/receipt')\n }\n async function preparedWork(attempt: WakeAdmissionAttempt): Promise<{ readonly body: string | null; readonly id: number } | undefined> {\n const record = database.prepare('SELECT queue_id FROM receiver_wakes WHERE identity=?').get(wakeKey(attempt))\n if (record === undefined) return undefined\n const row = currentRow(Number(record.queue_id))\n if (row === undefined) throw new Error('Receiver receipt has no work/completion record')\n const wake = row.body === null ? undefined : await parseAdmittedWake(JSON.parse(row.body) as unknown)\n validateAssociation(row, wake)\n return { id: row.id, body: row.body }\n }\n class WorkChanged extends Error {}\n async function validatedTransaction<T>(attempt: WakeAdmissionAttempt, work: (prepared: Awaited<ReturnType<typeof preparedWork>>) => T): Promise<T> {\n for (let tries = 0; tries < 4; tries++) {\n const prepared = await preparedWork(attempt)\n try {\n return transaction(() => work(prepared))\n } catch (error) { if (!(error instanceof WorkChanged)) throw error }\n }\n throw new Error('Receiver work changed during validation; retry admission')\n }\n\n function resolve(attempt: WakeAdmissionAttempt, prepared: Awaited<ReturnType<typeof preparedWork>>): WakeAttemptResolution {\n const token = database.prepare('SELECT * FROM receiver_tokens WHERE identity=?').get(tokenKey(attempt))\n if (token !== undefined && (token.event_hash !== attempt.eventHash || token.wake_id !== attempt.wakeId)) return { kind: 'jwt-id-collision' }\n const record = database.prepare('SELECT * FROM receiver_wakes WHERE identity=?').get(wakeKey(attempt))\n if (record === undefined) {\n if (token !== undefined) throw new Error('Receiver token points to missing admitted work')\n return { kind: 'new' }\n }\n if (record.event_hash !== attempt.eventHash) return { kind: 'wake-id-collision' }\n const receipt = JSON.parse(String(record.receipt)) as WakeAdmissionReceipt\n if (!sameValues([\n [receipt.id, wakeKey(attempt)],\n [receipt.eventHash, attempt.eventHash],\n [receipt.publisher, attempt.publisher],\n [receipt.audience, attempt.audience],\n [receipt.wakeId, attempt.wakeId],\n ])) {\n throw new Error('Receiver receipt does not match its identity')\n }\n const row = currentRow(Number(record.queue_id))\n if (row === undefined) throw new Error('Receiver receipt has no pending/completed work record')\n validateAssociation(row)\n if (row.state !== 'completed' && (prepared?.id !== row.id || prepared.body !== row.body)) throw new WorkChanged()\n if (token !== undefined && (token.wake_identity !== record.identity || !Number.isSafeInteger(token.retain_until) || Number(token.retain_until) < 0)) {\n throw new Error('Persisted token does not match its admitted work')\n }\n database.prepare(`INSERT INTO receiver_tokens(identity,wake_identity,event_hash,wake_id,retain_until) VALUES(?,?,?,?,?)\n ON CONFLICT(identity) DO UPDATE SET retain_until=MAX(retain_until,excluded.retain_until)`)\n .run(tokenKey(attempt), wakeKey(attempt), attempt.eventHash, attempt.wakeId, attempt.retainJwtUntil)\n return { kind: 'duplicate', receipt }\n }\n\n const inbox: AtomicWakeInbox = {\n async resolveAttempt(attempt) {\n validateAttempt(attempt)\n return await validatedTransaction(attempt, prepared => resolve(attempt, prepared))\n },\n async commitAuthorized(input) {\n validateAttempt(input.attempt)\n const wake = await parseAdmittedWake(input.wake)\n const { attempt, grant } = input\n if (attempt.audience !== wake.audience || attempt.publisher !== wake.publisher || attempt.wakeId !== wake.wakeId\n || attempt.eventHash !== wake.eventHash || attempt.jwtId !== wake.jti\n || grant.grant.authorizationKind !== 'activated-subscription'\n || grant.grant.target !== wake.publisher || grant.grant.deploymentId !== wake.deploymentId\n || grant.grant.queueId !== wake.queueId || grant.grant.filterHash !== wake.event.filterHash\n || grant.grant.authorizationChainId !== wake.event.authorizationChainId || wake.event.deliveryMode !== 'durable') {\n throw new TypeError('Authorized admission does not match its exact wake/identity binding')\n }\n return await validatedTransaction(attempt, (prepared) => {\n const previous = resolve(attempt, prepared)\n if (previous.kind !== 'new') return previous\n const receipt: WakeAdmissionReceipt = Object.freeze({\n audience: attempt.audience,\n eventHash: attempt.eventHash,\n id: wakeKey(attempt),\n publisher: attempt.publisher,\n wakeId: attempt.wakeId,\n })\n const row = insert.run(boundedBody(wake))\n database.prepare('INSERT INTO receiver_wakes(identity,audience,publisher,wake_id,event_hash,receipt,authorization,queue_id) VALUES(?,?,?,?,?,?,?,?)')\n .run(\n wakeKey(attempt),\n attempt.audience,\n attempt.publisher,\n attempt.wakeId,\n attempt.eventHash,\n JSON.stringify(receipt),\n JSON.stringify(grant),\n row.lastInsertRowid,\n )\n database.prepare('INSERT INTO receiver_tokens(identity,wake_identity,event_hash,wake_id,retain_until) VALUES(?,?,?,?,?)')\n .run(tokenKey(attempt), wakeKey(attempt), attempt.eventHash, attempt.wakeId, attempt.retainJwtUntil)\n return { kind: 'enqueued' as const, receipt }\n })\n },\n }\n\n function currentRow(id: number): ReceiverQueueRow | undefined {\n return getRow.get(id) as unknown as ReceiverQueueRow | undefined\n }\n function rows(): readonly ReceiverQueueRow[] {\n return database.prepare(`SELECT ${boundedRow} FROM receiver_queue WHERE state!='completed' ORDER BY id`).all() as unknown as ReceiverQueueRow[]\n }\n function finish(id: number, token: string, operation: 'ack' | 'release'): void {\n transaction(() => {\n const row = currentRow(id)\n if (row?.terminal_token === token && row.terminal_operation === operation) return\n if (row?.state !== 'inflight' || row.lease_token !== token) throw new StaleWakeLeaseError()\n if (operation === 'ack') database.prepare(`UPDATE receiver_queue\n SET state='completed',body=NULL,lease_token=NULL,terminal_token=?,terminal_operation='ack'\n WHERE id=? AND lease_token=?`).run(token, id, token)\n else database.prepare(`UPDATE receiver_queue\n SET state='pending',lease_token=NULL,terminal_token=?,terminal_operation='release'\n WHERE id=? AND lease_token=?`).run(token, id, token)\n })\n }\n async function claim(validate?: (row: ReceiverQueueRow) => Promise<void>): Promise<(LeasedWake & { readonly id: number; readonly token: string }) | undefined> {\n for (;;) {\n const row = pending.get() as unknown as ReceiverQueueRow | undefined\n if (row === undefined) return undefined\n if (typeof row.body !== 'string') throw new TypeError('Pending receiver work has no body')\n const wake = await parseAdmittedWake(JSON.parse(row.body) as unknown)\n validateAssociation(row, wake)\n await validate?.(row)\n const token = randomBytes(16).toString('hex')\n const won = transaction(() => database.prepare(`UPDATE receiver_queue SET state='inflight',lease_token=?\n WHERE id=? AND state='pending' AND body=?`).run(token, row.id, row.body).changes === 1)\n if (!won) continue\n let completed: 'ack' | 'release' | undefined\n const complete = (operation: 'ack' | 'release') => {\n if (completed !== undefined) {\n if (completed !== operation) throw new StaleWakeLeaseError()\n return\n }\n finish(row.id, token, operation)\n completed = operation\n }\n return {\n id: row.id,\n token,\n wake,\n async ack() { complete('ack') },\n async release() { complete('release') },\n }\n }\n }\n const queue: WakeQueue = {\n async append(wake) {\n const parsed = await parseAdmittedWake(wake)\n transaction(() => insert.run(boundedBody(parsed)))\n },\n claim: () => claim(),\n pendingCount: async () => Number(count.get()?.total),\n async recoverInflight(options: RecoverInflightOptions) {\n if (options?.consumersStopped !== true) throw new TypeError('Recovery requires all consumers to be stopped')\n return transaction(() => Number(database.prepare(\"UPDATE receiver_queue SET state='pending',lease_token=NULL WHERE state='inflight'\").run().changes))\n },\n }\n return {\n queue,\n inbox,\n database,\n claim,\n currentRow,\n rows,\n async append(wake: AdmittedWake): Promise<number> {\n const parsed = await parseAdmittedWake(wake)\n return transaction(() => Number(insert.run(boundedBody(parsed)).lastInsertRowid))\n },\n receiptQueueId(receipt: WakeAdmissionReceipt): number {\n const row = database.prepare('SELECT queue_id FROM receiver_wakes WHERE identity=?').get(receipt.id)\n if (row === undefined) throw new Error('Committed receipt has no work/completion record')\n return Number(row.queue_id)\n },\n close: () => owner.close(),\n pruneExpiredTokens(nowSeconds: number): number {\n NonnegativeJsonSafeIntegerZod.parse(nowSeconds)\n return transaction(() => Number(database.prepare('DELETE FROM receiver_tokens WHERE retain_until<=?').run(nowSeconds).changes))\n },\n }\n}\n\nexport type ReceiverAuthority = ReturnType<typeof openReceiverAuthority>\n", "import PATH from 'node:path'\n\nimport type {\n EventKitReplayCheckpoint,\n EventKitReplayCheckpointStore,\n} from '@xyo-network/event-kit-statement-graph'\n\nimport { readJsonFileStrict, replaceJsonFile } from './filesystemJson.ts'\n\nexport interface FilesystemEventKitReplayCheckpointStoreOptions {\n /** JSON file atomically replaced after every committed replay block. */\n readonly path: string\n}\n\n/** Single-process durable replay checkpoint store with crash-atomic replacement. */\nexport function createFilesystemEventKitReplayCheckpointStore(\n options: FilesystemEventKitReplayCheckpointStoreOptions,\n): EventKitReplayCheckpointStore {\n const path = PATH.resolve(options.path)\n let tail: Promise<unknown> = Promise.resolve()\n\n return {\n async load(): Promise<unknown> {\n await tail\n return await readJsonFileStrict(path)\n },\n\n async save(checkpoint: EventKitReplayCheckpoint): Promise<void> {\n const previous = tail\n const save = (async () => {\n await previous\n await replaceJsonFile(path, checkpoint)\n })()\n tail = (async () => {\n try {\n await save\n } catch {\n return false\n }\n })()\n await save\n },\n }\n}\n", "import { createHash } from 'node:crypto'\nimport PATH from 'node:path'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type {\n FinalizedStatementPublicationIntent,\n FinalizedStatementPublicationJournal,\n FinalizedStatementPublicationRecord,\n} from '@xyo-network/event-kit-xl1'\n\nimport {\n publishJsonFile, readJsonFileStrict, stringifyJson,\n} from './filesystemJson.ts'\n\nconst PublicationPhases = [\n 'signed',\n 'content-written',\n 'content-verified',\n 'broadcast',\n 'included',\n 'finalized',\n] as const satisfies readonly FinalizedStatementPublicationRecord['phase'][]\n\nconst PublicationPhaseSet = new Set<FinalizedStatementPublicationRecord['phase']>(PublicationPhases)\n\nexport interface FilesystemFinalizedStatementPublicationJournalOptions {\n /** Directory receiving immutable intent-bound publication phase records. */\n readonly path: string\n}\n\nfunction sameStrings(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n\nfunction assertIntentShape(intent: FinalizedStatementPublicationIntent): void {\n if (typeof intent.operationId !== 'string' || intent.operationId.length === 0 || intent.operationId.length > 256) {\n throw new TypeError('publication operationId must be a nonempty string of at most 256 characters')\n }\n if (!/^[0-9a-f]{40}$/u.test(intent.source)) {\n throw new TypeError('publication source must be a canonical 20-byte lowercase hexadecimal address')\n }\n if (!/^[0-9a-f]{40}$/u.test(intent.chainId)) {\n throw new TypeError('publication chainId must be a canonical 20-byte lowercase hexadecimal chain id')\n }\n if ([...intent.eventHashes, ...intent.attachmentHashes].some(hash => !/^[0-9a-f]{64}$/u.test(hash))) {\n throw new TypeError('publication intent hashes must be 32-byte lowercase hexadecimal')\n }\n}\n\nfunction sameIntent(\n left: FinalizedStatementPublicationIntent,\n right: FinalizedStatementPublicationIntent,\n): boolean {\n return left.operationId === right.operationId\n && left.source === right.source\n && left.chainId === right.chainId\n && sameStrings(left.eventHashes, right.eventHashes)\n && sameStrings(left.attachmentHashes, right.attachmentHashes)\n}\n\nfunction intentFromRecord(record: FinalizedStatementPublicationRecord): FinalizedStatementPublicationIntent {\n return {\n attachmentHashes: record.attachmentHashes,\n chainId: record.chainId,\n eventHashes: record.eventHashes,\n operationId: record.operationId,\n source: record.source,\n }\n}\n\nfunction publicationDirectory(root: string, intent: FinalizedStatementPublicationIntent): string {\n const key = createHash('sha256')\n .update(stringifyJson({\n chainId: intent.chainId, operationId: intent.operationId, source: intent.source,\n }))\n .digest('hex')\n return PATH.join(root, key)\n}\n\nfunction asPublicationRecord(value: unknown, path: string): FinalizedStatementPublicationRecord {\n if (typeof value !== 'object' || value === null) throw new Error(`malformed publication journal record at ${path}`)\n const record = value as FinalizedStatementPublicationRecord\n if (!PublicationPhaseSet.has(record.phase)) throw new Error(`unknown publication phase at ${path}`)\n return record\n}\n\nfunction assertBoundRecord(\n record: FinalizedStatementPublicationRecord,\n intent: FinalizedStatementPublicationIntent,\n signed: FinalizedStatementPublicationRecord,\n): void {\n if (!sameIntent(intentFromRecord(record), intent)) throw new Error('publication journal intent collision')\n if (!isDeepStrictEqual(record.evidence, signed.evidence)) {\n throw new Error('publication journal evidence collision')\n }\n}\n\n/**\n * Crash-safe append-only publication journal.\n *\n * The first `signed` record atomically binds a source/operation id to exact\n * ordered event and attachment hashes plus one signed transaction. Repeated\n * identical phases are idempotent; every collision fails closed.\n */\nexport function createFilesystemFinalizedStatementPublicationJournal(\n options: FilesystemFinalizedStatementPublicationJournalOptions,\n): FinalizedStatementPublicationJournal {\n const root = PATH.resolve(options.path)\n\n return {\n async load(intent: FinalizedStatementPublicationIntent): Promise<FinalizedStatementPublicationRecord | undefined> {\n assertIntentShape(intent)\n const directory = publicationDirectory(root, intent)\n const intentPath = PATH.join(directory, 'intent.json')\n const rawSigned = await readJsonFileStrict(intentPath)\n if (rawSigned === undefined) return undefined\n const signed = asPublicationRecord(rawSigned, intentPath)\n if (signed.phase !== 'signed') throw new Error(`publication intent record is not signed at ${intentPath}`)\n assertBoundRecord(signed, intent, signed)\n\n let latest = signed\n for (const phase of PublicationPhases.slice(1)) {\n const path = PATH.join(directory, `${phase}.json`)\n const rawRecord = await readJsonFileStrict(path)\n if (rawRecord === undefined) continue\n const record = asPublicationRecord(rawRecord, path)\n if (record.phase !== phase) throw new Error(`publication phase/path mismatch at ${path}`)\n assertBoundRecord(record, intent, signed)\n latest = record\n }\n return latest\n },\n async save(record: FinalizedStatementPublicationRecord): Promise<void> {\n const intent = intentFromRecord(record)\n assertIntentShape(intent)\n if (!/^[0-9a-f]{64}$/u.test(record.evidence.transactionHash)) {\n throw new TypeError('publication transaction hash must be 32-byte lowercase hex')\n }\n if (!PublicationPhaseSet.has(record.phase)) throw new TypeError('unknown publication phase')\n const directory = publicationDirectory(root, intent)\n const intentPath = PATH.join(directory, 'intent.json')\n\n if (record.phase === 'signed') {\n if (await publishJsonFile(intentPath, record)) return\n const existing = asPublicationRecord(await readJsonFileStrict(intentPath), intentPath)\n if (!isDeepStrictEqual(existing, record)) {\n if (!sameIntent(intentFromRecord(existing), intent)) throw new Error('publication journal intent collision')\n throw new Error('publication journal evidence collision')\n }\n return\n }\n\n const rawSigned = await readJsonFileStrict(intentPath)\n if (rawSigned === undefined) throw new Error('publication journal must bind signed evidence first')\n const signed = asPublicationRecord(rawSigned, intentPath)\n if (signed.phase !== 'signed') throw new Error(`publication intent record is not signed at ${intentPath}`)\n assertBoundRecord(record, intent, signed)\n\n const path = PATH.join(directory, `${record.phase}.json`)\n if (await publishJsonFile(path, record)) return\n\n const existing = asPublicationRecord(await readJsonFileStrict(path), path)\n if (!isDeepStrictEqual(existing, record)) {\n throw new Error(`publication journal collision at ${record.operationId}/${record.phase}`)\n }\n },\n }\n}\n", "import { stat } from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport { publishJsonFile, readJsonFileStrict } from './filesystemJson.ts'\nimport type {\n HandshakeMutationIntent,\n HandshakeMutationIntentLookup,\n HandshakeMutationIntentStore,\n} from './handshakeMutationIntent.ts'\nimport {\n assertSameIntentBinding,\n parseHandshakeMutationIntent,\n parseHandshakeMutationIntentLookup,\n} from './handshakeMutationIntent.ts'\n\nexport interface FilesystemHandshakeMutationIntentStoreOptions {\n /** Directory containing immutable source/kind/operation intent records. */\n readonly path: string\n}\n\n/**\n * Atomic first-writer-wins persistence for exact handshake mutation artifacts.\n * Every record is private because publisher service intents contain HPKE private\n * keys; subscription records still contain ciphertext only, never plaintext.\n */\nexport function createFilesystemHandshakeMutationIntentStore(\n options: FilesystemHandshakeMutationIntentStoreOptions,\n): HandshakeMutationIntentStore {\n const root = PATH.resolve(options.path)\n\n function pathFor(rawLookup: HandshakeMutationIntentLookup): string {\n const lookup = parseHandshakeMutationIntentLookup(rawLookup)\n return PATH.join(\n root,\n lookup.chainId,\n lookup.publisher,\n lookup.source,\n lookup.kind,\n `${lookup.operationId}.json`,\n )\n }\n\n async function readIntent(\n lookup: HandshakeMutationIntentLookup,\n ): Promise<HandshakeMutationIntent | undefined> {\n const path = pathFor(lookup)\n const raw = await readJsonFileStrict(path)\n if (raw === undefined) return undefined\n const intent = await parseHandshakeMutationIntent(raw)\n const parsedLookup = parseHandshakeMutationIntentLookup(lookup)\n if (intent.chainId !== parsedLookup.chainId\n || intent.kind !== parsedLookup.kind\n || intent.operationId !== parsedLookup.operationId\n || intent.publisher !== parsedLookup.publisher\n || intent.source !== parsedLookup.source) {\n throw new Error('handshake mutation intent does not match its immutable path')\n }\n const metadata = await stat(path)\n if ((metadata.mode & 0o077) !== 0) throw new Error('handshake mutation intent permissions are too broad')\n return intent\n }\n\n return {\n get: async lookup => await readIntent(parseHandshakeMutationIntentLookup(lookup)),\n\n async getOrCreate(rawIntent) {\n const proposed = await parseHandshakeMutationIntent(rawIntent) as typeof rawIntent\n const path = pathFor(proposed)\n const created = await publishJsonFile(path, proposed, { directoryMode: 0o700, mode: 0o600 })\n const winner = await readIntent(proposed)\n if (winner === undefined) throw new Error('handshake mutation intent winner vanished')\n assertSameIntentBinding(winner, proposed)\n return Object.freeze({\n disposition: created ? 'created' as const : 'resumed' as const,\n intent: winner as typeof rawIntent,\n })\n },\n }\n}\n", "import {\n canonicalJsonBytes,\n handshakeObjectHash,\n} from '@xyo-network/event-kit-protocol'\nimport type {\n ChainId,\n Hash,\n NormalizedAddress,\n} from '@xyo-network/event-kit-schemas'\nimport {\n Base64Url32BytesZod,\n ChainIdZod,\n EncryptedWakeSubscriptionZod,\n EndpointChallengeResponseZod,\n EndpointChallengeZod,\n HandshakeIdZod,\n HashZod,\n NormalizedAddressZod,\n PublisherEncryptionKeyRevocationZod,\n PublisherEncryptionKeyZod,\n PublisherServiceRevocationZod,\n PublisherServiceZod,\n WakeGrantObjectZod,\n WakeGrantRevocationZod,\n WakeSubscriptionAcceptanceZod,\n WakeSubscriptionRevocationZod,\n} from '@xyo-network/event-kit-schemas'\nimport { z } from 'zod'\n\nexport const HandshakeMutationIntentKinds = [\n 'publisher-encryption-key-retire',\n 'publisher-service-publish',\n 'publisher-service-retire',\n 'publisher-service-rotate-key',\n 'publisher-subscription-accept',\n 'subscriber-grant-revoke',\n 'subscriber-subscription-revoke',\n 'subscriber-subscription-subscribe',\n] as const\n\nexport type HandshakeMutationIntentKind = typeof HandshakeMutationIntentKinds[number]\nexport type HandshakeMutationIntentDisposition = 'created' | 'resumed'\n\nconst HandshakeMutationIntentKindZod = z.enum(HandshakeMutationIntentKinds)\nconst HandshakeMutationOperationIdZod = z.union([HandshakeIdZod, HashZod])\nconst WakeSubscriptionPrivateKeyZod = z.strictObject({\n encryptionKey: HashZod,\n keyId: HandshakeIdZod,\n privateKey: Base64Url32BytesZod,\n})\n\nconst IntentBaseFields = {\n chainId: ChainIdZod,\n operationId: HandshakeMutationOperationIdZod,\n publisher: NormalizedAddressZod,\n requestFingerprint: HashZod,\n source: NormalizedAddressZod,\n version: z.literal(1),\n} as const\n\nconst PublisherServicePublishIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('publisher-service-publish'),\n operationId: HandshakeIdZod,\n encryptionKey: PublisherEncryptionKeyZod,\n privateKey: WakeSubscriptionPrivateKeyZod,\n service: PublisherServiceZod,\n})\n\nconst PublisherServiceRotateKeyIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('publisher-service-rotate-key'),\n operationId: HandshakeIdZod,\n encryptionKey: PublisherEncryptionKeyZod,\n privateKey: WakeSubscriptionPrivateKeyZod,\n selectedKey: HashZod,\n selectedService: HashZod,\n service: PublisherServiceZod,\n})\n\nconst SubscriberSubscriptionIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('subscriber-subscription-subscribe'),\n operationId: HandshakeIdZod,\n encryptionKey: PublisherEncryptionKeyZod,\n grant: WakeGrantObjectZod,\n selectedKey: HashZod,\n selectedService: HashZod,\n service: PublisherServiceZod,\n subscription: EncryptedWakeSubscriptionZod,\n})\n\nconst PublisherAcceptanceIntentZod = z.strictObject({\n ...IntentBaseFields,\n acceptance: WakeSubscriptionAcceptanceZod,\n challenge: EndpointChallengeZod,\n kind: z.literal('publisher-subscription-accept'),\n operationId: HashZod,\n response: EndpointChallengeResponseZod,\n})\n\nconst PublisherServiceRetireIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('publisher-service-retire'),\n operationId: HashZod,\n revocation: PublisherServiceRevocationZod,\n})\n\nconst PublisherEncryptionKeyRetireIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('publisher-encryption-key-retire'),\n operationId: HashZod,\n revocation: PublisherEncryptionKeyRevocationZod,\n})\n\nconst SubscriberGrantRevokeIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('subscriber-grant-revoke'),\n operationId: HashZod,\n revocation: WakeGrantRevocationZod,\n})\n\nconst SubscriberSubscriptionRevokeIntentZod = z.strictObject({\n ...IntentBaseFields,\n kind: z.literal('subscriber-subscription-revoke'),\n operationId: HashZod,\n revocation: WakeSubscriptionRevocationZod,\n})\n\nexport const HandshakeMutationIntentZod = z.discriminatedUnion('kind', [\n PublisherEncryptionKeyRetireIntentZod,\n PublisherServicePublishIntentZod,\n PublisherServiceRetireIntentZod,\n PublisherServiceRotateKeyIntentZod,\n PublisherAcceptanceIntentZod,\n SubscriberGrantRevokeIntentZod,\n SubscriberSubscriptionRevokeIntentZod,\n SubscriberSubscriptionIntentZod,\n])\n\nexport type HandshakeMutationIntent = z.infer<typeof HandshakeMutationIntentZod>\nexport type PublisherServicePublishIntent = z.infer<typeof PublisherServicePublishIntentZod>\nexport type PublisherServiceRotateKeyIntent = z.infer<typeof PublisherServiceRotateKeyIntentZod>\nexport type SubscriberSubscriptionIntent = z.infer<typeof SubscriberSubscriptionIntentZod>\nexport type PublisherAcceptanceIntent = z.infer<typeof PublisherAcceptanceIntentZod>\nexport type PublisherServiceRetireIntent = z.infer<typeof PublisherServiceRetireIntentZod>\nexport type PublisherEncryptionKeyRetireIntent = z.infer<typeof PublisherEncryptionKeyRetireIntentZod>\nexport type SubscriberGrantRevokeIntent = z.infer<typeof SubscriberGrantRevokeIntentZod>\nexport type SubscriberSubscriptionRevokeIntent = z.infer<typeof SubscriberSubscriptionRevokeIntentZod>\n\nexport interface HandshakeMutationIntentLookup {\n readonly chainId: ChainId\n readonly kind: HandshakeMutationIntentKind\n readonly operationId: string\n readonly publisher: NormalizedAddress\n readonly source: NormalizedAddress\n}\n\nexport interface HandshakeMutationIntentResolution<TIntent extends HandshakeMutationIntent = HandshakeMutationIntent> {\n readonly disposition: HandshakeMutationIntentDisposition\n readonly intent: TIntent\n}\n\n/** Durable, first-writer-wins boundary for exact logical handshake mutations. */\nexport interface HandshakeMutationIntentStore {\n get(lookup: HandshakeMutationIntentLookup): Promise<HandshakeMutationIntent | undefined>\n getOrCreate<TIntent extends HandshakeMutationIntent>(\n intent: TIntent,\n ): Promise<HandshakeMutationIntentResolution<TIntent>>\n}\n\n/** Stable error for reuse of one operation ID with different request or chain context. */\nexport class HandshakeMutationIntentConflictError extends Error {\n constructor(message = 'Handshake mutation operation ID is already bound to different intent') {\n super(message)\n this.name = 'HandshakeMutationIntentConflictError'\n }\n}\n\n/** SHA-256 over the canonical private/public caller-input representation. */\nexport async function handshakeMutationRequestFingerprint(value: unknown): Promise<Hash> {\n const canonical = canonicalJsonBytes(value)\n const digestInput = new Uint8Array(canonical.byteLength)\n digestInput.set(canonical)\n const digest = await globalThis.crypto.subtle.digest('SHA-256', digestInput)\n const hex = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')\n return HashZod.parse(hex)\n}\n\nexport function parseHandshakeMutationIntentLookup(value: HandshakeMutationIntentLookup): HandshakeMutationIntentLookup {\n return Object.freeze({\n chainId: ChainIdZod.parse(value.chainId),\n kind: HandshakeMutationIntentKindZod.parse(value.kind),\n operationId: HandshakeMutationOperationIdZod.parse(value.operationId),\n publisher: NormalizedAddressZod.parse(value.publisher),\n source: NormalizedAddressZod.parse(value.source),\n })\n}\n\n/** Strictly validates an intent and recomputes every canonical object binding. */\nexport async function parseHandshakeMutationIntent(value: unknown): Promise<HandshakeMutationIntent> {\n const intent = HandshakeMutationIntentZod.parse(value)\n await assertIntentIntegrity(intent)\n return Object.freeze(intent)\n}\n\n/** In-memory first-writer-wins adapter for focused tests and ephemeral composition. */\nexport function createMemoryHandshakeMutationIntentStore(): HandshakeMutationIntentStore {\n const intents = new Map<string, HandshakeMutationIntent>()\n return {\n async get(rawLookup) {\n const lookup = parseHandshakeMutationIntentLookup(rawLookup)\n return intents.get(intentLookupKey(lookup))\n },\n async getOrCreate(rawIntent) {\n const proposed = await parseHandshakeMutationIntent(rawIntent) as typeof rawIntent\n const key = intentLookupKey(proposed)\n const existing = intents.get(key)\n if (existing === undefined) {\n intents.set(key, proposed)\n return Object.freeze({ disposition: 'created' as const, intent: proposed })\n }\n assertSameIntentBinding(existing, proposed)\n return Object.freeze({ disposition: 'resumed' as const, intent: existing as typeof rawIntent })\n },\n }\n}\n\nexport function intentLookupKey(lookup: HandshakeMutationIntentLookup): string {\n const parsed = parseHandshakeMutationIntentLookup(lookup)\n return [parsed.chainId, parsed.publisher, parsed.source, parsed.kind, parsed.operationId].join('/')\n}\n\nexport function assertSameIntentBinding(left: HandshakeMutationIntent, right: HandshakeMutationIntent): void {\n const shared = left.version === right.version\n && left.chainId === right.chainId\n && left.kind === right.kind\n && left.operationId === right.operationId\n && left.publisher === right.publisher\n && left.source === right.source\n && left.requestFingerprint === right.requestFingerprint\n const bothRotate = left.kind === 'publisher-service-rotate-key'\n && right.kind === 'publisher-service-rotate-key'\n const bothSubscribe = left.kind === 'subscriber-subscription-subscribe'\n && right.kind === 'subscriber-subscription-subscribe'\n const selected = bothRotate || bothSubscribe\n ? left.selectedService === right.selectedService && left.selectedKey === right.selectedKey\n : !('selectedService' in left) && !('selectedService' in right)\n if (!shared || !selected) throw new HandshakeMutationIntentConflictError()\n}\n\nasync function assertIntentIntegrity(intent: HandshakeMutationIntent): Promise<void> {\n if (intent.kind.startsWith('publisher-') && intent.source !== intent.publisher) {\n throw new TypeError('Publisher mutation intent source must equal publisher')\n }\n if (intent.kind === 'publisher-service-publish' || intent.kind === 'publisher-service-rotate-key') {\n await assertPublisherServiceIntent(intent)\n return\n }\n if (intent.kind === 'subscriber-subscription-subscribe') {\n await assertSubscriberSubscriptionIntent(intent)\n return\n }\n if (intent.kind === 'publisher-subscription-accept') {\n await assertPublisherAcceptanceIntent(intent)\n return\n }\n await assertRevocationIntent(intent)\n}\n\nasync function assertPublisherServiceIntent(\n intent: PublisherServicePublishIntent | PublisherServiceRotateKeyIntent,\n): Promise<void> {\n const keyHash = await handshakeObjectHash(intent.encryptionKey)\n if (intent.privateKey.encryptionKey !== keyHash\n || intent.privateKey.keyId !== intent.encryptionKey.keyId\n || intent.service.preferredEncryptionKey !== keyHash\n || intent.service.encryptionKeys.length !== 1\n || intent.service.encryptionKeys[0] !== keyHash) {\n throw new TypeError('Publisher service mutation intent has inconsistent encryption-key artifacts')\n }\n if (intent.kind === 'publisher-service-publish') {\n if (intent.service.revision !== 1 || intent.service.supersedes !== undefined) {\n throw new TypeError('Publisher service root intent must contain a root service revision')\n }\n } else if (intent.service.supersedes !== intent.selectedService || intent.service.revision <= 1) {\n throw new TypeError('Publisher service rotation intent does not extend its selected service')\n }\n}\n\nasync function assertSubscriberSubscriptionIntent(intent: SubscriberSubscriptionIntent): Promise<void> {\n const [keyHash, serviceHash, grantHash] = await Promise.all([\n handshakeObjectHash(intent.encryptionKey),\n handshakeObjectHash(intent.service),\n handshakeObjectHash(intent.grant),\n ])\n if (keyHash !== intent.selectedKey\n || serviceHash !== intent.selectedService\n || intent.service.preferredEncryptionKey !== keyHash\n || !intent.service.encryptionKeys.includes(keyHash)\n || intent.grant.publisher !== intent.publisher\n || intent.subscription.publisher !== intent.publisher\n || intent.subscription.service !== serviceHash\n || intent.subscription.encryptionKey !== keyHash\n || intent.subscription.keyId !== intent.encryptionKey.keyId\n || intent.subscription.grant !== grantHash) {\n throw new TypeError('Subscriber subscription intent has inconsistent public artifacts')\n }\n}\n\nasync function assertPublisherAcceptanceIntent(intent: PublisherAcceptanceIntent): Promise<void> {\n const [challengeHash, responseHash] = await Promise.all([\n handshakeObjectHash(intent.challenge),\n handshakeObjectHash(intent.response),\n ])\n if (challengeHash !== intent.operationId\n || intent.challenge.publisher !== intent.publisher\n || intent.response.challenge !== challengeHash\n || intent.acceptance.challenge !== challengeHash\n || intent.acceptance.response !== responseHash\n || intent.acceptance.service !== intent.challenge.service\n || intent.acceptance.encryptionKey !== intent.challenge.encryptionKey\n || intent.acceptance.grant !== intent.challenge.grant\n || intent.acceptance.subscription !== intent.challenge.subscription) {\n throw new TypeError('Publisher acceptance intent has inconsistent public artifacts')\n }\n}\n\nasync function assertRevocationIntent(\n intent:\n | PublisherEncryptionKeyRetireIntent\n | PublisherServiceRetireIntent\n | SubscriberGrantRevokeIntent\n | SubscriberSubscriptionRevokeIntent,\n): Promise<void> {\n const target = intent.kind === 'publisher-encryption-key-retire'\n ? intent.revocation.key\n : intent.kind === 'publisher-service-retire'\n ? intent.revocation.service\n : intent.kind === 'subscriber-grant-revoke'\n ? intent.revocation.grant\n : intent.revocation.subscription\n if (target !== intent.operationId) {\n throw new TypeError('Handshake revocation intent has inconsistent target binding')\n }\n}\n", "import { stat } from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type {\n PublisherEncryptionKeyLookup,\n PublisherEncryptionKeyStore,\n WakeSubscriptionPrivateKey,\n} from '@xyo-network/event-kit-protocol'\nimport {\n Base64Url32BytesZod,\n HandshakeIdZod,\n HashZod,\n NormalizedAddressZod,\n} from '@xyo-network/event-kit-schemas'\n\nimport {\n publishJsonFile, readJsonFileStrict, stringifyJson,\n} from './filesystemJson.ts'\n\nexport interface FilesystemPublisherEncryptionKeyStoreOptions {\n /** Directory containing immutable publisher-scoped private-key records. */\n readonly path: string\n}\n\nexport interface PutPublisherEncryptionPrivateKeyInput {\n readonly key: WakeSubscriptionPrivateKey\n readonly publisher: string\n}\n\nexport interface FilesystemPublisherEncryptionKeyStore extends PublisherEncryptionKeyStore {\n putPrivateKey: (input: PutPublisherEncryptionPrivateKeyInput) => Promise<'duplicate' | 'stored'>\n}\n\ninterface PrivateKeyRecord extends WakeSubscriptionPrivateKey {\n readonly publisher: string\n}\n\n/** Immutable, exact-key filesystem custody for dedicated HPKE private keys. */\nexport function createFilesystemPublisherEncryptionKeyStore(\n options: FilesystemPublisherEncryptionKeyStoreOptions,\n): FilesystemPublisherEncryptionKeyStore {\n const root = PATH.resolve(options.path)\n\n function parseLookup(lookup: PublisherEncryptionKeyLookup): PublisherEncryptionKeyLookup {\n return {\n encryptionKey: HashZod.parse(lookup.encryptionKey),\n keyId: HandshakeIdZod.parse(lookup.keyId),\n publisher: NormalizedAddressZod.parse(lookup.publisher),\n }\n }\n\n function pathFor(lookup: PublisherEncryptionKeyLookup): string {\n return PATH.join(root, lookup.publisher, `${lookup.encryptionKey}-${lookup.keyId}.json`)\n }\n\n function keyIdPath(lookup: PublisherEncryptionKeyLookup): string {\n return PATH.join(root, lookup.publisher, 'key-ids', `${lookup.keyId}.json`)\n }\n\n async function readRecord(lookup: PublisherEncryptionKeyLookup): Promise<PrivateKeyRecord | undefined> {\n const path = pathFor(lookup)\n const raw = await readJsonFileStrict(path)\n if (raw === undefined) return undefined\n const parsed = parsePrivateKeyRecord(raw)\n if (\n parsed.publisher !== lookup.publisher\n || parsed.encryptionKey !== lookup.encryptionKey\n || parsed.keyId !== lookup.keyId\n ) throw new Error('publisher encryption-key record does not match its immutable path')\n const keyIdRecord = parseKeyIdRecord(await readJsonFileStrict(keyIdPath(lookup)))\n if (\n keyIdRecord.publisher !== lookup.publisher\n || keyIdRecord.encryptionKey !== lookup.encryptionKey\n || keyIdRecord.keyId !== lookup.keyId\n ) throw new Error('publisher encryption-key keyId index does not match its immutable path')\n const metadata = await stat(path)\n if ((metadata.mode & 0o077) !== 0) throw new Error('publisher encryption-key record permissions are too broad')\n return parsed\n }\n\n return {\n async getPrivateKey(rawLookup): Promise<WakeSubscriptionPrivateKey | undefined> {\n const lookup = parseLookup(rawLookup)\n const record = await readRecord(lookup)\n if (record === undefined) return undefined\n return Object.freeze({\n encryptionKey: record.encryptionKey,\n keyId: record.keyId,\n privateKey: record.privateKey,\n })\n },\n\n async putPrivateKey(input): Promise<'duplicate' | 'stored'> {\n const record = parsePrivateKeyRecord({ ...input.key, publisher: input.publisher })\n const lookup = parseLookup(record)\n const path = pathFor(lookup)\n const keyIdRecord = {\n encryptionKey: record.encryptionKey,\n keyId: record.keyId,\n publisher: record.publisher,\n }\n if (!await publishJsonFile(\n keyIdPath(lookup),\n keyIdRecord,\n { directoryMode: 0o700, mode: 0o600 },\n )) {\n const existingKeyId = parseKeyIdRecord(await readJsonFileStrict(keyIdPath(lookup)))\n if (stringifyJson(existingKeyId) !== stringifyJson(keyIdRecord)) {\n throw new Error(`publisher encryption-key keyId collision for ${record.keyId}`)\n }\n }\n if (await publishJsonFile(path, record, { directoryMode: 0o700, mode: 0o600 })) return 'stored'\n const existing = await readRecord(lookup)\n if (stringifyJson(existing) !== stringifyJson(record)) {\n throw new Error(`publisher encryption-key collision for ${record.encryptionKey}/${record.keyId}`)\n }\n return 'duplicate'\n },\n }\n}\n\nfunction parseKeyIdRecord(value: unknown): Omit<PrivateKeyRecord, 'privateKey'> {\n if (typeof value !== 'object' || value === null) throw new TypeError('invalid publisher encryption-key keyId record')\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).toSorted()\n if (keys.join('|') !== 'encryptionKey|keyId|publisher') {\n throw new TypeError('invalid publisher encryption-key keyId record shape')\n }\n return {\n encryptionKey: HashZod.parse(record.encryptionKey),\n keyId: HandshakeIdZod.parse(record.keyId),\n publisher: NormalizedAddressZod.parse(record.publisher),\n }\n}\n\nfunction parsePrivateKeyRecord(value: unknown): PrivateKeyRecord {\n if (typeof value !== 'object' || value === null) throw new TypeError('invalid publisher encryption-key record')\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).toSorted()\n if (keys.join('|') !== 'encryptionKey|keyId|privateKey|publisher') {\n throw new TypeError('invalid publisher encryption-key record shape')\n }\n return {\n encryptionKey: HashZod.parse(record.encryptionKey),\n keyId: HandshakeIdZod.parse(record.keyId),\n privateKey: Base64Url32BytesZod.parse(record.privateKey),\n publisher: NormalizedAddressZod.parse(record.publisher),\n }\n}\n", "import PATH from 'node:path'\n\nimport type {\n BeginPublisherEndpointChallengeAttemptResult,\n CompletePublisherEndpointChallengeResult,\n PublisherEndpointChallengeRecord,\n PublisherEndpointChallengeStore,\n} from '@xyo-network/event-kit-protocol'\nimport { endpointChallengeHash } from '@xyo-network/event-kit-protocol'\nimport {\n ChallengeNonceZod,\n EndpointChallengeZod,\n HashZod,\n} from '@xyo-network/event-kit-schemas'\n\nimport {\n publishJsonFile, readJsonFileStrict, stringifyJson,\n} from './filesystemJson.ts'\n\nexport interface FilesystemPublisherEndpointChallengeStoreOptions {\n /** Directory containing immutable issued/attempted/verified state records. */\n readonly path: string\n}\n\ntype ChallengeState = PublisherEndpointChallengeRecord['state']\n\n/**\n * Cross-process, one-attempt challenge state using exclusive immutable files.\n * Each transition is a new hard-link publication; no process overwrites a\n * competing winner and a crash cannot expose a partial state record.\n */\nexport function createFilesystemPublisherEndpointChallengeStore(\n options: FilesystemPublisherEndpointChallengeStoreOptions,\n): PublisherEndpointChallengeStore {\n const root = PATH.resolve(options.path)\n\n function statePath(challengeHash: string, state: ChallengeState): string {\n return PATH.join(root, challengeHash, `${state}.json`)\n }\n\n function noncePath(nonce: string): string {\n return PATH.join(root, 'nonces', `${nonce}.json`)\n }\n\n async function readState(challengeHash: string, state: ChallengeState): Promise<PublisherEndpointChallengeRecord | undefined> {\n const raw = await readJsonFileStrict(statePath(challengeHash, state))\n if (raw === undefined) return undefined\n const record = await parseChallengeRecord(raw, state)\n if (record.challengeHash !== challengeHash) throw new Error('challenge record does not match its immutable path')\n return record\n }\n\n async function current(challengeHash: string): Promise<PublisherEndpointChallengeRecord | undefined> {\n return await readState(challengeHash, 'verified')\n ?? await readState(challengeHash, 'attempted')\n ?? await readState(challengeHash, 'issued')\n }\n\n async function publish(record: PublisherEndpointChallengeRecord): Promise<boolean> {\n return await publishJsonFile(\n statePath(record.challengeHash, record.state),\n record,\n { directoryMode: 0o700, mode: 0o600 },\n )\n }\n\n return {\n async beginAttempt(input): Promise<BeginPublisherEndpointChallengeAttemptResult> {\n const challengeHash = HashZod.parse(input.challengeHash)\n requireTime(input.nowSeconds)\n const observed = await current(challengeHash)\n if (observed === undefined) return { kind: 'missing' }\n if (observed.state === 'verified') return { kind: 'verified', record: observed }\n if (observed.state === 'attempted') return { kind: 'already-attempted', record: observed }\n if (!isLive(observed, input.nowSeconds)) return { kind: 'expired', record: observed }\n\n const attempted: PublisherEndpointChallengeRecord = { ...observed, state: 'attempted' }\n if (await publish(attempted)) return { kind: 'started', record: attempted }\n const winner = await current(challengeHash)\n if (winner === undefined) throw new Error('challenge attempt winner vanished')\n return ({ kind: winner.state === 'verified' ? 'verified' : 'already-attempted', record: winner })\n },\n\n async completeVerified(input): Promise<CompletePublisherEndpointChallengeResult> {\n const challengeHash = HashZod.parse(input.challengeHash)\n const responseHash = HashZod.parse(input.responseHash)\n requireTime(input.nowSeconds)\n const observed = await current(challengeHash)\n if (observed === undefined) return { kind: 'missing' }\n if (observed.state === 'verified') {\n return ({ kind: observed.responseHash === responseHash ? 'duplicate' : 'collision', record: observed })\n }\n if (observed.state !== 'attempted') return { kind: 'not-attempted', record: observed }\n if (!isLive(observed, input.nowSeconds)) return { kind: 'expired', record: observed }\n\n const verified: PublisherEndpointChallengeRecord = {\n ...observed,\n responseHash,\n state: 'verified',\n }\n if (await publish(verified)) return { kind: 'verified', record: verified }\n const winner = await readState(challengeHash, 'verified')\n if (winner === undefined) throw new Error('verified challenge winner vanished')\n return ({ kind: winner.responseHash === responseHash ? 'duplicate' : 'collision', record: winner })\n },\n\n get: async (rawHash): Promise<PublisherEndpointChallengeRecord | undefined> => await current(HashZod.parse(rawHash)),\n\n async issue(input) {\n const challenge = EndpointChallengeZod.parse(input.challenge)\n const challengeHash = HashZod.parse(input.challengeHash)\n if (await endpointChallengeHash(challenge) !== challengeHash) return { kind: 'collision' }\n const nonceRecord = { challengeHash, nonce: challenge.nonce }\n if (!await publishJsonFile(\n noncePath(challenge.nonce),\n nonceRecord,\n { directoryMode: 0o700, mode: 0o600 },\n )) {\n const existingNonce = parseNonceRecord(await readJsonFileStrict(noncePath(challenge.nonce)))\n if (existingNonce.nonce !== challenge.nonce || existingNonce.challengeHash !== challengeHash) {\n return { kind: 'collision' }\n }\n }\n const issued: PublisherEndpointChallengeRecord = {\n challenge, challengeHash, state: 'issued',\n }\n if (await publish(issued)) return { kind: 'issued', record: issued }\n const existing = await current(challengeHash)\n if (existing === undefined) throw new Error('issued challenge winner vanished')\n return sameChallenge(existing, issued)\n ? { kind: 'duplicate', record: existing }\n : { kind: 'collision' }\n },\n }\n}\n\nfunction parseNonceRecord(value: unknown): { readonly challengeHash: string; readonly nonce: string } {\n if (typeof value !== 'object' || value === null) throw new TypeError('invalid endpoint-challenge nonce record')\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).toSorted()\n if (keys.join('|') !== 'challengeHash|nonce') throw new TypeError('invalid endpoint-challenge nonce record shape')\n return {\n challengeHash: HashZod.parse(record.challengeHash),\n nonce: ChallengeNonceZod.parse(record.nonce),\n }\n}\n\nasync function parseChallengeRecord(\n value: unknown,\n expectedState: ChallengeState,\n): Promise<PublisherEndpointChallengeRecord> {\n if (typeof value !== 'object' || value === null) throw new TypeError('invalid endpoint-challenge record')\n const record = value as Record<string, unknown>\n const state = record.state\n if (state !== expectedState) throw new Error('endpoint-challenge record state does not match its path')\n const challenge = EndpointChallengeZod.parse(record.challenge)\n const challengeHash = HashZod.parse(record.challengeHash)\n if (await endpointChallengeHash(challenge) !== challengeHash) throw new Error('endpoint-challenge record hash mismatch')\n if (expectedState === 'verified') {\n return {\n challenge, challengeHash, responseHash: HashZod.parse(record.responseHash), state: expectedState,\n }\n }\n if (record.responseHash !== undefined) throw new TypeError('unverified challenge record contains a response hash')\n return {\n challenge, challengeHash, state: expectedState,\n }\n}\n\nfunction sameChallenge(\n left: PublisherEndpointChallengeRecord,\n right: PublisherEndpointChallengeRecord,\n): boolean {\n return left.challengeHash === right.challengeHash\n && stringifyJson(left.challenge) === stringifyJson(right.challenge)\n}\n\nfunction isLive(record: PublisherEndpointChallengeRecord, nowSeconds: number): boolean {\n return record.challenge.issuedAt <= nowSeconds && nowSeconds < record.challenge.expiresAt\n}\n\nfunction requireTime(value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new TypeError('nowSeconds must be a nonnegative safe integer')\n}\n", "/* eslint-disable max-lines -- Phase 3 keeps the closely coupled public handshake facade in one auditable module. */\nimport type {\n CompletePublisherEndpointChallengeApiResult,\n HashedHandshakeObject,\n PublisherEncryptionKeyStore,\n PublisherEndpointChallengeStore,\n PublisherSubscriptionCandidate,\n PublisherSubscriptionValidationFailureReason,\n WakeSubscriptionPrivateKey,\n} from '@xyo-network/event-kit-protocol'\nimport {\n beginPublisherEndpointChallengeAttempt,\n canonicalJson,\n completePublisherEndpointChallenge,\n createEncryptedWakeSubscription,\n createPublisherEncryptionKeyRevocation,\n createPublisherService,\n createPublisherServiceRevocation,\n createWakeGrant,\n createWakeGrantRevocation,\n createWakeSubscriptionPlaintext,\n createWakeSubscriptionRevocation,\n endpointChallengeMatchesPublisherContext,\n generatePublisherEncryptionKey,\n handshakeObjectHash,\n issuePublisherEndpointChallenge,\n validateAndDecryptPublisherSubscription,\n withHandshakeObjectHash,\n} from '@xyo-network/event-kit-protocol'\nimport type {\n Base64Url32Bytes,\n BestEffortDeliveryPolicy,\n ChainId,\n EncryptedWakeSubscription,\n EndpointChallenge,\n EndpointChallengeResponse,\n HandshakeId,\n Hash,\n NormalizedAddress,\n PublisherEncryptionKey,\n PublisherService,\n WakeDeliveryMode,\n WakeGrantObject,\n WakeSource,\n WakeSubscriptionAcceptance,\n WakeSubscriptionPlaintext,\n} from '@xyo-network/event-kit-schemas'\nimport {\n ChainIdZod, HandshakeIdZod, HashZod, normalizeAddress, NormalizedAddressZod,\n} from '@xyo-network/event-kit-schemas'\nimport type {\n EventKitHandshakeReadModel,\n FinalizedEventKitReplayController,\n FinalizedSubscriptionTuple,\n PublisherAcceptanceCandidate,\n PublisherAcceptanceCandidateDiscovery,\n PublisherHandshakeView,\n PublisherServiceDiscovery,\n PublisherServiceDiscoveryFailure,\n PublisherSubscriptionView,\n ReplayBlockedState,\n SubscriberSubscriptionLookup,\n SubscriberSubscriptionLookupSuccess,\n} from '@xyo-network/event-kit-statement-graph'\nimport { createEventKitHandshakeReadModel } from '@xyo-network/event-kit-statement-graph'\nimport type {\n EventKitChainIdViewer, EventKitNetworkSession, HandshakePublicationResult, HandshakePublicationTransport, PublishPublisherEncryptionKeyRevocationOptions,\n} from '@xyo-network/event-kit-xl1'\nimport {\n assertEventKitNetworkSession,\n publishPublisherEncryptionKeyRevocation,\n publishPublisherService,\n publishPublisherServiceRevocation,\n publishWakeGrantRevocation,\n publishWakeSubscription,\n publishWakeSubscriptionAcceptance,\n publishWakeSubscriptionRevocation,\n} from '@xyo-network/event-kit-xl1'\n\nimport type {\n HandshakeMutationIntent,\n HandshakeMutationIntentDisposition,\n HandshakeMutationIntentKind,\n HandshakeMutationIntentStore,\n PublisherAcceptanceIntent,\n PublisherServicePublishIntent,\n PublisherServiceRotateKeyIntent,\n SubscriberSubscriptionIntent,\n} from './handshakeMutationIntent.ts'\nimport { HandshakeMutationIntentConflictError, handshakeMutationRequestFingerprint } from './handshakeMutationIntent.ts'\nexport type EventKitHandshakeClientErrorCode\n = 'candidate-ambiguous'\n | 'candidate-not-found'\n | 'challenge-context-invalid'\n | 'challenge-not-found'\n | 'challenge-rejected'\n | 'identity-mismatch'\n | 'key-mismatch'\n | 'key-custody-failed'\n | 'mutation-intent-conflict'\n | 'mutation-intent-unavailable'\n | 'projection-blocked'\n | 'projection-stale'\n | 'service-already-exists'\n | 'service-root-requires-fresh-id'\n | 'service-mismatch'\n | 'service-unavailable'\n | 'subscription-invalid'\n | 'subscription-not-found'\n/** Stable, machine-readable failure raised before an unsafe handshake mutation. */\nexport class EventKitHandshakeClientError extends Error {\n readonly code: EventKitHandshakeClientErrorCode\n constructor(code: EventKitHandshakeClientErrorCode, message: string) {\n super(message)\n this.name = 'EventKitHandshakeClientError'\n this.code = code\n }\n}\nexport interface SynchronizedEventKitHandshakeSnapshot {\n readonly blocked?: ReplayBlockedState\n readonly finalizedHead: number\n readonly indexedThrough: number | null\n readonly readModel: EventKitHandshakeReadModel\n}\n/**\n * A publisher-scoped finalized projection. Every call creates a fresh read\n * model after replay synchronization; callers never retain a stale viewer.\n */\nexport interface SynchronizedEventKitHandshakeReader {\n readonly chainId: ChainId\n readonly publisher: NormalizedAddress\n sync(): Promise<SynchronizedEventKitHandshakeSnapshot>\n}\nexport interface CreateSynchronizedEventKitHandshakeReaderOptions {\n /** Live chain identity port; checked both before and after every replay sync. */\n readonly chain: EventKitChainIdViewer\n readonly publisher: string\n readonly replay: FinalizedEventKitReplayController\n readonly session: EventKitNetworkSession\n}\n/** Compose finalized replay with the public Statement Graph handshake model. */\nexport function createSynchronizedEventKitHandshakeReader(options: CreateSynchronizedEventKitHandshakeReaderOptions): SynchronizedEventKitHandshakeReader {\n const publisher = NormalizedAddressZod.parse(options.publisher)\n const chainId = ChainIdZod.parse(options.session.chainId)\n function assertIdentity(): void {\n const checkpoint = options.replay.snapshot()\n if (checkpoint.chainId !== chainId\n || checkpoint.network !== options.session.network\n || checkpoint.publisher !== publisher) {\n throw new EventKitHandshakeClientError('identity-mismatch', 'Finalized replay identity does not match the pinned Event Kit network and publisher')\n }\n }\n return Object.freeze({\n chainId,\n publisher,\n async sync(): Promise<SynchronizedEventKitHandshakeSnapshot> {\n await assertEventKitNetworkSession(options.session, options.chain)\n assertIdentity()\n const status = await options.replay.sync()\n await assertEventKitNetworkSession(options.session, options.chain)\n assertIdentity()\n return Object.freeze({\n ...(status.blocked === undefined ? {} : { blocked: status.blocked }),\n finalizedHead: status.finalizedHead,\n indexedThrough: status.indexedThrough,\n readModel: createEventKitHandshakeReadModel({\n body: hash => options.replay.body(hash),\n viewer: options.replay.viewer(),\n }),\n })\n },\n })\n}\nexport interface EventKitHandshakePublicationPort {\n readonly chainId: ChainId\n publishPublisherEncryptionKeyRevocation(input: Pick<PublishPublisherEncryptionKeyRevocationOptions, 'revocation'> & {\n readonly operationId: string\n }): Promise<HandshakePublicationResult>\n publishPublisherService(input: {\n readonly encryptionKeys: readonly PublisherEncryptionKey[]\n readonly operationId: string\n readonly service: PublisherService\n }): Promise<HandshakePublicationResult>\n publishPublisherServiceRevocation(input: {\n readonly operationId: string\n readonly revocation: ReturnType<typeof createPublisherServiceRevocation>\n }): Promise<HandshakePublicationResult>\n publishWakeGrantRevocation(input: {\n readonly operationId: string\n readonly publisher: NormalizedAddress\n readonly revocation: ReturnType<typeof createWakeGrantRevocation>\n }): Promise<HandshakePublicationResult>\n publishWakeSubscription(input: {\n readonly encryptionKey: PublisherEncryptionKey\n readonly grant: WakeGrantObject\n readonly operationId: string\n readonly service: PublisherService\n readonly subscription: EncryptedWakeSubscription\n }): Promise<HandshakePublicationResult>\n publishWakeSubscriptionAcceptance(input: {\n readonly acceptance: WakeSubscriptionAcceptance\n readonly challenge: EndpointChallenge\n readonly operationId: string\n readonly response: EndpointChallengeResponse\n }): Promise<HandshakePublicationResult>\n publishWakeSubscriptionRevocation(input: {\n readonly operationId: string\n readonly publisher: NormalizedAddress\n readonly revocation: ReturnType<typeof createWakeSubscriptionRevocation>\n }): Promise<HandshakePublicationResult>\n /** Canonical address that will sign the next publication. */\n source(): Promise<NormalizedAddress>\n}\n/** Bind all XL1 writes to one chain-pinned, Mainnet-interlocked transport. */\nexport function createEventKitHandshakePublicationPort(transport: HandshakePublicationTransport): EventKitHandshakePublicationPort {\n const chainId = ChainIdZod.parse(transport.session.chainId)\n const port: EventKitHandshakePublicationPort = {\n chainId,\n publishPublisherEncryptionKeyRevocation: async input => await publishPublisherEncryptionKeyRevocation({ ...transport, ...input }),\n publishPublisherService: async input => await publishPublisherService({ ...transport, ...input }),\n publishPublisherServiceRevocation: async input => await publishPublisherServiceRevocation({ ...transport, ...input }),\n publishWakeGrantRevocation: async input => await publishWakeGrantRevocation({ ...transport, ...input }),\n publishWakeSubscription: async input => await publishWakeSubscription({ ...transport, ...input }),\n publishWakeSubscriptionAcceptance: async input => await publishWakeSubscriptionAcceptance({ ...transport, ...input }),\n publishWakeSubscriptionRevocation: async input => await publishWakeSubscriptionRevocation({ ...transport, ...input }),\n async source(): Promise<NormalizedAddress> {\n const raw = String(await transport.signer.address())\n const normalized = NormalizedAddressZod.parse(normalizeAddress(raw))\n if (raw !== normalized) {\n throw new EventKitHandshakeClientError('identity-mismatch', 'XL1 publication signer address is not canonical lowercase hexadecimal without 0x')\n }\n return normalized\n },\n }\n return Object.freeze(port)\n}\nexport interface PublisherEncryptionKeyCustody extends PublisherEncryptionKeyStore {\n /** Must durably retain the exact private key before resolving. */\n putPrivateKey(input: {\n readonly key: WakeSubscriptionPrivateKey\n readonly publisher: string\n }): Promise<'duplicate' | 'stored'>\n}\nexport interface PublishPublisherServiceInput {\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly deliveryMode: WakeDeliveryMode\n readonly expiresAtBlock?: number\n readonly maxPositionsPerWake: number\n readonly maxSubscriptionLifetimeBlocks: number\n readonly operationId: HandshakeId\n readonly sources: readonly WakeSource[]\n readonly validFromBlock?: number\n}\nexport interface RotatePublisherEncryptionKeyInput {\n readonly expiresAtBlock?: number\n readonly keyExpiresAtBlock?: number\n readonly maxPositionsPerWake?: number\n readonly maxSubscriptionLifetimeBlocks?: number\n readonly operationId: HandshakeId\n /** Exact currently selected service object hash expected by the operator. */\n readonly service: string\n readonly validFromBlock?: number\n}\nexport interface PublisherServicePublicationResult {\n readonly encryptionKey: HashedHandshakeObject<PublisherEncryptionKey>\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly keyCustody: 'duplicate' | 'stored'\n readonly operationId: HandshakeId\n readonly publication: HandshakePublicationResult\n readonly service: HashedHandshakeObject<PublisherService>\n}\nexport interface PublisherServiceRetirementResult {\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly operationId: Hash\n readonly publication: HandshakePublicationResult\n readonly revocation: HashedHandshakeObject<ReturnType<typeof createPublisherServiceRevocation>>\n readonly service: Hash\n}\nexport interface PublisherKeyRetirementResult {\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly key: Hash\n readonly operationId: Hash\n readonly publication: HandshakePublicationResult\n readonly revocation: HashedHandshakeObject<ReturnType<typeof createPublisherEncryptionKeyRevocation>>\n}\nexport interface PublisherSubscriptionSelector {\n readonly subscriber: string\n /** Optional exact object hash; when omitted, exactly one candidate must exist for the stable identity. */\n readonly subscription?: string\n readonly subscriptionId?: string\n}\nexport interface IssuePublisherChallengeInput extends PublisherSubscriptionSelector {\n readonly issuedAt: number\n readonly lifetimeSeconds?: number\n}\nexport interface IssuedPublisherChallenge {\n readonly challenge: EndpointChallenge\n readonly challengeHash: Hash\n readonly disposition: 'duplicate' | 'issued'\n readonly subscriber: NormalizedAddress\n readonly subscription: Hash\n}\n/** Decrypted routing data. It is required for the outbound call and MUST NOT be logged as evidence. */\nexport interface PublisherChallengeDeliveryTarget {\n readonly audience: string\n readonly endpoint: string\n}\nexport type BeginPublisherChallengeResult = {\n readonly challenge: EndpointChallenge\n readonly challengeHash: Hash\n readonly kind: 'started'\n readonly subscriber: NormalizedAddress\n readonly subscription: Hash\n readonly target: PublisherChallengeDeliveryTarget\n} | {\n readonly kind: 'already-attempted' | 'expired' | 'missing' | 'verified'\n}\nexport interface CompletePublisherChallengeInput {\n readonly challengeHash: string\n /** Publisher-local Unix clock, sampled inside the client at the proof-decision boundary. */\n readonly nowSeconds: () => number\n readonly response: EndpointChallengeResponse\n /** Expected Claim source, independently supplied by the caller. */\n readonly subscriber: string\n /** Expected encrypted-subscription object hash, independently supplied by the caller. */\n readonly subscription: string\n}\nexport type PublisherAcceptanceReconciliation = {\n readonly finalizedHead: number\n readonly indexedThrough: number\n readonly lifecycle: PublisherSubscriptionView\n readonly status: 'active' | 'not-active'\n} | {\n readonly finalizedHead: number\n readonly indexedThrough: number\n readonly status: 'not-found'\n} | {\n readonly finalizedHead?: number\n readonly indexedThrough?: number | null\n readonly reason: 'ambiguous-lifecycle' | 'projection-blocked' | 'projection-stale' | 'publication-not-indexed' | 'synchronization-failed' | PublisherServiceDiscoveryFailure['reason']\n readonly status: 'unavailable'\n}\n/** A finalized acceptance publication plus its best-effort post-finality lifecycle reconciliation. */\nexport interface PublisherAcceptancePublicationResult {\n readonly acceptance: HashedHandshakeObject<WakeSubscriptionAcceptance>\n readonly challenge: Hash\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly operationId: Hash\n readonly publication: HandshakePublicationResult\n readonly reconciliation: PublisherAcceptanceReconciliation\n readonly response: Hash\n readonly subscriber: NormalizedAddress\n readonly subscription: Hash\n}\nexport interface PublisherHandshakeClient {\n acceptanceCandidates(selector?: Partial<PublisherSubscriptionSelector>): Promise<PublisherAcceptanceCandidateDiscovery>\n beginChallenge(input: {\n readonly challengeHash: string\n readonly nowSeconds: () => number\n }): Promise<BeginPublisherChallengeResult>\n completeChallengeAndAccept(input: CompletePublisherChallengeInput): Promise<PublisherAcceptancePublicationResult>\n issueChallenge(input: IssuePublisherChallengeInput): Promise<IssuedPublisherChallenge>\n key(): Promise<PublisherServiceDiscovery>\n publishService(input: PublishPublisherServiceInput): Promise<PublisherServicePublicationResult>\n retireEncryptionKey(key: string): Promise<PublisherKeyRetirementResult>\n retireService(service: string): Promise<PublisherServiceRetirementResult>\n rotateEncryptionKey(input: RotatePublisherEncryptionKeyInput): Promise<PublisherServicePublicationResult>\n service(): Promise<PublisherServiceDiscovery>\n subscriptions(): Promise<PublisherHandshakeView>\n}\nexport interface CreatePublisherHandshakeClientOptions {\n readonly challenges: PublisherEndpointChallengeStore\n readonly intents: HandshakeMutationIntentStore\n readonly keys: PublisherEncryptionKeyCustody\n readonly publication: EventKitHandshakePublicationPort\n readonly reader: SynchronizedEventKitHandshakeReader\n readonly serviceId?: string\n}\ninterface ResolvedPublisherCandidate {\n readonly candidate: PublisherAcceptanceCandidate\n readonly validated: Extract<Awaited<ReturnType<typeof validateAndDecryptPublisherSubscription>>, {\n readonly ok: true\n }>\n}\nfunction nextBlock(head: number): number {\n if (!Number.isSafeInteger(head) || head < 0 || head === Number.MAX_SAFE_INTEGER) {\n throw new RangeError('finalized head cannot advance to a JSON-safe block number')\n }\n return head + 1\n}\nfunction samplePublisherClock(nowSeconds: () => number): number {\n const sampled = nowSeconds()\n if (!Number.isSafeInteger(sampled) || sampled < 0) {\n throw new EventKitHandshakeClientError('challenge-rejected', 'Publisher clock must return a nonnegative JSON-safe Unix second')\n }\n return sampled\n}\nfunction readySnapshot(snapshot: SynchronizedEventKitHandshakeSnapshot): SynchronizedEventKitHandshakeSnapshot {\n if (snapshot.blocked !== undefined) {\n throw new EventKitHandshakeClientError('projection-blocked', 'Finalized handshake replay is blocked')\n }\n if (snapshot.indexedThrough !== snapshot.finalizedHead) {\n throw new EventKitHandshakeClientError('projection-stale', 'Finalized handshake replay is not caught up')\n }\n return snapshot\n}\nfunction serviceQuery(reader: SynchronizedEventKitHandshakeReader, snapshot: SynchronizedEventKitHandshakeSnapshot, serviceId?: HandshakeId) {\n return {\n chainId: reader.chainId,\n finalizedHead: snapshot.finalizedHead,\n publisher: reader.publisher,\n ...(serviceId === undefined ? {} : { serviceId }),\n }\n}\nfunction requireService(discovery: PublisherServiceDiscovery): Extract<PublisherServiceDiscovery, {\n readonly ok: true\n}> {\n if (!discovery.ok) {\n throw new EventKitHandshakeClientError('service-unavailable', `Publisher service is unavailable: ${discovery.reason}`)\n }\n return discovery\n}\nfunction requireExpectedService(discovery: Extract<PublisherServiceDiscovery, {\n readonly ok: true\n}>, expected: string): Hash {\n const expectedHash = HashZod.parse(expected)\n if (discovery.service.objectHash !== expectedHash) {\n throw new EventKitHandshakeClientError('service-mismatch', 'Currently selected publisher service does not match the expected object hash')\n }\n return expectedHash\n}\nfunction assertPublicationIdentity(publication: EventKitHandshakePublicationPort, reader: SynchronizedEventKitHandshakeReader): void {\n if (publication.chainId !== reader.chainId) {\n throw new EventKitHandshakeClientError('identity-mismatch', 'Publication transport chain ID does not match the synchronized handshake reader')\n }\n}\nasync function assertPublicationSource(publication: EventKitHandshakePublicationPort, expected: NormalizedAddress): Promise<void> {\n if (await publication.source() !== expected) {\n throw new EventKitHandshakeClientError('identity-mismatch', 'Publication signer does not match the required handshake Claim source')\n }\n}\ntype IntentOfKind<TKind extends HandshakeMutationIntentKind> = Extract<HandshakeMutationIntent, {\n readonly kind: TKind\n}>\nfunction intentLookup<TKind extends HandshakeMutationIntentKind>(reader: SynchronizedEventKitHandshakeReader, kind: TKind, operationId: string, source: NormalizedAddress) {\n return {\n chainId: reader.chainId,\n kind,\n operationId,\n publisher: reader.publisher,\n source,\n }\n}\nfunction mutationIntentError(error: unknown): EventKitHandshakeClientError {\n return error instanceof HandshakeMutationIntentConflictError\n ? new EventKitHandshakeClientError('mutation-intent-conflict', error.message)\n : new EventKitHandshakeClientError('mutation-intent-unavailable', 'Handshake mutation intent storage is unavailable or invalid')\n}\nasync function loadMutationIntent<TKind extends HandshakeMutationIntentKind>(\n store: HandshakeMutationIntentStore,\n reader: SynchronizedEventKitHandshakeReader,\n kind: TKind,\n operationId: string,\n source: NormalizedAddress,\n requestFingerprint: Hash,\n): Promise<IntentOfKind<TKind> | undefined> {\n try {\n const existing = await store.get(intentLookup(reader, kind, operationId, source))\n if (existing === undefined)\n return undefined\n if (existing.kind !== kind || existing.requestFingerprint !== requestFingerprint) {\n throw new HandshakeMutationIntentConflictError()\n }\n return existing as IntentOfKind<TKind>\n } catch (error) {\n throw mutationIntentError(error)\n }\n}\nasync function persistMutationIntent<TIntent extends HandshakeMutationIntent>(store: HandshakeMutationIntentStore, intent: TIntent): Promise<{\n readonly disposition: HandshakeMutationIntentDisposition\n readonly intent: TIntent\n}> {\n try {\n return await store.getOrCreate(intent)\n } catch (error) {\n throw mutationIntentError(error)\n }\n}\nasync function publisherServiceRequestFingerprint(input: PublishPublisherServiceInput): Promise<Hash> {\n return await handshakeMutationRequestFingerprint({\n deliveryMode: input.deliveryMode,\n bestEffort: input.bestEffort ?? null,\n expiresAtBlock: input.expiresAtBlock ?? null,\n maxPositionsPerWake: input.maxPositionsPerWake,\n sources: input.sources,\n maxSubscriptionLifetimeBlocks: input.maxSubscriptionLifetimeBlocks,\n validFromBlock: input.validFromBlock ?? null,\n })\n}\nasync function publisherRotationRequestFingerprint(input: RotatePublisherEncryptionKeyInput): Promise<Hash> {\n return await handshakeMutationRequestFingerprint({\n expiresAtBlock: input.expiresAtBlock ?? null,\n keyExpiresAtBlock: input.keyExpiresAtBlock ?? null,\n maxPositionsPerWake: input.maxPositionsPerWake ?? null,\n maxSubscriptionLifetimeBlocks: input.maxSubscriptionLifetimeBlocks ?? null,\n service: HashZod.parse(input.service),\n validFromBlock: input.validFromBlock ?? null,\n })\n}\nasync function subscriberSubscriptionRequestFingerprint(input: SubscribeToPublisherInput): Promise<Hash> {\n return await handshakeMutationRequestFingerprint({\n deliveryMode: input.deliveryMode,\n bestEffort: input.bestEffort ?? null,\n audience: input.audience,\n challengeSecret: input.challengeSecret,\n deploymentId: input.deploymentId,\n endpoint: input.endpoint,\n expiresAtBlock: input.expiresAtBlock,\n grantId: input.grantId ?? null,\n source: input.source,\n fromPosition: input.fromPosition,\n maxPositionsPerWake: input.maxPositionsPerWake ?? null,\n queueId: input.queueId ?? null,\n revision: input.revision ?? null,\n subscriptionId: input.subscriptionId ?? null,\n supersedes: input.supersedes ?? null,\n })\n}\nasync function exactMutationRequestFingerprint(value: unknown): Promise<Hash> {\n return await handshakeMutationRequestFingerprint(value)\n}\nfunction protocolCandidate(reader: SynchronizedEventKitHandshakeReader, discovery: Extract<PublisherAcceptanceCandidateDiscovery, {\n readonly ok: true\n}>, candidate: PublisherAcceptanceCandidate, keys: PublisherEncryptionKeyStore): PublisherSubscriptionCandidate {\n return {\n chainId: reader.chainId,\n finalizedHead: discovery.finalizedHead,\n grant: {\n body: candidate.tuple.grant.body,\n objectHash: HashZod.parse(candidate.tuple.grant.objectHash),\n },\n key: {\n body: candidate.key.body,\n objectHash: HashZod.parse(candidate.key.objectHash),\n },\n keys,\n publisher: reader.publisher,\n service: {\n body: candidate.tuple.service.body,\n objectHash: HashZod.parse(candidate.tuple.service.objectHash),\n },\n subscriber: NormalizedAddressZod.parse(candidate.subscriber),\n subscription: {\n body: candidate.tuple.subscription.body,\n objectHash: HashZod.parse(candidate.tuple.subscription.objectHash),\n },\n tupleBlock: candidate.tuple.tupleEvent.block,\n tupleObjectHashes: [\n HashZod.parse(candidate.tuple.service.objectHash),\n HashZod.parse(candidate.tuple.grant.objectHash),\n HashZod.parse(candidate.tuple.subscription.objectHash),\n ],\n tupleSubject: reader.publisher,\n }\n}\nfunction validationError(reason: PublisherSubscriptionValidationFailureReason): EventKitHandshakeClientError {\n return new EventKitHandshakeClientError('subscription-invalid', `Publisher subscription candidate failed validation: ${reason}`)\n}\nfunction challengeError(result: CompletePublisherEndpointChallengeApiResult): EventKitHandshakeClientError {\n const reason = result.ok ? 'unknown' : result.reason\n return new EventKitHandshakeClientError('challenge-rejected', `Endpoint challenge was rejected: ${reason}`)\n}\n/** Publisher-side handshake orchestration shared by automation, CLI, and the resident runtime. */\nexport function createPublisherHandshakeClient(options: CreatePublisherHandshakeClientOptions): PublisherHandshakeClient {\n assertPublicationIdentity(options.publication, options.reader)\n const serviceId = options.serviceId === undefined ? undefined : HandshakeIdZod.parse(options.serviceId)\n async function snapshot(): Promise<SynchronizedEventKitHandshakeSnapshot> {\n return readySnapshot(await options.reader.sync())\n }\n async function discovery(current: SynchronizedEventKitHandshakeSnapshot): Promise<PublisherServiceDiscovery> {\n return await current.readModel.discoverPublisherService(serviceQuery(options.reader, current, serviceId))\n }\n async function candidateDiscovery(selector: Partial<PublisherSubscriptionSelector> = {}): Promise<PublisherAcceptanceCandidateDiscovery> {\n const current = await snapshot()\n return await current.readModel.acceptanceCandidates({\n ...serviceQuery(options.reader, current, serviceId),\n ...(selector.subscriber === undefined\n ? {}\n : { subscriber: NormalizedAddressZod.parse(selector.subscriber) }),\n ...(selector.subscriptionId === undefined\n ? {}\n : { subscriptionId: HandshakeIdZod.parse(selector.subscriptionId) }),\n })\n }\n async function resolveCandidate(selector: PublisherSubscriptionSelector): Promise<ResolvedPublisherCandidate> {\n const found = await candidateDiscovery(selector)\n if (!found.ok)\n throw new EventKitHandshakeClientError('service-unavailable', `Publisher service is unavailable: ${found.reason}`)\n const subscriber = NormalizedAddressZod.parse(selector.subscriber)\n const subscription = selector.subscription === undefined ? undefined : HashZod.parse(selector.subscription)\n const candidates = found.candidates.filter(candidate => candidate.subscriber === subscriber\n && (subscription === undefined || candidate.tuple.subscription.objectHash === subscription))\n if (candidates.length === 0) {\n throw new EventKitHandshakeClientError('candidate-not-found', 'No exact finalized acceptance candidate was found')\n }\n if (candidates.length !== 1) {\n throw new EventKitHandshakeClientError('candidate-ambiguous', 'More than one finalized acceptance candidate matched')\n }\n const candidate = candidates[0]\n const validated = await validateAndDecryptPublisherSubscription(protocolCandidate(options.reader, found, candidate, options.keys))\n if (!validated.ok)\n throw validationError(validated.reason)\n return { candidate, validated }\n }\n async function candidateForChallenge(challenge: EndpointChallenge): Promise<ResolvedPublisherCandidate> {\n const resolved = await resolveCandidate({\n subscriber: challenge.subscriber,\n subscription: challenge.subscription,\n })\n if (!endpointChallengeMatchesPublisherContext(challenge, resolved.validated.context)) {\n throw new EventKitHandshakeClientError('challenge-context-invalid', 'Endpoint challenge does not match the current finalized subscription candidate')\n }\n return resolved\n }\n async function reconcileAcceptance(acceptance: Hash, publication: HandshakePublicationResult, subscriber: NormalizedAddress, subscription: Hash): Promise<PublisherAcceptanceReconciliation> {\n let current: SynchronizedEventKitHandshakeSnapshot\n try {\n current = await options.reader.sync()\n } catch {\n return Object.freeze({ reason: 'synchronization-failed', status: 'unavailable' as const })\n }\n if (current.blocked !== undefined) {\n return Object.freeze({\n finalizedHead: current.finalizedHead,\n indexedThrough: current.indexedThrough,\n reason: 'projection-blocked' as const,\n status: 'unavailable' as const,\n })\n }\n if (current.indexedThrough !== current.finalizedHead) {\n return Object.freeze({\n finalizedHead: current.finalizedHead,\n indexedThrough: current.indexedThrough,\n reason: 'projection-stale' as const,\n status: 'unavailable' as const,\n })\n }\n if (current.finalizedHead < publication.finalizedBlock) {\n return Object.freeze({\n finalizedHead: current.finalizedHead,\n indexedThrough: current.indexedThrough,\n reason: 'publication-not-indexed' as const,\n status: 'unavailable' as const,\n })\n }\n let view: PublisherHandshakeView\n try {\n view = await current.readModel.publisher(serviceQuery(options.reader, current, serviceId))\n } catch {\n return Object.freeze({\n finalizedHead: current.finalizedHead,\n indexedThrough: current.indexedThrough,\n reason: 'synchronization-failed' as const,\n status: 'unavailable' as const,\n })\n }\n if (!view.ok) {\n return Object.freeze({\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n reason: view.reason,\n status: 'unavailable' as const,\n })\n }\n const matches = view.subscriptions.filter(item => item.subscriber === subscriber\n && item.tuples.some(tuple => tuple.subscription.objectHash === subscription))\n if (matches.length === 0) {\n return Object.freeze({\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n status: 'not-found' as const,\n })\n }\n if (matches.length !== 1) {\n return Object.freeze({\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n reason: 'ambiguous-lifecycle' as const,\n status: 'unavailable' as const,\n })\n }\n const lifecycle = matches[0]\n const active = lifecycle.state === 'active'\n && lifecycle.selectedSubscription === subscription\n && lifecycle.acceptance?.objectHash === acceptance\n return Object.freeze({\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n lifecycle,\n status: active ? 'active' as const : 'not-active' as const,\n })\n }\n async function publishAcceptanceIntent(intent: PublisherAcceptanceIntent, intentDisposition: HandshakeMutationIntentDisposition): Promise<PublisherAcceptancePublicationResult> {\n const [acceptanceHash, responseHash] = await Promise.all([\n handshakeObjectHash(intent.acceptance),\n handshakeObjectHash(intent.response),\n ])\n const publication = await options.publication.publishWakeSubscriptionAcceptance({\n acceptance: intent.acceptance,\n challenge: intent.challenge,\n operationId: intent.operationId,\n response: intent.response,\n })\n const reconciliation = await reconcileAcceptance(acceptanceHash, publication, intent.challenge.subscriber, intent.challenge.subscription)\n return Object.freeze({\n acceptance: Object.freeze({ body: intent.acceptance, objectHash: acceptanceHash }),\n challenge: intent.acceptance.challenge,\n intentDisposition,\n operationId: intent.operationId,\n publication,\n reconciliation,\n response: responseHash,\n subscriber: intent.challenge.subscriber,\n subscription: intent.challenge.subscription,\n })\n }\n async function publishPublisherServiceIntent(\n intent: PublisherServicePublishIntent | PublisherServiceRotateKeyIntent,\n intentDisposition: HandshakeMutationIntentDisposition,\n ): Promise<PublisherServicePublicationResult> {\n let keyCustody: 'duplicate' | 'stored'\n try {\n keyCustody = await options.keys.putPrivateKey({\n key: intent.privateKey,\n publisher: options.reader.publisher,\n })\n } catch {\n throw new EventKitHandshakeClientError('key-custody-failed', 'Publisher encryption private key was not durably retained; publication was not attempted')\n }\n const [keyHash, serviceHash] = await Promise.all([\n handshakeObjectHash(intent.encryptionKey),\n handshakeObjectHash(intent.service),\n ])\n const publication = await options.publication.publishPublisherService({\n encryptionKeys: [intent.encryptionKey],\n operationId: intent.operationId,\n service: intent.service,\n })\n return Object.freeze({\n encryptionKey: Object.freeze({ body: intent.encryptionKey, objectHash: keyHash }),\n intentDisposition,\n keyCustody,\n operationId: intent.operationId,\n publication,\n service: Object.freeze({ body: intent.service, objectHash: serviceHash }),\n })\n }\n const client: PublisherHandshakeClient = {\n async acceptanceCandidates(selector = {}) {\n const found = await candidateDiscovery(selector)\n if (!found.ok || selector.subscription === undefined)\n return found\n const subscription = HashZod.parse(selector.subscription)\n return Object.freeze({\n ...found,\n candidates: found.candidates.filter(candidate => candidate.tuple.subscription.objectHash === subscription),\n })\n },\n async beginChallenge(input): Promise<BeginPublisherChallengeResult> {\n const challengeHash = HashZod.parse(input.challengeHash)\n const record = await options.challenges.get(challengeHash)\n if (record === undefined)\n return { kind: 'missing' }\n const resolved = await candidateForChallenge(record.challenge)\n const begun = await beginPublisherEndpointChallengeAttempt({\n challengeHash,\n nowSeconds: samplePublisherClock(input.nowSeconds),\n store: options.challenges,\n })\n if (begun.kind !== 'started') {\n if (begun.kind === 'store-invalid' || begun.kind === 'store-unavailable') {\n throw new EventKitHandshakeClientError('challenge-rejected', `Endpoint challenge store failed: ${begun.kind}`)\n }\n return { kind: begun.kind }\n }\n return Object.freeze({\n challenge: begun.record.challenge,\n challengeHash,\n kind: 'started' as const,\n subscriber: resolved.validated.context.subscriber,\n subscription: resolved.validated.context.subscription,\n target: Object.freeze({\n audience: resolved.validated.plaintext.audience,\n endpoint: resolved.validated.plaintext.endpoint,\n }),\n })\n },\n async completeChallengeAndAccept(input): Promise<PublisherAcceptancePublicationResult> {\n await assertPublicationSource(options.publication, options.reader.publisher)\n const challengeHash = HashZod.parse(input.challengeHash)\n const subscriber = NormalizedAddressZod.parse(input.subscriber)\n const subscription = HashZod.parse(input.subscription)\n const record = await options.challenges.get(challengeHash)\n if (record === undefined) {\n throw new EventKitHandshakeClientError('challenge-not-found', 'Endpoint challenge was not found')\n }\n if (record.challenge.subscriber !== subscriber\n || record.challenge.subscription !== subscription) {\n throw new EventKitHandshakeClientError('challenge-context-invalid', 'Stored endpoint challenge does not match the caller expected subscriber and subscription')\n }\n const responseHash = await handshakeObjectHash(input.response)\n const requestFingerprint = await exactMutationRequestFingerprint({\n challengeHash,\n responseHash,\n subscriber,\n subscription,\n })\n const existing = await loadMutationIntent(options.intents, options.reader, 'publisher-subscription-accept', challengeHash, options.reader.publisher, requestFingerprint)\n if (existing !== undefined) {\n if (record.state !== 'verified' || record.responseHash !== responseHash) {\n throw new EventKitHandshakeClientError('mutation-intent-conflict', 'Acceptance intent does not match the durable verified challenge decision')\n }\n return await publishAcceptanceIntent(existing, 'resumed')\n }\n const resolved = await candidateForChallenge(record.challenge)\n const completed = await completePublisherEndpointChallenge({\n challenge: record.challenge,\n nowSeconds: samplePublisherClock(input.nowSeconds),\n response: input.response,\n store: options.challenges,\n subscription: resolved.validated,\n })\n if (!completed.ok)\n throw challengeError(completed)\n const concurrentlyPersisted = await loadMutationIntent(options.intents, options.reader, 'publisher-subscription-accept', challengeHash, options.reader.publisher, requestFingerprint)\n if (concurrentlyPersisted !== undefined)\n return await publishAcceptanceIntent(concurrentlyPersisted, 'resumed')\n // This second replay is intentional: challenge success is not acceptance\n // eligibility. Recheck every finalized lifecycle edge immediately before\n // constructing and publishing the acceptance transaction.\n let current: ResolvedPublisherCandidate\n try {\n current = await candidateForChallenge(record.challenge)\n } catch (error) {\n const recovered = await loadMutationIntent(options.intents, options.reader, 'publisher-subscription-accept', challengeHash, options.reader.publisher, requestFingerprint)\n if (recovered !== undefined)\n return await publishAcceptanceIntent(recovered, 'resumed')\n throw error\n }\n if (!endpointChallengeMatchesPublisherContext(record.challenge, current.validated.context)) {\n throw new EventKitHandshakeClientError('challenge-context-invalid', 'Endpoint challenge candidate changed before acceptance publication')\n }\n const resolvedIntent = await persistMutationIntent(options.intents, {\n acceptance: completed.acceptance,\n chainId: options.reader.chainId,\n challenge: record.challenge,\n kind: 'publisher-subscription-accept',\n operationId: challengeHash,\n publisher: options.reader.publisher,\n requestFingerprint,\n response: input.response,\n source: options.reader.publisher,\n version: 1,\n })\n return await publishAcceptanceIntent(resolvedIntent.intent, resolvedIntent.disposition)\n },\n async issueChallenge(input): Promise<IssuedPublisherChallenge> {\n const resolved = await resolveCandidate(input)\n const issued = await issuePublisherEndpointChallenge({\n issuedAt: input.issuedAt,\n ...(input.lifetimeSeconds === undefined ? {} : { lifetimeSeconds: input.lifetimeSeconds }),\n store: options.challenges,\n subscription: resolved.validated,\n })\n if (!issued.ok) {\n throw new EventKitHandshakeClientError('challenge-rejected', `Endpoint challenge issue failed: ${issued.reason}`)\n }\n return Object.freeze({\n challenge: issued.challenge,\n challengeHash: issued.challengeHash,\n disposition: issued.disposition,\n subscriber: resolved.validated.context.subscriber,\n subscription: resolved.validated.context.subscription,\n })\n },\n async key(): Promise<PublisherServiceDiscovery> {\n const current = await options.reader.sync()\n return await current.readModel.discoverPublisherService(serviceQuery(options.reader, current, serviceId))\n },\n async publishService(input): Promise<PublisherServicePublicationResult> {\n await assertPublicationSource(options.publication, options.reader.publisher)\n if (serviceId !== undefined) {\n throw new EventKitHandshakeClientError('service-root-requires-fresh-id', 'Root service publication requires an unconfigured client so a fresh serviceId is generated')\n }\n const operationId = HandshakeIdZod.parse(input.operationId)\n const requestFingerprint = await publisherServiceRequestFingerprint(input)\n const priorIntent = await loadMutationIntent(options.intents, options.reader, 'publisher-service-publish', operationId, options.reader.publisher, requestFingerprint)\n if (priorIntent !== undefined)\n return await publishPublisherServiceIntent(priorIntent, 'resumed')\n const current = await snapshot()\n const existing = await discovery(current)\n if (existing.ok) {\n throw new EventKitHandshakeClientError('service-already-exists', 'An active publisher service already exists; rotate its key to publish a successor')\n }\n if (existing.reason !== 'service-not-found') {\n throw new EventKitHandshakeClientError('service-unavailable', `Cannot declare service: ${existing.reason}`)\n }\n const validFromBlock = input.validFromBlock ?? nextBlock(current.finalizedHead)\n const generated = await generatePublisherEncryptionKey({ validFromBlock })\n const serviceInput = {\n encryptionKeys: [generated.descriptorHash],\n ...(input.expiresAtBlock === undefined ? {} : { expiresAtBlock: input.expiresAtBlock }),\n maxSubscriptionLifetimeBlocks: input.maxSubscriptionLifetimeBlocks,\n preferredEncryptionKey: generated.descriptorHash,\n validFromBlock,\n }\n const service = createPublisherService({\n deliveryMode: input.deliveryMode,\n ...(input.bestEffort === undefined ? {} : { bestEffort: input.bestEffort }),\n ...serviceInput,\n authorizationChainId: options.reader.chainId,\n sources: input.sources,\n maxPositionsPerWake: input.maxPositionsPerWake,\n })\n const resolvedIntent = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n encryptionKey: generated.descriptor,\n kind: 'publisher-service-publish',\n operationId,\n privateKey: generated.privateKey,\n publisher: options.reader.publisher,\n requestFingerprint,\n service,\n source: options.reader.publisher,\n version: 1,\n })\n return await publishPublisherServiceIntent(resolvedIntent.intent, resolvedIntent.disposition)\n },\n async retireEncryptionKey(key): Promise<PublisherKeyRetirementResult> {\n await assertPublicationSource(options.publication, options.reader.publisher)\n const keyHash = HashZod.parse(key)\n const requestFingerprint = await exactMutationRequestFingerprint({ key: keyHash })\n let resolvedIntent = await loadMutationIntent(options.intents, options.reader, 'publisher-encryption-key-retire', keyHash, options.reader.publisher, requestFingerprint)\n let intentDisposition: HandshakeMutationIntentDisposition = 'resumed'\n if (resolvedIntent === undefined) {\n const current = await snapshot()\n const selected = requireService(await discovery(current))\n if (selected.key.objectHash !== keyHash\n || !selected.service.body.encryptionKeys.includes(keyHash)\n || selected.service.body.preferredEncryptionKey !== keyHash) {\n throw new EventKitHandshakeClientError('key-mismatch', 'Encryption key does not match the exact current preferred descriptor evidence')\n }\n const persisted = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n kind: 'publisher-encryption-key-retire',\n operationId: keyHash,\n publisher: options.reader.publisher,\n requestFingerprint,\n revocation: createPublisherEncryptionKeyRevocation(keyHash),\n source: options.reader.publisher,\n version: 1,\n })\n resolvedIntent = persisted.intent\n intentDisposition = persisted.disposition\n }\n const revocation = await withHandshakeObjectHash(resolvedIntent.revocation)\n const publication = await options.publication.publishPublisherEncryptionKeyRevocation({\n operationId: keyHash,\n revocation: resolvedIntent.revocation,\n })\n return Object.freeze({\n intentDisposition,\n key: keyHash,\n operationId: keyHash,\n publication,\n revocation,\n })\n },\n async retireService(expectedService): Promise<PublisherServiceRetirementResult> {\n await assertPublicationSource(options.publication, options.reader.publisher)\n const service = HashZod.parse(expectedService)\n const requestFingerprint = await exactMutationRequestFingerprint({ service })\n let resolvedIntent = await loadMutationIntent(options.intents, options.reader, 'publisher-service-retire', service, options.reader.publisher, requestFingerprint)\n let intentDisposition: HandshakeMutationIntentDisposition = 'resumed'\n if (resolvedIntent === undefined) {\n const current = await snapshot()\n const selected = requireService(await discovery(current))\n requireExpectedService(selected, service)\n const persisted = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n kind: 'publisher-service-retire',\n operationId: service,\n publisher: options.reader.publisher,\n requestFingerprint,\n revocation: createPublisherServiceRevocation(service),\n source: options.reader.publisher,\n version: 1,\n })\n resolvedIntent = persisted.intent\n intentDisposition = persisted.disposition\n }\n const revocation = await withHandshakeObjectHash(resolvedIntent.revocation)\n const publication = await options.publication.publishPublisherServiceRevocation({\n operationId: service,\n revocation: resolvedIntent.revocation,\n })\n return Object.freeze({\n intentDisposition,\n operationId: service,\n publication,\n revocation,\n service,\n })\n },\n async rotateEncryptionKey(input): Promise<PublisherServicePublicationResult> {\n await assertPublicationSource(options.publication, options.reader.publisher)\n const operationId = HandshakeIdZod.parse(input.operationId)\n const requestFingerprint = await publisherRotationRequestFingerprint(input)\n const priorIntent = await loadMutationIntent(options.intents, options.reader, 'publisher-service-rotate-key', operationId, options.reader.publisher, requestFingerprint)\n if (priorIntent !== undefined)\n return await publishPublisherServiceIntent(priorIntent, 'resumed')\n const current = await snapshot()\n const selected = requireService(await discovery(current))\n requireExpectedService(selected, input.service)\n const validFromBlock = input.validFromBlock ?? nextBlock(current.finalizedHead)\n const generated = await generatePublisherEncryptionKey({\n ...(input.keyExpiresAtBlock === undefined ? {} : { expiresAtBlock: input.keyExpiresAtBlock }),\n validFromBlock,\n })\n const serviceInput = {\n encryptionKeys: [generated.descriptorHash],\n ...(input.expiresAtBlock === undefined\n ? selected.service.body.expiresAtBlock === undefined\n ? {}\n : { expiresAtBlock: selected.service.body.expiresAtBlock }\n : { expiresAtBlock: input.expiresAtBlock }),\n maxSubscriptionLifetimeBlocks: input.maxSubscriptionLifetimeBlocks\n ?? selected.service.body.limits.maxSubscriptionLifetimeBlocks,\n preferredEncryptionKey: generated.descriptorHash,\n revision: selected.service.body.revision + 1,\n serviceId: selected.service.body.serviceId,\n supersedes: HashZod.parse(selected.service.objectHash),\n validFromBlock,\n }\n const service = createPublisherService({\n deliveryMode: selected.service.body.deliveryMode,\n ...(selected.service.body.bestEffort === undefined ? {} : { bestEffort: selected.service.body.bestEffort }),\n ...serviceInput,\n authorizationChainId: options.reader.chainId,\n sources: selected.service.body.events.map(event => event.source),\n maxPositionsPerWake: input.maxPositionsPerWake ?? selected.service.body.limits.maxPositionsPerWake,\n })\n const resolvedIntent = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n encryptionKey: generated.descriptor,\n kind: 'publisher-service-rotate-key',\n operationId,\n privateKey: generated.privateKey,\n publisher: options.reader.publisher,\n requestFingerprint,\n selectedKey: HashZod.parse(selected.key.objectHash),\n selectedService: HashZod.parse(selected.service.objectHash),\n service,\n source: options.reader.publisher,\n version: 1,\n })\n return await publishPublisherServiceIntent(resolvedIntent.intent, resolvedIntent.disposition)\n },\n async service(): Promise<PublisherServiceDiscovery> {\n const current = await options.reader.sync()\n return await current.readModel.discoverPublisherService(serviceQuery(options.reader, current, serviceId))\n },\n async subscriptions(): Promise<PublisherHandshakeView> {\n const current = await options.reader.sync()\n return await current.readModel.publisher(serviceQuery(options.reader, current, serviceId))\n },\n }\n return Object.freeze(client)\n}\nexport interface CreateSubscriberHandshakeClientOptions {\n readonly intents: HandshakeMutationIntentStore\n readonly publication: EventKitHandshakePublicationPort\n readonly reader: SynchronizedEventKitHandshakeReader\n readonly serviceId?: string\n readonly subscriber: string\n}\nexport interface SubscribeToPublisherInput {\n readonly audience: string\n readonly bestEffort?: BestEffortDeliveryPolicy\n /** Subscriber-owned secret already provisioned at the endpoint; it is never returned or published. */\n readonly challengeSecret: Base64Url32Bytes\n readonly deliveryMode: WakeDeliveryMode\n readonly deploymentId: string\n readonly endpoint: string\n readonly expiresAtBlock: number\n readonly fromPosition: number\n readonly grantId?: string\n readonly maxPositionsPerWake?: number\n readonly operationId: HandshakeId\n readonly queueId?: string | null\n readonly revision?: number\n readonly source: WakeSource\n readonly subscriptionId?: HandshakeId\n readonly supersedes?: Hash\n}\nexport interface SubscriberSubscriptionPublicationResult {\n readonly grant: HashedHandshakeObject<WakeGrantObject>\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly operationId: HandshakeId\n readonly publication: HandshakePublicationResult\n readonly service: Hash\n readonly subscription: HashedHandshakeObject<EncryptedWakeSubscription>\n}\nexport interface SubscriberSubscriptionRevocationResult {\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly operationId: Hash\n readonly publication: HandshakePublicationResult\n readonly revocation: HashedHandshakeObject<ReturnType<typeof createWakeSubscriptionRevocation>>\n readonly subscription: Hash\n}\nexport interface SubscriberGrantRevocationResult {\n readonly grant: Hash\n readonly intentDisposition: HandshakeMutationIntentDisposition\n readonly operationId: Hash\n readonly publication: HandshakePublicationResult\n readonly revocation: HashedHandshakeObject<ReturnType<typeof createWakeGrantRevocation>>\n}\nexport interface SubscriberHandshakeClient {\n revokeGrant(grant: string): Promise<SubscriberGrantRevocationResult>\n revokeSubscription(subscription: string): Promise<SubscriberSubscriptionRevocationResult>\n service(): Promise<PublisherServiceDiscovery>\n subscribe(input: SubscribeToPublisherInput): Promise<SubscriberSubscriptionPublicationResult>\n subscription(subscription: string): Promise<SubscriberExactSubscriptionLookup>\n subscriptions(subscriptionId?: string): Promise<SubscriberSubscriptionLookup>\n}\nexport interface SubscriberExactSubscriptionLookupSuccess {\n readonly found: true\n readonly lifecycle: PublisherSubscriptionView\n readonly lookup: SubscriberSubscriptionLookupSuccess\n readonly ok: true\n readonly tuple: FinalizedSubscriptionTuple\n}\nexport interface SubscriberExactSubscriptionLookupNotFound {\n readonly found: false\n readonly lookup: SubscriberSubscriptionLookupSuccess\n readonly ok: true\n}\nexport type SubscriberExactSubscriptionLookup = PublisherServiceDiscoveryFailure | SubscriberExactSubscriptionLookupNotFound | SubscriberExactSubscriptionLookupSuccess\nfunction tupleHashes(view: Extract<SubscriberSubscriptionLookup, {\n readonly ok: true\n}>): {\n readonly grants: ReadonlySet<string>\n readonly subscriptions: ReadonlySet<string>\n} {\n const tuples = view.subscriptions.flatMap(subscription => subscription.tuples)\n return {\n grants: new Set(tuples.map(tuple => tuple.grant.objectHash)),\n subscriptions: new Set(tuples.map(tuple => tuple.subscription.objectHash)),\n }\n}\n/** Subscriber-side discovery, encryption, exact tuple publication, and revocation. */\nexport function createSubscriberHandshakeClient(options: CreateSubscriberHandshakeClientOptions): SubscriberHandshakeClient {\n assertPublicationIdentity(options.publication, options.reader)\n const subscriber = NormalizedAddressZod.parse(options.subscriber)\n const serviceId = options.serviceId === undefined ? undefined : HandshakeIdZod.parse(options.serviceId)\n async function snapshot(): Promise<SynchronizedEventKitHandshakeSnapshot> {\n return readySnapshot(await options.reader.sync())\n }\n async function serviceAt(current: SynchronizedEventKitHandshakeSnapshot) {\n return requireService(await current.readModel.discoverPublisherService(serviceQuery(options.reader, current, serviceId)))\n }\n async function lookup(subscriptionId?: string): Promise<SubscriberSubscriptionLookup> {\n const current = await options.reader.sync()\n return await lookupAt(current, subscriptionId)\n }\n async function lookupAt(current: SynchronizedEventKitHandshakeSnapshot, subscriptionId?: string): Promise<SubscriberSubscriptionLookup> {\n return await current.readModel.subscriber({\n ...serviceQuery(options.reader, current, serviceId),\n subscriber,\n ...(subscriptionId === undefined ? {} : { subscriptionId: HandshakeIdZod.parse(subscriptionId) }),\n })\n }\n async function validateRevision(current: SynchronizedEventKitHandshakeSnapshot, input: SubscribeToPublisherInput): Promise<void> {\n const revision = input.revision ?? 1\n if (revision === 1) {\n if (input.supersedes !== undefined) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Subscription revision 1 must not declare supersedes')\n }\n if (input.subscriptionId === undefined)\n return\n const view = await lookupAt(current, input.subscriptionId)\n if (!view.ok) {\n throw new EventKitHandshakeClientError('service-unavailable', `Cannot validate subscription identity: ${view.reason}`)\n }\n if (view.subscriptions.some(item => item.subscriptionId === input.subscriptionId)) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Subscription revision 1 would duplicate an existing finalized stable identity')\n }\n return\n }\n if (input.subscriptionId === undefined || input.supersedes === undefined) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'A replacement subscription requires subscriptionId and supersedes')\n }\n const view = await lookupAt(current, input.subscriptionId)\n if (!view.ok) {\n throw new EventKitHandshakeClientError('service-unavailable', `Cannot validate subscription revision: ${view.reason}`)\n }\n const lifecycles = view.subscriptions.filter(item => item.subscriptionId === input.subscriptionId)\n if (lifecycles.length !== 1) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Replacement subscription does not resolve one finalized stable identity')\n }\n if (lifecycles[0].state === 'rejected') {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Replacement subscription cannot extend a rejected finalized revision chain')\n }\n const highestRevision = Math.max(...lifecycles[0].tuples.map(tuple => tuple.subscription.body.revision))\n const latest = lifecycles[0].tuples.filter(tuple => tuple.subscription.body.revision === highestRevision)\n if (latest.length !== 1\n || revision !== highestRevision + 1\n || latest[0].subscription.objectHash !== input.supersedes) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Replacement subscription revision and supersedes must extend the exact finalized chain tip')\n }\n }\n async function publishSubscriberSubscriptionIntent(intent: SubscriberSubscriptionIntent, intentDisposition: HandshakeMutationIntentDisposition): Promise<SubscriberSubscriptionPublicationResult> {\n const [grantHash, subscriptionHash] = await Promise.all([\n handshakeObjectHash(intent.grant),\n handshakeObjectHash(intent.subscription),\n ])\n const publication = await options.publication.publishWakeSubscription({\n encryptionKey: intent.encryptionKey,\n grant: intent.grant,\n operationId: intent.operationId,\n service: intent.service,\n subscription: intent.subscription,\n })\n return Object.freeze({\n grant: Object.freeze({ body: intent.grant, objectHash: grantHash }),\n intentDisposition,\n operationId: intent.operationId,\n publication,\n service: intent.selectedService,\n subscription: Object.freeze({ body: intent.subscription, objectHash: subscriptionHash }),\n })\n }\n const client: SubscriberHandshakeClient = {\n async revokeGrant(grant): Promise<SubscriberGrantRevocationResult> {\n await assertPublicationSource(options.publication, subscriber)\n const grantHash = HashZod.parse(grant)\n const requestFingerprint = await exactMutationRequestFingerprint({ grant: grantHash })\n let resolvedIntent = await loadMutationIntent(options.intents, options.reader, 'subscriber-grant-revoke', grantHash, subscriber, requestFingerprint)\n let intentDisposition: HandshakeMutationIntentDisposition = 'resumed'\n if (resolvedIntent === undefined) {\n const current = await snapshot()\n const view = await current.readModel.subscriber({ ...serviceQuery(options.reader, current, serviceId), subscriber })\n if (!view.ok || !tupleHashes(view).grants.has(grantHash)) {\n throw new EventKitHandshakeClientError('subscription-not-found', 'Grant is not present in this subscriber finalization view')\n }\n const persisted = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n kind: 'subscriber-grant-revoke',\n operationId: grantHash,\n publisher: options.reader.publisher,\n requestFingerprint,\n revocation: createWakeGrantRevocation(grantHash),\n source: subscriber,\n version: 1,\n })\n resolvedIntent = persisted.intent\n intentDisposition = persisted.disposition\n }\n const revocation = await withHandshakeObjectHash(resolvedIntent.revocation)\n const publication = await options.publication.publishWakeGrantRevocation({\n operationId: grantHash,\n publisher: options.reader.publisher,\n revocation: resolvedIntent.revocation,\n })\n return Object.freeze({\n grant: grantHash,\n intentDisposition,\n operationId: grantHash,\n publication,\n revocation,\n })\n },\n async revokeSubscription(subscription): Promise<SubscriberSubscriptionRevocationResult> {\n await assertPublicationSource(options.publication, subscriber)\n const subscriptionHash = HashZod.parse(subscription)\n const requestFingerprint = await exactMutationRequestFingerprint({ subscription: subscriptionHash })\n let resolvedIntent = await loadMutationIntent(options.intents, options.reader, 'subscriber-subscription-revoke', subscriptionHash, subscriber, requestFingerprint)\n let intentDisposition: HandshakeMutationIntentDisposition = 'resumed'\n if (resolvedIntent === undefined) {\n const current = await snapshot()\n const view = await current.readModel.subscriber({ ...serviceQuery(options.reader, current, serviceId), subscriber })\n if (!view.ok || !tupleHashes(view).subscriptions.has(subscriptionHash)) {\n throw new EventKitHandshakeClientError('subscription-not-found', 'Subscription is not present in this subscriber finalization view')\n }\n const persisted = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n kind: 'subscriber-subscription-revoke',\n operationId: subscriptionHash,\n publisher: options.reader.publisher,\n requestFingerprint,\n revocation: createWakeSubscriptionRevocation(subscriptionHash),\n source: subscriber,\n version: 1,\n })\n resolvedIntent = persisted.intent\n intentDisposition = persisted.disposition\n }\n const revocation = await withHandshakeObjectHash(resolvedIntent.revocation)\n const publication = await options.publication.publishWakeSubscriptionRevocation({\n operationId: subscriptionHash,\n publisher: options.reader.publisher,\n revocation: resolvedIntent.revocation,\n })\n return Object.freeze({\n intentDisposition,\n operationId: subscriptionHash,\n publication,\n revocation,\n subscription: subscriptionHash,\n })\n },\n async service(): Promise<PublisherServiceDiscovery> {\n const current = await options.reader.sync()\n return await current.readModel.discoverPublisherService(serviceQuery(options.reader, current, serviceId))\n },\n async subscription(subscription): Promise<SubscriberExactSubscriptionLookup> {\n const subscriptionHash = HashZod.parse(subscription)\n const current = await options.reader.sync()\n const view = await lookupAt(current)\n if (!view.ok)\n return view\n const matches = view.subscriptions.flatMap(lifecycle => lifecycle.tuples\n .filter(tuple => tuple.subscription.objectHash === subscriptionHash)\n .map(tuple => ({ lifecycle, tuple })))\n if (matches.length > 1) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Exact subscription hash appears more than once in the subscriber view')\n }\n if (matches.length === 0)\n return Object.freeze({\n found: false, lookup: view, ok: true,\n })\n return Object.freeze({\n found: true,\n lifecycle: matches[0].lifecycle,\n lookup: view,\n ok: true,\n tuple: matches[0].tuple,\n })\n },\n async subscribe(input): Promise<SubscriberSubscriptionPublicationResult> {\n await assertPublicationSource(options.publication, subscriber)\n const operationId = HandshakeIdZod.parse(input.operationId)\n const requestFingerprint = await subscriberSubscriptionRequestFingerprint(input)\n const priorIntent = await loadMutationIntent(options.intents, options.reader, 'subscriber-subscription-subscribe', operationId, subscriber, requestFingerprint)\n if (priorIntent !== undefined)\n return await publishSubscriberSubscriptionIntent(priorIntent, 'resumed')\n const current = await snapshot()\n const selected = await serviceAt(current)\n if (input.expiresAtBlock - current.finalizedHead <= 3) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Requested subscription expiry must leave finalized blocks for tuple publication, acceptance, and activation')\n }\n await validateRevision(current, input)\n const maximum = selected.service.body.limits.maxPositionsPerWake\n const maxPositionsPerWake = input.maxPositionsPerWake ?? maximum\n if (maxPositionsPerWake > maximum) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Requested maxPositionsPerWake exceeds the selected publisher service limit')\n }\n if (input.expiresAtBlock > current.finalizedHead + selected.service.body.limits.maxSubscriptionLifetimeBlocks) {\n throw new EventKitHandshakeClientError('subscription-invalid', 'Requested subscription expiry exceeds the selected publisher service lifetime limit')\n }\n const grant = createWakeGrant({\n deploymentId: input.deploymentId,\n ...(input.grantId === undefined ? {} : { grantId: input.grantId }),\n publisher: options.reader.publisher,\n ...(input.queueId === undefined || input.queueId === null ? {} : { queueId: input.queueId }),\n })\n const grantHash = await handshakeObjectHash(grant)\n const plaintext = subscriberPlaintext(selected.service.body, input, maxPositionsPerWake)\n const subscriptionInput = {\n chainId: options.reader.chainId,\n expiresAtBlock: input.expiresAtBlock,\n grant: grantHash,\n publisher: options.reader.publisher,\n publisherKey: {\n encryptionKey: HashZod.parse(selected.key.objectHash),\n keyId: selected.key.body.keyId,\n publicKey: selected.key.body.publicKey,\n },\n ...(input.revision === undefined ? {} : { revision: input.revision }),\n service: HashZod.parse(selected.service.objectHash),\n subscriber,\n ...(input.subscriptionId === undefined ? {} : { subscriptionId: input.subscriptionId }),\n ...(input.supersedes === undefined ? {} : { supersedes: input.supersedes }),\n }\n const subscription = await createEncryptedWakeSubscription({ ...subscriptionInput, plaintext })\n const resolvedIntent = await persistMutationIntent(options.intents, {\n chainId: options.reader.chainId,\n encryptionKey: selected.key.body,\n grant,\n kind: 'subscriber-subscription-subscribe',\n operationId,\n publisher: options.reader.publisher,\n requestFingerprint,\n selectedKey: HashZod.parse(selected.key.objectHash),\n selectedService: HashZod.parse(selected.service.objectHash),\n service: selected.service.body,\n source: subscriber,\n subscription,\n version: 1,\n })\n return await publishSubscriberSubscriptionIntent(resolvedIntent.intent, resolvedIntent.disposition)\n },\n subscriptions: async (subscriptionId): Promise<SubscriberSubscriptionLookup> => await lookup(subscriptionId),\n }\n return Object.freeze(client)\n}\n\nfunction subscriberPlaintext(service: PublisherService, input: SubscribeToPublisherInput, maxPositionsPerWake: number): WakeSubscriptionPlaintext {\n if (input.deliveryMode !== service.deliveryMode || canonicalJson(input.bestEffort ?? null) !== canonicalJson(service.bestEffort ?? null))\n throw new Error('Requested delivery terms do not match exact selected service')\n const plaintextInput = {\n audience: input.audience,\n challengeSecret: input.challengeSecret,\n deploymentId: input.deploymentId,\n endpoint: input.endpoint,\n queueId: input.queueId,\n }\n const source = input.source\n if (service.events.every(event => canonicalJson(event.source) !== canonicalJson(source))) {\n throw new Error('Requested source is not advertised by the selected service')\n }\n return createWakeSubscriptionPlaintext({\n deliveryMode: input.deliveryMode,\n ...(input.bestEffort === undefined ? {} : { bestEffort: input.bestEffort }),\n ...plaintextInput,\n source,\n fromPosition: input.fromPosition,\n maxPositionsPerWake,\n })\n}\n", "import { randomBytes } from 'node:crypto'\nimport {\n link, lstat, mkdir, mkdtemp, open, realpath, rm, unlink,\n} from 'node:fs/promises'\nimport OS from 'node:os'\nimport PATH from 'node:path'\n\nimport type { AdmittedWake } from '@xyo-network/event-kit-protocol'\nimport {\n HashZod, NormalizedAddressZod, WakeIdZod, WakeJwtAudienceZod,\n} from '@xyo-network/event-kit-schemas'\n\nimport { syncDirectory } from './filesystemDurability.ts'\nimport { ensurePrivateDirectory } from './privateSqlite.ts'\nimport { openReceiverAuthority, receiverIdentity } from './receiverAuthority.ts'\nimport { inventoryReceiverMigration } from './receiverMigrationInventory.ts'\nimport { snapshotMigrationSource, verifyMigrationSource } from './receiverMigrationSnapshot.ts'\nimport type {\n ReceiverMigrationEntry, ReceiverMigrationFile, ReceiverMigrationOptions, ReceiverMigrationPlan, ReceiverMigrationReport,\n} from './receiverMigrationTypes.ts'\n\nexport type {\n FilesystemReceiverMigrationSource, ReceiverMigrationFile, ReceiverMigrationIssue,\n ReceiverMigrationOptions, ReceiverMigrationReport, ReceiverMigrationReview, ReceiverMigrationSource,\n SqliteQueueMigrationSource,\n} from './receiverMigrationTypes.ts'\n\nconst rollback = 'restore-backup-only-before-new-writers-resume; after-that-repair-forward; reverse-migration-unsupported' as const\n\nasync function outsideSource(source: string, destination: string): Promise<string> {\n let parent = PATH.dirname(PATH.resolve(destination))\n const suffix = [PATH.basename(destination)]\n let canonicalParent: string\n for (;;) {\n try {\n canonicalParent = await realpath(parent)\n break\n } catch (error) {\n if (typeof error !== 'object' || error === null || !('code' in error) || error.code !== 'ENOENT') throw error\n suffix.unshift(PATH.basename(parent))\n parent = PATH.dirname(parent)\n }\n }\n const resolved = PATH.join(canonicalParent, ...suffix)\n if (resolved === source || resolved.startsWith(`${source}${PATH.sep}`)) throw new TypeError('Migration output must be outside the source store')\n return resolved\n}\n\nasync function writeReport(path: string, report: ReceiverMigrationReport): Promise<void> {\n const file = await open(path, 'wx', 0o600)\n try {\n await file.writeFile(`${JSON.stringify(report, null, 2)}\\n`)\n await file.sync()\n } finally {\n await file.close()\n }\n await syncDirectory(PATH.dirname(path))\n}\n\nfunction importEntries(database: ReturnType<typeof openReceiverAuthority>['database'], entries: readonly ReceiverMigrationEntry[]): void {\n database.exec('BEGIN IMMEDIATE')\n try {\n for (const entry of entries) {\n // New terminal marker attests to the reviewed migration decision; it does\n // not reconstruct any historical consumer lease or unrecorded ack.\n const terminalToken = entry.state === 'completed' ? randomBytes(16).toString('hex') : null\n const result = database.prepare('INSERT INTO receiver_queue(body,state,terminal_token,terminal_operation) VALUES(?,?,?,?)')\n .run(entry.state === 'completed' ? null : JSON.stringify(entry.wake), entry.state, terminalToken, terminalToken === null ? null : 'ack')\n if (entry.receipt === undefined) continue // Explicit standalone queue; no invented admission.\n const receipt = entry.receipt\n database.prepare('INSERT INTO receiver_wakes(identity,audience,publisher,wake_id,event_hash,receipt,authorization,queue_id) VALUES(?,?,?,?,?,?,?,?)')\n .run(\n receipt.id,\n receipt.audience,\n receipt.publisher,\n receipt.wakeId,\n receipt.eventHash,\n JSON.stringify(receipt),\n JSON.stringify({\n kind: 'legacy-migration',\n evidence: entry.evidence,\n artifacts: entry.paths,\n freshAuthorization: false,\n ...(terminalToken === null ? {} : { completion: { kind: 'reviewed-migration-decision', terminalToken } }),\n }),\n result.lastInsertRowid,\n )\n for (const token of entry.tokens) {\n database.prepare('INSERT INTO receiver_tokens(identity,wake_identity,event_hash,wake_id,retain_until) VALUES(?,?,?,?,?)')\n .run(receiverIdentity([token.audience, token.publisher, token.jwtId]), receipt.id, token.eventHash, token.wakeId, token.retainJwtUntil)\n }\n }\n database.exec('COMMIT')\n } catch (error) {\n database.exec('ROLLBACK')\n throw error\n }\n}\n\nasync function publishMigratedStore(target: string, entries: readonly ReceiverMigrationEntry[], verifySource: () => Promise<void>): Promise<void> {\n ensurePrivateDirectory(PATH.dirname(target))\n const staging = PATH.join(PATH.dirname(target), `.receiver-migration-${randomBytes(8).toString('hex')}`)\n await mkdir(staging, { mode: 0o700 })\n const file = PATH.join(staging, 'receiver.sqlite')\n try {\n const receiver = openReceiverAuthority(file)\n try {\n importEntries(receiver.database, entries)\n receiver.database.exec('PRAGMA wal_checkpoint(TRUNCATE)')\n } finally {\n receiver.close()\n }\n await verifySource()\n // Exclusive publication never overwrites a pre-existing receiver.\n await link(file, target)\n await syncDirectory(PATH.dirname(target))\n await unlink(file)\n } finally {\n await rm(staging, { recursive: true, force: true })\n }\n}\n\ninterface MigrationLocations {\n readonly backupPath?: string\n readonly sourcePath: string\n readonly targetPath?: string\n}\n\nasync function prepareLocations(options: ReceiverMigrationOptions): Promise<MigrationLocations> {\n if (options?.consumersStopped !== true) throw new TypeError('Migration requires every source writer and consumer to be stopped')\n if (!['filesystem', 'sqlite-queue'].includes(options.source.kind)) throw new TypeError('Unknown receiver migration source format')\n if (options.source.kind === 'sqlite-queue' && options.source.scope !== 'queue-only') throw new TypeError('SQLite queue migration requires explicit queue-only scope')\n const sourcePath = await realpath(options.source.path)\n if (!(await lstat(options.source.path)).isDirectory()) throw new TypeError('Migration source must be an owned store directory')\n const backupPath = options.backupPath === undefined ? undefined : await outsideSource(sourcePath, options.backupPath)\n const targetPath = options.targetPath === undefined ? undefined : await outsideSource(sourcePath, options.targetPath)\n if (!options.dryRun && (backupPath === undefined || targetPath === undefined)) throw new TypeError('Execution requires distinct backupPath and targetPath')\n if (backupPath !== undefined && targetPath !== undefined\n && (targetPath === backupPath || targetPath.startsWith(`${backupPath}${PATH.sep}`) || backupPath.startsWith(`${targetPath}${PATH.sep}`))) {\n throw new TypeError('Backup and target paths must be separate')\n }\n return {\n backupPath, sourcePath, targetPath,\n }\n}\n\nasync function prepareCopy(options: ReceiverMigrationOptions, paths: MigrationLocations, scratch: string): Promise<readonly ReceiverMigrationFile[]> {\n if (options.dryRun) return await snapshotMigrationSource(paths.sourcePath, PATH.join(scratch, 'source'))\n await mkdir(PATH.dirname(paths.backupPath!), { recursive: true, mode: 0o700 })\n await mkdir(paths.backupPath!, { mode: 0o700 })\n const files = await snapshotMigrationSource(paths.sourcePath, PATH.join(paths.backupPath!, 'source'))\n await syncDirectory(paths.backupPath!)\n await snapshotMigrationSource(PATH.join(paths.backupPath!, 'source'), PATH.join(scratch, 'source'))\n return files\n}\n\nfunction migrationReport(\n paths: MigrationLocations,\n files: readonly ReceiverMigrationFile[],\n plan: ReceiverMigrationPlan,\n options: ReceiverMigrationOptions,\n): ReceiverMigrationReport {\n const dryRun = options.dryRun === true\n const ready = plan.unknown.length === 0\n return {\n ...(paths.backupPath === undefined || dryRun ? {} : { backupPath: paths.backupPath }),\n completedIdentities: plan.entries.filter(entry => entry.state === 'completed').length,\n executed: ready && !dryRun,\n files,\n pendingIdentities: plan.entries.filter(entry => entry.state === 'pending').length,\n quarantined: plan.quarantined,\n ready,\n reviews: (options.reviews ?? []).map(review => ({\n action: review.action,\n evidence: review.evidence,\n identity: review.identity,\n ...(review.queueOrder === undefined ? {} : { queueOrder: review.queueOrder }),\n })),\n rollback,\n selected: plan.entries.map(entry => ({\n ...(entry.state === 'completed' ? { completionProvenance: 'Fresh reviewed migration tombstone; no historical lease or ack inferred' as const } : {}),\n eventHash: entry.receipt?.eventHash ?? entry.wake?.eventHash,\n identity: entry.identity,\n paths: entry.paths,\n ...(entry.queueOrder === undefined ? {} : { queueOrder: entry.queueOrder }),\n state: entry.state,\n })),\n sourceBytes: files.reduce((total, file) => total + file.bytes, 0),\n sourcePath: paths.sourcePath,\n sourceUnchanged: true,\n tokenRecords: plan.entries.reduce((total, entry) => total + entry.tokens.length, 0),\n unknown: plan.unknown,\n ...(paths.targetPath === undefined || dryRun ? {} : { targetPath: paths.targetPath }),\n }\n}\n\n/** Offline copy-only migration. Unknown history blocks target publication. */\nexport async function migrateReceiverStore(options: ReceiverMigrationOptions): Promise<ReceiverMigrationReport> {\n const paths = await prepareLocations(options)\n const scratch = await mkdtemp(PATH.join(OS.tmpdir(), 'event-kit-receiver-migration-'))\n try {\n const files = await prepareCopy(options, paths, scratch)\n const verify = async () => {\n await verifyMigrationSource(paths.sourcePath, files)\n }\n await verify()\n const plan = await inventoryReceiverMigration(options.source, PATH.join(scratch, 'source'), files, options.reviews ?? [])\n if (!options.dryRun) await writeReport(PATH.join(paths.backupPath!, 'migration-plan.json'), { ...migrationReport(paths, files, plan, options), executed: false })\n if (plan.unknown.length === 0 && !options.dryRun) await publishMigratedStore(paths.targetPath!, plan.entries, verify)\n await verify()\n const report = migrationReport(paths, files, plan, options)\n if (!options.dryRun) await writeReport(PATH.join(paths.backupPath!, 'migration-report.json'), report)\n return report\n } finally {\n await rm(scratch, { recursive: true, force: true })\n }\n}\n\nexport interface LegacyIdOnlyReducerCheckpoint {\n readonly appliedWakeIds: readonly string[]\n readonly lastProcessedPosition: number\n}\nexport interface MigratedReducerCheckpoint {\n readonly appliedWakes: readonly Pick<AdmittedWake, 'audience' | 'eventHash' | 'publisher' | 'wakeId'>[]\n readonly lastProcessedPosition: number\n}\n\n/** Requires one externally established exact scoped hash mapping for every historical ID. */\nexport function migrateIdOnlyReducerCheckpoint(\n checkpoint: LegacyIdOnlyReducerCheckpoint,\n mappings: MigratedReducerCheckpoint['appliedWakes'],\n): MigratedReducerCheckpoint {\n if (!Number.isSafeInteger(checkpoint.lastProcessedPosition) || checkpoint.lastProcessedPosition < -1) throw new TypeError('Invalid historical checkpoint position')\n const ids = new Set(checkpoint.appliedWakeIds.map(id => WakeIdZod.parse(id)))\n const records = new Map<string, MigratedReducerCheckpoint['appliedWakes'][number]>()\n for (const mapping of mappings) {\n const record = {\n audience: WakeJwtAudienceZod.parse(mapping.audience),\n eventHash: HashZod.parse(mapping.eventHash),\n publisher: NormalizedAddressZod.parse(mapping.publisher),\n wakeId: WakeIdZod.parse(mapping.wakeId),\n }\n if (!ids.has(record.wakeId) || records.has(record.wakeId)) throw new TypeError('Checkpoint mapping is extraneous or ambiguous')\n records.set(record.wakeId, record)\n }\n if (records.size !== ids.size) throw new TypeError('Every historical wake ID requires an exact scoped hash mapping')\n return { appliedWakes: [...ids].map(id => records.get(id)!), lastProcessedPosition: checkpoint.lastProcessedPosition }\n}\n", "import { readFile } from 'node:fs/promises'\nimport PATH from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nimport type { AdmittedWake, WakeAdmissionReceipt } from '@xyo-network/event-kit-protocol'\nimport { parseAdmittedWake } from '@xyo-network/event-kit-protocol'\nimport {\n HashZod, NonnegativeJsonSafeIntegerZod, NormalizedAddressZod, WakeIdZod, WakeJwtAudienceZod, WakeJwtIdZod,\n} from '@xyo-network/event-kit-schemas'\nimport { z } from 'zod'\n\nimport { receiverIdentity } from './receiverAuthority.ts'\nimport { migrationRelativePath } from './receiverMigrationSnapshot.ts'\nimport type {\n FilesystemReceiverMigrationSource, LegacyMigrationToken, ReceiverMigrationEntry, ReceiverMigrationFile, ReceiverMigrationIssue,\n ReceiverMigrationPlan, ReceiverMigrationQueueOrder, ReceiverMigrationReview, ReceiverMigrationSource, SqliteQueueMigrationSource,\n} from './receiverMigrationTypes.ts'\n\nconst ReceiptZod = z.strictObject({\n audience: WakeJwtAudienceZod, eventHash: HashZod, id: HashZod, publisher: NormalizedAddressZod, wakeId: WakeIdZod,\n})\nconst recordShape = {\n audience: WakeJwtAudienceZod, eventHash: HashZod, publisher: NormalizedAddressZod, receipt: ReceiptZod, wakeId: WakeIdZod,\n}\nconst WakeRecordZod = z.strictObject(recordShape)\nconst TokenRecordZod = z.strictObject({\n ...recordShape, jwtId: WakeJwtIdZod, retainJwtUntil: NonnegativeJsonSafeIntegerZod,\n})\ntype LegacyWakeRecord = z.infer<typeof WakeRecordZod>\n\ninterface Group {\n readonly bodies: { readonly order: Exclude<ReceiverMigrationQueueOrder, { readonly kind: 'reviewed-after-known' }>; readonly path: string; readonly wake: AdmittedWake }[]\n readonly identity: string\n readonly paths: Set<string>\n readonly queueOnly: boolean\n readonly reasons: string[]\n readonly receipts: LegacyWakeRecord[]\n readonly tokens: LegacyMigrationToken[]\n}\n\nexport function validateMigrationReceipt(receipt: WakeAdmissionReceipt): WakeAdmissionReceipt {\n const parsed = ReceiptZod.parse(receipt)\n if (parsed.id !== receiverIdentity([parsed.audience, parsed.publisher, parsed.wakeId])) throw new TypeError('Legacy receipt ID does not match its scoped identity')\n return parsed\n}\n\nfunction validateRecord(record: LegacyWakeRecord): void {\n const receipt = validateMigrationReceipt(record.receipt)\n if (receipt.audience !== record.audience || receipt.publisher !== record.publisher\n || receipt.wakeId !== record.wakeId || receipt.eventHash !== record.eventHash) {\n throw new TypeError('Legacy receipt does not match its record')\n }\n}\n\nfunction scope(value: Pick<AdmittedWake, 'audience' | 'publisher' | 'wakeId'>): string {\n return receiverIdentity([value.audience, value.publisher, value.wakeId])\n}\n\nfunction issue(group: Group, reason: string): ReceiverMigrationIssue {\n return {\n identity: group.identity, paths: [...group.paths], reason,\n }\n}\n\nfunction admissionIssue(group: Group, receipt: WakeAdmissionReceipt | undefined, wake: AdmittedWake | undefined, review?: ReceiverMigrationReview): ReceiverMigrationIssue | undefined {\n if (receipt?.id !== group.identity) return issue(group, 'Admission receipt is missing or disagrees with reviewed identity')\n if (review?.action !== 'completed' && (wake === undefined || scope(wake) !== group.identity || wake.eventHash !== receipt.eventHash)) {\n return issue(group, 'Receipt has no exact validated pending body; completion remains unknown')\n }\n if (group.tokens.some(token => token.eventHash !== receipt.eventHash || JSON.stringify(token.receipt) !== JSON.stringify(receipt))) {\n return issue(group, 'Token history conflicts with the reviewed receipt')\n }\n return review === undefined && (group.reasons.length > 0 || group.receipts.some(record => record.eventHash !== receipt.eventHash)\n || group.bodies.some(body => body.wake.eventHash !== receipt.eventHash))\n ? issue(group, 'Legacy body/receipt mappings disagree; explicit review is required')\n : undefined\n}\n\nfunction queueIssue(\n group: Group,\n receipt: WakeAdmissionReceipt | undefined,\n wake: AdmittedWake | undefined,\n review?: ReceiverMigrationReview,\n): ReceiverMigrationIssue | undefined {\n return group.reasons.length > 0 || wake === undefined || receipt !== undefined || review?.action === 'completed'\n ? issue(group, 'Standalone queue migration cannot infer receipt or completion history')\n : undefined\n}\n\nasync function selectEntry(group: Group, review?: ReceiverMigrationReview): Promise<ReceiverMigrationEntry | ReceiverMigrationIssue> {\n const receipt = review?.receipt === undefined ? group.receipts[0]?.receipt : validateMigrationReceipt(review.receipt)\n const wake = review?.wake === undefined\n ? group.bodies.find(body => receipt === undefined || body.wake.eventHash === receipt.eventHash)?.wake\n : await parseAdmittedWake(review.wake)\n const invalid = group.queueOnly ? queueIssue(group, receipt, wake, review) : admissionIssue(group, receipt, wake, review)\n if (invalid !== undefined) return invalid\n const queueOrder = review?.action === 'completed' ? undefined : selectQueueOrder(group, wake!, review)\n return queueOrder !== undefined && !('kind' in queueOrder) ? queueOrder : migrationEntry(group, receipt, wake, queueOrder, review)\n}\n\nfunction migrationEntry(\n group: Group,\n receipt: WakeAdmissionReceipt | undefined,\n wake: AdmittedWake | undefined,\n queueOrder: ReceiverMigrationQueueOrder | undefined,\n review?: ReceiverMigrationReview,\n): ReceiverMigrationEntry {\n return {\n evidence: review?.evidence ?? 'Exact validated legacy receipt and pending/inflight body; no fresh grant inferred',\n identity: group.identity,\n paths: [...group.paths],\n ...(receipt === undefined ? {} : { receipt }),\n ...(queueOrder === undefined ? {} : { queueOrder }),\n state: review?.action === 'completed' ? 'completed' : 'pending',\n tokens: group.tokens,\n ...(wake === undefined ? {} : { wake }),\n }\n}\n\nfunction compareQueueOrder(left: ReceiverMigrationQueueOrder, right: ReceiverMigrationQueueOrder): number {\n if (left.kind === 'reviewed-after-known') return right.kind === 'reviewed-after-known' ? 0 : 1\n if (right.kind === 'reviewed-after-known') return -1\n if (left.kind === 'sqlite-row-id' && right.kind === 'sqlite-row-id') return left.id - right.id\n if (left.kind === 'filesystem-entry-name' && right.kind === 'filesystem-entry-name') {\n // Match the legacy queue's default Array.toSorted() comparison exactly.\n return left.name < right.name ? -1 : left.name > right.name ? 1 : 0\n }\n throw new TypeError('Migration cannot combine unrelated source queue orders')\n}\n\nfunction selectQueueOrder(group: Group, wake: AdmittedWake, review?: ReceiverMigrationReview): ReceiverMigrationQueueOrder | ReceiverMigrationIssue {\n const matches = group.bodies.filter(body => body.wake.eventHash === wake.eventHash)\n .toSorted((left, right) => compareQueueOrder(left.order, right.order))\n const original = matches[0]?.order\n if (original !== undefined) return review?.queueOrder === undefined ? original : issue(group, 'Reviewed placement cannot override a matching original queue reference')\n return review?.queueOrder === undefined\n ? issue(group, 'Original queue order is unknown; an explicit after-known placement review is required')\n : { kind: 'reviewed-after-known', evidence: review.queueOrder.evidence }\n}\n\nfunction compareEntries(left: ReceiverMigrationEntry, right: ReceiverMigrationEntry): number {\n if (left.state === 'completed') return right.state === 'completed' ? 0 : 1\n return right.state === 'completed' ? -1 : compareQueueOrder(left.queueOrder!, right.queueOrder!)\n}\n\ninterface Collector {\n readonly groupFor: (identity: string, path: string, queueOnly?: boolean) => Group\n readonly groups: Map<string, Group>\n readonly invalid: (path: string, reason: string) => void\n readonly recognized: Set<string>\n}\n\nfunction createCollector(): Collector {\n const groups = new Map<string, Group>()\n const groupFor = (identity: string, path: string, queueOnly = false): Group => {\n let group = groups.get(identity)\n if (group === undefined) {\n group = {\n identity, paths: new Set(), bodies: [], receipts: [], reasons: [], tokens: [], queueOnly,\n }\n groups.set(identity, group)\n }\n group.paths.add(path)\n return group\n }\n return {\n groups,\n groupFor,\n recognized: new Set(),\n invalid(path, reason) { groupFor(`artifact:${path}`, path).reasons.push(reason) },\n }\n}\n\nfunction filesystemKind(queueRelative: string, inboxRelative: string): 'body' | 'receipt' | 'token' | undefined {\n if (/^(pending|inflight)\\/[\\w.-]+\\.json$/.test(queueRelative)) return 'body'\n if (/^wakes\\/[a-f0-9]{64}\\.json$/.test(inboxRelative)) return 'receipt'\n return /^tokens\\/[a-f0-9]{64}\\.json$/.test(inboxRelative) ? 'token' : undefined\n}\n\nasync function readFilesystemRecord(collector: Collector, absolute: string, path: string, kind: 'body' | 'receipt' | 'token'): Promise<void> {\n const raw: unknown = JSON.parse(await readFile(absolute, 'utf8'))\n if (kind === 'body') {\n const wake = await parseAdmittedWake(raw)\n collector.groupFor(scope(wake), path).bodies.push({\n order: {\n kind: 'filesystem-entry-name', name: PATH.basename(path), path,\n },\n path,\n wake,\n })\n return\n }\n const record = kind === 'receipt' ? WakeRecordZod.parse(raw) : TokenRecordZod.parse(raw)\n validateRecord(record)\n const key = kind === 'receipt' ? scope(record) : receiverIdentity([record.audience, record.publisher, (record as LegacyMigrationToken).jwtId])\n if (PATH.basename(path) !== `${key}.json`) throw new TypeError('Legacy record filename disagrees with identity')\n const group = collector.groupFor(scope(record), path)\n if (kind === 'receipt') group.receipts.push(record)\n else group.tokens.push(record as LegacyMigrationToken)\n}\n\nasync function scanFilesystem(source: FilesystemReceiverMigrationSource, root: string, files: readonly ReceiverMigrationFile[], collector: Collector): Promise<void> {\n const queueRoot = migrationRelativePath(root, source.queueDirectory)\n const inboxRoot = migrationRelativePath(root, source.inboxDirectory)\n for (const file of files) {\n const absolute = PATH.join(root, file.path)\n const kind = filesystemKind(PATH.relative(queueRoot, absolute), PATH.relative(inboxRoot, absolute))\n if (kind === undefined) continue\n collector.recognized.add(file.path)\n try {\n await readFilesystemRecord(collector, absolute, file.path, kind)\n } catch {\n collector.invalid(file.path, 'Malformed, corrupt, or incorrectly bound legacy record; exact bytes archived')\n }\n }\n}\n\nasync function scanSqlite(source: SqliteQueueMigrationSource, root: string, collector: Collector): Promise<void> {\n if (source.scope !== 'queue-only') throw new TypeError('SQLite queue migration requires explicit queue-only scope')\n const file = migrationRelativePath(root, source.databaseFile)\n for (const name of [source.databaseFile, `${source.databaseFile}-wal`, `${source.databaseFile}-shm`, `${source.databaseFile}-journal`]) collector.recognized.add(PATH.normalize(name))\n const database = new DatabaseSync(file, { readOnly: true })\n try {\n const tables = database.prepare(\"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\").all()\n if (tables.length !== 1 || tables[0]?.name !== 'wake_queue') throw new TypeError('Expected a legacy queue-only SQLite store')\n for (const row of database.prepare('SELECT id,body,state FROM wake_queue ORDER BY id').all()) {\n const path = `${source.databaseFile}#wake_queue/${String(row.id)}`\n try {\n if (typeof row.id !== 'number' || !Number.isSafeInteger(row.id)\n || typeof row.body !== 'string' || (row.state !== 'pending' && row.state !== 'inflight')) throw new TypeError('Invalid legacy queue row')\n const wake = await parseAdmittedWake(JSON.parse(row.body) as unknown)\n collector.groupFor(`queue:${String(row.id)}`, path, true).bodies.push({\n order: {\n kind: 'sqlite-row-id', id: row.id, path,\n },\n path,\n wake,\n })\n } catch {\n collector.invalid(path, 'Invalid legacy SQLite queue row; exact database bytes archived')\n }\n }\n } finally {\n database.close()\n }\n}\n\n/** Inspects a disposable private copy only. Originals and exact-byte backups are never opened by SQLite. */\nexport async function inventoryReceiverMigration(\n source: ReceiverMigrationSource,\n copiedRoot: string,\n files: readonly ReceiverMigrationFile[],\n reviews: readonly ReceiverMigrationReview[],\n): Promise<ReceiverMigrationPlan> {\n const collector = createCollector()\n if (source.kind === 'filesystem') await scanFilesystem(source, copiedRoot, files, collector)\n else await scanSqlite(source, copiedRoot, collector)\n for (const file of files) {\n if (!collector.recognized.has(file.path)) collector.invalid(file.path, 'Unclassified source artifact; explicit review or quarantine is required')\n }\n return await finalizeGroups(collector.groups, reviews)\n}\n\nfunction reviewMap(groups: ReadonlyMap<string, Group>, reviews: readonly ReceiverMigrationReview[]): ReadonlyMap<string, ReceiverMigrationReview> {\n const reviewed = new Map<string, ReceiverMigrationReview>()\n for (const review of reviews) {\n if (!['pending', 'completed', 'quarantine'].includes(review.action)\n || review.evidence.trim().length === 0 || reviewed.has(review.identity)) throw new TypeError('Reviews require unique identities, an explicit action and external evidence references')\n if (!groups.has(review.identity)) throw new TypeError('Review does not correspond to an inventoried identity')\n if (review.queueOrder !== undefined && (review.action !== 'pending' || review.queueOrder.kind !== 'after-known'\n || review.queueOrder.evidence.trim().length === 0)) throw new TypeError('Queue placement requires a pending review, after-known choice and separate placement evidence')\n reviewed.set(review.identity, review)\n }\n return reviewed\n}\n\nasync function finalizeGroups(groups: ReadonlyMap<string, Group>, reviews: readonly ReceiverMigrationReview[]): Promise<ReceiverMigrationPlan> {\n const reviewed = reviewMap(groups, reviews)\n const entries: ReceiverMigrationEntry[] = []\n const quarantined: ReceiverMigrationIssue[] = []\n const unknown: ReceiverMigrationIssue[] = []\n for (const group of groups.values()) {\n const review = reviewed.get(group.identity)\n if (review?.action === 'quarantine') {\n quarantined.push(issue(group, review.evidence))\n continue\n }\n if (group.identity.startsWith('artifact:')) {\n unknown.push(issue(group, group.reasons.join('; ')))\n continue\n }\n const selected = await selectEntry(group, review)\n if ('reason' in selected) unknown.push(selected)\n else {\n entries.push(selected)\n const rejectedBodies = group.bodies.filter(body => selected.receipt !== undefined && body.wake.eventHash !== selected.receipt.eventHash)\n if (rejectedBodies.length > 0) quarantined.push({\n identity: `reviewed-conflicts:${group.identity}`,\n paths: rejectedBodies.map(body => body.path),\n reason: 'Reviewed mapping excluded conflicting bodies; exact bytes remain in the backup',\n })\n }\n }\n return {\n entries: entries.toSorted(compareEntries), quarantined, unknown,\n }\n}\n", "import { createHash } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport {\n lstat, mkdir, open, readdir,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport { syncDirectory } from './filesystemDurability.ts'\nimport type { ReceiverMigrationFile } from './receiverMigrationTypes.ts'\n\n/** Refuse symlinks and escaping configuration rather than following other stores. */\nexport function migrationRelativePath(root: string, relative: string): string {\n if (PATH.isAbsolute(relative)) throw new TypeError('Migration store paths must be relative')\n const resolved = PATH.resolve(root, relative)\n if (resolved !== root && !resolved.startsWith(`${root}${PATH.sep}`)) throw new TypeError('Migration path escapes its source store')\n return resolved\n}\n\nasync function readExact(path: string): Promise<{ bytes: Buffer; mode: number }> {\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)\n try {\n const before = await file.stat()\n if (!before.isFile()) throw new TypeError('Migration source must contain ordinary files only')\n const bytes = await file.readFile()\n const after = await file.stat()\n if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ino !== after.ino) {\n throw new Error('Migration source changed while being copied')\n }\n return { bytes, mode: before.mode & 0o777 }\n } finally {\n await file.close()\n }\n}\n\nexport async function snapshotMigrationSource(root: string, destination?: string): Promise<readonly ReceiverMigrationFile[]> {\n const files: ReceiverMigrationFile[] = []\n async function visit(relative: string): Promise<void> {\n const source = PATH.join(root, relative)\n const info = await lstat(source)\n if (info.isSymbolicLink()) throw new TypeError('Migration source symlinks are unsupported')\n if (info.isDirectory()) {\n if (destination !== undefined) await mkdir(PATH.join(destination, relative), { mode: 0o700 })\n for (const child of (await readdir(source)).toSorted()) await visit(PATH.join(relative, child))\n if (destination !== undefined) await syncDirectory(PATH.join(destination, relative))\n return\n }\n const { bytes, mode } = await readExact(source)\n files.push({\n bytes: bytes.length, mode, path: relative, sha256: createHash('sha256').update(bytes).digest('hex'),\n })\n if (destination === undefined) return\n const target = await open(PATH.join(destination, relative), 'wx', 0o600)\n try {\n await target.writeFile(bytes)\n await target.sync()\n } finally {\n await target.close()\n }\n }\n await visit('')\n return files\n}\n\nexport async function verifyMigrationSource(root: string, files: readonly ReceiverMigrationFile[]): Promise<void> {\n const current = await snapshotMigrationSource(root)\n if (JSON.stringify(current) !== JSON.stringify(files)) throw new Error('Migration source changed; stop every owner and repeat on a new copy')\n}\n", "import { Buffer } from 'node:buffer'\n\nimport type { FetchGetUrlFunc } from 'ethers'\n\nimport { publisherAbortScope } from './abort.ts'\nexport interface BoundedPublisherFetchOptions {\n readonly maxConcurrency?: number\n readonly maxResponseBytes?: number\n readonly requestTimeoutMs?: number\n readonly signal?: AbortSignal\n}\n/** Per-instance SDK transport: aborts the real request, including its body, without changing global fetch. */\nexport function createBoundedPublisherFetch(options: BoundedPublisherFetchOptions = {}) {\n const owner = new AbortController()\n const timeout = options.requestTimeoutMs ?? 10_000\n const maximum = options.maxResponseBytes ?? 16 * 1024 * 1024\n const concurrency = options.maxConcurrency ?? 16\n if (!Number.isSafeInteger(timeout) || timeout < 100 || timeout > 60_000\n || !Number.isSafeInteger(maximum) || maximum < 1 || maximum > 64 * 1024 * 1024\n || !Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 64)\n throw new Error('Invalid publisher fetch limits')\n const active = new Set<Promise<Response>>()\n const nativeFetch = globalThis.fetch.bind(globalThis)\n const fetchFn: typeof globalThis.fetch = (input, init) => {\n if (active.size >= concurrency)\n return Promise.reject(new Error('Publisher HTTP concurrency limit exceeded'))\n const operation = (async () => {\n const signals = [owner.signal,\n ...(options.signal === undefined ? [] : [options.signal]),\n ...(init?.signal == null ? [] : [init.signal]),\n ...(input instanceof Request ? [input.signal] : [])]\n const scope = publisherAbortScope(signals, timeout)\n try {\n scope.signal.throwIfAborted()\n const response = await nativeFetch(input, {\n ...init, redirect: 'error', signal: scope.signal,\n })\n if (response.body === null)\n return response\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done)\n break\n const bytes: unknown = chunk.value\n if (!(bytes instanceof Uint8Array)) throw new TypeError('Publisher HTTP body returned a non-byte chunk')\n size += bytes.byteLength\n if (size > maximum) {\n await reader.cancel()\n throw new Error('Publisher HTTP body exceeds its bound')\n }\n chunks.push(bytes)\n }\n } finally {\n reader.releaseLock()\n }\n const headers = new Headers(response.headers)\n headers.delete('content-encoding')\n headers.delete('transfer-encoding')\n headers.set('content-length', String(size))\n return new Response(Buffer.concat(chunks), {\n status: response.status, statusText: response.statusText, headers,\n })\n } finally {\n scope.dispose()\n }\n })()\n active.add(operation)\n void operation.then(() => active.delete(operation), () => active.delete(operation))\n return operation\n }\n return {\n fetchFn,\n async close() {\n owner.abort()\n await Promise.allSettled(active)\n },\n get activeRequests() {\n return active.size\n },\n }\n}\n\n/** Ethers' documented per-request HTTP hook, without its unbounded Node body reader. */\nexport function createBoundedPublisherEthersTransport(options: BoundedPublisherFetchOptions = {}) {\n const bounded = createBoundedPublisherFetch(options)\n const getUrl: FetchGetUrlFunc = async (request, cancellation) => {\n const controller = new AbortController()\n cancellation?.addListener(() => controller.abort())\n cancellation?.checkSignal()\n const response = await bounded.fetchFn(request.url, {\n body: request.body === null ? undefined : Buffer.from(request.body),\n headers: request.headers,\n method: request.method,\n signal: controller.signal,\n })\n return {\n body: new Uint8Array(await response.arrayBuffer()),\n headers: Object.fromEntries(response.headers),\n statusCode: response.status,\n statusMessage: response.statusText,\n }\n }\n return {\n getUrl,\n async close() { await bounded.close() },\n get activeRequests() { return bounded.activeRequests },\n }\n}\n", "import { clearTimeout, setTimeout } from 'node:timers'\n\n/** Own every listener/timer used by a bounded operation; disposal is mandatory. */\nexport function publisherAbortScope(signals: readonly AbortSignal[], timeoutMs?: number) {\n const controller = new AbortController()\n const abort = () => controller.abort()\n const timer = timeoutMs === undefined ? undefined : setTimeout(abort, timeoutMs)\n timer?.unref()\n for (const signal of signals) {\n if (signal.aborted) controller.abort()\n else signal.addEventListener('abort', abort, { once: true })\n }\n return {\n signal: controller.signal,\n dispose() {\n if (timer !== undefined) clearTimeout(timer)\n for (const signal of signals) signal.removeEventListener('abort', abort)\n },\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport { decryptWakeSubscription, sourceWakeFilterHash } from '@xyo-network/event-kit-protocol'\nimport type {\n BestEffortDeliveryPolicy, EndpointChallengeResponse, WakeDeliveryMode,\n} from '@xyo-network/event-kit-schemas'\nimport { EndpointChallengeResponseZod } from '@xyo-network/event-kit-schemas'\nimport type { FinalizedSubscriptionTuple } from '@xyo-network/event-kit-statement-graph'\n\nimport type { PublisherEncryptionKeyCustody, PublisherHandshakeClient } from '../handshakeClients.ts'\nimport { publisherAbortScope } from './abort.ts'\nimport type { PublisherHttpsTransport } from './httpsTransport.ts'\nimport type {\n PublisherRuntimeDiscovery, PublisherRuntimeDiscoveryStatus, PublisherRuntimeSubscription,\n} from './publisherRuntime.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\ninterface PendingChallenge {\n readonly challengeHash: string\n readonly expiresAt: number\n readonly response?: EndpointChallengeResponse\n readonly subscriber: string\n readonly subscription: string\n}\n/** Real D005 lifecycle discovery. Off-chain configuration never grants delivery authority. */\nexport function createPublisherHandshakeDiscovery(options: {\n readonly authorizationChainId: string\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly client: PublisherHandshakeClient\n readonly deliveryMode?: WakeDeliveryMode\n readonly keys: PublisherEncryptionKeyCustody\n readonly maxSubscriptions?: number\n readonly nowSeconds?: () => number\n readonly publisher: string\n readonly serviceHash?: string\n readonly state: SqlitePublisherState\n readonly transport: PublisherHttpsTransport\n}): PublisherRuntimeDiscovery {\n const clock = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const owner = new AbortController()\n let accepting: Promise<void> | undefined\n let viewing: ReturnType<PublisherHandshakeClient['subscriptions']> | undefined\n let status: PublisherRuntimeDiscoveryStatus = {\n authorizationChainId: options.authorizationChainId,\n keyLoaded: false,\n activeKeyIds: [],\n pendingSubscriptions: 0,\n rejectedSubscriptions: 0,\n challengeFailures: 0,\n }\n function selectedTuple(tuple: FinalizedSubscriptionTuple): boolean {\n return (options.serviceHash === undefined || tuple.service.objectHash === options.serviceHash)\n && (options.deliveryMode === undefined || tuple.service.body.deliveryMode === options.deliveryMode)\n && (options.deliveryMode === undefined || tuple.subscription.body.deliveryMode === options.deliveryMode)\n && (options.deliveryMode === undefined || isDeepStrictEqual(tuple.service.body.bestEffort, options.bestEffort))\n }\n async function activeView(signal: AbortSignal) {\n signal.throwIfAborted()\n // A timed-out caller does not create a second SDK replay while the first\n // remains in flight. The configured REST transport aborts actual reads.\n viewing ??= (async () => {\n try {\n return await options.client.subscriptions()\n } finally {\n viewing = undefined\n }\n })()\n const view = await viewing\n signal.throwIfAborted()\n if (!view.ok || view.indexedThrough !== view.finalizedHead)\n throw new Error('Publisher subscription view is unavailable or stale')\n status = {\n ...status,\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n pendingSubscriptions: view.subscriptions.filter(item => item.state === 'pending' && item.tuples.some(selectedTuple)).length,\n rejectedSubscriptions: view.rejections.length,\n }\n return view\n }\n async function acceptCandidate(subscriber: string, subscription: string, signal: AbortSignal) {\n try {\n let pending = options.state.get<PendingChallenge>('outbound-challenges', subscription)\n if (pending !== undefined && pending.response === undefined && clock() >= pending.expiresAt)\n pending = undefined\n if (pending === undefined) {\n const issued = await options.client.issueChallenge({\n issuedAt: clock(), lifetimeSeconds: 300, subscriber: subscriber, subscription,\n })\n pending = {\n challengeHash: issued.challengeHash, subscriber: subscriber, subscription, expiresAt: issued.challenge.expiresAt,\n }\n options.state.set('outbound-challenges', subscription, pending)\n }\n if (pending.response === undefined) {\n const begun = await options.client.beginChallenge({ challengeHash: pending.challengeHash, nowSeconds: clock })\n if (begun.kind !== 'started')\n return\n signal.throwIfAborted()\n const response = await options.transport.post(begun.target.endpoint, begun.challenge, signal)\n if (response.status !== 200)\n throw new Error('Endpoint challenge was rejected')\n pending = { ...pending, response: EndpointChallengeResponseZod.parse(response.body) }\n options.state.set('outbound-challenges', subscription, pending)\n }\n signal.throwIfAborted()\n const response = pending.response\n if (response === undefined)\n throw new Error('Endpoint proof is unavailable')\n await options.client.completeChallengeAndAccept({\n ...pending, response, nowSeconds: clock,\n })\n } catch {\n if (signal.aborted)\n return\n const failures = options.state.get<number>('challenge-failures', subscription) ?? 0\n options.state.set('challenge-failures', subscription, failures + 1)\n const pending = options.state.get<PendingChallenge>('outbound-challenges', subscription)\n if (pending !== undefined && clock() >= pending.expiresAt)\n options.state.remove('outbound-challenges', subscription)\n }\n }\n\n async function accept(signal: AbortSignal) {\n signal.throwIfAborted()\n const now = clock()\n if (now < (options.state.get<number>('challenge-rate', 'next-pass') ?? 0))\n return\n options.state.set('challenge-rate', 'next-pass', now + 10)\n const found = await options.client.acceptanceCandidates()\n if (!found.ok)\n throw new Error('Publisher acceptance candidates are unavailable')\n const offset = options.state.get<number>('challenge-rate', 'offset') ?? 0\n const candidates = found.candidates.filter(candidate => selectedTuple(candidate.tuple))\n let attempted = 0\n // Bound inspected candidates and rotate the starting point: four failed\n // candidates must not permanently prevent the fifth from being challenged.\n for (let index = 0; index < Math.min(candidates.length, 128) && attempted < 4; index += 1) {\n const candidate = candidates[(offset + index) % candidates.length]\n if (candidate === undefined)\n break\n options.state.set('challenge-rate', 'offset', (offset + index + 1) % candidates.length)\n const next = options.state.get<number>('challenge-controller-rate', candidate.subscriber) ?? 0\n if (now < next)\n continue\n options.state.set('challenge-controller-rate', candidate.subscriber, now + 30)\n attempted += 1\n signal.throwIfAborted()\n await acceptCandidate(candidate.subscriber, candidate.tuple.subscription.objectHash, signal)\n }\n }\n async function loadScopedKeys(view: Extract<Awaited<ReturnType<PublisherHandshakeClient['subscriptions']>>, { ok: true }>, active: typeof view.subscriptions) {\n const scopedKeys = active.flatMap(item => item.tuples.filter(tuple => tuple.subscription.objectHash === item.selectedSubscription).map(tuple => ({\n encryptionKey: tuple.subscription.body.encryptionKey, keyId: tuple.subscription.body.keyId, publisher: options.publisher,\n })))\n if (view.hasCurrentAdvertisement && (options.serviceHash === undefined || view.service.objectHash === options.serviceHash)\n && (options.deliveryMode === undefined || view.service.body.deliveryMode === options.deliveryMode)) {\n scopedKeys.push({\n encryptionKey: view.key.objectHash, keyId: view.key.body.keyId, publisher: options.publisher,\n })\n }\n const loadedKeys = await Promise.all(scopedKeys.map(async key => await options.keys.getPrivateKey(key)))\n status = {\n ...status,\n keyLoaded: scopedKeys.length > 0 && loadedKeys.every(key => key !== undefined),\n activeKeyIds: [...new Set(scopedKeys.map(key => key.keyId))],\n }\n }\n return {\n async discover(signal) {\n const view = await activeView(signal)\n const active = view.subscriptions.filter(item => item.state === 'active' && item.tuples.some(tuple => tuple.subscription.objectHash === item.selectedSubscription && selectedTuple(tuple)))\n await loadScopedKeys(view, active)\n if (active.length > (options.maxSubscriptions ?? 64))\n throw new Error('Publisher active subscription limit exceeded')\n const subscriptions: PublisherRuntimeSubscription[] = []\n for (const lifecycle of active) {\n if (lifecycle.state !== 'active' || lifecycle.activeFromBlock === undefined)\n continue\n try {\n const tuple = lifecycle.tuples.find(item => item.subscription.objectHash === lifecycle.selectedSubscription)\n if (tuple === undefined || !selectedTuple(tuple))\n throw new Error('Active publisher subscription has no selected tuple')\n const encrypted = tuple.subscription.body\n if (encrypted.chainId !== options.authorizationChainId)\n throw new Error('Subscription authorization chain mismatch')\n const publisherKey = await options.keys.getPrivateKey({\n encryptionKey: encrypted.encryptionKey, keyId: encrypted.keyId, publisher: options.publisher,\n })\n if (publisherKey === undefined)\n throw new Error('Subscription encryption key is unavailable')\n const plaintext = await decryptWakeSubscription({\n publisherKey, subscriber: tuple.subscriber, subscription: encrypted,\n })\n options.transport.assertAllowed(plaintext.endpoint)\n subscriptions.push({\n subscriptionHash: tuple.subscription.objectHash,\n serviceHash: tuple.service.objectHash,\n deliveryMode: plaintext.filter.deliveryMode,\n ...(plaintext.filter.bestEffort === undefined ? {} : { bestEffort: plaintext.filter.bestEffort }),\n authorizationChainId: options.authorizationChainId,\n controller: tuple.subscriber,\n audience: plaintext.audience,\n endpoint: plaintext.endpoint,\n deploymentId: plaintext.deploymentId,\n ...(plaintext.queueId === null ? {} : { queueId: plaintext.queueId }),\n source: plaintext.filter.source,\n fromPosition: plaintext.filter.fromPosition,\n maxPositionsPerWake: plaintext.filter.maxPositionsPerWake,\n filterHash: await sourceWakeFilterHash(plaintext.filter),\n })\n } catch {\n // A malformed or locally disallowed endpoint cannot stop independent\n // accepted subscribers. Durable pending work remains until a fresh\n // authoritative check proves the subscription is inactive.\n status = { ...status, rejectedSubscriptions: status.rejectedSubscriptions + 1 }\n }\n }\n return subscriptions\n },\n async isActive(subscription, signal) {\n const view = await activeView(signal)\n return view.subscriptions.some(item => item.state === 'active' && item.selectedSubscription === subscription.subscriptionHash\n && item.tuples.some(tuple => tuple.subscription.objectHash === subscription.subscriptionHash && tuple.subscriber === subscription.controller && selectedTuple(tuple)))\n },\n async acceptPending(signal) {\n // A slow finality operation is shared across passes; timeout does not\n // spawn another acceptance/signing operation against the same state.\n if (accepting === undefined) {\n const scope = publisherAbortScope([owner.signal, signal])\n accepting = (async () => {\n try {\n await accept(scope.signal)\n } finally {\n scope.dispose()\n accepting = undefined\n }\n })()\n }\n await accepting\n },\n async close() {\n await Promise.allSettled([accepting, viewing].filter(item => item !== undefined))\n },\n status: () => ({ ...status, challengeFailures: options.state.entries<number>('challenge-failures').reduce((sum, item) => sum + item.value, 0) }),\n }\n}\n", "import { Buffer } from 'node:buffer'\nimport { lookup } from 'node:dns/promises'\nimport { request } from 'node:https'\nimport { BlockList, isIP } from 'node:net'\n\nimport { z } from 'zod'\n\nimport { publisherAbortScope } from './abort.ts'\nimport { boundedPublisherOperation } from './sources.ts'\nconst OptionsZod = z.strictObject({\n allowedEndpoints: z.array(z.url()).min(1).max(64),\n endpointHeaders: z.array(z.strictObject({\n endpoint: z.url(),\n headers: z.strictObject({ 'x-vercel-protection-bypass': z.string().min(1).max(4096).regex(/^[\\u{21}-\\u{7E}]+$/u) }),\n })).max(64).default([]),\n maxResponseBytes: z.number().int().min(1).max(1_048_576).default(65_536),\n requestTimeoutMs: z.number().int().min(100).max(60_000).default(10_000),\n})\nexport interface PublisherHttpsTransportOptions {\n /** Exact public HTTPS destinations approved by the operator, including their path. */\n readonly allowedEndpoints: readonly string[]\n /** Private operator-provisioned Vercel automation credential, bound to one exact destination. */\n readonly endpointHeaders?: readonly { readonly endpoint: string; readonly headers: Readonly<Record<string, string>> }[]\n readonly maxResponseBytes?: number\n readonly requestTimeoutMs?: number\n}\nexport interface PublisherHttpsResponse {\n readonly body: unknown\n readonly retryAfterMs?: number\n readonly status: number\n}\nexport interface PublisherHttpsTransport {\n assertAllowed(endpoint: string): void\n post(endpoint: string, body: unknown, signal: AbortSignal, jwt?: string): Promise<PublisherHttpsResponse>\n}\nconst NON_PUBLIC_IPV4_SUBNETS = [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.0.0.0', 24],\n ['192.0.2.0', 24],\n ['192.88.99.0', 24],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['198.51.100.0', 24],\n ['203.0.113.0', 24],\n ['224.0.0.0', 4],\n ['240.0.0.0', 4],\n] as const\nconst NON_PUBLIC_IPV6_SUBNETS = [\n ['2001::', 23], ['2001:db8::', 32], ['2002::', 16], ['3fff::', 20],\n] as const\n\ninterface PublisherAddressPolicy {\n readonly globalIpv6: BlockList\n readonly nonPublicIpv4: BlockList\n readonly nonPublicIpv6: BlockList\n}\n\nlet publisherAddressPolicy: PublisherAddressPolicy | undefined\n\nfunction loadPublisherAddressPolicy(): PublisherAddressPolicy {\n if (publisherAddressPolicy !== undefined) return publisherAddressPolicy\n const nonPublicIpv4 = new BlockList()\n for (const [address, prefix] of NON_PUBLIC_IPV4_SUBNETS) {\n nonPublicIpv4.addSubnet(address, prefix, 'ipv4')\n }\n const globalIpv6 = new BlockList()\n globalIpv6.addSubnet('2000::', 3, 'ipv6')\n const nonPublicIpv6 = new BlockList()\n for (const [address, prefix] of NON_PUBLIC_IPV6_SUBNETS) {\n nonPublicIpv6.addSubnet(address, prefix, 'ipv6')\n }\n publisherAddressPolicy = {\n globalIpv6, nonPublicIpv4, nonPublicIpv6,\n }\n return publisherAddressPolicy\n}\n\n/** Conservative public-unicast policy, with numeric subnet checks for every IPv6 spelling. */\nexport function isPublicPublisherAddress(address: string): boolean {\n const policy = loadPublisherAddressPolicy()\n return isIP(address) === 4\n ? !policy.nonPublicIpv4.check(address, 'ipv4')\n : isIP(address) === 6 && policy.globalIpv6.check(address, 'ipv6') && !policy.nonPublicIpv6.check(address, 'ipv6')\n}\nexport function createPublisherHttpsTransport(input: PublisherHttpsTransportOptions): PublisherHttpsTransport {\n const parsed = OptionsZod.safeParse(input)\n if (!parsed.success) throw new Error('Invalid publisher HTTPS transport configuration')\n const options = parsed.data\n const allowed = new Set(options.allowedEndpoints.map((endpoint) => {\n const url = new URL(endpoint)\n if (url.href !== endpoint || url.protocol !== 'https:' || (url.port !== '' && url.port !== '443')\n || url.username !== '' || url.password !== '' || url.hash !== '')\n throw new Error('Publisher destinations must be canonical public HTTPS URLs on port 443')\n const literal = url.hostname.replaceAll(/^\\[|\\]$/gu, '')\n if (isIP(literal) !== 0 && !isPublicPublisherAddress(literal))\n throw new Error('Publisher destination is not public')\n if (url.hostname === 'localhost' || url.hostname.endsWith('.localhost') || url.hostname.endsWith('.local'))\n throw new Error('Publisher destination is not public')\n return endpoint\n }))\n const assertAllowed = (endpoint: string) => {\n if (!allowed.has(endpoint))\n throw new Error('Publisher destination is not explicitly allowed')\n }\n const endpointHeaders = new Map<string, Readonly<Record<string, string>>>()\n for (const entry of options.endpointHeaders) {\n assertAllowed(entry.endpoint)\n if (endpointHeaders.has(entry.endpoint)) throw new Error('Duplicate publisher endpoint header configuration')\n endpointHeaders.set(entry.endpoint, entry.headers)\n }\n return {\n assertAllowed,\n async post(endpoint, body, signal, jwt) {\n assertAllowed(endpoint)\n signal.throwIfAborted()\n const url = new URL(endpoint)\n const scope = publisherAbortScope([signal], options.requestTimeoutMs)\n const combined = scope.signal\n try {\n const addresses = await boundedPublisherOperation(lookup(url.hostname.replaceAll(/^\\[|\\]$/gu, ''), { all: true, verbatim: true }), combined, options.requestTimeoutMs)\n combined.throwIfAborted()\n if (addresses.length === 0 || addresses.some(item => !isPublicPublisherAddress(item.address)))\n throw new Error('Publisher DNS answer includes a non-public address')\n const selected = addresses[0]\n if (selected === undefined)\n throw new Error('Publisher DNS lookup was empty')\n const encoded = Buffer.from(JSON.stringify(body))\n if (encoded.byteLength > 65_536)\n throw new Error('Publisher request body is too large')\n return await new Promise<PublisherHttpsResponse>((resolve, reject) => {\n const call = request(url, {\n agent: false,\n headers: {\n ...endpointHeaders.get(endpoint),\n 'content-length': encoded.byteLength,\n 'content-type': 'application/json',\n ...(jwt === undefined ? {} : { authorization: `Bearer ${jwt}` }),\n },\n lookup(_hostname, lookupOptions, callback) {\n // Pin the validated DNS answer for this connection; TLS still validates\n // the original hostname. No second resolver can rebind to a private IP.\n if (lookupOptions.all)\n callback(null, [{ address: selected.address, family: selected.family }])\n else\n callback(null, selected.address, selected.family)\n },\n method: 'POST',\n rejectUnauthorized: true,\n signal: combined,\n }, (response) => {\n const status = response.statusCode ?? 500\n if (status >= 300 && status < 400) {\n response.destroy()\n reject(new Error('Publisher HTTPS redirects are forbidden'))\n return\n }\n let size = 0\n const chunks: Buffer[] = []\n response.on('data', (chunk: Buffer) => {\n size += chunk.byteLength\n if (size > options.maxResponseBytes) {\n response.destroy()\n reject(new Error('Publisher HTTPS response is too large'))\n } else\n chunks.push(chunk)\n })\n response.on('error', () => reject(new Error('Publisher HTTPS response failed')))\n response.on('end', () => {\n try {\n const responseBody: unknown = size === 0 ? null : JSON.parse(Buffer.concat(chunks).toString('utf8'))\n const retry = Number(response.headers['retry-after'])\n resolve({\n status, body: responseBody, ...(Number.isFinite(retry) && retry > 0 ? { retryAfterMs: Math.min(retry * 1000, 3_600_000) } : {}),\n })\n } catch {\n reject(new Error('Publisher HTTPS response is not JSON'))\n }\n })\n })\n call.on('error', () => reject(new Error('Publisher HTTPS request failed')))\n call.end(encoded)\n })\n } finally {\n scope.dispose()\n }\n },\n }\n}\n", "import { createHash } from 'node:crypto'\n\nimport { canonicalJson } from '@xyo-network/event-kit-protocol'\nimport type { WakeSource } from '@xyo-network/event-kit-schemas'\nimport { completedUtcIntervalPosition, WakeSourceZod } from '@xyo-network/event-kit-schemas'\nimport { PayloadBuilder } from '@xyo-network/sdk'\nimport type { XyoGateway } from '@xyo-network/xl1-sdk'\nimport { asXL1BlockNumber } from '@xyo-network/xl1-sdk'\nimport { FetchRequest, JsonRpcProvider } from 'ethers'\n\nimport { publisherAbortScope } from './abort.ts'\nimport { createBoundedPublisherEthersTransport } from './boundedFetch.ts'\nexport interface PublisherSourceHead {\n readonly hash?: string\n readonly position: number\n}\nexport interface PublisherSourceReader {\n readonly source: WakeSource\n close?(): void | Promise<void>\n head(signal: AbortSignal): Promise<PublisherSourceHead>\n}\nexport function publisherSourceKey(source: WakeSource): string {\n return createHash('sha256').update(canonicalJson(WakeSourceZod.parse(source))).digest('hex')\n}\nexport async function boundedPublisherOperation<T>(operation: Promise<T>, signal: AbortSignal, timeoutMs = 10_000): Promise<T> {\n const scope = publisherAbortScope([signal], timeoutMs)\n const combined = scope.signal\n let rejectAbort: (() => void) | undefined\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = () => reject(new Error('Publisher operation aborted or timed out'))\n combined.addEventListener('abort', rejectAbort, { once: true })\n })\n try {\n combined.throwIfAborted()\n return await Promise.race([operation, aborted])\n } finally {\n if (rejectAbort !== undefined)\n combined.removeEventListener('abort', rejectAbort)\n scope.dispose()\n }\n}\ntype GatewayViewer = NonNullable<XyoGateway['connection']['viewer']>\nexport function createXl1PublisherSource(options: {\n readonly source: Extract<WakeSource, {\n kind: 'xl1-finalized'\n }>\n readonly viewer: Pick<GatewayViewer, 'block' | 'chainId' | 'finalization'>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'xl1-finalized')\n throw new Error('Expected an XL1 finalized source')\n return {\n source,\n async head(signal) {\n const chainId = String(await boundedPublisherOperation(Promise.resolve(options.viewer.chainId()), signal))\n if (chainId !== source.chainId)\n throw new Error('XL1 source chain identity changed')\n const position = Number(await boundedPublisherOperation(Promise.resolve(options.viewer.finalization.headNumber()), signal))\n if (!Number.isSafeInteger(position) || position < 0)\n throw new Error('XL1 finalized head is invalid')\n const block = await boundedPublisherOperation(Promise.resolve(options.viewer.block.blockByNumber(asXL1BlockNumber(position, true))), signal)\n if (block?.[0].block !== position || !/^[0-9a-f]{64}$/u.test(block[0]._hash)) {\n throw new Error('XL1 finalized head block is unavailable or inconsistent')\n }\n if (String(block[0].chain) !== source.chainId || await PayloadBuilder.hash(block[0]) !== block[0]._hash) {\n throw new Error('XL1 finalized head block chain or hash is inconsistent')\n }\n return { position, hash: block[0]._hash }\n },\n }\n}\nexport function createEthereumFinalizedPublisherSource(options: {\n readonly requestTimeoutMs?: number\n readonly rpcUrl: string\n readonly source: Extract<WakeSource, {\n kind: 'ethereum-finalized'\n }>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'ethereum-finalized')\n throw new Error('Expected an Ethereum finalized source')\n const { chainId, genesisHash } = source\n const url = new URL(options.rpcUrl)\n if (url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.hash !== '') {\n throw new Error('Ethereum source RPC must use HTTPS without URL credentials or fragments')\n }\n const connection = new FetchRequest(url.href)\n connection.timeout = options.requestTimeoutMs ?? 10_000\n const transport = createBoundedPublisherEthersTransport({\n requestTimeoutMs: options.requestTimeoutMs, maxResponseBytes: 2 * 1024 * 1024, maxConcurrency: 8,\n })\n connection.getUrlFunc = transport.getUrl\n connection.setThrottleParams({ maxAttempts: 1 })\n const provider = new JsonRpcProvider(connection, undefined, { batchMaxCount: 1, cacheTimeout: -1 })\n let reading: Promise<PublisherSourceHead> | undefined\n let closed = false\n let closing: Promise<void> | undefined\n const close = () => closing ??= (async () => {\n closed = true\n provider.destroy()\n await transport.close()\n })()\n const onAbort = () => {\n void close()\n }\n async function read() {\n const requests = [provider.getNetwork(), provider.getBlock(0), provider.getBlock('finalized')] as const\n // A failing sibling request cannot release the single-flight slot while\n // another request still owns a connection or a bounded response body.\n try {\n const [network, genesis, block] = await Promise.all(requests)\n if (network.chainId.toString() !== chainId || genesis?.hash?.slice(2).toLowerCase() !== genesisHash) {\n throw new Error('Ethereum source chain identity mismatch')\n }\n if (block?.hash === null || block === null || !/^0x[0-9a-fA-F]{64}$/u.test(block.hash)\n || !Number.isSafeInteger(block.number) || block.number < 0) throw new Error('Ethereum finalized head is unavailable')\n return { position: block.number, hash: block.hash.slice(2).toLowerCase() }\n } catch (error) {\n await Promise.allSettled(requests)\n throw error\n }\n }\n return {\n source,\n close,\n async head(signal) {\n signal.throwIfAborted()\n if (closed) throw new Error('Ethereum source is closed')\n signal.addEventListener('abort', onAbort, { once: true })\n reading ??= (async () => {\n try {\n return await read()\n } finally {\n reading = undefined\n }\n })()\n try {\n return await boundedPublisherOperation(reading, signal, options.requestTimeoutMs ?? 10_000)\n } finally {\n signal.removeEventListener('abort', onAbort)\n }\n },\n }\n}\n\nexport function createUtcIntervalPublisherSource(options: {\n readonly nowSeconds?: () => number\n readonly source: Extract<WakeSource, {\n kind: 'utc-interval'\n }>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'utc-interval')\n throw new Error('Expected a UTC interval source')\n const nowSeconds = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n return {\n source,\n async head(signal) {\n signal.throwIfAborted()\n const now = nowSeconds()\n if (!Number.isSafeInteger(now) || now < 0)\n throw new Error('UTC interval clock is invalid')\n return { position: completedUtcIntervalPosition(source, now) ?? -1 }\n },\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport type { PeriodicActorParams, PeriodicPassContext } from '@ariestools/actor'\nimport { createMemoryLocator, PeriodicActor } from '@ariestools/actor'\nimport { creatable } from '@ariestools/sdk'\nimport { BestEffortAdmissionAcknowledgmentZod } from '@xyo-network/event-kit-protocol'\nimport type {\n BestEffortDeliveryPolicy, WakeDeliveryMode, WakeEnvelope, WakeSource,\n} from '@xyo-network/event-kit-schemas'\nimport { BestEffortDeliveryPolicyZod, WakeDeliveryModeZod } from '@xyo-network/event-kit-schemas'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { publisherAbortScope } from './abort.ts'\nimport type { PublisherHttpsTransport } from './httpsTransport.ts'\nimport type { DeliveryState } from './publisherDeliveryState.ts'\nimport {\n assertDeliveryState, DeliveryResponseError, failedDelivery, makeEvent, prepareBestEffortDelivery,\n} from './publisherDeliveryState.ts'\nimport type { PublisherSourceHead, PublisherSourceReader } from './sources.ts'\nimport { boundedPublisherOperation, publisherSourceKey } from './sources.ts'\nimport { createAccountSourceWakeSigner } from './sourceSigner.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\nexport interface PublisherRuntimeSubscription {\n readonly audience: string\n readonly authorizationChainId: string\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly controller: string\n readonly deliveryMode: WakeDeliveryMode\n readonly deploymentId: string\n readonly endpoint: string\n readonly filterHash: string\n readonly fromPosition: number\n readonly maxPositionsPerWake: number\n readonly queueId?: string\n readonly serviceHash?: string\n readonly source: WakeSource\n readonly subscriptionHash: string\n}\n/** Discovery MUST return only current finalized, accepted subscriptions. */\nexport interface PublisherRuntimeDiscovery {\n acceptPending?(signal: AbortSignal): Promise<void>\n close?(): Promise<void>\n discover(signal: AbortSignal): Promise<readonly PublisherRuntimeSubscription[]>\n /** Re-check the exact current revision before each attempt, including retries. */\n isActive(subscription: PublisherRuntimeSubscription, signal: AbortSignal): Promise<boolean>\n status?(): PublisherRuntimeDiscoveryStatus\n}\nexport interface PublisherRuntimeDiscoveryStatus {\n readonly activeKeyIds: readonly string[]\n readonly authorizationChainId: string\n readonly challengeFailures: number\n readonly finalizedHead?: number\n readonly indexedThrough?: number\n readonly keyLoaded: boolean\n readonly pendingSubscriptions: number\n readonly rejectedSubscriptions: number\n}\nfunction activationReady(status?: PublisherRuntimeDiscoveryStatus): boolean {\n return (status?.keyLoaded ?? true) && (status?.pendingSubscriptions ?? 0) === 0\n}\n\nexport interface PersistentEventPublisherOptions {\n readonly account: AccountInstance\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly concurrency?: number\n readonly deliveryMode: WakeDeliveryMode\n readonly discovery: PublisherRuntimeDiscovery\n readonly intervalMs?: number\n readonly maxSubscriptions?: number\n readonly nowSeconds?: () => number\n readonly publisher: string\n readonly requestTimeoutMs?: number\n /** Optional immutable operator pin; mismatches fail readiness without revoking subscriptions. */\n readonly serviceHash?: string\n readonly sources: readonly PublisherSourceReader[]\n readonly state: SqlitePublisherState\n readonly transport: PublisherHttpsTransport\n}\nexport interface PersistentEventPublisherStatus {\n readonly abandoned: number\n readonly activeSubscriptions: number\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly clockHealthy: boolean\n readonly degraded: boolean\n readonly delivered: number\n readonly deliveryMode: WakeDeliveryMode\n readonly failures: number\n readonly handshake?: PublisherRuntimeDiscoveryStatus\n readonly lastError?: string\n readonly passes: number\n readonly pendingDeliveries: number\n readonly publisher: string\n readonly ready: boolean\n readonly running: boolean\n readonly sources: readonly {\n readonly hash?: string\n readonly id: string\n readonly position: number\n }[]\n readonly subscriptions: readonly {\n readonly attempts?: number\n readonly cursor: number\n readonly failures: number\n readonly id: string\n /** Best Effort admission target is not a contiguous source prefix. */\n readonly lastAdmissionTarget?: number\n readonly lastHintAt?: number\n readonly pending: boolean\n readonly state: string\n }[]\n readonly superseded: number\n readonly totalAttempts: number\n}\nexport interface PersistentEventPublisher {\n runOnce(): Promise<void>\n start(): Promise<void>\n status(): PersistentEventPublisherStatus\n stop(): Promise<void>\n}\ninterface RuntimeActorParams extends PeriodicActorParams {\n readonly tick: (signal: AbortSignal) => Promise<void>\n}\n@creatable()\nclass PublisherRuntimeActor extends PeriodicActor<RuntimeActorParams> {\n protected override async runPass(context: PeriodicPassContext): Promise<void> {\n await this.params.tick(context.signal)\n }\n}\nconst TimingZod = z.object({\n concurrency: z.number().int().min(1).max(32).default(4),\n intervalMs: z.number().int().min(100).max(60_000).default(1000),\n maxSubscriptions: z.number().int().min(1).max(1024).default(64),\n requestTimeoutMs: z.number().int().min(100).max(60_000).default(10_000),\n})\n\nfunction runtimeSettings(options: PersistentEventPublisherOptions) {\n const deliveryMode = WakeDeliveryModeZod.parse(options.deliveryMode)\n const bestEffort = options.bestEffort === undefined ? undefined : BestEffortDeliveryPolicyZod.parse(options.bestEffort)\n if ((deliveryMode === 'best-effort') !== (bestEffort !== undefined)) throw new TypeError('Explicit delivery mode requires its exact policy')\n return {\n bestEffort,\n deliveryMode,\n deliveryNamespace: deliveryMode === 'best-effort' ? 'best-effort-deliveries' : 'deliveries',\n timing: TimingZod.parse(options),\n }\n}\nexport async function createPersistentEventPublisherRuntime(options: PersistentEventPublisherOptions): Promise<PersistentEventPublisher> {\n const {\n bestEffort, deliveryMode, deliveryNamespace, timing,\n } = runtimeSettings(options)\n if (options.sources.length < 1 || options.sources.length > 16)\n throw new Error('Publisher requires between one and sixteen bounded sources')\n const clock = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const signer = createAccountSourceWakeSigner({\n account: options.account, publisher: options.publisher, nowSeconds: clock,\n })\n const sourceReaders = new Map(options.sources.map(reader => [publisherSourceKey(reader.source), reader]))\n if (sourceReaders.size !== options.sources.length)\n throw new Error('Duplicate publisher source identity')\n const state = options.state\n const existingMode = state.get<string>('metadata', 'runtime-delivery-mode')\n if (existingMode !== undefined && existingMode !== deliveryMode) throw new Error('Publisher state delivery mode mismatch; preserve custody and use an explicitly qualified state binding')\n state.set('metadata', 'runtime-delivery-mode', deliveryMode)\n const abort = new AbortController()\n const seenThisProcess = new Set<string>()\n let running = false\n let ready = false\n let clockHealthy = true\n let passes = 0\n let lastError: string | undefined\n let sourcesHealthy = false\n let stop: Promise<void> | undefined\n const timed = <T>(promise: Promise<T>, signal: AbortSignal) => boundedPublisherOperation(promise, signal, timing.requestTimeoutMs)\n function loadDelivery(subscription: PublisherRuntimeSubscription, now: number): DeliveryState {\n if (subscription.deliveryMode !== deliveryMode || !isDeepStrictEqual(subscription.bestEffort, bestEffort))\n throw new Error('Subscription delivery mode or policy disagrees with runtime')\n if (deliveryMode === 'best-effort' && (subscription.maxPositionsPerWake !== 1 || subscription.serviceHash === undefined)) throw new Error('Best Effort requires point range')\n if (options.serviceHash !== undefined && subscription.serviceHash !== options.serviceHash)\n throw new Error('Subscription does not match the configured exact service descriptor')\n const key = subscription.subscriptionHash\n if (deliveryMode === 'best-effort' && state.get(deliveryNamespace, key) === undefined\n && state.entries(deliveryNamespace).length >= timing.maxSubscriptions) throw new Error('Best Effort state capacity exceeded; live records are not evicted')\n let record = state.get<DeliveryState>(deliveryNamespace, key)\n if (record === undefined) {\n makeEvent(subscription, subscription.fromPosition, subscription.fromPosition, now, '0'.repeat(32))\n if (!Number.isSafeInteger(subscription.maxPositionsPerWake) || subscription.maxPositionsPerWake < 1 || subscription.maxPositionsPerWake > 4096) {\n throw new Error('Invalid source range budget')\n }\n record = {\n subscription, cursor: subscription.fromPosition - 1, delivered: 0, failures: 0, nextAttemptMs: 0, state: 'active',\n }\n state.set(deliveryNamespace, key, record)\n }\n assertDeliveryState(record, subscription)\n return record\n }\n\n function prepareDelivery(record: DeliveryState, now: number, heads: ReadonlyMap<string, PublisherSourceHead | Error>) {\n if (deliveryMode === 'best-effort' && bestEffort !== undefined) {\n const first = !seenThisProcess.has(record.subscription.subscriptionHash)\n const head = heads.get(publisherSourceKey(record.subscription.source))\n if (head !== undefined && !(head instanceof Error) && head.position >= record.subscription.fromPosition)\n seenThisProcess.add(record.subscription.subscriptionHash)\n return prepareBestEffortDelivery({\n bestEffort, first, heads, now, record, state,\n })\n }\n if (record.pending !== undefined) return { ...record, pending: record.pending }\n const subscription = record.subscription\n const head = heads.get(publisherSourceKey(subscription.source))\n if (head === undefined || head instanceof Error) throw new Error('Configured source is unavailable')\n if (head.position <= record.cursor) return\n const fromPosition = record.cursor + 1\n const pending = makeEvent(subscription, fromPosition, Math.min(head.position, fromPosition + subscription.maxPositionsPerWake - 1), now)\n const prepared = { ...record, pending }\n state.transaction(() => {\n const logicalKey = JSON.stringify([subscription.subscriptionHash, pending.fromPosition, pending.toPosition])\n if (!state.insert('delivery-events', logicalKey, pending)) throw new Error('Publisher logical range already exists outside its contiguous cursor')\n state.set(deliveryNamespace, subscription.subscriptionHash, prepared)\n })\n return prepared\n }\n\n async function stillActive(record: DeliveryState, signal: AbortSignal): Promise<boolean> {\n if (await timed(options.discovery.isActive(record.subscription, signal), signal)) return true\n state.set(deliveryNamespace, record.subscription.subscriptionHash, {\n ...record, pending: undefined, state: 'cancelled',\n })\n return false\n }\n\n function acknowledgeBestEffort(record: DeliveryState & { readonly pending: WakeEnvelope }, body: unknown, eventHash: string, signal: AbortSignal, now: number) {\n const { pending, subscription } = record\n const acknowledgment = BestEffortAdmissionAcknowledgmentZod.safeParse(body)\n if (!acknowledgment.success || acknowledgment.data.eventHash !== eventHash || acknowledgment.data.wakeId !== pending.wakeId\n || acknowledgment.data.expiresAt !== pending.issuedAt + (bestEffort?.maxHintAgeSeconds ?? 0) + 60\n || acknowledgment.data.acceptedAt < pending.issuedAt - 60 || acknowledgment.data.acceptedAt > now + 60)\n throw new Error('Publisher did not receive a matching finite acknowledgment')\n signal.throwIfAborted()\n state.set(deliveryNamespace, subscription.subscriptionHash, {\n subscription,\n cursor: pending.toPosition,\n delivered: record.delivered + 1,\n failures: 0,\n attempts: 0,\n superseded: record.superseded ?? 0,\n abandoned: record.abandoned ?? 0,\n totalAttempts: (record.totalAttempts ?? 0) + 1,\n lastNotifiedAt: now,\n lastHintAt: pending.issuedAt,\n lastHintTarget: pending.toPosition,\n nextAttemptMs: 0,\n state: 'active',\n } satisfies DeliveryState)\n }\n\n async function sendDelivery(record: DeliveryState & { readonly pending: WakeEnvelope }, signal: AbortSignal, now: number) {\n const { pending, subscription } = record\n signal.throwIfAborted()\n const signed = await signer.sign(pending, subscription.audience)\n signal.throwIfAborted()\n const attempt = deliveryMode === 'best-effort' ? record.attempts ?? 0 : state.get<{ count: number }>('delivery-attempts', pending.wakeId)?.count ?? 0\n if (deliveryMode === 'best-effort') state.set(deliveryNamespace, subscription.subscriptionHash, {\n ...record, attempts: attempt + 1, totalAttempts: (record.totalAttempts ?? 0) + 1,\n })\n else state.set('delivery-attempts', pending.wakeId, {\n count: attempt + 1, startedAt: now, status: 'in-flight',\n })\n const response = await options.transport.post(subscription.endpoint, signed.event, signal, signed.jwt)\n if (deliveryMode === 'durable') state.set('delivery-attempts', pending.wakeId, {\n count: attempt + 1, startedAt: now, status: response.status,\n })\n if (response.status !== 200 && response.status !== 202) throw new DeliveryResponseError(response.status, response.retryAfterMs)\n if (deliveryMode === 'best-effort') {\n acknowledgeBestEffort(record, response.body, signed.eventHash, signal, now)\n return\n }\n const receipt = z.object({ receiptId: z.string().min(1), wakeId: z.literal(pending.wakeId) }).safeParse(response.body)\n if (!receipt.success) throw new Error('Publisher admission did not return a matching durable receipt')\n signal.throwIfAborted()\n // Receipt, contiguous cursor, and outbox clear commit together. A lost\n // response or death before this transaction reuses the exact pending body.\n state.transaction(() => {\n state.set('delivery-receipts', pending.wakeId, { receiptId: receipt.data.receiptId, receivedAt: now })\n state.set(deliveryNamespace, subscription.subscriptionHash, {\n subscription,\n cursor: pending.toPosition,\n delivered: record.delivered + 1,\n failures: 0,\n nextAttemptMs: 0,\n state: 'active',\n } satisfies DeliveryState)\n })\n }\n\n async function deliver(subscription: PublisherRuntimeSubscription, signal: AbortSignal, now: number, heads: ReadonlyMap<string, PublisherSourceHead | Error>) {\n let record = loadDelivery(subscription, now)\n if (deliveryMode === 'durable' && (record.state !== 'active' || record.nextAttemptMs > now * 1000)) return\n try {\n if (!await stillActive(record, signal)) return\n options.transport.assertAllowed(subscription.endpoint)\n if (!sourceReaders.has(publisherSourceKey(subscription.source))) throw new Error('Subscription source is not configured')\n const prepared = prepareDelivery(record, now, heads)\n if (prepared === undefined) return\n record = prepared\n if (record.nextAttemptMs > now * 1000) return\n // Reconcile once more after observing source progress, before every attempt.\n if (!await stillActive(record, signal)) return\n await sendDelivery(prepared, signal, now)\n } catch (error) {\n if (signal.aborted) return\n state.set(\n deliveryNamespace,\n subscription.subscriptionHash,\n failedDelivery(record, state.get<DeliveryState>(deliveryNamespace, subscription.subscriptionHash), deliveryMode, error, now),\n )\n }\n }\n async function readSources(signal: AbortSignal): Promise<ReadonlyMap<string, PublisherSourceHead | Error>> {\n const heads = new Map<string, PublisherSourceHead | Error>()\n const results = await Promise.allSettled([...sourceReaders].map(async ([key, reader]) => {\n const head = await timed(reader.head(signal), signal)\n if (!Number.isSafeInteger(head.position) || head.position < -1)\n throw new Error('Source head is invalid')\n const previous = state.get<PublisherSourceHead>('source-heads', key)\n if (previous !== undefined && (head.position < previous.position || (head.position === previous.position && head.hash !== previous.hash))) {\n throw new Error('Finalized source regressed or changed hash')\n }\n signal.throwIfAborted()\n state.set('source-heads', key, head)\n heads.set(key, head)\n }))\n sourcesHealthy = results.every(item => item.status === 'fulfilled')\n // All rejections are inspected; delivery sees an unavailable source without\n // exposing provider URLs or allowing one source to deny another service.\n for (const [index, result] of results.entries())\n if (result.status === 'rejected') {\n const key = sourceReaders.keys().toArray()[index]\n if (key !== undefined)\n heads.set(key, new Error('Source read failed'))\n }\n return heads\n }\n async function reconcileDeliveries(subscriptions: readonly PublisherRuntimeSubscription[], signal: AbortSignal) {\n if (subscriptions.length > timing.maxSubscriptions) throw new Error('Publisher subscription limit exceeded')\n const active = new Set(subscriptions.map(subscription => subscription.subscriptionHash))\n if (active.size !== subscriptions.length) throw new Error('Duplicate subscription identity')\n const unavailable = state.entries<DeliveryState>(deliveryNamespace).filter(item => !active.has(item.key) && item.value.state !== 'cancelled')\n let available = true\n for (let offset = 0; offset < unavailable.length; offset += timing.concurrency) {\n signal.throwIfAborted()\n const results = await Promise.allSettled(unavailable.slice(offset, offset + timing.concurrency).map(async ({ key, value }) => {\n const stillAuthorized = await timed(options.discovery.isActive(value.subscription, signal), signal)\n if (!stillAuthorized) state.set(deliveryNamespace, key, {\n ...value, pending: undefined, state: 'cancelled',\n })\n return stillAuthorized\n }))\n // Local key loss, endpoint policy, or a failed replay cannot revoke a\n // finalized subscription. Preserve its exact pending body for restoration.\n available = available && results.every(result => result.status === 'fulfilled' && !result.value)\n }\n return available\n }\n\n async function tick(actorSignal: AbortSignal) {\n const scope = publisherAbortScope([abort.signal, actorSignal])\n const signal = scope.signal\n try {\n signal.throwIfAborted()\n const now = clock()\n const prior = state.get<number>('runtime', 'highest-wall-clock') ?? 0\n clockHealthy = Number.isSafeInteger(now) && now >= prior\n if (!clockHealthy)\n throw new Error('Publisher clock moved backwards')\n state.set('runtime', 'highest-wall-clock', now)\n const subscriptions = await timed(options.discovery.discover(signal), signal)\n const subscriptionsAvailable = await reconcileDeliveries(subscriptions, signal)\n const heads = await readSources(signal)\n for (let offset = 0; offset < subscriptions.length; offset += timing.concurrency) {\n signal.throwIfAborted()\n const outcomes = await Promise.allSettled(subscriptions.slice(offset, offset + timing.concurrency).map(subscription => deliver(subscription, signal, now, heads)))\n const failed = outcomes.find(result => result.status === 'rejected')\n if (failed?.status === 'rejected')\n throw failed.reason\n }\n // Challenge/finality work is bounded and occurs after already-active\n // subscribers, so a new or broken subscriber cannot starve delivery.\n if (options.discovery.acceptPending !== undefined)\n await timed(options.discovery.acceptPending(signal), signal)\n const discoveryStatus = options.discovery.status?.()\n ready = subscriptionsAvailable && sourcesHealthy && activationReady(discoveryStatus)\n lastError = subscriptionsAvailable ? undefined : 'publisher-subscription-unavailable'\n passes += 1\n } catch (error) {\n ready = false\n lastError = clockHealthy ? 'publisher-pass-failed' : 'publisher-clock-unhealthy'\n if (!signal.aborted)\n throw error\n } finally {\n scope.dispose()\n }\n }\n const actor = await PublisherRuntimeActor.create({\n locator: createMemoryLocator({}), intervalMs: timing.intervalMs, firstRun: 'immediate', readiness: 'immediate', tick,\n })\n return {\n async start() {\n if (stop !== undefined)\n throw new Error('Publisher is stopped')\n if (running) {\n return\n }\n\n await actor.start()\n running = true\n },\n async runOnce() {\n if (stop !== undefined)\n throw new Error('Publisher is stopped')\n await actor.runOnce()\n },\n stop: () => stop ??= (async () => {\n abort.abort()\n const failures: unknown[] = []\n try {\n await actor.stop()\n } catch (error) {\n failures.push(error)\n }\n try {\n await options.discovery.close?.()\n } catch (error) {\n failures.push(error)\n }\n for (const source of options.sources)\n try {\n await source.close?.()\n } catch (error) {\n failures.push(error)\n }\n running = false\n ready = false\n if (failures.length > 0)\n throw new AggregateError(failures, 'Publisher runtime shutdown failed')\n })(),\n status() {\n const deliveries = state.entries<DeliveryState>(deliveryNamespace).map(item => item.value)\n return {\n running,\n deliveryMode,\n ...(bestEffort === undefined ? {} : { bestEffort: Object.freeze({ ...bestEffort }) }),\n superseded: deliveries.reduce((sum, item) => sum + (item.superseded ?? 0), 0),\n abandoned: deliveries.reduce((sum, item) => sum + (item.abandoned ?? 0), 0),\n totalAttempts: deliveries.reduce((sum, item) => sum + (item.totalAttempts ?? 0), 0),\n ready: running && ready,\n clockHealthy,\n degraded: !ready || deliveries.some(item => item.state !== 'cancelled' && item.failures > 0),\n publisher: options.publisher,\n activeSubscriptions: deliveries.filter(item => item.state === 'active').length,\n pendingDeliveries: deliveries.filter(item => item.pending !== undefined).length,\n delivered: deliveries.reduce((sum, item) => sum + item.delivered, 0),\n failures: deliveries.reduce((sum, item) => sum + item.failures, 0),\n passes,\n ...(lastError === undefined ? {} : { lastError }),\n ...(options.discovery.status === undefined ? {} : { handshake: options.discovery.status() }),\n sources: state.entries<PublisherSourceHead>('source-heads').filter(item => sourceReaders.has(item.key)).map(item => ({ id: item.key, ...item.value })),\n subscriptions: state.entries<DeliveryState>(deliveryNamespace).map(item => ({\n id: item.key,\n cursor: item.value.cursor,\n ...(deliveryMode === 'best-effort'\n ? {\n ...(item.value.cursor < item.value.subscription.fromPosition ? {} : { lastAdmissionTarget: item.value.cursor }),\n attempts: item.value.attempts ?? 0,\n lastHintAt: item.value.lastHintAt,\n }\n : {}),\n state: item.value.state,\n pending: item.value.pending !== undefined,\n failures: item.value.failures,\n })),\n }\n },\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { BestEffortDeliveryPolicy, WakeEnvelope } from '@xyo-network/event-kit-schemas'\nimport { WakeEnvelopeSchema, WakeEnvelopeZod } from '@xyo-network/event-kit-schemas'\n\nimport type { PublisherRuntimeSubscription } from './publisherRuntime.ts'\nimport type { PublisherSourceHead } from './sources.ts'\nimport { publisherSourceKey } from './sources.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\n\nexport interface DeliveryState {\n readonly abandoned?: number\n readonly attempts?: number\n readonly cursor: number\n readonly delivered: number\n readonly failures: number\n readonly lastError?: string\n readonly lastHintAt?: number\n readonly lastHintTarget?: number\n readonly lastNotifiedAt?: number\n readonly nextAttemptMs: number\n readonly pending?: WakeEnvelope\n readonly state: 'active' | 'blocked' | 'cancelled'\n readonly subscription: PublisherRuntimeSubscription\n readonly superseded?: number\n readonly totalAttempts?: number\n}\nexport function assertDeliveryState(record: DeliveryState, subscription: PublisherRuntimeSubscription): void {\n if (!isDeepStrictEqual(record.subscription, subscription))\n throw new Error('Subscription revision changed without a new identity')\n if (!Number.isSafeInteger(record.cursor) || record.cursor < subscription.fromPosition - 1\n || [record.delivered, record.failures, record.nextAttemptMs].some(value => !(Number.isSafeInteger(value) && value >= 0))\n || [record.attempts, record.superseded, record.abandoned, record.totalAttempts, record.lastHintAt, record.lastNotifiedAt, record.lastHintTarget]\n .some(value => value !== undefined && !(Number.isSafeInteger(value) && value >= 0))\n || !['active', 'blocked', 'cancelled'].includes(record.state))\n throw new Error('Persisted publisher delivery state is invalid')\n if (record.pending === undefined) return\n const pending = WakeEnvelopeZod.parse(record.pending)\n if ((subscription.deliveryMode === 'durable' && pending.fromPosition !== record.cursor + 1)\n || pending.deliveryMode !== subscription.deliveryMode || pending.toPosition - pending.fromPosition + 1 > subscription.maxPositionsPerWake\n || pending.authorizationChainId !== subscription.authorizationChainId || pending.deploymentId !== subscription.deploymentId\n || pending.queueId !== subscription.queueId || pending.filterHash !== subscription.filterHash\n || !isDeepStrictEqual(pending.source, subscription.source))\n throw new Error('Persisted publisher outbox binding is invalid')\n}\nexport function makeEvent(subscription: PublisherRuntimeSubscription, fromPosition: number, toPosition: number, now: number, wakeId = randomBytes(16).toString('hex')) {\n return WakeEnvelopeZod.parse({\n schema: WakeEnvelopeSchema,\n authorizationChainId: subscription.authorizationChainId,\n deliveryMode: subscription.deliveryMode,\n deploymentId: subscription.deploymentId,\n filterHash: subscription.filterHash,\n fromPosition,\n issuedAt: now,\n source: subscription.source,\n toPosition,\n wakeId,\n ...(subscription.queueId === undefined ? {} : { queueId: subscription.queueId }),\n })\n}\n\nexport class DeliveryResponseError extends Error {\n readonly retryAfterMs?: number\n readonly status: number\n constructor(status: number, retryAfterMs?: number) {\n super('Publisher admission failed')\n this.status = status\n this.retryAfterMs = retryAfterMs\n }\n\n get retryable() {\n return this.status === 408 || this.status === 429 || this.status >= 500\n }\n}\n\nexport function prepareBestEffortDelivery(options: {\n readonly bestEffort: BestEffortDeliveryPolicy\n readonly first: boolean\n readonly heads: ReadonlyMap<string, PublisherSourceHead | Error>\n readonly now: number\n readonly record: DeliveryState\n readonly state: SqlitePublisherState\n}) {\n const {\n bestEffort, first, heads, now, record, state,\n } = options\n const subscription = record.subscription\n const head = heads.get(publisherSourceKey(subscription.source))\n const prior = record.pending\n const expired = isHintExpired(record, now, bestEffort)\n if (head === undefined || head instanceof Error || head.position < subscription.fromPosition) {\n if (prior !== undefined && !expired) return { ...record, pending: prior }\n if (prior !== undefined) state.set('best-effort-deliveries', subscription.subscriptionHash, {\n ...record, pending: undefined, abandoned: (record.abandoned ?? 0) + 1,\n })\n return\n }\n const refresh = refreshDue(record, now, bestEffort)\n if (freshHintRequired(record, head.position, first, refresh, expired)) {\n const pending = makeEvent(subscription, head.position, head.position, now)\n const prepared = {\n ...record,\n pending,\n attempts: 0,\n lastHintAt: now,\n lastHintTarget: head.position,\n superseded: (record.superseded ?? 0) + (prior !== undefined && !expired ? 1 : 0),\n abandoned: (record.abandoned ?? 0) + (expired ? 1 : 0),\n nextAttemptMs: 0,\n state: 'active' as const,\n }\n state.set('best-effort-deliveries', subscription.subscriptionHash, prepared)\n return prepared\n }\n if (expired) state.set('best-effort-deliveries', subscription.subscriptionHash, {\n ...record, pending: undefined, abandoned: (record.abandoned ?? 0) + 1,\n })\n return prior === undefined || expired ? undefined : { ...record, pending: prior }\n}\n\nfunction isHintExpired(record: DeliveryState, now: number, policy: BestEffortDeliveryPolicy): boolean {\n return record.pending !== undefined && (now > record.pending.issuedAt + policy.maxHintAgeSeconds || (record.attempts ?? 0) >= policy.maxAttempts)\n}\nfunction refreshDue(record: DeliveryState, now: number, policy: BestEffortDeliveryPolicy): boolean {\n return now - (record.lastHintAt ?? record.lastNotifiedAt ?? 0) >= policy.refreshIntervalSeconds\n}\nfunction freshHintRequired(record: DeliveryState, head: number, first: boolean, refresh: boolean, expired: boolean): boolean {\n return first || head > (record.pending?.toPosition ?? record.lastHintTarget ?? record.cursor) || (refresh && (record.pending === undefined || expired))\n}\nexport function failedDelivery(record: DeliveryState, current: DeliveryState | undefined, mode: string, error: unknown, now: number): DeliveryState {\n const bestEffort = mode === 'best-effort'\n const wait = error instanceof DeliveryResponseError && error.retryAfterMs !== undefined\n ? error.retryAfterMs\n : Math.min(300_000, 1000 * (2 ** Math.min(record.failures, 8)))\n return {\n ...record,\n failures: record.failures + 1,\n totalAttempts: bestEffort ? current?.totalAttempts ?? record.totalAttempts ?? 0 : record.totalAttempts,\n attempts: bestEffort ? current?.attempts ?? record.attempts ?? 0 : record.attempts,\n state: !bestEffort && error instanceof DeliveryResponseError && !error.retryable ? 'blocked' : 'active',\n nextAttemptMs: now * 1000 + Math.min(3_600_000, wait),\n lastError: 'delivery-failed',\n }\n}\n", "import { randomBytes } from 'node:crypto'\n\nimport type { WakeEnvelope } from '@xyo-network/event-kit-schemas'\nimport {\n NormalizedAddressZod, WakeEnvelopeZod, WakeJwtSchema,\n} from '@xyo-network/event-kit-schemas'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport { PayloadBuilder } from '@xyo-network/sdk'\n/** The wallet-JWT profile commits to the complete strict source-aware body. */\nexport function createAccountSourceWakeSigner(options: {\n readonly account: AccountInstance\n readonly nowSeconds?: () => number\n readonly publisher: string\n}) {\n const publisher = NormalizedAddressZod.parse(options.publisher)\n if (String(options.account.address).replace(/^0x/u, '').toLowerCase() !== publisher)\n throw new Error('Publisher signing account mismatch')\n return {\n async sign(input: WakeEnvelope, audience: string) {\n const event = WakeEnvelopeZod.parse(input)\n const eventHash = await PayloadBuilder.dataHash(event)\n const now = options.nowSeconds?.() ?? Math.floor(Date.now() / 1000)\n if (!Number.isSafeInteger(now) || now < 0)\n throw new Error('Publisher signing clock is invalid')\n const { token: jwt } = await options.account.signJwt({\n audience,\n claims: { eventHash, jti: randomBytes(16).toString('hex') },\n now,\n schema: WakeJwtSchema,\n ttl: 60,\n })\n return {\n event, eventHash, jwt, publisher,\n }\n },\n }\n}\n", "import { FetchJsonClient } from '@ariestools/sdk'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport type {\n GatewaySession, XyoGateway, XyoGatewayRunner,\n} from '@xyo-network/xl1-sdk'\nimport {\n baseConfigFactoryLocator, basicRestRunnerLocator, basicRestViewerLocator, creatableProvider,\n releaseProviderFactoryLocator, RestDataLakeRunner, RestDataLakeViewer, XyoGatewayMoniker, XyoGatewayRunnerMoniker,\n} from '@xyo-network/xl1-sdk'\nexport interface PublisherRestGatewayOptions {\n readonly chainStateUrl: string\n readonly fetchFn: typeof globalThis.fetch\n readonly finalizedUrl: string\n readonly indexUrl?: string\n readonly rpcUrl: string\n}\n/** Owned public SDK REST gateway; only the optional mutation runner uses RPC. */\nexport function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account: AccountInstance\n}): Promise<GatewaySession<XyoGatewayRunner>>\nexport function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account?: undefined\n}): Promise<GatewaySession<XyoGateway>>\nexport async function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account?: AccountInstance\n}): Promise<GatewaySession<XyoGateway | XyoGatewayRunner>> {\n const rest = {\n finalized: { type: 'rest' as const, baseUrl: options.finalizedUrl },\n chainState: { type: 'rest' as const, baseUrl: options.chainStateUrl },\n index: { type: 'rest' as const, baseUrl: options.indexUrl ?? options.finalizedUrl },\n }\n const locator = options.account === undefined\n ? await basicRestViewerLocator('event-kit-publisher-read', rest, undefined, { fetchFn: options.fetchFn, primeCaches: 'off' })\n : await basicRestRunnerLocator('event-kit-publisher-write', rest, undefined, {\n fetchFn: options.fetchFn, primeCaches: 'off', rpcUrl: options.rpcUrl, signerAccount: options.account,\n })\n try {\n const gateway = options.account === undefined\n ? await locator.getInstance<XyoGateway>(XyoGatewayMoniker)\n : await locator.getInstance<XyoGatewayRunner>(XyoGatewayRunnerMoniker)\n let stopping: Promise<void> | undefined\n return Object.freeze({ gateway, stop: () => stopping ??= releaseProviderFactoryLocator(locator) })\n } catch (error) {\n await releaseProviderFactoryLocator(locator)\n throw error\n }\n}\n@creatableProvider()\nclass BoundedRestDataLakeViewer extends RestDataLakeViewer {\n override get client() {\n if (this.context.fetchFn === undefined)\n throw new Error('Publisher datalake requires its bounded fetch transport')\n return new FetchJsonClient({ fetcher: this.context.fetchFn })\n }\n}\n@creatableProvider()\nclass BoundedRestDataLakeRunner extends RestDataLakeRunner {\n override get client() {\n if (this.context.fetchFn === undefined)\n throw new Error('Publisher datalake requires its bounded fetch transport')\n return new FetchJsonClient({ fetcher: this.context.fetchFn })\n }\n}\n/** Keeps SDK datalake methods and response semantics, overriding only its per-instance HTTP client. */\nexport async function openPublisherDataLake(options: {\n readonly fetchFn: typeof globalThis.fetch\n readonly url: string\n readonly writable: boolean\n}) {\n const locator = await baseConfigFactoryLocator({\n connections: { 'event-kit-lake': { type: 'rest', baseUrl: options.url } },\n providerBindings: { DataLakeViewer: { connection: 'event-kit-lake' }, DataLakeRunner: { connection: 'event-kit-lake' } },\n })\n locator.context.fetchFn = options.fetchFn\n locator.register(BoundedRestDataLakeViewer.factory<BoundedRestDataLakeViewer>(BoundedRestDataLakeViewer.dependencies))\n if (options.writable)\n locator.register(BoundedRestDataLakeRunner.factory<BoundedRestDataLakeRunner>(BoundedRestDataLakeRunner.dependencies))\n locator.freeze()\n try {\n const reader = await locator.getInstance<BoundedRestDataLakeViewer>(BoundedRestDataLakeViewer.defaultMoniker)\n const writer = options.writable ? await locator.getInstance<BoundedRestDataLakeRunner>(BoundedRestDataLakeRunner.defaultMoniker) : undefined\n return {\n reader, writer, async close() { await releaseProviderFactoryLocator(locator) },\n }\n } catch (error) {\n await releaseProviderFactoryLocator(locator)\n throw error\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport type { PublisherEndpointChallengeRecord, PublisherEndpointChallengeStore } from '@xyo-network/event-kit-protocol'\nimport { endpointChallengeHash } from '@xyo-network/event-kit-protocol'\nimport {\n Base64Url32BytesZod, EndpointChallengeZod, HandshakeIdZod, HashZod, NormalizedAddressZod,\n} from '@xyo-network/event-kit-schemas'\nimport type { EventKitReplayCheckpointStore } from '@xyo-network/event-kit-statement-graph'\nimport type {\n FinalizedStatementPublicationIntent, FinalizedStatementPublicationJournal, FinalizedStatementPublicationRecord,\n} from '@xyo-network/event-kit-xl1'\nimport { z } from 'zod'\n\nimport type { PublisherEncryptionKeyCustody } from '../handshakeClients.ts'\nimport type { HandshakeMutationIntent, HandshakeMutationIntentStore } from '../handshakeMutationIntent.ts'\nimport {\n assertSameIntentBinding, intentLookupKey, parseHandshakeMutationIntent,\n} from '../handshakeMutationIntent.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\n\nconst KeyZod = z.strictObject({\n encryptionKey: HashZod, keyId: HandshakeIdZod, privateKey: Base64Url32BytesZod, publisher: NormalizedAddressZod,\n})\nconst phases = ['signed', 'content-written', 'content-verified', 'broadcast', 'included', 'finalized'] as const\n\nfunction requireTime(value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new Error('Publisher clock is invalid')\n}\n\nfunction samePublicationIntent(left: FinalizedStatementPublicationIntent, right: FinalizedStatementPublicationIntent): boolean {\n return left.chainId === right.chainId && left.source === right.source && left.operationId === right.operationId\n && isDeepStrictEqual(left.eventHashes, right.eventHashes) && isDeepStrictEqual(left.attachmentHashes, right.attachmentHashes)\n}\n\nfunction publicationKey(intent: FinalizedStatementPublicationIntent): string {\n if (!/^[0-9a-f]{40}$/u.test(intent.chainId) || !/^[0-9a-f]{40}$/u.test(intent.source)\n || intent.operationId.length === 0 || intent.operationId.length > 256\n || [...intent.eventHashes, ...intent.attachmentHashes].some(hash => !HashZod.safeParse(hash).success)) {\n throw new Error('Invalid publication intent')\n }\n return JSON.stringify([intent.chainId, intent.source, intent.operationId])\n}\n\n/** All handshake durability uses the same single-owner SQLite authority as delivery. */\nexport function createSqlitePublisherHandshakeStores(state: SqlitePublisherState, options: { readonly replayNamespace?: string } = {}): {\n readonly challenges: PublisherEndpointChallengeStore\n readonly intents: HandshakeMutationIntentStore\n readonly journal: FinalizedStatementPublicationJournal\n readonly keys: PublisherEncryptionKeyCustody\n readonly replay: EventKitReplayCheckpointStore\n} {\n const replayKey = options.replayNamespace === undefined ? 'checkpoint' : `checkpoint:${z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/u).parse(options.replayNamespace)}`\n const replay: EventKitReplayCheckpointStore = {\n load: async () => state.get('replay', replayKey),\n async save(checkpoint) { state.set('replay', replayKey, checkpoint) },\n }\n const intents: HandshakeMutationIntentStore = {\n async get(lookup) {\n const value = state.get('intents', intentLookupKey(lookup))\n return value === undefined ? undefined : await parseHandshakeMutationIntent(value)\n },\n async getOrCreate(raw) {\n const proposed = await parseHandshakeMutationIntent(raw) as typeof raw\n return state.transaction(() => {\n const key = intentLookupKey(proposed)\n const winner = state.get<HandshakeMutationIntent>('intents', key)\n if (winner !== undefined) {\n assertSameIntentBinding(winner, proposed)\n return { disposition: 'resumed' as const, intent: winner as typeof raw }\n }\n state.set('intents', key, proposed)\n return { disposition: 'created' as const, intent: proposed }\n })\n },\n }\n const keys: PublisherEncryptionKeyCustody = {\n async getPrivateKey(input) {\n const key = `${NormalizedAddressZod.parse(input.publisher)}:${HandshakeIdZod.parse(input.keyId)}`\n const raw = state.get('encryption-keys', key)\n if (raw === undefined) return\n const record = KeyZod.parse(raw)\n if (record.encryptionKey !== HashZod.parse(input.encryptionKey)) throw new Error('Encryption key identity mismatch')\n const { publisher: _publisher, ...privateKey } = record\n return privateKey\n },\n async putPrivateKey(input) {\n const record = KeyZod.parse({ ...input.key, publisher: input.publisher })\n return state.transaction(() => {\n const key = `${record.publisher}:${record.keyId}`\n const prior = state.get('encryption-keys', key)\n if (prior !== undefined) {\n if (!isDeepStrictEqual(prior, record)) throw new Error('Encryption key collision')\n return 'duplicate'\n }\n state.set('encryption-keys', key, record)\n return 'stored'\n })\n },\n }\n const current = (hash: string) => state.get<PublisherEndpointChallengeRecord>('challenges', HashZod.parse(hash))\n const live = (record: PublisherEndpointChallengeRecord, now: number) => record.challenge.issuedAt <= now && now < record.challenge.expiresAt\n const challenges: PublisherEndpointChallengeStore = {\n get: async hash => current(hash),\n async issue(input) {\n const challenge = EndpointChallengeZod.parse(input.challenge)\n const hash = HashZod.parse(input.challengeHash)\n if (await endpointChallengeHash(challenge) !== hash) return { kind: 'collision' }\n return state.transaction(() => {\n const priorNonce = state.get<string>('challenge-nonces', challenge.nonce)\n if (priorNonce !== undefined && priorNonce !== hash) return { kind: 'collision' as const }\n const prior = current(hash)\n if (prior !== undefined) return isDeepStrictEqual(prior.challenge, challenge)\n ? { kind: 'duplicate' as const, record: prior }\n : { kind: 'collision' as const }\n const record: PublisherEndpointChallengeRecord = {\n challenge, challengeHash: hash, state: 'issued',\n }\n state.set('challenge-nonces', challenge.nonce, hash)\n state.set('challenges', hash, record)\n return { kind: 'issued' as const, record }\n })\n },\n async beginAttempt(input) {\n requireTime(input.nowSeconds)\n return state.transaction(() => {\n const record = current(input.challengeHash)\n if (record === undefined) return { kind: 'missing' as const }\n if (record.state === 'verified') return { kind: 'verified' as const, record }\n if (record.state === 'attempted') return { kind: 'already-attempted' as const, record }\n if (!live(record, input.nowSeconds)) return { kind: 'expired' as const, record }\n const attempted: PublisherEndpointChallengeRecord = { ...record, state: 'attempted' }\n state.set('challenges', input.challengeHash, attempted)\n return { kind: 'started' as const, record: attempted }\n })\n },\n async completeVerified(input) {\n requireTime(input.nowSeconds)\n const responseHash = HashZod.parse(input.responseHash)\n return state.transaction(() => {\n const record = current(input.challengeHash)\n if (record === undefined) return { kind: 'missing' as const }\n if (record.state === 'verified') return { kind: record.responseHash === responseHash ? 'duplicate' as const : 'collision' as const, record }\n if (record.state !== 'attempted') return { kind: 'not-attempted' as const, record }\n if (!live(record, input.nowSeconds)) return { kind: 'expired' as const, record }\n const verified: PublisherEndpointChallengeRecord = {\n ...record, responseHash, state: 'verified',\n }\n state.set('challenges', input.challengeHash, verified)\n return { kind: 'verified' as const, record: verified }\n })\n },\n }\n const journal: FinalizedStatementPublicationJournal = {\n async load(intent) {\n const key = publicationKey(intent)\n const signed = state.get<FinalizedStatementPublicationRecord>('publication:signed', key)\n if (signed === undefined) return\n if (!samePublicationIntent(signed, intent)) throw new Error('Publication intent collision')\n let latest = signed\n for (const phase of phases) {\n const record = state.get<FinalizedStatementPublicationRecord>(`publication:${phase}`, key)\n if (record === undefined) continue\n if (record.phase !== phase || !samePublicationIntent(record, intent) || !isDeepStrictEqual(record.evidence, signed.evidence)) {\n throw new Error('Publication evidence collision')\n }\n latest = record\n }\n return latest\n },\n async save(record) {\n const key = publicationKey(record)\n HashZod.parse(record.evidence.transactionHash)\n if (!phases.includes(record.phase)) throw new Error('Unknown publication phase')\n state.transaction(() => {\n const signed = state.get<FinalizedStatementPublicationRecord>('publication:signed', key)\n if (signed === undefined && record.phase !== 'signed') throw new Error('Publication must bind signed evidence first')\n if (signed !== undefined && (!samePublicationIntent(signed, record) || !isDeepStrictEqual(signed.evidence, record.evidence))) {\n throw new Error('Publication intent or evidence collision')\n }\n const namespace = `publication:${record.phase}`\n const prior = state.get(namespace, key)\n if (prior !== undefined && !isDeepStrictEqual(prior, record)) throw new Error('Publication phase collision')\n if (prior === undefined) state.set(namespace, key, record)\n })\n },\n }\n return {\n challenges, intents, journal, keys, replay,\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport {\n lstat, mkdir, open,\n} from 'node:fs/promises'\nimport { hostname } from 'node:os'\nimport PATH from 'node:path'\n\nimport { stringifyJson } from '../filesystemJson.ts'\nexport interface SqlitePublisherStateOptions {\n /** Immutable chain/publisher binding. A database must never silently change owners. */\n readonly identity: string\n readonly path: string\n}\ninterface JsonRow {\n readonly value: string\n}\ninterface OwnerRow {\n readonly host: string\n readonly pid: number\n readonly token: string\n}\n/** Single-process SQLite authority for publisher checkpoints, custody and delivery records. */\nexport interface SqlitePublisherState {\n readonly path: string\n close(): void\n entries<T>(namespace: string): readonly {\n readonly key: string\n readonly value: T\n }[]\n get<T>(namespace: string, key: string): T | undefined\n insert(namespace: string, key: string, value: unknown): boolean\n remove(namespace: string, key: string): void\n set(namespace: string, key: string, value: unknown): void\n transaction<T>(work: () => T): T\n}\nfunction decode<T>(value: string): T {\n return JSON.parse(value, (_key, candidate: unknown) => {\n return typeof candidate === 'object' && candidate !== null && Object.keys(candidate).length === 1\n && '$eventKitBigInt' in candidate && typeof candidate.$eventKitBigInt === 'string'\n && /^(?:0|[1-9][0-9]*)$/u.test(candidate.$eventKitBigInt)\n ? BigInt(candidate.$eventKitBigInt)\n : candidate\n }) as T\n}\nfunction processExists(pid: number): boolean {\n if (!Number.isSafeInteger(pid) || pid < 1)\n throw new Error('Invalid publisher owner record')\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ESRCH')\n return false\n return true\n }\n}\nexport async function openSqlitePublisherState(options: SqlitePublisherStateOptions): Promise<SqlitePublisherState> {\n if (options.path === ':memory:' || options.identity.length === 0)\n throw new Error('Persistent publisher needs a file and an identity')\n const path = PATH.resolve(options.path)\n const directory = PATH.dirname(path)\n await mkdir(directory, { recursive: true, mode: 0o700 })\n const metadata = await lstat(directory)\n if (!metadata.isDirectory() || (metadata.mode & 0o077) !== 0)\n throw new Error('Publisher state directory must be a real directory with 0700 permissions')\n const file = await open(path, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW, 0o600)\n try {\n const metadata = await file.stat()\n if (!metadata.isFile() || (metadata.mode & 0o077) !== 0)\n throw new Error('Publisher database permissions must be 0600')\n await file.sync()\n } finally {\n await file.close()\n }\n const { DatabaseSync } = await import('node:sqlite')\n const database = new DatabaseSync(path)\n const token = randomBytes(16).toString('hex')\n let closed = false\n let inTransaction = false\n const transaction = <T>(work: () => T): T => {\n if (closed)\n throw new Error('Publisher state is closed')\n if (inTransaction)\n return work()\n database.exec('BEGIN IMMEDIATE')\n inTransaction = true\n try {\n const result = work()\n if (result instanceof Promise)\n throw new TypeError('Publisher state transactions must be synchronous')\n database.exec('COMMIT')\n return result\n } catch (error) {\n database.exec('ROLLBACK')\n throw error\n } finally {\n inTransaction = false\n }\n }\n try {\n database.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = FULL;\n PRAGMA busy_timeout = 5000;\n CREATE TABLE IF NOT EXISTS publisher_records (namespace TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY(namespace, key));\n CREATE TABLE IF NOT EXISTS publisher_owner (id INTEGER PRIMARY KEY CHECK(id = 1), host TEXT NOT NULL, pid INTEGER NOT NULL, token TEXT NOT NULL);\n `)\n transaction(() => {\n const prior = database.prepare('SELECT host, pid, token FROM publisher_owner WHERE id = 1').get() as OwnerRow | undefined\n if (prior !== undefined && (prior.host !== hostname() || processExists(prior.pid))) {\n throw new Error('Publisher database already has an active owner; a shared or multi-host database is not supported')\n }\n const binding = database.prepare('SELECT value FROM publisher_records WHERE namespace = ? AND key = ?').get('metadata', 'identity') as JsonRow | undefined\n if (binding !== undefined && decode(binding.value) !== options.identity)\n throw new Error('Publisher database identity mismatch')\n database.prepare('INSERT OR IGNORE INTO publisher_records(namespace,key,value) VALUES (?,?,?)').run('metadata', 'identity', stringifyJson(options.identity))\n database.prepare('INSERT OR REPLACE INTO publisher_owner(id,host,pid,token) VALUES (1,?,?,?)').run(hostname(), process.pid, token)\n })\n } catch (error) {\n database.close()\n throw error\n }\n const read = database.prepare('SELECT value FROM publisher_records WHERE namespace = ? AND key = ?')\n const list = database.prepare('SELECT key, value FROM publisher_records WHERE namespace = ? ORDER BY key')\n const write = database.prepare('INSERT INTO publisher_records(namespace,key,value) VALUES (?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET value = excluded.value')\n const insert = database.prepare('INSERT OR IGNORE INTO publisher_records(namespace,key,value) VALUES (?,?,?)')\n const remove = database.prepare('DELETE FROM publisher_records WHERE namespace = ? AND key = ?')\n const assertOpen = () => {\n if (closed)\n throw new Error('Publisher state is closed')\n }\n return {\n path,\n get<T>(namespace: string, key: string): T | undefined {\n assertOpen()\n const row = read.get(namespace, key) as JsonRow | undefined\n return row === undefined ? undefined : decode<T>(row.value)\n },\n entries<T>(namespace: string) {\n assertOpen()\n return (list.all(namespace) as {\n key: string\n value: string\n }[]).map(row => ({ key: row.key, value: decode<T>(row.value) }))\n },\n set(namespace, key, value) {\n assertOpen()\n write.run(namespace, key, stringifyJson(value))\n },\n insert(namespace, key, value) {\n assertOpen()\n return insert.run(namespace, key, stringifyJson(value)).changes === 1\n },\n remove(namespace, key) {\n assertOpen()\n remove.run(namespace, key)\n },\n transaction,\n close() {\n if (closed)\n return\n transaction(() => {\n database.prepare('DELETE FROM publisher_owner WHERE id = 1 AND token = ?').run(token)\n })\n database.close()\n closed = true\n },\n }\n}\n", "import { createHash, randomBytes } from 'node:crypto'\n\nimport type { BestEffortAuthorizedAdmission, BestEffortCommitResult } from '@xyo-network/event-kit-protocol'\nimport {\n canonicalJson, commitBestEffortSecurity, createBestEffortSecurityState, parseAdmittedWake,\n parseBestEffortSecurityState, wakeSourceHash,\n} from '@xyo-network/event-kit-protocol'\nimport {\n ChainIdZod, DeploymentIdZod, HashZod, NonnegativeJsonSafeIntegerZod, NormalizedAddressZod,\n WakeJwtAudienceZod, WakeSourceZod,\n} from '@xyo-network/event-kit-schemas'\nimport { z } from 'zod'\n\nimport type {\n BestEffortConsumerBinding, BestEffortDirtyTarget, BestEffortWorkerLease, PersistentBestEffortInbox,\n} from './bestEffortTypes.ts'\nimport { openPrivateSqlite } from './privateSqlite.ts'\n\nexport interface SqliteBestEffortInboxOptions {\n /** An immutable host application/consumer identifier. Do not share with Durable Delivery. */\n readonly consumerId: string\n /** Finite per-index replay capacity; unexpired records are never evicted. */\n readonly maxSecurityRecords: number\n /** Finite exact binding capacity, including retained completed targets. */\n readonly maxTargets?: number\n readonly nowSeconds?: () => number\n readonly path: string\n /** Acceleration only. Failure is repaired by durable scanning or a matching duplicate. */\n readonly requestWork?: (target: BestEffortDirtyTarget) => void | Promise<void>\n}\n\nconst BindingZod = z.strictObject({\n audience: WakeJwtAudienceZod,\n authorizationChainId: ChainIdZod,\n consumerId: z.string().min(1).max(255),\n controller: NormalizedAddressZod,\n deploymentId: DeploymentIdZod,\n filterHash: HashZod,\n publisher: NormalizedAddressZod,\n queueId: z.string().min(1).max(255).optional(),\n source: WakeSourceZod,\n subscriptionHash: HashZod,\n})\nconst SnapshotPositionZod = z.strictObject({\n position: NonnegativeJsonSafeIntegerZod,\n hash: HashZod.optional(),\n})\nconst TargetZod = z.strictObject({\n binding: BindingZod,\n completedGeneration: NonnegativeJsonSafeIntegerZod,\n generation: NonnegativeJsonSafeIntegerZod,\n id: HashZod,\n requestedPosition: NonnegativeJsonSafeIntegerZod,\n fence: NonnegativeJsonSafeIntegerZod,\n previousSnapshot: SnapshotPositionZod.optional(),\n lease: z.strictObject({\n expiresAt: NonnegativeJsonSafeIntegerZod,\n token: z.string().regex(/^[0-9a-f]{32}$/u),\n }).optional(),\n}).refine(\n target => target.generation > 0 && target.completedGeneration <= target.generation\n && (target.lease === undefined || (target.fence > 0 && target.generation > target.completedGeneration))\n && (target.previousSnapshot === undefined || target.binding.source.kind === 'utc-interval' || target.previousSnapshot.hash !== undefined),\n 'Invalid Best Effort dirty generation',\n)\ntype StoredTarget = z.infer<typeof TargetZod>\nconst CatalogZod = z.strictObject({\n id: HashZod,\n binding: z.string(),\n target_hash: HashZod,\n fence: NonnegativeJsonSafeIntegerZod,\n generation: NonnegativeJsonSafeIntegerZod,\n}).refine(record => record.generation > 0, 'Invalid Best Effort catalog generation')\ntype TargetCatalog = z.infer<typeof CatalogZod>\n\nfunction bindingId(binding: BestEffortConsumerBinding) {\n return createHash('sha256').update(canonicalJson(binding)).digest('hex')\n}\nfunction targetHash(body: string) {\n return createHash('sha256').update(body).digest('hex')\n}\nfunction parseCatalog(value: unknown): TargetCatalog {\n const record = CatalogZod.parse(value)\n const binding = BindingZod.parse(JSON.parse(record.binding))\n if (record.id !== bindingId(binding) || record.binding !== canonicalJson(binding))\n throw new TypeError('Persisted Best Effort catalog changed exact binding')\n return record\n}\nfunction parseTarget(body: unknown, expectedId: string): StoredTarget {\n if (typeof body !== 'string') throw new TypeError('Malformed persisted Best Effort target')\n const parsed = TargetZod.parse(JSON.parse(body))\n if (parsed.id !== expectedId || bindingId(parsed.binding) !== expectedId)\n throw new TypeError('Persisted Best Effort target changed exact scope')\n return parsed\n}\nfunction publicTarget(target: StoredTarget): BestEffortDirtyTarget {\n return {\n binding: target.binding,\n completedGeneration: target.completedGeneration,\n generation: target.generation,\n id: target.id,\n requestedPosition: target.requestedPosition,\n }\n}\nfunction increment(value: number) {\n if (!Number.isSafeInteger(value + 1)) throw new RangeError('Best Effort fence/generation exhausted')\n return value + 1\n}\n\n/**\n * SQLite co-commits security, receive-clock high water and dirty generation in\n * one writer transaction. Only the Best Effort namespace is decoded. No callback\n * or external queue participates in the durability boundary.\n */\nexport async function createSqliteBestEffortInbox(options: SqliteBestEffortInboxOptions): Promise<PersistentBestEffortInbox> {\n const consumerId = z.string().min(1).max(255).parse(options.consumerId)\n const maxTargets = options.maxTargets ?? 1024\n if (!Number.isSafeInteger(options.maxSecurityRecords) || options.maxSecurityRecords < 1 || options.maxSecurityRecords > 65_536)\n throw new TypeError('Invalid finite Best Effort security capacity')\n if (!Number.isSafeInteger(maxTargets) || maxTargets < 1 || maxTargets > 65_536)\n throw new TypeError('Invalid finite Best Effort target capacity')\n const nowSeconds = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const connection = openPrivateSqlite({ path: options.path, format: 'event-kit-best-effort-inbox' })\n const { database } = connection\n const transaction = <T>(work: () => T): T => connection.transaction(work)\n try {\n const settings = canonicalJson({\n consumerId, maxSecurityRecords: options.maxSecurityRecords, maxTargets,\n })\n transaction(() => {\n const marker = database.prepare('SELECT initialized FROM eventkit_store WHERE id = 1').get()\n if (marker?.initialized !== 0 && marker?.initialized !== 1)\n throw new TypeError('Invalid Best Effort store initialization authority')\n const tables = database.prepare(\"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\").all()\n const names = new Set(tables.map(row => row.name))\n if (marker.initialized === 1) {\n if (['best_effort_security', 'best_effort_targets', 'best_effort_settings', 'best_effort_catalog'].some(name => !names.has(name)))\n throw new TypeError('Initialized Best Effort store lost authoritative tables; restore its custody before reopening')\n const previous = database.prepare('SELECT body FROM best_effort_settings WHERE id = 1').get()\n if (previous === undefined) throw new TypeError('Missing immutable Best Effort store settings')\n if (previous.body !== settings) throw new TypeError('Best Effort store consumer or capacity binding changed')\n return\n }\n\n if (tables.some(row => row.name !== 'eventkit_store'))\n throw new TypeError('Uninitialized Best Effort bootstrap contains unexpected custody')\n database.exec(`\n CREATE TABLE best_effort_security (id INTEGER PRIMARY KEY CHECK (id = 1), body TEXT NOT NULL);\n CREATE TABLE best_effort_targets (id TEXT PRIMARY KEY, body TEXT NOT NULL);\n CREATE TABLE best_effort_settings (id INTEGER PRIMARY KEY CHECK (id = 1), body TEXT NOT NULL, catalog_count INTEGER NOT NULL);\n CREATE TABLE best_effort_catalog (id TEXT PRIMARY KEY, binding TEXT NOT NULL, target_hash TEXT NOT NULL, fence INTEGER NOT NULL, generation INTEGER NOT NULL);\n `)\n database.prepare('INSERT INTO best_effort_settings (id, body, catalog_count) VALUES (1, ?, 0)').run(settings)\n database.prepare('INSERT INTO best_effort_security (id, body) VALUES (1, ?)')\n .run(JSON.stringify(createBestEffortSecurityState()))\n database.prepare('UPDATE eventkit_store SET initialized = 1 WHERE id = 1').run()\n })\n const readSecurity = () => {\n const row = database.prepare('SELECT body FROM best_effort_security WHERE id = 1').get()\n if (typeof row?.body !== 'string') throw new TypeError('Missing persisted Best Effort security state')\n const parsed = parseBestEffortSecurityState(JSON.parse(row.body))\n if (parsed.jwtRecords.length > options.maxSecurityRecords || parsed.wakeRecords.length > options.maxSecurityRecords)\n throw new TypeError('Persisted Best Effort security exceeds its configured bound')\n return parsed\n }\n const readCatalog = (id: string) => {\n const row = database.prepare('SELECT id, binding, target_hash, fence, generation FROM best_effort_catalog WHERE id = ?').get(id)\n return row === undefined ? undefined : parseCatalog(row)\n }\n const verifiedTarget = (body: unknown, catalog: TargetCatalog): StoredTarget => {\n const target = parseTarget(body, catalog.id)\n if (target.binding.consumerId !== consumerId) throw new TypeError('Persisted Best Effort target changed consumer')\n if (typeof body !== 'string' || catalog.target_hash !== targetHash(body)\n || catalog.binding !== canonicalJson(target.binding) || catalog.fence !== target.fence || catalog.generation !== target.generation)\n throw new TypeError('Persisted Best Effort target differs from its permanent catalog authority')\n return target\n }\n const readTargets = () => {\n const setting = database.prepare('SELECT catalog_count FROM best_effort_settings WHERE id = 1').get()\n const expectedCount = NonnegativeJsonSafeIntegerZod.parse(setting?.catalog_count)\n if (expectedCount > maxTargets) throw new TypeError('Persisted Best Effort catalog capacity exceeded')\n const catalogs = database.prepare('SELECT id, binding, target_hash, fence, generation FROM best_effort_catalog ORDER BY id').all()\n .map(parseCatalog)\n const rows = database.prepare('SELECT id, body FROM best_effort_targets ORDER BY id').all()\n if (catalogs.length !== expectedCount || rows.length !== expectedCount)\n throw new TypeError('Persisted Best Effort binding catalog lost authoritative target custody')\n const byId = new Map(catalogs.map(catalog => [catalog.id, catalog]))\n return rows.map((row) => {\n if (typeof row.id !== 'string') throw new TypeError('Malformed persisted Best Effort target identity')\n const catalog = byId.get(row.id)\n if (catalog === undefined) throw new TypeError('Persisted Best Effort target lost permanent binding custody')\n return verifiedTarget(row.body, catalog)\n })\n }\n const readTarget = (id: string) => {\n const row = database.prepare('SELECT body FROM best_effort_targets WHERE id = ?').get(id)\n const catalog = readCatalog(id)\n if (row === undefined && catalog === undefined) return\n if (row === undefined || catalog === undefined)\n throw new TypeError('Persisted Best Effort binding lost its authoritative target/catalog custody')\n return verifiedTarget(row.body, catalog)\n }\n const saveTarget = (target: StoredTarget) => {\n const catalog = readCatalog(target.id)\n const body = JSON.stringify(target)\n const binding = canonicalJson(target.binding)\n if (catalog === undefined) {\n if (database.prepare('SELECT id FROM best_effort_targets WHERE id = ?').get(target.id) !== undefined)\n throw new TypeError('Existing Best Effort target lost its permanent binding catalog')\n database.prepare('INSERT INTO best_effort_catalog (id, binding, target_hash, fence, generation) VALUES (?, ?, ?, ?, ?)')\n .run(target.id, binding, targetHash(body), target.fence, target.generation)\n database.prepare('UPDATE best_effort_settings SET catalog_count = catalog_count + 1 WHERE id = 1').run()\n } else {\n if (catalog.binding !== binding || target.fence < catalog.fence || target.generation < catalog.generation)\n throw new TypeError('Best Effort target mutation would regress permanent binding authority')\n database.prepare('UPDATE best_effort_catalog SET target_hash = ?, fence = ?, generation = ? WHERE id = ?')\n .run(targetHash(body), target.fence, target.generation, target.id)\n }\n database.prepare('INSERT INTO best_effort_targets (id, body) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET body = excluded.body')\n .run(target.id, body)\n }\n transaction(() => {\n const security = readSecurity()\n const targets = readTargets()\n if (security.jwtRecords.length > options.maxSecurityRecords || security.wakeRecords.length > options.maxSecurityRecords\n || targets.length > maxTargets || targets.some(target => target.binding.consumerId !== consumerId))\n throw new TypeError('Persisted Best Effort state exceeds its exact bound')\n })\n\n async function requestWork(target: StoredTarget) {\n if (target.generation === target.completedGeneration || options.requestWork === undefined) return false\n try {\n await options.requestWork(publicTarget(target))\n return true\n } catch {\n // Durable dirty state, not callback success, determines admitted work.\n return false\n }\n }\n const currentTarget = (captured: StoredTarget): StoredTarget | undefined => {\n const current = readTarget(captured.id)\n const now = NonnegativeJsonSafeIntegerZod.parse(nowSeconds())\n return current?.lease?.token === captured.lease?.token && current?.fence === captured.fence\n && current?.generation === captured.generation && current.lease !== undefined\n && current.lease.expiresAt > now\n ? current\n : undefined\n }\n\n return {\n async commitAuthorized(input: BestEffortAuthorizedAdmission): Promise<BestEffortCommitResult> {\n input = structuredClone(input)\n const wake = await parseAdmittedWake(input.wake)\n const grant = input.grant.grant\n if (grant.authorizationKind !== 'activated-subscription'\n || grant.target !== wake.publisher || grant.authorizationChainId !== wake.event.authorizationChainId\n || grant.deploymentId !== wake.deploymentId || grant.filterHash !== wake.event.filterHash\n || grant.queueId !== wake.queueId || grant.sourceHash !== await wakeSourceHash(wake.event.source))\n throw new TypeError('Best Effort grant does not match its exact admitted profile')\n const binding = BindingZod.parse({\n consumerId,\n audience: wake.audience,\n authorizationChainId: wake.event.authorizationChainId,\n controller: grant.controller,\n deploymentId: wake.deploymentId,\n filterHash: wake.event.filterHash,\n publisher: wake.publisher,\n source: wake.event.source,\n subscriptionHash: grant.subscriptionHash,\n ...(wake.queueId === undefined ? {} : { queueId: wake.queueId }),\n })\n const id = bindingId(binding)\n const committed = transaction(() => {\n const authority = { security: readSecurity(), targets: readTargets() }\n const next = commitBestEffortSecurity(authority.security, { ...input, wake }, options.maxSecurityRecords)\n if (next.result.kind !== 'accepted' && next.result.kind !== 'duplicate') return { result: next.result }\n const previous = authority.targets.find(target => target.id === id)\n if (previous === undefined && next.result.kind === 'duplicate')\n throw new TypeError('Persisted duplicate lost its authoritative Best Effort target')\n if (previous === undefined && authority.targets.length >= maxTargets)\n return { result: { kind: 'capacity-exceeded' } as const }\n const target: StoredTarget = previous === undefined\n ? {\n binding, id, completedGeneration: 0, generation: 1, fence: 0, requestedPosition: wake.toPosition,\n }\n : next.result.kind === 'duplicate'\n ? previous\n : {\n ...previous,\n generation: increment(previous.generation),\n requestedPosition: Math.max(previous.requestedPosition, wake.toPosition),\n }\n database.prepare('UPDATE best_effort_security SET body = ? WHERE id = 1').run(JSON.stringify(next.state))\n saveTarget(target)\n return { result: next.result, target }\n })\n if (committed.target !== undefined) await requestWork(committed.target)\n return committed.result\n },\n dirtyTargets: async () => transaction(() => readTargets().filter(target => target.generation > target.completedGeneration).map(publicTarget)),\n async repairDirty() {\n let failed = 0\n let scheduled = 0\n const targets = transaction(() => readTargets())\n for (const target of targets) {\n if (options.requestWork === undefined || target.generation === target.completedGeneration) continue\n if (await requestWork(target)) scheduled += 1\n else failed += 1\n }\n return { failed, scheduled }\n },\n async recoverExpired(now) {\n NonnegativeJsonSafeIntegerZod.parse(now)\n return transaction(() => {\n let recovered = 0\n for (const target of readTargets()) {\n if (target.lease === undefined || target.lease.expiresAt > now) continue\n saveTarget({ ...target, lease: undefined })\n recovered += 1\n }\n return recovered\n })\n },\n async claim(input): Promise<BestEffortWorkerLease | undefined> {\n NonnegativeJsonSafeIntegerZod.parse(input.nowSeconds)\n if (!Number.isSafeInteger(input.leaseSeconds) || input.leaseSeconds < 1\n || !Number.isSafeInteger(input.nowSeconds + input.leaseSeconds))\n throw new TypeError('Invalid Best Effort worker lease lifetime')\n const captured = transaction(() => {\n const target = readTargets().find(item => item.generation > item.completedGeneration && item.lease === undefined)\n if (target === undefined) return\n const claimed: StoredTarget = {\n ...target,\n fence: increment(target.fence),\n lease: { token: randomBytes(16).toString('hex'), expiresAt: input.nowSeconds + input.leaseSeconds },\n }\n saveTarget(claimed)\n return claimed\n })\n if (captured?.lease === undefined) return undefined\n return {\n ...publicTarget(captured),\n fence: captured.fence,\n leaseToken: captured.lease.token,\n ...(captured.previousSnapshot === undefined ? {} : { previousSnapshot: captured.previousSnapshot }),\n isCurrent: async () => transaction(() => currentTarget(captured) !== undefined),\n async complete(snapshot) {\n const position = SnapshotPositionZod.parse({ position: snapshot.position, ...(snapshot.hash === undefined ? {} : { hash: snapshot.hash }) })\n return transaction(() => {\n const current = currentTarget(captured)\n if (current === undefined) return false\n if (current.binding.source.kind !== 'utc-interval' && position.hash === undefined)\n throw new TypeError('Finalized snapshot completion requires its verified hash')\n const previous = current.previousSnapshot\n if (previous !== undefined && (position.position < previous.position\n || (position.position === previous.position && position.hash !== previous.hash)))\n throw new TypeError('Best Effort completion regressed its committed snapshot')\n saveTarget({\n ...current, completedGeneration: current.generation, previousSnapshot: position, lease: undefined,\n })\n return true\n })\n },\n async release() {\n transaction(() => {\n const current = readTarget(captured.id)\n if (current?.lease?.token === captured.lease?.token && current?.fence === captured.fence)\n saveTarget({ ...current, lease: undefined })\n })\n },\n }\n },\n close: () => connection.close(),\n }\n } catch (error) {\n connection.close()\n throw error\n }\n}\n", "import type { WakeQueue } from '@xyo-network/event-kit-protocol'\n\nimport { openReceiverAuthority } from './receiverAuthority.ts'\n\nexport interface SqliteWakeQueueOptions { readonly path: string }\nexport interface SqliteWakeQueue extends WakeQueue { close(): void }\n\n/** FULL/WAL queue; old unfenced databases require explicit offline migration. */\nexport async function createSqliteWakeQueue(options: SqliteWakeQueueOptions): Promise<SqliteWakeQueue> {\n const authority = openReceiverAuthority(options.path)\n return { ...authority.queue, close: authority.close }\n}\n\n/** Atomic production composition: identities and work live in one database. */\nexport async function createSqliteWakeReceiver(options: SqliteWakeQueueOptions) {\n const authority = openReceiverAuthority(options.path)\n return {\n queue: authority.queue,\n inbox: authority.inbox,\n close: authority.close,\n pruneExpiredTokens: async (nowSeconds: number) => authority.pruneExpiredTokens(nowSeconds),\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;AAAA,SAAS,eAAe,wBAAwB;AAChD;AAAA,EACE;AAAA,EAAS;AAAA,EAA+B;AAAA,OACnC;AAmDA,SAAS,+BACd,SAC0B;AAC1B,MAAI,CAAC,OAAO,cAAc,QAAQ,gBAAgB,KAAK,QAAQ,mBAAmB;AAChF,UAAM,IAAI,UAAU,qCAAqC;AAC3D,QAAM,aAAa,QAAQ,eAAe,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAC5E,QAAM,eAAe,QAAQ,gBAAgB;AAC7C,MAAI,CAAC,OAAO,cAAc,YAAY,KAAK,eAAe;AACxD,UAAM,IAAI,UAAU,2CAA2C;AAEjE,iBAAe,gBAAgB,OAA8B,QAA0D;AACrH,UAAM,SAAS,MAAM,QAAQ;AAC7B,UAAM,WAAW,MAAM,QAAQ,OAAO,YAAY;AAAA,MAChD;AAAA,MAAQ;AAAA,MAAQ,UAAU,QAAQ;AAAA,IACpC,CAAC;AACD,WAAO,eAAe;AACtB,UAAM,WAAW,MAAM,QAAQ,OAAO,eAAe;AAAA,MACnD;AAAA,MAAQ;AAAA,MAAQ,UAAU;AAAA,IAC5B,CAAC;AACD,WAAO,eAAe;AACtB,kBAAc,MAAM,SAAS,MAAM;AACnC,kCAA8B,MAAM,SAAS,QAAQ;AACrD,QAAI,SAAS,SAAS,OAAW,SAAQ,MAAM,SAAS,IAAI;AAC5D,QAAI,CAAC,iBAAiB,QAAQ,SAAS,MAAM,KACvC,OAAO,SAAS,kBAAkB,SAAS,SAAS;AACxD,YAAM,IAAI,UAAU,uDAAuD;AAC7E,QAAI,OAAO,WAAW,cAAc,SAAS,KAAK,GAAG,MAAM,IAAI,QAAQ;AACrE,YAAM,IAAI,WAAW,wDAAwD;AAC/E,UAA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SAAS;AAC1E,sBAAM,IAAI,UAAU,yDAAyD;AAC/E,yBAAW;AAAA,gBACT,GAAG;AAAA,gBAAS,qBAAqB,QAAQ;AAAA,gBAAY,kBAAkB;AAAA,gBAAU,OAAO;AAAA,cAC1F,CAAC;AACD,qBAAO;AAAA,YACT,CAAC;AAAA,UACH;AAAA,UACA,MAAM,UAAU;AACd,wBAAY,MAAM;AAChB,oBAAM,UAAU,WAAW,SAAS,EAAE;AACtC,kBAAI,SAAS,OAAO,UAAU,SAAS,OAAO,SAAS,SAAS,UAAU,SAAS;AACjF,2BAAW,EAAE,GAAG,SAAS,OAAO,OAAU,CAAC;AAAA,YAC/C,CAAC;AAAA,UACH;AAAA,QACF;AAAA,MACF;AAAA,MACA,OAAO,MAAM,WAAW,MAAM;AAAA,IAChC;AAAA,EACF,SAAS,OAAO;AACd,eAAW,MAAM;AACjB,UAAM;AAAA,EACR;AACF;;;AClXA,eAAsB,sBAAsB,SAA2D;AACrG,QAAM,YAAY,sBAAsB,QAAQ,IAAI;AACpD,SAAO,EAAE,GAAG,UAAU,OAAO,OAAO,UAAU,MAAM;AACtD;AAGA,eAAsB,yBAAyB,SAAiC;AAC9E,QAAM,YAAY,sBAAsB,QAAQ,IAAI;AACpD,SAAO;AAAA,IACL,OAAO,UAAU;AAAA,IACjB,OAAO,UAAU;AAAA,IACjB,OAAO,UAAU;AAAA,IACjB,oBAAoB,OAAO,eAAuB,UAAU,mBAAmB,UAAU;AAAA,EAC3F;AACF;",
|
|
6
6
|
"names": ["PATH", "NonnegativeJsonSafeIntegerZod", "open", "PATH", "open", "errorCode", "PATH", "PATH", "NonnegativeJsonSafeIntegerZod", "PATH", "randomBytes", "lstat", "rename", "unlink", "PATH", "PATH", "existingPrivateDirectory", "unlink", "randomBytes", "rename", "lstat", "existsSync", "readdirSync", "PATH", "randomBytes", "link", "open", "unlink", "PATH", "parseAdmittedWake", "StaleWakeLeaseError", "Buffer", "randomBytes", "HashZod", "NonnegativeJsonSafeIntegerZod", "HashZod", "NonnegativeJsonSafeIntegerZod", "Buffer", "randomBytes", "PATH", "randomBytes", "link", "unlinkIfMissing", "parseAdmittedWake", "StaleWakeLeaseError", "options", "open", "unlink", "PATH", "existsSync", "readdirSync", "PATH", "PATH", "createHash", "PATH", "createHash", "PATH", "existing", "PATH", "HashZod", "NormalizedAddressZod", "z", "lookup", "PATH", "lookup", "stat", "PATH", "Base64Url32BytesZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "PATH", "lookup", "HashZod", "HandshakeIdZod", "NormalizedAddressZod", "stat", "Base64Url32BytesZod", "PATH", "EndpointChallengeZod", "HashZod", "PATH", "HashZod", "EndpointChallengeZod", "canonicalJson", "handshakeObjectHash", "ChainIdZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "NormalizedAddressZod", "ChainIdZod", "HashZod", "HandshakeIdZod", "candidate", "handshakeObjectHash", "lookup", "view", "canonicalJson", "randomBytes", "link", "lstat", "mkdir", "open", "unlink", "PATH", "HashZod", "NormalizedAddressZod", "WakeIdZod", "WakeJwtAudienceZod", "PATH", "DatabaseSync", "parseAdmittedWake", "HashZod", "NonnegativeJsonSafeIntegerZod", "NormalizedAddressZod", "WakeIdZod", "WakeJwtAudienceZod", "WakeJwtIdZod", "z", "createHash", "constants", "lstat", "mkdir", "open", "readdir", "PATH", "PATH", "open", "constants", "lstat", "mkdir", "readdir", "createHash", "z", "WakeJwtAudienceZod", "HashZod", "NormalizedAddressZod", "WakeIdZod", "WakeJwtIdZod", "NonnegativeJsonSafeIntegerZod", "parseAdmittedWake", "PATH", "DatabaseSync", "PATH", "suffix", "open", "randomBytes", "mkdir", "link", "unlink", "lstat", "WakeIdZod", "WakeJwtAudienceZod", "HashZod", "NormalizedAddressZod", "Buffer", "scope", "Buffer", "request", "isDeepStrictEqual", "EndpointChallengeResponseZod", "isDeepStrictEqual", "response", "EndpointChallengeResponseZod", "scope", "Buffer", "z", "createHash", "canonicalJson", "WakeSourceZod", "createHash", "canonicalJson", "WakeSourceZod", "scope", "z", "scope", "Buffer", "isDeepStrictEqual", "z", "randomBytes", "isDeepStrictEqual", "WakeEnvelopeSchema", "WakeEnvelopeZod", "isDeepStrictEqual", "WakeEnvelopeZod", "randomBytes", "WakeEnvelopeSchema", "randomBytes", "NormalizedAddressZod", "WakeEnvelopeZod", "PayloadBuilder", "z", "isDeepStrictEqual", "head", "scope", "isDeepStrictEqual", "endpointChallengeHash", "Base64Url32BytesZod", "EndpointChallengeZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "z", "z", "HashZod", "HandshakeIdZod", "Base64Url32BytesZod", "NormalizedAddressZod", "requireTime", "isDeepStrictEqual", "lookup", "EndpointChallengeZod", "endpointChallengeHash", "randomBytes", "constants", "lstat", "mkdir", "open", "PATH", "PATH", "mkdir", "lstat", "open", "constants", "metadata", "DatabaseSync", "randomBytes", "createHash", "randomBytes", "canonicalJson", "parseAdmittedWake", "ChainIdZod", "HashZod", "NonnegativeJsonSafeIntegerZod", "NormalizedAddressZod", "WakeJwtAudienceZod", "WakeSourceZod", "z", "z", "WakeJwtAudienceZod", "ChainIdZod", "NormalizedAddressZod", "HashZod", "WakeSourceZod", "NonnegativeJsonSafeIntegerZod", "createHash", "canonicalJson", "parseAdmittedWake", "target", "randomBytes"]
|
|
7
7
|
}
|