@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,298 @@
1
+ import { KanonZkIssuerKeyService } from "../../zk/KanonZkIssuerKeyService.js";
2
+ import { KanonClientService } from "../../ledger/KanonClientService.js";
3
+ import "../../ledger/index.js";
4
+ import { kanonCredIdHash as kanonCredIdHash$1 } from "../utils/credIdHash.js";
5
+ import { TIER_ALL, TIER_ONE_TIME, TIER_ZK_SNARK } from "@ajna-inc/kanon-sdk";
6
+ import { GenericRecordsApi } from "@credo-ts/core";
7
+ import { anchorJson, credDefResourceId, decodeDataUri, encodeAnonCredsSchema, issuerOrgId, parseKanonDid, resourceIdToBytes32 } from "@ajna-inc/kanon-sdk/anoncreds";
8
+ import { ethers } from "ethers";
9
+
10
+ //#region src/anoncreds/services/KanonAnonCredsRegistry.ts
11
+ const CRED_DEF_RECORD_TAG = "kanonCredDefBody";
12
+ /**
13
+ * Recognize the `policyMask` AnonCreds-side option in a few shapes so callers
14
+ * who don't import the SDK constants can still opt into Mode B:
15
+ *
16
+ * policyMask: 1 // TIER_ONE_TIME
17
+ * policyMask: 2 // TIER_ZK_SNARK
18
+ * policyMask: 3 // TIER_ALL
19
+ * policyMask: 'TIER_ONE_TIME' // string aliases — same values
20
+ * policyMask: 'TIER_ZK_SNARK'
21
+ * policyMask: 'TIER_ALL' | 'ALL'
22
+ * policyMask: ['TIER_ONE_TIME', 'TIER_ZK_SNARK'] // array union
23
+ *
24
+ * Defaults to `TIER_ONE_TIME` when absent — same behaviour as the previous
25
+ * hard-coded path, so existing callers don't change.
26
+ */
27
+ function resolvePolicyMask(opts) {
28
+ const raw = opts?.policyMask;
29
+ if (raw === void 0 || raw === null) return TIER_ONE_TIME;
30
+ if (typeof raw === "number") {
31
+ if (raw === 0 || (raw & ~TIER_ALL) !== 0) throw new Error(`kanon: invalid policyMask ${raw}; expected 1, 2 or 3`);
32
+ return raw;
33
+ }
34
+ const toToken = (v) => {
35
+ if (typeof v !== "string") throw new Error(`kanon: invalid policyMask entry ${JSON.stringify(v)}`);
36
+ switch (v.toUpperCase()) {
37
+ case "TIER_ONE_TIME":
38
+ case "ONE_TIME":
39
+ case "MODE_A": return TIER_ONE_TIME;
40
+ case "TIER_ZK_SNARK":
41
+ case "ZK_SNARK":
42
+ case "ZK":
43
+ case "MODE_B": return TIER_ZK_SNARK;
44
+ case "TIER_ALL":
45
+ case "ALL": return TIER_ALL;
46
+ default: throw new Error(`kanon: unknown policyMask token '${v}'`);
47
+ }
48
+ };
49
+ if (Array.isArray(raw)) return raw.reduce((acc, v) => acc | toToken(v), 0) || TIER_ONE_TIME;
50
+ return toToken(raw);
51
+ }
52
+ function assertOrgIssuer(issuerId, kind) {
53
+ const parsed = parseKanonDid(issuerId);
54
+ if (!parsed || parsed.scope !== "org" || parsed.orgId == null) throw new Error(`did:kanon: ${kind} issuer must be an org DID (did:kanon:org:0x<64 hex>), got '${issuerId}'`);
55
+ return issuerOrgId(issuerId);
56
+ }
57
+ var KanonAnonCredsRegistry = class {
58
+ constructor() {
59
+ this.supportedIdentifier = /^did:kanon:.+$/;
60
+ this.methodName = "kanon";
61
+ }
62
+ async registerSchema(agentContext, options) {
63
+ const schema = options.schema;
64
+ try {
65
+ const orgId = assertOrgIssuer(schema.issuerId, "schema");
66
+ const enc = encodeAnonCredsSchema({
67
+ issuerId: schema.issuerId,
68
+ name: schema.name,
69
+ version: schema.version,
70
+ attrNames: schema.attrNames
71
+ });
72
+ const clientService = agentContext.dependencyManager.resolve(KanonClientService);
73
+ await clientService.client.registerSchema(clientService.getSigner(), orgId, enc.schemaIdBytes32, enc.schemaHash, enc.uri);
74
+ return {
75
+ schemaState: {
76
+ state: "finished",
77
+ schema,
78
+ schemaId: enc.schemaId
79
+ },
80
+ registrationMetadata: {},
81
+ schemaMetadata: {}
82
+ };
83
+ } catch (error) {
84
+ const message = error instanceof Error ? error.message : String(error);
85
+ agentContext.config.logger.debug(`Error registering schema for '${schema.issuerId}': ${message}`);
86
+ return {
87
+ schemaMetadata: {},
88
+ registrationMetadata: {},
89
+ schemaState: {
90
+ state: "failed",
91
+ schema,
92
+ reason: `unknownError: ${message}`
93
+ }
94
+ };
95
+ }
96
+ }
97
+ async getSchema(agentContext, schemaId) {
98
+ try {
99
+ const record = await agentContext.dependencyManager.resolve(KanonClientService).contracts.schemaRegistry.getSchema(resourceIdToBytes32(schemaId));
100
+ const body = record?.uri ? decodeDataUri(record.uri) : null;
101
+ if (!body) return {
102
+ schemaId,
103
+ resolutionMetadata: {
104
+ error: "notFound",
105
+ message: `schema not found: ${schemaId}`
106
+ },
107
+ schemaMetadata: {}
108
+ };
109
+ return {
110
+ schema: {
111
+ issuerId: String(body.issuerId),
112
+ attrNames: body.attrNames ?? [],
113
+ name: String(body.name),
114
+ version: String(body.version)
115
+ },
116
+ schemaId,
117
+ resolutionMetadata: {},
118
+ schemaMetadata: {}
119
+ };
120
+ } catch (error) {
121
+ const message = error instanceof Error ? error.message : String(error);
122
+ agentContext.config.logger.error(`Error retrieving schema '${schemaId}': ${message}`);
123
+ return {
124
+ schemaId,
125
+ resolutionMetadata: {
126
+ error: "notFound",
127
+ message: `unable to resolve schema: ${message}`
128
+ },
129
+ schemaMetadata: {}
130
+ };
131
+ }
132
+ }
133
+ async registerCredentialDefinition(agentContext, options) {
134
+ const credentialDefinition = options.credentialDefinition;
135
+ try {
136
+ assertOrgIssuer(credentialDefinition.issuerId, "cred-def");
137
+ const schema = await this.getSchema(agentContext, credentialDefinition.schemaId);
138
+ if (!schema.schema) throw new Error(`Schema not found: ${credentialDefinition.schemaId}`);
139
+ const credDefId = credDefResourceId(credentialDefinition.issuerId, schema.schema.name, credentialDefinition.tag);
140
+ const anchored = anchorJson(credentialDefinition);
141
+ const issuerPubKey = ethers.getBytes(anchored.hash);
142
+ const policyMask = resolvePolicyMask(options.options);
143
+ let issuerZkPubKey;
144
+ if ((policyMask & TIER_ZK_SNARK) !== 0) {
145
+ const key = await agentContext.dependencyManager.resolve(KanonZkIssuerKeyService).provision(agentContext, credDefId);
146
+ issuerZkPubKey = {
147
+ ax: key.publicKey.Ax,
148
+ ay: key.publicKey.Ay
149
+ };
150
+ }
151
+ const clientService = agentContext.dependencyManager.resolve(KanonClientService);
152
+ await clientService.client.registerCredentialDefinition(clientService.getSigner(), resourceIdToBytes32(credDefId), resourceIdToBytes32(credentialDefinition.schemaId), issuerPubKey, policyMask, anchored.uri, issuerZkPubKey);
153
+ await this.storeCredDefBody(agentContext, credDefId, credentialDefinition);
154
+ return {
155
+ credentialDefinitionState: {
156
+ state: "finished",
157
+ credentialDefinition,
158
+ credentialDefinitionId: credDefId
159
+ },
160
+ registrationMetadata: {},
161
+ credentialDefinitionMetadata: {}
162
+ };
163
+ } catch (error) {
164
+ const message = error instanceof Error ? error.message : String(error);
165
+ agentContext.config.logger.debug(`Error registering cred-def for '${credentialDefinition.issuerId}': ${message}`);
166
+ return {
167
+ credentialDefinitionState: {
168
+ state: "failed",
169
+ credentialDefinition,
170
+ reason: `unknownError: ${message}`
171
+ },
172
+ registrationMetadata: {},
173
+ credentialDefinitionMetadata: {}
174
+ };
175
+ }
176
+ }
177
+ async getCredentialDefinition(agentContext, credentialDefinitionId) {
178
+ try {
179
+ let body = await this.loadCredDefBody(agentContext, credentialDefinitionId);
180
+ if (!body) {
181
+ const record = await agentContext.dependencyManager.resolve(KanonClientService).contracts.credDefRegistry.getCredentialDefinition(resourceIdToBytes32(credentialDefinitionId));
182
+ const decoded = record?.uri ? decodeDataUri(record.uri) : null;
183
+ if (!decoded) return {
184
+ credentialDefinitionId,
185
+ resolutionMetadata: {
186
+ error: "notFound",
187
+ message: `cred-def not found: ${credentialDefinitionId}`
188
+ },
189
+ credentialDefinitionMetadata: {}
190
+ };
191
+ body = decoded;
192
+ }
193
+ return {
194
+ credentialDefinitionId,
195
+ resolutionMetadata: {},
196
+ credentialDefinitionMetadata: {},
197
+ credentialDefinition: body
198
+ };
199
+ } catch (error) {
200
+ return {
201
+ credentialDefinitionId,
202
+ resolutionMetadata: {
203
+ error: "notFound",
204
+ message: `unable to resolve cred-def: ${error instanceof Error ? error.message : String(error)}`
205
+ },
206
+ credentialDefinitionMetadata: {}
207
+ };
208
+ }
209
+ }
210
+ async storeCredDefBody(agentContext, credDefId, body) {
211
+ const genericRecords = agentContext.dependencyManager.resolve(GenericRecordsApi);
212
+ const existing = await genericRecords.findById(credDefId);
213
+ if (existing) {
214
+ existing.content = { body };
215
+ await genericRecords.update(existing);
216
+ return;
217
+ }
218
+ await genericRecords.save({
219
+ id: credDefId,
220
+ content: { body },
221
+ tags: { [CRED_DEF_RECORD_TAG]: credDefId }
222
+ });
223
+ }
224
+ async loadCredDefBody(agentContext, credDefId) {
225
+ const record = await agentContext.dependencyManager.resolve(GenericRecordsApi).findById(credDefId);
226
+ if (!record) return null;
227
+ const body = record.content?.body;
228
+ return body ? body : null;
229
+ }
230
+ /**
231
+ * Kanon does NOT implement the AnonCreds CKS revocation-registry model.
232
+ * Per-credential status is tracked in `AnonCredsStatusRegistry` instead,
233
+ * looked up by the verifier after `verifyProof` succeeds. These four methods
234
+ * stay rejected so callers expecting CKS revocation surface a clear error.
235
+ */
236
+ async getRevocationRegistryDefinition(_agentContext, revocationRegistryDefinitionId) {
237
+ return {
238
+ revocationRegistryDefinitionId,
239
+ resolutionMetadata: {
240
+ error: "notFound",
241
+ message: "Kanon VDR does not implement AnonCreds CKS revocation registries. Credentials use AnonCredsStatusRegistry status lookup after verifyProof."
242
+ },
243
+ revocationRegistryDefinitionMetadata: {}
244
+ };
245
+ }
246
+ async registerRevocationRegistryDefinition(_agentContext, options) {
247
+ return {
248
+ revocationRegistryDefinitionMetadata: {},
249
+ registrationMetadata: {},
250
+ revocationRegistryDefinitionState: {
251
+ state: "failed",
252
+ revocationRegistryDefinition: options.revocationRegistryDefinition,
253
+ reason: "Kanon VDR does not support AnonCreds CKS revocation registries. Issue credentials without revocationRegistryId; use KanonAnonCredsRegistry.revokeCredentialOnChain to revoke."
254
+ }
255
+ };
256
+ }
257
+ async getRevocationStatusList(_agentContext, _revocationRegistryId, _timestamp) {
258
+ return {
259
+ resolutionMetadata: {
260
+ error: "notFound",
261
+ message: "Kanon VDR uses on-chain per-credential status, not CKS status lists."
262
+ },
263
+ revocationStatusListMetadata: {}
264
+ };
265
+ }
266
+ async registerRevocationStatusList(_agentContext, options) {
267
+ return {
268
+ revocationStatusListMetadata: {},
269
+ registrationMetadata: {},
270
+ revocationStatusListState: {
271
+ state: "failed",
272
+ revocationStatusList: options.revocationStatusList,
273
+ reason: "Kanon VDR uses on-chain per-credential status, not CKS status lists. Use revokeCredentialOnChain to revoke."
274
+ }
275
+ };
276
+ }
277
+ /**
278
+ * Revokes a previously-issued credential by writing to the on-chain
279
+ * `AnonCredsStatusRegistry`. The signer must be a member of the credDef's org.
280
+ */
281
+ async revokeCredentialOnChain(agentContext, credDefId, credId) {
282
+ const clientService = agentContext.dependencyManager.resolve(KanonClientService);
283
+ if (!clientService.hasAnonCredsStatusRegistry()) throw new Error("Cannot revoke: KanonModule was loaded without anonCredsStatusRegistryAddress");
284
+ await clientService.revokeCredentialStatus(credDefId, kanonCredIdHash$1(credId));
285
+ }
286
+ /**
287
+ * Reads the on-chain revocation status of a credential.
288
+ */
289
+ async isCredentialRevokedOnChain(agentContext, credDefId, credId) {
290
+ const clientService = agentContext.dependencyManager.resolve(KanonClientService);
291
+ if (!clientService.hasAnonCredsStatusRegistry()) return false;
292
+ return clientService.isCredentialRevokedOnStatus(credDefId, kanonCredIdHash$1(credId));
293
+ }
294
+ };
295
+
296
+ //#endregion
297
+ export { KanonAnonCredsRegistry };
298
+ //# sourceMappingURL=KanonAnonCredsRegistry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonAnonCredsRegistry.js","names":["kanonCredIdHash"],"sources":["../../../src/anoncreds/services/KanonAnonCredsRegistry.ts"],"sourcesContent":["import type {\n AnonCredsCredentialDefinition,\n AnonCredsRegistry,\n AnonCredsSchema,\n GetCredentialDefinitionReturn,\n GetRevocationRegistryDefinitionReturn,\n GetRevocationStatusListReturn,\n GetSchemaReturn,\n RegisterCredentialDefinitionOptions,\n RegisterCredentialDefinitionReturn,\n RegisterRevocationRegistryDefinitionOptions,\n RegisterRevocationRegistryDefinitionReturn,\n RegisterRevocationStatusListOptions,\n RegisterRevocationStatusListReturn,\n RegisterSchemaOptions,\n RegisterSchemaReturn,\n} from '@credo-ts/anoncreds'\nimport type { AgentContext } from '@credo-ts/core'\n\nimport { TIER_ALL, TIER_ONE_TIME, TIER_ZK_SNARK } from '@ajna-inc/kanon-sdk'\n\nimport { KanonZkIssuerKeyService } from '../../zk/KanonZkIssuerKeyService'\nimport {\n anchorJson,\n credDefResourceId,\n decodeDataUri,\n encodeAnonCredsSchema,\n issuerOrgId,\n parseKanonDid,\n resourceIdToBytes32,\n} from '@ajna-inc/kanon-sdk/anoncreds'\nimport { GenericRecordsApi } from '@credo-ts/core'\nimport { ethers } from 'ethers'\n\nimport { KanonClientService } from '../../ledger'\nimport { kanonCredIdHash } from '../utils/credIdHash'\n\n// Tag prefix for the local GenericRecord that holds a cred-def body. kanon's\n// CredentialDefinitionRegistry anchors only (schemaId, issuerOrg, issuerPubKey,\n// policyMask) — the AnonCreds CL `value` has no on-chain home, so the issuing\n// agent keeps the full body locally and serves it on resolve.\nconst CRED_DEF_RECORD_TAG = 'kanonCredDefBody'\n\n/**\n * Recognize the `policyMask` AnonCreds-side option in a few shapes so callers\n * who don't import the SDK constants can still opt into Mode B:\n *\n * policyMask: 1 // TIER_ONE_TIME\n * policyMask: 2 // TIER_ZK_SNARK\n * policyMask: 3 // TIER_ALL\n * policyMask: 'TIER_ONE_TIME' // string aliases — same values\n * policyMask: 'TIER_ZK_SNARK'\n * policyMask: 'TIER_ALL' | 'ALL'\n * policyMask: ['TIER_ONE_TIME', 'TIER_ZK_SNARK'] // array union\n *\n * Defaults to `TIER_ONE_TIME` when absent — same behaviour as the previous\n * hard-coded path, so existing callers don't change.\n */\nfunction resolvePolicyMask(opts: Record<string, unknown> | undefined): number {\n const raw = opts?.policyMask\n if (raw === undefined || raw === null) return TIER_ONE_TIME\n if (typeof raw === 'number') {\n if (raw === 0 || (raw & ~TIER_ALL) !== 0) {\n throw new Error(`kanon: invalid policyMask ${raw}; expected 1, 2 or 3`)\n }\n return raw\n }\n const toToken = (v: unknown): number => {\n if (typeof v !== 'string') {\n throw new Error(`kanon: invalid policyMask entry ${JSON.stringify(v)}`)\n }\n switch (v.toUpperCase()) {\n case 'TIER_ONE_TIME':\n case 'ONE_TIME':\n case 'MODE_A':\n return TIER_ONE_TIME\n case 'TIER_ZK_SNARK':\n case 'ZK_SNARK':\n case 'ZK':\n case 'MODE_B':\n return TIER_ZK_SNARK\n case 'TIER_ALL':\n case 'ALL':\n return TIER_ALL\n default:\n throw new Error(`kanon: unknown policyMask token '${v}'`)\n }\n }\n if (Array.isArray(raw)) {\n return raw.reduce<number>((acc, v) => acc | toToken(v), 0) || TIER_ONE_TIME\n }\n return toToken(raw)\n}\n\nfunction assertOrgIssuer(issuerId: string, kind: string): string {\n const parsed = parseKanonDid(issuerId)\n if (!parsed || parsed.scope !== 'org' || parsed.orgId == null) {\n throw new Error(`did:kanon: ${kind} issuer must be an org DID (did:kanon:org:0x<64 hex>), got '${issuerId}'`)\n }\n return issuerOrgId(issuerId)\n}\n\nexport class KanonAnonCredsRegistry implements AnonCredsRegistry {\n public supportedIdentifier = /^did:kanon:.+$/\n\n public methodName = 'kanon'\n\n // ── Schemas ────────────────────────────────────────────────────────────\n\n public async registerSchema(\n agentContext: AgentContext,\n options: RegisterSchemaOptions\n ): Promise<RegisterSchemaReturn> {\n const schema = options.schema\n try {\n const orgId = assertOrgIssuer(schema.issuerId, 'schema')\n const enc = encodeAnonCredsSchema({\n issuerId: schema.issuerId,\n name: schema.name,\n version: schema.version,\n attrNames: schema.attrNames,\n })\n\n const clientService = agentContext.dependencyManager.resolve(KanonClientService)\n await clientService.client.registerSchema(\n clientService.getSigner(),\n orgId,\n enc.schemaIdBytes32,\n enc.schemaHash,\n enc.uri\n )\n\n return {\n schemaState: { state: 'finished', schema, schemaId: enc.schemaId },\n registrationMetadata: {},\n schemaMetadata: {},\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n agentContext.config.logger.debug(`Error registering schema for '${schema.issuerId}': ${message}`)\n return {\n schemaMetadata: {},\n registrationMetadata: {},\n schemaState: { state: 'failed', schema, reason: `unknownError: ${message}` },\n }\n }\n }\n\n public async getSchema(agentContext: AgentContext, schemaId: string): Promise<GetSchemaReturn> {\n try {\n const clientService = agentContext.dependencyManager.resolve(KanonClientService)\n const record = await clientService.contracts.schemaRegistry.getSchema(resourceIdToBytes32(schemaId))\n const body = record?.uri ? (decodeDataUri(record.uri) as Record<string, unknown> | null) : null\n if (!body) {\n return {\n schemaId,\n resolutionMetadata: { error: 'notFound', message: `schema not found: ${schemaId}` },\n schemaMetadata: {},\n }\n }\n const schema: AnonCredsSchema = {\n issuerId: String(body.issuerId),\n attrNames: (body.attrNames as string[]) ?? [],\n name: String(body.name),\n version: String(body.version),\n }\n return { schema, schemaId, resolutionMetadata: {}, schemaMetadata: {} }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n agentContext.config.logger.error(`Error retrieving schema '${schemaId}': ${message}`)\n return {\n schemaId,\n resolutionMetadata: { error: 'notFound', message: `unable to resolve schema: ${message}` },\n schemaMetadata: {},\n }\n }\n }\n\n // ── Credential definitions ───────────────────────────────────────────────\n\n public async registerCredentialDefinition(\n agentContext: AgentContext,\n options: RegisterCredentialDefinitionOptions\n ): Promise<RegisterCredentialDefinitionReturn> {\n const credentialDefinition = options.credentialDefinition\n try {\n const orgId = assertOrgIssuer(credentialDefinition.issuerId, 'cred-def')\n\n // The cred-def id is a DID URL under the issuer DID. We need the schema's\n // name as the schema tag; fetch the schema body for it.\n const schema = await this.getSchema(agentContext, credentialDefinition.schemaId)\n if (!schema.schema) throw new Error(`Schema not found: ${credentialDefinition.schemaId}`)\n\n const credDefId = credDefResourceId(credentialDefinition.issuerId, schema.schema.name, credentialDefinition.tag)\n\n // Store the full CL body inline as a data: URI (source of truth on\n // resolve, mirroring SchemaRegistry). issuerPubKey = keccak(canonical\n // body) stays the integrity anchor binding the entry to the body.\n const anchored = anchorJson(credentialDefinition)\n const issuerPubKey = ethers.getBytes(anchored.hash)\n\n // Policy mask + (optional) Tier 2 BabyJubjub key resolution.\n //\n // Callers opt into Tier 2 by passing `options.options.policyMask`. The\n // recognized values are `TIER_ONE_TIME` (Mode A), `TIER_ZK_SNARK`\n // (Mode B only — no on-chain status registry leakage at issue/revoke\n // time), or `TIER_ALL` (both). Default stays at Mode A so existing\n // callers don't have to think about ZK.\n //\n // When TIER_ZK_SNARK is requested the issuer's BabyJubjub keypair is\n // provisioned via `KanonZkIssuerKeyService.provision(credDefId)`. It's\n // idempotent (cache hit + single-flight lock for concurrent callers):\n // if the key already exists locally it's reused. The public coords\n // are passed to the contract atomically with the credDef registration\n // — there's no separate setIssuerZkPubKey hop.\n const policyMask = resolvePolicyMask(options.options as Record<string, unknown> | undefined)\n let issuerZkPubKey: { ax: bigint; ay: bigint } | undefined\n if ((policyMask & TIER_ZK_SNARK) !== 0) {\n const keyService = agentContext.dependencyManager.resolve(KanonZkIssuerKeyService)\n const key = await keyService.provision(agentContext, credDefId)\n issuerZkPubKey = { ax: key.publicKey.Ax, ay: key.publicKey.Ay }\n }\n\n // Do the on-chain register FIRST. If it reverts we don't want a stale\n // local body in GenericRecords pointing at a credDef that doesn't\n // exist on chain. The BJJ key (if any) is already persisted at this\n // point, but that's safe — provision is idempotent across retries\n // and the unused key has no on-chain footprint.\n const clientService = agentContext.dependencyManager.resolve(KanonClientService)\n await clientService.client.registerCredentialDefinition(\n clientService.getSigner(),\n resourceIdToBytes32(credDefId),\n resourceIdToBytes32(credentialDefinition.schemaId),\n issuerPubKey,\n policyMask,\n anchored.uri,\n issuerZkPubKey\n )\n\n // Chain register succeeded — now safe to cache the body locally as a\n // fast-path for cross-agent resolution.\n await this.storeCredDefBody(agentContext, credDefId, credentialDefinition)\n\n // Validate the org id matches the on-chain expectation (defensive — the\n // SDK already enforces membership; kept for parity with the reference).\n void orgId\n\n return {\n credentialDefinitionState: { state: 'finished', credentialDefinition, credentialDefinitionId: credDefId },\n registrationMetadata: {},\n credentialDefinitionMetadata: {},\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n agentContext.config.logger.debug(`Error registering cred-def for '${credentialDefinition.issuerId}': ${message}`)\n return {\n credentialDefinitionState: { state: 'failed', credentialDefinition, reason: `unknownError: ${message}` },\n registrationMetadata: {},\n credentialDefinitionMetadata: {},\n }\n }\n }\n\n public async getCredentialDefinition(\n agentContext: AgentContext,\n credentialDefinitionId: string\n ): Promise<GetCredentialDefinitionReturn> {\n try {\n // The full CL body is stored inline on-chain as a data: URI (source of\n // truth, mirroring schemas), so cross-agent resolution works. The local\n // store is consulted first only as an optional fast-path cache.\n let body = await this.loadCredDefBody(agentContext, credentialDefinitionId)\n if (!body) {\n const clientService = agentContext.dependencyManager.resolve(KanonClientService)\n const record = await clientService.contracts.credDefRegistry.getCredentialDefinition(\n resourceIdToBytes32(credentialDefinitionId)\n )\n const decoded = record?.uri ? (decodeDataUri(record.uri) as AnonCredsCredentialDefinition | null) : null\n if (!decoded) {\n return {\n credentialDefinitionId,\n resolutionMetadata: { error: 'notFound', message: `cred-def not found: ${credentialDefinitionId}` },\n credentialDefinitionMetadata: {},\n }\n }\n body = decoded\n }\n\n return {\n credentialDefinitionId,\n resolutionMetadata: {},\n credentialDefinitionMetadata: {},\n credentialDefinition: body,\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n credentialDefinitionId,\n resolutionMetadata: { error: 'notFound', message: `unable to resolve cred-def: ${message}` },\n credentialDefinitionMetadata: {},\n }\n }\n }\n\n private async storeCredDefBody(\n agentContext: AgentContext,\n credDefId: string,\n body: AnonCredsCredentialDefinition\n ): Promise<void> {\n const genericRecords = agentContext.dependencyManager.resolve(GenericRecordsApi)\n const existing = await genericRecords.findById(credDefId)\n if (existing) {\n existing.content = { body: body as unknown as Record<string, unknown> }\n await genericRecords.update(existing)\n return\n }\n await genericRecords.save({\n id: credDefId,\n content: { body: body as unknown as Record<string, unknown> },\n tags: { [CRED_DEF_RECORD_TAG]: credDefId },\n })\n }\n\n private async loadCredDefBody(\n agentContext: AgentContext,\n credDefId: string\n ): Promise<AnonCredsCredentialDefinition | null> {\n const genericRecords = agentContext.dependencyManager.resolve(GenericRecordsApi)\n const record = await genericRecords.findById(credDefId)\n if (!record) return null\n const body = record.content?.body\n return body ? (body as unknown as AnonCredsCredentialDefinition) : null\n }\n\n // ── Revocation (per-credential status registry; CL rev-reg unsupported) ─\n\n /**\n * Kanon does NOT implement the AnonCreds CKS revocation-registry model.\n * Per-credential status is tracked in `AnonCredsStatusRegistry` instead,\n * looked up by the verifier after `verifyProof` succeeds. These four methods\n * stay rejected so callers expecting CKS revocation surface a clear error.\n */\n public async getRevocationRegistryDefinition(\n _agentContext: AgentContext,\n revocationRegistryDefinitionId: string\n ): Promise<GetRevocationRegistryDefinitionReturn> {\n return {\n revocationRegistryDefinitionId,\n resolutionMetadata: {\n error: 'notFound',\n message:\n 'Kanon VDR does not implement AnonCreds CKS revocation registries. Credentials use AnonCredsStatusRegistry status lookup after verifyProof.',\n },\n revocationRegistryDefinitionMetadata: {},\n }\n }\n\n public async registerRevocationRegistryDefinition(\n _agentContext: AgentContext,\n options: RegisterRevocationRegistryDefinitionOptions\n ): Promise<RegisterRevocationRegistryDefinitionReturn> {\n return {\n revocationRegistryDefinitionMetadata: {},\n registrationMetadata: {},\n revocationRegistryDefinitionState: {\n state: 'failed',\n revocationRegistryDefinition: options.revocationRegistryDefinition,\n reason:\n 'Kanon VDR does not support AnonCreds CKS revocation registries. Issue credentials without revocationRegistryId; use KanonAnonCredsRegistry.revokeCredentialOnChain to revoke.',\n },\n }\n }\n\n public async getRevocationStatusList(\n _agentContext: AgentContext,\n _revocationRegistryId: string,\n _timestamp: number\n ): Promise<GetRevocationStatusListReturn> {\n return {\n resolutionMetadata: {\n error: 'notFound',\n message: 'Kanon VDR uses on-chain per-credential status, not CKS status lists.',\n },\n revocationStatusListMetadata: {},\n }\n }\n\n public async registerRevocationStatusList(\n _agentContext: AgentContext,\n options: RegisterRevocationStatusListOptions\n ): Promise<RegisterRevocationStatusListReturn> {\n return {\n revocationStatusListMetadata: {},\n registrationMetadata: {},\n revocationStatusListState: {\n state: 'failed',\n revocationStatusList: options.revocationStatusList,\n reason:\n 'Kanon VDR uses on-chain per-credential status, not CKS status lists. Use revokeCredentialOnChain to revoke.',\n },\n }\n }\n\n // ────────────────────────────────────────────────────────────────────────\n // Kanon-specific status registry helpers (not part of AnonCredsRegistry)\n // ────────────────────────────────────────────────────────────────────────\n\n /**\n * Revokes a previously-issued credential by writing to the on-chain\n * `AnonCredsStatusRegistry`. The signer must be a member of the credDef's org.\n */\n public async revokeCredentialOnChain(agentContext: AgentContext, credDefId: string, credId: string): Promise<void> {\n const clientService = agentContext.dependencyManager.resolve(KanonClientService)\n if (!clientService.hasAnonCredsStatusRegistry()) {\n throw new Error('Cannot revoke: KanonModule was loaded without anonCredsStatusRegistryAddress')\n }\n await clientService.revokeCredentialStatus(credDefId, kanonCredIdHash(credId))\n }\n\n /**\n * Reads the on-chain revocation status of a credential.\n */\n public async isCredentialRevokedOnChain(\n agentContext: AgentContext,\n credDefId: string,\n credId: string\n ): Promise<boolean> {\n const clientService = agentContext.dependencyManager.resolve(KanonClientService)\n if (!clientService.hasAnonCredsStatusRegistry()) return false\n return clientService.isCredentialRevokedOnStatus(credDefId, kanonCredIdHash(credId))\n }\n}\n"],"mappings":";;;;;;;;;;AAyCA,MAAM,sBAAsB;;;;;;;;;;;;;;;;AAiB5B,SAAS,kBAAkB,MAAmD;CAC5E,MAAM,MAAM,MAAM;AAClB,KAAI,QAAQ,UAAa,QAAQ,KAAM,QAAO;AAC9C,KAAI,OAAO,QAAQ,UAAU;AAC3B,MAAI,QAAQ,MAAM,MAAM,CAAC,cAAc,EACrC,OAAM,IAAI,MAAM,6BAA6B,IAAI,sBAAsB;AAEzE,SAAO;;CAET,MAAM,WAAW,MAAuB;AACtC,MAAI,OAAO,MAAM,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C7C,SAAO;GACL,8BAA8B,EAAE;GAChC,sBAAsB,EAAE;GACxB,2BAA2B;IACzB,OAAO;IACP,sBAAsB,QAAQ;IAC9B,QACE;IACH;GACF;;;;;;CAWH,MAAa,wBAAwB,cAA4B,WAAmB,QAA+B;EACjH,MAAM,gBAAgB,aAAa,kBAAkB,QAAQ,mBAAmB;AAChF,MAAI,CAAC,cAAc,4BAA4B,CAC7C,OAAM,IAAI,MAAM,+EAA+E;AAEjG,QAAM,cAAc,uBAAuB,WAAWA,kBAAgB,OAAO,CAAC;;;;;CAMhF,MAAa,2BACX,cACA,WACA,QACkB;EAClB,MAAM,gBAAgB,aAAa,kBAAkB,QAAQ,mBAAmB;AAChF,MAAI,CAAC,cAAc,4BAA4B,CAAE,QAAO;AACxD,SAAO,cAAc,4BAA4B,WAAWA,kBAAgB,OAAO,CAAC"}
@@ -0,0 +1,39 @@
1
+ import { KanonClientService } from "../../ledger/KanonClientService.js";
2
+ import "../../ledger/index.js";
3
+ import { KanonZkService } from "../../zk/KanonZkService.js";
4
+ import "../../zk/index.js";
5
+ import { AgentContext } from "@credo-ts/core";
6
+
7
+ //#region src/anoncreds/services/KanonIssuanceTracker.d.ts
8
+ /**
9
+ * Subscribes to Credo's credential lifecycle events and writes an `issueCredential`
10
+ * call to `AnonCredsStatusRegistry` once a credential is finalized on the issuer side.
11
+ *
12
+ * Reads the credential's `kanonCredId` attribute and the credential definition id
13
+ * from the AnonCreds metadata on the record, hashes the credId via `kanonCredIdHash`,
14
+ * and submits the tx. Logs and swallows failures so issuance never blocks on the
15
+ * on-chain write; operators can retry via a separate reconciliation job.
16
+ */
17
+ declare class KanonIssuanceTracker {
18
+ private readonly ledgerService;
19
+ private readonly zkService;
20
+ private subscriptions;
21
+ private policyMaskCache;
22
+ constructor(ledgerService: KanonClientService, zkService: KanonZkService);
23
+ /**
24
+ * Wire the listener to the given agent context. Safe to call multiple times for
25
+ * the same context — the listener will only be attached once per contextId.
26
+ */
27
+ attach(agentContext: AgentContext): void;
28
+ detach(agentContext: AgentContext): void;
29
+ private handleCredentialStateChanged;
30
+ /**
31
+ * Read + cache the on-chain `policyMask` for a credDef. The mask cannot
32
+ * change after registration, so the per-credDef cache is safe for the
33
+ * lifetime of the process.
34
+ */
35
+ private getPolicyMask;
36
+ }
37
+ //#endregion
38
+ export { KanonIssuanceTracker };
39
+ //# sourceMappingURL=KanonIssuanceTracker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonIssuanceTracker.d.ts","names":[],"sources":["../../../src/anoncreds/services/KanonIssuanceTracker.ts"],"mappings":";;;;;;;;;;;AA2BA;;;;;cACa,oBAAA;EAAA,iBAQQ,aAAA;EAAA,iBACA,SAAA;EAAA,QARX,aAAA;EAAA,QAIA,eAAA;cAGW,aAAA,EAAe,kBAAA,EACf,SAAA,EAAW,cAAA;EARtB;;;;EAeD,MAAA,CAAO,YAAA,EAAc,YAAA;EAkCrB,MAAA,CAAO,YAAA,EAAc,YAAA;EAAA,QAQd,4BAAA;EA1CP;;;;;EAAA,QA2HO,aAAA;AAAA"}
@@ -0,0 +1,141 @@
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 { KanonClientService } from "../../ledger/KanonClientService.js";
4
+ import "../../ledger/index.js";
5
+ import { KANON_CRED_ID_ATTRIBUTE as KANON_CRED_ID_ATTRIBUTE$1, kanonCredIdHash as kanonCredIdHash$1 } from "../utils/credIdHash.js";
6
+ import { KanonZkService } from "../../zk/KanonZkService.js";
7
+ import "../../zk/index.js";
8
+ import { encodeAttributesCanonical } from "@ajna-inc/kanon-sdk";
9
+ import { EventEmitter, injectable } from "@credo-ts/core";
10
+ import { DidCommCredentialEventTypes } from "@credo-ts/didcomm";
11
+
12
+ //#region src/anoncreds/services/KanonIssuanceTracker.ts
13
+ var _ref, _ref2;
14
+ const TIER_ONE_TIME$1 = 1;
15
+ const TIER_ZK_SNARK$1 = 2;
16
+ let KanonIssuanceTracker = class KanonIssuanceTracker {
17
+ constructor(ledgerService, zkService) {
18
+ this.ledgerService = ledgerService;
19
+ this.zkService = zkService;
20
+ this.subscriptions = /* @__PURE__ */ new Map();
21
+ this.policyMaskCache = /* @__PURE__ */ new Map();
22
+ }
23
+ /**
24
+ * Wire the listener to the given agent context. Safe to call multiple times for
25
+ * the same context — the listener will only be attached once per contextId.
26
+ */
27
+ attach(agentContext) {
28
+ if (!this.ledgerService.hasAnonCredsStatusRegistry()) agentContext.config.logger.warn("KanonIssuanceTracker: AnonCredsStatusRegistry not configured. Mode A writes will be skipped; Mode B writes still attempted when the credDef opts in to TIER_ZK_SNARK.");
29
+ if (this.subscriptions.has(agentContext.contextCorrelationId)) return;
30
+ const sub = agentContext.dependencyManager.resolve(EventEmitter).observable(DidCommCredentialEventTypes.DidCommCredentialStateChanged).subscribe(async (event) => {
31
+ try {
32
+ await this.handleCredentialStateChanged(agentContext, event.payload);
33
+ } catch (err) {
34
+ const message = err instanceof Error ? err.message : String(err);
35
+ agentContext.config.logger.error(`KanonIssuanceTracker: error handling CredentialStateChanged: ${message}`);
36
+ }
37
+ });
38
+ this.subscriptions.set(agentContext.contextCorrelationId, sub);
39
+ }
40
+ detach(agentContext) {
41
+ const sub = this.subscriptions.get(agentContext.contextCorrelationId);
42
+ if (sub) {
43
+ sub.unsubscribe();
44
+ this.subscriptions.delete(agentContext.contextCorrelationId);
45
+ }
46
+ }
47
+ async handleCredentialStateChanged(agentContext, payload) {
48
+ const record = payload.credentialExchangeRecord ?? payload.credentialRecord;
49
+ if (record?.state !== "done" || record?.role !== "issuer") return;
50
+ const credDefId = extractCredDefId(record);
51
+ const credId = extractKanonCredId(record);
52
+ if (!credDefId || !credId) {
53
+ agentContext.config.logger.debug(`KanonIssuanceTracker: skipping — record missing credDefId or ${KANON_CRED_ID_ATTRIBUTE$1}`, { credentialRecordId: record?.id });
54
+ return;
55
+ }
56
+ const credIdHash = kanonCredIdHash$1(credId);
57
+ const policyMask = await this.getPolicyMask(agentContext, credDefId);
58
+ if ((policyMask & TIER_ONE_TIME$1) !== 0) if (!this.ledgerService.hasAnonCredsStatusRegistry()) agentContext.config.logger.warn(`KanonIssuanceTracker: credDef ${credDefId} requires Mode A but AnonCredsStatusRegistry is not configured; skipping Mode A write`);
59
+ else {
60
+ agentContext.config.logger.info(`KanonIssuanceTracker: Mode A issue ${credDefId} ${credIdHash}`);
61
+ await this.ledgerService.issueCredentialStatus(credDefId, credIdHash);
62
+ }
63
+ else agentContext.config.logger.debug(`KanonIssuanceTracker: credDef ${credDefId} does not include TIER_ONE_TIME — skipping Mode A status write`);
64
+ if ((policyMask & TIER_ZK_SNARK$1) !== 0) try {
65
+ const attrs = extractLeafAttributes(record);
66
+ agentContext.config.logger.info(`KanonIssuanceTracker: Mode B publish leaf for ${credDefId} (${attrs.length} leaf attrs)`);
67
+ await this.zkService.addIssued(agentContext, credDefId, [{
68
+ credId,
69
+ attributes: attrs
70
+ }]);
71
+ } catch (err) {
72
+ const message = err instanceof Error ? err.message : String(err);
73
+ agentContext.config.logger.error(`KanonIssuanceTracker: Mode B publish failed for ${credDefId}: ${message}`);
74
+ }
75
+ }
76
+ /**
77
+ * Read + cache the on-chain `policyMask` for a credDef. The mask cannot
78
+ * change after registration, so the per-credDef cache is safe for the
79
+ * lifetime of the process.
80
+ */
81
+ async getPolicyMask(agentContext, credDefId) {
82
+ const cached = this.policyMaskCache.get(credDefId);
83
+ if (cached !== void 0) return cached;
84
+ try {
85
+ const mask = await this.ledgerService.client.getCredDefPolicy(credDefId);
86
+ this.policyMaskCache.set(credDefId, mask);
87
+ return mask;
88
+ } catch (err) {
89
+ const message = err instanceof Error ? err.message : String(err);
90
+ agentContext.config.logger.warn(`KanonIssuanceTracker: getCredDefPolicy(${credDefId}) failed (${message}); defaulting to TIER_ONE_TIME`);
91
+ this.policyMaskCache.set(credDefId, TIER_ONE_TIME$1);
92
+ return TIER_ONE_TIME$1;
93
+ }
94
+ }
95
+ };
96
+ KanonIssuanceTracker = __decorate([injectable(), __decorateMetadata("design:paramtypes", [KanonClientService, KanonZkService])], KanonIssuanceTracker);
97
+ /**
98
+ * Returns the AnonCreds credential definition id from a Credo credential record.
99
+ * Looks in several known metadata slots that Credo uses across versions.
100
+ */
101
+ function extractCredDefId(record) {
102
+ const meta = record?.metadata;
103
+ if (!meta) return void 0;
104
+ return [
105
+ meta.get?.("_anoncreds/credential")?.credentialDefinitionId,
106
+ meta.get?.("_anonCreds/credential")?.credentialDefinitionId,
107
+ meta.get?.("_internal/anoncreds")?.credentialDefinitionId,
108
+ meta.get?.("credentialDefinitionId"),
109
+ record.credentialDefinitionId
110
+ ].find((v) => typeof v === "string" && v.length > 0);
111
+ }
112
+ /**
113
+ * Returns the value of the `kanonCredId` attribute from the credential record's
114
+ * credentialAttributes list.
115
+ */
116
+ function extractKanonCredId(record) {
117
+ const attr = (Array.isArray(record?.credentialAttributes) ? record.credentialAttributes : []).find((a) => a?.name === KANON_CRED_ID_ATTRIBUTE$1);
118
+ return typeof attr?.value === "string" ? attr.value : void 0;
119
+ }
120
+ /**
121
+ * Map the credential's domain attributes onto BN254 felts using the SDK's
122
+ * CANONICAL ordering (lexicographic byte sort of attribute names,
123
+ * SDK-reserved names excluded). Same encoder the prep step and the holder
124
+ * wrapper use — the three sites produce identical felt arrays from the
125
+ * same value map regardless of how anoncreds-rs ordered the
126
+ * `credentialAttributes` array under the hood.
127
+ */
128
+ function extractLeafAttributes(record) {
129
+ const attrs = Array.isArray(record?.credentialAttributes) ? record.credentialAttributes : [];
130
+ const values = {};
131
+ for (const a of attrs) {
132
+ const name = a?.name;
133
+ if (typeof name !== "string") continue;
134
+ values[name] = typeof a?.value === "string" ? a.value : "";
135
+ }
136
+ return encodeAttributesCanonical(values);
137
+ }
138
+
139
+ //#endregion
140
+ export { KanonIssuanceTracker };
141
+ //# sourceMappingURL=KanonIssuanceTracker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonIssuanceTracker.js","names":["TIER_ONE_TIME","TIER_ZK_SNARK","KANON_CRED_ID_ATTRIBUTE","kanonCredIdHash"],"sources":["../../../src/anoncreds/services/KanonIssuanceTracker.ts"],"sourcesContent":["import type { AgentContext } from '@credo-ts/core'\nimport type { DidCommCredentialStateChangedEvent } from '@credo-ts/didcomm'\n\nimport { EventEmitter, injectable } from '@credo-ts/core'\nimport { DidCommCredentialEventTypes } from '@credo-ts/didcomm'\nimport type { Subscription } from 'rxjs'\n\nimport { encodeAttributesCanonical } from '@ajna-inc/kanon-sdk'\n\nimport { KanonClientService } from '../../ledger'\nimport { KanonZkService } from '../../zk'\nimport { KANON_CRED_ID_ATTRIBUTE, kanonCredIdHash } from '../utils/credIdHash'\n\n// Mirrors the SDK's TIER_* constants. Defined locally to avoid a runtime SDK\n// import when only the bit-mask values are needed.\nconst TIER_ONE_TIME = 0b01\nconst TIER_ZK_SNARK = 0b10\n\n/**\n * Subscribes to Credo's credential lifecycle events and writes an `issueCredential`\n * call to `AnonCredsStatusRegistry` once a credential is finalized on the issuer side.\n *\n * Reads the credential's `kanonCredId` attribute and the credential definition id\n * from the AnonCreds metadata on the record, hashes the credId via `kanonCredIdHash`,\n * and submits the tx. Logs and swallows failures so issuance never blocks on the\n * on-chain write; operators can retry via a separate reconciliation job.\n */\n@injectable()\nexport class KanonIssuanceTracker {\n private subscriptions = new Map<string, Subscription>()\n // policyMask is immutable for the lifetime of a credDef on chain, so cache\n // it once per credDef. Refreshing requires plugin restart, which is fine —\n // the mask cannot be changed after registration.\n private policyMaskCache = new Map<string, number>()\n\n public constructor(\n private readonly ledgerService: KanonClientService,\n private readonly zkService: KanonZkService\n ) {}\n\n /**\n * Wire the listener to the given agent context. Safe to call multiple times for\n * the same context — the listener will only be attached once per contextId.\n */\n public attach(agentContext: AgentContext): void {\n // The tracker handles BOTH modes: Mode A writes to AnonCredsStatusRegistry,\n // Mode B writes to MerkleStateRegistry. The address book always exposes a\n // MerkleStateRegistry, but the AnonCreds status registry is optional in\n // older deployments. Only refuse to attach when neither surface is wired —\n // a deployment with only the MerkleStateRegistry is valid for Mode B-only\n // cred-defs.\n const hasStatus = this.ledgerService.hasAnonCredsStatusRegistry()\n if (!hasStatus) {\n agentContext.config.logger.warn(\n 'KanonIssuanceTracker: AnonCredsStatusRegistry not configured. Mode A writes will be skipped; Mode B writes still attempted when the credDef opts in to TIER_ZK_SNARK.'\n )\n }\n if (this.subscriptions.has(agentContext.contextCorrelationId)) return\n\n const eventEmitter = agentContext.dependencyManager.resolve(EventEmitter)\n const observable = eventEmitter.observable<DidCommCredentialStateChangedEvent>(\n DidCommCredentialEventTypes.DidCommCredentialStateChanged\n )\n\n const sub = observable.subscribe(async (event) => {\n try {\n await this.handleCredentialStateChanged(agentContext, event.payload)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n agentContext.config.logger.error(\n `KanonIssuanceTracker: error handling CredentialStateChanged: ${message}`\n )\n }\n })\n\n this.subscriptions.set(agentContext.contextCorrelationId, sub)\n }\n\n public detach(agentContext: AgentContext): void {\n const sub = this.subscriptions.get(agentContext.contextCorrelationId)\n if (sub) {\n sub.unsubscribe()\n this.subscriptions.delete(agentContext.contextCorrelationId)\n }\n }\n\n private async handleCredentialStateChanged(\n agentContext: AgentContext,\n payload: DidCommCredentialStateChangedEvent['payload']\n ): Promise<void> {\n // The payload carries `credentialExchangeRecord` in current Credo versions; the\n // permissive `any` cast lets us read fields that vary across Credo versions.\n // biome-ignore lint/suspicious/noExplicitAny: credential record shape varies\n const record = (payload as any).credentialExchangeRecord ?? (payload as any).credentialRecord\n // Only react when the issuer side has finalized: state=\"done\" and role=\"issuer\".\n if (record?.state !== 'done' || record?.role !== 'issuer') return\n\n const credDefId = extractCredDefId(record)\n const credId = extractKanonCredId(record)\n if (!credDefId || !credId) {\n agentContext.config.logger.debug(\n `KanonIssuanceTracker: skipping — record missing credDefId or ${KANON_CRED_ID_ATTRIBUTE}`,\n { credentialRecordId: record?.id }\n )\n return\n }\n\n const credIdHash = kanonCredIdHash(credId)\n const policyMask = await this.getPolicyMask(agentContext, credDefId)\n\n // ── Mode A: AnonCredsStatusRegistry.issueCredential ──\n // Only writes when the credDef opted in to TIER_ONE_TIME AND the status\n // registry is configured for this agent. Skipping the write when the\n // credDef is ZK-only avoids the linkable on-chain trace that Mode B is\n // designed to avoid.\n if ((policyMask & TIER_ONE_TIME) !== 0) {\n if (!this.ledgerService.hasAnonCredsStatusRegistry()) {\n agentContext.config.logger.warn(\n `KanonIssuanceTracker: credDef ${credDefId} requires Mode A but AnonCredsStatusRegistry is not configured; skipping Mode A write`\n )\n } else {\n agentContext.config.logger.info(\n `KanonIssuanceTracker: Mode A issue ${credDefId} ${credIdHash}`\n )\n await this.ledgerService.issueCredentialStatus(credDefId, credIdHash)\n }\n } else {\n agentContext.config.logger.debug(\n `KanonIssuanceTracker: credDef ${credDefId} does not include TIER_ONE_TIME — skipping Mode A status write`\n )\n }\n\n // ── Mode B: MerkleStateRegistry.batchUpdate (publish leaf) ──\n if ((policyMask & TIER_ZK_SNARK) !== 0) {\n try {\n // For Mode B we must publish the SAME leaf the holder will later prove\n // against — derived from the credential's attribute values, in schema\n // order, encoded canonically as BN254 felts.\n //\n // The attribute list on the record includes `kanonZkSig` (the BJJ sig,\n // injected at prep time) and `kanonCredId`. Both are SDK-reserved; they\n // are part of the credential record so the AnonCreds CL signature\n // covers them, but they are NOT part of the in-circuit attribute hash\n // — the SNARK already binds credId via `publicSignals` and the BJJ sig\n // is checked over the leaf, so re-hashing them inside `attributes[]`\n // would double-bind. We strip them here.\n const attrs = extractLeafAttributes(record)\n agentContext.config.logger.info(\n `KanonIssuanceTracker: Mode B publish leaf for ${credDefId} (${attrs.length} leaf attrs)`\n )\n await this.zkService.addIssued(agentContext, credDefId, [\n { credId, attributes: attrs },\n ])\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n agentContext.config.logger.error(\n `KanonIssuanceTracker: Mode B publish failed for ${credDefId}: ${message}`\n )\n }\n }\n }\n\n /**\n * Read + cache the on-chain `policyMask` for a credDef. The mask cannot\n * change after registration, so the per-credDef cache is safe for the\n * lifetime of the process.\n */\n private async getPolicyMask(agentContext: AgentContext, credDefId: string): Promise<number> {\n const cached = this.policyMaskCache.get(credDefId)\n if (cached !== undefined) return cached\n try {\n const mask = await this.ledgerService.client.getCredDefPolicy(credDefId)\n this.policyMaskCache.set(credDefId, mask)\n return mask\n } catch (err) {\n // Backward compat: if the credDef predates `policyMask` or the call\n // reverts, fall back to TIER_ONE_TIME so legacy Mode A behaviour is\n // preserved instead of silently dropping the status-registry write.\n const message = err instanceof Error ? err.message : String(err)\n agentContext.config.logger.warn(\n `KanonIssuanceTracker: getCredDefPolicy(${credDefId}) failed (${message}); defaulting to TIER_ONE_TIME`\n )\n this.policyMaskCache.set(credDefId, TIER_ONE_TIME)\n return TIER_ONE_TIME\n }\n }\n}\n\n/**\n * Returns the AnonCreds credential definition id from a Credo credential record.\n * Looks in several known metadata slots that Credo uses across versions.\n */\n// biome-ignore lint/suspicious/noExplicitAny: record shape varies\nfunction extractCredDefId(record: any): string | undefined {\n const meta = record?.metadata\n if (!meta) return undefined\n const candidates = [\n meta.get?.('_anoncreds/credential')?.credentialDefinitionId,\n meta.get?.('_anonCreds/credential')?.credentialDefinitionId,\n meta.get?.('_internal/anoncreds')?.credentialDefinitionId,\n meta.get?.('credentialDefinitionId'),\n record.credentialDefinitionId,\n ]\n return candidates.find((v) => typeof v === 'string' && v.length > 0)\n}\n\n/**\n * Returns the value of the `kanonCredId` attribute from the credential record's\n * credentialAttributes list.\n */\n// biome-ignore lint/suspicious/noExplicitAny: record shape varies\nfunction extractKanonCredId(record: any): string | undefined {\n // biome-ignore lint/suspicious/noExplicitAny: attribute shape varies\n const attrs: any[] = Array.isArray(record?.credentialAttributes) ? record.credentialAttributes : []\n const attr = attrs.find((a) => a?.name === KANON_CRED_ID_ATTRIBUTE)\n return typeof attr?.value === 'string' ? attr.value : undefined\n}\n\n/**\n * Map the credential's domain attributes onto BN254 felts using the SDK's\n * CANONICAL ordering (lexicographic byte sort of attribute names,\n * SDK-reserved names excluded). Same encoder the prep step and the holder\n * wrapper use — the three sites produce identical felt arrays from the\n * same value map regardless of how anoncreds-rs ordered the\n * `credentialAttributes` array under the hood.\n */\n// biome-ignore lint/suspicious/noExplicitAny: record shape varies\nfunction extractLeafAttributes(record: any): bigint[] {\n // biome-ignore lint/suspicious/noExplicitAny: attr shape varies\n const attrs: any[] = Array.isArray(record?.credentialAttributes) ? record.credentialAttributes : []\n const values: Record<string, string> = {}\n for (const a of attrs) {\n const name = a?.name\n if (typeof name !== 'string') continue\n values[name] = typeof a?.value === 'string' ? a.value : ''\n }\n return encodeAttributesCanonical(values)\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAMA,kBAAgB;AACtB,MAAMC,kBAAgB;AAYf,iCAAM,qBAAqB;CAOhC,AAAO,YACL,AAAiB,eACjB,AAAiB,WACjB;EAFiB;EACA;OARX,gCAAgB,IAAI,KAA2B;OAI/C,kCAAkB,IAAI,KAAqB;;;;;;CAWnD,AAAO,OAAO,cAAkC;AAQ9C,MAAI,CADc,KAAK,cAAc,4BAA4B,CAE/D,cAAa,OAAO,OAAO,KACzB,wKACD;AAEH,MAAI,KAAK,cAAc,IAAI,aAAa,qBAAqB,CAAE;EAO/D,MAAM,MALe,aAAa,kBAAkB,QAAQ,aAAa,CACzC,WAC9B,4BAA4B,8BAC7B,CAEsB,UAAU,OAAO,UAAU;AAChD,OAAI;AACF,UAAM,KAAK,6BAA6B,cAAc,MAAM,QAAQ;YAC7D,KAAK;IACZ,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AAChE,iBAAa,OAAO,OAAO,MACzB,gEAAgE,UACjE;;IAEH;AAEF,OAAK,cAAc,IAAI,aAAa,sBAAsB,IAAI;;CAGhE,AAAO,OAAO,cAAkC;EAC9C,MAAM,MAAM,KAAK,cAAc,IAAI,aAAa,q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;AACjC,MAAI;GACF,MAAM,OAAO,MAAM,KAAK,cAAc,OAAO,iBAAiB,UAAU;AACxE,QAAK,gBAAgB,IAAI,WAAW,KAAK;AACzC,UAAO;WACA,KAAK;GAIZ,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;AAChE,gBAAa,OAAO,OAAO,KACzB,0CAA0C,UAAU,YAAY,QAAQ,gCACzE;AACD,QAAK,gBAAgB,IAAI,WAAWD,gBAAc;AAClD,UAAOA;;;;mCA5JZ,YAAY;;;;;AAsKb,SAAS,iBAAiB,QAAiC;CACzD,MAAM,OAAO,QAAQ;AACrB,KAAI,CAAC,KAAM,QAAO;AAQlB,QAPmB;EACjB,KAAK,MAAM,wBAAwB,EAAE;EACrC,KAAK,MAAM,wBAAwB,EAAE;EACrC,KAAK,MAAM,sBAAsB,EAAE;EACnC,KAAK,MAAM,yBAAyB;EACpC,OAAO;EACR,CACiB,MAAM,MAAM,OAAO,MAAM,YAAY,EAAE,SAAS,EAAE;;;;;;AAQtE,SAAS,mBAAmB,QAAiC;CAG3D,MAAM,QADe,MAAM,QAAQ,QAAQ,qBAAqB,GAAG,OAAO,uBAAuB,EAAE,EAChF,MAAM,MAAM,GAAG,SAASE,0BAAwB;AACnE,QAAO,OAAO,MAAM,UAAU,WAAW,KAAK,QAAQ;;;;;;;;;;AAYxD,SAAS,sBAAsB,QAAuB;CAEpD,MAAM,QAAe,MAAM,QAAQ,QAAQ,qBAAqB,GAAG,OAAO,uBAAuB,EAAE;CACnG,MAAM,SAAiC,EAAE;AACzC,MAAK,MAAM,KAAK,OAAO;EACrB,MAAM,OAAO,GAAG;AAChB,MAAI,OAAO,SAAS,SAAU;AAC9B,SAAO,QAAQ,OAAO,GAAG,UAAU,WAAW,EAAE,QAAQ;;AAE1D,QAAO,0BAA0B,OAAO"}
@@ -0,0 +1,82 @@
1
+ import { KanonClientService } from "../../ledger/KanonClientService.js";
2
+ import "../../ledger/index.js";
3
+ import { KanonZkPathService } from "../../zk/KanonZkPathService.js";
4
+ import { AgentContext, W3cJsonLdVerifiableCredential, W3cJsonLdVerifiablePresentation } from "@credo-ts/core";
5
+ import * as _credo_ts_anoncreds0 from "@credo-ts/anoncreds";
6
+ import { AnonCredsCredentialInfo, AnonCredsHolderService, AnonCredsProof, CreateCredentialRequestOptions, CreateCredentialRequestReturn, CreateLinkSecretOptions, CreateLinkSecretReturn, CreateProofOptions, CreateW3cPresentationOptions, GetCredentialOptions, GetCredentialsForProofRequestOptions, GetCredentialsForProofRequestReturn, GetCredentialsOptions, LegacyToW3cCredentialOptions, StoreCredentialOptions, W3cToLegacyCredentialOptions } from "@credo-ts/anoncreds";
7
+
8
+ //#region src/anoncreds/services/KanonWrappedAnonCredsHolderService.d.ts
9
+ /**
10
+ * DI token used by `KanonModule` to register the original
11
+ * `AnonCredsRsHolderService` so the wrapper can inject it without depending
12
+ * on a deep build path.
13
+ */
14
+ declare const OriginalAnonCredsHolderServiceSymbol: unique symbol;
15
+ /**
16
+ * Wraps the AnonCredsRsHolderService so Mode B presentations are entirely
17
+ * transparent to the application:
18
+ *
19
+ * - Before `createProof` runs, the wrapper inspects the selected
20
+ * credentials. For each credentialDefinitionId that opts into
21
+ * `TIER_ZK_SNARK` on chain, it generates the Groth16 non-revocation proof
22
+ * and injects it as a self-attested attribute named
23
+ * `kanon_<credDefId>_zkProof`.
24
+ *
25
+ * - The presentation that goes over the wire is a plain AnonCreds
26
+ * presentation. The self-attested attribute rides as a normal
27
+ * `requested_proof.self_attested_attrs` entry — anything that speaks
28
+ * AnonCreds can deserialize it, and the corresponding
29
+ * `KanonWrappedAnonCredsVerifierService` will verify it on chain.
30
+ *
31
+ * - For Mode-A-only and non-Kanon credentials the wrapper is a no-op; the
32
+ * inner service handles them unchanged.
33
+ *
34
+ * - Other methods on `AnonCredsHolderService` (createCredentialRequest,
35
+ * storeCredential, getCredentials, …) delegate to inner without
36
+ * modification.
37
+ *
38
+ * No DIDComm message extension, no proof-format URI change, no client-side
39
+ * coordination: the holder just calls `agent.modules.proofs.acceptRequest(…)`
40
+ * and the wrapper does the rest.
41
+ */
42
+ declare class KanonWrappedAnonCredsHolderService implements AnonCredsHolderService {
43
+ private readonly inner;
44
+ private readonly clientService;
45
+ private readonly pathService;
46
+ /** Per-credDef on-chain policyMask cache; immutable after registration. */
47
+ private readonly policyCache;
48
+ constructor(inner: AnonCredsHolderService, clientService: KanonClientService, pathService: KanonZkPathService);
49
+ createProof(agentContext: AgentContext, options: CreateProofOptions): Promise<AnonCredsProof>;
50
+ createLinkSecret(agentContext: AgentContext, options: CreateLinkSecretOptions): Promise<CreateLinkSecretReturn>;
51
+ createCredentialRequest(agentContext: AgentContext, options: CreateCredentialRequestOptions): Promise<CreateCredentialRequestReturn>;
52
+ storeCredential(agentContext: AgentContext, options: StoreCredentialOptions, metadata?: Record<string, unknown>): Promise<string>;
53
+ getCredential(agentContext: AgentContext, options: GetCredentialOptions): Promise<AnonCredsCredentialInfo>;
54
+ getCredentials(agentContext: AgentContext, options: GetCredentialsOptions): Promise<AnonCredsCredentialInfo[]>;
55
+ deleteCredential(agentContext: AgentContext, credentialId: string): Promise<void>;
56
+ getCredentialsForProofRequest(agentContext: AgentContext, options: GetCredentialsForProofRequestOptions): Promise<GetCredentialsForProofRequestReturn>;
57
+ createW3cPresentation(agentContext: AgentContext, options: CreateW3cPresentationOptions): Promise<W3cJsonLdVerifiablePresentation>;
58
+ w3cToLegacyCredential(agentContext: AgentContext, options: W3cToLegacyCredentialOptions): Promise<_credo_ts_anoncreds0.AnonCredsCredential>;
59
+ legacyToW3cCredential(agentContext: AgentContext, options: LegacyToW3cCredentialOptions): Promise<W3cJsonLdVerifiableCredential>;
60
+ generateNonce(agentContext: AgentContext): string;
61
+ /**
62
+ * For every Mode B credential referenced in `selectedCredentials`, compute
63
+ * the SNARK proof and add it to `selfAttestedAttributes` under
64
+ * `kanon_<credDefId>_zkProof`. The original options object is left
65
+ * untouched — we return a shallow copy with augmented self-attested attrs.
66
+ */
67
+ private augmentSelfAttested;
68
+ private buildZkProofAttr;
69
+ private getPolicyMask;
70
+ /**
71
+ * Bind the SNARK challenge to the verifier's session. We use the
72
+ * `proofRequest.nonce` directly — AnonCreds already guarantees freshness
73
+ * + binding to this exchange, which is exactly the property the verifier
74
+ * needs to detect replay.
75
+ */
76
+ private challengeFromProofRequest;
77
+ }
78
+ /** `kanon_<credDefId>_zkProof` — the self-attested attribute name we inject. */
79
+ declare function kanonZkProofReferent(credDefId: string): string;
80
+ //#endregion
81
+ export { KanonWrappedAnonCredsHolderService, OriginalAnonCredsHolderServiceSymbol, kanonZkProofReferent };
82
+ //# sourceMappingURL=KanonWrappedAnonCredsHolderService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KanonWrappedAnonCredsHolderService.d.ts","names":[],"sources":["../../../src/anoncreds/services/KanonWrappedAnonCredsHolderService.ts"],"mappings":";;;;;;;;;;;AA+CA;;cAAa,oCAAA;;;AAmCb;;;;;;;;;;;;;;;;;;;;;;;;;cACa,kCAAA,YAA8C,sBAAA;EAAA,iBAKQ,KAAA;EAAA,iBAC9C,aAAA;EAAA,iBACA,WAAA;EAqDhB;EAAA,iBA1Dc,WAAA;cAGgD,KAAA,EAAO,sBAAA,EACrD,aAAA,EAAe,kBAAA,EACf,WAAA,EAAa,kBAAA;EAGnB,WAAA,CACX,YAAA,EAAc,YAAA,EACd,OAAA,EAAS,kBAAA,GACR,OAAA,CAAQ,cAAA;EAeJ,gBAAA,CACL,YAAA,EAAc,YAAA,EACd,OAAA,EAAS,uBAAA,GACR,OAAA,CAAQ,sBAAA;EAIJ,uBAAA,CACL,YAAA,EAAc,YAAA,EACd,OAAA,EAAS,8BAAA,GACR,OAAA,CAAQ,6BAAA;EAIJ,eAAA,CACL,YAAA,EAAc,YAAA,EACd,OAAA,EAAS,sBAAA,EACT,QAAA,GAAW,MAAA,oBACV,OAAA;EAII,aAAA,CACL,YAAA,EAAc,YAAA,EACd,OAAA,EAAS,oBAAA,GACR,OAAA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