blossom-client-sdk 5.0.0 → 5.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 +65 -8
- package/lib/actions/delete.d.ts +3 -0
- package/lib/actions/delete.js +17 -38
- package/lib/actions/download.d.ts +3 -0
- package/lib/actions/download.js +17 -35
- package/lib/actions/has.d.ts +1 -1
- package/lib/actions/has.js +6 -2
- package/lib/actions/list.d.ts +3 -0
- package/lib/actions/list.js +18 -31
- package/lib/actions/media.js +28 -45
- package/lib/actions/mirror.d.ts +3 -0
- package/lib/actions/mirror.js +17 -40
- package/lib/actions/multi-server.js +27 -0
- package/lib/actions/resolve.js +5 -0
- package/lib/actions/upload.d.ts +3 -0
- package/lib/actions/upload.js +30 -47
- package/lib/helpers/blob.js +4 -3
- package/lib/helpers/cashu.d.ts +3 -1
- package/lib/helpers/cashu.js +185 -4
- package/lib/helpers/headers.d.ts +1 -0
- package/lib/helpers/headers.js +5 -0
- package/lib/helpers/index.d.ts +1 -1
- package/lib/helpers/index.js +1 -1
- package/lib/helpers/signal.d.ts +1 -0
- package/lib/helpers/signal.js +4 -3
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/internal/bytes.d.ts +2 -0
- package/lib/internal/bytes.js +6 -0
- package/lib/internal/challenges.d.ts +6 -0
- package/lib/internal/challenges.js +15 -0
- package/package.json +21 -21
- package/src/actions/delete.ts +20 -42
- package/src/actions/download.ts +20 -41
- package/src/actions/has.ts +5 -2
- package/src/actions/list.ts +21 -35
- package/src/actions/media.ts +26 -47
- package/src/actions/mirror.ts +20 -44
- package/src/actions/multi-server.ts +25 -0
- package/src/actions/resolve.ts +5 -0
- package/src/actions/upload.ts +31 -48
- package/src/helpers/blob.ts +5 -4
- package/src/helpers/cashu.ts +184 -7
- package/src/helpers/headers.ts +5 -0
- package/src/helpers/index.ts +1 -1
- package/src/helpers/signal.ts +6 -4
- package/src/index.ts +1 -0
- package/src/internal/bytes.ts +6 -0
- package/src/internal/challenges.ts +25 -0
- package/src/types.ts +1 -2
|
@@ -34,10 +34,12 @@ const defaultMediaUploadOptions = {
|
|
|
34
34
|
*/
|
|
35
35
|
export async function multiServerUpload(servers, blob, opts) {
|
|
36
36
|
const options = { ...defaultMultiServerOptions, ...opts };
|
|
37
|
+
options.signal?.throwIfAborted();
|
|
37
38
|
let initialUpload;
|
|
38
39
|
const results = new Map();
|
|
39
40
|
const authEvents = options.authEvents ?? new Set();
|
|
40
41
|
const blobSha256 = await getBlobSha256(blob);
|
|
42
|
+
options.signal?.throwIfAborted();
|
|
41
43
|
if (typeof options.auth === "object")
|
|
42
44
|
authEvents.add(options.auth);
|
|
43
45
|
const handleAuthRequest = async (server, sha256, type) => {
|
|
@@ -56,6 +58,11 @@ export async function multiServerUpload(servers, blob, opts) {
|
|
|
56
58
|
throw new Error("Missing payment handler");
|
|
57
59
|
return options.onPayment(server, sha256, blob, request);
|
|
58
60
|
};
|
|
61
|
+
const handlePaymentRequired = (server, sha256, _blob, headers) => {
|
|
62
|
+
if (!options.onPaymentRequired)
|
|
63
|
+
throw new Error("Missing payment handler");
|
|
64
|
+
return options.onPaymentRequired(server, sha256, blob, headers);
|
|
65
|
+
};
|
|
59
66
|
const handleRejection = async (server, sha256, error) => {
|
|
60
67
|
if (!HTTPError.isRejection(error))
|
|
61
68
|
return false;
|
|
@@ -76,6 +83,7 @@ export async function multiServerUpload(servers, blob, opts) {
|
|
|
76
83
|
});
|
|
77
84
|
return { server, exists };
|
|
78
85
|
}));
|
|
86
|
+
options.signal?.throwIfAborted();
|
|
79
87
|
for (const result of preflightResults) {
|
|
80
88
|
if (result.status === "fulfilled" && result.value.exists) {
|
|
81
89
|
serversWithBlob.add(result.value.server);
|
|
@@ -84,6 +92,7 @@ export async function multiServerUpload(servers, blob, opts) {
|
|
|
84
92
|
}
|
|
85
93
|
// upload to each server
|
|
86
94
|
for (const server of uploadServers) {
|
|
95
|
+
options.signal?.throwIfAborted();
|
|
87
96
|
const serverHasBlob = serversWithBlob.has(server);
|
|
88
97
|
try {
|
|
89
98
|
let metadata = undefined;
|
|
@@ -102,10 +111,12 @@ export async function multiServerUpload(servers, blob, opts) {
|
|
|
102
111
|
auth: typeof options.auth === "boolean" ? options.auth : undefined,
|
|
103
112
|
onAuth: (server, sha256) => handleAuthRequest(server, sha256, "upload"),
|
|
104
113
|
onPayment: handlePaymentRequest,
|
|
114
|
+
onPaymentRequired: options.onPaymentRequired ? handlePaymentRequired : undefined,
|
|
105
115
|
timeout: options.mirrorTimeout,
|
|
106
116
|
});
|
|
107
117
|
}
|
|
108
118
|
catch (error) {
|
|
119
|
+
options.signal?.throwIfAborted();
|
|
109
120
|
// mirror failed, if server already has blob skip upload fallback
|
|
110
121
|
if (serverHasBlob)
|
|
111
122
|
continue;
|
|
@@ -119,6 +130,7 @@ export async function multiServerUpload(servers, blob, opts) {
|
|
|
119
130
|
auth: typeof options.auth === "boolean" ? options.auth : undefined,
|
|
120
131
|
onAuth: handleAuthRequest,
|
|
121
132
|
onPayment: handlePaymentRequest,
|
|
133
|
+
onPaymentRequired: options.onPaymentRequired ? handlePaymentRequired : undefined,
|
|
122
134
|
timeout: options.mirrorTimeout,
|
|
123
135
|
});
|
|
124
136
|
if (!initialUpload)
|
|
@@ -128,6 +140,7 @@ export async function multiServerUpload(servers, blob, opts) {
|
|
|
128
140
|
options.onUpload?.(server, metadata.sha256, blob);
|
|
129
141
|
}
|
|
130
142
|
catch (error) {
|
|
143
|
+
options.signal?.throwIfAborted();
|
|
131
144
|
const rejection = await handleRejection(server, blobSha256, error);
|
|
132
145
|
if (rejection === "cancel")
|
|
133
146
|
return results;
|
|
@@ -157,10 +170,12 @@ export async function multiServerUpload(servers, blob, opts) {
|
|
|
157
170
|
*/
|
|
158
171
|
export async function multiServerMediaUpload(servers, blob, opts) {
|
|
159
172
|
const options = { ...defaultMediaUploadOptions, ...opts };
|
|
173
|
+
options.signal?.throwIfAborted();
|
|
160
174
|
let initialUpload;
|
|
161
175
|
const results = new Map();
|
|
162
176
|
const authEvents = options.authEvents ?? new Set();
|
|
163
177
|
const blobSha256 = await getBlobSha256(blob);
|
|
178
|
+
options.signal?.throwIfAborted();
|
|
164
179
|
if (typeof options.auth === "object")
|
|
165
180
|
authEvents.add(options.auth);
|
|
166
181
|
const handleAuthRequest = async (server, sha256, type) => {
|
|
@@ -179,6 +194,11 @@ export async function multiServerMediaUpload(servers, blob, opts) {
|
|
|
179
194
|
throw new Error("Missing payment handler");
|
|
180
195
|
return options.onPayment(server, sha256, blob, request);
|
|
181
196
|
};
|
|
197
|
+
const handlePaymentRequired = (server, sha256, _blob, headers) => {
|
|
198
|
+
if (!options.onPaymentRequired)
|
|
199
|
+
throw new Error("Missing payment handler");
|
|
200
|
+
return options.onPaymentRequired(server, sha256, blob, headers);
|
|
201
|
+
};
|
|
182
202
|
const handleRejection = async (server, sha256, error) => {
|
|
183
203
|
if (!HTTPError.isRejection(error))
|
|
184
204
|
return false;
|
|
@@ -193,6 +213,7 @@ export async function multiServerMediaUpload(servers, blob, opts) {
|
|
|
193
213
|
let mediaUploadServer;
|
|
194
214
|
// phase 1: upload to /media on one server for optimization
|
|
195
215
|
for (const server of mediaServers) {
|
|
216
|
+
options.signal?.throwIfAborted();
|
|
196
217
|
try {
|
|
197
218
|
options.onStart?.(server, blobSha256, blob);
|
|
198
219
|
initialUpload = await uploadMedia(server, blob, {
|
|
@@ -200,12 +221,14 @@ export async function multiServerMediaUpload(servers, blob, opts) {
|
|
|
200
221
|
auth: typeof options.auth === "boolean" ? options.auth : undefined,
|
|
201
222
|
onAuth: handleAuthRequest,
|
|
202
223
|
onPayment: handlePaymentRequest,
|
|
224
|
+
onPaymentRequired: options.onPaymentRequired ? handlePaymentRequired : undefined,
|
|
203
225
|
});
|
|
204
226
|
results.set(server, initialUpload);
|
|
205
227
|
mediaUploadServer = server;
|
|
206
228
|
options.onUpload?.(server, initialUpload.sha256, blob);
|
|
207
229
|
}
|
|
208
230
|
catch (error) {
|
|
231
|
+
options.signal?.throwIfAborted();
|
|
209
232
|
if (error instanceof MediaEndpointMissingError) {
|
|
210
233
|
// ignore, try next server
|
|
211
234
|
}
|
|
@@ -241,6 +264,7 @@ export async function multiServerMediaUpload(servers, blob, opts) {
|
|
|
241
264
|
});
|
|
242
265
|
return { server, exists };
|
|
243
266
|
}));
|
|
267
|
+
options.signal?.throwIfAborted();
|
|
244
268
|
for (const result of preflightResults) {
|
|
245
269
|
if (result.status === "fulfilled" && result.value.exists) {
|
|
246
270
|
serversWithBlob.add(result.value.server);
|
|
@@ -249,6 +273,7 @@ export async function multiServerMediaUpload(servers, blob, opts) {
|
|
|
249
273
|
}
|
|
250
274
|
// mirror to remaining servers
|
|
251
275
|
for (const server of remainingServers) {
|
|
276
|
+
options.signal?.throwIfAborted();
|
|
252
277
|
try {
|
|
253
278
|
options.onStart?.(server, initialUpload.sha256, blob);
|
|
254
279
|
const metadata = await mirrorBlob(server, initialUpload, {
|
|
@@ -256,12 +281,14 @@ export async function multiServerMediaUpload(servers, blob, opts) {
|
|
|
256
281
|
auth: typeof options.auth === "boolean" ? options.auth : undefined,
|
|
257
282
|
onAuth: (server, sha256) => handleAuthRequest(server, sha256, "upload"),
|
|
258
283
|
onPayment: handlePaymentRequest,
|
|
284
|
+
onPaymentRequired: options.onPaymentRequired ? handlePaymentRequired : undefined,
|
|
259
285
|
timeout: options.mirrorTimeout,
|
|
260
286
|
});
|
|
261
287
|
results.set(server, metadata);
|
|
262
288
|
options.onUpload?.(server, metadata.sha256, blob);
|
|
263
289
|
}
|
|
264
290
|
catch (error) {
|
|
291
|
+
options.signal?.throwIfAborted();
|
|
265
292
|
const rejection = await handleRejection(server, initialUpload.sha256, error);
|
|
266
293
|
if (rejection === "cancel")
|
|
267
294
|
return results;
|
package/lib/actions/resolve.js
CHANGED
|
@@ -66,11 +66,13 @@ export async function getBlobUrls(uri, opts) {
|
|
|
66
66
|
}
|
|
67
67
|
/** Resolves a blossom URI to a downloaded blob by trying servers from hints sequentially */
|
|
68
68
|
export async function resolveBlob(uri, opts) {
|
|
69
|
+
opts?.signal?.throwIfAborted();
|
|
69
70
|
const parsed = parseInput(uri);
|
|
70
71
|
const collector = createServerCollector(buildBlobPath(parsed.sha256, parsed.ext));
|
|
71
72
|
/** Try GET on each URL, return the first successful response */
|
|
72
73
|
const tryUrls = async (urls) => {
|
|
73
74
|
for (const url of urls) {
|
|
75
|
+
opts?.signal?.throwIfAborted();
|
|
74
76
|
try {
|
|
75
77
|
const res = await fetchWithTimeout(new URL(url), {
|
|
76
78
|
signal: opts?.signal,
|
|
@@ -80,6 +82,7 @@ export async function resolveBlob(uri, opts) {
|
|
|
80
82
|
return res;
|
|
81
83
|
}
|
|
82
84
|
catch {
|
|
85
|
+
opts?.signal?.throwIfAborted();
|
|
83
86
|
// server unreachable or error — try next
|
|
84
87
|
continue;
|
|
85
88
|
}
|
|
@@ -96,7 +99,9 @@ export async function resolveBlob(uri, opts) {
|
|
|
96
99
|
// 2. resolve and try author hints (deferred — requires relay queries)
|
|
97
100
|
if (opts?.getServers) {
|
|
98
101
|
for (const pubkey of parsed.authors) {
|
|
102
|
+
opts?.signal?.throwIfAborted();
|
|
99
103
|
const authorServers = await opts.getServers(pubkey);
|
|
104
|
+
opts?.signal?.throwIfAborted();
|
|
100
105
|
if (authorServers) {
|
|
101
106
|
const urls = collector.add(authorServers);
|
|
102
107
|
if (urls.length > 0) {
|
package/lib/actions/upload.d.ts
CHANGED
|
@@ -9,6 +9,8 @@ export type UploadOptions<S extends ServerType, B extends UploadType> = {
|
|
|
9
9
|
authEvents?: Set<SignedEvent>;
|
|
10
10
|
/** Request timeout */
|
|
11
11
|
timeout?: number;
|
|
12
|
+
/** Return headers to retry a request rejected with HTTP 402. */
|
|
13
|
+
onPaymentRequired?: (server: S, sha256: string, blob: B, headers: Headers) => Promise<HeadersInit>;
|
|
12
14
|
/**
|
|
13
15
|
* A method used to request payment when uploading or mirroring a blob
|
|
14
16
|
* @param server the server requiring payment
|
|
@@ -16,6 +18,7 @@ export type UploadOptions<S extends ServerType, B extends UploadType> = {
|
|
|
16
18
|
* @param blob the original blob
|
|
17
19
|
* @param request the payment request
|
|
18
20
|
*/
|
|
21
|
+
/** @deprecated Use onPaymentRequired to handle payment schemes generically. */
|
|
19
22
|
onPayment?: (server: S, sha256: string, blob: B, request: PaymentRequest) => Promise<PaymentToken>;
|
|
20
23
|
/**
|
|
21
24
|
* A method used to request a signed auth event for a server and sha256
|
package/lib/actions/upload.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
|
|
2
2
|
import HTTPError from "../error.js";
|
|
3
3
|
import { fetchWithTimeout, getBlobSha256, getBlobSize, getBlobType } from "../helpers/index.js";
|
|
4
|
+
import { handleChallenges } from "../internal/challenges.js";
|
|
5
|
+
import { toWebBytes } from "../internal/bytes.js";
|
|
4
6
|
/** Upload a blob to a server, handles payment and auth */
|
|
5
7
|
export async function uploadBlob(server, blob, opts) {
|
|
6
8
|
const url = new URL("/upload", server);
|
|
7
9
|
const sha256 = await getBlobSha256(blob);
|
|
10
|
+
const body = blob instanceof Blob ? blob : toWebBytes(blob);
|
|
8
11
|
const resolveAuth = async (preset = false) => {
|
|
9
12
|
const reused = opts?.authEvents
|
|
10
13
|
? await getReusableAuthEvent(opts.authEvents, { server, type: "upload", blob: sha256 })
|
|
@@ -46,63 +49,43 @@ export async function uploadBlob(server, blob, opts) {
|
|
|
46
49
|
timeout: opts?.timeout,
|
|
47
50
|
});
|
|
48
51
|
let upload = undefined;
|
|
52
|
+
if (![401, 402, 404].includes(firstTry.status))
|
|
53
|
+
await HTTPError.handleErrorResponse(firstTry);
|
|
49
54
|
if (firstTry.status === 404) {
|
|
50
55
|
// BUD-06 HEAD endpoint is not supported. attempt to upload
|
|
51
56
|
upload = firstTry = await fetchWithTimeout(url, {
|
|
52
|
-
body
|
|
57
|
+
body,
|
|
53
58
|
method: "PUT",
|
|
59
|
+
headers,
|
|
54
60
|
signal: opts?.signal,
|
|
55
61
|
timeout: opts?.timeout,
|
|
56
62
|
});
|
|
57
63
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
64
|
+
const request = (headers) => fetchWithTimeout(url, {
|
|
65
|
+
method: "PUT",
|
|
66
|
+
body,
|
|
67
|
+
headers,
|
|
68
|
+
signal: opts?.signal,
|
|
69
|
+
timeout: opts?.timeout,
|
|
70
|
+
});
|
|
71
|
+
upload = await handleChallenges(upload ?? (firstTry.ok ? await request(headers) : firstTry), headers, request, {
|
|
72
|
+
signal: opts?.signal,
|
|
73
|
+
auth: async () => {
|
|
62
74
|
if (opts?.auth === false)
|
|
63
75
|
throw new Error("Authorization disabled");
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
if (!opts?.onPayment)
|
|
78
|
-
throw new Error("Missing payment handler");
|
|
79
|
-
const { getEncodedToken } = await import("@cashu/cashu-ts");
|
|
80
|
-
const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
|
|
81
|
-
const request = await getPaymentRequestFromHeaders(firstTry.headers);
|
|
82
|
-
const token = await opts.onPayment(server, sha256, blob, request);
|
|
83
|
-
const payment = getEncodedToken(token);
|
|
84
|
-
// Try upload with payment
|
|
85
|
-
upload = await fetchWithTimeout(url, {
|
|
86
|
-
method: "PUT",
|
|
87
|
-
body: blob,
|
|
88
|
-
headers: { ...headers, "X-Cashu": payment },
|
|
89
|
-
signal: opts?.signal,
|
|
90
|
-
timeout: opts?.timeout,
|
|
91
|
-
});
|
|
92
|
-
break;
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
if (firstTry.status >= 500)
|
|
96
|
-
throw new Error("Server error");
|
|
97
|
-
// check passed, upload
|
|
98
|
-
if (!upload)
|
|
99
|
-
upload = await fetchWithTimeout(url, {
|
|
100
|
-
method: "PUT",
|
|
101
|
-
body: blob,
|
|
102
|
-
headers: { ...headers },
|
|
103
|
-
signal: opts?.signal,
|
|
104
|
-
timeout: opts?.timeout,
|
|
105
|
-
});
|
|
76
|
+
return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
|
|
77
|
+
},
|
|
78
|
+
payment: async (headers) => {
|
|
79
|
+
if (opts?.onPaymentRequired)
|
|
80
|
+
return opts.onPaymentRequired(server, sha256, blob, headers);
|
|
81
|
+
if (opts?.onPayment) {
|
|
82
|
+
const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
|
|
83
|
+
const request = await getPaymentRequestFromHeaders(headers);
|
|
84
|
+
return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, sha256, blob, request)) };
|
|
85
|
+
}
|
|
86
|
+
throw new Error("Missing payment handler");
|
|
87
|
+
},
|
|
88
|
+
});
|
|
106
89
|
// handle errors
|
|
107
90
|
await HTTPError.handleErrorResponse(upload);
|
|
108
91
|
// return blob descriptor
|
package/lib/helpers/blob.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { bytesToHex } from "@noble/hashes/utils";
|
|
1
|
+
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
2
|
+
import { toWebBytes } from "../internal/bytes.js";
|
|
2
3
|
/** Checks if a string is a 64 length hex string */
|
|
3
4
|
export function isSha256(str) {
|
|
4
5
|
return str.match(/^[0-9a-f]{64}$/);
|
|
@@ -23,7 +24,7 @@ export async function computeBlobSha256(blob) {
|
|
|
23
24
|
}
|
|
24
25
|
else {
|
|
25
26
|
// nodejs Buffer
|
|
26
|
-
buffer = blob;
|
|
27
|
+
buffer = toWebBytes(blob);
|
|
27
28
|
}
|
|
28
29
|
let hash;
|
|
29
30
|
if (typeof crypto !== "undefined" && crypto.subtle) {
|
|
@@ -31,7 +32,7 @@ export async function computeBlobSha256(blob) {
|
|
|
31
32
|
hash = new Uint8Array(hashBuffer);
|
|
32
33
|
}
|
|
33
34
|
else {
|
|
34
|
-
const { sha256 } = await import("@noble/hashes/sha2");
|
|
35
|
+
const { sha256 } = await import("@noble/hashes/sha2.js");
|
|
35
36
|
hash = sha256.create().update(new Uint8Array(buffer)).digest();
|
|
36
37
|
}
|
|
37
38
|
return bytesToHex(hash);
|
package/lib/helpers/cashu.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { PaymentRequest } from "../types.js";
|
|
2
|
-
/** Extracts a
|
|
2
|
+
/** Extracts a Cashu PaymentRequest-compatible object from Headers. */
|
|
3
3
|
export declare function getPaymentRequestFromHeaders(headers: Headers): Promise<PaymentRequest>;
|
|
4
4
|
export declare function getPaymentRequestFromHeaders(headers: Headers, quite: false): Promise<PaymentRequest>;
|
|
5
5
|
export declare function getPaymentRequestFromHeaders(headers: Headers, quite: true): Promise<PaymentRequest | undefined>;
|
|
6
|
+
/** Encodes the legacy Cashu token shape used by the deprecated onPayment callback. */
|
|
7
|
+
export declare function encodePaymentToken(token: unknown): string;
|
package/lib/helpers/cashu.js
CHANGED
|
@@ -1,3 +1,142 @@
|
|
|
1
|
+
const decodeBase64 = (value) => {
|
|
2
|
+
const base64 = value
|
|
3
|
+
.replace(/-/g, "+")
|
|
4
|
+
.replace(/_/g, "/")
|
|
5
|
+
.padEnd(Math.ceil(value.length / 4) * 4, "=");
|
|
6
|
+
return Uint8Array.from(atob(base64), (character) => character.charCodeAt(0));
|
|
7
|
+
};
|
|
8
|
+
const encodedRequests = new WeakMap();
|
|
9
|
+
class PaymentRequestCompatibility {
|
|
10
|
+
transport;
|
|
11
|
+
id;
|
|
12
|
+
amount;
|
|
13
|
+
unit;
|
|
14
|
+
mints;
|
|
15
|
+
description;
|
|
16
|
+
singleUse;
|
|
17
|
+
constructor(transport, id, amount, unit, mints, description, singleUse = false) {
|
|
18
|
+
this.transport = transport;
|
|
19
|
+
this.id = id;
|
|
20
|
+
this.amount = amount;
|
|
21
|
+
this.unit = unit;
|
|
22
|
+
this.mints = mints;
|
|
23
|
+
this.description = description;
|
|
24
|
+
this.singleUse = singleUse;
|
|
25
|
+
}
|
|
26
|
+
toRawRequest() {
|
|
27
|
+
return {
|
|
28
|
+
t: this.transport.map((item) => ({ t: item.type, a: item.target, g: item.tags })),
|
|
29
|
+
...(this.id ? { i: this.id } : {}),
|
|
30
|
+
...(this.amount ? { a: this.amount } : {}),
|
|
31
|
+
...(this.unit ? { u: this.unit } : {}),
|
|
32
|
+
...(this.mints ? { m: this.mints } : {}),
|
|
33
|
+
...(this.description ? { d: this.description } : {}),
|
|
34
|
+
...(this.singleUse ? { s: true } : {}),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
toEncodedRequest() {
|
|
38
|
+
return encodedRequests.get(this);
|
|
39
|
+
}
|
|
40
|
+
getTransport(type) {
|
|
41
|
+
return this.transport.find((item) => item.type === type);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function decodeCbor(data) {
|
|
45
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
46
|
+
const decodeLength = (offset, info) => {
|
|
47
|
+
if (info < 24)
|
|
48
|
+
return [info, offset];
|
|
49
|
+
if (info === 24)
|
|
50
|
+
return [view.getUint8(offset), offset + 1];
|
|
51
|
+
if (info === 25)
|
|
52
|
+
return [view.getUint16(offset), offset + 2];
|
|
53
|
+
if (info === 26)
|
|
54
|
+
return [view.getUint32(offset), offset + 4];
|
|
55
|
+
throw new Error("Unsupported CBOR length");
|
|
56
|
+
};
|
|
57
|
+
const decode = (offset) => {
|
|
58
|
+
const byte = view.getUint8(offset++);
|
|
59
|
+
const type = byte >> 5;
|
|
60
|
+
const info = byte & 0x1f;
|
|
61
|
+
const [length, next] = decodeLength(offset, info);
|
|
62
|
+
if (type === 0)
|
|
63
|
+
return [length, next];
|
|
64
|
+
if (type === 2)
|
|
65
|
+
return [data.slice(next, next + length), next + length];
|
|
66
|
+
if (type === 3)
|
|
67
|
+
return [new TextDecoder().decode(data.slice(next, next + length)), next + length];
|
|
68
|
+
if (type === 4) {
|
|
69
|
+
const values = [];
|
|
70
|
+
let cursor = next;
|
|
71
|
+
for (let index = 0; index < length; index++) {
|
|
72
|
+
const [value, end] = decode(cursor);
|
|
73
|
+
values.push(value);
|
|
74
|
+
cursor = end;
|
|
75
|
+
}
|
|
76
|
+
return [values, cursor];
|
|
77
|
+
}
|
|
78
|
+
if (type === 5) {
|
|
79
|
+
const value = {};
|
|
80
|
+
let cursor = next;
|
|
81
|
+
for (let index = 0; index < length; index++) {
|
|
82
|
+
const [key, keyEnd] = decode(cursor);
|
|
83
|
+
const [item, itemEnd] = decode(keyEnd);
|
|
84
|
+
value[String(key)] = item;
|
|
85
|
+
cursor = itemEnd;
|
|
86
|
+
}
|
|
87
|
+
return [value, cursor];
|
|
88
|
+
}
|
|
89
|
+
if (type === 7 && info >= 20 && info <= 23)
|
|
90
|
+
return [[false, true, null, undefined][info - 20], offset];
|
|
91
|
+
throw new Error("Unsupported CBOR value");
|
|
92
|
+
};
|
|
93
|
+
return decode(0)[0];
|
|
94
|
+
}
|
|
95
|
+
function encodeCbor(value) {
|
|
96
|
+
const output = [];
|
|
97
|
+
const length = (major, value) => {
|
|
98
|
+
if (value < 24)
|
|
99
|
+
output.push((major << 5) | value);
|
|
100
|
+
else if (value < 256)
|
|
101
|
+
output.push((major << 5) | 24, value);
|
|
102
|
+
else if (value < 65536)
|
|
103
|
+
output.push((major << 5) | 25, value >> 8, value & 0xff);
|
|
104
|
+
else
|
|
105
|
+
output.push((major << 5) | 26, value >> 24, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff);
|
|
106
|
+
};
|
|
107
|
+
const encode = (item) => {
|
|
108
|
+
if (typeof item === "number")
|
|
109
|
+
length(0, item);
|
|
110
|
+
else if (typeof item === "string") {
|
|
111
|
+
const bytes = new TextEncoder().encode(item);
|
|
112
|
+
length(3, bytes.length);
|
|
113
|
+
output.push(...bytes);
|
|
114
|
+
}
|
|
115
|
+
else if (item instanceof Uint8Array) {
|
|
116
|
+
length(2, item.length);
|
|
117
|
+
output.push(...item);
|
|
118
|
+
}
|
|
119
|
+
else if (Array.isArray(item)) {
|
|
120
|
+
length(4, item.length);
|
|
121
|
+
item.forEach(encode);
|
|
122
|
+
}
|
|
123
|
+
else if (item && typeof item === "object") {
|
|
124
|
+
const entries = Object.entries(item);
|
|
125
|
+
length(5, entries.length);
|
|
126
|
+
entries.forEach(([key, entry]) => {
|
|
127
|
+
encode(key);
|
|
128
|
+
encode(entry);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
else if (typeof item === "boolean")
|
|
132
|
+
output.push(item ? 0xf5 : 0xf4);
|
|
133
|
+
else
|
|
134
|
+
throw new Error("Unsupported CBOR value");
|
|
135
|
+
};
|
|
136
|
+
encode(value);
|
|
137
|
+
return Uint8Array.from(output);
|
|
138
|
+
}
|
|
139
|
+
const hexToBytes = (hex) => Uint8Array.from(hex.match(/.{1,2}/g) ?? [], (value) => Number.parseInt(value, 16));
|
|
1
140
|
export async function getPaymentRequestFromHeaders(headers, quite = false) {
|
|
2
141
|
const header = headers.get("X-Cashu");
|
|
3
142
|
if (!header) {
|
|
@@ -6,9 +145,51 @@ export async function getPaymentRequestFromHeaders(headers, quite = false) {
|
|
|
6
145
|
else
|
|
7
146
|
return undefined;
|
|
8
147
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
request
|
|
148
|
+
if (!header.startsWith("creqA"))
|
|
149
|
+
throw new Error("Unsupported cashu payment request");
|
|
150
|
+
const raw = decodeCbor(decodeBase64(header.slice(5)));
|
|
151
|
+
const request = new PaymentRequestCompatibility([], raw.i, raw.a, raw.u, raw.m, raw.d, raw.s);
|
|
152
|
+
encodedRequests.set(request, header);
|
|
13
153
|
return request;
|
|
14
154
|
}
|
|
155
|
+
/** Encodes the legacy Cashu token shape used by the deprecated onPayment callback. */
|
|
156
|
+
export function encodePaymentToken(token) {
|
|
157
|
+
const value = token;
|
|
158
|
+
const nonHex = value.proofs.some((proof) => !/^[0-9a-fA-F]+$/.test(proof.id));
|
|
159
|
+
if (nonHex) {
|
|
160
|
+
const json = JSON.stringify({
|
|
161
|
+
token: [{ mint: value.mint, proofs: value.proofs }],
|
|
162
|
+
unit: value.unit,
|
|
163
|
+
memo: value.memo,
|
|
164
|
+
});
|
|
165
|
+
const bytes = new TextEncoder().encode(json);
|
|
166
|
+
let binary = "";
|
|
167
|
+
for (const byte of bytes)
|
|
168
|
+
binary += String.fromCharCode(byte);
|
|
169
|
+
return "cashuA" + btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
170
|
+
}
|
|
171
|
+
const groups = new Map();
|
|
172
|
+
for (const proof of value.proofs)
|
|
173
|
+
groups.set(proof.id, [...(groups.get(proof.id) ?? []), proof]);
|
|
174
|
+
const template = {
|
|
175
|
+
m: value.mint,
|
|
176
|
+
u: value.unit || "sat",
|
|
177
|
+
t: [...groups].map(([id, proofs]) => ({
|
|
178
|
+
i: hexToBytes(id),
|
|
179
|
+
p: proofs.map((proof) => ({
|
|
180
|
+
a: proof.amount,
|
|
181
|
+
s: proof.secret,
|
|
182
|
+
c: hexToBytes(proof.C),
|
|
183
|
+
...(proof.dleq
|
|
184
|
+
? { d: { e: hexToBytes(proof.dleq.e), s: hexToBytes(proof.dleq.s), r: hexToBytes(proof.dleq.r ?? "00") } }
|
|
185
|
+
: {}),
|
|
186
|
+
})),
|
|
187
|
+
})),
|
|
188
|
+
...(value.memo ? { d: value.memo } : {}),
|
|
189
|
+
};
|
|
190
|
+
const bytes = encodeCbor(template);
|
|
191
|
+
let binary = "";
|
|
192
|
+
for (const byte of bytes)
|
|
193
|
+
binary += String.fromCharCode(byte);
|
|
194
|
+
return "cashuB" + btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
195
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function mergeHeaders(base: HeadersInit, extra: HeadersInit): Headers;
|
package/lib/helpers/index.d.ts
CHANGED
package/lib/helpers/index.js
CHANGED
package/lib/helpers/signal.d.ts
CHANGED
package/lib/helpers/signal.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
export class TimeoutError extends Error {
|
|
2
|
+
name = "TimeoutError";
|
|
2
3
|
}
|
|
3
4
|
/** Creates and optionally wraps an AbortSignal with a timeout */
|
|
4
5
|
export function wrapSignalWithTimeout(timeout, message, signal) {
|
|
5
6
|
const controller = new AbortController();
|
|
6
|
-
if (signal)
|
|
7
|
-
signal.addEventListener("abort", (err) => controller.abort(err), { once: true });
|
|
8
7
|
const t = setTimeout(() => {
|
|
9
8
|
controller.abort(new TimeoutError(message));
|
|
10
9
|
}, timeout);
|
|
11
10
|
const cancel = () => clearTimeout(t);
|
|
12
|
-
|
|
11
|
+
// Native composition preserves existing abort reasons and avoids retaining listeners
|
|
12
|
+
// on a caller's long-lived signal. It also keeps cancellation working after headers arrive.
|
|
13
|
+
return { cancel, signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal };
|
|
13
14
|
}
|
package/lib/index.d.ts
CHANGED
package/lib/index.js
CHANGED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Handle each challenge at most once, including challenges from a preflight response. */
|
|
2
|
+
export declare function handleChallenges(response: Response, headers: HeadersInit, request: (headers: HeadersInit) => Promise<Response>, handlers: {
|
|
3
|
+
auth: () => Promise<HeadersInit>;
|
|
4
|
+
payment: (headers: Headers) => Promise<HeadersInit>;
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
}): Promise<Response>;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { mergeHeaders } from "../helpers/headers.js";
|
|
2
|
+
/** Handle each challenge at most once, including challenges from a preflight response. */
|
|
3
|
+
export async function handleChallenges(response, headers, request, handlers) {
|
|
4
|
+
const handled = new Set();
|
|
5
|
+
while ((response.status === 401 || response.status === 402) && !handled.has(response.status)) {
|
|
6
|
+
handlers.signal?.throwIfAborted();
|
|
7
|
+
handled.add(response.status);
|
|
8
|
+
const nextHeaders = response.status === 401 ? await handlers.auth() : await handlers.payment(response.headers);
|
|
9
|
+
handlers.signal?.throwIfAborted();
|
|
10
|
+
headers = mergeHeaders(headers, nextHeaders);
|
|
11
|
+
await response.body?.cancel();
|
|
12
|
+
response = await request(headers);
|
|
13
|
+
}
|
|
14
|
+
return response;
|
|
15
|
+
}
|