@xyo-network/event-kit-node 2.2.0 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node/index.mjs +4 -4
- package/dist/node/index.mjs.map +2 -2
- package/dist/node/runtime.mjs +2 -2
- package/dist/node/runtime.mjs.map +2 -2
- package/package.json +24 -24
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/runtime/boundedFetch.ts", "../../src/runtime/abort.ts", "../../src/runtime/handshakeDiscovery.ts", "../../src/runtime/httpsTransport.ts", "../../src/runtime/sources.ts", "../../src/runtime/publisherRuntime.ts", "../../src/runtime/publisherDeliveryState.ts", "../../src/runtime/sourceSigner.ts", "../../src/runtime/restGateway.ts", "../../src/runtime/sqliteHandshakeStores.ts", "../../src/handshakeMutationIntent.ts", "../../src/runtime/sqlitePublisherState.ts", "../../src/filesystemJson.ts"],
|
|
4
|
-
"sourcesContent": ["import { Buffer } from 'node:buffer'\n\nimport type { FetchGetUrlFunc } from 'ethers'\n\nimport { publisherAbortScope } from './abort.ts'\nexport interface BoundedPublisherFetchOptions {\n readonly maxConcurrency?: number\n readonly maxResponseBytes?: number\n readonly requestTimeoutMs?: number\n readonly signal?: AbortSignal\n}\n/** Per-instance SDK transport: aborts the real request, including its body, without changing global fetch. */\nexport function createBoundedPublisherFetch(options: BoundedPublisherFetchOptions = {}) {\n const owner = new AbortController()\n const timeout = options.requestTimeoutMs ?? 10_000\n const maximum = options.maxResponseBytes ?? 16 * 1024 * 1024\n const concurrency = options.maxConcurrency ?? 16\n if (!Number.isSafeInteger(timeout) || timeout < 100 || timeout > 60_000\n || !Number.isSafeInteger(maximum) || maximum < 1 || maximum > 64 * 1024 * 1024\n || !Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 64)\n throw new Error('Invalid publisher fetch limits')\n const active = new Set<Promise<Response>>()\n const nativeFetch = globalThis.fetch.bind(globalThis)\n const fetchFn: typeof globalThis.fetch = (input, init) => {\n if (active.size >= concurrency)\n return Promise.reject(new Error('Publisher HTTP concurrency limit exceeded'))\n const operation = (async () => {\n const signals = [owner.signal,\n ...(options.signal === undefined ? [] : [options.signal]),\n ...(init?.signal == null ? [] : [init.signal]),\n ...(input instanceof Request ? [input.signal] : [])]\n const scope = publisherAbortScope(signals, timeout)\n try {\n scope.signal.throwIfAborted()\n const response = await nativeFetch(input, {\n ...init, redirect: 'error', signal: scope.signal,\n })\n if (response.body === null)\n return response\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done)\n break\n const bytes: unknown = chunk.value\n if (!(bytes instanceof Uint8Array)) throw new Error('Publisher HTTP body returned a non-byte chunk')\n size += bytes.byteLength\n if (size > maximum) {\n await reader.cancel()\n throw new Error('Publisher HTTP body exceeds its bound')\n }\n chunks.push(bytes)\n }\n } finally {\n reader.releaseLock()\n }\n const headers = new Headers(response.headers)\n headers.delete('content-encoding')\n headers.delete('transfer-encoding')\n headers.set('content-length', String(size))\n return new Response(Buffer.concat(chunks), {\n status: response.status, statusText: response.statusText, headers,\n })\n } finally {\n scope.dispose()\n }\n })()\n active.add(operation)\n void operation.then(() => active.delete(operation), () => active.delete(operation))\n return operation\n }\n return {\n fetchFn,\n async close() {\n owner.abort()\n await Promise.allSettled(active)\n },\n get activeRequests() {\n return active.size\n },\n }\n}\n\n/** Ethers' documented per-request HTTP hook, without its unbounded Node body reader. */\nexport function createBoundedPublisherEthersTransport(options: BoundedPublisherFetchOptions = {}) {\n const bounded = createBoundedPublisherFetch(options)\n const getUrl: FetchGetUrlFunc = async (request, cancellation) => {\n const controller = new AbortController()\n cancellation?.addListener(() => controller.abort())\n cancellation?.checkSignal()\n const response = await bounded.fetchFn(request.url, {\n body: request.body === null ? undefined : Buffer.from(request.body),\n headers: request.headers,\n method: request.method,\n signal: controller.signal,\n })\n return {\n body: new Uint8Array(await response.arrayBuffer()),\n headers: Object.fromEntries(response.headers),\n statusCode: response.status,\n statusMessage: response.statusText,\n }\n }\n return {\n getUrl,\n async close() { await bounded.close() },\n get activeRequests() { return bounded.activeRequests },\n }\n}\n", "import { clearTimeout, setTimeout } from 'node:timers'\n\n/** Own every listener/timer used by a bounded operation; disposal is mandatory. */\nexport function publisherAbortScope(signals: readonly AbortSignal[], timeoutMs?: number) {\n const controller = new AbortController()\n const abort = () => controller.abort()\n const timer = timeoutMs === undefined ? undefined : setTimeout(abort, timeoutMs)\n timer?.unref()\n for (const signal of signals) {\n if (signal.aborted) controller.abort()\n else signal.addEventListener('abort', abort, { once: true })\n }\n return {\n signal: controller.signal,\n dispose() {\n if (timer !== undefined) clearTimeout(timer)\n for (const signal of signals) signal.removeEventListener('abort', abort)\n },\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport { decryptWakeSubscription, sourceWakeFilterHash } from '@xyo-network/event-kit-protocol'\nimport type {\n BestEffortDeliveryPolicy, EndpointChallengeResponse, WakeDeliveryMode,\n} from '@xyo-network/event-kit-schemas'\nimport { EndpointChallengeResponseZod } from '@xyo-network/event-kit-schemas'\nimport type { FinalizedSubscriptionTuple } from '@xyo-network/event-kit-statement-graph'\n\nimport type { PublisherEncryptionKeyCustody, PublisherHandshakeClient } from '../handshakeClients.ts'\nimport { publisherAbortScope } from './abort.ts'\nimport type { PublisherHttpsTransport } from './httpsTransport.ts'\nimport type {\n PublisherRuntimeDiscovery, PublisherRuntimeDiscoveryStatus, PublisherRuntimeSubscription,\n} from './publisherRuntime.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\ninterface PendingChallenge {\n readonly challengeHash: string\n readonly expiresAt: number\n readonly response?: EndpointChallengeResponse\n readonly subscriber: string\n readonly subscription: string\n}\n/** Real D005 lifecycle discovery. Off-chain configuration never grants delivery authority. */\nexport function createPublisherHandshakeDiscovery(options: {\n readonly authorizationChainId: string\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly client: PublisherHandshakeClient\n readonly deliveryMode?: WakeDeliveryMode\n readonly keys: PublisherEncryptionKeyCustody\n readonly maxSubscriptions?: number\n readonly nowSeconds?: () => number\n readonly publisher: string\n readonly serviceHash?: string\n readonly state: SqlitePublisherState\n readonly transport: PublisherHttpsTransport\n}): PublisherRuntimeDiscovery {\n const clock = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const owner = new AbortController()\n let accepting: Promise<void> | undefined\n let viewing: ReturnType<PublisherHandshakeClient['subscriptions']> | undefined\n let status: PublisherRuntimeDiscoveryStatus = {\n authorizationChainId: options.authorizationChainId,\n keyLoaded: false,\n activeKeyIds: [],\n pendingSubscriptions: 0,\n rejectedSubscriptions: 0,\n challengeFailures: 0,\n }\n function selectedTuple(tuple: FinalizedSubscriptionTuple): boolean {\n return (options.serviceHash === undefined || tuple.service.objectHash === options.serviceHash)\n && (options.deliveryMode === undefined || tuple.service.body.deliveryMode === options.deliveryMode)\n && (options.deliveryMode === undefined || tuple.subscription.body.deliveryMode === options.deliveryMode)\n && (options.deliveryMode === undefined || isDeepStrictEqual(tuple.service.body.bestEffort, options.bestEffort))\n }\n async function activeView(signal: AbortSignal) {\n signal.throwIfAborted()\n // A timed-out caller does not create a second SDK replay while the first\n // remains in flight. The configured REST transport aborts actual reads.\n viewing ??= (async () => {\n try {\n return await options.client.subscriptions()\n } finally {\n viewing = undefined\n }\n })()\n const view = await viewing\n signal.throwIfAborted()\n if (!view.ok || view.indexedThrough !== view.finalizedHead)\n throw new Error('Publisher subscription view is unavailable or stale')\n status = {\n ...status,\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n pendingSubscriptions: view.subscriptions.filter(item => item.state === 'pending' && item.tuples.some(selectedTuple)).length,\n rejectedSubscriptions: view.rejections.length,\n }\n return view\n }\n async function acceptCandidate(subscriber: string, subscription: string, signal: AbortSignal) {\n try {\n let pending = options.state.get<PendingChallenge>('outbound-challenges', subscription)\n if (pending !== undefined && pending.response === undefined && clock() >= pending.expiresAt)\n pending = undefined\n if (pending === undefined) {\n const issued = await options.client.issueChallenge({\n issuedAt: clock(), lifetimeSeconds: 300, subscriber: subscriber, subscription,\n })\n pending = {\n challengeHash: issued.challengeHash, subscriber: subscriber, subscription, expiresAt: issued.challenge.expiresAt,\n }\n options.state.set('outbound-challenges', subscription, pending)\n }\n if (pending.response === undefined) {\n const begun = await options.client.beginChallenge({ challengeHash: pending.challengeHash, nowSeconds: clock })\n if (begun.kind !== 'started')\n return\n signal.throwIfAborted()\n const response = await options.transport.post(begun.target.endpoint, begun.challenge, signal)\n if (response.status !== 200)\n throw new Error('Endpoint challenge was rejected')\n pending = { ...pending, response: EndpointChallengeResponseZod.parse(response.body) }\n options.state.set('outbound-challenges', subscription, pending)\n }\n signal.throwIfAborted()\n const response = pending.response\n if (response === undefined)\n throw new Error('Endpoint proof is unavailable')\n await options.client.completeChallengeAndAccept({\n ...pending, response, nowSeconds: clock,\n })\n } catch {\n if (signal.aborted)\n return\n const failures = options.state.get<number>('challenge-failures', subscription) ?? 0\n options.state.set('challenge-failures', subscription, failures + 1)\n const pending = options.state.get<PendingChallenge>('outbound-challenges', subscription)\n if (pending !== undefined && clock() >= pending.expiresAt)\n options.state.remove('outbound-challenges', subscription)\n }\n }\n\n async function accept(signal: AbortSignal) {\n signal.throwIfAborted()\n const now = clock()\n if (now < (options.state.get<number>('challenge-rate', 'next-pass') ?? 0))\n return\n options.state.set('challenge-rate', 'next-pass', now + 10)\n const found = await options.client.acceptanceCandidates()\n if (!found.ok)\n throw new Error('Publisher acceptance candidates are unavailable')\n const offset = options.state.get<number>('challenge-rate', 'offset') ?? 0\n const candidates = found.candidates.filter(candidate => selectedTuple(candidate.tuple))\n let attempted = 0\n // Bound inspected candidates and rotate the starting point: four failed\n // candidates must not permanently prevent the fifth from being challenged.\n for (let index = 0; index < Math.min(candidates.length, 128) && attempted < 4; index += 1) {\n const candidate = candidates[(offset + index) % candidates.length]\n if (candidate === undefined)\n break\n options.state.set('challenge-rate', 'offset', (offset + index + 1) % candidates.length)\n const next = options.state.get<number>('challenge-controller-rate', candidate.subscriber) ?? 0\n if (now < next)\n continue\n options.state.set('challenge-controller-rate', candidate.subscriber, now + 30)\n attempted += 1\n signal.throwIfAborted()\n await acceptCandidate(candidate.subscriber, candidate.tuple.subscription.objectHash, signal)\n }\n }\n async function loadScopedKeys(view: Extract<Awaited<ReturnType<PublisherHandshakeClient['subscriptions']>>, { ok: true }>, active: typeof view.subscriptions) {\n const scopedKeys = active.flatMap(item => item.tuples.filter(tuple => tuple.subscription.objectHash === item.selectedSubscription).map(tuple => ({\n encryptionKey: tuple.subscription.body.encryptionKey, keyId: tuple.subscription.body.keyId, publisher: options.publisher,\n })))\n if (view.hasCurrentAdvertisement && (options.serviceHash === undefined || view.service.objectHash === options.serviceHash)\n && (options.deliveryMode === undefined || view.service.body.deliveryMode === options.deliveryMode)) {\n scopedKeys.push({\n encryptionKey: view.key.objectHash, keyId: view.key.body.keyId, publisher: options.publisher,\n })\n }\n const loadedKeys = await Promise.all(scopedKeys.map(async key => await options.keys.getPrivateKey(key)))\n status = {\n ...status,\n keyLoaded: scopedKeys.length > 0 && loadedKeys.every(key => key !== undefined),\n activeKeyIds: [...new Set(scopedKeys.map(key => key.keyId))],\n }\n }\n return {\n async discover(signal) {\n const view = await activeView(signal)\n const active = view.subscriptions.filter(item => item.state === 'active' && item.tuples.some(tuple => tuple.subscription.objectHash === item.selectedSubscription && selectedTuple(tuple)))\n await loadScopedKeys(view, active)\n if (active.length > (options.maxSubscriptions ?? 64))\n throw new Error('Publisher active subscription limit exceeded')\n const subscriptions: PublisherRuntimeSubscription[] = []\n for (const lifecycle of active) {\n if (lifecycle.state !== 'active' || lifecycle.activeFromBlock === undefined)\n continue\n try {\n const tuple = lifecycle.tuples.find(item => item.subscription.objectHash === lifecycle.selectedSubscription)\n if (tuple === undefined || !selectedTuple(tuple))\n throw new Error('Active publisher subscription has no selected tuple')\n const encrypted = tuple.subscription.body\n if (encrypted.chainId !== options.authorizationChainId)\n throw new Error('Subscription authorization chain mismatch')\n const publisherKey = await options.keys.getPrivateKey({\n encryptionKey: encrypted.encryptionKey, keyId: encrypted.keyId, publisher: options.publisher,\n })\n if (publisherKey === undefined)\n throw new Error('Subscription encryption key is unavailable')\n const plaintext = await decryptWakeSubscription({\n publisherKey, subscriber: tuple.subscriber, subscription: encrypted,\n })\n options.transport.assertAllowed(plaintext.endpoint)\n subscriptions.push({\n subscriptionHash: tuple.subscription.objectHash,\n serviceHash: tuple.service.objectHash,\n deliveryMode: plaintext.filter.deliveryMode,\n ...(plaintext.filter.bestEffort === undefined ? {} : { bestEffort: plaintext.filter.bestEffort }),\n authorizationChainId: options.authorizationChainId,\n controller: tuple.subscriber,\n audience: plaintext.audience,\n endpoint: plaintext.endpoint,\n deploymentId: plaintext.deploymentId,\n ...(plaintext.queueId === null ? {} : { queueId: plaintext.queueId }),\n source: plaintext.filter.source,\n fromPosition: plaintext.filter.fromPosition,\n maxPositionsPerWake: plaintext.filter.maxPositionsPerWake,\n filterHash: await sourceWakeFilterHash(plaintext.filter),\n })\n } catch {\n // A malformed or locally disallowed endpoint cannot stop independent\n // accepted subscribers. Durable pending work remains until a fresh\n // authoritative check proves the subscription is inactive.\n status = { ...status, rejectedSubscriptions: status.rejectedSubscriptions + 1 }\n }\n }\n return subscriptions\n },\n async isActive(subscription, signal) {\n const view = await activeView(signal)\n return view.subscriptions.some(item => item.state === 'active' && item.selectedSubscription === subscription.subscriptionHash\n && item.tuples.some(tuple => tuple.subscription.objectHash === subscription.subscriptionHash && tuple.subscriber === subscription.controller && selectedTuple(tuple)))\n },\n async acceptPending(signal) {\n // A slow finality operation is shared across passes; timeout does not\n // spawn another acceptance/signing operation against the same state.\n if (accepting === undefined) {\n const scope = publisherAbortScope([owner.signal, signal])\n accepting = (async () => {\n try {\n await accept(scope.signal)\n } finally {\n scope.dispose()\n accepting = undefined\n }\n })()\n }\n await accepting\n },\n async close() {\n await Promise.allSettled([accepting, viewing].filter(item => item !== undefined))\n },\n status: () => ({ ...status, challengeFailures: options.state.entries<number>('challenge-failures').reduce((sum, item) => sum + item.value, 0) }),\n }\n}\n", "import { Buffer } from 'node:buffer'\nimport { lookup } from 'node:dns/promises'\nimport { request } from 'node:https'\nimport { BlockList, isIP } from 'node:net'\n\nimport { z } from 'zod'\n\nimport { publisherAbortScope } from './abort.ts'\nimport { boundedPublisherOperation } from './sources.ts'\nconst OptionsZod = z.strictObject({\n allowedEndpoints: z.array(z.url()).min(1).max(64),\n endpointHeaders: z.array(z.strictObject({\n endpoint: z.url(),\n headers: z.strictObject({ 'x-vercel-protection-bypass': z.string().min(1).max(4096).regex(/^[\\u{21}-\\u{7E}]+$/u) }),\n })).max(64).default([]),\n maxResponseBytes: z.number().int().min(1).max(1_048_576).default(65_536),\n requestTimeoutMs: z.number().int().min(100).max(60_000).default(10_000),\n})\nexport interface PublisherHttpsTransportOptions {\n /** Exact public HTTPS destinations approved by the operator, including their path. */\n readonly allowedEndpoints: readonly string[]\n /** Private operator-provisioned Vercel automation credential, bound to one exact destination. */\n readonly endpointHeaders?: readonly { readonly endpoint: string; readonly headers: Readonly<Record<string, string>> }[]\n readonly maxResponseBytes?: number\n readonly requestTimeoutMs?: number\n}\nexport interface PublisherHttpsResponse {\n readonly body: unknown\n readonly retryAfterMs?: number\n readonly status: number\n}\nexport interface PublisherHttpsTransport {\n assertAllowed(endpoint: string): void\n post(endpoint: string, body: unknown, signal: AbortSignal, jwt?: string): Promise<PublisherHttpsResponse>\n}\nconst NON_PUBLIC_IPV4_SUBNETS = [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.0.0.0', 24],\n ['192.0.2.0', 24],\n ['192.88.99.0', 24],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['198.51.100.0', 24],\n ['203.0.113.0', 24],\n ['224.0.0.0', 4],\n ['240.0.0.0', 4],\n] as const\nconst NON_PUBLIC_IPV6_SUBNETS = [\n ['2001::', 23], ['2001:db8::', 32], ['2002::', 16], ['3fff::', 20],\n] as const\n\ninterface PublisherAddressPolicy {\n readonly globalIpv6: BlockList\n readonly nonPublicIpv4: BlockList\n readonly nonPublicIpv6: BlockList\n}\n\nlet publisherAddressPolicy: PublisherAddressPolicy | undefined\n\nfunction loadPublisherAddressPolicy(): PublisherAddressPolicy {\n if (publisherAddressPolicy !== undefined) return publisherAddressPolicy\n const nonPublicIpv4 = new BlockList()\n for (const [address, prefix] of NON_PUBLIC_IPV4_SUBNETS) {\n nonPublicIpv4.addSubnet(address, prefix, 'ipv4')\n }\n const globalIpv6 = new BlockList()\n globalIpv6.addSubnet('2000::', 3, 'ipv6')\n const nonPublicIpv6 = new BlockList()\n for (const [address, prefix] of NON_PUBLIC_IPV6_SUBNETS) {\n nonPublicIpv6.addSubnet(address, prefix, 'ipv6')\n }\n publisherAddressPolicy = {\n globalIpv6, nonPublicIpv4, nonPublicIpv6,\n }\n return publisherAddressPolicy\n}\n\n/** Conservative public-unicast policy, with numeric subnet checks for every IPv6 spelling. */\nexport function isPublicPublisherAddress(address: string): boolean {\n const policy = loadPublisherAddressPolicy()\n return isIP(address) === 4\n ? !policy.nonPublicIpv4.check(address, 'ipv4')\n : isIP(address) === 6 && policy.globalIpv6.check(address, 'ipv6') && !policy.nonPublicIpv6.check(address, 'ipv6')\n}\nexport function createPublisherHttpsTransport(input: PublisherHttpsTransportOptions): PublisherHttpsTransport {\n const parsed = OptionsZod.safeParse(input)\n if (!parsed.success) throw new Error('Invalid publisher HTTPS transport configuration')\n const options = parsed.data\n const allowed = new Set(options.allowedEndpoints.map((endpoint) => {\n const url = new URL(endpoint)\n if (url.href !== endpoint || url.protocol !== 'https:' || (url.port !== '' && url.port !== '443')\n || url.username !== '' || url.password !== '' || url.hash !== '')\n throw new Error('Publisher destinations must be canonical public HTTPS URLs on port 443')\n const literal = url.hostname.replaceAll(/^\\[|\\]$/gu, '')\n if (isIP(literal) !== 0 && !isPublicPublisherAddress(literal))\n throw new Error('Publisher destination is not public')\n if (url.hostname === 'localhost' || url.hostname.endsWith('.localhost') || url.hostname.endsWith('.local'))\n throw new Error('Publisher destination is not public')\n return endpoint\n }))\n const assertAllowed = (endpoint: string) => {\n if (!allowed.has(endpoint))\n throw new Error('Publisher destination is not explicitly allowed')\n }\n const endpointHeaders = new Map<string, Readonly<Record<string, string>>>()\n for (const entry of options.endpointHeaders) {\n assertAllowed(entry.endpoint)\n if (endpointHeaders.has(entry.endpoint)) throw new Error('Duplicate publisher endpoint header configuration')\n endpointHeaders.set(entry.endpoint, entry.headers)\n }\n return {\n assertAllowed,\n async post(endpoint, body, signal, jwt) {\n assertAllowed(endpoint)\n signal.throwIfAborted()\n const url = new URL(endpoint)\n const scope = publisherAbortScope([signal], options.requestTimeoutMs)\n const combined = scope.signal\n try {\n const addresses = await boundedPublisherOperation(lookup(url.hostname.replaceAll(/^\\[|\\]$/gu, ''), { all: true, verbatim: true }), combined, options.requestTimeoutMs)\n combined.throwIfAborted()\n if (addresses.length === 0 || addresses.some(item => !isPublicPublisherAddress(item.address)))\n throw new Error('Publisher DNS answer includes a non-public address')\n const selected = addresses[0]\n if (selected === undefined)\n throw new Error('Publisher DNS lookup was empty')\n const encoded = Buffer.from(JSON.stringify(body))\n if (encoded.byteLength > 65_536)\n throw new Error('Publisher request body is too large')\n return await new Promise<PublisherHttpsResponse>((resolve, reject) => {\n const call = request(url, {\n agent: false,\n headers: {\n ...endpointHeaders.get(endpoint),\n 'content-length': encoded.byteLength,\n 'content-type': 'application/json',\n ...(jwt === undefined ? {} : { authorization: `Bearer ${jwt}` }),\n },\n lookup(_hostname, lookupOptions, callback) {\n // Pin the validated DNS answer for this connection; TLS still validates\n // the original hostname. No second resolver can rebind to a private IP.\n if (lookupOptions.all)\n callback(null, [{ address: selected.address, family: selected.family }])\n else\n callback(null, selected.address, selected.family)\n },\n method: 'POST',\n rejectUnauthorized: true,\n signal: combined,\n }, (response) => {\n const status = response.statusCode ?? 500\n if (status >= 300 && status < 400) {\n response.destroy()\n reject(new Error('Publisher HTTPS redirects are forbidden'))\n return\n }\n let size = 0\n const chunks: Buffer[] = []\n response.on('data', (chunk: Buffer) => {\n size += chunk.byteLength\n if (size > options.maxResponseBytes) {\n response.destroy()\n reject(new Error('Publisher HTTPS response is too large'))\n } else\n chunks.push(chunk)\n })\n response.on('error', () => reject(new Error('Publisher HTTPS response failed')))\n response.on('end', () => {\n try {\n const responseBody: unknown = size === 0 ? null : JSON.parse(Buffer.concat(chunks).toString('utf8'))\n const retry = Number(response.headers['retry-after'])\n resolve({\n status, body: responseBody, ...(Number.isFinite(retry) && retry > 0 ? { retryAfterMs: Math.min(retry * 1000, 3_600_000) } : {}),\n })\n } catch {\n reject(new Error('Publisher HTTPS response is not JSON'))\n }\n })\n })\n call.on('error', () => reject(new Error('Publisher HTTPS request failed')))\n call.end(encoded)\n })\n } finally {\n scope.dispose()\n }\n },\n }\n}\n", "import { createHash } from 'node:crypto'\n\nimport { canonicalJson } from '@xyo-network/event-kit-protocol'\nimport type { WakeSource } from '@xyo-network/event-kit-schemas'\nimport { completedUtcIntervalPosition, WakeSourceZod } from '@xyo-network/event-kit-schemas'\nimport { PayloadBuilder } from '@xyo-network/sdk'\nimport type { XyoGateway } from '@xyo-network/xl1-sdk'\nimport { asXL1BlockNumber } from '@xyo-network/xl1-sdk'\nimport { FetchRequest, JsonRpcProvider } from 'ethers'\n\nimport { publisherAbortScope } from './abort.ts'\nimport { createBoundedPublisherEthersTransport } from './boundedFetch.ts'\nexport interface PublisherSourceHead {\n readonly hash?: string\n readonly position: number\n}\nexport interface PublisherSourceReader {\n readonly source: WakeSource\n close?(): void | Promise<void>\n head(signal: AbortSignal): Promise<PublisherSourceHead>\n}\nexport function publisherSourceKey(source: WakeSource): string {\n return createHash('sha256').update(canonicalJson(WakeSourceZod.parse(source))).digest('hex')\n}\nexport async function boundedPublisherOperation<T>(operation: Promise<T>, signal: AbortSignal, timeoutMs = 10_000): Promise<T> {\n const scope = publisherAbortScope([signal], timeoutMs)\n const combined = scope.signal\n let rejectAbort: (() => void) | undefined\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = () => reject(new Error('Publisher operation aborted or timed out'))\n combined.addEventListener('abort', rejectAbort, { once: true })\n })\n try {\n combined.throwIfAborted()\n return await Promise.race([operation, aborted])\n } finally {\n if (rejectAbort !== undefined)\n combined.removeEventListener('abort', rejectAbort)\n scope.dispose()\n }\n}\ntype GatewayViewer = NonNullable<XyoGateway['connection']['viewer']>\nexport function createXl1PublisherSource(options: {\n readonly source: Extract<WakeSource, {\n kind: 'xl1-finalized'\n }>\n readonly viewer: Pick<GatewayViewer, 'block' | 'chainId' | 'finalization'>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'xl1-finalized')\n throw new Error('Expected an XL1 finalized source')\n return {\n source,\n async head(signal) {\n const chainId = String(await boundedPublisherOperation(Promise.resolve(options.viewer.chainId()), signal))\n if (chainId !== source.chainId)\n throw new Error('XL1 source chain identity changed')\n const position = Number(await boundedPublisherOperation(Promise.resolve(options.viewer.finalization.headNumber()), signal))\n if (!Number.isSafeInteger(position) || position < 0)\n throw new Error('XL1 finalized head is invalid')\n const block = await boundedPublisherOperation(Promise.resolve(options.viewer.block.blockByNumber(asXL1BlockNumber(position, true))), signal)\n if (block?.[0].block !== position || !/^[0-9a-f]{64}$/u.test(block[0]._hash)) {\n throw new Error('XL1 finalized head block is unavailable or inconsistent')\n }\n if (String(block[0].chain) !== source.chainId || await PayloadBuilder.hash(block[0]) !== block[0]._hash) {\n throw new Error('XL1 finalized head block chain or hash is inconsistent')\n }\n return { position, hash: block[0]._hash }\n },\n }\n}\nexport function createEthereumFinalizedPublisherSource(options: {\n readonly requestTimeoutMs?: number\n readonly rpcUrl: string\n readonly source: Extract<WakeSource, {\n kind: 'ethereum-finalized'\n }>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'ethereum-finalized')\n throw new Error('Expected an Ethereum finalized source')\n const { chainId, genesisHash } = source\n const url = new URL(options.rpcUrl)\n if (url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.hash !== '') {\n throw new Error('Ethereum source RPC must use HTTPS without URL credentials or fragments')\n }\n const connection = new FetchRequest(url.href)\n connection.timeout = options.requestTimeoutMs ?? 10_000\n const transport = createBoundedPublisherEthersTransport({\n requestTimeoutMs: options.requestTimeoutMs, maxResponseBytes: 2 * 1024 * 1024, maxConcurrency: 8,\n })\n connection.getUrlFunc = transport.getUrl\n connection.setThrottleParams({ maxAttempts: 1 })\n const provider = new JsonRpcProvider(connection, undefined, { batchMaxCount: 1, cacheTimeout: -1 })\n let reading: Promise<PublisherSourceHead> | undefined\n let closed = false\n let closing: Promise<void> | undefined\n const close = () => closing ??= (async () => {\n closed = true\n provider.destroy()\n await transport.close()\n })()\n const onAbort = () => {\n void close()\n }\n async function read() {\n const requests = [provider.getNetwork(), provider.getBlock(0), provider.getBlock('finalized')] as const\n // A failing sibling request cannot release the single-flight slot while\n // another request still owns a connection or a bounded response body.\n try {\n const [network, genesis, block] = await Promise.all(requests)\n if (network.chainId.toString() !== chainId || genesis?.hash?.slice(2).toLowerCase() !== genesisHash) {\n throw new Error('Ethereum source chain identity mismatch')\n }\n if (block?.hash === null || block === null || !/^0x[0-9a-fA-F]{64}$/u.test(block.hash)\n || !Number.isSafeInteger(block.number) || block.number < 0) throw new Error('Ethereum finalized head is unavailable')\n return { position: block.number, hash: block.hash.slice(2).toLowerCase() }\n } catch (error) {\n await Promise.allSettled(requests)\n throw error\n }\n }\n return {\n source,\n close,\n async head(signal) {\n signal.throwIfAborted()\n if (closed) throw new Error('Ethereum source is closed')\n signal.addEventListener('abort', onAbort, { once: true })\n reading ??= (async () => {\n try {\n return await read()\n } finally {\n reading = undefined\n }\n })()\n try {\n return await boundedPublisherOperation(reading, signal, options.requestTimeoutMs ?? 10_000)\n } finally {\n signal.removeEventListener('abort', onAbort)\n }\n },\n }\n}\n\nexport function createUtcIntervalPublisherSource(options: {\n readonly nowSeconds?: () => number\n readonly source: Extract<WakeSource, {\n kind: 'utc-interval'\n }>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'utc-interval')\n throw new Error('Expected a UTC interval source')\n const nowSeconds = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n return {\n source,\n async head(signal) {\n signal.throwIfAborted()\n const now = nowSeconds()\n if (!Number.isSafeInteger(now) || now < 0)\n throw new Error('UTC interval clock is invalid')\n return { position: completedUtcIntervalPosition(source, now) ?? -1 }\n },\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport type { PeriodicActorParams, PeriodicPassContext } from '@ariestools/actor'\nimport { createMemoryLocator, PeriodicActor } from '@ariestools/actor'\nimport { creatable } from '@ariestools/sdk'\nimport { BestEffortAdmissionAcknowledgmentZod } from '@xyo-network/event-kit-protocol'\nimport type {\n BestEffortDeliveryPolicy, WakeDeliveryMode, WakeEnvelope, WakeSource,\n} from '@xyo-network/event-kit-schemas'\nimport { BestEffortDeliveryPolicyZod, WakeDeliveryModeZod } from '@xyo-network/event-kit-schemas'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { publisherAbortScope } from './abort.ts'\nimport type { PublisherHttpsTransport } from './httpsTransport.ts'\nimport type { DeliveryState } from './publisherDeliveryState.ts'\nimport {\n assertDeliveryState, DeliveryResponseError, failedDelivery, makeEvent, prepareBestEffortDelivery,\n} from './publisherDeliveryState.ts'\nimport type { PublisherSourceHead, PublisherSourceReader } from './sources.ts'\nimport { boundedPublisherOperation, publisherSourceKey } from './sources.ts'\nimport { createAccountSourceWakeSigner } from './sourceSigner.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\nexport interface PublisherRuntimeSubscription {\n readonly audience: string\n readonly authorizationChainId: string\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly controller: string\n readonly deliveryMode: WakeDeliveryMode\n readonly deploymentId: string\n readonly endpoint: string\n readonly filterHash: string\n readonly fromPosition: number\n readonly maxPositionsPerWake: number\n readonly queueId?: string\n readonly serviceHash?: string\n readonly source: WakeSource\n readonly subscriptionHash: string\n}\n/** Discovery MUST return only current finalized, accepted subscriptions. */\nexport interface PublisherRuntimeDiscovery {\n acceptPending?(signal: AbortSignal): Promise<void>\n close?(): Promise<void>\n discover(signal: AbortSignal): Promise<readonly PublisherRuntimeSubscription[]>\n /** Re-check the exact current revision before each attempt, including retries. */\n isActive(subscription: PublisherRuntimeSubscription, signal: AbortSignal): Promise<boolean>\n status?(): PublisherRuntimeDiscoveryStatus\n}\nexport interface PublisherRuntimeDiscoveryStatus {\n readonly activeKeyIds: readonly string[]\n readonly authorizationChainId: string\n readonly challengeFailures: number\n readonly finalizedHead?: number\n readonly indexedThrough?: number\n readonly keyLoaded: boolean\n readonly pendingSubscriptions: number\n readonly rejectedSubscriptions: number\n}\nfunction activationReady(status?: PublisherRuntimeDiscoveryStatus): boolean {\n return (status?.keyLoaded ?? true) && (status?.pendingSubscriptions ?? 0) === 0\n}\n\nexport interface PersistentEventPublisherOptions {\n readonly account: AccountInstance\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly concurrency?: number\n readonly deliveryMode: WakeDeliveryMode\n readonly discovery: PublisherRuntimeDiscovery\n readonly intervalMs?: number\n readonly maxSubscriptions?: number\n readonly nowSeconds?: () => number\n readonly publisher: string\n readonly requestTimeoutMs?: number\n /** Optional immutable operator pin; mismatches fail readiness without revoking subscriptions. */\n readonly serviceHash?: string\n readonly sources: readonly PublisherSourceReader[]\n readonly state: SqlitePublisherState\n readonly transport: PublisherHttpsTransport\n}\nexport interface PersistentEventPublisherStatus {\n readonly abandoned: number\n readonly activeSubscriptions: number\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly clockHealthy: boolean\n readonly degraded: boolean\n readonly delivered: number\n readonly deliveryMode: WakeDeliveryMode\n readonly failures: number\n readonly handshake?: PublisherRuntimeDiscoveryStatus\n readonly lastError?: string\n readonly passes: number\n readonly pendingDeliveries: number\n readonly publisher: string\n readonly ready: boolean\n readonly running: boolean\n readonly sources: readonly {\n readonly hash?: string\n readonly id: string\n readonly position: number\n }[]\n readonly subscriptions: readonly {\n readonly attempts?: number\n readonly cursor: number\n readonly failures: number\n readonly id: string\n /** Best Effort admission target is not a contiguous source prefix. */\n readonly lastAdmissionTarget?: number\n readonly lastHintAt?: number\n readonly pending: boolean\n readonly state: string\n }[]\n readonly superseded: number\n readonly totalAttempts: number\n}\nexport interface PersistentEventPublisher {\n runOnce(): Promise<void>\n start(): Promise<void>\n status(): PersistentEventPublisherStatus\n stop(): Promise<void>\n}\ninterface RuntimeActorParams extends PeriodicActorParams {\n readonly tick: (signal: AbortSignal) => Promise<void>\n}\n@creatable()\nclass PublisherRuntimeActor extends PeriodicActor<RuntimeActorParams> {\n protected override async runPass(context: PeriodicPassContext): Promise<void> {\n await this.params.tick(context.signal)\n }\n}\nconst TimingZod = z.object({\n concurrency: z.number().int().min(1).max(32).default(4),\n intervalMs: z.number().int().min(100).max(60_000).default(1000),\n maxSubscriptions: z.number().int().min(1).max(1024).default(64),\n requestTimeoutMs: z.number().int().min(100).max(60_000).default(10_000),\n})\n\nfunction runtimeSettings(options: PersistentEventPublisherOptions) {\n const deliveryMode = WakeDeliveryModeZod.parse(options.deliveryMode)\n const bestEffort = options.bestEffort === undefined ? undefined : BestEffortDeliveryPolicyZod.parse(options.bestEffort)\n if ((deliveryMode === 'best-effort') !== (bestEffort !== undefined)) throw new TypeError('Explicit delivery mode requires its exact policy')\n return {\n bestEffort,\n deliveryMode,\n deliveryNamespace: deliveryMode === 'best-effort' ? 'best-effort-deliveries' : 'deliveries',\n timing: TimingZod.parse(options),\n }\n}\nexport async function createPersistentEventPublisherRuntime(options: PersistentEventPublisherOptions): Promise<PersistentEventPublisher> {\n const {\n bestEffort, deliveryMode, deliveryNamespace, timing,\n } = runtimeSettings(options)\n if (options.sources.length < 1 || options.sources.length > 16)\n throw new Error('Publisher requires between one and sixteen bounded sources')\n const clock = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const signer = createAccountSourceWakeSigner({\n account: options.account, publisher: options.publisher, nowSeconds: clock,\n })\n const sourceReaders = new Map(options.sources.map(reader => [publisherSourceKey(reader.source), reader]))\n if (sourceReaders.size !== options.sources.length)\n throw new Error('Duplicate publisher source identity')\n const state = options.state\n const existingMode = state.get<string>('metadata', 'runtime-delivery-mode')\n if (existingMode !== undefined && existingMode !== deliveryMode) throw new Error('Publisher state delivery mode mismatch; preserve custody and use an explicitly qualified state binding')\n state.set('metadata', 'runtime-delivery-mode', deliveryMode)\n const abort = new AbortController()\n const seenThisProcess = new Set<string>()\n let running = false\n let ready = false\n let clockHealthy = true\n let passes = 0\n let lastError: string | undefined\n let sourcesHealthy = false\n let stop: Promise<void> | undefined\n const timed = <T>(promise: Promise<T>, signal: AbortSignal) => boundedPublisherOperation(promise, signal, timing.requestTimeoutMs)\n function loadDelivery(subscription: PublisherRuntimeSubscription, now: number): DeliveryState {\n if (subscription.deliveryMode !== deliveryMode || !isDeepStrictEqual(subscription.bestEffort, bestEffort))\n throw new Error('Subscription delivery mode or policy disagrees with runtime')\n if (deliveryMode === 'best-effort' && (subscription.maxPositionsPerWake !== 1 || subscription.serviceHash === undefined)) throw new Error('Best Effort requires point range')\n if (options.serviceHash !== undefined && subscription.serviceHash !== options.serviceHash)\n throw new Error('Subscription does not match the configured exact service descriptor')\n const key = subscription.subscriptionHash\n if (deliveryMode === 'best-effort' && state.get(deliveryNamespace, key) === undefined\n && state.entries(deliveryNamespace).length >= timing.maxSubscriptions) throw new Error('Best Effort state capacity exceeded; live records are not evicted')\n let record = state.get<DeliveryState>(deliveryNamespace, key)\n if (record === undefined) {\n makeEvent(subscription, subscription.fromPosition, subscription.fromPosition, now, '0'.repeat(32))\n if (!Number.isSafeInteger(subscription.maxPositionsPerWake) || subscription.maxPositionsPerWake < 1 || subscription.maxPositionsPerWake > 4096) {\n throw new Error('Invalid source range budget')\n }\n record = {\n subscription, cursor: subscription.fromPosition - 1, delivered: 0, failures: 0, nextAttemptMs: 0, state: 'active',\n }\n state.set(deliveryNamespace, key, record)\n }\n assertDeliveryState(record, subscription)\n return record\n }\n\n function prepareDelivery(record: DeliveryState, now: number, heads: ReadonlyMap<string, PublisherSourceHead | Error>) {\n if (deliveryMode === 'best-effort' && bestEffort !== undefined) {\n const first = !seenThisProcess.has(record.subscription.subscriptionHash)\n const head = heads.get(publisherSourceKey(record.subscription.source))\n if (head !== undefined && !(head instanceof Error) && head.position >= record.subscription.fromPosition)\n seenThisProcess.add(record.subscription.subscriptionHash)\n return prepareBestEffortDelivery({\n bestEffort, first, heads, now, record, state,\n })\n }\n if (record.pending !== undefined) return { ...record, pending: record.pending }\n const subscription = record.subscription\n const head = heads.get(publisherSourceKey(subscription.source))\n if (head === undefined || head instanceof Error) throw new Error('Configured source is unavailable')\n if (head.position <= record.cursor) return\n const fromPosition = record.cursor + 1\n const pending = makeEvent(subscription, fromPosition, Math.min(head.position, fromPosition + subscription.maxPositionsPerWake - 1), now)\n const prepared = { ...record, pending }\n state.transaction(() => {\n const logicalKey = JSON.stringify([subscription.subscriptionHash, pending.fromPosition, pending.toPosition])\n if (!state.insert('delivery-events', logicalKey, pending)) throw new Error('Publisher logical range already exists outside its contiguous cursor')\n state.set(deliveryNamespace, subscription.subscriptionHash, prepared)\n })\n return prepared\n }\n\n async function stillActive(record: DeliveryState, signal: AbortSignal): Promise<boolean> {\n if (await timed(options.discovery.isActive(record.subscription, signal), signal)) return true\n state.set(deliveryNamespace, record.subscription.subscriptionHash, {\n ...record, pending: undefined, state: 'cancelled',\n })\n return false\n }\n\n function acknowledgeBestEffort(record: DeliveryState & { readonly pending: WakeEnvelope }, body: unknown, eventHash: string, signal: AbortSignal, now: number) {\n const { pending, subscription } = record\n const acknowledgment = BestEffortAdmissionAcknowledgmentZod.safeParse(body)\n if (!acknowledgment.success || acknowledgment.data.eventHash !== eventHash || acknowledgment.data.wakeId !== pending.wakeId\n || acknowledgment.data.expiresAt !== pending.issuedAt + (bestEffort?.maxHintAgeSeconds ?? 0) + 60\n || acknowledgment.data.acceptedAt < pending.issuedAt - 60 || acknowledgment.data.acceptedAt > now + 60)\n throw new Error('Publisher did not receive a matching finite acknowledgment')\n signal.throwIfAborted()\n state.set(deliveryNamespace, subscription.subscriptionHash, {\n subscription,\n cursor: pending.toPosition,\n delivered: record.delivered + 1,\n failures: 0,\n attempts: 0,\n superseded: record.superseded ?? 0,\n abandoned: record.abandoned ?? 0,\n totalAttempts: (record.totalAttempts ?? 0) + 1,\n lastNotifiedAt: now,\n lastHintAt: pending.issuedAt,\n lastHintTarget: pending.toPosition,\n nextAttemptMs: 0,\n state: 'active',\n } satisfies DeliveryState)\n }\n\n async function sendDelivery(record: DeliveryState & { readonly pending: WakeEnvelope }, signal: AbortSignal, now: number) {\n const { pending, subscription } = record\n signal.throwIfAborted()\n const signed = await signer.sign(pending, subscription.audience)\n signal.throwIfAborted()\n const attempt = deliveryMode === 'best-effort' ? record.attempts ?? 0 : state.get<{ count: number }>('delivery-attempts', pending.wakeId)?.count ?? 0\n if (deliveryMode === 'best-effort') state.set(deliveryNamespace, subscription.subscriptionHash, {\n ...record, attempts: attempt + 1, totalAttempts: (record.totalAttempts ?? 0) + 1,\n })\n else state.set('delivery-attempts', pending.wakeId, {\n count: attempt + 1, startedAt: now, status: 'in-flight',\n })\n const response = await options.transport.post(subscription.endpoint, signed.event, signal, signed.jwt)\n if (deliveryMode === 'durable') state.set('delivery-attempts', pending.wakeId, {\n count: attempt + 1, startedAt: now, status: response.status,\n })\n if (response.status !== 200 && response.status !== 202) throw new DeliveryResponseError(response.status, response.retryAfterMs)\n if (deliveryMode === 'best-effort') {\n acknowledgeBestEffort(record, response.body, signed.eventHash, signal, now)\n return\n }\n const receipt = z.object({ receiptId: z.string().min(1), wakeId: z.literal(pending.wakeId) }).safeParse(response.body)\n if (!receipt.success) throw new Error('Publisher admission did not return a matching durable receipt')\n signal.throwIfAborted()\n // Receipt, contiguous cursor, and outbox clear commit together. A lost\n // response or death before this transaction reuses the exact pending body.\n state.transaction(() => {\n state.set('delivery-receipts', pending.wakeId, { receiptId: receipt.data.receiptId, receivedAt: now })\n state.set(deliveryNamespace, subscription.subscriptionHash, {\n subscription,\n cursor: pending.toPosition,\n delivered: record.delivered + 1,\n failures: 0,\n nextAttemptMs: 0,\n state: 'active',\n } satisfies DeliveryState)\n })\n }\n\n async function deliver(subscription: PublisherRuntimeSubscription, signal: AbortSignal, now: number, heads: ReadonlyMap<string, PublisherSourceHead | Error>) {\n let record = loadDelivery(subscription, now)\n if (deliveryMode === 'durable' && (record.state !== 'active' || record.nextAttemptMs > now * 1000)) return\n try {\n if (!await stillActive(record, signal)) return\n options.transport.assertAllowed(subscription.endpoint)\n if (!sourceReaders.has(publisherSourceKey(subscription.source))) throw new Error('Subscription source is not configured')\n const prepared = prepareDelivery(record, now, heads)\n if (prepared === undefined) return\n record = prepared\n if (record.nextAttemptMs > now * 1000) return\n // Reconcile once more after observing source progress, before every attempt.\n if (!await stillActive(record, signal)) return\n await sendDelivery(prepared, signal, now)\n } catch (error) {\n if (signal.aborted) return\n state.set(\n deliveryNamespace,\n subscription.subscriptionHash,\n failedDelivery(record, state.get<DeliveryState>(deliveryNamespace, subscription.subscriptionHash), deliveryMode, error, now),\n )\n }\n }\n async function readSources(signal: AbortSignal): Promise<ReadonlyMap<string, PublisherSourceHead | Error>> {\n const heads = new Map<string, PublisherSourceHead | Error>()\n const results = await Promise.allSettled([...sourceReaders].map(async ([key, reader]) => {\n const head = await timed(reader.head(signal), signal)\n if (!Number.isSafeInteger(head.position) || head.position < -1)\n throw new Error('Source head is invalid')\n const previous = state.get<PublisherSourceHead>('source-heads', key)\n if (previous !== undefined && (head.position < previous.position || (head.position === previous.position && head.hash !== previous.hash))) {\n throw new Error('Finalized source regressed or changed hash')\n }\n signal.throwIfAborted()\n state.set('source-heads', key, head)\n heads.set(key, head)\n }))\n sourcesHealthy = results.every(item => item.status === 'fulfilled')\n // All rejections are inspected; delivery sees an unavailable source without\n // exposing provider URLs or allowing one source to deny another service.\n for (const [index, result] of results.entries())\n if (result.status === 'rejected') {\n const key = sourceReaders.keys().toArray()[index]\n if (key !== undefined)\n heads.set(key, new Error('Source read failed'))\n }\n return heads\n }\n async function reconcileDeliveries(subscriptions: readonly PublisherRuntimeSubscription[], signal: AbortSignal) {\n if (subscriptions.length > timing.maxSubscriptions) throw new Error('Publisher subscription limit exceeded')\n const active = new Set(subscriptions.map(subscription => subscription.subscriptionHash))\n if (active.size !== subscriptions.length) throw new Error('Duplicate subscription identity')\n const unavailable = state.entries<DeliveryState>(deliveryNamespace).filter(item => !active.has(item.key) && item.value.state !== 'cancelled')\n let available = true\n for (let offset = 0; offset < unavailable.length; offset += timing.concurrency) {\n signal.throwIfAborted()\n const results = await Promise.allSettled(unavailable.slice(offset, offset + timing.concurrency).map(async ({ key, value }) => {\n const stillAuthorized = await timed(options.discovery.isActive(value.subscription, signal), signal)\n if (!stillAuthorized) state.set(deliveryNamespace, key, {\n ...value, pending: undefined, state: 'cancelled',\n })\n return stillAuthorized\n }))\n // Local key loss, endpoint policy, or a failed replay cannot revoke a\n // finalized subscription. Preserve its exact pending body for restoration.\n available = available && results.every(result => result.status === 'fulfilled' && !result.value)\n }\n return available\n }\n\n async function tick(actorSignal: AbortSignal) {\n const scope = publisherAbortScope([abort.signal, actorSignal])\n const signal = scope.signal\n try {\n signal.throwIfAborted()\n const now = clock()\n const prior = state.get<number>('runtime', 'highest-wall-clock') ?? 0\n clockHealthy = Number.isSafeInteger(now) && now >= prior\n if (!clockHealthy)\n throw new Error('Publisher clock moved backwards')\n state.set('runtime', 'highest-wall-clock', now)\n const subscriptions = await timed(options.discovery.discover(signal), signal)\n const subscriptionsAvailable = await reconcileDeliveries(subscriptions, signal)\n const heads = await readSources(signal)\n for (let offset = 0; offset < subscriptions.length; offset += timing.concurrency) {\n signal.throwIfAborted()\n const outcomes = await Promise.allSettled(subscriptions.slice(offset, offset + timing.concurrency).map(subscription => deliver(subscription, signal, now, heads)))\n const failed = outcomes.find(result => result.status === 'rejected')\n if (failed?.status === 'rejected')\n throw failed.reason\n }\n // Challenge/finality work is bounded and occurs after already-active\n // subscribers, so a new or broken subscriber cannot starve delivery.\n if (options.discovery.acceptPending !== undefined)\n await timed(options.discovery.acceptPending(signal), signal)\n const discoveryStatus = options.discovery.status?.()\n ready = subscriptionsAvailable && sourcesHealthy && activationReady(discoveryStatus)\n lastError = subscriptionsAvailable ? undefined : 'publisher-subscription-unavailable'\n passes += 1\n } catch (error) {\n ready = false\n lastError = clockHealthy ? 'publisher-pass-failed' : 'publisher-clock-unhealthy'\n if (!signal.aborted)\n throw error\n } finally {\n scope.dispose()\n }\n }\n const actor = await PublisherRuntimeActor.create({\n locator: createMemoryLocator({}), intervalMs: timing.intervalMs, firstRun: 'immediate', readiness: 'immediate', tick,\n })\n return {\n async start() {\n if (stop !== undefined)\n throw new Error('Publisher is stopped')\n if (running) {\n return\n }\n\n await actor.start()\n running = true\n },\n async runOnce() {\n if (stop !== undefined)\n throw new Error('Publisher is stopped')\n await actor.runOnce()\n },\n stop: () => stop ??= (async () => {\n abort.abort()\n const failures: unknown[] = []\n try {\n await actor.stop()\n } catch (error) {\n failures.push(error)\n }\n try {\n await options.discovery.close?.()\n } catch (error) {\n failures.push(error)\n }\n for (const source of options.sources)\n try {\n await source.close?.()\n } catch (error) {\n failures.push(error)\n }\n running = false\n ready = false\n if (failures.length > 0)\n throw new AggregateError(failures, 'Publisher runtime shutdown failed')\n })(),\n status() {\n const deliveries = state.entries<DeliveryState>(deliveryNamespace).map(item => item.value)\n return {\n running,\n deliveryMode,\n ...(bestEffort === undefined ? {} : { bestEffort: Object.freeze({ ...bestEffort }) }),\n superseded: deliveries.reduce((sum, item) => sum + (item.superseded ?? 0), 0),\n abandoned: deliveries.reduce((sum, item) => sum + (item.abandoned ?? 0), 0),\n totalAttempts: deliveries.reduce((sum, item) => sum + (item.totalAttempts ?? 0), 0),\n ready: running && ready,\n clockHealthy,\n degraded: !ready || deliveries.some(item => item.state !== 'cancelled' && item.failures > 0),\n publisher: options.publisher,\n activeSubscriptions: deliveries.filter(item => item.state === 'active').length,\n pendingDeliveries: deliveries.filter(item => item.pending !== undefined).length,\n delivered: deliveries.reduce((sum, item) => sum + item.delivered, 0),\n failures: deliveries.reduce((sum, item) => sum + item.failures, 0),\n passes,\n ...(lastError === undefined ? {} : { lastError }),\n ...(options.discovery.status === undefined ? {} : { handshake: options.discovery.status() }),\n sources: state.entries<PublisherSourceHead>('source-heads').filter(item => sourceReaders.has(item.key)).map(item => ({ id: item.key, ...item.value })),\n subscriptions: state.entries<DeliveryState>(deliveryNamespace).map(item => ({\n id: item.key,\n cursor: item.value.cursor,\n ...(deliveryMode === 'best-effort'\n ? {\n ...(item.value.cursor < item.value.subscription.fromPosition ? {} : { lastAdmissionTarget: item.value.cursor }),\n attempts: item.value.attempts ?? 0,\n lastHintAt: item.value.lastHintAt,\n }\n : {}),\n state: item.value.state,\n pending: item.value.pending !== undefined,\n failures: item.value.failures,\n })),\n }\n },\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { BestEffortDeliveryPolicy, WakeEnvelope } from '@xyo-network/event-kit-schemas'\nimport { WakeEnvelopeSchema, WakeEnvelopeZod } from '@xyo-network/event-kit-schemas'\n\nimport type { PublisherRuntimeSubscription } from './publisherRuntime.ts'\nimport type { PublisherSourceHead } from './sources.ts'\nimport { publisherSourceKey } from './sources.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\n\nexport interface DeliveryState {\n readonly abandoned?: number\n readonly attempts?: number\n readonly cursor: number\n readonly delivered: number\n readonly failures: number\n readonly lastError?: string\n readonly lastHintAt?: number\n readonly lastHintTarget?: number\n readonly lastNotifiedAt?: number\n readonly nextAttemptMs: number\n readonly pending?: WakeEnvelope\n readonly state: 'active' | 'blocked' | 'cancelled'\n readonly subscription: PublisherRuntimeSubscription\n readonly superseded?: number\n readonly totalAttempts?: number\n}\nexport function assertDeliveryState(record: DeliveryState, subscription: PublisherRuntimeSubscription): void {\n if (!isDeepStrictEqual(record.subscription, subscription))\n throw new Error('Subscription revision changed without a new identity')\n if (!Number.isSafeInteger(record.cursor) || record.cursor < subscription.fromPosition - 1\n || [record.delivered, record.failures, record.nextAttemptMs].some(value => !(Number.isSafeInteger(value) && value >= 0))\n || [record.attempts, record.superseded, record.abandoned, record.totalAttempts, record.lastHintAt, record.lastNotifiedAt, record.lastHintTarget]\n .some(value => value !== undefined && !(Number.isSafeInteger(value) && value >= 0))\n || !['active', 'blocked', 'cancelled'].includes(record.state))\n throw new Error('Persisted publisher delivery state is invalid')\n if (record.pending === undefined) return\n const pending = WakeEnvelopeZod.parse(record.pending)\n if ((subscription.deliveryMode === 'durable' && pending.fromPosition !== record.cursor + 1)\n || pending.deliveryMode !== subscription.deliveryMode || pending.toPosition - pending.fromPosition + 1 > subscription.maxPositionsPerWake\n || pending.authorizationChainId !== subscription.authorizationChainId || pending.deploymentId !== subscription.deploymentId\n || pending.queueId !== subscription.queueId || pending.filterHash !== subscription.filterHash\n || !isDeepStrictEqual(pending.source, subscription.source))\n throw new Error('Persisted publisher outbox binding is invalid')\n}\nexport function makeEvent(subscription: PublisherRuntimeSubscription, fromPosition: number, toPosition: number, now: number, wakeId = randomBytes(16).toString('hex')) {\n return WakeEnvelopeZod.parse({\n schema: WakeEnvelopeSchema,\n authorizationChainId: subscription.authorizationChainId,\n deliveryMode: subscription.deliveryMode,\n deploymentId: subscription.deploymentId,\n filterHash: subscription.filterHash,\n fromPosition,\n issuedAt: now,\n source: subscription.source,\n toPosition,\n wakeId,\n ...(subscription.queueId === undefined ? {} : { queueId: subscription.queueId }),\n })\n}\n\nexport class DeliveryResponseError extends Error {\n readonly retryAfterMs?: number\n readonly status: number\n constructor(status: number, retryAfterMs?: number) {\n super('Publisher admission failed')\n this.status = status\n this.retryAfterMs = retryAfterMs\n }\n\n get retryable() {\n return this.status === 408 || this.status === 429 || this.status >= 500\n }\n}\n\nexport function prepareBestEffortDelivery(options: {\n readonly bestEffort: BestEffortDeliveryPolicy\n readonly first: boolean\n readonly heads: ReadonlyMap<string, PublisherSourceHead | Error>\n readonly now: number\n readonly record: DeliveryState\n readonly state: SqlitePublisherState\n}) {\n const {\n bestEffort, first, heads, now, record, state,\n } = options\n const subscription = record.subscription\n const head = heads.get(publisherSourceKey(subscription.source))\n const prior = record.pending\n const expired = isHintExpired(record, now, bestEffort)\n if (head === undefined || head instanceof Error || head.position < subscription.fromPosition) {\n if (prior !== undefined && !expired) return { ...record, pending: prior }\n if (prior !== undefined) state.set('best-effort-deliveries', subscription.subscriptionHash, {\n ...record, pending: undefined, abandoned: (record.abandoned ?? 0) + 1,\n })\n return\n }\n const refresh = refreshDue(record, now, bestEffort)\n if (freshHintRequired(record, head.position, first, refresh, expired)) {\n const pending = makeEvent(subscription, head.position, head.position, now)\n const prepared = {\n ...record,\n pending,\n attempts: 0,\n lastHintAt: now,\n lastHintTarget: head.position,\n superseded: (record.superseded ?? 0) + (prior !== undefined && !expired ? 1 : 0),\n abandoned: (record.abandoned ?? 0) + (expired ? 1 : 0),\n nextAttemptMs: 0,\n state: 'active' as const,\n }\n state.set('best-effort-deliveries', subscription.subscriptionHash, prepared)\n return prepared\n }\n if (expired) state.set('best-effort-deliveries', subscription.subscriptionHash, {\n ...record, pending: undefined, abandoned: (record.abandoned ?? 0) + 1,\n })\n return prior === undefined || expired ? undefined : { ...record, pending: prior }\n}\n\nfunction isHintExpired(record: DeliveryState, now: number, policy: BestEffortDeliveryPolicy): boolean {\n return record.pending !== undefined && (now > record.pending.issuedAt + policy.maxHintAgeSeconds || (record.attempts ?? 0) >= policy.maxAttempts)\n}\nfunction refreshDue(record: DeliveryState, now: number, policy: BestEffortDeliveryPolicy): boolean {\n return now - (record.lastHintAt ?? record.lastNotifiedAt ?? 0) >= policy.refreshIntervalSeconds\n}\nfunction freshHintRequired(record: DeliveryState, head: number, first: boolean, refresh: boolean, expired: boolean): boolean {\n return first || head > (record.pending?.toPosition ?? record.lastHintTarget ?? record.cursor) || (refresh && (record.pending === undefined || expired))\n}\nexport function failedDelivery(record: DeliveryState, current: DeliveryState | undefined, mode: string, error: unknown, now: number): DeliveryState {\n const bestEffort = mode === 'best-effort'\n const wait = error instanceof DeliveryResponseError && error.retryAfterMs !== undefined\n ? error.retryAfterMs\n : Math.min(300_000, 1000 * (2 ** Math.min(record.failures, 8)))\n return {\n ...record,\n failures: record.failures + 1,\n totalAttempts: bestEffort ? current?.totalAttempts ?? record.totalAttempts ?? 0 : record.totalAttempts,\n attempts: bestEffort ? current?.attempts ?? record.attempts ?? 0 : record.attempts,\n state: !bestEffort && error instanceof DeliveryResponseError && !error.retryable ? 'blocked' : 'active',\n nextAttemptMs: now * 1000 + Math.min(3_600_000, wait),\n lastError: 'delivery-failed',\n }\n}\n", "import { randomBytes } from 'node:crypto'\n\nimport type { WakeEnvelope } from '@xyo-network/event-kit-schemas'\nimport {\n NormalizedAddressZod, WakeEnvelopeZod, WakeJwtSchema,\n} from '@xyo-network/event-kit-schemas'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport { PayloadBuilder } from '@xyo-network/sdk'\n/** The wallet-JWT profile commits to the complete strict source-aware body. */\nexport function createAccountSourceWakeSigner(options: {\n readonly account: AccountInstance\n readonly nowSeconds?: () => number\n readonly publisher: string\n}) {\n const publisher = NormalizedAddressZod.parse(options.publisher)\n if (String(options.account.address).replace(/^0x/u, '').toLowerCase() !== publisher)\n throw new Error('Publisher signing account mismatch')\n return {\n async sign(input: WakeEnvelope, audience: string) {\n const event = WakeEnvelopeZod.parse(input)\n const eventHash = await PayloadBuilder.dataHash(event)\n const now = options.nowSeconds?.() ?? Math.floor(Date.now() / 1000)\n if (!Number.isSafeInteger(now) || now < 0)\n throw new Error('Publisher signing clock is invalid')\n const { token: jwt } = await options.account.signJwt({\n audience,\n claims: { eventHash, jti: randomBytes(16).toString('hex') },\n now,\n schema: WakeJwtSchema,\n ttl: 60,\n })\n return {\n event, eventHash, jwt, publisher,\n }\n },\n }\n}\n", "import { FetchJsonClient } from '@ariestools/sdk'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport type {\n GatewaySession, XyoGateway, XyoGatewayRunner,\n} from '@xyo-network/xl1-sdk'\nimport {\n baseConfigFactoryLocator, basicRestRunnerLocator, basicRestViewerLocator, creatableProvider,\n releaseProviderFactoryLocator, RestDataLakeRunner, RestDataLakeViewer, XyoGatewayMoniker, XyoGatewayRunnerMoniker,\n} from '@xyo-network/xl1-sdk'\nexport interface PublisherRestGatewayOptions {\n readonly chainStateUrl: string\n readonly fetchFn: typeof globalThis.fetch\n readonly finalizedUrl: string\n readonly indexUrl?: string\n readonly rpcUrl: string\n}\n/** Owned public SDK REST gateway; only the optional mutation runner uses RPC. */\nexport function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account: AccountInstance\n}): Promise<GatewaySession<XyoGatewayRunner>>\nexport function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account?: undefined\n}): Promise<GatewaySession<XyoGateway>>\nexport async function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account?: AccountInstance\n}): Promise<GatewaySession<XyoGateway | XyoGatewayRunner>> {\n const rest = {\n finalized: { type: 'rest' as const, baseUrl: options.finalizedUrl },\n chainState: { type: 'rest' as const, baseUrl: options.chainStateUrl },\n index: { type: 'rest' as const, baseUrl: options.indexUrl ?? options.finalizedUrl },\n }\n const locator = options.account === undefined\n ? await basicRestViewerLocator('event-kit-publisher-read', rest, undefined, { fetchFn: options.fetchFn, primeCaches: 'off' })\n : await basicRestRunnerLocator('event-kit-publisher-write', rest, undefined, {\n fetchFn: options.fetchFn, primeCaches: 'off', rpcUrl: options.rpcUrl, signerAccount: options.account,\n })\n try {\n const gateway = options.account === undefined\n ? await locator.getInstance<XyoGateway>(XyoGatewayMoniker)\n : await locator.getInstance<XyoGatewayRunner>(XyoGatewayRunnerMoniker)\n let stopping: Promise<void> | undefined\n return Object.freeze({ gateway, stop: () => stopping ??= releaseProviderFactoryLocator(locator) })\n } catch (error) {\n await releaseProviderFactoryLocator(locator)\n throw error\n }\n}\n@creatableProvider()\nclass BoundedRestDataLakeViewer extends RestDataLakeViewer {\n override get client() {\n if (this.context.fetchFn === undefined)\n throw new Error('Publisher datalake requires its bounded fetch transport')\n return new FetchJsonClient({ fetcher: this.context.fetchFn })\n }\n}\n@creatableProvider()\nclass BoundedRestDataLakeRunner extends RestDataLakeRunner {\n override get client() {\n if (this.context.fetchFn === undefined)\n throw new Error('Publisher datalake requires its bounded fetch transport')\n return new FetchJsonClient({ fetcher: this.context.fetchFn })\n }\n}\n/** Keeps SDK datalake methods and response semantics, overriding only its per-instance HTTP client. */\nexport async function openPublisherDataLake(options: {\n readonly fetchFn: typeof globalThis.fetch\n readonly url: string\n readonly writable: boolean\n}) {\n const locator = await baseConfigFactoryLocator({\n connections: { 'event-kit-lake': { type: 'rest', baseUrl: options.url } },\n providerBindings: { DataLakeViewer: { connection: 'event-kit-lake' }, DataLakeRunner: { connection: 'event-kit-lake' } },\n })\n locator.context.fetchFn = options.fetchFn\n locator.register(BoundedRestDataLakeViewer.factory<BoundedRestDataLakeViewer>(BoundedRestDataLakeViewer.dependencies))\n if (options.writable)\n locator.register(BoundedRestDataLakeRunner.factory<BoundedRestDataLakeRunner>(BoundedRestDataLakeRunner.dependencies))\n locator.freeze()\n try {\n const reader = await locator.getInstance<BoundedRestDataLakeViewer>(BoundedRestDataLakeViewer.defaultMoniker)\n const writer = options.writable ? await locator.getInstance<BoundedRestDataLakeRunner>(BoundedRestDataLakeRunner.defaultMoniker) : undefined\n return {\n reader, writer, async close() { await releaseProviderFactoryLocator(locator) },\n }\n } catch (error) {\n await releaseProviderFactoryLocator(locator)\n throw error\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport type { PublisherEndpointChallengeRecord, PublisherEndpointChallengeStore } from '@xyo-network/event-kit-protocol'\nimport { endpointChallengeHash } from '@xyo-network/event-kit-protocol'\nimport {\n Base64Url32BytesZod, EndpointChallengeZod, HandshakeIdZod, HashZod, NormalizedAddressZod,\n} from '@xyo-network/event-kit-schemas'\nimport type { EventKitReplayCheckpointStore } from '@xyo-network/event-kit-statement-graph'\nimport type {\n FinalizedStatementPublicationIntent, FinalizedStatementPublicationJournal, FinalizedStatementPublicationRecord,\n} from '@xyo-network/event-kit-xl1'\nimport { z } from 'zod'\n\nimport type { PublisherEncryptionKeyCustody } from '../handshakeClients.ts'\nimport type { HandshakeMutationIntent, HandshakeMutationIntentStore } from '../handshakeMutationIntent.ts'\nimport {\n assertSameIntentBinding, intentLookupKey, parseHandshakeMutationIntent,\n} from '../handshakeMutationIntent.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\n\nconst KeyZod = z.strictObject({\n encryptionKey: HashZod, keyId: HandshakeIdZod, privateKey: Base64Url32BytesZod, publisher: NormalizedAddressZod,\n})\nconst phases = ['signed', 'content-written', 'content-verified', 'broadcast', 'included', 'finalized'] as const\n\nfunction requireTime(value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new Error('Publisher clock is invalid')\n}\n\nfunction samePublicationIntent(left: FinalizedStatementPublicationIntent, right: FinalizedStatementPublicationIntent): boolean {\n return left.chainId === right.chainId && left.source === right.source && left.operationId === right.operationId\n && isDeepStrictEqual(left.eventHashes, right.eventHashes) && isDeepStrictEqual(left.attachmentHashes, right.attachmentHashes)\n}\n\nfunction publicationKey(intent: FinalizedStatementPublicationIntent): string {\n if (!/^[0-9a-f]{40}$/u.test(intent.chainId) || !/^[0-9a-f]{40}$/u.test(intent.source)\n || intent.operationId.length === 0 || intent.operationId.length > 256\n || [...intent.eventHashes, ...intent.attachmentHashes].some(hash => !HashZod.safeParse(hash).success)) {\n throw new Error('Invalid publication intent')\n }\n return JSON.stringify([intent.chainId, intent.source, intent.operationId])\n}\n\n/** All handshake durability uses the same single-owner SQLite authority as delivery. */\nexport function createSqlitePublisherHandshakeStores(state: SqlitePublisherState, options: { readonly replayNamespace?: string } = {}): {\n readonly challenges: PublisherEndpointChallengeStore\n readonly intents: HandshakeMutationIntentStore\n readonly journal: FinalizedStatementPublicationJournal\n readonly keys: PublisherEncryptionKeyCustody\n readonly replay: EventKitReplayCheckpointStore\n} {\n const replayKey = options.replayNamespace === undefined ? 'checkpoint' : `checkpoint:${z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/u).parse(options.replayNamespace)}`\n const replay: EventKitReplayCheckpointStore = {\n load: async () => state.get('replay', replayKey),\n async save(checkpoint) { state.set('replay', replayKey, checkpoint) },\n }\n const intents: HandshakeMutationIntentStore = {\n async get(lookup) {\n const value = state.get('intents', intentLookupKey(lookup))\n return value === undefined ? undefined : await parseHandshakeMutationIntent(value)\n },\n async getOrCreate(raw) {\n const proposed = await parseHandshakeMutationIntent(raw) as typeof raw\n return state.transaction(() => {\n const key = intentLookupKey(proposed)\n const winner = state.get<HandshakeMutationIntent>('intents', key)\n if (winner !== undefined) {\n assertSameIntentBinding(winner, proposed)\n return { disposition: 'resumed' as const, intent: winner as typeof raw }\n }\n state.set('intents', key, proposed)\n return { disposition: 'created' as const, intent: proposed }\n })\n },\n }\n const keys: PublisherEncryptionKeyCustody = {\n async getPrivateKey(input) {\n const key = `${NormalizedAddressZod.parse(input.publisher)}:${HandshakeIdZod.parse(input.keyId)}`\n const raw = state.get('encryption-keys', key)\n if (raw === undefined) return\n const record = KeyZod.parse(raw)\n if (record.encryptionKey !== HashZod.parse(input.encryptionKey)) throw new Error('Encryption key identity mismatch')\n const { publisher: _publisher, ...privateKey } = record\n return privateKey\n },\n async putPrivateKey(input) {\n const record = KeyZod.parse({ ...input.key, publisher: input.publisher })\n return state.transaction(() => {\n const key = `${record.publisher}:${record.keyId}`\n const prior = state.get('encryption-keys', key)\n if (prior !== undefined) {\n if (!isDeepStrictEqual(prior, record)) throw new Error('Encryption key collision')\n return 'duplicate'\n }\n state.set('encryption-keys', key, record)\n return 'stored'\n })\n },\n }\n const current = (hash: string) => state.get<PublisherEndpointChallengeRecord>('challenges', HashZod.parse(hash))\n const live = (record: PublisherEndpointChallengeRecord, now: number) => record.challenge.issuedAt <= now && now < record.challenge.expiresAt\n const challenges: PublisherEndpointChallengeStore = {\n get: async hash => current(hash),\n async issue(input) {\n const challenge = EndpointChallengeZod.parse(input.challenge)\n const hash = HashZod.parse(input.challengeHash)\n if (await endpointChallengeHash(challenge) !== hash) return { kind: 'collision' }\n return state.transaction(() => {\n const priorNonce = state.get<string>('challenge-nonces', challenge.nonce)\n if (priorNonce !== undefined && priorNonce !== hash) return { kind: 'collision' as const }\n const prior = current(hash)\n if (prior !== undefined) return isDeepStrictEqual(prior.challenge, challenge)\n ? { kind: 'duplicate' as const, record: prior }\n : { kind: 'collision' as const }\n const record: PublisherEndpointChallengeRecord = {\n challenge, challengeHash: hash, state: 'issued',\n }\n state.set('challenge-nonces', challenge.nonce, hash)\n state.set('challenges', hash, record)\n return { kind: 'issued' as const, record }\n })\n },\n async beginAttempt(input) {\n requireTime(input.nowSeconds)\n return state.transaction(() => {\n const record = current(input.challengeHash)\n if (record === undefined) return { kind: 'missing' as const }\n if (record.state === 'verified') return { kind: 'verified' as const, record }\n if (record.state === 'attempted') return { kind: 'already-attempted' as const, record }\n if (!live(record, input.nowSeconds)) return { kind: 'expired' as const, record }\n const attempted: PublisherEndpointChallengeRecord = { ...record, state: 'attempted' }\n state.set('challenges', input.challengeHash, attempted)\n return { kind: 'started' as const, record: attempted }\n })\n },\n async completeVerified(input) {\n requireTime(input.nowSeconds)\n const responseHash = HashZod.parse(input.responseHash)\n return state.transaction(() => {\n const record = current(input.challengeHash)\n if (record === undefined) return { kind: 'missing' as const }\n if (record.state === 'verified') return { kind: record.responseHash === responseHash ? 'duplicate' as const : 'collision' as const, record }\n if (record.state !== 'attempted') return { kind: 'not-attempted' as const, record }\n if (!live(record, input.nowSeconds)) return { kind: 'expired' as const, record }\n const verified: PublisherEndpointChallengeRecord = {\n ...record, responseHash, state: 'verified',\n }\n state.set('challenges', input.challengeHash, verified)\n return { kind: 'verified' as const, record: verified }\n })\n },\n }\n const journal: FinalizedStatementPublicationJournal = {\n async load(intent) {\n const key = publicationKey(intent)\n const signed = state.get<FinalizedStatementPublicationRecord>('publication:signed', key)\n if (signed === undefined) return\n if (!samePublicationIntent(signed, intent)) throw new Error('Publication intent collision')\n let latest = signed\n for (const phase of phases) {\n const record = state.get<FinalizedStatementPublicationRecord>(`publication:${phase}`, key)\n if (record === undefined) continue\n if (record.phase !== phase || !samePublicationIntent(record, intent) || !isDeepStrictEqual(record.evidence, signed.evidence)) {\n throw new Error('Publication evidence collision')\n }\n latest = record\n }\n return latest\n },\n async save(record) {\n const key = publicationKey(record)\n HashZod.parse(record.evidence.transactionHash)\n if (!phases.includes(record.phase)) throw new Error('Unknown publication phase')\n state.transaction(() => {\n const signed = state.get<FinalizedStatementPublicationRecord>('publication:signed', key)\n if (signed === undefined && record.phase !== 'signed') throw new Error('Publication must bind signed evidence first')\n if (signed !== undefined && (!samePublicationIntent(signed, record) || !isDeepStrictEqual(signed.evidence, record.evidence))) {\n throw new Error('Publication intent or evidence collision')\n }\n const namespace = `publication:${record.phase}`\n const prior = state.get(namespace, key)\n if (prior !== undefined && !isDeepStrictEqual(prior, record)) throw new Error('Publication phase collision')\n if (prior === undefined) state.set(namespace, key, record)\n })\n },\n }\n return {\n challenges, intents, journal, keys, replay,\n }\n}\n", "import {\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 { randomBytes } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport {\n lstat, mkdir, open,\n} from 'node:fs/promises'\nimport { hostname } from 'node:os'\nimport PATH from 'node:path'\n\nimport { stringifyJson } from '../filesystemJson.ts'\nexport interface SqlitePublisherStateOptions {\n /** Immutable chain/publisher binding. A database must never silently change owners. */\n readonly identity: string\n readonly path: string\n}\ninterface JsonRow {\n readonly value: string\n}\ninterface OwnerRow {\n readonly host: string\n readonly pid: number\n readonly token: string\n}\n/** Single-process SQLite authority for publisher checkpoints, custody and delivery records. */\nexport interface SqlitePublisherState {\n readonly path: string\n close(): void\n entries<T>(namespace: string): readonly {\n readonly key: string\n readonly value: T\n }[]\n get<T>(namespace: string, key: string): T | undefined\n insert(namespace: string, key: string, value: unknown): boolean\n remove(namespace: string, key: string): void\n set(namespace: string, key: string, value: unknown): void\n transaction<T>(work: () => T): T\n}\nfunction decode<T>(value: string): T {\n return JSON.parse(value, (_key, candidate: unknown) => {\n return typeof candidate === 'object' && candidate !== null && Object.keys(candidate).length === 1\n && '$eventKitBigInt' in candidate && typeof candidate.$eventKitBigInt === 'string'\n && /^(?:0|[1-9][0-9]*)$/u.test(candidate.$eventKitBigInt)\n ? BigInt(candidate.$eventKitBigInt)\n : candidate\n }) as T\n}\nfunction processExists(pid: number): boolean {\n if (!Number.isSafeInteger(pid) || pid < 1)\n throw new Error('Invalid publisher owner record')\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ESRCH')\n return false\n return true\n }\n}\nexport async function openSqlitePublisherState(options: SqlitePublisherStateOptions): Promise<SqlitePublisherState> {\n if (options.path === ':memory:' || options.identity.length === 0)\n throw new Error('Persistent publisher needs a file and an identity')\n const path = PATH.resolve(options.path)\n const directory = PATH.dirname(path)\n await mkdir(directory, { recursive: true, mode: 0o700 })\n const metadata = await lstat(directory)\n if (!metadata.isDirectory() || (metadata.mode & 0o077) !== 0)\n throw new Error('Publisher state directory must be a real directory with 0700 permissions')\n const file = await open(path, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW, 0o600)\n try {\n const metadata = await file.stat()\n if (!metadata.isFile() || (metadata.mode & 0o077) !== 0)\n throw new Error('Publisher database permissions must be 0600')\n await file.sync()\n } finally {\n await file.close()\n }\n const { DatabaseSync } = await import('node:sqlite')\n const database = new DatabaseSync(path)\n const token = randomBytes(16).toString('hex')\n let closed = false\n let inTransaction = false\n const transaction = <T>(work: () => T): T => {\n if (closed)\n throw new Error('Publisher state is closed')\n if (inTransaction)\n return work()\n database.exec('BEGIN IMMEDIATE')\n inTransaction = true\n try {\n const result = work()\n if (result instanceof Promise)\n throw new Error('Publisher state transactions must be synchronous')\n database.exec('COMMIT')\n return result\n } catch (error) {\n database.exec('ROLLBACK')\n throw error\n } finally {\n inTransaction = false\n }\n }\n try {\n database.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = FULL;\n PRAGMA busy_timeout = 5000;\n CREATE TABLE IF NOT EXISTS publisher_records (namespace TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY(namespace, key));\n CREATE TABLE IF NOT EXISTS publisher_owner (id INTEGER PRIMARY KEY CHECK(id = 1), host TEXT NOT NULL, pid INTEGER NOT NULL, token TEXT NOT NULL);\n `)\n transaction(() => {\n const prior = database.prepare('SELECT host, pid, token FROM publisher_owner WHERE id = 1').get() as OwnerRow | undefined\n if (prior !== undefined && (prior.host !== hostname() || processExists(prior.pid))) {\n throw new Error('Publisher database already has an active owner; a shared or multi-host database is not supported')\n }\n const binding = database.prepare('SELECT value FROM publisher_records WHERE namespace = ? AND key = ?').get('metadata', 'identity') as JsonRow | undefined\n if (binding !== undefined && decode(binding.value) !== options.identity)\n throw new Error('Publisher database identity mismatch')\n database.prepare('INSERT OR IGNORE INTO publisher_records(namespace,key,value) VALUES (?,?,?)').run('metadata', 'identity', stringifyJson(options.identity))\n database.prepare('INSERT OR REPLACE INTO publisher_owner(id,host,pid,token) VALUES (1,?,?,?)').run(hostname(), process.pid, token)\n })\n } catch (error) {\n database.close()\n throw error\n }\n const read = database.prepare('SELECT value FROM publisher_records WHERE namespace = ? AND key = ?')\n const list = database.prepare('SELECT key, value FROM publisher_records WHERE namespace = ? ORDER BY key')\n const write = database.prepare('INSERT INTO publisher_records(namespace,key,value) VALUES (?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET value = excluded.value')\n const insert = database.prepare('INSERT OR IGNORE INTO publisher_records(namespace,key,value) VALUES (?,?,?)')\n const remove = database.prepare('DELETE FROM publisher_records WHERE namespace = ? AND key = ?')\n const assertOpen = () => {\n if (closed)\n throw new Error('Publisher state is closed')\n }\n return {\n path,\n get<T>(namespace: string, key: string): T | undefined {\n assertOpen()\n const row = read.get(namespace, key) as JsonRow | undefined\n return row === undefined ? undefined : decode<T>(row.value)\n },\n entries<T>(namespace: string) {\n assertOpen()\n return (list.all(namespace) as {\n key: string\n value: string\n }[]).map(row => ({ key: row.key, value: decode<T>(row.value) }))\n },\n set(namespace, key, value) {\n assertOpen()\n write.run(namespace, key, stringifyJson(value))\n },\n insert(namespace, key, value) {\n assertOpen()\n return insert.run(namespace, key, stringifyJson(value)).changes === 1\n },\n remove(namespace, key) {\n assertOpen()\n remove.run(namespace, key)\n },\n transaction,\n close() {\n if (closed)\n return\n transaction(() => {\n database.prepare('DELETE FROM publisher_owner WHERE id = 1 AND token = ?').run(token)\n })\n database.close()\n closed = true\n },\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport {\n link, open, rename, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport {\n ensureDurableDirectory,\n syncDirectory,\n writeDurableFile,\n} from './filesystemDurability.ts'\n\nexport interface FilesystemJsonWriteOptions {\n readonly directoryMode?: number\n readonly mode?: number\n}\n\nexport async function readJsonFileStrict(path: string): Promise<unknown> {\n let handle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return undefined\n throw error\n }\n try {\n return JSON.parse(await handle.readFile('utf8'), reviveJson) as unknown\n } finally { await handle.close() }\n}\n\n/** Atomically replaces one JSON file after its new bytes have reached disk. */\nexport async function replaceJsonFile(\n path: string,\n value: unknown,\n options: FilesystemJsonWriteOptions = {},\n): Promise<void> {\n const directory = PATH.dirname(path)\n await ensureDurableDirectory(directory, options.directoryMode)\n const tempPath = PATH.join(directory, `.${PATH.basename(path)}.${process.pid}.${suffix()}.tmp`)\n try {\n await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n await rename(tempPath, path)\n await syncDirectory(directory)\n } catch (error) {\n await unlinkIfMissing(tempPath)\n throw error\n }\n}\n\n/**\n * Publishes immutable JSON with an exclusive hard link. Returns `false` when\n * another process already owns the destination.\n */\nexport async function publishJsonFile(\n path: string,\n value: unknown,\n options: FilesystemJsonWriteOptions = {},\n): Promise<boolean> {\n const directory = PATH.dirname(path)\n await ensureDurableDirectory(directory, options.directoryMode)\n const tempPath = PATH.join(directory, `.${PATH.basename(path)}.${process.pid}.${suffix()}.tmp`)\n try {\n await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n await link(tempPath, path)\n await syncDirectory(directory)\n return true\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw error\n } finally {\n await unlinkIfMissing(tempPath)\n }\n}\n\nfunction suffix(): string {\n return randomBytes(8).toString('hex')\n}\n\nexport function stringifyJson(value: unknown): string {\n return JSON.stringify(value, replaceJsonValue)\n}\n\nfunction replaceJsonValue(_key: string, candidate: unknown): unknown {\n return typeof candidate === 'bigint'\n ? { $eventKitBigInt: candidate.toString() }\n : candidate\n}\n\nfunction reviveJson(_key: string, candidate: unknown): unknown {\n return typeof candidate === 'object'\n && candidate !== null\n && Object.keys(candidate).length === 1\n && '$eventKitBigInt' in candidate\n && typeof candidate.$eventKitBigInt === 'string'\n && /^(?:0|[1-9][0-9]*)$/u.test(candidate.$eventKitBigInt)\n ? BigInt(candidate.$eventKitBigInt)\n : candidate\n}\n\nasync function unlinkIfMissing(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') throw error\n }\n}\n\nfunction errorCode(error: unknown): unknown {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as { code?: unknown }).code\n : undefined\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;AAAA,SAAS,UAAAA,eAAc;;;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I;AACF;AACF,kBAAY,MAAM;AAChB,iBAAS,QAAQ,wDAAwD,EAAE,IAAI,KAAK;AAAA,MACtF,CAAC;AACD,eAAS,MAAM;AACf,eAAS;AAAA,IACX;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["import { Buffer } from 'node:buffer'\n\nimport type { FetchGetUrlFunc } from 'ethers'\n\nimport { publisherAbortScope } from './abort.ts'\nexport interface BoundedPublisherFetchOptions {\n readonly maxConcurrency?: number\n readonly maxResponseBytes?: number\n readonly requestTimeoutMs?: number\n readonly signal?: AbortSignal\n}\n/** Per-instance SDK transport: aborts the real request, including its body, without changing global fetch. */\nexport function createBoundedPublisherFetch(options: BoundedPublisherFetchOptions = {}) {\n const owner = new AbortController()\n const timeout = options.requestTimeoutMs ?? 10_000\n const maximum = options.maxResponseBytes ?? 16 * 1024 * 1024\n const concurrency = options.maxConcurrency ?? 16\n if (!Number.isSafeInteger(timeout) || timeout < 100 || timeout > 60_000\n || !Number.isSafeInteger(maximum) || maximum < 1 || maximum > 64 * 1024 * 1024\n || !Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 64)\n throw new Error('Invalid publisher fetch limits')\n const active = new Set<Promise<Response>>()\n const nativeFetch = globalThis.fetch.bind(globalThis)\n const fetchFn: typeof globalThis.fetch = (input, init) => {\n if (active.size >= concurrency)\n return Promise.reject(new Error('Publisher HTTP concurrency limit exceeded'))\n const operation = (async () => {\n const signals = [owner.signal,\n ...(options.signal === undefined ? [] : [options.signal]),\n ...(init?.signal == null ? [] : [init.signal]),\n ...(input instanceof Request ? [input.signal] : [])]\n const scope = publisherAbortScope(signals, timeout)\n try {\n scope.signal.throwIfAborted()\n const response = await nativeFetch(input, {\n ...init, redirect: 'error', signal: scope.signal,\n })\n if (response.body === null)\n return response\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done)\n break\n const bytes: unknown = chunk.value\n if (!(bytes instanceof Uint8Array)) throw new TypeError('Publisher HTTP body returned a non-byte chunk')\n size += bytes.byteLength\n if (size > maximum) {\n await reader.cancel()\n throw new Error('Publisher HTTP body exceeds its bound')\n }\n chunks.push(bytes)\n }\n } finally {\n reader.releaseLock()\n }\n const headers = new Headers(response.headers)\n headers.delete('content-encoding')\n headers.delete('transfer-encoding')\n headers.set('content-length', String(size))\n return new Response(Buffer.concat(chunks), {\n status: response.status, statusText: response.statusText, headers,\n })\n } finally {\n scope.dispose()\n }\n })()\n active.add(operation)\n void operation.then(() => active.delete(operation), () => active.delete(operation))\n return operation\n }\n return {\n fetchFn,\n async close() {\n owner.abort()\n await Promise.allSettled(active)\n },\n get activeRequests() {\n return active.size\n },\n }\n}\n\n/** Ethers' documented per-request HTTP hook, without its unbounded Node body reader. */\nexport function createBoundedPublisherEthersTransport(options: BoundedPublisherFetchOptions = {}) {\n const bounded = createBoundedPublisherFetch(options)\n const getUrl: FetchGetUrlFunc = async (request, cancellation) => {\n const controller = new AbortController()\n cancellation?.addListener(() => controller.abort())\n cancellation?.checkSignal()\n const response = await bounded.fetchFn(request.url, {\n body: request.body === null ? undefined : Buffer.from(request.body),\n headers: request.headers,\n method: request.method,\n signal: controller.signal,\n })\n return {\n body: new Uint8Array(await response.arrayBuffer()),\n headers: Object.fromEntries(response.headers),\n statusCode: response.status,\n statusMessage: response.statusText,\n }\n }\n return {\n getUrl,\n async close() { await bounded.close() },\n get activeRequests() { return bounded.activeRequests },\n }\n}\n", "import { clearTimeout, setTimeout } from 'node:timers'\n\n/** Own every listener/timer used by a bounded operation; disposal is mandatory. */\nexport function publisherAbortScope(signals: readonly AbortSignal[], timeoutMs?: number) {\n const controller = new AbortController()\n const abort = () => controller.abort()\n const timer = timeoutMs === undefined ? undefined : setTimeout(abort, timeoutMs)\n timer?.unref()\n for (const signal of signals) {\n if (signal.aborted) controller.abort()\n else signal.addEventListener('abort', abort, { once: true })\n }\n return {\n signal: controller.signal,\n dispose() {\n if (timer !== undefined) clearTimeout(timer)\n for (const signal of signals) signal.removeEventListener('abort', abort)\n },\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport { decryptWakeSubscription, sourceWakeFilterHash } from '@xyo-network/event-kit-protocol'\nimport type {\n BestEffortDeliveryPolicy, EndpointChallengeResponse, WakeDeliveryMode,\n} from '@xyo-network/event-kit-schemas'\nimport { EndpointChallengeResponseZod } from '@xyo-network/event-kit-schemas'\nimport type { FinalizedSubscriptionTuple } from '@xyo-network/event-kit-statement-graph'\n\nimport type { PublisherEncryptionKeyCustody, PublisherHandshakeClient } from '../handshakeClients.ts'\nimport { publisherAbortScope } from './abort.ts'\nimport type { PublisherHttpsTransport } from './httpsTransport.ts'\nimport type {\n PublisherRuntimeDiscovery, PublisherRuntimeDiscoveryStatus, PublisherRuntimeSubscription,\n} from './publisherRuntime.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\ninterface PendingChallenge {\n readonly challengeHash: string\n readonly expiresAt: number\n readonly response?: EndpointChallengeResponse\n readonly subscriber: string\n readonly subscription: string\n}\n/** Real D005 lifecycle discovery. Off-chain configuration never grants delivery authority. */\nexport function createPublisherHandshakeDiscovery(options: {\n readonly authorizationChainId: string\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly client: PublisherHandshakeClient\n readonly deliveryMode?: WakeDeliveryMode\n readonly keys: PublisherEncryptionKeyCustody\n readonly maxSubscriptions?: number\n readonly nowSeconds?: () => number\n readonly publisher: string\n readonly serviceHash?: string\n readonly state: SqlitePublisherState\n readonly transport: PublisherHttpsTransport\n}): PublisherRuntimeDiscovery {\n const clock = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const owner = new AbortController()\n let accepting: Promise<void> | undefined\n let viewing: ReturnType<PublisherHandshakeClient['subscriptions']> | undefined\n let status: PublisherRuntimeDiscoveryStatus = {\n authorizationChainId: options.authorizationChainId,\n keyLoaded: false,\n activeKeyIds: [],\n pendingSubscriptions: 0,\n rejectedSubscriptions: 0,\n challengeFailures: 0,\n }\n function selectedTuple(tuple: FinalizedSubscriptionTuple): boolean {\n return (options.serviceHash === undefined || tuple.service.objectHash === options.serviceHash)\n && (options.deliveryMode === undefined || tuple.service.body.deliveryMode === options.deliveryMode)\n && (options.deliveryMode === undefined || tuple.subscription.body.deliveryMode === options.deliveryMode)\n && (options.deliveryMode === undefined || isDeepStrictEqual(tuple.service.body.bestEffort, options.bestEffort))\n }\n async function activeView(signal: AbortSignal) {\n signal.throwIfAborted()\n // A timed-out caller does not create a second SDK replay while the first\n // remains in flight. The configured REST transport aborts actual reads.\n viewing ??= (async () => {\n try {\n return await options.client.subscriptions()\n } finally {\n viewing = undefined\n }\n })()\n const view = await viewing\n signal.throwIfAborted()\n if (!view.ok || view.indexedThrough !== view.finalizedHead)\n throw new Error('Publisher subscription view is unavailable or stale')\n status = {\n ...status,\n finalizedHead: view.finalizedHead,\n indexedThrough: view.indexedThrough,\n pendingSubscriptions: view.subscriptions.filter(item => item.state === 'pending' && item.tuples.some(selectedTuple)).length,\n rejectedSubscriptions: view.rejections.length,\n }\n return view\n }\n async function acceptCandidate(subscriber: string, subscription: string, signal: AbortSignal) {\n try {\n let pending = options.state.get<PendingChallenge>('outbound-challenges', subscription)\n if (pending !== undefined && pending.response === undefined && clock() >= pending.expiresAt)\n pending = undefined\n if (pending === undefined) {\n const issued = await options.client.issueChallenge({\n issuedAt: clock(), lifetimeSeconds: 300, subscriber: subscriber, subscription,\n })\n pending = {\n challengeHash: issued.challengeHash, subscriber: subscriber, subscription, expiresAt: issued.challenge.expiresAt,\n }\n options.state.set('outbound-challenges', subscription, pending)\n }\n if (pending.response === undefined) {\n const begun = await options.client.beginChallenge({ challengeHash: pending.challengeHash, nowSeconds: clock })\n if (begun.kind !== 'started')\n return\n signal.throwIfAborted()\n const response = await options.transport.post(begun.target.endpoint, begun.challenge, signal)\n if (response.status !== 200)\n throw new Error('Endpoint challenge was rejected')\n pending = { ...pending, response: EndpointChallengeResponseZod.parse(response.body) }\n options.state.set('outbound-challenges', subscription, pending)\n }\n signal.throwIfAborted()\n const response = pending.response\n if (response === undefined)\n throw new Error('Endpoint proof is unavailable')\n await options.client.completeChallengeAndAccept({\n ...pending, response, nowSeconds: clock,\n })\n } catch {\n if (signal.aborted)\n return\n const failures = options.state.get<number>('challenge-failures', subscription) ?? 0\n options.state.set('challenge-failures', subscription, failures + 1)\n const pending = options.state.get<PendingChallenge>('outbound-challenges', subscription)\n if (pending !== undefined && clock() >= pending.expiresAt)\n options.state.remove('outbound-challenges', subscription)\n }\n }\n\n async function accept(signal: AbortSignal) {\n signal.throwIfAborted()\n const now = clock()\n if (now < (options.state.get<number>('challenge-rate', 'next-pass') ?? 0))\n return\n options.state.set('challenge-rate', 'next-pass', now + 10)\n const found = await options.client.acceptanceCandidates()\n if (!found.ok)\n throw new Error('Publisher acceptance candidates are unavailable')\n const offset = options.state.get<number>('challenge-rate', 'offset') ?? 0\n const candidates = found.candidates.filter(candidate => selectedTuple(candidate.tuple))\n let attempted = 0\n // Bound inspected candidates and rotate the starting point: four failed\n // candidates must not permanently prevent the fifth from being challenged.\n for (let index = 0; index < Math.min(candidates.length, 128) && attempted < 4; index += 1) {\n const candidate = candidates[(offset + index) % candidates.length]\n if (candidate === undefined)\n break\n options.state.set('challenge-rate', 'offset', (offset + index + 1) % candidates.length)\n const next = options.state.get<number>('challenge-controller-rate', candidate.subscriber) ?? 0\n if (now < next)\n continue\n options.state.set('challenge-controller-rate', candidate.subscriber, now + 30)\n attempted += 1\n signal.throwIfAborted()\n await acceptCandidate(candidate.subscriber, candidate.tuple.subscription.objectHash, signal)\n }\n }\n async function loadScopedKeys(view: Extract<Awaited<ReturnType<PublisherHandshakeClient['subscriptions']>>, { ok: true }>, active: typeof view.subscriptions) {\n const scopedKeys = active.flatMap(item => item.tuples.filter(tuple => tuple.subscription.objectHash === item.selectedSubscription).map(tuple => ({\n encryptionKey: tuple.subscription.body.encryptionKey, keyId: tuple.subscription.body.keyId, publisher: options.publisher,\n })))\n if (view.hasCurrentAdvertisement && (options.serviceHash === undefined || view.service.objectHash === options.serviceHash)\n && (options.deliveryMode === undefined || view.service.body.deliveryMode === options.deliveryMode)) {\n scopedKeys.push({\n encryptionKey: view.key.objectHash, keyId: view.key.body.keyId, publisher: options.publisher,\n })\n }\n const loadedKeys = await Promise.all(scopedKeys.map(async key => await options.keys.getPrivateKey(key)))\n status = {\n ...status,\n keyLoaded: scopedKeys.length > 0 && loadedKeys.every(key => key !== undefined),\n activeKeyIds: [...new Set(scopedKeys.map(key => key.keyId))],\n }\n }\n return {\n async discover(signal) {\n const view = await activeView(signal)\n const active = view.subscriptions.filter(item => item.state === 'active' && item.tuples.some(tuple => tuple.subscription.objectHash === item.selectedSubscription && selectedTuple(tuple)))\n await loadScopedKeys(view, active)\n if (active.length > (options.maxSubscriptions ?? 64))\n throw new Error('Publisher active subscription limit exceeded')\n const subscriptions: PublisherRuntimeSubscription[] = []\n for (const lifecycle of active) {\n if (lifecycle.state !== 'active' || lifecycle.activeFromBlock === undefined)\n continue\n try {\n const tuple = lifecycle.tuples.find(item => item.subscription.objectHash === lifecycle.selectedSubscription)\n if (tuple === undefined || !selectedTuple(tuple))\n throw new Error('Active publisher subscription has no selected tuple')\n const encrypted = tuple.subscription.body\n if (encrypted.chainId !== options.authorizationChainId)\n throw new Error('Subscription authorization chain mismatch')\n const publisherKey = await options.keys.getPrivateKey({\n encryptionKey: encrypted.encryptionKey, keyId: encrypted.keyId, publisher: options.publisher,\n })\n if (publisherKey === undefined)\n throw new Error('Subscription encryption key is unavailable')\n const plaintext = await decryptWakeSubscription({\n publisherKey, subscriber: tuple.subscriber, subscription: encrypted,\n })\n options.transport.assertAllowed(plaintext.endpoint)\n subscriptions.push({\n subscriptionHash: tuple.subscription.objectHash,\n serviceHash: tuple.service.objectHash,\n deliveryMode: plaintext.filter.deliveryMode,\n ...(plaintext.filter.bestEffort === undefined ? {} : { bestEffort: plaintext.filter.bestEffort }),\n authorizationChainId: options.authorizationChainId,\n controller: tuple.subscriber,\n audience: plaintext.audience,\n endpoint: plaintext.endpoint,\n deploymentId: plaintext.deploymentId,\n ...(plaintext.queueId === null ? {} : { queueId: plaintext.queueId }),\n source: plaintext.filter.source,\n fromPosition: plaintext.filter.fromPosition,\n maxPositionsPerWake: plaintext.filter.maxPositionsPerWake,\n filterHash: await sourceWakeFilterHash(plaintext.filter),\n })\n } catch {\n // A malformed or locally disallowed endpoint cannot stop independent\n // accepted subscribers. Durable pending work remains until a fresh\n // authoritative check proves the subscription is inactive.\n status = { ...status, rejectedSubscriptions: status.rejectedSubscriptions + 1 }\n }\n }\n return subscriptions\n },\n async isActive(subscription, signal) {\n const view = await activeView(signal)\n return view.subscriptions.some(item => item.state === 'active' && item.selectedSubscription === subscription.subscriptionHash\n && item.tuples.some(tuple => tuple.subscription.objectHash === subscription.subscriptionHash && tuple.subscriber === subscription.controller && selectedTuple(tuple)))\n },\n async acceptPending(signal) {\n // A slow finality operation is shared across passes; timeout does not\n // spawn another acceptance/signing operation against the same state.\n if (accepting === undefined) {\n const scope = publisherAbortScope([owner.signal, signal])\n accepting = (async () => {\n try {\n await accept(scope.signal)\n } finally {\n scope.dispose()\n accepting = undefined\n }\n })()\n }\n await accepting\n },\n async close() {\n await Promise.allSettled([accepting, viewing].filter(item => item !== undefined))\n },\n status: () => ({ ...status, challengeFailures: options.state.entries<number>('challenge-failures').reduce((sum, item) => sum + item.value, 0) }),\n }\n}\n", "import { Buffer } from 'node:buffer'\nimport { lookup } from 'node:dns/promises'\nimport { request } from 'node:https'\nimport { BlockList, isIP } from 'node:net'\n\nimport { z } from 'zod'\n\nimport { publisherAbortScope } from './abort.ts'\nimport { boundedPublisherOperation } from './sources.ts'\nconst OptionsZod = z.strictObject({\n allowedEndpoints: z.array(z.url()).min(1).max(64),\n endpointHeaders: z.array(z.strictObject({\n endpoint: z.url(),\n headers: z.strictObject({ 'x-vercel-protection-bypass': z.string().min(1).max(4096).regex(/^[\\u{21}-\\u{7E}]+$/u) }),\n })).max(64).default([]),\n maxResponseBytes: z.number().int().min(1).max(1_048_576).default(65_536),\n requestTimeoutMs: z.number().int().min(100).max(60_000).default(10_000),\n})\nexport interface PublisherHttpsTransportOptions {\n /** Exact public HTTPS destinations approved by the operator, including their path. */\n readonly allowedEndpoints: readonly string[]\n /** Private operator-provisioned Vercel automation credential, bound to one exact destination. */\n readonly endpointHeaders?: readonly { readonly endpoint: string; readonly headers: Readonly<Record<string, string>> }[]\n readonly maxResponseBytes?: number\n readonly requestTimeoutMs?: number\n}\nexport interface PublisherHttpsResponse {\n readonly body: unknown\n readonly retryAfterMs?: number\n readonly status: number\n}\nexport interface PublisherHttpsTransport {\n assertAllowed(endpoint: string): void\n post(endpoint: string, body: unknown, signal: AbortSignal, jwt?: string): Promise<PublisherHttpsResponse>\n}\nconst NON_PUBLIC_IPV4_SUBNETS = [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.0.0.0', 24],\n ['192.0.2.0', 24],\n ['192.88.99.0', 24],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['198.51.100.0', 24],\n ['203.0.113.0', 24],\n ['224.0.0.0', 4],\n ['240.0.0.0', 4],\n] as const\nconst NON_PUBLIC_IPV6_SUBNETS = [\n ['2001::', 23], ['2001:db8::', 32], ['2002::', 16], ['3fff::', 20],\n] as const\n\ninterface PublisherAddressPolicy {\n readonly globalIpv6: BlockList\n readonly nonPublicIpv4: BlockList\n readonly nonPublicIpv6: BlockList\n}\n\nlet publisherAddressPolicy: PublisherAddressPolicy | undefined\n\nfunction loadPublisherAddressPolicy(): PublisherAddressPolicy {\n if (publisherAddressPolicy !== undefined) return publisherAddressPolicy\n const nonPublicIpv4 = new BlockList()\n for (const [address, prefix] of NON_PUBLIC_IPV4_SUBNETS) {\n nonPublicIpv4.addSubnet(address, prefix, 'ipv4')\n }\n const globalIpv6 = new BlockList()\n globalIpv6.addSubnet('2000::', 3, 'ipv6')\n const nonPublicIpv6 = new BlockList()\n for (const [address, prefix] of NON_PUBLIC_IPV6_SUBNETS) {\n nonPublicIpv6.addSubnet(address, prefix, 'ipv6')\n }\n publisherAddressPolicy = {\n globalIpv6, nonPublicIpv4, nonPublicIpv6,\n }\n return publisherAddressPolicy\n}\n\n/** Conservative public-unicast policy, with numeric subnet checks for every IPv6 spelling. */\nexport function isPublicPublisherAddress(address: string): boolean {\n const policy = loadPublisherAddressPolicy()\n return isIP(address) === 4\n ? !policy.nonPublicIpv4.check(address, 'ipv4')\n : isIP(address) === 6 && policy.globalIpv6.check(address, 'ipv6') && !policy.nonPublicIpv6.check(address, 'ipv6')\n}\nexport function createPublisherHttpsTransport(input: PublisherHttpsTransportOptions): PublisherHttpsTransport {\n const parsed = OptionsZod.safeParse(input)\n if (!parsed.success) throw new Error('Invalid publisher HTTPS transport configuration')\n const options = parsed.data\n const allowed = new Set(options.allowedEndpoints.map((endpoint) => {\n const url = new URL(endpoint)\n if (url.href !== endpoint || url.protocol !== 'https:' || (url.port !== '' && url.port !== '443')\n || url.username !== '' || url.password !== '' || url.hash !== '')\n throw new Error('Publisher destinations must be canonical public HTTPS URLs on port 443')\n const literal = url.hostname.replaceAll(/^\\[|\\]$/gu, '')\n if (isIP(literal) !== 0 && !isPublicPublisherAddress(literal))\n throw new Error('Publisher destination is not public')\n if (url.hostname === 'localhost' || url.hostname.endsWith('.localhost') || url.hostname.endsWith('.local'))\n throw new Error('Publisher destination is not public')\n return endpoint\n }))\n const assertAllowed = (endpoint: string) => {\n if (!allowed.has(endpoint))\n throw new Error('Publisher destination is not explicitly allowed')\n }\n const endpointHeaders = new Map<string, Readonly<Record<string, string>>>()\n for (const entry of options.endpointHeaders) {\n assertAllowed(entry.endpoint)\n if (endpointHeaders.has(entry.endpoint)) throw new Error('Duplicate publisher endpoint header configuration')\n endpointHeaders.set(entry.endpoint, entry.headers)\n }\n return {\n assertAllowed,\n async post(endpoint, body, signal, jwt) {\n assertAllowed(endpoint)\n signal.throwIfAborted()\n const url = new URL(endpoint)\n const scope = publisherAbortScope([signal], options.requestTimeoutMs)\n const combined = scope.signal\n try {\n const addresses = await boundedPublisherOperation(lookup(url.hostname.replaceAll(/^\\[|\\]$/gu, ''), { all: true, verbatim: true }), combined, options.requestTimeoutMs)\n combined.throwIfAborted()\n if (addresses.length === 0 || addresses.some(item => !isPublicPublisherAddress(item.address)))\n throw new Error('Publisher DNS answer includes a non-public address')\n const selected = addresses[0]\n if (selected === undefined)\n throw new Error('Publisher DNS lookup was empty')\n const encoded = Buffer.from(JSON.stringify(body))\n if (encoded.byteLength > 65_536)\n throw new Error('Publisher request body is too large')\n return await new Promise<PublisherHttpsResponse>((resolve, reject) => {\n const call = request(url, {\n agent: false,\n headers: {\n ...endpointHeaders.get(endpoint),\n 'content-length': encoded.byteLength,\n 'content-type': 'application/json',\n ...(jwt === undefined ? {} : { authorization: `Bearer ${jwt}` }),\n },\n lookup(_hostname, lookupOptions, callback) {\n // Pin the validated DNS answer for this connection; TLS still validates\n // the original hostname. No second resolver can rebind to a private IP.\n if (lookupOptions.all)\n callback(null, [{ address: selected.address, family: selected.family }])\n else\n callback(null, selected.address, selected.family)\n },\n method: 'POST',\n rejectUnauthorized: true,\n signal: combined,\n }, (response) => {\n const status = response.statusCode ?? 500\n if (status >= 300 && status < 400) {\n response.destroy()\n reject(new Error('Publisher HTTPS redirects are forbidden'))\n return\n }\n let size = 0\n const chunks: Buffer[] = []\n response.on('data', (chunk: Buffer) => {\n size += chunk.byteLength\n if (size > options.maxResponseBytes) {\n response.destroy()\n reject(new Error('Publisher HTTPS response is too large'))\n } else\n chunks.push(chunk)\n })\n response.on('error', () => reject(new Error('Publisher HTTPS response failed')))\n response.on('end', () => {\n try {\n const responseBody: unknown = size === 0 ? null : JSON.parse(Buffer.concat(chunks).toString('utf8'))\n const retry = Number(response.headers['retry-after'])\n resolve({\n status, body: responseBody, ...(Number.isFinite(retry) && retry > 0 ? { retryAfterMs: Math.min(retry * 1000, 3_600_000) } : {}),\n })\n } catch {\n reject(new Error('Publisher HTTPS response is not JSON'))\n }\n })\n })\n call.on('error', () => reject(new Error('Publisher HTTPS request failed')))\n call.end(encoded)\n })\n } finally {\n scope.dispose()\n }\n },\n }\n}\n", "import { createHash } from 'node:crypto'\n\nimport { canonicalJson } from '@xyo-network/event-kit-protocol'\nimport type { WakeSource } from '@xyo-network/event-kit-schemas'\nimport { completedUtcIntervalPosition, WakeSourceZod } from '@xyo-network/event-kit-schemas'\nimport { PayloadBuilder } from '@xyo-network/sdk'\nimport type { XyoGateway } from '@xyo-network/xl1-sdk'\nimport { asXL1BlockNumber } from '@xyo-network/xl1-sdk'\nimport { FetchRequest, JsonRpcProvider } from 'ethers'\n\nimport { publisherAbortScope } from './abort.ts'\nimport { createBoundedPublisherEthersTransport } from './boundedFetch.ts'\nexport interface PublisherSourceHead {\n readonly hash?: string\n readonly position: number\n}\nexport interface PublisherSourceReader {\n readonly source: WakeSource\n close?(): void | Promise<void>\n head(signal: AbortSignal): Promise<PublisherSourceHead>\n}\nexport function publisherSourceKey(source: WakeSource): string {\n return createHash('sha256').update(canonicalJson(WakeSourceZod.parse(source))).digest('hex')\n}\nexport async function boundedPublisherOperation<T>(operation: Promise<T>, signal: AbortSignal, timeoutMs = 10_000): Promise<T> {\n const scope = publisherAbortScope([signal], timeoutMs)\n const combined = scope.signal\n let rejectAbort: (() => void) | undefined\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = () => reject(new Error('Publisher operation aborted or timed out'))\n combined.addEventListener('abort', rejectAbort, { once: true })\n })\n try {\n combined.throwIfAborted()\n return await Promise.race([operation, aborted])\n } finally {\n if (rejectAbort !== undefined)\n combined.removeEventListener('abort', rejectAbort)\n scope.dispose()\n }\n}\ntype GatewayViewer = NonNullable<XyoGateway['connection']['viewer']>\nexport function createXl1PublisherSource(options: {\n readonly source: Extract<WakeSource, {\n kind: 'xl1-finalized'\n }>\n readonly viewer: Pick<GatewayViewer, 'block' | 'chainId' | 'finalization'>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'xl1-finalized')\n throw new Error('Expected an XL1 finalized source')\n return {\n source,\n async head(signal) {\n const chainId = String(await boundedPublisherOperation(Promise.resolve(options.viewer.chainId()), signal))\n if (chainId !== source.chainId)\n throw new Error('XL1 source chain identity changed')\n const position = Number(await boundedPublisherOperation(Promise.resolve(options.viewer.finalization.headNumber()), signal))\n if (!Number.isSafeInteger(position) || position < 0)\n throw new Error('XL1 finalized head is invalid')\n const block = await boundedPublisherOperation(Promise.resolve(options.viewer.block.blockByNumber(asXL1BlockNumber(position, true))), signal)\n if (block?.[0].block !== position || !/^[0-9a-f]{64}$/u.test(block[0]._hash)) {\n throw new Error('XL1 finalized head block is unavailable or inconsistent')\n }\n if (String(block[0].chain) !== source.chainId || await PayloadBuilder.hash(block[0]) !== block[0]._hash) {\n throw new Error('XL1 finalized head block chain or hash is inconsistent')\n }\n return { position, hash: block[0]._hash }\n },\n }\n}\nexport function createEthereumFinalizedPublisherSource(options: {\n readonly requestTimeoutMs?: number\n readonly rpcUrl: string\n readonly source: Extract<WakeSource, {\n kind: 'ethereum-finalized'\n }>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'ethereum-finalized')\n throw new Error('Expected an Ethereum finalized source')\n const { chainId, genesisHash } = source\n const url = new URL(options.rpcUrl)\n if (url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.hash !== '') {\n throw new Error('Ethereum source RPC must use HTTPS without URL credentials or fragments')\n }\n const connection = new FetchRequest(url.href)\n connection.timeout = options.requestTimeoutMs ?? 10_000\n const transport = createBoundedPublisherEthersTransport({\n requestTimeoutMs: options.requestTimeoutMs, maxResponseBytes: 2 * 1024 * 1024, maxConcurrency: 8,\n })\n connection.getUrlFunc = transport.getUrl\n connection.setThrottleParams({ maxAttempts: 1 })\n const provider = new JsonRpcProvider(connection, undefined, { batchMaxCount: 1, cacheTimeout: -1 })\n let reading: Promise<PublisherSourceHead> | undefined\n let closed = false\n let closing: Promise<void> | undefined\n const close = () => closing ??= (async () => {\n closed = true\n provider.destroy()\n await transport.close()\n })()\n const onAbort = () => {\n void close()\n }\n async function read() {\n const requests = [provider.getNetwork(), provider.getBlock(0), provider.getBlock('finalized')] as const\n // A failing sibling request cannot release the single-flight slot while\n // another request still owns a connection or a bounded response body.\n try {\n const [network, genesis, block] = await Promise.all(requests)\n if (network.chainId.toString() !== chainId || genesis?.hash?.slice(2).toLowerCase() !== genesisHash) {\n throw new Error('Ethereum source chain identity mismatch')\n }\n if (block?.hash === null || block === null || !/^0x[0-9a-fA-F]{64}$/u.test(block.hash)\n || !Number.isSafeInteger(block.number) || block.number < 0) throw new Error('Ethereum finalized head is unavailable')\n return { position: block.number, hash: block.hash.slice(2).toLowerCase() }\n } catch (error) {\n await Promise.allSettled(requests)\n throw error\n }\n }\n return {\n source,\n close,\n async head(signal) {\n signal.throwIfAborted()\n if (closed) throw new Error('Ethereum source is closed')\n signal.addEventListener('abort', onAbort, { once: true })\n reading ??= (async () => {\n try {\n return await read()\n } finally {\n reading = undefined\n }\n })()\n try {\n return await boundedPublisherOperation(reading, signal, options.requestTimeoutMs ?? 10_000)\n } finally {\n signal.removeEventListener('abort', onAbort)\n }\n },\n }\n}\n\nexport function createUtcIntervalPublisherSource(options: {\n readonly nowSeconds?: () => number\n readonly source: Extract<WakeSource, {\n kind: 'utc-interval'\n }>\n}): PublisherSourceReader {\n const source = WakeSourceZod.parse(options.source)\n if (source.kind !== 'utc-interval')\n throw new Error('Expected a UTC interval source')\n const nowSeconds = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n return {\n source,\n async head(signal) {\n signal.throwIfAborted()\n const now = nowSeconds()\n if (!Number.isSafeInteger(now) || now < 0)\n throw new Error('UTC interval clock is invalid')\n return { position: completedUtcIntervalPosition(source, now) ?? -1 }\n },\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport type { PeriodicActorParams, PeriodicPassContext } from '@ariestools/actor'\nimport { createMemoryLocator, PeriodicActor } from '@ariestools/actor'\nimport { creatable } from '@ariestools/sdk'\nimport { BestEffortAdmissionAcknowledgmentZod } from '@xyo-network/event-kit-protocol'\nimport type {\n BestEffortDeliveryPolicy, WakeDeliveryMode, WakeEnvelope, WakeSource,\n} from '@xyo-network/event-kit-schemas'\nimport { BestEffortDeliveryPolicyZod, WakeDeliveryModeZod } from '@xyo-network/event-kit-schemas'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { publisherAbortScope } from './abort.ts'\nimport type { PublisherHttpsTransport } from './httpsTransport.ts'\nimport type { DeliveryState } from './publisherDeliveryState.ts'\nimport {\n assertDeliveryState, DeliveryResponseError, failedDelivery, makeEvent, prepareBestEffortDelivery,\n} from './publisherDeliveryState.ts'\nimport type { PublisherSourceHead, PublisherSourceReader } from './sources.ts'\nimport { boundedPublisherOperation, publisherSourceKey } from './sources.ts'\nimport { createAccountSourceWakeSigner } from './sourceSigner.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\nexport interface PublisherRuntimeSubscription {\n readonly audience: string\n readonly authorizationChainId: string\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly controller: string\n readonly deliveryMode: WakeDeliveryMode\n readonly deploymentId: string\n readonly endpoint: string\n readonly filterHash: string\n readonly fromPosition: number\n readonly maxPositionsPerWake: number\n readonly queueId?: string\n readonly serviceHash?: string\n readonly source: WakeSource\n readonly subscriptionHash: string\n}\n/** Discovery MUST return only current finalized, accepted subscriptions. */\nexport interface PublisherRuntimeDiscovery {\n acceptPending?(signal: AbortSignal): Promise<void>\n close?(): Promise<void>\n discover(signal: AbortSignal): Promise<readonly PublisherRuntimeSubscription[]>\n /** Re-check the exact current revision before each attempt, including retries. */\n isActive(subscription: PublisherRuntimeSubscription, signal: AbortSignal): Promise<boolean>\n status?(): PublisherRuntimeDiscoveryStatus\n}\nexport interface PublisherRuntimeDiscoveryStatus {\n readonly activeKeyIds: readonly string[]\n readonly authorizationChainId: string\n readonly challengeFailures: number\n readonly finalizedHead?: number\n readonly indexedThrough?: number\n readonly keyLoaded: boolean\n readonly pendingSubscriptions: number\n readonly rejectedSubscriptions: number\n}\nfunction activationReady(status?: PublisherRuntimeDiscoveryStatus): boolean {\n return (status?.keyLoaded ?? true) && (status?.pendingSubscriptions ?? 0) === 0\n}\n\nexport interface PersistentEventPublisherOptions {\n readonly account: AccountInstance\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly concurrency?: number\n readonly deliveryMode: WakeDeliveryMode\n readonly discovery: PublisherRuntimeDiscovery\n readonly intervalMs?: number\n readonly maxSubscriptions?: number\n readonly nowSeconds?: () => number\n readonly publisher: string\n readonly requestTimeoutMs?: number\n /** Optional immutable operator pin; mismatches fail readiness without revoking subscriptions. */\n readonly serviceHash?: string\n readonly sources: readonly PublisherSourceReader[]\n readonly state: SqlitePublisherState\n readonly transport: PublisherHttpsTransport\n}\nexport interface PersistentEventPublisherStatus {\n readonly abandoned: number\n readonly activeSubscriptions: number\n readonly bestEffort?: BestEffortDeliveryPolicy\n readonly clockHealthy: boolean\n readonly degraded: boolean\n readonly delivered: number\n readonly deliveryMode: WakeDeliveryMode\n readonly failures: number\n readonly handshake?: PublisherRuntimeDiscoveryStatus\n readonly lastError?: string\n readonly passes: number\n readonly pendingDeliveries: number\n readonly publisher: string\n readonly ready: boolean\n readonly running: boolean\n readonly sources: readonly {\n readonly hash?: string\n readonly id: string\n readonly position: number\n }[]\n readonly subscriptions: readonly {\n readonly attempts?: number\n readonly cursor: number\n readonly failures: number\n readonly id: string\n /** Best Effort admission target is not a contiguous source prefix. */\n readonly lastAdmissionTarget?: number\n readonly lastHintAt?: number\n readonly pending: boolean\n readonly state: string\n }[]\n readonly superseded: number\n readonly totalAttempts: number\n}\nexport interface PersistentEventPublisher {\n runOnce(): Promise<void>\n start(): Promise<void>\n status(): PersistentEventPublisherStatus\n stop(): Promise<void>\n}\ninterface RuntimeActorParams extends PeriodicActorParams {\n readonly tick: (signal: AbortSignal) => Promise<void>\n}\n@creatable()\nclass PublisherRuntimeActor extends PeriodicActor<RuntimeActorParams> {\n protected override async runPass(context: PeriodicPassContext): Promise<void> {\n await this.params.tick(context.signal)\n }\n}\nconst TimingZod = z.object({\n concurrency: z.number().int().min(1).max(32).default(4),\n intervalMs: z.number().int().min(100).max(60_000).default(1000),\n maxSubscriptions: z.number().int().min(1).max(1024).default(64),\n requestTimeoutMs: z.number().int().min(100).max(60_000).default(10_000),\n})\n\nfunction runtimeSettings(options: PersistentEventPublisherOptions) {\n const deliveryMode = WakeDeliveryModeZod.parse(options.deliveryMode)\n const bestEffort = options.bestEffort === undefined ? undefined : BestEffortDeliveryPolicyZod.parse(options.bestEffort)\n if ((deliveryMode === 'best-effort') !== (bestEffort !== undefined)) throw new TypeError('Explicit delivery mode requires its exact policy')\n return {\n bestEffort,\n deliveryMode,\n deliveryNamespace: deliveryMode === 'best-effort' ? 'best-effort-deliveries' : 'deliveries',\n timing: TimingZod.parse(options),\n }\n}\nexport async function createPersistentEventPublisherRuntime(options: PersistentEventPublisherOptions): Promise<PersistentEventPublisher> {\n const {\n bestEffort, deliveryMode, deliveryNamespace, timing,\n } = runtimeSettings(options)\n if (options.sources.length < 1 || options.sources.length > 16)\n throw new Error('Publisher requires between one and sixteen bounded sources')\n const clock = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))\n const signer = createAccountSourceWakeSigner({\n account: options.account, publisher: options.publisher, nowSeconds: clock,\n })\n const sourceReaders = new Map(options.sources.map(reader => [publisherSourceKey(reader.source), reader]))\n if (sourceReaders.size !== options.sources.length)\n throw new Error('Duplicate publisher source identity')\n const state = options.state\n const existingMode = state.get<string>('metadata', 'runtime-delivery-mode')\n if (existingMode !== undefined && existingMode !== deliveryMode) throw new Error('Publisher state delivery mode mismatch; preserve custody and use an explicitly qualified state binding')\n state.set('metadata', 'runtime-delivery-mode', deliveryMode)\n const abort = new AbortController()\n const seenThisProcess = new Set<string>()\n let running = false\n let ready = false\n let clockHealthy = true\n let passes = 0\n let lastError: string | undefined\n let sourcesHealthy = false\n let stop: Promise<void> | undefined\n const timed = <T>(promise: Promise<T>, signal: AbortSignal) => boundedPublisherOperation(promise, signal, timing.requestTimeoutMs)\n function loadDelivery(subscription: PublisherRuntimeSubscription, now: number): DeliveryState {\n if (subscription.deliveryMode !== deliveryMode || !isDeepStrictEqual(subscription.bestEffort, bestEffort))\n throw new Error('Subscription delivery mode or policy disagrees with runtime')\n if (deliveryMode === 'best-effort' && (subscription.maxPositionsPerWake !== 1 || subscription.serviceHash === undefined)) throw new Error('Best Effort requires point range')\n if (options.serviceHash !== undefined && subscription.serviceHash !== options.serviceHash)\n throw new Error('Subscription does not match the configured exact service descriptor')\n const key = subscription.subscriptionHash\n if (deliveryMode === 'best-effort' && state.get(deliveryNamespace, key) === undefined\n && state.entries(deliveryNamespace).length >= timing.maxSubscriptions) throw new Error('Best Effort state capacity exceeded; live records are not evicted')\n let record = state.get<DeliveryState>(deliveryNamespace, key)\n if (record === undefined) {\n makeEvent(subscription, subscription.fromPosition, subscription.fromPosition, now, '0'.repeat(32))\n if (!Number.isSafeInteger(subscription.maxPositionsPerWake) || subscription.maxPositionsPerWake < 1 || subscription.maxPositionsPerWake > 4096) {\n throw new Error('Invalid source range budget')\n }\n record = {\n subscription, cursor: subscription.fromPosition - 1, delivered: 0, failures: 0, nextAttemptMs: 0, state: 'active',\n }\n state.set(deliveryNamespace, key, record)\n }\n assertDeliveryState(record, subscription)\n return record\n }\n\n function prepareDelivery(record: DeliveryState, now: number, heads: ReadonlyMap<string, PublisherSourceHead | Error>) {\n if (deliveryMode === 'best-effort' && bestEffort !== undefined) {\n const first = !seenThisProcess.has(record.subscription.subscriptionHash)\n const head = heads.get(publisherSourceKey(record.subscription.source))\n if (head !== undefined && !(head instanceof Error) && head.position >= record.subscription.fromPosition)\n seenThisProcess.add(record.subscription.subscriptionHash)\n return prepareBestEffortDelivery({\n bestEffort, first, heads, now, record, state,\n })\n }\n if (record.pending !== undefined) return { ...record, pending: record.pending }\n const subscription = record.subscription\n const head = heads.get(publisherSourceKey(subscription.source))\n if (head === undefined || head instanceof Error) throw new Error('Configured source is unavailable')\n if (head.position <= record.cursor) return\n const fromPosition = record.cursor + 1\n const pending = makeEvent(subscription, fromPosition, Math.min(head.position, fromPosition + subscription.maxPositionsPerWake - 1), now)\n const prepared = { ...record, pending }\n state.transaction(() => {\n const logicalKey = JSON.stringify([subscription.subscriptionHash, pending.fromPosition, pending.toPosition])\n if (!state.insert('delivery-events', logicalKey, pending)) throw new Error('Publisher logical range already exists outside its contiguous cursor')\n state.set(deliveryNamespace, subscription.subscriptionHash, prepared)\n })\n return prepared\n }\n\n async function stillActive(record: DeliveryState, signal: AbortSignal): Promise<boolean> {\n if (await timed(options.discovery.isActive(record.subscription, signal), signal)) return true\n state.set(deliveryNamespace, record.subscription.subscriptionHash, {\n ...record, pending: undefined, state: 'cancelled',\n })\n return false\n }\n\n function acknowledgeBestEffort(record: DeliveryState & { readonly pending: WakeEnvelope }, body: unknown, eventHash: string, signal: AbortSignal, now: number) {\n const { pending, subscription } = record\n const acknowledgment = BestEffortAdmissionAcknowledgmentZod.safeParse(body)\n if (!acknowledgment.success || acknowledgment.data.eventHash !== eventHash || acknowledgment.data.wakeId !== pending.wakeId\n || acknowledgment.data.expiresAt !== pending.issuedAt + (bestEffort?.maxHintAgeSeconds ?? 0) + 60\n || acknowledgment.data.acceptedAt < pending.issuedAt - 60 || acknowledgment.data.acceptedAt > now + 60)\n throw new Error('Publisher did not receive a matching finite acknowledgment')\n signal.throwIfAborted()\n state.set(deliveryNamespace, subscription.subscriptionHash, {\n subscription,\n cursor: pending.toPosition,\n delivered: record.delivered + 1,\n failures: 0,\n attempts: 0,\n superseded: record.superseded ?? 0,\n abandoned: record.abandoned ?? 0,\n totalAttempts: (record.totalAttempts ?? 0) + 1,\n lastNotifiedAt: now,\n lastHintAt: pending.issuedAt,\n lastHintTarget: pending.toPosition,\n nextAttemptMs: 0,\n state: 'active',\n } satisfies DeliveryState)\n }\n\n async function sendDelivery(record: DeliveryState & { readonly pending: WakeEnvelope }, signal: AbortSignal, now: number) {\n const { pending, subscription } = record\n signal.throwIfAborted()\n const signed = await signer.sign(pending, subscription.audience)\n signal.throwIfAborted()\n const attempt = deliveryMode === 'best-effort' ? record.attempts ?? 0 : state.get<{ count: number }>('delivery-attempts', pending.wakeId)?.count ?? 0\n if (deliveryMode === 'best-effort') state.set(deliveryNamespace, subscription.subscriptionHash, {\n ...record, attempts: attempt + 1, totalAttempts: (record.totalAttempts ?? 0) + 1,\n })\n else state.set('delivery-attempts', pending.wakeId, {\n count: attempt + 1, startedAt: now, status: 'in-flight',\n })\n const response = await options.transport.post(subscription.endpoint, signed.event, signal, signed.jwt)\n if (deliveryMode === 'durable') state.set('delivery-attempts', pending.wakeId, {\n count: attempt + 1, startedAt: now, status: response.status,\n })\n if (response.status !== 200 && response.status !== 202) throw new DeliveryResponseError(response.status, response.retryAfterMs)\n if (deliveryMode === 'best-effort') {\n acknowledgeBestEffort(record, response.body, signed.eventHash, signal, now)\n return\n }\n const receipt = z.object({ receiptId: z.string().min(1), wakeId: z.literal(pending.wakeId) }).safeParse(response.body)\n if (!receipt.success) throw new Error('Publisher admission did not return a matching durable receipt')\n signal.throwIfAborted()\n // Receipt, contiguous cursor, and outbox clear commit together. A lost\n // response or death before this transaction reuses the exact pending body.\n state.transaction(() => {\n state.set('delivery-receipts', pending.wakeId, { receiptId: receipt.data.receiptId, receivedAt: now })\n state.set(deliveryNamespace, subscription.subscriptionHash, {\n subscription,\n cursor: pending.toPosition,\n delivered: record.delivered + 1,\n failures: 0,\n nextAttemptMs: 0,\n state: 'active',\n } satisfies DeliveryState)\n })\n }\n\n async function deliver(subscription: PublisherRuntimeSubscription, signal: AbortSignal, now: number, heads: ReadonlyMap<string, PublisherSourceHead | Error>) {\n let record = loadDelivery(subscription, now)\n if (deliveryMode === 'durable' && (record.state !== 'active' || record.nextAttemptMs > now * 1000)) return\n try {\n if (!await stillActive(record, signal)) return\n options.transport.assertAllowed(subscription.endpoint)\n if (!sourceReaders.has(publisherSourceKey(subscription.source))) throw new Error('Subscription source is not configured')\n const prepared = prepareDelivery(record, now, heads)\n if (prepared === undefined) return\n record = prepared\n if (record.nextAttemptMs > now * 1000) return\n // Reconcile once more after observing source progress, before every attempt.\n if (!await stillActive(record, signal)) return\n await sendDelivery(prepared, signal, now)\n } catch (error) {\n if (signal.aborted) return\n state.set(\n deliveryNamespace,\n subscription.subscriptionHash,\n failedDelivery(record, state.get<DeliveryState>(deliveryNamespace, subscription.subscriptionHash), deliveryMode, error, now),\n )\n }\n }\n async function readSources(signal: AbortSignal): Promise<ReadonlyMap<string, PublisherSourceHead | Error>> {\n const heads = new Map<string, PublisherSourceHead | Error>()\n const results = await Promise.allSettled([...sourceReaders].map(async ([key, reader]) => {\n const head = await timed(reader.head(signal), signal)\n if (!Number.isSafeInteger(head.position) || head.position < -1)\n throw new Error('Source head is invalid')\n const previous = state.get<PublisherSourceHead>('source-heads', key)\n if (previous !== undefined && (head.position < previous.position || (head.position === previous.position && head.hash !== previous.hash))) {\n throw new Error('Finalized source regressed or changed hash')\n }\n signal.throwIfAborted()\n state.set('source-heads', key, head)\n heads.set(key, head)\n }))\n sourcesHealthy = results.every(item => item.status === 'fulfilled')\n // All rejections are inspected; delivery sees an unavailable source without\n // exposing provider URLs or allowing one source to deny another service.\n for (const [index, result] of results.entries())\n if (result.status === 'rejected') {\n const key = sourceReaders.keys().toArray()[index]\n if (key !== undefined)\n heads.set(key, new Error('Source read failed'))\n }\n return heads\n }\n async function reconcileDeliveries(subscriptions: readonly PublisherRuntimeSubscription[], signal: AbortSignal) {\n if (subscriptions.length > timing.maxSubscriptions) throw new Error('Publisher subscription limit exceeded')\n const active = new Set(subscriptions.map(subscription => subscription.subscriptionHash))\n if (active.size !== subscriptions.length) throw new Error('Duplicate subscription identity')\n const unavailable = state.entries<DeliveryState>(deliveryNamespace).filter(item => !active.has(item.key) && item.value.state !== 'cancelled')\n let available = true\n for (let offset = 0; offset < unavailable.length; offset += timing.concurrency) {\n signal.throwIfAborted()\n const results = await Promise.allSettled(unavailable.slice(offset, offset + timing.concurrency).map(async ({ key, value }) => {\n const stillAuthorized = await timed(options.discovery.isActive(value.subscription, signal), signal)\n if (!stillAuthorized) state.set(deliveryNamespace, key, {\n ...value, pending: undefined, state: 'cancelled',\n })\n return stillAuthorized\n }))\n // Local key loss, endpoint policy, or a failed replay cannot revoke a\n // finalized subscription. Preserve its exact pending body for restoration.\n available = available && results.every(result => result.status === 'fulfilled' && !result.value)\n }\n return available\n }\n\n async function tick(actorSignal: AbortSignal) {\n const scope = publisherAbortScope([abort.signal, actorSignal])\n const signal = scope.signal\n try {\n signal.throwIfAborted()\n const now = clock()\n const prior = state.get<number>('runtime', 'highest-wall-clock') ?? 0\n clockHealthy = Number.isSafeInteger(now) && now >= prior\n if (!clockHealthy)\n throw new Error('Publisher clock moved backwards')\n state.set('runtime', 'highest-wall-clock', now)\n const subscriptions = await timed(options.discovery.discover(signal), signal)\n const subscriptionsAvailable = await reconcileDeliveries(subscriptions, signal)\n const heads = await readSources(signal)\n for (let offset = 0; offset < subscriptions.length; offset += timing.concurrency) {\n signal.throwIfAborted()\n const outcomes = await Promise.allSettled(subscriptions.slice(offset, offset + timing.concurrency).map(subscription => deliver(subscription, signal, now, heads)))\n const failed = outcomes.find(result => result.status === 'rejected')\n if (failed?.status === 'rejected')\n throw failed.reason\n }\n // Challenge/finality work is bounded and occurs after already-active\n // subscribers, so a new or broken subscriber cannot starve delivery.\n if (options.discovery.acceptPending !== undefined)\n await timed(options.discovery.acceptPending(signal), signal)\n const discoveryStatus = options.discovery.status?.()\n ready = subscriptionsAvailable && sourcesHealthy && activationReady(discoveryStatus)\n lastError = subscriptionsAvailable ? undefined : 'publisher-subscription-unavailable'\n passes += 1\n } catch (error) {\n ready = false\n lastError = clockHealthy ? 'publisher-pass-failed' : 'publisher-clock-unhealthy'\n if (!signal.aborted)\n throw error\n } finally {\n scope.dispose()\n }\n }\n const actor = await PublisherRuntimeActor.create({\n locator: createMemoryLocator({}), intervalMs: timing.intervalMs, firstRun: 'immediate', readiness: 'immediate', tick,\n })\n return {\n async start() {\n if (stop !== undefined)\n throw new Error('Publisher is stopped')\n if (running) {\n return\n }\n\n await actor.start()\n running = true\n },\n async runOnce() {\n if (stop !== undefined)\n throw new Error('Publisher is stopped')\n await actor.runOnce()\n },\n stop: () => stop ??= (async () => {\n abort.abort()\n const failures: unknown[] = []\n try {\n await actor.stop()\n } catch (error) {\n failures.push(error)\n }\n try {\n await options.discovery.close?.()\n } catch (error) {\n failures.push(error)\n }\n for (const source of options.sources)\n try {\n await source.close?.()\n } catch (error) {\n failures.push(error)\n }\n running = false\n ready = false\n if (failures.length > 0)\n throw new AggregateError(failures, 'Publisher runtime shutdown failed')\n })(),\n status() {\n const deliveries = state.entries<DeliveryState>(deliveryNamespace).map(item => item.value)\n return {\n running,\n deliveryMode,\n ...(bestEffort === undefined ? {} : { bestEffort: Object.freeze({ ...bestEffort }) }),\n superseded: deliveries.reduce((sum, item) => sum + (item.superseded ?? 0), 0),\n abandoned: deliveries.reduce((sum, item) => sum + (item.abandoned ?? 0), 0),\n totalAttempts: deliveries.reduce((sum, item) => sum + (item.totalAttempts ?? 0), 0),\n ready: running && ready,\n clockHealthy,\n degraded: !ready || deliveries.some(item => item.state !== 'cancelled' && item.failures > 0),\n publisher: options.publisher,\n activeSubscriptions: deliveries.filter(item => item.state === 'active').length,\n pendingDeliveries: deliveries.filter(item => item.pending !== undefined).length,\n delivered: deliveries.reduce((sum, item) => sum + item.delivered, 0),\n failures: deliveries.reduce((sum, item) => sum + item.failures, 0),\n passes,\n ...(lastError === undefined ? {} : { lastError }),\n ...(options.discovery.status === undefined ? {} : { handshake: options.discovery.status() }),\n sources: state.entries<PublisherSourceHead>('source-heads').filter(item => sourceReaders.has(item.key)).map(item => ({ id: item.key, ...item.value })),\n subscriptions: state.entries<DeliveryState>(deliveryNamespace).map(item => ({\n id: item.key,\n cursor: item.value.cursor,\n ...(deliveryMode === 'best-effort'\n ? {\n ...(item.value.cursor < item.value.subscription.fromPosition ? {} : { lastAdmissionTarget: item.value.cursor }),\n attempts: item.value.attempts ?? 0,\n lastHintAt: item.value.lastHintAt,\n }\n : {}),\n state: item.value.state,\n pending: item.value.pending !== undefined,\n failures: item.value.failures,\n })),\n }\n },\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { BestEffortDeliveryPolicy, WakeEnvelope } from '@xyo-network/event-kit-schemas'\nimport { WakeEnvelopeSchema, WakeEnvelopeZod } from '@xyo-network/event-kit-schemas'\n\nimport type { PublisherRuntimeSubscription } from './publisherRuntime.ts'\nimport type { PublisherSourceHead } from './sources.ts'\nimport { publisherSourceKey } from './sources.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\n\nexport interface DeliveryState {\n readonly abandoned?: number\n readonly attempts?: number\n readonly cursor: number\n readonly delivered: number\n readonly failures: number\n readonly lastError?: string\n readonly lastHintAt?: number\n readonly lastHintTarget?: number\n readonly lastNotifiedAt?: number\n readonly nextAttemptMs: number\n readonly pending?: WakeEnvelope\n readonly state: 'active' | 'blocked' | 'cancelled'\n readonly subscription: PublisherRuntimeSubscription\n readonly superseded?: number\n readonly totalAttempts?: number\n}\nexport function assertDeliveryState(record: DeliveryState, subscription: PublisherRuntimeSubscription): void {\n if (!isDeepStrictEqual(record.subscription, subscription))\n throw new Error('Subscription revision changed without a new identity')\n if (!Number.isSafeInteger(record.cursor) || record.cursor < subscription.fromPosition - 1\n || [record.delivered, record.failures, record.nextAttemptMs].some(value => !(Number.isSafeInteger(value) && value >= 0))\n || [record.attempts, record.superseded, record.abandoned, record.totalAttempts, record.lastHintAt, record.lastNotifiedAt, record.lastHintTarget]\n .some(value => value !== undefined && !(Number.isSafeInteger(value) && value >= 0))\n || !['active', 'blocked', 'cancelled'].includes(record.state))\n throw new Error('Persisted publisher delivery state is invalid')\n if (record.pending === undefined) return\n const pending = WakeEnvelopeZod.parse(record.pending)\n if ((subscription.deliveryMode === 'durable' && pending.fromPosition !== record.cursor + 1)\n || pending.deliveryMode !== subscription.deliveryMode || pending.toPosition - pending.fromPosition + 1 > subscription.maxPositionsPerWake\n || pending.authorizationChainId !== subscription.authorizationChainId || pending.deploymentId !== subscription.deploymentId\n || pending.queueId !== subscription.queueId || pending.filterHash !== subscription.filterHash\n || !isDeepStrictEqual(pending.source, subscription.source))\n throw new Error('Persisted publisher outbox binding is invalid')\n}\nexport function makeEvent(subscription: PublisherRuntimeSubscription, fromPosition: number, toPosition: number, now: number, wakeId = randomBytes(16).toString('hex')) {\n return WakeEnvelopeZod.parse({\n schema: WakeEnvelopeSchema,\n authorizationChainId: subscription.authorizationChainId,\n deliveryMode: subscription.deliveryMode,\n deploymentId: subscription.deploymentId,\n filterHash: subscription.filterHash,\n fromPosition,\n issuedAt: now,\n source: subscription.source,\n toPosition,\n wakeId,\n ...(subscription.queueId === undefined ? {} : { queueId: subscription.queueId }),\n })\n}\n\nexport class DeliveryResponseError extends Error {\n readonly retryAfterMs?: number\n readonly status: number\n constructor(status: number, retryAfterMs?: number) {\n super('Publisher admission failed')\n this.status = status\n this.retryAfterMs = retryAfterMs\n }\n\n get retryable() {\n return this.status === 408 || this.status === 429 || this.status >= 500\n }\n}\n\nexport function prepareBestEffortDelivery(options: {\n readonly bestEffort: BestEffortDeliveryPolicy\n readonly first: boolean\n readonly heads: ReadonlyMap<string, PublisherSourceHead | Error>\n readonly now: number\n readonly record: DeliveryState\n readonly state: SqlitePublisherState\n}) {\n const {\n bestEffort, first, heads, now, record, state,\n } = options\n const subscription = record.subscription\n const head = heads.get(publisherSourceKey(subscription.source))\n const prior = record.pending\n const expired = isHintExpired(record, now, bestEffort)\n if (head === undefined || head instanceof Error || head.position < subscription.fromPosition) {\n if (prior !== undefined && !expired) return { ...record, pending: prior }\n if (prior !== undefined) state.set('best-effort-deliveries', subscription.subscriptionHash, {\n ...record, pending: undefined, abandoned: (record.abandoned ?? 0) + 1,\n })\n return\n }\n const refresh = refreshDue(record, now, bestEffort)\n if (freshHintRequired(record, head.position, first, refresh, expired)) {\n const pending = makeEvent(subscription, head.position, head.position, now)\n const prepared = {\n ...record,\n pending,\n attempts: 0,\n lastHintAt: now,\n lastHintTarget: head.position,\n superseded: (record.superseded ?? 0) + (prior !== undefined && !expired ? 1 : 0),\n abandoned: (record.abandoned ?? 0) + (expired ? 1 : 0),\n nextAttemptMs: 0,\n state: 'active' as const,\n }\n state.set('best-effort-deliveries', subscription.subscriptionHash, prepared)\n return prepared\n }\n if (expired) state.set('best-effort-deliveries', subscription.subscriptionHash, {\n ...record, pending: undefined, abandoned: (record.abandoned ?? 0) + 1,\n })\n return prior === undefined || expired ? undefined : { ...record, pending: prior }\n}\n\nfunction isHintExpired(record: DeliveryState, now: number, policy: BestEffortDeliveryPolicy): boolean {\n return record.pending !== undefined && (now > record.pending.issuedAt + policy.maxHintAgeSeconds || (record.attempts ?? 0) >= policy.maxAttempts)\n}\nfunction refreshDue(record: DeliveryState, now: number, policy: BestEffortDeliveryPolicy): boolean {\n return now - (record.lastHintAt ?? record.lastNotifiedAt ?? 0) >= policy.refreshIntervalSeconds\n}\nfunction freshHintRequired(record: DeliveryState, head: number, first: boolean, refresh: boolean, expired: boolean): boolean {\n return first || head > (record.pending?.toPosition ?? record.lastHintTarget ?? record.cursor) || (refresh && (record.pending === undefined || expired))\n}\nexport function failedDelivery(record: DeliveryState, current: DeliveryState | undefined, mode: string, error: unknown, now: number): DeliveryState {\n const bestEffort = mode === 'best-effort'\n const wait = error instanceof DeliveryResponseError && error.retryAfterMs !== undefined\n ? error.retryAfterMs\n : Math.min(300_000, 1000 * (2 ** Math.min(record.failures, 8)))\n return {\n ...record,\n failures: record.failures + 1,\n totalAttempts: bestEffort ? current?.totalAttempts ?? record.totalAttempts ?? 0 : record.totalAttempts,\n attempts: bestEffort ? current?.attempts ?? record.attempts ?? 0 : record.attempts,\n state: !bestEffort && error instanceof DeliveryResponseError && !error.retryable ? 'blocked' : 'active',\n nextAttemptMs: now * 1000 + Math.min(3_600_000, wait),\n lastError: 'delivery-failed',\n }\n}\n", "import { randomBytes } from 'node:crypto'\n\nimport type { WakeEnvelope } from '@xyo-network/event-kit-schemas'\nimport {\n NormalizedAddressZod, WakeEnvelopeZod, WakeJwtSchema,\n} from '@xyo-network/event-kit-schemas'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport { PayloadBuilder } from '@xyo-network/sdk'\n/** The wallet-JWT profile commits to the complete strict source-aware body. */\nexport function createAccountSourceWakeSigner(options: {\n readonly account: AccountInstance\n readonly nowSeconds?: () => number\n readonly publisher: string\n}) {\n const publisher = NormalizedAddressZod.parse(options.publisher)\n if (String(options.account.address).replace(/^0x/u, '').toLowerCase() !== publisher)\n throw new Error('Publisher signing account mismatch')\n return {\n async sign(input: WakeEnvelope, audience: string) {\n const event = WakeEnvelopeZod.parse(input)\n const eventHash = await PayloadBuilder.dataHash(event)\n const now = options.nowSeconds?.() ?? Math.floor(Date.now() / 1000)\n if (!Number.isSafeInteger(now) || now < 0)\n throw new Error('Publisher signing clock is invalid')\n const { token: jwt } = await options.account.signJwt({\n audience,\n claims: { eventHash, jti: randomBytes(16).toString('hex') },\n now,\n schema: WakeJwtSchema,\n ttl: 60,\n })\n return {\n event, eventHash, jwt, publisher,\n }\n },\n }\n}\n", "import { FetchJsonClient } from '@ariestools/sdk'\nimport type { AccountInstance } from '@xyo-network/sdk'\nimport type {\n GatewaySession, XyoGateway, XyoGatewayRunner,\n} from '@xyo-network/xl1-sdk'\nimport {\n baseConfigFactoryLocator, basicRestRunnerLocator, basicRestViewerLocator, creatableProvider,\n releaseProviderFactoryLocator, RestDataLakeRunner, RestDataLakeViewer, XyoGatewayMoniker, XyoGatewayRunnerMoniker,\n} from '@xyo-network/xl1-sdk'\nexport interface PublisherRestGatewayOptions {\n readonly chainStateUrl: string\n readonly fetchFn: typeof globalThis.fetch\n readonly finalizedUrl: string\n readonly indexUrl?: string\n readonly rpcUrl: string\n}\n/** Owned public SDK REST gateway; only the optional mutation runner uses RPC. */\nexport function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account: AccountInstance\n}): Promise<GatewaySession<XyoGatewayRunner>>\nexport function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account?: undefined\n}): Promise<GatewaySession<XyoGateway>>\nexport async function openPublisherRestGateway(options: PublisherRestGatewayOptions & {\n readonly account?: AccountInstance\n}): Promise<GatewaySession<XyoGateway | XyoGatewayRunner>> {\n const rest = {\n finalized: { type: 'rest' as const, baseUrl: options.finalizedUrl },\n chainState: { type: 'rest' as const, baseUrl: options.chainStateUrl },\n index: { type: 'rest' as const, baseUrl: options.indexUrl ?? options.finalizedUrl },\n }\n const locator = options.account === undefined\n ? await basicRestViewerLocator('event-kit-publisher-read', rest, undefined, { fetchFn: options.fetchFn, primeCaches: 'off' })\n : await basicRestRunnerLocator('event-kit-publisher-write', rest, undefined, {\n fetchFn: options.fetchFn, primeCaches: 'off', rpcUrl: options.rpcUrl, signerAccount: options.account,\n })\n try {\n const gateway = options.account === undefined\n ? await locator.getInstance<XyoGateway>(XyoGatewayMoniker)\n : await locator.getInstance<XyoGatewayRunner>(XyoGatewayRunnerMoniker)\n let stopping: Promise<void> | undefined\n return Object.freeze({ gateway, stop: () => stopping ??= releaseProviderFactoryLocator(locator) })\n } catch (error) {\n await releaseProviderFactoryLocator(locator)\n throw error\n }\n}\n@creatableProvider()\nclass BoundedRestDataLakeViewer extends RestDataLakeViewer {\n override get client() {\n if (this.context.fetchFn === undefined)\n throw new Error('Publisher datalake requires its bounded fetch transport')\n return new FetchJsonClient({ fetcher: this.context.fetchFn })\n }\n}\n@creatableProvider()\nclass BoundedRestDataLakeRunner extends RestDataLakeRunner {\n override get client() {\n if (this.context.fetchFn === undefined)\n throw new Error('Publisher datalake requires its bounded fetch transport')\n return new FetchJsonClient({ fetcher: this.context.fetchFn })\n }\n}\n/** Keeps SDK datalake methods and response semantics, overriding only its per-instance HTTP client. */\nexport async function openPublisherDataLake(options: {\n readonly fetchFn: typeof globalThis.fetch\n readonly url: string\n readonly writable: boolean\n}) {\n const locator = await baseConfigFactoryLocator({\n connections: { 'event-kit-lake': { type: 'rest', baseUrl: options.url } },\n providerBindings: { DataLakeViewer: { connection: 'event-kit-lake' }, DataLakeRunner: { connection: 'event-kit-lake' } },\n })\n locator.context.fetchFn = options.fetchFn\n locator.register(BoundedRestDataLakeViewer.factory<BoundedRestDataLakeViewer>(BoundedRestDataLakeViewer.dependencies))\n if (options.writable)\n locator.register(BoundedRestDataLakeRunner.factory<BoundedRestDataLakeRunner>(BoundedRestDataLakeRunner.dependencies))\n locator.freeze()\n try {\n const reader = await locator.getInstance<BoundedRestDataLakeViewer>(BoundedRestDataLakeViewer.defaultMoniker)\n const writer = options.writable ? await locator.getInstance<BoundedRestDataLakeRunner>(BoundedRestDataLakeRunner.defaultMoniker) : undefined\n return {\n reader, writer, async close() { await releaseProviderFactoryLocator(locator) },\n }\n } catch (error) {\n await releaseProviderFactoryLocator(locator)\n throw error\n }\n}\n", "import { isDeepStrictEqual } from 'node:util'\n\nimport type { PublisherEndpointChallengeRecord, PublisherEndpointChallengeStore } from '@xyo-network/event-kit-protocol'\nimport { endpointChallengeHash } from '@xyo-network/event-kit-protocol'\nimport {\n Base64Url32BytesZod, EndpointChallengeZod, HandshakeIdZod, HashZod, NormalizedAddressZod,\n} from '@xyo-network/event-kit-schemas'\nimport type { EventKitReplayCheckpointStore } from '@xyo-network/event-kit-statement-graph'\nimport type {\n FinalizedStatementPublicationIntent, FinalizedStatementPublicationJournal, FinalizedStatementPublicationRecord,\n} from '@xyo-network/event-kit-xl1'\nimport { z } from 'zod'\n\nimport type { PublisherEncryptionKeyCustody } from '../handshakeClients.ts'\nimport type { HandshakeMutationIntent, HandshakeMutationIntentStore } from '../handshakeMutationIntent.ts'\nimport {\n assertSameIntentBinding, intentLookupKey, parseHandshakeMutationIntent,\n} from '../handshakeMutationIntent.ts'\nimport type { SqlitePublisherState } from './sqlitePublisherState.ts'\n\nconst KeyZod = z.strictObject({\n encryptionKey: HashZod, keyId: HandshakeIdZod, privateKey: Base64Url32BytesZod, publisher: NormalizedAddressZod,\n})\nconst phases = ['signed', 'content-written', 'content-verified', 'broadcast', 'included', 'finalized'] as const\n\nfunction requireTime(value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new Error('Publisher clock is invalid')\n}\n\nfunction samePublicationIntent(left: FinalizedStatementPublicationIntent, right: FinalizedStatementPublicationIntent): boolean {\n return left.chainId === right.chainId && left.source === right.source && left.operationId === right.operationId\n && isDeepStrictEqual(left.eventHashes, right.eventHashes) && isDeepStrictEqual(left.attachmentHashes, right.attachmentHashes)\n}\n\nfunction publicationKey(intent: FinalizedStatementPublicationIntent): string {\n if (!/^[0-9a-f]{40}$/u.test(intent.chainId) || !/^[0-9a-f]{40}$/u.test(intent.source)\n || intent.operationId.length === 0 || intent.operationId.length > 256\n || [...intent.eventHashes, ...intent.attachmentHashes].some(hash => !HashZod.safeParse(hash).success)) {\n throw new Error('Invalid publication intent')\n }\n return JSON.stringify([intent.chainId, intent.source, intent.operationId])\n}\n\n/** All handshake durability uses the same single-owner SQLite authority as delivery. */\nexport function createSqlitePublisherHandshakeStores(state: SqlitePublisherState, options: { readonly replayNamespace?: string } = {}): {\n readonly challenges: PublisherEndpointChallengeStore\n readonly intents: HandshakeMutationIntentStore\n readonly journal: FinalizedStatementPublicationJournal\n readonly keys: PublisherEncryptionKeyCustody\n readonly replay: EventKitReplayCheckpointStore\n} {\n const replayKey = options.replayNamespace === undefined ? 'checkpoint' : `checkpoint:${z.string().min(1).max(128).regex(/^[A-Za-z0-9_-]+$/u).parse(options.replayNamespace)}`\n const replay: EventKitReplayCheckpointStore = {\n load: async () => state.get('replay', replayKey),\n async save(checkpoint) { state.set('replay', replayKey, checkpoint) },\n }\n const intents: HandshakeMutationIntentStore = {\n async get(lookup) {\n const value = state.get('intents', intentLookupKey(lookup))\n return value === undefined ? undefined : await parseHandshakeMutationIntent(value)\n },\n async getOrCreate(raw) {\n const proposed = await parseHandshakeMutationIntent(raw) as typeof raw\n return state.transaction(() => {\n const key = intentLookupKey(proposed)\n const winner = state.get<HandshakeMutationIntent>('intents', key)\n if (winner !== undefined) {\n assertSameIntentBinding(winner, proposed)\n return { disposition: 'resumed' as const, intent: winner as typeof raw }\n }\n state.set('intents', key, proposed)\n return { disposition: 'created' as const, intent: proposed }\n })\n },\n }\n const keys: PublisherEncryptionKeyCustody = {\n async getPrivateKey(input) {\n const key = `${NormalizedAddressZod.parse(input.publisher)}:${HandshakeIdZod.parse(input.keyId)}`\n const raw = state.get('encryption-keys', key)\n if (raw === undefined) return\n const record = KeyZod.parse(raw)\n if (record.encryptionKey !== HashZod.parse(input.encryptionKey)) throw new Error('Encryption key identity mismatch')\n const { publisher: _publisher, ...privateKey } = record\n return privateKey\n },\n async putPrivateKey(input) {\n const record = KeyZod.parse({ ...input.key, publisher: input.publisher })\n return state.transaction(() => {\n const key = `${record.publisher}:${record.keyId}`\n const prior = state.get('encryption-keys', key)\n if (prior !== undefined) {\n if (!isDeepStrictEqual(prior, record)) throw new Error('Encryption key collision')\n return 'duplicate'\n }\n state.set('encryption-keys', key, record)\n return 'stored'\n })\n },\n }\n const current = (hash: string) => state.get<PublisherEndpointChallengeRecord>('challenges', HashZod.parse(hash))\n const live = (record: PublisherEndpointChallengeRecord, now: number) => record.challenge.issuedAt <= now && now < record.challenge.expiresAt\n const challenges: PublisherEndpointChallengeStore = {\n get: async hash => current(hash),\n async issue(input) {\n const challenge = EndpointChallengeZod.parse(input.challenge)\n const hash = HashZod.parse(input.challengeHash)\n if (await endpointChallengeHash(challenge) !== hash) return { kind: 'collision' }\n return state.transaction(() => {\n const priorNonce = state.get<string>('challenge-nonces', challenge.nonce)\n if (priorNonce !== undefined && priorNonce !== hash) return { kind: 'collision' as const }\n const prior = current(hash)\n if (prior !== undefined) return isDeepStrictEqual(prior.challenge, challenge)\n ? { kind: 'duplicate' as const, record: prior }\n : { kind: 'collision' as const }\n const record: PublisherEndpointChallengeRecord = {\n challenge, challengeHash: hash, state: 'issued',\n }\n state.set('challenge-nonces', challenge.nonce, hash)\n state.set('challenges', hash, record)\n return { kind: 'issued' as const, record }\n })\n },\n async beginAttempt(input) {\n requireTime(input.nowSeconds)\n return state.transaction(() => {\n const record = current(input.challengeHash)\n if (record === undefined) return { kind: 'missing' as const }\n if (record.state === 'verified') return { kind: 'verified' as const, record }\n if (record.state === 'attempted') return { kind: 'already-attempted' as const, record }\n if (!live(record, input.nowSeconds)) return { kind: 'expired' as const, record }\n const attempted: PublisherEndpointChallengeRecord = { ...record, state: 'attempted' }\n state.set('challenges', input.challengeHash, attempted)\n return { kind: 'started' as const, record: attempted }\n })\n },\n async completeVerified(input) {\n requireTime(input.nowSeconds)\n const responseHash = HashZod.parse(input.responseHash)\n return state.transaction(() => {\n const record = current(input.challengeHash)\n if (record === undefined) return { kind: 'missing' as const }\n if (record.state === 'verified') return { kind: record.responseHash === responseHash ? 'duplicate' as const : 'collision' as const, record }\n if (record.state !== 'attempted') return { kind: 'not-attempted' as const, record }\n if (!live(record, input.nowSeconds)) return { kind: 'expired' as const, record }\n const verified: PublisherEndpointChallengeRecord = {\n ...record, responseHash, state: 'verified',\n }\n state.set('challenges', input.challengeHash, verified)\n return { kind: 'verified' as const, record: verified }\n })\n },\n }\n const journal: FinalizedStatementPublicationJournal = {\n async load(intent) {\n const key = publicationKey(intent)\n const signed = state.get<FinalizedStatementPublicationRecord>('publication:signed', key)\n if (signed === undefined) return\n if (!samePublicationIntent(signed, intent)) throw new Error('Publication intent collision')\n let latest = signed\n for (const phase of phases) {\n const record = state.get<FinalizedStatementPublicationRecord>(`publication:${phase}`, key)\n if (record === undefined) continue\n if (record.phase !== phase || !samePublicationIntent(record, intent) || !isDeepStrictEqual(record.evidence, signed.evidence)) {\n throw new Error('Publication evidence collision')\n }\n latest = record\n }\n return latest\n },\n async save(record) {\n const key = publicationKey(record)\n HashZod.parse(record.evidence.transactionHash)\n if (!phases.includes(record.phase)) throw new Error('Unknown publication phase')\n state.transaction(() => {\n const signed = state.get<FinalizedStatementPublicationRecord>('publication:signed', key)\n if (signed === undefined && record.phase !== 'signed') throw new Error('Publication must bind signed evidence first')\n if (signed !== undefined && (!samePublicationIntent(signed, record) || !isDeepStrictEqual(signed.evidence, record.evidence))) {\n throw new Error('Publication intent or evidence collision')\n }\n const namespace = `publication:${record.phase}`\n const prior = state.get(namespace, key)\n if (prior !== undefined && !isDeepStrictEqual(prior, record)) throw new Error('Publication phase collision')\n if (prior === undefined) state.set(namespace, key, record)\n })\n },\n }\n return {\n challenges, intents, journal, keys, replay,\n }\n}\n", "import {\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 { randomBytes } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport {\n lstat, mkdir, open,\n} from 'node:fs/promises'\nimport { hostname } from 'node:os'\nimport PATH from 'node:path'\n\nimport { stringifyJson } from '../filesystemJson.ts'\nexport interface SqlitePublisherStateOptions {\n /** Immutable chain/publisher binding. A database must never silently change owners. */\n readonly identity: string\n readonly path: string\n}\ninterface JsonRow {\n readonly value: string\n}\ninterface OwnerRow {\n readonly host: string\n readonly pid: number\n readonly token: string\n}\n/** Single-process SQLite authority for publisher checkpoints, custody and delivery records. */\nexport interface SqlitePublisherState {\n readonly path: string\n close(): void\n entries<T>(namespace: string): readonly {\n readonly key: string\n readonly value: T\n }[]\n get<T>(namespace: string, key: string): T | undefined\n insert(namespace: string, key: string, value: unknown): boolean\n remove(namespace: string, key: string): void\n set(namespace: string, key: string, value: unknown): void\n transaction<T>(work: () => T): T\n}\nfunction decode<T>(value: string): T {\n return JSON.parse(value, (_key, candidate: unknown) => {\n return typeof candidate === 'object' && candidate !== null && Object.keys(candidate).length === 1\n && '$eventKitBigInt' in candidate && typeof candidate.$eventKitBigInt === 'string'\n && /^(?:0|[1-9][0-9]*)$/u.test(candidate.$eventKitBigInt)\n ? BigInt(candidate.$eventKitBigInt)\n : candidate\n }) as T\n}\nfunction processExists(pid: number): boolean {\n if (!Number.isSafeInteger(pid) || pid < 1)\n throw new Error('Invalid publisher owner record')\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ESRCH')\n return false\n return true\n }\n}\nexport async function openSqlitePublisherState(options: SqlitePublisherStateOptions): Promise<SqlitePublisherState> {\n if (options.path === ':memory:' || options.identity.length === 0)\n throw new Error('Persistent publisher needs a file and an identity')\n const path = PATH.resolve(options.path)\n const directory = PATH.dirname(path)\n await mkdir(directory, { recursive: true, mode: 0o700 })\n const metadata = await lstat(directory)\n if (!metadata.isDirectory() || (metadata.mode & 0o077) !== 0)\n throw new Error('Publisher state directory must be a real directory with 0700 permissions')\n const file = await open(path, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW, 0o600)\n try {\n const metadata = await file.stat()\n if (!metadata.isFile() || (metadata.mode & 0o077) !== 0)\n throw new Error('Publisher database permissions must be 0600')\n await file.sync()\n } finally {\n await file.close()\n }\n const { DatabaseSync } = await import('node:sqlite')\n const database = new DatabaseSync(path)\n const token = randomBytes(16).toString('hex')\n let closed = false\n let inTransaction = false\n const transaction = <T>(work: () => T): T => {\n if (closed)\n throw new Error('Publisher state is closed')\n if (inTransaction)\n return work()\n database.exec('BEGIN IMMEDIATE')\n inTransaction = true\n try {\n const result = work()\n if (result instanceof Promise)\n throw new TypeError('Publisher state transactions must be synchronous')\n database.exec('COMMIT')\n return result\n } catch (error) {\n database.exec('ROLLBACK')\n throw error\n } finally {\n inTransaction = false\n }\n }\n try {\n database.exec(`\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = FULL;\n PRAGMA busy_timeout = 5000;\n CREATE TABLE IF NOT EXISTS publisher_records (namespace TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY(namespace, key));\n CREATE TABLE IF NOT EXISTS publisher_owner (id INTEGER PRIMARY KEY CHECK(id = 1), host TEXT NOT NULL, pid INTEGER NOT NULL, token TEXT NOT NULL);\n `)\n transaction(() => {\n const prior = database.prepare('SELECT host, pid, token FROM publisher_owner WHERE id = 1').get() as OwnerRow | undefined\n if (prior !== undefined && (prior.host !== hostname() || processExists(prior.pid))) {\n throw new Error('Publisher database already has an active owner; a shared or multi-host database is not supported')\n }\n const binding = database.prepare('SELECT value FROM publisher_records WHERE namespace = ? AND key = ?').get('metadata', 'identity') as JsonRow | undefined\n if (binding !== undefined && decode(binding.value) !== options.identity)\n throw new Error('Publisher database identity mismatch')\n database.prepare('INSERT OR IGNORE INTO publisher_records(namespace,key,value) VALUES (?,?,?)').run('metadata', 'identity', stringifyJson(options.identity))\n database.prepare('INSERT OR REPLACE INTO publisher_owner(id,host,pid,token) VALUES (1,?,?,?)').run(hostname(), process.pid, token)\n })\n } catch (error) {\n database.close()\n throw error\n }\n const read = database.prepare('SELECT value FROM publisher_records WHERE namespace = ? AND key = ?')\n const list = database.prepare('SELECT key, value FROM publisher_records WHERE namespace = ? ORDER BY key')\n const write = database.prepare('INSERT INTO publisher_records(namespace,key,value) VALUES (?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET value = excluded.value')\n const insert = database.prepare('INSERT OR IGNORE INTO publisher_records(namespace,key,value) VALUES (?,?,?)')\n const remove = database.prepare('DELETE FROM publisher_records WHERE namespace = ? AND key = ?')\n const assertOpen = () => {\n if (closed)\n throw new Error('Publisher state is closed')\n }\n return {\n path,\n get<T>(namespace: string, key: string): T | undefined {\n assertOpen()\n const row = read.get(namespace, key) as JsonRow | undefined\n return row === undefined ? undefined : decode<T>(row.value)\n },\n entries<T>(namespace: string) {\n assertOpen()\n return (list.all(namespace) as {\n key: string\n value: string\n }[]).map(row => ({ key: row.key, value: decode<T>(row.value) }))\n },\n set(namespace, key, value) {\n assertOpen()\n write.run(namespace, key, stringifyJson(value))\n },\n insert(namespace, key, value) {\n assertOpen()\n return insert.run(namespace, key, stringifyJson(value)).changes === 1\n },\n remove(namespace, key) {\n assertOpen()\n remove.run(namespace, key)\n },\n transaction,\n close() {\n if (closed)\n return\n transaction(() => {\n database.prepare('DELETE FROM publisher_owner WHERE id = 1 AND token = ?').run(token)\n })\n database.close()\n closed = true\n },\n }\n}\n", "import { randomBytes } from 'node:crypto'\nimport {\n link, open, rename, unlink,\n} from 'node:fs/promises'\nimport PATH from 'node:path'\n\nimport {\n ensureDurableDirectory,\n syncDirectory,\n writeDurableFile,\n} from './filesystemDurability.ts'\n\nexport interface FilesystemJsonWriteOptions {\n readonly directoryMode?: number\n readonly mode?: number\n}\n\nexport async function readJsonFileStrict(path: string): Promise<unknown> {\n let handle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (errorCode(error) === 'ENOENT') return undefined\n throw error\n }\n try {\n return JSON.parse(await handle.readFile('utf8'), reviveJson) as unknown\n } finally { await handle.close() }\n}\n\n/** Atomically replaces one JSON file after its new bytes have reached disk. */\nexport async function replaceJsonFile(\n path: string,\n value: unknown,\n options: FilesystemJsonWriteOptions = {},\n): Promise<void> {\n const directory = PATH.dirname(path)\n await ensureDurableDirectory(directory, options.directoryMode)\n const tempPath = PATH.join(directory, `.${PATH.basename(path)}.${process.pid}.${suffix()}.tmp`)\n try {\n await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n await rename(tempPath, path)\n await syncDirectory(directory)\n } catch (error) {\n await unlinkIfMissing(tempPath)\n throw error\n }\n}\n\n/**\n * Publishes immutable JSON with an exclusive hard link. Returns `false` when\n * another process already owns the destination.\n */\nexport async function publishJsonFile(\n path: string,\n value: unknown,\n options: FilesystemJsonWriteOptions = {},\n): Promise<boolean> {\n const directory = PATH.dirname(path)\n await ensureDurableDirectory(directory, options.directoryMode)\n const tempPath = PATH.join(directory, `.${PATH.basename(path)}.${process.pid}.${suffix()}.tmp`)\n try {\n await writeDurableFile(tempPath, `${stringifyJson(value)}\\n`, options.mode)\n await link(tempPath, path)\n await syncDirectory(directory)\n return true\n } catch (error) {\n if (errorCode(error) === 'EEXIST') return false\n throw error\n } finally {\n await unlinkIfMissing(tempPath)\n }\n}\n\nfunction suffix(): string {\n return randomBytes(8).toString('hex')\n}\n\nexport function stringifyJson(value: unknown): string {\n return JSON.stringify(value, replaceJsonValue)\n}\n\nfunction replaceJsonValue(_key: string, candidate: unknown): unknown {\n return typeof candidate === 'bigint'\n ? { $eventKitBigInt: candidate.toString() }\n : candidate\n}\n\nfunction reviveJson(_key: string, candidate: unknown): unknown {\n return typeof candidate === 'object'\n && candidate !== null\n && Object.keys(candidate).length === 1\n && '$eventKitBigInt' in candidate\n && typeof candidate.$eventKitBigInt === 'string'\n && /^(?:0|[1-9][0-9]*)$/u.test(candidate.$eventKitBigInt)\n ? BigInt(candidate.$eventKitBigInt)\n : candidate\n}\n\nasync function unlinkIfMissing(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) {\n if (errorCode(error) !== 'ENOENT') throw error\n }\n}\n\nfunction errorCode(error: unknown): unknown {\n return typeof error === 'object' && error !== null && 'code' in error\n ? (error as { code?: unknown }).code\n : undefined\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;AAAA,SAAS,UAAAA,eAAc;;;ACAvB,SAAS,cAAc,kBAAkB;AAGlC,SAAS,oBAAoB,SAAiC,WAAoB;AACvF,QAAM,aAAa,IAAI,gBAAgB;AACvC,QAAM,QAAQ,MAAM,WAAW,MAAM;AACrC,QAAM,QAAQ,cAAc,SAAY,SAAY,WAAW,OAAO,SAAS;AAC/E,SAAO,MAAM;AACb,aAAW,UAAU,SAAS;AAC5B,QAAI,OAAO,QAAS,YAAW,MAAM;AAAA,QAChC,QAAO,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;AAAA,EAC7D;AACA,SAAO;AAAA,IACL,QAAQ,WAAW;AAAA,IACnB,UAAU;AACR,UAAI,UAAU,OAAW,cAAa,KAAK;AAC3C,iBAAW,UAAU,QAAS,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AA+D;AAC/F,QAAM,aAAa,MAAM;AACvB,QAAI;AACF,YAAM,IAAI,MAAM,2BAA2B;AAAA,EAC/C;AACA,SAAO;AAAA,IACL;AAAA,IACA,IAAO,WAAmB,KAA4B;AACpD,iBAAW;AACX,YAAM,MAAM,KAAK,IAAI,WAAW,GAAG;AACnC,aAAO,QAAQ,SAAY,SAAY,OAAU,IAAI,KAAK;AAAA,IAC5D;AAAA,IACA,QAAW,WAAmB;AAC5B,iBAAW;AACX,aAAQ,KAAK,IAAI,SAAS,EAGrB,IAAI,UAAQ,EAAE,KAAK,IAAI,KAAK,OAAO,OAAU,IAAI,KAAK,EAAE,EAAE;AAAA,IACjE;AAAA,IACA,IAAI,WAAW,KAAK,OAAO;AACzB,iBAAW;AACX,YAAM,IAAI,WAAW,KAAK,cAAc,KAAK,CAAC;AAAA,IAChD;AAAA,IACA,OAAO,WAAW,KAAK,OAAO;AAC5B,iBAAW;AACX,aAAO,OAAO,IAAI,WAAW,KAAK,cAAc,KAAK,CAAC,EAAE,YAAY;AAAA,IACtE;AAAA,IACA,OAAO,WAAW,KAAK;AACrB,iBAAW;AACX,aAAO,IAAI,WAAW,GAAG;AAAA,IAC3B;AAAA,IACA;AAAA,IACA,QAAQ;AACN,UAAI;AACF;AACF,kBAAY,MAAM;AAChB,iBAAS,QAAQ,wDAAwD,EAAE,IAAI,KAAK;AAAA,MACtF,CAAC;AACD,eAAS,MAAM;AACf,eAAS;AAAA,IACX;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["Buffer", "Buffer", "request", "response", "Buffer", "Buffer", "isDeepStrictEqual", "z", "isDeepStrictEqual", "isDeepStrictEqual", "randomBytes", "WakeEnvelopeZod", "PayloadBuilder", "z", "isDeepStrictEqual", "head", "isDeepStrictEqual", "Base64Url32BytesZod", "EndpointChallengeZod", "HandshakeIdZod", "HashZod", "NormalizedAddressZod", "z", "EndpointChallengeResponseZod", "NormalizedAddressZod", "z", "NormalizedAddressZod", "lookup", "z", "HashZod", "HandshakeIdZod", "Base64Url32BytesZod", "NormalizedAddressZod", "isDeepStrictEqual", "lookup", "EndpointChallengeZod", "randomBytes", "metadata", "randomBytes"]
|
|
7
7
|
}
|