@oma3/omatrust 0.1.0-alpha.11 → 0.1.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +3 -0
  2. package/dist/app-registry/index.cjs +53 -0
  3. package/dist/app-registry/index.cjs.map +1 -1
  4. package/dist/app-registry/index.js +53 -0
  5. package/dist/app-registry/index.js.map +1 -1
  6. package/dist/identity/index.cjs +643 -164
  7. package/dist/identity/index.cjs.map +1 -1
  8. package/dist/identity/index.d.cts +2 -2
  9. package/dist/identity/index.d.ts +2 -2
  10. package/dist/identity/index.js +616 -165
  11. package/dist/identity/index.js.map +1 -1
  12. package/dist/{index-QueRiudB.d.cts → index-B5OC9_8B.d.cts} +155 -4
  13. package/dist/index-Bu-xxcv9.d.ts +407 -0
  14. package/dist/{index-C2w5EvFH.d.ts → index-C6WNgPRx.d.ts} +155 -4
  15. package/dist/index-C7odEbp6.d.cts +407 -0
  16. package/dist/index.cjs +1000 -185
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +3 -3
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +981 -185
  21. package/dist/index.js.map +1 -1
  22. package/dist/reputation/index.browser.cjs +153 -148
  23. package/dist/reputation/index.browser.cjs.map +1 -1
  24. package/dist/reputation/index.browser.js +153 -148
  25. package/dist/reputation/index.browser.js.map +1 -1
  26. package/dist/reputation/index.cjs +477 -140
  27. package/dist/reputation/index.cjs.map +1 -1
  28. package/dist/reputation/index.d.cts +2 -2
  29. package/dist/reputation/index.d.ts +2 -2
  30. package/dist/reputation/index.js +475 -141
  31. package/dist/reputation/index.js.map +1 -1
  32. package/dist/{types-dpYxRq8N.d.cts → types-Dn0OwaNj.d.cts} +37 -11
  33. package/dist/{types-dpYxRq8N.d.ts → types-Dn0OwaNj.d.ts} +37 -11
  34. package/dist/widgets/index.cjs.map +1 -1
  35. package/dist/widgets/index.d.cts +3 -0
  36. package/dist/widgets/index.d.ts +3 -0
  37. package/dist/widgets/index.js.map +1 -1
  38. package/package.json +4 -2
  39. package/dist/index-BOvk-7Ku.d.cts +0 -235
  40. package/dist/index-R78TpAhN.d.ts +0 -235
@@ -1,6 +1,11 @@
1
1
  import { keccak256, toUtf8Bytes, isAddress, getAddress, sha256 } from 'ethers';
2
2
  import { base64url, calculateJwkThumbprint } from 'jose';
3
3
  import canonicalize from 'canonicalize';
4
+ import { CID } from 'multiformats/cid';
5
+ import { sha256 as sha256$1 } from 'multiformats/hashes/sha2';
6
+ import * as raw from 'multiformats/codecs/raw';
7
+ import { base32 } from 'multiformats/bases/base32';
8
+ import { base58btc } from 'multiformats/bases/base58';
4
9
 
5
10
  // src/identity/did.ts
6
11
 
