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.
Files changed (50) hide show
  1. package/README.md +65 -8
  2. package/lib/actions/delete.d.ts +3 -0
  3. package/lib/actions/delete.js +17 -38
  4. package/lib/actions/download.d.ts +3 -0
  5. package/lib/actions/download.js +17 -35
  6. package/lib/actions/has.d.ts +1 -1
  7. package/lib/actions/has.js +6 -2
  8. package/lib/actions/list.d.ts +3 -0
  9. package/lib/actions/list.js +18 -31
  10. package/lib/actions/media.js +28 -45
  11. package/lib/actions/mirror.d.ts +3 -0
  12. package/lib/actions/mirror.js +17 -40
  13. package/lib/actions/multi-server.js +27 -0
  14. package/lib/actions/resolve.js +5 -0
  15. package/lib/actions/upload.d.ts +3 -0
  16. package/lib/actions/upload.js +30 -47
  17. package/lib/helpers/blob.js +4 -3
  18. package/lib/helpers/cashu.d.ts +3 -1
  19. package/lib/helpers/cashu.js +185 -4
  20. package/lib/helpers/headers.d.ts +1 -0
  21. package/lib/helpers/headers.js +5 -0
  22. package/lib/helpers/index.d.ts +1 -1
  23. package/lib/helpers/index.js +1 -1
  24. package/lib/helpers/signal.d.ts +1 -0
  25. package/lib/helpers/signal.js +4 -3
  26. package/lib/index.d.ts +1 -0
  27. package/lib/index.js +1 -0
  28. package/lib/internal/bytes.d.ts +2 -0
  29. package/lib/internal/bytes.js +6 -0
  30. package/lib/internal/challenges.d.ts +6 -0
  31. package/lib/internal/challenges.js +15 -0
  32. package/package.json +21 -21
  33. package/src/actions/delete.ts +20 -42
  34. package/src/actions/download.ts +20 -41
  35. package/src/actions/has.ts +5 -2
  36. package/src/actions/list.ts +21 -35
  37. package/src/actions/media.ts +26 -47
  38. package/src/actions/mirror.ts +20 -44
  39. package/src/actions/multi-server.ts +25 -0
  40. package/src/actions/resolve.ts +5 -0
  41. package/src/actions/upload.ts +31 -48
  42. package/src/helpers/blob.ts +5 -4
  43. package/src/helpers/cashu.ts +184 -7
  44. package/src/helpers/headers.ts +5 -0
  45. package/src/helpers/index.ts +1 -1
  46. package/src/helpers/signal.ts +6 -4
  47. package/src/index.ts +1 -0
  48. package/src/internal/bytes.ts +6 -0
  49. package/src/internal/challenges.ts +25 -0
  50. package/src/types.ts +1 -2
package/README.md CHANGED
@@ -4,10 +4,60 @@ A client for managing blobs on blossom servers
4
4
 
