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/.changeset/minimal-core.md b/.changeset/minimal-core.md new file mode 100644 index 0000000..c866959 --- /dev/null +++ b/.changeset/minimal-core.md @@ -0,0 +1,28 @@ +--- +"@ternent/identity": minor +"@ternent/seal": minor +"@ternent/armour": minor +"@ternent/ledger": minor +"@ternent/concord": minor +--- + +Replace the five libraries with smaller public interfaces. These are breaking changes +to the pre-1.0 APIs; applications must migrate before upgrading. + +- Identity provides identity creation, backup, recovery, exact-byte signing and strict + verification. The version 2 backup and mnemonic derivation path are preserved. +- Seal provides detached content-hash proofs. The CLI, artifacts and manifests are removed. +- Armour encrypts and decrypts bytes with identities, native age keys or a passphrase. + Input bytes, including Node Buffers, are copied when each call starts. +- Ledger uses canonical version 2 histories with a Seal proof per commit. Authoring is + staged, histories are immutable, and comparison never merges diverged copies. +- Concord reconstructs one application state from readable signed events. Plaintext is + the default; optional record encryption uses native age recipients as permission IDs. + Append-only grants share reusable keys, including historical access, without membership, + roles or upgrade governance. Applications own authoring rules through verified reducer + context. Unsupported readable model versions refuse opening. Drafts have one visibility + scope; local encrypted staging requires the selected key for validation and replay. + Captured model configuration, immutable JSON, write isolation and atomic adoption are + preserved. Reducer authors use the same normalized identity during staging and replay. + The stored Concord format and interface break compatibility with the previous + group-based design. No migration adapter is included. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2022f02..3f52112 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,25 +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: 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..972c125 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 }} @@ -103,40 +102,15 @@ 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 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/.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 9f4951a..f1a544e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,14 +6,12 @@ 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. Use installed, repository-configured versions; verify capabilities before - depending on flags or rules. The active workspace uses Vite+ Oxlint through - `pnpm lint`; excluded packages remain outside that check until migrated or retired. + depending on flags or rules. The active workspace uses Vite+ Oxlint through `pnpm lint`. - Encode repeatable mechanical rules in tooling when practical. Spend review attention on contracts, behavior, and design decisions. - Use diagnostics to drive small corrections. Review automatic fixes and scope @@ -44,63 +42,54 @@ 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. + +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: one application state from readable signed events, optional record encryption, + reusable permission keys and append-only grants, built on the other four. +- Applications: models, application authoring rules, document access, storage, sync 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. +- One application state is reconstructed from each reader's accepted, readable history. + Agreement requires equivalent readable histories and deterministic models; hidden + dependencies can change states and rejections. +- Permissions are reusable native age keys, identified by their public recipients. + Declarations cannot redefine a recipient; descriptive names need not be unique. + Grants disclose private keys and cannot revoke previous disclosure. Future access + changes use a new permission. +- Key possession establishes decryption capability, not application writing authority. + The model receives the verified author and historical batch version and owns its rules. +- Discover historical grants before application replay. A recovered private key must + derive the declared recipient; bad candidates cannot replace a valid key. +- A draft contains plaintext or one permission. Local encrypted staging requires its + key for validation and replay, not as a membership restriction. Competing mutations + reject during asynchronous writes; failed local adoption preserves the draft and state. +- A failing readable batch stays as evidence and changes no application state. Rejections + are relative to the reader's available history and model. Unreadable is not invalid + or empty. Unsupported readable model versions refuse opening; Ledger can still inspect + the bytes independently. +- Copies have one head and are compared, never silently merged. +- 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 +101,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..c8d8dac 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -1,125 +1,63 @@ -# 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 a public +record; only protected application batches and the private keys inside grants are 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. + +## Concord documents + +**Document**: a portable application database: a history read through a model by one identity. +Plaintext does not imply public access; the application owns access to the document itself. + +**Model**: an application's `id`, `version`, `initial()` state and `reduce` function. +Its definition is captured when opening or creating a document. The model ID is fixed in +signed genesis; authored batches carry historical application versions for the reducer. +An unsupported readable version refuses opening. There is no version ratchet. + +**Event**: `{ type, data }`, a fact an application records. Events are staged into a +**draft** and signed together by `commit`. +_Avoid_: command, action + +**Batch**: one commit's application events, all plaintext or encrypted to one permission. +A readable batch applies atomically for that reader; unreadable batches are skipped. + +**State**: one reader's accepted, readable events reduced through its model. It is derived, +never stored, and can be partial. Agreement requires equivalent readable histories and +models; different keys can lead to different states and rejections. +_Avoid_: projection, snapshot + +**Permission**: a reusable native age X25519 encryption capability, identified by its public +recipient. Its descriptive name need not be unique. A permission selects record encryption, +not application structure or writing authority. + +**Grant**: an append-only, encrypted copy of a permission's private key addressed to an +identity. Any holder can share it; later grants unlock historical records. Grant metadata +is public and does not prove another identity recovered a working key. Disclosed secrets +cannot be revoked; a new permission changes confidentiality for future records. + +**Rejected**: a signed commit that fails Concord's record contract or its readable +application batch fails the reader's model. It remains evidence and changes no accepted +state. Rejection is relative to that reader's available history and model. + +**Unreadable**: an encrypted application batch record this reader holds no permission key +for. It is neither invalid nor empty; its permission, author and ciphertext size remain +visible. Its event count, types, data and model version require decryption. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4dee79b..d90e7ef 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 | @@ -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,15 +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 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 +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 c580969..f6b4f3c 100644 --- a/README.md +++ b/README.md @@ -3,18 +3,20 @@ 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) | Standalone proofs, encrypted artifacts, manifests and a Node CLI | +| 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) | Portable, verifiable application databases; plaintext by default | 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 reconstructs application state from signed history, with optional record encryption and reusable permission keys. +Applications own document access, storage, sync and UI. Plaintext does not imply public +access: use controlled storage, whole-document Armour encryption, or selective record encryption as +needed. [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. @@ -29,24 +31,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, `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. CI -exercises Seal proofs over retained candidate bundles. 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. 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/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 ecf7241..f53a142 100644 --- a/llms.txt +++ b/llms.txt @@ -1,19 +1,18 @@ # Ternent libraries -> TypeScript ESM libraries for portable signed history, encrypted application documents, -> identity capabilities and standalone proofs. This is the consumer entry point for agents. +> TypeScript ESM libraries for portable signed history, plaintext application databases +> with optional record encryption, identities and standalone proofs. This is the +> consumer entry point for agents. ## 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. -- [Identity](packages/identity/llms.txt): generate/import identities, sign bytes and derive public encryption recipients. -- [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. +- [Concord](packages/concord/llms.txt): a portable, verifiable application database; plaintext by default, with optional record encryption. Applications control access to the document itself. +- [Ledger](packages/ledger/llms.txt): a signed, append-only history of JSON entries, verified on open, without Concord's application replay or encryption-key distribution. +- [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. -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 -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 @@ -23,8 +22,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 @@ -37,26 +35,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. +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 executable code: hosts select trusted models -and system implementations. Treat inspection evidence separately from trusted state. +Use the owning library's verification and cryptography rather than implementing them in +the application. Documents never load code: the application supplies its model. -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. +Copies have one head. Compare equal, ahead, behind, diverged or unrelated; never silently +choose or combine diverged history. To carry work across, open the other copy and stage your +events again. ## 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, permission and grant definitions. - [Contributor instructions](AGENTS.md): repository maintenance rather than application usage. 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..1855cd9 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 new Uint8Array(value); +} 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..b8264a1 100644 --- a/packages/armour/test/armour.test.ts +++ b/packages/armour/test/armour.test.ts @@ -1,251 +1,154 @@ -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(); +import { execFileSync } from "node:child_process"; +import { Buffer } from "node:buffer"; +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"]); +}); - const ciphertext = await armour.encryptTextForIdentities({ - identities: [identity], - text: "hello utf8", - }); - const plaintext = await armour.decryptTextWithIdentity({ - identity, - data: ciphertext, - }); +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)); +}); - expect(ciphertext).toContain("-----BEGIN AGE ENCRYPTED FILE-----"); - expect(plaintext).toBe("hello utf8"); - }); +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(); +}); - 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("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()); +}); - 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("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(new TextDecoder().decode(plaintextFromArrayBuffer)).toBe("buffer data"); - expect(new TextDecoder().decode(plaintextFromFile)).toBe("blob data"); - }); +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); +}); - 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("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(); + } +}); - 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("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(); + } +}); - await expect( - armour.encryptForIdentities({ - identities: [identity], - data: new TextEncoder().encode("async"), - }), - ).resolves.toBeInstanceOf(Uint8Array); - }); +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")); +}); - 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("Buffer plaintext is captured before asynchronous encryption", async () => { + const identity = await createIdentity(); + const plaintext = Buffer.from("original"); + const pending = encrypt(plaintext, [identity.publicIdentity]); + plaintext.set(utf8("modified")); + expect(await decrypt(await pending, identity)).toEqual(utf8("original")); +}); - const ciphertext = await armour.encryptForIdentities({ - identities: [identity], - data: new TextEncoder().encode("built package"), - }); - const plaintext = await armour.decryptWithIdentity({ - identity, - data: ciphertext, - }); +test("Buffer ciphertext is captured before asynchronous decryption", async () => { + const identity = await createIdentity(); + const ciphertext = Buffer.from(await encrypt(utf8("original"), [identity.publicIdentity])); + const replacement = await encrypt(utf8("modified"), [identity.publicIdentity]); + const pending = decrypt(ciphertext, identity); + ciphertext.set(replacement); + expect(await pending).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/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..f810bef 100644 --- a/packages/concord/CLAUDE.md +++ b/packages/concord/CLAUDE.md @@ -1,9 +1,59 @@ -# 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 source file: one application state over verified Ledger history, with +optional record encryption through reusable native age permissions and grants. + +## Ownership + +- Concord owns its closed record shapes, permission declarations, grant/key discovery, + readable application replay, staging and atomic local adoption. +- Identity owns identity validation and signing; Seal and Ledger own signed history, + canonical bytes, IDs and verification. Armour and age own encryption and key handling. +- The model owns domain validity and application authoring rules. Consumers own document + access, storage, publication, synchronization and presentation. + +## Contracts + +- Plaintext is the default. There is one model ID and one state per reader. A permission + is its native age recipient, not an application space or authority. Names may repeat; + declarations cannot redefine an existing recipient. +- Creation records the declaration and creator grant together. The creator recovers its + key through the same grant path as other identities. Anyone with a key can share it. + Grants are append-only disclosure; future confidentiality uses another permission. +- Discover matching keys throughout history before application replay. A recovered secret + counts only when its age recipient matches the permission ID. Invalid or unrelated + candidates never replace a working key or block a later valid grant. +- Public grant metadata is not proof that another identity holds a key. Expose all declared + permissions and accepted grants; `canDecrypt` describes local possession only. +- Replay uses readable batches in signed order. Unreadable is not invalid or empty. + A failing readable batch changes no application state; rejections are reader-relative. + Equivalent readable histories and deterministic models agree. Hidden dependencies can + change outcomes, including the rejection of updates and deletes. +- Model identity is fixed in genesis. Event versions reach the reducer; unsupported + readable versions refuse opening. Membership governance and a version ratchet do not + belong here. Ledger remains usable independently for inspection. +- Capture model/identity configuration and input values before asynchronous work. Validate + initial state and every reducer output. Keep the common Ledger JSON contract and + immutable values, sharing only previously captured immutable branches. +- Local drafts have one visibility scope: plaintext or one permission, explicitly selected + for each encrypted event. Local encrypted staging requires that key for validation; + application writing authority remains the model's decision. +- Acquire the mutation guard before yielding. Extend Ledger without opening prior history + again. Adopt a candidate only after local replay succeeds. Failure preserves accepted + history, state, capability views and draft. New keys unlocking old records require + application replay using the verified history, not another Ledger verification. +- Keep ordinary errors, direct composition and a small interface. No queues, generic + projection infrastructure, policy engines or independently persisted permission store. +- State exactly what raw bytes reveal and what requires decryption to verify. + +## Verification + +README.md states the consumer guarantees; SPEC.md fixes the stored format and replay +contract. `test/vector.json` fixes canonical bytes, a head, public grants and reader states. +A change that breaks it is a format change. Do not preserve retired source copies. + +Run the package check and root packed-consumer gate. Cover plaintext, multiple permissions, +historical/delegated grants, malformed candidates, new permissions for future records, +reader-relative rejections, versions, immutable values, call-time capture, concurrent writes, +failures and incremental/reopen equivalence. Verify native Armour/Ledger interoperability. +Update the README, SPEC and llms.txt with interface or format changes. diff --git a/packages/concord/README.md b/packages/concord/README.md index ce28bdc..d4a103a 100644 --- a/packages/concord/README.md +++ b/packages/concord/README.md @@ -1,116 +1,186 @@ # @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) · [Stored format and replay contract](SPEC.md) + +A portable, verifiable application database reconstructed from signed Ledger history. +There is one model and one application state per reader. Plaintext is the default; +permissions optionally encrypt records and grants distribute their reusable keys. + +A permission is a cryptographic capability, not an application role. Signatures establish +authorship; the application's reducer decides domain validity and authoring policy. +Storage, access to the document, publication, synchronization and presentation belong to +the consumer. Plaintext does not imply public distribution. + +## A plaintext application database + +```ts +import { createIdentity } from "@ternent/identity"; +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, { author, version }) { + // The application can check the verified author and historical event version here. + const data = event.data as { id?: string; title?: string } | null; + if (event.type !== "note.put" || typeof data?.id !== "string" || typeof data.title !== "string") + throw new Error("Invalid note"); + return { notes: { ...state.notes, [data.id]: data.title } }; + }, +}); + +const alice = await createIdentity(); +const doc = await createDocument({ model: notes, identity: alice }); +doc.stage({ type: "note.put", data: { id: "1", title: "Plaintext" } }); +await doc.commit(); +const reopened = await openDocument(doc.export(), { model: notes, identity: alice }); +reopened.state; // { notes: { 1: "Plaintext" } } +``` + +No permission configuration is needed. Another identity can open the same bytes and +write plaintext when the model accepts its events. A valid signature alone does not +establish application authorization. + +## Selectively encrypt records + +```ts +const financial = await doc.createPermission("financial"); +doc.stage({ type: "note.put", data: { id: "2", title: "Invoice" } }, { permission: financial }); +await doc.commit(); + +const bob = await createIdentity(); +await doc.grantPermission(financial, bob.publicIdentity); +const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); +bobs.state; // { notes: { 1: "Plaintext", 2: "Invoice" } } +bobs.permissions; // [{ id: financial, name: "financial", canDecrypt: true }] +``` + +The permission ID is its native age `age1…` public encryption recipient. Its declaration +is immutable; names are descriptive metadata and need not be unique. Creating a permission +stores its declaration and a grant to its creator in one signed commit. The creator +recovers the private key through the same grant mechanism as every other recipient. + +A grant wraps that private key to one identity with Armour. Later grants unlock historical +records. Any key holder can issue grants, without approval from a creator or another key +holder. `grants` lists public `{ entry, permission, to }` metadata; a grant's presence does +not prove its addressee recovered a working key. `canDecrypt` describes this handle only. +All declared permissions and accepted grant records remain inspectable without keys. + +Keys can be copied, retained and shared outside Concord. Grants are append-only and cannot +revoke previous disclosure. To change who reads future records, create another permission +and grant its key to the intended identities. Old keys continue to decrypt old records. + +Public recipients can encrypt without a private key. Concord's local `stage` convenience +requires the selected permission's key so this handle can validate and replay its own +commit. This is a local validation constraint, not a membership rule or cryptographic +writing restriction. Other permissions may remain unreadable. Models receive the verified +author regardless of which permission protects a batch. + +## Encrypt the whole document externally ```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 { encrypt, decrypt } from "@ternent/armour"; + +const encryptedFile = await encrypt(doc.export(), [alice.publicIdentity]); +const restored = await openDocument(await decrypt(encryptedFile, alice), { + model: notes, + identity: alice, }); -const report = await reopened.verify(); -const replayed = await reopened.replay(); ``` -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. +Private storage, authenticated transport, an outer Armour envelope and selective record +encryption compose independently. Decrypting an outer envelope does not grant inner keys +or application authorization. Armour also supports a passphrase envelope. + +## Document interface + +| Member | Meaning | +| --------------------------------------- | -------------------------------------------------------------------------------------------- | +| `stage(event, { permission? })` | Validate and stage one event; omitted permission means plaintext | +| `commit()` / `discard()` | Sign the staged batch / drop it | +| `state` | Immutable committed state reconstructed from this reader's accepted, readable history | +| `draft` | Immutable `{ permission, events, state }` preview, or `null`; plaintext permission is `null` | +| `createPermission(name)` | Commit a declaration and creator grant; return the native age recipient | +| `grantPermission(permission, identity)` | Commit a grant of an already held key to a public identity | +| `permissions` | Detached list of immutable `{ id, name, canDecrypt }` records | +| `grants` | Detached list of immutable `{ entry, permission, to }` records | +| `unreadable` | Count of encrypted application batch records this reader has no key for | +| `rejected` | Detached list of immutable `{ commit, message }` evidence, relative to this reader | +| `head`, `export()` | Current head commit ID and canonical Ledger bytes | + +A staged batch is plaintext or uses one permission. Every encrypted `stage` call supplies +that permission explicitly. Switching scope requires committing or discarding first. +Permission creation and grants commit immediately and require an empty draft. Application +events always use `stage` then `commit`; unfinished draft recovery belongs to the consumer. + +While an asynchronous write runs, competing mutations reject, including `stage` and +`discard`. Reads keep the previous committed state and draft. Local adoption is atomic: +signing, encryption or replay failure preserves history, state, capabilities and drafts +for retry. Errors are ordinary `Error`s. A locally created permission is not adopted if +its creator grant cannot be recovered. No mutation queue is maintained. + +## Partial replay and application validity + +An unreadable batch is not invalid or empty. Its events do not reach the reducer. A +readable batch applies all its events atomically: a throwing reducer or invalid output +rejects the entire batch and leaves the previous state; later readable batches continue. + +State can be incomplete. Readers with different keys can have different states and +rejection lists. For example, a delete may succeed for a reader who saw an encrypted row +and fail for a reader who never saw its creation. A later grant can change that outcome +when the same signed entries are replayed. Agreement requires equivalent readable histories +and equivalent deterministic models; arbitrary dependencies across hidden records have no +global consistency guarantee. + +Prefer independently protected rows, self-contained upserts and deliberate handling of +unknown rows or references. A reducer should throw when it lacks facts required to validate +an event. Local staging validates against this handle's readable state, not hidden history; +applications requiring complete state can check `unreadable` before authoring. Zero unreadable +records means no encountered encrypted batch lacked a key, not that every declared +permission is available or that all signed events were accepted. + +## Model and JSON contract + +Model ID, positive safe-integer version, `initial` and `reduce` are captured at create/open. +Model identity must match genesis. Every event batch carries its author's configured +version, passed as reducer context. Older versions remain allowed; there is no version +ratchet. Opening refuses an unsupported readable version. Any signer can append such a +batch and make older applications refuse that copy. Ledger remains independently usable +for inspection. An encrypted version is unknown without its key. + +`initial` and `reduce` must be synchronous, pure and deterministic, including their handling +of older events. Capturing functions does not freeze changing closures or sandbox application +code. Reducers receive immutable state and events and a frozen `{ author, version }` context. + +Event data, initial state and reducer results use the same Ledger JSON semantics: +well-formed Unicode strings and object keys, safe integers excluding negative zero, null, +booleans, dense arrays and plain objects. Fractions, undefined, functions, cycles and class +instances reject. Event `type` is a well-formed string of 1–128 UTF-16 code units. Object +key order matches Ledger; Unicode normalization is not performed. Inputs are captured before +asynchronous work, new values are detached and immutable, and captured branches can be +shared safely between successive states without recopying accumulated state. + +## What verification and the raw file reveal + +Ledger verifies signatures, canonical bytes, linkage and history integrity before opening. +It does not establish identity claims, data truth, application authorization or freshness. +A remembered head is needed to detect rollback or withholding. Claimed times are not trusted +timestamps. Rejected signed records remain in history; deletion never erases disclosure. + +An unencrypted file reveals the model ID, permission names and native public recipients, +grant target identity IDs, commit order and links, signer keys, claimed times, and ciphertext +sizes. Plaintext batch events and versions are visible. Protected event types, values and +versions require their key; the protecting permission remains visible. Grants encrypt native +private keys. An outer Armour envelope protects these inner records while still exposing +file size and external transport/storage metadata. + +This is cryptographic record confidentiality, not server-enforced row access control. +Processing is in memory with Ledger's default 16 MiB limit. Capturing values, reducer calls, +serialization and some cryptographic work can block browser rendering despite asynchronous +methods. Consumers own workload sizing and execution placement. JavaScript key strings +cannot be reliably zeroed. Copies have one head and are never silently merged; synchronization +and conflict resolution belong to the consumer. + +License: ISC. diff --git a/packages/concord/SPEC.md b/packages/concord/SPEC.md index a19ed82..00f3d76 100644 --- a/packages/concord/SPEC.md +++ b/packages/concord/SPEC.md @@ -1,8 +1,115 @@ -# 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. +# Concord format 1 + +Working decision, 2026-11-28: "Proceed with one application state, reusable encryption +capabilities and append-only grants." Permission names are descriptive metadata and need +not be unique. A permission's native age recipient is its identifier. Local encrypted +staging requires that permission's private key for validation and replay, independently +of application authoring policy. + +## Container and records + +The sole container is Ledger version 2, including its canonical bytes, signed commit +bodies, entry identifiers, authors and claimed times. Concord does not repeat those fields +in payloads. Entry kind is `"concord"`; payload objects have exactly the fields below. +Extra fields, unknown operations and malformed shapes reject their commit. + +| Operation | Exact payload fields | +| ---------------------- | ------------------------------------------------------------------------------- | +| Document declaration | `{ op: "document", format: 1, model: string }` | +| Permission declaration | `{ op: "permission", name: string, recipient: PermissionId }` | +| Grant | `{ op: "grant", permission: PermissionId, to: IdentityId, ciphertext: string }` | +| Plaintext batch | `{ op: "events", version: positiveSafeInteger, events: Event[] }` | +| Encrypted batch | `{ op: "encrypted", permission: PermissionId, ciphertext: string }` | + +Genesis contains exactly the document declaration. Another format or model ID prevents +opening. A later commit contains exactly one application batch, one grant, or a permission +declaration followed by its creator grant. In the pair, the grant names the declared +recipient and addresses the commit signer. System records and application batches do not +mix. A batch contains at least one event and has one visibility scope. + +A `PermissionId` is a canonical lowercase age X25519 recipient: Bech32 `age` with 32 bytes. +It identifies the key itself; there is no separately mutable recipient mapping. `name` is a +nonempty Unicode string and is not unique. A second declaration of an existing recipient +rejects the entire later commit, even if the name is identical. Grants and encrypted batches +must refer to a permission declared earlier in signed order. + +`IdentityId` is Identity's `identity:` followed by 64 lowercase hex digits. Grant ciphertext +is binary age encoded as unpadded base64url; its plaintext is the UTF-8 native age X25519 +secret-key string. It is wrapped through Armour to the supplied public identity. An +addressed identity ID is metadata, not proof of successful decryption. + +Encrypted application plaintext is UTF-8 JSON with exactly `{ version, events }`; its age +ciphertext uses the same transport encoding. Events have exactly `{ type, data }`. Data and +state follow the README's Ledger JSON contract. Event versions describe the application, +not this format number. The signed Ledger envelope remains canonical; encrypted plaintext +need not be a second canonical container. + +## Opening and discovery + +1. Open and verify Ledger once. Check genesis and the supplied model ID. +2. Read commits in signed order. Validate each commit's record shapes and permission + references before changing its public permission/grant view. Invalid record commits are + retained with rejection evidence and do not change those views. +3. Discover candidate keys from grants addressed to this identity throughout history. + Decrypt and parse with Armour and age. Accept a candidate only when its derived public + recipient equals its permission identifier. A malformed, unrelated or duplicate candidate + cannot replace a working key or stop later grants being tried. Candidate failures do not + establish application rejection or another identity's decryptability. +4. Replay valid application batches in signed order using all recovered keys, including + grants appearing after those batches. Public permission/grant records never reach the + application's reducer and have no application authoring authority. + +All declared permissions and structurally accepted grants are visible through inspection +lists. `canDecrypt` means the local reader holds a verified matching key. Malformed signed +records remain available through rejection evidence and the independently inspectable Ledger. + +## Application replay + +There is one captured `model.initial()` state per reader. A batch without a key increments +`unreadable` once, irrespective of how many events its ciphertext might contain. It is not +reduced, rejected or treated as an empty event list. If a key is held but age authentication, +UTF-8 decoding or batch validation fails, the batch is rejected. + +A readable batch with a version above the supplied model version prevents opening. Otherwise, +reduce each event using the commit's verified signer and the batch's recorded version. +Validate and capture every output. Adopt the resulting state only if the whole batch +succeeds. A throw or invalid output records `{ commit, message }` and preserves the previous +state; later batches still apply. Rejection lists preserve signed commit order. + +Rejection is relative to the reader's available history and model. A later grant may make an +earlier update or delete valid, or expose a previously unreadable rejected batch. Agreement +requires equivalent readable histories and deterministic models; hidden dependencies do not +have universal application transaction semantics. A commit is a cryptographic commitment, +not a guarantee that every reader reconstructs the same application outcome. + +## Local authoring and adoption + +Each staged event selects plaintext or an available permission key. A draft cannot change +scope. Local reduction uses this reader's current readable state. Key possession is required +for local encrypted validation, not application authorization; public recipients remain +usable for encryption independently through Armour and Ledger. + +Writes acquire the document guard before encryption or signing yields. All competing +mutations fail while reads retain the previous state. Use a fresh Ledger writer to extend +verified history without opening or verifying prior commits again. Prepare a private replay +candidate and adopt history, state and public capability views together only after local +acceptance. Failure preserves the existing draft and accepted values. A new creator grant +must recover the new key before local creation is adopted. + +Apply ordinary local application batches incrementally. If a discovered key unlocks an +existing permission's history, reconstruct application outcomes against the already verified +Ledger and known keys before adopting; no additional Ledger verification is needed. Opening +and incremental authoring produce equivalent results for the same identity and model. + +## Confidentiality and compatibility limits + +A grant discloses a reusable secret. It cannot be undone by another record or by hiding a +materialized grant. Future confidentiality changes require a new permission and new grants. +There is no upgrade governance: any signer can append a readable future-version batch that +older models cannot open. Ledger remains independently usable for inspection, without a +Concord inspection mode. Unreadable encrypted versions provide no compatibility guarantee. + +The raw document exposes declarations, names, recipients, grant targets, signers, claimed +times, links, plaintext events/versions, protecting permission identifiers and ciphertext +sizes. Signatures provide authorship and integrity, not application authorization or +freshness. Storage access and publication policy remain outside Concord. diff --git a/packages/concord/llms.txt b/packages/concord/llms.txt index 2e55196..dfb14c2 100644 --- a/packages/concord/llms.txt +++ b/packages/concord/llms.txt @@ -1,165 +1,84 @@ # @ternent/concord -> Build a bounded application around typed commands, signed history and encrypted groups. +> A portable, verifiable application database: one state reconstructed from signed, +> readable application history. Plaintext by default; optional record encryption uses +> reusable permission keys and append-only grants. Consumers own storage, document access, +> application authorization, publication, synchronization and presentation. -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: `Document`, `Model`, +`Event`, `Json`, `ReduceContext`, `PermissionId`, `Permission`, `Grant`, `Rejection`. +Declarations: `dist/index.d.ts`. [README](README.md) covers the interface and three uses; +[SPEC](SPEC.md) defines closed records, discovery, replay and local atomicity. ```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"; +import { encrypt, decrypt } from "@ternent/armour"; + +const counter = defineModel<{ count: number }>({ + id: "counter", version: 1, + initial: () => ({ count: 0 }), + reduce(state, event) { + if (event.type !== "increment" || event.data !== null) throw new Error("Unknown event"); + return { count: state.count + 1 }; }, - 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); +const alice = await createIdentity(); +const doc = await createDocument({ model: counter, identity: alice }); +doc.stage({ type: "increment", data: null }); +await doc.commit(); +const financial = await doc.createPermission("financial"); +doc.stage({ type: "increment", data: null }, { permission: financial }); +await doc.commit(); +const bob = await createIdentity(); +await doc.grantPermission(financial, bob.publicIdentity); +const bobs = await openDocument(doc.export(), { model: counter, identity: bob }); +bobs.state; // { count: 2 } +const envelope = await encrypt(doc.export(), [alice.publicIdentity]); +const restored = await openDocument(await decrypt(envelope, alice), { model: counter, identity: alice }); ``` -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 - -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. - -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. +- `state` is a value, not a scoped query. A permission selects encryption, not another + model or application state. Its ID is its immutable native age public recipient. + Names are metadata and may repeat. Plaintext does not imply public distribution. +- `createPermission(name)` commits its declaration and initial creator grant together. + Creator and other recipients recover keys through the same grant mechanism. Local + creation fails without adoption if its creator grant cannot recover the key. +- Any holder can `grantPermission(permission, publicIdentity)`. Grants disclose reusable + secrets and cannot revoke historical access. A new permission changes future access. +- `permissions` exposes `{ id, name, canDecrypt }`; `grants` exposes `{ entry, permission, + to }` for all accepted declarations/grants, not only this identity's. Grant presence + does not prove its addressee holds a working key. `canDecrypt` describes this handle. +- Local encrypted staging requires the selected key for validation and replay. Other + records may be unreadable. This is not membership or writing authority; the reducer + receives the verified `{ author, version }` and owns application authoring rules. +- `unreadable` counts encrypted batch records lacking a key. Such batches are neither + invalid nor empty. `rejected` is `{ commit, message }[]` relative to this reader's + available history and model. A readable failing batch changes no state, and replay + continues. A later grant can change earlier application outcomes on replay. +- Models must handle dependencies on hidden rows deliberately. Prefer independent rows + and self-contained events; unknown updates/deletes/references can reject. Agreement + requires equivalent readable histories and deterministic models, not arbitrary reducers + over different keys. Applications can require `unreadable === 0` before authoring. +- A batch is plaintext or one permission. Every encrypted `stage` supplies it explicitly; + omission means plaintext. `commit` and `discard` finish/drop the draft. Permission/key + operations commit immediately and require an empty draft. No unfinished draft is stored. +- Model fields and identity callbacks are captured before asynchronous work. State, events, + drafts and records are immutable or detached; safe captured branches are shared. JSON + means safe integers excluding -0, well-formed Unicode strings/keys, null, booleans, + dense arrays and plain objects. Fractions, undefined, cycles and class instances reject. +- Model ID must match genesis. Each batch records its authoring version. Reducers handle + historical versions. An unsupported readable version refuses opening; there is no + version ratchet or upgrade authority. Hidden versions are unknown. Ledger can inspect + those bytes independently. Model functions must remain synchronous, pure and deterministic. +- While a write runs, all competing mutations reject and reads remain available. Failed + encryption, signing or replay preserves history, state, capability views and draft. + Local writes extend verified Ledger history without re-verifying old commits. New + historical keys require application replay before adoption, using the verified history. +- Raw bytes expose permission names/recipients, grant target IDs, model ID, signers, claimed + times, links, plaintext events/versions and ciphertext sizes. Protected values/types/ + versions need decryption. Signatures prove authorship and integrity, not application + authority or freshness. Outer Armour encryption protects the complete inner document. +- Processing is in memory under Ledger's default 16 MiB limit. Async methods can block + rendering. Consumers own execution placement and workload sizes. Copies have one head; + synchronization, conflict resolution and rollback anchors belong to the consumer. diff --git a/packages/concord/package.json b/packages/concord/package.json index dbf90b1..033d521 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": "Portable, verifiable application databases with optional record encryption", "license": "ISC", "repository": { "type": "git", @@ -11,6 +11,7 @@ "files": [ "dist", "README.md", + "SPEC.md", "llms.txt" ], "type": "module", @@ -22,18 +23,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 +38,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..02db135 100644 --- a/packages/concord/src/index.ts +++ b/packages/concord/src/index.ts @@ -1,5 +1,549 @@ -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, bech32 } 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, + type JsonObject, +} 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 PermissionId = `age1${string}`; +export type Permission = Readonly<{ id: PermissionId; name: string; canDecrypt: boolean }>; +export type Grant = Readonly<{ entry: string; permission: PermissionId; to: string }>; +export type Rejection = Readonly<{ commit: string; message: string }>; +export type ReduceContext = Readonly<{ author: PublicIdentity; version: number }>; +export type Model = { + id: string; + version: number; + initial: () => S; + reduce: (state: S, event: Event, context: ReduceContext) => S; +}; + +export function defineModel(model: Model): Model { + return model; +} + +type Events = { version: number; events: Event[] }; +type Application = + | ({ op: "events" } & Events) + | { op: "encrypted"; permission: PermissionId; ciphertext: string }; +type PermissionRecord = { op: "permission"; name: string; recipient: PermissionId }; +type GrantRecord = { op: "grant"; permission: PermissionId; to: string; ciphertext: string }; +type Record = PermissionRecord | GrantRecord | Application; +type Replay = { + permissions: Map; + grants: Grant[]; + keys: Map; + state: S; + unreadable: number; + rejected: Rejection[]; +}; + +const KIND = "concord"; +const encoder = new TextEncoder(); +const decoder = new TextDecoder("utf-8", { fatal: true }); +// Only captured values may share their already validated, deeply immutable branches. +const jsonValues = new WeakSet(); + +class ConcordDocument { + readonly #model: Model; + readonly #identity: Identity; + #history: History; + #replay: Replay; + #draft: Readonly<{ permission: PermissionId | null; events: readonly Event[]; state: S }> | null = + null; + #writing = false; + + constructor(model: Model, identity: Identity, history: History, replay: Replay) { + this.#model = model; + this.#identity = identity; + this.#history = history; + this.#replay = replay; + } + + get state(): S { + return this.#replay.state; + } + get head(): string { + return this.#history.head; + } + get draft() { + return this.#draft; + } + get unreadable(): number { + return this.#replay.unreadable; + } + get rejected(): readonly Rejection[] { + return [...this.#replay.rejected]; + } + get grants(): readonly Grant[] { + return [...this.#replay.grants]; + } + get permissions(): readonly Permission[] { + return [...this.#replay.permissions].map(([id, name]) => + Object.freeze({ id, name, canDecrypt: this.#replay.keys.has(id) }), + ); + } + + export(): Uint8Array { + return this.#history.export(); + } + + stage(event: Event, options: { permission?: PermissionId } = {}): void { + this.#idle(); + const permission = options.permission ?? null; + if (this.#draft && this.#draft.permission !== permission) + throw new Error("A draft holds plaintext or one permission; commit or discard it first"); + if (permission !== null) this.#key(permission); + const captured = captureEvent(event); + const context = Object.freeze({ + author: this.#identity.publicIdentity, + version: this.#model.version, + }); + const base = this.#draft ? this.#draft.state : this.#replay.state; + const state = captureJson(this.#model.reduce(base, captured, context)) as S; + this.#draft = Object.freeze({ + permission, + events: Object.freeze([...(this.#draft?.events ?? []), captured]), + state, + }); + } + + discard(): void { + this.#idle(); + this.#draft = null; + } + + async commit(): Promise { + return this.#write(async () => { + const draft = this.#draft; + if (!draft) throw new Error("Nothing is staged"); + const body: Events = { version: this.#model.version, events: [...draft.events] }; + const record: Application = + draft.permission === null + ? { op: "events", ...body } + : { + op: "encrypted", + permission: draft.permission, + ciphertext: base64urlnopad.encode( + await encrypt(encoder.encode(JSON.stringify(body)), [draft.permission]), + ), + }; + await this.#append([record]); + this.#draft = null; + }); + } + + async createPermission(name: string): Promise { + return this.#write(async () => { + this.#noDraft(); + if (typeof name !== "string" || !name || /\p{Cs}/u.test(name)) + throw new TypeError("A permission needs a nonempty Unicode name"); + const secret = await generateX25519Identity(); + const recipient = (await identityToRecipient(secret)) as PermissionId; + await this.#append([ + { op: "permission", name, recipient }, + await grant(recipient, secret, this.#identity.publicIdentity), + ]); + return recipient; + }); + } + + async grantPermission(permission: PermissionId, identity: PublicIdentity): Promise { + return this.#write(async () => { + this.#noDraft(); + const secret = this.#key(permission); + const target = validatePublicIdentity(identity); + await this.#append([await grant(permission, secret, target)]); + }); + } + + #key(permission: PermissionId): string { + const secret = this.#replay.keys.get(permission); + if (!secret) throw new Error("This identity does not hold the permission's key"); + return secret; + } + + #idle(): void { + if (this.#writing) throw new Error("A document write is in progress"); + } + + #noDraft(): void { + if (this.#draft) throw new Error("Commit or discard the draft first"); + } + + async #write(write: () => Promise): Promise { + this.#idle(); + this.#writing = true; + try { + return await write(); + } finally { + this.#writing = false; + } + } + + async #append(records: Record[]): Promise { + const writer = createWriter(this.#history, this.#identity); + writer.append(records.map((record) => ({ kind: KIND, payload: record as JsonObject }))); + const history = await writer.commit(); + const commit = history.commits[history.commits.length - 1]; + let replay: Replay = { + ...this.#replay, + permissions: new Map(this.#replay.permissions), + grants: [...this.#replay.grants], + keys: new Map(this.#replay.keys), + rejected: [...this.#replay.rejected], + }; + const batch = await discover(commit, this.#identity, replay); + const historicalKey = [...replay.keys.keys()].some( + (key) => !this.#replay.keys.has(key) && this.#replay.permissions.has(key), + ); + // A later grant can change earlier application outcomes; Ledger is already verified. + if (historicalKey) + replay = await replayHistory(history, this.#model, this.#identity, replay.keys); + else if (batch) await apply(batch, commit, this.#model, replay); + const created = records.find((record) => record.op === "permission"); + if (created && !replay.keys.has(created.recipient)) { + throw new Error("Could not recover the permission's creator grant"); + } + const rejection = replay.rejected.find((item) => item.commit === commit.id); + if (rejection) throw new Error(`The commit was not accepted: ${rejection.message}`); + this.#history = history; + this.#replay = replay; + } +} + +export type Document = ConcordDocument; + +export async function createDocument(input: { + model: Model; + identity: Identity; +}): Promise> { + const model = captureModel(input.model); + const identity = captureIdentity(input.identity); + const declaration = { op: "document", format: 1, model: model.id }; + const history = await createLedger({ + signer: identity, + entries: [{ kind: KIND, payload: declaration }], + }); + return new ConcordDocument( + model, + identity, + history, + await replayHistory(history, model, identity), + ); +} + +export async function openDocument( + bytes: Uint8Array, + input: { model: Model; identity: Identity }, +): Promise> { + const model = captureModel(input.model); + const identity = captureIdentity(input.identity); + const history = await openLedger(bytes); + return new ConcordDocument( + model, + identity, + history, + await replayHistory(history, model, identity), + ); +} + +async function replayHistory( + history: History, + model: Model, + identity: Identity, + keys = new Map(), +): Promise> { + const genesis = history.commits[0]; + const declaration = genesis.entries[0]?.payload; + if ( + genesis.entries.length !== 1 || + genesis.entries[0].kind !== KIND || + !hasKeys(declaration, ["op", "format", "model"]) || + declaration.op !== "document" || + declaration.format !== 1 || + typeof declaration.model !== "string" + ) + throw new Error("Not a Concord format 1 document"); + if (declaration.model !== model.id) throw new Error(`Document uses model ${declaration.model}`); + const replay: Replay = { + permissions: new Map(), + grants: [], + keys: new Map(keys), + state: captureJson(model.initial()) as S, + unreadable: 0, + rejected: [], + }; + const pending: { commit: Commit; batch?: Application; error?: string }[] = []; + // Discover keys throughout history before applying events, including historical grants. + for (const commit of history.commits.slice(1)) { + try { + pending.push({ commit, batch: await discover(commit, identity, replay) }); + } catch (error) { + pending.push({ commit, error: messageOf(error) }); + } + } + for (const { commit, batch, error } of pending) { + if (error !== undefined) reject(replay, commit, error); + else if (batch) await apply(batch, commit, model, replay); + } + return replay; +} + +async function discover( + commit: Commit, + identity: Identity, + replay: Replay, +): Promise { + if (commit.entries.some((entry) => entry.kind !== KIND)) + throw new Error("A commit holds only Concord entries"); + const records = commit.entries.map((entry) => readRecord(entry.payload)); + const first = records[0]; + if ( + records.length === 2 && + first.op === "permission" && + records[1].op === "grant" && + records[1].permission === first.recipient && + records[1].to === commit.proof.signer.id + ) { + if (replay.permissions.has(first.recipient)) throw new Error("Permission already declared"); + replay.permissions.set(first.recipient, first.name); + await recover(records[1], commit.entries[1].id, identity, replay); + return undefined; + } + if (records.length !== 1 || first.op === "permission") + throw new Error( + "A commit holds one application batch, one grant, or a permission with its creator grant", + ); + if (first.op !== "events" && !replay.permissions.has(first.permission)) + throw new Error("Unknown permission"); + if (first.op === "grant") { + await recover(first, commit.entries[0].id, identity, replay); + return undefined; + } + return first; +} + +async function recover( + record: GrantRecord, + entry: string, + identity: Identity, + replay: Replay, +): Promise { + replay.grants.push(Object.freeze({ entry, permission: record.permission, to: record.to })); + if (record.to !== identity.publicIdentity.id || replay.keys.has(record.permission)) return; + try { + const secret = decoder.decode( + await decrypt(base64urlnopad.decode(record.ciphertext), identity), + ); + if ((await identityToRecipient(secret)) === record.permission) + replay.keys.set(record.permission, secret); + } catch { + /* A bad candidate cannot replace a valid key or prevent later grants. */ + } +} + +async function apply( + record: Application, + commit: Commit, + model: Model, + replay: Replay, +): Promise { + let batch: Events; + if (record.op === "encrypted") { + const secret = replay.keys.get(record.permission); + if (!secret) { + replay.unreadable++; + return; + } + try { + batch = readEvents( + JSON.parse(decoder.decode(await decrypt(base64urlnopad.decode(record.ciphertext), secret))), + ); + } catch (error) { + reject(replay, commit, messageOf(error)); + return; + } + } else batch = record; + if (batch.version > model.version) + throw new Error(`Document needs model version ${batch.version}`); + let state = replay.state; + try { + const context = Object.freeze({ + author: validatePublicIdentity(commit.proof.signer), + version: batch.version, + }); + for (const event of batch.events) state = captureJson(model.reduce(state, event, context)) as S; + } catch (error) { + reject(replay, commit, messageOf(error)); + return; + } + replay.state = state; +} + +function reject(replay: Replay, commit: Commit, message: string): void { + replay.rejected.push(Object.freeze({ commit: commit.id, message })); +} + +async function grant( + permission: PermissionId, + secret: string, + to: PublicIdentity, +): Promise { + const ciphertext = base64urlnopad.encode(await encrypt(encoder.encode(secret), [to])); + return { op: "grant", permission, to: to.id, ciphertext }; +} + +function readRecord(value: unknown): Record { + if ( + hasKeys(value, ["op", "name", "recipient"]) && + value.op === "permission" && + typeof value.name === "string" && + value.name.length > 0 && + isPermissionId(value.recipient) + ) + return value as PermissionRecord; + if ( + hasKeys(value, ["op", "permission", "to", "ciphertext"]) && + value.op === "grant" && + isPermissionId(value.permission) && + typeof value.to === "string" && + /^identity:[0-9a-f]{64}$/.test(value.to) && + typeof value.ciphertext === "string" + ) + return value as GrantRecord; + if ( + hasKeys(value, ["op", "permission", "ciphertext"]) && + value.op === "encrypted" && + isPermissionId(value.permission) && + typeof value.ciphertext === "string" + ) + return value as Application; + if (hasKeys(value, ["op", "version", "events"]) && value.op === "events") + return { op: "events", ...readEvents({ version: value.version, events: value.events }) }; + throw new Error("Malformed Concord record"); +} + +function readEvents(value: unknown): Events { + if ( + !hasKeys(value, ["version", "events"]) || + !isVersion(value.version) || + !Array.isArray(value.events) || + value.events.length === 0 + ) + throw new Error("Malformed application batch"); + return { version: value.version, events: value.events.map(captureEvent) }; +} + +function captureEvent(value: unknown): Event { + if (!hasKeys(value, ["type", "data"])) throw new TypeError("An event is { type, data }"); + const { type, data } = value; + if (typeof type !== "string" || type.length < 1 || type.length > 128 || /\p{Cs}/u.test(type)) { + throw new TypeError("An event is { type, data } with a type of 1 to 128 characters"); + } + return Object.freeze({ type, data: captureJson(data) }); +} + +function captureModel(value: Model): Model { + if (!isRecord(value)) throw new TypeError("A model is { id, version, initial, reduce }"); + const { id, version, initial, reduce } = value; + if ( + typeof id !== "string" || + !id || + /\p{Cs}/u.test(id) || + !isVersion(version) || + typeof initial !== "function" || + typeof reduce !== "function" + ) { + throw new TypeError("A model needs an id, a positive integer version, initial and reduce"); + } + return Object.freeze({ id, version, initial, reduce }); +} + +function captureIdentity(identity: Identity): Identity { + return Object.freeze({ + publicIdentity: validatePublicIdentity(identity.publicIdentity), + sign: identity.sign.bind(identity), + export: identity.export.bind(identity), + withX25519Secret: identity.withX25519Secret.bind(identity), + }); +} + +// Copy each new JSON branch once. Captured branches are deeply immutable and can be shared +// by successive states without copying the accumulated application state. +function captureJson(value: unknown, parents = new Set()): Json { + if (value === null || typeof value === "boolean") return value; + if (typeof value === "number") { + if (!Number.isSafeInteger(value) || Object.is(value, -0)) + throw new TypeError("Numbers must be safe integers, excluding negative zero"); + return value; + } + if (typeof value === "string") { + if (/\p{Cs}/u.test(value)) throw new TypeError("Strings must be well-formed Unicode"); + return value; + } + if ( + typeof value !== "object" || + (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) + ) { + throw new TypeError("Values must be plain Ledger JSON"); + } + if (jsonValues.has(value)) return value as Json; + if (parents.has(value)) throw new TypeError("JSON cannot contain cycles"); + parents.add(value); + const copy = Array.isArray(value) + ? Array.from(value, (child) => captureJson(child, parents)) + : Object.fromEntries( + Object.keys(value) + .sort() + .map((key) => { + if (/\p{Cs}/u.test(key)) throw new TypeError("Object keys must be well-formed Unicode"); + return [key, captureJson((value as { [key: string]: unknown })[key], parents)]; + }), + ); + parents.delete(value); + Object.freeze(copy); + jsonValues.add(copy); + return copy; +} + +function isRecord(value: unknown): value is { [key: string]: unknown } { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function hasKeys(value: unknown, keys: K[]): value is { [P in K]: unknown } { + return ( + isRecord(value) && + Object.keys(value).length === keys.length && + keys.every((key) => Object.hasOwn(value, key)) + ); +} + +function isPermissionId(value: unknown): value is PermissionId { + if (typeof value !== "string" || !value.startsWith("age1")) return false; + try { + const { prefix, words } = bech32.decode(value as PermissionId); + return ( + prefix === "age" && + bech32.fromWords(words).length === 32 && + bech32.encode(prefix, words) === value + ); + } catch { + return false; + } +} + +function isVersion(value: unknown): value is number { + return Number.isSafeInteger(value) && (value as number) >= 1; +} + +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..aec4c61 --- /dev/null +++ b/packages/concord/test/concord.test.ts @@ -0,0 +1,765 @@ +import { readFileSync } from "node:fs"; +import { expect, test, vi } from "vite-plus/test"; +import { base64urlnopad } from "@scure/base"; +import { decrypt, encrypt } from "@ternent/armour"; +import { + createIdentity, + restoreIdentity, + type Identity, + type PublicIdentity, +} from "@ternent/identity"; +import { createLedger, createWriter, openLedger, type JsonObject } from "@ternent/ledger"; +import { generateX25519Identity, identityToRecipient } from "age-encryption"; +import * as api from "../src/index.js"; +import { + createDocument, + defineModel, + openDocument, + type Document, + type Event, + type Json, + type Model, + type PermissionId, +} 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" && typeof data?.id === "string" && typeof data.title === "string") + return { notes: { ...state.notes, [data.id]: data.title } }; + if (event.type === "note.remove" && typeof data?.id === "string") { + 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}`); + }, +}); +const put = (id: string, title: string): Event => ({ type: "note.put", data: { id, title } }); +const bytes = (text: string) => new TextEncoder().encode(text); +async function people() { + const [alice, bob, carol, dave] = await Promise.all( + Array.from({ length: 4 }, () => createIdentity()), + ); + return { alice, bob, carol, dave }; +} +async function forge( + document: Uint8Array, + signer: Identity, + payloads: JsonObject[], + kind = "concord", +) { + const writer = createWriter(await openLedger(document), signer); + writer.append(payloads.map((payload) => ({ kind, payload }))); + return (await writer.commit()).export(); +} +async function wrapped(permission: PermissionId, secret: string, to: PublicIdentity) { + return { + op: "grant", + permission, + to: to.id, + ciphertext: base64urlnopad.encode(await encrypt(bytes(secret), [to])), + }; +} +async function encrypted(permission: PermissionId, events: Event[], version = 1) { + return { + op: "encrypted", + permission, + ciphertext: base64urlnopad.encode( + await encrypt(bytes(JSON.stringify({ version, events })), [permission]), + ), + }; +} +async function secretOf(document: Uint8Array, identity: Identity, permission: PermissionId) { + for (const commit of (await openLedger(document)).commits) { + for (const entry of commit.entries) { + const record = entry.payload as { + op: string; + permission: string; + to: string; + ciphertext: string; + }; + if ( + record.op === "grant" && + record.permission === permission && + record.to === identity.publicIdentity.id + ) + return new TextDecoder().decode( + await decrypt(base64urlnopad.decode(record.ciphertext), identity), + ); + } + } + throw new Error("No grant"); +} +async function agrees(doc: Document, model: Model, identity: Identity) { + const reopened = await openDocument(doc.export(), { model, identity }); + expect(reopened.state).toEqual(doc.state); + expect(reopened.head).toBe(doc.head); + expect(reopened.permissions).toEqual(doc.permissions); + expect(reopened.grants).toEqual(doc.grants); + expect(reopened.rejected).toEqual(doc.rejected); + expect(reopened.unreadable).toBe(doc.unreadable); + expect(reopened.export()).toEqual(doc.export()); +} + +test("the public exports are createDocument, defineModel and openDocument", () => { + expect(Object.keys(api).sort()).toEqual(["createDocument", "defineModel", "openDocument"]); + expect(defineModel(notes)).toBe(notes); +}); + +test("the saved format vector verifies and reconstructs each reader's single state", async () => { + const vector = JSON.parse(readFileSync(new URL("vector.json", import.meta.url), "utf8")); + for (const [name, backup] of Object.entries(vector.identities as { [name: string]: string })) { + const identity = await restoreIdentity(backup); + const doc = await openDocument(bytes(vector.document), { model: notes, identity }); + expect({ + state: doc.state, + unreadable: doc.unreadable, + rejected: doc.rejected, + permissions: doc.permissions, + }).toEqual(vector.expected[name]); + expect(doc.export()).toEqual(bytes(vector.document)); + expect(doc.head).toBe(vector.head); + expect(doc.grants).toEqual(vector.grants); + expect((await openLedger(doc.export())).head).toBe(doc.head); + } +}); + +test("plaintext needs no permissions and any identity can author when the model accepts", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + expect(doc.permissions).toEqual([]); + expect(doc.grants).toEqual([]); + expect(doc.state).toEqual({ notes: {} }); + doc.stage(put("1", "Alice")); + expect(doc.draft?.state).toEqual({ notes: { 1: "Alice" } }); + expect(doc.state).toEqual({ notes: {} }); + await doc.commit(); + const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); + bobs.stage(put("2", "Bob")); + await bobs.commit(); + expect(bobs.state).toEqual({ notes: { 1: "Alice", 2: "Bob" } }); + const ledger = await openLedger(bobs.export()); + expect(ledger.commits.at(-1)?.proof.signer).toEqual(bob.publicIdentity); + expect(ledger.commits[0].entries[0].payload).toEqual({ + op: "document", + format: 1, + model: "notes", + }); + await agrees(bobs, notes, bob); +}); + +test("the model, rather than a grant, determines application authoring authority", async () => { + const { alice, bob } = await people(); + const model: Model = { + ...notes, + reduce(state, event, context) { + if (context.author.id !== alice.publicIdentity.id) + throw new Error("Application writer required"); + return notes.reduce(state, event, context); + }, + }; + const doc = await createDocument({ model, identity: alice }); + const permission = await doc.createPermission("financial"); + await doc.grantPermission(permission, bob.publicIdentity); + const bobs = await openDocument(doc.export(), { model, identity: bob }); + expect(bobs.permissions[0].canDecrypt).toBe(true); + expect(() => bobs.stage(put("x", "denied"), { permission })).toThrow( + "Application writer required", + ); + const forged = await forge(bobs.export(), bob, [ + { op: "events", version: 1, events: [put("x", "denied")] }, + ]); + const opened = await openDocument(forged, { model, identity: alice }); + expect(opened.state).toEqual({ notes: {} }); + expect(opened.rejected).toEqual([ + expect.objectContaining({ message: "Application writer required" }), + ]); + await agrees(opened, model, alice); +}); + +test("multiple permissions protect records in one application state and do not need unique names", async () => { + const { alice, bob, carol } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + doc.stage(put("public", "plain")); + await doc.commit(); + const financial = await doc.createPermission("records"); + const personal = await doc.createPermission("records"); + expect(personal).not.toBe(financial); + doc.stage(put("financial", "invoice"), { permission: financial }); + await doc.commit(); + doc.stage(put("personal", "private"), { permission: personal }); + await doc.commit(); + await doc.grantPermission(financial, bob.publicIdentity); + const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); + expect(doc.state).toEqual({ + notes: { public: "plain", financial: "invoice", personal: "private" }, + }); + expect(bobs.state).toEqual({ notes: { public: "plain", financial: "invoice" } }); + expect(bobs.unreadable).toBe(1); + expect(bobs.permissions).toEqual([ + { id: financial, name: "records", canDecrypt: true }, + { id: personal, name: "records", canDecrypt: false }, + ]); + expect(() => bobs.stage(put("x", "blind"), { permission: personal })).toThrow(/permission's key/); + bobs.stage(put("bob", "allowed despite partial history")); + await bobs.commit(); + await bobs.grantPermission(financial, carol.publicIdentity); + const carols = await openDocument(bobs.export(), { model: notes, identity: carol }); + expect(carols.state).toEqual(bobs.state); + expect(carols.unreadable).toBe(1); + expect(carols.permissions).toEqual(bobs.permissions); + expect(carols.grants).toEqual(bobs.grants); + await agrees(bobs, notes, bob); +}); + +test("historical grants change reader-relative batch rejection without rewriting any earlier entries", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("financial"); + doc.stage(put("hidden", "old row"), { permission }); + await doc.commit(); + doc.stage({ type: "note.remove", data: { id: "hidden" } }); + await doc.commit(); + const prior = await openLedger(doc.export()); + const partial = await openDocument(doc.export(), { model: notes, identity: bob }); + expect(partial.state).toEqual({ notes: {} }); + expect(partial.unreadable).toBe(1); + expect(partial.rejected).toEqual([expect.objectContaining({ message: "No note hidden" })]); + expect(doc.rejected).toEqual([]); + await doc.grantPermission(permission, bob.publicIdentity); + const whole = await openDocument(doc.export(), { model: notes, identity: bob }); + expect(whole.state).toEqual(doc.state); + expect(whole.unreadable).toBe(0); + expect(whole.rejected).toEqual([]); + expect((await openLedger(doc.export())).commits.slice(0, prior.commits.length)).toEqual( + prior.commits, + ); + await agrees(doc, notes, alice); +}); + +test("future confidentiality uses a new permission while old grants remain effective", async () => { + const { alice, bob, carol } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const old = await doc.createPermission("financial"); + await doc.grantPermission(old, bob.publicIdentity); + doc.stage(put("row", "historical"), { permission: old }); + await doc.commit(); + const next = await doc.createPermission("financial"); + await doc.grantPermission(next, carol.publicIdentity); + doc.stage(put("row", "future"), { permission: next }); + await doc.commit(); + const bobs = await openDocument(doc.export(), { model: notes, identity: bob }); + const carols = await openDocument(doc.export(), { model: notes, identity: carol }); + expect(bobs.state).toEqual({ notes: { row: "historical" } }); + expect(carols.state).toEqual({ notes: { row: "future" } }); + expect(bobs.unreadable).toBe(1); + expect(carols.unreadable).toBe(1); + expect(bobs.grants).toHaveLength(4); + const last = (await openLedger(doc.export())).commits.at(-1)!.entries[0].payload as { + ciphertext: string; + }; + await expect( + decrypt(base64urlnopad.decode(last.ciphertext), await secretOf(doc.export(), bob, old)), + ).rejects.toThrow(); + await agrees(doc, notes, alice); +}); + +test("bad, unrelated, mislabelled and duplicate grants do not poison a later working key", async () => { + const { alice, bob, carol } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("financial"); + const other = await doc.createPermission("personal"); + doc.stage(put("protected", "secret"), { permission }); + await doc.commit(); + const secret = await secretOf(doc.export(), alice, permission); + const unrelated = await generateX25519Identity(); + let document = doc.export(); + const records = [ + { op: "grant", permission, to: bob.publicIdentity.id, ciphertext: "not age" }, + await wrapped(permission, unrelated, bob.publicIdentity), + await wrapped(other, secret, bob.publicIdentity), + await wrapped(permission, secret, carol.publicIdentity), + { op: "grant", permission, to: bob.publicIdentity.id, ciphertext: "", extra: true }, + await wrapped(permission, secret, bob.publicIdentity), + await wrapped(permission, secret, bob.publicIdentity), + await wrapped(permission, unrelated, bob.publicIdentity), + ]; + for (const record of records) document = await forge(document, alice, [record]); + const opened = await openDocument(document, { model: notes, identity: bob }); + expect(opened.state).toEqual({ notes: { protected: "secret" } }); + expect(opened.unreadable).toBe(0); + expect(opened.permissions.map((p) => p.canDecrypt)).toEqual([true, false]); + expect(opened.rejected).toEqual([ + expect.objectContaining({ message: "Malformed Concord record" }), + ]); + expect(opened.grants).toHaveLength(9); + await opened.grantPermission(permission, carol.publicIdentity); + await agrees(opened, notes, bob); +}); + +test("a grant addressed elsewhere is visible without implying that this reader holds its key", async () => { + const { alice, bob, carol } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("financial"); + const secret = await secretOf(doc.export(), alice, permission); + const record = await wrapped(permission, secret, bob.publicIdentity); + record.to = carol.publicIdentity.id; + const opened = await openDocument(await forge(doc.export(), alice, [record]), { + model: notes, + identity: bob, + }); + expect(opened.grants.at(-1)?.to).toBe(carol.publicIdentity.id); + expect(opened.permissions[0].canDecrypt).toBe(false); +}); + +test("permission declarations cannot rename or redefine an already declared recipient", async () => { + const { alice } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("first"); + const secret = await secretOf(doc.export(), alice, permission); + const document = await forge(doc.export(), alice, [ + { op: "permission", name: "redefined", recipient: permission }, + await wrapped(permission, secret, alice.publicIdentity), + ]); + const opened = await openDocument(document, { model: notes, identity: alice }); + expect(opened.permissions).toEqual([{ id: permission, name: "first", canDecrypt: true }]); + expect(opened.rejected).toEqual([ + expect.objectContaining({ message: "Permission already declared" }), + ]); + expect(opened.grants).toHaveLength(1); +}); + +test("application commits have one visibility scope and reject a failing readable batch atomically", async () => { + const { alice } = await people(); + for (const protectedBatch of [false, true]) { + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("financial"); + const events = [put("lost", "not adopted"), { type: "note.remove", data: { id: "missing" } }]; + const record = protectedBatch + ? await encrypted(permission, events) + : { op: "events", version: 1, events }; + const opened = await openDocument(await forge(doc.export(), alice, [record]), { + model: notes, + identity: alice, + }); + expect(opened.state).toEqual({ notes: {} }); + expect(opened.rejected).toEqual([expect.objectContaining({ message: "No note missing" })]); + opened.stage(put("later", "accepted")); + await opened.commit(); + expect(opened.state).toEqual({ notes: { later: "accepted" } }); + await agrees(opened, notes, alice); + } + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("financial"); + const mixed = await forge(doc.export(), alice, [ + { op: "events", version: 1, events: [put("public", "not adopted")] }, + await encrypted(permission, [put("private", "not adopted")]), + ]); + const opened = await openDocument(mixed, { model: notes, identity: alice }); + expect(opened.state).toEqual({ notes: {} }); + expect(opened.rejected).toHaveLength(1); +}); + +test("drafts require one scope, explicit encryption, and no pending events during key operations", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("financial"); + const other = await doc.createPermission("personal"); + doc.stage(put("1", "encrypted"), { permission }); + expect(() => doc.stage(put("2", "plain"))).toThrow(/one permission/); + expect(() => doc.stage(put("2", "other"), { permission: other })).toThrow(/one permission/); + await expect(doc.createPermission("later")).rejects.toThrow(/draft/); + await expect(doc.grantPermission(permission, bob.publicIdentity)).rejects.toThrow(/draft/); + await doc.commit(); + doc.stage(put("2", "plain")); + expect(doc.draft?.permission).toBeNull(); + doc.discard(); + expect(doc.draft).toBeNull(); + await expect(doc.commit()).rejects.toThrow(/Nothing is staged/); +}); + +test("model ID is fixed, event versions are historical context, and no signer controls upgrades", async () => { + const { alice, bob } = await people(); + const versioned = defineModel({ + id: "versions", + version: 1, + initial: () => [], + reduce(state, _event, context) { + return [...(state as Json[]), { version: context.version, author: context.author.id }]; + }, + }); + const doc = await createDocument({ model: versioned, identity: alice }); + doc.stage({ type: "v1", data: null }); + await doc.commit(); + const upgraded = await openDocument(doc.export(), { + model: { ...versioned, version: 2 }, + identity: bob, + }); + upgraded.stage({ type: "v2", data: null }); + await upgraded.commit(); + expect(upgraded.state).toEqual([ + { version: 1, author: alice.publicIdentity.id }, + { version: 2, author: bob.publicIdentity.id }, + ]); + await expect( + openDocument(upgraded.export(), { model: versioned, identity: alice }), + ).rejects.toThrow(/needs model version 2/); + const oldBatch = await forge(upgraded.export(), alice, [ + { op: "events", version: 1, events: [{ type: "v1-again", data: null }] }, + ]); + const opened = await openDocument(oldBatch, { + model: { ...versioned, version: 2 }, + identity: alice, + }); + expect((opened.state as Json[]).at(-1)).toEqual({ version: 1, author: alice.publicIdentity.id }); + await expect( + openDocument(doc.export(), { model: { ...versioned, id: "unrelated" }, identity: alice }), + ).rejects.toThrow(/uses model versions/); +}); + +test("unreadable encrypted versions make no compatibility claim, while a historical grant exposes unsupported versions", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: { ...notes, version: 2 }, identity: alice }); + const permission = await doc.createPermission("financial"); + doc.stage(put("2", "new version"), { permission }); + await doc.commit(); + const older = await openDocument(doc.export(), { model: notes, identity: bob }); + expect(older.state).toEqual({ notes: {} }); + expect(older.unreadable).toBe(1); + await doc.grantPermission(permission, bob.publicIdentity); + await expect(openDocument(doc.export(), { model: notes, identity: bob })).rejects.toThrow( + /needs model version 2/, + ); + expect((await openLedger(doc.export())).head).toBe(doc.head); +}); + +test("closed records reject extra fields, unknown permissions and unrelated entry kinds without changing accepted state", async () => { + const { alice } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const permission = (await identityToRecipient(await generateX25519Identity())) as PermissionId; + const records: JsonObject[][] = [ + [{ op: "events", version: 1, events: [], extra: true }], + [{ op: "events", version: 0, events: [put("x", "bad")] }], + [{ op: "events", version: 1, events: [] }], + [{ op: "events", version: 1, events: [{ ...put("x", "bad"), extra: 1 }] }], + [{ op: "encrypted", permission, ciphertext: "bad" }], + [{ op: "grant", permission, to: alice.publicIdentity.id, ciphertext: "bad" }], + [{ op: "permission", name: "alone", recipient: permission }], + [{ op: "document", format: 1, model: "notes" }], + [{ op: "unknown" }], + ]; + for (const payload of records) { + const opened = await openDocument(await forge(doc.export(), alice, payload), { + model: notes, + identity: alice, + }); + expect(opened.state).toEqual(doc.state); + expect(opened.permissions).toEqual([]); + expect(opened.rejected).toHaveLength(1); + } + const opened = await openDocument( + await forge( + doc.export(), + alice, + [{ op: "events", version: 1, events: [put("x", "other kind")] }], + "another.application", + ), + { model: notes, identity: alice }, + ); + expect(opened.rejected[0].message).toMatch(/only Concord entries/); +}); + +test("malformed encrypted records reject when a key is held and count as unreadable without it", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("financial"); + const bodies = [ + bytes('{"version":1,"events":[]}'), + bytes('{"version":1,"events":[{"type":"note.put","data":{"id":"1","title":0.5}}]}'), + new Uint8Array([255]), + ]; + for (const body of bodies) { + const ciphertext = base64urlnopad.encode(await encrypt(body, [permission])); + const document = await forge(doc.export(), alice, [ + { op: "encrypted", permission, ciphertext }, + ]); + const holder = await openDocument(document, { model: notes, identity: alice }); + const outsider = await openDocument(document, { model: notes, identity: bob }); + expect(holder.rejected).toHaveLength(1); + expect(holder.unreadable).toBe(0); + expect(outsider.rejected).toEqual([]); + expect(outsider.unreadable).toBe(1); + } +}); + +test("Ledger verifies the document and Armour independently decrypts grants and protected event batches", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("financial"); + doc.stage(put("secret", "content"), { permission }); + await doc.commit(); + const secret = await secretOf(doc.export(), alice, permission); + expect(await identityToRecipient(secret)).toBe(permission); + const record = (await openLedger(doc.export())).commits.at(-1)!.entries[0].payload as { + ciphertext: string; + }; + expect( + JSON.parse( + new TextDecoder().decode(await decrypt(base64urlnopad.decode(record.ciphertext), secret)), + ), + ).toEqual({ version: 1, events: [put("secret", "content")] }); + const envelope = await encrypt(doc.export(), [alice.publicIdentity, bob.publicIdentity]); + const unlocked = await openDocument(await decrypt(envelope, alice), { + model: notes, + identity: alice, + }); + expect(unlocked.state).toEqual(doc.state); + expect(unlocked.head).toBe(doc.head); + const outsider = await openDocument(await decrypt(envelope, bob), { + model: notes, + identity: bob, + }); + expect(outsider.unreadable).toBe(1); +}); + +test("the raw document reveals permission names, recipients and grant targets but not protected values", async () => { + const { alice, bob } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("financial"); + await doc.grantPermission(permission, bob.publicIdentity); + doc.stage(put("public-id", "public-title")); + await doc.commit(); + doc.stage(put("hidden-id", "hidden-title"), { permission }); + await doc.commit(); + const raw = new TextDecoder().decode(doc.export()); + for (const visible of [ + "financial", + permission, + bob.publicIdentity.id, + alice.publicIdentity.publicKey, + "public-id", + "public-title", + ]) + expect(raw).toContain(visible); + for (const hidden of ["hidden-id", "hidden-title", "AGE-SECRET-KEY-"]) + expect(raw).not.toContain(hidden); +}); + +test("tampering, an unrelated Ledger and obsolete declarations do not open", async () => { + const { alice } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const tampered = doc.export(); + tampered[tampered.length - 40] ^= 1; + await expect(openDocument(tampered, { model: notes, identity: alice })).rejects.toThrow(); + const declarations: (JsonObject | null)[] = [ + null, + { op: "create", group: "old", model: "notes", version: 1 }, + { op: "document", format: 2, model: "notes" }, + { op: "document", format: 1, model: "notes", extra: true }, + ]; + for (const payload of declarations) { + const history = await createLedger({ signer: alice, entries: [{ kind: "concord", payload }] }); + await expect(openDocument(history.export(), { model: notes, identity: alice })).rejects.toThrow( + /format 1/, + ); + } +}); + +test.each([false, true])( + "every pending write isolates all mutations while keeping reads available (encrypted=%s)", + async (isEncrypted) => { + const { alice, bob, carol } = await people(); + for (const operation of ["commit", "createPermission", "grantPermission"] as const) { + let hold: Promise | undefined; + const identity: Identity = { + ...alice, + sign: async (data) => { + await hold; + return alice.sign(data); + }, + }; + const doc = await createDocument({ model: notes, identity }); + const permission = await doc.createPermission("financial"); + if (operation === "commit") doc.stage(put("1", "saved"), isEncrypted ? { permission } : {}); + const before = { + head: doc.head, + bytes: doc.export(), + state: doc.state, + draft: doc.draft, + permissions: doc.permissions, + grants: doc.grants, + }; + let release!: () => void; + hold = new Promise((resolve) => { + release = resolve; + }); + const pending = + operation === "commit" + ? doc.commit() + : operation === "createPermission" + ? doc.createPermission("other") + : doc.grantPermission(permission, bob.publicIdentity); + try { + expect(() => doc.stage(put("x", "blocked"))).toThrow(/write is in progress/); + expect(() => doc.discard()).toThrow(/write is in progress/); + await expect(doc.commit()).rejects.toThrow(/write is in progress/); + await expect(doc.createPermission("blocked")).rejects.toThrow(/write is in progress/); + await expect(doc.grantPermission(permission, carol.publicIdentity)).rejects.toThrow( + /write is in progress/, + ); + expect(doc.head).toBe(before.head); + expect(doc.export()).toEqual(before.bytes); + expect(doc.state).toBe(before.state); + expect(doc.draft).toBe(before.draft); + expect(doc.permissions).toEqual(before.permissions); + expect(doc.grants).toEqual(before.grants); + } finally { + release(); + await pending; + } + await agrees(doc, notes, alice); + expect(doc.head).not.toBe(before.head); + doc.stage(put("after", "unlocked")); + await doc.commit(); + expect(doc.state.notes.after).toBe("unlocked"); + } + }, +); + +test.each([false, true])( + "failed signing keeps state and the exact draft for retry, including key operations (encrypted=%s)", + async (isEncrypted) => { + const { alice, bob } = await people(); + let fail = false; + const identity: Identity = { + ...alice, + sign(data) { + if (fail) throw new Error("Signing unavailable"); + return alice.sign(data); + }, + }; + const doc = await createDocument({ model: notes, identity }); + const permission = await doc.createPermission("financial"); + doc.stage(put("1", "retry"), isEncrypted ? { permission } : {}); + const before = { bytes: doc.export(), state: doc.state, draft: doc.draft }; + fail = true; + await expect(doc.commit()).rejects.toThrow("Signing unavailable"); + expect(doc.export()).toEqual(before.bytes); + expect(doc.state).toBe(before.state); + expect(doc.draft).toBe(before.draft); + fail = false; + await doc.commit(); + const committed = doc.export(); + fail = true; + await expect(doc.createPermission("failed")).rejects.toThrow("Signing unavailable"); + await expect(doc.grantPermission(permission, bob.publicIdentity)).rejects.toThrow( + "Signing unavailable", + ); + expect(doc.export()).toEqual(committed); + expect(doc.permissions).toHaveLength(1); + expect(doc.grants).toHaveLength(1); + fail = false; + await doc.grantPermission(permission, bob.publicIdentity); + await agrees(doc, notes, alice); + }, +); + +test("failed encryption preserves the draft and releases the write guard", async () => { + const { alice } = await people(); + const doc = await createDocument({ model: notes, identity: alice }); + const permission = await doc.createPermission("financial"); + doc.stage(put("1", "retry"), { permission }); + const before = { bytes: doc.export(), draft: doc.draft }; + const random = vi.spyOn(globalThis.crypto, "getRandomValues").mockImplementationOnce(() => { + throw new Error("Encryption randomness unavailable"); + }); + try { + await expect(doc.commit()).rejects.toThrow("Encryption randomness unavailable"); + } finally { + random.mockRestore(); + } + expect(doc.export()).toEqual(before.bytes); + expect(doc.draft).toBe(before.draft); + await doc.commit(); + await agrees(doc, notes, alice); +}); + +test("a failed local replay never adopts the candidate history and permits retry", async () => { + const { alice } = await people(); + let unavailable = false; + const model: Model = { + ...notes, + reduce(state, event, context) { + if (unavailable) throw new Error("Reducer unavailable"); + return notes.reduce(state, event, context); + }, + }; + const doc = await createDocument({ model, identity: alice }); + doc.stage(put("1", "retry")); + const before = { bytes: doc.export(), draft: doc.draft, state: doc.state }; + unavailable = true; + await expect(doc.commit()).rejects.toThrow(/not accepted/); + expect(doc.export()).toEqual(before.bytes); + expect(doc.draft).toBe(before.draft); + expect(doc.state).toBe(before.state); + unavailable = false; + await doc.commit(); + await agrees(doc, model, alice); +}); + +test("permission creation adopts nothing when its creator grant cannot be recovered", async () => { + const { alice } = await people(); + let unlocked = false; + const identity: Identity = { + ...alice, + withX25519Secret: (use) => { + if (!unlocked) throw new Error("Decryption unavailable"); + return alice.withX25519Secret(use); + }, + }; + const doc = await createDocument({ model: notes, identity }); + const before = doc.export(); + await expect(doc.createPermission("records")).rejects.toThrow(/creator grant/); + expect(doc.export()).toEqual(before); + expect(doc.permissions).toEqual([]); + expect(doc.grants).toEqual([]); + unlocked = true; + const permission = await doc.createPermission("records"); + expect(doc.permissions).toEqual([{ id: permission, name: "records", canDecrypt: true }]); + await agrees(doc, notes, alice); +}); + +test.each([false, true])( + "invalid reducer output rejects a readable batch atomically and later batches still apply (encrypted=%s)", + async (isEncrypted) => { + const { alice } = await people(); + const model: Model = { + ...notes, + reduce(state, event, context) { + if (event.type === "invalid.result") return { notes: undefined } as unknown as Notes; + return notes.reduce(state, event, context); + }, + }; + const doc = await createDocument({ model, identity: alice }); + const permission = await doc.createPermission("records"); + const events = [put("lost", "not adopted"), { type: "invalid.result", data: null }]; + const record = isEncrypted + ? await encrypted(permission, events) + : { op: "events", version: 1, events }; + const opened = await openDocument(await forge(doc.export(), alice, [record]), { + model, + identity: alice, + }); + expect(opened.state).toEqual({ notes: {} }); + expect(opened.rejected).toHaveLength(1); + opened.stage(put("kept", "later")); + await opened.commit(); + expect(opened.state).toEqual({ notes: { kept: "later" } }); + await agrees(opened, model, alice); + }, +); 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/review.test.ts b/packages/concord/test/review.test.ts new file mode 100644 index 0000000..8e51c4f --- /dev/null +++ b/packages/concord/test/review.test.ts @@ -0,0 +1,418 @@ +import { expect, test } from "vite-plus/test"; +import { createIdentity, type Identity } from "@ternent/identity"; +import { createWriter, openLedger } from "@ternent/ledger"; +import { + createDocument, + defineModel, + openDocument, + type Json, + type Event, + type Model, +} from "../src/index.js"; + +const values = defineModel({ + id: "values", + version: 1, + initial: () => null, + reduce: (_state, event) => event.data, +}); +const put = (data: Json): Event => ({ type: "put", data }); +async function database(model: Model, identity: Identity, encrypted: boolean) { + const doc = await createDocument({ model, identity }); + const options = encrypted ? { permission: await doc.createPermission("records") } : {}; + return { doc, options }; +} +function attempt(change: () => void) { + try { + change(); + } catch { + /* Immutable values may reject mutation. */ + } +} + +const invalidValues: unknown[] = [ + Symbol("invalid"), + Promise.resolve(null), + { toJSON: () => 1 }, + 0.5, + -0, + Number.MAX_SAFE_INTEGER + 1, + NaN, + Infinity, + "\ud800", + { "\udfff": true }, + undefined, + 1n, + () => 1, + new Date(), + new Uint8Array(1), + new Map(), + { value: undefined }, + [undefined], + Object.create(null), + Object.freeze({ nested: { bad: undefined } }), +]; +const cyclic: { self?: unknown } = {}; +cyclic.self = cyclic; +invalidValues.push(cyclic); +const sparse: Json[] = []; +sparse.length = 1; +invalidValues.push(sparse); + +test.each([false, true])( + "invalid event and state values reject consistently (encrypted=%s)", + async (encrypted) => { + const alice = await createIdentity(); + const { doc, options } = await database(values, alice, encrypted); + doc.stage(put("kept"), options); + const draft = doc.draft; + const head = doc.head; + for (const value of invalidValues) { + expect(() => doc.stage(put(value as Json), options)).toThrow(); + expect(doc.draft).toBe(draft); + expect(doc.head).toBe(head); + await expect( + createDocument({ model: { ...values, initial: () => value as Json }, identity: alice }), + ).rejects.toThrow(); + const bad = await createDocument({ + model: { ...values, reduce: () => value as Json }, + identity: alice, + }); + expect(() => bad.stage(put(null))).toThrow(); + expect(bad.draft).toBeNull(); + expect(bad.state).toBeNull(); + } + for (const type of ["", "\ud800", "x".repeat(129)]) + expect(() => doc.stage({ type, data: null }, options)).toThrow(); + await doc.commit(); + expect(doc.state).toBe("kept"); + }, +); + +test.each([false, true])( + "nested JSON, integer boundaries and Unicode retain the same semantics (encrypted=%s)", + async (encrypted) => { + const alice = await createIdentity(); + const { doc, options } = await database(values, alice, encrypted); + const inputs: Json[] = [ + null, + true, + false, + 0, + Number.MIN_SAFE_INTEGER, + Number.MAX_SAFE_INTEGER, + "é\u0000😀", + { "10": [1, { "2": "漢字" }], "2": null }, + JSON.parse('{"__proto__":{"value":1}}'), + ]; + for (const data of inputs) { + doc.stage(put(data), options); + expect(doc.draft?.state).toEqual(data); + await doc.commit(); + expect(doc.state).toEqual(data); + expect((await openDocument(doc.export(), { model: values, identity: alice })).state).toEqual( + data, + ); + } + }, +); + +test.each([false, true])( + "author serialization agrees during staging, incremental commits and reopening (encrypted=%s)", + async (encrypted) => { + const alice = await createIdentity(); + const expectedAuthor = JSON.stringify(alice.publicIdentity); + const model = defineModel({ + id: "authors", + version: 1, + initial: () => [] as string[], + reduce(state, _event, { author }) { + const serialized = JSON.stringify(author); + if (serialized !== expectedAuthor) throw new Error("Unexpected author"); + return [...state, serialized]; + }, + }); + const { doc, options } = await database(model, alice, encrypted); + doc.stage(put(null), options); + expect(doc.draft?.state).toEqual([expectedAuthor]); + await doc.commit(); + expect(doc.state).toEqual([expectedAuthor]); + const reopened = await openDocument(doc.export(), { model, identity: alice }); + expect(reopened.rejected).toEqual([]); + expect(reopened.state).toEqual(doc.state); + reopened.stage(put(null), options); + expect(reopened.draft?.state).toEqual([expectedAuthor, expectedAuthor]); + await reopened.commit(); + expect(reopened.state).toEqual([expectedAuthor, expectedAuthor]); + const again = await openDocument(reopened.export(), { model, identity: alice }); + expect(again.rejected).toEqual([]); + expect(again.state).toEqual(reopened.state); + }, +); + +test.each([false, true])( + "object key order and input ownership match staging and replay (encrypted=%s)", + async (encrypted) => { + const alice = await createIdentity(); + const model = defineModel({ + ...values, + reduce: (_state, event) => Object.keys(event.data as object), + }); + const { doc, options } = await database(model, alice, encrypted); + const data = { z: 1, a: 2, "10": 3, "2": 4 }; + doc.stage(put(data), options); + expect(doc.draft?.state).toEqual(["2", "10", "a", "z"]); + const pending = doc.commit(); + data.z = 9; + await pending; + expect((await openDocument(doc.export(), { model, identity: alice })).state).toEqual(doc.state); + }, +); + +test.each([false, true])( + "public views cannot mutate capability metadata, grants, drafts, events or state (encrypted=%s)", + async (encrypted) => { + const alice = await createIdentity(); + const bob = await createIdentity(); + const { doc, options } = await database(values, alice, encrypted); + const permission = options.permission ?? (await doc.createPermission("public metadata")); + const before = { permissions: doc.permissions, grants: doc.grants }; + attempt(() => { + Reflect.set(doc.permissions[0], "name", "changed"); + }); + attempt(() => { + Reflect.set(doc.permissions[0], "canDecrypt", false); + }); + attempt(() => { + Reflect.set(doc.permissions, "length", 0); + }); + attempt(() => { + Reflect.set(doc.grants[0], "to", bob.publicIdentity.id); + }); + attempt(() => { + Reflect.set(doc.grants, "length", 0); + }); + expect(doc.permissions).toEqual(before.permissions); + expect(doc.grants).toEqual(before.grants); + const data = { nested: { value: 1 } }; + doc.stage(put(data), options); + data.nested.value = 9; + const draft = doc.draft!; + attempt(() => { + Reflect.set(draft, "permission", null); + }); + attempt(() => { + Reflect.set(draft.events, "length", 0); + }); + attempt(() => { + Reflect.set(draft.events[0], "type", "changed"); + }); + attempt(() => { + (draft.events[0].data as typeof data).nested.value = 9; + }); + attempt(() => { + (draft.state as typeof data).nested.value = 9; + }); + await doc.commit(); + attempt(() => { + (doc.state as typeof data).nested.value = 9; + }); + expect(doc.state).toEqual({ nested: { value: 1 } }); + expect((await openDocument(doc.export(), { model: values, identity: alice })).state).toEqual( + doc.state, + ); + await doc.grantPermission(permission, bob.publicIdentity); + }, +); + +test("rejection views cannot remove or rewrite reader-relative evidence", async () => { + const alice = await createIdentity(); + const model = { + ...values, + reduce: () => { + throw new Error("Application refusal"); + }, + }; + const doc = await createDocument({ model, identity: alice }); + const writer = createWriter(await openLedger(doc.export()), alice); + writer.append({ kind: "concord", payload: { op: "events", version: 1, events: [put(1)] } }); + const opened = await openDocument((await writer.commit()).export(), { model, identity: alice }); + attempt(() => { + Reflect.set(opened.rejected[0], "message", "changed"); + }); + attempt(() => { + Reflect.set(opened.rejected, "length", 0); + }); + expect(opened.rejected).toEqual([expect.objectContaining({ message: "Application refusal" })]); + await opened.createPermission("still independent"); + expect(opened.rejected).toHaveLength(1); +}); + +test("create and open capture the model and input identity before yielding", async () => { + const alice = await createIdentity(); + const bob = await createIdentity(); + const model = { ...values }; + const creating = createDocument({ model, identity: alice }); + model.id = "changed"; + model.version = 9; + model.initial = () => "changed"; + model.reduce = () => "changed"; + const doc = await creating; + expect(doc.state).toBeNull(); + doc.stage(put("original")); + await doc.commit(); + expect(doc.state).toBe("original"); + const input = { model: { ...values }, identity: alice }; + const opening = openDocument(doc.export(), input); + input.model.id = "changed"; + input.model.version = 9; + input.model.reduce = () => "changed"; + input.identity = bob; + const opened = await opening; + opened.stage(put("still original")); + await opened.commit(); + expect(opened.state).toBe("still original"); + expect((await openLedger(opened.export())).commits.at(-1)?.proof.signer).toEqual( + alice.publicIdentity, + ); +}); + +test("model definitions are validated at create and open", async () => { + const alice = await createIdentity(); + const doc = await createDocument({ model: values, identity: alice }); + for (const change of [ + { id: "" }, + { id: "\ud800" }, + { version: 0 }, + { version: 1.5 }, + { version: Infinity }, + { initial: null }, + { reduce: null }, + ]) { + const model = { ...values, ...change } as typeof values; + await expect(createDocument({ model, identity: alice })).rejects.toThrow(/model/i); + await expect(openDocument(doc.export(), { model, identity: alice })).rejects.toThrow(/model/i); + } +}); + +test("identity fields and callbacks and grant targets are captured before asynchronous work", async () => { + const alice = await createIdentity(); + const bob = await createIdentity(); + const identity = { ...alice, publicIdentity: { ...alice.publicIdentity } }; + const creating = createDocument({ model: values, identity }); + identity.publicIdentity = { ...bob.publicIdentity }; + identity.sign = bob.sign.bind(bob); + identity.withX25519Secret = bob.withX25519Secret.bind(bob); + const doc = await creating; + const permission = await doc.createPermission("records"); + const target = { ...bob.publicIdentity }; + const granting = doc.grantPermission(permission, target); + target.id = alice.publicIdentity.id; + target.publicKey = alice.publicIdentity.publicKey; + await granting; + doc.stage(put("captured"), { permission }); + await doc.commit(); + expect(doc.grants.at(-1)?.to).toBe(bob.publicIdentity.id); + expect((await openLedger(doc.export())).commits.at(-1)?.proof.signer).toEqual( + alice.publicIdentity, + ); + expect((await openDocument(doc.export(), { model: values, identity: bob })).state).toBe( + "captured", + ); +}); + +test("initial and reducer outputs have no mutable aliases, including pre-frozen outer objects", async () => { + const alice = await createIdentity(); + const initial = Object.freeze({ nested: { value: 0 } }); + let output = { nested: { value: 0 } }; + const model = defineModel({ + ...values, + initial: () => initial, + reduce: (_state, event) => { + output = { nested: { value: event.data as number } }; + return output; + }, + }); + const doc = await createDocument({ model, identity: alice }); + initial.nested.value = 9; + expect(doc.state).toEqual({ nested: { value: 0 } }); + doc.stage(put(1)); + output.nested.value = 9; + expect(doc.draft?.state).toEqual({ nested: { value: 1 } }); + await doc.commit(); + output.nested.value = 9; + expect(doc.state).toEqual({ nested: { value: 1 } }); +}); + +test("captured branches are shared safely between successive states", async () => { + const alice = await createIdentity(); + const model = defineModel({ + id: "sharing", + version: 1, + initial: () => ({ left: { value: 0 }, right: { value: 0 } }), + reduce: (state, event) => ({ left: { value: event.data as number }, right: state.right }), + }); + const doc = await createDocument({ model, identity: alice }); + const first = doc.state; + doc.stage(put(1)); + expect(doc.draft?.state.right).toBe(first.right); + expect(doc.draft?.state.left).not.toBe(first.left); + await doc.commit(); + expect(doc.state.right).toBe(first.right); + expect(first.left.value).toBe(0); + expect(Object.isFrozen(first.right)).toBe(true); +}); + +test("null draft state is retained when the next event is staged", async () => { + const alice = await createIdentity(); + const model: Model = { + ...values, + initial: () => false, + reduce: (state, event) => (event.type === "null" ? null : state), + }; + const doc = await createDocument({ model, identity: alice }); + doc.stage({ type: "null", data: null }); + doc.stage(put(1)); + expect(doc.draft?.state).toBeNull(); + await doc.commit(); + expect(doc.state).toBeNull(); +}); + +test("reducers cannot mutate captured events, accepted state or context", async () => { + const alice = await createIdentity(); + for (const reduce of [ + (_state: Json, event: Event) => { + (event.data as { value: number }).value = 2; + return event.data; + }, + (state: Json) => { + (state as { value: number }).value = 2; + return state; + }, + ]) { + const doc = await createDocument({ + model: { ...values, initial: () => ({ value: 1 }), reduce }, + identity: alice, + }); + expect(() => doc.stage(put({ value: 1 }))).toThrow(TypeError); + expect(doc.state).toEqual({ value: 1 }); + expect(doc.draft).toBeNull(); + } +}); + +test("draft snapshots stay stable and failed staging preserves the current draft", async () => { + const alice = await createIdentity(); + const doc = await createDocument({ model: values, identity: alice }); + doc.stage(put(1)); + const first = doc.draft!; + doc.stage(put(2)); + const second = doc.draft!; + expect(first.events).toEqual([put(1)]); + expect(first.state).toBe(1); + expect(second.events).toEqual([put(1), put(2)]); + expect(() => doc.stage(put(0.5))).toThrow(); + expect(doc.draft).toBe(second); + await doc.commit(); + expect(doc.draft).toBeNull(); + expect((await openDocument(doc.export(), { model: values, identity: alice })).state).toBe(2); +}); 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..09997a5 --- /dev/null +++ b/packages/concord/test/vector.json @@ -0,0 +1,154 @@ +{ + "document": "{\"commits\":[{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"tjB3Ri-9_8FNofuSSpHyow\",\"payload\":{\"format\":1,\"model\":\"notes\",\"op\":\"document\"}}],\"nonce\":\"nX_O6QzV3r2pHiabaGnmBQ\",\"parent\":null},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.222Z\",\"format\":\"seal\",\"signature\":\"R7bsfY6My39caeNnATQFxcIBv0VQGh15ccg22Z5oRtKA3_e838qtMd9u-6E2IytH9bN3FhPlRE__oFPKmu81DQ\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\"publicKey\":\"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\"version\":1},\"subject\":{\"hash\":\"sha256:61a37d1ed8411827f0c485efecfc0101db5579dc8489e55a13335c985aa2ac04\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"ggXdgd00JP4izX6QTSsRPQ\",\"payload\":{\"events\":[{\"data\":{\"id\":\"public\",\"title\":\"Hello\"},\"type\":\"note.put\"}],\"op\":\"events\",\"version\":1}}],\"nonce\":\"OMG5dOYJt4U86yjPRDiTRA\",\"parent\":\"commit:d8f5f53535e4bdc0110622efc2cfcd04248d4b848f24dc13bcf106ffa7e11adc\"},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.251Z\",\"format\":\"seal\",\"signature\":\"DAiqCK9XgWlzDPjiBhBJ4XgEBP0VNOgtmyRJOesOwjERM8givRbs42QkFjJsuJZ-v9WayEsn1IH0xNN2QXBKCQ\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\"publicKey\":\"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\"version\":1},\"subject\":{\"hash\":\"sha256:bef35b9cd23a6ee74ed11496dab72ab7f644558e26f5588f1bb3dfde06a1010c\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"5iqzwF1zDHqRCgmt9inA4A\",\"payload\":{\"name\":\"financial\",\"op\":\"permission\",\"recipient\":\"age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu\"}},{\"kind\":\"concord\",\"nonce\":\"KifeeRlTEkT36_OwyZ8Skg\",\"payload\":{\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSA3aU5uMFhOYkRsZjhzMisrZzlYTVdRaTlvTVQ0ZDJuNDVFV3NCdjlMZkZzCkhraTdNSjFUVStJQTY3dkFKR2pmaDFud0g1bFQxcUhBbGNNTmVUaHVEVGMKLS0tIHp3bG5MNTZod05rMmQ4ZXJNMkdkc1oydFZUSHpuYzhEVlFBY1hFNXIwRVEKRGoYcHBJDiSlTBIgaKcIKLuYVCtD9srquV9-H-_ljt8IR1SFu2BVCN1SLWa4OX8vvDHEjtPfIlKs6g4ez8KwZSb7LIiNwZXrsoRfNg0NfZ6wjOlC74OiMTIiNBQpptow-V8mw-rcjMYXrA\",\"op\":\"grant\",\"permission\":\"age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu\",\"to\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\"}}],\"nonce\":\"7aurjKzhjauyRpCbKKDAsA\",\"parent\":\"commit:11015eb7882dbe170e953b5e44b3f949d612f0a569dcdfbd096715f6afd37985\"},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.272Z\",\"format\":\"seal\",\"signature\":\"S2MktAVBlEkywkuX6fHab0veNy1G9dz9yp0fouSbxGa7P7UbOIVhbiJMXNIv51YNxXD-uZ3latG9T8WtHK6mCA\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\"publicKey\":\"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\"version\":1},\"subject\":{\"hash\":\"sha256:22430cdc6f5335465c987440cdfeb42e142749c0ca52b88ae5ce81660c7eeebe\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"wEtPxWyKdRxAGUdJzaDE0g\",\"payload\":{\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBYcFU3S0U5YWVlalJ0bnVNc0RNajQxem9nemtXNXg3WHdzWTl6UCtXWVU4Cm9BU3ZLSUxFdlpacTIxLzVGc0FpQld6Q1A5TFRlemNwNE1jSGRiclYyWlEKLS0tIHRCMi9oa24zYkllWXhLdlFuV2NURlhMUFFzZnYxbHBBcStSQm1jZWoxRHcKdehCOdTcSi75-c9jt4gslEZXVnyBAPcjQzL5PvIQygFAE6SjXDx6LA3NKdyG8wuMLvjP6q6XchcwpgK8eXbBnagGQ1-adSIjDusnNZfEfZ_kUEYNyS7WX5qhEs8O2PZasif44TCNxZAwC_l-zlm0BYlhC-JrwAzIx6_92PQh\",\"op\":\"encrypted\",\"permission\":\"age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu\"}}],\"nonce\":\"W6NjOQtNrN5__6FsvtTpNQ\",\"parent\":\"commit:24b777c900a79979ec10c4217335281327a8de9f564e16f04ef5eb77ba3e599e\"},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.279Z\",\"format\":\"seal\",\"signature\":\"hjoPV34N0rQ1r7LXMcZYgSP6-8RPyJkujTu5Ise6mkiVp7tHvjC-gpPpNdDfSpphqvydYsnmfTSQ0YHrKgOADw\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\"publicKey\":\"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\"version\":1},\"subject\":{\"hash\":\"sha256:ab5a70e2e7b3088126f716618439d589b88affced917f0f24bf86457ceab9e4a\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"R9mo3LaGbBNtbVXJlxTIvw\",\"payload\":{\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBTY0J4dlhNdGxpOHN0UG10RDNnbU1lTTlhQmpZMXkrR0tPczU3TStTL1JNClh3Vlphd1RIdGxsT045K1pUMGdYZm9obU43b0ZTSVhxL3lYVnZpQVAyQlEKLS0tIDR2SmI3Ukl5aGNFZ1dZdTdnZlQwWGdvNXJURWNyYzdQWWZWcXdVRUdBSDQKIHKVwCzYiS6AWRWXZgc8DylLl1n2Kf0WJPe-vhBLQ3iAhvEMXDorQ9Oas7CurATp9QqK0HwFycDCb2jVF5t7S7i6I75_NLX171FpXRi04vXd9STqwFwbcBxTI9JJLmSDfCFgQlCRJp9SMQ\",\"op\":\"grant\",\"permission\":\"age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu\",\"to\":\"identity:0def39afe4b83ee4c9bb008654bb953b9624fdb3c4fadc04868dd4e545eaa2f8\"}}],\"nonce\":\"OAua80q5tJp2RenTQTJy8A\",\"parent\":\"commit:abd9efe760ffe002ddaaebe9faf0a14c172c5f19e77860719620927608747dc5\"},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.285Z\",\"format\":\"seal\",\"signature\":\"z4YO7a_cFX9pYwcbr46ojdvOZf6iCYtwHDhf-Itzq12mmioKY06P4QbYgP7dqJ56WW3j7VyKwa_2TkS4QTAIBQ\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\"publicKey\":\"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\"version\":1},\"subject\":{\"hash\":\"sha256:f7f897c5e18fcfcceb80580405fa307b263fed521132615d364e18fb823f95f0\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"zV8y1aiDvrQKcxvl-4H6BQ\",\"payload\":{\"name\":\"personal\",\"op\":\"permission\",\"recipient\":\"age1yjx766aglph46z4zthjjxmz64guarn4p78ue69l9rft77253kg0sjs8ln0\"}},{\"kind\":\"concord\",\"nonce\":\"hepdnmU3N4UbkOXtjCnZYQ\",\"payload\":{\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBiWTkvbFdEbk01YmZ5U1Z2WmdGR2ZwSUhJeWdqRTROZW5SbHhUdDZDU1dFCnAwMnBKVlc5M2hpZWErbGUxdEtJTFhlaEljTUNaemtTNnIwRGZPUDZOVmcKLS0tIDd4M2FHZHNsckswL0dnc3cyN3d3R2d0WTdzclpZQVdXS0NjeWZCWmplSlUKcNzU9UqqRwQRlHaOcZoGRQGOCVA7zJqeaqJXB6GseUPX1DbqQp_rtSEURHzRi8aToq1z4Se2RDJPQSDiXZubKqK_UEuMZ2XKkTL257rSRvTdtMQ2TKihM-_g7YvQ0uUTwx3RjTcFTDLwxg\",\"op\":\"grant\",\"permission\":\"age1yjx766aglph46z4zthjjxmz64guarn4p78ue69l9rft77253kg0sjs8ln0\",\"to\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\"}}],\"nonce\":\"BNN2kPNEnSpImPC-0olFJA\",\"parent\":\"commit:aa2a0a6246dc1df4aeb327796de50c4aec156182ad02006845d5c703687fd226\"},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.290Z\",\"format\":\"seal\",\"signature\":\"MdwSBBaCxbME5EHIbulFngpEajOJZRt4QIkjNo9ZObk10bdvsT8AgEY0YW7nLAxUW2oV7YDCPb-gc1PQHyNPDA\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\"publicKey\":\"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\"version\":1},\"subject\":{\"hash\":\"sha256:85150435bf4a2ad343c98019217894b8e8d3c8ce107093c78a1b8a86f1187207\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"Pr93apzj5HpbFPfEbWPo9A\",\"payload\":{\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBWb2hPN0JOMzVIQTZ0ZGM5WXZXekI5UkRBem92QU1xYS9nRnlMcjJFSmtvCkYzYjNjeldGdEFHRWxjUXh3UXdYSHBSQm1KYVRocU0vOUNpTjd1eUpHZzQKLS0tIGRXaW5yYnBDdUtCeTZ2TXJNUUV5RWZXbEpTb0p6eklndG10L1ZMaHlJNGsK8TroejGfzOSIbBVqTKcq5OdiMRGuhQsk1i_HlKsQpjISHP33Sw6oPxx593IWwOHVIITckRYub0LM-RjbxDAHcoq7XknwObIBhx07hezPZ5H51v65FY0uh3qwZYl0_7vlLjQSZiaJsix2saQ03QR_JYk45Ztb01E2fEU\",\"op\":\"encrypted\",\"permission\":\"age1yjx766aglph46z4zthjjxmz64guarn4p78ue69l9rft77253kg0sjs8ln0\"}}],\"nonce\":\"AsNkbb7O01aXJ2_c8A4sIw\",\"parent\":\"commit:5a8e74d753060d05db1b79736b2757b51ad24f3fb539cc60c4603977a9eb6420\"},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.295Z\",\"format\":\"seal\",\"signature\":\"dGASJwnmJrmgYQ1kwM9mDa3_C2BeEIHeMAonfqZFoD1kGJu3-yy90TagKctdPTpExEkHcZHqeZ_4q6tH6KpoDw\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\"publicKey\":\"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\"version\":1},\"subject\":{\"hash\":\"sha256:de684b79de9c1b27bb6a14065f982f4e3588eaa7d40c99c8c25bc5ad45e63fb5\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"TjgXD1NwVhVUvf7zkRK2Sw\",\"payload\":{\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBFYjdtREZMWmNsazhtdCtaalVXS0lwNUFDN0pLSDJqeng0RTFuUGNWVnlvCmhyQitkQlErWmhHSk9WZzU0bFBoWktjeDR2MlZrSGl3OFFIbGVwY25kZmcKLS0tIDBFYU9XMm1wR3owaXhDK1pwYzNTdkE1d0N4NVpOdC9WU2JQa0FLZzk3UmsK2m3ybcPiJf6Zq0OrNmriy6Ybw5fqzu913GphSUh1DCqINqOr3hdoEdlsNCXBdJjVZTKUIgUuq4xOAAS6tjJO7MasgVlFT2_7MSAWbgq79-ukwYL4V9Cp5zdhChEWhh1iWxtuaOLL7E7wtg\",\"op\":\"grant\",\"permission\":\"age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu\",\"to\":\"identity:5daeb69f9da5cb54ec676c6c7a698646b865221ea2e22c6fb7f48182d03c5d50\"}}],\"nonce\":\"HhYH1tjPKF8i7hqO1czuRQ\",\"parent\":\"commit:70b5afa7d2e836cb418e19219f7b5f51ad4fdfcbbfa697bf7d2b6fdedb126bf0\"},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.326Z\",\"format\":\"seal\",\"signature\":\"95OJzNXno8AoKsivGNxblUe0Ls3BoLj1uLna3pV6NG1qNsj2srJiiAjUCssXkhztvqXl5-v7JmC2G_jCEJuCCw\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:0def39afe4b83ee4c9bb008654bb953b9624fdb3c4fadc04868dd4e545eaa2f8\",\"publicKey\":\"YfzYbhd-KcKkkdhcImen2GCR1HOLMYo6PiT2O80V2aE\",\"version\":1},\"subject\":{\"hash\":\"sha256:8f18b366f923a704d31cc0f1ea92e36d971170a3adedfdbca2faafe273c821a7\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"h1JmlECrE1txnN5i06urqA\",\"payload\":{\"name\":\"financial\",\"op\":\"permission\",\"recipient\":\"age14ld5kpmue24dhtc9md32dfqdz9ekkrwvmtjqyvsmrtd7y4u72dxskz2ma7\"}},{\"kind\":\"concord\",\"nonce\":\"peSxSCXGEDMRBvhpkNM4pQ\",\"payload\":{\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSA4Z2xMc1p5S0tqVnJtT1NTMEoxM3IzNURIVWZteEVmS0VpbytqbXdFWVRRCnJuTFFtNDF4K2RCd2xCMUJBSm1CZ01xazBlbldqRzNvbDdCN3JDenEvOEkKLS0tIHpMUWdZSkR2Z0dBNENtRXJpT3ZwcTNKN1JyU0dqZUJlMlRXNHp4Y21BS0EKFO0bb4JJuoKquwGeNZ5LqmUT2hyeH0bjCRVfPjRTJa6idrV_OyJuSpLDqumQJJxIKEnMajrSCJsLHbKRmho8-3D6AJrSY6HBRCN1Dz6cq4cPYfSuLViAcTs1T90FB-ewSrWk-WM4cfzcbQ\",\"op\":\"grant\",\"permission\":\"age14ld5kpmue24dhtc9md32dfqdz9ekkrwvmtjqyvsmrtd7y4u72dxskz2ma7\",\"to\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\"}}],\"nonce\":\"ETjKEFAOl8IPiv-p1N_PPw\",\"parent\":\"commit:277b87d067f35f528639c8003e927d51c0d7fdcbc163bb7856999f7b3779561f\"},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.358Z\",\"format\":\"seal\",\"signature\":\"JUqMXkHMqWtUMM7-KdIUW_qamSt6OM7ITmzBX1YzqLAQzE7wVun4c62EzY66XLhmzqQW11dcD-M9A_R8W9fkCQ\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\"publicKey\":\"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\"version\":1},\"subject\":{\"hash\":\"sha256:606f8a6f888bc218b0d50710e55ed9ae7ae5897a99a03bc0808aa9b16ca764d2\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"WKuNxMYXqOWNBitSDGo8yA\",\"payload\":{\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSBmOS91RXVVVFoySlZuZUthQUpCdkMvWWd5NU05M1JTelhNNVpoSkRtWmhVCjR6cjBGelo5N3Z4czBqM016YktVY01HdTBDak5YTXdTVUpjTkxJTS8vVUEKLS0tIFJlQjZzQVNQVUl5cWdtQzMwdVRIQStjZW5TOTlhL1ZZSlpmdjZIbmFpdVEK5olMe5lh7zb_dYwqO1YUmGAe5jqJ0wpKj3gGqgcKe0ZznKkI5Az27to4SBqwL9q85sjKDJ1w6_ryDwCu13Wsme0X_1KPqCqA0eQf-RgyaHR0P0bPOL-0iqp1x1CyQysUwpyxMfo1AeW9nw\",\"op\":\"grant\",\"permission\":\"age14ld5kpmue24dhtc9md32dfqdz9ekkrwvmtjqyvsmrtd7y4u72dxskz2ma7\",\"to\":\"identity:5daeb69f9da5cb54ec676c6c7a698646b865221ea2e22c6fb7f48182d03c5d50\"}}],\"nonce\":\"6c7dW2AN8XIlhRQiZv7UQg\",\"parent\":\"commit:82d0e5196bee88c642d00b746d476365587b9817672a1225b3e14a6063ed7cb4\"},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.364Z\",\"format\":\"seal\",\"signature\":\"7UCRSvZ4itY375MIpDlY4nrd-AEfFCrUySHLhh48K4flmnu-9AaWkPGnVv_0c3irU01PwEH6yJbt7s_F6sy7CQ\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\"publicKey\":\"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\"version\":1},\"subject\":{\"hash\":\"sha256:bc826d15b3c058f92a407a01cb66cd69a44156c26f08a4cf85eae8387c6ee731\"},\"version\":1}},{\"body\":{\"entries\":[{\"kind\":\"concord\",\"nonce\":\"ElnthFSXWcdfqCy_nxtVCg\",\"payload\":{\"ciphertext\":\"YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0-IFgyNTUxOSB3MFJ2bHNtRnVTTWRlazNsV2NvcVpibDVMc1VYVHFzbDVzTlhnQUE3REVVCklra3M5c1BqQnhBSXRzdlNCZy9yVlUvU0FhQm0yV3B0Y2M2Z2IxK0xYaE0KLS0tIFFiZ0J4NFo5QVFFU3o3SENOY2RwQml6eVpqK0lwNVVvSlJoSW1WQXFpdEEK1gI9anHBs9LP4gJP2-lyZ2gnuHuzGiRRMTJ1Skjq1qSJgUWSrWqr5OVidmngBU8DvV5VH6crVTs5d7iH0ViPsMzMm6tCCf9NExjvtEHPZy3I5azXzM50c9WnEtpSzmQFs7Uoy3qcA8qnqdYNYnijReQBuyk6n8Q-5rTFsg\",\"op\":\"encrypted\",\"permission\":\"age14ld5kpmue24dhtc9md32dfqdz9ekkrwvmtjqyvsmrtd7y4u72dxskz2ma7\"}}],\"nonce\":\"TnGVujiGzVdhq2jnzmED6Q\",\"parent\":\"commit:a2847bf94eea8872b20a7f4c717ae4cc9314280f317408f948d94a718814f07e\"},\"proof\":{\"createdAt\":\"2026-11-28T23:26:30.367Z\",\"format\":\"seal\",\"signature\":\"J9RXUTnWNs_46shIBJXmOnmnKpVfsTHYQGGl4JRq4t1GzK3JZXBau24izKRHdAxJt4mo0PRwBoinVJ3F8sbLBA\",\"signer\":{\"algorithm\":\"Ed25519\",\"id\":\"identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\"publicKey\":\"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\"version\":1},\"subject\":{\"hash\":\"sha256:97775bedb2fb8dc5b5e32d9fa3acd930417583790c7f3ade6bed35a027494786\"},\"version\":1}}],\"format\":\"ledger\",\"version\":2}", + "head": "commit:b8f6a8ad2d142cdccb250a061f0a3a3e55dfbc0a0c181f61e59bab169a041665", + "identities": { + "alice": "{\n \"format\": \"ternent-identity\",\n \"version\": \"2\",\n \"algorithm\": \"Ed25519\",\n \"createdAt\": \"2026-11-28T14:46:01.081Z\",\n \"publicKey\": \"fWYWHbrA1-KM1xZ2xCe_kecRJeRrp-79QBEnLWAxuhU\",\n \"keyId\": \"b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c\",\n \"material\": {\n \"kind\": \"seed\",\n \"seed\": \"yiSJFUAOFcvD09kDG6ViCmWcVb2Q2PbaKXX4_i1tdDs\"\n }\n}", + "bob": "{\n \"format\": \"ternent-identity\",\n \"version\": \"2\",\n \"algorithm\": \"Ed25519\",\n \"createdAt\": \"2026-11-28T14:46:01.107Z\",\n \"publicKey\": \"YfzYbhd-KcKkkdhcImen2GCR1HOLMYo6PiT2O80V2aE\",\n \"keyId\": \"0def39afe4b83ee4c9bb008654bb953b9624fdb3c4fadc04868dd4e545eaa2f8\",\n \"material\": {\n \"kind\": \"seed\",\n \"seed\": \"2iFctLqta_TjzmJ_ZmBJPKawcL0uRAKhTP7g1SL4AGE\"\n }\n}", + "carol": "{\n \"format\": \"ternent-identity\",\n \"version\": \"2\",\n \"algorithm\": \"Ed25519\",\n \"createdAt\": \"2026-11-28T14:46:01.107Z\",\n \"publicKey\": \"I6xOM-1ZaES71uTP9JNyCbGJjV20N9F1xgOb7rJB9II\",\n \"keyId\": \"5daeb69f9da5cb54ec676c6c7a698646b865221ea2e22c6fb7f48182d03c5d50\",\n \"material\": {\n \"kind\": \"seed\",\n \"seed\": \"IigJJsibLodpn9xPIvZXnWw3BkYB5ClAj7B7IPBGqRc\"\n }\n}", + "dave": "{\n \"format\": \"ternent-identity\",\n \"version\": \"2\",\n \"algorithm\": \"Ed25519\",\n \"createdAt\": \"2026-11-28T14:46:01.108Z\",\n \"publicKey\": \"w8eXjmYHqLWB4T7pxyZ74GISoo2RAvooX1HJfOCoNIM\",\n \"keyId\": \"217feeaa1ba1485c73cb115706f12bebdeaec596a5218d9c47b1d08f2add30ee\",\n \"material\": {\n \"kind\": \"seed\",\n \"seed\": \"WRXn06u8iE1PgEWLg7YUm9L5kJqEa-XzWOooG4mfVNg\"\n }\n}" + }, + "grants": [ + { + "entry": "entry:300898adabe38aae8562a8cb02b683dc99810ed826294a52d0f137ccf25b2af2", + "permission": "age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu", + "to": "identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c" + }, + { + "entry": "entry:39251321ec578b90b297c34b9525066b9155f576c43db689b977a28b9d8de0f2", + "permission": "age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu", + "to": "identity:0def39afe4b83ee4c9bb008654bb953b9624fdb3c4fadc04868dd4e545eaa2f8" + }, + { + "entry": "entry:e405d00e666886118fcd2b8e08072b981ceac4e1128908b58a5ae650decc41ac", + "permission": "age1yjx766aglph46z4zthjjxmz64guarn4p78ue69l9rft77253kg0sjs8ln0", + "to": "identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c" + }, + { + "entry": "entry:87e4fee5d58a63908103037304516c51a2d4e4f84df66a0b4c98eaa10c4ec650", + "permission": "age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu", + "to": "identity:5daeb69f9da5cb54ec676c6c7a698646b865221ea2e22c6fb7f48182d03c5d50" + }, + { + "entry": "entry:b91d232f76e4dae101b4509ddd5ba4b9f9da110dbf35947b4e89b6fb2d3659d7", + "permission": "age14ld5kpmue24dhtc9md32dfqdz9ekkrwvmtjqyvsmrtd7y4u72dxskz2ma7", + "to": "identity:b0ff5d1c38650ce20e6146c9289b9298c91cd28fe32acffd5265b62fc461810c" + }, + { + "entry": "entry:8740e64fcbd6d458c3115f5265935c8bfd23e2a37f7ef24c1f164cfd41afa13c", + "permission": "age14ld5kpmue24dhtc9md32dfqdz9ekkrwvmtjqyvsmrtd7y4u72dxskz2ma7", + "to": "identity:5daeb69f9da5cb54ec676c6c7a698646b865221ea2e22c6fb7f48182d03c5d50" + } + ], + "expected": { + "alice": { + "state": { + "notes": { + "future": "Future invoice", + "past": "Historical invoice", + "personal": "Alice only", + "public": "Hello" + } + }, + "unreadable": 0, + "rejected": [], + "permissions": [ + { + "id": "age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu", + "name": "financial", + "canDecrypt": true + }, + { + "id": "age1yjx766aglph46z4zthjjxmz64guarn4p78ue69l9rft77253kg0sjs8ln0", + "name": "personal", + "canDecrypt": true + }, + { + "id": "age14ld5kpmue24dhtc9md32dfqdz9ekkrwvmtjqyvsmrtd7y4u72dxskz2ma7", + "name": "financial", + "canDecrypt": true + } + ] + }, + "bob": { + "state": { + "notes": { + "past": "Historical invoice", + "public": "Hello" + } + }, + "unreadable": 2, + "rejected": [], + "permissions": [ + { + "id": "age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu", + "name": "financial", + "canDecrypt": true + }, + { + "id": "age1yjx766aglph46z4zthjjxmz64guarn4p78ue69l9rft77253kg0sjs8ln0", + "name": "personal", + "canDecrypt": false + }, + { + "id": "age14ld5kpmue24dhtc9md32dfqdz9ekkrwvmtjqyvsmrtd7y4u72dxskz2ma7", + "name": "financial", + "canDecrypt": false + } + ] + }, + "carol": { + "state": { + "notes": { + "future": "Future invoice", + "past": "Historical invoice", + "public": "Hello" + } + }, + "unreadable": 1, + "rejected": [], + "permissions": [ + { + "id": "age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu", + "name": "financial", + "canDecrypt": true + }, + { + "id": "age1yjx766aglph46z4zthjjxmz64guarn4p78ue69l9rft77253kg0sjs8ln0", + "name": "personal", + "canDecrypt": false + }, + { + "id": "age14ld5kpmue24dhtc9md32dfqdz9ekkrwvmtjqyvsmrtd7y4u72dxskz2ma7", + "name": "financial", + "canDecrypt": true + } + ] + }, + "dave": { + "state": { + "notes": { + "public": "Hello" + } + }, + "unreadable": 3, + "rejected": [], + "permissions": [ + { + "id": "age1r4yywaztnseenhpaw8dkvp0vhh90u44rtqmwqs9dv4e74m9vudys9s74wu", + "name": "financial", + "canDecrypt": false + }, + { + "id": "age1yjx766aglph46z4zthjjxmz64guarn4p78ue69l9rft77253kg0sjs8ln0", + "name": "personal", + "canDecrypt": false + }, + { + "id": "age14ld5kpmue24dhtc9md32dfqdz9ekkrwvmtjqyvsmrtd7y4u72dxskz2ma7", + "name": "financial", + "canDecrypt": false + } + ] + } + } +} 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/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/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 3facc49..d64abb8 100644 --- a/packages/identity/README.md +++ b/packages/identity/README.md @@ -1,66 +1,52 @@ # @ternent/identity -[Agent interface guide](llms.txt): public imports, examples and lifecycle contracts. +[Agent interface guide](llms.txt): public imports, examples and contracts. -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. +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. -`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. -``` +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 +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..0942fda --- /dev/null +++ b/packages/identity/test/api.test.ts @@ -0,0 +1,214 @@ +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 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"; + +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(vectors.backup)); + expect(JSON.parse(identity.export())).toEqual(vectors.backup); + expect(identity.publicIdentity).toEqual({ + version: 1, + algorithm: "Ed25519", + publicKey: vectors.backup.publicKey, + id: `identity:${vectors.backup.keyId}`, + }); + expect(hex.encode(await identity.sign(new Uint8Array()))).toBe( + "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", + ); + expect( + await verify( + identity.publicIdentity, + hex.decode(vectors.signedMessageHex), + base64urlnopad.decode(vectors.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(vectors.backup)); + 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, + {}, + { ...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 [ + "", + vectors.backup.material.seed + "!", + vectors.backup.material.seed + "=", + " " + vectors.backup.material.seed, + base64urlnopad.encode(new Uint8Array(31)), + ]) { + await expect( + restoreIdentity(JSON.stringify({ ...vectors.backup, 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..3c5b034 100644 --- a/packages/identity/test/strict.test.ts +++ b/packages/identity/test/strict.test.ts @@ -1,21 +1,16 @@ 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 { + +const vector = JSON.parse(readFileSync(new URL("vectors.json", import.meta.url), "utf8")).seed as { seedHex: string; public: PublicIdentity; x25519SecretHex: string; @@ -23,39 +18,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 +59,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/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/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= 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..8edf5f1 100644 --- a/packages/ledger/src/index.ts +++ b/packages/ledger/src/index.ts @@ -1,28 +1,398 @@ -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}`))); +} + +// The whole batch is checked first, so one bad entry leaves the draft unchanged. +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/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 index d1ea4c3..ce314b3 100644 --- a/packages/seal/CLAUDE.md +++ b/packages/seal/CLAUDE.md @@ -1,8 +1,34 @@ -# 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. +# Working on Seal + +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 + +- 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 f36f4b8..b60362a 100644 --- a/packages/seal/README.md +++ b/packages/seal/README.md @@ -1,120 +1,49 @@ # @ternent/seal -[Agent interface guide](llms.txt): public imports, examples and lifecycle contracts. +[Agent interface guide](llms.txt): public imports, examples and 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). - -## 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` 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. +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. -[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/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 56f6cfa..f21d8e9 100644 --- a/packages/seal/llms.txt +++ b/packages/seal/llms.txt @@ -1,63 +1,25 @@ # @ternent/seal -> Standalone proofs, encrypted artifacts, manifests and the Node seal executable. +> Detached Ed25519 proofs over SHA-256 content hashes. -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. diff --git a/packages/seal/package.json b/packages/seal/package.json index 8f08a1a..9700f8f 100644 --- a/packages/seal/package.json +++ b/packages/seal/package.json @@ -1,11 +1,10 @@ { "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" ], @@ -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" @@ -37,26 +32,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 +47,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 deleted file mode 100644 index 3160c43..0000000 --- a/packages/seal/src/cli.ts +++ /dev/null @@ -1,379 +0,0 @@ -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"; - -type ProcessEnvLike = Record; - -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]"; - -type ParsedArgs = { - _: string[]; - flags: Record; -}; - -type OutputWriter = { - stdout: (value: string) => void; - stderr: (value: string) => void; -}; - -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"); - - 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); - } 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); - } -} - -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 deleted file mode 100644 index 1fd1e71..0000000 --- a/packages/seal/test/cli.test.ts +++ /dev/null @@ -1,216 +0,0 @@ -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 { runCli } from "../src/cli.js"; - -async function createSigningEnv() { - 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; -} - -function createWriter() { - let stdout = ""; - let stderr = ""; - return { - writer: { - stdout: (value: string) => { - stdout += value; - }, - stderr: (value: string) => { - stderr += value; - }, - }, - 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); - }); - - 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(); - - const exitCode = await runCli( - ["sign", "--input", subjectPath, "--recipient", "bad-recipient"], - { env, writer: writer.writer }, - ); - - expect(exitCode).toBe(1); - expect(writer.read().stderr).toContain("Recipient must be a valid age recipient string."); - expect(writer.read().stderr).not.toContain("ARMOUR_"); - }); -}); - -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(""); -}); 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..0251310 100644 --- a/packages/seal/vite.config.ts +++ b/packages/seal/vite.config.ts @@ -5,15 +5,6 @@ export default defineConfig({ ...base, 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" }, }, }); 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== 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 `