@@ -8,23 +13,23 @@ import canonicalize from 'canonicalize';
8
13
  var OmaTrustError = class extends Error {
9
14
  code;
10
15
  details;
11
- constructor(code, message, details) {
16
+ constructor(code2, message, details) {
12
17
  super(message);
13
18
  this.name = "OmaTrustError";
14
- this.code = code;
19
+ this.code = code2;
15
20
  this.details = details;
16
21
  }
17
22
  };
18
23
 
19
24
  // src/shared/assert.ts
20
- function assertString(value, name, code = "INVALID_INPUT") {
25
+ function assertString(value, name, code2 = "INVALID_INPUT") {
21
26
  if (typeof value !== "string" || value.trim().length === 0) {
22
- throw new OmaTrustError(code, `${name} must be a non-empty string`, { value });
27
+ throw new OmaTrustError(code2, `${name} must be a non-empty string`, { value });
23
28
  }
24
29
  }
25
- function assertObject(value, name, code = "INVALID_INPUT") {
30
+ function assertObject(value, name, code2 = "INVALID_INPUT") {
26
31
  if (!value || typeof value !== "object" || Array.isArray(value)) {
27
- throw new OmaTrustError(code, `${name} must be an object`, { value });
32
+ throw new OmaTrustError(code2, `${name} must be an object`, { value });
28
33
  }
29
34
  }
30
35
 
@@ -81,6 +86,158 @@ function parseCaip2(caip2) {
81
86
  }
82
87
  return { namespace, reference };
83
88
  }
89
+ var VALID_KTY = /* @__PURE__ */ new Set(["EC", "OKP", "RSA"]);
90
+ var PRIVATE_KEY_FIELDS = /* @__PURE__ */ new Set(["d", "p", "q", "dp", "dq", "qi", "oth"]);
91
+ var REQUIRED_PUBLIC_FIELDS = {
92
+ EC: ["crv", "x", "y"],
93
+ OKP: ["crv", "x"],
94
+ RSA: ["n", "e"]
95
+ };
96
+ function validatePublicJwk(jwk) {
97
+ if (!jwk || typeof jwk !== "object" || Array.isArray(jwk)) {
98
+ return { valid: false, error: "JWK must be a non-null object" };
99
+ }
100
+ const obj = jwk;
101
+ const kty = obj.kty;
102
+ if (typeof kty !== "string" || !VALID_KTY.has(kty)) {
103
+ return {
104
+ valid: false,
105
+ error: `Invalid or missing kty (must be one of: ${[...VALID_KTY].join(", ")})`
106
+ };
107
+ }
108
+ for (const field of PRIVATE_KEY_FIELDS) {
109
+ if (field in obj) {
110
+ return {
111
+ valid: false,
112
+ error: `JWK contains private key field "${field}" \u2014 only public keys are allowed`
113
+ };
114
+ }
115
+ }
116
+ const required = REQUIRED_PUBLIC_FIELDS[kty];
117
+ if (required) {
118
+ for (const field of required) {
119
+ if (!(field in obj) || obj[field] === void 0 || obj[field] === null || obj[field] === "") {
120
+ return {
121
+ valid: false,
122
+ error: `Missing required public key field "${field}" for kty="${kty}"`
123
+ };
124
+ }
125
+ }
126
+ }
127
+ return { valid: true };
128
+ }
129
+ function canonicalizeJwkJson(jwk) {
130
+ const sorted = Object.keys(jwk).sort();
131
+ const obj = {};
132
+ for (const key of sorted) {
133
+ obj[key] = jwk[key];
134
+ }
135
+ return JSON.stringify(obj);
136
+ }
137
+ function jwkToDidJwk(jwk) {
138
+ assertObject(jwk, "jwk", "INVALID_JWK");
139
+ const validation = validatePublicJwk(jwk);
140
+ if (!validation.valid) {
141
+ throw new OmaTrustError("INVALID_JWK", validation.error ?? "Invalid public JWK", { jwk });
142
+ }
143
+ const canonical = canonicalizeJwkJson(jwk);
144
+ const encoded = base64url.encode(new TextEncoder().encode(canonical));
145
+ return `did:jwk:${encoded}`;
146
+ }
147
+ function didJwkToJwk(didJwk) {
148
+ if (typeof didJwk !== "string" || !didJwk.startsWith("did:jwk:")) {
149
+ throw new OmaTrustError("INVALID_DID", "Expected a did:jwk DID", { input: didJwk });
150
+ }
151
+ const parts = didJwk.split(":");
152
+ if (parts.length !== 3) {
153
+ throw new OmaTrustError("INVALID_DID", "did:jwk must have exactly 3 colon-separated parts", {
154
+ input: didJwk
155
+ });
156
+ }
157
+ const encoded = parts[2];
158
+ if (!encoded || encoded.length === 0) {
159
+ throw new OmaTrustError("INVALID_DID", "Missing base64url-encoded JWK identifier", {
160
+ input: didJwk
161
+ });
162
+ }
163
+ let decoded;
164
+ try {
165
+ const bytes = base64url.decode(encoded);
166
+ decoded = new TextDecoder().decode(bytes);
167
+ } catch {
168
+ throw new OmaTrustError("INVALID_DID", "Failed to base64url-decode did:jwk identifier", {
169
+ input: didJwk
170
+ });
171
+ }
172
+ let jwk;
173
+ try {
174
+ jwk = JSON.parse(decoded);
175
+ } catch {
176
+ throw new OmaTrustError("INVALID_DID", "Decoded did:jwk identifier is not valid JSON", {
177
+ input: didJwk
178
+ });
179
+ }
180
+ if (!jwk || typeof jwk !== "object" || Array.isArray(jwk)) {
181
+ throw new OmaTrustError("INVALID_DID", "Decoded did:jwk must be a JSON object", {
182
+ input: didJwk
183
+ });
184
+ }
185
+ const validation = validatePublicJwk(jwk);
186
+ if (!validation.valid) {
187
+ throw new OmaTrustError("INVALID_DID", validation.error ?? "Invalid public JWK in did:jwk", {
188
+ input: didJwk
189
+ });
190
+ }
191
+ return jwk;
192
+ }
193
+ function extractPublicKeyFields(jwk) {
194
+ const result = {};
195
+ const metadataFields = /* @__PURE__ */ new Set(["kid", "use", "key_ops", "alg", "ext"]);
196
+ for (const [key, value] of Object.entries(jwk)) {
197
+ if (PRIVATE_KEY_FIELDS.has(key)) continue;
198
+ if (metadataFields.has(key)) continue;
199
+ result[key] = value;
200
+ }
201
+ return result;
202
+ }
203
+ function publicJwkEquals(a, b) {
204
+ assertObject(a, "a", "INVALID_JWK");
205
+ assertObject(b, "b", "INVALID_JWK");
206
+ const aObj = a;
207
+ const bObj = b;
208
+ for (const field of PRIVATE_KEY_FIELDS) {
209
+ if (field in aObj) {
210
+ throw new OmaTrustError(
211
+ "INVALID_JWK",
212
+ `First JWK contains private key field "${field}"`,
213
+ { field }
214
+ );
215
+ }
216
+ if (field in bObj) {
217
+ throw new OmaTrustError(
218
+ "INVALID_JWK",
219
+ `Second JWK contains private key field "${field}"`,
220
+ { field }
221
+ );
222
+ }
223
+ }
224
+ const aPublic = extractPublicKeyFields(aObj);
225
+ const bPublic = extractPublicKeyFields(bObj);
226
+ return canonicalizeJwkJson(aPublic) === canonicalizeJwkJson(bPublic);
227
+ }
228
+ async function computeJwkThumbprint(jwk, digestAlgorithm = "sha256") {
229
+ assertObject(jwk, "jwk", "INVALID_JWK");
230
+ const validation = validatePublicJwk(jwk);
231
+ if (!validation.valid) {
232
+ throw new OmaTrustError("INVALID_JWK", validation.error ?? "Invalid public JWK", { jwk });
233
+ }
234
+ const alg = digestAlgorithm === "sha256" ? "sha256" : digestAlgorithm === "sha384" ? "sha384" : "sha512";
235
+ return calculateJwkThumbprint(jwk, alg);
236
+ }
237
+ async function formatJktValue(jwk) {
238
+ const thumbprint = await computeJwkThumbprint(jwk, "sha256");
239
+ return `jkt=S256:${thumbprint}`;
240
+ }
84
241
 
85
242
  // src/identity/did.ts
86
243
  var DID_REGEX = /^did:[a-z0-9]+:.+$/i;
@@ -156,7 +313,7 @@ function normalizeDidKey(input) {
156
313
  }
157
314
  function normalizeDid(input) {
158
315
  assertString(input, "input", "INVALID_DID");
159
- const trimmed = input.trim();
316
+ const trimmed = input.trim().split("#")[0];
160
317
  if (!trimmed.startsWith("did:")) {
161
318
  return normalizeDidWeb(trimmed);
162
319
  }
@@ -345,6 +502,15 @@ function validateDidPkh(did) {
345
502
  };
346
503
  }
347
504
  }
505
+ if (namespace === "solana") {
506
+ if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address)) {
507
+ return {
508
+ valid: false,
509
+ method: "pkh",
510
+ error: `Invalid Solana address "${address}" (must be 32-44 base58 characters)`
511
+ };
512
+ }
513
+ }
348
514
  return { valid: true, method: "pkh" };
