zklicensing 0.1.0-beta.2 → 0.1.0-beta.4

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 (173) hide show
  1. package/README.md +335 -97
  2. package/build/appsLookup.d.ts +14 -0
  3. package/build/appsLookup.d.ts.map +1 -0
  4. package/build/appsLookup.js +12 -0
  5. package/build/appsLookup.js.map +1 -0
  6. package/build/archiveBootstrap.d.ts +15 -1
  7. package/build/archiveBootstrap.d.ts.map +1 -0
  8. package/build/archiveBootstrap.js +62 -9
  9. package/build/archiveBootstrap.js.map +1 -0
  10. package/build/bindClient.d.ts +51 -0
  11. package/build/bindClient.d.ts.map +1 -0
  12. package/build/bindClient.js +115 -0
  13. package/build/bindClient.js.map +1 -0
  14. package/build/buyClient.d.ts +10 -3
  15. package/build/buyClient.d.ts.map +1 -0
  16. package/build/buyClient.js +33 -15
  17. package/build/buyClient.js.map +1 -0
  18. package/build/contractInterface.d.ts +11 -5
  19. package/build/contractInterface.d.ts.map +1 -0
  20. package/build/contractInterface.js +82 -17
  21. package/build/contractInterface.js.map +1 -0
  22. package/build/countryStats.d.ts +6 -1
  23. package/build/countryStats.d.ts.map +1 -0
  24. package/build/countryStats.js +33 -9
  25. package/build/countryStats.js.map +1 -0
  26. package/build/deployClient.d.ts.map +1 -0
  27. package/build/deployClient.js +1 -1
  28. package/build/deployClient.js.map +1 -0
  29. package/build/deviceIdentity.d.ts +68 -0
  30. package/build/deviceIdentity.d.ts.map +1 -0
  31. package/build/deviceIdentity.js +209 -0
  32. package/build/deviceIdentity.js.map +1 -0
  33. package/build/freezeClient.d.ts.map +1 -0
  34. package/build/freezeClient.js +1 -1
  35. package/build/freezeClient.js.map +1 -0
  36. package/build/generationClient.d.ts +1 -0
  37. package/build/generationClient.d.ts.map +1 -0
  38. package/build/generationClient.js +2 -2
  39. package/build/generationClient.js.map +1 -0
  40. package/build/index.d.ts +27 -37
  41. package/build/index.d.ts.map +1 -0
  42. package/build/index.js +85 -116
  43. package/build/index.js.map +1 -0
  44. package/build/licenseLeaf.d.ts +76 -0
  45. package/build/licenseLeaf.d.ts.map +1 -0
  46. package/build/licenseLeaf.js +189 -0
  47. package/build/licenseLeaf.js.map +1 -0
  48. package/build/licenseRecord.d.ts +20 -1
  49. package/build/licenseRecord.d.ts.map +1 -0
  50. package/build/licenseRecord.js +1 -1
  51. package/build/licenseRecord.js.map +1 -0
  52. package/build/licenseStore.d.ts +17 -2
  53. package/build/licenseStore.d.ts.map +1 -0
  54. package/build/licenseStore.js +167 -7
  55. package/build/licenseStore.js.map +1 -0
  56. package/build/manifestVerify.d.ts.map +1 -0
  57. package/build/manifestVerify.js +8 -3
  58. package/build/manifestVerify.js.map +1 -0
  59. package/build/migrateClient.d.ts +6 -21
  60. package/build/migrateClient.d.ts.map +1 -0
  61. package/build/migrateClient.js +30 -17
  62. package/build/migrateClient.js.map +1 -0
  63. package/build/onChainRoot.d.ts +67 -0
  64. package/build/onChainRoot.d.ts.map +1 -0
  65. package/build/onChainRoot.js +87 -0
  66. package/build/onChainRoot.js.map +1 -0
  67. package/build/ownershipLicenseHash.d.ts +25 -0
  68. package/build/ownershipLicenseHash.d.ts.map +1 -0
  69. package/build/ownershipLicenseHash.js +29 -0
  70. package/build/ownershipLicenseHash.js.map +1 -0
  71. package/build/ownershipSignature.d.ts +122 -0
  72. package/build/ownershipSignature.d.ts.map +1 -0
  73. package/build/ownershipSignature.js +244 -0
  74. package/build/ownershipSignature.js.map +1 -0
  75. package/build/proveErrors.d.ts +35 -0
  76. package/build/proveErrors.d.ts.map +1 -0
  77. package/build/proveErrors.js +49 -0
  78. package/build/proveErrors.js.map +1 -0
  79. package/build/refundClient.d.ts +2 -11
  80. package/build/refundClient.d.ts.map +1 -0
  81. package/build/refundClient.js +35 -17
  82. package/build/refundClient.js.map +1 -0
  83. package/build/renewClient.d.ts +4 -1
  84. package/build/renewClient.d.ts.map +1 -0
  85. package/build/renewClient.js +11 -4
  86. package/build/renewClient.js.map +1 -0
  87. package/build/seatName.d.ts +8 -0
  88. package/build/seatName.d.ts.map +1 -0
  89. package/build/seatName.js +136 -0
  90. package/build/seatName.js.map +1 -0
  91. package/build/statsClient.d.ts +47 -4
  92. package/build/statsClient.d.ts.map +1 -0
  93. package/build/statsClient.js +44 -5
  94. package/build/statsClient.js.map +1 -0
  95. package/build/trustAnchorVerify.d.ts +48 -0
  96. package/build/trustAnchorVerify.d.ts.map +1 -0
  97. package/build/trustAnchorVerify.js +431 -0
  98. package/build/trustAnchorVerify.js.map +1 -0
  99. package/build/trustAnchorVerifyCli.d.ts +35 -0
  100. package/build/trustAnchorVerifyCli.d.ts.map +1 -0
  101. package/build/trustAnchorVerifyCli.js +177 -0
  102. package/build/trustAnchorVerifyCli.js.map +1 -0
  103. package/build/txBroadcastClient.d.ts +26 -0
  104. package/build/txBroadcastClient.d.ts.map +1 -0
  105. package/build/txBroadcastClient.js +20 -0
  106. package/build/txBroadcastClient.js.map +1 -0
  107. package/build/unbindClient.d.ts +56 -0
  108. package/build/unbindClient.d.ts.map +1 -0
  109. package/build/unbindClient.js +113 -0
  110. package/build/unbindClient.js.map +1 -0
  111. package/build/vendorAccountClient.d.ts +56 -0
  112. package/build/vendorAccountClient.d.ts.map +1 -0
  113. package/build/vendorAccountClient.js +47 -0
  114. package/build/vendorAccountClient.js.map +1 -0
  115. package/build/verifyCore.d.ts +1 -1
  116. package/build/verifyCore.d.ts.map +1 -0
  117. package/build/verifyCore.js +11 -4
  118. package/build/verifyCore.js.map +1 -0
  119. package/build/verifyOffline.d.ts +85 -0
  120. package/build/verifyOffline.d.ts.map +1 -0
  121. package/build/verifyOffline.js +139 -0
  122. package/build/verifyOffline.js.map +1 -0
  123. package/build/verifyService.d.ts.map +1 -0
  124. package/build/verifyService.js +582 -455
  125. package/build/verifyService.js.map +1 -0
  126. package/build/verifyWithAncestors.d.ts +18 -0
  127. package/build/verifyWithAncestors.d.ts.map +1 -0
  128. package/build/verifyWithAncestors.js +119 -0
  129. package/build/verifyWithAncestors.js.map +1 -0
  130. package/build/zipToState.d.ts +2 -0
  131. package/build/zipToState.d.ts.map +1 -0
  132. package/build/zipToState.js +94 -0
  133. package/build/zipToState.js.map +1 -0
  134. package/package.json +57 -13
  135. package/src/appsLookup.ts +48 -0
  136. package/src/archiveBootstrap.ts +342 -0
  137. package/src/bindClient.ts +175 -0
  138. package/src/buyClient.ts +304 -0
  139. package/src/contractInterface.d.ts +61 -0
  140. package/src/contractInterface.ts +313 -0
  141. package/src/countryStats.ts +171 -0
  142. package/src/deployClient.ts +388 -0
  143. package/src/deviceIdentity.ts +249 -0
  144. package/src/freezeClient.ts +117 -0
  145. package/src/generationClient.ts +165 -0
  146. package/src/index.ts +329 -0
  147. package/src/licenseLeaf.ts +221 -0
  148. package/src/licenseRecord.ts +108 -0
  149. package/src/licenseStore.ts +538 -0
  150. package/src/manifestVerify.ts +111 -0
  151. package/src/migrateClient.ts +84 -0
  152. package/src/onChainRoot.ts +107 -0
  153. package/src/ownershipLicenseHash.ts +31 -0
  154. package/src/ownershipSignature.ts +354 -0
  155. package/src/proveErrors.ts +70 -0
  156. package/src/refundClient.ts +158 -0
  157. package/src/renewClient.ts +214 -0
  158. package/src/seatName.ts +165 -0
  159. package/src/statsClient.ts +235 -0
  160. package/src/trustAnchorVerify.ts +548 -0
  161. package/src/trustAnchorVerifyCli.ts +179 -0
  162. package/src/txBroadcastClient.ts +48 -0
  163. package/src/unbindClient.ts +149 -0
  164. package/src/vendorAccountClient.ts +110 -0
  165. package/src/verifyCore.ts +92 -0
  166. package/src/verifyOffline.ts +212 -0
  167. package/src/verifyService.ts +969 -0
  168. package/src/verifyWithAncestors.ts +153 -0
  169. package/src/zipToState.ts +94 -0
  170. package/build/licenseProof.d.ts +0 -26
  171. package/build/licenseProof.js +0 -41
  172. package/build/ownership.d.ts +0 -34
  173. package/build/ownership.js +0 -147
