@peerbit/trusted-network 6.0.104 → 6.0.106

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.
@@ -0,0 +1,990 @@
1
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
2
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
3
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
4
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
5
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
6
+ var _, done = false;
7
+ for (var i = decorators.length - 1; i >= 0; i--) {
8
+ var context = {};
9
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
10
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
11
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
12
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
13
+ if (kind === "accessor") {
14
+ if (result === void 0) continue;
15
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
16
+ if (_ = accept(result.get)) descriptor.get = _;
17
+ if (_ = accept(result.set)) descriptor.set = _;
18
+ if (_ = accept(result.init)) initializers.unshift(_);
19
+ }
20
+ else if (_ = accept(result)) {
21
+ if (kind === "field") initializers.unshift(_);
22
+ else descriptor[key] = _;
23
+ }
24
+ }
25
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
26
+ done = true;
27
+ };
28
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
29
+ var useValue = arguments.length > 2;
30
+ for (var i = 0; i < initializers.length; i++) {
31
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
32
+ }
33
+ return useValue ? value : void 0;
34
+ };
35
+ import { deserialize, field, fixedArray, serialize, variant, } from "@dao-xyz/borsh";
36
+ import { PublicSignKey, sha256Sync } from "@peerbit/crypto";
37
+ import { compare, concat, equals } from "uint8arrays";
38
+ import { TrustedNetworkV2PolicyReducer, authenticatePolicySnapshotEntryV2, } from "./v2-policy-engine.js";
39
+ import { NetworkDescriptorV2, PolicySubjectBindingV2, TRUSTED_NETWORK_V2_KNOWN_ROLE_BITS, TRUSTED_NETWORK_V2_MAX_POLICY_ENTRY_BYTES, assertNetworkDescriptorV2, } from "./v2.js";
40
+ /**
41
+ * Internal crash-safe policy-anchor storage format.
42
+ *
43
+ * This module is intentionally absent from the package entry point. Its store
44
+ * must already be open and scoped to this namespace and descriptor. Exactly
45
+ * one wrapper may write that scope: this append-only format deliberately does
46
+ * not pretend that get-then-put is a multi-process compare-and-swap.
47
+ */
48
+ export const TRUSTED_NETWORK_V2_POLICY_ANCHOR_STORE_OWNER = "peerbit/trusted-network/v2/policy-anchor/v1";
49
+ export const TRUSTED_NETWORK_V2_MAX_POLICY_ANCHOR_GENERATION_BYTES = TRUSTED_NETWORK_V2_MAX_POLICY_ENTRY_BYTES * 4;
50
+ const GENERATION_KEY_PREFIX = `${TRUSTED_NETWORK_V2_POLICY_ANCHOR_STORE_OWNER}/generation/`;
51
+ const FORMAT_VERSION = 1;
52
+ const MAX_U64 = 0xffffffffffffffffn;
53
+ const MAX_UNAVAILABLE_REASON_LENGTH = 512;
54
+ const ZERO_DIGEST = new Uint8Array(32);
55
+ const textEncoder = new TextEncoder();
56
+ const DESCRIPTOR_DIGEST_DOMAIN = textEncoder.encode("peerbit/trusted-network/v2/policy-anchor/descriptor/v1");
57
+ const GENERATION_CHECKSUM_DOMAIN = textEncoder.encode("peerbit/trusted-network/v2/policy-anchor/generation/v1");
58
+ const ANCHOR_STATE = Object.freeze({
59
+ ACTIVE: 1,
60
+ UNAVAILABLE: 2,
61
+ FORKED: 3,
62
+ });
63
+ const GENERATION_KIND = Object.freeze({
64
+ STATE: 1,
65
+ FORK_OBSERVATION: 2,
66
+ });
67
+ const MAX_STATE_GENERATION_PAYLOAD_BYTES = TRUSTED_NETWORK_V2_MAX_POLICY_ENTRY_BYTES * 4;
68
+ const MAX_OBSERVATION_GENERATION_PAYLOAD_BYTES = TRUSTED_NETWORK_V2_MAX_POLICY_ENTRY_BYTES + 1024;
69
+ let PolicyAnchorCoreStateRecordV2 = (() => {
70
+ let _classDecorators = [variant([2, 16, 0])];
71
+ let _classDescriptor;
72
+ let _classExtraInitializers = [];
73
+ let _classThis;
74
+ let _state_decorators;
75
+ let _state_initializers = [];
76
+ let _state_extraInitializers = [];
77
+ let _acceptedHeadEntryBytes_decorators;
78
+ let _acceptedHeadEntryBytes_initializers = [];
79
+ let _acceptedHeadEntryBytes_extraInitializers = [];
80
+ let _comparisonCandidateEntryBytes_decorators;
81
+ let _comparisonCandidateEntryBytes_initializers = [];
82
+ let _comparisonCandidateEntryBytes_extraInitializers = [];
83
+ let _acceptedAncestorDigest_decorators;
84
+ let _acceptedAncestorDigest_initializers = [];
85
+ let _acceptedAncestorDigest_extraInitializers = [];
86
+ let _unavailableReason_decorators;
87
+ let _unavailableReason_initializers = [];
88
+ let _unavailableReason_extraInitializers = [];
89
+ let _forkChildEntryBytes0_decorators;
90
+ let _forkChildEntryBytes0_initializers = [];
91
+ let _forkChildEntryBytes0_extraInitializers = [];
92
+ let _forkChildEntryBytes1_decorators;
93
+ let _forkChildEntryBytes1_initializers = [];
94
+ let _forkChildEntryBytes1_extraInitializers = [];
95
+ var PolicyAnchorCoreStateRecordV2 = class {
96
+ static { _classThis = this; }
97
+ static {
98
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
99
+ _state_decorators = [field({ type: "u8" })];
100
+ _acceptedHeadEntryBytes_decorators = [field({ type: Uint8Array })];
101
+ _comparisonCandidateEntryBytes_decorators = [field({ type: Uint8Array })];
102
+ _acceptedAncestorDigest_decorators = [field({ type: fixedArray("u8", 32) })];
103
+ _unavailableReason_decorators = [field({ type: "string" })];
104
+ _forkChildEntryBytes0_decorators = [field({ type: Uint8Array })];
105
+ _forkChildEntryBytes1_decorators = [field({ type: Uint8Array })];
106
+ __esDecorate(null, null, _state_decorators, { kind: "field", name: "state", static: false, private: false, access: { has: obj => "state" in obj, get: obj => obj.state, set: (obj, value) => { obj.state = value; } }, metadata: _metadata }, _state_initializers, _state_extraInitializers);
107
+ __esDecorate(null, null, _acceptedHeadEntryBytes_decorators, { kind: "field", name: "acceptedHeadEntryBytes", static: false, private: false, access: { has: obj => "acceptedHeadEntryBytes" in obj, get: obj => obj.acceptedHeadEntryBytes, set: (obj, value) => { obj.acceptedHeadEntryBytes = value; } }, metadata: _metadata }, _acceptedHeadEntryBytes_initializers, _acceptedHeadEntryBytes_extraInitializers);
108
+ __esDecorate(null, null, _comparisonCandidateEntryBytes_decorators, { kind: "field", name: "comparisonCandidateEntryBytes", static: false, private: false, access: { has: obj => "comparisonCandidateEntryBytes" in obj, get: obj => obj.comparisonCandidateEntryBytes, set: (obj, value) => { obj.comparisonCandidateEntryBytes = value; } }, metadata: _metadata }, _comparisonCandidateEntryBytes_initializers, _comparisonCandidateEntryBytes_extraInitializers);
109
+ __esDecorate(null, null, _acceptedAncestorDigest_decorators, { kind: "field", name: "acceptedAncestorDigest", static: false, private: false, access: { has: obj => "acceptedAncestorDigest" in obj, get: obj => obj.acceptedAncestorDigest, set: (obj, value) => { obj.acceptedAncestorDigest = value; } }, metadata: _metadata }, _acceptedAncestorDigest_initializers, _acceptedAncestorDigest_extraInitializers);
110
+ __esDecorate(null, null, _unavailableReason_decorators, { kind: "field", name: "unavailableReason", static: false, private: false, access: { has: obj => "unavailableReason" in obj, get: obj => obj.unavailableReason, set: (obj, value) => { obj.unavailableReason = value; } }, metadata: _metadata }, _unavailableReason_initializers, _unavailableReason_extraInitializers);
111
+ __esDecorate(null, null, _forkChildEntryBytes0_decorators, { kind: "field", name: "forkChildEntryBytes0", static: false, private: false, access: { has: obj => "forkChildEntryBytes0" in obj, get: obj => obj.forkChildEntryBytes0, set: (obj, value) => { obj.forkChildEntryBytes0 = value; } }, metadata: _metadata }, _forkChildEntryBytes0_initializers, _forkChildEntryBytes0_extraInitializers);
112
+ __esDecorate(null, null, _forkChildEntryBytes1_decorators, { kind: "field", name: "forkChildEntryBytes1", static: false, private: false, access: { has: obj => "forkChildEntryBytes1" in obj, get: obj => obj.forkChildEntryBytes1, set: (obj, value) => { obj.forkChildEntryBytes1 = value; } }, metadata: _metadata }, _forkChildEntryBytes1_initializers, _forkChildEntryBytes1_extraInitializers);
113
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
114
+ PolicyAnchorCoreStateRecordV2 = _classThis = _classDescriptor.value;
115
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
116
+ __runInitializers(_classThis, _classExtraInitializers);
117
+ }
118
+ state = __runInitializers(this, _state_initializers, void 0);
119
+ acceptedHeadEntryBytes = (__runInitializers(this, _state_extraInitializers), __runInitializers(this, _acceptedHeadEntryBytes_initializers, void 0));
120
+ comparisonCandidateEntryBytes = (__runInitializers(this, _acceptedHeadEntryBytes_extraInitializers), __runInitializers(this, _comparisonCandidateEntryBytes_initializers, void 0));
121
+ acceptedAncestorDigest = (__runInitializers(this, _comparisonCandidateEntryBytes_extraInitializers), __runInitializers(this, _acceptedAncestorDigest_initializers, void 0));
122
+ unavailableReason = (__runInitializers(this, _acceptedAncestorDigest_extraInitializers), __runInitializers(this, _unavailableReason_initializers, void 0));
123
+ forkChildEntryBytes0 = (__runInitializers(this, _unavailableReason_extraInitializers), __runInitializers(this, _forkChildEntryBytes0_initializers, void 0));
124
+ forkChildEntryBytes1 = (__runInitializers(this, _forkChildEntryBytes0_extraInitializers), __runInitializers(this, _forkChildEntryBytes1_initializers, void 0));
125
+ constructor(properties) {
126
+ __runInitializers(this, _forkChildEntryBytes1_extraInitializers);
127
+ if (properties)
128
+ Object.assign(this, properties);
129
+ }
130
+ };
131
+ return PolicyAnchorCoreStateRecordV2 = _classThis;
132
+ })();
133
+ let PolicyAnchorStateGenerationPayloadV2 = (() => {
134
+ let _classDecorators = [variant([2, 16, 3])];
135
+ let _classDescriptor;
136
+ let _classExtraInitializers = [];
137
+ let _classThis;
138
+ let _coreState_decorators;
139
+ let _coreState_initializers = [];
140
+ let _coreState_extraInitializers = [];
141
+ var PolicyAnchorStateGenerationPayloadV2 = class {
142
+ static { _classThis = this; }
143
+ static {
144
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
145
+ _coreState_decorators = [field({ type: PolicyAnchorCoreStateRecordV2 })];
146
+ __esDecorate(null, null, _coreState_decorators, { kind: "field", name: "coreState", static: false, private: false, access: { has: obj => "coreState" in obj, get: obj => obj.coreState, set: (obj, value) => { obj.coreState = value; } }, metadata: _metadata }, _coreState_initializers, _coreState_extraInitializers);
147
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
148
+ PolicyAnchorStateGenerationPayloadV2 = _classThis = _classDescriptor.value;
149
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
150
+ __runInitializers(_classThis, _classExtraInitializers);
151
+ }
152
+ coreState = __runInitializers(this, _coreState_initializers, void 0);
153
+ constructor(properties) {
154
+ __runInitializers(this, _coreState_extraInitializers);
155
+ if (properties)
156
+ Object.assign(this, properties);
157
+ }
158
+ };
159
+ return PolicyAnchorStateGenerationPayloadV2 = _classThis;
160
+ })();
161
+ let PolicyAnchorObservationGenerationPayloadV2 = (() => {
162
+ let _classDecorators = [variant([2, 16, 4])];
163
+ let _classDescriptor;
164
+ let _classExtraInitializers = [];
165
+ let _classThis;
166
+ let _entryBytes_decorators;
167
+ let _entryBytes_initializers = [];
168
+ let _entryBytes_extraInitializers = [];
169
+ var PolicyAnchorObservationGenerationPayloadV2 = class {
170
+ static { _classThis = this; }
171
+ static {
172
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
173
+ _entryBytes_decorators = [field({ type: Uint8Array })];
174
+ __esDecorate(null, null, _entryBytes_decorators, { kind: "field", name: "entryBytes", static: false, private: false, access: { has: obj => "entryBytes" in obj, get: obj => obj.entryBytes, set: (obj, value) => { obj.entryBytes = value; } }, metadata: _metadata }, _entryBytes_initializers, _entryBytes_extraInitializers);
175
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
176
+ PolicyAnchorObservationGenerationPayloadV2 = _classThis = _classDescriptor.value;
177
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
178
+ __runInitializers(_classThis, _classExtraInitializers);
179
+ }
180
+ entryBytes = __runInitializers(this, _entryBytes_initializers, void 0);
181
+ constructor(properties) {
182
+ __runInitializers(this, _entryBytes_extraInitializers);
183
+ if (properties)
184
+ Object.assign(this, properties);
185
+ }
186
+ };
187
+ return PolicyAnchorObservationGenerationPayloadV2 = _classThis;
188
+ })();
189
+ let PolicyAnchorGenerationBodyV2 = (() => {
190
+ let _classDecorators = [variant([2, 16, 1])];
191
+ let _classDescriptor;
192
+ let _classExtraInitializers = [];
193
+ let _classThis;
194
+ let _formatVersion_decorators;
195
+ let _formatVersion_initializers = [];
196
+ let _formatVersion_extraInitializers = [];
197
+ let _generation_decorators;
198
+ let _generation_initializers = [];
199
+ let _generation_extraInitializers = [];
200
+ let _descriptorDigest_decorators;
201
+ let _descriptorDigest_initializers = [];
202
+ let _descriptorDigest_extraInitializers = [];
203
+ let _previousGenerationChecksum_decorators;
204
+ let _previousGenerationChecksum_initializers = [];
205
+ let _previousGenerationChecksum_extraInitializers = [];
206
+ let _kind_decorators;
207
+ let _kind_initializers = [];
208
+ let _kind_extraInitializers = [];
209
+ let _payloadBytes_decorators;
210
+ let _payloadBytes_initializers = [];
211
+ let _payloadBytes_extraInitializers = [];
212
+ var PolicyAnchorGenerationBodyV2 = class {
213
+ static { _classThis = this; }
214
+ static {
215
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
216
+ _formatVersion_decorators = [field({ type: "u8" })];
217
+ _generation_decorators = [field({ type: "u64" })];
218
+ _descriptorDigest_decorators = [field({ type: fixedArray("u8", 32) })];
219
+ _previousGenerationChecksum_decorators = [field({ type: fixedArray("u8", 32) })];
220
+ _kind_decorators = [field({ type: "u8" })];
221
+ _payloadBytes_decorators = [field({ type: Uint8Array })];
222
+ __esDecorate(null, null, _formatVersion_decorators, { kind: "field", name: "formatVersion", static: false, private: false, access: { has: obj => "formatVersion" in obj, get: obj => obj.formatVersion, set: (obj, value) => { obj.formatVersion = value; } }, metadata: _metadata }, _formatVersion_initializers, _formatVersion_extraInitializers);
223
+ __esDecorate(null, null, _generation_decorators, { kind: "field", name: "generation", static: false, private: false, access: { has: obj => "generation" in obj, get: obj => obj.generation, set: (obj, value) => { obj.generation = value; } }, metadata: _metadata }, _generation_initializers, _generation_extraInitializers);
224
+ __esDecorate(null, null, _descriptorDigest_decorators, { kind: "field", name: "descriptorDigest", static: false, private: false, access: { has: obj => "descriptorDigest" in obj, get: obj => obj.descriptorDigest, set: (obj, value) => { obj.descriptorDigest = value; } }, metadata: _metadata }, _descriptorDigest_initializers, _descriptorDigest_extraInitializers);
225
+ __esDecorate(null, null, _previousGenerationChecksum_decorators, { kind: "field", name: "previousGenerationChecksum", static: false, private: false, access: { has: obj => "previousGenerationChecksum" in obj, get: obj => obj.previousGenerationChecksum, set: (obj, value) => { obj.previousGenerationChecksum = value; } }, metadata: _metadata }, _previousGenerationChecksum_initializers, _previousGenerationChecksum_extraInitializers);
226
+ __esDecorate(null, null, _kind_decorators, { kind: "field", name: "kind", static: false, private: false, access: { has: obj => "kind" in obj, get: obj => obj.kind, set: (obj, value) => { obj.kind = value; } }, metadata: _metadata }, _kind_initializers, _kind_extraInitializers);
227
+ __esDecorate(null, null, _payloadBytes_decorators, { kind: "field", name: "payloadBytes", static: false, private: false, access: { has: obj => "payloadBytes" in obj, get: obj => obj.payloadBytes, set: (obj, value) => { obj.payloadBytes = value; } }, metadata: _metadata }, _payloadBytes_initializers, _payloadBytes_extraInitializers);
228
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
229
+ PolicyAnchorGenerationBodyV2 = _classThis = _classDescriptor.value;
230
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
231
+ __runInitializers(_classThis, _classExtraInitializers);
232
+ }
233
+ formatVersion = __runInitializers(this, _formatVersion_initializers, void 0);
234
+ generation = (__runInitializers(this, _formatVersion_extraInitializers), __runInitializers(this, _generation_initializers, void 0));
235
+ descriptorDigest = (__runInitializers(this, _generation_extraInitializers), __runInitializers(this, _descriptorDigest_initializers, void 0));
236
+ previousGenerationChecksum = (__runInitializers(this, _descriptorDigest_extraInitializers), __runInitializers(this, _previousGenerationChecksum_initializers, void 0));
237
+ kind = (__runInitializers(this, _previousGenerationChecksum_extraInitializers), __runInitializers(this, _kind_initializers, void 0));
238
+ payloadBytes = (__runInitializers(this, _kind_extraInitializers), __runInitializers(this, _payloadBytes_initializers, void 0));
239
+ constructor(properties) {
240
+ __runInitializers(this, _payloadBytes_extraInitializers);
241
+ if (properties)
242
+ Object.assign(this, properties);
243
+ }
244
+ };
245
+ return PolicyAnchorGenerationBodyV2 = _classThis;
246
+ })();
247
+ let PolicyAnchorGenerationRecordV2 = (() => {
248
+ let _classDecorators = [variant([2, 16, 2])];
249
+ let _classDescriptor;
250
+ let _classExtraInitializers = [];
251
+ let _classThis;
252
+ let _body_decorators;
253
+ let _body_initializers = [];
254
+ let _body_extraInitializers = [];
255
+ let _checksum_decorators;
256
+ let _checksum_initializers = [];
257
+ let _checksum_extraInitializers = [];
258
+ var PolicyAnchorGenerationRecordV2 = class {
259
+ static { _classThis = this; }
260
+ static {
261
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
262
+ _body_decorators = [field({ type: PolicyAnchorGenerationBodyV2 })];
263
+ _checksum_decorators = [field({ type: fixedArray("u8", 32) })];
264
+ __esDecorate(null, null, _body_decorators, { kind: "field", name: "body", static: false, private: false, access: { has: obj => "body" in obj, get: obj => obj.body, set: (obj, value) => { obj.body = value; } }, metadata: _metadata }, _body_initializers, _body_extraInitializers);
265
+ __esDecorate(null, null, _checksum_decorators, { kind: "field", name: "checksum", static: false, private: false, access: { has: obj => "checksum" in obj, get: obj => obj.checksum, set: (obj, value) => { obj.checksum = value; } }, metadata: _metadata }, _checksum_initializers, _checksum_extraInitializers);
266
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
267
+ PolicyAnchorGenerationRecordV2 = _classThis = _classDescriptor.value;
268
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
269
+ __runInitializers(_classThis, _classExtraInitializers);
270
+ }
271
+ body = __runInitializers(this, _body_initializers, void 0);
272
+ checksum = (__runInitializers(this, _body_extraInitializers), __runInitializers(this, _checksum_initializers, void 0));
273
+ constructor(properties) {
274
+ __runInitializers(this, _checksum_extraInitializers);
275
+ if (properties)
276
+ Object.assign(this, properties);
277
+ }
278
+ };
279
+ return PolicyAnchorGenerationRecordV2 = _classThis;
280
+ })();
281
+ const copyBytes = (bytes) => Uint8Array.from(bytes);
282
+ const bytesKey = (bytes) => {
283
+ let key = "";
284
+ for (const byte of bytes)
285
+ key += byte.toString(16).padStart(2, "0");
286
+ return key;
287
+ };
288
+ const copyBinding = (binding) => deserialize(serialize(binding), PolicySubjectBindingV2);
289
+ const copyHead = (head) => head === undefined
290
+ ? undefined
291
+ : {
292
+ sequence: head.sequence,
293
+ digest: copyBytes(head.digest),
294
+ bindings: head.bindings.map(copyBinding),
295
+ };
296
+ const copyForkEvidence = (evidence) => evidence === undefined
297
+ ? undefined
298
+ : {
299
+ commonParent: copyHead(evidence.commonParent),
300
+ children: [
301
+ {
302
+ sequence: evidence.children[0].sequence,
303
+ digest: copyBytes(evidence.children[0].digest),
304
+ entryBytes: copyBytes(evidence.children[0].entryBytes),
305
+ },
306
+ {
307
+ sequence: evidence.children[1].sequence,
308
+ digest: copyBytes(evidence.children[1].digest),
309
+ entryBytes: copyBytes(evidence.children[1].entryBytes),
310
+ },
311
+ ],
312
+ };
313
+ const keyId = (key) => bytesKey(serialize(key));
314
+ const descriptorDigest = (descriptor) => sha256Sync(concat([DESCRIPTOR_DIGEST_DOMAIN, serialize(descriptor)]));
315
+ const generationChecksum = (body) => sha256Sync(concat([GENERATION_CHECKSUM_DOMAIN, serialize(body)]));
316
+ const observationContentHash = (entryBytes) => sha256Sync(entryBytes);
317
+ const generationKey = (generation) => `${GENERATION_KEY_PREFIX}${generation.toString().padStart(20, "0")}`;
318
+ const assertOpenNotAborted = (signal) => {
319
+ if (signal?.aborted) {
320
+ throw new Error("TrustedNetwork v2 durable policy open was aborted");
321
+ }
322
+ };
323
+ const assertEntryBytes = (bytes, label) => {
324
+ if (!(bytes instanceof Uint8Array) ||
325
+ bytes.byteLength === 0 ||
326
+ bytes.byteLength > TRUSTED_NETWORK_V2_MAX_POLICY_ENTRY_BYTES) {
327
+ throw new Error(`${label} must contain 1-${TRUSTED_NETWORK_V2_MAX_POLICY_ENTRY_BYTES} bytes`);
328
+ }
329
+ };
330
+ const retainCanonicalForkChild = (children, candidate) => {
331
+ const existingIndex = children.findIndex(({ digest }) => equals(digest, candidate.digest));
332
+ if (existingIndex >= 0) {
333
+ if (compare(candidate.entryBytes, children[existingIndex].entryBytes) >= 0) {
334
+ return;
335
+ }
336
+ children.splice(existingIndex, 1);
337
+ }
338
+ children.push({
339
+ digest: copyBytes(candidate.digest),
340
+ entryBytes: copyBytes(candidate.entryBytes),
341
+ });
342
+ children.sort((left, right) => {
343
+ const digestOrder = compare(left.digest, right.digest);
344
+ return digestOrder === 0
345
+ ? compare(left.entryBytes, right.entryBytes)
346
+ : digestOrder;
347
+ });
348
+ if (children.length > 2)
349
+ children.length = 2;
350
+ };
351
+ const assertEmptyBytes = (bytes, label) => {
352
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength !== 0) {
353
+ throw new Error(`${label} must be empty`);
354
+ }
355
+ };
356
+ const coreRecordFromState = (state) => {
357
+ if (state.state === "ACTIVE") {
358
+ return new PolicyAnchorCoreStateRecordV2({
359
+ state: ANCHOR_STATE.ACTIVE,
360
+ acceptedHeadEntryBytes: copyBytes(state.acceptedHeadEntryBytes),
361
+ comparisonCandidateEntryBytes: new Uint8Array(0),
362
+ acceptedAncestorDigest: copyBytes(ZERO_DIGEST),
363
+ unavailableReason: "",
364
+ forkChildEntryBytes0: new Uint8Array(0),
365
+ forkChildEntryBytes1: new Uint8Array(0),
366
+ });
367
+ }
368
+ if (state.state === "UNAVAILABLE") {
369
+ return new PolicyAnchorCoreStateRecordV2({
370
+ state: ANCHOR_STATE.UNAVAILABLE,
371
+ acceptedHeadEntryBytes: copyBytes(state.acceptedHeadEntryBytes),
372
+ comparisonCandidateEntryBytes: copyBytes(state.comparisonCandidateEntryBytes),
373
+ acceptedAncestorDigest: copyBytes(state.acceptedAncestorDigest),
374
+ unavailableReason: state.reason,
375
+ forkChildEntryBytes0: new Uint8Array(0),
376
+ forkChildEntryBytes1: new Uint8Array(0),
377
+ });
378
+ }
379
+ return new PolicyAnchorCoreStateRecordV2({
380
+ state: ANCHOR_STATE.FORKED,
381
+ acceptedHeadEntryBytes: copyBytes(state.commonParentEntryBytes),
382
+ comparisonCandidateEntryBytes: new Uint8Array(0),
383
+ acceptedAncestorDigest: copyBytes(ZERO_DIGEST),
384
+ unavailableReason: "",
385
+ forkChildEntryBytes0: copyBytes(state.childEntryBytes[0]),
386
+ forkChildEntryBytes1: copyBytes(state.childEntryBytes[1]),
387
+ });
388
+ };
389
+ const durableStateFromCoreRecord = (record) => {
390
+ assertEntryBytes(record.acceptedHeadEntryBytes, "accepted head entry");
391
+ if (record.state === ANCHOR_STATE.ACTIVE) {
392
+ assertEmptyBytes(record.comparisonCandidateEntryBytes, "active comparison candidate");
393
+ if (!equals(record.acceptedAncestorDigest, ZERO_DIGEST)) {
394
+ throw new Error("Active accepted-ancestor digest must be zero");
395
+ }
396
+ if (record.unavailableReason !== "") {
397
+ throw new Error("Active unavailable reason must be empty");
398
+ }
399
+ assertEmptyBytes(record.forkChildEntryBytes0, "active fork child 0");
400
+ assertEmptyBytes(record.forkChildEntryBytes1, "active fork child 1");
401
+ return {
402
+ formatVersion: FORMAT_VERSION,
403
+ state: "ACTIVE",
404
+ acceptedHeadEntryBytes: copyBytes(record.acceptedHeadEntryBytes),
405
+ };
406
+ }
407
+ if (record.state === ANCHOR_STATE.UNAVAILABLE) {
408
+ assertEntryBytes(record.comparisonCandidateEntryBytes, "unavailable comparison candidate");
409
+ if (record.acceptedAncestorDigest.byteLength !== 32) {
410
+ throw new Error("Unavailable accepted-ancestor digest must be 32 bytes");
411
+ }
412
+ if (record.unavailableReason.length === 0 ||
413
+ record.unavailableReason.length > MAX_UNAVAILABLE_REASON_LENGTH) {
414
+ throw new Error("Unavailable reason is empty or exceeds its character ceiling");
415
+ }
416
+ assertEmptyBytes(record.forkChildEntryBytes0, "unavailable fork child 0");
417
+ assertEmptyBytes(record.forkChildEntryBytes1, "unavailable fork child 1");
418
+ return {
419
+ formatVersion: FORMAT_VERSION,
420
+ state: "UNAVAILABLE",
421
+ acceptedHeadEntryBytes: copyBytes(record.acceptedHeadEntryBytes),
422
+ comparisonCandidateEntryBytes: copyBytes(record.comparisonCandidateEntryBytes),
423
+ acceptedAncestorDigest: copyBytes(record.acceptedAncestorDigest),
424
+ reason: record.unavailableReason,
425
+ };
426
+ }
427
+ if (record.state === ANCHOR_STATE.FORKED) {
428
+ assertEmptyBytes(record.comparisonCandidateEntryBytes, "forked comparison candidate");
429
+ if (!equals(record.acceptedAncestorDigest, ZERO_DIGEST)) {
430
+ throw new Error("Forked accepted-ancestor digest must be zero");
431
+ }
432
+ if (record.unavailableReason !== "") {
433
+ throw new Error("Forked unavailable reason must be empty");
434
+ }
435
+ assertEntryBytes(record.forkChildEntryBytes0, "fork child 0");
436
+ assertEntryBytes(record.forkChildEntryBytes1, "fork child 1");
437
+ return {
438
+ formatVersion: FORMAT_VERSION,
439
+ state: "FORKED",
440
+ commonParentEntryBytes: copyBytes(record.acceptedHeadEntryBytes),
441
+ childEntryBytes: [
442
+ copyBytes(record.forkChildEntryBytes0),
443
+ copyBytes(record.forkChildEntryBytes1),
444
+ ],
445
+ };
446
+ }
447
+ throw new Error("Unknown durable policy-anchor state");
448
+ };
449
+ const decodeCanonicalPayload = (input, type, maxBytes, label) => {
450
+ if (!(input instanceof Uint8Array) ||
451
+ input.byteLength === 0 ||
452
+ input.byteLength > maxBytes) {
453
+ throw new Error(`${label} exceeds its byte ceiling`);
454
+ }
455
+ const bytes = copyBytes(input);
456
+ const payload = deserialize(bytes, type);
457
+ if (!equals(bytes, serialize(payload))) {
458
+ throw new Error(`${label} is not canonical`);
459
+ }
460
+ return payload;
461
+ };
462
+ const decodeGenerationPayload = (body) => {
463
+ if (body.kind === GENERATION_KIND.STATE) {
464
+ const payload = decodeCanonicalPayload(body.payloadBytes, PolicyAnchorStateGenerationPayloadV2, MAX_STATE_GENERATION_PAYLOAD_BYTES, "Policy-anchor state payload");
465
+ return {
466
+ kind: "state",
467
+ payload,
468
+ durableState: durableStateFromCoreRecord(payload.coreState),
469
+ };
470
+ }
471
+ if (body.kind === GENERATION_KIND.FORK_OBSERVATION) {
472
+ const payload = decodeCanonicalPayload(body.payloadBytes, PolicyAnchorObservationGenerationPayloadV2, MAX_OBSERVATION_GENERATION_PAYLOAD_BYTES, "Policy fork-observation payload");
473
+ assertEntryBytes(payload.entryBytes, "fork observation entry");
474
+ return { kind: "fork-observation", payload };
475
+ }
476
+ throw new Error("Unknown policy-anchor generation kind");
477
+ };
478
+ const decodeGenerationRecord = (input) => {
479
+ if (!(input instanceof Uint8Array) ||
480
+ input.byteLength === 0 ||
481
+ input.byteLength > TRUSTED_NETWORK_V2_MAX_POLICY_ANCHOR_GENERATION_BYTES) {
482
+ throw new Error("Policy-anchor generation record exceeds its byte ceiling");
483
+ }
484
+ const bytes = copyBytes(input);
485
+ const record = deserialize(bytes, PolicyAnchorGenerationRecordV2);
486
+ if (!equals(bytes, serialize(record))) {
487
+ throw new Error("Policy-anchor generation record is not canonical");
488
+ }
489
+ if (record.body.formatVersion !== FORMAT_VERSION) {
490
+ throw new Error("Unsupported policy-anchor generation format");
491
+ }
492
+ if (!equals(record.checksum, generationChecksum(record.body))) {
493
+ throw new Error("Policy-anchor generation checksum mismatch");
494
+ }
495
+ return { record, payload: decodeGenerationPayload(record.body) };
496
+ };
497
+ const publishedFromReducer = (reducer) => {
498
+ if (reducer.state === "HALTED") {
499
+ throw new Error("Cannot publish a halted policy reducer");
500
+ }
501
+ const head = copyHead(reducer.head);
502
+ const roles = new Map();
503
+ for (const binding of head?.bindings ?? []) {
504
+ roles.set(keyId(binding.signingKey), binding.roles);
505
+ }
506
+ return {
507
+ state: reducer.state,
508
+ head,
509
+ forkEvidence: copyForkEvidence(reducer.forkEvidence),
510
+ roles,
511
+ };
512
+ };
513
+ const assertCanonicalCoreRestore = (reducer, storedCoreBytes) => {
514
+ const restoredState = reducer.exportDurableState();
515
+ if (restoredState.state === "EMPTY") {
516
+ throw new Error("Restored policy-anchor state is unexpectedly empty");
517
+ }
518
+ const restoredCoreBytes = serialize(coreRecordFromState(restoredState));
519
+ if (!equals(restoredCoreBytes, storedCoreBytes)) {
520
+ throw new Error("Restored policy-anchor state is not canonical");
521
+ }
522
+ };
523
+ /**
524
+ * Crash-safe publication wrapper for the internal v2 reducer.
525
+ *
526
+ * The mutable reducer is never exposed. Authorization reads use only the last
527
+ * projection published after the store barrier. An admission places a
528
+ * fail-closed fence around both reducer mutation and durable publication.
529
+ */
530
+ export class TrustedNetworkV2DurablePolicyReducer {
531
+ store;
532
+ durability;
533
+ descriptor;
534
+ descriptorHash;
535
+ core;
536
+ published;
537
+ generation = 0n;
538
+ previousGenerationChecksum = copyBytes(ZERO_DIGEST);
539
+ durableCoreBytes;
540
+ observedHashes = new Set();
541
+ operationTail = Promise.resolve();
542
+ authorizationFences = 0;
543
+ terminalError;
544
+ constructor(properties) {
545
+ this.store = properties.store;
546
+ this.durability = properties.durability;
547
+ this.descriptor = deserialize(serialize(properties.descriptor), NetworkDescriptorV2);
548
+ this.descriptorHash = descriptorDigest(this.descriptor);
549
+ this.core = properties.core;
550
+ this.published = publishedFromReducer(this.core);
551
+ this.generation = properties.generation ?? 0n;
552
+ this.previousGenerationChecksum = copyBytes(properties.previousGenerationChecksum ?? ZERO_DIGEST);
553
+ this.durableCoreBytes =
554
+ properties.durableCoreBytes === undefined
555
+ ? undefined
556
+ : copyBytes(properties.durableCoreBytes);
557
+ this.observedHashes = new Set(properties.observedHashes);
558
+ }
559
+ static async open(options) {
560
+ assertNetworkDescriptorV2(options.descriptor);
561
+ const descriptor = deserialize(serialize(options.descriptor), NetworkDescriptorV2);
562
+ const signal = options.signal;
563
+ const store = options.store;
564
+ const coreProperties = {
565
+ descriptor,
566
+ resolvePolicyEntry: options.resolvePolicyEntry,
567
+ resolveTimeoutMs: options.resolveTimeoutMs,
568
+ signal,
569
+ maxPending: options.maxPending,
570
+ maxPendingPolicyBytes: options.maxPendingPolicyBytes,
571
+ };
572
+ assertOpenNotAborted(signal);
573
+ const durability = store?.crashSafeDurability;
574
+ if (durability?.crashSafe !== true ||
575
+ typeof durability.barrier !== "function") {
576
+ throw new Error("TrustedNetwork v2 durable policy requires a crash-safe store barrier");
577
+ }
578
+ // A successful fresh barrier is required on every open, including an empty
579
+ // store; a generic flush acknowledgement is not this physical fence.
580
+ await durability.barrier();
581
+ assertOpenNotAborted(signal);
582
+ const expectedDescriptorHash = descriptorDigest(descriptor);
583
+ // Keep only immutable keys while discovering the history, then use get()
584
+ // to decode one record at a time. This avoids retaining the raw log and its
585
+ // decoded payloads together during restore.
586
+ const generationKeys = [];
587
+ for await (const [key, input] of store.iterator()) {
588
+ assertOpenNotAborted(signal);
589
+ if (key.startsWith(GENERATION_KEY_PREFIX)) {
590
+ const suffix = key.slice(GENERATION_KEY_PREFIX.length);
591
+ if (!/^\d{20}$/.test(suffix)) {
592
+ throw new Error("Malformed policy-anchor generation key");
593
+ }
594
+ if (!(input instanceof Uint8Array) ||
595
+ input.byteLength === 0 ||
596
+ input.byteLength >
597
+ TRUSTED_NETWORK_V2_MAX_POLICY_ANCHOR_GENERATION_BYTES) {
598
+ throw new Error("Policy-anchor generation record exceeds its byte ceiling");
599
+ }
600
+ const generation = BigInt(suffix);
601
+ if (generation === 0n || generation > MAX_U64) {
602
+ throw new Error("Policy-anchor generation key is outside u64");
603
+ }
604
+ generationKeys.push(key);
605
+ continue;
606
+ }
607
+ if (key === TRUSTED_NETWORK_V2_POLICY_ANCHOR_STORE_OWNER ||
608
+ key.startsWith(`${TRUSTED_NETWORK_V2_POLICY_ANCHOR_STORE_OWNER}/`)) {
609
+ throw new Error("Unknown policy-anchor record in the owned namespace");
610
+ }
611
+ }
612
+ assertOpenNotAborted(signal);
613
+ generationKeys.sort();
614
+ let previousChecksum = copyBytes(ZERO_DIGEST);
615
+ let latestCoreBytes;
616
+ let latestDurableState;
617
+ let core;
618
+ let durableCoreBytes;
619
+ let forkEvidence;
620
+ const observedHashes = new Set();
621
+ const authenticatedEvidenceEntryByHash = new Map();
622
+ const canonicalChildren = [];
623
+ try {
624
+ for (let index = 0; index < generationKeys.length; index++) {
625
+ assertOpenNotAborted(signal);
626
+ const key = generationKeys[index];
627
+ const expectedGeneration = BigInt(index + 1);
628
+ const keyedGeneration = BigInt(key.slice(GENERATION_KEY_PREFIX.length));
629
+ if (keyedGeneration !== expectedGeneration) {
630
+ throw new Error("Policy-anchor generation history is gapped");
631
+ }
632
+ const input = await store.get(key);
633
+ assertOpenNotAborted(signal);
634
+ if (input === undefined) {
635
+ throw new Error("Policy-anchor generation disappeared during restore");
636
+ }
637
+ const { record, payload } = decodeGenerationRecord(input);
638
+ if (record.body.generation !== keyedGeneration ||
639
+ generationKey(record.body.generation) !== key) {
640
+ throw new Error("Policy-anchor generation key does not match record");
641
+ }
642
+ if (!equals(record.body.descriptorDigest, expectedDescriptorHash)) {
643
+ throw new Error("Policy-anchor generation belongs to another descriptor");
644
+ }
645
+ if (!equals(record.body.previousGenerationChecksum, previousChecksum)) {
646
+ throw new Error("Policy-anchor generation checksum chain is broken");
647
+ }
648
+ if (payload.kind === "state") {
649
+ if (latestDurableState?.state === "FORKED") {
650
+ throw new Error("A FORKED policy anchor may only append observation deltas");
651
+ }
652
+ latestCoreBytes = serialize(payload.payload.coreState);
653
+ latestDurableState = payload.durableState;
654
+ if (latestDurableState.state === "FORKED") {
655
+ core = await TrustedNetworkV2PolicyReducer.restore({
656
+ ...coreProperties,
657
+ durableState: latestDurableState,
658
+ });
659
+ assertOpenNotAborted(signal);
660
+ assertCanonicalCoreRestore(core, latestCoreBytes);
661
+ durableCoreBytes = copyBytes(latestCoreBytes);
662
+ forkEvidence = core.forkEvidence;
663
+ if (forkEvidence === undefined) {
664
+ throw new Error("Restored forked policy anchor has no fork evidence");
665
+ }
666
+ for (const child of forkEvidence.children) {
667
+ const hashKey = bytesKey(observationContentHash(child.entryBytes));
668
+ const retained = authenticatedEvidenceEntryByHash.get(hashKey);
669
+ if (retained !== undefined &&
670
+ !equals(retained, child.entryBytes)) {
671
+ throw new Error("Policy fork-observation content hash collision");
672
+ }
673
+ authenticatedEvidenceEntryByHash.set(hashKey, child.entryBytes);
674
+ observedHashes.add(hashKey);
675
+ retainCanonicalForkChild(canonicalChildren, child);
676
+ }
677
+ }
678
+ }
679
+ else {
680
+ if (latestDurableState?.state !== "FORKED" ||
681
+ core === undefined ||
682
+ forkEvidence === undefined) {
683
+ throw new Error("Policy fork-observation delta requires a preceding FORKED state");
684
+ }
685
+ const entryBytes = payload.payload.entryBytes;
686
+ const hashKey = bytesKey(observationContentHash(entryBytes));
687
+ if (observedHashes.has(hashKey)) {
688
+ const evidenceEntry = authenticatedEvidenceEntryByHash.get(hashKey);
689
+ if (evidenceEntry !== undefined &&
690
+ !equals(evidenceEntry, entryBytes)) {
691
+ throw new Error("Policy fork-observation content hash collision");
692
+ }
693
+ }
694
+ else {
695
+ const authenticated = await authenticatePolicySnapshotEntryV2(entryBytes, descriptor);
696
+ assertOpenNotAborted(signal);
697
+ if (authenticated.body.sequence !==
698
+ forkEvidence.commonParent.sequence + 1n ||
699
+ !equals(authenticated.body.previousPolicyDigest, forkEvidence.commonParent.digest)) {
700
+ throw new Error("Stored policy fork observation is not a direct child of the common parent");
701
+ }
702
+ observedHashes.add(hashKey);
703
+ retainCanonicalForkChild(canonicalChildren, {
704
+ digest: authenticated.digest,
705
+ entryBytes,
706
+ });
707
+ }
708
+ }
709
+ previousChecksum = copyBytes(record.checksum);
710
+ }
711
+ const highestGeneration = generationKeys.length === 0 ? undefined : BigInt(generationKeys.length);
712
+ if (highestGeneration !== undefined && latestCoreBytes === undefined) {
713
+ throw new Error("Policy-anchor history has no durable state generation");
714
+ }
715
+ if (core === undefined) {
716
+ if (highestGeneration === undefined) {
717
+ core = new TrustedNetworkV2PolicyReducer(coreProperties);
718
+ }
719
+ else {
720
+ core = await TrustedNetworkV2PolicyReducer.restore({
721
+ ...coreProperties,
722
+ durableState: latestDurableState,
723
+ });
724
+ assertOpenNotAborted(signal);
725
+ assertCanonicalCoreRestore(core, latestCoreBytes);
726
+ durableCoreBytes = copyBytes(latestCoreBytes);
727
+ }
728
+ }
729
+ if (latestDurableState?.state === "FORKED") {
730
+ if (forkEvidence === undefined) {
731
+ throw new Error("Restored forked policy anchor has no fork evidence");
732
+ }
733
+ if (canonicalChildren.length !== 2) {
734
+ throw new Error("Stored policy fork evidence has fewer than two distinct children");
735
+ }
736
+ const normalizedForkState = {
737
+ formatVersion: FORMAT_VERSION,
738
+ state: "FORKED",
739
+ commonParentEntryBytes: copyBytes(latestDurableState.commonParentEntryBytes),
740
+ childEntryBytes: [
741
+ copyBytes(canonicalChildren[0].entryBytes),
742
+ copyBytes(canonicalChildren[1].entryBytes),
743
+ ],
744
+ };
745
+ const pairChanged = canonicalChildren.some((child, index) => !equals(child.digest, forkEvidence.children[index].digest) ||
746
+ !equals(child.entryBytes, forkEvidence.children[index].entryBytes));
747
+ if (pairChanged) {
748
+ core.abort();
749
+ core = await TrustedNetworkV2PolicyReducer.restore({
750
+ ...coreProperties,
751
+ durableState: normalizedForkState,
752
+ });
753
+ assertOpenNotAborted(signal);
754
+ assertCanonicalCoreRestore(core, serialize(coreRecordFromState(normalizedForkState)));
755
+ }
756
+ latestDurableState = normalizedForkState;
757
+ durableCoreBytes = serialize(coreRecordFromState(normalizedForkState));
758
+ }
759
+ else if (observedHashes.size !== 0) {
760
+ throw new Error("Non-forked policy anchor has fork observations");
761
+ }
762
+ return new TrustedNetworkV2DurablePolicyReducer({
763
+ store,
764
+ durability,
765
+ descriptor,
766
+ core,
767
+ generation: highestGeneration,
768
+ previousGenerationChecksum: previousChecksum,
769
+ durableCoreBytes,
770
+ observedHashes,
771
+ });
772
+ }
773
+ catch (error) {
774
+ core?.abort();
775
+ throw error;
776
+ }
777
+ }
778
+ get state() {
779
+ if (this.terminalError !== undefined || this.core.state === "HALTED") {
780
+ return "HALTED";
781
+ }
782
+ return this.published.state;
783
+ }
784
+ get head() {
785
+ return copyHead(this.published.head);
786
+ }
787
+ get forkEvidence() {
788
+ return copyForkEvidence(this.published.forkEvidence);
789
+ }
790
+ get pendingCount() {
791
+ return this.core.pendingCount;
792
+ }
793
+ get pendingBytes() {
794
+ return this.core.pendingBytes;
795
+ }
796
+ get pendingDigests() {
797
+ return this.core.pendingDigests.map(copyBytes);
798
+ }
799
+ /** Projection query only; use isAuthorized() for the fail-closed gate. */
800
+ rolesFor(subject) {
801
+ return this.published.roles.get(keyId(subject)) ?? 0;
802
+ }
803
+ isAuthorized(subject, roles) {
804
+ if (this.authorizationFences !== 0 ||
805
+ this.state !== "ACTIVE" ||
806
+ !Number.isInteger(roles) ||
807
+ roles === 0 ||
808
+ (roles & ~TRUSTED_NETWORK_V2_KNOWN_ROLE_BITS) !== 0) {
809
+ return false;
810
+ }
811
+ return (this.rolesFor(subject) & roles) === roles;
812
+ }
813
+ abort() {
814
+ this.core.abort();
815
+ }
816
+ ingest(entryBytes) {
817
+ const captured = entryBytes instanceof Uint8Array &&
818
+ entryBytes.byteLength <= TRUSTED_NETWORK_V2_MAX_POLICY_ENTRY_BYTES
819
+ ? copyBytes(entryBytes)
820
+ : entryBytes;
821
+ return this.enqueue(async () => {
822
+ const result = await this.core.ingest(captured);
823
+ await this.persistCorePublication(result);
824
+ return result;
825
+ });
826
+ }
827
+ retryUnavailable() {
828
+ return this.enqueue(async () => {
829
+ const result = await this.core.retryUnavailable();
830
+ await this.persistCorePublication(result);
831
+ return result;
832
+ });
833
+ }
834
+ enqueue(operation) {
835
+ this.authorizationFences++;
836
+ const result = this.operationTail.then(async () => {
837
+ if (this.terminalError !== undefined)
838
+ throw this.terminalError;
839
+ try {
840
+ return await operation();
841
+ }
842
+ catch (error) {
843
+ throw this.halt(error);
844
+ }
845
+ });
846
+ this.operationTail = result.then(() => { }, () => { });
847
+ return result.finally(() => {
848
+ this.authorizationFences--;
849
+ });
850
+ }
851
+ halt(error) {
852
+ if (this.terminalError !== undefined)
853
+ return this.terminalError;
854
+ const cause = error instanceof Error ? error : new Error(String(error));
855
+ const terminal = new Error(`TrustedNetwork v2 durable policy publication is ambiguous and halted: ${cause.message}`);
856
+ terminal.cause = cause;
857
+ this.terminalError = terminal;
858
+ this.core.abort();
859
+ return terminal;
860
+ }
861
+ async persistCorePublication(result) {
862
+ const durableState = this.core.exportDurableState();
863
+ if (durableState.state === "EMPTY") {
864
+ if (this.durableCoreBytes !== undefined) {
865
+ throw this.halt("Durable policy state cannot return to EMPTY");
866
+ }
867
+ return;
868
+ }
869
+ const coreRecord = coreRecordFromState(durableState);
870
+ const coreBytes = serialize(coreRecord);
871
+ // FORKED is terminal. Once its common-parent anchor exists, later child
872
+ // proofs are observation deltas even when they change the live canonical
873
+ // pair; reopen derives that pair from the complete delta history.
874
+ const stateChanged = !(this.published.state === "FORKED" && durableState.state === "FORKED") &&
875
+ (this.durableCoreBytes === undefined ||
876
+ !equals(this.durableCoreBytes, coreBytes));
877
+ const suppliedObservations = new Map();
878
+ for (const proof of result.forkObservations ?? []) {
879
+ const contentHash = observationContentHash(proof.entryBytes);
880
+ const hashKey = bytesKey(contentHash);
881
+ const retained = suppliedObservations.get(hashKey);
882
+ if (retained !== undefined && !equals(retained, proof.entryBytes)) {
883
+ throw this.halt("Policy fork-observation content hash collision");
884
+ }
885
+ suppliedObservations.set(hashKey, copyBytes(proof.entryBytes));
886
+ }
887
+ if (durableState.state !== "FORKED") {
888
+ if (suppliedObservations.size !== 0 || this.observedHashes.size !== 0) {
889
+ throw this.halt("Only a forked policy anchor may contain observations");
890
+ }
891
+ }
892
+ else {
893
+ for (const entryBytes of durableState.childEntryBytes) {
894
+ const hashKey = bytesKey(observationContentHash(entryBytes));
895
+ if (stateChanged)
896
+ suppliedObservations.delete(hashKey);
897
+ else if (!this.observedHashes.has(hashKey) &&
898
+ !suppliedObservations.has(hashKey)) {
899
+ throw this.halt("Published fork state is missing a canonical observation");
900
+ }
901
+ }
902
+ }
903
+ for (const hashKey of this.observedHashes) {
904
+ suppliedObservations.delete(hashKey);
905
+ }
906
+ const observationEntries = [...suppliedObservations.entries()]
907
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
908
+ .map(([hashKey, entryBytes]) => ({ hashKey, entryBytes }));
909
+ const recordCount = (stateChanged ? 1 : 0) + observationEntries.length;
910
+ if (recordCount === 0)
911
+ return;
912
+ if (BigInt(recordCount) > MAX_U64 - this.generation) {
913
+ throw this.halt("Policy-anchor generation exhausted u64");
914
+ }
915
+ let nextGeneration = this.generation;
916
+ let previousChecksum = copyBytes(this.previousGenerationChecksum);
917
+ const stagedObservedHashes = new Set(this.observedHashes);
918
+ const drafts = [];
919
+ if (stateChanged) {
920
+ const payloadBytes = serialize(new PolicyAnchorStateGenerationPayloadV2({ coreState: coreRecord }));
921
+ if (payloadBytes.byteLength > MAX_STATE_GENERATION_PAYLOAD_BYTES) {
922
+ throw this.halt("Policy-anchor state payload exceeds its byte ceiling");
923
+ }
924
+ drafts.push({ kind: GENERATION_KIND.STATE, payloadBytes });
925
+ }
926
+ for (const { hashKey, entryBytes } of observationEntries) {
927
+ const payloadBytes = serialize(new PolicyAnchorObservationGenerationPayloadV2({
928
+ entryBytes: copyBytes(entryBytes),
929
+ }));
930
+ if (payloadBytes.byteLength > MAX_OBSERVATION_GENERATION_PAYLOAD_BYTES) {
931
+ throw this.halt("Policy fork-observation payload exceeds its byte ceiling");
932
+ }
933
+ drafts.push({
934
+ kind: GENERATION_KIND.FORK_OBSERVATION,
935
+ payloadBytes,
936
+ applyObservationHash: hashKey,
937
+ });
938
+ }
939
+ for (const draft of drafts) {
940
+ nextGeneration += 1n;
941
+ if (draft.kind === GENERATION_KIND.STATE) {
942
+ if (durableState.state === "FORKED") {
943
+ for (const entryBytes of durableState.childEntryBytes) {
944
+ stagedObservedHashes.add(bytesKey(observationContentHash(entryBytes)));
945
+ }
946
+ }
947
+ }
948
+ else {
949
+ stagedObservedHashes.add(draft.applyObservationHash);
950
+ }
951
+ const body = new PolicyAnchorGenerationBodyV2({
952
+ formatVersion: FORMAT_VERSION,
953
+ generation: nextGeneration,
954
+ descriptorDigest: copyBytes(this.descriptorHash),
955
+ previousGenerationChecksum: copyBytes(previousChecksum),
956
+ kind: draft.kind,
957
+ payloadBytes: copyBytes(draft.payloadBytes),
958
+ });
959
+ const record = new PolicyAnchorGenerationRecordV2({
960
+ body,
961
+ checksum: generationChecksum(body),
962
+ });
963
+ const recordBytes = serialize(record);
964
+ if (recordBytes.byteLength >
965
+ TRUSTED_NETWORK_V2_MAX_POLICY_ANCHOR_GENERATION_BYTES) {
966
+ throw this.halt("Policy-anchor generation record exceeds its byte ceiling");
967
+ }
968
+ const key = generationKey(nextGeneration);
969
+ if ((await this.store.get(key)) !== undefined) {
970
+ throw this.halt("Policy-anchor generation must never be overwritten");
971
+ }
972
+ await this.store.put(key, copyBytes(recordBytes));
973
+ // Each immutable generation gets one physical fence. The projection is
974
+ // published only after every state/observation delta is fenced.
975
+ await this.durability.barrier();
976
+ previousChecksum = copyBytes(record.checksum);
977
+ }
978
+ this.generation = nextGeneration;
979
+ this.previousGenerationChecksum = previousChecksum;
980
+ this.durableCoreBytes = copyBytes(coreBytes);
981
+ this.observedHashes = stagedObservedHashes;
982
+ try {
983
+ this.published = publishedFromReducer(this.core);
984
+ }
985
+ catch (error) {
986
+ throw this.halt(error);
987
+ }
988
+ }
989
+ }
990
+ //# sourceMappingURL=v2-policy-anchor.js.map