@dispatch-foo/protocol 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +25 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +3 -0
- package/dist/conformance-adapter.d.ts +1 -0
- package/dist/conformance-adapter.js +11 -0
- package/dist/conformance-adapter.js.map +1 -0
- package/dist/conformance.d.ts +243 -0
- package/dist/conformance.d.ts.map +1 -0
- package/dist/conformance.js +5 -0
- package/dist/constants-CRXF4f7g.js +89 -0
- package/dist/constants-CRXF4f7g.js.map +1 -0
- package/dist/constants-CUM7Sm5u.d.ts +36 -0
- package/dist/constants-CUM7Sm5u.d.ts.map +1 -0
- package/dist/federation/index.d.ts +360 -0
- package/dist/federation/index.d.ts.map +1 -0
- package/dist/federation/index.js +628 -0
- package/dist/federation/index.js.map +1 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/serve-CVPZbCpT.js +672 -0
- package/dist/serve-CVPZbCpT.js.map +1 -0
- package/dist/sqliteStore-BtFP1f8O.d.ts +376 -0
- package/dist/sqliteStore-BtFP1f8O.d.ts.map +1 -0
- package/dist/untrusted-DJNiucEX-tUd9XZzz.d.ts +388 -0
- package/dist/untrusted-DJNiucEX-tUd9XZzz.d.ts.map +1 -0
- package/dist/version-Ds8ZFZLh.js +2490 -0
- package/dist/version-Ds8ZFZLh.js.map +1 -0
- package/package.json +54 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["replica: string","now: () => number","FIELD_PRIME","SMALL_ORDER_Y: ReadonlySet<bigint>","OP_TYPES: readonly OpType[]","SEALED_TYPES: ReadonlySet<string>","STUBBABLE_TYPES: ReadonlySet<string>","h: OpHeader","content: { body?: JsonValue; sealed?: Sealed }","header: OpHeader","blocks: Buffer[]","keys: Sealed['keys']"],"sources":["../../src/federation/hlc.ts","../../src/federation/jcs.ts","../../src/federation/encoding.ts","../../src/federation/keys.ts","../../src/federation/ops.ts","../../src/federation/chain.ts","../../src/federation/fingerprint.ts","../../src/federation/hpke.ts","../../src/federation/seal.ts"],"sourcesContent":["// The largest counter an op's clock may carry: nine digits, far below 2^53,\n// so counters compare exactly. OpClock ticks into the next ms at the bound.\nexport const MAX_HLC_COUNTER = 999_999_999;\n\n// `<ms>.<counter>.<replica>`, compared numerically, since the counter can\n// outgrow its four-digit padding; nine digits at most, per MAX_HLC_COUNTER.\nconst HLC = /^(\\d{13})\\.(\\d{4,9})\\.(.+)$/;\n\nexport interface ParsedHlc {\n ms: number;\n counter: number;\n replica: string;\n}\n\nexport function parseOpHlc(hlc: string): ParsedHlc | null {\n const m = HLC.exec(hlc);\n if (m === null) return null;\n return { ms: Number(m[1]), counter: Number(m[2]), replica: m[3] ?? '' };\n}\n\nexport function compareHlc(a: ParsedHlc, b: ParsedHlc): number {\n if (a.ms !== b.ms) return a.ms < b.ms ? -1 : 1;\n if (a.counter !== b.counter) return a.counter < b.counter ? -1 : 1;\n return 0;\n}\n\n// The one clock rule (FW-R21, spec \"the clock guard\"): how far ahead of the\n// local wall clock a reading may be and still be applied or adopted; an op\n// stamped further ahead waits until the clock catches up.\nexport const MAX_CLOCK_LEAD_MS = 5 * 60 * 1000;\n\n/** Whether a reading's wall time is past the bound for the wall time `nowMs`. */\nexport function aheadOfClock(hlc: string, nowMs: number): boolean {\n const clock = readClamped(hlc);\n return clock !== null && clock.ms > nowMs + MAX_CLOCK_LEAD_MS;\n}\n\nexport function hlcWallMs(hlc: string): number | null {\n return parseOpHlc(hlc)?.ms ?? null;\n}\n\n// Any `<ms>.<counter>.` reading, v1's unbounded counters included, with the\n// counter clamped to MAX_HLC_COUNTER so a clock can adopt it and stay parseable.\nfunction readClamped(hlc: string): { ms: number; counter: number } | null {\n const m = /^(\\d{13})\\.(\\d{4,})\\./.exec(hlc);\n if (m === null) return null;\n return {\n ms: Number(m[1]),\n counter: Math.min(Number(m[2]), MAX_HLC_COUNTER),\n };\n}\n\n// The hybrid logical clock that stamps ops. Its counter never passes\n// MAX_HLC_COUNTER: at the bound a tick moves into the next ms instead.\nexport class OpClock {\n private ms: number;\n private counter: number;\n\n constructor(\n private readonly replica: string,\n last: string | null = null,\n private readonly now: () => number = Date.now\n ) {\n const start = last === null ? null : readClamped(last);\n this.ms = start?.ms ?? 0;\n this.counter = start?.counter ?? 0;\n }\n\n /** A reading for a change made now, after every reading seen so far. */\n tick(): string {\n const wall = this.now();\n if (wall > this.ms) {\n this.ms = wall;\n this.counter = 0;\n } else if (this.counter < MAX_HLC_COUNTER) {\n this.counter += 1;\n } else {\n this.ms += 1;\n this.counter = 0;\n }\n return this.last;\n }\n\n /** Moves past a reading from elsewhere, so the next tick sorts after it,\n * unless it is past the bound (FW-R21); false when it refused. */\n observe(remote: string): boolean {\n const clock = readClamped(remote);\n if (clock === null) return true;\n if (clock.ms > this.now() + MAX_CLOCK_LEAD_MS) return false;\n if (\n clock.ms > this.ms ||\n (clock.ms === this.ms && clock.counter > this.counter)\n ) {\n this.ms = clock.ms;\n this.counter = clock.counter;\n }\n return true;\n }\n\n /** The latest reading, for persisting across restarts. */\n get last(): string {\n return `${String(this.ms).padStart(13, '0')}.${String(this.counter).padStart(4, '0')}.${this.replica}`;\n }\n}\n","// What canonicalize throws for a value JCS cannot write: a lone surrogate, a\n// non-finite number, a type JSON lacks, or nesting past MAX_JSON_DEPTH.\nexport class CanonicalizeError extends TypeError {\n override name = 'CanonicalizeError';\n}\n\n// The deepest nesting of arrays and objects JCS writes. A fixed bound, well\n// under any runtime's stack, gives every peer the same verdict on an op.\nexport const MAX_JSON_DEPTH = 256;\n\n// Under the u flag a pair reads as one code point, so this matches only a\n// lone surrogate, which I-JSON (RFC 8785's input) forbids.\nconst LONE_SURROGATE = /\\p{Cs}/u;\n\nfunction iJsonString(s: string): string {\n if (LONE_SURROGATE.test(s))\n throw new CanonicalizeError('JCS refuses a lone surrogate');\n return JSON.stringify(s);\n}\n\n// JCS with `str` writing each string and key, so only hashed text need refuse.\n// `depth` counts the arrays and objects around `value`; a cycle hits the bound.\nfunction write(\n value: unknown,\n str: (s: string) => string,\n depth: number\n): string {\n if (value === null) return 'null';\n switch (typeof value) {\n case 'boolean':\n return value ? 'true' : 'false';\n case 'number':\n if (!Number.isFinite(value))\n throw new CanonicalizeError('JCS refuses non-finite numbers');\n return JSON.stringify(value);\n case 'string':\n return str(value);\n case 'object': {\n if (depth >= MAX_JSON_DEPTH)\n throw new CanonicalizeError(\n `JCS refuses nesting past ${MAX_JSON_DEPTH}`\n );\n const inner = depth + 1;\n if (Array.isArray(value))\n return `[${value.map((v: unknown) => write(v === undefined ? null : v, str, inner)).join(',')}]`;\n const obj = value as Record<string, unknown>;\n // A comparator-free sort compares UTF-16 code units, as JCS asks.\n const keys = Object.keys(obj)\n .filter((k) => obj[k] !== undefined)\n .sort();\n return `{${keys.map((k) => `${str(k)}:${write(obj[k], str, inner)}`).join(',')}}`;\n }\n default:\n throw new CanonicalizeError(`JCS cannot serialize a ${typeof value}`);\n }\n}\n\n// RFC 8785: keys sorted by UTF-16 code units (JS string order), strings and\n// numbers exactly as JSON.stringify writes them, lone surrogates refused.\nexport function canonicalize(value: unknown): string {\n return write(value, iJsonString, 0);\n}\n\n// canonicalize for text that is never hashed, such as a sealed payload: a lone\n// surrogate is escaped as JSON.stringify writes it rather than refused.\nexport function canonicalizeLenient(value: unknown): string {\n return write(value, JSON.stringify, 0);\n}\n","import { createHash } from 'node:crypto';\n\nconst B64U = /^[A-Za-z0-9_-]*$/;\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';\n\nexport function b64u(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n// Decodes only the one spelling b64u writes: padding, the standard alphabet\n// and stray trailing bits are refused, so no value has a second encoding.\nexport function fromB64u(text: string): Buffer {\n if (!B64U.test(text)) throw new TypeError('not base64url');\n const bytes = Buffer.from(text, 'base64url');\n if (b64u(bytes) !== text) throw new TypeError('not canonical base64url');\n return bytes;\n}\n\nexport function sha256Hex(data: string | Uint8Array): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n// Crockford base32, most significant bit first, no padding.\nexport function crockford32(bytes: Uint8Array): string {\n let out = '';\n let buffer = 0;\n let bits = 0;\n for (const byte of bytes) {\n buffer = ((buffer << 8) | byte) & 0xffff;\n bits += 8;\n while (bits >= 5) {\n out += CROCKFORD.charAt((buffer >>> (bits - 5)) & 31);\n bits -= 5;\n }\n }\n if (bits > 0) out += CROCKFORD.charAt((buffer << (5 - bits)) & 31);\n return out;\n}\n","import {\n createPrivateKey,\n createPublicKey,\n generateKeyPairSync,\n sign,\n verify,\n} from 'node:crypto';\nimport type { KeyObject } from 'node:crypto';\n\nimport { b64u, fromB64u } from './encoding.js';\n\n// The fixed PKCS8 prefix of an Ed25519 private key; the 32-byte seed follows.\nconst ED25519_PKCS8 = Buffer.from('302e020100300506032b657004220420', 'hex');\n\nconst FIELD_PRIME = 2n ** 255n - 19n;\n// The y of an Ed25519 point of order 8; the other is its negation.\nconst ORDER_8_Y =\n 2707385501144840649318225287225658788936804267575313519463743609750303402022n;\n// Every y whose point has order 1, 2, 4 or 8, whatever the sign bit says.\nconst SMALL_ORDER_Y: ReadonlySet<bigint> = new Set([\n 0n,\n 1n,\n FIELD_PRIME - 1n,\n ORDER_8_Y,\n FIELD_PRIME - ORDER_8_Y,\n]);\n\n// True for any spelling of a small-order point, as libsodium refuses: such a\n// key verifies signatures nobody made, so it proves nothing.\nfunction hasSmallOrder(raw: Uint8Array): boolean {\n let y = 0n;\n for (let i = raw.length - 1; i >= 0; i--) y = (y << 8n) | BigInt(raw[i] ?? 0);\n return SMALL_ORDER_Y.has((y & ((1n << 255n) - 1n)) % FIELD_PRIME);\n}\n\n// Privates are PKCS8 DER in base64url; publics are the raw 32 bytes in base64url.\nexport interface ReplicaKeys {\n signPriv: string;\n signPub: string;\n sealPriv: string;\n sealPub: string;\n}\n\nfunction rawPublic(key: KeyObject): string {\n const jwk = key.export({ format: 'jwk' });\n if (typeof jwk.x !== 'string') throw new Error('expected an OKP public key');\n return jwk.x;\n}\n\nexport function generateReplicaKeys(): ReplicaKeys {\n const s = generateKeyPairSync('ed25519');\n const x = generateKeyPairSync('x25519');\n return {\n signPriv: s.privateKey\n .export({ type: 'pkcs8', format: 'der' })\n .toString('base64url'),\n signPub: rawPublic(s.publicKey),\n sealPriv: x.privateKey\n .export({ type: 'pkcs8', format: 'der' })\n .toString('base64url'),\n sealPub: rawPublic(x.publicKey),\n };\n}\n\n// For recovery and invite codes, which carry only a seed.\nexport function ed25519FromSeed(seed: Uint8Array): {\n signPriv: string;\n signPub: string;\n} {\n const der = Buffer.concat([ED25519_PKCS8, Buffer.from(seed)]);\n const key = createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });\n return {\n signPriv: der.toString('base64url'),\n signPub: rawPublic(createPublicKey(key)),\n };\n}\n\nexport function privateKeyOf(der: string): KeyObject {\n return createPrivateKey({ key: fromB64u(der), format: 'der', type: 'pkcs8' });\n}\n\nexport function publicKeyOf(raw: string, crv: 'Ed25519' | 'X25519'): KeyObject {\n return createPublicKey({ key: { kty: 'OKP', crv, x: raw }, format: 'jwk' });\n}\n\n// Works for Ed25519 and X25519 alike: both export `x` in JWK.\nexport function publicOfPrivate(der: string): string {\n return rawPublic(createPublicKey(privateKeyOf(der)));\n}\n\nexport function signText(signPriv: string, text: string): string {\n return b64u(sign(null, Buffer.from(text, 'utf8'), privateKeyOf(signPriv)));\n}\n\n// Never throws: a malformed or small-order key, or a malformed signature, is\n// simply not a valid signature.\nexport function verifyText(\n signPub: string,\n text: string,\n sig: string\n): boolean {\n try {\n if (hasSmallOrder(fromB64u(signPub))) return false;\n return verify(\n null,\n Buffer.from(text, 'utf8'),\n publicKeyOf(signPub, 'Ed25519'),\n fromB64u(sig)\n );\n } catch {\n return false;\n }\n}\n","import type {\n DocStatus,\n LinkRel,\n LinkTarget,\n RevisionCause,\n} from '@dispatch-foo/core';\n\nimport type { Address } from '../address.js';\nimport type { JsonValue, Message } from '../envelope.js';\nimport type { DeliveryVia } from '../store.js';\nimport { sha256Hex } from './encoding.js';\nimport { canonicalize } from './jcs.js';\n\nexport type OpType =\n | 'key'\n | 'roster'\n | 'task'\n | 'presence'\n | 'agent'\n | 'channel'\n | 'mail'\n | 'state'\n | 'memory'\n | 'doc'\n // A2A over a teammate link (P5): only ever on a link's own branch.\n | 'a2a';\n\nexport const OP_TYPES: readonly OpType[] = [\n 'key',\n 'roster',\n 'task',\n 'presence',\n 'agent',\n 'channel',\n 'mail',\n 'state',\n 'memory',\n 'doc',\n 'a2a',\n];\n\n// Mail, state and a2a (teammate links) travel sealed; every other type is\n// board state in the clear.\nexport const SEALED_TYPES: ReadonlySet<string> = new Set([\n 'mail',\n 'state',\n 'a2a',\n]);\n// The types a transport may prune to a stub; board ops are never pruned.\nexport const STUBBABLE_TYPES: ReadonlySet<string> = new Set([\n 'mail',\n 'state',\n 'presence',\n 'a2a',\n]);\n\nexport const MAX_OP_BYTES = 1_048_576;\nexport const MAX_SEALED_RECIPIENTS = 256;\nexport const MAX_STATE_ENTRIES = 500;\n\nexport const REPLICA_ID = /^[A-Za-z0-9._-]{1,32}-[0-9a-f]{8}$/;\n// The `prev` of a replica's key op, the first op of its log.\nexport const ZERO_HASH = '0'.repeat(64);\n\n// Every signature and seal carries its own tag, so none can be replayed as another.\nexport const TAG = {\n op: 'dispatch-op-v2',\n sealed: 'dispatch-sealed-v1',\n ack: 'dispatch-ack-v1',\n relay: 'dispatch-relay-v1',\n invite: 'dispatch-invite-v1',\n recovery: 'dispatch-recovery-v1',\n fingerprint: 'dispatch-fp-v1',\n} as const;\n\nexport interface OpHeader {\n v: 2;\n replica: string; // the publisher\n seq: number; // strictly increasing along its chain; may skip values\n prev: string; // opHash of its previous op; ZERO_HASH on its key op\n hlc: string; // `<ms>.<counter>.<replica>`, strictly increasing along its chain\n type: string; // an OpType, or a newer build's type, which still verifies\n to?: string[]; // sealed types only: recipient replicas, sorted, 1-256\n bodyHash: string; // hex sha256 of JCS({ body?, sealed? })\n}\n\nexport interface Sealed {\n nonce: string; // 12 random bytes\n ct: string; // AES-256-GCM(K, nonce, JCS(payload), aad), 16-byte tag appended\n keys: Record<string, { enc: string; ct: string }>; // per replica in `to`: K sealed to it\n}\n\nexport interface FederatedOp extends OpHeader {\n body?: JsonValue; // plain types; the clear part of a forward\n sealed?: Sealed; // mail and state\n sig: string; // Ed25519 over TAG.op + \"\\n\" + JCS(the header)\n}\n\n// What replaces a pruned op: the header and its signature, unchanged, so the\n// stub verifies exactly as the op did.\nexport interface OpStub extends OpHeader {\n sig: string;\n pruned: true;\n}\n\nexport type LogEntry = FederatedOp | OpStub;\n\nexport interface MailPayload {\n message: Message; // as stored at its origin, `hlc` included, `origin` left out\n targets: MailTarget[]; // the origin's resolution of `to`\n}\n\nexport interface MailTarget {\n recipient: Address;\n via: DeliveryVia;\n homes: string[]; // replicas that deliver it, the origin included when it holds or delivers it\n wakeAt?: string; // task targets of a `wake: 'request'` message: the one replica that may wake it\n}\n\n// A forward is a mail op whose clear body is { forward: FederatedOp } and\n// whose sealed payload, for the one replica in `to`, is this.\nexport interface ForwardPayload {\n target: Address; // one of the original's targets\n key: string; // the original op's content key K\n}\n\nexport interface StatePayload {\n entries: (\n | {\n t: 'delivery';\n message: string;\n recipient: Address;\n state: 'held' | 'pushed' | 'notified' | 'read' | 'answered';\n at: string;\n }\n | {\n t: 'settle';\n question: string;\n answer: string; // the accepted answer's id, or the close's\n closed?: string; // set when the origin closed the question\n at: string;\n }\n | {\n t: 'refused'; // this home refused a remote message\n message: string;\n reason: string; // the MessagingError's code and message\n at: string;\n }\n )[]; // at most MAX_STATE_ENTRIES per op\n}\n\nexport interface KeyBody {\n handle: string; // the handle it asks to be admitted as\n device: string; // the short hostname\n build: string; // the Dispatch version\n signPub: string; // raw 32 bytes, base64url; this op's sig verifies with it\n sealPub: string; // raw 32 bytes, base64url\n legacy: { throughSeq: number; digest: string } | null; // its unsigned v1 history\n invite?: { id: string; sig: string };\n caps?: string[]; // what this build speaks, e.g. 'relay' (FW-R39); absent: none\n}\n\nexport type RosterBody = { rv: 1 } & (\n | {\n action: 'found';\n name: string;\n legacy: LegacyAttestation[];\n recoveryPub: string;\n }\n | {\n action: 'admit';\n replica: string;\n handle: string;\n role: 'member' | 'admin';\n fingerprint: string;\n hosts?: string[]; // handles a shared host serves\n observer?: true; // reads team mail that leaves its senders' machines; speaks for nobody\n }\n | {\n action: 'revoke';\n replica: string;\n afterSeq: number; // its last op that stays valid\n afterHash: string; // opHash of that op, so the cut names one history\n reason: string;\n }\n // A demotion or a removal of hosts carries afterSeq/afterHash too.\n | {\n action: 'role';\n replica: string;\n role: 'member' | 'admin';\n afterSeq?: number;\n afterHash?: string;\n }\n | {\n action: 'hosts';\n replica: string;\n hosts: string[];\n afterSeq?: number;\n afterHash?: string;\n }\n | { action: 'close-legacy'; entries: LegacyAttestation[] }\n | { action: 'license'; key: string } // the organization's signed dispatch1.… key\n | {\n action: 'invite';\n id: string;\n pub: string;\n handle: string;\n expires: string;\n }\n | { action: 'recover'; proof: string }\n | { action: 'recovery-key'; pub: string } // a new recovery code replaces the last\n | { action: 'transport'; kind: 'git' | 'relay'; url?: string }\n // Takes the named roster op, whose (action, rv) is outside Known(1), out of\n // every build's fold when an admin that may dismiss it sends it; no level.\n | { action: 'dismiss'; replica: string; seq: number; hash: string }\n);\n\nexport interface LegacyAttestation {\n replica: string;\n throughSeq: number;\n digest: string; // sha256 over JCS(op) + \"\\n\" for each of its v1 ops with seq ≤ throughSeq, in seq order\n}\n\nexport type PresenceBody =\n | { kind: 'replica'; build: string; device: string; wall: number } // wall = its raw clock, ms\n // FW-R39: the same, re-announcing what this build speaks when it changed.\n | {\n kind: 'replica';\n build: string;\n device: string;\n wall: number;\n caps: string[];\n }\n | {\n kind: 'run';\n run: string;\n task: string | null;\n runKind: string; // execute | review | verify | …\n live: boolean;\n waitingOn?: string; // the handle an open gate or blocking question on this run waits for\n }\n // An admin settles a run two replicas claimed first: it binds to `replica`.\n | { kind: 'resolve'; run: string; replica: string };\n\nexport interface AgentBody {\n address: Address; // agent:<op>/<name>; never agent:*/overseer or agent:*/a2a.*\n displayName: string;\n client: string;\n status: 'pending' | 'approved' | 'revoked';\n}\n\nexport interface ChannelBody {\n channel: string;\n member: Address; // a task or an actor; never a run, a2a:*, agent:*/overseer or agent:*/a2a.*\n joined: boolean; // last writer wins per (channel, member) on the hlc\n}\n\nexport interface MemoryBody {\n memory: string; // mem-<ulid>\n kind: 'put' | 'remove';\n fields?: Record<string, unknown>;\n trust: 'human' | 'confirmed' | 'agent'; // the trust the publisher asserts; receivers recompute it\n by?: string; // who made the change: the latest local revision's author\n}\n\n// A team doc change (docs design \"Team sync\"): a revision, meta fields\n// (last writer wins per field; aliases a union), a review, or a removal.\nexport interface DocBody {\n doc: string; // doc-<ulid>\n kind: 'put' | 'remove';\n by: Address; // who made this change\n revision?: {\n id: string;\n parents: string[];\n title: string;\n body: string;\n hash: string;\n author: Address;\n cause: RevisionCause;\n summary: string;\n createdAt: string;\n approval?: { by: Address; policy?: { rung: number } };\n task?: string; // a proposal's source task, for local policy\n };\n meta?: {\n slug?: string; // the claimed slug in the team namespace\n aliases?: string[]; // retired slugs; a grow-only set\n title?: string;\n status?: DocStatus;\n links?: { target: LinkTarget; rel: LinkRel }[];\n };\n review?: { rev: string }; // `by` reviewed that revision\n}\n\nexport function isStub(e: LogEntry): e is OpStub {\n return 'pruned' in e && e.pruned === true;\n}\n\nexport function headerOf(e: LogEntry): OpHeader {\n const h: OpHeader = {\n v: 2,\n replica: e.replica,\n seq: e.seq,\n prev: e.prev,\n hlc: e.hlc,\n type: e.type,\n bodyHash: e.bodyHash,\n };\n if (e.to !== undefined) h.to = e.to;\n return h;\n}\n\nexport function contentHash(content: {\n body?: JsonValue;\n sealed?: Sealed;\n}): string {\n return sha256Hex(canonicalize(content));\n}\n\nexport function signingInput(h: OpHeader): string {\n return `${TAG.op}\\n${canonicalize(h)}`;\n}\n\n// The same for an op and its stub, so pruning never breaks a chain.\nexport function opHash(e: LogEntry): string {\n return sha256Hex(canonicalize({ ...headerOf(e), sig: e.sig }));\n}\n\nexport function stubOf(op: FederatedOp): OpStub {\n return { ...headerOf(op), sig: op.sig, pruned: true };\n}\n","import type { JsonValue } from '../envelope.js';\nimport { compareHlc, parseOpHlc } from './hlc.js';\nimport { canonicalize } from './jcs.js';\nimport { signText, verifyText } from './keys.js';\nimport {\n contentHash,\n headerOf,\n isStub,\n MAX_OP_BYTES,\n MAX_SEALED_RECIPIENTS,\n opHash,\n REPLICA_ID,\n SEALED_TYPES,\n signingInput,\n STUBBABLE_TYPES,\n ZERO_HASH,\n} from './ops.js';\nimport type { FederatedOp, LogEntry, OpHeader, Sealed } from './ops.js';\n\nconst TYPE = /^[a-z][a-z0-9-]{0,31}$/;\nconst HEX64 = /^[0-9a-f]{64}$/;\n\nexport interface ChainHead {\n seq: number;\n hash: string;\n hlc: string;\n}\n\n// Signs an op. Throws CanonicalizeError for content JCS refuses, and a\n// RangeError for a grammar or sealing rule peers enforce; callers check size.\nexport function buildOp(\n fields: {\n replica: string;\n seq: number;\n prev: string;\n hlc: string;\n type: string;\n body?: JsonValue;\n to?: string[];\n sealed?: Sealed;\n },\n signPriv: string\n): FederatedOp {\n const problem = headerProblem(fields) ?? contentProblem(fields);\n if (problem !== null) throw new RangeError(`cannot sign: ${problem}`);\n const content: { body?: JsonValue; sealed?: Sealed } = {};\n if (fields.body !== undefined) content.body = fields.body;\n if (fields.sealed !== undefined) content.sealed = fields.sealed;\n const header: OpHeader = {\n v: 2,\n replica: fields.replica,\n seq: fields.seq,\n prev: fields.prev,\n hlc: fields.hlc,\n type: fields.type,\n bodyHash: contentHash(content),\n };\n if (fields.to !== undefined) header.to = fields.to;\n return {\n ...header,\n ...content,\n sig: signText(signPriv, signingInput(header)),\n };\n}\n\nconst fail = (reason: string) => ({ ok: false as const, reason });\n\n// 1 to `max` replica ids in strictly ascending order.\nfunction sortedUnique(list: unknown, max: number): boolean {\n if (!Array.isArray(list) || list.length === 0 || list.length > max)\n return false;\n let last = '';\n for (const r of list as unknown[]) {\n if (typeof r !== 'string' || !REPLICA_ID.test(r) || r <= last) return false;\n last = r;\n }\n return true;\n}\n\nfunction sameKeys(sorted: readonly string[], keys: string[]): boolean {\n const other = [...keys].sort();\n return (\n sorted.length === other.length && sorted.every((r, i) => r === other[i])\n );\n}\n\nconst isHex64 = (v: unknown) => typeof v === 'string' && HEX64.test(v);\n\n// The header rules that need no chain: what buildOp checks before signing and\n// verifyEntry after. Null when the fields pass.\nfunction headerProblem(h: {\n replica: unknown;\n seq: unknown;\n prev: unknown;\n hlc: unknown;\n type: unknown;\n to?: unknown;\n}): string | null {\n if (typeof h.replica !== 'string' || !REPLICA_ID.test(h.replica))\n return 'replica id outside the grammar';\n if (typeof h.type !== 'string' || !TYPE.test(h.type)) return 'not a v2 op';\n if (!Number.isSafeInteger(h.seq) || (h.seq as number) < 1)\n return 'seq must rise';\n if (!isHex64(h.prev)) return 'malformed op';\n const clock = typeof h.hlc === 'string' ? parseOpHlc(h.hlc) : null;\n if (clock === null) return 'hlc outside the grammar';\n if (clock.replica !== h.replica) return 'hlc must name its own replica';\n if (h.to !== undefined && !sortedUnique(h.to, MAX_SEALED_RECIPIENTS))\n return 'bad recipient list';\n return null;\n}\n\n// Which content each type carries: what buildOp checks before signing and\n// verifyEntry after the content hash. Null when the op passes.\nfunction contentProblem(e: {\n type: string;\n body?: JsonValue;\n to?: string[];\n sealed?: Sealed;\n}): string | null {\n const sealedType = SEALED_TYPES.has(e.type);\n if (sealedType && e.sealed === undefined)\n return 'sealed types carry sealed content';\n if (e.type === 'state' && e.body !== undefined)\n return 'state ops carry only sealed content';\n if (!sealedType && (e.sealed !== undefined || e.to !== undefined))\n return 'only mail and state are sealed';\n // A forward is a mail op with both a clear body and sealed content.\n if (\n sealedType &&\n (e.to === undefined || !sameKeys(e.to, Object.keys(e.sealed?.keys ?? {})))\n )\n return 'keys must equal to';\n return null;\n}\n\n// What JCS and the checks below need of an entry parsed off the branch: an\n// object with a string `sig` and hex hashes.\nfunction wellFormed(e: unknown): boolean {\n if (typeof e !== 'object' || e === null || Array.isArray(e)) return false;\n const { prev, bodyHash, sig } = e as Record<string, unknown>;\n return typeof sig === 'string' && isHex64(prev) && isHex64(bodyHash);\n}\n\n// Null in place of a throw: JCS refuses a non-finite number, a lone surrogate\n// and nesting past MAX_JSON_DEPTH.\nfunction orNull<T>(step: () => T): T | null {\n try {\n return step();\n } catch {\n return null;\n }\n}\n\n// Checks an entry's grammar, signature, content hash and chain links, but not\n// what its type means. Never throws: anyone can write the branch it came off.\nexport function verifyEntry(\n head: ChainHead | null,\n e: LogEntry,\n signPub: string\n): { ok: true; head: ChainHead } | { ok: false; reason: string } {\n if (!wellFormed(e)) return fail('malformed op');\n if (e.v !== 2) return fail('not a v2 op');\n const problem = headerProblem(e);\n if (problem !== null) return fail(problem);\n // JCS writes JSON.stringify's bytes in another key order, and fails fast on\n // deep nesting where the native stringify spends seconds.\n const bytes = orNull(() => Buffer.byteLength(canonicalize(e)));\n if (bytes === null) return fail('malformed op');\n if (bytes > MAX_OP_BYTES) return fail('over MAX_OP_BYTES');\n if (head === null) {\n if (isStub(e) || e.type !== 'key' || e.prev !== ZERO_HASH)\n return fail('a log must start with its key op');\n } else {\n if (e.type === 'key') return fail('a second key op');\n if (e.prev !== head.hash) return fail('prev does not match');\n if (e.seq <= head.seq) return fail('seq must rise');\n const clock = parseOpHlc(e.hlc);\n const before = parseOpHlc(head.hlc);\n if (clock !== null && before !== null && compareHlc(clock, before) <= 0)\n return fail('hlc must rise');\n }\n if (!verifyText(signPub, signingInput(headerOf(e)), e.sig))\n return fail('bad signature');\n if (isStub(e)) {\n if (!STUBBABLE_TYPES.has(e.type))\n return fail(`a ${e.type} op cannot be a stub`);\n // Stub content is never hashed, so it could claim anything.\n if ('body' in e || 'sealed' in e) return fail('a stub carries no content');\n } else {\n const content: { body?: JsonValue; sealed?: Sealed } = {};\n if (e.body !== undefined) content.body = e.body;\n if (e.sealed !== undefined) content.sealed = e.sealed;\n const hash = orNull(() => contentHash(content));\n if (hash === null) return fail('malformed op');\n if (hash !== e.bodyHash) return fail('bodyHash mismatch');\n const broken = contentProblem(e);\n if (broken !== null) return fail(broken);\n }\n return { ok: true, head: { seq: e.seq, hash: opHash(e), hlc: e.hlc } };\n}\n","import { createHash } from 'node:crypto';\n\nimport { crockford32 } from './encoding.js';\nimport { TAG } from './ops.js';\n\n// What two people compare out of band: the first 15 bytes of a tagged hash\n// over both public keys, as six groups of four Crockford characters.\nexport function fingerprint(signPub: string, sealPub: string): string {\n const digest = createHash('sha256')\n .update(`${TAG.fingerprint}\\n${signPub}\\n${sealPub}`)\n .digest();\n return (crockford32(digest.subarray(0, 15)).match(/.{4}/g) ?? []).join('-');\n}\n","// RFC 9180 base mode for DHKEM(X25519) 0x0020, HKDF-SHA256 0x0001, AES-256-GCM\n// 0x0002. Labeled HKDF uses createHmac, since hkdfSync fuses extract and expand.\nimport {\n createCipheriv,\n createDecipheriv,\n createHmac,\n createPrivateKey,\n diffieHellman,\n generateKeyPairSync,\n} from 'node:crypto';\nimport type { KeyObject } from 'node:crypto';\n\nimport { fromB64u } from './encoding.js';\nimport { publicKeyOf } from './keys.js';\n\nconst i2osp2 = (n: number) => Buffer.from([(n >> 8) & 0xff, n & 0xff]);\nconst KEM_SUITE = Buffer.concat([Buffer.from('KEM'), i2osp2(0x0020)]);\nconst HPKE_SUITE = Buffer.concat([\n Buffer.from('HPKE'),\n i2osp2(0x0020),\n i2osp2(0x0001),\n i2osp2(0x0002),\n]);\nconst V1 = Buffer.from('HPKE-v1');\nconst NH = 32;\nconst NK = 32;\nconst NN = 12;\nconst TAG_BYTES = 16;\nconst EMPTY = Buffer.alloc(0);\n\nfunction extract(salt: Buffer, ikm: Buffer): Buffer {\n return createHmac('sha256', salt.length === 0 ? Buffer.alloc(NH) : salt)\n .update(ikm)\n .digest();\n}\n\nfunction expand(prk: Buffer, info: Buffer, length: number): Buffer {\n const blocks: Buffer[] = [];\n let t = EMPTY;\n for (let i = 1; blocks.length * NH < length; i++) {\n t = createHmac('sha256', prk)\n .update(Buffer.concat([t, info, Buffer.from([i])]))\n .digest();\n blocks.push(t);\n }\n return Buffer.concat(blocks).subarray(0, length);\n}\n\nfunction labeledExtract(\n suite: Buffer,\n salt: Buffer,\n label: string,\n ikm: Buffer\n): Buffer {\n return extract(salt, Buffer.concat([V1, suite, Buffer.from(label), ikm]));\n}\n\nfunction labeledExpand(\n suite: Buffer,\n prk: Buffer,\n label: string,\n info: Buffer,\n length: number\n): Buffer {\n return expand(\n prk,\n Buffer.concat([i2osp2(length), V1, suite, Buffer.from(label), info]),\n length\n );\n}\n\nfunction x25519Public(raw: Buffer): KeyObject {\n return publicKeyOf(raw.toString('base64url'), 'X25519');\n}\n\n// For vectors, which give raw keys: a private X25519 key from its raw bytes.\nexport function x25519Private(raw: Buffer, publicRaw: Buffer): KeyObject {\n return createPrivateKey({\n key: {\n kty: 'OKP',\n crv: 'X25519',\n d: raw.toString('base64url'),\n x: publicRaw.toString('base64url'),\n },\n format: 'jwk',\n });\n}\n\ninterface Ephemeral {\n privateKey: KeyObject;\n publicRaw: Buffer;\n}\n\nfunction freshEphemeral(): Ephemeral {\n const pair = generateKeyPairSync('x25519');\n const { x } = pair.publicKey.export({ format: 'jwk' });\n if (typeof x !== 'string') throw new Error('expected an OKP public key');\n return { privateKey: pair.privateKey, publicRaw: fromB64u(x) };\n}\n\nfunction sharedSecretOf(dh: Buffer, enc: Buffer, pkR: Buffer): Buffer {\n const eaePrk = labeledExtract(KEM_SUITE, EMPTY, 'eae_prk', dh);\n return labeledExpand(\n KEM_SUITE,\n eaePrk,\n 'shared_secret',\n Buffer.concat([enc, pkR]),\n NH\n );\n}\n\n// The ephemeral key is fresh unless a test vector supplies one.\nexport function encap(\n pkR: Buffer,\n ephemeral: Ephemeral = freshEphemeral()\n): { sharedSecret: Buffer; enc: Buffer } {\n const dh = diffieHellman({\n privateKey: ephemeral.privateKey,\n publicKey: x25519Public(pkR),\n });\n return {\n sharedSecret: sharedSecretOf(dh, ephemeral.publicRaw, pkR),\n enc: ephemeral.publicRaw,\n };\n}\n\nexport function decap(enc: Buffer, skR: KeyObject, pkR: Buffer): Buffer {\n const dh = diffieHellman({ privateKey: skR, publicKey: x25519Public(enc) });\n return sharedSecretOf(dh, enc, pkR);\n}\n\nexport function keySchedule(\n sharedSecret: Buffer,\n info: Buffer\n): { key: Buffer; baseNonce: Buffer } {\n const pskIdHash = labeledExtract(HPKE_SUITE, EMPTY, 'psk_id_hash', EMPTY);\n const infoHash = labeledExtract(HPKE_SUITE, EMPTY, 'info_hash', info);\n const context = Buffer.concat([Buffer.from([0x00]), pskIdHash, infoHash]);\n const secret = labeledExtract(HPKE_SUITE, sharedSecret, 'secret', EMPTY);\n return {\n key: labeledExpand(HPKE_SUITE, secret, 'key', context, NK),\n baseNonce: labeledExpand(HPKE_SUITE, secret, 'base_nonce', context, NN),\n };\n}\n\n// base_nonce XOR I2OSP(seq, Nn); the vectors check every step from 0 to 256.\nexport function nonceFor(baseNonce: Buffer, seq: number): Buffer {\n const nonce = Buffer.from(baseNonce);\n let rest = seq;\n for (let i = nonce.length - 1; i >= 0 && rest > 0; i--) {\n nonce.writeUInt8(nonce.readUInt8(i) ^ (rest & 0xff), i);\n rest = Math.floor(rest / 256);\n }\n return nonce;\n}\n\n// AES-256-GCM with its 16-byte tag appended to the ciphertext.\nexport function aeadSeal(\n key: Buffer,\n nonce: Buffer,\n aad: Buffer,\n pt: Buffer\n): Buffer {\n const c = createCipheriv('aes-256-gcm', key, nonce);\n c.setAAD(aad);\n return Buffer.concat([c.update(pt), c.final(), c.getAuthTag()]);\n}\n\n// Throws when the tag does not verify.\nexport function aeadOpen(\n key: Buffer,\n nonce: Buffer,\n aad: Buffer,\n ct: Buffer\n): Buffer {\n if (ct.length < TAG_BYTES) throw new RangeError('ciphertext too short');\n const d = createDecipheriv('aes-256-gcm', key, nonce);\n d.setAAD(aad);\n d.setAuthTag(ct.subarray(ct.length - TAG_BYTES));\n return Buffer.concat([\n d.update(ct.subarray(0, ct.length - TAG_BYTES)),\n d.final(),\n ]);\n}\n\n// Single-shot: one context seals exactly once, at sequence 0.\nexport function sealBase(\n pkR: Buffer,\n info: Buffer,\n pt: Buffer\n): { enc: Buffer; ct: Buffer } {\n const { sharedSecret, enc } = encap(pkR);\n const { key, baseNonce } = keySchedule(sharedSecret, info);\n return { enc, ct: aeadSeal(key, baseNonce, EMPTY, pt) };\n}\n\nexport function openBase(\n enc: Buffer,\n skR: KeyObject,\n pkR: Buffer,\n info: Buffer,\n ct: Buffer\n): Buffer {\n const { key, baseNonce } = keySchedule(decap(enc, skR, pkR), info);\n return aeadOpen(key, baseNonce, EMPTY, ct);\n}\n","import { randomBytes } from 'node:crypto';\n\nimport type { JsonValue } from '../envelope.js';\nimport { b64u, fromB64u } from './encoding.js';\nimport { aeadOpen, aeadSeal, encap, openBase, sealBase } from './hpke.js';\nimport { canonicalizeLenient } from './jcs.js';\nimport { privateKeyOf, publicOfPrivate } from './keys.js';\nimport { MAX_SEALED_RECIPIENTS, REPLICA_ID, TAG } from './ops.js';\nimport type { FederatedOp, Sealed } from './ops.js';\n\nconst CONTENT_KEY_BYTES = 32;\nconst NONCE_BYTES = 12;\nconst X25519_PUBLIC_BYTES = 32;\nconst FIELD_PRIME = 2n ** 255n - 19n;\n\n// Binds a ciphertext to its op, so it cannot be moved into another one.\nexport function sealedAad(replica: string, seq: number, type: string): string {\n return `${TAG.sealed}\\n${replica}\\n${seq}\\n${type}`;\n}\n\n// Encrypts the payload once under a random key K, wrapped per recipient by HPKE\n// whose `info` names them. Throws a RangeError for recipients it cannot seal to.\nexport function sealPayload(input: {\n replica: string;\n seq: number;\n type: 'mail' | 'state' | 'a2a';\n payload: JsonValue;\n recipients: ReadonlyMap<string, string>;\n}): { to: string[]; sealed: Sealed; key: Buffer } {\n const to = [...input.recipients.keys()].sort();\n if (to.length === 0 || to.length > MAX_SEALED_RECIPIENTS)\n throw new RangeError(\n `a sealed op names 1-${MAX_SEALED_RECIPIENTS} recipients`\n );\n for (const r of to) {\n if (!REPLICA_ID.test(r)) throw new RangeError(`${r} is not a replica id`);\n if (!canSealTo(input.recipients.get(r) ?? ''))\n throw new RangeError(`cannot seal to ${r}: its sealPub is unusable`);\n }\n const key = randomBytes(CONTENT_KEY_BYTES);\n const nonce = randomBytes(NONCE_BYTES);\n const aad = sealedAad(input.replica, input.seq, input.type);\n const ct = aeadSeal(\n key,\n nonce,\n Buffer.from(aad),\n Buffer.from(canonicalizeLenient(input.payload))\n );\n const keys: Sealed['keys'] = {};\n for (const r of to)\n keys[r] = wrapContentKey(key, aad, r, input.recipients.get(r) ?? '');\n return { to, sealed: { nonce: b64u(nonce), ct: b64u(ct), keys }, key };\n}\n\n// True for a canonical X25519 key (bit 255 clear, u below p) not of low order.\n// Sealing to any other throws, or makes a wrap its owner cannot open.\nexport function canSealTo(sealPub: string): boolean {\n try {\n const raw = fromB64u(sealPub);\n if (raw.length !== X25519_PUBLIC_BYTES) return false;\n // Little-endian, so bit 255 set also lands at or above p.\n const u = BigInt(`0x${Buffer.from(raw).reverse().toString('hex')}`);\n if (u >= FIELD_PRIME) return false;\n encap(raw);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function wrapContentKey(\n key: Buffer,\n aad: string,\n recipient: string,\n sealPub: string\n): { enc: string; ct: string } {\n const { enc, ct } = sealBase(\n fromB64u(sealPub),\n Buffer.from(`${aad}\\n${recipient}`),\n key\n );\n return { enc: b64u(enc), ct: b64u(ct) };\n}\n\n// Null when the op is not sealed to `me` or any part fails to open.\nexport function unwrapContentKey(\n op: FederatedOp,\n me: string,\n sealPriv: string\n): Buffer | null {\n const wrap = op.sealed?.keys[me];\n if (wrap === undefined) return null;\n try {\n const skR = privateKeyOf(sealPriv);\n const pkR = fromB64u(publicOfPrivate(sealPriv));\n const aad = sealedAad(op.replica, op.seq, op.type);\n return openBase(\n fromB64u(wrap.enc),\n skR,\n pkR,\n Buffer.from(`${aad}\\n${me}`),\n fromB64u(wrap.ct)\n );\n } catch {\n return null;\n }\n}\n\n// Opens the payload with a content key already in hand, as a forward carries.\nexport function openWithKey(op: FederatedOp, key: Buffer): JsonValue | null {\n if (op.sealed === undefined) return null;\n try {\n const aad = sealedAad(op.replica, op.seq, op.type);\n const pt = aeadOpen(\n key,\n fromB64u(op.sealed.nonce),\n Buffer.from(aad),\n fromB64u(op.sealed.ct)\n );\n return JSON.parse(pt.toString('utf8')) as JsonValue;\n } catch {\n return null;\n }\n}\n\nexport function openPayload(\n op: FederatedOp,\n me: string,\n sealPriv: string\n): JsonValue | null {\n const key = unwrapContentKey(op, me, sealPriv);\n return key === null ? null : openWithKey(op, key);\n}\n"],"mappings":";;;AAEA,MAAa,kBAAkB;AAI/B,MAAM,MAAM;AAQZ,SAAgB,WAAW,KAA+B;CACxD,MAAM,IAAI,IAAI,KAAK,IAAI;AACvB,KAAI,MAAM,KAAM,QAAO;AACvB,QAAO;EAAE,IAAI,OAAO,EAAE,GAAG;EAAE,SAAS,OAAO,EAAE,GAAG;EAAE,SAAS,EAAE,MAAM;EAAI;;AAGzE,SAAgB,WAAW,GAAc,GAAsB;AAC7D,KAAI,EAAE,OAAO,EAAE,GAAI,QAAO,EAAE,KAAK,EAAE,KAAK,KAAK;AAC7C,KAAI,EAAE,YAAY,EAAE,QAAS,QAAO,EAAE,UAAU,EAAE,UAAU,KAAK;AACjE,QAAO;;AAMT,MAAa,oBAAoB,MAAS;;AAG1C,SAAgB,aAAa,KAAa,OAAwB;CAChE,MAAM,QAAQ,YAAY,IAAI;AAC9B,QAAO,UAAU,QAAQ,MAAM,KAAK,QAAQ;;AAG9C,SAAgB,UAAU,KAA4B;AACpD,QAAO,WAAW,IAAI,EAAE,MAAM;;AAKhC,SAAS,YAAY,KAAqD;CACxE,MAAM,IAAI,wBAAwB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,QAAO;AAC/B,KAAI;EACF,MAAM,MAAM,aAAa,SAAS;EAClC,MAAM,MAAM,SAAS,gBAAgB,SAAS,CAAC;EAC/C,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,KAAK,GAAG,KAAK;AAClD,SAAO,SACL,SAAS,KAAK,IAAI,EAClB,KACA,KACA,OAAO,KAAK,GAAG,IAAI,IAAI,KAAK,EAC5B,SAAS,KAAK,GAAG,CAClB;SACK;AACN,SAAO;;;AAKX,SAAgB,YAAY,IAAiB,KAA+B;AAC1E,KAAI,GAAG,WAAW,OAAW,QAAO;AACpC,KAAI;EACF,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,KAAK,GAAG,KAAK;EAClD,MAAM,KAAK,SACT,KACA,SAAS,GAAG,OAAO,MAAM,EACzB,OAAO,KAAK,IAAI,EAChB,SAAS,GAAG,OAAO,GAAG,CACvB;AACD,SAAO,KAAK,MAAM,GAAG,SAAS,OAAO,CAAC;SAChC;AACN,SAAO;;;AAIX,SAAgB,YACd,IACA,IACA,UACkB;CAClB,MAAM,MAAM,iBAAiB,IAAI,IAAI,SAAS;AAC9C,QAAO,QAAQ,OAAO,OAAO,YAAY,IAAI,IAAI"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { a as GATE_RAISERS, c as MARKERS, d as REF_TYPES, f as SYSTEM_ADDRESS, g as raiserOf, h as isDecidingAuthor, i as ERROR_CODES, l as MAX_ADDRESS_BYTES, m as hasGateData, n as BUILT_IN_KINDS, o as GATE_TYPES, p as gateTypeOf, r as DELIVERY_STATES, s as GateRaiser, t as ADDRESS_SCHEMES, u as MAX_SEGMENT_BYTES } from "./constants-CUM7Sm5u.js";
|
|
2
|
+
import { A as ValidateOptions, B as parseAddress, C as JsonValue, D as Ref, E as MessageKind, F as Address, I as PEER_ALIAS_PATTERN, L as ParsedAddress, M as gateOf, N as isSystemMarker, O as RefType, P as validateSendInput, R as isAgentAuthored, S as GateData, T as Message, _ as SettledAs, b as ThreadSummary, c as ChannelRecord, d as DeliveryState, f as DeliveryVia, g as RemoteState, h as RemoteDelivery, j as checkIdempotencyKey, k as SendInput, l as Delivery, m as REMOTE_STATES, o as AgentRecord, p as MessageStore, s as AgentStatus, u as DeliveryFilter, v as Settlement, w as MEMORY_GATE_KINDS, x as BuiltInKind, y as StoredMeta, z as isPeerAddress } from "./untrusted-DJNiucEX-tUd9XZzz.js";
|
|
3
|
+
import { C as RefusedEntry, D as StateEntry, E as SettleEntry, O as WakeResult, S as PolicyRuling, T as RemoteTarget, _ as ExternalTarget, a as openMessagesDb, b as Placement, c as EngineEvent, d as SendOptions, f as SendResult, g as ExternalKind, h as ExternalAdmission, i as SqliteMessageStore, l as EngineLimits, m as DeliveryEntry, n as ConversationPage, o as DEFAULT_LIMITS, p as Sender, r as MESSAGES_DB_VERSION, s as DeliveryEngine, t as ConversationMatch, u as ReceiveResult, v as FederationHooks, w as RemoteOrigin, x as PolicyRequest, y as MessagingHost } from "./sqliteStore-BtFP1f8O.js";
|
|
4
|
+
|
|
5
|
+
//#region src/errors.d.ts
|
|
6
|
+
type MessagingErrorCode = keyof typeof ERROR_CODES;
|
|
7
|
+
declare class MessagingError extends Error {
|
|
8
|
+
readonly code: MessagingErrorCode;
|
|
9
|
+
readonly field?: string | undefined;
|
|
10
|
+
constructor(code: MessagingErrorCode, message: string, field?: string | undefined);
|
|
11
|
+
}
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/localOnly.d.ts
|
|
14
|
+
/** Markers that never leave the machine: the registry's plus the policy engine's. */
|
|
15
|
+
declare const LOCAL_ONLY_MARKERS: readonly string[];
|
|
16
|
+
/** Overseer and A2A identities: never federated, never in channel or agent ops. */
|
|
17
|
+
declare function isFederationLocalAddress(address: Address): boolean;
|
|
18
|
+
type LocalOnlyReason = 'gate' | 'marker' | 'participant' | 'root';
|
|
19
|
+
declare function localOnlyReason(message: Message, replyTarget: Message | null, root: Message | null): LocalOnlyReason | null;
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/render.d.ts
|
|
22
|
+
declare function renderForAgent(m: Message, external?: boolean, remote?: string): string;
|
|
23
|
+
declare function renderDigestLine(m: Message, external?: boolean, remote?: string): string;
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/lines.d.ts
|
|
26
|
+
declare const LINE_BREAK: RegExp;
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/ulid.d.ts
|
|
29
|
+
declare function createUlidFactory(randomBytes?: (n: number) => Uint8Array): (nowMs: number) => string;
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/version.d.ts
|
|
32
|
+
declare const PROTOCOL_VERSION = "1.0.0-draft.2";
|
|
33
|
+
//#endregion
|
|
34
|
+
export { ADDRESS_SCHEMES, type Address, type AgentRecord, type AgentStatus, BUILT_IN_KINDS, type BuiltInKind, type ChannelRecord, type ConversationMatch, type ConversationPage, DEFAULT_LIMITS, DELIVERY_STATES, type Delivery, DeliveryEngine, type DeliveryEntry, type DeliveryFilter, type DeliveryState, type DeliveryVia, ERROR_CODES, type EngineEvent, type EngineLimits, type ExternalAdmission, type ExternalKind, type ExternalTarget, type FederationHooks, GATE_RAISERS, GATE_TYPES, type GateData, type GateRaiser, type JsonValue, LINE_BREAK, LOCAL_ONLY_MARKERS, type LocalOnlyReason, MARKERS, MAX_ADDRESS_BYTES, MAX_SEGMENT_BYTES, MEMORY_GATE_KINDS, MESSAGES_DB_VERSION, type Message, type MessageKind, type MessageStore, MessagingError, type MessagingErrorCode, type MessagingHost, PEER_ALIAS_PATTERN, PROTOCOL_VERSION, type ParsedAddress, type Placement, type PolicyRequest, type PolicyRuling, REF_TYPES, REMOTE_STATES, type ReceiveResult, type Ref, type RefType, type RefusedEntry, type RemoteDelivery, type RemoteOrigin, type RemoteState, type RemoteTarget, SYSTEM_ADDRESS, type SendInput, type SendOptions, type SendResult, type Sender, type SettleEntry, type SettledAs, type Settlement, SqliteMessageStore, type StateEntry, type StoredMeta, type ThreadSummary, type ValidateOptions, type WakeResult, checkIdempotencyKey, createUlidFactory, gateOf, gateTypeOf, hasGateData, isAgentAuthored, isDecidingAuthor, isFederationLocalAddress, isPeerAddress, isSystemMarker, localOnlyReason, openMessagesDb, parseAddress, raiserOf, renderDigestLine, renderForAgent, validateSendInput };
|
|
35
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/errors.ts","../src/localOnly.ts","../src/render.ts","../src/lines.ts","../src/ulid.ts","../src/version.ts"],"sourcesContent":[],"mappings":";;;;;KAEY,kBAAA,gBAAkC;cAIjC,cAAA,SAAuB,KAAA;iBAEjB;;EANP,WAAA,CAAA,IAAA,EAMO,kBAN2B,EAAA,OAAA,EAAW,MAAA,EAAA,KAAA,CAAA,EAAA,MAAA,GAAA,SAAA;AAIzD;;;;cCDa;;ADHD,iBCWI,wBAAA,CDX8B,OAAW,ECWP,ODXO,CAAA,EAAA,OAAA;AAI5C,KCeD,eAAA,GDfgB,MAAA,GAAA,QAAA,GAAA,aAAA,GAAA,MAAA;AAET,iBC8BH,eAAA,CD9BG,OAAA,EC+BR,OD/BQ,EAAA,WAAA,ECgCJ,ODhCI,GAAA,IAAA,EAAA,IAAA,ECiCX,ODjCW,GAAA,IAAA,CAAA,ECkChB,eDlCgB,GAAA,IAAA;;;iBEYH,cAAA,IACX;iBAoCW,gBAAA,IACX;;;cCxDQ,YAAU;;;iBC4BP,iBAAA,8BACc;;;cC7BjB,gBAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { a as GATE_RAISERS, c as MAX_ADDRESS_BYTES, d as SYSTEM_ADDRESS, f as gateTypeOf, h as raiserOf, i as ERROR_CODES, l as MAX_SEGMENT_BYTES, m as isDecidingAuthor, n as BUILT_IN_KINDS, o as GATE_TYPES, p as hasGateData, r as DELIVERY_STATES, s as MARKERS, t as ADDRESS_SCHEMES, u as REF_TYPES } from "./constants-CRXF4f7g.js";
|
|
2
|
+
import { C as parseAddress, S as isPeerAddress, _ as isSystemMarker, a as REMOTE_STATES, b as PEER_ALIAS_PATTERN, c as createUlidFactory, d as LOCAL_ONLY_MARKERS, f as isFederationLocalAddress, g as gateOf, h as checkIdempotencyKey, i as openMessagesDb, l as renderDigestLine, m as MEMORY_GATE_KINDS, n as MESSAGES_DB_VERSION, o as DEFAULT_LIMITS, p as localOnlyReason, r as SqliteMessageStore, s as DeliveryEngine, t as PROTOCOL_VERSION, u as renderForAgent, v as validateSendInput, w as MessagingError, x as isAgentAuthored, y as LINE_BREAK } from "./version-Ds8ZFZLh.js";
|
|
3
|
+
|
|
4
|
+
export { ADDRESS_SCHEMES, BUILT_IN_KINDS, DEFAULT_LIMITS, DELIVERY_STATES, DeliveryEngine, ERROR_CODES, GATE_RAISERS, GATE_TYPES, LINE_BREAK, LOCAL_ONLY_MARKERS, MARKERS, MAX_ADDRESS_BYTES, MAX_SEGMENT_BYTES, MEMORY_GATE_KINDS, MESSAGES_DB_VERSION, MessagingError, PEER_ALIAS_PATTERN, PROTOCOL_VERSION, REF_TYPES, REMOTE_STATES, SYSTEM_ADDRESS, SqliteMessageStore, checkIdempotencyKey, createUlidFactory, gateOf, gateTypeOf, hasGateData, isAgentAuthored, isDecidingAuthor, isFederationLocalAddress, isPeerAddress, isSystemMarker, localOnlyReason, openMessagesDb, parseAddress, raiserOf, renderDigestLine, renderForAgent, validateSendInput };
|