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.
- package/README.md +335 -97
- package/build/appsLookup.d.ts +14 -0
- package/build/appsLookup.d.ts.map +1 -0
- package/build/appsLookup.js +12 -0
- package/build/appsLookup.js.map +1 -0
- package/build/archiveBootstrap.d.ts +15 -1
- package/build/archiveBootstrap.d.ts.map +1 -0
- package/build/archiveBootstrap.js +62 -9
- package/build/archiveBootstrap.js.map +1 -0
- package/build/bindClient.d.ts +51 -0
- package/build/bindClient.d.ts.map +1 -0
- package/build/bindClient.js +115 -0
- package/build/bindClient.js.map +1 -0
- package/build/buyClient.d.ts +10 -3
- package/build/buyClient.d.ts.map +1 -0
- package/build/buyClient.js +33 -15
- package/build/buyClient.js.map +1 -0
- package/build/contractInterface.d.ts +11 -5
- package/build/contractInterface.d.ts.map +1 -0
- package/build/contractInterface.js +82 -17
- package/build/contractInterface.js.map +1 -0
- package/build/countryStats.d.ts +6 -1
- package/build/countryStats.d.ts.map +1 -0
- package/build/countryStats.js +33 -9
- package/build/countryStats.js.map +1 -0
- package/build/deployClient.d.ts.map +1 -0
- package/build/deployClient.js +1 -1
- package/build/deployClient.js.map +1 -0
- package/build/deviceIdentity.d.ts +68 -0
- package/build/deviceIdentity.d.ts.map +1 -0
- package/build/deviceIdentity.js +209 -0
- package/build/deviceIdentity.js.map +1 -0
- package/build/freezeClient.d.ts.map +1 -0
- package/build/freezeClient.js +1 -1
- package/build/freezeClient.js.map +1 -0
- package/build/generationClient.d.ts +1 -0
- package/build/generationClient.d.ts.map +1 -0
- package/build/generationClient.js +2 -2
- package/build/generationClient.js.map +1 -0
- package/build/index.d.ts +27 -37
- package/build/index.d.ts.map +1 -0
- package/build/index.js +85 -116
- package/build/index.js.map +1 -0
- package/build/licenseLeaf.d.ts +76 -0
- package/build/licenseLeaf.d.ts.map +1 -0
- package/build/licenseLeaf.js +189 -0
- package/build/licenseLeaf.js.map +1 -0
- package/build/licenseRecord.d.ts +20 -1
- package/build/licenseRecord.d.ts.map +1 -0
- package/build/licenseRecord.js +1 -1
- package/build/licenseRecord.js.map +1 -0
- package/build/licenseStore.d.ts +17 -2
- package/build/licenseStore.d.ts.map +1 -0
- package/build/licenseStore.js +167 -7
- package/build/licenseStore.js.map +1 -0
- package/build/manifestVerify.d.ts.map +1 -0
- package/build/manifestVerify.js +8 -3
- package/build/manifestVerify.js.map +1 -0
- package/build/migrateClient.d.ts +6 -21
- package/build/migrateClient.d.ts.map +1 -0
- package/build/migrateClient.js +30 -17
- package/build/migrateClient.js.map +1 -0
- package/build/onChainRoot.d.ts +67 -0
- package/build/onChainRoot.d.ts.map +1 -0
- package/build/onChainRoot.js +87 -0
- package/build/onChainRoot.js.map +1 -0
- package/build/ownershipLicenseHash.d.ts +25 -0
- package/build/ownershipLicenseHash.d.ts.map +1 -0
- package/build/ownershipLicenseHash.js +29 -0
- package/build/ownershipLicenseHash.js.map +1 -0
- package/build/ownershipSignature.d.ts +122 -0
- package/build/ownershipSignature.d.ts.map +1 -0
- package/build/ownershipSignature.js +244 -0
- package/build/ownershipSignature.js.map +1 -0
- package/build/proveErrors.d.ts +35 -0
- package/build/proveErrors.d.ts.map +1 -0
- package/build/proveErrors.js +49 -0
- package/build/proveErrors.js.map +1 -0
- package/build/refundClient.d.ts +2 -11
- package/build/refundClient.d.ts.map +1 -0
- package/build/refundClient.js +35 -17
- package/build/refundClient.js.map +1 -0
- package/build/renewClient.d.ts +4 -1
- package/build/renewClient.d.ts.map +1 -0
- package/build/renewClient.js +11 -4
- package/build/renewClient.js.map +1 -0
- package/build/seatName.d.ts +8 -0
- package/build/seatName.d.ts.map +1 -0
- package/build/seatName.js +136 -0
- package/build/seatName.js.map +1 -0
- package/build/statsClient.d.ts +47 -4
- package/build/statsClient.d.ts.map +1 -0
- package/build/statsClient.js +44 -5
- package/build/statsClient.js.map +1 -0
- package/build/trustAnchorVerify.d.ts +48 -0
- package/build/trustAnchorVerify.d.ts.map +1 -0
- package/build/trustAnchorVerify.js +431 -0
- package/build/trustAnchorVerify.js.map +1 -0
- package/build/trustAnchorVerifyCli.d.ts +35 -0
- package/build/trustAnchorVerifyCli.d.ts.map +1 -0
- package/build/trustAnchorVerifyCli.js +177 -0
- package/build/trustAnchorVerifyCli.js.map +1 -0
- package/build/txBroadcastClient.d.ts +26 -0
- package/build/txBroadcastClient.d.ts.map +1 -0
- package/build/txBroadcastClient.js +20 -0
- package/build/txBroadcastClient.js.map +1 -0
- package/build/unbindClient.d.ts +56 -0
- package/build/unbindClient.d.ts.map +1 -0
- package/build/unbindClient.js +113 -0
- package/build/unbindClient.js.map +1 -0
- package/build/vendorAccountClient.d.ts +56 -0
- package/build/vendorAccountClient.d.ts.map +1 -0
- package/build/vendorAccountClient.js +47 -0
- package/build/vendorAccountClient.js.map +1 -0
- package/build/verifyCore.d.ts +1 -1
- package/build/verifyCore.d.ts.map +1 -0
- package/build/verifyCore.js +11 -4
- package/build/verifyCore.js.map +1 -0
- package/build/verifyOffline.d.ts +85 -0
- package/build/verifyOffline.d.ts.map +1 -0
- package/build/verifyOffline.js +139 -0
- package/build/verifyOffline.js.map +1 -0
- package/build/verifyService.d.ts.map +1 -0
- package/build/verifyService.js +582 -455
- package/build/verifyService.js.map +1 -0
- package/build/verifyWithAncestors.d.ts +18 -0
- package/build/verifyWithAncestors.d.ts.map +1 -0
- package/build/verifyWithAncestors.js +119 -0
- package/build/verifyWithAncestors.js.map +1 -0
- package/build/zipToState.d.ts +2 -0
- package/build/zipToState.d.ts.map +1 -0
- package/build/zipToState.js +94 -0
- package/build/zipToState.js.map +1 -0
- package/package.json +57 -13
- package/src/appsLookup.ts +48 -0
- package/src/archiveBootstrap.ts +342 -0
- package/src/bindClient.ts +175 -0
- package/src/buyClient.ts +304 -0
- package/src/contractInterface.d.ts +61 -0
- package/src/contractInterface.ts +313 -0
- package/src/countryStats.ts +171 -0
- package/src/deployClient.ts +388 -0
- package/src/deviceIdentity.ts +249 -0
- package/src/freezeClient.ts +117 -0
- package/src/generationClient.ts +165 -0
- package/src/index.ts +329 -0
- package/src/licenseLeaf.ts +221 -0
- package/src/licenseRecord.ts +108 -0
- package/src/licenseStore.ts +538 -0
- package/src/manifestVerify.ts +111 -0
- package/src/migrateClient.ts +84 -0
- package/src/onChainRoot.ts +107 -0
- package/src/ownershipLicenseHash.ts +31 -0
- package/src/ownershipSignature.ts +354 -0
- package/src/proveErrors.ts +70 -0
- package/src/refundClient.ts +158 -0
- package/src/renewClient.ts +214 -0
- package/src/seatName.ts +165 -0
- package/src/statsClient.ts +235 -0
- package/src/trustAnchorVerify.ts +548 -0
- package/src/trustAnchorVerifyCli.ts +179 -0
- package/src/txBroadcastClient.ts +48 -0
- package/src/unbindClient.ts +149 -0
- package/src/vendorAccountClient.ts +110 -0
- package/src/verifyCore.ts +92 -0
- package/src/verifyOffline.ts +212 -0
- package/src/verifyService.ts +969 -0
- package/src/verifyWithAncestors.ts +153 -0
- package/src/zipToState.ts +94 -0
- package/build/licenseProof.d.ts +0 -26
- package/build/licenseProof.js +0 -41
- package/build/ownership.d.ts +0 -34
- package/build/ownership.js +0 -147
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// Copyright (c) 2025-2026 zkLicensing project developers
|
|
2
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* deviceIdentity.ts
|
|
6
|
+
*
|
|
7
|
+
* Per-install Pallas Schnorr keypair used to identify a device to the
|
|
8
|
+
* non-custodial binding flow. `getOrCreateDeviceIdentity(storageKey)`
|
|
9
|
+
* returns a stable keypair for the caller's storage key: created on
|
|
10
|
+
* first call, loaded verbatim on every subsequent call.
|
|
11
|
+
*
|
|
12
|
+
* The `deviceCommitment` this module exposes matches the on-chain
|
|
13
|
+
* `occupied[i]` field shape written by `LicensingApp.bind()` — it's
|
|
14
|
+
* `Poseidon([pk.x, pk.isOdd.toField()])` over the device's Pallas
|
|
15
|
+
* pubkey (see `ownerPubKeyHash` in ./licenseLeaf.ts for the identical
|
|
16
|
+
* shape applied to the ownership pubkey). Callers pass the commitment
|
|
17
|
+
* to `proveBind` and to the ownership signature; the raw device pubkey
|
|
18
|
+
* itself never crosses the wire.
|
|
19
|
+
*
|
|
20
|
+
* Storage tradeoffs (documented up front — the plan's original
|
|
21
|
+
* assumption was WebCrypto extractable=false, which only applies to
|
|
22
|
+
* WebCrypto-native primitives):
|
|
23
|
+
*
|
|
24
|
+
* Browser path — IndexedDB.
|
|
25
|
+
* Pallas is not a WebCrypto primitive, so we cannot store the
|
|
26
|
+
* private key as a non-extractable CryptoKey. The private key is
|
|
27
|
+
* persisted as its Mina canonical base58 encoding. An adversary
|
|
28
|
+
* with access to the browser profile (malware running as the user,
|
|
29
|
+
* evil browser extension) can read it. This matches the trust
|
|
30
|
+
* model of every other browser-persisted secret today (bearer
|
|
31
|
+
* cookies, IndexedDB tokens); binding to a fresh device after
|
|
32
|
+
* compromise is a keypair regen + one on-chain bind — no funds
|
|
33
|
+
* at risk, only slot churn. Users who want stronger storage can
|
|
34
|
+
* wipe the storageKey between sessions and re-bind on demand.
|
|
35
|
+
*
|
|
36
|
+
* Node / Electron path — keytar (OS keychain).
|
|
37
|
+
* `keytar` is loaded lazily and marked as an optional peer
|
|
38
|
+
* dependency in package.json so the browser bundle isn't dragged
|
|
39
|
+
* into installing native bindings it can't use. If keytar is
|
|
40
|
+
* unavailable at runtime, the SDK throws with a clear message
|
|
41
|
+
* rather than falling back to plaintext-on-disk.
|
|
42
|
+
*
|
|
43
|
+
* The keypair is Pallas-scalar-random, NOT passphrase-derived — the
|
|
44
|
+
* device identity is meant to survive a passphrase reset (the user
|
|
45
|
+
* can re-derive their ownership key from the passphrase, then unbind
|
|
46
|
+
* / rebind existing device slots without re-installing the app).
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
import { PrivateKey, PublicKey, Poseidon } from 'o1js';
|
|
50
|
+
|
|
51
|
+
// ── Storage key namespacing ───────────────────────────────────────
|
|
52
|
+
|
|
53
|
+
// All device identities live under this shared prefix in whatever
|
|
54
|
+
// backing store is chosen. Callers pass a per-app / per-installation
|
|
55
|
+
// suffix (e.g. the app's short name) so a single browser profile can
|
|
56
|
+
// hold distinct device identities for distinct vendors' apps.
|
|
57
|
+
const STORAGE_PREFIX = 'zklic_device_';
|
|
58
|
+
|
|
59
|
+
function namespaced(storageKey: string): string {
|
|
60
|
+
return `${STORAGE_PREFIX}${storageKey}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ── The identity shape callers get back ──────────────────────────
|
|
64
|
+
|
|
65
|
+
export type DeviceIdentity = {
|
|
66
|
+
devicePrivateKey: PrivateKey;
|
|
67
|
+
devicePubKey: PublicKey;
|
|
68
|
+
// Poseidon([pk.x, pk.isOdd.toField()]) as a decimal Field string.
|
|
69
|
+
// Same shape the on-chain `occupied[i]` slot stores, and the value
|
|
70
|
+
// /prove/bind expects in its request body. Callers pass this
|
|
71
|
+
// string directly — no further hashing at the call site.
|
|
72
|
+
deviceCommitment: string;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Compute the on-chain-shaped device commitment from a Pallas pubkey.
|
|
77
|
+
* Exported so tests and downstream tooling can re-derive it without
|
|
78
|
+
* re-instantiating the whole DeviceIdentity.
|
|
79
|
+
*/
|
|
80
|
+
export function computeDeviceCommitment(devicePubKey: PublicKey): string {
|
|
81
|
+
return Poseidon.hash([devicePubKey.x, devicePubKey.isOdd.toField()]).toString();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function buildIdentity(privateKey: PrivateKey): DeviceIdentity {
|
|
85
|
+
const devicePubKey = privateKey.toPublicKey();
|
|
86
|
+
return {
|
|
87
|
+
devicePrivateKey: privateKey,
|
|
88
|
+
devicePubKey,
|
|
89
|
+
deviceCommitment: computeDeviceCommitment(devicePubKey),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ── Environment detection ─────────────────────────────────────────
|
|
94
|
+
|
|
95
|
+
function hasIndexedDB(): boolean {
|
|
96
|
+
return typeof globalThis !== 'undefined'
|
|
97
|
+
&& typeof (globalThis as any).indexedDB !== 'undefined';
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function isNodeLike(): boolean {
|
|
101
|
+
// Node exposes `process.versions.node`; Deno/Bun don't (their
|
|
102
|
+
// process shims omit this key). Browsers have no `process` global
|
|
103
|
+
// unless something's polyfilled it, but the indexedDB branch runs
|
|
104
|
+
// first so that ordering is fine.
|
|
105
|
+
return typeof (globalThis as any).process !== 'undefined'
|
|
106
|
+
&& typeof (globalThis as any).process?.versions?.node === 'string';
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ── IndexedDB backing store (browser) ─────────────────────────────
|
|
110
|
+
|
|
111
|
+
// Small promisified wrapper — no third-party idb library, to keep the
|
|
112
|
+
// SDK dependency surface minimal. Single key/value store; the whole
|
|
113
|
+
// database is one object store with `storageKey` as the key.
|
|
114
|
+
const IDB_DB_NAME = 'zklicensing';
|
|
115
|
+
const IDB_STORE_NAME = 'device_identities';
|
|
116
|
+
const IDB_VERSION = 1;
|
|
117
|
+
|
|
118
|
+
function openIdb(): Promise<IDBDatabase> {
|
|
119
|
+
return new Promise((resolve, reject) => {
|
|
120
|
+
const req = (globalThis as any).indexedDB.open(IDB_DB_NAME, IDB_VERSION);
|
|
121
|
+
req.onupgradeneeded = () => {
|
|
122
|
+
const db = req.result as IDBDatabase;
|
|
123
|
+
if (!db.objectStoreNames.contains(IDB_STORE_NAME)) {
|
|
124
|
+
db.createObjectStore(IDB_STORE_NAME);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
req.onsuccess = () => resolve(req.result);
|
|
128
|
+
req.onerror = () => reject(req.error ?? new Error('IndexedDB open failed'));
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function idbGet(key: string): Promise<string | null> {
|
|
133
|
+
const db = await openIdb();
|
|
134
|
+
try {
|
|
135
|
+
return await new Promise<string | null>((resolve, reject) => {
|
|
136
|
+
const tx = db.transaction(IDB_STORE_NAME, 'readonly');
|
|
137
|
+
const store = tx.objectStore(IDB_STORE_NAME);
|
|
138
|
+
const req = store.get(key);
|
|
139
|
+
req.onsuccess = () => resolve((req.result as string | undefined) ?? null);
|
|
140
|
+
req.onerror = () => reject(req.error ?? new Error('IndexedDB get failed'));
|
|
141
|
+
});
|
|
142
|
+
} finally {
|
|
143
|
+
db.close();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function idbPut(key: string, value: string): Promise<void> {
|
|
148
|
+
const db = await openIdb();
|
|
149
|
+
try {
|
|
150
|
+
await new Promise<void>((resolve, reject) => {
|
|
151
|
+
const tx = db.transaction(IDB_STORE_NAME, 'readwrite');
|
|
152
|
+
const store = tx.objectStore(IDB_STORE_NAME);
|
|
153
|
+
const req = store.put(value, key);
|
|
154
|
+
req.onsuccess = () => resolve();
|
|
155
|
+
req.onerror = () => reject(req.error ?? new Error('IndexedDB put failed'));
|
|
156
|
+
});
|
|
157
|
+
} finally {
|
|
158
|
+
db.close();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ── keytar backing store (Node / Electron) ────────────────────────
|
|
163
|
+
|
|
164
|
+
// Loaded via dynamic import so a browser bundler doesn't try to
|
|
165
|
+
// resolve the native module. If keytar isn't installed we throw with
|
|
166
|
+
// a message that tells the caller which optional peer dep to add,
|
|
167
|
+
// rather than silently persisting to plaintext.
|
|
168
|
+
async function loadKeytar(): Promise<any> {
|
|
169
|
+
try {
|
|
170
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
171
|
+
return await (Function('return import("keytar")')() as Promise<any>);
|
|
172
|
+
} catch {
|
|
173
|
+
throw new Error(
|
|
174
|
+
'deviceIdentity requires the optional peer dependency `keytar` in Node/Electron. ' +
|
|
175
|
+
'Install it with `npm i keytar` alongside the zklicensing SDK.',
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// keytar's shape: getPassword(service, account) / setPassword(service, account, value).
|
|
181
|
+
// We use a single service name and let `storageKey` be the account, so
|
|
182
|
+
// multiple apps under the same node install can coexist under distinct
|
|
183
|
+
// storage keys without stomping each other.
|
|
184
|
+
const KEYTAR_SERVICE = 'zklicensing-device-identity';
|
|
185
|
+
|
|
186
|
+
async function keytarGet(key: string): Promise<string | null> {
|
|
187
|
+
const keytar = await loadKeytar();
|
|
188
|
+
const mod = (keytar.default ?? keytar) as { getPassword: (s: string, a: string) => Promise<string | null> };
|
|
189
|
+
return mod.getPassword(KEYTAR_SERVICE, key);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function keytarPut(key: string, value: string): Promise<void> {
|
|
193
|
+
const keytar = await loadKeytar();
|
|
194
|
+
const mod = (keytar.default ?? keytar) as { setPassword: (s: string, a: string, p: string) => Promise<void> };
|
|
195
|
+
await mod.setPassword(KEYTAR_SERVICE, key, value);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ── Backend selection ────────────────────────────────────────────
|
|
199
|
+
|
|
200
|
+
type Backend = {
|
|
201
|
+
get: (key: string) => Promise<string | null>;
|
|
202
|
+
put: (key: string, value: string) => Promise<void>;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
function pickBackend(): Backend {
|
|
206
|
+
if (hasIndexedDB()) return { get: idbGet, put: idbPut };
|
|
207
|
+
if (isNodeLike()) return { get: keytarGet, put: keytarPut };
|
|
208
|
+
throw new Error(
|
|
209
|
+
'deviceIdentity: no suitable storage backend detected. ' +
|
|
210
|
+
'Expected IndexedDB in the browser or a Node/Electron runtime with `keytar` installed.',
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ── Public API ────────────────────────────────────────────────────
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Load an existing device keypair for `storageKey`, or create + persist
|
|
218
|
+
* a fresh one on first call. Idempotent across every subsequent call
|
|
219
|
+
* for the same key on the same install.
|
|
220
|
+
*
|
|
221
|
+
* The `storageKey` should be per-app (e.g. the vendor's app short
|
|
222
|
+
* name or its `appId`), so a single browser profile / OS user account
|
|
223
|
+
* can hold distinct device identities for distinct vendors without
|
|
224
|
+
* cross-contamination.
|
|
225
|
+
*/
|
|
226
|
+
export async function getOrCreateDeviceIdentity(storageKey: string): Promise<DeviceIdentity> {
|
|
227
|
+
if (!storageKey || typeof storageKey !== 'string') {
|
|
228
|
+
throw new Error('getOrCreateDeviceIdentity: storageKey must be a non-empty string');
|
|
229
|
+
}
|
|
230
|
+
const backend = pickBackend();
|
|
231
|
+
const key = namespaced(storageKey);
|
|
232
|
+
|
|
233
|
+
const existing = await backend.get(key);
|
|
234
|
+
if (existing) {
|
|
235
|
+
try {
|
|
236
|
+
const privateKey = PrivateKey.fromBase58(existing);
|
|
237
|
+
return buildIdentity(privateKey);
|
|
238
|
+
} catch {
|
|
239
|
+
// Corrupt persisted value — fall through and mint a fresh key,
|
|
240
|
+
// overwriting the bad blob. Losing a device identity here is
|
|
241
|
+
// recoverable: the caller re-binds the new keypair and unbinds
|
|
242
|
+
// the old slot from any other device that still has the
|
|
243
|
+
// ownership key.
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const privateKey = PrivateKey.random();
|
|
247
|
+
await backend.put(key, privateKey.toBase58());
|
|
248
|
+
return buildIdentity(privateKey);
|
|
249
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Copyright (c) 2025-2026 zkLicensing project developers
|
|
2
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* freezeClient.ts
|
|
6
|
+
*
|
|
7
|
+
* Client-side view of the keeper's sales-freeze schedule. A freeze is set
|
|
8
|
+
* ahead of a hardfork so every open escrow window can drain (refund or
|
|
9
|
+
* release) before v1 → v2 migration. Once past the freeze slot the keeper
|
|
10
|
+
* refuses new buys and renewals; refunds and verify remain open.
|
|
11
|
+
*
|
|
12
|
+
* Resolution order for buy/renew clients that want to know the current
|
|
13
|
+
* freeze state:
|
|
14
|
+
* 1. Caller-supplied `freezeAfterSlot` (explicit override — build-time
|
|
15
|
+
* constant, or pulled from the vendor's own env at boot).
|
|
16
|
+
* 2. `process.env.FREEZE_AFTER_SLOT` when running under Node (server-side
|
|
17
|
+
* integrators / CLIs).
|
|
18
|
+
* 3. Keeper's own `/health` payload — the authoritative source of truth.
|
|
19
|
+
*
|
|
20
|
+
* A `freezeAfterSlot` of 0 / null / undefined means "no freeze scheduled".
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
export type KeeperHealth = {
|
|
24
|
+
status: string;
|
|
25
|
+
network: string;
|
|
26
|
+
slot: number;
|
|
27
|
+
salesFrozen: boolean;
|
|
28
|
+
freezeAfterSlot: number | null;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type FreezeState = {
|
|
32
|
+
// True when the current slot is past freezeAfterSlot — new buys and
|
|
33
|
+
// renewals are refused keeper-side.
|
|
34
|
+
salesFrozen: boolean;
|
|
35
|
+
// Scheduled freeze slot (announced ahead of a hardfork). Null when no
|
|
36
|
+
// freeze is configured. Buy clients should require an explicit
|
|
37
|
+
// refund-window waiver only when the buyer's 14-day refund window would
|
|
38
|
+
// extend past this slot (i.e. currentSlot + REFUND_WINDOW_N > freezeAfterSlot).
|
|
39
|
+
freezeAfterSlot: number | null;
|
|
40
|
+
// Chain slot at resolution time. Populated from /health; null on the
|
|
41
|
+
// caller-override / env paths where the slot is not known client-side.
|
|
42
|
+
// Callers computing refund-window overlap should treat null
|
|
43
|
+
// conservatively (require the waiver) — the keeper's own guard is still
|
|
44
|
+
// the last line of defence.
|
|
45
|
+
currentSlot: number | null;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
function baseUrl(url: string): string {
|
|
49
|
+
return url.replace(/\/+$/, '');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function envFreezeSlot(): number | null {
|
|
53
|
+
// Runs both in Node (process.env) and browser (no `process`). The typeof
|
|
54
|
+
// guard keeps bundlers from choking on the reference.
|
|
55
|
+
if (typeof process === 'undefined' || !process.env) return null;
|
|
56
|
+
const raw = process.env.FREEZE_AFTER_SLOT;
|
|
57
|
+
if (!raw) return null;
|
|
58
|
+
const n = parseInt(raw, 10);
|
|
59
|
+
return Number.isFinite(n) && n > 0 ? n : null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type GetKeeperHealthOptions = {
|
|
63
|
+
keeperUrl: string;
|
|
64
|
+
fetcher?: typeof fetch;
|
|
65
|
+
signal?: AbortSignal;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
// GET /health — raw payload. Callers that only need the freeze state
|
|
69
|
+
// should use resolveFreezeState() instead; this is exposed for UIs that
|
|
70
|
+
// surface slot / network info alongside freeze.
|
|
71
|
+
export async function getKeeperHealth(opts: GetKeeperHealthOptions): Promise<KeeperHealth> {
|
|
72
|
+
const fetcher = opts.fetcher ?? fetch;
|
|
73
|
+
const resp = await fetcher(`${baseUrl(opts.keeperUrl)}/health`, { signal: opts.signal });
|
|
74
|
+
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
|
75
|
+
return await resp.json() as KeeperHealth;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type ResolveFreezeStateOptions = {
|
|
79
|
+
keeperUrl: string;
|
|
80
|
+
// Explicit override (highest precedence). Null/undefined falls through
|
|
81
|
+
// to env, then /health.
|
|
82
|
+
freezeAfterSlot?: number | null;
|
|
83
|
+
fetcher?: typeof fetch;
|
|
84
|
+
signal?: AbortSignal;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// Resolves the effective freeze state for the caller. When the source is
|
|
88
|
+
// the caller override or process.env, the current slot is not known
|
|
89
|
+
// client-side, so salesFrozen is filled from /health only — the override
|
|
90
|
+
// path returns { freezeAfterSlot: N, salesFrozen: false, currentSlot: null }
|
|
91
|
+
// and lets the keeper reject the actual prove call if the freeze has fired.
|
|
92
|
+
export async function resolveFreezeState(opts: ResolveFreezeStateOptions): Promise<FreezeState> {
|
|
93
|
+
if (typeof opts.freezeAfterSlot === 'number' && opts.freezeAfterSlot > 0) {
|
|
94
|
+
return { salesFrozen: false, freezeAfterSlot: opts.freezeAfterSlot, currentSlot: null };
|
|
95
|
+
}
|
|
96
|
+
const envSlot = envFreezeSlot();
|
|
97
|
+
if (envSlot !== null) {
|
|
98
|
+
return { salesFrozen: false, freezeAfterSlot: envSlot, currentSlot: null };
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const health = await getKeeperHealth({
|
|
102
|
+
keeperUrl: opts.keeperUrl,
|
|
103
|
+
fetcher: opts.fetcher,
|
|
104
|
+
signal: opts.signal,
|
|
105
|
+
});
|
|
106
|
+
return {
|
|
107
|
+
salesFrozen: health.salesFrozen === true,
|
|
108
|
+
freezeAfterSlot: typeof health.freezeAfterSlot === 'number' ? health.freezeAfterSlot : null,
|
|
109
|
+
currentSlot: typeof health.slot === 'number' ? health.slot : null,
|
|
110
|
+
};
|
|
111
|
+
} catch {
|
|
112
|
+
// /health unreachable — treat as no freeze so we don't block buys on a
|
|
113
|
+
// transient network hiccup. The keeper's own guard is still the last
|
|
114
|
+
// line of defense.
|
|
115
|
+
return { salesFrozen: false, freezeAfterSlot: null, currentSlot: null };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// Copyright (c) 2025-2026 zkLicensing project developers
|
|
2
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* generationClient.ts
|
|
6
|
+
*
|
|
7
|
+
* Browser-safe fetcher for the keeper's signed generation-list. Returns the
|
|
8
|
+
* app's deployment history — every past address plus the current live one —
|
|
9
|
+
* verified against a caller-supplied pin list of platform manifest public
|
|
10
|
+
* keys.
|
|
11
|
+
*
|
|
12
|
+
* Trust model: the keeper is not the trust anchor for this data — it can
|
|
13
|
+
* be re-hosted, mirrored, cached, or (worst case) impersonated. The pin
|
|
14
|
+
* list is. Any response that fails signature verification is surfaced as
|
|
15
|
+
* `verified: false` with `generations: []` so callers cannot accidentally
|
|
16
|
+
* route a wallet prompt to an unverified address.
|
|
17
|
+
*
|
|
18
|
+
* Optional corroboration channel: an operator that publishes
|
|
19
|
+
* https://<vendor-host>/.well-known/zklicensing/<appId>.json
|
|
20
|
+
* (using the same keeper-signed payload) can be cross-checked from the
|
|
21
|
+
* on-chain zkappUri. Per-app filename because a vendor may host several
|
|
22
|
+
* apps at one origin. The cross-check is opt-in per-app — a 404 at that
|
|
23
|
+
* URL is not a failure signal, just "no corroboration published for this
|
|
24
|
+
* app." That's the caller's job, not this module's.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { verifyManifestSignature } from './manifestVerify.js';
|
|
28
|
+
|
|
29
|
+
export interface GenerationEntry {
|
|
30
|
+
gen: number;
|
|
31
|
+
zkAppAddress: string;
|
|
32
|
+
status: 'retired' | 'live';
|
|
33
|
+
frozenRoot?: string;
|
|
34
|
+
deployedAt?: string;
|
|
35
|
+
retiredAt?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface GenerationInfo {
|
|
39
|
+
/** Live-generation index (matches the entry with status: 'live'). Null when unverified or missing. */
|
|
40
|
+
current: number | null;
|
|
41
|
+
generations: GenerationEntry[];
|
|
42
|
+
/** True iff signature verified against one of the pinned pubkeys. */
|
|
43
|
+
verified: boolean;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface FetchGenerationRequest {
|
|
47
|
+
keeperUrl: string;
|
|
48
|
+
network: 'devnet' | 'mainnet';
|
|
49
|
+
appId: string;
|
|
50
|
+
/** Base64-encoded Ed25519 public keys pinned by the caller. Empty ⇒ verified:false. */
|
|
51
|
+
pinnedPublicKeysBase64: readonly string[];
|
|
52
|
+
fetcher?: typeof fetch;
|
|
53
|
+
signal?: AbortSignal;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface FetchGenerationByAddressRequest {
|
|
57
|
+
keeperUrl: string;
|
|
58
|
+
/** Any zkApp address in the app's generation chain — current live or any retired. */
|
|
59
|
+
zkAppAddress: string;
|
|
60
|
+
/** Base64-encoded Ed25519 public keys pinned by the caller. Empty ⇒ verified:false. */
|
|
61
|
+
pinnedPublicKeysBase64: readonly string[];
|
|
62
|
+
fetcher?: typeof fetch;
|
|
63
|
+
signal?: AbortSignal;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function baseUrl(url: string): string {
|
|
67
|
+
return url.replace(/\/+$/, '');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface ParsedGenerationBody {
|
|
71
|
+
current: number | null;
|
|
72
|
+
generations: GenerationEntry[];
|
|
73
|
+
signature: string | null;
|
|
74
|
+
issuedAt: string | null;
|
|
75
|
+
appId: string | null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function parseGenerationBody(body: Record<string, unknown>): ParsedGenerationBody {
|
|
79
|
+
const gensRaw = body.generations;
|
|
80
|
+
return {
|
|
81
|
+
current: typeof body.current === 'number' ? body.current : null,
|
|
82
|
+
generations: Array.isArray(gensRaw) ? gensRaw as GenerationEntry[] : [],
|
|
83
|
+
signature: typeof body.signature === 'string' ? body.signature : null,
|
|
84
|
+
issuedAt: typeof body.issuedAt === 'string' ? body.issuedAt : null,
|
|
85
|
+
appId: typeof body.appId === 'string' ? body.appId : null,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function verifyAndProject(
|
|
90
|
+
parsed: ParsedGenerationBody,
|
|
91
|
+
pinnedPublicKeysBase64: readonly string[],
|
|
92
|
+
): Promise<GenerationInfo> {
|
|
93
|
+
const { current, generations, signature, issuedAt, appId } = parsed;
|
|
94
|
+
if (!signature || !issuedAt || !appId || current === null) {
|
|
95
|
+
return { current, generations, verified: false };
|
|
96
|
+
}
|
|
97
|
+
// Reconstruct the canonical payload — must match keeperService's
|
|
98
|
+
// signPayload input exactly.
|
|
99
|
+
const canonical = { appId, current, generations, issuedAt };
|
|
100
|
+
const verified = await verifyManifestSignature(canonical, signature, pinnedPublicKeysBase64);
|
|
101
|
+
if (!verified) {
|
|
102
|
+
// Never surface unverified `current`/`generations` — a caller must not
|
|
103
|
+
// accidentally route a wallet prompt to an address we couldn't authenticate.
|
|
104
|
+
return { current: null, generations: [], verified: false };
|
|
105
|
+
}
|
|
106
|
+
return { current, generations, verified: true };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* GET /apps/:appId — returns { appId, current, generations, issuedAt, publicKey, signature }.
|
|
111
|
+
* We reconstruct the canonical payload (everything except `publicKey` +
|
|
112
|
+
* `signature`) and verify against the pin list. `publicKey` in the response
|
|
113
|
+
* is advisory only — it's the key the keeper claims to have signed with;
|
|
114
|
+
* the SDK never trusts it in place of a pin.
|
|
115
|
+
*/
|
|
116
|
+
export async function fetchGenerationInfo(req: FetchGenerationRequest): Promise<GenerationInfo> {
|
|
117
|
+
const fetcher = req.fetcher ?? fetch;
|
|
118
|
+
const resp = await fetcher(`${baseUrl(req.keeperUrl)}/apps/${encodeURIComponent(req.appId)}?network=${req.network}`, {
|
|
119
|
+
method: 'GET',
|
|
120
|
+
signal: req.signal,
|
|
121
|
+
});
|
|
122
|
+
if (!resp.ok) {
|
|
123
|
+
return { current: null, generations: [], verified: false };
|
|
124
|
+
}
|
|
125
|
+
let body: Record<string, unknown>;
|
|
126
|
+
try { body = await resp.json() as Record<string, unknown>; }
|
|
127
|
+
catch { return { current: null, generations: [], verified: false }; }
|
|
128
|
+
|
|
129
|
+
return verifyAndProject(parseGenerationBody(body), req.pinnedPublicKeysBase64);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* GET /apps/by-address/:zkAppAddress — same signed payload as fetchGenerationInfo,
|
|
134
|
+
* but keyed by an address the caller already has (direct-paste buys, renew on a
|
|
135
|
+
* since-retired address). Buyers arriving without an appId would otherwise have
|
|
136
|
+
* to trust the keeper's unsigned `/apps` list to bind their address to an appId
|
|
137
|
+
* first — defeating the pin.
|
|
138
|
+
*
|
|
139
|
+
* Extra assertion beyond the appId flow: the queried address MUST appear in the
|
|
140
|
+
* returned `generations[]`. Without this, a malicious keeper could return a
|
|
141
|
+
* validly-signed payload for a DIFFERENT app in response to the query, and the
|
|
142
|
+
* signature check alone wouldn't catch it.
|
|
143
|
+
*/
|
|
144
|
+
export async function fetchGenerationInfoByAddress(
|
|
145
|
+
req: FetchGenerationByAddressRequest,
|
|
146
|
+
): Promise<GenerationInfo> {
|
|
147
|
+
const fetcher = req.fetcher ?? fetch;
|
|
148
|
+
const resp = await fetcher(
|
|
149
|
+
`${baseUrl(req.keeperUrl)}/apps/by-address/${encodeURIComponent(req.zkAppAddress)}`,
|
|
150
|
+
{ method: 'GET', signal: req.signal },
|
|
151
|
+
);
|
|
152
|
+
if (!resp.ok) {
|
|
153
|
+
return { current: null, generations: [], verified: false };
|
|
154
|
+
}
|
|
155
|
+
let body: Record<string, unknown>;
|
|
156
|
+
try { body = await resp.json() as Record<string, unknown>; }
|
|
157
|
+
catch { return { current: null, generations: [], verified: false }; }
|
|
158
|
+
|
|
159
|
+
const projected = await verifyAndProject(parseGenerationBody(body), req.pinnedPublicKeysBase64);
|
|
160
|
+
if (!projected.verified) return projected;
|
|
161
|
+
if (!projected.generations.some(g => g.zkAppAddress === req.zkAppAddress)) {
|
|
162
|
+
return { current: null, generations: [], verified: false };
|
|
163
|
+
}
|
|
164
|
+
return projected;
|
|
165
|
+
}
|