@veridid/kanon 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +156 -2
  3. package/build/KanonApi.d.ts +52 -0
  4. package/build/KanonApi.d.ts.map +1 -0
  5. package/build/KanonApi.js +92 -0
  6. package/build/KanonApi.js.map +1 -0
  7. package/build/KanonModule.d.ts +15 -0
  8. package/build/KanonModule.d.ts.map +1 -0
  9. package/build/KanonModule.js +53 -0
  10. package/build/KanonModule.js.map +1 -0
  11. package/build/KanonModuleConfig.d.ts +123 -0
  12. package/build/KanonModuleConfig.d.ts.map +1 -0
  13. package/build/KanonModuleConfig.js +84 -0
  14. package/build/KanonModuleConfig.js.map +1 -0
  15. package/build/_virtual/_@oxc-project_runtime@0.112.0/helpers/decorate.js +10 -0
  16. package/build/_virtual/_@oxc-project_runtime@0.112.0/helpers/decorateMetadata.js +7 -0
  17. package/build/_virtual/_@oxc-project_runtime@0.112.0/helpers/decorateParam.js +9 -0
  18. package/build/anoncreds/helpers/buildKanonCredentialAttributes.d.ts +33 -0
  19. package/build/anoncreds/helpers/buildKanonCredentialAttributes.d.ts.map +1 -0
  20. package/build/anoncreds/helpers/buildKanonCredentialAttributes.js +43 -0
  21. package/build/anoncreds/helpers/buildKanonCredentialAttributes.js.map +1 -0
  22. package/build/anoncreds/helpers/buildKanonProofRequest.d.ts +45 -0
  23. package/build/anoncreds/helpers/buildKanonProofRequest.d.ts.map +1 -0
  24. package/build/anoncreds/helpers/buildKanonProofRequest.js +45 -0
  25. package/build/anoncreds/helpers/buildKanonProofRequest.js.map +1 -0
  26. package/build/anoncreds/helpers/buildKanonSchema.d.ts +23 -0
  27. package/build/anoncreds/helpers/buildKanonSchema.d.ts.map +1 -0
  28. package/build/anoncreds/helpers/buildKanonSchema.js +27 -0
  29. package/build/anoncreds/helpers/buildKanonSchema.js.map +1 -0
  30. package/build/anoncreds/helpers/index.js +3 -0
  31. package/build/anoncreds/index.d.ts +8 -0
  32. package/build/anoncreds/index.js +9 -0
  33. package/build/anoncreds/services/KanonAnonCredsRegistry.d.ts +36 -0
  34. package/build/anoncreds/services/KanonAnonCredsRegistry.d.ts.map +1 -0
  35. package/build/anoncreds/services/KanonAnonCredsRegistry.js +298 -0
  36. package/build/anoncreds/services/KanonAnonCredsRegistry.js.map +1 -0
  37. package/build/anoncreds/services/KanonIssuanceTracker.d.ts +39 -0
  38. package/build/anoncreds/services/KanonIssuanceTracker.d.ts.map +1 -0
  39. package/build/anoncreds/services/KanonIssuanceTracker.js +141 -0
  40. package/build/anoncreds/services/KanonIssuanceTracker.js.map +1 -0
  41. package/build/anoncreds/services/KanonWrappedAnonCredsHolderService.d.ts +82 -0
  42. package/build/anoncreds/services/KanonWrappedAnonCredsHolderService.d.ts.map +1 -0
  43. package/build/anoncreds/services/KanonWrappedAnonCredsHolderService.js +316 -0
  44. package/build/anoncreds/services/KanonWrappedAnonCredsHolderService.js.map +1 -0
  45. package/build/anoncreds/services/KanonWrappedAnonCredsVerifierService.d.ts +67 -0
  46. package/build/anoncreds/services/KanonWrappedAnonCredsVerifierService.d.ts.map +1 -0
  47. package/build/anoncreds/services/KanonWrappedAnonCredsVerifierService.js +330 -0
  48. package/build/anoncreds/services/KanonWrappedAnonCredsVerifierService.js.map +1 -0
  49. package/build/anoncreds/utils/credIdHash.d.ts +2 -0
  50. package/build/anoncreds/utils/credIdHash.js +3 -0
  51. package/build/dids/KanonDidRegistrar.d.ts +47 -0
  52. package/build/dids/KanonDidRegistrar.d.ts.map +1 -0
  53. package/build/dids/KanonDidRegistrar.js +140 -0
  54. package/build/dids/KanonDidRegistrar.js.map +1 -0
  55. package/build/dids/KanonDidResolver.d.ts +18 -0
  56. package/build/dids/KanonDidResolver.d.ts.map +1 -0
  57. package/build/dids/KanonDidResolver.js +88 -0
  58. package/build/dids/KanonDidResolver.js.map +1 -0
  59. package/build/dids/didEtherUtils.d.ts +18 -0
  60. package/build/dids/didEtherUtils.d.ts.map +1 -0
  61. package/build/dids/didEtherUtils.js +47 -0
  62. package/build/dids/didEtherUtils.js.map +1 -0
  63. package/build/dids/index.js +3 -0
  64. package/build/index.d.ts +24 -0
  65. package/build/index.js +25 -0
  66. package/build/ledger/KanonClientService.d.ts +45 -0
  67. package/build/ledger/KanonClientService.d.ts.map +1 -0
  68. package/build/ledger/KanonClientService.js +111 -0
  69. package/build/ledger/KanonClientService.js.map +1 -0
  70. package/build/ledger/index.d.ts +1 -0
  71. package/build/ledger/index.js +1 -0
  72. package/build/utils/identifiers.d.ts +24 -0
  73. package/build/utils/identifiers.d.ts.map +1 -0
  74. package/build/utils/identifiers.js +39 -0
  75. package/build/utils/identifiers.js.map +1 -0
  76. package/build/zk/KanonZkApi.d.ts +186 -0
  77. package/build/zk/KanonZkApi.d.ts.map +1 -0
  78. package/build/zk/KanonZkApi.js +226 -0
  79. package/build/zk/KanonZkApi.js.map +1 -0
  80. package/build/zk/KanonZkIssuerKeyService.d.ts +107 -0
  81. package/build/zk/KanonZkIssuerKeyService.d.ts.map +1 -0
  82. package/build/zk/KanonZkIssuerKeyService.js +137 -0
  83. package/build/zk/KanonZkIssuerKeyService.js.map +1 -0
  84. package/build/zk/KanonZkPathService.d.ts +66 -0
  85. package/build/zk/KanonZkPathService.d.ts.map +1 -0
  86. package/build/zk/KanonZkPathService.js +163 -0
  87. package/build/zk/KanonZkPathService.js.map +1 -0
  88. package/build/zk/KanonZkService.d.ts +91 -0
  89. package/build/zk/KanonZkService.d.ts.map +1 -0
  90. package/build/zk/KanonZkService.js +165 -0
  91. package/build/zk/KanonZkService.js.map +1 -0
  92. package/build/zk/index.d.ts +4 -0
  93. package/build/zk/index.js +4 -0
  94. package/build/zk/modeBLeaves.js +48 -0
  95. package/build/zk/modeBLeaves.js.map +1 -0
  96. package/package.json +66 -3
