@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.
- package/dist/node/handshake.mjs +12 -0
- package/dist/node/handshake.mjs.map +2 -2
- package/dist/node/handshakeClients.d.ts +5 -1
- package/dist/node/handshakeClients.d.ts.map +1 -1
- package/dist/node/handshakeMutationIntent.d.ts +128 -66
- package/dist/node/handshakeMutationIntent.d.ts.map +1 -1
- package/dist/node/index.mjs +277 -93
- package/dist/node/index.mjs.map +4 -4
- package/dist/node/runtime/handshakeDiscovery.d.ts +4 -0
- package/dist/node/runtime/handshakeDiscovery.d.ts.map +1 -1
- package/dist/node/runtime/publisherDeliveryState.d.ts +107 -0
- package/dist/node/runtime/publisherDeliveryState.d.ts.map +1 -0
- package/dist/node/runtime/publisherRuntime.d.ts +17 -1
- package/dist/node/runtime/publisherRuntime.d.ts.map +1 -1
- package/dist/node/runtime/sourceSigner.d.ts +1 -0
- package/dist/node/runtime/sourceSigner.d.ts.map +1 -1
- package/dist/node/runtime/sqliteHandshakeStores.d.ts +3 -1
- package/dist/node/runtime/sqliteHandshakeStores.d.ts.map +1 -1
- package/dist/node/runtime.mjs +265 -93
- package/dist/node/runtime.mjs.map +4 -4
- package/package.json +8 -8
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/filesystemEventKitReplayCheckpointStore.ts", "../../src/filesystemJson.ts", "../../src/filesystemDurability.ts", "../../src/filesystemFinalizedStatementPublicationJournal.ts", "../../src/filesystemHandshakeMutationIntentStore.ts", "../../src/handshakeMutationIntent.ts", "../../src/filesystemPublisherEncryptionKeyStore.ts", "../../src/filesystemPublisherEndpointChallengeStore.ts", "../../src/handshakeClients.ts"],
|
|
4
|
-
"sourcesContent": ["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 { 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 } 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"],
|
|
5
|
-
"mappings": ";AAAA,OAAOA,WAAU;;;ACAjB,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EAAM,QAAAC;AAAA,EAAM;AAAA,EAAQ;AAAA,OACf;AACP,OAAOC,WAAU;;;ACJjB,SAAS,OAAO,YAAY;AAC5B,OAAO,UAAU;AAGjB,eAAsB,iBAAiB,MAAc,MAAc,MAA8B;AAC/F,QAAM,SAAS,MAAM,KAAK,MAAM,KAAK,IAAI;AACzC,MAAI;AACF,UAAM,OAAO,UAAU,MAAM,MAAM;AACnC,UAAM,OAAO,KAAK;AAAA,EACpB,UAAE;AACA,UAAM,OAAO,MAAM;AAAA,EACrB;AACF;AAGA,eAAsB,uBAAuB,MAAc,MAA8B;AACvF,QAAM,YAAY,KAAK,QAAQ,IAAI;AACnC,QAAM,eAAe,MAAM,MAAM,WAAW,EAAE,MAAM,WAAW,KAAK,CAAC;AACrE,MAAI,iBAAiB,OAAW;AAEhC,QAAM,iBAAiB,KAAK,QAAQ,KAAK,QAAQ,YAAY,CAAC;AAC9D,MAAI,SAAS;AACb,SAAO,MAAM;AACX,UAAM,cAAc,MAAM;AAC1B,QAAI,WAAW,eAAgB;AAC/B,UAAM,SAAS,KAAK,QAAQ,MAAM;AAClC,QAAI,WAAW,OAAQ,OAAM,IAAI,MAAM,6DAA6D;AACpG,aAAS;AAAA,EACX;AACF;AAOA,eAAsB,cAAc,MAA6B;AAC/D,MAAI;AACJ,MAAI;AACF,aAAS,MAAM,KAAK,MAAM,GAAG;AAC7B,UAAM,OAAO,KAAK;AAAA,EACp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,WAAW;AAAA,IACpG;AAAA,IACA,eAAe,OAAO,mBAA0D,MAAM,OAAO,cAAc;AAAA,EAC7G;AACA,SAAO,OAAO,OAAO,MAAM;AAC7B;AAEA,SAAS,oBAAoB,SAA2B,OAAkC,qBAAwD;AAChJ,QAAM,iBAAiB;AAAA,IACrB,UAAU,MAAM;AAAA,IAChB,iBAAiB,MAAM;AAAA,IACvB,cAAc,MAAM;AAAA,IACpB,UAAU,MAAM;AAAA,IAChB,SAAS,MAAM;AAAA,EACjB;AACA,QAAM,SAAS,MAAM;AACrB,MAAI,QAAQ,OAAO,MAAM,WAAS,cAAc,MAAM,MAAM,MAAM,cAAc,MAAM,CAAC,GAAG;AACxF,UAAM,IAAI,MAAM,4DAA4D;AAAA,EAC9E;AACA,SAAO,gCAAgC;AAAA,IACrC,GAAG;AAAA,IAAgB;AAAA,IAAQ,cAAc,MAAM;AAAA,IAAc;AAAA,EAC/D,CAAC;AACH;",
|
|
4
|
+
"sourcesContent": ["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 { 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 } 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"],
|
|
5
|
+
"mappings": ";AAAA,OAAOA,WAAU;;;ACAjB,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EAAM,QAAAC;AAAA,EAAM;AAAA,EAAQ;AAAA,OACf;AACP,OAAOC,WAAU;;;ACJjB,SAAS,OAAO,YAAY;AAC5B,OAAO,UAAU;AAGjB,eAAsB,iBAAiB,MAAc,MAAc,MAA8B;AAC/F,QAAM,SAAS,MAAM,KAAK,MAAM,KAAK,IAAI;AACzC,MAAI;AACF,UAAM,OAAO,UAAU,MAAM,MAAM;AACnC,UAAM,OAAO,KAAK;AAAA,EACpB,UAAE;AACA,UAAM,OAAO,MAAM;AAAA,EACrB;AACF;AAGA,eAAsB,uBAAuB,MAAc,MAA8B;AACvF,QAAM,YAAY,KAAK,QAAQ,IAAI;AACnC,QAAM,eAAe,MAAM,MAAM,WAAW,EAAE,MAAM,WAAW,KAAK,CAAC;AACrE,MAAI,iBAAiB,OAAW;AAEhC,QAAM,iBAAiB,KAAK,QAAQ,KAAK,QAAQ,YAAY,CAAC;AAC9D,MAAI,SAAS;AACb,SAAO,MAAM;AACX,UAAM,cAAc,MAAM;AAC1B,QAAI,WAAW,eAAgB;AAC/B,UAAM,SAAS,KAAK,QAAQ,MAAM;AAClC,QAAI,WAAW,OAAQ,OAAM,IAAI,MAAM,6DAA6D;AACpG,aAAS;AAAA,EACX;AACF;AAOA,eAAsB,cAAc,MAA6B;AAC/D,MAAI;AACJ,MAAI;AACF,aAAS,MAAM,KAAK,MAAM,GAAG;AAC7B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ATH", "PATH", "existing", "PATH", "PATH", "stat", "PATH", "Base64Url32BytesZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "PATH", "HashZod", "HandshakeIdZod", "NormalizedAddressZod", "stat", "Base64Url32BytesZod", "PATH", "EndpointChallengeZod", "HashZod", "PATH", "HashZod", "EndpointChallengeZod", "handshakeObjectHash", "ChainIdZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "NormalizedAddressZod", "ChainIdZod", "HashZod", "HandshakeIdZod", "candidate", "handshakeObjectHash", "view"]
|
|
7
7
|
}
|