@@ -0,0 +1,548 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * trustAnchorVerify.ts
6
+ *
7
+ * End-to-end trust-anchor verification for a single zkLicensing app.
8
+ *
9
+ * Given a vendor origin + a zkApp address + one or more pinned platform
10
+ * manifest public keys, this module performs the full "does this vendor
11
+ * page point at a real zkLicensing deployment for this vendor?" pipeline
12
+ * that the trust-anchor page walks a human buyer through — mechanically,
13
+ * with structured findings suitable for CI, monitoring, or a
14
+ * wallet/extension consumer.
15
+ *
16
+ * The verifier is address-keyed: buyers see zkApp addresses in their
17
+ * wallet popup, not opaque platform appIds, so the primary lookup is by
18
+ * address. The signed manifest served at
19
+ * `<origin>/.well-known/zklicensing/<zkAppAddress>.json` carries the
20
+ * appId inside its signed payload, so callers never need to know the
21
+ * appId out-of-band.
22
+ *
23
+ * Pipeline (each step yields a discrete Finding — no boolean collapse):
24
+ *
25
+ * 1. manifest_fetch — GET https://<origin>/.well-known/zklicensing/<address>.json
26
+ * 2. manifest_signature — Ed25519 verify against caller-provided pinned keys
27
+ * 3. manifest_address_in_generations — opts.address appears in the signed generations[]
28
+ * 3b. manifest_matches_backend — (opt-in, opts.crossCheck) vendor payload equals
29
+ * zklicensing.com/apps/by-address/<address> after
30
+ * independent signature-verify against same pins
31
+ * 4. chain_account_exists — fetchAccount succeeds at the address
32
+ * 5. chain_zkapp_uri_match — on-chain zkappUri equals opts.origin
33
+ * 6. chain_vk_hash_pinned — on-chain verification-key hash equals CANONICAL_VK_HASHES[generation]
34
+ * 7. chain_set_zkapp_uri_impossible — permissions.setZkappUri === Permissions.impossible()
35
+ * 8. chain_set_permissions_impossible — permissions.setPermissions === Permissions.impossible() (meta-freeze)
36
+ * 9. chain_set_verification_key_locked — permissions.setVerificationKey.auth === Permissions.impossible()
37
+ * 10. chain_send_proof_only — permissions.send === Permissions.proof()
38
+ * 11. chain_edit_state_proof_only — permissions.editState === Permissions.proof()
39
+ *
40
+ * Steps 5 + 7 close the URI-binding loop: (5) proves the contract claims
41
+ * this origin, (7) proves nobody can rewrite that claim. Steps 8–11 verify
42
+ * the rest of LicensingApp.init()'s permission matrix — catching the case
43
+ * where a deployer used the correct VK but skipped/altered init(), leaving
44
+ * default `signature()` permissions that would still let the deploy key
45
+ * drain escrow, rewrite state, or swap the circuit.
46
+ *
47
+ * o1js is a peer dependency — this file imports it dynamically so callers
48
+ * that only want the manifest checks (no chain reads) can construct one
49
+ * with `skipChainChecks: true` and avoid the o1js install.
50
+ *
51
+ * The pinned pubkey list is caller-supplied — the SDK ships NO baked-in
52
+ * pin. Source it from https://zklicensing.com/trustanchor.html (published
53
+ * next to each generation's VK hash). See the SDK README for details.
54
+ */
55
+
56
+ import { verifyManifestSignature, canonicalize } from './manifestVerify.js';
57
+
58
+ export type Finding = {
59
+ /** Machine-readable check identifier, stable across releases. */
60
+ name: string;
61
+ /** True iff the check passed. */
62
+ ok: boolean;
63
+ /** Human-readable one-line summary or reason. */
64
+ detail: string;
65
+ };
66
+
67
+ export type TrustAnchorReport = {
68
+ /** True iff every finding is ok. */
69
+ ok: boolean;
70
+ origin: string;
71
+ /** Address that was checked. Echoed from opts.address. */
72
+ address: string;
73
+ /** appId as declared in the signed manifest payload. Undefined if the fetch/signature failed. */
74
+ appId?: string;
75
+ /** Generation index the address maps to in the signed manifest (1-based). */
76
+ generation?: number;
77
+ findings: Finding[];
78
+ };
79
+
80
+ export interface VerifyTrustAnchorOpts {
81
+ /** Vendor origin, e.g. `https://store.example.com`. HTTPS required. */
82
+ origin: string;
83
+ /** zkApp address (base58 PublicKey) — the manifest lives at `/.well-known/zklicensing/<address>.json`. */
84
+ address: string;
85
+ /** Platform manifest Ed25519 public keys (base64). Comma-list from `VITE_MANIFEST_PUBKEYS`. */
86
+ pinnedPublicKeysBase64: readonly string[];
87
+ /** Mina GraphQL endpoint for on-chain reads. Ignored when `skipChainChecks` is true. */
88
+ minaGraphqlUrl?: string;
89
+ /** Optional Mina networkId — 'mainnet' or 'testnet'. Defaults to 'mainnet'. */
90
+ minaNetworkId?: 'mainnet' | 'testnet' | 'devnet';
91
+ /** Fetch timeout in ms for the manifest fetch. Default 15000. */
92
+ fetchTimeoutMs?: number;
93
+ /** When true, skips all `chain_*` checks. Useful for manifest-only audits. */
94
+ skipChainChecks?: boolean;
95
+ /**
96
+ * When true, runs an extra `manifest_matches_backend` finding: fetch the
97
+ * same signed payload from `https://zklicensing.com/apps/by-address/{address}`,
98
+ * verify it against the same pinned keys, then byte-compare canonicalized
99
+ * payloads (minus `signature`, `publicKey`, `issuedAt`, `app`). Catches a
100
+ * vendor serving a stale/rolled-back manifest even when its own signature
101
+ * is still valid. Not on by default — adds a second network fetch and
102
+ * couples the verifier to zklicensing.com being reachable.
103
+ */
104
+ crossCheck?: boolean;
105
+ }
106
+
107
+ // Production keeper is mounted under /api/keeper on zklicensing.com — the
108
+ // bare /apps/... paths return 404 (they're not the app route, they're an
109
+ // unrelated marketing route). This is the concrete URL prefix, not just an
110
+ // origin.
111
+ const BACKEND_URL_PREFIX = 'https://zklicensing.com/api/keeper';
112
+
113
+ const DEFAULT_FETCH_TIMEOUT_MS = 15000;
114
+
115
+ function normalizeOrigin(origin: string): string {
116
+ return origin.replace(/\/+$/, '');
117
+ }
118
+
119
+ // Strip trailing slash / path from a URL so we can compare against zkappUri,
120
+ // which vendors typically set to their bare origin.
121
+ function urlOrigin(url: string): string | null {
122
+ try {
123
+ const u = new URL(url);
124
+ return `${u.protocol}//${u.host}`;
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+
130
+ type Generation = {
131
+ gen: number;
132
+ zkAppAddress: string;
133
+ status: 'retired' | 'live';
134
+ frozenRoot?: string;
135
+ deployedAt?: string;
136
+ retiredAt?: string;
137
+ // On-chain permissions.setVerificationKey.txnVersion recorded by the keeper
138
+ // at manifest-assembly time. Optional for backwards compatibility with
139
+ // older manifests written before the field existed.
140
+ deployTxnVersion?: number;
141
+ };
142
+
143
+ type ManifestPayload = {
144
+ appId: string;
145
+ current: number;
146
+ generations: Generation[];
147
+ issuedAt: string;
148
+ };
149
+
150
+ async function fetchManifest(
151
+ origin: string,
152
+ address: string,
153
+ timeoutMs: number,
154
+ ): Promise<Finding & { body?: unknown }> {
155
+ const originOk = origin.startsWith('https://');
156
+ if (!originOk) {
157
+ return { name: 'manifest_fetch', ok: false, detail: 'origin must be https://' };
158
+ }
159
+ let manifestUrl: string;
160
+ try {
161
+ manifestUrl = new URL(`/.well-known/zklicensing/${encodeURIComponent(address)}.json`, origin).href;
162
+ } catch {
163
+ return { name: 'manifest_fetch', ok: false, detail: 'origin is not a valid URL' };
164
+ }
165
+ const controller = new AbortController();
166
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
167
+ try {
168
+ const resp = await fetch(manifestUrl, { signal: controller.signal, redirect: 'follow' });
169
+ if (!resp.ok) {
170
+ return { name: 'manifest_fetch', ok: false, detail: `HTTP ${resp.status} from ${manifestUrl}` };
171
+ }
172
+ const text = await resp.text();
173
+ let parsed: unknown;
174
+ try { parsed = JSON.parse(text); }
175
+ catch { return { name: 'manifest_fetch', ok: false, detail: 'response is not valid JSON' }; }
176
+ return { name: 'manifest_fetch', ok: true, detail: `fetched ${manifestUrl}`, body: parsed };
177
+ } catch (err: any) {
178
+ return { name: 'manifest_fetch', ok: false, detail: `fetch failed: ${err?.message ?? String(err)}` };
179
+ } finally {
180
+ clearTimeout(timer);
181
+ }
182
+ }
183
+
184
+ // Split a raw manifest JSON into { signature, payload }. The keeper writes the
185
+ // payload fields at the top level plus { signature, publicKey } — we ignore
186
+ // publicKey (never trust the payload's self-declared key; only the
187
+ // caller-pinned list is authoritative). The same signed bytes are served at
188
+ // every /.well-known/zklicensing/<address>.json — one file per generation
189
+ // address, all carrying the same appId in the payload.
190
+ function splitManifest(raw: unknown): { signature: string | null; payload: ManifestPayload | null } {
191
+ if (!raw || typeof raw !== 'object') return { signature: null, payload: null };
192
+ const r = raw as Record<string, unknown>;
193
+ const signature = typeof r.signature === 'string' ? r.signature : null;
194
+ const { signature: _s, publicKey: _p, ...rest } = r;
195
+ const payload = rest as unknown as ManifestPayload;
196
+ if (
197
+ typeof payload.appId !== 'string' ||
198
+ typeof payload.current !== 'number' ||
199
+ !Array.isArray(payload.generations) ||
200
+ typeof payload.issuedAt !== 'string'
201
+ ) {
202
+ return { signature, payload: null };
203
+ }
204
+ return { signature, payload };
205
+ }
206
+
207
+ // Optional cross-check against the zkLicensing backend's own copy of the
208
+ // signed generation list. Fetches `https://zklicensing.com/apps/by-address/
209
+ // {address}`, verifies its signature against the same caller-pinned keys (so
210
+ // a compromised backend URL cannot lie), strips signature/publicKey/issuedAt/
211
+ // app, and byte-compares canonicalized payloads against the vendor's
212
+ // `.well-known` copy. `issuedAt` is stripped because the backend re-stamps on
213
+ // every call; `app` is stripped because it is an unsigned envelope field the
214
+ // by-address endpoint tacks on.
215
+ async function checkBackendMatch(args: {
216
+ address: string;
217
+ vendorPayload: ManifestPayload;
218
+ pinnedPublicKeysBase64: readonly string[];
219
+ timeoutMs: number;
220
+ }): Promise<Finding> {
221
+ const name = 'manifest_matches_backend';
222
+ const url = `${BACKEND_URL_PREFIX}/apps/by-address/${encodeURIComponent(args.address)}`;
223
+ const controller = new AbortController();
224
+ const timer = setTimeout(() => controller.abort(), args.timeoutMs);
225
+ let body: any;
226
+ try {
227
+ const resp = await fetch(url, { signal: controller.signal, redirect: 'follow' });
228
+ if (!resp.ok) return { name, ok: false, detail: `backend HTTP ${resp.status} from ${url}` };
229
+ body = await resp.json();
230
+ } catch (err: any) {
231
+ return { name, ok: false, detail: `backend fetch failed: ${err?.message ?? String(err)}` };
232
+ } finally {
233
+ clearTimeout(timer);
234
+ }
235
+ if (!body || typeof body !== 'object') {
236
+ return { name, ok: false, detail: 'backend response is not a JSON object' };
237
+ }
238
+ const { signature, publicKey: _pub, app: _app, ...backendPayload } = body as Record<string, unknown>;
239
+ if (typeof signature !== 'string') {
240
+ return { name, ok: false, detail: 'backend response missing signature' };
241
+ }
242
+ const kSigOk = await verifyManifestSignature(backendPayload, signature, args.pinnedPublicKeysBase64);
243
+ if (!kSigOk) {
244
+ return { name, ok: false, detail: 'backend response signature does not verify against pinned keys' };
245
+ }
246
+ const { issuedAt: _kIA, ...kRest } = backendPayload as Record<string, unknown>;
247
+ const { issuedAt: _vIA, ...vRest } = args.vendorPayload as unknown as Record<string, unknown>;
248
+ if (canonicalize(kRest) !== canonicalize(vRest)) {
249
+ return { name, ok: false, detail: 'vendor manifest content diverges from backend record (stale or drifted)' };
250
+ }
251
+ return { name, ok: true, detail: `vendor payload matches backend /apps/by-address/${args.address}` };
252
+ }
253
+
254
+ type ChainState = {
255
+ zkappUri?: string;
256
+ vkHash?: string;
257
+ // Each flag mirrors one line of LicensingApp.init()'s permissions matrix.
258
+ // undefined means the field could not be read from chain.
259
+ setZkappUriIsImpossible?: boolean;
260
+ setPermissionsIsImpossible?: boolean;
261
+ // setVerificationKey uses VerificationKey.impossibleDuringCurrentVersion(),
262
+ // which stores {auth: Impossible, txnVersion: currentChainTxnVersion} on the
263
+ // account. After a Mina hardfork the chain's current txnVersion advances
264
+ // past the stored value and the effective enforcement falls back to
265
+ // signature() by design — but the deploy key was discarded at deploy time
266
+ // (see LicensingApp.ts:546-547), so no one can sign the fallback update.
267
+ //
268
+ // We read both the stored auth string AND the stored txnVersion so the
269
+ // verifier can bind on-chain state to the manifest-recorded deployTxnVersion.
270
+ setVerificationKeyAuth?: string;
271
+ setVerificationKeyTxnVersion?: number;
272
+ sendIsProof?: boolean;
273
+ editStateIsProof?: boolean;
274
+ accountFound: boolean;
275
+ fetchError?: string;
276
+ };
277
+
278
+ // Converts an o1js-decoded Permission (three booleans) back to its canonical
279
+ // enum string. Mirrors the switch inside o1js's own AuthRequired.toJSON — kept
280
+ // inline because o1js doesn't publicly export it.
281
+ function permToString(p: any): string | undefined {
282
+ const b = (v: any) => (typeof v?.toBoolean === 'function' ? v.toBoolean() : Boolean(v)) ? 1 : 0;
283
+ const key = `${b(p?.constant)}${b(p?.signatureNecessary)}${b(p?.signatureSufficient)}`;
284
+ switch (key) {
285
+ case '110': return 'Impossible';
286
+ case '101': return 'None';
287
+ case '000': return 'Proof';
288
+ case '011': return 'Signature';
289
+ case '001': return 'Either';
290
+ default: return undefined;
291
+ }
292
+ }
293
+
294
+ // Reads the on-chain facts needed to close the trust loop for a single
295
+ // zkApp address. o1js is imported dynamically so this file can be pulled in
296
+ // by callers that don't need chain reads (e.g. an offline manifest audit).
297
+ async function readChainState(
298
+ address: string,
299
+ minaGraphqlUrl: string,
300
+ minaNetworkId: 'mainnet' | 'testnet' | 'devnet',
301
+ ): Promise<ChainState> {
302
+ let o1js: any;
303
+ try {
304
+ o1js = await import('o1js');
305
+ } catch (err: any) {
306
+ return {
307
+ accountFound: false,
308
+ fetchError: `o1js not installed — chain checks require o1js as a peer dep (${err?.message ?? err})`,
309
+ };
310
+ }
311
+ try {
312
+ // setActiveInstance mutates o1js global state. This is acceptable for a
313
+ // one-shot CLI; long-lived hosts should confine the call to their own
314
+ // network singleton and not use this helper.
315
+ const network = o1js.Mina.Network({
316
+ networkId: minaNetworkId === 'mainnet' ? 'mainnet' : 'testnet',
317
+ mina: minaGraphqlUrl,
318
+ });
319
+ o1js.Mina.setActiveInstance(network);
320
+ const publicKey = o1js.PublicKey.fromBase58(address);
321
+ const { account, error } = await o1js.fetchAccount({ publicKey });
322
+ if (!account) {
323
+ const detail = error
324
+ ? `${error.statusCode ?? ''} ${error.statusText ?? ''} ${error.errors ? JSON.stringify(error.errors) : ''}`.trim() || JSON.stringify(error)
325
+ : 'no account and no error returned';
326
+ return { accountFound: false, fetchError: `fetchAccount(${address}) via ${minaGraphqlUrl}: ${detail}` };
327
+ }
328
+ const zkappUri = account.zkapp?.zkappUri as string | undefined;
329
+ const vkHash = account.zkapp?.verificationKey?.hash?.toString?.();
330
+ const perms = account.permissions;
331
+ const setVkAuth = permToString(perms?.setVerificationKey?.auth);
332
+ const rawTxnVersion = perms?.setVerificationKey?.txnVersion;
333
+ const setVkTxnVersion = rawTxnVersion?.toString ? Number(rawTxnVersion.toString()) : undefined;
334
+ return {
335
+ accountFound: true,
336
+ zkappUri,
337
+ vkHash,
338
+ setZkappUriIsImpossible: permToString(perms?.setZkappUri) === 'Impossible',
339
+ setPermissionsIsImpossible: permToString(perms?.setPermissions) === 'Impossible',
340
+ setVerificationKeyAuth: setVkAuth,
341
+ setVerificationKeyTxnVersion: Number.isFinite(setVkTxnVersion) ? setVkTxnVersion : undefined,
342
+ sendIsProof: permToString(perms?.send) === 'Proof',
343
+ editStateIsProof: permToString(perms?.editState) === 'Proof',
344
+ };
345
+ } catch (err: any) {
346
+ return { accountFound: false, fetchError: err?.message ?? String(err) };
347
+ }
348
+ }
349
+
350
+ async function loadCanonicalVkHashes(): Promise<Readonly<Record<number, string>> | null> {
351
+ try {
352
+ const m = await import('./contractInterface.js');
353
+ return m.CANONICAL_VK_HASHES ?? null;
354
+ } catch {
355
+ return null;
356
+ }
357
+ }
358
+
359
+ export async function verifyTrustAnchor(opts: VerifyTrustAnchorOpts): Promise<TrustAnchorReport> {
360
+ const origin = normalizeOrigin(opts.origin);
361
+ const address = opts.address;
362
+ const findings: Finding[] = [];
363
+ const timeoutMs = opts.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
364
+
365
+ // 1. manifest_fetch
366
+ const fetchResult = await fetchManifest(origin, address, timeoutMs);
367
+ findings.push({ name: fetchResult.name, ok: fetchResult.ok, detail: fetchResult.detail });
368
+ if (!fetchResult.ok) {
369
+ return { ok: false, origin, address, findings };
370
+ }
371
+ const { signature, payload } = splitManifest(fetchResult.body);
372
+
373
+ // 2. manifest_signature
374
+ if (!signature || !payload) {
375
+ findings.push({ name: 'manifest_signature', ok: false, detail: 'manifest missing signature or payload fields' });
376
+ return { ok: false, origin, address, findings };
377
+ }
378
+ const sigOk = await verifyManifestSignature(payload, signature, opts.pinnedPublicKeysBase64);
379
+ findings.push({
380
+ name: 'manifest_signature',
381
+ ok: sigOk,
382
+ detail: sigOk
383
+ ? `Ed25519 verified against pinned key (1 of ${opts.pinnedPublicKeysBase64.length})`
384
+ : 'signature does not verify against any pinned key',
385
+ });
386
+ if (!sigOk) {
387
+ return { ok: false, origin, address, findings };
388
+ }
389
+
390
+ // appId is trusted only after signature verifies — it comes from the signed
391
+ // payload, not the caller.
392
+ const appId = payload.appId;
393
+
394
+ // 3. manifest_address_in_generations
395
+ const entry = payload.generations.find((g) => g.zkAppAddress === address);
396
+ findings.push({
397
+ name: 'manifest_address_in_generations',
398
+ ok: !!entry,
399
+ detail: entry
400
+ ? `address maps to gen ${entry.gen} (${entry.status})`
401
+ : `address ${address} not in manifest generations for app "${appId}"`,
402
+ });
403
+ const generation = entry?.gen;
404
+
405
+ // 3b. manifest_matches_backend (opt-in)
406
+ if (opts.crossCheck) {
407
+ findings.push(await checkBackendMatch({
408
+ address,
409
+ vendorPayload: payload,
410
+ pinnedPublicKeysBase64: opts.pinnedPublicKeysBase64,
411
+ timeoutMs,
412
+ }));
413
+ }
414
+
415
+ if (opts.skipChainChecks) {
416
+ const allOk = findings.every((f) => f.ok);
417
+ return { ok: allOk, origin, appId, address, generation, findings };
418
+ }
419
+
420
+ if (!opts.minaGraphqlUrl) {
421
+ findings.push({ name: 'chain_account_exists', ok: false, detail: 'minaGraphqlUrl is required for chain checks' });
422
+ return { ok: false, origin, appId, address, generation, findings };
423
+ }
424
+
425
+ // 4-11: chain reads
426
+ const state = await readChainState(address, opts.minaGraphqlUrl, opts.minaNetworkId ?? 'mainnet');
427
+ findings.push({
428
+ name: 'chain_account_exists',
429
+ ok: state.accountFound,
430
+ detail: state.accountFound ? `account ${address.slice(0, 12)}… found` : (state.fetchError ?? 'account not found'),
431
+ });
432
+ if (!state.accountFound) {
433
+ return { ok: false, origin, appId, address, generation, findings };
434
+ }
435
+
436
+ const onChainOrigin = state.zkappUri ? urlOrigin(state.zkappUri) : null;
437
+ const originClean = urlOrigin(origin);
438
+ const uriOk = !!state.zkappUri && !!onChainOrigin && !!originClean && onChainOrigin === originClean;
439
+ findings.push({
440
+ name: 'chain_zkapp_uri_match',
441
+ ok: uriOk,
442
+ detail: state.zkappUri
443
+ ? (uriOk ? `zkappUri "${state.zkappUri}" origin matches` : `zkappUri "${state.zkappUri}" origin ≠ "${originClean ?? origin}"`)
444
+ : 'zkappUri is empty on chain',
445
+ });
446
+
447
+ const canonicalVks = await loadCanonicalVkHashes();
448
+ const expectedVk = generation !== undefined ? canonicalVks?.[generation] : undefined;
449
+ const vkOk = !!state.vkHash && !!expectedVk && state.vkHash === expectedVk;
450
+ findings.push({
451
+ name: 'chain_vk_hash_pinned',
452
+ ok: vkOk,
453
+ detail: vkOk
454
+ ? `gen ${generation} hash matches CANONICAL_VK_HASHES[${generation}]`
455
+ : !expectedVk
456
+ ? `no CANONICAL_VK_HASHES entry for gen ${generation ?? '?'}`
457
+ : `on-chain vkHash "${state.vkHash?.slice(0, 16)}…" ≠ pinned "${expectedVk.slice(0, 16)}…"`,
458
+ });
459
+
460
+ findings.push({
461
+ name: 'chain_set_zkapp_uri_impossible',
462
+ ok: !!state.setZkappUriIsImpossible,
463
+ detail: state.setZkappUriIsImpossible
464
+ ? 'permissions.setZkappUri = impossible (zkappUri is frozen)'
465
+ : 'permissions.setZkappUri ≠ impossible — vendor could rewrite the URI',
466
+ });
467
+
468
+ // The meta-freeze: without this, every other permission lock below is
469
+ // reversible with a single signature. Priority #1 among the extras.
470
+ findings.push({
471
+ name: 'chain_set_permissions_impossible',
472
+ ok: !!state.setPermissionsIsImpossible,
473
+ detail: state.setPermissionsIsImpossible
474
+ ? 'permissions.setPermissions = impossible (permission matrix is meta-frozen)'
475
+ : 'permissions.setPermissions ≠ impossible — every other lock could be relaxed later',
476
+ });
477
+
478
+ // setVerificationKey lock, with hardfork-aware softening.
479
+ //
480
+ // The contract deploys with VerificationKey.impossibleDuringCurrentVersion(),
481
+ // which stores {auth: Impossible, txnVersion: <chain's txnVersion at deploy
482
+ // time>}. After a Mina hardfork the chain's current txnVersion advances
483
+ // past the stored value and the effective enforcement falls back to
484
+ // signature() — but the deploy key was discarded (LicensingApp.ts:546-547),
485
+ // so no one can sign the fallback update.
486
+ //
487
+ // The keeper records the deploy-time txnVersion in the signed manifest as
488
+ // deployTxnVersion. We accept two states as OK, provided the on-chain
489
+ // stored txnVersion still matches the manifest-recorded value (which proves
490
+ // no one has re-set the permission since deploy):
491
+ //
492
+ // - auth = Impossible → normal, pre-hardfork state
493
+ // - auth = Signature → post-hardfork fallback (see above)
494
+ //
495
+ // Any mismatch — different txnVersion, or auth is some other string, or
496
+ // deployTxnVersion missing from an old manifest — falls back to the strict
497
+ // rule (auth === 'Impossible').
498
+ const onChainAuth = state.setVerificationKeyAuth;
499
+ const onChainTxnVersion = state.setVerificationKeyTxnVersion;
500
+ const manifestDeployTxnVersion = entry?.deployTxnVersion;
501
+ let vkLockOk = false;
502
+ let vkLockDetail: string;
503
+ if (manifestDeployTxnVersion !== undefined && onChainTxnVersion !== undefined && onChainTxnVersion === manifestDeployTxnVersion) {
504
+ if (onChainAuth === 'Impossible') {
505
+ vkLockOk = true;
506
+ vkLockDetail = `permissions.setVerificationKey.auth = impossible (circuit cannot be swapped; txnVersion ${onChainTxnVersion} matches deploy)`;
507
+ } else if (onChainAuth === 'Signature') {
508
+ vkLockOk = true;
509
+ vkLockDetail = `permissions.setVerificationKey.auth = signature (post-hardfork fallback; deploy key was destroyed at deploy time; txnVersion ${onChainTxnVersion} matches deploy)`;
510
+ } else {
511
+ vkLockDetail = `permissions.setVerificationKey.auth = "${onChainAuth ?? '?'}" — expected impossible or signature`;
512
+ }
513
+ } else if (manifestDeployTxnVersion === undefined) {
514
+ // Older manifest without deployTxnVersion — fall back to strict.
515
+ vkLockOk = onChainAuth === 'Impossible';
516
+ vkLockDetail = vkLockOk
517
+ ? 'permissions.setVerificationKey.auth = impossible (circuit cannot be swapped; manifest omits deployTxnVersion — strict rule applied)'
518
+ : `permissions.setVerificationKey.auth = "${onChainAuth ?? '?'}" ≠ impossible — vendor could swap the circuit (manifest omits deployTxnVersion — strict rule applied)`;
519
+ } else {
520
+ vkLockDetail = `on-chain setVerificationKey.txnVersion (${onChainTxnVersion ?? 'unknown'}) ≠ manifest deployTxnVersion (${manifestDeployTxnVersion}) — permission may have been re-set since deploy`;
521
+ }
522
+ findings.push({
523
+ name: 'chain_set_verification_key_locked',
524
+ ok: vkLockOk,
525
+ detail: vkLockDetail,
526
+ });
527
+
528
+ // send + editState must be proof() (not signature()): withdrawals and Merkle
529
+ // root advances only happen via a valid LicensingApp proof.
530
+ findings.push({
531
+ name: 'chain_send_proof_only',
532
+ ok: !!state.sendIsProof,
533
+ detail: state.sendIsProof
534
+ ? 'permissions.send = proof() (escrow only leaves via a refund proof)'
535
+ : 'permissions.send ≠ proof() — vendor could drain escrow with a signature',
536
+ });
537
+
538
+ findings.push({
539
+ name: 'chain_edit_state_proof_only',
540
+ ok: !!state.editStateIsProof,
541
+ detail: state.editStateIsProof
542
+ ? 'permissions.editState = proof() (Merkle root advances only via a proof)'
543
+ : 'permissions.editState ≠ proof() — vendor could rewrite the license root',
544
+ });
545
+
546
+ const allOk = findings.every((f) => f.ok);
547
+ return { ok: allOk, origin, appId, address, generation, findings };
548
+ }