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,538 @@
|
|
|
1
|
+
// Copyright (c) 2025-2026 zkLicensing project developers
|
|
2
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* licenseStore.ts
|
|
6
|
+
*
|
|
7
|
+
* Off-chain MerkleMap state for the licensing system.
|
|
8
|
+
*
|
|
9
|
+
* Records are keyed by (zkAppAddress, licenseHash). Each LicensingApp deploys
|
|
10
|
+
* its own on-chain MerkleMap, so a passphrase used on two different apps
|
|
11
|
+
* produces the same `licenseHash` but two distinct records. Lookups that omit
|
|
12
|
+
* `zkAppAddress` would collide across apps — every API here takes it.
|
|
13
|
+
*
|
|
14
|
+
* Used by:
|
|
15
|
+
* - interact.ts / buyLicense.ts (CLI) — reads/writes directly
|
|
16
|
+
* - keeperService.ts — exposes the same logic over HTTP
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import fs from 'fs/promises';
|
|
20
|
+
import { Bool, Field, MerkleMap, MerkleMapWitness, Poseidon, PublicKey, UInt32, UInt64 } from 'o1js';
|
|
21
|
+
import { GRACE_PERIOD_N, REFUND_WINDOW_N } from './contractInterface.js';
|
|
22
|
+
import { computeDeviceSlotsRoot, DEVICE_SLOT_CAP_N, leafFromRecord, leafHash } from './licenseLeaf.js';
|
|
23
|
+
import { PENDING_REAP_SLOTS as _PENDING_REAP_SLOTS, type LicenseRecord as _LicenseRecord, type LicenseStatus as _LicenseStatus } from './licenseRecord.js';
|
|
24
|
+
|
|
25
|
+
// The record shape and pure types now live in licenseRecord.ts so browser
|
|
26
|
+
// modules (buyClient, statsClient, countryStats) can consume them without
|
|
27
|
+
// importing Node's `fs`. Re-exported here so existing Node imports of
|
|
28
|
+
// `zklicensing/internal/licenseStore` continue to resolve.
|
|
29
|
+
export type LicenseRecord = _LicenseRecord;
|
|
30
|
+
export type LicenseStatus = _LicenseStatus;
|
|
31
|
+
export const PENDING_REAP_SLOTS = _PENDING_REAP_SLOTS;
|
|
32
|
+
|
|
33
|
+
export function licenseStorePath(): string {
|
|
34
|
+
return process.env.LICENSE_STORE_PATH ?? 'licenses.json';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function readRecords(): Promise<LicenseRecord[]> {
|
|
38
|
+
let raw: unknown;
|
|
39
|
+
try {
|
|
40
|
+
raw = JSON.parse(await fs.readFile(licenseStorePath(), 'utf8'));
|
|
41
|
+
} catch {
|
|
42
|
+
return [];
|
|
43
|
+
}
|
|
44
|
+
if (!Array.isArray(raw)) return [];
|
|
45
|
+
const records = raw as LicenseRecord[];
|
|
46
|
+
// Records pre-dating composite keying lack `zkAppAddress` and cannot be
|
|
47
|
+
// safely matched against any specific zkApp. Drop them with a warning so
|
|
48
|
+
// bootstrap rebuilds them fresh from on-chain events.
|
|
49
|
+
const filtered = records.filter(r => typeof r.zkAppAddress === 'string' && r.zkAppAddress.length > 0);
|
|
50
|
+
if (filtered.length < records.length) {
|
|
51
|
+
console.warn(`[licenseStore] dropped ${records.length - filtered.length} record(s) missing zkAppAddress — re-bootstrap to recover`);
|
|
52
|
+
}
|
|
53
|
+
return filtered;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function writeRecords(records: LicenseRecord[]): Promise<void> {
|
|
57
|
+
await fs.writeFile(licenseStorePath(), JSON.stringify(records, null, 2));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Serialize all read-modify-write operations against licenses.json. Each
|
|
61
|
+
// mutating function does (readRecords → mutate → writeRecords); without a lock,
|
|
62
|
+
// two concurrent calls can interleave such that the second one's read predates
|
|
63
|
+
// the first one's write, and the second one's write then clobbers the first.
|
|
64
|
+
// This was visible during archive sync (applyEventsToStore fires many writes
|
|
65
|
+
// back-to-back) racing with /confirm/* writes from buyer flows.
|
|
66
|
+
let writeChain: Promise<void> = Promise.resolve();
|
|
67
|
+
function withWriteLock<T>(fn: () => Promise<T>): Promise<T> {
|
|
68
|
+
const result = writeChain.then(fn, fn);
|
|
69
|
+
writeChain = result.then(() => {}, () => {});
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Records belonging to a specific zkApp. Each zkApp owns an independent
|
|
74
|
+
// on-chain MerkleMap, so all map operations must filter first.
|
|
75
|
+
function recordsForApp(records: LicenseRecord[], zkAppAddress: string): LicenseRecord[] {
|
|
76
|
+
return records.filter(r => r.zkAppAddress === zkAppAddress);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Rebuild the license MerkleMap for a single zkApp. Only inserts entries
|
|
80
|
+
// with expirySlot > 0. The value stored at each key is `leaf.hash()` — the
|
|
81
|
+
// Poseidon commitment over (licenseHash, expirySlot, cap, deviceSlotsRoot,
|
|
82
|
+
// deviceSlotsFilled) — matching what LicensingApp writes. Records that
|
|
83
|
+
// predate device binding rebuild to a leaf with empty slots (see
|
|
84
|
+
// leafFromRecord for the exact defaults); on those records the rebuilt
|
|
85
|
+
// root matches what the old contract wrote, but any mutation call will
|
|
86
|
+
// fail the in-circuit hash check until the missing fields are backfilled
|
|
87
|
+
// from chain events.
|
|
88
|
+
export function buildMap(records: LicenseRecord[], zkAppAddress: string): MerkleMap {
|
|
89
|
+
const map = new MerkleMap();
|
|
90
|
+
for (const r of recordsForApp(records, zkAppAddress)) {
|
|
91
|
+
if (r.expirySlot !== 0) {
|
|
92
|
+
map.set(Field(r.licenseHash), leafHash(leafFromRecord(r)));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return map;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Rebuild the escrow MerkleMap for a single zkApp:
|
|
99
|
+
// licenseHash → escrowCommitment(amount, slot, buyerKey). Only includes
|
|
100
|
+
// entries with live escrow (not released, not refunded) and a known buyer.
|
|
101
|
+
export function buildEscrowMap(records: LicenseRecord[], zkAppAddress: string): MerkleMap {
|
|
102
|
+
const map = new MerkleMap();
|
|
103
|
+
for (const r of recordsForApp(records, zkAppAddress)) {
|
|
104
|
+
if (!r.released && !r.refunded && r.purchaseSlot > 0 && r.buyerAddress) {
|
|
105
|
+
const buyerKey = PublicKey.fromBase58(r.buyerAddress);
|
|
106
|
+
const commitment = Poseidon.hash([
|
|
107
|
+
UInt64.from(BigInt(r.purchaseAmount)).value,
|
|
108
|
+
UInt32.from(r.purchaseSlot).value,
|
|
109
|
+
buyerKey.x,
|
|
110
|
+
buyerKey.isOdd.toField(),
|
|
111
|
+
]);
|
|
112
|
+
map.set(Field(r.licenseHash), commitment);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return map;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Serialize a MerkleMapWitness to plain JSON (safe to send over HTTP).
|
|
119
|
+
export function serializeWitness(witness: MerkleMapWitness): {
|
|
120
|
+
isLefts: boolean[];
|
|
121
|
+
siblings: string[];
|
|
122
|
+
} {
|
|
123
|
+
return {
|
|
124
|
+
isLefts: witness.isLefts.map((b) => b.toBoolean()),
|
|
125
|
+
siblings: witness.siblings.map((f) => f.toString()),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Reconstruct a MerkleMapWitness from serialized JSON.
|
|
130
|
+
export function deserializeWitness(json: {
|
|
131
|
+
isLefts: boolean[];
|
|
132
|
+
siblings: string[];
|
|
133
|
+
}): MerkleMapWitness {
|
|
134
|
+
return new MerkleMapWitness(
|
|
135
|
+
json.isLefts.map((b: boolean) => Bool(b)),
|
|
136
|
+
json.siblings.map((s: string) => Field(s))
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Returns the witness for a licenseHash key in the given zkApp's map.
|
|
141
|
+
export async function getWitness(zkAppAddress: string, licenseHash: string): Promise<{
|
|
142
|
+
root: string;
|
|
143
|
+
currentValue: string;
|
|
144
|
+
witness: MerkleMapWitness;
|
|
145
|
+
serialized: ReturnType<typeof serializeWitness>;
|
|
146
|
+
}> {
|
|
147
|
+
const records = await readRecords();
|
|
148
|
+
const map = buildMap(records, zkAppAddress);
|
|
149
|
+
const key = Field(licenseHash);
|
|
150
|
+
const witness = map.getWitness(key);
|
|
151
|
+
return {
|
|
152
|
+
root: map.getRoot().toString(),
|
|
153
|
+
currentValue: map.get(key).toString(),
|
|
154
|
+
witness,
|
|
155
|
+
serialized: serializeWitness(witness),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Look up a single license record by its composite key.
|
|
160
|
+
export async function getLicense(zkAppAddress: string, licenseHash: string): Promise<LicenseRecord | null> {
|
|
161
|
+
const records = await readRecords();
|
|
162
|
+
return records.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash) ?? null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Determine the status of a license. A license in the 7-day grace window is
|
|
166
|
+
// still considered 'active' so renewal is not urgently forced.
|
|
167
|
+
export function licenseStatus(record: LicenseRecord | null, currentSlot: number): LicenseStatus {
|
|
168
|
+
if (!record) return 'unknown';
|
|
169
|
+
if (record.expirySlot === 0) return 'refunded';
|
|
170
|
+
if (record.expirySlot + GRACE_PERIOD_N < currentSlot) return 'expired';
|
|
171
|
+
return 'active';
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Add or update a license record (upsert by composite key).
|
|
175
|
+
export async function upsertLicense(record: LicenseRecord): Promise<void> {
|
|
176
|
+
if (!record.zkAppAddress) {
|
|
177
|
+
throw new Error('upsertLicense: record.zkAppAddress is required');
|
|
178
|
+
}
|
|
179
|
+
// Populate the empty-slot mirror at insert time when the license is capped.
|
|
180
|
+
// Without this, /confirm/buy writes deviceCap:N but leaves deviceSlotsRoot
|
|
181
|
+
// and deviceSlotsFilled undefined until the first bind — leafFromRecord's
|
|
182
|
+
// fallbacks paper over it for hash reconstruction, but every consumer that
|
|
183
|
+
// reads the mirror directly (preflight logs, /license responses, offline
|
|
184
|
+
// verify) would see undefined and either misreport or need its own fallback.
|
|
185
|
+
if ((record.deviceCap ?? 0) > 0 && (record.deviceSlotsRoot === undefined || record.deviceSlotsFilled === undefined)) {
|
|
186
|
+
refreshSlotMirror(record);
|
|
187
|
+
}
|
|
188
|
+
return withWriteLock(async () => {
|
|
189
|
+
const records = await readRecords();
|
|
190
|
+
const idx = records.findIndex(r => r.zkAppAddress === record.zkAppAddress && r.licenseHash === record.licenseHash);
|
|
191
|
+
if (idx >= 0) {
|
|
192
|
+
records[idx] = record;
|
|
193
|
+
} else {
|
|
194
|
+
records.push(record);
|
|
195
|
+
}
|
|
196
|
+
await writeRecords(records);
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Update the expirySlot for an existing record (used by renew).
|
|
201
|
+
// `opts.markRenewed` flips renewedAtLeastOnce so stats can detect first-renewal
|
|
202
|
+
// without re-walking events. `opts.renewal` appends to the renewals[] log so
|
|
203
|
+
// stats can compute renewal revenue from the store alone.
|
|
204
|
+
export async function updateExpiry(
|
|
205
|
+
zkAppAddress: string,
|
|
206
|
+
licenseHash: string,
|
|
207
|
+
expirySlot: number,
|
|
208
|
+
opts: { markRenewed?: boolean; renewal?: { slot: number; amount: string; newExpiry: number; txHash?: string } } = {},
|
|
209
|
+
): Promise<boolean> {
|
|
210
|
+
return withWriteLock(async () => {
|
|
211
|
+
const records = await readRecords();
|
|
212
|
+
const record = records.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash);
|
|
213
|
+
if (!record) return false;
|
|
214
|
+
record.expirySlot = expirySlot;
|
|
215
|
+
if (opts.markRenewed) record.renewedAtLeastOnce = true;
|
|
216
|
+
if (opts.renewal) {
|
|
217
|
+
const renewals = (record.renewals ??= []);
|
|
218
|
+
// Dedup by newExpiry — confirm-time and event-sync may both try to log
|
|
219
|
+
// the same renewal, but each renewal advances expiry by a unique tier
|
|
220
|
+
// amount, so newExpiry is a stable identifier.
|
|
221
|
+
if (!renewals.some(r => r.newExpiry === opts.renewal!.newExpiry)) {
|
|
222
|
+
renewals.push(opts.renewal);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
await writeRecords(records);
|
|
226
|
+
return true;
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Clear license and escrow data after a confirmed refund. Also flips `refunded`.
|
|
231
|
+
export async function recordRefund(zkAppAddress: string, licenseHash: string): Promise<boolean> {
|
|
232
|
+
return withWriteLock(async () => {
|
|
233
|
+
const records = await readRecords();
|
|
234
|
+
const record = records.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash);
|
|
235
|
+
if (!record) return false;
|
|
236
|
+
record.expirySlot = 0;
|
|
237
|
+
record.purchaseSlot = 0;
|
|
238
|
+
record.purchaseAmount = '0';
|
|
239
|
+
record.refunded = true;
|
|
240
|
+
// Same pending-clear the buy/renew apply* siblings do — /confirm/refund
|
|
241
|
+
// wrote pending:true optimistically; the on-chain event landing is what
|
|
242
|
+
// authorizes clearing it. Without this the SDK poller (which requires
|
|
243
|
+
// pending===false && status==='refunded') hangs forever.
|
|
244
|
+
delete record.pending;
|
|
245
|
+
delete record.provedAtSlot;
|
|
246
|
+
await writeRecords(records);
|
|
247
|
+
return true;
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Mark escrow as released. Preserves purchaseAmount/purchaseSlot so stats can
|
|
252
|
+
// compute released revenue. The `released` flag is the truth signal —
|
|
253
|
+
// buildEscrowMap and getReleasableRecords filter on it directly.
|
|
254
|
+
export async function recordRelease(
|
|
255
|
+
zkAppAddress: string,
|
|
256
|
+
licenseHash: string,
|
|
257
|
+
releaseSlot?: number,
|
|
258
|
+
txHash?: string,
|
|
259
|
+
): Promise<boolean> {
|
|
260
|
+
return withWriteLock(async () => {
|
|
261
|
+
const records = await readRecords();
|
|
262
|
+
const record = records.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash);
|
|
263
|
+
if (!record) return false;
|
|
264
|
+
record.released = true;
|
|
265
|
+
if (releaseSlot !== undefined) record.releaseSlot = releaseSlot;
|
|
266
|
+
if (txHash !== undefined) record.releaseTxHash = txHash;
|
|
267
|
+
await writeRecords(records);
|
|
268
|
+
return true;
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Clear the pending flag on a record after a chain event confirms it landed.
|
|
273
|
+
export async function confirmRecord(zkAppAddress: string, licenseHash: string): Promise<boolean> {
|
|
274
|
+
return withWriteLock(async () => {
|
|
275
|
+
const records = await readRecords();
|
|
276
|
+
const record = records.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash);
|
|
277
|
+
if (!record) return false;
|
|
278
|
+
if (!record.pending) return false;
|
|
279
|
+
delete record.pending;
|
|
280
|
+
delete record.provedAtSlot;
|
|
281
|
+
await writeRecords(records);
|
|
282
|
+
return true;
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Apply a licenseIssued event atomically: confirm any pending /confirm/buy
|
|
287
|
+
// write, backfill initialExpirySlot/tier if missing, or create a fresh record.
|
|
288
|
+
// Doing the whole read-decide-write inside a single lock acquisition avoids the
|
|
289
|
+
// stale-snapshot hazard that would arise if archiveBootstrap called
|
|
290
|
+
// getLicense + confirmRecord + upsertLicense as three separate locked steps —
|
|
291
|
+
// a concurrent write between them could be clobbered by the upsert's
|
|
292
|
+
// pre-confirm snapshot.
|
|
293
|
+
export async function applyLicenseIssued(
|
|
294
|
+
zkAppAddress: string,
|
|
295
|
+
licenseHash: string,
|
|
296
|
+
fields: {
|
|
297
|
+
expirySlot: number;
|
|
298
|
+
purchaseSlot: number;
|
|
299
|
+
purchaseAmount: string;
|
|
300
|
+
tier?: 'monthly' | 'yearly' | 'fiveYear' | 'perpetual';
|
|
301
|
+
// True for licenses minted through buyLicenseNoEscrow: funds went straight
|
|
302
|
+
// to vendor + platform, no escrow entry. Refund CTA must be suppressed.
|
|
303
|
+
escrowless?: boolean;
|
|
304
|
+
// Leaf fields carried by LicenseIssuedEvent so a record rehydrated purely
|
|
305
|
+
// from archive replay (no prior /confirm/buy) reconstructs the exact leaf
|
|
306
|
+
// hash the circuit committed. Optional so pre-event-extension replays
|
|
307
|
+
// (which never carried them) still bootstrap — those records will fail
|
|
308
|
+
// in-circuit hash checks on the next mutation, matching prior behavior.
|
|
309
|
+
// No ownerPubKeyHash field: the leaf's owner-pubkey commitment IS
|
|
310
|
+
// `licenseHash` itself (buyLicense asserts them equal), already the key
|
|
311
|
+
// this function is called with.
|
|
312
|
+
deviceCap?: number;
|
|
313
|
+
deviceSlotsRoot?: string;
|
|
314
|
+
deviceSlotsFilled?: number;
|
|
315
|
+
},
|
|
316
|
+
): Promise<void> {
|
|
317
|
+
return withWriteLock(async () => {
|
|
318
|
+
const records = await readRecords();
|
|
319
|
+
const record = records.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash);
|
|
320
|
+
let dirty = false;
|
|
321
|
+
if (record) {
|
|
322
|
+
if (record.pending) {
|
|
323
|
+
delete record.pending;
|
|
324
|
+
delete record.provedAtSlot;
|
|
325
|
+
dirty = true;
|
|
326
|
+
}
|
|
327
|
+
if (record.initialExpirySlot === undefined) {
|
|
328
|
+
record.initialExpirySlot = fields.expirySlot;
|
|
329
|
+
dirty = true;
|
|
330
|
+
}
|
|
331
|
+
if (!record.tier && fields.tier) {
|
|
332
|
+
record.tier = fields.tier;
|
|
333
|
+
dirty = true;
|
|
334
|
+
}
|
|
335
|
+
if (fields.escrowless === true && record.escrowless !== true) {
|
|
336
|
+
record.escrowless = true;
|
|
337
|
+
dirty = true;
|
|
338
|
+
}
|
|
339
|
+
// Backfill leaf fields if the record was created before the event
|
|
340
|
+
// carried them, or if a prior partial rehydrate is still missing them.
|
|
341
|
+
if (fields.deviceCap !== undefined && record.deviceCap === undefined) {
|
|
342
|
+
record.deviceCap = fields.deviceCap;
|
|
343
|
+
dirty = true;
|
|
344
|
+
}
|
|
345
|
+
if (fields.deviceSlotsRoot !== undefined && record.deviceSlotsRoot === undefined) {
|
|
346
|
+
record.deviceSlotsRoot = fields.deviceSlotsRoot;
|
|
347
|
+
dirty = true;
|
|
348
|
+
}
|
|
349
|
+
if (fields.deviceSlotsFilled !== undefined && record.deviceSlotsFilled === undefined) {
|
|
350
|
+
record.deviceSlotsFilled = fields.deviceSlotsFilled;
|
|
351
|
+
dirty = true;
|
|
352
|
+
}
|
|
353
|
+
} else {
|
|
354
|
+
const inserted: LicenseRecord = {
|
|
355
|
+
zkAppAddress,
|
|
356
|
+
licenseHash,
|
|
357
|
+
expirySlot: fields.expirySlot,
|
|
358
|
+
purchaseSlot: fields.purchaseSlot,
|
|
359
|
+
purchaseAmount: fields.purchaseAmount,
|
|
360
|
+
txHash: '',
|
|
361
|
+
createdAt: new Date().toISOString(),
|
|
362
|
+
initialExpirySlot: fields.expirySlot,
|
|
363
|
+
...(fields.tier ? { tier: fields.tier } : {}),
|
|
364
|
+
...(fields.escrowless === true ? { escrowless: true } : {}),
|
|
365
|
+
...(fields.deviceCap !== undefined ? { deviceCap: fields.deviceCap } : {}),
|
|
366
|
+
...(fields.deviceSlotsRoot !== undefined ? { deviceSlotsRoot: fields.deviceSlotsRoot } : {}),
|
|
367
|
+
...(fields.deviceSlotsFilled !== undefined ? { deviceSlotsFilled: fields.deviceSlotsFilled } : {}),
|
|
368
|
+
};
|
|
369
|
+
// Same rationale as upsertLicense: populate the empty-slot mirror on
|
|
370
|
+
// first insert so the record is immediately queryable without relying
|
|
371
|
+
// on leafFromRecord's undefined fallbacks.
|
|
372
|
+
if ((inserted.deviceCap ?? 0) > 0 && (inserted.deviceSlotsRoot === undefined || inserted.deviceSlotsFilled === undefined)) {
|
|
373
|
+
refreshSlotMirror(inserted);
|
|
374
|
+
}
|
|
375
|
+
records.push(inserted);
|
|
376
|
+
dirty = true;
|
|
377
|
+
}
|
|
378
|
+
if (dirty) await writeRecords(records);
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Apply a licenseRenewed event atomically: clear any pending /confirm/renew
|
|
383
|
+
// write, align expirySlot with the event, and flip renewedAtLeastOnce.
|
|
384
|
+
// Symmetric to applyLicenseIssued — the archive-events path is what closes
|
|
385
|
+
// out a renew that the bestChain sweep missed (tx landed after the sweep's
|
|
386
|
+
// BESTCHAIN_DEPTH window rolled past), and without a pending-clear step here
|
|
387
|
+
// the flag on a landed record could be stuck forever.
|
|
388
|
+
//
|
|
389
|
+
// Does NOT append to renewals[] — that log is populated at /confirm/renew
|
|
390
|
+
// time from the intent (which carries amount + txHash); the archive event
|
|
391
|
+
// carries only newExpiry, so replaying it must not overwrite the richer
|
|
392
|
+
// confirm-time entry.
|
|
393
|
+
export async function applyLicenseRenewed(
|
|
394
|
+
zkAppAddress: string,
|
|
395
|
+
licenseHash: string,
|
|
396
|
+
fields: { newExpiry: number },
|
|
397
|
+
): Promise<boolean> {
|
|
398
|
+
return withWriteLock(async () => {
|
|
399
|
+
const records = await readRecords();
|
|
400
|
+
const record = records.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash);
|
|
401
|
+
if (!record) return false;
|
|
402
|
+
let dirty = false;
|
|
403
|
+
if (record.pending) {
|
|
404
|
+
delete record.pending;
|
|
405
|
+
delete record.provedAtSlot;
|
|
406
|
+
dirty = true;
|
|
407
|
+
}
|
|
408
|
+
if (record.expirySlot !== fields.newExpiry) {
|
|
409
|
+
record.expirySlot = fields.newExpiry;
|
|
410
|
+
dirty = true;
|
|
411
|
+
}
|
|
412
|
+
if (!record.renewedAtLeastOnce) {
|
|
413
|
+
record.renewedAtLeastOnce = true;
|
|
414
|
+
dirty = true;
|
|
415
|
+
}
|
|
416
|
+
if (dirty) await writeRecords(records);
|
|
417
|
+
return true;
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Recompute deviceSlotsRoot + deviceSlotsFilled from the record's mirror after
|
|
422
|
+
// a bind/unbind mutation. `leafFromRecord` uses those two persisted fields when
|
|
423
|
+
// building the on-chain leaf hash; if they drift from the on-chain state the
|
|
424
|
+
// next mutation call fails the in-circuit leaf-hash assert. Mirror the exact
|
|
425
|
+
// packing the circuit uses (packSlotTimes: freedAt in low 32 bits, boundAt in
|
|
426
|
+
// high 32) so the fold matches the on-chain deviceSlotsRoot bit-for-bit.
|
|
427
|
+
function refreshSlotMirror(record: LicenseRecord): void {
|
|
428
|
+
const devices = record.devices ?? [];
|
|
429
|
+
const occupied: Field[] = [];
|
|
430
|
+
const freedAt: Field[] = [];
|
|
431
|
+
for (let i = 0; i < DEVICE_SLOT_CAP_N; i++) {
|
|
432
|
+
const entry = devices.find(d => d.slotIndex === i);
|
|
433
|
+
const occ = entry?.deviceCommitment ?? '0';
|
|
434
|
+
occupied.push(Field(occ));
|
|
435
|
+
const boundAt = BigInt(entry?.boundAtSlot ?? 0);
|
|
436
|
+
const freed = BigInt(entry?.freedAtSlot ?? 0);
|
|
437
|
+
// packSlotTimes(boundAt, freedAt) in licenseLeaf.ts: freedAt low 32, boundAt high 32.
|
|
438
|
+
const packed = freed + (boundAt << 32n);
|
|
439
|
+
freedAt.push(Field(packed));
|
|
440
|
+
}
|
|
441
|
+
record.deviceSlotsRoot = computeDeviceSlotsRoot(occupied, freedAt).toString();
|
|
442
|
+
record.deviceSlotsFilled = devices.filter(d => d.deviceCommitment !== '0').length;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// Apply a deviceBound event atomically: mirrors the on-chain slot mutation
|
|
446
|
+
// into the record.devices[] array and recomputes deviceSlotsRoot / filled so
|
|
447
|
+
// leafFromRecord reconstructs the exact leaf hash the chain committed.
|
|
448
|
+
//
|
|
449
|
+
// `boundAtSlot` MUST be the circuit's proof-time `globalSlotSinceGenesis` (the
|
|
450
|
+
// value emitted in `DeviceBoundEvent.boundAtSlot`). The block slot when the tx
|
|
451
|
+
// landed is NOT interchangeable: TOLERANCE_WINDOW allows them to differ, and
|
|
452
|
+
// any drift flips the packed `freedAt` field → wrong leaf → root divergence.
|
|
453
|
+
export async function applyDeviceBound(
|
|
454
|
+
zkAppAddress: string,
|
|
455
|
+
licenseHash: string,
|
|
456
|
+
fields: { slotIndex: number; deviceCommitment: string; boundAtSlot: number },
|
|
457
|
+
): Promise<boolean> {
|
|
458
|
+
return withWriteLock(async () => {
|
|
459
|
+
const records = await readRecords();
|
|
460
|
+
const record = records.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash);
|
|
461
|
+
if (!record) return false;
|
|
462
|
+
const devices = (record.devices ??= []);
|
|
463
|
+
// Ensure the array is long enough — pad with empty slots.
|
|
464
|
+
while (devices.length <= fields.slotIndex) {
|
|
465
|
+
devices.push({ slotIndex: devices.length, deviceCommitment: '0', boundAtSlot: 0, freedAtSlot: 0 });
|
|
466
|
+
}
|
|
467
|
+
devices[fields.slotIndex] = {
|
|
468
|
+
slotIndex: fields.slotIndex,
|
|
469
|
+
deviceCommitment: fields.deviceCommitment,
|
|
470
|
+
boundAtSlot: fields.boundAtSlot,
|
|
471
|
+
freedAtSlot: 0, // pristine → fresh bind resets freedAt
|
|
472
|
+
};
|
|
473
|
+
refreshSlotMirror(record);
|
|
474
|
+
await writeRecords(records);
|
|
475
|
+
return true;
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// Apply a deviceUnbound event atomically. Preserves boundAtSlot for audit,
|
|
480
|
+
// stamps freedAtSlot for the cooldown timer the circuit's next bind enforces.
|
|
481
|
+
//
|
|
482
|
+
// `freedAtSlot` MUST be the circuit's proof-time `globalSlotSinceGenesis` (the
|
|
483
|
+
// value emitted in `DeviceUnboundEvent.freedAtSlot`). Same reason as
|
|
484
|
+
// `applyDeviceBound.boundAtSlot`.
|
|
485
|
+
export async function applyDeviceUnbound(
|
|
486
|
+
zkAppAddress: string,
|
|
487
|
+
licenseHash: string,
|
|
488
|
+
fields: { slotIndex: number; freedAtSlot: number },
|
|
489
|
+
): Promise<boolean> {
|
|
490
|
+
return withWriteLock(async () => {
|
|
491
|
+
const records = await readRecords();
|
|
492
|
+
const record = records.find(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash);
|
|
493
|
+
if (!record || !record.devices) return false;
|
|
494
|
+
const slot = record.devices.find(d => d.slotIndex === fields.slotIndex);
|
|
495
|
+
if (!slot) return false;
|
|
496
|
+
slot.deviceCommitment = '0';
|
|
497
|
+
slot.freedAtSlot = fields.freedAtSlot;
|
|
498
|
+
// boundAtSlot stays as the last bind time — historical / audit.
|
|
499
|
+
refreshSlotMirror(record);
|
|
500
|
+
await writeRecords(records);
|
|
501
|
+
return true;
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// Delete a record entirely (used to reap stale pending entries the buyer never submitted).
|
|
506
|
+
export async function deleteRecord(zkAppAddress: string, licenseHash: string): Promise<boolean> {
|
|
507
|
+
return withWriteLock(async () => {
|
|
508
|
+
const records = await readRecords();
|
|
509
|
+
const idx = records.findIndex(r => r.zkAppAddress === zkAppAddress && r.licenseHash === licenseHash);
|
|
510
|
+
if (idx < 0) return false;
|
|
511
|
+
records.splice(idx, 1);
|
|
512
|
+
await writeRecords(records);
|
|
513
|
+
return true;
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// List pending records whose prove slot is older than `currentSlot - maxAgeSlots`.
|
|
518
|
+
// Used by the reaper to drop records the buyer never actually signed/submitted.
|
|
519
|
+
export async function getStalePendingRecords(currentSlot: number, maxAgeSlots = PENDING_REAP_SLOTS): Promise<LicenseRecord[]> {
|
|
520
|
+
const records = await readRecords();
|
|
521
|
+
return records.filter(
|
|
522
|
+
(r) => r.pending && typeof r.provedAtSlot === 'number' && currentSlot - r.provedAtSlot > maxAgeSlots,
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// Return all records where the refund window has passed and escrow is still live.
|
|
527
|
+
// Filters on the released/refunded flags so we don't re-release or release after refund.
|
|
528
|
+
export async function getReleasableRecords(currentSlot: number): Promise<LicenseRecord[]> {
|
|
529
|
+
const records = await readRecords();
|
|
530
|
+
return records.filter(
|
|
531
|
+
(r) =>
|
|
532
|
+
!r.released &&
|
|
533
|
+
!r.refunded &&
|
|
534
|
+
r.purchaseSlot > 0 &&
|
|
535
|
+
r.zkAppAddress &&
|
|
536
|
+
currentSlot > r.purchaseSlot + REFUND_WINDOW_N,
|
|
537
|
+
);
|
|
538
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Copyright (c) 2025-2026 zkLicensing project developers
|
|
2
|
+
// SPDX-License-Identifier: BUSL-1.1
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* manifestVerify.ts
|
|
6
|
+
*
|
|
7
|
+
* Browser + Node Ed25519 signature verification for platform-signed manifests
|
|
8
|
+
* (currently: the generation-list served at GET /apps/:appId, next: the
|
|
9
|
+
* sales-freeze manifest). The keeper signs with the platform manifest key
|
|
10
|
+
* loaded via PLATFORM_MANIFEST_KEY_FILE; the SDK pins the public key against
|
|
11
|
+
* a caller-supplied allow-list and verifies before trusting anything.
|
|
12
|
+
*
|
|
13
|
+
* Runtime: browsers and Node ≥ 20 expose `globalThis.crypto.subtle`. The
|
|
14
|
+
* SDK's `engines.node` is `>=20` for this reason — Node 18 child workers
|
|
15
|
+
* (spawned by `node --test`) do not populate `globalThis.crypto`.
|
|
16
|
+
*
|
|
17
|
+
* Canonicalization must match `src/manifestSign.ts` byte-for-byte:
|
|
18
|
+
* - sorted object keys
|
|
19
|
+
* - no whitespace
|
|
20
|
+
* - arrays preserved in order
|
|
21
|
+
* Any divergence silently breaks verification, so keep the algorithm dead
|
|
22
|
+
* simple and mirrored.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
// Canonical JSON: sorted keys, no whitespace, arrays preserved in order.
|
|
26
|
+
// Undefined values are skipped, mirroring JSON.stringify — otherwise the
|
|
27
|
+
// signed bytes would contain `"key":undefined` for optional fields left
|
|
28
|
+
// unset, while `res.json()` on the wire would strip them, and the signature
|
|
29
|
+
// would never verify.
|
|
30
|
+
// Mirror of src/manifestSign.ts:canonicalize. Divergence here silently
|
|
31
|
+
// breaks verification.
|
|
32
|
+
export function canonicalize(value: unknown): string {
|
|
33
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
|
34
|
+
if (Array.isArray(value)) return '[' + value.map(canonicalize).join(',') + ']';
|
|
35
|
+
const obj = value as Record<string, unknown>;
|
|
36
|
+
const keys = Object.keys(obj).filter(k => obj[k] !== undefined).sort();
|
|
37
|
+
return '{' + keys.map(k =>
|
|
38
|
+
JSON.stringify(k) + ':' + canonicalize(obj[k])
|
|
39
|
+
).join(',') + '}';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function base64ToBytes(b64: string): Uint8Array {
|
|
43
|
+
// atob is present in every modern JS runtime we target (browser + Node ≥ 16).
|
|
44
|
+
const bin = atob(b64);
|
|
45
|
+
const out = new Uint8Array(bin.length);
|
|
46
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function utf8Bytes(s: string): Uint8Array {
|
|
51
|
+
return new TextEncoder().encode(s);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// SPKI DER wrapper around a raw 32-byte Ed25519 public key.
|
|
55
|
+
// Same prefix used by src/manifestSign.ts:verifyPayload — WebCrypto needs
|
|
56
|
+
// SPKI to import; the wire format is raw base64 for space.
|
|
57
|
+
const ED25519_SPKI_PREFIX = new Uint8Array([
|
|
58
|
+
0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
|
|
59
|
+
]);
|
|
60
|
+
|
|
61
|
+
function rawEd25519ToSpki(raw: Uint8Array): Uint8Array {
|
|
62
|
+
if (raw.length !== 32) throw new Error(`Ed25519 pubkey must be 32 bytes, got ${raw.length}`);
|
|
63
|
+
const out = new Uint8Array(ED25519_SPKI_PREFIX.length + raw.length);
|
|
64
|
+
out.set(ED25519_SPKI_PREFIX, 0);
|
|
65
|
+
out.set(raw, ED25519_SPKI_PREFIX.length);
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Verify a base64 Ed25519 signature over a canonicalized payload against
|
|
71
|
+
* one of the pinned base64 public keys. Returns true iff at least one
|
|
72
|
+
* pinned key verifies. Fails closed on any error (unknown key format,
|
|
73
|
+
* WebCrypto rejection, missing subtle) — callers must interpret `false`
|
|
74
|
+
* as "do not trust."
|
|
75
|
+
*/
|
|
76
|
+
export async function verifyManifestSignature(
|
|
77
|
+
payload: unknown,
|
|
78
|
+
signatureBase64: string,
|
|
79
|
+
pinnedPublicKeysBase64: readonly string[],
|
|
80
|
+
): Promise<boolean> {
|
|
81
|
+
if (!pinnedPublicKeysBase64.length) return false;
|
|
82
|
+
const subtle = (globalThis.crypto as Crypto | undefined)?.subtle;
|
|
83
|
+
if (!subtle) return false;
|
|
84
|
+
const messageBytes = utf8Bytes(canonicalize(payload));
|
|
85
|
+
let signatureBytes: Uint8Array;
|
|
86
|
+
try { signatureBytes = base64ToBytes(signatureBase64); }
|
|
87
|
+
catch { return false; }
|
|
88
|
+
for (const pinB64 of pinnedPublicKeysBase64) {
|
|
89
|
+
try {
|
|
90
|
+
const spki = rawEd25519ToSpki(base64ToBytes(pinB64));
|
|
91
|
+
const key = await subtle.importKey(
|
|
92
|
+
'spki',
|
|
93
|
+
spki as unknown as ArrayBuffer,
|
|
94
|
+
{ name: 'Ed25519' },
|
|
95
|
+
false,
|
|
96
|
+
['verify'],
|
|
97
|
+
);
|
|
98
|
+
const ok = await subtle.verify(
|
|
99
|
+
{ name: 'Ed25519' },
|
|
100
|
+
key,
|
|
101
|
+
signatureBytes as unknown as ArrayBuffer,
|
|
102
|
+
messageBytes as unknown as ArrayBuffer,
|
|
103
|
+
);
|
|
104
|
+
if (ok) return true;
|
|
105
|
+
} catch {
|
|
106
|
+
// Try the next pin — one bad entry in the pin list must not mask
|
|
107
|
+
// a valid signature under a different pin.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return false;
|
|
111
|
+
}
|