@handlepay/resolve 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +99 -2
- package/dist/index.js +806 -0
- package/dist/index.js.map +1 -0
- package/dist/types/packages/resolve/src/index.d.ts +42 -0
- package/dist/types/src/lib/auth.d.ts +18 -0
- package/dist/types/src/lib/binding.d.ts +116 -0
- package/dist/types/src/lib/network.d.ts +36 -0
- package/dist/types/src/lib/nostr.d.ts +95 -0
- package/dist/types/src/lib/resolve.d.ts +35 -0
- package/package.json +29 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,806 @@
|
|
|
1
|
+
import { binToHex, cashAddressToLockingBytecode, decodeCashAddress, decodeTransaction, hashTransaction, hexToBin } from "@bitauth/libauth";
|
|
2
|
+
import { ElectrumNetworkProvider } from "cashscript";
|
|
3
|
+
import { SimplePool } from "nostr-tools/pool";
|
|
4
|
+
import { verifyEvent } from "nostr-tools/pure";
|
|
5
|
+
// ../../src/lib/network.ts
|
|
6
|
+
/** CashAddr prefix for each network. */
|
|
7
|
+
var PREFIX = {
|
|
8
|
+
chipnet: "bchtest",
|
|
9
|
+
mainnet: "bitcoincash"
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Electrum providers are cached per network. Each one opens a WebSocket to a
|
|
13
|
+
* public Fulcrum server (CashScript's defaults: chipnet.bch.ninja for chipnet,
|
|
14
|
+
* bch.imaginary.cash for mainnet). Override with VITE_ELECTRUM_CHIPNET /
|
|
15
|
+
* VITE_ELECTRUM_MAINNET if a default server is down.
|
|
16
|
+
*/
|
|
17
|
+
var providers = /* @__PURE__ */ new Map();
|
|
18
|
+
function getProvider(network) {
|
|
19
|
+
let provider = providers.get(network);
|
|
20
|
+
if (!provider) {
|
|
21
|
+
const hostname = network === "chipnet" ? void 0 : void 0;
|
|
22
|
+
provider = hostname ? new ElectrumNetworkProvider(network, { hostname }) : new ElectrumNetworkProvider(network);
|
|
23
|
+
providers.set(network, provider);
|
|
24
|
+
}
|
|
25
|
+
return provider;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Raw transaction plus confirmation count, from Fulcrum's verbose
|
|
29
|
+
* `blockchain.transaction.get`. Callers re-hash `hex` against the txid; the
|
|
30
|
+
* server is only trusted for availability and confirmation depth.
|
|
31
|
+
*/
|
|
32
|
+
/**
|
|
33
|
+
* True when the server answered that the transaction doesn't exist, as
|
|
34
|
+
* opposed to not answering at all (timeout, connection dropped). Only the
|
|
35
|
+
* first may be shown as "not found"; the second means "couldn't check".
|
|
36
|
+
*/
|
|
37
|
+
function isTxNotFound(e) {
|
|
38
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
39
|
+
return /no such mempool|not found|unknown transaction/i.test(message);
|
|
40
|
+
}
|
|
41
|
+
async function getTransaction(network, txid) {
|
|
42
|
+
const result = await getProvider(network).performRequest("blockchain.transaction.get", txid, true);
|
|
43
|
+
if (typeof result === "string") return {
|
|
44
|
+
hex: result,
|
|
45
|
+
confirmations: 0
|
|
46
|
+
};
|
|
47
|
+
const r = result;
|
|
48
|
+
if (typeof r?.hex !== "string") throw new Error(`Transaction ${txid} not found.`);
|
|
49
|
+
return {
|
|
50
|
+
hex: r.hex,
|
|
51
|
+
confirmations: typeof r.confirmations === "number" ? r.confirmations : 0
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
// ../../src/lib/binding.ts
|
|
55
|
+
/**
|
|
56
|
+
* HPAY-BIND v1: a name is Verified when two proofs point at each other.
|
|
57
|
+
*
|
|
58
|
+
* - A BCH proof transaction, spent only from the bound address, carries
|
|
59
|
+
* `OP_RETURN "HPAY" 0x01 <32-byte x-only Nostr pubkey>`.
|
|
60
|
+
* - A Nostr event signed by that pubkey names the address and the proof txid.
|
|
61
|
+
*
|
|
62
|
+
* This module is pure: building events, parsing them, and checking a proof
|
|
63
|
+
* transaction from raw bytes. Fetching lives in nostr.ts and resolve.ts.
|
|
64
|
+
*/
|
|
65
|
+
/** Binding event kind. Placeholder until Paytaca confirms a number. */
|
|
66
|
+
var BINDING_KIND = 30145;
|
|
67
|
+
var BINDING_D = "bch-bind";
|
|
68
|
+
/** NIP-A3 public payment target. */
|
|
69
|
+
var PAYTO_KIND = 10133;
|
|
70
|
+
/** Paytaca's existing app-data format; read-only, never Verified. */
|
|
71
|
+
var PAYTACA_KIND = 30078;
|
|
72
|
+
var PAYTACA_D = "paytaca:bch-address";
|
|
73
|
+
var PROOF_MAGIC = "48504159";
|
|
74
|
+
var PROOF_VERSION = 1;
|
|
75
|
+
var HEX64$1 = /^[0-9a-f]{64}$/;
|
|
76
|
+
/** Strip the `bitcoincash:` / `bchtest:` prefix (tags store addresses bare). */
|
|
77
|
+
function bareAddress(address) {
|
|
78
|
+
const i = address.indexOf(":");
|
|
79
|
+
return (i >= 0 ? address.slice(i + 1) : address).toLowerCase();
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Normalise an address (with or without prefix) to the full P2PKH cashaddr for
|
|
83
|
+
* `network`. Returns null if it doesn't decode, belongs to another network, or
|
|
84
|
+
* isn't P2PKH (bindings are P2PKH only).
|
|
85
|
+
*/
|
|
86
|
+
function normalizeAddress(address, network) {
|
|
87
|
+
const full = `${PREFIX[network]}:${bareAddress(address)}`;
|
|
88
|
+
if (address.includes(":") && !address.toLowerCase().startsWith(`${PREFIX[network]}:`)) return null;
|
|
89
|
+
const decoded = decodeCashAddress(full);
|
|
90
|
+
if (typeof decoded === "string") return null;
|
|
91
|
+
if (decoded.type !== "p2pkh") return null;
|
|
92
|
+
return full;
|
|
93
|
+
}
|
|
94
|
+
function lockingBytecodeHex(address) {
|
|
95
|
+
const decoded = cashAddressToLockingBytecode(address);
|
|
96
|
+
if (typeof decoded === "string") throw new Error(decoded);
|
|
97
|
+
return binToHex(decoded.bytecode);
|
|
98
|
+
}
|
|
99
|
+
/** OP_RETURN chunks for `sendBch({ opReturn })`, in CashScript's "0x…" hex form. */
|
|
100
|
+
function proofOpReturnChunks(pubkeyHex) {
|
|
101
|
+
const pubkey = pubkeyHex.toLowerCase();
|
|
102
|
+
if (!HEX64$1.test(pubkey)) throw new Error("Nostr pubkey must be 32 bytes of hex.");
|
|
103
|
+
return [
|
|
104
|
+
`0x${PROOF_MAGIC}`,
|
|
105
|
+
`0x01`,
|
|
106
|
+
`0x${pubkey}`
|
|
107
|
+
];
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Read the committed pubkey from one output's locking bytecode. Only the exact
|
|
111
|
+
* canonical form is accepted:
|
|
112
|
+
* `6a 04 48504159 01 01 20 <32 bytes>` (41 bytes).
|
|
113
|
+
*/
|
|
114
|
+
function parseProofOutput(lockingBytecode) {
|
|
115
|
+
const hex = binToHex(lockingBytecode);
|
|
116
|
+
const head = `6a04${PROOF_MAGIC}010120`;
|
|
117
|
+
if (hex.length !== head.length + 64 || !hex.startsWith(head)) return null;
|
|
118
|
+
return hex.slice(head.length);
|
|
119
|
+
}
|
|
120
|
+
/** Every pubkey a transaction commits to via an HPAY output. */
|
|
121
|
+
function proofCommitments(tx) {
|
|
122
|
+
return tx.outputs.map((o) => parseProofOutput(o.lockingBytecode)).filter((p) => p !== null);
|
|
123
|
+
}
|
|
124
|
+
function decodeHex(hex) {
|
|
125
|
+
try {
|
|
126
|
+
const tx = decodeTransaction(hexToBin(hex));
|
|
127
|
+
return typeof tx === "string" ? null : tx;
|
|
128
|
+
} catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* The four BCH-side checks, all re-derived from raw bytes so a server can't
|
|
134
|
+
* fake them beyond withholding data:
|
|
135
|
+
*
|
|
136
|
+
* a. every input spends a coin locked to the claimed address;
|
|
137
|
+
* b. an output is `OP_RETURN HPAY 01 <pubkey>` with the event author's pubkey;
|
|
138
|
+
* c. at least one confirmation;
|
|
139
|
+
* d. the event's network matches the page's.
|
|
140
|
+
*
|
|
141
|
+
* Spec note: v1 requires *every* input to come from the bound address (the
|
|
142
|
+
* proof transaction has "no other inputs"), so a mixed-input transaction is
|
|
143
|
+
* Claimed, not Verified.
|
|
144
|
+
*/
|
|
145
|
+
function checkProof(input) {
|
|
146
|
+
const { proofHex, proofTxid, confirmations, parents, address, pubkey, eventNetwork, network } = input;
|
|
147
|
+
const checks = [];
|
|
148
|
+
const tx = decodeHex(proofHex);
|
|
149
|
+
const hashOk = tx !== null && hashTransaction(hexToBin(proofHex)) === proofTxid;
|
|
150
|
+
let spends = {
|
|
151
|
+
id: "spends",
|
|
152
|
+
ok: false,
|
|
153
|
+
label: "Proof was paid from this address"
|
|
154
|
+
};
|
|
155
|
+
if (!hashOk) spends.detail = "Proof transaction could not be read";
|
|
156
|
+
else {
|
|
157
|
+
const want = lockingBytecodeHex(address);
|
|
158
|
+
let ok = tx.inputs.length > 0;
|
|
159
|
+
let detail;
|
|
160
|
+
for (const inp of tx.inputs) {
|
|
161
|
+
const parentTxid = binToHex(inp.outpointTransactionHash);
|
|
162
|
+
const parentHex = parents.get(parentTxid);
|
|
163
|
+
const spent = (parentHex && hashTransaction(hexToBin(parentHex)) === parentTxid ? decodeHex(parentHex) : null)?.outputs[inp.outpointIndex];
|
|
164
|
+
if (!spent) {
|
|
165
|
+
ok = false;
|
|
166
|
+
detail = "Could not read a coin the proof spent";
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
if (binToHex(spent.lockingBytecode) !== want) {
|
|
170
|
+
ok = false;
|
|
171
|
+
detail = "Proof spends a coin from a different address";
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
spends = {
|
|
176
|
+
...spends,
|
|
177
|
+
ok,
|
|
178
|
+
detail: ok ? void 0 : detail
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
checks.push(spends);
|
|
182
|
+
const commitments = hashOk ? proofCommitments(tx) : [];
|
|
183
|
+
const commits = {
|
|
184
|
+
id: "commits",
|
|
185
|
+
ok: commitments.includes(pubkey.toLowerCase()),
|
|
186
|
+
label: "Proof names this Nostr key"
|
|
187
|
+
};
|
|
188
|
+
if (!commits.ok) commits.detail = commitments.length ? "Proof names a different Nostr key" : hashOk ? "No HandlePay proof in this transaction" : "Proof transaction could not be read";
|
|
189
|
+
checks.push(commits);
|
|
190
|
+
checks.push({
|
|
191
|
+
id: "confirmed",
|
|
192
|
+
ok: hashOk && confirmations >= 1,
|
|
193
|
+
label: "Proof is confirmed on chain",
|
|
194
|
+
detail: hashOk && confirmations < 1 ? "Waiting for confirmation" : hashOk ? void 0 : "Proof not found"
|
|
195
|
+
});
|
|
196
|
+
const netOk = eventNetwork === network;
|
|
197
|
+
checks.push({
|
|
198
|
+
id: "network",
|
|
199
|
+
ok: netOk,
|
|
200
|
+
label: `Binding is for ${network}`,
|
|
201
|
+
detail: netOk ? void 0 : `Binding is for ${eventNetwork || "an unknown network"}`
|
|
202
|
+
});
|
|
203
|
+
return checks;
|
|
204
|
+
}
|
|
205
|
+
function buildBindingEvent(opts) {
|
|
206
|
+
const { address, proofTxid, network, nip05 } = opts;
|
|
207
|
+
const normalized = normalizeAddress(address, network);
|
|
208
|
+
if (!normalized) throw new Error(`Not a ${network} P2PKH address: ${address}`);
|
|
209
|
+
if (!HEX64$1.test(proofTxid)) throw new Error("Proof txid must be 32 bytes of hex.");
|
|
210
|
+
const bare = bareAddress(normalized);
|
|
211
|
+
const tags = [
|
|
212
|
+
["d", BINDING_D],
|
|
213
|
+
[
|
|
214
|
+
"payto",
|
|
215
|
+
"bitcoincash",
|
|
216
|
+
bare
|
|
217
|
+
],
|
|
218
|
+
["proof", proofTxid],
|
|
219
|
+
["network", network]
|
|
220
|
+
];
|
|
221
|
+
if (nip05) tags.push(["nip05", nip05.toLowerCase()]);
|
|
222
|
+
return {
|
|
223
|
+
kind: BINDING_KIND,
|
|
224
|
+
created_at: opts.createdAt ?? Math.floor(Date.now() / 1e3),
|
|
225
|
+
tags,
|
|
226
|
+
content: JSON.stringify({
|
|
227
|
+
v: 1,
|
|
228
|
+
network,
|
|
229
|
+
address: bare,
|
|
230
|
+
proof: {
|
|
231
|
+
type: "op_return_spend",
|
|
232
|
+
txid: proofTxid
|
|
233
|
+
}
|
|
234
|
+
})
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
function buildRevokeEvent(createdAt) {
|
|
238
|
+
return {
|
|
239
|
+
kind: BINDING_KIND,
|
|
240
|
+
created_at: createdAt ?? Math.floor(Date.now() / 1e3),
|
|
241
|
+
tags: [["d", BINDING_D]],
|
|
242
|
+
content: JSON.stringify({
|
|
243
|
+
v: 1,
|
|
244
|
+
revoked: true
|
|
245
|
+
})
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
/** NIP-A3 payment target so other Nostr clients can find the address. */
|
|
249
|
+
function buildPaytoEvent(address, createdAt) {
|
|
250
|
+
return {
|
|
251
|
+
kind: PAYTO_KIND,
|
|
252
|
+
created_at: createdAt ?? Math.floor(Date.now() / 1e3),
|
|
253
|
+
tags: [[
|
|
254
|
+
"payto",
|
|
255
|
+
"bitcoincash",
|
|
256
|
+
bareAddress(address)
|
|
257
|
+
]],
|
|
258
|
+
content: ""
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
var tagValue = (event, name, index = 1) => event.tags.find((t) => t[0] === name)?.[index];
|
|
262
|
+
/**
|
|
263
|
+
* Parse a kind-30145 event. Content and tags must agree; the address is
|
|
264
|
+
* returned normalised for the event's own network.
|
|
265
|
+
*/
|
|
266
|
+
function parseBindingEvent(event) {
|
|
267
|
+
if (event.kind !== 30145 || tagValue(event, "d") !== "bch-bind") return {
|
|
268
|
+
type: "invalid",
|
|
269
|
+
reason: "Not a HandlePay binding"
|
|
270
|
+
};
|
|
271
|
+
let content;
|
|
272
|
+
try {
|
|
273
|
+
content = JSON.parse(event.content);
|
|
274
|
+
} catch {
|
|
275
|
+
return {
|
|
276
|
+
type: "invalid",
|
|
277
|
+
reason: "Binding content is not JSON"
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
if (typeof content !== "object" || content === null) return {
|
|
281
|
+
type: "invalid",
|
|
282
|
+
reason: "Binding content is empty"
|
|
283
|
+
};
|
|
284
|
+
const c = content;
|
|
285
|
+
if (c.v !== 1) return {
|
|
286
|
+
type: "invalid",
|
|
287
|
+
reason: "Unsupported binding version"
|
|
288
|
+
};
|
|
289
|
+
if (c.revoked === true) return { type: "revoked" };
|
|
290
|
+
const network = typeof c.network === "string" ? c.network : "";
|
|
291
|
+
if (network !== "mainnet" && network !== "chipnet") return {
|
|
292
|
+
type: "invalid",
|
|
293
|
+
reason: "Unknown network"
|
|
294
|
+
};
|
|
295
|
+
const address = typeof c.address === "string" ? normalizeAddress(c.address, network) : null;
|
|
296
|
+
if (!address) return {
|
|
297
|
+
type: "invalid",
|
|
298
|
+
reason: "Address does not match the network"
|
|
299
|
+
};
|
|
300
|
+
const proof = c.proof;
|
|
301
|
+
const txid = typeof proof?.txid === "string" ? proof.txid.toLowerCase() : "";
|
|
302
|
+
if (proof?.type !== "op_return_spend" || !HEX64$1.test(txid)) return {
|
|
303
|
+
type: "invalid",
|
|
304
|
+
reason: "Missing proof"
|
|
305
|
+
};
|
|
306
|
+
const payto = event.tags.find((t) => t[0] === "payto" && t[1] === "bitcoincash")?.[2];
|
|
307
|
+
if (!payto || bareAddress(payto) !== bareAddress(address)) return {
|
|
308
|
+
type: "invalid",
|
|
309
|
+
reason: "Tags and content name different addresses"
|
|
310
|
+
};
|
|
311
|
+
if ((tagValue(event, "proof") ?? "").toLowerCase() !== txid) return {
|
|
312
|
+
type: "invalid",
|
|
313
|
+
reason: "Tags and content name different proofs"
|
|
314
|
+
};
|
|
315
|
+
if (tagValue(event, "network") !== network) return {
|
|
316
|
+
type: "invalid",
|
|
317
|
+
reason: "Tags and content disagree on network"
|
|
318
|
+
};
|
|
319
|
+
return {
|
|
320
|
+
type: "binding",
|
|
321
|
+
address,
|
|
322
|
+
proofTxid: txid,
|
|
323
|
+
network,
|
|
324
|
+
nip05: tagValue(event, "nip05")
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
/** Address from a NIP-A3 `payto` event (Claimed only). */
|
|
328
|
+
function parsePaytoEvent(event, network) {
|
|
329
|
+
if (event.kind !== 10133) return null;
|
|
330
|
+
for (const t of event.tags) if (t[0] === "payto" && t[1] === "bitcoincash" && t[2]) {
|
|
331
|
+
const a = normalizeAddress(t[2], network);
|
|
332
|
+
if (a) return a;
|
|
333
|
+
}
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Address from Paytaca's kind-30078 `paytaca:bch-address` event (Claimed only).
|
|
338
|
+
* The exact content format is unconfirmed, so this accepts either a bare
|
|
339
|
+
* address string or a JSON object with an `address` field.
|
|
340
|
+
*/
|
|
341
|
+
function parsePaytacaEvent(event, network) {
|
|
342
|
+
if (event.kind !== 30078 || tagValue(event, "d") !== "paytaca:bch-address") return null;
|
|
343
|
+
let candidate = event.content.trim();
|
|
344
|
+
try {
|
|
345
|
+
const parsed = JSON.parse(candidate);
|
|
346
|
+
if (parsed && typeof parsed.address === "string") candidate = parsed.address;
|
|
347
|
+
} catch {}
|
|
348
|
+
return normalizeAddress(candidate, network);
|
|
349
|
+
}
|
|
350
|
+
// ../../src/lib/nostr.ts
|
|
351
|
+
/** Always queried and published to, alongside any relays the NIP-05 file lists. */
|
|
352
|
+
var DEFAULT_RELAYS = [
|
|
353
|
+
"wss://relay.damus.io",
|
|
354
|
+
"wss://nos.lol",
|
|
355
|
+
"wss://relay.primal.net"
|
|
356
|
+
];
|
|
357
|
+
var HEX64 = /^[0-9a-f]{64}$/;
|
|
358
|
+
/** Parse `local@domain`. Returns null if it can't be a NIP-05 name. */
|
|
359
|
+
function parseHandle(input) {
|
|
360
|
+
const trimmed = input.trim().toLowerCase();
|
|
361
|
+
const at = trimmed.lastIndexOf("@");
|
|
362
|
+
if (at <= 0 || at === trimmed.length - 1) return null;
|
|
363
|
+
const local = trimmed.slice(0, at);
|
|
364
|
+
const domain = trimmed.slice(at + 1);
|
|
365
|
+
if (!/^[\p{L}\p{N}._-]+$/u.test(local)) return null;
|
|
366
|
+
if (!/^[\p{L}\p{N}-]+(\.[\p{L}\p{N}-]+)+$/u.test(domain)) return null;
|
|
367
|
+
const nonAscii = /[^\x20-\x7e]/.test(trimmed);
|
|
368
|
+
return {
|
|
369
|
+
local,
|
|
370
|
+
domain,
|
|
371
|
+
full: `${local}@${domain}`,
|
|
372
|
+
nonAscii
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
var Nip05UnreachableError = class extends Error {
|
|
376
|
+
constructor(domain) {
|
|
377
|
+
super(`Couldn't reach ${domain} to look up this name.`);
|
|
378
|
+
this.name = "Nip05UnreachableError";
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
/** Parse a nostr.json body for one name. */
|
|
382
|
+
function readNip05Json(json, local) {
|
|
383
|
+
if (typeof json !== "object" || json === null) return null;
|
|
384
|
+
const j = json;
|
|
385
|
+
const pubkey = j.names?.[local];
|
|
386
|
+
if (typeof pubkey !== "string" || !HEX64.test(pubkey)) return null;
|
|
387
|
+
const listed = j.relays?.[pubkey];
|
|
388
|
+
return {
|
|
389
|
+
pubkey,
|
|
390
|
+
relays: Array.isArray(listed) ? listed.filter((r) => typeof r === "string" && r.startsWith("wss://")) : []
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Look up `local@domain` via `https://domain/.well-known/nostr.json?name=local`.
|
|
395
|
+
* Tries the domain directly; if that fails at the network level (usually CORS),
|
|
396
|
+
* retries through the HandlePay Worker when `proxy` is set.
|
|
397
|
+
*
|
|
398
|
+
* Returns null when the domain answers but doesn't list the name; throws
|
|
399
|
+
* Nip05UnreachableError when it can't be reached at all.
|
|
400
|
+
*/
|
|
401
|
+
async function fetchNip05(handle, opts = {}) {
|
|
402
|
+
const fetchImpl = opts.fetchImpl ?? ((url, init) => fetch(url, init));
|
|
403
|
+
const proxy = opts.proxy ?? void 0;
|
|
404
|
+
const timeoutMs = opts.timeoutMs ?? 5e3;
|
|
405
|
+
const urls = [`https://${handle.domain}/.well-known/nostr.json?name=${encodeURIComponent(handle.local)}`];
|
|
406
|
+
if (proxy) urls.push(`${proxy.replace(/\/$/, "")}/nip05?name=${encodeURIComponent(handle.full)}`);
|
|
407
|
+
for (const url of urls) {
|
|
408
|
+
let response;
|
|
409
|
+
try {
|
|
410
|
+
response = await fetchImpl(url, {
|
|
411
|
+
redirect: "error",
|
|
412
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
413
|
+
});
|
|
414
|
+
} catch {
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (response.status === 404) return null;
|
|
418
|
+
if (!response.ok) continue;
|
|
419
|
+
try {
|
|
420
|
+
return readNip05Json(await response.json(), handle.local);
|
|
421
|
+
} catch {
|
|
422
|
+
return null;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
throw new Nip05UnreachableError(handle.domain);
|
|
426
|
+
}
|
|
427
|
+
var pool = null;
|
|
428
|
+
function getPool() {
|
|
429
|
+
pool ??= new SimplePool();
|
|
430
|
+
return pool;
|
|
431
|
+
}
|
|
432
|
+
function relaysFor(extra = []) {
|
|
433
|
+
return [...new Set([...extra, ...DEFAULT_RELAYS].map((r) => r.replace(/\/$/, "")))];
|
|
434
|
+
}
|
|
435
|
+
/** No relay could be reached, so an empty answer would mean "couldn't check", not "nothing published". */
|
|
436
|
+
var RelaysUnreachableError = class extends Error {
|
|
437
|
+
constructor() {
|
|
438
|
+
super("Couldn't reach any Nostr relay to read this name's records. Check your connection and try again.");
|
|
439
|
+
this.name = "RelaysUnreachableError";
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
/**
|
|
443
|
+
* The relays that accept a connection. querySync answers [] both when relays have nothing and when
|
|
444
|
+
* none can be reached; connecting first tells the two apart, so a dead connection reads as
|
|
445
|
+
* "couldn't check", never as "no identity". Throws RelaysUnreachableError when none connect.
|
|
446
|
+
*/
|
|
447
|
+
async function reachableRelays(p, relays, timeout) {
|
|
448
|
+
const connected = await Promise.allSettled(relays.map((url) => p.ensureRelay(url, { connectionTimeout: timeout })));
|
|
449
|
+
const ok = relays.filter((_, i) => connected[i].status === "fulfilled");
|
|
450
|
+
if (!ok.length) throw new RelaysUnreachableError();
|
|
451
|
+
return ok;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Fetch a pubkey's identity events (binding, payto, Paytaca) from relays.
|
|
455
|
+
* Drops anything with a bad signature or a different author.
|
|
456
|
+
*
|
|
457
|
+
* Throws RelaysUnreachableError when not one relay can be connected to.
|
|
458
|
+
*/
|
|
459
|
+
async function queryIdentityEvents(pubkey, relays, maxWait = 4e3) {
|
|
460
|
+
const p = getPool();
|
|
461
|
+
relays = await reachableRelays(p, relays, maxWait);
|
|
462
|
+
return dedupeVerified((await Promise.all([
|
|
463
|
+
p.querySync(relays, {
|
|
464
|
+
authors: [pubkey],
|
|
465
|
+
kinds: [BINDING_KIND],
|
|
466
|
+
"#d": [BINDING_D]
|
|
467
|
+
}, { maxWait }),
|
|
468
|
+
p.querySync(relays, {
|
|
469
|
+
authors: [pubkey],
|
|
470
|
+
kinds: [PAYTO_KIND]
|
|
471
|
+
}, { maxWait }),
|
|
472
|
+
p.querySync(relays, {
|
|
473
|
+
authors: [pubkey],
|
|
474
|
+
kinds: [PAYTACA_KIND],
|
|
475
|
+
"#d": [PAYTACA_D]
|
|
476
|
+
}, { maxWait })
|
|
477
|
+
])).flat(), pubkey);
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Check an event's id and signature from its fields alone.
|
|
481
|
+
*
|
|
482
|
+
* nostr-tools caches a successful check in a symbol property on the event
|
|
483
|
+
* object, and object spread copies that symbol. So `{...signed, sig: other}`
|
|
484
|
+
* would pass `verifyEvent` without being checked. Verifying a fresh copy of
|
|
485
|
+
* the NIP-01 fields defeats the cache.
|
|
486
|
+
*/
|
|
487
|
+
function verifySignature(e) {
|
|
488
|
+
const { id, pubkey, created_at, kind, tags, content, sig } = e;
|
|
489
|
+
try {
|
|
490
|
+
return verifyEvent({
|
|
491
|
+
id,
|
|
492
|
+
pubkey,
|
|
493
|
+
created_at,
|
|
494
|
+
kind,
|
|
495
|
+
tags,
|
|
496
|
+
content,
|
|
497
|
+
sig
|
|
498
|
+
});
|
|
499
|
+
} catch {
|
|
500
|
+
return false;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
/** Unique events by id, signature-checked, from `author` only. */
|
|
504
|
+
function dedupeVerified(events, author) {
|
|
505
|
+
const seen = /* @__PURE__ */ new Map();
|
|
506
|
+
for (const e of events) {
|
|
507
|
+
if (seen.has(e.id) || e.pubkey !== author) continue;
|
|
508
|
+
if (!verifySignature(e)) continue;
|
|
509
|
+
seen.set(e.id, e);
|
|
510
|
+
}
|
|
511
|
+
return [...seen.values()];
|
|
512
|
+
}
|
|
513
|
+
/** Newest event, ties broken by lowest id (NIP-01 replaceable-event rule). */
|
|
514
|
+
function newest(events) {
|
|
515
|
+
return [...events].sort((a, b) => b.created_at - a.created_at || (a.id < b.id ? -1 : 1))[0];
|
|
516
|
+
}
|
|
517
|
+
// ../../src/lib/resolve.ts
|
|
518
|
+
/**
|
|
519
|
+
* resolveHandle: name → Verified / Claimed / Changed / Not found, with the
|
|
520
|
+
* reasons. All fetching goes through `ResolveDeps`, so the same logic runs
|
|
521
|
+
* against live relays and Fulcrum or against test fixtures.
|
|
522
|
+
*/
|
|
523
|
+
function liveDeps(network) {
|
|
524
|
+
return {
|
|
525
|
+
fetchNip05: (h) => fetchNip05(h),
|
|
526
|
+
queryEvents: (pubkey, relays) => queryIdentityEvents(pubkey, relays),
|
|
527
|
+
getTransaction: (txid) => getTransaction(network, txid)
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
var firstFailure = (checks) => checks.find((c) => !c.ok);
|
|
531
|
+
async function resolveHandle(input, network, deps, pinned) {
|
|
532
|
+
const handle = parseHandle(input) ?? void 0;
|
|
533
|
+
if (!handle) return {
|
|
534
|
+
status: "not_found",
|
|
535
|
+
checks: [],
|
|
536
|
+
reason: "That doesn't look like a name (name@domain)"
|
|
537
|
+
};
|
|
538
|
+
let nip05;
|
|
539
|
+
try {
|
|
540
|
+
nip05 = await deps.fetchNip05(handle);
|
|
541
|
+
} catch (e) {
|
|
542
|
+
return {
|
|
543
|
+
status: "not_found",
|
|
544
|
+
handle,
|
|
545
|
+
checks: [{
|
|
546
|
+
id: "nip05",
|
|
547
|
+
ok: false,
|
|
548
|
+
label: `${handle.domain} lists this name`,
|
|
549
|
+
detail: e.message
|
|
550
|
+
}],
|
|
551
|
+
reason: e.message
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
const nip05Check = {
|
|
555
|
+
id: "nip05",
|
|
556
|
+
ok: !!nip05,
|
|
557
|
+
label: `${handle.domain} lists this name`
|
|
558
|
+
};
|
|
559
|
+
if (!nip05) return {
|
|
560
|
+
status: "not_found",
|
|
561
|
+
handle,
|
|
562
|
+
checks: [{
|
|
563
|
+
...nip05Check,
|
|
564
|
+
detail: "Name not listed"
|
|
565
|
+
}],
|
|
566
|
+
reason: "No HandlePay identity for this name"
|
|
567
|
+
};
|
|
568
|
+
const { pubkey } = nip05;
|
|
569
|
+
const events = dedupeVerified(await deps.queryEvents(pubkey, relaysFor(nip05.relays)), pubkey);
|
|
570
|
+
const binding = newest(events.filter((e) => e.kind === BINDING_KIND));
|
|
571
|
+
const parsed = binding ? parseBindingEvent(binding) : void 0;
|
|
572
|
+
if (parsed?.type === "revoked") return {
|
|
573
|
+
status: "not_found",
|
|
574
|
+
handle,
|
|
575
|
+
pubkey,
|
|
576
|
+
checks: [nip05Check, {
|
|
577
|
+
id: "signature",
|
|
578
|
+
ok: false,
|
|
579
|
+
label: "Signed binding found",
|
|
580
|
+
detail: "Binding revoked"
|
|
581
|
+
}],
|
|
582
|
+
reason: "Binding revoked"
|
|
583
|
+
};
|
|
584
|
+
if (parsed?.type === "binding") {
|
|
585
|
+
const checks = [
|
|
586
|
+
nip05Check,
|
|
587
|
+
{
|
|
588
|
+
id: "signature",
|
|
589
|
+
ok: true,
|
|
590
|
+
label: "Signed by this name's Nostr key"
|
|
591
|
+
},
|
|
592
|
+
...await gatherProofChecks(parsed, pubkey, network, deps)
|
|
593
|
+
];
|
|
594
|
+
const address = normalizeAddress(parsed.address, network) ?? void 0;
|
|
595
|
+
const failed = firstFailure(checks);
|
|
596
|
+
if (failed || !address) return {
|
|
597
|
+
status: "claimed",
|
|
598
|
+
handle,
|
|
599
|
+
pubkey,
|
|
600
|
+
address,
|
|
601
|
+
proofTxid: parsed.proofTxid,
|
|
602
|
+
source: "binding",
|
|
603
|
+
checks,
|
|
604
|
+
reason: failed?.detail ?? "Address is for another network"
|
|
605
|
+
};
|
|
606
|
+
const result = {
|
|
607
|
+
status: "verified",
|
|
608
|
+
handle,
|
|
609
|
+
pubkey,
|
|
610
|
+
address,
|
|
611
|
+
proofTxid: parsed.proofTxid,
|
|
612
|
+
source: "binding",
|
|
613
|
+
checks
|
|
614
|
+
};
|
|
615
|
+
if (pinned && (pinned.pubkey !== pubkey || pinned.address !== address)) return {
|
|
616
|
+
...result,
|
|
617
|
+
status: "changed",
|
|
618
|
+
previous: pinned,
|
|
619
|
+
reason: "This name now points to a different address than last time"
|
|
620
|
+
};
|
|
621
|
+
return result;
|
|
622
|
+
}
|
|
623
|
+
const payto = newest(events.filter((e) => e.kind === PAYTO_KIND));
|
|
624
|
+
const paytoAddress = payto ? parsePaytoEvent(payto, network) : null;
|
|
625
|
+
const paytaca = newest(events.filter((e) => e.kind === PAYTACA_KIND));
|
|
626
|
+
const paytacaAddress = paytaca ? parsePaytacaEvent(paytaca, network) : null;
|
|
627
|
+
const claimed = paytoAddress ?? paytacaAddress;
|
|
628
|
+
const bindingProblem = parsed?.type === "invalid" ? parsed.reason : void 0;
|
|
629
|
+
if (claimed) return {
|
|
630
|
+
status: "claimed",
|
|
631
|
+
handle,
|
|
632
|
+
pubkey,
|
|
633
|
+
address: claimed,
|
|
634
|
+
source: paytoAddress ? "payto" : "paytaca",
|
|
635
|
+
checks: [
|
|
636
|
+
nip05Check,
|
|
637
|
+
{
|
|
638
|
+
id: "signature",
|
|
639
|
+
ok: true,
|
|
640
|
+
label: "Signed by this name's Nostr key"
|
|
641
|
+
},
|
|
642
|
+
{
|
|
643
|
+
id: "spends",
|
|
644
|
+
ok: false,
|
|
645
|
+
label: "Proof was paid from this address",
|
|
646
|
+
detail: "No BCH proof from this address"
|
|
647
|
+
}
|
|
648
|
+
],
|
|
649
|
+
reason: bindingProblem ?? "No BCH proof from this address"
|
|
650
|
+
};
|
|
651
|
+
return {
|
|
652
|
+
status: "not_found",
|
|
653
|
+
handle,
|
|
654
|
+
pubkey,
|
|
655
|
+
checks: [nip05Check, {
|
|
656
|
+
id: "signature",
|
|
657
|
+
ok: false,
|
|
658
|
+
label: "Signed binding found",
|
|
659
|
+
detail: bindingProblem ?? "No binding published"
|
|
660
|
+
}],
|
|
661
|
+
reason: bindingProblem ?? "No HandlePay identity for this name"
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
async function gatherProofChecks(parsed, pubkey, network, deps) {
|
|
665
|
+
const unreachable = () => /* @__PURE__ */ new Error(`Couldn't reach the ${network} BCH server to check the proof. Check your connection and try again.`);
|
|
666
|
+
let proof;
|
|
667
|
+
try {
|
|
668
|
+
proof = await deps.getTransaction(parsed.proofTxid);
|
|
669
|
+
} catch (e) {
|
|
670
|
+
if (!isTxNotFound(e)) throw unreachable();
|
|
671
|
+
return [
|
|
672
|
+
{
|
|
673
|
+
id: "spends",
|
|
674
|
+
ok: false,
|
|
675
|
+
label: "Proof was paid from this address",
|
|
676
|
+
detail: "Proof transaction not found"
|
|
677
|
+
},
|
|
678
|
+
{
|
|
679
|
+
id: "commits",
|
|
680
|
+
ok: false,
|
|
681
|
+
label: "Proof names this Nostr key",
|
|
682
|
+
detail: "Proof transaction not found"
|
|
683
|
+
},
|
|
684
|
+
{
|
|
685
|
+
id: "confirmed",
|
|
686
|
+
ok: false,
|
|
687
|
+
label: "Proof is confirmed on chain",
|
|
688
|
+
detail: "Proof transaction not found"
|
|
689
|
+
},
|
|
690
|
+
{
|
|
691
|
+
id: "network",
|
|
692
|
+
ok: parsed.network === network,
|
|
693
|
+
label: `Binding is for ${network}`,
|
|
694
|
+
detail: parsed.network === network ? void 0 : `Binding is for ${parsed.network}`
|
|
695
|
+
}
|
|
696
|
+
];
|
|
697
|
+
}
|
|
698
|
+
const parents = /* @__PURE__ */ new Map();
|
|
699
|
+
try {
|
|
700
|
+
const tx = decodeTransaction(hexToBin(proof.hex));
|
|
701
|
+
if (typeof tx !== "string") {
|
|
702
|
+
const ids = [...new Set(tx.inputs.map((i) => binToHex(i.outpointTransactionHash)))];
|
|
703
|
+
await Promise.all(ids.map(async (id) => {
|
|
704
|
+
try {
|
|
705
|
+
parents.set(id, (await deps.getTransaction(id)).hex);
|
|
706
|
+
} catch (e) {
|
|
707
|
+
if (!isTxNotFound(e)) throw unreachable();
|
|
708
|
+
}
|
|
709
|
+
}));
|
|
710
|
+
}
|
|
711
|
+
} catch (e) {
|
|
712
|
+
if (e instanceof Error && e.message.startsWith("Couldn't reach")) throw e;
|
|
713
|
+
}
|
|
714
|
+
return checkProof({
|
|
715
|
+
proofHex: proof.hex,
|
|
716
|
+
proofTxid: parsed.proofTxid,
|
|
717
|
+
confirmations: proof.confirmations,
|
|
718
|
+
parents,
|
|
719
|
+
address: parsed.address,
|
|
720
|
+
pubkey,
|
|
721
|
+
eventNetwork: parsed.network,
|
|
722
|
+
network
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
/** Whether the pay button is allowed, and what has to be confirmed first. */
|
|
726
|
+
function paymentGate(r) {
|
|
727
|
+
if (!r.address) return "blocked";
|
|
728
|
+
switch (r.status) {
|
|
729
|
+
case "verified": return "allowed";
|
|
730
|
+
case "claimed": return "confirm_unverified";
|
|
731
|
+
case "changed": return "acknowledge_change";
|
|
732
|
+
default: return "blocked";
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
// ../../src/lib/auth.ts
|
|
736
|
+
/**
|
|
737
|
+
* F4: challenge–response sign-in against a handle's Nostr key. No server:
|
|
738
|
+
* the verifier makes the challenge, the user signs a kind-22242 event with
|
|
739
|
+
* NIP-07, and the verifier checks it. A real site must create and remember
|
|
740
|
+
* the challenge itself; this page does both ends to demonstrate the flow.
|
|
741
|
+
*/
|
|
742
|
+
var AUTH_KIND = 22242;
|
|
743
|
+
var AUTH_MAX_AGE_SEC = 300;
|
|
744
|
+
function createChallenge() {
|
|
745
|
+
return binToHex(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
|
|
746
|
+
}
|
|
747
|
+
function buildAuthTemplate(challenge, origin, createdAt) {
|
|
748
|
+
return {
|
|
749
|
+
kind: AUTH_KIND,
|
|
750
|
+
created_at: createdAt ?? Math.floor(Date.now() / 1e3),
|
|
751
|
+
tags: [["challenge", challenge], ["relay", origin]],
|
|
752
|
+
content: ""
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
function verifyAuthEvent(event, expected) {
|
|
756
|
+
const now = expected.now ?? Math.floor(Date.now() / 1e3);
|
|
757
|
+
const tag = (name) => event.tags.find((t) => t[0] === name)?.[1];
|
|
758
|
+
if (event.kind !== 22242) return {
|
|
759
|
+
ok: false,
|
|
760
|
+
reason: "Not a sign-in event"
|
|
761
|
+
};
|
|
762
|
+
if (!verifySignature(event)) return {
|
|
763
|
+
ok: false,
|
|
764
|
+
reason: "Signature is invalid"
|
|
765
|
+
};
|
|
766
|
+
if (tag("challenge") !== expected.challenge) return {
|
|
767
|
+
ok: false,
|
|
768
|
+
reason: "Signed a different challenge"
|
|
769
|
+
};
|
|
770
|
+
if (tag("relay") !== expected.origin) return {
|
|
771
|
+
ok: false,
|
|
772
|
+
reason: "Signed for a different site"
|
|
773
|
+
};
|
|
774
|
+
if (Math.abs(now - event.created_at) > 300) return {
|
|
775
|
+
ok: false,
|
|
776
|
+
reason: "Sign-in expired; try again"
|
|
777
|
+
};
|
|
778
|
+
if (event.pubkey !== expected.pubkey) return {
|
|
779
|
+
ok: false,
|
|
780
|
+
reason: "Signed with a key this name doesn't use"
|
|
781
|
+
};
|
|
782
|
+
return {
|
|
783
|
+
ok: true,
|
|
784
|
+
pubkey: event.pubkey
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
// src/index.ts
|
|
788
|
+
/**
|
|
789
|
+
* Resolve a name to a verified address.
|
|
790
|
+
*
|
|
791
|
+
* Looks the name up with NIP-05, reads its signed binding from Nostr relays,
|
|
792
|
+
* and checks the BCH proof transaction from raw bytes. Pay `address` only
|
|
793
|
+
* when `status` is "verified" (or after your user has confirmed a "claimed"
|
|
794
|
+
* or "changed" result, as the app does).
|
|
795
|
+
*
|
|
796
|
+
* Rejects, rather than returning "not_found", when it can't check: no Nostr
|
|
797
|
+
* relay could be reached (RelaysUnreachableError) or the BCH server didn't
|
|
798
|
+
* answer. A name you couldn't check isn't a name that doesn't exist.
|
|
799
|
+
*/
|
|
800
|
+
async function resolve(name, options = {}) {
|
|
801
|
+
const network = options.network ?? "mainnet";
|
|
802
|
+
return resolveHandle(name, network, options.deps ?? liveDeps(network), options.pinned);
|
|
803
|
+
}
|
|
804
|
+
export { AUTH_KIND, AUTH_MAX_AGE_SEC, BINDING_D, BINDING_KIND, DEFAULT_RELAYS, PAYTO_KIND, PROOF_MAGIC, PROOF_VERSION, RelaysUnreachableError, buildAuthTemplate, buildBindingEvent, buildPaytoEvent, buildRevokeEvent, checkProof, createChallenge, fetchNip05, liveDeps, normalizeAddress, parseBindingEvent, parseHandle, parseProofOutput, paymentGate, proofOpReturnChunks, queryIdentityEvents, resolve, resolveHandle, verifyAuthEvent };
|
|
805
|
+
|
|
806
|
+
//# sourceMappingURL=index.js.map
|