@vordium/sdk 0.2.1 → 0.2.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/README.md +13 -5
- package/dist/cjs/client.js +7 -3
- package/dist/cjs/http.js +46 -0
- package/dist/cjs/index.js +1 -0
- package/dist/cjs/network.js +128 -10
- package/dist/cjs/nonce.js +7 -3
- package/dist/cjs/releaseRecord.js +833 -0
- package/dist/esm/client.d.ts +9 -3
- package/dist/esm/client.js +8 -4
- package/dist/esm/http.d.ts +6 -0
- package/dist/esm/http.js +46 -0
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.js +1 -0
- package/dist/esm/network.d.ts +60 -12
- package/dist/esm/network.js +126 -9
- package/dist/esm/nonce.d.ts +3 -1
- package/dist/esm/nonce.js +7 -3
- package/dist/esm/pins.d.ts +3 -1
- package/dist/esm/releaseRecord.d.ts +141 -0
- package/dist/esm/releaseRecord.js +819 -0
- package/package.json +3 -1
|
@@ -0,0 +1,819 @@
|
|
|
1
|
+
import { ed25519 } from '@noble/curves/ed25519';
|
|
2
|
+
import { sha1 } from '@noble/hashes/sha1';
|
|
3
|
+
import { sha256 } from '@noble/hashes/sha256';
|
|
4
|
+
import { sha512 } from '@noble/hashes/sha512';
|
|
5
|
+
import { VordiumError } from './errors.js';
|
|
6
|
+
import { defaultNonceStore, memoryNonceStore } from './nonce.js';
|
|
7
|
+
/**
|
|
8
|
+
* The signed release record: the genesis, chain id and deposit bridge of each network, signed by the release key.
|
|
9
|
+
*
|
|
10
|
+
* A network's identity is taken from `releases.json`, and only after its detached OpenPGP signature
|
|
11
|
+
* (`releases.json.asc`) verifies under the release key that ships in this package ({@link RELEASE_KEY}, fingerprint
|
|
12
|
+
* {@link RELEASE_KEY_FINGERPRINT}). The signature covers the exact bytes as served; the record is read from those same
|
|
13
|
+
* bytes only after the signature holds.
|
|
14
|
+
*
|
|
15
|
+
* The key is pinned by its fingerprint. Its expiry is read from its newest self-signature. When that expiry is near
|
|
16
|
+
* ({@link KEY_REFRESH_BEFORE_S}) or past, the key is read again from where it is served ({@link KEY_URLS}). A served copy
|
|
17
|
+
* is used only when it is the same key (same fingerprint and point) and its self-signature verifies under that key: its
|
|
18
|
+
* newest self-signature then gives the expiry. A revocation that verifies under the key refuses every record. Nothing
|
|
19
|
+
* else is taken from a served copy, and when none can be read the shipped key is used as it is.
|
|
20
|
+
*
|
|
21
|
+
* Everything else is checked here, with no other program: the ASCII armour (and its CRC-24), the version 4 signature packet (EdDSA over Ed25519, SHA-256 or SHA-512),
|
|
22
|
+
* its hashed subpackets, the issuer fingerprint, the signature hash over the data and the hashed trailer, and the
|
|
23
|
+
* Ed25519 signature itself (RFC 8032).
|
|
24
|
+
*/
|
|
25
|
+
/** The release key: every network record must be signed by it. */
|
|
26
|
+
export const RELEASE_KEY_FINGERPRINT = 'C5EB4728F660369CE519D834B48FB4B71EFD48AE';
|
|
27
|
+
export const RELEASE_KEY = `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
|
28
|
+
|
|
29
|
+
mDMEaqXHBhYJKwYBBAHaRw8BAQdA8NRFgXw3NaEYFesojdDl1TlSlk9O5bXhsM4i
|
|
30
|
+
o7k3e+q0J1ZvcmRpdW0gUmVsZWFzZXMgPHJlbGVhc2VzQHZvcmRpdW0uY29tPoi1
|
|
31
|
+
BBMWCgBdFiEExetHKPZgNpzlGdg0tI+0tx79SK4FAmqlxwYbFIAAAAAABAAObWFu
|
|
32
|
+
dTIsMi41KzEuMTIsMCwzAhsDBQkDwmcABQsJCAcCAiICBhUKCQgLAgQWAgMBAh4H
|
|
33
|
+
AheAAAoJELSPtLce/UiuMUgA/2VojVnml+DJHQ6xbxhnbrNeD5p8H4lXsVASdpvs
|
|
34
|
+
RsCIAQCkMr8M76++QNGj08s+apf7CDgEVwbBFo4shxsYAU+gDw==
|
|
35
|
+
=20lT
|
|
36
|
+
-----END PGP PUBLIC KEY BLOCK-----
|
|
37
|
+
`;
|
|
38
|
+
/** Where each named network's record is read, in order. The signature is read at the same address + ".asc". */
|
|
39
|
+
export const RELEASE_RECORD_URLS = Object.freeze({
|
|
40
|
+
mainnet: Object.freeze(['https://binaries.vordium.com/mainnet/releases.json', 'https://rpc.vordium.com/releases.json']),
|
|
41
|
+
testnet: Object.freeze(['https://binaries.vordium.com/testnet/releases.json']),
|
|
42
|
+
});
|
|
43
|
+
/** The record format this SDK reads. */
|
|
44
|
+
export const RELEASE_RECORD_SCHEMA = 'vordium.release-record/3';
|
|
45
|
+
/** Where the release key is served. Read only when the key's expiry is near or past (see {@link refreshKey}). */
|
|
46
|
+
export const KEY_URLS = Object.freeze([
|
|
47
|
+
'https://raw.githubusercontent.com/Vordium/security/main/release-key.asc',
|
|
48
|
+
'https://raw.githubusercontent.com/Vordium/node/main/pub_key.asc',
|
|
49
|
+
]);
|
|
50
|
+
/** The key is read again from {@link KEY_URLS} from this long (seconds) before its expiry. */
|
|
51
|
+
export const KEY_REFRESH_BEFORE_S = 30 * 86400;
|
|
52
|
+
/** A key read from {@link KEY_URLS} is used for this long (seconds) before it is read again. */
|
|
53
|
+
export const KEY_REFRESH_TTL_S = 6 * 3600;
|
|
54
|
+
/** A read that left an expired key as it was is tried again after this long (seconds). */
|
|
55
|
+
export const KEY_RETRY_S = 30;
|
|
56
|
+
const MAX_KEY_BYTES = 64 * 1024;
|
|
57
|
+
const MAX_RECORD_BYTES = 4 * 1024 * 1024;
|
|
58
|
+
const MAX_SIGNATURE_BYTES = 64 * 1024;
|
|
59
|
+
/** The release record cannot be used. `code` names the reason; the message is a plain sentence. */
|
|
60
|
+
export class RecordRefused extends VordiumError {
|
|
61
|
+
constructor(code, message) {
|
|
62
|
+
super(code, message);
|
|
63
|
+
this.name = 'RecordRefused';
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// ── ASCII armour and packets ─────────────────────────────────────────────────────────────────────────────────────
|
|
67
|
+
const enc = new TextEncoder();
|
|
68
|
+
const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
69
|
+
function b64decode(s) {
|
|
70
|
+
if (s.length % 4 !== 0 || !/^[A-Za-z0-9+/]*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(s))
|
|
71
|
+
return null;
|
|
72
|
+
const out = [];
|
|
73
|
+
let acc = 0;
|
|
74
|
+
let bits = 0;
|
|
75
|
+
for (const ch of s) {
|
|
76
|
+
if (ch === '=')
|
|
77
|
+
break;
|
|
78
|
+
acc = ((acc << 6) | B64.indexOf(ch)) & 0xffffff;
|
|
79
|
+
bits += 6;
|
|
80
|
+
if (bits >= 8) {
|
|
81
|
+
bits -= 8;
|
|
82
|
+
out.push((acc >> bits) & 0xff);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return Uint8Array.from(out);
|
|
86
|
+
}
|
|
87
|
+
export function crc24(data) {
|
|
88
|
+
let crc = 0xb704ce;
|
|
89
|
+
for (const byte of data) {
|
|
90
|
+
crc ^= byte << 16;
|
|
91
|
+
for (let i = 0; i < 8; i++) {
|
|
92
|
+
crc <<= 1;
|
|
93
|
+
if (crc & 0x1000000)
|
|
94
|
+
crc ^= 0x1864cfb;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return crc & 0xffffff;
|
|
98
|
+
}
|
|
99
|
+
const ascii = (x, what) => {
|
|
100
|
+
if (typeof x === 'string')
|
|
101
|
+
return x;
|
|
102
|
+
for (const b of x)
|
|
103
|
+
if (b > 0x7f)
|
|
104
|
+
throw new RecordRefused('bad_armour', `The ${what} is not ASCII armour.`);
|
|
105
|
+
return new TextDecoder().decode(x);
|
|
106
|
+
};
|
|
107
|
+
/** The bytes inside one ASCII-armoured block of `kind` ("PGP SIGNATURE", "PGP PUBLIC KEY BLOCK"). The CRC-24 line, when
|
|
108
|
+
* present, must match. Throws {@link RecordRefused}. */
|
|
109
|
+
export function dearmor(text, kind) {
|
|
110
|
+
const what = kind.toLowerCase();
|
|
111
|
+
const lines = ascii(text, 'signature file').split('\n').map((l) => l.replace(/\r$/, '').replace(/[ \t]+$/, ''));
|
|
112
|
+
while (lines.length && !lines[0])
|
|
113
|
+
lines.shift();
|
|
114
|
+
while (lines.length && !lines[lines.length - 1])
|
|
115
|
+
lines.pop();
|
|
116
|
+
if (lines.length < 3 || lines[0] !== `-----BEGIN ${kind}-----` || lines[lines.length - 1] !== `-----END ${kind}-----`) {
|
|
117
|
+
throw new RecordRefused('bad_armour', `The file is not one ASCII-armoured ${what}.`);
|
|
118
|
+
}
|
|
119
|
+
const body = lines.slice(1, -1);
|
|
120
|
+
let i = 0;
|
|
121
|
+
for (; i < body.length && body[i]; i++) {
|
|
122
|
+
if (!body[i].includes(': '))
|
|
123
|
+
throw new RecordRefused('bad_armour', `The armour of the ${what} has a header line that is not one.`);
|
|
124
|
+
}
|
|
125
|
+
if (i >= body.length)
|
|
126
|
+
throw new RecordRefused('bad_armour', `The armour of the ${what} has no blank line before its data.`);
|
|
127
|
+
const data = body.slice(i + 1);
|
|
128
|
+
let crcLine = null;
|
|
129
|
+
if (data.length && data[data.length - 1].startsWith('='))
|
|
130
|
+
crcLine = data.pop();
|
|
131
|
+
if (!data.length || data.some((l) => l.startsWith('-----'))) {
|
|
132
|
+
throw new RecordRefused('bad_armour', `The armour of the ${what} holds no data, or more than one block.`);
|
|
133
|
+
}
|
|
134
|
+
const raw = b64decode(data.join(''));
|
|
135
|
+
if (!raw || !raw.length)
|
|
136
|
+
throw new RecordRefused('bad_armour', `The armour of the ${what} is not valid base64.`);
|
|
137
|
+
if (crcLine !== null) {
|
|
138
|
+
const c = b64decode(crcLine.slice(1));
|
|
139
|
+
if (!c || c.length !== 3 || ((c[0] << 16) | (c[1] << 8) | c[2]) !== crc24(raw)) {
|
|
140
|
+
throw new RecordRefused('bad_armour', `The armour checksum (CRC-24) of the ${what} does not match its data: the file was damaged or changed.`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return raw;
|
|
144
|
+
}
|
|
145
|
+
const be = (b, i, n) => { let v = 0; for (let k = 0; k < n; k++)
|
|
146
|
+
v = v * 256 + b[i + k]; return v; };
|
|
147
|
+
const badPacket = () => new RecordRefused('bad_packet', 'The OpenPGP data is not well formed.');
|
|
148
|
+
/** `[tag, body]` of an OpenPGP packet sequence (old and new headers; partial lengths refused). */
|
|
149
|
+
function packets(raw) {
|
|
150
|
+
const out = [];
|
|
151
|
+
let i = 0;
|
|
152
|
+
while (i < raw.length) {
|
|
153
|
+
const ctb = raw[i++];
|
|
154
|
+
if (!(ctb & 0x80))
|
|
155
|
+
throw badPacket();
|
|
156
|
+
let tag, n;
|
|
157
|
+
if (ctb & 0x40) {
|
|
158
|
+
tag = ctb & 0x3f;
|
|
159
|
+
if (i >= raw.length)
|
|
160
|
+
throw badPacket();
|
|
161
|
+
const o = raw[i];
|
|
162
|
+
if (o < 192) {
|
|
163
|
+
n = o;
|
|
164
|
+
i += 1;
|
|
165
|
+
}
|
|
166
|
+
else if (o < 224) {
|
|
167
|
+
if (i + 1 >= raw.length)
|
|
168
|
+
throw badPacket();
|
|
169
|
+
n = ((o - 192) << 8) + raw[i + 1] + 192;
|
|
170
|
+
i += 2;
|
|
171
|
+
}
|
|
172
|
+
else if (o === 255) {
|
|
173
|
+
if (i + 4 >= raw.length)
|
|
174
|
+
throw badPacket();
|
|
175
|
+
n = be(raw, i + 1, 4);
|
|
176
|
+
i += 5;
|
|
177
|
+
}
|
|
178
|
+
else
|
|
179
|
+
throw new RecordRefused('bad_packet', 'The OpenPGP data uses partial lengths, which are not read here.');
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
tag = (ctb >> 2) & 0x0f;
|
|
183
|
+
const lt = ctb & 0x03;
|
|
184
|
+
if (lt === 3)
|
|
185
|
+
throw new RecordRefused('bad_packet', 'The OpenPGP data uses an indeterminate length, which is not read here.');
|
|
186
|
+
const w = [1, 2, 4][lt];
|
|
187
|
+
if (i + w > raw.length)
|
|
188
|
+
throw badPacket();
|
|
189
|
+
n = be(raw, i, w);
|
|
190
|
+
i += w;
|
|
191
|
+
}
|
|
192
|
+
if (i + n > raw.length)
|
|
193
|
+
throw badPacket();
|
|
194
|
+
out.push([tag, raw.subarray(i, i + n)]);
|
|
195
|
+
i += n;
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
function mpi(b, i) {
|
|
200
|
+
if (i + 2 > b.length)
|
|
201
|
+
throw badPacket();
|
|
202
|
+
const n = Math.ceil(be(b, i, 2) / 8);
|
|
203
|
+
if (i + 2 + n > b.length)
|
|
204
|
+
throw badPacket();
|
|
205
|
+
return [b.subarray(i + 2, i + 2 + n), i + 2 + n];
|
|
206
|
+
}
|
|
207
|
+
const ED25519_OID = Uint8Array.from([0x2b, 0x06, 0x01, 0x04, 0x01, 0xda, 0x47, 0x0f, 0x01]);
|
|
208
|
+
const EDDSA_LEGACY = 22;
|
|
209
|
+
const HASHES = { 8: sha256, 10: sha512 };
|
|
210
|
+
const hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('').toUpperCase();
|
|
211
|
+
const concat = (...xs) => { const o = new Uint8Array(xs.reduce((a, x) => a + x.length, 0)); let i = 0; for (const x of xs) {
|
|
212
|
+
o.set(x, i);
|
|
213
|
+
i += x.length;
|
|
214
|
+
} return o; };
|
|
215
|
+
const u32 = (n) => Uint8Array.from([(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff]);
|
|
216
|
+
const eq = (a, b) => a.length === b.length && a.every((x, k) => x === b[k]);
|
|
217
|
+
/** A version 4 EdDSA signature packet of one of `types`, with its hashed subpackets read. */
|
|
218
|
+
function parseSig(b, types) {
|
|
219
|
+
if (!b.length)
|
|
220
|
+
throw new RecordRefused('bad_packet', 'The OpenPGP signature is empty.');
|
|
221
|
+
if (b[0] !== 4)
|
|
222
|
+
throw new RecordRefused('unsupported', `The signature is a version ${b[0]} OpenPGP signature; only version 4 signatures are accepted.`);
|
|
223
|
+
if (b.length < 6)
|
|
224
|
+
throw badPacket();
|
|
225
|
+
const [sigType, pkAlgo, hashAlgo] = [b[1], b[2], b[3]];
|
|
226
|
+
if (!types.includes(sigType))
|
|
227
|
+
throw new RecordRefused('unsupported', 'The signature is not a binary-document signature over the exact bytes.');
|
|
228
|
+
if (pkAlgo !== EDDSA_LEGACY)
|
|
229
|
+
throw new RecordRefused('unsupported', `The signature uses public-key algorithm ${pkAlgo}; only Ed25519 (EdDSA) signatures are accepted.`);
|
|
230
|
+
const hash = HASHES[hashAlgo];
|
|
231
|
+
if (!hash)
|
|
232
|
+
throw new RecordRefused('unsupported', `The signature uses hash algorithm ${hashAlgo}; only SHA-256 and SHA-512 are accepted.`);
|
|
233
|
+
const hashedEnd = 6 + be(b, 4, 2);
|
|
234
|
+
if (hashedEnd + 2 > b.length)
|
|
235
|
+
throw badPacket();
|
|
236
|
+
const hashed = b.subarray(6, hashedEnd);
|
|
237
|
+
const i = hashedEnd + 2 + be(b, hashedEnd, 2);
|
|
238
|
+
if (i + 2 > b.length)
|
|
239
|
+
throw badPacket();
|
|
240
|
+
const left16 = b.subarray(i, i + 2);
|
|
241
|
+
const [r, i2] = mpi(b, i + 2);
|
|
242
|
+
const [s, i3] = mpi(b, i2);
|
|
243
|
+
if (i3 !== b.length || r.length > 32 || s.length > 32)
|
|
244
|
+
throw badPacket();
|
|
245
|
+
let created = null;
|
|
246
|
+
let expires = null;
|
|
247
|
+
let keyExpires = null;
|
|
248
|
+
let issuer = null;
|
|
249
|
+
for (const [t, critical, val] of subpackets(hashed)) {
|
|
250
|
+
if (t === 2) {
|
|
251
|
+
if (created !== null || val.length !== 4)
|
|
252
|
+
throw new RecordRefused('bad_packet', "The signature's creation time is not well formed.");
|
|
253
|
+
created = be(val, 0, 4);
|
|
254
|
+
}
|
|
255
|
+
else if (t === 3) {
|
|
256
|
+
if (expires !== null || val.length !== 4)
|
|
257
|
+
throw new RecordRefused('bad_packet', "The signature's expiry is not well formed.");
|
|
258
|
+
expires = be(val, 0, 4);
|
|
259
|
+
}
|
|
260
|
+
else if (t === 9) {
|
|
261
|
+
if (keyExpires !== null || val.length !== 4)
|
|
262
|
+
throw new RecordRefused('bad_packet', "The key's expiry is not well formed.");
|
|
263
|
+
keyExpires = be(val, 0, 4);
|
|
264
|
+
}
|
|
265
|
+
else if (t === 33) {
|
|
266
|
+
if (issuer !== null || val.length !== 21 || val[0] !== 4)
|
|
267
|
+
throw new RecordRefused('bad_packet', "The signature's issuer fingerprint is not a version 4 fingerprint.");
|
|
268
|
+
issuer = hex(val.subarray(1));
|
|
269
|
+
}
|
|
270
|
+
else if (critical) {
|
|
271
|
+
throw new RecordRefused('unsupported', `The signature carries a critical subpacket (${t}) that is not read here.`);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (created === null)
|
|
275
|
+
throw new RecordRefused('bad_packet', 'The signature names no creation time.');
|
|
276
|
+
return { head: b.subarray(0, hashedEnd), hash, left16, r, s, created, expires, keyExpires, issuer };
|
|
277
|
+
}
|
|
278
|
+
/** Whether `sig` is a valid signature by `point` over `data` (the v4 hash: data, the hashed part, the trailer). */
|
|
279
|
+
function sigOk(sig, data, point) {
|
|
280
|
+
const digest = sig.hash(concat(data, sig.head, Uint8Array.from([0x04, 0xff]), u32(sig.head.length)));
|
|
281
|
+
const sig64 = new Uint8Array(64);
|
|
282
|
+
sig64.set(sig.r, 32 - sig.r.length);
|
|
283
|
+
sig64.set(sig.s, 64 - sig.s.length);
|
|
284
|
+
try {
|
|
285
|
+
return eq(digest.subarray(0, 2), sig.left16) && ed25519.verify(sig64, digest, point, { zip215: false });
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
/** The primary key of an armoured public key block. The fingerprint is computed from the key packet (SHA-1 over
|
|
292
|
+
* 0x99 || length || packet). Only a version 4 EdDSA key on Ed25519 is accepted, with at least one user ID whose
|
|
293
|
+
* self-signature verifies; the newest such self-signature gives the key's expiry. */
|
|
294
|
+
export function parsePublicKey(armoured) {
|
|
295
|
+
const pk = packets(dearmor(armoured, 'PGP PUBLIC KEY BLOCK'));
|
|
296
|
+
if (!pk.length || pk[0][0] !== 6)
|
|
297
|
+
throw new RecordRefused('bad_key', 'The release key is not an OpenPGP public key.');
|
|
298
|
+
const body = pk[0][1];
|
|
299
|
+
if (body.length < 7 || body[0] !== 4)
|
|
300
|
+
throw new RecordRefused('bad_key', 'The release key is not a version 4 OpenPGP key.');
|
|
301
|
+
if (body[5] !== EDDSA_LEGACY)
|
|
302
|
+
throw new RecordRefused('bad_key', 'The release key is not an Ed25519 key.');
|
|
303
|
+
const oidLen = body[6];
|
|
304
|
+
if (!eq(body.subarray(7, 7 + oidLen), ED25519_OID))
|
|
305
|
+
throw new RecordRefused('bad_key', 'The release key is not an Ed25519 key.');
|
|
306
|
+
const [pt, end] = mpi(body, 7 + oidLen);
|
|
307
|
+
if (end !== body.length || pt.length !== 33 || pt[0] !== 0x40)
|
|
308
|
+
throw new RecordRefused('bad_key', 'The release key is not well formed.');
|
|
309
|
+
const point = pt.slice(1);
|
|
310
|
+
const keyPrefix = concat(Uint8Array.from([0x99, (body.length >> 8) & 0xff, body.length & 0xff]), body);
|
|
311
|
+
const fp = hex(sha1(keyPrefix));
|
|
312
|
+
let best = null;
|
|
313
|
+
let uid = null;
|
|
314
|
+
let inSubkey = false;
|
|
315
|
+
let revoked = false;
|
|
316
|
+
for (const [tag, pbody] of pk.slice(1)) {
|
|
317
|
+
if (tag === 14) {
|
|
318
|
+
uid = null;
|
|
319
|
+
inSubkey = true;
|
|
320
|
+
continue;
|
|
321
|
+
} // a subkey: its signatures are not about the primary key
|
|
322
|
+
if (tag === 13) {
|
|
323
|
+
uid = pbody;
|
|
324
|
+
inSubkey = false;
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if (tag === 2 && !uid && !inSubkey) { // a signature on the key itself: only revocation is read
|
|
328
|
+
let rev;
|
|
329
|
+
try {
|
|
330
|
+
rev = parseSig(pbody, [0x20]);
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
if (rev.issuer === fp && sigOk(rev, keyPrefix, point))
|
|
336
|
+
revoked = true;
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
if (tag !== 2 || !uid)
|
|
340
|
+
continue;
|
|
341
|
+
let sig;
|
|
342
|
+
try {
|
|
343
|
+
sig = parseSig(pbody, [0x10, 0x11, 0x12, 0x13]);
|
|
344
|
+
}
|
|
345
|
+
catch {
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
if (sig.issuer !== fp)
|
|
349
|
+
continue;
|
|
350
|
+
if (!sigOk(sig, concat(keyPrefix, Uint8Array.from([0xb4]), u32(uid.length), uid), point))
|
|
351
|
+
continue;
|
|
352
|
+
if (!best || sig.created >= best.created)
|
|
353
|
+
best = { created: sig.created, keyExpires: sig.keyExpires };
|
|
354
|
+
}
|
|
355
|
+
if (!best)
|
|
356
|
+
throw new RecordRefused('bad_key', 'The release key carries no self-signature that verifies.');
|
|
357
|
+
return { fingerprint: fp, point, expires: best.keyExpires ? be(body, 1, 4) + best.keyExpires : null, signedAt: best.created, revoked };
|
|
358
|
+
}
|
|
359
|
+
function subpackets(area) {
|
|
360
|
+
const out = [];
|
|
361
|
+
const bad = () => new RecordRefused('bad_packet', "The signature's subpackets are not well formed.");
|
|
362
|
+
let i = 0;
|
|
363
|
+
while (i < area.length) {
|
|
364
|
+
const o = area[i];
|
|
365
|
+
let n;
|
|
366
|
+
if (o < 192) {
|
|
367
|
+
n = o;
|
|
368
|
+
i += 1;
|
|
369
|
+
}
|
|
370
|
+
else if (o < 255) {
|
|
371
|
+
if (i + 1 >= area.length)
|
|
372
|
+
throw bad();
|
|
373
|
+
n = ((o - 192) << 8) + area[i + 1] + 192;
|
|
374
|
+
i += 2;
|
|
375
|
+
}
|
|
376
|
+
else {
|
|
377
|
+
if (i + 4 >= area.length)
|
|
378
|
+
throw bad();
|
|
379
|
+
n = be(area, i + 1, 4);
|
|
380
|
+
i += 5;
|
|
381
|
+
}
|
|
382
|
+
if (n < 1 || i + n > area.length)
|
|
383
|
+
throw bad();
|
|
384
|
+
out.push([area[i] & 0x7f, (area[i] & 0x80) !== 0, area.subarray(i + 1, i + n)]);
|
|
385
|
+
i += n;
|
|
386
|
+
}
|
|
387
|
+
return out;
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Verify an armoured detached signature over the exact bytes `data` under one of `keys` (the pinned keys). Returns the
|
|
391
|
+
* signature's issuer and time; throws {@link RecordRefused} with a plain sentence otherwise.
|
|
392
|
+
*/
|
|
393
|
+
export function verifyDetached(data, armouredSig, keys, nowSec = Date.now() / 1000) {
|
|
394
|
+
if (!keys.length)
|
|
395
|
+
throw new RecordRefused('no_key', 'No release key is pinned, so no record can be trusted.');
|
|
396
|
+
const pk = packets(dearmor(armouredSig, 'PGP SIGNATURE'));
|
|
397
|
+
if (pk.length !== 1 || pk[0][0] !== 2)
|
|
398
|
+
throw new RecordRefused('bad_packet', 'The signature file must hold exactly one OpenPGP signature.');
|
|
399
|
+
const sig = parseSig(pk[0][1], [0x00]);
|
|
400
|
+
const issuer = sig.issuer;
|
|
401
|
+
if (issuer === null)
|
|
402
|
+
throw new RecordRefused('wrong_key', 'The signature does not name the fingerprint of the key that made it, so it cannot be matched to the release key.');
|
|
403
|
+
const key = keys.find((k) => k.fingerprint === issuer);
|
|
404
|
+
if (!key)
|
|
405
|
+
throw new RecordRefused('wrong_key', `The record is signed by key ${issuer}, not by the release key ${keys[0].fingerprint}. It is not used.`);
|
|
406
|
+
if (!sigOk(sig, data, key.point))
|
|
407
|
+
throw new RecordRefused('bad_signature', "The record's signature does not verify under the release key: the record was changed after it was signed, or the signature is damaged. It is not used.");
|
|
408
|
+
if (key.revoked)
|
|
409
|
+
throw new RecordRefused('key_revoked', `The release key ${key.fingerprint} has been revoked by its owner. The record is not used.`);
|
|
410
|
+
if (sig.expires && sig.created + sig.expires < nowSec)
|
|
411
|
+
throw new RecordRefused('signature_expired', "The record's signature has expired. It is not used.");
|
|
412
|
+
if (key.expires !== null && nowSec > key.expires) {
|
|
413
|
+
throw new RecordRefused('key_expired', `The release key ${key.fingerprint} expired at ${new Date(key.expires * 1000).toISOString().slice(0, 16).replace('T', ' ')} UTC, and no served copy of it gives a later expiry. The record is not used.`);
|
|
414
|
+
}
|
|
415
|
+
return { fingerprint: issuer, created: sig.created };
|
|
416
|
+
}
|
|
417
|
+
const malformed = (what) => new RecordRefused('malformed', `The signed release record is not well formed: ${what}. It is not used.`);
|
|
418
|
+
/** JSON.parse that refuses a key given twice in one object (two readers could otherwise take different values). */
|
|
419
|
+
export function parseStrictJson(text) {
|
|
420
|
+
let i = 0;
|
|
421
|
+
const ws = () => { while (i < text.length && ' \t\n\r'.includes(text[i]))
|
|
422
|
+
i++; };
|
|
423
|
+
const fail = () => { throw malformed('it is not JSON'); };
|
|
424
|
+
const str = () => {
|
|
425
|
+
const start = i;
|
|
426
|
+
i++;
|
|
427
|
+
while (i < text.length && text[i] !== '"') {
|
|
428
|
+
if (text[i] === '\\')
|
|
429
|
+
i++;
|
|
430
|
+
i++;
|
|
431
|
+
}
|
|
432
|
+
if (i >= text.length)
|
|
433
|
+
fail();
|
|
434
|
+
i++;
|
|
435
|
+
try {
|
|
436
|
+
return JSON.parse(text.slice(start, i));
|
|
437
|
+
}
|
|
438
|
+
catch {
|
|
439
|
+
return fail();
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
const value = () => {
|
|
443
|
+
ws();
|
|
444
|
+
const c = text[i];
|
|
445
|
+
if (c === '{') {
|
|
446
|
+
i++;
|
|
447
|
+
const o = Object.create(null);
|
|
448
|
+
ws();
|
|
449
|
+
if (text[i] === '}') {
|
|
450
|
+
i++;
|
|
451
|
+
return o;
|
|
452
|
+
}
|
|
453
|
+
for (;;) {
|
|
454
|
+
ws();
|
|
455
|
+
if (text[i] !== '"')
|
|
456
|
+
fail();
|
|
457
|
+
const k = str();
|
|
458
|
+
if (Object.prototype.hasOwnProperty.call(o, k))
|
|
459
|
+
throw malformed(`the key "${k}" appears twice`);
|
|
460
|
+
ws();
|
|
461
|
+
if (text[i++] !== ':')
|
|
462
|
+
fail();
|
|
463
|
+
o[k] = value();
|
|
464
|
+
ws();
|
|
465
|
+
if (text[i] === ',') {
|
|
466
|
+
i++;
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
if (text[i] === '}') {
|
|
470
|
+
i++;
|
|
471
|
+
return o;
|
|
472
|
+
}
|
|
473
|
+
fail();
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (c === '[') {
|
|
477
|
+
i++;
|
|
478
|
+
const a = [];
|
|
479
|
+
ws();
|
|
480
|
+
if (text[i] === ']') {
|
|
481
|
+
i++;
|
|
482
|
+
return a;
|
|
483
|
+
}
|
|
484
|
+
for (;;) {
|
|
485
|
+
a.push(value());
|
|
486
|
+
ws();
|
|
487
|
+
if (text[i] === ',') {
|
|
488
|
+
i++;
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
if (text[i] === ']') {
|
|
492
|
+
i++;
|
|
493
|
+
return a;
|
|
494
|
+
}
|
|
495
|
+
fail();
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
if (c === '"')
|
|
499
|
+
return str();
|
|
500
|
+
// whole numbers only: the record holds no other kind, and both SDKs read a number the same way
|
|
501
|
+
const m = /^(?:-?(?:0|[1-9][0-9]*)(?![.eE])|true|false|null)/.exec(text.slice(i));
|
|
502
|
+
if (!m)
|
|
503
|
+
fail();
|
|
504
|
+
i += m[0].length;
|
|
505
|
+
return JSON.parse(m[0]);
|
|
506
|
+
};
|
|
507
|
+
let v;
|
|
508
|
+
try {
|
|
509
|
+
v = value();
|
|
510
|
+
}
|
|
511
|
+
catch (e) {
|
|
512
|
+
if (e instanceof RangeError)
|
|
513
|
+
fail();
|
|
514
|
+
throw e;
|
|
515
|
+
} // nesting deeper than the stack
|
|
516
|
+
ws();
|
|
517
|
+
if (i !== text.length)
|
|
518
|
+
fail();
|
|
519
|
+
return v;
|
|
520
|
+
}
|
|
521
|
+
const isObj = (x) => !!x && typeof x === 'object' && !Array.isArray(x);
|
|
522
|
+
function whole(v, what) {
|
|
523
|
+
if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0)
|
|
524
|
+
throw malformed(`${what} is not a whole number`);
|
|
525
|
+
return v;
|
|
526
|
+
}
|
|
527
|
+
function time(v, what) {
|
|
528
|
+
const m = typeof v === 'string' ? /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/.exec(v) : null;
|
|
529
|
+
if (!m)
|
|
530
|
+
throw malformed(`${what} is not a time like 2026-01-01T00:00:00Z`);
|
|
531
|
+
const [y, mo, d, h, mi, s] = m.slice(1).map(Number);
|
|
532
|
+
const t = Date.UTC(y, mo - 1, d, h, mi, s);
|
|
533
|
+
const back = new Date(t);
|
|
534
|
+
if (back.getUTCFullYear() !== y || back.getUTCMonth() !== mo - 1 || back.getUTCDate() !== d || h > 23 || mi > 59 || s > 59)
|
|
535
|
+
throw malformed(`${what} is not a real date`);
|
|
536
|
+
return t / 1000;
|
|
537
|
+
}
|
|
538
|
+
function addr(v, what) {
|
|
539
|
+
if (typeof v !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(v))
|
|
540
|
+
throw malformed(`${what} is not an address`);
|
|
541
|
+
return v.toLowerCase();
|
|
542
|
+
}
|
|
543
|
+
function gen(v, what) {
|
|
544
|
+
if (typeof v !== 'string' || !/^[0-9a-f]{64}$/.test(v))
|
|
545
|
+
throw malformed(`${what} is not 64 lower-case hex characters`);
|
|
546
|
+
return v;
|
|
547
|
+
}
|
|
548
|
+
// ignoreBOM keeps a byte-order mark in the text, so it is refused as it is by the Python SDK
|
|
549
|
+
const utf8 = (data) => { try {
|
|
550
|
+
return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(data);
|
|
551
|
+
}
|
|
552
|
+
catch {
|
|
553
|
+
return null;
|
|
554
|
+
} };
|
|
555
|
+
/** Whether bytes that could not be verified claim to be a network record (a JSON object with `networks`). Used only to
|
|
556
|
+
* tell an unsigned record (refused) from another file (ignored); no value of it is ever used. */
|
|
557
|
+
export function isNetworkRecord(data) {
|
|
558
|
+
const t = utf8(data);
|
|
559
|
+
if (t === null)
|
|
560
|
+
return false;
|
|
561
|
+
try {
|
|
562
|
+
const j = JSON.parse(t);
|
|
563
|
+
return isObj(j) && 'networks' in j;
|
|
564
|
+
}
|
|
565
|
+
catch {
|
|
566
|
+
return false;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
/** The record in the VERIFIED bytes `data`. Null when the file is not a network record (it has no `networks`: the
|
|
570
|
+
* release list of an earlier format). Throws {@link RecordRefused} for a record that is not well formed. */
|
|
571
|
+
export function parseRecord(data, signedBy = '') {
|
|
572
|
+
const t = utf8(data);
|
|
573
|
+
if (t === null)
|
|
574
|
+
throw malformed('it is not UTF-8 text');
|
|
575
|
+
const j = parseStrictJson(t);
|
|
576
|
+
if (!isObj(j) || !('networks' in j))
|
|
577
|
+
return null;
|
|
578
|
+
if (j.schema !== RELEASE_RECORD_SCHEMA) {
|
|
579
|
+
throw new RecordRefused('schema', `The signed release record has schema ${JSON.stringify(j.schema)}; this SDK reads "${RELEASE_RECORD_SCHEMA}". Update the SDK. It is not used.`);
|
|
580
|
+
}
|
|
581
|
+
const sequence = whole(j.sequence, 'sequence');
|
|
582
|
+
const issuedAt = time(j.issued_at, 'issued_at');
|
|
583
|
+
const validUntil = time(j.valid_until, 'valid_until');
|
|
584
|
+
if (validUntil < issuedAt)
|
|
585
|
+
throw malformed('valid_until is before issued_at');
|
|
586
|
+
if (!isObj(j.networks) || !Object.keys(j.networks).length)
|
|
587
|
+
throw malformed('networks lists no network');
|
|
588
|
+
const networks = new Map();
|
|
589
|
+
for (const [key, e] of Object.entries(j.networks)) {
|
|
590
|
+
if (!isObj(e))
|
|
591
|
+
throw malformed(`network ${key} is not an object`);
|
|
592
|
+
const chainId = whole(e.chain_id, `network ${key} chain_id`);
|
|
593
|
+
if (chainId <= 0 || key !== String(chainId))
|
|
594
|
+
throw malformed(`network ${key} is listed under another chain id than its own (${chainId})`);
|
|
595
|
+
const genesis = gen(e.genesis_sha256, `network ${key} genesis_sha256`);
|
|
596
|
+
const b = e.bridge;
|
|
597
|
+
if (!isObj(b))
|
|
598
|
+
throw malformed(`network ${key} names no bridge`);
|
|
599
|
+
const bcid = whole(b.chain_id, `network ${key} bridge chain_id`);
|
|
600
|
+
if (bcid <= 0)
|
|
601
|
+
throw malformed(`network ${key} bridge chain_id is not a chain id`);
|
|
602
|
+
const bridge = Object.freeze({ chainId: bcid, vault: addr(b.vault, `network ${key} bridge vault`), handler: addr(b.handler, `network ${key} bridge handler`), usdc: addr(b.usdc, `network ${key} bridge usdc`) });
|
|
603
|
+
const rg = e.retired_genesis ?? [];
|
|
604
|
+
if (!Array.isArray(rg))
|
|
605
|
+
throw malformed(`network ${key} retired_genesis is not a list`);
|
|
606
|
+
const past = Object.freeze(rg.map((x) => gen(x, `network ${key} retired_genesis`)));
|
|
607
|
+
if (past.includes(genesis))
|
|
608
|
+
throw malformed(`network ${key} lists its own genesis in retired_genesis`);
|
|
609
|
+
networks.set(chainId, Object.freeze({ chainId, genesis, bridge, retiredGenesis: past, name: typeof e.name === 'string' ? e.name : null }));
|
|
610
|
+
}
|
|
611
|
+
return Object.freeze({ sequence, issuedAt, validUntil, networks, signedBy });
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* `key` as its newest served copy states it. A copy at `urls` (default {@link KEY_URLS}, through `transport.getBytes`) is
|
|
615
|
+
* used only when it parses as the same key (same fingerprint and point, a self-signature that verifies under that key)
|
|
616
|
+
* and its newest self-signature is newer than the one `key` was read from; a copy carrying a revocation that verifies
|
|
617
|
+
* under the key gives the key as revoked. A copy that cannot be read, is another key or is older is skipped; with none
|
|
618
|
+
* usable, `key` is returned as it is.
|
|
619
|
+
*/
|
|
620
|
+
export async function refreshKey(key, opts) {
|
|
621
|
+
let best = key;
|
|
622
|
+
for (const url of opts.urls ?? KEY_URLS) {
|
|
623
|
+
let k;
|
|
624
|
+
try {
|
|
625
|
+
const data = await fetchBytes(opts.transport, url, opts.timeoutMs ?? 10000, MAX_KEY_BYTES);
|
|
626
|
+
if (!data)
|
|
627
|
+
continue;
|
|
628
|
+
k = parsePublicKey(data);
|
|
629
|
+
}
|
|
630
|
+
catch {
|
|
631
|
+
continue;
|
|
632
|
+
}
|
|
633
|
+
if (k.fingerprint !== key.fingerprint || !eq(k.point, key.point))
|
|
634
|
+
continue;
|
|
635
|
+
if (k.revoked)
|
|
636
|
+
return k;
|
|
637
|
+
if (k.signedAt > best.signedAt)
|
|
638
|
+
best = k;
|
|
639
|
+
}
|
|
640
|
+
return best;
|
|
641
|
+
}
|
|
642
|
+
// The shipped key as last read from where it is served, per transport: [read again after (s), key].
|
|
643
|
+
const refreshed = new WeakMap();
|
|
644
|
+
let shippedPoint = null;
|
|
645
|
+
/** `key` with its expiry refreshed when it is the shipped release key and its expiry is near or past; else as given. A
|
|
646
|
+
* refresh starts from the newest copy read before on this transport, so a read that fails never takes back a later
|
|
647
|
+
* expiry; it is done again after {@link KEY_REFRESH_TTL_S}, or after {@link KEY_RETRY_S} while the key it gives has
|
|
648
|
+
* expired. */
|
|
649
|
+
async function keyNow(key, t, ms, nowSec) {
|
|
650
|
+
shippedPoint ??= parsePublicKey(RELEASE_KEY).point;
|
|
651
|
+
if (key.fingerprint !== RELEASE_KEY_FINGERPRINT || !eq(key.point, shippedPoint))
|
|
652
|
+
return key;
|
|
653
|
+
if (key.expires === null || nowSec < key.expires - KEY_REFRESH_BEFORE_S)
|
|
654
|
+
return key;
|
|
655
|
+
const hit = refreshed.get(t);
|
|
656
|
+
// start from the newest copy read before, so a read that fails never takes back a later expiry
|
|
657
|
+
const seed = hit && hit[1].signedAt >= key.signedAt ? hit[1] : key;
|
|
658
|
+
if (hit && seed === hit[1] && nowSec < hit[0])
|
|
659
|
+
return seed;
|
|
660
|
+
let r = await refreshKey(seed, { transport: t, timeoutMs: ms });
|
|
661
|
+
const now = refreshed.get(t); // another read may have finished meanwhile
|
|
662
|
+
if (now && (now[1].revoked || (now[1].signedAt > r.signedAt && !r.revoked)))
|
|
663
|
+
r = now[1]; // a revocation stays
|
|
664
|
+
const expired = r.expires !== null && nowSec > r.expires && !r.revoked;
|
|
665
|
+
refreshed.set(t, [nowSec + (expired ? KEY_RETRY_S : KEY_REFRESH_TTL_S), r]);
|
|
666
|
+
return r;
|
|
667
|
+
}
|
|
668
|
+
/** The keys a record must be signed by: the shipped release key, or (tests only) the armoured keys given. The shipped
|
|
669
|
+
* key's expiry is refreshed by {@link readRecord} from its served copy when near or past (see {@link refreshKey}). */
|
|
670
|
+
export function pinnedKeys(releaseKeys) {
|
|
671
|
+
if (releaseKeys === undefined) {
|
|
672
|
+
const k = parsePublicKey(RELEASE_KEY);
|
|
673
|
+
if (k.fingerprint !== RELEASE_KEY_FINGERPRINT)
|
|
674
|
+
throw new RecordRefused('bad_key', 'The shipped release key does not have the shipped fingerprint.');
|
|
675
|
+
return [k];
|
|
676
|
+
}
|
|
677
|
+
if (!releaseKeys.length)
|
|
678
|
+
throw new RecordRefused('no_key', 'No release key was given, so no record can be trusted.');
|
|
679
|
+
return releaseKeys.map((x) => parsePublicKey(x));
|
|
680
|
+
}
|
|
681
|
+
// The mark is the sequence + 1 (0 = none seen). Its own file name: the Python SDK keeps the plain sequence under
|
|
682
|
+
// release-record.<fp>.<chain>, behind a lock file of its own.
|
|
683
|
+
const stateKey = (fp, chainId) => `release-record-mark.${fp.slice(0, 16).toLowerCase()}.${chainId}`;
|
|
684
|
+
// When the state folder cannot be written (a read-only home), the marks are kept in this process only. A mark that
|
|
685
|
+
// cannot be read, or a lock that is not given, refuses.
|
|
686
|
+
const fallback = memoryNonceStore();
|
|
687
|
+
const NO_FOLDER = new Set(['EACCES', 'EROFS', 'EPERM', 'ENOENT', 'ENOTDIR']);
|
|
688
|
+
/** The mark stored at `store.where(key)`, read without the lock: 0 when there is none; refuses when it is there but
|
|
689
|
+
* cannot be read. */
|
|
690
|
+
async function storedMark(store, key) {
|
|
691
|
+
const file = store.where?.(key);
|
|
692
|
+
if (!file)
|
|
693
|
+
return 0;
|
|
694
|
+
const fs = (await import('node:fs/promises'));
|
|
695
|
+
let text;
|
|
696
|
+
try {
|
|
697
|
+
text = (await fs.readFile(file, 'utf8')).trim();
|
|
698
|
+
}
|
|
699
|
+
catch (e) {
|
|
700
|
+
if (e.code === 'ENOENT')
|
|
701
|
+
return 0;
|
|
702
|
+
throw new RecordRefused('state', `The stored sequence of the release record (${file}) cannot be read. Nothing is signed. Check the file, or remove it to accept the next record.`);
|
|
703
|
+
}
|
|
704
|
+
if (!/^\d+$/.test(text))
|
|
705
|
+
throw new RecordRefused('state', `The stored sequence of the release record (${file}) cannot be read. Nothing is signed. Check the file, or remove it to accept the next record.`);
|
|
706
|
+
return Number(text);
|
|
707
|
+
}
|
|
708
|
+
async function mark(store, key, fn) {
|
|
709
|
+
try {
|
|
710
|
+
return await store.update(key, fn, { unique: false, strict: true });
|
|
711
|
+
}
|
|
712
|
+
catch (e) {
|
|
713
|
+
if (e instanceof RecordRefused)
|
|
714
|
+
throw e;
|
|
715
|
+
const code = e.code ?? '';
|
|
716
|
+
if (NO_FOLDER.has(code)) {
|
|
717
|
+
// no lock (a folder that cannot be written): kept in this process, and still held to the stored mark, read as is
|
|
718
|
+
const stored = await storedMark(store, key);
|
|
719
|
+
return fallback.update(key, (last) => fn(Math.max(last, stored)), { unique: false });
|
|
720
|
+
}
|
|
721
|
+
throw new RecordRefused('state', `The stored sequence of the release record cannot be read (${e.message}). Nothing is signed. Check the file, or remove it to accept the next record.`);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
/** The highest sequence of a verified record seen for `chainId` (null when none). Kept in `store` as sequence + 1. */
|
|
725
|
+
async function seenSequence(store, fp, chainId) {
|
|
726
|
+
const v = await mark(store, stateKey(fp, chainId), (last) => last);
|
|
727
|
+
return v > 0 ? v - 1 : null;
|
|
728
|
+
}
|
|
729
|
+
/** Refuse `sequence` when it is lower than the highest seen for `chainId`; else keep the highest. */
|
|
730
|
+
async function acceptSequence(store, fp, chainId, sequence) {
|
|
731
|
+
await mark(store, stateKey(fp, chainId), (last) => {
|
|
732
|
+
if (last > 0 && sequence < last - 1) {
|
|
733
|
+
throw new RecordRefused('rollback', `The signed release record for chain ${chainId} has sequence ${sequence}, lower than sequence ${last - 1} already seen on this computer: an older record is being served. It is not used.`);
|
|
734
|
+
}
|
|
735
|
+
return Math.max(last, sequence + 1);
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
async function fetchBytes(t, url, timeoutMs, limit) {
|
|
739
|
+
if (!t.getBytes)
|
|
740
|
+
return null;
|
|
741
|
+
let r;
|
|
742
|
+
try {
|
|
743
|
+
r = await t.getBytes(url, timeoutMs, limit);
|
|
744
|
+
}
|
|
745
|
+
catch {
|
|
746
|
+
return null;
|
|
747
|
+
}
|
|
748
|
+
if (r.status !== 200)
|
|
749
|
+
return null;
|
|
750
|
+
if (r.bytes.length > limit)
|
|
751
|
+
throw new RecordRefused('too_large', `The file at ${url} is larger than a release record can be. It is not used.`);
|
|
752
|
+
return r.bytes;
|
|
753
|
+
}
|
|
754
|
+
const BEGIN_SIG = enc.encode('-----BEGIN PGP SIGNATURE-----');
|
|
755
|
+
const contains = (hay, needle) => { outer: for (let i = 0; i + needle.length <= hay.length; i++) {
|
|
756
|
+
for (let k = 0; k < needle.length; k++)
|
|
757
|
+
if (hay[i + k] !== needle[k])
|
|
758
|
+
continue outer;
|
|
759
|
+
return true;
|
|
760
|
+
} return false; };
|
|
761
|
+
/**
|
|
762
|
+
* Read the signed record for `chainId` from the first of `urls` that serves one (through `transport.getBytes`; a
|
|
763
|
+
* transport without it reads no record).
|
|
764
|
+
*
|
|
765
|
+
* Resolves null when no address serves a network record (nothing, or a signed release list of an earlier format) and no
|
|
766
|
+
* record for this network was seen on this computer before. Throws {@link RecordRefused} (with a plain sentence) for an
|
|
767
|
+
* unsigned record, a bad signature, another key, a record of an unknown format, an expired record, a sequence lower than
|
|
768
|
+
* one seen before, a record that does not list `chainId`, or, when a record for this network was seen before, for no
|
|
769
|
+
* record served now.
|
|
770
|
+
*/
|
|
771
|
+
export async function readRecord(chainId, urls, keys, opts) {
|
|
772
|
+
const t = opts.transport;
|
|
773
|
+
const ms = opts.timeoutMs ?? 10000;
|
|
774
|
+
const store = opts.store ?? defaultNonceStore();
|
|
775
|
+
const nowMs = opts.now ?? Date.now;
|
|
776
|
+
let problem = null;
|
|
777
|
+
for (const url of urls) {
|
|
778
|
+
try {
|
|
779
|
+
const data = await fetchBytes(t, url, ms, MAX_RECORD_BYTES);
|
|
780
|
+
if (!data)
|
|
781
|
+
continue;
|
|
782
|
+
const sig = await fetchBytes(t, url + '.asc', ms, MAX_SIGNATURE_BYTES);
|
|
783
|
+
if (!sig || !contains(sig, BEGIN_SIG)) {
|
|
784
|
+
if (isNetworkRecord(data))
|
|
785
|
+
throw new RecordRefused('unsigned', `The release record at ${url} is not signed (no ${url}.asc). It is not used.`);
|
|
786
|
+
continue;
|
|
787
|
+
}
|
|
788
|
+
const keysNow = [];
|
|
789
|
+
for (const k of keys)
|
|
790
|
+
keysNow.push(await keyNow(k, t, ms, nowMs() / 1000));
|
|
791
|
+
const signed = verifyDetached(data, sig, keysNow, nowMs() / 1000);
|
|
792
|
+
const record = parseRecord(data, signed.fingerprint); // the verified bytes, never a second read
|
|
793
|
+
if (!record)
|
|
794
|
+
continue;
|
|
795
|
+
if (nowMs() / 1000 > record.validUntil) {
|
|
796
|
+
throw new RecordRefused('expired', `The signed release record expired at ${new Date(record.validUntil * 1000).toISOString().slice(0, 16).replace('T', ' ')} UTC. It is not used.`);
|
|
797
|
+
}
|
|
798
|
+
const entry = record.networks.get(chainId);
|
|
799
|
+
if (!entry)
|
|
800
|
+
throw new RecordRefused('not_listed', `The signed release record does not list chain ${chainId}. Nothing is signed for it.`);
|
|
801
|
+
await acceptSequence(store, signed.fingerprint, chainId, record.sequence);
|
|
802
|
+
return { record, entry, url };
|
|
803
|
+
}
|
|
804
|
+
catch (e) {
|
|
805
|
+
if (!(e instanceof RecordRefused))
|
|
806
|
+
throw e;
|
|
807
|
+
problem ??= e;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
if (problem)
|
|
811
|
+
throw problem;
|
|
812
|
+
for (const k of keys) {
|
|
813
|
+
const last = await seenSequence(store, k.fingerprint, chainId);
|
|
814
|
+
if (last !== null) {
|
|
815
|
+
throw new RecordRefused('not_served', `No signed release record for chain ${chainId} is served now, though one (sequence ${last}) was read on this computer before. Nothing is signed until it is served again.`);
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
return null;
|
|
819
|
+
}
|