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