@outpost-protocol/core 0.1.1 → 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.
- package/README.md +3 -1
- package/dist/cert0.d.ts +12 -0
- package/dist/cert0.js +125 -0
- package/dist/contracts.d.ts +256 -0
- package/dist/contracts.js +665 -0
- package/dist/coordinators.d.ts +131 -0
- package/dist/coordinators.js +457 -0
- package/dist/hw.d.ts +243 -0
- package/dist/hw.js +858 -0
- package/dist/hwClient.d.ts +270 -0
- package/dist/hwClient.js +794 -0
- package/dist/hwTransport.d.ts +173 -0
- package/dist/hwTransport.js +431 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/wallet.d.ts +43 -4
- package/dist/wallet.js +136 -5
- package/dist/walletStorage.d.ts +128 -0
- package/dist/walletStorage.js +399 -0
- package/dist/wire.d.ts +10 -0
- package/dist/wire.js +31 -0
- package/dist/witnessClient.d.ts +20 -0
- package/package.json +1 -1
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outpost v2 Hardware Roaming Payment Handover Transports (`QR / Animated UR:SMESH` & `BLE GATT`).
|
|
3
|
+
*
|
|
4
|
+
* Gives wallets and receivers one clean, bounded, CRC32C-verified handover protocol for delivering
|
|
5
|
+
* a `SMESHH1` hardware payment + its full contiguous prior signature chain `[seq 1..=k]` +
|
|
6
|
+
* `HwGenesisCert` over:
|
|
7
|
+
* 1. **Static QR** (`SMESHH1...` Base32) when compact (e.g., iOS payment #1 = ~831 chars).
|
|
8
|
+
* 2. **Animated QR** (`UR:SMESH/i-n/...` frames @ 4–5 fps) for multi-payment chains up to 64 txs.
|
|
9
|
+
* 3. **Bluetooth LE GATT** (`OUTPOST_BLE_V1` chunking + Castagnoli CRC32C RPC envelope over
|
|
10
|
+
* `OUTPOST_BLE_P2P_SERVICE_UUID`, `POST /v2/hw-pay` & `GET /v2/invoice`).
|
|
11
|
+
*/
|
|
12
|
+
import { type BleGattLink, type BleReassemblyOutcome } from "./bleTransport.js";
|
|
13
|
+
import { type Smeshh1Packet } from "./hw.js";
|
|
14
|
+
import { type Sreq1Packet } from "./wire.js";
|
|
15
|
+
/**
|
|
16
|
+
* Default threshold (characters) below which a single static QR code (Alphanumeric Mode,
|
|
17
|
+
* <= QR V20-M) is preferred over animated `UR:SMESH` frames.
|
|
18
|
+
*/
|
|
19
|
+
export declare const DEFAULT_SMESHH1_STATIC_QR_MAX_CHARS = 900;
|
|
20
|
+
export interface Smeshh1QrPayload {
|
|
21
|
+
/** Recommended display mode: single static QR or animated `UR:SMESH` loop at 4-5 fps. */
|
|
22
|
+
readonly mode: "static_qr" | "animated_ur";
|
|
23
|
+
/** Single `SMESHH1...` framed Base32 string (present whenever within `MAX_FRAMED_BASE32_LEN`). */
|
|
24
|
+
readonly text?: string;
|
|
25
|
+
/** Animated `UR:SMESH/1-N/...` frames (ALWAYS populated so any animated QR scanner works). */
|
|
26
|
+
readonly urFrames: readonly string[];
|
|
27
|
+
/** Raw binary `SMESHH1` byte length (sent directly over BLE GATT). */
|
|
28
|
+
readonly byteLength: number;
|
|
29
|
+
}
|
|
30
|
+
/** Encode a `Smeshh1Packet` directly into `UR:SMESH/<idx>-<total>/...` animated QR frames. */
|
|
31
|
+
export declare function encodeSmeshh1UrFrames(packet: Smeshh1Packet, maxChunkBytes?: number): string[];
|
|
32
|
+
/** Reassemble `UR:SMESH` frames (in any order) and decode into a `Smeshh1Packet`. */
|
|
33
|
+
export declare function decodeSmeshh1UrFrames(frames: readonly string[]): Smeshh1Packet;
|
|
34
|
+
/**
|
|
35
|
+
* Encode a `Smeshh1Packet` for QR presentation, automatically selecting `"static_qr"` for
|
|
36
|
+
* compact chains (e.g. iOS seq #1) and `"animated_ur"` for larger multi-payment chains, while
|
|
37
|
+
* always returning `urFrames` and `byteLength`.
|
|
38
|
+
*/
|
|
39
|
+
export declare function encodeSmeshh1ForQr(packet: Smeshh1Packet, options?: {
|
|
40
|
+
readonly staticQrMaxChars?: number;
|
|
41
|
+
readonly maxChunkBytes?: number;
|
|
42
|
+
}): Smeshh1QrPayload;
|
|
43
|
+
export type Smeshh1QrScanOutcome = {
|
|
44
|
+
readonly complete: false;
|
|
45
|
+
readonly receivedCount: number;
|
|
46
|
+
readonly expectedTotal: number;
|
|
47
|
+
readonly progress: number;
|
|
48
|
+
readonly missingIndices: readonly number[];
|
|
49
|
+
} | {
|
|
50
|
+
readonly complete: true;
|
|
51
|
+
readonly transport: "static_qr" | "animated_ur";
|
|
52
|
+
readonly packet: Smeshh1Packet;
|
|
53
|
+
readonly rawBytes: Uint8Array;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Stateful QR scanner helper for receivers: feed ANY scanned QR string (single `SMESHH1...` OR
|
|
57
|
+
* out-of-order `UR:SMESH/i-n/...` frames) until `complete === true`.
|
|
58
|
+
*/
|
|
59
|
+
export declare class Smeshh1QrCollector {
|
|
60
|
+
private readonly urDecoder;
|
|
61
|
+
private completedPacket;
|
|
62
|
+
private completedRaw;
|
|
63
|
+
private completedTransport;
|
|
64
|
+
receiveScan(scannedText: string): Smeshh1QrScanOutcome;
|
|
65
|
+
isComplete(): boolean;
|
|
66
|
+
result(): {
|
|
67
|
+
readonly packet: Smeshh1Packet;
|
|
68
|
+
readonly rawBytes: Uint8Array;
|
|
69
|
+
readonly transport: "static_qr" | "animated_ur";
|
|
70
|
+
};
|
|
71
|
+
reset(): void;
|
|
72
|
+
}
|
|
73
|
+
/** Dedicated BLE GATT Service UUID advertised by Outpost receivers/POS accepting offline P2P payments. */
|
|
74
|
+
export declare const OUTPOST_BLE_P2P_SERVICE_UUID = "8d4f0011-7b3a-4e2c-9a1d-5c6e7f8a9b01";
|
|
75
|
+
/** Canonical BLE RPC path for submitting raw binary `SMESHH1` hardware payment chains. */
|
|
76
|
+
export declare const BLE_HW_PAY_PATH = "/v2/hw-pay";
|
|
77
|
+
/** Canonical BLE RPC path for fetching the merchant's current `SREQ1` invoice string. */
|
|
78
|
+
export declare const BLE_HW_INVOICE_PATH = "/v2/invoice";
|
|
79
|
+
export type BleHwPaymentAck = {
|
|
80
|
+
readonly status: "ACCEPTED";
|
|
81
|
+
readonly receipt_id: string;
|
|
82
|
+
readonly vault_id: string;
|
|
83
|
+
readonly pocket_id: number;
|
|
84
|
+
readonly epoch: number;
|
|
85
|
+
readonly seq: number;
|
|
86
|
+
readonly amount: string;
|
|
87
|
+
readonly cumulative_spent: string;
|
|
88
|
+
} | {
|
|
89
|
+
readonly status: "REJECTED";
|
|
90
|
+
readonly code: string;
|
|
91
|
+
readonly message: string;
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Encode a `Smeshh1Packet` into `OUTPOST_BLE_V1` chunks (`POST /v2/hw-pay` with raw binary body)
|
|
95
|
+
* ready to write sequentially to `OUTPOST_BLE_RX_CHAR_UUID`.
|
|
96
|
+
*/
|
|
97
|
+
export declare function encodeBleHwPaymentChunks(packet: Smeshh1Packet, attValueMtu: number, msgId?: number): Uint8Array[];
|
|
98
|
+
/** Decode a reassembled `POST /v2/hw-pay` BLE request envelope into a `Smeshh1Packet`. */
|
|
99
|
+
export declare function decodeBleHwPaymentEnvelope(envelopeBytes: Uint8Array): Smeshh1Packet;
|
|
100
|
+
/** Encode a receiver's `BleHwPaymentAck` into `OUTPOST_BLE_V1` TX notification chunks. */
|
|
101
|
+
export declare function encodeBleHwAckChunks(ack: BleHwPaymentAck, attValueMtu: number, msgId: number, httpStatus?: number): Uint8Array[];
|
|
102
|
+
/** Decode a reassembled BLE TX response envelope into a `BleHwPaymentAck`. */
|
|
103
|
+
export declare function decodeBleHwPaymentAck(envelopeBytes: Uint8Array): {
|
|
104
|
+
readonly status: number;
|
|
105
|
+
readonly ack: BleHwPaymentAck;
|
|
106
|
+
};
|
|
107
|
+
export declare class BleRequestReassembler {
|
|
108
|
+
private readonly maxInflightMsgs;
|
|
109
|
+
private readonly maxTotalBytes;
|
|
110
|
+
private readonly maxMessageBytes;
|
|
111
|
+
private readonly timeoutMs;
|
|
112
|
+
private readonly nowMsFn;
|
|
113
|
+
private readonly inflight;
|
|
114
|
+
private totalBytes;
|
|
115
|
+
constructor(options?: {
|
|
116
|
+
readonly maxInflightMsgs?: number;
|
|
117
|
+
readonly maxTotalBytes?: number;
|
|
118
|
+
readonly maxMessageBytes?: number;
|
|
119
|
+
readonly timeoutMs?: number;
|
|
120
|
+
readonly nowMs?: () => number;
|
|
121
|
+
});
|
|
122
|
+
deleteMsg(msgId: number): void;
|
|
123
|
+
sweepExpired(nowMs?: number): void;
|
|
124
|
+
feedChunk(chunk: Uint8Array, nowMs?: number): BleReassemblyOutcome;
|
|
125
|
+
}
|
|
126
|
+
export interface BleHwPaymentSenderOptions {
|
|
127
|
+
readonly link: BleGattLink;
|
|
128
|
+
readonly timeoutMs?: number;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* High-level Central (payer wallet) BLE P2P adapter over any `BleGattLink`.
|
|
132
|
+
* Sends raw binary `SMESHH1` chains to a receiver POS (`POST /v2/hw-pay`) and awaits the signed/structured ACK.
|
|
133
|
+
*/
|
|
134
|
+
export declare class BleHwPaymentSender {
|
|
135
|
+
private readonly link;
|
|
136
|
+
private readonly timeoutMs;
|
|
137
|
+
private nextMsgId;
|
|
138
|
+
constructor(options: BleHwPaymentSenderOptions);
|
|
139
|
+
private allocMsgId;
|
|
140
|
+
private exchange;
|
|
141
|
+
/** Optional: fetch the merchant's current `SREQ1` invoice over BLE (`GET /v2/invoice`). */
|
|
142
|
+
fetchInvoice(): Promise<{
|
|
143
|
+
readonly encoded: string;
|
|
144
|
+
readonly decoded: Sreq1Packet;
|
|
145
|
+
}>;
|
|
146
|
+
/** Send a complete `Smeshh1Packet` over BLE (`POST /v2/hw-pay`) and return the receiver's ACK. */
|
|
147
|
+
sendPayment(packet: Smeshh1Packet): Promise<BleHwPaymentAck>;
|
|
148
|
+
}
|
|
149
|
+
export interface BleHwPaymentReceiverOptions {
|
|
150
|
+
/** Current negotiated ATT characteristic value MTU (`20..=512`). */
|
|
151
|
+
readonly getAttValueMtu: () => number;
|
|
152
|
+
/** Invoked when a complete `SMESHH1` packet arrives over `POST /v2/hw-pay`. */
|
|
153
|
+
readonly onPayment: (packet: Smeshh1Packet, rawBytes: Uint8Array) => Promise<BleHwPaymentAck> | BleHwPaymentAck;
|
|
154
|
+
/** Optional provider for `GET /v2/invoice` returning the merchant's `SREQ1` string or packet. */
|
|
155
|
+
readonly getInvoice?: () => Promise<string | Sreq1Packet> | string | Sreq1Packet;
|
|
156
|
+
readonly timeoutMs?: number;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* High-level Peripheral (merchant/receiver) BLE P2P handler.
|
|
160
|
+
* Feed every incoming GATT RX write chunk to `receiveChunk(chunk)` and notify any returned TX chunks back to the payer.
|
|
161
|
+
*/
|
|
162
|
+
export declare class BleHwPaymentReceiver {
|
|
163
|
+
private readonly reassembler;
|
|
164
|
+
private readonly getAttValueMtu;
|
|
165
|
+
private readonly onPayment;
|
|
166
|
+
private readonly getInvoice?;
|
|
167
|
+
constructor(options: BleHwPaymentReceiverOptions);
|
|
168
|
+
/**
|
|
169
|
+
* Process one incoming GATT RX chunk. Returns `null` while more chunks are needed, or
|
|
170
|
+
* the `Uint8Array[]` TX response chunks once a complete request has been handled.
|
|
171
|
+
*/
|
|
172
|
+
receiveChunk(rxChunk: Uint8Array): Promise<Uint8Array[] | null>;
|
|
173
|
+
}
|
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outpost v2 Hardware Roaming Payment Handover Transports (`QR / Animated UR:SMESH` & `BLE GATT`).
|
|
3
|
+
*
|
|
4
|
+
* Gives wallets and receivers one clean, bounded, CRC32C-verified handover protocol for delivering
|
|
5
|
+
* a `SMESHH1` hardware payment + its full contiguous prior signature chain `[seq 1..=k]` +
|
|
6
|
+
* `HwGenesisCert` over:
|
|
7
|
+
* 1. **Static QR** (`SMESHH1...` Base32) when compact (e.g., iOS payment #1 = ~831 chars).
|
|
8
|
+
* 2. **Animated QR** (`UR:SMESH/i-n/...` frames @ 4–5 fps) for multi-payment chains up to 64 txs.
|
|
9
|
+
* 3. **Bluetooth LE GATT** (`OUTPOST_BLE_V1` chunking + Castagnoli CRC32C RPC envelope over
|
|
10
|
+
* `OUTPOST_BLE_P2P_SERVICE_UUID`, `POST /v2/hw-pay` & `GET /v2/invoice`).
|
|
11
|
+
*/
|
|
12
|
+
import { MAX_FRAMED_BASE32_LEN } from "./base32.js";
|
|
13
|
+
import { DEFAULT_UR_SMESH_MAX_CHUNK_BYTES, encodeUrSmesh, UR_SMESH_PREFIX, UrSmeshDecoder, } from "./bcur.js";
|
|
14
|
+
import { BLE_FLAG_ERROR, BLE_FLAG_REQUEST, BLE_FLAG_RESPONSE, BleResponseReassembler, BleTransportError, chunkBleMessage, decodeBleRequest, decodeBleResponse, DEFAULT_BLE_MAX_INFLIGHT_MSGS, DEFAULT_BLE_MAX_TOTAL_BUFFER_BYTES, DEFAULT_BLE_REASSEMBLY_TIMEOUT_MS, encodeBleRequest, encodeBleResponse, MAX_BLE_ATT_VALUE_MTU, MAX_BLE_REQUEST_BYTES, MIN_BLE_ATT_VALUE_MTU, parseBleChunk, } from "./bleTransport.js";
|
|
15
|
+
import { decodeSmeshh1, decodeSmeshh1Bytes, encodeSmeshh1, encodeSmeshh1Bytes, HRP_SMESHH, MAX_SMESHH1_BYTES, } from "./hw.js";
|
|
16
|
+
import { decodeSreq1, encodeSreq1 } from "./wire.js";
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// QR & Animated UR:SMESH Handover for SMESHH1
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
/**
|
|
21
|
+
* Default threshold (characters) below which a single static QR code (Alphanumeric Mode,
|
|
22
|
+
* <= QR V20-M) is preferred over animated `UR:SMESH` frames.
|
|
23
|
+
*/
|
|
24
|
+
export const DEFAULT_SMESHH1_STATIC_QR_MAX_CHARS = 900;
|
|
25
|
+
/** Encode a `Smeshh1Packet` directly into `UR:SMESH/<idx>-<total>/...` animated QR frames. */
|
|
26
|
+
export function encodeSmeshh1UrFrames(packet, maxChunkBytes = DEFAULT_UR_SMESH_MAX_CHUNK_BYTES) {
|
|
27
|
+
return encodeUrSmesh(encodeSmeshh1Bytes(packet), maxChunkBytes);
|
|
28
|
+
}
|
|
29
|
+
/** Reassemble `UR:SMESH` frames (in any order) and decode into a `Smeshh1Packet`. */
|
|
30
|
+
export function decodeSmeshh1UrFrames(frames) {
|
|
31
|
+
const decoder = new UrSmeshDecoder();
|
|
32
|
+
for (const frame of frames) {
|
|
33
|
+
decoder.receivePart(frame);
|
|
34
|
+
}
|
|
35
|
+
return decodeSmeshh1Bytes(decoder.result());
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Encode a `Smeshh1Packet` for QR presentation, automatically selecting `"static_qr"` for
|
|
39
|
+
* compact chains (e.g. iOS seq #1) and `"animated_ur"` for larger multi-payment chains, while
|
|
40
|
+
* always returning `urFrames` and `byteLength`.
|
|
41
|
+
*/
|
|
42
|
+
export function encodeSmeshh1ForQr(packet, options) {
|
|
43
|
+
const raw = encodeSmeshh1Bytes(packet);
|
|
44
|
+
const urFrames = encodeUrSmesh(raw, options?.maxChunkBytes ?? DEFAULT_UR_SMESH_MAX_CHUNK_BYTES);
|
|
45
|
+
const staticMax = options?.staticQrMaxChars ?? DEFAULT_SMESHH1_STATIC_QR_MAX_CHARS;
|
|
46
|
+
// Base32 length of (raw || 4B crc32c) + 7 chars ("SMESHH1")
|
|
47
|
+
const framedCharLen = HRP_SMESHH.length + 1 + Math.ceil(((raw.length + 4) * 8) / 5);
|
|
48
|
+
const text = framedCharLen <= MAX_FRAMED_BASE32_LEN ? encodeSmeshh1(packet) : undefined;
|
|
49
|
+
const mode = text !== undefined && text.length <= staticMax ? "static_qr" : "animated_ur";
|
|
50
|
+
return {
|
|
51
|
+
mode,
|
|
52
|
+
...(text !== undefined ? { text } : {}),
|
|
53
|
+
urFrames,
|
|
54
|
+
byteLength: raw.length,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Stateful QR scanner helper for receivers: feed ANY scanned QR string (single `SMESHH1...` OR
|
|
59
|
+
* out-of-order `UR:SMESH/i-n/...` frames) until `complete === true`.
|
|
60
|
+
*/
|
|
61
|
+
export class Smeshh1QrCollector {
|
|
62
|
+
urDecoder = new UrSmeshDecoder();
|
|
63
|
+
completedPacket = null;
|
|
64
|
+
completedRaw = null;
|
|
65
|
+
completedTransport = null;
|
|
66
|
+
receiveScan(scannedText) {
|
|
67
|
+
const trimmed = scannedText.trim();
|
|
68
|
+
const upperPrefix = trimmed.slice(0, UR_SMESH_PREFIX.length + 1).toUpperCase();
|
|
69
|
+
if (upperPrefix === `${UR_SMESH_PREFIX}/`) {
|
|
70
|
+
const done = this.urDecoder.receivePart(trimmed);
|
|
71
|
+
if (!done) {
|
|
72
|
+
return {
|
|
73
|
+
complete: false,
|
|
74
|
+
receivedCount: this.urDecoder.receivedCount(),
|
|
75
|
+
expectedTotal: this.urDecoder.expectedTotal() ?? 0,
|
|
76
|
+
progress: this.urDecoder.progress(),
|
|
77
|
+
missingIndices: this.urDecoder.missingIndices(),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const rawBytes = this.urDecoder.result();
|
|
81
|
+
const packet = decodeSmeshh1Bytes(rawBytes);
|
|
82
|
+
this.completedPacket = packet;
|
|
83
|
+
this.completedRaw = rawBytes;
|
|
84
|
+
this.completedTransport = "animated_ur";
|
|
85
|
+
return { complete: true, transport: "animated_ur", packet, rawBytes };
|
|
86
|
+
}
|
|
87
|
+
// Single static SMESHH1... QR
|
|
88
|
+
const packet = decodeSmeshh1(trimmed);
|
|
89
|
+
const rawBytes = encodeSmeshh1Bytes(packet);
|
|
90
|
+
this.completedPacket = packet;
|
|
91
|
+
this.completedRaw = rawBytes;
|
|
92
|
+
this.completedTransport = "static_qr";
|
|
93
|
+
return { complete: true, transport: "static_qr", packet, rawBytes };
|
|
94
|
+
}
|
|
95
|
+
isComplete() {
|
|
96
|
+
return this.completedPacket !== null;
|
|
97
|
+
}
|
|
98
|
+
result() {
|
|
99
|
+
if (!this.completedPacket || !this.completedRaw || !this.completedTransport) {
|
|
100
|
+
throw new Error("Smeshh1QrCollector is not complete yet");
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
packet: this.completedPacket,
|
|
104
|
+
rawBytes: this.completedRaw,
|
|
105
|
+
transport: this.completedTransport,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
reset() {
|
|
109
|
+
this.urDecoder.reset();
|
|
110
|
+
this.completedPacket = null;
|
|
111
|
+
this.completedRaw = null;
|
|
112
|
+
this.completedTransport = null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
// Bluetooth LE GATT P2P Handover (OUTPOST_BLE_V1 Framing + CRC32C Envelope)
|
|
117
|
+
// ---------------------------------------------------------------------------
|
|
118
|
+
/** Dedicated BLE GATT Service UUID advertised by Outpost receivers/POS accepting offline P2P payments. */
|
|
119
|
+
export const OUTPOST_BLE_P2P_SERVICE_UUID = "8d4f0011-7b3a-4e2c-9a1d-5c6e7f8a9b01";
|
|
120
|
+
/** Canonical BLE RPC path for submitting raw binary `SMESHH1` hardware payment chains. */
|
|
121
|
+
export const BLE_HW_PAY_PATH = "/v2/hw-pay";
|
|
122
|
+
/** Canonical BLE RPC path for fetching the merchant's current `SREQ1` invoice string. */
|
|
123
|
+
export const BLE_HW_INVOICE_PATH = "/v2/invoice";
|
|
124
|
+
const utf8Encoder = new TextEncoder();
|
|
125
|
+
const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
|
|
126
|
+
/**
|
|
127
|
+
* Encode a `Smeshh1Packet` into `OUTPOST_BLE_V1` chunks (`POST /v2/hw-pay` with raw binary body)
|
|
128
|
+
* ready to write sequentially to `OUTPOST_BLE_RX_CHAR_UUID`.
|
|
129
|
+
*/
|
|
130
|
+
export function encodeBleHwPaymentChunks(packet, attValueMtu, msgId = 1) {
|
|
131
|
+
const rawBytes = encodeSmeshh1Bytes(packet);
|
|
132
|
+
const envelope = encodeBleRequest("POST", BLE_HW_PAY_PATH, rawBytes);
|
|
133
|
+
return chunkBleMessage(BLE_FLAG_REQUEST, msgId, envelope, attValueMtu);
|
|
134
|
+
}
|
|
135
|
+
/** Decode a reassembled `POST /v2/hw-pay` BLE request envelope into a `Smeshh1Packet`. */
|
|
136
|
+
export function decodeBleHwPaymentEnvelope(envelopeBytes) {
|
|
137
|
+
const req = decodeBleRequest(envelopeBytes);
|
|
138
|
+
if (req.method !== "POST" || req.path !== BLE_HW_PAY_PATH) {
|
|
139
|
+
throw new BleTransportError("BLE_UNEXPECTED_ROUTE", `Expected POST ${BLE_HW_PAY_PATH}, got ${req.method} ${req.path}`);
|
|
140
|
+
}
|
|
141
|
+
if (req.body.byteLength === 0 || req.body.byteLength > MAX_SMESHH1_BYTES) {
|
|
142
|
+
throw new BleTransportError("BLE_MESSAGE_TOO_LARGE", `SMESHH1 BLE body length (${req.body.byteLength}B) out of bounds`);
|
|
143
|
+
}
|
|
144
|
+
return decodeSmeshh1Bytes(req.body);
|
|
145
|
+
}
|
|
146
|
+
/** Encode a receiver's `BleHwPaymentAck` into `OUTPOST_BLE_V1` TX notification chunks. */
|
|
147
|
+
export function encodeBleHwAckChunks(ack, attValueMtu, msgId, httpStatus) {
|
|
148
|
+
const status = httpStatus ?? (ack.status === "ACCEPTED" ? 200 : 400);
|
|
149
|
+
const body = utf8Encoder.encode(JSON.stringify(ack));
|
|
150
|
+
const envelope = encodeBleResponse(status, body);
|
|
151
|
+
return chunkBleMessage(ack.status === "ACCEPTED" ? BLE_FLAG_RESPONSE : BLE_FLAG_ERROR, msgId, envelope, attValueMtu);
|
|
152
|
+
}
|
|
153
|
+
/** Decode a reassembled BLE TX response envelope into a `BleHwPaymentAck`. */
|
|
154
|
+
export function decodeBleHwPaymentAck(envelopeBytes) {
|
|
155
|
+
const res = decodeBleResponse(envelopeBytes);
|
|
156
|
+
const text = utf8Decoder.decode(res.body);
|
|
157
|
+
const parsed = JSON.parse(text);
|
|
158
|
+
if (typeof parsed !== "object" ||
|
|
159
|
+
parsed === null ||
|
|
160
|
+
(parsed.status !== "ACCEPTED" && parsed.status !== "REJECTED")) {
|
|
161
|
+
throw new BleTransportError("BLE_MALFORMED_ENVELOPE", "Invalid BLE hardware payment ACK JSON");
|
|
162
|
+
}
|
|
163
|
+
return { status: res.status, ack: parsed };
|
|
164
|
+
}
|
|
165
|
+
function bytesEqLocal(a, b) {
|
|
166
|
+
if (a.byteLength !== b.byteLength)
|
|
167
|
+
return false;
|
|
168
|
+
for (let i = 0; i < a.byteLength; i++) {
|
|
169
|
+
if (a[i] !== b[i])
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
export class BleRequestReassembler {
|
|
175
|
+
maxInflightMsgs;
|
|
176
|
+
maxTotalBytes;
|
|
177
|
+
maxMessageBytes;
|
|
178
|
+
timeoutMs;
|
|
179
|
+
nowMsFn;
|
|
180
|
+
inflight = new Map();
|
|
181
|
+
totalBytes = 0;
|
|
182
|
+
constructor(options) {
|
|
183
|
+
this.maxInflightMsgs = Math.max(1, options?.maxInflightMsgs ?? DEFAULT_BLE_MAX_INFLIGHT_MSGS);
|
|
184
|
+
this.maxTotalBytes = Math.max(1024, options?.maxTotalBytes ?? DEFAULT_BLE_MAX_TOTAL_BUFFER_BYTES);
|
|
185
|
+
this.maxMessageBytes = Math.min(MAX_BLE_REQUEST_BYTES, Math.max(64, options?.maxMessageBytes ?? MAX_BLE_REQUEST_BYTES));
|
|
186
|
+
this.timeoutMs = Math.max(100, options?.timeoutMs ?? DEFAULT_BLE_REASSEMBLY_TIMEOUT_MS);
|
|
187
|
+
this.nowMsFn = options?.nowMs ?? (() => Date.now());
|
|
188
|
+
}
|
|
189
|
+
deleteMsg(msgId) {
|
|
190
|
+
const existing = this.inflight.get(msgId);
|
|
191
|
+
if (existing) {
|
|
192
|
+
this.totalBytes = Math.max(0, this.totalBytes - existing.bufferedBytes);
|
|
193
|
+
this.inflight.delete(msgId);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
sweepExpired(nowMs = this.nowMsFn()) {
|
|
197
|
+
for (const [msgId, partial] of this.inflight.entries()) {
|
|
198
|
+
if (nowMs - partial.createdAtMs >= this.timeoutMs) {
|
|
199
|
+
this.deleteMsg(msgId);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
feedChunk(chunk, nowMs = this.nowMsFn()) {
|
|
204
|
+
this.sweepExpired(nowMs);
|
|
205
|
+
const parsed = parseBleChunk(chunk);
|
|
206
|
+
if (parsed.flags !== BLE_FLAG_REQUEST) {
|
|
207
|
+
throw new BleTransportError("BLE_INVALID_FLAGS", `Expected BLE_FLAG_REQUEST (0x00), got 0x${parsed.flags.toString(16)}`);
|
|
208
|
+
}
|
|
209
|
+
if (parsed.totalChunks === 1) {
|
|
210
|
+
if (parsed.payload.byteLength > this.maxMessageBytes) {
|
|
211
|
+
throw new BleTransportError("BLE_MESSAGE_TOO_LARGE", "Single-chunk BLE request exceeds cap");
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
complete: true,
|
|
215
|
+
flags: parsed.flags,
|
|
216
|
+
msgId: parsed.msgId,
|
|
217
|
+
payload: new Uint8Array(parsed.payload),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
let partial = this.inflight.get(parsed.msgId);
|
|
221
|
+
if (!partial) {
|
|
222
|
+
while (this.inflight.size >= this.maxInflightMsgs) {
|
|
223
|
+
const oldestKey = this.inflight.keys().next().value;
|
|
224
|
+
if (oldestKey === undefined)
|
|
225
|
+
break;
|
|
226
|
+
this.deleteMsg(oldestKey);
|
|
227
|
+
}
|
|
228
|
+
partial = {
|
|
229
|
+
totalChunks: parsed.totalChunks,
|
|
230
|
+
chunks: new Map(),
|
|
231
|
+
bufferedBytes: 0,
|
|
232
|
+
createdAtMs: nowMs,
|
|
233
|
+
};
|
|
234
|
+
this.inflight.set(parsed.msgId, partial);
|
|
235
|
+
}
|
|
236
|
+
if (partial.totalChunks !== parsed.totalChunks) {
|
|
237
|
+
this.deleteMsg(parsed.msgId);
|
|
238
|
+
throw new BleTransportError("BLE_CONFLICTING_TOTAL_CHUNKS", "Conflicting BLE totalChunks");
|
|
239
|
+
}
|
|
240
|
+
const existing = partial.chunks.get(parsed.chunkIdx);
|
|
241
|
+
if (existing !== undefined) {
|
|
242
|
+
if (!bytesEqLocal(existing, parsed.payload)) {
|
|
243
|
+
this.deleteMsg(parsed.msgId);
|
|
244
|
+
throw new BleTransportError("BLE_CONFLICTING_CHUNK", "Conflicting duplicate BLE chunk");
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
complete: false,
|
|
248
|
+
msgId: parsed.msgId,
|
|
249
|
+
receivedChunks: partial.chunks.size,
|
|
250
|
+
totalChunks: partial.totalChunks,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
const incomingLen = parsed.payload.byteLength;
|
|
254
|
+
if (partial.bufferedBytes + incomingLen > this.maxMessageBytes) {
|
|
255
|
+
this.deleteMsg(parsed.msgId);
|
|
256
|
+
throw new BleTransportError("BLE_MESSAGE_TOO_LARGE", "BLE request exceeded maxMessageBytes");
|
|
257
|
+
}
|
|
258
|
+
if (this.totalBytes + incomingLen > this.maxTotalBytes) {
|
|
259
|
+
this.deleteMsg(parsed.msgId);
|
|
260
|
+
throw new BleTransportError("BLE_BUFFER_EXHAUSTED", "BLE request buffer cap exceeded");
|
|
261
|
+
}
|
|
262
|
+
partial.chunks.set(parsed.chunkIdx, new Uint8Array(parsed.payload));
|
|
263
|
+
partial.bufferedBytes += incomingLen;
|
|
264
|
+
this.totalBytes += incomingLen;
|
|
265
|
+
if (partial.chunks.size < partial.totalChunks) {
|
|
266
|
+
return {
|
|
267
|
+
complete: false,
|
|
268
|
+
msgId: parsed.msgId,
|
|
269
|
+
receivedChunks: partial.chunks.size,
|
|
270
|
+
totalChunks: partial.totalChunks,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
const out = new Uint8Array(partial.bufferedBytes);
|
|
274
|
+
let offset = 0;
|
|
275
|
+
for (let idx = 0; idx < partial.totalChunks; idx++) {
|
|
276
|
+
const piece = partial.chunks.get(idx);
|
|
277
|
+
if (!piece) {
|
|
278
|
+
this.deleteMsg(parsed.msgId);
|
|
279
|
+
throw new BleTransportError("BLE_MALFORMED_ENVELOPE", `Missing BLE chunk ${idx}`);
|
|
280
|
+
}
|
|
281
|
+
out.set(piece, offset);
|
|
282
|
+
offset += piece.byteLength;
|
|
283
|
+
}
|
|
284
|
+
this.deleteMsg(parsed.msgId);
|
|
285
|
+
return {
|
|
286
|
+
complete: true,
|
|
287
|
+
flags: BLE_FLAG_REQUEST,
|
|
288
|
+
msgId: parsed.msgId,
|
|
289
|
+
payload: out,
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* High-level Central (payer wallet) BLE P2P adapter over any `BleGattLink`.
|
|
295
|
+
* Sends raw binary `SMESHH1` chains to a receiver POS (`POST /v2/hw-pay`) and awaits the signed/structured ACK.
|
|
296
|
+
*/
|
|
297
|
+
export class BleHwPaymentSender {
|
|
298
|
+
link;
|
|
299
|
+
timeoutMs;
|
|
300
|
+
nextMsgId = 1;
|
|
301
|
+
constructor(options) {
|
|
302
|
+
this.link = options.link;
|
|
303
|
+
this.timeoutMs = Math.max(500, options.timeoutMs ?? DEFAULT_BLE_REASSEMBLY_TIMEOUT_MS);
|
|
304
|
+
}
|
|
305
|
+
allocMsgId() {
|
|
306
|
+
const id = this.nextMsgId;
|
|
307
|
+
this.nextMsgId = this.nextMsgId >= 0xffff ? 1 : this.nextMsgId + 1;
|
|
308
|
+
return id;
|
|
309
|
+
}
|
|
310
|
+
async exchange(method, path, body) {
|
|
311
|
+
const mtu = this.link.getAttValueMtu();
|
|
312
|
+
if (!Number.isInteger(mtu) || mtu < MIN_BLE_ATT_VALUE_MTU || mtu > MAX_BLE_ATT_VALUE_MTU) {
|
|
313
|
+
throw new BleTransportError("BLE_INVALID_MTU", `Invalid negotiated ATT value MTU: ${mtu}`);
|
|
314
|
+
}
|
|
315
|
+
const msgId = this.allocMsgId();
|
|
316
|
+
const reqEnv = encodeBleRequest(method, path, body ?? new Uint8Array(0));
|
|
317
|
+
const chunks = chunkBleMessage(BLE_FLAG_REQUEST, msgId, reqEnv, mtu);
|
|
318
|
+
const reassembler = new BleResponseReassembler({ timeoutMs: this.timeoutMs });
|
|
319
|
+
return new Promise((resolve, reject) => {
|
|
320
|
+
let settled = false;
|
|
321
|
+
let unsub;
|
|
322
|
+
const timer = setTimeout(() => {
|
|
323
|
+
if (settled)
|
|
324
|
+
return;
|
|
325
|
+
settled = true;
|
|
326
|
+
unsub?.();
|
|
327
|
+
reject(new BleTransportError("BLE_TIMEOUT", `BLE ${method} ${path} timed out after ${this.timeoutMs}ms`));
|
|
328
|
+
}, this.timeoutMs);
|
|
329
|
+
const finish = (err, payload) => {
|
|
330
|
+
if (settled)
|
|
331
|
+
return;
|
|
332
|
+
settled = true;
|
|
333
|
+
clearTimeout(timer);
|
|
334
|
+
unsub?.();
|
|
335
|
+
if (err !== undefined)
|
|
336
|
+
reject(err);
|
|
337
|
+
else
|
|
338
|
+
resolve(payload);
|
|
339
|
+
};
|
|
340
|
+
unsub = this.link.subscribeTx((chunk) => {
|
|
341
|
+
try {
|
|
342
|
+
const outcome = reassembler.feedChunk(chunk);
|
|
343
|
+
if (outcome.complete && outcome.msgId === msgId) {
|
|
344
|
+
finish(undefined, outcome.payload);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
catch (err) {
|
|
348
|
+
finish(err);
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
void (async () => {
|
|
352
|
+
try {
|
|
353
|
+
for (const frame of chunks) {
|
|
354
|
+
await this.link.writeRx(frame);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
catch (err) {
|
|
358
|
+
finish(err);
|
|
359
|
+
}
|
|
360
|
+
})();
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
/** Optional: fetch the merchant's current `SREQ1` invoice over BLE (`GET /v2/invoice`). */
|
|
364
|
+
async fetchInvoice() {
|
|
365
|
+
const respEnv = await this.exchange("GET", BLE_HW_INVOICE_PATH);
|
|
366
|
+
const res = decodeBleResponse(respEnv);
|
|
367
|
+
const text = utf8Decoder.decode(res.body).trim();
|
|
368
|
+
if (res.status < 200 || res.status >= 300) {
|
|
369
|
+
throw new BleTransportError("BLE_INVOICE_ERROR", `Receiver returned HTTP ${res.status}: ${text}`);
|
|
370
|
+
}
|
|
371
|
+
return { encoded: text, decoded: decodeSreq1(text) };
|
|
372
|
+
}
|
|
373
|
+
/** Send a complete `Smeshh1Packet` over BLE (`POST /v2/hw-pay`) and return the receiver's ACK. */
|
|
374
|
+
async sendPayment(packet) {
|
|
375
|
+
const raw = encodeSmeshh1Bytes(packet);
|
|
376
|
+
const respEnv = await this.exchange("POST", BLE_HW_PAY_PATH, raw);
|
|
377
|
+
return decodeBleHwPaymentAck(respEnv).ack;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* High-level Peripheral (merchant/receiver) BLE P2P handler.
|
|
382
|
+
* Feed every incoming GATT RX write chunk to `receiveChunk(chunk)` and notify any returned TX chunks back to the payer.
|
|
383
|
+
*/
|
|
384
|
+
export class BleHwPaymentReceiver {
|
|
385
|
+
reassembler;
|
|
386
|
+
getAttValueMtu;
|
|
387
|
+
onPayment;
|
|
388
|
+
getInvoice;
|
|
389
|
+
constructor(options) {
|
|
390
|
+
this.reassembler = new BleRequestReassembler({ timeoutMs: options.timeoutMs });
|
|
391
|
+
this.getAttValueMtu = options.getAttValueMtu;
|
|
392
|
+
this.onPayment = options.onPayment;
|
|
393
|
+
this.getInvoice = options.getInvoice;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Process one incoming GATT RX chunk. Returns `null` while more chunks are needed, or
|
|
397
|
+
* the `Uint8Array[]` TX response chunks once a complete request has been handled.
|
|
398
|
+
*/
|
|
399
|
+
async receiveChunk(rxChunk) {
|
|
400
|
+
const outcome = this.reassembler.feedChunk(rxChunk);
|
|
401
|
+
if (!outcome.complete) {
|
|
402
|
+
return null;
|
|
403
|
+
}
|
|
404
|
+
const mtu = this.getAttValueMtu();
|
|
405
|
+
try {
|
|
406
|
+
const req = decodeBleRequest(outcome.payload);
|
|
407
|
+
if (req.method === "GET" && req.path === BLE_HW_INVOICE_PATH) {
|
|
408
|
+
if (!this.getInvoice) {
|
|
409
|
+
const errEnv = encodeBleResponse(404, utf8Encoder.encode("No invoice configured"));
|
|
410
|
+
return chunkBleMessage(BLE_FLAG_ERROR, outcome.msgId, errEnv, mtu);
|
|
411
|
+
}
|
|
412
|
+
const inv = await this.getInvoice();
|
|
413
|
+
const encoded = typeof inv === "string" ? inv : encodeSreq1(inv);
|
|
414
|
+
const okEnv = encodeBleResponse(200, utf8Encoder.encode(encoded));
|
|
415
|
+
return chunkBleMessage(BLE_FLAG_RESPONSE, outcome.msgId, okEnv, mtu);
|
|
416
|
+
}
|
|
417
|
+
if (req.method === "POST" && req.path === BLE_HW_PAY_PATH) {
|
|
418
|
+
const packet = decodeSmeshh1Bytes(req.body);
|
|
419
|
+
const ack = await this.onPayment(packet, req.body);
|
|
420
|
+
return encodeBleHwAckChunks(ack, mtu, outcome.msgId);
|
|
421
|
+
}
|
|
422
|
+
const notFound = encodeBleResponse(404, utf8Encoder.encode(JSON.stringify({ status: "REJECTED", code: "NOT_FOUND", message: `Unknown BLE path ${req.path}` })));
|
|
423
|
+
return chunkBleMessage(BLE_FLAG_ERROR, outcome.msgId, notFound, mtu);
|
|
424
|
+
}
|
|
425
|
+
catch (err) {
|
|
426
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
427
|
+
const code = err instanceof BleTransportError ? err.code : "INVALID_HW_PAYMENT";
|
|
428
|
+
return encodeBleHwAckChunks({ status: "REJECTED", code, message: msg }, mtu, outcome.msgId, 400);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -5,8 +5,15 @@ export * from "./vault.js";
|
|
|
5
5
|
export * from "./digest.js";
|
|
6
6
|
export * from "./bcur.js";
|
|
7
7
|
export * from "./wire.js";
|
|
8
|
+
export * from "./cert0.js";
|
|
9
|
+
export * from "./contracts.js";
|
|
8
10
|
export * from "./relayDirect.js";
|
|
9
11
|
export * from "./feeBump.js";
|
|
10
12
|
export * from "./wallet.js";
|
|
13
|
+
export * from "./walletStorage.js";
|
|
11
14
|
export * from "./witnessClient.js";
|
|
15
|
+
export * from "./coordinators.js";
|
|
12
16
|
export * from "./bleTransport.js";
|
|
17
|
+
export * from "./hw.js";
|
|
18
|
+
export * from "./hwTransport.js";
|
|
19
|
+
export * from "./hwClient.js";
|
package/dist/index.js
CHANGED
|
@@ -5,8 +5,15 @@ export * from "./vault.js";
|
|
|
5
5
|
export * from "./digest.js";
|
|
6
6
|
export * from "./bcur.js";
|
|
7
7
|
export * from "./wire.js";
|
|
8
|
+
export * from "./cert0.js";
|
|
9
|
+
export * from "./contracts.js";
|
|
8
10
|
export * from "./relayDirect.js";
|
|
9
11
|
export * from "./feeBump.js";
|
|
10
12
|
export * from "./wallet.js";
|
|
13
|
+
export * from "./walletStorage.js";
|
|
11
14
|
export * from "./witnessClient.js";
|
|
15
|
+
export * from "./coordinators.js";
|
|
12
16
|
export * from "./bleTransport.js";
|
|
17
|
+
export * from "./hw.js";
|
|
18
|
+
export * from "./hwTransport.js";
|
|
19
|
+
export * from "./hwClient.js";
|