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,84 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * migrateClient.ts
6
+ *
7
+ * Browser-safe client for /prove/migrate. Assembles a single-hop cross-
8
+ * generation proof against the current live map — the keeper walks the
9
+ * deploymentHistory once, gathers all three witnesses (ancestor / pred /
10
+ * live-empty), and returns a signable tx.
11
+ *
12
+ * Failure surfaces:
13
+ * - 404 "license refunded or unknown": no leaf anywhere in history for
14
+ * this licenseHash. Caller should not retry — it's terminal.
15
+ * - 409 "already migrated": leaf is present in the live map. Caller
16
+ * should refresh their license record and stop.
17
+ * - 409 "proving queue busy": another root-mutating request (buy, renew,
18
+ * migrate) is holding this app's in-flight slot. Thrown as the shared
19
+ * ProveQueueBusyError so callers can wait+retry uniformly across the
20
+ * three endpoints.
21
+ */
22
+
23
+ import { readErrorBody, tryQueueBusyFromBody } from './proveErrors.js';
24
+
25
+ export interface ProveMigrateRequest {
26
+ keeperUrl: string;
27
+ network: 'devnet' | 'mainnet';
28
+ licenseHash: string;
29
+ appId: string;
30
+ buyerAddress: string;
31
+ fetcher?: typeof fetch;
32
+ signal?: AbortSignal;
33
+ }
34
+
35
+ export interface ProveMigrateResponse {
36
+ provenTxJson: string;
37
+ ancestorGen: number;
38
+ expirySlot: number;
39
+ licenseHash: string;
40
+ zkAppAddress: string;
41
+ // Key the keeper stored the per-app in-flight slot under. Passed back to
42
+ // POST /tx-broadcast after the wallet returns a hash. See ProveBuyResponse.
43
+ appKey: string;
44
+ }
45
+
46
+ /**
47
+ * Terminal migrate failures (404 refunded/unknown, 409 already migrated).
48
+ * The queue-busy 409 is surfaced separately as ProveQueueBusyError so
49
+ * callers can share one retry helper across buy/renew/migrate.
50
+ */
51
+ export class ProveMigrateError extends Error {
52
+ readonly status: number;
53
+ constructor(message: string, status: number) {
54
+ super(message);
55
+ this.name = 'ProveMigrateError';
56
+ this.status = status;
57
+ }
58
+ }
59
+
60
+ function baseUrl(url: string): string {
61
+ return url.replace(/\/+$/, '');
62
+ }
63
+
64
+ export async function proveMigrate(req: ProveMigrateRequest): Promise<ProveMigrateResponse> {
65
+ const fetcher = req.fetcher ?? fetch;
66
+ const resp = await fetcher(`${baseUrl(req.keeperUrl)}/prove/migrate`, {
67
+ method: 'POST',
68
+ headers: { 'Content-Type': 'application/json' },
69
+ signal: req.signal,
70
+ body: JSON.stringify({
71
+ network: req.network,
72
+ licenseHash: req.licenseHash,
73
+ appId: req.appId,
74
+ buyerAddress: req.buyerAddress,
75
+ }),
76
+ });
77
+ if (!resp.ok) {
78
+ const parsed = await readErrorBody(resp);
79
+ const queueBusy = tryQueueBusyFromBody(parsed);
80
+ if (queueBusy) throw queueBusy;
81
+ throw new ProveMigrateError(parsed.message, resp.status);
82
+ }
83
+ return await resp.json() as ProveMigrateResponse;
84
+ }
@@ -0,0 +1,107 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * onChainRoot.ts
6
+ *
7
+ * Non-custodial trust anchor for `verifyOffline`. Reads the live
8
+ * `licensesRoot` (`zkapp.appState[0]`) directly from Mina — no
9
+ * licensing-service round-trip, no trust assumption about whoever
10
+ * served the witness / license record.
11
+ *
12
+ * Pair it with `verifyOffline` to close the trust loop:
13
+ *
14
+ * ```ts
15
+ * import { fetchOnChainLicensesRoot } from 'zklicensing/on-chain-root';
16
+ * import { verifyOffline } from 'zklicensing/verify-offline';
17
+ *
18
+ * // 1. Ask the licensing service for a witness + slot snapshot.
19
+ * const snap = await fetch(`${service}/witness?licenseHash=${h}&zkAppAddress=${a}`).then(r => r.json());
20
+ *
21
+ * // 2. Fetch the on-chain root INDEPENDENTLY, from Mina.
22
+ * const onChainRoot = await fetchOnChainLicensesRoot({ zkAppAddress: a, network: 'devnet' });
23
+ *
24
+ * // 3. Cross-check — if they disagree, the service is stale/wrong; bail.
25
+ * if (snap.root !== onChainRoot) throw new Error('service root disagrees with chain');
26
+ *
27
+ * // 4. Fold-verify the snapshot against the on-chain root.
28
+ * const res = verifyOffline({ licensesRoot: onChainRoot, ...snap });
29
+ * ```
30
+ *
31
+ * o1js is a peer dep — this file imports it dynamically so callers
32
+ * that only want `verifyOffline` (pure fold, no chain read) don't
33
+ * have to install o1js.
34
+ *
35
+ * Global-state caveat: o1js `Mina.setActiveInstance` mutates a module-
36
+ * scoped singleton. Long-lived hosts that talk to multiple Mina
37
+ * networks in the same process should treat this helper as a
38
+ * one-shot and re-set their own preferred network after use, or wrap
39
+ * it in a mutex.
40
+ */
41
+
42
+ // GraphQL endpoints published by Minascan. These are read-only public
43
+ // nodes — no auth, no rate-limit key. Vendors who prefer their own
44
+ // Mina node can override via `graphqlUrl` on the input.
45
+ export const DEFAULT_MINA_GRAPHQL_URLS = {
46
+ mainnet: 'https://api.minascan.io/node/mainnet/v1/graphql',
47
+ devnet: 'https://api.minascan.io/node/devnet/v1/graphql',
48
+ } as const;
49
+
50
+ export type NetworkName = 'mainnet' | 'devnet';
51
+
52
+ export type FetchOnChainLicensesRootInput = {
53
+ /** B62q… address of the deployed LicensingApp for this app. */
54
+ zkAppAddress: string;
55
+ } & (
56
+ | { network: NetworkName; graphqlUrl?: string }
57
+ | { graphqlUrl: string; network?: NetworkName }
58
+ );
59
+
60
+ /**
61
+ * Read the live `licensesRoot` from the deployed LicensingApp's
62
+ * on-chain state. Returns the field value as a decimal string,
63
+ * matching the shape `verifyOffline` and the licensing service both
64
+ * consume.
65
+ *
66
+ * Throws on any of:
67
+ * - `o1js` not installed (peer dep missing);
68
+ * - `fetchAccount` returned an error (network down, wrong endpoint,
69
+ * account doesn't exist on this chain);
70
+ * - account exists but has no zkApp state (not a zkApp address, or
71
+ * contract deployed but `initialize()` never ran).
72
+ */
73
+ export async function fetchOnChainLicensesRoot(
74
+ input: FetchOnChainLicensesRootInput,
75
+ ): Promise<string> {
76
+ const { zkAppAddress } = input;
77
+ const network: NetworkName = input.network ?? 'devnet';
78
+ const graphqlUrl = input.graphqlUrl ?? DEFAULT_MINA_GRAPHQL_URLS[network];
79
+
80
+ let o1js: any;
81
+ try {
82
+ o1js = await import('o1js');
83
+ } catch (err: any) {
84
+ throw new Error(
85
+ `zklicensing/on-chain-root: o1js not installed — install it as a peer dep (${err?.message ?? err})`,
86
+ );
87
+ }
88
+
89
+ // o1js's networkId for devnet is 'testnet'; only mainnet uses 'mainnet'.
90
+ const networkId = network === 'mainnet' ? 'mainnet' : 'testnet';
91
+ const mina = o1js.Mina.Network({ networkId, mina: graphqlUrl });
92
+ o1js.Mina.setActiveInstance(mina);
93
+
94
+ const publicKey = o1js.PublicKey.fromBase58(zkAppAddress);
95
+ const { account, error } = await o1js.fetchAccount({ publicKey });
96
+ if (error) {
97
+ const detail = error.statusText ?? error.statusCode ?? JSON.stringify(error);
98
+ throw new Error(`fetchAccount(${zkAppAddress}) via ${graphqlUrl} failed: ${detail}`);
99
+ }
100
+ const root = account?.zkapp?.appState?.[0]?.toString?.();
101
+ if (!root) {
102
+ throw new Error(
103
+ `zkApp ${zkAppAddress} has no appState — is the LicensingApp deployed and initialized on ${network}?`,
104
+ );
105
+ }
106
+ return root;
107
+ }
@@ -0,0 +1,31 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * ownershipLicenseHash.ts
6
+ *
7
+ * Field-side binding between the buyer's Pallas Schnorr pubkey and the
8
+ * `licenseHash` Field stored on-chain. The buy circuit and the buy client
9
+ * both compute this from the pubkey and assert equality — that mutual
10
+ * assertion is what proves knowledge of the passphrase without ever
11
+ * showing the passphrase to the network.
12
+ *
13
+ * A Pallas `PublicKey` is `(x: Field, isOdd: Bool)` — the two Fields that
14
+ * uniquely identify the compressed point. Poseidon-hashing them yields a
15
+ * single Field that matches the on-chain shape of every other `licenseHash`
16
+ * used by LicensingApp (which treats licenseHash as an opaque Field
17
+ * commitment, not a specific preimage).
18
+ */
19
+
20
+ import { Poseidon, PublicKey } from 'o1js';
21
+
22
+ /**
23
+ * Derive the Field-side `licenseHash` from a Pallas Schnorr pubkey. The
24
+ * hash is domain-free because the whole platform treats `licenseHash` as
25
+ * an opaque commitment — the on-chain contract never re-derives it from
26
+ * a preimage, so there's no cross-preimage collision surface to guard
27
+ * against here.
28
+ */
29
+ export function licenseHashFromPubkey(publicKey: PublicKey): string {
30
+ return Poseidon.hash([publicKey.x, publicKey.isOdd.toField()]).toString();
31
+ }
@@ -0,0 +1,354 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * ownershipSignature.ts
6
+ *
7
+ * Schnorr-over-Pallas signing primitive for the two on-chain flows that
8
+ * need the passphrase-derived owner key:
9
+ *
10
+ * 1. The /prove/bind and /prove/unbind flows — the passphrase-derived
11
+ * keypair authorizes device slot mutations, and the signature is
12
+ * re-verified INSIDE the circuit by `Signature.verify()` so even a
13
+ * compromised licensing service cannot forge a bind.
14
+ * 2. The retained `ActivationMessage` shape (see below) — kept so external
15
+ * tooling can still sign an "I hold the passphrase for this license"
16
+ * assertion off-band. The platform no longer runs a challenge/respond
17
+ * endpoint; the shape is purely an SDK primitive now.
18
+ *
19
+ * Deterministic HKDF-SHA256 derivation of a seed from the passphrase,
20
+ * reduced to a Pallas scalar → o1js `PrivateKey`. The buyer can
21
+ * re-derive the same keypair anywhere from just the passphrase.
22
+ *
23
+ * o1js-dependent by design: the whole point of switching from Ed25519 to
24
+ * Pallas Schnorr is native in-circuit verification. Any client that
25
+ * signs an activation or binding challenge already ships o1js for the
26
+ * downstream buy/verify surface, so the "keep this module o1js-free"
27
+ * constraint that motivated the Ed25519 version no longer applies.
28
+ *
29
+ * HKDF still needs WebCrypto (Node ≥ 20, Chromium 137+, Safari 17+,
30
+ * Firefox 130+). The module throws at derive time if
31
+ * `globalThis.crypto.subtle` is unavailable — callers cannot silently
32
+ * fall back to a weaker path.
33
+ */
34
+
35
+ import { Field, PrivateKey, PublicKey, Signature } from 'o1js';
36
+
37
+ // HKDF info binds the derivation to a specific zkApp address, so the
38
+ // same passphrase yields different keypairs for different apps. This
39
+ // makes credentials per-app: a leaked passphrase for app A cannot be
40
+ // replayed as an activation for app B. RFC 5869 designates `info` as
41
+ // the domain-separation channel (salt is for randomness, which we don't
42
+ // have here — the passphrase IS the secret input).
43
+ //
44
+ // The `v1` prefix reserves room to rotate the KDF or the target key type
45
+ // later without a silent collision — a future scheme bumps to `v2` and
46
+ // derives an unrelated key from the same passphrase.
47
+ const HKDF_INFO_PREFIX = 'zkLicensing/v1/ownership|';
48
+ const HKDF_SALT = new Uint8Array(0);
49
+
50
+ // Domain-separation tags baked into every signed message. Prevents a
51
+ // signature captured on one flow (activation) from being replayed on
52
+ // another (binding) — the first Field the signer hashes is the flow ID,
53
+ // so the two signatures live in disjoint spaces even at identical
54
+ // (licenseHash, nonce).
55
+ //
56
+ // Exported so `LicensingApp.bind()` / `unbind()` can rebuild the exact
57
+ // same Field[] preimage inside the circuit for `Signature.verify()`.
58
+ // Bumping these values is a hardfork — every off-chain signer and every
59
+ // deployed circuit would need to agree.
60
+ export const TAG_ACTIVATION = 1n;
61
+ export const TAG_BINDING = 2n;
62
+ export const TAG_UNBINDING = 3n;
63
+
64
+ function buildHkdfInfo(zkAppAddress: string): Uint8Array {
65
+ return new TextEncoder().encode(HKDF_INFO_PREFIX + zkAppAddress);
66
+ }
67
+
68
+ function utf8Bytes(s: string): Uint8Array {
69
+ return new TextEncoder().encode(s);
70
+ }
71
+
72
+ function bytesToBase64(bytes: Uint8Array): string {
73
+ let s = '';
74
+ for (const b of bytes) s += String.fromCharCode(b);
75
+ return btoa(s);
76
+ }
77
+
78
+ function base64ToBytes(b64: string): Uint8Array {
79
+ const bin = atob(b64);
80
+ const out = new Uint8Array(bin.length);
81
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
82
+ return out;
83
+ }
84
+
85
+ function subtle(): SubtleCrypto {
86
+ const s = (globalThis.crypto as Crypto | undefined)?.subtle;
87
+ if (!s) {
88
+ throw new Error(
89
+ 'WebCrypto unavailable — ownershipSignature requires Node ≥ 20 or a modern browser (Chromium 137+, Safari 17+, Firefox 130+).',
90
+ );
91
+ }
92
+ return s;
93
+ }
94
+
95
+ function bytesToBigInt(bytes: Uint8Array): bigint {
96
+ let n = 0n;
97
+ for (const b of bytes) n = (n << 8n) | BigInt(b);
98
+ return n;
99
+ }
100
+
101
+ /**
102
+ * HKDF-SHA256 with empty salt and a per-app domain-separation info
103
+ * string (`zkLicensing/v1/ownership|<zkAppAddress>`). Deterministic:
104
+ * same (passphrase, zkAppAddress) → same 32-byte seed. Different
105
+ * zkAppAddress → cryptographically unrelated seed even with the same
106
+ * passphrase.
107
+ */
108
+ export async function deriveSeed(
109
+ passphrase: string,
110
+ zkAppAddress: string,
111
+ ): Promise<Uint8Array> {
112
+ const baseKey = await subtle().importKey(
113
+ 'raw',
114
+ utf8Bytes(passphrase) as unknown as ArrayBuffer,
115
+ 'HKDF',
116
+ false,
117
+ ['deriveBits'],
118
+ );
119
+ const info = buildHkdfInfo(zkAppAddress);
120
+ const bits = await subtle().deriveBits(
121
+ {
122
+ name: 'HKDF',
123
+ hash: 'SHA-256',
124
+ salt: HKDF_SALT as unknown as ArrayBuffer,
125
+ info: info as unknown as ArrayBuffer,
126
+ },
127
+ baseKey,
128
+ 256,
129
+ );
130
+ return new Uint8Array(bits);
131
+ }
132
+
133
+ export type OwnershipKeypair = {
134
+ privateKey: PrivateKey;
135
+ publicKey: PublicKey;
136
+ publicKeyBase58: string;
137
+ };
138
+
139
+ /**
140
+ * Derive a Pallas Schnorr keypair deterministically from (passphrase,
141
+ * zkAppAddress). The keypair is bound to the specific app: the same
142
+ * passphrase used against a different app yields a different keypair,
143
+ * so a leaked passphrase cannot be replayed as an activation for any
144
+ * other app.
145
+ *
146
+ * The 32-byte HKDF output is interpreted as a big-endian integer and
147
+ * passed to `PrivateKey.fromBigInt`, which reduces it modulo the Pallas
148
+ * scalar field order internally. All 2^256 possible HKDF outputs map to
149
+ * valid private keys with (256 - log2(Fq_order))-bit modular bias — the
150
+ * scalar field is ~254 bits, so bias is <2^-253 and lies well below any
151
+ * practical distinguisher.
152
+ */
153
+ export async function deriveOwnershipKeypair(
154
+ passphrase: string,
155
+ zkAppAddress: string,
156
+ ): Promise<OwnershipKeypair> {
157
+ const seed = await deriveSeed(passphrase, zkAppAddress);
158
+ const privateKey = PrivateKey.fromBigInt(bytesToBigInt(seed));
159
+ const publicKey = privateKey.toPublicKey();
160
+ return { privateKey, publicKey, publicKeyBase58: publicKey.toBase58() };
161
+ }
162
+
163
+ // ── Message shapes ────────────────────────────────────────────────
164
+
165
+ /**
166
+ * Activation assertion shape. Proves the caller holds the passphrase
167
+ * that derived the license's ownerPubKey. Retained as an SDK primitive
168
+ * so external tooling can still request / verify an off-band "I own
169
+ * this license" signature — the on-chain flows themselves do not use
170
+ * it.
171
+ */
172
+ export type ActivationMessage = {
173
+ licenseHash: string; // Field as decimal string
174
+ nonce: string; // Field as decimal string — replay defense
175
+ zkAppAddress: string; // base58
176
+ };
177
+
178
+ /**
179
+ * Binding / unbinding message — the /prove/bind and /prove/unbind
180
+ * flows. Authorizes a specific device commitment being placed into or
181
+ * cleared from a specific slot on a specific license.
182
+ */
183
+ export type BindingMessage = {
184
+ licenseHash: string; // Field as decimal string
185
+ deviceCommitment: string; // Field as decimal string (Poseidon(devicePubKeyHash))
186
+ slotIndex: number; // 0..cap-1
187
+ nonce: string; // Field as decimal string — replay defense
188
+ };
189
+
190
+ // Retained for back-compat with callers that imported ChallengeMessage
191
+ // from this module before the v2 rename. New code should use
192
+ // ActivationMessage directly.
193
+ export type ChallengeMessage = ActivationMessage;
194
+
195
+ /**
196
+ * Canonicalize the activation message into the Field[] that
197
+ * `Signature.create` / `Signature.verify` hash. The domain-separation
198
+ * tag prefix means no captured activation signature can be replayed as
199
+ * a binding signature, even if all other fields collide.
200
+ */
201
+ export function activationMessageFields(msg: ActivationMessage): Field[] {
202
+ const addr = PublicKey.fromBase58(msg.zkAppAddress);
203
+ return [
204
+ Field(TAG_ACTIVATION),
205
+ Field(msg.licenseHash),
206
+ Field(msg.nonce),
207
+ addr.x,
208
+ addr.isOdd.toField(),
209
+ ];
210
+ }
211
+
212
+ /**
213
+ * Canonicalize a binding or unbinding message. The `tag` argument
214
+ * distinguishes bind (TAG_BINDING) from unbind (TAG_UNBINDING) so a
215
+ * bind signature captured off-chain cannot be replayed as an unbind
216
+ * even at identical (licenseHash, deviceCommitment, slotIndex, nonce).
217
+ */
218
+ function bindingLikeFields(tag: bigint, msg: BindingMessage): Field[] {
219
+ return [
220
+ Field(tag),
221
+ Field(msg.licenseHash),
222
+ Field(msg.deviceCommitment),
223
+ Field(msg.slotIndex),
224
+ Field(msg.nonce),
225
+ ];
226
+ }
227
+
228
+ export function bindingMessageFields(msg: BindingMessage): Field[] {
229
+ return bindingLikeFields(TAG_BINDING, msg);
230
+ }
231
+
232
+ export function unbindingMessageFields(msg: BindingMessage): Field[] {
233
+ return bindingLikeFields(TAG_UNBINDING, msg);
234
+ }
235
+
236
+ // ── Signing ───────────────────────────────────────────────────────
237
+
238
+ export function signActivation(
239
+ privateKey: PrivateKey,
240
+ msg: ActivationMessage,
241
+ ): Signature {
242
+ return Signature.create(privateKey, activationMessageFields(msg));
243
+ }
244
+
245
+ export function signBinding(
246
+ privateKey: PrivateKey,
247
+ msg: BindingMessage,
248
+ ): Signature {
249
+ return Signature.create(privateKey, bindingMessageFields(msg));
250
+ }
251
+
252
+ export function signUnbinding(
253
+ privateKey: PrivateKey,
254
+ msg: BindingMessage,
255
+ ): Signature {
256
+ return Signature.create(privateKey, unbindingMessageFields(msg));
257
+ }
258
+
259
+ // Retained for back-compat with the Ed25519-era name. New code should
260
+ // call signActivation directly.
261
+ export function signChallenge(
262
+ privateKey: PrivateKey,
263
+ msg: ChallengeMessage,
264
+ ): Signature {
265
+ return signActivation(privateKey, msg);
266
+ }
267
+
268
+ // ── Verification ──────────────────────────────────────────────────
269
+
270
+ /**
271
+ * Verify an activation signature. Returns false (never throws) for any
272
+ * failure — malformed pubkey, malformed signature, actual signature
273
+ * mismatch. Callers get a single go/no-go decision without having to
274
+ * distinguish "invalid" from "unparseable."
275
+ */
276
+ export function verifyActivation(
277
+ publicKey: PublicKey,
278
+ msg: ActivationMessage,
279
+ signature: Signature,
280
+ ): boolean {
281
+ try {
282
+ return signature.verify(publicKey, activationMessageFields(msg)).toBoolean();
283
+ } catch {
284
+ return false;
285
+ }
286
+ }
287
+
288
+ export function verifyBinding(
289
+ publicKey: PublicKey,
290
+ msg: BindingMessage,
291
+ signature: Signature,
292
+ ): boolean {
293
+ try {
294
+ return signature.verify(publicKey, bindingMessageFields(msg)).toBoolean();
295
+ } catch {
296
+ return false;
297
+ }
298
+ }
299
+
300
+ export function verifyUnbinding(
301
+ publicKey: PublicKey,
302
+ msg: BindingMessage,
303
+ signature: Signature,
304
+ ): boolean {
305
+ try {
306
+ return signature.verify(publicKey, unbindingMessageFields(msg)).toBoolean();
307
+ } catch {
308
+ return false;
309
+ }
310
+ }
311
+
312
+ // Back-compat alias, see signChallenge.
313
+ export function verifyChallenge(
314
+ publicKey: PublicKey,
315
+ msg: ChallengeMessage,
316
+ signature: Signature,
317
+ ): boolean {
318
+ return verifyActivation(publicKey, msg, signature);
319
+ }
320
+
321
+ // ── Wire encoding helpers ─────────────────────────────────────────
322
+
323
+ /**
324
+ * Encode a signature for the wire (POST body, ProofFile JSON, etc).
325
+ * Base58 matches Mina's canonical serialization for both PublicKey and
326
+ * Signature, keeping the same encoding shape across everything the
327
+ * buyer's SDK produces.
328
+ */
329
+ export function encodeSignature(sig: Signature): string {
330
+ return sig.toBase58();
331
+ }
332
+
333
+ export function decodeSignature(base58: string): Signature {
334
+ return Signature.fromBase58(base58);
335
+ }
336
+
337
+ export function encodePublicKey(pk: PublicKey): string {
338
+ return pk.toBase58();
339
+ }
340
+
341
+ export function decodePublicKey(base58: string): PublicKey {
342
+ return PublicKey.fromBase58(base58);
343
+ }
344
+
345
+ // Retained so callers that already do `encodeBase64(seed)` for logging
346
+ // or persistence keep working — this module no longer produces raw byte
347
+ // pubkeys or signatures, only o1js objects with .toBase58().
348
+ export function encodeBase64(bytes: Uint8Array): string {
349
+ return bytesToBase64(bytes);
350
+ }
351
+
352
+ export function decodeBase64(b64: string): Uint8Array {
353
+ return base64ToBytes(b64);
354
+ }
@@ -0,0 +1,70 @@
1
+ // Copyright (c) 2025-2026 zkLicensing project developers
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+
4
+ /**
5
+ * proveErrors.ts
6
+ *
7
+ * Shared typed error for the "proving queue busy" 409 surface returned by
8
+ * /prove/buy, /prove/buy-no-escrow, /prove/renew, /prove/migrate, and
9
+ * /prove/refund. The keeper serializes all five endpoints on a per-app
10
+ * in-flight slot: while a proof is out with a buyer waiting to be signed
11
+ * (or a signed tx is waiting to land), further requests against the same
12
+ * app get an immediate 409 with a `retryAfterMs` hint. Callers should catch
13
+ * this and wait+retry rather than surfacing the failure — the wallet popup
14
+ * never opens for a proof with no live chance of landing.
15
+ *
16
+ * `queueDepth` is 1 in v1 (single slot per app); the field exists so that a
17
+ * future Tier-1 optimistic-chaining pass can widen it without breaking
18
+ * clients written today.
19
+ */
20
+
21
+ export class ProveQueueBusyError extends Error {
22
+ readonly status = 409;
23
+ readonly retryAfterMs: number;
24
+ readonly queueDepth: number;
25
+ constructor(message: string, retryAfterMs: number, queueDepth: number) {
26
+ super(message);
27
+ this.name = 'ProveQueueBusyError';
28
+ this.retryAfterMs = retryAfterMs;
29
+ this.queueDepth = queueDepth;
30
+ }
31
+ }
32
+
33
+ // Shared 409-body shape used by all four prove endpoints. Matches keeper.
34
+ export type ProveQueueBusyBody = {
35
+ error: 'proving queue busy';
36
+ retryAfterMs: number;
37
+ queueDepth?: number;
38
+ };
39
+
40
+ // Reads the response body as JSON exactly once and returns a normalized
41
+ // view. Callers use this in the non-2xx branch to decide the specific
42
+ // error surface (queue-busy, endpoint-specific, or generic).
43
+ export type ParsedErrorBody = {
44
+ status: number;
45
+ body: Record<string, unknown>;
46
+ // Convenience: extracted `body.error` when it's a string, else the HTTP fallback.
47
+ message: string;
48
+ };
49
+
50
+ export async function readErrorBody(resp: Response): Promise<ParsedErrorBody> {
51
+ let body: Record<string, unknown> = {};
52
+ try {
53
+ body = await resp.json() as Record<string, unknown>;
54
+ } catch { /* body wasn't JSON */ }
55
+ const message = typeof body.error === 'string' ? body.error : `HTTP ${resp.status}`;
56
+ return { status: resp.status, body, message };
57
+ }
58
+
59
+ // Returns a ProveQueueBusyError if the parsed body matches the queue-busy
60
+ // shape; otherwise null. Cheap to call — no I/O.
61
+ export function tryQueueBusyFromBody(parsed: ParsedErrorBody): ProveQueueBusyError | null {
62
+ if (parsed.status !== 409) return null;
63
+ const { body } = parsed;
64
+ if (body.error !== 'proving queue busy' || typeof body.retryAfterMs !== 'number') return null;
65
+ return new ProveQueueBusyError(
66
+ body.error,
67
+ body.retryAfterMs,
68
+ typeof body.queueDepth === 'number' ? body.queueDepth : 1,
69
+ );
70
+ }