From e2d18a0d4dfdd422464eef8280b3d5f772da98dc Mon Sep 17 00:00:00 2001 From: samternent Date: Fri, 27 Nov 2026 23:12:26 +0000 Subject: [PATCH 01/24] feat(identity)!: rewrite as one minimal Identity Replace the serialized and capability APIs with six functions: createIdentity, restoreIdentity, createMnemonicIdentity, recoverIdentity, verify and validatePublicIdentity. An Identity exports its v2 backup, signs exact bytes and lends a scoped X25519 secret. Use Scure for encodings and Noble's strict verification instead of handwritten equivalents. Keep the v2 backup format, the m/101010'/25519'/0' derivation and all existing vectors. Consumers are not yet adapted. Co-Authored-By: Claude Opus 5.5 --- packages/identity/README.md | 84 ++- packages/identity/llms.txt | 91 +-- packages/identity/package.json | 2 +- packages/identity/src/index.ts | 201 +++++-- packages/identity/src/serialized.ts | 538 ------------------ packages/identity/src/strict.ts | 200 ------- packages/identity/test/api.test.ts | 216 +++++++ packages/identity/test/identity.test.ts | 172 ------ packages/identity/test/strict.test.ts | 93 ++- ....timestamp-1783937652146-39c0190f2cc6e.mjs | 22 - ....timestamp-1786211734250-16c74f09d8ebb.mjs | 22 - 11 files changed, 480 insertions(+), 1161 deletions(-) delete mode 100644 packages/identity/src/serialized.ts delete mode 100644 packages/identity/src/strict.ts create mode 100644 packages/identity/test/api.test.ts delete mode 100644 packages/identity/test/identity.test.ts delete mode 100644 packages/identity/vite.config.ts.timestamp-1783937652146-39c0190f2cc6e.mjs delete mode 100644 packages/identity/vite.config.ts.timestamp-1786211734250-16c74f09d8ebb.mjs diff --git a/packages/identity/README.md b/packages/identity/README.md index 3facc49..e5424df 100644 --- a/packages/identity/README.md +++ b/packages/identity/README.md @@ -1,66 +1,46 @@ # @ternent/identity -[Agent interface guide](llms.txt): public imports, examples and lifecycle contracts. +One Ed25519 identity for the Ternent libraries. Create or restore it once and pass it +to Ledger, Seal and Armour; no consumer handles the seed. -The capability interface builds on the existing Ed25519/X25519 derivation code. -`signerFromSeed(seed)` and `generateSigner()` return structured results containing a -`BaseIdentityCapability`: public identity, exact-byte signing, and scoped -`withX25519Secret(callback)`. The copied scalar is zeroed after callback settlement, -including rejection. Callers must not retain secret copies from that trusted callback. -`validatePublicIdentity` and `verifySignature` enforce canonical prime-order points, -identity binding and strict signatures. Empty-message signing follows RFC 8032. - -`ageRecipientFromPublicIdentity`, `ageRecipientFromSecret`, `ageSecretKey`, and -`validateAgeRecipient` own the key/Bech32 conversions; `encodeBase64Url` and -`decodeBase64Url` provide canonical byte encoding. The package does not implement age -files or depend on Armour, Concord, or Seal. - -The root explicitly exports two useful interfaces: capabilities for protocol work -and seed/mnemonic/serialized helpers for host applications such as Seal. A -`SerializedIdentity` contains private seed material; `PublicIdentity` is the public -representation used in signed documents. Mnemonics and host identity exports are -outside the Concord wire format. No identity account or recovery service is implied. - -| Purpose | Public functions | -| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Host identity creation and persistence | `createIdentity`, `createIdentityFromMnemonic`, `createMnemonicIdentity`, `generateMnemonic`, `validateMnemonic`, `parseIdentity`, `serializeIdentity`, `validateIdentity` | -| Raw key and age derivation | `derivePublicKey`, `deriveKeyId`, `deriveX25519PrivateKey`, `deriveX25519PublicKey`, `convertEd25519PublicKeyToX25519PublicKey`, `deriveAgeRecipient`, `deriveAgeSecretKey` | -| Contextual signing | `signBytes`, `signUtf8`, `verifyBytes`, `verifyUtf8`, `getDefaultSignatureContext` | -| Mnemonic derivation details | `getIdentityDerivationPath` | +```ts +import { createIdentity, restoreIdentity, verify } from "@ternent/identity"; -`parseIdentity` checks and normalizes the serialized shape; `validateIdentity` also -checks that its seed, public key and key ID agree. Capability validation and -`verifySignature` use the strict point/signature rules described above. The -convenience verification helpers are not a substitute for protocol verification. +const identity = await createIdentity(); +const backup = identity.export(); // private: contains the seed +const restored = await restoreIdentity(backup); -`signBytes`/`signUtf8` sign `UTF8(context) || 0x00 || payload` and return a base64url -signature. Their default context is `ternent-seal/v2`; pass an explicit context for -another protocol. `verifyBytes`/`verifyUtf8` must use the same context. Capability -`sign` signs exactly the supplied bytes and returns raw bytes inside a structured -result. Concord constructs its own signing message and uses that exact-byte path. +const signature = await identity.sign(bytes); +await verify(identity.publicIdentity, bytes, signature); // true +``` -Historical implementations are available in Git. The distribution is ESM. +Recovery words are opt-in: ```ts -import { signerFromSeed } from "@ternent/identity"; -const result = await signerFromSeed(seed); // copies the 32-byte seed -if (!result.ok) throw new Error(result.error.code); -const signature = await result.value.sign(new Uint8Array()); +const { identity, mnemonic } = await createMnemonicIdentity({ words: 24, passphrase }); +const same = await recoverIdentity(mnemonic, passphrase); ``` -Host identity creation and persistence: +| Export | Purpose | +| ----------------------------------------------- | ---------------------------------------------------------- | +| `createIdentity()` | New identity from a random seed | +| `restoreIdentity(backup)` | Identity from `export()` JSON; rejects mismatched fields | +| `createMnemonicIdentity({ words, passphrase })` | New identity and its 12- or 24-word BIP-39 phrase | +| `recoverIdentity(mnemonic, passphrase?)` | Same identity from the same words and passphrase | +| `verify(publicIdentity, bytes, signature)` | Strict Ed25519 verification; `false` for any invalid input | +| `validatePublicIdentity(input)` | Frozen `PublicIdentity` from untrusted input, or throws | -```ts -import { createMnemonicIdentity, serializeIdentity } from "@ternent/identity"; -const { identity, mnemonic } = await createMnemonicIdentity({ words: 12 }); -const exportedIdentity = serializeIdentity(identity); -// The host owns persistence of the private identity and recovery phrase. -``` +An `Identity` has `publicIdentity`, `export()`, `sign(bytes)` and +`withX25519Secret(use)`. `sign` signs exactly the bytes given; protocols add their +own domain separation. The X25519 secret lent to `use` is zeroed when the callback +settles, so keep no copy. + +The backup is `ternent-identity` version `"2"` JSON. Encrypting and storing it is +the application's job, using Armour when needed. Recovery words derive the seed at +SLIP-0010 path `m/101010'/25519'/0'`; a different passphrase gives a different +identity. -Capability factories return `PrimitiveResult`; host helpers reject/throw on invalid -input. Import `PublicIdentity`, `BaseIdentityCapability`, `PrimitiveResult`, -`PrimitiveError`, `SerializedIdentity`, `IdentityMaterial` and `MnemonicWordCount` -from the package root when those types are needed. +Verification rejects non-canonical encodings, small-order and mixed-order keys and +`R` values, and `S` outside the group order. -Run `pnpm check` at the repository root for built-package, browser and consumer proof. License: ISC. diff --git a/packages/identity/llms.txt b/packages/identity/llms.txt index b8e0172..7c7a178 100644 --- a/packages/identity/llms.txt +++ b/packages/identity/llms.txt @@ -1,73 +1,38 @@ # @ternent/identity -> Public identities, private seed capabilities, signatures and Ed25519-to-X25519 derivation. +> One Ed25519 identity: create, back up, restore, recover from words, sign and verify. -Stable interface: `npm install @ternent/identity@0.6.0`. All functions and types come from the package -root. [Public README](https://github.com/ternent/core/blob/main/packages/identity/README.md). -Installed declarations: `dist/index.d.ts`. - -## Capability interface - -```ts -import { generateSigner, verifySignature } from "@ternent/identity"; -const created = await generateSigner(); -if (!created.ok) throw new Error(created.error.code); -const signer = created.value; -const message = new TextEncoder().encode("application.example/v1\0hello"); -const signed = await signer.sign(message); -if (!signed.ok) throw new Error(signed.error.code); -const verified = await verifySignature(signer.publicIdentity, message, signed.value); -if (!verified.ok || !verified.value) throw new Error("Invalid signature"); -``` - -`generateSigner()` and `signerFromSeed(seed)` return `PrimitiveResult`. -A seed is exactly 32 private bytes and is copied by the factory. The capability has -`publicIdentity`, exact-byte `sign(message)` and trusted `withX25519Secret(callback)`. -The borrowed scalar is zeroed after the callback settles; do not retain a copy. -Armour's `withAgeDecryption(base)` adds decryption without exporting the seed. - -`PublicIdentity` has version 1, algorithm Ed25519, a canonical base64url public key -and its derived identity ID. Validate untrusted identities with `validatePublicIdentity`. -`verifySignature` verifies raw message/signature bytes with strict encoding and point -checks. `ageRecipientFromPublicIdentity` returns a result; `ageRecipientFromSecret` -and `ageSecretKey` encode raw X25519 material. Identity does not encrypt age files. - -## Host persistence and recovery +All exports come from the package root. Declarations: `dist/index.d.ts`. +[Public README](https://github.com/ternent/core/blob/main/packages/identity/README.md). ```ts import { + createIdentity, + restoreIdentity, createMnemonicIdentity, - serializeIdentity, - parseIdentity, - validateIdentity, - decodeBase64Url, - signerFromSeed, + recoverIdentity, + verify, + validatePublicIdentity, + type Identity, + type PublicIdentity, } from "@ternent/identity"; -const { identity, mnemonic } = await createMnemonicIdentity({ words: 24 }); -const privateExport = serializeIdentity(identity); -const checked = await validateIdentity(parseIdentity(privateExport)); -const seed = decodeBase64Url(checked.material.seed); -if (!seed.ok) throw new Error(seed.error.code); -const restored = await signerFromSeed(seed.value); -seed.value.fill(0); -if (!restored.ok) throw new Error(restored.error.code); -``` -`SerializedIdentity` contains the private seed; it is not `PublicIdentity` or a -Concord document record. The host protects private exports and recovery phrases. -`parseIdentity` normalizes/checks shape; `validateIdentity` additionally checks -seed/public-key/key-ID consistency. These host helpers throw/reject on invalid input. -The restored base capability signs with the same identity. Armour’s -`withAgeDecryption(restored.value)` adds the decryption operation required by Concord. -Persist the private serialized identity securely; the executable capability itself -is not a portable persistence format. - -## Signing conventions and errors +const identity = await createIdentity(); +const backup = identity.export(); // JSON with the private seed; the app stores it +const restored = await restoreIdentity(backup); +const signature = await identity.sign(bytes); // 64 bytes over exactly `bytes` +const ok = await verify(identity.publicIdentity, bytes, signature); +``` -Capability operations return `PrimitiveResult` (`{ ok: true, value }` or -`{ ok: false, error: { code, message } }`). Host mnemonic/serialized helpers throw. -`signBytes`/`signUtf8` and `verifyBytes`/`verifyUtf8` use a context prefix and return/use -base64url signatures. Their default context is `ternent-seal/v2`; select an explicit -context for another application. They are not interchangeable with exact-byte -capability signing. Concord and Ledger construct their own domain-separated messages. -Do not invent an account/profile service or persist secrets inside signed documents. +- Pass the `Identity` itself to Ledger, Seal and Armour. Do not decode the seed or + build a second signer. +- `PublicIdentity` is `{ version: 1, algorithm: "Ed25519", publicKey, id }` with a + base64url key and `id = "identity:" + hex(sha256(publicKey))`. It is safe to put + in documents. Check untrusted values with `validatePublicIdentity` (throws). +- `verify` never throws; it returns `false` for a bad identity, signature or match. +- `restoreIdentity`, `recoverIdentity` and `createMnemonicIdentity` reject with an + ordinary `Error` on invalid input. +- `withX25519Secret(use)` lends a temporary X25519 secret for decryption and zeroes + it after `use` settles. Do not retain it. +- Recovery words are opt-in, shown once, and never part of the backup. +- Encryption, storage, accounts and two-factor checks belong to the application. diff --git a/packages/identity/package.json b/packages/identity/package.json index 3f614a0..80967ee 100644 --- a/packages/identity/package.json +++ b/packages/identity/package.json @@ -1,7 +1,7 @@ { "name": "@ternent/identity", "version": "0.6.0", - "description": "Seed-based Ed25519 identity primitives with X25519 bridge helpers", + "description": "One Ed25519 identity for the Ternent libraries", "license": "ISC", "repository": { "type": "git", diff --git a/packages/identity/src/index.ts b/packages/identity/src/index.ts index bc88690..65ab48b 100644 --- a/packages/identity/src/index.ts +++ b/packages/identity/src/index.ts @@ -1,42 +1,159 @@ -export { - convertEd25519PublicKeyToX25519PublicKey, - createIdentity, - createIdentityFromMnemonic, - createMnemonicIdentity, - deriveAgeRecipient, - deriveAgeSecretKey, - deriveKeyId, - derivePublicKey, - deriveX25519PrivateKey, - deriveX25519PublicKey, - generateMnemonic, - getDefaultSignatureContext, - getIdentityDerivationPath, - parseIdentity, - serializeIdentity, - signBytes, - signUtf8, - validateIdentity, - validateMnemonic, - verifyBytes, - verifyUtf8, -} from "./serialized.js"; -export type { IdentityMaterial, MnemonicWordCount, SerializedIdentity } from "./serialized.js"; -export { - ageRecipientFromPublicIdentity, - ageRecipientFromSecret, - ageSecretKey, - decodeBase64Url, - encodeBase64Url, - generateSigner, - signerFromSeed, - validateAgeRecipient, - validatePublicIdentity, - verifySignature, -} from "./strict.js"; -export type { - BaseIdentityCapability, - PrimitiveError, - PrimitiveResult, - PublicIdentity, -} from "./strict.js"; +import { ed25519 } from "@noble/curves/ed25519.js"; +import { hmac } from "@noble/hashes/hmac.js"; +import { sha256, sha512 } from "@noble/hashes/sha2.js"; +import { concatBytes } from "@noble/hashes/utils.js"; +import { base64urlnopad, hex } from "@scure/base"; +import { generateMnemonic, mnemonicToSeed, validateMnemonic } from "@scure/bip39"; +import { wordlist } from "@scure/bip39/wordlists/english.js"; + +export type PublicIdentity = Readonly<{ + version: 1; + algorithm: "Ed25519"; + publicKey: string; + id: string; +}>; + +export interface Identity { + readonly publicIdentity: PublicIdentity; + export(): string; + sign(bytes: Uint8Array): Promise; + withX25519Secret(use: (secret: Uint8Array) => T | Promise): Promise; +} + +// SLIP-0010 hardened path m/101010'/25519'/0'. +const DERIVATION_PATH = [101010, 25519, 0]; + +export async function createIdentity(): Promise { + return fromSeed(ed25519.utils.randomSecretKey(), new Date().toISOString()); +} + +export async function restoreIdentity(backup: string): Promise { + const { format, version, algorithm, createdAt, publicKey, keyId, material } = JSON.parse(backup); + if ( + format !== "ternent-identity" || + version !== "2" || + algorithm !== "Ed25519" || + typeof createdAt !== "string" || + material?.kind !== "seed" + ) { + throw new Error("Not a ternent-identity version 2 backup"); + } + const identity = fromSeed(base64urlnopad.decode(material.seed), createdAt); + if ( + publicKey !== identity.publicIdentity.publicKey || + `identity:${keyId}` !== identity.publicIdentity.id + ) { + throw new Error("Backup public key does not match its seed"); + } + return identity; +} + +export async function createMnemonicIdentity({ + words = 12, + passphrase = "", +}: { words?: 12 | 24; passphrase?: string } = {}): Promise<{ + identity: Identity; + mnemonic: string; +}> { + if (words !== 12 && words !== 24) throw new RangeError("Recovery phrases have 12 or 24 words"); + const mnemonic = generateMnemonic(wordlist, words === 24 ? 256 : 128); + return { identity: await recoverIdentity(mnemonic, passphrase), mnemonic }; +} + +export async function recoverIdentity(mnemonic: string, passphrase = ""): Promise { + if (!validateMnemonic(mnemonic, wordlist)) throw new Error("Invalid recovery phrase"); + let node = hmac( + sha512, + new TextEncoder().encode("ed25519 seed"), + await mnemonicToSeed(mnemonic, passphrase), + ); + for (const index of DERIVATION_PATH) { + const hardened = new Uint8Array(4); + new DataView(hardened.buffer).setUint32(0, index + 0x80000000); + node = hmac( + sha512, + node.subarray(32), + concatBytes(new Uint8Array(1), node.subarray(0, 32), hardened), + ); + } + return fromSeed(node.slice(0, 32), new Date().toISOString()); +} + +export async function verify( + publicIdentity: PublicIdentity, + bytes: Uint8Array, + signature: Uint8Array, +): Promise { + try { + const publicKey = base64urlnopad.decode(validatePublicIdentity(publicIdentity).publicKey); + // Noble's strict mode rejects non-canonical encodings, S >= L and a small-order key; + // the R check keeps a signature from carrying a small-order or torsion component. + return ( + isPrimeOrderPoint(signature.subarray(0, 32)) && + ed25519.verify(signature, bytes, publicKey, { zip215: false }) + ); + } catch { + return false; + } +} + +export function validatePublicIdentity(input: unknown): PublicIdentity { + if (typeof input !== "object" || input === null || Object.keys(input).length !== 4) { + throw new TypeError("Invalid public identity"); + } + const { version, algorithm, publicKey, id } = input as Record; + if (version !== 1 || algorithm !== "Ed25519" || typeof publicKey !== "string") { + throw new TypeError("Invalid public identity"); + } + const key = base64urlnopad.decode(publicKey); + if (!isPrimeOrderPoint(key) || id !== identityId(key)) { + throw new TypeError("Invalid public identity"); + } + return Object.freeze({ version, algorithm, publicKey, id }); +} + +function fromSeed(seed: Uint8Array, createdAt: string): Identity { + const key = ed25519.getPublicKey(seed); + const publicIdentity: PublicIdentity = Object.freeze({ + version: 1, + algorithm: "Ed25519", + publicKey: base64urlnopad.encode(key), + id: identityId(key), + }); + return Object.freeze({ + publicIdentity, + export: () => + JSON.stringify( + { + format: "ternent-identity", + version: "2", + algorithm: "Ed25519", + createdAt, + publicKey: publicIdentity.publicKey, + keyId: publicIdentity.id.slice("identity:".length), + material: { kind: "seed", seed: base64urlnopad.encode(seed) }, + }, + null, + 2, + ), + // Signing runs before the first await, so later changes to `bytes` cannot alter it. + sign: async (bytes: Uint8Array) => ed25519.sign(bytes, seed), + async withX25519Secret(use: (secret: Uint8Array) => T | Promise): Promise { + const secret = ed25519.utils.toMontgomerySecret(seed); + try { + return await use(secret); + } finally { + secret.fill(0); + } + }, + }); +} + +function identityId(publicKey: Uint8Array): string { + return `identity:${hex.encode(sha256(publicKey))}`; +} + +function isPrimeOrderPoint(bytes: Uint8Array): boolean { + const point = ed25519.Point.fromBytes(bytes); + return !point.isSmallOrder() && point.isTorsionFree(); +} diff --git a/packages/identity/src/serialized.ts b/packages/identity/src/serialized.ts deleted file mode 100644 index fcc5f81..0000000 --- a/packages/identity/src/serialized.ts +++ /dev/null @@ -1,538 +0,0 @@ -import { ed25519, x25519 } from "@noble/curves/ed25519.js"; -import { hmac } from "@noble/hashes/hmac.js"; -import { sha256, sha512 } from "@noble/hashes/sha2.js"; -import { - generateMnemonic as bip39GenerateMnemonic, - mnemonicToSeedSync, - validateMnemonic as bip39ValidateMnemonic, -} from "@scure/bip39"; -import { wordlist as englishWordlist } from "@scure/bip39/wordlists/english.js"; - -const IDENTITY_FORMAT = "ternent-identity" as const; -const IDENTITY_VERSION = "2" as const; -const IDENTITY_ALGORITHM = "Ed25519" as const; -const ED25519_CONTEXT = "ternent-seal/v2"; -const IDENTITY_MATERIAL_KIND = "seed" as const; -const IDENTITY_DERIVATION_PATH = "m/101010'/25519'/0'" as const; -const BIP39_LANGUAGE = "english" as const; -const SLIP10_HARDENED_OFFSET = 0x80000000; -const SLIP10_KEY = new TextEncoder().encode("ed25519 seed"); -const IDENTITY_PATH_SEGMENTS = [101010, 25519, 0] as const; -const BECH32_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; - -export type MnemonicWordCount = 12 | 24; - -export type IdentityMaterial = { - kind: typeof IDENTITY_MATERIAL_KIND; - seed: string; -}; - -export type SerializedIdentity = { - format: typeof IDENTITY_FORMAT; - version: typeof IDENTITY_VERSION; - algorithm: typeof IDENTITY_ALGORITHM; - createdAt: string; - publicKey: string; - keyId: string; - material: IdentityMaterial; -}; - -type SeedLike = SerializedIdentity | Uint8Array | ArrayBuffer | string; -type PublicKeyLike = - | SerializedIdentity - | Uint8Array - | ArrayBuffer - | string - | { publicKey: string | Uint8Array | ArrayBuffer } - | { seed: string | Uint8Array | ArrayBuffer }; - -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === "object" && !Array.isArray(value); -} - -function concatBytes(...parts: Uint8Array[]): Uint8Array { - const length = parts.reduce((sum, part) => sum + part.length, 0); - const output = new Uint8Array(length); - let offset = 0; - for (const part of parts) { - output.set(part, offset); - offset += part.length; - } - return output; -} - -function ensureBytes(value: Uint8Array | ArrayBuffer, label: string): Uint8Array { - const bytes = value instanceof Uint8Array ? value : new Uint8Array(value); - if (bytes.length === 0) { - throw new Error(`${label} must not be empty.`); - } - return bytes; -} - -function bytesToHex(bytes: Uint8Array): string { - return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); -} - -function normalizeBase64Url(value: string): string { - return String(value || "") - .trim() - .replace(/\+/g, "-") - .replace(/\//g, "_") - .replace(/=+$/g, ""); -} - -function base64Encode(bytes: Uint8Array): string { - const buffer = ( - globalThis as typeof globalThis & { - Buffer?: { - from(input: Uint8Array): { toString(encoding: "base64"): string }; - from(input: string, encoding: "base64"): Uint8Array; - }; - } - ).Buffer; - - if (buffer) { - return buffer.from(bytes).toString("base64"); - } - - let binary = ""; - for (const byte of bytes) { - binary += String.fromCharCode(byte); - } - if (typeof btoa !== "undefined") { - return btoa(binary); - } - throw new Error("Base64 encoding is not available in this runtime."); -} - -function base64Decode(value: string): Uint8Array { - const normalized = value.replace(/-/g, "+").replace(/_/g, "/"); - const buffer = ( - globalThis as typeof globalThis & { - Buffer?: { - from(input: Uint8Array): { toString(encoding: "base64"): string }; - from(input: string, encoding: "base64"): Uint8Array; - }; - } - ).Buffer; - - if (buffer) { - return new Uint8Array(buffer.from(normalized, "base64")); - } - - if (typeof atob !== "undefined") { - const binary = atob(normalized); - const bytes = new Uint8Array(binary.length); - for (let index = 0; index < binary.length; index += 1) { - bytes[index] = binary.charCodeAt(index); - } - return bytes; - } - - throw new Error("Base64 decoding is not available in this runtime."); -} - -function base64UrlEncode(bytes: Uint8Array): string { - return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, ""); -} - -function base64UrlDecode(value: string): Uint8Array { - const normalized = normalizeBase64Url(value); - if (!normalized) { - throw new Error("Base64url value is required."); - } - const pad = normalized.length % 4 === 0 ? "" : "=".repeat(4 - (normalized.length % 4)); - return base64Decode(`${normalized}${pad}`); -} - -function utf8Bytes(value: string): Uint8Array { - return new TextEncoder().encode(value); -} - -function combineContext(payload: Uint8Array, context = ED25519_CONTEXT): Uint8Array { - return concatBytes(utf8Bytes(context), new Uint8Array([0]), payload); -} - -function assertWordCount(words: number): MnemonicWordCount { - if (words === 12 || words === 24) { - return words; - } - throw new Error("Mnemonic word count must be 12 or 24."); -} - -function strengthFromWordCount(words: MnemonicWordCount): 128 | 256 { - return words === 24 ? 256 : 128; -} - -function serializeUint32(value: number): Uint8Array { - return new Uint8Array([ - (value >>> 24) & 0xff, - (value >>> 16) & 0xff, - (value >>> 8) & 0xff, - value & 0xff, - ]); -} - -function deriveSlip10Seed(seedBytes: Uint8Array): Uint8Array { - let chain = hmac(sha512, SLIP10_KEY, seedBytes); - let key = chain.slice(0, 32); - let chainCode = chain.slice(32); - - for (const segment of IDENTITY_PATH_SEGMENTS) { - const index = segment + SLIP10_HARDENED_OFFSET; - chain = hmac(sha512, chainCode, concatBytes(new Uint8Array([0]), key, serializeUint32(index))); - key = chain.slice(0, 32); - chainCode = chain.slice(32); - } - - return key; -} - -function isSerializedIdentity(value: unknown): value is SerializedIdentity { - return ( - isRecord(value) && - value.format === IDENTITY_FORMAT && - value.version === IDENTITY_VERSION && - value.algorithm === IDENTITY_ALGORITHM && - typeof value.createdAt === "string" && - typeof value.publicKey === "string" && - typeof value.keyId === "string" && - isRecord(value.material) && - value.material.kind === IDENTITY_MATERIAL_KIND && - typeof value.material.seed === "string" - ); -} - -function toCanonicalIdentity(identity: SerializedIdentity): SerializedIdentity { - return { - format: identity.format, - version: identity.version, - algorithm: identity.algorithm, - createdAt: identity.createdAt, - publicKey: identity.publicKey, - keyId: identity.keyId, - material: { - kind: identity.material.kind, - seed: identity.material.seed, - }, - }; -} - -function resolveSeedBytes(input: SeedLike): Uint8Array { - if (input instanceof Uint8Array || input instanceof ArrayBuffer) { - const bytes = ensureBytes(input, "Seed"); - if (bytes.length !== 32) { - throw new Error("Seed must be 32 bytes."); - } - return bytes; - } - if (typeof input === "string") { - const bytes = base64UrlDecode(input); - if (bytes.length !== 32) { - throw new Error("Seed must be 32 bytes."); - } - return bytes; - } - if (isSerializedIdentity(input)) { - return resolveSeedBytes(input.material.seed); - } - throw new Error("A valid identity or 32-byte seed is required."); -} - -function resolvePublicKeyBytes(input: PublicKeyLike): Uint8Array { - if (input instanceof Uint8Array || input instanceof ArrayBuffer) { - const bytes = ensureBytes(input, "Public key"); - if (bytes.length !== 32) { - throw new Error("Public key must be 32 bytes."); - } - return bytes; - } - if (typeof input === "string") { - const bytes = base64UrlDecode(input); - if (bytes.length !== 32) { - throw new Error("Public key must be 32 bytes."); - } - return bytes; - } - if (isSerializedIdentity(input)) { - return resolvePublicKeyBytes(input.publicKey); - } - if (isRecord(input) && "publicKey" in input) { - return resolvePublicKeyBytes(input.publicKey as string | Uint8Array | ArrayBuffer); - } - throw new Error("A valid 32-byte public key is required."); -} - -function resolveX25519PrivateKeyBytes(input: SeedLike): Uint8Array { - return ed25519.utils.toMontgomerySecret(resolveSeedBytes(input)); -} - -function convertEd25519PublicKeyToX25519PublicKeyBytes(publicKeyBytes: Uint8Array): Uint8Array { - return ed25519.utils.toMontgomery(publicKeyBytes); -} - -function resolveX25519PublicKeyBytes(input: PublicKeyLike): Uint8Array { - if (isRecord(input) && "seed" in input) { - return x25519.getPublicKey( - resolveX25519PrivateKeyBytes(input.seed as string | Uint8Array | ArrayBuffer), - ); - } - if (isSerializedIdentity(input)) { - return x25519.getPublicKey(resolveX25519PrivateKeyBytes(input)); - } - if (typeof input === "string" || input instanceof Uint8Array || input instanceof ArrayBuffer) { - return convertEd25519PublicKeyToX25519PublicKeyBytes(resolvePublicKeyBytes(input)); - } - if (isRecord(input) && "publicKey" in input) { - return convertEd25519PublicKeyToX25519PublicKeyBytes( - resolvePublicKeyBytes(input.publicKey as string | Uint8Array | ArrayBuffer), - ); - } - throw new Error("A valid identity seed or Ed25519 public key is required."); -} - -function bech32Polymod(values: number[]): number { - let checksum = 1; - for (const value of values) { - const top = checksum >>> 25; - checksum = ((checksum & 0x1ffffff) << 5) ^ value; - for (let bit = 0; bit < 5; bit += 1) { - if ((top >>> bit) & 1) { - checksum ^= BECH32_GENERATORS[bit]; - } - } - } - return checksum; -} - -function bech32HrpExpand(hrp: string): number[] { - const output: number[] = []; - for (let index = 0; index < hrp.length; index += 1) { - output.push(hrp.charCodeAt(index) >> 5); - } - output.push(0); - for (let index = 0; index < hrp.length; index += 1) { - output.push(hrp.charCodeAt(index) & 31); - } - return output; -} - -function convertBits(data: Uint8Array, fromBits: number, toBits: number): number[] { - let value = 0; - let bits = 0; - const maxValue = (1 << toBits) - 1; - const output: number[] = []; - for (const byte of data) { - value = (value << fromBits) | byte; - bits += fromBits; - while (bits >= toBits) { - bits -= toBits; - output.push((value >> bits) & maxValue); - } - } - if (bits > 0) { - output.push((value << (toBits - bits)) & maxValue); - } - return output; -} - -function bech32CreateChecksum(hrp: string, data: number[]): number[] { - const values = [...bech32HrpExpand(hrp), ...data, 0, 0, 0, 0, 0, 0]; - const polymod = bech32Polymod(values) ^ 1; - const checksum: number[] = []; - for (let index = 0; index < 6; index += 1) { - checksum.push((polymod >> (5 * (5 - index))) & 31); - } - return checksum; -} - -function bech32Encode(hrp: string, data: Uint8Array): string { - const charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; - const words = convertBits(data, 8, 5); - const combined = [...words, ...bech32CreateChecksum(hrp, words)]; - return `${hrp}1${combined.map((value) => charset[value]).join("")}`; -} - -async function createIdentityFromSeedBytes( - seedBytes: Uint8Array, - createdAt: string, -): Promise { - const publicKeyBytes = ed25519.getPublicKey(seedBytes); - return { - format: IDENTITY_FORMAT, - version: IDENTITY_VERSION, - algorithm: IDENTITY_ALGORITHM, - createdAt, - publicKey: base64UrlEncode(publicKeyBytes), - keyId: bytesToHex(sha256(publicKeyBytes)), - material: { - kind: IDENTITY_MATERIAL_KIND, - seed: base64UrlEncode(seedBytes), - }, - }; -} - -export function getDefaultSignatureContext(): string { - return ED25519_CONTEXT; -} - -export function getIdentityDerivationPath(): string { - return IDENTITY_DERIVATION_PATH; -} - -export function generateMnemonic( - input: { - words?: MnemonicWordCount; - } = {}, -): string { - const words = assertWordCount(input.words ?? 12); - return bip39GenerateMnemonic(englishWordlist, strengthFromWordCount(words)); -} - -export function validateMnemonic( - mnemonic: string, - options: { wordlist?: typeof BIP39_LANGUAGE } = {}, -): boolean { - if (options.wordlist && options.wordlist !== BIP39_LANGUAGE) { - throw new Error("Only the English BIP-39 wordlist is supported."); - } - return bip39ValidateMnemonic(String(mnemonic || "").trim(), englishWordlist); -} - -export async function createIdentity( - createdAt = new Date().toISOString(), -): Promise { - return createIdentityFromSeedBytes(ed25519.utils.randomSecretKey(), createdAt); -} - -export async function createIdentityFromMnemonic(input: { - mnemonic: string; - passphrase?: string; - createdAt?: string; -}): Promise { - const mnemonic = String(input.mnemonic || "").trim(); - if (!validateMnemonic(mnemonic)) { - throw new Error("Mnemonic phrase is not a valid English BIP-39 phrase."); - } - const mnemonicSeed = mnemonicToSeedSync(mnemonic, input.passphrase || ""); - const derivedSeed = deriveSlip10Seed(mnemonicSeed); - return createIdentityFromSeedBytes(derivedSeed, input.createdAt ?? new Date().toISOString()); -} - -export async function createMnemonicIdentity( - input: { - words?: MnemonicWordCount; - passphrase?: string; - createdAt?: string; - } = {}, -): Promise<{ identity: SerializedIdentity; mnemonic: string }> { - const mnemonic = generateMnemonic({ words: input.words ?? 12 }); - return { - mnemonic, - identity: await createIdentityFromMnemonic({ - mnemonic, - passphrase: input.passphrase, - createdAt: input.createdAt, - }), - }; -} - -export async function derivePublicKey(seed: string | Uint8Array | ArrayBuffer): Promise { - return base64UrlEncode(ed25519.getPublicKey(resolveSeedBytes(seed))); -} - -export async function deriveKeyId(publicKey: string | Uint8Array | ArrayBuffer): Promise { - return bytesToHex(sha256(resolvePublicKeyBytes(publicKey))); -} - -export function parseIdentity(input: string | SerializedIdentity): SerializedIdentity { - const parsed = typeof input === "string" ? JSON.parse(input) : input; - if (!isSerializedIdentity(parsed)) { - throw new Error("Identity payload must be a ternent-identity v2 object."); - } - return toCanonicalIdentity(parsed); -} - -export function serializeIdentity(identity: SerializedIdentity, pretty = true): string { - return `${JSON.stringify(parseIdentity(identity), null, pretty ? 2 : 0)}\n`; -} - -export async function validateIdentity(identity: SerializedIdentity): Promise { - const parsed = parseIdentity(identity); - const derivedPublicKey = await derivePublicKey(parsed.material.seed); - if (derivedPublicKey !== normalizeBase64Url(parsed.publicKey)) { - throw new Error("Identity publicKey does not match the stored seed."); - } - const derivedKeyId = await deriveKeyId(parsed.publicKey); - if (derivedKeyId !== parsed.keyId) { - throw new Error("Identity keyId does not match the public key."); - } - return parsed; -} - -export async function signBytes( - identityOrSeed: SeedLike, - payload: Uint8Array | ArrayBuffer, - options: { context?: string } = {}, -): Promise { - return base64UrlEncode( - ed25519.sign( - combineContext(ensureBytes(payload, "Payload"), options.context), - resolveSeedBytes(identityOrSeed), - ), - ); -} - -export async function verifyBytes( - publicKey: string | Uint8Array | ArrayBuffer, - payload: Uint8Array | ArrayBuffer, - signature: string, - options: { context?: string } = {}, -): Promise { - return ed25519.verify( - base64UrlDecode(signature), - combineContext(ensureBytes(payload, "Payload"), options.context), - resolvePublicKeyBytes(publicKey), - ); -} - -export async function signUtf8( - identityOrSeed: SeedLike, - value: string, - options: { context?: string } = {}, -): Promise { - return signBytes(identityOrSeed, utf8Bytes(value), options); -} - -export async function verifyUtf8( - publicKey: string | Uint8Array | ArrayBuffer, - value: string, - signature: string, - options: { context?: string } = {}, -): Promise { - return verifyBytes(publicKey, utf8Bytes(value), signature, options); -} - -export async function deriveX25519PrivateKey(input: SeedLike): Promise { - return base64UrlEncode(resolveX25519PrivateKeyBytes(input)); -} - -export async function deriveX25519PublicKey(input: PublicKeyLike): Promise { - return base64UrlEncode(resolveX25519PublicKeyBytes(input)); -} - -export async function convertEd25519PublicKeyToX25519PublicKey( - publicKey: string | Uint8Array | ArrayBuffer, -): Promise { - return base64UrlEncode( - convertEd25519PublicKeyToX25519PublicKeyBytes(resolvePublicKeyBytes(publicKey)), - ); -} - -export async function deriveAgeRecipient(input: PublicKeyLike): Promise { - return bech32Encode("age", resolveX25519PublicKeyBytes(input)); -} - -export async function deriveAgeSecretKey(input: SeedLike): Promise { - return bech32Encode("age-secret-key-", resolveX25519PrivateKeyBytes(input)).toUpperCase(); -} diff --git a/packages/identity/src/strict.ts b/packages/identity/src/strict.ts deleted file mode 100644 index 02c863b..0000000 --- a/packages/identity/src/strict.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { ed25519, x25519 } from "@noble/curves/ed25519.js"; -import { sha256 } from "@noble/hashes/sha2.js"; -import { base64urlnopad, bech32, hex } from "@scure/base"; - -export type PrimitiveError = { code: string; message: string }; -export type PrimitiveResult = { ok: true; value: T } | { ok: false; error: PrimitiveError }; -export type PublicIdentity = Readonly<{ - version: 1; - algorithm: "Ed25519"; - publicKey: string; - id: string; -}>; -export type BaseIdentityCapability = { - readonly publicIdentity: PublicIdentity; - sign(this: void, message: Uint8Array): Promise>; - withX25519Secret(this: void, callback: (secret: Uint8Array) => T | Promise): Promise; -}; - -const failure = (code: string): PrimitiveResult => ({ - ok: false, - error: { code, message: code.replaceAll("_", " ").toLowerCase() }, -}); - -export function encodeBase64Url(bytes: Uint8Array): string { - return base64urlnopad.encode(bytes); -} -export function decodeBase64Url(value: string): PrimitiveResult { - try { - if (typeof value !== "string" || !/^[A-Za-z0-9_-]*$/.test(value)) - return failure("ENCODING_INVALID"); - const bytes = base64urlnopad.decode(value); - return encodeBase64Url(bytes) === value - ? { ok: true, value: bytes } - : failure("ENCODING_INVALID"); - } catch { - return failure("ENCODING_INVALID"); - } -} - -function strictPoint(bytes: Uint8Array): boolean { - try { - if (bytes.length !== 32) return false; - const point = ed25519.Point.fromBytes(bytes, false); - return ( - !point.isSmallOrder() && - point.isTorsionFree() && - hex.encode(point.toBytes()) === hex.encode(bytes) - ); - } catch { - return false; - } -} - -export function validatePublicIdentity(input: unknown): PrimitiveResult { - try { - if (!input || typeof input !== "object" || Array.isArray(input)) - return failure("IDENTITY_INVALID"); - const descriptors = Object.getOwnPropertyDescriptors(input); - if ( - Reflect.ownKeys(input).length !== 4 || - !["version", "algorithm", "publicKey", "id"].every( - (key) => descriptors[key] && "value" in descriptors[key], - ) - ) - return failure("IDENTITY_INVALID"); - const identity = input as PublicIdentity; - if (identity.version !== 1 || identity.algorithm !== "Ed25519") - return failure("IDENTITY_INVALID"); - const decoded = decodeBase64Url(identity.publicKey); - if ( - !decoded.ok || - !strictPoint(decoded.value) || - identity.id !== `identity:${hex.encode(sha256(decoded.value))}` - ) - return failure("IDENTITY_INVALID"); - return { - ok: true, - value: Object.freeze({ - version: 1, - algorithm: "Ed25519", - publicKey: identity.publicKey, - id: identity.id, - }), - }; - } catch { - return failure("IDENTITY_INVALID"); - } -} - -export async function verifySignature( - identity: PublicIdentity, - message: Uint8Array, - signature: Uint8Array, -): Promise> { - const valid = validatePublicIdentity(identity); - if (!valid.ok) return valid; - try { - if ( - !(message instanceof Uint8Array) || - !(signature instanceof Uint8Array) || - signature.length !== 64 || - !strictPoint(signature.subarray(0, 32)) - ) - return failure("SIGNATURE_INVALID"); - let scalar = 0n; - for (let i = 63; i >= 32; i--) scalar = (scalar << 8n) | BigInt(signature[i]); - if (scalar >= ed25519.Point.CURVE().n) return failure("SIGNATURE_INVALID"); - const key = decodeBase64Url(valid.value.publicKey); - if (!key.ok) return key; - return ed25519.verify(signature, message, key.value, { zip215: false }) - ? { ok: true, value: true } - : failure("SIGNATURE_INVALID"); - } catch { - return failure("SIGNATURE_INVALID"); - } -} - -export function ageSecretKey(secret: Uint8Array): string { - if (secret.length !== 32) throw new TypeError("An X25519 scalar is 32 bytes"); - return bech32.encode("age-secret-key-", bech32.toWords(secret)).toUpperCase(); -} -export function validateAgeRecipient(recipient: string): PrimitiveResult { - try { - const decoded = bech32.decode(recipient as `${string}1${string}`); - if ( - decoded.prefix !== "age" || - bech32.fromWords(decoded.words).length !== 32 || - bech32.encode("age", decoded.words) !== recipient - ) - return failure("RECIPIENT_INVALID"); - return { ok: true, value: recipient }; - } catch { - return failure("RECIPIENT_INVALID"); - } -} -export function ageRecipientFromSecret(secret: Uint8Array): string { - if (secret.length !== 32) throw new TypeError("An X25519 scalar is 32 bytes"); - return bech32.encode("age", bech32.toWords(x25519.getPublicKey(secret))); -} -export function ageRecipientFromPublicIdentity(identity: PublicIdentity): PrimitiveResult { - const valid = validatePublicIdentity(identity); - if (!valid.ok) return valid; - const decoded = decodeBase64Url(valid.value.publicKey); - if (!decoded.ok) return decoded; - return { - ok: true, - value: bech32.encode("age", bech32.toWords(ed25519.utils.toMontgomery(decoded.value))), - }; -} - -export async function signerFromSeed( - input: Uint8Array, -): Promise> { - if (!(input instanceof Uint8Array) || input.length !== 32) return failure("SEED_INVALID"); - const seed = new Uint8Array(input); - const key = ed25519.getPublicKey(seed); - const publicIdentity: PublicIdentity = Object.freeze({ - version: 1, - algorithm: "Ed25519", - publicKey: encodeBase64Url(key), - id: `identity:${hex.encode(sha256(key))}`, - }); - return { - ok: true, - value: Object.freeze({ - publicIdentity, - async sign(message: Uint8Array) { - try { - if (!(message instanceof Uint8Array)) return failure("SIGNING_FAILED"); - return { ok: true as const, value: ed25519.sign(new Uint8Array(message), seed) }; - } catch { - return failure("SIGNING_FAILED"); - } - }, - async withX25519Secret( - this: void, - callback: (secret: Uint8Array) => T | Promise, - ): Promise { - const secret = ed25519.utils.toMontgomerySecret(seed); - try { - return await callback(secret); - } finally { - secret.fill(0); - } - }, - }), - }; -} -export async function generateSigner(): Promise> { - try { - const seed = ed25519.utils.randomSecretKey(); - try { - return await signerFromSeed(seed); - } finally { - seed.fill(0); - } - } catch { - return failure("GENERATION_FAILED"); - } -} diff --git a/packages/identity/test/api.test.ts b/packages/identity/test/api.test.ts new file mode 100644 index 0000000..d9fad8d --- /dev/null +++ b/packages/identity/test/api.test.ts @@ -0,0 +1,216 @@ +import { readFileSync } from "node:fs"; +import { expect, test } from "vite-plus/test"; +import { base64urlnopad, bech32, hex } from "@scure/base"; +import { ed25519, x25519 } from "@noble/curves/ed25519.js"; +import * as api from "../src/index.js"; +import { + createIdentity, + restoreIdentity, + createMnemonicIdentity, + recoverIdentity, + verify, + validatePublicIdentity, +} from "../src/index.js"; + +const saved = JSON.parse( + readFileSync(new URL("../../../docs/seal/vectors/proof.v2.json", import.meta.url), "utf8"), +); +const mnemonic = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + +test("the public interface contains exactly the six identity operations", () => { + expect(Object.keys(api).sort()).toEqual([ + "createIdentity", + "createMnemonicIdentity", + "recoverIdentity", + "restoreIdentity", + "validatePublicIdentity", + "verify", + ]); +}); + +test("create, export, restore and exact-byte signing use one usable identity", async () => { + const identity = await createIdentity(); + expect(Object.keys(identity).sort()).toEqual([ + "export", + "publicIdentity", + "sign", + "withX25519Secret", + ]); + expect(Object.isFrozen(identity)).toBe(true); + expect(Object.isFrozen(identity.publicIdentity)).toBe(true); + const backup = identity.export(); + const restored = await restoreIdentity(backup); + expect(restored.publicIdentity).toEqual(identity.publicIdentity); + expect(JSON.parse(restored.export())).toEqual(JSON.parse(backup)); + const bytes = new TextEncoder().encode("exact bytes"); + const signature = await identity.sign(bytes); + expect(signature).toHaveLength(64); + expect(await verify(identity.publicIdentity, bytes, signature)).toBe(true); + expect(await verify(restored.publicIdentity, bytes, await restored.sign(bytes))).toBe(true); + expect(await verify(identity.publicIdentity, new Uint8Array([1]), signature)).toBe(false); + expect(await verify((await createIdentity()).publicIdentity, bytes, signature)).toBe(false); +}); + +test("existing version 2 backups preserve keys, metadata, signatures and age derivation", async () => { + const identity = await restoreIdentity(JSON.stringify(saved.identity)); + expect(JSON.parse(identity.export())).toEqual(saved.identity); + expect(identity.publicIdentity).toEqual({ + version: 1, + algorithm: "Ed25519", + publicKey: saved.identity.publicKey, + id: `identity:${saved.identity.keyId}`, + }); + expect(hex.encode(await identity.sign(new Uint8Array()))).toBe( + "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", + ); + expect( + await verify( + identity.publicIdentity, + hex.decode(saved.messageHex), + base64urlnopad.decode(saved.proof.signature), + ), + ).toBe(true); + await identity.withX25519Secret((secret) => { + expect(hex.encode(secret)).toBe( + "307c83864f2833cb427a2ef1c00a013cfdff2768d980c0a3a520f006904de94f", + ); + expect(bech32.encode("age", bech32.toWords(x25519.getPublicKey(secret)))).toBe( + "age1mp0q0mpzkzkcs9fhct6y6e3drg2re7psc4av5sc9mpw84y8kkchq6r9kjp", + ); + }); + expect( + ed25519.utils.toMontgomery(base64urlnopad.decode(identity.publicIdentity.publicKey)), + ).toEqual(hex.decode("d85e07ec22b0ad881537c2f44d662d1a143cf830c57aca4305d85c7a90f6b62e")); +}); + +test("mutable signing input is captured and temporary secrets are cleared on settlement", async () => { + const identity = await restoreIdentity(JSON.stringify(saved.identity)); + const bytes = new Uint8Array([1, 2, 3]); + const signature = identity.sign(bytes); + bytes.fill(0); + expect(await verify(identity.publicIdentity, new Uint8Array([1, 2, 3]), await signature)).toBe( + true, + ); + let borrowed: Uint8Array | undefined; + await identity.withX25519Secret(async (secret) => { + borrowed = secret; + await Promise.resolve(); + expect(secret.some((byte) => byte !== 0)).toBe(true); + }); + expect(borrowed?.every((byte) => byte === 0)).toBe(true); + await expect( + identity.withX25519Secret((secret) => { + borrowed = secret; + throw new Error("callback"); + }), + ).rejects.toThrow("callback"); + expect(borrowed?.every((byte) => byte === 0)).toBe(true); + await expect( + identity.withX25519Secret(async (secret) => { + borrowed = secret; + await Promise.resolve(); + throw new Error("async callback"); + }), + ).rejects.toThrow("async callback"); + expect(borrowed?.every((byte) => byte === 0)).toBe(true); + const next = await identity.sign(new Uint8Array()); + expect(await verify(identity.publicIdentity, new Uint8Array(), next)).toBe(true); +}); + +test("restore rejects malformed and mismatched backup fields", async () => { + const other = JSON.parse((await createIdentity()).export()); + const invalid = [ + null, + {}, + { ...saved.identity, version: "1" }, + { ...saved.identity, algorithm: "other" }, + { ...saved.identity, createdAt: 42 }, + { ...saved.identity, publicKey: other.publicKey }, + { ...saved.identity, keyId: other.keyId }, + { ...saved.identity, material: { kind: "seed", seed: other.material.seed } }, + ]; + for (const input of invalid) + await expect(restoreIdentity(JSON.stringify(input))).rejects.toThrow(); + for (const seed of [ + "", + saved.identity.material.seed + "!", + saved.identity.material.seed + "=", + " " + saved.identity.material.seed, + base64urlnopad.encode(new Uint8Array(31)), + ]) { + await expect( + restoreIdentity(JSON.stringify({ ...saved.identity, material: { kind: "seed", seed } })), + ).rejects.toThrow(); + } + await expect(restoreIdentity("not json")).rejects.toThrow(); +}); + +test("mnemonic recovery retains the selected derivation path and fixed public keys", async () => { + const cases = [ + [ + mnemonic, + "TREZOR", + "6IBjlSqvqPfmXohZXC-oqbjX71wHutV9vvrRtw5VrUE", + "f34b06f6ffee32599d0e3f49bbee43baf4018ab07378b505da8c778f766096b8", + "u7XruZ6e2gC5owNbLcZEqRFbgD8GPrqjyn-l5-SIz64", + ], + [ + "liberty bag shell level tip galaxy glow shrimp cram hood lawsuit error waste zoo wash rough cinnamon firm sister mistake awful seven nurse hawk", + "", + "E71yH7ReOw9yPR0rACZpa_ZU1D8xotD0uYhv5-bDih0", + "41db29a5d32f112d1cec0511120309e9e02e7f15efda8a1890d269060e120839", + "GXKurndvf5UYhth7C_uuVjUf84V_17xe0kpIyVS12WI", + ], + [ + "legal winner thank year wave sausage worth useful legal winner thank yellow", + "", + "8gb5_L0cJPiga567IOtUgTydVa_2361Al17RE0v6sfA", + "9bcf8f0f872020e588995f39b82e3ceb454e415f7edef4ecf7a5007dc50f8824", + "9OLA_8sUT8OZ0ILgUUzjI3Bq_uBKGa9Z5fmAPhf1RmE", + ], + ]; + for (const [words, passphrase, publicKey, keyId, seed] of cases) { + const identity = await recoverIdentity(words, passphrase); + expect(identity.publicIdentity).toEqual({ + version: 1, + algorithm: "Ed25519", + publicKey, + id: `identity:${keyId}`, + }); + expect(JSON.parse(identity.export()).material.seed).toBe(seed); + } + expect((await recoverIdentity(mnemonic, "different")).publicIdentity).not.toEqual( + (await recoverIdentity(mnemonic, "TREZOR")).publicIdentity, + ); +}); + +test("mnemonic creation defaults to 12 words, supports 24 and exports no recovery phrase", async () => { + for (const words of [undefined, 24] as const) { + const created = await createMnemonicIdentity({ words, passphrase: "optional" }); + expect(created.mnemonic.split(" ")).toHaveLength(words ?? 12); + expect((await recoverIdentity(created.mnemonic, "optional")).publicIdentity).toEqual( + created.identity.publicIdentity, + ); + const backup = JSON.parse(created.identity.export()); + expect(backup.mnemonic).toBeUndefined(); + expect(backup.passphrase).toBeUndefined(); + } + await expect(recoverIdentity("not recovery words")).rejects.toThrow(); + await expect(createMnemonicIdentity({ words: 18 as 12 })).rejects.toThrow(); +}); + +test("validation returns a detached frozen public identity and verification rejects malformed input", async () => { + const identity = await createIdentity(); + const input = { ...identity.publicIdentity }; + const validated = validatePublicIdentity(input); + input.publicKey = "changed"; + expect(validated).toEqual(identity.publicIdentity); + expect(Object.isFrozen(validated)).toBe(true); + for (const publicIdentity of [null, {}, { ...identity.publicIdentity, id: "wrong" }]) { + expect(() => validatePublicIdentity(publicIdentity)).toThrow(); + expect(await verify(publicIdentity as never, new Uint8Array(), new Uint8Array(64))).toBe(false); + } + expect(await verify(identity.publicIdentity, new Uint8Array(), new Uint8Array(63))).toBe(false); + await expect(identity.sign("not bytes" as never)).rejects.toThrow(); +}); diff --git a/packages/identity/test/identity.test.ts b/packages/identity/test/identity.test.ts deleted file mode 100644 index e440393..0000000 --- a/packages/identity/test/identity.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import { - convertEd25519PublicKeyToX25519PublicKey, - createIdentity, - createIdentityFromMnemonic, - createMnemonicIdentity, - deriveAgeRecipient, - deriveAgeSecretKey, - deriveKeyId, - derivePublicKey, - deriveX25519PublicKey, - getIdentityDerivationPath, - generateMnemonic, - parseIdentity, - serializeIdentity, - signUtf8, - validateMnemonic, - verifyUtf8, -} from "../src/index.js"; - -describe("@ternent/identity", () => { - it("round-trips a serialized identity", async () => { - const identity = await createIdentity("2026-03-16T00:00:00.000Z"); - const parsed = parseIdentity(serializeIdentity(identity)); - - expect(parsed).toEqual(identity); - }); - - it("serializes a canonical identity payload without UI-only fields", async () => { - const identity = await createIdentity("2026-03-16T00:00:00.000Z"); - const withUiState = { - ...identity, - id: `identity-${identity.keyId.slice(0, 12)}`, - }; - - expect(JSON.parse(serializeIdentity(withUiState as typeof identity))).toEqual(identity); - }); - - it("derives deterministic public keys and key ids from the seed", async () => { - const identity = await createIdentity(); - - expect(await derivePublicKey(identity.material.seed)).toBe(identity.publicKey); - expect(await deriveKeyId(identity.publicKey)).toBe(identity.keyId); - }); - - it("creates deterministic identities from a mnemonic phrase", async () => { - const input = { - mnemonic: - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", - passphrase: "TREZOR", - createdAt: "2026-03-16T00:00:00.000Z", - }; - - const identityA = await createIdentityFromMnemonic(input); - const identityB = await createIdentityFromMnemonic(input); - - expect(identityA).toEqual(identityB); - expect(identityA).toEqual({ - format: "ternent-identity", - version: "2", - algorithm: "Ed25519", - createdAt: "2026-03-16T00:00:00.000Z", - publicKey: "6IBjlSqvqPfmXohZXC-oqbjX71wHutV9vvrRtw5VrUE", - keyId: "f34b06f6ffee32599d0e3f49bbee43baf4018ab07378b505da8c778f766096b8", - material: { - kind: "seed", - seed: "u7XruZ6e2gC5owNbLcZEqRFbgD8GPrqjyn-l5-SIz64", - }, - }); - expect(getIdentityDerivationPath()).toBe("m/101010'/25519'/0'"); - }); - - it("generates and validates 12- and 24-word mnemonics", async () => { - const mnemonic12 = generateMnemonic({ words: 12 }); - const mnemonic24 = - "liberty bag shell level tip galaxy glow shrimp cram hood lawsuit error waste zoo wash rough cinnamon firm sister mistake awful seven nurse hawk"; - const created = await createMnemonicIdentity({ - words: 12, - passphrase: "optional", - createdAt: "2026-03-16T00:00:00.000Z", - }); - const twentyFourWordIdentity = await createIdentityFromMnemonic({ - mnemonic: mnemonic24, - createdAt: "2026-03-16T00:00:00.000Z", - }); - const noPassphraseIdentity = await createIdentityFromMnemonic({ - mnemonic: "legal winner thank year wave sausage worth useful legal winner thank yellow", - createdAt: "2026-03-16T00:00:00.000Z", - }); - - expect(mnemonic12.split(" ")).toHaveLength(12); - expect(mnemonic24.split(" ")).toHaveLength(24); - expect(validateMnemonic(mnemonic12)).toBe(true); - expect(validateMnemonic(mnemonic24)).toBe(true); - expect(created.mnemonic.split(" ")).toHaveLength(12); - expect(created.identity.material.kind).toBe("seed"); - expect(twentyFourWordIdentity).toEqual({ - format: "ternent-identity", - version: "2", - algorithm: "Ed25519", - createdAt: "2026-03-16T00:00:00.000Z", - publicKey: "E71yH7ReOw9yPR0rACZpa_ZU1D8xotD0uYhv5-bDih0", - keyId: "41db29a5d32f112d1cec0511120309e9e02e7f15efda8a1890d269060e120839", - material: { - kind: "seed", - seed: "GXKurndvf5UYhth7C_uuVjUf84V_17xe0kpIyVS12WI", - }, - }); - expect(noPassphraseIdentity).toEqual({ - format: "ternent-identity", - version: "2", - algorithm: "Ed25519", - createdAt: "2026-03-16T00:00:00.000Z", - publicKey: "8gb5_L0cJPiga567IOtUgTydVa_2361Al17RE0v6sfA", - keyId: "9bcf8f0f872020e588995f39b82e3ceb454e415f7edef4ecf7a5007dc50f8824", - material: { - kind: "seed", - seed: "9OLA_8sUT8OZ0ILgUUzjI3Bq_uBKGa9Z5fmAPhf1RmE", - }, - }); - }); - - it("uses signature context separation", async () => { - const identity = await createIdentity(); - const signature = await signUtf8(identity, "hello", { context: "one" }); - - expect( - await verifyUtf8(identity.publicKey, "hello", signature, { - context: "one", - }), - ).toBe(true); - expect( - await verifyUtf8(identity.publicKey, "hello", signature, { - context: "two", - }), - ).toBe(false); - }); - - it("matches X25519 public derivation from seed and public conversion", async () => { - const identity = await createIdentity(); - - expect(await deriveX25519PublicKey(identity)).toBe( - await convertEd25519PublicKeyToX25519PublicKey(identity.publicKey), - ); - }); - - it("derives stable age-compatible recipient and secret strings", async () => { - const identity = await createIdentity(); - - const recipient = await deriveAgeRecipient(identity); - const secret = await deriveAgeSecretKey(identity); - - expect(recipient.startsWith("age1")).toBe(true); - expect(secret.startsWith("AGE-SECRET-KEY-1")).toBe(true); - expect(await deriveAgeRecipient(identity)).toBe(recipient); - expect(await deriveAgeSecretKey(identity)).toBe(secret); - }); - - it("never serializes mnemonic material into the exported identity", async () => { - const identity = await createIdentityFromMnemonic({ - mnemonic: - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", - passphrase: "TREZOR", - createdAt: "2026-03-16T00:00:00.000Z", - }); - const exported = JSON.parse(serializeIdentity(identity)) as Record; - - expect(exported.material).toEqual(identity.material); - expect(exported.mnemonic).toBeUndefined(); - expect(exported.passphrase).toBeUndefined(); - }); -}); diff --git a/packages/identity/test/strict.test.ts b/packages/identity/test/strict.test.ts index 0fd8359..2af8892 100644 --- a/packages/identity/test/strict.test.ts +++ b/packages/identity/test/strict.test.ts @@ -1,18 +1,15 @@ import { readFileSync } from "node:fs"; import { expect, test } from "vite-plus/test"; -import { ed25519 } from "@noble/curves/ed25519.js"; +import { ed25519, x25519 } from "@noble/curves/ed25519.js"; import { sha256 } from "@noble/hashes/sha2.js"; -import { hex } from "@scure/base"; +import { base64urlnopad, bech32, hex } from "@scure/base"; import { - signerFromSeed, + restoreIdentity, validatePublicIdentity, - verifySignature, - ageRecipientFromSecret, - ageSecretKey, - encodeBase64Url, - type PrimitiveResult, + verify, type PublicIdentity, } from "../src/index.js"; + const vector = JSON.parse( readFileSync(new URL("../../../docs/concord/vectors/primitives.json", import.meta.url), "utf8"), ).identity as { @@ -23,39 +20,38 @@ const vector = JSON.parse( ageSecretKey: string; rfc8032EmptyMessageSignatureHex: string; }; -function value(result: PrimitiveResult): T { - if (!result.ok) throw new Error(result.error.code); - return result.value; -} -test("P05: retained derivation primitives match the independent raw signature and age vector", async () => { - const seed = hex.decode(vector.seedHex); - const signer = value(await signerFromSeed(seed)); - seed.fill(0); - expect(signer.publicIdentity).toEqual(vector.public); - const signature = value(await signer.sign(new Uint8Array())); + +const backup = JSON.stringify({ + format: "ternent-identity", + version: "2", + algorithm: "Ed25519", + createdAt: "2026-01-01T00:00:00.000Z", + publicKey: vector.public.publicKey, + keyId: vector.public.id.slice("identity:".length), + material: { kind: "seed", seed: base64urlnopad.encode(hex.decode(vector.seedHex)) }, +}); + +test("a restored seed matches the independent signature and age vectors", async () => { + const identity = await restoreIdentity(backup); + expect(identity.publicIdentity).toEqual(vector.public); + const signature = await identity.sign(new Uint8Array()); expect(hex.encode(signature)).toBe(vector.rfc8032EmptyMessageSignatureHex); - expect(value(await verifySignature(vector.public, new Uint8Array(), signature))).toBe(true); - let borrowed: Uint8Array | undefined; - await signer.withX25519Secret(async (secret) => { - borrowed = secret; - await Promise.resolve(); + expect(await verify(vector.public, new Uint8Array(), signature)).toBe(true); + await identity.withX25519Secret((secret) => { expect(hex.encode(secret)).toBe(vector.x25519SecretHex); - expect(ageRecipientFromSecret(secret)).toBe(vector.ageRecipient); - expect(ageSecretKey(secret)).toBe(vector.ageSecretKey); + expect(bech32.encode("age", bech32.toWords(x25519.getPublicKey(secret)))).toBe( + vector.ageRecipient, + ); + expect(bech32.encode("age-secret-key-", bech32.toWords(secret)).toUpperCase()).toBe( + vector.ageSecretKey, + ); }); - expect(borrowed?.every((byte) => byte === 0)).toBe(true); - await expect( - signer.withX25519Secret((secret) => { - borrowed = secret; - throw new Error("callback"); - }), - ).rejects.toThrow("callback"); - expect(borrowed?.every((byte) => byte === 0)).toBe(true); }); -test("P06/P07: identity binding, noncanonical, small and mixed-order points fail strict validation", () => { - expect( + +test("identity binding, non-canonical, small-order and mixed-order keys fail validation", async () => { + expect(() => validatePublicIdentity({ ...vector.public, id: `identity:${"0".repeat(64)}` }), - ).toMatchObject({ ok: false }); + ).toThrow(); const mixed = ed25519.Point.BASE.add( ed25519.Point.fromBytes(hex.decode(`ec${"ff".repeat(30)}7f`), false), ).toBytes(); @@ -65,25 +61,24 @@ test("P06/P07: identity binding, noncanonical, small and mixed-order points fail hex.decode(`ed${"ff".repeat(30)}7f`), mixed, ]) { - expect( - validatePublicIdentity({ - ...vector.public, - publicKey: encodeBase64Url(bytes), - id: `identity:${hex.encode(sha256(bytes))}`, - }), - ).toMatchObject({ ok: false }); + const publicIdentity = { + ...vector.public, + publicKey: base64urlnopad.encode(bytes), + id: `identity:${hex.encode(sha256(bytes))}`, + }; + expect(() => validatePublicIdentity(publicIdentity)).toThrow(); + expect(await verify(publicIdentity, new Uint8Array(), new Uint8Array(64))).toBe(false); } }); -test("P07: signature R and S are strictly validated", async () => { + +test("signature R and S are strictly validated", async () => { const signature = hex.decode(vector.rfc8032EmptyMessageSignatureHex); const smallR = signature.slice(); smallR.fill(0, 0, 32); smallR[0] = 1; const badS = signature.slice(); badS.fill(255, 32); - for (const invalid of [smallR, badS]) - expect(await verifySignature(vector.public, new Uint8Array(), invalid)).toMatchObject({ - ok: false, - error: { code: "SIGNATURE_INVALID" }, - }); + for (const invalid of [smallR, badS]) { + expect(await verify(vector.public, new Uint8Array(), invalid)).toBe(false); + } }); diff --git a/packages/identity/vite.config.ts.timestamp-1783937652146-39c0190f2cc6e.mjs b/packages/identity/vite.config.ts.timestamp-1783937652146-39c0190f2cc6e.mjs deleted file mode 100644 index 90594c7..0000000 --- a/packages/identity/vite.config.ts.timestamp-1783937652146-39c0190f2cc6e.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// vite.config.ts -import { resolve } from "node:path"; -import { defineConfig } from "file:///Users/sam/dev/ternent/core/node_modules/.pnpm/vite@2.9.18/node_modules/vite/dist/node/index.js"; -var __vite_injected_original_dirname = "/Users/sam/dev/ternent/core/packages/identity"; -var vite_config_default = defineConfig({ - build: { - target: "es2020", - lib: { - entry: resolve(__vite_injected_original_dirname, "src/index.ts"), - name: "ternentIdentityV2", - fileName: "index" - }, - rollupOptions: {} - }, - test: { - environment: "node" - } -}); -export { - vite_config_default as default -}; -//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvc2FtL2Rldi90ZXJuZW50L2NvcmUvcGFja2FnZXMvaWRlbnRpdHlcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfZmlsZW5hbWUgPSBcIi9Vc2Vycy9zYW0vZGV2L3Rlcm5lbnQvY29yZS9wYWNrYWdlcy9pZGVudGl0eS92aXRlLmNvbmZpZy50c1wiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9pbXBvcnRfbWV0YV91cmwgPSBcImZpbGU6Ly8vVXNlcnMvc2FtL2Rldi90ZXJuZW50L2NvcmUvcGFja2FnZXMvaWRlbnRpdHkvdml0ZS5jb25maWcudHNcIjtpbXBvcnQgeyByZXNvbHZlIH0gZnJvbSBcIm5vZGU6cGF0aFwiO1xuaW1wb3J0IHsgZGVmaW5lQ29uZmlnIH0gZnJvbSBcInZpdGVcIjtcblxuZXhwb3J0IGRlZmF1bHQgZGVmaW5lQ29uZmlnKHtcbiAgYnVpbGQ6IHtcbiAgICB0YXJnZXQ6IFwiZXMyMDIwXCIsXG4gICAgbGliOiB7XG4gICAgICBlbnRyeTogcmVzb2x2ZShfX2Rpcm5hbWUsIFwic3JjL2luZGV4LnRzXCIpLFxuICAgICAgbmFtZTogXCJ0ZXJuZW50SWRlbnRpdHlWMlwiLFxuICAgICAgZmlsZU5hbWU6IFwiaW5kZXhcIixcbiAgICB9LFxuICAgIHJvbGx1cE9wdGlvbnM6IHt9LFxuICB9LFxuICB0ZXN0OiB7XG4gICAgZW52aXJvbm1lbnQ6IFwibm9kZVwiLFxuICB9LFxufSk7XG4iXSwKICAibWFwcGluZ3MiOiAiO0FBQXlULFNBQVMsZUFBZTtBQUNqVixTQUFTLG9CQUFvQjtBQUQ3QixJQUFNLG1DQUFtQztBQUd6QyxJQUFPLHNCQUFRLGFBQWE7QUFBQSxFQUMxQixPQUFPO0FBQUEsSUFDTCxRQUFRO0FBQUEsSUFDUixLQUFLO0FBQUEsTUFDSCxPQUFPLFFBQVEsa0NBQVcsY0FBYztBQUFBLE1BQ3hDLE1BQU07QUFBQSxNQUNOLFVBQVU7QUFBQSxJQUNaO0FBQUEsSUFDQSxlQUFlLENBQUM7QUFBQSxFQUNsQjtBQUFBLEVBQ0EsTUFBTTtBQUFBLElBQ0osYUFBYTtBQUFBLEVBQ2Y7QUFDRixDQUFDOyIsCiAgIm5hbWVzIjogW10KfQo= diff --git a/packages/identity/vite.config.ts.timestamp-1786211734250-16c74f09d8ebb.mjs b/packages/identity/vite.config.ts.timestamp-1786211734250-16c74f09d8ebb.mjs deleted file mode 100644 index 90594c7..0000000 --- a/packages/identity/vite.config.ts.timestamp-1786211734250-16c74f09d8ebb.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// vite.config.ts -import { resolve } from "node:path"; -import { defineConfig } from "file:///Users/sam/dev/ternent/core/node_modules/.pnpm/vite@2.9.18/node_modules/vite/dist/node/index.js"; -var __vite_injected_original_dirname = "/Users/sam/dev/ternent/core/packages/identity"; -var vite_config_default = defineConfig({ - build: { - target: "es2020", - lib: { - entry: resolve(__vite_injected_original_dirname, "src/index.ts"), - name: "ternentIdentityV2", - fileName: "index" - }, - rollupOptions: {} - }, - test: { - environment: "node" - } -}); -export { - vite_config_default as default -}; -//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvc2FtL2Rldi90ZXJuZW50L2NvcmUvcGFja2FnZXMvaWRlbnRpdHlcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfZmlsZW5hbWUgPSBcIi9Vc2Vycy9zYW0vZGV2L3Rlcm5lbnQvY29yZS9wYWNrYWdlcy9pZGVudGl0eS92aXRlLmNvbmZpZy50c1wiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9pbXBvcnRfbWV0YV91cmwgPSBcImZpbGU6Ly8vVXNlcnMvc2FtL2Rldi90ZXJuZW50L2NvcmUvcGFja2FnZXMvaWRlbnRpdHkvdml0ZS5jb25maWcudHNcIjtpbXBvcnQgeyByZXNvbHZlIH0gZnJvbSBcIm5vZGU6cGF0aFwiO1xuaW1wb3J0IHsgZGVmaW5lQ29uZmlnIH0gZnJvbSBcInZpdGVcIjtcblxuZXhwb3J0IGRlZmF1bHQgZGVmaW5lQ29uZmlnKHtcbiAgYnVpbGQ6IHtcbiAgICB0YXJnZXQ6IFwiZXMyMDIwXCIsXG4gICAgbGliOiB7XG4gICAgICBlbnRyeTogcmVzb2x2ZShfX2Rpcm5hbWUsIFwic3JjL2luZGV4LnRzXCIpLFxuICAgICAgbmFtZTogXCJ0ZXJuZW50SWRlbnRpdHlWMlwiLFxuICAgICAgZmlsZU5hbWU6IFwiaW5kZXhcIixcbiAgICB9LFxuICAgIHJvbGx1cE9wdGlvbnM6IHt9LFxuICB9LFxuICB0ZXN0OiB7XG4gICAgZW52aXJvbm1lbnQ6IFwibm9kZVwiLFxuICB9LFxufSk7XG4iXSwKICAibWFwcGluZ3MiOiAiO0FBQXlULFNBQVMsZUFBZTtBQUNqVixTQUFTLG9CQUFvQjtBQUQ3QixJQUFNLG1DQUFtQztBQUd6QyxJQUFPLHNCQUFRLGFBQWE7QUFBQSxFQUMxQixPQUFPO0FBQUEsSUFDTCxRQUFRO0FBQUEsSUFDUixLQUFLO0FBQUEsTUFDSCxPQUFPLFFBQVEsa0NBQVcsY0FBYztBQUFBLE1BQ3hDLE1BQU07QUFBQSxNQUNOLFVBQVU7QUFBQSxJQUNaO0FBQUEsSUFDQSxlQUFlLENBQUM7QUFBQSxFQUNsQjtBQUFBLEVBQ0EsTUFBTTtBQUFBLElBQ0osYUFBYTtBQUFBLEVBQ2Y7QUFDRixDQUFDOyIsCiAgIm5hbWVzIjogW10KfQo= From 4e6c5099c3061acffe88594280cfbe135a0860f0 Mon Sep 17 00:00:00 2001 From: samternent Date: Fri, 27 Nov 2026 23:21:02 +0000 Subject: [PATCH 02/24] feat(seal)!: rewrite as one detached proof over a content hash Replace the proof, artifact, manifest, public-key and error APIs with createSealHash, createSealProof and verifySealProof. A seal v1 proof signs "ternent-seal/v1" || 0x00 || canonical JSON of its fields with an Identity, and verification reports signature and hash results separately. The CLI keeps sign and verify, reading the signer from SEAL_IDENTITY_FILE. Armour is no longer a dependency. Test vectors live in the package. Consumers are not yet adapted. Co-Authored-By: Claude Opus 5.5 --- packages/seal/README.md | 142 +++----- packages/seal/llms.txt | 72 +--- packages/seal/package.json | 26 +- packages/seal/src/artifact.ts | 393 ---------------------- packages/seal/src/cli.ts | 420 +++--------------------- packages/seal/src/commands/identity.ts | 52 --- packages/seal/src/commands/manifest.ts | 71 ---- packages/seal/src/commands/publicKey.ts | 7 - packages/seal/src/commands/sign.ts | 56 ---- packages/seal/src/commands/verify.ts | 55 ---- packages/seal/src/crypto.ts | 112 ------- packages/seal/src/errors.ts | 88 ----- packages/seal/src/index.ts | 140 +++++++- packages/seal/src/json.ts | 63 ---- packages/seal/src/manifest.ts | 119 ------- packages/seal/src/node.ts | 22 -- packages/seal/src/proof.ts | 363 -------------------- packages/seal/test/artifact.test.ts | 182 ---------- packages/seal/test/cli.test.ts | 262 ++++----------- packages/seal/test/crypto.test.ts | 33 -- packages/seal/test/fixtures.ts | 22 -- packages/seal/test/manifest.test.ts | 106 ------ packages/seal/test/proof.test.ts | 204 ------------ packages/seal/test/seal.test.ts | 172 ++++++++++ packages/seal/test/vectors.json | 60 ++++ packages/seal/vite.config.ts | 10 +- pnpm-lock.yaml | 304 +---------------- 27 files changed, 550 insertions(+), 3006 deletions(-) delete mode 100644 packages/seal/src/artifact.ts delete mode 100644 packages/seal/src/commands/identity.ts delete mode 100644 packages/seal/src/commands/manifest.ts delete mode 100644 packages/seal/src/commands/publicKey.ts delete mode 100644 packages/seal/src/commands/sign.ts delete mode 100644 packages/seal/src/commands/verify.ts delete mode 100644 packages/seal/src/crypto.ts delete mode 100644 packages/seal/src/errors.ts delete mode 100644 packages/seal/src/json.ts delete mode 100644 packages/seal/src/manifest.ts delete mode 100644 packages/seal/src/node.ts delete mode 100644 packages/seal/src/proof.ts delete mode 100644 packages/seal/test/artifact.test.ts delete mode 100644 packages/seal/test/crypto.test.ts delete mode 100644 packages/seal/test/fixtures.ts delete mode 100644 packages/seal/test/manifest.test.ts delete mode 100644 packages/seal/test/proof.test.ts create mode 100644 packages/seal/test/seal.test.ts create mode 100644 packages/seal/test/vectors.json diff --git a/packages/seal/README.md b/packages/seal/README.md index f36f4b8..789be2a 100644 --- a/packages/seal/README.md +++ b/packages/seal/README.md @@ -1,120 +1,58 @@ # @ternent/seal -[Agent interface guide](llms.txt): public imports, examples and lifecycle contracts. - -Standalone file/manifest proofs and recipient-encrypted artifacts, with a browser-safe -library and the Node `seal` executable. Uses the public Identity and Armour APIs; -Armour's typage implementation needs no initialization or WASM step. - -The stable interface version is `0.5.0`. -Proof/public-key wire version remains `2`; manifest/artifact wire version remains `1`. -The public proof type is `SealProofV2`. - -## Library +A detached Ed25519 proof over a content hash. Identity supplies the signer. ```ts -import { createSealIdentity } from "@ternent/seal/crypto"; -import { createSealHash, createSealProof, verifySealProofAgainstBytes } from "@ternent/seal/proof"; +import { createSealHash, createSealProof, verifySealProof } from "@ternent/seal"; -const identity = await createSealIdentity(); -const bytes = new TextEncoder().encode("signed bytes"); const proof = await createSealProof({ - signer: { identity }, - subject: { kind: "file", path: "example.txt", hash: await createSealHash(bytes) }, + signer: identity, + subject: { hash: await createSealHash(bytes) }, }); -const result = await verifySealProofAgainstBytes(proof, bytes); +const { valid, signatureValid, hashMatch } = await verifySealProof(proof, bytes); ``` -Root re-exports the library. Typed subpaths are `/proof`, `/artifact`, `/manifest`, -`/crypto` and `/errors`. They import no Node filesystem/CLI code. The CLI is a separate -executable, with no import-time execution from public library paths. No Concord or -Utils dependency is required. - -```ts -import { recipientFromIdentity } from "@ternent/armour"; -import { - createSealArtifact, - verifySealArtifact, - decryptSealArtifactPayload, -} from "@ternent/seal/artifact"; - -const recipient = await createSealIdentity(); -const artifact = await createSealArtifact({ - signer: { identity }, - subjectPath: "example.txt", - payload: bytes, - recipients: [await recipientFromIdentity(recipient)], -}); -const verification = await verifySealArtifact(artifact); -const plaintext = await decryptSealArtifactPayload({ artifact, identity: recipient }); +`createSealHash(bytes)` returns `sha256:` and 64 lowercase hex digits (Web Crypto). +`createSealProof({ signer, subject, createdAt? })` signs with any object that has an +Identity's `publicIdentity` and `sign`, checks the returned signature, and returns the +proof. `verifySealProof(proof, bytes)` never throws: a malformed proof is invalid. +`valid` needs both the signature and the hash to match. + +A valid proof says which key signed. Whether that key is trusted is the caller's +decision: compare `proof.signer` with the public identity you expect. + +Seal anything as bytes. For a release, seal a manifest that lists the release and +each file's hash, then check the files against it. For encrypted data, seal the exact +ciphertext bytes you store, so the proof verifies before decryption. For armored +text, hash its UTF-8 bytes, line endings included. + +## Format + +```json +{ + "format": "seal", + "version": 1, + "createdAt": "2026-11-26T12:00:00.000Z", + "subject": { "hash": "sha256:e3b0c442…b855" }, + "signer": { "version": 1, "algorithm": "Ed25519", "publicKey": "…", "id": "identity:…" }, + "signature": "…" +} ``` -Verification is offline. The proof binds the canonical unsigned proof fields with -Ed25519 over `UTF8("ternent-seal/v2") || 0x00 || UTF8(payload)`. Signer key ID is the -SHA-256 of its raw Ed25519 public key. Signing validates seed/public-key/key-ID binding; -verification uses Identity's strict point, encoding and signature checks. Valid signatures -identify a key; the caller decides whether that signer is trusted. - -Artifact verification checks the signed unsigned-container hash and the armored -ciphertext hash before decryption. Payload bytes are encrypted; proof signer, subject -path, timestamp, container metadata, sizes and age headers remain public. Recipients -are not added as plaintext JSON fields; no traffic-pattern or metadata-hiding promise -is made. Verification does not prove other recipients can decrypt. - -Canonical JSON accepts plain objects, normal arrays, valid Unicode strings, booleans, -null and safe integers, with a depth limit of 64. It rejects accessors, custom prototypes, -`toJSON` hooks, symbols, cycles, sparse arrays, undefined, bigint, nonfinite/fractional -numbers and negative zero. Object keys sort by UTF-16 code units before native JSON -serialization; native integer-index enumeration is retained from the prior Seal codec. -The format is Seal's own contract, not Concord canonicalization or a JCS claim. -See [the format and fixed evidence](../../docs/seal/format.md). +The signature covers `UTF8("ternent-seal/v1") || 0x00 || JSON` of every field except +`signature`, with object keys in UTF-16 order and no whitespace. Verification accepts +exactly these fields, a millisecond UTC `createdAt` and canonical unpadded base64url. +`createdAt` is the signer's claim, not evidence of time. ## CLI -Run the installed package's `seal` executable. - ```sh -seal --help -seal identity create --out identity.json --words 24 --mnemonic-out seal-backup.txt --quiet -export SEAL_IDENTITY_FILE=./identity.json -seal manifest create --input dist --out dist/dist-manifest.json --quiet -seal sign --input dist/dist-manifest.json --out dist/proof.json --quiet -seal verify --proof dist/proof.json --input dist/dist-manifest.json --json -seal public-key --json -seal sign --input example.txt --recipient age1... --out example.seal.json --quiet -seal verify --artifact example.seal.json --json +SEAL_IDENTITY_FILE=identity.json seal sign --input release-manifest.json --out proof.json +seal verify --proof proof.json --input release-manifest.json ``` -`SEAL_IDENTITY` may instead contain the serialized Identity v2 JSON and takes precedence -over `SEAL_IDENTITY_FILE`. Identity and mnemonic output files are created/written with -owner-only mode `0600`. `--quiet` suppresses normal output; without it, identity creation -may print the secret identity/backup when JSON output is requested. Keep signer files -outside the directory being manifested. Manifest creation hashes the actual files in -its input tree, skips `.DS_Store` and non-file/non-directory entries, and includes -prototype-like filenames safely. Use a clean build directory before generating the -manifest/proof/public-key outputs into it. - -| Exit | Meaning | -| ---- | --------------------------------------------------- | -| 0 | Success, including help | -| 1 | General/argument/encryption failure | -| 2 | Subject or artifact hash mismatch | -| 3 | Invalid signature or signer key binding | -| 4 | Malformed proof/artifact schema or JSON | -| 5 | Missing, unreadable or invalid signer configuration | - -The separately maintained Seal Action accepts `package-name`, `package-version` and -`cli-command`. Its observed defaults still target the old package name. Select -`@ternent/seal` and an actually published version when using its package path; an -explicit CLI override can exercise a locally installed candidate. This migration -proves its manifest/sign/public-key command sequence against the installed executable. -Core CI also pins and invokes the actual Action with an explicit CLI command to sign -the release candidate bundle, then verifies its complete file set and proof with a -disposable test key. Production release verification requires an externally trusted -public key. The Action is independently released. Published-package acceptance is recorded -in the repository release record. +`sign` reads an Identity backup from `SEAL_IDENTITY_FILE` and prints the proof +unless `--out` is given. `verify` prints `{ valid, signatureValid, hashMatch }`. +Exit codes: 0 success, 1 error, 2 invalid proof. -[Repository acceptance](../../docs/engineering/repository-hygiene.md#acceptance-boundaries) -describes source and installed-consumer checks. -[Release evidence](../../docs/engineering/release-and-deployment.md) is separate -from local candidate verification. +License: ISC. diff --git a/packages/seal/llms.txt b/packages/seal/llms.txt index 56f6cfa..94a6a6a 100644 --- a/packages/seal/llms.txt +++ b/packages/seal/llms.txt @@ -1,63 +1,27 @@ # @ternent/seal -> Standalone proofs, encrypted artifacts, manifests and the Node seal executable. +> Detached Ed25519 proofs over SHA-256 content hashes, plus a `seal` CLI. -Stable interface: `npm install @ternent/seal@0.5.0`. -[Public README](https://github.com/ternent/core/blob/main/packages/seal/README.md). -Declarations accompany each dist entry. Root and `/proof`, `/artifact`, `/manifest`, -`/crypto`, `/errors` are browser-safe. CLI/filesystem operations require Node. - -## Sign and verify exact file bytes +Three exports from the package root: `createSealHash`, `createSealProof`, `verifySealProof`. +Types: `SealProof`, `SealHash`, `SealVerification`. Declarations: `dist/index.d.ts`. ```ts -import { createSealIdentity } from "@ternent/seal/crypto"; -import { createSealHash, createSealProof, verifySealProofAgainstBytes } from "@ternent/seal/proof"; -const identity = await createSealIdentity(); -const bytes = new TextEncoder().encode("signed content"); +import { createIdentity } from "@ternent/identity"; +import { createSealHash, createSealProof, verifySealProof } from "@ternent/seal"; + +const identity = await createIdentity(); const proof = await createSealProof({ - signer: { identity }, - subject: { kind: "file", path: "example.txt", hash: await createSealHash(bytes) }, + signer: identity, // any { publicIdentity, sign } from @ternent/identity + subject: { hash: await createSealHash(bytes) }, }); -const checked = await verifySealProofAgainstBytes(proof, bytes); -if (!checked.valid) throw new Error("Verification failed"); -``` - -Identity helpers return a private SerializedIdentity, not a capability Result. Host -helpers reject/throw on invalid input. verifySealProofAgainstBytes reports valid, -hashMatch and signatureValid separately. Valid signatures identify a public key; -the caller must compare it against an independently trusted key. A public-key artifact -bundled with a proof cannot establish its own trust. - -Proof/public-key wire version is 2 (SealProofV2); manifest/artifact wire version is 1. -Package semver is unrelated. Use Seal's functions for canonical proof bytes and hashes. -It has its own canonical JSON contract; do not substitute Ledger canonicalization or -claim JCS compatibility. Proof signing uses context ternent-seal/v2. - -## Encrypted artifacts - -createSealArtifact({ signer: { identity }, subjectPath, payload: bytes, recipients }) -returns an encrypted artifact. Obtain age recipients with Armour recipientFromIdentity -for serialized identities. verifySealArtifact checks the proof, unsigned container hash -and ciphertext hash; decryptSealArtifactPayload({ artifact, identity }) verifies before -asking Armour for plaintext. Decryption requires a recipient's private identity. -Metadata, signer, path, timing, size and age headers remain public. No init is needed. -Seal is independent of Concord and is not a Concord document or authority system. - -## Node CLI - -```sh -seal --help -seal identity create --out identity.json --words 24 --mnemonic-out backup.txt --quiet -export SEAL_IDENTITY_FILE=./identity.json -seal sign --input example.txt --out proof.json --quiet -seal verify --proof proof.json --input example.txt --json -seal public-key --json +const { valid } = await verifySealProof(proof, bytes); +if (!valid || proof.signer.id !== trustedPublisher.id) throw new Error("Untrusted"); ``` -SEAL_IDENTITY (serialized private JSON) takes precedence over SEAL_IDENTITY_FILE. -Use private identity/backup files outside build assets; never commit them. Manifest -creation hashes regular files and skips symlinks. Keep outputs outside the input tree -or generate them only after the intended build is complete. CLI exits: 0 success, -1 general/argument/encryption error, 2 hash mismatch, 3 signature/key-binding failure, -4 malformed schema/JSON, 5 missing/invalid signer configuration. Use quiet to avoid -printing private identity/recovery material. No separate Seal CLI package is needed. +- `verifySealProof` never throws; malformed proofs return `valid: false`. +- `signatureValid` and `hashMatch` are reported separately; `valid` needs both. +- Seal does not decide trust. Pin the expected signer yourself. +- Seal has no recipients or encryption. To prove encrypted data, seal its ciphertext bytes. +- To prove several files, seal a manifest of their hashes and check each file yourself. +- CLI: `seal sign --input [--out ]` with `SEAL_IDENTITY_FILE` set; + `seal verify --proof --input `. Exit 0 ok, 1 error, 2 invalid proof. diff --git a/packages/seal/package.json b/packages/seal/package.json index 8f08a1a..e3d449f 100644 --- a/packages/seal/package.json +++ b/packages/seal/package.json @@ -1,11 +1,11 @@ { "name": "@ternent/seal", "version": "0.5.0", - "description": "Deterministic artifact signing for Seal", + "description": "Detached Ed25519 proofs over content hashes", "keywords": [ "cli", "integrity", - "manifest", + "proof", "seal", "signature" ], @@ -37,26 +37,6 @@ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" - }, - "./proof": { - "types": "./dist/proof.d.ts", - "import": "./dist/proof.js" - }, - "./artifact": { - "types": "./dist/artifact.d.ts", - "import": "./dist/artifact.js" - }, - "./manifest": { - "types": "./dist/manifest.d.ts", - "import": "./dist/manifest.js" - }, - "./crypto": { - "types": "./dist/crypto.d.ts", - "import": "./dist/crypto.js" - }, - "./errors": { - "types": "./dist/errors.d.ts", - "import": "./dist/errors.js" } }, "publishConfig": { @@ -72,7 +52,7 @@ "check": "pnpm --filter @ternent/seal... run build && pnpm run fmt:check && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run check:artifact" }, "dependencies": { - "@ternent/armour": "workspace:^", + "@scure/base": "2.4.0", "@ternent/identity": "workspace:^" }, "devDependencies": { diff --git a/packages/seal/src/artifact.ts b/packages/seal/src/artifact.ts deleted file mode 100644 index a2f0172..0000000 --- a/packages/seal/src/artifact.ts +++ /dev/null @@ -1,393 +0,0 @@ -import { - decryptWithIdentity, - encryptForRecipients, - type ArmourIdentityInput, -} from "@ternent/armour"; -import { canonicalStringify, copyJson } from "./json.js"; -import type { SealHash } from "./manifest.js"; -import { - createSealHash, - createSealProof, - validateSealProofShape, - verifySealProofSignature, - type SealProofV2, -} from "./proof.js"; -import type { SealSignerInput } from "./crypto.js"; -import { - toSealDecryptionError, - toSealEncryptionError, - unsupportedEncryptionModeError, -} from "./errors.js"; - -const utf8Encoder = new TextEncoder(); -const utf8Decoder = new TextDecoder(); - -export const SEAL_ARTIFACT_VERSION = "1" as const; -export const SEAL_ARTIFACT_TYPE = "seal-artifact" as const; -export const SEAL_ARTIFACT_MANIFEST_VERSION = "1" as const; - -export type SealArtifactManifestV1 = { - version: typeof SEAL_ARTIFACT_MANIFEST_VERSION; - payloadType: "encrypted"; - payloadScheme: "age"; - payloadMode: "recipients"; - payloadEncoding: "armor"; - payloadHash: SealHash; -}; - -export type SealEncryptedPayloadV1 = { - type: "encrypted"; - scheme: "age"; - mode: "recipients"; - encoding: "armor"; - data: string; -}; - -export type SealArtifactUnsignedV1 = { - version: typeof SEAL_ARTIFACT_VERSION; - type: typeof SEAL_ARTIFACT_TYPE; - manifest: SealArtifactManifestV1; - payload: SealEncryptedPayloadV1; -}; - -export type SealArtifactV1 = SealArtifactUnsignedV1 & { - proof: SealProofV2; -}; - -export type VerifySealArtifactResult = { - valid: boolean; - hashMatch: boolean; - signatureValid: boolean; - encrypted: boolean; - payloadScheme: "age"; - payloadMode: "recipients"; - keyId: string; - algorithm: SealProofV2["algorithm"]; - subjectHash: SealHash; - errors: string[]; -}; - -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === "object" && !Array.isArray(value); -} - -function hasOnlyKeys(value: Record, allowed: string[]): boolean { - return Object.keys(value).every((key) => allowed.includes(key)); -} - -function isSealHash(value: unknown): value is SealHash { - return typeof value === "string" && /^sha256:[0-9a-f]{64}$/.test(value); -} - -function normalizeBytes(value: Uint8Array | ArrayBuffer): Uint8Array { - if (!(value instanceof Uint8Array) && !(value instanceof ArrayBuffer)) - throw new TypeError("Expected payload bytes"); - return value instanceof Uint8Array ? new Uint8Array(value) : new Uint8Array(value.slice(0)); -} - -export function getSealArtifactUnsignedFields( - artifact: SealArtifactV1 | SealArtifactUnsignedV1, -): SealArtifactUnsignedV1 { - artifact = copyJson(artifact); - return { - version: artifact.version, - type: artifact.type, - manifest: artifact.manifest, - payload: artifact.payload, - }; -} - -function getUnsignedArtifactBytes(artifact: SealArtifactV1 | SealArtifactUnsignedV1): Uint8Array { - return utf8Encoder.encode(canonicalStringify(getSealArtifactUnsignedFields(artifact))); -} - -export async function createSealArtifact(input: { - createdAt?: string; - signer: SealSignerInput; - subjectPath: string; - payload: Uint8Array | ArrayBuffer; - recipients: string[]; -}): Promise { - const plaintext = normalizeBytes(input.payload); - const recipients = [...input.recipients]; - const subjectPath = input.subjectPath; - const createdAt = input.createdAt; - const signer = { identity: copyJson(input.signer.identity) }; - - try { - const ciphertext = await encryptForRecipients({ - recipients, - data: plaintext, - output: "armor", - }); - const payloadData = utf8Decoder.decode(ciphertext); - const manifest: SealArtifactManifestV1 = { - version: SEAL_ARTIFACT_MANIFEST_VERSION, - payloadType: "encrypted", - payloadScheme: "age", - payloadMode: "recipients", - payloadEncoding: "armor", - payloadHash: await createSealHash(ciphertext), - }; - const payload: SealEncryptedPayloadV1 = { - type: "encrypted", - scheme: "age", - mode: "recipients", - encoding: "armor", - data: payloadData, - }; - const unsignedArtifact: SealArtifactUnsignedV1 = { - version: SEAL_ARTIFACT_VERSION, - type: SEAL_ARTIFACT_TYPE, - manifest, - payload, - }; - - const proof = await createSealProof({ - createdAt, - signer, - subject: { - kind: "artifact", - path: subjectPath, - hash: await createSealHash(getUnsignedArtifactBytes(unsignedArtifact)), - }, - }); - - return { - ...unsignedArtifact, - proof, - }; - } catch (error) { - throw toSealEncryptionError(error); - } -} - -export function validateSealArtifactShape(value: unknown): { - ok: boolean; - errors: string[]; - artifact: SealArtifactV1 | null; -} { - try { - value = copyJson(value); - } catch { - return { ok: false, errors: ["Expected canonical JSON data."], artifact: null }; - } - if (!isRecord(value)) { - return { - ok: false, - errors: ["Artifact must be a JSON object."], - artifact: null, - }; - } - - const errors: string[] = []; - - if (!hasOnlyKeys(value, ["version", "type", "manifest", "payload", "proof"])) { - errors.push("Artifact contains unsupported fields."); - } - if (value.version !== SEAL_ARTIFACT_VERSION) { - errors.push(`Artifact version must be ${SEAL_ARTIFACT_VERSION}.`); - } - if (value.type !== SEAL_ARTIFACT_TYPE) { - errors.push(`Artifact type must be ${SEAL_ARTIFACT_TYPE}.`); - } - if (!isRecord(value.manifest)) { - errors.push("Artifact manifest must be an object."); - } - if (!isRecord(value.payload)) { - errors.push("Artifact payload must be an object."); - } - if (!isRecord(value.proof)) { - errors.push("Artifact proof must be an object."); - } - - if ( - errors.length > 0 || - !isRecord(value.manifest) || - !isRecord(value.payload) || - !isRecord(value.proof) - ) { - return { - ok: false, - errors, - artifact: null, - }; - } - - if ( - !hasOnlyKeys(value.manifest, [ - "version", - "payloadType", - "payloadScheme", - "payloadMode", - "payloadEncoding", - "payloadHash", - ]) - ) { - errors.push("Artifact manifest contains unsupported fields."); - } - if (!hasOnlyKeys(value.payload, ["type", "scheme", "mode", "encoding", "data"])) { - errors.push("Artifact payload contains unsupported fields."); - } - - if (value.manifest.version !== SEAL_ARTIFACT_MANIFEST_VERSION) { - errors.push(`Artifact manifest version must be ${SEAL_ARTIFACT_MANIFEST_VERSION}.`); - } - if (value.manifest.payloadType !== "encrypted") { - errors.push("Artifact manifest payloadType must be encrypted."); - } - if (value.manifest.payloadScheme !== "age") { - errors.push("Artifact manifest payloadScheme must be age."); - } - if (value.manifest.payloadMode !== "recipients") { - errors.push("Artifact manifest payloadMode must be recipients."); - } - if (value.manifest.payloadEncoding !== "armor") { - errors.push("Artifact manifest payloadEncoding must be armor."); - } - if (!isSealHash(value.manifest.payloadHash)) { - errors.push("Artifact manifest payloadHash must be a sha256 hash."); - } - - if (value.payload.type !== "encrypted") { - errors.push("Artifact payload type must be encrypted."); - } - if (value.payload.scheme !== "age") { - errors.push("Artifact payload scheme must be age."); - } - if (value.payload.mode !== "recipients") { - errors.push("Artifact payload mode must be recipients."); - } - if (value.payload.encoding !== "armor") { - errors.push("Artifact payload encoding must be armor."); - } - if (typeof value.payload.data !== "string" || value.payload.data.length === 0) { - errors.push("Artifact payload data must be a non-empty string."); - } - - if ( - value.manifest.payloadType !== value.payload.type || - value.manifest.payloadScheme !== value.payload.scheme || - value.manifest.payloadMode !== value.payload.mode || - value.manifest.payloadEncoding !== value.payload.encoding - ) { - errors.push("Artifact manifest and payload metadata must match."); - } - - const proofValidation = validateSealProofShape(value.proof); - if (!proofValidation.ok || !proofValidation.proof) { - errors.push(...proofValidation.errors); - } else if (proofValidation.proof.subject.kind !== "artifact") { - errors.push("Artifact proof subject kind must be artifact."); - } - - if (errors.length > 0) { - return { - ok: false, - errors, - artifact: null, - }; - } - - return { - ok: true, - errors: [], - artifact: value as SealArtifactV1, - }; -} - -export function parseSealArtifactJson(raw: string): { - ok: boolean; - errors: string[]; - artifact: SealArtifactV1 | null; -} { - try { - return validateSealArtifactShape(JSON.parse(raw)); - } catch { - return { - ok: false, - errors: ["Artifact JSON is not valid JSON."], - artifact: null, - }; - } -} - -export async function verifySealArtifact( - artifact: SealArtifactV1, -): Promise { - const validation = validateSealArtifactShape(artifact); - if (!validation.ok || !validation.artifact) { - return { - valid: false, - hashMatch: false, - signatureValid: false, - encrypted: true, - payloadScheme: "age", - payloadMode: "recipients", - keyId: "", - algorithm: "Ed25519", - subjectHash: "sha256:0000000000000000000000000000000000000000000000000000000000000000", - errors: validation.errors, - }; - } - - artifact = validation.artifact; - const signatureCheck = await verifySealProofSignature(artifact.proof); - const subjectHash = await createSealHash(getUnsignedArtifactBytes(artifact)); - const payloadHash = await createSealHash(utf8Encoder.encode(artifact.payload.data)); - const artifactHashMatch = artifact.proof.subject.hash === subjectHash; - const payloadHashMatch = artifact.manifest.payloadHash === payloadHash; - const errors = [...signatureCheck.errors]; - - if (!artifactHashMatch) { - errors.push("Artifact hash does not match proof subject hash."); - } - if (!payloadHashMatch) { - errors.push("Encrypted payload hash does not match manifest payload hash."); - } - - return { - valid: signatureCheck.ok && artifactHashMatch && payloadHashMatch, - hashMatch: artifactHashMatch && payloadHashMatch, - signatureValid: signatureCheck.ok, - encrypted: true, - payloadScheme: artifact.payload.scheme, - payloadMode: artifact.payload.mode, - keyId: artifact.proof.signer.keyId, - algorithm: artifact.proof.algorithm, - subjectHash, - errors, - }; -} - -export async function decryptSealArtifactPayload(input: { - artifact: SealArtifactV1; - identity: ArmourIdentityInput; -}): Promise { - const identity = copyJson(input.identity); - const snapshot = validateSealArtifactShape(input.artifact); - if (!snapshot.ok || !snapshot.artifact) throw new Error(snapshot.errors.join(" ")); - const artifact = snapshot.artifact; - const verification = await verifySealArtifact(artifact); - if (!verification.valid) { - throw new Error(verification.errors.join(" ") || "Artifact verification failed."); - } - - if ( - artifact.payload.type !== "encrypted" || - artifact.payload.scheme !== "age" || - artifact.payload.mode !== "recipients" || - artifact.payload.encoding !== "armor" - ) { - throw unsupportedEncryptionModeError("Seal only supports age recipient-mode armored payloads."); - } - - try { - return await decryptWithIdentity({ - identity, - data: utf8Encoder.encode(artifact.payload.data), - }); - } catch (error) { - throw toSealDecryptionError(error); - } -} diff --git a/packages/seal/src/cli.ts b/packages/seal/src/cli.ts index 3160c43..0964683 100644 --- a/packages/seal/src/cli.ts +++ b/packages/seal/src/cli.ts @@ -1,379 +1,63 @@ -import { mkdir, open, writeFile } from "node:fs/promises"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { createManifestArtifact } from "./commands/manifest.js"; -import { createIdentityArtifact } from "./commands/identity.js"; -import { createProofArtifact, createRecipientArtifact } from "./commands/sign.js"; -import { createPublicKeyArtifact } from "./commands/publicKey.js"; -import { verifyArtifactProof, verifyProofArtifact } from "./commands/verify.js"; -import { resolveSealIdentityFromEnv } from "./node.js"; -import { - EXIT_FAILURE, - EXIT_HASH_MISMATCH, - EXIT_INVALID_PROOF, - EXIT_KEY_CONFIG, - EXIT_SIGNATURE_INVALID, - EXIT_SUCCESS, - SealCliError, - getExitCode, -} from "./errors.js"; +import { readFile, writeFile } from "node:fs/promises"; +import { parseArgs } from "node:util"; +import { restoreIdentity } from "@ternent/identity"; +import { createSealHash, createSealProof, verifySealProof } from "./index.js"; -type ProcessEnvLike = Record; +const usage = `Usage: seal sign --input [--out ] + seal verify --proof --input -const usage = - "Usage: seal identity create [--out ] [--words 12|24] [--passphrase ] [--mnemonic-out ] [--json] [--quiet]\n" + - " seal manifest create --input [--out ] [--json] [--quiet]\n" + - " seal sign --input [--recipient ] [--out ] [--json] [--quiet]\n" + - " seal verify --proof --input [--json] [--quiet]\n" + - " seal verify --artifact [--json] [--quiet]\n" + - " seal public-key [--json] [--quiet]"; +sign reads the identity backup named by SEAL_IDENTITY_FILE. +Exit codes: 0 success, 1 error, 2 invalid proof.`; -type ParsedArgs = { - _: string[]; - flags: Record; +type Io = { + env: Record; + stdout: (text: string) => void; + stderr: (text: string) => void; }; -type OutputWriter = { - stdout: (value: string) => void; - stderr: (value: string) => void; +const processIo: Io = { + env: process.env, + stdout: (text) => process.stdout.write(text), + stderr: (text) => process.stderr.write(text), }; -function parseArgs(argv: string[]): ParsedArgs { - const result: ParsedArgs = { _: [], flags: Object.create(null) as ParsedArgs["flags"] }; - for (let index = 0; index < argv.length; index += 1) { - const arg = argv[index]; - if (!arg.startsWith("--")) { - result._.push(arg); - continue; - } - - const equals = arg.indexOf("="); - const rawKey = equals === -1 ? arg.slice(2) : arg.slice(2, equals); - const inlineValue = equals === -1 ? undefined : arg.slice(equals + 1); - const key = rawKey.trim(); - const next = argv[index + 1]; - const hasNextValue = inlineValue === undefined && next && !next.startsWith("--"); - const value = inlineValue ?? (hasNextValue ? next : undefined); - - if (hasNextValue) { - index += 1; - } - - if (value === undefined) { - result.flags[key] = true; - continue; - } - - const existing = result.flags[key]; - if (existing === undefined) { - result.flags[key] = value; - continue; - } - - if (Array.isArray(existing)) { - existing.push(value); - result.flags[key] = existing; - continue; - } - - result.flags[key] = [String(existing), value]; - } - - return result; -} - -function getFlag(flags: ParsedArgs["flags"], key: string): string | undefined { - const value = flags[key]; - if (Array.isArray(value)) { - return value[value.length - 1]; - } - return typeof value === "string" ? value : undefined; -} - -function getFlags(flags: ParsedArgs["flags"], key: string): string[] { - const value = flags[key]; - if (Array.isArray(value)) { - return value.map(String); - } - if (typeof value === "string") { - return [value]; - } - return []; -} - -function hasFlag(flags: ParsedArgs["flags"], key: string): boolean { - return flags[key] === true; -} - -function requireFlag(flags: ParsedArgs["flags"], key: string): string { - const value = getFlag(flags, key); - if (!value) { - throw new SealCliError(`Missing --${key}`, EXIT_FAILURE); - } - return value; -} - -function parseMnemonicWordCount(flags: ParsedArgs["flags"]): 12 | 24 | undefined { - const words = getFlag(flags, "words"); - if (!words) { - return undefined; - } - if (words === "12" || words === "24") { - return Number(words) as 12 | 24; - } - throw new SealCliError("Mnemonic word count must be 12 or 24.", EXIT_FAILURE); -} - -async function writeOutputFile(filePath: string, content: string, secret = false): Promise { - const resolvedPath = resolve(filePath); - await mkdir(dirname(resolvedPath), { recursive: true }); - if (secret) { - const file = await open(resolvedPath, "w", 0o600); - try { - await file.chmod(0o600); - await file.writeFile(content, "utf8"); - } finally { - await file.close(); - } - } else await writeFile(resolvedPath, content, "utf8"); -} - -function outputResult(writer: OutputWriter, json: boolean, quiet: boolean, value: unknown): void { - if (quiet) { - return; - } - - if (typeof value === "string") { - writer.stdout(`${value}\n`); - return; - } - - if (json) { - writer.stdout(`${JSON.stringify(value, null, 2)}\n`); - return; - } - - writer.stdout(`${JSON.stringify(value, null, 2)}\n`); -} - -function outputError(writer: OutputWriter, json: boolean, error: unknown): number { - const exitCode = getExitCode(error); - const message = error instanceof Error ? error.message : String(error); - if (json) { - writer.stderr(`${JSON.stringify({ error: message, exitCode }, null, 2)}\n`); - } else { - writer.stderr(`${message}\n`); - } - return exitCode; -} - -export async function runCli( - argv: string[], - params: { - env?: ProcessEnvLike; - writer?: OutputWriter; - } = {}, -): Promise { - const parsed = parseArgs(argv); - const env = params.env ?? process.env; - const writer: OutputWriter = params.writer ?? { - stdout: (value) => process.stdout.write(value), - stderr: (value) => process.stderr.write(value), - }; - const json = hasFlag(parsed.flags, "json"); - const quiet = hasFlag(parsed.flags, "quiet"); - +export async function runCli(argv: string[], io: Io = processIo): Promise { try { - const [command, subcommand] = parsed._; - if (hasFlag(parsed.flags, "help") || command === "help") { - if (!quiet) writer.stdout(`${usage}\n`); - return EXIT_SUCCESS; - } - - if (command === "identity" && subcommand === "create") { - const mnemonicOutPath = getFlag(parsed.flags, "mnemonic-out"); - const artifact = await createIdentityArtifact({ - withMnemonic: Boolean(mnemonicOutPath), - words: parseMnemonicWordCount(parsed.flags), - passphrase: getFlag(parsed.flags, "passphrase"), - }); - const outPath = getFlag(parsed.flags, "out"); - if (outPath) { - await writeOutputFile(outPath, artifact.content, true); - } - if (mnemonicOutPath) { - await writeOutputFile(mnemonicOutPath, artifact.mnemonicContent || "", true); - } - - if (outPath) { - outputResult( - writer, - json, - quiet, - json - ? artifact.mnemonic - ? { - identity: artifact.identity, - mnemonic: artifact.mnemonic, - mnemonicFile: mnemonicOutPath || null, - } - : artifact.identity - : outPath, - ); - } else { - outputResult( - writer, - true, - quiet, - artifact.mnemonic - ? { - identity: artifact.identity, - mnemonic: artifact.mnemonic, - mnemonicFile: mnemonicOutPath || null, - } - : artifact.identity, - ); - } - return EXIT_SUCCESS; - } - - if (command === "manifest" && subcommand === "create") { - const artifact = await createManifestArtifact(requireFlag(parsed.flags, "input")); - const outPath = getFlag(parsed.flags, "out"); - if (outPath) { - await writeOutputFile(outPath, artifact.content); - outputResult(writer, json, quiet, json ? artifact.manifest : outPath); - } else { - outputResult(writer, true, quiet, artifact.manifest); - } - return EXIT_SUCCESS; - } - - if (command === "sign") { - const identity = await resolveSealIdentityFromEnv(env); - const recipients = getFlags(parsed.flags, "recipient"); - const inputPath = requireFlag(parsed.flags, "input"); - const outPath = getFlag(parsed.flags, "out"); - if (recipients.length > 0) { - const artifact = await createRecipientArtifact({ - inputPath, - identity, - recipients, - }); - if (outPath) { - await writeOutputFile(outPath, artifact.content); - outputResult(writer, json, quiet, json ? artifact.artifact : outPath); - } else { - outputResult(writer, true, quiet, artifact.artifact); - } - } else { - const artifact = await createProofArtifact({ - inputPath, - identity, - }); - if (outPath) { - await writeOutputFile(outPath, artifact.content); - outputResult(writer, json, quiet, json ? artifact.proof : outPath); - } else { - outputResult(writer, true, quiet, artifact.proof); - } - } - return EXIT_SUCCESS; - } - - if (command === "verify") { - const artifactPath = getFlag(parsed.flags, "artifact"); - if (artifactPath) { - const { result } = await verifyArtifactProof({ artifactPath }); - outputResult( - writer, - json, - quiet, - json - ? result - : [ - `valid=${result.valid}`, - `hashMatch=${result.hashMatch}`, - `signatureValid=${result.signatureValid}`, - `encrypted=${result.encrypted}`, - `payloadScheme=${result.payloadScheme}`, - `payloadMode=${result.payloadMode}`, - `keyId=${result.keyId}`, - `algorithm=${result.algorithm}`, - `subjectHash=${result.subjectHash}`, - ].join("\n"), - ); - - if (!result.hashMatch) { - return EXIT_HASH_MISMATCH; - } - if (!result.signatureValid) { - return EXIT_SIGNATURE_INVALID; - } - return EXIT_SUCCESS; - } - - const proofPath = requireFlag(parsed.flags, "proof"); - const inputPath = requireFlag(parsed.flags, "input"); - const { result } = await verifyProofArtifact({ proofPath, inputPath }); - outputResult( - writer, - json, - quiet, - json - ? result - : [ - `valid=${result.valid}`, - `hashMatch=${result.hashMatch}`, - `signatureValid=${result.signatureValid}`, - `keyId=${result.keyId}`, - `algorithm=${result.algorithm}`, - `subjectHash=${result.subjectHash}`, - ].join("\n"), - ); - - if (!result.hashMatch) { - return EXIT_HASH_MISMATCH; - } - if (!result.signatureValid) { - return EXIT_SIGNATURE_INVALID; - } - return EXIT_SUCCESS; - } - - if (command === "public-key") { - const artifact = await createPublicKeyArtifact({ - identity: await resolveSealIdentityFromEnv(env), - }); - outputResult(writer, true, quiet, artifact); - return EXIT_SUCCESS; - } - - throw new SealCliError(usage, EXIT_FAILURE); + const { positionals, values } = parseArgs({ + args: argv, + allowPositionals: true, + options: { + input: { type: "string" }, + out: { type: "string" }, + proof: { type: "string" }, + help: { type: "boolean" }, + }, + }); + const [command] = positionals; + + if (values.help || positionals.length === 0) { + io.stdout(`${usage}\n`); + return 0; + } + if (command === "sign" && positionals.length === 1 && values.input && !values.proof) { + const identityFile = io.env.SEAL_IDENTITY_FILE; + if (!identityFile) throw new Error("Set SEAL_IDENTITY_FILE to an identity backup"); + const signer = await restoreIdentity(await readFile(identityFile, "utf8")); + const hash = await createSealHash(await readFile(values.input)); + const proof = `${JSON.stringify(await createSealProof({ signer, subject: { hash } }), null, 2)}\n`; + if (values.out) await writeFile(values.out, proof); + else io.stdout(proof); + return 0; + } + if (command === "verify" && positionals.length === 1 && values.input && values.proof) { + const proof: unknown = JSON.parse(await readFile(values.proof, "utf8")); + const result = await verifySealProof(proof, await readFile(values.input)); + io.stdout(`${JSON.stringify(result)}\n`); + return result.valid ? 0 : 2; + } + throw new Error(usage); } catch (error) { - if (error instanceof SealCliError) return outputError(writer, json, error); - if (error instanceof Error && error.message.includes("Proof")) { - return outputError(writer, json, new SealCliError(error.message, EXIT_INVALID_PROOF)); - } - if ( - error instanceof Error && - (error.message.includes("public key") || - error.message.includes("SEAL_IDENTITY") || - error.message.includes("identity")) - ) { - return outputError(writer, json, new SealCliError(error.message, EXIT_KEY_CONFIG)); - } - return outputError(writer, json, error); + io.stderr(`${error instanceof Error ? error.message : String(error)}\n`); + return 1; } } - -const isDirectRun = - typeof process !== "undefined" && - process.argv[1] && - fileURLToPath(import.meta.url) === resolve(process.argv[1]); - -if (isDirectRun) { - void runCli(process.argv.slice(2)).then((exitCode) => { - process.exitCode = exitCode; - }); -} diff --git a/packages/seal/src/commands/identity.ts b/packages/seal/src/commands/identity.ts deleted file mode 100644 index cbe14a2..0000000 --- a/packages/seal/src/commands/identity.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { createSealIdentity, createSealMnemonicIdentity, exportIdentityJson } from "../crypto.js"; - -function formatMnemonicBackup(input: { mnemonic: string; passphrase?: string }): string { - const lines = ["Seal seed phrase backup", "", "Mnemonic:", input.mnemonic]; - if (String(input.passphrase || "").trim()) { - lines.push("", "Passphrase:", String(input.passphrase)); - } - lines.push( - "", - "Store this file securely. Anyone with this recovery material can recreate the signer.", - ); - return `${lines.join("\n")}\n`; -} - -export async function createIdentityArtifact( - input: { - withMnemonic?: boolean; - words?: 12 | 24; - passphrase?: string; - } = {}, -): Promise<{ - identity: import("@ternent/identity").SerializedIdentity; - content: string; - mnemonic: string | null; - mnemonicContent: string | null; -}> { - const useMnemonic = - Boolean(input.withMnemonic) || - input.words === 12 || - input.words === 24 || - Boolean(input.passphrase); - const created = useMnemonic - ? await createSealMnemonicIdentity({ - words: input.words, - passphrase: input.passphrase, - }) - : { - identity: await createSealIdentity(), - mnemonic: null, - }; - return { - identity: created.identity, - content: exportIdentityJson(created.identity), - mnemonic: created.mnemonic, - mnemonicContent: created.mnemonic - ? formatMnemonicBackup({ - mnemonic: created.mnemonic, - passphrase: input.passphrase, - }) - : null, - }; -} diff --git a/packages/seal/src/commands/manifest.ts b/packages/seal/src/commands/manifest.ts deleted file mode 100644 index 2717d40..0000000 --- a/packages/seal/src/commands/manifest.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { readdir, readFile, stat } from "node:fs/promises"; -import { basename, join, relative, resolve } from "node:path"; -import { createSealHash } from "../proof.js"; -import { - SEAL_MANIFEST_TYPE, - SEAL_MANIFEST_VERSION, - stringifySealManifest, - type SealManifestV1, -} from "../manifest.js"; - -function normalizeRelativePath(value: string): string { - return value.split("\\").join("/"); -} - -async function collectFiles( - rootPath: string, - currentPath: string, - files: Record, -): Promise { - const entries = await readdir(currentPath, { withFileTypes: true }); - const sorted = entries - .filter((entry) => entry.name !== ".DS_Store") - .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); - - for (const entry of sorted) { - const entryPath = join(currentPath, entry.name); - if (entry.isDirectory()) { - await collectFiles(rootPath, entryPath, files); - continue; - } - if (!entry.isFile()) { - continue; - } - const bytes = await readFile(entryPath); - const relativePath = normalizeRelativePath(relative(rootPath, entryPath)); - files[relativePath] = await createSealHash(bytes); - } -} - -export async function createManifestArtifact(inputPath: string): Promise<{ - manifest: SealManifestV1; - content: string; -}> { - const resolvedInput = resolve(inputPath); - const inputStat = await stat(resolvedInput); - const root = basename(resolvedInput); - const files = Object.create(null) as SealManifestV1["files"]; - - if (inputStat.isDirectory()) { - await collectFiles(resolvedInput, resolvedInput, files); - } else if (inputStat.isFile()) { - const bytes = await readFile(resolvedInput); - files[root] = await createSealHash(bytes); - } else { - throw new Error("Manifest input must be a file or directory."); - } - - const manifest: SealManifestV1 = { - version: SEAL_MANIFEST_VERSION, - type: SEAL_MANIFEST_TYPE, - root, - files: Object.fromEntries( - Object.entries(files).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)), - ), - }; - - return { - manifest, - content: `${stringifySealManifest(manifest)}\n`, - }; -} diff --git a/packages/seal/src/commands/publicKey.ts b/packages/seal/src/commands/publicKey.ts deleted file mode 100644 index 450c795..0000000 --- a/packages/seal/src/commands/publicKey.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { createSealPublicKeyArtifact } from "../proof.js"; - -export async function createPublicKeyArtifact(params: { - identity: import("@ternent/identity").SerializedIdentity; -}) { - return createSealPublicKeyArtifact(params); -} diff --git a/packages/seal/src/commands/sign.ts b/packages/seal/src/commands/sign.ts deleted file mode 100644 index 1204cfa..0000000 --- a/packages/seal/src/commands/sign.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { basename } from "node:path"; -import { readFile } from "node:fs/promises"; -import { createSealArtifact, type SealArtifactV1 } from "../artifact.js"; -import { parseSealManifestJson } from "../manifest.js"; -import { createSealProof, createSealHash, type SealProofV2 } from "../proof.js"; - -export async function createProofArtifact(params: { - inputPath: string; - identity: import("@ternent/identity").SerializedIdentity; -}): Promise<{ - proof: SealProofV2; - content: string; -}> { - const bytes = await readFile(params.inputPath); - const raw = new TextDecoder().decode(bytes); - const parsedManifest = parseSealManifestJson(raw); - const proof = await createSealProof({ - signer: { - identity: params.identity, - }, - subject: { - kind: parsedManifest.ok ? "manifest" : "file", - path: basename(params.inputPath), - hash: await createSealHash(bytes), - }, - }); - - return { - proof, - content: `${JSON.stringify(proof, null, 2)}\n`, - }; -} - -export async function createRecipientArtifact(params: { - inputPath: string; - identity: import("@ternent/identity").SerializedIdentity; - recipients: string[]; -}): Promise<{ - artifact: SealArtifactV1; - content: string; -}> { - const bytes = await readFile(params.inputPath); - const artifact = await createSealArtifact({ - signer: { - identity: params.identity, - }, - subjectPath: basename(params.inputPath), - payload: bytes, - recipients: params.recipients, - }); - - return { - artifact, - content: `${JSON.stringify(artifact, null, 2)}\n`, - }; -} diff --git a/packages/seal/src/commands/verify.ts b/packages/seal/src/commands/verify.ts deleted file mode 100644 index 5b33901..0000000 --- a/packages/seal/src/commands/verify.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { SealCliError, EXIT_INVALID_PROOF } from "../errors.js"; -import { readFile } from "node:fs/promises"; -import { - parseSealArtifactJson, - verifySealArtifact, - type SealArtifactV1, - type VerifySealArtifactResult, -} from "../artifact.js"; -import { parseSealProofJson, verifySealProofAgainstBytes, type SealProofV2 } from "../proof.js"; - -export type VerifyArtifactResult = { - valid: boolean; - hashMatch: boolean; - signatureValid: boolean; - keyId: string; - algorithm: "Ed25519"; - subjectHash: `sha256:${string}`; -}; - -export async function verifyProofArtifact(params: { - proofPath: string; - inputPath: string; -}): Promise<{ - proof: SealProofV2; - result: VerifyArtifactResult; -}> { - const rawProof = await readFile(params.proofPath, "utf8"); - const parsed = parseSealProofJson(rawProof); - if (!parsed.ok || !parsed.proof) { - throw new SealCliError(parsed.errors.join(" "), EXIT_INVALID_PROOF); - } - - const subjectBytes = await readFile(params.inputPath); - const result = await verifySealProofAgainstBytes(parsed.proof, subjectBytes); - return { - proof: parsed.proof, - result, - }; -} - -export async function verifyArtifactProof(params: { artifactPath: string }): Promise<{ - artifact: SealArtifactV1; - result: VerifySealArtifactResult; -}> { - const rawArtifact = await readFile(params.artifactPath, "utf8"); - const parsed = parseSealArtifactJson(rawArtifact); - if (!parsed.ok || !parsed.artifact) { - throw new SealCliError(parsed.errors.join(" "), EXIT_INVALID_PROOF); - } - - return { - artifact: parsed.artifact, - result: await verifySealArtifact(parsed.artifact), - }; -} diff --git a/packages/seal/src/crypto.ts b/packages/seal/src/crypto.ts deleted file mode 100644 index 3f3fd46..0000000 --- a/packages/seal/src/crypto.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { - createIdentity, - createIdentityFromMnemonic, - createMnemonicIdentity, - deriveKeyId, - validateIdentity, - validatePublicIdentity, - decodeBase64Url, - verifySignature, - serializeIdentity, - signUtf8, - type SerializedIdentity, -} from "@ternent/identity"; - -export type SealSignerInput = { - identity: SerializedIdentity; -}; - -export type ResolvedSealSigner = { - identity: SerializedIdentity; - publicKey: string; - keyId: string; -}; - -export const SEAL_SIGNATURE_CONTEXT = "ternent-seal/v2"; - -export async function createSealIdentity( - createdAt = new Date().toISOString(), -): Promise { - return createIdentity(createdAt); -} - -export async function createSealIdentityFromMnemonic(input: { - mnemonic: string; - passphrase?: string; - createdAt?: string; -}): Promise { - return createIdentityFromMnemonic(input); -} - -export async function createSealMnemonicIdentity( - input: { - words?: 12 | 24; - passphrase?: string; - createdAt?: string; - } = {}, -): Promise<{ identity: SerializedIdentity; mnemonic: string }> { - return createMnemonicIdentity(input); -} - -export function exportIdentityJson(identity: SerializedIdentity): string { - return serializeIdentity(identity); -} - -export async function resolveSealSigner(input: SealSignerInput): Promise { - const identity = await validateIdentity(input.identity); - const keyId = await deriveKeyId(identity.publicKey); - if (keyId !== identity.keyId || !(await verifyPublicKeyKeyId(identity.publicKey, keyId))) { - throw new Error("Identity keyId does not match the signer public key."); - } - - return { - identity, - publicKey: identity.publicKey, - keyId, - }; -} - -export async function signSealUtf8(identity: SerializedIdentity, value: string): Promise { - return signUtf8(identity, value, { - context: SEAL_SIGNATURE_CONTEXT, - }); -} - -export async function verifySealUtf8( - signature: string, - value: string, - publicKey: string, -): Promise { - try { - const keyId = await deriveKeyId(publicKey); - const identity = { - version: 1 as const, - algorithm: "Ed25519" as const, - publicKey, - id: `identity:${keyId}`, - }; - const decoded = decodeBase64Url(signature); - if (!decoded.ok) return false; - const result = await verifySignature( - identity, - new TextEncoder().encode(`${SEAL_SIGNATURE_CONTEXT}\0${value}`), - decoded.value, - ); - return result.ok && result.value; - } catch { - return false; - } -} - -export async function verifyPublicKeyKeyId(publicKey: string, keyId: string): Promise { - try { - return validatePublicIdentity({ - version: 1, - algorithm: "Ed25519", - publicKey, - id: `identity:${keyId}`, - }).ok; - } catch { - return false; - } -} diff --git a/packages/seal/src/errors.ts b/packages/seal/src/errors.ts deleted file mode 100644 index 9d9f36c..0000000 --- a/packages/seal/src/errors.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { ArmourError, ArmourValidationError } from "@ternent/armour"; - -export const EXIT_SUCCESS = 0; -export const EXIT_FAILURE = 1; -export const EXIT_HASH_MISMATCH = 2; -export const EXIT_SIGNATURE_INVALID = 3; -export const EXIT_INVALID_PROOF = 4; -export const EXIT_KEY_CONFIG = 5; - -export type SealErrorCode = - | "SEAL_INVALID_RECIPIENT" - | "SEAL_ENCRYPTION_FAILED" - | "SEAL_DECRYPTION_FAILED" - | "SEAL_UNSUPPORTED_ENCRYPTION_MODE"; - -export class SealError extends Error { - readonly code: SealErrorCode; - readonly cause?: unknown; - - constructor(code: SealErrorCode, message: string, cause?: unknown) { - super(message); - this.name = new.target.name; - this.code = code; - if (cause !== undefined) { - this.cause = cause; - } - } -} - -export class SealArtifactError extends SealError {} - -export class SealCliError extends Error { - exitCode: number; - - constructor(message: string, exitCode = EXIT_FAILURE) { - super(message); - this.name = "SealCliError"; - this.exitCode = exitCode; - } -} - -export function getExitCode(error: unknown): number { - if (error instanceof SealCliError) { - return error.exitCode; - } - return EXIT_FAILURE; -} - -export function unsupportedEncryptionModeError( - message = "Seal does not support this encryption mode.", -): SealArtifactError { - return new SealArtifactError("SEAL_UNSUPPORTED_ENCRYPTION_MODE", message); -} - -export function toSealEncryptionError(error: unknown): SealArtifactError { - if (error instanceof SealArtifactError) { - return error; - } - - if ( - error instanceof ArmourValidationError && - (error.code === "ARMOUR_EMPTY_RECIPIENTS" || error.code === "ARMOUR_INVALID_RECIPIENT") - ) { - return new SealArtifactError( - "SEAL_INVALID_RECIPIENT", - "Recipient must be a valid age recipient string.", - error, - ); - } - - if (error instanceof ArmourError) { - return new SealArtifactError("SEAL_ENCRYPTION_FAILED", "Failed to encrypt payload.", error); - } - - return new SealArtifactError("SEAL_ENCRYPTION_FAILED", "Failed to encrypt payload.", error); -} - -export function toSealDecryptionError(error: unknown): SealArtifactError { - if (error instanceof SealArtifactError) { - return error; - } - - if (error instanceof ArmourError) { - return new SealArtifactError("SEAL_DECRYPTION_FAILED", "Failed to decrypt payload.", error); - } - - return new SealArtifactError("SEAL_DECRYPTION_FAILED", "Failed to decrypt payload.", error); -} diff --git a/packages/seal/src/index.ts b/packages/seal/src/index.ts index 35bf030..c8f8ce4 100644 --- a/packages/seal/src/index.ts +++ b/packages/seal/src/index.ts @@ -1,5 +1,135 @@ -export * from "./proof.js"; -export * from "./artifact.js"; -export * from "./manifest.js"; -export * from "./crypto.js"; -export * from "./errors.js"; +import { + validatePublicIdentity, + verify, + type Identity, + type PublicIdentity, +} from "@ternent/identity"; +import { base64urlnopad, hex } from "@scure/base"; + +export type SealHash = `sha256:${string}`; + +export type SealProof = { + format: "seal"; + version: 1; + createdAt: string; + subject: { hash: SealHash }; + signer: PublicIdentity; + signature: string; +}; + +export type SealVerification = { valid: boolean; signatureValid: boolean; hashMatch: boolean }; + +export async function createSealHash(bytes: Uint8Array): Promise { + const digest = await crypto.subtle.digest("SHA-256", bytes); + return `sha256:${hex.encode(new Uint8Array(digest))}`; +} + +export async function createSealProof(input: { + signer: Pick; + subject: { hash: SealHash }; + createdAt?: string; +}): Promise { + const { publicKey, id } = input.signer.publicIdentity; + const hash = input.subject.hash; + const createdAt = input.createdAt ?? new Date().toISOString(); + if (!isSealHash(hash)) throw new TypeError("Subject hash must be sha256: and 64 lowercase hex"); + if (!isTimestamp(createdAt)) throw new TypeError("createdAt must be a UTC timestamp"); + + const signer: PublicIdentity = { version: 1, algorithm: "Ed25519", publicKey, id }; + const unsigned = { format: "seal", version: 1, createdAt, subject: { hash }, signer } as const; + const message = signingMessage(unsigned); + const signature = await input.signer.sign(message.slice()); + if (!(await verify(signer, message, signature))) { + throw new Error("The signer returned a signature that does not verify"); + } + return { ...unsigned, signature: base64urlnopad.encode(signature) }; +} + +export async function verifySealProof( + proof: unknown, + bytes: Uint8Array, +): Promise { + const actualHash = createSealHash(bytes); + let claimedHash: string | undefined; + let signatureValid = false; + try { + const { signature, signer: claimedSigner, ...unsigned } = readProof(proof); + claimedHash = unsigned.subject.hash; + const signer = validatePublicIdentity(claimedSigner); + signatureValid = await verify( + signer, + signingMessage({ ...unsigned, signer }), + base64urlnopad.decode(signature), + ); + } catch { + // A malformed proof is an invalid proof. + } + const hashMatch = claimedHash === (await actualHash); + return { valid: signatureValid && hashMatch, signatureValid, hashMatch }; +} + +// "ternent-seal/v1" || 0x00 || canonical JSON of the unsigned proof. Every value is a +// fixed-format ASCII string or the integer 1, so building the record with its keys +// in UTF-16 order makes JSON.stringify canonical. +function signingMessage(proof: Omit): Uint8Array { + const { createdAt, format, signer, subject, version } = proof; + const canonical = JSON.stringify({ + createdAt, + format, + signer: { + algorithm: signer.algorithm, + id: signer.id, + publicKey: signer.publicKey, + version: signer.version, + }, + subject: { hash: subject.hash }, + version, + }); + return new TextEncoder().encode(`ternent-seal/v1\0${canonical}`); +} + +function readProof(input: unknown): Omit & { signer: unknown } { + if (!hasExactKeys(input, ["format", "version", "createdAt", "subject", "signer", "signature"])) { + throw new TypeError("Invalid proof"); + } + const { format, version, createdAt, subject, signer, signature } = input; + if ( + format !== "seal" || + version !== 1 || + !isTimestamp(createdAt) || + !hasExactKeys(subject, ["hash"]) || + !isSealHash(subject.hash) || + typeof signature !== "string" + ) { + throw new TypeError("Invalid proof"); + } + return { + format, + version, + createdAt, + subject: { hash: subject.hash }, + signer, + signature, + }; +} + +function hasExactKeys(value: unknown, keys: K[]): value is Record { + return ( + typeof value === "object" && + value !== null && + Object.keys(value).length === keys.length && + keys.every((key) => Object.hasOwn(value, key)) + ); +} + +function isSealHash(value: unknown): value is SealHash { + return typeof value === "string" && /^sha256:[0-9a-f]{64}$/.test(value); +} + +function isTimestamp(value: unknown): value is string { + return ( + typeof value === "string" && + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value) && + new Date(value).toISOString() === value + ); +} diff --git a/packages/seal/src/json.ts b/packages/seal/src/json.ts deleted file mode 100644 index 48bc318..0000000 --- a/packages/seal/src/json.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Seal's canonical JSON domain is independent of Concord's protocol. -export function canonicalStringify(input: unknown): string { - const seen = new Set(); - function string(value: string): string { - for (let i = 0; i < value.length; i++) { - const code = value.charCodeAt(i); - if (code >= 0xd800 && code <= 0xdbff) { - const next = value.charCodeAt(++i); - if (!(next >= 0xdc00 && next <= 0xdfff)) throw new TypeError("Invalid Unicode string"); - } else if (code >= 0xdc00 && code <= 0xdfff) throw new TypeError("Invalid Unicode string"); - } - return value; - } - function visit(value: unknown, depth: number): unknown { - if (value === null || typeof value === "boolean") return value; - if (typeof value === "string") return string(value); - if (typeof value === "number" && Number.isSafeInteger(value) && !Object.is(value, -0)) - return value; - if (!value || typeof value !== "object") - throw new TypeError("Unsupported canonical JSON value"); - if (depth >= 64 || seen.has(value)) throw new TypeError("Canonical JSON depth or cycle"); - const proto: unknown = Object.getPrototypeOf(value); - if ( - Array.isArray(value) - ? proto !== Array.prototype - : proto !== Object.prototype && proto !== null - ) - throw new TypeError("Canonical JSON requires plain objects"); - seen.add(value); - try { - const keys = Reflect.ownKeys(value); - if (keys.some((key) => typeof key !== "string")) throw new TypeError("JSON symbol key"); - const get = (key: string) => { - const descriptor = Object.getOwnPropertyDescriptor(value, key); - if (!descriptor || !Object.hasOwn(descriptor, "value") || !descriptor.enumerable) - throw new TypeError("Canonical JSON requires enumerable data properties"); - return visit(descriptor.value, depth + 1); - }; - if (Array.isArray(value)) { - if (keys.length !== value.length + 1) throw new TypeError("Invalid JSON array"); - return Array.from({ length: value.length }, (_, i) => get(String(i))); - } - const result = Object.create(null) as Record; - for (const key of (keys as string[]).sort()) result[string(key)] = get(key); - return result; - } finally { - seen.delete(value); - } - } - // Native integer-index enumeration is retained from the previous Seal codec. - return JSON.stringify(visit(input, 0)); -} -export function copyJson(input: T): T { - return JSON.parse(canonicalStringify(input)) as T; -} -export async function hashBytes(input: Uint8Array | ArrayBuffer): Promise { - if (!(input instanceof Uint8Array) && !(input instanceof ArrayBuffer)) - throw new TypeError("Expected bytes"); - const bytes = - input instanceof Uint8Array ? new Uint8Array(input) : new Uint8Array(input.slice(0)); - const digest = await crypto.subtle.digest("SHA-256", bytes); - return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); -} diff --git a/packages/seal/src/manifest.ts b/packages/seal/src/manifest.ts deleted file mode 100644 index 4e1b883..0000000 --- a/packages/seal/src/manifest.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { canonicalStringify, copyJson } from "./json.js"; - -export const SEAL_MANIFEST_VERSION = "1" as const; -export const SEAL_MANIFEST_TYPE = "seal-manifest" as const; - -export type SealHash = `sha256:${string}`; - -export type SealManifestV1 = { - version: typeof SEAL_MANIFEST_VERSION; - type: typeof SEAL_MANIFEST_TYPE; - root: string; - files: Record; -}; - -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === "object" && !Array.isArray(value); -} - -function hasOnlyKeys(value: Record, allowed: string[]): boolean { - return Object.keys(value).every((key) => allowed.includes(key)); -} - -function isSealHash(value: unknown): value is SealHash { - return typeof value === "string" && /^sha256:[0-9a-f]{64}$/.test(value); -} - -export function validateSealManifestShape(value: unknown): { - ok: boolean; - errors: string[]; - manifest: SealManifestV1 | null; -} { - try { - value = copyJson(value); - } catch { - return { ok: false, errors: ["Expected canonical JSON data."], manifest: null }; - } - if (!isRecord(value)) { - return { - ok: false, - errors: ["Manifest must be a JSON object."], - manifest: null, - }; - } - - const errors: string[] = []; - - if (!hasOnlyKeys(value, ["version", "type", "root", "files"])) { - errors.push("Manifest contains unsupported fields."); - } - - if (value.version !== SEAL_MANIFEST_VERSION) { - errors.push(`Manifest version must be ${SEAL_MANIFEST_VERSION}.`); - } - - if (value.type !== SEAL_MANIFEST_TYPE) { - errors.push(`Manifest type must be ${SEAL_MANIFEST_TYPE}.`); - } - - if (typeof value.root !== "string" || value.root.length === 0) { - errors.push("Manifest root must be a non-empty string."); - } - - if (!isRecord(value.files)) { - errors.push("Manifest files must be an object."); - } - - if (errors.length > 0 || !isRecord(value.files)) { - return { ok: false, errors, manifest: null }; - } - - const filesEntries = Object.entries(value.files); - const files = Object.create(null) as Record; - for (const [path, hash] of filesEntries) { - if (!path || path.includes("\\")) { - errors.push(`Manifest file path is invalid: ${path || ""}.`); - continue; - } - if (!isSealHash(hash)) { - errors.push(`Manifest file hash is invalid for ${path}.`); - continue; - } - files[path] = hash; - } - - if (errors.length > 0) { - return { ok: false, errors, manifest: null }; - } - - return { - ok: true, - errors: [], - manifest: { - version: SEAL_MANIFEST_VERSION, - type: SEAL_MANIFEST_TYPE, - root: value.root as string, - files: Object.fromEntries(Object.entries(files)), - }, - }; -} - -export function parseSealManifestJson(raw: string): { - ok: boolean; - errors: string[]; - manifest: SealManifestV1 | null; -} { - try { - return validateSealManifestShape(JSON.parse(raw)); - } catch { - return { - ok: false, - errors: ["Manifest JSON is not valid JSON."], - manifest: null, - }; - } -} - -export function stringifySealManifest(manifest: SealManifestV1): string { - return canonicalStringify(manifest); -} diff --git a/packages/seal/src/node.ts b/packages/seal/src/node.ts deleted file mode 100644 index 560093e..0000000 --- a/packages/seal/src/node.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { readFile } from "node:fs/promises"; -import { parseIdentity, validateIdentity, type SerializedIdentity } from "@ternent/identity"; -import { SealCliError, EXIT_KEY_CONFIG } from "./errors.js"; - -export async function resolveSealIdentityFromEnv( - env: Record, -): Promise { - const identityJson = String(env.SEAL_IDENTITY || "").trim(); - const identityFile = String(env.SEAL_IDENTITY_FILE || "").trim(); - if (!identityJson && !identityFile) - throw new SealCliError( - "Missing SEAL_IDENTITY or SEAL_IDENTITY_FILE environment variable.", - EXIT_KEY_CONFIG, - ); - try { - return await validateIdentity( - parseIdentity(identityJson || (await readFile(identityFile, "utf8"))), - ); - } catch { - throw new SealCliError("Invalid Seal identity configuration.", EXIT_KEY_CONFIG); - } -} diff --git a/packages/seal/src/proof.ts b/packages/seal/src/proof.ts deleted file mode 100644 index 1b11da2..0000000 --- a/packages/seal/src/proof.ts +++ /dev/null @@ -1,363 +0,0 @@ -import { canonicalStringify, copyJson, hashBytes } from "./json.js"; -import { - resolveSealSigner, - signSealUtf8, - verifyPublicKeyKeyId, - verifySealUtf8, - type SealSignerInput, -} from "./crypto.js"; - -export const SEAL_PROOF_VERSION = "2" as const; -export const SEAL_PROOF_TYPE = "seal-proof" as const; -export const SEAL_PUBLIC_KEY_TYPE = "seal-public-key" as const; -export const SEAL_SIGNATURE_ALGORITHM = "Ed25519" as const; - -export type SealSubjectKind = "file" | "manifest" | "artifact"; - -export type SealProofV2 = { - version: typeof SEAL_PROOF_VERSION; - type: typeof SEAL_PROOF_TYPE; - algorithm: typeof SEAL_SIGNATURE_ALGORITHM; - createdAt: string; - subject: { - kind: SealSubjectKind; - path: string; - hash: `sha256:${string}`; - }; - signer: { - publicKey: string; - keyId: string; - }; - signature: string; -}; - -export type SealPublicKeyArtifact = { - version: typeof SEAL_PROOF_VERSION; - type: typeof SEAL_PUBLIC_KEY_TYPE; - algorithm: typeof SEAL_SIGNATURE_ALGORITHM; - publicKey: string; - keyId: string; -}; - -type SealProofSignableFields = Omit; - -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === "object" && !Array.isArray(value); -} - -function hasOnlyKeys(value: Record, allowed: string[]): boolean { - return Object.keys(value).every((key) => allowed.includes(key)); -} - -function isSealHash(value: unknown): value is `sha256:${string}` { - return typeof value === "string" && /^sha256:[0-9a-f]{64}$/.test(value); -} - -function isIsoDate(value: string): boolean { - return !Number.isNaN(Date.parse(value)); -} - -export function getSealProofSignableFields( - proof: SealProofV2 | SealProofSignableFields, -): SealProofSignableFields { - proof = copyJson(proof); - return { - version: proof.version, - type: proof.type, - algorithm: proof.algorithm, - createdAt: proof.createdAt, - subject: proof.subject, - signer: proof.signer, - }; -} - -export function getSealProofSigningPayload(proof: SealProofV2 | SealProofSignableFields): string { - return canonicalStringify(getSealProofSignableFields(proof)); -} - -export async function createSealHash(bytes: Uint8Array | ArrayBuffer): Promise<`sha256:${string}`> { - const hash = await hashBytes(bytes); - return `sha256:${hash}`; -} - -export async function createSealProof(input: { - createdAt?: string; - signer: SealSignerInput; - subject: SealProofV2["subject"]; -}): Promise { - const subject = copyJson(input.subject); - const createdAt = input.createdAt ?? new Date().toISOString(); - const signer = await resolveSealSigner(input.signer); - const fields: SealProofSignableFields = { - version: SEAL_PROOF_VERSION, - type: SEAL_PROOF_TYPE, - algorithm: SEAL_SIGNATURE_ALGORITHM, - createdAt, - subject, - signer: { - publicKey: signer.publicKey, - keyId: signer.keyId, - }, - }; - - const candidate = { ...fields, signature: "pending" }; - const validation = validateSealProofShape(candidate); - if (!validation.ok) throw new TypeError(validation.errors.join(" ")); - const signature = await signSealUtf8(signer.identity, getSealProofSigningPayload(fields)); - - return { - ...fields, - signature, - }; -} - -export async function createSealPublicKeyArtifact( - signer: SealSignerInput, -): Promise { - const resolved = await resolveSealSigner(signer); - return { - version: SEAL_PROOF_VERSION, - type: SEAL_PUBLIC_KEY_TYPE, - algorithm: SEAL_SIGNATURE_ALGORITHM, - publicKey: resolved.publicKey, - keyId: resolved.keyId, - }; -} - -export function validateSealProofShape(value: unknown): { - ok: boolean; - errors: string[]; - proof: SealProofV2 | null; -} { - try { - value = copyJson(value); - } catch { - return { ok: false, errors: ["Expected canonical JSON data."], proof: null }; - } - if (!isRecord(value)) { - return { ok: false, errors: ["Proof must be a JSON object."], proof: null }; - } - - const errors: string[] = []; - - if ( - !hasOnlyKeys(value, [ - "version", - "type", - "algorithm", - "createdAt", - "subject", - "signer", - "signature", - ]) - ) { - errors.push("Proof contains unsupported fields."); - } - - if (value.version !== SEAL_PROOF_VERSION) { - errors.push(`Proof version must be ${SEAL_PROOF_VERSION}.`); - } - if (value.type !== SEAL_PROOF_TYPE) { - errors.push(`Proof type must be ${SEAL_PROOF_TYPE}.`); - } - if (value.algorithm !== SEAL_SIGNATURE_ALGORITHM) { - errors.push(`Proof algorithm must be ${SEAL_SIGNATURE_ALGORITHM}.`); - } - if (typeof value.createdAt !== "string" || !isIsoDate(value.createdAt)) { - errors.push("Proof createdAt must be an ISO timestamp."); - } - if (typeof value.signature !== "string" || value.signature.length === 0) { - errors.push("Proof signature must be a non-empty base64url string."); - } - if (!isRecord(value.subject)) { - errors.push("Proof subject must be an object."); - } - if (!isRecord(value.signer)) { - errors.push("Proof signer must be an object."); - } - - if (errors.length > 0 || !isRecord(value.subject) || !isRecord(value.signer)) { - return { ok: false, errors, proof: null }; - } - - if (!hasOnlyKeys(value.subject, ["kind", "path", "hash"])) { - errors.push("Proof subject contains unsupported fields."); - } - if (!hasOnlyKeys(value.signer, ["publicKey", "keyId"])) { - errors.push("Proof signer contains unsupported fields."); - } - if ( - value.subject.kind !== "file" && - value.subject.kind !== "manifest" && - value.subject.kind !== "artifact" - ) { - errors.push("Proof subject kind must be file, manifest, or artifact."); - } - if (typeof value.subject.path !== "string" || value.subject.path.length === 0) { - errors.push("Proof subject path must be a non-empty string."); - } - if (!isSealHash(value.subject.hash)) { - errors.push("Proof subject hash must be a sha256 hash."); - } - if (typeof value.signer.publicKey !== "string" || value.signer.publicKey.length === 0) { - errors.push("Proof signer publicKey must be a non-empty base64url string."); - } - if (typeof value.signer.keyId !== "string" || value.signer.keyId.length === 0) { - errors.push("Proof signer keyId must be a non-empty string."); - } - - if (errors.length > 0) { - return { ok: false, errors, proof: null }; - } - - return { - ok: true, - errors: [], - proof: value as SealProofV2, - }; -} - -export function parseSealProofJson(raw: string): { - ok: boolean; - errors: string[]; - proof: SealProofV2 | null; -} { - try { - return validateSealProofShape(JSON.parse(raw)); - } catch { - return { - ok: false, - errors: ["Proof JSON is not valid JSON."], - proof: null, - }; - } -} - -export function validateSealPublicKeyShape(value: unknown): { - ok: boolean; - errors: string[]; - artifact: SealPublicKeyArtifact | null; -} { - try { - value = copyJson(value); - } catch { - return { ok: false, errors: ["Expected canonical JSON data."], artifact: null }; - } - if (!isRecord(value)) { - return { - ok: false, - errors: ["Public key artifact must be a JSON object."], - artifact: null, - }; - } - - const errors: string[] = []; - - if (!hasOnlyKeys(value, ["version", "type", "algorithm", "publicKey", "keyId"])) { - errors.push("Public key artifact contains unsupported fields."); - } - if (value.version !== SEAL_PROOF_VERSION) { - errors.push(`Public key artifact version must be ${SEAL_PROOF_VERSION}.`); - } - if (value.type !== SEAL_PUBLIC_KEY_TYPE) { - errors.push(`Public key artifact type must be ${SEAL_PUBLIC_KEY_TYPE}.`); - } - if (value.algorithm !== SEAL_SIGNATURE_ALGORITHM) { - errors.push(`Public key artifact algorithm must be ${SEAL_SIGNATURE_ALGORITHM}.`); - } - if (typeof value.publicKey !== "string" || value.publicKey.length === 0) { - errors.push("Public key artifact publicKey must be a non-empty base64url string."); - } - if (typeof value.keyId !== "string" || value.keyId.length === 0) { - errors.push("Public key artifact keyId must be a non-empty string."); - } - - if (errors.length > 0) { - return { ok: false, errors, artifact: null }; - } - - return { - ok: true, - errors: [], - artifact: value as SealPublicKeyArtifact, - }; -} - -export function parseSealPublicKeyJson(raw: string): { - ok: boolean; - errors: string[]; - artifact: SealPublicKeyArtifact | null; -} { - try { - return validateSealPublicKeyShape(JSON.parse(raw)); - } catch { - return { - ok: false, - errors: ["Public key JSON is not valid JSON."], - artifact: null, - }; - } -} - -export async function verifySealProofSignature(proof: SealProofV2): Promise<{ - ok: boolean; - errors: string[]; -}> { - const validation = validateSealProofShape(proof); - if (!validation.ok || !validation.proof) { - return { ok: false, errors: validation.errors }; - } - - proof = validation.proof; - if (!(await verifyPublicKeyKeyId(proof.signer.publicKey, proof.signer.keyId))) { - return { - ok: false, - errors: ["Proof signer keyId does not match signer public key."], - }; - } - - try { - const valid = await verifySealUtf8( - proof.signature, - getSealProofSigningPayload(proof), - proof.signer.publicKey, - ); - if (!valid) { - return { ok: false, errors: ["Invalid signature."] }; - } - return { ok: true, errors: [] }; - } catch { - return { - ok: false, - errors: ["Invalid signature."], - }; - } -} - -export async function verifySealProofAgainstBytes( - proof: SealProofV2, - bytes: Uint8Array | ArrayBuffer, -): Promise<{ - valid: boolean; - hashMatch: boolean; - signatureValid: boolean; - keyId: string; - algorithm: typeof SEAL_SIGNATURE_ALGORITHM; - subjectHash: `sha256:${string}`; -}> { - const validation = validateSealProofShape(proof); - const subjectHash = await createSealHash(bytes); - const checked = validation.proof; - const signatureCheck = checked ? await verifySealProofSignature(checked) : { ok: false }; - const hashMatch = subjectHash === checked?.subject.hash; - const signatureValid = signatureCheck.ok; - - return { - valid: hashMatch && signatureValid, - hashMatch, - signatureValid, - keyId: checked?.signer.keyId ?? "", - algorithm: checked?.algorithm ?? SEAL_SIGNATURE_ALGORITHM, - subjectHash, - }; -} diff --git a/packages/seal/test/artifact.test.ts b/packages/seal/test/artifact.test.ts deleted file mode 100644 index 03f1de2..0000000 --- a/packages/seal/test/artifact.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import { createIdentity } from "@ternent/identity"; -import { recipientFromIdentity } from "@ternent/armour"; -import { - createSealArtifact, - decryptSealArtifactPayload, - verifySealArtifact, - parseSealArtifactJson, -} from "../src/artifact.js"; - -async function createSigner() { - return createIdentity(); -} - -describe("seal artifact", () => { - it("creates, verifies, and decrypts an encrypted artifact", async () => { - const signer = await createSigner(); - const alice = await createIdentity(); - const bob = await createIdentity(); - const aliceRecipient = await recipientFromIdentity(alice); - const bobRecipient = await recipientFromIdentity(bob); - const plaintext = new TextEncoder().encode("recipient targeted payload"); - const artifact = await createSealArtifact({ - signer: { identity: signer }, - subjectPath: "dist-manifest.json", - payload: plaintext, - recipients: [aliceRecipient, bobRecipient], - }); - - expect(artifact.type).toBe("seal-artifact"); - expect(artifact.version).toBe("1"); - expect(artifact.proof.subject.kind).toBe("artifact"); - const serialized = JSON.stringify(artifact); - expect(serialized).not.toContain(aliceRecipient); - expect(serialized).not.toContain(bobRecipient); - - const verification = await verifySealArtifact(artifact); - expect(verification.valid).toBe(true); - expect(verification.subjectHash).toBe(artifact.proof.subject.hash); - expect(artifact.manifest.payloadHash).not.toBe(artifact.proof.subject.hash); - - const decrypted = await decryptSealArtifactPayload({ - artifact, - identity: bob, - }); - expect(new TextDecoder().decode(decrypted)).toBe("recipient targeted payload"); - }); - - it("maps invalid recipients to seal errors", async () => { - const signer = await createSigner(); - - await expect( - createSealArtifact({ - signer: { identity: signer }, - subjectPath: "artifact.tar.gz", - payload: new TextEncoder().encode("secret"), - recipients: ["bad-recipient"], - }), - ).rejects.toMatchObject({ - code: "SEAL_INVALID_RECIPIENT", - message: "Recipient must be a valid age recipient string.", - }); - }); - - it("fails decryption for unauthorized identities", async () => { - const signer = await createSigner(); - const recipient = await createIdentity(); - const outsider = await createIdentity(); - const artifact = await createSealArtifact({ - signer: { identity: signer }, - subjectPath: "artifact.tar.gz", - payload: new TextEncoder().encode("secret"), - recipients: [await recipientFromIdentity(recipient)], - }); - - await expect( - decryptSealArtifactPayload({ - artifact, - identity: outsider, - }), - ).rejects.toMatchObject({ - code: "SEAL_DECRYPTION_FAILED", - message: "Failed to decrypt payload.", - }); - }); -}); - -describe("artifact integrity boundaries", () => { - it("rejects changed manifest, payload and proof before returning plaintext", async () => { - const signer = await createSigner(); - const recipient = await createIdentity(); - const artifact = await createSealArtifact({ - signer: { identity: signer }, - subjectPath: "private.bin", - payload: new TextEncoder().encode("authenticated plaintext"), - recipients: [await recipientFromIdentity(recipient)], - }); - const changes: ((value: typeof artifact) => void)[] = [ - (value) => { - value.manifest.payloadHash = `sha256:${"0".repeat(64)}`; - }, - (value) => { - value.payload.data += "modified"; - }, - (value) => { - value.proof.subject.path = "other.bin"; - }, - (value) => { - value.proof.signature = "!"; - }, - (value) => { - Object.assign(value.manifest, { recipients: ["unexpected public routing"] }); - }, - ]; - for (const change of changes) { - const altered = structuredClone(artifact); - change(altered); - await expect(verifySealArtifact(altered)).resolves.toMatchObject({ valid: false }); - await expect( - decryptSealArtifactPayload({ artifact: altered, identity: recipient }), - ).rejects.toThrow(); - } - expect( - new TextDecoder().decode(await decryptSealArtifactPayload({ artifact, identity: recipient })), - ).toBe("authenticated plaintext"); - }); - - it("rejects unsupported encryption metadata and malformed artifact JSON", async () => { - const signer = await createSigner(); - const artifact = await createSealArtifact({ - signer: { identity: signer }, - subjectPath: "private.bin", - payload: new Uint8Array([1, 2, 3]), - recipients: [await recipientFromIdentity(signer)], - }); - for (const mode of ["passphrase", "unsupported"]) { - const altered = structuredClone(artifact); - Object.assign(altered.payload, { mode }); - await expect(verifySealArtifact(altered)).resolves.toMatchObject({ valid: false }); - } - expect(parseSealArtifactJson("not-json").ok).toBe(false); - expect(parseSealArtifactJson('{"version":"1","type":"seal-artifact"}').ok).toBe(false); - }); -}); - -it("captures artifact authoring, verification and decryption inputs before asynchronous work", async () => { - const signer = await createIdentity(); - const recipient = await createIdentity(); - const recipientValue = await recipientFromIdentity(recipient); - const input = { - signer: { identity: signer }, - subjectPath: "captured.bin", - createdAt: "2026-11-20T00:00:00.000Z", - payload: new TextEncoder().encode("captured plaintext"), - recipients: [recipientValue], - }; - const creating = createSealArtifact(input); - input.payload.fill(0); - input.recipients[0] = "caller-mutated-recipient"; - input.subjectPath = "caller-mutated.bin"; - input.createdAt = "2026-11-21T00:00:00.000Z"; - signer.material.seed = Buffer.alloc(32).toString("base64url"); - const artifact = await creating; - expect(artifact.proof.subject.path).toBe("captured.bin"); - expect(artifact.proof.createdAt).toBe("2026-11-20T00:00:00.000Z"); - expect(await verifySealArtifact(artifact)).toMatchObject({ valid: true }); - expect( - new TextDecoder().decode(await decryptSealArtifactPayload({ artifact, identity: recipient })), - ).toBe("captured plaintext"); - - const evidence = structuredClone(artifact); - const checking = verifySealArtifact(evidence); - evidence.manifest.payloadHash = `sha256:${"0".repeat(64)}`; - evidence.payload.data = "caller-mutated-ciphertext"; - expect(await checking).toMatchObject({ valid: true }); - const decryptingArtifact = structuredClone(artifact); - const identity = structuredClone(recipient); - const decrypting = decryptSealArtifactPayload({ artifact: decryptingArtifact, identity }); - decryptingArtifact.payload.data = "caller-mutated-ciphertext"; - identity.material.seed = Buffer.alloc(32).toString("base64url"); - expect(new TextDecoder().decode(await decrypting)).toBe("captured plaintext"); -}); diff --git a/packages/seal/test/cli.test.ts b/packages/seal/test/cli.test.ts index 1fd1e71..cd8d083 100644 --- a/packages/seal/test/cli.test.ts +++ b/packages/seal/test/cli.test.ts @@ -1,216 +1,86 @@ import { mkdtemp, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { describe, expect, it } from "vite-plus/test"; -import { createIdentity, serializeIdentity } from "@ternent/identity"; -import { recipientFromIdentity } from "@ternent/armour"; +import { expect, test } from "vite-plus/test"; +import { createIdentity } from "@ternent/identity"; import { runCli } from "../src/cli.js"; -async function createSigningEnv() { +async function setup() { + const dir = await mkdtemp(join(tmpdir(), "seal-cli-")); const identity = await createIdentity(); - return { - SEAL_IDENTITY: serializeIdentity(identity, false).trim(), - }; -} - -async function createTempFile(name: string, content: string): Promise { - const root = await mkdtemp(join(tmpdir(), "seal-cli-")); - const filePath = join(root, name); - await writeFile(filePath, content, "utf8"); - return filePath; + const identityFile = join(dir, "identity.json"); + await writeFile(identityFile, identity.export()); + const input = join(dir, "release-manifest.json"); + await writeFile(input, '{"release":"1.0.0"}\n'); + return { dir, identity, input, env: { SEAL_IDENTITY_FILE: identityFile } }; } -function createWriter() { - let stdout = ""; - let stderr = ""; +function io(env: Record = {}) { + const out = { stdout: "", stderr: "" }; return { - writer: { - stdout: (value: string) => { - stdout += value; - }, - stderr: (value: string) => { - stderr += value; - }, + out, + io: { + env, + stdout: (text: string) => void (out.stdout += text), + stderr: (text: string) => void (out.stderr += text), }, - read: () => ({ stdout, stderr }), }; } -describe("seal cli", () => { - it("verifies a proof successfully", async () => { - const env = await createSigningEnv(); - const subjectPath = await createTempFile("sample.txt", "sample file\n"); - const proofPath = await createTempFile("proof.json", ""); - const writer = createWriter(); - - const signExit = await runCli(["sign", "--input", subjectPath, "--out", proofPath], { - env, - writer: writer.writer, - }); - const verifyExit = await runCli( - ["verify", "--proof", proofPath, "--input", subjectPath, "--json"], - { env, writer: writer.writer }, - ); - - expect(signExit).toBe(0); - expect(verifyExit).toBe(0); - expect(writer.read().stdout).toContain('"valid": true'); - }); - - it("signs and verifies an encrypted artifact successfully", async () => { - const env = await createSigningEnv(); - const recipient = await createIdentity(); - const recipientValue = await recipientFromIdentity(recipient); - const subjectPath = await createTempFile("sample.txt", "sample file\n"); - const artifactPath = await createTempFile("artifact.json", ""); - const writer = createWriter(); - - const signExit = await runCli( - ["sign", "--input", subjectPath, "--recipient", recipientValue, "--out", artifactPath], - { env, writer: writer.writer }, - ); - const verifyExit = await runCli(["verify", "--artifact", artifactPath, "--json"], { - writer: writer.writer, - }); - - expect(signExit).toBe(0); - expect(verifyExit).toBe(0); - expect(await readFile(artifactPath, "utf8")).toContain('"type": "seal-artifact"'); - expect(writer.read().stdout).toContain('"encrypted": true'); - }); - - it("creates an identity file", async () => { - const identityPath = await createTempFile("identity.json", ""); - const writer = createWriter(); - - const exitCode = await runCli(["identity", "create", "--out", identityPath, "--json"], { - writer: writer.writer, - }); - - expect(exitCode).toBe(0); - expect(writer.read().stdout).toContain('"format": "ternent-identity"'); - expect(await readFile(identityPath, "utf8")).toContain('"material"'); - }); - - it("creates a mnemonic-backed identity and writes the seed phrase", async () => { - const identityPath = await createTempFile("identity.json", ""); - const mnemonicPath = await createTempFile("seed.txt", ""); - const writer = createWriter(); - - const exitCode = await runCli( - [ - "identity", - "create", - "--out", - identityPath, - "--words", - "24", - "--mnemonic-out", - mnemonicPath, - "--json", - ], - { writer: writer.writer }, - ); - - expect(exitCode).toBe(0); - expect(writer.read().stdout).toContain('"mnemonic"'); - expect(await readFile(identityPath, "utf8")).toContain('"format": "ternent-identity"'); - expect(await readFile(mnemonicPath, "utf8")).toContain("Seal seed phrase backup"); - }); - - it("returns exit code 2 for a hash mismatch", async () => { - const env = await createSigningEnv(); - const subjectPath = await createTempFile("sample.txt", "sample file\n"); - const mismatchPath = await createTempFile("different.txt", "different\n"); - const proofPath = await createTempFile("proof.json", ""); - - await runCli(["sign", "--input", subjectPath, "--out", proofPath], { env }); - const exitCode = await runCli(["verify", "--proof", proofPath, "--input", mismatchPath], { - env, - }); - - expect(exitCode).toBe(2); - }); - - it("keeps the legacy proof output when no recipients are provided", async () => { - const env = await createSigningEnv(); - const subjectPath = await createTempFile("sample.txt", "sample file\n"); - const proofPath = await createTempFile("proof.json", ""); - - const exitCode = await runCli(["sign", "--input", subjectPath, "--out", proofPath], { env }); - - expect(exitCode).toBe(0); - expect(await readFile(proofPath, "utf8")).toContain('"type": "seal-proof"'); - }); - - it("returns exit code 3 for an invalid signature", async () => { - const env = await createSigningEnv(); - const otherEnv = await createSigningEnv(); - const subjectPath = await createTempFile("sample.txt", "sample file\n"); - const proofPath = await createTempFile("proof.json", ""); - - await runCli(["sign", "--input", subjectPath, "--out", proofPath], { - env: otherEnv, - }); - - const rawProof = await readFile(proofPath, "utf8"); - const parsed = JSON.parse(rawProof) as Record; - parsed.signer = { - ...(parsed.signer as Record), - keyId: "bad-key-id", - }; - await writeFile(proofPath, `${JSON.stringify(parsed, null, 2)}\n`, "utf8"); - - const exitCode = await runCli(["verify", "--proof", proofPath, "--input", subjectPath], { - env, - }); - - expect(exitCode).toBe(3); - }); - - it("returns exit code 4 for schema invalid proof", async () => { - const env = await createSigningEnv(); - const subjectPath = await createTempFile("sample.txt", "sample file\n"); - const proofPath = await createTempFile("proof.json", '{"type":"bad"}'); - - const exitCode = await runCli(["verify", "--proof", proofPath, "--input", subjectPath], { - env, - }); - - expect(exitCode).toBe(4); - }); - - it("returns exit code 5 for key mismatch", async () => { - const writer = createWriter(); - - const exitCode = await runCli(["public-key"], { - env: {}, - writer: writer.writer, - }); - - expect(exitCode).toBe(5); +test("sign writes a proof that verify accepts", async () => { + const { dir, identity, input, env } = await setup(); + const proofPath = join(dir, "proof.json"); + expect(await runCli(["sign", "--input", input, "--out", proofPath], io(env).io)).toBe(0); + expect(JSON.parse(await readFile(proofPath, "utf8")).signer).toEqual(identity.publicIdentity); + + const verified = io(); + expect(await runCli(["verify", "--proof", proofPath, "--input", input], verified.io)).toBe(0); + expect(JSON.parse(verified.out.stdout)).toEqual({ + valid: true, + signatureValid: true, + hashMatch: true, }); +}); - it("surfaces invalid recipients without leaking armour errors", async () => { - const env = await createSigningEnv(); - const subjectPath = await createTempFile("sample.txt", "sample file\n"); - const writer = createWriter(); +test("sign without --out prints the proof", async () => { + const { input, env } = await setup(); + const signed = io(env); + expect(await runCli(["sign", "--input", input], signed.io)).toBe(0); + expect(JSON.parse(signed.out.stdout).format).toBe("seal"); +}); - const exitCode = await runCli( - ["sign", "--input", subjectPath, "--recipient", "bad-recipient"], - { env, writer: writer.writer }, - ); +test("verify exits 2 when the input changed", async () => { + const { dir, input, env } = await setup(); + const proofPath = join(dir, "proof.json"); + await runCli(["sign", "--input", input, "--out", proofPath], io(env).io); + await writeFile(input, '{"release":"1.0.1"}\n'); + const verified = io(); + expect(await runCli(["verify", "--proof", proofPath, "--input", input], verified.io)).toBe(2); + expect(JSON.parse(verified.out.stdout)).toMatchObject({ valid: false, hashMatch: false }); +}); - expect(exitCode).toBe(1); - expect(writer.read().stderr).toContain("Recipient must be a valid age recipient string."); - expect(writer.read().stderr).not.toContain("ARMOUR_"); - }); +test("usage errors, missing identity and unreadable files exit 1", async () => { + const { dir, input, env } = await setup(); + const badIdentity = join(dir, "bad.json"); + await writeFile(badIdentity, "{}"); + const cases: [string[], Record][] = [ + [["sign", "--input", input], {}], + [["sign", "--input", input], { SEAL_IDENTITY_FILE: badIdentity }], + [["sign"], env], + [["verify", "--input", input], env], + [["verify", "--proof", join(dir, "missing.json"), "--input", input], env], + [["publish", "--input", input], env], + [["sign", "--input", input, "--unknown"], env], + ]; + for (const [argv, caseEnv] of cases) { + const run = io(caseEnv); + expect(await runCli(argv, run.io)).toBe(1); + expect(run.out.stderr).not.toBe(""); + } }); -it("prints help successfully without requiring signer credentials", async () => { - const output = createWriter(); - expect(await runCli(["--help"], { env: {}, writer: output.writer })).toBe(0); - expect(output.read().stdout).toContain("Usage: seal"); - expect(output.read().stdout).toContain("seal verify"); - expect(output.read().stderr).toBe(""); +test("help prints usage", async () => { + const run = io(); + expect(await runCli(["--help"], run.io)).toBe(0); + expect(run.out.stdout).toMatch(/^Usage: seal sign/); }); diff --git a/packages/seal/test/crypto.test.ts b/packages/seal/test/crypto.test.ts deleted file mode 100644 index 0863da6..0000000 --- a/packages/seal/test/crypto.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import { parseIdentity } from "@ternent/identity"; -import { - createSealIdentity, - createSealMnemonicIdentity, - exportIdentityJson, -} from "../src/index.js"; - -describe("seal crypto", () => { - it("creates and serializes a seal identity", async () => { - const identity = await createSealIdentity("2026-03-17T00:00:00.000Z"); - const exported = exportIdentityJson(identity); - - expect(identity.format).toBe("ternent-identity"); - expect(identity.version).toBe("2"); - expect(parseIdentity(exported)).toEqual(identity); - }); - - it("creates a mnemonic-backed seal identity", async () => { - const created = await createSealMnemonicIdentity({ words: 12 }); - - expect(created.mnemonic.split(/\s+/).length).toBe(12); - expect(created.identity.format).toBe("ternent-identity"); - }); -}); - -it("rejects serialized signers whose seed does not match the claimed public key", async () => { - const { resolveSealSigner } = await import("../src/crypto.js"); - const identity = await createSealIdentity(); - const other = await createSealIdentity(); - const mismatched = { ...identity, material: { ...identity.material, seed: other.material.seed } }; - await expect(resolveSealSigner({ identity: mismatched })).rejects.toThrow(/publicKey|seed/i); -}); diff --git a/packages/seal/test/fixtures.ts b/packages/seal/test/fixtures.ts deleted file mode 100644 index e2a2903..0000000 --- a/packages/seal/test/fixtures.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { readFileSync } from "node:fs"; -import type { SerializedIdentity } from "@ternent/identity"; -import type { createSealProof } from "../src/proof.js"; -import type { SealManifestV1 } from "../src/manifest.js"; - -type Proof = Awaited>; -export type SealVector = { - seedHex: string; - identity: SerializedIdentity; - contentUtf8: string; - subjectHash: `sha256:${string}`; - context: string; - signingPayload: string; - messageHex: string; - proof: Proof; - manifest: SealManifestV1; - canonicalManifest: string; -}; -export const sealVector = (): SealVector => - JSON.parse( - readFileSync(new URL("../../../docs/seal/vectors/proof.v2.json", import.meta.url), "utf8"), - ) as SealVector; diff --git a/packages/seal/test/manifest.test.ts b/packages/seal/test/manifest.test.ts deleted file mode 100644 index 914ef4d..0000000 --- a/packages/seal/test/manifest.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { mkdtemp, mkdir, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { describe, expect, it, vi } from "vite-plus/test"; -import { createManifestArtifact } from "../src/commands/manifest.js"; - -import { - parseSealManifestJson, - stringifySealManifest, - type SealManifestV1, -} from "../src/manifest.js"; -import { sealVector } from "./fixtures.js"; - -async function createFixtureTree(): Promise { - const root = await mkdtemp(join(tmpdir(), "seal-manifest-")); - await mkdir(join(root, "nested"), { recursive: true }); - await writeFile(join(root, "a.txt"), "alpha\n", "utf8"); - await writeFile(join(root, ".DS_Store"), "ignore", "utf8"); - await writeFile(join(root, "nested", "b.txt"), "beta\n", "utf8"); - return root; -} - -describe("manifest command", () => { - it("is deterministic across runs", async () => { - const fixtureRoot = await createFixtureTree(); - const first = await createManifestArtifact(fixtureRoot); - const second = await createManifestArtifact(fixtureRoot); - - expect(first.content).toBe(second.content); - expect(first.manifest).toEqual(second.manifest); - }); - - it("excludes .DS_Store and sorts file keys", async () => { - const fixtureRoot = await createFixtureTree(); - const { manifest } = await createManifestArtifact(fixtureRoot); - - expect(Object.keys(manifest.files)).toEqual(["a.txt", "nested/b.txt"]); - }); -}); - -describe("portable manifest boundaries", () => { - it("preserves numeric and prototype-like filenames in the saved canonical manifest", () => { - const fixed = sealVector(); - expect(stringifySealManifest(fixed.manifest)).toBe(fixed.canonicalManifest); - const parsed = parseSealManifestJson(fixed.canonicalManifest); - expect(parsed.ok).toBe(true); - expect(parsed.manifest).toEqual(fixed.manifest); - expect(Object.hasOwn(parsed.manifest!.files, "__proto__")).toBe(true); - expect(Object.keys(JSON.parse(fixed.canonicalManifest).files).slice(0, 2)).toEqual(["2", "10"]); - }); - - it("includes real files named __proto__, constructor and integer keys without prototype mutation", async () => { - const root = await createFixtureTree(); - for (const name of ["__proto__", "constructor", "2", "10"]) - await writeFile(join(root, name), `content:${name}`, "utf8"); - const { manifest, content } = await createManifestArtifact(root); - for (const name of ["__proto__", "constructor", "2", "10"]) { - expect(Object.hasOwn(manifest.files, name)).toBe(true); - expect(manifest.files[name]).toMatch(/^sha256:[a-f0-9]{64}$/); - expect(Object.hasOwn(JSON.parse(content).files, name)).toBe(true); - } - expect(parseSealManifestJson(content).manifest).toEqual(manifest); - }); - - it("rejects values that cannot participate in the strict canonical JSON contract", () => { - const cyclic: Record = {}; - cyclic.self = cyclic; - const sparse: unknown[] = []; - sparse.length = 1; - const customArray = Object.setPrototypeOf(["value"], null) as unknown[]; - class ArraySubclass extends Array {} - const invalid = [ - { value: undefined }, - { value: NaN }, - { value: Infinity }, - { value: -0 }, - { value: Number.MAX_SAFE_INTEGER + 1 }, - { value: 1n }, - { value: () => "hidden" }, - { value: "unpaired-\ud800" }, - sparse, - customArray, - new ArraySubclass(), - [undefined], - cyclic, - Object.create({ inherited: true }), - new Date("2026-11-20T00:00:00.000Z"), - ]; - for (const input of invalid) - expect(() => stringifySealManifest(input as unknown as SealManifestV1)).toThrow(); - let deep: Record = {}; - for (let index = 0; index < 65; index++) deep = { nested: deep }; - expect(() => stringifySealManifest(deep as unknown as SealManifestV1)).toThrow(); - }); - - it("does not execute getters or toJSON while rejecting host objects", () => { - const getter = vi.fn(() => "must not execute"); - const hostile = {}; - Object.defineProperty(hostile, "secret", { enumerable: true, get: getter }); - expect(() => stringifySealManifest(hostile as SealManifestV1)).toThrow(); - expect(getter).not.toHaveBeenCalled(); - const toJSON = vi.fn(() => ({ hidden: "must not execute" })); - expect(() => stringifySealManifest({ toJSON } as unknown as SealManifestV1)).toThrow(); - expect(toJSON).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/seal/test/proof.test.ts b/packages/seal/test/proof.test.ts deleted file mode 100644 index 58e87e3..0000000 --- a/packages/seal/test/proof.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { createHash, createPublicKey, verify } from "node:crypto"; -import { describe, expect, it, vi } from "vite-plus/test"; -import { createIdentity, deriveKeyId } from "@ternent/identity"; -import { - createSealHash, - createSealProof, - createSealPublicKeyArtifact, - getSealProofSigningPayload, - validateSealProofShape, - parseSealProofJson, - verifySealProofAgainstBytes, - verifySealProofSignature, -} from "../src/proof.js"; - -import { sealVector } from "./fixtures.js"; - -async function createSigner() { - const identity = await createIdentity(); - return { - identity, - publicKey: identity.publicKey, - keyId: await deriveKeyId(identity.publicKey), - }; -} - -describe("seal proof", () => { - it("signs and verifies a valid proof", async () => { - const signer = await createSigner(); - const bytes = new TextEncoder().encode("seal proof bytes"); - const proof = await createSealProof({ - signer: { identity: signer.identity }, - subject: { - kind: "file", - path: "sample.txt", - hash: await createSealHash(bytes), - }, - }); - - const signatureCheck = await verifySealProofSignature(proof); - const verification = await verifySealProofAgainstBytes(proof, bytes); - - expect(signatureCheck.ok).toBe(true); - expect(verification.valid).toBe(true); - expect(verification.keyId).toBe(signer.keyId); - }); - - it("rejects invalid proof JSON", () => { - const parsed = parseSealProofJson("not-json"); - - expect(parsed.ok).toBe(false); - expect(parsed.errors[0]).toContain("not valid JSON"); - }); - - it("creates a portable public-key artifact", async () => { - const signer = await createSigner(); - const artifact = await createSealPublicKeyArtifact({ - identity: signer.identity, - }); - - expect(artifact.publicKey).toBe(signer.publicKey); - expect(artifact.keyId).toBe(signer.keyId); - expect(artifact.version).toBe("2"); - expect(artifact.type).toBe("seal-public-key"); - }); -}); - -describe("independent fixed proof v2", () => { - it("matches saved canonical payload, context, hash and Node Ed25519 signature bytes", async () => { - const fixed = sealVector(); - const bytes = new TextEncoder().encode(fixed.contentUtf8); - expect(await createSealHash(bytes)).toBe(fixed.subjectHash); - expect(`sha256:${createHash("sha256").update(bytes).digest("hex")}`).toBe(fixed.subjectHash); - expect(getSealProofSigningPayload(fixed.proof)).toBe(fixed.signingPayload); - const message = Buffer.concat([ - Buffer.from(fixed.context), - Buffer.from([0]), - Buffer.from(fixed.signingPayload), - ]); - expect(message.toString("hex")).toBe(fixed.messageHex); - const publicKey = createPublicKey({ - key: Buffer.concat([ - Buffer.from("302a300506032b6570032100", "hex"), - Buffer.from(fixed.identity.publicKey, "base64url"), - ]), - format: "der", - type: "spki", - }); - expect(verify(null, message, publicKey, Buffer.from(fixed.proof.signature, "base64url"))).toBe( - true, - ); - expect( - verify( - null, - Buffer.from(fixed.signingPayload), - publicKey, - Buffer.from(fixed.proof.signature, "base64url"), - ), - ).toBe(false); - expect( - await createSealProof({ - createdAt: fixed.proof.createdAt, - signer: { identity: fixed.identity }, - subject: fixed.proof.subject, - }), - ).toEqual(fixed.proof); - expect(await verifySealProofAgainstBytes(fixed.proof, bytes)).toMatchObject({ - valid: true, - hashMatch: true, - signatureValid: true, - }); - }); - - it("binds all subject, timestamp and signer fields rather than just the content hash", async () => { - const fixed = sealVector(); - const other = await createSigner(); - const changes: ((proof: typeof fixed.proof) => void)[] = [ - (proof) => { - proof.subject.kind = "manifest"; - }, - (proof) => { - proof.subject.path = "different.txt"; - }, - (proof) => { - proof.subject.hash = `sha256:${"0".repeat(64)}`; - }, - (proof) => { - proof.createdAt = "2026-11-21T00:00:00.000Z"; - }, - (proof) => { - proof.signer.publicKey = other.publicKey; - }, - (proof) => { - proof.signer.keyId = other.keyId; - }, - (proof) => { - proof.signer = { publicKey: other.publicKey, keyId: other.keyId }; - }, - (proof) => { - proof.signature = `${proof.signature[0] === "A" ? "B" : "A"}${proof.signature.slice(1)}`; - }, - ]; - for (const change of changes) { - const proof = structuredClone(fixed.proof); - change(proof); - expect(await verifySealProofSignature(proof)).toMatchObject({ ok: false }); - expect( - await verifySealProofAgainstBytes(proof, new TextEncoder().encode(fixed.contentUtf8)), - ).toMatchObject({ valid: false }); - } - expect( - await verifySealProofAgainstBytes(fixed.proof, new TextEncoder().encode("changed content")), - ).toMatchObject({ valid: false, signatureValid: true, hashMatch: false }); - }); - - it("returns failed verification for malformed key and signature encodings without throwing", async () => { - const fixed = sealVector(); - for (const encoding of ["!", "A", "AA==", "_", "A".repeat(43), "A".repeat(85)]) { - const key = structuredClone(fixed.proof); - key.signer.publicKey = encoding; - await expect(verifySealProofSignature(key)).resolves.toMatchObject({ ok: false }); - const signature = structuredClone(fixed.proof); - signature.signature = encoding; - await expect(verifySealProofSignature(signature)).resolves.toMatchObject({ ok: false }); - } - }); - - it("rejects non-JSON proof fields without invoking host getters", async () => { - const fixed = sealVector(); - const getter = vi.fn(() => fixed.proof.subject); - const hostile = { ...fixed.proof }; - Object.defineProperty(hostile, "subject", { enumerable: true, get: getter }); - expect(validateSealProofShape(hostile).ok).toBe(false); - await expect(verifySealProofSignature(hostile)).resolves.toMatchObject({ ok: false }); - expect(getter).not.toHaveBeenCalled(); - expect(() => getSealProofSigningPayload(hostile)).toThrow(); - expect(getter).not.toHaveBeenCalled(); - const invalidUnicode = structuredClone(fixed.proof); - invalidUnicode.subject.path = "unpaired-\ud800"; - expect(validateSealProofShape(invalidUnicode).ok).toBe(false); - }); -}); - -it("captures proof authoring and verification inputs before asynchronous signing or hashing", async () => { - const fixed = sealVector(); - const identity = structuredClone(fixed.identity); - const input = { - createdAt: fixed.proof.createdAt, - signer: { identity }, - subject: structuredClone(fixed.proof.subject), - }; - const creating = createSealProof(input); - input.createdAt = "2026-11-21T00:00:00.000Z"; - input.subject.path = "caller-mutated.txt"; - identity.material.seed = Buffer.alloc(32).toString("base64url"); - expect(await creating).toEqual(fixed.proof); - - const proof = structuredClone(fixed.proof); - const bytes = new TextEncoder().encode(fixed.contentUtf8); - const checking = verifySealProofAgainstBytes(proof, bytes); - proof.subject.path = "mutated during verification.txt"; - proof.signature = "!"; - bytes.fill(0); - expect(await checking).toMatchObject({ valid: true, signatureValid: true, hashMatch: true }); -}); diff --git a/packages/seal/test/seal.test.ts b/packages/seal/test/seal.test.ts new file mode 100644 index 0000000..757de54 --- /dev/null +++ b/packages/seal/test/seal.test.ts @@ -0,0 +1,172 @@ +import { readFileSync } from "node:fs"; +import { expect, test } from "vite-plus/test"; +import { base64urlnopad, hex } from "@scure/base"; +import { createIdentity, restoreIdentity, type Identity } from "@ternent/identity"; +import * as api from "../src/index.js"; +import { createSealHash, createSealProof, verifySealProof, type SealProof } from "../src/index.js"; + +const vectors = JSON.parse(readFileSync(new URL("vectors.json", import.meta.url), "utf8")) as { + rfc8032: { seedHex: string; proof: SealProof }; + ledger: { subjectUtf8: string; signatureMessageUtf8: string; proof: SealProof }[]; +}; +const utf8 = (text: string) => new TextEncoder().encode(text); + +async function rfc8032Identity(): Promise { + const { signer } = vectors.rfc8032.proof; + return restoreIdentity( + JSON.stringify({ + format: "ternent-identity", + version: "2", + algorithm: "Ed25519", + createdAt: "2026-01-01T00:00:00.000Z", + publicKey: signer.publicKey, + keyId: signer.id.slice("identity:".length), + material: { kind: "seed", seed: base64urlnopad.encode(hex.decode(vectors.rfc8032.seedHex)) }, + }), + ); +} + +test("the public interface is the three Seal operations", () => { + expect(Object.keys(api).sort()).toEqual(["createSealHash", "createSealProof", "verifySealProof"]); +}); + +test("createSealHash is lowercase SHA-256 with a sha256: prefix", async () => { + expect(await createSealHash(new Uint8Array())).toBe(vectors.rfc8032.proof.subject.hash); +}); + +test("authoring reproduces the fixed RFC 8032 vector byte for byte", async () => { + const identity = await rfc8032Identity(); + const { createdAt, subject } = vectors.rfc8032.proof; + const proof = await createSealProof({ signer: identity, subject, createdAt }); + expect(JSON.stringify(proof)).toBe(JSON.stringify(vectors.rfc8032.proof)); + expect(await verifySealProof(proof, new Uint8Array())).toEqual({ + valid: true, + signatureValid: true, + hashMatch: true, + }); +}); + +test("the signing message matches the Ledger vector regardless of signer field order", async () => { + for (const { subjectUtf8, signatureMessageUtf8, proof } of vectors.ledger) { + expect(await verifySealProof(proof, utf8(subjectUtf8))).toMatchObject({ valid: true }); + const { publicKey, id, algorithm, version } = proof.signer; + const signed: Uint8Array[] = []; + const recorder = { + publicIdentity: { id, publicKey, algorithm, version }, + sign: async (bytes: Uint8Array) => { + signed.push(bytes.slice()); + return base64urlnopad.decode(proof.signature); + }, + }; + const created = await createSealProof({ + signer: recorder, + subject: proof.subject, + createdAt: proof.createdAt, + }); + expect(new TextDecoder().decode(signed[0])).toBe(signatureMessageUtf8); + expect(JSON.stringify(created)).toBe(JSON.stringify(proof)); + } +}); + +test("tampering with any signed field or the bytes fails the matching check", async () => { + const { proof } = vectors.rfc8032; + const bytes = new Uint8Array(); + const other = (await createIdentity()).publicIdentity; + const flipped = base64urlnopad.decode(proof.signature); + flipped[10] ^= 1; + const cases: [unknown, Uint8Array, boolean, boolean][] = [ + [proof, utf8("x"), true, false], + [{ ...proof, subject: { hash: `sha256:${"0".repeat(64)}` } }, bytes, false, false], + [{ ...proof, createdAt: "2026-11-26T12:00:01.000Z" }, bytes, false, true], + [{ ...proof, signer: other }, bytes, false, true], + [{ ...proof, signer: { ...proof.signer, id: other.id } }, bytes, false, true], + [{ ...proof, signature: base64urlnopad.encode(flipped) }, bytes, false, true], + ]; + for (const [input, data, signatureValid, hashMatch] of cases) { + expect(await verifySealProof(input, data)).toEqual({ valid: false, signatureValid, hashMatch }); + } +}); + +test("malformed proofs verify as invalid without throwing", async () => { + const { proof } = vectors.rfc8032; + const { signature: _signature, ...unsigned } = proof; + for (const input of [ + null, + "proof", + {}, + unsigned, + { ...proof, extra: true }, + { ...proof, version: 2 }, + { ...proof, format: "other" }, + { ...proof, createdAt: "2026-11-26T12:00:00Z" }, + { ...proof, createdAt: "2026-02-30T12:00:00.000Z" }, + { ...proof, subject: { hash: proof.subject.hash.toUpperCase() } }, + { ...proof, subject: { ...proof.subject, path: "x" } }, + { ...proof, signer: { ...proof.signer, extra: true } }, + { ...proof, signature: `${proof.signature}=` }, + { ...proof, signature: proof.signature.slice(0, -2) }, + ]) { + expect((await verifySealProof(input, new Uint8Array())).valid).toBe(false); + } +}); + +test("authoring captures inputs at call time and gives the signer a copy", async () => { + const identity = await createIdentity(); + const bytes = utf8("content"); + const subject = { hash: await createSealHash(bytes) }; + const publicIdentity = { ...identity.publicIdentity }; + const pending = createSealProof({ + subject, + signer: { + publicIdentity, + sign: async (message) => { + const signature = await identity.sign(message); + message.fill(0); + return signature; + }, + }, + }); + subject.hash = `sha256:${"0".repeat(64)}`; + publicIdentity.publicKey = "changed"; + const proof = await pending; + expect(proof.signer).toEqual(identity.publicIdentity); + expect((await verifySealProof(proof, bytes)).valid).toBe(true); +}); + +test("authoring rejects bad subjects, timestamps and signatures that do not verify", async () => { + const identity = await createIdentity(); + const subject = { hash: await createSealHash(new Uint8Array()) }; + await expect( + createSealProof({ signer: identity, subject: { hash: "sha256:abc" as never } }), + ).rejects.toThrow(); + await expect( + createSealProof({ signer: identity, subject, createdAt: "yesterday" }), + ).rejects.toThrow(); + const wrongKey = await createIdentity(); + for (const sign of [wrongKey.sign, async () => new Uint8Array(63)]) { + await expect( + createSealProof({ signer: { publicIdentity: identity.publicIdentity, sign }, subject }), + ).rejects.toThrow(); + } +}); + +test("a manifest and an armored ciphertext use the same proof path", async () => { + const identity = await createIdentity(); + const manifest = utf8(JSON.stringify({ release: "1.0.0", files: { "a.js": "sha256:..." } })); + const armored = + "-----BEGIN AGE ENCRYPTED FILE-----\r\nYWdl\r\n-----END AGE ENCRYPTED FILE-----\r\n"; + for (const bytes of [manifest, utf8(armored)]) { + const proof = await createSealProof({ + signer: identity, + subject: { hash: await createSealHash(bytes) }, + }); + expect((await verifySealProof(proof, bytes)).valid).toBe(true); + } + const proof = await createSealProof({ + signer: identity, + subject: { hash: await createSealHash(utf8(armored)) }, + }); + expect((await verifySealProof(proof, utf8(armored.replaceAll("\r\n", "\n")))).hashMatch).toBe( + false, + ); +}); diff --git a/packages/seal/test/vectors.json b/packages/seal/test/vectors.json new file mode 100644 index 0000000..df9a16a --- /dev/null +++ b/packages/seal/test/vectors.json @@ -0,0 +1,60 @@ +{ + "rfc8032": { + "seedHex": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + "proof": { + "format": "seal", + "version": 1, + "createdAt": "2026-11-26T12:00:00.000Z", + "subject": { + "hash": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "signer": { + "version": 1, + "algorithm": "Ed25519", + "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", + "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" + }, + "signature": "A3werKnxfw5ZNuto4BlAbWmghn8k3mKtUpDgnIdQQiTXKHJmiXnw05xtWy51HgC9vvnoLU8Kz-aX5S2tnScmCA" + } + }, + "ledger": [ + { + "subjectUtf8": "ledger.commit/2\u0000{\"entries\":[],\"metadata\":{\"model\":\"expenses\"},\"nonce\":\"AQEBAQEBAQEBAQEBAQEBAQ\",\"parent\":null}", + "signatureMessageUtf8": "ternent-seal/v1\u0000{\"createdAt\":\"2026-11-27T12:00:00.000Z\",\"format\":\"seal\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:34750f98bd59fcfc946da45aaabe933be154a4b5094e1c4abf42866505f3c97e\",\"publicKey\":\"iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w\",\"version\":1},\"subject\":{\"hash\":\"sha256:c1cdc29b334ce1e6e53777539f0ac941fa98c9118cd0c17231cb7e89319bcc81\"},\"version\":1}", + "proof": { + "format": "seal", + "version": 1, + "createdAt": "2026-11-27T12:00:00.000Z", + "subject": { + "hash": "sha256:c1cdc29b334ce1e6e53777539f0ac941fa98c9118cd0c17231cb7e89319bcc81" + }, + "signer": { + "version": 1, + "algorithm": "Ed25519", + "publicKey": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w", + "id": "identity:34750f98bd59fcfc946da45aaabe933be154a4b5094e1c4abf42866505f3c97e" + }, + "signature": "Qmqca3aN4guyg8TXiYMN3po0UInwGBYB8JXuxglbMYYlH-ItT06b0P8gwk5XcRYEO4mTodvhrwfDxlRloA25AA" + } + }, + { + "subjectUtf8": "ledger.commit/2\u0000{\"entries\":[{\"kind\":\"expense.recorded\",\"meta\":{\"example\":true},\"nonce\":\"AwMDAwMDAwMDAwMDAwMDAw\",\"payload\":{\"amount\":2500}},{\"kind\":\"expense.tagged\",\"nonce\":\"BAQEBAQEBAQEBAQEBAQEBA\",\"payload\":{\"10\":\"train\",\"2\":\"travel\"}}],\"nonce\":\"AgICAgICAgICAgICAgICAg\",\"parent\":\"commit:b0e752d63fc76670e3bd6a9e69baa7de336894dc50b1360a5c0d86f85d36f18a\"}", + "signatureMessageUtf8": "ternent-seal/v1\u0000{\"createdAt\":\"2026-11-27T12:00:01.000Z\",\"format\":\"seal\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827\",\"publicKey\":\"gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q\",\"version\":1},\"subject\":{\"hash\":\"sha256:c8192893ef94449bf584a4f0e6119c32504554aad64f987cd4226c0deb958aab\"},\"version\":1}", + "proof": { + "format": "seal", + "version": 1, + "createdAt": "2026-11-27T12:00:01.000Z", + "subject": { + "hash": "sha256:c8192893ef94449bf584a4f0e6119c32504554aad64f987cd4226c0deb958aab" + }, + "signer": { + "version": 1, + "algorithm": "Ed25519", + "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", + "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" + }, + "signature": "a1m92SrdIZnz8ov-rLot7c9JoIRIZ0gAfg60DDjLKxYHWKIyVYkFdK-V9ATtkiu5o_b4k8M0gR5Jj1IhHpiXDw" + } + } + ] +} diff --git a/packages/seal/vite.config.ts b/packages/seal/vite.config.ts index b8e952c..2edbb3d 100644 --- a/packages/seal/vite.config.ts +++ b/packages/seal/vite.config.ts @@ -6,14 +6,6 @@ export default defineConfig({ pack: { ...base.pack, platform: "node", - entry: { - index: "src/index.ts", - proof: "src/proof.ts", - artifact: "src/artifact.ts", - manifest: "src/manifest.ts", - crypto: "src/crypto.ts", - errors: "src/errors.ts", - cli: "src/cli.ts", - }, + entry: { index: "src/index.ts", cli: "src/cli.ts" }, }, }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 813f98e..8c65e7d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -290,9 +290,9 @@ importers: packages/seal: dependencies: - '@ternent/armour': - specifier: workspace:^ - version: link:../armour + '@scure/base': + specifier: 2.4.0 + version: 2.4.0 '@ternent/identity': specifier: workspace:^ version: link:../identity @@ -662,9 +662,6 @@ packages: resolution: {integrity: sha512-z+wJlHpqB2rsnQ5PbQlWKC7lYISlHrniQ3N5JF4LGaa+kOopx5u5DMT2P7pN12fsXFg1gVcoLdRXPRyIS61OKQ==} engines: {node: ^20.19.0 || >=22.12.0} - '@oxc-project/types@0.155.0': - resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==} - '@oxc-project/types@0.159.0': resolution: {integrity: sha512-QWjWhxheluOJ82kDHNyps00UvRpQCtI34B5A/SzpgQycUD/79FuvT4I0aQIfE/bdPwKmX4QPftnywFBH6FxJhQ==} @@ -930,105 +927,6 @@ packages: resolution: {integrity: sha512-4EDEmvxWtgsCnnVeBvtFIFZtUhPPt1+bA9JrSwU4Sa//6oKtzCSlGGXYJr44OD9aGISymbieJ4mCKHUygUDU+g==} engines: {node: '>=18'} - '@rolldown/binding-android-arm-eabi@1.2.15': - resolution: {integrity: sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [android] - - '@rolldown/binding-android-arm64@1.2.15': - resolution: {integrity: sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [android] - - '@rolldown/binding-darwin-arm64@1.2.15': - resolution: {integrity: sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [darwin] - - '@rolldown/binding-darwin-x64@1.2.15': - resolution: {integrity: sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [darwin] - - '@rolldown/binding-freebsd-x64@1.2.15': - resolution: {integrity: sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [freebsd] - - '@rolldown/binding-linux-arm-gnueabihf@1.2.15': - resolution: {integrity: sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - - '@rolldown/binding-linux-arm64-gnu@1.2.15': - resolution: {integrity: sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-arm64-musl@1.2.15': - resolution: {integrity: sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@rolldown/binding-linux-ppc64-gnu@1.2.15': - resolution: {integrity: sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-s390x-gnu@1.2.15': - resolution: {integrity: sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-x64-gnu@1.2.15': - resolution: {integrity: sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-x64-musl@1.2.15': - resolution: {integrity: sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [musl] - - '@rolldown/binding-openharmony-arm64@1.2.15': - resolution: {integrity: sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [openharmony] - - '@rolldown/binding-win32-arm64-msvc@1.2.15': - resolution: {integrity: sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [win32] - - '@rolldown/binding-win32-x64-msvc@1.2.15': - resolution: {integrity: sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [win32] - - '@rolldown/pluginutils@1.0.1': - resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} - '@scure/base@2.4.0': resolution: {integrity: sha512-thZ1TuJwFwBblOhgsjDKvvGirBxNp+wSvY/DR6tJBJOTDhdAAcHJ8Vbr2eFnqaxeca4+t0i9KBf+uHYGWwZORg==} @@ -2537,11 +2435,6 @@ packages: resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} engines: {iojs: '>=1.0.0', node: '>=0.10.0'} - rolldown@1.2.15: - resolution: {integrity: sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - router@2.3.0: resolution: {integrity: sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w==} engines: {node: '>= 18'} @@ -2833,49 +2726,6 @@ packages: playwright: optional: true - vite@8.3.5: - resolution: {integrity: sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - peerDependencies: - '@types/node': 26.6.6 - '@vitejs/devtools': ^0.7.1 || ^0.8.0 - esbuild: ^0.27.0 || ^0.28.0 - jiti: '>=1.21.0' - less: ^4.0.0 - sass: ^1.70.0 - sass-embedded: ^1.70.0 - stylus: '>=0.54.8' - sugarss: ^5.0.0 - terser: ^5.16.0 - tsx: ^4.8.1 - yaml: ^2.4.2 - peerDependenciesMeta: - '@types/node': - optional: true - '@vitejs/devtools': - optional: true - esbuild: - optional: true - jiti: - optional: true - less: - optional: true - sass: - optional: true - sass-embedded: - optional: true - stylus: - optional: true - sugarss: - optional: true - terser: - optional: true - tsx: - optional: true - yaml: - optional: true - vitest@5.1.0: resolution: {integrity: sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==} engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} @@ -3332,8 +3182,6 @@ snapshots: '@oxc-project/runtime@0.159.0': {} - '@oxc-project/types@0.155.0': {} - '@oxc-project/types@0.159.0': {} '@oxfmt/binding-android-arm-eabi@0.79.0': @@ -3462,38 +3310,6 @@ snapshots: dependencies: tinyexec: 1.3.1 - '@rolldown/binding-android-arm-eabi@1.2.15': {} - - '@rolldown/binding-android-arm64@1.2.15': {} - - '@rolldown/binding-darwin-arm64@1.2.15': {} - - '@rolldown/binding-darwin-x64@1.2.15': {} - - '@rolldown/binding-freebsd-x64@1.2.15': {} - - '@rolldown/binding-linux-arm-gnueabihf@1.2.15': {} - - '@rolldown/binding-linux-arm64-gnu@1.2.15': {} - - '@rolldown/binding-linux-arm64-musl@1.2.15': {} - - '@rolldown/binding-linux-ppc64-gnu@1.2.15': {} - - '@rolldown/binding-linux-s390x-gnu@1.2.15': {} - - '@rolldown/binding-linux-x64-gnu@1.2.15': {} - - '@rolldown/binding-linux-x64-musl@1.2.15': {} - - '@rolldown/binding-openharmony-arm64@1.2.15': {} - - '@rolldown/binding-win32-arm64-msvc@1.2.15': {} - - '@rolldown/binding-win32-x64-msvc@1.2.15': {} - - '@rolldown/pluginutils@1.0.1': {} - '@scure/base@2.4.0': {} '@scure/bip39@2.4.0': @@ -3847,19 +3663,6 @@ snapshots: - utf-8-validate - vite - '@vitest/browser-preview@5.1.0(@vitest/ui@5.1.0)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1))(vitest@5.1.0)': - dependencies: - '@testing-library/dom': 10.4.2 - '@testing-library/user-event': 14.6.8(@testing-library/dom@10.4.2) - '@vitest/browser': 5.1.0(@vitest/browser-preview@5.1.0)(@vitest/ui@5.1.0)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1))(vitest@5.1.0) - vitest: 5.1.0(@types/node@26.6.6)(@vitest/browser-preview@5.1.0)(@vitest/ui@5.1.0)(jsdom@24.1.3)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1)) - transitivePeerDependencies: - - '@vitest/ui' - - bufferutil - - msw - - utf-8-validate - - vite - '@vitest/browser@5.1.0(@vitest/browser-preview@5.1.0)(@vitest/ui@5.1.0)(@voidzero-dev/vite-plus-core@8.3.8000(@types/node@26.6.6)(@typescript/typescript6@6.0.2)(@volar/typescript@2.4.30(@typescript/typescript6@6.0.2))(@vue/language-core@3.3.14)(esbuild@0.27.7)(jiti@2.7.0)(publint@0.3.25)(vue-tsc@3.3.14(@typescript/typescript6@6.0.2))(yaml@2.9.1))(vitest@5.1.0)': dependencies: '@blazediff/core': 1.10.0 @@ -3880,26 +3683,6 @@ snapshots: - utf-8-validate - vite - '@vitest/browser@5.1.0(@vitest/browser-preview@5.1.0)(@vitest/ui@5.1.0)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1))(vitest@5.1.0)': - dependencies: - '@blazediff/core': 1.10.0 - '@vitest/mocker': 5.1.0(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1)) - '@vitest/ui': 5.1.0(@vitest/browser-preview@5.1.0)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1))(vitest@5.1.0) - '@vitest/utils': 5.1.0 - magic-string: 1.4.3 - pngjs: 7.0.0 - sirv: 3.0.2 - tinyrainbow: 3.2.0 - vitest: 5.1.0(@types/node@26.6.6)(@vitest/browser-preview@5.1.0)(@vitest/ui@5.1.0)(jsdom@24.1.3)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1)) - ws: 8.22.0 - transitivePeerDependencies: - - '@vitest/browser-preview' - - '@vitest/ui' - - bufferutil - - msw - - utf-8-validate - - vite - '@vitest/mocker@5.1.0(@voidzero-dev/vite-plus-core@8.3.8000(@types/node@26.6.6)(@typescript/typescript6@6.0.2)(@volar/typescript@2.4.30(@typescript/typescript6@6.0.2))(@vue/language-core@3.3.14)(esbuild@0.27.7)(jiti@2.7.0)(publint@0.3.25)(vue-tsc@3.3.14(@typescript/typescript6@6.0.2))(yaml@2.9.1))': dependencies: '@jridgewell/trace-mapping': 0.3.31 @@ -3909,15 +3692,6 @@ snapshots: optionalDependencies: vite: '@voidzero-dev/vite-plus-core@8.3.8000(@types/node@26.6.6)(@typescript/typescript6@6.0.2)(@volar/typescript@2.4.30(@typescript/typescript6@6.0.2))(@vue/language-core@3.3.14)(esbuild@0.27.7)(jiti@2.7.0)(publint@0.3.25)(vue-tsc@3.3.14(@typescript/typescript6@6.0.2))(yaml@2.9.1)' - '@vitest/mocker@5.1.0(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1))': - dependencies: - '@jridgewell/trace-mapping': 0.3.31 - '@vitest/spy': 5.1.0 - estree-walker: 3.0.3 - magic-string: 1.4.3 - optionalDependencies: - vite: 8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1) - '@vitest/pretty-format@5.1.0': dependencies: tinyrainbow: 3.2.0 @@ -3944,19 +3718,6 @@ snapshots: - '@vitest/browser-preview' - vite - '@vitest/ui@5.1.0(@vitest/browser-preview@5.1.0)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1))(vitest@5.1.0)': - dependencies: - '@vitest/utils': 5.1.0 - fflate: 0.8.3 - flatted: 3.4.4 - pathe: 2.0.3 - sirv: 3.0.2 - tinyrainbow: 3.2.0 - vitest: 5.1.0(@types/node@26.6.6)(@vitest/browser-preview@5.1.0)(@vitest/ui@5.1.0)(jsdom@24.1.3)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1)) - transitivePeerDependencies: - - '@vitest/browser-preview' - - vite - '@vitest/utils@5.1.0': dependencies: '@vitest/pretty-format': 5.1.0 @@ -5213,27 +4974,6 @@ snapshots: reusify@1.1.0: {} - rolldown@1.2.15: - dependencies: - '@oxc-project/types': 0.155.0 - '@rolldown/pluginutils': 1.0.1 - optionalDependencies: - '@rolldown/binding-android-arm-eabi': 1.2.15 - '@rolldown/binding-android-arm64': 1.2.15 - '@rolldown/binding-darwin-arm64': 1.2.15 - '@rolldown/binding-darwin-x64': 1.2.15 - '@rolldown/binding-freebsd-x64': 1.2.15 - '@rolldown/binding-linux-arm-gnueabihf': 1.2.15 - '@rolldown/binding-linux-arm64-gnu': 1.2.15 - '@rolldown/binding-linux-arm64-musl': 1.2.15 - '@rolldown/binding-linux-ppc64-gnu': 1.2.15 - '@rolldown/binding-linux-s390x-gnu': 1.2.15 - '@rolldown/binding-linux-x64-gnu': 1.2.15 - '@rolldown/binding-linux-x64-musl': 1.2.15 - '@rolldown/binding-openharmony-arm64': 1.2.15 - '@rolldown/binding-win32-arm64-msvc': 1.2.15 - '@rolldown/binding-win32-x64-msvc': 1.2.15 - router@2.3.0: dependencies: debug: 4.4.3 @@ -5629,20 +5369,6 @@ snapshots: - vue-tsc - yaml - vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1): - dependencies: - lightningcss: 1.33.0 - picomatch: 4.0.7 - postcss: 8.5.33 - rolldown: 1.2.15 - tinyglobby: 0.2.17 - optionalDependencies: - '@types/node': 26.6.6 - esbuild: 0.27.7 - fsevents: 2.3.3 - jiti: 2.7.0 - yaml: 2.9.1 - vitest@5.1.0(@types/node@26.6.6)(@vitest/browser-preview@5.1.0)(@vitest/ui@5.1.0)(@voidzero-dev/vite-plus-core@8.3.8000(@types/node@26.6.6)(@typescript/typescript6@6.0.2)(@volar/typescript@2.4.30(@typescript/typescript6@6.0.2))(@vue/language-core@3.3.14)(esbuild@0.27.7)(jiti@2.7.0)(publint@0.3.25)(vue-tsc@3.3.14(@typescript/typescript6@6.0.2))(yaml@2.9.1))(jsdom@24.1.3): dependencies: '@types/chai': 5.2.3 @@ -5667,30 +5393,6 @@ snapshots: transitivePeerDependencies: - msw - vitest@5.1.0(@types/node@26.6.6)(@vitest/browser-preview@5.1.0)(@vitest/ui@5.1.0)(jsdom@24.1.3)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1)): - dependencies: - '@types/chai': 5.2.3 - '@vitest/mocker': 5.1.0(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1)) - chai: 6.3.0 - es-module-lexer: 2.3.2 - expect-type: 1.4.0 - magic-string: 1.4.3 - obug: 3.0.0 - picomatch: 4.0.7 - std-env: 4.3.0 - tinybench: 6.2.2 - tinyexec: 1.3.1 - tinyglobby: 0.2.17 - vite: 8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1) - why-is-node-running: 3.2.1 - optionalDependencies: - '@types/node': 26.6.6 - '@vitest/browser-preview': 5.1.0(@vitest/ui@5.1.0)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1))(vitest@5.1.0) - '@vitest/ui': 5.1.0(@vitest/browser-preview@5.1.0)(vite@8.3.5(@types/node@26.6.6)(esbuild@0.27.7)(jiti@2.7.0)(yaml@2.9.1))(vitest@5.1.0) - jsdom: 24.1.3 - transitivePeerDependencies: - - msw - vscode-jsonrpc@9.0.3: optional: true From 7aafb305e57b10796eee0125495ff6a6b03d021a Mon Sep 17 00:00:00 2001 From: samternent Date: Fri, 27 Nov 2026 23:27:01 +0000 Subject: [PATCH 03/24] chore(identity, seal): keep only files that describe the current packages Remove the changelogs, agent guides and Seal's CLAUDE.md, which described the retired APIs, and a stray Vite timestamp file. Each README now carries the package's interface. Identity's test vectors move into the package so its tests no longer read the docs folder. Co-Authored-By: Claude Opus 5.5 --- packages/identity/CHANGELOG.md | 86 -------- packages/identity/README.md | 4 + packages/identity/llms.txt | 38 ---- packages/identity/package.json | 3 +- packages/identity/test/api.test.ts | 38 ++-- packages/identity/test/strict.test.ts | 4 +- packages/identity/test/vectors.json | 30 +++ packages/seal/CHANGELOG.md | 197 ------------------ packages/seal/CLAUDE.md | 8 - packages/seal/llms.txt | 27 --- packages/seal/package.json | 3 +- ....timestamp-1783937652813-3c5d451f6ccec.mjs | 100 --------- 12 files changed, 55 insertions(+), 483 deletions(-) delete mode 100644 packages/identity/CHANGELOG.md delete mode 100644 packages/identity/llms.txt create mode 100644 packages/identity/test/vectors.json delete mode 100644 packages/seal/CHANGELOG.md delete mode 100644 packages/seal/CLAUDE.md delete mode 100644 packages/seal/llms.txt delete mode 100644 packages/seal/vite.config.ts.timestamp-1783937652813-3c5d451f6ccec.mjs diff --git a/packages/identity/CHANGELOG.md b/packages/identity/CHANGELOG.md deleted file mode 100644 index fb9ee7e..0000000 --- a/packages/identity/CHANGELOG.md +++ /dev/null @@ -1,86 +0,0 @@ -# @ternent/identity - -## 0.6.0 - -### Minor Changes - -- e5c6808: Establish the five-library alpha: standalone Identity, Armour, Ledger and Seal, - with Concord composing Ledger's common signed container, authority, independent - encrypted groups, command drafts and application replay. The common container - deliberately replaces the previous Concord alpha wire format. - - Armour uses typage and offers explicit payload codecs for Ledger. Uncommitted - entries and command intents stay in memory; consumers own draft recovery and - storage publication. Verify public imports, declarations, CLI behavior and exact - candidate bytes before publication. - -### Patch Changes - -- 7d55bda: Include agent interface guides with public imports, runnable examples, lifecycle and - error contracts, and host-owned storage/recovery behavior. - -## 0.6.0-alpha.1 - -### Minor Changes - -- e5c6808: Establish the five-library alpha: standalone Identity, Armour, Ledger and Seal, - with Concord composing Ledger's common signed container, authority, independent - encrypted groups, command drafts and application replay. The common container - deliberately replaces the previous Concord alpha wire format. - - Armour uses typage and offers explicit payload codecs for Ledger. Uncommitted - entries and command intents stay in memory; consumers own draft recovery and - storage publication. Verify public imports, declarations, CLI behavior and exact - candidate bytes before publication. - -## 0.5.1 - -### Patch Changes - -- [`4aa5e00`](https://github.com/ternent/core/commit/4aa5e001cecf61cb702414be2e63209002a521ca) Thanks [@samternent](https://github.com/samternent)! - Update deploys - -## 0.5.0 - -### Minor Changes - -- [`89ed4d7`](https://github.com/ternent/core/commit/89ed4d73d016d1d3b7b2905298cf22977b7f26be) Thanks [@samternent](https://github.com/samternent)! - fix package formats - -## 0.4.2 - -### Patch Changes - -- [`9aa260e`](https://github.com/ternent/core/commit/9aa260e70bf5750a01369404cdc29340f1bf3d39) Thanks [@samternent](https://github.com/samternent)! - fix builds - -## 0.4.1 - -### Patch Changes - -- [`46c60f6`](https://github.com/ternent/core/commit/46c60f6407ba8ac659aee5254bc5e74936989a61) Thanks [@samternent](https://github.com/samternent)! - Fix publish script - -## 0.4.0 - -### Minor Changes - -- [`b85f1eb`](https://github.com/ternent/core/commit/b85f1ebc2e47199e6259e5102e3cc16e1db279f6) Thanks [@samternent](https://github.com/samternent)! - Migrate to ternent org - -## 0.3.1 - -### Patch Changes - -- [`cb63d9c1dc91e0cd3924bafd5abcde89cc02992f`](https://github.com/samternent/home/commit/cb63d9c1dc91e0cd3924bafd5abcde89cc02992f) Thanks [@samternent](https://github.com/samternent)! - Fix workflows - -## 0.3.0 - -### Minor Changes - -- [`f364cb7d38f18770d32fe4a628b3c8b4bcccc31f`](https://github.com/samternent/home/commit/f364cb7d38f18770d32fe4a628b3c8b4bcccc31f) Thanks [@samternent](https://github.com/samternent)! - Introduce the new `@ternent/identity` package with Ed25519 signing, BIP-39 mnemonic recovery, Noble-backed Curve25519 conversion helpers, and versioned JSON identity exports. Migrate `@ternent/seal-cli` and the Seal web app to the seed-material envelope format, `SEAL_IDENTITY` configuration, and Ed25519 proof artifacts while keeping `ternent-identity` as the documented legacy package for existing Concord and PixPax consumers. - -## 0.2.0 - -### Minor Changes - -- [`f364cb7d38f18770d32fe4a628b3c8b4bcccc31f`](https://github.com/samternent/home/commit/f364cb7d38f18770d32fe4a628b3c8b4bcccc31f) Thanks [@samternent](https://github.com/samternent)! - Introduce the new `@ternent/identity` package with Ed25519 signing, X25519 bridge helpers, and versioned JSON identity exports. Migrate `@ternent/seal-cli` and the Seal web app to the new identity format, `SEAL_IDENTITY` configuration, and Ed25519 proof artifacts while keeping `ternent-identity` as the documented legacy package for existing Concord and PixPax consumers. - -### Patch Changes - -- [`f364cb7d38f18770d32fe4a628b3c8b4bcccc31f`](https://github.com/samternent/home/commit/f364cb7d38f18770d32fe4a628b3c8b4bcccc31f) Thanks [@samternent](https://github.com/samternent)! - Move idenity algo with v2 diff --git a/packages/identity/README.md b/packages/identity/README.md index e5424df..e23bc53 100644 --- a/packages/identity/README.md +++ b/packages/identity/README.md @@ -30,6 +30,10 @@ const same = await recoverIdentity(mnemonic, passphrase); | `verify(publicIdentity, bytes, signature)` | Strict Ed25519 verification; `false` for any invalid input | | `validatePublicIdentity(input)` | Frozen `PublicIdentity` from untrusted input, or throws | +A `PublicIdentity` is `{ version: 1, algorithm: "Ed25519", publicKey, id }`, with a +base64url key and `id` = `identity:` + hex SHA-256 of the key. It is safe to store in +documents. + An `Identity` has `publicIdentity`, `export()`, `sign(bytes)` and `withX25519Secret(use)`. `sign` signs exactly the bytes given; protocols add their own domain separation. The X25519 secret lent to `use` is zeroed when the callback diff --git a/packages/identity/llms.txt b/packages/identity/llms.txt deleted file mode 100644 index 7c7a178..0000000 --- a/packages/identity/llms.txt +++ /dev/null @@ -1,38 +0,0 @@ -# @ternent/identity - -> One Ed25519 identity: create, back up, restore, recover from words, sign and verify. - -All exports come from the package root. Declarations: `dist/index.d.ts`. -[Public README](https://github.com/ternent/core/blob/main/packages/identity/README.md). - -```ts -import { - createIdentity, - restoreIdentity, - createMnemonicIdentity, - recoverIdentity, - verify, - validatePublicIdentity, - type Identity, - type PublicIdentity, -} from "@ternent/identity"; - -const identity = await createIdentity(); -const backup = identity.export(); // JSON with the private seed; the app stores it -const restored = await restoreIdentity(backup); -const signature = await identity.sign(bytes); // 64 bytes over exactly `bytes` -const ok = await verify(identity.publicIdentity, bytes, signature); -``` - -- Pass the `Identity` itself to Ledger, Seal and Armour. Do not decode the seed or - build a second signer. -- `PublicIdentity` is `{ version: 1, algorithm: "Ed25519", publicKey, id }` with a - base64url key and `id = "identity:" + hex(sha256(publicKey))`. It is safe to put - in documents. Check untrusted values with `validatePublicIdentity` (throws). -- `verify` never throws; it returns `false` for a bad identity, signature or match. -- `restoreIdentity`, `recoverIdentity` and `createMnemonicIdentity` reject with an - ordinary `Error` on invalid input. -- `withX25519Secret(use)` lends a temporary X25519 secret for decryption and zeroes - it after `use` settles. Do not retain it. -- Recovery words are opt-in, shown once, and never part of the backup. -- Encryption, storage, accounts and two-factor checks belong to the application. diff --git a/packages/identity/package.json b/packages/identity/package.json index 80967ee..d05c7c7 100644 --- a/packages/identity/package.json +++ b/packages/identity/package.json @@ -10,8 +10,7 @@ }, "files": [ "dist", - "README.md", - "llms.txt" + "README.md" ], "type": "module", "sideEffects": false, diff --git a/packages/identity/test/api.test.ts b/packages/identity/test/api.test.ts index d9fad8d..0942fda 100644 --- a/packages/identity/test/api.test.ts +++ b/packages/identity/test/api.test.ts @@ -12,9 +12,7 @@ import { validatePublicIdentity, } from "../src/index.js"; -const saved = JSON.parse( - readFileSync(new URL("../../../docs/seal/vectors/proof.v2.json", import.meta.url), "utf8"), -); +const vectors = JSON.parse(readFileSync(new URL("vectors.json", import.meta.url), "utf8")); const mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; @@ -53,13 +51,13 @@ test("create, export, restore and exact-byte signing use one usable identity", a }); test("existing version 2 backups preserve keys, metadata, signatures and age derivation", async () => { - const identity = await restoreIdentity(JSON.stringify(saved.identity)); - expect(JSON.parse(identity.export())).toEqual(saved.identity); + const identity = await restoreIdentity(JSON.stringify(vectors.backup)); + expect(JSON.parse(identity.export())).toEqual(vectors.backup); expect(identity.publicIdentity).toEqual({ version: 1, algorithm: "Ed25519", - publicKey: saved.identity.publicKey, - id: `identity:${saved.identity.keyId}`, + publicKey: vectors.backup.publicKey, + id: `identity:${vectors.backup.keyId}`, }); expect(hex.encode(await identity.sign(new Uint8Array()))).toBe( "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", @@ -67,8 +65,8 @@ test("existing version 2 backups preserve keys, metadata, signatures and age der expect( await verify( identity.publicIdentity, - hex.decode(saved.messageHex), - base64urlnopad.decode(saved.proof.signature), + hex.decode(vectors.signedMessageHex), + base64urlnopad.decode(vectors.signature), ), ).toBe(true); await identity.withX25519Secret((secret) => { @@ -85,7 +83,7 @@ test("existing version 2 backups preserve keys, metadata, signatures and age der }); test("mutable signing input is captured and temporary secrets are cleared on settlement", async () => { - const identity = await restoreIdentity(JSON.stringify(saved.identity)); + const identity = await restoreIdentity(JSON.stringify(vectors.backup)); const bytes = new Uint8Array([1, 2, 3]); const signature = identity.sign(bytes); bytes.fill(0); @@ -123,24 +121,24 @@ test("restore rejects malformed and mismatched backup fields", async () => { const invalid = [ null, {}, - { ...saved.identity, version: "1" }, - { ...saved.identity, algorithm: "other" }, - { ...saved.identity, createdAt: 42 }, - { ...saved.identity, publicKey: other.publicKey }, - { ...saved.identity, keyId: other.keyId }, - { ...saved.identity, material: { kind: "seed", seed: other.material.seed } }, + { ...vectors.backup, version: "1" }, + { ...vectors.backup, algorithm: "other" }, + { ...vectors.backup, createdAt: 42 }, + { ...vectors.backup, publicKey: other.publicKey }, + { ...vectors.backup, keyId: other.keyId }, + { ...vectors.backup, material: { kind: "seed", seed: other.material.seed } }, ]; for (const input of invalid) await expect(restoreIdentity(JSON.stringify(input))).rejects.toThrow(); for (const seed of [ "", - saved.identity.material.seed + "!", - saved.identity.material.seed + "=", - " " + saved.identity.material.seed, + vectors.backup.material.seed + "!", + vectors.backup.material.seed + "=", + " " + vectors.backup.material.seed, base64urlnopad.encode(new Uint8Array(31)), ]) { await expect( - restoreIdentity(JSON.stringify({ ...saved.identity, material: { kind: "seed", seed } })), + restoreIdentity(JSON.stringify({ ...vectors.backup, material: { kind: "seed", seed } })), ).rejects.toThrow(); } await expect(restoreIdentity("not json")).rejects.toThrow(); diff --git a/packages/identity/test/strict.test.ts b/packages/identity/test/strict.test.ts index 2af8892..3c5b034 100644 --- a/packages/identity/test/strict.test.ts +++ b/packages/identity/test/strict.test.ts @@ -10,9 +10,7 @@ import { type PublicIdentity, } from "../src/index.js"; -const vector = JSON.parse( - readFileSync(new URL("../../../docs/concord/vectors/primitives.json", import.meta.url), "utf8"), -).identity as { +const vector = JSON.parse(readFileSync(new URL("vectors.json", import.meta.url), "utf8")).seed as { seedHex: string; public: PublicIdentity; x25519SecretHex: string; diff --git a/packages/identity/test/vectors.json b/packages/identity/test/vectors.json new file mode 100644 index 0000000..b815af7 --- /dev/null +++ b/packages/identity/test/vectors.json @@ -0,0 +1,30 @@ +{ + "backup": { + "format": "ternent-identity", + "version": "2", + "algorithm": "Ed25519", + "createdAt": "2026-11-20T00:00:00.000Z", + "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", + "keyId": "21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", + "material": { + "kind": "seed", + "seed": "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A" + } + }, + "signedMessageHex": "7465726e656e742d7365616c2f7632007b22616c676f726974686d223a2245643235353139222c22637265617465644174223a22323032362d31312d32305430303a30303a30302e3030305a222c227369676e6572223a7b226b65794964223a2232316665333164666131353461323631363236626638353430343666643232373162376265643462366162653435616135383837376566343766393732316239222c227075626c69634b6579223a223131715941594b7843726656535f3754795751484f6737686376506170694d6c727749616150634855526f227d2c227375626a656374223a7b2268617368223a227368613235363a65616439373437346338333534303732343630303062376439383433306264376537316461633663393838633732316635326437633161323535333438656163222c226b696e64223a2266696c65222c2270617468223a22646973742fceb42e747874227d2c2274797065223a227365616c2d70726f6f66222c2276657273696f6e223a2232227d", + "signature": "3bX0FY6naBoXDXNUtjdkYVO7-vjcOWsD-LwYZFWDTWNHq9nayOcnfg75Q3HRpo7E9xqhpmPd_hOivZVxwXEICQ", + "seed": { + "seedHex": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + "public": { + "version": 1, + "algorithm": "Ed25519", + "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", + "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" + }, + "x25519SecretHex": "307c83864f2833cb427a2ef1c00a013cfdff2768d980c0a3a520f006904de94f", + "x25519PublicHex": "d85e07ec22b0ad881537c2f44d662d1a143cf830c57aca4305d85c7a90f6b62e", + "ageRecipient": "age1mp0q0mpzkzkcs9fhct6y6e3drg2re7psc4av5sc9mpw84y8kkchq6r9kjp", + "ageSecretKey": "AGE-SECRET-KEY-1XP7G8PJ09QEUKSN69MCUQZSP8N7L7FMGMXQVPGA9YRCQDYZDA98STDSL3D", + "rfc8032EmptyMessageSignatureHex": "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b" + } +} diff --git a/packages/seal/CHANGELOG.md b/packages/seal/CHANGELOG.md deleted file mode 100644 index ea9882d..0000000 --- a/packages/seal/CHANGELOG.md +++ /dev/null @@ -1,197 +0,0 @@ -# @ternent/seal-cli - -## 0.5.0 - -### Minor Changes - -- e5c6808: Establish the five-library alpha: standalone Identity, Armour, Ledger and Seal, - with Concord composing Ledger's common signed container, authority, independent - encrypted groups, command drafts and application replay. The common container - deliberately replaces the previous Concord alpha wire format. - - Armour uses typage and offers explicit payload codecs for Ledger. Uncommitted - entries and command intents stay in memory; consumers own draft recovery and - storage publication. Verify public imports, declarations, CLI behavior and exact - candidate bytes before publication. - -### Patch Changes - -- 7d55bda: Include agent interface guides with public imports, runnable examples, lifecycle and - error contracts, and host-owned storage/recovery behavior. -- Updated dependencies [7d55bda] -- Updated dependencies [e5c6808] - - @ternent/identity@0.6.0 - - @ternent/armour@0.3.0 - -## 0.5.0-alpha.1 - -### Minor Changes - -- e5c6808: Establish the five-library alpha: standalone Identity, Armour, Ledger and Seal, - with Concord composing Ledger's common signed container, authority, independent - encrypted groups, command drafts and application replay. The common container - deliberately replaces the previous Concord alpha wire format. - - Armour uses typage and offers explicit payload codecs for Ledger. Uncommitted - entries and command intents stay in memory; consumers own draft recovery and - storage publication. Verify public imports, declarations, CLI behavior and exact - candidate bytes before publication. - -### Patch Changes - -- Updated dependencies [e5c6808] - - @ternent/identity@0.6.0-alpha.1 - - @ternent/armour@0.3.0-alpha.1 - -## 0.4.1 - -### Patch Changes - -- [`4aa5e00`](https://github.com/ternent/core/commit/4aa5e001cecf61cb702414be2e63209002a521ca) Thanks [@samternent](https://github.com/samternent)! - Update deploys - -- Updated dependencies [[`4aa5e00`](https://github.com/ternent/core/commit/4aa5e001cecf61cb702414be2e63209002a521ca)]: - - @ternent/armour@0.2.4 - - @ternent/identity@0.5.1 - - @ternent/utils@1.3.2 - -## 0.4.0 - -### Minor Changes - -- [`b79d16d`](https://github.com/ternent/core/commit/b79d16d13b55e292065a6779c42faeafc2da50d1) Thanks [@samternent](https://github.com/samternent)! - Migrate seal - -## 0.3.10 - -### Patch Changes - -- [`9d23630e3dd0d0ffb22b62e3bf159dd01d60bbaa`](https://github.com/samternent/home/commit/9d23630e3dd0d0ffb22b62e3bf159dd01d60bbaa) Thanks [@samternent](https://github.com/samternent)! - Fix ternent-api deploy packaging by building the proof-only Seal surface used by PixPax issuer and including the missing runtime package outputs in the image build. - -## 0.3.9 - -### Patch Changes - -- Updated dependencies [[`ad1b704fb8ba54b12d6140ffbed0fee66adcb6fd`](https://github.com/samternent/home/commit/ad1b704fb8ba54b12d6140ffbed0fee66adcb6fd)]: - - ternent-utils@1.1.3 - -## 0.3.8 - -### Patch Changes - -- Updated dependencies [[`4932df0ce286521f874ffd670ca022592f7d3462`](https://github.com/samternent/home/commit/4932df0ce286521f874ffd670ca022592f7d3462)]: - - ternent-utils@1.1.2 - -## 0.3.7 - -### Patch Changes - -- [`cb63d9c1dc91e0cd3924bafd5abcde89cc02992f`](https://github.com/samternent/home/commit/cb63d9c1dc91e0cd3924bafd5abcde89cc02992f) Thanks [@samternent](https://github.com/samternent)! - Fix workflows - -- Updated dependencies [[`cb63d9c1dc91e0cd3924bafd5abcde89cc02992f`](https://github.com/samternent/home/commit/cb63d9c1dc91e0cd3924bafd5abcde89cc02992f)]: - - @ternent/identity@0.3.1 - - @ternent/armour@0.1.5 - -## 0.3.6 - -### Patch Changes - -- [`acf974919a1176da235e7ec7468c46df8bc13402`](https://github.com/samternent/home/commit/acf974919a1176da235e7ec7468c46df8bc13402) Thanks [@samternent](https://github.com/samternent)! - Update build configs - -- Updated dependencies [[`acf974919a1176da235e7ec7468c46df8bc13402`](https://github.com/samternent/home/commit/acf974919a1176da235e7ec7468c46df8bc13402)]: - - @ternent/armour@0.1.4 - -## 0.3.5 - -### Patch Changes - -- [`3fd51c9f51ccc3d816d044aa8aa161d9683534c3`](https://github.com/samternent/home/commit/3fd51c9f51ccc3d816d044aa8aa161d9683534c3) Thanks [@samternent](https://github.com/samternent)! - alias utils - -## 0.3.4 - -### Patch Changes - -- [`109f8c3989b16a161a34b933dcad68390d9219c5`](https://github.com/samternent/home/commit/109f8c3989b16a161a34b933dcad68390d9219c5) Thanks [@samternent](https://github.com/samternent)! - Fix deps - -- Updated dependencies [[`109f8c3989b16a161a34b933dcad68390d9219c5`](https://github.com/samternent/home/commit/109f8c3989b16a161a34b933dcad68390d9219c5)]: - - @ternent/armour@0.1.3 - -## 0.3.3 - -### Patch Changes - -- [`91246e9d2645faa6d25b0a05cc507bc0c66ade01`](https://github.com/samternent/home/commit/91246e9d2645faa6d25b0a05cc507bc0c66ade01) Thanks [@samternent](https://github.com/samternent)! - Add armoured seal - -## 0.3.2 - -### Patch Changes - -- [`e3b14dab10ce8da5b875826383c71283cbd5b99c`](https://github.com/samternent/home/commit/e3b14dab10ce8da5b875826383c71283cbd5b99c) Thanks [@samternent](https://github.com/samternent)! - Adds create identity to seal-cli - -## 0.3.1 - -### Patch Changes - -- [`ee7aa501b6a57f0896e9a3b8c13c3446f8751a5a`](https://github.com/samternent/home/commit/ee7aa501b6a57f0896e9a3b8c13c3446f8751a5a) Thanks [@samternent](https://github.com/samternent)! - Fix the package runtime dependency graph by shipping `@ternent/identity` and `ternent-utils` as production dependencies. This prevents browser consumers that bundle Seal proof helpers from source from failing to resolve `@ternent/identity` during app builds. - -## 0.3.0 - -### Minor Changes - -- [`f364cb7d38f18770d32fe4a628b3c8b4bcccc31f`](https://github.com/samternent/home/commit/f364cb7d38f18770d32fe4a628b3c8b4bcccc31f) Thanks [@samternent](https://github.com/samternent)! - Introduce the new `@ternent/identity` package with Ed25519 signing, BIP-39 mnemonic recovery, Noble-backed Curve25519 conversion helpers, and versioned JSON identity exports. Migrate `@ternent/seal-cli` and the Seal web app to the seed-material envelope format, `SEAL_IDENTITY` configuration, and Ed25519 proof artifacts while keeping `ternent-identity` as the documented legacy package for existing Concord and PixPax consumers. - -## 0.2.0 - -### Minor Changes - -- [`f364cb7d38f18770d32fe4a628b3c8b4bcccc31f`](https://github.com/samternent/home/commit/f364cb7d38f18770d32fe4a628b3c8b4bcccc31f) Thanks [@samternent](https://github.com/samternent)! - Introduce the new `@ternent/identity` package with Ed25519 signing, X25519 bridge helpers, and versioned JSON identity exports. Migrate `@ternent/seal-cli` and the Seal web app to the new identity format, `SEAL_IDENTITY` configuration, and Ed25519 proof artifacts while keeping `ternent-identity` as the documented legacy package for existing Concord and PixPax consumers. - -### Patch Changes - -- [`f364cb7d38f18770d32fe4a628b3c8b4bcccc31f`](https://github.com/samternent/home/commit/f364cb7d38f18770d32fe4a628b3c8b4bcccc31f) Thanks [@samternent](https://github.com/samternent)! - Move idenity algo with v2 - -## 0.1.8 - -### Patch Changes - -- [`e694239710abbe9ab15bd386901f34334f7692e5`](https://github.com/samternent/home/commit/e694239710abbe9ab15bd386901f34334f7692e5) Thanks [@samternent](https://github.com/samternent)! - code deletion and renaming - -## 0.1.7 - -### Patch Changes - -- [`ba97b4b9466f7c16a7226609f8047e5367afdd70`](https://github.com/samternent/home/commit/ba97b4b9466f7c16a7226609f8047e5367afdd70) Thanks [@samternent](https://github.com/samternent)! - Update seal publish - -## 0.1.6 - -### Patch Changes - -- [`44a52fc20be15459f3771f37a002d5ea40068d10`](https://github.com/samternent/home/commit/44a52fc20be15459f3771f37a002d5ea40068d10) Thanks [@samternent](https://github.com/samternent)! - Bump version with action - -## 0.1.5 - -### Patch Changes - -- [`be5ecca6e2c9db462407c4edd6d3f668c5d51060`](https://github.com/samternent/home/commit/be5ecca6e2c9db462407c4edd6d3f668c5d51060) Thanks [@samternent](https://github.com/samternent)! - Publish seal-cli - -## 0.1.4 - -### Patch Changes - -- [`0b11c7d885e591fb1c9f373d209abe9d9f9dfb61`](https://github.com/samternent/home/commit/0b11c7d885e591fb1c9f373d209abe9d9f9dfb61) Thanks [@samternent](https://github.com/samternent)! - Seal publsh bump - -## 0.1.3 - -### Patch Changes - -- [`d1ffa2ed2d23d6c007ab829c0c4d4fd026ce188b`](https://github.com/samternent/home/commit/d1ffa2ed2d23d6c007ab829c0c4d4fd026ce188b) Thanks [@samternent](https://github.com/samternent)! - Update seal-cli scoping - -## 0.1.2 - -### Patch Changes - -- [`fd130eb5815c2ea636f66acb5a81c947c4081d95`](https://github.com/samternent/home/commit/fd130eb5815c2ea636f66acb5a81c947c4081d95) Thanks [@samternent](https://github.com/samternent)! - Adds to publish script - -## 0.1.1 - -### Patch Changes - -- [`36dd9bfac417eba61b8e81756cf15a3d3ac7a216`](https://github.com/samternent/home/commit/36dd9bfac417eba61b8e81756cf15a3d3ac7a216) Thanks [@samternent](https://github.com/samternent)! - Adds cli and GHA diff --git a/packages/seal/CLAUDE.md b/packages/seal/CLAUDE.md deleted file mode 100644 index d1ea4c3..0000000 --- a/packages/seal/CLAUDE.md +++ /dev/null @@ -1,8 +0,0 @@ -# Seal architecture - -`@ternent/seal` supplies browser-safe proof/artifact/manifest/crypto/error APIs and a -separate Node executable. Preserve wire proof/public-key version 2 and manifest/artifact -version 1. Seal owns its canonical signing subjects; Identity owns signing, strict -verification and identity derivation; Armour/typage owns encryption. No Concord, Utils, -Rage, source aliases or cryptographic reimplementations belong here. Read docs/seal/format.md -and the dated migration evidence before changing signatures or accepted canonical values. diff --git a/packages/seal/llms.txt b/packages/seal/llms.txt deleted file mode 100644 index 94a6a6a..0000000 --- a/packages/seal/llms.txt +++ /dev/null @@ -1,27 +0,0 @@ -# @ternent/seal - -> Detached Ed25519 proofs over SHA-256 content hashes, plus a `seal` CLI. - -Three exports from the package root: `createSealHash`, `createSealProof`, `verifySealProof`. -Types: `SealProof`, `SealHash`, `SealVerification`. Declarations: `dist/index.d.ts`. - -```ts -import { createIdentity } from "@ternent/identity"; -import { createSealHash, createSealProof, verifySealProof } from "@ternent/seal"; - -const identity = await createIdentity(); -const proof = await createSealProof({ - signer: identity, // any { publicIdentity, sign } from @ternent/identity - subject: { hash: await createSealHash(bytes) }, -}); -const { valid } = await verifySealProof(proof, bytes); -if (!valid || proof.signer.id !== trustedPublisher.id) throw new Error("Untrusted"); -``` - -- `verifySealProof` never throws; malformed proofs return `valid: false`. -- `signatureValid` and `hashMatch` are reported separately; `valid` needs both. -- Seal does not decide trust. Pin the expected signer yourself. -- Seal has no recipients or encryption. To prove encrypted data, seal its ciphertext bytes. -- To prove several files, seal a manifest of their hashes and check each file yourself. -- CLI: `seal sign --input [--out ]` with `SEAL_IDENTITY_FILE` set; - `seal verify --proof --input `. Exit 0 ok, 1 error, 2 invalid proof. diff --git a/packages/seal/package.json b/packages/seal/package.json index e3d449f..a59f5b8 100644 --- a/packages/seal/package.json +++ b/packages/seal/package.json @@ -25,8 +25,7 @@ "files": [ "bin", "dist", - "README.md", - "llms.txt" + "README.md" ], "type": "module", "sideEffects": false, diff --git a/packages/seal/vite.config.ts.timestamp-1783937652813-3c5d451f6ccec.mjs b/packages/seal/vite.config.ts.timestamp-1783937652813-3c5d451f6ccec.mjs deleted file mode 100644 index 0bb1f85..0000000 --- a/packages/seal/vite.config.ts.timestamp-1783937652813-3c5d451f6ccec.mjs +++ /dev/null @@ -1,100 +0,0 @@ -// vite.config.ts -import { dirname as dirname2, resolve as resolve2 } from "node:path"; -import { fileURLToPath as fileURLToPath2 } from "node:url"; -import { defineConfig } from "file:///Users/sam/dev/ternent/core/node_modules/.pnpm/vite@2.9.18/node_modules/vite/dist/node/index.js"; - -// ../../scripts/vite/package-lib-config.ts -import { builtinModules } from "node:module"; -import { readFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -function loadPackageJson(packageDir) { - const packageJsonPath = resolve(packageDir, "package.json"); - return JSON.parse(readFileSync(packageJsonPath, "utf8")); -} -function createPackageNames(packageJson) { - return /* @__PURE__ */ new Set([ - ...Object.keys(packageJson.dependencies || {}), - ...Object.keys(packageJson.peerDependencies || {}), - ...Object.keys(packageJson.optionalDependencies || {}) - ]); -} -function isExternalId(id, packageNames, includeNodeBuiltins) { - if (includeNodeBuiltins) { - if (builtinModules.includes(id) || builtinModules.includes(id.replace(/^node:/, ""))) { - return true; - } - if (id.startsWith("node:")) { - return true; - } - } - for (const packageName of packageNames) { - if (id === packageName || id.startsWith(`${packageName}/`)) { - return true; - } - } - return false; -} -function createPackageExternal(packageDir, options = {}) { - const packageJson = loadPackageJson(packageDir); - const packageNames = createPackageNames(packageJson); - const includeNodeBuiltins = options.includeNodeBuiltins === true; - return function external2(id) { - return isExternalId(id, packageNames, includeNodeBuiltins); - }; -} -function resolvePackageDir(metaUrl) { - return dirname(fileURLToPath(metaUrl)); -} - -// vite.config.ts -var __vite_injected_original_import_meta_url = "file:///Users/sam/dev/ternent/core/packages/seal/vite.config.ts"; -var configDir = dirname2(fileURLToPath2(__vite_injected_original_import_meta_url)); -var external = createPackageExternal(resolvePackageDir(__vite_injected_original_import_meta_url), { - includeNodeBuiltins: true -}); -var vite_config_default = defineConfig(({ mode }) => { - const proofOnly = mode === "proof-only"; - return { - build: { - outDir: "dist", - target: "node20", - sourcemap: true, - minify: false, - rollupOptions: { - preserveEntrySignatures: "strict", - input: proofOnly ? { - proof: resolve2(configDir, "src/proof.ts"), - crypto: resolve2(configDir, "src/crypto.ts") - } : { - cli: resolve2(configDir, "src/cli.ts"), - index: resolve2(configDir, "src/index.ts"), - proof: resolve2(configDir, "src/proof.ts"), - artifact: resolve2(configDir, "src/artifact.ts"), - manifest: resolve2(configDir, "src/manifest.ts"), - crypto: resolve2(configDir, "src/crypto.ts"), - errors: resolve2(configDir, "src/errors.ts") - }, - external, - output: { - format: "es", - entryFileNames: "[name].js", - chunkFileNames: "chunks/[name]-[hash].js" - } - } - }, - test: { - environment: "node", - alias: { - "@ternent/armour": resolve2(configDir, "../armour/src/index.ts"), - "@ternent/identity": resolve2(configDir, "../identity-v2/src/index.ts"), - "@ternent/rage": resolve2(configDir, "../rage/src/index.ts"), - "ternent-utils": resolve2(configDir, "../utils/src/index.ts") - } - } - }; -}); -export { - vite_config_default as default -}; -//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiLCAiLi4vLi4vc2NyaXB0cy92aXRlL3BhY2thZ2UtbGliLWNvbmZpZy50cyJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiY29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2Rpcm5hbWUgPSBcIi9Vc2Vycy9zYW0vZGV2L3Rlcm5lbnQvY29yZS9wYWNrYWdlcy9zZWFsXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ZpbGVuYW1lID0gXCIvVXNlcnMvc2FtL2Rldi90ZXJuZW50L2NvcmUvcGFja2FnZXMvc2VhbC92aXRlLmNvbmZpZy50c1wiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9pbXBvcnRfbWV0YV91cmwgPSBcImZpbGU6Ly8vVXNlcnMvc2FtL2Rldi90ZXJuZW50L2NvcmUvcGFja2FnZXMvc2VhbC92aXRlLmNvbmZpZy50c1wiO2ltcG9ydCB7IGRpcm5hbWUsIHJlc29sdmUgfSBmcm9tIFwibm9kZTpwYXRoXCI7XG5pbXBvcnQgeyBmaWxlVVJMVG9QYXRoIH0gZnJvbSBcIm5vZGU6dXJsXCI7XG5pbXBvcnQgeyBkZWZpbmVDb25maWcgfSBmcm9tIFwidml0ZVwiO1xuaW1wb3J0IHsgY3JlYXRlUGFja2FnZUV4dGVybmFsLCByZXNvbHZlUGFja2FnZURpciB9IGZyb20gXCIuLi8uLi9zY3JpcHRzL3ZpdGUvcGFja2FnZS1saWItY29uZmlnXCI7XG5cbmNvbnN0IGNvbmZpZ0RpciA9IGRpcm5hbWUoZmlsZVVSTFRvUGF0aChpbXBvcnQubWV0YS51cmwpKTtcbmNvbnN0IGV4dGVybmFsID0gY3JlYXRlUGFja2FnZUV4dGVybmFsKHJlc29sdmVQYWNrYWdlRGlyKGltcG9ydC5tZXRhLnVybCksIHtcbiAgaW5jbHVkZU5vZGVCdWlsdGluczogdHJ1ZSxcbn0pO1xuXG5leHBvcnQgZGVmYXVsdCBkZWZpbmVDb25maWcoKHsgbW9kZSB9KSA9PiB7XG4gIGNvbnN0IHByb29mT25seSA9IG1vZGUgPT09IFwicHJvb2Ytb25seVwiO1xuXG4gIHJldHVybiB7XG4gICAgYnVpbGQ6IHtcbiAgICAgIG91dERpcjogXCJkaXN0XCIsXG4gICAgICB0YXJnZXQ6IFwibm9kZTIwXCIsXG4gICAgICBzb3VyY2VtYXA6IHRydWUsXG4gICAgICBtaW5pZnk6IGZhbHNlLFxuICAgICAgcm9sbHVwT3B0aW9uczoge1xuICAgICAgICBwcmVzZXJ2ZUVudHJ5U2lnbmF0dXJlczogXCJzdHJpY3RcIixcbiAgICAgICAgaW5wdXQ6IHByb29mT25seVxuICAgICAgICAgID8ge1xuICAgICAgICAgICAgICBwcm9vZjogcmVzb2x2ZShjb25maWdEaXIsIFwic3JjL3Byb29mLnRzXCIpLFxuICAgICAgICAgICAgICBjcnlwdG86IHJlc29sdmUoY29uZmlnRGlyLCBcInNyYy9jcnlwdG8udHNcIiksXG4gICAgICAgICAgICB9XG4gICAgICAgICAgOiB7XG4gICAgICAgICAgICAgIGNsaTogcmVzb2x2ZShjb25maWdEaXIsIFwic3JjL2NsaS50c1wiKSxcbiAgICAgICAgICAgICAgaW5kZXg6IHJlc29sdmUoY29uZmlnRGlyLCBcInNyYy9pbmRleC50c1wiKSxcbiAgICAgICAgICAgICAgcHJvb2Y6IHJlc29sdmUoY29uZmlnRGlyLCBcInNyYy9wcm9vZi50c1wiKSxcbiAgICAgICAgICAgICAgYXJ0aWZhY3Q6IHJlc29sdmUoY29uZmlnRGlyLCBcInNyYy9hcnRpZmFjdC50c1wiKSxcbiAgICAgICAgICAgICAgbWFuaWZlc3Q6IHJlc29sdmUoY29uZmlnRGlyLCBcInNyYy9tYW5pZmVzdC50c1wiKSxcbiAgICAgICAgICAgICAgY3J5cHRvOiByZXNvbHZlKGNvbmZpZ0RpciwgXCJzcmMvY3J5cHRvLnRzXCIpLFxuICAgICAgICAgICAgICBlcnJvcnM6IHJlc29sdmUoY29uZmlnRGlyLCBcInNyYy9lcnJvcnMudHNcIiksXG4gICAgICAgICAgICB9LFxuICAgICAgICBleHRlcm5hbCxcbiAgICAgICAgb3V0cHV0OiB7XG4gICAgICAgICAgZm9ybWF0OiBcImVzXCIsXG4gICAgICAgICAgZW50cnlGaWxlTmFtZXM6IFwiW25hbWVdLmpzXCIsXG4gICAgICAgICAgY2h1bmtGaWxlTmFtZXM6IFwiY2h1bmtzL1tuYW1lXS1baGFzaF0uanNcIixcbiAgICAgICAgfSxcbiAgICAgIH0sXG4gICAgfSxcbiAgICB0ZXN0OiB7XG4gICAgICBlbnZpcm9ubWVudDogXCJub2RlXCIsXG4gICAgICBhbGlhczoge1xuICAgICAgICBcIkB0ZXJuZW50L2FybW91clwiOiByZXNvbHZlKGNvbmZpZ0RpciwgXCIuLi9hcm1vdXIvc3JjL2luZGV4LnRzXCIpLFxuICAgICAgICBcIkB0ZXJuZW50L2lkZW50aXR5XCI6IHJlc29sdmUoY29uZmlnRGlyLCBcIi4uL2lkZW50aXR5LXYyL3NyYy9pbmRleC50c1wiKSxcbiAgICAgICAgXCJAdGVybmVudC9yYWdlXCI6IHJlc29sdmUoY29uZmlnRGlyLCBcIi4uL3JhZ2Uvc3JjL2luZGV4LnRzXCIpLFxuICAgICAgICBcInRlcm5lbnQtdXRpbHNcIjogcmVzb2x2ZShjb25maWdEaXIsIFwiLi4vdXRpbHMvc3JjL2luZGV4LnRzXCIpLFxuICAgICAgfSxcbiAgICB9LFxuICB9O1xufSk7XG4iLCAiY29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2Rpcm5hbWUgPSBcIi9Vc2Vycy9zYW0vZGV2L3Rlcm5lbnQvY29yZS9zY3JpcHRzL3ZpdGVcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfZmlsZW5hbWUgPSBcIi9Vc2Vycy9zYW0vZGV2L3Rlcm5lbnQvY29yZS9zY3JpcHRzL3ZpdGUvcGFja2FnZS1saWItY29uZmlnLnRzXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ltcG9ydF9tZXRhX3VybCA9IFwiZmlsZTovLy9Vc2Vycy9zYW0vZGV2L3Rlcm5lbnQvY29yZS9zY3JpcHRzL3ZpdGUvcGFja2FnZS1saWItY29uZmlnLnRzXCI7aW1wb3J0IHsgYnVpbHRpbk1vZHVsZXMgfSBmcm9tIFwibm9kZTptb2R1bGVcIjtcbmltcG9ydCB7IHJlYWRGaWxlU3luYyB9IGZyb20gXCJub2RlOmZzXCI7XG5pbXBvcnQgeyBkaXJuYW1lLCByZXNvbHZlIH0gZnJvbSBcIm5vZGU6cGF0aFwiO1xuaW1wb3J0IHsgZmlsZVVSTFRvUGF0aCB9IGZyb20gXCJub2RlOnVybFwiO1xuXG50eXBlIFBhY2thZ2VKc29uU2hhcGUgPSB7XG4gIGRlcGVuZGVuY2llcz86IFJlY29yZDxzdHJpbmcsIHN0cmluZz47XG4gIHBlZXJEZXBlbmRlbmNpZXM/OiBSZWNvcmQ8c3RyaW5nLCBzdHJpbmc+O1xuICBvcHRpb25hbERlcGVuZGVuY2llcz86IFJlY29yZDxzdHJpbmcsIHN0cmluZz47XG59O1xuXG5mdW5jdGlvbiBsb2FkUGFja2FnZUpzb24ocGFja2FnZURpcjogc3RyaW5nKTogUGFja2FnZUpzb25TaGFwZSB7XG4gIGNvbnN0IHBhY2thZ2VKc29uUGF0aCA9IHJlc29sdmUocGFja2FnZURpciwgXCJwYWNrYWdlLmpzb25cIik7XG4gIHJldHVybiBKU09OLnBhcnNlKHJlYWRGaWxlU3luYyhwYWNrYWdlSnNvblBhdGgsIFwidXRmOFwiKSkgYXMgUGFja2FnZUpzb25TaGFwZTtcbn1cblxuZnVuY3Rpb24gY3JlYXRlUGFja2FnZU5hbWVzKHBhY2thZ2VKc29uOiBQYWNrYWdlSnNvblNoYXBlKSB7XG4gIHJldHVybiBuZXcgU2V0KFtcbiAgICAuLi5PYmplY3Qua2V5cyhwYWNrYWdlSnNvbi5kZXBlbmRlbmNpZXMgfHwge30pLFxuICAgIC4uLk9iamVjdC5rZXlzKHBhY2thZ2VKc29uLnBlZXJEZXBlbmRlbmNpZXMgfHwge30pLFxuICAgIC4uLk9iamVjdC5rZXlzKHBhY2thZ2VKc29uLm9wdGlvbmFsRGVwZW5kZW5jaWVzIHx8IHt9KSxcbiAgXSk7XG59XG5cbmZ1bmN0aW9uIGlzRXh0ZXJuYWxJZChpZDogc3RyaW5nLCBwYWNrYWdlTmFtZXM6IFNldDxzdHJpbmc+LCBpbmNsdWRlTm9kZUJ1aWx0aW5zOiBib29sZWFuKSB7XG4gIGlmIChpbmNsdWRlTm9kZUJ1aWx0aW5zKSB7XG4gICAgaWYgKGJ1aWx0aW5Nb2R1bGVzLmluY2x1ZGVzKGlkKSB8fCBidWlsdGluTW9kdWxlcy5pbmNsdWRlcyhpZC5yZXBsYWNlKC9ebm9kZTovLCBcIlwiKSkpIHtcbiAgICAgIHJldHVybiB0cnVlO1xuICAgIH1cbiAgICBpZiAoaWQuc3RhcnRzV2l0aChcIm5vZGU6XCIpKSB7XG4gICAgICByZXR1cm4gdHJ1ZTtcbiAgICB9XG4gIH1cblxuICBmb3IgKGNvbnN0IHBhY2thZ2VOYW1lIG9mIHBhY2thZ2VOYW1lcykge1xuICAgIGlmIChpZCA9PT0gcGFja2FnZU5hbWUgfHwgaWQuc3RhcnRzV2l0aChgJHtwYWNrYWdlTmFtZX0vYCkpIHtcbiAgICAgIHJldHVybiB0cnVlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiBmYWxzZTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGNyZWF0ZVBhY2thZ2VFeHRlcm5hbChcbiAgcGFja2FnZURpcjogc3RyaW5nLFxuICBvcHRpb25zOiB7IGluY2x1ZGVOb2RlQnVpbHRpbnM/OiBib29sZWFuIH0gPSB7fSxcbikge1xuICBjb25zdCBwYWNrYWdlSnNvbiA9IGxvYWRQYWNrYWdlSnNvbihwYWNrYWdlRGlyKTtcbiAgY29uc3QgcGFja2FnZU5hbWVzID0gY3JlYXRlUGFja2FnZU5hbWVzKHBhY2thZ2VKc29uKTtcbiAgY29uc3QgaW5jbHVkZU5vZGVCdWlsdGlucyA9IG9wdGlvbnMuaW5jbHVkZU5vZGVCdWlsdGlucyA9PT0gdHJ1ZTtcblxuICByZXR1cm4gZnVuY3Rpb24gZXh0ZXJuYWwoaWQ6IHN0cmluZykge1xuICAgIHJldHVybiBpc0V4dGVybmFsSWQoaWQsIHBhY2thZ2VOYW1lcywgaW5jbHVkZU5vZGVCdWlsdGlucyk7XG4gIH07XG59XG5cbmV4cG9ydCBmdW5jdGlvbiByZXNvbHZlUGFja2FnZURpcihtZXRhVXJsOiBzdHJpbmcpIHtcbiAgcmV0dXJuIGRpcm5hbWUoZmlsZVVSTFRvUGF0aChtZXRhVXJsKSk7XG59XG4iXSwKICAibWFwcGluZ3MiOiAiO0FBQTZTLFNBQVMsV0FBQUEsVUFBUyxXQUFBQyxnQkFBZTtBQUM5VSxTQUFTLGlCQUFBQyxzQkFBcUI7QUFDOUIsU0FBUyxvQkFBb0I7OztBQ0YyUixTQUFTLHNCQUFzQjtBQUN2VixTQUFTLG9CQUFvQjtBQUM3QixTQUFTLFNBQVMsZUFBZTtBQUNqQyxTQUFTLHFCQUFxQjtBQVE5QixTQUFTLGdCQUFnQixZQUFzQztBQUM3RCxRQUFNLGtCQUFrQixRQUFRLFlBQVksY0FBYztBQUMxRCxTQUFPLEtBQUssTUFBTSxhQUFhLGlCQUFpQixNQUFNLENBQUM7QUFDekQ7QUFFQSxTQUFTLG1CQUFtQixhQUErQjtBQUN6RCxTQUFPLG9CQUFJLElBQUk7QUFBQSxJQUNiLEdBQUcsT0FBTyxLQUFLLFlBQVksZ0JBQWdCLENBQUMsQ0FBQztBQUFBLElBQzdDLEdBQUcsT0FBTyxLQUFLLFlBQVksb0JBQW9CLENBQUMsQ0FBQztBQUFBLElBQ2pELEdBQUcsT0FBTyxLQUFLLFlBQVksd0JBQXdCLENBQUMsQ0FBQztBQUFBLEVBQ3ZELENBQUM7QUFDSDtBQUVBLFNBQVMsYUFBYSxJQUFZLGNBQTJCLHFCQUE4QjtBQUN6RixNQUFJLHFCQUFxQjtBQUN2QixRQUFJLGVBQWUsU0FBUyxFQUFFLEtBQUssZUFBZSxTQUFTLEdBQUcsUUFBUSxVQUFVLEVBQUUsQ0FBQyxHQUFHO0FBQ3BGLGFBQU87QUFBQSxJQUNUO0FBQ0EsUUFBSSxHQUFHLFdBQVcsT0FBTyxHQUFHO0FBQzFCLGFBQU87QUFBQSxJQUNUO0FBQUEsRUFDRjtBQUVBLGFBQVcsZUFBZSxjQUFjO0FBQ3RDLFFBQUksT0FBTyxlQUFlLEdBQUcsV0FBVyxHQUFHLFdBQVcsR0FBRyxHQUFHO0FBQzFELGFBQU87QUFBQSxJQUNUO0FBQUEsRUFDRjtBQUVBLFNBQU87QUFDVDtBQUVPLFNBQVMsc0JBQ2QsWUFDQSxVQUE2QyxDQUFDLEdBQzlDO0FBQ0EsUUFBTSxjQUFjLGdCQUFnQixVQUFVO0FBQzlDLFFBQU0sZUFBZSxtQkFBbUIsV0FBVztBQUNuRCxRQUFNLHNCQUFzQixRQUFRLHdCQUF3QjtBQUU1RCxTQUFPLFNBQVNDLFVBQVMsSUFBWTtBQUNuQyxXQUFPLGFBQWEsSUFBSSxjQUFjLG1CQUFtQjtBQUFBLEVBQzNEO0FBQ0Y7QUFFTyxTQUFTLGtCQUFrQixTQUFpQjtBQUNqRCxTQUFPLFFBQVEsY0FBYyxPQUFPLENBQUM7QUFDdkM7OztBRDFEMEwsSUFBTSwyQ0FBMkM7QUFLM08sSUFBTSxZQUFZQyxTQUFRQyxlQUFjLHdDQUFlLENBQUM7QUFDeEQsSUFBTSxXQUFXLHNCQUFzQixrQkFBa0Isd0NBQWUsR0FBRztBQUFBLEVBQ3pFLHFCQUFxQjtBQUN2QixDQUFDO0FBRUQsSUFBTyxzQkFBUSxhQUFhLENBQUMsRUFBRSxLQUFLLE1BQU07QUFDeEMsUUFBTSxZQUFZLFNBQVM7QUFFM0IsU0FBTztBQUFBLElBQ0wsT0FBTztBQUFBLE1BQ0wsUUFBUTtBQUFBLE1BQ1IsUUFBUTtBQUFBLE1BQ1IsV0FBVztBQUFBLE1BQ1gsUUFBUTtBQUFBLE1BQ1IsZUFBZTtBQUFBLFFBQ2IseUJBQXlCO0FBQUEsUUFDekIsT0FBTyxZQUNIO0FBQUEsVUFDRSxPQUFPQyxTQUFRLFdBQVcsY0FBYztBQUFBLFVBQ3hDLFFBQVFBLFNBQVEsV0FBVyxlQUFlO0FBQUEsUUFDNUMsSUFDQTtBQUFBLFVBQ0UsS0FBS0EsU0FBUSxXQUFXLFlBQVk7QUFBQSxVQUNwQyxPQUFPQSxTQUFRLFdBQVcsY0FBYztBQUFBLFVBQ3hDLE9BQU9BLFNBQVEsV0FBVyxjQUFjO0FBQUEsVUFDeEMsVUFBVUEsU0FBUSxXQUFXLGlCQUFpQjtBQUFBLFVBQzlDLFVBQVVBLFNBQVEsV0FBVyxpQkFBaUI7QUFBQSxVQUM5QyxRQUFRQSxTQUFRLFdBQVcsZUFBZTtBQUFBLFVBQzFDLFFBQVFBLFNBQVEsV0FBVyxlQUFlO0FBQUEsUUFDNUM7QUFBQSxRQUNKO0FBQUEsUUFDQSxRQUFRO0FBQUEsVUFDTixRQUFRO0FBQUEsVUFDUixnQkFBZ0I7QUFBQSxVQUNoQixnQkFBZ0I7QUFBQSxRQUNsQjtBQUFBLE1BQ0Y7QUFBQSxJQUNGO0FBQUEsSUFDQSxNQUFNO0FBQUEsTUFDSixhQUFhO0FBQUEsTUFDYixPQUFPO0FBQUEsUUFDTCxtQkFBbUJBLFNBQVEsV0FBVyx3QkFBd0I7QUFBQSxRQUM5RCxxQkFBcUJBLFNBQVEsV0FBVyw2QkFBNkI7QUFBQSxRQUNyRSxpQkFBaUJBLFNBQVEsV0FBVyxzQkFBc0I7QUFBQSxRQUMxRCxpQkFBaUJBLFNBQVEsV0FBVyx1QkFBdUI7QUFBQSxNQUM3RDtBQUFBLElBQ0Y7QUFBQSxFQUNGO0FBQ0YsQ0FBQzsiLAogICJuYW1lcyI6IFsiZGlybmFtZSIsICJyZXNvbHZlIiwgImZpbGVVUkxUb1BhdGgiLCAiZXh0ZXJuYWwiLCAiZGlybmFtZSIsICJmaWxlVVJMVG9QYXRoIiwgInJlc29sdmUiXQp9Cg== From 872109cabbf190cc9bca1966ce521d7b428b0a27 Mon Sep 17 00:00:00 2001 From: samternent Date: Fri, 27 Nov 2026 23:32:27 +0000 Subject: [PATCH 04/24] docs(identity, seal): restore agent guides and add package working notes Each package ships an llms.txt for developers whose agents use it, linked from its README and the root guide. A CLAUDE.md for each package records what it owns and the rules that keep it small. Co-Authored-By: Claude Opus 5.5 --- llms.txt | 4 ++-- packages/identity/CLAUDE.md | 32 ++++++++++++++++++++++++++++ packages/identity/README.md | 2 ++ packages/identity/llms.txt | 38 ++++++++++++++++++++++++++++++++++ packages/identity/package.json | 3 ++- packages/seal/CLAUDE.md | 34 ++++++++++++++++++++++++++++++ packages/seal/README.md | 2 ++ packages/seal/llms.txt | 27 ++++++++++++++++++++++++ packages/seal/package.json | 3 ++- 9 files changed, 141 insertions(+), 4 deletions(-) create mode 100644 packages/identity/CLAUDE.md create mode 100644 packages/identity/llms.txt create mode 100644 packages/seal/CLAUDE.md create mode 100644 packages/seal/llms.txt diff --git a/llms.txt b/llms.txt index ecf7241..acb34d5 100644 --- a/llms.txt +++ b/llms.txt @@ -7,9 +7,9 @@ - [Concord](packages/concord/llms.txt): build an application using typed commands, events, authority, private groups and replay. - [Ledger](packages/ledger/llms.txt): build a standalone signed log without Concord application or permission semantics. -- [Identity](packages/identity/llms.txt): generate/import identities, sign bytes and derive public encryption recipients. +- [Identity](packages/identity/llms.txt): create, back up, restore or recover one identity; sign and verify bytes. - [Armour](packages/armour/llms.txt): encrypt/decrypt with age; compose identity capabilities and explicit Ledger payload codecs. -- [Seal](packages/seal/llms.txt): sign/verify file proofs, manifests and encrypted artifacts; use the Node CLI. +- [Seal](packages/seal/llms.txt): sign and verify a detached proof over any bytes' hash; use the Node CLI. The active libraries are exactly the five above. Workspace and UI are outside this release, and Utils and separate Seal CLI packages are retired. Use the published diff --git a/packages/identity/CLAUDE.md b/packages/identity/CLAUDE.md new file mode 100644 index 0000000..d242d2d --- /dev/null +++ b/packages/identity/CLAUDE.md @@ -0,0 +1,32 @@ +# Working on Identity + +Identity is one file, `src/index.ts`: six functions that produce or check one +`Identity`. Ledger, Seal and Armour take that object directly. Keep it that small. + +## What Identity owns + +- Key creation, the `ternent-identity` version 2 backup, BIP-39 recovery at SLIP-0010 + path `m/101010'/25519'/0'`, exact-byte signing and strict verification. +- The `PublicIdentity` shape and its `id` binding. +- Not protocol messages. Seal and Ledger build their own domain-separated bytes and + call `sign` on them. Not age encoding either: Armour derives recipients itself. + +## How the code stays small + +- Use Noble and Scure for every primitive and encoding. Don't write a Base64, hex or + Bech32 routine, and don't wrap a library call that already fails clearly. +- Noble's `zip215: false` verification rejects non-canonical encodings, `S` outside + the group order and small-order keys. The code adds only what Noble doesn't do: + rejecting mixed-order keys and small- or mixed-order `R`. +- Validate where data enters (`restoreIdentity`, `validatePublicIdentity`, `verify`), + then trust the values you built. Seeds produced inside the package aren't re-checked. +- The private seed leaves only through `export()`. `withX25519Secret` lends a derived + secret and zeroes it when the callback settles, including on failure. +- `sign` runs before its first `await`, which captures the caller's bytes. + +## Checks + +Run `pnpm run check` in this package under the Node version in `.node-version`. +`test/vectors.json` holds existing backups, signatures and derivations; changing a +result there breaks every stored identity. Update `README.md` and `llms.txt` with any +interface change. diff --git a/packages/identity/README.md b/packages/identity/README.md index e23bc53..d64abb8 100644 --- a/packages/identity/README.md +++ b/packages/identity/README.md @@ -1,5 +1,7 @@ # @ternent/identity +[Agent interface guide](llms.txt): public imports, examples and contracts. + One Ed25519 identity for the Ternent libraries. Create or restore it once and pass it to Ledger, Seal and Armour; no consumer handles the seed. diff --git a/packages/identity/llms.txt b/packages/identity/llms.txt new file mode 100644 index 0000000..7c7a178 --- /dev/null +++ b/packages/identity/llms.txt @@ -0,0 +1,38 @@ +# @ternent/identity + +> One Ed25519 identity: create, back up, restore, recover from words, sign and verify. + +All exports come from the package root. Declarations: `dist/index.d.ts`. +[Public README](https://github.com/ternent/core/blob/main/packages/identity/README.md). + +```ts +import { + createIdentity, + restoreIdentity, + createMnemonicIdentity, + recoverIdentity, + verify, + validatePublicIdentity, + type Identity, + type PublicIdentity, +} from "@ternent/identity"; + +const identity = await createIdentity(); +const backup = identity.export(); // JSON with the private seed; the app stores it +const restored = await restoreIdentity(backup); +const signature = await identity.sign(bytes); // 64 bytes over exactly `bytes` +const ok = await verify(identity.publicIdentity, bytes, signature); +``` + +- Pass the `Identity` itself to Ledger, Seal and Armour. Do not decode the seed or + build a second signer. +- `PublicIdentity` is `{ version: 1, algorithm: "Ed25519", publicKey, id }` with a + base64url key and `id = "identity:" + hex(sha256(publicKey))`. It is safe to put + in documents. Check untrusted values with `validatePublicIdentity` (throws). +- `verify` never throws; it returns `false` for a bad identity, signature or match. +- `restoreIdentity`, `recoverIdentity` and `createMnemonicIdentity` reject with an + ordinary `Error` on invalid input. +- `withX25519Secret(use)` lends a temporary X25519 secret for decryption and zeroes + it after `use` settles. Do not retain it. +- Recovery words are opt-in, shown once, and never part of the backup. +- Encryption, storage, accounts and two-factor checks belong to the application. diff --git a/packages/identity/package.json b/packages/identity/package.json index d05c7c7..80967ee 100644 --- a/packages/identity/package.json +++ b/packages/identity/package.json @@ -10,7 +10,8 @@ }, "files": [ "dist", - "README.md" + "README.md", + "llms.txt" ], "type": "module", "sideEffects": false, diff --git a/packages/seal/CLAUDE.md b/packages/seal/CLAUDE.md new file mode 100644 index 0000000..37b0273 --- /dev/null +++ b/packages/seal/CLAUDE.md @@ -0,0 +1,34 @@ +# Working on Seal + +Seal is three functions and a two-command CLI. `src/index.ts` is the library and must +stay browser-safe; `src/cli.ts` is the only Node code. Keep it that small. + +## What Seal owns + +- The proof format and its signing message: `ternent-seal/v1`, a zero byte, then the + unsigned proof as JSON with keys in UTF-16 order. `test/vectors.json` fixes those + bytes. A change to them is a new format version, never an edit to the vectors. +- Nothing else. Identity owns keys, signing and strict verification. Trust in a signer + is the caller's decision. Encryption, manifests and file sets belong to callers, + who seal the bytes they produce. + +## How the code stays small + +- Validate untrusted input once, where it enters: `readProof` for proofs, Identity's + `verify` for signatures. Don't re-check values that already passed. +- Use the dependencies' own checks. Noble's strict mode and Identity's validation + already reject bad points, scalars and encodings; Scure's base64url rejects + non-canonical text. +- Read every input field synchronously, before the first `await`, so a caller can't + change it mid-operation. Pass the signer a copy of the message and check its + signature against the original. +- `verifySealProof` never throws. It reports `signatureValid` and `hashMatch` + separately, and the hash check stands even when the proof's signer is malformed. +- No error classes, result wrappers, subpath exports or option objects without a + caller that needs them. A new export needs a consumer example first. + +## Checks + +Run `pnpm run check` in this package under the Node version in `.node-version`. Test +the observable contract: the fixed vectors, tampering with each signed field, malformed +proofs and call-time capture. Update `README.md` and `llms.txt` with any interface change. diff --git a/packages/seal/README.md b/packages/seal/README.md index 789be2a..3af290e 100644 --- a/packages/seal/README.md +++ b/packages/seal/README.md @@ -1,5 +1,7 @@ # @ternent/seal +[Agent interface guide](llms.txt): public imports, examples and contracts. + A detached Ed25519 proof over a content hash. Identity supplies the signer. ```ts diff --git a/packages/seal/llms.txt b/packages/seal/llms.txt new file mode 100644 index 0000000..94a6a6a --- /dev/null +++ b/packages/seal/llms.txt @@ -0,0 +1,27 @@ +# @ternent/seal + +> Detached Ed25519 proofs over SHA-256 content hashes, plus a `seal` CLI. + +Three exports from the package root: `createSealHash`, `createSealProof`, `verifySealProof`. +Types: `SealProof`, `SealHash`, `SealVerification`. Declarations: `dist/index.d.ts`. + +```ts +import { createIdentity } from "@ternent/identity"; +import { createSealHash, createSealProof, verifySealProof } from "@ternent/seal"; + +const identity = await createIdentity(); +const proof = await createSealProof({ + signer: identity, // any { publicIdentity, sign } from @ternent/identity + subject: { hash: await createSealHash(bytes) }, +}); +const { valid } = await verifySealProof(proof, bytes); +if (!valid || proof.signer.id !== trustedPublisher.id) throw new Error("Untrusted"); +``` + +- `verifySealProof` never throws; malformed proofs return `valid: false`. +- `signatureValid` and `hashMatch` are reported separately; `valid` needs both. +- Seal does not decide trust. Pin the expected signer yourself. +- Seal has no recipients or encryption. To prove encrypted data, seal its ciphertext bytes. +- To prove several files, seal a manifest of their hashes and check each file yourself. +- CLI: `seal sign --input [--out ]` with `SEAL_IDENTITY_FILE` set; + `seal verify --proof --input `. Exit 0 ok, 1 error, 2 invalid proof. diff --git a/packages/seal/package.json b/packages/seal/package.json index a59f5b8..e3d449f 100644 --- a/packages/seal/package.json +++ b/packages/seal/package.json @@ -25,7 +25,8 @@ "files": [ "bin", "dist", - "README.md" + "README.md", + "llms.txt" ], "type": "module", "sideEffects": false, From 5db3bbbf87de2692203bb464efd1b6d08d303c5a Mon Sep 17 00:00:00 2001 From: samternent Date: Fri, 27 Nov 2026 23:37:58 +0000 Subject: [PATCH 05/24] feat(armour)!: rewrite as encrypt and decrypt over bytes Replace the text, file, codec, capability and error APIs with two functions. encrypt takes public identities and native X25519 age recipients, or a passphrase; decrypt takes an Identity, a native age secret key, or a passphrase. Both return binary age through one age Encrypter or Decrypter. Saved native-age vectors move into the package, and the tests check interop with the age CLI in both directions and scrypt work-factor rejection. Consumers are not yet adapted. Co-Authored-By: Claude Opus 5.5 --- llms.txt | 2 +- packages/armour/CHANGELOG.md | 116 --------- packages/armour/CLAUDE.md | 39 ++- packages/armour/README.md | 89 ++----- packages/armour/SPEC.md | 14 -- packages/armour/llms.txt | 69 ++---- packages/armour/package.json | 4 +- packages/armour/src/age.ts | 74 ------ packages/armour/src/codec.ts | 80 ------ packages/armour/src/constants.ts | 5 - packages/armour/src/engine.ts | 86 ------- packages/armour/src/errors.ts | 147 ----------- packages/armour/src/files.ts | 73 ------ packages/armour/src/identity.ts | 62 ----- packages/armour/src/index.ts | 141 ++++++----- packages/armour/src/passphrase.ts | 33 --- packages/armour/src/recipients.ts | 73 ------ packages/armour/src/text.ts | 68 ------ packages/armour/src/types.ts | 92 ------- packages/armour/test/age.test.ts | 109 --------- packages/armour/test/armour.test.ts | 367 ++++++++++------------------ packages/armour/test/codec.test.ts | 50 ---- packages/armour/test/vectors.json | 26 ++ pnpm-lock.yaml | 6 + 24 files changed, 324 insertions(+), 1501 deletions(-) delete mode 100644 packages/armour/CHANGELOG.md delete mode 100644 packages/armour/SPEC.md delete mode 100644 packages/armour/src/age.ts delete mode 100644 packages/armour/src/codec.ts delete mode 100644 packages/armour/src/constants.ts delete mode 100644 packages/armour/src/engine.ts delete mode 100644 packages/armour/src/errors.ts delete mode 100644 packages/armour/src/files.ts delete mode 100644 packages/armour/src/identity.ts delete mode 100644 packages/armour/src/passphrase.ts delete mode 100644 packages/armour/src/recipients.ts delete mode 100644 packages/armour/src/text.ts delete mode 100644 packages/armour/src/types.ts delete mode 100644 packages/armour/test/age.test.ts delete mode 100644 packages/armour/test/codec.test.ts create mode 100644 packages/armour/test/vectors.json diff --git a/llms.txt b/llms.txt index acb34d5..4386e36 100644 --- a/llms.txt +++ b/llms.txt @@ -8,7 +8,7 @@ - [Concord](packages/concord/llms.txt): build an application using typed commands, events, authority, private groups and replay. - [Ledger](packages/ledger/llms.txt): build a standalone signed log without Concord application or permission semantics. - [Identity](packages/identity/llms.txt): create, back up, restore or recover one identity; sign and verify bytes. -- [Armour](packages/armour/llms.txt): encrypt/decrypt with age; compose identity capabilities and explicit Ledger payload codecs. +- [Armour](packages/armour/llms.txt): encrypt and decrypt bytes with age for identities, groups and passphrases. - [Seal](packages/seal/llms.txt): sign and verify a detached proof over any bytes' hash; use the Node CLI. The active libraries are exactly the five above. Workspace and UI are outside this diff --git a/packages/armour/CHANGELOG.md b/packages/armour/CHANGELOG.md deleted file mode 100644 index b84060b..0000000 --- a/packages/armour/CHANGELOG.md +++ /dev/null @@ -1,116 +0,0 @@ -# @ternent/armour - -## 0.3.0 - -### Minor Changes - -- e5c6808: Establish the five-library alpha: standalone Identity, Armour, Ledger and Seal, - with Concord composing Ledger's common signed container, authority, independent - encrypted groups, command drafts and application replay. The common container - deliberately replaces the previous Concord alpha wire format. - - Armour uses typage and offers explicit payload codecs for Ledger. Uncommitted - entries and command intents stay in memory; consumers own draft recovery and - storage publication. Verify public imports, declarations, CLI behavior and exact - candidate bytes before publication. - -### Patch Changes - -- 7d55bda: Include agent interface guides with public imports, runnable examples, lifecycle and - error contracts, and host-owned storage/recovery behavior. -- Updated dependencies [7d55bda] -- Updated dependencies [e5c6808] - - @ternent/identity@0.6.0 - -## 0.3.0-alpha.1 - -### Minor Changes - -- e5c6808: Establish the five-library alpha: standalone Identity, Armour, Ledger and Seal, - with Concord composing Ledger's common signed container, authority, independent - encrypted groups, command drafts and application replay. The common container - deliberately replaces the previous Concord alpha wire format. - - Armour uses typage and offers explicit payload codecs for Ledger. Uncommitted - entries and command intents stay in memory; consumers own draft recovery and - storage publication. Verify public imports, declarations, CLI behavior and exact - candidate bytes before publication. - -### Patch Changes - -- Updated dependencies [e5c6808] - - @ternent/identity@0.6.0-alpha.1 - -## 0.2.4 - -### Patch Changes - -- [`4aa5e00`](https://github.com/ternent/core/commit/4aa5e001cecf61cb702414be2e63209002a521ca) Thanks [@samternent](https://github.com/samternent)! - Update deploys - -- Updated dependencies [[`4aa5e00`](https://github.com/ternent/core/commit/4aa5e001cecf61cb702414be2e63209002a521ca)]: - - @ternent/identity@0.5.1 - -## 0.2.3 - -### Patch Changes - -- [`4c4a1c8`](https://github.com/ternent/core/commit/4c4a1c83f1f8d0ebe354f0589159ba84d60ab8f3) Thanks [@samternent](https://github.com/samternent)! - Adds armour workflow - -## 0.2.2 - -### Patch Changes - -- [`e6f7d70`](https://github.com/ternent/core/commit/e6f7d70e7d94bf7d6e6730c228f3f06c250da621) Thanks [@samternent](https://github.com/samternent)! - Publuish armour - -## 0.2.1 - -### Patch Changes - -- [`c674665`](https://github.com/ternent/core/commit/c674665919ba0d610b77938c728c75265b343c41) Thanks [@samternent](https://github.com/samternent)! - publish armour - -## 0.2.0 - -### Minor Changes - -- [`a73a962`](https://github.com/ternent/core/commit/a73a962540b89985ed5227e3b39742432fbc965e) Thanks [@samternent](https://github.com/samternent)! - Move armour to org - -- [`89ed4d7`](https://github.com/ternent/core/commit/89ed4d73d016d1d3b7b2905298cf22977b7f26be) Thanks [@samternent](https://github.com/samternent)! - fix package formats - -### Patch Changes - -- Updated dependencies [[`89ed4d7`](https://github.com/ternent/core/commit/89ed4d73d016d1d3b7b2905298cf22977b7f26be)]: - - @ternent/identity@0.5.0 - -## 0.1.5 - -### Patch Changes - -- [`cb63d9c1dc91e0cd3924bafd5abcde89cc02992f`](https://github.com/samternent/home/commit/cb63d9c1dc91e0cd3924bafd5abcde89cc02992f) Thanks [@samternent](https://github.com/samternent)! - Fix workflows - -- Updated dependencies [[`cb63d9c1dc91e0cd3924bafd5abcde89cc02992f`](https://github.com/samternent/home/commit/cb63d9c1dc91e0cd3924bafd5abcde89cc02992f)]: - - @ternent/identity@0.3.1 - - @ternent/rage@0.1.3 - -## 0.1.4 - -### Patch Changes - -- [`acf974919a1176da235e7ec7468c46df8bc13402`](https://github.com/samternent/home/commit/acf974919a1176da235e7ec7468c46df8bc13402) Thanks [@samternent](https://github.com/samternent)! - Update build configs - -## 0.1.3 - -### Patch Changes - -- [`109f8c3989b16a161a34b933dcad68390d9219c5`](https://github.com/samternent/home/commit/109f8c3989b16a161a34b933dcad68390d9219c5) Thanks [@samternent](https://github.com/samternent)! - Fix deps - -## 0.1.2 - -### Patch Changes - -- [`db52303d4c626a97abb4e1fd04ee04019404b6fa`](https://github.com/samternent/home/commit/db52303d4c626a97abb4e1fd04ee04019404b6fa) Thanks [@samternent](https://github.com/samternent)! - fix armour tests - -## 0.1.1 - -### Patch Changes - -- [`4d5f4e0deddc1a5cc1aed49745f27b0979adfe7e`](https://github.com/samternent/home/commit/4d5f4e0deddc1a5cc1aed49745f27b0979adfe7e) Thanks [@samternent](https://github.com/samternent)! - adds armour package diff --git a/packages/armour/CLAUDE.md b/packages/armour/CLAUDE.md index 3ebc711..24f9ea5 100644 --- a/packages/armour/CLAUDE.md +++ b/packages/armour/CLAUDE.md @@ -1,8 +1,31 @@ -# Armour architecture - -Armour composes Identity with the pinned TypeScript age engine. Keep encryption, -decryption and compatibility helpers here. Identity owns signing primitives; Ledger -owns signed history; Concord owns framework authority and encryption orchestration. -Keep the optional payload codec structurally compatible with Ledger without adding -a package dependency in either direction. Read the current README before extending -the interface. Historical implementations are available in Git. +# Working on Armour + +Armour is two functions in `src/index.ts` that choose age keys and call one age +`Encrypter` or `Decrypter`. Keep it that small. + +## What Armour owns + +- Turning a `PublicIdentity` into an age X25519 recipient (Noble's Ed25519 to + X25519 conversion, Scure's Bech32) and an `Identity` into a decryption key through + `withX25519Secret`. +- Which key forms are accepted: identities, native X25519 strings and a nonempty + passphrase. Nothing else. +- Not the cryptography. age does the encryption, authentication, armor and scrypt + limits. Not groups or key distribution: Concord owns those. Not signing: Seal. + +## How the code stays small + +- Let age's errors through. No error classes, codes or result wrappers. +- Copy input bytes before the first `await`: age reads them later. Read recipients + and passphrases synchronously for the same reason. +- The seed never enters Armour. Only the scoped X25519 secret does, and the Bech32 + words built from it are cleared. A JavaScript string holding a secret key can't be + erased, and that is accepted. +- No text, file, codec or streaming variants. Callers own transport and size limits. + +## Checks + +Run `pnpm run check` in this package under the Node version in `.node-version`. The +tests need the native `age` CLI on `PATH` for the interop check. `test/vectors.json` +holds ciphertext made by native age for a personal and a group key; it must keep +decrypting. Update `README.md` and `llms.txt` with any interface change. diff --git a/packages/armour/README.md b/packages/armour/README.md index 2ac9adb..217890e 100644 --- a/packages/armour/README.md +++ b/packages/armour/README.md @@ -1,75 +1,38 @@ # @ternent/armour -[Agent interface guide](llms.txt): public imports, examples and lifecycle contracts. +[Agent interface guide](llms.txt): public imports, examples and contracts. -Identity-aware age encryption, backed by the pinned pure TypeScript `age-encryption` -engine. No runtime WASM initialization or command-line process is required. +Encrypt and decrypt bytes with [age](https://age-encryption.org). Identity supplies +personal keys; groups use native age keys; backups use a passphrase. ```ts -import { generateIdentity, encryptAge } from "@ternent/armour"; -const created = await generateIdentity(); -if (!created.ok) throw new Error(created.error.code); -const identity = created.value; // public identity, exact-byte sign, decryptAge -``` - -`identityFromSeed(seed)` copies the private root through Identity's signer factory. -`withAgeDecryption(base)` synchronously composes an existing base signer without -moving private identity ownership into Armour. `identityFromSeed` and -`generateIdentity` return structured primitive results; `withAgeDecryption` returns -the composed capability directly. -`encryptAge({ recipients, plaintext })` accepts X25519 recipients and returns binary age. -`decryptAgeWithSecret({ secret, ciphertext })` accepts a raw 32-byte X25519 scalar. -These operations have no init step and support an empty plaintext. - -All operations work immediately after import. There is no `initArmour` API or -global initialization state. Text, recipient, passphrase and binary conveniences -use the same TypeScript engine as the capability interface. - -| Input/output need | Public helpers | -| ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -| Serialized identities or age recipients, byte payload | `encryptForIdentities`, `encryptForRecipients`, `decryptWithIdentity`, `decryptWithSecretKey` | -| Passphrase, byte payload | `encryptWithPassphrase`, `decryptWithPassphrase` | -| UTF-8 text | `encryptTextForIdentities`, `decryptTextWithIdentity`, `encryptTextWithPassphrase`, `decryptTextWithPassphrase` | -| Blob/File/ArrayBuffer/Uint8Array | `encryptBinaryForIdentities`, `decryptBinaryWithIdentity`, `encryptBinaryWithPassphrase`, `decryptBinaryWithPassphrase` | -| Host identity resolution and recipient derivation | `resolveIdentity`, `recipientFromIdentity`, `secretKeyFromIdentity`, `recipientsFromIdentities` | +import { encrypt, decrypt } from "@ternent/armour"; -Convenience encryption defaults to ASCII armor; byte/binary helpers accept -`output: "binary"` explicitly. Decryption accepts the supported binary/armor form -and returns bytes, except text helpers return UTF-8 strings. Convenience helpers -reject with `ArmourValidationError`, `ArmourIdentityError`, `ArmourEncryptionError` -or `ArmourDecryptionError`, all derived from `ArmourError` with a structured code. -They require nonempty payloads, with a 64 MiB engine limit; the low-level -`encryptAge` interface supports empty plaintext and returns `PrimitiveResult`. - -```ts -import { createIdentity } from "@ternent/identity"; -import { encryptTextForIdentities, decryptTextWithIdentity } from "@ternent/armour"; -const identity = await createIdentity(); -const encrypted = await encryptTextForIdentities({ identities: [identity], text: "hello" }); -const text = await decryptTextWithIdentity({ identity, data: encrypted }); +const ciphertext = await encrypt(bytes, [alice.publicIdentity, bob.publicIdentity]); +const plaintext = await decrypt(ciphertext, bob); ``` -Historical implementations are available in Git. +| Use | Encrypt with | Decrypt with | +| --------------- | ------------------------------------ | -------------------------------------- | +| People | Their `PublicIdentity` records | The recipient's `Identity` | +| A group | The group's `age1…` X25519 recipient | The group's `AGE-SECRET-KEY-1…` string | +| Identity backup | `{ passphrase }` | `{ passphrase }` | + +Identities and group recipients can share one recipient array. Every call uses fresh +randomness. Output is binary age, readable by the `age` CLI and any age library. +Empty plaintext is valid. -## Optional payload integration +Invalid input, a wrong key or passphrase, and tampered ciphertext all reject with an +ordinary `Error`. Plaintext is returned only after age authenticates it. Inputs are +copied when the call starts. -`createAgeCodec({ recipients?, reader? })` supplies an `id: "age"` byte codec for -composing Armour with Ledger's `encodePayload`/`decodePayload` helpers. Armour does -not import Ledger. Supplying recipients enables encoding; supplying a `decryptAge` -reader capability enables decoding. Recipients are copied when the codec is created. -An absent operation remains absent; it never falls back to plaintext. -The factory preserves these capabilities in its return type: recipients guarantee -`encode`, a reader guarantees `decode`, and supplying both guarantees both methods. -No non-null assertions are needed. Dynamically optional configuration returns the -general codec type and does not promise either operation. +Armour works in memory: bound the size of incoming ciphertext before decrypting. +Passphrase files use scrypt; age rejects a work factor above 2^20 (about 1 GiB of +memory) before deriving a key. Scrypt runs synchronously, so unlock a backup off the +browser's main thread. -The codec uses the existing binary age operations. Its decoder returns `null` when -the reader reports an authentication/decryption failure, covering both wrong keys -and malformed ciphertext. Other reader failures reject; implementation exceptions propagate. The caller -owns entry creation, signed history and interpretation of readable/locked results. -See the [Ledger composition example](../ledger/README.md#optional-payload-codecs). +Text transport, file reads and storage belong to the caller. For ASCII armor, use +`armor.encode` and `armor.decode` from `age-encryption`. To sign ciphertext, seal its +exact bytes with `@ternent/seal`. -Armour owns neither signing semantics, document envelopes, authorization nor storage. -Identity owns key derivation. Ledger owns signed history; Concord composes it with -its private system profile. -Native age interop and the fixed independent ciphertexts are required tests. +License: ISC. diff --git a/packages/armour/SPEC.md b/packages/armour/SPEC.md deleted file mode 100644 index d96ca54..0000000 --- a/packages/armour/SPEC.md +++ /dev/null @@ -1,14 +0,0 @@ -# Armour interface contract - -The current interfaces and compatibility guarantees are in [README.md](README.md). -The published declarations define the capability and binary operations. Armour -remains independently usable; its optional payload codec composes structurally -with Ledger without a package dependency in either direction. - -The intentionally retained text/binary/recipient/passphrase helpers, error codes and -output defaults are described in README.md and exercised by behavior/consumer tests. -Every operation is init-free. The old initialization API/error and redundant -`assertIdentityCapabilityRoot` helper are not part of the shipping surface. -Historical specifications remain source evidence in Git, not compatibility -requirements. Rage/WASM is not a runtime dependency, and Armour -adds neither document semantics nor a second encryption construction. diff --git a/packages/armour/llms.txt b/packages/armour/llms.txt index 08faeae..9270ae4 100644 --- a/packages/armour/llms.txt +++ b/packages/armour/llms.txt @@ -1,55 +1,32 @@ # @ternent/armour -> age encryption and identity decryption capabilities. No init or WASM step. +> Encrypt and decrypt bytes with age for Ternent identities, groups and passphrases. -Stable interface: `npm install @ternent/armour@0.3.0 @ternent/identity@0.6.0`. -[Public README](https://github.com/ternent/core/blob/main/packages/armour/README.md). -Installed declarations: `dist/index.d.ts`. Imports use the package root. - -## Capability encryption +Two exports from the package root: `encrypt` and `decrypt`. Type: `Passphrase`. +Declarations: `dist/index.d.ts`. ```ts -import { generateIdentity, encryptAge } from "@ternent/armour"; -import { ageRecipientFromPublicIdentity } from "@ternent/identity"; -const created = await generateIdentity(); -if (!created.ok) throw new Error(created.error.code); -const identity = created.value; -const recipient = ageRecipientFromPublicIdentity(identity.publicIdentity); -if (!recipient.ok) throw new Error(recipient.error.code); -const encrypted = await encryptAge({ - recipients: [recipient.value], - plaintext: new TextEncoder().encode("hello"), -}); -if (!encrypted.ok) throw new Error(encrypted.error.code); -const decrypted = await identity.decryptAge(encrypted.value); -if (!decrypted.ok) throw new Error(decrypted.error.code); -``` +import { createIdentity } from "@ternent/identity"; +import { encrypt, decrypt } from "@ternent/armour"; -`generateIdentity()` and `identityFromSeed(seed)` return structured results containing -`IdentityCapability`: publicIdentity, exact-byte sign and decryptAge. A -`ReaderCapability` has publicIdentity and decryptAge only. `withAgeDecryption(base)` -synchronously wraps an Identity base capability. Private material remains host-owned. -`encryptAge({ recipients, plaintext })` returns a structured result containing binary -age bytes, accepts empty plaintext and encrypts with fresh material each time. -`decryptAgeWithSecret({ secret, ciphertext })` uses a raw 32-byte X25519 scalar. +const alice = await createIdentity(); +const ciphertext = await encrypt(bytes, [alice.publicIdentity]); +const plaintext = await decrypt(ciphertext, alice); -## Convenience functions +// Groups: native age X25519 keys, e.g. from age-encryption's generateX25519Identity(). +await encrypt(bytes, [alice.publicIdentity, "age1…"]); +await decrypt(ciphertext, "AGE-SECRET-KEY-1…"); -`encryptForIdentities`, `encryptForRecipients`, `decryptWithIdentity` and -`decryptWithSecretKey` work with serialized identities/age strings and bytes. -`encryptWithPassphrase`/`decryptWithPassphrase`, text and binary variants are listed -in the README. Convenience encryption defaults to ASCII armor; select -`output: "binary"` where supported. Text decryptors return strings; byte/binary -helpers return bytes. Convenience helpers require nonempty data with a 64 MiB limit -and reject with ArmourError subclasses carrying codes; they do not return PrimitiveResult. -No `initArmour` call exists. - -## Optional Ledger payload codec +// Backups: a nonempty passphrase, used exactly as given. +const locked = await encrypt(new TextEncoder().encode(alice.export()), { passphrase }); +``` -`createAgeCodec({ recipients?, reader? })` returns an explicit byte codec with id age. -Recipients enable encode; reader enables decode. Supplying both guarantees both -methods in its type. Compose it with Ledger's `encodePayload`/`decodePayload`; Armour -never imports Ledger or manages its commits. A missing operation does not fall back -to plaintext. Decoder authentication/decryption failures return null (Ledger reports -locked); unexpected reader errors propagate. Signing, authorization, membership, -document history and storage are owned by other layers. +- `encrypt(plaintext, recipients | { passphrase })`; `decrypt(ciphertext, identity | secretKey | { passphrase })`. + Both take and return `Uint8Array`. +- Recipient strings must be X25519 `age1…`; secret keys must be `AGE-SECRET-KEY-1…`. + Hybrid and plugin keys are rejected. +- Failures reject with an ordinary `Error`; there are no error codes. +- Output is binary. For text, use `armor.encode`/`armor.decode` from `age-encryption`. +- Bound ciphertext size before decrypting; this is an in-memory API. +- Passphrase decryption runs scrypt synchronously: use a worker in browsers. +- Armour does not sign. Seal the ciphertext bytes with `@ternent/seal` to prove authorship. diff --git a/packages/armour/package.json b/packages/armour/package.json index 155bf4c..695fdbb 100644 --- a/packages/armour/package.json +++ b/packages/armour/package.json @@ -1,7 +1,7 @@ { "name": "@ternent/armour", "version": "0.3.0", - "description": "Identity-aware age encryption with text, binary and passphrase helpers", + "description": "Encrypt and decrypt bytes with age for Ternent identities, groups and passphrases", "license": "ISC", "repository": { "type": "git", @@ -37,6 +37,8 @@ "check": "pnpm --filter @ternent/armour... run build && pnpm run fmt:check && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run check:artifact" }, "dependencies": { + "@noble/curves": "2.4.0", + "@scure/base": "2.4.0", "@ternent/identity": "workspace:^", "age-encryption": "0.3.1" }, diff --git a/packages/armour/src/age.ts b/packages/armour/src/age.ts deleted file mode 100644 index d4494bc..0000000 --- a/packages/armour/src/age.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { Encrypter, Decrypter } from "age-encryption"; -import { - ageSecretKey, - generateSigner, - signerFromSeed, - type BaseIdentityCapability, - type PrimitiveResult, - type PublicIdentity, -} from "@ternent/identity"; - -export type ReaderCapability = { - readonly publicIdentity: PublicIdentity; - decryptAge(this: void, ciphertext: Uint8Array): Promise>; -}; -export type IdentityCapability = ReaderCapability & Pick; -const failed = (code: string): PrimitiveResult => ({ - ok: false, - error: { code, message: code.replaceAll("_", " ").toLowerCase() }, -}); - -export async function encryptAge(input: { - recipients: readonly string[]; - plaintext: Uint8Array; -}): Promise> { - try { - if ( - !Array.isArray(input.recipients) || - !input.recipients.length || - !(input.plaintext instanceof Uint8Array) - ) - return failed("ENCRYPTION_INVALID"); - const encrypter = new Encrypter(); - for (const recipient of input.recipients) { - if (!/^age1[023456789acdefghjklmnpqrstuvwxyz]{58}$/.test(recipient)) - return failed("RECIPIENT_INVALID"); - encrypter.addRecipient(recipient); - } - return { ok: true, value: await encrypter.encrypt(new Uint8Array(input.plaintext)) }; - } catch { - return failed("ENCRYPTION_FAILED"); - } -} -export async function decryptAgeWithSecret(input: { - secret: Uint8Array; - ciphertext: Uint8Array; -}): Promise> { - try { - const decrypter = new Decrypter(); - decrypter.addIdentity(ageSecretKey(input.secret)); - return { ok: true, value: await decrypter.decrypt(new Uint8Array(input.ciphertext)) }; - } catch { - return failed("DECRYPTION_FAILED"); - } -} -export function withAgeDecryption(base: BaseIdentityCapability): IdentityCapability { - return Object.freeze({ - publicIdentity: base.publicIdentity, - sign: (message: Uint8Array) => base.sign(new Uint8Array(message)), - decryptAge: (ciphertext: Uint8Array) => { - const bytes = new Uint8Array(ciphertext); - return base.withX25519Secret((secret) => decryptAgeWithSecret({ secret, ciphertext: bytes })); - }, - }); -} -export async function identityFromSeed( - seed: Uint8Array, -): Promise> { - const base = await signerFromSeed(seed); - return base.ok ? { ok: true, value: withAgeDecryption(base.value) } : base; -} -export async function generateIdentity(): Promise> { - const base = await generateSigner(); - return base.ok ? { ok: true, value: withAgeDecryption(base.value) } : base; -} diff --git a/packages/armour/src/codec.ts b/packages/armour/src/codec.ts deleted file mode 100644 index 9c0cfb8..0000000 --- a/packages/armour/src/codec.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { validateAgeRecipient } from "@ternent/identity"; -import { encryptAge, type ReaderCapability } from "./age.js"; -import { ArmourDecryptionError, ArmourEncryptionError, ArmourValidationError } from "./errors.js"; - -/** Compatible with Ledger's optional payload helpers, without a dependency on Ledger. */ -export type AgePayloadCodec = { - readonly id: "age"; - encode?(this: void, plaintext: Uint8Array): Promise; - decode?(this: void, ciphertext: Uint8Array): Promise; -}; -export type AgePayloadEncoder = AgePayloadCodec & Required>; -export type AgePayloadDecoder = AgePayloadCodec & Required>; -type AgeCodecOptions = { - recipients?: readonly string[]; - reader?: Pick; -}; -export function createAgeCodec( - input: Required, -): AgePayloadEncoder & AgePayloadDecoder; -export function createAgeCodec( - input: AgeCodecOptions & { recipients: readonly string[] }, -): AgePayloadEncoder; -export function createAgeCodec( - input: AgeCodecOptions & { reader: Pick }, -): AgePayloadDecoder; -export function createAgeCodec(input?: AgeCodecOptions): AgePayloadCodec; -export function createAgeCodec(input: AgeCodecOptions = {}): AgePayloadCodec { - if ( - !input || - typeof input !== "object" || - Array.isArray(input) || - Object.keys(input).some((key) => key !== "recipients" && key !== "reader") - ) - throw new ArmourValidationError("ARMOUR_INVALID_RECIPIENT", "Invalid codec configuration."); - const recipients = input.recipients; - if ( - recipients !== undefined && - (!Array.isArray(recipients) || - !recipients.length || - recipients.some((recipient) => !validateAgeRecipient(recipient).ok)) - ) - throw new ArmourValidationError( - "ARMOUR_INVALID_RECIPIENT", - "Expected nonempty age recipients.", - ); - const targets = recipients && [...recipients]; - const decrypt = input.reader?.decryptAge; - if (input.reader !== undefined && typeof decrypt !== "function") - throw new ArmourValidationError("ARMOUR_INVALID_IDENTITY", "Expected a decryption capability."); - return Object.freeze({ - id: "age", - ...(targets - ? { - encode: async (plaintext: Uint8Array) => { - const result = await encryptAge({ recipients: targets, plaintext }); - if (!result.ok) - throw new ArmourEncryptionError( - "ARMOUR_ENCRYPT_FAILED", - "Failed to encrypt payload.", - ); - return result.value; - }, - } - : {}), - ...(decrypt - ? { - decode: async (ciphertext: Uint8Array) => { - const result = await decrypt(new Uint8Array(ciphertext)); - if (result.ok) return result.value; - if (result.error.code === "DECRYPTION_FAILED") return null; - throw new ArmourDecryptionError( - "ARMOUR_DECRYPT_FAILED", - "Reader could not process the payload.", - result.error, - ); - }, - } - : {}), - }); -} diff --git a/packages/armour/src/constants.ts b/packages/armour/src/constants.ts deleted file mode 100644 index 7512921..0000000 --- a/packages/armour/src/constants.ts +++ /dev/null @@ -1,5 +0,0 @@ -export const AGE_RECIPIENT_PREFIX = "age1"; -export const AGE_SECRET_KEY_PREFIX = "AGE-SECRET-KEY-"; - -export const utf8Encoder = new TextEncoder(); -export const utf8Decoder = new TextDecoder("utf-8", { fatal: true }); diff --git a/packages/armour/src/engine.ts b/packages/armour/src/engine.ts deleted file mode 100644 index f3bccbf..0000000 --- a/packages/armour/src/engine.ts +++ /dev/null @@ -1,86 +0,0 @@ -// Text, file and passphrase operations over the same TypeScript age engine. -import { Encrypter, Decrypter, armor } from "age-encryption"; -import type { ArmourOutputFormat } from "./types.js"; -export class AgeEngineError extends Error { - constructor(readonly code: string) { - super(code); - } -} -export class AgeEngineValidationError extends AgeEngineError {} -export class AgeEngineEncryptionError extends AgeEngineError {} -export class AgeEngineDecryptionError extends AgeEngineError {} -function dataCheck(data: Uint8Array): void { - if (!(data instanceof Uint8Array) || !data.length) - throw new AgeEngineValidationError("AGE_ENGINE_EMPTY_DATA"); - if (data.length > 64 * 1024 * 1024) - throw new AgeEngineValidationError("AGE_ENGINE_DATA_TOO_LARGE"); -} -function output(data: Uint8Array, format?: ArmourOutputFormat): Uint8Array { - return (format ?? "armor") === "armor" ? new TextEncoder().encode(armor.encode(data)) : data; -} -function binary(data: Uint8Array): Uint8Array { - return new TextDecoder().decode(data.subarray(0, 35)).startsWith("-----BEGIN AGE") - ? armor.decode(new TextDecoder().decode(data)) - : data; -} -export async function encryptWithRecipients(input: { - recipients: string[]; - data: Uint8Array; - output?: ArmourOutputFormat; -}): Promise { - dataCheck(input.data); - if (!input.recipients.length) throw new AgeEngineValidationError("AGE_ENGINE_EMPTY_RECIPIENTS"); - const encrypter = new Encrypter(); - try { - for (const recipient of input.recipients) encrypter.addRecipient(recipient); - } catch { - throw new AgeEngineValidationError("AGE_ENGINE_INVALID_RECIPIENT"); - } - try { - return output(await encrypter.encrypt(input.data), input.output); - } catch { - throw new AgeEngineEncryptionError("AGE_ENGINE_ENCRYPT_FAILED"); - } -} -export async function decryptWithIdentity(input: { - identity: string; - data: Uint8Array; -}): Promise { - dataCheck(input.data); - const decrypter = new Decrypter(); - try { - decrypter.addIdentity(input.identity); - } catch { - throw new AgeEngineValidationError("AGE_ENGINE_INVALID_IDENTITY"); - } - try { - return await decrypter.decrypt(binary(input.data)); - } catch { - throw new AgeEngineDecryptionError("AGE_ENGINE_DECRYPT_FAILED"); - } -} -export async function encryptWithPassphrase(input: { - passphrase: string; - data: Uint8Array; - output?: ArmourOutputFormat; -}): Promise { - dataCheck(input.data); - if (!input.passphrase) throw new AgeEngineValidationError("AGE_ENGINE_EMPTY_PASSPHRASE"); - const encrypter = new Encrypter(); - encrypter.setPassphrase(input.passphrase); - return output(await encrypter.encrypt(input.data), input.output); -} -export async function decryptWithPassphrase(input: { - passphrase: string; - data: Uint8Array; -}): Promise { - dataCheck(input.data); - if (!input.passphrase) throw new AgeEngineValidationError("AGE_ENGINE_EMPTY_PASSPHRASE"); - const decrypter = new Decrypter(); - decrypter.addPassphrase(input.passphrase); - try { - return await decrypter.decrypt(binary(input.data)); - } catch { - throw new AgeEngineDecryptionError("AGE_ENGINE_DECRYPT_FAILED"); - } -} diff --git a/packages/armour/src/errors.ts b/packages/armour/src/errors.ts deleted file mode 100644 index 23a8a19..0000000 --- a/packages/armour/src/errors.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { - AgeEngineDecryptionError, - AgeEngineEncryptionError, - AgeEngineError, - AgeEngineValidationError, -} from "./engine.js"; -import type { ArmourErrorCode } from "./types.js"; - -export class ArmourError extends Error { - readonly code: ArmourErrorCode; - readonly cause?: unknown; - - constructor(code: ArmourErrorCode, message: string, cause?: unknown) { - super(message); - this.name = new.target.name; - this.code = code; - if (cause !== undefined) { - this.cause = cause; - } - } -} - -export class ArmourValidationError extends ArmourError {} -export class ArmourIdentityError extends ArmourError {} -export class ArmourEncryptionError extends ArmourError {} -export class ArmourDecryptionError extends ArmourError {} - -function getMessage(error: unknown): string { - if (error instanceof Error) { - return error.message; - } - return String(error); -} - -export function toArmourIdentityError( - error: unknown, - code: "ARMOUR_INVALID_IDENTITY" | "ARMOUR_IDENTITY_DERIVATION_FAILED", - fallbackMessage: string, -): ArmourIdentityError { - if (error instanceof ArmourIdentityError) { - return error; - } - - return new ArmourIdentityError(code, fallbackMessage, error); -} - -export function toArmourEncryptionError(error: unknown): ArmourError { - if (error instanceof ArmourError) { - return error; - } - - if (error instanceof AgeEngineValidationError) { - switch (error.code) { - case "AGE_ENGINE_EMPTY_DATA": - return new ArmourValidationError( - "ARMOUR_EMPTY_DATA", - "Data must be a non-empty Uint8Array.", - error, - ); - case "AGE_ENGINE_EMPTY_RECIPIENTS": - return new ArmourValidationError( - "ARMOUR_EMPTY_RECIPIENTS", - "At least one recipient is required.", - error, - ); - case "AGE_ENGINE_INVALID_RECIPIENT": - return new ArmourValidationError( - "ARMOUR_INVALID_RECIPIENT", - "Recipient must be an age recipient string.", - error, - ); - case "AGE_ENGINE_EMPTY_PASSPHRASE": - return new ArmourValidationError( - "ARMOUR_EMPTY_PASSPHRASE", - "Passphrase must not be empty.", - error, - ); - case "AGE_ENGINE_DATA_TOO_LARGE": - return new ArmourValidationError( - "ARMOUR_DATA_TOO_LARGE", - "Data exceeds the 64MB maximum message size.", - error, - ); - default: - break; - } - } - - if (error instanceof AgeEngineEncryptionError || error instanceof AgeEngineError) { - return new ArmourEncryptionError("ARMOUR_ENCRYPT_FAILED", "Failed to encrypt data.", error); - } - - return new ArmourEncryptionError("ARMOUR_ENCRYPT_FAILED", "Failed to encrypt data.", error); -} - -export function toArmourDecryptionError(error: unknown): ArmourError { - if (error instanceof ArmourError) { - return error; - } - - if (error instanceof AgeEngineValidationError) { - switch (error.code) { - case "AGE_ENGINE_EMPTY_DATA": - return new ArmourValidationError( - "ARMOUR_EMPTY_DATA", - "Data must be a non-empty Uint8Array.", - error, - ); - case "AGE_ENGINE_INVALID_IDENTITY": - return new ArmourValidationError( - "ARMOUR_INVALID_SECRET_KEY", - "Secret key must be an age secret key string.", - error, - ); - case "AGE_ENGINE_EMPTY_PASSPHRASE": - return new ArmourValidationError( - "ARMOUR_EMPTY_PASSPHRASE", - "Passphrase must not be empty.", - error, - ); - default: - break; - } - } - - if (error instanceof AgeEngineDecryptionError || error instanceof AgeEngineError) { - return new ArmourDecryptionError("ARMOUR_DECRYPT_FAILED", "Failed to decrypt data.", error); - } - - return new ArmourDecryptionError("ARMOUR_DECRYPT_FAILED", "Failed to decrypt data.", error); -} -export function invalidUtf8Error(error: unknown): ArmourDecryptionError { - return new ArmourDecryptionError( - "ARMOUR_DECRYPT_FAILED", - "Decrypted data is not valid UTF-8.", - error, - ); -} - -export function invalidBinaryInputError(value: unknown): ArmourValidationError { - const detail = - value instanceof ArrayBuffer || value instanceof Uint8Array || value instanceof Blob - ? "Data must be a non-empty Blob, File, ArrayBuffer, or Uint8Array." - : `Unsupported binary input type: ${getMessage(value)}`; - - return new ArmourValidationError("ARMOUR_EMPTY_DATA", detail, value); -} diff --git a/packages/armour/src/files.ts b/packages/armour/src/files.ts deleted file mode 100644 index 0582b5a..0000000 --- a/packages/armour/src/files.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { invalidBinaryInputError } from "./errors.js"; -import { decryptWithIdentity, encryptForIdentities } from "./recipients.js"; -import { decryptWithPassphrase, encryptWithPassphrase } from "./passphrase.js"; -import type { - ArmourBinaryInput, - DecryptBinaryWithIdentityInput, - DecryptBinaryWithPassphraseInput, - EncryptBinaryForIdentitiesInput, - EncryptBinaryWithPassphraseInput, -} from "./types.js"; - -async function toUint8Array(data: ArmourBinaryInput): Promise { - if (data instanceof Uint8Array) { - if (data.byteLength === 0) { - throw invalidBinaryInputError(data); - } - return Uint8Array.from(data); - } - - if (data instanceof ArrayBuffer) { - if (data.byteLength === 0) { - throw invalidBinaryInputError(data); - } - return new Uint8Array(data.slice(0)); - } - - if (data instanceof Blob) { - if (data.size === 0) { - throw invalidBinaryInputError(data); - } - return new Uint8Array(await data.arrayBuffer()); - } - - throw invalidBinaryInputError(data); -} - -export async function encryptBinaryForIdentities( - input: EncryptBinaryForIdentitiesInput, -): Promise { - return encryptForIdentities({ - identities: input.identities, - data: await toUint8Array(input.data), - output: input.output, - }); -} - -export async function decryptBinaryWithIdentity( - input: DecryptBinaryWithIdentityInput, -): Promise { - return decryptWithIdentity({ - identity: input.identity, - data: await toUint8Array(input.data), - }); -} - -export async function encryptBinaryWithPassphrase( - input: EncryptBinaryWithPassphraseInput, -): Promise { - return encryptWithPassphrase({ - passphrase: input.passphrase, - data: await toUint8Array(input.data), - output: input.output, - }); -} - -export async function decryptBinaryWithPassphrase( - input: DecryptBinaryWithPassphraseInput, -): Promise { - return decryptWithPassphrase({ - passphrase: input.passphrase, - data: await toUint8Array(input.data), - }); -} diff --git a/packages/armour/src/identity.ts b/packages/armour/src/identity.ts deleted file mode 100644 index 258ca02..0000000 --- a/packages/armour/src/identity.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { - deriveAgeRecipient, - deriveAgeSecretKey, - parseIdentity, - type SerializedIdentity, -} from "@ternent/identity"; -import { AGE_SECRET_KEY_PREFIX } from "./constants.js"; -import { ArmourValidationError, toArmourIdentityError } from "./errors.js"; -import type { ArmourIdentityInput } from "./types.js"; - -export async function resolveIdentity(input: ArmourIdentityInput): Promise { - try { - return parseIdentity(input); - } catch (error) { - throw toArmourIdentityError( - error, - "ARMOUR_INVALID_IDENTITY", - "Identity input must be a valid @ternent/identity serialized identity.", - ); - } -} - -export async function recipientFromIdentity(input: ArmourIdentityInput): Promise { - const identity = await resolveIdentity(input); - - try { - return await deriveAgeRecipient(identity); - } catch (error) { - throw toArmourIdentityError( - error, - "ARMOUR_IDENTITY_DERIVATION_FAILED", - "Failed to derive an age recipient from the provided identity.", - ); - } -} - -export async function secretKeyFromIdentity(input: ArmourIdentityInput): Promise { - const identity = await resolveIdentity(input); - - try { - return await deriveAgeSecretKey(identity); - } catch (error) { - throw toArmourIdentityError( - error, - "ARMOUR_IDENTITY_DERIVATION_FAILED", - "Failed to derive an age secret key from the provided identity.", - ); - } -} - -export async function normalizeSecretKey(secretKey: string): Promise { - const normalized = String(secretKey || "").trim(); - - if (!normalized.startsWith(AGE_SECRET_KEY_PREFIX)) { - throw new ArmourValidationError( - "ARMOUR_INVALID_SECRET_KEY", - "Secret key must be an age secret key string.", - ); - } - - return normalized; -} diff --git a/packages/armour/src/index.ts b/packages/armour/src/index.ts index 3c32b0d..db005a5 100644 --- a/packages/armour/src/index.ts +++ b/packages/armour/src/index.ts @@ -1,59 +1,82 @@ -export { - ArmourDecryptionError, - ArmourEncryptionError, - ArmourError, - ArmourIdentityError, - ArmourValidationError, -} from "./errors.js"; -export { - decryptBinaryWithIdentity, - decryptBinaryWithPassphrase, - encryptBinaryForIdentities, - encryptBinaryWithPassphrase, -} from "./files.js"; -export { recipientFromIdentity, resolveIdentity, secretKeyFromIdentity } from "./identity.js"; -export { decryptWithPassphrase, encryptWithPassphrase } from "./passphrase.js"; -export { - decryptWithIdentity, - decryptWithSecretKey, - encryptForIdentities, - encryptForRecipients, - recipientsFromIdentities, -} from "./recipients.js"; -export { - decryptTextWithIdentity, - decryptTextWithPassphrase, - encryptTextForIdentities, - encryptTextWithPassphrase, -} from "./text.js"; -export type { SerializedIdentity } from "@ternent/identity"; -export type { - ArmourBinaryInput, - ArmourErrorCode, - ArmourIdentityInput, - ArmourOutputFormat, - DecryptBinaryWithIdentityInput, - DecryptBinaryWithPassphraseInput, - DecryptTextWithIdentityInput, - DecryptTextWithPassphraseInput, - DecryptWithIdentityInput, - DecryptWithPassphraseInput, - DecryptWithSecretKeyInput, - EncryptBinaryForIdentitiesInput, - EncryptBinaryWithPassphraseInput, - EncryptForIdentitiesInput, - EncryptForRecipientsInput, - EncryptTextForIdentitiesInput, - EncryptTextWithPassphraseInput, - EncryptWithPassphraseInput, -} from "./types.js"; -export { - encryptAge, - decryptAgeWithSecret, - withAgeDecryption, - identityFromSeed, - generateIdentity, -} from "./age.js"; -export type { ReaderCapability, IdentityCapability } from "./age.js"; -export { createAgeCodec } from "./codec.js"; -export type { AgePayloadCodec, AgePayloadEncoder, AgePayloadDecoder } from "./codec.js"; +import { ed25519 } from "@noble/curves/ed25519.js"; +import { base64urlnopad, bech32 } from "@scure/base"; +import { validatePublicIdentity, type Identity, type PublicIdentity } from "@ternent/identity"; +import { Decrypter, Encrypter } from "age-encryption"; + +export type Passphrase = { passphrase: string }; + +// age's own parsers also accept hybrid and plugin keys; Armour takes X25519 only. +const X25519_RECIPIENT = /^age1[02-9ac-hj-np-z]{58}$/; +const X25519_SECRET_KEY = /^AGE-SECRET-KEY-1[02-9AC-HJ-NP-Z]{58}$/; + +export async function encrypt( + plaintext: Uint8Array, + target: readonly (PublicIdentity | string)[] | Passphrase, +): Promise { + const bytes = copyBytes(plaintext); + const encrypter = new Encrypter(); + if (isPassphrase(target)) { + encrypter.setPassphrase(readPassphrase(target)); + } else { + if (!Array.isArray(target) || target.length === 0) { + throw new TypeError("Encrypt needs at least one recipient"); + } + for (const recipient of target) encrypter.addRecipient(toRecipient(recipient)); + } + return encrypter.encrypt(bytes); +} + +export async function decrypt( + ciphertext: Uint8Array, + key: Identity | string | Passphrase, +): Promise { + const bytes = copyBytes(ciphertext); + const decrypter = new Decrypter(); + if (typeof key === "string") { + if (!X25519_SECRET_KEY.test(key)) throw new TypeError("Expected an age X25519 secret key"); + decrypter.addIdentity(key); + return decrypter.decrypt(bytes); + } + if (isPassphrase(key)) { + decrypter.addPassphrase(readPassphrase(key)); + return decrypter.decrypt(bytes); + } + if (typeof key?.withX25519Secret !== "function") { + throw new TypeError("Decrypt needs an Identity, an age secret key or a passphrase"); + } + return key.withX25519Secret((secret) => { + const words = bech32.toWords(secret); + try { + decrypter.addIdentity(bech32.encode("age-secret-key-", words).toUpperCase()); + } finally { + words.fill(0); + } + return decrypter.decrypt(bytes); + }); +} + +function toRecipient(recipient: PublicIdentity | string): string { + if (typeof recipient === "string") { + if (!X25519_RECIPIENT.test(recipient)) throw new TypeError("Expected an age X25519 recipient"); + return recipient; + } + const publicKey = base64urlnopad.decode(validatePublicIdentity(recipient).publicKey); + return bech32.encode("age", bech32.toWords(ed25519.utils.toMontgomery(publicKey))); +} + +function isPassphrase(value: unknown): value is Passphrase { + return typeof value === "object" && value !== null && Object.hasOwn(value, "passphrase"); +} + +function readPassphrase({ passphrase }: Passphrase): string { + if (typeof passphrase !== "string" || passphrase === "") { + throw new TypeError("A passphrase must be a nonempty string"); + } + return passphrase; +} + +// age reads its input after the first await, so the caller's buffer is copied first. +function copyBytes(value: Uint8Array): Uint8Array { + if (!(value instanceof Uint8Array)) throw new TypeError("Expected bytes"); + return value.slice(); +} diff --git a/packages/armour/src/passphrase.ts b/packages/armour/src/passphrase.ts deleted file mode 100644 index 83a21b6..0000000 --- a/packages/armour/src/passphrase.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { - decryptWithPassphrase as rageDecryptWithPassphrase, - encryptWithPassphrase as rageEncryptWithPassphrase, -} from "./engine.js"; -import { toArmourDecryptionError, toArmourEncryptionError } from "./errors.js"; -import type { DecryptWithPassphraseInput, EncryptWithPassphraseInput } from "./types.js"; - -export async function encryptWithPassphrase( - input: EncryptWithPassphraseInput, -): Promise { - try { - return await rageEncryptWithPassphrase({ - passphrase: input.passphrase, - data: input.data, - output: input.output, - }); - } catch (error) { - throw toArmourEncryptionError(error); - } -} - -export async function decryptWithPassphrase( - input: DecryptWithPassphraseInput, -): Promise { - try { - return await rageDecryptWithPassphrase({ - passphrase: input.passphrase, - data: input.data, - }); - } catch (error) { - throw toArmourDecryptionError(error); - } -} diff --git a/packages/armour/src/recipients.ts b/packages/armour/src/recipients.ts deleted file mode 100644 index a56c105..0000000 --- a/packages/armour/src/recipients.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { - decryptWithIdentity as rageDecryptWithIdentity, - encryptWithRecipients as rageEncryptWithRecipients, -} from "./engine.js"; -import { - normalizeSecretKey, - recipientFromIdentity, - resolveIdentity, - secretKeyFromIdentity, -} from "./identity.js"; -import { toArmourDecryptionError, toArmourEncryptionError } from "./errors.js"; -import type { - ArmourIdentityInput, - DecryptWithIdentityInput, - DecryptWithSecretKeyInput, - EncryptForIdentitiesInput, - EncryptForRecipientsInput, -} from "./types.js"; - -export async function recipientsFromIdentities( - identities: ArmourIdentityInput[], -): Promise { - const resolved: string[] = []; - - for (const identity of identities) { - await resolveIdentity(identity); - resolved.push(await recipientFromIdentity(identity)); - } - - return resolved; -} - -export async function encryptForRecipients(input: EncryptForRecipientsInput): Promise { - try { - return await rageEncryptWithRecipients({ - recipients: input.recipients, - data: input.data, - output: input.output, - }); - } catch (error) { - throw toArmourEncryptionError(error); - } -} - -export async function decryptWithSecretKey(input: DecryptWithSecretKeyInput): Promise { - try { - return await rageDecryptWithIdentity({ - identity: await normalizeSecretKey(input.secretKey), - data: input.data, - }); - } catch (error) { - throw toArmourDecryptionError(error); - } -} - -export async function encryptForIdentities(input: EncryptForIdentitiesInput): Promise { - return encryptForRecipients({ - recipients: await recipientsFromIdentities(input.identities), - data: input.data, - output: input.output, - }); -} - -export async function decryptWithIdentity(input: DecryptWithIdentityInput): Promise { - try { - return await rageDecryptWithIdentity({ - identity: await secretKeyFromIdentity(input.identity), - data: input.data, - }); - } catch (error) { - throw toArmourDecryptionError(error); - } -} diff --git a/packages/armour/src/text.ts b/packages/armour/src/text.ts deleted file mode 100644 index 8538880..0000000 --- a/packages/armour/src/text.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { utf8Decoder, utf8Encoder } from "./constants.js"; -import { invalidUtf8Error } from "./errors.js"; -import { decryptWithIdentity, encryptForIdentities } from "./recipients.js"; -import { decryptWithPassphrase, encryptWithPassphrase } from "./passphrase.js"; -import type { - DecryptTextWithIdentityInput, - DecryptTextWithPassphraseInput, - EncryptTextForIdentitiesInput, - EncryptTextWithPassphraseInput, -} from "./types.js"; - -function decodeUtf8(data: Uint8Array): string { - try { - return utf8Decoder.decode(data); - } catch (error) { - throw invalidUtf8Error(error); - } -} - -function normalizeCiphertext(data: string | Uint8Array): Uint8Array { - return typeof data === "string" ? utf8Encoder.encode(data) : data; -} - -export async function encryptTextForIdentities( - input: EncryptTextForIdentitiesInput, -): Promise { - const ciphertext = await encryptForIdentities({ - identities: input.identities, - data: utf8Encoder.encode(input.text), - output: "armor", - }); - - return utf8Decoder.decode(ciphertext); -} - -export async function decryptTextWithIdentity( - input: DecryptTextWithIdentityInput, -): Promise { - const plaintext = await decryptWithIdentity({ - identity: input.identity, - data: normalizeCiphertext(input.data), - }); - - return decodeUtf8(plaintext); -} - -export async function encryptTextWithPassphrase( - input: EncryptTextWithPassphraseInput, -): Promise { - const ciphertext = await encryptWithPassphrase({ - passphrase: input.passphrase, - data: utf8Encoder.encode(input.text), - output: "armor", - }); - - return utf8Decoder.decode(ciphertext); -} - -export async function decryptTextWithPassphrase( - input: DecryptTextWithPassphraseInput, -): Promise { - const plaintext = await decryptWithPassphrase({ - passphrase: input.passphrase, - data: normalizeCiphertext(input.data), - }); - - return decodeUtf8(plaintext); -} diff --git a/packages/armour/src/types.ts b/packages/armour/src/types.ts deleted file mode 100644 index f520f94..0000000 --- a/packages/armour/src/types.ts +++ /dev/null @@ -1,92 +0,0 @@ -import type { SerializedIdentity } from "@ternent/identity"; - -export type ArmourIdentityInput = string | SerializedIdentity; -export type ArmourOutputFormat = "armor" | "binary"; -export type ArmourBinaryInput = Uint8Array | ArrayBuffer | Blob; - -export type ArmourErrorCode = - | "ARMOUR_EMPTY_DATA" - | "ARMOUR_EMPTY_RECIPIENTS" - | "ARMOUR_INVALID_RECIPIENT" - | "ARMOUR_INVALID_SECRET_KEY" - | "ARMOUR_EMPTY_PASSPHRASE" - | "ARMOUR_DATA_TOO_LARGE" - | "ARMOUR_INVALID_IDENTITY" - | "ARMOUR_IDENTITY_DERIVATION_FAILED" - | "ARMOUR_ENCRYPT_FAILED" - | "ARMOUR_DECRYPT_FAILED"; - -export interface EncryptForRecipientsInput { - recipients: string[]; - data: Uint8Array; - output?: ArmourOutputFormat; -} - -export interface DecryptWithSecretKeyInput { - secretKey: string; - data: Uint8Array; -} - -export interface EncryptForIdentitiesInput { - identities: ArmourIdentityInput[]; - data: Uint8Array; - output?: ArmourOutputFormat; -} - -export interface DecryptWithIdentityInput { - identity: ArmourIdentityInput; - data: Uint8Array; -} - -export interface EncryptWithPassphraseInput { - passphrase: string; - data: Uint8Array; - output?: ArmourOutputFormat; -} - -export interface DecryptWithPassphraseInput { - passphrase: string; - data: Uint8Array; -} - -export interface EncryptTextForIdentitiesInput { - identities: ArmourIdentityInput[]; - text: string; -} - -export interface DecryptTextWithIdentityInput { - identity: ArmourIdentityInput; - data: string | Uint8Array; -} - -export interface EncryptTextWithPassphraseInput { - passphrase: string; - text: string; -} - -export interface DecryptTextWithPassphraseInput { - passphrase: string; - data: string | Uint8Array; -} - -export interface EncryptBinaryForIdentitiesInput { - identities: ArmourIdentityInput[]; - data: ArmourBinaryInput; - output?: ArmourOutputFormat; -} - -export interface DecryptBinaryWithIdentityInput { - identity: ArmourIdentityInput; - data: ArmourBinaryInput; -} - -export interface EncryptBinaryWithPassphraseInput { - passphrase: string; - data: ArmourBinaryInput; - output?: ArmourOutputFormat; -} - -export interface DecryptBinaryWithPassphraseInput { - passphrase: string; - data: ArmourBinaryInput; -} diff --git a/packages/armour/test/age.test.ts b/packages/armour/test/age.test.ts deleted file mode 100644 index e7324f2..0000000 --- a/packages/armour/test/age.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { expect, test } from "vite-plus/test"; -import { readFileSync } from "node:fs"; -import { execFileSync } from "node:child_process"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { type PrimitiveResult } from "@ternent/identity"; -import { - identityFromSeed, - encryptAge, - decryptAgeWithSecret, - encryptForRecipients, -} from "../src/index.js"; -const hex = (value: string) => Uint8Array.from(value.match(/../g)!, (byte) => parseInt(byte, 16)); -function value(result: PrimitiveResult): T { - if (!result.ok) throw new Error(result.error.code); - return result.value; -} -const vectors = JSON.parse( - readFileSync( - new URL("../../../docs/concord/vectors/owner.expected.json", import.meta.url), - "utf8", - ), -) as { - identitySeedHex: string; - groupSecretHex: string; - groupRecipient: string; - groupAgeSecretKey: string; - keyPlaintext: unknown; - eventPlaintext: unknown; -}; -const document = JSON.parse( - readFileSync( - new URL("../../../docs/concord/vectors/owner.document.json", import.meta.url), - "utf8", - ), -) as { - entries: { - subject: { - payload: { data: { data?: { wraps: { ciphertext: string }[] }; ciphertext?: string } }; - }; - }[]; -}; -const decode = (text: string) => new Uint8Array(Buffer.from(text, "base64url")); -test("saved independent native-age ciphertext decrypts with the same owner and group material", async () => { - const owner = value(await identityFromSeed(hex(vectors.identitySeedHex))); - const wrapped = document.entries[0].subject.payload.data.data!.wraps[0].ciphertext; - expect( - JSON.parse(new TextDecoder().decode(value(await owner.decryptAge(decode(wrapped))))), - ).toEqual(vectors.keyPlaintext); - const event = document.entries[1].subject.payload.data.ciphertext!; - expect( - JSON.parse( - new TextDecoder().decode( - value( - await decryptAgeWithSecret({ - secret: hex(vectors.groupSecretHex), - ciphertext: decode(event), - }), - ), - ), - ), - ).toEqual(vectors.eventPlaintext); -}); -test("binary age needs no initialization; fresh encryption, tampering and wrong identities", async () => { - const owner = value(await identityFromSeed(hex(vectors.identitySeedHex))); - const plaintext = new TextEncoder().encode("portable age"); - const a = value(await encryptAge({ recipients: [vectors.groupRecipient], plaintext })); - const b = value(await encryptAge({ recipients: [vectors.groupRecipient], plaintext })); - expect(a).not.toEqual(b); - expect( - value(await decryptAgeWithSecret({ secret: hex(vectors.groupSecretHex), ciphertext: a })), - ).toEqual(plaintext); - expect(await owner.decryptAge(a)).toMatchObject({ ok: false }); - a[a.length - 1] ^= 1; - expect( - await decryptAgeWithSecret({ secret: hex(vectors.groupSecretHex), ciphertext: a }), - ).toMatchObject({ ok: false }); -}); -test("T04: TypeScript to native age and native age to TypeScript", async () => { - const temporary = mkdtempSync(join(tmpdir(), "concord-age-")); - try { - const key = join(temporary, "key.txt"); - writeFileSync(key, `${vectors.groupAgeSecretKey}\n`, { mode: 0o600 }); - const plaintext = new TextEncoder().encode("independent interop"); - const encrypted = value(await encryptAge({ recipients: [vectors.groupRecipient], plaintext })); - expect( - new Uint8Array(execFileSync("age", ["--decrypt", "-i", key], { input: encrypted })), - ).toEqual(plaintext); - const native = new Uint8Array( - execFileSync("age", ["--encrypt", "-r", vectors.groupRecipient], { input: plaintext }), - ); - expect( - value( - await decryptAgeWithSecret({ secret: hex(vectors.groupSecretHex), ciphertext: native }), - ), - ).toEqual(plaintext); - } finally { - rmSync(temporary, { recursive: true, force: true }); - } -}); - -test("retained recipient helpers preserve their default ASCII armor output", async () => { - const result = await encryptForRecipients({ - recipients: [vectors.groupRecipient], - data: new TextEncoder().encode("legacy output"), - }); - expect(new TextDecoder().decode(result)).toContain("-----BEGIN AGE ENCRYPTED FILE-----"); -}); diff --git a/packages/armour/test/armour.test.ts b/packages/armour/test/armour.test.ts index 5415d2c..8736dba 100644 --- a/packages/armour/test/armour.test.ts +++ b/packages/armour/test/armour.test.ts @@ -1,251 +1,136 @@ -import { dirname, resolve } from "node:path"; -import { readFile } from "node:fs/promises"; -import { fileURLToPath, pathToFileURL } from "node:url"; -import { describe, expect, it, vi } from "vite-plus/test"; -import { createIdentity, serializeIdentity } from "@ternent/identity"; - -const testDir = dirname(fileURLToPath(import.meta.url)); -const packageDir = resolve(testDir, ".."); - -async function loadSourceModule() { - vi.resetModules(); - return import("../src/index.js"); -} - -describe("@ternent/armour", () => { - it("encrypts and decrypts immediately after import", async () => { - const armour = await loadSourceModule(); - const identity = await createIdentity(); - const plaintext = new TextEncoder().encode("no setup required"); - const ciphertext = await armour.encryptForIdentities({ - identities: [identity], - data: plaintext, - }); - await expect(armour.decryptWithIdentity({ identity, data: ciphertext })).resolves.toEqual( - plaintext, - ); - }); - - it("derives age recipients and secrets from identity objects and strings", async () => { - const armour = await loadSourceModule(); - const identity = await createIdentity("2026-03-17T00:00:00.000Z"); - const serialized = serializeIdentity(identity); - - const recipientFromObject = await armour.recipientFromIdentity(identity); - const recipientFromString = await armour.recipientFromIdentity(serialized); - const secret = await armour.secretKeyFromIdentity(identity); - - expect(recipientFromObject).toMatch(/^age1/); - expect(recipientFromString).toBe(recipientFromObject); - expect(secret).toMatch(/^AGE-SECRET-KEY-1/); - }); - - it("rejects malformed identity input with structured errors", async () => { - const armour = await loadSourceModule(); - - await expect( - armour.recipientFromIdentity('{"format":"ternent-identity","version":"nope"}'), - ).rejects.toMatchObject({ - name: "ArmourIdentityError", - code: "ARMOUR_INVALID_IDENTITY", - }); - }); - - it("encrypts for one identity and decrypts with the same identity", async () => { - const armour = await loadSourceModule(); - const identity = await createIdentity(); - - const ciphertext = await armour.encryptForIdentities({ - identities: [identity], - data: new TextEncoder().encode("hello"), - }); - const plaintext = await armour.decryptWithIdentity({ - identity, - data: ciphertext, - }); - - expect(new TextDecoder().decode(plaintext)).toBe("hello"); - }); - - it("encrypts for multiple identities in one pass", async () => { - const armour = await loadSourceModule(); - const alice = await createIdentity(); - const bob = await createIdentity(); - - const ciphertext = await armour.encryptForIdentities({ - identities: [alice, bob], - data: new TextEncoder().encode("shared"), - }); - const plaintext = await armour.decryptWithIdentity({ - identity: bob, - data: ciphertext, - }); - - expect(new TextDecoder().decode(plaintext)).toBe("shared"); - }); - - it("supports raw recipient passthrough and raw secret decryption", async () => { - const armour = await loadSourceModule(); - const identity = await createIdentity(); - const recipient = await armour.recipientFromIdentity(identity); - const secretKey = await armour.secretKeyFromIdentity(identity); - - const ciphertext = await armour.encryptForRecipients({ - recipients: [recipient], - data: new TextEncoder().encode("raw"), - output: "binary", - }); - const plaintext = await armour.decryptWithSecretKey({ - secretKey, - data: ciphertext, - }); - - expect(new TextDecoder().decode(plaintext)).toBe("raw"); - }); - - it("normalizes recipient validation failures", async () => { - const armour = await loadSourceModule(); - - await expect( - armour.encryptForRecipients({ - recipients: [], - data: new TextEncoder().encode("hello"), - }), - ).rejects.toMatchObject({ - name: "ArmourValidationError", - code: "ARMOUR_EMPTY_RECIPIENTS", - }); - }); - - it("round trips passphrase encryption and rejects wrong passphrases", async () => { - const armour = await loadSourceModule(); - - const ciphertext = await armour.encryptWithPassphrase({ - passphrase: "correct horse battery staple", - data: new TextEncoder().encode("secret"), - }); - const plaintext = await armour.decryptWithPassphrase({ - passphrase: "correct horse battery staple", - data: ciphertext, - }); - - expect(new TextDecoder().decode(plaintext)).toBe("secret"); - - await expect( - armour.decryptWithPassphrase({ - passphrase: "wrong", - data: ciphertext, - }), - ).rejects.toMatchObject({ - name: "ArmourDecryptionError", - code: "ARMOUR_DECRYPT_FAILED", - }); - }); - - it("rejects empty passphrases with structured validation errors", async () => { - const armour = await loadSourceModule(); - - await expect( - armour.encryptWithPassphrase({ - passphrase: "", - data: new TextEncoder().encode("hello"), - }), - ).rejects.toMatchObject({ - name: "ArmourValidationError", - code: "ARMOUR_EMPTY_PASSPHRASE", - }); - }); - - it("round trips text helpers", async () => { - const armour = await loadSourceModule(); - const identity = await createIdentity(); - - const ciphertext = await armour.encryptTextForIdentities({ - identities: [identity], - text: "hello utf8", - }); - const plaintext = await armour.decryptTextWithIdentity({ - identity, - data: ciphertext, - }); - - expect(ciphertext).toContain("-----BEGIN AGE ENCRYPTED FILE-----"); - expect(plaintext).toBe("hello utf8"); - }); +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vite-plus/test"; +import { base64urlnopad } from "@scure/base"; +import { createIdentity, restoreIdentity } from "@ternent/identity"; +import { Encrypter } from "age-encryption"; +import * as api from "../src/index.js"; +import { decrypt, encrypt } from "../src/index.js"; + +const vectors = JSON.parse(readFileSync(new URL("vectors.json", import.meta.url), "utf8")); +const utf8 = (text: string) => new TextEncoder().encode(text); +const owner = () => restoreIdentity(JSON.stringify(vectors.owner)); +const { recipient: groupRecipient, secretKey: groupSecretKey } = vectors.group; + +test("the public interface is encrypt and decrypt", () => { + expect(Object.keys(api).sort()).toEqual(["decrypt", "encrypt"]); +}); - it("accepts ArrayBuffer, Blob, and File-compatible inputs for binary helpers", async () => { - const armour = await loadSourceModule(); - const identity = await createIdentity(); - const fileLike = - typeof File === "undefined" - ? new Blob(["blob data"], { type: "text/plain" }) - : new File(["blob data"], "demo.txt", { type: "text/plain" }); +test("saved native-age ciphertext decrypts with the owner identity and the group key", async () => { + const opened = async (ciphertext: string, key: Parameters[1]) => + JSON.parse(new TextDecoder().decode(await decrypt(base64urlnopad.decode(ciphertext), key))); + const { toOwner, toGroup } = vectors; + expect(await opened(toOwner.ciphertext, await owner())).toEqual(JSON.parse(toOwner.plaintext)); + expect(await opened(toGroup.ciphertext, groupSecretKey)).toEqual(JSON.parse(toGroup.plaintext)); +}); - const ciphertextFromArrayBuffer = await armour.encryptBinaryForIdentities({ - identities: [identity], - data: new TextEncoder().encode("buffer data").buffer, - output: "binary", - }); - const plaintextFromArrayBuffer = await armour.decryptBinaryWithIdentity({ - identity, - data: ciphertextFromArrayBuffer, - }); - const ciphertextFromFile = await armour.encryptBinaryForIdentities({ - identities: [identity], - data: fileLike, - }); - const plaintextFromFile = await armour.decryptBinaryWithIdentity({ - identity, - data: ciphertextFromFile, - }); +test("one call encrypts to several identities and a group, with fresh randomness", async () => { + const alice = await createIdentity(); + const bob = await createIdentity(); + const outsider = await createIdentity(); + const plaintext = utf8("shared"); + const targets = [alice.publicIdentity, bob.publicIdentity, groupRecipient]; + const ciphertext = await encrypt(plaintext, targets); + expect(ciphertext).not.toEqual(await encrypt(plaintext, targets)); + expect(new TextDecoder().decode(ciphertext.subarray(0, 21))).toBe("age-encryption.org/v1"); + for (const key of [alice, bob, groupSecretKey]) { + expect(await decrypt(ciphertext, key)).toEqual(plaintext); + } + await expect(decrypt(ciphertext, outsider)).rejects.toThrow(); +}); - expect(new TextDecoder().decode(plaintextFromArrayBuffer)).toBe("buffer data"); - expect(new TextDecoder().decode(plaintextFromFile)).toBe("blob data"); - }); +test("empty plaintext is valid", async () => { + const identity = await createIdentity(); + const ciphertext = await encrypt(new Uint8Array(), [identity.publicIdentity]); + expect(await decrypt(ciphertext, identity)).toEqual(new Uint8Array()); +}); - it("keeps the package boundary clean", async () => { - const sourceFiles = [ - resolve(packageDir, "src/index.ts"), - resolve(packageDir, "src/identity.ts"), - resolve(packageDir, "src/recipients.ts"), - resolve(packageDir, "src/passphrase.ts"), - resolve(packageDir, "src/text.ts"), - resolve(packageDir, "src/files.ts"), - ]; - const source = (await Promise.all(sourceFiles.map((file) => readFile(file, "utf8")))).join( - "\n", - ); - const armour = await loadSourceModule(); - const identity = await createIdentity(); +test("passphrase encryption round-trips an Identity backup with the exact passphrase", async () => { + const identity = await createIdentity(); + const backup = utf8(identity.export()); + const passphrase = " correct horse "; + const ciphertext = await encrypt(backup, { passphrase }); + const restored = await restoreIdentity( + new TextDecoder().decode(await decrypt(ciphertext, { passphrase })), + ); + expect(restored.publicIdentity).toEqual(identity.publicIdentity); + await expect(decrypt(ciphertext, { passphrase: "correct horse" })).rejects.toThrow(); + await expect(decrypt(ciphertext, identity)).rejects.toThrow(); +}); - expect(source).not.toMatch(/@ternent\/seal-/); - expect(source).not.toMatch(/\benvelope\b/i); - expect(source).not.toMatch(/\b(sign|verify)(Utf8|Bytes)?\b/); - expect(source).not.toMatch(/\bencryptText\b(?!ForIdentities|WithPassphrase)/); - expect(source).not.toMatch(/\bdecryptText\b(?!WithIdentity|WithPassphrase)/); +test("passphrase decryption rejects a scrypt work factor above 20 before deriving a key", async () => { + // age refuses to encrypt at logN 21, so raise the factor in a cheap file's header. + const encrypter = new Encrypter(); + encrypter.setPassphrase("secret"); + encrypter.setScryptWorkFactor(10); + const file = String.fromCharCode(...(await encrypter.encrypt(utf8("x")))); + const edited = file.replace(/(-> scrypt \S+) 10\n/, "$1 21\n"); + expect(edited).not.toBe(file); + const raised = Uint8Array.from(edited, (char) => char.charCodeAt(0)); + const started = performance.now(); + await expect(decrypt(raised, { passphrase: "secret" })).rejects.toThrow(/work factor|logN/i); + expect(performance.now() - started).toBeLessThan(500); +}); - await expect( - armour.encryptForIdentities({ - identities: [identity], - data: new TextEncoder().encode("async"), - }), - ).resolves.toBeInstanceOf(Uint8Array); - }); +test("tampered ciphertext releases no plaintext", async () => { + const identity = await createIdentity(); + const ciphertext = await encrypt(utf8("authentic"), [identity.publicIdentity]); + for (const index of [30, ciphertext.length - 1]) { + const tampered = ciphertext.slice(); + tampered[index] ^= 1; + await expect(decrypt(tampered, identity)).rejects.toThrow(); + } +}); - it("imports from built ESM output without manual path hacks", async () => { - const entryUrl = pathToFileURL(resolve(packageDir, "dist/index.js")).href; - const armour = await import(entryUrl); - const identity = await createIdentity(); +test("invalid inputs reject", async () => { + const identity = await createIdentity(); + const ciphertext = await encrypt(utf8("x"), [groupRecipient]); + const badBinding = { ...identity.publicIdentity, id: (await createIdentity()).publicIdentity.id }; + for (const target of [ + [], + [badBinding], + ["age1notarecipient"], + [groupSecretKey], + { passphrase: "" }, + { passphrase: 1 }, + "age1" as never, + ]) { + await expect(encrypt(utf8("x"), target as never)).rejects.toThrow(); + } + await expect(encrypt("text" as never, [groupRecipient])).rejects.toThrow(); + for (const key of [groupRecipient, groupSecretKey.toLowerCase(), { passphrase: "" }, {}, null]) { + await expect(decrypt(ciphertext, key as never)).rejects.toThrow(); + } +}); - const ciphertext = await armour.encryptForIdentities({ - identities: [identity], - data: new TextEncoder().encode("built package"), - }); - const plaintext = await armour.decryptWithIdentity({ - identity, - data: ciphertext, - }); +test("inputs are captured at call time", async () => { + const identity = await createIdentity(); + const plaintext = utf8("original"); + const targets = [{ ...identity.publicIdentity }]; + const pending = encrypt(plaintext, targets); + plaintext.fill(0); + targets[0].publicKey = "changed"; + const ciphertext = await pending; + const decrypting = decrypt(ciphertext, identity); + ciphertext.fill(0); + expect(await decrypting).toEqual(utf8("original")); +}); - expect(new TextDecoder().decode(plaintext)).toBe("built package"); - }); +test("the native age CLI and Armour read each other's ciphertext", async () => { + const dir = mkdtempSync(join(tmpdir(), "armour-age-")); + try { + const keyFile = join(dir, "key.txt"); + writeFileSync(keyFile, `${groupSecretKey}\n`, { mode: 0o600 }); + const plaintext = utf8("interop"); + const ours = await encrypt(plaintext, [groupRecipient]); + expect( + new Uint8Array(execFileSync("age", ["--decrypt", "-i", keyFile], { input: ours })), + ).toEqual(plaintext); + const native = execFileSync("age", ["--encrypt", "-r", groupRecipient], { input: plaintext }); + expect(await decrypt(new Uint8Array(native), groupSecretKey)).toEqual(plaintext); + } finally { + rmSync(dir, { recursive: true, force: true }); + } }); diff --git a/packages/armour/test/codec.test.ts b/packages/armour/test/codec.test.ts deleted file mode 100644 index c78027d..0000000 --- a/packages/armour/test/codec.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { expect, test } from "vite-plus/test"; -import { ageRecipientFromPublicIdentity, type PrimitiveResult } from "@ternent/identity"; -import { createAgeCodec, identityFromSeed } from "../src/index.js"; - -function value(result: PrimitiveResult): T { - if (!result.ok) throw new Error(result.error.code); - return result.value; -} -test("age codec composes recipients and reader capabilities without Ledger or Concord", async () => { - const alice = value(await identityFromSeed(new Uint8Array(32).fill(4))); - const bob = value(await identityFromSeed(new Uint8Array(32).fill(5))); - const recipients = [value(ageRecipientFromPublicIdentity(alice.publicIdentity))]; - const writer = createAgeCodec({ recipients }); - recipients[0] = value(ageRecipientFromPublicIdentity(bob.publicIdentity)); - const plaintext = new TextEncoder().encode("private payload"); - const encrypted = await writer.encode(plaintext); - expect(await createAgeCodec({ reader: alice }).decode(encrypted)).toEqual(plaintext); - expect(await createAgeCodec({ reader: bob }).decode(encrypted)).toBeNull(); - const tampered = new Uint8Array(encrypted); - tampered[tampered.length - 1] ^= 1; - expect(await createAgeCodec({ reader: alice }).decode(tampered)).toBeNull(); - expect(createAgeCodec()).toEqual({ id: "age" }); - expect(writer.decode).toBeUndefined(); - expect(createAgeCodec({ reader: alice }).encode).toBeUndefined(); - const empty = await writer.encode(new Uint8Array()); - expect(await createAgeCodec({ reader: alice }).decode(empty)).toEqual(new Uint8Array()); -}); -test("invalid configuration rejects and reader implementation exceptions are not hidden as locked data", async () => { - for (const input of [null, [], { recipients: [] }, { recipients: ["bad"] }, { reader: {} }]) - expect(() => createAgeCodec(input as never)).toThrow(); - const codec = createAgeCodec({ - reader: { - decryptAge: async () => { - throw new Error("device unavailable"); - }, - }, - }); - await expect(codec.decode(new Uint8Array([1]))).rejects.toThrow("device unavailable"); - const unavailable = createAgeCodec({ - reader: { - decryptAge: async () => ({ - ok: false, - error: { code: "DEVICE_UNAVAILABLE", message: "device unavailable" }, - }), - }, - }); - await expect(unavailable.decode(new Uint8Array([1]))).rejects.toMatchObject({ - code: "ARMOUR_DECRYPT_FAILED", - }); -}); diff --git a/packages/armour/test/vectors.json b/packages/armour/test/vectors.json new file mode 100644 index 0000000..212f12b --- /dev/null +++ b/packages/armour/test/vectors.json @@ -0,0 +1,26 @@ +{ + "owner": { + "format": "ternent-identity", + "version": "2", + "algorithm": "Ed25519", + "createdAt": "2026-01-01T00:00:00.000Z", + "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", + "keyId": "21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", + "material": { + "kind": "seed", + "seed": "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A" + } + }, + "group": { + "recipient": "age13aqvttdk3ujkyjh9kg2w5an6dmy5mq5a84a4uxk3hfhnugfc9p0sy5p2wh", + "secretKey": "AGE-SECRET-KEY-1QQQSYQCYQ5RQWZQFPG9SCRGWPUGPZYSNZS23V9CCRYDPK8QARE0SVPD6HS" + }, + "toOwner": { + "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBxbmxVekN5c2Y5bDRDVkphd3hKTk1VMFNTL0E3SzJieTc3ejBZenpCc0RrCmtaNkFCMStIRUVpTVBlcWo2NkJEYU1KZnArRTZLR2xBdWIzUmVScFNDNXcKLS0tIFB5Ri9jcHN1VEtkMmRkM1FPOTk3SWNNYnRoTG5sNGU0QVpQWmgrdDhNcDAKgXq1gkuX619OwyMlTXlenSdi2fTdyr_5TNA0C1bHgFZIiYLHOToGaNqFn4o79YpVM46h5qJ7KFPsXyvFmd1pQRfM_63OZKH1T5VSgnW1xm9Vd6SxeYwIhlm9MXvn3be47NcVnsgtiOmbDw8Ns8rX3RyuQ6WGawXHTSxLGMaPc3d0hgRAWPWtUjVh-jEmM2Bab7OHXgffcxnsOIorvwEWYFB9p4bJCY_UrXUSV59v-WvHd0OIEitfA1BMK6abezN2HevfKol19100TMBWzpTLBh8JjVMy_Kp6ruFP8oF_IE_JAgYcgTA3mHo4WCHCd4oJwC_5SncJqa51cltvC0nH7VkMdwOXL-zmE1UPmIOuqBl_zxc8lZeMpya5BiOM5HxNmsBHe_aPH2dhGDGv4_ZdoiYc_LAYFswL86VkG-Nmc9Sa2ZTan6PeLEzTSA8ZesM1b2ob1qkhN8119vq5_Sp71CjXd87ugaopawnU2QQ7E9Q", + "plaintext": "{\"context\":\"concord.audience-key/1\",\"parent\":null,\"nonce\":\"AQEBAQEBAQEBAQEBAQEBAQ\",\"audience\":\"document\",\"epoch\":0,\"identityId\":\"identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9\",\"recipient\":\"age13aqvttdk3ujkyjh9kg2w5an6dmy5mq5a84a4uxk3hfhnugfc9p0sy5p2wh\",\"secret\":\"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHl8\"}" + }, + "toGroup": { + "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSA4dWY3emwyTjRBNGNRTDdEZ0VNRlRWUDI2ZU1vdkc5em95dUFYQVQ0cERZCm1SUG12dkYwb0x5Q29CdGN2eHNHTVdnZ2xhK29LZ2FQZ1RqLzM3azVhMUkKLS0tIGhiM1A0TzN5RTVSa3ZGV0pPK3RkQmowTklHSG9LcDl0a1pYWWkrcFdweWMKBtQhYXvGVT49bAT_6v18BZ_l_3V4ruTZX8JP_rziAqE8HBblmGdydubASHHcPNZ3yrHeFAAFW_Ar3-bldPoB8SDKBoWDhq6f80qQSxdCGgj9O6OT0yWrHs45xZOr-pojDGx4WKYVbdb4VsfwcpnQh52dINB1M_kh75OguP62_lZX2ZJ1bmaB0Wwg-xBV6y1NW8nSP13uaIBaSWCD9-vQgAx_an0Jt1vE-51QRIKAQLwIHg6cVDhhuuX_Bc-2cHRHMW79e3KXlO5OLC81cZODs-erFu1Y76pTRTtbdP8bitTUOf39S8JS-FKYWQmrYlTvSWv2DdnBvi8TOuXJAwK2MAx-7UjPNHBAqYEGu589JHqzrfXJTaPCPK5Zkutg955I5JPfZIMA45JTnIxOEgagN_TbhRr4WWLHRUWI880ax9K2bv0MbNJfH2YA4UtmfWFJW1UW3SV5Vw", + "plaintext": "{\"context\":\"concord.application/1\",\"parent\":\"commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8\",\"nonce\":\"AwMDAwMDAwMDAwMDAwMDAw\",\"model\":{\"id\":\"concord.example.register\",\"version\":1},\"audience\":\"document\",\"epoch\":0,\"event\":{\"type\":\"value.set\",\"version\":1,\"data\":{\"value\":\"hello Concord\"}}}" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8c65e7d..1973afb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -217,6 +217,12 @@ importers: packages/armour: dependencies: + '@noble/curves': + specifier: 2.4.0 + version: 2.4.0 + '@scure/base': + specifier: 2.4.0 + version: 2.4.0 '@ternent/identity': specifier: workspace:^ version: link:../identity From 9db76b8e17a450ebc96ebb534f08ab280f9e26d5 Mon Sep 17 00:00:00 2001 From: samternent Date: Fri, 27 Nov 2026 23:49:58 +0000 Subject: [PATCH 06/24] feat(ledger)!: rewrite as an immutable v2 history with a writer Replace the stateful log, projections, subscriptions and protocol subpath with createLedger, openLedger and createWriter. A history is immutable and issued only by Ledger; a writer stages validated entries and advances on a successful commit. Each commit carries a Seal v1 proof over its body. openLedger accepts only canonical v2 bytes and verifies every proof, linkage and entry rule. maxBytes is the single size limit. The v2 vector lives in the package. Consumers are not yet adapted. Co-Authored-By: Claude Opus 5.5 --- llms.txt | 2 +- packages/ledger/CHANGELOG.md | 42 -- packages/ledger/CLAUDE.md | 36 ++ packages/ledger/README.md | 208 ++----- packages/ledger/llms.txt | 84 +-- packages/ledger/package.json | 10 +- packages/ledger/src/common/errors.ts | 41 -- packages/ledger/src/common/immutable.ts | 10 - packages/ledger/src/common/random.ts | 4 - packages/ledger/src/index.ts | 427 ++++++++++++- packages/ledger/src/ledger.ts | 368 ----------- packages/ledger/src/payload.ts | 89 --- packages/ledger/src/protocol/index.ts | 21 - packages/ledger/src/protocol/json.ts | 186 ------ packages/ledger/src/protocol/types.ts | 15 - packages/ledger/src/protocol/verify.ts | 221 ------- packages/ledger/src/schema.ts | 170 ----- packages/ledger/src/types.ts | 89 --- packages/ledger/test/ledger.test.ts | 619 ++++++++----------- packages/ledger/test/payload.test.ts | 136 ---- packages/ledger/test/vectors.json | 95 +++ packages/ledger/test/vectors/signed-log.json | 70 --- packages/ledger/vite.config.ts | 2 +- pnpm-lock.yaml | 6 + 24 files changed, 905 insertions(+), 2046 deletions(-) delete mode 100644 packages/ledger/CHANGELOG.md create mode 100644 packages/ledger/CLAUDE.md delete mode 100644 packages/ledger/src/common/errors.ts delete mode 100644 packages/ledger/src/common/immutable.ts delete mode 100644 packages/ledger/src/common/random.ts delete mode 100644 packages/ledger/src/ledger.ts delete mode 100644 packages/ledger/src/payload.ts delete mode 100644 packages/ledger/src/protocol/index.ts delete mode 100644 packages/ledger/src/protocol/json.ts delete mode 100644 packages/ledger/src/protocol/types.ts delete mode 100644 packages/ledger/src/protocol/verify.ts delete mode 100644 packages/ledger/src/schema.ts delete mode 100644 packages/ledger/src/types.ts delete mode 100644 packages/ledger/test/payload.test.ts create mode 100644 packages/ledger/test/vectors.json delete mode 100644 packages/ledger/test/vectors/signed-log.json diff --git a/llms.txt b/llms.txt index 4386e36..77a5ef5 100644 --- a/llms.txt +++ b/llms.txt @@ -6,7 +6,7 @@ ## Choose the interface - [Concord](packages/concord/llms.txt): build an application using typed commands, events, authority, private groups and replay. -- [Ledger](packages/ledger/llms.txt): build a standalone signed log without Concord application or permission semantics. +- [Ledger](packages/ledger/llms.txt): a signed, append-only history of JSON entries, verified on open, without Concord's application or permission rules. - [Identity](packages/identity/llms.txt): create, back up, restore or recover one identity; sign and verify bytes. - [Armour](packages/armour/llms.txt): encrypt and decrypt bytes with age for identities, groups and passphrases. - [Seal](packages/seal/llms.txt): sign and verify a detached proof over any bytes' hash; use the Node CLI. diff --git a/packages/ledger/CHANGELOG.md b/packages/ledger/CHANGELOG.md deleted file mode 100644 index 64af554..0000000 --- a/packages/ledger/CHANGELOG.md +++ /dev/null @@ -1,42 +0,0 @@ -# @ternent/ledger - -## 0.2.0 - -### Minor Changes - -- e5c6808: Establish the five-library alpha: standalone Identity, Armour, Ledger and Seal, - with Concord composing Ledger's common signed container, authority, independent - encrypted groups, command drafts and application replay. The common container - deliberately replaces the previous Concord alpha wire format. - - Armour uses typage and offers explicit payload codecs for Ledger. Uncommitted - entries and command intents stay in memory; consumers own draft recovery and - storage publication. Verify public imports, declarations, CLI behavior and exact - candidate bytes before publication. - -### Patch Changes - -- 7d55bda: Include agent interface guides with public imports, runnable examples, lifecycle and - error contracts, and host-owned storage/recovery behavior. -- Updated dependencies [7d55bda] -- Updated dependencies [e5c6808] - - @ternent/identity@0.6.0 - -## 0.2.0-alpha.1 - -### Minor Changes - -- e5c6808: Establish the five-library alpha: standalone Identity, Armour, Ledger and Seal, - with Concord composing Ledger's common signed container, authority, independent - encrypted groups, command drafts and application replay. The common container - deliberately replaces the previous Concord alpha wire format. - - Armour uses typage and offers explicit payload codecs for Ledger. Uncommitted - entries and command intents stay in memory; consumers own draft recovery and - storage publication. Verify public imports, declarations, CLI behavior and exact - candidate bytes before publication. - -### Patch Changes - -- Updated dependencies [e5c6808] - - @ternent/identity@0.6.0-alpha.1 diff --git a/packages/ledger/CLAUDE.md b/packages/ledger/CLAUDE.md new file mode 100644 index 0000000..6e8c6a1 --- /dev/null +++ b/packages/ledger/CLAUDE.md @@ -0,0 +1,36 @@ +# Working on Ledger + +Ledger is one file, `src/index.ts`: create, open and a writer over an immutable +history. Keep it that small. + +## What Ledger owns + +- The v2 document format, canonical JSON, commit and entry IDs, and verification of a + whole history on open. `test/vectors.json` fixes the bytes and IDs. A change to them + is a new format version. +- Staging and the writer lifecycle: commit advances the writer, an empty commit + rejects, mutations throw while a commit runs, and failure keeps history and staging. +- Not signatures: Seal builds and checks each proof. Not meaning: projections, + permissions and storage belong to Concord or the application. + +## How the code stays small + +- Histories are issued only by Ledger. The private `#records` field is the brand, and + `internals` is the only way to extend one. Never add a public method that accepts + entries or records, or a lookalike could become trusted history. +- Validate where data enters: `prepareEntries` for appended input, `openLedger` for + bytes. Committed entries were validated when staged and aren't checked again. +- Open accepts only canonical bytes, so there is no lenient parser. Canonical JSON is + written by hand because JavaScript objects list integer-like keys ("2", "10") + numerically, which breaks sorting by rebuilding an object. +- Capture input by encoding it canonically and parsing it back: the copy is detached + and already validated. Do it before the first `await`. +- `maxBytes` is the only limit. Add another only for a demonstrated failure. +- No projections, subscriptions, replay helpers, error classes or subpath exports. + +## Checks + +Run `pnpm run check` in this package under the Node version in `.node-version`. Test +the observable contract: the vector, tampering, linkage, canonical-only import, +lookalike histories, the writer lifecycle and `maxBytes` at the boundary. Update +`README.md` and `llms.txt` with any interface change. diff --git a/packages/ledger/README.md b/packages/ledger/README.md index e8f309f..e4a6b8f 100644 --- a/packages/ledger/README.md +++ b/packages/ledger/README.md @@ -1,150 +1,78 @@ # @ternent/ledger -[Agent interface guide](llms.txt): public imports, examples and lifecycle contracts. +[Agent interface guide](llms.txt): public imports, examples and contracts. -A standalone signed append-only log. Create or load a log, stage JSON entries, -commit them, verify the history and replay it into a projection. Ledger has no -dependency on Concord, Armour, Seal, a framework, storage or Node filesystem APIs. +A signed, append-only history of JSON entries. Each commit is signed with a Seal proof +by an Identity. Ledger verifies history; your application decides what it means. ```ts -import { generateSigner } from "@ternent/identity"; -import { createLedger } from "@ternent/ledger"; - -const signer = await generateSigner(); -if (!signer.ok) throw new Error(signer.error.code); - -const log = await createLedger({ signer: signer.value }); -await log.create({ metadata: { title: "Readings" } }); -await log.append({ kind: "temperature", payload: { value: 21 } }); -await log.commit({ metadata: { source: "sensor" } }); - -const snapshot = await log.export(); -const reader = await createLedger(); -await reader.load(snapshot); -const report = await reader.verify(); -const entries = await reader.replay(); +import { createIdentity } from "@ternent/identity"; +import { createLedger, createWriter, openLedger } from "@ternent/ledger"; + +const alice = await createIdentity(); +const genesis = await createLedger({ signer: alice, metadata: { model: "expenses" } }); + +const writer = createWriter(genesis, alice); +writer.append({ kind: "expense.recorded", payload: { amount: 2500 } }); +const history = await writer.commit(); + +const bytes = history.export(); +const reopened = await openLedger(bytes); // verifies every commit +for (const commit of reopened.commits) { + for (const entry of commit.entries) apply(entry, commit.proof.signer); +} ``` -`create()` immediately signs a genesis commit. It is empty by default; an `entries` -array can supply initial records atomically. Advanced encrypted-envelope builders -may supply a 16-byte base64url `nonce` when appending; duplicate nonces in one commit -are rejected. `append()` and `appendMany()` -stage entries and update the local preview. `export()` and `verify()` concern the -committed snapshot only. Replay includes staged entries by default; pass -`{ includeStaged: false }` for committed-only reconstruction. Each replayed entry -has `committed` and `commitId` fields, so a preview never masquerades as signed history. -`clearStaged()` discards the preview without changing committed history. - -Supply `initialProjection` and a synchronous `projector(projection, entry)` to derive -your own state. Without them, replay returns the ordered entries. `getState()` gives -a detached, frozen state; `subscribe()` observes successful changes. Projectors must -be pure and return portable JSON. Callbacks must not await operations on the same Ledger handle. - -Mutations are serialized. Inputs are captured when called. Failed validation, -projection or signing preserves the previous committed snapshot and staged entries. -Loading while entries are staged rejects with `DRAFT_PENDING`; commit or clear them -first. Validation and signing failures reject with `Fault`, whose `finding` provides a code -and phase. Projector exceptions propagate while preserving the previous state. -Observer exceptions cannot roll back a published state. `destroy()` closes the local -handle; it does not erase exported history or data held elsewhere. - -The `ledger` v1 format uses strict canonical JSON, content-addressed entries and -commits, parent linkage and Ed25519 signatures. A commit signature binds its signer, -ordered entry IDs, timestamp and metadata. Entry authors bind to their commit signer. -An explicit signer can append to any valid log: membership, permissions, encryption -and application rules belong to the host or Concord. Store opaque ciphertext as JSON -when composing Ledger directly with an encryption library. - -`verifyLedger(bytes)` checks the full signed history without opening a handle. -`compareLedgers(a, b)` reports equal, ahead, behind, diverged or unrelated snapshots; -it never merges or chooses a head. Integrity proves neither freshness nor completeness -without a remembered head or external anchor. The host owns storage and publication. - -The specialist `/protocol` export supplies the same concrete Ledger codec, identifiers, -signature subjects and verifier, without loading the authoring lifecycle. Concord -consumes Ledger's lifecycle and puts its framework records in this same container; -it does not maintain a second signed container or commit engine. A Ledger reader -requires no Concord declarations, model, permissions or group keys to verify history. - -## Optional payload codecs - -Ledger supports Armour integration through explicit payload composition. It has no -Armour dependency, recipient configuration, key management or automatic decryption. -`encodePayload(data, codec)` turns portable JSON into a versioned JSON envelope for -the ordinary `append()` API. `decodePayload(data, codec?)` reads that envelope after -replay. A codec is just an `id` and optional asynchronous byte `encode`/`decode` -functions; there is no plugin registry or lifecycle to configure. -`encodePayload` requires a `LedgerPayloadEncoder`, so reader-only or unknown -encoding capabilities are rejected by TypeScript. `LedgerPayloadDecoder` describes -a guaranteed decoder; the general `LedgerPayloadCodec` keeps both methods optional -for inspection and locked-result handling. +## History -```ts -import { encodePayload, decodePayload } from "@ternent/ledger"; -import { ageRecipientFromPublicIdentity } from "@ternent/identity"; -import { createAgeCodec, withAgeDecryption } from "@ternent/armour"; - -const identity = withAgeDecryption(signer.value); -const recipient = ageRecipientFromPublicIdentity(identity.publicIdentity); -if (!recipient.ok) throw new Error(recipient.error.code); -const codec = createAgeCodec({ recipients: [recipient.value], reader: identity }); - -await log.append({ - kind: "private-note", - payload: await encodePayload({ text: "Only the recipients can read this" }, codec), -}); -await log.commit(); - -const entry = (await log.replay()).at(-1)!; -const result = await decodePayload(entry.payload.data, codec); -// { status: "decoded", data: { text: "Only the recipients can read this" } } -const withoutKeys = await decodePayload(entry.payload.data); -// { status: "locked", codec: "age" } +A `History` is immutable and only comes from `createLedger`, `openLedger` or a +writer's `commit`. It has `documentId` (the genesis commit ID), `head`, and `commits` +in order, starting with genesis. Each commit has its `id`, `parent`, `entries`, optional +`metadata`, and its Seal `proof`, which carries the signer and claimed `createdAt`. + +`history.compare(other)` returns `"equal"`, `"ahead"`, `"behind"`, `"diverged"` or +`"unrelated"`. Ledger never merges diverged histories. `history.export()` returns the +canonical document bytes. + +## Writer + +`createWriter(history, signer)` stages entries on top of a history. + +- `append(entry | entries)` validates and copies the whole batch before staging any of it. +- `commit(metadata?)` signs the staged entries, advances `writer.history` and returns + the new history. Earlier histories are unchanged. Committing with nothing staged rejects. +- While a commit runs, `append`, `discard` and `commit` throw; `history` and `staged` + still read the previous state. A failed commit keeps both, so you can retry. + +An entry is `{ kind, payload, meta?, nonce? }`. `kind` is 1–128 characters, `payload` +is any JSON value, `meta` a JSON object. A nonce is generated unless you supply 16 bytes +of base64url. JSON here means null, booleans, strings, safe integers, arrays and plain +objects. + +## Trust and limits + +A valid history proves who signed each commit and that nothing was changed or +reordered. It doesn't say whether a signer was allowed to write: that is the +application's rule. It can't detect a rolled-back or withheld copy either; compare +with a head you remember. + +`openLedger` accepts only the exact canonical bytes that `export()` writes. The one +limit is `maxBytes` (default 16 MiB), set on `createLedger` or `openLedger` and +inherited by writers. + +## Format + +The document is `{"commits":[…],"format":"ledger","version":2}`, as canonical JSON +(keys sorted by UTF-16 code units, no whitespace). Each commit is `{ body, proof }`, +where `body` is `{ parent, nonce, entries, metadata? }`. + +```text +proof = Seal proof over UTF8("ledger.commit/2") || 0x00 || body +commitId = "commit:" + sha256hex(UTF8("ledger.commit-id/2") || 0x00 || proof) +entryId = "entry:" + sha256hex(UTF8("ledger.entry-id/2") || 0x00 || { author, entry, parent }) ``` -Plain JSON returns `{ status: "plain", data }`. A missing or different codec, an -encode-only codec, or a decoder returning `null` produces a locked result. Armour -returns `null` when its reader cannot authenticate/decrypt the ciphertext; this does -not distinguish a wrong key from malformed ciphertext. Codec exceptions propagate. -Invalid envelopes or decoded JSON reject. Encoding failures reject before append; -there is no plaintext fallback. The helpers use Ledger's portable JSON rules and -default byte/depth limits; their optional last argument accepts `maxBytes` and -`maxDepth`. Limits apply to both decoded JSON and the encoded envelope. - -The envelope has exactly `format: "ledger-payload"`, `version: 1`, `codec` and -canonical base64url `data`. This marker is reserved within payloads decoded by this -helper. The log treats it as opaque JSON; verification, commits, export and raw -replay require no codec. Decoding never modifies signed bytes or establishes their -trust. Only payload data is encrypted: entry kind, author, timestamps, metadata and -history structure remain visible. The host decides which decoded data to project; -Ledger's synchronous projector continues to receive the recorded payload. - -Staged entries stay in a simple in-memory array. The consumer chooses when to commit -and owns any draft autosave or recovery. Ledger has no draft persistence adapter, -recovery snapshot or restore API. Committed `export()` remains signed-history only; -external storage and push/pull workflows exchange committed snapshots. See -[the persistence decision](../../docs/adr/0019-keep-draft-persistence-with-consumers.md). -No historical `concord-ledger` or former Concord-alpha import adapter is included. - -## Container format - -The container has exactly `format: "ledger"`, `version: 1`, `documentId`, `head`, -ordered `commits` and ordered `entries`. The genesis commit defines `documentId`; -`head` is the last commit. Every committed entry is referenced exactly once in order. -Records and subjects are closed objects; `meta`, commit `metadata` and payload data -are the explicit JSON slots. Timestamps are signed canonical UTC ISO strings, while -parent linkage and array order determine history order. - -Given strict canonical JSON bytes `C(subject)`, IDs are lowercase SHA-256: - -- Entry: `entry:` + SHA-256(UTF8(`ledger.entry/1`) + NUL + `C(entry.subject)`). -- Commit: `commit:` + SHA-256(UTF8(`ledger.commit/1`) + NUL + `C(commit.subject)`). -- Signature: Ed25519 over UTF8(`ledger.signature/1`) + NUL + `C(commit.subject)`. - -The commit suite is `ledger-ed25519-v1`. Nonces are 16 bytes; signatures are 64 bytes; -wire bytes use canonical unpadded base64url. Entry authors must equal their commit -signer's identity ID. Hashes include the full subjects: metadata, parent links, -nonces, timestamps and ordered entry IDs. Public types define the exact record fields. - -Build and test with the repository's pinned toolchain. Installed-package checks cover -Node 22.18, 24 and 26, browser execution, declarations and isolated imports. ISC licensed. +Genesis has a null parent and may be empty; every later commit names the previous +commit and has at least one entry. Entry nonces are unique within a commit. + +License: ISC. diff --git a/packages/ledger/llms.txt b/packages/ledger/llms.txt index a61a1a1..34816be 100644 --- a/packages/ledger/llms.txt +++ b/packages/ledger/llms.txt @@ -1,67 +1,33 @@ # @ternent/ledger -> Standalone signed append-only history. Staging and committed history are distinct. +> A signed, append-only history of JSON entries, verified on open. -Stable interface: `npm install @ternent/ledger@0.2.0 @ternent/identity@0.6.0`. -[Public README](https://github.com/ternent/core/blob/main/packages/ledger/README.md). -Declarations: `dist/index.d.ts`, `dist/protocol/index.d.ts` and referenced types. - -## Create, stage, commit and reopen +Three exports from the package root: `createLedger`, `openLedger`, `createWriter`. +Types: `History`, `Writer`, `Commit`, `Entry`, `EntryInput`, `Json`, `JsonObject`, +`Signer`, `Relationship`. Declarations: `dist/index.d.ts`. ```ts -import { generateSigner } from "@ternent/identity"; -import { createLedger, encodeJson, verifyLedger } from "@ternent/ledger"; -const created = await generateSigner(); -if (!created.ok) throw new Error(created.error.code); -const log = await createLedger({ signer: created.value }); -await log.create(); -await log.append({ kind: "reading", payload: { value: 21 } }); -const preview = await log.replay(); -await log.commit(); -const snapshot = await log.export(); -const bytes = encodeJson(snapshot); -const report = await verifyLedger(bytes); -if (report.integrity !== "valid") throw new Error("Invalid history"); -const reader = await createLedger(); -await reader.import(bytes); -const committed = await reader.replay({ includeStaged: false }); -``` - -`create()` immediately signs genesis. `append`/`appendMany` stage entries; `commit` -signs them together. `export()` returns a committed snapshot object, not bytes; -`encodeJson` converts it to portable bytes. `load(snapshot)` accepts an object; -`import(bytes)` accepts the encoded container. Failed operations preserve history -and staged work. Loading while staged rejects DRAFT_PENDING. `clearStaged()` drops -staging. Staging is volatile and never exported. - -Replay includes staged entries by default; each item marks committed and commitId. -Use includeStaged false for committed reconstruction. Optional `initialProjection` -and synchronous pure `projector(projection, entry)` derive application data. -`getState()` is detached/frozen; `subscribe()` observes successful changes; -`destroy()` closes the handle. Callbacks must not reenter the mutation queue. -Validation/signing failures reject Fault with a structured finding; projector errors -propagate. This differs from Concord's structured mutation results. +import { createIdentity } from "@ternent/identity"; +import { createLedger, createWriter, openLedger } from "@ternent/ledger"; -## Trust and composition +const alice = await createIdentity(); +let history = await createLedger({ signer: alice }); +const writer = createWriter(history, alice); +writer.append({ kind: "note.added", payload: { text: "hello" } }); +history = await writer.commit(); -Root exports lifecycle, payload helpers and protocol helpers. `/protocol` exposes -canonicalize, encodeJson, parseJson, inspectLedger, verifyLedger, compareLedgers, -hashLedgerEntry, hashLedgerCommit and ledgerSignatureMessage without the lifecycle. -Verify original imported bytes; do not parse/reserialize with JSON.parse first. -Ledger verifies the full signed linear history and signer/author binding. It has no -membership policy: a supplied signer can append to a valid log. Use Concord for -application authority, encrypted groups and command semantics. - -Portable JSON uses safe integers (no fractions, unsafe integers or negative zero), -valid Unicode, dense arrays and plain objects; closed record schemas apply. Use -these APIs for canonical bytes, IDs and signatures rather than recreating them. -compareLedgers reports equal/ahead/behind/diverged/unrelated, without merging or -selecting a head. A valid signature does not establish freshness. - -## Optional encryption +const reopened = await openLedger(history.export()); +const entries = reopened.commits.flatMap((commit) => commit.entries); +``` -`encodePayload(data, codec)` and `decodePayload(data, codec?)` compose explicit -byte codecs such as Armour's createAgeCodec. Decode yields plain, decoded or locked. -Raw replay still returns the stored envelope at entry.payload.data. Missing codecs -never invent plaintext. Ledger neither distributes keys nor automatically decrypts. -Keep secrets, storage, synchronization and draft recovery with the host. +- Histories are immutable and only come from Ledger. Don't build or spread one. +- Read entries from `history.commits[i].entries`. The signer is `commit.proof.signer`; + the claimed time is `commit.proof.createdAt`. Put event time in your payload if needed. +- Ledger keeps no derived state. Reduce entries into your own state. +- `writer.commit()` rejects if nothing is staged, and on failure keeps the staged entries. + Don't call `append`, `discard` or `commit` while a commit is pending; they throw. +- Decide in your app whether a signer may write. Ledger only proves who signed. +- `openLedger` accepts only canonical bytes from `export()`. Store and send those bytes as-is. +- One limit: `maxBytes` (default 16 MiB) on `createLedger` and `openLedger`. +- Values must be JSON with safe integers only: no floats, `undefined`, `Date` or class instances. +- Errors are ordinary `Error`/`TypeError`/`RangeError` with a message; there are no codes. diff --git a/packages/ledger/package.json b/packages/ledger/package.json index 1d22728..8d942bd 100644 --- a/packages/ledger/package.json +++ b/packages/ledger/package.json @@ -1,7 +1,7 @@ { "name": "@ternent/ledger", "version": "0.2.0", - "description": "Standalone signed append-only logs with staging, commits, verification and replay", + "description": "A signed, append-only history of JSON entries", "license": "ISC", "repository": { "type": "git", @@ -22,10 +22,6 @@ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" - }, - "./protocol": { - "types": "./dist/protocol/index.d.ts", - "import": "./dist/protocol/index.js" } }, "publishConfig": { @@ -42,7 +38,9 @@ }, "dependencies": { "@noble/hashes": "2.4.0", - "@ternent/identity": "workspace:^" + "@scure/base": "2.4.0", + "@ternent/identity": "workspace:^", + "@ternent/seal": "workspace:^" }, "devDependencies": { "typescript": "npm:@typescript/typescript6@6.0.2", diff --git a/packages/ledger/src/common/errors.ts b/packages/ledger/src/common/errors.ts deleted file mode 100644 index 1aef1f2..0000000 --- a/packages/ledger/src/common/errors.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { JsonObject } from "../protocol/types.js"; - -export type HistoryError = { - code: string; - phase: string; - message: string; - path?: string; - commitId?: string; - entryId?: string; - details?: Readonly; -}; -export type Result = { ok: true; value: T } | { ok: false; error: E }; -export const ok = (value: T): Result => ({ ok: true, value }); -export const error = (code: string, phase: string, path?: string): HistoryError => ({ - code, - phase, - message: code.replaceAll("_", " ").toLowerCase(), - ...(path === undefined ? {} : { path }), -}); -export class Fault extends Error { - constructor(readonly finding: HistoryError) { - super(finding.code); - } -} -export function fail(code: string, phase = "protocol", path?: string): never { - throw new Fault(error(code, phase, path)); -} -export function caught(cause: unknown, fallback: string, phase: string): HistoryError { - return cause instanceof Fault ? cause.finding : error(fallback, phase); -} -export function attempt( - body: () => T, - fallback = "SCHEMA_INVALID", - phase = "protocol", -): Result { - try { - return ok(body()); - } catch (cause) { - return { ok: false, error: caught(cause, fallback, phase) }; - } -} diff --git a/packages/ledger/src/common/immutable.ts b/packages/ledger/src/common/immutable.ts deleted file mode 100644 index c08803b..0000000 --- a/packages/ledger/src/common/immutable.ts +++ /dev/null @@ -1,10 +0,0 @@ -export function freeze(value: T): T { - if (value && typeof value === "object" && !Object.isFrozen(value)) { - for (const item of Object.values(value)) freeze(item); - Object.freeze(value); - } - return value; -} -export function detached(value: T): T { - return freeze(structuredClone(value)); -} diff --git a/packages/ledger/src/common/random.ts b/packages/ledger/src/common/random.ts deleted file mode 100644 index c51502a..0000000 --- a/packages/ledger/src/common/random.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { encodeBase64Url } from "@ternent/identity"; -export function nonce(): string { - return encodeBase64Url(crypto.getRandomValues(new Uint8Array(16))); -} diff --git a/packages/ledger/src/index.ts b/packages/ledger/src/index.ts index 9d51b20..35366ca 100644 --- a/packages/ledger/src/index.ts +++ b/packages/ledger/src/index.ts @@ -1,28 +1,399 @@ -export { createLedger } from "./ledger.js"; -export { encodePayload, decodePayload } from "./payload.js"; -export type { - LedgerPayloadCodec, - LedgerPayloadEncoder, - LedgerPayloadDecoder, - LedgerEncodedPayload, - LedgerDecodedPayload, -} from "./payload.js"; -export type * from "./types.js"; -export { canonicalize, encodeJson, parseJson, Fault } from "./protocol/index.js"; -export type { - Json, - JsonObject, - CommitId, - EntryId, - VerificationReport, - Relationship, - HistoryError, -} from "./protocol/index.js"; -export { - inspectLedger, - ledgerSignatureMessage, - verifyLedger, - compareLedgers, - hashLedgerEntry, - hashLedgerCommit, -} from "./protocol/index.js"; +import { sha256 } from "@noble/hashes/sha2.js"; +import { base64urlnopad, hex } from "@scure/base"; +import { validatePublicIdentity, type Identity } from "@ternent/identity"; +import { createSealHash, createSealProof, verifySealProof, type SealProof } from "@ternent/seal"; + +export type Json = null | boolean | number | string | readonly Json[] | JsonObject; +export type JsonObject = { readonly [key: string]: Json }; +export type Signer = Pick; + +export type EntryInput = { + readonly kind: string; + readonly payload: Json; + readonly nonce?: string; + readonly meta?: JsonObject; +}; +export type Entry = EntryInput & { readonly id: `entry:${string}`; readonly nonce: string }; +export type Commit = { + readonly id: `commit:${string}`; + readonly parent: `commit:${string}` | null; + readonly nonce: string; + readonly metadata?: JsonObject; + readonly entries: readonly Entry[]; + readonly proof: SealProof; +}; +export type Relationship = "equal" | "ahead" | "behind" | "diverged" | "unrelated"; + +export interface History { + readonly documentId: `commit:${string}`; + readonly head: `commit:${string}`; + readonly commits: readonly Commit[]; + compare(other: History): Relationship; + export(): Uint8Array; +} + +export interface Writer { + readonly history: History; + readonly staged: readonly Entry[]; + append(input: EntryInput | readonly EntryInput[]): void; + discard(): void; + commit(metadata?: JsonObject): Promise; +} + +const DEFAULT_MAX_BYTES = 16 * 1024 * 1024; +const ENVELOPE = ['{"commits":[', '],"format":"ledger","version":2}'] as const; +const ISSUE = Symbol("issue"); +const encoder = new TextEncoder(); + +type Internals = { records: readonly string[]; size: number; maxBytes: number }; +// Module-private access to a history's stored records, so only Ledger can extend one. +let internals: (history: LedgerHistory) => Internals; + +class LedgerHistory implements History { + readonly documentId: `commit:${string}`; + readonly head: `commit:${string}`; + readonly commits: readonly Commit[]; + readonly #records: readonly string[]; + readonly #size: number; + readonly #maxBytes: number; + + constructor(key: symbol, commits: Commit[], records: string[], size: number, maxBytes: number) { + if (key !== ISSUE) throw new TypeError("Histories come from createLedger or openLedger"); + this.commits = Object.freeze(commits); + this.documentId = commits[0].id; + this.head = commits[commits.length - 1].id; + this.#records = Object.freeze(records); + this.#size = size; + this.#maxBytes = maxBytes; + Object.freeze(this); + } + + static isIssued(value: unknown): value is LedgerHistory { + return typeof value === "object" && value !== null && #records in value; + } + + compare(other: History): Relationship { + if (!LedgerHistory.isIssued(other)) throw new TypeError("Compare needs a Ledger history"); + const ours = this.commits; + const theirs = other.commits; + if (ours[0].id !== theirs[0].id) return "unrelated"; + let shared = 1; + while ( + shared < ours.length && + shared < theirs.length && + ours[shared].id === theirs[shared].id + ) { + shared += 1; + } + if (shared === ours.length && shared === theirs.length) return "equal"; + if (shared === theirs.length) return "ahead"; + if (shared === ours.length) return "behind"; + return "diverged"; + } + + export(): Uint8Array { + return encoder.encode(`${ENVELOPE[0]}${this.#records.join(",")}${ENVELOPE[1]}`); + } + + static { + internals = (history) => ({ + records: history.#records, + size: history.#size, + maxBytes: history.#maxBytes, + }); + } +} + +export async function createLedger(input: { + signer: Signer; + entries?: readonly EntryInput[]; + metadata?: JsonObject; + maxBytes?: number; +}): Promise { + const signer = captureSigner(input.signer); + const entries = prepareEntries(input.entries ?? [], null, signer.publicIdentity.id, []); + const metadata = input.metadata === undefined ? undefined : captureObject(input.metadata); + const maxBytes = resolveMaxBytes(input.maxBytes); + return appendCommit(null, signer, entries, metadata, maxBytes); +} + +export async function openLedger( + bytes: Uint8Array, + options: { maxBytes?: number } = {}, +): Promise { + const maxBytes = resolveMaxBytes(options.maxBytes); + if (!(bytes instanceof Uint8Array)) throw new TypeError("openLedger needs bytes"); + if (bytes.length > maxBytes) throw new RangeError(`Ledger is larger than ${maxBytes} bytes`); + const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes); + const document: unknown = JSON.parse(text); + // Accepting only canonical bytes gives each document one representation and + // rejects duplicate keys, non-canonical numbers and escapes, and a BOM. + if (canonical(document) !== text) throw new Error("Ledger bytes are not canonical"); + if ( + !hasExactKeys(document, ["commits", "format", "version"]) || + document.format !== "ledger" || + document.version !== 2 || + !Array.isArray(document.commits) || + document.commits.length === 0 + ) { + throw new Error("Not a version 2 ledger"); + } + + const commits: Commit[] = []; + const records: string[] = []; + for (const [index, record] of document.commits.entries()) { + if (!hasExactKeys(record, ["body", "proof"])) throw new Error(`Commit ${index} is malformed`); + const body = readBody(record.body, commits.at(-1)?.id ?? null); + const proof = record.proof as SealProof; + const verification = await verifySealProof(proof, bodyBytes(body)); + if (!verification.valid) throw new Error(`Commit ${index} has an invalid proof`); + const author = proof.signer.id; + const entries = body.entries.map((entry) => withId(entry, body.parent, author)); + commits.push(makeCommit(body, entries, proof)); + records.push(canonical(record)); + } + return new LedgerHistory(ISSUE, commits, records, bytes.length, maxBytes); +} + +export function createWriter(history: History, signer: Signer): Writer { + if (!LedgerHistory.isIssued(history)) throw new TypeError("createWriter needs a Ledger history"); + const author = captureSigner(signer); + let current = history; + let staged: readonly Entry[] = Object.freeze([]); + let committing = false; + const idle = (action: string) => { + if (committing) throw new Error(`Cannot ${action} while a commit is in progress`); + }; + + return Object.freeze({ + get history() { + return current; + }, + get staged() { + return staged; + }, + append(input: EntryInput | readonly EntryInput[]) { + idle("append"); + const batch = Array.isArray(input) ? input : [input as EntryInput]; + const prepared = prepareEntries(batch, current.head, author.publicIdentity.id, staged); + if (prepared.length > 0) staged = Object.freeze([...staged, ...prepared]); + }, + discard() { + idle("discard"); + staged = Object.freeze([]); + }, + async commit(metadata?: JsonObject) { + idle("commit"); + if (staged.length === 0) throw new Error("Nothing is staged"); + const captured = metadata === undefined ? undefined : captureObject(metadata); + committing = true; + try { + current = await appendCommit(current, author, staged, captured); + staged = Object.freeze([]); + return current; + } finally { + committing = false; + } + }, + }); +} + +// Signs a commit over already validated entries and returns the extended history. +// The previous history is unchanged. +async function appendCommit( + previous: LedgerHistory | null, + signer: Signer, + entries: readonly Entry[], + metadata: JsonObject | undefined, + maxBytesForGenesis = DEFAULT_MAX_BYTES, +): Promise { + const { records, size, maxBytes } = previous + ? internals(previous) + : { records: [], size: 0, maxBytes: maxBytesForGenesis }; + const body: Body = { + parent: previous?.head ?? null, + nonce: base64urlnopad.encode(crypto.getRandomValues(new Uint8Array(16))), + entries: entries.map(({ id: _id, ...entry }) => entry), + ...(metadata === undefined ? {} : { metadata }), + }; + const proof = await createSealProof({ + signer, + subject: { hash: await createSealHash(bodyBytes(body)) }, + }); + const record = canonical({ body, proof }); + const nextSize = + (previous ? size + 1 : encoder.encode(ENVELOPE.join("")).length) + + encoder.encode(record).length; + if (nextSize > maxBytes) throw new RangeError(`Ledger would exceed ${maxBytes} bytes`); + return new LedgerHistory( + ISSUE, + [...(previous?.commits ?? []), makeCommit(body, entries, proof)], + [...records, record], + nextSize, + maxBytes, + ); +} + +type StoredEntry = { nonce: string; kind: string; payload: Json; meta?: JsonObject }; +type Body = { + parent: `commit:${string}` | null; + nonce: string; + entries: StoredEntry[]; + metadata?: JsonObject; +}; + +function makeCommit(body: Body, entries: readonly Entry[], proof: SealProof): Commit { + const id = `commit:${digest("ledger.commit-id/2", canonical(proof))}` as const; + return deepFreeze({ id, ...body, entries: [...entries], proof }); +} + +function bodyBytes(body: Body): Uint8Array { + return encoder.encode(`ledger.commit/2\0${canonical(body)}`); +} + +function withId(entry: StoredEntry, parent: string | null, author: string): Entry { + const id = `entry:${digest("ledger.entry-id/2", canonical({ author, entry, parent }))}` as const; + return deepFreeze({ ...entry, id }); +} + +function digest(domain: string, value: string): string { + return hex.encode(sha256(encoder.encode(`${domain}\0${value}`))); +} + +// Validates and copies a batch before any of it is staged. Nonces must be unique +// within the commit, including against entries already staged. +function prepareEntries( + inputs: readonly EntryInput[], + parent: string | null, + author: string, + staged: readonly Entry[], +): Entry[] { + if (!Array.isArray(inputs)) throw new TypeError("Entries must be an array"); + const nonces = new Set(staged.map((entry) => entry.nonce)); + return inputs.map((input) => { + const { kind, payload, nonce, meta } = input; + const entry = readEntry({ + nonce: nonce ?? base64urlnopad.encode(crypto.getRandomValues(new Uint8Array(16))), + kind, + payload: capture(payload), + ...(meta === undefined ? {} : { meta: captureObject(meta) }), + }); + if (nonces.has(entry.nonce)) throw new Error(`Duplicate entry nonce ${entry.nonce}`); + nonces.add(entry.nonce); + return withId(entry, parent, author); + }); +} + +function readBody(value: unknown, parent: `commit:${string}` | null): Body { + const keys = ["entries", "nonce", "parent"]; + if (!hasExactKeys(value, Object.hasOwn(value ?? {}, "metadata") ? [...keys, "metadata"] : keys)) { + throw new Error("Commit body is malformed"); + } + if (value.parent !== parent) throw new Error("Commit does not follow its parent"); + if (!isNonce(value.nonce) || !Array.isArray(value.entries)) { + throw new Error("Commit body is malformed"); + } + if (parent !== null && value.entries.length === 0) throw new Error("Commit has no entries"); + if (value.metadata !== undefined && !isObject(value.metadata)) { + throw new Error("Commit metadata must be an object"); + } + const nonces = new Set(); + const entries = value.entries.map((entry) => { + const read = readEntry(entry); + if (nonces.has(read.nonce)) throw new Error(`Duplicate entry nonce ${read.nonce}`); + nonces.add(read.nonce); + return read; + }); + return { ...(value as Body), entries }; +} + +function readEntry(value: unknown): StoredEntry { + const keys = ["kind", "nonce", "payload"]; + if (!hasExactKeys(value, Object.hasOwn(value ?? {}, "meta") ? [...keys, "meta"] : keys)) { + throw new Error("Entry is malformed"); + } + const { kind, nonce, meta } = value; + if (typeof kind !== "string" || kind.length < 1 || kind.length > 128) { + throw new Error("Entry kind must be 1 to 128 characters"); + } + if (!isNonce(nonce)) throw new Error("Entry nonce must be 16 bytes of base64url"); + if (meta !== undefined && !isObject(meta)) throw new Error("Entry meta must be an object"); + return value as StoredEntry; +} + +function captureSigner(signer: Signer): Signer { + const publicIdentity = validatePublicIdentity(signer.publicIdentity); + const sign = signer.sign.bind(signer); + return { publicIdentity, sign }; +} + +function capture(value: unknown): Json { + return JSON.parse(canonical(value)) as Json; +} + +function captureObject(value: unknown): JsonObject { + const copy = capture(value); + if (!isObject(copy)) throw new TypeError("Expected a JSON object"); + return copy; +} + +function resolveMaxBytes(value: number | undefined): number { + if (value === undefined) return DEFAULT_MAX_BYTES; + if (!Number.isSafeInteger(value) || value <= 0) throw new RangeError("maxBytes must be positive"); + return value; +} + +// Canonical JSON: keys sorted by UTF-16 code units, no whitespace, safe integers only. +function canonical(value: unknown): string { + if (value === null || typeof value === "boolean") return String(value); + if (typeof value === "number") { + if (!Number.isSafeInteger(value) || Object.is(value, -0)) { + throw new TypeError(`${value} is not a safe integer`); + } + return String(value); + } + if (typeof value === "string") return quote(value); + if (Array.isArray(value)) return `[${Array.from(value, canonical).join(",")}]`; + if (typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) { + const object = value as Record; + const members = Object.keys(object) + .sort() + .map((key) => `${quote(key)}:${canonical(object[key])}`); + return `{${members.join(",")}}`; + } + throw new TypeError("Ledger values must be plain JSON"); +} + +function quote(value: string): string { + // In a /u regex a lone surrogate is one code point of category Cs; a valid pair is not. + if (/\p{Cs}/u.test(value)) throw new TypeError("Strings must be well-formed Unicode"); + return JSON.stringify(value); +} + +function hasExactKeys(value: unknown, keys: K[]): value is Record { + return ( + isObject(value) && + Object.keys(value).length === keys.length && + keys.every((key) => Object.hasOwn(value, key)) + ); +} + +function isObject(value: unknown): value is JsonObject { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isNonce(value: unknown): value is string { + try { + return typeof value === "string" && base64urlnopad.decode(value).length === 16; + } catch { + return false; + } +} + +function deepFreeze(value: T): T { + if (typeof value === "object" && value !== null && !Object.isFrozen(value)) { + for (const child of Object.values(value)) deepFreeze(child); + Object.freeze(value); + } + return value; +} diff --git a/packages/ledger/src/ledger.ts b/packages/ledger/src/ledger.ts deleted file mode 100644 index 4ce3b4c..0000000 --- a/packages/ledger/src/ledger.ts +++ /dev/null @@ -1,368 +0,0 @@ -import * as protocol from "./protocol/verify.js"; -import { encodeBase64Url, validatePublicIdentity } from "@ternent/identity"; -import { detached, encodeJson, fail, Fault, nonce, parseJson } from "./protocol/index.js"; -import { appendInput, limits, snapshot, timestamp } from "./schema.js"; -import type { CommitId, JsonObject, VerificationReport } from "./protocol/index.js"; -import type { - CreateLedgerConfig, - LedgerOptions, - LedgerInstance, - LedgerState, - LedgerSnapshot, - LedgerReplayEntry, - LedgerEntryRecord, - LedgerAppendInput, - LedgerCommitSubject, - LedgerCommitRecord, -} from "./types.js"; - -function optionsObject(value: unknown): value is Record { - return value !== null && typeof value === "object" && !Array.isArray(value); -} - -export function createLedger

(config: CreateLedgerConfig

): Promise>; -export function createLedger(config?: LedgerOptions): Promise>; -export async function createLedger

( - config: LedgerOptions | CreateLedgerConfig

= {}, -): Promise> { - if ( - !optionsObject(config) || - Object.keys(config).some( - (key) => !["signer", "limits", "now", "initialProjection", "projector"].includes(key), - ) || - "initialProjection" in config !== "projector" in config - ) - fail("HOST_CONFIGURATION", "requirements"); - const lim = limits(config.limits); - const copy = (value: T): T => - parseJson(encodeJson(value, lim.maxDepth), lim.maxDepth, lim.maxBytes) as unknown as T; - const initial = detached( - copy("initialProjection" in config ? config.initialProjection : ([] as unknown as P)), - ); - const projector = - "projector" in config - ? config.projector - : (projection: P, entry: LedgerReplayEntry) => - [...(projection as unknown as LedgerReplayEntry[]), entry] as unknown as P; - if ( - typeof projector !== "function" || - (config.now !== undefined && typeof config.now !== "function") - ) - fail("HOST_CONFIGURATION", "requirements"); - const now = config.now ?? (() => new Date().toISOString()); - const signer = config.signer && { - publicIdentity: detached(config.signer.publicIdentity), - sign: config.signer.sign, - }; - if ( - signer && - (!validatePublicIdentity(signer.publicIdentity).ok || typeof signer.sign !== "function") - ) - fail("HOST_CONFIGURATION", "requirements"); - let state: Readonly> = detached({ - container: null, - staged: [], - projection: initial, - verification: null, - }); - let queue: Promise = Promise.resolve(); - let callbacks = 0; - let destroyed = false; - const listeners = new Set<(state: Readonly>) => void>(); - const call = (fn: () => T): T => { - callbacks++; - try { - return fn(); - } finally { - callbacks--; - } - }; - const clock = () => { - const value = call(now); - timestamp(value); - return value; - }; - function submit(prepare: () => () => T | Promise): Promise { - try { - if (callbacks) fail("HOST_CONFIGURATION", "requirements"); - if (destroyed) fail("LEDGER_DESTROYED", "author"); - const body = prepare(); - const pending = queue.then(() => { - if (destroyed) fail("LEDGER_DESTROYED", "author"); - return body(); - }); - queue = pending.then( - () => undefined, - () => undefined, - ); - return pending; - } catch (cause) { - return Promise.reject(cause); - } - } - function publish(next: LedgerState

): void { - state = detached(next); - for (const listener of listeners) { - // An observer cannot undo an already published commit or poison the mutation queue. - try { - call(() => listener(state)); - } catch { - /* Observer owns its failure. */ - } - } - } - function created(): LedgerSnapshot { - if (!state.container) fail("LEDGER_NOT_CREATED", "author"); - return state.container; - } - function writer() { - if (!signer) fail("READ_ONLY_RUNTIME", "author"); - return signer; - } - function project(container: LedgerSnapshot, staged: readonly LedgerEntryRecord[]): P { - let projection = detached(initial); - const reduce = (entry: LedgerEntryRecord, commitId: LedgerCommitRecord["id"] | null) => { - const event = detached({ - ...entry.subject, - entryId: entry.id, - commitId, - committed: commitId !== null, - }); - projection = detached(copy(call(() => projector(projection, event)))); - }; - for (const { commit, entry } of protocol.orderedEntries(container)) reduce(entry, commit.id); - for (const entry of staged) reduce(entry, null); - return projection; - } - async function verified( - bytes: Uint8Array, - ): Promise<{ container: LedgerSnapshot; report: VerificationReport }> { - const result = await protocol.inspectProtocol(bytes, { limits: lim }); - if (!result.snapshot) throw new Fault(result.report.findings[0]); - return { container: detached(result.snapshot), report: detached(result.report) }; - } - function metadata(input: { metadata?: JsonObject }): JsonObject | null { - if (!optionsObject(input) || Object.keys(input).some((key) => key !== "metadata")) - fail("SCHEMA_INVALID", "input"); - const value = input.metadata ?? null; - if (value !== null && (typeof value !== "object" || Array.isArray(value))) - fail("SCHEMA_INVALID", "input"); - if (encodeJson(value, lim.maxDepth).length > lim.maxMetadataBytes) - fail("RESOURCE_LIMIT", "input"); - return value; - } - async function candidate( - base: LedgerSnapshot | null, - entries: readonly LedgerEntryRecord[], - meta: JsonObject | null, - ) { - const identity = writer(); - const subject: LedgerCommitSubject = { - version: 1, - suite: "ledger-ed25519-v1", - parent: base?.head ?? null, - nonce: nonce(), - signer: identity.publicIdentity, - committedAt: clock(), - entryIds: entries.map((entry) => entry.id), - metadata: meta, - }; - const id = protocol.identifier(subject, "commit", lim.maxDepth); - const commit = { id, subject, signature: encodeBase64Url(new Uint8Array(64)) }; - const container: LedgerSnapshot = { - format: "ledger", - version: 1, - documentId: base?.documentId ?? id, - head: id, - commits: [...(base?.commits ?? []), commit], - entries: [...(base?.entries ?? []), ...entries], - }; - if (encodeJson(container, lim.maxDepth).length > lim.maxBytes) fail("RESOURCE_LIMIT", "author"); - snapshot(container, lim); - const message = protocol.signatureMessage(subject, lim.maxDepth); - let signature: Awaited>; - try { - signature = await call(() => identity.sign(message)); - } catch { - fail("SIGNING_FAILED", "author"); - } - if (!signature.ok || !(signature.value instanceof Uint8Array) || signature.value.length !== 64) - fail("SIGNING_FAILED", "author"); - commit.signature = encodeBase64Url(signature.value); - return { ...(await verified(encodeJson(container, lim.maxDepth))), commit }; - } - function load(input: LedgerSnapshot | Uint8Array): Promise { - return submit(() => { - if (input instanceof Uint8Array && input.byteLength > lim.maxBytes) - fail("RESOURCE_LIMIT", "input"); - const bytes = - input instanceof Uint8Array ? new Uint8Array(input) : encodeJson(input, lim.maxDepth); - return async () => { - if (state.staged.length) fail("DRAFT_PENDING", "author"); - const next = await verified(bytes); - publish({ - container: next.container, - verification: next.report, - staged: [], - projection: project(next.container, []), - }); - }; - }); - } - function makeEntries( - parent: CommitId | null, - inputs: readonly LedgerAppendInput[], - ): LedgerEntryRecord[] { - const identity = writer(); - return inputs.map((input) => { - const subject = { - version: 1 as const, - parent, - nonce: input.nonce ?? nonce(), - kind: input.kind, - author: identity.publicIdentity.id, - authoredAt: clock(), - meta: input.meta ?? null, - payload: { type: "plain" as const, data: input.payload ?? null }, - }; - return { id: protocol.identifier(subject, "entry", lim.maxDepth), subject }; - }); - } - function uniqueNonces(entries: readonly LedgerEntryRecord[]): void { - if (new Set(entries.map((entry) => entry.subject.nonce)).size !== entries.length) - fail("SCHEMA_INVALID", "author", "/nonce"); - } - function appendBatch(inputs: readonly LedgerAppendInput[]) { - return submit(() => { - const captured = copy(inputs); - if (!Array.isArray(captured) || !captured.length) fail("NO_ENTRIES", "author"); - for (const input of captured) appendInput(input, lim); - return () => { - const base = created(); - if (base.entries.length + state.staged.length + captured.length > lim.maxEntries) - fail("RESOURCE_LIMIT", "author"); - const entries = makeEntries(base.head, captured); - const staged = [...state.staged, ...entries]; - uniqueNonces(staged); - if ( - encodeJson({ ...base, entries: [...base.entries, ...staged] }, lim.maxDepth).length > - lim.maxBytes - ) - fail("RESOURCE_LIMIT", "author"); - publish({ ...state, staged, projection: project(base, staged) }); - return { entries: detached(entries), stagedCount: staged.length }; - }; - }); - } - const ledger: LedgerInstance

= { - create(input = {}) { - return submit(() => { - const captured = copy(input); - if ( - !optionsObject(captured) || - Object.keys(captured).some((key) => !["metadata", "entries"].includes(key)) - ) - fail("SCHEMA_INVALID", "input"); - const meta = metadata( - captured.metadata === undefined ? {} : { metadata: captured.metadata }, - ); - const inputs = captured.entries ?? []; - if (!Array.isArray(inputs) || inputs.length > lim.maxEntries) - fail("RESOURCE_LIMIT", "input"); - for (const entry of inputs) appendInput(entry, lim); - return async () => { - if (state.container) fail("LEDGER_ALREADY_CREATED", "author"); - const entries = makeEntries(null, inputs); - uniqueNonces(entries); - const next = await candidate(null, entries, meta); - publish({ - container: next.container, - staged: [], - projection: project(next.container, []), - verification: next.report, - }); - }; - }); - }, - load, - import: load, - async append(input) { - const result = await appendBatch([input]); - return { entry: result.entries[0], stagedCount: result.stagedCount }; - }, - async appendMany(inputs) { - return (await appendBatch(inputs)).entries; - }, - commit(input = {}) { - return submit(() => { - const meta = metadata(copy(input)); - return async () => { - const base = created(); - if (!state.staged.length) fail("NO_ENTRIES", "author"); - const entries = state.staged; - const next = await candidate(base, entries, meta); - const projection = project(next.container, []); - publish({ container: next.container, staged: [], projection, verification: next.report }); - return detached({ - commit: next.commit, - committedEntries: entries, - committedEntryIds: next.commit.subject.entryIds, - }); - }; - }); - }, - replay(options = {}) { - return submit(() => { - const captured = copy(options); - if ( - !optionsObject(captured) || - Object.keys(captured).some((key) => key !== "includeStaged") || - (captured.includeStaged !== undefined && typeof captured.includeStaged !== "boolean") - ) - fail("HOST_CONFIGURATION", "requirements"); - return () => project(created(), captured.includeStaged === false ? [] : state.staged); - }); - }, - recompute() { - return submit(() => () => { - const projection = project(created(), state.staged); - publish({ ...state, projection }); - return projection; - }); - }, - verify() { - return submit( - () => () => protocol.verifyDocument(encodeJson(created(), lim.maxDepth), { limits: lim }), - ); - }, - export() { - return submit(() => () => detached(created())); - }, - getState: () => state, - subscribe(listener) { - if (destroyed || typeof listener !== "function") fail("HOST_CONFIGURATION", "requirements"); - listeners.add(listener); - try { - call(() => listener(state)); - } catch { - /* Observer owns its failure. */ - } - return () => { - listeners.delete(listener); - }; - }, - clearStaged() { - return submit( - () => () => publish({ ...state, staged: [], projection: project(created(), []) }), - ); - }, - destroy() { - return submit(() => () => { - destroyed = true; - publish({ container: null, staged: [], projection: initial, verification: null }); - listeners.clear(); - }); - }, - }; - return Object.freeze(ledger); -} diff --git a/packages/ledger/src/payload.ts b/packages/ledger/src/payload.ts deleted file mode 100644 index ce734dc..0000000 --- a/packages/ledger/src/payload.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { decodeBase64Url, encodeBase64Url } from "@ternent/identity"; -import { fail } from "./common/errors.js"; -import { detached } from "./common/immutable.js"; -import { encodeJson, parseJson } from "./protocol/json.js"; -import { limits } from "./schema.js"; -import type { Json } from "./protocol/types.js"; -import type { LedgerLimits } from "./types.js"; - -/** Structural byte codec supplied by the host; Ledger owns no encryption or keys. */ -export type LedgerPayloadCodec = { - readonly id: string; - encode?(this: void, plaintext: Uint8Array): Promise; - /** null means unavailable to this reader; exceptions remain operational failures. */ - decode?(this: void, encoded: Uint8Array): Promise; -}; -export type LedgerPayloadEncoder = LedgerPayloadCodec & - Required>; -export type LedgerPayloadDecoder = LedgerPayloadCodec & - Required>; -export type LedgerEncodedPayload = { - format: "ledger-payload"; - version: 1; - codec: string; - data: string; -}; -export type LedgerDecodedPayload = - | { status: "plain" | "decoded"; data: Json } - | { status: "locked"; codec: string }; -type PayloadLimits = Partial>; -const validId = (id: unknown): id is string => - typeof id === "string" && /^[a-z][a-z0-9.-]{0,127}$/.test(id); -function codecId(codec: LedgerPayloadCodec): string { - if (!codec || !validId(codec.id)) fail("HOST_CONFIGURATION", "requirements"); - return codec.id; -} - -/** Encode portable JSON before appending it through the ordinary Ledger API. */ -export async function encodePayload( - data: Json, - codec: LedgerPayloadEncoder, - options?: PayloadLimits, -): Promise { - const lim = limits(options), - id = codecId(codec), - encode = codec.encode; - if (typeof encode !== "function") fail("HOST_CONFIGURATION", "requirements"); - const plaintext = encodeJson(data, lim.maxDepth); - if (plaintext.byteLength > lim.maxBytes) fail("RESOURCE_LIMIT", "input"); - const encoded = await encode(plaintext); - if (!(encoded instanceof Uint8Array)) fail("PAYLOAD_CODEC_INVALID", "input"); - if (encoded.byteLength > lim.maxBytes) fail("RESOURCE_LIMIT", "input"); - const payload: LedgerEncodedPayload = { - format: "ledger-payload", - version: 1, - codec: id, - data: encodeBase64Url(encoded), - }; - if (encodeJson(payload, lim.maxDepth).byteLength > lim.maxBytes) fail("RESOURCE_LIMIT", "input"); - return detached(payload); -} - -/** Decode a replayed payload without changing the signed entry or asserting trust. */ -export async function decodePayload( - payload: Json, - codec?: LedgerPayloadCodec, - options?: PayloadLimits, -): Promise { - const lim = limits(options); - const data = parseJson(encodeJson(payload, lim.maxDepth), lim.maxDepth, lim.maxBytes); - if (!data || typeof data !== "object" || Array.isArray(data) || data.format !== "ledger-payload") - return detached({ status: "plain", data }); - if ( - Object.keys(data).length !== 4 || - data.version !== 1 || - !validId(data.codec) || - typeof data.data !== "string" - ) - fail("PAYLOAD_INVALID", "input"); - const encoded = decodeBase64Url(data.data); - if (!encoded.ok) fail("PAYLOAD_INVALID", "input"); - const locked = () => detached({ status: "locked" as const, codec: data.codec as string }); - if (!codec || codecId(codec) !== data.codec || codec.decode === undefined) return locked(); - const decode = codec.decode; - if (typeof decode !== "function") fail("HOST_CONFIGURATION", "requirements"); - const plaintext = await decode(encoded.value); - if (plaintext === null) return locked(); - if (!(plaintext instanceof Uint8Array)) fail("PAYLOAD_CODEC_INVALID", "input"); - return detached({ status: "decoded", data: parseJson(plaintext, lim.maxDepth, lim.maxBytes) }); -} diff --git a/packages/ledger/src/protocol/index.ts b/packages/ledger/src/protocol/index.ts deleted file mode 100644 index c4c7380..0000000 --- a/packages/ledger/src/protocol/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -export { - identifier, - signatureMessage, - inspectProtocol, - verifyDocument, - compareSnapshots, - orderedEntries, - concat, - inspectLedger, - ledgerSignatureMessage, - verifyLedger, - compareLedgers, - hashLedgerEntry, - hashLedgerCommit, -} from "./verify.js"; -export { encodeJson, parseJson, canonicalize, unicode, utf8, text } from "./json.js"; -export { detached, freeze } from "../common/immutable.js"; -export { nonce } from "../common/random.js"; -export { Fault, error, fail, caught, attempt, ok } from "../common/errors.js"; -export type { HistoryError, Result } from "../common/errors.js"; -export type * from "./types.js"; diff --git a/packages/ledger/src/protocol/json.ts b/packages/ledger/src/protocol/json.ts deleted file mode 100644 index 320a53a..0000000 --- a/packages/ledger/src/protocol/json.ts +++ /dev/null @@ -1,186 +0,0 @@ -import { attempt, fail, type Result } from "../common/errors.js"; -import type { Json } from "./types.js"; -export const utf8 = new TextEncoder(); -export const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); -export function unicode(value: string): boolean { - for (let i = 0; i < value.length; i++) { - const c = value.charCodeAt(i); - if (c >= 0xd800 && c <= 0xdbff) { - const next = value.charCodeAt(++i); - if (!(next >= 0xdc00 && next <= 0xdfff)) return false; - } else if (c >= 0xdc00 && c <= 0xdfff) return false; - } - return true; -} -export function encodeJson(input: unknown, maxDepth = 64): Uint8Array { - const active = new Set(); - function encode(value: unknown, depth: number): string { - if (value === null) return "null"; - if (typeof value === "string") { - if (!unicode(value)) fail("JSON_INVALID", "input"); - return JSON.stringify(value); - } - if (typeof value === "boolean") return String(value); - if (typeof value === "number") { - if (!Number.isSafeInteger(value) || Object.is(value, -0)) fail("JSON_INVALID", "input"); - return String(value); - } - if (!value || typeof value !== "object") fail("JSON_INVALID", "input"); - if (depth + 1 > maxDepth) fail("RESOURCE_LIMIT"); - const prototype = Object.getPrototypeOf(value); - if ( - (Array.isArray(value) && prototype !== Array.prototype) || - (!Array.isArray(value) && prototype !== null && prototype !== Object.prototype) || - active.has(value) - ) - fail("JSON_INVALID", "input"); - const descriptors = Object.getOwnPropertyDescriptors(value); - if ( - Object.getOwnPropertySymbols(value).length || - Object.values(descriptors).some((d) => !("value" in d)) - ) - fail("JSON_INVALID", "input"); - active.add(value); - let output: string; - if (Array.isArray(value)) { - if (Object.keys(descriptors).length !== value.length + 1) fail("JSON_INVALID", "input"); - const items: string[] = []; - for (let i = 0; i < value.length; i++) { - if (!Object.hasOwn(descriptors, String(i))) fail("JSON_INVALID", "input"); - items.push(encode(descriptors[i].value, depth + 1)); - } - output = `[${items.join(",")}]`; - } else { - output = `{${Object.keys(descriptors) - .sort() - .map((key) => `${encode(key, depth + 1)}:${encode(descriptors[key].value, depth + 1)}`) - .join(",")}}`; - } - active.delete(value); - return output; - } - return utf8.encode(encode(input, 0)); -} -export function canonicalize(value: unknown): Result { - return attempt(() => encodeJson(value), "JSON_INVALID", "input"); -} -function numberToken(token: string): number { - const match = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(token)!; - let digits = (match[2] + (match[3] ?? "")).replace(/^0+/, ""); - if (!digits) { - if (match[1]) fail("JSON_INVALID", "input"); - return 0; - } - const scale = Number(match[4] ?? 0) - (match[3]?.length ?? 0); - if (!Number.isSafeInteger(scale)) fail("JSON_INVALID", "input"); - if (scale < 0) { - if (-scale > digits.length || !digits.endsWith("0".repeat(-scale))) - fail("JSON_INVALID", "input"); - digits = digits.slice(0, scale); - } else { - if (digits.length + scale > 16) fail("JSON_INVALID", "input"); - digits += "0".repeat(scale); - } - if (digits.length > 16 || (digits.length === 16 && digits > "9007199254740991")) - fail("JSON_INVALID", "input"); - return Number(`${match[1]}${digits}`); -} -export function parseJson(bytes: Uint8Array, maxDepth = 64, maxBytes = 16 * 1024 * 1024): Json { - if (bytes.length > maxBytes) fail("RESOURCE_LIMIT"); - let source: string; - try { - source = text.decode(bytes); - } catch { - fail("JSON_INVALID", "input"); - } - if (source.charCodeAt(0) === 0xfeff) fail("JSON_INVALID", "input"); - let offset = 0; - function space() { - while (offset < source.length && " \t\n\r".includes(source[offset])) offset++; - } - function string(): string { - const start = offset++; - while (offset < source.length) { - const c = source[offset++]; - if (c === '"') { - let value: string; - try { - value = JSON.parse(source.slice(start, offset)); - } catch { - fail("JSON_INVALID", "input"); - } - if (!unicode(value)) fail("JSON_INVALID", "input"); - return value; - } - if (c === "\\") offset++; - } - return fail("JSON_INVALID", "input"); - } - function value(depth: number): Json { - space(); - const c = source[offset]; - if (c === '"') return string(); - if (c === "{" || c === "[") { - if (depth + 1 > maxDepth) fail("RESOURCE_LIMIT"); - offset++; - space(); - if (c === "[") { - const result: Json[] = []; - if (source[offset] === "]") { - offset++; - return result; - } - while (true) { - result.push(value(depth + 1)); - space(); - if (source[offset] === "]") { - offset++; - return result; - } - if (source[offset++] !== ",") fail("JSON_INVALID", "input"); - } - } - const result: Record = Object.create(null); - const keys = new Set(); - if (source[offset] === "}") { - offset++; - return result; - } - while (true) { - space(); - if (source[offset] !== '"') fail("JSON_INVALID", "input"); - const key = string(); - if (keys.has(key)) fail("JSON_INVALID", "input"); - keys.add(key); - space(); - if (source[offset++] !== ":") fail("JSON_INVALID", "input"); - result[key] = value(depth + 1); - space(); - if (source[offset] === "}") { - offset++; - return result; - } - if (source[offset++] !== ",") fail("JSON_INVALID", "input"); - } - } - for (const [literal, result] of [ - ["true", true], - ["false", false], - ["null", null], - ] as const) - if (source.startsWith(literal, offset)) { - offset += literal.length; - return result; - } - const number = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(source.slice(offset)); - if (number) { - offset += number[0].length; - return numberToken(number[0]); - } - return fail("JSON_INVALID", "input"); - } - const result = value(0); - space(); - if (offset !== source.length) fail("JSON_INVALID", "input"); - return result; -} diff --git a/packages/ledger/src/protocol/types.ts b/packages/ledger/src/protocol/types.ts deleted file mode 100644 index 491ce1e..0000000 --- a/packages/ledger/src/protocol/types.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { HistoryError } from "../common/errors.js"; -export type { PublicIdentity } from "@ternent/identity"; -export type Json = null | boolean | string | number | Json[] | { [key: string]: Json }; -export type JsonObject = { [key: string]: Json }; -export type CommitId = `commit:${string}`; -export type EntryId = `entry:${string}`; -export type Relationship = "equal" | "ahead" | "behind" | "diverged" | "unrelated"; -export type VerificationReport = { - integrity: "valid" | "invalid" | "unsupported"; - documentId: CommitId | null; - head: CommitId | null; - checkedCommits: number; - checkedEntries: number; - findings: readonly HistoryError[]; -}; diff --git a/packages/ledger/src/protocol/verify.ts b/packages/ledger/src/protocol/verify.ts deleted file mode 100644 index ad3b1cc..0000000 --- a/packages/ledger/src/protocol/verify.ts +++ /dev/null @@ -1,221 +0,0 @@ -import { sha256 } from "@noble/hashes/sha2.js"; -import { validatePublicIdentity, verifySignature } from "@ternent/identity"; -import { attempt, caught, fail, ok, type Result } from "../common/errors.js"; -import { encodeJson, parseJson, utf8 } from "./json.js"; -import type { CommitId, EntryId, Relationship, VerificationReport } from "./types.js"; - -import * as schema from "../schema.js"; -import type { - LedgerSnapshot, - LedgerLimits, - LedgerEntrySubject, - LedgerCommitSubject, -} from "../types.js"; -const domains = { - entry: "ledger.entry/1\0", - commit: "ledger.commit/1\0", - signature: "ledger.signature/1\0", -}; -const hexadecimal = (value: Uint8Array) => - Array.from(value, (v) => v.toString(16).padStart(2, "0")).join(""); -export function concat(a: Uint8Array, b: Uint8Array): Uint8Array { - const out = new Uint8Array(a.length + b.length); - out.set(a); - out.set(b, a.length); - return out; -} - -export function signatureMessage(subject: LedgerCommitSubject, depth = 64): Uint8Array { - return concat(utf8.encode(domains.signature), encodeJson(subject, depth)); -} -export function identifier(subject: LedgerEntrySubject, kind: "entry", depth?: number): EntryId; -export function identifier(subject: LedgerCommitSubject, kind: "commit", depth?: number): CommitId; -export function identifier( - subject: LedgerEntrySubject | LedgerCommitSubject, - kind: "entry" | "commit", - depth = 64, -): EntryId | CommitId { - return `${kind}:${hexadecimal(sha256(concat(utf8.encode(domains[kind]), encodeJson(subject, depth))))}`; -} -const unsupported = new Set([ - "PROTOCOL_UNSUPPORTED", - "SUITE_UNSUPPORTED", - "ENTRY_KIND_UNSUPPORTED", - "RESOURCE_LIMIT", - "HOST_CONFIGURATION", -]); -export async function inspectProtocol( - bytes: Uint8Array, - options: { limits?: Partial } = {}, -): Promise<{ - report: VerificationReport; - snapshot?: LedgerSnapshot; - untrustedHistory: readonly LedgerSnapshot["commits"][number][]; -}> { - const report: VerificationReport = { - integrity: "invalid", - documentId: null, - head: null, - checkedCommits: 0, - checkedEntries: 0, - findings: [], - }; - let untrustedHistory: readonly LedgerSnapshot["commits"][number][] = []; - try { - const lim = schema.limits(options.limits); - if (bytes.byteLength > lim.maxBytes) fail("RESOURCE_LIMIT"); - const parsed = parseJson(new Uint8Array(bytes), lim.maxDepth, lim.maxBytes); - schema.snapshot(parsed, lim); - // Parsed envelopes are inspection evidence; only snapshot grants verified input. - untrustedHistory = parsed.commits; - report.documentId = parsed.documentId; - report.head = parsed.head; - if (encodeJson(parsed, lim.maxDepth).length > lim.maxBytes) fail("RESOURCE_LIMIT"); - const entryIds = new Set(), - commitIds = new Set(), - references = new Set(); - for (let i = 0; i < parsed.entries.length; i++) { - const record = parsed.entries[i]; - if (entryIds.has(record.id)) fail("DUPLICATE_RECORD", "protocol", `/entries/${i}/id`); - entryIds.add(record.id); - } - const expected: EntryId[] = []; - const referencePaths: string[] = []; - for (let i = 0; i < parsed.commits.length; i++) { - const record = parsed.commits[i]; - if (commitIds.has(record.id)) fail("DUPLICATE_RECORD", "protocol", `/commits/${i}/id`); - commitIds.add(record.id); - for (let j = 0; j < record.subject.entryIds.length; j++) { - const id = record.subject.entryIds[j]; - if (references.has(id)) - fail("DUPLICATE_RECORD", "protocol", `/commits/${i}/subject/entryIds/${j}`); - references.add(id); - expected.push(id); - referencePaths.push(`/commits/${i}/subject/entryIds/${j}`); - } - } - for (let i = 0; i < expected.length; i++) - if (!entryIds.has(expected[i])) fail("ENTRY_MISSING", "protocol", referencePaths[i]); - for (let i = 0; i < parsed.entries.length; i++) - if (!references.has(parsed.entries[i].id)) - fail("UNREFERENCED_RECORD", "protocol", `/entries/${i}`); - for (let i = 0; i < expected.length; i++) - if (parsed.entries[i]?.id !== expected[i]) fail("ENTRY_ORDER", "protocol", `/entries/${i}`); - const selected = parsed.commits.findIndex((commit) => commit.id === parsed.head); - const linear = parsed.commits.every( - (commit, index) => - commit.subject.parent === (index === 0 ? null : parsed.commits[index - 1].id), - ); - if (selected >= 0 && selected < parsed.commits.length - 1 && !linear) { - const records = new Map(parsed.commits.map((commit) => [commit.id, commit])); - const reachable = new Set(); - let cursor: CommitId | null = parsed.head; - while (cursor !== null && records.has(cursor) && !reachable.has(cursor)) { - reachable.add(cursor); - cursor = records.get(cursor)!.subject.parent; - } - const detached = parsed.commits.findIndex((commit) => !reachable.has(commit.id)); - if (detached >= 0) fail("UNREFERENCED_RECORD", "protocol", `/commits/${detached}`); - } - for (let i = 0; i < parsed.entries.length; i++) { - if (identifier(parsed.entries[i].subject, "entry", lim.maxDepth) !== parsed.entries[i].id) - fail("HASH_MISMATCH", "protocol", `/entries/${i}/id`); - report.checkedEntries++; - } - for (let i = 0; i < parsed.commits.length; i++) - if (identifier(parsed.commits[i].subject, "commit", lim.maxDepth) !== parsed.commits[i].id) - fail("HASH_MISMATCH", "protocol", `/commits/${i}/id`); - let offset = 0; - for (let i = 0; i < parsed.commits.length; i++) { - const subject = parsed.commits[i].subject; - if (subject.parent !== (i === 0 ? null : parsed.commits[i - 1].id)) - fail("LINK_INVALID", "protocol", `/commits/${i}/subject/parent`); - const nonces = new Set(); - for (let j = 0; j < subject.entryIds.length; j++) { - const entry = parsed.entries[offset++]; - if (entry.subject.parent !== subject.parent) - fail("LINK_INVALID", "protocol", `/entries/${offset - 1}/subject/parent`); - if (nonces.has(entry.subject.nonce)) - fail("SCHEMA_INVALID", "protocol", `/entries/${offset - 1}/subject/nonce`); - nonces.add(entry.subject.nonce); - } - } - if (parsed.documentId !== parsed.commits[0].id) fail("HEAD_INVALID", "protocol", "/documentId"); - if (parsed.head !== parsed.commits.at(-1)!.id) fail("HEAD_INVALID", "protocol", "/head"); - for (let i = 0; i < parsed.commits.length; i++) { - const record = parsed.commits[i]; - if (!validatePublicIdentity(record.subject.signer).ok) - fail("IDENTITY_INVALID", "protocol", `/commits/${i}/subject/signer`); - const valid = await verifySignature( - record.subject.signer, - signatureMessage(record.subject, lim.maxDepth), - schema.bytes(record.signature, 64, `/commits/${i}/signature`), - ); - if (!valid.ok || !valid.value) - fail("SIGNATURE_INVALID", "protocol", `/commits/${i}/signature`); - report.checkedCommits++; - } - report.integrity = "valid"; - return { report, snapshot: parsed, untrustedHistory }; - } catch (cause) { - const finding = caught(cause, "SCHEMA_INVALID", "protocol"); - report.integrity = unsupported.has(finding.code) ? "unsupported" : "invalid"; - report.findings = [finding]; - return { report, untrustedHistory }; - } -} -export async function verifyDocument( - bytes: Uint8Array, - options?: { limits?: Partial }, -): Promise { - return (await inspectProtocol(bytes, options)).report; -} -export async function compareSnapshots( - a: Uint8Array, - b: Uint8Array, - options?: { limits?: Partial }, -): Promise> { - const left = await inspectProtocol(a, options), - right = await inspectProtocol(b, options); - if (!left.snapshot) return { ok: false, error: left.report.findings[0] }; - if (!right.snapshot) return { ok: false, error: right.report.findings[0] }; - const x = left.snapshot, - y = right.snapshot; - return ok( - x.documentId !== y.documentId - ? "unrelated" - : x.head === y.head - ? "equal" - : y.commits.some((c) => c.id === x.head) - ? "behind" - : x.commits.some((c) => c.id === y.head) - ? "ahead" - : "diverged", - ); -} - -export const inspectLedger = inspectProtocol; -export const ledgerSignatureMessage = signatureMessage; -export const verifyLedger = verifyDocument; -export const compareLedgers = compareSnapshots; -/** Ordered records from a verified snapshot; traversal does not itself establish trust. */ -export function* orderedEntries(snapshot: LedgerSnapshot) { - let offset = 0; - for (const commit of snapshot.commits) - for (let index = 0; index < commit.subject.entryIds.length; index++) - yield { commit, entry: snapshot.entries[offset++] }; -} -export function hashLedgerEntry(subject: LedgerEntrySubject) { - return attempt(() => { - const safe = parseJson(encodeJson(subject)); - schema.entrySubject(safe, "", schema.limits()); - return identifier(safe, "entry"); - }); -} -export function hashLedgerCommit(subject: LedgerCommitSubject) { - return attempt(() => { - const safe = parseJson(encodeJson(subject)); - schema.commitSubject(safe, "", schema.limits()); - return identifier(safe, "commit"); - }); -} diff --git a/packages/ledger/src/schema.ts b/packages/ledger/src/schema.ts deleted file mode 100644 index 0267a75..0000000 --- a/packages/ledger/src/schema.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { decodeBase64Url, validatePublicIdentity } from "@ternent/identity"; -import { encodeJson } from "./protocol/json.js"; -import { fail } from "./common/errors.js"; -import type { - LedgerSnapshot, - LedgerLimits, - LedgerAppendInput, - LedgerEntrySubject, - LedgerCommitSubject, -} from "./types.js"; - -const defaults: LedgerLimits = { - maxBytes: 16 * 1024 * 1024, - maxCommits: 10_000, - maxEntries: 100_000, - maxDepth: 64, - maxMetadataBytes: 64 * 1024, - // Framework ciphertext is opaque JSON here; the total snapshot cap remains authoritative. - maxPayloadBytes: 16 * 1024 * 1024, -}; -export function limits(input: Partial = {}): LedgerLimits { - if ( - !input || - typeof input !== "object" || - Array.isArray(input) || - Object.keys(input).some((key) => !Object.hasOwn(defaults, key)) - ) - fail("HOST_CONFIGURATION", "requirements"); - const output = { ...defaults, ...input }; - if (Object.values(output).some((value) => !Number.isSafeInteger(value) || value <= 0)) - fail("HOST_CONFIGURATION", "requirements"); - return output; -} -function record(value: unknown): value is Record { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function closed( - value: unknown, - keys: readonly string[], - path: string, -): asserts value is Record { - if ( - !record(value) || - Object.keys(value).length !== keys.length || - keys.some((key) => !Object.hasOwn(value, key)) - ) - fail("SCHEMA_INVALID", "protocol", path); -} -function id(value: unknown, kind: "commit" | "entry", path: string): void { - if (typeof value !== "string" || !new RegExp(`^${kind}:[0-9a-f]{64}$`).test(value)) - fail("SCHEMA_INVALID", "protocol", path); -} -export function bytes(value: unknown, size: number, path: string): Uint8Array { - if (typeof value !== "string") fail("SCHEMA_INVALID", "protocol", path); - const decoded = decodeBase64Url(value); - if (!decoded.ok || decoded.value.length !== size) fail("SCHEMA_INVALID", "protocol", path); - return decoded.value; -} -export function timestamp(value: unknown): asserts value is string { - if ( - typeof value !== "string" || - !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value) || - !Number.isFinite(Date.parse(value)) || - new Date(value).toISOString() !== value - ) - fail("SCHEMA_INVALID", "protocol"); -} -function metadata(value: unknown, lim: LedgerLimits): void { - if (value !== null && !record(value)) fail("SCHEMA_INVALID", "protocol"); - if (value !== null && encodeJson(value, lim.maxDepth).length > lim.maxMetadataBytes) - fail("RESOURCE_LIMIT", "protocol"); -} -export function appendInput(input: unknown, lim: LedgerLimits): asserts input is LedgerAppendInput { - if ( - !record(input) || - Object.keys(input).some((key) => !["kind", "payload", "meta", "nonce"].includes(key)) || - typeof input.kind !== "string" || - input.kind.length < 1 || - input.kind.length > 128 - ) - fail("SCHEMA_INVALID", "input"); - if (input.nonce !== undefined) bytes(input.nonce, 16, "/nonce"); - metadata(input.meta ?? null, lim); - if (encodeJson(input.payload ?? null, lim.maxDepth).length > lim.maxPayloadBytes) - fail("RESOURCE_LIMIT", "input"); -} -export function entrySubject( - input: unknown, - path: string, - lim: LedgerLimits, -): asserts input is LedgerEntrySubject { - closed( - input, - ["version", "parent", "nonce", "kind", "author", "authoredAt", "meta", "payload"], - path, - ); - const subject = input; - if ( - subject.version !== 1 || - typeof subject.kind !== "string" || - subject.kind.length < 1 || - subject.kind.length > 128 || - typeof subject.author !== "string" - ) - fail("SCHEMA_INVALID", "protocol", path); - if (subject.parent !== null) id(subject.parent, "commit", `${path}/parent`); - bytes(subject.nonce, 16, `${path}/nonce`); - timestamp(subject.authoredAt); - metadata(subject.meta, lim); - closed(subject.payload, ["type", "data"], `${path}/payload`); - if (subject.payload.type !== "plain") fail("ENTRY_KIND_UNSUPPORTED", "protocol", path); - if (encodeJson(subject.payload.data, lim.maxDepth).length > lim.maxPayloadBytes) - fail("RESOURCE_LIMIT", "protocol", path); -} -export function commitSubject( - input: unknown, - path: string, - lim: LedgerLimits, -): asserts input is LedgerCommitSubject { - closed( - input, - ["version", "suite", "parent", "nonce", "signer", "committedAt", "entryIds", "metadata"], - path, - ); - const subject = input; - if (subject.version !== 1 || subject.suite !== "ledger-ed25519-v1") - fail("SUITE_UNSUPPORTED", "protocol", path); - if (subject.parent !== null) id(subject.parent, "commit", `${path}/parent`); - bytes(subject.nonce, 16, `${path}/nonce`); - if (!record(subject.signer) || !validatePublicIdentity(subject.signer).ok) - fail("IDENTITY_INVALID", "protocol", path); - timestamp(subject.committedAt); - metadata(subject.metadata, lim); - if (!Array.isArray(subject.entryIds) || subject.entryIds.length > lim.maxEntries) - fail("SCHEMA_INVALID", "protocol", path); - - subject.entryIds.forEach((entryId, index) => id(entryId, "entry", `${path}/entryIds/${index}`)); -} -export function snapshot(input: unknown, lim: LedgerLimits): asserts input is LedgerSnapshot { - closed(input, ["format", "version", "documentId", "head", "commits", "entries"], ""); - if (input.format !== "ledger" || input.version !== 1) fail("PROTOCOL_UNSUPPORTED", "protocol"); - id(input.documentId, "commit", "/documentId"); - id(input.head, "commit", "/head"); - if (!Array.isArray(input.commits) || !input.commits.length || !Array.isArray(input.entries)) - fail("SCHEMA_INVALID", "protocol"); - if (input.commits.length > lim.maxCommits || input.entries.length > lim.maxEntries) - fail("RESOURCE_LIMIT", "protocol"); - for (const [index, entry] of input.entries.entries()) { - const path = `/entries/${index}`; - closed(entry, ["id", "subject"], path); - id(entry.id, "entry", `${path}/id`); - entrySubject(entry.subject, `${path}/subject`, lim); - } - let offset = 0; - for (const [index, commit] of input.commits.entries()) { - const path = `/commits/${index}`; - closed(commit, ["id", "subject", "signature"], path); - id(commit.id, "commit", `${path}/id`); - commitSubject(commit.subject, `${path}/subject`, lim); - const subject = commit.subject; - if (index > 0 && !subject.entryIds.length) fail("SCHEMA_INVALID", "protocol", path); - for (const [entryIndex, entryId] of subject.entryIds.entries()) { - id(entryId, "entry", `${path}/subject/entryIds/${entryIndex}`); - const entry = input.entries[offset++]; - if (record(entry) && record(entry.subject) && entry.subject.author !== subject.signer.id) - fail("IDENTITY_MISMATCH", "protocol", `/entries/${offset - 1}/subject/author`); - } - bytes(commit.signature, 64, `${path}/signature`); - } -} diff --git a/packages/ledger/src/types.ts b/packages/ledger/src/types.ts deleted file mode 100644 index f25525f..0000000 --- a/packages/ledger/src/types.ts +++ /dev/null @@ -1,89 +0,0 @@ -import type { BaseIdentityCapability, PublicIdentity } from "@ternent/identity"; -import type { Json, JsonObject, CommitId, EntryId, VerificationReport } from "./protocol/index.js"; - -export type LedgerSigner = Pick; -export type LedgerPayload = { type: "plain"; data: Json }; -export type LedgerEntrySubject = { - version: 1; - parent: CommitId | null; - nonce: string; - kind: string; - author: string; - authoredAt: string; - meta: JsonObject | null; - payload: LedgerPayload; -}; -export type LedgerEntryRecord = { id: EntryId; subject: LedgerEntrySubject }; -export type LedgerCommitSubject = { - version: 1; - suite: "ledger-ed25519-v1"; - parent: CommitId | null; - nonce: string; - signer: PublicIdentity; - committedAt: string; - entryIds: EntryId[]; - metadata: JsonObject | null; -}; -export type LedgerCommitRecord = { - id: CommitId; - subject: LedgerCommitSubject; - signature: string; -}; -export type LedgerSnapshot = { - format: "ledger"; - version: 1; - documentId: CommitId; - head: CommitId; - commits: LedgerCommitRecord[]; - entries: LedgerEntryRecord[]; -}; -export type LedgerLimits = { - maxBytes: number; - maxCommits: number; - maxEntries: number; - maxDepth: number; - maxMetadataBytes: number; - maxPayloadBytes: number; -}; -export type LedgerAppendInput = { kind: string; payload?: Json; meta?: JsonObject; nonce?: string }; -export type LedgerReplayEntry = LedgerEntrySubject & { - entryId: EntryId; - commitId: CommitId | null; - committed: boolean; -}; -export type LedgerProjector

= (projection: P, entry: Readonly) => P; -export type LedgerOptions = { - signer?: LedgerSigner; - limits?: Partial; - now?: () => string; -}; -export type CreateLedgerConfig

= LedgerOptions & { - initialProjection: P; - projector: LedgerProjector

; -}; -export type LedgerState

= { - container: LedgerSnapshot | null; - staged: readonly LedgerEntryRecord[]; - projection: P; - verification: VerificationReport | null; -}; -export type LedgerInstance

= { - create(input?: { metadata?: JsonObject; entries?: readonly LedgerAppendInput[] }): Promise; - load(snapshot: LedgerSnapshot | Uint8Array): Promise; - import(snapshot: LedgerSnapshot | Uint8Array): Promise; - append(input: LedgerAppendInput): Promise<{ entry: LedgerEntryRecord; stagedCount: number }>; - appendMany(inputs: readonly LedgerAppendInput[]): Promise; - commit(input?: { metadata?: JsonObject }): Promise<{ - commit: LedgerCommitRecord; - committedEntries: readonly LedgerEntryRecord[]; - committedEntryIds: readonly EntryId[]; - }>; - replay(options?: { includeStaged?: boolean }): Promise

; - recompute(): Promise

; - verify(): Promise; - export(): Promise; - getState(): Readonly>; - subscribe(listener: (state: Readonly>) => void): () => void; - clearStaged(): Promise; - destroy(): Promise; -}; diff --git a/packages/ledger/test/ledger.test.ts b/packages/ledger/test/ledger.test.ts index 75b0e12..be4bdce 100644 --- a/packages/ledger/test/ledger.test.ts +++ b/packages/ledger/test/ledger.test.ts @@ -1,370 +1,291 @@ -import { createHash, createPrivateKey, sign } from "node:crypto"; import { readFileSync } from "node:fs"; import { expect, test } from "vite-plus/test"; -import { signerFromSeed, type BaseIdentityCapability } from "@ternent/identity"; -import { - createLedger, - verifyLedger, - compareLedgers, - encodeJson, - Fault, - type LedgerSnapshot, - type LedgerSigner, -} from "../src/index.js"; +import { createHash } from "node:crypto"; +import { createIdentity, type Identity } from "@ternent/identity"; +import * as api from "../src/index.js"; +import { createLedger, createWriter, openLedger, type History } from "../src/index.js"; -const seed = Uint8Array.from( - Buffer.from("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "hex"), -); -async function signer(byte?: number): Promise { - const result = await signerFromSeed(byte === undefined ? seed : new Uint8Array(32).fill(byte)); - if (!result.ok) throw new Error(result.error.code); - return result.value; -} -const now = () => "2026-11-21T00:00:00.000Z"; -function canonical(value: unknown): string { - if (value === null || typeof value !== "object") return JSON.stringify(value); - if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; - return `{${Object.keys(value) - .sort() - .map((key) => `${JSON.stringify(key)}:${canonical((value as Record)[key])}`) - .join(",")}}`; -} -async function saved(): Promise { - const log = await createLedger({ signer: await signer(), now }); - await log.create({ metadata: { title: "log" } }); - await log.append({ kind: "reading", payload: { value: 7 } }); - await log.commit(); - return log.export(); -} -test("standalone staged log: create, append, preview, commit, export and reopen", async () => { - const log = await createLedger({ signer: await signer(), now }); - await log.create(); - const empty = await log.export(); - const input = { kind: "measurement", payload: { value: 0 } }; - const appended = log.append(input); - input.payload.value = 99; - await appended; - expect(await log.export()).toEqual(empty); - expect(await log.replay()).toMatchObject([ - { kind: "measurement", payload: { data: { value: 0 } }, committed: false }, - ]); - expect(await log.replay({ includeStaged: false })).toEqual([]); - expect((await log.verify()).integrity).toBe("valid"); - const meta = { note: "captured" }; - const pending = log.commit({ metadata: meta }); - meta.note = "changed"; - const receipt = await pending; - expect(receipt.commit.subject.metadata).toEqual({ note: "captured" }); - expect(log.getState().staged).toEqual([]); - const snapshot = await log.export(); - const reopened = await createLedger(); - await reopened.import(encodeJson(snapshot)); - expect(await reopened.replay()).toEqual(await log.replay()); - expect(await reopened.replay()).toMatchObject([{ committed: true, commitId: receipt.commit.id }]); - await expect(reopened.append({ kind: "no" })).rejects.toMatchObject({ - finding: { code: "READ_ONLY_RUNTIME" }, - }); +const vector = JSON.parse(readFileSync(new URL("vectors.json", import.meta.url), "utf8")); +const utf8 = (text: string) => new TextEncoder().encode(text); +const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes); +// An independent canonical form: keys sorted recursively, no whitespace. It writes the +// string directly because objects list integer-like keys ("2", "10") numerically. +const canonicalJson = (value: unknown): string => + Array.isArray(value) + ? `[${value.map(canonicalJson).join(",")}]` + : typeof value === "object" && value !== null + ? `{${Object.keys(value) + .sort() + .map((key) => `${JSON.stringify(key)}:${canonicalJson((value as never)[key])}`) + .join(",")}}` + : JSON.stringify(value); +const vectorBytes = () => utf8(canonicalJson(vector.document)); +const sha256 = (value: string) => createHash("sha256").update(value).digest("hex"); + +test("the public interface is create, open and write", () => { + expect(Object.keys(api).sort()).toEqual(["createLedger", "createWriter", "openLedger"]); }); -test("independent Node author verifies Ledger hash and signature subjects", async () => { - const fixed = JSON.parse( - readFileSync(new URL("./vectors/signed-log.json", import.meta.url), "utf8"), - ) as LedgerSnapshot; - const generated = await saved(); - const key = createPrivateKey({ - key: Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed]), - format: "der", - type: "pkcs8", - }); - for (const wire of [fixed, generated]) { - for (const [kind, records] of [ - ["entry", wire.entries], - ["commit", wire.commits], - ] as const) - for (const record of records) - expect(record.id).toBe( - `${kind}:${createHash("sha256").update(`ledger.${kind}/1\0`).update(canonical(record.subject)).digest("hex")}`, - ); - for (const record of wire.commits) - expect(record.signature).toBe( - sign(null, Buffer.from(`ledger.signature/1\0${canonical(record.subject)}`), key).toString( - "base64url", - ), - ); - expect((await verifyLedger(encodeJson(wire))).integrity).toBe("valid"); - } - const reader = await createLedger(); - await reader.import(fixed); - expect((await reader.replay())[0].payload.data).toEqual({ value: 7 }); + +test("the v2 vector opens with the expected IDs and exports the same bytes", async () => { + const bytes = vectorBytes(); + const history = await openLedger(bytes); + expect(history.documentId).toBe(vector.expected.documentId); + expect(history.head).toBe(vector.expected.head); + expect( + history.commits.map((commit) => ({ id: commit.id, entryIds: commit.entries.map((e) => e.id) })), + ).toEqual( + vector.expected.commits.map((c: { commitId: string; entryIds: string[] }) => ({ + id: c.commitId, + entryIds: c.entryIds, + })), + ); + expect(history.export()).toEqual(bytes); + expect(bytes.length).toBe(1403); }); -test("custom projection replays saved history and includes explicitly marked staged entries", async () => { - const log = await createLedger({ - signer: await signer(), - now, - initialProjection: 0, - projector: (total, entry) => total + Number((entry.payload.data as { value: number }).value), - }); - await log.load(await saved()); - expect(await log.replay()).toBe(7); - await log.append({ kind: "reading", payload: { value: 3 } }); - expect(log.getState().projection).toBe(10); - expect(await log.replay({ includeStaged: false })).toBe(7); - await log.clearStaged(); - expect(await log.recompute()).toBe(7); + +test("IDs and signed messages match an independent Node hash of the vector", async () => { + const history = await openLedger(vectorBytes()); + vector.expected.commits.forEach( + (expected: { bodyMessageUtf8: string; signatureMessageUtf8: string }, index: number) => { + const commit = history.commits[index]; + expect(commit.proof.subject.hash).toBe(`sha256:${sha256(expected.bodyMessageUtf8)}`); + const proofJson = JSON.parse(expected.signatureMessageUtf8.split("\0")[1]); + expect(proofJson.subject.hash).toBe(commit.proof.subject.hash); + }, + ); + const child = history.commits[1]; + expect(text(history.export())).toContain('"payload":{"10":"train","2":"travel"}'); + expect(child.entries[0].meta).toEqual({ example: true }); }); -test("concurrent operations serialize into the same commit, with no lost entries", async () => { - const log = await createLedger({ signer: await signer(), now }); - await log.create(); - const [a, b, committed] = await Promise.all([ - log.append({ kind: "a", payload: 1 }), - log.append({ kind: "b", payload: 2 }), - log.commit(), + +test("create, write, commit, export and reopen round-trip", async () => { + const alice = await createIdentity(); + const genesis = await createLedger({ signer: alice, metadata: { model: "expenses" } }); + expect(genesis.commits).toHaveLength(1); + expect(genesis.commits[0].entries).toEqual([]); + + const writer = createWriter(genesis, alice); + writer.append({ kind: "expense.recorded", payload: { amount: 2500, note: "café ☕" } }); + writer.append([ + { kind: "expense.tagged", payload: ["travel"], meta: { source: "test" } }, + { kind: "expense.noted", payload: null }, ]); - expect(committed.committedEntryIds).toEqual([a.entry.id, b.entry.id]); - expect((await log.export()).entries).toHaveLength(2); + expect(writer.staged).toHaveLength(3); + const next = await writer.commit({ device: "phone" }); + + expect(writer.history).toBe(next); + expect(writer.staged).toEqual([]); + expect(genesis.commits).toHaveLength(1); + expect(next.commits[0]).toBe(genesis.commits[0]); + expect(next.commits[1].parent).toBe(genesis.head); + expect(next.commits[1].proof.signer).toEqual(alice.publicIdentity); + + const bytes = next.export(); + const reopened = await openLedger(bytes); + expect(reopened.commits).toEqual(next.commits); + expect(reopened.export()).toEqual(bytes); + expect(reopened.compare(next)).toBe("equal"); + await expect(openLedger(bytes, { maxBytes: bytes.length })).resolves.toBeDefined(); + await expect(openLedger(bytes, { maxBytes: bytes.length - 1 })).rejects.toThrow(RangeError); }); -test("genesis entries and supplied context nonces use the same Ledger lifecycle", async () => { - const log = await createLedger({ signer: await signer(), now }); - const contextNonce = Buffer.alloc(16, 7).toString("base64url"); - await log.create({ - metadata: { framework: "example" }, - entries: [{ kind: "init", nonce: contextNonce, payload: { initialized: true } }], - }); - const wire = await log.export(); - expect(wire.commits).toHaveLength(1); - expect(wire.entries).toHaveLength(1); - expect(wire.entries[0].subject).toMatchObject({ parent: null, nonce: contextNonce }); - expect((await log.verify()).integrity).toBe("valid"); - await log.append({ kind: "next", nonce: contextNonce }); - const before = log.getState(); - await expect(log.append({ kind: "duplicate", nonce: contextNonce })).rejects.toMatchObject({ - finding: { code: "SCHEMA_INVALID" }, - }); - expect(log.getState()).toBe(before); - await expect(log.append({ kind: "malformed", nonce: "bad" })).rejects.toMatchObject({ - finding: { code: "SCHEMA_INVALID" }, - }); + +test("staged entry IDs are kept through commit", async () => { + const alice = await createIdentity(); + const writer = createWriter(await createLedger({ signer: alice }), alice); + writer.append({ kind: "a", payload: 1, nonce: "AAAAAAAAAAAAAAAAAAAAAA" }); + const [staged] = writer.staged; + const history = await writer.commit(); + expect(history.commits[1].entries[0]).toEqual(staged); + const reopened = await openLedger(history.export()); + expect(reopened.commits[1].entries[0].id).toBe(staged.id); }); -test("signing failures preserve the committed snapshot and staged entries for retry", async () => { - const identity = await signer(); - let broken = false; - const cap: LedgerSigner = { - publicIdentity: identity.publicIdentity, - sign: (bytes) => { - if (broken) throw new Error("secret implementation failure"); - return identity.sign(bytes); - }, - }; - const log = await createLedger({ signer: cap, now }); - await log.create(); - await log.append({ kind: "retry", payload: false }); - const before = log.getState(); - broken = true; - await expect(log.commit()).rejects.toMatchObject({ finding: { code: "SIGNING_FAILED" } }); - expect(log.getState()).toBe(before); - broken = false; - await log.commit(); - expect(log.getState().staged).toEqual([]); + +test("compare reports equal, ahead, behind, diverged and unrelated", async () => { + const alice = await createIdentity(); + const base = await createLedger({ signer: alice }); + const one = createWriter(base, alice); + one.append({ kind: "a", payload: 1 }); + const ahead = await one.commit(); + const two = createWriter(base, alice); + two.append({ kind: "b", payload: 2 }); + const fork = await two.commit(); + const other = await createLedger({ signer: alice }); + + expect(base.compare(base)).toBe("equal"); + expect(ahead.compare(base)).toBe("ahead"); + expect(base.compare(ahead)).toBe("behind"); + expect(ahead.compare(fork)).toBe("diverged"); + expect(base.compare(other)).toBe("unrelated"); }); -test("a signature from another key cannot publish a candidate", async () => { - const a = await signer(), - b = await signer(2); - const log = await createLedger({ - signer: { publicIdentity: a.publicIdentity, sign: b.sign }, - now, - }); - await expect(log.create()).rejects.toMatchObject({ finding: { code: "SIGNATURE_INVALID" } }); - expect(log.getState().container).toBeNull(); + +test("histories can only come from Ledger", async () => { + const alice = await createIdentity(); + const history = await createLedger({ signer: alice }); + const lookalike = { ...history, commits: history.commits } as History; + const prototypeCopy = Object.create(Object.getPrototypeOf(history)) as History; + expect(() => createWriter(lookalike, alice)).toThrow(); + expect(() => createWriter(prototypeCopy, alice)).toThrow(); + expect(() => history.compare(lookalike)).toThrow(); + const Constructor = history.constructor as new (...args: unknown[]) => History; + expect(() => new Constructor(Symbol("issue"), [], [], 0, 1)).toThrow(); }); -test("invalid inputs and failed batch projections leave staged and committed state intact", async () => { - const log = await createLedger({ - signer: await signer(), - now, - initialProjection: [] as string[], - projector: (entries, entry) => { - if (entry.kind === "rejected") throw new Error("reducer failure"); - return [...entries, entry.kind]; - }, - }); - await log.create(); - const before = log.getState(); - await expect(log.appendMany([{ kind: "ok" }, { kind: "rejected" }])).rejects.toThrow( - "reducer failure", - ); - expect(log.getState()).toBe(before); - let read = false; - const payload = Object.defineProperty({}, "value", { - enumerable: true, - get() { - read = true; - return 1; - }, - }); - await expect(log.append({ kind: "accessor", payload })).rejects.toBeInstanceOf(Fault); - expect(read).toBe(false); - expect(log.getState()).toBe(before); - await log.append({ kind: "ok" }); - await expect(log.load(await saved())).rejects.toMatchObject({ - finding: { code: "DRAFT_PENDING" }, - }); - expect(log.getState().staged).toHaveLength(1); + +test("an empty commit rejects, and discard clears staging", async () => { + const alice = await createIdentity(); + const writer = createWriter(await createLedger({ signer: alice }), alice); + await expect(writer.commit()).rejects.toThrow(); + writer.append({ kind: "a", payload: 1 }); + writer.discard(); + expect(writer.staged).toEqual([]); + writer.append([]); + expect(writer.staged).toEqual([]); }); -test("tampering, duplicate records, unsupported formats and bad signatures never replace valid state", async () => { - const original = await saved(); - const mutations: ((wire: LedgerSnapshot) => void)[] = [ - (wire) => { - wire.entries[0].subject.payload.data = "tampered"; - }, - (wire) => { - wire.commits[1].subject.metadata = { altered: true }; - }, - (wire) => { - wire.commits[1].signature = Buffer.alloc(64).toString("base64url"); - }, - (wire) => { - wire.entries.push(wire.entries[0]); - }, - (wire) => { - wire.commits.reverse(); - }, - (wire) => { - wire.format = "concord" as "ledger"; - }, + +test("a batch is validated whole before any of it is staged", async () => { + const alice = await createIdentity(); + const writer = createWriter(await createLedger({ signer: alice }), alice); + const nonce = "AAAAAAAAAAAAAAAAAAAAAA"; + writer.append({ kind: "a", payload: 1, nonce }); + const invalid = [ + [ + { kind: "ok", payload: 1 }, + { kind: "", payload: 1 }, + ], + [ + { kind: "ok", payload: 1 }, + { kind: "x".repeat(129), payload: 1 }, + ], + [ + { kind: "ok", payload: 1 }, + { kind: "b", payload: 1, nonce }, + ], + [{ kind: "b", payload: 1, nonce: "short" }], + [{ kind: "b", payload: 1.5 }], + [{ kind: "b", payload: -0 }], + [{ kind: "b", payload: Number.MAX_SAFE_INTEGER + 1 }], + [{ kind: "b", payload: "\ud800" }], + [{ kind: "b", payload: new Date() }], + [{ kind: "b", payload: undefined }], + [{ kind: "b", payload: 1, meta: [] }], ]; - const log = await createLedger(); - await log.load(original); - for (const mutate of mutations) { - const wire = structuredClone(original); - mutate(wire); - expect((await verifyLedger(encodeJson(wire))).integrity).not.toBe("valid"); - await expect(log.import(wire)).rejects.toBeInstanceOf(Fault); - expect(await log.export()).toEqual(original); - } -}); -test("new signers can append without introducing framework membership or authority policy", async () => { - const log = await createLedger({ signer: await signer(3), now }); - await log.load(await saved()); - await log.append({ kind: "second-writer" }); - await log.commit(); - expect((await log.verify()).integrity).toBe("valid"); - const wire = await log.export(); - expect(wire.entries[1].subject.author).toBe(wire.commits[2].subject.signer.id); -}); -test("snapshot relationships retain independent forks and reject cross-protocol imports", async () => { - const base = await saved(), - a = await createLedger({ signer: await signer(), now }), - b = await createLedger({ signer: await signer(2), now }); - await a.load(base); - await b.load(base); - await a.append({ kind: "a" }); - await b.append({ kind: "b" }); - await a.commit(); - await b.commit(); - const x = encodeJson(await a.export()), - y = encodeJson(await b.export()); - expect(await compareLedgers(x, y)).toEqual({ ok: true, value: "diverged" }); - expect(await compareLedgers(encodeJson(base), x)).toEqual({ ok: true, value: "behind" }); + for (const batch of invalid) expect(() => writer.append(batch as never)).toThrow(); + expect(writer.staged).toHaveLength(1); }); -test("resource bounds and observer failures preserve usable committed state", async () => { - const log = await createLedger({ - signer: await signer(), - now, - limits: { maxPayloadBytes: 16, maxMetadataBytes: 16 }, - }); - let notifications = 0; - const unsubscribe = log.subscribe(() => { - notifications++; - throw new Error("observer"); - }); - await log.create(); - await expect(log.append({ kind: "large", payload: "x".repeat(20) })).rejects.toMatchObject({ - finding: { code: "RESOURCE_LIMIT" }, - }); - await log.append({ kind: "ok", payload: null }); - await expect(log.commit({ metadata: { large: "x".repeat(20) } })).rejects.toMatchObject({ - finding: { code: "RESOURCE_LIMIT" }, - }); - await log.commit(); - expect(notifications).toBeGreaterThan(2); - unsubscribe(); - await log.destroy(); - await expect(log.export()).rejects.toMatchObject({ finding: { code: "LEDGER_DESTROYED" } }); + +test("inputs are copied when staged and committed views are frozen", async () => { + const alice = await createIdentity(); + const writer = createWriter(await createLedger({ signer: alice }), alice); + const payload = { amount: 1, tags: ["a"] }; + writer.append({ kind: "a", payload }); + payload.tags.push("b"); + const history = await writer.commit(); + const entry = history.commits[1].entries[0]; + expect(entry.payload).toEqual({ amount: 1, tags: ["a"] }); + expect(Object.isFrozen(entry.payload)).toBe(true); + expect(Object.isFrozen(history.commits)).toBe(true); + expect(() => (history.commits as Commit[]).push(history.commits[0])).toThrow(); }); -test("default Ledger readers accept opaque framework payloads within the shared snapshot cap", async () => { - const log = await createLedger({ signer: await signer(), now }); - await log.create(); - await log.append({ kind: "opaque", payload: { ciphertext: "A".repeat(1400 * 1024) } }); - await log.commit(); - const reader = await createLedger(); - await reader.load(await log.export()); - expect((await reader.verify()).integrity).toBe("valid"); +type Commit = History["commits"][number]; + +test("mutations reject during a commit; reads see the previous history", async () => { + const alice = await createIdentity(); + const history = await createLedger({ signer: alice }); + let release!: () => void; + const gate = new Promise((resolve) => (release = resolve)); + const slowSigner = { + publicIdentity: alice.publicIdentity, + sign: async (bytes: Uint8Array) => { + await gate; + return alice.sign(bytes); + }, + }; + const writer = createWriter(history, slowSigner); + writer.append({ kind: "a", payload: 1 }); + const pending = writer.commit(); + expect(writer.history).toBe(history); + expect(writer.staged).toHaveLength(1); + expect(() => writer.append({ kind: "b", payload: 2 })).toThrow(); + expect(() => writer.discard()).toThrow(); + await expect(writer.commit()).rejects.toThrow(); + release(); + await pending; + writer.append({ kind: "b", payload: 2 }); + expect(writer.staged).toHaveLength(1); }); -test("callbacks cannot synchronously reenter the same mutation queue", async () => { - const log = await createLedger({ signer: await signer(), now }); - await log.create(); - const attempts: Promise[] = []; - log.subscribe(() => { - attempts.push(log.append({ kind: "recursive" })); - }); - await Promise.all( - attempts.map((pending) => - expect(pending).rejects.toMatchObject({ finding: { code: "HOST_CONFIGURATION" } }), - ), - ); - expect(log.getState().staged).toEqual([]); + +test("a failed commit keeps history and staging, and a retry succeeds", async () => { + const alice = await createIdentity(); + const mallory = await createIdentity(); + const history = await createLedger({ signer: alice }); + let wrongKey = true; + const flaky: Pick = { + publicIdentity: alice.publicIdentity, + sign: (bytes) => (wrongKey ? mallory.sign(bytes) : alice.sign(bytes)), + }; + const writer = createWriter(history, flaky); + writer.append({ kind: "a", payload: 1 }); + await expect(writer.commit()).rejects.toThrow(); + expect(writer.history).toBe(history); + expect(writer.staged).toHaveLength(1); + wrongKey = false; + expect((await writer.commit()).commits).toHaveLength(2); }); -test("invalid option shapes cannot sign or change the current state", async () => { - const identity = await signer(); - let signatures = 0; - const log = await createLedger({ - signer: { - publicIdentity: identity.publicIdentity, - sign(bytes) { - signatures++; - return identity.sign(bytes); - }, - }, - now, - }); - const empty = log.getState(); - for (const invalid of [null, 7, false, "", []]) { - await expect(createLedger(invalid as never)).rejects.toMatchObject({ - finding: { code: "HOST_CONFIGURATION" }, - }); - await expect(log.create(invalid as never)).rejects.toMatchObject({ - finding: { code: "SCHEMA_INVALID" }, - }); - expect(log.getState()).toBe(empty); - } - expect(signatures).toBe(0); - await expect(createLedger({ limits: [] as never })).rejects.toMatchObject({ - finding: { code: "HOST_CONFIGURATION" }, - }); - await log.create(); - await log.append({ kind: "pending" }); - const staged = log.getState(); - for (const invalid of [null, 7, false, "", []]) { - await expect(log.commit(invalid as never)).rejects.toMatchObject({ - finding: { code: "SCHEMA_INVALID" }, - }); - await expect(log.replay(invalid as never)).rejects.toMatchObject({ - finding: { code: "HOST_CONFIGURATION" }, - }); - expect(log.getState()).toBe(staged); - } - expect(signatures).toBe(1); - await log.commit(); - expect(signatures).toBe(2); + +test("a commit that would pass maxBytes rejects and keeps staging", async () => { + const alice = await createIdentity(); + const genesis = await createLedger({ signer: alice, maxBytes: 2000 }); + const writer = createWriter(genesis, alice); + writer.append({ kind: "a", payload: "x".repeat(2000) }); + await expect(writer.commit()).rejects.toThrow(RangeError); + expect(writer.staged).toHaveLength(1); + writer.discard(); + writer.append({ kind: "a", payload: "é".repeat(100) }); + const next = await writer.commit(); + expect(next.export().length).toBeLessThanOrEqual(2000); + await expect(openLedger(next.export(), { maxBytes: 2000 })).resolves.toBeDefined(); }); -test("oversized byte imports reject and preserve the current state", async () => { - const log = await createLedger({ signer: await signer(), now, limits: { maxBytes: 4096 } }); - await log.create(); - const before = log.getState(); - const input = new Uint8Array(4097); - for (const load of [ - (bytes: Uint8Array) => log.load(bytes), - (bytes: Uint8Array) => log.import(bytes), + +test("open rejects tampering, broken linkage, non-canonical bytes and other versions", async () => { + const doc = () => structuredClone(vector.document); + const reject = async (document: unknown) => + expect(openLedger(utf8(canonicalJson(document)))).rejects.toThrow(); + + const payload = doc(); + payload.commits[1].body.entries[0].payload.amount = 2501; + await reject(payload); + const kind = doc(); + kind.commits[1].body.entries[1].kind = "expense.untagged"; + await reject(kind); + const parent = doc(); + parent.commits[1].body.parent = `commit:${"0".repeat(64)}`; + await reject(parent); + const order = doc(); + order.commits.reverse(); + await reject(order); + const signer = doc(); + signer.commits[1].proof.signer = signer.commits[0].proof.signer; + await reject(signer); + const extra = doc(); + extra.commits[1].body.entries[0].extra = true; + await reject(extra); + const empty = doc(); + empty.commits[1].body.entries = []; + await reject(empty); + const duplicate = doc(); + duplicate.commits[1].body.entries[1].nonce = duplicate.commits[1].body.entries[0].nonce; + await reject(duplicate); + await reject({ ...doc(), version: 1 }); + await reject({ ...doc(), commits: [] }); + + const canonical = text(vectorBytes()); + for (const variant of [ + JSON.stringify(vector.document, null, 2), + `${canonical}`, + canonical.replace('"amount":2500', '"amount":2.5e3'), + canonical.replace('"format":"ledger"', '"format":"ledger","format":"ledger"'), + canonical.replace('"model"', '"\\u006dodel"'), ]) { - await expect(load(input)).rejects.toMatchObject({ finding: { code: "RESOURCE_LIMIT" } }); - expect(log.getState()).toBe(before); + await expect(openLedger(utf8(variant))).rejects.toThrow(); } + await expect(openLedger(new Uint8Array([0xff]))).rejects.toThrow(); }); diff --git a/packages/ledger/test/payload.test.ts b/packages/ledger/test/payload.test.ts deleted file mode 100644 index aeddb7b..0000000 --- a/packages/ledger/test/payload.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { expect, test } from "vite-plus/test"; -import { - createLedger, - encodePayload, - decodePayload, - type LedgerPayloadEncoder, - type LedgerPayloadDecoder, -} from "../src/index.js"; -import { signerFromSeed } from "@ternent/identity"; - -// A transport codec proves that payload integration is independent of encryption. -const codec: LedgerPayloadEncoder & LedgerPayloadDecoder = { - id: "test.reverse", - encode: async (bytes) => new Uint8Array(bytes).reverse(), - decode: async (bytes) => new Uint8Array(bytes).reverse(), -}; -test("host codecs round-trip through ordinary staging, committed export and replay", async () => { - const signer = await signerFromSeed(new Uint8Array(32).fill(4)); - if (!signer.ok) throw new Error(signer.error.code); - const log = await createLedger({ signer: signer.value }); - await log.create(); - const encoded = await encodePayload({ value: "payload" }, codec); - await log.appendMany([ - { kind: "plain", payload: false }, - { kind: "encoded", payload: encoded }, - ]); - expect((await log.export()).entries).toHaveLength(0); - expect((await log.replay())[1].committed).toBe(false); - await log.commit(); - const before = await log.export(); - const reader = await createLedger(); - await reader.load(before); - const entries = await reader.replay(); - expect(await decodePayload(entries[0].payload.data, codec)).toEqual({ - status: "plain", - data: false, - }); - expect(await decodePayload(entries[1].payload.data, codec)).toEqual({ - status: "decoded", - data: { value: "payload" }, - }); - expect(await decodePayload(encoded)).toEqual({ status: "locked", codec: codec.id }); - expect( - await decodePayload(encoded, { - id: "another", - decode: async () => { - throw new Error("must not run"); - }, - }), - ).toEqual({ status: "locked", codec: codec.id }); - expect(await decodePayload(encoded, { id: codec.id })).toEqual({ - status: "locked", - codec: codec.id, - }); - expect(await decodePayload(encoded, { id: codec.id, decode: async () => null })).toEqual({ - status: "locked", - codec: codec.id, - }); - expect(await reader.export()).toEqual(before); - expect((await reader.verify()).integrity).toBe("valid"); -}); -test("failed encoding never appends plaintext; codec and malformed payload failures stay explicit", async () => { - const broken = { - id: "failed", - encode: async () => { - throw new Error("unavailable"); - }, - }; - await expect(encodePayload("secret", broken)).rejects.toThrow("unavailable"); - await expect(encodePayload("secret", { id: "read-only" } as never)).rejects.toMatchObject({ - finding: { code: "HOST_CONFIGURATION" }, - }); - await expect( - encodePayload("secret", { id: "Bad ID", encode: codec.encode }), - ).rejects.toMatchObject({ finding: { code: "HOST_CONFIGURATION" } }); - const payload = await encodePayload("secret", codec); - for (const malformed of [ - { ...payload, version: 2 }, - { ...payload, data: "non-canonical=" }, - { ...payload, extra: true }, - { ...payload, codec: "" }, - ]) - await expect(decodePayload(malformed, codec)).rejects.toMatchObject({ - finding: { code: "PAYLOAD_INVALID" }, - }); - await expect( - decodePayload(payload, { - id: codec.id, - decode: async () => { - throw new Error("reader failed"); - }, - }), - ).rejects.toThrow("reader failed"); - await expect( - decodePayload(payload, { - id: codec.id, - decode: async () => new TextEncoder().encode('{"duplicate":1,"duplicate":2}'), - }), - ).rejects.toMatchObject({ finding: { code: "JSON_INVALID" } }); - await expect( - encodePayload("secret", { id: "invalid", encode: async () => null as never }), - ).rejects.toMatchObject({ finding: { code: "PAYLOAD_CODEC_INVALID" } }); - await expect( - decodePayload(payload, { id: codec.id, decode: async () => "bad" as never }), - ).rejects.toMatchObject({ finding: { code: "PAYLOAD_CODEC_INVALID" } }); -}); -test("codec calls capture portable JSON before awaiting and enforce encoded and decoded limits", async () => { - const input = { value: "before" }; - const pending = encodePayload(input, codec); - input.value = "after"; - expect(await decodePayload(await pending, codec)).toEqual({ - status: "decoded", - data: { value: "before" }, - }); - await expect(encodePayload("x".repeat(100), codec, { maxBytes: 16 })).rejects.toMatchObject({ - finding: { code: "RESOURCE_LIMIT" }, - }); - await expect( - encodePayload( - null, - { id: "large", encode: async () => new Uint8Array(128) }, - { maxBytes: 100 }, - ), - ).rejects.toMatchObject({ finding: { code: "RESOURCE_LIMIT" } }); - await expect( - encodePayload(null, { id: "large", encode: async () => new Uint8Array(64) }, { maxBytes: 100 }), - ).rejects.toMatchObject({ finding: { code: "RESOURCE_LIMIT" } }); - const payload = await encodePayload(null, codec); - await expect( - decodePayload( - payload, - { id: codec.id, decode: async () => new Uint8Array(129) }, - { maxBytes: 128 }, - ), - ).rejects.toMatchObject({ finding: { code: "RESOURCE_LIMIT" } }); -}); diff --git a/packages/ledger/test/vectors.json b/packages/ledger/test/vectors.json new file mode 100644 index 0000000..c7fe0bf --- /dev/null +++ b/packages/ledger/test/vectors.json @@ -0,0 +1,95 @@ +{ + "document": { + "format": "ledger", + "version": 2, + "commits": [ + { + "body": { + "parent": null, + "nonce": "AQEBAQEBAQEBAQEBAQEBAQ", + "entries": [], + "metadata": { + "model": "expenses" + } + }, + "proof": { + "format": "seal", + "version": 1, + "createdAt": "2026-11-27T12:00:00.000Z", + "subject": { + "hash": "sha256:c1cdc29b334ce1e6e53777539f0ac941fa98c9118cd0c17231cb7e89319bcc81" + }, + "signer": { + "version": 1, + "algorithm": "Ed25519", + "publicKey": "iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w", + "id": "identity:34750f98bd59fcfc946da45aaabe933be154a4b5094e1c4abf42866505f3c97e" + }, + "signature": "Qmqca3aN4guyg8TXiYMN3po0UInwGBYB8JXuxglbMYYlH-ItT06b0P8gwk5XcRYEO4mTodvhrwfDxlRloA25AA" + } + }, + { + "body": { + "parent": "commit:b0e752d63fc76670e3bd6a9e69baa7de336894dc50b1360a5c0d86f85d36f18a", + "nonce": "AgICAgICAgICAgICAgICAg", + "entries": [ + { + "nonce": "AwMDAwMDAwMDAwMDAwMDAw", + "kind": "expense.recorded", + "payload": { + "amount": 2500 + }, + "meta": { + "example": true + } + }, + { + "nonce": "BAQEBAQEBAQEBAQEBAQEBA", + "kind": "expense.tagged", + "payload": { + "2": "travel", + "10": "train" + } + } + ] + }, + "proof": { + "format": "seal", + "version": 1, + "createdAt": "2026-11-27T12:00:01.000Z", + "subject": { + "hash": "sha256:c8192893ef94449bf584a4f0e6119c32504554aad64f987cd4226c0deb958aab" + }, + "signer": { + "version": 1, + "algorithm": "Ed25519", + "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", + "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" + }, + "signature": "a1m92SrdIZnz8ov-rLot7c9JoIRIZ0gAfg60DDjLKxYHWKIyVYkFdK-V9ATtkiu5o_b4k8M0gR5Jj1IhHpiXDw" + } + } + ] + }, + "expected": { + "documentId": "commit:b0e752d63fc76670e3bd6a9e69baa7de336894dc50b1360a5c0d86f85d36f18a", + "head": "commit:821bcd4f2fa3fb20ec0e11c91b43cd6b2d20b33c9f788e085314088de9bea908", + "commits": [ + { + "commitId": "commit:b0e752d63fc76670e3bd6a9e69baa7de336894dc50b1360a5c0d86f85d36f18a", + "entryIds": [], + "bodyMessageUtf8": "ledger.commit/2\u0000{\"entries\":[],\"metadata\":{\"model\":\"expenses\"},\"nonce\":\"AQEBAQEBAQEBAQEBAQEBAQ\",\"parent\":null}", + "signatureMessageUtf8": "ternent-seal/v1\u0000{\"createdAt\":\"2026-11-27T12:00:00.000Z\",\"format\":\"seal\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:34750f98bd59fcfc946da45aaabe933be154a4b5094e1c4abf42866505f3c97e\",\"publicKey\":\"iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w\",\"version\":1},\"subject\":{\"hash\":\"sha256:c1cdc29b334ce1e6e53777539f0ac941fa98c9118cd0c17231cb7e89319bcc81\"},\"version\":1}" + }, + { + "commitId": "commit:821bcd4f2fa3fb20ec0e11c91b43cd6b2d20b33c9f788e085314088de9bea908", + "entryIds": [ + "entry:1388f326b19c6b1ba4d9c6fd7744fd72c4921f41c8e31be7fa4ef71d3fa11028", + "entry:0a6c8066ea58f35198e364d7af92d70988d8a944ff80dade2b6d937b651dca59" + ], + "bodyMessageUtf8": "ledger.commit/2\u0000{\"entries\":[{\"kind\":\"expense.recorded\",\"meta\":{\"example\":true},\"nonce\":\"AwMDAwMDAwMDAwMDAwMDAw\",\"payload\":{\"amount\":2500}},{\"kind\":\"expense.tagged\",\"nonce\":\"BAQEBAQEBAQEBAQEBAQEBA\",\"payload\":{\"10\":\"train\",\"2\":\"travel\"}}],\"nonce\":\"AgICAgICAgICAgICAgICAg\",\"parent\":\"commit:b0e752d63fc76670e3bd6a9e69baa7de336894dc50b1360a5c0d86f85d36f18a\"}", + "signatureMessageUtf8": "ternent-seal/v1\u0000{\"createdAt\":\"2026-11-27T12:00:01.000Z\",\"format\":\"seal\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827\",\"publicKey\":\"gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q\",\"version\":1},\"subject\":{\"hash\":\"sha256:c8192893ef94449bf584a4f0e6119c32504554aad64f987cd4226c0deb958aab\"},\"version\":1}" + } + ] + } +} diff --git a/packages/ledger/test/vectors/signed-log.json b/packages/ledger/test/vectors/signed-log.json deleted file mode 100644 index d6cf4ac..0000000 --- a/packages/ledger/test/vectors/signed-log.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "format": "ledger", - "version": 1, - "documentId": "commit:44036914c869f0b6f510affdcd4bb4c6ff330ea5f45dc57f1d3d3362e354125e", - "head": "commit:1f6252775f4724a16d08eb4c7e24d6db3b9514b129f837fbe6fbeff18172ec70", - "commits": [ - { - "id": "commit:44036914c869f0b6f510affdcd4bb4c6ff330ea5f45dc57f1d3d3362e354125e", - "subject": { - "version": 1, - "suite": "ledger-ed25519-v1", - "parent": null, - "nonce": "AQEBAQEBAQEBAQEBAQEBAQ", - "signer": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "committedAt": "2026-11-21T00:00:00.000Z", - "entryIds": [], - "metadata": { - "title": "Independent log" - } - }, - "signature": "jEFmZc56rh6Frxtgx_ye-Q5vBuHJshyt2nblVE1uzXC5EgP8kpt3inFgAiNMHrnTMx18YzworNXGfuhu4WWkBw" - }, - { - "id": "commit:1f6252775f4724a16d08eb4c7e24d6db3b9514b129f837fbe6fbeff18172ec70", - "subject": { - "version": 1, - "suite": "ledger-ed25519-v1", - "parent": "commit:44036914c869f0b6f510affdcd4bb4c6ff330ea5f45dc57f1d3d3362e354125e", - "nonce": "AwMDAwMDAwMDAwMDAwMDAw", - "signer": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "committedAt": "2026-11-21T00:00:02.000Z", - "entryIds": ["entry:ae773cd6e368c5dab353cec92ea37742263bfdbb1ee1458b0b5a22df7501b838"], - "metadata": { - "source": "Node crypto reference author" - } - }, - "signature": "RrgR48AqYVvf5tMevc87lmt3KCW9ardWtbMQ_2R9j5-f6M7eS8dwwHuzeafhni5VK7ze-PnugslQt8f0u2evDA" - } - ], - "entries": [ - { - "id": "entry:ae773cd6e368c5dab353cec92ea37742263bfdbb1ee1458b0b5a22df7501b838", - "subject": { - "version": 1, - "parent": "commit:44036914c869f0b6f510affdcd4bb4c6ff330ea5f45dc57f1d3d3362e354125e", - "nonce": "AgICAgICAgICAgICAgICAg", - "kind": "reading", - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T00:00:01.000Z", - "meta": null, - "payload": { - "type": "plain", - "data": { - "value": 7 - } - } - } - } - ] -} diff --git a/packages/ledger/vite.config.ts b/packages/ledger/vite.config.ts index 7530923..0251310 100644 --- a/packages/ledger/vite.config.ts +++ b/packages/ledger/vite.config.ts @@ -5,6 +5,6 @@ export default defineConfig({ ...base, pack: { ...base.pack, - entry: { index: "src/index.ts", "protocol/index": "src/protocol/index.ts" }, + entry: { index: "src/index.ts" }, }, }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1973afb..62cfaff 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -283,9 +283,15 @@ importers: '@noble/hashes': specifier: 2.4.0 version: 2.4.0 + '@scure/base': + specifier: 2.4.0 + version: 2.4.0 '@ternent/identity': specifier: workspace:^ version: link:../identity + '@ternent/seal': + specifier: workspace:^ + version: link:../seal devDependencies: typescript: specifier: npm:@typescript/typescript6@6.0.2 From 365f3c8f6711b3bc8221a48b55cb989f8b3be511 Mon Sep 17 00:00:00 2001 From: samternent Date: Sat, 28 Nov 2026 00:06:14 +0000 Subject: [PATCH 07/24] ci: stop sealing release bundles Remove the Seal Action, the test and release signing identities and the proof verification from CI and the release workflow, along with the release CLI commands and the mandatory Seal hook in the publisher that served them. prepare-release still records the workflow origin and checks it on resume. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 17 -------- .github/workflows/release.yml | 26 ------------- scripts/release/cli.mjs | 60 +--------------------------- scripts/release/cli.test.mjs | 59 ++-------------------------- scripts/release/publish.mjs | 20 ++-------- scripts/release/publish.test.mjs | 60 ++-------------------------- scripts/release/seal.mjs | 63 ------------------------------ scripts/release/seal.test.mjs | 67 -------------------------------- 8 files changed, 14 insertions(+), 358 deletions(-) delete mode 100644 scripts/release/seal.mjs delete mode 100644 scripts/release/seal.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2022f02..621debc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,23 +63,6 @@ jobs: run: node scripts/release/cli.mjs verification-plan - name: Retain the built release verifier tools run: node scripts/release/flow.mjs capture-tools - - name: Create a disposable proof-test identity - id: seal-test-key - run: node scripts/release/cli.mjs test-identity - - name: Exercise the pinned Seal Action on the release bundle - uses: samternent/seal-action@d07a683a9195a1190c3e15b6e4374a1d59592b57 - with: - assets-directory: artifacts/release - manifest-name: release-manifest.json - proof-name: release-proof.json - public-key-name: release-public-key.json - cli-command: '"${{ steps.seal-test-key.outputs.node }}" "${{ github.workspace }}/packages/seal/bin/seal"' - env: - SEAL_IDENTITY_FILE: ${{ steps.seal-test-key.outputs.identity-file }} - - name: Verify the Action proof and every bundled file - run: node scripts/release/cli.mjs verify-seal - env: - SEAL_RELEASE_PUBLIC_KEY: ${{ steps.seal-test-key.outputs.public-key }} - name: Retain acceptance evidence if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 10c6c5e..4f133db 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -71,7 +71,6 @@ jobs: id-token: write env: CORE_RELEASE_ENABLED: ${{ vars.CORE_RELEASE_ENABLED }} - SEAL_RELEASE_PUBLIC_KEY: ${{ vars.SEAL_RELEASE_PUBLIC_KEY }} RELEASE_SOURCE_SHA: ${{ needs.select.outputs.source-sha }} RELEASE_ARTIFACT_ID: ${{ needs.select.outputs.artifact-id }} RELEASE_ARTIFACT_DIGEST: ${{ needs.select.outputs.artifact-digest }} @@ -110,33 +109,8 @@ jobs: run: node scripts/release/cli.mjs prepare-release env: RELEASE_RESUMED: ${{ steps.bundle.outputs.resumed }} - - name: Materialise the dedicated release identity - if: steps.bundle.outputs.resumed != 'true' - id: identity - run: node scripts/release/cli.mjs release-identity - env: - SEAL_RELEASE_IDENTITY_B64: ${{ secrets.SEAL_RELEASE_IDENTITY_B64 }} - - name: Seal the final release bundle - if: steps.bundle.outputs.resumed != 'true' - uses: samternent/seal-action@d07a683a9195a1190c3e15b6e4374a1d59592b57 - with: - assets-directory: artifacts/release - manifest-name: release-manifest.json - proof-name: release-proof.json - public-key-name: release-public-key.json - cli-command: '"${{ steps.bundle.outputs.node }}" "${{ github.workspace }}/packages/seal/bin/seal"' - env: - SEAL_IDENTITY_FILE: ${{ steps.identity.outputs.identity-file }} - - name: Verify the externally trusted release signature - run: node scripts/release/cli.mjs verify-seal - name: Publish retained bytes, verify fresh consumers and promote the planned channel run: pnpm release:publish - - name: Remove the temporary signing identity - if: always() - env: - SEAL_IDENTITY_FILE: ${{ steps.identity.outputs.identity-file }} - run: | - if [ -n "$SEAL_IDENTITY_FILE" ]; then rm -f -- "$SEAL_IDENTITY_FILE"; fi - name: Collect complete or incomplete release evidence if: always() && steps.bundle.outcome == 'success' run: node scripts/release/flow.mjs collect diff --git a/scripts/release/cli.mjs b/scripts/release/cli.mjs index d45953d..f279e5d 100644 --- a/scripts/release/cli.mjs +++ b/scripts/release/cli.mjs @@ -1,22 +1,17 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { appendFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; -import { createSealIdentity } from "../../packages/seal/dist/crypto.js"; -import { createSealPublicKeyArtifact } from "../../packages/seal/dist/proof.js"; import { workspacePackages, readManifest } from "../verify/workspace.mjs"; import { createPlan, validatePlan } from "./plan.mjs"; import { publishRelease } from "./publish.mjs"; import { createNpmRegistryAdapter } from "./npm.mjs"; import { ReleaseError, sha256 } from "./shared.mjs"; -import { verifyReleaseSeal } from "./seal.mjs"; const [command, argument, ...extra] = process.argv.slice(2); assert(extra.length === 0, "Unexpected release arguments"); const root = process.cwd(); const directory = resolve(argument ?? "artifacts/release"); -const expectedPublicKey = (process.env.SEAL_RELEASE_PUBLIC_KEY ?? "").trim(); /** @param {string} sha */ function committedIntent(sha) { @@ -65,7 +60,6 @@ function authorize() { "RELEASE_WORKFLOW_INVALID", ); assert.equal(process.env.CORE_RELEASE_ENABLED, "true", "RELEASE_NOT_ENABLED"); - assert(expectedPublicKey, "SEAL_TRUST_MISSING"); assert( !process.env.NPM_TOKEN && !process.env.NODE_AUTH_TOKEN, "OIDC_ONLY: remove token fallback", @@ -111,34 +105,16 @@ try { sourceSha: result.plan.sourceSha, }), ); - } else if (command === "test-identity") { - assert(!argument, "test-identity takes no directory argument"); - const identity = await createSealIdentity(); - const file = join(process.env.RUNNER_TEMP ?? tmpdir(), `ternent-seal-ci-${process.pid}.json`); - writeFileSync(file, JSON.stringify(identity), { mode: 0o600, flag: "wx" }); - const key = await createSealPublicKeyArtifact({ identity }); - assert(process.env.GITHUB_OUTPUT, "GITHUB_OUTPUT_REQUIRED"); - appendFileSync( - process.env.GITHUB_OUTPUT, - `identity-file=${file}\npublic-key=${key.publicKey}\nnode=${process.execPath}\n`, - ); } else if (command === "prepare-release") { authorize(); const { plan, origin } = releaseSource(); if (process.env.RELEASE_RESUMED === "true") { - await verifyReleaseSeal({ directory, expectedPublicKey }); assert.deepEqual( JSON.parse(readFileSync(join(directory, "release-origin.json"), "utf8")), origin, "ORIGIN_INVALID", ); } else { - // GitHub archive provenance authenticates the producer. Its disposable proof - // establishes consistency here, not trust in a production release signer. - const testKey = JSON.parse(readFileSync(join(directory, "release-public-key.json"), "utf8")); - await verifyReleaseSeal({ directory, expectedPublicKey: testKey.publicKey }); - for (const file of ["release-manifest.json", "release-proof.json", "release-public-key.json"]) - rmSync(join(directory, file)); writeFileSync(join(directory, "release-origin.json"), `${JSON.stringify(origin)}\n`); } validatePlan(plan, { directory, expectedSourceSha: origin.sourceSha }); @@ -150,37 +126,6 @@ try { resumed: process.env.RELEASE_RESUMED === "true", }), ); - } else if (command === "release-identity") { - authorize(); - assert(process.env.GITHUB_OUTPUT && process.env.RUNNER_TEMP, "RUNNER_CONFIGURATION_REQUIRED"); - const encoded = process.env.SEAL_RELEASE_IDENTITY_B64; - assert(encoded, "RELEASE_IDENTITY_MISSING"); - let identity; - try { - identity = JSON.parse(Buffer.from(encoded, "base64").toString("utf8")); - } catch { - throw new Error("RELEASE_IDENTITY_INVALID"); - } - assert( - typeof identity?.material?.seed === "string" && - /^[A-Za-z0-9_-]{43}$/.test(identity.material.seed), - "RELEASE_IDENTITY_INVALID", - ); - console.log(`::add-mask::${identity.material.seed}`); - console.log(`::add-mask::${JSON.stringify(identity)}`); - let key; - try { - key = await createSealPublicKeyArtifact({ identity }); - } catch { - throw new Error("RELEASE_IDENTITY_INVALID"); - } - assert.equal(key.publicKey, expectedPublicKey, "RELEASE_IDENTITY_KEY_MISMATCH"); - const file = join(process.env.RUNNER_TEMP, `ternent-seal-release-${process.pid}.json`); - writeFileSync(file, JSON.stringify(identity), { mode: 0o600, flag: "wx" }); - appendFileSync(process.env.GITHUB_OUTPUT, `identity-file=${file}\n`); - } else if (command === "verify-seal") { - await verifyReleaseSeal({ directory, expectedPublicKey }); - console.log("Seal release bundle verified"); } else if (command === "publish") { authorize(); const { plan, origin } = releaseSource(); @@ -197,7 +142,6 @@ try { sourceSha: plan.sourceSha, channel: plan.channel, }), - verifySeal: () => verifyReleaseSeal({ directory, expectedPublicKey }), verifyConsumers: async () => { execFileSync("pnpm", ["run", "check:artifact"], { cwd: root, @@ -216,7 +160,7 @@ try { console.log(JSON.stringify(receipt)); } else throw new Error( - "Usage: release CLI plan|verification-plan|test-identity|prepare-release|release-identity|verify-seal|publish [bundle directory]", + "Usage: release CLI plan|verification-plan|prepare-release|publish [bundle directory]", ); } catch (error) { const details = diff --git a/scripts/release/cli.test.mjs b/scripts/release/cli.test.mjs index 050f709..17264b0 100644 --- a/scripts/release/cli.test.mjs +++ b/scripts/release/cli.test.mjs @@ -2,19 +2,15 @@ import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; import { chmodSync, - existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, - statSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { test } from "node:test"; -import { createSealIdentity } from "../../packages/seal/dist/crypto.js"; -import { createSealPublicKeyArtifact } from "../../packages/seal/dist/proof.js"; import { fixture } from "./fixtures.mjs"; import { createPlan } from "./plan.mjs"; import { captureTools } from "./flow.mjs"; @@ -60,11 +56,10 @@ await test("release entrypoint rejects uncommitted intent and local publication" assert.match(published.stderr, /RELEASE_WORKFLOW_REQUIRED/); }); -await test("production entrypoint preserves verified candidates through signing and resume", async (t) => { +await test("production entrypoint records the origin and preserves candidates through resume", async (t) => { const f = fixture(); t.after(() => rmSync(f.root, { recursive: true, force: true })); const cli = resolve("scripts/release/cli.mjs"); - const seal = resolve("packages/seal/bin/seal"); /** @param {string[]} args */ const git = (args) => execFileSync("git", ["-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", ...args], { @@ -92,9 +87,6 @@ await test("production entrypoint preserves verified candidates through signing const { plan } = createPlan({ ...f.planOptions, sourceSha, directory, now: new Date() }); captureTools(process.cwd(), directory); const before = plan.packages.map((pkg) => sha256(readFileSync(join(directory, pkg.tarball)))); - const signer = await createSealIdentity(); - const trusted = await createSealPublicKeyArtifact({ identity: signer }); - const producer = await createSealIdentity(); const bin = join(f.root, "bin"); mkdirSync(bin); writeFileSync( @@ -125,7 +117,6 @@ await test("production entrypoint preserves verified candidates through signing RELEASE_RUN_ID: "123", RELEASE_ARTIFACT_ID: "456", RELEASE_ARTIFACT_DIGEST: origin.artifactDigest, - SEAL_RELEASE_PUBLIC_KEY: trusted.publicKey, RUNNER_TEMP: f.root, GITHUB_OUTPUT: output, NPM_TOKEN: "", @@ -134,8 +125,6 @@ await test("production entrypoint preserves verified candidates through signing GITHUB_TOKEN: "", ACTIONS_ID_TOKEN_REQUEST_TOKEN: "", ACTIONS_ID_TOKEN_REQUEST_URL: "", - SEAL_IDENTITY: "", - SEAL_IDENTITY_FILE: "", RELEASE_RESUMED: "false", }; /** @param {string} command @param {NodeJS.ProcessEnv} [overrides] */ @@ -146,66 +135,26 @@ await test("production entrypoint preserves verified candidates through signing encoding: "utf8", }); assert.equal(result.status, 0, result.stderr); - // stdout may contain GitHub mask commands for a synthetic secret; never log it. } - /** @param {NodeJS.ProcessEnv} credentials */ - function sign(credentials) { - /** @param {string[]} args */ - const run = (args) => - execFileSync(process.execPath, [seal, ...args], { - cwd: f.root, - env: { ...env, ...credentials }, - encoding: "utf8", - }); - run([ - "manifest", - "create", - "--input", - directory, - "--out", - join(directory, "release-manifest.json"), - "--quiet", - ]); - run([ - "sign", - "--input", - join(directory, "release-manifest.json"), - "--out", - join(directory, "release-proof.json"), - "--quiet", - ]); - writeFileSync(join(directory, "release-public-key.json"), run(["public-key", "--json"])); - } - sign({ SEAL_IDENTITY: JSON.stringify(producer) }); entry("prepare-release"); - assert(!existsSync(join(directory, "release-proof.json"))); assert.deepEqual( JSON.parse(readFileSync(join(directory, "release-origin.json"), "utf8")), origin, ); - entry("release-identity", { - SEAL_RELEASE_IDENTITY_B64: Buffer.from(JSON.stringify(signer)).toString("base64"), - }); - const identityFile = readFileSync(output, "utf8").trim().slice("identity-file=".length); - assert.equal(statSync(identityFile).mode & 0o777, 0o600); - assert(!identityFile.startsWith(`${directory}/`)); - sign({ SEAL_IDENTITY_FILE: identityFile }); - entry("verify-seal"); - const proof = readFileSync(join(directory, "release-proof.json")); const receipt = '{"state":"partial","attempt":1}\n'; writeFileSync(join(f.root, "artifacts/release-receipt.json"), receipt); entry("prepare-release", { RELEASE_RESUMED: "true" }); - assert.deepEqual(readFileSync(join(directory, "release-proof.json")), proof); assert.equal(readFileSync(join(f.root, "artifacts/release-receipt.json"), "utf8"), receipt); assert.deepEqual( plan.packages.map((pkg) => sha256(readFileSync(join(directory, pkg.tarball)))), before, ); + writeJson(join(directory, "release-origin.json"), { ...origin, runId: 999 }); const rejected = spawnSync(process.execPath, [cli, "prepare-release"], { cwd: f.root, - env: { ...env, RELEASE_RESUMED: "true", SEAL_RELEASE_PUBLIC_KEY: "wrong" }, + env: { ...env, RELEASE_RESUMED: "true" }, encoding: "utf8", }); assert.equal(rejected.status, 1); - assert.match(rejected.stderr, /SEAL_SIGNER_UNTRUSTED/); + assert.match(rejected.stderr, /ORIGIN_INVALID/); }); diff --git a/scripts/release/publish.mjs b/scripts/release/publish.mjs index d3bfe1e..c29e23a 100644 --- a/scripts/release/publish.mjs +++ b/scripts/release/publish.mjs @@ -29,9 +29,9 @@ function failure(error, code, message) { } /** - * Publish verified retained bytes. Hooks are mandatory; no default can certify a seal or consumers. + * Publish verified retained bytes. The consumer hook is mandatory; no default can certify consumers. * Journal/receipts stay outside the signed bundle and remote truth is rechecked on every retry. - * @param {{plan:ReleasePlan,directory:string,registry:RegistryAdapter,verifySeal:(plan:ReleasePlan)=>Promise,verifyConsumers:(plan:ReleasePlan)=>Promise,journalPath?:string,expectedSourceSha?:string,now?:Date,attempts?:number,wait?:(ms:number)=>Promise}} options + * @param {{plan:ReleasePlan,directory:string,registry:RegistryAdapter,verifyConsumers:(plan:ReleasePlan)=>Promise,journalPath?:string,expectedSourceSha?:string,now?:Date,attempts?:number,wait?:(ms:number)=>Promise}} options */ async function publishVerifiedRelease(options) { const now = options.now ?? new Date(), @@ -45,17 +45,10 @@ async function publishVerifiedRelease(options) { ); const channel = plan.channel; requireThat( - typeof options.verifySeal === "function" && typeof options.verifyConsumers === "function", + typeof options.verifyConsumers === "function", "HOST_CONFIGURATION", - "Seal and published-consumer verification hooks are required", + "The published-consumer verification hook is required", ); - try { - await options.verifySeal(plan); - } catch { - const error = new ReleaseError("SEAL_INVALID", "Release seal verification failed"); - error.phase = "seal"; - throw error; - } validatePlan(plan, { directory, now }); if (!plan.packages.length) return { @@ -246,11 +239,6 @@ async function publishVerifiedRelease(options) { } // Recheck all retained bytes and registry versions after the external consumer hook. validatePlan(plan, { directory, now }); - try { - await options.verifySeal(plan); - } catch { - throw new ReleaseError("SEAL_INVALID", "Release seal verification failed before promotion"); - } for (const pkg of plan.packages) requireThat( await observed(pkg), diff --git a/scripts/release/publish.test.mjs b/scripts/release/publish.test.mjs index c19bd8c..ef30cf3 100644 --- a/scripts/release/publish.test.mjs +++ b/scripts/release/publish.test.mjs @@ -21,7 +21,6 @@ function setup(t, config) { now, journalPath, wait: async () => {}, - verifySeal: async () => {}, verifyConsumers: async () => { assert( plan.packages.every( @@ -36,21 +35,11 @@ function setup(t, config) { const error = (code) => (e) => e.code === code; const writes = new Set(["publish", "setTag", "removeTag"]); -await test("no-op never contacts npm; absent verification hooks and invalid Seal block all activity", async (t) => { +await test("no-op never contacts npm; an absent consumer hook blocks all activity", async (t) => { const noop = setup(t, { intent: false }); assert.equal((await publishRelease(noop.options)).status, "noop"); assert.deepEqual(noop.calls, []); const f = setup(t); - await assert.rejects( - publishRelease({ - ...f.options, - verifySeal: async () => { - throw Error("private cause"); - }, - }), - error("SEAL_INVALID"), - ); - assert.deepEqual(f.calls, []); await assert.rejects( publishRelease({ ...f.options, verifyConsumers: /** @type {any} */ (undefined) }), error("HOST_CONFIGURATION"), @@ -239,41 +228,6 @@ await test("published-consumer hook is mandatory and runs before channel promoti assert(!f.calls.some((call) => call[0] === "setTag")); }); -await test("proof corruption during consumers blocks promotion while retaining candidate publications", async (t) => { - const f = setup(t); - const proof = join(f.directory, "release-proof.json"); - writeFileSync(proof, "verified proof"); - let sealChecks = 0; - await assert.rejects( - publishRelease({ - ...f.options, - verifySeal: async () => { - sealChecks++; - assert.equal(readFileSync(proof, "utf8"), "verified proof"); - }, - verifyConsumers: async () => { - await f.options.verifyConsumers(); - writeFileSync(proof, "corrupted proof"); - }, - }), - error("SEAL_INVALID"), - ); - assert.equal(sealChecks, 2); - assert.equal(f.versions.size, 5); - assert.equal(f.calls.filter((call) => call[0] === "publish").length, 5); - assert( - f.calls - .filter((call) => call[0] === "publish") - .every((call) => call[3] === `candidate-${f.plan.releaseId}`), - ); - assert(!f.calls.some((call) => call[0] === "setTag" || call[0] === "removeTag")); - assert([...f.tags.values()].every((tag) => tag === "0.9.0")); - const journal = readJson(f.journalPath); - assert.equal(journal.status, "incomplete"); - assert.equal(journal.error.code, "SEAL_INVALID"); - assert(Object.values(journal.packages).every((state) => state.state === "published")); -}); - await test("promotion interruption restores prior channels and retry completes without new publish", async (t) => { const f = setup(t); const setTag = f.registry.setTag; @@ -325,16 +279,10 @@ await test("failed restoration is reported incomplete and does not claim release assert.notEqual(journal.phase, "complete"); }); -await test("tampering before publish and after Seal is rejected without registry mutations", async (t) => { +await test("tampering before publish is rejected without registry mutations", async (t) => { const f = setup(t); - await assert.rejects( - publishRelease({ - ...f.options, - verifySeal: async () => - writeFileSync(join(f.directory, f.plan.packages[0].tarball), "changed"), - }), - error("DIGEST_MISMATCH"), - ); + writeFileSync(join(f.directory, f.plan.packages[0].tarball), "changed"); + await assert.rejects(publishRelease(f.options), error("DIGEST_MISMATCH")); assert.deepEqual(f.calls, []); }); diff --git a/scripts/release/seal.mjs b/scripts/release/seal.mjs deleted file mode 100644 index 565e33b..0000000 --- a/scripts/release/seal.mjs +++ /dev/null @@ -1,63 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync, readdirSync } from "node:fs"; -import { join } from "node:path"; -import { parseSealManifestJson } from "../../packages/seal/dist/manifest.js"; -import { - createSealHash, - parseSealProofJson, - parseSealPublicKeyJson, - verifySealProofAgainstBytes, -} from "../../packages/seal/dist/proof.js"; - -const outputs = new Set(["release-manifest.json", "release-proof.json", "release-public-key.json"]); - -/** @param {string} directory @param {string} [prefix] @returns {string[]} */ -function bundleFiles(directory, prefix = "") { - return readdirSync(join(directory, prefix), { withFileTypes: true }).flatMap((entry) => { - const path = prefix ? `${prefix}/${entry.name}` : entry.name; - assert(!entry.isSymbolicLink(), `SEAL_BUNDLE_INVALID: symbolic link ${path}`); - if (entry.isDirectory()) return bundleFiles(directory, path); - assert(entry.isFile(), `SEAL_BUNDLE_INVALID: unsupported file ${path}`); - return outputs.has(path) ? [] : [path]; - }); -} - -/** - * The trusted key comes from repository/environment configuration, never from the bundle. - * @param {{directory: string, expectedPublicKey: string}} input - */ -export async function verifyReleaseSeal({ directory, expectedPublicKey }) { - assert(expectedPublicKey?.trim(), "SEAL_TRUST_MISSING: configure the release public key"); - const manifestBytes = readFileSync(join(directory, "release-manifest.json")); - const parsedManifest = parseSealManifestJson(manifestBytes.toString("utf8")); - const parsedProof = parseSealProofJson( - readFileSync(join(directory, "release-proof.json"), "utf8"), - ); - const parsedKey = parseSealPublicKeyJson( - readFileSync(join(directory, "release-public-key.json"), "utf8"), - ); - assert(parsedManifest.ok && parsedManifest.manifest, "SEAL_MANIFEST_INVALID"); - assert(parsedProof.ok && parsedProof.proof, "SEAL_PROOF_INVALID"); - assert(parsedKey.ok && parsedKey.artifact, "SEAL_PUBLIC_KEY_INVALID"); - const proof = parsedProof.proof; - const key = parsedKey.artifact; - assert.equal(proof.signer.publicKey, expectedPublicKey.trim(), "SEAL_SIGNER_UNTRUSTED"); - assert.equal(key.publicKey, expectedPublicKey.trim(), "SEAL_PUBLIC_KEY_UNTRUSTED"); - assert.equal(key.keyId, proof.signer.keyId, "SEAL_KEY_BINDING_INVALID"); - assert.equal(proof.subject.kind, "manifest", "SEAL_SUBJECT_INVALID"); - assert.equal(proof.subject.path, "release-manifest.json", "SEAL_SUBJECT_INVALID"); - assert((await verifySealProofAgainstBytes(proof, manifestBytes)).valid, "SEAL_SIGNATURE_INVALID"); - const files = bundleFiles(directory).sort(); - assert(files.includes("release-plan.json"), "SEAL_PLAN_MISSING"); - assert.deepEqual( - Object.keys(parsedManifest.manifest.files).sort(), - files, - "SEAL_FILE_SET_INVALID", - ); - for (const path of files) - assert.equal( - await createSealHash(readFileSync(join(directory, path))), - parsedManifest.manifest.files[path], - `SEAL_FILE_CHANGED: ${path}`, - ); -} diff --git a/scripts/release/seal.test.mjs b/scripts/release/seal.test.mjs deleted file mode 100644 index 112fa3f..0000000 --- a/scripts/release/seal.test.mjs +++ /dev/null @@ -1,67 +0,0 @@ -import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join, resolve } from "node:path"; -import { test } from "node:test"; -import { createSealIdentity } from "../../packages/seal/dist/crypto.js"; -import { verifyReleaseSeal } from "./seal.mjs"; - -await test("Seal binds the complete release bundle to an externally trusted key", async (t) => { - const directory = mkdtempSync(join(tmpdir(), "ternent-release-seal-")); - t.after(() => rmSync(directory, { recursive: true, force: true })); - const identity = await createSealIdentity(); - const env = { ...process.env, SEAL_IDENTITY: JSON.stringify(identity), SEAL_IDENTITY_FILE: "" }; - const cli = resolve("packages/seal/bin/seal"); - /** @param {string[]} args */ - const run = (args) => execFileSync(process.execPath, [cli, ...args], { env, encoding: "utf8" }); - writeFileSync(join(directory, "release-plan.json"), '{"releaseId":"tested-plan"}\n'); - writeFileSync(join(directory, "candidate.tgz"), "immutable candidate bytes"); - run([ - "manifest", - "create", - "--input", - directory, - "--out", - join(directory, "release-manifest.json"), - "--quiet", - ]); - run([ - "sign", - "--input", - join(directory, "release-manifest.json"), - "--out", - join(directory, "release-proof.json"), - "--quiet", - ]); - const publicKey = JSON.parse(run(["public-key", "--json"])); - writeFileSync(join(directory, "release-public-key.json"), JSON.stringify(publicKey)); - const verify = () => verifyReleaseSeal({ directory, expectedPublicKey: publicKey.publicKey }); - await verify(); - await assert.rejects( - () => verifyReleaseSeal({ directory, expectedPublicKey: "" }), - /SEAL_TRUST_MISSING/, - ); - await assert.rejects( - () => verifyReleaseSeal({ directory, expectedPublicKey: "untrusted" }), - /SEAL_SIGNER_UNTRUSTED/, - ); - writeFileSync(join(directory, "candidate.tgz"), "tampered"); - await assert.rejects(verify, /SEAL_FILE_CHANGED/); - writeFileSync(join(directory, "candidate.tgz"), "immutable candidate bytes"); - writeFileSync(join(directory, "extra.tgz"), "unlisted"); - await assert.rejects(verify, /SEAL_FILE_SET_INVALID/); - rmSync(join(directory, "extra.tgz")); - symlinkSync(join(directory, "candidate.tgz"), join(directory, "linked.tgz")); - await assert.rejects(verify, /symbolic link/); - rmSync(join(directory, "linked.tgz")); - const proofPath = join(directory, "release-proof.json"); - const proof = JSON.parse(readFileSync(proofPath, "utf8")); - proof.subject.path = "other.json"; - writeFileSync(proofPath, JSON.stringify(proof)); - await assert.rejects(verify, /SEAL_SUBJECT_INVALID/); - proof.subject.path = "release-manifest.json"; - proof.signature = "A".repeat(86); - writeFileSync(proofPath, JSON.stringify(proof)); - await assert.rejects(verify, /SEAL_SIGNATURE_INVALID/); -}); From d42afbae05d84182bd3858e8111d329203bb6414 Mon Sep 17 00:00:00 2001 From: samternent Date: Sat, 28 Nov 2026 00:13:53 +0000 Subject: [PATCH 08/24] chore(seal)!: remove the Seal CLI and release-sealing tooling Seal is now its three library functions. Remove bin/seal, the CLI and its tests, the release flow's retained verifier tools, the Seal consumer, type and isolation checks, the browser check's Seal block, the old Seal format docs and vectors, and the CLI and release-sealing mentions in the root docs. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 - .github/workflows/release.yml | 2 +- CONTRIBUTING.md | 5 +- README.md | 5 +- docs/seal/format.md | 86 ---------------------------- docs/seal/vectors/README.md | 21 ------- docs/seal/vectors/proof.v2.json | 51 ----------------- llms.txt | 7 +-- packages/seal/CLAUDE.md | 4 +- packages/seal/README.md | 11 ---- packages/seal/bin/seal | 6 -- packages/seal/llms.txt | 4 +- packages/seal/package.json | 5 -- packages/seal/src/cli.ts | 63 --------------------- packages/seal/test/cli.test.ts | 86 ---------------------------- packages/seal/vite.config.ts | 3 +- scripts/release/cli.test.mjs | 11 +--- scripts/release/fixtures.mjs | 2 +- scripts/release/flow.mjs | 51 +---------------- scripts/release/flow.test.mjs | 46 +++------------ scripts/release/plan.test.mjs | 2 +- scripts/release/publish.mjs | 4 +- scripts/release/publish.test.mjs | 2 +- scripts/verify/concord-browser.txt | 24 -------- scripts/verify/consumers.mjs | 21 +------ scripts/verify/seal-consumer.txt | 91 ------------------------------ scripts/verify/seal-isolation.txt | 12 ---- scripts/verify/seal-types.txt | 21 ------- 28 files changed, 27 insertions(+), 621 deletions(-) delete mode 100644 docs/seal/format.md delete mode 100644 docs/seal/vectors/README.md delete mode 100644 docs/seal/vectors/proof.v2.json delete mode 100755 packages/seal/bin/seal delete mode 100644 packages/seal/src/cli.ts delete mode 100644 packages/seal/test/cli.test.ts delete mode 100644 scripts/verify/seal-consumer.txt delete mode 100644 scripts/verify/seal-isolation.txt delete mode 100644 scripts/verify/seal-types.txt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 621debc..3f52112 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,8 +61,6 @@ jobs: run: pnpm check - name: Freeze the accepted release candidate bundle run: node scripts/release/cli.mjs verification-plan - - name: Retain the built release verifier tools - run: node scripts/release/flow.mjs capture-tools - name: Retain acceptance evidence if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4f133db..972c125 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -102,7 +102,7 @@ jobs: pnpm install --frozen-lockfile --ignore-scripts npm install --global npm@12.2.3 --ignore-scripts --registry=https://registry.npmjs.org/ - run: pnpm exec playwright install --with-deps chromium - - name: Validate producer, download exact artifact and restore verifier tools + - name: Validate producer and download the exact artifact id: bundle run: node scripts/release/flow.mjs stage - name: Validate committed intent, source binding and retained bundle diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4dee79b..32a156d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,7 +26,7 @@ tests also need `age` 1.3.1; CI installs its checksum-verified official binary. | `pnpm --filter @ternent/concord check` | Build that package and its dependencies, then run its checks | | `pnpm check:artifact` | Exact packed consumers; requires built outputs and Chromium | | `pnpm check` | Complete acceptance gate | -| `pnpm test:release` | Release plan, retry, integrity and Seal trust tests | +| `pnpm test:release` | Release plan, retry and integrity tests | | `pnpm release:version` | Review registry history, apply Changesets and record intent | | `pnpm release:plan` | Freeze accepted tarballs and reports from committed source | @@ -66,8 +66,7 @@ of creating legacy archives; Git keeps history. UI and Workspace remain excluded See the [repository guide](docs/engineering/repository-hygiene.md) for ownership and check boundaries. -The read-only CI workflow verifies candidates and exercises the pinned Seal Action -on a retained release bundle with a disposable test identity. Separate version-PR +The read-only CI workflow verifies candidates and retains a release bundle. Separate version-PR and production release workflows require explicit account setup and enablement. Review their [release contract and setup](docs/engineering/release-and-deployment.md) before enabling them. Public-registry acceptance remains outstanding; no workflow diff --git a/README.md b/README.md index c580969..5df728e 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ the host owns its data and storage. | [Armour](packages/armour/README.md) | age encryption through the TypeScript implementation, typage | | [Ledger](packages/ledger/README.md) | Standalone signed log, staging, commits, verification and replay | | [Concord](packages/concord/README.md) | Commands, authority, encrypted groups and application replay above Ledger | -| [Seal](packages/seal/README.md) | Standalone proofs, encrypted artifacts, manifests and a Node CLI | +| [Seal](packages/seal/README.md) | Detached Ed25519 proofs over a content hash | These five independently usable libraries are the active workspace and release scope. Ledger owns the common signed container and history lifecycle. Concord @@ -45,8 +45,7 @@ Start with the [project brief](docs/concord/context.md), [alpha architecture](docs/concord/alpha-architecture.md) and [repository guide](docs/engineering/repository-hygiene.md). Signed history is authoritative; projections are derived, and storage publication is a separate step. -Candidate-registry checks and the release planner/publisher are implemented. CI -exercises Seal proofs over retained candidate bundles. The first registry-backed alpha is published; the [release record](docs/engineering/release-and-deployment.md) +Candidate-registry checks and the release planner/publisher are implemented. The first registry-backed alpha is published; the [release record](docs/engineering/release-and-deployment.md) identifies its versions and acceptance evidence. ISC licensed. See [LICENSE](LICENSE). diff --git a/docs/seal/format.md b/docs/seal/format.md deleted file mode 100644 index 826173e..0000000 --- a/docs/seal/format.md +++ /dev/null @@ -1,86 +0,0 @@ -# Seal format contract - -Pre-release migration contract, 2026-11-20. Package candidate `@ternent/seal@0.5.0-alpha.0` -is distinct from wire versions. Existing proof/public-key v2, directory manifest v1 -and encrypted artifact v1 formats remain selected. `SealProofV2` names the actual proof -version. No inaccurate V1 type alias, Utils dependency or Concord hash format is kept. - -## Values and canonical bytes - -Seal uses a narrow internal canonical JSON codec. Accepted values are null, booleans, -valid Unicode strings, safe integers except negative zero, dense normal arrays, and -plain objects (Object.prototype or null prototype). At most 64 object/array levels -are accepted. Functions, undefined, symbols, bigint, nonfinite/fractional/unsafe numbers, -accessors, hidden properties, custom prototypes, cycles and toJSON hooks are rejected. -No getters or serialization hooks execute. Validators and public signing-field helpers -copy canonical data before reading fields. Async operations capture caller-owned subjects, -identities, payload/recipient buffers and verification inputs before awaits. - -Object keys are inserted in UTF-16 code-unit sort order into a null-prototype object, -then serialized with native JSON.stringify. ECMAScript integer-index enumeration -therefore places numeric filename keys in numeric order. This retains ordinary schema bytes and the previous -integer-key ordering. Prototype-like keys are now retained; this corrects dropped -entries and changes canonical bytes for affected manifests. There is no whitespace in canonical output and no Unicode -normalization. Manifests written by the CLI append one newline; file signing hashes -those raw bytes, including that newline. This is neither JCS nor Concord's numeric- -value/wire contract. SHA-256 is computed by Web Crypto over the exact supplied bytes. - -## Proof and public key - -A proof has exactly `version: "2"`, `type: "seal-proof"`, `algorithm: "Ed25519"`, -createdAt, subject, signer and signature. Subject has kind (`file`, `manifest`, -`artifact`), nonempty path and `sha256:` plus 64 lowercase hexadecimal digits. -Signer has raw canonical-base64url Ed25519 publicKey and a matching lowercase hex -SHA-256 keyId. Shape validation requires a parseable createdAt string; authoring -chooses an ISO timestamp unless one is supplied. That timestamp is a signed author -claim, not an independently trusted clock. - -The canonical signing payload consists of all those fields except signature. The -signed message is `UTF8("ternent-seal/v2") || 0x00 || UTF8(payload)`. Identity's -contextual signing and strict raw-message verifier implement it. Signer resolution -validates the stored seed against its public key and key ID. Verification checks -canonical encodings and Identity's strict point/scalar/signature rules; malformed -keys/signatures produce failed verification rather than an escaping parser error. - -A public-key artifact has exactly version `"2"`, type `"seal-public-key"`, algorithm, -publicKey and keyId. It conveys public material, not trust in that key. A host can pin -it or compare it against a proof signer. No profile/directory lookup is performed. - -## Manifest and encrypted artifact - -Directory manifests have exactly version `"1"`, type `"seal-manifest"`, nonempty root -and files mapping relative forward-slash paths to Seal hashes. Filesystem enumeration -is Node-only; parsing/stringifying remains browser-safe. CLI traversal skips `.DS_Store` -and symlinks/special entries, recursively hashes regular files and uses deterministic -code-unit ordering. It does not load files based on paths from an untrusted manifest. - -Encrypted artifacts have exactly version `"1"`, type `"seal-artifact"`, manifest, -payload and proof. Artifact manifest version is `"1"`; both manifest and payload -identify encrypted age recipient mode and armored encoding. Manifest payloadHash hashes -the UTF-8 armored ciphertext bytes. Payload contains that armor string. The proof's -kind is artifact; its subject hash covers canonical version/type/manifest/payload, -excluding proof. Verification requires schema/metadata agreement, the signature, the -unsigned-container hash and payload hash. Only after success does decryption ask Armour -for the selected identity's plaintext. Unrelated identities fail decryption. - -Age ciphertexts are randomized. Equal plaintext commands are not expected to emit -identical encrypted artifacts. Public proof signer/path/timestamp, metadata, age headers -and sizes remain visible. Recipient lists are not added as plaintext JSON fields; -this is no membership-hiding or guaranteed-delivery claim. No WASM initialization, -plaintext fallback, extra transport or new encryption scheme is introduced. - -## Fixed evidence and executable boundary - -[vectors/proof.v2.json](vectors/proof.v2.json) was independently constructed with -Node crypto: RFC 8032 public test seed, SHA-256 subjects/key ID, exact canonical payload, -context-prefixed message hex and Ed25519 signature. It also fixes Unicode/prototype/ -numeric manifest-key encoding. The saved identity is public test material and must -never sign private data. Source and installed-package consumers compare literal -payload/hash/signature values and verify offline; they do not generate their expected -signature with Seal itself. - -Only the separate executable imports Node filesystem/path/URL APIs. All six public -library exports have declarations and are checked with Node builtins, Concord, Utils -and Rage imports blocked. The browser fixture bundles proof/artifact operations from -the installed candidates. Its execution status is recorded separately in the -[current acceptance reports](../engineering/repository-hygiene.md#acceptance-boundaries). diff --git a/docs/seal/vectors/README.md b/docs/seal/vectors/README.md deleted file mode 100644 index 901f956..0000000 --- a/docs/seal/vectors/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Seal fixed vectors - -`proof.v2.json` uses the public RFC 8032 first Ed25519 test seed. It is test -material, never a private signing identity. - -The fixture was generated independently with Node's `node:crypto` APIs. The seed -was encoded as PKCS#8 Ed25519, the public key extracted from SPKI, and the key ID -computed as lowercase SHA-256 of the raw 32-byte public key. The subject hash is -SHA-256 of `contentUtf8` encoded as UTF-8. - -The proof payload recursively sorts object keys by UTF-16 code units and then -uses native `JSON.stringify`. Native ordering of integer-like property names is -therefore retained. The independent manifest example includes numeric names, -`__proto__` and supplementary-plane Unicode keys to fix those ordering details. - -The signed message is UTF-8 `ternent-seal/v2`, one zero byte, then UTF-8 -`signingPayload`. `messageHex` records those exact bytes. The signature is Node -Ed25519 over that message, encoded as unpadded base64url. Node verified the -signature before the fixture was saved. Behavior tests compare the library's -canonical payload, hash and signature against the saved values and separately -verify the saved signature with Node. diff --git a/docs/seal/vectors/proof.v2.json b/docs/seal/vectors/proof.v2.json deleted file mode 100644 index 88c36f4..0000000 --- a/docs/seal/vectors/proof.v2.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "description": "Public RFC 8032 test seed. Independently generated with Node crypto; never use this identity for private signing.", - "seedHex": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", - "identity": { - "format": "ternent-identity", - "version": "2", - "algorithm": "Ed25519", - "createdAt": "2026-11-20T00:00:00.000Z", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "keyId": "21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "material": { - "kind": "seed", - "seed": "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A" - } - }, - "contentUtf8": "Seal fixed proof vector\nπ / café 🔏\n", - "subjectHash": "sha256:ead97474c835407246000b7d98430bd7e71dac6c988c721f52d7c1a255348eac", - "context": "ternent-seal/v2", - "signingPayload": "{\"algorithm\":\"Ed25519\",\"createdAt\":\"2026-11-20T00:00:00.000Z\",\"signer\":{\"keyId\":\"21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9\",\"publicKey\":\"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\"},\"subject\":{\"hash\":\"sha256:ead97474c835407246000b7d98430bd7e71dac6c988c721f52d7c1a255348eac\",\"kind\":\"file\",\"path\":\"dist/δ.txt\"},\"type\":\"seal-proof\",\"version\":\"2\"}", - "messageHex": "7465726e656e742d7365616c2f7632007b22616c676f726974686d223a2245643235353139222c22637265617465644174223a22323032362d31312d32305430303a30303a30302e3030305a222c227369676e6572223a7b226b65794964223a2232316665333164666131353461323631363236626638353430343666643232373162376265643462366162653435616135383837376566343766393732316239222c227075626c69634b6579223a223131715941594b7843726656535f3754795751484f6737686376506170694d6c727749616150634855526f227d2c227375626a656374223a7b2268617368223a227368613235363a65616439373437346338333534303732343630303062376439383433306264376537316461633663393838633732316635326437633161323535333438656163222c226b696e64223a2266696c65222c2270617468223a22646973742fceb42e747874227d2c2274797065223a227365616c2d70726f6f66222c2276657273696f6e223a2232227d", - "proof": { - "version": "2", - "type": "seal-proof", - "algorithm": "Ed25519", - "createdAt": "2026-11-20T00:00:00.000Z", - "subject": { - "kind": "file", - "path": "dist/δ.txt", - "hash": "sha256:ead97474c835407246000b7d98430bd7e71dac6c988c721f52d7c1a255348eac" - }, - "signer": { - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "keyId": "21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "signature": "3bX0FY6naBoXDXNUtjdkYVO7-vjcOWsD-LwYZFWDTWNHq9nayOcnfg75Q3HRpo7E9xqhpmPd_hOivZVxwXEICQ" - }, - "manifest": { - "version": "1", - "type": "seal-manifest", - "root": "fixed", - "files": { - "2": "sha256:b50726ca891c3e79a1f0cee7cf67df767a9ba3dff026d8a2614534e27840c283", - "10": "sha256:88ed149bc96b79c4004d4a13039950c5889cd8022a16ea705597d52d7a391c4e", - "a": "sha256:98c64c8ae66ca1f50af31d7dec04a7f34ab6981ef103d4abb80d28d2fd959c0d", - "__proto__": "sha256:1e9c49fa7fc3dbbd833db74effd94f17167c24e6d8fcbcad53753be8b69415fa", - "𐀀": "sha256:b6c490fcb1046ba8722222ed410e74e994f14020abe12a203bc37dfcd4adbd6f", - "": "sha256:c49ff3d8c04e6b674f79ba61970a66fd8a20e2e2fe96e37c4f560f6e2d708a0a" - } - }, - "canonicalManifest": "{\"files\":{\"2\":\"sha256:b50726ca891c3e79a1f0cee7cf67df767a9ba3dff026d8a2614534e27840c283\",\"10\":\"sha256:88ed149bc96b79c4004d4a13039950c5889cd8022a16ea705597d52d7a391c4e\",\"__proto__\":\"sha256:1e9c49fa7fc3dbbd833db74effd94f17167c24e6d8fcbcad53753be8b69415fa\",\"a\":\"sha256:98c64c8ae66ca1f50af31d7dec04a7f34ab6981ef103d4abb80d28d2fd959c0d\",\"𐀀\":\"sha256:b6c490fcb1046ba8722222ed410e74e994f14020abe12a203bc37dfcd4adbd6f\",\"\":\"sha256:c49ff3d8c04e6b674f79ba61970a66fd8a20e2e2fe96e37c4f560f6e2d708a0a\"},\"root\":\"fixed\",\"type\":\"seal-manifest\",\"version\":\"1\"}" -} diff --git a/llms.txt b/llms.txt index 77a5ef5..9437cf6 100644 --- a/llms.txt +++ b/llms.txt @@ -9,10 +9,10 @@ - [Ledger](packages/ledger/llms.txt): a signed, append-only history of JSON entries, verified on open, without Concord's application or permission rules. - [Identity](packages/identity/llms.txt): create, back up, restore or recover one identity; sign and verify bytes. - [Armour](packages/armour/llms.txt): encrypt and decrypt bytes with age for identities, groups and passphrases. -- [Seal](packages/seal/llms.txt): sign and verify a detached proof over any bytes' hash; use the Node CLI. +- [Seal](packages/seal/llms.txt): sign and verify a detached proof over any bytes' hash. The active libraries are exactly the five above. Workspace and UI are outside this -release, and Utils and separate Seal CLI packages are retired. Use the published +release, and Utils is retired. Use the published exports rather than historical workspace runtime/plugin examples. ## Installation and source of truth @@ -23,8 +23,7 @@ before installing from an unreleased checkout, and commit the consumer lockfile. Install only the libraries the application uses. An unqualified package install selects npm's `latest` tag; `@next` selects the preview channel. Dist-tags and version stability are separate: check the resolved version, including any prerelease suffix, in the -consumer lockfile. Libraries support Node 22.18+ and modern browsers; Seal’s CLI -and filesystem operations require Node. Core development uses its own pinned toolchain. +consumer lockfile. Libraries support Node 22.18+ and modern browsers. Core development uses its own pinned toolchain. The package guides link to their public README and declarations. The published `dist/*.d.ts` files define the installed interface; do not infer APIs from old examples diff --git a/packages/seal/CLAUDE.md b/packages/seal/CLAUDE.md index 37b0273..ce314b3 100644 --- a/packages/seal/CLAUDE.md +++ b/packages/seal/CLAUDE.md @@ -1,7 +1,7 @@ # Working on Seal -Seal is three functions and a two-command CLI. `src/index.ts` is the library and must -stay browser-safe; `src/cli.ts` is the only Node code. Keep it that small. +Seal is three functions in `src/index.ts`. It runs in browsers and Node and has no +Node-only code. Keep it that small. ## What Seal owns diff --git a/packages/seal/README.md b/packages/seal/README.md index 3af290e..b60362a 100644 --- a/packages/seal/README.md +++ b/packages/seal/README.md @@ -46,15 +46,4 @@ The signature covers `UTF8("ternent-seal/v1") || 0x00 || JSON` of every field ex exactly these fields, a millisecond UTC `createdAt` and canonical unpadded base64url. `createdAt` is the signer's claim, not evidence of time. -## CLI - -```sh -SEAL_IDENTITY_FILE=identity.json seal sign --input release-manifest.json --out proof.json -seal verify --proof proof.json --input release-manifest.json -``` - -`sign` reads an Identity backup from `SEAL_IDENTITY_FILE` and prints the proof -unless `--out` is given. `verify` prints `{ valid, signatureValid, hashMatch }`. -Exit codes: 0 success, 1 error, 2 invalid proof. - License: ISC. diff --git a/packages/seal/bin/seal b/packages/seal/bin/seal deleted file mode 100755 index 45f80fb..0000000 --- a/packages/seal/bin/seal +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env node -import { runCli } from "../dist/cli.js"; - -void runCli(process.argv.slice(2)).then((exitCode) => { - process.exitCode = exitCode; -}); diff --git a/packages/seal/llms.txt b/packages/seal/llms.txt index 94a6a6a..f21d8e9 100644 --- a/packages/seal/llms.txt +++ b/packages/seal/llms.txt @@ -1,6 +1,6 @@ # @ternent/seal -> Detached Ed25519 proofs over SHA-256 content hashes, plus a `seal` CLI. +> Detached Ed25519 proofs over SHA-256 content hashes. Three exports from the package root: `createSealHash`, `createSealProof`, `verifySealProof`. Types: `SealProof`, `SealHash`, `SealVerification`. Declarations: `dist/index.d.ts`. @@ -23,5 +23,3 @@ if (!valid || proof.signer.id !== trustedPublisher.id) throw new Error("Untruste - Seal does not decide trust. Pin the expected signer yourself. - Seal has no recipients or encryption. To prove encrypted data, seal its ciphertext bytes. - To prove several files, seal a manifest of their hashes and check each file yourself. -- CLI: `seal sign --input [--out ]` with `SEAL_IDENTITY_FILE` set; - `seal verify --proof --input `. Exit 0 ok, 1 error, 2 invalid proof. diff --git a/packages/seal/package.json b/packages/seal/package.json index e3d449f..9700f8f 100644 --- a/packages/seal/package.json +++ b/packages/seal/package.json @@ -3,7 +3,6 @@ "version": "0.5.0", "description": "Detached Ed25519 proofs over content hashes", "keywords": [ - "cli", "integrity", "proof", "seal", @@ -19,11 +18,7 @@ "url": "git+https://github.com/ternent/core.git", "directory": "packages/seal" }, - "bin": { - "seal": "./bin/seal" - }, "files": [ - "bin", "dist", "README.md", "llms.txt" diff --git a/packages/seal/src/cli.ts b/packages/seal/src/cli.ts deleted file mode 100644 index 0964683..0000000 --- a/packages/seal/src/cli.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { readFile, writeFile } from "node:fs/promises"; -import { parseArgs } from "node:util"; -import { restoreIdentity } from "@ternent/identity"; -import { createSealHash, createSealProof, verifySealProof } from "./index.js"; - -const usage = `Usage: seal sign --input [--out ] - seal verify --proof --input - -sign reads the identity backup named by SEAL_IDENTITY_FILE. -Exit codes: 0 success, 1 error, 2 invalid proof.`; - -type Io = { - env: Record; - stdout: (text: string) => void; - stderr: (text: string) => void; -}; - -const processIo: Io = { - env: process.env, - stdout: (text) => process.stdout.write(text), - stderr: (text) => process.stderr.write(text), -}; - -export async function runCli(argv: string[], io: Io = processIo): Promise { - try { - const { positionals, values } = parseArgs({ - args: argv, - allowPositionals: true, - options: { - input: { type: "string" }, - out: { type: "string" }, - proof: { type: "string" }, - help: { type: "boolean" }, - }, - }); - const [command] = positionals; - - if (values.help || positionals.length === 0) { - io.stdout(`${usage}\n`); - return 0; - } - if (command === "sign" && positionals.length === 1 && values.input && !values.proof) { - const identityFile = io.env.SEAL_IDENTITY_FILE; - if (!identityFile) throw new Error("Set SEAL_IDENTITY_FILE to an identity backup"); - const signer = await restoreIdentity(await readFile(identityFile, "utf8")); - const hash = await createSealHash(await readFile(values.input)); - const proof = `${JSON.stringify(await createSealProof({ signer, subject: { hash } }), null, 2)}\n`; - if (values.out) await writeFile(values.out, proof); - else io.stdout(proof); - return 0; - } - if (command === "verify" && positionals.length === 1 && values.input && values.proof) { - const proof: unknown = JSON.parse(await readFile(values.proof, "utf8")); - const result = await verifySealProof(proof, await readFile(values.input)); - io.stdout(`${JSON.stringify(result)}\n`); - return result.valid ? 0 : 2; - } - throw new Error(usage); - } catch (error) { - io.stderr(`${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -} diff --git a/packages/seal/test/cli.test.ts b/packages/seal/test/cli.test.ts deleted file mode 100644 index cd8d083..0000000 --- a/packages/seal/test/cli.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { mkdtemp, readFile, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { expect, test } from "vite-plus/test"; -import { createIdentity } from "@ternent/identity"; -import { runCli } from "../src/cli.js"; - -async function setup() { - const dir = await mkdtemp(join(tmpdir(), "seal-cli-")); - const identity = await createIdentity(); - const identityFile = join(dir, "identity.json"); - await writeFile(identityFile, identity.export()); - const input = join(dir, "release-manifest.json"); - await writeFile(input, '{"release":"1.0.0"}\n'); - return { dir, identity, input, env: { SEAL_IDENTITY_FILE: identityFile } }; -} - -function io(env: Record = {}) { - const out = { stdout: "", stderr: "" }; - return { - out, - io: { - env, - stdout: (text: string) => void (out.stdout += text), - stderr: (text: string) => void (out.stderr += text), - }, - }; -} - -test("sign writes a proof that verify accepts", async () => { - const { dir, identity, input, env } = await setup(); - const proofPath = join(dir, "proof.json"); - expect(await runCli(["sign", "--input", input, "--out", proofPath], io(env).io)).toBe(0); - expect(JSON.parse(await readFile(proofPath, "utf8")).signer).toEqual(identity.publicIdentity); - - const verified = io(); - expect(await runCli(["verify", "--proof", proofPath, "--input", input], verified.io)).toBe(0); - expect(JSON.parse(verified.out.stdout)).toEqual({ - valid: true, - signatureValid: true, - hashMatch: true, - }); -}); - -test("sign without --out prints the proof", async () => { - const { input, env } = await setup(); - const signed = io(env); - expect(await runCli(["sign", "--input", input], signed.io)).toBe(0); - expect(JSON.parse(signed.out.stdout).format).toBe("seal"); -}); - -test("verify exits 2 when the input changed", async () => { - const { dir, input, env } = await setup(); - const proofPath = join(dir, "proof.json"); - await runCli(["sign", "--input", input, "--out", proofPath], io(env).io); - await writeFile(input, '{"release":"1.0.1"}\n'); - const verified = io(); - expect(await runCli(["verify", "--proof", proofPath, "--input", input], verified.io)).toBe(2); - expect(JSON.parse(verified.out.stdout)).toMatchObject({ valid: false, hashMatch: false }); -}); - -test("usage errors, missing identity and unreadable files exit 1", async () => { - const { dir, input, env } = await setup(); - const badIdentity = join(dir, "bad.json"); - await writeFile(badIdentity, "{}"); - const cases: [string[], Record][] = [ - [["sign", "--input", input], {}], - [["sign", "--input", input], { SEAL_IDENTITY_FILE: badIdentity }], - [["sign"], env], - [["verify", "--input", input], env], - [["verify", "--proof", join(dir, "missing.json"), "--input", input], env], - [["publish", "--input", input], env], - [["sign", "--input", input, "--unknown"], env], - ]; - for (const [argv, caseEnv] of cases) { - const run = io(caseEnv); - expect(await runCli(argv, run.io)).toBe(1); - expect(run.out.stderr).not.toBe(""); - } -}); - -test("help prints usage", async () => { - const run = io(); - expect(await runCli(["--help"], run.io)).toBe(0); - expect(run.out.stdout).toMatch(/^Usage: seal sign/); -}); diff --git a/packages/seal/vite.config.ts b/packages/seal/vite.config.ts index 2edbb3d..0251310 100644 --- a/packages/seal/vite.config.ts +++ b/packages/seal/vite.config.ts @@ -5,7 +5,6 @@ export default defineConfig({ ...base, pack: { ...base.pack, - platform: "node", - entry: { index: "src/index.ts", cli: "src/cli.ts" }, + entry: { index: "src/index.ts" }, }, }); diff --git a/scripts/release/cli.test.mjs b/scripts/release/cli.test.mjs index 17264b0..1ccb845 100644 --- a/scripts/release/cli.test.mjs +++ b/scripts/release/cli.test.mjs @@ -1,19 +1,11 @@ import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; -import { - chmodSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync, -} from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { test } from "node:test"; import { fixture } from "./fixtures.mjs"; import { createPlan } from "./plan.mjs"; -import { captureTools } from "./flow.mjs"; import { sha256, writeJson } from "./shared.mjs"; await test("release entrypoint rejects uncommitted intent and local publication", (t) => { @@ -85,7 +77,6 @@ await test("production entrypoint records the origin and preserves candidates th } const directory = join(f.root, "artifacts/release"); const { plan } = createPlan({ ...f.planOptions, sourceSha, directory, now: new Date() }); - captureTools(process.cwd(), directory); const before = plan.packages.map((pkg) => sha256(readFileSync(join(directory, pkg.tarball)))); const bin = join(f.root, "bin"); mkdirSync(bin); diff --git a/scripts/release/fixtures.mjs b/scripts/release/fixtures.mjs index 715cbc4..0e2ae95 100644 --- a/scripts/release/fixtures.mjs +++ b/scripts/release/fixtures.mjs @@ -29,7 +29,7 @@ export function fixture(options = {}) { "@ternent/armour": "^1.0.0-alpha.0", "@ternent/ledger": "^1.0.0-alpha.0", }, - "@ternent/seal": { "@ternent/identity": "^1.0.0-alpha.0", "@ternent/armour": "^1.0.0-alpha.0" }, + "@ternent/seal": { "@ternent/identity": "^1.0.0-alpha.0" }, }; /** @type {{name:string,path:string}[]} */ const inventory = []; /** @type {Record} */ const candidates = {}; diff --git a/scripts/release/flow.mjs b/scripts/release/flow.mjs index ee162d5..fb07bae 100644 --- a/scripts/release/flow.mjs +++ b/scripts/release/flow.mjs @@ -3,11 +3,9 @@ import { appendFileSync, cpSync, existsSync, - lstatSync, mkdirSync, mkdtempSync, readFileSync, - readdirSync, rmSync, writeFileSync, } from "node:fs"; @@ -18,7 +16,6 @@ import { packageNames, requireThat, sha256, validateChannel } from "./shared.mjs const repository = "ternent/core"; const apiRoot = `repos/${repository}`; -const toolPackages = ["identity", "armour", "seal"]; /** @typedef {{sourceSha:string,runId:number,artifactId:number,artifactDigest:string,requestedReleaseId:string}} Selection */ /** @param {unknown} value */ function identifier(value) { @@ -212,49 +209,6 @@ export async function extractArtifact({ id, digest, directory, readArchive }) { writeFileSync(file, bytes, { flag: "wx" }); } } -/** @param {string} directory */ -function regularTree(directory) { - requireThat( - lstatSync(directory).isDirectory() && !lstatSync(directory).isSymbolicLink(), - "PATH_INVALID", - "Expected a regular tools directory", - ); - for (const entry of readdirSync(directory, { withFileTypes: true })) { - requireThat( - !entry.isSymbolicLink() && (entry.isFile() || entry.isDirectory()), - "PATH_INVALID", - "Tools must contain regular files only", - ); - if (entry.isDirectory()) regularTree(join(directory, entry.name)); - } -} -/** Preserve the already-built verifier; no build/repack runs in the publisher. - * @param {string} root @param {string} bundle - */ -export function captureTools(root, bundle) { - for (const name of toolPackages) { - const source = join(root, "packages", name, "dist"), - target = join(bundle, "tools/packages", name, "dist"); - regularTree(source); - requireThat(!existsSync(target), "ARTIFACT_EXISTS", "Verifier tools already captured"); - cpSync(source, target, { recursive: true }); - } -} -/** @param {string} root @param {string} bundle */ -export function restoreTools(root, bundle) { - for (const name of toolPackages) { - const source = join(bundle, "tools/packages", name, "dist"), - target = join(root, "packages", name, "dist"); - requireThat( - existsSync(join(source, "index.js")), - "ARTIFACT_MISSING", - "Verified CLI tools were not retained", - ); - regularTree(source); - rmSync(target, { recursive: true, force: true }); - cpSync(source, target, { recursive: true }); - } -} /** @param {Selection} selection @param {any} plan */ function bindPlan(selection, plan) { requireThat( @@ -371,7 +325,6 @@ export async function stageRelease({ root, selection, resumeRunId, api = github, writeFileSync(join(root, "artifacts/release-receipt.json"), `${JSON.stringify(receipt)}\n`); } writeFileSync(join(root, "artifacts/release-origin.json"), `${JSON.stringify(handoff)}\n`); - restoreTools(root, directory); return { releaseId: plan.releaseId, resumed: Boolean(receipt) }; } finally { rmSync(temporary, { recursive: true, force: true }); @@ -390,8 +343,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1] try { const command = process.argv[2], root = process.cwd(); - if (command === "capture-tools") captureTools(root, resolve("artifacts/release")); - else if (command === "version-needed") { + if (command === "version-needed") { const temporary = mkdtempSync(join(tmpdir(), "ternent-changesets-status-")); try { const file = join(temporary, "status.json"); @@ -460,7 +412,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1] outputs({ "release-id": staged.releaseId, resumed: String(staged.resumed), - node: process.execPath, }); } } else if (command === "collect") { diff --git a/scripts/release/flow.test.mjs b/scripts/release/flow.test.mjs index f46a133..60acf68 100644 --- a/scripts/release/flow.test.mjs +++ b/scripts/release/flow.test.mjs @@ -5,13 +5,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { zipSync, strToU8 } from "fflate"; -import { - captureTools, - extractArtifact, - restoreTools, - selectRelease, - stageRelease, -} from "./flow.mjs"; +import { extractArtifact, selectRelease, stageRelease } from "./flow.mjs"; import { packageNames, sha256 } from "./shared.mjs"; import { fixture } from "./fixtures.mjs"; @@ -55,11 +49,7 @@ function producerArchive() { return zipSync( Object.fromEntries([ entry("release/release-plan.json", JSON.stringify(plan)), - entry("release/release-proof.json", "producer proof"), entry("release/candidates/candidate.tgz", "immutable candidate"), - ...["identity", "armour", "seal"].map((name) => - entry(`release/tools/packages/${name}/dist/index.js`, "export const verified = true;"), - ), ]), ); } @@ -251,7 +241,7 @@ await test("archive digest and paths are checked before extraction; unsafe entri assert.equal(readFileSync(join(root, "good/release/plan.json"), "utf8"), "checked"); }); -await test("staging restores captured verifier files without building or changing candidate bytes", async (t) => { +await test("staging keeps candidate bytes and records the producer origin", async (t) => { const root = temporary(t), archive = producerArchive(), f = responses(archive); @@ -268,10 +258,6 @@ await test("staging restores captured verifier files without building or changin readFileSync(join(root, "artifacts/release/candidates/candidate.tgz"), "utf8"), "immutable candidate", ); - assert.equal( - readFileSync(join(root, "packages/seal/dist/index.js"), "utf8"), - "export const verified = true;", - ); assert.equal( JSON.parse(readFileSync(join(root, "artifacts/release-origin.json"), "utf8")).sourceSha, sourceSha, @@ -292,10 +278,10 @@ await test("a requested release ID cannot select another plan even from an other () => stageRelease({ root, selection, api: f.api, readArchive: async () => archive }), /selected source\/release/, ); - assert(!existsSync(join(root, "packages/seal/dist/index.js"))); + assert(!existsSync(join(root, "artifacts/release-origin.json"))); }); -await test("retry handoff retains the existing signed bundle and publication journal", async (t) => { +await test("retry handoff retains the existing bundle and publication journal", async (t) => { const root = temporary(t), archive = producerArchive(), f = responses(archive); @@ -318,15 +304,12 @@ await test("retry handoff retains the existing signed bundle and publication jou const prior = zipSync( Object.fromEntries([ entry("release/release-plan.json", JSON.stringify(priorPlan)), - entry("release/release-proof.json", "unchanged production proof"), + entry("release/retained.txt", "unchanged prior bundle file"), entry("release/release-origin.json", JSON.stringify(handoff)), entry( "release-receipt.json", JSON.stringify({ sourceSha, releaseId, status: "incomplete", attempt: 1 }), ), - ...["identity", "armour", "seal"].map((name) => - entry(`release/tools/packages/${name}/dist/index.js`, "export const verified = true;"), - ), ]), ); f.values[`${rootApi}/actions/runs/30`] = { @@ -361,8 +344,8 @@ await test("retry handoff retains the existing signed bundle and publication jou }); assert.equal(result.resumed, true); assert.equal( - readFileSync(join(root, "artifacts/release/release-proof.json"), "utf8"), - "unchanged production proof", + readFileSync(join(root, "artifacts/release/retained.txt"), "utf8"), + "unchanged prior bundle file", ); assert.equal( JSON.parse(readFileSync(join(root, "artifacts/release-receipt.json"), "utf8")).attempt, @@ -382,21 +365,6 @@ await test("retry handoff retains the existing signed bundle and publication jou ); }); -await test("captured tools are separate from tarballs and restoring them never invokes a builder", (t) => { - const root = temporary(t), - bundle = join(root, "bundle"); - mkdirSync(bundle); - for (const name of ["identity", "armour", "seal"]) - put(join(root, "packages", name, "dist/index.js"), "original verifier"); - captureTools(root, bundle); - put(join(root, "packages/seal/dist/index.js"), "changed local file"); - restoreTools(root, bundle); - assert.equal( - readFileSync(join(root, "packages/seal/dist/index.js"), "utf8"), - "original verifier", - ); -}); - await test("version detection ignores consumed Changesets 3 prereleases and accepts the next changeset", (t) => { const f = fixture(); t.after(() => rmSync(f.root, { recursive: true, force: true })); diff --git a/scripts/release/plan.test.mjs b/scripts/release/plan.test.mjs index d6f7200..06649ea 100644 --- a/scripts/release/plan.test.mjs +++ b/scripts/release/plan.test.mjs @@ -43,7 +43,7 @@ await test("planner freezes all five exact bytes, orders dependencies and binds assert(!JSON.stringify(plan).includes("@ternent/private")); }); -await test("no intent is an explicit no-op while the signed bundle still carries all five candidates", (t) => { +await test("no intent is an explicit no-op while the bundle still carries all five candidates", (t) => { const f = setup(t, { intent: false }); const { status, plan } = createPlan(f.planOptions); assert.equal(status, "noop"); diff --git a/scripts/release/publish.mjs b/scripts/release/publish.mjs index c29e23a..f0eff27 100644 --- a/scripts/release/publish.mjs +++ b/scripts/release/publish.mjs @@ -30,7 +30,7 @@ function failure(error, code, message) { /** * Publish verified retained bytes. The consumer hook is mandatory; no default can certify consumers. - * Journal/receipts stay outside the signed bundle and remote truth is rechecked on every retry. + * Journal/receipts stay outside the release bundle and remote truth is rechecked on every retry. * @param {{plan:ReleasePlan,directory:string,registry:RegistryAdapter,verifyConsumers:(plan:ReleasePlan)=>Promise,journalPath?:string,expectedSourceSha?:string,now?:Date,attempts?:number,wait?:(ms:number)=>Promise}} options */ async function publishVerifiedRelease(options) { @@ -84,7 +84,7 @@ async function publishVerifiedRelease(options) { requireThat( local === ".." || local.startsWith(`..${sep}`) || isAbsolute(local), "PATH_INVALID", - "Journal must stay outside the signed bundle", + "Journal must stay outside the release bundle", ); /** @type {any} */ const journal = existsSync(journalPath) diff --git a/scripts/release/publish.test.mjs b/scripts/release/publish.test.mjs index ef30cf3..79a66cb 100644 --- a/scripts/release/publish.test.mjs +++ b/scripts/release/publish.test.mjs @@ -303,7 +303,7 @@ await test("retry rejects a newer channel before writes even with a saved earlie assert(!f.calls.some((call) => writes.has(call[0]))); }); -await test("failure context is structured and journals cannot be placed in the signed bundle", async (t) => { +await test("failure context is structured and journals cannot be placed in the release bundle", async (t) => { const f = setup(t); f.registry.publish = async () => { throw Error("secret host detail"); diff --git a/scripts/verify/concord-browser.txt b/scripts/verify/concord-browser.txt index 7452464..82c00a1 100644 --- a/scripts/verify/concord-browser.txt +++ b/scripts/verify/concord-browser.txt @@ -1,9 +1,3 @@ -import { verifySealProofAgainstBytes, type SealProofV2 } from "@ternent/seal/proof"; -import { - createSealArtifact, - verifySealArtifact, - decryptSealArtifactPayload, -} from "@ternent/seal/artifact"; import { createDocument, openDocument, @@ -237,24 +231,6 @@ export async function proveConcord() { storedDocument.draft() !== null ) throw new Error("browser stored snapshot reopen failed"); - const sealFixture: { proof: SealProofV2; contentUtf8: string; identity: typeof hostIdentity } = - await (await fetch("/seal-proof.v2.json")).json(); - const sealBytes = new TextEncoder().encode(sealFixture.contentUtf8); - if (!(await verifySealProofAgainstBytes(sealFixture.proof, sealBytes)).valid) - throw new Error("browser fixed Seal proof failed"); - const sealed = await createSealArtifact({ - signer: { identity: sealFixture.identity }, - subjectPath: "browser.txt", - payload: sealBytes, - recipients: [await recipientFromIdentity(hostIdentity)], - }); - const openedSeal = await decryptSealArtifactPayload({ artifact: sealed, identity: hostIdentity }); - if ( - !(await verifySealArtifact(sealed)).valid || - openedSeal.length !== sealBytes.length || - !openedSeal.every((byte, index) => byte === sealBytes[index]) - ) - throw new Error("browser Seal artifact roundtrip failed"); const output = document.createElement("output"); output.id = "concord-proof"; output.textContent = "Concord: hello browser"; diff --git a/scripts/verify/consumers.mjs b/scripts/verify/consumers.mjs index 4efb0cd..03c2d93 100644 --- a/scripts/verify/consumers.mjs +++ b/scripts/verify/consumers.mjs @@ -359,18 +359,12 @@ try { "groups.expected.json", ]) cpSync(resolve(root, "docs/concord/vectors", name), join(consumer, name)); - cpSync(resolve(root, "docs/seal/vectors/proof.v2.json"), join(consumer, "seal-proof.v2.json")); cpSync( resolve(root, "packages/ledger/test/vectors/signed-log.json"), join(consumer, "ledger-signed-log.json"), ); put("ledger.mjs", readFileSync(resolve(root, "scripts/verify/ledger-consumer.txt"), "utf8")); put("payload.mjs", readFileSync(resolve(root, "scripts/verify/payload-consumer.txt"), "utf8")); - put("seal.mjs", readFileSync(resolve(root, "scripts/verify/seal-consumer.txt"), "utf8")); - put( - "seal-isolation.mjs", - readFileSync(resolve(root, "scripts/verify/seal-isolation.txt"), "utf8"), - ); put("storage.mjs", readFileSync(resolve(root, "scripts/verify/storage-consumer.txt"), "utf8")); put("groups.mjs", readFileSync(resolve(root, "scripts/verify/groups-consumer.txt"), "utf8")); put("concord.mjs", readFileSync(resolve(root, "scripts/verify/concord-consumer.txt"), "utf8")); @@ -408,10 +402,6 @@ try { console.log(execFileSync(executable, ["concord.mjs"], { cwd: consumer, encoding: "utf8" })); console.log(execFileSync(executable, ["groups.mjs"], { cwd: consumer, encoding: "utf8" })); console.log(execFileSync(executable, ["storage.mjs"], { cwd: consumer, encoding: "utf8" })); - console.log(execFileSync(executable, ["seal.mjs"], { cwd: consumer, encoding: "utf8" })); - console.log( - execFileSync(executable, ["seal-isolation.mjs"], { cwd: consumer, encoding: "utf8" }), - ); console.log( execFileSync(executable, ["protocol-isolation.mjs"], { cwd: consumer, encoding: "utf8" }), ); @@ -428,9 +418,6 @@ try { checks.push( `External artifact storage, expected-head conflicts, retained forks and committed-only draft publication on ${versions}`, ); - checks.push( - `Seal installed public paths, fixed signature, artifact encryption, CLI/Action sequence, exits and Node-free library import graph on ${versions}`, - ); checks.push( `Standalone Ledger lifecycle, fixed vectors, declarations and import isolation on ${versions}`, ); @@ -456,7 +443,6 @@ try { "primitives-types.ts", "groups-types.ts", "storage-types.ts", - "seal-types.ts", "ledger-types.ts", "src/**/*.ts", "vite.config.ts", @@ -464,7 +450,6 @@ try { ], }); put("ledger-types.ts", readFileSync(resolve(root, "scripts/verify/ledger-types.txt"), "utf8")); - put("seal-types.ts", readFileSync(resolve(root, "scripts/verify/seal-types.txt"), "utf8")); put("groups-types.ts", readFileSync(resolve(root, "scripts/verify/groups-types.txt"), "utf8")); put("storage-types.ts", readFileSync(resolve(root, "scripts/verify/storage-types.txt"), "utf8")); put( @@ -497,10 +482,6 @@ export default defineConfig({ }); `, ); - put( - "public/seal-proof.v2.json", - readFileSync(resolve(root, "docs/seal/vectors/proof.v2.json"), "utf8"), - ); put( "src/concord-proof.ts", readFileSync(resolve(root, "scripts/verify/concord-browser.txt"), "utf8"), @@ -542,7 +523,7 @@ export default defineConfig({ await page.screenshot({ path: resolve(root, "artifacts/browser.png") }); await page.close(); checks.push( - "Chromium: standalone Ledger, Armour codecs, fixed Seal proof/artifact, encrypted Concord and independent groups, storage, drafts, production CSS and Vue render interaction", + "Chromium: standalone Ledger, Armour codecs, encrypted Concord and independent groups, storage, drafts, production CSS and Vue render interaction", ); } finally { await app.close(); diff --git a/scripts/verify/seal-consumer.txt b/scripts/verify/seal-consumer.txt deleted file mode 100644 index 05fd36e..0000000 --- a/scripts/verify/seal-consumer.txt +++ /dev/null @@ -1,91 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync, writeFileSync, mkdirSync, statSync, rmSync } from "node:fs"; -import { resolve } from "node:path"; -import { spawnSync } from "node:child_process"; -import { createSealIdentity, exportIdentityJson } from "@ternent/seal"; -import { createSealProof, getSealProofSigningPayload, verifySealProofAgainstBytes, verifySealProofSignature, createSealHash } from "@ternent/seal/proof"; -import { createSealArtifact, verifySealArtifact, decryptSealArtifactPayload, parseSealArtifactJson } from "@ternent/seal/artifact"; -import { stringifySealManifest, parseSealManifestJson } from "@ternent/seal/manifest"; -import { verifyPublicKeyKeyId, verifySealUtf8 } from "@ternent/seal/crypto"; -import { EXIT_KEY_CONFIG, EXIT_INVALID_PROOF, EXIT_SIGNATURE_INVALID, EXIT_HASH_MISMATCH } from "@ternent/seal/errors"; -import { recipientFromIdentity } from "@ternent/armour"; -const fixed = JSON.parse(readFileSync("seal-proof.v2.json","utf8")); -const content = new TextEncoder().encode(fixed.contentUtf8); -assert.equal(await createSealHash(content),fixed.subjectHash); -assert.equal(getSealProofSigningPayload(fixed.proof),fixed.signingPayload); -assert.deepEqual(await createSealProof({signer:{identity:fixed.identity},subject:fixed.proof.subject,createdAt:fixed.proof.createdAt}),fixed.proof); -assert.equal((await verifySealProofAgainstBytes(fixed.proof,content)).valid,true); -assert.equal(await verifySealUtf8(fixed.proof.signature,fixed.signingPayload,fixed.proof.signer.publicKey),true); -assert.equal(await verifyPublicKeyKeyId(fixed.proof.signer.publicKey,fixed.proof.signer.keyId),true); -assert.equal((await verifySealProofSignature({...fixed.proof,signer:{...fixed.proof.signer,publicKey:"malformed"}})).ok,false); -assert.equal(stringifySealManifest(fixed.manifest),fixed.canonicalManifest); -assert.deepEqual(parseSealManifestJson(fixed.canonicalManifest).manifest,fixed.manifest); -assert.equal(Object.hasOwn(parseSealManifestJson(fixed.canonicalManifest).manifest.files,"__proto__"),true); -const recipient = await createSealIdentity(); -const outsider = await createSealIdentity(); -const encrypted = await createSealArtifact({signer:{identity:fixed.identity},payload:content,subjectPath:"test.txt",recipients:[await recipientFromIdentity(recipient)]}); -assert.equal((await verifySealArtifact(encrypted)).valid,true); -assert.deepEqual(await decryptSealArtifactPayload({artifact:encrypted,identity:recipient}),content); -await assert.rejects(()=>decryptSealArtifactPayload({artifact:encrypted,identity:outsider}),error=>error.code === "SEAL_DECRYPTION_FAILED"); -const altered = structuredClone(encrypted); altered.payload.data += "tamper"; -assert.equal((await verifySealArtifact(altered)).valid,false); -await assert.rejects(()=>decryptSealArtifactPayload({artifact:altered,identity:recipient})); - -const bin = resolve("node_modules/@ternent/seal/bin/seal"); -assert.equal(readFileSync(bin,"utf8").startsWith("#!/usr/bin/env node\n"),true); -assert.notEqual(statSync(bin).mode & 0o111,0); -const keyPath = resolve("seal-identity.json"); -const env = {...process.env,SEAL_IDENTITY:"",SEAL_IDENTITY_FILE:keyPath}; -function cli(args,status=0,config=env) { - const result = spawnSync(process.execPath,[bin,...args],{env:config,encoding:"utf8"}); - assert.equal(result.status,status,`seal ${args[0]}: ${result.stderr}`); - return result.stdout; -} -assert.match(cli(["--help"],0,{...env,SEAL_IDENTITY_FILE:""}),/Usage: seal/); -cli(["identity","create","--out",keyPath,"--words","12","--passphrase=with=equals","--mnemonic-out","seal-backup.txt","--quiet"]); -assert.equal(statSync(keyPath).mode & 0o777,0o600); -assert.equal(statSync("seal-backup.txt").mode & 0o777,0o600); -assert.match(readFileSync("seal-backup.txt","utf8"),/Passphrase:\nwith=equals/); -const createdIdentity = JSON.parse(readFileSync(keyPath,"utf8")); -assert.equal(createdIdentity.version,"2"); -rmSync("seal-assets",{recursive:true,force:true}); -mkdirSync("seal-assets/nested",{recursive:true}); -writeFileSync("seal-assets/index.html","

Seal packed candidate
"); -writeFileSync("seal-assets/nested/example.txt","signed bytes"); -writeFileSync("seal-assets/__proto__","own filename"); -// The inspected Action's configurable CLI runs this same sequence on a clean build directory. -cli(["manifest","create","--input","seal-assets","--out","seal-assets/dist-manifest.json","--quiet"]); -cli(["sign","--input","seal-assets/dist-manifest.json","--out","seal-assets/proof.json","--quiet"]); -writeFileSync("seal-assets/public-key.json",cli(["public-key","--json"])); -const manifest = JSON.parse(readFileSync("seal-assets/dist-manifest.json","utf8")); -assert.equal(Object.hasOwn(manifest.files,"__proto__"),true); -const proof = JSON.parse(readFileSync("seal-assets/proof.json","utf8")); -const publicKey = JSON.parse(readFileSync("seal-assets/public-key.json","utf8")); -assert.equal(proof.subject.kind,"manifest"); -assert.equal(publicKey.publicKey,proof.signer.publicKey); -assert.equal(publicKey.keyId,proof.signer.keyId); -assert.equal(JSON.parse(cli(["verify","--proof","seal-assets/proof.json","--input","seal-assets/dist-manifest.json","--json"])).valid,true); -const manifestBytes = new Uint8Array(readFileSync("seal-assets/dist-manifest.json")); -assert.equal((await verifySealProofAgainstBytes(proof,manifestBytes)).valid,true); -writeFileSync("different.txt","different bytes"); -cli(["verify","--proof","seal-assets/proof.json","--input","different.txt","--quiet"],EXIT_HASH_MISMATCH); -const badSignature = structuredClone(proof);badSignature.signature="A".repeat(86); -writeFileSync("bad-signature.json",JSON.stringify(badSignature)); -cli(["verify","--proof","bad-signature.json","--input","seal-assets/dist-manifest.json","--quiet"],EXIT_SIGNATURE_INVALID); -writeFileSync("invalid-proof.json",'{"type":"bad"}'); -cli(["verify","--proof","invalid-proof.json","--input","different.txt","--quiet"],EXIT_INVALID_PROOF); -cli(["public-key","--quiet"],EXIT_KEY_CONFIG,{...env,SEAL_IDENTITY_FILE:""}); -cli(["manifest","create","--quiet"],1); -cli(["public-key","--quiet"],EXIT_KEY_CONFIG,{...env,SEAL_IDENTITY:"not-json"}); -const mismatchedIdentity = {...fixed.identity,material:outsider.material}; -cli(["public-key","--quiet"],EXIT_KEY_CONFIG,{...env,SEAL_IDENTITY:JSON.stringify(mismatchedIdentity)}); -const ageRecipient = await recipientFromIdentity(recipient); -cli(["sign","--input","different.txt","--recipient",ageRecipient,"--out","encrypted-artifact.json","--quiet"]); -assert.equal(JSON.parse(cli(["verify","--artifact","encrypted-artifact.json","--json"])).valid,true); -const parsedArtifact = parseSealArtifactJson(readFileSync("encrypted-artifact.json","utf8")); -assert.equal(parsedArtifact.ok,true); -assert.equal(new TextDecoder().decode(await decryptSealArtifactPayload({artifact:parsedArtifact.artifact,identity:recipient})),"different bytes"); -writeFileSync("invalid-artifact.json",'{"type":"bad"}'); -cli(["verify","--artifact","invalid-artifact.json","--quiet"],EXIT_INVALID_PROOF); -assert.match(exportIdentityJson(createdIdentity),/ternent-identity/); -console.log(`Seal public paths, fixed proof, encrypted artifacts, executable, Action command sequence and exits passed on ${process.version}`); diff --git a/scripts/verify/seal-isolation.txt b/scripts/verify/seal-isolation.txt deleted file mode 100644 index 267f482..0000000 --- a/scripts/verify/seal-isolation.txt +++ /dev/null @@ -1,12 +0,0 @@ -import { isBuiltin, registerHooks } from "node:module"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -const fixed = JSON.parse(readFileSync("seal-proof.v2.json","utf8")); -registerHooks({resolve(specifier,context,next){ - if(isBuiltin(specifier) || specifier.startsWith("@ternent/concord") || specifier.includes("ternent-utils") || specifier.startsWith("@ternent/rage"))throw new Error(`Forbidden library dependency: ${specifier}`); - return next(specifier,context); -}}); -for(const path of ["@ternent/seal","@ternent/seal/proof","@ternent/seal/artifact","@ternent/seal/manifest","@ternent/seal/crypto","@ternent/seal/errors"])await import(path); -const {verifySealProofSignature}=await import("@ternent/seal/proof"); -assert.equal((await verifySealProofSignature(fixed.proof)).ok,true); -console.log("Seal library imports/verifies with Node builtins, Concord, Utils and Rage imports blocked"); diff --git a/scripts/verify/seal-types.txt b/scripts/verify/seal-types.txt deleted file mode 100644 index 959b395..0000000 --- a/scripts/verify/seal-types.txt +++ /dev/null @@ -1,21 +0,0 @@ -import { createSealIdentity, type SealProofV2 } from "@ternent/seal"; -import { createSealProof, verifySealProofAgainstBytes } from "@ternent/seal/proof"; -import { createSealArtifact, decryptSealArtifactPayload } from "@ternent/seal/artifact"; -import { parseSealManifestJson } from "@ternent/seal/manifest"; -import { verifySealUtf8 } from "@ternent/seal/crypto"; -import { SealArtifactError } from "@ternent/seal/errors"; -const identity = await createSealIdentity(); -const proof: SealProofV2 = await createSealProof({signer:{identity},subject:{kind:"file",path:"test",hash:`sha256:${"0".repeat(64)}`}}); -const report = await verifySealProofAgainstBytes(proof,new Uint8Array()); -const valid: boolean = report.valid; -const artifact = await createSealArtifact({signer:{identity},subjectPath:"test",payload:new Uint8Array(),recipients:["age1..."]}); -const bytes: Uint8Array = await decryptSealArtifactPayload({artifact,identity}); -// @ts-expect-error Proof v2 has an explicit string version. -const version: "1" = proof.version; -// @ts-expect-error The signing subject uses an explicit kind. -await createSealProof({signer:{identity},subject:{kind:"unknown",path:"test",hash:"sha256:abc"}}); -// @ts-expect-error Encryption is byte based. -await createSealArtifact({signer:{identity},subjectPath:"test",payload:"text",recipients:[]}); -// @ts-expect-error Standalone public keys do not contain a signing seed. -await createSealProof({signer:{identity:{publicKey:"public only"}},subject:proof.subject}); -void [valid,bytes,version,parseSealManifestJson,verifySealUtf8,SealArtifactError]; From d751f3d30c9d77dd7db4f5eb871ac1098ebcfe45 Mon Sep 17 00:00:00 2001 From: samternent Date: Sat, 28 Nov 2026 01:45:32 +0000 Subject: [PATCH 09/24] feat(concord)!: rewrite as a document of events with private groups Replace commands, system profiles, capability sets, authoring modes, inspection handles, locked views and the /protocol, /system and /testing subpaths with createDocument, openDocument and defineModel. A model is events and one pure reducer; a document stages and commits events per group. Every entry is one age ciphertext with no group label. Membership, roles and key epochs live in encrypted group records; a key gains authority only through an accepted record. Each group replays independently, rejected commits stay as evidence with no effect, and rebase reapplies unpublished local commits onto another copy. A saved vector fixes the format. Consumers are not yet adapted. Co-Authored-By: Claude Opus 5.5 --- llms.txt | 2 +- packages/concord/CHANGELOG.md | 128 -- packages/concord/CLAUDE.md | 49 +- packages/concord/README.md | 215 ++- packages/concord/SPEC.md | 8 - packages/concord/llms.txt | 194 +-- packages/concord/package.json | 18 +- packages/concord/src/common/errors.ts | 96 -- packages/concord/src/common/immutable.ts | 1 - packages/concord/src/common/random.ts | 1 - packages/concord/src/index.ts | 710 +++++++++- packages/concord/src/model/index.ts | 7 - packages/concord/src/model/types.ts | 108 -- packages/concord/src/protocol/history.ts | 22 - packages/concord/src/protocol/index.ts | 4 - packages/concord/src/protocol/json.ts | 6 - packages/concord/src/protocol/schema.ts | 159 --- packages/concord/src/protocol/types.ts | 43 - packages/concord/src/protocol/verify.ts | 84 -- packages/concord/src/runtime.ts | 601 --------- packages/concord/src/runtime/host.ts | 87 -- packages/concord/src/runtime/model-replay.ts | 67 - packages/concord/src/runtime/system-output.ts | 134 -- packages/concord/src/runtime/validation.ts | 49 - packages/concord/src/system/audience.ts | 150 --- packages/concord/src/system/authoring.ts | 41 - packages/concord/src/system/index.ts | 4 - packages/concord/src/system/membership.ts | 90 -- packages/concord/src/system/standard.ts | 607 --------- packages/concord/src/system/types.ts | 80 -- .../concord/src/testing/artifact-store.ts | 103 -- packages/concord/src/testing/index.ts | 81 -- packages/concord/test/concord.test.ts | 491 +++++++ packages/concord/test/drafts.test.ts | 697 ---------- packages/concord/test/fixtures.ts | 142 -- packages/concord/test/groups.test.ts | 1150 ----------------- packages/concord/test/membership.test.ts | 451 ------- packages/concord/test/protocol.test.ts | 323 ----- packages/concord/test/runtime.test.ts | 979 -------------- packages/concord/test/storage.test.ts | 321 ----- packages/concord/test/vector.json | 50 + packages/concord/vite.config.ts | 7 +- ....timestamp-1774262297922-ffd76e35ea668.mjs | 83 -- pnpm-lock.yaml | 6 + 44 files changed, 1443 insertions(+), 7206 deletions(-) delete mode 100644 packages/concord/CHANGELOG.md delete mode 100644 packages/concord/SPEC.md delete mode 100644 packages/concord/src/common/errors.ts delete mode 100644 packages/concord/src/common/immutable.ts delete mode 100644 packages/concord/src/common/random.ts delete mode 100644 packages/concord/src/model/index.ts delete mode 100644 packages/concord/src/model/types.ts delete mode 100644 packages/concord/src/protocol/history.ts delete mode 100644 packages/concord/src/protocol/index.ts delete mode 100644 packages/concord/src/protocol/json.ts delete mode 100644 packages/concord/src/protocol/schema.ts delete mode 100644 packages/concord/src/protocol/types.ts delete mode 100644 packages/concord/src/protocol/verify.ts delete mode 100644 packages/concord/src/runtime.ts delete mode 100644 packages/concord/src/runtime/host.ts delete mode 100644 packages/concord/src/runtime/model-replay.ts delete mode 100644 packages/concord/src/runtime/system-output.ts delete mode 100644 packages/concord/src/runtime/validation.ts delete mode 100644 packages/concord/src/system/audience.ts delete mode 100644 packages/concord/src/system/authoring.ts delete mode 100644 packages/concord/src/system/index.ts delete mode 100644 packages/concord/src/system/membership.ts delete mode 100644 packages/concord/src/system/standard.ts delete mode 100644 packages/concord/src/system/types.ts delete mode 100644 packages/concord/src/testing/artifact-store.ts delete mode 100644 packages/concord/src/testing/index.ts create mode 100644 packages/concord/test/concord.test.ts delete mode 100644 packages/concord/test/drafts.test.ts delete mode 100644 packages/concord/test/fixtures.ts delete mode 100644 packages/concord/test/groups.test.ts delete mode 100644 packages/concord/test/membership.test.ts delete mode 100644 packages/concord/test/protocol.test.ts delete mode 100644 packages/concord/test/runtime.test.ts delete mode 100644 packages/concord/test/storage.test.ts create mode 100644 packages/concord/test/vector.json delete mode 100644 packages/concord/vite.config.ts.timestamp-1774262297922-ffd76e35ea668.mjs diff --git a/llms.txt b/llms.txt index 9437cf6..408613a 100644 --- a/llms.txt +++ b/llms.txt @@ -5,7 +5,7 @@ ## Choose the interface -- [Concord](packages/concord/llms.txt): build an application using typed commands, events, authority, private groups and replay. +- [Concord](packages/concord/llms.txt): build an application whose data is a shared, signed document with private groups. - [Ledger](packages/ledger/llms.txt): a signed, append-only history of JSON entries, verified on open, without Concord's application or permission rules. - [Identity](packages/identity/llms.txt): create, back up, restore or recover one identity; sign and verify bytes. - [Armour](packages/armour/llms.txt): encrypt and decrypt bytes with age for identities, groups and passphrases. diff --git a/packages/concord/CHANGELOG.md b/packages/concord/CHANGELOG.md deleted file mode 100644 index dbb3bba..0000000 --- a/packages/concord/CHANGELOG.md +++ /dev/null @@ -1,128 +0,0 @@ -# @ternent/concord - -## 0.3.0 - -### Minor Changes - -- e5c6808: Establish the five-library alpha: standalone Identity, Armour, Ledger and Seal, - with Concord composing Ledger's common signed container, authority, independent - encrypted groups, command drafts and application replay. The common container - deliberately replaces the previous Concord alpha wire format. - - Armour uses typage and offers explicit payload codecs for Ledger. Uncommitted - entries and command intents stay in memory; consumers own draft recovery and - storage publication. Verify public imports, declarations, CLI behavior and exact - candidate bytes before publication. - -### Patch Changes - -- 7d55bda: Include agent interface guides with public imports, runnable examples, lifecycle and - error contracts, and host-owned storage/recovery behavior. -- Updated dependencies [7d55bda] -- Updated dependencies [e5c6808] - - @ternent/identity@0.6.0 - - @ternent/armour@0.3.0 - - @ternent/ledger@0.2.0 - -## 0.3.0-alpha.1 - -### Minor Changes - -- e5c6808: Establish the five-library alpha: standalone Identity, Armour, Ledger and Seal, - with Concord composing Ledger's common signed container, authority, independent - encrypted groups, command drafts and application replay. The common container - deliberately replaces the previous Concord alpha wire format. - - Armour uses typage and offers explicit payload codecs for Ledger. Uncommitted - entries and command intents stay in memory; consumers own draft recovery and - storage publication. Verify public imports, declarations, CLI behavior and exact - candidate bytes before publication. - -### Patch Changes - -- Updated dependencies [e5c6808] - - @ternent/identity@0.6.0-alpha.1 - - @ternent/armour@0.3.0-alpha.1 - - @ternent/ledger@0.2.0-alpha.1 - -## 0.2.9 - -### Patch Changes - -- Updated dependencies []: - - @ternent/ledger@0.1.8 - -## 0.2.8 - -### Patch Changes - -- Updated dependencies []: - - @ternent/ledger@0.1.7 - -## 0.2.7 - -### Patch Changes - -- Updated dependencies []: - - @ternent/ledger@0.1.6 - -## 0.2.6 - -### Patch Changes - -- [`583a65c2dc6917a634019ea53c6987dc3960a8b2`](https://github.com/samternent/home/commit/583a65c2dc6917a634019ea53c6987dc3960a8b2) Thanks [@samternent](https://github.com/samternent)! - Update concord - -## 0.2.5 - -### Patch Changes - -- [`42a5b52f19d93079ca76a07f44c647d5e6866009`](https://github.com/samternent/home/commit/42a5b52f19d93079ca76a07f44c647d5e6866009) Thanks [@samternent](https://github.com/samternent)! - Align build with identity - -## 0.2.4 - -### Patch Changes - -- [`cb63d9c1dc91e0cd3924bafd5abcde89cc02992f`](https://github.com/samternent/home/commit/cb63d9c1dc91e0cd3924bafd5abcde89cc02992f) Thanks [@samternent](https://github.com/samternent)! - Fix workflows - -- Updated dependencies [[`cb63d9c1dc91e0cd3924bafd5abcde89cc02992f`](https://github.com/samternent/home/commit/cb63d9c1dc91e0cd3924bafd5abcde89cc02992f)]: - - @ternent/ledger@0.1.5 - -## 0.2.3 - -### Patch Changes - -- [`acf974919a1176da235e7ec7468c46df8bc13402`](https://github.com/samternent/home/commit/acf974919a1176da235e7ec7468c46df8bc13402) Thanks [@samternent](https://github.com/samternent)! - Update build configs - -- Updated dependencies [[`acf974919a1176da235e7ec7468c46df8bc13402`](https://github.com/samternent/home/commit/acf974919a1176da235e7ec7468c46df8bc13402)]: - - @ternent/ledger@0.1.4 - -## 0.2.2 - -### Patch Changes - -- [`3fd51c9f51ccc3d816d044aa8aa161d9683534c3`](https://github.com/samternent/home/commit/3fd51c9f51ccc3d816d044aa8aa161d9683534c3) Thanks [@samternent](https://github.com/samternent)! - alias utils - -- Updated dependencies []: - - @ternent/ledger@0.1.3 - -## 0.2.1 - -### Patch Changes - -- [`109f8c3989b16a161a34b933dcad68390d9219c5`](https://github.com/samternent/home/commit/109f8c3989b16a161a34b933dcad68390d9219c5) Thanks [@samternent](https://github.com/samternent)! - Fix deps - -- Updated dependencies [[`109f8c3989b16a161a34b933dcad68390d9219c5`](https://github.com/samternent/home/commit/109f8c3989b16a161a34b933dcad68390d9219c5)]: - - @ternent/ledger@0.1.2 - -## 0.2.0 - -### Minor Changes - -- [`92050833da54cacbd6fe33349d9b8fb66754d82c`](https://github.com/samternent/home/commit/92050833da54cacbd6fe33349d9b8fb66754d82c) Thanks [@samternent](https://github.com/samternent)! - Add the initial Concord command runtime on top of `@ternent/ledger`. - -### Patch Changes - -- [`92050833da54cacbd6fe33349d9b8fb66754d82c`](https://github.com/samternent/home/commit/92050833da54cacbd6fe33349d9b8fb66754d82c) Thanks [@samternent](https://github.com/samternent)! - Concord library migration - -- Updated dependencies [[`92050833da54cacbd6fe33349d9b8fb66754d82c`](https://github.com/samternent/home/commit/92050833da54cacbd6fe33349d9b8fb66754d82c)]: - - @ternent/ledger@0.1.1 diff --git a/packages/concord/CLAUDE.md b/packages/concord/CLAUDE.md index bed22b9..18b24ea 100644 --- a/packages/concord/CLAUDE.md +++ b/packages/concord/CLAUDE.md @@ -1,9 +1,40 @@ -# Concord architecture - -Ledger owns the common signed container, canonical bytes, IDs, signatures, staging, -commits, verification and ordered replay. Concord composes that lifecycle with -commands, authority, encryption and atomic application-state publication. Standard -system owns authority and private replay; models own application meaning. Do not -duplicate Ledger's commit engine or add Workspace, Seal proofs, plugin ordering, -ambient reducer clocks or storage to the runtime. Keep protocol imports independent -of runtime, model and Armour. Historical implementations are available in Git. +# Working on Concord + +Concord is one file, `src/index.ts`: a document handle over a Ledger history, with private +groups and a model's reducer. Keep it that small. + +## What Concord owns + +- Groups, membership, roles, key epochs and the wraps that distribute them. +- Replay: authority first, then the model's `reduce`, per group. +- The encrypted record formats inside each entry. `test/vector.json` fixes a document and + the state each identity sees. A change that breaks it is a format change. +- Not signatures or history (Ledger and Seal), not encryption (Armour and age), not the + application's meaning (the model), and not storage or sync (the application). + +## Rules that keep it sound + +- Enforce only what the readers who rely on a rule can verify. A group's validity uses only + that group's history; no rule may depend on another group's state. +- A key gains authority only through an accepted record: creation for epoch 0, an + authorized removal for each later epoch. Decrypting something proves nothing. +- Opening is three passes: Ledger verification, key discovery from every wrap, then replay. + A single pass cannot give a new member the history before they joined. +- Authoring signs through a fresh Ledger writer and adopts the result only if replaying the + new commit accepts it, so failure leaves history and state unchanged. +- Never claim privacy the raw bytes don't give. Update the README's list if a format change + alters what is visible. + +## How the code stays small + +- No command layer, capability sets, pluggable system, modes, error codes or subpaths. + Add one only for a demonstrated need. +- Validate where data enters: `readBody` and `readWrap` for decrypted records, `captureEvent` + for staged events. Values that passed aren't checked again. +- Let Ledger and Armour fail clearly; don't re-check what they reject. + +## Checks + +Run `pnpm run check` in this package under the Node version in `.node-version`. Each +replay rule has a test that fails if the rule is removed; keep it that way when adding one. +Update `README.md` and `llms.txt` with any interface change. diff --git a/packages/concord/README.md b/packages/concord/README.md index ce28bdc..af738ef 100644 --- a/packages/concord/README.md +++ b/packages/concord/README.md @@ -1,116 +1,113 @@ # @ternent/concord -[Agent interface guide](llms.txt): public imports, examples and lifecycle contracts. - -A framework composing Ledger, Identity and Armour into portable signed documents -with independent encrypted groups and explicit application replay coverage. -The runtime implements -create → dispatch/commit → export → open → verify → replay → inspect. - -Concord stores its framework records inside the common `ledger` v1 container. -Ledger owns entry staging, commit construction, signatures, verification and ordered -history. The signed genesis commit's `metadata.concord` declares the system and model. -A raw Ledger entry keeps its `system` or `application` kind, with the framework -envelope in `subject.payload.data`. Encrypted application values remain ciphertext; -Ledger's JSON envelope does not make them plaintext. - -Concord retains command-intent drafts and model previews. When committing, it creates -a private Ledger candidate, prepares/encrypts and appends the entries, commits through -Ledger, and validates full system and application replay before adopting the candidate. -Failures retain the active signed history and command draft. Storage publication is -still separate. A standalone Ledger reader can verify/export the same container -without a Concord model, decryptor or permission system. - -This alpha breaks the former Concord-only signed container; no legacy import or -conversion adapter is included. See [the current profile](../../docs/concord/alpha-protocol.md) -and [ADR 0018](../../docs/adr/0018-use-one-ledger-container-for-concord.md). +[Agent interface guide](llms.txt): public imports, examples and contracts. + +Shared, signed, partly private documents built from your application's events. You +define a model; Concord gives you a document that several people can write to, with +private groups inside it, that anyone holding the file can verify. ```ts -import { createDocument, openDocument } from "@ternent/concord"; -import { createStandardSystemProfile } from "@ternent/concord/system"; -import { registerModel } from "@ternent/concord/testing"; -import { generateIdentity } from "@ternent/armour"; -const generated = await generateIdentity(); -if (!generated.ok) throw new Error(generated.error.code); -const system = createStandardSystemProfile(); -const created = await createDocument({ model: registerModel, system, identity: generated.value }); -if (!created.ok) throw new Error(created.error.code); -const committed = await created.value.dispatch("set", { value: "hello Concord" }); -if (!committed.ok) throw new Error(committed.error.code); -const reopened = await openDocument({ - bytes: created.value.export(), - model: registerModel, - system, - signer: generated.value, +import { createIdentity } from "@ternent/identity"; +import { createDocument, defineModel, openDocument } from "@ternent/concord"; + +const notes = defineModel({ + id: "notes", + version: 1, + initial: () => ({ notes: {} }), + reduce(state, event, { author, version }) { + if (event.type === "note.put") + return { notes: { ...state.notes, [event.data.id]: event.data.title } }; + throw new Error(`Unknown event ${event.type}`); + }, }); -const report = await reopened.verify(); -const replayed = await reopened.replay(); + +const [alice, bob] = [await createIdentity(), await createIdentity()]; +const doc = await createDocument({ model: notes, identity: alice }); +doc.stage({ type: "note.put", data: { id: "1", title: "Hello" } }); +await doc.commit(); + +const team = await doc.createGroup(); +await doc.setMember(bob.publicIdentity, { group: team, role: "member" }); +const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); +bobs.state(team); ``` -Root exports the lifecycle, model definition helper, and their public types. -`/protocol` verifies bytes without a model, runtime, decryption or age import. -`/system` supplies the standard private profile, `setMember`, `removeMember`, and -`createGroup` and specialist types. `document` is the default group. A default-group -writer may create an independently administered group; the document owner gets no -automatic access. Pass `{ audience, identity, capabilities }` to `setMember` and -`{ audience, identityId }` to `removeMember`; omitting audience selects `document`. -Admission/re-admission grants that group's full history. Removal rotates only that -group's future key; retained historical access remains readable. -`/testing` supplies the exact register model, literal model-conformance checks, and -copied-buffer artifact storage. `createMemoryExpectedHeadStore()` additionally offers -`expectedHead: true` and atomic `writeExpected(bytes, expectedHead)` for writers sharing -that reference instance. Null means create-only; a conflict returns `HEAD_CONFLICT` -with copied `error.remote` bytes. No test runner is a production dependency. - -Storage publication is explicitly separate from dispatch/commit. Failed I/O or head -conflict preserves local history and drafts. Retain both local and remote snapshots; -compare them with `/protocol` and select explicitly. Expected-head comparison does -not provide ancestry policy, model validity or read freshness; use a remembered anchor -when opening. These are in-memory reference helpers, with no cross-process/provider -atomicity claim. See [the storage contract](../../docs/concord/storage-boundary.md). - -Immediate commits are the default. Pass `mode: "draft"` to create/open to stage -application commands in memory. `draft()` returns `{ baseHead, entryCount, preview }`; -subsequent commands decide against that preview. `state()`, `inspect()`, `export()`, -`verify()` and `replay()` continue to describe committed history. - -Call `commit({ message: "Group edits" })` to encrypt the staged events and create one -signed commit, or `discardDraft()` to drop the preview. Genesis always commits -immediately. Drafts are volatile and never included in exports. Failed dispatch or -commit retains the previous committed state and any successful staged work for retry. -Pending command intents stay in memory. Consumers choose immediate or draft authoring -and own any autosave or recovery of unfinished work. Export and external storage -contain committed history only; Concord has no draft persistence adapter or recovery -format. See [the persistence decision](../../docs/adr/0019-keep-draft-persistence-with-consumers.md). -A draft can batch several commands targeting different groups; each command still -selects exactly one audience. Commit metadata is public and signed. - -All mutation is serialized per handle, with complete candidate verification/replay -before atomic publication. Read-only and inspection handles reject writes. Empty or -immediate-mode `commit()` returns `NO_DRAFT`. Group/membership operations require an -immediate-mode handle: on a draft handle they return `DRAFT_PENDING` when work is -staged, otherwise `HOST_CONFIGURATION`. There is no implicit mode switch. -The standard profile rejects unknown system events with `UNSUPPORTED_SYSTEM_EVENT`. -Inspection marks other recipients' decryptability as `unverified`. - -A command's optional `audience(input)` selects one group (default `document`) before -its decision receives scoped facts. The model's `audience(event)` must return the -same group for every emitted event and match signed envelopes during replay. -A command cannot span audiences. - -Models requiring all events remain locked when any event is unavailable. Opt into -readable views with `reduceLocked(state, { audience, epoch }, facts)`. Ready states -and `replay()` results both carry `coverage: "complete" | "readable"` and -`lockedEntries`; `replay()` returns `{ projection, coverage, lockedEntries }`. -Inspection exposes ordered readable/locked `entries` and public `audiences` after -the complete system pass, including when subsequent model replay fails. Scoped -coverage does not validate hidden application semantics. - -Protocol and semantic failures are separate. Invalid, locked, incompatible and stale -imports remain exportable inspection evidence. Projection is derived; storage is not -trust. Ready exports are canonical; inspection exports retain original bytes. - -The [protocol](../../docs/concord/alpha-protocol.md), -[standard profile](../../docs/concord/standard-profile.md) and -[conformance contract](../../docs/concord/conformance.md) define the current wire, -authority, encryption and acceptance behavior. Git retains previous implementations. +## Model + +A model is an `id`, a `version`, `initial()` and `reduce(state, event, { author, version })`. +`reduce` is synchronous and pure. It receives frozen state and returns the next state; +throwing rejects the event. An event is `{ type, data }` with JSON `data`. + +An optional `squash(events)` may shorten a draft before it is signed. Concord replays both +versions and fails the commit if the result differs, so squash never changes meaning. + +Each group pins the model ID that created it, and each commit records the model version. +A newer model must replay older events exactly; `version` lets `reduce` branch. `state` +throws for a group with a different model or a newer version than yours. + +## Document + +| Member | Meaning | +| -------------------------------------- | ---------------------------------------------------------------------- | +| `stage(event, { group? })` | Adds an event to the draft after checking it with `reduce` | +| `commit()` / `discard()` | Signs the draft as one commit / drops it | +| `draft` | `{ group, events, state }` or `null` | +| `state(group?)` | A readable group's state; the default group when omitted | +| `groups` | Readable groups with their members and roles | +| `rejected` | Commits with no effect, with `reason` `"authority"` or `"application"` | +| `unreadable` | How many entries none of your keys open | +| `head`, `export()` | The head commit ID and the document bytes | +| `createGroup()` | A new group with you as its admin | +| `setMember(identity, { group, role })` | Adds a member or changes a role; admins only | +| `removeMember(identity, { group })` | Removes a member and rotates the group key; admins only | +| `rebase(remote, { published })` | Reapplies your unpublished commits onto another copy | + +A draft belongs to one group. Group operations commit immediately and throw while a draft +has events. Call `stage` then `commit` to write immediately. Errors are ordinary `Error`s. + +## Groups + +Genesis creates the default group with its creator as admin. Anyone who can add to the +file can create a group and becomes its only admin. Roles are `member` (read and write) and +`admin` (also manages members); a group always keeps one admin. + +Each group's state is built only from its own events, so every member of a group computes +the same state whatever other groups they are in. A new member receives every past key and +reads the whole history. Removing a member gives the group a new key for future events; +they keep what they already had. Removal from the default group does not remove anyone from +other groups. A removed member is not told: their copy shows the group as it was when they +last could read it. + +## What Concord guarantees + +- Anyone holding the file can verify its history is intact and signed by the keys it names. +- A group's members can check who was allowed to make each change in that group. +- Readers with the same group history, keys and model compute the same state for it. + +A signed commit that breaks a group's rules stays in the history as evidence, changes +nothing, and appears in `rejected`. A document whose history fails Ledger verification does +not open. + +## What the raw file can reveal + +Without keys, someone holding the file can see each commit's signer key (so an author's +activity is linkable), its claimed time, the shape of the history, how many entries each +commit has, ciphertext sizes, and how many people a key was wrapped to. Those can hint at +the kind and volume of activity. Group IDs, models, membership, roles, event types and data +are encrypted. + +## Rebase + +Two copies that both moved on from the same head have diverged; Concord never merges them. +`rebase(remote, { published })` takes the other copy and the last head you published. It +re-signs your own later commits on top of the remote, checking each against the remote's +current rules, and returns the commits that no longer apply. It throws rather than discard +someone else's unpublished commits, and while a draft is open. + +## Limits + +Readers try every key they hold on every entry, because entries carry no group label. Opening +took about 90 ms with 10 groups and 330 ms with 30 in a local measurement, growing with groups +times entries. Storage, sync, group names and UI belong to the application. + +License: ISC. diff --git a/packages/concord/SPEC.md b/packages/concord/SPEC.md deleted file mode 100644 index a19ed82..0000000 --- a/packages/concord/SPEC.md +++ /dev/null @@ -1,8 +0,0 @@ -# Concord alpha contract - -The accepted ownership is [one Ledger container](../../docs/adr/0018-use-one-ledger-container-for-concord.md). -The current wire contract is [Protocol 1](../../docs/concord/alpha-protocol.md), with -[standard profile 1](../../docs/concord/standard-profile.md) defining authority and encryption. -Ledger owns the signed history lifecycle; Concord composes commands, system replay -and application replay. Current implemented scope and the alpha compatibility break -are documented in [README.md](README.md). Older implementations remain in Git. diff --git a/packages/concord/llms.txt b/packages/concord/llms.txt index 2e55196..1bf4a97 100644 --- a/packages/concord/llms.txt +++ b/packages/concord/llms.txt @@ -1,165 +1,49 @@ # @ternent/concord -> Build a bounded application around typed commands, signed history and encrypted groups. +> Shared, signed, partly private documents built from an application's events and reducer. -Stable interface: `npm install @ternent/concord@0.3.0 @ternent/armour@0.3.0`. -[Public README](https://github.com/ternent/core/blob/main/packages/concord/README.md). -Root declarations: `dist/index.d.ts` and its referenced model/protocol types. -Specialist exports: `/system`, `/protocol`, `/testing`. - -## Define a model and author a document +Exports: `createDocument`, `openDocument`, `defineModel`. Types include `Model`, `Event`, +`Document`, `Group`, `GroupId`, `Member`, `Role`, `Rejection`, `Returned`, `Json`. +Declarations: `dist/index.d.ts`. ```ts -import { - defineModel, - createDocument, - openDocument, - type Result, - type ModelIssue, -} from "@ternent/concord"; -import { createStandardSystemProfile } from "@ternent/concord/system"; -import { generateIdentity } from "@ternent/armour"; - -type State = { value: string }; -type Commands = { set: { value: string } }; -type Event = { type: "value.set"; version: 1; data: { value: string } }; -function ok(value: T): Result { - return { ok: true, value }; -} -const invalid = (): Result => ({ - ok: false, - error: { code: "VALUE_INVALID", message: "Expected a string value" }, -}); -function validate(input: unknown): Result { - if ( - !input || - typeof input !== "object" || - Array.isArray(input) || - !("value" in input) || - typeof input.value !== "string" - ) - return invalid(); - return ok({ value: input.value }); -} -const model = defineModel({ - ref: { id: "example.value", version: 1 }, - initial: () => ({ value: "" }), - commands: { - set: { validate, decide: (input) => ok([{ type: "value.set", version: 1, data: input }]) }, +import { createIdentity } from "@ternent/identity"; +import { createDocument, defineModel, openDocument } from "@ternent/concord"; + +const tasks = defineModel({ + id: "tasks", + version: 1, + initial: () => ({ tasks: {} }), + reduce(state, event) { + if (event.type === "task.add") return { tasks: { ...state.tasks, [event.data.id]: event.data } }; + throw new Error(`Unknown event ${event.type}`); }, - validateEvent(input) { - if ( - !input || - typeof input !== "object" || - Array.isArray(input) || - !("type" in input) || - input.type !== "value.set" || - !("version" in input) || - input.version !== 1 || - !("data" in input) - ) - return invalid(); - const data = validate(input.data); - return data.ok ? ok({ type: "value.set", version: 1, data: data.value }) : data; - }, - requirements: () => ["write"], - reduce: (_state, event) => ok({ value: event.data.value }), }); -const identityResult = await generateIdentity(); -if (!identityResult.ok) throw new Error(identityResult.error.code); -const identity = identityResult.value; -const system = createStandardSystemProfile(); -const created = await createDocument({ model, system, identity }); -if (!created.ok) throw new Error(created.error.code); -const document = created.value; -const written = await document.dispatch("set", { value: "hello" }); -if (!written.ok) throw new Error(written.error.code); -const bytes = document.export(); -const reopened = await openDocument({ bytes, model, system, signer: identity }); -const state = reopened.state(); -if (state.status !== "ready") throw new Error(reopened.inspect().findings[0]?.code); -console.log(state.projection.value); -``` - -The host owns the identity and chooses trusted model/system implementations. Persisting -committed document bytes does not persist the identity capability. Reopen needs those -implementations and the reader's keys to reconstruct private application state. - -## Model contract - -One document declares one stable model id/version. Commands validate unknown input, -then decide events against the current projection (or draft preview). validateEvent -checks recorded events during replay; reduce is pure and returns new JSON state. -requirements declares needed capabilities and is checked during authoring and replay. -Time, randomness and external reads belong in authored input, never reducers. Values -must be portable JSON with safe integers, valid Unicode and no undefined or hooks. -There is no in-place model upgrade or automatic plugin loading. - -## Handle lifecycle and errors - -createDocument returns Result; openDocument returns a handle, including -read-only inspection handles for invalid, incompatible, locked or stale input. -state is either ready (projection, head, documentId, canWrite, coverage, lockedEntries) -or inspection (reason). Always narrow status before rendering a projection. inspect -exposes verification, system/application status, findings, requirements and evidence. -verify returns an integrity report; it does not certify freshness or model validity. -replay returns Result<{ projection, coverage, lockedEntries }>. -Dispatch, commit and discardDraft return structured Results. Treat thrown host or -transport failures separately. export returns Uint8Array committed bytes; inspection -exports preserve original evidence. Default dispatch immediately signs a local commit. -Publication to storage is a separate host operation. -## Drafts +const alice = await createIdentity(); +const doc = await createDocument({ model: tasks, identity: alice }); +doc.stage({ type: "task.add", data: { id: "1", title: "Plan" } }); +await doc.commit(); // stage + commit is an immediate write -Pass mode draft to create/open. dispatch stages command intents in memory; draft() -returns baseHead, entryCount and preview. state/inspect/export/verify/replay continue -to describe committed history. commit({ message: "..." }) signs the staged group; -discardDraft drops it. Empty or immediate-mode commit fails NO_DRAFT. Genesis always -commits immediately. Drafts are not exported or recovered by the library. The host -owns autosave, command retention and recovery. Commit messages are public metadata. - -## Members, groups and readable replay - -Import createGroup, setMember, removeMember and createStandardSystemProfile from -`@ternent/concord/system`. Genesis signer initially owns the default document group. -Capabilities are read/write/grant/administer. System changes require an immediate-mode -handle; draft mode does not implicitly switch modes. A default-group writer can -createGroup(handle), receiving an AudienceId. Additional groups have independent -memberships; document ownership does not grant their keys or administration. - -setMember(handle, { audience, identity: publicIdentity, capabilities: ["read", "write"] }) -admits or changes a member. Omitting audience selects document. Admission/readmission -grants that group's history. removeMember(handle, { audience, identityId }) rotates -future group encryption; historical keys/plaintext remain readable. Recipients' actual -decryptability cannot be certified by another reader. Do not implement these operations -with UI filters or by editing serialized history. - -A command's audience(input) selects exactly one group (default document) before its -decision gets group-scoped facts. model.audience(event) must agree with every emitted -event and its signed envelope. A command cannot span groups; a draft can group several -commands that target different groups. - -Without reduceLocked, missing private events prevent trusted application replay. -Opt into readable coverage with reduceLocked(state, { audience, epoch }, facts). -Never invent hidden event contents. A ready readable projection has incomplete -coverage; lockedEntries counts events, not distinct domain objects. Invalid reachable -signed history blocks trusted state even for groups the reader cannot decrypt. - -## Storage, conflict retry and freshness - -export bytes for storage. `/testing` exports ArtifactStore/ExpectedHeadArtifactStore -and copied-buffer in-memory reference stores, including createMemoryExpectedHeadStore. -They are reference implementations, not a network sync provider. Production adapters -must implement atomic expected-head writes using provider transactions or conditions. - -Keep a remembered remote head and the intended commands until publication succeeds. -On an explicit HEAD_CONFLICT, retain local and remote bytes, inspect/compare snapshots, -open the accepted remote snapshot and reissue the intent under current authority. -Reissue creates new signed events and can fail validation or permission checks. Retain -local work if it fails. Do not blindly retry an uncertain transport outcome or infer -commands from encrypted event history. Runtime mutations do not publish or retry. +const leads = await doc.createGroup(); +doc.stage({ type: "task.add", data: { id: "2", title: "Private" } }, { group: leads }); +await doc.commit(); +const bytes = doc.export(); // store or sync these bytes; Concord does neither +``` -openDocument({ bytes, model, system, signer, anchor: rememberedSnapshotBytes }) detects -older/divergent snapshots relative to that verified anchor. Without it, valid integrity -reports freshness unanchored. Storage latest-head discovery belongs to the adapter/host. -There are no merge, fetch, push, pull or checkpoint methods in the runtime. +- `reduce` must be synchronous and pure, never mutate `state` (it is frozen), and throw to reject. +- `reduce` only sees its own group's state. Rules that must bind a group can only use that + group's events. Combine group states for display in the app. +- A draft holds events for one group. `createGroup`, `setMember`, `removeMember` and + `rebase` throw while a draft has events. +- `state(group)` throws for a group you cannot read; that is different from an empty group. +- Check `doc.rejected`: signed commits that broke a group's rules have no effect. +- Roles: `"member"` and `"admin"`. Only admins change membership; the last admin stays. +- Adding a member reveals the group's whole history to them. Removal rotates the key for the + future only. +- Bump `version` when `reduce` rules change, and keep handling old events; older apps refuse + newer groups. +- After two copies diverge, call `rebase(otherBytes, { published: lastPublishedHead })` and + show the returned commits to the user. +- Without keys, the file still shows signer keys, times, history shape and sizes. Don't + promise users more privacy than that. diff --git a/packages/concord/package.json b/packages/concord/package.json index dbf90b1..faf6ed5 100644 --- a/packages/concord/package.json +++ b/packages/concord/package.json @@ -1,7 +1,7 @@ { "name": "@ternent/concord", "version": "0.3.0", - "description": "Command-driven developer runtime for building non-custodial apps on @ternent/ledger", + "description": "Shared, signed, partly private documents built from an application's events", "license": "ISC", "repository": { "type": "git", @@ -22,18 +22,6 @@ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" - }, - "./protocol": { - "types": "./dist/protocol/index.d.ts", - "import": "./dist/protocol/index.js" - }, - "./system": { - "types": "./dist/system/index.d.ts", - "import": "./dist/system/index.js" - }, - "./testing": { - "types": "./dist/testing/index.d.ts", - "import": "./dist/testing/index.js" } }, "publishConfig": { @@ -49,9 +37,11 @@ "check": "pnpm --filter @ternent/concord... run build && pnpm run fmt:check && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run check:artifact" }, "dependencies": { + "@scure/base": "2.4.0", "@ternent/armour": "workspace:^", "@ternent/identity": "workspace:^", - "@ternent/ledger": "workspace:^" + "@ternent/ledger": "workspace:^", + "age-encryption": "0.3.1" }, "devDependencies": { "typescript": "npm:@typescript/typescript6@6.0.2", diff --git a/packages/concord/src/common/errors.ts b/packages/concord/src/common/errors.ts deleted file mode 100644 index cdd0b77..0000000 --- a/packages/concord/src/common/errors.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { - Fault, - ok as historyOk, - error as historyError, - fail as historyFail, - caught as historyCaught, - attempt as historyAttempt, -} from "@ternent/ledger/protocol"; -export { Fault }; -import type { JsonObject } from "../protocol/types.js"; -export type ErrorCode = - | "JSON_INVALID" - | "SCHEMA_INVALID" - | "PROTOCOL_UNSUPPORTED" - | "SUITE_UNSUPPORTED" - | "ENTRY_KIND_UNSUPPORTED" - | "RESOURCE_LIMIT" - | "DUPLICATE_RECORD" - | "UNREFERENCED_RECORD" - | "ENTRY_MISSING" - | "ENTRY_ORDER" - | "HASH_MISMATCH" - | "LINK_INVALID" - | "DECLARATION_INVALID" - | "HEAD_INVALID" - | "IDENTITY_INVALID" - | "SIGNATURE_INVALID" - | "REQUIREMENT_UNAVAILABLE" - | "HOST_CONFIGURATION" - | "IDENTITY_MISMATCH" - | "STALE_HEAD" - | "DIVERGED_HEAD" - | "DOCUMENT_MISMATCH" - | "ANCHOR_INVALID" - | "SYSTEM_EVENT_INVALID" - | "SYSTEM_NO_CHANGE" - | "LAST_ADMINISTRATOR" - | "UNSUPPORTED_SYSTEM_EVENT" - | "CAPABILITY_DENIED" - | "READ_ACCESS_REQUIRED" - | "KEY_UNAVAILABLE" - | "KEY_WRAP_INVALID" - | "DECRYPTION_INVALID" - | "EVENT_CONTEXT_INVALID" - | "HISTORICAL_KEY_UNAVAILABLE" - | "COMMAND_UNSUPPORTED" - | "COMMAND_INVALID" - | "COMMAND_REJECTED" - | "NO_EVENTS" - | "EVENT_UNSUPPORTED" - | "EVENT_INVALID" - | "MODEL_TRANSITION_INVALID" - | "MODEL_FAILED" - | "SYSTEM_FAILED" - | "READ_ONLY_RUNTIME" - | "INSPECTION_ONLY" - | "NO_DRAFT" - | "DRAFT_PENDING" - | "SIGNING_FAILED" - | "ENCRYPTION_FAILED" - | "STORAGE_FAILED" - | "HEAD_CONFLICT"; -export type Phase = - | "input" - | "protocol" - | "requirements" - | "system" - | "model" - | "author" - | "storage"; -export type ConcordError = { - code: ErrorCode; - phase: Phase; - message: string; - path?: string; - commitId?: string; - entryId?: string; - details?: Readonly; -}; -export type Result = { ok: true; value: T } | { ok: false; error: E }; -export const ok = (value: T): Result => historyOk(value) as Result; -export const error = (code: ErrorCode, phase: Phase, path?: string): ConcordError => - historyError(code, phase, path) as ConcordError; -export function fail(code: ErrorCode, phase: Phase = "protocol", path?: string): never { - return historyFail(code, phase, path); -} -export function caught(cause: unknown, fallback: ErrorCode, phase: Phase): ConcordError { - return historyCaught(cause, fallback, phase) as ConcordError; -} -export function attempt( - body: () => T, - fallback: ErrorCode = "SCHEMA_INVALID", - phase: Phase = "protocol", -): Result { - return historyAttempt(body, fallback, phase) as Result; -} diff --git a/packages/concord/src/common/immutable.ts b/packages/concord/src/common/immutable.ts deleted file mode 100644 index 4224b32..0000000 --- a/packages/concord/src/common/immutable.ts +++ /dev/null @@ -1 +0,0 @@ -export { detached, freeze } from "@ternent/ledger/protocol"; diff --git a/packages/concord/src/common/random.ts b/packages/concord/src/common/random.ts deleted file mode 100644 index 5a9bf88..0000000 --- a/packages/concord/src/common/random.ts +++ /dev/null @@ -1 +0,0 @@ -export { nonce } from "@ternent/ledger/protocol"; diff --git a/packages/concord/src/index.ts b/packages/concord/src/index.ts index 65013c4..11fd8d7 100644 --- a/packages/concord/src/index.ts +++ b/packages/concord/src/index.ts @@ -1,5 +1,705 @@ -export { createDocument, openDocument } from "./runtime.js"; -export { defineModel } from "./model/index.js"; -export type * from "./model/types.js"; -export type * from "./protocol/types.js"; -export type { Result, ConcordError, ErrorCode } from "./common/errors.js"; +import { base64urlnopad } from "@scure/base"; +import { decrypt, encrypt } from "@ternent/armour"; +import { validatePublicIdentity, type Identity, type PublicIdentity } from "@ternent/identity"; +import { createLedger, createWriter, openLedger, type Commit, type History } from "@ternent/ledger"; +import { generateX25519Identity, identityToRecipient } from "age-encryption"; + +export type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; +export type Event = { type: string; data: Json }; +export type Role = "member" | "admin"; +export type GroupId = `group:${string}`; +export type Member = { identity: PublicIdentity; role: Role }; +export type Group = { id: GroupId; default: boolean; members: Member[] }; +export type Rejection = { + commit: string; + group: GroupId; + reason: "authority" | "application"; + message: string; +}; +export type Returned = { commit: string; group: GroupId; events: Event[]; message: string }; +export type ReduceContext = { author: PublicIdentity; version: number }; + +export type Model = { + id: string; + version: number; + initial(): S; + reduce(state: S, event: Event, context: ReduceContext): S; + squash?(events: readonly Event[]): Event[]; +}; + +export function defineModel(model: Model): Model { + return model; +} + +type Epoch = { secret: string; recipient: string }; +type GroupState = { + id: GroupId; + isDefault: boolean; + members: Map; + epochs: Map; + current: number; + state: Json; + unsupported?: string; +}; +type Replay = { + groups: Map; + candidates: Map>; + // Entries that are key wraps to this identity; they are not group records. + wraps: Set; + rejected: Rejection[]; + unreadable: number; + // This identity's application commits, kept for rebase. + authored: Map; +}; +type Body = + | { op: "create"; id: GroupId; model: string; members: Member[] } + | { op: "set"; identity: PublicIdentity; role: Role } + | { op: "remove"; identity: PublicIdentity; epoch: number } + | { op: "events"; events: Event[]; version: number }; + +const KIND = "concord"; +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +class Rejected extends Error { + constructor( + readonly reason: Rejection["reason"], + message: string, + ) { + super(message); + } +} + +class ConcordDocument { + readonly #model: Model; + readonly #identity: Identity; + #history: History; + #replay: Replay; + #draft: { group: GroupId; events: Event[]; state: S } | null = null; + + constructor(model: Model, identity: Identity, history: History, replay: Replay) { + this.#model = model; + this.#identity = identity; + this.#history = history; + this.#replay = replay; + } + + get head(): string { + return this.#history.head; + } + + get draft(): { group: GroupId; events: readonly Event[]; state: S } | null { + return this.#draft; + } + + get rejected(): readonly Rejection[] { + return this.#replay.rejected; + } + + get unreadable(): number { + return this.#replay.unreadable; + } + + get groups(): Group[] { + return [...this.#replay.groups.values()].map((group) => ({ + id: group.id, + default: group.isDefault, + members: [...group.members.values()], + })); + } + + export(): Uint8Array { + return this.#history.export(); + } + + state(group?: GroupId): S { + return this.#readable(group ?? this.#defaultGroup()).state as S; + } + + stage(event: Event, options: { group?: GroupId } = {}): void { + const id = options.group ?? this.#draft?.group ?? this.#defaultGroup(); + if (this.#draft && this.#draft.group !== id) { + throw new Error("A draft holds events for one group; commit or discard it first"); + } + const group = this.#readable(id); + if (!group.members.has(this.#identity.publicIdentity.id)) { + throw new Error("Only members of a group can write to it"); + } + const captured = captureEvent(event); + const context = { author: this.#identity.publicIdentity, version: this.#model.version }; + const base = (this.#draft?.state ?? group.state) as S; + const state = deepFreeze(this.#model.reduce(base, captured, context)); + this.#draft = { group: id, events: [...(this.#draft?.events ?? []), captured], state }; + } + + discard(): void { + this.#draft = null; + } + + async commit(): Promise { + await this.#commitDraft(true); + } + + async createGroup(): Promise { + this.#noDraft(); + const id: GroupId = `group:${base64urlnopad.encode(crypto.getRandomValues(new Uint8Array(16)))}`; + await this.#append(await createEntries(id, this.#model.id, this.#identity.publicIdentity)); + return id; + } + + async setMember( + identity: PublicIdentity, + options: { group: GroupId; role: Role }, + ): Promise { + this.#noDraft(); + const group = this.#administered(options.group); + const target = validatePublicIdentity(identity); + if (options.role !== "member" && options.role !== "admin") throw new Error("Unknown role"); + const existing = group.members.get(target.id); + if (existing?.role === options.role) throw new Error("The member already has that role"); + if (existing?.role === "admin" && lastAdmin(group, target.id)) { + throw new Error("A group keeps at least one admin"); + } + const entries = [ + await sealGroup({ op: "set", identity: target, role: options.role }, currentEpoch(group)), + ]; + if (!existing) { + // A new member receives every epoch, so they can read the whole history. + const epochs = Object.fromEntries([...group.epochs].map(([n, epoch]) => [n, epoch.secret])); + entries.push(await sealWrap(group.id, epochs, [target])); + } + await this.#append(entries); + } + + async removeMember(identity: PublicIdentity, options: { group: GroupId }): Promise { + this.#noDraft(); + const group = this.#administered(options.group); + const target = validatePublicIdentity(identity); + const existing = group.members.get(target.id); + if (!existing) throw new Error("Not a member of this group"); + if (existing.role === "admin" && lastAdmin(group, target.id)) { + throw new Error("A group keeps at least one admin"); + } + const epoch = group.current + 1; + const secret = await generateX25519Identity(); + const next = { secret, recipient: await identityToRecipient(secret) }; + const remaining = [...group.members.values()] + .filter((member) => member.identity.id !== target.id) + .map((member) => member.identity); + await this.#append([ + await sealGroup({ op: "remove", identity: existing.identity, epoch }, next), + await sealWrap(group.id, { [epoch]: secret }, remaining), + ]); + } + + async rebase(remote: Uint8Array, options: { published: string }): Promise { + this.#noDraft(); + const local = this.#history.commits; + const start = local.findIndex((commit) => commit.id === options.published); + if (start < 0) throw new Error("The published head is not in this history"); + const other = await open(remote, this.#model, this.#identity); + const remoteIds = new Set(other.#history.commits.map((commit) => commit.id)); + if (!remoteIds.has(options.published)) { + throw new Error("The published head is not in the remote history"); + } + const pending = local.slice(start + 1).filter((commit) => !remoteIds.has(commit.id)); + for (const commit of pending) { + if (commit.proof.signer.id !== this.#identity.publicIdentity.id) { + throw new Error(`Commit ${commit.id} is another identity's unpublished work`); + } + if (!this.#replay.authored.has(commit.id)) { + throw new Error(`Commit ${commit.id} changes membership; publish or redo it first`); + } + } + const returned: Returned[] = []; + for (const commit of pending) { + const { group, events } = this.#replay.authored.get(commit.id)!; + try { + for (const event of events) other.stage(event, { group }); + await other.#commitDraft(false); + } catch (error) { + other.discard(); + returned.push({ commit: commit.id, group, events, message: messageOf(error) }); + } + } + this.#history = other.#history; + this.#replay = other.#replay; + return returned; + } + + async #commitDraft(squash: boolean): Promise { + const draft = this.#draft; + if (!draft) throw new Error("Nothing is staged"); + const group = this.#readable(draft.group); + let events = draft.events; + if (squash && this.#model.squash) { + events = this.#model.squash(draft.events.map((event) => structuredClone(event))); + events = events.map(captureEvent); + const context = { author: this.#identity.publicIdentity, version: this.#model.version }; + const squashed = events.reduce( + (state, event) => deepFreeze(this.#model.reduce(state, event, context)), + group.state as S, + ); + if (!sameJson(squashed, draft.state)) { + throw new Error("squash changed the result of the staged events"); + } + } + const body: Body = { op: "events", events, version: this.#model.version }; + await this.#append([await sealGroup(body, currentEpoch(group))]); + this.#draft = null; + } + + // Signs `ciphertexts` as one commit, then adopts it only if this identity's own replay + // accepts it, so a failure leaves history and state unchanged. + async #append(ciphertexts: Uint8Array[]): Promise { + const writer = createWriter(this.#history, this.#identity); + writer.append( + ciphertexts.map((bytes) => ({ kind: KIND, payload: base64urlnopad.encode(bytes) })), + ); + const history = await writer.commit(); + const replay = cloneReplay(this.#replay); + const commit = history.commits[history.commits.length - 1]; + await discover(commit, this.#identity, replay); + await apply(commit, history.commits.length - 1, this.#model, this.#identity, replay); + const rejection = replay.rejected.find((entry) => entry.commit === commit.id); + if (rejection) throw new Error(`The commit was not accepted: ${rejection.message}`); + this.#history = history; + this.#replay = replay; + } + + #defaultGroup(): GroupId { + const group = [...this.#replay.groups.values()].find((entry) => entry.isDefault); + if (!group) throw new Error("This identity cannot read the default group"); + return group.id; + } + + #readable(id: GroupId): GroupState { + const group = this.#replay.groups.get(id); + if (!group) throw new Error(`This identity cannot read group ${id}`); + if (group.unsupported) throw new Error(group.unsupported); + return group; + } + + #administered(id: GroupId): GroupState { + const group = this.#readable(id); + if (group.members.get(this.#identity.publicIdentity.id)?.role !== "admin") { + throw new Error("Only an admin of the group can change its membership"); + } + return group; + } + + #noDraft(): void { + if (this.#draft) throw new Error("Commit or discard the draft first"); + } + + static async create( + model: Model, + identity: Identity, + ): Promise> { + const id: GroupId = `group:${base64urlnopad.encode(crypto.getRandomValues(new Uint8Array(16)))}`; + const entries = await createEntries(id, model.id, identity.publicIdentity); + const history = await createLedger({ + signer: identity, + entries: entries.map((bytes) => ({ kind: KIND, payload: base64urlnopad.encode(bytes) })), + }); + return replayHistory(history, model, identity); + } +} + +export type Document = ConcordDocument; + +export async function createDocument(input: { + model: Model; + identity: Identity; +}): Promise> { + return ConcordDocument.create(input.model, input.identity); +} + +export async function openDocument( + bytes: Uint8Array, + input: { model: Model; identity: Identity }, +): Promise> { + return open(bytes, input.model, input.identity); +} + +async function open( + bytes: Uint8Array, + model: Model, + identity: Identity, +): Promise> { + return replayHistory(await openLedger(bytes), model, identity); +} + +// Opening is three passes: Ledger verifies the history, every wrap is decrypted to find +// candidate keys, then each group replays in order. A key gains authority only when an +// accepted record establishes its epoch, never because it decrypts something. +async function replayHistory( + history: History, + model: Model, + identity: Identity, +): Promise> { + const replay: Replay = { + groups: new Map(), + candidates: new Map(), + wraps: new Set(), + rejected: [], + unreadable: 0, + authored: new Map(), + }; + for (const commit of history.commits) await discover(commit, identity, replay); + for (const [index, commit] of history.commits.entries()) { + await apply(commit, index, model, identity, replay); + } + return new ConcordDocument(model, identity, history, replay); +} + +async function discover(commit: Commit, identity: Identity, replay: Replay): Promise { + for (const entry of commit.entries) { + const opened = await tryDecrypt(entry.payload, identity); + if (opened === undefined) continue; + const wrap = readWrap(opened); + if (!wrap) continue; + replay.wraps.add(entry.id); + const known = replay.candidates.get(wrap.group) ?? new Map(); + for (const [epoch, secret] of wrap.epochs) known.set(epoch, secret); + replay.candidates.set(wrap.group, known); + } +} + +async function apply( + commit: Commit, + index: number, + model: Model, + identity: Identity, + replay: Replay, +): Promise { + const opened: { group: GroupId; epoch: number; secret: string; body: unknown }[] = []; + for (const entry of commit.entries) { + if (replay.wraps.has(entry.id)) continue; + const found = await openGroupEntry(entry.payload, replay.candidates); + if (found) opened.push(found); + else replay.unreadable += 1; + } + const byGroup = new Map(); + for (const entry of opened) + byGroup.set(entry.group, [...(byGroup.get(entry.group) ?? []), entry]); + const signer = commit.proof.signer; + for (const [groupId, entries] of byGroup) { + try { + if (entries.length !== 1) + throw new Rejected("authority", "A commit holds one record per group"); + const [{ epoch, secret, body: raw }] = entries; + const body = readBody(raw); + if (body.op === "events" && signer.id === identity.publicIdentity.id) { + replay.authored.set(commit.id, { group: groupId, events: body.events }); + } + await applyRecord(groupId, epoch, secret, body, signer, index === 0, model, replay); + } catch (error) { + if (!(error instanceof Rejected)) throw error; + replay.rejected.push({ + commit: commit.id, + group: groupId, + reason: error.reason, + message: error.message, + }); + } + } +} + +async function applyRecord( + groupId: GroupId, + epoch: number, + secret: string, + body: Body, + signer: PublicIdentity, + genesis: boolean, + model: Model, + replay: Replay, +): Promise { + if (body.op === "create") { + if (replay.groups.has(groupId) || epoch !== 0 || body.id !== groupId) { + throw new Rejected("authority", "Invalid group creation"); + } + if ( + body.members.length !== 1 || + body.members[0].role !== "admin" || + body.members[0].identity.id !== signer.id + ) { + throw new Rejected("authority", "A group is created with its signer as the only admin"); + } + replay.groups.set(groupId, { + id: groupId, + isDefault: genesis, + members: new Map([[signer.id, body.members[0]]]), + epochs: new Map([[0, { secret, recipient: await identityToRecipient(secret) }]]), + current: 0, + state: deepFreeze(model.initial()), + unsupported: + body.model === model.id ? undefined : `Group ${groupId} uses model ${body.model}`, + }); + return; + } + const group = replay.groups.get(groupId); + if (!group) throw new Rejected("authority", "Unknown group"); + if (group.unsupported) return; + const author = group.members.get(signer.id); + + if (body.op === "events") { + if (!author) throw new Rejected("authority", "The author is not a member"); + if (epoch !== group.current) + throw new Rejected("authority", "Encrypted to an epoch that is not current"); + if (body.version > model.version) { + group.unsupported = `Group ${groupId} needs model version ${body.version}`; + return; + } + const context = { author: signer, version: body.version }; + let state = group.state as S; + try { + for (const event of body.events) state = deepFreeze(model.reduce(state, event, context)); + } catch (error) { + throw new Rejected("application", messageOf(error)); + } + group.state = state; + return; + } + + if (author?.role !== "admin") + throw new Rejected("authority", "Only an admin can change membership"); + const target = group.members.get(body.identity.id); + + if (body.op === "set") { + if (epoch !== group.current) + throw new Rejected("authority", "Encrypted to an epoch that is not current"); + if (target?.role === body.role) throw new Rejected("authority", "No change"); + if (target?.role === "admin" && lastAdmin(group, target.identity.id)) { + throw new Rejected("authority", "A group keeps at least one admin"); + } + group.members.set(body.identity.id, { identity: body.identity, role: body.role }); + return; + } + + if (epoch !== group.current + 1 || body.epoch !== epoch) { + throw new Rejected("authority", "A removal starts the next epoch"); + } + if (!target) throw new Rejected("authority", "Not a member"); + if (target.role === "admin" && lastAdmin(group, target.identity.id)) { + throw new Rejected("authority", "A group keeps at least one admin"); + } + group.members.delete(target.identity.id); + group.epochs.set(epoch, { secret, recipient: await identityToRecipient(secret) }); + group.current = epoch; +} + +async function openGroupEntry( + payload: unknown, + candidates: Replay["candidates"], +): Promise<{ group: GroupId; epoch: number; secret: string; body: unknown } | undefined> { + for (const [group, epochs] of candidates) { + for (const [epoch, secret] of epochs) { + const opened = await tryDecrypt(payload, secret); + if (opened !== undefined) return { group, epoch, secret, body: opened }; + } + } + return undefined; +} + +async function tryDecrypt(payload: unknown, key: Identity | string): Promise { + if (typeof payload !== "string") return undefined; + try { + return JSON.parse(decoder.decode(await decrypt(base64urlnopad.decode(payload), key))); + } catch { + return undefined; + } +} + +async function createEntries( + id: GroupId, + model: string, + creator: PublicIdentity, +): Promise { + const secret = await generateX25519Identity(); + const epoch = { secret, recipient: await identityToRecipient(secret) }; + return [ + await sealGroup( + { op: "create", id, model, members: [{ identity: creator, role: "admin" }] }, + epoch, + ), + await sealWrap(id, { 0: secret }, [creator]), + ]; +} + +async function sealGroup(body: Body, epoch: Epoch): Promise { + return encrypt(encoder.encode(JSON.stringify({ concord: 1, ...body })), [epoch.recipient]); +} + +async function sealWrap( + group: GroupId, + epochs: Record, + recipients: PublicIdentity[], +): Promise { + return encrypt(encoder.encode(JSON.stringify({ concord: 1, group, epochs })), recipients); +} + +function readWrap(value: unknown): { group: GroupId; epochs: [number, string][] } | undefined { + if ( + !isRecord(value) || + value.concord !== 1 || + !isGroupId(value.group) || + !isRecord(value.epochs) + ) { + return undefined; + } + const epochs = Object.entries(value.epochs).map( + ([key, secret]) => [Number(key), secret] as const, + ); + if ( + !epochs.every(([n, secret]) => Number.isSafeInteger(n) && n >= 0 && typeof secret === "string") + ) { + return undefined; + } + return { group: value.group, epochs: epochs as [number, string][] }; +} + +function readBody(value: unknown): Body { + const invalid = () => new Rejected("authority", "Malformed record"); + if (!isRecord(value) || value.concord !== 1) throw invalid(); + if (Array.isArray(value.events)) { + if (!Number.isSafeInteger(value.version) || (value.version as number) < 1) throw invalid(); + try { + return { + op: "events", + events: value.events.map(captureEvent), + version: value.version as number, + }; + } catch { + throw invalid(); + } + } + try { + if ( + value.op === "create" && + isGroupId(value.id) && + typeof value.model === "string" && + Array.isArray(value.members) + ) { + return { + op: "create", + id: value.id, + model: value.model, + members: value.members.map(readMember), + }; + } + if (value.op === "set" && (value.role === "member" || value.role === "admin")) { + return { op: "set", identity: validatePublicIdentity(value.identity), role: value.role }; + } + if (value.op === "remove" && Number.isSafeInteger(value.epoch)) { + return { + op: "remove", + identity: validatePublicIdentity(value.identity), + epoch: value.epoch as number, + }; + } + } catch { + throw invalid(); + } + throw invalid(); +} + +function readMember(value: unknown): Member { + if (!isRecord(value) || (value.role !== "member" && value.role !== "admin")) { + throw new Error("Malformed member"); + } + return { identity: validatePublicIdentity(value.identity), role: value.role }; +} + +function captureEvent(value: unknown): Event { + if ( + !isRecord(value) || + typeof value.type !== "string" || + value.type.length < 1 || + value.type.length > 128 + ) { + throw new TypeError("An event is { type, data } with a type of 1 to 128 characters"); + } + if (!isJson(value.data)) throw new TypeError("Event data must be JSON"); + return { type: value.type, data: structuredClone(value.data) }; +} + +function isJson(value: unknown): value is Json { + if (value === null || typeof value === "boolean" || typeof value === "string") return true; + if (typeof value === "number") return Number.isFinite(value); + if (Array.isArray(value)) return value.every(isJson); + return ( + typeof value === "object" && + Object.getPrototypeOf(value) === Object.prototype && + Object.values(value).every(isJson) + ); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isGroupId(value: unknown): value is GroupId { + return typeof value === "string" && /^group:[A-Za-z0-9_-]{22}$/.test(value); +} + +function currentEpoch(group: GroupState): Epoch { + const epoch = group.epochs.get(group.current); + if (!epoch) throw new Error("This identity does not hold the group's current key"); + return epoch; +} + +function lastAdmin(group: GroupState, id: string): boolean { + return ![...group.members.values()].some( + (member) => member.role === "admin" && member.identity.id !== id, + ); +} + +function cloneReplay(replay: Replay): Replay { + return { + groups: new Map( + [...replay.groups].map(([id, group]) => [ + id, + { ...group, members: new Map(group.members), epochs: new Map(group.epochs) }, + ]), + ), + candidates: new Map([...replay.candidates].map(([id, epochs]) => [id, new Map(epochs)])), + wraps: new Set(replay.wraps), + rejected: [...replay.rejected], + unreadable: replay.unreadable, + authored: new Map(replay.authored), + }; +} + +// Compares JSON values regardless of object key order. +function sameJson(a: unknown, b: unknown): boolean { + if (Array.isArray(a) || Array.isArray(b)) { + return ( + Array.isArray(a) && + Array.isArray(b) && + a.length === b.length && + a.every((v, i) => sameJson(v, b[i])) + ); + } + if (isRecord(a) && isRecord(b)) { + const keys = Object.keys(a); + return ( + keys.length === Object.keys(b).length && + keys.every((key) => Object.hasOwn(b, key) && sameJson(a[key], b[key])) + ); + } + return a === b; +} + +function deepFreeze(value: T): T { + if (typeof value === "object" && value !== null && !Object.isFrozen(value)) { + for (const child of Object.values(value)) deepFreeze(child); + Object.freeze(value); + } + return value; +} + +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/packages/concord/src/model/index.ts b/packages/concord/src/model/index.ts deleted file mode 100644 index ff49537..0000000 --- a/packages/concord/src/model/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { ApplicationModel } from "./types.js"; -import type { Json, DomainEvent } from "../protocol/types.js"; -export function defineModel, E extends DomainEvent>( - model: ApplicationModel, -): ApplicationModel { - return model; -} diff --git a/packages/concord/src/model/types.ts b/packages/concord/src/model/types.ts deleted file mode 100644 index 6bf14ec..0000000 --- a/packages/concord/src/model/types.ts +++ /dev/null @@ -1,108 +0,0 @@ -import type { IdentityCapability, ReaderCapability } from "@ternent/armour"; -import type { - PublicIdentity, - CommitId, - EntryId, - Json, - JsonObject, - ModelRef, - DomainEvent, - Limits, - VerificationReport, - CommitRecord, - Relationship, - AudienceId, -} from "../protocol/types.js"; -import type { Result } from "../common/errors.js"; -export type { IdentityCapability, ReaderCapability } from "@ternent/armour"; -export type Capability = "read" | "write" | "grant" | "administer"; -export type Member = { identity: PublicIdentity; capabilities: readonly Capability[] }; -export type SystemFacts = { - actor: PublicIdentity; - audience: AudienceId; - capabilities: readonly Capability[]; - members: readonly Member[]; -}; -export type ModelIssue = { code: string; message: string; path?: string }; -export type ApplicationModel< - S extends Json, - C extends Record, - E extends DomainEvent = DomainEvent, -> = { - ref: ModelRef; - initial(this: void): S; - commands: { - [K in keyof C]: { - validate(this: void, input: unknown): Result; - audience?(this: void, input: C[K]): AudienceId; - decide( - this: void, - input: C[K], - state: Readonly, - context: { facts: SystemFacts }, - ): Result; - }; - }; - validateEvent(this: void, input: unknown): Result; - audience?(this: void, event: E): AudienceId; - requirements(this: void, event: E): readonly Capability[]; - reduce(this: void, state: Readonly, event: E, facts: SystemFacts): Result; - reduceLocked?( - this: void, - state: Readonly, - entry: { audience: AudienceId; epoch: number }, - facts: SystemFacts, - ): Result; -}; -export type ReplayCoverage = { coverage: "complete" | "readable"; lockedEntries: number }; -export type ProjectionResult = ReplayCoverage & { projection: Readonly }; -export type ReadyState = ReplayCoverage & { - status: "ready"; - documentId: CommitId; - head: CommitId; - projection: Readonly; - canWrite: boolean; -}; -export type InspectionState = { - status: "inspection"; - reason: "invalid" | "locked" | "incompatible" | "freshness"; -}; -export type CommitReceipt = { status: "committed"; head: CommitId; entryIds: readonly EntryId[] }; -export type DraftReceipt = { status: "staged"; baseHead: CommitId; entryCount: number }; -export type DraftState = { baseHead: CommitId; entryCount: number; preview: Readonly }; -export type InspectionReport = { - verification: VerificationReport; - system: "valid" | "invalid" | "unsupported" | "not-run"; - application: "valid" | "scoped" | "invalid" | "unsupported" | "locked" | "not-run"; - otherRecipientsDecryptability: "unverified"; - freshness: "unanchored" | Relationship; - requirements: readonly { kind: "system" | "model"; ref: ModelRef }[]; - lockedEntries: number | null; - findings: readonly import("../common/errors.js").ConcordError[]; - history: readonly CommitRecord[]; - entries: readonly import("../system/types.js").ReplayItem[] | null; - audiences: readonly import("../system/types.js").AudienceState[] | null; -}; -export interface DocumentHandle> { - state(): ReadyState | InspectionState; - dispatch( - command: K, - input: C[K], - ): Promise>; - commit(metadata?: JsonObject): Promise>; - discardDraft(): Promise>; - draft(): DraftState | null; - export(): Uint8Array; - verify(): Promise; - replay(): Promise>>; - inspect(): InspectionReport; -} -export type HostOptions, E extends DomainEvent> = { - model?: ApplicationModel; - system?: import("../system/types.js").SystemProfile; - reader?: ReaderCapability; - signer?: IdentityCapability; - mode?: "immediate" | "draft"; - limits?: Partial; - anchor?: Uint8Array; -}; diff --git a/packages/concord/src/protocol/history.ts b/packages/concord/src/protocol/history.ts deleted file mode 100644 index b92a534..0000000 --- a/packages/concord/src/protocol/history.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { orderedEntries } from "@ternent/ledger/protocol"; -import { detached } from "../common/immutable.js"; -import { declaration, logicalEntry } from "./schema.js"; -import type { Snapshot } from "./types.js"; -import type { VerifiedHistory } from "../system/types.js"; -const issued = new WeakSet(); -export function issueHistory(snapshot: Snapshot): VerifiedHistory { - const history = detached({ - documentId: snapshot.documentId, - head: snapshot.head, - declaration: declaration(snapshot), - ordered: Array.from(orderedEntries(snapshot), ({ commit, entry }) => ({ - commit, - entry: logicalEntry(entry), - })), - }) as unknown as VerifiedHistory; - issued.add(history); - return history; -} -export function isVerifiedHistory(value: VerifiedHistory): boolean { - return issued.has(value); -} diff --git a/packages/concord/src/protocol/index.ts b/packages/concord/src/protocol/index.ts deleted file mode 100644 index b6a331d..0000000 --- a/packages/concord/src/protocol/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { canonicalize } from "./json.js"; -export { hashEntrySubject, hashCommitSubject, verifyDocument, compareSnapshots } from "./verify.js"; -export type * from "./types.js"; -export type { Result, ConcordError, ErrorCode } from "../common/errors.js"; diff --git a/packages/concord/src/protocol/json.ts b/packages/concord/src/protocol/json.ts deleted file mode 100644 index 373ec52..0000000 --- a/packages/concord/src/protocol/json.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { canonicalize as canonicalizeHistory } from "@ternent/ledger/protocol"; -import type { Result } from "../common/errors.js"; -export { encodeJson, parseJson, unicode, utf8, text } from "@ternent/ledger/protocol"; -export function canonicalize(value: unknown): Result { - return canonicalizeHistory(value) as Result; -} diff --git a/packages/concord/src/protocol/schema.ts b/packages/concord/src/protocol/schema.ts deleted file mode 100644 index 915c294..0000000 --- a/packages/concord/src/protocol/schema.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { decodeBase64Url } from "@ternent/identity"; -import { fail } from "../common/errors.js"; -import type { - AudienceId, - Limits, - Snapshot, - Declaration, - RawEntryRecord, - EntryRecord, - EntrySubject, -} from "./types.js"; -export function isAudienceId(value: unknown): value is AudienceId { - if (value === "document") return true; - if (typeof value !== "string" || !/^group:[A-Za-z0-9_-]{22}$/.test(value)) return false; - const decoded = decodeBase64Url(value.slice(6)); - return decoded.ok && decoded.value.length === 16; -} -export const defaults: Limits = { - maxBytes: 16 * 1024 * 1024, - maxCommits: 10_000, - maxEntries: 100_000, - maxCiphertextBytes: 1024 * 1024, - maxDepth: 64, - maxMetadataBytes: 64 * 1024, -}; -export function limits(input: Partial = {}): Limits { - if ( - !input || - typeof input !== "object" || - Object.keys(input).some((k) => !Object.hasOwn(defaults, k)) - ) - fail("HOST_CONFIGURATION", "requirements"); - const result = { ...defaults, ...input }; - if (Object.values(result).some((v) => !Number.isSafeInteger(v) || v <= 0)) - fail("HOST_CONFIGURATION", "requirements"); - return result; -} -export function object(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -export function closed( - value: unknown, - keys: readonly string[], - path: string, -): asserts value is Record { - if ( - !object(value) || - Object.keys(value).length !== keys.length || - keys.some((k) => !Object.hasOwn(value, k)) - ) - fail("SCHEMA_INVALID", "protocol", path); -} -export function ref(value: unknown, path: string): void { - closed(value, ["id", "version"], path); - if ( - typeof value.id !== "string" || - !/^[a-z][a-z0-9.-]{0,127}$/.test(value.id) || - !Number.isInteger(value.version) || - Number(value.version) < 1 || - Number(value.version) > 2147483647 - ) - fail("SCHEMA_INVALID", "protocol", path); -} -function id(value: unknown, kind: "entry" | "commit", path: string): void { - if (typeof value !== "string" || !new RegExp(`^${kind}:[0-9a-f]{64}$`).test(value)) - fail("SCHEMA_INVALID", "protocol", path); -} -export function bytes( - value: unknown, - size: number | null, - path: string, - maximum?: number, -): Uint8Array { - if (typeof value !== "string") fail("SCHEMA_INVALID", "protocol", path); - if (maximum !== undefined && Math.floor((value.length * 6) / 8) > maximum) - fail("RESOURCE_LIMIT", "protocol", path); - const decoded = decodeBase64Url(value); - if ( - !decoded.ok || - (size !== null && decoded.value.length !== size) || - (size === null && !decoded.value.length) - ) - fail("SCHEMA_INVALID", "protocol", path); - return decoded.value; -} -export function entrySubject( - input: unknown, - path: string, - lim: Limits, -): asserts input is EntrySubject { - closed(input, ["version", "parent", "nonce", "kind", "payload"], path); - if (input.version !== 1) fail("SCHEMA_INVALID", "protocol", `${path}/version`); - if (input.parent !== null) id(input.parent, "commit", `${path}/parent`); - bytes(input.nonce, 16, `${path}/nonce`); - if (typeof input.kind !== "string" || !object(input.payload)) - fail("SCHEMA_INVALID", "protocol", path); - if (input.kind === "system") { - closed(input.payload, ["type", "version", "data"], `${path}/payload`); - ref({ id: input.payload.type, version: input.payload.version }, `${path}/payload`); - if (!object(input.payload.data)) fail("SCHEMA_INVALID", "protocol", `${path}/payload/data`); - // Ciphertext resource limits apply to every key wrap before profile execution. - const scan = (value: unknown): void => { - if (Array.isArray(value)) { - for (const item of value) scan(item); - } else if (object(value)) - for (const [key, item] of Object.entries(value)) { - if ( - key === "ciphertext" && - typeof item === "string" && - Math.floor((item.length * 6) / 8) > lim.maxCiphertextBytes - ) - fail("RESOURCE_LIMIT", "protocol", `${path}/payload/data`); - scan(item); - } - }; - scan(input.payload.data); - } else if (input.kind === "application") { - closed(input.payload, ["audience", "epoch", "ciphertext"], `${path}/payload`); - if ( - !isAudienceId(input.payload.audience) || - !Number.isSafeInteger(input.payload.epoch) || - Number(input.payload.epoch) < 0 - ) - fail("SCHEMA_INVALID", "protocol", `${path}/payload`); - bytes(input.payload.ciphertext, null, `${path}/payload/ciphertext`, lim.maxCiphertextBytes); - } else fail("ENTRY_KIND_UNSUPPORTED", "protocol", `${path}/kind`); -} -export function declaration(input: Snapshot): Declaration { - const metadata = input.commits[0].subject.metadata; - if (!object(metadata) || !Object.hasOwn(metadata, "concord")) - fail("DECLARATION_INVALID", "protocol", "/commits/0/subject/metadata"); - closed(metadata, ["concord"], "/commits/0/subject/metadata"); - closed(metadata.concord, ["system", "model"], "/commits/0/subject/metadata/concord"); - ref(metadata.concord.system, "/commits/0/subject/metadata/concord/system"); - ref(metadata.concord.model, "/commits/0/subject/metadata/concord/model"); - return metadata.concord as Declaration; -} - -/** Logical framework view of a raw signed entry, retaining its Ledger record ID. */ -export function logicalEntry(entry: RawEntryRecord): EntryRecord { - const subject = entry.subject; - return { - id: entry.id, - subject: { - version: 1, - parent: subject.parent, - nonce: subject.nonce, - kind: subject.kind, - payload: subject.payload.data, - } as EntrySubject, - }; -} - -/** Ledger has already validated the raw container and every cryptographic link. */ -export function snapshot(input: Snapshot, lim: Limits): void { - declaration(input); - for (const [index, entry] of input.entries.entries()) - entrySubject(logicalEntry(entry).subject, `/entries/${index}/subject/payload/data`, lim); -} diff --git a/packages/concord/src/protocol/types.ts b/packages/concord/src/protocol/types.ts deleted file mode 100644 index 717b51f..0000000 --- a/packages/concord/src/protocol/types.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { ConcordError } from "../common/errors.js"; -export type { PublicIdentity } from "@ternent/identity"; -export type Json = null | boolean | string | number | Json[] | { [key: string]: Json }; -export type JsonObject = { [key: string]: Json }; -export type CommitId = `commit:${string}`; -export type EntryId = `entry:${string}`; -export type ModelRef = { id: string; version: number }; -export type Declaration = { system: ModelRef; model: ModelRef }; -export type DomainEvent = { type: string; version: number; data: Json }; -export type SystemEvent = DomainEvent & { data: JsonObject }; -export type GroupId = `group:${string}`; -export type AudienceId = "document" | GroupId; -export type ProtectedEvent = { audience: AudienceId; epoch: number; ciphertext: string }; -type EntryBase = { version: 1; parent: CommitId | null; nonce: string }; -/** Prepared or replayed framework view; its signed source is RawEntrySubject. */ -export type EntrySubject = EntryBase & - ({ kind: "system"; payload: SystemEvent } | { kind: "application"; payload: ProtectedEvent }); -/** Logical replay view retaining the corresponding raw Ledger entry ID. */ -export type EntryRecord = { id: EntryId; subject: EntrySubject }; -// History records are the shared signed Ledger container. EntrySubject above is a -// prepared/replay view; it is never independently hashed or signed by Concord. -export type CommitSubject = import("@ternent/ledger").LedgerCommitSubject; -export type CommitRecord = import("@ternent/ledger").LedgerCommitRecord; -export type Snapshot = import("@ternent/ledger").LedgerSnapshot; -export type RawEntrySubject = import("@ternent/ledger").LedgerEntrySubject; -export type RawEntryRecord = import("@ternent/ledger").LedgerEntryRecord; -export type Limits = { - maxBytes: number; - maxCommits: number; - maxEntries: number; - maxCiphertextBytes: number; - maxDepth: number; - maxMetadataBytes: number; -}; -export type VerificationReport = { - integrity: "valid" | "invalid" | "unsupported"; - documentId: CommitId | null; - head: CommitId | null; - checkedCommits: number; - checkedEntries: number; - findings: readonly ConcordError[]; -}; -export type Relationship = "equal" | "ahead" | "behind" | "diverged" | "unrelated"; diff --git a/packages/concord/src/protocol/verify.ts b/packages/concord/src/protocol/verify.ts deleted file mode 100644 index a64b6bb..0000000 --- a/packages/concord/src/protocol/verify.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { - inspectLedger, - compareLedgers, - hashLedgerEntry, - hashLedgerCommit, - ledgerSignatureMessage, -} from "@ternent/ledger/protocol"; -import { caught, type Result } from "../common/errors.js"; -import * as schema from "./schema.js"; -import type { CommitRecord, Limits, Relationship, Snapshot, VerificationReport } from "./types.js"; - -export const hashEntrySubject = hashLedgerEntry; -export const hashCommitSubject = hashLedgerCommit; -export const signatureMessage = ledgerSignatureMessage; -export function ledgerLimits(limits: Limits) { - return { - maxBytes: limits.maxBytes, - maxDepth: limits.maxDepth, - maxEntries: limits.maxEntries, - maxCommits: limits.maxCommits, - maxMetadataBytes: limits.maxMetadataBytes, - maxPayloadBytes: limits.maxBytes, - }; -} -export async function inspectProtocol( - bytes: Uint8Array, - options: { limits?: Partial } = {}, -): Promise<{ - report: VerificationReport; - snapshot?: Snapshot; - untrustedHistory: readonly CommitRecord[]; -}> { - let report: VerificationReport = { - integrity: "invalid", - documentId: null, - head: null, - checkedCommits: 0, - checkedEntries: 0, - findings: [], - }; - let untrustedHistory: readonly CommitRecord[] = []; - try { - const limits = schema.limits(options.limits); - const history = await inspectLedger(bytes, { limits: ledgerLimits(limits) }); - report = history.report as VerificationReport; - untrustedHistory = history.untrustedHistory; - if (!history.snapshot) return { report, untrustedHistory }; - schema.snapshot(history.snapshot, limits); - return { report, snapshot: history.snapshot, untrustedHistory }; - } catch (cause) { - const finding = caught(cause, "SCHEMA_INVALID", "protocol"); - return { - report: { - ...report, - integrity: ["RESOURCE_LIMIT", "HOST_CONFIGURATION", "ENTRY_KIND_UNSUPPORTED"].includes( - finding.code, - ) - ? "unsupported" - : "invalid", - findings: [finding], - }, - untrustedHistory, - }; - } -} -export async function verifyDocument( - bytes: Uint8Array, - options?: { limits?: Partial }, -): Promise { - return (await inspectProtocol(bytes, options)).report; -} -export async function compareSnapshots( - a: Uint8Array, - b: Uint8Array, - options?: { limits?: Partial }, -): Promise> { - const left = await inspectProtocol(a, options), - right = await inspectProtocol(b, options); - if (!left.snapshot) return { ok: false, error: left.report.findings[0] }; - if (!right.snapshot) return { ok: false, error: right.report.findings[0] }; - return (await compareLedgers(a, b, { - limits: ledgerLimits(schema.limits(options?.limits)), - })) as Result; -} diff --git a/packages/concord/src/runtime.ts b/packages/concord/src/runtime.ts deleted file mode 100644 index 68ebe87..0000000 --- a/packages/concord/src/runtime.ts +++ /dev/null @@ -1,601 +0,0 @@ -import { createLedger, type LedgerAppendInput, type LedgerInstance } from "@ternent/ledger"; -import { caught, error, fail, ok, type Result, Fault } from "./common/errors.js"; -import { detached, freeze } from "./common/immutable.js"; -import { encodeJson } from "./protocol/json.js"; -import { inspectProtocol, ledgerLimits, compareSnapshots } from "./protocol/verify.js"; -import { - isAudienceId, - object, - limits as configureLimits, - ref, - declaration as frameworkDeclaration, - entrySubject, -} from "./protocol/schema.js"; -import { issueHistory } from "./protocol/history.js"; -import type { - AudienceId, - Json, - JsonObject, - CommitId, - DomainEvent, - Snapshot, - Limits, - EntrySubject, -} from "./protocol/types.js"; -import type { - ApplicationModel, - DocumentHandle, - HostOptions, - InspectionReport, - InspectionState, - ReadyState, - CommitReceipt, - DraftReceipt, -} from "./model/types.js"; -import { systemAuthors } from "./system/authoring.js"; -import type { - SystemProfile, - SystemReplay, - ApplicationIntent, - SystemIntent, -} from "./system/types.js"; -import { host, copyOptions, type Options } from "./runtime/host.js"; -import { accepted, checkRequirements, json, same } from "./runtime/validation.js"; -import { checkSystem } from "./runtime/system-output.js"; -import { fold } from "./runtime/model-replay.js"; -import type { IdentityCapability } from "@ternent/armour"; -type Evaluation = - | { inspection: InspectionReport; state: InspectionState } - | { - inspection: InspectionReport; - state: ReadyState; - snapshot: Snapshot; - system: SystemReplay; - }; -async function evaluate( - bytes: Uint8Array, - options: Options, - call: (fn: () => T) => T, -): Promise { - const protocol = await inspectProtocol(bytes, { limits: options.limits }); - const report: InspectionReport = { - verification: protocol.report, - system: "not-run", - application: "not-run", - otherRecipientsDecryptability: "unverified", - freshness: "unanchored", - requirements: [], - lockedEntries: null, - findings: [...protocol.report.findings], - history: protocol.untrustedHistory, - entries: null, - audiences: null, - }; - const inspect = (reason: InspectionState["reason"]): Evaluation => ({ - inspection: detached(report), - state: { status: "inspection", reason }, - }); - if (!protocol.snapshot) - return inspect(protocol.report.integrity === "invalid" ? "invalid" : "incompatible"); - const wire = detached(protocol.snapshot), - declaration = frameworkDeclaration(wire); - try { - host(options); - } catch (cause) { - report.findings = [caught(cause, "HOST_CONFIGURATION", "requirements")]; - return inspect("incompatible"); - } - const missing: InspectionReport["requirements"][number][] = []; - if (!options.system || !same(options.system.ref, declaration.system)) - missing.push({ kind: "system", ref: declaration.system }); - if (!options.model || !same(options.model.ref, declaration.model)) - missing.push({ kind: "model", ref: declaration.model }); - if (missing.length) { - report.requirements = missing; - report.findings = [error("REQUIREMENT_UNAVAILABLE", "requirements")]; - return inspect("incompatible"); - } - if (options.anchor) { - const relation = await compareSnapshots(bytes, options.anchor, { limits: options.limits }); - if (!relation.ok) { - report.findings = [error("ANCHOR_INVALID", "protocol")]; - return inspect("freshness"); - } - report.freshness = relation.value; - const code = - relation.value === "behind" - ? "STALE_HEAD" - : relation.value === "diverged" - ? "DIVERGED_HEAD" - : relation.value === "unrelated" - ? "DOCUMENT_MISMATCH" - : null; - if (code) { - report.findings = [error(code, "protocol")]; - return inspect("freshness"); - } - } - const lim = configureLimits(options.limits); - let system: SystemReplay; - try { - const result = await call(() => - options.system!.replay({ - history: issueHistory(wire), - reader: options.reader ?? options.signer, - limits: lim, - }), - ); - if (!result.ok) throw new Fault(result.error); - system = checkSystem(result.value, wire, lim); - if ( - (options.reader && !same(system.reader, options.reader.publicIdentity)) || - (!options.reader && options.signer && !same(system.reader, options.signer.publicIdentity)) || - (!options.reader && !options.signer && system.reader !== null) - ) - fail("SYSTEM_FAILED", "system"); - } catch (cause) { - const finding = caught(cause, "SYSTEM_FAILED", "system"); - report.findings = [finding]; - report.system = - finding.code === "UNSUPPORTED_SYSTEM_EVENT" || finding.code === "RESOURCE_LIMIT" - ? "unsupported" - : "invalid"; - return inspect(report.system === "unsupported" ? "incompatible" : "invalid"); - } - report.system = "valid"; - report.entries = system.entries; - report.audiences = system.audiences; - const lockedEntries = system.entries.filter((item) => item.status === "locked").length; - report.lockedEntries = lockedEntries; - if ((!system.reader || lockedEntries > 0) && !options.model!.reduceLocked) { - report.application = "locked"; - report.findings = [ - error(!system.reader ? "READ_ACCESS_REQUIRED" : "KEY_UNAVAILABLE", "system"), - ]; - return inspect("locked"); - } - try { - const projection = fold(options.model!, system, lim, call); - const coverage = lockedEntries > 0 ? "readable" : "complete"; - report.application = coverage === "complete" ? "valid" : "scoped"; - const signer = options.signer; - const canWrite = Boolean( - signer && - system.audiences.some((group) => - group.members.some( - (m) => same(m.identity, signer.publicIdentity) && m.capabilities.includes("write"), - ), - ), - ); - return { - inspection: detached(report), - snapshot: wire, - system, - state: freeze({ - status: "ready", - documentId: wire.documentId, - head: wire.head, - projection, - canWrite, - coverage, - lockedEntries, - }), - }; - } catch (cause) { - const finding = caught(cause, "MODEL_FAILED", "model"); - report.findings = [finding]; - report.application = - finding.code === "EVENT_UNSUPPORTED" || finding.code === "RESOURCE_LIMIT" - ? "unsupported" - : "invalid"; - return inspect(report.application === "unsupported" ? "incompatible" : "invalid"); - } -} -function preparedInputs( - subjects: readonly EntrySubject[], - parent: CommitId | null, - lim: Limits, -): LedgerAppendInput[] { - return subjects.map((subject) => { - entrySubject(subject, "", lim); - if (subject.parent !== parent) fail("SYSTEM_FAILED", "system"); - return { kind: subject.kind, nonce: subject.nonce, payload: subject.payload }; - }); -} -async function newLedger( - options: Options, - lim: Limits, - call: (fn: () => T) => T, -): Promise> { - return createLedger({ - initialProjection: null, - projector: () => null, - limits: ledgerLimits(lim), - signer: options.signer - ? { - publicIdentity: options.signer.publicIdentity, - sign: (message) => call(() => options.signer!.sign(message)), - } - : undefined, - }); -} -async function handle( - initial: Evaluation, - input: Uint8Array, - options: Options, -): Promise>> { - let current = initial, - callbacks = 0; - let bytes: Uint8Array = new Uint8Array(input); - let queue: Promise = Promise.resolve(); - let pendingDraft: { - baseHead: CommitId; - intents: readonly ApplicationIntent[]; - preview: Readonly; - } | null = null; - const call = (fn: () => T): T => { - callbacks++; - try { - return fn(); - } finally { - callbacks--; - } - }; - let active: LedgerInstance | null = null; - if ("snapshot" in initial) { - active = await newLedger(options, configureLimits(options.limits), call); - await active.load(initial.snapshot); - } - const serialized = (body: () => Promise> | Result): Promise> => { - if (callbacks) - return Promise.resolve({ ok: false, error: error("HOST_CONFIGURATION", "requirements") }); - const pending = queue.then(async () => { - try { - return await body(); - } catch (cause) { - return { ok: false as const, error: caught(cause, "MODEL_FAILED", "model") }; - } - }); - queue = pending.then( - () => undefined, - () => undefined, - ); - return pending; - }; - function authoring(): Extract { - if (current.state.status !== "ready") fail("INSPECTION_ONLY", "author"); - if (!options.signer) fail("READ_ONLY_RUNTIME", "author"); - return current as Extract; - } - function writable(): Extract { - const ready = authoring(); - if (!ready.state.canWrite) fail("CAPABILITY_DENIED", "system"); - return ready; - } - async function commitIntents( - ready: Extract, - intents: readonly (ApplicationIntent | SystemIntent)[], - lim: Limits, - metadata: JsonObject | null = null, - ): Promise> { - const signer = options.signer!; - let prepared: Result; - try { - prepared = await call(() => - options.system!.prepare({ - history: issueHistory(ready.snapshot), - current: ready.system, - signer, - intents: freeze(intents), - limits: lim, - }), - ); - } catch { - fail("SYSTEM_FAILED", "system"); - } - if (!prepared.ok) throw new Fault(prepared.error); - if ( - prepared.value.length !== intents.length || - prepared.value.some((entry, index) => { - const intent = intents[index]; - return intent.kind === "application" - ? entry.kind !== "application" || entry.payload.audience !== intent.audience - : entry.kind !== "system" || entry.payload.type !== `system.${intent.kind}`; - }) - ) - fail("SYSTEM_FAILED", "system"); - if (!active) fail("INSPECTION_ONLY", "author"); - const candidate = await newLedger(options, lim, call); - await candidate.load(await active.export()); - await candidate.appendMany( - preparedInputs(json(prepared.value, lim, "SYSTEM_FAILED"), ready.snapshot.head, lim), - ); - await candidate.commit(metadata === null ? {} : { metadata }); - const wire = await candidate.export(); - const nextBytes = encodeJson(wire, lim.maxDepth), - next = await evaluate(nextBytes, options, call); - if (next.state.status !== "ready") return { ok: false, error: next.inspection.findings[0] }; - current = next; - active = candidate; - bytes = nextBytes; - pendingDraft = null; - return ok({ - status: "committed", - head: wire.head, - entryIds: wire.commits.at(-1)!.subject.entryIds, - }); - } - const document: DocumentHandle> = { - state: () => detached(current.state), - inspect: () => detached(current.inspection), - export: () => new Uint8Array(bytes), - verify: async () => - detached( - active - ? ((await active.verify()) as InspectionReport["verification"]) - : (await inspectProtocol(new Uint8Array(bytes), { limits: options.limits })).report, - ), - async replay() { - if (current.state.status !== "ready") - return { - ok: false, - error: current.inspection.findings[0] ?? error("INSPECTION_ONLY", "author"), - }; - const result = await evaluate(new Uint8Array(bytes), options, call); - return result.state.status === "ready" - ? ok( - detached({ - projection: result.state.projection, - coverage: result.state.coverage, - lockedEntries: result.state.lockedEntries, - }), - ) - : { ok: false, error: result.inspection.findings[0] }; - }, - dispatch(command, input) { - let copied: Json | undefined, copyFailure: ReturnType | undefined; - try { - copied = json(input, configureLimits(options.limits), "COMMAND_INVALID", "author"); - } catch (cause) { - copyFailure = caught(cause, "COMMAND_INVALID", "author"); - } - return serialized(async () => { - const ready = writable(), - model = options.model!, - lim = configureLimits(options.limits); - if (!Object.hasOwn(model.commands, command)) fail("COMMAND_UNSUPPORTED", "author"); - if (copyFailure) return { ok: false, error: copyFailure }; - const registration = model.commands[command]; - const actor = options.signer!.publicIdentity; - const validated = json( - accepted( - call(() => registration.validate(copied)), - "COMMAND_INVALID", - ), - lim, - "COMMAND_INVALID", - "author", - ); - const audience: AudienceId = call(() => - registration.audience ? registration.audience(validated) : "document", - ); - if (!isAudienceId(audience)) fail("COMMAND_INVALID", "author"); - const group = ready.system.audiences.find((group) => group.audience === audience); - const member = group?.members.find((m) => same(m.identity, actor)); - if (!group || !member?.capabilities.includes("write")) fail("CAPABILITY_DENIED", "system"); - const facts = detached({ - audience, - actor, - capabilities: member.capabilities, - members: group.members, - }); - const events = accepted( - call(() => - registration.decide( - validated, - pendingDraft ? pendingDraft.preview : ready.state.projection, - { - facts, - }, - ), - ), - "COMMAND_REJECTED", - ); - if (!Array.isArray(events)) fail("MODEL_FAILED", "model"); - if (!events.length) fail("NO_EVENTS", "author"); - if ( - options.mode === "draft" && - (ready.snapshot.entries.length + (pendingDraft?.intents.length ?? 0) + events.length > - lim.maxEntries || - ready.snapshot.commits.length + 1 > lim.maxCommits) - ) - fail("RESOURCE_LIMIT", "author"); - const intents: ApplicationIntent[] = events.map((input) => { - const event = json( - accepted( - call(() => model.validateEvent(input)), - "EVENT_INVALID", - ), - lim, - "EVENT_INVALID", - ); - if (!object(event) || Object.keys(event).length !== 3 || !Object.hasOwn(event, "data")) - fail("EVENT_INVALID", "model"); - try { - ref({ id: event.type, version: event.version }, ""); - } catch { - fail("EVENT_INVALID", "model"); - } - const eventAudience = call(() => (model.audience ? model.audience(event) : "document")); - if (!isAudienceId(eventAudience) || eventAudience !== audience) - fail("EVENT_INVALID", "model"); - const required = call(() => model.requirements(event)); - checkRequirements(required); - if (!required.every((capability) => member.capabilities.includes(capability))) - fail("CAPABILITY_DENIED", "system"); - return detached({ - kind: "application" as const, - event, - required, - audience, - }); - }); - if (options.mode === "draft") { - const staged = json([...(pendingDraft?.intents ?? []), ...intents], lim, "EVENT_INVALID"); - let preview = pendingDraft ? pendingDraft.preview : ready.state.projection; - for (const intent of intents) { - preview = json( - accepted( - call(() => model.reduce(preview, intent.event, facts)), - "MODEL_TRANSITION_INVALID", - ), - lim, - "MODEL_TRANSITION_INVALID", - ); - } - pendingDraft = { baseHead: ready.snapshot.head, intents: staged, preview }; - return ok({ - status: "staged" as const, - baseHead: ready.snapshot.head, - entryCount: staged.length, - }); - } - return commitIntents(ready, intents, lim); - }); - }, - commit(metadata) { - let copied: JsonObject | null = null, - copyFailure: ReturnType | undefined; - try { - const lim = configureLimits(options.limits); - if (metadata !== undefined) { - copied = json(metadata, lim, "SCHEMA_INVALID", "author"); - if (!object(copied)) fail("SCHEMA_INVALID", "author"); - if (encodeJson(copied, lim.maxDepth).length > lim.maxMetadataBytes) - fail("RESOURCE_LIMIT", "author"); - } - } catch (cause) { - copyFailure = caught(cause, "SCHEMA_INVALID", "author"); - } - return serialized(() => { - const ready = writable(); - if (options.mode !== "draft" || !pendingDraft) fail("NO_DRAFT", "author"); - if (copyFailure) return { ok: false, error: copyFailure }; - if (pendingDraft.baseHead !== ready.snapshot.head) fail("HEAD_CONFLICT", "author"); - return commitIntents(ready, pendingDraft.intents, configureLimits(options.limits), copied); - }); - }, - discardDraft: () => - serialized(() => { - writable(); - pendingDraft = null; - return ok(undefined); - }), - draft: () => - pendingDraft - ? detached({ - baseHead: pendingDraft.baseHead, - entryCount: pendingDraft.intents.length, - preview: pendingDraft.preview, - }) - : null, - }; - systemAuthors.set(document, (kind, input) => { - let intent: SystemIntent | undefined; - let copyFailure: ReturnType | undefined; - try { - const copied = json(input, configureLimits(options.limits), "SYSTEM_EVENT_INVALID", "system"); - if ( - !copied || - typeof copied !== "object" || - Array.isArray(copied) || - Object.hasOwn(copied, "kind") - ) - fail("SYSTEM_EVENT_INVALID", "system"); - intent = { - ...copied, - ...(kind !== "group.create" && !Object.hasOwn(copied, "audience") - ? { audience: "document" } - : {}), - kind, - } as SystemIntent; - } catch (cause) { - copyFailure = caught(cause, "SYSTEM_EVENT_INVALID", "system"); - } - return serialized(() => { - const ready = authoring(); - if (pendingDraft) fail("DRAFT_PENDING", "author"); - if (options.mode === "draft") fail("HOST_CONFIGURATION", "requirements"); - if (copyFailure) return { ok: false, error: copyFailure }; - return commitIntents(ready, [intent!], configureLimits(options.limits)); - }); - }); - return document; -} -export async function createDocument< - S extends Json, - C extends Record, - E extends DomainEvent, ->(input: { - model: ApplicationModel; - system: SystemProfile; - identity: IdentityCapability; - mode?: "immediate" | "draft"; - limits?: Partial; -}): Promise>> { - try { - const options = copyOptions({ ...input, signer: input.identity } as unknown as Options), - lim = configureLimits(options.limits); - host(options); - if ( - !options.model || - !options.system || - !options.signer || - !same(options.system.ref, { id: "concord.standard", version: 1 }) - ) - fail("HOST_CONFIGURATION", "requirements"); - let bootstrap: Result; - try { - bootstrap = await options.system.bootstrap({ signer: options.signer, limits: lim }); - } catch { - fail("SYSTEM_FAILED", "system"); - } - if (!bootstrap.ok) return bootstrap; - const ledger = await newLedger(options, lim, (fn) => fn()); - await ledger.create({ - metadata: { concord: { model: options.model.ref, system: options.system.ref } }, - entries: preparedInputs([json(bootstrap.value, lim, "SYSTEM_FAILED")], null, lim), - }); - const wire = await ledger.export(), - bytes = encodeJson(wire, lim.maxDepth), - evaluated = await evaluate(bytes, options, (fn) => fn()); - if (evaluated.state.status !== "ready") - return { ok: false, error: evaluated.inspection.findings[0] }; - return ok((await handle(evaluated, bytes, options)) as unknown as DocumentHandle); - } catch (cause) { - return { ok: false, error: caught(cause, "HOST_CONFIGURATION", "requirements") }; - } -} -export async function openDocument< - S extends Json = never, - C extends Record = Record, - E extends DomainEvent = DomainEvent, ->(input: HostOptions & { bytes: Uint8Array }): Promise> { - const bytes = new Uint8Array(input.bytes); - let options: Options; - try { - options = copyOptions(input as unknown as Options); - } catch { - options = { limits: input.limits, invalidHost: true }; - } - const evaluated = await evaluate(bytes, options, (fn) => fn()); - if ("snapshot" in evaluated) { - const lim = configureLimits(options.limits); - return (await handle( - evaluated, - encodeJson(evaluated.snapshot, lim.maxDepth), - options, - )) as unknown as DocumentHandle; - } - return (await handle(evaluated, bytes, options)) as unknown as DocumentHandle; -} diff --git a/packages/concord/src/runtime/host.ts b/packages/concord/src/runtime/host.ts deleted file mode 100644 index 59c49ec..0000000 --- a/packages/concord/src/runtime/host.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { validatePublicIdentity } from "@ternent/identity"; -import { fail } from "../common/errors.js"; -import { detached } from "../common/immutable.js"; -import { limits as configureLimits, ref } from "../protocol/schema.js"; -import type { Json, DomainEvent } from "../protocol/types.js"; -import type { HostOptions } from "../model/types.js"; -import { same } from "./validation.js"; - -export type Options = HostOptions, DomainEvent> & { invalidHost?: true }; - -export function host(options: Options): void { - if (options.invalidHost) fail("HOST_CONFIGURATION", "requirements"); - if (options.mode !== undefined && options.mode !== "immediate" && options.mode !== "draft") - fail("HOST_CONFIGURATION", "requirements"); - if (options.model) { - const model = options.model; - try { - ref(model.ref, ""); - } catch { - fail("HOST_CONFIGURATION", "requirements"); - } - if ( - !model.commands || - typeof model.commands !== "object" || - ![ - model.initial, - model.validateEvent, - model.requirements, - model.reduce, - ...Object.values(model.commands).flatMap((c) => [c?.validate, c?.decide]), - ].every((fn) => typeof fn === "function") || - [ - model.audience, - model.reduceLocked, - ...Object.values(model.commands).map((c) => c?.audience), - ].some((fn) => fn !== undefined && typeof fn !== "function") - ) - fail("HOST_CONFIGURATION", "requirements"); - } - if (options.system) { - try { - ref(options.system.ref, ""); - } catch { - fail("HOST_CONFIGURATION", "requirements"); - } - if ( - ![options.system.bootstrap, options.system.replay, options.system.prepare].every( - (fn) => typeof fn === "function", - ) - ) - fail("HOST_CONFIGURATION", "requirements"); - } - for (const capability of [options.signer, options.reader]) - if ( - capability && - (!validatePublicIdentity(capability.publicIdentity).ok || - typeof capability.decryptAge !== "function") - ) - fail("HOST_CONFIGURATION", "requirements"); - if (options.signer && typeof options.signer.sign !== "function") - fail("HOST_CONFIGURATION", "requirements"); - if ( - options.signer && - options.reader && - !same(options.signer.publicIdentity, options.reader.publicIdentity) - ) - fail("IDENTITY_MISMATCH", "requirements"); -} -export function copyOptions(input: Options): Options { - configureLimits(input.limits); - const model = input.model; - return { - ...input, - limits: input.limits ? { ...input.limits } : undefined, - anchor: input.anchor ? new Uint8Array(input.anchor) : undefined, - model: model - ? { - ...model, - ref: detached(model.ref), - commands: Object.fromEntries( - Object.entries(model.commands ?? {}).map(([key, value]) => [key, { ...value }]), - ), - } - : undefined, - system: input.system ? { ...input.system, ref: detached(input.system.ref) } : undefined, - }; -} diff --git a/packages/concord/src/runtime/model-replay.ts b/packages/concord/src/runtime/model-replay.ts deleted file mode 100644 index 4859fa1..0000000 --- a/packages/concord/src/runtime/model-replay.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { fail } from "../common/errors.js"; -import { isAudienceId } from "../protocol/schema.js"; -import type { Json, DomainEvent, Limits } from "../protocol/types.js"; -import type { ApplicationModel } from "../model/types.js"; -import type { SystemReplay } from "../system/types.js"; -import { accepted, checkRequirements, json } from "./validation.js"; - -type AnyModel = ApplicationModel, DomainEvent>; - -export function fold( - model: AnyModel, - system: SystemReplay, - lim: Limits, - call: (fn: () => T) => T, -): Json { - let projection = json( - call(() => model.initial()), - lim, - "MODEL_TRANSITION_INVALID", - ); - for (const item of system.entries) { - if (item.status === "locked") { - if (!model.reduceLocked) fail("KEY_UNAVAILABLE", "system"); - projection = json( - accepted( - call(() => - model.reduceLocked!( - projection, - { audience: item.audience, epoch: item.epoch }, - item.facts, - ), - ), - "MODEL_TRANSITION_INVALID", - ), - lim, - "MODEL_TRANSITION_INVALID", - ); - continue; - } - const event = json( - accepted( - call(() => model.validateEvent(item.event)), - "EVENT_INVALID", - ), - lim, - "EVENT_INVALID", - ); - const audience = call(() => (model.audience ? model.audience(event) : "document")); - if (!isAudienceId(audience) || audience !== item.facts.audience) fail("EVENT_INVALID", "model"); - const required = call(() => model.requirements(event)); - checkRequirements(required); - if ( - !item.facts.capabilities.includes("write") || - !required.every((c) => item.facts.capabilities.includes(c)) - ) - fail("CAPABILITY_DENIED", "system"); - projection = json( - accepted( - call(() => model.reduce(projection, event, item.facts)), - "MODEL_TRANSITION_INVALID", - ), - lim, - "MODEL_TRANSITION_INVALID", - ); - } - return projection; -} diff --git a/packages/concord/src/runtime/system-output.ts b/packages/concord/src/runtime/system-output.ts deleted file mode 100644 index 4a26d82..0000000 --- a/packages/concord/src/runtime/system-output.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { validateAgeRecipient, validatePublicIdentity } from "@ternent/identity"; -import { fail } from "../common/errors.js"; -import { freeze } from "../common/immutable.js"; -import { isAudienceId, logicalEntry } from "../protocol/schema.js"; -import type { Snapshot, Limits, PublicIdentity } from "../protocol/types.js"; -import type { Capability, Member } from "../model/types.js"; -import type { SystemReplay } from "../system/types.js"; -import { capabilities, json, same } from "./validation.js"; - -export function checkSystem(output: SystemReplay, wire: Snapshot, lim: Limits): SystemReplay { - const application = wire.entries - .map(logicalEntry) - .filter((e) => e.subject.kind === "application"); - if ( - !output || - !output.session || - typeof output.session !== "object" || - !Array.isArray(output.entryFacts) || - !Array.isArray(output.entries) || - !Array.isArray(output.audiences) || - output.entryFacts.length !== wire.entries.length || - output.entries.length !== application.length - ) - fail("SYSTEM_FAILED", "system"); - // Repeated facts expand with history; bound each value, not their aggregate encoding. - const copy = (value: T): T => json(value, lim, "SYSTEM_FAILED", "system"); - const entryFacts = output.entryFacts.map(copy); - const entries = output.entries.map(copy); - const audiences = output.audiences.map(copy); - const reader = copy(output.reader); - const exact = (value: unknown, keys: readonly string[]) => - value !== null && - typeof value === "object" && - !Array.isArray(value) && - Object.keys(value).length === keys.length && - keys.every((key) => Object.hasOwn(value, key)); - const identities = new Map(); - const validIdentity = (value: PublicIdentity): boolean => { - if (!exact(value, ["version", "algorithm", "publicKey", "id"])) return false; - const known = identities.get(value.id); - if (known) return same(known, value); - if (!validatePublicIdentity(value).ok) return false; - identities.set(value.id, value); - return true; - }; - const validCapabilities = (values: readonly Capability[], read: boolean): boolean => - Array.isArray(values) && - (!read || values.includes("read")) && - values.every( - (value: Capability, i: number) => - capabilities.includes(value) && - (i === 0 || capabilities.indexOf(values[i - 1]) < capabilities.indexOf(value)), - ); - const validMembers = (values: readonly Member[]): boolean => - Array.isArray(values) && - values.every( - (member: Member, i: number) => - exact(member, ["identity", "capabilities"]) && - validIdentity(member.identity) && - validCapabilities(member.capabilities, true) && - (i === 0 || values[i - 1].identity.id < member.identity.id), - ); - const recipients = new Set(); - const validRecipient = (value: string): boolean => { - if (typeof value !== "string") return false; - if (recipients.has(value)) return true; - if (!validateAgeRecipient(value).ok) return false; - recipients.add(value); - return true; - }; - if (reader !== null && !validIdentity(reader)) fail("SYSTEM_FAILED", "system"); - if ( - !audiences.some((group) => group.audience === "document") || - audiences.some( - (group, i) => - !exact(group, ["audience", "members", "epochs"]) || - !isAudienceId(group.audience) || - !validMembers(group.members) || - !Array.isArray(group.epochs) || - group.epochs.length === 0 || - !group.epochs.every( - (record: { epoch: number; recipient: string }, index: number) => - exact(record, ["epoch", "recipient"]) && - record.epoch === index && - validRecipient(record.recipient), - ) || - (i > 0 && audiences[i - 1].audience >= group.audience), - ) - ) - fail("SYSTEM_FAILED", "system"); - const audienceIds = new Set(audiences.map((group) => group.audience)); - let index = 0; - for (const commit of wire.commits) - for (const entryId of commit.subject.entryIds) { - const item = entryFacts[index++]; - if ( - !item || - !exact(item, ["entryId", "facts"]) || - !exact(item.facts, ["actor", "audience", "capabilities", "members"]) || - item.entryId !== entryId || - !same(item.facts.actor, commit.subject.signer) || - !audienceIds.has(item.facts.audience) || - !validMembers(item.facts.members) || - !validCapabilities(item.facts.capabilities, false) - ) - fail("SYSTEM_FAILED", "system"); - } - const facts = new Map(entryFacts.map((item) => [item.entryId, item.facts])); - for (let i = 0; i < application.length; i++) { - const item = entries[i]; - const subject = application[i].subject; - if (subject.kind !== "application") fail("SYSTEM_FAILED", "system"); - const envelope = subject.payload; - if ( - !item || - !exact( - item, - item.status === "readable" - ? ["status", "entryId", "event", "facts"] - : ["status", "entryId", "audience", "epoch", "facts"], - ) || - item.entryId !== application[i].id || - !same(item.facts, facts.get(application[i].id)) || - item.facts.audience !== envelope.audience || - (item.status !== "readable" && item.status !== "locked") || - (item.status === "locked" && - (item.audience !== envelope.audience || - item.epoch !== envelope.epoch || - Object.hasOwn(item, "event"))) - ) - fail("SYSTEM_FAILED", "system"); - } - return freeze({ entryFacts, entries, audiences, reader, session: output.session }); -} diff --git a/packages/concord/src/runtime/validation.ts b/packages/concord/src/runtime/validation.ts deleted file mode 100644 index a2fa0f6..0000000 --- a/packages/concord/src/runtime/validation.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { error, fail, Fault, type Result, type ErrorCode } from "../common/errors.js"; -import { freeze } from "../common/immutable.js"; -import { encodeJson, parseJson, text } from "../protocol/json.js"; -import type { Limits } from "../protocol/types.js"; -import type { Capability, ModelIssue } from "../model/types.js"; - -export const same = (a: unknown, b: unknown) => - text.decode(encodeJson(a)) === text.decode(encodeJson(b)); -export const capabilities: Capability[] = ["read", "write", "grant", "administer"]; -export function checkRequirements(values: readonly Capability[]): void { - if ( - !Array.isArray(values) || - new Set(values).size !== values.length || - !values.every((v) => capabilities.includes(v)) - ) - fail("MODEL_FAILED", "model"); -} - -export function accepted(result: Result, code: ErrorCode): T { - if (!result || typeof result !== "object" || typeof result.ok !== "boolean") - fail("MODEL_FAILED", "model"); - if (!result.ok) { - const outer = - code === "EVENT_INVALID" && result.error.code === "EVENT_UNSUPPORTED" - ? "EVENT_UNSUPPORTED" - : code; - const finding = error( - outer, - outer.startsWith("COMMAND") ? "author" : "model", - result.error.path, - ); - finding.details = { modelCode: result.error.code }; - throw new Fault(finding); - } - return result.value; -} -export function json( - value: T, - lim: Limits, - code: ErrorCode, - phase: "model" | "author" | "system" = "model", -): T { - try { - return freeze(parseJson(encodeJson(value, lim.maxDepth), lim.maxDepth, lim.maxBytes)) as T; - } catch (cause) { - if (cause instanceof Fault && cause.finding.code === "RESOURCE_LIMIT") throw cause; - fail(code, phase); - } -} diff --git a/packages/concord/src/system/audience.ts b/packages/concord/src/system/audience.ts deleted file mode 100644 index 03bbd65..0000000 --- a/packages/concord/src/system/audience.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { - ageRecipientFromPublicIdentity, - ageRecipientFromSecret, - decodeBase64Url, - encodeBase64Url, -} from "@ternent/identity"; -import { encryptAge, type ReaderCapability } from "@ternent/armour"; -import { fail } from "../common/errors.js"; -import { encodeJson, parseJson, text } from "../protocol/json.js"; -import { object } from "../protocol/schema.js"; -import type { - AudienceId, - EntrySubject, - JsonObject, - Limits, - PublicIdentity, -} from "../protocol/types.js"; - -type ContextError = "SYSTEM_EVENT_INVALID" | "KEY_WRAP_INVALID" | "EVENT_CONTEXT_INVALID"; -type EntryContext = Pick; - -export const equal = (a: unknown, b: unknown) => - text.decode(encodeJson(a)) === text.decode(encodeJson(b)); - -export function fields( - value: unknown, - keys: string[], - code: ContextError, -): asserts value is JsonObject { - if ( - !object(value) || - Object.keys(value).length !== keys.length || - keys.some((key) => !Object.hasOwn(value, key)) - ) - fail(code, "system"); -} - -export function unbase( - value: unknown, - lim: Limits, - code: "KEY_WRAP_INVALID" | "EVENT_CONTEXT_INVALID", -): Uint8Array { - if (typeof value !== "string" || Math.floor((value.length * 6) / 8) > lim.maxCiphertextBytes) - fail(code, "system"); - const result = decodeBase64Url(value); - if (!result.ok || result.value.length === 0) fail(code, "system"); - return result.value; -} - -export function plaintext( - bytes: Uint8Array, - lim: Limits, - code: "KEY_WRAP_INVALID" | "EVENT_CONTEXT_INVALID", -): JsonObject { - try { - const parsed = parseJson(bytes, lim.maxDepth, lim.maxBytes); - if (!object(parsed)) fail(code, "system"); - const canonical = encodeJson(parsed, lim.maxDepth); - if (canonical.length !== bytes.length || !canonical.every((byte, i) => byte === bytes[i])) - fail(code, "system"); - return parsed as JsonObject; - } catch { - fail(code, "system"); - } -} - -export function groupSecret(): Uint8Array { - const secret = crypto.getRandomValues(new Uint8Array(32)); - secret[0] &= 248; - secret[31] = (secret[31] & 127) | 64; - return secret; -} - -export async function encrypt(recipient: string, body: JsonObject, lim: Limits): Promise { - const encrypted = await encryptAge({ - recipients: [recipient], - plaintext: encodeJson(body, lim.maxDepth), - }); - if (!encrypted.ok) fail("ENCRYPTION_FAILED", "author"); - if (encrypted.value.length > lim.maxCiphertextBytes) fail("RESOURCE_LIMIT"); - return encodeBase64Url(encrypted.value); -} - -export function wrapKey( - context: EntryContext, - identity: PublicIdentity, - epoch: number, - recipient: string, - secret: Uint8Array, - lim: Limits, - audience: AudienceId = "document", -): Promise { - const target = ageRecipientFromPublicIdentity(identity); - if (!target.ok) fail("IDENTITY_MISMATCH", "requirements"); - return encrypt( - target.value, - { - context: "concord.audience-key/1", - parent: context.parent, - nonce: context.nonce, - audience, - epoch, - identityId: identity.id, - recipient, - secret: encodeBase64Url(secret), - }, - lim, - ); -} - -export async function unwrapKey( - context: EntryContext, - reader: ReaderCapability, - epoch: number, - recipient: string, - ciphertext: string, - lim: Limits, - audience: AudienceId = "document", -): Promise { - const decrypted = await reader.decryptAge(unbase(ciphertext, lim, "KEY_WRAP_INVALID")); - if (!decrypted.ok) fail("KEY_WRAP_INVALID", "system"); - const key = plaintext(decrypted.value, lim, "KEY_WRAP_INVALID"); - fields( - key, - ["context", "parent", "nonce", "audience", "epoch", "identityId", "recipient", "secret"], - "KEY_WRAP_INVALID", - ); - if ( - key.context !== "concord.audience-key/1" || - key.parent !== context.parent || - key.nonce !== context.nonce || - key.audience !== audience || - key.epoch !== epoch || - key.identityId !== reader.publicIdentity.id || - key.recipient !== recipient - ) - fail("KEY_WRAP_INVALID", "system"); - - const secret = unbase(key.secret, lim, "KEY_WRAP_INVALID"); - if ( - secret.length !== 32 || - (secret[0] & 7) !== 0 || - (secret[31] & 192) !== 64 || - ageRecipientFromSecret(secret) !== recipient - ) { - secret.fill(0); - fail("KEY_WRAP_INVALID", "system"); - } - return secret; -} diff --git a/packages/concord/src/system/authoring.ts b/packages/concord/src/system/authoring.ts deleted file mode 100644 index ad480ce..0000000 --- a/packages/concord/src/system/authoring.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { caught, error, type Result } from "../common/errors.js"; -import { nonce } from "../common/random.js"; -import type { Capability, CommitReceipt, DocumentHandle } from "../model/types.js"; -import type { AudienceId, GroupId, Json, PublicIdentity } from "../protocol/types.js"; -import type { SystemIntent } from "./types.js"; - -type Author = (kind: SystemIntent["kind"], input: unknown) => Promise>; -export const systemAuthors = new WeakMap(); - -function author(handle: object, kind: SystemIntent["kind"], input: unknown) { - const write = systemAuthors.get(handle); - return write - ? write(kind, input) - : Promise.resolve({ ok: false as const, error: error("HOST_CONFIGURATION", "requirements") }); -} - -export function setMember>( - handle: DocumentHandle, - input: { audience?: AudienceId; identity: PublicIdentity; capabilities: readonly Capability[] }, -): Promise> { - return author(handle, "member.set", input); -} - -export function removeMember>( - handle: DocumentHandle, - input: { audience?: AudienceId; identityId: string }, -): Promise> { - return author(handle, "member.remove", input); -} - -export async function createGroup>( - handle: DocumentHandle, -): Promise> { - try { - const audience: GroupId = `group:${nonce()}`; - const result = await author(handle, "group.create", { audience }); - return result.ok ? { ok: true, value: { ...result.value, audience } } : result; - } catch (cause) { - return { ok: false, error: caught(cause, "SYSTEM_FAILED", "author") }; - } -} diff --git a/packages/concord/src/system/index.ts b/packages/concord/src/system/index.ts deleted file mode 100644 index 85f2904..0000000 --- a/packages/concord/src/system/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { createStandardSystemProfile } from "./standard.js"; -export { createGroup, setMember, removeMember } from "./authoring.js"; -export type * from "./types.js"; -export type { Capability, SystemFacts } from "../model/types.js"; diff --git a/packages/concord/src/system/membership.ts b/packages/concord/src/system/membership.ts deleted file mode 100644 index 2a38e2f..0000000 --- a/packages/concord/src/system/membership.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { validatePublicIdentity } from "@ternent/identity"; -import { fail } from "../common/errors.js"; -import type { Capability, Member } from "../model/types.js"; -import type { PublicIdentity } from "../protocol/types.js"; -import { equal } from "./audience.js"; - -export const allCapabilities: readonly Capability[] = ["read", "write", "grant", "administer"]; - -export function identity(value: unknown): PublicIdentity { - const result = validatePublicIdentity(value); - if (!result.ok) fail("SYSTEM_EVENT_INVALID", "system"); - return result.value; -} - -export function identityId(value: unknown): string { - if (typeof value !== "string" || !/^identity:[0-9a-f]{64}$/.test(value)) - fail("SYSTEM_EVENT_INVALID", "system"); - return value; -} - -export function capabilitySet(value: unknown, wire: boolean): Capability[] { - if (!Array.isArray(value)) fail("SYSTEM_EVENT_INVALID", "system"); - const capabilities = allCapabilities.filter((capability) => value.includes(capability)); - if ( - capabilities.length !== value.length || - !capabilities.includes("read") || - (wire && !capabilities.every((capability, index) => value[index] === capability)) - ) - fail("SYSTEM_EVENT_INVALID", "system"); - return capabilities; -} - -export function orderedMembers(members: ReadonlyMap): Member[] { - return [...members.keys()].sort().map((id) => members.get(id)!); -} - -export function capabilitiesOf(members: ReadonlyMap, actor: PublicIdentity) { - const member = members.get(actor.id); - return member && equal(member.identity, actor) ? member.capabilities : []; -} - -function anotherAdministrator(members: ReadonlyMap, target: string): boolean { - return [...members.values()].some( - (member) => member.identity.id !== target && member.capabilities.includes("administer"), - ); -} - -export function checkSet( - members: ReadonlyMap, - actor: PublicIdentity, - target: PublicIdentity, - capabilities: readonly Capability[], -): boolean { - const authority = capabilitiesOf(members, actor); - const existing = members.get(target.id); - if ( - !authority.includes("administer") && - (!authority.includes("grant") || - capabilities.some( - (capability) => - (capability !== "read" && capability !== "write") || !authority.includes(capability), - ) || - existing?.capabilities.some( - (capability) => capability === "grant" || capability === "administer", - )) - ) - fail("CAPABILITY_DENIED", "system"); - - if (!existing) return true; - if (!equal(existing.identity, target)) fail("SYSTEM_EVENT_INVALID", "system"); - if (equal(existing.capabilities, capabilities)) fail("SYSTEM_NO_CHANGE", "system"); - if ( - existing.capabilities.includes("administer") && - !capabilities.includes("administer") && - !anotherAdministrator(members, target.id) - ) - fail("LAST_ADMINISTRATOR", "system"); - return false; -} - -export function checkRemoval( - members: ReadonlyMap, - actor: PublicIdentity, - target: string, -): void { - if (!capabilitiesOf(members, actor).includes("administer")) fail("CAPABILITY_DENIED", "system"); - if (!members.has(target)) fail("SYSTEM_EVENT_INVALID", "system"); - if (!anotherAdministrator(members, target)) fail("LAST_ADMINISTRATOR", "system"); - if (actor.id === target) fail("SYSTEM_EVENT_INVALID", "system"); -} diff --git a/packages/concord/src/system/standard.ts b/packages/concord/src/system/standard.ts deleted file mode 100644 index b77e3a4..0000000 --- a/packages/concord/src/system/standard.ts +++ /dev/null @@ -1,607 +0,0 @@ -import { ageRecipientFromSecret, validateAgeRecipient } from "@ternent/identity"; -import { decryptAgeWithSecret } from "@ternent/armour"; -import { caught, fail, ok } from "../common/errors.js"; -import { detached, freeze } from "../common/immutable.js"; -import { nonce } from "../common/random.js"; -import { isAudienceId } from "../protocol/schema.js"; -import { isVerifiedHistory } from "../protocol/history.js"; -import type { - AudienceId, - CommitId, - DomainEvent, - EntryId, - EntrySubject, - JsonObject, - Limits, -} from "../protocol/types.js"; -import type { Member, SystemFacts } from "../model/types.js"; -import type { SystemProfile, SystemReplay } from "./types.js"; -import { - encrypt, - equal, - fields, - groupSecret, - plaintext, - unbase, - unwrapKey, - wrapKey, -} from "./audience.js"; -import { - allCapabilities, - capabilitiesOf, - capabilitySet, - checkRemoval, - checkSet, - identity, - identityId, - orderedMembers, -} from "./membership.js"; - -type Location = { entryId: EntryId; commitId: CommitId; path: string }; -type SystemEntry = Extract; -type ApplicationEntry = Extract; -type Group = { members: Map; recipients: string[] }; -const keyId = (audience: AudienceId, epoch: number) => `${audience}/${epoch}`; -function audienceId(value: unknown): AudienceId { - if (!isAudienceId(value)) fail("SYSTEM_EVENT_INVALID", "system"); - return value; -} -type Wrap = { - audience: AudienceId; - identityId: string; - epoch: number; - ciphertext: string; - subject: SystemEntry; - location: Location; -}; -type Session = { - head: CommitId; - readerId: string | null; - groups: Map; - secrets: Map; -}; - -function recipient(value: unknown): string { - if (typeof value !== "string" || !validateAgeRecipient(value).ok) - fail("SYSTEM_EVENT_INVALID", "system"); - return value; -} - -function epochNumber(value: unknown): number { - if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) - fail("SYSTEM_EVENT_INVALID", "system"); - return value; -} - -function ciphertext(value: unknown, lim: Limits): string { - if (typeof value !== "string") fail("SYSTEM_EVENT_INVALID", "system"); - unbase(value, lim, "KEY_WRAP_INVALID"); - return value; -} - -function recipientWraps( - value: unknown, - epoch: number, - subject: SystemEntry, - location: Location, - lim: Limits, - audience: AudienceId, -): Wrap[] { - if (!Array.isArray(value)) fail("SYSTEM_EVENT_INVALID", "system"); - const wraps = value.map((record: unknown, index) => { - fields(record, ["identityId", "ciphertext"], "SYSTEM_EVENT_INVALID"); - return { - audience, - identityId: identityId(record.identityId), - ciphertext: ciphertext(record.ciphertext, lim), - epoch, - subject, - location: { ...location, path: `${location.path}/data/wraps/${index}` }, - }; - }); - if (wraps.some((wrap, i) => i > 0 && wraps[i - 1].identityId >= wrap.identityId)) - fail("SYSTEM_EVENT_INVALID", "system"); - return wraps; -} - -function historicalWraps( - value: unknown, - target: string, - subject: SystemEntry, - location: Location, - lim: Limits, - audience: AudienceId, -): Wrap[] { - if (!Array.isArray(value)) fail("SYSTEM_EVENT_INVALID", "system"); - const wraps = value.map((record: unknown, index) => { - fields(record, ["epoch", "ciphertext"], "SYSTEM_EVENT_INVALID"); - return { - audience, - identityId: target, - epoch: epochNumber(record.epoch), - ciphertext: ciphertext(record.ciphertext, lim), - subject, - location: { ...location, path: `${location.path}/data/history/${index}` }, - }; - }); - if (wraps.some((wrap, i) => i > 0 && wraps[i - 1].epoch >= wrap.epoch)) - fail("SYSTEM_EVENT_INVALID", "system"); - return wraps; -} - -async function decryptApplication( - subject: ApplicationEntry, - secret: Uint8Array, - model: JsonObject, - lim: Limits, -): Promise { - const decrypted = await decryptAgeWithSecret({ - secret, - ciphertext: unbase(subject.payload.ciphertext, lim, "EVENT_CONTEXT_INVALID"), - }); - if (!decrypted.ok) fail("DECRYPTION_INVALID", "system"); - const body = plaintext(decrypted.value, lim, "EVENT_CONTEXT_INVALID"); - fields( - body, - ["context", "parent", "nonce", "model", "audience", "epoch", "event"], - "EVENT_CONTEXT_INVALID", - ); - if ( - body.context !== "concord.application/1" || - body.parent !== subject.parent || - body.nonce !== subject.nonce || - !equal(body.model, model) || - body.audience !== subject.payload.audience || - body.epoch !== subject.payload.epoch - ) - fail("EVENT_CONTEXT_INVALID", "system"); - fields(body.event, ["type", "version", "data"], "EVENT_CONTEXT_INVALID"); - if ( - typeof body.event.type !== "string" || - !/^[a-z][a-z0-9.-]{0,127}$/.test(body.event.type) || - !Number.isInteger(body.event.version) || - Number(body.event.version) < 1 || - Number(body.event.version) > 2147483647 - ) - fail("EVENT_CONTEXT_INVALID", "system"); - return body.event as DomainEvent; -} - -export function createStandardSystemProfile(): SystemProfile { - const sessions = new WeakMap(); - return Object.freeze({ - ref: freeze({ id: "concord.standard", version: 1 }), - async bootstrap({ signer, limits: lim }) { - const secret = groupSecret(); - try { - const recipient = ageRecipientFromSecret(secret); - const context = { parent: null, nonce: nonce() }; - const owner = signer.publicIdentity; - return ok({ - ...context, - version: 1, - kind: "system", - payload: { - type: "system.init", - version: 1, - data: { - audience: "document", - epoch: 0, - recipient, - owner: { ...owner }, - wraps: [ - { - identityId: owner.id, - ciphertext: await wrapKey(context, owner, 0, recipient, secret, lim), - }, - ], - }, - }, - }); - } catch (cause) { - return { ok: false, error: caught(cause, "SYSTEM_FAILED", "system") }; - } finally { - secret.fill(0); - } - }, - - async replay({ history, reader, limits: lim }) { - const secrets = new Map(); - let stored = false; - let location: Location | undefined; - try { - if (!isVerifiedHistory(history)) fail("HOST_CONFIGURATION", "requirements"); - const groups = new Map(); - const allRecipients = new Set(); - const wraps: Wrap[] = []; - const entryFacts: SystemReplay["entryFacts"][number][] = []; - const applications: { - subject: ApplicationEntry; - facts: SystemFacts; - location: Location; - }[] = []; - const factsFor = (audience: AudienceId, actor: SystemFacts["actor"]): SystemFacts => { - const members = groups.get(audience)?.members ?? new Map(); - return detached({ - audience, - actor, - capabilities: capabilitiesOf(members, actor), - members: orderedMembers(members), - }); - }; - const fresh = (value: unknown): string => { - const next = recipient(value); - if (allRecipients.has(next)) fail("SYSTEM_EVENT_INVALID", "system"); - allRecipients.add(next); - return next; - }; - - // Establish authority for the entire signed history before touching any key. - for (const [index, { entry, commit }] of history.ordered.entries()) { - const subject = entry.subject; - const actor = commit.subject.signer; - location = { - entryId: entry.id, - commitId: commit.id, - path: `/entries/${index}/subject/payload`, - }; - let facts: SystemFacts; - if (subject.kind === "application") { - const audience = subject.payload.audience; - const group = groups.get(audience); - facts = factsFor(audience, actor); - if (!group || subject.parent === null) fail("SYSTEM_EVENT_INVALID", "system"); - if (!facts.capabilities.includes("write")) fail("CAPABILITY_DENIED", "system"); - if (subject.payload.epoch !== group.recipients.length - 1) - fail("SYSTEM_EVENT_INVALID", "system"); - applications.push({ subject, facts, location }); - } else { - const { type, version, data } = subject.payload; - if ( - version !== 1 || - ![ - "system.init", - "system.group.create", - "system.member.set", - "system.member.remove", - ].includes(type) - ) - fail("UNSUPPORTED_SYSTEM_EVENT", "system"); - if (type === "system.init") { - if (index !== 0 || subject.parent !== null || commit.subject.entryIds.length !== 1) - fail("SYSTEM_EVENT_INVALID", "system"); - fields( - data, - ["audience", "epoch", "recipient", "owner", "wraps"], - "SYSTEM_EVENT_INVALID", - ); - const owner = identity(data.owner); - const first = fresh(data.recipient); - const initial = recipientWraps(data.wraps, 0, subject, location, lim, "document"); - if ( - !equal(owner, actor) || - data.audience !== "document" || - data.epoch !== 0 || - initial.length !== 1 || - initial[0].identityId !== owner.id - ) - fail("SYSTEM_EVENT_INVALID", "system"); - groups.set("document", { - members: new Map([[owner.id, { identity: owner, capabilities: allCapabilities }]]), - recipients: [first], - }); - wraps.push(...initial); - facts = factsFor("document", actor); - } else if (type === "system.group.create") { - fields(data, ["audience", "epoch", "recipient", "wraps"], "SYSTEM_EVENT_INVALID"); - const audience = audienceId(data.audience); - facts = factsFor("document", actor); - if (audience === "document" || groups.has(audience) || data.epoch !== 0) - fail("SYSTEM_EVENT_INVALID", "system"); - if (!facts.capabilities.includes("write")) fail("CAPABILITY_DENIED", "system"); - const first = fresh(data.recipient); - const initial = recipientWraps(data.wraps, 0, subject, location, lim, audience); - if (initial.length !== 1 || initial[0].identityId !== actor.id) - fail("SYSTEM_EVENT_INVALID", "system"); - groups.set(audience, { - members: new Map([[actor.id, { identity: actor, capabilities: allCapabilities }]]), - recipients: [first], - }); - wraps.push(...initial); - } else { - const audience = audienceId(data.audience); - const group = groups.get(audience); - if (!group) fail("SYSTEM_EVENT_INVALID", "system"); - const { members, recipients } = group; - facts = factsFor(audience, actor); - if (type === "system.member.set") { - fields( - data, - ["audience", "identity", "capabilities", "history"], - "SYSTEM_EVENT_INVALID", - ); - const target = identity(data.identity); - const capabilities = capabilitySet(data.capabilities, true); - const historical = historicalWraps( - data.history, - target.id, - subject, - location, - lim, - audience, - ); - const admission = checkSet(members, actor, target, capabilities); - if ( - historical.length !== (admission ? recipients.length : 0) || - historical.some((wrap, i) => wrap.epoch !== i) - ) - fail("SYSTEM_EVENT_INVALID", "system"); - members.set(target.id, { identity: target, capabilities }); - wraps.push(...historical); - } else { - fields( - data, - ["audience", "identityId", "epoch", "recipient", "wraps"], - "SYSTEM_EVENT_INVALID", - ); - const target = identityId(data.identityId); - const epoch = epochNumber(data.epoch); - const next = recipient(data.recipient); - const rotations = recipientWraps( - data.wraps, - epoch, - subject, - location, - lim, - audience, - ); - checkRemoval(members, actor, target); - const remaining = [...members.keys()].filter((id) => id !== target).sort(); - if ( - epoch !== recipients.length || - allRecipients.has(next) || - rotations.length !== remaining.length || - rotations.some((wrap, i) => wrap.identityId !== remaining[i]) - ) - fail("SYSTEM_EVENT_INVALID", "system"); - allRecipients.add(next); - members.delete(target); - recipients.push(next); - wraps.push(...rotations); - } - } - } - entryFacts.push({ entryId: entry.id, facts }); - } - - for (const wrap of wraps) { - if (!reader || wrap.identityId !== reader.publicIdentity.id) continue; - location = wrap.location; - const secret = await unwrapKey( - wrap.subject, - reader, - wrap.epoch, - groups.get(wrap.audience)!.recipients[wrap.epoch], - wrap.ciphertext, - lim, - wrap.audience, - ); - const id = keyId(wrap.audience, wrap.epoch); - // Every addressed wrap is checked, including superseded admissions. - secrets.get(id)?.fill(0); - secrets.set(id, secret); - } - const entries: SystemReplay["entries"][number][] = []; - for (const application of applications) { - location = application.location; - const { audience, epoch } = application.subject.payload; - const secret = secrets.get(keyId(audience, epoch)); - entries.push( - secret - ? { - status: "readable", - entryId: location.entryId, - event: await decryptApplication( - application.subject, - secret, - history.declaration.model, - lim, - ), - facts: application.facts, - } - : { - status: "locked", - entryId: location.entryId, - audience, - epoch, - facts: application.facts, - }, - ); - } - const session = Object.freeze({}); - const audiences = [...groups.keys()].sort().map((audience) => { - const group = groups.get(audience)!; - return { - audience, - members: orderedMembers(group.members), - epochs: group.recipients.map((recipient, epoch) => ({ epoch, recipient })), - }; - }); - const output = freeze({ - entryFacts, - entries, - audiences, - reader: reader?.publicIdentity ?? null, - session, - }); - sessions.set(session, { - head: history.head, - readerId: reader?.publicIdentity.id ?? null, - groups, - secrets, - }); - stored = true; - return ok(output); - } catch (cause) { - const finding = caught(cause, "SYSTEM_FAILED", "system"); - if (location) Object.assign(finding, location); - return { ok: false, error: finding }; - } finally { - if (!stored) for (const secret of secrets.values()) secret.fill(0); - } - }, - - async prepare({ history, current, signer, intents, limits: lim }) { - const generated: Uint8Array[] = []; - try { - const session = sessions.get(current.session); - if (!isVerifiedHistory(history) || !session || session.head !== history.head) - fail("HOST_CONFIGURATION", "requirements"); - const actor = signer.publicIdentity; - if (actor.id !== session.readerId || !equal(actor, current.reader)) - fail("CAPABILITY_DENIED", "system"); - const groups = new Map( - [...session.groups].map(([id, group]) => [ - id, - { members: new Map(group.members), recipients: [...group.recipients] }, - ]), - ); - const allRecipients = new Set([...groups.values()].flatMap((group) => group.recipients)); - const secrets = new Map(session.secrets); - const entries: EntrySubject[] = []; - for (const intent of intents) { - const entry = { version: 1 as const, parent: history.head, nonce: nonce() }; - const audience = audienceId(intent.audience); - if (intent.kind === "group.create") { - fields(intent, ["kind", "audience"], "SYSTEM_EVENT_INVALID"); - if (audience === "document" || groups.has(audience)) - fail("SYSTEM_EVENT_INVALID", "system"); - if (!capabilitiesOf(groups.get("document")!.members, actor).includes("write")) - fail("CAPABILITY_DENIED", "system"); - const secret = groupSecret(); - generated.push(secret); - const recipient = ageRecipientFromSecret(secret); - if (allRecipients.has(recipient)) fail("SYSTEM_FAILED", "system"); - allRecipients.add(recipient); - const wraps = [ - { - identityId: actor.id, - ciphertext: await wrapKey(entry, actor, 0, recipient, secret, lim, audience), - }, - ]; - groups.set(audience, { - members: new Map([[actor.id, { identity: actor, capabilities: allCapabilities }]]), - recipients: [recipient], - }); - secrets.set(keyId(audience, 0), secret); - entries.push({ - ...entry, - kind: "system", - payload: { - type: "system.group.create", - version: 1, - data: { audience, epoch: 0, recipient, wraps }, - }, - }); - continue; - } - const group = groups.get(audience); - if (!group) fail("SYSTEM_EVENT_INVALID", "system"); - const { members, recipients } = group; - if (intent.kind === "application") { - const authority = capabilitiesOf(members, actor); - if ( - !authority.includes("write") || - !intent.required.every((capability) => authority.includes(capability)) - ) - fail("CAPABILITY_DENIED", "system"); - const epoch = recipients.length - 1; - if (!secrets.has(keyId(audience, epoch))) fail("KEY_UNAVAILABLE", "author"); - const ciphertext = await encrypt( - recipients[epoch], - { - context: "concord.application/1", - parent: entry.parent, - nonce: entry.nonce, - model: history.declaration.model, - audience, - epoch, - event: intent.event, - }, - lim, - ); - entries.push({ - ...entry, - kind: "application", - payload: { audience, epoch, ciphertext }, - }); - } else if (intent.kind === "member.set") { - fields( - intent, - ["kind", "audience", "identity", "capabilities"], - "SYSTEM_EVENT_INVALID", - ); - const target = identity(intent.identity); - const capabilities = capabilitySet(intent.capabilities, false); - const admission = checkSet(members, actor, target, capabilities); - const history: { epoch: number; ciphertext: string }[] = []; - if (admission) { - for (const [epoch, recipient] of recipients.entries()) { - const secret = secrets.get(keyId(audience, epoch)); - if (!secret) fail("HISTORICAL_KEY_UNAVAILABLE", "author"); - history.push({ - epoch, - ciphertext: await wrapKey(entry, target, epoch, recipient, secret, lim, audience), - }); - } - } - members.set(target.id, { identity: target, capabilities }); - entries.push({ - ...entry, - kind: "system", - payload: { - type: "system.member.set", - version: 1, - data: { audience, identity: target, capabilities, history }, - }, - }); - } else { - fields(intent, ["kind", "audience", "identityId"], "SYSTEM_EVENT_INVALID"); - const target = identityId(intent.identityId); - checkRemoval(members, actor, target); - const secret = groupSecret(); - generated.push(secret); - const recipient = ageRecipientFromSecret(secret); - if (allRecipients.has(recipient)) fail("SYSTEM_FAILED", "system"); - allRecipients.add(recipient); - const epoch = recipients.length; - members.delete(target); - const wraps: { identityId: string; ciphertext: string }[] = []; - for (const { identity } of orderedMembers(members)) { - wraps.push({ - identityId: identity.id, - ciphertext: await wrapKey(entry, identity, epoch, recipient, secret, lim, audience), - }); - } - recipients.push(recipient); - secrets.set(keyId(audience, epoch), secret); - entries.push({ - ...entry, - kind: "system", - payload: { - type: "system.member.remove", - version: 1, - data: { audience, identityId: target, epoch, recipient, wraps }, - }, - }); - } - } - return ok(entries); - } catch (cause) { - return { ok: false, error: caught(cause, "SYSTEM_FAILED", "system") }; - } finally { - for (const secret of generated) secret.fill(0); - } - }, - }); -} diff --git a/packages/concord/src/system/types.ts b/packages/concord/src/system/types.ts deleted file mode 100644 index 5027357..0000000 --- a/packages/concord/src/system/types.ts +++ /dev/null @@ -1,80 +0,0 @@ -import type { IdentityCapability, ReaderCapability } from "@ternent/armour"; -import type { Result } from "../common/errors.js"; -import type { - DomainEvent, - EntryId, - EntrySubject, - Limits, - ModelRef, - Declaration, - CommitId, - CommitRecord, - EntryRecord, - PublicIdentity, - AudienceId, - GroupId, -} from "../protocol/types.js"; -import type { Capability, SystemFacts, Member } from "../model/types.js"; -declare const verified: unique symbol; -export type VerifiedHistory = { - readonly [verified]: true; - readonly documentId: CommitId; - readonly head: CommitId; - readonly declaration: Declaration; - readonly ordered: readonly { commit: CommitRecord; entry: EntryRecord }[]; -}; -export type ApplicationIntent = { - kind: "application"; - event: DomainEvent; - required: readonly Capability[]; - audience: AudienceId; -}; -export type SystemIntent = - | { kind: "group.create"; audience: GroupId } - | { - kind: "member.set"; - audience: AudienceId; - identity: PublicIdentity; - capabilities: readonly Capability[]; - } - | { kind: "member.remove"; audience: AudienceId; identityId: string }; -export type AudienceState = { - audience: AudienceId; - members: readonly Member[]; - epochs: readonly { epoch: number; recipient: string }[]; -}; -export type ReplayItem = - | { status: "readable"; entryId: EntryId; event: DomainEvent; facts: SystemFacts } - | { status: "locked"; entryId: EntryId; audience: AudienceId; epoch: number; facts: SystemFacts }; -export type SystemReplay = { - entryFacts: readonly { entryId: EntryId; facts: SystemFacts }[]; - entries: readonly ReplayItem[]; - audiences: readonly AudienceState[]; - reader: PublicIdentity | null; - session: object; -}; -export type SystemProfile = { - ref: ModelRef; - bootstrap( - this: void, - input: { signer: IdentityCapability; limits: Limits }, - ): Promise>; - replay( - this: void, - input: { - history: VerifiedHistory; - reader: ReaderCapability | undefined; - limits: Limits; - }, - ): Promise>; - prepare( - this: void, - input: { - history: VerifiedHistory; - current: SystemReplay; - signer: IdentityCapability; - intents: readonly (ApplicationIntent | SystemIntent)[]; - limits: Limits; - }, - ): Promise>; -}; diff --git a/packages/concord/src/testing/artifact-store.ts b/packages/concord/src/testing/artifact-store.ts deleted file mode 100644 index d2043ea..0000000 --- a/packages/concord/src/testing/artifact-store.ts +++ /dev/null @@ -1,103 +0,0 @@ -import type { Result } from "../common/errors.js"; -import { defaults } from "../protocol/schema.js"; -import { verifyDocument } from "../protocol/verify.js"; -import type { CommitId } from "../protocol/types.js"; - -export type StorageError = - | { code: "STORAGE_FAILED"; phase: "storage"; message: string } - | { code: "HEAD_CONFLICT"; phase: "storage"; message: string; remote: Uint8Array | null }; -export type ArtifactStore = { - read(): Promise>; - write(bytes: Uint8Array): Promise>; -}; -export type ExpectedHeadArtifactStore = ArtifactStore & { - readonly expectedHead: true; - writeExpected(bytes: Uint8Array, expected: CommitId | null): Promise>; -}; -const failed = (): { ok: false; error: StorageError } => ({ - ok: false, - error: { code: "STORAGE_FAILED", phase: "storage", message: "Artifact storage operation failed" }, -}); -function capture(bytes: Uint8Array, maxBytes?: number): Result { - try { - return bytes instanceof Uint8Array && (maxBytes === undefined || bytes.byteLength <= maxBytes) - ? { ok: true, value: new Uint8Array(bytes) } - : failed(); - } catch { - return failed(); - } -} - -export function createMemoryArtifactStore(): ArtifactStore { - let stored: Uint8Array | null = null; - return { - async read() { - return { ok: true, value: stored === null ? null : new Uint8Array(stored) }; - }, - async write(bytes) { - const copied = capture(bytes); - if (!copied.ok) return copied; - stored = copied.value; - return { ok: true, value: undefined }; - }, - }; -} - -/** Reference atomicity is limited to writers sharing this in-memory instance. */ -export function createMemoryExpectedHeadStore(): ExpectedHeadArtifactStore { - let stored: Uint8Array | null = null; - let queue: Promise = Promise.resolve(); - const mutate = ( - body: () => Result | Promise>, - ): Promise> => { - const result = queue.then(body).catch(failed); - queue = result.then(() => undefined); - return result; - }; - return Object.freeze({ - expectedHead: true as const, - async read() { - return { ok: true as const, value: stored === null ? null : new Uint8Array(stored) }; - }, - write(bytes: Uint8Array) { - const copied = capture(bytes); - return mutate(() => { - if (!copied.ok) return copied; - stored = copied.value; - return { ok: true, value: undefined }; - }); - }, - writeExpected(bytes: Uint8Array, expected: CommitId | null) { - const copied = capture(bytes, defaults.maxBytes); - return mutate(async () => { - if (!copied.ok) return copied; - if ( - expected !== null && - (typeof expected !== "string" || !/^commit:[0-9a-f]{64}$/.test(expected)) - ) - return failed(); - // Validation and comparison share the mutation queue, including unconditional writes. - const candidate = await verifyDocument(copied.value); - if (candidate.integrity !== "valid") return failed(); - let head: CommitId | null = null; - if (stored !== null) { - const current = await verifyDocument(stored); - if (current.integrity !== "valid") return failed(); - head = current.head; - } - if (head !== expected) - return { - ok: false, - error: { - code: "HEAD_CONFLICT", - phase: "storage", - message: "Stored head differs from expected head", - remote: stored === null ? null : new Uint8Array(stored), - }, - }; - stored = copied.value; - return { ok: true, value: undefined }; - }); - }, - }); -} diff --git a/packages/concord/src/testing/index.ts b/packages/concord/src/testing/index.ts deleted file mode 100644 index ef1965b..0000000 --- a/packages/concord/src/testing/index.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { detached, freeze } from "../common/immutable.js"; -import { defineModel } from "../model/index.js"; -import { canonicalize, text, unicode, utf8 } from "../protocol/json.js"; -import { object } from "../protocol/schema.js"; -import { error, ok, type Result } from "../common/errors.js"; -import type { ApplicationModel, ModelIssue, SystemFacts } from "../model/types.js"; -import type { Json, DomainEvent } from "../protocol/types.js"; -type RegisterState = { value: string }; -type RegisterCommands = { set: { value: string } }; -type RegisterEvent = { type: "value.set"; version: 1; data: { value: string } }; -const issue = (code: string): { ok: false; error: ModelIssue } => ({ - ok: false, - error: { code, message: code }, -}); -function value(input: unknown): Result<{ value: string }, ModelIssue> { - if ( - !canonicalize(input).ok || - !object(input) || - Object.keys(input).length !== 1 || - typeof input.value !== "string" || - !unicode(input.value) || - utf8.encode(input.value).length > 4096 - ) - return issue("VALUE_INVALID"); - return { ok: true, value: { value: input.value } }; -} -export const registerModel = defineModel({ - ref: { id: "concord.example.register", version: 1 }, - initial: () => ({ value: "" }), - commands: { - set: { - validate: value, - decide: (input) => ({ ok: true, value: [{ type: "value.set", version: 1, data: input }] }), - }, - }, - validateEvent(input) { - if (!object(input) || Object.keys(input).length !== 3) return issue("EVENT_INVALID"); - if (input.type !== "value.set" || input.version !== 1) return issue("EVENT_UNSUPPORTED"); - const valid = value(input.data); - return valid.ok - ? { ok: true, value: { type: "value.set", version: 1, data: valid.value } } - : issue("VALUE_INVALID"); - }, - requirements: () => ["write"], - reduce: (_state, event) => ({ ok: true, value: { value: event.data.value } }), -}); -export function assertModelConformance< - S extends Json, - C extends Record, - E extends DomainEvent, ->( - model: ApplicationModel, - cases: { initial: S; steps: readonly { event: E; facts: SystemFacts; expected: S }[] }, -): Result<{ passed: number }> { - const canonical = (input: unknown) => { - const encoded = canonicalize(input); - if (!encoded.ok) throw new Error("invalid"); - return text.decode(encoded.value); - }; - try { - const fixed = detached(cases); - for (let pass = 0; pass < 2; pass++) { - let state = detached(model.initial()); - if (canonical(state) !== canonical(fixed.initial)) - return { ok: false, error: error("MODEL_TRANSITION_INVALID", "model") }; - for (const step of fixed.steps) { - const event = model.validateEvent(step.event); - if (!event.ok) return { ok: false, error: error("EVENT_INVALID", "model") }; - const next = model.reduce(state, freeze(event.value), step.facts); - if (!next.ok || canonical(next.value) !== canonical(step.expected)) - return { ok: false, error: error("MODEL_TRANSITION_INVALID", "model") }; - state = detached(next.value); - } - } - return ok({ passed: cases.steps.length + 1 }); - } catch { - return { ok: false, error: error("MODEL_FAILED", "model") }; - } -} -export { createMemoryArtifactStore, createMemoryExpectedHeadStore } from "./artifact-store.js"; -export type { ArtifactStore, ExpectedHeadArtifactStore, StorageError } from "./artifact-store.js"; diff --git a/packages/concord/test/concord.test.ts b/packages/concord/test/concord.test.ts new file mode 100644 index 0000000..900c0ba --- /dev/null +++ b/packages/concord/test/concord.test.ts @@ -0,0 +1,491 @@ +import { readFileSync } from "node:fs"; +import { expect, test } from "vite-plus/test"; +import { base64urlnopad } from "@scure/base"; +import { decrypt, encrypt } from "@ternent/armour"; +import { createIdentity, restoreIdentity, type Identity } from "@ternent/identity"; +import { createWriter, openLedger } from "@ternent/ledger"; +import { generateX25519Identity, identityToRecipient } from "age-encryption"; +import * as api from "../src/index.js"; +import { + createDocument, + defineModel, + openDocument, + type Event, + type GroupId, + type Json, +} from "../src/index.js"; + +type Notes = { notes: { [id: string]: string } }; + +const notes = defineModel({ + id: "notes", + version: 1, + initial: () => ({ notes: {} }), + reduce(state, event) { + const data = event.data as { id: string; title?: string }; + if (event.type === "note.put") return { notes: { ...state.notes, [data.id]: data.title! } }; + if (event.type === "note.remove") { + if (!(data.id in state.notes)) throw new Error(`No note ${data.id}`); + const { [data.id]: _removed, ...rest } = state.notes; + return { notes: rest }; + } + throw new Error(`Unknown event ${event.type}`); + }, + squash(events) { + const last = new Map(events.map((event) => [(event.data as { id: string }).id, event])); + return [...last.values()]; + }, +}); + +const put = (id: string, title: string): Event => ({ type: "note.put", data: { id, title } }); +const encoder = new TextEncoder(); + +async function people() { + const [alice, bob, carol, mallory] = await Promise.all( + Array.from({ length: 4 }, () => createIdentity()), + ); + return { alice, bob, carol, mallory }; +} + +// Builds a commit the public API would refuse, to test that replay rejects it. +async function forge(bytes: Uint8Array, signer: Identity, payloads: Uint8Array[]) { + const writer = createWriter(await openLedger(bytes), signer); + writer.append( + payloads.map((payload) => ({ kind: "concord", payload: base64urlnopad.encode(payload) })), + ); + return (await writer.commit()).export(); +} + +async function sealRecord(body: Record, secret: string) { + const json = JSON.stringify({ concord: 1, ...body }); + return encrypt(encoder.encode(json), [await identityToRecipient(secret)]); +} + +// The epoch secrets wrapped to `identity`, read directly from the bytes. +async function keysOf(bytes: Uint8Array, identity: Identity) { + const keys = new Map>(); + for (const commit of (await openLedger(bytes)).commits) { + for (const entry of commit.entries) { + try { + const opened = await decrypt(base64urlnopad.decode(entry.payload as string), identity); + const wrap = JSON.parse(new TextDecoder().decode(opened)); + keys.set(wrap.group, { ...keys.get(wrap.group), ...wrap.epochs }); + } catch { + // Not a wrap for this identity. + } + } + } + return keys; +} + +test("the public interface is createDocument, defineModel and openDocument", () => { + expect(Object.keys(api).sort()).toEqual(["createDocument", "defineModel", "openDocument"]); + expect(defineModel(notes)).toBe(notes); +}); + +test("the saved vector opens with the expected state for each identity", async () => { + const vector = JSON.parse(readFileSync(new URL("vector.json", import.meta.url), "utf8")); + const bytes = encoder.encode(vector.document); + for (const [name, backup] of Object.entries(vector.identities as Record)) { + const doc = await openDocument(bytes, { + model: notes, + identity: await restoreIdentity(backup), + }); + const groups = Object.fromEntries( + doc.groups.map((g) => [g.default ? "default" : "team", doc.state(g.id)]), + ); + expect({ groups, unreadable: doc.unreadable, rejected: doc.rejected.length }).toEqual( + vector.expected[name], + ); + expect(doc.export()).toEqual(bytes); + } +}); + +test("stage, commit, export and reopen give the same state", async () => { + const { alice } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + expect(doc.state()).toEqual({ notes: {} }); + doc.stage(put("1", "Hello")); + expect(doc.draft?.state).toEqual({ notes: { 1: "Hello" } }); + expect(doc.state()).toEqual({ notes: {} }); + await doc.commit(); + expect(doc.draft).toBeNull(); + const reopened = await openDocument(doc.export(), { model: notes, identity: alice }); + expect(reopened.state()).toEqual({ notes: { 1: "Hello" } }); + expect(reopened.head).toBe(doc.head); + expect(reopened.rejected).toEqual([]); + expect(reopened.unreadable).toBe(0); + const ledger = await openLedger(doc.export()); + expect(ledger.commits.flatMap((commit) => commit.entries.map((entry) => entry.kind))).toEqual( + Array(3).fill("concord"), + ); +}); + +test("a new member reads the group's whole history, and nothing outside it", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const team = await doc.createGroup(); + doc.stage(put("1", "first"), { group: team }); + await doc.commit(); + doc.stage(put("2", "second"), { group: team }); + await doc.commit(); + await doc.setMember(bob.publicIdentity, { group: team, role: "member" }); + + const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); + expect(bobs.state(team)).toEqual({ notes: { 1: "first", 2: "second" } }); + expect(bobs.groups.map((group) => group.id)).toEqual([team]); + expect(bobs.groups[0].members.map((member) => member.role).sort()).toEqual(["admin", "member"]); + expect(() => bobs.state()).toThrow(/cannot read/); + expect(bobs.unreadable).toBeGreaterThan(0); +}); + +test("removal rotates the key: the removed member reads nothing new and cannot write", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const team = await doc.createGroup(); + await doc.setMember(bob.publicIdentity, { group: team, role: "member" }); + doc.stage(put("1", "before"), { group: team }); + await doc.commit(); + await doc.removeMember(bob.publicIdentity, { group: team }); + doc.stage(put("2", "after"), { group: team }); + await doc.commit(); + + const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); + expect(bobs.state(team)).toEqual({ notes: { 1: "before" } }); + expect(doc.groups.find((group) => group.id === team)?.members).toHaveLength(1); + + // Bob still thinks he is a member and writes with the old epoch key. + bobs.stage(put("3", "from bob"), { group: team }); + await bobs.commit(); + const alices = await openDocument(bobs.export(), { model: notes, identity: alice }); + expect(alices.state(team)).toEqual({ notes: { 1: "before", 2: "after" } }); + expect(alices.rejected).toEqual([expect.objectContaining({ group: team, reason: "authority" })]); +}); + +test("replay rejects writes by non-members, obsolete epochs and non-admins", async () => { + const { alice, bob, carol } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const team = await doc.createGroup(); + await doc.setMember(bob.publicIdentity, { group: team, role: "member" }); + await doc.setMember(carol.publicIdentity, { group: team, role: "member" }); + await doc.removeMember(carol.publicIdentity, { group: team }); + const bytes = doc.export(); + const bobKeys = (await keysOf(bytes, bob)).get(team)!; + const carolKeys = (await keysOf(bytes, carol)).get(team)!; + + const cases: [Identity, Record, string][] = [ + [carol, { op: "events", events: [put("x", "carol")], version: 1 }, carolKeys["0"]], + [bob, { op: "events", events: [put("x", "obsolete")], version: 1 }, bobKeys["0"]], + [bob, { op: "set", identity: carol.publicIdentity, role: "member" }, bobKeys["1"]], + [ + bob, + { op: "remove", identity: alice.publicIdentity, epoch: 2 }, + await generateX25519Identity(), + ], + ]; + for (const [index, [signer, body, secret]] of cases.entries()) { + const forged = await forge(bytes, signer, [await sealRecord(body, secret)]); + const alices = await openDocument(forged, { model: notes, identity: alice }); + expect(alices.state(team)).toEqual({ notes: {} }); + expect(alices.groups.find((group) => group.id === team)?.members).toHaveLength(2); + // The last forgery uses a key nobody was given, so it is unreadable, not rejected. + if (index < 3) { + expect(alices.rejected).toEqual([ + expect.objectContaining({ group: team, reason: "authority" }), + ]); + } else { + expect(alices.rejected).toEqual([]); + } + } +}); + +test("replay rejects a role change on an obsolete epoch and removing the last admin", async () => { + const { alice, bob, carol } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const team = await doc.createGroup(); + await doc.setMember(bob.publicIdentity, { group: team, role: "member" }); + await doc.setMember(carol.publicIdentity, { group: team, role: "member" }); + await doc.removeMember(carol.publicIdentity, { group: team }); + const bytes = doc.export(); + const keys = (await keysOf(bytes, alice)).get(team)!; + + const obsolete = await forge(bytes, alice, [ + await sealRecord({ op: "set", identity: bob.publicIdentity, role: "admin" }, keys["0"]), + ]); + const afterObsolete = await openDocument(obsolete, { model: notes, identity: alice }); + expect(afterObsolete.rejected).toEqual([expect.objectContaining({ reason: "authority" })]); + expect( + afterObsolete.groups + .find((g) => g.id === team) + ?.members.map((m) => m.role) + .sort(), + ).toEqual(["admin", "member"]); + + const next = await generateX25519Identity(); + const lastAdmin = await forge(bytes, alice, [ + await sealRecord({ op: "remove", identity: alice.publicIdentity, epoch: 2 }, next), + await encrypt( + encoder.encode(JSON.stringify({ concord: 1, group: team, epochs: { 2: next } })), + [alice.publicIdentity], + ), + ]); + const afterLastAdmin = await openDocument(lastAdmin, { model: notes, identity: alice }); + expect(afterLastAdmin.rejected).toEqual([ + expect.objectContaining({ reason: "authority", message: "A group keeps at least one admin" }), + ]); + expect(afterLastAdmin.groups.find((g) => g.id === team)?.members).toHaveLength(2); +}); + +test("a commit whose events fail reduce is rejected whole, and later commits still apply", async () => { + const { alice } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const group = doc.groups[0].id; + const secret = (await keysOf(doc.export(), alice)).get(group)!["0"]; + const bad = await sealRecord( + { + op: "events", + events: [put("1", "kept?"), { type: "note.remove", data: { id: "missing" } }], + version: 1, + }, + secret, + ); + const withBad = await forge(doc.export(), alice, [bad]); + const later = await openDocument(withBad, { model: notes, identity: alice }); + later.stage(put("2", "later")); + await later.commit(); + const reopened = await openDocument(later.export(), { model: notes, identity: alice }); + expect(reopened.state()).toEqual({ notes: { 2: "later" } }); + expect(reopened.rejected).toEqual([ + expect.objectContaining({ reason: "application", message: "No note missing" }), + ]); +}); + +test("a group keeps at least one admin, and admins can promote and demote", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const group = doc.groups[0].id; + await expect(doc.removeMember(alice.publicIdentity, { group })).rejects.toThrow( + /at least one admin/, + ); + await expect(doc.setMember(alice.publicIdentity, { group, role: "member" })).rejects.toThrow( + /at least one admin/, + ); + await doc.setMember(bob.publicIdentity, { group, role: "admin" }); + await doc.setMember(alice.publicIdentity, { group, role: "member" }); + const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); + expect(bobs.groups[0].members.find((m) => m.identity.id === alice.publicIdentity.id)?.role).toBe( + "member", + ); + await expect(doc.setMember(bob.publicIdentity, { group, role: "member" })).rejects.toThrow( + /admin/, + ); +}); + +test("two members agree on a group's state whatever other groups they belong to", async () => { + const { alice, bob, carol } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const team = await doc.createGroup(); + const leads = await doc.createGroup(); + await doc.setMember(bob.publicIdentity, { group: team, role: "member" }); + await doc.setMember(carol.publicIdentity, { group: team, role: "member" }); + await doc.setMember(bob.publicIdentity, { group: leads, role: "member" }); + doc.stage(put("1", "team"), { group: team }); + await doc.commit(); + doc.stage(put("2", "leads"), { group: leads }); + await doc.commit(); + const [bobs, carols] = await Promise.all( + [bob, carol].map((identity) => openDocument(doc.export(), { model: notes, identity })), + ); + expect(bobs.state(team)).toEqual(carols.state(team)); + expect(bobs.rejected).toEqual(carols.rejected); + expect(() => carols.state(leads)).toThrow(/cannot read/); +}); + +test("a forged key wrap and an unsolicited group carry no authority", async () => { + const { alice, bob, mallory } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const team = await doc.createGroup(); + await doc.setMember(bob.publicIdentity, { group: team, role: "member" }); + const bytes = doc.export(); + + const fake = await generateX25519Identity(); + const wrap = await encrypt( + encoder.encode(JSON.stringify({ concord: 1, group: team, epochs: { 1: fake } })), + [bob.publicIdentity], + ); + const removal = await sealRecord( + { op: "remove", identity: alice.publicIdentity, epoch: 1 }, + fake, + ); + const forged = await forge(bytes, mallory, [removal, wrap]); + const bobs = await openDocument(forged, { model: notes, identity: bob }); + expect(bobs.groups.find((group) => group.id === team)?.members).toHaveLength(2); + expect(bobs.rejected).toEqual([expect.objectContaining({ reason: "authority" })]); + + const theirs = await openDocument(bytes, { model: notes, identity: mallory }); + expect(theirs.groups).toEqual([]); + const own = await theirs.createGroup(); + await theirs.setMember(alice.publicIdentity, { group: own, role: "member" }); + const alices = await openDocument(theirs.export(), { model: notes, identity: alice }); + expect(alices.groups.map((group) => group.id)).toContain(own); + expect(alices.groups.find((group) => group.id === team)?.members).toHaveLength(2); + expect(alices.groups.find((group) => group.default)?.members).toHaveLength(1); +}); + +test("each group pins its model, and a newer version refuses only that group", async () => { + const { alice } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const team = await doc.createGroup(); + const newer = defineModel({ ...notes, version: 2 }); + const v2 = await openDocument(doc.export(), { model: newer, identity: alice }); + v2.stage(put("1", "v2"), { group: team }); + await v2.commit(); + + const v1 = await openDocument(v2.export(), { model: notes, identity: alice }); + expect(() => v1.state(team)).toThrow(/needs model version 2/); + expect(v1.state()).toEqual({ notes: {} }); + const other = defineModel({ ...notes, id: "tasks" }); + const tasks = await openDocument(doc.export(), { model: other, identity: alice }); + expect(() => tasks.state()).toThrow(/uses model notes/); +}); + +test("reduce receives frozen state, so a mutating reducer cannot change accepted state", async () => { + const { alice } = await people(); + const mutating = defineModel({ + ...notes, + reduce(state, event) { + state.notes[(event.data as { id: string }).id] = "mutated"; + return state; + }, + }); + const doc = await createDocument({ model: mutating, identity: alice }); + expect(() => doc.stage(put("1", "x"))).toThrow(TypeError); + expect(doc.state()).toEqual({ notes: {} }); + expect(doc.draft).toBeNull(); +}); + +test("squash shortens a draft, and a squash that changes the result fails the commit", async () => { + const { alice } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + for (const title of ["H", "He", "Hello"]) doc.stage(put("1", title)); + await doc.commit(); + expect(doc.state()).toEqual({ notes: { 1: "Hello" } }); + + const dropping = defineModel({ ...notes, squash: (events) => events.slice(0, 1) }); + const broken = await openDocument(doc.export(), { model: dropping, identity: alice }); + broken.stage(put("2", "a")); + broken.stage(put("3", "b")); + await expect(broken.commit()).rejects.toThrow(/squash changed/); + expect(broken.draft?.events).toHaveLength(2); + expect(broken.state()).toEqual({ notes: { 1: "Hello" } }); +}); + +test("a draft holds one group, and group operations wait for it", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const team = await doc.createGroup(); + doc.stage(put("1", "default")); + expect(() => doc.stage(put("2", "team"), { group: team })).toThrow(/one group/); + await expect(doc.createGroup()).rejects.toThrow(/draft/); + await expect(doc.setMember(bob.publicIdentity, { group: team, role: "member" })).rejects.toThrow( + /draft/, + ); + doc.discard(); + expect(doc.draft).toBeNull(); + await expect(doc.commit()).rejects.toThrow(/Nothing is staged/); +}); + +test("rebase reapplies only this identity's unpublished work and returns what no longer applies", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const group = doc.groups[0].id; + await doc.setMember(bob.publicIdentity, { group, role: "member" }); + doc.stage(put("1", "shared")); + await doc.commit(); + const published = doc.head; + const shared = doc.export(); + + const bobs = await openDocument(shared, { model: notes, identity: bob }); + bobs.stage(put("2", "bob")); + await bobs.commit(); + bobs.stage({ type: "note.remove", data: { id: "1" } }); + await bobs.commit(); + + doc.stage({ type: "note.remove", data: { id: "1" } }); + await doc.commit(); + const remote = doc.export(); + + const returned = await bobs.rebase(remote, { published }); + expect(bobs.state()).toEqual({ notes: { 2: "bob" } }); + expect(returned).toEqual([ + expect.objectContaining({ + group, + message: "No note 1", + events: [{ type: "note.remove", data: { id: "1" } }], + }), + ]); + const alices = await openDocument(bobs.export(), { model: notes, identity: alice }); + expect(alices.state()).toEqual({ notes: { 2: "bob" } }); + expect((await openLedger(bobs.export())).compare(await openLedger(remote))).toBe("ahead"); + + // Rebasing again against the same remote reapplies nothing twice. + expect(await bobs.rebase(remote, { published })).toEqual([]); + expect(bobs.state()).toEqual({ notes: { 2: "bob" } }); +}); + +test("rebase refuses other people's unpublished work, a draft and an unknown head", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const group = doc.groups[0].id; + await doc.setMember(bob.publicIdentity, { group, role: "member" }); + const published = doc.head; + const remote = doc.export(); + doc.stage(put("1", "alice")); + await doc.commit(); + + const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); + await expect(bobs.rebase(remote, { published })).rejects.toThrow(/another identity/); + bobs.stage(put("2", "bob")); + await expect(bobs.rebase(remote, { published })).rejects.toThrow(/draft/); + bobs.discard(); + await expect(bobs.rebase(remote, { published: `commit:${"0".repeat(64)}` })).rejects.toThrow( + /not in this history/, + ); + const membership = await openDocument(remote, { model: notes, identity: alice }); + await membership.setMember(bob.publicIdentity, { group, role: "admin" }); + const unrelated = await createDocument({ model: notes, identity: alice }); + await expect(membership.rebase(unrelated.export(), { published })).rejects.toThrow( + /not in the remote/, + ); + await expect(membership.rebase(remote, { published })).rejects.toThrow(/membership/); +}); + +test("tampered bytes do not open", async () => { + const { alice } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const bytes = doc.export(); + const tampered = bytes.slice(); + tampered[tampered.length - 40] ^= 1; + await expect(openDocument(tampered, { model: notes, identity: alice })).rejects.toThrow(); +}); + +test("the raw bytes show no group ID, model, event type, role or data", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const team = await doc.createGroup(); + await doc.setMember(bob.publicIdentity, { group: team, role: "member" }); + doc.stage(put("note-id", "secret title"), { group: team }); + await doc.commit(); + const text = new TextDecoder().decode(doc.export()); + for (const hidden of [ + team, + doc.groups[0].id as GroupId, + '"notes"', + "note.put", + "admin", + '"member"', + "secret title", + ]) { + expect(text).not.toContain(hidden); + } +}); diff --git a/packages/concord/test/drafts.test.ts b/packages/concord/test/drafts.test.ts deleted file mode 100644 index 4d10f3f..0000000 --- a/packages/concord/test/drafts.test.ts +++ /dev/null @@ -1,697 +0,0 @@ -import { expect, test, vi } from "vite-plus/test"; -import { identityFromSeed, type IdentityCapability } from "@ternent/armour"; -import { - createDocument, - defineModel, - openDocument, - type ApplicationModel, - type AudienceId, - type DocumentHandle, - type JsonObject, - type ModelIssue, - type Result, - type Snapshot, -} from "../src/index.js"; -import { createGroup, createStandardSystemProfile, setMember } from "../src/system/index.js"; -import { seed, protectedPayload } from "./fixtures.js"; - -type Input = { audience: AudienceId; key: string; value: string }; -type Commands = { set: Input }; -type State = { values: Record; order: string[] }; -type Event = { - type: "draft.value"; - version: 1; - data: Input & { previous: string | null }; -}; -type Model = ApplicationModel; -const success = (value: T): Result => ({ ok: true, value }); -const issue = (code: string): { ok: false; error: ModelIssue } => ({ - ok: false, - error: { code, message: code }, -}); -const failure = (code: string) => ({ ok: false, error: { code } }); -function value(result: { ok: true; value: T } | { ok: false; error: { code: string } }): T { - if (!result.ok) throw new Error(result.error.code); - return result.value; -} -const ownerIdentity = async () => value(await identityFromSeed(seed)); -const set = (key: string, text: string, audience: AudienceId = "document"): Input => ({ - audience, - key, - value: text, -}); -const wire = (bytes: Uint8Array): Snapshot => - JSON.parse(new TextDecoder().decode(bytes)) as Snapshot; -function model(): Model { - return defineModel({ - ref: { id: "concord.test.drafts", version: 1 }, - initial: () => ({ values: {}, order: [] }), - commands: { - set: { - validate(input) { - if (!input || typeof input !== "object") return issue("INPUT_INVALID"); - const record = input as Record; - if ( - typeof record.audience !== "string" || - typeof record.key !== "string" || - typeof record.value !== "string" - ) - return issue("INPUT_INVALID"); - return success({ - audience: record.audience as AudienceId, - key: record.key, - value: record.value, - }); - }, - audience: (input) => input.audience, - decide: (input, state) => - success([ - { - type: "draft.value", - version: 1, - data: { ...input, previous: state.values[input.key] ?? null }, - }, - ]), - }, - }, - validateEvent(input) { - if (!input || typeof input !== "object") return issue("EVENT_INVALID"); - const event = input as Event; - if ( - event.type !== "draft.value" || - event.version !== 1 || - !event.data || - typeof event.data.audience !== "string" || - typeof event.data.key !== "string" || - typeof event.data.value !== "string" || - (event.data.previous !== null && typeof event.data.previous !== "string") - ) - return issue("EVENT_INVALID"); - return success(event); - }, - audience: (event) => event.data.audience, - requirements: () => ["write"], - reduce(state, event) { - if ((state.values[event.data.key] ?? null) !== event.data.previous) - return issue("PREVIOUS_VALUE_INVALID"); - return success({ - values: { ...state.values, [event.data.key]: event.data.value }, - order: [...state.order, `${event.data.audience}:${event.data.value}`], - }); - }, - }); -} -const create = async (identity: IdentityCapability, definition = model()) => - value( - await createDocument({ identity, model: definition, system: createStandardSystemProfile() }), - ); -const openDraft = (bytes: Uint8Array, signer: IdentityCapability, definition = model()) => - openDocument({ - bytes, - signer, - mode: "draft", - model: definition, - system: createStandardSystemProfile(), - }); - -test("draft creation commits only genesis and subsequent commands decide against the staged preview", async () => { - const owner = await ownerIdentity(); - const profile = createStandardSystemProfile(); - const prepare = vi.fn(profile.prepare); - const sign = vi.fn(owner.sign); - const document = value( - await createDocument({ - identity: { ...owner, sign }, - model: model(), - system: { ...profile, prepare }, - mode: "draft", - }), - ); - expect(wire(document.export()).commits).toHaveLength(1); - expect(wire(document.export()).entries).toHaveLength(1); - expect(sign).toHaveBeenCalledOnce(); - expect(prepare).not.toHaveBeenCalled(); - sign.mockClear(); - const before = document.export(); - const beforeState = document.state(); - const head = wire(before).head; - expect(document.draft()).toBeNull(); - expect(value(await document.dispatch("set", set("same", "first")))).toEqual({ - status: "staged", - baseHead: head, - entryCount: 1, - }); - expect(value(await document.dispatch("set", set("same", "second")))).toEqual({ - status: "staged", - baseHead: head, - entryCount: 2, - }); - expect(document.draft()).toEqual({ - baseHead: head, - entryCount: 2, - preview: { values: { same: "second" }, order: ["document:first", "document:second"] }, - }); - expect(document.state()).toEqual(beforeState); - expect(document.export()).toEqual(before); - expect(document.inspect().entries).toEqual([]); - expect((await document.verify()).integrity).toBe("valid"); - expect(value(await document.replay())).toEqual({ - projection: { values: {}, order: [] }, - coverage: "complete", - lockedEntries: 0, - }); - expect(prepare).not.toHaveBeenCalled(); - expect(sign).not.toHaveBeenCalled(); - const receipt = value(await document.commit({ note: "one explicit batch" })); - expect(receipt.entryIds).toHaveLength(2); - expect(prepare).toHaveBeenCalledOnce(); - expect(sign).toHaveBeenCalledOnce(); - expect(wire(document.export()).commits).toHaveLength(2); - expect(wire(document.export()).commits.at(-1)!.subject.metadata).toEqual({ - note: "one explicit batch", - }); - expect(document.draft()).toBeNull(); - expect(document.state()).toMatchObject({ - head: receipt.head, - projection: { values: { same: "second" }, order: ["document:first", "document:second"] }, - }); - expect((await openDraft(document.export(), owner)).state()).toEqual(document.state()); -}); - -test("one explicit draft commit can contain ordered commands for independent audiences", async () => { - const owner = await ownerIdentity(); - const immediate = await create(owner); - const first = value(await createGroup(immediate)).audience; - const second = value(await createGroup(immediate)).audience; - const document = await openDraft(immediate.export(), owner); - const before = wire(document.export()); - for (const input of [ - set("default", "one"), - set("first", "two", first), - set("second", "three", second), - ]) - value(await document.dispatch("set", input)); - const preview = document.draft()!.preview; - value(await document.commit()); - const committed = wire(document.export()); - expect(committed.commits).toHaveLength(before.commits.length + 1); - expect(committed.commits.at(-1)!.subject.entryIds).toHaveLength(3); - expect( - committed.entries.slice(-3).map(({ subject }) => { - if (subject.kind !== "application") throw new Error("Expected staged application entry"); - return protectedPayload(subject).audience; - }), - ).toEqual(["document", first, second]); - expect(document.state()).toMatchObject({ projection: preview }); - expect(value(await document.replay()).projection).toEqual(preview); -}); - -test("staging captures inputs and returns detached previews while rejected dispatch preserves the existing draft", async () => { - const owner = await ownerIdentity(); - const document = await openDraft((await create(owner)).export(), owner); - const input = set("captured", "original"); - const pending = document.dispatch("set", input); - input.value = "mutated before queued validation"; - value(await pending); - const staged = document.draft()!; - expect(staged.preview.values.captured).toBe("original"); - try { - (staged.preview.values as Record).captured = "external mutation"; - } catch { - /* Frozen copies are allowed. */ - } - expect(document.draft()!.preview.values.captured).toBe("original"); - const before = document.export(); - const draft = document.draft(); - expect( - await document.dispatch("set", { ...set("invalid", "invalid"), value: 42 } as unknown as Input), - ).toMatchObject(failure("COMMAND_INVALID")); - expect( - await document.dispatch("set", set("denied", "denied", `group:${"A".repeat(22)}`)), - ).toMatchObject(failure("CAPABILITY_DENIED")); - expect(document.draft()).toEqual(draft); - expect(document.export()).toEqual(before); - value(await document.dispatch("set", set("captured", "next"))); - expect(document.draft()!.entryCount).toBe(2); - value(await document.commit()); - expect(document.state()).toMatchObject({ projection: { values: { captured: "next" } } }); -}); - -test("discard removes only pending work and empty or immediate commits return NO_DRAFT", async () => { - const owner = await ownerIdentity(); - const immediate = await create(owner); - value(await immediate.dispatch("set", set("committed", "retained"))); - expect(await immediate.commit()).toMatchObject(failure("NO_DRAFT")); - const document = await openDraft(immediate.export(), owner); - const before = document.export(); - const state = document.state(); - expect(await document.commit()).toMatchObject(failure("NO_DRAFT")); - value(await document.dispatch("set", set("pending", "discarded"))); - value(await document.discardDraft()); - expect(document.draft()).toBeNull(); - expect(document.export()).toEqual(before); - expect(document.state()).toEqual(state); - expect(await document.commit()).toMatchObject(failure("NO_DRAFT")); - value(await document.dispatch("set", set("new", "replacement"))); - expect(document.draft()!.entryCount).toBe(1); -}); - -test("system helpers never implicitly change draft authoring mode", async () => { - const owner = await ownerIdentity(); - const other = value(await identityFromSeed(new Uint8Array(32).fill(2))); - const immediate = await create(owner); - value(await createGroup(immediate)); - const document = await openDraft(immediate.export(), owner); - const before = document.export(); - expect(await createGroup(document)).toMatchObject(failure("HOST_CONFIGURATION")); - expect( - await setMember(document, { identity: other.publicIdentity, capabilities: ["read"] }), - ).toMatchObject(failure("HOST_CONFIGURATION")); - value(await document.dispatch("set", set("pending", "keep draft"))); - const draft = document.draft(); - expect(await createGroup(document)).toMatchObject(failure("DRAFT_PENDING")); - expect( - await setMember(document, { identity: other.publicIdentity, capabilities: ["read"] }), - ).toMatchObject(failure("DRAFT_PENDING")); - expect(document.export()).toEqual(before); - expect(document.draft()).toEqual(draft); -}); - -test("draft mutations retain signer-free and inspection-only guards", async () => { - const owner = await ownerIdentity(); - const bytes = (await create(owner)).export(); - const readOnly = await openDocument({ - bytes, - reader: owner, - mode: "draft", - model: model(), - system: createStandardSystemProfile(), - }); - const incompatible = model(); - incompatible.ref = { ...incompatible.ref, version: 2 }; - const inspection = await openDraft(bytes, owner, incompatible); - for (const [handle, code] of [ - [readOnly, "READ_ONLY_RUNTIME"], - [inspection, "INSPECTION_ONLY"], - ] as const) { - expect(await handle.dispatch("set", set("denied", "denied"))).toMatchObject(failure(code)); - expect(await handle.commit()).toMatchObject(failure(code)); - expect(await handle.discardDraft()).toMatchObject(failure(code)); - expect(handle.export()).toEqual(bytes); - expect(handle.draft()).toBeNull(); - } -}); - -test("preparation and signing failures preserve pending intents for an explicit retry", async () => { - const owner = await ownerIdentity(); - const bytes = (await create(owner)).export(); - for (const phase of ["prepare", "sign"] as const) { - const profile = createStandardSystemProfile(); - const prepare = vi.fn(profile.prepare); - const sign = vi.fn(owner.sign); - if (phase === "prepare") prepare.mockRejectedValueOnce(new Error("private host failure")); - else sign.mockRejectedValueOnce(new Error("private host failure")); - const document = await openDocument({ - bytes, - mode: "draft", - model: model(), - system: { ...profile, prepare }, - signer: { ...owner, sign }, - }); - value(await document.dispatch("set", set("retry", "saved intent"))); - const staged = document.draft(); - const state = document.state(); - expect(await document.commit()).toMatchObject( - failure(phase === "prepare" ? "SYSTEM_FAILED" : "SIGNING_FAILED"), - ); - expect(document.export()).toEqual(bytes); - expect(document.state()).toEqual(state); - expect(document.draft()).toEqual(staged); - if (phase === "prepare") expect(sign).not.toHaveBeenCalled(); - value(await document.commit()); - expect(document.draft()).toBeNull(); - expect(document.state()).toMatchObject({ projection: { values: { retry: "saved intent" } } }); - } -}); - -test("candidate authentication failure and late model rejection never publish or discard the draft", async () => { - const owner = await ownerIdentity(); - const bytes = (await create(owner)).export(); - for (const phase of ["authentication", "model"] as const) { - let reject = false; - const definition = model(); - const reduce = definition.reduce; - definition.reduce = (state, event, facts) => - reject && phase === "model" ? issue("CANDIDATE_REJECTED") : reduce(state, event, facts); - const profile = createStandardSystemProfile(); - const system = { - ...profile, - async prepare(input: Parameters[0]) { - const prepared = await profile.prepare(input); - if (!prepared.ok || !reject || phase !== "authentication") return prepared; - const entries = prepared.value.map((entry) => structuredClone(entry)); - for (const entry of entries) - if (entry.kind === "application") entry.payload.ciphertext = "AA"; - return { ok: true as const, value: entries }; - }, - }; - const document = await openDocument({ - bytes, - signer: owner, - mode: "draft", - model: definition, - system, - }); - value(await document.dispatch("set", set("atomic", "only after complete replay"))); - const draft = document.draft(); - const beforeState = document.state(); - reject = true; - expect(await document.commit()).toMatchObject( - failure(phase === "authentication" ? "DECRYPTION_INVALID" : "MODEL_TRANSITION_INVALID"), - ); - expect(document.export()).toEqual(bytes); - expect(document.state()).toEqual(beforeState); - expect(document.draft()).toEqual(draft); - reject = false; - value(await document.commit()); - expect(document.draft()).toBeNull(); - expect(document.state()).toMatchObject({ - projection: { values: { atomic: "only after complete replay" } }, - }); - } -}); - -test("commit captures metadata before queueing and pending signing exposes committed reads only", async () => { - const owner = await ownerIdentity(); - const bytes = (await create(owner)).export(); - let release!: () => void; - let entering!: () => void; - const waiting = new Promise((resolve) => { - release = resolve; - }); - const entered = new Promise((resolve) => { - entering = resolve; - }); - const sign = vi.fn(async (message: Uint8Array) => { - entering(); - await waiting; - return owner.sign(message); - }); - const document = await openDraft(bytes, { ...owner, sign }); - value(await document.dispatch("set", set("serial", "first"))); - const metadata: JsonObject = { label: "captured", nested: { revision: 1 } }; - const commit = document.commit(metadata); - metadata.label = "mutated"; - (metadata.nested as JsonObject).revision = 2; - await entered; - const queued = document.dispatch("set", set("serial", "second")); - expect(document.export()).toEqual(bytes); - expect(document.state()).toMatchObject({ projection: { values: {}, order: [] } }); - expect(value(await document.replay()).projection).toEqual({ values: {}, order: [] }); - expect(document.inspect().entries).toEqual([]); - expect(document.draft()!.preview.values.serial).toBe("first"); - release(); - const receipt = value(await commit); - expect(value(await queued)).toMatchObject({ - status: "staged", - baseHead: receipt.head, - entryCount: 1, - }); - expect(wire(document.export()).commits.at(-1)!.subject.metadata).toEqual({ - label: "captured", - nested: { revision: 1 }, - }); - expect(document.state()).toMatchObject({ projection: { values: { serial: "first" } } }); - expect(document.draft()!.preview.values.serial).toBe("second"); - value(await document.commit()); - expect(sign).toHaveBeenCalledTimes(2); - expect(document.state()).toMatchObject({ projection: { values: { serial: "second" } } }); -}); - -test("model reentry is rejected during preview without deadlocking or staging its nested command", async () => { - const owner = await ownerIdentity(); - const bytes = (await create(owner)).export(); - const definition = model(); - const decide = definition.commands.set.decide; - let document!: DocumentHandle; - let nested: Promise | undefined; - definition.commands.set.decide = (input, state, context) => { - nested = document.dispatch("set", set("nested", "must not stage")); - return decide(input, state, context); - }; - document = await openDraft(bytes, owner, definition); - value(await document.dispatch("set", set("outer", "staged"))); - expect(await nested).toMatchObject(failure("HOST_CONFIGURATION")); - expect(document.draft()!.entryCount).toBe(1); - expect(document.draft()!.preview.values).toEqual({ outer: "staged" }); -}); - -test("draft count, metadata and JSON depth limits fail atomically before signing", async () => { - const owner = await ownerIdentity(); - const bytes = (await create(owner)).export(); - const sign = vi.fn(owner.sign); - const document = await openDocument({ - bytes, - signer: { ...owner, sign }, - mode: "draft", - model: model(), - system: createStandardSystemProfile(), - limits: { maxEntries: 2, maxMetadataBytes: 256, maxDepth: 16 }, - }); - value(await document.dispatch("set", set("one", "within entry bound"))); - const before = document.draft(); - expect(await document.dispatch("set", set("two", "over entry bound"))).toMatchObject( - failure("RESOURCE_LIMIT"), - ); - expect(await document.commit({ oversized: "x".repeat(512) })).toMatchObject( - failure("RESOURCE_LIMIT"), - ); - let nested: JsonObject = {}; - for (let index = 0; index < 20; index++) nested = { nested }; - expect( - await document.dispatch("set", { ...set("deep", "no publication"), nested } as Input), - ).toMatchObject(failure("RESOURCE_LIMIT")); - expect(document.draft()).toEqual(before); - expect(document.export()).toEqual(bytes); - expect(sign).not.toHaveBeenCalled(); - value(await document.commit({ note: "within bound" })); - expect(sign).toHaveBeenCalledOnce(); -}); - -test("candidate byte bounds preserve a valid preview and invalid metadata never runs getters", async () => { - const owner = await ownerIdentity(); - const bytes = (await create(owner)).export(); - const sign = vi.fn(owner.sign); - const document = await openDocument({ - bytes, - signer: { ...owner, sign }, - mode: "draft", - model: model(), - system: createStandardSystemProfile(), - limits: { maxBytes: bytes.length + 256 }, - }); - value( - await document.dispatch("set", set("bounded", "candidate expands beyond available wire bytes")), - ); - const before = document.draft(); - const getter = vi.fn(() => "do not evaluate host accessors"); - const metadata: JsonObject = {}; - Object.defineProperty(metadata, "secret", { enumerable: true, get: getter }); - expect(await document.commit(metadata)).toMatchObject(failure("SCHEMA_INVALID")); - expect(getter).not.toHaveBeenCalled(); - expect(await document.commit()).toMatchObject(failure("RESOURCE_LIMIT")); - expect(document.export()).toEqual(bytes); - expect(document.draft()).toEqual(before); - expect(sign).not.toHaveBeenCalled(); -}); - -test("a null draft preview is passed to the next decision instead of the committed projection", async () => { - type NullState = string | null; - type NullCommands = { clear: {}; append: { value: string } }; - type NullEvent = { type: "draft.replace"; version: 1; data: { value: NullState } }; - const definition = defineModel({ - ref: { id: "concord.test.null-draft", version: 1 }, - initial: () => "committed", - commands: { - clear: { - validate: () => success({}), - decide: () => success([{ type: "draft.replace", version: 1, data: { value: null } }]), - }, - append: { - validate: (input) => - input && - typeof input === "object" && - typeof (input as { value: unknown }).value === "string" - ? success({ value: (input as { value: string }).value }) - : issue("INPUT_INVALID"), - decide: (input, state) => - success([ - { - type: "draft.replace", - version: 1, - data: { value: `${state === null ? "null" : "stale"}:${input.value}` }, - }, - ]), - }, - }, - validateEvent: (input) => success(input as NullEvent), - requirements: () => ["write"], - reduce: (_state, event) => success(event.data.value), - }); - const document = value( - await createDocument({ - identity: await ownerIdentity(), - model: definition, - system: createStandardSystemProfile(), - mode: "draft", - }), - ); - value(await document.dispatch("clear", {})); - expect(document.draft()!.preview).toBeNull(); - value(await document.dispatch("append", { value: "next" })); - expect(document.draft()).toMatchObject({ entryCount: 2, preview: "null:next" }); - expect(document.state()).toMatchObject({ projection: "committed" }); - value(await document.commit()); - expect(document.state()).toMatchObject({ projection: "null:next" }); -}); - -test("prospective commit limits and invalid outer domain events fail before adding pending work", async () => { - const owner = await ownerIdentity(); - const bytes = (await create(owner)).export(); - const sign = vi.fn(owner.sign); - const limited = await openDocument({ - bytes, - signer: { ...owner, sign }, - model: model(), - system: createStandardSystemProfile(), - mode: "draft", - limits: { maxCommits: 1 }, - }); - expect( - await limited.dispatch("set", set("blocked", "would require a second commit")), - ).toMatchObject(failure("RESOURCE_LIMIT")); - expect(limited.export()).toEqual(bytes); - expect(limited.draft()).toBeNull(); - expect(sign).not.toHaveBeenCalled(); - - const definition = model(); - const validateEvent = definition.validateEvent; - let malformed = false; - definition.validateEvent = (input) => { - const result = validateEvent(input); - return result.ok && malformed - ? success({ ...result.value, version: 0 } as unknown as Event) - : result; - }; - const document = await openDraft(bytes, { ...owner, sign }, definition); - value(await document.dispatch("set", set("kept", "valid pending input"))); - const before = document.draft(); - malformed = true; - expect(await document.dispatch("set", set("bad", "invalid event envelope"))).toMatchObject( - failure("EVENT_INVALID"), - ); - expect(document.draft()).toEqual(before); - expect(document.export()).toEqual(bytes); - expect(sign).not.toHaveBeenCalled(); -}); - -test("an independently authorized writer stages and commits against readable coverage without unlocking hidden audiences", async () => { - const owner = await ownerIdentity(); - const writer = value(await identityFromSeed(new Uint8Array(32).fill(2))); - const immediate = await create(owner); - const own = value(await createGroup(immediate)).audience; - const hidden = value(await createGroup(immediate)).audience; - value(await immediate.dispatch("set", set("default", "default private content"))); - value(await immediate.dispatch("set", set("hidden", "hidden private content", hidden))); - value(await immediate.dispatch("set", set("own", "visible history", own))); - value( - await setMember(immediate, { - audience: own, - identity: writer.publicIdentity, - capabilities: ["read", "write"], - }), - ); - const definition = model(); - definition.reduceLocked = (state, entry) => - success({ - values: { ...state.values }, - order: [...state.order, `locked:${entry.audience}:${entry.epoch}`], - }); - const document = await openDraft(immediate.export(), writer, definition); - const before = document.export(); - expect(document.state()).toMatchObject({ - status: "ready", - canWrite: true, - coverage: "readable", - lockedEntries: 2, - projection: { values: { own: "visible history" } }, - }); - expect( - document - .inspect() - .audiences!.find(({ audience }) => audience === "document")! - .members.some(({ identity }) => identity.id === writer.publicIdentity.id), - ).toBe(false); - value(await document.dispatch("set", set("own", "staged independently", own))); - const draft = document.draft()!; - expect(draft.preview).toEqual({ - values: { own: "staged independently" }, - order: [ - "locked:document:0", - `locked:${hidden}:0`, - `${own}:visible history`, - `${own}:staged independently`, - ], - }); - for (const audience of ["document", hidden] as const) { - expect( - await document.dispatch("set", set("denied", "cannot cross authority", audience)), - ).toMatchObject(failure("CAPABILITY_DENIED")); - expect(document.draft()).toEqual(draft); - expect(document.export()).toEqual(before); - } - value(await document.commit()); - expect(document.draft()).toBeNull(); - expect(document.state()).toMatchObject({ - projection: draft.preview, - coverage: "readable", - lockedEntries: 2, - canWrite: true, - }); - expect(value(await document.replay())).toEqual({ - projection: draft.preview, - coverage: "readable", - lockedEntries: 2, - }); - expect(document.inspect()).toMatchObject({ application: "scoped", lockedEntries: 2 }); - expect(document.inspect().entries!.map(({ status }) => status)).toEqual([ - "locked", - "locked", - "readable", - "readable", - ]); -}); - -test("later metadata named concord cannot replace the immutable genesis framework declaration", async () => { - const owner = await ownerIdentity(); - const document = await openDraft((await create(owner)).export(), owner); - const genesis = wire(document.export()).commits[0].subject.metadata; - value(await document.dispatch("set", set("metadata", "same model and system"))); - const metadata = { - concord: { - model: { id: "other.model", version: 9 }, - system: { id: "other.system", version: 9 }, - }, - note: "ordinary signed commit metadata", - }; - value(await document.commit(metadata)); - const raw = wire(document.export()); - expect(raw.commits[0].subject.metadata).toEqual(genesis); - expect(raw.commits.at(-1)!.subject.metadata).toEqual(metadata); - expect(document.state()).toMatchObject({ - status: "ready", - projection: { values: { metadata: "same model and system" } }, - }); - const reopened = await openDraft(document.export(), owner); - expect(reopened.state()).toEqual(document.state()); -}); diff --git a/packages/concord/test/fixtures.ts b/packages/concord/test/fixtures.ts deleted file mode 100644 index f55c1bc..0000000 --- a/packages/concord/test/fixtures.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { readFileSync } from "node:fs"; -import { createHash, createPrivateKey, sign } from "node:crypto"; -import type { - Json, - Snapshot, - CommitSubject, - EntrySubject, - RawEntrySubject, - SystemEvent, - ProtectedEvent, -} from "../src/protocol/index.js"; -export function vector(name: string): T { - return JSON.parse( - readFileSync(new URL(`../../../docs/concord/vectors/${name}.json`, import.meta.url), "utf8"), - ) as T; -} -export const seed = Uint8Array.from( - Buffer.from("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "hex"), -); -// Independent fixture author: Node crypto and a small encoder for trusted test values. -export function reference(value: unknown): string { - if (value === null || typeof value !== "object") return JSON.stringify(value); - if (Array.isArray(value)) return `[${value.map(reference).join(",")}]`; - return `{${Object.keys(value) - .sort() - .map((key) => `${JSON.stringify(key)}:${reference((value as Record)[key])}`) - .join(",")}}`; -} -export const encoded = (value: unknown) => new TextEncoder().encode(reference(value)); -export const base64 = (value: Uint8Array) => Buffer.from(value).toString("base64url"); -export const decoded = (value: string) => new Uint8Array(Buffer.from(value, "base64url")); -export function hash(subject: RawEntrySubject, kind: "entry"): `entry:${string}`; -export function hash(subject: CommitSubject, kind: "commit"): `commit:${string}`; -export function hash( - subject: RawEntrySubject | CommitSubject, - kind: "entry" | "commit", -): `entry:${string}` | `commit:${string}` { - return `${kind}:${createHash("sha256").update(`ledger.${kind}/1\0`).update(reference(subject)).digest("hex")}`; -} -export function referenceSignature(subject: CommitSubject, seedBytes: Uint8Array): string { - const key = createPrivateKey({ - key: Buffer.concat([ - Buffer.from("302e020100300506032b657004220420", "hex"), - Buffer.from(seedBytes), - ]), - format: "der", - type: "pkcs8", - }); - return sign(null, Buffer.from(`ledger.signature/1\0${reference(subject)}`), key).toString( - "base64url", - ); -} -export function resign(wire: Snapshot): Snapshot { - let index = 0; - for (let i = 0; i < wire.commits.length; i++) { - const commit = wire.commits[i]; - const subjects = commit.subject.entryIds.map(() => wire.entries[index++]); - commit.subject.entryIds = subjects.map((entry) => { - entry.id = hash(entry.subject, "entry"); - return entry.id; - }); - commit.id = hash(commit.subject, "commit"); - commit.signature = referenceSignature(commit.subject, seed); - } - wire.documentId = wire.commits[0].id; - wire.head = wire.commits.at(-1)!.id; - return wire; -} -export type Mutation = { - id: string; - operations: { op: string; path: string; from?: string; value?: Json }[]; - expected: { integrity: string; code: string }; -}; -export function mutate(source: Snapshot, operations: Mutation["operations"]): Snapshot { - const root = structuredClone(source) as unknown as Json; - function location(pointer: string): { parent: Json[] | Record; key: string } { - const parts = pointer - .slice(1) - .split("/") - .map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~")); - let parent = root; - for (const part of parts.slice(0, -1)) parent = (parent as Record)[part]; - return { parent: parent as Json[] | Record, key: parts.at(-1)! }; - } - function remove(pointer: string): Json { - const { parent, key } = location(pointer); - if (Array.isArray(parent)) return parent.splice(Number(key), 1)[0]; - const value = parent[key]; - delete parent[key]; - return value; - } - for (const operation of operations) { - if (operation.op === "remove") { - remove(operation.path); - continue; - } - const value = - operation.op === "move" ? remove(operation.from!) : structuredClone(operation.value!); - const { parent, key } = location(operation.path); - if (Array.isArray(parent) && operation.op !== "replace") - parent.splice(key === "-" ? parent.length : Number(key), 0, value); - else (parent as Record)[key] = value; - } - return root as unknown as Snapshot; -} - -// Test adapters expose the signed raw payload explicitly; no logical view is hashed. -export function frameworkSubject(subject: RawEntrySubject): EntrySubject { - return { - version: 1, - parent: subject.parent, - nonce: subject.nonce, - kind: subject.kind, - payload: subject.payload.data, - } as EntrySubject; -} -export function systemPayload(subject: RawEntrySubject): SystemEvent { - if (subject.kind !== "system") throw new Error("Expected raw system entry"); - return subject.payload.data as SystemEvent; -} -export function protectedPayload(subject: RawEntrySubject): ProtectedEvent { - if (subject.kind !== "application") throw new Error("Expected raw application entry"); - return subject.payload.data as ProtectedEvent; -} -export function rawSubject( - subject: EntrySubject | RawEntrySubject, - signer: import("@ternent/armour").IdentityCapability, - parent: CommitSubject["parent"], -): RawEntrySubject { - return "author" in subject - ? { ...subject, parent, author: signer.publicIdentity.id } - : { - version: 1, - parent, - nonce: subject.nonce, - kind: subject.kind, - author: signer.publicIdentity.id, - authoredAt: "2026-11-20T00:00:00.000Z", - meta: null, - payload: { type: "plain", data: subject.payload }, - }; -} diff --git a/packages/concord/test/groups.test.ts b/packages/concord/test/groups.test.ts deleted file mode 100644 index 05591c0..0000000 --- a/packages/concord/test/groups.test.ts +++ /dev/null @@ -1,1150 +0,0 @@ -import { createHash } from "node:crypto"; -import { expect, test, vi } from "vite-plus/test"; -import { identityFromSeed, type IdentityCapability } from "@ternent/armour"; -import { - createDocument, - defineModel, - openDocument, - type ApplicationModel, - type AudienceId, - type CommitSubject, - type EntrySubject, - type RawEntrySubject, - type ModelIssue, - type ProjectionResult, - type Result, - type Snapshot, -} from "../src/index.js"; -import { verifyDocument } from "../src/protocol/index.js"; -import { - createGroup, - createStandardSystemProfile, - removeMember, - setMember, -} from "../src/system/index.js"; -import { - base64, - encoded, - hash, - referenceSignature, - seed, - vector, - frameworkSubject, - rawSubject, -} from "./fixtures.js"; - -type Input = { audience: string; key: string; value: string; admin: boolean }; -type Commands = { put: Input; cross: Input & { other: string } }; -type Event = { type: "group.value"; version: 1; data: Input }; -type State = { values: Record; locked: string[]; actors: string[] }; -type Model = ApplicationModel; - -const success = (value: T): Result => ({ ok: true, value }); -const failure = (code: string) => ({ ok: false, error: { code } }); -function value(result: { ok: true; value: T } | { ok: false; error: { code: string } }): T { - if (!result.ok) throw new Error(result.error.code); - return result.value; -} -const identitySeed = (number: number) => new Uint8Array(32).fill(number); -const identity = async (number: number) => value(await identityFromSeed(identitySeed(number))); -const ownerIdentity = async () => value(await identityFromSeed(seed)); -const wire = (bytes: Uint8Array): Snapshot => - JSON.parse(new TextDecoder().decode(bytes)) as Snapshot; -const put = (audience: AudienceId, key: string, text: string, admin = false): Input => ({ - audience, - key, - value: text, - admin, -}); - -function input(candidate: unknown): Result { - if (!candidate || typeof candidate !== "object") - return { ok: false, error: { code: "INPUT_INVALID", message: "Expected group input" } }; - const record = candidate as Record; - if ( - typeof record.audience !== "string" || - typeof record.key !== "string" || - typeof record.value !== "string" || - typeof record.admin !== "boolean" - ) - return { ok: false, error: { code: "INPUT_INVALID", message: "Expected group fields" } }; - return success({ - audience: record.audience, - key: record.key, - value: record.value, - admin: record.admin, - }); -} - -function mapModel(scoped = true): Model { - return defineModel({ - ref: { id: "concord.test.independent-groups", version: 1 }, - initial: () => ({ values: {}, locked: [], actors: [] }), - commands: { - put: { - validate: input, - audience: (selected) => selected.audience as AudienceId, - decide: (selected) => success([{ type: "group.value", version: 1, data: selected }]), - }, - cross: { - validate(candidate) { - const checked = input(candidate); - if (!checked.ok) return checked; - if (typeof (candidate as Record).other !== "string") - return { ok: false, error: { code: "INPUT_INVALID", message: "Missing audience" } }; - return success({ ...checked.value, other: (candidate as { other: string }).other }); - }, - audience: (selected) => selected.audience as AudienceId, - decide: ({ other, ...selected }) => - success([ - { type: "group.value", version: 1, data: selected }, - { type: "group.value", version: 1, data: { ...selected, audience: other } }, - ]), - }, - }, - validateEvent(candidate) { - if (!candidate || typeof candidate !== "object") - return { ok: false, error: { code: "EVENT_INVALID", message: "Expected an event" } }; - const event = candidate as Record; - const checked = input(event.data); - if (event.type !== "group.value" || event.version !== 1 || !checked.ok) - return { ok: false, error: { code: "EVENT_INVALID", message: "Invalid group event" } }; - return success({ type: "group.value", version: 1, data: checked.value }); - }, - audience: (event) => event.data.audience as AudienceId, - requirements: (event) => (event.data.admin ? ["administer"] : ["write"]), - reduce: (state, event, facts) => - success({ - values: { ...state.values, [event.data.key]: event.data.value }, - locked: [...state.locked], - actors: [...state.actors, `${facts.audience}:${facts.actor.id}`], - }), - ...(scoped - ? { - reduceLocked: (state: Readonly, entry: { audience: AudienceId; epoch: number }) => - success({ - values: { ...state.values }, - locked: [...state.locked, `${entry.audience}:${entry.epoch}`], - actors: [...state.actors], - }), - } - : {}), - }); -} - -const create = async (owner: IdentityCapability, model = mapModel()) => - value(await createDocument({ identity: owner, model, system: createStandardSystemProfile() })); -const open = (bytes: Uint8Array, signer?: IdentityCapability, model = mapModel()) => - openDocument({ bytes, signer, model, system: createStandardSystemProfile() }); - -function append( - bytes: Uint8Array, - prepared: EntrySubject | RawEntrySubject, - signer: IdentityCapability, - signerSeed: Uint8Array, -): Uint8Array { - const snapshot = wire(bytes); - const subject = rawSubject(prepared, signer, snapshot.head); - const entry = { id: hash(subject, "entry"), subject }; - const commit: CommitSubject = { - version: 1, - suite: "ledger-ed25519-v1", - committedAt: "2026-11-20T00:00:00.000Z", - parent: snapshot.head, - nonce: base64(new Uint8Array(16).fill(101)), - signer: signer.publicIdentity, - entryIds: [entry.id], - metadata: null, - }; - snapshot.head = hash(commit, "commit"); - snapshot.commits.push({ - id: snapshot.head, - subject: commit, - signature: referenceSignature(commit, signerSeed), - }); - snapshot.entries.push(entry); - return encoded(snapshot); -} - -test("G01-G04 writers create independent groups and owners cannot grant themselves access", async () => { - const [owner, writer, outsider] = await Promise.all([ownerIdentity(), identity(2), identity(3)]); - const document = await create(owner); - value(await document.dispatch("put", put("document", "default", "default history"))); - value( - await setMember(document, { identity: writer.publicIdentity, capabilities: ["read", "write"] }), - ); - const authored = await open(document.export(), writer); - const accounts = value(await createGroup(authored)).audience; - const notes = value(await createGroup(authored)).audience; - expect(accounts).not.toBe(notes); - value(await authored.dispatch("put", put(accounts, "accounts", "accounts history"))); - value(await authored.dispatch("put", put(notes, "notes", "private notes"))); - value( - await setMember(authored, { - audience: accounts, - identity: outsider.publicIdentity, - capabilities: ["read", "write"], - }), - ); - - const ownerView = await open(authored.export(), owner); - expect(ownerView.state()).toMatchObject({ - status: "ready", - coverage: "readable", - lockedEntries: 2, - projection: { values: { default: "default history" } }, - }); - const saved = ownerView.export(); - expect( - await setMember(ownerView, { - audience: accounts, - identity: owner.publicIdentity, - capabilities: ["read", "write", "grant", "administer"], - }), - ).toMatchObject(failure("CAPABILITY_DENIED")); - expect(ownerView.export()).toEqual(saved); - - const member = await open(authored.export(), outsider); - expect(member.state()).toMatchObject({ - status: "ready", - canWrite: true, - coverage: "readable", - lockedEntries: 2, - projection: { values: { accounts: "accounts history" } }, - }); - const audiences = member.inspect().audiences!; - expect( - audiences - .find(({ audience }) => audience === "document")! - .members.some(({ identity: enrolled }) => enrolled.id === outsider.publicIdentity.id), - ).toBe(false); - expect(await createGroup(member)).toMatchObject(failure("CAPABILITY_DENIED")); - value(await member.dispatch("put", put(accounts, "accounts", "outsider can contribute"))); - expect((await open(member.export(), writer)).state()).toMatchObject({ - projection: { values: { accounts: "outsider can contribute", notes: "private notes" } }, - }); -}); - -test("G05 default membership removal preserves independent group write and keys", async () => { - const [owner, writer] = await Promise.all([ownerIdentity(), identity(2)]); - const document = await create(owner); - value( - await setMember(document, { identity: writer.publicIdentity, capabilities: ["read", "write"] }), - ); - const writerView = await open(document.export(), writer); - const group = value(await createGroup(writerView)).audience; - value(await writerView.dispatch("put", put(group, "group", "before default removal"))); - const adminView = await open(writerView.export(), owner); - value(await removeMember(adminView, { identityId: writer.publicIdentity.id })); - value(await adminView.dispatch("put", put("document", "default", "new default epoch"))); - - const removed = await open(adminView.export(), writer); - expect(removed.state()).toMatchObject({ status: "ready", canWrite: true, lockedEntries: 1 }); - expect( - removed.inspect().audiences!.find(({ audience }) => audience === group)!.epochs, - ).toHaveLength(1); - expect(await removed.dispatch("put", put("document", "default", "denied"))).toMatchObject( - failure("CAPABILITY_DENIED"), - ); - expect(await createGroup(removed)).toMatchObject(failure("CAPABILITY_DENIED")); - value(await removed.dispatch("put", put(group, "group", "still independently authorized"))); - expect(removed.state()).toMatchObject({ - projection: { values: { group: "still independently authorized" } }, - }); -}); - -test("G06-G09 removal rotates only its group and readmission grants every saved epoch", async () => { - const [owner, member] = await Promise.all([ownerIdentity(), identity(2)]); - const document = await create(owner); - const accounts = value(await createGroup(document)).audience; - const notes = value(await createGroup(document)).audience; - for (const audience of [accounts, notes]) { - value( - await setMember(document, { - audience, - identity: member.publicIdentity, - capabilities: ["read", "write"], - }), - ); - } - value(await document.dispatch("put", put(accounts, "old", "historical plaintext"))); - value(await removeMember(document, { audience: accounts, identityId: member.publicIdentity.id })); - value(await document.dispatch("put", put(accounts, "new", "future account plaintext"))); - value(await document.dispatch("put", put(notes, "notes", "independent plaintext"))); - const saved = document.export(); - const removed = await open(saved, member); - expect(removed.state()).toMatchObject({ - status: "ready", - coverage: "readable", - canWrite: true, - lockedEntries: 1, - projection: { values: { old: "historical plaintext", notes: "independent plaintext" } }, - }); - const current = removed.inspect().audiences!; - expect( - current.find(({ audience }) => audience === accounts)!.epochs.map(({ epoch }) => epoch), - ).toEqual([0, 1]); - expect( - current.find(({ audience }) => audience === notes)!.epochs.map(({ epoch }) => epoch), - ).toEqual([0]); - expect( - current.find(({ audience }) => audience === "document")!.epochs.map(({ epoch }) => epoch), - ).toEqual([0]); - expect(await removed.dispatch("put", put(accounts, "denied", "denied"))).toMatchObject( - failure("CAPABILITY_DENIED"), - ); - value(await removed.dispatch("put", put(notes, "notes", "notes remain writable"))); - - value( - await setMember(document, { - audience: accounts, - identity: member.publicIdentity, - capabilities: ["read", "write"], - }), - ); - const last = frameworkSubject(wire(document.export()).entries.at(-1)!.subject); - expect(last.payload).toMatchObject({ - type: "system.member.set", - data: { audience: accounts, history: [{ epoch: 0 }, { epoch: 1 }] }, - }); - const readmitted = await open(document.export(), member); - expect(readmitted.state()).toMatchObject({ - status: "ready", - coverage: "complete", - lockedEntries: 0, - projection: { - values: { - old: "historical plaintext", - new: "future account plaintext", - notes: "independent plaintext", - }, - }, - }); - expect((await open(saved, member)).state()).toMatchObject({ - coverage: "readable", - lockedEntries: 1, - }); -}); - -test("G10 identical saved bytes replay deterministically with explicit coverage and ordered markers", async () => { - const [owner, reader] = await Promise.all([ownerIdentity(), identity(2)]); - const document = await create(owner); - value(await setMember(document, { identity: reader.publicIdentity, capabilities: ["read"] })); - const hidden = value(await createGroup(document)).audience; - value(await document.dispatch("put", put("document", "first", "visible first"))); - value(await document.dispatch("put", put(hidden, "secret", "not readable"))); - value(await document.dispatch("put", put("document", "last", "visible last"))); - const saved = document.export(); - const first = await open(saved, reader); - const second = await open(saved, reader); - const firstReplay = value(await first.replay()); - expect(firstReplay).toEqual(value(await second.replay())); - expect(firstReplay).toMatchObject({ - coverage: "readable", - lockedEntries: 1, - projection: { - values: { first: "visible first", last: "visible last" }, - locked: [`${hidden}:0`], - actors: [`document:${owner.publicIdentity.id}`, `document:${owner.publicIdentity.id}`], - }, - }); - expect(first.state()).toMatchObject(firstReplay); - expect(first.inspect()).toMatchObject({ - system: "valid", - application: "scoped", - lockedEntries: 1, - }); - expect(first.inspect().entries!.map(({ status }) => status)).toEqual([ - "readable", - "locked", - "readable", - ]); - expect(first.inspect().entries!.map(({ entryId }) => entryId)).toEqual( - wire(saved) - .entries.filter(({ subject }) => subject.kind === "application") - .map(({ id }) => id), - ); - const marker = first.inspect().entries![1]; - expect(marker.facts.audience).toBe(hidden); - expect(marker.facts.actor.id).toBe(owner.publicIdentity.id); - expect("event" in marker).toBe(false); - expect(first.export()).toEqual(saved); -}); - -test("G11 full models stop before callbacks while opted-in models expose locked read-only coverage", async () => { - const [owner, outsider] = await Promise.all([ownerIdentity(), identity(2)]); - const document = await create(owner); - value(await document.dispatch("put", put("document", "secret", "private"))); - const model = mapModel(false); - model.initial = vi.fn(model.initial); - model.reduce = vi.fn(model.reduce); - const full = await open(document.export(), outsider, model); - expect(full.state()).toEqual({ status: "inspection", reason: "locked" }); - expect(model.initial).not.toHaveBeenCalled(); - expect(model.reduce).not.toHaveBeenCalled(); - expect(full.inspect().entries).toMatchObject([ - { status: "locked", audience: "document", epoch: 0 }, - ]); - - const scoped = await open(document.export(), outsider); - expect(scoped.state()).toMatchObject({ - status: "ready", - coverage: "readable", - lockedEntries: 1, - canWrite: false, - projection: { values: {}, locked: ["document:0"] }, - }); - expect(await scoped.dispatch("put", put("document", "secret", "denied"))).toMatchObject( - failure("CAPABILITY_DENIED"), - ); - const unsigned = await open(document.export()); - expect(unsigned.state()).toMatchObject({ - status: "ready", - coverage: "readable", - lockedEntries: 1, - canWrite: false, - }); - expect(await unsigned.dispatch("put", put("document", "secret", "denied"))).toMatchObject( - failure("READ_ONLY_RUNTIME"), - ); -}); - -test("G12 a command cannot cross audiences or bypass model capabilities and failures are atomic", async () => { - const [owner, writer] = await Promise.all([ownerIdentity(), identity(2)]); - const document = await create(owner); - const left = value(await createGroup(document)).audience; - const right = value(await createGroup(document)).audience; - value( - await setMember(document, { - audience: left, - identity: writer.publicIdentity, - capabilities: ["read", "write"], - }), - ); - const before = document.export(); - const state = document.state(); - expect( - await document.dispatch("cross", { ...put(left, "cross", "must be atomic"), other: right }), - ).toMatchObject(failure("EVENT_INVALID")); - expect(document.export()).toEqual(before); - expect(document.state()).toEqual(state); - const writerView = await open(before, writer); - expect(await writerView.dispatch("put", put(left, "admin", "denied", true))).toMatchObject( - failure("CAPABILITY_DENIED"), - ); - expect(writerView.export()).toEqual(before); - value(await writerView.dispatch("put", put(left, "allowed", "group writer"))); -}); - -test("G13 rejected locked-model passes keep readable evidence without publishing a projection", async () => { - const [owner, reader] = await Promise.all([ownerIdentity(), identity(2)]); - const document = await create(owner); - value(await setMember(document, { identity: reader.publicIdentity, capabilities: ["read"] })); - value(await document.dispatch("put", put("document", "visible", "inspectable evidence"))); - const hidden = value(await createGroup(document)).audience; - value(await document.dispatch("put", put(hidden, "hidden", "hidden transition"))); - const model = mapModel(); - model.reduceLocked = () => ({ - ok: false, - error: { code: "LOCKED_DEPENDENCY", message: "Missing model dependency" }, - }); - const rejected = await open(document.export(), reader, model); - expect(rejected.state()).toEqual({ status: "inspection", reason: "invalid" }); - expect(rejected.inspect()).toMatchObject({ system: "valid", application: "invalid" }); - expect(rejected.inspect().entries).toMatchObject([ - { status: "readable", event: { data: { value: "inspectable evidence" } } }, - { status: "locked", audience: hidden }, - ]); - expect(rejected.export()).toEqual(document.export()); -}); - -test("G14 hidden-group authority is checked before any reader decryption or model callbacks", async () => { - const [owner, writer, target] = await Promise.all([ownerIdentity(), identity(2), identity(3)]); - const document = await create(owner); - value( - await setMember(document, { identity: writer.publicIdentity, capabilities: ["read", "write"] }), - ); - const creator = await open(document.export(), writer); - const group = value(await createGroup(creator)).audience; - const before = creator.export(); - value( - await setMember(creator, { - audience: group, - identity: target.publicIdentity, - capabilities: ["read"], - }), - ); - const grant = wire(creator.export()).entries.at(-1)!.subject; - const forged = append(before, grant, owner, seed); - expect((await verifyDocument(forged)).integrity).toBe("valid"); - const model = mapModel(); - model.initial = vi.fn(model.initial); - model.reduce = vi.fn(model.reduce); - const decryptAge = vi.fn(owner.decryptAge); - const inspected = await openDocument({ - bytes: forged, - model, - system: createStandardSystemProfile(), - reader: { publicIdentity: owner.publicIdentity, decryptAge }, - }); - expect(inspected.inspect().findings).toMatchObject([{ code: "CAPABILITY_DENIED" }]); - expect(inspected.inspect().entries).toBeNull(); - expect(decryptAge).not.toHaveBeenCalled(); - expect(model.initial).not.toHaveBeenCalled(); - expect(model.reduce).not.toHaveBeenCalled(); -}); - -test("G15 ciphertext cannot be substituted between independently keyed groups", async () => { - const owner = await ownerIdentity(); - const document = await create(owner); - const first = value(await createGroup(document)).audience; - const second = value(await createGroup(document)).audience; - const before = document.export(); - value(await document.dispatch("put", put(first, "secret", "bound to first group"))); - const entry = frameworkSubject(wire(document.export()).entries.at(-1)!.subject); - if (entry.kind !== "application") throw new Error("Expected application entry"); - entry.payload.audience = second; - const substituted = append(before, entry, owner, seed); - expect((await verifyDocument(substituted)).integrity).toBe("valid"); - const model = mapModel(); - model.initial = vi.fn(model.initial); - model.reduce = vi.fn(model.reduce); - const inspected = await open(substituted, owner, model); - expect(inspected.inspect().findings).toMatchObject([{ code: "DECRYPTION_INVALID" }]); - expect(inspected.inspect().entries).toBeNull(); - expect(model.initial).not.toHaveBeenCalled(); - expect(model.reduce).not.toHaveBeenCalled(); -}); - -test("G16 protocol tampering never reaches either model replay path", async () => { - const owner = await ownerIdentity(); - const document = await create(owner); - const group = value(await createGroup(document)).audience; - value(await document.dispatch("put", put(group, "private", "untampered"))); - const corrupt = wire(document.export()); - const entry = frameworkSubject(corrupt.entries.at(-1)!.subject); - if (entry.kind !== "application") throw new Error("Expected application entry"); - entry.payload.ciphertext = "AA"; - const model = mapModel(); - model.initial = vi.fn(model.initial); - model.reduce = vi.fn(model.reduce); - model.reduceLocked = vi.fn(model.reduceLocked!); - const inspected = await open(encoded(corrupt), owner, model); - expect(inspected.state()).toEqual({ status: "inspection", reason: "invalid" }); - expect(inspected.inspect().verification.integrity).toBe("invalid"); - expect(inspected.inspect().entries).toBeNull(); - expect(model.initial).not.toHaveBeenCalled(); - expect(model.reduce).not.toHaveBeenCalled(); - expect(model.reduceLocked).not.toHaveBeenCalled(); -}); - -test("G17 readable event routing must match its signed audience during replay", async () => { - const owner = await ownerIdentity(); - const document = await create(owner); - const group = value(await createGroup(document)).audience; - value(await document.dispatch("put", put(group, "private", "group-bound event"))); - const model = mapModel(); - model.audience = () => "document"; - model.reduce = vi.fn(model.reduce); - const inspected = await open(document.export(), owner, model); - expect(inspected.state()).toEqual({ status: "inspection", reason: "invalid" }); - expect(inspected.inspect().findings).toMatchObject([{ code: "EVENT_INVALID" }]); - expect(inspected.inspect().entries).toMatchObject([ - { - status: "readable", - facts: { audience: group }, - event: { data: { value: "group-bound event" } }, - }, - ]); - expect(model.reduce).not.toHaveBeenCalled(); -}); - -test("a group administrator without write can manage only that group and retains final-admin protection", async () => { - const [owner, administrator, target] = await Promise.all([ - ownerIdentity(), - identity(2), - identity(3), - ]); - const document = await create(owner); - const group = value(await createGroup(document)).audience; - value(await document.dispatch("put", put(group, "history", "administrator can inspect"))); - value( - await setMember(document, { - audience: group, - identity: administrator.publicIdentity, - capabilities: ["read", "administer"], - }), - ); - const admin = await open(document.export(), administrator); - expect(admin.state()).toMatchObject({ - status: "ready", - canWrite: false, - coverage: "complete", - projection: { values: { history: "administrator can inspect" } }, - }); - const before = admin.export(); - expect(await admin.dispatch("put", put(group, "denied", "no write capability"))).toMatchObject( - failure("CAPABILITY_DENIED"), - ); - expect( - await setMember(admin, { - identity: target.publicIdentity, - capabilities: ["read"], - }), - ).toMatchObject(failure("CAPABILITY_DENIED")); - expect(admin.export()).toEqual(before); - value( - await setMember(admin, { - audience: group, - identity: target.publicIdentity, - capabilities: ["read"], - }), - ); - value(await removeMember(admin, { audience: group, identityId: target.publicIdentity.id })); - value(await removeMember(admin, { audience: group, identityId: owner.publicIdentity.id })); - const soleAdmin = admin.export(); - expect( - await setMember(admin, { - audience: group, - identity: administrator.publicIdentity, - capabilities: ["read", "write"], - }), - ).toMatchObject(failure("LAST_ADMINISTRATOR")); - expect( - await removeMember(admin, { audience: group, identityId: administrator.publicIdentity.id }), - ).toMatchObject(failure("LAST_ADMINISTRATOR")); - expect(admin.export()).toEqual(soleAdmin); - expect( - admin.inspect().audiences!.find(({ audience }) => audience === "document")!.members, - ).toMatchObject([{ identity: owner.publicIdentity }]); -}); - -test("command decisions receive selected-group facts and mixed routing stops before prepare or signing", async () => { - const [owner, writer] = await Promise.all([ownerIdentity(), identity(2)]); - const document = await create(owner); - const selected = value(await createGroup(document)).audience; - const other = value(await createGroup(document)).audience; - value( - await setMember(document, { - identity: writer.publicIdentity, - capabilities: ["read"], - }), - ); - value( - await setMember(document, { - audience: selected, - identity: writer.publicIdentity, - capabilities: ["read", "write"], - }), - ); - const model = mapModel(); - const decide = vi.fn(model.commands.cross.decide); - model.commands.cross.decide = decide; - const profile = createStandardSystemProfile(); - const prepare = vi.fn(profile.prepare); - const system = { ...profile, prepare }; - const sign = vi.fn(writer.sign); - const authored = await openDocument({ - bytes: document.export(), - signer: { ...writer, sign }, - model, - system, - }); - const before = authored.export(); - const beforeState = authored.state(); - expect( - await authored.dispatch("cross", { - ...put(selected, "mixed", "must not publish"), - other, - }), - ).toMatchObject(failure("EVENT_INVALID")); - expect(decide).toHaveBeenCalledOnce(); - expect(decide.mock.calls[0][2].facts).toMatchObject({ - audience: selected, - actor: writer.publicIdentity, - capabilities: ["read", "write"], - }); - expect(prepare).not.toHaveBeenCalled(); - expect(sign).not.toHaveBeenCalled(); - expect(authored.export()).toEqual(before); - expect(authored.state()).toEqual(beforeState); - value(await authored.dispatch("put", put(selected, "valid", "same group succeeds"))); - expect(prepare).toHaveBeenCalledOnce(); - expect(sign).toHaveBeenCalledOnce(); -}); - -async function systemRejection( - bytes: Uint8Array, - reader: IdentityCapability, - code: "SYSTEM_EVENT_INVALID" | "KEY_WRAP_INVALID", - decrypts = false, -) { - expect((await verifyDocument(bytes)).integrity).toBe("valid"); - const model = mapModel(); - model.initial = vi.fn(model.initial); - model.reduce = vi.fn(model.reduce); - model.reduceLocked = vi.fn(model.reduceLocked!); - const decryptAge = vi.fn(reader.decryptAge); - const inspected = await openDocument({ - bytes, - model, - system: createStandardSystemProfile(), - reader: { publicIdentity: reader.publicIdentity, decryptAge }, - }); - expect(inspected.state()).toEqual({ status: "inspection", reason: "invalid" }); - expect(inspected.inspect().findings).toMatchObject([{ code }]); - expect(inspected.inspect().entries).toBeNull(); - if (decrypts) expect(decryptAge).toHaveBeenCalled(); - else expect(decryptAge).not.toHaveBeenCalled(); - expect(model.initial).not.toHaveBeenCalled(); - expect(model.reduce).not.toHaveBeenCalled(); - expect(model.reduceLocked).not.toHaveBeenCalled(); -} - -function systemEntry(bytes: Uint8Array): Extract { - const entry = frameworkSubject(wire(bytes).entries.at(-1)!.subject); - if (entry.kind !== "system") throw new Error("Expected system entry"); - return entry; -} - -const unusedGroup = `group:${base64(new Uint8Array(16).fill(99))}` as const; - -test("re-signed group creation and membership reject duplicate, unknown, noncanonical and open shapes", async () => { - const [owner, newcomer] = await Promise.all([ownerIdentity(), identity(2)]); - const document = await create(owner); - const beforeCreation = document.export(); - const created = value(await createGroup(document)).audience; - const creation = systemEntry(document.export()); - const afterCreation = document.export(); - await systemRejection( - append(afterCreation, structuredClone(creation), owner, seed), - owner, - "SYSTEM_EVENT_INVALID", - ); - - for (const change of [ - (entry: typeof creation) => { - entry.payload.data.label = "must remain encrypted"; - }, - (entry: typeof creation) => { - entry.payload.data.audience = "group:noncanonical"; - }, - (entry: typeof creation) => { - entry.payload.data.audience = `group:${"A".repeat(21)}B`; - }, - (entry: typeof creation) => { - entry.payload.data.audience = "document"; - }, - (entry: typeof creation) => { - entry.payload.data.epoch = 1; - }, - ]) { - const altered = structuredClone(creation); - change(altered); - await systemRejection( - append(beforeCreation, altered, owner, seed), - owner, - "SYSTEM_EVENT_INVALID", - ); - } - - value( - await setMember(document, { - audience: created, - identity: newcomer.publicIdentity, - capabilities: ["read"], - }), - ); - const admission = systemEntry(document.export()); - for (const audience of [unusedGroup, "group:noncanonical"]) { - const altered = structuredClone(admission); - altered.payload.data.audience = audience; - await systemRejection( - append(afterCreation, altered, owner, seed), - owner, - "SYSTEM_EVENT_INVALID", - ); - } -}); - -test("re-signed create and rotation reject recipient reuse across every audience", async () => { - const [owner, member] = await Promise.all([ownerIdentity(), identity(2)]); - const document = await create(owner); - const defaultRecipient = systemEntry(document.export()).payload.data.recipient; - const first = value(await createGroup(document)).audience; - const firstRecipient = systemEntry(document.export()).payload.data.recipient; - const beforeSecond = document.export(); - const second = value(await createGroup(document)).audience; - const secondCreation = systemEntry(document.export()); - for (const recipient of [defaultRecipient, firstRecipient]) { - const altered = structuredClone(secondCreation); - altered.payload.data.recipient = recipient; - await systemRejection( - append(beforeSecond, altered, owner, seed), - owner, - "SYSTEM_EVENT_INVALID", - ); - } - - value( - await setMember(document, { - audience: first, - identity: member.publicIdentity, - capabilities: ["read"], - }), - ); - const beforeRotation = document.export(); - value(await removeMember(document, { audience: first, identityId: member.publicIdentity.id })); - const rotation = systemEntry(document.export()); - const secondRecipient = document.inspect().audiences!.find(({ audience }) => audience === second)! - .epochs[0].recipient; - for (const recipient of [defaultRecipient, firstRecipient, secondRecipient]) { - const altered = structuredClone(rotation); - altered.payload.data.recipient = recipient; - await systemRejection( - append(beforeRotation, altered, owner, seed), - owner, - "SYSTEM_EVENT_INVALID", - ); - } -}); - -test("addressed key wraps cannot be substituted across otherwise valid group creation envelopes", async () => { - const owner = await ownerIdentity(); - const document = await create(owner); - value(await createGroup(document)); - const first = systemEntry(document.export()); - const beforeSecond = document.export(); - value(await createGroup(document)); - const substituted = systemEntry(document.export()); - const firstWrap = (first.payload.data.wraps as { identityId: string; ciphertext: string }[])[0]; - const secondWrap = ( - substituted.payload.data.wraps as { identityId: string; ciphertext: string }[] - )[0]; - expect(firstWrap.identityId).toBe(secondWrap.identityId); - secondWrap.ciphertext = firstWrap.ciphertext; - await systemRejection( - append(beforeSecond, substituted, owner, seed), - owner, - "KEY_WRAP_INVALID", - true, - ); -}); - -test("custom profiles cannot omit, duplicate, reorder, misroute or inject payloads into locked entries", async () => { - const [owner, outsider] = await Promise.all([ownerIdentity(), identity(2)]); - const document = await create(owner); - const group = value(await createGroup(document)).audience; - value(await document.dispatch("put", put("document", "first", "default private event"))); - value(await document.dispatch("put", put(group, "second", "group private event"))); - const profile = createStandardSystemProfile(); - type Items = import("../src/system/index.js").ReplayItem[]; - const mutations: ((entries: Items) => void)[] = [ - (entries) => { - entries.pop(); - }, - (entries) => { - entries[1] = entries[0]; - }, - (entries) => { - entries.reverse(); - }, - (entries) => { - if (entries[0].status !== "locked") throw new Error("Expected locked entry"); - entries[0].audience = group; - }, - (entries) => { - entries[0].facts.audience = group; - }, - (entries) => { - Object.assign(entries[0], { - event: { - type: "group.value", - version: 1, - data: put("document", "invented", "fabricated plaintext"), - }, - }); - }, - ]; - for (const mutate of mutations) { - const model = mapModel(); - model.initial = vi.fn(model.initial); - model.reduce = vi.fn(model.reduce); - model.reduceLocked = vi.fn(model.reduceLocked!); - const altered = { - ...profile, - async replay(input: Parameters[0]) { - const result = await profile.replay(input); - if (!result.ok) return result; - const entries = result.value.entries.map((item) => structuredClone(item)); - expect(entries.every(({ status }) => status === "locked")).toBe(true); - mutate(entries); - return { ok: true as const, value: { ...result.value, entries } }; - }, - }; - const inspected = await openDocument({ - bytes: document.export(), - model, - system: altered, - reader: outsider, - }); - expect(inspected.inspect().verification.integrity).toBe("valid"); - expect(inspected.inspect().findings).toMatchObject([{ code: "SYSTEM_FAILED" }]); - expect(inspected.inspect().entries).toBeNull(); - expect(inspected.state()).toEqual({ status: "inspection", reason: "invalid" }); - expect(model.initial).not.toHaveBeenCalled(); - expect(model.reduce).not.toHaveBeenCalled(); - expect(model.reduceLocked).not.toHaveBeenCalled(); - } -}); - -test("fixed signed group vectors replay the same saved history for each reader and admission stage", async () => { - type Reader = "owner" | "creator" | "bob"; - type Stage = "removed" | "readmitted"; - const expected = vector<{ - audiences: { accounts: AudienceId; personal: AudienceId }; - readers: Record>>; - canWrite: Record; - canonicalSha256: Record; - heads: Record; - documentId: string; - }>("groups.expected"); - const readers = { - owner: await ownerIdentity(), - creator: await identity(2), - bob: await identity(3), - }; - for (const stage of ["removed", "readmitted"] as const) { - const bytes = encoded(vector(`groups.${stage}.document`)); - expect((await verifyDocument(bytes)).integrity).toBe("valid"); - expect(createHash("sha256").update(bytes).digest("hex")).toBe(expected.canonicalSha256[stage]); - expect(wire(bytes).head).toBe(expected.heads[stage]); - expect(wire(bytes).documentId).toBe(expected.documentId); - for (const name of ["owner", "creator", "bob"] as const) { - const first = await open(bytes, readers[name]); - const second = await open(bytes, readers[name]); - const projection = expected.readers[name][stage]; - expect(value(await first.replay())).toEqual(projection); - expect(value(await second.replay())).toEqual(projection); - const state = { - status: "ready", - documentId: expected.documentId, - head: expected.heads[stage], - canWrite: expected.canWrite[name], - ...projection, - }; - expect(first.state()).toEqual(state); - expect(second.state()).toEqual(state); - expect(first.inspect()).toMatchObject({ - system: "valid", - application: projection.coverage === "complete" ? "valid" : "scoped", - lockedEntries: projection.lockedEntries, - }); - expect( - first - .inspect() - .audiences!.map(({ audience }) => audience) - .sort(), - ).toEqual(["document", expected.audiences.accounts, expected.audiences.personal].sort()); - expect(first.export()).toEqual(bytes); - expect(second.export()).toEqual(bytes); - } - } -}); - -test("nested profile security records are closed and validated before inspection or model publication", async () => { - type Replay = import("../src/system/index.js").SystemReplay; - const owner = await ownerIdentity(); - const bytes = encoded(vector("groups.readmitted.document")); - const expected = vector<{ audiences: { accounts: AudienceId } }>("groups.expected"); - const profile = createStandardSystemProfile(); - const accounts = (output: Replay) => - output.audiences.find(({ audience }) => audience === expected.audiences.accounts)!; - const historical = (output: Replay) => - output.entryFacts.find( - ({ facts }) => facts.audience === expected.audiences.accounts && facts.members.length > 1, - )!.facts; - const cases: [string, (output: Replay) => void][] = [ - [ - "secret in an epoch", - (output) => { - Object.assign(accounts(output).epochs[0], { secret: "must stay private" }); - }, - ], - [ - "secret in a current member", - (output) => { - Object.assign(accounts(output).members[0], { secret: "must stay private" }); - }, - ], - [ - "secret in a historical member", - (output) => { - Object.assign(historical(output).members[0], { secret: "must stay private" }); - }, - ], - [ - "extra field in public identity", - (output) => { - Object.assign(accounts(output).members[0].identity, { secret: "must stay private" }); - }, - ], - [ - "member identity does not bind its key", - (output) => { - Object.assign(accounts(output).members[0].identity, { id: `identity:${"0".repeat(64)}` }); - }, - ], - [ - "historical identity does not bind its key", - (output) => { - Object.assign(historical(output).members[0].identity, { id: `identity:${"0".repeat(64)}` }); - }, - ], - [ - "member identity has an invalid point", - (output) => { - Object.assign(accounts(output).members[0].identity, { - publicKey: base64(new Uint8Array(32)), - }); - }, - ], - [ - "unknown member capability", - (output) => { - Object.assign(accounts(output).members[0], { capabilities: ["read", "imaginary"] }); - }, - ], - [ - "noncanonical member capabilities", - (output) => { - Object.assign(accounts(output).members[0], { capabilities: ["write", "read"] }); - }, - ], - [ - "duplicate member capabilities", - (output) => { - Object.assign(accounts(output).members[0], { capabilities: ["read", "read"] }); - }, - ], - [ - "member capabilities omit read", - (output) => { - Object.assign(accounts(output).members[0], { capabilities: ["write"] }); - }, - ], - [ - "noncanonical historical member capabilities", - (output) => { - Object.assign(historical(output).members[0], { capabilities: ["write", "read"] }); - }, - ], - [ - "noncanonical actor capabilities", - (output) => { - historical(output).capabilities = ["write", "read"]; - }, - ], - [ - "duplicate current members", - (output) => { - const group = accounts(output); - group.members = [...group.members, group.members[0]]; - }, - ], - [ - "unsorted current members", - (output) => { - const group = accounts(output); - group.members = [...group.members].reverse(); - }, - ], - [ - "duplicate historical members", - (output) => { - const facts = historical(output); - facts.members = [...facts.members, facts.members[0]]; - }, - ], - [ - "unsorted historical members", - (output) => { - const facts = historical(output); - facts.members = [...facts.members].reverse(); - }, - ], - [ - "invalid recipient", - (output) => { - accounts(output).epochs[0].recipient = "age1invalid"; - }, - ], - [ - "empty epoch sequence", - (output) => { - accounts(output).epochs = []; - }, - ], - [ - "epoch gap", - (output) => { - accounts(output).epochs[1].epoch = 9; - }, - ], - [ - "negative epoch", - (output) => { - accounts(output).epochs[0].epoch = -1; - }, - ], - [ - "fractional epoch", - (output) => { - accounts(output).epochs[0].epoch = 0.5; - }, - ], - [ - "duplicate epochs", - (output) => { - accounts(output).epochs[1].epoch = 0; - }, - ], - [ - "unsorted epochs", - (output) => { - const group = accounts(output); - group.epochs = [...group.epochs].reverse(); - }, - ], - ]; - for (const [name, mutate] of cases) { - const model = mapModel(); - model.initial = vi.fn(model.initial); - model.reduce = vi.fn(model.reduce); - model.reduceLocked = vi.fn(model.reduceLocked!); - const system = { - ...profile, - async replay(input: Parameters[0]) { - const result = await profile.replay(input); - if (!result.ok) return result; - const output = { ...structuredClone(result.value), session: result.value.session }; - mutate(output); - // Keep matching entry facts coherent so each failure exercises the nested boundary. - output.entries = output.entries.map((entry) => ({ - ...entry, - facts: output.entryFacts.find(({ entryId }) => entryId === entry.entryId)!.facts, - })); - return { ok: true as const, value: output }; - }, - }; - const inspected = await openDocument({ bytes, model, system, reader: owner }); - expect(inspected.inspect().verification.integrity, name).toBe("valid"); - expect(inspected.inspect().findings, name).toMatchObject([{ code: "SYSTEM_FAILED" }]); - expect(inspected.inspect().entries, name).toBeNull(); - expect(inspected.inspect().audiences, name).toBeNull(); - expect(inspected.state(), name).toEqual({ status: "inspection", reason: "invalid" }); - expect(model.initial, name).not.toHaveBeenCalled(); - expect(model.reduce, name).not.toHaveBeenCalled(); - expect(model.reduceLocked, name).not.toHaveBeenCalled(); - } -}); diff --git a/packages/concord/test/membership.test.ts b/packages/concord/test/membership.test.ts deleted file mode 100644 index e210b9d..0000000 --- a/packages/concord/test/membership.test.ts +++ /dev/null @@ -1,451 +0,0 @@ -import { expect, test, vi } from "vite-plus/test"; -import { encryptAge, identityFromSeed, type IdentityCapability } from "@ternent/armour"; -import { - createDocument, - openDocument, - type CommitSubject, - type EntrySubject, - type RawEntrySubject, - type Snapshot, -} from "../src/index.js"; -import { compareSnapshots, verifyDocument } from "../src/protocol/index.js"; -import { - createStandardSystemProfile, - removeMember, - setMember, - type Capability, -} from "../src/system/index.js"; -import { registerModel } from "../src/testing/index.js"; -import { - base64, - decoded, - encoded, - hash, - referenceSignature, - seed, - frameworkSubject, - rawSubject, -} from "./fixtures.js"; - -function value(result: { ok: true; value: T } | { ok: false; error: { code: string } }): T { - if (!result.ok) throw new Error(result.error.code); - return result.value; -} - -const model = registerModel; -const otherSeed = (id: number) => new Uint8Array(32).fill(id); -const identity = async (id: number) => value(await identityFromSeed(otherSeed(id))); -const original = async () => value(await identityFromSeed(seed)); -const decodeWire = (bytes: Uint8Array): Snapshot => - JSON.parse(new TextDecoder().decode(bytes)) as Snapshot; -const open = (bytes: Uint8Array, signer?: IdentityCapability) => - openDocument({ bytes, signer, model, system: createStandardSystemProfile() }); -const create = async (owner: IdentityCapability) => - value(await createDocument({ identity: owner, model, system: createStandardSystemProfile() })); -const failure = (code: string) => ({ ok: false, error: { code } }); - -function lastSystem(bytes: Uint8Array) { - const entry = frameworkSubject(decodeWire(bytes).entries.at(-1)!.subject); - if (entry.kind !== "system") throw new Error("expected system entry"); - return entry; -} - -function append( - bytes: Uint8Array, - subjects: (EntrySubject | RawEntrySubject)[], - signer: IdentityCapability, - seed: Uint8Array, -): Uint8Array { - const wire = decodeWire(bytes); - const entries = subjects.map((prepared) => { - const subject = rawSubject(prepared, signer, wire.head); - return { id: hash(subject, "entry"), subject }; - }); - const subject: CommitSubject = { - version: 1, - suite: "ledger-ed25519-v1", - committedAt: "2026-11-20T00:00:00.000Z", - parent: wire.head, - nonce: base64(new Uint8Array(16).fill(100)), - signer: signer.publicIdentity, - entryIds: entries.map(({ id }) => id), - metadata: null, - }; - wire.head = hash(subject, "commit"); - wire.commits.push({ id: wire.head, subject, signature: referenceSignature(subject, seed) }); - wire.entries.push(...entries); - return encoded(wire); -} - -test("S01/S02 private admission gives complete history and separates viewing from authoring", async () => { - const [owner, viewer, editor, outsider] = await Promise.all([ - original(), - identity(2), - identity(3), - identity(4), - ]); - const document = await create(owner); - value(await document.dispatch("set", { value: "before admission" })); - const capabilities: Capability[] = ["write", "read"]; - const editorAdmission = setMember(document, { identity: editor.publicIdentity, capabilities }); - capabilities.pop(); - const viewerAdmission = setMember(document, { - identity: viewer.publicIdentity, - capabilities: ["read"], - }); - const [editorReceipt, viewerReceipt] = ( - await Promise.all([editorAdmission, viewerAdmission]) - ).map(value); - const saved = document.export(); - const wire = decodeWire(saved); - expect(wire.commits.at(-1)!.subject.parent).toBe(editorReceipt.head); - expect(wire.head).toBe(viewerReceipt.head); - const editorEntry = frameworkSubject(wire.entries.at(-2)!.subject); - expect(editorEntry.payload).toMatchObject({ - type: "system.member.set", - data: { capabilities: ["read", "write"], history: [{ epoch: 0 }] }, - }); - const viewerDocument = await open(saved, viewer); - expect(viewerDocument.state()).toMatchObject({ - status: "ready", - canWrite: false, - projection: { value: "before admission" }, - }); - expect(viewerDocument.inspect().otherRecipientsDecryptability).toBe("unverified"); - expect(await viewerDocument.dispatch("set", { value: "denied" })).toMatchObject( - failure("CAPABILITY_DENIED"), - ); - const editorDocument = await open(saved, editor); - expect( - await setMember(editorDocument, { identity: outsider.publicIdentity, capabilities: ["read"] }), - ).toMatchObject(failure("CAPABILITY_DENIED")); - value(await editorDocument.dispatch("set", { value: "editor authorized" })); - expect((await open(editorDocument.export(), viewer)).state()).toMatchObject({ - projection: { value: "editor authorized" }, - }); - const locked = await open(saved, outsider); - expect(locked.state()).toEqual({ status: "inspection", reason: "locked" }); - expect(await removeMember(locked, { identityId: editor.publicIdentity.id })).toMatchObject( - failure("INSPECTION_ONLY"), - ); - const readOnly = await openDocument({ - bytes: saved, - model, - system: createStandardSystemProfile(), - reader: { publicIdentity: viewer.publicIdentity, decryptAge: viewer.decryptAge }, - }); - expect( - await setMember(readOnly, { identity: outsider.publicIdentity, capabilities: ["read"] }), - ).toMatchObject(failure("READ_ONLY_RUNTIME")); -}); - -test("S02/S03 grants are bounded even in independently signed history", async () => { - const [owner, delegate, grantOnly, target, administrator] = await Promise.all([ - original(), - identity(2), - identity(3), - identity(4), - identity(5), - ]); - const document = await create(owner); - for (const [member, capabilities] of [ - [delegate, ["read", "write", "grant"]], - [grantOnly, ["read", "grant"]], - [administrator, ["read", "administer"]], - ] as const) { - value(await setMember(document, { identity: member.publicIdentity, capabilities })); - } - const initial = document.export(); - const delegated = await open(initial, delegate); - const input = { identity: target.publicIdentity, capabilities: ["read", "write"] } as const; - value(await setMember(delegated, input)); - expect((await open(delegated.export(), target)).state()).toMatchObject({ canWrite: true }); - expect( - await setMember(delegated, { identity: administrator.publicIdentity, capabilities: ["read"] }), - ).toMatchObject(failure("CAPABILITY_DENIED")); - const grantOnlyDocument = await open(initial, grantOnly); - expect(await setMember(grantOnlyDocument, input)).toMatchObject(failure("CAPABILITY_DENIED")); - expect( - await setMember(grantOnlyDocument, { ...input, capabilities: ["read", "administer"] }), - ).toMatchObject(failure("CAPABILITY_DENIED")); - value(await setMember(grantOnlyDocument, { ...input, capabilities: ["read"] })); - const adminDocument = await open(initial, administrator); - expect(adminDocument.state()).toMatchObject({ canWrite: false }); - value(await setMember(adminDocument, input)); - - const forged = lastSystem(delegated.export()); - forged.payload.data.capabilities = ["read", "administer"]; - const unsignedAuthority = append(initial, [forged], delegate, otherSeed(2)); - expect((await verifyDocument(unsignedAuthority)).integrity).toBe("valid"); - const decryptAge = vi.fn(owner.decryptAge); - const inspected = await openDocument({ - bytes: unsignedAuthority, - model, - system: createStandardSystemProfile(), - reader: { publicIdentity: owner.publicIdentity, decryptAge }, - }); - expect(inspected.inspect().findings).toMatchObject([{ code: "CAPABILITY_DENIED" }]); - expect(decryptAge).not.toHaveBeenCalled(); -}); - -test("S04/S11 no-op grants and administrator protection are atomic", async () => { - const [owner, another] = await Promise.all([original(), identity(2)]); - const document = await create(owner); - const before = document.export(); - expect( - await setMember(document, { - identity: owner.publicIdentity, - capabilities: ["read", "write", "grant", "administer"], - }), - ).toMatchObject(failure("SYSTEM_NO_CHANGE")); - expect( - await setMember(document, { identity: owner.publicIdentity, capabilities: ["read"] }), - ).toMatchObject(failure("LAST_ADMINISTRATOR")); - expect(await removeMember(document, { identityId: another.publicIdentity.id })).toMatchObject( - failure("SYSTEM_EVENT_INVALID"), - ); - expect(await removeMember(document, { identityId: owner.publicIdentity.id })).toMatchObject( - failure("LAST_ADMINISTRATOR"), - ); - expect(document.export()).toEqual(before); - - value( - await setMember(document, { - identity: another.publicIdentity, - capabilities: ["read", "administer"], - }), - ); - const admitted = document.export(); - expect(await removeMember(document, { identityId: owner.publicIdentity.id })).toMatchObject( - failure("SYSTEM_EVENT_INVALID"), - ); - expect(document.export()).toEqual(admitted); - const admin = await open(admitted, another); - value(await removeMember(admin, { identityId: owner.publicIdentity.id })); - expect(admin.state()).toMatchObject({ status: "ready", canWrite: false }); -}); - -test("S05-S08 and S12 revocation rotates keys and preserves both historical authorization and forks", async () => { - const [owner, editor, other, newcomer] = await Promise.all([ - original(), - identity(2), - identity(3), - identity(4), - ]); - const document = await create(owner); - const editorInput = { identity: editor.publicIdentity, capabilities: ["read", "write"] } as const; - value(await document.dispatch("set", { value: "first epoch" })); - value(await setMember(document, editorInput)); - value(await setMember(document, { identity: other.publicIdentity, capabilities: ["read"] })); - const editorDocument = await open(document.export(), editor); - value(await editorDocument.dispatch("set", { value: "editor before removal" })); - const before = editorDocument.export(); - const ownerDocument = await open(before, owner); - - value(await removeMember(ownerDocument, { identityId: editor.publicIdentity.id })); - const afterRemoval = ownerDocument.export(); - const removal = lastSystem(afterRemoval); - expect(removal.payload.data).toMatchObject({ - epoch: 1, - wraps: [owner.publicIdentity.id, other.publicIdentity.id] - .sort() - .map((identityId) => ({ identityId })), - }); - expect(ownerDocument.state()).toMatchObject({ projection: { value: "editor before removal" } }); - expect((await open(before, editor)).state()).toMatchObject({ status: "ready", canWrite: true }); - expect((await open(afterRemoval, editor)).state()).toMatchObject({ - status: "ready", - canWrite: false, - coverage: "complete", - projection: { value: "editor before removal" }, - }); - - value(await editorDocument.dispatch("set", { value: "offline branch" })); - const branch = editorDocument.export(); - expect(value(await compareSnapshots(branch, afterRemoval))).toBe("diverged"); - expect((await open(branch, editor)).state()).toMatchObject({ - projection: { value: "offline branch" }, - }); - const unauthorized = frameworkSubject(decodeWire(branch).entries.at(-1)!.subject); - if (unauthorized.kind !== "application") throw new Error(); - unauthorized.parent = decodeWire(afterRemoval).head; - unauthorized.payload.epoch = 1; - const forged = append(afterRemoval, [unauthorized], editor, otherSeed(2)); - expect((await verifyDocument(forged)).integrity).toBe("valid"); - expect((await open(forged, owner)).inspect().findings).toMatchObject([ - { code: "CAPABILITY_DENIED" }, - ]); - - value(await ownerDocument.dispatch("set", { value: "after first rotation" })); - expect((await open(ownerDocument.export(), editor)).inspect()).toMatchObject({ - application: "locked", - lockedEntries: 1, - findings: [{ code: "KEY_UNAVAILABLE" }], - }); - value(await removeMember(ownerDocument, { identityId: other.publicIdentity.id })); - value(await ownerDocument.dispatch("set", { value: "after second rotation" })); - value( - await setMember(ownerDocument, { identity: newcomer.publicIdentity, capabilities: ["read"] }), - ); - expect(lastSystem(ownerDocument.export()).payload.data.history).toMatchObject([ - { epoch: 0 }, - { epoch: 1 }, - { epoch: 2 }, - ]); - const newcomerDocument = await open(ownerDocument.export(), newcomer); - expect(value(await newcomerDocument.replay()).projection).toEqual({ - value: "after second rotation", - }); - - value(await setMember(ownerDocument, editorInput)); - expect(lastSystem(ownerDocument.export()).payload.data.history).toMatchObject([ - { epoch: 0 }, - { epoch: 1 }, - { epoch: 2 }, - ]); - const reAdmitted = await open(ownerDocument.export(), editor); - expect(reAdmitted.state()).toMatchObject({ - canWrite: true, - projection: { value: "after second rotation" }, - }); - value(await setMember(ownerDocument, { ...editorInput, capabilities: ["read"] })); - expect(lastSystem(ownerDocument.export()).payload.data.history).toEqual([]); - expect((await open(ownerDocument.export(), editor)).state()).toMatchObject({ - canWrite: false, - projection: { value: "after second rotation" }, - }); -}); - -test("S09 signed wrap invariants fail before decryption and decryptability is reader-specific", async () => { - const members = await Promise.all([original(), identity(2), identity(3), identity(4)]); - const [owner, target] = members; - const document = await create(owner); - for (const member of members.slice(1)) { - value(await setMember(document, { identity: member.publicIdentity, capabilities: ["read"] })); - } - const before = document.export(); - value(await removeMember(document, { identityId: target.publicIdentity.id })); - const rotation = lastSystem(document.export()); - const cases: ((wraps: { identityId: string; ciphertext: string }[]) => void)[] = [ - (wraps) => { - wraps.pop(); - }, - (wraps) => { - wraps.reverse(); - }, - (wraps) => { - wraps[1] = { ...wraps[0] }; - }, - ]; - for (const corrupt of cases) { - const entry = structuredClone(rotation); - corrupt(entry.payload.data.wraps as { identityId: string; ciphertext: string }[]); - const forged = append(before, [entry], owner, seed); - expect((await verifyDocument(forged)).integrity).toBe("valid"); - const decryptAge = vi.fn(owner.decryptAge); - const inspected = await openDocument({ - bytes: forged, - model, - system: createStandardSystemProfile(), - reader: { publicIdentity: owner.publicIdentity, decryptAge }, - }); - expect(inspected.inspect().findings).toMatchObject([{ code: "SYSTEM_EVENT_INVALID" }]); - expect(decryptAge).not.toHaveBeenCalled(); - } - const victim = members[2]; - const wraps = rotation.payload.data.wraps as { identityId: string; ciphertext: string }[]; - wraps.find(({ identityId }) => identityId === victim.publicIdentity.id)!.ciphertext = "AA"; - const corrupt = append(before, [rotation], owner, seed); - expect((await open(corrupt, owner)).state()).toMatchObject({ status: "ready" }); - expect((await open(corrupt, victim)).inspect().findings).toMatchObject([ - { code: "KEY_WRAP_INVALID" }, - ]); - - value(await setMember(document, { identity: target.publicIdentity, capabilities: ["read"] })); - // Compare a reader that cannot open its old admission with one that can open every addressed wrap. - const oldWrap = frameworkSubject(decodeWire(before).entries[1].subject); - if (oldWrap.kind !== "system") throw new Error(); - const oldCiphertext = (oldWrap.payload.data.history as { ciphertext: string }[])[0].ciphertext; - const replayed = await openDocument({ - bytes: document.export(), - model, - system: createStandardSystemProfile(), - reader: { - publicIdentity: target.publicIdentity, - decryptAge: (bytes) => - base64(bytes) === oldCiphertext - ? Promise.resolve({ - ok: false, - error: { code: "DECRYPTION_FAILED", message: "test old wrap" }, - }) - : target.decryptAge(bytes), - }, - }); - expect(replayed.inspect().findings).toMatchObject([{ code: "KEY_WRAP_INVALID" }]); -}); - -test("S10 removal and application in the same commit use the rotated epoch", async () => { - const [owner, target] = await Promise.all([original(), identity(2)]); - const document = await create(owner); - value( - await setMember(document, { identity: target.publicIdentity, capabilities: ["read", "write"] }), - ); - const before = document.export(); - value(await removeMember(document, { identityId: target.publicIdentity.id })); - const rotation = lastSystem(document.export()); - const wraps = rotation.payload.data.wraps as { ciphertext: string }[]; - const key = JSON.parse( - new TextDecoder().decode(value(await owner.decryptAge(decoded(wraps[0].ciphertext)))), - ) as { recipient: string }; - const context = { parent: rotation.parent, nonce: base64(new Uint8Array(16).fill(70)) }; - const ciphertext = value( - await encryptAge({ - recipients: [key.recipient], - plaintext: encoded({ - context: "concord.application/1", - ...context, - model: model.ref, - audience: "document", - epoch: 1, - event: { type: "value.set", version: 1, data: { value: "same commit" } }, - }), - }), - ); - const application: EntrySubject = { - version: 1, - kind: "application", - ...context, - payload: { audience: "document", epoch: 1, ciphertext: base64(ciphertext) }, - }; - const valid = append(before, [rotation, application], owner, seed); - expect((await open(valid, owner)).state()).toMatchObject({ - projection: { value: "same commit" }, - }); - application.payload.epoch = 0; - const invalid = append(before, [rotation, application], owner, seed); - expect((await open(invalid, owner)).inspect().findings).toMatchObject([ - { code: "SYSTEM_EVENT_INVALID" }, - ]); -}); - -test("membership failures preserve the committed head and captured inputs", async () => { - const [owner, other] = await Promise.all([original(), identity(2)]); - const document = await create(owner); - const saved = document.export(); - const temporarilyBroken = await open(saved, { - ...owner, - sign: vi.fn().mockRejectedValue(new Error("host secret")), - }); - const command = { identity: other.publicIdentity, capabilities: ["read"] } as const; - expect(await setMember(temporarilyBroken, command)).toMatchObject(failure("SIGNING_FAILED")); - expect(temporarilyBroken.export()).toEqual(saved); - - const input = { capabilities: ["read"] } as unknown as typeof command; - const unexpectedGetter = vi.fn(() => other.publicIdentity); - Object.defineProperty(input, "identity", { enumerable: true, get: unexpectedGetter }); - expect(await setMember(document, input)).toMatchObject(failure("SYSTEM_EVENT_INVALID")); - expect(unexpectedGetter).not.toHaveBeenCalled(); - expect(document.export()).toEqual(saved); - value(await setMember(document, command)); - expect((await open(document.export(), other)).state()).toMatchObject({ status: "ready" }); -}); diff --git a/packages/concord/test/protocol.test.ts b/packages/concord/test/protocol.test.ts deleted file mode 100644 index fec1afd..0000000 --- a/packages/concord/test/protocol.test.ts +++ /dev/null @@ -1,323 +0,0 @@ -import { expect, test } from "vite-plus/test"; -import { verifyLedger } from "@ternent/ledger"; -import { - canonicalize, - compareSnapshots, - hashCommitSubject, - hashEntrySubject, - verifyDocument, - type Snapshot, -} from "../src/protocol/index.js"; -import { - vector, - encoded, - reference, - mutate, - resign, - base64, - protectedPayload, - type Mutation, -} from "./fixtures.js"; -const owner = () => vector("owner.document"); -const primitives = vector<{ - canonical: { id: string; inputJson: string; canonical: string }[]; - rejectedJson: { id: string; inputJson: string; errorCode: string }[]; -}>("primitives"); -function value(result: { ok: true; value: T } | { ok: false; error: { code: string } }): T { - if (!result.ok) throw new Error(result.error.code); - return result.value; -} -for (const item of primitives.canonical) - test(`P01 ${item.id}`, () => - expect(new TextDecoder().decode(value(canonicalize(JSON.parse(item.inputJson))))).toBe( - item.canonical, - )); -for (const item of primitives.rejectedJson) - test(`P02 ${item.id}`, async () => - expect((await verifyDocument(new TextEncoder().encode(item.inputJson))).findings[0].code).toBe( - item.errorCode, - )); -test("P02 malformed UTF-8, BOM and trailing data", async () => { - for (const bytes of [ - new Uint8Array([255]), - new TextEncoder().encode("\ufeff{}"), - new TextEncoder().encode("{} {}"), - ]) - expect((await verifyDocument(bytes)).findings[0].code).toBe("JSON_INVALID"); -}); -test("P03 unsafe values reject without invoking accessors", () => { - let invoked = false; - const accessor = Object.defineProperty({}, "x", { - enumerable: true, - get() { - invoked = true; - return 1; - }, - }); - const cycle: unknown[] = []; - cycle.push(cycle); - for (const input of [ - NaN, - Infinity, - -0, - 0.5, - undefined, - 1n, - () => 1, - Array(2), - accessor, - new Date(), - cycle, - { [Symbol()]: 1 }, - Object.create({ x: 1 }), - Object.setPrototypeOf([], null), - ]) - expect(canonicalize(input)).toMatchObject({ ok: false }); - expect(invoked).toBe(false); -}); -test("P08 exact entry/commit IDs, canonical signature subjects and signatures", async () => { - const document = owner(), - expected = vector<{ - commits: { - id: string; - canonicalSubject: string; - signatureMessageHex: string; - signatureHex: string; - }[]; - entries: { id: string; canonicalSubject: string }[]; - }>("owner.expected"); - document.entries.forEach((entry, i) => { - expect(value(hashEntrySubject(entry.subject))).toBe(expected.entries[i].id); - expect(new TextDecoder().decode(value(canonicalize(entry.subject)))).toBe( - expected.entries[i].canonicalSubject, - ); - }); - document.commits.forEach((commit, i) => { - expect(value(hashCommitSubject(commit.subject))).toBe(expected.commits[i].id); - expect(reference(commit.subject)).toBe(expected.commits[i].canonicalSubject); - expect(Buffer.from(`ledger.signature/1\0${reference(commit.subject)}`).toString("hex")).toBe( - expected.commits[i].signatureMessageHex, - ); - expect(Buffer.from(commit.signature, "base64url").toString("hex")).toBe( - expected.commits[i].signatureHex, - ); - }); - expect(await verifyDocument(encoded(document))).toEqual({ - integrity: "valid", - documentId: document.documentId, - head: document.head, - checkedCommits: 2, - checkedEntries: 2, - findings: [], - }); -}); -for (const item of vector<{ cases: Mutation[] }>("mutations").cases) - test(`P mutation ${item.id}`, async () => { - const result = await verifyDocument(encoded(mutate(owner(), item.operations))); - expect(result.integrity).toBe(item.expected.integrity); - expect(result.findings[0].code).toBe(item.expected.code); - }); -test("P04 encodings and closed schemas fail without normalization", async () => { - const cases: [(wire: Snapshot) => void, string][] = [ - [ - (wire) => { - wire.commits[1].signature += "="; - }, - "SCHEMA_INVALID", - ], - [ - (wire) => { - wire.commits[1].signature = wire.commits[1].signature.slice(0, -1) + "B"; - }, - "SCHEMA_INVALID", - ], - [ - (wire) => { - wire.commits[1].subject.signer = { ...wire.commits[1].subject.signer, publicKey: "AA" }; - }, - "IDENTITY_INVALID", - ], - [ - (wire) => { - Object.assign(wire.entries[0].subject, { extra: true }); - }, - "SCHEMA_INVALID", - ], - [ - (wire) => { - wire.entries[0].id = wire.entries[0].id.toUpperCase() as Snapshot["entries"][number]["id"]; - }, - "SCHEMA_INVALID", - ], - ]; - for (const [modify, code] of cases) { - const wire = owner(); - modify(wire); - expect((await verifyDocument(encoded(wire))).findings[0].code).toBe(code); - } -}); -test("P06 identity binding is checked after independent rehashing/signing", async () => { - const wire = owner(); - Object.assign(wire.commits[1].subject.signer, { id: `identity:${"0".repeat(64)}` }); - resign(wire); - expect((await verifyDocument(encoded(wire))).findings[0].code).toBe("IDENTITY_INVALID"); -}); -test("P13 ordered entry IDs bind hashes and signatures", async () => { - const wire = owner(), - extra = structuredClone(wire.entries[1]); - extra.subject.nonce = base64(new Uint8Array(16).fill(9)); - wire.entries.push(extra); - wire.commits[1].subject.entryIds.push(extra.id); - resign(wire); - expect((await verifyDocument(encoded(wire))).integrity).toBe("valid"); - wire.commits[1].subject.entryIds.reverse(); - wire.entries.splice(1, 2, ...wire.entries.slice(1).reverse()); - expect((await verifyDocument(encoded(wire))).findings[0].code).toBe("HASH_MISMATCH"); - wire.commits[1].id = value(hashCommitSubject(wire.commits[1].subject)); - wire.head = wire.commits[1].id; - expect((await verifyDocument(encoded(wire))).findings[0].code).toBe("SIGNATURE_INVALID"); -}); -test("P14/P15 correct signatures cannot repair linkage or selectors", async () => { - for (const [modify, code] of [ - [ - (wire: Snapshot) => { - wire.commits[1].subject.parent = `commit:${"0".repeat(64)}`; - }, - "LINK_INVALID", - ], - [ - (wire: Snapshot) => { - wire.entries[1].subject.parent = null; - }, - "LINK_INVALID", - ], - [ - (wire: Snapshot) => { - wire.commits[0].subject.parent = `commit:${"0".repeat(64)}`; - }, - "LINK_INVALID", - ], - ] as const) { - const wire = owner(); - modify(wire); - resign(wire); - expect((await verifyDocument(encoded(wire))).findings[0].code).toBe(code); - } -}); -test("P16 unsupported requirements and resource limits do not claim invalid cryptography", async () => { - const raw = encoded(owner()); - for (const limits of [ - { maxBytes: raw.length - 1 }, - { maxCommits: 1 }, - { maxEntries: 1 }, - { maxCiphertextBytes: 1 }, - { maxDepth: 2 }, - { maxMetadataBytes: 1 }, - ]) - expect(await verifyDocument(raw, { limits })).toMatchObject({ - integrity: "unsupported", - findings: [{ code: "RESOURCE_LIMIT" }], - }); - expect(await verifyDocument(raw, { limits: { maxDepth: 0 } })).toMatchObject({ - integrity: "unsupported", - findings: [{ code: "HOST_CONFIGURATION" }], - }); - const wire = owner(); - wire.version = 2 as 1; - expect((await verifyDocument(encoded(wire))).integrity).toBe("unsupported"); - const unknown = owner(); - Object.assign(unknown.entries[1].subject, { kind: "future" }); - resign(unknown); - expect((await verifyDocument(encoded(unknown))).findings[0].code).toBe("ENTRY_KIND_UNSUPPORTED"); -}); -test("P17/P19 transport formatting, signed metadata and prototype keys", async () => { - const wire = owner(); - wire.commits.at(-1)!.subject.metadata = JSON.parse( - '{"__proto__":{"polluted":true},"unicode":"é"}', - ); - resign(wire); - expect( - (await verifyDocument(new TextEncoder().encode(JSON.stringify(wire, null, 2)))).integrity, - ).toBe("valid"); - expect(({} as { polluted?: boolean }).polluted).toBeUndefined(); - wire.commits.at(-1)!.subject.metadata!.unicode = "changed after signing"; - expect((await verifyDocument(encoded(wire))).findings[0].code).toBe("HASH_MISMATCH"); -}); -test("C01-C05 snapshot relationships have no implicit merge", async () => { - const child = encoded(owner()), - genesis = encoded(vector("owner.genesis.document")), - fork = encoded(vector("owner.fork.document")); - for (const [a, b, relation] of [ - [child, child, "equal"], - [genesis, child, "behind"], - [child, genesis, "ahead"], - [child, fork, "diverged"], - [fork, child, "diverged"], - ] as const) - expect(value(await compareSnapshots(a, b))).toBe(relation); - const other = vector("owner.genesis.document"); - other.commits[0].subject.nonce = base64(new Uint8Array(16).fill(12)); - resign(other); - expect(value(await compareSnapshots(child, encoded(other)))).toBe("unrelated"); - expect(await compareSnapshots(child, new Uint8Array())).toMatchObject({ ok: false }); -}); - -test("P15 duplicates, absent genesis, selectors and repeated per-commit nonces", async () => { - const duplicate = owner(); - duplicate.commits.unshift(structuredClone(duplicate.commits[0])); - expect((await verifyDocument(encoded(duplicate))).findings[0].code).toBe("DUPLICATE_RECORD"); - const missing = owner(); - missing.commits.shift(); - missing.entries.shift(); - expect((await verifyDocument(encoded(missing))).findings[0].code).toBe("LINK_INVALID"); - const wrong = owner(); - wrong.documentId = `commit:${"0".repeat(64)}`; - expect((await verifyDocument(encoded(wrong))).findings[0].code).toBe("HEAD_INVALID"); - const repeated = owner(), - extra = structuredClone(repeated.entries[1]); - if (extra.subject.kind !== "application") throw new Error("fixture"); - protectedPayload(extra.subject).ciphertext = "AA"; - repeated.entries.push(extra); - repeated.commits[1].subject.entryIds.push(extra.id); - resign(repeated); - expect((await verifyDocument(encoded(repeated))).findings[0].code).toBe("SCHEMA_INVALID"); -}); - -test("P19 large bounded metadata and exact integral number token import", async () => { - const wire = owner(); - wire.commits.at(-1)!.subject.metadata = { items: Array.from({ length: 5000 }, (_, i) => i) }; - resign(wire); - expect((await verifyDocument(encoded(wire))).integrity).toBe("valid"); - const raw = new TextEncoder().encode( - new TextDecoder().decode(encoded(wire)).replace('"version":1', '"version":1.0e0'), - ); - expect((await verifyDocument(raw)).integrity).toBe("valid"); -}); - -test("P11 a detached commit cannot hide beside the selected chain", async () => { - const wire = owner(), - fork = vector("owner.fork.document"); - fork.entries[1].subject.nonce = base64(new Uint8Array(16).fill(27)); - resign(fork); - expect((await verifyDocument(encoded(fork))).integrity).toBe("valid"); - wire.commits.push(fork.commits[1]); - wire.entries.push(fork.entries[1]); - expect((await verifyDocument(encoded(wire))).findings[0].code).toBe("UNREFERENCED_RECORD"); -}); - -test("Concord validates signed genesis requirements after Ledger integrity succeeds", async () => { - for (const mode of ["missing", "invalid"] as const) { - const raw = vector("owner.genesis.document"); - if (mode === "missing") raw.commits[0].subject.metadata = {}; - else - ( - raw.commits[0].subject.metadata!.concord as import("../src/index.js").Declaration - ).model.version = 0; - const bytes = encoded(resign(raw)); - expect((await verifyLedger(bytes)).integrity).toBe("valid"); - expect(await verifyDocument(bytes)).toMatchObject({ - integrity: "invalid", - findings: [{ code: mode === "missing" ? "DECLARATION_INVALID" : "SCHEMA_INVALID" }], - }); - } -}); diff --git a/packages/concord/test/runtime.test.ts b/packages/concord/test/runtime.test.ts deleted file mode 100644 index 2a6f725..0000000 --- a/packages/concord/test/runtime.test.ts +++ /dev/null @@ -1,979 +0,0 @@ -import { expect, test, vi } from "vite-plus/test"; -import { createLedger, verifyLedger } from "@ternent/ledger"; -import { - identityFromSeed, - generateIdentity, - encryptAge, - type IdentityCapability, -} from "@ternent/armour"; -import { createDocument, openDocument, type Snapshot, type Json } from "../src/index.js"; -import { createStandardSystemProfile } from "../src/system/index.js"; -import { - registerModel, - assertModelConformance, - createMemoryArtifactStore, -} from "../src/testing/index.js"; -import { verifyDocument } from "../src/protocol/index.js"; -import { - vector, - seed, - encoded, - base64, - decoded, - resign, - protectedPayload, - systemPayload, -} from "./fixtures.js"; -const value = (result: { ok: true; value: T } | { ok: false; error: { code: string } }): T => { - if (!result.ok) throw new Error(result.error.code); - return result.value; -}; -const owner = async () => value(await identityFromSeed(seed)); -const model = registerModel; -const bytes = () => encoded(vector("owner.document")); -const open = async ( - extra: { - bytes?: Uint8Array; - anchor?: Uint8Array; - signer?: IdentityCapability; - reader?: import("@ternent/armour").ReaderCapability; - model?: typeof model; - } = {}, -) => - openDocument({ - bytes: bytes(), - model, - system: createStandardSystemProfile(), - signer: await owner(), - ...extra, - }); -test("R01-R05 immediate create, dispatch, export, reopen, independent verify and saved replay", async () => { - const identity = await owner(), - system = createStandardSystemProfile(); - const created = value(await createDocument({ model, system, identity })); - expect(created.state()).toMatchObject({ - status: "ready", - projection: { value: "" }, - canWrite: true, - }); - expect(JSON.parse(new TextDecoder().decode(created.export())).commits).toHaveLength(1); - const receipt = value(await created.dispatch("set", { value: "hello Concord" })); - expect(receipt.status).toBe("committed"); - expect(created.state()).toMatchObject({ projection: { value: "hello Concord" } }); - const saved = created.export(), - wire = JSON.parse(new TextDecoder().decode(saved)) as Snapshot; - expect(wire.commits).toHaveLength(2); - expect(wire.entries).toHaveLength(2); - expect(new TextDecoder().decode(saved)).not.toContain("hello Concord"); - expect(Object.keys(wire).sort()).toEqual([ - "commits", - "documentId", - "entries", - "format", - "head", - "version", - ]); - const reopened = await openDocument({ bytes: saved, model, system, signer: identity }); - expect(reopened.state()).toEqual(created.state()); - expect(await reopened.verify()).toMatchObject({ integrity: "valid" }); - expect(await verifyDocument(saved)).toMatchObject({ integrity: "valid" }); - expect(value(await reopened.replay())).toEqual({ - projection: { value: "hello Concord" }, - coverage: "complete", - lockedEntries: 0, - }); - expect(await reopened.replay()).toEqual(await reopened.replay()); - expect(reopened.inspect()).toMatchObject({ - system: "valid", - application: "valid", - freshness: "unanchored", - findings: [], - lockedEntries: 0, - }); -}); -test("R06 fixed independent owner artifact reconstructs its literal projection and IDs", async () => { - const expected = vector<{ projection: Json; documentId: string; head: string }>("owner.expected"), - handle = await open(); - expect(handle.state()).toEqual({ - status: "ready", - projection: expected.projection, - documentId: expected.documentId, - head: expected.head, - canWrite: true, - coverage: "complete", - lockedEntries: 0, - }); -}); -test("R07/R20 no reader and unrelated reader stay locked, including a private genesis", async () => { - for (const [input, count] of [ - [bytes(), 1], - [encoded(vector("owner.genesis.document")), 0], - ] as const) { - const locked = await openDocument({ - bytes: input, - model, - system: createStandardSystemProfile(), - }); - expect(locked.state()).toEqual({ status: "inspection", reason: "locked" }); - expect(locked.inspect()).toMatchObject({ - application: "locked", - lockedEntries: count, - findings: [{ code: "READ_ACCESS_REQUIRED" }], - }); - expect(locked.export()).toEqual(input); - expect(await locked.dispatch("set", { value: "bad" })).toMatchObject({ - ok: false, - error: { code: "INSPECTION_ONLY" }, - }); - } - const unrelated = value(await generateIdentity()); - expect((await open({ signer: unrelated })).state()).toMatchObject({ - status: "inspection", - reason: "locked", - }); -}); -test("R08 decrypt-only capability is ready but all mutations are read-only", async () => { - const identity = await owner(), - handle = await openDocument({ - bytes: bytes(), - model, - system: createStandardSystemProfile(), - reader: { publicIdentity: identity.publicIdentity, decryptAge: identity.decryptAge }, - }); - expect(handle.state()).toMatchObject({ - status: "ready", - canWrite: false, - projection: { value: "hello Concord" }, - }); - for (const result of [ - await handle.dispatch("set", { value: "bad" }), - await handle.commit(), - await handle.discardDraft(), - ]) - expect(result).toMatchObject({ ok: false, error: { code: "READ_ONLY_RUNTIME" } }); -}); -test("R09/R18 tampering never invokes models; malformed evidence remains byte-exact", async () => { - const initial = vi.fn(model.initial), - spy = { ...model, initial }; - for (const input of [ - new TextEncoder().encode("{broken"), - (() => { - const wire = vector("owner.document"); - wire.commits[1].subject.metadata = { message: "tamper" }; - return encoded(wire); - })(), - ]) { - const handle = await openDocument({ - bytes: input, - model: spy, - system: createStandardSystemProfile(), - signer: await owner(), - }); - expect(handle.state()).toEqual({ status: "inspection", reason: "invalid" }); - expect(handle.export()).toEqual(input); - expect((await handle.verify()).integrity).toBe("invalid"); - expect(await handle.replay()).toMatchObject({ ok: false }); - } - expect(initial).not.toHaveBeenCalled(); -}); -test("R10/P18 exact requirements, host configuration and reader/signer identity", async () => { - const unavailable = await openDocument({ bytes: bytes() }); - expect(unavailable.inspect().requirements).toEqual([ - { kind: "system", ref: { id: "concord.standard", version: 1 } }, - { kind: "model", ref: model.ref }, - ]); - expect(unavailable.state()).toMatchObject({ reason: "incompatible" }); - expect((await unavailable.verify()).integrity).toBe("valid"); - const other = value(await generateIdentity()); - expect((await open({ reader: other })).inspect().findings[0].code).toBe("IDENTITY_MISMATCH"); - expect( - (await open({ model: { ...model, ref: { ...model.ref, version: 2 } } })).inspect().findings[0] - .code, - ).toBe("REQUIREMENT_UNAVAILABLE"); - expect( - await createDocument({ - model, - system: createStandardSystemProfile(), - identity: await owner(), - limits: { maxBytes: 0 }, - }), - ).toMatchObject({ ok: false, error: { code: "HOST_CONFIGURATION" } }); -}); -test("R11-R13 integrity-valid private events still require authentication, exact context and model meaning", async () => { - const expected = vector<{ - groupRecipient: string; - eventPlaintext: { - context: string; - parent: string; - nonce: string; - model: { id: string; version: number }; - audience: string; - epoch: number; - event: { type: string; version: number; data: Json }; - }; - }>("owner.expected"); - for (const [edit, code] of [ - [ - (body: typeof expected.eventPlaintext) => { - body.nonce = base64(new Uint8Array(16).fill(42)); - }, - "EVENT_CONTEXT_INVALID", - ], - [ - (body: typeof expected.eventPlaintext) => { - body.parent = `commit:${"0".repeat(64)}`; - }, - "EVENT_CONTEXT_INVALID", - ], - [ - (body: typeof expected.eventPlaintext) => { - body.model.version = 2; - }, - "EVENT_CONTEXT_INVALID", - ], - [ - (body: typeof expected.eventPlaintext) => { - body.epoch = 1; - }, - "EVENT_CONTEXT_INVALID", - ], - [ - (body: typeof expected.eventPlaintext) => { - body.event.type = "value.future"; - }, - "EVENT_UNSUPPORTED", - ], - [ - (body: typeof expected.eventPlaintext) => { - body.event.data = { value: 12 }; - }, - "EVENT_INVALID", - ], - ] as const) { - const wire = vector("owner.document"), - body = structuredClone(expected.eventPlaintext); - edit(body); - if (wire.entries[1].subject.kind !== "application") throw new Error("fixture"); - protectedPayload(wire.entries[1].subject).ciphertext = base64( - value(await encryptAge({ recipients: [expected.groupRecipient], plaintext: encoded(body) })), - ); - resign(wire); - expect((await verifyDocument(encoded(wire))).integrity).toBe("valid"); - const handle = await open({ bytes: encoded(wire) }); - expect(handle.state().status).toBe("inspection"); - expect(handle.inspect().findings[0].code).toBe(code); - } - const wire = vector("owner.document"); - if (wire.entries[1].subject.kind !== "application") throw new Error("fixture"); - const ciphertext = decoded(protectedPayload(wire.entries[1].subject).ciphertext); - ciphertext[ciphertext.length - 1] ^= 1; - protectedPayload(wire.entries[1].subject).ciphertext = base64(ciphertext); - resign(wire); - expect((await open({ bytes: encoded(wire) })).inspect().findings[0].code).toBe( - "DECRYPTION_INVALID", - ); -}); -test("R13 reducers reject and throw without leaking messages or partial projection", async () => { - for (const [reduce, code] of [ - [ - () => ({ ok: false as const, error: { code: "DOMAIN_REJECTED", message: "private" } }), - "MODEL_TRANSITION_INVALID", - ], - [ - () => { - throw new Error("private plaintext"); - }, - "MODEL_FAILED", - ], - [() => ({ ok: true as const, value: { value: NaN } }), "MODEL_TRANSITION_INVALID"], - ] as const) { - const handle = await openDocument({ - bytes: bytes(), - model: { ...model, reduce } as unknown as typeof model, - system: createStandardSystemProfile(), - signer: await owner(), - }); - expect(handle.inspect().findings[0].code).toBe(code); - expect(JSON.stringify(handle.inspect())).not.toContain("private"); - expect(handle.state().status).toBe("inspection"); - } -}); -test("R14 author failures preserve export; equal commands still commit", async () => { - const handle = await open(), - before = handle.export(); - // @ts-expect-error Unknown commands remain rejected for JS callers too. - expect(await handle.dispatch("missing", {})).toMatchObject({ - ok: false, - error: { code: "COMMAND_UNSUPPORTED" }, - }); - for (const data of [ - { value: 1 }, - { value: "a", extra: true }, - { value: "\ud800" }, - { value: "x".repeat(4097) }, - ]) { - // @ts-expect-error Runtime validation remains necessary for JS callers. - expect(await handle.dispatch("set", data)).toMatchObject({ - ok: false, - error: { code: "COMMAND_INVALID" }, - }); - } - expect(handle.export()).toEqual(before); - value(await handle.dispatch("set", { value: "hello Concord" })); - expect(handle.export()).not.toEqual(before); - for (const [decide, code] of [ - [() => ({ ok: false as const, error: { code: "NO", message: "private" } }), "COMMAND_REJECTED"], - [() => ({ ok: true as const, value: [] }), "NO_EVENTS"], - ] as const) { - const altered = await openDocument({ - bytes: bytes(), - model: { ...model, commands: { set: { ...model.commands.set, decide } } }, - system: createStandardSystemProfile(), - signer: await owner(), - }); - expect(await altered.dispatch("set", { value: "a" })).toMatchObject({ - ok: false, - error: { code }, - }); - expect(altered.export()).toEqual(bytes()); - } -}); -test("R15 signing, preparation and candidate replay failures are atomic", async () => { - const identity = await owner(), - system = createStandardSystemProfile(); - const failures = [ - { - identity: { - ...identity, - async sign() { - return { ok: false as const, error: { code: "FAILED", message: "private" } }; - }, - }, - system, - code: "SIGNING_FAILED", - }, - { - identity, - system: { - ...system, - async prepare() { - throw new Error("private key"); - }, - }, - code: "SYSTEM_FAILED", - }, - ]; - for (const input of failures) { - const handle = await openDocument({ - bytes: bytes(), - model, - system: input.system, - signer: input.identity, - }); - const before = handle.export(), - state = handle.state(); - expect(await handle.dispatch("set", { value: "a" })).toMatchObject({ - ok: false, - error: { code: input.code }, - }); - expect(handle.export()).toEqual(before); - expect(handle.state()).toEqual(state); - expect(handle.draft()).toBeNull(); - } - let failReplay = false; - const profile = { - ...system, - async replay(input: Parameters[0]) { - if (failReplay) throw new Error("private"); - return system.replay(input); - }, - }; - const handle = await openDocument({ bytes: bytes(), model, system: profile, signer: identity }); - failReplay = true; - expect(await handle.dispatch("set", { value: "a" })).toMatchObject({ - ok: false, - error: { code: "SYSTEM_FAILED" }, - }); - expect(handle.export()).toEqual(bytes()); -}); -test("R16 operations serialize and pending encryption does not publish intermediate state", async () => { - const system = createStandardSystemProfile(); - let release!: () => void, started!: () => void; - const waiting = new Promise((resolve) => { - release = resolve; - }), - entered = new Promise((resolve) => { - started = resolve; - }); - let first = true; - const profile = { - ...system, - async prepare(input: Parameters[0]) { - if (first) { - first = false; - started(); - await waiting; - } - return system.prepare(input); - }, - }; - const handle = await openDocument({ - bytes: bytes(), - model, - system: profile, - signer: await owner(), - }), - before = handle.state(); - const a = handle.dispatch("set", { value: "first" }); - await entered; - const b = handle.dispatch("set", { value: "second" }); - expect(handle.state()).toEqual(before); - release(); - value(await a); - value(await b); - expect(handle.state()).toMatchObject({ projection: { value: "second" } }); - const wire = JSON.parse(new TextDecoder().decode(handle.export())) as Snapshot; - expect(wire.commits[3].subject.parent).toBe(wire.commits[2].id); -}); -test("R17 all public values detach; authoring rejects accessors before invoking them", async () => { - const input = bytes(), - handle = await open({ bytes: input }); - input.fill(0); - const before = handle.export(), - copy = handle.export(); - copy.fill(0); - const state = handle.state(); - if (state.status === "ready") - expect(() => Object.assign(state.projection, { value: "bad" })).toThrow(); - const report = handle.inspect(); - expect(() => Object.assign(report.history[0].subject, { nonce: "bad" })).toThrow(); - expect(handle.export()).toEqual(before); - let invoked = false; - const data = Object.defineProperty({}, "value", { - get() { - invoked = true; - return "bad"; - }, - enumerable: true, - }); - expect(await handle.dispatch("set", data as { value: string })).toMatchObject({ - ok: false, - error: { code: "COMMAND_INVALID" }, - }); - expect(invoked).toBe(false); -}); -test("R19 malformed bootstrap owner/wrap and unknown system events remain inspectable", async () => { - for (const [edit, code] of [ - [ - (wire: Snapshot) => { - if (wire.entries[0].subject.kind !== "system") throw new Error(); - systemPayload(wire.entries[0].subject).data.wraps = []; - }, - "SYSTEM_EVENT_INVALID", - ], - [ - (wire: Snapshot) => { - if (wire.entries[0].subject.kind !== "system") throw new Error(); - ( - systemPayload(wire.entries[0].subject).data.wraps as { ciphertext: string }[] - )[0].ciphertext = "AA"; - }, - "KEY_WRAP_INVALID", - ], - [ - (wire: Snapshot) => { - if (wire.entries[0].subject.kind !== "system") throw new Error(); - systemPayload(wire.entries[0].subject).type = "system.member.future"; - }, - "UNSUPPORTED_SYSTEM_EVENT", - ], - ] as const) { - const wire = vector("owner.genesis.document"); - edit(wire); - resign(wire); - expect((await verifyDocument(encoded(wire))).integrity).toBe("valid"); - const handle = await open({ bytes: encoded(wire) }); - expect(handle.inspect().findings[0].code).toBe(code); - expect(handle.state().status).toBe("inspection"); - } -}); -test("C06-C10 anchors gate replay while integrity remains valid", async () => { - const genesis = encoded(vector("owner.genesis.document")), - child = bytes(), - fork = encoded(vector("owner.fork.document")); - expect((await open({ anchor: genesis })).inspect().freshness).toBe("ahead"); - expect((await open({ anchor: child })).inspect().freshness).toBe("equal"); - for (const [input, anchor, code] of [ - [genesis, child, "STALE_HEAD"], - [fork, child, "DIVERGED_HEAD"], - [child, new Uint8Array(), "ANCHOR_INVALID"], - ] as const) { - const handle = await open({ bytes: input, anchor }); - expect(handle.state()).toMatchObject({ reason: "freshness" }); - expect(handle.inspect().findings[0].code).toBe(code); - expect((await handle.verify()).integrity).toBe("valid"); - } -}); -test("testing helpers assert literal model transitions and copy stored bytes", async () => { - const identity = await owner(); - expect( - assertModelConformance(model, { - initial: { value: "" }, - steps: [ - { - event: { type: "value.set", version: 1, data: { value: "literal" } }, - facts: { - audience: "document", - actor: identity.publicIdentity, - capabilities: ["read", "write"], - members: [], - }, - expected: { value: "literal" }, - }, - ], - }), - ).toEqual({ ok: true, value: { passed: 2 } }); - const store = createMemoryArtifactStore(), - input = bytes(); - value(await store.write(input)); - input.fill(0); - const read = value(await store.read())!; - expect(read).toEqual(bytes()); - read.fill(0); - expect(value(await store.read())).toEqual(bytes()); -}); - -test("author resource limits are checked before signing, and multi-event decisions form one commit", async () => { - const identity = await owner(), - sign = vi.fn(identity.sign); - expect( - await createDocument({ - model, - system: createStandardSystemProfile(), - identity: { ...identity, sign }, - limits: { maxBytes: 100 }, - }), - ).toMatchObject({ ok: false, error: { code: "RESOURCE_LIMIT" } }); - expect(sign).not.toHaveBeenCalled(); - const multi = { - ...model, - commands: { - set: { - ...model.commands.set, - decide: (input: { value: string }) => ({ - ok: true as const, - value: [ - { type: "value.set" as const, version: 1 as const, data: { value: "first" } }, - { type: "value.set" as const, version: 1 as const, data: input }, - ], - }), - }, - }, - }; - const handle = value( - await createDocument({ model: multi, system: createStandardSystemProfile(), identity }), - ); - value(await handle.dispatch("set", { value: "last" })); - const wire = JSON.parse(new TextDecoder().decode(handle.export())) as Snapshot; - expect(wire.commits).toHaveLength(2); - expect(wire.commits[1].subject.entryIds).toHaveLength(2); - expect(handle.state()).toMatchObject({ projection: { value: "last" } }); -}); - -test("synchronous model reentry is rejected without queue deadlock", async () => { - let nested: Promise | undefined; - let handle: Awaited>; - const reentrant = { - ...model, - commands: { - set: { - ...model.commands.set, - decide: (input: { value: string }) => { - nested = handle.dispatch("set", { value: "nested" }); - return { - ok: true as const, - value: [{ type: "value.set" as const, version: 1 as const, data: input }], - }; - }, - }, - }, - }; - handle = await open({ model: reentrant }); - value(await handle.dispatch("set", { value: "outer" })); - expect(await nested).toMatchObject({ ok: false, error: { code: "HOST_CONFIGURATION" } }); - expect(handle.state()).toMatchObject({ projection: { value: "outer" } }); -}); - -test("profile output cannot omit events or rebind actors", async () => { - const system = createStandardSystemProfile(), - identity = await owner(); - for (const mode of ["missing", "actor"]) { - const profile = { - ...system, - async replay(input: Parameters[0]) { - const result = await system.replay(input); - if (!result.ok) return result; - const value = result.value; - return { - ok: true as const, - value: { - ...value, - entries: mode === "missing" ? [] : value.entries, - entryFacts: - mode === "actor" - ? value.entryFacts.map((item) => ({ - ...item, - facts: { - ...item.facts, - actor: { ...item.facts.actor, id: `identity:${"0".repeat(64)}` }, - }, - })) - : value.entryFacts, - }, - }; - }, - }; - expect( - (await openDocument({ bytes: bytes(), model, system: profile, signer: identity })).inspect() - .findings[0].code, - ).toBe("SYSTEM_FAILED"); - } -}); - -test("model capabilities remain mandatory during authoring and historical replay", async () => { - const extra = { - ...model, - requirements: () => ["write", "imaginary"] as unknown as ("read" | "write")[], - }; - const result = await openDocument({ - bytes: bytes(), - model: extra, - system: createStandardSystemProfile(), - signer: await owner(), - }); - expect(result.inspect().findings[0].code).toBe("MODEL_FAILED"); -}); - -test("authoring accepts draft mode but rejects alternative profile declarations", async () => { - const identity = await owner(), - system = createStandardSystemProfile(); - const drafted = value(await createDocument({ model, system, identity, mode: "draft" })); - expect(drafted.state()).toMatchObject({ status: "ready", projection: { value: "" } }); - expect(drafted.draft()).toBeNull(); - expect( - await createDocument({ - model, - system: { ...system, ref: { id: "custom.system", version: 1 } }, - identity, - }), - ).toMatchObject({ ok: false, error: { code: "HOST_CONFIGURATION" } }); - expect( - ( - await open({ anchor: value(await createDocument({ model, system, identity })).export() }) - ).inspect().findings[0].code, - ).toBe("DOCUMENT_MISMATCH"); -}); - -test("canonical export must fit the byte budget before any extension runs", async () => { - const wire = vector("owner.document"); - wire.commits.at(-1)!.subject.metadata = { n: 1000000000000000 }; - resign(wire); - const canonical = encoded(wire), - transport = new TextEncoder().encode( - new TextDecoder().decode(canonical).replace("1000000000000000", "1e15"), - ), - initial = vi.fn(model.initial), - system = createStandardSystemProfile(), - replay = vi.fn(system.replay), - identity = await owner(); - expect(transport.length).toBeLessThan(canonical.length); - const rejected = await openDocument({ - bytes: transport, - model: { ...model, initial }, - system: { ...system, replay }, - signer: identity, - limits: { maxBytes: transport.length }, - }); - expect(rejected.state()).toEqual({ status: "inspection", reason: "incompatible" }); - expect(await rejected.verify()).toMatchObject({ - integrity: "unsupported", - findings: [{ code: "RESOURCE_LIMIT" }], - }); - expect(rejected.export()).toEqual(transport); - expect(await rejected.dispatch("set", { value: "blocked" })).toMatchObject({ - ok: false, - error: { code: "INSPECTION_ONLY" }, - }); - expect(initial).not.toHaveBeenCalled(); - expect(replay).not.toHaveBeenCalled(); - const accepted = await openDocument({ - bytes: transport, - model, - system, - signer: identity, - limits: { maxBytes: canonical.length }, - }); - expect(accepted.state()).toMatchObject({ - status: "ready", - projection: { value: "hello Concord" }, - }); - expect(accepted.export()).toEqual(canonical); - expect((await accepted.verify()).integrity).toBe("valid"); - expect(value(await accepted.replay())).toEqual({ - projection: { value: "hello Concord" }, - coverage: "complete", - lockedEntries: 0, - }); -}); - -test("a multi-event snapshot reopens at its exact wire budget despite expanded replay facts", async () => { - const identity = await owner(), - multi = { - ...model, - commands: { - set: { - ...model.commands.set, - decide: () => ({ - ok: true as const, - value: Array.from({ length: 20 }, () => ({ - type: "value.set" as const, - version: 1 as const, - data: { value: "" }, - })), - }), - }, - }, - }, - created = value( - await createDocument({ model: multi, system: createStandardSystemProfile(), identity }), - ); - value(await created.dispatch("set", { value: "" })); - const saved = created.export(), - limits = { maxBytes: saved.length }; - expect((await verifyDocument(saved, { limits })).integrity).toBe("valid"); - const reopened = await openDocument({ - bytes: saved, - model: multi, - system: createStandardSystemProfile(), - signer: identity, - limits, - }); - expect(reopened.state()).toEqual(created.state()); - expect(reopened.export()).toEqual(saved); - expect(reopened.inspect().findings).toEqual([]); - expect(value(await reopened.replay())).toEqual({ - projection: { value: "" }, - coverage: "complete", - lockedEntries: 0, - }); - expect(await reopened.replay()).toEqual(await reopened.replay()); -}); - -test.each(["system", "model"] as const)( - "%s replay resource exhaustion is unsupported rather than invalid history", - async (phase) => { - const input = bytes(), - system = createStandardSystemProfile(), - oversized = "x".repeat(input.length); - const handle = await openDocument({ - bytes: input, - signer: await owner(), - limits: { maxBytes: input.length }, - model: phase === "model" ? { ...model, initial: () => ({ value: oversized }) } : model, - system: { - ...system, - async replay(options) { - const result = await system.replay(options); - if (!result.ok || phase !== "system") return result; - return { - ok: true, - value: { - ...result.value, - entries: result.value.entries.map((item) => - item.status === "locked" - ? item - : { - ...item, - event: { ...item.event, data: { value: oversized } }, - }, - ), - }, - }; - }, - }, - }); - expect(handle.state()).toEqual({ status: "inspection", reason: "incompatible" }); - expect(handle.inspect()).toMatchObject({ - verification: { integrity: "valid" }, - [phase === "model" ? "application" : "system"]: "unsupported", - findings: [{ code: "RESOURCE_LIMIT" }], - }); - expect(handle.export()).toEqual(input); - }, -); - -test("per-entry profile validation still rejects non-JSON output before model replay", async () => { - const system = createStandardSystemProfile(), - initial = vi.fn(model.initial), - handle = await openDocument({ - bytes: bytes(), - signer: await owner(), - model: { ...model, initial }, - system: { - ...system, - async replay(options) { - const result = await system.replay(options); - if (!result.ok) return result; - return { - ok: true, - value: { - ...result.value, - entries: result.value.entries.map((item) => - item.status === "locked" - ? item - : { - ...item, - event: { ...item.event, data: undefined as unknown as Json }, - }, - ), - }, - }; - }, - }, - }); - expect(handle.state()).toEqual({ status: "inspection", reason: "invalid" }); - expect(handle.inspect().findings[0].code).toBe("SYSTEM_FAILED"); - expect(initial).not.toHaveBeenCalled(); -}); - -test("parseable failed verification retains detached untrusted history without running extensions", async () => { - const system = createStandardSystemProfile(), - replay = vi.fn(system.replay), - initial = vi.fn(model.initial); - for (const code of ["SIGNATURE_INVALID", "HASH_MISMATCH", "LINK_INVALID"] as const) { - const wire = vector("owner.document"); - if (code === "SIGNATURE_INVALID") wire.commits[1].signature = "A".repeat(86); - if (code === "HASH_MISMATCH") wire.commits[1].subject.metadata = { message: "tamper" }; - if (code === "LINK_INVALID") { - wire.commits[1].subject.parent = null; - resign(wire); - } - const input = encoded(wire), - handle = await openDocument({ - bytes: input, - model: { ...model, initial }, - system: { ...system, replay }, - signer: await owner(), - }); - expect(handle.state()).toEqual({ status: "inspection", reason: "invalid" }); - expect(handle.inspect().findings[0].code).toBe(code); - expect(handle.inspect().history).toEqual(wire.commits); - expect(() => - Object.assign(handle.inspect().history[1].subject, { nonce: "changed" }), - ).toThrow(); - wire.commits.pop(); - expect(handle.inspect().history).toHaveLength(2); - expect(handle.export()).toEqual(input); - expect((await handle.verify()).findings[0].code).toBe(code); - expect(await handle.dispatch("set", { value: "blocked" })).toMatchObject({ - ok: false, - error: { code: "INSPECTION_ONLY" }, - }); - expect(await handle.replay()).toMatchObject({ ok: false, error: { code } }); - } - const malformed = await openDocument({ bytes: new TextEncoder().encode("{broken") }); - expect(malformed.inspect().history).toEqual([]); - expect(initial).not.toHaveBeenCalled(); - expect(replay).not.toHaveBeenCalled(); -}); - -test("Concord exports one raw Ledger container that standalone Ledger loads without framework dependencies", async () => { - const signer = await owner(); - const document = value( - await createDocument({ identity: signer, model, system: createStandardSystemProfile() }), - ); - value(await document.dispatch("set", { value: "one shared history" })); - const bytes = document.export(); - const raw = JSON.parse(new TextDecoder().decode(bytes)) as Snapshot; - expect(raw.format).toBe("ledger"); - expect(raw.commits[0].subject.metadata).toEqual({ - concord: { system: { id: "concord.standard", version: 1 }, model: model.ref }, - }); - expect(raw.commits.every(({ subject }) => subject.suite === "ledger-ed25519-v1")).toBe(true); - expect(raw.entries.every(({ subject }) => subject.payload.type === "plain")).toBe(true); - expect(await verifyLedger(bytes)).toMatchObject({ integrity: "valid", head: raw.head }); - const standalone = await createLedger(); - await standalone.load(bytes); - expect(await standalone.export()).toEqual(raw); - const entries = await standalone.replay(); - expect(entries.map(({ entryId }) => entryId)).toEqual(raw.entries.map(({ id }) => id)); - expect(entries.at(-1)!.payload.type).toBe("plain"); - expect(JSON.stringify(entries)).not.toContain("one shared history"); - const reopened = await openDocument({ - bytes: encoded(await standalone.export()), - model, - system: createStandardSystemProfile(), - signer, - }); - expect(reopened.state()).toEqual(document.state()); -}); - -test("prepared encryption nonces survive Ledger authoring and wrong parents fail before signing", async () => { - const identity = await owner(); - const system = createStandardSystemProfile(); - let wrongParent = true; - let preparedNonce = ""; - const profile = { - ...system, - async prepare(input: Parameters[0]) { - const result = await system.prepare(input); - if (!result.ok) return result; - const entries = result.value.map((entry) => structuredClone(entry)); - preparedNonce = entries[0].nonce; - if (wrongParent) entries[0].parent = `commit:${"0".repeat(64)}`; - return { ok: true as const, value: entries }; - }, - }; - const sign = vi.fn(identity.sign); - const document = await openDocument({ - bytes: bytes(), - model, - system: profile, - signer: { ...identity, sign }, - mode: "draft", - }); - value(await document.dispatch("set", { value: "same context" })); - const before = document.export(); - const pending = document.draft(); - expect(await document.commit()).toMatchObject({ ok: false, error: { code: "SYSTEM_FAILED" } }); - expect(sign).not.toHaveBeenCalled(); - expect(document.export()).toEqual(before); - expect(document.draft()).toEqual(pending); - wrongParent = false; - const receipt = value(await document.commit()); - const raw = JSON.parse(new TextDecoder().decode(document.export())) as Snapshot; - expect(raw.entries.at(-1)!.subject.nonce).toBe(preparedNonce); - expect(raw.entries.at(-1)!.id).toBe(receipt.entryIds[0]); - expect(document.inspect().entries!.at(-1)!.entryId).toBe(raw.entries.at(-1)!.id); - expect(document.state()).toMatchObject({ projection: { value: "same context" } }); -}); - -test("Ledger signing callbacks retain Concord's synchronous reentry guard", async () => { - const identity = await owner(); - let document!: Awaited>; - let nested: Promise | undefined; - const signer = { - ...identity, - sign(message: Uint8Array) { - nested = document.dispatch("set", { value: "nested signer command" }); - return identity.sign(message); - }, - }; - document = await open({ signer }); - value(await document.dispatch("set", { value: "outer command" })); - expect(await nested).toMatchObject({ ok: false, error: { code: "HOST_CONFIGURATION" } }); - expect(document.state()).toMatchObject({ projection: { value: "outer command" } }); - expect( - (JSON.parse(new TextDecoder().decode(document.export())) as Snapshot).commits, - ).toHaveLength(3); -}); diff --git a/packages/concord/test/storage.test.ts b/packages/concord/test/storage.test.ts deleted file mode 100644 index 7162b4a..0000000 --- a/packages/concord/test/storage.test.ts +++ /dev/null @@ -1,321 +0,0 @@ -import { expect, test, vi } from "vite-plus/test"; -import { identityFromSeed, type IdentityCapability } from "@ternent/armour"; -import { createDocument, openDocument, type CommitId, type Snapshot } from "../src/index.js"; -import { compareSnapshots, verifyDocument } from "../src/protocol/index.js"; -import { createStandardSystemProfile } from "../src/system/index.js"; -import { - createMemoryArtifactStore, - createMemoryExpectedHeadStore, - registerModel, -} from "../src/testing/index.js"; -import { encoded, resign, seed, systemPayload } from "./fixtures.js"; - -function value(result: { ok: true; value: T } | { ok: false; error: { code: string } }): T { - if (!result.ok) throw new Error(result.error.code); - return result.value; -} -const failure = (code: string) => ({ ok: false, error: { code, phase: "storage" } }); -const ownerIdentity = async () => value(await identityFromSeed(seed)); -const head = (bytes: Uint8Array): CommitId => - (JSON.parse(new TextDecoder().decode(bytes)) as Snapshot).head; -const create = async (identity: IdentityCapability) => - value( - await createDocument({ - identity, - model: registerModel, - system: createStandardSystemProfile(), - }), - ); -const open = ( - bytes: Uint8Array, - signer: IdentityCapability, - mode: "immediate" | "draft" = "immediate", - anchor?: Uint8Array, -) => - openDocument({ - bytes, - signer, - mode, - anchor, - model: registerModel, - system: createStandardSystemProfile(), - }); -type ExpectedStore = ReturnType; -async function conflict(store: ExpectedStore, bytes: Uint8Array, expected: CommitId | null) { - const result = await store.writeExpected(bytes, expected); - expect(result).toMatchObject(failure("HEAD_CONFLICT")); - if (result.ok || result.error.code !== "HEAD_CONFLICT") throw new Error("Expected head conflict"); - expect(Object.hasOwn(result.error, "details")).toBe(false); - return result.error.remote; -} - -async function branches() { - const owner = await ownerIdentity(); - const document = await create(owner); - const base = document.export(); - const left = await open(base, owner); - const right = await open(base, owner); - value(await left.dispatch("set", { value: "left branch" })); - value(await right.dispatch("set", { value: "right branch" })); - return { owner, base, left, right }; -} - -test("raw memory stores copy buffers and do not turn stored bytes into trusted state", async () => { - for (const store of [createMemoryArtifactStore(), createMemoryExpectedHeadStore()]) { - expect(value(await store.read())).toBeNull(); - const input = new Uint8Array([1, 2, 3]); - const writing = store.write(input); - input.fill(99); - value(await writing); - const first = value(await store.read())!; - expect(first).toEqual(new Uint8Array([1, 2, 3])); - first.fill(77); - expect(value(await store.read())).toEqual(new Uint8Array([1, 2, 3])); - const untrusted = await open(value(await store.read())!, await ownerIdentity()); - expect(untrusted.state()).toEqual({ status: "inspection", reason: "invalid" }); - expect((await untrusted.verify()).integrity).toBe("invalid"); - } -}); - -test("expected-head create is explicit and conflict snapshots are detached outside JSON details", async () => { - const { base, left, right } = await branches(); - const store = createMemoryExpectedHeadStore(); - expect(store.expectedHead).toBe(true); - const absent = await conflict(store, left.export(), head(base)); - expect(absent).toBeNull(); - value(await store.writeExpected(base, null)); - const remote = await conflict(store, left.export(), null); - expect(remote).toEqual(base); - remote!.fill(0); - expect(value(await store.read())).toEqual(base); - const next = value(await store.read())!; - next.fill(0); - const again = await conflict(store, right.export(), null); - expect(again).toEqual(base); -}); - -test("competing create-only writes install exactly one complete artifact", async () => { - const owner = await ownerIdentity(); - const first = (await create(owner)).export(); - const second = (await create(owner)).export(); - const store = createMemoryExpectedHeadStore(); - const attempts = await Promise.all([ - store.writeExpected(first, null), - store.writeExpected(second, null), - ]); - expect(attempts.filter(({ ok }) => ok)).toHaveLength(1); - const winner = value(await store.read())!; - expect([head(first), head(second)]).toContain(head(winner)); - const rejected = attempts.find((attempt) => !attempt.ok)!; - if (rejected.ok || rejected.error.code !== "HEAD_CONFLICT") - throw new Error("Expected losing create conflict"); - expect(rejected.error.remote).toEqual(winner); - expect((await verifyDocument(winner)).integrity).toBe("valid"); -}); - -test("competing expected writes retain both divergent local documents and expose the winning remote", async () => { - const { base, left, right } = await branches(); - const store = createMemoryExpectedHeadStore(); - value(await store.writeExpected(base, null)); - const originals = [left.export(), right.export()]; - const attempts = await Promise.all( - originals.map((bytes) => store.writeExpected(bytes, head(base))), - ); - expect(attempts.filter(({ ok }) => ok)).toHaveLength(1); - const winner = value(await store.read())!; - const losingIndex = attempts.findIndex((attempt) => !attempt.ok); - const rejected = attempts[losingIndex]; - if (rejected.ok || rejected.error.code !== "HEAD_CONFLICT") - throw new Error("Expected losing write conflict"); - expect(rejected.error.remote).toEqual(winner); - expect(value(await compareSnapshots(originals[losingIndex], winner))).toBe("diverged"); - expect(left.export()).toEqual(originals[0]); - expect(right.export()).toEqual(originals[1]); - expect(left.state()).toMatchObject({ projection: { value: "left branch" } }); - expect(right.state()).toMatchObject({ projection: { value: "right branch" } }); -}); - -test("unconditional and expected writes share one transaction queue", async () => { - const { owner, base, left, right } = await branches(); - const store = createMemoryExpectedHeadStore(); - value(await store.writeExpected(base, null)); - const laterLeft = await open(left.export(), owner); - value(await laterLeft.dispatch("set", { value: "later left" })); - const conditional = store.writeExpected(left.export(), head(base)); - const unconditional = store.write(right.export()); - const afterUnconditional = store.writeExpected(laterLeft.export(), head(left.export())); - const [first, second, third] = await Promise.all([ - conditional, - unconditional, - afterUnconditional, - ]); - value(first); - value(second); - expect(third).toMatchObject(failure("HEAD_CONFLICT")); - if (third.ok || third.error.code !== "HEAD_CONFLICT") throw new Error("Expected queued conflict"); - expect(third.error.remote).toEqual(right.export()); - expect(value(await store.read())).toEqual(right.export()); -}); - -test("expected writes capture candidate bytes at invocation and reads cannot mutate later checks", async () => { - const { base, left } = await branches(); - const store = createMemoryExpectedHeadStore(); - const first = new Uint8Array(base); - const creating = store.writeExpected(first, null); - first.fill(0); - value(await creating); - const candidate = left.export(); - const writing = store.writeExpected(candidate, head(base)); - candidate.fill(0); - value(await writing); - expect(value(await store.read())).toEqual(left.export()); - const external = value(await store.read())!; - external.fill(0); - expect((await verifyDocument(value(await store.read())!)).integrity).toBe("valid"); -}); - -test("invalid candidates and expected arguments fail atomically without changing stored bytes", async () => { - const { base, left } = await branches(); - const store = createMemoryExpectedHeadStore(); - value(await store.writeExpected(base, null)); - const corrupt = JSON.parse(new TextDecoder().decode(left.export())) as Snapshot; - corrupt.commits.at(-1)!.signature = "A".repeat(86); - const malformed = [ - new Uint8Array([1, 2]), - new TextEncoder().encode(JSON.stringify(corrupt)), - null as unknown as Uint8Array, - ]; - for (const bytes of malformed) { - expect(await store.writeExpected(bytes, head(base))).toMatchObject(failure("STORAGE_FAILED")); - expect(value(await store.read())).toEqual(base); - } - for (const expected of [undefined, "not a commit", {}, `commit:${"G".repeat(64)}`]) { - expect(await store.writeExpected(left.export(), expected as CommitId)).toMatchObject( - failure("STORAGE_FAILED"), - ); - expect(value(await store.read())).toEqual(base); - } - value(await store.writeExpected(left.export(), head(base))); -}); - -test("corrupt current bytes block expected writes and remain readable as raw evidence", async () => { - const { base, left } = await branches(); - const store = createMemoryExpectedHeadStore(); - const corrupt = new Uint8Array([7, 8, 9]); - value(await store.write(corrupt)); - for (const expected of [null, head(base)]) { - expect(await store.writeExpected(left.export(), expected)).toMatchObject( - failure("STORAGE_FAILED"), - ); - expect(value(await store.read())).toEqual(corrupt); - } - const evidence = await open(value(await store.read())!, await ownerIdentity()); - expect(evidence.export()).toEqual(corrupt); - expect(evidence.state()).toEqual({ status: "inspection", reason: "invalid" }); -}); - -test("an expected-head adapter does not infer rollback or document-selection policy", async () => { - const { owner, base, left } = await branches(); - const store = createMemoryExpectedHeadStore(); - value(await store.writeExpected(left.export(), null)); - expect(value(await compareSnapshots(base, left.export()))).toBe("behind"); - value(await store.writeExpected(base, head(left.export()))); - expect(value(await store.read())).toEqual(base); - const unrelated = (await create(owner)).export(); - expect(value(await compareSnapshots(unrelated, base))).toBe("unrelated"); - value(await store.writeExpected(unrelated, head(base))); - expect(value(await store.read())).toEqual(unrelated); -}); - -test("remembered heads reject stored rollback while unanchored older history remains valid", async () => { - const { owner, base, left } = await branches(); - const store = createMemoryExpectedHeadStore(); - value(await store.writeExpected(left.export(), null)); - const anchor = value(await store.read())!; - value(await store.writeExpected(base, head(anchor))); - const older = value(await store.read())!; - const anchored = await open(older, owner, "immediate", anchor); - expect(anchored.state()).toEqual({ status: "inspection", reason: "freshness" }); - expect(anchored.inspect().findings).toMatchObject([{ code: "STALE_HEAD" }]); - expect(anchored.inspect().verification.integrity).toBe("valid"); - expect(anchored.export()).toEqual(older); - const unanchored = await open(older, owner); - expect(unanchored.state()).toMatchObject({ status: "ready", projection: { value: "" } }); - expect(unanchored.inspect().freshness).toBe("unanchored"); -}); - -test("dispatch and local drafts do not publish, and reopen reconstructs committed bytes only", async () => { - const owner = await ownerIdentity(); - const store = createMemoryExpectedHeadStore(); - const immediate = await create(owner); - value(await immediate.dispatch("set", { value: "committed locally" })); - expect(value(await store.read())).toBeNull(); - const draft = await open(immediate.export(), owner, "draft"); - value(await draft.dispatch("set", { value: "pending locally" })); - const staged = draft.draft(); - expect(value(await store.read())).toBeNull(); - value(await store.writeExpected(draft.export(), null)); - expect(draft.draft()).toEqual(staged); - const reopened = await open(value(await store.read())!, owner, "draft"); - expect(reopened.state()).toMatchObject({ projection: { value: "committed locally" } }); - expect(reopened.draft()).toBeNull(); - expect(draft.draft()!.preview).toEqual({ value: "pending locally" }); -}); - -test("external failed I/O preserves the local committed artifact and pending draft", async () => { - const owner = await ownerIdentity(); - const document = await create(owner); - value(await document.dispatch("set", { value: "local commit" })); - const draft = await open(document.export(), owner, "draft"); - value(await draft.dispatch("set", { value: "pending after local commit" })); - const before = draft.export(); - const state = draft.state(); - const pending = draft.draft(); - const write = vi.fn(async (_bytes: Uint8Array) => ({ - ok: false as const, - error: { code: "STORAGE_FAILED" as const, phase: "storage" as const, message: "offline" }, - })); - expect(await write(draft.export())).toMatchObject(failure("STORAGE_FAILED")); - expect(write).toHaveBeenCalledOnce(); - expect(draft.export()).toEqual(before); - expect(draft.state()).toEqual(state); - expect(draft.draft()).toEqual(pending); - value(await draft.commit()); - expect(draft.state()).toMatchObject({ projection: { value: "pending after local commit" } }); -}); - -test("protocol head verification is independent of installed model support and profile authority", async () => { - const owner = await ownerIdentity(); - const other = value(await identityFromSeed(new Uint8Array(32).fill(2))); - const original = (await create(owner)).export(); - for (const mode of ["unknown-model", "unknown-system", "invalid-owner"] as const) { - const snapshot = JSON.parse(new TextDecoder().decode(original)) as Snapshot; - if (mode === "unknown-model") - ( - snapshot.commits[0].subject.metadata!.concord as import("../src/index.js").Declaration - ).model = { id: "concord.unavailable", version: 1 }; - else if (mode === "unknown-system") - ( - snapshot.commits[0].subject.metadata!.concord as import("../src/index.js").Declaration - ).system = { id: "concord.unavailable", version: 1 }; - else { - const entry = snapshot.entries[0].subject; - if (entry.kind !== "system") throw new Error("Expected system genesis"); - systemPayload(entry).data.owner = other.publicIdentity; - } - const bytes = encoded(resign(snapshot)); - expect((await verifyDocument(bytes)).integrity).toBe("valid"); - const store = createMemoryExpectedHeadStore(); - value(await store.writeExpected(bytes, null)); - expect(value(await store.read())).toEqual(bytes); - const opened = await open(value(await store.read())!, owner); - expect(opened.state()).toEqual({ - status: "inspection", - reason: mode === "invalid-owner" ? "invalid" : "incompatible", - }); - expect(opened.inspect().findings).toMatchObject([ - { code: mode === "invalid-owner" ? "SYSTEM_EVENT_INVALID" : "REQUIREMENT_UNAVAILABLE" }, - ]); - expect(opened.export()).toEqual(bytes); - } -}); diff --git a/packages/concord/test/vector.json b/packages/concord/test/vector.json new file mode 100644 index 0000000..84b430c --- /dev/null +++ b/packages/concord/test/vector.json @@ -0,0 +1,50 @@ +{ + "document": "{\"commits\":[{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"R7uGlKsGUPHV-gL26z5K4g\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB6bytnTDJFUTE3VDVQM3NTMjIvZGJmbEtCZThIRlRjOWE5em96UGhOdTNNCnR6aGYrZzYybWQ2MHVkcU1YRzREMzBoYWUvanVEa0dTNDVJVGdTWVdGWkkKLS0tIFJhdEdFVVhyNEczWUQ5VHZkN2xPMXAya1QvVEVETS9KdSt3dVpDanVieVUK0LiW7ag7CQOr13XwebyHKZz7MzNKppt5DfKMcn6dNjWc_kWHcZzWC59zFVLmc8WRlyK9yrh1ff4SabZ5XPhZ4qO8POSQHkOT0Nr_H2fqvxp0M48NHFwYG1G7wi6c1GREsHtz-eFBSJeKvJfIHCi-KLWZaI4oRKdAQtOcAaOFAOa5j53vhguUUPAfAs34LvP4IEDEL1yPWbGCiXuUHug1mrJenEQz7OvmSjrFfmV8IScSGCcFAvaqIwq_uj19OXKMqX1VnlTNG4u2uNUtnGfE-VydI81kYdlp7TUihbGAozIgssx80t-R7D85zMiYMyfjzyQR5QYS1EP2pgBcPWd_pQBW_MwK7aZwMhO2F3suPwE1LmzH7tMVWEk5PunatuETcAg6S2teltOFQhnlxPpRyTlgzi3P5kUDv6WPK4EELoNMPctawsM\"},{\"kind\":\"concord\",\"nonce\":\"I1MB582R73mJlCL-7JP33g\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSA2NDVDRVFSMkhyblgyeHRWKytaczI2dW0xOUxBNWs1cXpWbjZLdGtOandRCitzdm1rOEZpUTR1K1BSa0dsNEpIS3JoUXZ4enNhRXdPeWZ6K2xXSHl4QUkKLS0tIEZkMThtZmFtcy9nNDU3emFXV1N4UHZ2RzRNWWZWMVJINVF2U3hEa2owV00KeiDaPz3DrlCSE2picyUwuqBI80CuKMexNsAumzbI0jlr6IswuajNmYMpJhP9L_WsUk3CrX0zyIvxpwFV-FZ4b4wIxSUqlxz60k1ln7qnc5OpuCMbIsb0YssI_-0saC9Xx6jwA7OV-pugRE9cLULE2Ud28h8-h-c6jirmtr4NZo_NYXjTWDaerb_VL1GeCtDRzsy6SzICyVPuCDxn0_jc-R2qCEGMg5wT0lhDBJ-1KNo\"}],\"nonce\":\"ED9xjVZHFjMWcPdCDr4NbA\",\"parent\":null},\"proof\":{\"createdAt\":\"2026-11-28T01:44:08.209Z\",\"format\":\"seal\",\"signature\":\"tFOviUwoHAQzad3o5x4t2CUdXjQUEkgR_Ce9CGI8vzetMOsyO7Drib5hGI512v683Fvs-o1QVTA-akDS8E97BA\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:e0238194e0154a81c5e00edf213b9d75b1a3eecee95f5ef57cb3aec7ace91b7d\",\"publicKey\":\"Y3zx3tGeabdvTGSomqKQCa7kLBNqBjEWBYQIhem11qM\",\"version\":1},\"subject\":{\"hash\":\"sha256:ae2a56b8fa48023d4699326af126da065c58ec41981d314a196b3740ef223a18\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"c9GdZUTul0J-F058fgtQ7w\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSAvZkFpOFUzdUFQMXpXNFFLUGpIQk9WMjYwUTlCd1IxanU3YzRHZElXLzJNCmlvZExRd3Qva3cra2kwT1hKSTdwSWd4eUExcmdYaTFHeU1saDRweWRkdVUKLS0tIDJBY3QwMzNjdGNXUHdYRzVRZDNoYm1xWS9ReXpiRzdBUGR5bzc3dW5nUDQKpprGm67Fc9u7eOf3_mks5S54xc6tvusOYOCpHQaliB672mmEiP4OES7GtLk4bSD6ghknGF55dYaLXqDiv4nrCGKwvzdgIP-m4b4RXpPeLm_o_l4lAyH1BN5PvhKQkgBR-w7bvppcjXPlCrHQ4tKgHn-jd-1XM6iWoN7tGfUe1BL6BdRcu7Pzc-CcMKhg\"}],\"nonce\":\"0iIcJ8sAAz6FCyU0p6cwyw\",\"parent\":\"commit:7340fcd6771c66a38da20960081eced6c04f11a83c7d48b76573c189f47f118e\"},\"proof\":{\"createdAt\":\"2026-11-28T01:44:08.225Z\",\"format\":\"seal\",\"signature\":\"igTKhETYHG2F8oYtIfX-82RE_pcWlel1hH0ctxm3cpvqHGmdj41Qxvhzh-2Ri2gyvl5NzDWKRycvu02YVgU-DQ\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:e0238194e0154a81c5e00edf213b9d75b1a3eecee95f5ef57cb3aec7ace91b7d\",\"publicKey\":\"Y3zx3tGeabdvTGSomqKQCa7kLBNqBjEWBYQIhem11qM\",\"version\":1},\"subject\":{\"hash\":\"sha256:da15dfa9268c793dfc24847cece64dcbecdad443568e6ef60d418c2a0dfbfb37\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"6fRk7yQiwwTYeYByICJa8g\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBWdjNucGxKT0ptcHBKVVNCTXFRTkpwVmJ6YkdhVE8xR0FrdGRHZlVudHhzCm5TZS9uVGttbGhmTDRBU0lkRHhPaVZ6Ykpsb0JpdlpSdUkyTTJpMjRMMEUKLS0tIFhoK3dkNW1ERGkwUVRhOGQ4RXZHSEw5NmUzVDFMaCsvNnAzQ0FLSnNmM1EK3vUJXGIOWcNp4dF0IXG24SZOwNpqYGg3VVt2rFzkvS-A0pyaodM9-N6yhfW98M59d_PbmIFbgdGuBVY_DvqeFKIth3QlG5javee4Oo765WUGjeLlBOeVKKlGRh2-8sCbsbfJ-6xKpzmIpKF34GnKJWN33or9jSyiePA0gz4bt_PbfFo8O1dcjHNsO5sq7I-KkxtVA7NiOk2s0LyZwPdKar3uMRCWxP4X1QnvWjFwu2yfQUGQ9xU5uQPNBse27yDWiKeBDoOggxeUPvaCd2Z_HuM4681gagwl4wknxhY6RMeZgJgg5TzAgs47AGSlF2wREstoffO-nf77l2O-mr-AReD4F69Hg-Ir0HNkj2v4MsO9S_fzsRL0fcAGuFJ8aGvyVeaoSAsBGmnS2_yzsP2gWf-JmQQ91c_alUOE7miINEVTuw4NslY\"},{\"kind\":\"concord\",\"nonce\":\"Vd372OcLK7w-p4HZa5my9Q\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBaY1dtcFd0a0h5Y0grMnNDR2hrdkdTWDZiRnFmN2tHRXEyRzE1YldYbG04Cmhxd3pkREpkNTVXaE5RcHFpK21WWTlLcHNBQzJ4UTRUQkRmYnRuSU0vTkUKLS0tIHRqd0FWNE03MWEzczB2QnU5VXRzMjhGQmRxZ292WnZqZERKVUFnd0J1U1EKyEs9_gzX1zAdnsmCx3yIswTMyiTnDYyzuORDJRM3cya4M2jjFQGYub7egxEZvscXn1cvY0peonHlQ1rmp-4AP35fyJR8u3gJF1jQiQ5-QNLP_A6Luj3EKEe7b-lL6rrC4kHRfbdja2p5pjG7PPRcQZxyVYq8zfvAiDncxA0v74aS7Hw__TCBtip04jQII8GoqZ7BD1PZLsE8hpk50rhMU0wHSf54JMJ625mHWeddliA\"}],\"nonce\":\"p_ufsiGCYEacxVq3gfGaVg\",\"parent\":\"commit:31628a58632136454fac2c4ac02c5570af8c3df597076a855b7f158ec89ede0a\"},\"proof\":{\"createdAt\":\"2026-11-28T01:44:08.232Z\",\"format\":\"seal\",\"signature\":\"jV6b5lTwTC4JRoJxbsnYjhoQQ_WK4zafdmilvhWG9jjNUZUxiBRSWnfp6SJKl-srV7hmKmFLeq2ULwN2b3jKAA\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:e0238194e0154a81c5e00edf213b9d75b1a3eecee95f5ef57cb3aec7ace91b7d\",\"publicKey\":\"Y3zx3tGeabdvTGSomqKQCa7kLBNqBjEWBYQIhem11qM\",\"version\":1},\"subject\":{\"hash\":\"sha256:c670a7c6049259cc86c97c0ff590075837be426ec6bb2f3d70680f5a67f03bf7\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"BaFrFv4pkMp_-kLVsjLStg\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBDT3l1R1VFRzc3NHhjNFJib0tTRytOaklqajhDQjRaNXQ0ZUZxQVVjTlJZCkhaZkhwTzZVSU16Vkh0a3FxTkVubll4YnN3MWJtM1oxV0kwSkhMSlVKb1kKLS0tIE5HY09uOUJxMHV2eE5BWkJzN1FlN0xYS0cwaU9yUVRONk1iUTVIMmNoZHMKMGehGKioqUFBJax30jg6QlK05xk6-k9l33NmoD7iDuOssNqNMKress6Q-of5f75Gf_c8CkKU4bk0lvjSfS-LWxZIzqENR1Svmemi9L4bnOk4WqlERFBNDfWyRBDaia1tVKeAzQufIuQVcvsovFo_D70lzMILh7wTrtS5gjoD1myTtPtKOvQ-0Dxjb-BGvShxAxDukHYeNwveI3EnaVR96YvrauqD4d3pVrDBTxyr4-A2C17QhrEJ6a6kg7lx6dtc-wPd5jmtHHRJ2w34ITH4i0_UFZYR7OMqidz2EkO103SMQLXt-YK5i8hICr7Qr8eJB1Bi5dLloLG3TwAZo24LNGqq\"},{\"kind\":\"concord\",\"nonce\":\"r5u8nUk2d7ak_dwas-uFjw\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSByclovM1F2d0tQNGZIbU1HMVpuK1IwdUZ1bE5PSUMyQmZFWU1GNG5UL1RVCkpjZ08zRUx2NThVYytmaGl3elgzcE55eUtCdHFkWnp1cDdUaFArcVZoVEkKLS0tIGRZSjlEdHFvdysvenZkWmEzUlVKOW12dVVIc2NUdEhaVXVQd3ZhVlMwRXMKx-Feh4Gjcw8pWq4jV7ILzVygi-tA4y_5AQh85tKaDnfA4tIhdMiLoeSqPoLMJzFO_RWhRiXmEgm-orhvhmZ92CP-OD4GsdIGk-LaVb25GKX9lJrr9S2hMt1thRvKr-xacGKyuL3U5uV3hSyF0LhXpzJ6a9s7ay4-rzd2uxBzVqyZbcFhqgy3Px2mvLxB0RX4xSZlOAxtTj3GSQexPWwc6IpclF3iYNQPv_9CDE9Q1w0\"}],\"nonce\":\"l6cwuAXWZWyhhUxIlELvdg\",\"parent\":\"commit:ac456dfaab67cf36474c8805b53d0679c2bffce27efa2158163d74f64c4b6ac6\"},\"proof\":{\"createdAt\":\"2026-11-28T01:44:08.241Z\",\"format\":\"seal\",\"signature\":\"uCZBJ5u-Nt6pMjmzXwmrgzfRgmn6-dwOKl9xL1OaZSSyOCBHTgMA7x2N9koTBifAWcuyMr9ahnrUmG62XE4MBA\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:e0238194e0154a81c5e00edf213b9d75b1a3eecee95f5ef57cb3aec7ace91b7d\",\"publicKey\":\"Y3zx3tGeabdvTGSomqKQCa7kLBNqBjEWBYQIhem11qM\",\"version\":1},\"subject\":{\"hash\":\"sha256:e3d737bc664d850cc4397870ffeae93fe187c850a49364a0f6daa73a11fa210b\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"K9loXKEtT45JajurCLw8ug\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSAvRUdsbW1PbGpnbmUxM0xsZU8xRDhhcTZiaXhPRGFqdEhwbWhqaFhpa3lJCjF0L09QUWFHZ2FRSjVBRHdpTFp3YnpScmVIc2c1d0VuaXZLR1ZkWUN2cU0KLS0tICs1dUs2VWZPY1hjYzhMNVBKNjlraXdSdTlaQnFUR0lFM2ZqcWtUY0tWNFEK4W0BpsJtcMCpuB4SkonL1qVR0Qwqk2f30uwdy3bBIuGZS7gbKyQS2K8VeYOpa-r625PUfgB3OnbN60bi9PGgCWC2LaLt-3hPcvx5AYH09XX5YyXv4_b_wMF4NGgIwrR2yUHL5KYAUR-9Oc4k2yzU7OWOzVZb7PXgWsOEcNq19UCA4tB1qMJYtglEbtNJJy0yeEoLeTnECu9zmJ4V4fBn1M6uVqhnZ6_G6x4bqvQ5y8alMtchKSUyVgxuRjX9icWa9yK3nVi89wRUP5fBaZSJLrnwl7FBPdgb246saMT-VHsSAopfBhARk41YDqt6oM7A49W_75OZ1Cm9SRMUomUT8Ok\"},{\"kind\":\"concord\",\"nonce\":\"nO662De1wiRz61X67nfwCg\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBrSGhrRklkdHNhUlM0SzdXOE1QWHNWNVg4ZXdVWGlxZXY2Mk0zRXZKeTJBCnBYZnhiNERXNitjMnZoc0Z0ZWhVdXk3b29oc0ROZjhaKzNNalZiWUsyZ1kKLS0tIGtlMUhRUzRrbVJ5T2h5TTEyZTFnOU1jNmVGRFV6WHB0VGo4bmtKT0JpSzgKbk9wASmWs2Nouk_afF1Z9BBQ76E2R3onDpuv9TfROzS_BXV9lp1gNn5-5Yz97JLpSEw_QYgN5v-tCWAhgfUZ0PdxDbuqhCb8GOQun7GANPGrpuWvF9DpkTezrBP6PiLezfGAgYSa5DLgjxSvG1PQ7eYD2oTSFRkVWaeEiOuhGg8n_5wqNL3SGN14qyxq7GdSwfntFl7HPM7qxb1fsUX_T0jLkJ4udEjCLJXdWZqztnU\"}],\"nonce\":\"N6VDGfFN6M7jBnK9GD5cZQ\",\"parent\":\"commit:f593835f1d71bee899e43d4139c290ee59880f1b2e32b76e72ab8aaa0fadbd7b\"},\"proof\":{\"createdAt\":\"2026-11-28T01:44:08.250Z\",\"format\":\"seal\",\"signature\":\"1CDOCrY_wtftImdoHZrmcNF5k7MeOeiwE_TVvQCI3PuGT8clMxkXPQrWiGGuyveQuKWBLt3bDSVaTW5sJE5XBg\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:e0238194e0154a81c5e00edf213b9d75b1a3eecee95f5ef57cb3aec7ace91b7d\",\"publicKey\":\"Y3zx3tGeabdvTGSomqKQCa7kLBNqBjEWBYQIhem11qM\",\"version\":1},\"subject\":{\"hash\":\"sha256:11cc8c5c18c235fed0f431a67c61af0c422ede3aa67d5f1881dba1925bfccceb\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"c0UEFprAfD48GW-P3jt21A\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBhRWF5VHM3RExwMWZwVmc1MjhHcjJYd2RjbTJ0UXExQlJ2Rk5FVWUxdzNBCjd2eDN4eVUvL3lzUVluVDlNdU5DQkVVN0tkNFB2MkhhWFVsRlFMUzFKTHMKLS0tIDZXM3h1akc2SDdhWXBvV2dFaXlCa05veEVKNE5WWFhBV2R0dm4vSWFFYzQK8A0Lh_ecqtVH5WG69r1GluQL-DxUo0Mbg9KFPuujCCg-cIQGdxD1KGkUN8GtDIaDcWyFkPQCANELRKlDa13NG6iXF-JjT5Nj0A-CSdAICAVGtKkoRkzE6lDOPxdOA8UBeuFFq53JKxsO8sJDXsvw5vBFHXW73AwJaQFmncjlebZ_ec1uOMkiNXdPCTeWClTqHA\"}],\"nonce\":\"MwA9FVMHsPRMfc6J_8It-g\",\"parent\":\"commit:8fcba169608dbe46b715237ee0220536208339ba43ec48a107d8b02dda30a957\"},\"proof\":{\"createdAt\":\"2026-11-28T01:44:08.256Z\",\"format\":\"seal\",\"signature\":\"uvUQ5mp_xGb-ORXcRDnlPLkdgdeb7Q10xMUZicoh2bzWwbC7YwF9V-BmvexRc58GUrIFVE-xChD47ZrkdxnzDQ\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:e0238194e0154a81c5e00edf213b9d75b1a3eecee95f5ef57cb3aec7ace91b7d\",\"publicKey\":\"Y3zx3tGeabdvTGSomqKQCa7kLBNqBjEWBYQIhem11qM\",\"version\":1},\"subject\":{\"hash\":\"sha256:a52a7ca9a26586064eaa14a751071a21d81030bd48f9f42d4ca5ae95e0f5d368\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"BF-5kKsWepOjcL8v58rhUw\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBBUElFY1BQeGEvc3BUd3NiTmI4TlBubnhqaGlVVERvSkdKZEF0Rm9nSVhZCjI2ZGpZbnp6ejZraGFVbFRWOVpPekxnMlVOdlVPYWliQ2tSanlqN2haaFkKLS0tIEc0anI2b1FKcjJ0bzFNTEhna1Bpdk0zMjBNRDEzd2pGZ3FsNStIczVYNEkKL1czO2Y4aBoxKO6GTnioSjenuPyg4UY_0DNRtJd5yF9cD6nHb1NHEBILdhmjkcPwvzb-xI7TeaKFO_lH5c6c7aDcqyNvcWA2TW-jOcRBbFDfJa1C9mLDvxi-Uzmy0tyEgj3efVUo5w552gcUUQFO4MJL2AkXnXOHFZ1xX9V6Pnuo0Exe573qYHnQi0YK9IjBWrgrhqZIoPSqlwUcEas2ne_xQslNOVDSXxWtJfMpvR1Ih0FcN5vPNKfeyTpZbSi0l6Yzpe4ZiJhuZ-vClt5vAIrRib7lF_9YD-EtBefg_W8i5eW4u_xeh1tU8myN2WjWPk5HcB5KTdhNNqljMm5lqbUt\"}],\"nonce\":\"W7tKA9a71gz40HyGc4_6YA\",\"parent\":\"commit:bfdc28a8f8f9ed53e04352ea4acb900ce57e3c651a4c6f1d6719d062885ad1ab\"},\"proof\":{\"createdAt\":\"2026-11-28T01:44:08.262Z\",\"format\":\"seal\",\"signature\":\"Zt1WNKbkEF60a_Uj2RWhtbXKs_RqMdSUYBG5hbmlVR9DURn6l31LZ-dFAlpviLVdAxTe0W1n5EXieNdQ95RLBQ\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:e0238194e0154a81c5e00edf213b9d75b1a3eecee95f5ef57cb3aec7ace91b7d\",\"publicKey\":\"Y3zx3tGeabdvTGSomqKQCa7kLBNqBjEWBYQIhem11qM\",\"version\":1},\"subject\":{\"hash\":\"sha256:3015b294fc022190700bf6c79a7f45ab9a9e3a1dd455400b0097bc9ed4e98acf\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"iF2IlyByc8rwKhQXsbDcGg\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSAxSnhGNDJpMnp6UkNCVjlacGpaSzJFRW91cWVGKzB2OWdXcUpnOVQ0R0RVCks0LzBHblEyeFRZUFAxZVVWSlI0LzNmc24xMWREeXhMUzNyS0NCS0ZtbFkKLS0tIGFJSTJDVkxUaFp6MExhajZKMWY0TjB1SVZ4SGxyNGFNZ05UWFBNdFdhRlUKJU2dKGW9U5LhdzS3ccIagbqcA8bFOUqv_M_NUbQ0oF-aZTScLZCPHlNtz44dzpYTZ2mKBttXs06_zbq9LjIvjcBAUw8tvZYWkmVDEDC8zuOdxMGEwC2_khFL5KoeafZTJH7A8Urogs6WntAiPl6tdyOXW0OK51brS02nFxHVfCE4Y0kC66GCaZvI2PR5xiauau0DtHsu_xbPWDwH2DywrkncJG6GTakwjKYi-6Vj_eeaKw1vtgQ3GNFhAZsnTLXqjnR1-tumfsYk0mYJxed0MKiiJ8Z9RpmsnE1DWhVWf3yKOKXtZe2DaO9OedwWYqbmpWfKWWw6Vv_6596n6jh9\"},{\"kind\":\"concord\",\"nonce\":\"u_I91aUEswp0nkBdPV41KQ\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBHeEhvUld6VmcrZU02UEpwU1d4WTcwVDA4NEdVL0UyN0QvaklkTFFWR25VCkgwazZQM0pOVjdrenNWZ25IeWNsSHB2c3d5RE1xNVFRS3JDRWcrdnNhSncKLT4gWDI1NTE5IENwMFhQaWRtTmZhZ3RjN2lnSjlhMmsxemxYR3BYZGRZUkJ3OFN2Sjg5VmMKeGZmQytkdnRaZVhwWE5Pc1lOeDNmaXVWOWVrZXZXdGlPamVETHNjbXU2WQotLS0gNVRSTUJlbWsvRXl3eXY5NWJFS3NUcnpSZ2Y0eWgraEVPV1QrUWlkRHZTdwofiTCqEhecq3XmBeqlbrpYO1i0JOBjegNjgIfNDY5-kwDLNXLJ1AMiTTfIYV31aCsoi5KSbeGln_sjdmYsMEaDQOS91ZtfFqj_sUYsDuU6VvIy356m2AQam7ZMfiShqK3z9C9e6Ye3z7CmqNQ9Z4e0rbuL2rwLJ7LFc0P16y9yrLO2nKjgi4MTQZyCiXK9_5VFj_BqLU3lRLrPyFA1m1oyq8DBRAOH2fJ2aGT6GeFtOA\"}],\"nonce\":\"daZ0QXpcvcDvtH6VVm4qGQ\",\"parent\":\"commit:85f68201ce3bfad47b06c5e133ff7db4f4730e76d82a98be3b3cf2afad2f3100\"},\"proof\":{\"createdAt\":\"2026-11-28T01:44:08.271Z\",\"format\":\"seal\",\"signature\":\"7eopFGsHZX-Mu7SpC8LQFL-iryEmt778qK8Y6U-9Zfiy-kXemOl8tpzQC4BS696nmDaxI7JthwWjjT3-AT8ADA\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:e0238194e0154a81c5e00edf213b9d75b1a3eecee95f5ef57cb3aec7ace91b7d\",\"publicKey\":\"Y3zx3tGeabdvTGSomqKQCa7kLBNqBjEWBYQIhem11qM\",\"version\":1},\"subject\":{\"hash\":\"sha256:a2f673a0e765fcf4832b78e793791d96602d2737b01e10a98f59b01dd2b28a97\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"XsLZqvzBmZ_5IRCJHALh-Q\",\"payload\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBWbkMrMVhETlR5ZTIxK1JMa1F4bndrVi92NDJpK0x4aDdLb1pmT1FIK3hRCkFZTVhHQjVCNHNLZy8xZzJqM2VhWFVJbnlBb2tYZkdRWldtSUFFdjlIdGMKLS0tIE5wVWxNL1R0c29BTFR5YWFONmhDd01QaEFJSGZiV0U4eTJHb2d2NmtBcncKlantimi4GN2HYc1Y3aS99qf2BLqgp0IfY7qnOJ-uweeu2jh6elo7E8YcIONpgsZ8TdAspFs_vvBBMr-TN9oIiB6rmfllDY41k7VqOqB-Iv4wdeTArffJHZXfH5xuNV5DOvtaFEUh5sYmjfI_olnxI1AHdhVx6GjME7RSxHNjaKT572j1O5J7slOdYCC7FwxL\"}],\"nonce\":\"36Es_obnq6xMzdsQnKk9IA\",\"parent\":\"commit:80474ef2e2cb975cd7738735616ac9203dd900d48cb1542f0a0ed5a6c36c0667\"},\"proof\":{\"createdAt\":\"2026-11-28T01:44:08.277Z\",\"format\":\"seal\",\"signature\":\"p1AWVjAkXfrgVr76NAb1UzJzYeC5GfGWnB5q87-BEU7du7mt13IKRGzYFW8cu-uELPeXHHcbkAuxfYM9-LU3AQ\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:e0238194e0154a81c5e00edf213b9d75b1a3eecee95f5ef57cb3aec7ace91b7d\",\"publicKey\":\"Y3zx3tGeabdvTGSomqKQCa7kLBNqBjEWBYQIhem11qM\",\"version\":1},\"subject\":{\"hash\":\"sha256:7b9e34e9e1970903293fb094f18b0c83a1cc1d520ba922087da434fa5f518888\"},\"version\":1}}],\"format\":\"ledger\",\"version\":2}", + "identities": { + "alice": "{\n \"format\": \"ternent-identity\",\n \"version\": \"2\",\n \"algorithm\": \"Ed25519\",\n \"createdAt\": \"2026-11-28T01:44:08.174Z\",\n \"publicKey\": \"Y3zx3tGeabdvTGSomqKQCa7kLBNqBjEWBYQIhem11qM\",\n \"keyId\": \"e0238194e0154a81c5e00edf213b9d75b1a3eecee95f5ef57cb3aec7ace91b7d\",\n \"material\": {\n \"kind\": \"seed\",\n \"seed\": \"JlI1dY2IQrSCIbjoHgE2f32dBxKtpuTOfQeCK45Yd_E\"\n }\n}", + "bob": "{\n \"format\": \"ternent-identity\",\n \"version\": \"2\",\n \"algorithm\": \"Ed25519\",\n \"createdAt\": \"2026-11-28T01:44:08.188Z\",\n \"publicKey\": \"YoCeViUD9YO55XJKklC-Tkbvl45tYY1yX0IAmc9bQKw\",\n \"keyId\": \"990a65fd8bf29c7408d39c16122ad1775e7f810b3c67c56766a1e29de9ce1f4c\",\n \"material\": {\n \"kind\": \"seed\",\n \"seed\": \"6EYAToQCayiR7WVud-Ds5f2d-MmUHyjfUNORkv0Jj6s\"\n }\n}", + "carol": "{\n \"format\": \"ternent-identity\",\n \"version\": \"2\",\n \"algorithm\": \"Ed25519\",\n \"createdAt\": \"2026-11-28T01:44:08.188Z\",\n \"publicKey\": \"4oC0tcqeArSWVEiMFGZ3-lZ0v7nf0FMStgNmhg-FQbQ\",\n \"keyId\": \"a9ca8865f6c98115884d342cebbefafa9dbb7519c6a4aab6d2d18eac187cef21\",\n \"material\": {\n \"kind\": \"seed\",\n \"seed\": \"qqs3Ws_wnRZb5kH4jLDwzYmPk7RyfBTG2mNqDtA0F6Q\"\n }\n}" + }, + "expected": { + "alice": { + "groups": { + "default": { + "notes": { + "1": "in default" + } + }, + "team": { + "notes": { + "2": "before removal", + "3": "after removal" + } + } + }, + "unreadable": 2, + "rejected": 0 + }, + "bob": { + "groups": { + "team": { + "notes": { + "2": "before removal" + } + } + }, + "unreadable": 8, + "rejected": 0 + }, + "carol": { + "groups": { + "team": { + "notes": { + "2": "before removal", + "3": "after removal" + } + } + }, + "unreadable": 5, + "rejected": 0 + } + } +} diff --git a/packages/concord/vite.config.ts b/packages/concord/vite.config.ts index 9e886c6..0251310 100644 --- a/packages/concord/vite.config.ts +++ b/packages/concord/vite.config.ts @@ -5,11 +5,6 @@ export default defineConfig({ ...base, pack: { ...base.pack, - entry: { - index: "src/index.ts", - "protocol/index": "src/protocol/index.ts", - "system/index": "src/system/index.ts", - "testing/index": "src/testing/index.ts", - }, + entry: { index: "src/index.ts" }, }, }); diff --git a/packages/concord/vite.config.ts.timestamp-1774262297922-ffd76e35ea668.mjs b/packages/concord/vite.config.ts.timestamp-1774262297922-ffd76e35ea668.mjs deleted file mode 100644 index d149f52..0000000 --- a/packages/concord/vite.config.ts.timestamp-1774262297922-ffd76e35ea668.mjs +++ /dev/null @@ -1,83 +0,0 @@ -// vite.config.ts -import { dirname as dirname2, resolve as resolve2 } from "node:path"; -import { fileURLToPath as fileURLToPath2 } from "node:url"; -import { defineConfig } from "file:///Users/sam/dev/samternent/home/node_modules/.pnpm/vite@4.5.3_@types+node@24.10.4/node_modules/vite/dist/node/index.js"; -import dts from "file:///Users/sam/dev/samternent/home/node_modules/.pnpm/vite-plugin-dts@1.7.3_@types+node@24.10.4_vite@4.5.3/node_modules/vite-plugin-dts/dist/index.mjs"; - -// ../../scripts/vite/package-lib-config.ts -import { builtinModules } from "node:module"; -import { readFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -function loadPackageJson(packageDir) { - const packageJsonPath = resolve(packageDir, "package.json"); - return JSON.parse(readFileSync(packageJsonPath, "utf8")); -} -function createPackageNames(packageJson) { - return /* @__PURE__ */ new Set([ - ...Object.keys(packageJson.dependencies || {}), - ...Object.keys(packageJson.peerDependencies || {}), - ...Object.keys(packageJson.optionalDependencies || {}), - ]); -} -function isExternalId(id, packageNames, includeNodeBuiltins) { - if (includeNodeBuiltins) { - if (builtinModules.includes(id) || builtinModules.includes(id.replace(/^node:/, ""))) { - return true; - } - if (id.startsWith("node:")) { - return true; - } - } - for (const packageName of packageNames) { - if (id === packageName || id.startsWith(`${packageName}/`)) { - return true; - } - } - return false; -} -function createPackageExternal(packageDir, options = {}) { - const packageJson = loadPackageJson(packageDir); - const packageNames = createPackageNames(packageJson); - const includeNodeBuiltins = options.includeNodeBuiltins === true; - return function external2(id) { - return isExternalId(id, packageNames, includeNodeBuiltins); - }; -} -function resolvePackageDir(metaUrl) { - return dirname(fileURLToPath(metaUrl)); -} - -// vite.config.ts -var __vite_injected_original_import_meta_url = - "file:///Users/sam/dev/samternent/home/packages/concord/vite.config.ts"; -var configDir = dirname2(fileURLToPath2(__vite_injected_original_import_meta_url)); -var external = createPackageExternal(resolvePackageDir(__vite_injected_original_import_meta_url)); -var vite_config_default = defineConfig({ - build: { - outDir: "dist", - sourcemap: true, - target: "es2020", - minify: false, - lib: { - entry: resolve2(configDir, "src/index.ts"), - name: "ternentConcord", - fileName: "index", - formats: ["es"], - }, - rollupOptions: { - external, - output: { - format: "es", - entryFileNames: "index.js", - }, - }, - }, - plugins: [ - dts({ - tsConfigFilePath: resolve2(configDir, "tsconfig.json"), - }), - ], -}); -export { vite_config_default as default }; -//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiLCAiLi4vLi4vc2NyaXB0cy92aXRlL3BhY2thZ2UtbGliLWNvbmZpZy50cyJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiY29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2Rpcm5hbWUgPSBcIi9Vc2Vycy9zYW0vZGV2L3NhbXRlcm5lbnQvaG9tZS9wYWNrYWdlcy9jb25jb3JkXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ZpbGVuYW1lID0gXCIvVXNlcnMvc2FtL2Rldi9zYW10ZXJuZW50L2hvbWUvcGFja2FnZXMvY29uY29yZC92aXRlLmNvbmZpZy50c1wiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9pbXBvcnRfbWV0YV91cmwgPSBcImZpbGU6Ly8vVXNlcnMvc2FtL2Rldi9zYW10ZXJuZW50L2hvbWUvcGFja2FnZXMvY29uY29yZC92aXRlLmNvbmZpZy50c1wiO2ltcG9ydCB7IGRpcm5hbWUsIHJlc29sdmUgfSBmcm9tIFwibm9kZTpwYXRoXCI7XG5pbXBvcnQgeyBmaWxlVVJMVG9QYXRoIH0gZnJvbSBcIm5vZGU6dXJsXCI7XG5pbXBvcnQgeyBkZWZpbmVDb25maWcgfSBmcm9tIFwidml0ZVwiO1xuaW1wb3J0IGR0cyBmcm9tIFwidml0ZS1wbHVnaW4tZHRzXCI7XG5pbXBvcnQgeyBjcmVhdGVQYWNrYWdlRXh0ZXJuYWwsIHJlc29sdmVQYWNrYWdlRGlyIH0gZnJvbSBcIi4uLy4uL3NjcmlwdHMvdml0ZS9wYWNrYWdlLWxpYi1jb25maWdcIjtcblxuY29uc3QgY29uZmlnRGlyID0gZGlybmFtZShmaWxlVVJMVG9QYXRoKGltcG9ydC5tZXRhLnVybCkpO1xuY29uc3QgZXh0ZXJuYWwgPSBjcmVhdGVQYWNrYWdlRXh0ZXJuYWwocmVzb2x2ZVBhY2thZ2VEaXIoaW1wb3J0Lm1ldGEudXJsKSk7XG5cbmV4cG9ydCBkZWZhdWx0IGRlZmluZUNvbmZpZyh7XG4gIGJ1aWxkOiB7XG4gICAgb3V0RGlyOiBcImRpc3RcIixcbiAgICBzb3VyY2VtYXA6IHRydWUsXG4gICAgdGFyZ2V0OiBcImVzMjAyMFwiLFxuICAgIG1pbmlmeTogZmFsc2UsXG4gICAgbGliOiB7XG4gICAgICBlbnRyeTogcmVzb2x2ZShjb25maWdEaXIsIFwic3JjL2luZGV4LnRzXCIpLFxuICAgICAgbmFtZTogXCJ0ZXJuZW50Q29uY29yZFwiLFxuICAgICAgZmlsZU5hbWU6IFwiaW5kZXhcIixcbiAgICAgIGZvcm1hdHM6IFtcImVzXCJdLFxuICAgIH0sXG4gICAgcm9sbHVwT3B0aW9uczoge1xuICAgICAgZXh0ZXJuYWwsXG4gICAgICBvdXRwdXQ6IHtcbiAgICAgICAgZm9ybWF0OiBcImVzXCIsXG4gICAgICAgIGVudHJ5RmlsZU5hbWVzOiBcImluZGV4LmpzXCIsXG4gICAgICB9LFxuICAgIH0sXG4gIH0sXG4gIHBsdWdpbnM6IFtcbiAgICBkdHMoe1xuICAgICAgdHNDb25maWdGaWxlUGF0aDogcmVzb2x2ZShjb25maWdEaXIsIFwidHNjb25maWcuanNvblwiKSxcbiAgICB9KSxcbiAgXSxcbn0pO1xuIiwgImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvVXNlcnMvc2FtL2Rldi9zYW10ZXJuZW50L2hvbWUvc2NyaXB0cy92aXRlXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ZpbGVuYW1lID0gXCIvVXNlcnMvc2FtL2Rldi9zYW10ZXJuZW50L2hvbWUvc2NyaXB0cy92aXRlL3BhY2thZ2UtbGliLWNvbmZpZy50c1wiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9pbXBvcnRfbWV0YV91cmwgPSBcImZpbGU6Ly8vVXNlcnMvc2FtL2Rldi9zYW10ZXJuZW50L2hvbWUvc2NyaXB0cy92aXRlL3BhY2thZ2UtbGliLWNvbmZpZy50c1wiO2ltcG9ydCB7IGJ1aWx0aW5Nb2R1bGVzIH0gZnJvbSBcIm5vZGU6bW9kdWxlXCI7XG5pbXBvcnQgeyByZWFkRmlsZVN5bmMgfSBmcm9tIFwibm9kZTpmc1wiO1xuaW1wb3J0IHsgZGlybmFtZSwgcmVzb2x2ZSB9IGZyb20gXCJub2RlOnBhdGhcIjtcbmltcG9ydCB7IGZpbGVVUkxUb1BhdGggfSBmcm9tIFwibm9kZTp1cmxcIjtcblxudHlwZSBQYWNrYWdlSnNvblNoYXBlID0ge1xuICBkZXBlbmRlbmNpZXM/OiBSZWNvcmQ8c3RyaW5nLCBzdHJpbmc+O1xuICBwZWVyRGVwZW5kZW5jaWVzPzogUmVjb3JkPHN0cmluZywgc3RyaW5nPjtcbiAgb3B0aW9uYWxEZXBlbmRlbmNpZXM/OiBSZWNvcmQ8c3RyaW5nLCBzdHJpbmc+O1xufTtcblxuZnVuY3Rpb24gbG9hZFBhY2thZ2VKc29uKHBhY2thZ2VEaXI6IHN0cmluZyk6IFBhY2thZ2VKc29uU2hhcGUge1xuICBjb25zdCBwYWNrYWdlSnNvblBhdGggPSByZXNvbHZlKHBhY2thZ2VEaXIsIFwicGFja2FnZS5qc29uXCIpO1xuICByZXR1cm4gSlNPTi5wYXJzZShyZWFkRmlsZVN5bmMocGFja2FnZUpzb25QYXRoLCBcInV0ZjhcIikpIGFzIFBhY2thZ2VKc29uU2hhcGU7XG59XG5cbmZ1bmN0aW9uIGNyZWF0ZVBhY2thZ2VOYW1lcyhwYWNrYWdlSnNvbjogUGFja2FnZUpzb25TaGFwZSkge1xuICByZXR1cm4gbmV3IFNldChbXG4gICAgLi4uT2JqZWN0LmtleXMocGFja2FnZUpzb24uZGVwZW5kZW5jaWVzIHx8IHt9KSxcbiAgICAuLi5PYmplY3Qua2V5cyhwYWNrYWdlSnNvbi5wZWVyRGVwZW5kZW5jaWVzIHx8IHt9KSxcbiAgICAuLi5PYmplY3Qua2V5cyhwYWNrYWdlSnNvbi5vcHRpb25hbERlcGVuZGVuY2llcyB8fCB7fSksXG4gIF0pO1xufVxuXG5mdW5jdGlvbiBpc0V4dGVybmFsSWQoaWQ6IHN0cmluZywgcGFja2FnZU5hbWVzOiBTZXQ8c3RyaW5nPiwgaW5jbHVkZU5vZGVCdWlsdGluczogYm9vbGVhbikge1xuICBpZiAoaW5jbHVkZU5vZGVCdWlsdGlucykge1xuICAgIGlmIChidWlsdGluTW9kdWxlcy5pbmNsdWRlcyhpZCkgfHwgYnVpbHRpbk1vZHVsZXMuaW5jbHVkZXMoaWQucmVwbGFjZSgvXm5vZGU6LywgXCJcIikpKSB7XG4gICAgICByZXR1cm4gdHJ1ZTtcbiAgICB9XG4gICAgaWYgKGlkLnN0YXJ0c1dpdGgoXCJub2RlOlwiKSkge1xuICAgICAgcmV0dXJuIHRydWU7XG4gICAgfVxuICB9XG5cbiAgZm9yIChjb25zdCBwYWNrYWdlTmFtZSBvZiBwYWNrYWdlTmFtZXMpIHtcbiAgICBpZiAoaWQgPT09IHBhY2thZ2VOYW1lIHx8IGlkLnN0YXJ0c1dpdGgoYCR7cGFja2FnZU5hbWV9L2ApKSB7XG4gICAgICByZXR1cm4gdHJ1ZTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gZmFsc2U7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBjcmVhdGVQYWNrYWdlRXh0ZXJuYWwoXG4gIHBhY2thZ2VEaXI6IHN0cmluZyxcbiAgb3B0aW9uczogeyBpbmNsdWRlTm9kZUJ1aWx0aW5zPzogYm9vbGVhbiB9ID0ge30sXG4pIHtcbiAgY29uc3QgcGFja2FnZUpzb24gPSBsb2FkUGFja2FnZUpzb24ocGFja2FnZURpcik7XG4gIGNvbnN0IHBhY2thZ2VOYW1lcyA9IGNyZWF0ZVBhY2thZ2VOYW1lcyhwYWNrYWdlSnNvbik7XG4gIGNvbnN0IGluY2x1ZGVOb2RlQnVpbHRpbnMgPSBvcHRpb25zLmluY2x1ZGVOb2RlQnVpbHRpbnMgPT09IHRydWU7XG5cbiAgcmV0dXJuIGZ1bmN0aW9uIGV4dGVybmFsKGlkOiBzdHJpbmcpIHtcbiAgICByZXR1cm4gaXNFeHRlcm5hbElkKGlkLCBwYWNrYWdlTmFtZXMsIGluY2x1ZGVOb2RlQnVpbHRpbnMpO1xuICB9O1xufVxuXG5leHBvcnQgZnVuY3Rpb24gcmVzb2x2ZVBhY2thZ2VEaXIobWV0YVVybDogc3RyaW5nKSB7XG4gIHJldHVybiBkaXJuYW1lKGZpbGVVUkxUb1BhdGgobWV0YVVybCkpO1xufVxuIl0sCiAgIm1hcHBpbmdzIjogIjtBQUErVCxTQUFTLFdBQUFBLFVBQVMsV0FBQUMsZ0JBQWU7QUFDaFcsU0FBUyxpQkFBQUMsc0JBQXFCO0FBQzlCLFNBQVMsb0JBQW9CO0FBQzdCLE9BQU8sU0FBUzs7O0FDSGlULFNBQVMsc0JBQXNCO0FBQ2hXLFNBQVMsb0JBQW9CO0FBQzdCLFNBQVMsU0FBUyxlQUFlO0FBQ2pDLFNBQVMscUJBQXFCO0FBUTlCLFNBQVMsZ0JBQWdCLFlBQXNDO0FBQzdELFFBQU0sa0JBQWtCLFFBQVEsWUFBWSxjQUFjO0FBQzFELFNBQU8sS0FBSyxNQUFNLGFBQWEsaUJBQWlCLE1BQU0sQ0FBQztBQUN6RDtBQUVBLFNBQVMsbUJBQW1CLGFBQStCO0FBQ3pELFNBQU8sb0JBQUksSUFBSTtBQUFBLElBQ2IsR0FBRyxPQUFPLEtBQUssWUFBWSxnQkFBZ0IsQ0FBQyxDQUFDO0FBQUEsSUFDN0MsR0FBRyxPQUFPLEtBQUssWUFBWSxvQkFBb0IsQ0FBQyxDQUFDO0FBQUEsSUFDakQsR0FBRyxPQUFPLEtBQUssWUFBWSx3QkFBd0IsQ0FBQyxDQUFDO0FBQUEsRUFDdkQsQ0FBQztBQUNIO0FBRUEsU0FBUyxhQUFhLElBQVksY0FBMkIscUJBQThCO0FBQ3pGLE1BQUkscUJBQXFCO0FBQ3ZCLFFBQUksZUFBZSxTQUFTLEVBQUUsS0FBSyxlQUFlLFNBQVMsR0FBRyxRQUFRLFVBQVUsRUFBRSxDQUFDLEdBQUc7QUFDcEYsYUFBTztBQUFBLElBQ1Q7QUFDQSxRQUFJLEdBQUcsV0FBVyxPQUFPLEdBQUc7QUFDMUIsYUFBTztBQUFBLElBQ1Q7QUFBQSxFQUNGO0FBRUEsYUFBVyxlQUFlLGNBQWM7QUFDdEMsUUFBSSxPQUFPLGVBQWUsR0FBRyxXQUFXLEdBQUcsV0FBVyxHQUFHLEdBQUc7QUFDMUQsYUFBTztBQUFBLElBQ1Q7QUFBQSxFQUNGO0FBRUEsU0FBTztBQUNUO0FBRU8sU0FBUyxzQkFDZCxZQUNBLFVBQTZDLENBQUMsR0FDOUM7QUFDQSxRQUFNLGNBQWMsZ0JBQWdCLFVBQVU7QUFDOUMsUUFBTSxlQUFlLG1CQUFtQixXQUFXO0FBQ25ELFFBQU0sc0JBQXNCLFFBQVEsd0JBQXdCO0FBRTVELFNBQU8sU0FBU0MsVUFBUyxJQUFZO0FBQ25DLFdBQU8sYUFBYSxJQUFJLGNBQWMsbUJBQW1CO0FBQUEsRUFDM0Q7QUFDRjtBQUVPLFNBQVMsa0JBQWtCLFNBQWlCO0FBQ2pELFNBQU8sUUFBUSxjQUFjLE9BQU8sQ0FBQztBQUN2Qzs7O0FEMURzTSxJQUFNLDJDQUEyQztBQU12UCxJQUFNLFlBQVlDLFNBQVFDLGVBQWMsd0NBQWUsQ0FBQztBQUN4RCxJQUFNLFdBQVcsc0JBQXNCLGtCQUFrQix3Q0FBZSxDQUFDO0FBRXpFLElBQU8sc0JBQVEsYUFBYTtBQUFBLEVBQzFCLE9BQU87QUFBQSxJQUNMLFFBQVE7QUFBQSxJQUNSLFdBQVc7QUFBQSxJQUNYLFFBQVE7QUFBQSxJQUNSLFFBQVE7QUFBQSxJQUNSLEtBQUs7QUFBQSxNQUNILE9BQU9DLFNBQVEsV0FBVyxjQUFjO0FBQUEsTUFDeEMsTUFBTTtBQUFBLE1BQ04sVUFBVTtBQUFBLE1BQ1YsU0FBUyxDQUFDLElBQUk7QUFBQSxJQUNoQjtBQUFBLElBQ0EsZUFBZTtBQUFBLE1BQ2I7QUFBQSxNQUNBLFFBQVE7QUFBQSxRQUNOLFFBQVE7QUFBQSxRQUNSLGdCQUFnQjtBQUFBLE1BQ2xCO0FBQUEsSUFDRjtBQUFBLEVBQ0Y7QUFBQSxFQUNBLFNBQVM7QUFBQSxJQUNQLElBQUk7QUFBQSxNQUNGLGtCQUFrQkEsU0FBUSxXQUFXLGVBQWU7QUFBQSxJQUN0RCxDQUFDO0FBQUEsRUFDSDtBQUNGLENBQUM7IiwKICAibmFtZXMiOiBbImRpcm5hbWUiLCAicmVzb2x2ZSIsICJmaWxlVVJMVG9QYXRoIiwgImV4dGVybmFsIiwgImRpcm5hbWUiLCAiZmlsZVVSTFRvUGF0aCIsICJyZXNvbHZlIl0KfQo= diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 62cfaff..c2891dc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -239,6 +239,9 @@ importers: packages/concord: dependencies: + '@scure/base': + specifier: 2.4.0 + version: 2.4.0 '@ternent/armour': specifier: workspace:^ version: link:../armour @@ -248,6 +251,9 @@ importers: '@ternent/ledger': specifier: workspace:^ version: link:../ledger + age-encryption: + specifier: 0.3.1 + version: 0.3.1 devDependencies: typescript: specifier: npm:@typescript/typescript6@6.0.2 From 99afc60ee366f88a1c97fab214b434fa0b44a661 Mon Sep 17 00:00:00 2001 From: samternent Date: Sat, 28 Nov 2026 01:57:12 +0000 Subject: [PATCH 10/24] chore: bring repository checks and guides in line with the rewritten libraries Replace eleven consumer and type checks written against the old APIs with one consumer covering all five libraries and their saved vectors, a per-package import-isolation check and one typed consumer, and rewrite the browser proof. Update AGENTS.md, CONTEXT.md, the README and the agent guide to the current design, and mark docs/ as history. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 93 ++++---- CONTEXT.md | 179 +++++---------- README.md | 39 ++-- llms.txt | 30 +-- scripts/verify/concord-browser.txt | 288 +++++-------------------- scripts/verify/concord-consumer.txt | 124 ----------- scripts/verify/consumer.txt | 74 +++++++ scripts/verify/consumers.mjs | 87 ++------ scripts/verify/groups-consumer.txt | 95 -------- scripts/verify/groups-types.txt | 61 ------ scripts/verify/isolation.txt | 28 +++ scripts/verify/ledger-consumer.txt | 30 --- scripts/verify/ledger-types.txt | 57 ----- scripts/verify/payload-consumer.txt | 24 --- scripts/verify/primitives-consumer.txt | 60 ------ scripts/verify/primitives-types.txt | 27 --- scripts/verify/protocol-isolation.txt | 10 - scripts/verify/storage-consumer.txt | 63 ------ scripts/verify/storage-types.txt | 27 --- scripts/verify/types.txt | 36 ++++ 20 files changed, 323 insertions(+), 1109 deletions(-) delete mode 100644 scripts/verify/concord-consumer.txt create mode 100644 scripts/verify/consumer.txt delete mode 100644 scripts/verify/groups-consumer.txt delete mode 100644 scripts/verify/groups-types.txt create mode 100644 scripts/verify/isolation.txt delete mode 100644 scripts/verify/ledger-consumer.txt delete mode 100644 scripts/verify/ledger-types.txt delete mode 100644 scripts/verify/payload-consumer.txt delete mode 100644 scripts/verify/primitives-consumer.txt delete mode 100644 scripts/verify/primitives-types.txt delete mode 100644 scripts/verify/protocol-isolation.txt delete mode 100644 scripts/verify/storage-consumer.txt delete mode 100644 scripts/verify/storage-types.txt create mode 100644 scripts/verify/types.txt diff --git a/AGENTS.md b/AGENTS.md index 9f4951a..1df7f55 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,63 +44,44 @@ repeatable, and useful to both people and agents. ## Project context -For architecture or migration work, read [the project brief](docs/concord/context.md). -The accepted clean-rebuild target is -[the alpha architecture](docs/concord/alpha-architecture.md), and canonical domain -language is in [CONTEXT.md](CONTEXT.md). When current packages or their specifications -conflict with that target, treat them as legacy evidence rather than requirements. -Inspect the relevant package README, SPEC, types, and tests for the task at hand. -Existing package `CLAUDE.md` files also contain architecture guidance; read them -when touching that package. They are legacy documentation, not a requirement to -use Claude. Check stale names and contradictions against actual exports and the -user's intended contract. - -Keep these target responsibilities distinct: - -- Ledger: the standalone signed log, common container, canonicalization, identifiers, - signatures, entry staging, commit construction, verification and ordered replay. -- Concord runtime: compose Ledger with commands, authority, encryption and two-stage - replay. Retain command-intent drafts and previews; delegate signed history to Ledger. -- System extensions: identities, capabilities, audiences, key distribution, and - decryption. -- Application models: typed commands, domain events, validation, and reducers. -- Storage adapters: reading, writing, and any adapter-specific synchronization. -- Identity, Armour, and Seal: independently usable identity, encryption, and proof - primitives. -- Armour integration with Ledger: explicit payload codecs; keep recipients, keys - and decryption outside Ledger's container and history lifecycle. -- Framework adapters and UI: consumers above the runtime. - -Do not put application policy into the Concord runtime or system extensions, or -duplicate the owning layer's cryptography and verification in consumers. +Each package's README states its interface and guarantees, and its `CLAUDE.md` the rules +for changing it; read both before touching a package. [CONTEXT.md](CONTEXT.md) holds the +vocabulary. `docs/` holds earlier designs and decisions as history: where it disagrees +with a package README or the exports, the package is current. + +Keep these responsibilities distinct: + +- Identity: one identity, its backup and recovery, exact-byte signing and verification. +- Seal: a detached proof over a content hash. +- Armour: age encryption for identities, native group keys and passphrases. +- Ledger: signed history, canonical bytes, commit and entry IDs, staging, verification + and comparison. +- Concord: groups, membership, key epochs, authority and per-group replay of an + application's events, built on the other four. +- Applications: models, storage, sync, group names and UI. + +Do not put application policy into Concord, or duplicate the owning layer's +cryptography and verification in a consumer. ## Contracts to preserve -- Signed history is authoritative; projection is derived. Storage does not - make a document trustworthy. -- Immediate commit is the default authoring mode. Draft mode may group several commands - into an explicit commit. Storage publication is a separate operation. -- Staged entries and pending command intents stay in memory. Consumers choose commit - cadence and own any draft autosave or recovery; libraries exchange committed history. - See [the draft persistence decision](docs/adr/0019-keep-draft-persistence-with-consumers.md). -- Commit identifiers and signatures bind the canonical unsigned commit subject, - including parent linkage and ordered entry identifiers. -- Invalid reachable committed history cannot produce trusted runtime state. -- Replay is deterministic for identical ordered entries, capabilities, and conforming - pure model implementations. Reissuing a command with fresh keys or timestamps is not - replaying the same input. -- System replay establishes authority and decryptability before application replay. - Publish state only after a successful complete pass. -- Partial replay is not authoritative full reconstruction without genesis or - a valid checkpoint. Preserve read-only runtime behavior. -- Bind actor claims to the signer. Keep historical grants distinct from active - membership; revocation cannot erase keys or plaintext already obtained. -- A document snapshot has one selected head. Classify two snapshots as equal, ahead, - behind, or diverged; never silently combine or choose between divergent histories. - Alpha does not merge divergent histories. Retain both, ask a person to select one, or - author a new document that references both source heads. -- Integrity does not establish freshness or completeness. Detect rollback or withholding - only against a remembered head or another external freshness anchor. +- Signed history is authoritative; state is derived. Storage does not make a document + trustworthy. +- Authoring is `stage` then `commit`; there is no immediate mode. Staged events stay in + memory, and applications own any draft recovery. Storage publication is separate. +- Commit IDs and signatures bind the canonical commit body, its parent and its entries. +- History that fails Ledger verification does not open. +- A group's validity depends only on that group's history, so its members agree on its + state whatever else they can read. Enforce only rules the affected readers can verify. +- Authority is checked before the model's `reduce`. A signed commit that fails either is + kept as evidence and changes nothing. +- A key gains authority only through an accepted membership record. +- Adding a member reveals the group's whole history; removal protects only future events. +- Copies have one head and are compared, never silently merged. Rebase reapplies only + this identity's unpublished commits and returns what no longer applies. +- Integrity does not establish freshness. Detect rollback or withholding only against a + remembered head. +- State what the raw file can reveal, and claim no privacy beyond it. ## Verification and delivery @@ -112,8 +93,8 @@ duplicate the owning layer's cryptography and verification in consumers. - For package or build changes, verify built public imports, declaration output, and dependency wiring as well as source tests. A successful build is insufficient evidence that a consumer can import the package. -- For persistence changes, check reopen, staged-state handling, and the affected - failure or conflict paths. Run applicable type checks and builds. +- For format changes, check reopen, the saved vectors and the affected failure paths. + Run applicable type checks and builds. - Report passing checks, existing failures, introduced failures, and unverified behavior separately. Do not weaken assertions to make a failure disappear. - Keep comments about local rationale. Put change history in the delivery report. diff --git a/CONTEXT.md b/CONTEXT.md index 610e5de..a99aeef 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -1,125 +1,54 @@ -# Concord - -Concord is the domain of portable, signed application documents whose trusted state is -rebuilt from their history. This glossary defines the language used across the runtime, -protocol, documentation, and examples. - -## Document and history - -**Concord document**: -A portable, single-head snapshot holding a signed commit history and the declarations -needed to interpret it. -_Avoid_: Ledger, database, workspace - -**Entry**: -An immutable unit of recorded system or application meaning contained in a commit. -_Avoid_: Row, mutation, action - -**Commit**: -A signed boundary containing one or more ordered entries and a link to its parent. -_Avoid_: Save, transaction - -**Head**: -The commit selected as the tip of a Concord document snapshot. -_Avoid_: Latest version, current state - -**Document ID**: -The genesis commit identifier shared by every snapshot in one document lineage. -_Avoid_: Head, storage key - -**Divergence**: -The relationship between two valid snapshots whose heads share history but neither head -is an ancestor of the other. -_Avoid_: Invalid document, automatic merge - -**Replay**: -Deterministic reconstruction from the ordered entries in a Concord document. -_Avoid_: Loading, event handling - -**Projection**: -Derived state produced by replay and never treated as the authoritative record. -_Avoid_: Document state, source of truth - -**Draft**: -An unpublished local group of intended entries awaiting one explicit commit. Its preview -is provisional and does not change the selected committed head. -_Avoid_: Unsigned history, saved document - -## Identity and authority - -**Public identity**: -A versioned Ed25519 public key and its derived identifier, safe to record and share. -_Avoid_: User, account, profile - -**Identity capability**: -Private identity material and the operations it authorizes, held by the host outside a -Concord document. -_Avoid_: Private identity record, document identity - -**Capability**: -An authority such as read, write, grant, or administer that a system extension assigns -to a public identity. -_Avoid_: Role, permission flag - -**Audience**: -The identities allowed to decrypt a protected entry. -_Avoid_: Role, access level - -**Privacy group**: -A managed audience with shared encryption material and membership history. Membership, -past key possession, and authority to write are separate facts. -_Avoid_: Role, team - -**Audience epoch**: -A generation of a privacy group's encryption material. A later epoch protects future -entries without retracting knowledge of earlier entries. -_Avoid_: Identity rotation, erased access - -## Runtime - -**Host**: -The trusted application environment that supplies identity capabilities, storage, and -approved extension implementations to Concord. -_Avoid_: Server, owner - -**System profile**: -The declared set of system semantics required to interpret a document, including -identity, authority, and privacy behavior. -_Avoid_: Core plugin bundle, user system - -**System extension**: -A host-trusted implementation of system semantics that runs before application replay -and owns identities, capabilities, and encryption. -_Avoid_: First-class plugin, application plugin - -**Application model**: -The single, versioned domain contract selected when a document is created, expressed -through commands, events, validation, and reducers. -_Avoid_: App type, replay plugin - -**Application projection**: -Application state rebuilt from the authorized and decrypted events exposed by the -system profile. -_Avoid_: Database, document contents - -**Inspection handle**: -A read-only view of a document that exposes history and diagnostics when a trusted -application projection cannot be produced. -_Avoid_: Broken runtime, partial app - -**Freshness anchor**: -A head or checkpoint remembered outside a document and used to detect an older or -divergent snapshot served later. -_Avoid_: Signature, timestamp - -## Boundaries - -**Storage adapter**: -A replaceable integration that reads and writes complete Concord documents. Richer -synchronization behavior belongs to the adapter rather than the Concord runtime. -_Avoid_: Concord backend, sync engine - -**Identity directory**: -An optional service or application facility that maps public identities to profiles, -presence, discovery, or peer connections. -_Avoid_: Concord user system, profile plugin +# Ternent vocabulary + +The words used across the libraries, their READMEs and examples. Ternent documents are +portable, signed histories whose application state is rebuilt by replaying them. + +## History + +**Identity**: one Ed25519 key pair, created or restored by `@ternent/identity`. Its +`publicIdentity` is safe to share; the private seed leaves only through `export()`. + +**Proof**: a Seal signature over a content hash, naming its signer and claimed time. + +**History**: an immutable Ledger history of commits, verified when opened. +_Avoid_: database, log file + +**Commit**: a signed step in a history, naming its parent and holding ordered entries. +The first commit is **genesis**; its ID is the **document ID**. The last is the **head**. + +**Entry**: one stored item in a commit. In a Concord document every entry is one age +ciphertext. + +**Diverged**: two copies that share a commit but each moved on from it. Ledger reports +copies as equal, ahead, behind, diverged or unrelated, and never merges them. + +**Rebase**: reapplying your own unpublished commits on top of another copy. +_Avoid_: merge, sync + +## Concord documents + +**Document**: a history read through a model by one identity. + +**Model**: an application's `id`, `version`, `initial()` state and `reduce` function. + +**Event**: `{ type, data }`, a fact an application records. Events are staged into a +**draft** and signed together by `commit`. +_Avoid_: command, action + +**State**: what a group's accepted events reduce to. It is derived, never stored. +_Avoid_: projection, snapshot + +**Group**: a set of members sharing a key, with its own events and state. Every document +has a **default group** created at genesis. +_Avoid_: audience, channel, room + +**Member** and **admin**: the two roles in a group. Members read and write; admins also +manage membership. +_Avoid_: capability, permission + +**Epoch**: one key for a group. Removing a member starts a new epoch. + +**Rejected**: a signed commit that broke its group's rules. It stays as evidence and +changes nothing. + +**Unreadable**: an entry none of your keys open. You can tell it exists, nothing more. diff --git a/README.md b/README.md index 5df728e..b9b0f3a 100644 --- a/README.md +++ b/README.md @@ -3,18 +3,18 @@ Identity, encryption, signed documents and standalone proofs for software where the host owns its data and storage. -| Package | Responsibility | -| --------------------------------------- | ------------------------------------------------------------------------- | -| [Identity](packages/identity/README.md) | Seed identities, signatures, recovery and key derivation | -| [Armour](packages/armour/README.md) | age encryption through the TypeScript implementation, typage | -| [Ledger](packages/ledger/README.md) | Standalone signed log, staging, commits, verification and replay | -| [Concord](packages/concord/README.md) | Commands, authority, encrypted groups and application replay above Ledger | -| [Seal](packages/seal/README.md) | Detached Ed25519 proofs over a content hash | +| Package | Responsibility | +| --------------------------------------- | --------------------------------------------------------------------- | +| [Identity](packages/identity/README.md) | One Ed25519 identity: create, back up, recover, sign and verify | +| [Seal](packages/seal/README.md) | Detached Ed25519 proofs over a content hash | +| [Armour](packages/armour/README.md) | age encryption for identities, group keys and passphrases | +| [Ledger](packages/ledger/README.md) | Signed, append-only history of JSON entries, verified on open | +| [Concord](packages/concord/README.md) | Shared documents of application events with private, encrypted groups | These five independently usable libraries are the active workspace and release -scope. Ledger owns the common signed container and history lifecycle. Concord -composes commands, authority and encryption above it. Staging is in memory; -consumers choose commit cadence and own any draft persistence or recovery. +scope. Ledger owns signed history, Seal signs each commit, Armour encrypts, and +Concord builds shared documents with private groups on top. Applications own +storage, sync and UI. [CONTEXT.md](CONTEXT.md) defines the vocabulary. Agents building applications should start with [llms.txt](llms.txt), which links to each package’s consumer interface guide and working examples. @@ -33,19 +33,10 @@ Node/browser consumer. The temporary Vue browser consumer uses ordinary render functions and CSS. See [CONTRIBUTING.md](CONTRIBUTING.md) for prerequisites and focused checks. A configured check is not a release receipt. -`packages/` owns the libraries, `scripts/verify/` owns repository acceptance, -and `docs/` owns contracts and decisions. Root Vite+ and TypeScript base configs -share repository defaults; each package declares its own entries and outputs. -There is no portable tooling product or maintained application in core. UI is -outside this release under [ADR 0017](docs/adr/0017-drop-ui-from-the-library-release.md). -Workspace remains deferred until the libraries are stable and substantial demos -exist. Demos should consume published libraries from outside core. - -Start with the [project brief](docs/concord/context.md), -[alpha architecture](docs/concord/alpha-architecture.md) and -[repository guide](docs/engineering/repository-hygiene.md). Signed history is -authoritative; projections are derived, and storage publication is a separate step. -Candidate-registry checks and the release planner/publisher are implemented. The first registry-backed alpha is published; the [release record](docs/engineering/release-and-deployment.md) -identifies its versions and acceptance evidence. +`packages/` owns the libraries and `scripts/` owns repository acceptance and release. +Each package's README describes its interface and guarantees, and its `CLAUDE.md` the +rules for changing it. `docs/` holds earlier designs and decisions as history; where it +disagrees with a package README, the README is current. Workspace and UI are outside +the release. ISC licensed. See [LICENSE](LICENSE). diff --git a/llms.txt b/llms.txt index 408613a..5672fb2 100644 --- a/llms.txt +++ b/llms.txt @@ -36,26 +36,18 @@ installed package's declarations when its tarball has no guide. ## Shared contracts -Signed committed history is authoritative; projections are derived. Local commits and -storage publication are separate. Staged Ledger entries and Concord drafts stay in -memory. Private identity capabilities are held outside the document; the host owns -identity persistence, recovery and synchronization. - -Use the owning library's verification and cryptography rather than implementing them -in the application. Documents never load executable code: hosts select trusted models -and system implementations. Treat inspection evidence separately from trusted state. - -Snapshots have one selected head. Compare equal/ahead/behind/diverged/unrelated; never -silently choose or combine divergent history. A storage adapter may implement atomic -expected-head publication. After an explicit rejected write, retain local bytes and -command intents, reopen the accepted snapshot and reissue the intended command under -current authority. Reissue can fail validation; retain the work for resolution. This -is host behavior, not an automatic retry or merge method in Concord. No runtime -`merge`, `push`, `pull`, checkpoint, draft persistence or model-upgrade API exists. +Signed history is authoritative; application state is derived by replaying it. Staged +events stay in memory until committed. Identities are held by the application, which owns +their persistence and recovery, along with storage and sync of document bytes. + +Use the owning library's verification and cryptography rather than implementing them in +the application. Documents never load code: the application supplies its model. + +Copies have one head. Compare equal, ahead, behind, diverged or unrelated; never silently +choose or combine diverged history. Concord's `rebase` reapplies your own unpublished +commits onto another copy and returns what no longer applies. ## Further reading -- [Concord vocabulary](CONTEXT.md): document, commit, projection, capability and audience definitions. -- [Storage contract](docs/concord/storage-boundary.md): publication, conflicts and freshness anchors. -- [Protocol](docs/concord/alpha-protocol.md): specialist wire, signatures and canonicalization. +- [Vocabulary](CONTEXT.md): history, commit, document, model, event, group and role definitions. - [Contributor instructions](AGENTS.md): repository maintenance rather than application usage. diff --git a/scripts/verify/concord-browser.txt b/scripts/verify/concord-browser.txt index 82c00a1..8806e5b 100644 --- a/scripts/verify/concord-browser.txt +++ b/scripts/verify/concord-browser.txt @@ -1,238 +1,58 @@ -import { - createDocument, - openDocument, - defineModel, - type AudienceId, - type ModelIssue, - type Result, -} from "@ternent/concord"; -import { createGroup, createStandardSystemProfile, setMember } from "@ternent/concord/system"; -import { registerModel, createMemoryExpectedHeadStore } from "@ternent/concord/testing"; -import { - createAgeCodec, - generateIdentity, - encryptForIdentities, - decryptWithIdentity, - recipientFromIdentity, -} from "@ternent/armour"; -import { ageRecipientFromPublicIdentity, createIdentity, generateSigner } from "@ternent/identity"; -import { createLedger, encodePayload, decodePayload } from "@ternent/ledger"; -export async function proveConcord() { - const logSigner = await generateSigner(); - if (!logSigner.ok) throw new Error(logSigner.error.code); - const log = await createLedger({ signer: logSigner.value }); - await log.create(); - await log.append({ kind: "browser", payload: { value: "plain signed log" } }); - if ((await log.export()).entries.length !== 0) throw new Error("Ledger draft leaked into export"); - await log.commit(); - const logReader = await createLedger(); - await logReader.import(await log.export()); - if ( - (await logReader.verify()).integrity !== "valid" || - JSON.stringify((await logReader.replay())[0].payload.data) !== - JSON.stringify({ value: "plain signed log" }) - ) - throw new Error("browser Ledger failed"); - const hostIdentity = await createIdentity(); - const helperPlaintext = new TextEncoder().encode("browser helpers need no setup"); - const helperCiphertext = await encryptForIdentities({ - identities: [hostIdentity], - data: helperPlaintext, - }); - const helperResult = await decryptWithIdentity({ - identity: hostIdentity, - data: helperCiphertext, - }); - if (new TextDecoder().decode(helperResult) !== "browser helpers need no setup") - throw new Error("browser helper roundtrip failed"); - const identity = await generateIdentity(); - if (!identity.ok) throw new Error(identity.error.code); - const recipient = ageRecipientFromPublicIdentity(identity.value.publicIdentity); - if (!recipient.ok) throw new Error(recipient.error.code); - const payloadCodec = createAgeCodec({ recipients: [recipient.value], reader: identity.value }); - await log.append({ - kind: "private", - payload: await encodePayload({ value: "private browser payload" }, payloadCodec), - }); - await log.commit(); - const raw = await log.export(); - if (JSON.stringify(raw).includes("private browser payload")) - throw new Error("private payload leaked"); - await logReader.load(raw); - const privatePayload = (await logReader.replay())[1].payload.data; - const lockedPayload = await decodePayload(privatePayload), - decodedPayload = await decodePayload(privatePayload, payloadCodec); - if ( - lockedPayload.status !== "locked" || - decodedPayload.status !== "decoded" || - JSON.stringify(decodedPayload.data) !== JSON.stringify({ value: "private browser payload" }) || - (await logReader.verify()).integrity !== "valid" - ) - throw new Error("optional Armour/Ledger composition failed"); - const system = createStandardSystemProfile(); - const created = await createDocument({ model: registerModel, system, identity: identity.value }); - if (!created.ok) throw new Error(created.error.code); - const committed = await created.value.dispatch("set", { value: "hello browser" }); - if (!committed.ok) throw new Error(committed.error.code); - const reopened = await openDocument({ - bytes: created.value.export(), - model: registerModel, - system, - signer: identity.value, - }); - const replayed = await reopened.replay(); - if ( - !replayed.ok || - replayed.value.projection.value !== "hello browser" || - (await reopened.verify()).integrity !== "valid" - ) - throw new Error("browser lifecycle failed"); - type Input = { audience: AudienceId; value: string }; - type Event = { type: "group.value"; version: 1; data: Input }; - const ok = (value: T): Result => ({ ok: true, value }); - const validate = (input: unknown): Result => { - if ( - !input || - typeof input !== "object" || - !("audience" in input) || - !("value" in input) || - typeof input.audience !== "string" || - typeof input.value !== "string" - ) - return { ok: false, error: { code: "INVALID", message: "Expected group input" } }; - return ok({ audience: input.audience as AudienceId, value: input.value }); - }; - const grouped = defineModel<{ value: string; locked: number }, { set: Input }, Event>({ - ref: { id: "concord.browser.groups", version: 1 }, - initial: () => ({ value: "", locked: 0 }), - commands: { - set: { - validate, - audience: (input) => input.audience, - decide: (data) => ok([{ type: "group.value", version: 1, data }]), - }, - }, - validateEvent(input) { - if ( - !input || - typeof input !== "object" || - !("type" in input) || - !("version" in input) || - !("data" in input) || - input.type !== "group.value" || - input.version !== 1 - ) - return { ok: false, error: { code: "INVALID", message: "Expected group event" } }; - const checked = validate(input.data); - return checked.ok ? ok({ type: "group.value", version: 1, data: checked.value }) : checked; - }, - audience: (event) => event.data.audience, - requirements: () => ["write"], - reduce: (state, event) => ok({ ...state, value: event.data.value }), - reduceLocked: (state) => ok({ ...state, locked: state.locked + 1 }), - }); - const doc = await createDocument({ - model: grouped, - system: createStandardSystemProfile(), - identity: identity.value, - }); - if (!doc.ok) throw new Error(doc.error.code); - const visible = await createGroup(doc.value), - hidden = await createGroup(doc.value); - if (!visible.ok || !hidden.ok) throw new Error("browser group creation failed"); - const guest = await generateIdentity(); - if (!guest.ok) throw new Error(guest.error.code); - const granted = await setMember(doc.value, { - audience: visible.value.audience, - identity: guest.value.publicIdentity, - capabilities: ["read"], - }); - if (!granted.ok) throw new Error(granted.error.code); - for (const [audience, value] of [ - [visible.value.audience, "visible group"], - [hidden.value.audience, "hidden group"], - ] as const) { - const committed = await doc.value.dispatch("set", { audience, value }); - if (!committed.ok) throw new Error(committed.error.code); - } - const scoped = await openDocument({ - bytes: doc.value.export(), - model: grouped, - system: createStandardSystemProfile(), - reader: guest.value, - }); - const state = scoped.state(); - if ( - state.status !== "ready" || - state.coverage !== "readable" || - state.lockedEntries !== 1 || - state.canWrite || - state.projection.value !== "visible group" || - state.projection.locked !== 1 || - scoped.inspect().application !== "scoped" || - scoped.inspect().entries?.length !== 2 - ) - throw new Error("browser independent group replay failed"); - const drafting = await createDocument({ - model: registerModel, - system: createStandardSystemProfile(), - identity: identity.value, - mode: "draft", - }); - if (!drafting.ok) throw new Error(drafting.error.code); - const beforeDraft = drafting.value.export(); - const first = await drafting.value.dispatch("set", { value: "first browser draft" }); - const second = await drafting.value.dispatch("set", { value: "committed browser draft" }); - if ( - !first.ok || - first.value.status !== "staged" || - !second.ok || - second.value.status !== "staged" || - second.value.entryCount !== 2 || - drafting.value.draft()?.preview.value !== "committed browser draft" || - !drafting.value.export().every((byte, index) => byte === beforeDraft[index]) - ) - throw new Error("browser draft staging failed"); - const batch = await drafting.value.commit({ message: "Browser draft batch" }); - if (!batch.ok || batch.value.entryIds.length !== 2 || drafting.value.draft() !== null) - throw new Error("browser draft commit failed"); - const reopenedDraft = await openDocument({ - bytes: drafting.value.export(), - model: registerModel, - system: createStandardSystemProfile(), - reader: identity.value, - }); - const draftReplay = await reopenedDraft.replay(); - if (!draftReplay.ok || draftReplay.value.projection.value !== "committed browser draft") - throw new Error("browser draft reopen failed"); - const storage = createMemoryExpectedHeadStore(); - const published = await storage.writeExpected(drafting.value.export(), null); - const collision = await storage.writeExpected(drafting.value.export(), null); - const stored = await storage.read(); - if ( - !published.ok || - collision.ok || - collision.error.code !== "HEAD_CONFLICT" || - !collision.error.remote || - !stored.ok || - !stored.value - ) - throw new Error("browser expected-head storage failed"); - const storedDocument = await openDocument({ - bytes: stored.value, - model: registerModel, - system: createStandardSystemProfile(), - reader: identity.value, - }); - const storedReplay = await storedDocument.replay(); - if ( - !storedReplay.ok || - storedReplay.value.projection.value !== "committed browser draft" || - storedDocument.draft() !== null - ) - throw new Error("browser stored snapshot reopen failed"); +import { createIdentity, verify } from "@ternent/identity"; +import { createSealHash, createSealProof, verifySealProof } from "@ternent/seal"; +import { decrypt, encrypt } from "@ternent/armour"; +import { createLedger, createWriter, openLedger } from "@ternent/ledger"; +import { createDocument, defineModel, openDocument } from "@ternent/concord"; + +type Notes = { notes: { [id: string]: string } }; + +const notes = defineModel({ + id: "notes", + version: 1, + initial: () => ({ notes: {} }), + reduce(state, event) { + const data = event.data as { id: string; title: string }; + if (event.type === "note.put") return { notes: { ...state.notes, [data.id]: data.title } }; + throw new Error(`Unknown event ${event.type}`); + }, +}); + +function check(condition: boolean, message: string): void { + if (!condition) throw new Error(`browser ${message} failed`); +} + +// Runs every library in the browser through its installed, built package. +export async function proveConcord(): Promise { + const text = new TextEncoder(); + const alice = await createIdentity(); + const bob = await createIdentity(); + const signature = await alice.sign(text.encode("browser")); + check(await verify(alice.publicIdentity, text.encode("browser"), signature), "Identity"); + + const proof = await createSealProof({ + signer: alice, + subject: { hash: await createSealHash(text.encode("browser")) }, + }); + check((await verifySealProof(proof, text.encode("browser"))).valid, "Seal"); + + const ciphertext = await encrypt(text.encode("browser"), [bob.publicIdentity]); + check(new TextDecoder().decode(await decrypt(ciphertext, bob)) === "browser", "Armour"); + + const writer = createWriter(await createLedger({ signer: alice }), alice); + writer.append({ kind: "browser", payload: { value: "signed" } }); + const history = await writer.commit(); + check((await openLedger(history.export())).compare(history) === "equal", "Ledger"); + + const doc = await createDocument({ model: notes, identity: alice }); + const team = await doc.createGroup(); + await doc.setMember(bob.publicIdentity, { group: team, role: "member" }); + doc.stage({ type: "note.put", data: { id: "1", title: "hello browser" } }, { group: team }); + await doc.commit(); + const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); + check(bobs.state(team).notes["1"] === "hello browser", "Concord"); + const output = document.createElement("output"); output.id = "concord-proof"; - output.textContent = "Concord: hello browser"; + output.textContent = `Concord: ${bobs.state(team).notes["1"]}`; document.body.append(output); } diff --git a/scripts/verify/concord-consumer.txt b/scripts/verify/concord-consumer.txt deleted file mode 100644 index 0be79ca..0000000 --- a/scripts/verify/concord-consumer.txt +++ /dev/null @@ -1,124 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { identityFromSeed, generateIdentity, encryptAge, decryptAgeWithSecret } from "@ternent/armour"; -import { ledgerSignatureMessage, verifyLedger } from "@ternent/ledger"; -import { encodeBase64Url, validatePublicIdentity } from "@ternent/identity"; -import { createDocument, openDocument } from "@ternent/concord"; -import { createStandardSystemProfile, setMember, removeMember } from "@ternent/concord/system"; -import { registerModel, createMemoryArtifactStore, assertModelConformance } from "@ternent/concord/testing"; -import { canonicalize, hashEntrySubject, hashCommitSubject, verifyDocument, compareSnapshots } from "@ternent/concord/protocol"; -const value = result => { assert.equal(result.ok, true, result.error?.code); return result.value; }; -const fixed = JSON.parse(readFileSync("owner.expected.json", "utf8")); -const identity = value(await identityFromSeed(new Uint8Array(Buffer.from(fixed.identitySeedHex,"hex")))); -assert.equal(validatePublicIdentity(identity.publicIdentity).ok, true); -const system = createStandardSystemProfile(); -const handle = value(await createDocument({model:registerModel,system,identity})); -value(await handle.dispatch("set",{value:"packed Concord"})); -const artifact = handle.export(); -const opened = await openDocument({bytes:artifact,model:registerModel,system,signer:identity}); -assert.equal(opened.state().status,"ready"); -assert.deepEqual(value(await opened.replay()).projection,{value:"packed Concord"}); -assert.deepEqual(opened.inspect().findings,[]); -assert.equal((await opened.verify()).integrity,"valid"); -assert.equal((await verifyDocument(artifact)).integrity,"valid"); -assert.equal((await verifyLedger(artifact)).integrity,"valid"); -assert.equal(JSON.parse(new TextDecoder().decode(artifact)).format,"ledger"); -assert.equal(value(await compareSnapshots(artifact,opened.export())),"equal"); -const saved = new Uint8Array(readFileSync("owner.document.json")); -const reference = await openDocument({bytes:saved,model:registerModel,system,signer:identity}); -assert.deepEqual(reference.state(),{status:"ready",documentId:fixed.documentId,head:fixed.head,projection:fixed.projection,canWrite:true,coverage:"complete",lockedEntries:0}); -const wire = JSON.parse(new TextDecoder().decode(saved)); -assert.equal(value(hashEntrySubject(wire.entries[0].subject)),wire.entries[0].id); -assert.equal(value(hashCommitSubject(wire.commits[0].subject)),wire.commits[0].id); -assert.equal(new TextDecoder().decode(value(canonicalize({z:1,a:2}))),'{"a":2,"z":1}'); -const locked = await openDocument({bytes:saved,model:registerModel,system}); -assert.equal(locked.state().reason,"locked"); -assert.deepEqual(locked.export(),saved); -const store = createMemoryArtifactStore();value(await store.write(artifact));assert.deepEqual(value(await store.read()),artifact); -assert.equal(assertModelConformance(registerModel,{initial:{value:""},steps:[]}).ok,true); -const fresh = value(await generateIdentity());assert.notEqual(fresh.publicIdentity.id,identity.publicIdentity.id); -const membership = value(await createDocument({model:registerModel,system:createStandardSystemProfile(),identity})); -value(await membership.dispatch("set",{value:"history before admission"})); -value(await setMember(membership,{identity:fresh.publicIdentity,capabilities:["read"]})); -const viewer = await openDocument({bytes:membership.export(),model:registerModel,system:createStandardSystemProfile(),reader:fresh}); -assert.deepEqual(value(await viewer.replay()).projection,{value:"history before admission"}); -assert.equal(viewer.state().canWrite,false); -assert.equal(viewer.inspect().otherRecipientsDecryptability,"unverified"); -value(await removeMember(membership,{identityId:fresh.publicIdentity.id})); -const revoked = await openDocument({bytes:membership.export(),model:registerModel,system:createStandardSystemProfile(),reader:fresh}); -assert.equal(revoked.state().canWrite,false); -assert.deepEqual(value(await revoked.replay()).projection,{value:"history before admission"}); -value(await membership.dispatch("set",{value:"future after removal"})); -const futureLocked = await openDocument({bytes:membership.export(),model:registerModel,system:createStandardSystemProfile(),reader:fresh}); -assert.equal(futureLocked.inspect().findings[0].code,"KEY_UNAVAILABLE"); -const group = new Uint8Array(Buffer.from(fixed.groupSecretHex,"hex")); -const cipher = value(await encryptAge({recipients:[fixed.groupRecipient],plaintext:new TextEncoder().encode("standalone Armour")})); -assert.equal(new TextDecoder().decode(value(await decryptAgeWithSecret({secret:group,ciphertext:cipher}))),"standalone Armour"); - -const annotated = structuredClone(wire); -const annotatedCommit = annotated.commits.at(-1); -annotatedCommit.subject.metadata = { n: 1000000000000000 }; -annotatedCommit.id = value(hashCommitSubject(annotatedCommit.subject)); -annotatedCommit.signature = encodeBase64Url(value(await identity.sign(ledgerSignatureMessage(annotatedCommit.subject)))); -annotated.head = annotatedCommit.id; -const canonical = value(canonicalize(annotated)); -const transport = new TextEncoder().encode(new TextDecoder().decode(canonical).replace("1000000000000000", "1e15")); -const bounded = await openDocument({bytes:transport,model:registerModel,system,signer:identity,limits:{maxBytes:transport.length}}); -assert.deepEqual(bounded.state(),{status:"inspection",reason:"incompatible"}); -assert.equal((await bounded.verify()).findings[0].code,"RESOURCE_LIMIT"); -assert.deepEqual(bounded.export(),transport); -const expanded = await openDocument({bytes:transport,model:registerModel,system,signer:identity,limits:{maxBytes:canonical.length}}); -assert.equal(expanded.state().status,"ready"); -assert.deepEqual(expanded.export(),canonical); -assert.equal((await expanded.verify()).integrity,"valid"); - -const tampered = structuredClone(wire); -tampered.commits[1].signature = "A".repeat(86); -const badBytes = value(canonicalize(tampered)); -const inspection = await openDocument({bytes:badBytes,model:registerModel,system,signer:identity}); -assert.deepEqual(inspection.state(),{status:"inspection",reason:"invalid"}); -assert.equal(inspection.inspect().findings[0].code,"SIGNATURE_INVALID"); -assert.deepEqual(inspection.inspect().history,tampered.commits); -assert.deepEqual(inspection.export(),badBytes); -assert.equal((await inspection.dispatch("set",{value:"blocked"})).error.code,"INSPECTION_ONLY"); - -const multi = {...registerModel,commands:{set:{...registerModel.commands.set,decide:()=>({ok:true,value:Array.from({length:20},()=>({type:"value.set",version:1,data:{value:""}}))})}}}; -const batch = value(await createDocument({model:multi,system,identity})); -value(await batch.dispatch("set",{value:""})); -const batchBytes = batch.export(); -const batchOpen = await openDocument({bytes:batchBytes,model:multi,system:createStandardSystemProfile(),signer:identity,limits:{maxBytes:batchBytes.length}}); -assert.deepEqual(batchOpen.state(),batch.state()); -assert.deepEqual(batchOpen.export(),batchBytes); -assert.deepEqual(value(await batchOpen.replay()).projection,{value:""}); -assert.equal((await batchOpen.verify()).integrity,"valid"); -console.log(`Concord public consumers passed on ${process.version}`); - -const staged = value(await createDocument({model:registerModel,system:createStandardSystemProfile(),identity,mode:"draft"})); -const committedBefore = staged.export(); -const stateBefore = staged.state(); -assert.equal(value(await staged.dispatch("set",{value:"first staged value"})).status,"staged"); -assert.equal(value(await staged.dispatch("set",{value:"final staged value"})).entryCount,2); -assert.deepEqual(staged.export(),committedBefore); -assert.deepEqual(staged.state(),stateBefore); -assert.equal(value(await staged.replay()).projection.value,""); -assert.equal(staged.draft().preview.value,"final staged value"); -assert.equal((await setMember(staged,{identity:fresh.publicIdentity,capabilities:["read"]})).error.code,"DRAFT_PENDING"); -const receipt = value(await staged.commit({message:"Two register edits"})); -assert.equal(receipt.entryIds.length,2); -assert.equal(staged.draft(),null); -const stagedWire = JSON.parse(new TextDecoder().decode(staged.export())); -assert.equal(stagedWire.commits.length,2); -assert.deepEqual(stagedWire.commits[1].subject.metadata,{message:"Two register edits"}); -assert.equal(value(hashCommitSubject(stagedWire.commits[1].subject)),receipt.head); -assert.equal((await verifyDocument(staged.export())).integrity,"valid"); -assert.equal(staged.state().projection.value,"final staged value"); -assert.equal((await staged.commit()).error.code,"NO_DRAFT"); -value(await staged.dispatch("set",{value:"discard this plaintext"})); -const savedCommitted = staged.export(); -value(await staged.discardDraft()); -assert.equal(staged.draft(),null); -assert.deepEqual(staged.export(),savedCommitted); -const stagedReopen = await openDocument({bytes:staged.export(),model:registerModel,system:createStandardSystemProfile(),signer:identity,mode:"draft"}); -assert.deepEqual(stagedReopen.state(),staged.state()); -assert.equal(stagedReopen.draft(),null); -console.log(`Draft commit, signed metadata, discard and committed-only replay passed on ${process.version}`); diff --git a/scripts/verify/consumer.txt b/scripts/verify/consumer.txt new file mode 100644 index 0000000..b3faa28 --- /dev/null +++ b/scripts/verify/consumer.txt @@ -0,0 +1,74 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { createIdentity, recoverIdentity, restoreIdentity, verify } from "@ternent/identity"; +import { createSealHash, createSealProof, verifySealProof } from "@ternent/seal"; +import { decrypt, encrypt } from "@ternent/armour"; +import { createLedger, createWriter, openLedger } from "@ternent/ledger"; +import { createDocument, defineModel, openDocument } from "@ternent/concord"; + +const bytes = (text) => new TextEncoder().encode(text); + +// Identity: create, back up, restore, recover, sign and verify. +const alice = await createIdentity(); +const restored = await restoreIdentity(alice.export()); +assert.deepEqual(restored.publicIdentity, alice.publicIdentity); +const signature = await alice.sign(bytes("signed")); +assert.equal(await verify(alice.publicIdentity, bytes("signed"), signature), true); +assert.equal(await verify(alice.publicIdentity, bytes("changed"), signature), false); +const words = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; +assert.equal((await recoverIdentity(words, "TREZOR")).publicIdentity.publicKey, "6IBjlSqvqPfmXohZXC-oqbjX71wHutV9vvrRtw5VrUE"); + +// Seal: a detached proof checks signature and hash separately. +const proof = await createSealProof({ signer: alice, subject: { hash: await createSealHash(bytes("artifact")) } }); +assert.deepEqual(await verifySealProof(proof, bytes("artifact")), { valid: true, signatureValid: true, hashMatch: true }); +assert.equal((await verifySealProof(proof, bytes("other"))).hashMatch, false); + +// Armour: identities, a native group key and a passphrase. +const bob = await createIdentity(); +const ciphertext = await encrypt(bytes("shared"), [alice.publicIdentity, bob.publicIdentity]); +assert.deepEqual(await decrypt(ciphertext, bob), bytes("shared")); +const locked = await encrypt(bytes(alice.export()), { passphrase: "correct horse" }); +assert.equal(new TextDecoder().decode(await decrypt(locked, { passphrase: "correct horse" })), alice.export()); +await assert.rejects(decrypt(ciphertext, await createIdentity())); + +// Ledger: the saved v2 vector opens with its IDs, and a written history round-trips. +const ledgerVector = JSON.parse(readFileSync("ledger-vector.json", "utf8")); +const canonical = (value) => + Array.isArray(value) + ? `[${value.map(canonical).join(",")}]` + : value && typeof value === "object" + ? `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}` + : JSON.stringify(value); +const opened = await openLedger(bytes(canonical(ledgerVector.document))); +assert.equal(opened.head, ledgerVector.expected.head); +const writer = createWriter(await createLedger({ signer: alice }), alice); +writer.append({ kind: "note", payload: { text: "hello" } }); +const history = await writer.commit(); +assert.equal((await openLedger(history.export())).compare(history), "equal"); + +// Concord: the saved vector opens for each identity, and a new document with a group works. +const notes = defineModel({ + id: "notes", + version: 1, + initial: () => ({ notes: {} }), + reduce(state, event) { + if (event.type === "note.put") return { notes: { ...state.notes, [event.data.id]: event.data.title } }; + throw new Error(`Unknown event ${event.type}`); + }, +}); +const concordVector = JSON.parse(readFileSync("concord-vector.json", "utf8")); +for (const [name, backup] of Object.entries(concordVector.identities)) { + const doc = await openDocument(bytes(concordVector.document), { model: notes, identity: await restoreIdentity(backup) }); + const groups = Object.fromEntries(doc.groups.map((g) => [g.default ? "default" : "team", doc.state(g.id)])); + assert.deepEqual({ groups, unreadable: doc.unreadable, rejected: doc.rejected.length }, concordVector.expected[name]); +} +const doc = await createDocument({ model: notes, identity: alice }); +const team = await doc.createGroup(); +await doc.setMember(bob.publicIdentity, { group: team, role: "member" }); +doc.stage({ type: "note.put", data: { id: "1", title: "private" } }, { group: team }); +await doc.commit(); +const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); +assert.deepEqual(bobs.state(team), { notes: { 1: "private" } }); +assert.throws(() => bobs.state()); + +console.log(`All five installed libraries and their saved vectors pass on ${process.version}`); diff --git a/scripts/verify/consumers.mjs b/scripts/verify/consumers.mjs index 03c2d93..4e1e957 100644 --- a/scripts/verify/consumers.mjs +++ b/scripts/verify/consumers.mjs @@ -231,7 +231,7 @@ try { type: "module", dependencies: { "@ternent/identity": "999999.0.0-b13" }, }); - put("probes/range-package/index.js", 'export { generateSigner } from "@ternent/identity";\n'); + put("probes/range-package/index.js", 'export { createIdentity } from "@ternent/identity";\n'); const probePack = JSON.parse( pnpm( ["pack", "--json", "--pack-destination", join(consumer, "probes")], @@ -351,31 +351,10 @@ try { checks.push( `${publishedBundle ? "fresh public-registry" : "temporary-registry"} names/versions resolve without sibling overrides; registry tarball digests, locked SRI and every resolved candidate copy match the packed bytes`, ); - for (const name of [ - "owner.document.json", - "owner.expected.json", - "groups.removed.document.json", - "groups.readmitted.document.json", - "groups.expected.json", - ]) - cpSync(resolve(root, "docs/concord/vectors", name), join(consumer, name)); - cpSync( - resolve(root, "packages/ledger/test/vectors/signed-log.json"), - join(consumer, "ledger-signed-log.json"), - ); - put("ledger.mjs", readFileSync(resolve(root, "scripts/verify/ledger-consumer.txt"), "utf8")); - put("payload.mjs", readFileSync(resolve(root, "scripts/verify/payload-consumer.txt"), "utf8")); - put("storage.mjs", readFileSync(resolve(root, "scripts/verify/storage-consumer.txt"), "utf8")); - put("groups.mjs", readFileSync(resolve(root, "scripts/verify/groups-consumer.txt"), "utf8")); - put("concord.mjs", readFileSync(resolve(root, "scripts/verify/concord-consumer.txt"), "utf8")); - put( - "primitives.mjs", - readFileSync(resolve(root, "scripts/verify/primitives-consumer.txt"), "utf8"), - ); - put( - "protocol-isolation.mjs", - readFileSync(resolve(root, "scripts/verify/protocol-isolation.txt"), "utf8"), - ); + cpSync(resolve(root, "packages/ledger/test/vectors.json"), join(consumer, "ledger-vector.json")); + cpSync(resolve(root, "packages/concord/test/vector.json"), join(consumer, "concord-vector.json")); + put("consumer.mjs", readFileSync(resolve(root, "scripts/verify/consumer.txt"), "utf8")); + put("isolation.mjs", readFileSync(resolve(root, "scripts/verify/isolation.txt"), "utf8")); const runtimes = [process.execPath]; for (const major of [22, 24]) { const executable = process.env[`CONCORD_NODE${major}`]; @@ -396,33 +375,14 @@ try { .map((executable) => execFileSync(executable, ["--version"], { encoding: "utf8" }).trim()) .join(", "); for (const executable of runtimes) { - console.log(execFileSync(executable, ["ledger.mjs"], { cwd: consumer, encoding: "utf8" })); - console.log(execFileSync(executable, ["payload.mjs"], { cwd: consumer, encoding: "utf8" })); - console.log(execFileSync(executable, ["primitives.mjs"], { cwd: consumer, encoding: "utf8" })); - console.log(execFileSync(executable, ["concord.mjs"], { cwd: consumer, encoding: "utf8" })); - console.log(execFileSync(executable, ["groups.mjs"], { cwd: consumer, encoding: "utf8" })); - console.log(execFileSync(executable, ["storage.mjs"], { cwd: consumer, encoding: "utf8" })); - console.log( - execFileSync(executable, ["protocol-isolation.mjs"], { cwd: consumer, encoding: "utf8" }), - ); + console.log(execFileSync(executable, ["consumer.mjs"], { cwd: consumer, encoding: "utf8" })); + for (const name of Object.keys(candidates)) + console.log( + execFileSync(executable, ["isolation.mjs", name], { cwd: consumer, encoding: "utf8" }), + ); } checks.push( - `Identity, Armour and all Concord subpaths: lifecycle, draft batching, signed metadata and fixed vectors on ${versions}; protocol import isolation`, - ); - checks.push( - `Independent group saved vectors, readable coverage, scoped authoring and retryable cross-group draft commits on ${versions}`, - ); - checks.push( - `Identity mnemonic/serialization/signing and init-free Armour helper contracts on ${versions}`, - ); - checks.push( - `External artifact storage, expected-head conflicts, retained forks and committed-only draft publication on ${versions}`, - ); - checks.push( - `Standalone Ledger lifecycle, fixed vectors, declarations and import isolation on ${versions}`, - ); - checks.push( - `Optional Armour payload codec, keyless Ledger verification and locked/readable decoding on ${versions}`, + `Identity, Seal, Armour, Ledger and Concord behaviour, saved Ledger and Concord vectors, and import isolation on ${versions}`, ); put("tsconfig.json", { compilerOptions: { @@ -438,28 +398,9 @@ try { lib: ["ES2022", "DOM"], types: ["node", "vite-plus/client"], }, - include: [ - "concord-types.ts", - "primitives-types.ts", - "groups-types.ts", - "storage-types.ts", - "ledger-types.ts", - "src/**/*.ts", - "vite.config.ts", - "feedback.ts", - ], + include: ["types.ts", "src/**/*.ts", "vite.config.ts", "feedback.ts"], }); - put("ledger-types.ts", readFileSync(resolve(root, "scripts/verify/ledger-types.txt"), "utf8")); - put("groups-types.ts", readFileSync(resolve(root, "scripts/verify/groups-types.txt"), "utf8")); - put("storage-types.ts", readFileSync(resolve(root, "scripts/verify/storage-types.txt"), "utf8")); - put( - "primitives-types.ts", - readFileSync(resolve(root, "scripts/verify/primitives-types.txt"), "utf8"), - ); - put( - "concord-types.ts", - 'import {createDocument,openDocument} from "@ternent/concord";\nimport {createStandardSystemProfile} from "@ternent/concord/system";\nimport {registerModel} from "@ternent/concord/testing";\nimport {generateIdentity} from "@ternent/armour";\nconst identity=await generateIdentity();if(!identity.ok)throw new Error();\nconst created=await createDocument({model:registerModel,system:createStandardSystemProfile(),identity:identity.value});if(!created.ok)throw new Error();\nawait created.value.dispatch("set",{value:"typed"});\n// @ts-expect-error unknown command names are rejected.\nawait created.value.dispatch("missing",{});\n// @ts-expect-error command payload types survive publishing.\nawait created.value.dispatch("set",{value:42});\nconst opened=await openDocument({bytes:created.value.export(),model:registerModel,system:createStandardSystemProfile(),signer:identity.value});\nawait opened.dispatch("set",{value:"typed"});\n// @ts-expect-error open retains model command types.\nawait opened.dispatch("set",{value:42});\n', - ); + put("types.ts", readFileSync(resolve(root, "scripts/verify/types.txt"), "utf8")); put( "index.html", 'Library consumer verification
', @@ -523,7 +464,7 @@ export default defineConfig({ await page.screenshot({ path: resolve(root, "artifacts/browser.png") }); await page.close(); checks.push( - "Chromium: standalone Ledger, Armour codecs, encrypted Concord and independent groups, storage, drafts, production CSS and Vue render interaction", + "Chromium: Identity, Seal, Armour, Ledger and an encrypted Concord group, production CSS and Vue render interaction", ); } finally { await app.close(); diff --git a/scripts/verify/groups-consumer.txt b/scripts/verify/groups-consumer.txt deleted file mode 100644 index 0cf52a1..0000000 --- a/scripts/verify/groups-consumer.txt +++ /dev/null @@ -1,95 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { createHash } from "node:crypto"; -import { identityFromSeed } from "@ternent/armour"; -import { createDocument, openDocument } from "@ternent/concord"; -import { createGroup, createStandardSystemProfile, setMember, removeMember } from "@ternent/concord/system"; -import { verifyDocument } from "@ternent/concord/protocol"; -const value = result => { assert.equal(result.ok, true, result.error?.code); return result.value; }; -const ok = value => ({ok:true,value}); -const checkInput = input => input && typeof input === "object" && - typeof input.audience === "string" && typeof input.key === "string" && - typeof input.value === "string" && typeof input.admin === "boolean" - ? ok(input) : {ok:false,error:{code:"INVALID_INPUT",message:"Expected group value"}}; -const model = { - ref:{id:"concord.test.independent-groups",version:1}, - initial:()=>({values:{},locked:[],actors:[]}), - commands:{put:{validate:checkInput,audience:input=>input.audience, - decide:data=>ok([{type:"group.value",version:1,data}])}}, - validateEvent:event=>event?.type === "group.value" && event.version === 1 && checkInput(event.data).ok - ? ok(event) : {ok:false,error:{code:"INVALID_EVENT",message:"Expected group event"}}, - audience:event=>event.data.audience, - requirements:event=>event.data.admin ? ["administer"] : ["write"], - reduce:(state,event,facts)=>ok({values:{...state.values,[event.data.key]:event.data.value}, - locked:[...state.locked],actors:[...state.actors,`${facts.audience}:${facts.actor.id}`]}), - reduceLocked:(state,entry)=>ok({...state,locked:[...state.locked,`${entry.audience}:${entry.epoch}`]}), -}; -const fixed = JSON.parse(readFileSync("owner.expected.json","utf8")); -const expected = JSON.parse(readFileSync("groups.expected.json","utf8")); -const identities = { - owner:value(await identityFromSeed(new Uint8Array(Buffer.from(fixed.identitySeedHex,"hex")))), - creator:value(await identityFromSeed(new Uint8Array(32).fill(2))), - bob:value(await identityFromSeed(new Uint8Array(32).fill(3))), -}; -for (const stage of ["removed","readmitted"]) { - const bytes = new Uint8Array(readFileSync(`groups.${stage}.document.json`)); - assert.equal((await verifyDocument(bytes)).integrity,"valid"); - for (const [name,signer] of Object.entries(identities)) { - const handle = await openDocument({bytes,model,system:createStandardSystemProfile(),signer}); - assert.deepEqual(value(await handle.replay()),expected.readers[name][stage]); - assert.deepEqual(value(await handle.replay()),value(await handle.replay())); - assert.equal(handle.state().canWrite,expected.canWrite[name]); - assert.equal(handle.state().head,expected.heads[stage]); - assert.equal(createHash("sha256").update(handle.export()).digest("hex"),expected.canonicalSha256[stage]); - assert.equal(handle.inspect().application,name === "creator" ? "valid" : "scoped"); - assert.equal(handle.inspect().entries.length,6); - } - const full = {...model,reduceLocked:undefined}; - const blocked = await openDocument({bytes,model:full,system:createStandardSystemProfile(),reader:identities.bob}); - assert.equal(blocked.state().reason,"locked"); -} -const host = value(await createDocument({model,system:createStandardSystemProfile(),identity:identities.owner})); -const group = value(await createGroup(host)).audience; -value(await host.dispatch("put",{audience:group,key:"label",value:"encrypted group title",admin:false})); -value(await setMember(host,{audience:group,identity:identities.bob.publicIdentity,capabilities:["read","write"]})); -const bob = await openDocument({bytes:host.export(),model,system:createStandardSystemProfile(),signer:identities.bob}); -value(await bob.dispatch("put",{audience:group,key:"entry",value:"independent writer",admin:false})); -assert.equal((await createGroup(bob)).error.code,"CAPABILITY_DENIED"); -const latest = await openDocument({bytes:bob.export(),model,system:createStandardSystemProfile(),signer:identities.owner}); -value(await removeMember(latest,{audience:group,identityId:identities.bob.publicIdentity.id})); -value(await latest.dispatch("put",{audience:group,key:"entry",value:"future private epoch",admin:false})); -const removed = await openDocument({bytes:latest.export(),model,system:createStandardSystemProfile(),signer:identities.bob}); -assert.equal(removed.state().coverage,"readable"); -assert.equal(removed.state().lockedEntries,1); -assert.equal(removed.state().projection.values.entry,"independent writer"); -assert.equal(removed.state().canWrite,false); -console.log(`Independent group fixed vectors and public authoring passed on ${process.version}`); - -let failSigning = true; -const signer = {...identities.owner,sign:message=>failSigning - ? Promise.resolve({ok:false,error:{code:"INJECTED",message:"Injected signing failure"}}) - : identities.owner.sign(message)}; -const draft = await openDocument({bytes:latest.export(),model,system:createStandardSystemProfile(),signer,mode:"draft"}); -const beforeDraft = draft.export(); -value(await draft.dispatch("put",{audience:"document",key:"shared",value:"staged default",admin:false})); -value(await draft.dispatch("put",{audience:group,key:"entry",value:"staged private",admin:false})); -assert.equal(draft.draft().entryCount,2); -assert.deepEqual(draft.export(),beforeDraft); -const preview = draft.draft(); -assert.equal((await draft.commit({message:"Retriable cross-group batch"})).error.code,"SIGNING_FAILED"); -assert.deepEqual(draft.draft(),preview); -assert.deepEqual(draft.export(),beforeDraft); -failSigning = false; -const metadata = {message:"Retriable cross-group batch"}; -const pending = draft.commit(metadata); -metadata.message = "caller mutation"; -const receipt = value(await pending); -assert.equal(receipt.entryIds.length,2); -assert.equal(draft.draft(),null); -const batch = JSON.parse(new TextDecoder().decode(draft.export())); -assert.deepEqual(batch.commits.at(-1).subject.metadata,{message:"Retriable cross-group batch"}); -assert.deepEqual(batch.entries.slice(-2).map(entry=>entry.subject.payload.data.audience),["document",group]); -assert.equal((await verifyDocument(draft.export())).integrity,"valid"); -const reopened = await openDocument({bytes:draft.export(),model,system:createStandardSystemProfile(),signer:identities.owner}); -assert.deepEqual(reopened.state(),draft.state()); -console.log(`Cross-group draft batch, signing failure retention and retry passed on ${process.version}`); diff --git a/scripts/verify/groups-types.txt b/scripts/verify/groups-types.txt deleted file mode 100644 index f5e125b..0000000 --- a/scripts/verify/groups-types.txt +++ /dev/null @@ -1,61 +0,0 @@ -import { createDocument, type AudienceId, type GroupId, type ProjectionResult } from "@ternent/concord"; -import { createGroup, createStandardSystemProfile, setMember } from "@ternent/concord/system"; -import { registerModel } from "@ternent/concord/testing"; -import { generateIdentity } from "@ternent/armour"; -const identity = await generateIdentity(); -if (!identity.ok) throw new Error(identity.error.code); -const created = await createDocument({model:registerModel,system:createStandardSystemProfile(),identity:identity.value}); -if (!created.ok) throw new Error(created.error.code); -const group = await createGroup(created.value); -if (!group.ok) throw new Error(group.error.code); -const groupId: GroupId = group.value.audience; -const audience: AudienceId = groupId; -await setMember(created.value,{audience,identity:identity.value.publicIdentity,capabilities:["read"]}); -// @ts-expect-error Default audience is not an independent GroupId. -const invalid: GroupId = "document"; -// @ts-expect-error Public helpers reject nullable audiences. -await setMember(created.value,{audience:null,identity:identity.value.publicIdentity,capabilities:["read"]}); -const replay = await created.value.replay(); -if (replay.ok) { - const result: ProjectionResult<{value:string}> = replay.value; - const value: string = result.projection.value; - const coverage: "complete" | "readable" = result.coverage; - // @ts-expect-error Replay metadata wraps the projection, rather than masquerading as it. - const bare: {value:string} = replay.value; - void [value,coverage,bare]; -} -const state = created.value.state(); -if (state.status === "ready") { - const coverage: "complete" | "readable" = state.coverage; - const count: number = state.lockedEntries; - void [coverage,count]; -} -for (const entry of created.value.inspect().entries ?? []) { - if (entry.status === "locked") { - const audience: AudienceId = entry.audience; - // @ts-expect-error Locked markers never expose fabricated plaintext events. - void entry.event; - void audience; - } else { - const type: string = entry.event.type; - void type; - } -} -void invalid; -const pending = await created.value.dispatch("set",{value:"draft typed receipt"}); -if (pending.ok && pending.value.status === "staged") { - const count: number = pending.value.entryCount; - // @ts-expect-error A provisional receipt has no signed head. - void pending.value.head; - void count; -} -const preview = created.value.draft(); -if (preview) { - const text: string = preview.preview.value; - // @ts-expect-error Preview state retains model types. - const wrong: number = preview.preview.value; - void [text,wrong]; -} -await created.value.commit({message:"Typed signed metadata"}); -// @ts-expect-error Commit metadata is an object. -await created.value.commit("message"); diff --git a/scripts/verify/isolation.txt b/scripts/verify/isolation.txt new file mode 100644 index 0000000..b674d93 --- /dev/null +++ b/scripts/verify/isolation.txt @@ -0,0 +1,28 @@ +import { readFileSync } from "node:fs"; +import { isBuiltin, registerHooks } from "node:module"; + +// Imports one installed library with Node built-ins blocked, and lets each Ternent package +// import only the Ternent packages it declares. A library that needs Node, or reaches past +// its own dependencies, fails here. +const name = process.argv[2]; +const declared = new Map(); +function dependenciesOf(packageUrl) { + if (!declared.has(packageUrl)) { + const manifest = JSON.parse(readFileSync(new URL(`${packageUrl}/package.json`), "utf8")); + declared.set(packageUrl, new Set(Object.keys(manifest.dependencies ?? {}))); + } + return declared.get(packageUrl); +} +registerHooks({ + resolve(specifier, context, next) { + if (isBuiltin(specifier)) throw new Error(`${name} loads a Node built-in: ${specifier}`); + const target = specifier.match(/^@ternent\/[^/]+/)?.[0]; + const parent = context.parentURL?.match(/^(.*\/node_modules\/(@ternent\/[^/]+))\//); + if (target && parent && !dependenciesOf(parent[1]).has(target)) { + throw new Error(`${parent[2]} imports undeclared ${target}`); + } + return next(specifier, context); + }, +}); +await import(name); +console.log(`${name} imports without Node built-ins or undeclared Ternent packages`); diff --git a/scripts/verify/ledger-consumer.txt b/scripts/verify/ledger-consumer.txt deleted file mode 100644 index 4d39c75..0000000 --- a/scripts/verify/ledger-consumer.txt +++ /dev/null @@ -1,30 +0,0 @@ -import assert from "node:assert/strict"; -import { isBuiltin, registerHooks } from "node:module"; -import { readFileSync } from "node:fs"; -const fixed = new Uint8Array(readFileSync("ledger-signed-log.json")); -registerHooks({resolve(specifier,context,next){ - if (isBuiltin(specifier) || specifier.startsWith("@ternent/concord") || specifier.startsWith("@ternent/armour") || specifier.startsWith("@ternent/seal") || specifier.startsWith("age-encryption")) throw new Error(`Forbidden Ledger dependency: ${specifier}`); - return next(specifier,context); -}}); -const {createLedger,verifyLedger,compareLedgers,encodeJson}=await import("@ternent/ledger"); -await import("@ternent/ledger/protocol"); -const {signerFromSeed}=await import("@ternent/identity"); -const identity=await signerFromSeed(new Uint8Array(32).fill(4));if(!identity.ok)throw new Error(identity.error.code); -assert.equal((await verifyLedger(fixed)).integrity,"valid"); -const log=await createLedger({signer:identity.value}); -await log.load(fixed); -const base=await log.export(); -await log.append({kind:"standalone",payload:{value:42}}); -assert.deepEqual(await log.export(),base); -assert.equal((await log.replay()).at(-1).committed,false); -const receipt=await log.commit({metadata:{note:"packed consumer"}}); -assert.equal(receipt.committedEntries.length,1); -const wire=await log.export(); -assert.equal((await log.verify()).integrity,"valid"); -assert.deepEqual(await compareLedgers(fixed,encodeJson(wire)),{ok:true,value:"behind"}); -const reader=await createLedger();await reader.import(wire); -assert.deepEqual(await reader.replay(),await log.replay()); -const tampered=structuredClone(wire);tampered.entries.at(-1).subject.payload.data={value:0}; -await assert.rejects(()=>reader.import(tampered)); -assert.deepEqual(await reader.export(),wire); -console.log("Standalone Ledger create/load/stage/commit/replay/verify and fixed vector pass with Node builtins, Concord, Armour and Seal imports blocked"); diff --git a/scripts/verify/ledger-types.txt b/scripts/verify/ledger-types.txt deleted file mode 100644 index ac33c47..0000000 --- a/scripts/verify/ledger-types.txt +++ /dev/null @@ -1,57 +0,0 @@ -import { createLedger, encodePayload, decodePayload, type LedgerPayloadCodec, type LedgerPayloadEncoder, type LedgerPayloadDecoder, type LedgerReplayEntry } from "@ternent/ledger"; -import { createAgeCodec, generateIdentity, type AgePayloadEncoder, type AgePayloadDecoder } from "@ternent/armour"; -import { ageRecipientFromPublicIdentity, generateSigner } from "@ternent/identity"; -const signer = await generateSigner(); -if (!signer.ok) throw new Error(signer.error.code); -const log = await createLedger({signer: signer.value}); -await log.create(); -await log.append({kind:"reading",payload:{value:7}}); -const entries: LedgerReplayEntry[] = await log.replay(); -const projected = await createLedger({signer:signer.value,initialProjection:0,projector:(count,entry)=>count+1}); -const count: number = await projected.replay(); -// @ts-expect-error A kind is required. -await log.append({payload:42}); -// @ts-expect-error Payloads are portable JSON. -await log.append({kind:"bad",payload:1n}); -// @ts-expect-error A custom projection requires its projector. -await createLedger({initialProjection:0}); -// @ts-expect-error The selected projection type survives package declarations. -const wrong: string = await projected.replay(); -void [entries,count,wrong]; -const reader = await generateIdentity(); if (!reader.ok) throw new Error(reader.error.code); -const codec: LedgerPayloadCodec = createAgeCodec({reader:reader.value}); -const recipient = ageRecipientFromPublicIdentity(reader.value.publicIdentity); if (!recipient.ok) throw new Error(recipient.error.code); -const recipients = [recipient.value]; -const writer = createAgeCodec({recipients}); -const readerOnly = createAgeCodec({reader:reader.value}); -const both = createAgeCodec({recipients,reader:reader.value}); -const encoder: LedgerPayloadEncoder = writer; -const decoder: LedgerPayloadDecoder = readerOnly; -const armourEncoder: AgePayloadEncoder = writer; -const armourDecoder: AgePayloadDecoder = readerOnly; -await writer.encode(new Uint8Array()); -await readerOnly.decode(new Uint8Array()); -await both.encode(new Uint8Array()); -await both.decode(new Uint8Array()); -await encodePayload({value:7},writer); -await encodePayload({value:7},both); -// @ts-expect-error A reader-only codec cannot encode payloads. -await encodePayload({value:7},readerOnly); -// @ts-expect-error A codec with no operations cannot encode payloads. -await encodePayload({value:7},createAgeCodec()); -// @ts-expect-error An optional encoder is not a guaranteed encoding capability. -await encodePayload({value:7},codec); -const dynamicOptions: {recipients?: readonly string[];reader?: typeof reader.value} = {}; -const dynamicCodec = createAgeCodec(dynamicOptions); -// @ts-expect-error Optional configuration cannot promise an encoder. -await encodePayload({value:7},dynamicCodec); -const decoded = await decodePayload((await log.replay())[0].payload.data,codec); -if (decoded.status === "locked") { - // @ts-expect-error Unavailable payloads do not expose plaintext. - decoded.data; -} -// @ts-expect-error Codec integration retains the portable JSON requirement. -await encodePayload(1n,writer); -// @ts-expect-error Byte codecs cannot return text instead of bytes. -const invalidCodec: LedgerPayloadCodec = {id:"broken",encode:async()=>"text"}; -void [invalidCodec,encoder,decoder,armourEncoder,armourDecoder]; diff --git a/scripts/verify/payload-consumer.txt b/scripts/verify/payload-consumer.txt deleted file mode 100644 index 7f18448..0000000 --- a/scripts/verify/payload-consumer.txt +++ /dev/null @@ -1,24 +0,0 @@ -import assert from "node:assert/strict"; -import { ageRecipientFromPublicIdentity } from "@ternent/identity"; -import { createAgeCodec, identityFromSeed } from "@ternent/armour"; -import { createLedger, encodePayload, decodePayload } from "@ternent/ledger"; -const value = result => { assert.equal(result.ok,true,result.error?.code); return result.value; }; -const alice = value(await identityFromSeed(new Uint8Array(32).fill(11))); -const bob = value(await identityFromSeed(new Uint8Array(32).fill(12))); -const codec = createAgeCodec({recipients:[value(ageRecipientFromPublicIdentity(alice.publicIdentity))],reader:alice}); -const log = await createLedger({signer:alice}); await log.create(); -await log.append({kind:"note",payload:await encodePayload({text:"private packed payload"},codec)}); -assert.equal((await log.export()).entries.length,0); -await log.commit(); -const wire = await log.export(); -assert.equal(JSON.stringify(wire).includes("private packed payload"),false); -const reader = await createLedger(); await reader.load(wire); -assert.equal((await reader.verify()).integrity,"valid"); -const payload = (await reader.replay())[0].payload.data; -assert.deepEqual(await decodePayload(payload),{status:"locked",codec:"age"}); -assert.deepEqual(await decodePayload(payload,createAgeCodec({reader:bob})),{status:"locked",codec:"age"}); -assert.deepEqual(await decodePayload(payload,codec),{status:"decoded",data:{text:"private packed payload"}}); -assert.deepEqual(await reader.export(),wire); -const tampered = structuredClone(wire);tampered.entries[0].subject.payload.data.data += "A"; -await assert.rejects(()=>reader.load(tampered)); -console.log(`Opt-in Armour codec with ordinary Ledger staging, keyless verification, locked/readable payloads and tampering passed on ${process.version}`); diff --git a/scripts/verify/primitives-consumer.txt b/scripts/verify/primitives-consumer.txt deleted file mode 100644 index 4d0b910..0000000 --- a/scripts/verify/primitives-consumer.txt +++ /dev/null @@ -1,60 +0,0 @@ -import assert from "node:assert/strict"; -import { - createIdentityFromMnemonic, - createMnemonicIdentity, - decodeBase64Url, - deriveAgeRecipient, - deriveKeyId, - getDefaultSignatureContext, - parseIdentity, - serializeIdentity, - signerFromSeed, - signUtf8, - validateIdentity, - verifySignature, - verifyUtf8, -} from "@ternent/identity"; -import { - encryptForIdentities, - encryptForRecipients, - decryptWithIdentity, - withAgeDecryption, -} from "@ternent/armour"; - -const value = (result) => { - assert.equal(result.ok, true, result.error?.code); - return result.value; -}; -const createdAt = "2026-11-20T00:00:00.000Z"; -const { identity, mnemonic } = await createMnemonicIdentity({ words: 12, createdAt }); -const restored = await createIdentityFromMnemonic({ mnemonic, createdAt }); -assert.deepEqual(restored, identity); -assert.deepEqual(parseIdentity(serializeIdentity(identity)), identity); -assert.deepEqual(await validateIdentity(identity), identity); -assert.equal(await deriveKeyId(identity.publicKey), identity.keyId); - -const signer = value(await signerFromSeed(value(decodeBase64Url(identity.material.seed)))); -assert.equal(signer.publicIdentity.publicKey, identity.publicKey); -assert.equal(signer.publicIdentity.id, `identity:${identity.keyId}`); -const plaintext = new TextEncoder().encode("installed primitive contracts"); -const rawSignature = value(await signer.sign(plaintext)); -assert.equal(value(await verifySignature(signer.publicIdentity, plaintext, rawSignature)), true); -const signature = await signUtf8(identity, new TextDecoder().decode(plaintext)); -assert.equal(getDefaultSignatureContext(), "ternent-seal/v2"); -assert.equal(await verifyUtf8(identity.publicKey, new TextDecoder().decode(plaintext), signature), true); -assert.equal( - await verifyUtf8(identity.publicKey, new TextDecoder().decode(plaintext), signature, { context: "other-context" }), - false, -); -assert.equal((await verifySignature(signer.publicIdentity, plaintext, value(decodeBase64Url(signature)))).ok, false); - -const recipient = await deriveAgeRecipient(identity); -const ciphertext = await encryptForRecipients({ recipients: [recipient], data: plaintext }); -assert.match(new TextDecoder().decode(ciphertext), /^-----BEGIN AGE ENCRYPTED FILE-----/); -assert.deepEqual(await decryptWithIdentity({ identity, data: ciphertext }), plaintext); -const binary = await encryptForIdentities({ identities: [identity], data: plaintext, output: "binary" }); -assert.deepEqual(value(await withAgeDecryption(signer).decryptAge(binary)), plaintext); -const { identity: stranger } = await createMnemonicIdentity(); -await assert.rejects(decryptWithIdentity({ identity: stranger, data: ciphertext }), { code: "ARMOUR_DECRYPT_FAILED" }); - -console.log(`Identity host helpers, exact/contextual signing and init-free Armour passed on ${process.version}`); diff --git a/scripts/verify/primitives-types.txt b/scripts/verify/primitives-types.txt deleted file mode 100644 index b255c90..0000000 --- a/scripts/verify/primitives-types.txt +++ /dev/null @@ -1,27 +0,0 @@ -import { - createMnemonicIdentity, - decodeBase64Url, - signerFromSeed, - type BaseIdentityCapability, - type PublicIdentity, - type SerializedIdentity, -} from "@ternent/identity"; -import { encryptForIdentities, withAgeDecryption, type IdentityCapability } from "@ternent/armour"; - -const { identity } = await createMnemonicIdentity(); -const serialized: SerializedIdentity = identity; -const seed = decodeBase64Url(serialized.material.seed); -if (!seed.ok) throw new Error(seed.error.code); -const base = await signerFromSeed(seed.value); -if (!base.ok) throw new Error(base.error.code); -const signer: BaseIdentityCapability = base.value; -const capable: IdentityCapability = withAgeDecryption(signer); -const publicOnly: PublicIdentity = capable.publicIdentity; -await encryptForIdentities({ identities: [serialized], data: new Uint8Array([1]) }); -// @ts-expect-error A public identity has no private signing operation. -publicOnly.sign(new Uint8Array()); -// @ts-expect-error An identity capability is not an exportable seed document. -const privateExport: SerializedIdentity = capable; -// @ts-expect-error Byte-based authoring does not accept strings. -signer.sign("message"); -void privateExport; diff --git a/scripts/verify/protocol-isolation.txt b/scripts/verify/protocol-isolation.txt deleted file mode 100644 index 47c9ada..0000000 --- a/scripts/verify/protocol-isolation.txt +++ /dev/null @@ -1,10 +0,0 @@ -import { registerHooks } from "node:module"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -registerHooks({resolve(specifier,context,next){ - if(specifier === "@ternent/armour" || specifier.startsWith("age-encryption") || specifier === "@ternent/concord" || specifier.startsWith("@ternent/concord/system") || specifier.startsWith("@ternent/concord/testing"))throw new Error("forbidden protocol dependency"); - return next(specifier,context); -}}); -const {verifyDocument}=await import("@ternent/concord/protocol"); -assert.equal((await verifyDocument(new Uint8Array(readFileSync("owner.document.json")))).integrity,"valid"); -console.log("Protocol imports and verifies with runtime, model and age imports blocked"); diff --git a/scripts/verify/storage-consumer.txt b/scripts/verify/storage-consumer.txt deleted file mode 100644 index a4fd8d7..0000000 --- a/scripts/verify/storage-consumer.txt +++ /dev/null @@ -1,63 +0,0 @@ -import assert from "node:assert/strict"; -import { identityFromSeed } from "@ternent/armour"; -import { createDocument, openDocument } from "@ternent/concord"; -import { createStandardSystemProfile } from "@ternent/concord/system"; -import { registerModel, createMemoryArtifactStore, createMemoryExpectedHeadStore } from "@ternent/concord/testing"; -import { compareSnapshots, verifyDocument } from "@ternent/concord/protocol"; -const value = result => { assert.equal(result.ok,true,result.error?.code);return result.value; }; -const identity = value(await identityFromSeed(new Uint8Array(32).fill(7))); -const create = () => createDocument({model:registerModel,system:createStandardSystemProfile(),identity}); -const open = (bytes,extra={}) => openDocument({bytes,model:registerModel,system:createStandardSystemProfile(),signer:identity,...extra}); -const local = value(await create()); -const base = local.export(); -const baseHead = local.state().head; -const store = createMemoryExpectedHeadStore(); -assert.equal(store.expectedHead,true); -assert.equal(value(await store.read()),null); -value(await store.writeExpected(base,null)); -assert.equal((await store.writeExpected(base,null)).error.code,"HEAD_CONFLICT"); -const left = await open(base), right = await open(base); -value(await left.dispatch("set",{value:"left branch"})); -value(await right.dispatch("set",{value:"right branch"})); -const localSnapshots = [left.export(),right.export()]; -const results = await Promise.all(localSnapshots.map(bytes=>store.writeExpected(bytes,baseHead))); -assert.equal(results.filter(result=>result.ok).length,1); -const loser = results.findIndex(result=>!result.ok); -const conflict = results[loser].error; -assert.equal(conflict.code,"HEAD_CONFLICT"); -assert(conflict.remote instanceof Uint8Array); -assert.equal(value(await compareSnapshots(localSnapshots[loser],conflict.remote)),"diverged"); -assert.deepEqual(value(await store.read()),conflict.remote); -assert.deepEqual((loser === 0 ? left : right).export(),localSnapshots[loser]); -const storedCopy = new Uint8Array(conflict.remote); -conflict.remote.fill(0); -assert.deepEqual(value(await store.read()),storedCopy); -assert.equal((await verifyDocument(localSnapshots[loser])).integrity,"valid"); -const published = await open(value(await store.read())); -assert.equal(published.state().status,"ready"); -const anchored = await open(base,{anchor:storedCopy}); -assert.equal(anchored.state().reason,"freshness"); -assert.equal(anchored.inspect().findings[0].code,"STALE_HEAD"); -assert.equal((await open(base)).state().status,"ready"); - -const draft = await open(storedCopy,{mode:"draft"}); -value(await draft.dispatch("set",{value:"unpublished draft"})); -const pending = draft.draft(); -const committed = draft.export(); -const failedStore = {async write(){return {ok:false,error:{code:"STORAGE_FAILED",phase:"storage",message:"Injected I/O failure"}}}}; -assert.equal((await failedStore.write(draft.export())).error.code,"STORAGE_FAILED"); -assert.deepEqual(draft.export(),committed); -assert.deepEqual(draft.draft(),pending); -const raw = createMemoryArtifactStore(); -value(await raw.write(draft.export())); -const reopened = await open(value(await raw.read()),{mode:"draft"}); -assert.deepEqual(reopened.state(),draft.state()); -assert.equal(reopened.draft(),null); -assert.notEqual(reopened.state().projection.value,"unpublished draft"); -const input = new Uint8Array([1,2,3]); -value(await raw.write(input));input.fill(0); -const read = value(await raw.read());assert.deepEqual(read,new Uint8Array([1,2,3]));read.fill(0); -assert.deepEqual(value(await raw.read()),new Uint8Array([1,2,3])); -assert.equal((await store.writeExpected(new Uint8Array([1]),published.state().head)).error.code,"STORAGE_FAILED"); -assert.deepEqual(value(await store.read()),storedCopy); -console.log(`External storage, atomic expected-head conflicts, retained forks, anchors and draft isolation passed on ${process.version}`); diff --git a/scripts/verify/storage-types.txt b/scripts/verify/storage-types.txt deleted file mode 100644 index 45134e1..0000000 --- a/scripts/verify/storage-types.txt +++ /dev/null @@ -1,27 +0,0 @@ -import { type CommitId } from "@ternent/concord"; -import { createMemoryArtifactStore, createMemoryExpectedHeadStore, type ArtifactStore, type ExpectedHeadArtifactStore, type StorageError } from "@ternent/concord/testing"; -const raw: ArtifactStore = createMemoryArtifactStore(); -const store: ExpectedHeadArtifactStore = createMemoryExpectedHeadStore(); -const head: CommitId = `commit:${"0".repeat(64)}`; -const bytes = new Uint8Array(); -await raw.write(bytes); -await store.writeExpected(bytes,null); -const result = await store.writeExpected(bytes,head); -if (!result.ok) { - const error: StorageError = result.error; - if (error.code === "HEAD_CONFLICT") { - const remote: Uint8Array | null = error.remote; - void remote; - } else { - // @ts-expect-error An I/O failure does not invent remote snapshot evidence. - void error.remote; - } -} -// @ts-expect-error Basic byte stores do not advertise atomic head comparison. -await raw.writeExpected(bytes,head); -// @ts-expect-error Create-only must be explicit null, not an omitted expected head. -await store.writeExpected(bytes); -// @ts-expect-error Text is not an artifact byte buffer. -await raw.write("snapshot"); -// @ts-expect-error The optional capability is readonly and always true on this reference store. -store.expectedHead = false; diff --git a/scripts/verify/types.txt b/scripts/verify/types.txt new file mode 100644 index 0000000..a3735d0 --- /dev/null +++ b/scripts/verify/types.txt @@ -0,0 +1,36 @@ +import { createIdentity, type PublicIdentity } from "@ternent/identity"; +import { createSealHash, createSealProof, type SealProof } from "@ternent/seal"; +import { encrypt } from "@ternent/armour"; +import { createLedger, type History } from "@ternent/ledger"; +import { createDocument, defineModel, type GroupId } from "@ternent/concord"; + +const alice = await createIdentity(); +const publicIdentity: PublicIdentity = alice.publicIdentity; +const proof: SealProof = await createSealProof({ + signer: alice, + subject: { hash: await createSealHash(new Uint8Array()) }, +}); +// @ts-expect-error a subject hash has the sha256: prefix. +await createSealProof({ signer: alice, subject: { hash: "abc" } }); +await encrypt(new Uint8Array(), [publicIdentity, "age1..."]); +// @ts-expect-error Armour takes bytes, not text. +await encrypt("text", [publicIdentity]); +const history: History = await createLedger({ signer: alice }); + +type Counter = { count: number }; +const counter = defineModel({ + id: "counter", + version: 1, + initial: () => ({ count: 0 }), + reduce: (state) => ({ count: state.count + 1 }), +}); +const doc = await createDocument({ model: counter, identity: alice }); +const count: number = doc.state().count; +const group: GroupId = await doc.createGroup(); +doc.stage({ type: "increment", data: null }, { group }); +// @ts-expect-error state keeps the model's type. +const wrong: string = doc.state().count; +// @ts-expect-error roles are member or admin. +await doc.setMember(publicIdentity, { group, role: "owner" }); + +export { count, history, proof, wrong }; From 75fcf34e0dd5843031d3cff2549d608512a9f056 Mon Sep 17 00:00:00 2001 From: samternent Date: Sat, 28 Nov 2026 02:05:13 +0000 Subject: [PATCH 11/24] chore!: remove ui, workspace, docs and everything the five libraries don't need Delete packages/ui and packages/workspace (published versions remain on npm), the docs folder, an unused Vite library config and a tsconfig for a removed app. The browser consumer drops its Vue counter and CSS check, and the consumer check drops probes of the toolchain's own lint, format and test failures. Renovate no longer ignores Ledger, and guides lose their links to the removed docs. Vue stays as a root dependency because Vite+'s type declarations need it. Co-Authored-By: Claude Opus 5.5 --- .changeset/README.md | 5 +- .gitignore | 1 - AGENTS.md | 6 +- CONTRIBUTING.md | 15 +- README.md | 7 +- docs/adr/0001-center-the-alpha-on-concord.md | 12 - ...arate-system-and-application-extensions.md | 12 - ...ind-one-application-model-to-a-document.md | 11 - .../0004-use-one-derived-identity-suite.md | 11 - ...-head-snapshots-and-explicit-divergence.md | 15 - .../0006-sign-canonical-commit-subjects.md | 14 - ...tart-with-one-private-document-audience.md | 19 - ...only-complete-committed-reconstructions.md | 21 - ...ord-crypto-composition-above-primitives.md | 14 - ...ite-plus-with-portable-tooling-profiles.md | 20 - ...verified-artifacts-through-one-workflow.md | 13 - ...y-private-ui-apps-to-cloudflare-workers.md | 14 - docs/adr/0013-pilot-candidate-isolation.md | 29 - ...p-async-profile-reentry-a-host-contract.md | 27 - ...5-keep-audience-memberships-independent.md | 38 - ...0016-route-each-command-to-one-audience.md | 22 - .../0017-drop-ui-from-the-library-release.md | 28 - ...18-use-one-ledger-container-for-concord.md | 39 - ...9-keep-draft-persistence-with-consumers.md | 23 - ...020-simplify-core-around-five-libraries.md | 41 - docs/concord/alpha-architecture.md | 380 --- docs/concord/alpha-protocol.md | 169 -- docs/concord/conformance.md | 208 -- docs/concord/context.md | 142 -- docs/concord/examples/independent-groups.json | 93 - docs/concord/group-profile-design.md | 393 --- docs/concord/implementation-blueprint.md | 605 ----- docs/concord/standard-profile.md | 220 -- docs/concord/storage-boundary.md | 113 - docs/concord/vectors/README.md | 94 - docs/concord/vectors/groups.expected.json | 144 -- .../vectors/groups.readmitted.document.json | 710 ------ .../vectors/groups.removed.document.json | 648 ----- docs/concord/vectors/mutations.json | 195 -- docs/concord/vectors/owner.document.json | 121 - docs/concord/vectors/owner.expected.json | 67 - docs/concord/vectors/owner.fork.document.json | 121 - .../vectors/owner.genesis.document.json | 78 - docs/concord/vectors/primitives.json | 92 - docs/concord/vectors/relationships.json | 30 - docs/engineering/alpha-first-slice.md | 75 - docs/engineering/developer-archetype.md | 108 - .../independent-groups-2026-11-20.md | 81 - docs/engineering/release-and-deployment.md | 326 --- docs/engineering/repository-hygiene.md | 164 -- llms.txt | 4 +- packages/ui/CHANGELOG.md | 399 --- packages/ui/README.md | 57 - packages/ui/jsconfig.json | 19 - packages/ui/package.json | 64 - packages/ui/scripts/check-tokens.js | 56 - packages/ui/scripts/generate-theme-css.mjs | 85 - packages/ui/src/design-system/base.css | 8 - .../design-system/docs/ACCESSIBILITY_RULES.md | 186 -- .../ui/src/design-system/docs/AI_SYSTEM.md | 281 -- .../src/design-system/docs/PATTERN_RULES.md | 83 - .../src/design-system/docs/PRIMITIVE_RULES.md | 258 -- .../ui/src/design-system/docs/TOKEN_RULES.md | 235 -- .../design-system/docs/VISUAL_DIRECTION.md | 68 - packages/ui/src/design-system/foundation.js | 420 --- packages/ui/src/design-system/tokens.css | 140 - packages/ui/src/design-system/tokens.js | 327 --- packages/ui/src/design-system/utils.js | 246 -- packages/ui/src/main.js | 4 - .../patterns/FeatureCard/FeatureCard.spec.md | 24 - .../patterns/FeatureCard/FeatureCard.types.ts | 8 - .../src/patterns/FeatureCard/FeatureCard.vue | 175 -- .../src/patterns/FormField/FormField.spec.md | 65 - .../src/patterns/FormField/FormField.types.ts | 11 - .../ui/src/patterns/FormField/FormField.vue | 87 - .../patterns/IdentityGlyph/IdentityGlyph.vue | 61 - .../patterns/IdentityGlyph/IdentityHandle.vue | 58 - .../IdentityGlyph/identityGlyph.types.ts | 36 - .../IdentityGlyph/identityGlyph.utils.ts | 585 ----- .../ui/src/patterns/IdentityGlyph/index.ts | 5 - .../KeyValueList/KeyValueList.spec.md | 28 - .../KeyValueList/KeyValueList.types.ts | 16 - .../patterns/KeyValueList/KeyValueList.vue | 50 - .../src/patterns/LandingPage/LandingIcon.vue | 90 - .../patterns/LandingPage/LandingPage.spec.md | 24 - .../patterns/LandingPage/LandingPage.types.ts | 212 -- .../src/patterns/LandingPage/LandingPage.vue | 599 ----- .../ListWorkspaceLayout.test.ts | 33 - .../ListWorkspaceLayout.vue | 44 - packages/ui/src/patterns/Logo/Logo.spec.md | 22 - packages/ui/src/patterns/Logo/Logo.vue | 160 -- .../patterns/PageSurface/PageSurface.spec.md | 15 - .../src/patterns/PageSurface/PageSurface.vue | 85 - .../patterns/PanelChrome/PanelChrome.spec.md | 39 - .../patterns/PanelChrome/PanelChrome.types.ts | 1 - .../src/patterns/PanelChrome/PanelChrome.vue | 187 -- .../PreviewPanel/PreviewPanel.spec.md | 31 - .../PreviewPanel/PreviewPanel.types.ts | 23 - .../patterns/PreviewPanel/PreviewPanel.vue | 354 --- .../patterns/RecordList/RecordList.spec.md | 35 - .../patterns/RecordList/RecordList.test.ts | 42 - .../patterns/RecordList/RecordList.types.ts | 9 - .../patterns/RecordList/RecordList.utils.ts | 5 - .../ui/src/patterns/RecordList/RecordList.vue | 134 - .../SectionClarifier/SectionClarifier.vue | 85 - .../SectionIntro/SectionIntro.spec.md | 25 - .../SectionIntro/SectionIntro.types.ts | 7 - .../patterns/SectionIntro/SectionIntro.vue | 141 -- .../patterns/SidebarNav/SidebarNav.spec.md | 34 - .../patterns/SidebarNav/SidebarNav.types.ts | 17 - .../ui/src/patterns/SidebarNav/SidebarNav.vue | 110 - .../src/patterns/SplitView/SplitView.spec.md | 28 - .../src/patterns/SplitView/SplitView.test.ts | 22 - .../src/patterns/SplitView/SplitView.types.ts | 3 - .../src/patterns/SplitView/SplitView.utils.ts | 13 - .../ui/src/patterns/SplitView/SplitView.vue | 39 - .../ui/src/patterns/StepList/StepList.spec.md | 15 - .../src/patterns/StepList/StepList.types.ts | 4 - .../ui/src/patterns/StepList/StepList.vue | 91 - .../Verification/VerificationBadge.vue | 97 - .../VerificationComponents.test.ts | 153 -- .../Verification/VerificationDetailsPanel.vue | 270 -- .../Verification/VerificationSummary.vue | 171 -- .../ui/src/patterns/Verification/index.ts | 6 - .../Verification/verification.types.ts | 8 - .../Verification/verification.utils.test.ts | 37 - .../Verification/verification.utils.ts | 75 - packages/ui/src/patterns/index.ts | 25 - .../ui/src/primitives/Accordian/Accordian.vue | 11 - .../primitives/Accordian/AccordianItem.vue | 14 - .../primitives/Accordion/Accordion.props.ts | 21 - .../primitives/Accordion/Accordion.spec.md | 50 - .../primitives/Accordion/Accordion.types.ts | 4 - .../Accordion/Accordion.variants.ts | 12 - .../ui/src/primitives/Accordion/Accordion.vue | 71 - .../Accordion/AccordionItem.props.ts | 14 - .../primitives/Accordion/AccordionItem.vue | 40 - .../ui/src/primitives/Badge/Badge.props.ts | 17 - .../ui/src/primitives/Badge/Badge.spec.md | 17 - .../ui/src/primitives/Badge/Badge.types.ts | 15 - .../ui/src/primitives/Badge/Badge.variants.ts | 48 - packages/ui/src/primitives/Badge/Badge.vue | 31 - .../ui/src/primitives/Button/Button.props.ts | 29 - .../ui/src/primitives/Button/Button.spec.md | 139 - .../ui/src/primitives/Button/Button.types.ts | 19 - .../src/primitives/Button/Button.variants.ts | 72 - packages/ui/src/primitives/Button/Button.vue | 90 - packages/ui/src/primitives/Card/Card.props.ts | 17 - packages/ui/src/primitives/Card/Card.spec.md | 29 - packages/ui/src/primitives/Card/Card.types.ts | 12 - .../ui/src/primitives/Card/Card.variants.ts | 27 - packages/ui/src/primitives/Card/Card.vue | 37 - .../src/primitives/Checkbox/Checkbox.props.ts | 21 - .../src/primitives/Checkbox/Checkbox.spec.md | 51 - .../src/primitives/Checkbox/Checkbox.types.ts | 4 - .../primitives/Checkbox/Checkbox.variants.ts | 34 - .../ui/src/primitives/Checkbox/Checkbox.vue | 92 - .../ui/src/primitives/Dialog/Dialog.props.ts | 29 - .../ui/src/primitives/Dialog/Dialog.spec.md | 52 - .../ui/src/primitives/Dialog/Dialog.types.ts | 3 - .../src/primitives/Dialog/Dialog.variants.ts | 27 - packages/ui/src/primitives/Dialog/Dialog.vue | 78 - .../ui/src/primitives/Drawer/Drawer.props.ts | 33 - .../ui/src/primitives/Drawer/Drawer.spec.md | 50 - .../ui/src/primitives/Drawer/Drawer.types.ts | 5 - .../src/primitives/Drawer/Drawer.variants.ts | 35 - packages/ui/src/primitives/Drawer/Drawer.vue | 88 - .../FieldMessage/FieldMessage.props.ts | 17 - .../FieldMessage/FieldMessage.spec.md | 35 - .../FieldMessage/FieldMessage.types.ts | 5 - .../FieldMessage/FieldMessage.variants.ts | 14 - .../primitives/FieldMessage/FieldMessage.vue | 40 - .../primitives/FileInput/FileInput.props.ts | 41 - .../primitives/FileInput/FileInput.types.ts | 6 - .../FileInput/FileInput.variants.ts | 46 - .../ui/src/primitives/FileInput/FileInput.vue | 163 -- .../ui/src/primitives/Input/Input.props.ts | 29 - .../ui/src/primitives/Input/Input.spec.md | 79 - .../ui/src/primitives/Input/Input.types.ts | 13 - .../ui/src/primitives/Input/Input.variants.ts | 54 - packages/ui/src/primitives/Input/Input.vue | 99 - .../ui/src/primitives/Label/Label.props.ts | 25 - .../ui/src/primitives/Label/Label.spec.md | 31 - .../ui/src/primitives/Label/Label.types.ts | 3 - .../ui/src/primitives/Label/Label.variants.ts | 17 - packages/ui/src/primitives/Label/Label.vue | 38 - packages/ui/src/primitives/Menu/Menu.props.ts | 17 - packages/ui/src/primitives/Menu/Menu.spec.md | 38 - packages/ui/src/primitives/Menu/Menu.types.ts | 10 - .../ui/src/primitives/Menu/Menu.variants.ts | 10 - packages/ui/src/primitives/Menu/Menu.vue | 57 - .../src/primitives/Popover/Popover.props.ts | 25 - .../ui/src/primitives/Popover/Popover.spec.md | 49 - .../src/primitives/Popover/Popover.types.ts | 3 - .../primitives/Popover/Popover.variants.ts | 18 - .../ui/src/primitives/Popover/Popover.vue | 74 - .../primitives/RadioGroup/RadioGroup.props.ts | 29 - .../primitives/RadioGroup/RadioGroup.spec.md | 50 - .../primitives/RadioGroup/RadioGroup.types.ts | 12 - .../RadioGroup/RadioGroup.variants.ts | 48 - .../src/primitives/RadioGroup/RadioGroup.vue | 87 - .../primitives/Separator/Separator.props.ts | 9 - .../primitives/Separator/Separator.spec.md | 15 - .../primitives/Separator/Separator.types.ts | 3 - .../Separator/Separator.variants.ts | 8 - .../ui/src/primitives/Separator/Separator.vue | 23 - .../src/primitives/Skeleton/Skeleton.props.ts | 21 - .../src/primitives/Skeleton/Skeleton.spec.md | 18 - .../src/primitives/Skeleton/Skeleton.types.ts | 5 - .../primitives/Skeleton/Skeleton.variants.ts | 18 - .../ui/src/primitives/Skeleton/Skeleton.vue | 37 - .../src/primitives/Spinner/Spinner.props.ts | 13 - .../ui/src/primitives/Spinner/Spinner.spec.md | 16 - .../src/primitives/Spinner/Spinner.types.ts | 5 - .../primitives/Spinner/Spinner.variants.ts | 15 - .../ui/src/primitives/Spinner/Spinner.vue | 33 - .../primitives/SplitButton/SplitButton.vue | 108 - .../ui/src/primitives/Switch/Switch.props.ts | 21 - .../ui/src/primitives/Switch/Switch.spec.md | 49 - .../ui/src/primitives/Switch/Switch.types.ts | 3 - .../src/primitives/Switch/Switch.variants.ts | 34 - packages/ui/src/primitives/Switch/Switch.vue | 71 - packages/ui/src/primitives/Tabs/Tabs.props.ts | 25 - packages/ui/src/primitives/Tabs/Tabs.spec.md | 48 - packages/ui/src/primitives/Tabs/Tabs.types.ts | 11 - .../ui/src/primitives/Tabs/Tabs.variants.ts | 28 - packages/ui/src/primitives/Tabs/Tabs.vue | 59 - .../src/primitives/Textarea/Textarea.props.ts | 33 - .../src/primitives/Textarea/Textarea.spec.md | 59 - .../src/primitives/Textarea/Textarea.types.ts | 5 - .../primitives/Textarea/Textarea.variants.ts | 27 - .../ui/src/primitives/Textarea/Textarea.vue | 74 - .../src/primitives/Tooltip/Tooltip.props.ts | 21 - .../ui/src/primitives/Tooltip/Tooltip.spec.md | 45 - .../src/primitives/Tooltip/Tooltip.types.ts | 3 - .../primitives/Tooltip/Tooltip.variants.ts | 4 - .../ui/src/primitives/Tooltip/Tooltip.vue | 31 - .../src/primitives/TreeView/TreeView.types.ts | 10 - .../ui/src/primitives/TreeView/TreeView.vue | 113 - .../src/primitives/TreeView/TreeViewNode.vue | 190 -- packages/ui/src/primitives/index.ts | 29 - packages/ui/src/style.css | 7 - packages/ui/src/style.js | 1 - packages/ui/src/themes/armour.css | 147 -- packages/ui/src/themes/aurora.css | 147 -- packages/ui/src/themes/citrine-ash.css | 147 -- packages/ui/src/themes/concord.css | 147 -- packages/ui/src/themes/garnet-honey.css | 147 -- packages/ui/src/themes/harbor-rose.css | 147 -- packages/ui/src/themes/ledger.css | 147 -- packages/ui/src/themes/neon-noir.css | 74 - packages/ui/src/themes/obsidian-iris.css | 147 -- packages/ui/src/themes/pixpax.css | 147 -- packages/ui/src/themes/print.css | 147 -- packages/ui/src/themes/prism.css | 147 -- packages/ui/src/themes/proof.css | 145 -- .../ui/src/themes/semanticThemeContract.js | 2256 ----------------- packages/ui/src/themes/spruce-ink.css | 147 -- packages/ui/src/themes/sunset.css | 147 -- packages/ui/tailwind.config.js | 64 - packages/ui/vite.config.js | 35 - ....timestamp-1780697224943-89fbc929987bc.mjs | 38 - ....timestamp-1783937650184-1d7fa2b0d1bb4.mjs | 38 - packages/workspace/CHANGELOG.md | 33 - packages/workspace/README.md | 38 - packages/workspace/llms.txt | 19 - packages/workspace/package.json | 46 - packages/workspace/src/index.ts | 21 - packages/workspace/src/plugins/identityKey.ts | 213 -- packages/workspace/src/plugins/index.ts | 12 - packages/workspace/src/plugins/permissions.ts | 1208 --------- .../workspace/src/plugins/replayContext.ts | 69 - packages/workspace/src/plugins/users.ts | 181 -- .../workspace/src/runtime/contracts/apps.ts | 12 - .../src/runtime/contracts/identity.ts | 8 - .../workspace/src/runtime/contracts/index.ts | 6 - .../src/runtime/contracts/privacy.ts | 18 - .../workspace/src/runtime/contracts/replay.ts | 26 - .../src/runtime/contracts/runtime.ts | 6 - .../src/runtime/contracts/storage.ts | 99 - packages/workspace/src/runtime/createApp.ts | 870 ------- packages/workspace/src/runtime/identity.ts | 653 ----- packages/workspace/src/runtime/index.ts | 9 - packages/workspace/src/runtime/privacy.ts | 225 -- packages/workspace/src/runtime/qr.ts | 835 ------ packages/workspace/src/runtime/storage.ts | 111 - .../src/runtime/storageProviders/helpers.ts | 95 - .../runtime/storageProviders/httpProvider.ts | 331 --- .../src/runtime/storageProviders/index.ts | 4 - .../runtime/storageProviders/localProvider.ts | 64 - .../src/runtime/storageProviders/registry.ts | 74 - packages/workspace/src/runtime/totp.ts | 164 -- packages/workspace/src/runtime/types.ts | 77 - .../src/runtimeCore/createRuntimeCore.ts | 354 --- packages/workspace/src/runtimeCore/helpers.ts | 122 - packages/workspace/src/runtimeCore/index.ts | 2 - .../src/runtimeCore/sections/identity.ts | 99 - .../src/runtimeCore/sections/permissions.ts | 160 -- .../src/runtimeCore/sections/shared.ts | 19 - .../src/runtimeCore/sections/users.ts | 27 - packages/workspace/src/runtimeCore/types.ts | 161 -- packages/workspace/src/workspaceLifecycle.ts | 87 - packages/workspace/test/public-api.test.ts | 25 - packages/workspace/test/runtime-core.test.ts | 504 ---- packages/workspace/tsconfig.build.json | 12 - packages/workspace/tsconfig.json | 12 - packages/workspace/vite.config.ts | 24 - renovate.json | 10 +- scripts/verify/browser-main.txt | 19 - scripts/verify/consumers.mjs | 72 +- scripts/verify/contract.mjs | 1 - scripts/verify/scope.mjs | 1 - scripts/vite/package-lib-config.ts | 59 - tsconfig.node.json | 9 - 314 files changed, 17 insertions(+), 29521 deletions(-) delete mode 100644 docs/adr/0001-center-the-alpha-on-concord.md delete mode 100644 docs/adr/0002-separate-system-and-application-extensions.md delete mode 100644 docs/adr/0003-bind-one-application-model-to-a-document.md delete mode 100644 docs/adr/0004-use-one-derived-identity-suite.md delete mode 100644 docs/adr/0005-use-single-head-snapshots-and-explicit-divergence.md delete mode 100644 docs/adr/0006-sign-canonical-commit-subjects.md delete mode 100644 docs/adr/0007-start-with-one-private-document-audience.md delete mode 100644 docs/adr/0008-publish-only-complete-committed-reconstructions.md delete mode 100644 docs/adr/0009-keep-concord-crypto-composition-above-primitives.md delete mode 100644 docs/adr/0010-use-vite-plus-with-portable-tooling-profiles.md delete mode 100644 docs/adr/0011-publish-verified-artifacts-through-one-workflow.md delete mode 100644 docs/adr/0012-deploy-private-ui-apps-to-cloudflare-workers.md delete mode 100644 docs/adr/0013-pilot-candidate-isolation.md delete mode 100644 docs/adr/0014-keep-async-profile-reentry-a-host-contract.md delete mode 100644 docs/adr/0015-keep-audience-memberships-independent.md delete mode 100644 docs/adr/0016-route-each-command-to-one-audience.md delete mode 100644 docs/adr/0017-drop-ui-from-the-library-release.md delete mode 100644 docs/adr/0018-use-one-ledger-container-for-concord.md delete mode 100644 docs/adr/0019-keep-draft-persistence-with-consumers.md delete mode 100644 docs/adr/0020-simplify-core-around-five-libraries.md delete mode 100644 docs/concord/alpha-architecture.md delete mode 100644 docs/concord/alpha-protocol.md delete mode 100644 docs/concord/conformance.md delete mode 100644 docs/concord/context.md delete mode 100644 docs/concord/examples/independent-groups.json delete mode 100644 docs/concord/group-profile-design.md delete mode 100644 docs/concord/implementation-blueprint.md delete mode 100644 docs/concord/standard-profile.md delete mode 100644 docs/concord/storage-boundary.md delete mode 100644 docs/concord/vectors/README.md delete mode 100644 docs/concord/vectors/groups.expected.json delete mode 100644 docs/concord/vectors/groups.readmitted.document.json delete mode 100644 docs/concord/vectors/groups.removed.document.json delete mode 100644 docs/concord/vectors/mutations.json delete mode 100644 docs/concord/vectors/owner.document.json delete mode 100644 docs/concord/vectors/owner.expected.json delete mode 100644 docs/concord/vectors/owner.fork.document.json delete mode 100644 docs/concord/vectors/owner.genesis.document.json delete mode 100644 docs/concord/vectors/primitives.json delete mode 100644 docs/concord/vectors/relationships.json delete mode 100644 docs/engineering/alpha-first-slice.md delete mode 100644 docs/engineering/developer-archetype.md delete mode 100644 docs/engineering/independent-groups-2026-11-20.md delete mode 100644 docs/engineering/release-and-deployment.md delete mode 100644 docs/engineering/repository-hygiene.md delete mode 100644 packages/ui/CHANGELOG.md delete mode 100644 packages/ui/README.md delete mode 100644 packages/ui/jsconfig.json delete mode 100644 packages/ui/package.json delete mode 100644 packages/ui/scripts/check-tokens.js delete mode 100644 packages/ui/scripts/generate-theme-css.mjs delete mode 100644 packages/ui/src/design-system/base.css delete mode 100644 packages/ui/src/design-system/docs/ACCESSIBILITY_RULES.md delete mode 100644 packages/ui/src/design-system/docs/AI_SYSTEM.md delete mode 100644 packages/ui/src/design-system/docs/PATTERN_RULES.md delete mode 100644 packages/ui/src/design-system/docs/PRIMITIVE_RULES.md delete mode 100644 packages/ui/src/design-system/docs/TOKEN_RULES.md delete mode 100644 packages/ui/src/design-system/docs/VISUAL_DIRECTION.md delete mode 100644 packages/ui/src/design-system/foundation.js delete mode 100644 packages/ui/src/design-system/tokens.css delete mode 100644 packages/ui/src/design-system/tokens.js delete mode 100644 packages/ui/src/design-system/utils.js delete mode 100644 packages/ui/src/main.js delete mode 100644 packages/ui/src/patterns/FeatureCard/FeatureCard.spec.md delete mode 100644 packages/ui/src/patterns/FeatureCard/FeatureCard.types.ts delete mode 100644 packages/ui/src/patterns/FeatureCard/FeatureCard.vue delete mode 100644 packages/ui/src/patterns/FormField/FormField.spec.md delete mode 100644 packages/ui/src/patterns/FormField/FormField.types.ts delete mode 100644 packages/ui/src/patterns/FormField/FormField.vue delete mode 100644 packages/ui/src/patterns/IdentityGlyph/IdentityGlyph.vue delete mode 100644 packages/ui/src/patterns/IdentityGlyph/IdentityHandle.vue delete mode 100644 packages/ui/src/patterns/IdentityGlyph/identityGlyph.types.ts delete mode 100644 packages/ui/src/patterns/IdentityGlyph/identityGlyph.utils.ts delete mode 100644 packages/ui/src/patterns/IdentityGlyph/index.ts delete mode 100644 packages/ui/src/patterns/KeyValueList/KeyValueList.spec.md delete mode 100644 packages/ui/src/patterns/KeyValueList/KeyValueList.types.ts delete mode 100644 packages/ui/src/patterns/KeyValueList/KeyValueList.vue delete mode 100644 packages/ui/src/patterns/LandingPage/LandingIcon.vue delete mode 100644 packages/ui/src/patterns/LandingPage/LandingPage.spec.md delete mode 100644 packages/ui/src/patterns/LandingPage/LandingPage.types.ts delete mode 100644 packages/ui/src/patterns/LandingPage/LandingPage.vue delete mode 100644 packages/ui/src/patterns/ListWorkspaceLayout/ListWorkspaceLayout.test.ts delete mode 100644 packages/ui/src/patterns/ListWorkspaceLayout/ListWorkspaceLayout.vue delete mode 100644 packages/ui/src/patterns/Logo/Logo.spec.md delete mode 100644 packages/ui/src/patterns/Logo/Logo.vue delete mode 100644 packages/ui/src/patterns/PageSurface/PageSurface.spec.md delete mode 100644 packages/ui/src/patterns/PageSurface/PageSurface.vue delete mode 100644 packages/ui/src/patterns/PanelChrome/PanelChrome.spec.md delete mode 100644 packages/ui/src/patterns/PanelChrome/PanelChrome.types.ts delete mode 100644 packages/ui/src/patterns/PanelChrome/PanelChrome.vue delete mode 100644 packages/ui/src/patterns/PreviewPanel/PreviewPanel.spec.md delete mode 100644 packages/ui/src/patterns/PreviewPanel/PreviewPanel.types.ts delete mode 100644 packages/ui/src/patterns/PreviewPanel/PreviewPanel.vue delete mode 100644 packages/ui/src/patterns/RecordList/RecordList.spec.md delete mode 100644 packages/ui/src/patterns/RecordList/RecordList.test.ts delete mode 100644 packages/ui/src/patterns/RecordList/RecordList.types.ts delete mode 100644 packages/ui/src/patterns/RecordList/RecordList.utils.ts delete mode 100644 packages/ui/src/patterns/RecordList/RecordList.vue delete mode 100644 packages/ui/src/patterns/SectionClarifier/SectionClarifier.vue delete mode 100644 packages/ui/src/patterns/SectionIntro/SectionIntro.spec.md delete mode 100644 packages/ui/src/patterns/SectionIntro/SectionIntro.types.ts delete mode 100644 packages/ui/src/patterns/SectionIntro/SectionIntro.vue delete mode 100644 packages/ui/src/patterns/SidebarNav/SidebarNav.spec.md delete mode 100644 packages/ui/src/patterns/SidebarNav/SidebarNav.types.ts delete mode 100644 packages/ui/src/patterns/SidebarNav/SidebarNav.vue delete mode 100644 packages/ui/src/patterns/SplitView/SplitView.spec.md delete mode 100644 packages/ui/src/patterns/SplitView/SplitView.test.ts delete mode 100644 packages/ui/src/patterns/SplitView/SplitView.types.ts delete mode 100644 packages/ui/src/patterns/SplitView/SplitView.utils.ts delete mode 100644 packages/ui/src/patterns/SplitView/SplitView.vue delete mode 100644 packages/ui/src/patterns/StepList/StepList.spec.md delete mode 100644 packages/ui/src/patterns/StepList/StepList.types.ts delete mode 100644 packages/ui/src/patterns/StepList/StepList.vue delete mode 100644 packages/ui/src/patterns/Verification/VerificationBadge.vue delete mode 100644 packages/ui/src/patterns/Verification/VerificationComponents.test.ts delete mode 100644 packages/ui/src/patterns/Verification/VerificationDetailsPanel.vue delete mode 100644 packages/ui/src/patterns/Verification/VerificationSummary.vue delete mode 100644 packages/ui/src/patterns/Verification/index.ts delete mode 100644 packages/ui/src/patterns/Verification/verification.types.ts delete mode 100644 packages/ui/src/patterns/Verification/verification.utils.test.ts delete mode 100644 packages/ui/src/patterns/Verification/verification.utils.ts delete mode 100644 packages/ui/src/patterns/index.ts delete mode 100644 packages/ui/src/primitives/Accordian/Accordian.vue delete mode 100644 packages/ui/src/primitives/Accordian/AccordianItem.vue delete mode 100644 packages/ui/src/primitives/Accordion/Accordion.props.ts delete mode 100644 packages/ui/src/primitives/Accordion/Accordion.spec.md delete mode 100644 packages/ui/src/primitives/Accordion/Accordion.types.ts delete mode 100644 packages/ui/src/primitives/Accordion/Accordion.variants.ts delete mode 100644 packages/ui/src/primitives/Accordion/Accordion.vue delete mode 100644 packages/ui/src/primitives/Accordion/AccordionItem.props.ts delete mode 100644 packages/ui/src/primitives/Accordion/AccordionItem.vue delete mode 100644 packages/ui/src/primitives/Badge/Badge.props.ts delete mode 100644 packages/ui/src/primitives/Badge/Badge.spec.md delete mode 100644 packages/ui/src/primitives/Badge/Badge.types.ts delete mode 100644 packages/ui/src/primitives/Badge/Badge.variants.ts delete mode 100644 packages/ui/src/primitives/Badge/Badge.vue delete mode 100644 packages/ui/src/primitives/Button/Button.props.ts delete mode 100644 packages/ui/src/primitives/Button/Button.spec.md delete mode 100644 packages/ui/src/primitives/Button/Button.types.ts delete mode 100644 packages/ui/src/primitives/Button/Button.variants.ts delete mode 100644 packages/ui/src/primitives/Button/Button.vue delete mode 100644 packages/ui/src/primitives/Card/Card.props.ts delete mode 100644 packages/ui/src/primitives/Card/Card.spec.md delete mode 100644 packages/ui/src/primitives/Card/Card.types.ts delete mode 100644 packages/ui/src/primitives/Card/Card.variants.ts delete mode 100644 packages/ui/src/primitives/Card/Card.vue delete mode 100644 packages/ui/src/primitives/Checkbox/Checkbox.props.ts delete mode 100644 packages/ui/src/primitives/Checkbox/Checkbox.spec.md delete mode 100644 packages/ui/src/primitives/Checkbox/Checkbox.types.ts delete mode 100644 packages/ui/src/primitives/Checkbox/Checkbox.variants.ts delete mode 100644 packages/ui/src/primitives/Checkbox/Checkbox.vue delete mode 100644 packages/ui/src/primitives/Dialog/Dialog.props.ts delete mode 100644 packages/ui/src/primitives/Dialog/Dialog.spec.md delete mode 100644 packages/ui/src/primitives/Dialog/Dialog.types.ts delete mode 100644 packages/ui/src/primitives/Dialog/Dialog.variants.ts delete mode 100644 packages/ui/src/primitives/Dialog/Dialog.vue delete mode 100644 packages/ui/src/primitives/Drawer/Drawer.props.ts delete mode 100644 packages/ui/src/primitives/Drawer/Drawer.spec.md delete mode 100644 packages/ui/src/primitives/Drawer/Drawer.types.ts delete mode 100644 packages/ui/src/primitives/Drawer/Drawer.variants.ts delete mode 100644 packages/ui/src/primitives/Drawer/Drawer.vue delete mode 100644 packages/ui/src/primitives/FieldMessage/FieldMessage.props.ts delete mode 100644 packages/ui/src/primitives/FieldMessage/FieldMessage.spec.md delete mode 100644 packages/ui/src/primitives/FieldMessage/FieldMessage.types.ts delete mode 100644 packages/ui/src/primitives/FieldMessage/FieldMessage.variants.ts delete mode 100644 packages/ui/src/primitives/FieldMessage/FieldMessage.vue delete mode 100644 packages/ui/src/primitives/FileInput/FileInput.props.ts delete mode 100644 packages/ui/src/primitives/FileInput/FileInput.types.ts delete mode 100644 packages/ui/src/primitives/FileInput/FileInput.variants.ts delete mode 100644 packages/ui/src/primitives/FileInput/FileInput.vue delete mode 100644 packages/ui/src/primitives/Input/Input.props.ts delete mode 100644 packages/ui/src/primitives/Input/Input.spec.md delete mode 100644 packages/ui/src/primitives/Input/Input.types.ts delete mode 100644 packages/ui/src/primitives/Input/Input.variants.ts delete mode 100644 packages/ui/src/primitives/Input/Input.vue delete mode 100644 packages/ui/src/primitives/Label/Label.props.ts delete mode 100644 packages/ui/src/primitives/Label/Label.spec.md delete mode 100644 packages/ui/src/primitives/Label/Label.types.ts delete mode 100644 packages/ui/src/primitives/Label/Label.variants.ts delete mode 100644 packages/ui/src/primitives/Label/Label.vue delete mode 100644 packages/ui/src/primitives/Menu/Menu.props.ts delete mode 100644 packages/ui/src/primitives/Menu/Menu.spec.md delete mode 100644 packages/ui/src/primitives/Menu/Menu.types.ts delete mode 100644 packages/ui/src/primitives/Menu/Menu.variants.ts delete mode 100644 packages/ui/src/primitives/Menu/Menu.vue delete mode 100644 packages/ui/src/primitives/Popover/Popover.props.ts delete mode 100644 packages/ui/src/primitives/Popover/Popover.spec.md delete mode 100644 packages/ui/src/primitives/Popover/Popover.types.ts delete mode 100644 packages/ui/src/primitives/Popover/Popover.variants.ts delete mode 100644 packages/ui/src/primitives/Popover/Popover.vue delete mode 100644 packages/ui/src/primitives/RadioGroup/RadioGroup.props.ts delete mode 100644 packages/ui/src/primitives/RadioGroup/RadioGroup.spec.md delete mode 100644 packages/ui/src/primitives/RadioGroup/RadioGroup.types.ts delete mode 100644 packages/ui/src/primitives/RadioGroup/RadioGroup.variants.ts delete mode 100644 packages/ui/src/primitives/RadioGroup/RadioGroup.vue delete mode 100644 packages/ui/src/primitives/Separator/Separator.props.ts delete mode 100644 packages/ui/src/primitives/Separator/Separator.spec.md delete mode 100644 packages/ui/src/primitives/Separator/Separator.types.ts delete mode 100644 packages/ui/src/primitives/Separator/Separator.variants.ts delete mode 100644 packages/ui/src/primitives/Separator/Separator.vue delete mode 100644 packages/ui/src/primitives/Skeleton/Skeleton.props.ts delete mode 100644 packages/ui/src/primitives/Skeleton/Skeleton.spec.md delete mode 100644 packages/ui/src/primitives/Skeleton/Skeleton.types.ts delete mode 100644 packages/ui/src/primitives/Skeleton/Skeleton.variants.ts delete mode 100644 packages/ui/src/primitives/Skeleton/Skeleton.vue delete mode 100644 packages/ui/src/primitives/Spinner/Spinner.props.ts delete mode 100644 packages/ui/src/primitives/Spinner/Spinner.spec.md delete mode 100644 packages/ui/src/primitives/Spinner/Spinner.types.ts delete mode 100644 packages/ui/src/primitives/Spinner/Spinner.variants.ts delete mode 100644 packages/ui/src/primitives/Spinner/Spinner.vue delete mode 100644 packages/ui/src/primitives/SplitButton/SplitButton.vue delete mode 100644 packages/ui/src/primitives/Switch/Switch.props.ts delete mode 100644 packages/ui/src/primitives/Switch/Switch.spec.md delete mode 100644 packages/ui/src/primitives/Switch/Switch.types.ts delete mode 100644 packages/ui/src/primitives/Switch/Switch.variants.ts delete mode 100644 packages/ui/src/primitives/Switch/Switch.vue delete mode 100644 packages/ui/src/primitives/Tabs/Tabs.props.ts delete mode 100644 packages/ui/src/primitives/Tabs/Tabs.spec.md delete mode 100644 packages/ui/src/primitives/Tabs/Tabs.types.ts delete mode 100644 packages/ui/src/primitives/Tabs/Tabs.variants.ts delete mode 100644 packages/ui/src/primitives/Tabs/Tabs.vue delete mode 100644 packages/ui/src/primitives/Textarea/Textarea.props.ts delete mode 100644 packages/ui/src/primitives/Textarea/Textarea.spec.md delete mode 100644 packages/ui/src/primitives/Textarea/Textarea.types.ts delete mode 100644 packages/ui/src/primitives/Textarea/Textarea.variants.ts delete mode 100644 packages/ui/src/primitives/Textarea/Textarea.vue delete mode 100644 packages/ui/src/primitives/Tooltip/Tooltip.props.ts delete mode 100644 packages/ui/src/primitives/Tooltip/Tooltip.spec.md delete mode 100644 packages/ui/src/primitives/Tooltip/Tooltip.types.ts delete mode 100644 packages/ui/src/primitives/Tooltip/Tooltip.variants.ts delete mode 100644 packages/ui/src/primitives/Tooltip/Tooltip.vue delete mode 100644 packages/ui/src/primitives/TreeView/TreeView.types.ts delete mode 100644 packages/ui/src/primitives/TreeView/TreeView.vue delete mode 100644 packages/ui/src/primitives/TreeView/TreeViewNode.vue delete mode 100644 packages/ui/src/primitives/index.ts delete mode 100644 packages/ui/src/style.css delete mode 100644 packages/ui/src/style.js delete mode 100644 packages/ui/src/themes/armour.css delete mode 100644 packages/ui/src/themes/aurora.css delete mode 100644 packages/ui/src/themes/citrine-ash.css delete mode 100644 packages/ui/src/themes/concord.css delete mode 100644 packages/ui/src/themes/garnet-honey.css delete mode 100644 packages/ui/src/themes/harbor-rose.css delete mode 100644 packages/ui/src/themes/ledger.css delete mode 100644 packages/ui/src/themes/neon-noir.css delete mode 100644 packages/ui/src/themes/obsidian-iris.css delete mode 100644 packages/ui/src/themes/pixpax.css delete mode 100644 packages/ui/src/themes/print.css delete mode 100644 packages/ui/src/themes/prism.css delete mode 100644 packages/ui/src/themes/proof.css delete mode 100644 packages/ui/src/themes/semanticThemeContract.js delete mode 100644 packages/ui/src/themes/spruce-ink.css delete mode 100644 packages/ui/src/themes/sunset.css delete mode 100644 packages/ui/tailwind.config.js delete mode 100644 packages/ui/vite.config.js delete mode 100644 packages/ui/vite.config.js.timestamp-1780697224943-89fbc929987bc.mjs delete mode 100644 packages/ui/vite.config.js.timestamp-1783937650184-1d7fa2b0d1bb4.mjs delete mode 100644 packages/workspace/CHANGELOG.md delete mode 100644 packages/workspace/README.md delete mode 100644 packages/workspace/llms.txt delete mode 100644 packages/workspace/package.json delete mode 100644 packages/workspace/src/index.ts delete mode 100644 packages/workspace/src/plugins/identityKey.ts delete mode 100644 packages/workspace/src/plugins/index.ts delete mode 100644 packages/workspace/src/plugins/permissions.ts delete mode 100644 packages/workspace/src/plugins/replayContext.ts delete mode 100644 packages/workspace/src/plugins/users.ts delete mode 100644 packages/workspace/src/runtime/contracts/apps.ts delete mode 100644 packages/workspace/src/runtime/contracts/identity.ts delete mode 100644 packages/workspace/src/runtime/contracts/index.ts delete mode 100644 packages/workspace/src/runtime/contracts/privacy.ts delete mode 100644 packages/workspace/src/runtime/contracts/replay.ts delete mode 100644 packages/workspace/src/runtime/contracts/runtime.ts delete mode 100644 packages/workspace/src/runtime/contracts/storage.ts delete mode 100644 packages/workspace/src/runtime/createApp.ts delete mode 100644 packages/workspace/src/runtime/identity.ts delete mode 100644 packages/workspace/src/runtime/index.ts delete mode 100644 packages/workspace/src/runtime/privacy.ts delete mode 100644 packages/workspace/src/runtime/qr.ts delete mode 100644 packages/workspace/src/runtime/storage.ts delete mode 100644 packages/workspace/src/runtime/storageProviders/helpers.ts delete mode 100644 packages/workspace/src/runtime/storageProviders/httpProvider.ts delete mode 100644 packages/workspace/src/runtime/storageProviders/index.ts delete mode 100644 packages/workspace/src/runtime/storageProviders/localProvider.ts delete mode 100644 packages/workspace/src/runtime/storageProviders/registry.ts delete mode 100644 packages/workspace/src/runtime/totp.ts delete mode 100644 packages/workspace/src/runtime/types.ts delete mode 100644 packages/workspace/src/runtimeCore/createRuntimeCore.ts delete mode 100644 packages/workspace/src/runtimeCore/helpers.ts delete mode 100644 packages/workspace/src/runtimeCore/index.ts delete mode 100644 packages/workspace/src/runtimeCore/sections/identity.ts delete mode 100644 packages/workspace/src/runtimeCore/sections/permissions.ts delete mode 100644 packages/workspace/src/runtimeCore/sections/shared.ts delete mode 100644 packages/workspace/src/runtimeCore/sections/users.ts delete mode 100644 packages/workspace/src/runtimeCore/types.ts delete mode 100644 packages/workspace/src/workspaceLifecycle.ts delete mode 100644 packages/workspace/test/public-api.test.ts delete mode 100644 packages/workspace/test/runtime-core.test.ts delete mode 100644 packages/workspace/tsconfig.build.json delete mode 100644 packages/workspace/tsconfig.json delete mode 100644 packages/workspace/vite.config.ts delete mode 100644 scripts/vite/package-lib-config.ts delete mode 100644 tsconfig.node.json diff --git a/.changeset/README.md b/.changeset/README.md index 25b94b1..c3c1fdd 100644 --- a/.changeset/README.md +++ b/.changeset/README.md @@ -1,7 +1,7 @@ # Library version intent -Use `pnpm exec changeset add` for changes to the five public libraries. UI and -Workspace are outside this release; private packages are not versioned or tagged. +Use `pnpm exec changeset add` for changes to the five public libraries. Private +packages are not versioned or tagged. The enabled version workflow opens a draft PR for unconsumed public changesets or an exit from prerelease mode. `pnpm release:version` checks npm history, validates @@ -19,4 +19,3 @@ described in the release contract. The release planner requires matching committed intent for new package versions. It freezes the existing tested tarballs, and the publisher never repacks them. -See the [release contract](../docs/engineering/release-and-deployment.md). diff --git a/.gitignore b/.gitignore index 44e1c52..ee224a8 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,6 @@ node_modules *.d.ts.map *.css.map *.html.map -*.vue.map *.scss.map *.sass.map *.less.map diff --git a/AGENTS.md b/AGENTS.md index 1df7f55..49cae05 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,8 +6,7 @@ independent of work-specific agents, services, credentials, and workflows. ## Developer archetype: the toolchain engineer -Adopt the [toolchain engineer profile](docs/engineering/developer-archetype.md). -Treat the development feedback loop as part of the product: make checks fast, +Work as a toolchain engineer. Treat the development feedback loop as part of the product: make checks fast, repeatable, and useful to both people and agents. - Prefer Oxfmt for formatting and Oxlint for JavaScript/TypeScript linting. @@ -46,8 +45,7 @@ repeatable, and useful to both people and agents. Each package's README states its interface and guarantees, and its `CLAUDE.md` the rules for changing it; read both before touching a package. [CONTEXT.md](CONTEXT.md) holds the -vocabulary. `docs/` holds earlier designs and decisions as history: where it disagrees -with a package README or the exports, the package is current. +vocabulary. Keep these responsibilities distinct: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 32a156d..d90e7ef 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,13 +48,11 @@ and `tsconfig.base.json` hold ordinary shared defaults; package configs own publ entries, environment differences and output paths. pnpm owns dependency ordering. The `typescript` dependency aliases `@typescript/typescript6` for declaration and compiler API compatibility; use its `tsc6` CLI for explicit type checking. -There is no Vue SFC, Volar or portable tooling-profile contract in this workspace. Keep signed vectors and observable failure cases when refactoring. Public imports, -declarations, CLI behavior, import isolation and exact tarballs need their own -checks. The temporary Vue render consumer proves production CSS, interaction and -browser cryptography; it does not certify a component library or documentation -site. Formatting, types, behavior and installed consumers establish different +declarations, import isolation and exact tarballs need their own checks. The +browser consumer proves each library works in a production browser build. +Formatting, types, behavior and installed consumers establish different properties. Report unavailable checks honestly and preserve failing exit statuses. Current run reports, candidate digests and the browser screenshot are written to ignored `artifacts/`. @@ -62,14 +60,11 @@ ignored `artifacts/`. `pnpm-workspace.yaml` selects exactly Identity, Armour, Ledger, Concord and Seal. Keep runtime dependencies with their owning library and use declared public exports between packages. Preserve unrelated edits. Retire unused source instead -of creating legacy archives; Git keeps history. UI and Workspace remain excluded. -See the [repository guide](docs/engineering/repository-hygiene.md) for ownership -and check boundaries. +of creating legacy archives; Git keeps history. The read-only CI workflow verifies candidates and retains a release bundle. Separate version-PR and production release workflows require explicit account setup and enablement. -Review their [release contract and setup](docs/engineering/release-and-deployment.md) -before enabling them. Public-registry acceptance remains outstanding; no workflow +Review the workflow files before enabling them. Public-registry acceptance remains outstanding; no workflow deploys applications. `renovate.json` configures dependency updates; the owner must enable Renovate for it to open PRs. diff --git a/README.md b/README.md index b9b0f3a..492dbc7 100644 --- a/README.md +++ b/README.md @@ -29,14 +29,11 @@ pnpm check The acceptance gate checks contracts, formatting, builds, lint, types and behavior, then validates exact tarballs with publint and installs them in an isolated -Node/browser consumer. The temporary Vue browser consumer uses ordinary render -functions and CSS. See [CONTRIBUTING.md](CONTRIBUTING.md) for prerequisites and +Node/browser consumer. See [CONTRIBUTING.md](CONTRIBUTING.md) for prerequisites and focused checks. A configured check is not a release receipt. `packages/` owns the libraries and `scripts/` owns repository acceptance and release. Each package's README describes its interface and guarantees, and its `CLAUDE.md` the -rules for changing it. `docs/` holds earlier designs and decisions as history; where it -disagrees with a package README, the README is current. Workspace and UI are outside -the release. +rules for changing it. ISC licensed. See [LICENSE](LICENSE). diff --git a/docs/adr/0001-center-the-alpha-on-concord.md b/docs/adr/0001-center-the-alpha-on-concord.md deleted file mode 100644 index 75b72f1..0000000 --- a/docs/adr/0001-center-the-alpha-on-concord.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -status: accepted ---- - -# Center the alpha on Concord - -Keep the code in one monorepo, but make `@ternent/concord` the primary developer-facing -package with protocol, system, and testing subpaths. Identity, Armour, and Seal remain -independently consumable because they have real standalone uses; Ledger mechanics and -the former Workspace runtime stay internal until an independent consumer justifies a -public boundary. This avoids cross-repository coordination and package seams inherited -from the unfinished migration while preserving extraction paths. diff --git a/docs/adr/0002-separate-system-and-application-extensions.md b/docs/adr/0002-separate-system-and-application-extensions.md deleted file mode 100644 index dce7275..0000000 --- a/docs/adr/0002-separate-system-and-application-extensions.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -status: accepted ---- - -# Separate system and application extensions - -Concord recognizes system extensions and application models as its two execution -classes. Host-trusted system extensions establish identity, authority, privacy, and -decryption before a typed application model sees domain events; application code never -handles raw keys or mutable permission state. This preserves the proven two-pass design -without exposing the legacy mutable replay context or requiring applications to rebuild -security lifecycle code. diff --git a/docs/adr/0003-bind-one-application-model-to-a-document.md b/docs/adr/0003-bind-one-application-model-to-a-document.md deleted file mode 100644 index 377f6c7..0000000 --- a/docs/adr/0003-bind-one-application-model-to-a-document.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -status: accepted ---- - -# Bind one application model to a document - -Each alpha document selects one application model and version at creation and cannot -upgrade it in place. Breaking changes create another document and may record ordinary -provenance metadata. Bounded documents reduce the pressure to become permanent, -mixed-schema databases; multi-document explorers and aggregators can provide larger -experiences above Concord. diff --git a/docs/adr/0004-use-one-derived-identity-suite.md b/docs/adr/0004-use-one-derived-identity-suite.md deleted file mode 100644 index 389b41c..0000000 --- a/docs/adr/0004-use-one-derived-identity-suite.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -status: accepted ---- - -# Use one derived identity suite - -Alpha fixes one versioned suite: an Ed25519 identity signs, and deterministic conversion -of the same key material supplies its X25519 age capability. Public identity data and -private host capability are separate API types, while conversion rules and vectors are -normative for interoperability. This retains one simple identity for developers and -removes the need to store or bind a second encryption key. diff --git a/docs/adr/0005-use-single-head-snapshots-and-explicit-divergence.md b/docs/adr/0005-use-single-head-snapshots-and-explicit-divergence.md deleted file mode 100644 index eb1ae7c..0000000 --- a/docs/adr/0005-use-single-head-snapshots-and-explicit-divergence.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -status: accepted ---- - -# Use single-head snapshots and explicit divergence - -The genesis commit identifies a document lineage; every snapshot selects one head and -replays its linear parent chain. Two snapshots whose heads descend independently from -the same commit may both be valid. Concord classifies them as diverged but never orders, -combines, or silently selects between them. Alpha has no merge operation: integrations -retain both variants or ask a person to choose, while combining their meaning creates a -new document that may reference both source heads. The resolver signs that new -document's genesis and establishes its authority and audiences explicitly; security -state does not carry over from either source. This keeps signatures and attribution -honest without putting a DAG or merge engine into the protocol. diff --git a/docs/adr/0006-sign-canonical-commit-subjects.md b/docs/adr/0006-sign-canonical-commit-subjects.md deleted file mode 100644 index 46b6977..0000000 --- a/docs/adr/0006-sign-canonical-commit-subjects.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -status: accepted ---- - -# Sign canonical commit subjects with explicit domains - -Use restricted RFC 8785 JSON, safe integers, canonical binary encodings, and separate -entry/commit/signature domain prefixes. A commit signs the complete unsigned subject, -including declarations at genesis, signer, parent, ordered entry IDs, nonce, and signed -metadata. Entry hashes are authenticated by their commit, so independent entry proofs -and Seal's artifact envelope are unnecessary. This chooses a small language-neutral -document contract over legacy proof reuse; permissive parsing or changing canonical -values later would change identifiers and interoperability. See the exact byte rules -and fixed artifacts in [Protocol 1](../concord/alpha-protocol.md). diff --git a/docs/adr/0007-start-with-one-private-document-audience.md b/docs/adr/0007-start-with-one-private-document-audience.md deleted file mode 100644 index af7b3b5..0000000 --- a/docs/adr/0007-start-with-one-private-document-audience.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -status: accepted ---- - -# Start with one private document audience and complete historical admission - -The initial single-audience scope is extended by -[ADR 0015](0015-keep-audience-memberships-independent.md), accepted 2026-11-20. -Historical admission and per-audience rotation remain; the paragraph below records -the original starting decision rather than the full shipping scope. - -The standard alpha profile encrypts application entries to one shared document audience -from genesis. Admitting a reader explicitly wraps every historical epoch key; removing -a member creates a fresh epoch for remaining members. This favors complete bounded -reconstruction over task-specific audiences or future-only admission, which would -require defined partial-projection semantics. Current read authority, historical write -authority, and retained key knowledge remain distinct. A host cannot certify encrypted -wraps it cannot decrypt, or revoke plaintext already obtained. See -[the standard profile](../concord/standard-profile.md). diff --git a/docs/adr/0008-publish-only-complete-committed-reconstructions.md b/docs/adr/0008-publish-only-complete-committed-reconstructions.md deleted file mode 100644 index f6faf7e..0000000 --- a/docs/adr/0008-publish-only-complete-committed-reconstructions.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -status: accepted ---- - -# Publish only complete committed reconstructions - -2026-11-20 clarification: [ADR 0015](0015-keep-audience-memberships-independent.md) -retains atomic publication and full signed-history verification while introducing -explicitly scoped readable views. The [group design draft](../concord/group-profile-design.md) -proposes a complete model pass over readable events and locked markers, with -coverage carried in the result. It never labels skipped content as full application -reconstruction. That refinement is not yet implemented. - -Protocol verification, historical system replay/decryption, and model reduction complete -before a candidate snapshot and projection replace the prior published state. Unknown -requirements, unavailable keys, invalid events, and incomplete ancestry produce -read-only inspection with retained original bytes. Draft previews are explicitly -provisional, volatile, and separate from committed projection/export. This rejects -best-effort skipping and legacy staged-state-as-truth behavior because either can make -different readers silently present incomplete state as the same authoritative snapshot. -See [the lifecycle interface](../concord/implementation-blueprint.md). diff --git a/docs/adr/0009-keep-concord-crypto-composition-above-primitives.md b/docs/adr/0009-keep-concord-crypto-composition-above-primitives.md deleted file mode 100644 index aebb61a..0000000 --- a/docs/adr/0009-keep-concord-crypto-composition-above-primitives.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -status: accepted ---- - -# Compose document crypto above independent primitives - -Identity owns strict raw-byte signing and deterministic key conversion; Armour owns the -pure TypeScript age engine and composes decryption capabilities with Identity. Concord -owns canonical signed document subjects and its standard system profile; Seal remains -an independent artifact-proof consumer. Protocol verification has no runtime, model, -Armour, or Seal dependency. This avoids a primitive-package cycle and prevents legacy -Identity signature context or Seal proof semantics from silently changing Concord's -wire bytes. Candidate tarball consumers must prove those separations. See -[module ownership](../concord/implementation-blueprint.md#5-modules-and-packages). diff --git a/docs/adr/0010-use-vite-plus-with-portable-tooling-profiles.md b/docs/adr/0010-use-vite-plus-with-portable-tooling-profiles.md deleted file mode 100644 index 948a2a1..0000000 --- a/docs/adr/0010-use-vite-plus-with-portable-tooling-profiles.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -status: accepted ---- - -# Use Vite+ with portable tooling profiles - -The portable-profile, product-scope and scheduling details below are superseded by -[ADR 0020](0020-simplify-core-around-five-libraries.md). pnpm and project-local Vite+ -remain selected; ordinary repository configs replace the published tooling module. -The text below records the original decision. - -Rebuild the monorepo around pnpm and project-local Vite+, with independently versioned -Identity, Armour, Seal, Concord, UI, and a portable development-only tooling module. -The tooling module owns a few tested library/CLI/Vue/app/docs profiles; package manifests -own public metadata and Vite Task owns scheduling. This replaces copied per-package -configurations and legacy Ledger/Workspace seams without introducing another build -system. Plain executable ESM tooling is an explicit bootstrap exception to compiled -library outputs. Experimental tsrs stays a comparison lane until diagnostic, consumer, -and repository performance evidence supports promotion. See -[the current repository guide](../engineering/repository-hygiene.md). diff --git a/docs/adr/0011-publish-verified-artifacts-through-one-workflow.md b/docs/adr/0011-publish-verified-artifacts-through-one-workflow.md deleted file mode 100644 index 23317dc..0000000 --- a/docs/adr/0011-publish-verified-artifacts-through-one-workflow.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -status: accepted ---- - -# Publish verified artifacts through one workflow - -Changesets versions independent public packages, and one GitHub Actions publisher uses -npm OIDC to publish the exact tarballs installed by isolated consumers. A digest-bound -release plan and per-package journal allow partial releases to resume without rebuilding -or overwriting a version. Tags are evidence of successful publication rather than a -second publisher trigger. This trades a small artifact handoff for confidence that -published bytes match reviewed checks; npm release sets remain explicitly non-atomic. -See [the release contract](../engineering/release-and-deployment.md). diff --git a/docs/adr/0012-deploy-private-ui-apps-to-cloudflare-workers.md b/docs/adr/0012-deploy-private-ui-apps-to-cloudflare-workers.md deleted file mode 100644 index 31bd1c5..0000000 --- a/docs/adr/0012-deploy-private-ui-apps-to-cloudflare-workers.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -status: accepted ---- - -# Deploy private UI applications to Cloudflare Workers Static Assets - -Publish libraries/components to npm and deploy their private application consumers to -Cloudflare through one GitHub-controlled Wrangler workflow. New stateless UI apps use -Workers Static Assets with explicit Preview configuration and verified immutable asset -bundles; Cloudflare hosting does not introduce a Concord backend or storage dependency. -Separate deployment receipts, environments, and rollback from package versioning so -an application change need not publish its libraries. Prefer this single deployment -family over parallel Pages/Workers build pipelines for the clean target. See -[deployment semantics](../engineering/release-and-deployment.md). diff --git a/docs/adr/0013-pilot-candidate-isolation.md b/docs/adr/0013-pilot-candidate-isolation.md deleted file mode 100644 index e464ed3..0000000 --- a/docs/adr/0013-pilot-candidate-isolation.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -status: accepted ---- - -# Isolate R1 consumers with exact candidate overrides - -Exact candidate overrides remain the local isolation method. -[ADR 0020](0020-simplify-core-around-five-libraries.md) retires the portable-profile -and fixture products described below; the five libraries retain their public consumer -checks. Final registry-range acceptance remains on the -[release backlog](../engineering/release-and-deployment.md#release-backlog). - -For the tooling pilot, pack every candidate once and install those tarballs in a -temporary directory outside the workspace. Override every candidate name to its -exact local tarball, including transitive sibling references. Registry access may -resolve external dependencies, but cannot substitute a published predecessor for a -candidate. Record candidate SHA-256 digests with the consumer acceptance results. - -This exercises public exports, declarations, CLI metadata, Vue assets, and portable -tooling without sibling-source aliases or root dependency resolution. The validator -also rejects undeclared imports in emitted JavaScript and declarations. Private -fixtures use packable manifests but never become publication candidates. - -This is equivalent isolated resolution for R1, not an npm publication rehearsal. -R5 adds the temporary registry, planned release versions, packed registry metadata, -OIDC identity, and artifact-preserving publication checks specified in the release -contract. No release infrastructure is required merely to prove portable profiles. - -See [current acceptance boundaries](../engineering/repository-hygiene.md#acceptance-boundaries). diff --git a/docs/adr/0014-keep-async-profile-reentry-a-host-contract.md b/docs/adr/0014-keep-async-profile-reentry-a-host-contract.md deleted file mode 100644 index 8bddd51..0000000 --- a/docs/adr/0014-keep-async-profile-reentry-a-host-contract.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -status: accepted ---- - -# Keep asynchronous profile reentry a host contract - -Models and system profiles are trusted host implementations. Neither may dispatch -back into the same handle while evaluating its current operation. Model callbacks -are synchronous and pure; profiles may await cryptographic operations. - -The runtime rejects synchronous callback reentry with `HOST_CONFIGURATION`. It -does not hold that guard across an asynchronous profile's entire promise: doing so -would also reject legitimate external dispatches while encryption is pending, -breaking the required per-handle operation queue. - -Asynchronous profiles must therefore honor the no-reentry rule after their own -awaits. The alpha runtime does not instrument host async context or promise -ownership to distinguish that invalid call from an independent caller. An async -profile that awaits its own queued dispatch can deadlock; it is a nonconforming -host implementation, not a supported failure path with guaranteed automatic -detection. The official standard profile has no handle reference and follows this -rule. Loading document bytes never loads executable profiles. - -This clarifies the earlier blanket rejection promise without weakening serialized -authoring or purity for conforming extensions. Future host-context instrumentation -must preserve queued concurrent dispatch and prove behavior in Node and browser -consumers before expanding automatic detection. diff --git a/docs/adr/0015-keep-audience-memberships-independent.md b/docs/adr/0015-keep-audience-memberships-independent.md deleted file mode 100644 index ec3f756..0000000 --- a/docs/adr/0015-keep-audience-memberships-independent.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -status: accepted ---- - -# Keep audience memberships independent - -On 2026-11-20, Sam accepted treating the existing `document` audience as the -default group and keeping additional encrypted groups independent: - -> sounds good, lets go with your recommendation to keep them separate - -Each audience owns its members, capabilities, epoch keys, admissions and removals. -An identity can join a private group without joining the default group. Removing -default-group membership does not remove another group's membership or rotate its -keys. The default group's administrators cannot grant themselves access to an -independent group. Its writers may create groups without owner approval; the -new group's creator initially administers that group. - -The genesis signer initially administers the default group. This does not give -them universal authority over every group created later. A group editor can -continue authoring in that group after losing default-group membership, provided -their group authority remains valid. Creating another group still requires -default-group write. There is no implicit document-wide ban or cascading removal. - -Joining or rejoining a group grants its full history. Removing a member rotates -that group's future key; it cannot retract old keys or plaintext. System replay -establishes historical authority and available decryption before application replay. -Readable content remains inspectable even after current membership ends. - -This extends the single-audience starting scope in [ADR 0007](0007-start-with-one-private-document-audience.md). -The atomic publication rule in [ADR 0008](0008-publish-only-complete-committed-reconstructions.md) -continues to hold. A readable view must explicitly distinguish locked entries and -its limited application coverage; it cannot claim full reconstruction by skipping -unavailable content. - -The [group design](../concord/group-profile-design.md) proposes concrete schemas, -interfaces and acceptance checks. Those implementation details are a design draft; -this ADR records the accepted membership decision, not implemented multi-group support. diff --git a/docs/adr/0016-route-each-command-to-one-audience.md b/docs/adr/0016-route-each-command-to-one-audience.md deleted file mode 100644 index 93f3863..0000000 --- a/docs/adr/0016-route-each-command-to-one-audience.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -status: accepted ---- - -# Route each command to one audience - -On 2026-11-20, Sam chose one audience per application command: - -> no, we'll stick with one. Lets keep it simple - -After input validation, a command selects its audience before its decision runs. -Its decision receives the signer's facts for that audience. Every emitted event -must select the same audience, and replay checks the model's event selection -against its signed envelope. A command cannot emit entries for several groups. - -Explicit draft mode may group multiple commands from different audiences into one -atomic commit, subject to the author having each command's required authority. -An application can express a cross-group operation through such a draft; it does -not require a second multi-audience command contract. - -See the [group design](../concord/group-profile-design.md). The routing decision is -accepted; multi-group authoring and draft support are not yet implemented. diff --git a/docs/adr/0017-drop-ui-from-the-library-release.md b/docs/adr/0017-drop-ui-from-the-library-release.md deleted file mode 100644 index 376b0b7..0000000 --- a/docs/adr/0017-drop-ui-from-the-library-release.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -status: accepted ---- - -# Drop the maintained UI package from the library release - -On 2026-11-21, Sam accepted removing `@ternent/ui` from the v1 release requirements. -The design-system package was an earlier decision and does not justify ongoing -maintenance by itself. - -The public release contains five products: Identity, Armour, Concord, Seal and -portable Tooling. UI migration tasks B08–B10 are cancelled. Their work is not a -prerequisite for package verification, publishing or demos. This supersedes the -six-product boundary and UI-product requirements in earlier architecture documents. - -Keep the existing excluded UI sources available as reference. No UI source migration, -new package or replacement design system is required by this decision. Portable -Vue build profiles and consumer fixtures remain useful verification of the tooling -and browser-facing libraries; they do not imply a public UI product. - -When building demos, choose a maintained component foundation, a small visual brief -and theme, and application components shaped by the actual demo. Review generated -UI through browser behavior and accessibility checks. Extract shared components -only when repeated use establishes a need; do not prebuild another component library. - -Next: complete isolated candidate-registry verification (B13), then release planning, -workflow integration and published consumption proof (B14–B16). Workspace remains -deferred until the libraries run smoothly and plenty of demos exist. diff --git a/docs/adr/0018-use-one-ledger-container-for-concord.md b/docs/adr/0018-use-one-ledger-container-for-concord.md deleted file mode 100644 index 9c0e89c..0000000 --- a/docs/adr/0018-use-one-ledger-container-for-concord.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -status: accepted ---- - -# Use one Ledger container for Concord - -Working decision, 2026-11-21. The accepted answer is: - -> yes - -To this question: - -> Should Concord adopt the common Ledger container, accepting a breaking change to current Concord alpha documents? - -The five public packages are Identity, Armour, Concord, Seal and Ledger. This -replaces the Tooling product in the earlier release boundary; tooling is repository -infrastructure. It supersedes the Ledger ownership in -[ADR 0001](0001-center-the-alpha-on-concord.md) and the product list in -[ADR 0017](0017-drop-ui-from-the-library-release.md) where they conflict. - -Ledger is independently usable and owns the common signed container, entry staging, -commit construction, hashes, signatures, chain verification, import/export and -ordered replay. Concord consumes that lifecycle and composes commands, authority, -group membership, encryption orchestration and application replay. Its framework -records live within the Ledger container. A separate Concord signed container and -commit engine are not the target. - -This gives signed history one owner and keeps the standalone log useful without -adopting the framework. The original composition in -`samternent/home/packages/concord/src/app.ts` provides delegation evidence; the -scoped source Ledger is `samternent/home/packages/ledger-v2`. - -The common format breaks compatibility with the current Concord alpha documents. -Their existing bytes and vectors are not assumed readable under the new format. -Legacy import or conversion support is separate scope. Original standalone Ledger -encryption conveniences and staged-state persistence still require explicit -retain, move or drop decisions; accepting the common container does not settle them. - -This records an accepted target, not completed integration or release evidence. diff --git a/docs/adr/0019-keep-draft-persistence-with-consumers.md b/docs/adr/0019-keep-draft-persistence-with-consumers.md deleted file mode 100644 index 8e7d692..0000000 --- a/docs/adr/0019-keep-draft-persistence-with-consumers.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -status: accepted ---- - -# Keep draft persistence with consumers - -Decision, 2026-11-21: Ledger stages uncommitted entries in a simple in-memory array. -Concord keeps its pending command intents in memory. These are provisional local -work, separate from signed committed history. - -The consumer chooses when to commit and whether to autosave or recover unfinished -work. Ledger and Concord do not provide a persistence adapter, recovery snapshot or -restore protocol for drafts. Hosts can keep their own forms, commands or draft data -and submit them through the normal library APIs when appropriate. - -Committed export, import and external storage concern signed history only. A -Git-style push/pull workflow exchanges committed snapshots. Existing explicit -divergence and pending-draft checks remain; this decision introduces no automatic -merge or rebase. - -The previous Ledger's staged-state persistence is deliberately left to consumers. -It is not an outstanding library migration feature. Applications may still value -draft recovery; its behavior and storage belong to the application. diff --git a/docs/adr/0020-simplify-core-around-five-libraries.md b/docs/adr/0020-simplify-core-around-five-libraries.md deleted file mode 100644 index 9719d59..0000000 --- a/docs/adr/0020-simplify-core-around-five-libraries.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -status: accepted ---- - -# Simplify core around five libraries - -Core's active workspace and release scope are Identity, Armour, Ledger, Concord and -Seal. Ledger owns one common signed container and history lifecycle; Concord composes -commands, system authority, group encryption and model replay above it. UI is outside -the library release and Workspace remains deferred. Demos belong in separate projects -consuming published libraries. - -Remove the portable tooling package, tooling-profile fixtures, handshake app and -VitePress patch. Share ordinary root Vite+ and TypeScript base configs, keep explicit -package entries/outputs, and use standard pnpm recursive builds. Keep small repository -contract and consumer scripts; use standard publint for package validation instead of -a custom validator framework. This supersedes the portable-profile and Vite Task -scheduling requirements in [ADR 0010](0010-use-vite-plus-with-portable-tooling-profiles.md). - -Preserve meaningful evidence for all five products: separate format/lint/type/build/ -behavior gates, exact-tarball publint, fixed crypto vectors, public declarations, CLI -and import isolation, Node compatibility lanes and Chromium cryptography. Generate a -minimal Vue render/CSS consumer in a temporary directory. Retire SFC, documentation -routing, profile portability and handshake proof products; their removal does not -remove a library contract. [ADR 0013](0013-pilot-candidate-isolation.md)'s exact candidate -overrides were the initial isolation method. The consumer gate now uses an isolated -candidate registry without sibling overrides, checking dependency ranges as described -in the [repository guide](../engineering/repository-hygiene.md#acceptance-boundaries). - -Consolidate contributor guidance in [CONTRIBUTING.md](../../CONTRIBUTING.md) and the -[repository guide](../engineering/repository-hygiene.md). Keep the current release -contract/backlog in [release and deployment](../engineering/release-and-deployment.md). -Remove superseded reports after preserving their durable contracts and fixing links; -do not create forwarding stubs or copied legacy archives. Keep normative crypto, -group and storage contracts, vectors and durable ADR history. - -Staging is intentionally in memory. Consumers own commit cadence and any persistence -or recovery of uncommitted work under [ADR 0019](0019-keep-draft-persistence-with-consumers.md). -No library draft-persistence feature is pending. Publication and account onboarding -remain separate work; this cleanup neither publishes packages nor certifies a new -acceptance run. diff --git a/docs/concord/alpha-architecture.md b/docs/concord/alpha-architecture.md deleted file mode 100644 index 6adf834..0000000 --- a/docs/concord/alpha-architecture.md +++ /dev/null @@ -1,380 +0,0 @@ -# Concord alpha architecture - -Current container/ownership revision: [ADR 0018](../adr/0018-use-one-ledger-container-for-concord.md) -and [the Ledger-backed profile](alpha-protocol.md) supersede the Concord-only wire, -signing domains and internal-Ledger ownership described in this earlier plan. -Ledger is a standalone public product. Concord delegates its history lifecycle; -UI and public Tooling are outside the five-product release. - -Shipping update, 2026-11-20: [ADR 0015](../adr/0015-keep-audience-memberships-independent.md) -extends the initial single-audience scope with independent memberships. The -[group contract](group-profile-design.md) distinguishes complete projection -from explicitly scoped readable replay; atomic publication and full reachable -history verification still apply. B03/B04 now implement that contract. - -Status: accepted direction, 2026-10-21. This is the target for a clean rebuild. Existing -packages and specifications are evidence, not a compatibility requirement, unless this -document explicitly preserves a behavior. - -The [implementation blueprint](implementation-blueprint.md) specifies the alpha's wire -format, interfaces, standard-profile semantics, conformance vectors, and delivery gates. -Use it to implement this direction; the architecture below remains the product rationale. - -## Product definition - -> Concord lets TypeScript developers build small user-owned applications whose durable -> state is a portable, signed document that can be stored anywhere, verified -> independently, and rebuilt through deterministic replay. - -The first developer using Concord will usually be a coding agent. The interface should -therefore have a small number of explicit concepts, strong types, structured failures, -and fast conformance checks. The runtime should own difficult lifecycle and security -mechanics while leaving application meaning and storage behavior replaceable. - -Concord is intended for bounded records and data-entry applications. A document should -stay small enough to understand, move, inspect, and eventually replace. Software that -combines several documents belongs above Concord. - -## Design rules - -1. Signed history is authoritative; every projection is derived. -2. The same exact document snapshot, conforming models, and available capabilities - produce the same projection when their replay functions are deterministic. -3. A document remains portable across storage providers and independently verifiable. -4. The host chooses executable code. A document declares requirements but never causes - untrusted code to load. -5. System mechanics and application meaning have separate extension classes. -6. The standard system profile contains identities, authority, and privacy, not users or - profiles. -7. The smallest useful contract wins. Synchronization, directories, profiles, and - multi-document experiences stay outside the core runtime. - -## Conceptual shape - -```text -application UI or agent - | - v -typed application model commands -> domain events -> projection - | - v -standard system profile signer binding, authority, audiences, encryption - | - v -Concord runtime open, verify, replay, commit, inspect, export - | - v -protocol canonical bytes, hashes, signatures, chain validation - | - v -storage adapter read document / write document -``` - -These are responsibility boundaries, not necessarily public packages. - -## Concord document - -A document contains: - -- its protocol and cryptographic-suite versions; -- the required system profile and application model identifiers; -- an ordered, signed commit history; -- entries carried by those commits; and -- non-authoritative container metadata where useful. - -Each commit binds its canonical contents, ordered entry identifiers, parent commit, and -signer. Validation rejects altered, missing, reordered, or incorrectly signed reachable -history. - -The application model is fixed when the document is created. Alpha has no in-place model -upgrade mechanism. Updated software continues to read older model versions. A breaking -change uses an explicit migration tool to read the old document and author a new one; -the new document may record ordinary `derivedFrom` provenance. Concord gives that -metadata no authority. A migration can contain application-specific upcasters without -making upcasting part of replay or changing the old history. - -A byte-for-byte copy is still the same document snapshot. The genesis commit identifier -is the document ID shared by its lineage. Every snapshot selects exactly one head; the -head identifier names that exact snapshot, and its trusted history is the single parent -chain reachable from the head. Copies may continue from the same verified commit and -later diverge. Both variants can be valid; they share a document ID but are no longer the -same snapshot. - -The protocol defines how to compare two snapshots as equal, ahead, behind, or diverged. -It never combines divergent histories or silently selects a winner. Alpha has no merge -operation for divergent snapshots. Storage and product integrations must retain and -surface both or ask a person to select one; they cannot describe either action as a -cryptographic merge. - -If an application needs to combine meaning from both variants, it authors a new document -with a new genesis and may reference both source heads in ordinary provenance metadata. -The source snapshots remain independently auditable, and the new author's signature -attests to the resolution rather than impersonating the original authors. The resolver -signs the new genesis and becomes its initial owner through the normal create lifecycle. -Capabilities, audiences, and encryption keys from the source documents do not carry over -implicitly; the new document grants them explicitly. A combined container with ambiguous -heads cannot produce a trusted projection and opens for inspection. - -## Runtime lifecycle - -### Create - -Creating a document selects one system profile and one application model. The genesis -signer becomes the initial owner with read, write, grant, and administer capabilities. -The first commit records the declarations and initial system state. - -### Open - -`open` owns the complete trusted-read lifecycle: - -1. read or accept a document; -2. validate its container and complete reachable history; -3. resolve trusted implementations for the declared system profile and application - model; -4. replay system entries to establish identities, capabilities, and decryptability; -5. supply decrypted application events and explicit locked markers in their original order; and -6. publish projection and coverage together once the whole opted-in model pass succeeds. - -Integrity validity and model validity are separate. An unknown model is not tampering. -It means the host cannot produce a complete trusted application projection. - -Integrity validity is also separate from freshness and completeness. A valid signature -cannot prove that storage returned the newest known head or disclosed every divergent -variant. A host that remembers a prior head or trusted checkpoint can detect an older or -divergent response; a host with no external anchor cannot. - -Invalid, locked, or incompatible documents return an inspection handle rather than -disappearing behind a generic load error. It exposes raw history, validation findings, -missing requirements, locked-entry counts, and export facilities. It does not expose a -trusted projection or allow writes. - -### Author - -Application code dispatches a typed command. Its application model validates the input -and returns domain events. The system profile binds the actor to the active signer, -checks capabilities, applies audience protection, and creates the protocol entries. -Application code does not handle raw keys, permission state, or entry envelopes. - -Concord supports two authoring modes over the same history model: - -- **Immediate** is the default: a successful command creates a signed local commit. -- **Draft** groups several successful commands into one explicit commit with optional - metadata such as a message. - -Storage publication is separate from local commit creation. A storage adapter decides -whether writing is immediate, explicit, remote, synchronized, or conflict-aware. - -### Export - -Export returns the portable document. The exported artifact must be sufficient for an -independent implementation to validate its history and, when it has the declared models -and required keys, reproduce its projection. - -## Extension contract - -Concord recognizes exactly two execution classes. - -### System extensions - -System extensions are selected by the trusted host to satisfy a document's declared -system profile. They own: - -- public identities and signer binding; -- capabilities such as read, write, grant, and administer; -- privacy groups, audiences, and key distribution; -- decryption before application replay; and -- authorization before application events are recorded. - -The official alpha system profile is used from genesis, including for a single-owner -document. A deliberately public specialist profile may be added later without weakening -the default. - -### Application models - -The primary application interface is declarative and typed: - -- stable model identifier and version; -- initial projection state; -- typed commands with input validation and decision functions; -- versioned event validation; and -- pure reducers. - -A document has one bounded application model. Several interfaces may understand that -model, but unrelated application schemas do not accumulate in one long-lived document. -Low-level replay hooks may exist as a specialist surface; they are not the normal way to -build an application. - -An application model may declare the audience and capability required for an operation. -During replay it receives authorized, decrypted domain events and stable system facts, -not mutable security internals. An explicit `reduceLocked` hook opts into missing-event -markers. A full model requires every event; a readable view certifies only available -semantics, with coverage and locked counts on every public projection result. - -### Deterministic replay conditions - -Concord makes determinism a model contract and a conformance target rather than claiming -that TypeScript can enforce purity. Reducers and system replay functions must depend only -on their ordered inputs and declared deterministic context. Time, randomness, generated -identifiers, locale-sensitive behavior, and external reads must be captured in authored -events before replay. Canonicalization and numeric behavior must be specified for every -protocol value. - -Independent signature verification does not require application code. Reproducing an -application projection additionally requires a conforming implementation of the declared -system profile and application model. Shared model vectors should catch incompatible -implementations; the trusted host remains responsible for selecting the implementation. - -## Identity and cryptography - -The alpha suite is fixed and versioned: - -- Ed25519 for signatures; -- identity ID derived from the canonical Ed25519 public key; -- deterministic Ed25519-to-X25519 conversion; -- age-compatible X25519 recipient encryption; and -- typage through the pure TypeScript `age-encryption` package, without WASM initialization. - -One seed is the identity capability root. Its Ed25519 key signs; its deterministically -converted X25519 key decrypts. Concord does not store a second encryption public key. -The exact conversion, canonical encodings, and expected outputs are normative protocol -material with shared cross-language vectors. - -The Identity API separates: - -- `PublicIdentity`, safe for documents, containing version, algorithm, public key, and - derived ID; and -- `IdentityCapability`, held by the host, containing private material and signing and - decryption operations. - -Profiles, names, avatars, emails, presence, and peer discovery are not system records. -An application may model them when they belong to its domain. An optional identity -directory may map identities to profiles and facilitate peer or real-time connections. -Offline interfaces can represent an identity with a deterministic glyph derived from -its ID. - -Alpha does not define key rotation, account recovery, or continuity proofs. Replacing a -key introduces a new identity and requires an authorized grant. - -## Privacy and authority - -Privacy and authority remain distinct: - -- an audience determines who can decrypt; -- a capability determines who may perform an operation; -- historical key possession records what an identity may already know; -- active membership records current group participation; and -- revocation prevents future access or writes but cannot erase previously obtained keys - or plaintext. - -Friendly products may present viewer, editor, and owner presets. They compile to the -separate audience and capability rules rather than replacing them. - -Authority is evaluated along the selected head's ancestry. An editor who authors from a -parent before their revocation may create a valid divergent variant in which the later -revocation never occurred. That commit cannot be inserted after the revocation or merged -silently into the revocation branch. Neither variant is globally canonical from the -signatures alone. Detecting or rejecting the unwanted variant requires a remembered head, -trusted checkpoint, or another external coordination mechanism. - -## Security and privacy limits - -Signatures establish integrity and authorship within the selected history. They do not -establish freshness, availability, global completeness, or consensus between writers. -Storage can withhold a branch or return an older valid snapshot; Concord can only detect -this when the host has an external freshness anchor. - -Encrypting entry payloads does not necessarily hide envelope metadata such as authors, -commit cadence, ciphertext sizes, or relationship patterns. The exact public envelope -must be minimized and documented in the protocol. - -Append-only history and uncontrolled copies mean Concord cannot promise universal -erasure. Removing keys can make encrypted content inaccessible to a particular host but -cannot retract plaintext or keys already obtained. Applications with deletion or legal -retention requirements must account for that limit explicitly. - -## Storage boundary - -The minimum storage adapter can read and write a complete document. Concord validates -documents after reading and before exposing trusted state. Storage never establishes -authority and cannot silently repair, rewrite, invent, or combine signed history. - -Adapters may independently add compare-and-swap, revisions, subscriptions, Solid pod -behavior, peer exchange, push/pull, or conflict presentation. Those capabilities do not -expand the core storage contract or change application-model behavior. In alpha, -"handling" a divergence means retaining it, presenting it, or asking the caller to pick -a variant; it does not mean synthesizing a merged Concord history. - -A concurrency-aware adapter can accept an expected head and report divergence rather -than overwrite another writer. An adapter without that facility remains usable for -single-writer or externally coordinated storage, but cannot claim concurrent-write -protection. Shared applications should prefer expected-head writes so routine races are -rejected before one snapshot overwrites another. The rejected local snapshot remains a -valid variant; the application can reopen the accepted head and ask the author to issue -the intended command again. The runtime should expose that storage capability so -applications can communicate the difference. - -## Protocol and interoperability - -The protocol is part of the Concord product contract rather than a separately designed -product. It consists of a language-neutral specification, canonical encodings, and -conformance vectors. TypeScript helpers are published at `@ternent/concord/protocol`. -Normal application developers should not need to import them. - -Rust, shell, or another implementation can interoperate by following the specification -and passing the same vectors. Vectors cover at least canonicalization, entry IDs, commit -IDs, signatures, parent linkage, identity derivation, age-recipient derivation, valid -documents, snapshot relationship classification, divergent revocation histories, and -representative tampering failures. - -## Repository and packages - -Keep one monorepo while the contracts are being established. Repository layout, -installable package boundaries, and release cadence are separate decisions. - -The five public packages are Identity, Armour, Ledger, Concord and Seal. Ledger -owns the common signed container and history lifecycle. Concord composes commands, -authority, group encryption and application replay, with specialist `/protocol`, -`/system` and `/testing` subpaths. Workspace is deferred. - -Storage integrations and applications are consumers. The libraries use ordinary -Vite+/TypeScript configs and exact-tarball acceptance under the -[repository guide](../engineering/repository-hygiene.md). - -## Application consumers - -Applications and demos live outside core and consume the libraries. The earlier -handshake pilot is retained in Git; it is not a library release gate. Current -acceptance exercises signed history, private membership, authoring, export and -deterministic replay through installed-package consumers, including a temporary -browser application. Hosts own draft persistence and publication of committed data. - -## Deferred project-board example - -One document represents one project board. The application model demonstrates: - -- board metadata and columns or lists; -- task creation, editing, movement, assignment, and archival; -- identities represented without requiring profiles; -- viewer, editor, and owner capabilities; -- private audiences and shared encryption keys; -- immediate commands and grouped commits with messages; -- expected-head publication rejecting a routine stale write, plus two offline editors - producing surfaced divergence with no silent merge; -- document export, reopen, deterministic replay, and history inspection; and -- useful inspection states for tampering, missing models, and locked entries. - -A later explorer can open and compare several board documents. Multi-board aggregation -does not change the one-model-per-document rule. - -## Explicitly deferred - -Alpha does not require: - -- in-place application-model upgrades; -- key rotation, recovery, or identity continuity; -- a profile, user, or account system; -- a network service, real-time transport, or peer-discovery protocol; -- a core push, pull, merge, or conflict-resolution algorithm; -- multi-document queries inside Concord; -- automatic loading of code named by a document; or -- multiple unrelated application models in one document. diff --git a/docs/concord/alpha-protocol.md b/docs/concord/alpha-protocol.md deleted file mode 100644 index 8bdc9d5..0000000 --- a/docs/concord/alpha-protocol.md +++ /dev/null @@ -1,169 +0,0 @@ -# Concord profile over the common Ledger container - -Accepted breaking alpha revision, 2026-11-21, under -[ADR 0018](../adr/0018-use-one-ledger-container-for-concord.md). Ledger owns the -container, history lifecycle and all history cryptography. Concord supplies framework -records, authority, group encryption and application replay. Former Concord-only -containers and historical `concord-ledger` containers are not accepted by this alpha; -no import/conversion adapter is implied. - -Read with [Ledger's format and interface](../../packages/ledger/README.md), the -[standard profile](standard-profile.md), [group contract](group-profile-design.md) -and [current vectors](vectors/README.md). MUST and MUST NOT describe the checked -contract, not historical fixture parity or completed registry publication. - -## 1. Values and bytes - -`Json` is null, boolean, Unicode string, safe integer, array of Json, or an object -whose own string keys map to Json. Numbers MUST be integers in -`[-9007199254740991, 9007199254740991]`. Negative zero is rejected, including the -lexical forms `-0` and `-0.0`. Fractions, non-finite numbers, sparse arrays, -undefined, bigint, functions, cycles, accessors, symbol keys, and custom prototypes -are rejected at the authoring interface. Parsed objects may have a null prototype. -Decimal application values use model-defined strings. No coercion or normalization. -`JsonObject` denotes an object of such values; it excludes arrays and null. - -`C(value)` is UTF-8 without BOM of the JSON Canonicalization Scheme in -[RFC 8785](https://www.rfc-editor.org/rfc/rfc8785.html), restricted to the above -numeric domain. Object keys sort by unsigned UTF-16 code units recursively; array -order is preserved. Strings preserve their Unicode form. Lone surrogates are -rejected. Thus visually identical normalized and decomposed strings may hash -differently. Export uses `C(snapshot)`, with no trailing newline. - -Import accepts non-canonical JSON whitespace and key ordering, but MUST use a -duplicate-detecting, strict UTF-8 parser before making objects. Duplicate decoded -keys (including escape aliases), BOM, invalid UTF-8, trailing data, invalid JSON, -and numbers outside the value domain fail. Inspect raw bytes on failure; do not -parse with `JSON.parse` alone and lose evidence. Validate numeric tokens before -rounding to binary64; evaluate the token's mathematical decimal/exponent value as an -exact rational first. It must be integral and in range. A fraction or out-of-range -value MUST NOT round into an accepted integer. -An integral representation such as `1.0` or `1e0` imports as 1; export emits 1. - -`B(bytes)` is canonical unpadded base64url (RFC 4648 section 5): URL alphabet only, -zero unused bits, no whitespace or `=`, and decode/re-encode equality. Hashes use -lowercase hexadecimal. All protocol objects are closed: missing or extra fields -fail schema validation. Fields typed `JsonObject | null` are the explicit open -metadata slots. Required nulls are not omitted. Ledger timestamps are signed canonical UTC ISO -strings; parent linkage and array order determine history order. - -## 2. Identity and algorithms - -Ledger uses the suite string `ledger-ed25519-v1`. `PublicIdentity` has exactly: - -```ts -type PublicIdentity = { - version: 1; - algorithm: "Ed25519"; - publicKey: string; // B(raw compressed 32-byte Ed25519 key) - id: string; // "identity:" + lowercase hex(SHA-256(raw public key)) -}; -``` - -Identity ID deliberately preserves the existing raw-key SHA-256 derivation while -giving the identifier a type prefix. Created time and private seed are excluded. -Reject mismatched IDs, non-canonical point encodings, identity/small-order points, -and points outside the prime-order subgroup. This validation also applies to -signature R points. Decode points using RFC 8032, require `[L]P = identity` and -`P != identity`, where `L = 2^252 + 27742317777372353535851937790883648493`. -Signature scalar S MUST be less than L. Verify the uncofactored equation -`[S]B = R + [H(R || A || message) mod L]A`. Alpha deliberately disallows permissive -ZIP-215 acceptance; adapters must configure or wrap their crypto library accordingly. -Ed25519 refers to PureEdDSA in [RFC 8032](https://www.rfc-editor.org/rfc/rfc8032.html), -not Ed25519ph or Ed25519ctx. - -The private root is exactly a 32-byte Ed25519 seed. For X25519, compute SHA-512(seed), -take its first 32 bytes, clear the low three bits of byte 0, clear bit 7 of byte 31, -and set bit 6 of byte 31. For the public conversion, decode Edwards y, then compute -`u = (1+y)/(1-y) mod (2^255-19)` and encode u as 32-byte little endian. Validate the -Edwards point first; reject denominator zero. The private and public routes MUST -produce the same X25519 public key. This is the conversion described by -[libsodium](https://libsodium.gitbook.io/doc/advanced/ed25519-curve25519), not a -second seed or a mnemonic derivation. Mnemonics are outside the wire contract. - -Encode X25519 public keys as lowercase Bech32 HRP `age`, and secrets as uppercase -Bech32 HRP `AGE-SECRET-KEY-`, with the original Bech32 checksum, not Bech32m. -Use the X25519 recipient and binary file format of -[age v1, C2SP revision v1.1.0](https://c2sp.org/age@v1.1.0). -Concord authors only X25519 recipient stanzas, no armor, passphrase, SSH, or plugin -recipients. Armour owns age implementation; Concord MUST NOT implement an alternate -encryption construction. Age bytes are stored as B(bytes). Fresh age file keys, -ephemeral keys, and nonces are required for every encryption. - -## 3. Framework records inside Ledger - -The outer object is exactly the common Ledger snapshot: `format: "ledger"`, -`version: 1`, `documentId`, `head`, ordered `commits` and ordered `entries`. -There is no outer Concord format, signature domain or unsigned annotation slot. -Ledger entry/commit IDs and signatures use its `ledger.entry/1`, `ledger.commit/1` -and `ledger.signature/1` domains, each followed by NUL and the canonical subject. -The full raw subject, including timestamps and metadata, is bound by the history. - -The signed genesis commit metadata is exactly: - -```ts -{ concord: { system: { id: string, version: number }, model: { id: string, version: number } } } -``` - -References use lowercase IDs matching `^[a-z][a-z0-9.-]{0,127}$` and integer versions -from 1 to 2147483647. Only genesis metadata establishes these requirements. Later -commit metadata is arbitrary signed JSON metadata and cannot replace the declaration. -A syntactically valid unknown reference is a runtime requirement, not a bad signature. - -Concord uses raw Ledger entries with `kind: "system" | "application"`: - -- `system`: `subject.payload.data` is `{ type, version, data }`, where data is a JSON - object. The standard profile owns its event schemas and historical authority. -- `application`: `subject.payload.data` is `{ audience, epoch, ciphertext }`. - Audience is `document` or a canonical 16-byte `group:` identifier; epoch is a - non-negative safe integer; ciphertext is canonical base64url of a binary age file. - -The raw Ledger payload envelope is `{ type: "plain", data: }`. -This describes its JSON representation; encrypted application content stays ciphertext. -The Ledger subject's parent, nonce and bound author supply the history context. -Concord's prepared/replay `EntrySubject` is a logical view retaining the raw entry ID; -it is not another signed subject and MUST NOT be independently hashed as the wire record. - -## 4. Verification, authoring and replay - -Ledger first enforces strict parsing, resource bounds, closed record schemas, -identity validity, unique/ordered referenced records, content hashes, parent linkage -and signatures. Genesis may be empty in standalone Ledger; Concord's standard -profile creates one initial system record atomically in its genesis commit. -Only after Ledger verification may Concord validate framework envelopes/declaration, -execute the system pass, decrypt available content and run application replay. -Invalid or incomplete reachable history never produces a trusted application state. - -Concord delegates create/load, entry staging, commits, verification and export to -Ledger. It retains application command-intent drafts and previews. At commit time it -prepares records, builds a private Ledger candidate, and runs the complete framework -validation/replay before adopting that candidate and projection together. Failure -preserves the active history and pending command draft. Export contains committed -Ledger history; storage publication remains a separate host operation. - -Default Concord limits remain 16 MiB input/export, 10,000 commits, 100,000 entries, -1 MiB decoded ciphertext per application entry/key wrap, 64 nesting levels and -64 KiB canonical metadata per slot. Metadata bounds include the signed genesis -declaration. Exceeding a bound returns `RESOURCE_LIMIT`/unsupported. Limits are -checked before decryption and publication; framework replay and metadata access -must not bypass the limits already enforced by Ledger. - -Integrity is separate from authority, decryptability, application validity and -freshness. A standalone Ledger reader can verify the same bytes without Concord's -model or group keys. A valid older prefix remains cryptographically valid; only an -external remembered head can establish that it is stale. There is no automatic merge. - -## 5. Snapshot relationships and anchors - -`compareSnapshots(a, b)` first protocol-verifies both. Different document IDs return -`unrelated`; same heads return `equal`; if a.head is in b's ancestry return `behind`; -if b.head is in a's ancestry return `ahead`; otherwise return `diverged`. These names -describe a relative to b. Invalid/unsupported inputs return an error, not a relation. -Matching IDs with unequal subjects would be a hash failure and MUST NOT be reconciled. - -`open({ anchor })` accepts a previously verified full snapshot (minimum alpha anchor; -checkpoints are deferred). Compare candidate to anchor: equal/ahead may proceed; -behind yields `STALE_HEAD`, diverged yields `DIVERGED_HEAD`, unrelated yields -`DOCUMENT_MISMATCH`. Keep integrity valid and return inspection. Supplying only an -unknown head cannot prove ancestry; alpha does not pretend it can. No implicit -anchor is inferred from a timestamp or storage revision. diff --git a/docs/concord/conformance.md b/docs/concord/conformance.md deleted file mode 100644 index df2877b..0000000 --- a/docs/concord/conformance.md +++ /dev/null @@ -1,208 +0,0 @@ -# Alpha conformance and delivery gates - -Shipping update, 2026-11-20: independent groups and readable coverage are implemented. -The [group matrix](group-profile-design.md#6-concrete-scenario-and-acceptance-matrix) -remains the scenario checklist; [implementation and evidence locations](../engineering/independent-groups-2026-11-20.md) -identify tests and fixed-vector provenance. The current vectors use the accepted -common Ledger container; earlier Concord-only wire hashes are superseded. Draft -gates are implemented; B12 supplies reusable storage/conflict reference checks. The -library release does not require the deferred board application. - -Status: implementation acceptance contract, 2026-10-21. Case IDs are stable test -names. A coding agent implements these as one-shot tests crossing the public interface; -private helpers may isolate crypto diagnostics but cannot replace observable checks. -The [vector artifacts](vectors/README.md) contain fixed bytes independent of the -candidate implementation. This document also specifies cases not yet executed. - -## Error contract - -`ErrorCode` is the union of the codes in this table. An error has the shape defined -in the [blueprint](implementation-blueprint.md). Expected errors never throw, change -the committed head, clear a draft, or expose partial projection. Invalid opened -artifacts stay inspectable/exportable. For unexpected host exceptions, sanitize the -message; a private host diagnostic callback may receive the cause, but it is never -part of a document or public report. Alpha has no default logging callback. - -| Codes | Phase / meaning | -| --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -| `JSON_INVALID` | input / malformed UTF-8/JSON, duplicates, invalid value domain | -| `SCHEMA_INVALID` | protocol / known version with missing/extra fields, invalid encoding or shape | -| `PROTOCOL_UNSUPPORTED`, `SUITE_UNSUPPORTED`, `ENTRY_KIND_UNSUPPORTED`, `RESOURCE_LIMIT` | protocol / cannot evaluate with this implementation or configured limits; integrity unsupported | -| `DUPLICATE_RECORD`, `UNREFERENCED_RECORD`, `ENTRY_MISSING`, `ENTRY_ORDER` | protocol / container membership/reference/order failure | -| `HASH_MISMATCH`, `LINK_INVALID`, `DECLARATION_INVALID`, `HEAD_INVALID` | protocol / subject IDs, parent chain, genesis declarations, or selected identifiers inconsistent | -| `IDENTITY_INVALID`, `SIGNATURE_INVALID` | protocol / malformed identity binding/point or failed strict signature check | -| `REQUIREMENT_UNAVAILABLE`, `HOST_CONFIGURATION`, `IDENTITY_MISMATCH` | requirements / no exact implementation, invalid host definition, reader/signer mismatch | -| `STALE_HEAD`, `DIVERGED_HEAD`, `DOCUMENT_MISMATCH`, `ANCHOR_INVALID` | protocol / valid candidate fails external freshness check, or supplied anchor cannot be verified | -| `SYSTEM_EVENT_INVALID`, `SYSTEM_NO_CHANGE`, `LAST_ADMINISTRATOR` | system / malformed transition, no-op member set, removal/demotion of last administrator | -| `UNSUPPORTED_SYSTEM_EVENT` | system / unknown type/version or profile event not yet implemented; incompatible inspection | -| `CAPABILITY_DENIED` | system / historical or current actor lacks required authority | -| `READ_ACCESS_REQUIRED`, `KEY_UNAVAILABLE` | system / full-replay model requires unavailable events or no reader; locked inspection | -| `KEY_WRAP_INVALID`, `DECRYPTION_INVALID`, `EVENT_CONTEXT_INVALID` | system / decryptable-addressed wrap invalid, ciphertext authentication failure with available key, or decrypted contextual mismatch | -| `HISTORICAL_KEY_UNAVAILABLE` | author / cannot author admission carrying every epoch key | -| `COMMAND_UNSUPPORTED`, `COMMAND_INVALID`, `COMMAND_REJECTED`, `NO_EVENTS` | author / command absent, validation failure, domain decision rejection, or empty emitted event list | -| `EVENT_UNSUPPORTED`, `EVENT_INVALID`, `MODEL_TRANSITION_INVALID`, `MODEL_FAILED` | model / unknown event/version, event validation failure, reducer rejection/non-JSON state, or unexpected model exception | -| `SYSTEM_FAILED` | system / unexpected trusted profile exception | -| `READ_ONLY_RUNTIME`, `INSPECTION_ONLY`, `NO_DRAFT`, `DRAFT_PENDING` | author / lifecycle precondition failure | -| `SIGNING_FAILED`, `ENCRYPTION_FAILED` | author / primitive failure creating candidate; no committed mutation | -| `STORAGE_FAILED`, `HEAD_CONFLICT` | storage / adapter failure or expected-head mismatch; local history retained | - -Ledger validates signer identity through Identity: malformed identity shape, encoding, -point or key-ID binding gives IDENTITY_INVALID. Wrong-length/noncanonical signature -encoding is SCHEMA_INVALID; a well-sized signature with invalid R/S/equation is -SIGNATURE_INVALID. Verification stops at the first failure in the protocol's declared phase order. A missing root parent -record is LINK_INVALID, missing listed entry ENTRY_MISSING. HEAD_INVALID covers wrong -documentId/head selectors; DECLARATION_INVALID covers declaration placement. Unknown -model event is incompatible application, invalid event data or transition is invalid -application. Neither changes `integrity: valid`. System invalidity likewise does not -retroactively invalidate signatures. - -`open` reason precedence is invalid protocol, incompatible protocol, unavailable -requirements, freshness, invalid/unsupported system, locked, then model failure. -Known system authority/event failure gives reason invalid; unsupported event gives -incompatible. Unavailable events give locked for a full model; an opted-in model may publish readable/scoped coverage. Model unknown event gives incompatible; -other model failure gives invalid. Report which layer failed. A fresh valid candidate -without an anchor reports freshness unanchored, never fresh/latest. Input parse errors -use integrity invalid, checked counts zero, no trusted history, and reason invalid. - -## P: bytes, schema, and integrity (first slice) - -| ID | Input/action | Required observation | -| --- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- | -| P01 | Every positive canonical case in primitives.json | Exact canonical string, UTF-8 bytes and key order | -| P02 | Every rejected JSON case; BOM; malformed UTF-8; trailing bytes | JSON_INVALID before crypto; raw bytes retained | -| P03 | Unsafe JS values, NaN, Infinity, -0, sparse array, accessor, custom prototype, cycle | Author input rejected without invoking accessors or signing | -| P04 | Padded/non-URL base64, nonzero unused bits, uppercase hash, wrong byte length, extra field | SCHEMA_INVALID; no normalization | -| P05 | Fixed Identity seed and supplied conversion outputs | Exact public identity ID, private/public X25519, age strings, RFC8032 empty-message signature | -| P06 | Identity ID changed with correctly rebound commit hashes/signatures | IDENTITY_INVALID; ID cannot select another key | -| P07 | Small/mixed-order public point, non-canonical point; signature R small-order or S >= L | Strict rejection, independent of crypto library permissive defaults | -| P08 | owner.document.json and expected bytes | Two entry IDs, two commit IDs, exact signature messages/signatures, valid protocol report | -| P09 | Change child signed metadata without changing its ID | HASH_MISMATCH; no reducers invoked | -| P10 | Change child signature only, retaining length/canonical encoding | SIGNATURE_INVALID | -| P11 | Remove referenced entry; repeat entry/commit; append detached record | ENTRY_MISSING; DUPLICATE_RECORD; UNREFERENCED_RECORD respectively | -| P12 | Swap physical entries but preserve commits | ENTRY_ORDER | -| P13 | Reorder ordered entry IDs in a multi-event commit without rehashing | HASH_MISMATCH; after rehashing but not signing, SIGNATURE_INVALID | -| P14 | Rehash/re-sign child with wrong parent, or entry parent not equal child parent | LINK_INVALID; valid signatures cannot repair linkage | -| P15 | Duplicate/missing genesis, missing/malformed genesis `metadata.concord` declaration, wrong head/doc ID | No trusted state; appropriate duplicate/link/declaration/head code | -| P16 | Unknown suite/protocol; exceeded resource/depth limit | Unsupported inspection, not a claim of invalid cryptography | -| P17 | Transport whitespace/key-order changes only | Same history IDs/signatures; canonical export stable; signed metadata changes remain P09 | -| P18 | Signed genesis profile/model ref unknown to host | Protocol valid; REQUIREMENT_UNAVAILABLE on open; no automatic module load | -| P19 | Large bounded arrays and attacker keys such as **proto** | Bounded parser behavior, no prototype mutation, no unchecked recursion | - -P13's two-event input is constructed by repeating the register command twice in draft -mode in Step 4; before then use the protocol helper with two saved valid entry subjects -bound to the same parent. No reissuing commands to establish replay determinism. - -## C: lineage and anchors (first slice) - -| ID | Inputs | Required observation | -| --- | ------------------------------------------------------- | -------------------------------------------------------- | -| C01 | Same snapshot, including transport formatting variants | equal | -| C02 | Genesis compared to child and child compared to genesis | behind; ahead | -| C03 | owner compared to owner.fork | diverged in both directions, both integrity-valid | -| C04 | Two independently created genesis documents | unrelated | -| C05 | Any comparison containing invalid/unsupported bytes | Error, never equal/diverged | -| C06 | Open child anchored to genesis / same child | Ready; freshness ahead / equal | -| C07 | Open genesis anchored to child | Freshness inspection, STALE_HEAD, integrity valid | -| C08 | Open fork anchored to child / unrelated anchor | DIVERGED_HEAD / DOCUMENT_MISMATCH; no model replay | -| C09 | Open older valid snapshot with no anchor | Integrity valid; unanchored; no false rollback detection | -| C10 | Malformed/invalid anchor | ANCHOR_INVALID; candidate cannot become ready | - -## R: create, commit, export, open, verify, replay, inspect (first slice) - -| ID | Action | Required observation | -| --- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -| R01 | Create register with owner and standard profile | One signed genesis/init; owner all four rights; initial { value: "" }; ready | -| R02 | Immediate set({value:"hello Concord"}) | Exactly one child commit and event; ready value; storage not invoked | -| R03 | Export then open with model/profile/owner | Same doc ID/head, committed value, no private material or projection in wire | -| R04 | Verify export without model/profile/reader | Integrity valid independently; no extension execution | -| R05 | Replay identical saved export twice, then new open | Equal projections and reports; no fresh key/time/ID generation during replay | -| R06 | Open owner.document using public test seed | Matches literal expected projection, IDs, event plaintext and key material derivation | -| R07 | Open without reader or with unrelated reader | Full model locked: READ_ACCESS_REQUIRED without reader, KEY_UNAVAILABLE for missing keys; no projection/writes | -| R08 | Open with authorized decrypt-only reader | Ready same projection, canWrite false; all mutations READ_ONLY_RUNTIME | -| R09 | Tampered reachable record | Invalid inspection, no model calls, raw evidence/report available | -| R10 | Omit or mismatch required model/profile | Incompatible inspection, exact missing refs; integrity remains independently verifiable | -| R11 | Correctly sign event encrypted to wrong epoch key or corrupt age bytes and rehash/sign | Integrity valid, DECRYPTION_INVALID with available expected key; no projection | -| R12 | Correctly sign decryptable plaintext with wrong parent/nonce/model/epoch | EVENT_CONTEXT_INVALID, not a reducer error | -| R13 | Valid signed unknown event, invalid data, reducer rejection/throw | EVENT_UNSUPPORTED / EVENT_INVALID / MODEL_TRANSITION_INVALID / MODEL_FAILED; no partial publish | -| R14 | Unknown command, invalid input, decision rejection, empty event list | Specific author error, same export/projection; no new commit | -| R15 | Inject sign/encrypt failure or candidate replay failure | Specific error; previous export, projection, draft unchanged | -| R16 | Parallel dispatch calls; reads while encryption awaits | Invocation order, parents chained correctly; reads see last published state | -| R17 | Mutate caller input bytes, returned bytes, projection or reports | Internal snapshot/history/projection unaffected | -| R18 | Replay on ready handle, verify on inspection, export malformed input | No bypass or upgrade of trust; original bytes remain available | -| R19 | Genesis init owner mismatch; missing/wrong owner wrap; duplicate init | Integrity can be valid; SYSTEM_EVENT_INVALID or KEY_WRAP_INVALID; no ready state | -| R20 | No-command genesis opened without reader | Locked, lockedEntries 0, no projection; owner is still private-profile member | - -For R11–R13/R19, an offline fixture builder must explicitly rehash affected entries, -rebuild ordered commit subjects, re-sign using public test seeds, and rebind head/doc -IDs as needed. Changing ciphertext alone without this process tests protocol integrity, -not system/model validation. Keep encryption plaintext contexts consistent except the -specific field under test. Reference outputs remain literal fixture files, not values -computed by the production verifier under test. - -## D and S: grouped authoring and complete standard profile (Step 4) - -B05 implements D01–D05 and cross-group command batches. Drafts remain in memory; -[ADR 0019](../adr/0019-keep-draft-persistence-with-consumers.md) keeps persistence and -recovery with consumers. - -| ID | Action | Required observation | -| --- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | -| D01 | Two successful draft sets | Original head/projection unchanged, preview latest value, two staged intents | -| D02 | Commit with {message:"Group edits"} | One new commit, ordered entries, signed metadata, cleared draft | -| D03 | Fail second draft command / fail commit signing or replay | First draft retained / entire draft retained; no committed change | -| D04 | Export/reopen while drafting | Only committed history reopens; no staged keys or data in artifact | -| D05 | Discard, empty commit, system action while drafting | Preview discarded; NO_DRAFT; DRAFT_PENDING | -| S01 | Owner adds viewer, editor; grants full history | Both reconstruct exact prior projection with their own capability | -| S02 | Viewer application write / editor grant / grant-only actor granting administer | CAPABILITY_DENIED in authoring and equally in forged signed history | -| S03 | Owner grants bounded grant privilege; delegate adds editor | Delegation follows exact subset/target rules; no privilege amplification | -| S04 | Set same rights, remove absent member, demote/remove last administrator | SYSTEM_NO_CHANGE, SYSTEM_EVENT_INVALID, LAST_ADMINISTRATOR | -| S05 | Remove editor after its earlier valid task event | Earlier authority remains valid; future epoch has exactly remaining members; old epoch not rewritten | -| S06 | Removed editor appends after removal | CAPABILITY_DENIED; retained history stays readable but old keys do not unlock future epochs | -| S07 | Removed editor appends from pre-removal parent | Valid separate variant; diverged from revocation head; no automatic merge or ordering | -| S08 | Add reader after several removals/epochs | Explicit wraps for every historical epoch; full reconstruction; unavailable author key blocks admission atomically | -| S09 | Malformed host-addressed wrap; missing/reordered/duplicate member wraps | KEY_WRAP_INVALID / SYSTEM_EVENT_INVALID; do not certify other recipients' encrypted plaintext | -| S10 | System removal then application in same signed commit | New epoch required; actor rights evaluated per position; removed actor cannot authorize a later commit | -| S11 | Self-removal while another administrator remains | SYSTEM_EVENT_INVALID; original head/projection unchanged; a different administrator can remove the identity | -| S12 | Add identity after its removal, or disable write while retaining read | Re-admission carries all epochs; readable history and current canWrite remain independent | - -## B and T: board and actual package consumers - -B01 replays every board command/event in the blueprint with literal before/after -projections. B02 rejects duplicate IDs, invalid movement targets, stale task references, -unknown columns, unknown assignees, malformed data, and edits to archived tasks both -at decision and reducer seams. B03 proves viewer/editor/owner presets compile to system -rules. B04 runs the full board walkthrough with saved artifacts and divergent heads. -B05 proves expected-head write checks atomically: two candidates use the same expected -head, exactly one succeeds, the other returns HEAD_CONFLICT and remains exportable. -B06 reopens publication, simulates failed write, and proves no draft persistence. These storage -observations are implemented independently of the deferred board model in -`test/storage.test.ts`; see [the boundary contract](storage-boundary.md). The new -in-memory expected-head proof covers writers sharing one store instance, not a -production provider or a cross-process update transaction. - -T01 checks every exported JS/types path exists in packed tarballs. T02 installs the -exact candidate set in an isolated consumer outside the workspace, imports every public -subpath, typechecks typed command success plus expected compile-time errors, and runs -the owner lifecycle. No aliases, sibling-source imports, registry predecessor fallback, -or ambient workspace hoisting. T03 imports protocol alone without loading Armour, -models, runtime, framework, or Seal; assert the dependency closure. T04 exercises -Identity/Armour standalone and both directions of native age interop. T05 runs the -Node 22/24 and pinned browser fixtures and rejects accidental Node globals in browser -outputs. T06 validates required scripts, true one-shot test failure statuses, declaration -dependencies, workspace range rewriting, assets, and release dependency order. - -## Evidence and completion reporting - -The supplied reference artifacts were checked with Node crypto and native age, -independently of the runtime. See [the vector README](vectors/README.md) for exact -coverage. Current library completion requires applicable P/C/R/D/S/T and storage cases through -public interfaces. B01–B04 remain deferred board examples; the library release does -not require that application. Run outcomes belong to the -[acceptance reports](../engineering/repository-hygiene.md#acceptance-boundaries); -release delivery has its own [backlog](../engineering/release-and-deployment.md#release-backlog). - -Record formatter, lint, typecheck, behavior, build, packed-consumer, and browser results -separately. Record runtime/tool versions and elapsed scope before making feedback-speed -claims. Existing legacy failures, introduced failures, and unverified checks get separate -lines. Never replace a fixed expectation with a value produced by the candidate merely -to get a passing test. Changes to vectors are protocol/model changes requiring review. diff --git a/docs/concord/context.md b/docs/concord/context.md deleted file mode 100644 index 90cfa6a..0000000 --- a/docs/concord/context.md +++ /dev/null @@ -1,142 +0,0 @@ -# Concord project brief - -Current scope, 2026-11-21. This brief records the accepted product direction and -repository boundaries. [AGENTS.md](../../AGENTS.md) owns the working agreement; -[CONTEXT.md](../../CONTEXT.md) defines the domain language. In a conversation without -repository access, supply those files with this brief. They are context, not a -separate running agent or background process. - -## Purpose and ethos - -Concord supports small, user-owned applications whose durable state is a portable -signed document. Keep the history, sign contributions, replay it into application -state, and let consumers decide where it lives. The -[original Ledger](https://github.com/ternent/ledger/tree/76f857338d209f0d512c0ba66ed31ad13f5e6432/packages/ledger) -is a reference for that ethos, not a requirement to preserve every old mechanism -or wire format. - -Signed history is authoritative; projections are derived. A document can move -between storage providers and be verified independently. Interpreting its application -meaning additionally requires conforming model/system implementations and any -required keys. The host selects trusted executable code; documents never load code. - -The [alpha architecture](alpha-architecture.md), -[current protocol](alpha-protocol.md) and -[standard profile](standard-profile.md) define the accepted framework. The -[repository guide](../engineering/repository-hygiene.md) describes actual package -and acceptance scope. Recheck dated evidence before making readiness claims. - -## Five public libraries - -| Library | Responsibility | -| -------- | ------------------------------------------------------------------------------------------------------- | -| Identity | Public identities, private capabilities, signing, recovery helpers and key conversion | -| Armour | age-compatible encryption through typage (`age-encryption`) and explicit payload codecs | -| Ledger | Standalone common signed container, staging, commit construction, verification and ordered replay | -| Concord | Commands/previews, authority, independent encrypted groups and application replay composed above Ledger | -| Seal | Independent proof, artifact and manifest formats, public APIs and Node CLI | - -[ADR 0018](../adr/0018-use-one-ledger-container-for-concord.md) assigns the container -and history lifecycle to Ledger. Concord uses that same container and delegates -commit construction; it has no competing signed history engine. The previous -Concord alpha format deliberately breaks, with no legacy importer included. - -Ledger has no Armour dependency, recipient management or automatic decryption. -Its optional payload helpers compose explicitly with an external codec. Concord -owns framework authority, group protection and decryption before model replay. - -## Product decisions to preserve - -- Application models define typed commands, validated domain events and pure reducers. - A document declares one bounded model. Identical history, conforming implementations - and available capabilities must reconstruct the same projection. Time, randomness - and external reads belong in authored inputs, not replay. -- Immediate signed commits are the default. Draft mode groups command intents before - an explicit commit. Ledger staging and Concord intents stay in memory; consumers - choose commit cadence and own any draft autosave/recovery under - [ADR 0019](../adr/0019-keep-draft-persistence-with-consumers.md). -- Storage publication is separate from local commits. Ordinary exports contain - committed history. Storage supplies bytes, not trust. The - [storage contract](storage-boundary.md) preserves failed local work and surfaces - head conflicts without silently choosing or combining divergent histories. -- Each snapshot selects one head. Signatures establish integrity and authorship, - not global consensus, freshness or completeness. A remembered head or another - external anchor is needed to detect rollback or withheld variants. -- The default `document` group and additional groups have independent memberships - under [ADR 0015](../adr/0015-keep-audience-memberships-independent.md). Removing - default membership does not revoke unrelated group access. Group owners do not - gain automatic access to other groups. Admission/readmission grants that group's - history; removal rotates its future key without erasing retained keys or plaintext. -- System replay establishes authority and decryptability before application replay. - Invalid history cannot publish trusted state. Models that require every event stay - locked when some are unavailable; opted-in readable views expose locked markers, - coverage and counts. Scoped coverage never certifies hidden application semantics. -- Encrypt application content, group titles and descriptive metadata wherever the - design permits. Every public envelope field needs a verification, key-discovery or - interoperability reason. Minimise public membership, grant-recipient identities - and correlating group references where authority and key discovery permit. - Current encryption does not conceal all membership, author, linkage, size or - activity metadata; do not claim otherwise. -- Keep access honest. If a holder can read data from the raw document or decrypt it - with their keys, an application should provide access to it. UI filtering is not - confidentiality. Distinguish readable, locked, unverified and trusted information; - inspection of evidence does not grant authority or a trusted projection. - -## Current repository and delivery scope - -The active workspace contains exactly the five public libraries above. Portable -Tooling is not a public product. The tooling package/profile fixtures, handshake app, -VitePress patch, copied legacy implementations, Utils and obsolete publishers were -removed under [ADR 0020](../adr/0020-simplify-core-around-five-libraries.md). -Git preserves their history. Ledger remains an active standalone library. - -UI is dropped from this release under -[ADR 0017](../adr/0017-drop-ui-from-the-library-release.md). Workspace is deferred: -it is not live, and its existing sources/edits do not block the libraries. Applications -and demos belong outside core and follow stable libraries and their delivery setup. -Do not make Workspace cleanup or an application port a library prerequisite. - -Candidate checks install all five exact tarballs through an isolated registry. -Release planning, collision detection, retryable publication and Seal bundle -verification are implemented. Read-only CI exercises the pinned Seal Action with a -disposable test identity. Production workflow wiring, release identity/trust setup -and public-registry acceptance remain on the -[release backlog](../engineering/release-and-deployment.md). No package publication -or deployment follows merely from merging or tagging this branch. - -Performance on representative workloads remains an open follow-up. Measure a workload -envelope and consider incremental replay under the -[replay performance follow-up](../engineering/repository-hygiene.md#replay-performance-follow-up). -Incremental replay/checkpoints are not implemented. A second complete implementation -or external protocol/security review remains future assurance work; it is deferred -from the current task, not evidence already obtained. - -## Repository map - -| Area | Starting point | -| --------------------------------------------------- | --------------------------------------------------------------- | -| Signed container, verification, staging and commits | `packages/ledger/src/` | -| Framework lifecycle, drafts and atomic publication | `packages/concord/src/runtime.ts` | -| Host/model replay validation | `packages/concord/src/runtime/` | -| Authority, groups and key distribution | `packages/concord/src/system/` | -| Memory storage/conflict reference | `packages/concord/src/testing/` | -| Package inventory and setup/checks | `pnpm-workspace.yaml`, [CONTRIBUTING.md](../../CONTRIBUTING.md) | -| Candidate checks and release planning/publication | `scripts/verify/`, `scripts/release/` | - -Our [toolchain engineer profile](../engineering/developer-archetype.md) guides -engineering practice: explicit checks, useful diagnostics and measured feedback. -Use current reports and retained artifacts as evidence for their own revision; -configured checks and older successful runs do not certify newer edits. - -## Application reference and earlier work - -The [todo application in samternent/home](https://github.com/samternent/home/blob/main/apps/concord-demo/src/route/workspace/WorkspaceTodo.vue) -supplies useful behavioural requirements: tasks/lists, assignments and independently -shared private groups inside one document. Keep that multi-tenant, entry-level -encryption story; separate documents for each group would change the demonstration. -The reference is not proof that every historical security mechanism is correct. - -Earlier migration inventories, test counts and the retired handshake pilot are in -Git history. They do not describe the active workspace or establish compatibility -with the current container. The current package READMEs, normative contracts and -revision-bound acceptance reports are the starting points for implementation work. diff --git a/docs/concord/examples/independent-groups.json b/docs/concord/examples/independent-groups.json deleted file mode 100644 index b79627e..0000000 --- a/docs/concord/examples/independent-groups.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "format": "concord.design.scenario", - "version": 1, - "status": "proposed-expectations-not-a-signed-vector", - "actors": ["owner", "alice", "bob"], - "audiences": { - "default": "document", - "accounts": "group:AAAAAAAAAAAAAAAAAAAAAA", - "personal": "group:AQEBAQEBAQEBAQEBAQEBAQ" - }, - "notes": "Audience labels, actor names and entry labels are scenario notation, not public wire metadata. Fixed group IDs are fixture-only. Every successful operation is one immediate commit; denied operations leave history unchanged.", - "operations": [ - { "by": "owner", "action": "createDocument" }, - { - "by": "owner", - "action": "setMember", - "audience": "default", - "identity": "alice", - "capabilities": ["read", "write"] - }, - { "by": "owner", "action": "append", "audience": "default", "entry": "shared-0" }, - { "by": "alice", "action": "createGroup", "audience": "accounts" }, - { "by": "alice", "action": "createGroup", "audience": "personal" }, - { "by": "alice", "action": "append", "audience": "accounts", "entry": "accounts-0" }, - { "by": "alice", "action": "append", "audience": "personal", "entry": "personal-0" }, - { - "by": "alice", - "action": "setMember", - "audience": "accounts", - "identity": "bob", - "capabilities": ["read", "write"] - }, - { - "by": "owner", - "action": "setMember", - "audience": "accounts", - "identity": "owner", - "capabilities": ["read", "write", "grant", "administer"], - "expectedError": "CAPABILITY_DENIED" - }, - { "by": "owner", "action": "removeMember", "audience": "default", "identity": "alice" }, - { "by": "owner", "action": "append", "audience": "default", "entry": "shared-1" }, - { "by": "alice", "action": "append", "audience": "accounts", "entry": "accounts-1" }, - { "by": "alice", "action": "createGroup", "expectedError": "CAPABILITY_DENIED" }, - { "by": "alice", "action": "removeMember", "audience": "accounts", "identity": "bob" }, - { "by": "alice", "action": "append", "audience": "accounts", "entry": "accounts-2" }, - { - "by": "bob", - "action": "append", - "audience": "accounts", - "expectedError": "CAPABILITY_DENIED" - }, - { "action": "observe", "checkpoint": "before-readmission" }, - { - "by": "alice", - "action": "setMember", - "audience": "accounts", - "identity": "bob", - "capabilities": ["read", "write"] - }, - { "action": "observe", "checkpoint": "after-readmission" } - ], - "expected": { - "before-readmission": { - "currentEpochs": { "default": 1, "accounts": 1, "personal": 0 }, - "owner": { - "readable": ["shared-0", "shared-1"], - "locked": ["accounts-0", "personal-0", "accounts-1", "accounts-2"], - "coverage": "readable" - }, - "alice": { - "readable": ["shared-0", "accounts-0", "personal-0", "accounts-1", "accounts-2"], - "locked": ["shared-1"], - "coverage": "readable" - }, - "bob": { - "readable": ["accounts-0", "accounts-1"], - "locked": ["shared-0", "personal-0", "shared-1", "accounts-2"], - "coverage": "readable" - } - }, - "after-readmission": { - "currentEpochs": { "default": 1, "accounts": 1, "personal": 0 }, - "bob": { - "readable": ["accounts-0", "accounts-1", "accounts-2"], - "locked": ["shared-0", "personal-0", "shared-1"], - "coverage": "readable" - }, - "bobKeyEpochs": { "accounts": [0, 1] }, - "bobMembership": { "default": false, "accounts": true, "personal": false } - } - } -} diff --git a/docs/concord/group-profile-design.md b/docs/concord/group-profile-design.md deleted file mode 100644 index ff80c7b..0000000 --- a/docs/concord/group-profile-design.md +++ /dev/null @@ -1,393 +0,0 @@ -# Independent groups and readable replay - -Status: implemented B03/B04 design rationale, 2026-11-20. Independent membership and -one audience per command are accepted in [ADR 0015](../adr/0015-keep-audience-memberships-independent.md) -and [ADR 0016](../adr/0016-route-each-command-to-one-audience.md). The normative -[standard profile](standard-profile.md) and runtime/model types now implement these -interfaces. The acceptance matrix remains a scenario checklist; executed evidence -is recorded in [the implementation note](../engineering/independent-groups-2026-11-20.md). - -## 1. Scope and evidence - -Keep one signed document and one bounded application model. System extensions own -group authority, key distribution and decryption; models own application meaning. -Identity/Armour continue to own the cryptography. No new package, global membership -layer, transport, merge, anonymous envelope or trial-decryption routing is needed. - -The relevant existing code is `packages/concord/src/system/{standard,membership, -audience,authoring}.ts`, `src/{runtime,model/types,protocol/types}.ts`, and the -legacy behavior in `packages/workspace/src/{plugins/permissions,runtime/privacy}.ts`. -The latter creates independent group keys and encrypted grants but does not rotate -on removal. Reuse the current standard profile's stronger validation/rotation rules. - -### Accepted behavior - -- `document` is the default group. Each additional group has independent authority - and keys. Membership in the default group is not required to join another group. -- Default-group writers may create groups without approval. Document ownership - gives no automatic access or administration in those groups. -- Admission and re-admission give full group history. Removal rotates only that - group's future key. Retained historical access remains readable. -- System replay completes before model replay. Raw readable content must be - accessible; locked markers do not certify hidden application semantics. -- Signed-history integrity, signer binding, atomic publication, read-only handles, - deterministic replay and explicit divergence remain mandatory. - -### Implementation choices - -Reuse the existing four capabilities and membership rules per audience. Keep group -titles/descriptions in encrypted application events rather than adding system -profile policy. Add an explicit model hook for locked entries; models that require -all events continue to return locked inspection when any event is unavailable. - -This is a pre-release revision of the intended v1 contract. No old/new runtime -compatibility layer is requested. Authoring still declares -`{ id: "concord.standard", version: 1 }` and uses the existing suite/container/hash -domains. The normative profile/protocol/model docs are revised together. Existing fixed single-audience vectors remain unchanged where their -bytes still satisfy the revised contract; do not regenerate them just to pass. -Old executables need not understand new groups; no interoperability claim is made. - -## 2. Audience identifiers and authority - -```ts -type GroupId = `group:${string}`; // "group:" + B(16 CSPRNG bytes) -type AudienceId = "document" | GroupId; -type Capability = "read" | "write" | "grant" | "administer"; -``` - -Group identifiers are opaque public routing values with canonical base64url suffixes -of exactly 16 decoded bytes. They carry no label, identity or policy. IDs cannot be -reused within a document. Epochs start at zero independently for each audience. - -| Operation | Required authority immediately before the entry | -| ---------------------------- | ------------------------------------------------------------------------------------------- | -| Create independent group | `write` in `document`; creator receives all four capabilities in the new group | -| Author application event | `write` in the selected audience plus its model-required capabilities | -| Set member | `administer` in that audience, or its existing bounded `grant` rule | -| Remove member | `administer` in that audience; existing target and another administrator must remain | -| Inspect historical plaintext | Possession of the matching historical key; current membership is not a confidentiality gate | - -Every active member has `read`; capability arrays remain unique in the order read, -write, grant, administer. As today, a grant holder can give a subset of read/write -they hold, and cannot change a target with grant/administer. Administrators can set -any nonempty set including read. Unchanged sets fail `SYSTEM_NO_CHANGE`. - -Apply final-administrator protection separately to each audience. Retain the current -self-removal prohibition; another administrator performs removal. There is no group -deletion, implicit ownership transfer, cross-group privilege inheritance or global -revocation operation. Last-administrator demotion/removal fails `LAST_ADMINISTRATOR`; -non-final self-removal fails `SYSTEM_EVENT_INVALID`. - -An Accounts editor can still write Accounts after removal from `document`. They -cannot create another group unless they again have default-group write. Granting -someone default-group administer never grants them authority over Accounts. - -## 3. Minimal wire changes - -Canonical values/encodings, unsigned commit subjects, signatures, chain structure -and one selected head are unchanged. Generalize only the audience routing fields -and the closed system event data needed for independent membership. - -```ts -type ProtectedEvent = { - audience: AudienceId; - epoch: number; - ciphertext: string; // B(binary age), encrypted once to this audience/epoch -}; -type Wrap = { identityId: string; ciphertext: string }; -type HistoricalWrap = { epoch: number; ciphertext: string }; - -// Existing genesis event; exact existing shape retained. -type InitData = { - audience: "document"; - epoch: 0; - recipient: string; - owner: PublicIdentity; - wraps: [Wrap]; -}; -type GroupCreateData = { - audience: GroupId; - epoch: 0; - recipient: string; - wraps: [Wrap]; // only the creator, bound to the containing commit signer -}; -type MemberSetData = { - audience: AudienceId; - identity: PublicIdentity; - capabilities: Capability[]; - history: HistoricalWrap[]; -}; -type MemberRemoveData = { - audience: AudienceId; - identityId: string; - epoch: number; // selected audience's prior epoch + 1 - recipient: string; - wraps: Wrap[]; // exactly this audience's remaining active members -}; -``` - -Events are `system.init`, `system.group.create`, `system.member.set`, and -`system.member.remove`, each with event version 1. All shapes are closed. Unknown -events remain unsupported, never ignored. Group creation after genesis requires a -new GroupId, epoch zero, a fresh recipient and exactly one creator wrap. No group -creation or application entry may share genesis with `system.init`. - -Membership operations must name an existing audience. For admission/re-admission, -`history` has exactly one wrap for every epoch of that audience, in increasing order. -For an existing member's capability change, it is empty. An author missing any -required historical secret fails `HISTORICAL_KEY_UNAVAILABLE` before publication. - -Removal generates a fresh epoch key and wraps it to exactly the remaining members -of that audience, sorted by identity ID. On creation or rotation, reject a recipient -already recorded for any audience/epoch in the document. This detects declared key -reuse across groups; it cannot prove an authorized author kept secrets confidential. -Other audiences and their epochs/wraps are untouched. -Later entries in the same commit observe the changed authority and epoch. - -The key-wrap plaintext retains `context: "concord.audience-key/1"`, parent, nonce, -epoch, identityId, recipient and secret, with `audience: AudienceId`. The application -plaintext likewise retains `context: "concord.application/1"`, parent, nonce, model, -epoch and event, with `audience: AudienceId`. Decryption checks exact canonical bytes -and every context field against the actual envelope. Cross-group ciphertext/wrap -substitution must fail even when a host can decrypt both groups. - -### Public metadata and privacy - -Audience IDs, group creation, signers, membership/capability changes, grant target -identities, epochs/recipients, linkage, sizes/counts and signed commit metadata stay -public so any host can validate the complete authority transitions without keys. -The identifiers link activity within a group; this design does not hide membership -or traffic patterns. Other recipients' wraps remain decryptability-unverified. - -Group labels/descriptions belong to the application model and are encrypted to the -chosen group like any other event. There is no public label field or plaintext -fallback. Ciphertext and public metadata remain inspectable by every holder of the -document. Any model exposing a label outside its group does so deliberately. - -## 4. System replay and truthful coverage - -### Stage A: public authority, then decryption - -1. Verify all reachable protocol history and apply any external freshness anchor. -2. Scan every entry in order, checking group transitions and application outer - audience existence, current epoch and historical signer write authority. Group - creation checks the actor's default-group authority at that position. -3. Record immutable per-entry facts. For an application entry these are its actor, - selected audience, and that actor's capabilities/membership in that audience at - the original entry position. Later grants never retroactively authorize a signer. -4. Process all wraps addressed to the supplied reader across selected history, - including later historical grants and grants made before removal. Validate every - addressed wrap, including repeated admissions. Private keys remain system-private. -5. For every application entry, return exactly one readable event or locked marker - in the same order. With a matching key, authentication/context failure is invalid. - Without the key, mark locked; do not try unrelated keys or treat ciphertext as an - empty event. A missing reader produces locked markers without decryption attempts. - -No current-membership check suppresses historical plaintext that can be decrypted. -Current capabilities still control authoring. A removed member opening a later head -can read old events and see new-epoch events as locked. A later re-admission can -unlock those saved events; it does not alter the old history. - -The runtime validates a total ordered partition of the exact expected application -entry IDs. A profile cannot omit, duplicate, reorder, substitute or invent entries, -misbind actor/audience facts, or return secrets. Public system validation succeeds -for all groups before any model callback, including groups the reader cannot decrypt. - -### Stage B: complete pass over the available stream - -```ts -type SystemFacts = { - actor: PublicIdentity; - audience: AudienceId; - capabilities: readonly Capability[]; // actor in this audience at this position - members: readonly Member[]; // this audience at this position -}; -type ReplayItem = - | { status: "readable"; entryId: EntryId; event: DomainEvent; facts: SystemFacts } - | { status: "locked"; entryId: EntryId; audience: AudienceId; epoch: number; facts: SystemFacts }; -type LockedEvent = { audience: AudienceId; epoch: number }; -// Exhaustive audience-scoped replay output: -type SystemReplay = { - entryFacts: readonly { entryId: EntryId; facts: SystemFacts }[]; - entries: readonly ReplayItem[]; // exhaustive application entries, in order - audiences: readonly { - audience: AudienceId; - members: readonly Member[]; - epochs: readonly { epoch: number; recipient: string }[]; - }[]; - reader: PublicIdentity | null; - session: object; // opaque; secrets remain private to the system implementation -}; -``` - -Model additions: - -```ts -// On each command definition, after input validation and before decide(): -audience?(input: CommandInput): AudienceId; // absent means "document" -// On the model, checked on both authored and replayed readable events: -audience?(event: E): AudienceId; // absent means the default "document" -reduceLocked?(state: Readonly, entry: LockedEvent, - facts: SystemFacts): Result; -``` - -The existing readable-event validate/requirements/reduce path remains. Audience -selection is pure model behavior. A command validates its input, selects one existing -audience, checks current write there, and receives that audience's signer facts in -its decision context. Every emitted event must select the same audience. On replay, -the validated event's selection must equal its public envelope audience. Unknown/ -noncanonical selections or inconsistent emitted-event routing fail before authoring; -they never cause implicit group creation or plaintext downgrade. - -This resolves the otherwise circular need to decide events before discovering which -audience's permission facts to pass into the decision. A single command does not -span audiences in this contract; explicit draft mode groups several commands from -different audiences into one atomic commit. Cross-group domain operations must be -modeled explicitly rather than treated as a runtime migration or permission bypass. -Sam accepted one audience per command on 2026-11-20; see -[ADR 0016](../adr/0016-route-each-command-to-one-audience.md). Moving an item between -groups uses several commands in an explicit draft commit, implemented by B05 after -the B03/B04 group slice. - -An absent `reduceLocked` means the model requires every event. If any entry is locked, -return locked inspection before invoking initial/reducer callbacks. An explicit hook -opts into readable replay and runs once for every locked entry in its original -position. The hook has public facts and the marker, never a fabricated event payload, -reader identity, mutable security map or key. IDs/provenance remain in inspection. - -The model owns cross-group dependencies: it can retain a placeholder, defer a -relationship in its projection, or reject the transition. Runtime does not infer an -application-specific repair or silently ignore a missing target. A hook exception, -invalid result/state or readable-event/model failure aborts the entire pass. Publish -snapshot, projection, inspection and coverage together only after success. - -Public result additions: - -```ts -// Required on every ready state; replay() returns this metadata with projection. -type ReplayCoverage = { coverage: "complete" | "readable"; lockedEntries: number }; -type ProjectionResult = ReplayCoverage & { projection: Readonly }; -// ReadyState includes ReplayCoverage alongside head/projection/canWrite. -// InspectionReport.application gains "scoped" for successful readable coverage. -``` - -`complete` requires zero locked entries; otherwise a successful model pass is -`readable` and application status `scoped`. The same coverage must accompany both -`state()` and `replay()`; there is no bare replay result that implies full coverage. -Integrity `valid` covers complete signed history, while `scoped` does not certify -hidden event data, event types, model-required capabilities or hidden transitions. -An unknown reader with an opted-in model may therefore receive a completely locked, -read-only view; the ordinary full-replay model still receives locked inspection. - -Inspection remains available for raw readable evidence after failure, but must not -label a failed or incomplete model pass as trusted projection. No new universal -raw-decryption/export format is introduced in this design. - -The runtime exposes `InspectionReport.entries: readonly ReplayItem[] | null`: -populate it only after the full system pass succeeds, retain it if the later model -pass fails, and return immutable copies. `null` means a complete system-evaluated -entry stream is unavailable. Entry evidence is distinct from projection and from -sanitized error `details`; do not place plaintext in error messages. Raw failed -protocol/system artifacts remain exportable inspection evidence without certifying -their contents. This lets consumers expose successfully decrypted content even -when they cannot produce an application projection. - -## 5. Authoring interface and failure behavior - -Public `/system` operations: - -```ts -createGroup(handle): Promise>; -setMember(handle, { audience, identity, capabilities }): Promise>; -removeMember(handle, { audience, identityId }): Promise>; -``` - -No actor, raw key, epoch, recipient or ciphertext comes from callers. Group creation -generates its ID/key internally and returns the ID only on success. Application -commands still dispatch through the model; individual emitted events may choose -their command's selected audience only. A grouped commit can contain commands for -different audiences only when the author has the required rights in each. - -Keep immediate system authoring; draft-specific guards are implemented by B05. One operation is one -verified/replayed commit. Failed validation/encryption/signing/replay retains the -previous head, bytes, projection and draft. App commands on a readable view are -permitted only after a successful model pass; the model decides whether visible -state is sufficient, and normal scoped capability checks still apply. Nothing -certifies hidden whole-document model invariants on such a view. - -`canWrite` means a signer has current write in at least -one audience, not permission for every command/group. The standard profile validates -addressed key delivery during replay and requires the current key before protection. -System administration checks -its own privileges, including administer without write, as in the existing profile. -A signer-free handle always rejects mutations. Inspection-only handles cannot author. - -Reuse the current error vocabulary: unsupported event/version → -`UNSUPPORTED_SYSTEM_EVENT`; unknown audience, duplicate group, invalid epoch/wrap -sets → `SYSTEM_EVENT_INVALID`; missing authority → `CAPABILITY_DENIED`; absent -historical author key → `HISTORICAL_KEY_UNAVAILABLE`; malformed addressed wrap → -`KEY_WRAP_INVALID`; available-key authentication failure → `DECRYPTION_INVALID`; -decrypted audience/context mismatch → `EVENT_CONTEXT_INVALID`. A model audience -selection that disagrees with a readable envelope is `EVENT_INVALID`. - -For public transition errors retain the existing precedence: schema/encoding, -actor authority, target existence, no-op, last administrator, self-removal, epoch/ -wrap-set invariants. Never downgrade an invalid addressed wrap or an available-key -decryption failure to locked. Missing keys are locked coverage rather than proof of -an invalid author; `KEY_UNAVAILABLE`/`READ_ACCESS_REQUIRED` still produce locked -inspection where the model requires complete coverage. - -## 6. Concrete scenario and acceptance matrix - -[The saved semantic scenario](examples/independent-groups.json) uses symbolic -identities and labels for readability. It is an operation/expectation plan, not a -signed document, runnable test, ciphertext fixture or independent crypto vector. -Implementation tests must materialize entries once and reopen those exact bytes. - -| ID | Input/action | Observable result | -| --- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| G01 | Default writer Alice creates Accounts and Personal | Two independent audiences/keys; creator administers both; default owner receives neither key automatically | -| G02 | Bob joins Accounts without default-group membership | Complete Accounts history, default/Personal locked; no default write or group creation privilege | -| G03 | Default owner attempts self-grant into Accounts | `CAPABILITY_DENIED`; identical prior head/export/projection | -| G04 | Remove Alice from default while she edits Accounts | Default key rotates; Accounts unchanged; Accounts write succeeds and new group creation fails | -| G05 | Remove Accounts editor Bob | Only Accounts epoch advances; Bob retains prior plaintext/keys and cannot decrypt later Accounts content or write there | -| G06 | Re-admit Bob after multiple Accounts epochs | Every Accounts epoch is wrapped; exact saved history becomes readable, including the interval while absent | -| G07 | Grant holder exceeds its subset or last administrator is removed/demoted | Existing scoped authority/last-administrator errors; no partial mutation | -| G08 | Signed wrong/unknown group, old epoch, wrong recipient set or cross-group context | Public system failure or addressed-wrap/decryption/context failure in its owning stage | -| G09 | Reader has Accounts key but lacks Personal | One ordered readable/locked stream; opted-in model reports readable coverage; full model returns locked inspection | -| G10 | Replay the same snapshot with the same capabilities twice | Identical projection, locked markers/count and coverage; fresh randomized authoring is not compared for equality | -| G11 | Readable model event/hook rejects after earlier successful reductions | No intermediate trusted projection or head; evidence remains inspectable/exportable | -| G12 | Tamper, omit or reorder reachable committed content | Protocol fails before system/model callbacks; no trusted view, including scoped views | -| G13 | Profile drops/duplicates/reorders a locked item or forges its facts | Runtime rejects profile output; exact application-entry partition required | -| G14 | Change a group label | Only encrypted application data changes; system envelope contains no title/description | -| G15 | Forge write after revocation vs fork before revocation | Post-removal authority fails; valid older-parent fork remains divergent with no automatic merge | -| G16 | Corrupt another recipient's encrypted wrap | Public structure can be valid; that recipient later fails on decryption; other hosts report its decryptability unverified | -| G17 | No reader, opted-in model vs full model | All locked/readable-coverage read-only view vs locked inspection; neither exposes fabricated events | -| G18 | Group admin without write grants/removes vs app authoring | Scoped management allowed subject to admin rules; application write denied | -| G19 | Route a command to Accounts, then emit an event routed to Personal | Decision gets Accounts facts; mixed routing fails before encryption/signing and leaves the prior head unchanged | - -Tests for G08/G16 must separate ordinary byte tampering from deliberately re-signed -system-invalid fixtures. Fix expected outputs independently; do not compute an -expectation with the implementation under test. Preserve Node/browser/package import -checks and the fixed Identity/age/protocol vectors. - -## 7. Cost model and implementation handoff - -The default group introduces no outer encryption pass. Every application entry is -encrypted once to one explicitly named audience/epoch. On open, route by public -audience ID; unwrap only host-addressed records. Never trial every group key. - -Group creation adds one key/creator wrap. Admission adds one wrap per historical -epoch of that group; removal adds one fresh epoch and a wrap per remaining member. -Open still verifies full history and decrypts readable entries; repeated membership -facts and full candidate replay can also dominate cost. These are operation counts, -not measured latency or a claim of linear total runtime. Measure history size, epoch -count, membership and reader coverage before introducing cache/incremental replay. - -B03/B04 now implement these transitions, readable/locked output, model hooks and -coverage. Normative profile/protocol/blueprint docs change with the implementation. -Drafts and the [storage conflict proof](storage-boundary.md) are implemented. -[Release delivery](../engineering/release-and-deployment.md#release-backlog) remains -separate. No benchmark, publication or remote verification is implied; the -[implementation note](../engineering/independent-groups-2026-11-20.md) identifies -source tests, fixed evidence and current acceptance-report locations. diff --git a/docs/concord/implementation-blueprint.md b/docs/concord/implementation-blueprint.md deleted file mode 100644 index 014f1fd..0000000 --- a/docs/concord/implementation-blueprint.md +++ /dev/null @@ -1,605 +0,0 @@ -# Concord alpha implementation blueprint - -Current container/ownership revision: [ADR 0018](../adr/0018-use-one-ledger-container-for-concord.md) -and [the Ledger-backed profile](alpha-protocol.md) supersede the Concord-only wire, -signing domains and internal-Ledger ownership described in this earlier plan. -Ledger is a standalone public product. Concord delegates its history lifecycle; -UI and public Tooling are outside the five-product release. - -Shipping update, 2026-11-20: independent memberships, scoped command routing and -readable/locked replay are implemented. [ADR 0015](../adr/0015-keep-audience-memberships-independent.md) -and [ADR 0016](../adr/0016-route-each-command-to-one-audience.md) record the decisions. -The [standard profile](standard-profile.md) defines their wire and replay contract. -Draft authoring is implemented in B05; the reusable storage conflict proof is implemented by B12. - -Status: first-slice contract, 2026-10-21. Identity, Armour and the private immediate -commit/register slice are implemented; [migration evidence](../engineering/alpha-first-slice.md) -records the retained lifecycle and ownership. The former local handshake is retired; -public library consumers preserve its applicable lifecycle/storage checks. Drafts and the reusable storage proof are implemented. The -[accepted architecture](alpha-architecture.md) and ADRs 0001–0005 remain in force. -New decisions are recorded in ADRs 0006–0009. No legacy compatibility is implied. - -Start with this path: - -```text -create -> dispatch/commit -> export -> open -> verify -> replay -> inspect -``` - -`open` already verifies and replays; the explicit verify/replay calls demonstrate -independent verification and repeatability rather than required extra loading steps. -The normative details are split by ownership: - -| Contract | Source | -| -------------------------------------------------------------- | ----------------------------------------------------------------------------------- | -| Signed wire schema, canonical bytes, IDs, signatures, ancestry | [Protocol 1](alpha-protocol.md) | -| Bootstrap, authorization, group keys, two-stage system replay | [Standard profile 1](standard-profile.md) | -| Fixed artifacts and observable success/failure checks | [Conformance](conformance.md) and [vectors](vectors/README.md) | -| Runtime, typed models, module ownership, delivery | This blueprint | -| Published artifact and feedback gates | [Repository acceptance](../engineering/repository-hygiene.md#acceptance-boundaries) | - -If an implementation requires a new wire field or new security interpretation, -change these documents and vectors deliberately before coding that behavior. Package -versions and the wire/model/profile versions are separate numbers. - -## 1. First slice and exact model - -The first application is a register, not yet the board. It exercises every lifecycle -seam without task policy. Its ref is `{ id: "concord.example.register", version: 1 }`. -Initial projection is `{ value: "" }`. Its only command `set` accepts exactly -`{ value: string }`, with value at most 4096 UTF-8 bytes (empty is allowed). Unknown -fields and invalid Unicode fail `COMMAND_INVALID`. It emits exactly one event -`{ type: "value.set", version: 1, data: { value } }`. Event validation uses the same -closed data shape and bound; unknown type/version gives `EVENT_UNSUPPORTED`. -The reducer replaces value; the model requires write and audience `document`. -Setting the same value still emits an event and commits; no hidden deduplication. - -Create selects the standard profile and this model, generates a fresh epoch-0 key, -and signs a genesis containing only `system.init`. The resulting projection is the -model initial state. The first set creates one application entry and a child commit. -Export transfers committed history only. Open with the same identity capability -must reproduce the value. Open without a reader returns locked inspection, even -if there are no application entries yet. Open with a decrypt-only capability returns -ready but read-only. No storage, framework, clock, network, or UI is required. - -The first consumer fixture should read like this; `registerModel` is the exact model -above, supplied by `/testing`, not application logic bundled into the runtime entry: - -```ts -import { createDocument, openDocument } from "@ternent/concord"; -import { createStandardSystemProfile } from "@ternent/concord/system"; -import { registerModel } from "@ternent/concord/testing"; -import { generateIdentity } from "@ternent/armour"; - -const identityResult = await generateIdentity(); -if (!identityResult.ok) throw new Error(identityResult.error.message); -const identity = identityResult.value; -const system = createStandardSystemProfile(); -const created = await createDocument({ model: registerModel, system, identity }); -if (!created.ok) throw new Error(created.error.message); -const handle = created.value; -const committed = await handle.dispatch("set", { value: "hello Concord" }); -if (!committed.ok) throw new Error(committed.error.message); -const bytes = handle.export(); -const reopened = await openDocument({ bytes, model: registerModel, system, signer: identity }); -const report = await reopened.verify(); -const replayed = await reopened.replay(); -const inspection = reopened.inspect(); -// Assert report.integrity === "valid", replayed value and committed head; -// assert inspection has no findings. Use the conformance cases for failure paths. -``` - -## 2. Application-facing interface - -New interfaces replace the legacy `createConcordApp` surface in the clean alpha; -do not layer another runtime around Workspace. Code here is the target TypeScript -contract. Wire structures are defined in the protocol; their public types are -re-exported where callers need them. - -```ts -type Result = { ok: true; value: T } | { ok: false; error: E }; -type ConcordError = { - code: ErrorCode; // closed union in conformance.md - phase: "input" | "protocol" | "requirements" | "system" | "model" | "author" | "storage"; - message: string; // explanatory, not a stable assertion target - path?: string; // JSON pointer into input; stable when a record exists - commitId?: CommitId; - entryId?: EntryId; - details?: Readonly; // never keys, decrypted data, or secrets -}; -type ReplayCoverage = { coverage: "complete" | "readable"; lockedEntries: number }; -type ProjectionResult = ReplayCoverage & { projection: Readonly }; -type ReadyState = ReplayCoverage & { - status: "ready"; - documentId: CommitId; - head: CommitId; - projection: Readonly; - canWrite: boolean; -}; -type InspectionState = { - status: "inspection"; - reason: "invalid" | "locked" | "incompatible" | "freshness"; -}; -type CommitReceipt = { status: "committed"; head: CommitId; entryIds: readonly EntryId[] }; -type DraftReceipt = { status: "staged"; baseHead: CommitId; entryCount: number }; -type DraftState = { baseHead: CommitId; entryCount: number; preview: Readonly }; - -interface DocumentHandle> { - state(): ReadyState | InspectionState; - dispatch( - command: K, - input: Commands[K], - ): Promise>; - commit(metadata?: JsonObject): Promise>; - discardDraft(): Promise>; - draft(): DraftState | null; - export(): Uint8Array; - verify(): Promise; - replay(): Promise>>; - inspect(): InspectionReport; -} -``` - -Factories at `@ternent/concord`: - -```ts -declare function createDocument, E extends DomainEvent>(options: { - model: ApplicationModel; - system: SystemProfile; - identity: IdentityCapability; - mode?: "immediate" | "draft"; // immediate by default - limits?: Partial; -}): Promise>>; - -declare function openDocument, E extends DomainEvent>(options: { - bytes: Uint8Array; - model?: ApplicationModel; - system?: SystemProfile; - reader?: ReaderCapability; - signer?: IdentityCapability; - mode?: "immediate" | "draft"; - anchor?: Uint8Array; // previously verified full snapshot - limits?: Partial; -}): Promise>; -``` - -`Limits` has integer fields `maxBytes`, `maxCommits`, `maxEntries`, -`maxCiphertextBytes`, `maxDepth`, and `maxMetadataBytes`, with the defaults in -Protocol 1. Values must be positive safe integers; invalid overrides are host -configuration errors. `maxBytes` bounds export as well as import; limits apply to -every authored candidate before signing. A byte limit failure leaves drafts intact. -Protocol verification checks both transport and canonical snapshot lengths before -extension execution, so expanding accepted numeric notation cannot create an -over-budget ready export. - -At host seams, JSON/depth/byte validation applies to each logical value: command -input, event, projection, per-entry system result, and each system summary. Entry -and event counts must match verified history. Do not apply the snapshot byte budget -to a combined serialization of all replay facts: repeated facts expand with history. -A replay resource limit marks the affected stage unsupported and returns incompatible -inspection; it does not invalidate the signed history. - -`Json`, `JsonObject`, public wire types, Result, ConcordError, and the lifecycle/model -types are exported from the root when mentioned in its declarations. `/protocol` -also exports Json/wire/report types, canonicalize, hashEntrySubject, hashCommitSubject, -verifyDocument, and compareSnapshots. Canonicalize and hash helpers return Result; -the verifier returns its report, and comparison returns Result of the five relations. -Hash helpers compute IDs only; commit signing is runtime-owned. `defineModel` is at -root. `createStandardSystemProfile()` is at `/system`, takes no required arguments, -and returns the official implementation described by standard-profile.md. - -```ts -declare function canonicalize(value: unknown): Result; -declare function hashEntrySubject(subject: EntrySubject): Result; -declare function hashCommitSubject(subject: CommitSubject): Result; -declare function verifyDocument( - bytes: Uint8Array, - options?: { - limits?: Partial; - }, -): Promise; -declare function compareSnapshots( - a: Uint8Array, - b: Uint8Array, - options?: { - limits?: Partial; - }, -): Promise>; -``` - -Canonicalize validates the value domain; hash helpers additionally validate the exact -known subject shape, without verifying a signature or resolving an entry reference. -Invalid verifier limit configuration gives an unsupported report with HOST_CONFIGURATION; -it is not mislabeled as document tampering. - -`/system` exports `setMember(handle, { identity, capabilities })` and -`removeMember(handle, { identityId })`, each generic over the handle model and returning -`Promise>`. They use the handle's active signer and private -serialized authoring port, with no caller-supplied actor, keys, epoch, or ciphertext. -The runtime owns their one-commit lifecycle. They require immediate mode, reject -nonempty drafts with DRAFT_PENDING, and reject an empty draft-mode handle with -HOST_CONFIGURATION (no implicit mode switch). These specialist management functions -and their draft guards are implemented. `createGroup` follows these same guards; -member operations accept an optional audience that defaults to `document`. - -An untyped inspection overload of open returns `DocumentHandle>`. Passing a model gives its inferred types even when open returns inspection; -the caller must narrow `state().status` before using projection. Freeze/copy input -bytes on entry. Missing profile/model implementations do not cause creation to guess: -create requires both and checks their refs before any key generation. - -Signer defaults as reader when present; an explicitly supplied reader must identify -the same identity as signer or open returns incompatible `IDENTITY_MISMATCH`. -A supplied signer is not evidence of membership. No signer means all mutation methods -fail `READ_ONLY_RUNTIME`, including discardDraft. `canWrite` also requires ready, -active write, and complete key access. System operations check their own capabilities. -Inspection handles reject all mutations with `INSPECTION_ONLY` before checking signer. - -Expected failures return Result or inspection, not exceptions. Constructors take typed -configuration; invalid executable host configuration returns `HOST_CONFIGURATION` at -create, or incompatible inspection at open. Unexpected extension exceptions are caught -as `MODEL_FAILED` or `SYSTEM_FAILED` without plaintext in errors. No global rejection -handler, dynamic code loader, or console-only failure channel. JS allocation failure -and process termination are outside the contract. - -### Independent verification and inspection - -`verifyDocument(bytes, { limits? })` at `/protocol` returns `VerificationReport` and -requires no identity, profile, model, Armour, or Seal. The report is: - -```ts -type VerificationReport = { - integrity: "valid" | "invalid" | "unsupported"; - documentId: CommitId | null; - head: CommitId | null; - checkedCommits: number; - checkedEntries: number; - findings: readonly ConcordError[]; -}; -type InspectionReport = { - verification: VerificationReport; - system: "valid" | "invalid" | "unsupported" | "not-run"; - application: "valid" | "scoped" | "invalid" | "unsupported" | "locked" | "not-run"; - freshness: "unanchored" | "equal" | "ahead" | "behind" | "diverged" | "unrelated"; - otherRecipientsDecryptability: "unverified"; - requirements: readonly { kind: "system" | "model"; ref: ModelRef }[]; - lockedEntries: number | null; // null if structure/profile could not be interpreted - findings: readonly ConcordError[]; - history: readonly CommitRecord[]; // raw public envelopes; [] when unparseable - entries: readonly ReplayItem[] | null; // only after complete system pass - audiences: readonly AudienceState[] | null; // public group summaries -}; -``` - -Verification counts only records successfully checked in each phase; an unsupported -suite leaves signature-checked commits at zero. A valid report counts all records. -Unknown requirements appear in `requirements` only when unavailable/mismatched, in -system-then-model order. Inspection merges findings in protocol, requirements, -freshness, system, model order. Protocol failure prevents later phases. Resolve -requirements before system execution; freshness failure also stops replay. A complete -system pass yields one readable entry or locked marker per application entry, including -retained historical access after removal. No reader yields locked application entries. -Missing keys count only entries using unavailable audience/epoch keys; available-key -cryptographic/context failure is invalid. Models without `reduceLocked` return locked -inspection before callbacks if any entry is unavailable (also for private genesis -without a reader). Opted-in models fold the complete readable/locked stream and report -`coverage: "readable"`, application `scoped`, when locked entries exist. Zero locked -entries gives complete/valid. Hidden application semantics remain unverified. -Inspection exposes entries/audiences after successful system replay even when model -replay fails, with no intermediate trusted projection. Other recipients' encrypted -wraps remain decryptability-unverified. - -`handle.verify()` verifies committed bytes without replaying or upgrading readiness. -`handle.replay()` performs both complete stages against the fixed committed snapshot -and returns its fresh `{ projection, coverage, lockedEntries }`; it cannot bypass verification or replay a range. -Inspection stays read-only; supplying new keys/models means a fresh open. -`inspect()` never decrypts on demand or returns keys. Reports and history are detached -immutable views. Ready-state projection and draft previews must not allow external -mutation of internal state; copy/freeze at public and extension seams. -After bounded parsing and known-schema validation, public commit envelopes remain -available as untrusted inspection evidence even if hashes, linkage or signatures -fail. Keep them separate from verified input; they never authorize extension replay. -When parsing/schema validation cannot establish those envelopes, history is empty. - -Ready export is canonical protocol JSON. Inspection export returns an exact copy of -the input bytes, including malformed input, so evidence can be retained. `verify` on -an inspection handle validates those same bytes. Re-exporting a ready document need -not preserve original whitespace or annotations formatting, but preserves all signed -subjects and ciphertext bytes. Export never adds a projection, draft, identity seed, -group scalar, or cached verification assertion to the document. - -### Authoring and atomicity - -All mutating calls on a handle are queued in invocation order; no two operations share -a mutable candidate. Reads during a pending operation see the last published snapshot. -Synchronous reentrant dispatch from model/system callbacks fails `HOST_CONFIGURATION`. -Asynchronous profiles MUST NOT dispatch into the same pending handle after an await; -that host contract violation is not automatically distinguishable from an independent -queued caller in this runtime. See [ADR 0014](../adr/0014-keep-async-profile-reentry-a-host-contract.md). -Async I/O remains internal to signing/encryption, not model decisions. - -Immediate dispatch validates input, invokes the model decision on committed projection, -validates every event, checks model/system requirements, creates protected entries, -builds and signs one commit, protocol-verifies it, and completes two-stage replay of -the candidate. It atomically swaps committed snapshot, system facts, and projection -only after all steps succeed. Return its receipt. Multi-event decisions are one commit; -empty event lists fail `NO_EVENTS`. No implicit timestamp, ID, storage write, or retry -of a failed decision. Signing failure leaves the original head and projection intact. -The standard profile forbids self-removal, so authoring never needs a success path -that publishes an unreadable candidate. A different administrator may remove an actor. - -Create follows the same candidate validation before returning a ready handle. Genesis -always commits immediately, even in draft mode. Creation failure returns no document. - -Draft mode stages application intents in memory against an immutable base head, runs -their model transitions, and publishes only `draft().preview`. `state().projection` -remains committed. Subsequent decisions use the preview. Provisional previews are not -trusted committed reconstructions; no final entry IDs or ciphertext are promised. -`commit(metadata)` protects staged events using the current base, signs one commit, -verifies/replays, and atomically publishes it and clears the draft. Encryption happens -at commit time; on failure retain the full draft and original snapshot. Empty draft -fails `NO_DRAFT`. Explicit commit in immediate mode also fails `NO_DRAFT`; dispatch -already committed. `discardDraft()` discards the whole draft; empty draft is a no-op -success for a writable handle. Partial discard and mode switching are outside alpha. - -The preview is provisional and carries the same reader scope as its committed base; -it cannot certify hidden application semantics. No protocol entry/commit IDs, nonces, ciphertext or -signature are allocated while staging. Staged event count includes committed entries -for `maxEntries`, and the prospective commit must fit `maxCommits`. Aggregate staged -intents and each preview are independently bounded by `maxBytes`/`maxDepth`. The -protected final snapshot may still exceed a byte/ciphertext limit at commit time; -that failure retains the draft. There is no estimate presented as a verified size. -Commit metadata is copied when `commit` is invoked, must be a JSON object within -`maxMetadataBytes`, and is checked before protection/signing. Omitted metadata is -signed as null. Invalid metadata fails `SCHEMA_INVALID`; bound failures use -`RESOURCE_LIMIT`. Signed metadata remains public. - -Drafts are volatile. Export, verify, and full replay concern committed history and -leave staged intents unchanged. Reopening export discards any local draft by design; -no unsigned draft persistence is hidden in a storage adapter. System authoring is -immediate and is blocked by `DRAFT_PENDING` until an existing draft is committed or -discarded. Handle state never replaces another document via import/load; open creates -another handle. A failed candidate must leave the previous handle byte-for-byte -export-equivalent, with the same projection and draft. - -## 3. Typed application models - -The model interface has depth: callers define domain meaning while the runtime owns -entry envelopes, actor binding, security replay, encryption, and atomic publication. - -```ts -type DomainEvent = { type: string; version: number; data: Json }; -type ModelIssue = { code: string; message: string; path?: string }; -type Capability = "read" | "write" | "grant" | "administer"; -type SystemFacts = { - actor: PublicIdentity; - audience: AudienceId; - capabilities: readonly Capability[]; // actor's rights at this entry position - members: readonly { identity: PublicIdentity; capabilities: readonly Capability[] }[]; -}; -type DecisionContext = { facts: SystemFacts }; -type ApplicationModel, E extends DomainEvent> = { - ref: ModelRef; - initial(): S; - commands: { - [K in keyof C]: { - validate(input: unknown): Result; - audience?(input: C[K]): AudienceId; // default document - decide( - input: C[K], - state: Readonly, - ctx: DecisionContext, - ): Result; - }; - }; - validateEvent(input: unknown): Result; - audience?(event: E): AudienceId; // default document - requirements(event: E): readonly Capability[]; - reduce(state: Readonly, event: E, facts: SystemFacts): Result; - reduceLocked?( - state: Readonly, - entry: { audience: AudienceId; epoch: number }, - facts: SystemFacts, - ): Result; -}; -``` - -`defineModel` is a typed identity/validation helper for this interface; it does not -register global state. Initial state, requirements, validations, decisions, and reducers -are synchronous pure functions. S MUST be Json. Typed input validation remains necessary -for JS/agent callers. Unknown command names return `COMMAND_UNSUPPORTED`; model issues -map to the phase's outer error code with `details.modelCode`, not arbitrary core codes. - -Event type/version and data schemas are part of the model contract, fixed at its ref. -Commands are ephemeral authoring interfaces and are not replayed. Decisions must encode -time, randomness, IDs, and external observations in event data via validated inputs. -The host captures these before dispatch; the runtime does not inject ambient helpers -into reducers. Facts exclude current wall time, reader identity, mutable permission -maps, raw ciphertext, keys, and derived UI profiles. Requirement sets are checked on -authoring and historical replay. The runtime retains provenance (commit/entry IDs) -for inspection; the reducer cannot make state depend on the new commit ID. - -After command input validation, select one audience and check current write there -before decide receives that group's signer facts. Every emitted event must select the -same audience. On replay event selection must match its signed envelope. Unknown or -inconsistent routing fails; no implicit group creation. Each selector is synchronous -and pure. Locked hooks get public facts/marker only; the model explicitly owns missing -cross-group dependencies. Rejecting any transition aborts the whole pass. - -The model validates transitions in reduce as well as deciding commands: an authenticated -writer can produce a structurally valid event that violates model invariants. Such -history is integrity-valid and application-invalid, never a partially trusted board. -No upcasters, fallback model version, ignored unknown event, or mutable replay hooks. - -## 4. Identity and primitive package interfaces - -`@ternent/identity` owns raw-byte Ed25519 signing/verification, public identity checking, -strict point validation, seed derivation, and X25519/age conversion. The new capability -interface is: - -```ts -// Capability types exported by Armour; PublicIdentity comes from Identity. -type PrimitiveError = { code: string; message: string }; -type PrimitiveResult = Result; -type ReaderCapability = { - publicIdentity: PublicIdentity; - decryptAge(ciphertext: Uint8Array): Promise>; -}; -type IdentityCapability = ReaderCapability & { - sign(message: Uint8Array): Promise>; // exactly these bytes -}; -// Convenience factories exported by Armour, delegating key derivation to Identity. -declare function identityFromSeed(seed: Uint8Array): Promise>; -declare function generateIdentity(): Promise>; -``` - -Identity owns the derived private key and MUST NOT depend on Armour to implement age. -Construct capabilities in two steps: Identity's base signer capability has -`publicIdentity`, `sign`, and `withX25519Secret(callback)` (a copied scalar scoped to the -async callback, zeroed in finally after callback settlement, never serialized); -Armour's `withAgeDecryption(base)` returns the above reader/signer capability by -composing its age implementation. Identity's factories are named `signerFromSeed` -and `generateSigner` and return BaseIdentityCapability. Identity also exports -`validatePublicIdentity(input)` and `verifySignature(publicIdentity, message, signature)` -with structured results and the protocol's strict point rules. The full identity -convenience factories above live at Armour. Concord consumes the resulting structural -types and does not construct or store private identity material. Identity exports -PublicIdentity and BaseIdentityCapability; Armour exports ReaderCapability and -IdentityCapability. The snippets use Result generically: primitive packages own their -error types, without importing ConcordError. - -Armour additionally exposes `encryptAge({ recipients: readonly string[], plaintext: -Uint8Array }): Promise>` and `decryptAgeWithSecret({ secret: -Uint8Array, ciphertext: Uint8Array }): Promise>` for group-key use. -These operate on binary files and raw X25519 scalars/age recipients; no init/WASM step. -Its private engine must be pure TypeScript, satisfy the pinned age format, and pass -independent age CLI interop. Selecting the engine is an implementation/tooling choice, -not a new protocol choice. No production spawn of an age CLI. Primitive packages use -their own structured errors; Concord maps them to phase-specific codes without a -reverse dependency on Concord. Seed import and generation copy caller bytes. - -Seal remains an independent artifact/proof module. Concord neither stores a Seal -proof on every entry nor makes protocol verification depend on Seal's manifest shape. -Both can consume Identity's raw signing primitives. No Seal changes or Action migration -are prerequisite to implementing this first slice. - -## 5. Modules and packages - -| Owner | Deep implementation behind its interface | Must not own | -| -------------------------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------- | -| Concord `protocol/` | Strict parser, canonicalization, IDs, commit verification, lineage comparison | Model code, membership, decryption, storage | -| Concord `runtime/` | Lifecycle, serialized candidates, draft state, trust transitions, atomic publication | Domain commands, permission algorithms, age internals | -| Concord `system/standard/` | Bootstrap, historical authority, epochs, wraps, two-stage input preparation | Board policy, profiles, persistence | -| Concord `model/` | Types, model definition validation, deterministic fold runner | Application-specific schemas or reducers | -| Identity | Key material, strict signature behavior, derived identities | Documents, age file implementation, accounts | -| Armour | Pure TS age operations and composition with Identity | Signed history, authority, application events | -| Seal | Standalone artifact proofs | Concord lifecycle | -| Example register / board | Commands, event schemas, reducers, domain invariants | Cryptographic envelopes or mutable system facts | -| Storage adapter | Whole artifact reads/writes and optional expected-head checks | Trust, repair, merges, projection persistence | -| Tooling | Config profiles, graph orchestration, isolated artifact verification | Runtime dependencies | - -Only `@ternent/concord`, `/protocol`, `/system`, `/testing` are exported. Proposed -source entries are `src/index.ts`, `src/protocol/index.ts`, `src/system/index.ts`, -`src/testing/index.ts`. Public import filenames are `dist/index.js`, -`dist/protocol/index.js`, etc., with matching `.d.ts` and sourcemaps. `/protocol` -has no import path to runtime/system/Armour; inspect built dependency closure. -`/testing` exposes register fixtures, `assertModelConformance`, and a memory artifact -store, with no test runner in production dependencies. A conformance helper returns -structured assertions; it never auto-generates expected outputs from the implementation. - -Runtime -> protocol, model runner, system interface. Standard system -> protocol, -Identity, Armour. Armour -> Identity. Identity -> reviewed crypto primitives. -Tooling has no runtime package dependencies. Framework/UI -> root Concord interface. -No new Ledger, Workspace, protocol-only package, storage framework, or universal plugin -package. Internal seams are private except the documented specialist subpaths. - -Storage remains separate from the runtime. The minimal adapter and optional atomic -expected-head capability are implemented as reference helpers in `/testing`; see -[the storage boundary](storage-boundary.md) for exact types and limits. The basic -`createMemoryArtifactStore` stores copied raw bytes. The richer -`createMemoryExpectedHeadStore` advertises `expectedHead: true` and adds -`writeExpected(bytes, expected: CommitId | null)`. Null means create only if absent; -HEAD_CONFLICT returns copied remote bytes outside JSON error details. It serializes -all writes through validation/compare/replacement, so async verification cannot create -a read-then-write race within that shared instance. It verifies protocol history only -and uses default verifier limits; application validity still requires runtime open. - -Failed publication never rolls back a local commit or erases a pending draft. Keep -both local and returned remote artifacts and compare explicitly. No automatic merge, -head selection, overwrite retry, draft persistence, transport or provider is added. -Expected head is not a byte revision or ancestry policy; freshness needs an external -anchor. Atomicity is limited to the reference instance. A production adapter must use -a real provider transaction/conditional write, not a non-atomic client read/write. - -## 6. Toolchain and implementation order - -The [repository guide](../engineering/repository-hygiene.md) defines the current -five-library workspace, ordinary shared Vite+/TypeScript base configs and standard -pnpm recursive builds. It supersedes the earlier portable-profile and app-driven -rollout. The [release contract and backlog](../engineering/release-and-deployment.md) -own candidate-registry verification, planning, publication and onboarding. - -The implemented library sequence covers strict Identity/Armour primitives, the -Ledger-owned common container/lifecycle, Concord bootstrap and typed register, -independent membership/readable replay, in-memory drafts, external storage conflict -proof, and standalone Seal library/CLI. UI, portable tooling and the retired handshake -are not release gates. The deferred board below remains an application example, -not a required core package or hosted app. - -ESM/ES2022 outputs are tested through installed Node 22/24/development-runtime -consumers and Chromium. Browser execution must exercise real cryptography; a syntax -target or successful bundle does not establish that result. Keep formatting, typed -lint, explicit types, behavior, builds and installed-artifact checks separate. -Use declared public workspace dependencies rather than source aliases or registry -predecessors. See [CONTRIBUTING.md](../../CONTRIBUTING.md) for current pins and commands. - -## 7. Deferred project-board proof - -Board ref: `{ id: "concord.example.project-board", version: 1 }`. It is example model -code above Concord. Use one document audience and grant history on admission. Initial -state is `{ title: "", columns: [], tasks: {} }`; board.configure must occur before -task commands. IDs are caller-supplied nonempty ASCII `[A-Za-z0-9_-]{1,64}`, unique -within their collection forever. Strings preserve Unicode; title/task title are 1–256 -UTF-8 bytes, description 0–16,384. No model-generated time/randomness. - -| Command -> event, all event version 1 | Exact payload and transition | -| ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| configure -> board.configured | `{ title, columns: { id, title }[] }`; once only, 1–32 unique columns, same title bound | -| rename -> board.renamed | `{ title }`; configured board required | -| createTask -> task.created | `{ id, title, description, columnId }`; configured, new ID, existing column; append to column, assignee null, archived false | -| editTask -> task.edited | `{ id, title, description }`; existing non-archived task; replace these fields | -| moveTask -> task.moved | `{ id, columnId, beforeId: string \| null }`; existing non-archived task and target column; remove first, insert before active task in target column or append; cannot reference itself | -| assignTask -> task.assigned | `{ id, identityId: string \| null }`; existing non-archived task; target must be an active reader at event position, or null | -| archiveTask -> task.archived | `{ id }`; existing non-archived task; remove from ordered column list, retain task content and last column ID, mark archived true | - -Every task record holds id/title/description/columnId/assignee/archived; each column -holds id/title and an ordered task ID array. Configure's event columns gain empty -arrays in reduction. All commands and events use closed schemas and require write; -errors identify absent/duplicate/archived task, absent column, invalid before target, -absent assignee, and unconfigured/already configured board. Repeating archive fails. -No unarchive, column mutation, deletion, task permissions, automatic reassignment after -member removal, or attachments. Historic assignment remains as an identity reference -after removal. Display identity IDs or deterministic glyphs; directory/profile lookup -is optional UI work outside Concord. Future glyph design does not affect protocol. - -The walkthrough creates/configures a private board; adds viewer and editor; proves the -viewer cannot write; edits/moves/assigns/archives as editor; groups commands with a -draft message; exports and reopens; admits another member with all historical keys; -removes the editor and rotates audience keys; rejects its write after removal; retains -its valid offline branch from before removal; rejects a routine stale publication -through expected-head write; and surfaces the two heads without merging or picking. -Tampered, missing-model, and locked imports remain exportable inspection artifacts. - -## 8. Decisions, product questions, and observed evidence - -There is no blocking product question for the first slice. Independent groups, -full history on admission, atomic complete or explicitly readable projections, and local volatile drafts -are explicit alpha constraints rather than prompts for an implementer to guess. A -product needing private task subsets or future-only membership needs a separately -specified profile/model; it must not quietly widen this alpha. - -Networking, profiles/directories, consensus, merges, recovery, continuity, key rotation -of identities, checkpoints, partial authoritative replay, model upgrades, and -multi-document queries remain outside this implementation. The expected-head proof -is a local adapter test, not a network product. No existing consumer requires changing -these semantics. Seal Action command-sequence checks use the installed candidate; -registry-backed integration remains part of published-consumption acceptance. diff --git a/docs/concord/standard-profile.md b/docs/concord/standard-profile.md deleted file mode 100644 index 9926480..0000000 --- a/docs/concord/standard-profile.md +++ /dev/null @@ -1,220 +0,0 @@ -# Standard system profile 1 - -Status: implemented pre-release contract, 2026-11-20. Profile reference: -`{ id: "concord.standard", version: 1 }`. This revises the unpublished alpha in -place; no compatibility with older executables is promised. Genesis and the fixed -owner-only vectors retain their exact bytes. See [ADR 0015](../adr/0015-keep-audience-memberships-independent.md) -and [ADR 0016](../adr/0016-route-each-command-to-one-audience.md). - -## Authority and privacy - -`document` is the default group. Additional groups have independent members, keys, -and epochs. A `GroupId` is `group:` plus canonical base64url of 16 random bytes; -`AudienceId` is `"document" | GroupId`. Group IDs cannot be reused in a document. -Default-group membership is not required to join another group. Default-group -ownership gives no implicit read, write, grant or administer in other groups. - -Genesis gives its signer all four capabilities in `document`. An actor with write -in `document` may create an independent group without owner approval; only its -creator receives the initial key and all four capabilities in that group. - -Every active member has read. Capability arrays contain unique values in order -`read`, `write`, `grant`, `administer`. A grant holder may give a subset of read/write -that they hold, and cannot edit a member with grant/administer. An administrator may -set any nonempty set containing read or remove a member. At least one administrator -must remain in each group. Self-removal is forbidden: another administrator must do -it. Removing the last administrator fails `LAST_ADMINISTRATOR`; other self-removal -fails `SYSTEM_EVENT_INVALID`. Unchanged sets fail `SYSTEM_NO_CHANGE`. - -Application entries require historical write in their selected audience, plus the -model's required capabilities there. Later grants never authorize an earlier signer. -Admission and re-admission deliver every historical key of that group. Removal rotates -only its future key; existing historical keys and plaintext remain readable. Current -membership controls authoring, not suppression of decryptable history. Removing a -member from `document` changes no other group's membership, keys or rights. - -Group labels/descriptions belong in encrypted application events. Public group IDs, -signers, membership/capability changes, wrap targets, epochs/recipients, linkage, -counts/sizes and signed commit metadata remain observable. This profile does not -hide membership or traffic patterns. Other recipients' decryptability is always -reported as `unverified`. - -## Keys and contextual binding - -Each group epoch uses a fresh clamped 32-byte X25519 scalar and its age recipient. -Generate 32 random bytes, clamp as X25519 and encode B(bytes). These are audience -keys, not additional identities. Private scalars never appear in public JSON. -On creation or rotation, reject a recipient already recorded in any audience/epoch. -This detects declared key reuse, not an authorized author disclosing a secret. - -A wrap is a binary age file encrypted to one member's derived identity recipient. -Its canonical plaintext is: - -```ts -type KeyPlaintext = { - context: "concord.audience-key/1"; - parent: CommitId | null; - nonce: Nonce; - audience: AudienceId; - epoch: number; - identityId: string; - recipient: string; - secret: string; // B(clamped 32-byte scalar) -}; -type Wrap = { identityId: string; ciphertext: string }; -type HistoricalWrap = { epoch: number; ciphertext: string }; -``` - -Every addressed wrap must decrypt and match canonical bytes, all context fields, -scalar clamping and the declared recipient derived from that scalar. A malformed -addressed wrap fails `KEY_WRAP_INVALID`, even if a later admission supplies a valid -replacement. Other recipients' encrypted contents cannot be verified by this host. - -Each application entry encrypts canonical [event plaintext](alpha-protocol.md) once -to the selected group's current epoch recipient, with fresh age file material. Check -parent, nonce, model, audience and epoch on decryption. An available key with failed -authentication/context is invalid, not locked. Cryptography stays in Identity/Armour; -Armour uses typage's `age-encryption` implementation, with no WASM initialization. - -## Closed system events - -Every event is `{ type, version: 1, data }`. All data shapes below are closed. -Wrap arrays sort by identity ID using ASCII order; historical wraps sort by increasing -epoch. Every referenced identity must validate. Duplicate, omitted and extra elements -fail. Unknown event type/version yields `UNSUPPORTED_SYSTEM_EVENT`, never a no-op. - -```ts -// system.init: only entry in genesis, owner equals containing commit signer. -type InitData = { - audience: "document"; - epoch: 0; - recipient: string; - owner: PublicIdentity; - wraps: [Wrap]; // exactly the owner -}; -// system.group.create: actor has document.write; new ID, fresh key, epoch zero. -type GroupCreateData = { - audience: GroupId; - epoch: 0; - recipient: string; - wraps: [Wrap]; // exactly the containing commit signer -}; -// system.member.set: audience exists; authority is checked in that audience. -type MemberSetData = { - audience: AudienceId; - identity: PublicIdentity; - capabilities: Capability[]; - history: HistoricalWrap[]; -}; -// system.member.remove: active target, authorized administrator, fresh rotation. -type MemberRemoveData = { - audience: AudienceId; - identityId: string; - epoch: number; // selected group's previous epoch + 1 - recipient: string; - wraps: Wrap[]; // exactly the selected group's remaining active members -}; -``` - -New/re-admitted members receive exactly one wrap for every epoch of their selected -group. Existing members' capability changes have empty history. Admission does not -rotate. Authoring without any required historical secret fails -`HISTORICAL_KEY_UNAVAILABLE` atomically. Removal wraps the fresh epoch to every -remaining member, sorted by ID, and no removed member. Other groups are untouched. -Later entries of the same commit observe updated authority and epoch. - -No group deletion, public label fields, generic rotate event, role/account registry, -anonymous envelope or implicit cross-group privilege exists in profile 1. - -## Two-stage replay and coverage - -Protocol verification checks every reachable record before resolving exact model and -profile implementations from the host. No document-provided code is loaded. - -Stage A first validates the entire public authority history: group creation, -membership, epoch and historical signer write for every application envelope. It -records immutable per-entry facts. No decryption or model callback runs until the -complete public pass succeeds, including groups hidden from the reader. - -Then validate every wrap addressed to the reader across the selected history, -including grants before removal and later historical admissions. Decrypt each -application entry whose audience/epoch key is available. Return exactly one readable -entry or locked marker per application entry in order. No reader means no unwrap -attempts and all application entries locked. Retained old keys remain usable after -removal; unavailable future epochs stay locked. Never trial-decrypt unrelated keys. - -Stage B replays the whole resulting stream. A model without `reduceLocked` requires -all events; any locked entry returns locked inspection before even `initial` runs. -Without a reader this full model also returns locked inspection for private genesis. -A model with `reduceLocked` explicitly decides what public locked markers mean in -its own state. The hook gets no fabricated event payload, reader identity or secrets. -Any hook/reducer/validation/requirement failure aborts the entire projection. - -Successful ready state and `replay()` carry `coverage: "complete"` for zero locked -entries, otherwise `"readable"`, and the exact `lockedEntries` count. Inspection's -application status is respectively `valid` or `scoped`. Scoped success validates -readable semantics only; it does not certify hidden event types, model requirements -or transitions. `canWrite` means the supplied signer has write in at least one group; -each command still checks its selected audience independently. - -After a successful complete system pass, inspection exposes immutable `entries` and -`audiences`, even if later model replay fails. They are null if no complete system -result exists. Failed replay never exposes a trusted intermediate projection. - -## Public system seam - -`@ternent/concord/system` exports `createStandardSystemProfile`, `createGroup`, -`setMember`, `removeMember` and specialist types. Member helpers default to -`document` only when audience is omitted; null or invalid IDs fail. Callers never -supply actor, key, epoch, recipient or ciphertext. Group creation returns the generated -ID with its receipt only on successful publication. - -```ts -type ReplayItem = - | { status: "readable"; entryId: EntryId; event: DomainEvent; facts: SystemFacts } - | { status: "locked"; entryId: EntryId; audience: AudienceId; epoch: number; facts: SystemFacts }; -type AudienceState = { - audience: AudienceId; - members: readonly Member[]; - epochs: readonly { epoch: number; recipient: string }[]; -}; -type SystemReplay = { - entryFacts: readonly { entryId: EntryId; facts: SystemFacts }[]; - entries: readonly ReplayItem[]; - audiences: readonly AudienceState[]; // sorted by audience ID - reader: PublicIdentity | null; - session: object; // opaque; keys stay in profile-private WeakMap -}; -type ApplicationIntent = { - kind: "application"; - event: DomainEvent; - required: readonly Capability[]; - audience: AudienceId; -}; -type SystemIntent = - | { kind: "group.create"; audience: GroupId } - | { - kind: "member.set"; - audience: AudienceId; - identity: PublicIdentity; - capabilities: readonly Capability[]; - } - | { kind: "member.remove"; audience: AudienceId; identityId: string }; -``` - -`SystemProfile` has bootstrap, replay and prepare, using runtime-branded verified -history. Bootstrap owns the init nonce/key/wrap. Prepare generates entry nonces, -wraps and ciphertext through Identity/Armour. The runtime owns the signed commit, -checks total ordered entry coverage and signer/audience binding, and verifies/replays -the complete candidate before atomically publishing bytes, state and report. -Sessions are not serializable and never expose key material. Values crossing the -seam are immutable. Custom profiles are trusted host code with explicit versioned -semantics, not untrusted plugins supplied by a document. - -Commands validate input, select one audience with `commands[name].audience` (default -`document`), check write there, then decide with that group's current signer facts. -Every emitted event must select that same audience using the model's `audience` -hook (default `document`). Replay checks event selection against its signed envelope. -Mixed-audience commands fail before encryption/signing. Draft mode now groups -several commands across audiences into one atomic commit; each command retains this -single-audience rule. System management requires an immediate-mode handle. diff --git a/docs/concord/storage-boundary.md b/docs/concord/storage-boundary.md deleted file mode 100644 index c4d08b2..0000000 --- a/docs/concord/storage-boundary.md +++ /dev/null @@ -1,113 +0,0 @@ -# Storage boundary and expected-head publication - -Implemented B12 reference proof, 2026-11-20. Storage reads and writes complete byte -artifacts. Commit authoring is a separate local operation; the runtime does not know -about a store, publish on dispatch, persist drafts or roll back a commit after a save -failure. Existing Identity/Armour cryptography and Concord verification/replay remain -the trust boundary. - -## Minimal adapter and optional capability - -`@ternent/concord/testing` exports these types and in-memory reference helpers: - -```ts -type StorageError = - | { code: "STORAGE_FAILED"; phase: "storage"; message: string } - | { code: "HEAD_CONFLICT"; phase: "storage"; message: string; remote: Uint8Array | null }; -type ArtifactStore = { - read(): Promise>; - write(bytes: Uint8Array): Promise>; -}; -type ExpectedHeadArtifactStore = ArtifactStore & { - readonly expectedHead: true; - writeExpected(bytes: Uint8Array, expected: CommitId | null): Promise>; -}; -``` - -`createMemoryArtifactStore()` is the existing raw byte store. It copies on write/read -and does not verify or interpret its contents. Empty storage is null; a zero-length -artifact is still an artifact. A successful write is not evidence that a document is -valid, authorized, decryptable, current or complete. - -`createMemoryExpectedHeadStore()` adds an atomic compare-and-write reference for -writers sharing that instance. It verifies candidate and stored protocol history with -default protocol limits, then compares the stored head with the expected head before -replacement. Null means create only if absent. An omitted, malformed or noncanonical -expected head fails `STORAGE_FAILED`; it never becomes an unconditional write. - -All mutations, including unconditional `write`, share a serialized queue. Validation, -comparison and replacement occupy one operation; another write cannot interleave -while verification awaits. Inputs are copied at invocation, reads/conflict bytes are -copied at return, and reads observe the last published artifact while a write is -pending. Exactly one of two new child heads using the same old expected head can -succeed. On mismatch, `HEAD_CONFLICT` returns a detached copy of the stored bytes (or -null if absent) without altering storage. `remote` is separate byte evidence, not a -JSON error-details field or an exception message. - -Malformed/unsupported candidates, corrupt stored artifacts and invalid arguments fail -`STORAGE_FAILED` without replacement. Read the stored raw bytes to inspect corrupt -content; do not silently erase it because head lookup failed. A failed operation does -not poison the mutation queue. The richer store's ordinary `write` is deliberately -unconditional and remains a raw byte operation; callers wanting compare-and-write -must use `writeExpected`. - -The richer store's protocol check only establishes a verified head for comparison. -It never resolves model/profile code or proves their semantics. A cryptographically -valid artifact with unknown requirements or invalid authority can be stored and still -open as incompatible/invalid inspection. Always open and replay under the host's -chosen model/system/capabilities before exposing trusted application state. - -## Caller flow and conflict evidence - -Export once to capture the committed local candidate, then explicitly publish it. -When replacing a known stored head, pass that remembered head as expected. Keep the -candidate until the operation completes. With pending draft work, export still -contains committed history only. Saving and reopening cannot persist that draft. - -On conflict, retain local and returned remote bytes. Verify/compare them using -`compareSnapshots(localBytes, remoteBytes)` when remote is present. Equal/ahead/behind/ -diverged/unrelated describe the two snapshots; they do not select one. A missing or -invalid remote is separate evidence, not permission to overwrite. The runtime does -not merge, import over an existing handle, retry a different expected head or choose -a winner automatically. Open another handle for a chosen snapshot. - -```ts -const localBytes = document.export(); -const result = await store.writeExpected(localBytes, rememberedHead); -if (!result.ok && result.error.code === "HEAD_CONFLICT") { - const remoteBytes = result.error.remote; - const relation = remoteBytes === null ? null : await compareSnapshots(localBytes, remoteBytes); - // Retain localBytes and remoteBytes for explicit inspection/selection. -} -``` - -An adapter's expected-head match does not enforce document identity or ancestry. If a -caller deliberately supplies the actual current head, it can publish a valid older, -divergent or unrelated candidate. The reference store adds no hidden replacement -policy. Expected-head checks prevent routine stale writes; anchors detect stale reads. -An old valid snapshot can still open unanchored. Opening with a remembered full newer -snapshot rejects rollback as `STALE_HEAD` and retains the bytes for inspection. - -Expected head is not a byte revision: transport whitespace/key ordering can change -while retaining the same head, and an away-and-back sequence is not detected by this -token alone. All Ledger subject metadata is signed. A host needing byte-revision -distinctions must use a provider revision/ETag or a stronger transaction contract. -No freshness protection can be inferred from success when the host forgot its anchor. - -## Scope of the proof - -The new helper is a volatile reference, not a production filesystem or network adapter. -Atomicity applies only to writers using the same instance; it does not coordinate -other processes or independent instances. A real adapter advertising this capability -must use its storage transaction/conditional-write primitive. A client-side read then -ordinary write cannot establish atomic expected-head protection. - -The former handshake app is retired. The reference helper and public tests retain -the library conflict, fork, anchor and failure-preservation checks. No transport, -persistence provider, storage framework, new subpath or runtime storage option is -introduced here. - -Source cases live in `packages/concord/test/storage.test.ts`; external Node/browser -consumers exercise the public package. The -[repository guide](../engineering/repository-hygiene.md#acceptance-boundaries) identifies -acceptance reports and their limits. diff --git a/docs/concord/vectors/README.md b/docs/concord/vectors/README.md deleted file mode 100644 index d484518..0000000 --- a/docs/concord/vectors/README.md +++ /dev/null @@ -1,94 +0,0 @@ -# Concord alpha reference vectors - -These files are current alpha inputs/outputs for Concord's profile inside the common -Ledger container (2026-11-21). The private -values are **public test material**, including RFC 8032's first Ed25519 test seed; -never use them for real documents. Fixed nonces are for fixtures only. - -| File | Purpose | -| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -| [primitives.json](primitives.json) | Five canonicalization examples; nine raw JSON rejects; fixed identity, X25519 conversion, age encodings, raw Ed25519 signature | -| [owner.document.json](owner.document.json) | Complete valid private register snapshot: genesis/init plus one set event | -| [owner.expected.json](owner.expected.json) | Literal subject bytes, signature messages/signatures, decrypted wrap/event, projection and snapshot digest | -| [owner.genesis.document.json](owner.genesis.document.json) | Valid ancestor snapshot, same lineage | -| [owner.fork.document.json](owner.fork.document.json) | Valid alternative child, same entries but different signed commit metadata/nonce | -| [relationships.json](relationships.json) | Literal pairwise results for supplied snapshots | -| [mutations.json](mutations.json) | Nine RFC 6902 patches to the owner artifact, each with a literal protocol integrity/error expectation | - -Fixture fields that name `Hex` are byte strings in hex; other cryptographic wire -strings use the protocol's encodings. `canonicalSubject` is the exact JSON text before -UTF-8 encoding; `signatureMessageHex` includes the domain prefix and its zero byte. -`canonicalSnapshotSha256` hashes C(snapshot), not the pretty file on disk. Test export -by canonicalizing and comparing this digest, not by expecting preserved whitespace. -Expected files are not document containers and may contain secret fixture material. -Only `*.document.json` may be passed to the runtime as documents. -For each mutation case, clone its source, apply the RFC 6902 operations in order, -serialize as JSON, and assert the expected verifier status and first finding code. -Do not rehash or re-sign these patches: these are protocol failure vectors. System -and model failures use the deliberately re-signed construction in conformance.md. - -Generated and checked on 2026-10-21 using Node 23.7.0's built-in crypto (independent -of Concord packages) and native age 1.3.1. The identity public key matches RFC 8032; -X25519 public conversion was independently calculated by the Edwards-y formula and -compared with public derivation from the converted seed. Native age generated the -two saved randomized ciphertexts, then decrypted both to exact canonical plaintext. -Node verified both commit signatures and recomputed all entry/commit IDs. Fork and -ancestor artifacts were additionally checked for hashes, signatures and relationships. - -The ciphertext bytes are now fixed. Implementations decrypt/validate these artifacts; -they do not reproduce them by running randomized authoring again. A separate authoring -test encrypts new bytes, checks envelope/context invariants and independent decryption, -then reopens those saved bytes. Never demand equal IDs from freshly generated keys or -fresh authoring nonces. - -The reference construction is evidence for the fixtures, not a production verifier. -Strict invalid-point/parser/authority cases in [conformance](../conformance.md) remain -implementation acceptance work. Complete profile-sharing/revocation and board fixtures -must be added in their delivery steps with literal expected outputs before claiming -those conformance levels. No alpha runtime was executed to verify these files today. - -## Independent-group vectors (2026-11-20) - -- `groups.removed.document.json`: two independently administered groups in one signed - document, creator removed from default membership, Bob removed from Accounts, and - a subsequent Accounts event encrypted under the rotated epoch. -- `groups.readmitted.document.json`: direct child admitting Bob back to Accounts as - read-only, carrying every Accounts epoch key. -- `groups.expected.json`: fixed audience/document/head IDs, canonical snapshot digests, - exact projections/coverage/locked counts for owner, creator and Bob, and current - authoring rights. Expectations were constructed from the six intended events, - independently of replay output. - -These new artifacts were authored once through the runtime and saved. Built-in Node -crypto separately recomputed every entry/commit ID and verified every Ed25519 signature. -They are regression vectors, not independent native-age construction like the original -owner fixture. `groups.test.ts` opens the same bytes twice for each reader/stage and -checks the literal expected result; the isolated packed consumers do the same on -Node 22/24. Model ref is `concord.test.independent-groups`, version 1. Test identities -use the original RFC seed (owner), 32 bytes of `02` (creator), and 32 bytes of `03` -(Bob). All are public test secrets; never use them for real data. - -The application events are, in order: default `shared = "default history"`; Accounts -`account = "initial account"`; Personal `personal = "private description"`; Bob's -Accounts `account = "from Bob"`; creator's Accounts `account = "after default removal"`; -and creator's Accounts `account = "after removal"`. Each event is `group.value`, -version 1, with data `{ audience, key, value, admin: false }`. The model maps values -by key, records readable actor/audience facts and records locked audience/epoch markers. -The default owner lacks both group keys; creator has all events including retained -default history; Bob sees Accounts history, one future Accounts lock while removed, -and all Accounts history after re-admission. Default/Personal remain locked to Bob. - -## Common Ledger container revision (2026-11-21) - -Owner, ancestor and fork artifacts were re-authored with Node crypto and native age, -without importing Ledger/Concord hashing or verification. Application plaintext was -rebound to the new Ledger parent and re-encrypted; the saved ciphertext is fixed. -Expected subject bytes, IDs, signature messages, signatures and canonical digest -now describe Ledger records and the signed genesis `metadata.concord` declaration. -The signing domains are `ledger.entry/1`, `ledger.commit/1`, `ledger.signature/1`. - -Independent-group artifacts were authored through the public framework interface, -then all raw Ledger hashes and signatures were independently recomputed/verified -with Node crypto. Expected projections and locked counts remain manually derived -from the intended events. Prior format-specific observations above are historical; -these replacements are a breaking alpha revision, not a compatibility fixture. diff --git a/docs/concord/vectors/groups.expected.json b/docs/concord/vectors/groups.expected.json deleted file mode 100644 index 7b449b1..0000000 --- a/docs/concord/vectors/groups.expected.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "audiences": { - "accounts": "group:-GBcGU_EZy30gnkHcj05xg", - "personal": "group:tZkn2eFhVW6ofURIS0dRwA" - }, - "documentId": "commit:3df334832b1fa2864b4c6776e325d176b6442c18ec2c0c4f5a97c52b1e2022b1", - "heads": { - "removed": "commit:785530ba410faf42a1c8c6f0449702f407286b10652ceef51b76b15369f98175", - "readmitted": "commit:8fde4c90a4669efee735bd6cd325bb66dd50fef826a6717af2f81fff19962b1c" - }, - "readers": { - "owner": { - "removed": { - "projection": { - "values": { - "shared": "default history" - }, - "locked": [ - "group:-GBcGU_EZy30gnkHcj05xg:0", - "group:tZkn2eFhVW6ofURIS0dRwA:0", - "group:-GBcGU_EZy30gnkHcj05xg:0", - "group:-GBcGU_EZy30gnkHcj05xg:0", - "group:-GBcGU_EZy30gnkHcj05xg:1" - ], - "actors": [ - "document:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - ] - }, - "coverage": "readable", - "lockedEntries": 5 - }, - "readmitted": { - "projection": { - "values": { - "shared": "default history" - }, - "locked": [ - "group:-GBcGU_EZy30gnkHcj05xg:0", - "group:tZkn2eFhVW6ofURIS0dRwA:0", - "group:-GBcGU_EZy30gnkHcj05xg:0", - "group:-GBcGU_EZy30gnkHcj05xg:0", - "group:-GBcGU_EZy30gnkHcj05xg:1" - ], - "actors": [ - "document:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - ] - }, - "coverage": "readable", - "lockedEntries": 5 - } - }, - "creator": { - "removed": { - "projection": { - "values": { - "shared": "default history", - "account": "after removal", - "personal": "private description" - }, - "locked": [], - "actors": [ - "document:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:tZkn2eFhVW6ofURIS0dRwA:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:-GBcGU_EZy30gnkHcj05xg:identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - ] - }, - "coverage": "complete", - "lockedEntries": 0 - }, - "readmitted": { - "projection": { - "values": { - "shared": "default history", - "account": "after removal", - "personal": "private description" - }, - "locked": [], - "actors": [ - "document:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:tZkn2eFhVW6ofURIS0dRwA:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:-GBcGU_EZy30gnkHcj05xg:identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - ] - }, - "coverage": "complete", - "lockedEntries": 0 - } - }, - "bob": { - "removed": { - "projection": { - "values": { - "account": "after default removal" - }, - "locked": [ - "document:0", - "group:tZkn2eFhVW6ofURIS0dRwA:0", - "group:-GBcGU_EZy30gnkHcj05xg:1" - ], - "actors": [ - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:-GBcGU_EZy30gnkHcj05xg:identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - ] - }, - "coverage": "readable", - "lockedEntries": 3 - }, - "readmitted": { - "projection": { - "values": { - "account": "after removal" - }, - "locked": [ - "document:0", - "group:tZkn2eFhVW6ofURIS0dRwA:0" - ], - "actors": [ - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:-GBcGU_EZy30gnkHcj05xg:identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "group:-GBcGU_EZy30gnkHcj05xg:identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - ] - }, - "coverage": "readable", - "lockedEntries": 2 - } - } - }, - "canWrite": { - "owner": true, - "creator": true, - "bob": false - }, - "canonicalSha256": { - "removed": "d5274c428510c901af0c9ffb10c028e9b6bf22aac5996ba90d67b1cb1eea6ef6", - "readmitted": "d1ab687812e8cb7cfa16a0f40e91d88448dd5ad67ee2bee19deeb9ebdf4b99b0" - } -} diff --git a/docs/concord/vectors/groups.readmitted.document.json b/docs/concord/vectors/groups.readmitted.document.json deleted file mode 100644 index ac0a437..0000000 --- a/docs/concord/vectors/groups.readmitted.document.json +++ /dev/null @@ -1,710 +0,0 @@ -{ - "commits": [ - { - "id": "commit:3df334832b1fa2864b4c6776e325d176b6442c18ec2c0c4f5a97c52b1e2022b1", - "signature": "xsWkolFXPZ3r5_fvUAvHug3EJ_AKVQBu0pMR6PeOwlMuIP5AQcNVXTEcvJ5gziSwjPsyRiTJHCSF0CynEa0yAg", - "subject": { - "committedAt": "2026-11-21T09:54:00.507Z", - "entryIds": [ - "entry:e3bffc0380c25eedcb99cf5e7dbd78f5e1516ba75abc63cbddcc14ea13759237" - ], - "metadata": { - "concord": { - "model": { - "id": "concord.test.independent-groups", - "version": 1 - }, - "system": { - "id": "concord.standard", - "version": 1 - } - } - }, - "nonce": "bDM7WdZ6REQxOyW-n1nxfw", - "parent": null, - "signer": { - "algorithm": "Ed25519", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:550074abf0ac8418bf49971861db5c966c181ff5bf1952e50f760ddc29958ef7", - "signature": "EVOTxofHuBNNjYAa7cJhaTBOEsFDut0Dh17cxOGep-HJjgEfikOw5PS1U5D38rY1qypWm7L1cDnI1M0-XmxzCQ", - "subject": { - "committedAt": "2026-11-21T09:54:00.550Z", - "entryIds": [ - "entry:2b699596f1cb6b1367becfd6bc95ad8d84397a0160609078c2accc9a834daec3" - ], - "metadata": null, - "nonce": "kJky70KH8ClsjjYANK639Q", - "parent": "commit:3df334832b1fa2864b4c6776e325d176b6442c18ec2c0c4f5a97c52b1e2022b1", - "signer": { - "algorithm": "Ed25519", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:84564cbbca000cd0e991137a7f1200c42bdc28f2e1e15c548506deb8b68b3564", - "signature": "lUXspbUAb2uTGl9RIbsgedu9dZ7tBronZAlms5b-sOH1t9n3yczjRB99r2QbyZmIqIPsF0DtnbZtNtqfXg2XCA", - "subject": { - "committedAt": "2026-11-21T09:54:00.607Z", - "entryIds": [ - "entry:a05f26bb8f040470d0638f437e4999ae786aacf2a87d3bd7c715067ce8e45c62" - ], - "metadata": null, - "nonce": "ipqK2kabnx68dopMa1CUjg", - "parent": "commit:550074abf0ac8418bf49971861db5c966c181ff5bf1952e50f760ddc29958ef7", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:9075c437ac992ebe65554656e91038513a712ac2e933547878bef5ce0432a1b7", - "signature": "kVz9ERGyMCNAy9t9S5MRMPRcBgfHj7L5ImYewQvCkfL_WMWiZaPcGI1vGV3xuwrQzfsHW_CRdRMIyDo25pgXCw", - "subject": { - "committedAt": "2026-11-21T09:54:00.651Z", - "entryIds": [ - "entry:f1b176831eb301acdd59b6cd526b6041076b34d2d60cde019559826989201eee" - ], - "metadata": null, - "nonce": "ryXQU4ULR0n-etcExa6Lkg", - "parent": "commit:84564cbbca000cd0e991137a7f1200c42bdc28f2e1e15c548506deb8b68b3564", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:d3b4ea042dbbbeb9e4ab8d20b0a8dba1c75b91bfc4010ed29e81edb53fedcefa", - "signature": "_2xg5N_WTwekRC24RYAyuPiyKT2cyEAbHjN8i4Hvv8qsdtA9UiFUyqe6CIzg-CpiyDktmGma-dn33CdtN8M5BA", - "subject": { - "committedAt": "2026-11-21T09:54:00.707Z", - "entryIds": [ - "entry:68ddeb62301a045c900ac8c96b9fb774c8f8436d396b90f8992603667b640d1c" - ], - "metadata": null, - "nonce": "BmuMbtoaoR2-Sne7GEce4Q", - "parent": "commit:9075c437ac992ebe65554656e91038513a712ac2e933547878bef5ce0432a1b7", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:409e4213310057fbe1849663b690d0059910564209867edd2d7303acb07b2e31", - "signature": "84ew6WCQ_fEA8gNNfN7GdY_pYXNWLmATs4sSXCSbl3qjD1s7TB2h7mCrFqF7OKPo1Hoezzx0x5JdPGcAY77rDA", - "subject": { - "committedAt": "2026-11-21T09:54:00.777Z", - "entryIds": [ - "entry:f050e2916ac2ebba1e1aa4e56c95944dcddaec5b90c1289c51e5f053fa57523e" - ], - "metadata": null, - "nonce": "hosRFKAPRsNDDD79wh-A3g", - "parent": "commit:d3b4ea042dbbbeb9e4ab8d20b0a8dba1c75b91bfc4010ed29e81edb53fedcefa", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:5d0bd64d3cb9ea67ff6d3b29963aa774e3c6409f9f76a5ab510eb449bbbd10d1", - "signature": "c3PsXWQLKgMoZjtM2Ug3mUcwVIaOnDPP2uu33a0H1RdxGbC4bsMAnXY6Vlw0vWbnNCXqiok1JHCdtoUIOVVBCA", - "subject": { - "committedAt": "2026-11-21T09:54:00.857Z", - "entryIds": [ - "entry:974aa191deec2a9d0e7f99ad83a0b2979de9536cc016710d788e7d06bded9a3b" - ], - "metadata": null, - "nonce": "weIzBbNIoXLHk8j5UVlzSw", - "parent": "commit:409e4213310057fbe1849663b690d0059910564209867edd2d7303acb07b2e31", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:f41f8c2a26a16a0bacada86c46de45e0f30a3d0f2a7c6d2561efcc16acf88609", - "signature": "cD1aMdSKpcIYzVn9fZ6Rfn-wB679rZt5gOeMtLh1ZuRIrQVP97DBVWy64Rjrn-GpMWOjpRhpyIMXud-uIMuuAQ", - "subject": { - "committedAt": "2026-11-21T09:54:00.946Z", - "entryIds": [ - "entry:788a0b4f685defde5dca6168a90fb7779dc1d14cf172c167b527bed230d87c8e" - ], - "metadata": null, - "nonce": "u0lIhTR4H_NSW8nNj2E3lg", - "parent": "commit:5d0bd64d3cb9ea67ff6d3b29963aa774e3c6409f9f76a5ab510eb449bbbd10d1", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:b7994bc826e1e0a797a90bafb5785b59be0e452319b6e099975626295f3787cb", - "signature": "LN9ZWEcV36fQp7mhCo38oy-DZuNwRv88IUl_TMNCjYF8PEqt8bawrq-QTK2X78ozuCT0a2rGIy95j1U53MylDA", - "subject": { - "committedAt": "2026-11-21T09:54:01.111Z", - "entryIds": [ - "entry:16fbe65be6cd2e18767c6b911d73150218eebb8237379b672e69544e32c4b98d" - ], - "metadata": null, - "nonce": "Gdl_1volIOYBe1_wk-Q_MA", - "parent": "commit:f41f8c2a26a16a0bacada86c46de45e0f30a3d0f2a7c6d2561efcc16acf88609", - "signer": { - "algorithm": "Ed25519", - "id": "identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "publicKey": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY_k2NsFGFKyHN9E", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:907049e2ffd92825ba2cc47952d8c43ca862c891cbdedd67cca3ab07d3d55dbd", - "signature": "HMmr2J0n5bM7saHYK5aqJoYTN8G2kFEIvRMN-e1wjeJYOBgpw_WlPvaCD6c4ej8iWyug4or0_8-TABtHGrecCA", - "subject": { - "committedAt": "2026-11-21T09:54:01.297Z", - "entryIds": [ - "entry:1657e406aec860a6a1a31c7fa24c550ce965b6b0e5b86547e29a5c7967c7da52" - ], - "metadata": null, - "nonce": "VG0UBBKzNS2C0bIKierplg", - "parent": "commit:b7994bc826e1e0a797a90bafb5785b59be0e452319b6e099975626295f3787cb", - "signer": { - "algorithm": "Ed25519", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:5c69a03d3911dd7d3a535c8a3f55cca22dca44df8203916977cf7202d4d8667f", - "signature": "SgYd8oowgVgjNZIT34M36FMTK3a60naNCM0OHFu4PQ5lyUoxWVuGX5N8hghYioSR0OoXLut_sdrfthcaqWNhAA", - "subject": { - "committedAt": "2026-11-21T09:54:01.495Z", - "entryIds": [ - "entry:de77783d68a7b8597f9a0b85f4c7c0b396ebff2f9871de10512454c2b57f2be7" - ], - "metadata": null, - "nonce": "l7lFXu5eH83xnvvxOKbUPg", - "parent": "commit:907049e2ffd92825ba2cc47952d8c43ca862c891cbdedd67cca3ab07d3d55dbd", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:a66fe891d23f1b9dc6970aef7f788be4c747d1a1345ec32ffba84a83f1183443", - "signature": "EMhfX2LI0a26tYxBvRI9bDTcnD013sOEufHBZ_dadqRul0UtDM7_eW7Y1vGLYSycyCdxM_Nh6RZZpAjhW1_oAg", - "subject": { - "committedAt": "2026-11-21T09:54:01.626Z", - "entryIds": [ - "entry:efa98130d44c04e8d8988ce6b8dbfca7478647fdef83748c94509f347c6df4b6" - ], - "metadata": null, - "nonce": "oT76IhM2rJaxSt00ssgbIg", - "parent": "commit:5c69a03d3911dd7d3a535c8a3f55cca22dca44df8203916977cf7202d4d8667f", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:785530ba410faf42a1c8c6f0449702f407286b10652ceef51b76b15369f98175", - "signature": "ay1ghIz9CqtI_-IkWML4G_e1opyShDNHsx79qgrMdqKa8cPjwtQkThhW7_Utd9ckLq9GASzSAVbOlNMKqLx_Ag", - "subject": { - "committedAt": "2026-11-21T09:54:01.768Z", - "entryIds": [ - "entry:39c050f6b7fb1e5e5ce567c795a68c797b0923ef56746711a134fc47dd83a13c" - ], - "metadata": null, - "nonce": "Vli8hBDbLr6f5jJYLf1lGQ", - "parent": "commit:a66fe891d23f1b9dc6970aef7f788be4c747d1a1345ec32ffba84a83f1183443", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:8fde4c90a4669efee735bd6cd325bb66dd50fef826a6717af2f81fff19962b1c", - "signature": "hqsDpyaQgFs2m05JI2Hto8vVP40HDvPafvANDXcG1TlFjHK5v5PW8Z6fK2ZPJgBietYRBJ48Jas4gP9sNprUBw", - "subject": { - "committedAt": "2026-11-21T09:54:01.920Z", - "entryIds": [ - "entry:bfb3fb1b995a720d68091c06c85fbab67a0fd7cb5fc88e672d870f43958b121b" - ], - "metadata": null, - "nonce": "1O1l6xxgRCsc45HNrYwYrQ", - "parent": "commit:785530ba410faf42a1c8c6f0449702f407286b10652ceef51b76b15369f98175", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - } - ], - "documentId": "commit:3df334832b1fa2864b4c6776e325d176b6442c18ec2c0c4f5a97c52b1e2022b1", - "entries": [ - { - "id": "entry:e3bffc0380c25eedcb99cf5e7dbd78f5e1516ba75abc63cbddcc14ea13759237", - "subject": { - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T09:54:00.502Z", - "kind": "system", - "meta": null, - "nonce": "7Zf8I8Rtas6D4GJGrFtddw", - "parent": null, - "payload": { - "data": { - "data": { - "audience": "document", - "epoch": 0, - "owner": { - "algorithm": "Ed25519", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "version": 1 - }, - "recipient": "age1yw9vprggazqjue3t2fpcwcfkcayrhfs05j9yvzsgt8tz3jyu45yqkn67p3", - "wraps": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBtYjgwbGYyclUybWlDczgvVHlmcTBCWnptTm9JbUZxTURYVG1xa0RBOG44Ck50RUg1bUpSc2NKeUtaN3IvRFFIY28zR245aW9qZ3dpQ2IwaTMzeXJIdWcKLS0tIE5QWkxlNlBETGpTSE04V2NMelNLc0pYYUQrUi81WHFsQkxqYjZiVkpGYncKMKcMWD_AaK3ZjXjpkwyMUG00_9QxZGMONZgYuD695Q9czdhjgUP4Y2CeVvszHCl_ec6e2qhnVq_sfqUuNE9UVr4YGvS_KbkktnUycihJO58OJmPE32UCrAqdwtqF11ljB7sLzad2wbfe4eKjsSmpC97ohD6i3QzZqf5ooiAWEuLWQPsKnA7Iu2-6RD_Eh4WOJDyx1_X-Vo_asyMHPHXDVK2nZpkqpn45NdNT-toSWKu36aS1hOrdTIrptFmYdVz_FuYldE649YuaWBcPt8alUeth3yZxfOeqg2o4sY-wJ4fSyxgg3s-0Bpv6NEHGvuAHcW0XwGbIcP4CxVuR47GqVBI3YUtS96JKdhnwCLAOIa9l7hAi6O3qlaPWdO7pFzKpN2XwNzX6vqxXmHwOxo9ULu2tz6vI-mHwFJs8YD5P_k9dNCFS6ouDcaU3e-pIggVfJf4Gio2-vIxmjjjwO2a__1EQ1_OxcLahH6nUR9mKCBw", - "identityId": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - } - ] - }, - "type": "system.init", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:2b699596f1cb6b1367becfd6bc95ad8d84397a0160609078c2accc9a834daec3", - "subject": { - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T09:54:00.550Z", - "kind": "system", - "meta": null, - "nonce": "MjXr8Bs5TAEDibZa3srMqg", - "parent": "commit:3df334832b1fa2864b4c6776e325d176b6442c18ec2c0c4f5a97c52b1e2022b1", - "payload": { - "data": { - "data": { - "audience": "document", - "capabilities": [ - "read", - "write" - ], - "history": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB0OU8xdG5PM2NlYmhOYVBHZjNNelVETk5jOThUaUlEQ0Q3NGZsWnN4NHdjCnJmaWxKT3ZpVnVMMjlIMjBlQUlxaFJiNjhkVVJxcHBhMGQyZ1ZCSE5vN1UKLS0tIFg3RHZDWmtjN1lVaDE5dEZCYTFJV01vSEs4cFVKS0srRm1FeE9MVlFZZmsK4VSTePdhum6D1pod_7T7HULOA5HblnioPUrRAikbJEug_zakn-5wxQF3y-ZUfHetZICeUxNDP2hgwb8SdZLRJWL47tx5z6p1yXrO4pzXzxGPGDHcCgCY3EJhXWnEGAhieS4mJx3MmvUYUjyJ4dFeoDXfp-S0u5pm0bM5bGGqfct7kG-2FP6drDC3egINegu4Ko2eBbhqDLuxNlX8SDWYQVS6lYD2253vdfuCGJIX6VU61rLd-yTYkgHlAP4wp0kwXW374LlAYIvfAWqkuNhDIUXCSRdJYkOEl_EWbevQIRHq4ywd-ZyIjD46cx2hdJgqde9MMNzTWv77WlMC5Ymf8u8C6lWLTYJLXEQsThUrLnGXGtccOFwCBcv_MHG8tSb03mfxYD2CnafshahNLOK5qqdGavBXQ6vaoxPSKKyvU4F-W0B4jl0HAG_IzivWuKR2jh0aQc45XUPdu5NTSWe05myNyo3s1Qgw6Pz1Y7EsvFf3dgBGF5LhW2livXLjePF33lxAp5aoVZ5KRPGErkdNvhSJXaATQ6qQdG0j2zQISOdD0cLeh_dDySZmc5Tt8h5JjhtKuFk", - "epoch": 0 - } - ], - "identity": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - } - }, - "type": "system.member.set", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:a05f26bb8f040470d0638f437e4999ae786aacf2a87d3bd7c715067ce8e45c62", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.607Z", - "kind": "system", - "meta": null, - "nonce": "jF27KKozjxZvR10ltCYhpA", - "parent": "commit:550074abf0ac8418bf49971861db5c966c181ff5bf1952e50f760ddc29958ef7", - "payload": { - "data": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "epoch": 0, - "recipient": "age1zjkq9gpqclyj7rqq2qldx6l9m3yfvm8v9u8h39e9uaj204rqpe3svmyh4x", - "wraps": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBFakQ5NWZyeVppTnFuc2FLSG14bHo3R3NVdFBLZHQwQ0N3Z0M4OW9yTXlFCkpiZEFNeFloUURyWEdlRVJnRFBCcmRCSVNRYmk3NTlYdjR0R0V3aXVMVXMKLS0tIGJnT1hrNEQ2YnRkR1ZTenBZYXdoUmg4ZWg4b0ZIeEJwd0h1bEk0UkdickEK8uiGY5syprGuCn5eXJiIdyCBF8wTczt88-ee47DOgqM2bbA4cm6Hh7fCWtNJM9qOp7KD0HwiAhjzBvOegiEQK-xFgDpf0lqIe-jkfQpLR4XEJgVsWKF-dJugG4QPU_dcPDWrQRaYb5iJQtLFP9S38JhiAhqPAkOxLWLvxuK6DD4l1WKxhzmPshIdZdPBCZAe_0Zq0dkMrPW6Xyix0CgM8vFLChEDWinhNYKc_UmcMnC2mYBrjjN1C3yfp2duY5dUsyCIU5PFhRUPPbYQ7KJ1MBTdhzDY3uiNkX7571qYhdHgDNOr_RefY9ey6V7S1PFVps4ubTeNqfqMmcZckqfIEW9nSvjZKWFSNNHLKJlIWUfaRgqvcRKiyc1_tPboslmVXI4z7yrTPIk3dZEseCSe6kkNPwMnUZWmGQlbSASRqDPhLVvfhJKHM5DEAgw_CXIzfE9cMF8-O7gCn38Rkqrd2LFOncJQmcGRtY9tZfedK2DscVtO9uOCOBJZmHZ7H2G_6AHOIQ8aV0suD_dXxISszzubq1VMyrSCOrq9tcYU_8bfDYf7TPky-eGkFFr_Hvvxit9YrlpBvMGMu4WikPl-lJNVALkGuQrF2A", - "identityId": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - } - ] - }, - "type": "system.group.create", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:f1b176831eb301acdd59b6cd526b6041076b34d2d60cde019559826989201eee", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.651Z", - "kind": "system", - "meta": null, - "nonce": "HwNpXQsOVj1RhX5RqokwTg", - "parent": "commit:84564cbbca000cd0e991137a7f1200c42bdc28f2e1e15c548506deb8b68b3564", - "payload": { - "data": { - "data": { - "audience": "group:tZkn2eFhVW6ofURIS0dRwA", - "epoch": 0, - "recipient": "age1xt6m3ac0np0kudxw8c6j70eva92k9qlh68ftx8wswy4n9ky6udrqvez0ga", - "wraps": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSA0Y3lKa3lIVmdLNkFmNDV5WDdWc21xc3hGa1hYVnBjN0pJS2N6Y3lTcWlNCjlZdzA4cEpwZkoyRzRObkdXeloxU2Z5QVpqaFhQYmJiZGtQQUltajYrQWsKLS0tIEE4Q3RzU3VYUHVEbXlxenU3a2hlYkZHMU9EOW9uMGdGeGN5bzVsZm12b28KrsUUpMN3ClKR-48k4tGtzDlnZthAB12sJHtpz6zTmrp_65EB-IYVUreux6JPfH2EEd-BTrw_si__26xVNjrFGObp1japHDYqyprwIILkUfqTwUwXsauk9AvYcIG2-Di24ldby001X7DRxm7LnE7RhWbek76VU_Wm71vVCrcRrvGLAMDim0J0HADrycTBKXeryxsYQeUWeZhGJAUzwR1iLf70ObCgRs9HIu7jyCnCQgtt7sk34jUGqWplqx9gK6icxnoE0zengG9xKnFm0Cn0Qi3Qv84s6VpHvVlfdW-zpQjr0xSVJwKSj4mft5MA804RlwdsM-0jeKW8SS2EDPAjk4YDJlfl3ehgEAHoMAncvni7u1lcvrkHqQdIYFINqgiZv1HavIbyIGDCmiCUozu15uBdWPHt-APc6uWgajVOf3R3bxWYHh5KmdWUNQD_AErgGSfUsyjD0-HwRU58YKi1qvIv_HQjUTB5USDl2lwTJBJU7Q0xH-1tSh99CC32w5DVb4e3jxogBkP_9M04VeYfnqdelkoMzFAGJENY2TiMd-U3-ISaeilQ4pbOUUzECv9MPwU65VS9dMyx6AJtyIYX3QR3-kabsOVmlg", - "identityId": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - } - ] - }, - "type": "system.group.create", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:68ddeb62301a045c900ac8c96b9fb774c8f8436d396b90f8992603667b640d1c", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.706Z", - "kind": "application", - "meta": null, - "nonce": "oSYJYzQMSWuFDVDKSHQBaw", - "parent": "commit:9075c437ac992ebe65554656e91038513a712ac2e933547878bef5ce0432a1b7", - "payload": { - "data": { - "audience": "document", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBadWdqTkdOcXYrQU1EcENmcGUvOXF1bXN6QVZxRG1vcmc0d2hrckQzYkVVCnNIN05uK0VUd0FKY2RTd211WlcwOXIzM2xKeXg5SUM5MVJ5eXZuMDd1emMKLS0tIHVhQ0R5OEFKemN2Z01NS2U1UW15Rks0WXVwaXJwMmcyMTBYbHVmeFN3WmMKiih4OBZ5f6mIPy1NarSGqYWWdFJtNuN5bxCZ-66SciY8W_ypSJ2NfwNfdXNWQZBGbObxrysC_S0txpoJTfsYqvKKrnA-hgVA0JVLMF6v3W6NiE3zZ3UwBmJuoblXTTJPx8EqmGWUUftW_-dYaEXYBAaRNLj7BDfWTyInCg5YNJmlVSOV842y5Ku83072FseJjSVi5s7S_naNTdOOr7pJo4nuwA5gUVpxl0qcwpgkIFb_zdtUNO05lvhlqSxUtL5iESul2y_SWcwAQrhaoIoi89B4OLa7kg67fM1tzwGuvvKAz5v1FLPwdzngaJpfPit83xbxm5LdUuLsfcThT7LjYVY3HA7dJCnwhJOc5QEP8ZEgzXOWWKyl1Qm_80T_e39pDAIjqWaRjC-CNXmdEBUjP_9whqk0eLj-3IeisjGMJn8mTHJKIjMQP4uRIaqsBiUKX5cPNa2YPgEM0Y-pGneqvrk7Rp5XW4LhvoyLRpjr3Zxdx3uPzm3ow0Wb9De7Q01f4yMHUUZm4oo61Dji1iK4bqXNOn7a", - "epoch": 0 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:f050e2916ac2ebba1e1aa4e56c95944dcddaec5b90c1289c51e5f053fa57523e", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.777Z", - "kind": "application", - "meta": null, - "nonce": "UoEZwXHePEKefg_6uL9TwA", - "parent": "commit:d3b4ea042dbbbeb9e4ab8d20b0a8dba1c75b91bfc4010ed29e81edb53fedcefa", - "payload": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB0QUlCWWtWMlNrR25CTVZsTTFXek9qMUdBMXhzWXNBZFVGZTlYdVN1azBFCi9SZFUvSUpudnBHZ216MFF6YWJRNk9TeE16MkF3RlZXOStLajNzMDdWaTQKLS0tIDI1YzlJWC9KcFJvUHZMWER2SUwrdlR1SW1yV241UkladStBZ3VRTU0rQTgKwEoTy47B6qBNzheP4KgNvs78wBNqGGW7BekYg1fV6y5SUTrwP1R0rZirJUsrlfXOV0oTE23V8uw0fLOmwvvqeer4eGrALosk06ie1-7mxUNKa1BGE4GfXRnIcSZXY4daztAINkHycaqTa1L9onBstPQHeuQID8vPLe9qaypPalKyb3d4mVwjCRVPdqMnOXu3Ing1pb8IY7sq8yUT-8zuuk3mLJUowAcHBxNJKfUSBREmyfwYHOMqM3I3LL6x6PVv9PNdguDC1_AnyMCoIMOB0Q93-_kKKL6P0AUHP5de8bb515HMBkHUGAk-kqNkh8Ou21jbZynEY4u_634ZJEcbf8fX4AHs9T8v-Idd5yofbQcP_OrB63YFaAgrp6uNxCnq__MnD27JINPNikbBhDoNjRnaO1I-Y-oPS2AmHOtdfXzeA8wg1tkjOOqGNcRxkWhMMVocwgintCXeR9OP5J8tkGP6u0-5pZY8OaeQNWz3XEyTFW1bd_nngcTEt5meKO2kIUibwFcSmH0XQVtNcGAeO2FK2a92DkTI69pISlcFgRoANptKovEh3J9IYuNyt6g_TKsbMLVqgiDnmsNfR_Y", - "epoch": 0 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:974aa191deec2a9d0e7f99ad83a0b2979de9536cc016710d788e7d06bded9a3b", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.857Z", - "kind": "application", - "meta": null, - "nonce": "IXy2raI8ey741BGHcpOEMw", - "parent": "commit:409e4213310057fbe1849663b690d0059910564209867edd2d7303acb07b2e31", - "payload": { - "data": { - "audience": "group:tZkn2eFhVW6ofURIS0dRwA", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB4dm1XdlNKV3pCbU13TzIwYk1mVkx4NExiMStyUEViVm04K0dndjdkUG5rClVsblFuKzlqaTBUSGZXM0V0blZ5dER6enk4T3BNb0hvZmFJdTBxa3c5bHcKLS0tIDBSR09KYk0wbHMrbklWTFpTTzY0ams0UW05VU93ZUFZZUZySkVRVjRjbjQKC-XQza208BnzhH_WxlQpb_mOv9oH6SgIFz9sCW81vIN9WMRvRaFp8vJxhjd7W57-wg_dG1DJS5VtXAz6Na6L89wzr9bAL7nZzjSzibNAvbebT4MoVIfKPZQ9tMjMlRBQ5g9XNnawAQlIom6yqZhDnH3E23N12CvsuTLgc3PkXKWpUUut8VxS1UFMJRx6-PqzYMGAo1ZJM1nu5slwzOgfUM00Z_0dg57rMJ0EiZcnCurGjMrSKHnwcmPZzgysdYhzRjGlltoYSHyml36u16FYIJrGaYsj2J0rZaanVl1aLYNnGrUurxkUTN9s08ZlWIo6dJVrPBvnocMwAeys0DcEIIIqaXuFxI7KIBifFXPgYhAbh-cHbC1urIJgwLvktS_6he9mR5y47rWR-yw6wPODDZzMo2C_foVkkCflDu10s_ye08QFxFMY-_pLp6EgzqUBZZoRNBwzDn1R7qXxnsUWtTWHSfIYd8EpyPnvwVPdoFSHTi5t0nlflnZy-LAZ8XwprxHphm_GNQaps86ovq101_kuVd60j54WbvJHXNNgeocQqU-3PwI2nEIiEAIUQcPvSuBhWJw_vWj7RF7JfsmhyoXtvA", - "epoch": 0 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:788a0b4f685defde5dca6168a90fb7779dc1d14cf172c167b527bed230d87c8e", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.946Z", - "kind": "system", - "meta": null, - "nonce": "FN9MqpLkhx13qZaPRcz-5A", - "parent": "commit:5d0bd64d3cb9ea67ff6d3b29963aa774e3c6409f9f76a5ab510eb449bbbd10d1", - "payload": { - "data": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "capabilities": [ - "read", - "write" - ], - "history": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBobUJsYU45MlIyaHN3S1RyRVJaRSsxQkNNV3VuQTZ1enZvNmxnS2prS2hjCk05aVQva3ozWFMzVWpYNmZFVURaaVplTTY0cmZ2cWhPZGp0dFVXQkgxUncKLS0tIEROLzdCTUF4UWh6eHFSWk1WczF1cXBHWUdYb20wUzR5Rys3L3pUcjFDQ1kKtP4lJkm7MqWCyC25WjcZeSHnw1EVC2om2cKdtWaIoU-TiA1buN2FPN56KLbaLq7lSfJ51TBj_6U5_HQVxT-cZWtBAmmyTuh3rF3mCMF9AaA2OAfcmCgndBrJWohVi_rhkWvxr5eL5QrRj7m6aSCZjJTiY8iRAePKAV_Mar5UU9IVT5deNeZb6LjEC-9qUzkNShUWMGJGCFOg0LzxaKHqyaCDHefUecvf6dkzw2ZOutG7F-yRa5Tq3_cikp0JCWCbypMhjQkNkduI0lsFsQnldJrF_G8mYX1c5h_byQC0ikthkTP5uiUOiEEtYRdzi8MfyRkHZ_aHQQZUwej8rqNP8wdVy-YnxIRg0-ia-BqxqKxVtjJcRnIqJNO_eVWahrvBq9XqsfAjQiqDJ0s9l5bYnaRwrzsr1Fwx4FiiGahg278wLjugfy7vVQbK49Lyt0rumNwYIo7CfqZUbbdJskZqknZ2Dsjfh-O-KOaZ_3Pgq22UF0Kh9GmMvYnGRJVaMA68hOQy-RTRdnU9hVolvMOskd_wRVBag8B1xGK-zGS3MzK7Ii1IDfL7KuJ38o-pHC4lDOwb6tA6iT2oCwJeia-oOd5ojlX95GhjAA", - "epoch": 0 - } - ], - "identity": { - "algorithm": "Ed25519", - "id": "identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "publicKey": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY_k2NsFGFKyHN9E", - "version": 1 - } - }, - "type": "system.member.set", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:16fbe65be6cd2e18767c6b911d73150218eebb8237379b672e69544e32c4b98d", - "subject": { - "author": "identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "authoredAt": "2026-11-21T09:54:01.110Z", - "kind": "application", - "meta": null, - "nonce": "2Cop8P3TdAGd8MyPcsw_eQ", - "parent": "commit:f41f8c2a26a16a0bacada86c46de45e0f30a3d0f2a7c6d2561efcc16acf88609", - "payload": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB1SDkxdFltTldFWkt5WkVVM0crUjQrbUkzRnU1YmtUSCtTOGpLK3ZLbXpnCi80NlpaN3hiOTVnWlBnVXVnV1lnL2QrRCt3eDZyaTJjTkFKOEU1SXRBYW8KLS0tIFRvbWxCUkZ4SWxBbEpiTVN5Vk85K0xiSTQwcnRMOUptdDBJamRoMzdFS0EKJnsx-4BLzeknwzpk103GitYJKqaFjF7JAi4dkt3xN8f4Ms_wZUrj9frP0dVbHmQvCHC7KV2YGBD9hr_vWvfF8GT5gFjiMLjbHzERIVzp1F2avYx_wFhcp3ZHGrSks9L1HEHsnm-FZ3YzgErXGVApP1021-3mhtU1SQ9Qy-NTQW2F1exwmJ8U5qCAyhRwz6G7Yav1fNOc0XMfzYQ4OLiz3eYaZFApcGo0gMr1bEc6MDgGUusDvxzms8Yet3Mj52cWOpvKyWZP_PDrNNK3HUbhz3SF075YC0SZqGBm4NxLbVb6igFNfDjCx0Wls1Mm1zjXLk_cehn8fiHZyRgoiKVN8xZxagUfrISHEr8GmglyKabsrBf7wNrFbFFjBxeK1fj3jrKPeQfMea5fh14ugKMs-PxqkZrIw5qgZFR4DEuC649KvAk3CVngd9NthJir1d10SWSLUNShf_vyaBltorzovl8nM1AnPvpSDKOLfFHPA7D8rHzExuYy6WKCqkoIJ3B736Qce-gD-_cNR0-NE6ByPN7vb0NVu6mz83QCbMYnCiPKOXzKe-jhTPKf2Ln3z8CC64YydluZJw", - "epoch": 0 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:1657e406aec860a6a1a31c7fa24c550ce965b6b0e5b86547e29a5c7967c7da52", - "subject": { - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T09:54:01.297Z", - "kind": "system", - "meta": null, - "nonce": "tSu8K2jRuH7G5QNPSwYwHw", - "parent": "commit:b7994bc826e1e0a797a90bafb5785b59be0e452319b6e099975626295f3787cb", - "payload": { - "data": { - "data": { - "audience": "document", - "epoch": 1, - "identityId": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "recipient": "age1z6ljgmtdq6ntx3rjy8hmp25qfarv8v0fan896esz6kj4f8swpc9sved2ry", - "wraps": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBleExrVDhKOExCWm1mK2pwRmlTaE9MQ0xvTXhwVmlMOXNpMjEzMmVpbXgwCmVJaDdyWDZCVkJNV0VNY28yVnNxOGJTTG5EUHpTYUFhVEErdWtadTRVSFUKLS0tIHZ6VVN3RGNCQlBKWWJRd1VKY3ZnMThmYTJMbjlBclJ5b215cTZueFowN1EKiuHXaAxBgC6ZZJqUNRdinfvo9WwtcGMDDR82bz-SjEsjA_NVYxKL_Fpz5poON1W55MjiH1wkailhpO_eD9eLpI-K4RqhOTtVHqDhTcxibAeoPXcyt5_lsIbmY8IKOToiB83sJrte3fbCMeIBwLvJq8vNaYw64iHYn2wkE_y0AhzpxwWmtP48dD1EVPlKVrU075jsoCsGkGtVJhR8k1sXn2HV20xeByKdvAqOTGJnR9c0bJC5jB3fLe-ZLSf4ZD-wPcs3iF9WswdtNIUo7Elnd7XBx1Ajc4_vBAoHU16meJWW1I7a2Z7yz2OXTM-nUteJxMI21ylQ0QHuyLihrum8MkDb6Tss5nM76uuG6j3FDIB8qoJh0boDBFKJo22xNa4i5l_Nu6wRC8q0BAYb3PPRdCTHxeDpaSj605GJx-8S47IRgBJdJS1sqGvpu4hwOLk2HfpkXhz8gX2i16Aa01nS8FAvlzcD_xXm3zbo_82wiD39P4pLBXpjVuffZuOPerd6CAGhBVt8679zYjcwX6N1J4N6yMvoELdEPO1mKiqgClLj3x2gbm92CkzU3cl1hJbU01mIKDc", - "identityId": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - } - ] - }, - "type": "system.member.remove", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:de77783d68a7b8597f9a0b85f4c7c0b396ebff2f9871de10512454c2b57f2be7", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:01.495Z", - "kind": "application", - "meta": null, - "nonce": "OMEIA5O4-h3JMbmzdjvU6w", - "parent": "commit:907049e2ffd92825ba2cc47952d8c43ca862c891cbdedd67cca3ab07d3d55dbd", - "payload": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB4WCtPMDJoOXBKWjh2bVZBWUcvME4zdmV4SnRWMTR5TnZUYXFla1lDa3dvCm8ybkI3cXg0YkpLa0ZZSTk0Q3NGcmxmWWg2ZEdJYTVrU1grOEFCUXBJZzQKLS0tIG5HSE1jWGpMc3RoNDVrdE5PbXJoWVkxelM1b2R0OVZGekJkMmo2T3VhSm8KSy7uTKFqjSBPxU4cEI_1rQfPHW9sZlfjdr3Ivm4jm3phrpbdVGL8wQp-kZr5vs4oYVvDkDhmDXUNBVLXcDMeKl5algfw6J0vm61z1BN2YrLubLAaGZeIdbXAJqSwD3_p8adBHL2THR1V3rztl0YeCC8LE_9OldW4kcR09MOy2woYKud38lMrsgWPhvoBinS6d9zXwb1ExGY4x9yGMB76PKGl1yTuBP8P2au4m_NcTx61QrGjXWiKMgVZfy_TrHLSBFDULPjBaEw6UYCHJYRYLWgDh9oaJx-sukeLYEaI9pf7xlPBrOUONks7wjp0c0BfPqalo9Atam6bnwP1PuykZTnJq8dz2As5fCfKim8OfgQt5nWe05mXuHeJHpxrb21p1g5eu9ptk12XepRSQumRuXKvPEhzJARYEeB65zsSwSgdVFoua96VgOjHE_rY6uJI4b-aO97cq68LVSKBfSo5Rfh7pNS8EPzWmduD3CtcQciN5yQLt6HjZPfWB6JGAifGzdeoz5vciYBJGyCDqw7JHQqTal6MZF4dxxrdq7r215CRtsk3c9DII6qfnPMKMAxUMd6FUbraUSZX-Kd_skx1w6D6SCk", - "epoch": 0 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:efa98130d44c04e8d8988ce6b8dbfca7478647fdef83748c94509f347c6df4b6", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:01.625Z", - "kind": "system", - "meta": null, - "nonce": "GHYakBv8OBPiHFtQcAsQcg", - "parent": "commit:5c69a03d3911dd7d3a535c8a3f55cca22dca44df8203916977cf7202d4d8667f", - "payload": { - "data": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "epoch": 1, - "identityId": "identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "recipient": "age1t9uv7yh5g37sskw2pegmag53la3xje0p88atzlqqlnqpcjwd3azsmxduvm", - "wraps": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBsQk52VHRHN2JacnBSSllLZk9TSkVnSWNiRkxFMWtUT0pBYnU3eDRGTHlVCnhHNzYya08vRlFyV3ZNa1U5aUZua0tUcTMxSG8vNDdneU5KazVMYm9sSFkKLS0tIFdqSTdTV2JEcklOVzBzYmRrSHRrb0dDa0ZyS096M2JaYXNpUGdjcWhPZzAKtmvrW-AV9MuxrCuA3ezq0Lvzpqb5O3kYrdM8eyeLarvpP4GsGIk23IjsNsw3fK1gYV2uWiaF2GJyEsdqwtvT_IFqDvYJp0G-6fCQlIC6DRM_rNlpJbxtuok4aWbeM-hVj4Qajz3LQfCrnZKEoE8XQK2p8uIl-X6hXI1-YOzlY9J94v3XNa5NrsXgd0wF6-Xw_mQJkf7Qfm0ElVm93aAQ9rYiynQBCzEsZNeri8luHdQk8KHcVrC8B5NMKNq5GmSboFu0m2NE2kkPEQi4FdFyjH5BAELkolKiwNnCA_1Iv2RZjb_hPYbuqp4f5dQN3mC4F9ENfHSTsjpKn46QGyjq54a80BzqXw5aL8EUOZhmxttlm8WQZUygHCIqgu7NLBJBTXPk_nRjDRG3PLiMhmhY4B3mC8aM5_KL-uuYRZ1MBs6kKiQ-VvWjXnWerAHgmNGDnhnGduteIupnIdaDnBB06xr5fT431467Veuj9hpZrJ7YjwW1FKczgV9bUG-SDTW8J8p1ESq0kcegSEJjLMDpK762a1sDFFTTrE7wiRXk8DxektmPGn0ncf9JAinbiJz9LhWGX9JeY73JVtOHStGoFVOKZE_3KeFR3A", - "identityId": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - } - ] - }, - "type": "system.member.remove", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:39c050f6b7fb1e5e5ce567c795a68c797b0923ef56746711a134fc47dd83a13c", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:01.767Z", - "kind": "application", - "meta": null, - "nonce": "pRTx9TxaxBPxKYuVgUnA3A", - "parent": "commit:a66fe891d23f1b9dc6970aef7f788be4c747d1a1345ec32ffba84a83f1183443", - "payload": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBpL05MODhMOGRLNmJjTjcvUjVlczNuWVVvRm5na3ZIaXVBTU5kV1dwUHlNCnNHNFY2VXROZFo1bjYzbExFd0pvNjkydFdDbzY3blRWRmd2aVhDRE9ub3MKLS0tIExaOVN6cWtUWkRTcXNEQUFjNDRONWh2VFMrUEFUWkQvVkpsdUZaNS9nQXcKQK3sQT05LEyJ3_vWfwY7TIis9FWy6D14vCAlMqRg8Yl-C2xBcl-VME76svPmzRe1WKmYBPcbbd2j3mM65XK_jEEvA_YPqLSAwzzmjT8PEkgDyIH8NIKFRyOKdOUG3JZQiz1IVd91cIa0YErCQ9ZP-rhSDBtB2Njv-tHEmhGjfQcDibJNMTN-jw2YIo90oFXwvbP1efANi01y_iZ5q0vREZa5aGU7r8IF9T0MmfsV38jQ_Qn2lhsa_MLhaGmKR30PmdtTKlHUNm7JinmicGQhgSo2a8bxqdu6SJXK9Cy5ry4iPNM1ULD-9zDtVdYlKGBxTOPGQaJZvjWtIY-wmfGwPx1moidoeLUPpH-ndMfBi7zd0vFbXXvKJjN-3qZCAq279lpjEKaClP8xqE6WtYLuGtYSy11-TuRAgBTfGNQXpuXMeSRcDj8FwX8qXTN4ujxATo-qgxUfudqfMOuki-x0oUH3WnnuzSq1pPVauT-ezMIWfJ2R-wyUi9Ty4LwaAvL03wvoriH8iEZdCXXDP-JhN0TCDTKEeMTZKJNSutcvOvuX2Ak89tZ5mf52UhuENK9IhxW8vfLCEFEWzqog", - "epoch": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:bfb3fb1b995a720d68091c06c85fbab67a0fd7cb5fc88e672d870f43958b121b", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:01.920Z", - "kind": "system", - "meta": null, - "nonce": "qhpRBSIex4SJI2Eut5YNEA", - "parent": "commit:785530ba410faf42a1c8c6f0449702f407286b10652ceef51b76b15369f98175", - "payload": { - "data": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "capabilities": [ - "read" - ], - "history": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBtUU1ibGNxT1FXMEU1aUdIOTk1YUdrMWdnd1JoMnd4MGphd2dtK3FLcGhFCjlXcUpQV1dEYk1TQ1B4R0pyekNid1FScmFxa01WaW1lNVFjWkVUcmR2ZzQKLS0tIHRnTmxOQTBFdld4RjZyY0NVNjVsL1ZmLzFZQXZHaFFLbHIxV0tJZzRrck0K_7cvGHxT9oR2YPZv_QZBoO0qXEyCplFk6hkFYrWZdtivagz0xmV6Lzh4Z1sWdNCsgqXABEkeigTS5qKQFNdpWeZhiO0QDIFhl7uJvmXz8-MHGjlFgq7cFMXfhBbRqu3srATDTjI9EfjzjcOqo7R3ZFQq5-oPWBsG5iZwbbM2d2gMDjGsZeEsnncVzCIFNNRROFPwI3epOwlyJdHLRE-1TOQwNJlibgwdkCf4KaNM22sR8EXD5_MZ0kOofvr3Eh9iXXYjOTVrtMejIPaZOfqN1aYd_7LU9jmdUceYISGE10Tik8jpKygaTlq0NEoEUXKGrK6aKP_70CQKKa-KtmLxNRZ519RxkZ5PKM4t4L3lz87xFKo5hMWzaSX7Ojv6HYu6Mwx1IVuhur4oVTk1flXwqHydet8JISCyKpAyemABWpa7-vTv0iFScMTVajvYCWu2Fo2oAIVF5YkrPgaYhNQjY0Q0KJPFAHCrlx9-2z-ERLQOzItpZCFdighzcacU0oC7w7pnNnw5Wm0uuyyCaysMJUcEPbeq1AFmRSn0XWWuStBGfO3wcr-vE7VkaZASPcjN1FW8IhUflCe5VevTB6hNP8CxWCyTOW6GMg", - "epoch": 0 - }, - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBvc3prdFJ4dkxPb0taSHRRWGtqa2JHdm5sZWUyYXIyVldweGFVS2VOS0ZjCmFaTmVXSkFHbGxEaXlBY2RnNGgxcEZhMDhiWkVkZXArZGVlZGI3T0NPSzAKLS0tIEpzV0lvQ0M5UTRqdmo1MklxZEY0eHlGZXBVRTJmaFByaC9UV1NydXU5SUUKVl4jV33rnySrlVrh2K0EjmhRYWl-HRK_HKzAxGf6p_a_7CcyyzDH-FqzzcApz4vs-lm1raqfnS2qkySmkWzRVm_j8LCiJqEKRyUlze7QeL-VqNiUQctTgu4dkl78P-6lWpdedWFU_DTOZi0PMe6fVUnSG-cp8ig3-XIIK1OotfhnkvyIggHHG6uNEkpNW0NOJfnhqrhqwRrwfC5EMmBb2EDFOYuiKz2G7s1A3YROdg3yTAoWeQ5SAoYGLhTW7grGgDiKjc8f9wnh_YtzBqZta5xW-vszGJ3v2BvLxqq-ifpqKRR-F0zpBf_y8nGP3p51nGARrlZ1LVAyWcwRN0Yw5RhFm1uyKGd-ZmSadxcq_hOAB21tMblc_vjTe7iUv6DYKnQDTEDfTinmQLwsLYmGljkFhmi6M6G4APw8cwldQRekeJp0NpXTsy_G2BTD-tcJiUW4VFSrHc0VV8qkOPNHSXlX9ADb6eyqoBaGU5VURNqoQS6jnC02AJMmDTgYdUkp186ImxpwHtoimauPMWe00oEkhu2FHPtI2meux0UkUB_Cr_OYuPCApF3cDyRgcQVOZKOXBvKNaTlDzLUDnlpBMMr1P_eBBXcZGQ", - "epoch": 1 - } - ], - "identity": { - "algorithm": "Ed25519", - "id": "identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "publicKey": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY_k2NsFGFKyHN9E", - "version": 1 - } - }, - "type": "system.member.set", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - } - ], - "format": "ledger", - "head": "commit:8fde4c90a4669efee735bd6cd325bb66dd50fef826a6717af2f81fff19962b1c", - "version": 1 -} diff --git a/docs/concord/vectors/groups.removed.document.json b/docs/concord/vectors/groups.removed.document.json deleted file mode 100644 index facf6fa..0000000 --- a/docs/concord/vectors/groups.removed.document.json +++ /dev/null @@ -1,648 +0,0 @@ -{ - "commits": [ - { - "id": "commit:3df334832b1fa2864b4c6776e325d176b6442c18ec2c0c4f5a97c52b1e2022b1", - "signature": "xsWkolFXPZ3r5_fvUAvHug3EJ_AKVQBu0pMR6PeOwlMuIP5AQcNVXTEcvJ5gziSwjPsyRiTJHCSF0CynEa0yAg", - "subject": { - "committedAt": "2026-11-21T09:54:00.507Z", - "entryIds": [ - "entry:e3bffc0380c25eedcb99cf5e7dbd78f5e1516ba75abc63cbddcc14ea13759237" - ], - "metadata": { - "concord": { - "model": { - "id": "concord.test.independent-groups", - "version": 1 - }, - "system": { - "id": "concord.standard", - "version": 1 - } - } - }, - "nonce": "bDM7WdZ6REQxOyW-n1nxfw", - "parent": null, - "signer": { - "algorithm": "Ed25519", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:550074abf0ac8418bf49971861db5c966c181ff5bf1952e50f760ddc29958ef7", - "signature": "EVOTxofHuBNNjYAa7cJhaTBOEsFDut0Dh17cxOGep-HJjgEfikOw5PS1U5D38rY1qypWm7L1cDnI1M0-XmxzCQ", - "subject": { - "committedAt": "2026-11-21T09:54:00.550Z", - "entryIds": [ - "entry:2b699596f1cb6b1367becfd6bc95ad8d84397a0160609078c2accc9a834daec3" - ], - "metadata": null, - "nonce": "kJky70KH8ClsjjYANK639Q", - "parent": "commit:3df334832b1fa2864b4c6776e325d176b6442c18ec2c0c4f5a97c52b1e2022b1", - "signer": { - "algorithm": "Ed25519", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:84564cbbca000cd0e991137a7f1200c42bdc28f2e1e15c548506deb8b68b3564", - "signature": "lUXspbUAb2uTGl9RIbsgedu9dZ7tBronZAlms5b-sOH1t9n3yczjRB99r2QbyZmIqIPsF0DtnbZtNtqfXg2XCA", - "subject": { - "committedAt": "2026-11-21T09:54:00.607Z", - "entryIds": [ - "entry:a05f26bb8f040470d0638f437e4999ae786aacf2a87d3bd7c715067ce8e45c62" - ], - "metadata": null, - "nonce": "ipqK2kabnx68dopMa1CUjg", - "parent": "commit:550074abf0ac8418bf49971861db5c966c181ff5bf1952e50f760ddc29958ef7", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:9075c437ac992ebe65554656e91038513a712ac2e933547878bef5ce0432a1b7", - "signature": "kVz9ERGyMCNAy9t9S5MRMPRcBgfHj7L5ImYewQvCkfL_WMWiZaPcGI1vGV3xuwrQzfsHW_CRdRMIyDo25pgXCw", - "subject": { - "committedAt": "2026-11-21T09:54:00.651Z", - "entryIds": [ - "entry:f1b176831eb301acdd59b6cd526b6041076b34d2d60cde019559826989201eee" - ], - "metadata": null, - "nonce": "ryXQU4ULR0n-etcExa6Lkg", - "parent": "commit:84564cbbca000cd0e991137a7f1200c42bdc28f2e1e15c548506deb8b68b3564", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:d3b4ea042dbbbeb9e4ab8d20b0a8dba1c75b91bfc4010ed29e81edb53fedcefa", - "signature": "_2xg5N_WTwekRC24RYAyuPiyKT2cyEAbHjN8i4Hvv8qsdtA9UiFUyqe6CIzg-CpiyDktmGma-dn33CdtN8M5BA", - "subject": { - "committedAt": "2026-11-21T09:54:00.707Z", - "entryIds": [ - "entry:68ddeb62301a045c900ac8c96b9fb774c8f8436d396b90f8992603667b640d1c" - ], - "metadata": null, - "nonce": "BmuMbtoaoR2-Sne7GEce4Q", - "parent": "commit:9075c437ac992ebe65554656e91038513a712ac2e933547878bef5ce0432a1b7", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:409e4213310057fbe1849663b690d0059910564209867edd2d7303acb07b2e31", - "signature": "84ew6WCQ_fEA8gNNfN7GdY_pYXNWLmATs4sSXCSbl3qjD1s7TB2h7mCrFqF7OKPo1Hoezzx0x5JdPGcAY77rDA", - "subject": { - "committedAt": "2026-11-21T09:54:00.777Z", - "entryIds": [ - "entry:f050e2916ac2ebba1e1aa4e56c95944dcddaec5b90c1289c51e5f053fa57523e" - ], - "metadata": null, - "nonce": "hosRFKAPRsNDDD79wh-A3g", - "parent": "commit:d3b4ea042dbbbeb9e4ab8d20b0a8dba1c75b91bfc4010ed29e81edb53fedcefa", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:5d0bd64d3cb9ea67ff6d3b29963aa774e3c6409f9f76a5ab510eb449bbbd10d1", - "signature": "c3PsXWQLKgMoZjtM2Ug3mUcwVIaOnDPP2uu33a0H1RdxGbC4bsMAnXY6Vlw0vWbnNCXqiok1JHCdtoUIOVVBCA", - "subject": { - "committedAt": "2026-11-21T09:54:00.857Z", - "entryIds": [ - "entry:974aa191deec2a9d0e7f99ad83a0b2979de9536cc016710d788e7d06bded9a3b" - ], - "metadata": null, - "nonce": "weIzBbNIoXLHk8j5UVlzSw", - "parent": "commit:409e4213310057fbe1849663b690d0059910564209867edd2d7303acb07b2e31", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:f41f8c2a26a16a0bacada86c46de45e0f30a3d0f2a7c6d2561efcc16acf88609", - "signature": "cD1aMdSKpcIYzVn9fZ6Rfn-wB679rZt5gOeMtLh1ZuRIrQVP97DBVWy64Rjrn-GpMWOjpRhpyIMXud-uIMuuAQ", - "subject": { - "committedAt": "2026-11-21T09:54:00.946Z", - "entryIds": [ - "entry:788a0b4f685defde5dca6168a90fb7779dc1d14cf172c167b527bed230d87c8e" - ], - "metadata": null, - "nonce": "u0lIhTR4H_NSW8nNj2E3lg", - "parent": "commit:5d0bd64d3cb9ea67ff6d3b29963aa774e3c6409f9f76a5ab510eb449bbbd10d1", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:b7994bc826e1e0a797a90bafb5785b59be0e452319b6e099975626295f3787cb", - "signature": "LN9ZWEcV36fQp7mhCo38oy-DZuNwRv88IUl_TMNCjYF8PEqt8bawrq-QTK2X78ozuCT0a2rGIy95j1U53MylDA", - "subject": { - "committedAt": "2026-11-21T09:54:01.111Z", - "entryIds": [ - "entry:16fbe65be6cd2e18767c6b911d73150218eebb8237379b672e69544e32c4b98d" - ], - "metadata": null, - "nonce": "Gdl_1volIOYBe1_wk-Q_MA", - "parent": "commit:f41f8c2a26a16a0bacada86c46de45e0f30a3d0f2a7c6d2561efcc16acf88609", - "signer": { - "algorithm": "Ed25519", - "id": "identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "publicKey": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY_k2NsFGFKyHN9E", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:907049e2ffd92825ba2cc47952d8c43ca862c891cbdedd67cca3ab07d3d55dbd", - "signature": "HMmr2J0n5bM7saHYK5aqJoYTN8G2kFEIvRMN-e1wjeJYOBgpw_WlPvaCD6c4ej8iWyug4or0_8-TABtHGrecCA", - "subject": { - "committedAt": "2026-11-21T09:54:01.297Z", - "entryIds": [ - "entry:1657e406aec860a6a1a31c7fa24c550ce965b6b0e5b86547e29a5c7967c7da52" - ], - "metadata": null, - "nonce": "VG0UBBKzNS2C0bIKierplg", - "parent": "commit:b7994bc826e1e0a797a90bafb5785b59be0e452319b6e099975626295f3787cb", - "signer": { - "algorithm": "Ed25519", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:5c69a03d3911dd7d3a535c8a3f55cca22dca44df8203916977cf7202d4d8667f", - "signature": "SgYd8oowgVgjNZIT34M36FMTK3a60naNCM0OHFu4PQ5lyUoxWVuGX5N8hghYioSR0OoXLut_sdrfthcaqWNhAA", - "subject": { - "committedAt": "2026-11-21T09:54:01.495Z", - "entryIds": [ - "entry:de77783d68a7b8597f9a0b85f4c7c0b396ebff2f9871de10512454c2b57f2be7" - ], - "metadata": null, - "nonce": "l7lFXu5eH83xnvvxOKbUPg", - "parent": "commit:907049e2ffd92825ba2cc47952d8c43ca862c891cbdedd67cca3ab07d3d55dbd", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:a66fe891d23f1b9dc6970aef7f788be4c747d1a1345ec32ffba84a83f1183443", - "signature": "EMhfX2LI0a26tYxBvRI9bDTcnD013sOEufHBZ_dadqRul0UtDM7_eW7Y1vGLYSycyCdxM_Nh6RZZpAjhW1_oAg", - "subject": { - "committedAt": "2026-11-21T09:54:01.626Z", - "entryIds": [ - "entry:efa98130d44c04e8d8988ce6b8dbfca7478647fdef83748c94509f347c6df4b6" - ], - "metadata": null, - "nonce": "oT76IhM2rJaxSt00ssgbIg", - "parent": "commit:5c69a03d3911dd7d3a535c8a3f55cca22dca44df8203916977cf7202d4d8667f", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - }, - { - "id": "commit:785530ba410faf42a1c8c6f0449702f407286b10652ceef51b76b15369f98175", - "signature": "ay1ghIz9CqtI_-IkWML4G_e1opyShDNHsx79qgrMdqKa8cPjwtQkThhW7_Utd9ckLq9GASzSAVbOlNMKqLx_Ag", - "subject": { - "committedAt": "2026-11-21T09:54:01.768Z", - "entryIds": [ - "entry:39c050f6b7fb1e5e5ce567c795a68c797b0923ef56746711a134fc47dd83a13c" - ], - "metadata": null, - "nonce": "Vli8hBDbLr6f5jJYLf1lGQ", - "parent": "commit:a66fe891d23f1b9dc6970aef7f788be4c747d1a1345ec32ffba84a83f1183443", - "signer": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - }, - "suite": "ledger-ed25519-v1", - "version": 1 - } - } - ], - "documentId": "commit:3df334832b1fa2864b4c6776e325d176b6442c18ec2c0c4f5a97c52b1e2022b1", - "entries": [ - { - "id": "entry:e3bffc0380c25eedcb99cf5e7dbd78f5e1516ba75abc63cbddcc14ea13759237", - "subject": { - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T09:54:00.502Z", - "kind": "system", - "meta": null, - "nonce": "7Zf8I8Rtas6D4GJGrFtddw", - "parent": null, - "payload": { - "data": { - "data": { - "audience": "document", - "epoch": 0, - "owner": { - "algorithm": "Ed25519", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "version": 1 - }, - "recipient": "age1yw9vprggazqjue3t2fpcwcfkcayrhfs05j9yvzsgt8tz3jyu45yqkn67p3", - "wraps": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBtYjgwbGYyclUybWlDczgvVHlmcTBCWnptTm9JbUZxTURYVG1xa0RBOG44Ck50RUg1bUpSc2NKeUtaN3IvRFFIY28zR245aW9qZ3dpQ2IwaTMzeXJIdWcKLS0tIE5QWkxlNlBETGpTSE04V2NMelNLc0pYYUQrUi81WHFsQkxqYjZiVkpGYncKMKcMWD_AaK3ZjXjpkwyMUG00_9QxZGMONZgYuD695Q9czdhjgUP4Y2CeVvszHCl_ec6e2qhnVq_sfqUuNE9UVr4YGvS_KbkktnUycihJO58OJmPE32UCrAqdwtqF11ljB7sLzad2wbfe4eKjsSmpC97ohD6i3QzZqf5ooiAWEuLWQPsKnA7Iu2-6RD_Eh4WOJDyx1_X-Vo_asyMHPHXDVK2nZpkqpn45NdNT-toSWKu36aS1hOrdTIrptFmYdVz_FuYldE649YuaWBcPt8alUeth3yZxfOeqg2o4sY-wJ4fSyxgg3s-0Bpv6NEHGvuAHcW0XwGbIcP4CxVuR47GqVBI3YUtS96JKdhnwCLAOIa9l7hAi6O3qlaPWdO7pFzKpN2XwNzX6vqxXmHwOxo9ULu2tz6vI-mHwFJs8YD5P_k9dNCFS6ouDcaU3e-pIggVfJf4Gio2-vIxmjjjwO2a__1EQ1_OxcLahH6nUR9mKCBw", - "identityId": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - } - ] - }, - "type": "system.init", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:2b699596f1cb6b1367becfd6bc95ad8d84397a0160609078c2accc9a834daec3", - "subject": { - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T09:54:00.550Z", - "kind": "system", - "meta": null, - "nonce": "MjXr8Bs5TAEDibZa3srMqg", - "parent": "commit:3df334832b1fa2864b4c6776e325d176b6442c18ec2c0c4f5a97c52b1e2022b1", - "payload": { - "data": { - "data": { - "audience": "document", - "capabilities": [ - "read", - "write" - ], - "history": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB0OU8xdG5PM2NlYmhOYVBHZjNNelVETk5jOThUaUlEQ0Q3NGZsWnN4NHdjCnJmaWxKT3ZpVnVMMjlIMjBlQUlxaFJiNjhkVVJxcHBhMGQyZ1ZCSE5vN1UKLS0tIFg3RHZDWmtjN1lVaDE5dEZCYTFJV01vSEs4cFVKS0srRm1FeE9MVlFZZmsK4VSTePdhum6D1pod_7T7HULOA5HblnioPUrRAikbJEug_zakn-5wxQF3y-ZUfHetZICeUxNDP2hgwb8SdZLRJWL47tx5z6p1yXrO4pzXzxGPGDHcCgCY3EJhXWnEGAhieS4mJx3MmvUYUjyJ4dFeoDXfp-S0u5pm0bM5bGGqfct7kG-2FP6drDC3egINegu4Ko2eBbhqDLuxNlX8SDWYQVS6lYD2253vdfuCGJIX6VU61rLd-yTYkgHlAP4wp0kwXW374LlAYIvfAWqkuNhDIUXCSRdJYkOEl_EWbevQIRHq4ywd-ZyIjD46cx2hdJgqde9MMNzTWv77WlMC5Ymf8u8C6lWLTYJLXEQsThUrLnGXGtccOFwCBcv_MHG8tSb03mfxYD2CnafshahNLOK5qqdGavBXQ6vaoxPSKKyvU4F-W0B4jl0HAG_IzivWuKR2jh0aQc45XUPdu5NTSWe05myNyo3s1Qgw6Pz1Y7EsvFf3dgBGF5LhW2livXLjePF33lxAp5aoVZ5KRPGErkdNvhSJXaATQ6qQdG0j2zQISOdD0cLeh_dDySZmc5Tt8h5JjhtKuFk", - "epoch": 0 - } - ], - "identity": { - "algorithm": "Ed25519", - "id": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "publicKey": "gTl3Dqh9F19Wo1Rmw0x-zMuNipG07jeiXfYPW4_Js5Q", - "version": 1 - } - }, - "type": "system.member.set", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:a05f26bb8f040470d0638f437e4999ae786aacf2a87d3bd7c715067ce8e45c62", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.607Z", - "kind": "system", - "meta": null, - "nonce": "jF27KKozjxZvR10ltCYhpA", - "parent": "commit:550074abf0ac8418bf49971861db5c966c181ff5bf1952e50f760ddc29958ef7", - "payload": { - "data": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "epoch": 0, - "recipient": "age1zjkq9gpqclyj7rqq2qldx6l9m3yfvm8v9u8h39e9uaj204rqpe3svmyh4x", - "wraps": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBFakQ5NWZyeVppTnFuc2FLSG14bHo3R3NVdFBLZHQwQ0N3Z0M4OW9yTXlFCkpiZEFNeFloUURyWEdlRVJnRFBCcmRCSVNRYmk3NTlYdjR0R0V3aXVMVXMKLS0tIGJnT1hrNEQ2YnRkR1ZTenBZYXdoUmg4ZWg4b0ZIeEJwd0h1bEk0UkdickEK8uiGY5syprGuCn5eXJiIdyCBF8wTczt88-ee47DOgqM2bbA4cm6Hh7fCWtNJM9qOp7KD0HwiAhjzBvOegiEQK-xFgDpf0lqIe-jkfQpLR4XEJgVsWKF-dJugG4QPU_dcPDWrQRaYb5iJQtLFP9S38JhiAhqPAkOxLWLvxuK6DD4l1WKxhzmPshIdZdPBCZAe_0Zq0dkMrPW6Xyix0CgM8vFLChEDWinhNYKc_UmcMnC2mYBrjjN1C3yfp2duY5dUsyCIU5PFhRUPPbYQ7KJ1MBTdhzDY3uiNkX7571qYhdHgDNOr_RefY9ey6V7S1PFVps4ubTeNqfqMmcZckqfIEW9nSvjZKWFSNNHLKJlIWUfaRgqvcRKiyc1_tPboslmVXI4z7yrTPIk3dZEseCSe6kkNPwMnUZWmGQlbSASRqDPhLVvfhJKHM5DEAgw_CXIzfE9cMF8-O7gCn38Rkqrd2LFOncJQmcGRtY9tZfedK2DscVtO9uOCOBJZmHZ7H2G_6AHOIQ8aV0suD_dXxISszzubq1VMyrSCOrq9tcYU_8bfDYf7TPky-eGkFFr_Hvvxit9YrlpBvMGMu4WikPl-lJNVALkGuQrF2A", - "identityId": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - } - ] - }, - "type": "system.group.create", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:f1b176831eb301acdd59b6cd526b6041076b34d2d60cde019559826989201eee", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.651Z", - "kind": "system", - "meta": null, - "nonce": "HwNpXQsOVj1RhX5RqokwTg", - "parent": "commit:84564cbbca000cd0e991137a7f1200c42bdc28f2e1e15c548506deb8b68b3564", - "payload": { - "data": { - "data": { - "audience": "group:tZkn2eFhVW6ofURIS0dRwA", - "epoch": 0, - "recipient": "age1xt6m3ac0np0kudxw8c6j70eva92k9qlh68ftx8wswy4n9ky6udrqvez0ga", - "wraps": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSA0Y3lKa3lIVmdLNkFmNDV5WDdWc21xc3hGa1hYVnBjN0pJS2N6Y3lTcWlNCjlZdzA4cEpwZkoyRzRObkdXeloxU2Z5QVpqaFhQYmJiZGtQQUltajYrQWsKLS0tIEE4Q3RzU3VYUHVEbXlxenU3a2hlYkZHMU9EOW9uMGdGeGN5bzVsZm12b28KrsUUpMN3ClKR-48k4tGtzDlnZthAB12sJHtpz6zTmrp_65EB-IYVUreux6JPfH2EEd-BTrw_si__26xVNjrFGObp1japHDYqyprwIILkUfqTwUwXsauk9AvYcIG2-Di24ldby001X7DRxm7LnE7RhWbek76VU_Wm71vVCrcRrvGLAMDim0J0HADrycTBKXeryxsYQeUWeZhGJAUzwR1iLf70ObCgRs9HIu7jyCnCQgtt7sk34jUGqWplqx9gK6icxnoE0zengG9xKnFm0Cn0Qi3Qv84s6VpHvVlfdW-zpQjr0xSVJwKSj4mft5MA804RlwdsM-0jeKW8SS2EDPAjk4YDJlfl3ehgEAHoMAncvni7u1lcvrkHqQdIYFINqgiZv1HavIbyIGDCmiCUozu15uBdWPHt-APc6uWgajVOf3R3bxWYHh5KmdWUNQD_AErgGSfUsyjD0-HwRU58YKi1qvIv_HQjUTB5USDl2lwTJBJU7Q0xH-1tSh99CC32w5DVb4e3jxogBkP_9M04VeYfnqdelkoMzFAGJENY2TiMd-U3-ISaeilQ4pbOUUzECv9MPwU65VS9dMyx6AJtyIYX3QR3-kabsOVmlg", - "identityId": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - } - ] - }, - "type": "system.group.create", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:68ddeb62301a045c900ac8c96b9fb774c8f8436d396b90f8992603667b640d1c", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.706Z", - "kind": "application", - "meta": null, - "nonce": "oSYJYzQMSWuFDVDKSHQBaw", - "parent": "commit:9075c437ac992ebe65554656e91038513a712ac2e933547878bef5ce0432a1b7", - "payload": { - "data": { - "audience": "document", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBadWdqTkdOcXYrQU1EcENmcGUvOXF1bXN6QVZxRG1vcmc0d2hrckQzYkVVCnNIN05uK0VUd0FKY2RTd211WlcwOXIzM2xKeXg5SUM5MVJ5eXZuMDd1emMKLS0tIHVhQ0R5OEFKemN2Z01NS2U1UW15Rks0WXVwaXJwMmcyMTBYbHVmeFN3WmMKiih4OBZ5f6mIPy1NarSGqYWWdFJtNuN5bxCZ-66SciY8W_ypSJ2NfwNfdXNWQZBGbObxrysC_S0txpoJTfsYqvKKrnA-hgVA0JVLMF6v3W6NiE3zZ3UwBmJuoblXTTJPx8EqmGWUUftW_-dYaEXYBAaRNLj7BDfWTyInCg5YNJmlVSOV842y5Ku83072FseJjSVi5s7S_naNTdOOr7pJo4nuwA5gUVpxl0qcwpgkIFb_zdtUNO05lvhlqSxUtL5iESul2y_SWcwAQrhaoIoi89B4OLa7kg67fM1tzwGuvvKAz5v1FLPwdzngaJpfPit83xbxm5LdUuLsfcThT7LjYVY3HA7dJCnwhJOc5QEP8ZEgzXOWWKyl1Qm_80T_e39pDAIjqWaRjC-CNXmdEBUjP_9whqk0eLj-3IeisjGMJn8mTHJKIjMQP4uRIaqsBiUKX5cPNa2YPgEM0Y-pGneqvrk7Rp5XW4LhvoyLRpjr3Zxdx3uPzm3ow0Wb9De7Q01f4yMHUUZm4oo61Dji1iK4bqXNOn7a", - "epoch": 0 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:f050e2916ac2ebba1e1aa4e56c95944dcddaec5b90c1289c51e5f053fa57523e", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.777Z", - "kind": "application", - "meta": null, - "nonce": "UoEZwXHePEKefg_6uL9TwA", - "parent": "commit:d3b4ea042dbbbeb9e4ab8d20b0a8dba1c75b91bfc4010ed29e81edb53fedcefa", - "payload": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB0QUlCWWtWMlNrR25CTVZsTTFXek9qMUdBMXhzWXNBZFVGZTlYdVN1azBFCi9SZFUvSUpudnBHZ216MFF6YWJRNk9TeE16MkF3RlZXOStLajNzMDdWaTQKLS0tIDI1YzlJWC9KcFJvUHZMWER2SUwrdlR1SW1yV241UkladStBZ3VRTU0rQTgKwEoTy47B6qBNzheP4KgNvs78wBNqGGW7BekYg1fV6y5SUTrwP1R0rZirJUsrlfXOV0oTE23V8uw0fLOmwvvqeer4eGrALosk06ie1-7mxUNKa1BGE4GfXRnIcSZXY4daztAINkHycaqTa1L9onBstPQHeuQID8vPLe9qaypPalKyb3d4mVwjCRVPdqMnOXu3Ing1pb8IY7sq8yUT-8zuuk3mLJUowAcHBxNJKfUSBREmyfwYHOMqM3I3LL6x6PVv9PNdguDC1_AnyMCoIMOB0Q93-_kKKL6P0AUHP5de8bb515HMBkHUGAk-kqNkh8Ou21jbZynEY4u_634ZJEcbf8fX4AHs9T8v-Idd5yofbQcP_OrB63YFaAgrp6uNxCnq__MnD27JINPNikbBhDoNjRnaO1I-Y-oPS2AmHOtdfXzeA8wg1tkjOOqGNcRxkWhMMVocwgintCXeR9OP5J8tkGP6u0-5pZY8OaeQNWz3XEyTFW1bd_nngcTEt5meKO2kIUibwFcSmH0XQVtNcGAeO2FK2a92DkTI69pISlcFgRoANptKovEh3J9IYuNyt6g_TKsbMLVqgiDnmsNfR_Y", - "epoch": 0 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:974aa191deec2a9d0e7f99ad83a0b2979de9536cc016710d788e7d06bded9a3b", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.857Z", - "kind": "application", - "meta": null, - "nonce": "IXy2raI8ey741BGHcpOEMw", - "parent": "commit:409e4213310057fbe1849663b690d0059910564209867edd2d7303acb07b2e31", - "payload": { - "data": { - "audience": "group:tZkn2eFhVW6ofURIS0dRwA", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB4dm1XdlNKV3pCbU13TzIwYk1mVkx4NExiMStyUEViVm04K0dndjdkUG5rClVsblFuKzlqaTBUSGZXM0V0blZ5dER6enk4T3BNb0hvZmFJdTBxa3c5bHcKLS0tIDBSR09KYk0wbHMrbklWTFpTTzY0ams0UW05VU93ZUFZZUZySkVRVjRjbjQKC-XQza208BnzhH_WxlQpb_mOv9oH6SgIFz9sCW81vIN9WMRvRaFp8vJxhjd7W57-wg_dG1DJS5VtXAz6Na6L89wzr9bAL7nZzjSzibNAvbebT4MoVIfKPZQ9tMjMlRBQ5g9XNnawAQlIom6yqZhDnH3E23N12CvsuTLgc3PkXKWpUUut8VxS1UFMJRx6-PqzYMGAo1ZJM1nu5slwzOgfUM00Z_0dg57rMJ0EiZcnCurGjMrSKHnwcmPZzgysdYhzRjGlltoYSHyml36u16FYIJrGaYsj2J0rZaanVl1aLYNnGrUurxkUTN9s08ZlWIo6dJVrPBvnocMwAeys0DcEIIIqaXuFxI7KIBifFXPgYhAbh-cHbC1urIJgwLvktS_6he9mR5y47rWR-yw6wPODDZzMo2C_foVkkCflDu10s_ye08QFxFMY-_pLp6EgzqUBZZoRNBwzDn1R7qXxnsUWtTWHSfIYd8EpyPnvwVPdoFSHTi5t0nlflnZy-LAZ8XwprxHphm_GNQaps86ovq101_kuVd60j54WbvJHXNNgeocQqU-3PwI2nEIiEAIUQcPvSuBhWJw_vWj7RF7JfsmhyoXtvA", - "epoch": 0 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:788a0b4f685defde5dca6168a90fb7779dc1d14cf172c167b527bed230d87c8e", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:00.946Z", - "kind": "system", - "meta": null, - "nonce": "FN9MqpLkhx13qZaPRcz-5A", - "parent": "commit:5d0bd64d3cb9ea67ff6d3b29963aa774e3c6409f9f76a5ab510eb449bbbd10d1", - "payload": { - "data": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "capabilities": [ - "read", - "write" - ], - "history": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBobUJsYU45MlIyaHN3S1RyRVJaRSsxQkNNV3VuQTZ1enZvNmxnS2prS2hjCk05aVQva3ozWFMzVWpYNmZFVURaaVplTTY0cmZ2cWhPZGp0dFVXQkgxUncKLS0tIEROLzdCTUF4UWh6eHFSWk1WczF1cXBHWUdYb20wUzR5Rys3L3pUcjFDQ1kKtP4lJkm7MqWCyC25WjcZeSHnw1EVC2om2cKdtWaIoU-TiA1buN2FPN56KLbaLq7lSfJ51TBj_6U5_HQVxT-cZWtBAmmyTuh3rF3mCMF9AaA2OAfcmCgndBrJWohVi_rhkWvxr5eL5QrRj7m6aSCZjJTiY8iRAePKAV_Mar5UU9IVT5deNeZb6LjEC-9qUzkNShUWMGJGCFOg0LzxaKHqyaCDHefUecvf6dkzw2ZOutG7F-yRa5Tq3_cikp0JCWCbypMhjQkNkduI0lsFsQnldJrF_G8mYX1c5h_byQC0ikthkTP5uiUOiEEtYRdzi8MfyRkHZ_aHQQZUwej8rqNP8wdVy-YnxIRg0-ia-BqxqKxVtjJcRnIqJNO_eVWahrvBq9XqsfAjQiqDJ0s9l5bYnaRwrzsr1Fwx4FiiGahg278wLjugfy7vVQbK49Lyt0rumNwYIo7CfqZUbbdJskZqknZ2Dsjfh-O-KOaZ_3Pgq22UF0Kh9GmMvYnGRJVaMA68hOQy-RTRdnU9hVolvMOskd_wRVBag8B1xGK-zGS3MzK7Ii1IDfL7KuJ38o-pHC4lDOwb6tA6iT2oCwJeia-oOd5ojlX95GhjAA", - "epoch": 0 - } - ], - "identity": { - "algorithm": "Ed25519", - "id": "identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "publicKey": "7UkoxijRwsbq6QM4kFmVYSlZJzpcY_k2NsFGFKyHN9E", - "version": 1 - } - }, - "type": "system.member.set", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:16fbe65be6cd2e18767c6b911d73150218eebb8237379b672e69544e32c4b98d", - "subject": { - "author": "identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "authoredAt": "2026-11-21T09:54:01.110Z", - "kind": "application", - "meta": null, - "nonce": "2Cop8P3TdAGd8MyPcsw_eQ", - "parent": "commit:f41f8c2a26a16a0bacada86c46de45e0f30a3d0f2a7c6d2561efcc16acf88609", - "payload": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB1SDkxdFltTldFWkt5WkVVM0crUjQrbUkzRnU1YmtUSCtTOGpLK3ZLbXpnCi80NlpaN3hiOTVnWlBnVXVnV1lnL2QrRCt3eDZyaTJjTkFKOEU1SXRBYW8KLS0tIFRvbWxCUkZ4SWxBbEpiTVN5Vk85K0xiSTQwcnRMOUptdDBJamRoMzdFS0EKJnsx-4BLzeknwzpk103GitYJKqaFjF7JAi4dkt3xN8f4Ms_wZUrj9frP0dVbHmQvCHC7KV2YGBD9hr_vWvfF8GT5gFjiMLjbHzERIVzp1F2avYx_wFhcp3ZHGrSks9L1HEHsnm-FZ3YzgErXGVApP1021-3mhtU1SQ9Qy-NTQW2F1exwmJ8U5qCAyhRwz6G7Yav1fNOc0XMfzYQ4OLiz3eYaZFApcGo0gMr1bEc6MDgGUusDvxzms8Yet3Mj52cWOpvKyWZP_PDrNNK3HUbhz3SF075YC0SZqGBm4NxLbVb6igFNfDjCx0Wls1Mm1zjXLk_cehn8fiHZyRgoiKVN8xZxagUfrISHEr8GmglyKabsrBf7wNrFbFFjBxeK1fj3jrKPeQfMea5fh14ugKMs-PxqkZrIw5qgZFR4DEuC649KvAk3CVngd9NthJir1d10SWSLUNShf_vyaBltorzovl8nM1AnPvpSDKOLfFHPA7D8rHzExuYy6WKCqkoIJ3B736Qce-gD-_cNR0-NE6ByPN7vb0NVu6mz83QCbMYnCiPKOXzKe-jhTPKf2Ln3z8CC64YydluZJw", - "epoch": 0 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:1657e406aec860a6a1a31c7fa24c550ce965b6b0e5b86547e29a5c7967c7da52", - "subject": { - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T09:54:01.297Z", - "kind": "system", - "meta": null, - "nonce": "tSu8K2jRuH7G5QNPSwYwHw", - "parent": "commit:b7994bc826e1e0a797a90bafb5785b59be0e452319b6e099975626295f3787cb", - "payload": { - "data": { - "data": { - "audience": "document", - "epoch": 1, - "identityId": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "recipient": "age1z6ljgmtdq6ntx3rjy8hmp25qfarv8v0fan896esz6kj4f8swpc9sved2ry", - "wraps": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBleExrVDhKOExCWm1mK2pwRmlTaE9MQ0xvTXhwVmlMOXNpMjEzMmVpbXgwCmVJaDdyWDZCVkJNV0VNY28yVnNxOGJTTG5EUHpTYUFhVEErdWtadTRVSFUKLS0tIHZ6VVN3RGNCQlBKWWJRd1VKY3ZnMThmYTJMbjlBclJ5b215cTZueFowN1EKiuHXaAxBgC6ZZJqUNRdinfvo9WwtcGMDDR82bz-SjEsjA_NVYxKL_Fpz5poON1W55MjiH1wkailhpO_eD9eLpI-K4RqhOTtVHqDhTcxibAeoPXcyt5_lsIbmY8IKOToiB83sJrte3fbCMeIBwLvJq8vNaYw64iHYn2wkE_y0AhzpxwWmtP48dD1EVPlKVrU075jsoCsGkGtVJhR8k1sXn2HV20xeByKdvAqOTGJnR9c0bJC5jB3fLe-ZLSf4ZD-wPcs3iF9WswdtNIUo7Elnd7XBx1Ajc4_vBAoHU16meJWW1I7a2Z7yz2OXTM-nUteJxMI21ylQ0QHuyLihrum8MkDb6Tss5nM76uuG6j3FDIB8qoJh0boDBFKJo22xNa4i5l_Nu6wRC8q0BAYb3PPRdCTHxeDpaSj605GJx-8S47IRgBJdJS1sqGvpu4hwOLk2HfpkXhz8gX2i16Aa01nS8FAvlzcD_xXm3zbo_82wiD39P4pLBXpjVuffZuOPerd6CAGhBVt8679zYjcwX6N1J4N6yMvoELdEPO1mKiqgClLj3x2gbm92CkzU3cl1hJbU01mIKDc", - "identityId": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - } - ] - }, - "type": "system.member.remove", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:de77783d68a7b8597f9a0b85f4c7c0b396ebff2f9871de10512454c2b57f2be7", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:01.495Z", - "kind": "application", - "meta": null, - "nonce": "OMEIA5O4-h3JMbmzdjvU6w", - "parent": "commit:907049e2ffd92825ba2cc47952d8c43ca862c891cbdedd67cca3ab07d3d55dbd", - "payload": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB4WCtPMDJoOXBKWjh2bVZBWUcvME4zdmV4SnRWMTR5TnZUYXFla1lDa3dvCm8ybkI3cXg0YkpLa0ZZSTk0Q3NGcmxmWWg2ZEdJYTVrU1grOEFCUXBJZzQKLS0tIG5HSE1jWGpMc3RoNDVrdE5PbXJoWVkxelM1b2R0OVZGekJkMmo2T3VhSm8KSy7uTKFqjSBPxU4cEI_1rQfPHW9sZlfjdr3Ivm4jm3phrpbdVGL8wQp-kZr5vs4oYVvDkDhmDXUNBVLXcDMeKl5algfw6J0vm61z1BN2YrLubLAaGZeIdbXAJqSwD3_p8adBHL2THR1V3rztl0YeCC8LE_9OldW4kcR09MOy2woYKud38lMrsgWPhvoBinS6d9zXwb1ExGY4x9yGMB76PKGl1yTuBP8P2au4m_NcTx61QrGjXWiKMgVZfy_TrHLSBFDULPjBaEw6UYCHJYRYLWgDh9oaJx-sukeLYEaI9pf7xlPBrOUONks7wjp0c0BfPqalo9Atam6bnwP1PuykZTnJq8dz2As5fCfKim8OfgQt5nWe05mXuHeJHpxrb21p1g5eu9ptk12XepRSQumRuXKvPEhzJARYEeB65zsSwSgdVFoua96VgOjHE_rY6uJI4b-aO97cq68LVSKBfSo5Rfh7pNS8EPzWmduD3CtcQciN5yQLt6HjZPfWB6JGAifGzdeoz5vciYBJGyCDqw7JHQqTal6MZF4dxxrdq7r215CRtsk3c9DII6qfnPMKMAxUMd6FUbraUSZX-Kd_skx1w6D6SCk", - "epoch": 0 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:efa98130d44c04e8d8988ce6b8dbfca7478647fdef83748c94509f347c6df4b6", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:01.625Z", - "kind": "system", - "meta": null, - "nonce": "GHYakBv8OBPiHFtQcAsQcg", - "parent": "commit:5c69a03d3911dd7d3a535c8a3f55cca22dca44df8203916977cf7202d4d8667f", - "payload": { - "data": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "epoch": 1, - "identityId": "identity:b62e867fa2f33afe62d5d6b1642e1621d543307846b2a57b897e710919b76709", - "recipient": "age1t9uv7yh5g37sskw2pegmag53la3xje0p88atzlqqlnqpcjwd3azsmxduvm", - "wraps": [ - { - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBsQk52VHRHN2JacnBSSllLZk9TSkVnSWNiRkxFMWtUT0pBYnU3eDRGTHlVCnhHNzYya08vRlFyV3ZNa1U5aUZua0tUcTMxSG8vNDdneU5KazVMYm9sSFkKLS0tIFdqSTdTV2JEcklOVzBzYmRrSHRrb0dDa0ZyS096M2JaYXNpUGdjcWhPZzAKtmvrW-AV9MuxrCuA3ezq0Lvzpqb5O3kYrdM8eyeLarvpP4GsGIk23IjsNsw3fK1gYV2uWiaF2GJyEsdqwtvT_IFqDvYJp0G-6fCQlIC6DRM_rNlpJbxtuok4aWbeM-hVj4Qajz3LQfCrnZKEoE8XQK2p8uIl-X6hXI1-YOzlY9J94v3XNa5NrsXgd0wF6-Xw_mQJkf7Qfm0ElVm93aAQ9rYiynQBCzEsZNeri8luHdQk8KHcVrC8B5NMKNq5GmSboFu0m2NE2kkPEQi4FdFyjH5BAELkolKiwNnCA_1Iv2RZjb_hPYbuqp4f5dQN3mC4F9ENfHSTsjpKn46QGyjq54a80BzqXw5aL8EUOZhmxttlm8WQZUygHCIqgu7NLBJBTXPk_nRjDRG3PLiMhmhY4B3mC8aM5_KL-uuYRZ1MBs6kKiQ-VvWjXnWerAHgmNGDnhnGduteIupnIdaDnBB06xr5fT431467Veuj9hpZrJ7YjwW1FKczgV9bUG-SDTW8J8p1ESq0kcegSEJjLMDpK762a1sDFFTTrE7wiRXk8DxektmPGn0ncf9JAinbiJz9LhWGX9JeY73JVtOHStGoFVOKZE_3KeFR3A", - "identityId": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827" - } - ] - }, - "type": "system.member.remove", - "version": 1 - }, - "type": "plain" - }, - "version": 1 - } - }, - { - "id": "entry:39c050f6b7fb1e5e5ce567c795a68c797b0923ef56746711a134fc47dd83a13c", - "subject": { - "author": "identity:6a3803d5f059902a1c6dafbc9ba4729212f7caac08634cc3ae76b27529f03827", - "authoredAt": "2026-11-21T09:54:01.767Z", - "kind": "application", - "meta": null, - "nonce": "pRTx9TxaxBPxKYuVgUnA3A", - "parent": "commit:a66fe891d23f1b9dc6970aef7f788be4c747d1a1345ec32ffba84a83f1183443", - "payload": { - "data": { - "audience": "group:-GBcGU_EZy30gnkHcj05xg", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBpL05MODhMOGRLNmJjTjcvUjVlczNuWVVvRm5na3ZIaXVBTU5kV1dwUHlNCnNHNFY2VXROZFo1bjYzbExFd0pvNjkydFdDbzY3blRWRmd2aVhDRE9ub3MKLS0tIExaOVN6cWtUWkRTcXNEQUFjNDRONWh2VFMrUEFUWkQvVkpsdUZaNS9nQXcKQK3sQT05LEyJ3_vWfwY7TIis9FWy6D14vCAlMqRg8Yl-C2xBcl-VME76svPmzRe1WKmYBPcbbd2j3mM65XK_jEEvA_YPqLSAwzzmjT8PEkgDyIH8NIKFRyOKdOUG3JZQiz1IVd91cIa0YErCQ9ZP-rhSDBtB2Njv-tHEmhGjfQcDibJNMTN-jw2YIo90oFXwvbP1efANi01y_iZ5q0vREZa5aGU7r8IF9T0MmfsV38jQ_Qn2lhsa_MLhaGmKR30PmdtTKlHUNm7JinmicGQhgSo2a8bxqdu6SJXK9Cy5ry4iPNM1ULD-9zDtVdYlKGBxTOPGQaJZvjWtIY-wmfGwPx1moidoeLUPpH-ndMfBi7zd0vFbXXvKJjN-3qZCAq279lpjEKaClP8xqE6WtYLuGtYSy11-TuRAgBTfGNQXpuXMeSRcDj8FwX8qXTN4ujxATo-qgxUfudqfMOuki-x0oUH3WnnuzSq1pPVauT-ezMIWfJ2R-wyUi9Ty4LwaAvL03wvoriH8iEZdCXXDP-JhN0TCDTKEeMTZKJNSutcvOvuX2Ak89tZ5mf52UhuENK9IhxW8vfLCEFEWzqog", - "epoch": 1 - }, - "type": "plain" - }, - "version": 1 - } - } - ], - "format": "ledger", - "head": "commit:785530ba410faf42a1c8c6f0449702f407286b10652ceef51b76b15369f98175", - "version": 1 -} diff --git a/docs/concord/vectors/mutations.json b/docs/concord/vectors/mutations.json deleted file mode 100644 index 0a7e58f..0000000 --- a/docs/concord/vectors/mutations.json +++ /dev/null @@ -1,195 +0,0 @@ -{ - "format": "concord.conformance.mutations", - "version": 1, - "patch": "RFC6902", - "cases": [ - { - "id": "signed-metadata", - "source": "owner.document.json", - "operations": [ - { - "op": "replace", - "path": "/commits/1/subject/metadata/message", - "value": "tampered" - } - ], - "expected": { - "integrity": "invalid", - "code": "HASH_MISMATCH" - } - }, - { - "id": "signature-bit", - "source": "owner.document.json", - "operations": [ - { - "op": "replace", - "path": "/commits/1/signature", - "value": "eoKs2WGqVrrJ9KHFdKO6INAIWkRF1QWiSyzQ8iJYeD7z2_11pteE6zG9GrjAASibyid4edfbHQFtbCupzwo1AA" - } - ], - "expected": { - "integrity": "invalid", - "code": "SIGNATURE_INVALID" - } - }, - { - "id": "missing-entry", - "source": "owner.document.json", - "operations": [ - { - "op": "remove", - "path": "/entries/1" - } - ], - "expected": { - "integrity": "invalid", - "code": "ENTRY_MISSING" - } - }, - { - "id": "duplicate-entry", - "source": "owner.document.json", - "operations": [ - { - "op": "add", - "path": "/entries/-", - "value": { - "id": "entry:8f426795f49c1c5c7a0ebbbd9899642b4e96724d8614415485abe626b0fe4bf2", - "subject": { - "version": 1, - "parent": null, - "nonce": "AQEBAQEBAQEBAQEBAQEBAQ", - "kind": "system", - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T00:00:00.000Z", - "meta": null, - "payload": { - "type": "plain", - "data": { - "type": "system.init", - "version": 1, - "data": { - "audience": "document", - "epoch": 0, - "recipient": "age13aqvttdk3ujkyjh9kg2w5an6dmy5mq5a84a4uxk3hfhnugfc9p0sy5p2wh", - "owner": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "wraps": [ - { - "identityId": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBxbmxVekN5c2Y5bDRDVkphd3hKTk1VMFNTL0E3SzJieTc3ejBZenpCc0RrCmtaNkFCMStIRUVpTVBlcWo2NkJEYU1KZnArRTZLR2xBdWIzUmVScFNDNXcKLS0tIFB5Ri9jcHN1VEtkMmRkM1FPOTk3SWNNYnRoTG5sNGU0QVpQWmgrdDhNcDAKgXq1gkuX619OwyMlTXlenSdi2fTdyr_5TNA0C1bHgFZIiYLHOToGaNqFn4o79YpVM46h5qJ7KFPsXyvFmd1pQRfM_63OZKH1T5VSgnW1xm9Vd6SxeYwIhlm9MXvn3be47NcVnsgtiOmbDw8Ns8rX3RyuQ6WGawXHTSxLGMaPc3d0hgRAWPWtUjVh-jEmM2Bab7OHXgffcxnsOIorvwEWYFB9p4bJCY_UrXUSV59v-WvHd0OIEitfA1BMK6abezN2HevfKol19100TMBWzpTLBh8JjVMy_Kp6ruFP8oF_IE_JAgYcgTA3mHo4WCHCd4oJwC_5SncJqa51cltvC0nH7VkMdwOXL-zmE1UPmIOuqBl_zxc8lZeMpya5BiOM5HxNmsBHe_aPH2dhGDGv4_ZdoiYc_LAYFswL86VkG-Nmc9Sa2ZTan6PeLEzTSA8ZesM1b2ob1qkhN8119vq5_Sp71CjXd87ugaopawnU2QQ7E9Q" - } - ] - } - } - } - } - } - } - ], - "expected": { - "integrity": "invalid", - "code": "DUPLICATE_RECORD" - } - }, - { - "id": "detached-entry", - "source": "owner.document.json", - "operations": [ - { - "op": "add", - "path": "/entries/-", - "value": { - "id": "entry:3e211ba058fff7e22c1da3bfbe5bf7d44171c01203a7345b5e3bb46d96ce6318", - "subject": { - "version": 1, - "parent": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "nonce": "BgYGBgYGBgYGBgYGBgYGBg", - "kind": "application", - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T00:00:00.000Z", - "meta": null, - "payload": { - "type": "plain", - "data": { - "audience": "document", - "epoch": 0, - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB3bDVjblRJVHA2T0R5M0dXanF4d1NDRHpGcXZuTTRIbGE0ell1UEZ2eUhNClF1UlFZSzVXZm9qa1YzRy9iUzZYOFZwaHluYWVtaWxHMERiTVFSNkJ0aDAKLS0tIDQ2cExzUC9YMTNxZ2w0bDNqTXdMZ3dFV2VvWk9uR0hkUjZTcHA5M0tJRncKFlIfi2_E25W_HzwmtAFErTfy2UHdh3jOcTnlFRFJW1dhK1leLhjGvsa1bq4ry63B2cJ8TKdTYF4NPpKaf8PMf5-UogN8F5_FXDOFsS8T7Y6wApkk_Z8BtgzaUMnVRDPlYszFuULeF_mdlOisQRroB9lQDRzznOiOqFKYTnrxPubb7pi8091qqWogxnIovtc30OwAhP1vB2MxPo8LDcHmjhraRpCmY2k8TXdVcU_kp2kQAf3VTnf071QGtVcAllZYKF88E9YHUB1Lbpyrg_UAoBqR3sTmCqxpp6bShVGU-6Wh49i2jUVRRCBPO9HqY1OO1tsq06HWqDN933Isgv980kgHR9NbN8Lezkp101A7BNzMNw2Y888zhjhPQ3L4AVccM9WueqTqUpX5c3lO_vAkQfACHKS7KeMhReQB2m9JykfAry9PnwdcR6mAds9tfJNhZDDB509JUg" - } - } - } - } - } - ], - "expected": { - "integrity": "invalid", - "code": "UNREFERENCED_RECORD" - } - }, - { - "id": "physical-order", - "source": "owner.document.json", - "operations": [ - { - "op": "move", - "from": "/entries/1", - "path": "/entries/0" - } - ], - "expected": { - "integrity": "invalid", - "code": "ENTRY_ORDER" - } - }, - { - "id": "head-selector", - "source": "owner.document.json", - "operations": [ - { - "op": "replace", - "path": "/head", - "value": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8" - } - ], - "expected": { - "integrity": "invalid", - "code": "HEAD_INVALID" - } - }, - { - "id": "padded-signature", - "source": "owner.document.json", - "operations": [ - { - "op": "replace", - "path": "/commits/1/signature", - "value": "e4Ks2WGqVrrJ9KHFdKO6INAIWkRF1QWiSyzQ8iJYeD7z2_11pteE6zG9GrjAASibyid4edfbHQFtbCupzwo1AA=" - } - ], - "expected": { - "integrity": "invalid", - "code": "SCHEMA_INVALID" - } - }, - { - "id": "suite-version", - "source": "owner.document.json", - "operations": [ - { - "op": "replace", - "path": "/commits/0/subject/suite", - "value": "concord-future-suite" - } - ], - "expected": { - "integrity": "unsupported", - "code": "SUITE_UNSUPPORTED" - } - } - ] -} diff --git a/docs/concord/vectors/owner.document.json b/docs/concord/vectors/owner.document.json deleted file mode 100644 index 6701db2..0000000 --- a/docs/concord/vectors/owner.document.json +++ /dev/null @@ -1,121 +0,0 @@ -{ - "format": "ledger", - "version": 1, - "documentId": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "head": "commit:eb091b1a0a05708612b7429a38661946ab50b91e32eb6125041eb5bc25449672", - "commits": [ - { - "id": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "subject": { - "version": 1, - "suite": "ledger-ed25519-v1", - "parent": null, - "nonce": "AgICAgICAgICAgICAgICAg", - "signer": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "committedAt": "2026-11-21T00:00:00.000Z", - "entryIds": [ - "entry:8f426795f49c1c5c7a0ebbbd9899642b4e96724d8614415485abe626b0fe4bf2" - ], - "metadata": { - "concord": { - "system": { - "id": "concord.standard", - "version": 1 - }, - "model": { - "id": "concord.example.register", - "version": 1 - } - } - } - }, - "signature": "n8mq8BN_shgrtJJYFHuCqILxfGhP5Ehh6WMnMfIsZb8HnfzyokSmPm0pk8WkYbow867EpAUHpS4V2fEXZZ1VCg" - }, - { - "id": "commit:eb091b1a0a05708612b7429a38661946ab50b91e32eb6125041eb5bc25449672", - "subject": { - "version": 1, - "suite": "ledger-ed25519-v1", - "parent": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "nonce": "BAQEBAQEBAQEBAQEBAQEBA", - "signer": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "committedAt": "2026-11-21T00:00:01.000Z", - "entryIds": [ - "entry:d5e5883e6638f11fcfe5f0f088713b0664d0d9135cdae42aa67fe153e4a65591" - ], - "metadata": { - "message": "Set register" - } - }, - "signature": "2JGoKE8TWUVLtToXXsQwa3KqRfHp1n6Bg4D-Ne-f0NSAINaaGITATLSD4a_bxBVnlF-HN5shNiXnSgcEA5JnAw" - } - ], - "entries": [ - { - "id": "entry:8f426795f49c1c5c7a0ebbbd9899642b4e96724d8614415485abe626b0fe4bf2", - "subject": { - "version": 1, - "parent": null, - "nonce": "AQEBAQEBAQEBAQEBAQEBAQ", - "kind": "system", - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T00:00:00.000Z", - "meta": null, - "payload": { - "type": "plain", - "data": { - "type": "system.init", - "version": 1, - "data": { - "audience": "document", - "epoch": 0, - "recipient": "age13aqvttdk3ujkyjh9kg2w5an6dmy5mq5a84a4uxk3hfhnugfc9p0sy5p2wh", - "owner": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "wraps": [ - { - "identityId": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBxbmxVekN5c2Y5bDRDVkphd3hKTk1VMFNTL0E3SzJieTc3ejBZenpCc0RrCmtaNkFCMStIRUVpTVBlcWo2NkJEYU1KZnArRTZLR2xBdWIzUmVScFNDNXcKLS0tIFB5Ri9jcHN1VEtkMmRkM1FPOTk3SWNNYnRoTG5sNGU0QVpQWmgrdDhNcDAKgXq1gkuX619OwyMlTXlenSdi2fTdyr_5TNA0C1bHgFZIiYLHOToGaNqFn4o79YpVM46h5qJ7KFPsXyvFmd1pQRfM_63OZKH1T5VSgnW1xm9Vd6SxeYwIhlm9MXvn3be47NcVnsgtiOmbDw8Ns8rX3RyuQ6WGawXHTSxLGMaPc3d0hgRAWPWtUjVh-jEmM2Bab7OHXgffcxnsOIorvwEWYFB9p4bJCY_UrXUSV59v-WvHd0OIEitfA1BMK6abezN2HevfKol19100TMBWzpTLBh8JjVMy_Kp6ruFP8oF_IE_JAgYcgTA3mHo4WCHCd4oJwC_5SncJqa51cltvC0nH7VkMdwOXL-zmE1UPmIOuqBl_zxc8lZeMpya5BiOM5HxNmsBHe_aPH2dhGDGv4_ZdoiYc_LAYFswL86VkG-Nmc9Sa2ZTan6PeLEzTSA8ZesM1b2ob1qkhN8119vq5_Sp71CjXd87ugaopawnU2QQ7E9Q" - } - ] - } - } - } - } - }, - { - "id": "entry:d5e5883e6638f11fcfe5f0f088713b0664d0d9135cdae42aa67fe153e4a65591", - "subject": { - "version": 1, - "parent": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "nonce": "AwMDAwMDAwMDAwMDAwMDAw", - "kind": "application", - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T00:00:00.000Z", - "meta": null, - "payload": { - "type": "plain", - "data": { - "audience": "document", - "epoch": 0, - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSA4dWY3emwyTjRBNGNRTDdEZ0VNRlRWUDI2ZU1vdkc5em95dUFYQVQ0cERZCm1SUG12dkYwb0x5Q29CdGN2eHNHTVdnZ2xhK29LZ2FQZ1RqLzM3azVhMUkKLS0tIGhiM1A0TzN5RTVSa3ZGV0pPK3RkQmowTklHSG9LcDl0a1pYWWkrcFdweWMKBtQhYXvGVT49bAT_6v18BZ_l_3V4ruTZX8JP_rziAqE8HBblmGdydubASHHcPNZ3yrHeFAAFW_Ar3-bldPoB8SDKBoWDhq6f80qQSxdCGgj9O6OT0yWrHs45xZOr-pojDGx4WKYVbdb4VsfwcpnQh52dINB1M_kh75OguP62_lZX2ZJ1bmaB0Wwg-xBV6y1NW8nSP13uaIBaSWCD9-vQgAx_an0Jt1vE-51QRIKAQLwIHg6cVDhhuuX_Bc-2cHRHMW79e3KXlO5OLC81cZODs-erFu1Y76pTRTtbdP8bitTUOf39S8JS-FKYWQmrYlTvSWv2DdnBvi8TOuXJAwK2MAx-7UjPNHBAqYEGu589JHqzrfXJTaPCPK5Zkutg955I5JPfZIMA45JTnIxOEgagN_TbhRr4WWLHRUWI880ax9K2bv0MbNJfH2YA4UtmfWFJW1UW3SV5Vw" - } - } - } - } - ] -} diff --git a/docs/concord/vectors/owner.expected.json b/docs/concord/vectors/owner.expected.json deleted file mode 100644 index dc30a83..0000000 --- a/docs/concord/vectors/owner.expected.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "format": "concord.conformance.owner", - "version": 1, - "notice": "PUBLIC TEST MATERIAL. Never use these keys or fixed nonces for real documents.", - "identitySeedHex": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", - "groupSecretHex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e5f", - "groupRecipient": "age13aqvttdk3ujkyjh9kg2w5an6dmy5mq5a84a4uxk3hfhnugfc9p0sy5p2wh", - "groupAgeSecretKey": "AGE-SECRET-KEY-1QQQSYQCYQ5RQWZQFPG9SCRGWPUGPZYSNZS23V9CCRYDPK8QARE0SVPD6HS", - "keyPlaintext": { - "context": "concord.audience-key/1", - "parent": null, - "nonce": "AQEBAQEBAQEBAQEBAQEBAQ", - "audience": "document", - "epoch": 0, - "identityId": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "recipient": "age13aqvttdk3ujkyjh9kg2w5an6dmy5mq5a84a4uxk3hfhnugfc9p0sy5p2wh", - "secret": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHl8" - }, - "eventPlaintext": { - "context": "concord.application/1", - "parent": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "nonce": "AwMDAwMDAwMDAwMDAwMDAw", - "model": { - "id": "concord.example.register", - "version": 1 - }, - "audience": "document", - "epoch": 0, - "event": { - "type": "value.set", - "version": 1, - "data": { - "value": "hello Concord" - } - } - }, - "projection": { - "value": "hello Concord" - }, - "documentId": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "head": "commit:eb091b1a0a05708612b7429a38661946ab50b91e32eb6125041eb5bc25449672", - "canonicalSnapshotSha256": "cdab89d49b2d7df4ea5f768ef73711372b56a125948159442df44918b1fdc9f5", - "commits": [ - { - "id": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "canonicalSubject": "{\"committedAt\":\"2026-11-21T00:00:00.000Z\",\"entryIds\":[\"entry:8f426795f49c1c5c7a0ebbbd9899642b4e96724d8614415485abe626b0fe4bf2\"],\"metadata\":{\"concord\":{\"model\":{\"id\":\"concord.example.register\",\"version\":1},\"system\":{\"id\":\"concord.standard\",\"version\":1}}},\"nonce\":\"AgICAgICAgICAgICAgICAg\",\"parent\":null,\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9\",\"publicKey\":\"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\",\"version\":1},\"suite\":\"ledger-ed25519-v1\",\"version\":1}", - "signatureMessageHex": "6c65646765722e7369676e61747572652f31007b22636f6d6d69747465644174223a22323032362d31312d32315430303a30303a30302e3030305a222c22656e747279496473223a5b22656e7472793a38663432363739356634396331633563376130656262626439383939363432623465393637323464383631343431353438356162653632366230666534626632225d2c226d65746164617461223a7b22636f6e636f7264223a7b226d6f64656c223a7b226964223a22636f6e636f72642e6578616d706c652e7265676973746572222c2276657273696f6e223a317d2c2273797374656d223a7b226964223a22636f6e636f72642e7374616e64617264222c2276657273696f6e223a317d7d7d2c226e6f6e6365223a2241674943416749434167494341674943416749434167222c22706172656e74223a6e756c6c2c227369676e6572223a7b22616c676f726974686d223a2245643235353139222c226964223a226964656e746974793a32316665333164666131353461323631363236626638353430343666643232373162376265643462366162653435616135383837376566343766393732316239222c227075626c69634b6579223a223131715941594b7843726656535f3754795751484f6737686376506170694d6c727749616150634855526f222c2276657273696f6e223a317d2c227375697465223a226c65646765722d656432353531392d7631222c2276657273696f6e223a317d", - "signatureHex": "9fc9aaf0137fb2182bb49258147b82a882f17c684fe44861e9632731f22c65bf079dfcf2a244a63e6d2993c5a461ba30f3aec4a40507a52e15d9f117659d550a" - }, - { - "id": "commit:eb091b1a0a05708612b7429a38661946ab50b91e32eb6125041eb5bc25449672", - "canonicalSubject": "{\"committedAt\":\"2026-11-21T00:00:01.000Z\",\"entryIds\":[\"entry:d5e5883e6638f11fcfe5f0f088713b0664d0d9135cdae42aa67fe153e4a65591\"],\"metadata\":{\"message\":\"Set register\"},\"nonce\":\"BAQEBAQEBAQEBAQEBAQEBA\",\"parent\":\"commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9\",\"publicKey\":\"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\",\"version\":1},\"suite\":\"ledger-ed25519-v1\",\"version\":1}", - "signatureMessageHex": "6c65646765722e7369676e61747572652f31007b22636f6d6d69747465644174223a22323032362d31312d32315430303a30303a30312e3030305a222c22656e747279496473223a5b22656e7472793a64356535383833653636333866313166636665356630663038383731336230363634643064393133356364616534326161363766653135336534613635353931225d2c226d65746164617461223a7b226d657373616765223a22536574207265676973746572227d2c226e6f6e6365223a2242415145424151454241514542415145424151454241222c22706172656e74223a22636f6d6d69743a36373163356531386631616365363733616139613638623232613161343133376636376431303638616238326165333438343036323761666336666663326638222c227369676e6572223a7b22616c676f726974686d223a2245643235353139222c226964223a226964656e746974793a32316665333164666131353461323631363236626638353430343666643232373162376265643462366162653435616135383837376566343766393732316239222c227075626c69634b6579223a223131715941594b7843726656535f3754795751484f6737686376506170694d6c727749616150634855526f222c2276657273696f6e223a317d2c227375697465223a226c65646765722d656432353531392d7631222c2276657273696f6e223a317d", - "signatureHex": "d891a8284f1359454bb53a175ec4306b72aa45f1e9d67e818380fe35ef9fd0d48020d69a1884c04cb483e1afdbc41567945f87379b213625e74a070403926703" - } - ], - "entries": [ - { - "id": "entry:8f426795f49c1c5c7a0ebbbd9899642b4e96724d8614415485abe626b0fe4bf2", - "canonicalSubject": "{\"author\":\"identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9\",\"authoredAt\":\"2026-11-21T00:00:00.000Z\",\"kind\":\"system\",\"meta\":null,\"nonce\":\"AQEBAQEBAQEBAQEBAQEBAQ\",\"parent\":null,\"payload\":{\"data\":{\"data\":{\"audience\":\"document\",\"epoch\":0,\"owner\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9\",\"publicKey\":\"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo\",\"version\":1},\"recipient\":\"age13aqvttdk3ujkyjh9kg2w5an6dmy5mq5a84a4uxk3hfhnugfc9p0sy5p2wh\",\"wraps\":[{\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBxbmxVekN5c2Y5bDRDVkphd3hKTk1VMFNTL0E3SzJieTc3ejBZenpCc0RrCmtaNkFCMStIRUVpTVBlcWo2NkJEYU1KZnArRTZLR2xBdWIzUmVScFNDNXcKLS0tIFB5Ri9jcHN1VEtkMmRkM1FPOTk3SWNNYnRoTG5sNGU0QVpQWmgrdDhNcDAKgXq1gkuX619OwyMlTXlenSdi2fTdyr_5TNA0C1bHgFZIiYLHOToGaNqFn4o79YpVM46h5qJ7KFPsXyvFmd1pQRfM_63OZKH1T5VSgnW1xm9Vd6SxeYwIhlm9MXvn3be47NcVnsgtiOmbDw8Ns8rX3RyuQ6WGawXHTSxLGMaPc3d0hgRAWPWtUjVh-jEmM2Bab7OHXgffcxnsOIorvwEWYFB9p4bJCY_UrXUSV59v-WvHd0OIEitfA1BMK6abezN2HevfKol19100TMBWzpTLBh8JjVMy_Kp6ruFP8oF_IE_JAgYcgTA3mHo4WCHCd4oJwC_5SncJqa51cltvC0nH7VkMdwOXL-zmE1UPmIOuqBl_zxc8lZeMpya5BiOM5HxNmsBHe_aPH2dhGDGv4_ZdoiYc_LAYFswL86VkG-Nmc9Sa2ZTan6PeLEzTSA8ZesM1b2ob1qkhN8119vq5_Sp71CjXd87ugaopawnU2QQ7E9Q\",\"identityId\":\"identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9\"}]},\"type\":\"system.init\",\"version\":1},\"type\":\"plain\"},\"version\":1}" - }, - { - "id": "entry:d5e5883e6638f11fcfe5f0f088713b0664d0d9135cdae42aa67fe153e4a65591", - "canonicalSubject": "{\"author\":\"identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9\",\"authoredAt\":\"2026-11-21T00:00:00.000Z\",\"kind\":\"application\",\"meta\":null,\"nonce\":\"AwMDAwMDAwMDAwMDAwMDAw\",\"parent\":\"commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8\",\"payload\":{\"data\":{\"audience\":\"document\",\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSA4dWY3emwyTjRBNGNRTDdEZ0VNRlRWUDI2ZU1vdkc5em95dUFYQVQ0cERZCm1SUG12dkYwb0x5Q29CdGN2eHNHTVdnZ2xhK29LZ2FQZ1RqLzM3azVhMUkKLS0tIGhiM1A0TzN5RTVSa3ZGV0pPK3RkQmowTklHSG9LcDl0a1pYWWkrcFdweWMKBtQhYXvGVT49bAT_6v18BZ_l_3V4ruTZX8JP_rziAqE8HBblmGdydubASHHcPNZ3yrHeFAAFW_Ar3-bldPoB8SDKBoWDhq6f80qQSxdCGgj9O6OT0yWrHs45xZOr-pojDGx4WKYVbdb4VsfwcpnQh52dINB1M_kh75OguP62_lZX2ZJ1bmaB0Wwg-xBV6y1NW8nSP13uaIBaSWCD9-vQgAx_an0Jt1vE-51QRIKAQLwIHg6cVDhhuuX_Bc-2cHRHMW79e3KXlO5OLC81cZODs-erFu1Y76pTRTtbdP8bitTUOf39S8JS-FKYWQmrYlTvSWv2DdnBvi8TOuXJAwK2MAx-7UjPNHBAqYEGu589JHqzrfXJTaPCPK5Zkutg955I5JPfZIMA45JTnIxOEgagN_TbhRr4WWLHRUWI880ax9K2bv0MbNJfH2YA4UtmfWFJW1UW3SV5Vw\",\"epoch\":0},\"type\":\"plain\"},\"version\":1}" - } - ] -} diff --git a/docs/concord/vectors/owner.fork.document.json b/docs/concord/vectors/owner.fork.document.json deleted file mode 100644 index 649762e..0000000 --- a/docs/concord/vectors/owner.fork.document.json +++ /dev/null @@ -1,121 +0,0 @@ -{ - "format": "ledger", - "version": 1, - "documentId": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "head": "commit:4175be5fa139ebe8c6847ae24b7fceb10bf9a2e113726d95917870d4dabf7f34", - "commits": [ - { - "id": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "subject": { - "version": 1, - "suite": "ledger-ed25519-v1", - "parent": null, - "nonce": "AgICAgICAgICAgICAgICAg", - "signer": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "committedAt": "2026-11-21T00:00:00.000Z", - "entryIds": [ - "entry:8f426795f49c1c5c7a0ebbbd9899642b4e96724d8614415485abe626b0fe4bf2" - ], - "metadata": { - "concord": { - "system": { - "id": "concord.standard", - "version": 1 - }, - "model": { - "id": "concord.example.register", - "version": 1 - } - } - } - }, - "signature": "n8mq8BN_shgrtJJYFHuCqILxfGhP5Ehh6WMnMfIsZb8HnfzyokSmPm0pk8WkYbow867EpAUHpS4V2fEXZZ1VCg" - }, - { - "id": "commit:4175be5fa139ebe8c6847ae24b7fceb10bf9a2e113726d95917870d4dabf7f34", - "subject": { - "version": 1, - "suite": "ledger-ed25519-v1", - "parent": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "nonce": "BQUFBQUFBQUFBQUFBQUFBQ", - "signer": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "committedAt": "2026-11-21T00:00:01.000Z", - "entryIds": [ - "entry:d5e5883e6638f11fcfe5f0f088713b0664d0d9135cdae42aa67fe153e4a65591" - ], - "metadata": { - "message": "Alternative local commit" - } - }, - "signature": "LQhpvy333gGHsxSQDgxtg4Sjhvtt8btZk2bnHRkVKOdQq7agJ_MhklB1Dno96NnqgvBQHtTVCHzjQZpO3_npDQ" - } - ], - "entries": [ - { - "id": "entry:8f426795f49c1c5c7a0ebbbd9899642b4e96724d8614415485abe626b0fe4bf2", - "subject": { - "version": 1, - "parent": null, - "nonce": "AQEBAQEBAQEBAQEBAQEBAQ", - "kind": "system", - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T00:00:00.000Z", - "meta": null, - "payload": { - "type": "plain", - "data": { - "type": "system.init", - "version": 1, - "data": { - "audience": "document", - "epoch": 0, - "recipient": "age13aqvttdk3ujkyjh9kg2w5an6dmy5mq5a84a4uxk3hfhnugfc9p0sy5p2wh", - "owner": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "wraps": [ - { - "identityId": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBxbmxVekN5c2Y5bDRDVkphd3hKTk1VMFNTL0E3SzJieTc3ejBZenpCc0RrCmtaNkFCMStIRUVpTVBlcWo2NkJEYU1KZnArRTZLR2xBdWIzUmVScFNDNXcKLS0tIFB5Ri9jcHN1VEtkMmRkM1FPOTk3SWNNYnRoTG5sNGU0QVpQWmgrdDhNcDAKgXq1gkuX619OwyMlTXlenSdi2fTdyr_5TNA0C1bHgFZIiYLHOToGaNqFn4o79YpVM46h5qJ7KFPsXyvFmd1pQRfM_63OZKH1T5VSgnW1xm9Vd6SxeYwIhlm9MXvn3be47NcVnsgtiOmbDw8Ns8rX3RyuQ6WGawXHTSxLGMaPc3d0hgRAWPWtUjVh-jEmM2Bab7OHXgffcxnsOIorvwEWYFB9p4bJCY_UrXUSV59v-WvHd0OIEitfA1BMK6abezN2HevfKol19100TMBWzpTLBh8JjVMy_Kp6ruFP8oF_IE_JAgYcgTA3mHo4WCHCd4oJwC_5SncJqa51cltvC0nH7VkMdwOXL-zmE1UPmIOuqBl_zxc8lZeMpya5BiOM5HxNmsBHe_aPH2dhGDGv4_ZdoiYc_LAYFswL86VkG-Nmc9Sa2ZTan6PeLEzTSA8ZesM1b2ob1qkhN8119vq5_Sp71CjXd87ugaopawnU2QQ7E9Q" - } - ] - } - } - } - } - }, - { - "id": "entry:d5e5883e6638f11fcfe5f0f088713b0664d0d9135cdae42aa67fe153e4a65591", - "subject": { - "version": 1, - "parent": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "nonce": "AwMDAwMDAwMDAwMDAwMDAw", - "kind": "application", - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T00:00:00.000Z", - "meta": null, - "payload": { - "type": "plain", - "data": { - "audience": "document", - "epoch": 0, - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSA4dWY3emwyTjRBNGNRTDdEZ0VNRlRWUDI2ZU1vdkc5em95dUFYQVQ0cERZCm1SUG12dkYwb0x5Q29CdGN2eHNHTVdnZ2xhK29LZ2FQZ1RqLzM3azVhMUkKLS0tIGhiM1A0TzN5RTVSa3ZGV0pPK3RkQmowTklHSG9LcDl0a1pYWWkrcFdweWMKBtQhYXvGVT49bAT_6v18BZ_l_3V4ruTZX8JP_rziAqE8HBblmGdydubASHHcPNZ3yrHeFAAFW_Ar3-bldPoB8SDKBoWDhq6f80qQSxdCGgj9O6OT0yWrHs45xZOr-pojDGx4WKYVbdb4VsfwcpnQh52dINB1M_kh75OguP62_lZX2ZJ1bmaB0Wwg-xBV6y1NW8nSP13uaIBaSWCD9-vQgAx_an0Jt1vE-51QRIKAQLwIHg6cVDhhuuX_Bc-2cHRHMW79e3KXlO5OLC81cZODs-erFu1Y76pTRTtbdP8bitTUOf39S8JS-FKYWQmrYlTvSWv2DdnBvi8TOuXJAwK2MAx-7UjPNHBAqYEGu589JHqzrfXJTaPCPK5Zkutg955I5JPfZIMA45JTnIxOEgagN_TbhRr4WWLHRUWI880ax9K2bv0MbNJfH2YA4UtmfWFJW1UW3SV5Vw" - } - } - } - } - ] -} diff --git a/docs/concord/vectors/owner.genesis.document.json b/docs/concord/vectors/owner.genesis.document.json deleted file mode 100644 index 103787c..0000000 --- a/docs/concord/vectors/owner.genesis.document.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "format": "ledger", - "version": 1, - "documentId": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "head": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "commits": [ - { - "id": "commit:671c5e18f1ace673aa9a68b22a1a4137f67d1068ab82ae34840627afc6ffc2f8", - "subject": { - "version": 1, - "suite": "ledger-ed25519-v1", - "parent": null, - "nonce": "AgICAgICAgICAgICAgICAg", - "signer": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "committedAt": "2026-11-21T00:00:00.000Z", - "entryIds": [ - "entry:8f426795f49c1c5c7a0ebbbd9899642b4e96724d8614415485abe626b0fe4bf2" - ], - "metadata": { - "concord": { - "system": { - "id": "concord.standard", - "version": 1 - }, - "model": { - "id": "concord.example.register", - "version": 1 - } - } - } - }, - "signature": "n8mq8BN_shgrtJJYFHuCqILxfGhP5Ehh6WMnMfIsZb8HnfzyokSmPm0pk8WkYbow867EpAUHpS4V2fEXZZ1VCg" - } - ], - "entries": [ - { - "id": "entry:8f426795f49c1c5c7a0ebbbd9899642b4e96724d8614415485abe626b0fe4bf2", - "subject": { - "version": 1, - "parent": null, - "nonce": "AQEBAQEBAQEBAQEBAQEBAQ", - "kind": "system", - "author": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "authoredAt": "2026-11-21T00:00:00.000Z", - "meta": null, - "payload": { - "type": "plain", - "data": { - "type": "system.init", - "version": 1, - "data": { - "audience": "document", - "epoch": 0, - "recipient": "age13aqvttdk3ujkyjh9kg2w5an6dmy5mq5a84a4uxk3hfhnugfc9p0sy5p2wh", - "owner": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "wraps": [ - { - "identityId": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9", - "ciphertext": "YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBxbmxVekN5c2Y5bDRDVkphd3hKTk1VMFNTL0E3SzJieTc3ejBZenpCc0RrCmtaNkFCMStIRUVpTVBlcWo2NkJEYU1KZnArRTZLR2xBdWIzUmVScFNDNXcKLS0tIFB5Ri9jcHN1VEtkMmRkM1FPOTk3SWNNYnRoTG5sNGU0QVpQWmgrdDhNcDAKgXq1gkuX619OwyMlTXlenSdi2fTdyr_5TNA0C1bHgFZIiYLHOToGaNqFn4o79YpVM46h5qJ7KFPsXyvFmd1pQRfM_63OZKH1T5VSgnW1xm9Vd6SxeYwIhlm9MXvn3be47NcVnsgtiOmbDw8Ns8rX3RyuQ6WGawXHTSxLGMaPc3d0hgRAWPWtUjVh-jEmM2Bab7OHXgffcxnsOIorvwEWYFB9p4bJCY_UrXUSV59v-WvHd0OIEitfA1BMK6abezN2HevfKol19100TMBWzpTLBh8JjVMy_Kp6ruFP8oF_IE_JAgYcgTA3mHo4WCHCd4oJwC_5SncJqa51cltvC0nH7VkMdwOXL-zmE1UPmIOuqBl_zxc8lZeMpya5BiOM5HxNmsBHe_aPH2dhGDGv4_ZdoiYc_LAYFswL86VkG-Nmc9Sa2ZTan6PeLEzTSA8ZesM1b2ob1qkhN8119vq5_Sp71CjXd87ugaopawnU2QQ7E9Q" - } - ] - } - } - } - } - } - ] -} diff --git a/docs/concord/vectors/primitives.json b/docs/concord/vectors/primitives.json deleted file mode 100644 index b2b28ac..0000000 --- a/docs/concord/vectors/primitives.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "format": "concord.conformance.primitives", - "version": 1, - "identity": { - "seedHex": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", - "public": { - "version": 1, - "algorithm": "Ed25519", - "publicKey": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo", - "id": "identity:21fe31dfa154a261626bf854046fd2271b7bed4b6abe45aa58877ef47f9721b9" - }, - "x25519SecretHex": "307c83864f2833cb427a2ef1c00a013cfdff2768d980c0a3a520f006904de94f", - "x25519PublicHex": "d85e07ec22b0ad881537c2f44d662d1a143cf830c57aca4305d85c7a90f6b62e", - "ageRecipient": "age1mp0q0mpzkzkcs9fhct6y6e3drg2re7psc4av5sc9mpw84y8kkchq6r9kjp", - "ageSecretKey": "AGE-SECRET-KEY-1XP7G8PJ09QEUKSN69MCUQZSP8N7L7FMGMXQVPGA9YRCQDYZDA98STDSL3D", - "rfc8032EmptyMessageSignatureHex": "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b" - }, - "canonical": [ - { - "id": "key-order", - "inputJson": "{\"z\":1,\"a\":[true,null,\"x\"]}", - "canonical": "{\"a\":[true,null,\"x\"],\"z\":1}" - }, - { - "id": "integer-extremes", - "inputJson": "[9007199254740991,-9007199254740991,1.0,1e0]", - "canonical": "[9007199254740991,-9007199254740991,1,1]" - }, - { - "id": "unicode-key-order", - "inputJson": "{\"\":1,\"😀\":2,\"a\":3}", - "canonical": "{\"a\":3,\"😀\":2,\"\":1}" - }, - { - "id": "unicode-preserved", - "inputJson": "[\"é\",\"é\"]", - "canonical": "[\"é\",\"é\"]" - }, - { - "id": "escaping", - "inputJson": "{\"line\":\"a\\nb\",\"quote\":\"\\\"\",\"slash\":\"/\"}", - "canonical": "{\"line\":\"a\\nb\",\"quote\":\"\\\"\",\"slash\":\"/\"}" - } - ], - "rejectedJson": [ - { - "id": "duplicate", - "inputJson": "{\"a\":1,\"a\":2}", - "errorCode": "JSON_INVALID" - }, - { - "id": "escape-duplicate", - "inputJson": "{\"a\":1,\"\\u0061\":2}", - "errorCode": "JSON_INVALID" - }, - { - "id": "unsafe", - "inputJson": "9007199254740992", - "errorCode": "JSON_INVALID" - }, - { - "id": "rounded-unsafe", - "inputJson": "9007199254740991.1", - "errorCode": "JSON_INVALID" - }, - { - "id": "fraction", - "inputJson": "0.5", - "errorCode": "JSON_INVALID" - }, - { - "id": "negative-zero", - "inputJson": "-0", - "errorCode": "JSON_INVALID" - }, - { - "id": "negative-zero-decimal", - "inputJson": "-0.0", - "errorCode": "JSON_INVALID" - }, - { - "id": "surrogate", - "inputJson": "\"\\ud800\"", - "errorCode": "JSON_INVALID" - }, - { - "id": "trailing", - "inputJson": "{} {}", - "errorCode": "JSON_INVALID" - } - ] -} diff --git a/docs/concord/vectors/relationships.json b/docs/concord/vectors/relationships.json deleted file mode 100644 index 8318447..0000000 --- a/docs/concord/vectors/relationships.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "version": 1, - "cases": [ - { - "a": "owner.document.json", - "b": "owner.document.json", - "expected": "equal" - }, - { - "a": "owner.genesis.document.json", - "b": "owner.document.json", - "expected": "behind" - }, - { - "a": "owner.document.json", - "b": "owner.genesis.document.json", - "expected": "ahead" - }, - { - "a": "owner.document.json", - "b": "owner.fork.document.json", - "expected": "diverged" - }, - { - "a": "owner.fork.document.json", - "b": "owner.document.json", - "expected": "diverged" - } - ] -} diff --git a/docs/engineering/alpha-first-slice.md b/docs/engineering/alpha-first-slice.md deleted file mode 100644 index b513891..0000000 --- a/docs/engineering/alpha-first-slice.md +++ /dev/null @@ -1,75 +0,0 @@ -# Identity, Armour and the Concord first slice - -This established migration path is retained for the project brief's implementation -history. The first slice introduced strict Identity capabilities, TypeScript age -composition and a private register lifecycle. Subsequent work added independent -groups, drafts, storage proof and Seal, then moved the signed container and history -lifecycle into standalone Ledger. [ADR 0018](../adr/0018-use-one-ledger-container-for-concord.md) -records that accepted container change; earlier Concord-only signed bytes are not a -compatibility promise. - -The current workspace is five libraries. Setup and check scope live in -[CONTRIBUTING.md](../../CONTRIBUTING.md) and the -[repository guide](repository-hygiene.md); release work lives in the -[release backlog](release-and-deployment.md). Earlier migration commands, test totals -and temporary artifact digests do not certify the current checkout. Git retains the -superseded implementation reports and sources. - -## Retained capabilities and their owners - -| Area | Retained behavior | Current owner | -| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | -| Identity | Seeds, mnemonic/serialized helpers, Ed25519 signatures, X25519/age conversion, strict public identities and exact-byte signer capability | Identity public exports; secret scalar callbacks stay scoped and cleaned up | -| Encryption | Recipient/identity/passphrase and binary/text age operations | Armour over typage, without WASM or an initialization lifecycle | -| Signed history | Bounded parsing, canonical subjects, IDs, signatures, chain verification, comparison, staging and ordered replay | Ledger's common container and lifecycle | -| Private framework | Bootstrap, signer-bound authority, group epochs/wraps and contextual application encryption | Concord system extensions using Identity/Armour | -| Application projection | Typed commands, event validation and pure reducers | Concord application models; register is an example in `/testing` | -| Publication | Complete candidate evaluation followed by atomic adoption; detached bytes/reports/state | Concord runtime above a private candidate Ledger handle | - -Identity's contextual convenience signing and capability exact-byte signing remain -distinct contracts. Armour's production implementation does not invoke the native -age executable; the independent executable is a test oracle. Seal owns its separate -proof format and does not depend on Concord for canonical subjects. - -## Lifecycle proof - -The small register demonstrates: - -```text -create -> dispatch/commit -> export -> open -> verify -> replay -> inspect -``` - -Create signs genesis; immediate dispatch commits an encrypted event. Export contains -committed history. Open with the matching reader verifies all reachable history, -completes system replay and reconstructs the register. A decrypt-only reader can -reconstruct without write authority. Missing requirements, unavailable keys, invalid -integrity and failed application reconstruction have explicit inspection outcomes; -none publishes a partial trusted projection. Replay consumes saved history rather -than reissuing commands with new randomness. - -The [protocol](../concord/alpha-protocol.md), -[standard profile](../concord/standard-profile.md), -[conformance cases](../concord/conformance.md) and -[fixed vectors](../concord/vectors/README.md) define the current checks. -Public tests preserve malformed input, tamper, context, authority, reducer failure, -resource limits, concurrent authoring and detached-value cases. Semantic negative -fixtures are re-signed with public test seeds so system/model failures are distinct -from ordinary integrity failures. - -## Later slices and explicit boundaries - -Independent membership and readable/locked replay are described in the -[group note](independent-groups-2026-11-20.md) and -[group contract](../concord/group-profile-design.md). Draft cases are defined in -[conformance](../concord/conformance.md#d-and-s-grouped-authoring-and-complete-standard-profile-step-4). -Drafts are in memory; consumers own persistence/recovery under -[ADR 0019](../adr/0019-keep-draft-persistence-with-consumers.md). -The [storage contract](../concord/storage-boundary.md) keeps saving separate from -local commits and makes expected-head conflict limits explicit. - -The former handshake application is retired. Its useful library contracts survive -in public lifecycle, group, draft, storage and installed-consumer tests; no maintained -MCP application or hosted board is required to release these libraries. UI is outside -scope, Workspace is deferred, and legacy import is separate work. Custom asynchronous -profiles still obey the host no-reentry contract in -[ADR 0014](../adr/0014-keep-async-profile-reentry-a-host-contract.md). diff --git a/docs/engineering/developer-archetype.md b/docs/engineering/developer-archetype.md deleted file mode 100644 index 391b937..0000000 --- a/docs/engineering/developer-archetype.md +++ /dev/null @@ -1,108 +0,0 @@ -# The toolchain engineer - -Our developer archetype for personal projects with Codex and ChatGPT. -Concord is its first application. This is an engineering stance and working -practice, not a claim that all of the preferred tools are installed. - -## Purpose - -Build software through short, trustworthy feedback loops. Own the environment -that makes a correct change easy to produce, check, review, and ship. Treat tool -configuration, diagnostics, public types, and package outputs as engineering -surfaces with real users. - -Use Oxc as the preferred foundation for JavaScript and TypeScript code-quality -tooling. Its separate formatter, linter, parser, transformer, resolver, and -minifier offer different capabilities; choose the component that serves the job. -See [Oxc's tool map](https://oxc.rs/docs/guide/introduction.html). - -## Habits - -### Make feedback cheap enough to use continuously - -Run the smallest meaningful check while shaping a change, then the relevant -integration checks before delivery. Fix slow or unreliable checks as concrete -engineering problems. Measure elapsed time, scope, and environment so an apparent -speedup cannot hide reduced coverage or a warm cache. - -### Turn repeated judgments into executable checks - -Let the formatter settle layout. Use lint rules for repeatable mistakes, types -for contracts, and tests for observable behavior. When a review finding recurs, -consider a focused rule or regression test. A new rule should have a demonstrated -failure to catch and an acceptable false-positive rate. - -### Give agents a precise working environment - -Expose stable package scripts, useful diagnostics, and small coherent changes. -Keep local and CI checks aligned. Use structured or agent-oriented diagnostics -where the installed tool supports them, and retain exit statuses. Read the -diagnostic and surrounding code before applying a fix. Repair the cause rather -than broadening an ignore or weakening an assertion. - -### Understand the language and package boundaries - -Know the distinction between parsing, transforming, type checking, bundling, -and running code. Removing TypeScript syntax does not prove type correctness. -Successful source tests do not prove that an exported package works. For semantic -code migrations, prefer syntax-aware transformations when text replacement cannot -safely distinguish code structure; verify the transformed behavior. - -### Adopt tools deliberately - -Prefer Oxc when it covers the required behavior. Before a replacement, compare -rule coverage, file support, resolution, output targets, and consumer contracts. -Keep a narrowly documented fallback for a real gap. Revisit it when that gap -closes. A tool's implementation language or upstream benchmark is not evidence -of a benefit in this repository. - -## Preferred tool roles - -| Responsibility | Direction | Evidence required | -| --------------------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------- | -| Formatting | Oxfmt | Supported file types, reviewed output, clean scoped check | -| JS/TS linting | Oxlint | Relevant rules enabled, diagnostics understood, no silently lost checks | -| Type-aware linting | Oxlint with `oxlint-tsgolint` | Resolved project types and compatible rules/configuration | -| Type correctness | Keep an explicit type-checking gate | Validate equivalent diagnostics before replacing the existing checker | -| Parsing, transforms, resolution, minification | Prefer appropriate Oxc components when building or replacing tooling | Correct outputs, targets, imports, and measured benefit | -| Behavioral tests and builds | Use the project's test and build tools | Observable contracts and public package outputs verified | - -[Oxlint](https://oxc.rs/docs/guide/usage/linter.html) prioritizes correctness -diagnostics. [Oxfmt](https://oxc.rs/docs/guide/usage/formatter.html) provides the -formatting workflow. [Type-aware linting](https://oxc.rs/docs/guide/usage/linter/type-aware.html) -uses an additional component and needs resolved type information, including -dependency declarations in a monorepo. Its optional type-checking mode must be -evaluated separately from simply enabling type-aware lint rules. - -## Development loop - -1. Identify the observable contract and the check that can establish it. -2. Inspect the relevant implementation, consumers, and resolved dependencies. -3. Make a small coherent change; run available focused diagnostics and tests. -4. Apply appropriate automatic fixes, inspect the diff, and format touched files. -5. Run the relevant final gates, including built-package imports for packaging work. -6. Report outcomes and limitations with actual command results. - -This adapts [Oxc's coding-agent guidance](https://oxc.rs/docs/guide/usage/coding-agents.html) -to scoped edits and the tools actually available in the repository. It does not -replace runtime verification with a lint-and-format pass. - -## Application to Concord - -Concord's hard guarantees are signed-history integrity, deterministic replay, -permission enforcement, and portable package behavior. Fast tooling should make -it easier to check these guarantees frequently. Linting cannot establish their -correctness by itself. - -The repository uses Vite+ Oxfmt, typed Oxlint and explicit TypeScript checks. -The [repository guide](repository-hygiene.md) records current scope and ownership; -[CONTRIBUTING.md](../../CONTRIBUTING.md) records commands. Keep tool upgrades and -mass formatting separate from behavior changes so each diff remains reviewable. -Assess replacements through consumer evidence and measured feedback-loop costs. - -## What good looks like - -A developer using this profile can explain which contract changed, which tool -checked each part of it, why the result is trustworthy, and where uncertainty -remains. The toolchain reduces routine work while leaving more attention for -domain design and user-visible behavior. diff --git a/docs/engineering/independent-groups-2026-11-20.md b/docs/engineering/independent-groups-2026-11-20.md deleted file mode 100644 index febc6cf..0000000 --- a/docs/engineering/independent-groups-2026-11-20.md +++ /dev/null @@ -1,81 +0,0 @@ -# Independent groups and readable replay - -The B03/B04 slice introduced independent membership and explicit readable/locked -replay. This retained note describes that implemented behavior and where to find -its evidence. The current signed container is Ledger under -[ADR 0018](../adr/0018-use-one-ledger-container-for-concord.md); fixed documents were -regenerated for that accepted format change. Earlier Concord-only hashes and old -test counts are not current acceptance evidence. - -## Behavior and authority - -- A default `document` writer can create a group without owner approval. Its creator - gets the group's four capabilities; the document owner gets no implicit access. -- Group membership is independent of `document`. Removing default membership leaves - other group rights intact. Every command selects one audience, and every event - emitted by that command must select that same audience. -- Admission/re-admission grants every historical epoch key for that group. Removal - rotates only that group and wraps the new key for exactly its remaining members. - Already obtained keys/plaintext remain available; revocation cannot erase them. -- Replay verifies complete signed history and every public authority transition - before decryption/model callbacks. Missing keys yield locked markers; available-key - authentication/context failure invalidates reconstruction. -- A model requires all events unless it opts into `reduceLocked`. That hook receives - a public marker and historical audience-scoped facts. Neither failed locked handling - nor a late readable transition may publish an intermediate trusted projection. -- Ready state and `replay()` report projection, coverage and exact locked count. - Complete coverage has no locked entries. Readable coverage is a scoped application - reconstruction and does not certify hidden application semantics. -- Successful system replay exposes ordered readable/locked inspection entries and - public audience summaries, even if later model replay fails. Runtime checks profile - output for exact coverage, signer/audience binding and closed nested member/epoch - records before exposing that evidence. - -The [group design](../concord/group-profile-design.md), -[standard profile](../concord/standard-profile.md) and -[conformance scenarios](../concord/conformance.md) own the exact current contract. -[ADR 0015](../adr/0015-keep-audience-memberships-independent.md) and -[ADR 0016](../adr/0016-route-each-command-to-one-audience.md) record the decisions. - -## API and disclosure - -`@ternent/concord/system` supplies `createGroup`, `setMember` and `removeMember`. -Member helpers default to `document` only when audience is omitted. Models can supply -command/event audience selectors and `reduceLocked`; omitted selectors use document -routing. Mixed command routing fails before protection/signing. - -The system owns membership, group keys, wraps and epochs; Identity/Armour own the -cryptography. Each application entry is encrypted once to one named group/epoch. -No anonymous envelope, trial-decryption routing or automatic owner self-grant is -introduced. Group IDs, capabilities, signers, wrap targets, epochs/recipients, -linkage, sizes/counts and signed metadata remain public. Names and descriptions -belong in encrypted application data. - -## Evidence to preserve - -Saved `groups.removed.document.json` and `groups.readmitted.document.json` vectors -cover two groups, an owner outside both, independent default removal, group rotation -and full-history readmission. Literal expectations cover three readers at both heads. -Node crypto independently checked the Ledger hashes and Ed25519 signatures; expected -projections were constructed from the six intended application events, not replay. -See [vector provenance](../concord/vectors/README.md). - -`packages/concord/test/groups.test.ts` covers permissions, historical access, -routing/atomicity, opted-in/full models, saved-byte determinism, signed semantic -failures, cross-group substitution, tampering before callbacks and malformed profile -streams. Membership/runtime tests retain complementary failure coverage. External -candidate consumers exercise the saved vectors and public authoring; declaration -fixtures check helpers, coverage and locked-marker narrowing. The Chromium proof -includes independent-group scoped replay. - -Current gate results belong to the run reports described in the -[repository guide](repository-hygiene.md#acceptance-boundaries), not this dated note. -No publication, remote CI status or performance measurement is inferred here. - -Draft authoring now groups separate single-audience commands into an atomic commit; -see [draft conformance](../concord/conformance.md#d-and-s-grouped-authoring-and-complete-standard-profile-step-4). -Draft persistence stays consumer-owned under -[ADR 0019](../adr/0019-keep-draft-persistence-with-consumers.md). -The [storage proof](../concord/storage-boundary.md) is implemented independently of -runtime publication. Remaining delivery work is on the -[release backlog](release-and-deployment.md#release-backlog). diff --git a/docs/engineering/release-and-deployment.md b/docs/engineering/release-and-deployment.md deleted file mode 100644 index bd994db..0000000 --- a/docs/engineering/release-and-deployment.md +++ /dev/null @@ -1,326 +0,0 @@ -# Library release contract and backlog - -Current scope, 2026-11-22: ship five independently usable npm products: -`@ternent/identity`, `@ternent/armour`, `@ternent/ledger`, `@ternent/concord` and -`@ternent/seal`. Ledger owns the common signed container; Concord composes the -framework above it. [ADR 0020](../adr/0020-simplify-core-around-five-libraries.md) -records the repository simplification. UI, portable tooling and hosted applications -are outside this release. Workspace is deferred. - -The first registry-backed alpha completed on 2026-11-22 through the protected -[release run](https://github.com/ternent/core/actions/runs/45040724049), using -[main verification](https://github.com/ternent/core/actions/runs/45040402005). -All five packages published with npm provenance and passed fresh public-registry -consumption on Node 22.18.0, 24.21.0 and 26.13.1, declarations, CLI and Chromium -before `next` promotion. Existing `latest` tags were preserved. - -| Package | Published `next` | Preserved `latest` | -| ------------------- | ---------------- | ------------------ | -| `@ternent/identity` | `0.6.0-alpha.1` | `0.5.0` | -| `@ternent/armour` | `0.3.0-alpha.1` | `0.2.3` | -| `@ternent/ledger` | `0.2.0-alpha.1` | `0.1.8` | -| `@ternent/concord` | `0.3.0-alpha.1` | `0.2.9` | -| `@ternent/seal` | `0.5.0-alpha.1` | `0.3.10` | - -Release ID: `0eea0155bc9ecfda049d60130c39c85c999ec36853eafe7bfaf4bdb5719cc538`. -The retained receipt is complete; every downloaded npm tarball matched the plan, -and the production Seal proof verified against the separately trusted release key. -Retries reused identical published versions; Concord's unpublished candidate was -corrected to include its provenance repository before its successful first publish. -The verification scope is described in the [repository guide](repository-hygiene.md). - -## Current boundary - -The five libraries implement identity/encryption primitives, Ledger's signed-log -lifecycle and optional Armour payload codecs, Concord's independent groups/readable -replay/drafts/storage boundary, and Seal's library/CLI. Staging is deliberately in -memory; consumers own commit cadence and any draft persistence/recovery under -[ADR 0019](../adr/0019-keep-draft-persistence-with-consumers.md). There is no pending -library persistence feature or UI migration required for release. - -Current candidate acceptance serves exact packed tarballs from a disposable loopback -registry and installs by package name/version in an external directory, without -sibling overrides. The registry cannot proxy `@ternent/*` to published predecessors. -It checks candidate integrity, strict publint, runtime behavior, declarations, -CLI, fixed vectors, import isolation and Chromium. Deliberate missing-candidate and -incompatible sibling-range probes must fail. This establishes candidate dependency -resolution, not publication or consumption from the public registry. -The publisher consumes a retained plan and tarballs, checks collisions, and journals -partial publication and channel promotion. Its live entry point requires the -`release.yml` workflow on main, explicit enablement, a trusted Seal key and pinned -npm 12.2.3. The repository App, protected environment, dedicated Seal release -identity and all five npm trusted publishers are configured. Publication uses OIDC; -no npm access token is configured in this release workflow. - -## Release acceptance - -The identifiers below record the completed shipping acceptance without carrying -forward cancelled UI/tooling products. - -| Item | Deliverable | Observable exit | -| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| B13 — Candidate registry | Implemented: serve all five final-name/version tarballs from an isolated temporary registry; install without sibling overrides | Candidate digests and resolution failure probes are checked by the consumer gate; each run's reports record the Node/browser/type/CLI/vector/isolation results | -| B14 — Planner and publisher | Implemented: Changesets version intent, immutable release bundle and dependency-ordered retryable publisher | Release tests cover failure/retry and exact npm argv; CI exercises the pinned Seal Action and verifies the complete candidate bundle | -| B15 — Workflow chain | Implemented: separate version-PR and protected signing/publishing workflows, immutable artifact handoff and retry restoration | Tests cover provenance rejection, production signing, unchanged candidate bytes and resume; checksum-pinned actionlint validates workflows; account enablement completed | -| B16 — Registry acceptance | Completed: trusted publishers, protected Seal signing, alpha publication and fresh public-registry consumption | Registry integrity matches retained tarballs; exact published versions work outside this checkout without overrides; receipts record incomplete as well as complete channel state | - -B13's consumer gate feeds B14's final artifact proof; B15 wires that proof into -automation; B16 passed in the release linked above. Recheck current npm/GitHub -policy and supported tool versions when changing the flow. Account configuration -is operational state; this document does not establish it by itself. - -## Immutable candidates and release plan - -`pnpm release:version` runs Changesets after checking proposed versions against -observed npm history. It updates the lockfile and writes `release-intent.json` with -the five-library version snapshot and selected channel. Active alpha prerelease -mode selects `next`; exiting prerelease mode or ordinary versioning selects -`latest`. A `latest` intent and plan require stable versions for all five libraries. -The foundation changeset has been consumed. The first version PR, frozen reinstall -and public alpha publication have completed. - -Working decision, 2026-11-24: prepare a new stable release of the five libraries -through the existing version-PR and protected publication workflows. Committing -`changeset pre exit` requests the transition; the version workflow generates the -stable manifests, changelogs, lockfile and `latest` intent in a draft PR. Its merge -remains the publication boundary. The intended first stable versions are Identity -0.6.0, Armour 0.3.0, Ledger 0.2.0, Concord 0.3.0 and Seal 0.5.0, subject to the -version allocator's fresh registry collision and sequence checks. No local npm -credentials or separate dist-tag promotion workflow is required. - -After `pnpm check`, `pnpm release:plan` freezes the retained candidates and reports -under `artifacts/release/`. The source must be committed and reports must bind that -revision. A changed public version requires matching release intent. An unchanged -revision without intent produces an explicit no-op plan while retaining all five -candidates for proof verification. CI uses `verification-plan` to retain such a -no-op bundle before version allocation; that mode cannot infer publication intent -from changed versions. The strict production planner rejects that missing intent. - -CI invokes `samternent/seal-action` at -`d07a683a9195a1190c3e15b6e4374a1d59592b57`, using an explicit built CLI from the -checked revision. It signs `release-manifest.json` covering the final plan, reports -and unchanged tarballs plus captured verifier tools, and emits `release-proof.json` -and `release-public-key.json`. -The verification job uses a disposable test identity. These are CI test proofs; -production release eligibility requires a separately configured release public key. -Sign a clean bundle: remove the three disposable proof outputs before production -signing, preserving and rechecking the plan, reports and tarball bytes. -The Action's old npm package defaults are not used, and this does not imply a -registry-backed run of the new Seal package. - -The publisher requires Seal verification before reading or mutating npm state. -Verification binds the signer to the externally trusted key, checks the proof and -every file hash, rejects symbolic links and requires an exact manifest file set. -A bundled public key cannot establish its own trust. Keep receipts outside the -signed bundle so retries cannot silently alter the accepted artifacts. - -`pnpm release:publish` uses only retained tarball paths. After publication under a -release-specific candidate tag, it reuses the full consumer harness in fresh public -registry mode, without packing or sibling overrides. Only then may it promote the -channel bound into the signed plan: `next` for alpha releases or `latest` for stable -releases. The other channel is left unchanged. Journals bind their channel, and -compensating writes restore only that channel after a failed promotion. -The first B16 run verified this public-registry path before promoting `next`. - -Use Changesets for independent package version intent and sibling range changes. -Do not select versions from commit messages or reset existing npm names to a fresh -version sequence. Check actual registry state before allocating releases. Alpha -versions use the `next` channel; stable releases use `latest`. -The prerelease version and registry dist-tag are separate concepts. - -A planner discovers eligible public manifests, validates the committed version plan -and dependency graph, then records at least: - -- Source SHA, lockfile SHA-256, exact toolchain versions and target channel. -- Each package's name/version, safe relative tarball path, SHA-256 and sha512 SRI. -- Exact in-release sibling versions and dependency publication order. -- Gate-report digests, artifact retention/expiry and a deterministic release ID. - -Finalize the plan only after candidate and gate digests exist. Use RFC 8785 -serialization for the plan and its SHA-256 release ID. This is automation metadata, -not a reason to import Concord runtime cryptography. No credentials belong in the plan or report. - -The release flow must preserve the checked bytes: - -1. Check out the eligible version commit; use frozen setup and validate public - metadata, scripts, workspace ranges, exports and release intent. Run all required - source, type, behavior, build and consumer gates for that revision. -2. Build in dependency order and pack each public candidate once with pnpm's normal - workspace-range rewriting. Reject lifecycle hooks that rebuild or rewrite during - packing/publication. Compute digests and retain those exact tarballs. -3. Run strict publint and isolated-registry consumers against final names/versions. - External dependencies may resolve normally; in-release siblings must resolve only - to candidate bytes, with missing candidates/ranges failing. Retain reports and - prove tarball digests remain unchanged. -4. Upload the finalized plan, reports and candidates under source SHA/release ID. - The publisher accepts only artifacts from the eligible same-SHA run and verifies - provenance and every digest. A pull-request artifact cannot authorize main release. -5. Query npm before publishing each dependency-ordered package. Absent versions may - receive the exact retained tarball; identical existing integrity is already done; - different integrity is `VERSION_COLLISION` and blocks dependent publication. -6. Use a per-release candidate tag, bounded registry propagation retries and a fresh - registry consumer check. Move intended `next`/`latest` tags only after the whole - set passes. Record prior/target tags, each result and final release receipts. - -Invoke publication with validated argv and the retained tarball path, never shell -interpolation of manifest text or a recursive publish command that repacks. A new -version without a valid plan fails; a validated run with no new public version is -an explicit no-op. Tags document successful publication rather than triggering a -second publisher. - -## Failure and retry contract - -An npm release set is not atomic. Journal each package's expected/observed integrity, -source SHA, release ID, attempt and state. A partial outage resumes the same artifacts, -skips identical completed versions and continues in dependency order. Never invent a -version or rebuild under an old digest to bypass a failed publish. If retained bytes -expire, create a new verified run/plan and compare any existing registry integrity. - -Registry/CDN visibility can lag a successful publish. The publisher checks integrity -up to ten times, using exponential backoff capped at 60 seconds per wait (about five -minutes of backoff per package, plus query time). It never republishes during that -wait. Exhaustion retains an incomplete receipt and blocks dependents and promotion; -a later retry rechecks remote integrity. Channel writes use the same bounded -visibility checks. Rollback issues a compensating write even if cached reads still -show the old value; it never treats that stale observation alone as restoration. -The protected job has a 45-minute global cap, including waits and fresh consumers. - -Dist-tag promotion is also non-atomic. Record partial promotion and restore prior -values where permitted, reporting any remaining state. Alpha publication must not -change `latest`. npm unpublish is not a rollback mechanism. Do not mark a release -complete until all required packages and published consumers pass. - -Use structured diagnostics with phase, source SHA, release ID, package, retryability -and a useful exit status. Meaningful failures include missing/tampered artifacts, -invalid plans, collisions, unavailable registry, unconfigured package identity and -partial publication. Keep secrets out of diagnostics. Tests use saved responses and -argv-recording adapters before authorized live test-channel exercises. - -Every packed library must declare the public `ternent/core` Git repository, matching -npm's provenance source. The planner checks the packed manifest before any writes. -Failed npm writes retain the package selector and an allowlisted npm error code; -raw CLI output and error summaries stay out of logs and receipts because they can -contain credentials. - -## Workflow and account boundary - -There is one publisher, `release.yml`. Read-only `ci.yml` verifies every PR and -main push; `version.yml` uses a repository-scoped GitHub App to open a draft version -PR for unconsumed changesets. The App token lets that PR receive ordinary CI events. - -A successful main push verification triggers release selection. The selector checks -repository, event, branch, workflow identity, completion, main ancestry and a newly -changed five-library intent. Missing or unchanged intent is an explicit no-op. -PR evidence, failed runs and arbitrary dispatch refs are rejected. Manual dispatch -requires both the successful main-push verification run ID and its exact release ID. -An explicit dispatch may select an unchanged committed intent after a publisher-only -fix. It uses that new run's verified plan and retained tarballs, with the same source, -digest, collision and channel checks. Automatic runs still skip unchanged intent. -This permits infrastructure recovery without inventing new library versions. - -Selection binds one `core-evidence` artifact ID and GitHub SHA-256 archive digest. -The publisher checks that digest before extraction or execution, rejects unsafe ZIP -paths and excessive sizes, restores the captured built tools and checks the plan, -committed intent, lockfile, reports and tarball bytes against the producer SHA. -It does not rebuild or repack. The original disposable proof is checked before its -three sidecars are replaced; the production manifest additionally binds -`release-origin.json`. The pinned Seal Action signs with the dedicated release -identity, and verification uses the separately configured trusted public key. - -The release workflow's default SHA can be newer than the producer SHA. Checkout, -plan validation, published-consumer reports and npm provenance therefore use the -validated producer SHA. In particular, the npm child receives that SHA as -`GITHUB_SHA`; the workflow/invocation identity remains the actual release workflow. -No caller can supply an arbitrary SHA or registry. - -Publication runs on a GitHub-hosted Ubuntu runner in the `npm-release` environment, -with read-only contents/actions permissions plus `id-token: write`. npm 12.2.3 is -pinned for OIDC publication **and dist-tag management**. There is no npm token -fallback. The release identity secret is available only to its materialisation -step, checked against the expected public key, written outside artifacts with mode -0600 and removed after signing. Versioning has no npm or Seal identity. - -### One-time account setup - -Land the reviewed workflows on main before enabling them. Configure these exact -values; private material belongs in GitHub secrets, never repository files or chat. - -| Location | Name | Value or scope | -| ---------------------- | ------------------------------ | -------------------------------------------------------------------------------------- | -| Repository variable | `CORE_VERSION_APP_CLIENT_ID` | Client ID of a GitHub App installed only on `ternent/core` | -| Repository secret | `CORE_VERSION_APP_PRIVATE_KEY` | That App's private key; contents and pull requests write, metadata read | -| Repository variable | `CORE_VERSIONING_ENABLED` | `true` after App setup; enables draft version PRs | -| Repository environment | `npm-release` | Restrict deployment branches to main; any required reviewers are an owner policy | -| Environment variable | `SEAL_RELEASE_PUBLIC_KEY` | Raw public-key string from the dedicated release identity | -| Environment secret | `SEAL_RELEASE_IDENTITY_B64` | Base64 of the complete serialized release identity JSON, without line breaks | -| Repository variable | `CORE_RELEASE_ENABLED` | `true` only after all package trusted publishers and the signing environment are ready | - -Create and securely back up a dedicated Seal release identity with the reviewed -CLI. Derive its public-key artifact, configure the raw `publicKey` string separately, -and upload the base64 identity through the secret UI or `gh secret set` from a local -file. A release rejects a mismatched identity before signing. Do not reuse CI's -disposable identity or include private material in evidence. - -For **each** existing public package, configure npm trusted publishing: - -| npm field | Exact value | -| ----------------- | ------------------------------------------------------------ | -| Provider | GitHub Actions | -| Organisation/user | `ternent` | -| Repository | `core` | -| Workflow filename | `release.yml` | -| Environment | `npm-release` | -| Permissions | Enable direct publication and dist-tag management separately | - -All five names already exist on npm, so no new-package token bootstrap is needed. -An authenticated package owner configures their trusted publishers; all five are -configured for this flow. See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/). -The first `next` publication, registry integrity comparison, provenance inspection -and fresh published consumption passed in the release linked above. - -### Retry and retention - -The release concurrency group does not cancel a running publisher. GitHub does -not guarantee FIFO for pending runs; inspect skipped/cancelled pending runs and -dispatch the intended eligible release explicitly when needed. Collision and -channel-downgrade checks still apply. - -After staging, success or failure retains `core-release--attempt-` -for seven days. It contains the unchanged signed bundle and an outside publication -receipt when publishing started. Re-running the same workflow run automatically -restores its latest matching journal. For a separate manual retry, supply the same -verification run/release ID plus the prior release workflow's `resume_run_id`. -The handoff checks both workflows and artifacts, binds the prior journal to the -same release, verifies the production signature and never re-signs an already -published attempt. - -Artifact upload is best effort after a failure; abrupt runner loss can prevent a -receipt being retained. Do not claim atomic recovery or reconstruct prior channel -values from guesses. Inspect npm state and retained receipts before selecting a -recovery path. Expired or untrusted artifacts cannot authorize a retry. - -Once enabled, normal main events provide routine release authorization. Draft -version PRs remain deliberate owner actions; initial enablement has completed. Neither -merging an unrelated change nor pushing a tag creates new release intent. - -## Applications and deployment - -Applications/demos live outside core and have independent delivery graphs. The -historical [Cloudflare decision](../adr/0012-deploy-private-ui-apps-to-cloudflare-workers.md) -does not require a board, docs site, deployer or hosting account for the library -release. No core deployment workflow is active. - -When an application is implemented, keep its deployment identity separate from npm: -source SHA, exact bundle digest, environment and provider deployment/version receipt. -Deploy the verified artifact without rebuilding. Record resolved library versions and -digests without implying candidate versions are already published. Separate package -failure/retry from application deployment failure/rollback. - -Future static-app automation must verify assets, content types, missing-asset behavior, -routing and browser startup; retain the previous compatible artifact and smoke-tested -rollback result. Separate preview and production credentials; fork PRs receive checks -without secrets. Credential-bearing upload/cleanup jobs use trusted automation and -verified artifacts, never execute untrusted PR source. Isolate previews and synthetic -data, and keep host identity seeds out of bundles and environment variables. Provider -account/domain configuration and a real preview/deploy/rollback proof belong to that -application's implementation, not an implied library-release prerequisite. diff --git a/docs/engineering/repository-hygiene.md b/docs/engineering/repository-hygiene.md deleted file mode 100644 index 317987c..0000000 --- a/docs/engineering/repository-hygiene.md +++ /dev/null @@ -1,164 +0,0 @@ -# Repository guide - -Current structure, 2026-11-21. [ADR 0020](../adr/0020-simplify-core-around-five-libraries.md) -records the simplification; [CONTRIBUTING.md](../../CONTRIBUTING.md) owns setup and -commands. This guide describes configured scope, not the outcome of an uncompleted -check or a published release. - -## Ownership - -The active workspace contains exactly five public ESM libraries: - -| Library | Owns | -| -------- | ------------------------------------------------------------------------------------------------------------ | -| Identity | Identity validation, seed custody, signatures, recovery and key conversion | -| Armour | age encryption/decryption and explicit payload codecs | -| Ledger | Common signed container, canonical bytes, IDs, signatures, staging, commits, verification and ordered replay | -| Concord | Command intents/previews, system authority and decryption, model replay and atomic publication above Ledger | -| Seal | Its independent proof/artifact/manifest formats and separate Node CLI | - -Ledger and Concord stage work in memory. Consumers own commit cadence, draft -persistence and recovery; there is no missing library persistence layer to ship. -[ADR 0019](../adr/0019-keep-draft-persistence-with-consumers.md) records that boundary. -Storage publication remains external under the -[storage contract](../concord/storage-boundary.md). - -`packages/` holds the products, `scripts/verify/` holds small repository checks, -and `docs/` holds contracts, vectors and decisions. `pnpm-workspace.yaml` is the -package inventory. Root formatting, lint and test discovery derive their package -scope from it; standard pnpm recursion builds dependencies before consumers. - -The portable tooling package, profile fixtures, handshake app and VitePress patch -are removed. Ordinary `vite.config.base.ts` and `tsconfig.base.json` share defaults; -explicit package configs own entry/output mappings and the Seal CLI environment. -Do not rebuild a general profile framework inside repository scripts. - -UI is outside the library release under [ADR 0017](../adr/0017-drop-ui-from-the-library-release.md). -Workspace is deferred until the libraries are stable and substantial demos exist. -Their excluded sources and existing edits remain outside active acceptance. -Applications and demos should consume published libraries from separate projects. - -## Toolchain and installation - -| Tool | Repository pin | Use | -| ------------ | ----------------------------------- | ----------------------------------------------------------------- | -| Node | 26.13.1 | Development and CI | -| pnpm | 12.21.0 | Frozen dependency installation and recursive builds | -| Vite+ | 1.7.0 | Library build, Oxfmt, typed Oxlint and behavior tests | -| TypeScript | `npm:@typescript/typescript6@6.0.2` | Explicit `tsc6` checks and declaration/compiler API compatibility | -| publint | 0.3.25 | Standard built-package and exact-tarball validation | -| Vue | 3.5.46 | Runtime in the temporary browser consumer | -| Playwright | 1.65.1 | Chromium execution against installed candidates | -| Verdaccio | 7.1.2 | Disposable local candidate registry with no uplinks | -| Changesets | 3.0.3 | Package version intent and changelogs | -| canonicalize | 5.1.0 | RFC 8785 release-plan serialization | -| semver | 7.8.6 | Candidate dependency and registry version checks | -| fflate | 0.8.3 | Digest-checked release artifact extraction | -| actionlint | 1.7.12 | Checksum-pinned GitHub workflow validation | - -Volar, vue-tsc, unplugin-vue and the Vue Vite plugin are no longer direct repository -dependencies or explicit requirements. Declaration tooling may still resolve Vue -typing peers transitively. -The browser proof uses `createApp`, `h`, a button and CSS; no SFC or docs build is a -release requirement. Product dependencies remain with the package that uses them. -Armour uses typage (`age-encryption`); native age is an independent test oracle. - -pnpm reads install policy from `pnpm-workspace.yaml`; `.npmrc` declares the registry. -The workspace explicitly permits esbuild's install script and records the reviewed -Vue release-age exceptions. The lockfile resolves transitive versions. Toolchain -updates need the same source and installed-consumer checks as other packaging changes. -No speed claim follows from switching tools without a measured comparison. - -## Acceptance boundaries - -`pnpm check` runs nine separate gates: project contract, read-only formatting, -recursive build, typed lint, root types, package types, library behavior, release -automation tests and packed consumers. -The small contract check enforces five-library membership, public ESM metadata, -required scripts and workspace dependency policy. Standard publint validates package -artifacts; it does not replace behavior, declaration or browser checks. - -The consumer harness packs each library once, records SHA-256, runs strict publint -on those bytes, and installs the candidates by name/version outside the workspace -from a disposable loopback registry, without sibling overrides. It exercises Node -22.18, Node 24.21 and the development runtime; CI requires the compatibility -executables explicitly. It retains fixed crypto -vectors, public declarations and intended compiler failures, CLI behavior, protocol -and library import isolation, Armour codecs, Ledger lifecycle, Concord groups/drafts/ -storage and Seal proof/artifact behavior. A temporary plain Vite+ Vue production -build executes those browser proofs in Chromium and checks CSS/interaction. -Deliberately failing lint, format and behavior inputs check useful failure propagation. - -The candidate registry cannot proxy `@ternent/*` to published predecessors. Missing -candidates and incompatible transitive sibling ranges must fail resolution, and -installed candidate integrity is checked against the retained tarballs. Real public -registry publication and fresh published consumption remain on the -[release backlog](release-and-deployment.md#release-backlog). -Reports are `artifacts/check.json`, `artifacts/consumers.json`, -`artifacts/browser.png`, registry logs and retained candidate tarballs. They describe their own run; -older test counts, builds or remote CI results do not certify newer edits. - -Reports record their source revision. `scripts/release/` freezes the accepted -candidates into a digest-bound plan, verifies the Seal-signed file set, and provides -a retryable publisher. CI exercises the pinned Seal Action over the candidate bundle -with a disposable identity, retaining `artifacts/release/`. That proof establishes -test integration; production release trust uses a separately configured public key. - -## Replay performance follow-up - -Incremental replay is a candidate optimisation, not an implemented API or a change -to the trust model. The original Ledger offered `replay(from, to)`; current Ledger -offers `replay({ includeStaged })` and current Concord offers `replay()`. A cursor -alone does not reconstruct the state preceding it. - -A locally trusted cache could retain the projection at a verified committed head -and apply only a validated descendant suffix. It must bind the document, head, -model/system implementations, reader/key availability and replay coverage. Concord -also needs the authority, membership and epoch/key state required to interpret the -suffix; a projection and entry index alone are insufficient. Draft previews never -serve as verified committed checkpoints. - -Important invalidation cases: - -- A branch change requires a compatible ancestor checkpoint or full replay; an - entry count or timestamp cannot identify the same verified prefix. -- Newly acquired historical keys can make previously locked entries readable. - Admission/readmission already has this behaviour. Rebuild the affected application - projection from a suitable earlier checkpoint or genesis rather than applying only - newly appended events. A changed reader/model/system also invalidates incompatible - cached state. -- A cache restored from untrusted storage is not trustworthy merely because it names - a valid head, carries a checksum or has a signature. Establish its provenance and - correctness under an explicit checkpoint policy or reconstruct from verified - history. Keep secret system/key state outside portable public snapshots. -- An incoming snapshot must agree with the trusted prefix. Reuse the verified prefix - itself or establish that agreement; never skip altered historical bytes based only - on the supplied head identifier. Validate new linkage/signatures and historical - authority before publishing any extended projection. - -Incremental application reduction alone does not remove repeated full-history -verification, decryption, serialisation and copying. Measure those costs separately -on representative document sizes/commit patterns before choosing an implementation. -Full replay remains the correctness reference. Any optimisation must match it for -unchanged capabilities, and explicitly invalidate/rebuild when earlier readability -changes. No performance budget or persisted checkpoint format is established here. - -## Automation and retained documentation - -Read-only CI installs the frozen lockfile, pinned age reference and browser, -validates workflows with checksum-pinned actionlint, runs acceptance and retains -reports, tarballs and built release verifier tools. Third-party actions are pinned -to reviewed SHAs. Separate version-PR and protected signing/publishing workflows -are implemented behind explicit enablement variables. Account onboarding and real -registry acceptance remain; there is no enabled npm publisher or application deployer. -See the [release contract](release-and-deployment.md) for exact identities, setup and -retry behavior. Acceptance uses synthetic identities, saved registry responses and -recorded publication argv; it does not mutate the public registry. -Renovate is configured without automatic merging; the owner must enable it. - -Copied legacy implementations, the retired Utils product and obsolete publishers -were removed; Git retains their history. Current protocol, standard-profile, group, -storage and Seal format docs and fixed vectors remain authoritative. Dated migration, -tooling and review reports whose useful contracts are now represented there are -retired rather than retained as competing plans. The first-slice and independent-group -notes remain at their established paths with current ownership and evidence pointers. diff --git a/llms.txt b/llms.txt index 5672fb2..7676448 100644 --- a/llms.txt +++ b/llms.txt @@ -11,9 +11,7 @@ - [Armour](packages/armour/llms.txt): encrypt and decrypt bytes with age for identities, groups and passphrases. - [Seal](packages/seal/llms.txt): sign and verify a detached proof over any bytes' hash. -The active libraries are exactly the five above. Workspace and UI are outside this -release, and Utils is retired. Use the published -exports rather than historical workspace runtime/plugin examples. +The active libraries are exactly the five above. Use their published exports. ## Installation and source of truth diff --git a/packages/ui/CHANGELOG.md b/packages/ui/CHANGELOG.md deleted file mode 100644 index 233e6ee..0000000 --- a/packages/ui/CHANGELOG.md +++ /dev/null @@ -1,399 +0,0 @@ -# ternent-ui - -## 0.6.1 - -### Patch Changes - -- [`4aa5e00`](https://github.com/ternent/core/commit/4aa5e001cecf61cb702414be2e63209002a521ca) Thanks [@samternent](https://github.com/samternent)! - Update deploys - -## 0.6.0 - -### Minor Changes - -- [`70ecb82`](https://github.com/ternent/core/commit/70ecb824f0863dc1b4cb79b1eeeed0b93a45891d) Thanks [@samternent](https://github.com/samternent)! - add sidebar and workspace layout patterns to `@ternent/ui` - -## 0.5.7 - -### Patch Changes - -- [`a297fd0`](https://github.com/ternent/core/commit/a297fd06ec4f98262534b19f05c1e8722b016aa8) Thanks [@samternent](https://github.com/samternent)! - fix missed export - -## 0.5.6 - -### Patch Changes - -- [`f721f3a`](https://github.com/ternent/core/commit/f721f3af081f93b1e4b8f6d3f8f3e7a2f8ea8ea9) Thanks [@samternent](https://github.com/samternent)! - Adds identity patterns - -## 0.5.5 - -### Patch Changes - -- Fix package file - -## 0.5.4 - -### Patch Changes - -- [`9e4db22`](https://github.com/ternent/core/commit/9e4db2281ba076ae3c20db6d42944c3aff786b91) Thanks [@samternent](https://github.com/samternent)! - Debug action - -## 0.5.3 - -### Patch Changes - -- [`c07a829`](https://github.com/ternent/core/commit/c07a8296d3316099e6cfce2955b9a8289e342c33) Thanks [@samternent](https://github.com/samternent)! - Fix css exports and deploy file - -## 0.5.2 - -### Patch Changes - -- [`6e35115`](https://github.com/ternent/core/commit/6e35115fd8b7225292d9666da5f26184786b5785) Thanks [@samternent](https://github.com/samternent)! - Updates deploy action - -## 0.5.1 - -### Patch Changes - -- [`9c434fd`](https://github.com/ternent/core/commit/9c434fd7f880bb9fa6400adbefdc1cc28e72461c) Thanks [@samternent](https://github.com/samternent)! - Update export css names - -## 0.5.0 - -### Minor Changes - -- [`20732cf`](https://github.com/ternent/core/commit/20732cf77acd279e07fa3f7601ea9c02f1e85564) Thanks [@samternent](https://github.com/samternent)! - Move @ternent/ui - -## 0.4.15 - -### Patch Changes - -- [`f1499a5ba7980ae9d33fed6bcdb710f7b398f1c3`](https://github.com/samternent/home/commit/f1499a5ba7980ae9d33fed6bcdb710f7b398f1c3) Thanks [@samternent](https://github.com/samternent)! - Overhaul landing page - -## 0.4.14 - -### Patch Changes - -- [`9141d333ba1f6da7295f55661fcaa309c14af4e6`](https://github.com/samternent/home/commit/9141d333ba1f6da7295f55661fcaa309c14af4e6) Thanks [@samternent](https://github.com/samternent)! - Update loading states - -## 0.4.13 - -### Patch Changes - -- [`13540fde40ad2158e5c873f539fdecb4160c48d8`](https://github.com/samternent/home/commit/13540fde40ad2158e5c873f539fdecb4160c48d8) Thanks [@samternent](https://github.com/samternent)! - Update layout and copy - -## 0.4.12 - -### Patch Changes - -- [`a7c7e3c9f61300396fb11caf364d10e721b078ec`](https://github.com/samternent/home/commit/a7c7e3c9f61300396fb11caf364d10e721b078ec) Thanks [@samternent](https://github.com/samternent)! - Update seal theme and concord copy - -## 0.4.11 - -### Patch Changes - -- [`69de6bfe65a37ac88be939a00b82480f5f62334f`](https://github.com/samternent/home/commit/69de6bfe65a37ac88be939a00b82480f5f62334f) Thanks [@samternent](https://github.com/samternent)! - Fix footer and theme toggle - -## 0.4.10 - -### Patch Changes - -- [`cd973e5413f67670371efe25835c3b5cabe63edb`](https://github.com/samternent/home/commit/cd973e5413f67670371efe25835c3b5cabe63edb) Thanks [@samternent](https://github.com/samternent)! - Cocnord theme - -## 0.4.9 - -### Patch Changes - -- [`92050833da54cacbd6fe33349d9b8fb66754d82c`](https://github.com/samternent/home/commit/92050833da54cacbd6fe33349d9b8fb66754d82c) Thanks [@samternent](https://github.com/samternent)! - Concord library migration - -## 0.4.8 - -### Patch Changes - -- [`f52fa81d8adac2176f0578a01a3486e787d43083`](https://github.com/samternent/home/commit/f52fa81d8adac2176f0578a01a3486e787d43083) Thanks [@samternent](https://github.com/samternent)! - Update teh landing page on seal - -## 0.4.7 - -### Patch Changes - -- [`e694239710abbe9ab15bd386901f34334f7692e5`](https://github.com/samternent/home/commit/e694239710abbe9ab15bd386901f34334f7692e5) Thanks [@samternent](https://github.com/samternent)! - code deletion and renaming - -## 0.4.6 - -### Patch Changes - -- [`0d44f4eb18ec74b394018a709d0dc78c9e1fd520`](https://github.com/samternent/home/commit/0d44f4eb18ec74b394018a709d0dc78c9e1fd520) Thanks [@samternent](https://github.com/samternent)! - consuming template updates - -## 0.4.5 - -### Patch Changes - -- [`3016b41acffdf9664b01afd9f32f76f3b2880303`](https://github.com/samternent/home/commit/3016b41acffdf9664b01afd9f32f76f3b2880303) Thanks [@samternent](https://github.com/samternent)! - Updates definition blocks - -- [`80c1a8e095299c23af67358ddcc074a431d079b8`](https://github.com/samternent/home/commit/80c1a8e095299c23af67358ddcc074a431d079b8) Thanks [@samternent](https://github.com/samternent)! - Update to use template - -## 0.4.4 - -### Patch Changes - -- [`6845ce703aa2fb677b74786de02ce1d22ec98aa9`](https://github.com/samternent/home/commit/6845ce703aa2fb677b74786de02ce1d22ec98aa9) Thanks [@samternent](https://github.com/samternent)! - Updates verification - -## 0.4.3 - -### Patch Changes - -- [`346a6cf11407bb3e94bf1e553683769d50112616`](https://github.com/samternent/home/commit/346a6cf11407bb3e94bf1e553683769d50112616) Thanks [@samternent](https://github.com/samternent)! - Updates it to seal - -## 0.4.2 - -### Patch Changes - -- [`8427fb06e4ee9a14197e89dc34d26b6894654eaf`](https://github.com/samternent/home/commit/8427fb06e4ee9a14197e89dc34d26b6894654eaf) Thanks [@samternent](https://github.com/samternent)! - UUpdate landing - -## 0.4.1 - -### Patch Changes - -- [`a9b21ff9ca09718b824ef6e665e1d79d29fdeb69`](https://github.com/samternent/home/commit/a9b21ff9ca09718b824ef6e665e1d79d29fdeb69) Thanks [@samternent](https://github.com/samternent)! - Adfds action and slight tweak - -## 0.4.0 - -### Minor Changes - -- [#508](https://github.com/samternent/home/pull/508) [`b35c163b4c4d3c084591ca8512b2d43083eb40ce`](https://github.com/samternent/home/commit/b35c163b4c4d3c084591ca8512b2d43083eb40ce) Thanks [@samternent](https://github.com/samternent)! - Add shared UI primitives (`SDisclosure`, `SRadioGroup`, `STextarea`) and align proof app usage with `ternent-ui`. - - Add `hashBytes` utility for deterministic raw-byte hashing in browser signing/verification flows. - -## 0.3.5 - -### Patch Changes - -- [`de32160374bb34fb3968b4c755c52dc6c1fe8e3f`](https://github.com/samternent/home/commit/de32160374bb34fb3968b4c755c52dc6c1fe8e3f) Thanks [@samternent](https://github.com/samternent)! - some styles and theme - -## 0.3.4 - -### Patch Changes - -- [`05930613e323b1a121bcadc1afc458b81100d9c0`](https://github.com/samternent/home/commit/05930613e323b1a121bcadc1afc458b81100d9c0) Thanks [@samternent](https://github.com/samternent)! - Partial permissions and 404 - -## 0.3.3 - -### Patch Changes - -- [`f32fc4ad99cdc4966b66956b4665ceba1d485698`](https://github.com/samternent/home/commit/f32fc4ad99cdc4966b66956b4665ceba1d485698) Thanks [@samternent](https://github.com/samternent)! - Update whitepaper - -## 0.3.2 - -### Patch Changes - -- [#396](https://github.com/samternent/home/pull/396) [`9d0a9664d6d2e71fd9f31540d52fd3dc98c54307`](https://github.com/samternent/home/commit/9d0a9664d6d2e71fd9f31540d52fd3dc98c54307) Thanks [@samternent](https://github.com/samternent)! - Consolidate styles - -## 0.3.1 - -### Patch Changes - -- [`636f8a0491193a83166a2dd796cc351c57fe5cc5`](https://github.com/samternent/home/commit/636f8a0491193a83166a2dd796cc351c57fe5cc5) Thanks [@samternent](https://github.com/samternent)! - Fix some copy and vercel config - -## 0.3.0 - -### Minor Changes - -- [`d8807ea4a3c40f2d58e4c9784c2374088b9dc745`](https://github.com/samternent/home/commit/d8807ea4a3c40f2d58e4c9784c2374088b9dc745) Thanks [@samternent](https://github.com/samternent)! - Complete rework of the app. AI driven - -## 0.1.18 - -### Patch Changes - -- [`ffbadc602da814226cf74dc7a8667b8770ac3f2b`](https://github.com/samternent/home/commit/ffbadc602da814226cf74dc7a8667b8770ac3f2b) Thanks [@samternent](https://github.com/samternent)! - Adds a bit more from the other day - -## 0.1.17 - -### Patch Changes - -- [`078d2f8585fed6fa13f587217c5cfbaa45357793`](https://github.com/samternent/home/commit/078d2f8585fed6fa13f587217c5cfbaa45357793) Thanks [@samternent](https://github.com/samternent)! - Remove proof of work, update some tabs and add new routes - -## 0.1.16 - -### Patch Changes - -- [`5a88278372830d5f24e7fcc12cf430560f93ad13`](https://github.com/samternent/home/commit/5a88278372830d5f24e7fcc12cf430560f93ad13) Thanks [@samternent](https://github.com/samternent)! - Updates ledger and tabs - -## 0.1.15 - -### Patch Changes - -- [#375](https://github.com/samternent/home/pull/375) [`4dbe5c228213d174b670a3faf544b89c51eb4e71`](https://github.com/samternent/home/commit/4dbe5c228213d174b670a3faf544b89c51eb4e71) Thanks [@samternent](https://github.com/samternent)! - Updates SResizers - -- [#375](https://github.com/samternent/home/pull/375) [`906c84e95a7b82f6e124ba04a680990c3b1df14a`](https://github.com/samternent/home/commit/906c84e95a7b82f6e124ba04a680990c3b1df14a) Thanks [@samternent](https://github.com/samternent)! - Adds new themes - -## 0.1.14 - -### Patch Changes - -- [`edb639cff3654fdd3250f48ef05350154ab09ca0`](https://github.com/samternent/home/commit/edb639cff3654fdd3250f48ef05350154ab09ca0) Thanks [@samternent](https://github.com/samternent)! - A few more nice tweaks - -## 0.1.13 - -### Patch Changes - -- [`30e4e7b9752544c3ff8deb7b1453618101cfadfc`](https://github.com/samternent/home/commit/30e4e7b9752544c3ff8deb7b1453618101cfadfc) Thanks [@samternent](https://github.com/samternent)! - Some menu and repsonsive tweaks - -## 0.1.12 - -### Patch Changes - -- [`39e4521fa018b7706ac00b8d1dd8fb3eebf63395`](https://github.com/samternent/home/commit/39e4521fa018b7706ac00b8d1dd8fb3eebf63395) Thanks [@samternent](https://github.com/samternent)! - Theme and layout changes - -## 0.1.11 - -### Patch Changes - -- 98ce971: Updates many styles - -## 0.1.10 - -### Patch Changes - -- [`a301948d8d49e1d6ec2a2448578c1479bbba6644`](https://github.com/samternent/home/commit/a301948d8d49e1d6ec2a2448578c1479bbba6644) Thanks [@samternent](https://github.com/samternent)! - Remove unused code - -## 0.1.9 - -### Patch Changes - -- [`60286f07aaab9fd281e61c3f98260d3589e1eaf6`](https://github.com/samternent/home/commit/60286f07aaab9fd281e61c3f98260d3589e1eaf6) Thanks [@samternent](https://github.com/samternent)! - Updates ternentdotdev content - -## 0.1.8 - -### Patch Changes - -- [`b578f6f06c90fe327d8ff084764dafd7c6fd8ec9`](https://github.com/samternent/home/commit/b578f6f06c90fe327d8ff084764dafd7c6fd8ec9) Thanks [@samternent](https://github.com/samternent)! - Improve theming - -## 0.1.7 - -### Patch Changes - -- [`20cf93fc3e2fd25b7463cc5bd66e42d74413fc92`](https://github.com/samternent/home/commit/20cf93fc3e2fd25b7463cc5bd66e42d74413fc92) Thanks [@samternent](https://github.com/samternent)! - Adds themes and landing page - -## 0.1.6 - -### Patch Changes - -- [`0263ee49bbd5bcd82d4ddd142dbf0bd72294a48a`](https://github.com/samternent/home/commit/0263ee49bbd5bcd82d4ddd142dbf0bd72294a48a) Thanks [@samternent](https://github.com/samternent)! - Adds teamwork theme - -## 0.1.5 - -### Patch Changes - -- [`f8a222fb97d95038f940503d1bbd6427b4cfb0ee`](https://github.com/samternent/home/commit/f8a222fb97d95038f940503d1bbd6427b4cfb0ee) Thanks [@samternent](https://github.com/samternent)! - Update white label themes - -## 0.1.4 - -### Patch Changes - -- [`f4afb11f20f27b23599f45d83c7b7a3419afb1b7`](https://github.com/samternent/home/commit/f4afb11f20f27b23599f45d83c7b7a3419afb1b7) Thanks [@samternent](https://github.com/samternent)! - Adds basic whitelabling - -## 0.1.3 - -### Patch Changes - -- [`7435a4dc0feb608720f58c878c30635b809fd36e`](https://github.com/samternent/home/commit/7435a4dc0feb608720f58c878c30635b809fd36e) Thanks [@samternent](https://github.com/samternent)! - Update home p age feel - -## 0.1.2 - -### Patch Changes - -- [`0bc405a1277d88bf868980aa9b25eab044937715`](https://github.com/samternent/home/commit/0bc405a1277d88bf868980aa9b25eab044937715) Thanks [@samternent](https://github.com/samternent)! - Adds gamewek navigation - -## 0.1.1 - -### Patch Changes - -- [`4dbe84d678340adfec62721ca1aea8755d88717e`](https://github.com/samternent/home/commit/4dbe84d678340adfec62721ca1aea8755d88717e) Thanks [@samternent](https://github.com/samternent)! - Adjust small font sizes and player links - -## 0.1.0 - -### Minor Changes - -- [`1f3ad0d2b7052f3b8359e94f1edb20ef4b40c73a`](https://github.com/samternent/home/commit/1f3ad0d2b7052f3b8359e94f1edb20ef4b40c73a) Thanks [@samternent](https://github.com/samternent)! - Remove 401 block - -## 0.0.14 - -### Patch Changes - -- [`e9b74d04d15b0bf4f74c47f58ec7558e9a86e991`](https://github.com/samternent/home/commit/e9b74d04d15b0bf4f74c47f58ec7558e9a86e991) Thanks [@samternent](https://github.com/samternent)! - Add new font and style sizes - -## 0.0.13 - -### Patch Changes - -- [`299229c0af7dc84f698062c48a1d8e24bb721ae1`](https://github.com/samternent/home/commit/299229c0af7dc84f698062c48a1d8e24bb721ae1) Thanks [@samternent](https://github.com/samternent)! - Minor component and theme tweaks - -## 0.0.12 - -### Patch Changes - -- [`ba650644b361ca55b8b46cceb550bc384e997433`](https://github.com/samternent/home/commit/ba650644b361ca55b8b46cceb550bc384e997433) Thanks [@samternent](https://github.com/samternent)! - Adds base varient to tabs - -## 0.0.11 - -### Patch Changes - -- [`f80141b83a9cc857d0a9c7e7bccaac9b0fd04d70`](https://github.com/samternent/home/commit/f80141b83a9cc857d0a9c7e7bccaac9b0fd04d70) Thanks [@samternent](https://github.com/samternent)! - Adds greener theme - -## 0.0.10 - -### Patch Changes - -- [`765c387249dbd62441490a5083b8d4d30af46369`](https://github.com/samternent/home/commit/765c387249dbd62441490a5083b8d4d30af46369) Thanks [@samternent](https://github.com/samternent)! - Adds concords themes - -## 0.0.9 - -### Patch Changes - -- [`d464a231ac93035bd252e67d1f278d1fb59f9e09`](https://github.com/samternent/home/commit/d464a231ac93035bd252e67d1f278d1fb59f9e09) Thanks [@samternent](https://github.com/samternent)! - Update ternentdotdev theme and some styles - -## 0.0.8 - -### Patch Changes - -- [`383c709f107fc869a19430a9565f2b84c8ddc9cf`](https://github.com/samternent/home/commit/383c709f107fc869a19430a9565f2b84c8ddc9cf) Thanks [@samternent](https://github.com/samternent)! - Adds game - -## 0.0.7 - -### Patch Changes - -- [`bb82d84026eb26dfc8e048e5d35d2bebb918c664`](https://github.com/samternent/home/commit/bb82d84026eb26dfc8e048e5d35d2bebb918c664) Thanks [@samternent](https://github.com/samternent)! - Update theme and home page - -## 0.0.6 - -### Patch Changes - -- [`dfb7156622931290d861583139e0d16b8711fdc1`](https://github.com/samternent/home/commit/dfb7156622931290d861583139e0d16b8711fdc1) Thanks [@samternent](https://github.com/samternent)! - Remove content and tweak tabs - -## 0.0.5 - -### Patch Changes - -- [`9dcad6a68edb8012b34dfc30d2f652114db085d4`](https://github.com/samternent/home/commit/9dcad6a68edb8012b34dfc30d2f652114db085d4) Thanks [@samternent](https://github.com/samternent)! - Updates responsiveness of things - -## 0.0.4 - -### Patch Changes - -- [`f8abac1f83db402de41970b39677d0c045a210c0`](https://github.com/samternent/home/commit/f8abac1f83db402de41970b39677d0c045a210c0) Thanks [@samternent](https://github.com/samternent)! - Close nav on navigate - -## 0.0.3 - -### Patch Changes - -- [`2393ddcb514083518aac92c9de0cbc4c4518048b`](https://github.com/samternent/home/commit/2393ddcb514083518aac92c9de0cbc4c4518048b) Thanks [@samternent](https://github.com/samternent)! - Adds breakpoints to nav - -- [`df81b8fd87ae1e906c9da463d1d2fe37610eb1c7`](https://github.com/samternent/home/commit/df81b8fd87ae1e906c9da463d1d2fe37610eb1c7) Thanks [@samternent](https://github.com/samternent)! - Update UI nav - -## 0.0.2 - -### Patch Changes - -- [`0d7ddc5753740017962335661e9a169093edebb4`](https://github.com/samternent/home/commit/0d7ddc5753740017962335661e9a169093edebb4) Thanks [@samternent](https://github.com/samternent)! - Testing package bump - -## 0.0.1 - -### Patch Changes - -- [`e6bbb9f04034a9510b06c8b992937379221587db`](https://github.com/samternent/home/commit/e6bbb9f04034a9510b06c8b992937379221587db) Thanks [@samternent](https://github.com/samternent)! - Expose ternent-ui diff --git a/packages/ui/README.md b/packages/ui/README.md deleted file mode 100644 index b9adb32..0000000 --- a/packages/ui/README.md +++ /dev/null @@ -1,57 +0,0 @@ -# ternent-ui drop-in AI pack - -This pack is designed to be copied directly into the `ternent-ui` package root. - -## What this gives you - -- a clear v2 architecture for `src/primitives` -- strict AI governance docs -- token and theming rules -- primitive and accessibility rules -- a pattern boundary so product UI does not leak into the core -- ready-to-paste prompts for Codex or similar agents -- templates for component specs and PR review -- a concrete phased roadmap - -## Assumptions this pack makes - -- `src/components/S*` is legacy and should be frozen except for urgent maintenance -- `src/primitives/*` is the future design-system source of truth -- Tailwind is retained as the styling implementation layer -- Ark UI is used selectively for interactive/a11y-heavy primitives -- multiple branded themes remain a first-class requirement - -## Suggested first move - -1. Copy the contents of this pack into the `ternent-ui` repo. -2. Commit the docs before any major refactor so AI has a stable contract. -3. Start Codex with `ai/prompts/00-master-system-prompt.md`. -4. Then run the prompts in order. - -## Suggested placement - -- `src/design-system/docs/*` should live exactly where provided. -- `ai/prompts/*` and `ai/templates/*` can live at package root or be moved under `.ai/` if you prefer. -- `plans/*` can stay at package root or be copied into your internal docs area. - -## Recommended execution order - -1. `ai/prompts/00-master-system-prompt.md` -2. `ai/prompts/01-bootstrap-docs.md` -3. `ai/prompts/02-button-hardening.md` -4. `ai/prompts/03-form-primitives.md` -5. `ai/prompts/04-choice-controls.md` -6. `ai/prompts/05-dialog-and-overlays.md` -7. `ai/prompts/06-navigation-and-disclosure.md` - -## Grounding notes for this repo - -This pack was written to match the current shape of `ternent-ui` as shared: - -- legacy `src/components/S*.vue` -- new `src/primitives/Button/*` -- token css under `src/design-system/tokens.css` -- multi-theme setup under `src/themes/*` -- existing token names like `--ui-bg`, `--ui-fg`, `--ui-surface`, `--ui-primary`, `--ui-critical`, `--ui-ring` - -The docs intentionally allow a staged migration rather than forcing an immediate token rename. diff --git a/packages/ui/jsconfig.json b/packages/ui/jsconfig.json deleted file mode 100644 index 48a3ace..0000000 --- a/packages/ui/jsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "target": "esnext", - "useDefineForClassFields": true, - "module": "esnext", - "moduleResolution": "node", - "strict": true, - "jsx": "preserve", - "sourceMap": true, - "resolveJsonModule": true, - "esModuleInterop": true, - "lib": ["esnext", "dom"], - "baseUrl": ".", - "paths": { - "@/*": ["src/*"] - } - }, - "exclude": ["**/node_modules/**/*", "**/dist/**/*"] -} diff --git a/packages/ui/package.json b/packages/ui/package.json deleted file mode 100644 index 9251f93..0000000 --- a/packages/ui/package.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "name": "@ternent/ui", - "version": "0.6.1", - "description": "A collection of Vue components and themes for ternent applications", - "repository": { - "type": "git", - "url": "git+https://github.com/ternent/core.git", - "directory": "packages/ui" - }, - "type": "module", - "main": "./dist/components.js", - "exports": { - ".": "./dist/components.js", - "./primitives": "./dist/primitives.js", - "./patterns": "./dist/patterns.js", - "./styles.css": "./dist/ui.css", - "./themes/print.css": "./src/themes/print.css", - "./themes/neon-noir.css": "./src/themes/neon-noir.css", - "./themes/spruce-ink.css": "./src/themes/spruce-ink.css", - "./themes/citrine-ash.css": "./src/themes/citrine-ash.css", - "./themes/harbor-rose.css": "./src/themes/harbor-rose.css", - "./themes/obsidian-iris.css": "./src/themes/obsidian-iris.css", - "./themes/pixpax.css": "./src/themes/pixpax.css", - "./themes/proof.css": "./src/themes/proof.css", - "./themes/concord.css": "./src/themes/concord.css", - "./themes/ledger.css": "./src/themes/ledger.css", - "./themes/garnet-honey.css": "./src/themes/garnet-honey.css", - "./themes/prism.css": "./src/themes/prism.css", - "./themes/sunset.css": "./src/themes/sunset.css", - "./themes/armour.css": "./src/themes/armour.css", - "./themes/aurora.css": "./src/themes/aurora.css", - "./tailwind.config": "./tailwind.config.js" - }, - "scripts": { - "build": "node ./scripts/generate-theme-css.mjs && vite build", - "dev": "vite build --watch", - "generate:themes": "node ./scripts/generate-theme-css.mjs", - "serve": "http-server ./dist -p 5001 --cors='*'", - "lint:tokens": "node ./scripts/check-tokens.js", - "test": "pnpm exec vitest run" - }, - "dependencies": { - "@ark-ui/vue": "^5.30.0", - "@tailwindcss/typography": "^0.5.14", - "@tailwindcss/vite": "^4.1.18", - "@vueuse/core": "^10.11.1", - "autoprefixer": "^10.4.20", - "luxon": "^3.5.0", - "tailwind-merge": "^1.14.0", - "tailwindcss": "^4.1.18", - "tailwindcss-animate": "^1.0.7", - "vite-plugin-dts": "^1.7.3", - "vue": "^3.4.38" - }, - "devDependencies": { - "@originjs/vite-plugin-federation": "^1.3.5", - "@vitejs/plugin-vue": "^4.6.2", - "@vue/test-utils": "^2.4.6", - "http-server": "^14.1.1", - "jsdom": "^24.1.1", - "vite": "^7.3.0", - "vitest": "^1.6.0" - } -} diff --git a/packages/ui/scripts/check-tokens.js b/packages/ui/scripts/check-tokens.js deleted file mode 100644 index 38dd621..0000000 --- a/packages/ui/scripts/check-tokens.js +++ /dev/null @@ -1,56 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); - -const componentsDir = path.resolve(__dirname, "../src/components"); -const styleFile = path.resolve(__dirname, "../src/style.css"); - -/** - * Recursively collect files matching the given extensions. - */ -const collectFiles = (dir, extensions) => { - const entries = fs.readdirSync(dir, { withFileTypes: true }); - return entries.flatMap((entry) => { - const fullPath = path.join(dir, entry.name); - if (entry.isDirectory()) return collectFiles(fullPath, extensions); - return extensions.some((ext) => entry.name.endsWith(ext)) ? [fullPath] : []; - }); -}; - -const filesToCheck = [...collectFiles(componentsDir, [".vue", ".js", ".ts"]), styleFile]; - -const arbitraryValuePattern = /\[[^\]]*?\d+(?:\.\d+)?(?:px|rem)[^\]]*?\]/g; -const hardCodedUnitPattern = /\b\d+(?:\.\d+)?(?:px|rem)\b/g; - -const issues = []; - -for (const file of filesToCheck) { - const content = fs.readFileSync(file, "utf8"); - - const arbitraryMatches = content.match(arbitraryValuePattern) || []; - if (arbitraryMatches.length) { - issues.push({ file, matches: arbitraryMatches, reason: "arbitrary values" }); - } - - if (file.endsWith(".css")) { - const unitMatches = (content.match(hardCodedUnitPattern) || []).filter( - (match) => parseFloat(match) !== 0, - ); - if (unitMatches.length) { - issues.push({ file, matches: unitMatches, reason: "hardcoded CSS units" }); - } - } -} - -if (issues.length) { - console.error("Found hardcoded values that should map to design tokens:"); - for (const { file, matches, reason } of issues) { - console.error(`- ${file} (${reason}): ${[...new Set(matches)].join(", ")}`); - } - process.exit(1); -} - -console.log("Token lint passed: no hardcoded px/rem values detected."); diff --git a/packages/ui/scripts/generate-theme-css.mjs b/packages/ui/scripts/generate-theme-css.mjs deleted file mode 100644 index b3ae3b0..0000000 --- a/packages/ui/scripts/generate-theme-css.mjs +++ /dev/null @@ -1,85 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; -import { namedSemanticThemes, rootSemanticThemes } from "../src/themes/semanticThemeContract.js"; - -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); - -const rootDir = path.resolve(__dirname, ".."); -const tokensCssPath = path.join(rootDir, "src/design-system/tokens.css"); -const themesDir = path.join(rootDir, "src/themes"); - -const generatedHeader = "/* This file is generated from src/themes/semanticThemeContract.js. */"; - -const singletonThemeSelectors = { - "neon-noir": { - dark: "neon-noir", - }, - proof: { - dark: "proof-dark", - }, -}; - -function renderDeclaration([property, value], indent = " ") { - const normalizedValue = String(value) - .trim() - .replace(/[;,]+\s*$/, ""); - return `${indent}${property}: ${normalizedValue};`; -} - -function renderRule(selector, declarations, indent = "") { - const lines = [`${indent}${selector} {`]; - for (const entry of Object.entries(declarations)) { - lines.push(renderDeclaration(entry, `${indent} `)); - } - lines.push(`${indent}}`); - return lines.join("\n"); -} - -function renderRootCss() { - const lightRule = renderRule(":root", rootSemanticThemes.light); - const darkRule = renderRule(":root", rootSemanticThemes.dark, " "); - - return [ - generatedHeader, - "", - lightRule, - "", - "@media (prefers-color-scheme: dark) {", - darkRule, - "}", - "", - ].join("\n"); -} - -function getThemeSelector(themeName, mode) { - const singletonSelector = singletonThemeSelectors[themeName]?.[mode]; - if (singletonSelector) { - return `:root[data-theme="${singletonSelector}"], [data-theme="${singletonSelector}"]`; - } - - const selector = `${themeName}-${mode}`; - return `:root[data-theme="${selector}"], [data-theme="${selector}"]`; -} - -function renderThemeCss(themeName, variants) { - const sections = [generatedHeader, ""]; - - for (const mode of ["light", "dark"]) { - if (!variants[mode]) continue; - sections.push(renderRule(getThemeSelector(themeName, mode), variants[mode])); - sections.push(""); - } - - return sections.join("\n"); -} - -fs.writeFileSync(tokensCssPath, renderRootCss()); - -for (const [themeName, variants] of Object.entries(namedSemanticThemes)) { - const filePath = path.join(themesDir, `${themeName}.css`); - fs.writeFileSync(filePath, renderThemeCss(themeName, variants)); -} - -console.log("Generated semantic theme CSS."); diff --git a/packages/ui/src/design-system/base.css b/packages/ui/src/design-system/base.css deleted file mode 100644 index 1fa5d80..0000000 --- a/packages/ui/src/design-system/base.css +++ /dev/null @@ -1,8 +0,0 @@ -:root { - color-scheme: light dark; -} - -:focus-visible { - outline: 2px solid var(--ui-ring); - outline-offset: 2px; -} diff --git a/packages/ui/src/design-system/docs/ACCESSIBILITY_RULES.md b/packages/ui/src/design-system/docs/ACCESSIBILITY_RULES.md deleted file mode 100644 index 041b3bf..0000000 --- a/packages/ui/src/design-system/docs/ACCESSIBILITY_RULES.md +++ /dev/null @@ -1,186 +0,0 @@ -# ACCESSIBILITY_RULES - -## Goal - -Accessibility is a built-in requirement of the design system, not a later enhancement. -AI must treat accessibility as part of the primitive contract. - -## Current repo baseline - -The accessibility contract is ahead of the current primitive implementation. - -- `Button` established the baseline for focus treatment in the current v2 primitive layer. -- `Accordion` is the canonical disclosure primitive in `src/primitives`, and several Ark-backed accessibility patterns also exist in legacy `src/components/S*` files as behavior reference only. -- Some existing primitives such as `SplitButton` predate the full contract in this document. -- Primitive `*.spec.md` files now exist for the active v2 surface, so future interactive primitive work must update them rather than assume documentation can lag behind behavior. - -## Core principles - -1. keyboard access must work without mouse interaction -2. focus visibility must be present and consistent -3. semantics must match the component role -4. ARIA must be correct, not decorative -5. disabled and invalid states must remain understandable -6. stateful behavior must be operable and perceivable - -## Focus treatment - -All interactive primitives must implement a consistent focus-visible style using system tokens. - -Preferred pattern based on current repo tokens: - -- `focus-visible:outline-none` -- `focus-visible:ring-2` -- `focus-visible:ring-[var(--ui-ring)]` - -The exact ring width may vary if the system later defines a dedicated token, but the treatment must remain consistent across primitives. - -## Native elements first - -Use native semantics whenever practical. - -Examples: - -- use `