@ninsei-labs/sdk 0.56.1 → 0.57.2
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/CHANGELOG.md +13 -0
- package/LICENSE-POLICY.md +9 -2
- package/README.md +17 -4
- package/THIRD_PARTY_NOTICES.md +174 -0
- package/assets/vendors/MANIFEST.json +1 -5
- package/assets/vendors/sdk/sdk-browser.js +5 -4
- package/engine/atomic/dleq2.js +116 -15
- package/engine/atomic/order.js +21 -3
- package/engine/core/config.js +17 -24
- package/engine/core/deployments.generated.js +103 -0
- package/engine/core/swap.js +7 -7
- package/engine/evm/asyncRoute.js +1 -1
- package/engine/evm/claimGas.js +2 -1
- package/engine/evm/escrow.js +13 -8
- package/engine/evm/factory.js +11 -6
- package/engine/evm/funding.js +8 -3
- package/engine/evm/index.js +2 -4
- package/engine/evm/session.js +3 -3
- package/engine/monero/scan.js +101 -22
- package/engine/recovery/restore.js +8 -8
- package/engine/sdk/bridge.js +2 -5
- package/index.d.ts +48 -11
- package/package.json +4 -2
- package/src/actions.mjs +8 -5
- package/src/codes.mjs +5 -0
- package/src/config.mjs +1 -0
- package/src/engine.mjs +6 -6
- package/src/feeEstimate.mjs +11 -4
- package/src/http.mjs +4 -1
- package/src/index.mjs +1 -1
- package/src/legs/kyber.mjs +23 -0
- package/src/lock.mjs +1 -0
- package/src/order.mjs +108 -20
- package/src/primitives.mjs +4 -5
- package/src/probes.mjs +9 -3
- package/src/public/networks.d.ts +45 -0
- package/src/public/networks.mjs +10 -1
- package/src/public/xmr.mjs +1 -1
- package/src/quotes.mjs +97 -23
- package/src/recovery-key.mjs +32 -14
- package/src/relayFeatures.mjs +25 -13
- package/src/relayFirmClient.mjs +33 -7
- package/src/relayQuote.mjs +87 -10
- package/src/relayView.mjs +3 -3
- package/src/swap-flow.mjs +100 -58
- package/src/swaps.mjs +234 -64
- package/src/sweep-restore.mjs +8 -4
- package/src/sweep.mjs +5 -1
- package/src/version.mjs +1 -1
- package/src/xmr-arrival.mjs +55 -24
- package/assets/vendors/atomic/atomic-browser.js +0 -24
- package/engine/atomic/order-client.js +0 -56
- package/engine/atomic/order-worker.js +0 -156
- package/engine/evm/asyncExec.js +0 -577
- package/engine/evm/asyncLegs.js +0 -308
package/src/recovery-key.mjs
CHANGED
|
@@ -247,6 +247,10 @@ export async function createRecoveryKeyFile({ mnemonic, createdAt, passphrase =
|
|
|
247
247
|
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
248
248
|
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
249
249
|
const header = {
|
|
250
|
+
// THE ENCRYPTED FILE NAMES ITSELF TOO. The plain file has its magic line; without a `kind` the JSON backup was
|
|
251
|
+
// indistinguishable from any other ciphertext object. It is outside the AAD (which carries the same constant),
|
|
252
|
+
// so older files without it still open.
|
|
253
|
+
kind: "ninsei-recovery-key",
|
|
250
254
|
v: RECOVERY_KEY_ENVELOPE_VERSION,
|
|
251
255
|
alg: RECOVERY_KEY_ALG,
|
|
252
256
|
iter: RECOVERY_KEY_ITER,
|
|
@@ -289,9 +293,11 @@ export async function openRecoveryKeyFile(contents, passphrase = "") {
|
|
|
289
293
|
} catch {
|
|
290
294
|
throw failed("parse");
|
|
291
295
|
}
|
|
292
|
-
if (!envelope || envelope.
|
|
296
|
+
if (!envelope || (envelope.kind !== undefined && envelope.kind !== "ninsei-recovery-key")
|
|
297
|
+
|| envelope.v !== RECOVERY_KEY_ENVELOPE_VERSION || envelope.alg !== RECOVERY_KEY_ALG) throw failed("parse");
|
|
293
298
|
for (const field of ["salt", "iv", "ciphertext"]) if (typeof envelope[field] !== "string" || !envelope[field]) throw failed("parse");
|
|
294
|
-
|
|
299
|
+
let iter = null;
|
|
300
|
+
try { iter = Number(envelope.iter); } catch { iter = null; }
|
|
295
301
|
if (!Number.isInteger(iter) || iter < ITER_MIN || iter > ITER_MAX) throw failed("parse");
|
|
296
302
|
if (passphrase.length < 12) throw failed("passphrase");
|
|
297
303
|
|
|
@@ -363,12 +369,18 @@ function topicAddress(address) {
|
|
|
363
369
|
}
|
|
364
370
|
|
|
365
371
|
function decodeOrderLog(log) {
|
|
366
|
-
|
|
367
|
-
const
|
|
368
|
-
if (topics.length < 4 ||
|
|
369
|
-
const
|
|
372
|
+
if (!log || typeof log !== "object") return null;
|
|
373
|
+
const topics = Array.isArray(log.topics) ? log.topics : [];
|
|
374
|
+
if (topics.length < 4 || topics.some((topic) => typeof topic !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(topic))) return null;
|
|
375
|
+
const topic0 = topics[0].toLowerCase();
|
|
376
|
+
if (!ORDER_CREATED_TOPICS.includes(topic0)) return null;
|
|
377
|
+
if (typeof log.data !== "string" || !/^0x[0-9a-fA-F]*$/.test(log.data)) return null;
|
|
378
|
+
const data = log.data.slice(2);
|
|
370
379
|
const modern = topic0 === ORDER_CREATED_TOPIC;
|
|
371
|
-
if (data.length < 64 * (modern ? 13 : 12)) return null;
|
|
380
|
+
if (data.length < 64 * (modern ? 13 : 12) || data.length % 64 !== 0) return null;
|
|
381
|
+
if (log.transactionHash !== undefined && log.transactionHash !== null && typeof log.transactionHash !== "string") return null;
|
|
382
|
+
if (log.blockNumber !== undefined && log.blockNumber !== null && typeof log.blockNumber !== "number" && typeof log.blockNumber !== "string") return null;
|
|
383
|
+
if (log.logIndex !== undefined && log.logIndex !== null && typeof log.logIndex !== "number" && typeof log.logIndex !== "string") return null;
|
|
372
384
|
const word = (i) => "0x" + data.slice(i * 64, (i + 1) * 64).toLowerCase();
|
|
373
385
|
// THE FIELD OFFSETS MOVED WHEN `xmrAmount` JOINED THE EVENT. The old topic has no XMR amount; its orders fall
|
|
374
386
|
// back to the clone read, and a caller can still tell why from `xmrAmountReason`.
|
|
@@ -390,15 +402,15 @@ function decodeOrderLog(log) {
|
|
|
390
402
|
registry: "0x" + data.slice((9 + shift) * 64 + 24, (10 + shift) * 64),
|
|
391
403
|
provider: "0x" + data.slice((10 + shift) * 64 + 24, (11 + shift) * 64),
|
|
392
404
|
quoteKey: "0x" + data.slice((11 + shift) * 64 + 24, (12 + shift) * 64),
|
|
393
|
-
transactionHash: log.transactionHash
|
|
405
|
+
transactionHash: typeof log.transactionHash === "string" ? log.transactionHash : null,
|
|
394
406
|
blockNumber: log.blockNumber != null ? Number(log.blockNumber) : null,
|
|
395
407
|
logIndex: log.logIndex != null ? Number(log.logIndex) : null,
|
|
396
408
|
};
|
|
397
409
|
}
|
|
398
410
|
|
|
399
|
-
// THE CLONE CARRIES THE ORDER, INCLUDING THE XMR AMOUNT. OrderCreated
|
|
400
|
-
// has no getter
|
|
401
|
-
// shape: a contract of another size is not this order and must not yield a guessed number.
|
|
411
|
+
// THE CLONE CARRIES THE ORDER, INCLUDING THE XMR AMOUNT. The legacy OrderCreated has no `xmrAmount`; the modern
|
|
412
|
+
// event carries it, while a clone has no getter, but word 18 of the condition blob is in its code. Read the clone
|
|
413
|
+
// only from the exact shape: a contract of another size is not this order and must not yield a guessed number.
|
|
402
414
|
const CLONE_CODE_BYTES = 877;
|
|
403
415
|
const XMR_AMOUNT_WORD = 18;
|
|
404
416
|
const CLONE_PROXY_BYTES = 45;
|
|
@@ -668,11 +680,17 @@ export async function findSwaps({ mnemonic, chainId, factory = null, factories =
|
|
|
668
680
|
logs = await readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS] });
|
|
669
681
|
}
|
|
670
682
|
for (const log of logs) {
|
|
671
|
-
|
|
683
|
+
if (!log || typeof log !== "object") continue;
|
|
684
|
+
const logAddress = typeof log.address === "string" ? log.address : "";
|
|
685
|
+
const logTx = typeof log.transactionHash === "string" ? log.transactionHash : "";
|
|
686
|
+
const logIndex = typeof log.logIndex === "number" || typeof log.logIndex === "string" ? log.logIndex : "";
|
|
687
|
+
const id = `${target.factory}:${logAddress}:${logTx}:${logIndex}`;
|
|
672
688
|
if (seenLogs.has(id)) continue;
|
|
689
|
+
let order = null;
|
|
690
|
+
try { order = decodeOrderLog(log); } catch { order = null; }
|
|
691
|
+
if (!order) continue;
|
|
673
692
|
seenLogs.add(id);
|
|
674
|
-
|
|
675
|
-
if (order) orders.push({ ...order, factory: target.factory });
|
|
693
|
+
orders.push({ ...order, factory: target.factory });
|
|
676
694
|
}
|
|
677
695
|
}
|
|
678
696
|
const orderKey = (order) => `${order.factory || ""}:${order.transactionHash || ""}:${order.logIndex ?? ""}`;
|
package/src/relayFeatures.mjs
CHANGED
|
@@ -42,7 +42,19 @@ export const NODE_FEATURES_FIELDS = [
|
|
|
42
42
|
["nonce", "bytes32"],
|
|
43
43
|
];
|
|
44
44
|
|
|
45
|
-
const
|
|
45
|
+
const wireText = (value, field) => {
|
|
46
|
+
if (typeof value === "string") return value;
|
|
47
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
48
|
+
if (typeof value === "bigint") return String(value);
|
|
49
|
+
throw new SdkError("bad-input", { field });
|
|
50
|
+
};
|
|
51
|
+
const wireNumber = (value, field) => {
|
|
52
|
+
let n = null;
|
|
53
|
+
try { n = Number(value); } catch { n = null; }
|
|
54
|
+
if (!Number.isFinite(n)) throw new SdkError("bad-input", { field });
|
|
55
|
+
return n;
|
|
56
|
+
};
|
|
57
|
+
const utf8 = (value, field = "text") => new TextEncoder().encode(wireText(value, field));
|
|
46
58
|
const concat = (...arrays) => {
|
|
47
59
|
const total = arrays.reduce((n, a) => n + a.length, 0);
|
|
48
60
|
const out = new Uint8Array(total);
|
|
@@ -51,7 +63,7 @@ const concat = (...arrays) => {
|
|
|
51
63
|
return out;
|
|
52
64
|
};
|
|
53
65
|
const hexBytes = (value, field, width) => {
|
|
54
|
-
const text =
|
|
66
|
+
const text = wireText(value === undefined || value === null ? "" : value, field).replace(/^0x/, "");
|
|
55
67
|
if (!new RegExp("^[0-9a-fA-F]{" + width * 2 + "}$").test(text)) {
|
|
56
68
|
throw new SdkError("bad-input", { field });
|
|
57
69
|
}
|
|
@@ -68,13 +80,13 @@ const numberWord = (value, field, bits) => {
|
|
|
68
80
|
return out;
|
|
69
81
|
};
|
|
70
82
|
const addressWord = (value, field) => {
|
|
71
|
-
const text =
|
|
83
|
+
const text = wireText(value === undefined || value === null ? "" : value, field).trim();
|
|
72
84
|
if (!/^(0x)?[0-9a-fA-F]{40}$/.test(text)) throw new SdkError("bad-input", { field });
|
|
73
85
|
const out = new Uint8Array(32);
|
|
74
86
|
out.set(hexBytes(text, field, 20), 12);
|
|
75
87
|
return out;
|
|
76
88
|
};
|
|
77
|
-
const stringWord = (value) => keccak256(utf8(value === undefined || value === null ? "" : value));
|
|
89
|
+
const stringWord = (value, field) => keccak256(utf8(value === undefined || value === null ? "" : value, field));
|
|
78
90
|
const arrayWord = (values, field, hashOf) => {
|
|
79
91
|
if (!Array.isArray(values)) throw new SdkError("bad-input", { field });
|
|
80
92
|
const parts = values.map((value) => hashOf(value));
|
|
@@ -85,7 +97,7 @@ function firmWindowHash(window) {
|
|
|
85
97
|
if (!window || typeof window !== "object") throw new SdkError("bad-input", { field: "firmWindows" });
|
|
86
98
|
const parts = [keccak256(utf8(FIRM_WINDOW_TYPE))];
|
|
87
99
|
for (const [field, type] of FIRM_WINDOW_FIELDS) {
|
|
88
|
-
parts.push(type === "string" ? stringWord(window[field]) : numberWord(window[field], "firmWindows." + field, 32));
|
|
100
|
+
parts.push(type === "string" ? stringWord(window[field], "firmWindows." + field) : numberWord(window[field], "firmWindows." + field, 32));
|
|
89
101
|
}
|
|
90
102
|
return keccak256(concat(...parts));
|
|
91
103
|
}
|
|
@@ -94,11 +106,11 @@ export function nodeFeaturesStructHash(features) {
|
|
|
94
106
|
if (!features || typeof features !== "object") throw new SdkError("bad-input", { field: "features" });
|
|
95
107
|
const parts = [keccak256(utf8(NODE_FEATURES_TYPE))];
|
|
96
108
|
for (const [field, type] of NODE_FEATURES_FIELDS) {
|
|
97
|
-
if (type === "string") parts.push(stringWord(features[field]));
|
|
109
|
+
if (type === "string") parts.push(stringWord(features[field], "features." + field));
|
|
98
110
|
else if (type === "address") parts.push(addressWord(features[field], "features." + field));
|
|
99
111
|
else if (type === "bytes32") parts.push(hexBytes(features[field], "features." + field, 32));
|
|
100
112
|
else if (type === "uint64") parts.push(numberWord(features[field], "features." + field, 64));
|
|
101
|
-
else if (type === "string[]") parts.push(arrayWord(features[field], "features." + field, (value) => stringWord(value)));
|
|
113
|
+
else if (type === "string[]") parts.push(arrayWord(features[field], "features." + field, (value) => stringWord(value, "features." + field)));
|
|
102
114
|
else if (type === "FirmWindow[]") parts.push(arrayWord(features[field], "features." + field, firmWindowHash));
|
|
103
115
|
else throw new SdkError("bad-input", { field: "features." + field });
|
|
104
116
|
}
|
|
@@ -124,7 +136,7 @@ const bytesToHex = (bytes) => {
|
|
|
124
136
|
};
|
|
125
137
|
|
|
126
138
|
function recoverAddress(digest, signature) {
|
|
127
|
-
const sig =
|
|
139
|
+
const sig = wireText(signature === undefined || signature === null ? "" : signature, "signature").replace(/^0x/, "");
|
|
128
140
|
if (!/^[0-9a-fA-F]{130}$/.test(sig)) return null;
|
|
129
141
|
let v = parseInt(sig.slice(128, 130), 16);
|
|
130
142
|
if (v >= 27) v -= 27;
|
|
@@ -147,16 +159,16 @@ function recoverAddress(digest, signature) {
|
|
|
147
159
|
*/
|
|
148
160
|
export function verifyNodeFeatures({ features, terms = null } = {}) {
|
|
149
161
|
if (!features || typeof features !== "object") throw new SdkError("bad-input", { field: "features" });
|
|
150
|
-
if (features.type !== "node_features" ||
|
|
162
|
+
if (features.type !== "node_features" || wireNumber(features.version, "features.version") !== 1) {
|
|
151
163
|
throw new SdkError("quote-refused", { step: "features", why: "version" });
|
|
152
164
|
}
|
|
153
165
|
const digest = nodeFeaturesDigest(features);
|
|
154
166
|
const recovered = recoverAddress(digest, features.signature);
|
|
155
|
-
const quoteKey =
|
|
167
|
+
const quoteKey = wireText(features.quoteKey === undefined || features.quoteKey === null ? "" : features.quoteKey, "features.quoteKey").toLowerCase();
|
|
156
168
|
if (recovered === null || recovered !== quoteKey) {
|
|
157
169
|
throw new SdkError("quote-refused", { step: "features", why: "signature" });
|
|
158
170
|
}
|
|
159
|
-
const hpkeKey =
|
|
171
|
+
const hpkeKey = wireText(features.hpkeKey === undefined || features.hpkeKey === null ? "" : features.hpkeKey, "features.hpkeKey").replace(/^0x/, "").toLowerCase();
|
|
160
172
|
if (!/^[0-9a-f]{64}$/.test(hpkeKey) || /^0+$/.test(hpkeKey)) {
|
|
161
173
|
throw new SdkError("quote-refused", { step: "features", why: "hpke-key" });
|
|
162
174
|
}
|
|
@@ -164,8 +176,8 @@ export function verifyNodeFeatures({ features, terms = null } = {}) {
|
|
|
164
176
|
throw new SdkError("quote-refused", { step: "features", why: "windows" });
|
|
165
177
|
}
|
|
166
178
|
if (terms) {
|
|
167
|
-
if (
|
|
168
|
-
||
|
|
179
|
+
if (wireText(features.provider === undefined || features.provider === null ? "" : features.provider, "features.provider").toLowerCase() !== String(terms.maker || "").toLowerCase()
|
|
180
|
+
|| wireText(features.registry === undefined || features.registry === null ? "" : features.registry, "features.registry").toLowerCase() !== String(terms.registry || "").toLowerCase()) {
|
|
169
181
|
throw new SdkError("quote-refused", { step: "features", why: "identity" });
|
|
170
182
|
}
|
|
171
183
|
const market = String(terms.market || "");
|
package/src/relayFirmClient.mjs
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import { SdkError } from "./errors.mjs";
|
|
7
7
|
import { createHttp } from "./http.mjs";
|
|
8
8
|
import { buildFirmRequest } from "./relayRequest.mjs";
|
|
9
|
-
import { verifyFirmAnswer } from "./relayQuote.mjs";
|
|
9
|
+
import { verifyFirmAnswer, verifyRelayForwarded } from "./relayQuote.mjs";
|
|
10
10
|
|
|
11
11
|
const REFUSAL_CODES = new Set([
|
|
12
12
|
"compliance",
|
|
@@ -17,7 +17,14 @@ const REFUSAL_CODES = new Set([
|
|
|
17
17
|
"bad_request",
|
|
18
18
|
"price_changed",
|
|
19
19
|
]);
|
|
20
|
-
const
|
|
20
|
+
const wireText = (value, field) => {
|
|
21
|
+
if (typeof value === "string") return value;
|
|
22
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
23
|
+
if (typeof value === "bigint") return String(value);
|
|
24
|
+
throw new SdkError("bad-input", { field });
|
|
25
|
+
};
|
|
26
|
+
const sameRelay = (a, b) => (a === undefined || a === null ? "" : wireText(a, "relay")) ===
|
|
27
|
+
(b === undefined || b === null ? "" : wireText(b, "relay"));
|
|
21
28
|
|
|
22
29
|
/**
|
|
23
30
|
* Request a firm quote from a relay.
|
|
@@ -37,6 +44,9 @@ export async function requestFirmQuote({
|
|
|
37
44
|
} = {}) {
|
|
38
45
|
const base = String(relayUrl === undefined || relayUrl === null ? "" : relayUrl).trim().replace(/\/+$/, "");
|
|
39
46
|
if (!base) throw new SdkError("bad-input", { field: "relayUrl" });
|
|
47
|
+
// A QUOTE IS SIGNED FOR A RELAY ORIGIN, NOT FOR A PLAIN-TEXT HOP. An http:// base would let any middlebox read
|
|
48
|
+
// the sealed view material and change the relay's answer before the signature check.
|
|
49
|
+
if (!/^https:\/\//i.test(base)) throw new SdkError("bad-input", { field: "relayUrl", why: "not-https" });
|
|
40
50
|
|
|
41
51
|
const built = await buildFirmRequest(request);
|
|
42
52
|
const body = JSON.stringify({
|
|
@@ -86,7 +96,9 @@ export async function requestFirmQuote({
|
|
|
86
96
|
}
|
|
87
97
|
|
|
88
98
|
const answer = response.body && response.body.answer;
|
|
89
|
-
|
|
99
|
+
let envelopeVersion = null;
|
|
100
|
+
try { envelopeVersion = response.body ? Number(response.body.version) : null; } catch { envelopeVersion = null; }
|
|
101
|
+
if (!response.body || envelopeVersion !== 1 || !answer) {
|
|
90
102
|
throw new SdkError("quote-refused", { step: "answer", why: "envelope" });
|
|
91
103
|
}
|
|
92
104
|
if (typeof response.body.relay !== "string" || !response.body.relay
|
|
@@ -97,20 +109,34 @@ export async function requestFirmQuote({
|
|
|
97
109
|
throw new SdkError("quote-refused", { step: "answer", why: "relay" });
|
|
98
110
|
}
|
|
99
111
|
|
|
112
|
+
// THE RELAY'S OWN FORWARDED FRAME IS SIGNED AND BOUND TO THE CLIENT'S EXACT PAYLOAD. Checking it here, before
|
|
113
|
+
// the answer is used, closes the gap where a relay changed the forwarded payload/provider but returned a valid
|
|
114
|
+
// answer for another request.
|
|
115
|
+
verifyRelayForwarded({
|
|
116
|
+
forwarded: response.body.forwarded,
|
|
117
|
+
relayKey: published.relayKey,
|
|
118
|
+
payload: built.payload,
|
|
119
|
+
provider: request.features.provider,
|
|
120
|
+
requestHash: answer.requestHash === undefined || answer.requestHash === null ? "" : answer.requestHash,
|
|
121
|
+
});
|
|
100
122
|
const verified = verifyFirmAnswer({
|
|
101
123
|
answer,
|
|
102
124
|
features: request.features,
|
|
103
125
|
request: built,
|
|
104
126
|
});
|
|
105
|
-
const publishedRecipient =
|
|
106
|
-
const quoteRecipient =
|
|
127
|
+
const publishedRecipient = wireText(published.feeRecipient === undefined || published.feeRecipient === null ? "" : published.feeRecipient, "relay.feeRecipient").toLowerCase();
|
|
128
|
+
const quoteRecipient = wireText(verified.quote.feeRecipient === undefined || verified.quote.feeRecipient === null ? "" : verified.quote.feeRecipient, "quote.feeRecipient").toLowerCase();
|
|
107
129
|
if (!publishedRecipient || publishedRecipient !== quoteRecipient) {
|
|
108
130
|
throw new SdkError("quote-refused", { step: "fee", why: "fee-recipient" });
|
|
109
131
|
}
|
|
110
|
-
if (!partner &&
|
|
132
|
+
if (!partner && wireText(published.feeBps === undefined || published.feeBps === null ? "" : published.feeBps, "relay.feeBps") !==
|
|
133
|
+
wireText(verified.quote.feeBps === undefined || verified.quote.feeBps === null ? "" : verified.quote.feeBps, "quote.feeBps")) {
|
|
111
134
|
throw new SdkError("quote-refused", { step: "fee", why: "fee-bps" });
|
|
112
135
|
}
|
|
113
|
-
|
|
136
|
+
// THE RELAY MUST NAME ITSELF. A missing id on GET /v1/relay is not "nothing to compare": the answer's relay
|
|
137
|
+
// label would then be accepted without the one check that binds it.
|
|
138
|
+
if (published.relayId === undefined || published.relayId === null
|
|
139
|
+
|| wireText(published.relayId, "relay.relayId") !== wireText(response.body.relay, "relay")) {
|
|
114
140
|
throw new SdkError("quote-refused", { step: "relay-info", why: "relay" });
|
|
115
141
|
}
|
|
116
142
|
return {
|
package/src/relayQuote.mjs
CHANGED
|
@@ -15,7 +15,19 @@ const DOMAIN_TYPE = "EIP712Domain(string name,string version)";
|
|
|
15
15
|
const DOMAIN_NAME = "Ninsei Relay";
|
|
16
16
|
const DOMAIN_VERSION = "1";
|
|
17
17
|
|
|
18
|
-
const
|
|
18
|
+
const wireText = (value, field) => {
|
|
19
|
+
if (typeof value === "string") return value;
|
|
20
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
21
|
+
if (typeof value === "bigint") return String(value);
|
|
22
|
+
throw new SdkError("bad-input", { field });
|
|
23
|
+
};
|
|
24
|
+
const wireNumber = (value, field) => {
|
|
25
|
+
let n = null;
|
|
26
|
+
try { n = Number(value); } catch { n = null; }
|
|
27
|
+
if (!Number.isFinite(n)) throw new SdkError("bad-input", { field });
|
|
28
|
+
return n;
|
|
29
|
+
};
|
|
30
|
+
const utf8 = (value, field = "text") => new TextEncoder().encode(wireText(value, field));
|
|
19
31
|
const concat = (...arrays) => {
|
|
20
32
|
const total = arrays.reduce((n, a) => n + a.length, 0);
|
|
21
33
|
const out = new Uint8Array(total);
|
|
@@ -24,7 +36,7 @@ const concat = (...arrays) => {
|
|
|
24
36
|
return out;
|
|
25
37
|
};
|
|
26
38
|
const hexBytes = (value, field, width) => {
|
|
27
|
-
const text =
|
|
39
|
+
const text = wireText(value === undefined || value === null ? "" : value, field).replace(/^0x/, "");
|
|
28
40
|
if (!new RegExp("^[0-9a-fA-F]{" + width * 2 + "}$").test(text)) throw new SdkError("bad-input", { field });
|
|
29
41
|
const out = new Uint8Array(width);
|
|
30
42
|
for (let i = 0; i < width; i += 1) out[i] = parseInt(text.slice(i * 2, i * 2 + 2), 16);
|
|
@@ -44,19 +56,19 @@ const wordUint = (value, field) => {
|
|
|
44
56
|
for (let i = 31; i >= 0 && n > 0n; i -= 1) { out[i] = Number(n & 0xffn); n >>= 8n; }
|
|
45
57
|
return out;
|
|
46
58
|
};
|
|
47
|
-
const wordString = (value) => keccak256(utf8(value === undefined || value === null ? "" : value));
|
|
59
|
+
const wordString = (value, field) => keccak256(utf8(value === undefined || value === null ? "" : value, field));
|
|
48
60
|
|
|
49
61
|
export function relayQuoteStructHash(answer) {
|
|
50
62
|
if (!answer || typeof answer !== "object") throw new SdkError("bad-input", { field: "answer" });
|
|
51
63
|
return keccak256(concat(
|
|
52
64
|
keccak256(utf8(RELAY_QUOTE_TYPE)),
|
|
53
|
-
wordString(answer.relayId),
|
|
65
|
+
wordString(answer.relayId, "answer.relayId"),
|
|
54
66
|
wordAddress(answer.provider, "answer.provider"),
|
|
55
67
|
wordBytes32(answer.session, "answer.session"),
|
|
56
68
|
wordBytes32(answer.requestId, "answer.requestId"),
|
|
57
69
|
wordUint(answer.counter, "answer.counter"),
|
|
58
70
|
wordBytes32(answer.requestHash, "answer.requestHash"),
|
|
59
|
-
wordString(answer.payload),
|
|
71
|
+
wordString(answer.payload, "answer.payload"),
|
|
60
72
|
wordUint(answer.time, "answer.time"),
|
|
61
73
|
));
|
|
62
74
|
}
|
|
@@ -73,13 +85,73 @@ export function relayQuoteDigest(answer) {
|
|
|
73
85
|
return keccak256(concat(Uint8Array.from([0x19, 0x01]), relayQuoteDomainSeparator(), relayQuoteStructHash(answer)));
|
|
74
86
|
}
|
|
75
87
|
|
|
88
|
+
export const RELAY_REQUEST_TYPE =
|
|
89
|
+
"QuoteRequest(string relayId,address provider,bytes32 session,bytes32 requestId,uint64 counter,uint64 expiry,string payload,uint256 feeBps,address feeRecipient)";
|
|
90
|
+
|
|
91
|
+
export function relayRequestStructHash(request) {
|
|
92
|
+
if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "forwarded" });
|
|
93
|
+
return keccak256(concat(
|
|
94
|
+
keccak256(utf8(RELAY_REQUEST_TYPE)),
|
|
95
|
+
wordString(request.relayId, "forwarded.relayId"),
|
|
96
|
+
wordAddress(request.provider, "forwarded.provider"),
|
|
97
|
+
wordBytes32(request.session, "forwarded.session"),
|
|
98
|
+
wordBytes32(request.requestId, "forwarded.requestId"),
|
|
99
|
+
wordUint(request.counter, "forwarded.counter"),
|
|
100
|
+
wordUint(request.expiry, "forwarded.expiry"),
|
|
101
|
+
wordString(request.payload, "forwarded.payload"),
|
|
102
|
+
wordUint(request.feeBps, "forwarded.feeBps"),
|
|
103
|
+
wordAddress(request.feeRecipient, "forwarded.feeRecipient"),
|
|
104
|
+
));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function relayRequestDigest(request) {
|
|
108
|
+
return keccak256(concat(Uint8Array.from([0x19, 0x01]), relayQuoteDomainSeparator(), relayRequestStructHash(request)));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* THE FORWARDED REQUEST IS THE RELAY'S OWN SIGNED FRAME. The answer's `requestHash` is the digest of this
|
|
113
|
+
* object; without recomputing it, a relay could forward a different payload or maker while returning a
|
|
114
|
+
* correctly signed answer. The client always passes the answer's hash; a missing value becomes an empty
|
|
115
|
+
* string and fails the comparison.
|
|
116
|
+
*
|
|
117
|
+
* The frame's expiry and counter are not checked here. A fresh salt per request binds the payload, so a
|
|
118
|
+
* replayed old frame fails the payload comparison; the hash comparison then rejects a substituted one.
|
|
119
|
+
*/
|
|
120
|
+
export function verifyRelayForwarded({ forwarded, relayKey, payload, provider, requestHash = null } = {}) {
|
|
121
|
+
if (!forwarded || typeof forwarded !== "object" || forwarded.type !== "quote_request" ||
|
|
122
|
+
wireNumber(forwarded.version, "forwarded.version") !== 1) {
|
|
123
|
+
throw new SdkError("quote-refused", { step: "answer", why: "forwarded" });
|
|
124
|
+
}
|
|
125
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(String(relayKey || ""))) {
|
|
126
|
+
throw new SdkError("quote-refused", { step: "relay-info", why: "key" });
|
|
127
|
+
}
|
|
128
|
+
if (wireText(forwarded.payload === undefined || forwarded.payload === null ? "" : forwarded.payload,
|
|
129
|
+
"forwarded.payload") !== payload) {
|
|
130
|
+
throw new SdkError("quote-refused", { step: "answer", why: "forwarded-payload" });
|
|
131
|
+
}
|
|
132
|
+
if (!same(forwarded.provider, provider)) {
|
|
133
|
+
throw new SdkError("quote-refused", { step: "answer", why: "forwarded-provider" });
|
|
134
|
+
}
|
|
135
|
+
const recovered = recoverAddress(relayRequestDigest(forwarded), forwarded.signature);
|
|
136
|
+
if (recovered === null || recovered !== String(relayKey).toLowerCase()) {
|
|
137
|
+
throw new SdkError("quote-refused", { step: "answer", why: "forwarded-signature" });
|
|
138
|
+
}
|
|
139
|
+
if (requestHash !== null && requestHash !== undefined) {
|
|
140
|
+
const digest = hex(relayRequestDigest(forwarded));
|
|
141
|
+
if (!same(digest, requestHash)) {
|
|
142
|
+
throw new SdkError("quote-refused", { step: "answer", why: "forwarded-hash" });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return forwarded;
|
|
146
|
+
}
|
|
147
|
+
|
|
76
148
|
const hex = (bytes) => {
|
|
77
149
|
let out = "0x";
|
|
78
150
|
for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
|
|
79
151
|
return out;
|
|
80
152
|
};
|
|
81
153
|
function recoverAddress(digest, signature) {
|
|
82
|
-
const sig =
|
|
154
|
+
const sig = wireText(signature === undefined || signature === null ? "" : signature, "signature").replace(/^0x/, "");
|
|
83
155
|
if (!/^[0-9a-fA-F]{130}$/.test(sig)) return null;
|
|
84
156
|
let v = parseInt(sig.slice(128, 130), 16);
|
|
85
157
|
if (v >= 27) v -= 27;
|
|
@@ -97,7 +169,7 @@ function recoverAddress(digest, signature) {
|
|
|
97
169
|
|
|
98
170
|
// The outer frame: signed by the quote key in the relay domain.
|
|
99
171
|
export function verifyRelayQuoteFrame(answer, quoteKey) {
|
|
100
|
-
if (!answer || typeof answer !== "object" || answer.type !== "quote" ||
|
|
172
|
+
if (!answer || typeof answer !== "object" || answer.type !== "quote" || wireNumber(answer.version, "answer.version") !== 1) {
|
|
101
173
|
throw new SdkError("quote-refused", { step: "answer", why: "frame" });
|
|
102
174
|
}
|
|
103
175
|
const recovered = recoverAddress(relayQuoteDigest(answer), answer.signature);
|
|
@@ -108,7 +180,7 @@ export function verifyRelayQuoteFrame(answer, quoteKey) {
|
|
|
108
180
|
}
|
|
109
181
|
|
|
110
182
|
const ZERO = "0x" + "00".repeat(20);
|
|
111
|
-
const lower = (value) =>
|
|
183
|
+
const lower = (value) => wireText(value === undefined || value === null ? "" : value, "field").toLowerCase();
|
|
112
184
|
const same = (a, b) => lower(a) === lower(b);
|
|
113
185
|
|
|
114
186
|
function checkOrderQuote(quote, terms, nowSec) {
|
|
@@ -143,10 +215,15 @@ function checkOrderQuote(quote, terms, nowSec) {
|
|
|
143
215
|
throw new SdkError("quote-refused", { step: "answer", why: "fee" });
|
|
144
216
|
}
|
|
145
217
|
if (fee !== (amount * BigInt(bps)) / 10000n) throw new SdkError("quote-refused", { step: "answer", why: "fee" });
|
|
146
|
-
const validUntil =
|
|
218
|
+
const validUntil = wireNumber(quote.validUntil, "quote.validUntil");
|
|
147
219
|
if (!Number.isSafeInteger(validUntil) || validUntil <= nowSec) {
|
|
148
220
|
throw new SdkError("quote-expired", { step: "answer", validUntil: quote.validUntil });
|
|
149
221
|
}
|
|
222
|
+
const readyBy = wireNumber(order.readyBy, "order.readyBy");
|
|
223
|
+
const t1 = wireNumber(order.t1, "order.t1");
|
|
224
|
+
if (!Number.isSafeInteger(readyBy) || !Number.isSafeInteger(t1) || readyBy >= t1 || validUntil >= readyBy) {
|
|
225
|
+
throw new SdkError("quote-refused", { step: "answer", why: "validity", field: "validUntil" });
|
|
226
|
+
}
|
|
150
227
|
}
|
|
151
228
|
|
|
152
229
|
/**
|
|
@@ -164,7 +241,7 @@ export function verifyFirmAnswer({ answer, features, request, now = null } = {})
|
|
|
164
241
|
if (!payload || typeof payload !== "object" || !payload.quote) {
|
|
165
242
|
throw new SdkError("quote-refused", { step: "answer", why: "payload" });
|
|
166
243
|
}
|
|
167
|
-
if (payload.contextVersion !== "ninsei-order-v3" ||
|
|
244
|
+
if (payload.contextVersion !== "ninsei-order-v3" || wireNumber(payload.quoteVersion, "payload.quoteVersion") !== 10) {
|
|
168
245
|
throw new SdkError("quote-refused", { step: "answer", why: "version" });
|
|
169
246
|
}
|
|
170
247
|
if (!same(payload.factory, request.terms.order.factory)) {
|
package/src/relayView.mjs
CHANGED
|
@@ -66,9 +66,9 @@ export function relayViewInfo({ termsDigest, commitHalf, edPoint, edViewPointCli
|
|
|
66
66
|
// One sender context, one Seal. The relay spec forbids reusing an ephemeral key for another encryption, so
|
|
67
67
|
// the context is created here and never exposed.
|
|
68
68
|
export async function sealViewEnvelope({ hpkeKey, info, plaintext } = {}) {
|
|
69
|
-
//
|
|
70
|
-
//
|
|
71
|
-
// network or cryptographic work.
|
|
69
|
+
// Both current request paths seal 64 bytes: the node's view scalar followed by the client's. A 32-byte body is
|
|
70
|
+
// still accepted for older vectors, but no current request produces one; a caller that passes another length is
|
|
71
|
+
// refused before any network or cryptographic work.
|
|
72
72
|
const publicKey = hexToBytes(hpkeKey, 32, "hpkeKey");
|
|
73
73
|
const body = bytesOf(plaintext);
|
|
74
74
|
if (body.length !== 32 && body.length !== 64) {
|