@xyo-network/event-kit-node 1.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../src/filesystemCursorStore.ts", "../../src/filesystemPublisherOutbox.ts", "../../src/filesystemWakeQueue.ts", "../../src/filesystemDurability.ts", "../../src/filesystemWakeInbox.ts", "../../src/filesystemEventKitReplayCheckpointStore.ts", "../../src/filesystemJson.ts", "../../src/filesystemFinalizedStatementPublicationJournal.ts", "../../src/filesystemHandshakeMutationIntentStore.ts", "../../src/handshakeMutationIntent.ts", "../../src/filesystemPublisherEncryptionKeyStore.ts", "../../src/filesystemPublisherEndpointChallengeStore.ts", "../../src/handshakeClients.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/sourceSigner.ts", "../../src/runtime/restGateway.ts", "../../src/runtime/sqliteHandshakeStores.ts", "../../src/runtime/sqlitePublisherState.ts", "../../src/sqliteWakeQueue.ts"],
4
- "sourcesContent": ["import {\n mkdir, readFile, writeFile,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type { PublisherCursorStore } from '@xyo-network/event-kit-actor'\n\nexport interface FilesystemCursorStoreOptions {\n /** Absolute or relative path to the cursor JSON file. */\n readonly path: string\n}\n\ninterface CursorFile {\n readonly lastProcessedBlock: number\n}\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 return {\n async load(): Promise<number | undefined> {\n try {\n const raw = await readFile(filePath, 'utf8')\n const parsed = JSON.parse(raw) as CursorFile\n return typeof parsed.lastProcessedBlock !== 'number' || !Number.isFinite(parsed.lastProcessedBlock) ? undefined : parsed.lastProcessedBlock\n } catch (error) {\n if (isNotFound(error)) return undefined\n throw error\n }\n },\n async save(lastProcessedBlock: number): Promise<void> {\n await mkdir(PATH.dirname(filePath), { recursive: true })\n const body: CursorFile = { lastProcessedBlock }\n await writeFile(filePath, `${JSON.stringify(body)}\\n`, 'utf8')\n },\n }\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", "import { randomBytes } from 'node:crypto'\nimport {\n mkdir, rename, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type { PendingWake, PublisherOutbox } from '@xyo-network/event-kit-actor'\n\nimport { readJsonFile, writeDurableFile } from './filesystemWakeQueue.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\n return {\n async clear(): Promise<void> {\n try {\n await unlink(filePath)\n } catch (error) {\n if (!isNotFound(error)) throw error\n }\n },\n\n load: async (): Promise<PendingWake | undefined> => await readJsonFile<PendingWake>(filePath),\n\n async save(pending: PendingWake): Promise<void> {\n await mkdir(PATH.dirname(filePath), { recursive: true })\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 await writeDurableFile(tempPath, `${JSON.stringify(pending)}\\n`)\n try {\n await rename(tempPath, filePath)\n } catch (error) {\n try {\n await unlink(tempPath)\n } catch {\n // A leftover temp file is harmless; the rename failure is what matters.\n }\n throw error\n }\n },\n }\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", "import { randomBytes } from 'node:crypto'\nimport {\n link, open, readdir, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type {\n AdmittedWake,\n LeasedWake,\n WakeQueue,\n} from '@xyo-network/event-kit-protocol'\n\nimport {\n ensureDurableDirectory,\n syncDirectory,\n writeDurableFile,\n} from './filesystemDurability.ts'\n\nexport {\n ensureDurableDirectory,\n syncDirectory,\n writeDurableFile,\n}\n\nexport interface FilesystemWakeQueueOptions {\n /** Directory owning the `pending/` and `inflight/` entry sets. */\n readonly path: string\n}\n\nexport type FilesystemWakeQueue = WakeQueue\n\n/**\n * Directory-backed at-least-once wake queue.\n *\n * Entries are published by `link`, never `rename`. `rename` is unsound as a\n * claim: when two callers race the same source, both can observe success once\n * the paths resolve to one inode, and the entry is then handed out twice. `link`\n * fails with `EEXIST`, so exactly one claimer wins.\n *\n * A claim is `link(pending -> inflight)` followed by `unlink(pending)`. A crash\n * between the two leaves the entry in both sets as one inode; recovery drops the\n * inflight copy and the entry stays pending. A consumer that dies mid-handler\n * leaves its entry inflight for `recoverInflight` rather than dropping it.\n *\n * Ordering is approximate FIFO by entry name. Single-node only: this survives\n * process death, not host loss, and does not coordinate across machines.\n */\nexport function createFilesystemWakeQueue(\n options: FilesystemWakeQueueOptions,\n): FilesystemWakeQueue {\n const root = PATH.resolve(options.path)\n const pendingDir = PATH.join(root, 'pending')\n const inflightDir = PATH.join(root, 'inflight')\n const tempDir = PATH.join(root, 'tmp')\n let sequence = 0\n\n async function ensureDirs(): Promise<void> {\n await ensureDurableDirectory(pendingDir)\n await ensureDurableDirectory(inflightDir)\n await ensureDurableDirectory(tempDir)\n }\n\n /** Moves one entry back to `pending/`, tolerating an existing half-claimed copy. */\n async function returnToPending(name: string): Promise<void> {\n try {\n await link(PATH.join(inflightDir, name), PATH.join(pendingDir, name))\n } catch (error) {\n // EEXIST means a crash left both links to the same entry; the pending copy wins.\n if (!isAlreadyExists(error) && !isNotFound(error)) throw error\n }\n await unlinkIfMissing(PATH.join(inflightDir, name))\n }\n\n return {\n async append(wake: AdmittedWake): Promise<void> {\n await ensureDirs()\n const name = entryName(wake, sequence += 1)\n const tempPath = PATH.join(tempDir, name)\n await writeDurableFile(tempPath, `${JSON.stringify(wake)}\\n`)\n try {\n await link(tempPath, PATH.join(pendingDir, name))\n await syncDirectory(pendingDir)\n } finally {\n await unlinkIfMissing(tempPath)\n }\n },\n\n async claim(): Promise<LeasedWake | undefined> {\n await ensureDirs()\n const names = (await readdir(pendingDir)).toSorted()\n for (const name of names) {\n const inflightPath = PATH.join(inflightDir, name)\n const pendingPath = PATH.join(pendingDir, name)\n try {\n // The link is the claim: a second claimer gets EEXIST and moves on.\n await link(pendingPath, inflightPath)\n } catch (error) {\n if (isAlreadyExists(error) || isNotFound(error)) continue\n throw error\n }\n await unlinkIfMissing(pendingPath)\n\n const wake = await readJsonFile<AdmittedWake>(inflightPath)\n if (wake === undefined) {\n await unlinkIfMissing(inflightPath)\n continue\n }\n\n return {\n wake,\n async ack(): Promise<void> {\n await unlinkIfMissing(inflightPath)\n },\n async release(): Promise<void> {\n await returnToPending(name)\n },\n }\n }\n return undefined\n },\n\n async pendingCount(): Promise<number> {\n await ensureDirs()\n return (await readdir(pendingDir)).length\n },\n\n async recoverInflight(): Promise<number> {\n await ensureDirs()\n const names = await readdir(inflightDir)\n let recovered = 0\n for (const name of names) {\n await returnToPending(name)\n recovered += 1\n }\n return recovered\n },\n }\n}\n\n/** Reads and parses a JSON file, treating an absent or unreadable file as empty. */\nexport async function readJsonFile<T>(path: string): Promise<T | undefined> {\n try {\n const handle = await open(path, 'r')\n try {\n const raw = await handle.readFile('utf8')\n return JSON.parse(raw) as T\n } finally {\n await handle.close()\n }\n } catch {\n return undefined\n }\n}\n\n/** Sorts approximately FIFO; the random suffix keeps concurrent writers from colliding. */\nfunction entryName(wake: AdmittedWake, sequence: number): string {\n const stamp = String(Date.now()).padStart(15, '0')\n const ordinal = String(sequence).padStart(6, '0')\n return `${stamp}-${ordinal}-${randomBytes(6).toString('hex')}-${wake.wakeId}.json`\n}\n\nasync function unlinkIfMissing(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) {\n if (!isNotFound(error)) throw error\n }\n}\n\nfunction isNotFound(error: unknown): boolean {\n return errorCode(error) === 'ENOENT'\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return errorCode(error) === 'EEXIST'\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 { 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 { createHash, randomBytes } from 'node:crypto'\nimport {\n link, mkdir, open, readdir, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type {\n AdmittedWake,\n AtomicWakeInbox,\n WakeAdmissionAttempt,\n WakeAdmissionReceipt,\n WakeAttemptResolution,\n WakeCommitResult,\n} from '@xyo-network/event-kit-protocol'\n\nimport type { FilesystemWakeQueue } from './filesystemWakeQueue.ts'\nimport { syncDirectory, writeDurableFile } from './filesystemWakeQueue.ts'\n\nexport interface FilesystemWakeInboxOptions {\n /** Directory owning the `tokens/` and `wakes/` record sets. */\n readonly path: string\n /** Durable sink receiving each newly admitted wake inside the commit. */\n readonly queue: FilesystemWakeQueue\n}\n\nexport interface FilesystemWakeInbox extends AtomicWakeInbox {\n /** Deletes token records past `retainJwtUntil`. Returns how many were removed. */\n pruneExpiredTokens: (nowSeconds: number) => Promise<number>\n}\n\ninterface WakeRecord {\n readonly audience: string\n readonly eventHash: string\n readonly publisher: string\n readonly receipt: WakeAdmissionReceipt\n readonly wakeId: string\n}\n\ninterface TokenRecord extends WakeRecord {\n readonly jwtId: string\n readonly retainJwtUntil: number\n}\n\n/** The already-recorded outcomes, common to both the resolve and commit unions. */\ntype RecordedResolution = Exclude<WakeAttemptResolution, { readonly kind: 'new' }>\n\n/**\n * Crash-safe single-node `AtomicWakeInbox`.\n *\n * Commit order is the correctness property: the wake reaches the durable queue\n * **before** either identity record is written. A crash in the gap redelivers\n * the wake, which the idempotent consumer absorbs; the reverse order could\n * claim `wakeId` for a wake that was never queued and wedge it permanently.\n * D-002 \u00A76 forbids burning a valid `jti` ahead of a fallible enqueue.\n *\n * Identity records are published by `link`, which fails rather than overwrites,\n * so a concurrent writer loses the race and re-reads the winner's receipt.\n *\n * This survives process death, not host loss, and does not coordinate across\n * machines. A multi-node deployment needs a transactional store or a cloud\n * queue with native deduplication.\n */\nexport function createFilesystemWakeInbox(\n options: FilesystemWakeInboxOptions,\n): FilesystemWakeInbox {\n const root = PATH.resolve(options.path)\n const tokensDir = PATH.join(root, 'tokens')\n const wakesDir = PATH.join(root, 'wakes')\n const tempDir = PATH.join(root, 'tmp')\n let tail: Promise<unknown> = Promise.resolve()\n\n /**\n * Serializes this process's critical section. Cross-process safety comes from\n * the exclusive record creates; this keeps one process from racing itself.\n */\n function exclusive<T>(work: () => Promise<T>): Promise<T> {\n const previous = tail\n const run = (async (): Promise<T> => {\n try {\n await previous\n } catch {\n // Prior section still releases the lock; this section must run either way.\n }\n return await work()\n })()\n tail = Promise.allSettled([run])\n return run\n }\n\n async function ensureDirs(): Promise<void> {\n await mkdir(tokensDir, { recursive: true })\n await mkdir(wakesDir, { recursive: true })\n await mkdir(tempDir, { recursive: true })\n }\n\n function tokenPath(attempt: WakeAdmissionAttempt): string {\n return PATH.join(tokensDir, `${digest([attempt.audience, attempt.publisher, attempt.jwtId])}.json`)\n }\n\n function wakePath(attempt: WakeAdmissionAttempt): string {\n return PATH.join(wakesDir, `${digest([attempt.audience, attempt.publisher, attempt.wakeId])}.json`)\n }\n\n /** Binds `attempt`'s token to an already-committed wake receipt. */\n async function bindToken(attempt: WakeAdmissionAttempt, wake: WakeRecord): Promise<void> {\n const record: TokenRecord = {\n ...wake,\n jwtId: attempt.jwtId,\n retainJwtUntil: attempt.retainJwtUntil,\n }\n await writeRecordExclusive(tempDir, tokenPath(attempt), record)\n }\n\n async function matchRecorded(attempt: WakeAdmissionAttempt): Promise<RecordedResolution | undefined> {\n const token = await readRecord<TokenRecord>(tokenPath(attempt))\n if (token !== undefined) {\n return token.eventHash === attempt.eventHash && token.wakeId === attempt.wakeId\n ? { kind: 'duplicate', receipt: token.receipt }\n : { kind: 'jwt-id-collision' }\n }\n\n const wake = await readRecord<WakeRecord>(wakePath(attempt))\n if (wake === undefined) return undefined\n if (wake.eventHash !== attempt.eventHash) return { kind: 'wake-id-collision' }\n await bindToken(attempt, wake)\n return { kind: 'duplicate', receipt: wake.receipt }\n }\n\n return {\n resolveAttempt: async (attempt: WakeAdmissionAttempt): Promise<WakeAttemptResolution> => await exclusive(async () => {\n await ensureDirs()\n return await matchRecorded(attempt) ?? { kind: 'new' }\n }),\n\n commitAuthorized: async ({ attempt, wake }: {\n readonly attempt: WakeAdmissionAttempt\n readonly wake: AdmittedWake\n }): Promise<WakeCommitResult> => await exclusive(async () => {\n await ensureDirs()\n const recorded = await matchRecorded(attempt)\n if (recorded !== undefined) return recorded\n\n const receipt: WakeAdmissionReceipt = Object.freeze({\n audience: attempt.audience,\n eventHash: attempt.eventHash,\n id: digest([attempt.audience, attempt.publisher, attempt.wakeId]),\n publisher: attempt.publisher,\n wakeId: attempt.wakeId,\n })\n const record: WakeRecord = {\n audience: attempt.audience,\n eventHash: attempt.eventHash,\n publisher: attempt.publisher,\n receipt,\n wakeId: attempt.wakeId,\n }\n\n // Durable queue first: a crash after this point redelivers, which the\n // consumer deduplicates. Claiming the identity first could wedge the wake.\n await options.queue.append(wake)\n\n const claimed = await writeRecordExclusive(tempDir, wakePath(attempt), record)\n if (!claimed) {\n // Another writer committed this wakeId between our check and our write.\n const winner = await readRecord<WakeRecord>(wakePath(attempt))\n if (winner === undefined) throw new Error('wake record vanished during commit')\n if (winner.eventHash !== attempt.eventHash) return { kind: 'wake-id-collision' }\n await bindToken(attempt, winner)\n return { kind: 'duplicate', receipt: winner.receipt }\n }\n\n await bindToken(attempt, record)\n return { kind: 'enqueued', receipt }\n }),\n\n async pruneExpiredTokens(nowSeconds: number): Promise<number> {\n await ensureDirs()\n let removed = 0\n for (const name of await readdir(tokensDir)) {\n const path = PATH.join(tokensDir, name)\n const token = await readRecord<TokenRecord>(path)\n if (token === undefined || token.retainJwtUntil > nowSeconds) continue\n await unlinkIfMissing(path)\n removed += 1\n }\n return removed\n },\n }\n}\n\n/**\n * Atomically publishes a record. Returns `false` when another writer already\n * claimed the path, which is how a cross-process race is detected.\n *\n * The content is written and fsynced to a temp file first, then `link`ed into\n * place: `link` fails when the destination exists (unlike `rename`, which would\n * overwrite the winner) and publishes only complete bytes, so a concurrent\n * reader can never observe a half-written record.\n */\nasync function writeRecordExclusive(tempDir: string, path: string, record: unknown): Promise<boolean> {\n const tempPath = PATH.join(tempDir, `${PATH.basename(path)}.${process.pid}.${randomSuffix()}`)\n await writeDurableFile(tempPath, `${JSON.stringify(record)}\\n`)\n try {\n await link(tempPath, path)\n await syncDirectory(PATH.dirname(path))\n return true\n } catch (error) {\n if (isAlreadyExists(error)) return false\n throw error\n } finally {\n await unlinkIfMissing(tempPath)\n }\n}\n\nasync function readRecord<T>(path: string): Promise<T | undefined> {\n try {\n const handle = await open(path, 'r')\n try {\n const raw = await handle.readFile('utf8')\n return JSON.parse(raw) as T\n } finally {\n await handle.close()\n }\n } catch (error) {\n if (isNotFound(error)) return undefined\n throw error\n }\n}\n\nfunction digest(parts: readonly string[]): string {\n return createHash('sha256').update(JSON.stringify(parts)).digest('hex')\n}\n\nfunction randomSuffix(): string {\n return randomBytes(8).toString('hex')\n}\n\nasync function unlinkIfMissing(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) {\n if (!isNotFound(error)) throw error\n }\n}\n\nfunction isNotFound(error: unknown): boolean {\n return errorCode(error) === 'ENOENT'\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return errorCode(error) === 'EEXIST'\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 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 { 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 try {\n const handle = await open(path, 'r')\n try {\n return JSON.parse(await handle.readFile('utf8'), reviveJson) as unknown\n } finally {\n await handle.close()\n }\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return undefined\n throw error\n }\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 await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n try {\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 await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n try {\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 { 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 ChainId,\n EncryptedWakeSubscription,\n EndpointChallenge,\n EndpointChallengeResponse,\n HandshakeId,\n Hash,\n NormalizedAddress,\n PublisherEncryptionKey,\n PublisherService,\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 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 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 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.operationId,\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 ...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 ...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 /** Subscriber-owned secret already provisioned at the endpoint; it is never returned or published. */\n readonly challengeSecret: Base64Url32Bytes\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 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 ...plaintextInput, source, fromPosition: input.fromPosition, maxPositionsPerWake,\n })\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 { decryptWakeSubscription, sourceWakeFilterHash } from '@xyo-network/event-kit-protocol'\nimport type { EndpointChallengeResponse } from '@xyo-network/event-kit-schemas'\nimport { EndpointChallengeResponseZod } from '@xyo-network/event-kit-schemas'\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 client: PublisherHandshakeClient\n readonly keys: PublisherEncryptionKeyCustody\n readonly maxSubscriptions?: number\n readonly nowSeconds?: () => number\n readonly publisher: 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 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').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\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 return {\n async discover(signal) {\n const view = await activeView(signal)\n const key = view.hasCurrentAdvertisement ? view.key : undefined\n const loaded = key === undefined\n ? undefined\n : await options.keys.getPrivateKey({\n encryptionKey: key.objectHash, keyId: key.body.keyId, publisher: options.publisher,\n })\n status = {\n ...status, keyLoaded: loaded !== undefined, activeKeyIds: key === undefined ? [] : [key.body.keyId],\n }\n const subscriptions: PublisherRuntimeSubscription[] = []\n const active = view.subscriptions.filter(item => item.state === 'active')\n if (active.length > (options.maxSubscriptions ?? 64))\n throw new Error('Publisher active subscription limit exceeded')\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)\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 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))\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 { randomBytes } from 'node:crypto'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { PeriodicActorParams, PeriodicPassContext } from '@ariestools/actor'\nimport { createMemoryLocator, PeriodicActor } from '@ariestools/actor'\nimport { creatable } from '@ariestools/sdk'\nimport type { WakeEnvelope, WakeSource } from '@xyo-network/event-kit-schemas'\nimport { WakeEnvelopeSchema, WakeEnvelopeZod } 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 { 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 controller: string\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 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\ninterface DeliveryState {\n readonly cursor: number\n readonly delivered: number\n readonly failures: number\n readonly lastError?: string\n readonly nextAttemptMs: number\n readonly pending?: WakeEnvelope\n readonly state: 'active' | 'blocked' | 'cancelled'\n readonly subscription: PublisherRuntimeSubscription\n}\nfunction 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 || !['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 (pending.fromPosition !== record.cursor + 1 || 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}\nfunction 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 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 interface PersistentEventPublisherOptions {\n readonly account: AccountInstance\n readonly concurrency?: number\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 readonly sources: readonly PublisherSourceReader[]\n readonly state: SqlitePublisherState\n readonly transport: PublisherHttpsTransport\n}\nexport interface PersistentEventPublisherStatus {\n readonly activeSubscriptions: number\n readonly clockHealthy: boolean\n readonly degraded: boolean\n readonly delivered: number\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 cursor: number\n readonly failures: number\n readonly id: string\n readonly pending: boolean\n readonly state: string\n }[]\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})\nclass 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}\nexport async function createPersistentEventPublisherRuntime(options: PersistentEventPublisherOptions): Promise<PersistentEventPublisher> {\n const timing = TimingZod.parse(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 abort = new AbortController()\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 state = options.state\n const timed = <T>(promise: Promise<T>, signal: AbortSignal) => boundedPublisherOperation(promise, signal, timing.requestTimeoutMs)\n function loadDelivery(subscription: PublisherRuntimeSubscription, now: number): DeliveryState {\n const key = subscription.subscriptionHash\n let record = state.get<DeliveryState>('deliveries', 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('deliveries', 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 (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('deliveries', 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('deliveries', record.subscription.subscriptionHash, {\n ...record, pending: undefined, state: 'cancelled',\n })\n return false\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 = state.get<{ count: number }>('delivery-attempts', pending.wakeId)?.count ?? 0\n 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 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 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('deliveries', 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 (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 // 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('deliveries', subscription.subscriptionHash, {\n ...record,\n failures: record.failures + 1,\n state: error instanceof DeliveryResponseError && !error.retryable ? 'blocked' : 'active',\n nextAttemptMs: now * 1000 + Math.min(3_600_000, error instanceof DeliveryResponseError && error.retryAfterMs !== undefined\n ? error.retryAfterMs\n : Math.min(300_000, 1000 * (2 ** Math.min(record.failures, 8)))),\n lastError: 'delivery-failed',\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>('deliveries').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('deliveries', 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>('deliveries').map(item => item.value)\n return {\n running,\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').map(item => ({ id: item.key, ...item.value })),\n subscriptions: state.entries<DeliveryState>('deliveries').map(item => ({\n id: item.key, cursor: item.value.cursor, state: item.value.state, pending: item.value.pending !== undefined, failures: item.value.failures,\n })),\n }\n },\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): {\n readonly challenges: PublisherEndpointChallengeStore\n readonly intents: HandshakeMutationIntentStore\n readonly journal: FinalizedStatementPublicationJournal\n readonly keys: PublisherEncryptionKeyCustody\n readonly replay: EventKitReplayCheckpointStore\n} {\n const replay: EventKitReplayCheckpointStore = {\n load: async () => state.get('replay', 'checkpoint'),\n async save(checkpoint) { state.set('replay', 'checkpoint', 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 { mkdir } from 'node:fs/promises'\nimport PATH from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nimport type {\n AdmittedWake,\n LeasedWake,\n WakeQueue,\n} from '@xyo-network/event-kit-protocol'\n\nexport interface SqliteWakeQueueOptions {\n /** Database file path, or `:memory:` for a throwaway store. */\n readonly path: string\n}\n\nexport interface SqliteWakeQueue extends WakeQueue {\n /** Releases the underlying handle. */\n close: () => void\n}\n\ninterface QueueRow {\n readonly body: string\n readonly id: number\n}\n\n/**\n * SQLite-backed `WakeQueue`.\n *\n * Every state change is a single statement under WAL, so a claim cannot be\n * observed half-applied and two callers cannot lease one row: the claim is an\n * `UPDATE \u2026 WHERE state = 'pending'` whose affected-row count decides the\n * winner. That is the transactional form of the lease the filesystem provider\n * approximates with `link`.\n *\n * WAL also permits concurrent readers with one writer, so several processes on\n * one host can share the file. It does not coordinate across hosts.\n *\n * Uses Node's built-in `node:sqlite`, which still emits an ExperimentalWarning.\n */\nexport async function createSqliteWakeQueue(\n options: SqliteWakeQueueOptions,\n): Promise<SqliteWakeQueue> {\n const inMemory = options.path === ':memory:'\n const file = inMemory ? options.path : PATH.resolve(options.path)\n if (!inMemory) await mkdir(PATH.dirname(file), { recursive: true })\n\n const database = new DatabaseSync(file)\n database.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = FULL;\n CREATE TABLE IF NOT EXISTS wake_queue (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n body TEXT NOT NULL,\n state TEXT NOT NULL DEFAULT 'pending'\n );\n CREATE INDEX IF NOT EXISTS wake_queue_state ON wake_queue (state, id);\n `)\n\n const insert = database.prepare('INSERT INTO wake_queue (body) VALUES (?)')\n const nextPending = database.prepare(\n 'SELECT id, body FROM wake_queue WHERE state = \\'pending\\' ORDER BY id LIMIT 1',\n )\n // The affected-row count is the lease: a loser updates zero rows and retries.\n const lease = database.prepare(\n 'UPDATE wake_queue SET state = \\'inflight\\' WHERE id = ? AND state = \\'pending\\'',\n )\n const remove = database.prepare('DELETE FROM wake_queue WHERE id = ?')\n const restore = database.prepare(\n 'UPDATE wake_queue SET state = \\'pending\\' WHERE id = ? AND state = \\'inflight\\'',\n )\n const countPending = database.prepare(\n 'SELECT COUNT(*) AS total FROM wake_queue WHERE state = \\'pending\\'',\n )\n const recoverAll = database.prepare(\n 'UPDATE wake_queue SET state = \\'pending\\' WHERE state = \\'inflight\\'',\n )\n\n return {\n async append(wake: AdmittedWake): Promise<void> {\n insert.run(JSON.stringify(wake))\n },\n\n async claim(): Promise<LeasedWake | undefined> {\n for (;;) {\n const row = nextPending.get() as QueueRow | undefined\n if (row === undefined) return undefined\n if (lease.run(row.id).changes !== 1) continue // another claimer won it\n\n return {\n wake: JSON.parse(row.body) as AdmittedWake,\n async ack(): Promise<void> {\n remove.run(row.id)\n },\n async release(): Promise<void> {\n restore.run(row.id)\n },\n }\n }\n },\n\n close(): void {\n database.close()\n },\n\n pendingCount: async (): Promise<number> => Number((countPending.get() as { total: number }).total),\n\n recoverInflight: async (): Promise<number> => Number(recoverAll.run().changes),\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EAAO;AAAA,EAAU;AAAA,OACZ;AACP,OAAO,UAAU;AAgBV,SAAS,4BACd,SACsB;AACtB,QAAM,WAAW,KAAK,QAAQ,QAAQ,IAAI;AAC1C,SAAO;AAAA,IACL,MAAM,OAAoC;AACxC,UAAI;AACF,cAAM,MAAM,MAAM,SAAS,UAAU,MAAM;AAC3C,cAAM,SAAS,KAAK,MAAM,GAAG;AAC7B,eAAO,OAAO,OAAO,uBAAuB,YAAY,CAAC,OAAO,SAAS,OAAO,kBAAkB,IAAI,SAAY,OAAO;AAAA,MAC3H,SAAS,OAAO;AACd,YAAI,WAAW,KAAK,EAA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AAA,IAEA,MAAM,QAAyC;AAC7C,iBAAS;AACP,cAAM,MAAM,YAAY,IAAI;AAC5B,YAAI,QAAQ,OAAW,QAAO;AAC9B,YAAI,MAAM,IAAI,IAAI,EAAE,EAAE,YAAY,EAAG;AAErC,eAAO;AAAA,UACL,MAAM,KAAK,MAAM,IAAI,IAAI;AAAA,UACzB,MAAM,MAAqB;AACzB,mBAAO,IAAI,IAAI,EAAE;AAAA,UACnB;AAAA,UACA,MAAM,UAAyB;AAC7B,oBAAQ,IAAI,IAAI,EAAE;AAAA,UACpB;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,IAEA,QAAc;AACZ,eAAS,MAAM;AAAA,IACjB;AAAA,IAEA,cAAc,YAA6B,OAAQ,aAAa,IAAI,EAAwB,KAAK;AAAA,IAEjG,iBAAiB,YAA6B,OAAO,WAAW,IAAI,EAAE,OAAO;AAAA,EAC/E;AACF;",
6
- "names": ["randomBytes", "mkdir", "unlink", "PATH", "open", "PATH", "mkdir", "PATH", "PATH", "isNotFound", "open", "errorCode", "PATH", "unlink", "isNotFound", "mkdir", "randomBytes", "randomBytes", "link", "mkdir", "open", "readdir", "unlink", "PATH", "PATH", "mkdir", "readdir", "unlinkIfMissing", "link", "isAlreadyExists", "open", "isNotFound", "randomBytes", "unlink", "errorCode", "PATH", "randomBytes", "link", "open", "rename", "unlink", "PATH", "open", "errorCode", "PATH", "rename", "unlinkIfMissing", "link", "randomBytes", "unlink", "PATH", "createHash", "PATH", "createHash", "PATH", "existing", "PATH", "digest", "lookup", "PATH", "lookup", "stat", "PATH", "Base64Url32BytesZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "PATH", "lookup", "HashZod", "HandshakeIdZod", "NormalizedAddressZod", "readRecord", "stat", "Base64Url32BytesZod", "PATH", "EndpointChallengeZod", "HashZod", "PATH", "HashZod", "EndpointChallengeZod", "handshakeObjectHash", "ChainIdZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "NormalizedAddressZod", "ChainIdZod", "HashZod", "HandshakeIdZod", "candidate", "handshakeObjectHash", "lookup", "view", "Buffer", "Buffer", "request", "EndpointChallengeResponseZod", "response", "EndpointChallengeResponseZod", "Buffer", "z", "createHash", "canonicalJson", "createHash", "canonicalJson", "z", "Buffer", "randomBytes", "isDeepStrictEqual", "WakeEnvelopeZod", "z", "randomBytes", "NormalizedAddressZod", "PayloadBuilder", "isDeepStrictEqual", "WakeEnvelopeZod", "randomBytes", "z", "isDeepStrictEqual", "endpointChallengeHash", "Base64Url32BytesZod", "EndpointChallengeZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "z", "z", "HashZod", "HandshakeIdZod", "Base64Url32BytesZod", "NormalizedAddressZod", "requireTime", "isDeepStrictEqual", "lookup", "EndpointChallengeZod", "endpointChallengeHash", "randomBytes", "mkdir", "open", "PATH", "PATH", "mkdir", "open", "metadata", "DatabaseSync", "randomBytes", "mkdir", "PATH"]
3
+ "sources": ["../../src/filesystemCursorStore.ts", "../../src/filesystemPublisherOutbox.ts", "../../src/filesystemWakeQueue.ts", "../../src/filesystemDurability.ts", "../../src/filesystemWakeInbox.ts", "../../src/filesystemEventKitReplayCheckpointStore.ts", "../../src/filesystemJson.ts", "../../src/filesystemFinalizedStatementPublicationJournal.ts", "../../src/filesystemHandshakeMutationIntentStore.ts", "../../src/handshakeMutationIntent.ts", "../../src/filesystemPublisherEncryptionKeyStore.ts", "../../src/filesystemPublisherEndpointChallengeStore.ts", "../../src/handshakeClients.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/sqliteWakeQueue.ts"],
4
+ "sourcesContent": ["import {\n mkdir, readFile, writeFile,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type { PublisherCursorStore } from '@xyo-network/event-kit-actor'\n\nexport interface FilesystemCursorStoreOptions {\n /** Absolute or relative path to the cursor JSON file. */\n readonly path: string\n}\n\ninterface CursorFile {\n readonly lastProcessedBlock: number\n}\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 return {\n async load(): Promise<number | undefined> {\n try {\n const raw = await readFile(filePath, 'utf8')\n const parsed = JSON.parse(raw) as CursorFile\n return typeof parsed.lastProcessedBlock !== 'number' || !Number.isFinite(parsed.lastProcessedBlock) ? undefined : parsed.lastProcessedBlock\n } catch (error) {\n if (isNotFound(error)) return undefined\n throw error\n }\n },\n async save(lastProcessedBlock: number): Promise<void> {\n await mkdir(PATH.dirname(filePath), { recursive: true })\n const body: CursorFile = { lastProcessedBlock }\n await writeFile(filePath, `${JSON.stringify(body)}\\n`, 'utf8')\n },\n }\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", "import { randomBytes } from 'node:crypto'\nimport {\n mkdir, rename, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type { PendingWake, PublisherOutbox } from '@xyo-network/event-kit-actor'\n\nimport { readJsonFile, writeDurableFile } from './filesystemWakeQueue.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\n return {\n async clear(): Promise<void> {\n try {\n await unlink(filePath)\n } catch (error) {\n if (!isNotFound(error)) throw error\n }\n },\n\n load: async (): Promise<PendingWake | undefined> => await readJsonFile<PendingWake>(filePath),\n\n async save(pending: PendingWake): Promise<void> {\n await mkdir(PATH.dirname(filePath), { recursive: true })\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 await writeDurableFile(tempPath, `${JSON.stringify(pending)}\\n`)\n try {\n await rename(tempPath, filePath)\n } catch (error) {\n try {\n await unlink(tempPath)\n } catch {\n // A leftover temp file is harmless; the rename failure is what matters.\n }\n throw error\n }\n },\n }\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", "import { randomBytes } from 'node:crypto'\nimport {\n link, open, readdir, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type {\n AdmittedWake,\n LeasedWake,\n WakeQueue,\n} from '@xyo-network/event-kit-protocol'\n\nimport {\n ensureDurableDirectory,\n syncDirectory,\n writeDurableFile,\n} from './filesystemDurability.ts'\n\nexport {\n ensureDurableDirectory,\n syncDirectory,\n writeDurableFile,\n}\n\nexport interface FilesystemWakeQueueOptions {\n /** Directory owning the `pending/` and `inflight/` entry sets. */\n readonly path: string\n}\n\nexport type FilesystemWakeQueue = WakeQueue\n\n/**\n * Directory-backed at-least-once wake queue.\n *\n * Entries are published by `link`, never `rename`. `rename` is unsound as a\n * claim: when two callers race the same source, both can observe success once\n * the paths resolve to one inode, and the entry is then handed out twice. `link`\n * fails with `EEXIST`, so exactly one claimer wins.\n *\n * A claim is `link(pending -> inflight)` followed by `unlink(pending)`. A crash\n * between the two leaves the entry in both sets as one inode; recovery drops the\n * inflight copy and the entry stays pending. A consumer that dies mid-handler\n * leaves its entry inflight for `recoverInflight` rather than dropping it.\n *\n * Ordering is approximate FIFO by entry name. Single-node only: this survives\n * process death, not host loss, and does not coordinate across machines.\n */\nexport function createFilesystemWakeQueue(\n options: FilesystemWakeQueueOptions,\n): FilesystemWakeQueue {\n const root = PATH.resolve(options.path)\n const pendingDir = PATH.join(root, 'pending')\n const inflightDir = PATH.join(root, 'inflight')\n const tempDir = PATH.join(root, 'tmp')\n let sequence = 0\n\n async function ensureDirs(): Promise<void> {\n await ensureDurableDirectory(pendingDir)\n await ensureDurableDirectory(inflightDir)\n await ensureDurableDirectory(tempDir)\n }\n\n /** Moves one entry back to `pending/`, tolerating an existing half-claimed copy. */\n async function returnToPending(name: string): Promise<void> {\n try {\n await link(PATH.join(inflightDir, name), PATH.join(pendingDir, name))\n } catch (error) {\n // EEXIST means a crash left both links to the same entry; the pending copy wins.\n if (!isAlreadyExists(error) && !isNotFound(error)) throw error\n }\n await unlinkIfMissing(PATH.join(inflightDir, name))\n }\n\n return {\n async append(wake: AdmittedWake): Promise<void> {\n await ensureDirs()\n const name = entryName(wake, sequence += 1)\n const tempPath = PATH.join(tempDir, name)\n await writeDurableFile(tempPath, `${JSON.stringify(wake)}\\n`)\n try {\n await link(tempPath, PATH.join(pendingDir, name))\n await syncDirectory(pendingDir)\n } finally {\n await unlinkIfMissing(tempPath)\n }\n },\n\n async claim(): Promise<LeasedWake | undefined> {\n await ensureDirs()\n const names = (await readdir(pendingDir)).toSorted()\n for (const name of names) {\n const inflightPath = PATH.join(inflightDir, name)\n const pendingPath = PATH.join(pendingDir, name)\n try {\n // The link is the claim: a second claimer gets EEXIST and moves on.\n await link(pendingPath, inflightPath)\n } catch (error) {\n if (isAlreadyExists(error) || isNotFound(error)) continue\n throw error\n }\n await unlinkIfMissing(pendingPath)\n\n const wake = await readJsonFile<AdmittedWake>(inflightPath)\n if (wake === undefined) {\n await unlinkIfMissing(inflightPath)\n continue\n }\n\n return {\n wake,\n async ack(): Promise<void> {\n await unlinkIfMissing(inflightPath)\n },\n async release(): Promise<void> {\n await returnToPending(name)\n },\n }\n }\n return undefined\n },\n\n async pendingCount(): Promise<number> {\n await ensureDirs()\n return (await readdir(pendingDir)).length\n },\n\n async recoverInflight(): Promise<number> {\n await ensureDirs()\n const names = await readdir(inflightDir)\n let recovered = 0\n for (const name of names) {\n await returnToPending(name)\n recovered += 1\n }\n return recovered\n },\n }\n}\n\n/** Reads and parses a JSON file, treating an absent or unreadable file as empty. */\nexport async function readJsonFile<T>(path: string): Promise<T | undefined> {\n try {\n const handle = await open(path, 'r')\n try {\n const raw = await handle.readFile('utf8')\n return JSON.parse(raw) as T\n } finally {\n await handle.close()\n }\n } catch {\n return undefined\n }\n}\n\n/** Sorts approximately FIFO; the random suffix keeps concurrent writers from colliding. */\nfunction entryName(wake: AdmittedWake, sequence: number): string {\n const stamp = String(Date.now()).padStart(15, '0')\n const ordinal = String(sequence).padStart(6, '0')\n return `${stamp}-${ordinal}-${randomBytes(6).toString('hex')}-${wake.wakeId}.json`\n}\n\nasync function unlinkIfMissing(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) {\n if (!isNotFound(error)) throw error\n }\n}\n\nfunction isNotFound(error: unknown): boolean {\n return errorCode(error) === 'ENOENT'\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return errorCode(error) === 'EEXIST'\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 { 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 { createHash, randomBytes } from 'node:crypto'\nimport {\n link, mkdir, open, readdir, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport type {\n AdmittedWake,\n AtomicWakeInbox,\n WakeAdmissionAttempt,\n WakeAdmissionReceipt,\n WakeAttemptResolution,\n WakeCommitResult,\n} from '@xyo-network/event-kit-protocol'\n\nimport type { FilesystemWakeQueue } from './filesystemWakeQueue.ts'\nimport { syncDirectory, writeDurableFile } from './filesystemWakeQueue.ts'\n\nexport interface FilesystemWakeInboxOptions {\n /** Directory owning the `tokens/` and `wakes/` record sets. */\n readonly path: string\n /** Durable sink receiving each newly admitted wake inside the commit. */\n readonly queue: FilesystemWakeQueue\n}\n\nexport interface FilesystemWakeInbox extends AtomicWakeInbox {\n /** Deletes token records past `retainJwtUntil`. Returns how many were removed. */\n pruneExpiredTokens: (nowSeconds: number) => Promise<number>\n}\n\ninterface WakeRecord {\n readonly audience: string\n readonly eventHash: string\n readonly publisher: string\n readonly receipt: WakeAdmissionReceipt\n readonly wakeId: string\n}\n\ninterface TokenRecord extends WakeRecord {\n readonly jwtId: string\n readonly retainJwtUntil: number\n}\n\n/** The already-recorded outcomes, common to both the resolve and commit unions. */\ntype RecordedResolution = Exclude<WakeAttemptResolution, { readonly kind: 'new' }>\n\n/**\n * Crash-safe single-node `AtomicWakeInbox`.\n *\n * Commit order is the correctness property: the wake reaches the durable queue\n * **before** either identity record is written. A crash in the gap redelivers\n * the wake, which the idempotent consumer absorbs; the reverse order could\n * claim `wakeId` for a wake that was never queued and wedge it permanently.\n * D-002 \u00A76 forbids burning a valid `jti` ahead of a fallible enqueue.\n *\n * Identity records are published by `link`, which fails rather than overwrites,\n * so a concurrent writer loses the race and re-reads the winner's receipt.\n *\n * This survives process death, not host loss, and does not coordinate across\n * machines. A multi-node deployment needs a transactional store or a cloud\n * queue with native deduplication.\n */\nexport function createFilesystemWakeInbox(\n options: FilesystemWakeInboxOptions,\n): FilesystemWakeInbox {\n const root = PATH.resolve(options.path)\n const tokensDir = PATH.join(root, 'tokens')\n const wakesDir = PATH.join(root, 'wakes')\n const tempDir = PATH.join(root, 'tmp')\n let tail: Promise<unknown> = Promise.resolve()\n\n /**\n * Serializes this process's critical section. Cross-process safety comes from\n * the exclusive record creates; this keeps one process from racing itself.\n */\n function exclusive<T>(work: () => Promise<T>): Promise<T> {\n const previous = tail\n const run = (async (): Promise<T> => {\n try {\n await previous\n } catch {\n // Prior section still releases the lock; this section must run either way.\n }\n return await work()\n })()\n tail = Promise.allSettled([run])\n return run\n }\n\n async function ensureDirs(): Promise<void> {\n await mkdir(tokensDir, { recursive: true })\n await mkdir(wakesDir, { recursive: true })\n await mkdir(tempDir, { recursive: true })\n }\n\n function tokenPath(attempt: WakeAdmissionAttempt): string {\n return PATH.join(tokensDir, `${digest([attempt.audience, attempt.publisher, attempt.jwtId])}.json`)\n }\n\n function wakePath(attempt: WakeAdmissionAttempt): string {\n return PATH.join(wakesDir, `${digest([attempt.audience, attempt.publisher, attempt.wakeId])}.json`)\n }\n\n /** Binds `attempt`'s token to an already-committed wake receipt. */\n async function bindToken(attempt: WakeAdmissionAttempt, wake: WakeRecord): Promise<void> {\n const record: TokenRecord = {\n ...wake,\n jwtId: attempt.jwtId,\n retainJwtUntil: attempt.retainJwtUntil,\n }\n await writeRecordExclusive(tempDir, tokenPath(attempt), record)\n }\n\n async function matchRecorded(attempt: WakeAdmissionAttempt): Promise<RecordedResolution | undefined> {\n const token = await readRecord<TokenRecord>(tokenPath(attempt))\n if (token !== undefined) {\n return token.eventHash === attempt.eventHash && token.wakeId === attempt.wakeId\n ? { kind: 'duplicate', receipt: token.receipt }\n : { kind: 'jwt-id-collision' }\n }\n\n const wake = await readRecord<WakeRecord>(wakePath(attempt))\n if (wake === undefined) return undefined\n if (wake.eventHash !== attempt.eventHash) return { kind: 'wake-id-collision' }\n await bindToken(attempt, wake)\n return { kind: 'duplicate', receipt: wake.receipt }\n }\n\n return {\n resolveAttempt: async (attempt: WakeAdmissionAttempt): Promise<WakeAttemptResolution> => await exclusive(async () => {\n await ensureDirs()\n return await matchRecorded(attempt) ?? { kind: 'new' }\n }),\n\n commitAuthorized: async ({ attempt, wake }: {\n readonly attempt: WakeAdmissionAttempt\n readonly wake: AdmittedWake\n }): Promise<WakeCommitResult> => await exclusive(async () => {\n await ensureDirs()\n const recorded = await matchRecorded(attempt)\n if (recorded !== undefined) return recorded\n\n const receipt: WakeAdmissionReceipt = Object.freeze({\n audience: attempt.audience,\n eventHash: attempt.eventHash,\n id: digest([attempt.audience, attempt.publisher, attempt.wakeId]),\n publisher: attempt.publisher,\n wakeId: attempt.wakeId,\n })\n const record: WakeRecord = {\n audience: attempt.audience,\n eventHash: attempt.eventHash,\n publisher: attempt.publisher,\n receipt,\n wakeId: attempt.wakeId,\n }\n\n // Durable queue first: a crash after this point redelivers, which the\n // consumer deduplicates. Claiming the identity first could wedge the wake.\n await options.queue.append(wake)\n\n const claimed = await writeRecordExclusive(tempDir, wakePath(attempt), record)\n if (!claimed) {\n // Another writer committed this wakeId between our check and our write.\n const winner = await readRecord<WakeRecord>(wakePath(attempt))\n if (winner === undefined) throw new Error('wake record vanished during commit')\n if (winner.eventHash !== attempt.eventHash) return { kind: 'wake-id-collision' }\n await bindToken(attempt, winner)\n return { kind: 'duplicate', receipt: winner.receipt }\n }\n\n await bindToken(attempt, record)\n return { kind: 'enqueued', receipt }\n }),\n\n async pruneExpiredTokens(nowSeconds: number): Promise<number> {\n await ensureDirs()\n let removed = 0\n for (const name of await readdir(tokensDir)) {\n const path = PATH.join(tokensDir, name)\n const token = await readRecord<TokenRecord>(path)\n if (token === undefined || token.retainJwtUntil > nowSeconds) continue\n await unlinkIfMissing(path)\n removed += 1\n }\n return removed\n },\n }\n}\n\n/**\n * Atomically publishes a record. Returns `false` when another writer already\n * claimed the path, which is how a cross-process race is detected.\n *\n * The content is written and fsynced to a temp file first, then `link`ed into\n * place: `link` fails when the destination exists (unlike `rename`, which would\n * overwrite the winner) and publishes only complete bytes, so a concurrent\n * reader can never observe a half-written record.\n */\nasync function writeRecordExclusive(tempDir: string, path: string, record: unknown): Promise<boolean> {\n const tempPath = PATH.join(tempDir, `${PATH.basename(path)}.${process.pid}.${randomSuffix()}`)\n await writeDurableFile(tempPath, `${JSON.stringify(record)}\\n`)\n try {\n await link(tempPath, path)\n await syncDirectory(PATH.dirname(path))\n return true\n } catch (error) {\n if (isAlreadyExists(error)) return false\n throw error\n } finally {\n await unlinkIfMissing(tempPath)\n }\n}\n\nasync function readRecord<T>(path: string): Promise<T | undefined> {\n try {\n const handle = await open(path, 'r')\n try {\n const raw = await handle.readFile('utf8')\n return JSON.parse(raw) as T\n } finally {\n await handle.close()\n }\n } catch (error) {\n if (isNotFound(error)) return undefined\n throw error\n }\n}\n\nfunction digest(parts: readonly string[]): string {\n return createHash('sha256').update(JSON.stringify(parts)).digest('hex')\n}\n\nfunction randomSuffix(): string {\n return randomBytes(8).toString('hex')\n}\n\nasync function unlinkIfMissing(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) {\n if (!isNotFound(error)) throw error\n }\n}\n\nfunction isNotFound(error: unknown): boolean {\n return errorCode(error) === 'ENOENT'\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return errorCode(error) === 'EEXIST'\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 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 { 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 try {\n const handle = await open(path, 'r')\n try {\n return JSON.parse(await handle.readFile('utf8'), reviveJson) as unknown\n } finally {\n await handle.close()\n }\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return undefined\n throw error\n }\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 await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n try {\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 await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n try {\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 { 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.operationId,\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 { 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 { mkdir } from 'node:fs/promises'\nimport PATH from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nimport type {\n AdmittedWake,\n LeasedWake,\n WakeQueue,\n} from '@xyo-network/event-kit-protocol'\n\nexport interface SqliteWakeQueueOptions {\n /** Database file path, or `:memory:` for a throwaway store. */\n readonly path: string\n}\n\nexport interface SqliteWakeQueue extends WakeQueue {\n /** Releases the underlying handle. */\n close: () => void\n}\n\ninterface QueueRow {\n readonly body: string\n readonly id: number\n}\n\n/**\n * SQLite-backed `WakeQueue`.\n *\n * Every state change is a single statement under WAL, so a claim cannot be\n * observed half-applied and two callers cannot lease one row: the claim is an\n * `UPDATE \u2026 WHERE state = 'pending'` whose affected-row count decides the\n * winner. That is the transactional form of the lease the filesystem provider\n * approximates with `link`.\n *\n * WAL also permits concurrent readers with one writer, so several processes on\n * one host can share the file. It does not coordinate across hosts.\n *\n * Uses Node's built-in `node:sqlite`, which still emits an ExperimentalWarning.\n */\nexport async function createSqliteWakeQueue(\n options: SqliteWakeQueueOptions,\n): Promise<SqliteWakeQueue> {\n const inMemory = options.path === ':memory:'\n const file = inMemory ? options.path : PATH.resolve(options.path)\n if (!inMemory) await mkdir(PATH.dirname(file), { recursive: true })\n\n const database = new DatabaseSync(file)\n database.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = FULL;\n CREATE TABLE IF NOT EXISTS wake_queue (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n body TEXT NOT NULL,\n state TEXT NOT NULL DEFAULT 'pending'\n );\n CREATE INDEX IF NOT EXISTS wake_queue_state ON wake_queue (state, id);\n `)\n\n const insert = database.prepare('INSERT INTO wake_queue (body) VALUES (?)')\n const nextPending = database.prepare(\n 'SELECT id, body FROM wake_queue WHERE state = \\'pending\\' ORDER BY id LIMIT 1',\n )\n // The affected-row count is the lease: a loser updates zero rows and retries.\n const lease = database.prepare(\n 'UPDATE wake_queue SET state = \\'inflight\\' WHERE id = ? AND state = \\'pending\\'',\n )\n const remove = database.prepare('DELETE FROM wake_queue WHERE id = ?')\n const restore = database.prepare(\n 'UPDATE wake_queue SET state = \\'pending\\' WHERE id = ? AND state = \\'inflight\\'',\n )\n const countPending = database.prepare(\n 'SELECT COUNT(*) AS total FROM wake_queue WHERE state = \\'pending\\'',\n )\n const recoverAll = database.prepare(\n 'UPDATE wake_queue SET state = \\'pending\\' WHERE state = \\'inflight\\'',\n )\n\n return {\n async append(wake: AdmittedWake): Promise<void> {\n insert.run(JSON.stringify(wake))\n },\n\n async claim(): Promise<LeasedWake | undefined> {\n for (;;) {\n const row = nextPending.get() as QueueRow | undefined\n if (row === undefined) return undefined\n if (lease.run(row.id).changes !== 1) continue // another claimer won it\n\n return {\n wake: JSON.parse(row.body) as AdmittedWake,\n async ack(): Promise<void> {\n remove.run(row.id)\n },\n async release(): Promise<void> {\n restore.run(row.id)\n },\n }\n }\n },\n\n close(): void {\n database.close()\n },\n\n pendingCount: async (): Promise<number> => Number((countPending.get() as { total: number }).total),\n\n recoverInflight: async (): Promise<number> => Number(recoverAll.run().changes),\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EAAO;AAAA,EAAU;AAAA,OACZ;AACP,OAAO,UAAU;AAgBV,SAAS,4BACd,SACsB;AACtB,QAAM,WAAW,KAAK,QAAQ,QAAQ,IAAI;AAC1C,SAAO;AAAA,IACL,MAAM,OAAoC;AACxC,UAAI;AACF,cAAM,MAAM,MAAM,SAAS,UAAU,MAAM;AAC3C,cAAM,SAAS,KAAK,MAAM,G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EACF;AAEA,QAAM,QAAQ,SAAS;AAAA,IACrB;AAAA,EACF;AACA,QAAM,SAAS,SAAS,QAAQ,qCAAqC;AACrE,QAAM,UAAU,SAAS;AAAA,IACvB;AAAA,EACF;AACA,QAAM,eAAe,SAAS;AAAA,IAC5B;AAAA,EACF;AACA,QAAM,aAAa,SAAS;AAAA,IAC1B;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM,OAAO,MAAmC;AAC9C,aAAO,IAAI,KAAK,UAAU,IAAI,CAAC;AAAA,IACjC;AAAA,IAEA,MAAM,QAAyC;AAC7C,iBAAS;AACP,cAAM,MAAM,YAAY,IAAI;AAC5B,YAAI,QAAQ,OAAW,QAAO;AAC9B,YAAI,MAAM,IAAI,IAAI,EAAE,EAAE,YAAY,EAAG;AAErC,eAAO;AAAA,UACL,MAAM,KAAK,MAAM,IAAI,IAAI;AAAA,UACzB,MAAM,MAAqB;AACzB,mBAAO,IAAI,IAAI,EAAE;AAAA,UACnB;AAAA,UACA,MAAM,UAAyB;AAC7B,oBAAQ,IAAI,IAAI,EAAE;AAAA,UACpB;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,IAEA,QAAc;AACZ,eAAS,MAAM;AAAA,IACjB;AAAA,IAEA,cAAc,YAA6B,OAAQ,aAAa,IAAI,EAAwB,KAAK;AAAA,IAEjG,iBAAiB,YAA6B,OAAO,WAAW,IAAI,EAAE,OAAO;AAAA,EAC/E;AACF;",
6
+ "names": ["randomBytes", "mkdir", "unlink", "PATH", "open", "PATH", "mkdir", "PATH", "PATH", "isNotFound", "open", "errorCode", "PATH", "unlink", "isNotFound", "mkdir", "randomBytes", "randomBytes", "link", "mkdir", "open", "readdir", "unlink", "PATH", "PATH", "mkdir", "readdir", "unlinkIfMissing", "link", "isAlreadyExists", "open", "isNotFound", "randomBytes", "unlink", "errorCode", "PATH", "randomBytes", "link", "open", "rename", "unlink", "PATH", "open", "errorCode", "PATH", "rename", "unlinkIfMissing", "link", "randomBytes", "unlink", "PATH", "createHash", "PATH", "createHash", "PATH", "existing", "PATH", "digest", "lookup", "PATH", "lookup", "stat", "PATH", "Base64Url32BytesZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "PATH", "lookup", "HashZod", "HandshakeIdZod", "NormalizedAddressZod", "readRecord", "stat", "Base64Url32BytesZod", "PATH", "EndpointChallengeZod", "HashZod", "PATH", "HashZod", "EndpointChallengeZod", "handshakeObjectHash", "ChainIdZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "NormalizedAddressZod", "ChainIdZod", "HashZod", "HandshakeIdZod", "candidate", "handshakeObjectHash", "lookup", "view", "Buffer", "Buffer", "request", "isDeepStrictEqual", "EndpointChallengeResponseZod", "isDeepStrictEqual", "response", "EndpointChallengeResponseZod", "Buffer", "z", "createHash", "canonicalJson", "createHash", "canonicalJson", "z", "Buffer", "isDeepStrictEqual", "z", "randomBytes", "isDeepStrictEqual", "isDeepStrictEqual", "randomBytes", "randomBytes", "NormalizedAddressZod", "WakeEnvelopeZod", "PayloadBuilder", "z", "isDeepStrictEqual", "head", "isDeepStrictEqual", "endpointChallengeHash", "Base64Url32BytesZod", "EndpointChallengeZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "z", "z", "HashZod", "HandshakeIdZod", "Base64Url32BytesZod", "NormalizedAddressZod", "requireTime", "isDeepStrictEqual", "lookup", "EndpointChallengeZod", "endpointChallengeHash", "randomBytes", "mkdir", "open", "PATH", "PATH", "mkdir", "open", "metadata", "DatabaseSync", "randomBytes", "mkdir", "PATH"]
7
7
  }