@ghostlytools/sdk 1.11.4 → 1.12.1
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/dist/app.js +1 -2
- package/dist/bitcoinAddress-C2MAmcDT.js +1225 -0
- package/dist/bitcoinAddress-C2MAmcDT.js.map +1 -0
- package/dist/bolt11-CRiQrma3.js +266 -0
- package/dist/bolt11-CRiQrma3.js.map +1 -0
- package/dist/core.js +41852 -336
- package/dist/core.js.map +1 -1
- package/dist/{fakes-CXeeyI4Z.js → fakes-Cgl1w4Nv.js} +6 -9
- package/dist/{fakes-CXeeyI4Z.js.map → fakes-Cgl1w4Nv.js.map} +1 -1
- package/dist/fakes.js +1 -2
- package/dist/index.js +8 -9
- package/dist/index.js.map +1 -1
- package/dist/{keet-identity-key-DLXTTFZH.js → keet-identity-key-LuoCuz1t.js} +648 -324
- package/dist/keet-identity-key-LuoCuz1t.js.map +1 -0
- package/dist/pairedTransports-CkYMAoYN.js +1149 -0
- package/dist/pairedTransports-CkYMAoYN.js.map +1 -0
- package/dist/rolldown-runtime-DpEnGzO4.js +45 -0
- package/dist/testing.js +7 -8
- package/dist/testing.js.map +1 -1
- package/dist/types/browser/src/proofs/contract.d.ts +10 -0
- package/dist/types/browser/src/shared/mints.d.ts +3 -1
- package/dist/types/core/src/chatFiles.d.ts +3 -1
- package/dist/types/core/src/communityRendezvous.d.ts +4 -0
- package/dist/types/core/src/dhtDelivery.d.ts +16 -0
- package/dist/types/core/src/engineErrors.d.ts +7 -0
- package/dist/types/core/src/ghostlink.d.ts +12 -2
- package/dist/types/core/src/groupCalls.d.ts +56 -0
- package/dist/types/core/src/groupCommunity.d.ts +59 -1
- package/dist/types/core/src/groupCrypto.d.ts +6 -0
- package/dist/types/core/src/groupMeta.d.ts +22 -0
- package/dist/types/core/src/groupSession.d.ts +42 -2
- package/dist/types/core/src/handoff.d.ts +0 -2
- package/dist/types/core/src/http.d.ts +2 -1
- package/dist/types/core/src/index.d.ts +1 -0
- package/dist/types/core/src/pairedTransports.d.ts +5 -0
- package/dist/types/core/src/relayBreaker.d.ts +5 -1
- package/dist/types/core/src/services.d.ts +6 -0
- package/dist/types/core/src/text.d.ts +2 -0
- package/dist/types/core/src/transport.d.ts +1 -1
- package/dist/{types-DYLIIkU8.js → types-DbgC491n.js} +2 -3
- package/dist/{types-DYLIIkU8.js.map → types-DbgC491n.js.map} +1 -1
- package/dist/{verify-B9s82dbd.js → verify-CSo7-43-.js} +3 -4
- package/dist/{verify-B9s82dbd.js.map → verify-CSo7-43-.js.map} +1 -1
- package/package.json +3 -3
- package/dist/keet-identity-key-DLXTTFZH.js.map +0 -1
- package/dist/src-CqAqFhh9.js +0 -43635
- package/dist/src-CqAqFhh9.js.map +0 -1
|
@@ -0,0 +1,1149 @@
|
|
|
1
|
+
import { a as concatBytes, c as fromZ32, d as toBase64, f as toBase64Url, h as utf8Encode, m as utf8Decode, o as fromBase64, p as toZ32, s as fromBase64Url, u as randomBytes } from "./bolt11-CRiQrma3.js";
|
|
2
|
+
import { H as identityFromSeed, K as sign, U as identityFromSeedB64, W as publicKeyFromZ32, q as verify } from "./bitcoinAddress-C2MAmcDT.js";
|
|
3
|
+
import { xsalsa20poly1305 } from "@noble/ciphers/salsa.js";
|
|
4
|
+
import { ed25519, x25519 } from "@noble/curves/ed25519.js";
|
|
5
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
6
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
7
|
+
// ../core/src/crypto.ts
|
|
8
|
+
var NONCE_LENGTH = 24;
|
|
9
|
+
var KEY_LENGTH = 32;
|
|
10
|
+
function generateEncryptionKey() {
|
|
11
|
+
return randomBytes(KEY_LENGTH);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* NaCl secretbox (XSalsa20-Poly1305). Wire format matches the Rust
|
|
15
|
+
* implementation in `apps/desktop/src/crypto.rs`: base64(nonce || box).
|
|
16
|
+
*/
|
|
17
|
+
function encrypt(plaintext, key) {
|
|
18
|
+
if (key.length !== KEY_LENGTH) throw new Error("Invalid key length: expected 32 bytes");
|
|
19
|
+
const nonce = randomBytes(NONCE_LENGTH);
|
|
20
|
+
const box = xsalsa20poly1305(key, nonce).encrypt(utf8Encode(plaintext));
|
|
21
|
+
return toBase64(concatBytes(nonce, box));
|
|
22
|
+
}
|
|
23
|
+
/** The length of what `encrypt` returns for a plaintext of this many UTF-8 bytes: base64 of nonce, box and 16-byte tag. */
|
|
24
|
+
function sealedLength(plaintextBytes) {
|
|
25
|
+
return 4 * Math.ceil((40 + plaintextBytes) / 3);
|
|
26
|
+
}
|
|
27
|
+
function decrypt(encoded, key) {
|
|
28
|
+
if (key.length !== KEY_LENGTH) throw new Error("Invalid key length: expected 32 bytes");
|
|
29
|
+
const combined = fromBase64(encoded);
|
|
30
|
+
if (combined.length < 25) throw new Error("Invalid ciphertext: too short");
|
|
31
|
+
const nonce = combined.subarray(0, NONCE_LENGTH);
|
|
32
|
+
const box = combined.subarray(NONCE_LENGTH);
|
|
33
|
+
return utf8Decode(xsalsa20poly1305(key, nonce).decrypt(box));
|
|
34
|
+
}
|
|
35
|
+
function tryDecrypt(encoded, key) {
|
|
36
|
+
try {
|
|
37
|
+
return decrypt(encoded, key);
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// ../core/src/dns.ts
|
|
43
|
+
var TYPE_NS = 2;
|
|
44
|
+
var TYPE_TXT = 16;
|
|
45
|
+
var CLASS_IN = 1;
|
|
46
|
+
var FLAGS_REPLY = 32768;
|
|
47
|
+
var MAX_CHARACTER_STRING = 255;
|
|
48
|
+
var MAX_POINTER_OFFSET = 16383;
|
|
49
|
+
var Writer = class {
|
|
50
|
+
chunks = [];
|
|
51
|
+
length = 0;
|
|
52
|
+
push(bytes) {
|
|
53
|
+
this.chunks.push(bytes);
|
|
54
|
+
this.length += bytes.length;
|
|
55
|
+
}
|
|
56
|
+
u8(v) {
|
|
57
|
+
this.push(Uint8Array.of(v & 255));
|
|
58
|
+
}
|
|
59
|
+
u16(v) {
|
|
60
|
+
this.push(Uint8Array.of(v >>> 8 & 255, v & 255));
|
|
61
|
+
}
|
|
62
|
+
u32(v) {
|
|
63
|
+
this.push(Uint8Array.of(v >>> 24 & 255, v >>> 16 & 255, v >>> 8 & 255, v & 255));
|
|
64
|
+
}
|
|
65
|
+
bytes() {
|
|
66
|
+
return concatBytes(...this.chunks);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
function writeName(writer, name, suffixOffsets) {
|
|
70
|
+
const labels = name.split(".").filter((l) => l.length > 0);
|
|
71
|
+
for (let i = 0; i < labels.length; i++) {
|
|
72
|
+
const suffix = labels.slice(i).join(".");
|
|
73
|
+
const pointer = suffixOffsets.get(suffix);
|
|
74
|
+
if (pointer !== void 0) {
|
|
75
|
+
writer.u16(49152 | pointer);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (writer.length <= MAX_POINTER_OFFSET) suffixOffsets.set(suffix, writer.length);
|
|
79
|
+
const label = utf8Encode(labels[i]);
|
|
80
|
+
if (label.length > 63) throw new Error(`DNS label too long: ${labels[i]}`);
|
|
81
|
+
writer.u8(label.length);
|
|
82
|
+
writer.push(label);
|
|
83
|
+
}
|
|
84
|
+
writer.u8(0);
|
|
85
|
+
}
|
|
86
|
+
/** `authoritative` sets the AA flag, which a did:dht packet must carry. */
|
|
87
|
+
function encodeTxtPacket(records, options = {}) {
|
|
88
|
+
const writer = new Writer();
|
|
89
|
+
writer.u16(0);
|
|
90
|
+
writer.u16(options.authoritative ? 33792 : FLAGS_REPLY);
|
|
91
|
+
writer.u16(0);
|
|
92
|
+
writer.u16(records.length);
|
|
93
|
+
writer.u16(0);
|
|
94
|
+
writer.u16(0);
|
|
95
|
+
const suffixOffsets = /* @__PURE__ */ new Map();
|
|
96
|
+
for (const record of records) {
|
|
97
|
+
writeName(writer, record.name, suffixOffsets);
|
|
98
|
+
if ("host" in record) {
|
|
99
|
+
writer.u16(TYPE_NS);
|
|
100
|
+
writer.u16(CLASS_IN);
|
|
101
|
+
writer.u32(record.ttl);
|
|
102
|
+
const host = new Writer();
|
|
103
|
+
writeName(host, record.host, /* @__PURE__ */ new Map());
|
|
104
|
+
writer.u16(host.length);
|
|
105
|
+
writer.push(host.bytes());
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
writer.u16(TYPE_TXT);
|
|
109
|
+
writer.u16(CLASS_IN);
|
|
110
|
+
writer.u32(record.ttl);
|
|
111
|
+
const value = utf8Encode(record.value);
|
|
112
|
+
const strings = [];
|
|
113
|
+
for (let i = 0; i < value.length || i === 0; i += MAX_CHARACTER_STRING) {
|
|
114
|
+
const chunk = value.subarray(i, i + MAX_CHARACTER_STRING);
|
|
115
|
+
strings.push(Uint8Array.of(chunk.length), chunk);
|
|
116
|
+
}
|
|
117
|
+
const rdata = concatBytes(...strings);
|
|
118
|
+
writer.u16(rdata.length);
|
|
119
|
+
writer.push(rdata);
|
|
120
|
+
}
|
|
121
|
+
return writer.bytes();
|
|
122
|
+
}
|
|
123
|
+
/** A name at `start` (compressed or not), and where the bytes after it begin. Labels are joined with ".", no trailing dot. */
|
|
124
|
+
function readDnsName(data, start) {
|
|
125
|
+
const labels = [];
|
|
126
|
+
let pos = start;
|
|
127
|
+
let next = -1;
|
|
128
|
+
let jumps = 0;
|
|
129
|
+
for (;;) {
|
|
130
|
+
if (pos >= data.length) throw new Error("DNS name out of bounds");
|
|
131
|
+
const len = data[pos];
|
|
132
|
+
if ((len & 192) === 192) {
|
|
133
|
+
if (pos + 1 >= data.length) throw new Error("DNS pointer out of bounds");
|
|
134
|
+
if (next < 0) next = pos + 2;
|
|
135
|
+
pos = (len & 63) << 8 | data[pos + 1];
|
|
136
|
+
if (++jumps > 32) throw new Error("DNS name has too many compression pointers");
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (len & 192) throw new Error("Unsupported DNS label type");
|
|
140
|
+
pos += 1;
|
|
141
|
+
if (len === 0) break;
|
|
142
|
+
if (pos + len > data.length) throw new Error("DNS label out of bounds");
|
|
143
|
+
labels.push(utf8Decode(data.subarray(pos, pos + len)));
|
|
144
|
+
pos += len;
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
name: labels.join("."),
|
|
148
|
+
next: next < 0 ? pos : next
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function decodeTxtPacket(data) {
|
|
152
|
+
if (data.length < 12) throw new Error("DNS packet too short");
|
|
153
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
154
|
+
const questions = view.getUint16(4);
|
|
155
|
+
const answers = view.getUint16(6);
|
|
156
|
+
let pos = 12;
|
|
157
|
+
for (let i = 0; i < questions; i++) pos = readDnsName(data, pos).next + 4;
|
|
158
|
+
const records = [];
|
|
159
|
+
for (let i = 0; i < answers; i++) {
|
|
160
|
+
const { name, next } = readDnsName(data, pos);
|
|
161
|
+
pos = next;
|
|
162
|
+
if (pos + 10 > data.length) throw new Error("DNS record out of bounds");
|
|
163
|
+
const type = view.getUint16(pos);
|
|
164
|
+
const ttl = view.getUint32(pos + 4);
|
|
165
|
+
const rdLength = view.getUint16(pos + 8);
|
|
166
|
+
pos += 10;
|
|
167
|
+
const end = pos + rdLength;
|
|
168
|
+
if (end > data.length) throw new Error("DNS rdata out of bounds");
|
|
169
|
+
if (type === TYPE_TXT) {
|
|
170
|
+
const parts = [];
|
|
171
|
+
let p = pos;
|
|
172
|
+
while (p < end) {
|
|
173
|
+
const len = data[p];
|
|
174
|
+
if (p + 1 + len > end) throw new Error("DNS character-string out of bounds");
|
|
175
|
+
parts.push(data.subarray(p + 1, p + 1 + len));
|
|
176
|
+
p += 1 + len;
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
records.push({
|
|
180
|
+
name,
|
|
181
|
+
value: utf8Decode(concatBytes(...parts)),
|
|
182
|
+
ttl
|
|
183
|
+
});
|
|
184
|
+
} catch {}
|
|
185
|
+
}
|
|
186
|
+
pos = end;
|
|
187
|
+
}
|
|
188
|
+
return records;
|
|
189
|
+
}
|
|
190
|
+
/** Every answer record of a packet, of any type. Names are decompressed; the rdata is left to the caller. */
|
|
191
|
+
function decodeDnsAnswers(data) {
|
|
192
|
+
if (data.length < 12) throw new Error("DNS packet too short");
|
|
193
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
194
|
+
const questions = view.getUint16(4);
|
|
195
|
+
const answers = view.getUint16(6);
|
|
196
|
+
let pos = 12;
|
|
197
|
+
for (let i = 0; i < questions; i++) pos = readDnsName(data, pos).next + 4;
|
|
198
|
+
const records = [];
|
|
199
|
+
for (let i = 0; i < answers; i++) {
|
|
200
|
+
const { name, next } = readDnsName(data, pos);
|
|
201
|
+
pos = next;
|
|
202
|
+
if (pos + 10 > data.length) throw new Error("DNS record out of bounds");
|
|
203
|
+
const type = view.getUint16(pos);
|
|
204
|
+
const ttl = view.getUint32(pos + 4);
|
|
205
|
+
const length = view.getUint16(pos + 8);
|
|
206
|
+
pos += 10;
|
|
207
|
+
if (pos + length > data.length) throw new Error("DNS rdata out of bounds");
|
|
208
|
+
records.push({
|
|
209
|
+
name,
|
|
210
|
+
type,
|
|
211
|
+
ttl,
|
|
212
|
+
offset: pos,
|
|
213
|
+
length
|
|
214
|
+
});
|
|
215
|
+
pos += length;
|
|
216
|
+
}
|
|
217
|
+
return records;
|
|
218
|
+
}
|
|
219
|
+
// ../core/src/pkarr.ts
|
|
220
|
+
/** Mainline DHT (BEP44) caps the value of a mutable item at 1000 bytes. */
|
|
221
|
+
var MAX_DNS_PACKET_BYTES = 1e3;
|
|
222
|
+
var SIGNATURE_LENGTH = 64;
|
|
223
|
+
var TIMESTAMP_LENGTH = 8;
|
|
224
|
+
/** The largest relay payload: a 64-byte signature, an 8-byte timestamp and the largest DNS packet (1072 bytes). */
|
|
225
|
+
var RELAY_PAYLOAD_MAX_BYTES = 1072;
|
|
226
|
+
var PacketTooLargeError = class extends Error {
|
|
227
|
+
size;
|
|
228
|
+
constructor(size) {
|
|
229
|
+
super(`DNS packet is too large, expected max ${MAX_DNS_PACKET_BYTES} bytes but got: ${size}`);
|
|
230
|
+
this.size = size;
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
var DEFAULT_TTL = 300;
|
|
234
|
+
function signable(timestampMicros, dnsPacket) {
|
|
235
|
+
return concatBytes(utf8Encode(`3:seqi${timestampMicros}e1:v${dnsPacket.length}:`), dnsPacket);
|
|
236
|
+
}
|
|
237
|
+
function toTxtRecords(pubKeyZ32, records) {
|
|
238
|
+
return records.map((r) => ({
|
|
239
|
+
name: `${r.label}.${pubKeyZ32}`,
|
|
240
|
+
value: r.value,
|
|
241
|
+
ttl: r.ttl ?? DEFAULT_TTL
|
|
242
|
+
}));
|
|
243
|
+
}
|
|
244
|
+
/** Size of the encoded DNS packet these records would produce. */
|
|
245
|
+
function measureRecords(pubKeyZ32, records) {
|
|
246
|
+
return encodeTxtPacket(toTxtRecords(pubKeyZ32, records)).length;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Builds the payload Pkarr relays accept on `PUT /<z32 public key>`:
|
|
250
|
+
* `<64 bytes signature><8 bytes big-endian timestamp (µs)><encoded DNS packet>`
|
|
251
|
+
*/
|
|
252
|
+
function createRelayPayload(identity, records, timestampMicros = BigInt(Date.now()) * 1000n) {
|
|
253
|
+
return signRelayPayload(identity, encodeTxtPacket(toTxtRecords(identity.pubKeyZ32, records)), timestampMicros);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Signs a DNS packet exactly as given (its own names and flags) into a relay payload. `seq` is the
|
|
257
|
+
* BEP44 sequence number: Ghostly's records use microseconds, a did:dht document seconds.
|
|
258
|
+
*/
|
|
259
|
+
function signRelayPayload(identity, dnsPacket, seq) {
|
|
260
|
+
if (dnsPacket.length > 1e3) throw new PacketTooLargeError(dnsPacket.length);
|
|
261
|
+
if (seq < 0n || seq >= 1n << 64n) throw new RangeError(`Sequence number ${seq} does not fit in 64 bits`);
|
|
262
|
+
const signature = sign(signable(seq, dnsPacket), identity.seed);
|
|
263
|
+
const timestamp = new Uint8Array(TIMESTAMP_LENGTH);
|
|
264
|
+
new DataView(timestamp.buffer).setBigUint64(0, seq);
|
|
265
|
+
return concatBytes(signature, timestamp, dnsPacket);
|
|
266
|
+
}
|
|
267
|
+
/** A relay payload's parts, its size checked: the signature, the sequence number and the DNS packet (not decoded). */
|
|
268
|
+
function splitRelayPayload(payload) {
|
|
269
|
+
if (payload.length < 84) throw new Error("Relay payload too short");
|
|
270
|
+
if (payload.length > 1072) throw new PacketTooLargeError(payload.length);
|
|
271
|
+
return {
|
|
272
|
+
signature: payload.subarray(0, SIGNATURE_LENGTH),
|
|
273
|
+
seq: new DataView(payload.buffer, payload.byteOffset + SIGNATURE_LENGTH, TIMESTAMP_LENGTH).getBigUint64(0),
|
|
274
|
+
dnsPacket: payload.subarray(72)
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
/** Checks a relay payload's size and signature. Returns its sequence number and DNS packet, not decoded. */
|
|
278
|
+
function openRelayPayload(pubKeyZ32, payload) {
|
|
279
|
+
const { signature, seq, dnsPacket } = splitRelayPayload(payload);
|
|
280
|
+
const publicKey = publicKeyFromZ32(pubKeyZ32);
|
|
281
|
+
if (!verify(signature, signable(seq, dnsPacket), publicKey)) throw new Error("Invalid signature");
|
|
282
|
+
return {
|
|
283
|
+
seq,
|
|
284
|
+
dnsPacket
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
function decodeRelayPayload(pubKeyZ32, seq, dnsPacket) {
|
|
288
|
+
const suffix = `.${pubKeyZ32}`;
|
|
289
|
+
return {
|
|
290
|
+
pubKeyZ32,
|
|
291
|
+
timestampMicros: seq,
|
|
292
|
+
records: decodeTxtPacket(dnsPacket).map((r) => ({
|
|
293
|
+
label: r.name.endsWith(suffix) ? r.name.slice(0, -suffix.length) : r.name,
|
|
294
|
+
value: r.value,
|
|
295
|
+
ttl: r.ttl
|
|
296
|
+
}))
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
/** Verifies and decodes a relay payload. Throws if the signature does not match. */
|
|
300
|
+
function parseRelayPayload(pubKeyZ32, payload) {
|
|
301
|
+
const { seq, dnsPacket } = openRelayPayload(pubKeyZ32, payload);
|
|
302
|
+
return decodeRelayPayload(pubKeyZ32, seq, dnsPacket);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Decodes a payload whose signature this process made or already checked (one it is putting), without checking it
|
|
306
|
+
* again: an Ed25519 verify costs about 1 ms, and a CLI daemon at its relay budget checked its own packets ~500 times a
|
|
307
|
+
* minute. Never for bytes read from elsewhere: `parseRelayPayload` is.
|
|
308
|
+
*/
|
|
309
|
+
function readOwnRelayPayload(pubKeyZ32, payload) {
|
|
310
|
+
const { seq, dnsPacket } = splitRelayPayload(payload);
|
|
311
|
+
return decodeRelayPayload(pubKeyZ32, seq, dnsPacket);
|
|
312
|
+
}
|
|
313
|
+
/** How far ahead of this clock a packet's time may be and still count as now: clocks drift, not by this much. */
|
|
314
|
+
var PKARR_FUTURE_SKEW_MS = 6e5;
|
|
315
|
+
/**
|
|
316
|
+
* The newer of two signed packets of one key. A packet dated further ahead than `PKARR_FUTURE_SKEW_MS` never wins over
|
|
317
|
+
* one dated now or before: whoever could sign it once (a key several people hold, a clock far off) must not keep every
|
|
318
|
+
* later packet from being taken. Between two of the same kind, the later time wins; on a tie, `known` stays.
|
|
319
|
+
*/
|
|
320
|
+
function newerPacket(known, packet, now = Date.now()) {
|
|
321
|
+
if (!known) return packet ?? null;
|
|
322
|
+
if (!packet) return known;
|
|
323
|
+
const limit = BigInt(now + PKARR_FUTURE_SKEW_MS) * 1000n;
|
|
324
|
+
const knownAhead = known.timestampMicros > limit;
|
|
325
|
+
if (knownAhead !== packet.timestampMicros > limit) return knownAhead ? packet : known;
|
|
326
|
+
return packet.timestampMicros > known.timestampMicros ? packet : known;
|
|
327
|
+
}
|
|
328
|
+
// ../core/src/domainProofs.ts
|
|
329
|
+
var DOMAIN_METHODS = [
|
|
330
|
+
"dns",
|
|
331
|
+
"https",
|
|
332
|
+
"nip05"
|
|
333
|
+
];
|
|
334
|
+
var DNS_LABEL = "_ghostly";
|
|
335
|
+
var WELL_KNOWN_PATH = "/.well-known/ghostly.json";
|
|
336
|
+
var NIP05_PATH = "/.well-known/nostr.json?name=_";
|
|
337
|
+
/** Everything read from a domain is bounded; these match the fetch limits. */
|
|
338
|
+
var DOMAIN_FILE_MAX_BYTES = 16384;
|
|
339
|
+
var DOMAIN_TXT_MAX_BYTES = 1024;
|
|
340
|
+
var DOMAIN_MAX_RECORDS = 8;
|
|
341
|
+
var z32 = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;
|
|
342
|
+
var hex64 = /^[a-f0-9]{64}$/;
|
|
343
|
+
/** Names that never resolve publicly (RFC 6761, 6762, 7686, 8375, 9476) or that
|
|
344
|
+
* only ever mean a private network. A proof for them could only point inward. */
|
|
345
|
+
var SPECIAL_USE = [
|
|
346
|
+
"localhost",
|
|
347
|
+
"local",
|
|
348
|
+
"internal",
|
|
349
|
+
"lan",
|
|
350
|
+
"home",
|
|
351
|
+
"corp",
|
|
352
|
+
"intranet",
|
|
353
|
+
"private",
|
|
354
|
+
"test",
|
|
355
|
+
"example",
|
|
356
|
+
"invalid",
|
|
357
|
+
"onion",
|
|
358
|
+
"alt",
|
|
359
|
+
"arpa"
|
|
360
|
+
];
|
|
361
|
+
/**
|
|
362
|
+
* Normalizes what a person typed ("Example.COM.", "https://example.com/") into
|
|
363
|
+
* a lowercase ASCII host name, or throws with a message fit for the UI.
|
|
364
|
+
* Internationalized names become punycode (xn--), the form DNS carries.
|
|
365
|
+
*/
|
|
366
|
+
function normalizeDomain(input) {
|
|
367
|
+
if (typeof input !== "string") throw new Error("Enter a domain name, like example.com");
|
|
368
|
+
let value = input.trim();
|
|
369
|
+
if (!value || value.length > 300) throw new Error("Enter a domain name, like example.com");
|
|
370
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
|
|
371
|
+
let url;
|
|
372
|
+
try {
|
|
373
|
+
url = new URL(value);
|
|
374
|
+
} catch {
|
|
375
|
+
throw new Error("Enter a domain name, like example.com");
|
|
376
|
+
}
|
|
377
|
+
if (url.protocol !== "https:" || url.username || url.password || url.port || url.pathname !== "/" && url.pathname !== "" || url.search || url.hash) throw new Error("Enter only the domain name, without a path or port");
|
|
378
|
+
value = url.hostname;
|
|
379
|
+
} else {
|
|
380
|
+
if (/[/:@?#\s\\]/.test(value)) throw new Error("Enter only the domain name, without a path or port");
|
|
381
|
+
try {
|
|
382
|
+
value = new URL(`https://${value}`).hostname;
|
|
383
|
+
} catch {
|
|
384
|
+
throw new Error("That is not a valid domain name");
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
value = value.toLowerCase().replace(/\.$/, "");
|
|
388
|
+
if (value.length > 244) throw new Error("That domain name is too long");
|
|
389
|
+
const labels = value.split(".");
|
|
390
|
+
if (labels.length < 2) throw new Error("Use a full domain name, like example.com");
|
|
391
|
+
for (const label of labels) if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) throw new Error("That is not a valid domain name");
|
|
392
|
+
const tld = labels[labels.length - 1];
|
|
393
|
+
if (/^[0-9]+$/.test(tld) || /^\[/.test(value)) throw new Error("Use a domain name, not an IP address");
|
|
394
|
+
if (SPECIAL_USE.includes(tld) || labels.length >= 2 && labels.slice(-2).join(".") === "home.arpa") throw new Error("That name only works on private networks");
|
|
395
|
+
return value;
|
|
396
|
+
}
|
|
397
|
+
var dnsProofName = (domain) => `${DNS_LABEL}.${normalizeDomain(domain)}`;
|
|
398
|
+
var wellKnownUrl = (domain, method = "https") => `https://${normalizeDomain(domain)}${method === "nip05" ? NIP05_PATH : WELL_KNOWN_PATH}`;
|
|
399
|
+
function validDomainRecord(r) {
|
|
400
|
+
if (!r || typeof r.key !== "string" || typeof r.proof !== "string" || !z32.test(r.key) || !hex64.test(r.proof)) return false;
|
|
401
|
+
try {
|
|
402
|
+
return toZ32(fromZ32(r.key)) === r.key;
|
|
403
|
+
} catch {
|
|
404
|
+
return false;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
/** The TXT record value, in the `tag=value; …` style people know from DKIM. */
|
|
408
|
+
function domainTxtRecord(r) {
|
|
409
|
+
if (!validDomainRecord(r)) throw new Error("Invalid domain record");
|
|
410
|
+
return `v=ghostly1; key=${r.key}; proof=${r.proof}`;
|
|
411
|
+
}
|
|
412
|
+
/** Parses one TXT string. Undefined for anything that is not ours or not exactly
|
|
413
|
+
* well-formed; unknown extra tags are ignored for forward compatibility. */
|
|
414
|
+
function parseDomainTxt(value) {
|
|
415
|
+
if (typeof value !== "string" || utf8Encode(value).length > 1024) return;
|
|
416
|
+
const tags = /* @__PURE__ */ new Map();
|
|
417
|
+
const parts = value.split(";").map((p) => p.trim()).filter(Boolean);
|
|
418
|
+
for (const part of parts) {
|
|
419
|
+
const eq = part.indexOf("=");
|
|
420
|
+
if (eq < 1) return;
|
|
421
|
+
const name = part.slice(0, eq).trim().toLowerCase();
|
|
422
|
+
if (tags.has(name)) return;
|
|
423
|
+
tags.set(name, part.slice(eq + 1).trim());
|
|
424
|
+
}
|
|
425
|
+
if (!parts[0]?.toLowerCase().startsWith("v=") || tags.get("v") !== "ghostly1") return;
|
|
426
|
+
const r = {
|
|
427
|
+
key: tags.get("key"),
|
|
428
|
+
proof: tags.get("proof")
|
|
429
|
+
};
|
|
430
|
+
return validDomainRecord(r) ? r : void 0;
|
|
431
|
+
}
|
|
432
|
+
var addRecord = (list, r) => {
|
|
433
|
+
if (!list.some((x) => x.key === r.key && x.proof === r.proof)) list.push(r);
|
|
434
|
+
};
|
|
435
|
+
/** All records among the first 32 TXT strings of `_ghostly.<domain>`; other strings are skipped. A TXT set has
|
|
436
|
+
* no order, so every record is kept: the one a proof needs may come in any position. */
|
|
437
|
+
function recordsFromTxt(values) {
|
|
438
|
+
const out = [];
|
|
439
|
+
for (const value of values.slice(0, 32)) {
|
|
440
|
+
const r = parseDomainTxt(value);
|
|
441
|
+
if (r) addRecord(out, r);
|
|
442
|
+
}
|
|
443
|
+
return out;
|
|
444
|
+
}
|
|
445
|
+
/** The body of `/.well-known/ghostly.json`. */
|
|
446
|
+
function domainWellKnownFile(records) {
|
|
447
|
+
if (!records.length || records.length > 8 || !records.every(validDomainRecord)) throw new Error("Invalid domain records");
|
|
448
|
+
return JSON.stringify({
|
|
449
|
+
ghostly: 1,
|
|
450
|
+
proofs: records.map((r) => ({
|
|
451
|
+
key: r.key,
|
|
452
|
+
proof: r.proof
|
|
453
|
+
}))
|
|
454
|
+
}, null, 2) + "\n";
|
|
455
|
+
}
|
|
456
|
+
function parseJson(text) {
|
|
457
|
+
if (typeof text !== "string" || utf8Encode(text).length > 16384) throw new Error("File too large");
|
|
458
|
+
return JSON.parse(text);
|
|
459
|
+
}
|
|
460
|
+
/** Records from the first 32 entries of `ghostly.json`. Throws on a malformed file; [] when it names none. */
|
|
461
|
+
function recordsFromWellKnown(text) {
|
|
462
|
+
const body = parseJson(text);
|
|
463
|
+
if (!body || typeof body !== "object" || Array.isArray(body) || body.ghostly !== 1 || !Array.isArray(body.proofs)) throw new Error("Not a Ghostly domain file");
|
|
464
|
+
const out = [];
|
|
465
|
+
for (const entry of body.proofs.slice(0, 32)) {
|
|
466
|
+
if (!entry || typeof entry !== "object") continue;
|
|
467
|
+
const r = {
|
|
468
|
+
key: entry.key,
|
|
469
|
+
proof: entry.proof
|
|
470
|
+
};
|
|
471
|
+
if (validDomainRecord(r)) addRecord(out, r);
|
|
472
|
+
}
|
|
473
|
+
return out;
|
|
474
|
+
}
|
|
475
|
+
/** NIP-05: only the root name `_` speaks for the domain itself. Undefined when absent. */
|
|
476
|
+
function nip05RootKey(text) {
|
|
477
|
+
const body = parseJson(text);
|
|
478
|
+
if (!body || typeof body !== "object" || !body.names || typeof body.names !== "object" || Array.isArray(body.names)) throw new Error("Not a NIP-05 file");
|
|
479
|
+
const root = body.names["_"];
|
|
480
|
+
return typeof root === "string" && hex64.test(root) ? root : void 0;
|
|
481
|
+
}
|
|
482
|
+
var recordsName = (records, r) => records.some((x) => x.key === r.key && x.proof === r.proof);
|
|
483
|
+
var DNS_TYPE = {
|
|
484
|
+
A: 1,
|
|
485
|
+
CNAME: 5,
|
|
486
|
+
TXT: 16,
|
|
487
|
+
AAAA: 28
|
|
488
|
+
};
|
|
489
|
+
/**
|
|
490
|
+
* EDNS0 OPT record (RFC 6891) with one Client Subnet option of source prefix 0 (RFC 7871 §7.1.2): a resolver must
|
|
491
|
+
* not add this device's subnet to its queries to the name's servers, as Google Public DNS otherwise does.
|
|
492
|
+
*/
|
|
493
|
+
var NO_CLIENT_SUBNET = Uint8Array.of(0, 0, 41, 4, 208, 0, 0, 0, 0, 0, 8, 0, 8, 0, 4, 0, 1, 0, 0);
|
|
494
|
+
/** A recursive query for one name and type. ID 0, as RFC 8484 recommends for caching;
|
|
495
|
+
* the AD bit asks the resolver to report DNSSEC validation (RFC 6840 §5.7). */
|
|
496
|
+
function encodeDnsQuery(name, type) {
|
|
497
|
+
const labels = name.replace(/\.$/, "").split(".");
|
|
498
|
+
const parts = [Uint8Array.of(0, 0, 1, 32, 0, 1, 0, 0, 0, 0, 0, 1)];
|
|
499
|
+
for (const label of labels) {
|
|
500
|
+
const bytes = utf8Encode(label);
|
|
501
|
+
if (!bytes.length || bytes.length > 63) throw new Error("Invalid DNS name");
|
|
502
|
+
parts.push(Uint8Array.of(bytes.length), bytes);
|
|
503
|
+
}
|
|
504
|
+
const code = DNS_TYPE[type];
|
|
505
|
+
parts.push(Uint8Array.of(0, code >> 8, code & 255, 0, 1), NO_CLIENT_SUBNET);
|
|
506
|
+
return concatBytes(...parts);
|
|
507
|
+
}
|
|
508
|
+
function readName(data, start) {
|
|
509
|
+
const labels = [];
|
|
510
|
+
let pos = start, next = -1, jumps = 0, length = 0;
|
|
511
|
+
for (;;) {
|
|
512
|
+
if (pos >= data.length) throw new Error("DNS name out of bounds");
|
|
513
|
+
const len = data[pos];
|
|
514
|
+
if ((len & 192) === 192) {
|
|
515
|
+
if (pos + 1 >= data.length) throw new Error("DNS pointer out of bounds");
|
|
516
|
+
if (next < 0) next = pos + 2;
|
|
517
|
+
pos = (len & 63) << 8 | data[pos + 1];
|
|
518
|
+
if (++jumps > 32) throw new Error("DNS name loops");
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (len & 192) throw new Error("Unsupported DNS label");
|
|
522
|
+
pos += 1;
|
|
523
|
+
if (len === 0) break;
|
|
524
|
+
if (pos + len > data.length) throw new Error("DNS label out of bounds");
|
|
525
|
+
length += len + 1;
|
|
526
|
+
if (length > 255) throw new Error("DNS name too long");
|
|
527
|
+
labels.push(utf8Decode(data.subarray(pos, pos + len)).toLowerCase());
|
|
528
|
+
pos += len;
|
|
529
|
+
}
|
|
530
|
+
return {
|
|
531
|
+
name: labels.join("."),
|
|
532
|
+
next: next < 0 ? pos : next
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* Decodes a resolver's answer to `encodeDnsQuery(name, type)`. Refuses a reply
|
|
537
|
+
* to another question or a truncated one, and keeps only records of the asked
|
|
538
|
+
* type owned by the name or by the CNAME chain the answer itself follows.
|
|
539
|
+
*/
|
|
540
|
+
function decodeDnsResponse(data, name, type) {
|
|
541
|
+
if (data.length < 12) throw new Error("DNS response too short");
|
|
542
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
543
|
+
const flags = view.getUint16(2);
|
|
544
|
+
if (!(flags & 32768) || flags & 30720 || flags & 512) throw new Error("Unusable DNS response");
|
|
545
|
+
const questions = view.getUint16(4), count = view.getUint16(6);
|
|
546
|
+
const want = name.replace(/\.$/, "").toLowerCase(), code = DNS_TYPE[type];
|
|
547
|
+
if (questions !== 1) throw new Error("DNS response is for another question");
|
|
548
|
+
const q = readName(data, 12);
|
|
549
|
+
if (q.name !== want || q.next + 4 > data.length || view.getUint16(q.next) !== code) throw new Error("DNS response is for another question");
|
|
550
|
+
let pos = q.next + 4;
|
|
551
|
+
const all = [];
|
|
552
|
+
for (let i = 0; i < count && i < 64; i++) {
|
|
553
|
+
const owner = readName(data, pos);
|
|
554
|
+
pos = owner.next;
|
|
555
|
+
if (pos + 10 > data.length) throw new Error("DNS record out of bounds");
|
|
556
|
+
const rtype = view.getUint16(pos), ttl = view.getUint32(pos + 4), len = view.getUint16(pos + 8);
|
|
557
|
+
pos += 10;
|
|
558
|
+
if (pos + len > data.length) throw new Error("DNS record out of bounds");
|
|
559
|
+
const rdata = rtype === DNS_TYPE.CNAME ? utf8Encode(readName(data, pos).name) : data.slice(pos, pos + len);
|
|
560
|
+
all.push({
|
|
561
|
+
name: owner.name,
|
|
562
|
+
type: rtype,
|
|
563
|
+
ttl,
|
|
564
|
+
data: rdata
|
|
565
|
+
});
|
|
566
|
+
pos += len;
|
|
567
|
+
}
|
|
568
|
+
const owners = /* @__PURE__ */ new Set([want]);
|
|
569
|
+
for (let hop = 0; hop < 8; hop++) {
|
|
570
|
+
const cname = all.find((a) => a.type === DNS_TYPE.CNAME && owners.has(a.name) && !owners.has(utf8Decode(a.data)));
|
|
571
|
+
if (!cname) break;
|
|
572
|
+
owners.add(utf8Decode(cname.data));
|
|
573
|
+
}
|
|
574
|
+
return {
|
|
575
|
+
rcode: flags & 15,
|
|
576
|
+
authenticated: !!(flags & 32),
|
|
577
|
+
answers: all.filter((a) => a.type === code && owners.has(a.name))
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
/** The TXT character-strings of one record, joined as RFC 7208 §3.3 does. */
|
|
581
|
+
function txtValue(rdata) {
|
|
582
|
+
const parts = [];
|
|
583
|
+
for (let p = 0; p < rdata.length;) {
|
|
584
|
+
const len = rdata[p];
|
|
585
|
+
if (p + 1 + len > rdata.length) throw new Error("DNS text out of bounds");
|
|
586
|
+
parts.push(rdata.subarray(p + 1, p + 1 + len));
|
|
587
|
+
p += 1 + len;
|
|
588
|
+
}
|
|
589
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(concatBytes(...parts));
|
|
590
|
+
}
|
|
591
|
+
/** False for loopback, private, link-local, shared (CGNAT), multicast, reserved
|
|
592
|
+
* and unspecified addresses, including IPv4 embedded in IPv6. */
|
|
593
|
+
function isPublicAddress(address) {
|
|
594
|
+
if (address.length === 4) {
|
|
595
|
+
const [a, b, c] = address;
|
|
596
|
+
return !(a === 0 || a === 10 || a === 127 || a >= 224 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 192 && b === 0 && c === 0 || a === 198 && (b === 18 || b === 19));
|
|
597
|
+
}
|
|
598
|
+
if (address.length !== 16) return false;
|
|
599
|
+
const zeroTo = (n) => address.subarray(0, n).every((x) => x === 0);
|
|
600
|
+
if (zeroTo(15) && (address[15] === 0 || address[15] === 1)) return false;
|
|
601
|
+
if (zeroTo(10) && address[10] === 255 && address[11] === 255) return isPublicAddress(address.subarray(12));
|
|
602
|
+
if (address[0] === 0 && address[1] === 100 && address[2] === 255 && address[3] === 155 && address.subarray(4, 12).every((x) => x === 0)) return isPublicAddress(address.subarray(12));
|
|
603
|
+
if (zeroTo(12)) return false;
|
|
604
|
+
if ((address[0] & 254) === 252) return false;
|
|
605
|
+
if (address[0] === 254 && (address[1] & 192) === 128) return false;
|
|
606
|
+
if (address[0] === 254 && (address[1] & 192) === 192) return false;
|
|
607
|
+
if (address[0] === 255) return false;
|
|
608
|
+
if (address[0] === 1 && address.subarray(1, 8).every((x) => x === 0)) return false;
|
|
609
|
+
return (address[0] & 224) === 32;
|
|
610
|
+
}
|
|
611
|
+
// ../core/src/storeForward.ts
|
|
612
|
+
/**
|
|
613
|
+
* Store-and-forward for an away contact (WISP 404 draft, `hold/1`).
|
|
614
|
+
*
|
|
615
|
+
* What a person sends while the contact is away is sealed into a *bundle* (signed by the sender's
|
|
616
|
+
* participation key, then encrypted to a key only the two of them can derive), put in the sender's
|
|
617
|
+
* own storage (WISP 1000), and named in a *manifest* the storage also holds. A small signed, encrypted
|
|
618
|
+
* *pointer* record on a per-link Pkarr key tells the contact where the manifest is (a URL that expires)
|
|
619
|
+
* and which of the contact's own bundles have been received. Storage and relays see ciphertext, sizes
|
|
620
|
+
* and timing only. Nothing here promises forward secrecy or retention beyond the bounds below.
|
|
621
|
+
*/
|
|
622
|
+
var HOLD_CAPABILITY = "hold/1";
|
|
623
|
+
var HOLD_LIMITS = {
|
|
624
|
+
/** One bundle, ciphertext and header included: a picture, not a video. */
|
|
625
|
+
maxBundleBytes: 8388608,
|
|
626
|
+
/** All bundles held for one contact at once. */
|
|
627
|
+
maxMailboxBytes: 67108864,
|
|
628
|
+
maxMailboxBundles: 64,
|
|
629
|
+
/** A bundle not picked up by then is dropped by its sender. The longest a presigned URL lives, too. */
|
|
630
|
+
ttlMs: 6048e5,
|
|
631
|
+
maxTextBytes: 16384,
|
|
632
|
+
maxPaymentRequestBytes: 65536,
|
|
633
|
+
maxManifestBytes: 65536,
|
|
634
|
+
/**
|
|
635
|
+
* How far past one lifetime from now an expiry may reach by the reader's clock: the sender's clock may be ahead, and
|
|
636
|
+
* a day covers any clock that is merely wrong. Nothing else about a pointer or a bundle is held against this clock.
|
|
637
|
+
*/
|
|
638
|
+
clockSkewMs: 864e5
|
|
639
|
+
};
|
|
640
|
+
/**
|
|
641
|
+
* How far before its own clock a sender dates its pointer and its manifest, and ends the lifetimes it gives. A reader
|
|
642
|
+
* refuses nothing for those dates: `rev` orders pointers and `seq` orders items, both kept by the reader. Apps up to
|
|
643
|
+
* 1.0.2 refuse a pointer or a manifest dated more than a minute past their clock, and an expiry more than a minute
|
|
644
|
+
* past one lifetime from now, each without a word: the items of a sender whose clock ran two minutes fast were never
|
|
645
|
+
* fetched. Dated back, a sender up to about eleven minutes ahead is read by them.
|
|
646
|
+
*/
|
|
647
|
+
var HOLD_DATED_BACK_MS = 6e5;
|
|
648
|
+
var KINDS = [
|
|
649
|
+
"text",
|
|
650
|
+
"file",
|
|
651
|
+
"pay-req",
|
|
652
|
+
"manifest"
|
|
653
|
+
];
|
|
654
|
+
var WIRE_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
655
|
+
var MAILBOX = /^[A-Za-z0-9_-]{22}$/;
|
|
656
|
+
var SIG = /^[A-Za-z0-9_-]{86}$/;
|
|
657
|
+
var MAGIC = utf8Encode("GHLD");
|
|
658
|
+
var VERSION = 1;
|
|
659
|
+
var NONCE = 24;
|
|
660
|
+
/** A bundle sealed by the chat's ratchet (WISP 4xx § Held items). */
|
|
661
|
+
var RATCHETED = 2;
|
|
662
|
+
/** Why a bundle, manifest or pointer was refused. Never a reason to trust it a little. */
|
|
663
|
+
var HoldRefusedError = class extends Error {
|
|
664
|
+
reason;
|
|
665
|
+
/** The bytes the chat's ratchet opened, when it opened them before the item was refused: the caller commits them. */
|
|
666
|
+
ratcheted;
|
|
667
|
+
constructor(reason, message) {
|
|
668
|
+
super(message);
|
|
669
|
+
this.reason = reason;
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
var bodyDigest = (body) => toBase64Url(sha256(body));
|
|
673
|
+
var newMailbox = () => toBase64Url(randomBytes(16)).slice(0, 22);
|
|
674
|
+
/**
|
|
675
|
+
* Everything derived once per link for this feature: my pointer key, the contact's pointer address and
|
|
676
|
+
* the key that seals bundles and pointers between the two participation keys. Needs a pinned contact.
|
|
677
|
+
*/
|
|
678
|
+
var HoldKeys = class {
|
|
679
|
+
from;
|
|
680
|
+
to;
|
|
681
|
+
me;
|
|
682
|
+
peer;
|
|
683
|
+
/** Publishes my pointer. */
|
|
684
|
+
identity;
|
|
685
|
+
/** Where the contact publishes its pointer. */
|
|
686
|
+
peerAddress;
|
|
687
|
+
seed;
|
|
688
|
+
sealKey;
|
|
689
|
+
constructor(params, participationSeedB64, peerKey) {
|
|
690
|
+
this.from = identityFromSeedB64(params.seedB64).pubKeyZ32;
|
|
691
|
+
this.to = params.peerPubKeyZ32;
|
|
692
|
+
const mine = identityFromSeedB64(participationSeedB64);
|
|
693
|
+
this.seed = mine.seed;
|
|
694
|
+
this.me = mine.pubKeyZ32;
|
|
695
|
+
this.peer = peerKey;
|
|
696
|
+
const secret = fromBase64Url(params.encKeyB64);
|
|
697
|
+
const context = JSON.stringify(["ghostly-hold/1", [this.from, this.to].sort()]);
|
|
698
|
+
const derive = (label) => hkdf(sha256, secret, utf8Encode(context), utf8Encode(label), 32);
|
|
699
|
+
this.identity = identityFromSeed(derive(`pointer:${this.from}`));
|
|
700
|
+
this.peerAddress = identityFromSeed(derive(`pointer:${this.to}`)).pubKeyZ32;
|
|
701
|
+
const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(this.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(peerKey)));
|
|
702
|
+
this.sealKey = hkdf(sha256, shared, derive("envelope"), utf8Encode("ghostly-hold-envelope/1"), 32);
|
|
703
|
+
}
|
|
704
|
+
/** Seals one item for the contact: signed with my participation key, encrypted to our shared key. */
|
|
705
|
+
seal(item, body) {
|
|
706
|
+
const nonce = randomBytes(NONCE);
|
|
707
|
+
const box = xsalsa20poly1305(this.sealKey, nonce).encrypt(this.inner(item, body));
|
|
708
|
+
return concatBytes(MAGIC, new Uint8Array([VERSION]), nonce, box);
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* The same item as a version-2 bundle (WISP 4xx § Held items): the same plaintext, sealed by the chat's ratchet
|
|
712
|
+
* (`seal`, which saves the ratchet's state before it returns), so the bundle can be uploaded once this returns.
|
|
713
|
+
*/
|
|
714
|
+
async sealRatcheted(item, body, seal) {
|
|
715
|
+
return concatBytes(MAGIC, new Uint8Array([RATCHETED]), await seal(this.inner(item, body)));
|
|
716
|
+
}
|
|
717
|
+
/** What a bundle seals: the header's length, the signed header, the body. */
|
|
718
|
+
inner(item, body) {
|
|
719
|
+
const fields = [
|
|
720
|
+
VERSION,
|
|
721
|
+
this.from,
|
|
722
|
+
this.to,
|
|
723
|
+
this.me,
|
|
724
|
+
this.peer,
|
|
725
|
+
item.mailbox,
|
|
726
|
+
item.seq,
|
|
727
|
+
item.id,
|
|
728
|
+
item.ts,
|
|
729
|
+
item.kind,
|
|
730
|
+
item.meta ?? null,
|
|
731
|
+
bodyDigest(body),
|
|
732
|
+
item.expires
|
|
733
|
+
];
|
|
734
|
+
const signature = toBase64Url(sign(utf8Encode(JSON.stringify(["ghostly-hold-bundle", fields])), this.seed));
|
|
735
|
+
const header = utf8Encode(JSON.stringify([fields, signature]));
|
|
736
|
+
const length = /* @__PURE__ */ new Uint8Array(4);
|
|
737
|
+
new DataView(length.buffer).setUint32(0, header.length);
|
|
738
|
+
return concatBytes(length, header, body);
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Opens a bundle the contact sealed for me. Everything is checked before anything is returned: the
|
|
742
|
+
* authenticated encryption, the header's shape, that it names this link, this contact and me, the
|
|
743
|
+
* signature, the body digest and the limits of its kind. `loopback`: see `isHoldUrl`.
|
|
744
|
+
*/
|
|
745
|
+
/**
|
|
746
|
+
* `ratchet`: opens a version-2 bundle's sealed bytes (WISP 4xx), without keeping anything; absent, one is from a newer
|
|
747
|
+
* Ghostly. `refusePlain`: a ratcheted item from this contact opened here, so a version-1 item other than the manifest is
|
|
748
|
+
* refused (WISP 4xx § Downgrade). `ratcheted` in the result: the bytes the ratchet opened, for the caller to commit once
|
|
749
|
+
* the item is stored.
|
|
750
|
+
*/
|
|
751
|
+
open(bytes, expect = {}) {
|
|
752
|
+
const now = expect.now ?? Date.now();
|
|
753
|
+
if (bytes.length > (expect.maxBytes ?? HOLD_LIMITS.maxBundleBytes)) throw new HoldRefusedError("size", "The held item is larger than allowed");
|
|
754
|
+
if (bytes.length < MAGIC.length + 1 + 16 + 4 || !MAGIC.every((b, i) => bytes[i] === b)) throw new HoldRefusedError("format", "Not a held item");
|
|
755
|
+
const version = bytes[MAGIC.length];
|
|
756
|
+
if (version !== VERSION && (version !== RATCHETED || !expect.ratchet)) throw new HoldRefusedError("format", "Held item from a newer Ghostly");
|
|
757
|
+
let plain, ratcheted;
|
|
758
|
+
if (version === RATCHETED) {
|
|
759
|
+
ratcheted = bytes.subarray(MAGIC.length + 1);
|
|
760
|
+
try {
|
|
761
|
+
plain = expect.ratchet(ratcheted);
|
|
762
|
+
} catch {
|
|
763
|
+
plain = null;
|
|
764
|
+
}
|
|
765
|
+
if (!plain) throw new HoldRefusedError("tampered", "The held item was changed, is not for this chat, or was opened already");
|
|
766
|
+
} else {
|
|
767
|
+
if (bytes.length < MAGIC.length + 1 + NONCE + 16 + 4) throw new HoldRefusedError("format", "Not a held item");
|
|
768
|
+
try {
|
|
769
|
+
plain = xsalsa20poly1305(this.sealKey, bytes.subarray(MAGIC.length + 1, MAGIC.length + 1 + NONCE)).decrypt(bytes.subarray(MAGIC.length + 1 + NONCE));
|
|
770
|
+
} catch {
|
|
771
|
+
throw new HoldRefusedError("tampered", "The held item was changed or is not for this chat");
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
try {
|
|
775
|
+
return this.read(plain, ratcheted, expect, now);
|
|
776
|
+
} catch (error) {
|
|
777
|
+
if (error instanceof HoldRefusedError && ratcheted) error.ratcheted = ratcheted;
|
|
778
|
+
throw error;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
/** The checks of `open` once the bundle is decrypted. */
|
|
782
|
+
read(plain, ratcheted, expect, now) {
|
|
783
|
+
if (plain.length < 4) throw new HoldRefusedError("format", "Not a held item");
|
|
784
|
+
const headerLength = new DataView(plain.buffer, plain.byteOffset, 4).getUint32(0);
|
|
785
|
+
if (headerLength > 131072 || 4 + headerLength > plain.length) throw new HoldRefusedError("format", "Not a held item");
|
|
786
|
+
let parsed;
|
|
787
|
+
try {
|
|
788
|
+
parsed = JSON.parse(utf8Decode(plain.subarray(4, 4 + headerLength)));
|
|
789
|
+
} catch {
|
|
790
|
+
throw new HoldRefusedError("format", "Not a held item");
|
|
791
|
+
}
|
|
792
|
+
if (!Array.isArray(parsed) || parsed.length !== 2 || !Array.isArray(parsed[0]) || parsed[0].length !== 13 || typeof parsed[1] !== "string" || !SIG.test(parsed[1])) throw new HoldRefusedError("format", "Not a held item");
|
|
793
|
+
const [fields, signature] = parsed;
|
|
794
|
+
const [v, from, to, author, recipient, mailbox, seq, id, ts, kind, meta, digest, expires] = fields;
|
|
795
|
+
if (v !== VERSION || typeof from !== "string" || typeof to !== "string" || typeof author !== "string" || typeof recipient !== "string" || typeof mailbox !== "string" || !MAILBOX.test(mailbox) || !Number.isSafeInteger(seq) || seq < 0 || typeof id !== "string" || !WIRE_ID.test(id) || !Number.isSafeInteger(ts) || ts <= 0 || typeof kind !== "string" || !KINDS.includes(kind) || typeof digest !== "string" || !Number.isSafeInteger(expires)) throw new HoldRefusedError("format", "Not a held item");
|
|
796
|
+
if (from !== this.to || to !== this.from || recipient !== this.me) throw new HoldRefusedError("not-for-me", "The held item is for another chat");
|
|
797
|
+
if (author !== this.peer) throw new HoldRefusedError("author", "The held item was not signed by this contact");
|
|
798
|
+
if (expect.mailbox && mailbox !== expect.mailbox) throw new HoldRefusedError("not-for-me", "The held item is from another mailbox");
|
|
799
|
+
let valid;
|
|
800
|
+
try {
|
|
801
|
+
valid = verify(fromBase64Url(signature), utf8Encode(JSON.stringify(["ghostly-hold-bundle", fields])), publicKeyFromZ32(author));
|
|
802
|
+
} catch {
|
|
803
|
+
valid = false;
|
|
804
|
+
}
|
|
805
|
+
if (!valid) throw new HoldRefusedError("signature", "The held item's signature does not check out");
|
|
806
|
+
const body = plain.subarray(4 + headerLength);
|
|
807
|
+
if (bodyDigest(body) !== digest) throw new HoldRefusedError("digest", "The held item's content does not match its header");
|
|
808
|
+
if (expires <= ts || expires > now + HOLD_LIMITS.ttlMs + HOLD_LIMITS.clockSkewMs) throw new HoldRefusedError("limits", "The held item's lifetime is out of bounds");
|
|
809
|
+
const header = {
|
|
810
|
+
v: 1,
|
|
811
|
+
from,
|
|
812
|
+
to,
|
|
813
|
+
author,
|
|
814
|
+
recipient,
|
|
815
|
+
mailbox,
|
|
816
|
+
seq,
|
|
817
|
+
id,
|
|
818
|
+
ts,
|
|
819
|
+
kind,
|
|
820
|
+
meta,
|
|
821
|
+
digest,
|
|
822
|
+
expires
|
|
823
|
+
};
|
|
824
|
+
if (!ratcheted && expect.refusePlain && kind !== "manifest") throw new HoldRefusedError("plain", "The held item was sealed without forward secrecy, which this chat no longer takes");
|
|
825
|
+
checkKind(header, body, expect.loopback);
|
|
826
|
+
return {
|
|
827
|
+
header,
|
|
828
|
+
body,
|
|
829
|
+
...ratcheted && { ratcheted }
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
/** My pointer, as records to publish under `identity`. Throws when it cannot fit a packet. */
|
|
833
|
+
pointerRecords(pointer, now = Date.now()) {
|
|
834
|
+
const body = [
|
|
835
|
+
VERSION,
|
|
836
|
+
pointer.rev,
|
|
837
|
+
pointer.issued,
|
|
838
|
+
pointer.expires,
|
|
839
|
+
pointer.manifestUrl,
|
|
840
|
+
pointer.top,
|
|
841
|
+
pointer.ack,
|
|
842
|
+
pointer.count,
|
|
843
|
+
pointer.bytes,
|
|
844
|
+
pointer.refused.slice(-32)
|
|
845
|
+
];
|
|
846
|
+
const signature = toBase64Url(sign(utf8Encode(JSON.stringify([
|
|
847
|
+
"ghostly-hold-pointer",
|
|
848
|
+
this.from,
|
|
849
|
+
this.to,
|
|
850
|
+
body
|
|
851
|
+
])), this.seed));
|
|
852
|
+
const ttl = Math.min(86400, Math.max(60, Math.ceil((pointer.expires - now) / 1e3)));
|
|
853
|
+
const records = [{
|
|
854
|
+
label: "_hold",
|
|
855
|
+
value: encrypt(JSON.stringify([body, signature]), this.sealKey),
|
|
856
|
+
ttl
|
|
857
|
+
}];
|
|
858
|
+
if (measureRecords(this.identity.pubKeyZ32, records) > 1e3) throw new Error("The storage address is too long for a DHT packet. Use a shorter endpoint or prefix.");
|
|
859
|
+
return records;
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* The contact's pointer out of its packet, or null when the packet is not one of its pointers. Its `issued` is the
|
|
863
|
+
* contact's clock and refuses nothing: an older pointer cannot take a newer one's place because of `rev`. The
|
|
864
|
+
* manifest's address is held to what an item's is (`isHoldUrl`): it is fetched as soon as the pointer is read.
|
|
865
|
+
*/
|
|
866
|
+
readPointer(packet, loopback = false) {
|
|
867
|
+
if (packet.pubKeyZ32 !== this.peerAddress || measureRecords(packet.pubKeyZ32, packet.records) > 1e3) return null;
|
|
868
|
+
const records = packet.records.filter((r) => r.label === "_hold");
|
|
869
|
+
if (records.length !== 1) return null;
|
|
870
|
+
const plain = tryDecrypt(records[0].value, this.sealKey);
|
|
871
|
+
if (!plain) return null;
|
|
872
|
+
let parsed;
|
|
873
|
+
try {
|
|
874
|
+
parsed = JSON.parse(plain);
|
|
875
|
+
} catch {
|
|
876
|
+
return null;
|
|
877
|
+
}
|
|
878
|
+
if (!Array.isArray(parsed) || parsed.length !== 2 || !Array.isArray(parsed[0]) || parsed[0].length !== 9 && parsed[0].length !== 10 || typeof parsed[1] !== "string" || !SIG.test(parsed[1])) return null;
|
|
879
|
+
const [body, signature] = parsed;
|
|
880
|
+
const [v, rev, issued, expires, manifestUrl, top, ack, count, bytes, refused = []] = body;
|
|
881
|
+
if (v !== VERSION || ![
|
|
882
|
+
rev,
|
|
883
|
+
issued,
|
|
884
|
+
expires,
|
|
885
|
+
top,
|
|
886
|
+
ack,
|
|
887
|
+
count,
|
|
888
|
+
bytes
|
|
889
|
+
].every((n) => Number.isSafeInteger(n) && n >= 0) || manifestUrl !== null && !isHoldUrl(manifestUrl, loopback) || !Array.isArray(refused) || refused.length > 32 || !refused.every((n) => Number.isSafeInteger(n) && n > 0)) return null;
|
|
890
|
+
try {
|
|
891
|
+
if (!verify(fromBase64Url(signature), utf8Encode(JSON.stringify([
|
|
892
|
+
"ghostly-hold-pointer",
|
|
893
|
+
this.to,
|
|
894
|
+
this.from,
|
|
895
|
+
body
|
|
896
|
+
])), publicKeyFromZ32(this.peer))) return null;
|
|
897
|
+
} catch {
|
|
898
|
+
return null;
|
|
899
|
+
}
|
|
900
|
+
return {
|
|
901
|
+
rev,
|
|
902
|
+
issued,
|
|
903
|
+
expires,
|
|
904
|
+
manifestUrl,
|
|
905
|
+
top,
|
|
906
|
+
ack,
|
|
907
|
+
count,
|
|
908
|
+
bytes,
|
|
909
|
+
refused
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
};
|
|
913
|
+
/** Names only a local network answers (RFC 6762, RFC 8375, ICANN's .internal, and the usual router ones). */
|
|
914
|
+
var LOCAL_SUFFIXES = [
|
|
915
|
+
"localhost",
|
|
916
|
+
"local",
|
|
917
|
+
"internal",
|
|
918
|
+
"lan",
|
|
919
|
+
"home",
|
|
920
|
+
"home.arpa",
|
|
921
|
+
"localdomain",
|
|
922
|
+
"intranet",
|
|
923
|
+
"corp"
|
|
924
|
+
];
|
|
925
|
+
/**
|
|
926
|
+
* A URL a bundle or manifest may be fetched from. The contact chose it and this device fetches it on its own, so it
|
|
927
|
+
* is HTTPS, without a user or password, at a public name or a public IPv4 address: never this machine or its network.
|
|
928
|
+
* A name with no dot or under a local suffix is a local one. A public name may still resolve to a local address:
|
|
929
|
+
* where the host can resolve, its `fetch` refuses that too (the CLI's, packages/cli/src/runtime/holdFetch.ts, and
|
|
930
|
+
* Desktop's, apps/desktop/src/hold_fetch.rs).
|
|
931
|
+
* `loopback` adds plain HTTP to this machine, for a test against a local server; no shipped app passes it.
|
|
932
|
+
*/
|
|
933
|
+
function isHoldUrl(value, loopback = false) {
|
|
934
|
+
if (typeof value !== "string" || value.length > 2048) return false;
|
|
935
|
+
let url;
|
|
936
|
+
try {
|
|
937
|
+
url = new URL(value);
|
|
938
|
+
} catch {
|
|
939
|
+
return false;
|
|
940
|
+
}
|
|
941
|
+
if (url.username || url.password) return false;
|
|
942
|
+
const host = url.hostname.toLowerCase().replace(/\.$/, "");
|
|
943
|
+
if (loopback && url.protocol === "http:" && [
|
|
944
|
+
"localhost",
|
|
945
|
+
"127.0.0.1",
|
|
946
|
+
"[::1]"
|
|
947
|
+
].includes(host)) return true;
|
|
948
|
+
if (url.protocol !== "https:" || !host.includes(".") || host.startsWith("[") || LOCAL_SUFFIXES.some((s) => host === s || host.endsWith(`.${s}`))) return false;
|
|
949
|
+
return !/^\d+\.\d+\.\d+\.\d+$/.test(host) || isPublicAddress(Uint8Array.from(host.split("."), Number));
|
|
950
|
+
}
|
|
951
|
+
/** The limits of each kind, on the way in. */
|
|
952
|
+
function checkKind(header, body, loopback = false) {
|
|
953
|
+
const bad = (message) => new HoldRefusedError("limits", message);
|
|
954
|
+
switch (header.kind) {
|
|
955
|
+
case "text":
|
|
956
|
+
if (body.length > HOLD_LIMITS.maxTextBytes) throw bad("The held text is too long");
|
|
957
|
+
try {
|
|
958
|
+
utf8Decode(body);
|
|
959
|
+
} catch {
|
|
960
|
+
throw bad("The held text is not text");
|
|
961
|
+
}
|
|
962
|
+
return;
|
|
963
|
+
case "pay-req":
|
|
964
|
+
if (body.length > HOLD_LIMITS.maxPaymentRequestBytes) throw bad("The held payment request is too large");
|
|
965
|
+
return;
|
|
966
|
+
case "file": {
|
|
967
|
+
const meta = header.meta;
|
|
968
|
+
if (!meta || typeof meta !== "object" || typeof meta.name !== "string" || meta.name.length > 255 || typeof meta.mime !== "string" || meta.mime.length > 255 || meta.size !== body.length) throw bad("The held file does not match its description");
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
case "manifest":
|
|
972
|
+
if (body.length !== 0) throw bad("A manifest carries no body");
|
|
973
|
+
readManifest(header.meta, loopback);
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
/** The entries of a manifest, checked: strictly increasing sequences, bounded sizes, fetchable URLs. */
|
|
978
|
+
function readManifest(meta, loopback = false) {
|
|
979
|
+
const bad = (message) => new HoldRefusedError("limits", message);
|
|
980
|
+
const entries = meta?.entries;
|
|
981
|
+
if (!Array.isArray(entries) || entries.length > HOLD_LIMITS.maxMailboxBundles) throw bad("The manifest lists too many items");
|
|
982
|
+
let last = 0, total = 0;
|
|
983
|
+
const out = [];
|
|
984
|
+
for (const entry of entries) {
|
|
985
|
+
if (!Array.isArray(entry) || entry.length !== 6) throw bad("The manifest is malformed");
|
|
986
|
+
const [seq, id, kind, bytes, url, expires] = entry;
|
|
987
|
+
if (!Number.isSafeInteger(seq) || seq <= last || typeof id !== "string" || !WIRE_ID.test(id) || typeof kind !== "string" || !KINDS.includes(kind) || kind === "manifest" || !Number.isSafeInteger(bytes) || bytes < 0 || bytes > HOLD_LIMITS.maxBundleBytes || !isHoldUrl(url, loopback) || !Number.isSafeInteger(expires)) throw bad("The manifest is malformed");
|
|
988
|
+
last = seq;
|
|
989
|
+
total += bytes;
|
|
990
|
+
if (total > HOLD_LIMITS.maxMailboxBytes) throw bad("The manifest lists more than a mailbox may hold");
|
|
991
|
+
out.push([
|
|
992
|
+
seq,
|
|
993
|
+
id,
|
|
994
|
+
kind,
|
|
995
|
+
bytes,
|
|
996
|
+
url,
|
|
997
|
+
expires
|
|
998
|
+
]);
|
|
999
|
+
}
|
|
1000
|
+
return out;
|
|
1001
|
+
}
|
|
1002
|
+
// ../core/src/pairedTransports.ts
|
|
1003
|
+
var TRANSPORTS = [
|
|
1004
|
+
"iroh/1",
|
|
1005
|
+
"hyperdht/1",
|
|
1006
|
+
"webrtc/1"
|
|
1007
|
+
];
|
|
1008
|
+
function irohRelayUrl(value, spelling = "dotted") {
|
|
1009
|
+
let url;
|
|
1010
|
+
try {
|
|
1011
|
+
url = new URL(value);
|
|
1012
|
+
} catch {
|
|
1013
|
+
return value;
|
|
1014
|
+
}
|
|
1015
|
+
const host = url.hostname, name = host.replace(/\.$/, "");
|
|
1016
|
+
if (!name.includes(".") && name !== "localhost") return value;
|
|
1017
|
+
if (name.startsWith("[") || /^\d+(\.\d+){3}$/.test(name)) return value;
|
|
1018
|
+
const wanted = spelling === "dotted" && /(^|\.)iroh\.link$/.test(name) ? `${name}.` : name;
|
|
1019
|
+
if (wanted === host) return value;
|
|
1020
|
+
url.hostname = wanted;
|
|
1021
|
+
return url.href;
|
|
1022
|
+
}
|
|
1023
|
+
/** An Iroh descriptor with its relay in one spelling (`irohRelayUrl`); anything else as it is. */
|
|
1024
|
+
function irohDescriptor(descriptor, spelling = "dotted") {
|
|
1025
|
+
const relay = descriptor?.relay;
|
|
1026
|
+
if (typeof relay !== "string") return descriptor;
|
|
1027
|
+
const canonical = irohRelayUrl(relay, spelling);
|
|
1028
|
+
return canonical === relay ? descriptor : {
|
|
1029
|
+
...descriptor,
|
|
1030
|
+
relay: canonical
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* A relay server's URL, short: https, or wss for a browser's relay; plain http or ws only on this machine's loopback,
|
|
1035
|
+
* as a test relay is (the same rule as the relay settings).
|
|
1036
|
+
*/
|
|
1037
|
+
var RELAY_URL = /^((https|wss):\/\/[^\s]{1,120}|(http|ws):\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d{1,5})?(\/[^\s]{0,100})?)$/;
|
|
1038
|
+
/**
|
|
1039
|
+
* A relay URL with more than its server's address in it: a login, a query or a fragment, which no relay setting takes
|
|
1040
|
+
* (irohWeb.ts `irohRelayProblem`, hyperdhtRelay.ts `hyperdhtRelayProblem`). An older app named its HyperDHT relay as
|
|
1041
|
+
* set, with them; such a descriptor is not dialed or kept, and the rest of what the contact told still is.
|
|
1042
|
+
*/
|
|
1043
|
+
var RELAY_WITH_SECRETS = /^[a-z]+:\/\/[^/?#]*@|[?#]/i;
|
|
1044
|
+
/** A relay URL a descriptor may name: `RELAY_URL`, with nothing but the server's address in it. */
|
|
1045
|
+
var relayUrl = (value) => typeof value === "string" && RELAY_URL.test(value) && !RELAY_WITH_SECRETS.test(value);
|
|
1046
|
+
/** `RELAY_URL` at any length. */
|
|
1047
|
+
var RELAY_URL_ANY_LENGTH = /^((https|wss):\/\/[^\s]+|(http|ws):\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d{1,5})?(\/[^\s]*)?)$/;
|
|
1048
|
+
/**
|
|
1049
|
+
* A relay URL `relayUrl` refuses for its length alone (past 120 characters, a loopback path past 100): a relay setting
|
|
1050
|
+
* asks for a shorter one, where "not a relay address" sent the person looking for a typo in it.
|
|
1051
|
+
*/
|
|
1052
|
+
var relayUrlTooLong = (value) => !relayUrl(value) && !RELAY_WITH_SECRETS.test(value) && RELAY_URL_ANY_LENGTH.test(value);
|
|
1053
|
+
/**
|
|
1054
|
+
* Whether an Iroh endpoint may dial a contact through the relay its descriptor names (none: a direct address alone).
|
|
1055
|
+
* The contact chose that relay and this device opens it on its own, again on each redial, so it is held to what a held
|
|
1056
|
+
* item's address is (`isHoldUrl`): https at a public name or a public address, never this machine or its network.
|
|
1057
|
+
* One of the endpoint's own relays (`own`: the person's settings, a private network's or a test's) is dialled as well,
|
|
1058
|
+
* in either spelling: this device opens it anyway.
|
|
1059
|
+
*/
|
|
1060
|
+
function dialableIrohRelay(relay, own) {
|
|
1061
|
+
if (relay === null || relay === void 0) return true;
|
|
1062
|
+
if (!relayUrl(relay)) return false;
|
|
1063
|
+
const same = (a, b) => {
|
|
1064
|
+
try {
|
|
1065
|
+
return new URL(irohRelayUrl(a, "plain")).href === new URL(irohRelayUrl(b, "plain")).href;
|
|
1066
|
+
} catch {
|
|
1067
|
+
return false;
|
|
1068
|
+
}
|
|
1069
|
+
};
|
|
1070
|
+
return own.some((mine) => same(mine, relay)) || isHoldUrl(relay);
|
|
1071
|
+
}
|
|
1072
|
+
var HEX_KEY = /^[0-9a-f]{64}$/;
|
|
1073
|
+
/** An Iroh direct address as the adapters parse it: an IPv4 or bracketed IPv6 address and its port. */
|
|
1074
|
+
var SOCKET_ADDRESS = /^(\d{1,3}(\.\d{1,3}){3}|\[[0-9A-Fa-f:.]{2,45}(%[A-Za-z0-9._-]{1,16})?\]):\d{1,5}$/;
|
|
1075
|
+
var MAX_ADDRESSES = 8;
|
|
1076
|
+
/**
|
|
1077
|
+
* A contact's native descriptors as it tells them on a session (`paired-policy`, `paired-adapters`) or as this app
|
|
1078
|
+
* kept them: only what the adapters dial, each field in the shape its adapter makes. The keys are 64 hex characters,
|
|
1079
|
+
* a relay passes `relayUrl` (the rule its capability record is read by), an Iroh descriptor lists at most eight
|
|
1080
|
+
* socket addresses. A descriptor that is anything else is left out, as one the contact never told; a field this app
|
|
1081
|
+
* does not know is not kept.
|
|
1082
|
+
*/
|
|
1083
|
+
function checkedDescriptors(value) {
|
|
1084
|
+
const out = {};
|
|
1085
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return out;
|
|
1086
|
+
const raw = value;
|
|
1087
|
+
const relayed = (v) => v === void 0 || typeof v === "boolean";
|
|
1088
|
+
const iroh = raw["iroh/1"];
|
|
1089
|
+
if (iroh && typeof iroh === "object" && typeof iroh.id === "string" && HEX_KEY.test(iroh.id) && (iroh.relay === void 0 || iroh.relay === null || relayUrl(iroh.relay)) && relayed(iroh.relayed) && Array.isArray(iroh.addresses) && iroh.addresses.length <= MAX_ADDRESSES && iroh.addresses.every((a) => typeof a === "string" && SOCKET_ADDRESS.test(a))) out["iroh/1"] = {
|
|
1090
|
+
id: iroh.id,
|
|
1091
|
+
relay: iroh.relay ?? null,
|
|
1092
|
+
addresses: [...iroh.addresses],
|
|
1093
|
+
...iroh.relayed !== void 0 ? { relayed: iroh.relayed } : {}
|
|
1094
|
+
};
|
|
1095
|
+
const hyper = raw["hyperdht/1"];
|
|
1096
|
+
if (hyper && typeof hyper === "object" && typeof hyper.publicKey === "string" && HEX_KEY.test(hyper.publicKey) && (hyper.relay === void 0 || relayUrl(hyper.relay)) && relayed(hyper.relayed)) out["hyperdht/1"] = {
|
|
1097
|
+
publicKey: hyper.publicKey,
|
|
1098
|
+
...hyper.relay !== void 0 ? { relay: hyper.relay } : {},
|
|
1099
|
+
...hyper.relayed !== void 0 ? { relayed: hyper.relayed } : {}
|
|
1100
|
+
};
|
|
1101
|
+
return out;
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Relay only (WISP 100, "Relayed"): the transport reaches this contact only through a relay server, never
|
|
1105
|
+
* directly. A descriptor says so with `relayed: true`, and an Iroh descriptor with no direct address is relayed
|
|
1106
|
+
* too (a browser's, WISP 102). Either side being relay only makes the whole path relayed. Both sides hold both
|
|
1107
|
+
* descriptors after the exchange, so they agree, and the rank stays symmetric.
|
|
1108
|
+
*/
|
|
1109
|
+
function relayedTransports(local, remote) {
|
|
1110
|
+
const relayOnly = (transport, descriptor) => {
|
|
1111
|
+
if (!descriptor || typeof descriptor !== "object") return false;
|
|
1112
|
+
const d = descriptor;
|
|
1113
|
+
return d.relayed === true || transport === "iroh/1" && Array.isArray(d.addresses) && d.addresses.length === 0;
|
|
1114
|
+
};
|
|
1115
|
+
return ["iroh/1", "hyperdht/1"].filter((t) => relayOnly(t, local[t]) || relayOnly(t, remote[t]));
|
|
1116
|
+
}
|
|
1117
|
+
/** Symmetric rank sum; the fixed order breaks ties deterministically. Neither
|
|
1118
|
+
* a remote list nor a preference can add an unavailable local adapter. A
|
|
1119
|
+
* relayed transport ranks after every direct one: it is where a failed direct
|
|
1120
|
+
* path goes, never ahead of one that works. Iroh through its relay is the
|
|
1121
|
+
* exception (WISP 100, revision 2026-11-08): it comes back almost at once after
|
|
1122
|
+
* the app was away, and a browser's Iroh is never anything else. */
|
|
1123
|
+
function rankTransports(local, remote, relayed = []) {
|
|
1124
|
+
const penalty = (t) => t !== "iroh/1" && relayed.includes(t) ? 1 : 0;
|
|
1125
|
+
return TRANSPORTS.filter((t) => local.includes(t) && remote.includes(t)).sort((a, b) => penalty(a) - penalty(b) || local.indexOf(a) + remote.indexOf(a) - (local.indexOf(b) + remote.indexOf(b)) || TRANSPORTS.indexOf(a) - TRANSPORTS.indexOf(b));
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* What a chat prefers when nobody chose (Automatic): Iroh where the app has it, then WebRTC, then HyperDHT (WISP 100,
|
|
1129
|
+
* revision 2026-11-08). Every app puts Iroh first, so the rank sum of two apps that both run it puts it first on both
|
|
1130
|
+
* sides. With nothing at all, WebRTC, which the offer then leaves out.
|
|
1131
|
+
* With Fallback off the chat may use only that one transport, and nothing moves it off a relayed Iroh then: WebRTC
|
|
1132
|
+
* where the app has it, else the first transport it has (a Linux Desktop: WebKitGTK has no WebRTC), as before.
|
|
1133
|
+
*/
|
|
1134
|
+
var AUTOMATIC_ORDER = [
|
|
1135
|
+
"iroh/1",
|
|
1136
|
+
"webrtc/1",
|
|
1137
|
+
"hyperdht/1"
|
|
1138
|
+
];
|
|
1139
|
+
function automaticTransport(available, fallback = true) {
|
|
1140
|
+
if (!fallback) return available.includes("webrtc/1") ? "webrtc/1" : TRANSPORTS.find((t) => available.includes(t)) ?? "webrtc/1";
|
|
1141
|
+
return AUTOMATIC_ORDER.find((t) => available.includes(t)) ?? "webrtc/1";
|
|
1142
|
+
}
|
|
1143
|
+
function transportOrder(available, preferred, fallback) {
|
|
1144
|
+
const rest = TRANSPORTS.filter((t) => available.includes(t) && t !== preferred);
|
|
1145
|
+
return [...available.includes(preferred) ? [preferred] : [], ...fallback ? rest : []];
|
|
1146
|
+
}
|
|
1147
|
+
export { openRelayPayload as $, WELL_KNOWN_PATH as A, recordsFromTxt as B, DNS_LABEL as C, DOMAIN_METHODS as D, DOMAIN_MAX_RECORDS as E, encodeDnsQuery as F, wellKnownUrl as G, recordsName as H, isPublicAddress as I, PacketTooLargeError as J, MAX_DNS_PACKET_BYTES as K, nip05RootKey as L, dnsProofName as M, domainTxtRecord as N, DOMAIN_TXT_MAX_BYTES as O, domainWellKnownFile as P, newerPacket as Q, normalizeDomain as R, readManifest as S, DOMAIN_FILE_MAX_BYTES as T, txtValue as U, recordsFromWellKnown as V, validDomainRecord as W, createRelayPayload as X, RELAY_PAYLOAD_MAX_BYTES as Y, measureRecords as Z, HOLD_LIMITS as _, automaticTransport as a, encodeTxtPacket as at, isHoldUrl as b, irohDescriptor as c, encrypt as ct, relayUrl as d, tryDecrypt as dt, parseRelayPayload as et, relayUrlTooLong as f, HOLD_DATED_BACK_MS as g, HOLD_CAPABILITY as h, TRANSPORTS as i, decodeTxtPacket as it, decodeDnsResponse as j, NIP05_PATH as k, irohRelayUrl as l, generateEncryptionKey as lt, transportOrder as m, RELAY_URL as n, signRelayPayload as nt, checkedDescriptors as o, readDnsName as ot, relayedTransports as p, PKARR_FUTURE_SKEW_MS as q, RELAY_WITH_SECRETS as r, decodeDnsAnswers as rt, dialableIrohRelay as s, decrypt as st, AUTOMATIC_ORDER as t, readOwnRelayPayload as tt, rankTransports as u, sealedLength as ut, HoldKeys as v, DNS_TYPE as w, newMailbox as x, HoldRefusedError as y, parseDomainTxt as z };
|
|
1148
|
+
|
|
1149
|
+
//# sourceMappingURL=pairedTransports-CkYMAoYN.js.map
|