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
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  // Copyright (c) 2025-2026 zkLicensing project developers
3
- // All rights reserved.
3
+ // SPDX-License-Identifier: BUSL-1.1
4
4
  /**
5
5
  * verifyService.ts
6
6
  *
@@ -10,21 +10,21 @@
10
10
  * no circuit compilation, no o1js native backend. Starts in ~2 seconds and
11
11
  * runs on any small VPS or container.
12
12
  *
13
+ * Multi-network: one process can serve both devnet and mainnet. Every
14
+ * state endpoint receives a `zkAppAddress`, which routes unambiguously to
15
+ * one network via AppRecord.deployments (each generation has its own
16
+ * keypair — zkAppAddresses are globally unique across networks). The active
17
+ * o1js instance is switched per-request via withNetwork(), which also holds
18
+ * a process-global mutex so two concurrent handlers on different networks
19
+ * can't race the Mina.setActiveInstance swap.
20
+ *
13
21
  * No write endpoints — chain events are the source of truth. License state
14
22
  * is rebuilt from the archive node in three ways:
15
- * - auto-bootstrap on startup when licenses.json is empty,
23
+ * - auto-bootstrap on startup when licenses.json is empty (loops over
24
+ * every configured network's apps),
16
25
  * - lazy bootstrap inside GET / when the computed Merkle root
17
- * disagrees with the on-chain root for the requested app (the canonical
18
- * "we're stale" signal). One replay + one retry is enough — root is
19
- * consensus. This catches licenses issued, renewed, or refunded after
20
- * boot on the very next verify call, with zero work done when no one is
21
- * asking. Concurrent verifies for the same app share one in-flight
22
- * bootstrap so a popular license under load does not stampede the
23
- * archive node.
24
- * - POST /bootstrap (admin) for ad-hoc reasons: a newly registered zkApp
25
- * (verify won't trigger a sync for an app no client knows about yet), a
26
- * corrupted licenses.json, or repopulating the offline /license/...
27
- * debug endpoint without first hitting /verify.
26
+ * disagrees with the on-chain root for the requested app,
27
+ * - POST /bootstrap (admin) for ad-hoc reasons.
28
28
  *
29
29
  * Deployment modes
30
30
  * ----------------
@@ -35,16 +35,9 @@
35
35
  *
36
36
  * 2. Separate machine (replica)
37
37
  * - Copy the keeper's apps.json into the verifyService working directory.
38
- * apps.json tells the service which zkApp addresses to replay events for.
39
- * - Start the service. On boot it auto-bootstraps every app in apps.json
40
- * from the archive node. MINA_ARCHIVE_URL defaults to the Minascan public
41
- * archive matching MINA_NETWORK_ID:
42
- * mainnet → https://api.minascan.io/archive/mainnet/v1/graphql
43
- * else → https://api.minascan.io/archive/devnet/v1/graphql
44
- * Override by setting MINA_ARCHIVE_URL in the environment.
45
- * - To register a NEW app on the replica afterwards:
46
- * a) Re-copy apps.json from the keeper (it owns the registry), then
47
- * b) POST /bootstrap with the new zkAppAddress to ingest its events.
38
+ * - Set at least one of MINA_DEVNET_GRAPHQL_URL / MINA_MAINNET_GRAPHQL_URL.
39
+ * - Optionally set MINA_{DEVNET,MAINNET}_{GRAPHQL,ARCHIVE}_FALLBACK for a
40
+ * per-network fallback endpoint (used by the manual rotation on 5xx).
48
41
  * - Re-copying apps.json on a cron (or pulling it via GET /apps from the
49
42
  * keeper) is the recommended way to keep the registry in sync.
50
43
  *
@@ -52,18 +45,20 @@
52
45
  * node build/src/verifyService.js
53
46
  *
54
47
  * Configuration is read from environment variables (see README §Configuration).
55
- * Required: MINA_GRAPHQL_URL, PLATFORM_ADDRESS.
56
- * Optional: MINA_NETWORK_ID (default testnet), MINA_ARCHIVE_URL (defaults by
57
- * network), VERIFY_PORT (default 8081), VERIFY_ADMIN_TOKEN.
48
+ * Required: at least one of MINA_DEVNET_GRAPHQL_URL or MINA_MAINNET_GRAPHQL_URL
49
+ * (each also picks up MINA_{DEVNET,MAINNET}_ARCHIVE_URL, defaulting
50
+ * to Minascan public archive per-network).
51
+ * Optional: VERIFY_PORT (default 8081), VERIFY_ADMIN_TOKEN,
52
+ * MINA_{DEVNET,MAINNET}_{GRAPHQL,ARCHIVE}_FALLBACK (single fallback
53
+ * URL per network — manual rotation retries it on 5xx).
54
+ *
55
+ * NOTE: the pre-multi-network single-network trio (MINA_NETWORK_ID +
56
+ * MINA_GRAPHQL_URL + MINA_ARCHIVE_URL) is no longer accepted. Operators must
57
+ * migrate systemd units to the per-network variable names.
58
58
  *
59
59
  * Endpoints:
60
60
  * GET /health
61
61
  * GET /?licenseHash=...&zkAppAddress=... ← primary endpoint for apps
62
- * GET /challenge?licenseHash=... ← ownership nonce
63
- * POST /respond ← ownership proof + token
64
- * POST /refresh ← extend token TTL (no re-prove)
65
- * POST /releaseSeat ← release this device's seat
66
- * POST /reset-sessions ← drop all sessions (re-prove)
67
62
  * GET /root?zkApp=...
68
63
  * GET /witness/:zkAppAddress/:licenseHash
69
64
  * GET /license/:zkAppAddress/:licenseHash
@@ -71,141 +66,410 @@
71
66
  * POST /bootstrap ← replay events from archive
72
67
  */
73
68
  import fs from 'fs/promises';
74
- import { mkdirSync } from 'fs';
75
- import { homedir } from 'os';
76
- import { join } from 'path';
77
69
  import express from 'express';
78
- import { Field, Mina, fetchLastBlock, fetchAccount, PublicKey, Cache, setBackend, verify, } from 'o1js';
70
+ import { Field, Mina, fetchLastBlock, fetchAccount, PublicKey, setBackend, setGraphqlEndpoint, setArchiveGraphqlEndpoint, } from 'o1js';
71
+ import { createRequire } from 'node:module';
72
+ import { pathToFileURL } from 'node:url';
73
+ import { dirname, resolve as pathResolve } from 'path';
79
74
  import { buildMap, getLicense, licenseStatus, readRecords, serializeWitness, } from './licenseStore.js';
80
- import { verifyLicenseCore } from './verifyCore.js';
81
- import { bootstrapFromArchive, applyEventsToStore, lazyBootstrap } from './archiveBootstrap.js';
82
- import { LicenseProof, LicenseProofProof } from './licenseProof.js';
83
- import { CANONICAL_VK_HASHES, CANONICAL_LICENSE_PROOF_VK_HASH, SUPPORTED_LICENSING_APP_VERSIONS, fetchLicensingAppVersion, } from './contractInterface.js';
84
- import { createChallengeStore, createSessionStore, newJti, signOwnershipToken, verifyOwnershipToken, newOwnershipKey, OWNERSHIP_TOKEN_TTL_MS, } from './ownership.js';
75
+ import { verifyLicenseWithAncestors } from './verifyWithAncestors.js';
76
+ import { bootstrapFromArchive, applyEventsToStore } from './archiveBootstrap.js';
77
+ import { CANONICAL_VK_HASHES, SUPPORTED_LICENSING_APP_VERSIONS, fetchLicensingAppVersion, } from './contractInterface.js';
85
78
  setBackend('native');
86
- const CIRCUIT_CACHE_DIR = join(homedir(), '.cache', 'zklic-verifier');
87
- mkdirSync(CIRCUIT_CACHE_DIR, { recursive: true });
88
- // ------------------------------------------------------------
89
- // CONFIG (env vars) & NETWORK
90
- // ------------------------------------------------------------
91
- function requireEnv(name, hint) {
92
- const v = process.env[name];
93
- if (!v) {
94
- console.error(`❌ ${name} env var is required. ${hint}`);
95
- process.exit(1);
96
- }
97
- return v;
98
- }
99
- const MINA_NETWORK_ID = process.env.MINA_NETWORK_ID ?? 'devnet';
100
- const MINA_GRAPHQL_URL = requireEnv('MINA_GRAPHQL_URL', 'e.g. https://api.minascan.io/node/devnet/v1/graphql');
79
+ const NETWORKS = ['devnet', 'mainnet'];
80
+ const MINA_DEVNET_GRAPHQL_URL = process.env.MINA_DEVNET_GRAPHQL_URL;
81
+ const MINA_DEVNET_ARCHIVE_URL = process.env.MINA_DEVNET_ARCHIVE_URL;
82
+ const MINA_DEVNET_GRAPHQL_FALLBACK = process.env.MINA_DEVNET_GRAPHQL_FALLBACK;
83
+ const MINA_DEVNET_ARCHIVE_FALLBACK = process.env.MINA_DEVNET_ARCHIVE_FALLBACK;
84
+ const MINA_MAINNET_GRAPHQL_URL = process.env.MINA_MAINNET_GRAPHQL_URL;
85
+ const MINA_MAINNET_ARCHIVE_URL = process.env.MINA_MAINNET_ARCHIVE_URL;
86
+ const MINA_MAINNET_GRAPHQL_FALLBACK = process.env.MINA_MAINNET_GRAPHQL_FALLBACK;
87
+ const MINA_MAINNET_ARCHIVE_FALLBACK = process.env.MINA_MAINNET_ARCHIVE_FALLBACK;
101
88
  const PORT = parseInt(process.env.VERIFY_PORT ?? '8081', 10);