5
5
  [Documentation](https://hzrd149.github.io/blossom-client-sdk/)
6
6
 
7
+ ## Testing
8
+
9
+ Install dependencies with `pnpm install --frozen-lockfile`.
10
+
11
+ - `pnpm test`: the Node Vitest suite.
12
+ - `pnpm test:browser`: the Vitest suite, including DOM/media tests, in headless Chromium, Firefox, and WebKit.
13
+ Install browsers first with `pnpm exec playwright install --with-deps`.
14
+ To run one browser, append `--browser.name=chromium` (or `firefox` / `webkit`).
15
+ - `pnpm test:node`, `pnpm test:deno`, `pnpm test:bun`: build the package and run the **same full Vitest suite**
16
+ in the selected runtime, followed by the same built-package export and HTTP integration tests.
17
+ Install Deno 2 or Bun for their respective commands. Worker runtime checks prevent accidental fallback to Node.
18
+ DOM-only tests run in browsers; Buffer-only tests run in server runtimes.
19
+ Deno needs `-A` for Vitest's workers, module loading, and local servers. TypeScript is checked during the build.
20
+ - `pnpm test:all`: run all of the above (requires all runtimes and browsers).
21
+
22
+ GitHub Actions runs the full suite across supported Node versions, Deno 2, the latest Bun, and all three browser engines.
23
+
24
+ ### ngit CI
25
+
26
+ The native [ngit CI workflow](https://ngit.dev/ci/workflows/) is `.grasp/nix/workflows/ci.yaml`.
27
+ It runs the same scripts in six independent jobs: Node 22, Deno, Bun, Chromium, Firefox, and WebKit.
28
+ The root `flake.lock` pins the Nix toolchain; `pnpm-lock.yaml` pins JavaScript dependencies and Playwright browser revisions.
29
+ Jobs require an x86_64 Linux provider with network access for package/browser downloads and support for
30
+ Bubblewrap's FHS environment (user namespaces). No repository secrets are needed.
31
+
32
+ With Nix flakes enabled, validate and run commands locally from this checkout:
33
+
34
+ ```sh
35
+ nix flake check --no-build
36
+ nix run .#install
37
+ nix run .#node
38
+ nix run .#deno
39
+ nix run .#bun
40
+ nix run .#chromium
41
+ nix run .#firefox
42
+ nix run .#webkit
43
+ ```
44
+
45
+ A maintainer must arrange a coordinator/provider and authorize the coordinator before automatic runs:
46
+
47
+ ```sh
48
+ ngit ci request <coordinator-npub>
49
+ # After publishing the committed workflow to the repository:
50
+ ngit ci trigger <coordinator-npub> HEAD --workflow .grasp/nix/workflows/ci.yaml
51
+ ngit ci status HEAD --json --require-ci-trust maintainer-directed
52
+ ```
53
+
54
+ The workflow responds to pushes and pull requests targeting `master`. Adding it alone does not activate a hosted CI service.
55
+
7
56
  ## Basic Usage
8
57
 
9
58
  ```js
10
- import { uploadBlob, createUploadAuth, encodeAuthorizationHeader } from "blossom-client-sdk";
59
+ import { createUploadAuth, encodeAuthorizationHeader } from "blossom-client-sdk";
60
+ import { uploadBlob } from "blossom-client-sdk/actions";
11
61
 
12
62
  async function signer(event) {
13
63
  return await window.nostr.signEvent(event);
@@ -230,7 +280,8 @@ hls.attachMedia(videoElement);
230
280
  ### List a page of blobs on a server
231
281
 
232
282
  ```js
233
- import { listBlobs, createListAuth } from "blossom-client-sdk";
283
+ import { createListAuth } from "blossom-client-sdk";
284
+ import { listBlobs } from "blossom-client-sdk/actions";
234
285
 
235
286
  async function signer(event) {
236
287
  return await window.nostr.signEvent(event);
@@ -247,7 +298,8 @@ const blobs = await listBlobs(server, pubkey, {
247
298
  ### Iterate blob pages on a server
248
299
 
249
300
  ```js
250
- import { iterateBlobs, createListAuth } from "blossom-client-sdk/actions";
301
+ import { createListAuth } from "blossom-client-sdk";
302
+ import { iterateBlobs } from "blossom-client-sdk/actions";
251
303
 
252
304
  async function signer(event) {
253
305
  return await window.nostr.signEvent(event);
@@ -267,7 +319,8 @@ for await (const page of iterateBlobs(server, pubkey, {
267
319
  ### Upload a single blob
268
320
 
269
321
  ```js
270
- import { uploadBlob, createUploadAuth } from "blossom-client-sdk";
322
+ import { createUploadAuth } from "blossom-client-sdk";
323
+ import { uploadBlob } from "blossom-client-sdk/actions";
271
324
 
272
325
  async function signer(event) {
273
326
  return await window.nostr.signEvent(event);
@@ -283,7 +336,8 @@ const blob = await uploadBlob(server, new File(["testing"], "test.txt"), {
283
336
  ### Upload a single blob to multiple servers
284
337
 
285
338
  ```js
286
- import { uploadBlob, createUploadAuth } from "blossom-client-sdk";
339
+ import { createUploadAuth } from "blossom-client-sdk";
340
+ import { uploadBlob } from "blossom-client-sdk/actions";
287
341
 
288
342
  async function signer(event) {
289
343
  return await window.nostr.signEvent(event);
@@ -304,7 +358,8 @@ for (let server of servers) {
304
358
  The `multiServerUpload` method uploads a blob to the first server, then mirrors it to the remaining servers. It runs parallel preflight checks (`HEAD /<sha256>`) to detect which servers already have the blob, using `/mirror` to register ownership on those servers instead of re-uploading.
305
359
 
306
360
  ```ts
307
- import { multiServerUpload, createUploadAuth } from "blossom-client-sdk";
361
+ import { createUploadAuth } from "blossom-client-sdk";
362
+ import { multiServerUpload } from "blossom-client-sdk/actions";
308
363
 
309
364
  async function signer(event: any) {
310
365
  // @ts-expect-error
@@ -336,7 +391,8 @@ const results = await multiServerUpload(servers, file, {
336
391
  The `multiServerMediaUpload` method is designed for media files (images, videos) that should be optimized before distribution. It uploads the blob to a single server's BUD-05 `/media` endpoint for processing, then mirrors the optimized result to all other servers. The original unprocessed blob is never uploaded to other servers since the `/media` endpoint may transform it (resize, re-encode, etc.).
337
392
 
338
393
  ```ts
339
- import { multiServerMediaUpload, createUploadAuth } from "blossom-client-sdk";
394
+ import { createUploadAuth } from "blossom-client-sdk";
395
+ import { multiServerMediaUpload } from "blossom-client-sdk/actions";
340
396
 
341
397
  async function signer(event: any) {
342
398
  // @ts-expect-error
@@ -362,7 +418,8 @@ const results = await multiServerMediaUpload(servers, media, {
362
418
  ### Upload and Mirror manually
363
419
 
364
420
  ```js
365
- import { uploadBlob, mirrorBlob, createUploadAuth } from "blossom-client-sdk";
421
+ import { createUploadAuth } from "blossom-client-sdk";
422
+ import { uploadBlob, mirrorBlob } from "blossom-client-sdk/actions";
366
423
 
367
424
  async function signer(event) {
368
425
  return await window.nostr.signEvent(event);
@@ -9,12 +9,15 @@ export type DeleteOptions<S extends ServerType> = {
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, headers: Headers) => Promise<HeadersInit>;
12
14
  /**
13
15
  * A method used to request payment when deleting
14
16
  * @param server the server requiring payment
15
17
  * @param sha256 the sha256 of the blob being uploaded or mirrored
16
18
  * @param request the payment request
17
19
  */
20
+ /** @deprecated Use onPaymentRequired to handle payment schemes generically. */
18
21
  onPayment?: (server: S, sha256: string, request: PaymentRequest) => Promise<PaymentToken>;
19
22
  /**
20
23
  * A method used to request a signed auth event for a server and sha256
@@ -1,6 +1,7 @@
1
1
  import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
2
2
  import HTTPError from "../error.js";
3
3
  import { fetchWithTimeout } from "../helpers/fetch.js";
4
+ import { handleChallenges } from "../internal/challenges.js";
4
5
  /** Deletes a blob to a server */
5
6
  export async function deleteBlob(server, hash, opts) {
6
7
  const url = new URL("/" + hash, server);
@@ -27,47 +28,25 @@ export async function deleteBlob(server, hash, opts) {
27
28
  headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
28
29
  }
29
30
  }
30
- let res = await fetchWithTimeout(url, {
31
- method: "DELETE",
32
- headers,
31
+ const request = (headers) => fetchWithTimeout(url, { method: "DELETE", headers, signal: opts?.signal, timeout: opts?.timeout });
32
+ const res = await handleChallenges(await request(headers), headers, request, {
33
33
  signal: opts?.signal,
34
- timeout: opts?.timeout,
35
- });
36
- // handle auth and payment
37
- switch (res.status) {
38
- case 401: {
39
- // throw an error if authorization is required but disabled
34
+ auth: async () => {
40
35
  if (opts?.auth === false)
41
36
  throw new Error("Authorization disabled");
42
- // request authorization for this request
43
- const auth = await resolveAuth();
44
- // Try delete with auth
45
- res = await fetchWithTimeout(url, {
46
- signal: opts?.signal,
47
- method: "DELETE",
48
- headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
49
- timeout: opts?.timeout,
50
- });
51
- break;
52
- }
53
- case 402: {
54
- if (!opts?.onPayment)
55
- throw new Error("Missing payment handler");
56
- const { getEncodedToken } = await import("@cashu/cashu-ts");
57
- const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
58
- const request = await getPaymentRequestFromHeaders(res.headers);
59
- const token = await opts.onPayment(server, hash, request);
60
- const payment = getEncodedToken(token);
61
- // Try delete with payment
62
- res = await fetchWithTimeout(url, {
63
- signal: opts?.signal,
64
- method: "DELETE",
65
- headers: { ...headers, "X-Cashu": payment },
66
- timeout: opts?.timeout,
67
- });
68
- break;
69
- }
70
- }
37
+ return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
38
+ },
39
+ payment: async (headers) => {
40
+ if (opts?.onPaymentRequired)
41
+ return opts.onPaymentRequired(server, hash, headers);
42
+ if (opts?.onPayment) {
43
+ const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
44
+ const request = await getPaymentRequestFromHeaders(headers);
45
+ return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, hash, request)) };
46
+ }
47
+ throw new Error("Missing payment handler");
48
+ },
49
+ });
71
50
  // handle errors
72
51
  await HTTPError.handleErrorResponse(res);
73
52
  // return blob descriptor
@@ -9,12 +9,15 @@ export type DownloadOptions<S extends ServerType> = {
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, headers: Headers) => Promise<HeadersInit>;
12
14
  /**
13
15
  * A method used to request payment when downloading
14
16
  * @param server the server requiring payment
15
17
  * @param sha256 the sha256 of the blob being uploaded or mirrored
16
18
  * @param request the payment request
17
19
  */
20
+ /** @deprecated Use onPaymentRequired to handle payment schemes generically. */
18
21
  onPayment?: (server: S, sha256: string, request: PaymentRequest) => Promise<PaymentToken>;
19
22
  /**
20
23
  * A method used to request a signed auth event for a server and sha256
@@ -1,6 +1,7 @@
1
1
  import HTTPError from "../error.js";
2
2
  import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
3
3
  import { fetchWithTimeout } from "../helpers/index.js";
4
+ import { handleChallenges } from "../internal/challenges.js";
4
5
  /** Downloads a blob from a server and returns the Response */
5
6
  export async function downloadBlob(server, hash, opts) {
6
7
  const url = new URL("/" + hash, server);
@@ -27,44 +28,25 @@ export async function downloadBlob(server, hash, opts) {
27
28
  headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
28
29
  }
29
30
  }
30
- let download = await fetchWithTimeout(url, {
31
- headers,
31
+ const request = (headers) => fetchWithTimeout(url, { headers, signal: opts?.signal, timeout: opts?.timeout });
32
+ const download = await handleChallenges(await request(headers), headers, request, {
32
33
  signal: opts?.signal,
33
- timeout: opts?.timeout,
34
- });
35
- // handle auth and payment
36
- switch (download.status) {
37
- case 401: {
38
- // throw an error if auth is requested and disabled
34
+ auth: async () => {
39
35
  if (opts?.auth === false)
40
36
  throw new Error("Authorization disabled");
41
- // Request authorization for this request
42
- const auth = await resolveAuth();
43
- // Try download with auth
44
- download = await fetchWithTimeout(url, {
45
- headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
46
- signal: opts?.signal,
47
- timeout: opts?.timeout,
48
- });
49
- break;
50
- }
51
- case 402: {
52
- if (!opts?.onPayment)
53
- throw new Error("Missing payment handler");
54
- const { getEncodedToken } = await import("@cashu/cashu-ts");
55
- const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
56
- const request = await getPaymentRequestFromHeaders(download.headers);
57
- const token = await opts.onPayment(server, hash, request);
58
- const payment = getEncodedToken(token);
59
- // Try download with payment
60
- download = await fetchWithTimeout(url, {
61
- headers: { ...headers, "X-Cashu": payment },
62
- signal: opts?.signal,
63
- timeout: opts?.timeout,
64
- });
65
- break;
66
- }
67
- }
37
+ return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
38
+ },
39
+ payment: async (headers) => {
40
+ if (opts?.onPaymentRequired)
41
+ return opts.onPaymentRequired(server, hash, headers);
42
+ if (opts?.onPayment) {
43
+ const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
44
+ const request = await getPaymentRequestFromHeaders(headers);
45
+ return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, hash, request)) };
46
+ }
47
+ throw new Error("Missing payment handler");
48
+ },
49
+ });
68
50
  // check download errors
69
51
  await HTTPError.handleErrorResponse(download);
70
52
  // return the raw response
@@ -5,5 +5,5 @@ export type HasBlobOptions = {
5
5
  /** Request timeout */
6
6
  timeout?: number;
7
7
  };
8
- /** Checks if a blob exists on a server */
8
+ /** Returns false for a missing blob (404), true on success, and throws on other HTTP errors. */
9
9
  export declare function hasBlob<S extends ServerType>(server: S, hash: string, opts?: HasBlobOptions): Promise<boolean>;
@@ -1,10 +1,14 @@
1
1
  import { fetchWithTimeout } from "../helpers/index.js";
2
- /** Checks if a blob exists on a server */
2
+ import HTTPError from "../error.js";
3
+ /** Returns false for a missing blob (404), true on success, and throws on other HTTP errors. */
3
4
  export async function hasBlob(server, hash, opts) {
4
5
  const res = await fetchWithTimeout(new URL("/" + hash, server), {
5
6
  method: "HEAD",
6
7
  signal: opts?.signal,
7
8
  timeout: opts?.timeout,
8
9
  });
9
- return res.status !== 404;
10
+ if (res.status === 404)
11
+ return false;
12
+ await HTTPError.handleErrorResponse(res);
13
+ return true;
10
14
  }
@@ -13,11 +13,14 @@ export type ListOptions<S extends ServerType> = {
13
13
  limit?: number;
14
14
  since?: number;
15
15
  until?: number;
16
+ /** Return headers to retry a request rejected with HTTP 402. */
17
+ onPaymentRequired?: (server: S, headers: Headers) => Promise<HeadersInit>;
16
18
  /**
17
19
  * A method used to request payment
18
20
  * @param server the server requiring payment
19
21
  * @param request the payment request
20
22
  */
23
+ /** @deprecated Use onPaymentRequired to handle payment schemes generically. */
21
24
  onPayment?: (server: S, request: PaymentRequest) => Promise<PaymentToken>;
22
25
  /**
23
26
  * A method used to request a signed auth event for a server
@@ -1,6 +1,7 @@
1
1
  import HTTPError from "../error.js";
2
2
  import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
3
3
  import { fetchWithTimeout } from "../helpers/index.js";
4
+ import { handleChallenges } from "../internal/challenges.js";
4
5
  /** Lists a page of blobs from a server */
5
6
  export async function listBlobs(server, pubkey, opts) {
6
7
  const url = new URL(`/list/` + pubkey, server);
@@ -34,39 +35,25 @@ export async function listBlobs(server, pubkey, opts) {
34
35
  headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
35
36
  }
36
37
  }
37
- let list = await fetchWithTimeout(url, { headers, signal: opts?.signal, timeout: opts?.timeout });
38
- // handle auth and payments
39
- switch (list.status) {
40
- case 401: {
41
- // throw an error if auth is requested and disabled
38
+ const request = (headers) => fetchWithTimeout(url, { headers, signal: opts?.signal, timeout: opts?.timeout });
39
+ const list = await handleChallenges(await request(headers), headers, request, {
40
+ signal: opts?.signal,
41
+ auth: async () => {
42
42
  if (opts?.auth === false)
43
43
  throw new Error("Authorization disabled");
44
- const auth = await resolveAuth();
45
- // Try list with auth
46
- list = await fetchWithTimeout(url, {
47
- headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
48
- signal: opts?.signal,
49
- timeout: opts?.timeout,
50
- });
51
- break;
52
- }
53
- case 402: {
54
- if (!opts?.onPayment)
55
- throw new Error("Missing payment handler");
56
- const { getEncodedToken } = await import("@cashu/cashu-ts");
57
- const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
58
- const request = await getPaymentRequestFromHeaders(list.headers);
59
- const token = await opts.onPayment(server, request);
60
- const payment = getEncodedToken(token);
61
- // Try list with payment
62
- list = await fetchWithTimeout(url, {
63
- headers: { ...headers, "X-Cashu": payment },
64
- signal: opts?.signal,
65
- timeout: opts?.timeout,
66
- });
67
- break;
68
- }
69
- }
44
+ return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
45
+ },
46
+ payment: async (headers) => {
47
+ if (opts?.onPaymentRequired)
48
+ return opts.onPaymentRequired(server, headers);
49
+ if (opts?.onPayment) {
50
+ const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
51
+ const request = await getPaymentRequestFromHeaders(headers);
52
+ return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, request)) };
53
+ }
54
+ throw new Error("Missing payment handler");
55
+ },
56
+ });
70
57
  // handle errors
71
58
  await HTTPError.handleErrorResponse(list);
72
59
  // return blob descriptor
@@ -1,6 +1,8 @@
1
1
  import { getBlobSha256, getBlobSize, getBlobType } from "../helpers/index.js";
2
+ import { handleChallenges } from "../internal/challenges.js";
2
3
  import HTTPError from "../error.js";
3
4
  import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
5
+ import { toWebBytes } from "../internal/bytes.js";
4
6
  /** Error thrown when /media endpoint is not present on a server */
5
7
  export class MediaEndpointMissingError extends Error {
6
8
  }
@@ -8,6 +10,7 @@ export class MediaEndpointMissingError extends Error {
8
10
  export async function uploadMedia(server, blob, opts) {
9
11
  const url = new URL("/media", server);
10
12
  const sha256 = await getBlobSha256(blob);
13
+ const body = blob instanceof Blob ? blob : toWebBytes(blob);
11
14
  const authEvents = opts?.authEvents;
12
15
  const resolveAuth = async (preset = false) => {
13
16
  const reused = authEvents
@@ -43,61 +46,41 @@ export async function uploadMedia(server, blob, opts) {
43
46
  if (type)
44
47
  checkHeaders["X-Content-Type"] = type;
45
48
  // check upload with HEAD /media
46
- let firstTry = await fetch(url, {
49
+ const firstTry = await fetch(url, {
47
50
  method: "HEAD",
48
51
  signal: opts?.signal,
49
52
  headers: checkHeaders,
50
53
  });
51
- let upload = undefined;
52
54
  if (firstTry.status === 404) {
53
55
  // HEAD endpoint is not supported. abort
54
56
  throw new MediaEndpointMissingError("/media endpoint not supported");
55
57
  }
56
- // handle auth and payment
57
- switch (firstTry.status) {
58
- case 401: {
59
- // throw an error if auth is requested and disabled
58
+ if (![401, 402].includes(firstTry.status))
59
+ await HTTPError.handleErrorResponse(firstTry);
60
+ const request = (headers) => fetch(url, {
61
+ signal: opts?.signal,
62
+ method: "PUT",
63
+ body,
64
+ headers,
65
+ });
66
+ const upload = await handleChallenges(firstTry.ok ? await request(headers) : firstTry, headers, request, {
67
+ signal: opts?.signal,
68
+ auth: async () => {
60
69
  if (opts?.auth === false)
61
70
  throw new Error("Authorization disabled");
62
- // Request authorization event for this upload
63
- const auth = await resolveAuth();
64
- // Try upload with auth
65
- upload = await fetch(url, {
66
- signal: opts?.signal,
67
- method: "PUT",
68
- body: blob,
69
- headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
70
- });
71
- break;
72
- }
73
- case 402: {
74
- if (!opts?.onPayment)
75
- throw new Error("Missing payment handler");
76
- const { getEncodedToken } = await import("@cashu/cashu-ts");
77
- const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
78
- const request = await getPaymentRequestFromHeaders(firstTry.headers);
79
- const token = await opts.onPayment(server, sha256, blob, request);
80
- const payment = getEncodedToken(token);
81
- // Try upload with payment
82
- upload = await fetch(url, {
83
- signal: opts?.signal,
84
- method: "PUT",
85
- body: blob,
86
- headers: { ...headers, "X-Cashu": payment },
87
- });
88
- break;
89
- }
90
- }
91
- if (firstTry.status >= 500)
92
- throw new Error("Server error");
93
- // check passed, upload
94
- if (!upload)
95
- upload = await fetch(url, {
96
- signal: opts?.signal,
97
- method: "PUT",
98
- body: blob,
99
- headers: { ...headers },
100
- });
71
+ return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
72
+ },
73
+ payment: async (headers) => {
74
+ if (opts?.onPaymentRequired)
75
+ return opts.onPaymentRequired(server, sha256, blob, headers);
76
+ if (opts?.onPayment) {
77
+ const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
78
+ const request = await getPaymentRequestFromHeaders(headers);
79
+ return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, sha256, blob, request)) };
80
+ }
81
+ throw new Error("Missing payment handler");
82
+ },
83
+ });
101
84
  // handle errors
102
85
  await HTTPError.handleErrorResponse(upload);
103
86
  // return blob descriptor
@@ -9,6 +9,8 @@ export type MirrorOptions<S extends ServerType> = {
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: BlobDescriptor, 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 MirrorOptions<S extends ServerType> = {
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: BlobDescriptor, request: PaymentRequest) => Promise<PaymentToken>;
20
23
  /**
21
24
  * A method used to request a signed auth event for a server and sha256
@@ -1,6 +1,7 @@
1
1
  import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
2
2
  import HTTPError from "../error.js";
3
3
  import { fetchWithTimeout } from "../helpers/index.js";
4
+ import { handleChallenges } from "../internal/challenges.js";
4
5
  /** Mirrors a blob to a server */
5
6
  export async function mirrorBlob(server, blob, opts) {
6
7
  const url = new URL("/mirror", server);
@@ -34,49 +35,25 @@ export async function mirrorBlob(server, blob, opts) {
34
35
  }
35
36
  }
36
37
  const body = JSON.stringify({ url: blob.url });
37
- let mirror = await fetchWithTimeout(url, {
38
- method: "PUT",
38
+ const request = (headers) => fetchWithTimeout(url, { method: "PUT", body, headers, signal: opts?.signal, timeout: opts?.timeout });
39
+ const mirror = await handleChallenges(await request(headers), headers, request, {
39
40
  signal: opts?.signal,
40
- headers,
41
- body,
42
- timeout: opts?.timeout,
43
- });
44
- switch (mirror.status) {
45
- case 401: {
46
- // throw an error if auth is requested and disabled
41
+ auth: async () => {
47
42
  if (opts?.auth === false)
48
43
  throw new Error("Authorization disabled");
49
- // Request authorization event for this mirror
50
- const auth = await resolveAuth();
51
- // Try mirror with auth
52
- mirror = await fetchWithTimeout(url, {
53
- signal: opts?.signal,
54
- method: "PUT",
55
- body,
56
- headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
57
- timeout: opts?.timeout,
58
- });
59
- break;
60
- }
61
- case 402: {
62
- if (!opts?.onPayment)
63
- throw new Error("Missing payment handler");
64
- const { getEncodedToken } = await import("@cashu/cashu-ts");
65
- const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
66
- const request = await getPaymentRequestFromHeaders(mirror.headers);
67
- const token = await opts.onPayment(server, blob.sha256, blob, request);
68
- const payment = getEncodedToken(token);
69
- // Try mirror with payment
70
- mirror = await fetchWithTimeout(url, {
71
- signal: opts?.signal,
72
- method: "PUT",
73
- body,
74
- headers: { ...headers, "X-Cashu": payment },
75
- timeout: opts?.timeout,
76
- });
77
- break;
78
- }
79
- }
44
+ return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
45
+ },
46
+ payment: async (headers) => {
47
+ if (opts?.onPaymentRequired)
48
+ return opts.onPaymentRequired(server, blob.sha256, blob, headers);
49
+ if (opts?.onPayment) {
50
+ const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
51
+ const request = await getPaymentRequestFromHeaders(headers);
52
+ return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, blob.sha256, blob, request)) };
53
+ }
54
+ throw new Error("Missing payment handler");
55
+ },
56
+ });
80
57
  // handle errors
81
58
  await HTTPError.handleErrorResponse(mirror);
82
59
  // return blob descriptor