@@ -0,0 +1,330 @@
1
+ import { __decorate } from "../../_virtual/_@oxc-project_runtime@0.112.0/helpers/decorate.js";
2
+ import { __decorateMetadata } from "../../_virtual/_@oxc-project_runtime@0.112.0/helpers/decorateMetadata.js";
3
+ import { __decorateParam } from "../../_virtual/_@oxc-project_runtime@0.112.0/helpers/decorateParam.js";
4
+ import { KanonClientService } from "../../ledger/KanonClientService.js";
5
+ import "../../ledger/index.js";
6
+ import { KANON_CRED_ID_ATTRIBUTE as KANON_CRED_ID_ATTRIBUTE$1, kanonCredIdHash as kanonCredIdHash$1 } from "../utils/credIdHash.js";
7
+ import { credDefIdToBytes32, kanonZkProofReferent } from "./KanonWrappedAnonCredsHolderService.js";
8
+ import { BN254_SCALAR_FIELD, KANON_ZK_SIG_ATTRIBUTE, attrValueToFelt, decodeKanonZkProofAttr } from "@ajna-inc/kanon-sdk";
9
+ import { inject, injectable } from "@credo-ts/core";
10
+
11
+ //#region src/anoncreds/services/KanonWrappedAnonCredsVerifierService.ts
12
+ var _ref;
13
+ const TIER_ZK_SNARK$1 = 2;
14
+ /**
15
+ * Injection token used by {@link KanonModule} to register the original
16
+ * `AnonCredsRsVerifierService` so the {@link KanonWrappedAnonCredsVerifierService}
17
+ * can inject it without pulling in a deep `@credo-ts/anoncreds/build/...` import.
18
+ *
19
+ * The module registers the original verifier under this symbol, then overrides
20
+ * the public `AnonCredsVerifierServiceSymbol` binding with the wrapper.
21
+ */
22
+ const OriginalAnonCredsVerifierServiceSymbol = Symbol("OriginalAnonCredsVerifierService");
23
+ let KanonWrappedAnonCredsVerifierService = class KanonWrappedAnonCredsVerifierService {
24
+ constructor(inner, ledgerService) {
25
+ this.inner = inner;
26
+ this.ledgerService = ledgerService;
27
+ this.policyCache = /* @__PURE__ */ new Map();
28
+ }
29
+ async verifyProof(agentContext, options) {
30
+ const modeBCredDefs = await this.collectModeBCredDefIds(agentContext, options);
31
+ if (!await this.inner.verifyProof(agentContext, options)) return false;
32
+ if (!await this.verifyModeBProofs(agentContext, options, modeBCredDefs)) return false;
33
+ if (!this.ledgerService.hasAnonCredsStatusRegistry()) {
34
+ agentContext.config.logger.debug("KanonWrappedAnonCredsVerifierService: status registry not configured; skipping on-chain revocation check");
35
+ return true;
36
+ }
37
+ if (!proofRequestHasKanonCredIdReferent(options)) {
38
+ agentContext.config.logger.debug(`KanonWrappedAnonCredsVerifierService: proof request did not declare a ${KANON_CRED_ID_ATTRIBUTE$1} referent; skipping Mode A revocation check`);
39
+ return true;
40
+ }
41
+ const checks = collectKanonCredentialIdentifiers(options);
42
+ if (checks.length === 0) {
43
+ agentContext.config.logger.warn(`KanonWrappedAnonCredsVerifierService: no disclosed ${KANON_CRED_ID_ATTRIBUTE$1} attribute found; cannot verify revocation status — rejecting proof`);
44
+ return false;
45
+ }
46
+ for (const { credDefId, credId } of checks) {
47
+ const credIdHash = kanonCredIdHash$1(credId);
48
+ if (await this.ledgerService.isCredentialRevokedOnStatus(credDefId, credIdHash)) {
49
+ agentContext.config.logger.debug(`KanonWrappedAnonCredsVerifierService: credential ${credId} is revoked on-chain under credDef ${credDefId}`);
50
+ return false;
51
+ }
52
+ }
53
+ return true;
54
+ }
55
+ /**
56
+ * Verify the Mode B SNARK proof carried by each Tier-2 credDef in the
57
+ * presentation.
58
+ *
59
+ * For every credDef referenced in `proof.identifiers` whose on-chain
60
+ * policyMask includes `TIER_ZK_SNARK`, we look for
61
+ * `proof.requested_proof.self_attested_attrs[kanon_<credDefId>_zkProof]`,
62
+ * decode it, and submit to `MerkleStateRegistry.verifyZKMembership`. Any
63
+ * missing or rejected proof fails the whole presentation.
64
+ *
65
+ * Mode A-only credDefs are unaffected — their presentations don't carry a
66
+ * `kanonZkProof` referent and this check is a no-op for them.
67
+ */
68
+ /**
69
+ * Scan `proof.identifiers` for credDefs that satisfy BOTH:
70
+ *
71
+ * 1. On-chain policyMask includes `TIER_ZK_SNARK` (the credDef opted into
72
+ * Mode B at registration).
73
+ * 2. This verifier's proof request DECLARED the
74
+ * `kanon_<credDefId>_zkProof` referent (the verifier opted in to
75
+ * checking it here).
76
+ *
77
+ * Both conditions must hold — Mode B is opt-in per-verifier-per-request.
78
+ */
79
+ async collectModeBCredDefIds(agentContext, options) {
80
+ const proof = options.proof;
81
+ const identifiers = Array.isArray(proof?.identifiers) ? proof.identifiers : [];
82
+ const requestedAttrs = options.proofRequest?.requested_attributes ?? {};
83
+ const out = [];
84
+ const seen = /* @__PURE__ */ new Set();
85
+ for (const id of identifiers) {
86
+ const credDefId = id?.cred_def_id;
87
+ if (typeof credDefId !== "string" || seen.has(credDefId)) continue;
88
+ seen.add(credDefId);
89
+ if ((await this.getPolicyMask(agentContext, credDefId) & TIER_ZK_SNARK$1) === 0) continue;
90
+ if (!(kanonZkProofReferent(credDefId) in requestedAttrs)) continue;
91
+ out.push(credDefId);
92
+ }
93
+ return out;
94
+ }
95
+ async verifyModeBProofs(agentContext, options, modeBCredDefs) {
96
+ if (modeBCredDefs.length === 0) return true;
97
+ const selfAttested = options.proof?.requested_proof?.self_attested_attrs ?? {};
98
+ const nonceRaw = options.proofRequest?.nonce;
99
+ if (typeof nonceRaw !== "string" || nonceRaw.length === 0) {
100
+ agentContext.config.logger.warn("KanonWrappedAnonCredsVerifierService: proof request missing nonce; cannot bind Mode B challenge — rejecting");
101
+ return false;
102
+ }
103
+ const expectedChallenge = BigInt(nonceRaw) % BN254_SCALAR_FIELD;
104
+ for (const credDefId of modeBCredDefs) {
105
+ const referent = kanonZkProofReferent(credDefId);
106
+ const encoded = selfAttested[referent];
107
+ if (typeof encoded !== "string" || encoded.length === 0) {
108
+ agentContext.config.logger.warn(`KanonWrappedAnonCredsVerifierService: Mode B credDef ${credDefId} requires ${referent} self-attested attribute; not found in proof — rejecting`);
109
+ return false;
110
+ }
111
+ let wire;
112
+ try {
113
+ wire = decodeKanonZkProofAttr(encoded);
114
+ } catch (err) {
115
+ const message = err instanceof Error ? err.message : String(err);
116
+ agentContext.config.logger.warn(`KanonWrappedAnonCredsVerifierService: failed to decode ${referent}: ${message} — rejecting`);
117
+ return false;
118
+ }
119
+ const providedChallenge = BigInt(wire.publicSignals[2]);
120
+ if (providedChallenge !== expectedChallenge) {
121
+ agentContext.config.logger.warn(`KanonWrappedAnonCredsVerifierService: Mode B challenge mismatch for ${credDefId} — expected=${expectedChallenge}, got=${providedChallenge} (possible replay) — rejecting`);
122
+ return false;
123
+ }
124
+ const providedDisclosedIndex = Number(BigInt(wire.publicSignals[5]));
125
+ const providedDisclosedFelt = BigInt(wire.publicSignals[6]);
126
+ const matchingRevealed = collectAnonCredsRevealedFelts(options, credDefId);
127
+ if (matchingRevealed.length === 0) {
128
+ agentContext.config.logger.warn(`KanonWrappedAnonCredsVerifierService: Mode B credDef ${credDefId} requires a revealed AnonCreds attribute the SNARK can bind to, but the proof has none — rejecting`);
129
+ return false;
130
+ }
131
+ if (!matchingRevealed.some((p) => p.position === providedDisclosedIndex && p.felt === providedDisclosedFelt)) {
132
+ agentContext.config.logger.warn(`KanonWrappedAnonCredsVerifierService: Mode B disclosed (idx=${providedDisclosedIndex}, val=${providedDisclosedFelt}) for ${credDefId} does not match any AnonCreds-revealed (position, felt) pair — rejecting`);
133
+ return false;
134
+ }
135
+ const merkleStateRegistry = this.ledgerService.contracts.merkleStateRegistry;
136
+ let ok = false;
137
+ try {
138
+ ok = await merkleStateRegistry.verifyZKMembership(credDefIdToBytes32(credDefId), wire.proofBytes, wire.publicSignals);
139
+ } catch (err) {
140
+ const message = err instanceof Error ? err.message : String(err);
141
+ agentContext.config.logger.warn(`KanonWrappedAnonCredsVerifierService: verifyZKMembership(${credDefId}) reverted: ${message}`);
142
+ return false;
143
+ }
144
+ if (!ok) {
145
+ agentContext.config.logger.warn(`KanonWrappedAnonCredsVerifierService: Mode B proof for ${credDefId} rejected on chain`);
146
+ return false;
147
+ }
148
+ agentContext.config.logger.debug(`KanonWrappedAnonCredsVerifierService: Mode B proof for ${credDefId} verified on chain`);
149
+ }
150
+ return true;
151
+ }
152
+ async getPolicyMask(agentContext, credDefId) {
153
+ const cached = this.policyCache.get(credDefId);
154
+ if (cached !== void 0) return cached;
155
+ try {
156
+ const mask = await this.ledgerService.client.getCredDefPolicy(credDefIdToBytes32(credDefId));
157
+ this.policyCache.set(credDefId, mask);
158
+ return mask;
159
+ } catch (err) {
160
+ const message = err instanceof Error ? err.message : String(err);
161
+ agentContext.config.logger.debug(`KanonWrappedAnonCredsVerifierService: getCredDefPolicy(${credDefId}) failed (${message}); defaulting to Mode A only`);
162
+ this.policyCache.set(credDefId, 1);
163
+ return 1;
164
+ }
165
+ }
166
+ async verifyW3cPresentation(agentContext, options) {
167
+ if (!await this.inner.verifyW3cPresentation(agentContext, options)) return false;
168
+ if (!this.ledgerService.hasAnonCredsStatusRegistry()) return true;
169
+ const checks = collectKanonCredentialIdentifiersFromW3c(options);
170
+ if (checks.length === 0) {
171
+ agentContext.config.logger.warn(`KanonWrappedAnonCredsVerifierService: no disclosed ${KANON_CRED_ID_ATTRIBUTE$1} found in W3C presentation; rejecting`);
172
+ return false;
173
+ }
174
+ for (const { credDefId, credId } of checks) {
175
+ const credIdHash = kanonCredIdHash$1(credId);
176
+ if (await this.ledgerService.isCredentialRevokedOnStatus(credDefId, credIdHash)) return false;
177
+ }
178
+ return true;
179
+ }
180
+ };
181
+ KanonWrappedAnonCredsVerifierService = __decorate([
182
+ injectable(),
183
+ __decorateParam(0, inject(OriginalAnonCredsVerifierServiceSymbol)),
184
+ __decorateMetadata("design:paramtypes", [Object, KanonClientService])
185
+ ], KanonWrappedAnonCredsVerifierService);
186
+ /**
187
+ * Matches the referent naming convention produced by `buildKanonProofRequest`,
188
+ * which scopes the disclosed `kanonCredId` per credDef as `kanon_<credDefId>_credId`.
189
+ * The verifier accepts either the simple `kanonCredId` attribute name or any
190
+ * referent matching this pattern, so callers can use the helper or hand-craft
191
+ * the request.
192
+ */
193
+ const KANON_REFERENT_PATTERN = /^kanon_.+_credId$/;
194
+ /**
195
+ * Collect AnonCreds-revealed (position, felt) pairs for `credDefId`.
196
+ *
197
+ * Walks `proof.requested_proof.revealed_attrs` (and `revealed_attr_groups`)
198
+ * matching against `proof.identifiers[sub_proof_index].cred_def_id` to find
199
+ * entries that belong to the credDef. For each match, we look up the
200
+ * attribute name in the canonical (lexicographic) order of the credDef's
201
+ * schema attrNames — same order the holder + leaf use. SDK-reserved names
202
+ * (`kanonCredId`, `kanonZkSig`) are excluded both from the canonical
203
+ * ordering AND from eligibility.
204
+ *
205
+ * Returns the list of valid `(position, felt)` pairs. Empty if none are
206
+ * eligible (verifier should reject the Mode B presentation in that case).
207
+ */
208
+ function collectAnonCredsRevealedFelts(options, credDefId) {
209
+ const proof = options.proof;
210
+ const identifiers = Array.isArray(proof?.identifiers) ? proof.identifiers : [];
211
+ const revealedAttrs = proof?.requested_proof?.revealed_attrs ?? {};
212
+ const revealedAttrGroups = proof?.requested_proof?.revealed_attr_groups ?? {};
213
+ const requested = options.proofRequest?.requested_attributes ?? {};
214
+ const credDef = options.credentialDefinitions?.[credDefId];
215
+ if (!credDef) return [];
216
+ const schema = options.schemas?.[credDef.schemaId];
217
+ if (!schema) return [];
218
+ const reserved = new Set([KANON_CRED_ID_ATTRIBUTE$1, KANON_ZK_SIG_ATTRIBUTE]);
219
+ const sortedDomainNames = [...schema.attrNames].filter((n) => !reserved.has(n)).sort();
220
+ const positionOf = (name) => sortedDomainNames.indexOf(name);
221
+ const out = [];
222
+ const isForCredDef = (subProofIndex) => identifiers[subProofIndex]?.cred_def_id === credDefId;
223
+ for (const [ref, value] of Object.entries(revealedAttrs)) {
224
+ const subProofIndex = value.sub_proof_index;
225
+ if (!isForCredDef(subProofIndex)) continue;
226
+ const name = requested[ref]?.name;
227
+ if (!name || reserved.has(name)) continue;
228
+ const position = positionOf(name);
229
+ if (position < 0) continue;
230
+ const raw = value?.raw;
231
+ if (typeof raw !== "string") continue;
232
+ out.push({
233
+ position,
234
+ felt: attrValueToFelt(raw)
235
+ });
236
+ }
237
+ for (const [ref, group] of Object.entries(revealedAttrGroups)) {
238
+ const subProofIndex = group.sub_proof_index;
239
+ if (!isForCredDef(subProofIndex)) continue;
240
+ const meta = requested[ref];
241
+ const names = Array.isArray(meta?.names) ? meta.names : [];
242
+ const values = group?.values ?? {};
243
+ for (const name of names) {
244
+ if (reserved.has(name)) continue;
245
+ const position = positionOf(name);
246
+ if (position < 0) continue;
247
+ const raw = values[name]?.raw;
248
+ if (typeof raw !== "string") continue;
249
+ out.push({
250
+ position,
251
+ felt: attrValueToFelt(raw)
252
+ });
253
+ }
254
+ }
255
+ return out;
256
+ }
257
+ /**
258
+ * `true` iff the verifier declared a referent in the proof request that
259
+ * targets `kanonCredId` — either by attribute name or via the
260
+ * `kanon_<credDefId>_credId` referent pattern. Used to gate the Mode A
261
+ * status-registry check: if the verifier didn't ask for `kanonCredId`,
262
+ * Mode A is skipped (the verifier opted out).
263
+ */
264
+ function proofRequestHasKanonCredIdReferent(options) {
265
+ const requested = options.proofRequest?.requested_attributes ?? {};
266
+ for (const [referent, meta] of Object.entries(requested)) {
267
+ if (!meta) continue;
268
+ if ((meta.name ? [meta.name] : Array.isArray(meta.names) ? meta.names : []).includes(KANON_CRED_ID_ATTRIBUTE$1)) return true;
269
+ if (KANON_REFERENT_PATTERN.test(referent)) return true;
270
+ }
271
+ return false;
272
+ }
273
+ /**
274
+ * Walks an AnonCreds proof for revealed `kanonCredId` attributes and pairs each
275
+ * with the corresponding cred_def_id from `proof.identifiers`.
276
+ */
277
+ function collectKanonCredentialIdentifiers(options) {
278
+ const out = [];
279
+ const proof = options.proof;
280
+ const identifiers = Array.isArray(proof?.identifiers) ? proof.identifiers : [];
281
+ const revealed = proof?.requested_proof?.revealed_attrs ?? {};
282
+ const revealedGroups = proof?.requested_proof?.revealed_attr_groups ?? {};
283
+ const requestedAttrs = options.proofRequest?.requested_attributes ?? {};
284
+ const pickByReferent = (referent) => {
285
+ const meta = requestedAttrs[referent];
286
+ if (!meta) return KANON_REFERENT_PATTERN.test(referent) ? KANON_CRED_ID_ATTRIBUTE$1 : void 0;
287
+ if ((meta.name ? [meta.name] : Array.isArray(meta.names) ? meta.names : []).find((n) => n === KANON_CRED_ID_ATTRIBUTE$1)) return KANON_CRED_ID_ATTRIBUTE$1;
288
+ return KANON_REFERENT_PATTERN.test(referent) ? KANON_CRED_ID_ATTRIBUTE$1 : void 0;
289
+ };
290
+ for (const [referent, value] of Object.entries(revealed)) {
291
+ if (pickByReferent(referent) !== KANON_CRED_ID_ATTRIBUTE$1) continue;
292
+ const identifier = identifiers[value.sub_proof_index];
293
+ if (!identifier?.cred_def_id) continue;
294
+ out.push({
295
+ credDefId: identifier.cred_def_id,
296
+ credId: String(value.raw)
297
+ });
298
+ }
299
+ for (const [referent, group] of Object.entries(revealedGroups)) {
300
+ const meta = requestedAttrs[referent];
301
+ if (!(Array.isArray(meta?.names) ? meta.names : []).includes(KANON_CRED_ID_ATTRIBUTE$1) && !KANON_REFERENT_PATTERN.test(referent)) continue;
302
+ const identifier = identifiers[group.sub_proof_index];
303
+ const raw = (group.values ?? {})[KANON_CRED_ID_ATTRIBUTE$1]?.raw;
304
+ if (!identifier?.cred_def_id || raw === void 0) continue;
305
+ out.push({
306
+ credDefId: identifier.cred_def_id,
307
+ credId: String(raw)
308
+ });
309
+ }
310
+ return out;
311
+ }
312
+ function collectKanonCredentialIdentifiersFromW3c(options) {
313
+ const out = [];
314
+ const presentation = options.presentation;
315
+ const vcs = Array.isArray(presentation?.verifiableCredential) ? presentation.verifiableCredential : presentation?.verifiableCredential ? [presentation.verifiableCredential] : [];
316
+ for (const vc of vcs) {
317
+ const subject = vc?.credentialSubject;
318
+ const credDefId = vc?.credentialSchema?.id ?? vc?.credentialSchema?.[0]?.id ?? vc?.credentialDefinitionId;
319
+ const credId = subject?.[KANON_CRED_ID_ATTRIBUTE$1] ?? subject?.kanonCredId;
320
+ if (credDefId && credId) out.push({
321
+ credDefId: String(credDefId),
322
+ credId: String(credId)
323
+ });
324
+ }
325
+ return out;
326
+ }
327
+
328
+ //#endregion
329
+ export { KanonWrappedAnonCredsVerifierService, OriginalAnonCredsVerifierServiceSymbol };
330
+ //# sourceMappingURL=KanonWrappedAnonCredsVerifierService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonWrappedAnonCredsVerifierService.js","names":["TIER_ZK_SNARK","KANON_CRED_ID_ATTRIBUTE","kanonCredIdHash"],"sources":["../../../src/anoncreds/services/KanonWrappedAnonCredsVerifierService.ts"],"sourcesContent":["import type {\n AnonCredsVerifierService,\n VerifyProofOptions,\n VerifyW3cPresentationOptions,\n} from '@credo-ts/anoncreds'\nimport type { AgentContext } from '@credo-ts/core'\n\nimport { attrValueToFelt, BN254_SCALAR_FIELD, decodeKanonZkProofAttr, KANON_ZK_SIG_ATTRIBUTE } from '@ajna-inc/kanon-sdk'\nimport { inject, injectable } from '@credo-ts/core'\n\nimport { KanonClientService } from '../../ledger'\nimport { KANON_CRED_ID_ATTRIBUTE, kanonCredIdHash } from '../utils/credIdHash'\nimport {\n augmentProofRequestForKanon,\n credDefIdToBytes32,\n kanonZkProofReferent,\n} from './KanonWrappedAnonCredsHolderService'\n\nconst TIER_ZK_SNARK = 0b10\n\n/**\n * Injection token used by {@link KanonModule} to register the original\n * `AnonCredsRsVerifierService` so the {@link KanonWrappedAnonCredsVerifierService}\n * can inject it without pulling in a deep `@credo-ts/anoncreds/build/...` import.\n *\n * The module registers the original verifier under this symbol, then overrides\n * the public `AnonCredsVerifierServiceSymbol` binding with the wrapper.\n */\nexport const OriginalAnonCredsVerifierServiceSymbol = Symbol('OriginalAnonCredsVerifierService')\n\n/**\n * Wraps Credo's default `AnonCredsVerifierService` so that, after the standard\n * AnonCreds proof verifies, the verifier additionally checks the on-chain\n * `AnonCredsStatusRegistry` for revocation. Both checks must pass.\n *\n * Privacy model: the credential schema must include the canonical `kanonCredId`\n * attribute and the verifier proof request must mark it as revealed. The verifier\n * extracts the disclosed value, hashes it with `kanonCredIdHash`, and looks up\n * the (credDefId, credIdHash) status.\n *\n * If no AnonCredsStatusRegistry is configured on the Kanon module, this wrapper\n * skips the on-chain check and returns whatever the inner verifier returned —\n * useful for tests and for credentials not under kanon governance.\n */\n@injectable()\nexport class KanonWrappedAnonCredsVerifierService implements AnonCredsVerifierService {\n public constructor(\n @inject(OriginalAnonCredsVerifierServiceSymbol) private readonly inner: AnonCredsVerifierService,\n private readonly ledgerService: KanonClientService\n ) {}\n\n public async verifyProof(agentContext: AgentContext, options: VerifyProofOptions): Promise<boolean> {\n // Mode B is OPT-IN per presentation:\n //\n // - If THIS verifier declared the `kanon_<credDefId>_zkProof` referent in\n // the proof request, the holder (if Kanon-aware) injected the SNARK\n // proof; we delegate to `inner.verifyProof` unchanged and then\n // additionally check the SNARK on chain.\n //\n // - If THIS verifier sent a vanilla proof request (no kanon referent),\n // we skip the SNARK check — the wire-format presentation is a plain\n // AnonCreds proof that any AnonCreds verifier would accept, and we\n // have nothing to validate against. This preserves interop with\n // legacy verifiers and matches the Mode A status-registry pattern\n // (also opt-in).\n //\n // Either way the AnonCreds CL signature is checked unchanged.\n const modeBCredDefs = await this.collectModeBCredDefIds(agentContext, options)\n\n const innerResult = await this.inner.verifyProof(agentContext, options)\n if (!innerResult) return false\n\n // ── Mode B: on-chain SNARK check for every Tier-2 credDef the verifier\n // asked the holder to prove non-revocation for ──\n const modeBOk = await this.verifyModeBProofs(agentContext, options, modeBCredDefs)\n if (!modeBOk) return false\n\n if (!this.ledgerService.hasAnonCredsStatusRegistry()) {\n agentContext.config.logger.debug(\n 'KanonWrappedAnonCredsVerifierService: status registry not configured; skipping on-chain revocation check'\n )\n return true\n }\n\n // Mode A is opt-in per-presentation, same as Mode B. The signal is that\n // the verifier declared a `kanonCredId` referent in the proof request —\n // either with `name: kanonCredId` or via the `kanon_*_credId` referent\n // pattern produced by `buildKanonProofRequest`. If the verifier did not\n // ask for it, we skip the on-chain status lookup. This matters because:\n //\n // - Mode-B-only credentials don't disclose `kanonCredId` in their\n // proofs. Without the gate, this wrapper would reject every valid\n // Mode B presentation when a status registry happens to be wired up.\n //\n // - Verifiers that don't want Mode A revocation checks (e.g. test or\n // read-only flows) shouldn't be forced to pay for them.\n if (!proofRequestHasKanonCredIdReferent(options)) {\n agentContext.config.logger.debug(\n `KanonWrappedAnonCredsVerifierService: proof request did not declare a ${KANON_CRED_ID_ATTRIBUTE} referent; skipping Mode A revocation check`\n )\n return true\n }\n\n const checks = collectKanonCredentialIdentifiers(options)\n if (checks.length === 0) {\n // Verifier declared `kanonCredId` but the holder revealed none. This\n // is the suspicious case the original wrapper was trying to detect:\n // the verifier asked but didn't get an answer.\n agentContext.config.logger.warn(\n `KanonWrappedAnonCredsVerifierService: no disclosed ${KANON_CRED_ID_ATTRIBUTE} attribute found; cannot verify revocation status — rejecting proof`\n )\n return false\n }\n\n for (const { credDefId, credId } of checks) {\n const credIdHash = kanonCredIdHash(credId)\n const revoked = await this.ledgerService.isCredentialRevokedOnStatus(credDefId, credIdHash)\n if (revoked) {\n agentContext.config.logger.debug(\n `KanonWrappedAnonCredsVerifierService: credential ${credId} is revoked on-chain under credDef ${credDefId}`\n )\n return false\n }\n }\n return true\n }\n\n /**\n * Verify the Mode B SNARK proof carried by each Tier-2 credDef in the\n * presentation.\n *\n * For every credDef referenced in `proof.identifiers` whose on-chain\n * policyMask includes `TIER_ZK_SNARK`, we look for\n * `proof.requested_proof.self_attested_attrs[kanon_<credDefId>_zkProof]`,\n * decode it, and submit to `MerkleStateRegistry.verifyZKMembership`. Any\n * missing or rejected proof fails the whole presentation.\n *\n * Mode A-only credDefs are unaffected — their presentations don't carry a\n * `kanonZkProof` referent and this check is a no-op for them.\n */\n /**\n * Scan `proof.identifiers` for credDefs that satisfy BOTH:\n *\n * 1. On-chain policyMask includes `TIER_ZK_SNARK` (the credDef opted into\n * Mode B at registration).\n * 2. This verifier's proof request DECLARED the\n * `kanon_<credDefId>_zkProof` referent (the verifier opted in to\n * checking it here).\n *\n * Both conditions must hold — Mode B is opt-in per-verifier-per-request.\n */\n private async collectModeBCredDefIds(\n agentContext: AgentContext,\n options: VerifyProofOptions\n ): Promise<string[]> {\n // biome-ignore lint/suspicious/noExplicitAny: AnonCreds proof JSON is permissive\n const proof = options.proof as any\n // biome-ignore lint/suspicious/noExplicitAny: identifiers is a permissive payload\n const identifiers: any[] = Array.isArray(proof?.identifiers) ? proof.identifiers : []\n const requestedAttrs = ((options.proofRequest as { requested_attributes?: Record<string, unknown> })\n ?.requested_attributes ?? {}) as Record<string, unknown>\n const out: string[] = []\n const seen = new Set<string>()\n for (const id of identifiers) {\n const credDefId = id?.cred_def_id\n if (typeof credDefId !== 'string' || seen.has(credDefId)) continue\n seen.add(credDefId)\n const mask = await this.getPolicyMask(agentContext, credDefId)\n if ((mask & TIER_ZK_SNARK) === 0) continue\n // Opt-in: verifier must have declared the kanon referent. Otherwise we\n // treat the credential as a standard AnonCreds presentation.\n if (!(kanonZkProofReferent(credDefId) in requestedAttrs)) continue\n out.push(credDefId)\n }\n return out\n }\n\n private async verifyModeBProofs(\n agentContext: AgentContext,\n options: VerifyProofOptions,\n modeBCredDefs: string[]\n ): Promise<boolean> {\n if (modeBCredDefs.length === 0) return true\n // biome-ignore lint/suspicious/noExplicitAny: AnonCreds proof JSON is permissive\n const proof = options.proof as any\n // biome-ignore lint/suspicious/noExplicitAny: self_attested_attrs is permissive\n const selfAttested: Record<string, string> = proof?.requested_proof?.self_attested_attrs ?? {}\n\n // The proof-request nonce IS the SNARK challenge — the holder wrapper\n // derives `challenge = uint256(nonce) mod p` and feeds it as\n // `publicSignals[2]`. AnonCreds already binds the nonce to this\n // exchange (freshness, anti-replay), so reusing it is exactly the\n // property we need: a SNARK proof from a previous exchange has a\n // different `publicSignals[2]` and will not match the current nonce.\n const nonceRaw = (options.proofRequest as { nonce?: string })?.nonce\n if (typeof nonceRaw !== 'string' || nonceRaw.length === 0) {\n agentContext.config.logger.warn(\n 'KanonWrappedAnonCredsVerifierService: proof request missing nonce; cannot bind Mode B challenge — rejecting'\n )\n return false\n }\n const expectedChallenge = BigInt(nonceRaw) % BN254_SCALAR_FIELD\n\n for (const credDefId of modeBCredDefs) {\n const referent = kanonZkProofReferent(credDefId)\n const encoded = selfAttested[referent]\n if (typeof encoded !== 'string' || encoded.length === 0) {\n agentContext.config.logger.warn(\n `KanonWrappedAnonCredsVerifierService: Mode B credDef ${credDefId} requires ${referent} self-attested attribute; not found in proof — rejecting`\n )\n return false\n }\n let wire: ReturnType<typeof decodeKanonZkProofAttr>\n try {\n wire = decodeKanonZkProofAttr(encoded)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n agentContext.config.logger.warn(\n `KanonWrappedAnonCredsVerifierService: failed to decode ${referent}: ${message} — rejecting`\n )\n return false\n }\n // Challenge binding: `publicSignals[2]` MUST equal the proof-request\n // nonce reduced mod p. Without this, a SNARK from a previous exchange\n // would replay successfully — `verifyZKMembership` checks the recent\n // root window but not the challenge.\n const providedChallenge = BigInt(wire.publicSignals[2])\n if (providedChallenge !== expectedChallenge) {\n agentContext.config.logger.warn(\n `KanonWrappedAnonCredsVerifierService: Mode B challenge mismatch for ${credDefId} — expected=${expectedChallenge}, got=${providedChallenge} (possible replay) — rejecting`\n )\n return false\n }\n // Disclosed-attribute binding. The SNARK's `publicSignals[5]/[6]` are\n // `(disclosedIndex, disclosedValue)` for the credential's domain\n // attributes (in canonical sort order). For the SNARK to add meaning\n // beyond \"non-revocation\", we require BOTH coordinates to match a\n // SPECIFIC AnonCreds-revealed attribute:\n //\n // - `publicSignals[5]` (position) MUST equal the canonical-sort\n // position of one of the revealed attribute names.\n // - `publicSignals[6]` (felt) MUST equal `attrValueToFelt(rawValue)`\n // of that SAME attribute.\n //\n // Without the position constraint, a holder presenting two attributes\n // with the same felt value (e.g. both equal \"25\") could SNARK-bind to\n // attribute Y while AnonCreds revealed attribute X — the verifier\n // would accept both as consistent even though they prove different\n // facts. Requiring the matching pair closes that gap.\n const providedDisclosedIndex = Number(BigInt(wire.publicSignals[5]))\n const providedDisclosedFelt = BigInt(wire.publicSignals[6])\n const matchingRevealed = collectAnonCredsRevealedFelts(options, credDefId)\n if (matchingRevealed.length === 0) {\n agentContext.config.logger.warn(\n `KanonWrappedAnonCredsVerifierService: Mode B credDef ${credDefId} requires a revealed AnonCreds attribute the SNARK can bind to, but the proof has none — rejecting`\n )\n return false\n }\n const hasMatchingPair = matchingRevealed.some(\n (p) => p.position === providedDisclosedIndex && p.felt === providedDisclosedFelt\n )\n if (!hasMatchingPair) {\n agentContext.config.logger.warn(\n `KanonWrappedAnonCredsVerifierService: Mode B disclosed (idx=${providedDisclosedIndex}, val=${providedDisclosedFelt}) for ${credDefId} does not match any AnonCreds-revealed (position, felt) pair — rejecting`\n )\n return false\n }\n const merkleStateRegistry = this.ledgerService.contracts.merkleStateRegistry as unknown as {\n verifyZKMembership: (\n credDefId: string,\n proof: string,\n publicSignals: string[]\n ) => Promise<boolean>\n }\n let ok = false\n try {\n ok = await merkleStateRegistry.verifyZKMembership(credDefIdToBytes32(credDefId), wire.proofBytes, wire.publicSignals)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n agentContext.config.logger.warn(\n `KanonWrappedAnonCredsVerifierService: verifyZKMembership(${credDefId}) reverted: ${message}`\n )\n return false\n }\n if (!ok) {\n agentContext.config.logger.warn(\n `KanonWrappedAnonCredsVerifierService: Mode B proof for ${credDefId} rejected on chain`\n )\n return false\n }\n agentContext.config.logger.debug(\n `KanonWrappedAnonCredsVerifierService: Mode B proof for ${credDefId} verified on chain`\n )\n }\n return true\n }\n\n private readonly policyCache = new Map<string, number>()\n\n private async getPolicyMask(agentContext: AgentContext, credDefId: string): Promise<number> {\n const cached = this.policyCache.get(credDefId)\n if (cached !== undefined) return cached\n try {\n // credDef on-chain key is the bytes32 resourceId hash (keccak256), not\n // the raw DID URL — otherwise this throws and silently defaults to Mode\n // A, skipping the on-chain non-revocation check.\n const mask = await this.ledgerService.client.getCredDefPolicy(credDefIdToBytes32(credDefId))\n this.policyCache.set(credDefId, mask)\n return mask\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n agentContext.config.logger.debug(\n `KanonWrappedAnonCredsVerifierService: getCredDefPolicy(${credDefId}) failed (${message}); defaulting to Mode A only`\n )\n this.policyCache.set(credDefId, 0b01)\n return 0b01\n }\n }\n\n public async verifyW3cPresentation(\n agentContext: AgentContext,\n options: VerifyW3cPresentationOptions\n ): Promise<boolean> {\n const innerResult = await this.inner.verifyW3cPresentation(agentContext, options)\n if (!innerResult) return false\n\n if (!this.ledgerService.hasAnonCredsStatusRegistry()) return true\n\n const checks = collectKanonCredentialIdentifiersFromW3c(options)\n if (checks.length === 0) {\n agentContext.config.logger.warn(\n `KanonWrappedAnonCredsVerifierService: no disclosed ${KANON_CRED_ID_ATTRIBUTE} found in W3C presentation; rejecting`\n )\n return false\n }\n\n for (const { credDefId, credId } of checks) {\n const credIdHash = kanonCredIdHash(credId)\n const revoked = await this.ledgerService.isCredentialRevokedOnStatus(credDefId, credIdHash)\n if (revoked) return false\n }\n return true\n }\n}\n\ninterface KanonCredentialIdentifier {\n credDefId: string\n credId: string\n}\n\n/**\n * Matches the referent naming convention produced by `buildKanonProofRequest`,\n * which scopes the disclosed `kanonCredId` per credDef as `kanon_<credDefId>_credId`.\n * The verifier accepts either the simple `kanonCredId` attribute name or any\n * referent matching this pattern, so callers can use the helper or hand-craft\n * the request.\n */\nconst KANON_REFERENT_PATTERN = /^kanon_.+_credId$/\n\n/**\n * One `(position, value)` pair from an AnonCreds-revealed attribute. The\n * position is the canonical-sort index of the attribute *name* within the\n * credDef's domain attributes (the SDK-reserved names excluded). The value\n * is `attrValueToFelt` of the raw revealed value — same felt the holder\n * passed to `publicSignals[6]`.\n *\n * The verifier requires `(publicSignals[5], publicSignals[6])` to equal\n * exactly one of these pairs. That binds the SNARK's disclosed slot to a\n * SPECIFIC AnonCreds-revealed attribute, not just any value that happens\n * to match — defends against collision-style abuse where two attributes\n * share the same felt value and a holder could otherwise claim to prove\n * one while AnonCreds revealed the other.\n */\ninterface RevealedFeltPair {\n position: number\n felt: bigint\n}\n\n/**\n * Collect AnonCreds-revealed (position, felt) pairs for `credDefId`.\n *\n * Walks `proof.requested_proof.revealed_attrs` (and `revealed_attr_groups`)\n * matching against `proof.identifiers[sub_proof_index].cred_def_id` to find\n * entries that belong to the credDef. For each match, we look up the\n * attribute name in the canonical (lexicographic) order of the credDef's\n * schema attrNames — same order the holder + leaf use. SDK-reserved names\n * (`kanonCredId`, `kanonZkSig`) are excluded both from the canonical\n * ordering AND from eligibility.\n *\n * Returns the list of valid `(position, felt)` pairs. Empty if none are\n * eligible (verifier should reject the Mode B presentation in that case).\n */\nfunction collectAnonCredsRevealedFelts(options: VerifyProofOptions, credDefId: string): RevealedFeltPair[] {\n // biome-ignore lint/suspicious/noExplicitAny: AnonCreds proof JSON is permissive\n const proof = options.proof as any\n // biome-ignore lint/suspicious/noExplicitAny: identifiers payload is permissive\n const identifiers: any[] = Array.isArray(proof?.identifiers) ? proof.identifiers : []\n // biome-ignore lint/suspicious/noExplicitAny: revealed_attrs payload is permissive\n const revealedAttrs: Record<string, any> = proof?.requested_proof?.revealed_attrs ?? {}\n // biome-ignore lint/suspicious/noExplicitAny: revealed_attr_groups payload is permissive\n const revealedAttrGroups: Record<string, any> = proof?.requested_proof?.revealed_attr_groups ?? {}\n // biome-ignore lint/suspicious/noExplicitAny: proofRequest is permissive\n const requested: Record<string, any> = options.proofRequest?.requested_attributes ?? {}\n\n // Map credDefId -> schemaId via the credentialDefinitions block, then\n // schemaId -> attrNames via the schemas block. Both blocks are supplied\n // by the AnonCreds caller (they're required for verifyProof anyway).\n const credDef = options.credentialDefinitions?.[credDefId]\n if (!credDef) return []\n const schema = options.schemas?.[credDef.schemaId]\n if (!schema) return []\n const reserved = new Set([KANON_CRED_ID_ATTRIBUTE, KANON_ZK_SIG_ATTRIBUTE])\n // Canonical position = index in lexicographic sort of NON-reserved attrNames.\n const sortedDomainNames = [...schema.attrNames]\n .filter((n) => !reserved.has(n))\n .sort()\n const positionOf = (name: string): number => sortedDomainNames.indexOf(name)\n\n const out: RevealedFeltPair[] = []\n\n const isForCredDef = (subProofIndex: number) => identifiers[subProofIndex]?.cred_def_id === credDefId\n\n for (const [ref, value] of Object.entries(revealedAttrs)) {\n const subProofIndex: number = value.sub_proof_index\n if (!isForCredDef(subProofIndex)) continue\n const meta = requested[ref]\n const name = meta?.name as string | undefined\n if (!name || reserved.has(name)) continue\n const position = positionOf(name)\n if (position < 0) continue\n const raw = value?.raw\n if (typeof raw !== 'string') continue\n out.push({ position, felt: attrValueToFelt(raw) })\n }\n for (const [ref, group] of Object.entries(revealedAttrGroups)) {\n const subProofIndex: number = group.sub_proof_index\n if (!isForCredDef(subProofIndex)) continue\n const meta = requested[ref]\n const names: string[] = Array.isArray(meta?.names) ? meta.names : []\n const values = group?.values ?? {}\n for (const name of names) {\n if (reserved.has(name)) continue\n const position = positionOf(name)\n if (position < 0) continue\n const raw = values[name]?.raw\n if (typeof raw !== 'string') continue\n out.push({ position, felt: attrValueToFelt(raw) })\n }\n }\n return out\n}\n\n/**\n * `true` iff the verifier declared a referent in the proof request that\n * targets `kanonCredId` — either by attribute name or via the\n * `kanon_<credDefId>_credId` referent pattern. Used to gate the Mode A\n * status-registry check: if the verifier didn't ask for `kanonCredId`,\n * Mode A is skipped (the verifier opted out).\n */\nfunction proofRequestHasKanonCredIdReferent(options: VerifyProofOptions): boolean {\n // biome-ignore lint/suspicious/noExplicitAny: proofRequest is a permissive payload\n const requested: Record<string, any> = options.proofRequest?.requested_attributes ?? {}\n for (const [referent, meta] of Object.entries(requested)) {\n if (!meta) continue\n const candidates: string[] = (meta as { name?: string }).name\n ? [(meta as { name: string }).name]\n : Array.isArray((meta as { names?: string[] }).names)\n ? (meta as { names: string[] }).names\n : []\n if (candidates.includes(KANON_CRED_ID_ATTRIBUTE)) return true\n if (KANON_REFERENT_PATTERN.test(referent)) return true\n }\n return false\n}\n\n/**\n * Walks an AnonCreds proof for revealed `kanonCredId` attributes and pairs each\n * with the corresponding cred_def_id from `proof.identifiers`.\n */\nfunction collectKanonCredentialIdentifiers(options: VerifyProofOptions): KanonCredentialIdentifier[] {\n const out: KanonCredentialIdentifier[] = []\n // biome-ignore lint/suspicious/noExplicitAny: AnonCreds proof JSON is permissive\n const proof = options.proof as any\n // biome-ignore lint/suspicious/noExplicitAny: cred_def_id lives on a permissive identifier struct\n const identifiers: any[] = Array.isArray(proof?.identifiers) ? proof.identifiers : []\n // biome-ignore lint/suspicious/noExplicitAny: revealed_attrs is a permissive map\n const revealed: Record<string, any> = proof?.requested_proof?.revealed_attrs ?? {}\n // biome-ignore lint/suspicious/noExplicitAny: revealed_attr_groups is a permissive map\n const revealedGroups: Record<string, any> = proof?.requested_proof?.revealed_attr_groups ?? {}\n // biome-ignore lint/suspicious/noExplicitAny: proofRequest carries permissive attribute metadata\n const requestedAttrs: Record<string, any> = options.proofRequest?.requested_attributes ?? {}\n\n const pickByReferent = (referent: string): string | undefined => {\n const meta = requestedAttrs[referent]\n if (!meta) {\n // Referent has no metadata in the proof request; fall back to naming convention.\n return KANON_REFERENT_PATTERN.test(referent) ? KANON_CRED_ID_ATTRIBUTE : undefined\n }\n const candidates: string[] = meta.name ? [meta.name] : Array.isArray(meta.names) ? meta.names : []\n if (candidates.find((n) => n === KANON_CRED_ID_ATTRIBUTE)) return KANON_CRED_ID_ATTRIBUTE\n // Accept the referent naming pattern as a fallback (`kanon_<credDefId>_credId`).\n return KANON_REFERENT_PATTERN.test(referent) ? KANON_CRED_ID_ATTRIBUTE : undefined\n }\n\n for (const [referent, value] of Object.entries(revealed)) {\n const attrName = pickByReferent(referent)\n if (attrName !== KANON_CRED_ID_ATTRIBUTE) continue\n // biome-ignore lint/suspicious/noExplicitAny: sub_proof_index is on permissive payload\n const subProofIndex: number = (value as any).sub_proof_index\n const identifier = identifiers[subProofIndex]\n if (!identifier?.cred_def_id) continue\n out.push({\n credDefId: identifier.cred_def_id,\n // biome-ignore lint/suspicious/noExplicitAny: raw is on permissive payload\n credId: String((value as any).raw),\n })\n }\n\n for (const [referent, group] of Object.entries(revealedGroups)) {\n const meta = requestedAttrs[referent]\n const names: string[] = Array.isArray(meta?.names) ? meta.names : []\n if (!names.includes(KANON_CRED_ID_ATTRIBUTE) && !KANON_REFERENT_PATTERN.test(referent)) continue\n // biome-ignore lint/suspicious/noExplicitAny: sub_proof_index is on permissive payload\n const subProofIndex: number = (group as any).sub_proof_index\n const identifier = identifiers[subProofIndex]\n // biome-ignore lint/suspicious/noExplicitAny: values map is permissive\n const values = (group as any).values ?? {}\n const raw = values[KANON_CRED_ID_ATTRIBUTE]?.raw\n if (!identifier?.cred_def_id || raw === undefined) continue\n out.push({ credDefId: identifier.cred_def_id, credId: String(raw) })\n }\n\n return out\n}\n\nfunction collectKanonCredentialIdentifiersFromW3c(\n options: VerifyW3cPresentationOptions\n): KanonCredentialIdentifier[] {\n const out: KanonCredentialIdentifier[] = []\n // biome-ignore lint/suspicious/noExplicitAny: presentation is a permissive W3C VP\n const presentation: any = options.presentation as any\n // biome-ignore lint/suspicious/noExplicitAny: verifiableCredential entries are permissive\n const vcs: any[] = Array.isArray(presentation?.verifiableCredential)\n ? presentation.verifiableCredential\n : presentation?.verifiableCredential\n ? [presentation.verifiableCredential]\n : []\n for (const vc of vcs) {\n const subject = vc?.credentialSubject\n const credDefId = vc?.credentialSchema?.id ?? vc?.credentialSchema?.[0]?.id ?? vc?.credentialDefinitionId\n const credId = subject?.[KANON_CRED_ID_ATTRIBUTE] ?? subject?.kanonCredId\n if (credDefId && credId) {\n out.push({ credDefId: String(credDefId), credId: String(credId) })\n }\n }\n return out\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAMA,kBAAgB;;;;;;;;;AAUtB,MAAa,yCAAyC,OAAO,mCAAmC;AAiBzF,iDAAM,qCAAyE;CACpF,AAAO,YACL,AAAiE,OACjE,AAAiB,eACjB;EAFiE;EAChD;OAyPF,8BAAc,IAAI,KAAqB;;CAtPxD,MAAa,YAAY,cAA4B,SAA+C;EAgBlG,MAAM,gBAAgB,MAAM,KAAK,uBAAuB,cAAc,QAAQ;AAG9E,MAAI,CADgB,MAAM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AAE;AACR,MAAK,MAAM,MAAM,KAAK;EACpB,MAAM,UAAU,IAAI;EACpB,MAAM,YAAY,IAAI,kBAAkB,MAAM,IAAI,mBAAmB,IAAI,MAAM,IAAI;EACnF,MAAM,SAAS,UAAUA,8BAA4B,SAAS;AAC9D,MAAI,aAAa,OACf,KAAI,KAAK;GAAE,WAAW,OAAO,UAAU;GAAE,QAAQ,OAAO,OAAO;GAAE,CAAC;;AAGtE,QAAO"}
@@ -0,0 +1,2 @@
1
+ import { KANON_CRED_ID_ATTRIBUTE, kanonCredIdHash } from "@ajna-inc/kanon-sdk/anoncreds";
2
+ export { KANON_CRED_ID_ATTRIBUTE, kanonCredIdHash };
@@ -0,0 +1,3 @@
1
+ import { KANON_CRED_ID_ATTRIBUTE, kanonCredIdHash } from "@ajna-inc/kanon-sdk/anoncreds";
2
+
3
+ export { KANON_CRED_ID_ATTRIBUTE, kanonCredIdHash };
@@ -0,0 +1,47 @@
1
+ import { KanonModuleConfig } from "../KanonModuleConfig.js";
2
+ import { KanonClientService } from "../ledger/KanonClientService.js";
3
+ import "../ledger/index.js";
4
+ import { AgentContext, DidCreateOptions, DidCreateResult, DidDeactivateOptions, DidDeactivateResult, DidOperationStateActionBase, DidRegistrar, DidUpdateOptions, DidUpdateResult } from "@credo-ts/core";
5
+
6
+ //#region src/dids/KanonDidRegistrar.d.ts
7
+ interface KanonDidServiceOptions {
8
+ id: string;
9
+ type: string;
10
+ serviceEndpoint: string;
11
+ }
12
+ /**
13
+ * Mints + on-chain registers did:kanon DIDs against the kanon `DIDRegistry`.
14
+ * Issuer DIDs are org-scoped (`did:kanon:org:<orgId>`); holder DIDs are
15
+ * user-scoped (`did:kanon:user:0x<hash>`). Each DID gets a fresh Ed25519 key
16
+ * minted in the agent KMS and registered as its first verification method.
17
+ */
18
+ declare class KanonDidRegistrar implements DidRegistrar {
19
+ private clientService;
20
+ private config;
21
+ readonly supportedMethods: string[];
22
+ constructor(clientService: KanonClientService, config: KanonModuleConfig);
23
+ create(agentContext: AgentContext, options: KanonDidCreateOptions): Promise<DidCreateResult<DidOperationStateActionBase>>;
24
+ update(_agentContext: AgentContext, _options: KanonDidUpdateOptions): Promise<DidUpdateResult>;
25
+ deactivate(_agentContext: AgentContext, _options: KanonDidDeactivateOptions): Promise<DidDeactivateResult>;
26
+ }
27
+ interface KanonDidCreateOptions extends DidCreateOptions {
28
+ method: 'kanon';
29
+ /** 'org' (issuer) or 'user' (holder). Defaults to 'org'. */
30
+ scope?: 'org' | 'user';
31
+ /** Org id (bytes32 as 0x<64 hex>) for org-scoped DIDs; falls back to config.issuerOrgId. */
32
+ orgId?: string;
33
+ options?: {
34
+ services?: KanonDidServiceOptions[];
35
+ };
36
+ }
37
+ interface KanonDidUpdateOptions extends DidUpdateOptions {
38
+ method?: 'kanon';
39
+ did: string;
40
+ }
41
+ interface KanonDidDeactivateOptions extends DidDeactivateOptions {
42
+ method: 'kanon';
43
+ did: string;
44
+ }
45
+ //#endregion
46
+ export { KanonDidCreateOptions, KanonDidDeactivateOptions, KanonDidRegistrar, KanonDidServiceOptions, KanonDidUpdateOptions };
47
+ //# sourceMappingURL=KanonDidRegistrar.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonDidRegistrar.d.ts","names":[],"sources":["../../src/dids/KanonDidRegistrar.ts"],"mappings":";;;;;;UA4BiB,sBAAA;EACf,EAAA;EACA,IAAA;EACA,eAAA;AAAA;;;;;;;cAUW,iBAAA,YAA6B,YAAA;EAAA,QAI9B,aAAA;EAAA,QACA,MAAA;EAAA,SAJM,gBAAA;cAGN,aAAA,EAAe,kBAAA,EACf,MAAA,EAAQ,iBAAA;EAGL,MAAA,CACX,YAAA,EAAc,YAAA,EACd,OAAA,EAAS,qBAAA,GACR,OAAA,CAAQ,eAAA,CAAgB,2BAAA;EAmHd,MAAA,CAAO,aAAA,EAAe,YAAA,EAAc,QAAA,EAAU,qBAAA,GAAwB,OAAA,CAAQ,eAAA;EAW9E,UAAA,CACX,aAAA,EAAe,YAAA,EACf,QAAA,EAAU,yBAAA,GACT,OAAA,CAAQ,mBAAA;AAAA;AAAA,UAYI,qBAAA,SAA8B,gBAAA;EAC7C,MAAA;EA3BmC;EA6BnC,KAAA;EA7B2F;EA+B3F,KAAA;EACA,OAAA;IACE,QAAA,GAAW,sBAAA;EAAA;AAAA;AAAA,UAIE,qBAAA,SAA8B,gBAAA;EAC7C,MAAA;EACA,GAAA;AAAA;AAAA,UAGe,yBAAA,SAAkC,oBAAA;EACjD,MAAA;EACA,GAAA;AAAA"}
@@ -0,0 +1,140 @@
1
+ import { __decorate } from "../_virtual/_@oxc-project_runtime@0.112.0/helpers/decorate.js";
2
+ import { KanonModuleConfig } from "../KanonModuleConfig.js";
3
+ import { __decorateMetadata } from "../_virtual/_@oxc-project_runtime@0.112.0/helpers/decorateMetadata.js";
4
+ import { KanonClientService } from "../ledger/KanonClientService.js";
5
+ import "../ledger/index.js";
6
+ import { VerificationMethodType } from "@ajna-inc/kanon-sdk";
7
+ import { DidDocument, DidDocumentRole, DidRecord, DidRepository, Kms, TypedArrayEncoder, injectable } from "@credo-ts/core";
8
+ import { orgDid } from "@ajna-inc/kanon-sdk/anoncreds";
9
+ import { ethers } from "ethers";
10
+
11
+ //#region src/dids/KanonDidRegistrar.ts
12
+ var _ref, _ref2;
13
+ let KanonDidRegistrar = class KanonDidRegistrar {
14
+ constructor(clientService, config) {
15
+ this.clientService = clientService;
16
+ this.config = config;
17
+ this.supportedMethods = ["kanon"];
18
+ }
19
+ async create(agentContext, options) {
20
+ const didRepository = agentContext.dependencyManager.resolve(DidRepository);
21
+ await this.clientService.init();
22
+ const client = this.clientService.client;
23
+ const signer = this.clientService.getSigner();
24
+ const scope = options.scope ?? "org";
25
+ const services = options.options?.services ?? [];
26
+ let userSalt;
27
+ try {
28
+ const { keyId, publicJwk } = await agentContext.dependencyManager.resolve(Kms.KeyManagementApi).createKey({ type: {
29
+ kty: "OKP",
30
+ crv: "Ed25519"
31
+ } });
32
+ const publicKeyBytes = Kms.PublicJwk.fromPublicJwk(publicJwk).publicKey.publicKey;
33
+ const publicKeyBase58 = TypedArrayEncoder.toBase58(publicKeyBytes);
34
+ const publicKeyHex = ethers.hexlify(publicKeyBytes);
35
+ let did;
36
+ if (scope === "org") {
37
+ const orgId = options.orgId ?? this.config.issuerOrgId;
38
+ if (orgId == null) throw new Error("did:kanon: org-scoped DID needs an org id (set issuerOrgId in KanonModuleConfig or pass orgId)");
39
+ did = orgDid(orgId);
40
+ } else if (scope === "user") {
41
+ const u = client.computeUserDid(await signer.getAddress());
42
+ did = u.did;
43
+ userSalt = u.salt;
44
+ } else throw new Error(`did:kanon: unknown scope '${scope}' (use 'org' or 'user')`);
45
+ const kid = `${did}#key-1`;
46
+ const verificationMethods = [{
47
+ id: ethers.keccak256(ethers.toUtf8Bytes(kid)),
48
+ vmType: VerificationMethodType.Ed25519VerificationKey2020,
49
+ publicKey: publicKeyHex
50
+ }];
51
+ const serviceStructs = services.map((svc) => ({
52
+ id: ethers.keccak256(ethers.toUtf8Bytes(svc.id)),
53
+ serviceType: svc.type,
54
+ endpoint: svc.serviceEndpoint
55
+ }));
56
+ if (scope === "org") {
57
+ const orgId = options.orgId ?? this.config.issuerOrgId;
58
+ await client.registerOrgDid(signer, orgId, {
59
+ verificationMethods,
60
+ services: serviceStructs
61
+ });
62
+ } else await client.registerUserDid(signer, userSalt, { verificationMethods });
63
+ const didDocument = new DidDocument({
64
+ id: did,
65
+ context: ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/suites/ed25519-2020/v1"],
66
+ verificationMethod: [{
67
+ id: kid,
68
+ type: "Ed25519VerificationKey2020",
69
+ controller: did,
70
+ publicKeyBase58
71
+ }],
72
+ authentication: [kid],
73
+ assertionMethod: [kid],
74
+ service: serviceStructs.length ? services.map((svc) => ({
75
+ id: svc.id,
76
+ type: svc.type,
77
+ serviceEndpoint: svc.serviceEndpoint
78
+ })) : void 0
79
+ });
80
+ const didRecord = new DidRecord({
81
+ did,
82
+ role: DidDocumentRole.Created,
83
+ didDocument,
84
+ keys: [{
85
+ kmsKeyId: keyId,
86
+ didDocumentRelativeKeyId: "#key-1"
87
+ }],
88
+ tags: {
89
+ method: "kanon",
90
+ role: DidDocumentRole.Created
91
+ }
92
+ });
93
+ await didRepository.save(agentContext, didRecord);
94
+ return {
95
+ didDocumentMetadata: {},
96
+ didRegistrationMetadata: {},
97
+ didState: {
98
+ state: "finished",
99
+ did,
100
+ didDocument,
101
+ secret: options.secret
102
+ }
103
+ };
104
+ } catch (e) {
105
+ return {
106
+ didDocumentMetadata: {},
107
+ didRegistrationMetadata: {},
108
+ didState: {
109
+ state: "failed",
110
+ reason: e instanceof Error ? e.message : String(e)
111
+ }
112
+ };
113
+ }
114
+ }
115
+ async update(_agentContext, _options) {
116
+ return {
117
+ didDocumentMetadata: {},
118
+ didRegistrationMetadata: {},
119
+ didState: {
120
+ state: "failed",
121
+ reason: "did:kanon: update is not supported by this registrar"
122
+ }
123
+ };
124
+ }
125
+ async deactivate(_agentContext, _options) {
126
+ return {
127
+ didDocumentMetadata: {},
128
+ didRegistrationMetadata: {},
129
+ didState: {
130
+ state: "failed",
131
+ reason: "did:kanon: deactivate is not supported by this registrar"
132
+ }
133
+ };
134
+ }
135
+ };
136
+ KanonDidRegistrar = __decorate([injectable(), __decorateMetadata("design:paramtypes", [KanonClientService, KanonModuleConfig])], KanonDidRegistrar);
137
+
138
+ //#endregion
139
+ export { KanonDidRegistrar };
140
+ //# sourceMappingURL=KanonDidRegistrar.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonDidRegistrar.js","names":[],"sources":["../../src/dids/KanonDidRegistrar.ts"],"sourcesContent":["import type {\n AgentContext,\n DidCreateOptions,\n DidCreateResult,\n DidDeactivateOptions,\n DidDeactivateResult,\n DidOperationStateActionBase,\n DidRegistrar,\n DidUpdateOptions,\n DidUpdateResult,\n} from '@credo-ts/core'\n\nimport { VerificationMethodType } from '@ajna-inc/kanon-sdk'\nimport { orgDid } from '@ajna-inc/kanon-sdk/anoncreds'\nimport {\n DidDocument,\n DidDocumentRole,\n DidRecord,\n DidRepository,\n injectable,\n Kms,\n TypedArrayEncoder,\n} from '@credo-ts/core'\nimport { ethers } from 'ethers'\n\nimport { KanonModuleConfig } from '../KanonModuleConfig'\nimport { KanonClientService } from '../ledger'\n\nexport interface KanonDidServiceOptions {\n id: string\n type: string\n serviceEndpoint: string\n}\n\n/**\n * Mints + on-chain registers did:kanon DIDs against the kanon `DIDRegistry`.\n * Issuer DIDs are org-scoped (`did:kanon:org:<orgId>`); holder DIDs are\n * user-scoped (`did:kanon:user:0x<hash>`). Each DID gets a fresh Ed25519 key\n * minted in the agent KMS and registered as its first verification method.\n */\n@injectable()\nexport class KanonDidRegistrar implements DidRegistrar {\n public readonly supportedMethods = ['kanon']\n\n public constructor(\n private clientService: KanonClientService,\n private config: KanonModuleConfig\n ) {}\n\n public async create(\n agentContext: AgentContext,\n options: KanonDidCreateOptions\n ): Promise<DidCreateResult<DidOperationStateActionBase>> {\n const didRepository = agentContext.dependencyManager.resolve(DidRepository)\n // Ensure the address-book-resolved client is built (idempotent).\n await this.clientService.init()\n const client = this.clientService.client\n const signer = this.clientService.getSigner()\n\n const scope = options.scope ?? 'org'\n const services = options.options?.services ?? []\n // For user-scoped DIDs the salt must be generated ONCE and reused at\n // registration — computeUserDid() mints a fresh random salt per call.\n let userSalt: string | undefined\n\n try {\n // Mint an Ed25519 verification key in the agent KMS.\n const kms = agentContext.dependencyManager.resolve(Kms.KeyManagementApi)\n const { keyId, publicJwk } = await kms.createKey({\n type: { kty: 'OKP', crv: 'Ed25519' },\n })\n const publicJwkInstance = Kms.PublicJwk.fromPublicJwk(publicJwk)\n const publicKeyBytes = publicJwkInstance.publicKey.publicKey\n const publicKeyBase58 = TypedArrayEncoder.toBase58(publicKeyBytes)\n const publicKeyHex = ethers.hexlify(publicKeyBytes)\n\n let did: string\n if (scope === 'org') {\n const orgId = options.orgId ?? this.config.issuerOrgId\n if (orgId == null) {\n throw new Error(\n 'did:kanon: org-scoped DID needs an org id (set issuerOrgId in KanonModuleConfig or pass orgId)'\n )\n }\n did = orgDid(orgId)\n } else if (scope === 'user') {\n // Capture BOTH the did and its salt from a SINGLE computeUserDid call so\n // the same salt is reused below — otherwise the on-chain DID (salt #2)\n // would differ from the returned/saved DID (salt #1).\n const u = client.computeUserDid(await signer.getAddress())\n did = u.did\n userSalt = u.salt\n } else {\n throw new Error(`did:kanon: unknown scope '${scope}' (use 'org' or 'user')`)\n }\n\n const kid = `${did}#key-1`\n const vmId = ethers.keccak256(ethers.toUtf8Bytes(kid))\n\n const verificationMethods = [{ id: vmId, vmType: VerificationMethodType.Ed25519VerificationKey2020, publicKey: publicKeyHex }]\n const serviceStructs = services.map((svc) => ({\n id: ethers.keccak256(ethers.toUtf8Bytes(svc.id)),\n serviceType: svc.type,\n endpoint: svc.serviceEndpoint,\n }))\n\n if (scope === 'org') {\n // orgId is a bytes32 value encoded as a 0x<64 hex> string. Any revert\n // from registerOrgDid (e.g. a duplicate DID) propagates and is caught\n // below, surfacing as a `failed` DidCreateResult — never a fake success.\n const orgId = options.orgId ?? (this.config.issuerOrgId as string)\n await client.registerOrgDid(signer, orgId, {\n verificationMethods,\n services: serviceStructs,\n })\n } else {\n await client.registerUserDid(signer, userSalt as string, { verificationMethods })\n }\n\n // Build the W3C DID document we persist locally and return to the caller.\n const didDocument = new DidDocument({\n id: did,\n context: ['https://www.w3.org/ns/did/v1', 'https://w3id.org/security/suites/ed25519-2020/v1'],\n verificationMethod: [\n {\n id: kid,\n type: 'Ed25519VerificationKey2020',\n controller: did,\n publicKeyBase58,\n },\n ],\n authentication: [kid],\n assertionMethod: [kid],\n service: serviceStructs.length\n ? services.map((svc) => ({ id: svc.id, type: svc.type, serviceEndpoint: svc.serviceEndpoint }))\n : undefined,\n })\n\n const didRecord = new DidRecord({\n did,\n role: DidDocumentRole.Created,\n didDocument,\n keys: [{ kmsKeyId: keyId, didDocumentRelativeKeyId: '#key-1' }],\n tags: { method: 'kanon', role: DidDocumentRole.Created },\n })\n await didRepository.save(agentContext, didRecord)\n\n return {\n didDocumentMetadata: {},\n didRegistrationMetadata: {},\n didState: {\n state: 'finished',\n did,\n didDocument,\n secret: options.secret,\n },\n }\n } catch (e) {\n const reason = e instanceof Error ? e.message : String(e)\n return {\n didDocumentMetadata: {},\n didRegistrationMetadata: {},\n didState: { state: 'failed', reason },\n }\n }\n }\n\n public async update(_agentContext: AgentContext, _options: KanonDidUpdateOptions): Promise<DidUpdateResult> {\n return {\n didDocumentMetadata: {},\n didRegistrationMetadata: {},\n didState: {\n state: 'failed',\n reason: 'did:kanon: update is not supported by this registrar',\n },\n }\n }\n\n public async deactivate(\n _agentContext: AgentContext,\n _options: KanonDidDeactivateOptions\n ): Promise<DidDeactivateResult> {\n return {\n didDocumentMetadata: {},\n didRegistrationMetadata: {},\n didState: {\n state: 'failed',\n reason: 'did:kanon: deactivate is not supported by this registrar',\n },\n }\n }\n}\n\nexport interface KanonDidCreateOptions extends DidCreateOptions {\n method: 'kanon'\n /** 'org' (issuer) or 'user' (holder). Defaults to 'org'. */\n scope?: 'org' | 'user'\n /** Org id (bytes32 as 0x<64 hex>) for org-scoped DIDs; falls back to config.issuerOrgId. */\n orgId?: string\n options?: {\n services?: KanonDidServiceOptions[]\n }\n}\n\nexport interface KanonDidUpdateOptions extends DidUpdateOptions {\n method?: 'kanon'\n did: string\n}\n\nexport interface KanonDidDeactivateOptions extends DidDeactivateOptions {\n method: 'kanon'\n did: string\n}\n"],"mappings":";;;;;;;;;;;;AAyCO,8BAAM,kBAA0C;CAGrD,AAAO,YACL,AAAQ,eACR,AAAQ,QACR;EAFQ;EACA;OAJM,mBAAmB,CAAC,QAAQ;;CAO5C,MAAa,OACX,cACA,SACuD;EACvD,MAAM,gBAAgB,aAAa,kBAAkB,QAAQ,cAAc;AAE3E,QAAM,KAAK,cAAc,MAAM;EAC/B,MAAM,SAAS,KAAK,cAAc;EAClC,MAAM,SAAS,KAAK,cA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IACJ,SAAS,CAAC,gCAAgC,mDAAmD;IAC7F,oBAAoB,CAClB;KACE,IAAI;KACJ,MAAM;KACN,YAAY;KACZ;KACD,CACF;IACD,gBAAgB,CAAC,IAAI;IACrB,iBAAiB,CAAC,IAAI;IACtB,SAAS,eAAe,SACpB,SAAS,KAAK,SAAS;KAAE,IAAI,IAAI;KAAI,MAAM,IAAI;KAAM,iBAAiB,IAAI;KAAiB,EAAE,GAC7F;IACL,CAAC;GAEF,MAAM,YAAY,IAAI,UAAU;IAC9B;IACA,MAAM,gBAAgB;IACtB;IACA,MAAM,CAAC;KAAE,UAAU;KAAO,0BAA0B;KAAU,CAAC;IAC/D,MAAM;KAAE,QAAQ;KAAS,MAAM,gBAAgB;KAAS;IACzD,CAAC;AACF,SAAM,cAAc,KAAK,cAAc,UAAU;AAEjD,UAAO;IACL,qBAAqB,EAAE;IACvB,yBAAyB,EAAE;IAC3B,UAAU;KACR,OAAO;KACP;KACA;KACA,QAAQ,QAAQ;KACjB;IACF;WACM,GAAG;AAEV,UAAO;IACL,qBAAqB,EAAE;IACvB,yBAAyB,EAAE;IAC3B,UAAU;KAAE,OAAO;KAAU,QAJhB,aAAa,QAAQ,EAAE,UAAU,OAAO,EAAE;KAIlB;IACtC;;;CAIL,MAAa,OAAO,eAA6B,UAA2D;AAC1G,SAAO;GACL,qBAAqB,EAAE;GACvB,yBAAyB,EAAE;GAC3B,UAAU;IACR,OAAO;IACP,QAAQ;IACT;GACF;;CAGH,MAAa,WACX,eACA,UAC8B;AAC9B,SAAO;GACL,qBAAqB,EAAE;GACvB,yBAAyB,EAAE;GAC3B,UAAU;IACR,OAAO;IACP,QAAQ;IACT;GACF;;;gCArJJ,YAAY"}
@@ -0,0 +1,18 @@
1
+ import { KanonClientService } from "../ledger/KanonClientService.js";
2
+ import "../ledger/index.js";
3
+ import { AgentContext, DidResolutionResult, DidResolver, ParsedDid } from "@credo-ts/core";
4
+
5
+ //#region src/dids/KanonDidResolver.d.ts
6
+ declare class KanonDidResolver implements DidResolver {
7
+ private clientService;
8
+ readonly supportedMethods: string[];
9
+ readonly allowsCaching = true;
10
+ readonly allowsLocalDidRecord = true;
11
+ constructor(clientService: KanonClientService);
12
+ resolve(agentContext: AgentContext, did: string, _parsed: ParsedDid): Promise<DidResolutionResult>;
13
+ private toDidDocument;
14
+ private errorResponse;
15
+ }
16
+ //#endregion
17
+ export { KanonDidResolver };
18
+ //# sourceMappingURL=KanonDidResolver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonDidResolver.d.ts","names":[],"sources":["../../src/dids/KanonDidResolver.ts"],"mappings":";;;;;cAiBa,gBAAA,YAA4B,WAAA;EAAA,QAKZ,aAAA;EAAA,SAJX,gBAAA;EAAA,SACA,aAAA;EAAA,SACA,oBAAA;cAEW,aAAA,EAAe,kBAAA;EAE7B,OAAA,CAAQ,YAAA,EAAc,YAAA,EAAc,GAAA,UAAa,OAAA,EAAS,SAAA,GAAY,OAAA,CAAQ,mBAAA;EAAA,QAuBnF,aAAA;EAAA,QAyCA,aAAA;AAAA"}