102
- function defaultArchiveUrl(networkId) {
103
- switch (networkId) {
104
- case 'mainnet':
105
- return 'https://api.minascan.io/archive/mainnet/v1/graphql';
106
- case 'devnet':
107
- return 'https://api.minascan.io/archive/devnet/v1/graphql';
108
- default:
109
- return null;
110
- }
89
+ // Default archive endpoint per network (Minascan public archive). When the
90
+ // operator sets an explicit MINA_*_ARCHIVE_URL env var, that value wins.
91
+ const DEFAULT_ARCHIVE_URL = {
92
+ devnet: 'https://api.minascan.io/archive/devnet/v1/graphql',
93
+ mainnet: 'https://api.minascan.io/archive/mainnet/v1/graphql',
94
+ };
95
+ // Build per-network Mina.Network instances. Any network the operator didn't
96
+ // configure (no RPC URL) stays out of the map — requests targeting it fall
97
+ // through to `unregistered-address`. At least one must be configured.
98
+ const NETWORK_CONFIG = {};
99
+ function buildNetworkConfig(networkId, graphqlUrl, archiveEnv, graphqlFallbackEnv, archiveFallbackEnv) {
100
+ if (!graphqlUrl)
101
+ return;
102
+ const archiveUrl = archiveEnv ?? DEFAULT_ARCHIVE_URL[networkId];
103
+ const trim = (s) => (s ? s.trim() : '');
104
+ const graphqlFallback = trim(graphqlFallbackEnv) && trim(graphqlFallbackEnv) !== graphqlUrl
105
+ ? trim(graphqlFallbackEnv) : null;
106
+ const archiveFallback = trim(archiveFallbackEnv) && trim(archiveFallbackEnv) !== archiveUrl
107
+ ? trim(archiveFallbackEnv) : null;
108
+ // See keeperService.ts for the full rationale: o1js's array-based fallback
109
+ // form (`mina: [primary, fallback]`) is unusable — Promise.race lets a fast
110
+ // 5xx from primary beat a slow 200 from fallback, and the winning-URL
111
+ // cache-key bug causes subsequent `.get()` calls to miss. Manual rotation
112
+ // via a second single-URL Mina.Network instance is the sole failover path.
113
+ const fallbackMinaArg = graphqlFallback ? graphqlFallback : null;
114
+ const fallbackArchiveArg = graphqlFallback ? (archiveFallback ?? archiveUrl) : null;
115
+ NETWORK_CONFIG[networkId] = {
116
+ networkId,
117
+ graphqlUrl,
118
+ archiveUrl,
119
+ graphqlFallback,
120
+ archiveFallback,
121
+ network: Mina.Network({ networkId: networkId, mina: graphqlUrl, archive: archiveUrl }),
122
+ fallbackNetwork: fallbackMinaArg
123
+ ? Mina.Network({ networkId: networkId, mina: fallbackMinaArg, archive: fallbackArchiveArg })
124
+ : null,
125
+ };
126
+ console.log(`🔗 ${networkId.padEnd(7)} Mina node: ${graphqlUrl}`);
127
+ if (graphqlFallback)
128
+ console.log(` ${networkId.padEnd(7)} fallback: ${graphqlFallback}`);
129
+ console.log(`📚 ${networkId.padEnd(7)} Archive node: ${archiveUrl}${archiveEnv ? ' (from env)' : ' (default)'}`);
130
+ if (archiveFallback)
131
+ console.log(` ${networkId.padEnd(7)} fallback: ${archiveFallback}`);
111
132
  }
112
- const archiveUrl = process.env.MINA_ARCHIVE_URL ?? defaultArchiveUrl(MINA_NETWORK_ID);
113
- if (!archiveUrl) {
114
- console.error(`❌ No archive URL for MINA_NETWORK_ID="${MINA_NETWORK_ID}" and no built-in default for this network.\n` +
115
- ` Set MINA_ARCHIVE_URL to the archive node GraphQL endpoint.`);
133
+ buildNetworkConfig('devnet', MINA_DEVNET_GRAPHQL_URL, MINA_DEVNET_ARCHIVE_URL, MINA_DEVNET_GRAPHQL_FALLBACK, MINA_DEVNET_ARCHIVE_FALLBACK);
134
+ buildNetworkConfig('mainnet', MINA_MAINNET_GRAPHQL_URL, MINA_MAINNET_ARCHIVE_URL, MINA_MAINNET_GRAPHQL_FALLBACK, MINA_MAINNET_ARCHIVE_FALLBACK);
135
+ if (Object.keys(NETWORK_CONFIG).length === 0) {
136
+ console.error('❌ No Mina network configured. Set at least one of MINA_DEVNET_GRAPHQL_URL / MINA_MAINNET_GRAPHQL_URL.');
116
137
  process.exit(1);
117
138
  }
118
- console.log(`🔗 Mina node: ${MINA_GRAPHQL_URL}`);
119
- console.log(`📚 Archive node: ${archiveUrl}${process.env.MINA_ARCHIVE_URL ? ' (from MINA_ARCHIVE_URL)' : ' (default — set MINA_ARCHIVE_URL to override)'}`);
120
- Mina.setActiveInstance(Mina.Network({
121
- networkId: MINA_NETWORK_ID,
122
- mina: MINA_GRAPHQL_URL,
123
- archive: archiveUrl,
124
- }));
125
- // ------------------------------------------------------------
126
- // CIRCUIT — LicenseProof (ownership challenge/response)
127
- // ------------------------------------------------------------
128
- let licenseProofVk = null;
129
- let licenseProofCompile = null;
130
- async function ensureCompiled() {
131
- if (licenseProofVk)
139
+ // Leaked-transaction-context reset scaffolding. The verifier has no
140
+ // Mina.transaction() calls today, so the leak defense is theoretical — but
141
+ // it's cheap (one dynamic import at boot) and future-proofs against a code
142
+ // path we haven't accounted for taking the process out until systemd
143
+ // restarts it. Same shape as keeperService.ts.
144
+ const _o1jsRequire = createRequire(import.meta.url);
145
+ let _o1jsCurrentTransaction = null;
146
+ try {
147
+ const o1jsMainPath = _o1jsRequire.resolve('o1js');
148
+ const contextUrl = pathToFileURL(pathResolve(dirname(o1jsMainPath), 'lib/mina/v1/transaction-context.js')).href;
149
+ const mod = await import(contextUrl);
150
+ _o1jsCurrentTransaction = mod.currentTransaction ?? null;
151
+ }
152
+ catch (e) {
153
+ console.warn('[withNetwork] o1js leak defense disabled — could not reach internal transaction-context:', e?.message ?? e);
154
+ }
155
+ function resetLeakedTransactionContext() {
156
+ if (!_o1jsCurrentTransaction)
132
157
  return;
133
- licenseProofCompile ??= (async () => {
134
- const cached = Cache.FileSystem(CIRCUIT_CACHE_DIR);
135
- const t = Date.now();
136
- console.log(`[verify-prover] Compiling LicenseProof (cache: ${CIRCUIT_CACHE_DIR})…`);
137
- const lpVk = await LicenseProof.compile({ cache: cached });
138
- const vk = lpVk.verificationKey;
139
- if (CANONICAL_LICENSE_PROOF_VK_HASH && vk.hash.toString() !== CANONICAL_LICENSE_PROOF_VK_HASH) {
140
- throw new Error(`LicenseProof VK hash ${vk.hash.toString()} does not match CANONICAL_LICENSE_PROOF_VK_HASH ${CANONICAL_LICENSE_PROOF_VK_HASH}`);
158
+ while (_o1jsCurrentTransaction.has()) {
159
+ try {
160
+ _o1jsCurrentTransaction.leave(_o1jsCurrentTransaction.id());
161
+ }
162
+ catch {
163
+ break;
141
164
  }
142
- licenseProofVk = vk;
143
- console.log(`[verify-prover] Ready in ${((Date.now() - t) / 1000).toFixed(1)}s — vk ${vk.hash.toString().slice(0, 16)}…`);
144
- })();
145
- await licenseProofCompile;
165
+ }
146
166
  }
147
- ensureCompiled().catch((e) => console.error('[verify-prover] Compile failed:', e));
148
- // ------------------------------------------------------------
149
- // OWNERSHIP — challenge + activation token (helpers live in ownership.ts)
150
- // ------------------------------------------------------------
151
- const ownershipChallenges = createChallengeStore();
152
- setInterval(() => { /* opportunistic GC */ ownershipChallenges.size(); }, 30_000).unref();
153
- // Per-license active-device session store. Backs the concurrent-device cap
154
- // (AppRecord.maxConcurrentDevices), /releaseSeat, and /reset-sessions. In-memory
155
- // by design — a keeper restart drops every session, forcing devices to
156
- // re-prove ownership. That is a security feature: persisted sessions would
157
- // let a stolen token bypass concurrency caps across restarts.
158
- const ownershipSessions = createSessionStore();
159
- setInterval(() => { /* opportunistic GC — activeCount touches prune */ ownershipSessions.size(); }, 30_000).unref();
160
- async function loadAppByAddress(zkAppAddress) {
161
- const apps = await readApps();
162
- return apps.find((a) => a.zkAppAddress === zkAppAddress) ?? null;
167
+ let _networkMutexTail = Promise.resolve();
168
+ // Which endpoint (primary vs fallback) currently succeeds for each network.
169
+ // Updated by the rotation helpers whenever a call succeeds on a specific
170
+ // endpoint. `withNetwork` restores from this map at region entry so that a
171
+ // successful fallback rotation in one region persists into the next region
172
+ // — otherwise a resetToPrimary here would stomp the fallback state and the
173
+ // following .get() cache lookup would miss on primary (the o1js account
174
+ // cache is keyed by graphql endpoint URL).
175
+ //
176
+ // Sticky-until-proven-broken semantics: we don't automatically retry primary
177
+ // on every region entry. If primary comes back up, the next rotation call
178
+ // will hit it first (attempt 1) and flip us back.
179
+ const _activeEndpointByNetwork = new Map();
180
+ // Swap the active Mina instance AND the o1js module-global fetch endpoint
181
+ // atomically. These are two independent globals inside o1js:
182
+ // - `activeInstance` (mina-instance.js) — what zkApp.<state>.get() closes
183
+ // over for its cache lookups
184
+ // - `networkConfig.minaEndpoint` (fetch.js) — the DEFAULT endpoint for
185
+ // bare `fetchAccount({publicKey})` / `fetchLastBlock()` calls
186
+ // `Mina.setActiveInstance` only touches the first. Because we build TWO
187
+ // Mina.Network() instances at startup (primary + fallback) and the second
188
+ // call's Fetch.setGraphqlEndpoint side-effect leaves `networkConfig.minaEndpoint`
189
+ // pinned to the LAST-constructed URL (the fallback), a plain
190
+ // setActiveInstance(cfg.network) leaves fetchAccount hitting the fallback URL
191
+ // while zkApp.<state>.get() looks up under the primary URL — cache miss →
192
+ // "Could not find account". We must always keep the two endpoints in sync,
193
+ // which this helper does.
194
+ function activateNetworkEndpoints(cfg, useFallback) {
195
+ if (useFallback && cfg.fallbackNetwork) {
196
+ Mina.setActiveInstance(cfg.fallbackNetwork);
197
+ setGraphqlEndpoint(cfg.graphqlFallback ?? cfg.graphqlUrl);
198
+ setArchiveGraphqlEndpoint(cfg.archiveFallback ?? cfg.archiveUrl);
199
+ _activeEndpointByNetwork.set(cfg.networkId, 'fallback');
200
+ }
201
+ else {
202
+ Mina.setActiveInstance(cfg.network);
203
+ setGraphqlEndpoint(cfg.graphqlUrl);
204
+ setArchiveGraphqlEndpoint(cfg.archiveUrl);
205
+ _activeEndpointByNetwork.set(cfg.networkId, 'primary');
206
+ }
163
207
  }
164
- // Resolve which generation a zkAppAddress claims to belong to by walking the
165
- // keeper's AppRecord.deploymentHistory[]. The top-level address is the current
166
- // generation (history.length + 1); older addresses live in history at
167
- // increasing index. Returns null when the address is not present in any
168
- // app's history — which is exactly what stops a "genuine v1 circuit
169
- // redeployed at a fresh address" impersonation: unlisted address → no
170
- // generation → verify rejects. See CANONICAL_VK_HASHES in contractInterface.ts.
171
- async function resolveGenerationByAddress(zkAppAddress) {
172
- const apps = await readApps();
173
- for (const a of apps) {
174
- const historyLen = a.deploymentHistory?.length ?? 0;
175
- if (a.zkAppAddress === zkAppAddress)
176
- return historyLen + 1;
177
- if (a.deploymentHistory) {
178
- for (let i = 0; i < a.deploymentHistory.length; i++) {
179
- if (a.deploymentHistory[i].zkAppAddress === zkAppAddress)
180
- return i + 1;
181
- }
208
+ // Active-instance juggling: o1js/Mina keeps a single global active network
209
+ // instance, so multi-network handlers must switch it before making any
210
+ // on-chain call. Wrap the region that needs a specific network in
211
+ // withNetwork(network, () => …). Handlers that don't touch chain state
212
+ // (local record reads, witness computation) don't need this.
213
+ async function withNetwork(networkId, fn) {
214
+ const cfg = NETWORK_CONFIG[networkId];
215
+ if (!cfg)
216
+ throw new Error(`Network ${networkId} is not configured on this verifier`);
217
+ let release = () => { };
218
+ const prev = _networkMutexTail;
219
+ _networkMutexTail = new Promise((r) => { release = r; });
220
+ await prev;
221
+ try {
222
+ const stickyFallback = _activeEndpointByNetwork.get(networkId) === 'fallback';
223
+ activateNetworkEndpoints(cfg, stickyFallback);
224
+ return await fn();
225
+ }
226
+ catch (err) {
227
+ resetLeakedTransactionContext();
228
+ throw err;
229
+ }
230
+ finally {
231
+ release();
232
+ }
233
+ }
234
+ // Per-attempt timeout for fetchLastBlock. Sized for the SLOW path: the
235
+ // Minascan public node (often used as fallback) frequently rate-limits and
236
+ // can take 60–120s to return during load spikes. Cutting the timeout shorter
237
+ // would surface as a spurious "fetchLastBlock failed" after primary is down
238
+ // — the exact situation this fallback exists to cover. Primary endpoints
239
+ // (minataur, self-hosted) that return quickly aren't penalized because a
240
+ // fast success short-circuits the timer.
241
+ const CURRENT_SLOT_TIMEOUT_MS = 180_000;
242
+ // 5xx and 408 (o1js's own timeout stand-in) rotate to the fallback. 404 means
243
+ // "account genuinely doesn't exist" and short-circuits — no point rotating.
244
+ // Anything else (4xx GraphQL error, 400 malformed request) also short-circuits
245
+ // because it's not endpoint-health related.
246
+ function shouldRotateOnError(statusCode) {
247
+ if (statusCode === undefined)
248
+ return true; // network throw with no status — treat as transport
249
+ if (statusCode === 408)
250
+ return true;
251
+ if (statusCode >= 500 && statusCode <= 599)
252
+ return true;
253
+ return false;
254
+ }
255
+ // Manual endpoint rotation for fetchAccount. Must be called from inside a
256
+ // withNetwork() region so the mutex prevents concurrent handlers from
257
+ // observing a mid-flight setActiveInstance swap. On success leaves the
258
+ // winning instance active so the next zkApp.<state>.get() cache lookup finds
259
+ // the freshly-fetched account under the same graphql-endpoint cache key.
260
+ async function fetchAccountWithRotation(networkId, publicKey, attempts, backoffMs = (a) => 400 * a) {
261
+ const cfg = NETWORK_CONFIG[networkId];
262
+ if (!cfg)
263
+ throw new Error(`Network ${networkId} is not configured on this verifier`);
264
+ let last = { account: undefined, error: { statusCode: 500, statusText: 'no attempt made' } };
265
+ let succeededOn = null;
266
+ const trace = [];
267
+ for (let attempt = 1; attempt <= attempts; attempt++) {
268
+ // Alternate primary / fallback across attempts when fallback exists:
269
+ // attempt 1 → primary, 2 → fallback, 3 → primary, …
270
+ const useFallback = cfg.fallbackNetwork !== null && attempt % 2 === 0;
271
+ const url = useFallback ? (cfg.graphqlFallback ?? cfg.graphqlUrl) : cfg.graphqlUrl;
272
+ activateNetworkEndpoints(cfg, useFallback);
273
+ last = await fetchAccount({ publicKey });
274
+ if (last.account) {
275
+ succeededOn = useFallback ? 'fallback' : 'primary';
276
+ trace.push({ url, outcome: 'ok' });
277
+ break;
182
278
  }
279
+ const status = last.error?.statusCode;
280
+ const outcome = status === 404 ? '404' : `HTTP ${status ?? '?'} ${last.error?.statusText ?? ''}`.trim();
281
+ trace.push({ url, outcome });
282
+ if (status === 404)
283
+ break; // real not-found
284
+ if (!shouldRotateOnError(status))
285
+ break; // non-transport error
286
+ if (attempt < attempts)
287
+ await new Promise((r) => setTimeout(r, backoffMs(attempt)));
288
+ }
289
+ if (!last.account && last.error?.statusCode !== 404) {
290
+ logUtc('fetchAccountWithRotation', '✗ all attempts failed', {
291
+ network: networkId,
292
+ publicKey: publicKey.toBase58(),
293
+ attempts,
294
+ trace,
295
+ });
183
296
  }
184
- return null;
297
+ if (succeededOn === null) {
298
+ activateNetworkEndpoints(cfg, false);
299
+ }
300
+ return last;
185
301
  }
186
- const OWNERSHIP_KEY_PATH = process.env.OWNERSHIP_KEY_PATH ?? join(CIRCUIT_CACHE_DIR, 'ownership-hmac.key');
187
- let ownershipKey;
188
- try {
189
- ownershipKey = await fs.readFile(OWNERSHIP_KEY_PATH);
190
- console.log(`🔑 Ownership HMAC key loaded from ${OWNERSHIP_KEY_PATH}`);
302
+ // Same rotation semantics as fetchAccountWithRotation but for fetchLastBlock.
303
+ // Wraps the o1js call in the CURRENT_SLOT_TIMEOUT_MS timeout race so a dead
304
+ // endpoint doesn't hang the whole attempt. Must be called from inside a
305
+ // withNetwork() region. Returns null on terminal failure so callers can decide
306
+ // (throw, retry higher up, or degrade gracefully — currentSlot returns 0).
307
+ async function fetchLastBlockWithRotation(networkId, attempts, backoffMs = (a) => 400 * a) {
308
+ const cfg = NETWORK_CONFIG[networkId];
309
+ if (!cfg)
310
+ throw new Error(`Network ${networkId} is not configured on this verifier`);
311
+ let succeededOn = null;
312
+ const trace = [];
313
+ for (let attempt = 1; attempt <= attempts; attempt++) {
314
+ const useFallback = cfg.fallbackNetwork !== null && attempt % 2 === 0;
315
+ const url = useFallback ? (cfg.graphqlFallback ?? cfg.graphqlUrl) : cfg.graphqlUrl;
316
+ activateNetworkEndpoints(cfg, useFallback);
317
+ try {
318
+ const block = await Promise.race([
319
+ fetchLastBlock(),
320
+ new Promise((_, reject) => setTimeout(() => reject(new Error(`fetchLastBlock timed out after ${CURRENT_SLOT_TIMEOUT_MS}ms`)), CURRENT_SLOT_TIMEOUT_MS)),
321
+ ]);
322
+ succeededOn = useFallback ? 'fallback' : 'primary';
323
+ trace.push({ url, outcome: 'ok' });
324
+ return block;
325
+ }
326
+ catch (err) {
327
+ trace.push({ url, outcome: err?.message ?? String(err) });
328
+ if (attempt < attempts)
329
+ await new Promise((r) => setTimeout(r, backoffMs(attempt)));
330
+ }
331
+ }
332
+ if (succeededOn === null) {
333
+ activateNetworkEndpoints(cfg, false);
334
+ }
335
+ logUtc('fetchLastBlockWithRotation', '✗ all attempts failed', {
336
+ network: networkId,
337
+ attempts,
338
+ trace,
339
+ });
340
+ return null;
191
341
  }
192
- catch {
193
- ownershipKey = newOwnershipKey();
194
- await fs.writeFile(OWNERSHIP_KEY_PATH, ownershipKey, { mode: 0o600 });
195
- console.log(`🔑 Ownership HMAC key generated → ${OWNERSHIP_KEY_PATH}`);
342
+ // UTC-stamped structured log. Arrays/objects in `extra` are JSON-stringified
343
+ // so per-attempt traces don't render as [object Object].
344
+ function logUtc(scope, msg, extra) {
345
+ const ts = new Date().toISOString();
346
+ const tail = extra
347
+ ? ' ' + Object.entries(extra).map(([k, v]) => {
348
+ const s = (v !== null && typeof v === 'object') ? JSON.stringify(v) : `${v}`;
349
+ return `${k}=${s}`;
350
+ }).join(' ')
351
+ : '';
352
+ console.log(`[${ts}] [${scope}] ${msg}${tail}`);
196
353
  }
354
+ // Default the active instance to whichever network is configured (mainnet
355
+ // wins if both are up, so idle background code without explicit context lands
356
+ // on the production network). withNetwork() overrides this per-request.
357
+ activateNetworkEndpoints((NETWORK_CONFIG.mainnet ?? NETWORK_CONFIG.devnet), false);
197
358
  // ------------------------------------------------------------
198
359
  // HELPERS
199
360
  // ------------------------------------------------------------
200
- async function currentSlot() {
361
+ // Fetch the current slot on the specified network. Rotation-aware. Callers
362
+ // that need the value in a broader on-chain region should pass the network
363
+ // they already resolved from the zkAppAddress.
364
+ async function currentSlot(network) {
201
365
  try {
202
- const block = await fetchLastBlock();
366
+ const block = await withNetwork(network, () => fetchLastBlockWithRotation(network, 3));
367
+ if (!block)
368
+ return 0;
203
369
  return Number(block.globalSlotSinceGenesis.toString());
204
370
  }
205
- catch {
371
+ catch (e) {
372
+ logUtc('currentSlot', '✗ fetchLastBlock failed', { network, reason: e?.message ?? String(e) });
206
373
  return 0;
207
374
  }
208
375
  }
376
+ // Return an error message if `zkAppAddress` isn't a well-formed B62q address,
377
+ // null otherwise. Called at request-parse time so garbage input fails with a
378
+ // legible 400 in a couple of ms instead of ~1 s of proof-verify CPU followed
379
+ // by a generic 502 from `fromBase58` throwing deep inside checkOnChainLicense.
380
+ function validateZkAppAddress(zkAppAddress) {
381
+ try {
382
+ PublicKey.fromBase58(zkAppAddress);
383
+ return null;
384
+ }
385
+ catch (err) {
386
+ return `Invalid zkAppAddress: ${err?.message || 'not a valid Mina B62q address'}`;
387
+ }
388
+ }
389
+ // Resolve a zkAppAddress to its owning AppRecord + network + deployment
390
+ // slice. Walks both networks' current-live address and every entry in
391
+ // deploymentHistory. Under the keeper-routing design a buyer who pinned an
392
+ // original gen-1 address stays valid forever even after N generation bumps.
393
+ function resolveAppAndNetwork(apps, zkAppAddress) {
394
+ for (const app of apps) {
395
+ for (const net of NETWORKS) {
396
+ const dep = app.deployments[net];
397
+ if (!dep)
398
+ continue;
399
+ if (dep.zkAppAddress === zkAppAddress ||
400
+ (dep.deploymentHistory ?? []).some(h => h.zkAppAddress === zkAppAddress)) {
401
+ return { app, network: net, deployment: dep };
402
+ }
403
+ }
404
+ }
405
+ return null;
406
+ }
407
+ // Fetch fresh on-chain state and delegate address routing + ancestor walk
408
+ // to verifyLicenseWithAncestors. Resolves the target network from the
409
+ // zkAppAddress; unknown addresses (not in any configured network's registry)
410
+ // surface as `unregistered-address`. Throws only on network / RPC failure.
411
+ //
412
+ // The `generation` field echoes the *request* address's own stable
413
+ // generation, so a client that pinned an older address at build time sees
414
+ // a token whose `g` still matches its local expectation across bumps.
415
+ async function checkOnChainLicense(zkAppAddress, licenseHash) {
416
+ const apps = await readApps();
417
+ const resolved = resolveAppAndNetwork(apps, zkAppAddress);
418
+ if (!resolved)
419
+ return { kind: 'unregistered-address' };
420
+ const { network, deployment } = resolved;
421
+ if (!NETWORK_CONFIG[network])
422
+ return { kind: 'unregistered-address' };
423
+ const historyLen = deployment.deploymentHistory?.length ?? 0;
424
+ const currentGeneration = historyLen + 1;
425
+ const currentLive = deployment.zkAppAddress;
426
+ // Echo: the request address's own stable generation. Stays consistent
427
+ // across bumps for any client that pinned an older address.
428
+ let requestGeneration = currentGeneration;
429
+ if (zkAppAddress !== currentLive) {
430
+ const idx = (deployment.deploymentHistory ?? []).findIndex((d) => d.zkAppAddress === zkAppAddress);
431
+ if (idx >= 0)
432
+ requestGeneration = idx + 1;
433
+ }
434
+ // Sequential (was Promise.all): the rotation helpers do Mina.setActiveInstance
435
+ // internally, so running fetchAccount + fetchLastBlock in parallel would race
436
+ // the instance swap. Same pattern as the keeper sweep.
437
+ const records = await readRecords();
438
+ const { account } = await withNetwork(network, () => fetchAccountWithRotation(network, PublicKey.fromBase58(currentLive), 3));
439
+ const lastBlock = await withNetwork(network, () => fetchLastBlockWithRotation(network, 3));
440
+ if (!lastBlock) {
441
+ throw new Error('fetchLastBlock failed');
442
+ }
443
+ const currentRoot = account?.zkapp?.appState?.[0]?.toString();
444
+ if (!currentRoot)
445
+ return { kind: 'zkapp-not-found' };
446
+ const zkAppVersion = Number(account?.zkapp?.appState?.[7]?.toString() ?? '0');
447
+ const onChainVk = account?.zkapp?.verificationKey?.hash?.toString();
448
+ const expectedVk = CANONICAL_VK_HASHES[currentGeneration];
449
+ if (expectedVk && onChainVk !== expectedVk)
450
+ return { kind: 'vk-mismatch', generation: currentGeneration };
451
+ const currentSlotNum = Number(lastBlock.globalSlotSinceGenesis.toString());
452
+ // verifyLicenseWithAncestors uses bare fetchAccount internally on retired
453
+ // addresses — wrap it in withNetwork so the active instance points at the
454
+ // correct network for the whole walk.
455
+ const walked = await withNetwork(network, () => verifyLicenseWithAncestors({
456
+ deployment,
457
+ licenseHash,
458
+ currentSlot: currentSlotNum,
459
+ currentLiveRoot: currentRoot,
460
+ records,
461
+ }));
462
+ return {
463
+ kind: 'checked',
464
+ onChainRoot: walked.onChainRoot,
465
+ currentSlot: currentSlotNum,
466
+ zkAppVersion,
467
+ generation: requestGeneration,
468
+ resolvedAddress: walked.resolvedAddress,
469
+ liveRecords: walked.liveRecords,
470
+ result: walked.result,
471
+ };
472
+ }
209
473
  const APPS_FILE = 'apps.json';
210
474
  async function readApps() {
211
475
  try {
@@ -230,6 +494,26 @@ app.use((_req, res, next) => {
230
494
  }
231
495
  next();
232
496
  });
497
+ // Per-request access log. One line per request: method + path + status + ms.
498
+ // Skips CORS preflights (already short-circuited above with 204). Path is the
499
+ // raw req.path — query strings are dropped so the licenseHash from `GET /`
500
+ // doesn't leak into logs (the redacted-prefix log on the / handler below is
501
+ // the canonical place to see which license was queried).
502
+ // Toggle off with VERIFY_ACCESS_LOG=off if the verifier ever runs behind a
503
+ // hot-path API where per-request lines become noise.
504
+ const ACCESS_LOG_ENABLED = (process.env.VERIFY_ACCESS_LOG ?? '').toLowerCase() !== 'off';
505
+ if (ACCESS_LOG_ENABLED) {
506
+ app.use((req, res, next) => {
507
+ const started = Date.now();
508
+ res.on('finish', () => {
509
+ logUtc('access', `${req.method} ${req.path}`, {
510
+ status: res.statusCode,
511
+ elapsed_ms: Date.now() - started,
512
+ });
513
+ });
514
+ next();
515
+ });
516
+ }
233
517
  const VERIFY_ADMIN_TOKEN = process.env.VERIFY_ADMIN_TOKEN ?? '';
234
518
  function requireAdmin(req, res, next) {
235
519
  if (!VERIFY_ADMIN_TOKEN) {
@@ -244,11 +528,29 @@ function requireAdmin(req, res, next) {
244
528
  }
245
529
  next();
246
530
  }
247
- // Health
531
+ // Health.
532
+ //
533
+ // `networkId` per entry is the authoritative "which Mina chain" answer — a
534
+ // stable identifier the client can compare against exactly. `network` (the
535
+ // raw GraphQL URL) is kept for operator-facing observability only, since it
536
+ // can rotate providers (Minascan ↔ Minataur ↔ self-hosted) without the chain
537
+ // changing. `fallback` mirrors the same for the configured fallback endpoint.
248
538
  app.get('/health', (_req, res) => {
249
- res.json({ status: 'ok', service: 'verify', network: MINA_GRAPHQL_URL });
539
+ const networks = {};
540
+ for (const net of NETWORKS) {
541
+ const cfg = NETWORK_CONFIG[net];
542
+ if (!cfg)
543
+ continue;
544
+ networks[net] = {
545
+ networkId: cfg.networkId,
546
+ network: cfg.graphqlUrl,
547
+ fallback: cfg.graphqlFallback,
548
+ };
549
+ }
550
+ res.json({ status: 'ok', service: 'verify', networks });
250
551
  });
251
- // Current MerkleMap root for a specific zkApp.
552
+ // Current MerkleMap root for a specific zkApp. Network-agnostic — reads local
553
+ // records only.
252
554
  app.get('/root', async (req, res) => {
253
555
  const zkAppAddress = req.query.zkApp ?? '';
254
556
  if (!zkAppAddress) {
@@ -258,308 +560,99 @@ app.get('/root', async (req, res) => {
258
560
  const map = buildMap(records, zkAppAddress);
259
561
  res.json({ root: map.getRoot().toString() });
260
562
  });
261
- // GET /challenge?licenseHash=...
262
- // Issues a nonce for the ownership challenge-response flow.
263
- app.get('/challenge', (req, res) => {
264
- const licenseHash = String(req.query.licenseHash ?? '');
265
- if (!licenseHash) {
266
- return res.status(400).json({ error: 'Missing licenseHash' });
267
- }
268
- res.json(ownershipChallenges.issue(licenseHash));
269
- });
270
- // POST /respond — body: { zkAppAddress, proof }
271
- // Verifies a LicenseProof against the issued nonce, consumes the nonce,
272
- // enforces the vendor's concurrent-device cap (if any), and returns
273
- // { ownership: 'verified', token, expiresAt, jti, activeSessions, deviceLimit }
274
- // on success. On cap overflow returns 429 without minting a token — clients
275
- // must release a seat (POST /releaseSeat), reset all sessions (POST
276
- // /reset-sessions), or wait for the oldest to hit TTL.
277
- app.post('/respond', async (req, res) => {
278
- await ensureCompiled();
279
- if (!licenseProofVk) {
280
- return res.status(503).json({ error: 'Verify service not ready — circuits compiling' });
281
- }
282
- const { zkAppAddress, proof: proofJson } = req.body;
283
- if (!zkAppAddress || !proofJson) {
284
- return res.status(400).json({ error: 'Missing zkAppAddress or proof' });
285
- }
286
- let proof;
287
- try {
288
- proof = await LicenseProofProof.fromJSON(proofJson);
289
- }
290
- catch {
291
- return res.status(400).json({ error: 'Invalid proof format' });
292
- }
293
- let proofValid = false;
294
- try {
295
- proofValid = await verify(proof, licenseProofVk);
296
- }
297
- catch {
298
- return res.status(400).json({ error: 'Proof verification threw' });
299
- }
300
- if (!proofValid) {
301
- return res.status(400).json({ error: 'Proof is cryptographically invalid' });
302
- }
303
- const licenseHash = proof.publicInput.licenseHash.toString();
304
- const nonce = proof.publicInput.nonce.toString();
305
- const nonceState = ownershipChallenges.consume(licenseHash, nonce);
306
- if (nonceState !== 'ok') {
307
- return res.status(400).json({ error: `Nonce ${nonceState} — request a fresh /challenge` });
308
- }
309
- // Concurrent-device cap enforcement. Read the vendor's per-app limit
310
- // (0/undefined = unlimited) and try to reserve a session slot BEFORE
311
- // minting the HMAC — a token without a matching session-store entry is
312
- // dead on arrival at GET / anyway, so refusing here avoids handing the
313
- // caller a bearer that they can only use to be rejected.
314
- const app_record = await loadAppByAddress(zkAppAddress);
315
- const cap = Math.max(0, Math.floor(app_record?.maxConcurrentDevices ?? 0));
316
- const jti = newJti();
317
- const exp = Date.now() + OWNERSHIP_TOKEN_TTL_MS;
318
- const reserved = ownershipSessions.insert(licenseHash, jti, exp, cap);
319
- if (reserved.state === 'at-cap') {
320
- return res.status(429).json({
321
- error: 'Concurrent-device limit reached — release a seat, run POST /reset-sessions, or wait for the oldest session to expire',
322
- activeSessions: reserved.active,
323
- deviceLimit: cap,
324
- });
325
- }
326
- const token = signOwnershipToken(ownershipKey, { z: zkAppAddress, l: licenseHash, e: exp, jti });
327
- res.json({
328
- ownership: 'verified',
329
- token,
330
- expiresAt: exp,
331
- jti,
332
- activeSessions: reserved.active,
333
- deviceLimit: cap,
334
- });
335
- });
336
- // POST /releaseSeat — body: { token }
337
- // Releases the seat identified by the token's jti. Possession of the token
338
- // is authorization to release it (same threat model as any bearer token);
339
- // no proof-of-ownership is required. Enables an in-app "log out this device"
340
- // button. Idempotent — a second call with the same token silently no-ops.
341
- app.post('/releaseSeat', (req, res) => {
342
- const { token } = req.body;
343
- if (!token)
344
- return res.status(400).json({ error: 'Missing token' });
345
- const payload = verifyOwnershipToken(ownershipKey, token);
346
- if (!payload)
347
- return res.status(401).json({ error: 'Invalid or expired token' });
348
- if (!payload.jti) {
349
- // Pre-jti tokens aren't tracked in the session store, so there's no seat
350
- // to release. Return 200 for idempotency — the caller's intent (log this
351
- // device out) is satisfied by the local token delete.
352
- return res.json({ ok: true, released: false, reason: 'token has no jti (pre-jti issue)' });
353
- }
354
- const released = ownershipSessions.releaseSeat(payload.l, payload.jti);
355
- res.json({ ok: true, released, jti: payload.jti });
356
- });
357
- // POST /refresh — body: { token }
358
- // Extends the lifetime of the current session without a fresh ownership proof.
359
- // The caller sends the token they already hold; the server verifies the HMAC,
360
- // checks the jti is still active in the session store (i.e. not released or
361
- // evicted), and issues a new token with the same jti and a fresh exp. The
362
- // session store's insert is idempotent per jti, so no cap check is needed —
363
- // the slot was already reserved at /respond time.
364
- //
365
- // Intended for background renewal from a running app: the client polls this
366
- // endpoint before the token expires so a user who keeps the app open never
367
- // has to redo the passphrase-gated challenge/response. A stolen token can be
368
- // refreshed too, which is why /releaseSeat exists — losing a device means the
369
- // owner explicitly logs it out, and subsequent refreshes fail.
370
- //
371
- // Pre-jti tokens (legacy /respond without session tracking) can also refresh:
372
- // they're valid HMAC, they carry no jti, and there's no session-store row to
373
- // gate against. The reissued token is identically pre-jti. Callers that want
374
- // concurrency enforcement must reissue via /respond so a jti gets minted.
375
- app.post('/refresh', (req, res) => {
376
- const { token } = req.body;
377
- if (!token)
378
- return res.status(400).json({ error: 'Missing token' });
379
- const payload = verifyOwnershipToken(ownershipKey, token);
380
- if (!payload)
381
- return res.status(401).json({ error: 'Invalid or expired token' });
382
- const newExp = Date.now() + OWNERSHIP_TOKEN_TTL_MS;
383
- if (payload.jti) {
384
- if (!ownershipSessions.has(payload.l, payload.jti)) {
385
- return res.status(401).json({ error: 'Seat released' });
386
- }
387
- // Idempotent for existing jti — updates the expiry, never trips the cap.
388
- ownershipSessions.insert(payload.l, payload.jti, newExp, 0);
389
- }
390
- const next = {
391
- z: payload.z,
392
- l: payload.l,
393
- e: newExp,
394
- ...(payload.jti ? { jti: payload.jti } : {}),
395
- };
396
- const nextToken = signOwnershipToken(ownershipKey, next);
397
- res.json({ token: nextToken, expiresAt: newExp, jti: payload.jti });
398
- });
399
- // POST /reset-sessions — body: { zkAppAddress, proof }
400
- // Drops ALL active sessions for the licenseHash proved by the LicenseProof.
401
- // Requires the same challenge/response as /respond — only the passphrase
402
- // holder can invoke it. Intended for "reinstall unsticks a device that
403
- // burned a slot without logging out" recovery. After this returns, the
404
- // caller runs a fresh /respond to re-provision a session under a zero
405
- // active count.
406
- app.post('/reset-sessions', async (req, res) => {
407
- await ensureCompiled();
408
- if (!licenseProofVk) {
409
- return res.status(503).json({ error: 'Verify service not ready — circuits compiling' });
410
- }
411
- const { zkAppAddress, proof: proofJson } = req.body;
412
- if (!zkAppAddress || !proofJson) {
413
- return res.status(400).json({ error: 'Missing zkAppAddress or proof' });
414
- }
415
- let proof;
416
- try {
417
- proof = await LicenseProofProof.fromJSON(proofJson);
418
- }
419
- catch {
420
- return res.status(400).json({ error: 'Invalid proof format' });
421
- }
422
- let proofValid = false;
423
- try {
424
- proofValid = await verify(proof, licenseProofVk);
425
- }
426
- catch {
427
- return res.status(400).json({ error: 'Proof verification threw' });
428
- }
429
- if (!proofValid) {
430
- return res.status(400).json({ error: 'Proof is cryptographically invalid' });
431
- }
432
- const licenseHash = proof.publicInput.licenseHash.toString();
433
- const nonce = proof.publicInput.nonce.toString();
434
- const nonceState = ownershipChallenges.consume(licenseHash, nonce);
435
- if (nonceState !== 'ok') {
436
- return res.status(400).json({ error: `Nonce ${nonceState} — request a fresh /challenge` });
437
- }
438
- const dropped = ownershipSessions.reset(licenseHash);
439
- res.json({ ok: true, dropped });
440
- });
441
- // GET /?licenseHash=...&zkAppAddress=...[&token=...]
442
- // Primary endpoint for Android, iOS, PWA, and Node SDK license verification.
443
- //
444
- // Ownership semantics:
445
- // - Without `token`, the response describes the state of the on-chain leaf
446
- // only — it does NOT prove the caller owns the license. This is fine for
447
- // status displays; gate access behind /respond or pass a fresh
448
- // activation `token` in the query string.
449
- // - With `token`, the service checks the HMAC and refuses if the token isn't
450
- // for this (zkAppAddress, licenseHash) pair.
563
+ // GET /?licenseHash=...&zkAppAddress=...
564
+ // Primary endpoint for Android, PWA, and Node SDK license verification.
565
+ // Describes the on-chain state of the requested license leaf — validity,
566
+ // expiry slot, grace-period flag, purchaseSlot. Callers that need to prove
567
+ // ownership of the license (e.g. before revealing app features) do so via
568
+ // the passphrase-derived Pallas Schnorr keypair off-band — this endpoint is
569
+ // state-only.
451
570
  app.get('/', async (req, res) => {
452
- const { licenseHash: licenseHashStr, zkAppAddress, token } = req.query;
571
+ const { licenseHash: licenseHashStr, zkAppAddress } = req.query;
453
572
  if (!licenseHashStr || !zkAppAddress) {
454
573
  return res.status(400).json({ error: 'Missing required query params: licenseHash, zkAppAddress' });
455
574
  }
456
- let ownershipVerified = false;
457
- if (token) {
458
- const payload = verifyOwnershipToken(ownershipKey, token);
459
- if (!payload || payload.z !== zkAppAddress || payload.l !== licenseHashStr) {
460
- return res.status(401).json({ error: 'Invalid or expired ownership token' });
461
- }
462
- // Session-store gate: a jti-bearing token must still be in the active-
463
- // session set for its license. A token whose jti was released (via
464
- // /releaseSeat, /reset-sessions, or evicted by TTL prune) is refused even if
465
- // it's still HMAC-valid and inside its exp. Pre-jti tokens (issued
466
- // before the session-tracking rollout) skip this check and remain
467
- // usable until their exp — no forced logout across the migration.
468
- if (payload.jti && !ownershipSessions.has(payload.l, payload.jti)) {
469
- return res.status(401).json({ error: 'Seat released — call POST /respond to acquire a fresh token' });
470
- }
471
- ownershipVerified = true;
472
- }
473
- try {
474
- const [records, { account }, lastBlock] = await Promise.all([
475
- readRecords(),
476
- fetchAccount({ publicKey: PublicKey.fromBase58(zkAppAddress) }),
477
- fetchLastBlock(),
478
- ]);
479
- const onChainRoot = account?.zkapp?.appState?.[0]?.toString();
480
- if (!onChainRoot) {
481
- return res.status(404).json({ error: 'zkApp not found on chain' });
482
- }
483
- // Source-version tag from the already-fetched account state — free byte
484
- // for the SDK / dashboard to label which protocol revision a license lives
485
- // on. Not a security gate (that's the boot + bootstrap check); purely
486
- // informational.
487
- const zkAppVersion = Number(account?.zkapp?.appState?.[7]?.toString() ?? '0');
488
- // Defense in depth against impersonation. The contract locks
489
- // `setVerificationKey` via `Permissions.VerificationKey
490
- // .impossibleDuringCurrentVersion()` plus deploy-key disposal, so VK
491
- // rotation post-deploy is impossible for any *listed* address. The check
492
- // below resolves the address's generation via keeper deploymentHistory
493
- // and asserts its on-chain VK equals that generation's canonical hash.
494
- // Two failure modes: (a) the address is unknown (not the current live
495
- // deployment of any registered app, not in any deploymentHistory[]) —
496
- // reject; that stops a genuine old circuit deployed at a fresh address.
497
- // (b) the address is listed but its VK doesn't equal its generation's
498
- // hash — reject; that's a loud index-corruption tripwire.
499
- const onChainVk = account?.zkapp?.verificationKey?.hash?.toString();
500
- const generation = await resolveGenerationByAddress(zkAppAddress);
501
- if (generation === null) {
502
- return res.json({
503
- valid: false,
504
- expiresAt: null,
505
- expirySlot: 0,
506
- inGracePeriod: false,
507
- remainingDays: 0,
508
- reason: 'zkAppAddress is not in any registered app deployment history',
509
- ownership: ownershipVerified ? 'verified' : 'unverified',
510
- });
511
- }
512
- const expectedVk = CANONICAL_VK_HASHES[generation];
513
- if (expectedVk && onChainVk !== expectedVk) {
514
- return res.json({
515
- valid: false,
516
- expiresAt: null,
517
- expirySlot: 0,
518
- inGracePeriod: false,
519
- remainingDays: 0,
520
- reason: `zkApp verification key does not match generation ${generation}'s canonical LicensingApp circuit`,
521
- ownership: ownershipVerified ? 'verified' : 'unverified',
522
- });
523
- }
524
- const currentSlot = Number(lastBlock.globalSlotSinceGenesis.toString());
525
- let liveRecords = records;
526
- let result = verifyLicenseCore({
527
- zkAppAddress,
528
- licenseHash: licenseHashStr,
529
- records: liveRecords,
530
- onChainRoot,
531
- currentSlot,
575
+ // Per-request verdict log. Redacts licenseHash to a 12-char prefix so logs
576
+ // stay pseudonymous but retain enough entropy to correlate a user's report
577
+ // ("my activation says invalid at 03:52") to the exact decision without
578
+ // grepping full hashes. resolvedAddress lets you see when an older
579
+ // generation was the actual match (pre-bump buyer).
580
+ const startedAt = Date.now();
581
+ const hashShort = licenseHashStr.slice(0, 12) + '…';
582
+ const emitVerdict = (verdict, reason, resolvedAddress) => {
583
+ logUtc('verify', 'verdict', {
584
+ licenseHash: hashShort,
585
+ zkAppAddress: zkAppAddress.slice(0, 12) + '…',
586
+ resolvedAddress: resolvedAddress ? resolvedAddress.slice(0, 12) + '…' : undefined,
587
+ verdict,
588
+ reason: reason ?? undefined,
589
+ elapsed_ms: Date.now() - startedAt,
532
590
  });
533
- // Lazy self-heal: a root mismatch means the local store is stale (a
534
- // license has been bought, renewed, or refunded since we last replayed).
535
- // One replay + one retry is enough — the on-chain root is the source of
536
- // truth and the archive node will reflect it.
537
- if (!result.valid && result.reason === 'License state does not match on-chain root') {
538
- await lazyBootstrap(zkAppAddress);
539
- liveRecords = await readRecords();
540
- result = verifyLicenseCore({
541
- zkAppAddress,
542
- licenseHash: licenseHashStr,
543
- records: liveRecords,
544
- onChainRoot,
545
- currentSlot,
546
- });
591
+ };
592
+ // Defense-in-depth against impersonation: the helper resolves the address's
593
+ // generation via keeper deploymentHistory and asserts its on-chain VK equals
594
+ // that generation's canonical hash. Two rejection modes it covers: (a) the
595
+ // address is not in any registered app's deployment history — stops a
596
+ // genuine old circuit redeployed at a fresh address; (b) the address is
597
+ // listed but its VK doesn't match — a loud index-corruption tripwire.
598
+ try {
599
+ const onChain = await checkOnChainLicense(zkAppAddress, licenseHashStr);
600
+ switch (onChain.kind) {
601
+ case 'zkapp-not-found':
602
+ emitVerdict('zkapp-not-found');
603
+ return res.status(404).json({ error: 'zkApp not found on chain' });
604
+ case 'unregistered-address':
605
+ emitVerdict('unregistered-address');
606
+ return res.json({
607
+ valid: false,
608
+ expiresAt: null,
609
+ expirySlot: 0,
610
+ inGracePeriod: false,
611
+ remainingDays: 0,
612
+ reason: 'zkAppAddress is not in any registered app deployment history',
613
+ });
614
+ case 'vk-mismatch':
615
+ emitVerdict('vk-mismatch', `generation=${onChain.generation}`);
616
+ return res.json({
617
+ valid: false,
618
+ expiresAt: null,
619
+ expirySlot: 0,
620
+ inGracePeriod: false,
621
+ remainingDays: 0,
622
+ reason: `zkApp verification key does not match generation ${onChain.generation}'s canonical LicensingApp circuit`,
623
+ });
624
+ case 'checked': {
625
+ // Key on resolvedAddress (the address the license was actually found
626
+ // under) rather than the request address — for pre-bump buyers who
627
+ // never migrated, these differ: request is the retired addr the
628
+ // client pinned, resolved is the retired addr the record lives on.
629
+ const record = onChain.liveRecords.find(r => r.zkAppAddress === onChain.resolvedAddress && r.licenseHash === licenseHashStr);
630
+ // Collapse the VerifyResponse shape into a single-word verdict for
631
+ // log scanning: valid | grace | invalid. `invalid` carries the
632
+ // core's own reason string ("License not found", "License state
633
+ // does not match on-chain root", …) so the log line is enough to
634
+ // triage without opening the JSON body.
635
+ const verdict = onChain.result.valid
636
+ ? (onChain.result.inGracePeriod ? 'grace' : 'valid')
637
+ : 'invalid';
638
+ emitVerdict(verdict, onChain.result.reason, onChain.resolvedAddress);
639
+ return res.json({
640
+ ...onChain.result,
641
+ currentSlot: onChain.currentSlot,
642
+ purchaseSlot: record?.purchaseSlot ?? 0,
643
+ zkAppVersion: onChain.zkAppVersion,
644
+ });
645
+ }
547
646
  }
548
- const record = liveRecords.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHashStr);
549
- return res.json({
550
- ...result,
551
- currentSlot,
552
- purchaseSlot: record?.purchaseSlot ?? 0,
553
- ownership: ownershipVerified ? 'verified' : 'unverified',
554
- zkAppVersion,
555
- });
556
647
  }
557
648
  catch (err) {
649
+ emitVerdict('error', err?.message ?? String(err));
558
650
  console.error('[verify]', err?.message ?? err);
559
651
  res.status(500).json({ error: err?.message ?? 'Verification failed' });
560
652
  }
561
653
  });
562
- // License map witness — composite (zkAppAddress, licenseHash) key.
654
+ // License map witness — composite (zkAppAddress, licenseHash) key. Network-
655
+ // agnostic — witness comes from the local MerkleMap of records.
563
656
  app.get('/witness/:zkAppAddress/:licenseHash', async (req, res) => {
564
657
  const { zkAppAddress, licenseHash } = req.params;
565
658
  try {
@@ -578,16 +671,30 @@ app.get('/witness/:zkAppAddress/:licenseHash', async (req, res) => {
578
671
  }
579
672
  });
580
673
  // License status — composite (zkAppAddress, licenseHash) key.
674
+ // deviceCap + devices ride along so vendor SDKs can drive their bind flow
675
+ // (activate() reads these to decide whether to prompt for a bind and which
676
+ // slot to target). Sourced from the license record, which is the on-chain
677
+ // mirror populated by eventSyncLoop from DeviceBound/DeviceUnbound events.
581
678
  app.get('/license/:zkAppAddress/:licenseHash', async (req, res) => {
582
679
  const { zkAppAddress, licenseHash } = req.params;
583
680
  const record = await getLicense(zkAppAddress, licenseHash);
584
- const slot = await currentSlot();
681
+ // Resolve the address's network so currentSlot hits the right chain. An
682
+ // unregistered address (or one whose network isn't configured here) falls
683
+ // back to slot 0 — status computation still returns a sensible verdict from
684
+ // the record's own expirySlot.
685
+ const apps = await readApps();
686
+ const resolved = resolveAppAndNetwork(apps, zkAppAddress);
687
+ const slot = resolved && NETWORK_CONFIG[resolved.network]
688
+ ? await currentSlot(resolved.network)
689
+ : 0;
585
690
  const status = licenseStatus(record, slot);
586
691
  res.json({
587
692
  found: record !== null,
588
693
  expirySlot: record?.expirySlot ?? 0,
589
694
  status,
590
695
  txHash: record?.txHash ?? null,
696
+ deviceCap: record?.deviceCap ?? 0,
697
+ devices: record?.devices ?? [],
591
698
  });
592
699
  });
593
700
  // List registered apps
@@ -605,11 +712,23 @@ app.post('/bootstrap', requireAdmin, async (req, res) => {
605
712
  if (!zkAppAddress) {
606
713
  return res.status(400).json({ error: 'Missing zkAppAddress' });
607
714
  }
715
+ const addrErr = validateZkAppAddress(zkAppAddress);
716
+ if (addrErr)
717
+ return res.status(400).json({ error: addrErr });
608
718
  try {
719
+ const apps = await readApps();
720
+ const resolved = resolveAppAndNetwork(apps, zkAppAddress);
721
+ if (!resolved) {
722
+ return res.status(400).json({ error: `zkAppAddress not in any registered app deployment history` });
723
+ }
724
+ const { network } = resolved;
725
+ if (!NETWORK_CONFIG[network]) {
726
+ return res.status(400).json({ error: `zkAppAddress belongs to ${network} but that network is not configured on this verifier` });
727
+ }
609
728
  // Refuse to replay a zkApp whose immutable source-version tag doesn't match
610
729
  // one this verifier understands. Otherwise a v2-deployed contract's events
611
730
  // could be decoded with a v1 schema and yield subtly wrong state.
612
- const onChainVersion = await fetchLicensingAppVersion(zkAppAddress);
731
+ const onChainVersion = await withNetwork(network, () => fetchLicensingAppVersion(zkAppAddress));
613
732
  if (onChainVersion === null) {
614
733
  return res.status(400).json({ error: `zkApp ${zkAppAddress.slice(0, 16)}… not visible on chain` });
615
734
  }
@@ -618,8 +737,9 @@ app.post('/bootstrap', requireAdmin, async (req, res) => {
618
737
  error: `unsupported LicensingApp version — on-chain v${onChainVersion}, this verifier supports v${SUPPORTED_LICENSING_APP_VERSIONS.join(', v')}`,
619
738
  });
620
739
  }
621
- console.log(`[bootstrap] Replaying events for ${zkAppAddress.slice(0, 16)}… (v${onChainVersion}) from ${archiveUrl}`);
622
- const { events } = await bootstrapFromArchive(zkAppAddress);
740
+ const cfg = NETWORK_CONFIG[network];
741
+ console.log(`[bootstrap] Replaying events for ${zkAppAddress.slice(0, 16)}… (${network} v${onChainVersion}) from ${cfg.archiveUrl}`);
742
+ const { events } = await withNetwork(network, () => bootstrapFromArchive(zkAppAddress));
623
743
  const { count, warnings } = await applyEventsToStore(zkAppAddress, events);
624
744
  for (const w of warnings)
625
745
  console.warn('[bootstrap]', w);
@@ -635,32 +755,43 @@ app.post('/bootstrap', requireAdmin, async (req, res) => {
635
755
  // START
636
756
  // ------------------------------------------------------------
637
757
  let records = await readRecords();
638
- // Auto-bootstrap from archive if store is empty.
758
+ // Auto-bootstrap from archive if store is empty. Iterates every configured
759
+ // network and each of that network's registered apps. Apps whose network
760
+ // isn't configured on this verifier are skipped silently.
639
761
  if (records.length === 0) {
640
762
  const apps = await readApps();
641
- if (apps.length > 0) {
642
- console.log(`📦 licenses.json is empty — bootstrapping ${apps.length} app(s) from archive node…`);
643
- for (const appRecord of apps) {
763
+ const configuredNetworks = NETWORKS.filter(n => !!NETWORK_CONFIG[n]);
764
+ const bootstrapPlan = [];
765
+ for (const network of configuredNetworks) {
766
+ for (const app of apps) {
767
+ const dep = app.deployments[network];
768
+ if (dep)
769
+ bootstrapPlan.push({ network, app, dep });
770
+ }
771
+ }
772
+ if (bootstrapPlan.length > 0) {
773
+ console.log(`📦 licenses.json is empty — bootstrapping ${bootstrapPlan.length} app deployment(s) from archive node…`);
774
+ for (const { network, app: appRecord, dep } of bootstrapPlan) {
644
775
  try {
645
776
  // Same version guard as POST /bootstrap — refuse to replay any address
646
777
  // whose on-chain source-version tag this verifier doesn't understand.
647
- const onChainVersion = await fetchLicensingAppVersion(appRecord.zkAppAddress);
778
+ const onChainVersion = await withNetwork(network, () => fetchLicensingAppVersion(dep.zkAppAddress));
648
779
  if (onChainVersion === null) {
649
- console.warn(` ⚠️ ${appRecord.name}: zkApp not visible on chain — skipping`);
780
+ console.warn(` ⚠️ ${appRecord.name} (${network}): zkApp not visible on chain — skipping`);
650
781
  continue;
651
782
  }
652
783
  if (!SUPPORTED_LICENSING_APP_VERSIONS.includes(onChainVersion)) {
653
- console.warn(` ⚠️ ${appRecord.name}: on-chain v${onChainVersion} not supported (supports v${SUPPORTED_LICENSING_APP_VERSIONS.join(', v')}) — skipping`);
784
+ console.warn(` ⚠️ ${appRecord.name} (${network}): on-chain v${onChainVersion} not supported (supports v${SUPPORTED_LICENSING_APP_VERSIONS.join(', v')}) — skipping`);
654
785
  continue;
655
786
  }
656
- const { events } = await bootstrapFromArchive(appRecord.zkAppAddress);
657
- const { count, warnings } = await applyEventsToStore(appRecord.zkAppAddress, events);
787
+ const { events } = await withNetwork(network, () => bootstrapFromArchive(dep.zkAppAddress));
788
+ const { count, warnings } = await applyEventsToStore(dep.zkAppAddress, events);
658
789
  for (const w of warnings)
659
790
  console.warn('⚠️', w);
660
- console.log(` ✅ ${appRecord.name} (v${onChainVersion}): ${count} records`);
791
+ console.log(` ✅ ${appRecord.name} (${network} v${onChainVersion}): ${count} records`);
661
792
  }
662
793
  catch (err) {
663
- console.warn(` ⚠️ ${appRecord.name}: bootstrap failed — ${err?.message ?? err}`);
794
+ console.warn(` ⚠️ ${appRecord.name} (${network}): bootstrap failed — ${err?.message ?? err}`);
664
795
  }
665
796
  }
666
797
  records = await readRecords();
@@ -669,12 +800,7 @@ if (records.length === 0) {
669
800
  console.log(`📋 Loaded ${records.length} license records across ${new Set(records.map(r => r.zkAppAddress)).size} zkApp(s)`);
670
801
  app.listen(PORT, () => {
671
802
  console.log(`🔍 Verify service listening on http://localhost:${PORT}`);
672
- console.log(` GET /?licenseHash=...&zkAppAddress=...[&token=...]`);
673
- console.log(` GET /challenge?licenseHash=...`);
674
- console.log(` POST /respond`);
675
- console.log(` POST /refresh`);
676
- console.log(` POST /releaseSeat`);
677
- console.log(` POST /reset-sessions`);
803
+ console.log(` GET /?licenseHash=...&zkAppAddress=...`);
678
804
  console.log(` GET /witness/:zkAppAddress/:licenseHash`);
679
805
  console.log(` GET /license/:zkAppAddress/:licenseHash`);
680
806
  console.log(` GET /apps`);
@@ -686,5 +812,6 @@ app.listen(PORT, () => {
686
812
  console.log(`⚠️ Admin endpoints disabled (set VERIFY_ADMIN_TOKEN to enable)`);
687
813
  }
688
814
  console.log(`🔁 Lazy bootstrap on root mismatch (no periodic poller)`);
815
+ console.log(`📝 Access log: ${ACCESS_LOG_ENABLED ? 'ON' : 'off (VERIFY_ACCESS_LOG=off)'}`);
689
816
  });
690
817
  //# sourceMappingURL=verifyService.js.map