attenu-guard 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +202 -0
  3. package/README.md +200 -0
  4. package/SECURITY.md +34 -0
  5. package/bin/attenu-guard.js +4 -0
  6. package/dist/cjs/adapters/langgraph.d.ts +174 -0
  7. package/dist/cjs/adapters/langgraph.d.ts.map +1 -0
  8. package/dist/cjs/adapters/langgraph.js +242 -0
  9. package/dist/cjs/adapters/langgraph.js.map +1 -0
  10. package/dist/cjs/audit.d.ts +82 -0
  11. package/dist/cjs/audit.d.ts.map +1 -0
  12. package/dist/cjs/audit.js +195 -0
  13. package/dist/cjs/audit.js.map +1 -0
  14. package/dist/cjs/authority.d.ts +114 -0
  15. package/dist/cjs/authority.d.ts.map +1 -0
  16. package/dist/cjs/authority.js +238 -0
  17. package/dist/cjs/authority.js.map +1 -0
  18. package/dist/cjs/canonical.d.ts +91 -0
  19. package/dist/cjs/canonical.d.ts.map +1 -0
  20. package/dist/cjs/canonical.js +372 -0
  21. package/dist/cjs/canonical.js.map +1 -0
  22. package/dist/cjs/ceilings.d.ts +211 -0
  23. package/dist/cjs/ceilings.d.ts.map +1 -0
  24. package/dist/cjs/ceilings.js +476 -0
  25. package/dist/cjs/ceilings.js.map +1 -0
  26. package/dist/cjs/chain.d.ts +106 -0
  27. package/dist/cjs/chain.d.ts.map +1 -0
  28. package/dist/cjs/chain.js +0 -0
  29. package/dist/cjs/chain.js.map +1 -0
  30. package/dist/cjs/cli.d.ts +16 -0
  31. package/dist/cjs/cli.d.ts.map +1 -0
  32. package/dist/cjs/cli.js +100 -0
  33. package/dist/cjs/cli.js.map +1 -0
  34. package/dist/cjs/evidence.d.ts +163 -0
  35. package/dist/cjs/evidence.d.ts.map +1 -0
  36. package/dist/cjs/evidence.js +409 -0
  37. package/dist/cjs/evidence.js.map +1 -0
  38. package/dist/cjs/guard.d.ts +186 -0
  39. package/dist/cjs/guard.d.ts.map +1 -0
  40. package/dist/cjs/guard.js +432 -0
  41. package/dist/cjs/guard.js.map +1 -0
  42. package/dist/cjs/index.d.ts +52 -0
  43. package/dist/cjs/index.d.ts.map +1 -0
  44. package/dist/cjs/index.js +99 -0
  45. package/dist/cjs/index.js.map +1 -0
  46. package/dist/cjs/package.json +3 -0
  47. package/dist/cjs/reasons.d.ts +93 -0
  48. package/dist/cjs/reasons.d.ts.map +1 -0
  49. package/dist/cjs/reasons.js +139 -0
  50. package/dist/cjs/reasons.js.map +1 -0
  51. package/dist/cjs/strikes.d.ts +24 -0
  52. package/dist/cjs/strikes.d.ts.map +1 -0
  53. package/dist/cjs/strikes.js +30 -0
  54. package/dist/cjs/strikes.js.map +1 -0
  55. package/dist/cjs/wire.d.ts +83 -0
  56. package/dist/cjs/wire.d.ts.map +1 -0
  57. package/dist/cjs/wire.js +165 -0
  58. package/dist/cjs/wire.js.map +1 -0
  59. package/dist/esm/adapters/langgraph.d.ts +174 -0
  60. package/dist/esm/adapters/langgraph.d.ts.map +1 -0
  61. package/dist/esm/adapters/langgraph.js +199 -0
  62. package/dist/esm/adapters/langgraph.js.map +1 -0
  63. package/dist/esm/audit.d.ts +82 -0
  64. package/dist/esm/audit.d.ts.map +1 -0
  65. package/dist/esm/audit.js +189 -0
  66. package/dist/esm/audit.js.map +1 -0
  67. package/dist/esm/authority.d.ts +114 -0
  68. package/dist/esm/authority.d.ts.map +1 -0
  69. package/dist/esm/authority.js +233 -0
  70. package/dist/esm/authority.js.map +1 -0
  71. package/dist/esm/canonical.d.ts +91 -0
  72. package/dist/esm/canonical.d.ts.map +1 -0
  73. package/dist/esm/canonical.js +359 -0
  74. package/dist/esm/canonical.js.map +1 -0
  75. package/dist/esm/ceilings.d.ts +211 -0
  76. package/dist/esm/ceilings.d.ts.map +1 -0
  77. package/dist/esm/ceilings.js +460 -0
  78. package/dist/esm/ceilings.js.map +1 -0
  79. package/dist/esm/chain.d.ts +106 -0
  80. package/dist/esm/chain.d.ts.map +1 -0
  81. package/dist/esm/chain.js +0 -0
  82. package/dist/esm/chain.js.map +1 -0
  83. package/dist/esm/cli.d.ts +16 -0
  84. package/dist/esm/cli.d.ts.map +1 -0
  85. package/dist/esm/cli.js +97 -0
  86. package/dist/esm/cli.js.map +1 -0
  87. package/dist/esm/evidence.d.ts +163 -0
  88. package/dist/esm/evidence.d.ts.map +1 -0
  89. package/dist/esm/evidence.js +398 -0
  90. package/dist/esm/evidence.js.map +1 -0
  91. package/dist/esm/guard.d.ts +186 -0
  92. package/dist/esm/guard.d.ts.map +1 -0
  93. package/dist/esm/guard.js +427 -0
  94. package/dist/esm/guard.js.map +1 -0
  95. package/dist/esm/index.d.ts +52 -0
  96. package/dist/esm/index.d.ts.map +1 -0
  97. package/dist/esm/index.js +42 -0
  98. package/dist/esm/index.js.map +1 -0
  99. package/dist/esm/package.json +3 -0
  100. package/dist/esm/reasons.d.ts +93 -0
  101. package/dist/esm/reasons.d.ts.map +1 -0
  102. package/dist/esm/reasons.js +134 -0
  103. package/dist/esm/reasons.js.map +1 -0
  104. package/dist/esm/strikes.d.ts +24 -0
  105. package/dist/esm/strikes.d.ts.map +1 -0
  106. package/dist/esm/strikes.js +26 -0
  107. package/dist/esm/strikes.js.map +1 -0
  108. package/dist/esm/wire.d.ts +83 -0
  109. package/dist/esm/wire.d.ts.map +1 -0
  110. package/dist/esm/wire.js +159 -0
  111. package/dist/esm/wire.js.map +1 -0
  112. package/package.json +89 -0
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ /**
3
+ * Authority — the core value object.
4
+ *
5
+ * An Authority is an immutable capability: a set of scopes plus typed `Ceiling`
6
+ * bounds and a TTL. The single most important operation is `meet`: the greatest
7
+ * authority that is within BOTH a parent's authority and a requested one. A
8
+ * child of a delegation can never hold more than the meet — attenuation is a
9
+ * lattice operation, enforced in code, not a convention.
10
+ *
11
+ * The guarantee everything else rests on:
12
+ *
13
+ * meet(parent, requested) <= parent for ALL requested.
14
+ *
15
+ * There is no code path by which a derived child authority can exceed its
16
+ * parent. That is what makes model-proposed authority safe to accept: the
17
+ * proposal is only ever an input to `meet`, and `meet` can only shrink.
18
+ *
19
+ * `isNarrowerThan` is exactly the wire protocol's subsumption relation
20
+ * (draft-asor-wimse-agent-delegation-chain-00), so a chain that verifies offline
21
+ * is one the library would have permitted, and the reverse.
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.Authority = exports.AuthorityError = void 0;
25
+ const canonical_js_1 = require("./canonical.js");
26
+ const ceilings_js_1 = require("./ceilings.js");
27
+ const reasons_js_1 = require("./reasons.js");
28
+ /**
29
+ * Raised for STRUCTURAL failures — bad input or invalid chain state, such as
30
+ * delegating from a revoked or expired node, or a depth/fanout overflow.
31
+ * Deliberately distinct from a policy denial: a denial is a normal outcome,
32
+ * expressed as a `Decision`. A structural error means the caller did something
33
+ * invalid; a denial means the caller asked for something the authority model
34
+ * legitimately refuses.
35
+ */
36
+ class AuthorityError extends Error {
37
+ reason;
38
+ detail;
39
+ constructor(message, reason, detail = {}) {
40
+ super(message);
41
+ this.name = "AuthorityError";
42
+ this.reason = reason;
43
+ this.detail = detail;
44
+ }
45
+ }
46
+ exports.AuthorityError = AuthorityError;
47
+ class Authority {
48
+ /**
49
+ * Permission strings, e.g. `crm.read`. Scopes support one level of prefix
50
+ * wildcard: `crm.*` covers `crm.read` and `crm.write`. A child requesting
51
+ * `crm.read` under a parent holding `crm.*` is allowed; the reverse is not.
52
+ */
53
+ scopes;
54
+ /**
55
+ * At most one ceiling per `key` (last one wins), sorted by key for a
56
+ * deterministic wire form and integrity seal. A dimension with no ceiling is
57
+ * unbounded on that dimension unless a parent in the chain bounds it —
58
+ * attenuation can only add or tighten bounds, never remove one.
59
+ */
60
+ ceilings;
61
+ /** Seconds from issuance. `null` is unbounded (discouraged). */
62
+ ttl;
63
+ constructor(init = {}) {
64
+ this.scopes = new Set(init.scopes ?? []);
65
+ const byKey = new Map();
66
+ for (const c of init.ceilings ?? [])
67
+ byKey.set(String(c.key), c);
68
+ this.ceilings = Array.from(byKey.keys())
69
+ .sort(canonical_js_1.compareCodePoints)
70
+ .map((k) => byKey.get(k));
71
+ this.ttl = init.ttl ?? null;
72
+ }
73
+ byKey() {
74
+ const m = new Map();
75
+ for (const c of this.ceilings)
76
+ m.set(String(c.key), c);
77
+ return m;
78
+ }
79
+ /** The ceiling bound to `key`, or `undefined`. */
80
+ ceiling(key) {
81
+ return this.byKey().get(key);
82
+ }
83
+ // ---- scope helpers ----------------------------------------------------
84
+ /** Does a held scope cover a requested scope? Supports one `x.*` wildcard. */
85
+ static scopeCovers(held, requested) {
86
+ if (held === requested)
87
+ return true;
88
+ if (held.endsWith(".*"))
89
+ return requested.startsWith(held.slice(0, -1)); // keep the dot
90
+ return false;
91
+ }
92
+ coversScope(requested) {
93
+ for (const held of this.scopes) {
94
+ if (Authority.scopeCovers(held, requested))
95
+ return true;
96
+ }
97
+ return false;
98
+ }
99
+ // ---- the lattice ------------------------------------------------------
100
+ /**
101
+ * The greatest authority within BOTH `this` and `other` — the attenuation.
102
+ * This is the only way a child authority is constructed. It is commutative
103
+ * and can only ever shrink relative to either input.
104
+ */
105
+ meet(other) {
106
+ // Scopes: keep a requested scope only if this side covers it, and keep this
107
+ // side's own concrete scopes that the other covers. The net effect is a
108
+ // wildcard-aware intersection, never larger than either side's coverage.
109
+ const merged = new Set();
110
+ for (const s of other.scopes)
111
+ if (this.coversScope(s))
112
+ merged.add(s);
113
+ for (const s of this.scopes)
114
+ if (other.coversScope(s))
115
+ merged.add(s);
116
+ // Remove only REDUNDANT scopes: one covered by a broader wildcard that is
117
+ // also present. This keeps the broadest legitimately-granted authority and
118
+ // only trims duplicates, so a wildcard granted by both sides survives.
119
+ const wildcards = Array.from(merged).filter((s) => s.endsWith(".*"));
120
+ const pruned = new Set(Array.from(merged).filter((s) => !wildcards.some((w) => w !== s && Authority.scopeCovers(w, s))));
121
+ // Ceilings: union of keys. Where BOTH sides bound a key, narrow it; where
122
+ // only one side bounds it, carry that bound through unchanged. A ceiling
123
+ // therefore only ever appears or tightens across a meet, never disappears —
124
+ // exactly the property `isNarrowerThan` checks.
125
+ const mine = this.byKey();
126
+ const theirs = other.byKey();
127
+ const keys = Array.from(new Set([...mine.keys(), ...theirs.keys()])).sort(canonical_js_1.compareCodePoints);
128
+ const ceilings = [];
129
+ for (const k of keys) {
130
+ const a = mine.get(k);
131
+ const b = theirs.get(k);
132
+ ceilings.push(a !== undefined && b !== undefined ? a.narrow(b) : (a ?? b));
133
+ }
134
+ const ttls = [this.ttl, other.ttl].filter((t) => t !== null);
135
+ const ttl = ttls.length > 0 ? Math.min(...ttls) : null;
136
+ return new Authority({ scopes: pruned, ceilings, ttl });
137
+ }
138
+ /**
139
+ * `this <= other`: is `this` provably no more powerful than `other` in every
140
+ * dimension? True iff:
141
+ *
142
+ * 1. every scope of `this` is covered by `other` (wildcard-aware);
143
+ * 2. for every ceiling in `other` there is a ceiling of the same key in
144
+ * `this` that `other`'s ceiling subsumes. A ceiling present in `other`
145
+ * and ABSENT here means `this` is unbounded on that dimension, i.e. more
146
+ * powerful, so the relation is false. This holds for any ceiling key,
147
+ * including ones outside the built-in registry, which is what makes the
148
+ * relation sound for custom ceilings too;
149
+ * 3. `this.ttl` is not null and (`other.ttl` is null or `this.ttl <= other.ttl`).
150
+ *
151
+ * This is exactly the wire subsumption relation: the library relation and the
152
+ * token relation are the same relation.
153
+ */
154
+ isNarrowerThan(other) {
155
+ for (const s of this.scopes) {
156
+ if (!other.coversScope(s))
157
+ return false;
158
+ }
159
+ const mine = this.byKey();
160
+ for (const [k, otherCeiling] of other.byKey()) {
161
+ const selfCeiling = mine.get(k);
162
+ if (selfCeiling === undefined)
163
+ return false; // unbounded here where other bounds
164
+ if (!otherCeiling.subsumes(selfCeiling))
165
+ return false;
166
+ }
167
+ if (other.ttl !== null) {
168
+ if (this.ttl === null || this.ttl > other.ttl)
169
+ return false;
170
+ }
171
+ return true;
172
+ }
173
+ // ---- policy evaluation ------------------------------------------------
174
+ /**
175
+ * Is `scope` permitted under this authority, given a request context such as
176
+ * `{rows: 5000, egress: "none"}`?
177
+ *
178
+ * Checks scope coverage AND every ceiling this authority holds, collecting
179
+ * every failing reason — not just the first — so a single evaluation can
180
+ * explain everything wrong with a request. A ceiling whose context field is
181
+ * absent is not asserting anything on this call and is treated as satisfied.
182
+ */
183
+ permits(scope, ctx = null) {
184
+ const context = ctx ?? {};
185
+ const reasons = [];
186
+ if (!this.coversScope(scope)) {
187
+ reasons.push(new reasons_js_1.Reason(reasons_js_1.ReasonCode.SCOPE_NOT_GRANTED, {
188
+ requested: scope,
189
+ message: `scope '${scope}' not covered by held scopes [${(0, canonical_js_1.sortedStrings)(this.scopes)
190
+ .map((s) => `'${s}'`)
191
+ .join(", ")}]`,
192
+ }));
193
+ }
194
+ // Reserved key so scoped ceilings can tell whether they apply.
195
+ const cctx = { ...context };
196
+ if (!("_scope" in cctx))
197
+ cctx["_scope"] = scope;
198
+ for (const c of this.ceilings) {
199
+ const decision = c.permits(cctx);
200
+ if (!decision.allowed)
201
+ reasons.push(...decision.reasons);
202
+ }
203
+ return reasons.length > 0 ? reasons_js_1.Decision.deny(reasons) : reasons_js_1.Decision.allow();
204
+ }
205
+ withTtl(ttl) {
206
+ return new Authority({ scopes: this.scopes, ceilings: this.ceilings, ttl });
207
+ }
208
+ // ---- wire form --------------------------------------------------------
209
+ toWire() {
210
+ return {
211
+ scopes: (0, canonical_js_1.sortedStrings)(this.scopes),
212
+ constraints: this.ceilings.map((c) => c.toWire()),
213
+ ttl: this.ttl,
214
+ };
215
+ }
216
+ static fromWire(wire) {
217
+ const d = (0, canonical_js_1.toPlain)(wire) ?? {};
218
+ const scopes = d["scopes"] ?? [];
219
+ const constraints = d["constraints"] ?? [];
220
+ const ttl = d["ttl"];
221
+ return new Authority({
222
+ scopes,
223
+ ceilings: constraints.map((c) => (0, ceilings_js_1.ceilingFromWire)(c)),
224
+ ttl: typeof ttl === "number" ? ttl : null,
225
+ });
226
+ }
227
+ /** A stable, human-readable one-liner. */
228
+ describe() {
229
+ const scopes = (0, canonical_js_1.sortedStrings)(this.scopes).join(", ");
230
+ const cs = this.ceilings.map((c) => (0, ceilings_js_1.describe)(c)).sort(canonical_js_1.compareCodePoints).join(", ");
231
+ return `scopes=[${scopes}] ceilings=[${cs}] ttl=${this.ttl}`;
232
+ }
233
+ toString() {
234
+ return `Authority(${this.describe()})`;
235
+ }
236
+ }
237
+ exports.Authority = Authority;
238
+ //# sourceMappingURL=authority.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authority.js","sourceRoot":"","sources":["../../src/authority.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,iDAAkG;AAClG,+CAAyG;AACzG,6CAA4D;AAE5D;;;;;;;GAOG;AACH,MAAa,cAAe,SAAQ,KAAK;IAC9B,MAAM,CAAS;IACf,MAAM,CAAuB;IAEtC,YAAY,OAAe,EAAE,MAAc,EAAE,SAA+B,EAAE;QAC5E,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAVD,wCAUC;AAmBD,MAAa,SAAS;IACpB;;;;OAIG;IACM,MAAM,CAAsB;IAErC;;;;;OAKG;IACM,QAAQ,CAAqB;IAEtC,gEAAgE;IACvD,GAAG,CAAgB;IAE5B,YAAY,OAAsB,EAAE;QAClC,IAAI,CAAC,MAAM,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;QACzC,MAAM,KAAK,GAAG,IAAI,GAAG,EAAmB,CAAC;QACzC,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,IAAI,EAAE;YAAE,KAAK,CAAC,GAAG,CAAC,MAAM,CAA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AE,CAAC,IAAA,6BAAe,EAAC,CAAC,CAAC,CAAC;YACpD,GAAG,EAAE,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI;SAC1C,CAAC,CAAC;IACL,CAAC;IAED,0CAA0C;IAC1C,QAAQ;QACN,MAAM,MAAM,GAAG,IAAA,4BAAa,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACrD,MAAM,EAAE,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAA,sBAAe,EAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,gCAAiB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC3F,OAAO,WAAW,MAAM,eAAe,EAAE,SAAS,IAAI,CAAC,GAAG,EAAE,CAAC;IAC/D,CAAC;IAED,QAAQ;QACN,OAAO,aAAa,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC;IACzC,CAAC;CACF;AA9MD,8BA8MC"}
@@ -0,0 +1,91 @@
1
+ /**
2
+ * canonical.ts — byte-exact interoperability with the Python implementation.
3
+ *
4
+ * Every hash, seal and signature in Attenu is taken over a canonical JSON
5
+ * serialisation. The Python library produces those bytes with
6
+ * `json.dumps(obj, sort_keys=True, separators=(",", ":"))`, whose defaults
7
+ * include `ensure_ascii=True`. `JSON.stringify` differs from that in three
8
+ * ways that would each silently break cross-language verification:
9
+ *
10
+ * 1. key order — `JSON.stringify` preserves insertion order, Python sorts;
11
+ * 2. non-ASCII — Python escapes every code point above U+007E as `\uXXXX`
12
+ * (astral characters as a surrogate pair), `JSON.stringify` emits them raw;
13
+ * 3. numbers — Python distinguishes `int` from `float` (`100` vs `100.0`) and
14
+ * switches to exponential notation at different magnitudes than JavaScript
15
+ * (`1e-05` where `String()` gives `0.00001`).
16
+ *
17
+ * (1) and (2) are handled by `canonicalJson` below. (3) cannot be solved by a
18
+ * serialiser alone, because a JavaScript `number` has forgotten whether the
19
+ * document said `100` or `100.0`. So a document that is going to be re-hashed —
20
+ * a ledger or a bundle produced elsewhere — is read with `parseJson`, which
21
+ * keeps each number's original literal alongside its value as a `RawNumber`.
22
+ * `canonicalJson` re-emits that literal verbatim, so a Python-written entry
23
+ * hashes to the byte-identical digest here. Values created in this library are
24
+ * plain numbers, and `pyNumber` formats them the way Python's `json` would, so
25
+ * the reverse direction round-trips too.
26
+ */
27
+ /** A number as it was written in the source document, plus its parsed value. */
28
+ export declare class RawNumber {
29
+ readonly raw: string;
30
+ readonly value: number;
31
+ constructor(raw: string, value: number);
32
+ valueOf(): number;
33
+ toJSON(): number;
34
+ }
35
+ /** A JSON value that may still carry original number literals. */
36
+ export type CJson = null | boolean | number | string | RawNumber | CJson[] | {
37
+ [key: string]: CJson;
38
+ };
39
+ /** A plain JSON value — what the rest of the library works with. */
40
+ export type Json = null | boolean | number | string | Json[] | {
41
+ [key: string]: Json;
42
+ };
43
+ /** Compare two strings by Unicode code point, as Python's `sorted` does. */
44
+ export declare function compareCodePoints(a: string, b: string): number;
45
+ /** Sort strings by code point (Python's `sorted(list_of_str)`). */
46
+ export declare function sortedStrings(values: Iterable<string>): string[];
47
+ /**
48
+ * Format a number the way Python's `json.dumps` would.
49
+ *
50
+ * Integral values are emitted without a decimal point, matching a Python `int`.
51
+ * A TypeScript number cannot record that it was meant to be the float `100.0`,
52
+ * so such a value serialises as `100`; Python reads that back as an `int` and
53
+ * re-emits `100`, which keeps the chain verifiable in both directions. Values
54
+ * with a fractional part follow CPython's `repr`: shortest round-tripping
55
+ * digits, exponential notation when the decimal exponent is below -4 or at
56
+ * least 16, a two-digit signed exponent, and always a decimal point otherwise.
57
+ */
58
+ export declare function pyNumber(n: number): string;
59
+ /** Escape a string the way Python's `json.dumps(ensure_ascii=True)` does. */
60
+ export declare function pyString(s: string): string;
61
+ /**
62
+ * Serialise to the exact bytes Python's
63
+ * `json.dumps(obj, sort_keys=True, separators=(",", ":"))` produces:
64
+ * sorted keys, no incidental whitespace, ASCII-escaped strings.
65
+ *
66
+ * Object entries whose value is `undefined` are omitted, matching a Python dict
67
+ * that simply never held the key. `null` is kept — it is a value.
68
+ */
69
+ export declare function canonicalJson(value: CJson | undefined): string;
70
+ /**
71
+ * Serialise with sorted keys and ASCII escaping, choosing the separators.
72
+ *
73
+ * `canonicalJson` uses the compact `(",", ":")` pair every hash is taken over.
74
+ * The `.jsonl` ledger on disk is written with Python's DEFAULT separators
75
+ * (`", "` and `": "`), so a line read back by either language re-serialises to
76
+ * the same bytes its writer produced.
77
+ */
78
+ export declare function pyJsonDumps(value: CJson | undefined, itemSeparator?: string, keySeparator?: string): string;
79
+ /** The canonical bytes — what every hash, seal and signature is taken over. */
80
+ export declare function canonicalBytes(value: CJson | undefined): Buffer;
81
+ /** Strip `RawNumber` wrappers, yielding ordinary JavaScript values. */
82
+ export declare function toPlain<T = Json>(value: CJson | undefined): T;
83
+ /**
84
+ * Parse JSON, keeping every number's original literal.
85
+ *
86
+ * `JSON.parse` is not used: it discards the literal, and with it the ability to
87
+ * reproduce the bytes the writer hashed. Objects preserve their key order for
88
+ * readability; canonical serialisation sorts them anyway.
89
+ */
90
+ export declare function parseJson(text: string): CJson;
91
+ //# sourceMappingURL=canonical.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonical.d.ts","sourceRoot":"","sources":["../../src/canonical.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,gFAAgF;AAChF,qBAAa,SAAS;IAElB,QAAQ,CAAC,GAAG,EAAE,MAAM;IACpB,QAAQ,CAAC,KAAK,EAAE,MAAM;gBADb,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM;IAExB,OAAO,IAAI,MAAM;IAGjB,MAAM,IAAI,MAAM;CAGjB;AAED,kEAAkE;AAClE,MAAM,MAAM,KAAK,GACb,IAAI,GACJ,OAAO,GACP,MAAM,GACN,M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