349
515
  }
350
516
  function validateDidJwk(did) {
@@ -398,6 +564,10 @@ function validateDidJwk(did) {
398
564
  error: "DID must reference a public key \u2014 private key component (d) is not allowed"
399
565
  };
400
566
  }
567
+ const jwkValidation = validatePublicJwk(jwk);
568
+ if (!jwkValidation.valid) {
569
+ return { valid: false, method: "jwk", error: jwkValidation.error };
570
+ }
401
571
  return { valid: true, method: "jwk" };
402
572
  }
403
573
  function normalizeDidJwk(input) {
@@ -464,158 +634,6 @@ function assertBareDid(input, paramName = "did") {
464
634
  );
465
635
  }
466
636
  }
467
- var VALID_KTY = /* @__PURE__ */ new Set(["EC", "OKP", "RSA"]);
468
- var PRIVATE_KEY_FIELDS = /* @__PURE__ */ new Set(["d", "p", "q", "dp", "dq", "qi", "oth"]);
469
- var REQUIRED_PUBLIC_FIELDS = {
470
- EC: ["crv", "x", "y"],
471
- OKP: ["crv", "x"],
472
- RSA: ["n", "e"]
473
- };
474
- function validatePublicJwk(jwk) {
475
- if (!jwk || typeof jwk !== "object" || Array.isArray(jwk)) {
476
- return { valid: false, error: "JWK must be a non-null object" };
477
- }
478
- const obj = jwk;
479
- const kty = obj.kty;
480
- if (typeof kty !== "string" || !VALID_KTY.has(kty)) {
481
- return {
482
- valid: false,
483
- error: `Invalid or missing kty (must be one of: ${[...VALID_KTY].join(", ")})`
484
- };
485
- }
486
- for (const field of PRIVATE_KEY_FIELDS) {
487
- if (field in obj) {
488
- return {
489
- valid: false,
490
- error: `JWK contains private key field "${field}" \u2014 only public keys are allowed`
491
- };
492
- }
493
- }
494
- const required = REQUIRED_PUBLIC_FIELDS[kty];
495
- if (required) {
496
- for (const field of required) {
497
- if (!(field in obj) || obj[field] === void 0 || obj[field] === null || obj[field] === "") {
498
- return {
499
- valid: false,
500
- error: `Missing required public key field "${field}" for kty="${kty}"`
501
- };
502
- }
503
- }
504
- }
505
- return { valid: true };
506
- }
507
- function canonicalizeJwkJson(jwk) {
508
- const sorted = Object.keys(jwk).sort();
509
- const obj = {};
510
- for (const key of sorted) {
511
- obj[key] = jwk[key];
512
- }
513
- return JSON.stringify(obj);
514
- }
515
- function jwkToDidJwk(jwk) {
516
- assertObject(jwk, "jwk", "INVALID_JWK");
517
- const validation = validatePublicJwk(jwk);
518
- if (!validation.valid) {
519
- throw new OmaTrustError("INVALID_JWK", validation.error ?? "Invalid public JWK", { jwk });
520
- }
521
- const canonical = canonicalizeJwkJson(jwk);
522
- const encoded = base64url.encode(new TextEncoder().encode(canonical));
523
- return `did:jwk:${encoded}`;
524
- }
525
- function didJwkToJwk(didJwk) {
526
- if (typeof didJwk !== "string" || !didJwk.startsWith("did:jwk:")) {
527
- throw new OmaTrustError("INVALID_DID", "Expected a did:jwk DID", { input: didJwk });
528
- }
529
- const parts = didJwk.split(":");
530
- if (parts.length !== 3) {
531
- throw new OmaTrustError("INVALID_DID", "did:jwk must have exactly 3 colon-separated parts", {
532
- input: didJwk
533
- });
534
- }
535
- const encoded = parts[2];
536
- if (!encoded || encoded.length === 0) {
537
- throw new OmaTrustError("INVALID_DID", "Missing base64url-encoded JWK identifier", {
538
- input: didJwk
539
- });
540
- }
541
- let decoded;
542
- try {
543
- const bytes = base64url.decode(encoded);
544
- decoded = new TextDecoder().decode(bytes);
545
- } catch {
546
- throw new OmaTrustError("INVALID_DID", "Failed to base64url-decode did:jwk identifier", {
547
- input: didJwk
548
- });
549
- }
550
- let jwk;
551
- try {
552
- jwk = JSON.parse(decoded);
553
- } catch {
554
- throw new OmaTrustError("INVALID_DID", "Decoded did:jwk identifier is not valid JSON", {
555
- input: didJwk
556
- });
557
- }
558
- if (!jwk || typeof jwk !== "object" || Array.isArray(jwk)) {
559
- throw new OmaTrustError("INVALID_DID", "Decoded did:jwk must be a JSON object", {
560
- input: didJwk
561
- });
562
- }
563
- const validation = validatePublicJwk(jwk);
564
- if (!validation.valid) {
565
- throw new OmaTrustError("INVALID_DID", validation.error ?? "Invalid public JWK in did:jwk", {
566
- input: didJwk
567
- });
568
- }
569
- return jwk;
570
- }
571
- function extractPublicKeyFields(jwk) {
572
- const result = {};
573
- const metadataFields = /* @__PURE__ */ new Set(["kid", "use", "key_ops", "alg", "ext"]);
574
- for (const [key, value] of Object.entries(jwk)) {
575
- if (PRIVATE_KEY_FIELDS.has(key)) continue;
576
- if (metadataFields.has(key)) continue;
577
- result[key] = value;
578
- }
579
- return result;
580
- }
581
- function publicJwkEquals(a, b) {
582
- assertObject(a, "a", "INVALID_JWK");
583
- assertObject(b, "b", "INVALID_JWK");
584
- const aObj = a;
585
- const bObj = b;
586
- for (const field of PRIVATE_KEY_FIELDS) {
587
- if (field in aObj) {
588
- throw new OmaTrustError(
589
- "INVALID_JWK",
590
- `First JWK contains private key field "${field}"`,
591
- { field }
592
- );
593
- }
594
- if (field in bObj) {
595
- throw new OmaTrustError(
596
- "INVALID_JWK",
597
- `Second JWK contains private key field "${field}"`,
598
- { field }
599
- );
600
- }
601
- }
602
- const aPublic = extractPublicKeyFields(aObj);
603
- const bPublic = extractPublicKeyFields(bObj);
604
- return canonicalizeJwkJson(aPublic) === canonicalizeJwkJson(bPublic);
605
- }
606
- async function computeJwkThumbprint(jwk, digestAlgorithm = "sha256") {
607
- assertObject(jwk, "jwk", "INVALID_JWK");
608
- const validation = validatePublicJwk(jwk);
609
- if (!validation.valid) {
610
- throw new OmaTrustError("INVALID_JWK", validation.error ?? "Invalid public JWK", { jwk });
611
- }
612
- const alg = digestAlgorithm === "sha256" ? "sha256" : digestAlgorithm === "sha384" ? "sha384" : "sha512";
613
- return calculateJwkThumbprint(jwk, alg);
614
- }
615
- async function formatJktValue(jwk) {
616
- const thumbprint = await computeJwkThumbprint(jwk, "sha256");
617
- return `jkt=S256:${thumbprint}`;
618
- }
619
637
 
