@outpost-protocol/core 0.2.0 → 0.3.0

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.
@@ -0,0 +1,794 @@
1
+ /**
2
+ * High-Level Outpost v2 Hardware Roaming Wallet & Gateway SDK (`@outpost-protocol/core`).
3
+ *
4
+ * Provides:
5
+ * - `HwGatewayClient`: Bounded HTTP client for `GET /health`, `POST /v2/hw-attest` (`preview` & `cert`),
6
+ * and `POST /v2/settle/hw` (accepting `SMESHH1` strings or `{ cert, entry }`).
7
+ * - `HwPocketSession`: Stateful, serializable offline pocket manager for mobile apps (iOS Secure Enclave
8
+ * & Android KeyMint/StrongBox) with non-zero `(recipient, orderId)` retry deduplication, safe `SREQ1`
9
+ * tip capping, pre-mutation P-256 verification, and 1-call QR/UR:SMESH/BLE encoding.
10
+ */
11
+ import * as StellarSdk from "@stellar/stellar-sdk";
12
+ import { buildDepositHwOp } from "./contracts.js";
13
+ import { assertBytesLength, MAX_U64, verifyEd25519 } from "./digest.js";
14
+ import { computeHwAttestationChallenge, computeHwGenesisDigest, computeHwIntentDigest, encodeSmeshh1, HW_KIND_ANDROID_KEYMINT_MERKLE, HW_KIND_IOS_APP_ATTEST, HW_MIN_EXIT_DELAY_SECS, hwGenesisCertFromDto, hwGenesisCertToDto, hwPaymentEntryFromDto, hwPaymentEntryToDto, hwProofToDto, normalizeP256DerToLowS64, verifyAndroidKeyMintProof, verifyIosAppAttestProof, } from "./hw.js";
15
+ import { encodeBleHwPaymentChunks, encodeSmeshh1ForQr, } from "./hwTransport.js";
16
+ import { DEFAULT_MAX_TIP_BPS, DEFAULT_SAFETY_MARGIN_SECS, MAX_INTENT_TTL_LEDGERS, MAX_INTENT_TTL_SECS, } from "./wallet.js";
17
+ import { bytesToHex, hexToBytes } from "./witnessClient.js";
18
+ import { assertNetworkHint, assertNotMuxedStrKey, bytesEqual, defaultTokenResolver, networkIdFromPassphrase, networkPassphraseForHint, strKeyToWireAddress, wireAddressToStrKey, } from "./xdr.js";
19
+ const DEFAULT_HW_GATEWAY_TIMEOUT_MS = 15_000;
20
+ const MAX_HW_GATEWAY_RESPONSE_BYTES = 1_048_576;
21
+ const utf8Decoder = new TextDecoder("utf-8", { fatal: false });
22
+ const utf8Encoder = new TextEncoder();
23
+ export class HwGatewayError extends Error {
24
+ status;
25
+ code;
26
+ details;
27
+ constructor(status, code, message, details) {
28
+ super(message);
29
+ this.name = "HwGatewayError";
30
+ this.status = status;
31
+ this.code = code;
32
+ this.details = details;
33
+ }
34
+ }
35
+ async function readBoundedText(res, maxBytes) {
36
+ const cl = res.headers?.get?.("content-length");
37
+ if (cl !== null && cl !== undefined) {
38
+ const n = Number(cl.trim());
39
+ if (Number.isFinite(n) && n > maxBytes) {
40
+ try {
41
+ await res.body?.cancel();
42
+ }
43
+ catch {
44
+ // ignore cancel error
45
+ }
46
+ throw new HwGatewayError(502, "RESPONSE_TOO_LARGE", `Gateway response exceeded ${maxBytes}B`);
47
+ }
48
+ }
49
+ if (res.body && typeof res.body.getReader === "function") {
50
+ const reader = res.body.getReader();
51
+ const chunks = [];
52
+ let total = 0;
53
+ try {
54
+ for (;;) {
55
+ const { done, value } = await reader.read();
56
+ if (done)
57
+ break;
58
+ if (value) {
59
+ total += value.byteLength;
60
+ if (total > maxBytes) {
61
+ await reader.cancel();
62
+ throw new HwGatewayError(502, "RESPONSE_TOO_LARGE", `Gateway response exceeded ${maxBytes}B`);
63
+ }
64
+ chunks.push(value);
65
+ }
66
+ }
67
+ }
68
+ finally {
69
+ reader.releaseLock();
70
+ }
71
+ const merged = new Uint8Array(total);
72
+ let off = 0;
73
+ for (const c of chunks) {
74
+ merged.set(c, off);
75
+ off += c.byteLength;
76
+ }
77
+ return utf8Decoder.decode(merged);
78
+ }
79
+ const text = await res.text();
80
+ if (utf8Encoder.encode(text).byteLength > maxBytes) {
81
+ throw new HwGatewayError(502, "RESPONSE_TOO_LARGE", `Gateway response exceeded ${maxBytes}B`);
82
+ }
83
+ return text;
84
+ }
85
+ function bytesToBase64(bytes) {
86
+ if (typeof Buffer !== "undefined") {
87
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
88
+ }
89
+ let binary = "";
90
+ for (let i = 0; i < bytes.length; i++)
91
+ binary += String.fromCharCode(bytes[i]);
92
+ return btoa(binary);
93
+ }
94
+ export class HwGatewayClient {
95
+ baseUrl;
96
+ fetchFn;
97
+ timeoutMs;
98
+ posApiKey;
99
+ constructor(options) {
100
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
101
+ const fn = options.fetch ?? (typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : undefined);
102
+ if (!fn) {
103
+ throw new Error("HwGatewayClient requires globalThis.fetch or an explicit fetch implementation");
104
+ }
105
+ this.fetchFn = fn;
106
+ this.timeoutMs = Math.max(500, options.timeoutMs ?? DEFAULT_HW_GATEWAY_TIMEOUT_MS);
107
+ this.posApiKey = options.posApiKey;
108
+ }
109
+ async requestJson(method, path, body) {
110
+ const controller = new AbortController();
111
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
112
+ const headers = { Accept: "application/json" };
113
+ if (body !== undefined)
114
+ headers["Content-Type"] = "application/json";
115
+ if (this.posApiKey)
116
+ headers["X-Outpost-Api-Key"] = this.posApiKey;
117
+ try {
118
+ const res = await this.fetchFn(`${this.baseUrl}${path}`, {
119
+ method,
120
+ headers,
121
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
122
+ signal: controller.signal,
123
+ });
124
+ const text = await readBoundedText(res, MAX_HW_GATEWAY_RESPONSE_BYTES);
125
+ let parsed = {};
126
+ if (text.trim().length > 0) {
127
+ try {
128
+ parsed = JSON.parse(text);
129
+ }
130
+ catch {
131
+ throw new HwGatewayError(res.status, "INVALID_JSON", `Non-JSON response from gateway: ${text.slice(0, 120)}`);
132
+ }
133
+ }
134
+ if (!res.ok) {
135
+ throw new HwGatewayError(res.status, typeof parsed.code === "string" ? parsed.code : `HTTP_${res.status}`, typeof parsed.message === "string" ? parsed.message : `Gateway returned HTTP ${res.status}`, parsed);
136
+ }
137
+ return parsed;
138
+ }
139
+ catch (err) {
140
+ if (err instanceof HwGatewayError)
141
+ throw err;
142
+ const isAbort = err instanceof Error && err.name === "AbortError";
143
+ throw new HwGatewayError(isAbort ? 504 : 502, isAbort ? "GATEWAY_TIMEOUT" : "GATEWAY_NETWORK_ERROR", err instanceof Error ? err.message : String(err));
144
+ }
145
+ finally {
146
+ clearTimeout(timer);
147
+ }
148
+ }
149
+ async getHealth() {
150
+ return this.requestJson("GET", "/health");
151
+ }
152
+ parsePreview(raw) {
153
+ const hwAnchor = hexToBytes(String(raw.hw_anchor));
154
+ const appIdHash = hexToBytes(String(raw.app_id_hash));
155
+ const attestationDigest = hexToBytes(String(raw.attestation_digest));
156
+ const hwKind = Number(raw.hw_kind);
157
+ const maxSeq = Number(raw.max_seq);
158
+ const vaultId = String(raw.vault_id);
159
+ const pocketId = Number(raw.pocket_id);
160
+ const merkleProofs = Array.isArray(raw.merkle_proofs)
161
+ ? raw.merkle_proofs.map((p) => p.map(hexToBytes))
162
+ : undefined;
163
+ const leafPubkeys65 = Array.isArray(raw.leaf_pubkeys)
164
+ ? raw.leaf_pubkeys.map(hexToBytes)
165
+ : undefined;
166
+ return {
167
+ factoryVer: Number(raw.factory_ver),
168
+ owner: String(raw.owner),
169
+ vaultId,
170
+ pocketId,
171
+ epoch: Number(raw.epoch),
172
+ hwKind,
173
+ maxSeq,
174
+ hwAnchor,
175
+ appIdHash,
176
+ attestationDigest,
177
+ ...(merkleProofs !== undefined ? { merkleProofs } : {}),
178
+ ...(leafPubkeys65 !== undefined ? { leafPubkeys65 } : {}),
179
+ ...(raw.security_level === "strongbox" || raw.security_level === "tee"
180
+ ? { securityLevel: raw.security_level }
181
+ : {}),
182
+ ...(typeof raw.package_name === "string" ? { packageName: raw.package_name } : {}),
183
+ ...(raw.aaguid_env === "production" || raw.aaguid_env === "development"
184
+ ? { aaguidEnv: raw.aaguid_env }
185
+ : {}),
186
+ buildDepositOp: ({ token, amount, exitDelaySecs = HW_MIN_EXIT_DELAY_SECS }) => buildDepositHwOp({
187
+ vaultId,
188
+ pocketId,
189
+ token,
190
+ amount,
191
+ hwKind,
192
+ maxSeq,
193
+ hwAnchor,
194
+ appIdHash,
195
+ attestationDigest,
196
+ exitDelaySecs,
197
+ }),
198
+ };
199
+ }
200
+ parseCert(raw, networkHint, expectedVerifierPubkey) {
201
+ const certDto = raw.cert;
202
+ const cert = hwGenesisCertFromDto(certDto);
203
+ const verifierPubkeyHex = String(raw.verifier_pubkey).toLowerCase();
204
+ const verifierPubkey = hexToBytes(verifierPubkeyHex);
205
+ assertBytesLength(verifierPubkey, 32, "verifier_pubkey");
206
+ if (expectedVerifierPubkey !== undefined && !bytesEqual(verifierPubkey, expectedVerifierPubkey)) {
207
+ throw new HwGatewayError(502, "VERIFIER_PUBKEY_MISMATCH", "Gateway returned unexpected hardware attestation verifier pubkey");
208
+ }
209
+ const networkId = networkIdFromPassphrase(networkPassphraseForHint(networkHint));
210
+ const digest = computeHwGenesisDigest(networkId, cert);
211
+ if (!verifyEd25519(cert.verifierSig, digest, verifierPubkey)) {
212
+ throw new HwGatewayError(502, "INVALID_CERT_SIGNATURE", "Gateway returned HwGenesisCert with invalid Ed25519 signature");
213
+ }
214
+ const merkleProofs = Array.isArray(raw.merkle_proofs)
215
+ ? raw.merkle_proofs.map((p) => p.map(hexToBytes))
216
+ : undefined;
217
+ const leafPubkeys65 = Array.isArray(raw.leaf_pubkeys)
218
+ ? raw.leaf_pubkeys.map(hexToBytes)
219
+ : undefined;
220
+ return {
221
+ cert,
222
+ certDto,
223
+ verifierPubkey,
224
+ verifierPubkeyHex,
225
+ vaultId: String(raw.vault_id),
226
+ tokenContractId: String(raw.token),
227
+ ...(merkleProofs !== undefined ? { merkleProofs } : {}),
228
+ ...(leafPubkeys65 !== undefined ? { leafPubkeys65 } : {}),
229
+ ...(raw.security_level === "strongbox" || raw.security_level === "tee"
230
+ ? { securityLevel: raw.security_level }
231
+ : {}),
232
+ ...(typeof raw.package_name === "string" ? { packageName: raw.package_name } : {}),
233
+ ...(raw.aaguid_env === "production" || raw.aaguid_env === "development"
234
+ ? { aaguidEnv: raw.aaguid_env }
235
+ : {}),
236
+ };
237
+ }
238
+ async previewIosAttestation(params) {
239
+ const b64 = typeof params.attestationObject === "string"
240
+ ? params.attestationObject
241
+ : bytesToBase64(params.attestationObject);
242
+ const raw = await this.requestJson("POST", "/v2/hw-attest", {
243
+ mode: "preview",
244
+ platform: "ios",
245
+ owner: params.owner,
246
+ pocket_id: params.pocketId,
247
+ epoch: params.epoch,
248
+ ...(params.maxSeq !== undefined ? { max_seq: params.maxSeq } : {}),
249
+ ...(params.factoryVer !== undefined ? { factory_ver: params.factoryVer } : {}),
250
+ attestation_object: b64,
251
+ });
252
+ return this.parsePreview(raw);
253
+ }
254
+ async certifyIosPocket(params) {
255
+ const b64 = typeof params.attestationObject === "string"
256
+ ? params.attestationObject
257
+ : bytesToBase64(params.attestationObject);
258
+ const raw = await this.requestJson("POST", "/v2/hw-attest", {
259
+ mode: "cert",
260
+ platform: "ios",
261
+ owner: params.owner,
262
+ pocket_id: params.pocketId,
263
+ epoch: params.epoch,
264
+ ...(params.factoryVer !== undefined ? { factory_ver: params.factoryVer } : {}),
265
+ attestation_object: b64,
266
+ });
267
+ return this.parseCert(raw, params.networkHint, params.expectedVerifierPubkey);
268
+ }
269
+ async previewAndroidAttestation(params) {
270
+ const raw = await this.requestJson("POST", "/v2/hw-attest", {
271
+ mode: "preview",
272
+ platform: "android",
273
+ owner: params.owner,
274
+ pocket_id: params.pocketId,
275
+ epoch: params.epoch,
276
+ ...(params.factoryVer !== undefined ? { factory_ver: params.factoryVer } : {}),
277
+ ...(params.keyChains !== undefined
278
+ ? {
279
+ android_key_chains: params.keyChains.map((c) => c.map((x) => (typeof x === "string" ? x : bytesToBase64(x)))),
280
+ }
281
+ : {}),
282
+ ...(params.leafCerts !== undefined
283
+ ? {
284
+ android_leaf_certs: params.leafCerts.map((x) => typeof x === "string" ? x : bytesToBase64(x)),
285
+ }
286
+ : {}),
287
+ ...(params.issuerChain !== undefined
288
+ ? {
289
+ android_issuer_chain: params.issuerChain.map((x) => typeof x === "string" ? x : bytesToBase64(x)),
290
+ }
291
+ : {}),
292
+ });
293
+ return this.parsePreview(raw);
294
+ }
295
+ async certifyAndroidPocket(params) {
296
+ const raw = await this.requestJson("POST", "/v2/hw-attest", {
297
+ mode: "cert",
298
+ platform: "android",
299
+ owner: params.owner,
300
+ pocket_id: params.pocketId,
301
+ epoch: params.epoch,
302
+ ...(params.factoryVer !== undefined ? { factory_ver: params.factoryVer } : {}),
303
+ ...(params.keyChains !== undefined
304
+ ? {
305
+ android_key_chains: params.keyChains.map((c) => c.map((x) => (typeof x === "string" ? x : bytesToBase64(x)))),
306
+ }
307
+ : {}),
308
+ ...(params.leafCerts !== undefined
309
+ ? {
310
+ android_leaf_certs: params.leafCerts.map((x) => typeof x === "string" ? x : bytesToBase64(x)),
311
+ }
312
+ : {}),
313
+ ...(params.issuerChain !== undefined
314
+ ? {
315
+ android_issuer_chain: params.issuerChain.map((x) => typeof x === "string" ? x : bytesToBase64(x)),
316
+ }
317
+ : {}),
318
+ });
319
+ return this.parseCert(raw, params.networkHint, params.expectedVerifierPubkey);
320
+ }
321
+ /**
322
+ * Settle a hardware-backed payment via `POST /v2/settle/hw`.
323
+ * Accepts EITHER a framed `SMESHH1...` string / `Smeshh1Packet` OR explicit `{ cert, entry }`.
324
+ */
325
+ async settleHwPayment(params) {
326
+ let body;
327
+ if ("payload" in params) {
328
+ const encoded = typeof params.payload === "string" ? params.payload : encodeSmeshh1(params.payload);
329
+ body = {
330
+ payload: encoded,
331
+ ...(params.seq !== undefined ? { seq: params.seq } : {}),
332
+ ...(params.actualTip !== undefined ? { actual_tip: params.actualTip.toString() } : {}),
333
+ ...(params.gateway !== undefined ? { gateway: params.gateway } : {}),
334
+ };
335
+ }
336
+ else {
337
+ body = {
338
+ cert: hwGenesisCertToDto(params.cert),
339
+ entry: {
340
+ seq: params.entry.seq,
341
+ to: wireAddressToStrKey(params.entry.to),
342
+ amount: params.entry.amount.toString(),
343
+ max_tip: params.entry.maxTip.toString(),
344
+ cumulative_spent: params.entry.cumulativeSpent.toString(),
345
+ expiry_ts: params.entry.expiryTs.toString(),
346
+ expiry_ledger: params.entry.expiryLedger,
347
+ order_id: params.entry.orderId.toString(),
348
+ hw_proof: hwProofToDto(params.entry.hwProof),
349
+ },
350
+ ...(params.actualTip !== undefined ? { actual_tip: params.actualTip.toString() } : {}),
351
+ ...(params.gateway !== undefined ? { gateway: params.gateway } : {}),
352
+ };
353
+ }
354
+ const raw = await this.requestJson("POST", "/v2/settle/hw", body);
355
+ const status = raw.status === "CREDIT_PARKED" ? "CREDIT_PARKED" : "L1_FINAL";
356
+ return {
357
+ status,
358
+ ...(typeof raw.txHash === "string" ? { txHash: raw.txHash } : {}),
359
+ ...(typeof raw.ledgerSeq === "number" ? { ledgerSeq: raw.ledgerSeq } : {}),
360
+ ...(raw.alreadySettled === true || raw.already_settled === true ? { alreadySettled: true } : {}),
361
+ ...(typeof raw.vault_id === "string" ? { vaultId: raw.vault_id } : {}),
362
+ ...(typeof raw.recipient === "string" ? { recipient: raw.recipient } : {}),
363
+ ...(typeof raw.token === "string" ? { token: raw.token } : {}),
364
+ ...(typeof raw.amount === "string" ? { amount: raw.amount } : {}),
365
+ ...(Array.isArray(raw.advisoryTags) ? { advisoryTags: raw.advisoryTags } : {}),
366
+ };
367
+ }
368
+ }
369
+ // ---------------------------------------------------------------------------
370
+ // 2. HwPocketSession (Stateful Offline Wallet Manager + Portable JSON Persistence)
371
+ // ---------------------------------------------------------------------------
372
+ export const HW_SESSION_SCHEMA_VERSION = 1;
373
+ export class HwPocketSession {
374
+ networkHint;
375
+ networkId;
376
+ cert;
377
+ verifierPubkey;
378
+ merkleProofs;
379
+ leafPubkeys65;
380
+ entriesList;
381
+ constructor(params) {
382
+ this.networkHint = assertNetworkHint(params.networkHint);
383
+ this.networkId = networkIdFromPassphrase(networkPassphraseForHint(this.networkHint));
384
+ this.cert = params.cert;
385
+ this.verifierPubkey =
386
+ typeof params.verifierPubkey === "string"
387
+ ? hexToBytes(params.verifierPubkey)
388
+ : new Uint8Array(params.verifierPubkey);
389
+ assertBytesLength(this.verifierPubkey, 32, "verifierPubkey");
390
+ const digest = computeHwGenesisDigest(this.networkId, this.cert);
391
+ if (!verifyEd25519(this.cert.verifierSig, digest, this.verifierPubkey)) {
392
+ throw new Error("Cannot initialize HwPocketSession: invalid HwGenesisCert verifier signature");
393
+ }
394
+ this.merkleProofs = params.merkleProofs;
395
+ this.leafPubkeys65 = params.leafPubkeys65;
396
+ this.entriesList = params.entries ? [...params.entries] : [];
397
+ }
398
+ /** Helper to compute the `"SMW2_HWCHAL"` 32-byte challenge before calling `DCAppAttestService` / Android KeyStore. */
399
+ static attestationChallenge(params) {
400
+ const networkId = networkIdFromPassphrase(networkPassphraseForHint(params.networkHint));
401
+ return computeHwAttestationChallenge({
402
+ networkId,
403
+ vaultId: params.vaultId,
404
+ pocketId: params.pocketId,
405
+ epoch: params.epoch,
406
+ seq: params.seq,
407
+ });
408
+ }
409
+ get vaultId() {
410
+ return StellarSdk.StrKey.encodeContract(this.cert.vaultId);
411
+ }
412
+ get tokenContractId() {
413
+ return StellarSdk.StrKey.encodeContract(this.cert.tokenId);
414
+ }
415
+ get entries() {
416
+ return this.entriesList;
417
+ }
418
+ get nextSeq() {
419
+ return this.entriesList.length + 1;
420
+ }
421
+ get remainingCount() {
422
+ return Math.max(0, this.cert.maxSeq - this.entriesList.length);
423
+ }
424
+ get cumulativeSpent() {
425
+ if (this.entriesList.length === 0)
426
+ return 0n;
427
+ return this.entriesList[this.entriesList.length - 1].cumulativeSpent;
428
+ }
429
+ get remainingBalance() {
430
+ const rem = this.cert.epochTotalDeposited - this.cumulativeSpent;
431
+ return rem > 0n ? rem : 0n;
432
+ }
433
+ /**
434
+ * Prepare the next offline hardware payment.
435
+ * Deduplicates retries for identical non-zero `(to, orderId)` without burning `seq + 1` (`AGENTS.md` §1.6).
436
+ */
437
+ preparePayment(params) {
438
+ const toWire = typeof params.to === "string"
439
+ ? (() => {
440
+ assertNotMuxedStrKey(params.to);
441
+ return strKeyToWireAddress(params.to);
442
+ })()
443
+ : params.to;
444
+ const toStrKey = wireAddressToStrKey(toWire);
445
+ if (toStrKey === this.vaultId) {
446
+ throw new Error("Recipient cannot equal UserVault contract ID");
447
+ }
448
+ const maxTip = params.maxTip ?? 0n;
449
+ if (params.amount <= 0n || params.amount > MAX_U64) {
450
+ throw new RangeError(`amount out of range: ${params.amount}`);
451
+ }
452
+ if (maxTip < 0n || maxTip > MAX_U64) {
453
+ throw new RangeError(`maxTip out of range: ${maxTip}`);
454
+ }
455
+ if (params.orderId < 0n || params.orderId > MAX_U64) {
456
+ throw new RangeError(`orderId out of range: ${params.orderId}`);
457
+ }
458
+ // AGENTS.md §1.6: Idempotent non-zero (recipient, orderId) retry deduplication
459
+ if (params.orderId !== 0n) {
460
+ const existing = this.entriesList.find((e) => e.orderId === params.orderId &&
461
+ wireAddressToStrKey(e.to) === toStrKey &&
462
+ e.amount === params.amount);
463
+ if (existing) {
464
+ const digest = computeHwIntentDigest({
465
+ networkId: this.networkId,
466
+ vaultId: this.cert.vaultId,
467
+ pocketId: this.cert.pocketId,
468
+ epoch: this.cert.epoch,
469
+ seq: existing.seq,
470
+ tokenId: this.cert.tokenId,
471
+ to: existing.to,
472
+ amount: existing.amount,
473
+ maxTip: existing.maxTip,
474
+ cumulativeSpent: existing.cumulativeSpent,
475
+ expiryTs: existing.expiryTs,
476
+ expiryLedger: existing.expiryLedger,
477
+ orderId: existing.orderId,
478
+ });
479
+ return {
480
+ seq: existing.seq,
481
+ to: existing.to,
482
+ toStrKey,
483
+ amount: existing.amount,
484
+ maxTip: existing.maxTip,
485
+ cumulativeSpent: existing.cumulativeSpent,
486
+ expiryTs: existing.expiryTs,
487
+ expiryLedger: existing.expiryLedger,
488
+ orderId: existing.orderId,
489
+ hwIntentDigest: digest,
490
+ alreadySignedEntry: existing,
491
+ };
492
+ }
493
+ }
494
+ const seq = this.nextSeq;
495
+ if (seq > this.cert.maxSeq) {
496
+ throw new Error(`HwPocket exhausted: all ${this.cert.maxSeq} hardware slots used`);
497
+ }
498
+ const newCumulative = this.cumulativeSpent + params.amount + maxTip;
499
+ if (newCumulative > this.cert.epochTotalDeposited) {
500
+ throw new Error(`Insufficient HwPocket balance: need ${params.amount + maxTip}, remaining ${this.remainingBalance}`);
501
+ }
502
+ const exitMargin = params.exitMarginSecs ?? BigInt(DEFAULT_SAFETY_MARGIN_SECS);
503
+ const safeHorizon = this.cert.syncedAtTs + this.cert.exitDelaySecs - exitMargin;
504
+ if (params.expiryTs > safeHorizon) {
505
+ throw new Error(`expiryTs (${params.expiryTs}) exceeds safe exit horizon (${safeHorizon}); clamp expiryTs before signing`);
506
+ }
507
+ const hwIntentDigest = computeHwIntentDigest({
508
+ networkId: this.networkId,
509
+ vaultId: this.cert.vaultId,
510
+ pocketId: this.cert.pocketId,
511
+ epoch: this.cert.epoch,
512
+ seq,
513
+ tokenId: this.cert.tokenId,
514
+ to: toWire,
515
+ amount: params.amount,
516
+ maxTip,
517
+ cumulativeSpent: newCumulative,
518
+ expiryTs: params.expiryTs,
519
+ expiryLedger: params.expiryLedger,
520
+ orderId: params.orderId,
521
+ });
522
+ const leafIdx = seq - 1;
523
+ const androidLeafPubkey65 = this.cert.hwKind === HW_KIND_ANDROID_KEYMINT_MERKLE
524
+ ? this.leafPubkeys65?.[leafIdx]
525
+ : undefined;
526
+ const androidMerkleProof = this.cert.hwKind === HW_KIND_ANDROID_KEYMINT_MERKLE
527
+ ? this.merkleProofs?.[leafIdx]
528
+ : undefined;
529
+ return {
530
+ seq,
531
+ to: toWire,
532
+ toStrKey,
533
+ amount: params.amount,
534
+ maxTip,
535
+ cumulativeSpent: newCumulative,
536
+ expiryTs: params.expiryTs,
537
+ expiryLedger: params.expiryLedger,
538
+ orderId: params.orderId,
539
+ hwIntentDigest,
540
+ ...(androidLeafPubkey65 !== undefined ? { androidLeafPubkey65 } : {}),
541
+ ...(androidMerkleProof !== undefined ? { androidMerkleProof } : {}),
542
+ };
543
+ }
544
+ /**
545
+ * Prepare the next offline payment directly from a scanned merchant `SREQ1` invoice,
546
+ * automatically verifying token/network/verifier match, safely capping untrusted `SREQ1.tip`
547
+ * (`AGENTS.md` §1.6), and clamping `expiryTs`/`expiryLedger` inside the safe exit horizon.
548
+ */
549
+ preparePaymentFromInvoice(invoice, options) {
550
+ if (invoice.networkHint !== this.networkHint) {
551
+ throw new Error(`Invoice networkHint (${invoice.networkHint}) does not match pocket (${this.networkHint})`);
552
+ }
553
+ if (invoice.acceptedFactoryVers !== undefined &&
554
+ !invoice.acceptedFactoryVers.includes(this.cert.factoryVer)) {
555
+ throw new Error(`Merchant invoice does not accept factory_ver ${this.cert.factoryVer}`);
556
+ }
557
+ if (invoice.hwVerifierPubkeys !== undefined &&
558
+ !invoice.hwVerifierPubkeys.some((pk) => bytesEqual(pk, this.verifierPubkey))) {
559
+ throw new Error("Merchant invoice does not trust this pocket's hardware attestation verifier pubkey");
560
+ }
561
+ const resolver = options.tokenResolver ?? defaultTokenResolver;
562
+ const resolvedToken = resolver.resolve(invoice.token, invoice.networkHint);
563
+ if (resolvedToken.contractId !== this.tokenContractId) {
564
+ throw new Error(`Invoice token (${resolvedToken.contractId}) does not match pocket token (${this.tokenContractId})`);
565
+ }
566
+ // AGENTS.md §1.6: Cap untrusted SREQ1.tip by default (500 bps = 5%)
567
+ const maxTipBps = options.maxTipBps ?? DEFAULT_MAX_TIP_BPS;
568
+ const requestedTip = invoice.tip ?? 0n;
569
+ const tipCap = (invoice.amount * BigInt(maxTipBps)) / 10000n;
570
+ if (requestedTip > tipCap) {
571
+ throw new Error(`Untrusted SREQ1.tip (${requestedTip}) exceeds safe wallet cap (${tipCap}, ${maxTipBps} bps)`);
572
+ }
573
+ const exitMargin = options.exitMarginSecs ?? BigInt(DEFAULT_SAFETY_MARGIN_SECS);
574
+ const safeHorizon = this.cert.syncedAtTs + this.cert.exitDelaySecs - exitMargin;
575
+ const desiredExpiry = options.localNowTs + BigInt(Math.min(MAX_INTENT_TTL_SECS, 86_400));
576
+ const expiryTs = desiredExpiry < safeHorizon ? desiredExpiry : safeHorizon;
577
+ if (expiryTs <= options.localNowTs) {
578
+ throw new Error("HwPocket is too close to exit horizon to issue a safe offline payment");
579
+ }
580
+ const baseLedger = Math.max(this.cert.syncedLedgerSeq, invoice.syncedLedgerSeq, options.localLedgerSeq ?? 0);
581
+ const deltaSecs = Number(expiryTs - options.localNowTs);
582
+ // Conservative upper ledger bound at 3s/ledger + safety margin
583
+ const expiryLedger = baseLedger + Math.min(MAX_INTENT_TTL_LEDGERS, Math.ceil(deltaSecs / 3) + 1_000);
584
+ return this.preparePayment({
585
+ to: invoice.recipient,
586
+ amount: invoice.amount,
587
+ maxTip: requestedTip,
588
+ expiryTs,
589
+ expiryLedger,
590
+ orderId: invoice.orderId,
591
+ exitMarginSecs: exitMargin,
592
+ });
593
+ }
594
+ /**
595
+ * Commit an iOS `DCAppAttestService.generateAssertion` signature (accepts raw ASN.1 DER OR 64B low-S).
596
+ * Verifies P-256 signature locally STRICTLY BEFORE mutating session state (`AGENTS.md` §1.1).
597
+ */
598
+ commitIosPayment(prepared, assertion) {
599
+ if (this.cert.hwKind !== HW_KIND_IOS_APP_ATTEST) {
600
+ throw new Error("commitIosPayment called on non-iOS HwPocketSession");
601
+ }
602
+ if (prepared.alreadySignedEntry) {
603
+ const packet = this.buildPacketUpTo(prepared.alreadySignedEntry.seq);
604
+ return {
605
+ entry: prepared.alreadySignedEntry,
606
+ packet,
607
+ smeshh1: encodeSmeshh1(packet),
608
+ qr: encodeSmeshh1ForQr(packet),
609
+ deduplicated: true,
610
+ };
611
+ }
612
+ if (prepared.seq !== this.nextSeq) {
613
+ throw new Error(`Stale prepared payment seq ${prepared.seq}; expected ${this.nextSeq}`);
614
+ }
615
+ const sig64 = assertion.signature.length === 64
616
+ ? assertion.signature
617
+ : normalizeP256DerToLowS64(assertion.signature);
618
+ const ok = verifyIosAppAttestProof({
619
+ pubkey65: this.cert.hwAnchor,
620
+ expectedAppIdHash: this.cert.appIdHash,
621
+ expectedSeq: prepared.seq,
622
+ clientDataHash: prepared.hwIntentDigest,
623
+ authData: assertion.authData,
624
+ sig64,
625
+ });
626
+ if (!ok) {
627
+ throw new Error("iOS AppAttest P-256 assertion failed local verification; session not mutated");
628
+ }
629
+ const hwProof = {
630
+ kind: "ios_app_attest",
631
+ authData: new Uint8Array(assertion.authData),
632
+ sig64: new Uint8Array(sig64),
633
+ };
634
+ const entry = {
635
+ seq: prepared.seq,
636
+ to: prepared.to,
637
+ amount: prepared.amount,
638
+ maxTip: prepared.maxTip,
639
+ cumulativeSpent: prepared.cumulativeSpent,
640
+ expiryTs: prepared.expiryTs,
641
+ expiryLedger: prepared.expiryLedger,
642
+ orderId: prepared.orderId,
643
+ hwProof,
644
+ };
645
+ this.entriesList.push(entry);
646
+ const packet = this.buildCurrentPacket();
647
+ return {
648
+ entry,
649
+ packet,
650
+ smeshh1: encodeSmeshh1(packet),
651
+ qr: encodeSmeshh1ForQr(packet),
652
+ deduplicated: false,
653
+ };
654
+ }
655
+ /**
656
+ * Commit an Android KeyMint / StrongBox single-use signature (accepts ASN.1 DER OR 64B low-S).
657
+ * Verifies Merkle inclusion + P-256 signature locally STRICTLY BEFORE mutating session state (`AGENTS.md` §1.1).
658
+ */
659
+ commitAndroidPayment(prepared, sigParams) {
660
+ if (this.cert.hwKind !== HW_KIND_ANDROID_KEYMINT_MERKLE) {
661
+ throw new Error("commitAndroidPayment called on non-Android HwPocketSession");
662
+ }
663
+ if (prepared.alreadySignedEntry) {
664
+ const packet = this.buildPacketUpTo(prepared.alreadySignedEntry.seq);
665
+ return {
666
+ entry: prepared.alreadySignedEntry,
667
+ packet,
668
+ smeshh1: encodeSmeshh1(packet),
669
+ qr: encodeSmeshh1ForQr(packet),
670
+ deduplicated: true,
671
+ };
672
+ }
673
+ if (prepared.seq !== this.nextSeq) {
674
+ throw new Error(`Stale prepared payment seq ${prepared.seq}; expected ${this.nextSeq}`);
675
+ }
676
+ const leafPubkey65 = sigParams.leafPubkey65 ?? prepared.androidLeafPubkey65;
677
+ const merkleProof = sigParams.merkleProof ?? prepared.androidMerkleProof;
678
+ if (!leafPubkey65 || !merkleProof) {
679
+ throw new Error("Missing Android leafPubkey65 or merkleProof for this seq");
680
+ }
681
+ const sig64 = sigParams.signature.length === 64
682
+ ? sigParams.signature
683
+ : normalizeP256DerToLowS64(sigParams.signature);
684
+ const ok = verifyAndroidKeyMintProof({
685
+ expectedMerkleRoot: this.cert.hwAnchor,
686
+ maxSeq: this.cert.maxSeq,
687
+ expectedSeq: prepared.seq,
688
+ clientDataHash: prepared.hwIntentDigest,
689
+ leafPubkey65,
690
+ merkleProof,
691
+ sig64,
692
+ });
693
+ if (!ok) {
694
+ throw new Error("Android KeyMint P-256 / Merkle proof failed local verification; session not mutated");
695
+ }
696
+ const hwProof = {
697
+ kind: "android_keymint_merkle",
698
+ leafPubkey65: new Uint8Array(leafPubkey65),
699
+ merkleProof: merkleProof.map((h) => new Uint8Array(h)),
700
+ sig64: new Uint8Array(sig64),
701
+ };
702
+ const entry = {
703
+ seq: prepared.seq,
704
+ to: prepared.to,
705
+ amount: prepared.amount,
706
+ maxTip: prepared.maxTip,
707
+ cumulativeSpent: prepared.cumulativeSpent,
708
+ expiryTs: prepared.expiryTs,
709
+ expiryLedger: prepared.expiryLedger,
710
+ orderId: prepared.orderId,
711
+ hwProof,
712
+ };
713
+ this.entriesList.push(entry);
714
+ const packet = this.buildCurrentPacket();
715
+ return {
716
+ entry,
717
+ packet,
718
+ smeshh1: encodeSmeshh1(packet),
719
+ qr: encodeSmeshh1ForQr(packet),
720
+ deduplicated: false,
721
+ };
722
+ }
723
+ buildPacketUpTo(seq) {
724
+ if (seq < 1 || seq > this.entriesList.length) {
725
+ throw new Error(`No committed payment at seq ${seq} (have ${this.entriesList.length})`);
726
+ }
727
+ return {
728
+ networkHint: this.networkHint,
729
+ cert: this.cert,
730
+ entries: this.entriesList.slice(0, seq),
731
+ };
732
+ }
733
+ buildCurrentPacket() {
734
+ if (this.entriesList.length === 0) {
735
+ throw new Error("No committed payments in HwPocketSession yet");
736
+ }
737
+ return {
738
+ networkHint: this.networkHint,
739
+ cert: this.cert,
740
+ entries: [...this.entriesList],
741
+ };
742
+ }
743
+ encodeCurrentQr(options) {
744
+ return encodeSmeshh1ForQr(this.buildCurrentPacket(), options);
745
+ }
746
+ encodeCurrentBleChunks(attValueMtu, msgId = 1) {
747
+ return encodeBleHwPaymentChunks(this.buildCurrentPacket(), attValueMtu, msgId);
748
+ }
749
+ /** Serialize session state to versioned portable JSON for Keychain / Keystore / MMKV / SecureStore. */
750
+ toJson() {
751
+ const snap = {
752
+ version: HW_SESSION_SCHEMA_VERSION,
753
+ networkHint: this.networkHint,
754
+ cert: hwGenesisCertToDto(this.cert),
755
+ verifierPubkeyHex: bytesToHex(this.verifierPubkey),
756
+ entries: this.entriesList.map(hwPaymentEntryToDto),
757
+ ...(this.merkleProofs !== undefined
758
+ ? { merkleProofsHex: this.merkleProofs.map((p) => p.map(bytesToHex)) }
759
+ : {}),
760
+ ...(this.leafPubkeys65 !== undefined
761
+ ? { leafPubkeysHex: this.leafPubkeys65.map(bytesToHex) }
762
+ : {}),
763
+ };
764
+ return JSON.stringify(snap);
765
+ }
766
+ /** Restore a persisted `HwPocketSession` from versioned JSON (re-verifying `HwGenesisCert`!). */
767
+ static fromJson(json) {
768
+ const parsed = JSON.parse(json);
769
+ if (!parsed || parsed.version !== HW_SESSION_SCHEMA_VERSION) {
770
+ throw new Error(`Unsupported HwPocketSession JSON version: ${String(parsed?.version)}`);
771
+ }
772
+ if (parsed.networkHint === undefined || !parsed.cert || !parsed.verifierPubkeyHex) {
773
+ throw new Error("Missing required fields in serialized HwPocketSession");
774
+ }
775
+ const cert = hwGenesisCertFromDto(parsed.cert);
776
+ const entries = Array.isArray(parsed.entries)
777
+ ? parsed.entries.map(hwPaymentEntryFromDto)
778
+ : [];
779
+ const merkleProofs = Array.isArray(parsed.merkleProofsHex)
780
+ ? parsed.merkleProofsHex.map((p) => p.map(hexToBytes))
781
+ : undefined;
782
+ const leafPubkeys65 = Array.isArray(parsed.leafPubkeysHex)
783
+ ? parsed.leafPubkeysHex.map(hexToBytes)
784
+ : undefined;
785
+ return new HwPocketSession({
786
+ networkHint: parsed.networkHint,
787
+ cert,
788
+ verifierPubkey: hexToBytes(parsed.verifierPubkeyHex),
789
+ entries,
790
+ ...(merkleProofs !== undefined ? { merkleProofs } : {}),
791
+ ...(leafPubkeys65 !== undefined ? { leafPubkeys65 } : {}),
792
+ });
793
+ }
794
+ }