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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +335 -97
  2. package/build/appsLookup.d.ts +14 -0
  3. package/build/appsLookup.d.ts.map +1 -0
  4. package/build/appsLookup.js +12 -0
  5. package/build/appsLookup.js.map +1 -0
  6. package/build/archiveBootstrap.d.ts +15 -1
  7. package/build/archiveBootstrap.d.ts.map +1 -0
  8. package/build/archiveBootstrap.js +62 -9
  9. package/build/archiveBootstrap.js.map +1 -0
  10. package/build/bindClient.d.ts +51 -0
  11. package/build/bindClient.d.ts.map +1 -0
  12. package/build/bindClient.js +115 -0
  13. package/build/bindClient.js.map +1 -0
  14. package/build/buyClient.d.ts +10 -3
  15. package/build/buyClient.d.ts.map +1 -0
  16. package/build/buyClient.js +33 -15
  17. package/build/buyClient.js.map +1 -0
  18. package/build/contractInterface.d.ts +11 -5
  19. package/build/contractInterface.d.ts.map +1 -0
  20. package/build/contractInterface.js +82 -17
  21. package/build/contractInterface.js.map +1 -0
  22. package/build/countryStats.d.ts +6 -1
  23. package/build/countryStats.d.ts.map +1 -0
  24. package/build/countryStats.js +33 -9
  25. package/build/countryStats.js.map +1 -0
  26. package/build/deployClient.d.ts.map +1 -0
  27. package/build/deployClient.js +1 -1
  28. package/build/deployClient.js.map +1 -0
  29. package/build/deviceIdentity.d.ts +68 -0
  30. package/build/deviceIdentity.d.ts.map +1 -0
  31. package/build/deviceIdentity.js +209 -0
  32. package/build/deviceIdentity.js.map +1 -0
  33. package/build/freezeClient.d.ts.map +1 -0
  34. package/build/freezeClient.js +1 -1
  35. package/build/freezeClient.js.map +1 -0
  36. package/build/generationClient.d.ts +1 -0
  37. package/build/generationClient.d.ts.map +1 -0
  38. package/build/generationClient.js +2 -2
  39. package/build/generationClient.js.map +1 -0
  40. package/build/index.d.ts +27 -37
  41. package/build/index.d.ts.map +1 -0
  42. package/build/index.js +85 -116
  43. package/build/index.js.map +1 -0
  44. package/build/licenseLeaf.d.ts +76 -0
  45. package/build/licenseLeaf.d.ts.map +1 -0
  46. package/build/licenseLeaf.js +189 -0
  47. package/build/licenseLeaf.js.map +1 -0
  48. package/build/licenseRecord.d.ts +20 -1
  49. package/build/licenseRecord.d.ts.map +1 -0
  50. package/build/licenseRecord.js +1 -1
  51. package/build/licenseRecord.js.map +1 -0
  52. package/build/licenseStore.d.ts +17 -2
  53. package/build/licenseStore.d.ts.map +1 -0
  54. package/build/licenseStore.js +167 -7
  55. package/build/licenseStore.js.map +1 -0
  56. package/build/manifestVerify.d.ts.map +1 -0
  57. package/build/manifestVerify.js +8 -3
  58. package/build/manifestVerify.js.map +1 -0
  59. package/build/migrateClient.d.ts +6 -21
  60. package/build/migrateClient.d.ts.map +1 -0
  61. package/build/migrateClient.js +30 -17
  62. package/build/migrateClient.js.map +1 -0
  63. package/build/onChainRoot.d.ts +67 -0
  64. package/build/onChainRoot.d.ts.map +1 -0
  65. package/build/onChainRoot.js +87 -0
  66. package/build/onChainRoot.js.map +1 -0
  67. package/build/ownershipLicenseHash.d.ts +25 -0
  68. package/build/ownershipLicenseHash.d.ts.map +1 -0
  69. package/build/ownershipLicenseHash.js +29 -0
  70. package/build/ownershipLicenseHash.js.map +1 -0
  71. package/build/ownershipSignature.d.ts +122 -0
  72. package/build/ownershipSignature.d.ts.map +1 -0
  73. package/build/ownershipSignature.js +244 -0
  74. package/build/ownershipSignature.js.map +1 -0
  75. package/build/proveErrors.d.ts +35 -0
  76. package/build/proveErrors.d.ts.map +1 -0
  77. package/build/proveErrors.js +49 -0
  78. package/build/proveErrors.js.map +1 -0
  79. package/build/refundClient.d.ts +2 -11
  80. package/build/refundClient.d.ts.map +1 -0
  81. package/build/refundClient.js +35 -17
  82. package/build/refundClient.js.map +1 -0
  83. package/build/renewClient.d.ts +4 -1
  84. package/build/renewClient.d.ts.map +1 -0
  85. package/build/renewClient.js +11 -4
  86. package/build/renewClient.js.map +1 -0
  87. package/build/seatName.d.ts +8 -0
  88. package/build/seatName.d.ts.map +1 -0
  89. package/build/seatName.js +136 -0
  90. package/build/seatName.js.map +1 -0
  91. package/build/statsClient.d.ts +47 -4
  92. package/build/statsClient.d.ts.map +1 -0
  93. package/build/statsClient.js +44 -5
  94. package/build/statsClient.js.map +1 -0
  95. package/build/trustAnchorVerify.d.ts +48 -0
  96. package/build/trustAnchorVerify.d.ts.map +1 -0
  97. package/build/trustAnchorVerify.js +431 -0
  98. package/build/trustAnchorVerify.js.map +1 -0
  99. package/build/trustAnchorVerifyCli.d.ts +35 -0
  100. package/build/trustAnchorVerifyCli.d.ts.map +1 -0
  101. package/build/trustAnchorVerifyCli.js +177 -0
  102. package/build/trustAnchorVerifyCli.js.map +1 -0
  103. package/build/txBroadcastClient.d.ts +26 -0
  104. package/build/txBroadcastClient.d.ts.map +1 -0
  105. package/build/txBroadcastClient.js +20 -0
  106. package/build/txBroadcastClient.js.map +1 -0
  107. package/build/unbindClient.d.ts +56 -0
  108. package/build/unbindClient.d.ts.map +1 -0
  109. package/build/unbindClient.js +113 -0
  110. package/build/unbindClient.js.map +1 -0
  111. package/build/vendorAccountClient.d.ts +56 -0
  112. package/build/vendorAccountClient.d.ts.map +1 -0
  113. package/build/vendorAccountClient.js +47 -0
  114. package/build/vendorAccountClient.js.map +1 -0
  115. package/build/verifyCore.d.ts +1 -1
  116. package/build/verifyCore.d.ts.map +1 -0
  117. package/build/verifyCore.js +11 -4
  118. package/build/verifyCore.js.map +1 -0
  119. package/build/verifyOffline.d.ts +85 -0
  120. package/build/verifyOffline.d.ts.map +1 -0
  121. package/build/verifyOffline.js +139 -0
  122. package/build/verifyOffline.js.map +1 -0
  123. package/build/verifyService.d.ts.map +1 -0
  124. package/build/verifyService.js +582 -455
  125. package/build/verifyService.js.map +1 -0
  126. package/build/verifyWithAncestors.d.ts +18 -0
  127. package/build/verifyWithAncestors.d.ts.map +1 -0
  128. package/build/verifyWithAncestors.js +119 -0
  129. package/build/verifyWithAncestors.js.map +1 -0
  130. package/build/zipToState.d.ts +2 -0
  131. package/build/zipToState.d.ts.map +1 -0
  132. package/build/zipToState.js +94 -0
  133. package/build/zipToState.js.map +1 -0
  134. package/package.json +57 -13
  135. package/src/appsLookup.ts +48 -0
  136. package/src/archiveBootstrap.ts +342 -0
  137. package/src/bindClient.ts +175 -0
  138. package/src/buyClient.ts +304 -0
  139. package/src/contractInterface.d.ts +61 -0
  140. package/src/contractInterface.ts +313 -0
  141. package/src/countryStats.ts +171 -0
  142. package/src/deployClient.ts +388 -0
  143. package/src/deviceIdentity.ts +249 -0
  144. package/src/freezeClient.ts +117 -0
  145. package/src/generationClient.ts +165 -0
  146. package/src/index.ts +329 -0
  147. package/src/licenseLeaf.ts +221 -0
  148. package/src/licenseRecord.ts +108 -0
  149. package/src/licenseStore.ts +538 -0
  150. package/src/manifestVerify.ts +111 -0
  151. package/src/migrateClient.ts +84 -0
  152. package/src/onChainRoot.ts +107 -0
  153. package/src/ownershipLicenseHash.ts +31 -0
  154. package/src/ownershipSignature.ts +354 -0
  155. package/src/proveErrors.ts +70 -0
  156. package/src/refundClient.ts +158 -0
  157. package/src/renewClient.ts +214 -0
  158. package/src/seatName.ts +165 -0
  159. package/src/statsClient.ts +235 -0
  160. package/src/trustAnchorVerify.ts +548 -0
  161. package/src/trustAnchorVerifyCli.ts +179 -0
  162. package/src/txBroadcastClient.ts +48 -0
  163. package/src/unbindClient.ts +149 -0
  164. package/src/vendorAccountClient.ts +110 -0
  165. package/src/verifyCore.ts +92 -0
  166. package/src/verifyOffline.ts +212 -0
  167. package/src/verifyService.ts +969 -0
  168. package/src/verifyWithAncestors.ts +153 -0
  169. package/src/zipToState.ts +94 -0
  170. package/build/licenseProof.d.ts +0 -26
  171. package/build/licenseProof.js +0 -41
  172. package/build/ownership.d.ts +0 -34
  173. package/build/ownership.js +0 -147
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+ // Copyright (c) 2025-2026 zkLicensing project developers
3
+ // SPDX-License-Identifier: BUSL-1.1
4
+
5
+ /**
6
+ * trustAnchorVerifyCli.ts
7
+ *
8
+ * Command-line front-end for verifyTrustAnchor(). Ships as the `zklicensing-verify-trust`
9
+ * bin — the sibling of `zklicensing-verify` (which is the verifyService HTTP daemon).
10
+ *
11
+ * Usage:
12
+ * zklicensing-verify-trust \
13
+ * --origin https://store.example.com \
14
+ * --address B62q... \
15
+ * --pinned-key <base64-ed25519-pubkey> \
16
+ * [--mina-graphql https://api.minascan.io/node/mainnet/v1/graphql] \
17
+ * [--mina-network-id mainnet|testnet|devnet] \
18
+ * [--skip-chain-checks] \
19
+ * [--json]
20
+ *
21
+ * The manifest lives at `<origin>/.well-known/zklicensing/<address>.json` —
22
+ * one file per generation address, all signed by the same platform key. The
23
+ * appId is read out of the signed payload; callers never need to know it
24
+ * out-of-band, which lets buyers verify from just the address their wallet
25
+ * shows them (including addresses for retired generations).
26
+ *
27
+ * Exit codes:
28
+ * 0 — every finding passed
29
+ * 1 — one or more findings failed
30
+ * 2 — invalid arguments
31
+ *
32
+ * --pinned-key is required and may be repeated; the CLI ships NO baked-in
33
+ * pin. Source it from https://zklicensing.com/trustanchor.html (published
34
+ * next to each generation's VK hash). See the SDK README for details.
35
+ */
36
+
37
+ import { verifyTrustAnchor, type Finding, type TrustAnchorReport } from './trustAnchorVerify.js';
38
+
39
+ type Args = {
40
+ origin?: string;
41
+ address?: string;
42
+ pinnedKeys: string[];
43
+ minaGraphql: string;
44
+ minaNetworkId: 'mainnet' | 'testnet' | 'devnet';
45
+ skipChainChecks: boolean;
46
+ crossCheck: boolean;
47
+ json: boolean;
48
+ help: boolean;
49
+ };
50
+
51
+ const DEFAULT_MAINNET_GRAPHQL = 'https://api.minascan.io/node/mainnet/v1/graphql';
52
+
53
+ function usage(): string {
54
+ return [
55
+ 'zklicensing-verify-trust — verify a vendor page + on-chain zkApp mutually bind',
56
+ '',
57
+ 'Required:',
58
+ ' --origin <url> Vendor origin (https://...)',
59
+ ' --address <B62q...> zkApp address (the address your wallet shows you)',
60
+ ' --pinned-key <b64> Platform manifest pubkey (repeatable during rotation)',
61
+ '',
62
+ 'Optional:',
63
+ ` --mina-graphql <url> Mina GraphQL endpoint (default: ${DEFAULT_MAINNET_GRAPHQL})`,
64
+ ' --mina-network-id <id> mainnet | testnet | devnet (default: mainnet)',
65
+ ' --skip-chain-checks Manifest-only audit — no o1js chain reads',
66
+ ' --cross-check Also verify vendor manifest matches the',
67
+ ' zkLicensing backend record at',
68
+ ' https://zklicensing.com/apps/by-address/<address>',
69
+ ' --json Emit TrustAnchorReport as JSON on stdout',
70
+ '',
71
+ 'Exit: 0 all-ok · 1 any check failed · 2 bad args',
72
+ ].join('\n');
73
+ }
74
+
75
+ function parseArgs(argv: string[]): Args {
76
+ const args: Args = {
77
+ pinnedKeys: [],
78
+ minaGraphql: DEFAULT_MAINNET_GRAPHQL,
79
+ minaNetworkId: 'mainnet',
80
+ skipChainChecks: false,
81
+ crossCheck: false,
82
+ json: false,
83
+ help: false,
84
+ };
85
+ for (let i = 0; i < argv.length; i++) {
86
+ const a = argv[i];
87
+ const next = () => {
88
+ const v = argv[++i];
89
+ if (v === undefined) throw new Error(`missing value for ${a}`);
90
+ return v;
91
+ };
92
+ switch (a) {
93
+ case '--origin': args.origin = next(); break;
94
+ case '--address': args.address = next(); break;
95
+ case '--pinned-key': args.pinnedKeys.push(next()); break;
96
+ case '--mina-graphql': args.minaGraphql = next(); break;
97
+ case '--mina-network-id': {
98
+ const v = next();
99
+ if (v !== 'mainnet' && v !== 'testnet' && v !== 'devnet') {
100
+ throw new Error(`--mina-network-id must be mainnet|testnet|devnet, got "${v}"`);
101
+ }
102
+ args.minaNetworkId = v;
103
+ break;
104
+ }
105
+ case '--skip-chain-checks': args.skipChainChecks = true; break;
106
+ case '--cross-check': args.crossCheck = true; break;
107
+ case '--json': args.json = true; break;
108
+ case '-h':
109
+ case '--help': args.help = true; break;
110
+ default: throw new Error(`unknown argument: ${a}`);
111
+ }
112
+ }
113
+ return args;
114
+ }
115
+
116
+ function formatHuman(report: TrustAnchorReport): string {
117
+ const lines: string[] = [];
118
+ const banner = report.ok ? 'TRUST ANCHOR VERIFIED' : 'TRUST ANCHOR FAILED';
119
+ lines.push(banner);
120
+ lines.push(` origin: ${report.origin}`);
121
+ lines.push(` address: ${report.address}`);
122
+ if (report.appId) lines.push(` appId: ${report.appId}`);
123
+ if (report.generation !== undefined) lines.push(` generation: ${report.generation}`);
124
+ lines.push('');
125
+ for (const f of report.findings) {
126
+ const mark = f.ok ? '[ok] ' : '[FAIL]';
127
+ lines.push(` ${mark} ${f.name} — ${f.detail}`);
128
+ }
129
+ return lines.join('\n');
130
+ }
131
+
132
+ async function main(): Promise<number> {
133
+ let args: Args;
134
+ try {
135
+ args = parseArgs(process.argv.slice(2));
136
+ } catch (err: any) {
137
+ process.stderr.write(`${err.message}\n\n${usage()}\n`);
138
+ return 2;
139
+ }
140
+ if (args.help) {
141
+ process.stdout.write(`${usage()}\n`);
142
+ return 0;
143
+ }
144
+ const missing: string[] = [];
145
+ if (!args.origin) missing.push('--origin');
146
+ if (!args.address) missing.push('--address');
147
+ if (args.pinnedKeys.length === 0) missing.push('--pinned-key');
148
+ if (missing.length > 0) {
149
+ process.stderr.write(`missing required argument(s): ${missing.join(', ')}\n\n${usage()}\n`);
150
+ return 2;
151
+ }
152
+ const report = await verifyTrustAnchor({
153
+ origin: args.origin!,
154
+ address: args.address!,
155
+ pinnedPublicKeysBase64: args.pinnedKeys,
156
+ minaGraphqlUrl: args.minaGraphql,
157
+ minaNetworkId: args.minaNetworkId,
158
+ skipChainChecks: args.skipChainChecks,
159
+ crossCheck: args.crossCheck,
160
+ });
161
+ if (args.json) {
162
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
163
+ } else {
164
+ process.stdout.write(`${formatHuman(report)}\n`);
165
+ }
166
+ return report.ok ? 0 : 1;
167
+ }
168
+
169
+ main().then(
170
+ (code) => process.exit(code),
171
+ (err) => {
172
+ process.stderr.write(`unexpected error: ${err?.stack ?? err}\n`);
173
+ process.exit(1);
174
+ },
175
+ );
176
+
177
+ // Silence unused-import warning when someone bundles the module (Finding is
178
+ // re-exported here for consumers that import from the CLI module directly).
179
+ export type { Finding };
@@ -0,0 +1,48 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * txBroadcastClient.ts
6
+ *
7
+ * Small helper for POST /tx-broadcast. Called by the buy/renew/migrate
8
+ * flows immediately after the buyer's wallet returns a txHash — signals
9
+ * the keeper to extend the app's in-flight slot from the short signing-TTL
10
+ * to the longer landing-TTL, so concurrent buyers on the same app don't
11
+ * think the slot has expired while an honest signed tx is still in the
12
+ * mempool.
13
+ *
14
+ * Fire-and-forget by design: this is a tightening signal, not a
15
+ * correctness dependency. Land-clear in the buy-watcher and the
16
+ * signing-TTL both remain live regardless of whether this call succeeds.
17
+ * Failures are swallowed with an optional log callback so a network blip
18
+ * doesn't surface as a confusing error mid-checkout.
19
+ */
20
+
21
+ export type NotifyBroadcastRequest = {
22
+ keeperUrl: string;
23
+ appId: string;
24
+ txHash: string;
25
+ fetcher?: typeof fetch;
26
+ signal?: AbortSignal;
27
+ // Optional hook for surfacing swallowed failures to the caller's logger.
28
+ // Not called on the happy path.
29
+ onError?: (err: unknown) => void;
30
+ };
31
+
32
+ function baseUrl(url: string): string {
33
+ return url.replace(/\/+$/, '');
34
+ }
35
+
36
+ export async function notifyBroadcast(req: NotifyBroadcastRequest): Promise<void> {
37
+ const fetcher = req.fetcher ?? fetch;
38
+ try {
39
+ await fetcher(`${baseUrl(req.keeperUrl)}/tx-broadcast`, {
40
+ method: 'POST',
41
+ headers: { 'Content-Type': 'application/json' },
42
+ signal: req.signal,
43
+ body: JSON.stringify({ appId: req.appId, txHash: req.txHash }),
44
+ });
45
+ } catch (err) {
46
+ req.onError?.(err);
47
+ }
48
+ }
@@ -0,0 +1,149 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * unbindClient.ts
6
+ *
7
+ * Browser-safe client for the non-custodial device-unbinding flow.
8
+ * Mirrors `bindClient.ts` in shape: signs the unbind message with
9
+ * TAG_UNBINDING, POSTs to /prove/unbind, then /confirm/unbind after
10
+ * the wallet returns a txHash.
11
+ *
12
+ * Notable asymmetry with bind: the unbind message shape carries the
13
+ * deviceCommitment position too, but the backend and circuit both
14
+ * hard-code it to `Field(0)` (the "not about any specific new
15
+ * device" sentinel — the message is about freeing a slot, not
16
+ * introducing a new device). The SDK matches by omitting
17
+ * deviceCommitment from the request and using "0" when computing
18
+ * the signature preimage.
19
+ *
20
+ * Non-custodial invariant: the signature is re-verified in-circuit
21
+ * against the leaf's `licenseHash` (which IS the owner-pubkey
22
+ * commitment — the circuit asserts equality at buy time), so no
23
+ * backend / vendor can unilaterally kick a device — only the
24
+ * passphrase holder can.
25
+ * A user who lost the physical device but still has the passphrase
26
+ * can unbind the missing device's slot from any device that holds
27
+ * the ownership key (the "remote log-off" case).
28
+ */
29
+
30
+ import { Field, PrivateKey, PublicKey, Signature } from 'o1js';
31
+ import { readErrorBody, tryQueueBusyFromBody } from './proveErrors.js';
32
+ import { encodePublicKey, encodeSignature, signUnbinding } from './ownershipSignature.js';
33
+
34
+ export type ProveUnbindRequest = {
35
+ keeperUrl: string;
36
+ network: 'devnet' | 'mainnet';
37
+ zkAppAddress: string;
38
+ licenseHash: string;
39
+ ownerPrivateKey: PrivateKey;
40
+ // Which slot (0..cap-1) to free.
41
+ slotIndex: number;
42
+ buyerAddress: string;
43
+ // Optional nonce override. Sampled fresh (128-bit random) when
44
+ // omitted — same shape as bindClient.
45
+ nonce?: string;
46
+ fetcher?: typeof fetch;
47
+ signal?: AbortSignal;
48
+ };
49
+
50
+ export type ProveUnbindResponse = {
51
+ provenTxJson: string;
52
+ licenseHash: string;
53
+ slotIndex: number;
54
+ };
55
+
56
+ export type ConfirmUnbindRequest = {
57
+ keeperUrl: string;
58
+ zkAppAddress: string;
59
+ licenseHash: string;
60
+ txHash: string;
61
+ fetcher?: typeof fetch;
62
+ signal?: AbortSignal;
63
+ };
64
+
65
+ function baseUrl(url: string): string {
66
+ return url.replace(/\/+$/, '');
67
+ }
68
+
69
+ async function readJsonError(resp: Response): Promise<string> {
70
+ try {
71
+ const body = await resp.json() as Record<string, unknown>;
72
+ if (typeof body.error === 'string') return body.error;
73
+ } catch { /* body wasn't JSON */ }
74
+ return `HTTP ${resp.status}`;
75
+ }
76
+
77
+ function freshNonce(): string {
78
+ const crypto = (globalThis as any).crypto as Crypto | undefined;
79
+ if (!crypto?.getRandomValues) {
80
+ throw new Error(
81
+ 'crypto.getRandomValues unavailable — unbindClient requires Node ≥ 20 or a modern browser',
82
+ );
83
+ }
84
+ const bytes = new Uint8Array(16); // 128 bits
85
+ crypto.getRandomValues(bytes);
86
+ let n = 0n;
87
+ for (const b of bytes) n = (n << 8n) | BigInt(b);
88
+ return Field(n).toString();
89
+ }
90
+
91
+ // POST /prove/unbind — same retry contract as /prove/bind. Returns
92
+ // 409 `ProveQueueBusyError` when another root-mutating tx for the
93
+ // same app is in flight; the caller retries with the server-supplied
94
+ // `retryAfterMs` cadence.
95
+ export async function proveUnbind(req: ProveUnbindRequest): Promise<ProveUnbindResponse> {
96
+ const fetcher = req.fetcher ?? fetch;
97
+ const nonce = req.nonce ?? freshNonce();
98
+
99
+ const ownerPubKey: PublicKey = req.ownerPrivateKey.toPublicKey();
100
+ // deviceCommitment=0 for the preimage — matches TAG_UNBINDING's
101
+ // circuit-side check (see verifyUnbinding / bindingLikeFields in
102
+ // ownershipSignature.ts).
103
+ const ownerSig: Signature = signUnbinding(req.ownerPrivateKey, {
104
+ licenseHash: req.licenseHash,
105
+ deviceCommitment: '0',
106
+ slotIndex: req.slotIndex,
107
+ nonce,
108
+ });
109
+
110
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/prove/unbind`, {
111
+ method: 'POST',
112
+ headers: { 'Content-Type': 'application/json' },
113
+ signal: req.signal,
114
+ body: JSON.stringify({
115
+ licenseHash: req.licenseHash,
116
+ buyerAddress: req.buyerAddress,
117
+ zkAppAddress: req.zkAppAddress,
118
+ network: req.network,
119
+ ownerPubKey: encodePublicKey(ownerPubKey),
120
+ ownerSig: encodeSignature(ownerSig),
121
+ slotIndex: req.slotIndex,
122
+ nonce,
123
+ }),
124
+ });
125
+ if (!resp.ok) {
126
+ const parsed = await readErrorBody(resp);
127
+ const queueBusy = tryQueueBusyFromBody(parsed);
128
+ if (queueBusy) throw queueBusy;
129
+ throw new Error(parsed.message);
130
+ }
131
+ return await resp.json() as ProveUnbindResponse;
132
+ }
133
+
134
+ // POST /confirm/unbind — pass-through no-op mirror of /confirm/bind.
135
+ export async function confirmUnbind(req: ConfirmUnbindRequest): Promise<{ ok: true }> {
136
+ const fetcher = req.fetcher ?? fetch;
137
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/confirm/unbind`, {
138
+ method: 'POST',
139
+ headers: { 'Content-Type': 'application/json' },
140
+ signal: req.signal,
141
+ body: JSON.stringify({
142
+ zkAppAddress: req.zkAppAddress,
143
+ licenseHash: req.licenseHash,
144
+ txHash: req.txHash,
145
+ }),
146
+ });
147
+ if (!resp.ok) throw new Error(await readJsonError(resp));
148
+ return { ok: true };
149
+ }
@@ -0,0 +1,110 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * vendorAccountClient.ts
6
+ *
7
+ * Browser-safe client for the vendor's shared legal/billing block —
8
+ * the fields that must stay consistent across every app registered by
9
+ * one vendor wallet (legal entity name, billing country and address,
10
+ * VAT id, company registry). One PATCH updates all of the vendor's
11
+ * apps atomically on the keeper, so a legal-entity rename or address
12
+ * move doesn't leave old apps advertising stale CRD Art. 6 disclosures.
13
+ *
14
+ * Signature covers the vendor address, mirroring the "sign the
15
+ * resource id" pattern PUT /apps/:appId uses. The keeper verifies
16
+ * against the on-chain vendor recorded on the app records.
17
+ */
18
+
19
+ export type VendorLegalBlock = {
20
+ country?: string;
21
+ legalName?: string;
22
+ billingAddress?: {
23
+ line1: string;
24
+ line2?: string;
25
+ city: string;
26
+ postalCode: string;
27
+ };
28
+ invoiceEmail?: string;
29
+ vatId?: string;
30
+ companyRegistrationRegistry?: string;
31
+ companyRegistrationNumber?: string;
32
+ };
33
+
34
+ export type GetVendorLegalRequest = {
35
+ keeperUrl: string;
36
+ vendorAddress: string;
37
+ vendorSessionToken: string;
38
+ fetcher?: typeof fetch;
39
+ signal?: AbortSignal;
40
+ };
41
+
42
+ export type GetVendorLegalResponse = {
43
+ // null when the wallet has no apps yet — register form should prompt
44
+ // for the block instead of treating first-app registration as an error.
45
+ legal: VendorLegalBlock | null;
46
+ };
47
+
48
+ export type UpdateVendorLegalRequest = {
49
+ keeperUrl: string;
50
+ vendorAddress: string;
51
+ signature: { field: string; scalar: string };
52
+ payload: VendorLegalBlock;
53
+ fetcher?: typeof fetch;
54
+ signal?: AbortSignal;
55
+ };
56
+
57
+ export type UpdateVendorLegalResponse = {
58
+ ok: true;
59
+ appsUpdated: number;
60
+ };
61
+
62
+ function baseUrl(url: string): string {
63
+ return url.replace(/\/+$/, '');
64
+ }
65
+
66
+ async function readJsonError(resp: Response): Promise<string> {
67
+ try {
68
+ const body = await resp.json() as Record<string, unknown>;
69
+ if (typeof body.error === 'string') return body.error;
70
+ } catch { /* body wasn't JSON */ }
71
+ return `HTTP ${resp.status}`;
72
+ }
73
+
74
+ // GET /vendors/:address/legal — fetch the shared legal block for a wallet.
75
+ // Returns `{ legal: null }` for wallets with no registered apps.
76
+ export async function getVendorLegal(req: GetVendorLegalRequest): Promise<GetVendorLegalResponse> {
77
+ const fetcher = req.fetcher ?? fetch;
78
+ const resp = await fetcher(
79
+ `${baseUrl(req.keeperUrl)}/vendors/${encodeURIComponent(req.vendorAddress)}/legal`,
80
+ {
81
+ signal: req.signal,
82
+ headers: { Authorization: `VendorSession ${req.vendorSessionToken}` },
83
+ },
84
+ );
85
+ if (!resp.ok) throw new Error(await readJsonError(resp));
86
+ return await resp.json() as GetVendorLegalResponse;
87
+ }
88
+
89
+ // PATCH /vendors/:address/legal — updates the block on EVERY app the vendor
90
+ // owns in a single atomic sweep. Bypasses the pendingEdit staging that
91
+ // per-app metadata edits go through; legal fields are factual (not
92
+ // marketing copy) so admin review doesn't gain anything and staleness
93
+ // hurts CRD Art. 6 compliance.
94
+ export async function updateVendorLegal(req: UpdateVendorLegalRequest): Promise<UpdateVendorLegalResponse> {
95
+ const fetcher = req.fetcher ?? fetch;
96
+ const resp = await fetcher(
97
+ `${baseUrl(req.keeperUrl)}/vendors/${encodeURIComponent(req.vendorAddress)}/legal`,
98
+ {
99
+ method: 'PATCH',
100
+ headers: { 'Content-Type': 'application/json' },
101
+ signal: req.signal,
102
+ body: JSON.stringify({
103
+ signature: req.signature,
104
+ payload: req.payload,
105
+ }),
106
+ },
107
+ );
108
+ if (!resp.ok) throw new Error(await readJsonError(resp));
109
+ return await resp.json() as UpdateVendorLegalResponse;
110
+ }
@@ -0,0 +1,92 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * verifyCore.ts
6
+ *
7
+ * Pure verification logic shared by keeperService and verifyService.
8
+ * No HTTP, no network — takes already-fetched on-chain state and
9
+ * performs Merkle inclusion check + expiry logic.
10
+ */
11
+
12
+ import { Field } from 'o1js';
13
+ import { buildMap, type LicenseRecord } from './licenseStore.js';
14
+ import { GRACE_PERIOD_N, MS_PER_SLOT_N, SLOTS_PER_DAY_N } from './contractInterface.js';
15
+
16
+ export type VerifyResponse = {
17
+ valid: boolean;
18
+ expiresAt: string | null;
19
+ expirySlot: number;
20
+ inGracePeriod: boolean;
21
+ // Whole days until expiry. Negative while in the grace period (down to ~-7
22
+ // — GRACE_PERIOD_N is 6 720 slots = 7 days) and below that once expired.
23
+ // 0 when expirySlot is unknown (unknown/refunded/root-mismatch).
24
+ remainingDays: number;
25
+ reason: string | null;
26
+ };
27
+
28
+ function computeRemainingDays(expirySlot: number, currentSlot: number): number {
29
+ if (expirySlot === 0) return 0;
30
+ return Math.floor((expirySlot - currentSlot) / SLOTS_PER_DAY_N);
31
+ }
32
+
33
+ /**
34
+ * Core license verification.
35
+ *
36
+ * @param zkAppAddress - app address (composite key with licenseHash)
37
+ * @param licenseHash - Poseidon hash of the buyer's Ed25519 pubkey (see ownershipLicenseHash.ts) as a field string
38
+ * @param records - current off-chain license records (from licenseStore)
39
+ * @param onChainRoot - zkApp appState[0] fetched from Mina
40
+ * @param currentSlot - current blockchain slot (globalSlotSinceGenesis)
41
+ */
42
+ export function verifyLicenseCore(params: {
43
+ zkAppAddress: string;
44
+ licenseHash: string;
45
+ records: LicenseRecord[];
46
+ onChainRoot: string;
47
+ currentSlot: number;
48
+ }): VerifyResponse {
49
+ const { zkAppAddress, licenseHash, records, onChainRoot, currentSlot } = params;
50
+
51
+ const map = buildMap(records, zkAppAddress);
52
+ const key = Field(licenseHash);
53
+ const currentValue = map.get(key).toString();
54
+ const witness = map.getWitness(key);
55
+
56
+ const [computedRoot] = witness.computeRootAndKey(Field(currentValue));
57
+
58
+ if (computedRoot.toString() !== onChainRoot) {
59
+ return { valid: false, expiresAt: null, expirySlot: 0, inGracePeriod: false, remainingDays: 0, reason: 'License state does not match on-chain root' };
60
+ }
61
+
62
+ // Post-LicenseLeaf: the map value is `leaf.hash()`, not raw expirySlot.
63
+ // Empty slots still hash to Field(0). Look up the record to recover
64
+ // expirySlot; `buildMap` excludes refunded/empty entries, so a missing
65
+ // record here means either "never bought" or "refunded" (record kept but
66
+ // expirySlot cleared to 0).
67
+ const record = records.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash);
68
+
69
+ if (currentValue === '0') {
70
+ const reason = record?.refunded ? 'License has been refunded' : 'License not found';
71
+ return { valid: false, expiresAt: null, expirySlot: 0, inGracePeriod: false, remainingDays: 0, reason };
72
+ }
73
+
74
+ const expirySlot = record?.expirySlot ?? 0;
75
+ const inGracePeriod = currentSlot > expirySlot && currentSlot <= expirySlot + GRACE_PERIOD_N;
76
+ const expired = currentSlot > expirySlot + GRACE_PERIOD_N;
77
+ const expiresAt = new Date(Date.now() + (expirySlot - currentSlot) * MS_PER_SLOT_N).toISOString();
78
+ const remainingDays = computeRemainingDays(expirySlot, currentSlot);
79
+
80
+ if (expired) {
81
+ return { valid: false, expiresAt, expirySlot, inGracePeriod: false, remainingDays, reason: 'License has expired' };
82
+ }
83
+
84
+ return {
85
+ valid: true,
86
+ expiresAt,
87
+ expirySlot,
88
+ inGracePeriod,
89
+ remainingDays,
90
+ reason: inGracePeriod ? 'License is in grace period — renew to avoid interruption' : null,
91
+ };
92
+ }