620
638
  // src/shared/did-document.ts
621
639
  async function fetchDidDocument(domain) {
@@ -778,7 +796,7 @@ function extractControllerEvmAddress(controllerDid) {
778
796
  function extractAuthorizationMetadata(result) {
779
797
  const payload = result.payload;
780
798
  const resourceUrl = typeof payload.resourceUrl === "string" ? payload.resourceUrl : null;
781
- const issuedAt = typeof payload.issuedAt === "string" ? payload.issuedAt : null;
799
+ const issuedAt = typeof payload.issuedAt === "string" ? payload.issuedAt : typeof payload.issuedAt === "number" ? payload.issuedAt : null;
782
800
  let subjectDid = null;
783
801
  if (resourceUrl) {
784
802
  try {
@@ -787,35 +805,468 @@ function extractAuthorizationMetadata(result) {
787
805
  } catch {
788
806
  }
789
807
  }
808
+ if ("publicKeyDid" in result) {
809
+ const jwsResult = result;
810
+ return {
811
+ controllerDid: jwsResult.publicKeyDid,
812
+ subjectDid,
813
+ resourceUrl,
814
+ issuedAt,
815
+ kid: jwsResult.kid,
816
+ publicKeyJwk: jwsResult.publicKeyJwk,
817
+ signer: null
818
+ };
819
+ }
820
+ const eip712Result = result;
821
+ const signerAddress = eip712Result.signer.toLowerCase();
790
822
  return {
791
- controllerDid: result.publicKeyDid,
823
+ controllerDid: `did:pkh:eip155:1:${signerAddress}`,
792
824
  subjectDid,
793
825
  resourceUrl,
794
826
  issuedAt,
795
- kid: result.kid,
796
- publicKeyJwk: result.publicKeyJwk
827
+ kid: null,
828
+ publicKeyJwk: null,
829
+ signer: eip712Result.signer
797
830
  };
798
831
  }
832
+ var VALID_ALGORITHMS = /* @__PURE__ */ new Set(["keccak256", "sha256"]);
833
+ var MAX_JSON_DEPTH = 32;
834
+ function assertDepthLimit(depth, context) {
835
+ if (depth > MAX_JSON_DEPTH) {
836
+ const msg = context ? `JSON nesting depth exceeds maximum of ${MAX_JSON_DEPTH} at ${context}` : `JSON nesting depth exceeds maximum of ${MAX_JSON_DEPTH}`;
837
+ throw new OmaTrustError("INVALID_INPUT", msg);
838
+ }
839
+ }
840
+ function parseJsonStrict(input) {
841
+ if (typeof input !== "string") {
842
+ throw new OmaTrustError("INVALID_INPUT", "Input must be a string");
843
+ }
844
+ const duplicateKeys = detectDuplicateKeys(input);
845
+ if (duplicateKeys.length > 0) {
846
+ throw new OmaTrustError(
847
+ "INVALID_INPUT",
848
+ `Duplicate JSON key${duplicateKeys.length > 1 ? "s" : ""} detected: ${duplicateKeys.map((k) => `"${k}"`).join(", ")}`,
849
+ { duplicateKeys }
850
+ );
851
+ }
852
+ try {
853
+ return JSON.parse(input);
854
+ } catch {
855
+ throw new OmaTrustError("INVALID_INPUT", "Input is not valid JSON");
856
+ }
857
+ }
858
+ function detectDuplicateKeys(input) {
859
+ const duplicates = [];
860
+ const objectKeyStack = [];
861
+ let inString = false;
862
+ let escaped = false;
863
+ let currentKey = "";
864
+ let collectingKey = false;
865
+ let afterColon = false;
866
+ let i = 0;
867
+ while (i < input.length) {
868
+ const ch = input[i];
869
+ if (escaped) {
870
+ if (collectingKey) currentKey += ch;
871
+ escaped = false;
872
+ i++;
873
+ continue;
874
+ }
875
+ if (ch === "\\") {
876
+ escaped = true;
877
+ if (collectingKey) currentKey += ch;
878
+ i++;
879
+ continue;
880
+ }
881
+ if (ch === '"') {
882
+ if (!inString) {
883
+ inString = true;
884
+ if (objectKeyStack.length > 0 && !afterColon) {
885
+ collectingKey = true;
886
+ currentKey = "";
887
+ }
888
+ } else {
889
+ inString = false;
890
+ if (collectingKey) {
891
+ collectingKey = false;
892
+ const keySet = objectKeyStack[objectKeyStack.length - 1];
893
+ if (keySet.has(currentKey)) {
894
+ if (!duplicates.includes(currentKey)) {
895
+ duplicates.push(currentKey);
896
+ }
897
+ } else {
898
+ keySet.add(currentKey);
899
+ }
900
+ }
901
+ }
902
+ i++;
903
+ continue;
904
+ }
905
+ if (inString) {
906
+ if (collectingKey) currentKey += ch;
907
+ i++;
908
+ continue;
909
+ }
910
+ if (ch === "{") {
911
+ objectKeyStack.push(/* @__PURE__ */ new Set());
912
+ assertDepthLimit(objectKeyStack.length);
913
+ afterColon = false;
914
+ } else if (ch === "}") {
915
+ objectKeyStack.pop();
916
+ afterColon = objectKeyStack.length > 0;
917
+ } else if (ch === "[") {
918
+ objectKeyStack.push(/* @__PURE__ */ new Set(["__array__"]));
919
+ assertDepthLimit(objectKeyStack.length);
920
+ afterColon = false;
921
+ } else if (ch === "]") {
922
+ objectKeyStack.pop();
923
+ afterColon = objectKeyStack.length > 0;
924
+ } else if (ch === ":") {
925
+ afterColon = true;
926
+ } else if (ch === ",") {
927
+ afterColon = false;
928
+ }
929
+ i++;
930
+ }
931
+ return duplicates;
932
+ }
933
+ function assertJsonSafe(value, path = "$", depth = 0) {
934
+ assertDepthLimit(depth, path);
935
+ if (value === void 0) {
936
+ throw new OmaTrustError("INVALID_INPUT", `Non-JSON-safe value at ${path}: undefined`);
937
+ }
938
+ if (value === null) return;
939
+ switch (typeof value) {
940
+ case "string":
941
+ case "boolean":
942
+ return;
943
+ case "number":
944
+ if (!Number.isFinite(value)) {
945
+ throw new OmaTrustError("INVALID_INPUT", `Non-JSON-safe value at ${path}: ${value} (must be finite number)`);
946
+ }
947
+ return;
948
+ case "bigint":
949
+ throw new OmaTrustError("INVALID_INPUT", `Non-JSON-safe value at ${path}: BigInt (use number or string)`);
950
+ case "function":
951
+ throw new OmaTrustError("INVALID_INPUT", `Non-JSON-safe value at ${path}: function`);
952
+ case "symbol":
953
+ throw new OmaTrustError("INVALID_INPUT", `Non-JSON-safe value at ${path}: Symbol`);
954
+ case "object":
955
+ if (value instanceof Date) {
956
+ throw new OmaTrustError("INVALID_INPUT", `Non-JSON-safe value at ${path}: Date (use ISO string or timestamp)`);
957
+ }
958
+ if (value instanceof RegExp) {
959
+ throw new OmaTrustError("INVALID_INPUT", `Non-JSON-safe value at ${path}: RegExp`);
960
+ }
961
+ if (Array.isArray(value)) {
962
+ for (let i = 0; i < value.length; i++) {
963
+ assertJsonSafe(value[i], `${path}[${i}]`, depth + 1);
964
+ }
965
+ return;
966
+ }
967
+ for (const [key, val] of Object.entries(value)) {
968
+ assertJsonSafe(val, `${path}.${key}`, depth + 1);
969
+ }
970
+ return;
971
+ default:
972
+ throw new OmaTrustError("INVALID_INPUT", `Non-JSON-safe value at ${path}: unknown type "${typeof value}"`);
973
+ }
974
+ }
799
975
  function canonicalizeJson(obj) {
976
+ assertJsonSafe(obj);
800
977
  const jcs = canonicalize(obj);
801
978
  if (!jcs) {
802
979
  throw new OmaTrustError("INVALID_INPUT", "Object cannot be canonicalized", { obj });
803
980
  }
804
981
  return jcs;
805
982
  }
806
- function canonicalizeForHash(obj) {
983
+ function canonicalizeAndKeccak256(obj) {
807
984
  const jcsJson = canonicalizeJson(obj);
808
985
  return {
809
986
  jcsJson,
810
987
  hash: keccak256(toUtf8Bytes(jcsJson))
811
988
  };
812
989
  }
990
+ function canonicalizeForHash(obj) {
991
+ return canonicalizeAndKeccak256(obj);
992
+ }
813
993
  function hashCanonicalizedJson(obj, algorithm) {
994
+ if (!VALID_ALGORITHMS.has(algorithm)) {
995
+ throw new OmaTrustError("INVALID_INPUT", `Unsupported hash algorithm: "${algorithm}". Must be "keccak256" or "sha256".`, { algorithm });
996
+ }
814
997
  const jcs = canonicalizeJson(obj);
815
998
  const bytes = toUtf8Bytes(jcs);
816
999
  return algorithm === "keccak256" ? keccak256(bytes) : sha256(bytes);
817
1000
  }
1001
+ var DID_ARTIFACT_PREFIX = "did:artifact:";
1002
+ var CID_VERSION = 1;
1003
+ var RAW_CODEC = raw.code;
1004
+ var SHA2_256_CODE = 18;
1005
+ var SHA2_256_DIGEST_LENGTH = 32;
1006
+ async function artifactDidFromBytes(bytes) {
1007
+ if (!(bytes instanceof Uint8Array) || bytes.length === 0) {
1008
+ throw new OmaTrustError(
1009
+ "INVALID_INPUT",
1010
+ "bytes must be a non-empty Uint8Array"
1011
+ );
1012
+ }
1013
+ const digest = await sha256$1.digest(bytes);
1014
+ const cid = CID.createV1(RAW_CODEC, digest);
1015
+ return `${DID_ARTIFACT_PREFIX}${cid.toString(base32)}`;
1016
+ }
1017
+ async function artifactDidFromJson(input) {
1018
+ const value = typeof input === "string" ? parseJsonStrict(input) : input;
1019
+ const jcs = canonicalizeJson(value);
1020
+ const bytes = new TextEncoder().encode(jcs);
1021
+ const digest = await sha256$1.digest(bytes);
1022
+ const cid = CID.createV1(RAW_CODEC, digest);
1023
+ return `${DID_ARTIFACT_PREFIX}${cid.toString(base32)}`;
1024
+ }
1025
+ function parseArtifactDid(did) {
1026
+ if (typeof did !== "string" || !did.startsWith(DID_ARTIFACT_PREFIX)) {
1027
+ throw new OmaTrustError("INVALID_DID", "Expected a did:artifact DID", { did });
1028
+ }
1029
+ const identifier = did.slice(DID_ARTIFACT_PREFIX.length);
1030
+ if (!identifier || identifier.length === 0) {
1031
+ throw new OmaTrustError("INVALID_DID", "Missing method-specific identifier", { did });
1032
+ }
1033
+ if (identifier[0] !== "b") {
1034
+ throw new OmaTrustError(
1035
+ "INVALID_DID",
1036
+ `Invalid multibase prefix "${identifier[0]}", expected "b" (base32lower)`,
1037
+ { did }
1038
+ );
1039
+ }
1040
+ let cid;
1041
+ try {
1042
+ cid = CID.parse(identifier, base32);
1043
+ } catch (err) {
1044
+ throw new OmaTrustError(
1045
+ "INVALID_DID",
1046
+ "Failed to decode base32 CID from did:artifact identifier",
1047
+ { did, cause: err }
1048
+ );
1049
+ }
1050
+ if (cid.version !== CID_VERSION) {
1051
+ throw new OmaTrustError(
1052
+ "INVALID_DID",
1053
+ `CID version must be 1, got ${cid.version}`,
1054
+ { did }
1055
+ );
1056
+ }
1057
+ if (cid.code !== RAW_CODEC) {
1058
+ throw new OmaTrustError(
1059
+ "INVALID_DID",
1060
+ `Multicodec must be raw (0x55), got 0x${cid.code.toString(16)}`,
1061
+ { did }
1062
+ );
1063
+ }
1064
+ if (cid.multihash.code !== SHA2_256_CODE) {
1065
+ throw new OmaTrustError(
1066
+ "INVALID_DID",
1067
+ `Multihash function must be sha2-256 (0x12), got 0x${cid.multihash.code.toString(16)}`,
1068
+ { did }
1069
+ );
1070
+ }
1071
+ if (cid.multihash.digest.length !== SHA2_256_DIGEST_LENGTH) {
1072
+ throw new OmaTrustError(
1073
+ "INVALID_DID",
1074
+ `SHA-256 digest must be 32 bytes, got ${cid.multihash.digest.length}`,
1075
+ { did }
1076
+ );
1077
+ }
1078
+ const digest = cid.multihash.digest;
1079
+ const digestHex = Array.from(digest).map((b) => b.toString(16).padStart(2, "0")).join("");
1080
+ return { did, identifier, digest, digestHex };
1081
+ }
1082
+ async function verifyDidArtifact(did, content) {
1083
+ let parsed;
1084
+ try {
1085
+ parsed = parseArtifactDid(did);
1086
+ } catch (err) {
1087
+ return {
1088
+ valid: false,
1089
+ reason: err instanceof OmaTrustError ? err.message : "Invalid did:artifact DID"
1090
+ };
1091
+ }
1092
+ const expectedHex = parsed.digestHex;
1093
+ if (typeof content === "string" || typeof content === "object" && content !== null && !(content instanceof Uint8Array)) {
1094
+ try {
1095
+ const value = typeof content === "string" ? parseJsonStrict(content) : content;
1096
+ const jcs = canonicalizeJson(value);
1097
+ const jcsBytes = new TextEncoder().encode(jcs);
1098
+ const digest2 = await sha256$1.digest(jcsBytes);
1099
+ const digestHex2 = Array.from(digest2.digest).map((b) => b.toString(16).padStart(2, "0")).join("");
1100
+ if (digestHex2 === expectedHex) {
1101
+ return { valid: true, matchedAs: "json" };
1102
+ }
1103
+ } catch {
1104
+ }
1105
+ }
1106
+ let rawBytes;
1107
+ if (content instanceof Uint8Array) {
1108
+ rawBytes = content;
1109
+ } else if (typeof content === "string") {
1110
+ rawBytes = new TextEncoder().encode(content);
1111
+ } else {
1112
+ return {
1113
+ valid: false,
1114
+ reason: "Content did not match as canonical JSON and is not raw bytes"
1115
+ };
1116
+ }
1117
+ const digest = await sha256$1.digest(rawBytes);
1118
+ const digestHex = Array.from(digest.digest).map((b) => b.toString(16).padStart(2, "0")).join("");
1119
+ if (digestHex === expectedHex) {
1120
+ return { valid: true, matchedAs: "binary" };
1121
+ }
1122
+ return {
1123
+ valid: false,
1124
+ reason: "Content does not match the did:artifact identifier (neither as canonical JSON nor as raw bytes)"
1125
+ };
1126
+ }
1127
+ function didEthrToDidPkh(did) {
1128
+ if (typeof did !== "string" || !did.startsWith("did:ethr:")) {
1129
+ throw new OmaTrustError("INVALID_DID", "Expected a did:ethr DID", { did });
1130
+ }
1131
+ const remainder = did.slice("did:ethr:".length);
1132
+ if (!remainder) {
1133
+ throw new OmaTrustError("INVALID_DID", "Missing identifier in did:ethr DID", { did });
1134
+ }
1135
+ let chainId;
1136
+ let address;
1137
+ const parts = remainder.split(":");
1138
+ if (parts.length === 1) {
1139
+ chainId = "1";
1140
+ address = parts[0];
1141
+ } else if (parts.length === 2) {
1142
+ const rawChainId = parts[0];
1143
+ address = parts[1];
1144
+ if (rawChainId.startsWith("0x")) {
1145
+ chainId = String(parseInt(rawChainId, 16));
1146
+ } else if (/^\d+$/.test(rawChainId)) {
1147
+ chainId = rawChainId;
1148
+ } else {
1149
+ const networkMap = {
1150
+ mainnet: "1",
1151
+ goerli: "5",
1152
+ sepolia: "11155111",
1153
+ polygon: "137",
1154
+ arbitrum: "42161",
1155
+ optimism: "10",
1156
+ base: "8453"
1157
+ };
1158
+ const mapped = networkMap[rawChainId.toLowerCase()];
1159
+ if (!mapped) {
1160
+ throw new OmaTrustError(
1161
+ "INVALID_DID",
1162
+ `Unknown did:ethr network "${rawChainId}"`,
1163
+ { did, network: rawChainId }
1164
+ );
1165
+ }
1166
+ chainId = mapped;
1167
+ }
1168
+ } else {
1169
+ throw new OmaTrustError("INVALID_DID", "Invalid did:ethr format", { did });
1170
+ }
1171
+ if (!isAddress(address)) {
1172
+ throw new OmaTrustError("INVALID_DID", "Invalid Ethereum address in did:ethr DID", {
1173
+ did,
1174
+ address
1175
+ });
1176
+ }
1177
+ const checksummed = getAddress(address);
1178
+ return `did:pkh:eip155:${chainId}:${checksummed.toLowerCase()}`;
1179
+ }
1180
+ var MULTICODEC_KEY_TYPES = {
1181
+ // Ed25519 public key: 0xed (varint encoded as [0xed, 0x01])
1182
+ 237: { kty: "OKP", crv: "Ed25519" },
1183
+ // X25519 public key: 0xec (varint encoded as [0xec, 0x01])
1184
+ 236: { kty: "OKP", crv: "X25519" },
1185
+ // secp256k1 public key (compressed): 0xe7 (varint encoded as [0xe7, 0x01])
1186
+ 231: { kty: "EC", crv: "secp256k1", coordSize: 33 },
1187
+ // P-256 public key (compressed): 0x80 0x24 (varint 0x1200)
1188
+ 4608: { kty: "EC", crv: "P-256", coordSize: 33 },
1189
+ // P-384 public key (compressed): 0x81 0x24 (varint 0x1201)
1190
+ 4609: { kty: "EC", crv: "P-384", coordSize: 49 }
1191
+ };
1192
+ function readVarint(bytes, offset) {
1193
+ let value = 0;
1194
+ let shift = 0;
1195
+ let bytesRead = 0;
1196
+ while (offset + bytesRead < bytes.length) {
1197
+ const byte = bytes[offset + bytesRead];
1198
+ value |= (byte & 127) << shift;
1199
+ bytesRead++;
1200
+ if ((byte & 128) === 0) {
1201
+ return { value, bytesRead };
1202
+ }
1203
+ shift += 7;
1204
+ if (shift > 28) {
1205
+ throw new OmaTrustError("INVALID_DID", "Varint too long in did:key multicodec prefix");
1206
+ }
1207
+ }
1208
+ throw new OmaTrustError("INVALID_DID", "Truncated varint in did:key multicodec prefix");
1209
+ }
1210
+ function decompressEcKey(compressedKey, crv) {
1211
+ throw new OmaTrustError(
1212
+ "UNSUPPORTED_KEY_TYPE",
1213
+ `Cannot convert compressed EC key (${crv}) from did:key to did:jwk. Decompressing EC points requires elliptic curve arithmetic. For EVM keys, use didEthrToDidPkh() instead.`,
1214
+ { crv, keyLength: compressedKey.length }
1215
+ );
1216
+ }
1217
+ function didKeyToDidJwk(did) {
1218
+ if (typeof did !== "string" || !did.startsWith("did:key:")) {
1219
+ throw new OmaTrustError("INVALID_DID", "Expected a did:key DID", { did });
1220
+ }
1221
+ const identifier = did.slice("did:key:".length);
1222
+ if (!identifier || !identifier.startsWith("z")) {
1223
+ throw new OmaTrustError(
1224
+ "INVALID_DID",
1225
+ "did:key identifier must start with 'z' (base58btc multibase prefix)",
1226
+ { did }
1227
+ );
1228
+ }
1229
+ let decoded;
1230
+ try {
1231
+ decoded = base58btc.decode(identifier);
1232
+ } catch (err) {
1233
+ throw new OmaTrustError(
1234
+ "INVALID_DID",
1235
+ "Failed to decode base58btc from did:key identifier",
1236
+ { did, cause: err }
1237
+ );
1238
+ }
1239
+ if (decoded.length < 3) {
1240
+ throw new OmaTrustError("INVALID_DID", "did:key decoded bytes too short", { did });
1241
+ }
1242
+ const { value: codecValue, bytesRead } = readVarint(decoded, 0);
1243
+ const keyType = MULTICODEC_KEY_TYPES[codecValue];
1244
+ if (!keyType) {
1245
+ throw new OmaTrustError(
1246
+ "UNSUPPORTED_KEY_TYPE",
1247
+ `Unsupported multicodec key type 0x${codecValue.toString(16)} in did:key`,
1248
+ { did, codec: `0x${codecValue.toString(16)}` }
1249
+ );
1250
+ }
1251
+ const keyBytes = decoded.slice(bytesRead);
1252
+ if (keyType.kty === "OKP") {
1253
+ if (keyBytes.length !== 32) {
1254
+ throw new OmaTrustError(
1255
+ "INVALID_DID",
1256
+ `Expected 32-byte ${keyType.crv} key, got ${keyBytes.length} bytes`,
1257
+ { did, crv: keyType.crv }
1258
+ );
1259
+ }
1260
+ const jwk = {
1261
+ kty: keyType.kty,
1262
+ crv: keyType.crv,
1263
+ x: base64url.encode(keyBytes)
1264
+ };
1265
+ return jwkToDidJwk(jwk);
1266
+ }
1267
+ return decompressEcKey(keyBytes, keyType.crv).x.toString();
1268
+ }
818
1269
 
819
- export { assertBareDid, buildCaip10, buildCaip2, buildDidPkh, buildDidPkhFromCaip10, buildDidWeb, buildEvmDidPkh, canonicalizeForHash, canonicalizeJson, computeDidAddress, computeDidHash, computeJwkThumbprint, didJwkToJwk, didToAddress, extractAddressFromDid, extractAuthorizationMetadata, extractControllerEvmAddress, extractDidIdentifier, extractDidMethod, formatJktValue, getAddressFromDidPkh, getChainIdFromDidPkh, getDomainFromDidWeb, getNamespaceFromDidPkh, hashCanonicalizedJson, isDidUrl, isEvmDidPkh, isPrivateKeyDid, isSameControllerId, isValidDid, jwkToDidJwk, normalizeCaip10, normalizeDid, normalizeDidHandle, normalizeDidJwk, normalizeDidKey, normalizeDidPkh, normalizeDidWeb, normalizeDomain, parseCaip10, parseCaip2, parseDidUrl, publicJwkEquals, resolveDidUrlToControllerDid, resolveDidUrlToPublicKey, validateDidAddress, validatePrivateKeyDid, validatePublicJwk };
1270
+ export { artifactDidFromBytes, artifactDidFromJson, assertBareDid, assertJsonSafe, buildCaip10, buildCaip2, buildDidPkh, buildDidPkhFromCaip10, buildDidWeb, buildEvmDidPkh, canonicalizeAndKeccak256, canonicalizeForHash, canonicalizeJson, computeDidAddress, computeDidHash, computeJwkThumbprint, didEthrToDidPkh, didJwkToJwk, didKeyToDidJwk, didToAddress, extractAddressFromDid, extractAuthorizationMetadata, extractControllerEvmAddress, extractDidIdentifier, extractDidMethod, formatJktValue, getAddressFromDidPkh, getChainIdFromDidPkh, getDomainFromDidWeb, getNamespaceFromDidPkh, hashCanonicalizedJson, isDidUrl, isEvmDidPkh, isPrivateKeyDid, isSameControllerId, isValidDid, jwkToDidJwk, normalizeCaip10, normalizeDid, normalizeDidHandle, normalizeDidJwk, normalizeDidKey, normalizeDidPkh, normalizeDidWeb, normalizeDomain, parseArtifactDid, parseCaip10, parseCaip2, parseDidUrl, parseJsonStrict, publicJwkEquals, resolveDidUrlToControllerDid, resolveDidUrlToPublicKey, validateDidAddress, validatePrivateKeyDid, validatePublicJwk, verifyDidArtifact };
820
1271
  //# sourceMappingURL=index.js.map
821
1272
  //# sourceMappingURL=index.js.map