@tinycloud/sdk-core 2.6.3 → 2.7.0-beta.3

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,2166 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/policy/index.ts
21
+ var policy_exports = {};
22
+ __export(policy_exports, {
23
+ ED25519_JCS_SIGNATURE_SUITE: () => ED25519_JCS_SIGNATURE_SUITE,
24
+ EIP191_JCS_SIGNATURE_SUITE: () => EIP191_JCS_SIGNATURE_SUITE,
25
+ OWNER_NODE_ENDPOINT_SCHEMA: () => OWNER_NODE_ENDPOINT_SCHEMA,
26
+ POLICY_ENGINE_RECORD_SCHEMA: () => POLICY_ENGINE_RECORD_SCHEMA,
27
+ POLICY_SCHEMA: () => POLICY_SCHEMA,
28
+ POLICY_STATUS_SCHEMA: () => POLICY_STATUS_SCHEMA,
29
+ POLICY_VERSION_V0: () => POLICY_VERSION_V0,
30
+ PolicyAuthoringError: () => PolicyAuthoringError,
31
+ PolicyCapabilityError: () => PolicyCapabilityError,
32
+ SignatureMaterialError: () => SignatureMaterialError,
33
+ SignatureVerificationError: () => SignatureVerificationError,
34
+ SignedObjectCanonicalizationError: () => SignedObjectCanonicalizationError,
35
+ SignedObjectDigestError: () => SignedObjectDigestError,
36
+ SignedObjectIdError: () => SignedObjectIdError,
37
+ SignedObjectProfileError: () => SignedObjectProfileError,
38
+ SignedObjectSchemaError: () => SignedObjectSchemaError,
39
+ SigningKeyBindingError: () => SigningKeyBindingError,
40
+ TRANSCRIPT_SHARE_BOOTSTRAP_SCHEMA: () => TRANSCRIPT_SHARE_BOOTSTRAP_SCHEMA,
41
+ UnsupportedSignatureSuiteError: () => UnsupportedSignatureSuiteError,
42
+ W3C_VC_CREDENTIAL_VERIFIER: () => W3C_VC_CREDENTIAL_VERIFIER,
43
+ canonicalizePolicyCapability: () => canonicalizePolicyCapability,
44
+ canonicalizeSignedObjectUnsigned: () => canonicalizeSignedObjectUnsigned,
45
+ composeTranscriptShareBootstrap: () => composeTranscriptShareBootstrap,
46
+ createAndSignPolicy: () => createAndSignPolicy,
47
+ createAndSignPolicyEngineRecord: () => createAndSignPolicyEngineRecord,
48
+ createAndSignPolicyStatus: () => createAndSignPolicyStatus,
49
+ createAndSignRequesterPolicyEngineRecord: () => createAndSignRequesterPolicyEngineRecord,
50
+ createAndSignSignedObject: () => createAndSignSignedObject,
51
+ createAndSignTranscriptSharePolicy: () => createAndSignTranscriptSharePolicy,
52
+ createUnsignedPolicyEngineRecord: () => createUnsignedPolicyEngineRecord,
53
+ deriveSignedObjectMaterial: () => deriveSignedObjectMaterial,
54
+ jcsCanonicalize: () => jcsCanonicalize,
55
+ normalizeJson: () => normalizeJson,
56
+ normalizePolicyCapability: () => normalizePolicyCapability,
57
+ policyCapabilityContains: () => policyCapabilityContains,
58
+ policyCapabilityDigestHex: () => policyCapabilityDigestHex,
59
+ serializeJcsJson: () => serialize,
60
+ signedObjectIdFor: () => signedObjectIdFor,
61
+ toSignedObjectError: () => toSignedObjectError,
62
+ validatePolicyEngineRecordSigned: () => validatePolicyEngineRecordSigned,
63
+ validatePolicyEngineRecordSignedShape: () => validatePolicyEngineRecordSignedShape,
64
+ validatePolicyEngineRecordUnsigned: () => validatePolicyEngineRecordUnsigned,
65
+ validatePolicySigned: () => validatePolicySigned,
66
+ validatePolicySignedShape: () => validatePolicySignedShape,
67
+ validatePolicyStatusSigned: () => validatePolicyStatusSigned,
68
+ validatePolicyStatusSignedShape: () => validatePolicyStatusSignedShape,
69
+ validatePolicyStatusUnsigned: () => validatePolicyStatusUnsigned,
70
+ validatePolicyUnsigned: () => validatePolicyUnsigned,
71
+ verifyPolicy: () => verifyPolicy,
72
+ verifyPolicyEngineRecord: () => verifyPolicyEngineRecord,
73
+ verifyPolicyEngineRecordForRequester: () => verifyPolicyEngineRecordForRequester,
74
+ verifyPolicyStatus: () => verifyPolicyStatus,
75
+ verifySignedObject: () => verifySignedObject
76
+ });
77
+ module.exports = __toCommonJS(policy_exports);
78
+
79
+ // src/policy/errors.ts
80
+ var SignedObjectProfileError = class extends Error {
81
+ constructor(code, message) {
82
+ super(message);
83
+ this.name = "SignedObjectProfileError";
84
+ this.code = code;
85
+ }
86
+ };
87
+ var SignedObjectSchemaError = class extends SignedObjectProfileError {
88
+ constructor(message) {
89
+ super("schema-invalid", message);
90
+ this.name = "SignedObjectSchemaError";
91
+ }
92
+ };
93
+ var SignedObjectCanonicalizationError = class extends SignedObjectProfileError {
94
+ constructor(message) {
95
+ super("canonicalization-mismatch", message);
96
+ this.name = "SignedObjectCanonicalizationError";
97
+ }
98
+ };
99
+ var SignedObjectDigestError = class extends SignedObjectProfileError {
100
+ constructor(message) {
101
+ super("digest-mismatch", message);
102
+ this.name = "SignedObjectDigestError";
103
+ }
104
+ };
105
+ var SignedObjectIdError = class extends SignedObjectProfileError {
106
+ constructor(message) {
107
+ super("id-mismatch", message);
108
+ this.name = "SignedObjectIdError";
109
+ }
110
+ };
111
+ var SigningKeyBindingError = class extends SignedObjectProfileError {
112
+ constructor(message) {
113
+ super("signing-key-binding", message);
114
+ this.name = "SigningKeyBindingError";
115
+ }
116
+ };
117
+ var SignatureMaterialError = class extends SignedObjectProfileError {
118
+ constructor(message) {
119
+ super("signature-material-invalid", message);
120
+ this.name = "SignatureMaterialError";
121
+ }
122
+ };
123
+ var UnsupportedSignatureSuiteError = class extends SignedObjectProfileError {
124
+ constructor(message) {
125
+ super("signature-suite-unsupported", message);
126
+ this.name = "UnsupportedSignatureSuiteError";
127
+ }
128
+ };
129
+ var SignatureVerificationError = class extends SignedObjectProfileError {
130
+ constructor(message) {
131
+ super("signature-invalid", message);
132
+ this.name = "SignatureVerificationError";
133
+ }
134
+ };
135
+ function toSignedObjectError(error) {
136
+ if (error instanceof SignedObjectProfileError) {
137
+ return error;
138
+ }
139
+ return new SignedObjectProfileError(
140
+ "schema-invalid",
141
+ error instanceof Error ? error.message : String(error)
142
+ );
143
+ }
144
+
145
+ // src/policy/jcs.ts
146
+ var objectHasOwn = Object.hasOwn ?? Object.prototype.hasOwnProperty.call.bind(
147
+ Object.prototype.hasOwnProperty
148
+ );
149
+ function jcsCanonicalize(input) {
150
+ return serialize(normalizeJson(input, "$"));
151
+ }
152
+ function normalizeJson(input, path = "$") {
153
+ if (input === null) {
154
+ return null;
155
+ }
156
+ switch (typeof input) {
157
+ case "boolean":
158
+ return input;
159
+ case "number":
160
+ if (!Number.isFinite(input)) {
161
+ throw new SignedObjectCanonicalizationError(
162
+ `${path} must be a finite JSON number`
163
+ );
164
+ }
165
+ return input;
166
+ case "string":
167
+ assertUnicodeScalarString(input, path);
168
+ return input;
169
+ case "object":
170
+ return normalizeJsonObjectOrArray(input, path);
171
+ case "bigint":
172
+ case "function":
173
+ case "symbol":
174
+ case "undefined":
175
+ default:
176
+ throw new SignedObjectCanonicalizationError(
177
+ `${path} is not a JSON value`
178
+ );
179
+ }
180
+ }
181
+ function serialize(value) {
182
+ if (value === null) {
183
+ return "null";
184
+ }
185
+ switch (typeof value) {
186
+ case "boolean":
187
+ return value ? "true" : "false";
188
+ case "number": {
189
+ const encoded = JSON.stringify(value);
190
+ if (encoded === void 0) {
191
+ throw new SignedObjectCanonicalizationError(
192
+ "number could not be serialized as JSON"
193
+ );
194
+ }
195
+ return encoded;
196
+ }
197
+ case "string":
198
+ return JSON.stringify(value);
199
+ case "object":
200
+ if (Array.isArray(value)) {
201
+ return `[${value.map((item) => serialize(item)).join(",")}]`;
202
+ }
203
+ return serializeObject(value);
204
+ default:
205
+ throw new SignedObjectCanonicalizationError(
206
+ `unsupported JSON value type ${typeof value}`
207
+ );
208
+ }
209
+ }
210
+ function normalizeJsonObjectOrArray(input, path) {
211
+ assertNoSymbolKeys(input, path);
212
+ if (Array.isArray(input)) {
213
+ for (const key of Object.getOwnPropertyNames(input)) {
214
+ if (key === "length") {
215
+ continue;
216
+ }
217
+ if (!isArrayIndexKey(key, input.length)) {
218
+ throw new SignedObjectCanonicalizationError(
219
+ `${path}.${key} is not allowed on a JSON array`
220
+ );
221
+ }
222
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
223
+ if (descriptor?.enumerable !== true) {
224
+ throw new SignedObjectCanonicalizationError(
225
+ `${path}[${key}] must be an enumerable JSON array item`
226
+ );
227
+ }
228
+ if (!("value" in descriptor)) {
229
+ throw new SignedObjectCanonicalizationError(
230
+ `${path}[${key}] must be a JSON data property`
231
+ );
232
+ }
233
+ }
234
+ const output2 = [];
235
+ for (let index = 0; index < input.length; index++) {
236
+ if (!objectHasOwn(input, index)) {
237
+ throw new SignedObjectCanonicalizationError(
238
+ `${path}[${index}] must not be a sparse array hole`
239
+ );
240
+ }
241
+ output2.push(normalizeJson(input[index], `${path}[${index}]`));
242
+ }
243
+ return output2;
244
+ }
245
+ const proto = Object.getPrototypeOf(input);
246
+ if (proto !== Object.prototype && proto !== null) {
247
+ throw new SignedObjectCanonicalizationError(
248
+ `${path} must be a plain JSON object`
249
+ );
250
+ }
251
+ const output = /* @__PURE__ */ Object.create(null);
252
+ for (const key of Object.getOwnPropertyNames(input)) {
253
+ assertUnicodeScalarString(key, `${path} key`);
254
+ if (key === "__proto__" || key === "constructor") {
255
+ throw new SignedObjectCanonicalizationError(
256
+ `${path}.${key} is not allowed`
257
+ );
258
+ }
259
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
260
+ if (descriptor?.enumerable !== true) {
261
+ throw new SignedObjectCanonicalizationError(
262
+ `${path}.${key} must be an enumerable JSON object property`
263
+ );
264
+ }
265
+ if (!("value" in descriptor)) {
266
+ throw new SignedObjectCanonicalizationError(
267
+ `${path}.${key} must be a JSON data property`
268
+ );
269
+ }
270
+ const value = descriptor.value;
271
+ output[key] = normalizeJson(value, `${path}.${key}`);
272
+ }
273
+ return output;
274
+ }
275
+ function assertNoSymbolKeys(input, path) {
276
+ if (Object.getOwnPropertySymbols(input).length > 0) {
277
+ throw new SignedObjectCanonicalizationError(
278
+ `${path} must not have symbol properties`
279
+ );
280
+ }
281
+ }
282
+ function isArrayIndexKey(key, length) {
283
+ if (!/^(0|[1-9]\d*)$/.test(key)) {
284
+ return false;
285
+ }
286
+ const index = Number(key);
287
+ return Number.isSafeInteger(index) && index >= 0 && index < length;
288
+ }
289
+ function serializeObject(value) {
290
+ const keys = Object.keys(value).sort(compareCodePoints);
291
+ const parts = keys.map((key) => `${JSON.stringify(key)}:${serialize(value[key])}`);
292
+ return `{${parts.join(",")}}`;
293
+ }
294
+ function compareCodePoints(a, b) {
295
+ const left = Array.from(a);
296
+ const right = Array.from(b);
297
+ const max = Math.min(left.length, right.length);
298
+ for (let index = 0; index < max; index++) {
299
+ const leftPoint = left[index].codePointAt(0) ?? 0;
300
+ const rightPoint = right[index].codePointAt(0) ?? 0;
301
+ if (leftPoint !== rightPoint) {
302
+ return leftPoint - rightPoint;
303
+ }
304
+ }
305
+ return left.length - right.length;
306
+ }
307
+ function assertUnicodeScalarString(value, path) {
308
+ for (let index = 0; index < value.length; index++) {
309
+ const code = value.charCodeAt(index);
310
+ if (code >= 55296 && code <= 56319) {
311
+ const next = value.charCodeAt(index + 1);
312
+ if (Number.isNaN(next) || next < 56320 || next > 57343) {
313
+ throw new SignedObjectCanonicalizationError(
314
+ `${path} contains a lone high surrogate`
315
+ );
316
+ }
317
+ index++;
318
+ continue;
319
+ }
320
+ if (code >= 56320 && code <= 57343) {
321
+ throw new SignedObjectCanonicalizationError(
322
+ `${path} contains a lone low surrogate`
323
+ );
324
+ }
325
+ }
326
+ }
327
+
328
+ // src/policy/capability.ts
329
+ var import_bootstrap = require("@tinycloud/bootstrap");
330
+ var import_viem = require("viem");
331
+ var POLICY_CAPABILITY_DOMAIN = "xyz.tinycloud.policy/PolicyCapability/v0";
332
+ var textEncoder = new TextEncoder();
333
+ var PolicyCapabilityError = class extends Error {
334
+ constructor(code, message) {
335
+ super(message);
336
+ this.name = "PolicyCapabilityError";
337
+ this.code = code;
338
+ }
339
+ };
340
+ var objectHasOwn2 = Object.hasOwn ?? Object.prototype.hasOwnProperty.call.bind(
341
+ Object.prototype.hasOwnProperty
342
+ );
343
+ var CEILING_SERVICES = /* @__PURE__ */ new Set(["tinycloud.kv", "tinycloud.sql", "tinycloud.vfs"]);
344
+ var GRANTABLE_ACTIONS = /* @__PURE__ */ new Map();
345
+ for (const entry of import_bootstrap.CAPABILITY_REGISTRY) {
346
+ if (!CEILING_SERVICES.has(entry.service)) {
347
+ continue;
348
+ }
349
+ if (entry.aliasOf !== void 0 || entry.implies !== void 0 || entry.urn.endsWith("/*")) {
350
+ continue;
351
+ }
352
+ const existing = GRANTABLE_ACTIONS.get(entry.service);
353
+ if (existing === void 0) {
354
+ GRANTABLE_ACTIONS.set(entry.service, /* @__PURE__ */ new Set([entry.urn]));
355
+ continue;
356
+ }
357
+ existing.add(entry.urn);
358
+ }
359
+ function normalizePolicyCapability(input) {
360
+ return normalizePolicyCapabilityWithOptions(input, { requireCanonical: true });
361
+ }
362
+ function canonicalizePolicyCapability(input) {
363
+ return normalizePolicyCapabilityWithOptions(input, { allowPrefixPaths: true });
364
+ }
365
+ function policyCapabilityDigestHex(input) {
366
+ const canonical = canonicalizePolicyCapability(input);
367
+ const jcs = textEncoder.encode(jcsCanonicalize(canonical));
368
+ const domain = textEncoder.encode(`${POLICY_CAPABILITY_DOMAIN}\0`);
369
+ const bytes = new Uint8Array(domain.length + jcs.length);
370
+ bytes.set(domain, 0);
371
+ bytes.set(jcs, domain.length);
372
+ return (0, import_viem.bytesToHex)((0, import_viem.sha256)(bytes, "bytes")).slice(2);
373
+ }
374
+ function policyCapabilityContains(authority, request) {
375
+ let auth;
376
+ let req;
377
+ try {
378
+ auth = canonicalizePolicyCapability(authority);
379
+ req = canonicalizePolicyCapability(request);
380
+ } catch {
381
+ return false;
382
+ }
383
+ if (auth.service !== req.service || auth.space !== req.space) {
384
+ return false;
385
+ }
386
+ if (!pathContains(auth.path, req.path)) {
387
+ return false;
388
+ }
389
+ const authActions = new Set(auth.actions);
390
+ for (const action of req.actions) {
391
+ if (!authActions.has(action)) {
392
+ return false;
393
+ }
394
+ }
395
+ return caveatsContain(auth.caveats, req.caveats);
396
+ }
397
+ function normalizePolicyCapabilityWithOptions(input, options) {
398
+ const object = expectObject(input, "$");
399
+ assertExactKeys(object, ["service", "space", "path", "actions", "caveats"], "$");
400
+ const service = requiredString(object, "service", "$", "policy-capability-malformed-service");
401
+ if (!CEILING_SERVICES.has(service)) {
402
+ throw new PolicyCapabilityError(
403
+ "policy-capability-malformed-service",
404
+ "$.service is outside the frozen permissionsCeiling vocabulary"
405
+ );
406
+ }
407
+ const space = requiredString(object, "space", "$", "policy-capability-malformed-space");
408
+ validateConcreteSpace(space);
409
+ const canonicalSpace = space.normalize("NFC");
410
+ if (options.requireCanonical && canonicalSpace !== space) {
411
+ throw new PolicyCapabilityError(
412
+ "policy-capability-malformed-space",
413
+ "$.space must already be canonical NFC"
414
+ );
415
+ }
416
+ const rawPath = requiredString(object, "path", "$", "policy-capability-malformed-path");
417
+ validateRawPath(rawPath, options);
418
+ const path = normalizePath(rawPath);
419
+ if (options.requireCanonical && path !== rawPath) {
420
+ throw new PolicyCapabilityError(
421
+ "policy-capability-malformed-path",
422
+ "$.path must already be canonical"
423
+ );
424
+ }
425
+ validateRawPath(path, options);
426
+ const actions = normalizeActions(
427
+ requiredArray(object, "actions", "$", "policy-capability-malformed-action"),
428
+ service,
429
+ options
430
+ );
431
+ const output = /* @__PURE__ */ Object.create(null);
432
+ output.service = service;
433
+ output.space = canonicalSpace;
434
+ output.path = path;
435
+ output.actions = actions;
436
+ if (hasOwn(object, "caveats")) {
437
+ output.caveats = validateCaveats(
438
+ requiredValue(object, "caveats", "$", "policy-capability-malformed-caveats"),
439
+ output.service
440
+ );
441
+ }
442
+ return output;
443
+ }
444
+ function expectObject(input, path) {
445
+ try {
446
+ const normalized = normalizeJson(input);
447
+ if (normalized === null || typeof normalized !== "object" || Array.isArray(normalized)) {
448
+ throw new PolicyCapabilityError("policy-capability-malformed", `${path} must be an object`);
449
+ }
450
+ return normalized;
451
+ } catch (error) {
452
+ if (error instanceof PolicyCapabilityError) {
453
+ throw error;
454
+ }
455
+ throw new PolicyCapabilityError(
456
+ "policy-capability-malformed",
457
+ error instanceof Error ? error.message : String(error)
458
+ );
459
+ }
460
+ }
461
+ function assertExactKeys(object, allowed, path) {
462
+ const allowedSet = new Set(allowed);
463
+ for (const key of Object.keys(object)) {
464
+ if (!allowedSet.has(key)) {
465
+ throw new PolicyCapabilityError(
466
+ key === "id" || key === "scope" ? "policy-capability-malformed" : "policy-capability-unknown-key",
467
+ `${path} has unknown field ${key}`
468
+ );
469
+ }
470
+ }
471
+ }
472
+ function requiredValue(object, key, path, code) {
473
+ if (!hasOwn(object, key)) {
474
+ throw new PolicyCapabilityError(code, `${path}.${key} is required`);
475
+ }
476
+ return object[key];
477
+ }
478
+ function requiredString(object, key, path, code) {
479
+ const value = requiredValue(object, key, path, code);
480
+ if (typeof value !== "string" || value.length === 0) {
481
+ throw new PolicyCapabilityError(code, `${path}.${key} must be a non-empty string`);
482
+ }
483
+ return value;
484
+ }
485
+ function requiredArray(object, key, path, code) {
486
+ const value = requiredValue(object, key, path, code);
487
+ if (!Array.isArray(value)) {
488
+ throw new PolicyCapabilityError(code, `${path}.${key} must be an array`);
489
+ }
490
+ return value;
491
+ }
492
+ function validateConcreteSpace(space) {
493
+ if (space === "*" || space.includes("*") || space.includes("?") || space.includes("/")) {
494
+ throw new PolicyCapabilityError(
495
+ "policy-capability-malformed-space",
496
+ "$.space must be concrete"
497
+ );
498
+ }
499
+ }
500
+ function validateRawPath(path, options) {
501
+ if (path.length === 0) {
502
+ throw new PolicyCapabilityError("policy-capability-malformed-path", "$.path is empty");
503
+ }
504
+ if (!options.allowPrefixPaths && path.endsWith("/")) {
505
+ throw new PolicyCapabilityError(
506
+ "policy-capability-malformed-path",
507
+ "$.path must be an exact concrete path, not a prefix"
508
+ );
509
+ }
510
+ if (path.endsWith("/*") || path.includes("**")) {
511
+ throw new PolicyCapabilityError("policy-capability-malformed-path", "$.path is a prefix form");
512
+ }
513
+ const segments = path.split("/");
514
+ for (let index = 0; index < segments.length; index++) {
515
+ const segment = segments[index];
516
+ const isTrailingPrefixSegment = options.allowPrefixPaths && index === segments.length - 1 && segment.length === 0;
517
+ if (segment.length === 0 && !isTrailingPrefixSegment) {
518
+ throw new PolicyCapabilityError("policy-capability-malformed-path", "$.path has an empty segment");
519
+ }
520
+ if (segment === "." || segment === "..") {
521
+ throw new PolicyCapabilityError(
522
+ "policy-capability-malformed-path",
523
+ "$.path has a traversal segment"
524
+ );
525
+ }
526
+ if (segment === "*" || segment === "?" || segment.includes("*") || segment.includes("?")) {
527
+ throw new PolicyCapabilityError(
528
+ "policy-capability-malformed-path",
529
+ "$.path has a wildcard segment"
530
+ );
531
+ }
532
+ }
533
+ }
534
+ function normalizePath(path) {
535
+ return decodeUnreserved(path).normalize("NFC");
536
+ }
537
+ function decodeUnreserved(path) {
538
+ return path.replace(/%[0-9A-Fa-f]{2}/g, (encoded) => {
539
+ const char = String.fromCharCode(Number.parseInt(encoded.slice(1), 16));
540
+ return /^[A-Za-z0-9._~-]$/.test(char) ? char : encoded.toUpperCase();
541
+ });
542
+ }
543
+ function normalizeActions(actions, service, options) {
544
+ const accepted = GRANTABLE_ACTIONS.get(service);
545
+ if (accepted === void 0) {
546
+ throw new PolicyCapabilityError(
547
+ "policy-capability-malformed-service",
548
+ "$.service is unsupported"
549
+ );
550
+ }
551
+ const unique = /* @__PURE__ */ new Set();
552
+ const rawActions = [];
553
+ for (let index = 0; index < actions.length; index++) {
554
+ const action = actions[index];
555
+ if (typeof action !== "string" || action.length === 0) {
556
+ throw new PolicyCapabilityError(
557
+ "policy-capability-malformed-action",
558
+ `$.actions[${index}] must be a non-empty action URN`
559
+ );
560
+ }
561
+ if (!action.startsWith(`${service}/`) || action.includes("*") || !accepted.has(action)) {
562
+ throw new PolicyCapabilityError(
563
+ "policy-capability-malformed-action",
564
+ `$.actions[${index}] is not a grantable action URN`
565
+ );
566
+ }
567
+ rawActions.push(action);
568
+ unique.add(action);
569
+ }
570
+ if (unique.size === 0) {
571
+ throw new PolicyCapabilityError(
572
+ "policy-capability-empty-actions",
573
+ "$.actions must not be empty"
574
+ );
575
+ }
576
+ const normalizedActions = [...unique].sort();
577
+ if (options.requireCanonical && (rawActions.length !== normalizedActions.length || rawActions.some((action, index) => action !== normalizedActions[index]))) {
578
+ throw new PolicyCapabilityError(
579
+ "policy-capability-malformed-action",
580
+ "$.actions must already be sorted, deduplicated canonical action URNs"
581
+ );
582
+ }
583
+ return normalizedActions;
584
+ }
585
+ function validateCaveats(input, service) {
586
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
587
+ throw new PolicyCapabilityError(
588
+ "policy-capability-malformed-caveats",
589
+ "$.caveats must be an object"
590
+ );
591
+ }
592
+ if (service === "tinycloud.sql") {
593
+ return validateSqlCaveats(input);
594
+ }
595
+ throw new PolicyCapabilityError(
596
+ "policy-capability-malformed-caveats",
597
+ "$.caveats are not defined for this service"
598
+ );
599
+ }
600
+ function validateSqlCaveats(input) {
601
+ assertCaveatKeys(input, ["mode", "readOnly", "statements"], "$.caveats");
602
+ const mode = caveatString(input, "mode", "$.caveats");
603
+ if (mode !== "constrained-statements") {
604
+ throw new PolicyCapabilityError(
605
+ "policy-capability-malformed-caveats",
606
+ "$.caveats.mode is unsupported"
607
+ );
608
+ }
609
+ if (requiredCaveat(input, "readOnly", "$.caveats") !== true) {
610
+ throw new PolicyCapabilityError(
611
+ "policy-capability-malformed-caveats",
612
+ "$.caveats.readOnly must be true"
613
+ );
614
+ }
615
+ const statements = requiredCaveat(input, "statements", "$.caveats");
616
+ if (!Array.isArray(statements) || statements.length === 0) {
617
+ throw new PolicyCapabilityError(
618
+ "policy-capability-malformed-caveats",
619
+ "$.caveats.statements must be a non-empty array"
620
+ );
621
+ }
622
+ for (let index = 0; index < statements.length; index++) {
623
+ validateSqlStatement(statements[index], `$.caveats.statements[${index}]`);
624
+ }
625
+ return input;
626
+ }
627
+ function validateSqlStatement(input, path) {
628
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
629
+ throw new PolicyCapabilityError("policy-capability-malformed-caveats", `${path} must be an object`);
630
+ }
631
+ const object = input;
632
+ assertCaveatKeys(object, ["name", "sql", "fixedParams"], path);
633
+ caveatString(object, "name", path);
634
+ caveatString(object, "sql", path);
635
+ const fixedParams = requiredCaveat(object, "fixedParams", path);
636
+ if (!Array.isArray(fixedParams)) {
637
+ throw new PolicyCapabilityError(
638
+ "policy-capability-malformed-caveats",
639
+ `${path}.fixedParams must be an array`
640
+ );
641
+ }
642
+ for (let index = 0; index < fixedParams.length; index++) {
643
+ validateFixedParam(fixedParams[index], `${path}.fixedParams[${index}]`);
644
+ }
645
+ }
646
+ function validateFixedParam(input, path) {
647
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
648
+ throw new PolicyCapabilityError("policy-capability-malformed-caveats", `${path} must be an object`);
649
+ }
650
+ const object = input;
651
+ assertCaveatKeys(object, ["index", "value"], path);
652
+ const index = requiredCaveat(object, "index", path);
653
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) {
654
+ throw new PolicyCapabilityError(
655
+ "policy-capability-malformed-caveats",
656
+ `${path}.index must be a non-negative integer`
657
+ );
658
+ }
659
+ requiredCaveat(object, "value", path);
660
+ }
661
+ function assertCaveatKeys(object, allowed, path) {
662
+ const allowedSet = new Set(allowed);
663
+ for (const key of Object.keys(object)) {
664
+ if (!allowedSet.has(key)) {
665
+ throw new PolicyCapabilityError(
666
+ "policy-capability-malformed-caveats",
667
+ `${path} has unknown field ${key}`
668
+ );
669
+ }
670
+ }
671
+ }
672
+ function requiredCaveat(object, key, path) {
673
+ if (!hasOwn(object, key)) {
674
+ throw new PolicyCapabilityError(
675
+ "policy-capability-malformed-caveats",
676
+ `${path}.${key} is required`
677
+ );
678
+ }
679
+ return object[key];
680
+ }
681
+ function caveatString(object, key, path) {
682
+ const value = requiredCaveat(object, key, path);
683
+ if (typeof value !== "string" || value.length === 0) {
684
+ throw new PolicyCapabilityError(
685
+ "policy-capability-malformed-caveats",
686
+ `${path}.${key} must be a non-empty string`
687
+ );
688
+ }
689
+ return value;
690
+ }
691
+ function pathContains(authority, request) {
692
+ if (authority === request) {
693
+ return true;
694
+ }
695
+ return authority.endsWith("/") && request.startsWith(authority);
696
+ }
697
+ function caveatsContain(authority, request) {
698
+ if (authority === void 0) {
699
+ return request === void 0;
700
+ }
701
+ if (request === void 0) {
702
+ return Object.keys(authority).length === 0;
703
+ }
704
+ if (authority.mode !== "constrained-statements" || request.mode !== "constrained-statements") {
705
+ return false;
706
+ }
707
+ const authorityStatements = Array.isArray(authority.statements) ? authority.statements : [];
708
+ const requestStatements = Array.isArray(request.statements) ? request.statements : [];
709
+ return requestStatements.every(
710
+ (statement) => authorityStatements.some((candidate) => jcsCanonicalize(candidate) === jcsCanonicalize(statement))
711
+ );
712
+ }
713
+ function hasOwn(object, key) {
714
+ return objectHasOwn2(object, key);
715
+ }
716
+
717
+ // src/policy/signed-object.ts
718
+ var import_ed25519 = require("@noble/curves/ed25519");
719
+ var import_basics = require("multiformats/basics");
720
+ var import_viem3 = require("viem");
721
+
722
+ // src/identity.ts
723
+ var import_viem2 = require("viem");
724
+ var IdentityParseError = class extends Error {
725
+ constructor(message) {
726
+ super(message);
727
+ this.name = "IdentityParseError";
728
+ }
729
+ };
730
+ var PKH_DID_RE = /^did:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40})$/;
731
+ function assertValidChainId(chainId) {
732
+ if (!Number.isSafeInteger(chainId) || chainId <= 0) {
733
+ throw new IdentityParseError(`Invalid EIP-155 chain ID: ${chainId}`);
734
+ }
735
+ }
736
+ function isEvmAddress(input) {
737
+ return (0, import_viem2.isAddress)(input, { strict: false });
738
+ }
739
+ function canonicalizeAddress(address) {
740
+ if (!isEvmAddress(address)) {
741
+ throw new IdentityParseError(`Invalid EVM address: ${address}`);
742
+ }
743
+ return (0, import_viem2.getAddress)(address);
744
+ }
745
+ function parsePkhDid(did) {
746
+ const match = did.match(PKH_DID_RE);
747
+ if (!match) return null;
748
+ const chainId = Number(match[1]);
749
+ assertValidChainId(chainId);
750
+ return {
751
+ method: "pkh",
752
+ namespace: "eip155",
753
+ chainId,
754
+ address: canonicalizeAddress(match[2])
755
+ };
756
+ }
757
+
758
+ // src/policy/signed-object.ts
759
+ var POLICY_SCHEMA = "xyz.tinycloud.policy/policy/v0";
760
+ var POLICY_STATUS_SCHEMA = "xyz.tinycloud.policy/status/v0";
761
+ var POLICY_ENGINE_RECORD_SCHEMA = "xyz.tinycloud.policy/engine-record/v0";
762
+ var ED25519_JCS_SIGNATURE_SUITE = "eddsa-ed25519-sha256-jcs-v1";
763
+ var EIP191_JCS_SIGNATURE_SUITE = "eip191-secp256k1-sha256-jcs-v1";
764
+ var DESCRIPTORS = {
765
+ Policy: {
766
+ kind: "Policy",
767
+ schema: POLICY_SCHEMA,
768
+ idField: "policyId",
769
+ idPrefix: "pol_",
770
+ domain: POLICY_SCHEMA
771
+ },
772
+ PolicyStatus: {
773
+ kind: "PolicyStatus",
774
+ schema: POLICY_STATUS_SCHEMA,
775
+ idField: "statusId",
776
+ idPrefix: "polst_",
777
+ domain: POLICY_STATUS_SCHEMA
778
+ },
779
+ PolicyEngineRecord: {
780
+ kind: "PolicyEngineRecord",
781
+ schema: POLICY_ENGINE_RECORD_SCHEMA,
782
+ idField: "engineRecordId",
783
+ idPrefix: "peng_",
784
+ domain: POLICY_ENGINE_RECORD_SCHEMA
785
+ }
786
+ };
787
+ var textEncoder2 = new TextEncoder();
788
+ var BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
789
+ var BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
790
+ var objectHasOwn3 = Object.hasOwn ?? Object.prototype.hasOwnProperty.call.bind(
791
+ Object.prototype.hasOwnProperty
792
+ );
793
+ function canonicalizeSignedObjectUnsigned(input) {
794
+ return jcsCanonicalize(input);
795
+ }
796
+ function deriveSignedObjectMaterial(input) {
797
+ const descriptor = descriptorForUnsigned(input);
798
+ const unsigned = validateUnsignedForDescriptor(input, descriptor);
799
+ return materialForUnsigned(unsigned, descriptor);
800
+ }
801
+ function signedObjectIdFor(input) {
802
+ return deriveSignedObjectMaterial(input).id;
803
+ }
804
+ async function createAndSignSignedObject(input, signer) {
805
+ const normalized = expectJsonObject(normalizeJson(input), "$");
806
+ const descriptor = descriptorForUnsigned(normalized);
807
+ const stripped = stripOwnIdAndSignature(normalized, descriptor);
808
+ const unsigned = validateUnsignedForDescriptor(stripped, descriptor);
809
+ if (descriptor.kind === "Policy") {
810
+ validatePolicyPermissionsCeilingForSigning(unsigned);
811
+ }
812
+ assertSupportedSignatureSuite(signer.suite);
813
+ requireStringType(signer.signerDid, "$.signer.signerDid");
814
+ assertSignerDidMatchesSuite(signer.signerDid, signer.suite);
815
+ assertSigningKeyBindingForCreate(unsigned, signer.signerDid);
816
+ const material = materialForUnsigned(unsigned, descriptor);
817
+ const signatureValue = encodeSignatureValue(
818
+ await signer.signDigest(material.digest),
819
+ signer.suite
820
+ );
821
+ const signature = validateSignature({
822
+ suite: signer.suite,
823
+ signerDid: signer.signerDid,
824
+ value: signatureValue
825
+ });
826
+ return {
827
+ ...unsigned,
828
+ [descriptor.idField]: material.id,
829
+ signature
830
+ };
831
+ }
832
+ function createAndSignPolicy(input, signer) {
833
+ return createAndSignSignedObject(input, signer).then(
834
+ (object) => validatePolicySignedShape(object)
835
+ );
836
+ }
837
+ function createAndSignPolicyStatus(input, signer) {
838
+ return createAndSignSignedObject(input, signer).then(
839
+ (object) => validatePolicyStatusSignedShape(object)
840
+ );
841
+ }
842
+ function createAndSignPolicyEngineRecord(input, signer) {
843
+ return createAndSignSignedObject(input, signer).then(
844
+ (object) => validatePolicyEngineRecordSignedShape(object)
845
+ );
846
+ }
847
+ async function verifySignedObject(input) {
848
+ const signed = validateSignedObjectShape(input);
849
+ const signedJson = signed;
850
+ const descriptor = descriptorForSchema(signed.schema);
851
+ const signature = validateSignature(signed.signature);
852
+ assertSigningKeyBindingForVerify(signedJson, signature);
853
+ const unsigned = stripOwnIdAndSignature(signedJson, descriptor);
854
+ const material = materialForUnsigned(unsigned, descriptor);
855
+ assertIdMatches(signedJson, material, descriptor);
856
+ if (!await verifySignature(signature, material.digest)) {
857
+ throw new SignatureVerificationError("signature verification failed");
858
+ }
859
+ return { object: signed, material };
860
+ }
861
+ async function verifyPolicy(input) {
862
+ const result = await verifySignedObject(input);
863
+ return {
864
+ object: validatePolicySignedShape(result.object),
865
+ material: result.material
866
+ };
867
+ }
868
+ async function verifyPolicyStatus(input) {
869
+ const result = await verifySignedObject(input);
870
+ return {
871
+ object: validatePolicyStatusSignedShape(result.object),
872
+ material: result.material
873
+ };
874
+ }
875
+ async function verifyPolicyEngineRecord(input) {
876
+ const result = await verifySignedObject(input);
877
+ return {
878
+ object: validatePolicyEngineRecordSignedShape(result.object),
879
+ material: result.material
880
+ };
881
+ }
882
+ async function validatePolicySigned(input) {
883
+ try {
884
+ const result = await verifyPolicy(input);
885
+ return { ok: true, object: result.object, material: result.material };
886
+ } catch (error) {
887
+ return { ok: false, error: toSignedObjectError(error) };
888
+ }
889
+ }
890
+ async function validatePolicyStatusSigned(input) {
891
+ try {
892
+ const result = await verifyPolicyStatus(input);
893
+ return { ok: true, object: result.object, material: result.material };
894
+ } catch (error) {
895
+ return { ok: false, error: toSignedObjectError(error) };
896
+ }
897
+ }
898
+ async function validatePolicyEngineRecordSigned(input) {
899
+ try {
900
+ const result = await verifyPolicyEngineRecord(input);
901
+ return { ok: true, object: result.object, material: result.material };
902
+ } catch (error) {
903
+ return { ok: false, error: toSignedObjectError(error) };
904
+ }
905
+ }
906
+ function validatePolicyUnsigned(input) {
907
+ return validatePolicyShape(input, false);
908
+ }
909
+ function validatePolicyStatusUnsigned(input) {
910
+ return validatePolicyStatusShape(input, false);
911
+ }
912
+ function validatePolicyEngineRecordUnsigned(input) {
913
+ return validatePolicyEngineRecordShape(input, false);
914
+ }
915
+ function validatePolicySignedShape(input) {
916
+ return validatePolicyShape(input, true);
917
+ }
918
+ function validatePolicyStatusSignedShape(input) {
919
+ return validatePolicyStatusShape(input, true);
920
+ }
921
+ function validatePolicyEngineRecordSignedShape(input) {
922
+ return validatePolicyEngineRecordShape(input, true);
923
+ }
924
+ function validateSignedObjectShape(input) {
925
+ const normalized = expectJsonObject(normalizeJson(input), "$");
926
+ const schema = requiredString2(normalized, "schema", "$");
927
+ const descriptor = descriptorForSchema(schema);
928
+ switch (descriptor.kind) {
929
+ case "Policy":
930
+ return validatePolicySignedShape(normalized);
931
+ case "PolicyStatus":
932
+ return validatePolicyStatusSignedShape(normalized);
933
+ case "PolicyEngineRecord":
934
+ return validatePolicyEngineRecordSignedShape(normalized);
935
+ }
936
+ }
937
+ function validateUnsignedForDescriptor(input, descriptor) {
938
+ switch (descriptor.kind) {
939
+ case "Policy":
940
+ return validatePolicyUnsigned(input);
941
+ case "PolicyStatus":
942
+ return validatePolicyStatusUnsigned(input);
943
+ case "PolicyEngineRecord":
944
+ return validatePolicyEngineRecordUnsigned(input);
945
+ }
946
+ }
947
+ function validatePolicyShape(input, signed) {
948
+ const object = expectJsonObject(normalizeJson(input), "$");
949
+ assertExactKeys2(
950
+ object,
951
+ signed ? [
952
+ "schema",
953
+ "policyId",
954
+ "ownerDid",
955
+ "signingKeyDid",
956
+ "createdAt",
957
+ "expiresAt",
958
+ "resource",
959
+ "when",
960
+ "grant",
961
+ "disclosure",
962
+ "audit",
963
+ "signature"
964
+ ] : [
965
+ "schema",
966
+ "ownerDid",
967
+ "signingKeyDid",
968
+ "createdAt",
969
+ "expiresAt",
970
+ "resource",
971
+ "when",
972
+ "grant",
973
+ "disclosure",
974
+ "audit"
975
+ ],
976
+ "$"
977
+ );
978
+ expectConst(requiredString2(object, "schema", "$"), POLICY_SCHEMA, "$.schema");
979
+ if (signed) {
980
+ requiredString2(object, "policyId", "$");
981
+ validateSignature(requiredValue2(object, "signature", "$"));
982
+ }
983
+ requiredString2(object, "ownerDid", "$");
984
+ requiredString2(object, "signingKeyDid", "$");
985
+ requiredDateString(object, "createdAt", "$");
986
+ optionalDateString(object, "expiresAt", "$");
987
+ validatePolicyResource(requiredValue2(object, "resource", "$"), "$.resource");
988
+ validateExpression(requiredValue2(object, "when", "$"), "$.when");
989
+ validateGrant(requiredValue2(object, "grant", "$"), "$.grant");
990
+ if (hasOwn2(object, "disclosure")) {
991
+ validateDisclosure(requiredValue2(object, "disclosure", "$"), "$.disclosure");
992
+ }
993
+ if (hasOwn2(object, "audit")) {
994
+ validateAudit(requiredValue2(object, "audit", "$"), "$.audit");
995
+ }
996
+ return object;
997
+ }
998
+ function validatePolicyStatusShape(input, signed) {
999
+ const object = expectJsonObject(normalizeJson(input), "$");
1000
+ assertExactKeys2(
1001
+ object,
1002
+ signed ? [
1003
+ "schema",
1004
+ "statusId",
1005
+ "policyId",
1006
+ "ownerDid",
1007
+ "sequence",
1008
+ "disposition",
1009
+ "effectiveAt",
1010
+ "reasonCode",
1011
+ "signingKeyDid",
1012
+ "signature"
1013
+ ] : [
1014
+ "schema",
1015
+ "policyId",
1016
+ "ownerDid",
1017
+ "sequence",
1018
+ "disposition",
1019
+ "effectiveAt",
1020
+ "reasonCode",
1021
+ "signingKeyDid"
1022
+ ],
1023
+ "$"
1024
+ );
1025
+ expectConst(requiredString2(object, "schema", "$"), POLICY_STATUS_SCHEMA, "$.schema");
1026
+ if (signed) {
1027
+ requiredString2(object, "statusId", "$");
1028
+ validateSignature(requiredValue2(object, "signature", "$"));
1029
+ }
1030
+ requiredString2(object, "policyId", "$");
1031
+ requiredString2(object, "ownerDid", "$");
1032
+ requiredInteger(object, "sequence", "$", 0);
1033
+ expectOneOf(requiredString2(object, "disposition", "$"), [
1034
+ "active",
1035
+ "suspended",
1036
+ "revoked"
1037
+ ], "$.disposition");
1038
+ requiredDateString(object, "effectiveAt", "$");
1039
+ optionalString(object, "reasonCode", "$");
1040
+ requiredString2(object, "signingKeyDid", "$");
1041
+ return object;
1042
+ }
1043
+ function validatePolicyEngineRecordShape(input, signed) {
1044
+ const object = expectJsonObject(normalizeJson(input), "$");
1045
+ assertExactKeys2(
1046
+ object,
1047
+ signed ? [
1048
+ "schema",
1049
+ "engineRecordId",
1050
+ "ownerDid",
1051
+ "endpoint",
1052
+ "audience",
1053
+ "supportedPolicyVersions",
1054
+ "supportedEvidenceVerifiers",
1055
+ "grantIssuerDid",
1056
+ "expiresAt",
1057
+ "signature"
1058
+ ] : [
1059
+ "schema",
1060
+ "ownerDid",
1061
+ "endpoint",
1062
+ "audience",
1063
+ "supportedPolicyVersions",
1064
+ "supportedEvidenceVerifiers",
1065
+ "grantIssuerDid",
1066
+ "expiresAt"
1067
+ ],
1068
+ "$"
1069
+ );
1070
+ expectConst(
1071
+ requiredString2(object, "schema", "$"),
1072
+ POLICY_ENGINE_RECORD_SCHEMA,
1073
+ "$.schema"
1074
+ );
1075
+ if (signed) {
1076
+ requiredString2(object, "engineRecordId", "$");
1077
+ validateSignature(requiredValue2(object, "signature", "$"));
1078
+ }
1079
+ requiredString2(object, "ownerDid", "$");
1080
+ requiredString2(object, "endpoint", "$");
1081
+ requiredString2(object, "audience", "$");
1082
+ requiredStringArray(
1083
+ object,
1084
+ "supportedPolicyVersions",
1085
+ "$",
1086
+ (value, path) => expectConst(value, "v0", path)
1087
+ );
1088
+ requiredStringArray(object, "supportedEvidenceVerifiers", "$");
1089
+ requiredString2(object, "grantIssuerDid", "$");
1090
+ requiredDateString(object, "expiresAt", "$");
1091
+ return object;
1092
+ }
1093
+ function validateSignature(input) {
1094
+ const object = expectJsonObject(input, "$.signature");
1095
+ assertExactKeys2(object, ["suite", "signerDid", "value"], "$.signature");
1096
+ const suite = requiredString2(object, "suite", "$.signature");
1097
+ assertSupportedSignatureSuite(suite);
1098
+ const signerDid = requiredString2(object, "signerDid", "$.signature");
1099
+ const value = requiredString2(object, "value", "$.signature");
1100
+ decodeSignatureValue(value, suite);
1101
+ return { suite, signerDid, value };
1102
+ }
1103
+ function validatePolicyResource(input, path) {
1104
+ const object = expectJsonObject(input, path);
1105
+ assertExactKeys2(object, ["resourceType", "resourceId", "permissionsCeiling"], path);
1106
+ requiredString2(object, "resourceType", path);
1107
+ requiredString2(object, "resourceId", path);
1108
+ const ceiling = requiredArray2(object, "permissionsCeiling", path, 1);
1109
+ for (let index = 0; index < ceiling.length; index++) {
1110
+ validatePolicyCapability(ceiling[index], `${path}.permissionsCeiling[${index}]`);
1111
+ }
1112
+ }
1113
+ function validatePolicyPermissionsCeilingForSigning(input) {
1114
+ const resource = expectJsonObject(requiredValue2(input, "resource", "$"), "$.resource");
1115
+ const ceiling = requiredArray2(resource, "permissionsCeiling", "$.resource", 1);
1116
+ for (let index = 0; index < ceiling.length; index++) {
1117
+ validatePolicyCapabilityForSigning(
1118
+ ceiling[index],
1119
+ `$.resource.permissionsCeiling[${index}]`
1120
+ );
1121
+ }
1122
+ }
1123
+ function validatePolicyCapability(input, path) {
1124
+ const object = expectJsonObject(input, path);
1125
+ try {
1126
+ const canonical = canonicalizePolicyCapability(object);
1127
+ if (jcsCanonicalize(object) !== jcsCanonicalize(canonical)) {
1128
+ throw new SignedObjectSchemaError(`${path} must be canonical PolicyCapability JSON`);
1129
+ }
1130
+ } catch (error) {
1131
+ if (error instanceof SignedObjectSchemaError) {
1132
+ throw error;
1133
+ }
1134
+ throw new SignedObjectSchemaError(
1135
+ error instanceof Error ? error.message : String(error)
1136
+ );
1137
+ }
1138
+ }
1139
+ function validatePolicyCapabilityForSigning(input, path) {
1140
+ const object = expectJsonObject(input, path);
1141
+ try {
1142
+ const canonical = normalizePolicyCapability(object);
1143
+ if (jcsCanonicalize(object) !== jcsCanonicalize(canonical)) {
1144
+ throw new SignedObjectSchemaError(`${path} must be strict canonical PolicyCapability JSON`);
1145
+ }
1146
+ } catch (error) {
1147
+ if (error instanceof SignedObjectSchemaError) {
1148
+ throw error;
1149
+ }
1150
+ throw new SignedObjectSchemaError(
1151
+ error instanceof Error ? error.message : String(error)
1152
+ );
1153
+ }
1154
+ }
1155
+ function validateExpression(input, path) {
1156
+ const object = expectJsonObject(input, path);
1157
+ const keys = Object.keys(object);
1158
+ if (keys.length !== 1) {
1159
+ throw new SignedObjectSchemaError(`${path} must have exactly one expression key`);
1160
+ }
1161
+ const key = keys[0];
1162
+ if (key === "allOf" || key === "anyOf") {
1163
+ const values = requiredArray2(object, key, path, 1);
1164
+ for (let index = 0; index < values.length; index++) {
1165
+ validateExpression(values[index], `${path}.${key}[${index}]`);
1166
+ }
1167
+ return;
1168
+ }
1169
+ if (key === "subject") {
1170
+ const subject = expectJsonObject(requiredValue2(object, "subject", path), `${path}.subject`);
1171
+ assertExactKeys2(subject, ["did"], `${path}.subject`);
1172
+ requiredString2(subject, "did", `${path}.subject`);
1173
+ return;
1174
+ }
1175
+ if (key === "evidence") {
1176
+ validateEvidenceRequirement(requiredValue2(object, "evidence", path), `${path}.evidence`);
1177
+ return;
1178
+ }
1179
+ throw new SignedObjectSchemaError(`${path} has unknown expression key ${key}`);
1180
+ }
1181
+ function validateEvidenceRequirement(input, path) {
1182
+ const object = expectJsonObject(input, path);
1183
+ assertExactKeys2(
1184
+ object,
1185
+ ["requirementId", "verifier", "requirements", "authority", "freshness"],
1186
+ path
1187
+ );
1188
+ requiredString2(object, "requirementId", path);
1189
+ requiredString2(object, "verifier", path);
1190
+ requiredValue2(object, "requirements", path);
1191
+ if (hasOwn2(object, "authority")) {
1192
+ const authority = expectJsonObject(requiredValue2(object, "authority", path), `${path}.authority`);
1193
+ assertExactKeys2(
1194
+ authority,
1195
+ ["profile", "acceptedIssuers", "allowOwnerAuthorizedIssuer"],
1196
+ `${path}.authority`
1197
+ );
1198
+ optionalString(authority, "profile", `${path}.authority`);
1199
+ if (hasOwn2(authority, "acceptedIssuers")) {
1200
+ requiredStringArray(authority, "acceptedIssuers", `${path}.authority`);
1201
+ }
1202
+ optionalBoolean(authority, "allowOwnerAuthorizedIssuer", `${path}.authority`);
1203
+ }
1204
+ if (hasOwn2(object, "freshness")) {
1205
+ const freshness = expectJsonObject(requiredValue2(object, "freshness", path), `${path}.freshness`);
1206
+ assertExactKeys2(freshness, ["maxStatusAgeSeconds"], `${path}.freshness`);
1207
+ requiredInteger(freshness, "maxStatusAgeSeconds", `${path}.freshness`, 0);
1208
+ }
1209
+ }
1210
+ function validateGrant(input, path) {
1211
+ const object = expectJsonObject(input, path);
1212
+ assertExactKeys2(object, ["output", "maxTtlSeconds", "delegationMode", "revocation"], path);
1213
+ expectConst(requiredString2(object, "output", path), "portable-delegation", `${path}.output`);
1214
+ requiredInteger(object, "maxTtlSeconds", path, 1);
1215
+ expectOneOf(requiredString2(object, "delegationMode", path), [
1216
+ "terminal",
1217
+ "attenuable"
1218
+ ], `${path}.delegationMode`);
1219
+ expectOneOf(requiredString2(object, "revocation", path), [
1220
+ "refresh_only",
1221
+ "active_cutoff"
1222
+ ], `${path}.revocation`);
1223
+ }
1224
+ function validateDisclosure(input, path) {
1225
+ const object = expectJsonObject(input, path);
1226
+ assertExactKeys2(object, ["denial"], path);
1227
+ expectOneOf(requiredString2(object, "denial", path), ["none", "code", "debug"], `${path}.denial`);
1228
+ }
1229
+ function validateAudit(input, path) {
1230
+ const object = expectJsonObject(input, path);
1231
+ assertExactKeys2(object, ["issuance"], path);
1232
+ expectOneOf(requiredString2(object, "issuance", path), ["off", "security", "full"], `${path}.issuance`);
1233
+ }
1234
+ function materialForUnsigned(unsigned, descriptor) {
1235
+ const jcs = jcsCanonicalize(unsigned);
1236
+ const jcsBytes = textEncoder2.encode(jcs);
1237
+ const digest = sha256Bytes(concatBytes(textEncoder2.encode(`${descriptor.domain}\0`), jcsBytes));
1238
+ const id = `${descriptor.idPrefix}${base32LowerNoPad(digest)}`;
1239
+ return {
1240
+ kind: descriptor.kind,
1241
+ idField: descriptor.idField,
1242
+ id,
1243
+ domain: descriptor.domain,
1244
+ unsigned,
1245
+ jcs,
1246
+ jcsBytes,
1247
+ digest,
1248
+ digestHex: (0, import_viem3.bytesToHex)(digest).slice(2)
1249
+ };
1250
+ }
1251
+ function assertIdMatches(signed, material, descriptor) {
1252
+ const actual = requiredString2(signed, descriptor.idField, "$");
1253
+ if (actual === material.id) {
1254
+ return;
1255
+ }
1256
+ if (new RegExp(`^${descriptor.idPrefix}[a-z2-7]{52}$`).test(actual)) {
1257
+ throw new SignedObjectDigestError(
1258
+ `${descriptor.idField} was not derived from the signed object digest`
1259
+ );
1260
+ }
1261
+ throw new SignedObjectIdError(`${descriptor.idField} does not match ${descriptor.idPrefix}`);
1262
+ }
1263
+ function assertSigningKeyBindingForCreate(unsigned, signerDid) {
1264
+ if (!hasOwn2(unsigned, "signingKeyDid")) {
1265
+ return;
1266
+ }
1267
+ const signingKeyDid = requiredString2(unsigned, "signingKeyDid", "$");
1268
+ if (signingKeyDid !== signerDid) {
1269
+ throw new SigningKeyBindingError(
1270
+ `signer DID ${signerDid} does not match signingKeyDid ${signingKeyDid}`
1271
+ );
1272
+ }
1273
+ }
1274
+ function assertSigningKeyBindingForVerify(signed, signature) {
1275
+ if (!hasOwn2(signed, "signingKeyDid")) {
1276
+ return;
1277
+ }
1278
+ const signingKeyDid = requiredString2(signed, "signingKeyDid", "$");
1279
+ if (signature.signerDid !== signingKeyDid) {
1280
+ throw new SigningKeyBindingError(
1281
+ `signature signerDid ${signature.signerDid} does not match signingKeyDid ${signingKeyDid}`
1282
+ );
1283
+ }
1284
+ }
1285
+ function assertSignerDidMatchesSuite(signerDid, suite) {
1286
+ if (suite === ED25519_JCS_SIGNATURE_SUITE) {
1287
+ ed25519PublicKeyFromDidKey(signerDid);
1288
+ return;
1289
+ }
1290
+ if (suite === EIP191_JCS_SIGNATURE_SUITE) {
1291
+ parseDidPkh(signerDid);
1292
+ return;
1293
+ }
1294
+ throw new UnsupportedSignatureSuiteError(`unsupported signature suite: ${suite}`);
1295
+ }
1296
+ async function verifySignature(signature, digest) {
1297
+ if (signature.suite === ED25519_JCS_SIGNATURE_SUITE) {
1298
+ const publicKey = ed25519PublicKeyFromDidKey(signature.signerDid);
1299
+ const signatureBytes = decodeSignatureValue(signature.value, signature.suite);
1300
+ try {
1301
+ return import_ed25519.ed25519.verify(signatureBytes, digest, publicKey);
1302
+ } catch {
1303
+ throw new SignatureVerificationError("Ed25519 signature verification failed");
1304
+ }
1305
+ }
1306
+ if (signature.suite === EIP191_JCS_SIGNATURE_SUITE) {
1307
+ const pkh = parseDidPkh(signature.signerDid);
1308
+ const signatureBytes = decodeSignatureValue(signature.value, signature.suite);
1309
+ try {
1310
+ return (0, import_viem3.verifyMessage)({
1311
+ address: pkh.address,
1312
+ message: { raw: digest },
1313
+ signature: (0, import_viem3.bytesToHex)(signatureBytes)
1314
+ });
1315
+ } catch {
1316
+ throw new SignatureVerificationError("EIP-191 signature verification failed");
1317
+ }
1318
+ }
1319
+ throw new UnsupportedSignatureSuiteError(`unsupported signature suite: ${signature.suite}`);
1320
+ }
1321
+ function ed25519PublicKeyFromDidKey(did) {
1322
+ if (!did.startsWith("did:key:")) {
1323
+ throw new SignatureMaterialError("Ed25519 signerDid must be did:key");
1324
+ }
1325
+ const identifier = did.slice("did:key:".length);
1326
+ if (!identifier.startsWith("z")) {
1327
+ throw new SignatureMaterialError("did:key must use base58btc multibase");
1328
+ }
1329
+ let bytes;
1330
+ try {
1331
+ bytes = import_basics.bases.base58btc.decode(identifier);
1332
+ } catch {
1333
+ throw new SignatureMaterialError("did:key signerDid is undecodable");
1334
+ }
1335
+ if (bytes.length === 34 && bytes[0] === 237 && bytes[1] === 1) {
1336
+ return bytes.slice(2);
1337
+ }
1338
+ throw new SignatureMaterialError("did:key signerDid is not an Ed25519 key");
1339
+ }
1340
+ function parseDidPkh(did) {
1341
+ let parsed;
1342
+ try {
1343
+ parsed = parsePkhDid(did);
1344
+ } catch {
1345
+ throw new SignatureMaterialError("did:pkh signerDid is undecodable");
1346
+ }
1347
+ if (!parsed) {
1348
+ throw new SignatureMaterialError("EIP-191 signerDid must be did:pkh");
1349
+ }
1350
+ return { address: parsed.address };
1351
+ }
1352
+ function decodeSignatureValue(value, suite) {
1353
+ if (value.length === 0 || !BASE64URL_RE.test(value) || value.includes("=")) {
1354
+ throw new SignatureMaterialError("signature value must be base64url without padding");
1355
+ }
1356
+ const bytes = base64UrlDecode(value);
1357
+ if (suite === ED25519_JCS_SIGNATURE_SUITE && bytes.length !== 64) {
1358
+ throw new SignatureMaterialError("Ed25519 signature must be 64 bytes");
1359
+ }
1360
+ if (suite === EIP191_JCS_SIGNATURE_SUITE) {
1361
+ if (bytes.length !== 65) {
1362
+ throw new SignatureMaterialError("EIP-191 signature must be 65 bytes");
1363
+ }
1364
+ const v = bytes[64];
1365
+ if (v !== 27 && v !== 28) {
1366
+ throw new SignatureMaterialError("EIP-191 signature recovery id must be 27 or 28");
1367
+ }
1368
+ }
1369
+ return bytes;
1370
+ }
1371
+ function encodeSignatureValue(value, suite) {
1372
+ if (typeof value === "string") {
1373
+ const encoded2 = value.startsWith("0x") ? base64UrlEncode(hexToBytes(value)) : value;
1374
+ decodeSignatureValue(encoded2, suite);
1375
+ return encoded2;
1376
+ }
1377
+ const encoded = base64UrlEncode(value);
1378
+ decodeSignatureValue(encoded, suite);
1379
+ return encoded;
1380
+ }
1381
+ function stripOwnIdAndSignature(object, descriptor) {
1382
+ const output = /* @__PURE__ */ Object.create(null);
1383
+ for (const [key, value] of Object.entries(object)) {
1384
+ if (key === descriptor.idField || key === "signature") {
1385
+ continue;
1386
+ }
1387
+ output[key] = value;
1388
+ }
1389
+ return output;
1390
+ }
1391
+ function descriptorForUnsigned(input) {
1392
+ const object = expectJsonObject(normalizeJson(input), "$");
1393
+ return descriptorForSchema(requiredString2(object, "schema", "$"));
1394
+ }
1395
+ function descriptorForSchema(schema) {
1396
+ if (schema === POLICY_SCHEMA) return DESCRIPTORS.Policy;
1397
+ if (schema === POLICY_STATUS_SCHEMA) return DESCRIPTORS.PolicyStatus;
1398
+ if (schema === POLICY_ENGINE_RECORD_SCHEMA) return DESCRIPTORS.PolicyEngineRecord;
1399
+ throw new SignedObjectSchemaError(`unsupported signed-object schema: ${schema}`);
1400
+ }
1401
+ function expectJsonObject(input, path) {
1402
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
1403
+ throw new SignedObjectSchemaError(`${path} must be an object`);
1404
+ }
1405
+ return input;
1406
+ }
1407
+ function assertExactKeys2(object, allowed, path) {
1408
+ const allowedSet = new Set(allowed);
1409
+ for (const key of Object.keys(object)) {
1410
+ if (!allowedSet.has(key)) {
1411
+ throw new SignedObjectSchemaError(`${path} has unknown field ${key}`);
1412
+ }
1413
+ }
1414
+ }
1415
+ function requiredValue2(object, key, path) {
1416
+ if (!hasOwn2(object, key)) {
1417
+ throw new SignedObjectSchemaError(`${path}.${key} is required`);
1418
+ }
1419
+ return object[key];
1420
+ }
1421
+ function requiredString2(object, key, path) {
1422
+ return requireStringType(requiredValue2(object, key, path), `${path}.${key}`);
1423
+ }
1424
+ function optionalString(object, key, path) {
1425
+ if (!hasOwn2(object, key)) {
1426
+ return;
1427
+ }
1428
+ requireStringType(requiredValue2(object, key, path), `${path}.${key}`);
1429
+ }
1430
+ function requireStringType(value, path) {
1431
+ if (typeof value !== "string" || value.length === 0) {
1432
+ throw new SignedObjectSchemaError(`${path} must be a non-empty string`);
1433
+ }
1434
+ return value;
1435
+ }
1436
+ function optionalBoolean(object, key, path) {
1437
+ if (!hasOwn2(object, key)) {
1438
+ return;
1439
+ }
1440
+ if (typeof requiredValue2(object, key, path) !== "boolean") {
1441
+ throw new SignedObjectSchemaError(`${path}.${key} must be a boolean`);
1442
+ }
1443
+ }
1444
+ function requiredInteger(object, key, path, minimum) {
1445
+ const value = requiredValue2(object, key, path);
1446
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum) {
1447
+ throw new SignedObjectSchemaError(
1448
+ `${path}.${key} must be an integer >= ${minimum}`
1449
+ );
1450
+ }
1451
+ return value;
1452
+ }
1453
+ function requiredArray2(object, key, path, minimum) {
1454
+ const value = requiredValue2(object, key, path);
1455
+ if (!Array.isArray(value) || value.length < minimum) {
1456
+ throw new SignedObjectSchemaError(
1457
+ `${path}.${key} must be an array with at least ${minimum} item(s)`
1458
+ );
1459
+ }
1460
+ return value;
1461
+ }
1462
+ function requiredStringArray(object, key, path, check) {
1463
+ const values = requiredArray2(object, key, path, 0);
1464
+ for (let index = 0; index < values.length; index++) {
1465
+ const itemPath = `${path}.${key}[${index}]`;
1466
+ const value = requireStringType(values[index], itemPath);
1467
+ check?.(value, itemPath);
1468
+ }
1469
+ }
1470
+ function requiredDateString(object, key, path) {
1471
+ assertRfc3339(requiredString2(object, key, path), `${path}.${key}`);
1472
+ }
1473
+ function optionalDateString(object, key, path) {
1474
+ if (!hasOwn2(object, key)) {
1475
+ return;
1476
+ }
1477
+ assertRfc3339(requiredString2(object, key, path), `${path}.${key}`);
1478
+ }
1479
+ function assertRfc3339(value, path) {
1480
+ const match = value.match(
1481
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})$/
1482
+ );
1483
+ if (!match) {
1484
+ throw new SignedObjectSchemaError(`${path} must be strict RFC 3339`);
1485
+ }
1486
+ const parsed = Date.parse(value);
1487
+ if (Number.isNaN(parsed)) {
1488
+ throw new SignedObjectSchemaError(`${path} must be a parseable RFC 3339 timestamp`);
1489
+ }
1490
+ const canonical = new Date(parsed).toISOString().replace(".000Z", "Z");
1491
+ if (canonical !== value) {
1492
+ throw new SignedObjectSchemaError(`${path} must be a normalizable RFC 3339 timestamp`);
1493
+ }
1494
+ }
1495
+ function expectConst(actual, expected, path) {
1496
+ if (actual !== expected) {
1497
+ throw new SignedObjectSchemaError(`${path} must be ${expected}`);
1498
+ }
1499
+ return expected;
1500
+ }
1501
+ function expectOneOf(actual, allowed, path) {
1502
+ for (const value of allowed) {
1503
+ if (actual === value) {
1504
+ return value;
1505
+ }
1506
+ }
1507
+ throw new SignedObjectSchemaError(`${path} has unsupported value ${actual}`);
1508
+ }
1509
+ function hasOwn2(object, key) {
1510
+ return objectHasOwn3(object, key);
1511
+ }
1512
+ function assertSupportedSignatureSuite(suite) {
1513
+ if (suite !== ED25519_JCS_SIGNATURE_SUITE && suite !== EIP191_JCS_SIGNATURE_SUITE) {
1514
+ throw new UnsupportedSignatureSuiteError(`unsupported signature suite: ${suite}`);
1515
+ }
1516
+ }
1517
+ function sha256Bytes(bytes) {
1518
+ return (0, import_viem3.sha256)(bytes, "bytes");
1519
+ }
1520
+ function concatBytes(left, right) {
1521
+ const output = new Uint8Array(left.length + right.length);
1522
+ output.set(left, 0);
1523
+ output.set(right, left.length);
1524
+ return output;
1525
+ }
1526
+ function base32LowerNoPad(bytes) {
1527
+ let output = "";
1528
+ let buffer = 0;
1529
+ let bits = 0;
1530
+ for (const byte of bytes) {
1531
+ buffer = buffer << 8 | byte;
1532
+ bits += 8;
1533
+ while (bits >= 5) {
1534
+ bits -= 5;
1535
+ output += BASE32_ALPHABET[buffer >> bits & 31];
1536
+ }
1537
+ }
1538
+ if (bits > 0) {
1539
+ output += BASE32_ALPHABET[buffer << 5 - bits & 31];
1540
+ }
1541
+ return output;
1542
+ }
1543
+ function base64UrlEncode(bytes) {
1544
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1545
+ let output = "";
1546
+ for (let index = 0; index < bytes.length; index += 3) {
1547
+ const a = bytes[index];
1548
+ const b = bytes[index + 1];
1549
+ const c = bytes[index + 2];
1550
+ const triplet = a << 16 | (b ?? 0) << 8 | (c ?? 0);
1551
+ output += alphabet[triplet >> 18 & 63];
1552
+ output += alphabet[triplet >> 12 & 63];
1553
+ if (index + 1 < bytes.length) {
1554
+ output += alphabet[triplet >> 6 & 63];
1555
+ }
1556
+ if (index + 2 < bytes.length) {
1557
+ output += alphabet[triplet & 63];
1558
+ }
1559
+ }
1560
+ return output;
1561
+ }
1562
+ function base64UrlDecode(value) {
1563
+ if (value.length % 4 === 1) {
1564
+ throw new SignatureMaterialError("signature value is not canonical base64url");
1565
+ }
1566
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1567
+ const bytes = [];
1568
+ let buffer = 0;
1569
+ let bits = 0;
1570
+ for (const char of value) {
1571
+ const index = alphabet.indexOf(char);
1572
+ if (index < 0) {
1573
+ throw new SignatureMaterialError("signature value is not base64url");
1574
+ }
1575
+ buffer = buffer << 6 | index;
1576
+ bits += 6;
1577
+ if (bits >= 8) {
1578
+ bits -= 8;
1579
+ bytes.push(buffer >> bits & 255);
1580
+ }
1581
+ }
1582
+ const decoded = Uint8Array.from(bytes);
1583
+ if (base64UrlEncode(decoded) !== value) {
1584
+ throw new SignatureMaterialError("signature value is not canonical base64url");
1585
+ }
1586
+ return decoded;
1587
+ }
1588
+ function hexToBytes(value) {
1589
+ const hex = value.slice(2);
1590
+ if (hex.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(hex)) {
1591
+ throw new SignatureMaterialError("hex signature must have even length");
1592
+ }
1593
+ const output = new Uint8Array(hex.length / 2);
1594
+ for (let index = 0; index < output.length; index++) {
1595
+ output[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);
1596
+ }
1597
+ return output;
1598
+ }
1599
+
1600
+ // src/policy/authoring.ts
1601
+ var TRANSCRIPT_SHARE_BOOTSTRAP_SCHEMA = "xyz.tinycloud.exchange/transcript-bootstrap/v0";
1602
+ var OWNER_NODE_ENDPOINT_SCHEMA = "xyz.tinycloud.exchange/owner-node-endpoint/v1";
1603
+ var POLICY_VERSION_V0 = "v0";
1604
+ var W3C_VC_CREDENTIAL_VERIFIER = "w3c.vc/credential/v1";
1605
+ var PolicyAuthoringError = class extends Error {
1606
+ constructor(code, message) {
1607
+ super(message);
1608
+ this.name = "PolicyAuthoringError";
1609
+ this.code = code;
1610
+ }
1611
+ };
1612
+ async function createAndSignTranscriptSharePolicy(input, signer) {
1613
+ const normalized = expectObject2(input, "$", "policy-authoring-malformed");
1614
+ assertExactKeys3(
1615
+ normalized,
1616
+ [
1617
+ "ownerDid",
1618
+ "signingKeyDid",
1619
+ "createdAt",
1620
+ "expiresAt",
1621
+ "resourceType",
1622
+ "resourceId",
1623
+ "permissionsCeiling",
1624
+ "when",
1625
+ "grant",
1626
+ "disclosure",
1627
+ "audit"
1628
+ ],
1629
+ "$"
1630
+ );
1631
+ const permissions = requiredArray3(normalized, "permissionsCeiling", "$");
1632
+ if (permissions.length === 0) {
1633
+ throw new PolicyAuthoringError(
1634
+ "policy-authoring-malformed",
1635
+ "$.permissionsCeiling must not be empty"
1636
+ );
1637
+ }
1638
+ const ceiling = [];
1639
+ for (let index = 0; index < permissions.length; index++) {
1640
+ ceiling.push(
1641
+ wrapCapabilityError(() => normalizePolicyCapability(permissions[index]))
1642
+ );
1643
+ }
1644
+ return createAndSignPolicy(
1645
+ {
1646
+ schema: POLICY_SCHEMA,
1647
+ ownerDid: requiredString3(normalized, "ownerDid", "$"),
1648
+ signingKeyDid: requiredString3(normalized, "signingKeyDid", "$"),
1649
+ createdAt: requiredString3(normalized, "createdAt", "$"),
1650
+ ...hasOwn3(normalized, "expiresAt") ? { expiresAt: requiredString3(normalized, "expiresAt", "$") } : {},
1651
+ resource: {
1652
+ resourceType: requiredString3(normalized, "resourceType", "$"),
1653
+ resourceId: requiredString3(normalized, "resourceId", "$"),
1654
+ permissionsCeiling: ceiling
1655
+ },
1656
+ when: requiredObject(normalized, "when", "$"),
1657
+ grant: requiredObject(normalized, "grant", "$"),
1658
+ ...hasOwn3(normalized, "disclosure") ? { disclosure: requiredObject(normalized, "disclosure", "$") } : {},
1659
+ ...hasOwn3(normalized, "audit") ? { audit: requiredObject(normalized, "audit", "$") } : {}
1660
+ },
1661
+ signer
1662
+ ).catch((error) => {
1663
+ throw wrapSignedObjectError(error);
1664
+ });
1665
+ }
1666
+ function createUnsignedPolicyEngineRecord(input) {
1667
+ const normalized = expectObject2(input, "$", "policy-authoring-malformed");
1668
+ assertExactKeys3(
1669
+ normalized,
1670
+ [
1671
+ "ownerDid",
1672
+ "endpoint",
1673
+ "audience",
1674
+ "grantIssuerDid",
1675
+ "expiresAt",
1676
+ "supportedPolicyVersions",
1677
+ "supportedEvidenceVerifiers"
1678
+ ],
1679
+ "$"
1680
+ );
1681
+ const supportedPolicyVersions = hasOwn3(normalized, "supportedPolicyVersions") ? requiredStringArray2(normalized, "supportedPolicyVersions", "$") : [POLICY_VERSION_V0];
1682
+ validateSupportedPolicyVersions(
1683
+ supportedPolicyVersions,
1684
+ "$.supportedPolicyVersions"
1685
+ );
1686
+ const supportedEvidenceVerifiers = hasOwn3(
1687
+ normalized,
1688
+ "supportedEvidenceVerifiers"
1689
+ ) ? requiredStringArray2(normalized, "supportedEvidenceVerifiers", "$") : [W3C_VC_CREDENTIAL_VERIFIER];
1690
+ validateSupportedEvidenceVerifiers(
1691
+ supportedEvidenceVerifiers,
1692
+ "$.supportedEvidenceVerifiers"
1693
+ );
1694
+ const expiresAt = fieldString(
1695
+ normalized,
1696
+ "expiresAt",
1697
+ "$",
1698
+ "policy-engine-record-date-invalid"
1699
+ );
1700
+ parseStrictRfc3339(expiresAt, "$.expiresAt");
1701
+ return {
1702
+ schema: POLICY_ENGINE_RECORD_SCHEMA,
1703
+ ownerDid: requiredString3(normalized, "ownerDid", "$"),
1704
+ endpoint: validatePolicyEngineEndpoint(
1705
+ requiredString3(normalized, "endpoint", "$")
1706
+ ),
1707
+ audience: requiredString3(normalized, "audience", "$"),
1708
+ supportedPolicyVersions,
1709
+ supportedEvidenceVerifiers,
1710
+ grantIssuerDid: requiredString3(normalized, "grantIssuerDid", "$"),
1711
+ expiresAt
1712
+ };
1713
+ }
1714
+ async function createAndSignRequesterPolicyEngineRecord(input, signer) {
1715
+ return createAndSignPolicyEngineRecord(
1716
+ createUnsignedPolicyEngineRecord(input),
1717
+ signer
1718
+ ).catch((error) => {
1719
+ throw wrapSignedObjectError(error);
1720
+ });
1721
+ }
1722
+ function composeTranscriptShareBootstrap(input) {
1723
+ const normalized = expectObject2(
1724
+ input,
1725
+ "$",
1726
+ "transcript-share-bootstrap-malformed"
1727
+ );
1728
+ assertExactKeys3(
1729
+ normalized,
1730
+ [
1731
+ "policyId",
1732
+ "policyEngineRecord",
1733
+ "ownerNodeEndpoint",
1734
+ "ownerSpaceId",
1735
+ "resourceHint"
1736
+ ],
1737
+ "$"
1738
+ );
1739
+ const signedRecord = expectPolicyEngineRecord(
1740
+ requiredValue3(normalized, "policyEngineRecord", "$")
1741
+ );
1742
+ if (!signedRecord.supportedEvidenceVerifiers.includes(
1743
+ W3C_VC_CREDENTIAL_VERIFIER
1744
+ )) {
1745
+ throw new PolicyAuthoringError(
1746
+ "transcript-share-bootstrap-malformed",
1747
+ "policy engine record does not support the bootstrap evidence verifier"
1748
+ );
1749
+ }
1750
+ return {
1751
+ schema: TRANSCRIPT_SHARE_BOOTSTRAP_SCHEMA,
1752
+ policyId: requiredString3(normalized, "policyId", "$"),
1753
+ policyEngine: {
1754
+ endpoint: signedRecord.endpoint,
1755
+ audience: signedRecord.audience,
1756
+ supportedEvidenceVerifiers: [W3C_VC_CREDENTIAL_VERIFIER],
1757
+ signedRecord
1758
+ },
1759
+ ownerNode: {
1760
+ schema: OWNER_NODE_ENDPOINT_SCHEMA,
1761
+ endpoint: validateOwnerNodeEndpoint(
1762
+ requiredString3(normalized, "ownerNodeEndpoint", "$")
1763
+ ),
1764
+ spaceId: requiredString3(normalized, "ownerSpaceId", "$")
1765
+ },
1766
+ resourceHint: requiredObject(normalized, "resourceHint", "$")
1767
+ };
1768
+ }
1769
+ function validateOwnerNodeEndpoint(value) {
1770
+ let url;
1771
+ try {
1772
+ url = new URL(value);
1773
+ } catch {
1774
+ throw new PolicyAuthoringError(
1775
+ "transcript-share-bootstrap-malformed",
1776
+ "$.ownerNodeEndpoint must be a URL"
1777
+ );
1778
+ }
1779
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.hash !== "" || url.search !== "") {
1780
+ throw new PolicyAuthoringError(
1781
+ "transcript-share-bootstrap-malformed",
1782
+ "$.ownerNodeEndpoint must be an HTTPS URL without credentials, query, or fragment"
1783
+ );
1784
+ }
1785
+ return url.toString().replace(/\/$/, "");
1786
+ }
1787
+ function validatePolicyEngineEndpoint(value) {
1788
+ let url;
1789
+ try {
1790
+ url = new URL(value);
1791
+ } catch {
1792
+ throw new PolicyAuthoringError(
1793
+ "policy-authoring-malformed",
1794
+ "$.endpoint must be a URL"
1795
+ );
1796
+ }
1797
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.hash !== "" || url.search !== "") {
1798
+ throw new PolicyAuthoringError(
1799
+ "policy-authoring-malformed",
1800
+ "$.endpoint must be an HTTPS URL without credentials, query, or fragment"
1801
+ );
1802
+ }
1803
+ return url.toString().replace(/\/$/, "");
1804
+ }
1805
+ async function verifyPolicyEngineRecordForRequester(options) {
1806
+ const normalized = expectObject2(options, "$", "policy-authoring-malformed");
1807
+ assertExactKeys3(
1808
+ normalized,
1809
+ [
1810
+ "signedRecord",
1811
+ "ownerDid",
1812
+ "audience",
1813
+ "grantIssuerDid",
1814
+ "now",
1815
+ "requiredPolicyVersion",
1816
+ "requiredEvidenceVerifier"
1817
+ ],
1818
+ "$"
1819
+ );
1820
+ if (!hasOwn3(normalized, "signedRecord")) {
1821
+ throw new PolicyAuthoringError(
1822
+ "policy-engine-record-absent",
1823
+ "$.signedRecord must be present"
1824
+ );
1825
+ }
1826
+ const signedRecord = normalized["signedRecord"];
1827
+ if (signedRecord === null || typeof signedRecord !== "object" || Array.isArray(signedRecord)) {
1828
+ throw new PolicyAuthoringError(
1829
+ "policy-engine-record-absent",
1830
+ "$.signedRecord must be present"
1831
+ );
1832
+ }
1833
+ const recordObject = signedRecord;
1834
+ const expiresAt = fieldString(
1835
+ recordObject,
1836
+ "expiresAt",
1837
+ "$.signedRecord",
1838
+ "policy-engine-record-date-invalid"
1839
+ );
1840
+ const now = fieldString(
1841
+ normalized,
1842
+ "now",
1843
+ "$",
1844
+ "policy-engine-record-date-invalid"
1845
+ );
1846
+ const expiresMs = parseStrictRfc3339(expiresAt, "$.signedRecord.expiresAt");
1847
+ const nowMs = parseStrictRfc3339(now, "$.now");
1848
+ if (expiresMs <= nowMs) {
1849
+ throw new PolicyAuthoringError(
1850
+ "policy-engine-record-expired",
1851
+ "$.signedRecord.expiresAt is expired"
1852
+ );
1853
+ }
1854
+ let verified;
1855
+ try {
1856
+ verified = (await verifyPolicyEngineRecord(recordObject)).object;
1857
+ } catch (error) {
1858
+ throw new PolicyAuthoringError(
1859
+ "policy-engine-record-signature-invalid",
1860
+ error instanceof Error ? error.message : String(error)
1861
+ );
1862
+ }
1863
+ if (verified.signature.signerDid !== verified.ownerDid) {
1864
+ throw new PolicyAuthoringError(
1865
+ "policy-engine-record-signature-invalid",
1866
+ "$.signedRecord.signature.signerDid must match ownerDid for the direct-owner requester profile"
1867
+ );
1868
+ }
1869
+ const expectedOwnerDid = requiredString3(normalized, "ownerDid", "$");
1870
+ if (verified.ownerDid !== expectedOwnerDid) {
1871
+ throw new PolicyAuthoringError(
1872
+ "policy-engine-record-owner-mismatch",
1873
+ "$.signedRecord.ownerDid does not match"
1874
+ );
1875
+ }
1876
+ const expectedAudience = requiredString3(normalized, "audience", "$");
1877
+ if (verified.audience !== expectedAudience) {
1878
+ throw new PolicyAuthoringError(
1879
+ "policy-engine-record-audience-mismatch",
1880
+ "$.signedRecord.audience does not match"
1881
+ );
1882
+ }
1883
+ const expectedGrantIssuerDid = requiredString3(
1884
+ normalized,
1885
+ "grantIssuerDid",
1886
+ "$"
1887
+ );
1888
+ if (verified.grantIssuerDid !== expectedGrantIssuerDid) {
1889
+ throw new PolicyAuthoringError(
1890
+ "policy-engine-record-grant-issuer-mismatch",
1891
+ "$.signedRecord.grantIssuerDid does not match"
1892
+ );
1893
+ }
1894
+ const requiredPolicyVersion = hasOwn3(normalized, "requiredPolicyVersion") ? requiredString3(normalized, "requiredPolicyVersion", "$") : POLICY_VERSION_V0;
1895
+ if (!verified.supportedPolicyVersions.includes(requiredPolicyVersion)) {
1896
+ throw new PolicyAuthoringError(
1897
+ "policy-engine-record-policy-version-unsupported",
1898
+ "$.signedRecord.supportedPolicyVersions does not include the required version"
1899
+ );
1900
+ }
1901
+ const requiredEvidenceVerifier = hasOwn3(
1902
+ normalized,
1903
+ "requiredEvidenceVerifier"
1904
+ ) ? requiredString3(normalized, "requiredEvidenceVerifier", "$") : W3C_VC_CREDENTIAL_VERIFIER;
1905
+ if (!verified.supportedEvidenceVerifiers.includes(requiredEvidenceVerifier)) {
1906
+ throw new PolicyAuthoringError(
1907
+ "policy-engine-record-evidence-verifier-unsupported",
1908
+ "$.signedRecord.supportedEvidenceVerifiers does not include the required verifier"
1909
+ );
1910
+ }
1911
+ return verified;
1912
+ }
1913
+ function expectObject2(input, path, code) {
1914
+ try {
1915
+ const normalized = normalizeJson(input);
1916
+ if (normalized === null || typeof normalized !== "object" || Array.isArray(normalized)) {
1917
+ throw new PolicyAuthoringError(code, `${path} must be an object`);
1918
+ }
1919
+ return normalized;
1920
+ } catch (error) {
1921
+ if (error instanceof PolicyAuthoringError) {
1922
+ throw error;
1923
+ }
1924
+ throw new PolicyAuthoringError(
1925
+ code,
1926
+ error instanceof Error ? error.message : String(error)
1927
+ );
1928
+ }
1929
+ }
1930
+ function expectPolicyEngineRecord(input) {
1931
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
1932
+ throw new PolicyAuthoringError(
1933
+ "transcript-share-bootstrap-malformed",
1934
+ "$.policyEngineRecord must be an object"
1935
+ );
1936
+ }
1937
+ try {
1938
+ return validatePolicyEngineRecordSignedShape(input);
1939
+ } catch (error) {
1940
+ throw new PolicyAuthoringError(
1941
+ "transcript-share-bootstrap-malformed",
1942
+ error instanceof Error ? error.message : String(error)
1943
+ );
1944
+ }
1945
+ }
1946
+ function assertExactKeys3(object, allowed, path) {
1947
+ const allowedSet = new Set(allowed);
1948
+ for (const key of Object.keys(object)) {
1949
+ if (!allowedSet.has(key)) {
1950
+ throw new PolicyAuthoringError(
1951
+ "policy-authoring-unknown-key",
1952
+ `${path} has unknown field ${key}`
1953
+ );
1954
+ }
1955
+ }
1956
+ }
1957
+ function requiredValue3(object, key, path) {
1958
+ if (!hasOwn3(object, key)) {
1959
+ throw new PolicyAuthoringError(
1960
+ "policy-authoring-malformed",
1961
+ `${path}.${key} is required`
1962
+ );
1963
+ }
1964
+ return object[key];
1965
+ }
1966
+ function requiredString3(object, key, path) {
1967
+ const value = requiredValue3(object, key, path);
1968
+ if (typeof value !== "string" || value.length === 0) {
1969
+ throw new PolicyAuthoringError(
1970
+ "policy-authoring-malformed",
1971
+ `${path}.${key} must be a non-empty string`
1972
+ );
1973
+ }
1974
+ return value;
1975
+ }
1976
+ function fieldString(object, key, path, code) {
1977
+ if (!hasOwn3(object, key)) {
1978
+ throw new PolicyAuthoringError(code, `${path}.${key} is required`);
1979
+ }
1980
+ const value = object[key];
1981
+ if (typeof value !== "string" || value.length === 0) {
1982
+ throw new PolicyAuthoringError(
1983
+ code,
1984
+ `${path}.${key} must be a non-empty string`
1985
+ );
1986
+ }
1987
+ return value;
1988
+ }
1989
+ function requiredObject(object, key, path) {
1990
+ const value = requiredValue3(object, key, path);
1991
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
1992
+ throw new PolicyAuthoringError(
1993
+ "policy-authoring-malformed",
1994
+ `${path}.${key} must be an object`
1995
+ );
1996
+ }
1997
+ return value;
1998
+ }
1999
+ function requiredArray3(object, key, path) {
2000
+ const value = requiredValue3(object, key, path);
2001
+ if (!Array.isArray(value)) {
2002
+ throw new PolicyAuthoringError(
2003
+ "policy-authoring-malformed",
2004
+ `${path}.${key} must be an array`
2005
+ );
2006
+ }
2007
+ return value;
2008
+ }
2009
+ function requiredStringArray2(object, key, path) {
2010
+ const values = requiredArray3(object, key, path);
2011
+ return values.map((value, index) => {
2012
+ if (typeof value !== "string" || value.length === 0) {
2013
+ throw new PolicyAuthoringError(
2014
+ "policy-authoring-malformed",
2015
+ `${path}.${key}[${index}] must be a non-empty string`
2016
+ );
2017
+ }
2018
+ return value;
2019
+ });
2020
+ }
2021
+ function validateSupportedPolicyVersions(values, path) {
2022
+ if (values.length === 0) {
2023
+ throw new PolicyAuthoringError(
2024
+ "policy-authoring-malformed",
2025
+ `${path} must not be empty`
2026
+ );
2027
+ }
2028
+ for (let index = 0; index < values.length; index++) {
2029
+ if (values[index] !== POLICY_VERSION_V0) {
2030
+ throw new PolicyAuthoringError(
2031
+ "policy-authoring-malformed",
2032
+ `${path}[${index}] is unsupported`
2033
+ );
2034
+ }
2035
+ }
2036
+ }
2037
+ function validateSupportedEvidenceVerifiers(values, path) {
2038
+ if (values.length === 0) {
2039
+ throw new PolicyAuthoringError(
2040
+ "policy-authoring-malformed",
2041
+ `${path} must not be empty`
2042
+ );
2043
+ }
2044
+ for (let index = 0; index < values.length; index++) {
2045
+ if (values[index] !== W3C_VC_CREDENTIAL_VERIFIER) {
2046
+ throw new PolicyAuthoringError(
2047
+ "policy-authoring-malformed",
2048
+ `${path}[${index}] is unsupported`
2049
+ );
2050
+ }
2051
+ }
2052
+ }
2053
+ function wrapCapabilityError(fn) {
2054
+ try {
2055
+ return fn();
2056
+ } catch (error) {
2057
+ if (error instanceof PolicyCapabilityError) {
2058
+ throw new PolicyAuthoringError(error.code, error.message);
2059
+ }
2060
+ throw error;
2061
+ }
2062
+ }
2063
+ function wrapSignedObjectError(error) {
2064
+ if (error instanceof PolicyAuthoringError) {
2065
+ return error;
2066
+ }
2067
+ if (error instanceof SignedObjectSchemaError || error instanceof SignedObjectProfileError) {
2068
+ return new PolicyAuthoringError(
2069
+ "policy-authoring-malformed",
2070
+ error.message
2071
+ );
2072
+ }
2073
+ return new PolicyAuthoringError(
2074
+ "policy-authoring-malformed",
2075
+ error instanceof Error ? error.message : String(error)
2076
+ );
2077
+ }
2078
+ function parseStrictRfc3339(value, path) {
2079
+ const match = value.match(
2080
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?Z$/
2081
+ );
2082
+ if (!match) {
2083
+ throw new PolicyAuthoringError(
2084
+ "policy-engine-record-date-invalid",
2085
+ `${path} must be strict RFC 3339`
2086
+ );
2087
+ }
2088
+ const parsed = Date.parse(value);
2089
+ if (Number.isNaN(parsed)) {
2090
+ throw new PolicyAuthoringError(
2091
+ "policy-engine-record-date-invalid",
2092
+ `${path} must be parseable`
2093
+ );
2094
+ }
2095
+ const canonical = new Date(parsed).toISOString().replace(".000Z", "Z");
2096
+ if (canonical !== value) {
2097
+ throw new PolicyAuthoringError(
2098
+ "policy-engine-record-date-invalid",
2099
+ `${path} must be normalizable`
2100
+ );
2101
+ }
2102
+ return parsed;
2103
+ }
2104
+ var objectHasOwn4 = Object.hasOwn ?? Object.prototype.hasOwnProperty.call.bind(
2105
+ Object.prototype.hasOwnProperty
2106
+ );
2107
+ function hasOwn3(object, key) {
2108
+ return objectHasOwn4(object, key);
2109
+ }
2110
+ // Annotate the CommonJS export names for ESM import in node:
2111
+ 0 && (module.exports = {
2112
+ ED25519_JCS_SIGNATURE_SUITE,
2113
+ EIP191_JCS_SIGNATURE_SUITE,
2114
+ OWNER_NODE_ENDPOINT_SCHEMA,
2115
+ POLICY_ENGINE_RECORD_SCHEMA,
2116
+ POLICY_SCHEMA,
2117
+ POLICY_STATUS_SCHEMA,
2118
+ POLICY_VERSION_V0,
2119
+ PolicyAuthoringError,
2120
+ PolicyCapabilityError,
2121
+ SignatureMaterialError,
2122
+ SignatureVerificationError,
2123
+ SignedObjectCanonicalizationError,
2124
+ SignedObjectDigestError,
2125
+ SignedObjectIdError,
2126
+ SignedObjectProfileError,
2127
+ SignedObjectSchemaError,
2128
+ SigningKeyBindingError,
2129
+ TRANSCRIPT_SHARE_BOOTSTRAP_SCHEMA,
2130
+ UnsupportedSignatureSuiteError,
2131
+ W3C_VC_CREDENTIAL_VERIFIER,
2132
+ canonicalizePolicyCapability,
2133
+ canonicalizeSignedObjectUnsigned,
2134
+ composeTranscriptShareBootstrap,
2135
+ createAndSignPolicy,
2136
+ createAndSignPolicyEngineRecord,
2137
+ createAndSignPolicyStatus,
2138
+ createAndSignRequesterPolicyEngineRecord,
2139
+ createAndSignSignedObject,
2140
+ createAndSignTranscriptSharePolicy,
2141
+ createUnsignedPolicyEngineRecord,
2142
+ deriveSignedObjectMaterial,
2143
+ jcsCanonicalize,
2144
+ normalizeJson,
2145
+ normalizePolicyCapability,
2146
+ policyCapabilityContains,
2147
+ policyCapabilityDigestHex,
2148
+ serializeJcsJson,
2149
+ signedObjectIdFor,
2150
+ toSignedObjectError,
2151
+ validatePolicyEngineRecordSigned,
2152
+ validatePolicyEngineRecordSignedShape,
2153
+ validatePolicyEngineRecordUnsigned,
2154
+ validatePolicySigned,
2155
+ validatePolicySignedShape,
2156
+ validatePolicyStatusSigned,
2157
+ validatePolicyStatusSignedShape,
2158
+ validatePolicyStatusUnsigned,
2159
+ validatePolicyUnsigned,
2160
+ verifyPolicy,
2161
+ verifyPolicyEngineRecord,
2162
+ verifyPolicyEngineRecordForRequester,
2163
+ verifyPolicyStatus,
2164
+ verifySignedObject
2165
+ });
2166
+ //# sourceMappingURL=index.cjs.map