zklicensing 0.1.0-beta.15 → 0.1.0-beta.17

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 (264) hide show
  1. package/README.md +92 -88
  2. package/build/agent.d.ts +369 -0
  3. package/build/agent.d.ts.map +1 -0
  4. package/build/agent.js +549 -0
  5. package/build/agent.js.map +1 -0
  6. package/build/agentActions.d.ts +827 -0
  7. package/build/agentActions.d.ts.map +1 -0
  8. package/build/agentActions.js +543 -0
  9. package/build/agentActions.js.map +1 -0
  10. package/build/agentRecord.d.ts +83 -0
  11. package/build/agentRecord.d.ts.map +1 -0
  12. package/build/agentRecord.js +69 -0
  13. package/build/agentRecord.js.map +1 -0
  14. package/build/agentVendor.d.ts +220 -0
  15. package/build/agentVendor.d.ts.map +1 -0
  16. package/build/agentVendor.js +292 -0
  17. package/build/agentVendor.js.map +1 -0
  18. package/build/archiveBootstrap.d.ts +12 -4
  19. package/build/archiveBootstrap.d.ts.map +1 -1
  20. package/build/archiveBootstrap.js +32 -33
  21. package/build/archiveBootstrap.js.map +1 -1
  22. package/build/atomicJson.d.ts +5 -0
  23. package/build/atomicJson.d.ts.map +1 -0
  24. package/build/atomicJson.js +55 -0
  25. package/build/atomicJson.js.map +1 -0
  26. package/build/bindClient.d.ts +15 -1
  27. package/build/bindClient.d.ts.map +1 -1
  28. package/build/bindClient.js +25 -2
  29. package/build/bindClient.js.map +1 -1
  30. package/build/buyClient.d.ts +15 -0
  31. package/build/buyClient.d.ts.map +1 -1
  32. package/build/buyClient.js +30 -4
  33. package/build/buyClient.js.map +1 -1
  34. package/build/chainHead.d.ts +61 -0
  35. package/build/chainHead.d.ts.map +1 -0
  36. package/build/chainHead.js +88 -0
  37. package/build/chainHead.js.map +1 -0
  38. package/build/compactMerkleMap.d.ts +72 -0
  39. package/build/compactMerkleMap.d.ts.map +1 -0
  40. package/build/compactMerkleMap.js +224 -0
  41. package/build/compactMerkleMap.js.map +1 -0
  42. package/build/contractInterface.d.ts +189 -55
  43. package/build/contractInterface.d.ts.map +1 -1
  44. package/build/contractInterface.js +163 -37
  45. package/build/contractInterface.js.map +1 -1
  46. package/build/contractTypes.d.ts +9 -0
  47. package/build/contractTypes.d.ts.map +1 -0
  48. package/build/contractTypes.js +28 -0
  49. package/build/contractTypes.js.map +1 -0
  50. package/build/countryStats.d.ts +5 -1
  51. package/build/countryStats.d.ts.map +1 -1
  52. package/build/countryStats.js +61 -21
  53. package/build/countryStats.js.map +1 -1
  54. package/build/deployClient.d.ts +126 -20
  55. package/build/deployClient.d.ts.map +1 -1
  56. package/build/deployClient.js +76 -19
  57. package/build/deployClient.js.map +1 -1
  58. package/build/freezeClient.d.ts +23 -3
  59. package/build/freezeClient.d.ts.map +1 -1
  60. package/build/freezeClient.js +27 -3
  61. package/build/freezeClient.js.map +1 -1
  62. package/build/generationClient.d.ts +2 -0
  63. package/build/generationClient.d.ts.map +1 -1
  64. package/build/generationClient.js +17 -30
  65. package/build/generationClient.js.map +1 -1
  66. package/build/holderSecret.d.ts +70 -0
  67. package/build/holderSecret.d.ts.map +1 -0
  68. package/build/holderSecret.js +76 -0
  69. package/build/holderSecret.js.map +1 -0
  70. package/build/index.d.ts +7 -4
  71. package/build/index.d.ts.map +1 -1
  72. package/build/index.js +28 -17
  73. package/build/index.js.map +1 -1
  74. package/build/keysClient.d.ts +142 -0
  75. package/build/keysClient.d.ts.map +1 -0
  76. package/build/keysClient.js +109 -0
  77. package/build/keysClient.js.map +1 -0
  78. package/build/licenseRecord.d.ts +46 -3
  79. package/build/licenseRecord.d.ts.map +1 -1
  80. package/build/licenseRecord.js +25 -0
  81. package/build/licenseRecord.js.map +1 -1
  82. package/build/licenseStore.d.ts +63 -3
  83. package/build/licenseStore.d.ts.map +1 -1
  84. package/build/licenseStore.js +207 -30
  85. package/build/licenseStore.js.map +1 -1
  86. package/build/licenseTrustless.d.ts +43 -0
  87. package/build/licenseTrustless.d.ts.map +1 -0
  88. package/build/licenseTrustless.js +180 -0
  89. package/build/licenseTrustless.js.map +1 -0
  90. package/build/manifestVerify.d.ts +28 -0
  91. package/build/manifestVerify.d.ts.map +1 -1
  92. package/build/manifestVerify.js +37 -0
  93. package/build/manifestVerify.js.map +1 -1
  94. package/build/onChainRoot.d.ts +3 -10
  95. package/build/onChainRoot.d.ts.map +1 -1
  96. package/build/onChainRoot.js +10 -25
  97. package/build/onChainRoot.js.map +1 -1
  98. package/build/ownershipSignature.d.ts +31 -0
  99. package/build/ownershipSignature.d.ts.map +1 -1
  100. package/build/ownershipSignature.js +54 -1
  101. package/build/ownershipSignature.js.map +1 -1
  102. package/build/permitCheckFlow.d.ts +155 -0
  103. package/build/permitCheckFlow.d.ts.map +1 -0
  104. package/build/permitCheckFlow.js +196 -0
  105. package/build/permitCheckFlow.js.map +1 -0
  106. package/build/permitDescribe.d.ts +124 -0
  107. package/build/permitDescribe.d.ts.map +1 -0
  108. package/build/permitDescribe.js +324 -0
  109. package/build/permitDescribe.js.map +1 -0
  110. package/build/permitInterface.d.ts +85 -0
  111. package/build/permitInterface.d.ts.map +1 -0
  112. package/build/permitInterface.js +121 -0
  113. package/build/permitInterface.js.map +1 -0
  114. package/build/permitMessages.d.ts +313 -0
  115. package/build/permitMessages.d.ts.map +1 -0
  116. package/build/permitMessages.js +462 -0
  117. package/build/permitMessages.js.map +1 -0
  118. package/build/permitProof.d.ts +108 -0
  119. package/build/permitProof.d.ts.map +1 -0
  120. package/build/permitProof.js +202 -0
  121. package/build/permitProof.js.map +1 -0
  122. package/build/permitRegistryRebuild.d.ts +166 -0
  123. package/build/permitRegistryRebuild.d.ts.map +1 -0
  124. package/build/permitRegistryRebuild.js +347 -0
  125. package/build/permitRegistryRebuild.js.map +1 -0
  126. package/build/permitTree.d.ts +88 -0
  127. package/build/permitTree.d.ts.map +1 -0
  128. package/build/permitTree.js +230 -0
  129. package/build/permitTree.js.map +1 -0
  130. package/build/permitsClient.d.ts +680 -0
  131. package/build/permitsClient.d.ts.map +1 -0
  132. package/build/permitsClient.js +597 -0
  133. package/build/permitsClient.js.map +1 -0
  134. package/build/proveErrors.d.ts +1 -1
  135. package/build/proveErrors.js +1 -1
  136. package/build/receipt.d.ts +90 -0
  137. package/build/receipt.d.ts.map +1 -0
  138. package/build/receipt.js +83 -0
  139. package/build/receipt.js.map +1 -0
  140. package/build/refundClient.d.ts +3 -0
  141. package/build/refundClient.d.ts.map +1 -1
  142. package/build/refundClient.js +5 -3
  143. package/build/refundClient.js.map +1 -1
  144. package/build/registryTrustVerify.d.ts +78 -0
  145. package/build/registryTrustVerify.d.ts.map +1 -0
  146. package/build/registryTrustVerify.js +129 -0
  147. package/build/registryTrustVerify.js.map +1 -0
  148. package/build/releaseClient.d.ts +26 -0
  149. package/build/releaseClient.d.ts.map +1 -0
  150. package/build/releaseClient.js +65 -0
  151. package/build/releaseClient.js.map +1 -0
  152. package/build/renewClient.d.ts +22 -0
  153. package/build/renewClient.d.ts.map +1 -1
  154. package/build/renewClient.js +5 -19
  155. package/build/renewClient.js.map +1 -1
  156. package/build/slotConstants.d.ts +15 -0
  157. package/build/slotConstants.d.ts.map +1 -0
  158. package/build/slotConstants.js +17 -0
  159. package/build/slotConstants.js.map +1 -0
  160. package/build/statsClient.d.ts +8 -0
  161. package/build/statsClient.d.ts.map +1 -1
  162. package/build/statsClient.js.map +1 -1
  163. package/build/successorChain.d.ts +35 -0
  164. package/build/successorChain.d.ts.map +1 -0
  165. package/build/successorChain.js +69 -0
  166. package/build/successorChain.js.map +1 -0
  167. package/build/taxId.d.ts +44 -0
  168. package/build/taxId.d.ts.map +1 -0
  169. package/build/taxId.js +212 -0
  170. package/build/taxId.js.map +1 -0
  171. package/build/trustAnchorVerify.d.ts +1 -0
  172. package/build/trustAnchorVerify.d.ts.map +1 -1
  173. package/build/trustAnchorVerify.js +67 -94
  174. package/build/trustAnchorVerify.js.map +1 -1
  175. package/build/trustAnchorVerifyCli.d.ts +10 -0
  176. package/build/trustAnchorVerifyCli.d.ts.map +1 -1
  177. package/build/trustAnchorVerifyCli.js +42 -0
  178. package/build/trustAnchorVerifyCli.js.map +1 -1
  179. package/build/unbindClient.d.ts +2 -0
  180. package/build/unbindClient.d.ts.map +1 -1
  181. package/build/unbindClient.js +7 -0
  182. package/build/unbindClient.js.map +1 -1
  183. package/build/units.d.ts +28 -0
  184. package/build/units.d.ts.map +1 -0
  185. package/build/units.js +65 -0
  186. package/build/units.js.map +1 -0
  187. package/build/vatRates.d.ts +54 -0
  188. package/build/vatRates.d.ts.map +1 -0
  189. package/build/vatRates.js +82 -0
  190. package/build/vatRates.js.map +1 -0
  191. package/build/vatRatesData.d.ts +5 -0
  192. package/build/vatRatesData.d.ts.map +1 -0
  193. package/build/vatRatesData.js +42 -0
  194. package/build/vatRatesData.js.map +1 -0
  195. package/build/vendorAccountClient.d.ts +8 -2
  196. package/build/vendorAccountClient.d.ts.map +1 -1
  197. package/build/vendorAccountClient.js +6 -6
  198. package/build/vendorAccountClient.js.map +1 -1
  199. package/build/verifyCore.d.ts +3 -0
  200. package/build/verifyCore.d.ts.map +1 -1
  201. package/build/verifyCore.js +10 -6
  202. package/build/verifyCore.js.map +1 -1
  203. package/build/verifyService.js +17 -76
  204. package/build/verifyService.js.map +1 -1
  205. package/build/verifyWithAncestors.d.ts +1 -0
  206. package/build/verifyWithAncestors.d.ts.map +1 -1
  207. package/build/verifyWithAncestors.js +11 -3
  208. package/build/verifyWithAncestors.js.map +1 -1
  209. package/package.json +90 -9
  210. package/src/agent.ts +679 -0
  211. package/src/agentActions.ts +596 -0
  212. package/src/agentRecord.ts +121 -0
  213. package/src/agentVendor.ts +345 -0
  214. package/src/archiveBootstrap.ts +37 -36
  215. package/src/atomicJson.ts +53 -0
  216. package/src/bindClient.ts +44 -2
  217. package/src/buyClient.ts +35 -6
  218. package/src/chainHead.ts +106 -0
  219. package/src/compactMerkleMap.ts +222 -0
  220. package/src/contractInterface.ts +190 -38
  221. package/src/contractTypes.ts +31 -0
  222. package/src/countryStats.ts +50 -21
  223. package/src/deployClient.ts +213 -101
  224. package/src/freezeClient.ts +51 -6
  225. package/src/generationClient.ts +20 -40
  226. package/src/holderSecret.ts +91 -0
  227. package/src/index.ts +39 -17
  228. package/src/keysClient.ts +135 -0
  229. package/src/licenseRecord.ts +80 -9
  230. package/src/licenseStore.ts +221 -28
  231. package/src/licenseTrustless.ts +207 -0
  232. package/src/manifestVerify.ts +53 -0
  233. package/src/onChainRoot.ts +10 -29
  234. package/src/ownershipSignature.ts +69 -2
  235. package/src/permitCheckFlow.ts +227 -0
  236. package/src/permitDescribe.ts +362 -0
  237. package/src/permitInterface.ts +146 -0
  238. package/src/permitMessages.ts +572 -0
  239. package/src/permitProof.ts +230 -0
  240. package/src/permitRegistryRebuild.ts +423 -0
  241. package/src/permitTree.ts +232 -0
  242. package/src/permitsClient.ts +746 -0
  243. package/src/proveErrors.ts +1 -1
  244. package/src/receipt.ts +153 -0
  245. package/src/refundClient.ts +7 -4
  246. package/src/registryTrustVerify.ts +192 -0
  247. package/src/releaseClient.ts +101 -0
  248. package/src/renewClient.ts +10 -2
  249. package/src/slotConstants.ts +18 -0
  250. package/src/statsClient.ts +7 -0
  251. package/src/successorChain.ts +87 -0
  252. package/src/taxId.ts +227 -0
  253. package/src/trustAnchorVerify.ts +69 -97
  254. package/src/trustAnchorVerifyCli.ts +38 -0
  255. package/src/unbindClient.ts +11 -0
  256. package/src/units.ts +74 -0
  257. package/src/vatRates.ts +100 -0
  258. package/src/vatRatesData.ts +43 -0
  259. package/src/vendorAccountClient.ts +13 -7
  260. package/src/verifyCore.ts +14 -6
  261. package/src/verifyService.ts +19 -9
  262. package/src/verifyWithAncestors.ts +13 -3
  263. package/src/contractInterface.d.ts +0 -61
  264. package/src/migrateClient.ts +0 -84
