@ternent/ledger 0.1.7 → 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 Sam Ternent
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any purpose
6
+ with or without fee is hereby granted, provided that the above copyright notice
7
+ and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # @ternent/ledger
2
+
3
+ A standalone signed append-only log. Create or load a log, stage JSON entries,
4
+ commit them, verify the history and replay it into a projection. Ledger has no
5
+ dependency on Concord, Armour, Seal, a framework, storage or Node filesystem APIs.
6
+
7
+ ```ts
8
+ import { generateSigner } from "@ternent/identity";
9
+ import { createLedger } from "@ternent/ledger";
10
+
11
+ const signer = await generateSigner();
12
+ if (!signer.ok) throw new Error(signer.error.code);
13
+
14
+ const log = await createLedger({ signer: signer.value });
15
+ await log.create({ metadata: { title: "Readings" } });
16
+ await log.append({ kind: "temperature", payload: { value: 21 } });
17
+ await log.commit({ metadata: { source: "sensor" } });
18
+
19
+ const snapshot = await log.export();
20
+ const reader = await createLedger();
21
+ await reader.load(snapshot);
22
+ const report = await reader.verify();
23
+ const entries = await reader.replay();
24
+ ```
25
+
26
+ `create()` immediately signs a genesis commit. It is empty by default; an `entries`
27
+ array can supply initial records atomically. Advanced encrypted-envelope builders
28
+ may supply a 16-byte base64url `nonce` when appending; duplicate nonces in one commit
29
+ are rejected. `append()` and `appendMany()`
30
+ stage entries and update the local preview. `export()` and `verify()` concern the
31
+ committed snapshot only. Replay includes staged entries by default; pass
32
+ `{ includeStaged: false }` for committed-only reconstruction. Each replayed entry
33
+ has `committed` and `commitId` fields, so a preview never masquerades as signed history.
34
+ `clearStaged()` discards the preview without changing committed history.
35
+
36
+ Supply `initialProjection` and a synchronous `projector(projection, entry)` to derive
37
+ your own state. Without them, replay returns the ordered entries. `getState()` gives
38
+ a detached, frozen state; `subscribe()` observes successful changes. Projectors must
39
+ be pure and return portable JSON. Callbacks must not await operations on the same Ledger handle.
40
+
41
+ Mutations are serialized. Inputs are captured when called. Failed validation,
42
+ projection or signing preserves the previous committed snapshot and staged entries.
43
+ Loading while entries are staged rejects with `DRAFT_PENDING`; commit or clear them
44
+ first. Validation and signing failures reject with `Fault`, whose `finding` provides a code
45
+ and phase. Projector exceptions propagate while preserving the previous state.
46
+ Observer exceptions cannot roll back a published state. `destroy()` closes the local
47
+ handle; it does not erase exported history or data held elsewhere.
48
+
49
+ The `ledger` v1 format uses strict canonical JSON, content-addressed entries and
50
+ commits, parent linkage and Ed25519 signatures. A commit signature binds its signer,
51
+ ordered entry IDs, timestamp and metadata. Entry authors bind to their commit signer.
52
+ An explicit signer can append to any valid log: membership, permissions, encryption
53
+ and application rules belong to the host or Concord. Store opaque ciphertext as JSON
54
+ when composing Ledger directly with an encryption library.
55
+
56
+ `verifyLedger(bytes)` checks the full signed history without opening a handle.
57
+ `compareLedgers(a, b)` reports equal, ahead, behind, diverged or unrelated snapshots;
58
+ it never merges or chooses a head. Integrity proves neither freshness nor completeness
59
+ without a remembered head or external anchor. The host owns storage and publication.
60
+
61
+ The specialist `/protocol` export supplies the same concrete Ledger codec, identifiers,
62
+ signature subjects and verifier, without loading the authoring lifecycle. Concord
63
+ consumes Ledger's lifecycle and puts its framework records in this same container;
64
+ it does not maintain a second signed container or commit engine. A Ledger reader
65
+ requires no Concord declarations, model, permissions or group keys to verify history.
66
+
67
+ ## Optional payload codecs
68
+
69
+ Ledger supports Armour integration through explicit payload composition. It has no
70
+ Armour dependency, recipient configuration, key management or automatic decryption.
71
+ `encodePayload(data, codec)` turns portable JSON into a versioned JSON envelope for
72
+ the ordinary `append()` API. `decodePayload(data, codec?)` reads that envelope after
73
+ replay. A codec is just an `id` and optional asynchronous byte `encode`/`decode`
74
+ functions; there is no plugin registry or lifecycle to configure.
75
+ `encodePayload` requires a `LedgerPayloadEncoder`, so reader-only or unknown
76
+ encoding capabilities are rejected by TypeScript. `LedgerPayloadDecoder` describes
77
+ a guaranteed decoder; the general `LedgerPayloadCodec` keeps both methods optional
78
+ for inspection and locked-result handling.
79
+
80
+ ```ts
81
+ import { encodePayload, decodePayload } from "@ternent/ledger";
82
+ import { ageRecipientFromPublicIdentity } from "@ternent/identity";
83
+ import { createAgeCodec, withAgeDecryption } from "@ternent/armour";
84
+
85
+ const identity = withAgeDecryption(signer.value);
86
+ const recipient = ageRecipientFromPublicIdentity(identity.publicIdentity);
87
+ if (!recipient.ok) throw new Error(recipient.error.code);
88
+ const codec = createAgeCodec({ recipients: [recipient.value], reader: identity });
89
+
90
+ await log.append({
91
+ kind: "private-note",
92
+ payload: await encodePayload({ text: "Only the recipients can read this" }, codec),
93
+ });
94
+ await log.commit();
95
+
96
+ const entry = (await log.replay()).at(-1)!;
97
+ const result = await decodePayload(entry.payload.data, codec);
98
+ // { status: "decoded", data: { text: "Only the recipients can read this" } }
99
+ const withoutKeys = await decodePayload(entry.payload.data);
100
+ // { status: "locked", codec: "age" }
101
+ ```
102
+
103
+ Plain JSON returns `{ status: "plain", data }`. A missing or different codec, an
104
+ encode-only codec, or a decoder returning `null` produces a locked result. Armour
105
+ returns `null` when its reader cannot authenticate/decrypt the ciphertext; this does
106
+ not distinguish a wrong key from malformed ciphertext. Codec exceptions propagate.
107
+ Invalid envelopes or decoded JSON reject. Encoding failures reject before append;
108
+ there is no plaintext fallback. The helpers use Ledger's portable JSON rules and
109
+ default byte/depth limits; their optional last argument accepts `maxBytes` and
110
+ `maxDepth`. Limits apply to both decoded JSON and the encoded envelope.
111
+
112
+ The envelope has exactly `format: "ledger-payload"`, `version: 1`, `codec` and
113
+ canonical base64url `data`. This marker is reserved within payloads decoded by this
114
+ helper. The log treats it as opaque JSON; verification, commits, export and raw
115
+ replay require no codec. Decoding never modifies signed bytes or establishes their
116
+ trust. Only payload data is encrypted: entry kind, author, timestamps, metadata and
117
+ history structure remain visible. The host decides which decoded data to project;
118
+ Ledger's synchronous projector continues to receive the recorded payload.
119
+
120
+ Staged entries stay in a simple in-memory array. The consumer chooses when to commit
121
+ and owns any draft autosave or recovery. Ledger has no draft persistence adapter,
122
+ recovery snapshot or restore API. Committed `export()` remains signed-history only;
123
+ external storage and push/pull workflows exchange committed snapshots. See
124
+ [the persistence decision](../../docs/adr/0019-keep-draft-persistence-with-consumers.md).
125
+ No historical `concord-ledger` or former Concord-alpha import adapter is included.
126
+
127
+ ## Container format
128
+
129
+ The container has exactly `format: "ledger"`, `version: 1`, `documentId`, `head`,
130
+ ordered `commits` and ordered `entries`. The genesis commit defines `documentId`;
131
+ `head` is the last commit. Every committed entry is referenced exactly once in order.
132
+ Records and subjects are closed objects; `meta`, commit `metadata` and payload data
133
+ are the explicit JSON slots. Timestamps are signed canonical UTC ISO strings, while
134
+ parent linkage and array order determine history order.
135
+
136
+ Given strict canonical JSON bytes `C(subject)`, IDs are lowercase SHA-256:
137
+
138
+ - Entry: `entry:` + SHA-256(UTF8(`ledger.entry/1`) + NUL + `C(entry.subject)`).
139
+ - Commit: `commit:` + SHA-256(UTF8(`ledger.commit/1`) + NUL + `C(commit.subject)`).
140
+ - Signature: Ed25519 over UTF8(`ledger.signature/1`) + NUL + `C(commit.subject)`.
141
+
142
+ The commit suite is `ledger-ed25519-v1`. Nonces are 16 bytes; signatures are 64 bytes;
143
+ wire bytes use canonical unpadded base64url. Entry authors must equal their commit
144
+ signer's identity ID. Hashes include the full subjects: metadata, parent links,
145
+ nonces, timestamps and ordered entry IDs. Public types define the exact record fields.
146
+
147
+ Build and test with the repository's pinned toolchain. Installed-package checks cover
148
+ Node 22.18, 24 and 26, browser execution, declarations and isolated imports. ISC licensed.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,32 @@
1
- export * from "./ledger.js";
2
- export * from "./types.js";
1
+ import { J as Json, K as CommitId, L as verifyLedger, N as ledgerSignatureMessage, O as hashLedgerCommit, Q as VerificationReport, R as Fault, T as compareLedgers, Y as JsonObject, Z as Relationship, a as LedgerEntryRecord, b as encodeJson, c as LedgerLimits, d as LedgerProjector, f as LedgerReplayEntry, h as LedgerState, i as LedgerCommitSubject, j as inspectLedger, k as hashLedgerEntry, l as LedgerOptions, m as LedgerSnapshot, n as LedgerAppendInput, o as LedgerEntrySubject, p as LedgerSigner, q as EntryId, r as LedgerCommitRecord, s as LedgerInstance, t as CreateLedgerConfig, u as LedgerPayload, x as parseJson, y as canonicalize, z as HistoryError } from "./types-CR2908aA.js";
2
+ export declare function createLedger<P>(config: CreateLedgerConfig<P>): Promise<LedgerInstance<P>>;
3
+ export declare function createLedger(config?: LedgerOptions): Promise<LedgerInstance<LedgerReplayEntry[]>>;
4
+ /** Structural byte codec supplied by the host; Ledger owns no encryption or keys. */
5
+ type LedgerPayloadCodec = {
6
+ readonly id: string;
7
+ encode?(this: void, plaintext: Uint8Array): Promise<Uint8Array>;
8
+ /** null means unavailable to this reader; exceptions remain operational failures. */
9
+ decode?(this: void, encoded: Uint8Array): Promise<Uint8Array | null>;
10
+ };
11
+ type LedgerPayloadEncoder = LedgerPayloadCodec & Required<Pick<LedgerPayloadCodec, "encode">>;
12
+ type LedgerPayloadDecoder = LedgerPayloadCodec & Required<Pick<LedgerPayloadCodec, "decode">>;
13
+ type LedgerEncodedPayload = {
14
+ format: "ledger-payload";
15
+ version: 1;
16
+ codec: string;
17
+ data: string;
18
+ };
19
+ type LedgerDecodedPayload = {
20
+ status: "plain" | "decoded";
21
+ data: Json;
22
+ } | {
23
+ status: "locked";
24
+ codec: string;
25
+ };
26
+ type PayloadLimits = Partial<Pick<LedgerLimits, "maxBytes" | "maxDepth">>;
27
+ /** Encode portable JSON before appending it through the ordinary Ledger API. */
28
+ export declare function encodePayload(data: Json, codec: LedgerPayloadEncoder, options?: PayloadLimits): Promise<LedgerEncodedPayload>;
29
+ /** Decode a replayed payload without changing the signed entry or asserting trust. */
30
+ export declare function decodePayload(payload: Json, codec?: LedgerPayloadCodec, options?: PayloadLimits): Promise<LedgerDecodedPayload>;
31
+ export { type CommitId, type CreateLedgerConfig, type EntryId, Fault, type HistoryError, type Json, type JsonObject, type LedgerAppendInput, type LedgerCommitRecord, type LedgerCommitSubject, type LedgerDecodedPayload, type LedgerEncodedPayload, type LedgerEntryRecord, type LedgerEntrySubject, type LedgerInstance, type LedgerLimits, type LedgerOptions, type LedgerPayload, type LedgerPayloadCodec, type LedgerPayloadDecoder, type LedgerPayloadEncoder, type LedgerProjector, type LedgerReplayEntry, type LedgerSigner, type LedgerSnapshot, type LedgerState, type Relationship, type VerificationReport, canonicalize, compareLedgers, encodeJson, hashLedgerCommit, hashLedgerEntry, inspectLedger, ledgerSignatureMessage, parseJson, verifyLedger };
3
32
  //# sourceMappingURL=index.d.ts.map