package/README.md CHANGED
@@ -76,7 +76,7 @@ type VerifyResult = {
76
76
  function verifyLicense(proof: ProofInput, options?: VerifyOptions): Promise<VerifyResult>;
77
77
  ```
78
78
 
79
- The refund-window decision is server-side: the verifier returns `refundWindowClosed: boolean` on its `/verify` response, computed from its own `purchaseSlot` record against the on-chain `currentSlot`. The SDK gates anchor writes on that boolean and never trusts a `purchaseSlot` supplied by the local proof file, so a user who forges their proof metadata cannot force the offline branch prematurely.
79
+ The refund-window decision is server-side: the verifier returns `refundWindowClosed: boolean` on its `/verify` response, computed from its own `purchaseSlot` record against the on-chain `currentSlot`. The SDK gates anchor writes on that boolean and never trusts a `purchaseSlot` supplied by the local license file, so a user who forges their proof metadata cannot force the offline branch prematurely.
80
80
 
81
81
  The package also re-exports the three constants the SDK uses internally:
82
82
 
@@ -135,7 +135,7 @@ await confirmBind({ keeperUrl, zkAppAddress, licenseHash, txHash });
135
135
  - Unbinding stamps `freedAt = currentSlot`; the slot cannot be re-bound until `COOLDOWN_SLOTS_N = 6_720` slots (≈ 7 days at 90 s/slot) have elapsed. The cooldown is a flat one-week wait for every tier (monthly, yearly, five-year), independent of `deviceCap` — one number to reason about, not a per-tier formula.
136
136
  - `deviceCap = 0` disables binding entirely — `bind()` rejects with "bindings disabled" and no slot state is written to the leaf.
137
137
  - Cap is committed to the leaf at buy time and immutable for the life of the license. A vendor cannot tighten enforcement retroactively.
138
- - Bindings survive cross-generation migration: `migrateLicense` copies the ancestor leaf verbatim (including the device slot array) into the successor tree.
138
+ - Bindings survive a redeploy: the successor starts with its predecessor's licenses tree as it was at retirement (device slots included), checked on chain.
139
139
 
140
140
  **Offline verification.** After bind, the SDK caches the leaf's slot array locally. `verifyOffline` compares the device's local Poseidon commitment against `occupiedSlot[]`; a stolen laptop's commitment vanishing from the slot array denies access on the next launch without any network call.
141
141
 
@@ -229,7 +229,7 @@ Three drop-in pages, one SDK. Fork them, restyle, ship.
229
229
  - **`examples/renew.html`** — one click, one wallet prompt.
230
230
  - **`examples/refund.html`** — 14-day window, handled.
231
231
  - **`examples/bind.html`** / **`examples/unbind.html`** — device-slot writes for `deviceCap > 0` apps.
232
- - **`examples/verify.html`** — non-custodial verify: paste proof.json → witness + record from the service, root from Mina, folded locally.
232
+ - **`examples/verify.html`** — non-custodial verify: paste license file → witness + record from the service, root from Mina, folded locally.
233
233
 
234
234
  Each page is a self-contained HTML + TS pair calling one SDK subpath.
235
235
 
@@ -262,13 +262,13 @@ The main entry point (`zklicensing`) covers licence verification. Additional ent
262
262
 
263
263
  ### Per-app in-flight proving guard
264
264
 
265
- `/prove/buy`, `/prove/buy-no-escrow`, `/prove/renew`, `/prove/migrate`, and `/prove/refund` all mutate the same on-chain `licensesRoot` (and, for buy/refund, `escrowRoot`) preconditions. Two proofs assembled against the same pre-state root within one landing window are mutually exclusive — the chain admits whichever lands first, the second's precondition fails and the tx is dropped. Left unguarded, the second buyer pays the wallet-popup + fee for a doomed tx.
265
+ `/prove/buy`, `/prove/buy-no-escrow`, `/prove/renew`, and `/prove/refund` all mutate the same on-chain `licensesRoot` (and, for buy/refund, `escrowRoot`) preconditions. Two proofs assembled against the same pre-state root within one landing window are mutually exclusive — the chain admits whichever lands first, the second's precondition fails and the tx is dropped. Left unguarded, the second buyer pays the wallet-popup + fee for a doomed tx.
266
266
 
267
- The keeper defends against this with a **per-app in-flight slot** shared across all five endpoints. While the slot is held, a second concurrent request for the same app receives an immediate `409 { error: "proving queue busy", retryAfterMs, queueDepth }` — before any circuit work or wallet prompt. The SDK surfaces this as a shared `ProveQueueBusyError` (from `zklicensing/prove-errors`) thrown by `proveBuy`, `proveRenew`, `proveMigrate`, and `proveRefund`. Callers wait `retryAfterMs`, then retry — no popup, no fee, no signed-tx-doomed-to-fail.
267
+ The keeper defends against this with a **per-app in-flight slot** shared across all four endpoints. While the slot is held, a second concurrent request for the same app receives an immediate `409 { error: "proving queue busy", retryAfterMs, queueDepth }` — before any circuit work or wallet prompt. The SDK surfaces this as a shared `ProveQueueBusyError` (from `zklicensing/prove-errors`) thrown by `proveBuy`, `proveRenew`, and `proveRefund`. Callers wait `retryAfterMs`, then retry — no popup, no fee, no signed-tx-doomed-to-fail.
268
268
 
269
269
  Each prove response carries an `appKey` field — the same value the keeper uses to key the slot. After the wallet returns a tx hash, the SDK client calls `notifyBroadcast({ keeperUrl, appId: appKey, txHash })` (from `zklicensing/tx-broadcast`, fire-and-forget) to extend the slot's TTL from signing-TTL to landing-TTL, giving the honest broadcast room to land before another prove goes through.
270
270
 
271
- See [`zklicensing/prove-errors`](#zklicensingprove-errors--shared-typed-errors) and [`zklicensing/tx-broadcast`](#zklicensingtx-broadcast--broadcast-signal) below; each of `zklicensing/buy`, `zklicensing/renew`, `zklicensing/migrate` references this contract.
271
+ See [`zklicensing/prove-errors`](#zklicensingprove-errors--shared-typed-errors) and [`zklicensing/tx-broadcast`](#zklicensingtx-broadcast--broadcast-signal) below; each of `zklicensing/buy` and `zklicensing/renew` references this contract.
272
272
 
273
273
  ### `zklicensing/deploy` — deploy flow client
274
274
 
@@ -294,9 +294,11 @@ const status = await pollDeployStatus({ keeperUrl, zkAppAddress });
294
294
 
295
295
  The SDK does not expose a raw `initialize()` helper. `initialize()` sets `vendor` on-chain and is guarded only by a `vendor.requireEquals(PublicKey.empty())` precondition — no in-circuit signature check (adding one collides with the proof-based `editState` permission that `deploy()` installs). Front-running is prevented operationally instead: the backend puts `deploy()` and `initialize()` in the same `Mina.transaction`, and the throwaway zkApp keypair is generated inside the handler and dropped at return, so the target address is not observable to an attacker until the initialize AU is already signed and locked to `(vendor, prices)`. Drivers bypassing `proveDeploy` are responsible for the same discipline.
296
296
 
297
- #### Post-hardfork redeploy
297
+ #### Redeploy (hard fork)
298
298
 
299
- After a Mina hardfork relaxes `impossibleDuringCurrentVersion` back to `signature()`, every existing zkApp becomes uneditable in place (deploy keys are already discarded). Vendors migrate their app to a fresh v2 address themselves. Authentication is a Mina signature against the on-chain vendor of the target app, and the vendor pays gas via their own fee-payer AU. Three-step flow, mirroring the first-time deploy:
299
+ A redeploy moves an app to a fresh zkApp address in two on-chain steps. **Retire**: the old app, with an empty escrow, freezes its licenses tree; the vendor's key (or the platform key, on a platform redeploy) signs it. **Successor**: the new app starts with that frozen tree — its initialization checks on chain that the predecessor is retired at that root with the same vendor, prices and device cap, and its `appCreated` event names the predecessor. Licenses carry on there under the same hashes; nothing for buyers to do. Before a hard fork only the retire happens (the old circuit can't prove after the fork); the successor follows after it. A license that lapsed during the pre-fork sales freeze renews from the fork slot (`effectiveExpirySlot`).
300
+
301
+ Authentication is a Mina signature against the on-chain vendor of the target app, and the vendor's wallet pays for every step (the retire and the successor), as the admin wallet does on a platform redeploy: the keeper proves each step and holds no key.
300
302
 
301
303
  ```ts
302
304
  import {
@@ -306,39 +308,34 @@ import {
306
308
  pollDeployStatus,
307
309
  } from 'zklicensing/deploy';
308
310
 
309
- // 1. Ask the backend for a single-use signing challenge.
310
- const { nonce } = await getVendorRedeployChallenge({ keeperUrl, appId });
311
-
312
- // 2. Vendor's wallet signs the nonce (Auro / Mina wallet's mina_signMessage
313
- // or the equivalent that returns a Signature.toObject() form).
314
- const signature = await wallet.signMessage(nonce); // { field, scalar }
315
-
316
- // 3. Backend verifies signature against on-chain vendor, runs all redeploy
317
- // guards, generates a throwaway zkApp keypair, and returns the proven tx
318
- // for the wallet to sign + broadcast.
319
- const { provenTxJson, zkAppAddress, redeployId } = await proveVendorRedeploy({
320
- keeperUrl, appId,
321
- nonce,
322
- signature,
323
- senderPublicKey: vendorAddress, // fee payer
324
- // force: true, // optional — bypass escrow-empty guard
325
- });
326
-
327
- // 4. Wallet adds the fee-payer signature and broadcasts (same as proveDeploy).
328
- const { hash: txHash } = await wallet.sendTransaction({ transaction: provenTxJson });
329
-
330
- // 5. Register the pending redeploy so the backend arms its deploy-watcher.
331
- // On landing, the backend promotes the new deployment onto the AppRecord
332
- // (push old to deploymentHistory[], overwrite live fields, clear sync cursors).
333
- await registerVendorRedeploy({ keeperUrl, appId, redeployId, txHash });
311
+ let retireSignature: string | undefined;
312
+ for (;;) {
313
+ // 1. A single-use signing challenge (one per prove call), signed by the vendor's wallet.
314
+ const { nonce } = await getVendorRedeployChallenge({ keeperUrl, appId });
315
+ const signature = await wallet.signMessage(nonce); // { field, scalar }
316
+
317
+ // 2. The backend verifies the signature against the on-chain vendor, runs
318
+ // the redeploy guards and answers with the next step.
319
+ const r = await proveVendorRedeploy({ keeperUrl, appId, nonce, signature, senderPublicKey: vendorAddress, retireSignature });
320
+ if ('status' in r && r.status === 'draining') break; // sales paused; come back after r.readyAt
321
+ if ('status' in r && r.status === 'sign-retire') { // the vendor signs the retirement
322
+ retireSignature = await wallet.signFields(r.retireMessage); // base58
323
+ continue;
324
+ }
334
325
 
335
- // 6. Poll for landing.
336
- await pollDeployStatus({ keeperUrl, zkAppAddress });
326
+ // 3. The wallet adds the fee-payer signature, sends and pays for the step.
327
+ const { hash: txHash } = await wallet.sendTransaction({ transaction: r.provenTxJson });
328
+ // 4. Register it: a retire is marked (before a fork; the successor follows
329
+ // after it), a deploy is promoted when it lands.
330
+ await registerVendorRedeploy({ keeperUrl, appId, redeployId: r.redeployId, txHash });
331
+ if (r.step !== 'retire') await pollDeployStatus({ keeperUrl, zkAppAddress: r.zkAppAddress });
332
+ break;
333
+ }
337
334
  ```
338
335
 
339
- Guards enforced by the backend before proving: freeze slot configured, refund window closed past `FREEZE_AFTER_SLOT + REFUND_WINDOW`, app status `active`, on-chain version in `SUPPORTED_LICENSING_APP_VERSIONS`. The nonce expires 60 seconds after `getVendorRedeployChallenge` returns; consumed on `proveVendorRedeploy`.
336
+ Guards enforced by the backend before proving: freeze slot configured, refund window closed past `FREEZE_AFTER_SLOT + REFUND_WINDOW`, escrow empty, app status `active`, on-chain version in `SUPPORTED_LICENSING_APP_VERSIONS`. The nonce expires 60 seconds after `getVendorRedeployChallenge` returns; consumed on `proveVendorRedeploy`.
340
337
 
341
- Pass `force: true` to bypass the `escrowRoot === EMPTY_ROOT` guard when a straggling refund is still in flight and the vendor accepts responsibility for the unrefunded balance. Other guards remain strict. Unrefunded buyers retain the refund path against the retired v1 address; its on-chain state persists indefinitely, and the retired address stays in `AppRecord.deploymentHistory[]` for out-of-band buyer notification.
338
+ An app retires only with an empty escrow (the circuit requires it): refunds and releases must be done first.
342
339
 
343
340
  > **Buy links auto-update — vendor-embedded links do not.** `proveVendorRedeploy` returns a fresh `zkAppAddress`. The platform marketplace stores your `buyUrl`/`renewUrl`/`refundUrl` as **base URLs** and appends `?app=<zkAppAddress>&network=<net>` at render time, so the "Get" button on the `/apps` listing routes buyers to the new v2 address automatically the moment `finalizeRedeploy` promotes it onto the AppRecord — no vendor action required. Only surfaces where you have hand-embedded the raw `zkAppAddress` yourself (landing pages, docs, emails, screenshots) need manual updating. Existing licenses on the retired v1 address remain independently verifiable.
344
341
 
@@ -379,13 +376,13 @@ Two properties matter for integrators:
379
376
 
380
377
  This is what `buy.html` and `renew.html` on zklicensing.com call — an inactive-listing app can still be bought and renewed against so long as its on-chain LicensingApp is live. Use this endpoint when starting from a `zkAppAddress` (URL param, wallet paste); use `GET /apps/:appId` when you already know the stable app ID and only need the lineage.
381
378
 
382
- On renew, `renew.ts` fetches this endpoint and, if the licence's `zkAppAddress` is retired, presents a **blocking** "Migrate & Renew" flow (the keeper 409s `/prove/renew` and `/prove/buy*` on retired addresses — buyer-held renewals against a retired tree would silently strand). Migration is a single call — no hop-walking — and copies the current expiry verbatim into the live map; see `zklicensing/migrate` below.
379
+ On renew, `renew.ts` fetches this endpoint and, if the licence's `zkAppAddress` is retired, renews on the current one instead: the successor started with the retired app's licenses, so the licence is there under the same hash (the keeper 409s `/prove/renew` and `/prove/buy*` on retired addresses, and a retired app refuses them on chain).
383
380
 
384
381
  **Signed generation-list, pin-verified.** The response body carries a `publicKey` + `signature` over the canonical `{ appId, current, generations, issuedAt }` payload, signed with the platform manifest Ed25519 key (the same key material that signs the freeze manifest). The SDK verifies against a caller-supplied pin list (`fetchGenerationInfo({ pinnedPublicKeysBase64 })`, see `zklicensing/generation` below) and fails closed — `verified: false` with `current: null` and `generations: []` — when the signature doesn't match. The keeper is not the trust anchor; the pin list is.
385
382
 
386
- Snapshot atomicity: `finalizeRedeploy` gates a retiring generation from all `/prove/*` handlers **before** draining the tolerance window, capturing `frozenRoot`, and persisting — so any buyer-held `provenTxJson` proven against the retiring tree becomes unlandable inside the drain window rather than accidentally landing after the ancestor root is composed.
383
+ Retirement atomicity: the keeper gates a retiring generation from all `/prove/*` handlers **before** draining the tolerance window and retiring it — so any buyer-held `provenTxJson` proven against the retiring tree becomes unlandable inside the drain window; after `retire` the app refuses writes on chain.
387
384
 
388
- Never trusts `current` blindly: renew always continues against the licence's own stored `zkAppAddress` unless the buyer explicitly opts into the migrate flow. This means a compromised or misreporting keeper cannot redirect a renew to an address the buyer didn't already receive at purchase time. A verified signature is required to even enable the "Migrate & Renew" button.
385
+ Never trusts `current` blindly: renew moves to the current address only when the generation list verifies against the pinned key, so a compromised or misreporting keeper cannot redirect a renew to an address of its choosing.
389
386
 
390
387
  ### `zklicensing/buy` — buy flow client
391
388
 
@@ -453,7 +450,7 @@ The SDK never touches a wallet — the caller drives the sign step between `prov
453
450
 
454
451
  `proveBuy` also refuses locally when the backend's sales freeze is in effect (fetched from `GET /health`) — the request would 423 anyway, so surfacing the message before the round-trip saves a wasted call. See `zklicensing/freeze` below.
455
452
 
456
- **No-escrow routing.** When the buyer's advertised 14-day refund window would land past `FREEZE_AFTER_SLOT` (checked as `currentSlot + REFUND_WINDOW_N + TOLERANCE_WINDOW_N > FREEZE_AFTER_SLOT`), `proveBuy` transparently switches to `POST /prove/buy-no-escrow` — the backend endpoint for a distinct circuit method (`buyLicenseNoEscrow`) that pays vendor + platform directly at buy time (98 / 2, same as `renewLicense`) and never writes an escrow entry. This is the mechanism that makes the pre-hardfork waiver materially real: with no escrow entry there is nothing for the freeze-window migration guard to strand, and no refund path exists at all (a refund would fail the `escrowCommitment` check by construction). Passing `refundWaiverAccepted: true` is mandatory on those routed calls; the backend refuses the endpoint without it. When the backend hasn't yet been redeployed with a build that offers `/prove/buy-no-escrow`, the client throws an actionable message rather than silently falling back to an escrow-backed buy that would strand funds — vendors on old backend builds must complete their §12.13 redeploy before the overlap-window sales resume.
453
+ **No-escrow routing.** When the buyer's advertised 14-day refund window would land past `FREEZE_AFTER_SLOT` (checked as `currentSlot + REFUND_WINDOW_N + TOLERANCE_WINDOW_N > FREEZE_AFTER_SLOT`), `proveBuy` transparently switches to `POST /prove/buy-no-escrow` — the backend endpoint for a distinct circuit method (`buyLicenseNoEscrow`) that pays vendor + platform directly at buy time (98 / 2, same as `renewLicense`) and never writes an escrow entry. This is the mechanism that makes the pre-hardfork waiver materially real: with no escrow entry nothing blocks the redeploy (an app retires only with an empty escrow), and no refund path exists at all (a refund would fail the `escrowCommitment` check by construction). Passing `refundWaiverAccepted: true` is mandatory on those routed calls; the backend refuses the endpoint without it. When the backend hasn't yet been redeployed with a build that offers `/prove/buy-no-escrow`, the client throws an actionable message rather than silently falling back to an escrow-backed buy that would strand funds — vendors on old backend builds must complete their §12.13 redeploy before the overlap-window sales resume.
457
454
 
458
455
  ### `zklicensing/renew` — renew flow client
459
456
 
@@ -495,46 +492,6 @@ await confirmRenew({ keeperUrl, zkAppAddress, licenseHash, txHash });
495
492
 
496
493
  `proveRenew` also refuses locally when the backend's sales freeze is in effect (fetched from `GET /health`), for the same reason as `proveBuy`. Concurrent-prove serialization is via the shared per-app in-flight guard — see [Per-app in-flight proving guard](#per-app-in-flight-proving-guard).
497
494
 
498
- ### `zklicensing/migrate` — cross-generation migrate client
499
-
500
- Wraps `POST /prove/migrate`. The keeper locates the buyer's licence in the freshest ancestor generation where it still exists, assembles the three witnesses (ancestor / predecessor / current-live-empty), and returns a signable transaction that copies the expiry verbatim into the current live map at zero payment.
501
-
502
- **Full "Migrate & Renew" sequence** (two txs, one wallet sign each):
503
-
504
- 1. `fetchGenerationInfo` (see `zklicensing/generation`) — pin-verified signed lineage. If the licence's `zkAppAddress` is retired, present the buyer with a blocking "Migrate & Renew" step.
505
- 2. `proveMigrate` → wallet signs `provenTxJson` → broadcast → poll landing on the current `zkAppAddress`.
506
- 3. `proveRenew` (see `zklicensing/renew`) against the current `zkAppAddress` → wallet signs → broadcast → poll → rewrite `ProofFile` with the new `{ generation, zkAppAddress, expirySlot }`.
507
-
508
- The keeper 409s `/prove/renew` and `/prove/buy*` for any retired `zkAppAddress`, so skipping step 2 is not an option.
509
-
510
- ```ts
511
- import { proveMigrate, ProveMigrateError } from 'zklicensing/migrate';
512
- import { ProveQueueBusyError } from 'zklicensing/prove-errors';
513
-
514
- try {
515
- const { provenTxJson, ancestorGen, expirySlot, zkAppAddress, appKey } = await proveMigrate({
516
- keeperUrl: 'https://dev.zklicensing.com/api/keeper',
517
- licenseHash: '…',
518
- appId: 'app_…',
519
- buyerAddress: 'B62q…', // fee payer (buyer-signed mode)
520
- });
521
- // Wallet signs provenTxJson → broadcast → poll landing → resume with renew.
522
- } catch (e) {
523
- if (e instanceof ProveQueueBusyError) {
524
- // Another root-mutating prove (buy / renew / migrate) is in flight on this app.
525
- // Wait e.retryAfterMs, then retry — no wallet popup was opened.
526
- }
527
- if (e instanceof ProveMigrateError) {
528
- // Terminal 4xx: 404 "license refunded or unknown", 409 "already migrated", etc.
529
- }
530
- throw e;
531
- }
532
- ```
533
-
534
- Single-flight is enforced keeper-side by the shared per-app in-flight slot (see [§Per-app in-flight proving guard](#per-app-in-flight-proving-guard)) — not a per-`licenseHash` marker. The second concurrent caller on the same app receives an immediate `409 { error: "proving queue busy", retryAfterMs, queueDepth }` before any wallet prompt, whether the other request was a buy, renew, or migrate against the same `licensesRoot`. This is stricter than the previous per-`licenseHash` marker: two migrates of *different* licenses on the same app are also serialized, because both mutate the same root.
535
-
536
- Terminal 4xx surfaces (`ProveMigrateError`): 404 "license refunded or unknown" (no leaf in any generation — stop), 409 "already migrated" (leaf already in the current live map — refresh the record).
537
-
538
495
  ### `zklicensing/generation` — signed generation-list client
539
496
 
540
497
  Wraps `GET /apps/:appId` — every past `zkAppAddress` plus the currently live one, with the response's Ed25519 signature verified against a caller-supplied pin list of platform manifest public keys.
@@ -592,9 +549,15 @@ zklicensing-verify-trust \
592
549
 
593
550
  **Where `--pinned-key` comes from.** Read the current platform manifest pubkey(s) off the published trust-anchor page — <https://dev.zklicensing.com/trustanchor.html> lists them alongside each generation's verification-key hash. The same data is served as JSON for CI: <https://dev.zklicensing.com/trustanchor/manifest-pubkeys.json> (and VK hashes at <https://dev.zklicensing.com/trustanchor/vk-hashes.json>). Copy that base64 value into your build config and pass it as `--pinned-key`. **Do not** rely on the pubkey embedded inside the `.well-known` manifest itself — it is the signer's self-declaration and is not trusted; only the caller-pinned list is. Repeat `--pinned-key <b64>` once per key during a rotation window.
594
551
 
552
+ **Permit registries.** `--registry <address>` checks a zkPermits registry instead (`verifyRegistryTrust` in `zklicensing/permits/trust`): the on-chain verification key is a published `PermitRegistry` release (`CANONICAL_PERMIT_VK_HASHES`), initialize ran, the registry is bound to the network, and its permissions are locked (verification key, permissions, zkApp URI, delegate and timing impossible; `send` and `editState` proof-only). It also checks who the registry belongs to: the authority's https website is written into its `zkappUri` at deployment (frozen), `--origin` compares that website's host with the one you expect, and the website must serve `/.well-known/zkpermits/<address>.json` naming the registry and network (`wellKnownFile(address, network)` builds it; skip the fetch with `--no-well-known`). With `--keeper-url` it also checks that the keeper's authority keys, payout address and website match the chain.
553
+
554
+ ```sh
555
+ zklicensing-verify-trust --registry B62q… --origin https://permits.city.example --mina-network-id mainnet --keeper-url https://zklicensing.com/api/keeper
556
+ ```
557
+
595
558
  ### `zklicensing/refund` — refund flow client
596
559
 
597
- Same shape as buy/renew. The backend enforces the 14-day refund window and returns HTTP 409 when it has closed — the error surfaces through the thrown `Error` message, so the SDK doesn't second-guess it locally. Refunds stay open during a sales freeze (that's the whole point of freezing). Refund shares the per-app in-flight guard with buy/renew/migrate, so `proveRefund` throws `ProveQueueBusyError` on concurrent-prove collisions.
560
+ Same shape as buy/renew. The backend enforces the 14-day refund window and returns HTTP 409 when it has closed — the error surfaces through the thrown `Error` message, so the SDK doesn't second-guess it locally. Refunds stay open during a sales freeze (that's the whole point of freezing). Refund shares the per-app in-flight guard with buy/renew, so `proveRefund` throws `ProveQueueBusyError` on concurrent-prove collisions.
598
561
 
599
562
  ```ts
600
563
  import { proveRefund, confirmRefund } from 'zklicensing/refund';
@@ -628,7 +591,7 @@ await confirmRefund({ keeperUrl, zkAppAddress, licenseHash, txHash });
628
591
 
629
592
  ### `zklicensing/freeze` — sales-freeze state
630
593
 
631
- Read helpers for the backend's sales-freeze schedule. A platform operator sets `FREEZE_AFTER_SLOT` on the backend ahead of a hardfork migration; from that slot on the backend refuses new buys and renewals so open escrow can drain. Refunds, releases, and verify stay open throughout.
594
+ Read helpers for the backend's sales-freeze schedule. A platform operator sets `FREEZE_AFTER_SLOT` on the backend ahead of a hardfork redeploy; from that slot on the backend refuses new buys and renewals so open escrow can drain. Refunds, releases, and verify stay open throughout.
632
595
 
633
596
  ```ts
634
597
  import { getKeeperHealth, resolveFreezeState } from 'zklicensing/freeze';
@@ -664,6 +627,14 @@ const apps = await fetchVendorApps({ keeperUrl, vendorAddress });
664
627
 
665
628
  Each helper returns `null` on non-OK response so a degraded backend doesn't tear the dashboard down.
666
629
 
630
+ ### `zklicensing/vat` — VAT rates and VAT-inclusive prices
631
+
632
+ Prices on zkLicensing include VAT. `standardVatRate(country, date)` gives the standard rate in force on a date (EU member states and the UK, with history; pinned from `ibericode/vat-rates`, MIT; regenerate with `node scripts/build-vat-rates.mjs`). `vatIncludedNano(totalNano, rate)` splits a VAT-inclusive amount exactly; `priceWithVat(totalNano, country)` gives what a buyer sees (net + VAT = total); `vatReceipt(...)` is the `vat` block for a license file. Countries outside the table give `null`. For display and vendors' own reporting — an estimate for consumer sales, not tax advice.
633
+
634
+ ### `zklicensing/tax-id` — vendor tax IDs
635
+
636
+ `checkTaxId(country, taxId)` checks a vendor's tax ID for their country, offline: EU VAT numbers (format per member state; the keeper also looks them up in VIES), UK VAT, Norwegian MVA, Swiss UID, Australian ABN, New Zealand GST, Canadian BN and Indian GSTIN (format and check digits), US EIN, Japanese and Singapore registration numbers (format). Other countries are accepted for an admin to review. Returns the normalized form, or an error and an `example`; `taxIdExample(country)` gives a form placeholder.
637
+
667
638
  ### `zklicensing/country-stats` — buyer-country breakdown
668
639
 
669
640
  Pure computation over `LicenseRecord[]`, bucketed by UTC calendar year and structured for tax reporting (one row per `year × appId × countryCode`). Used by both the backend (for `/stats.countryBreakdown`) and any downstream dashboard, so numbers can never drift between them.
@@ -679,7 +650,7 @@ Purchase revenue attributes to `createdAt` (falling back to slot-derived time fo
679
650
 
680
651
  ### `zklicensing/prove-errors` — shared typed errors
681
652
 
682
- Typed error surface for the per-app in-flight guard shared across `proveBuy`, `proveRenew`, `proveMigrate`, and `proveRefund`. See [Per-app in-flight proving guard](#per-app-in-flight-proving-guard) for the wire contract.
653
+ Typed error surface for the per-app in-flight guard shared across `proveBuy`, `proveRenew`, and `proveRefund`. See [Per-app in-flight proving guard](#per-app-in-flight-proving-guard) for the wire contract.
683
654
 
684
655
  ```ts
685
656
  import { ProveQueueBusyError } from 'zklicensing/prove-errors';
@@ -698,7 +669,7 @@ try {
698
669
  }
699
670
  ```
700
671
 
701
- Also exports `readErrorBody(resp)` + `tryQueueBusyFromBody(parsed)` — pure helpers used internally by the buy/renew/migrate clients to consume the response body exactly once and then classify it. Available for driver integrations that need to inspect a keeper 409 without re-parsing.
672
+ Also exports `readErrorBody(resp)` + `tryQueueBusyFromBody(parsed)` — pure helpers used internally by the buy/renew/refund clients to consume the response body exactly once and then classify it. Available for driver integrations that need to inspect a keeper 409 without re-parsing.
702
673
 
703
674
  ### `zklicensing/tx-broadcast` — broadcast signal
704
675
 
@@ -710,7 +681,7 @@ import { notifyBroadcast } from 'zklicensing/tx-broadcast';
710
681
  // After sendWithWallet returns:
711
682
  void notifyBroadcast({
712
683
  keeperUrl,
713
- appId: appKey, // the `appKey` returned by proveBuy / proveRenew / proveMigrate
684
+ appId: appKey, // the `appKey` returned by proveBuy / proveRenew
714
685
  txHash,
715
686
  });
716
687
  ```
@@ -730,7 +701,7 @@ import type { LicenseRecord, LicenseStatus } from 'zklicensing/record';
730
701
 
731
702
  ### `zklicensing/internal/ownershipSignature` — ownership challenge signer
732
703
 
733
- `deriveOwnershipKeypair(passphrase, zkAppAddress)` + `signBinding(privateKey, { licenseHash, deviceCommitment, slotIndex, nonce })` — the Pallas Schnorr signer used by the bind/unbind clients to authorize on-chain slot writes. Derivation is bound to the app's zkApp address, so a leaked passphrase for one app cannot bind against any other. Signatures are re-verified IN-CIRCUIT by `Signature.verify()`, so a compromised backend cannot forge a bind or unbind. Runs via `o1js` — the same primitive `licenseHash` was derived from at buy time.
704
+ `deriveOwnershipKeypair(passphrase, zkAppAddress)` + `signBinding(privateKey, { licenseHash, deviceCommitment, slotIndex, nonce, slotState, expirySlot, zkAppAddress })` — the Pallas Schnorr signer used by the bind/unbind clients to authorize on-chain slot writes. `slotState` is the target slot's current packed `(boundAt, freedAt)` (`slotStateOf(devices[slotIndex])` from `GET /license`) and `expirySlot` the license's current expiry (`fetchBindingState(...)` returns both); together they make each signature single-use, so a captured signature cannot be replayed once the slot changes — including after a refund and re-buy with the same passphrase. `proveBind` / `proveUnbind` fill it in automatically. Derivation is bound to the app's zkApp address, so a leaked passphrase for one app cannot bind against any other. Signatures are re-verified IN-CIRCUIT by `Signature.verify()`, so a compromised backend cannot forge a bind or unbind. Runs via `o1js` — the same primitive `licenseHash` was derived from at buy time.
734
705
 
735
706
  ### `zklicensing/verify-offline` — non-custodial offline verify
736
707
 
@@ -785,7 +756,7 @@ const res = verifyOffline({
785
756
  });
786
757
  ```
787
758
 
788
- A worked end-to-end example — proof.json paste box, three-way fetch, cross-check, verdict — lives at `packages/sdk/examples/verify.html` alongside the buy / renew / refund / bind / unbind pages.
759
+ A worked end-to-end example — license file paste box, three-way fetch, cross-check, verdict — lives at `packages/sdk/examples/verify.html` alongside the buy / renew / refund / bind / unbind pages.
789
760
 
790
761
  Two sourcing modes for `licensesRoot`:
791
762
 
@@ -794,10 +765,43 @@ Two sourcing modes for `licensesRoot`:
794
765
 
795
766
  Default public Mina GraphQL endpoints are wired in (`DEFAULT_MINA_GRAPHQL_URLS.mainnet` / `.devnet`); pass `graphqlUrl` to point at your own node.
796
767
 
768
+ ### `zklicensing/verify-trustless` — the same, in one call
769
+
770
+ `verifyLicenseTrustless` does the steps above for you, plus the checks a raw root read leaves out: the contract at the address must run a published LicensingApp release (its verification key is one of `CANONICAL_VK_HASHES`) and be locked (state changes only by proof, no new verification key, no new permissions), and the current slot comes from the node too. The service supplies only the leaf fields and Merkle path; they must hash to the on-chain root, so a stale or lying service can make the check fail but never pass. An absent license is proved the same way. The app's contract generations come from the platform-signed list (checked against the pinned manifest keys), current generation first, so a license file naming a retired contract still verifies (the license carried over to the current one). The chain names the current generation too: a retired contract stores its successor, and each successor must run a published release and have started from its predecessor's frozen root. Without a valid signed list, the given address and its on-chain successors are checked (`generations: 'given-address-only'`).
771
+
772
+ ```ts
773
+ import { verifyLicenseTrustless } from 'zklicensing/verify-trustless';
774
+
775
+ const r = await verifyLicenseTrustless({ keeperUrl, network: 'mainnet', zkAppAddress, licenseHash /*, graphqlUrl: your own node */ });
776
+ // { valid, expiresAt, expirySlot, inGracePeriod, remainingDays, reason, trustless: true,
777
+ // resolvedAddress, generation, slot, generations: 'verified' | 'given-address-only' }
778
+ ```
779
+
780
+ A service that is a block or two behind a fresh purchase gets one more read; after that the call throws `STATE_MISMATCH` (retryable). Whether the address is the app you think it is (the seller's website) is `verifyTrustAnchor`. The agent client's `verifyLicense({ …, trustless: true })` and the MCP `verify_license` tool use it.
781
+
797
782
  ### Verify service — on-chain state only
798
783
 
799
784
  The verify service is a stateless mirror of on-chain license state. `GET /verify?licenseHash=…&zkAppAddress=…` returns `{ valid, expirySlot, inGracePeriod, reason, currentSlot, purchaseSlot }`. No session tokens, no HMAC-signed bearer state, no challenge/response — the verifier reads the archive and reports. Device-cap enforcement lives entirely on-chain via the [Non-custodial device binding](#non-custodial-device-binding) flow: the buyer's `bind()` / `unbind()` transactions write into the `LicenseLeaf`'s slot array, and offline verification checks the local device commitment against the cached leaf. There is no server-side seat concept the verifier or keeper can revoke; the only party who can add or remove a device commitment is whoever holds the passphrase-derived ownership private key.
800
785
 
786
+ ### `zklicensing/permits/*` — zkPermits
787
+
788
+ Registries of permits run by an authority (multi-key approval), held by a holder's wallet, checkable by anyone. Working pages for each role are in [`examples/`](examples/README.md#permits).
789
+
790
+ | Subpath | What it gives you |
791
+ |---|---|
792
+ | `zklicensing/permits/client` | `createPermitsClient({ keeperUrl, network, wallet })`: reads (`listRegistries`, `getRegistry`, `getPermit`, `verifyPermit`), the holder flow (`apply`, which pays the fee into escrow, or `apply(…, { pay: false })` then `fileApplication(id, payer?)`; `getApplication`, `withdrawApplication`, `reclaimApplication` after an undecided deadline, `acceptGrant` for a renewal the authority offers, `surrender`) and the authority flow (`acceptAuthorityTerms`, `createRegistry` with `processingFeeMina` and `decisionWindow`, `signRequest`, `deployRegistry`, `approveApplication` / `rejectApplication` (exactly as filed), `requestRenewal` / `requestStatus` / `requestFees` / `requestRotation`, `executeRequest`, and `redeployRegistry` / `cancelRedeploy` / `getDeployment` for moving a registry to the current release: it drains open applications, then the keys sign `retire` (the old registry freezes) and the next generation's deployment, which commits to the frozen permits; `getPermit` and `verifyPermitTrustless` follow the generations). An approval pays the escrowed fee out 98/2; a rejection or withdrawal keeps the registry's processing fee and refunds the rest to the payer; past the decision deadline the payer gets it all back. Writes sign in first; the sign-in text names the site and network and the session works only on that network. `acceptAuthorityTerms` takes `AuthorityDetails`: on mainnet also `registrationNumber` and `billingAddress`, and `vatId` only if the authority is VAT-registered; `authorityFeeStatement(month)` returns the platform's monthly fee statement for the wallet's registries. Also `verifyPermitTrustless` (the keeper's leaf and witness must fold to the root read from a Mina node, dated by the node's slot), `readRegistryHead` (a registry's root and the current slot from a Mina node) and `minaSignerWallet` (a `PermitWallet` from a private key, for scripts and agents). Options `confirmSignature(description)` (called before every field signature with what it does in words and a fingerprint to compare with the wallet; return `false` to cancel, error code `CANCELLED`) and `describeContext(registry)` (activity names and dates for those descriptions). The client rebuilds every message from the request's details first and refuses one that doesn't match (`SIGNATURE_INVALID`). |
793
+ | `zklicensing/receipt` | The purchase receipt (`PurchaseReceipt`): the durable confirmation the keeper issues at `confirmBuy`, `confirmRenew` and permit `acceptGrant` (each returns it as `receipt`), for an approved permit application when the approval is sent, and for the processing fee kept on a rejection or withdrawal (kind `permit-processing`; `withdrawApplication` returns it, otherwise `getReceipt(txHash)` with the holder's sign-in), in the seller's name and numbered in the seller's own series; `confirmRefund` returns a credit note (`creditNote`, kind `license-refund`, negative amounts, `creditFor` naming the receipt it cancels) in the seller's credit-note series. It is a document of its own, not part of the license or permit file: offer it as a separate download, `receiptHtml(receipt or list)` (a self-contained printable page, no scripts) saved as `receiptFileName(…)` (Vendor Terms §7.1). The buyer can fetch them again from `GET /receipts` with their wallet sign-in. |
794
+ | `zklicensing/permits/describe` | Field signatures appear in wallets as bare numbers. `describeRequest(request, ctx)`, `describeAccept`, `describeSurrender` rebuild the message from its details and return `{ title, facts, verified, problem?, fingerprint }` (`fingerprint`: "7 numbers, the last ending …123456", to compare with the wallet's screen); `identifyPermitMessage(fields)` reads the kind, network and registry from any message's numbers alone. |
795
+ | `zklicensing/permits/holder-secret` | The holder secret behind anonymous proofs, without loading the proof: `deriveHolderSecret(wallet, { lineage, network, index })` (one text `signMessage` over `holderSecretText(lineage, network, index)`, which the wallet shows in words; `lineage` is the registry's first address, `registry.lineage` from the keeper or `client.registryLineage(registry)`, the same in every generation so a permit's secret survives redeploys; `index` counts the key's permits in the registry: 0, 1, …; signatures are deterministic, so nothing needs keeping), `findHolderSecret(wallet, { lineage, network, subject })` (recovers a permit's secret from the chain alone: tries 0, 1, … until the subject matches, usually the first), `saltFromHolderSecret`, and `holderSecretMatches(holderKey, subject, secret)`. Only sign that text on pages you trust: anyone holding the signature can recognise that permit's nullifiers (not prove with it). |
796
+ | `zklicensing/permits/rebuild` (also) | `RegistryView.tree` is a `CompactMerkleMap`: a MerkleMap drop-in (same roots and witnesses) that stores only the leaves and the split-children values, so `registryViewToStored` / `registryViewFromStored` save and load a registry without re-hashing (10,000 permits: 4 MB, 0.3 s to load; a rebuild from events re-hashes a 256-level path per permit, about 17 min), and `refreshRegistryView(view, events)` re-hashes only the permits that changed. |
797
+ | `zklicensing/permits/tree` | A compact copy of a registry's permits tree: every permit plus the 2(N − 1) node values where two permits' paths split, so a holder builds its Merkle witness without the keeper learning which permit and without re-hashing the 256-level tree (about 0.1 s per permit). `compactTreeFrom` (keeper side, from the full tree), `witnessFromCompactTree` (checked by folding to the root), `applyTreeDiff` (the permits changed since a root; re-hashes only above them), `syncRegistryTree({ registry, fetchTree, cache })` (cached copy brought up to date, else a full download). Measured: 10,000 permits ≈ 1.5 MB gzipped and 0.4 s on the device; 100,000 ≈ 15 MB and 3.5 s. |
798
+ | `zklicensing/permits/check` | Anonymous checks through the keeper's relay (the site's verify.html Anonymous mode and prove.html use it). `createCheckRelay(keeperUrl)`: `openCheck` (own nonce, nullifiers never repeat), `createEvent` + `openEventCheck` (one nonce per event: a permit's nullifier repeats there, so second use shows), `getCheck`, `submitProof`, `markSeen` / `seenCount` (the event's shared list, with its key), `getTree`. `proveForCheck({ checkId, permit, wallet, origin, treeCache? })` (holder: builds the witness from a compact copy of the whole registry so the keeper can't tell which permit, re-derives the secret, proves, sends) and `verifyCheck({ checkId, origin, trustless? })` (checker). `origin` is the site both sides are on: the challenge is `verifierContext(origin, nonce)`. |
799
+ | `zklicensing/permits/proof` | The holder's anonymous proof: `proveHolder` (runs on the holder's device — it needs the holder's signature over `holderProofMessage(registry, root, context)` and the holder secret, which the holder's wallet re-derives from the chain with `findHolderSecret` (`zklicensing/permits/holder-secret`); the client's `apply` derives it and sends only its hash, the salt) and `verifyHolderProof` (checks the proof, its registry, root, slot, required activities and challenge; returns the nullifier, the same for one holder and one challenge). The nullifier is `Poseidon(tag, holderSecret, context)`: subjects are public and the keeper and authority see the salt, but only the holder's wallet can produce the secret, so nobody else can match a nullifier to a permit. The challenge is bound to the verifier: `context = verifierContext(verifier, nonce)`, from the verifier's identity as the holder reaches it (a URL counts as its origin, `normalizeVerifier`) and a `randomNonce()`; verifiers pass `{ verifier, nonce }` to `verifyHolderProof`. Two verifiers that agree on one nonce still get different challenges, so they can't link a holder by comparing nullifiers. |
800
+ | `zklicensing/permits/trust` | `verifyRegistryTrust`: is an address a genuine, unmodifiable registry (a published verification key from `CANONICAL_PERMIT_VK_HASHES`, initialized, bound to the network, permissions locked), and does it belong to the website it names (`zkappUri`, options `website` and `checkWellKnown`; `wellKnownPath` / `wellKnownFile` for the authority's claim file)? Also the `--registry` mode of `zklicensing-verify-trust`. |
801
+ | `zklicensing/permits/messages` | The permit leaf, its hash and subject, packed fees and policy, the escrowed `Application` (its `filing` number is the registry's `filingCount` when filed, so every filing hashes differently and a decision or withdrawal signature settles only that filing; `applicationTermsHash`, which the holder signs, leaves out the payer, deadline and filing number) and the exact field messages the authority keys and the holder sign (`toSignableFields` turns one into wallet `signFields` input). |
802
+ | `zklicensing/permits/rebuild` | `rebuildRegistry` / `applyRegistryEvents`: a registry's permits and root from its on-chain events alone, without the keeper; `permitStatusAt` for a permit's status at a slot. |
803
+ | `zklicensing/permits/interface` | Event shapes, the on-chain state layout, `CANONICAL_PERMIT_VK_HASHES` and `CANONICAL_PERMIT_PROOF_VK_HASH`. |
804
+
801
805
  ## Documentation
802
806
 
803
807
  - Integration walkthrough — [dev.zklicensing.com/docs.html](https://dev.zklicensing.com/docs.html)