blossom-client-sdk 3.0.1 → 4.1.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 (47) hide show
  1. package/lib/actions/delete.d.ts +4 -5
  2. package/lib/actions/delete.js +18 -6
  3. package/lib/actions/download.d.ts +4 -5
  4. package/lib/actions/download.js +18 -5
  5. package/lib/actions/list.d.ts +4 -5
  6. package/lib/actions/list.js +22 -5
  7. package/lib/actions/media.js +18 -5
  8. package/lib/actions/mirror.d.ts +4 -5
  9. package/lib/actions/mirror.js +19 -6
  10. package/lib/actions/multi-server.js +15 -4
  11. package/lib/actions/upload.d.ts +4 -5
  12. package/lib/actions/upload.js +19 -6
  13. package/lib/auth.d.ts +4 -1
  14. package/lib/auth.js +18 -8
  15. package/lib/helpers/blob.d.ts +2 -0
  16. package/lib/helpers/blob.js +8 -5
  17. package/lib/helpers/cashu.js +14 -0
  18. package/lib/helpers/index.d.ts +1 -1
  19. package/lib/helpers/index.js +1 -1
  20. package/lib/helpers/signal.js +1 -1
  21. package/lib/image.js +25 -11
  22. package/lib/types.d.ts +20 -4
  23. package/package.json +18 -17
  24. package/src/actions/delete.ts +96 -0
  25. package/src/actions/download.ts +95 -0
  26. package/src/actions/index.ts +7 -0
  27. package/src/actions/list.ts +95 -0
  28. package/src/actions/media.ts +113 -0
  29. package/src/actions/mirror.ts +110 -0
  30. package/src/actions/multi-server.ts +218 -0
  31. package/src/actions/upload.ts +140 -0
  32. package/src/auth.ts +145 -0
  33. package/src/client.ts +221 -0
  34. package/src/const.ts +1 -0
  35. package/src/error.ts +23 -0
  36. package/src/helpers/blob.ts +62 -0
  37. package/src/helpers/cashu.ts +21 -0
  38. package/src/helpers/fetch.ts +16 -0
  39. package/src/helpers/index.ts +5 -0
  40. package/src/helpers/signal.ts +20 -0
  41. package/src/helpers/url.ts +16 -0
  42. package/src/image.ts +122 -0
  43. package/src/index.ts +9 -0
  44. package/src/nostr.ts +17 -0
  45. package/src/types.ts +63 -0
  46. package/lib/helpers/cachu.js +0 -6
  47. /package/lib/helpers/{cachu.d.ts → cashu.d.ts} +0 -0
@@ -0,0 +1,110 @@
1
+ import { encodeAuthorizationHeader } from "../auth.js";
2
+ import { ServerType } from "../client.js";
3
+ import HTTPError from "../error.js";
4
+ import { fetchWithTimeout } from "../helpers/index.js";
5
+ import { BlobDescriptor, PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
6
+
7
+ export type MirrorOptions<S extends ServerType> = {
8
+ /** AbortSignal to cancel the action */
9
+ signal?: AbortSignal;
10
+ /** Override authorization event, or true to always use authorization, false to disable authorization */
11
+ auth?: SignedEvent | boolean;
12
+ /** Request timeout */
13
+ timeout?: number;
14
+ /**
15
+ * A method used to request payment when uploading or mirroring a blob
16
+ * @param server the server requiring payment
17
+ * @param sha256 the sha256 of the blob being uploaded or mirrored
18
+ * @param blob the original blob
19
+ * @param request the payment request
20
+ */
21
+ onPayment?: (server: S, sha256: string, blob: BlobDescriptor, request: PaymentRequest) => Promise<PaymentToken>;
22
+ /**
23
+ * A method used to request a signed auth event for a server and sha256
24
+ * @param server the server requesting the auth
25
+ * @param sha256 the sha256 of the blob being upload or mirror to the server
26
+ * @param blob the original blob passed to the method
27
+ */
28
+ onAuth?: (server: S, sha256: string, blob: BlobDescriptor) => Promise<SignedEvent>;
29
+ };
30
+
31
+ /** Mirrors a blob to a server */
32
+ export async function mirrorBlob<S extends ServerType>(
33
+ server: S,
34
+ blob: BlobDescriptor,
35
+ opts?: MirrorOptions<S>,
36
+ ): Promise<BlobDescriptor> {
37
+ const url = new URL("/mirror", server);
38
+
39
+ const headers: Record<string, string> = {
40
+ "X-SHA-256": blob.sha256,
41
+ "X-Content-Length": String(blob.size),
42
+ "Content-Type": "application/json",
43
+ };
44
+ if (blob.type) headers["X-Content-Type"] = blob.type;
45
+
46
+ // attach the authorization if its already set
47
+ if (opts?.auth) {
48
+ if (typeof opts.auth === "boolean") {
49
+ if (!opts.onAuth) throw new Error("Missing onAuth handler");
50
+ headers["Authorization"] = encodeAuthorizationHeader(await opts.onAuth(server, blob.sha256, blob));
51
+ } else {
52
+ headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
53
+ }
54
+ }
55
+
56
+ const body = JSON.stringify({ url: blob.url });
57
+ let mirror = await fetchWithTimeout(url, {
58
+ method: "PUT",
59
+ signal: opts?.signal,
60
+ headers,
61
+ body,
62
+ timeout: opts?.timeout,
63
+ });
64
+
65
+ switch (mirror.status) {
66
+ case 401: {
67
+ // throw an error if auth is requested and disabled
68
+ if (opts?.auth === false) throw new Error("Authorization disabled");
69
+
70
+ // Request authorization event for this mirror
71
+ const auth = await opts?.onAuth?.(server, blob.sha256, blob);
72
+ if (!auth) throw new Error("Missing auth handler");
73
+
74
+ // Try mirror with auth
75
+ mirror = await fetchWithTimeout(url, {
76
+ signal: opts?.signal,
77
+ method: "PUT",
78
+ body,
79
+ headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
80
+ timeout: opts?.timeout,
81
+ });
82
+ break;
83
+ }
84
+ case 402: {
85
+ if (!opts?.onPayment) throw new Error("Missing payment handler");
86
+ const { getEncodedToken } = await import("@cashu/cashu-ts");
87
+ const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
88
+ const request = getPaymentRequestFromHeaders(mirror.headers);
89
+
90
+ const token = await opts.onPayment(server, blob.sha256, blob, request);
91
+ const payment = getEncodedToken(token);
92
+
93
+ // Try mirror with payment
94
+ mirror = await fetchWithTimeout(url, {
95
+ signal: opts?.signal,
96
+ method: "PUT",
97
+ body,
98
+ headers: { ...headers, "X-Cashu": payment },
99
+ timeout: opts?.timeout,
100
+ });
101
+ break;
102
+ }
103
+ }
104
+
105
+ // handle errors
106
+ await HTTPError.handleErrorResponse(mirror);
107
+
108
+ // return blob descriptor
109
+ return mirror.json();
110
+ }
@@ -0,0 +1,218 @@
1
+ import { doseAuthMatchBlob } from "../auth.js";
2
+ import { ServerType, UploadType } from "../client.js";
3
+ import { getBlobSha256 } from "../helpers/index.js";
4
+ import { BlobDescriptor, PaymentRequest } from "../types.js";
5
+ import { MediaEndpointMissingError, uploadMedia } from "./media.js";
6
+ import { mirrorBlob } from "./mirror.js";
7
+ import { uploadBlob, UploadOptions } from "./upload.js";
8
+
9
+ export type MultiServerUploadOptions<S extends ServerType, B extends UploadType> = UploadOptions<S, B> & {
10
+ /**
11
+ * Signals this blob should be treated as a media file and should attempt to use BUD-05 /media endpoint for upload on first server
12
+ * @default false
13
+ */
14
+ isMedia?: boolean;
15
+ /**
16
+ * If isMedia is enabled, this determines how /media endpoints should be prioritized
17
+ * - "first" Only use the first server in the list to optimize the media
18
+ * - "any" Use any server in the list to optimize the media
19
+ * @default "first"
20
+ */
21
+ mediaUploadBehavior?: "first" | "any";
22
+ /**
23
+ * If isMedia is enabled, should the raw blob be uploaded if no /media endpoint can be found
24
+ * @default false
25
+ */
26
+ mediaUploadFallback?: boolean;
27
+ /**
28
+ * Timeout for mirror requests
29
+ * @default 5000
30
+ */
31
+ mirrorTimeout?: number;
32
+ /**
33
+ * called on blob when uploaded to started to a server
34
+ * @param server
35
+ * @param sha256 the hash of the blob being uploaded or mirrored
36
+ * @param blob the original blob
37
+ */
38
+ onStart?: (server: S, sha256: string, blob: B) => void;
39
+ /** called when upload to a server is complete */
40
+ onUpload?: (server: S, sha256: string, blob: B) => void;
41
+ /** called when upload to a server fails */
42
+ onError?: (server: S, sha256: string, blob: B, error: Error) => void;
43
+ };
44
+
45
+ const defaultMultiServerOptions: MultiServerUploadOptions<any, any> = {
46
+ isMedia: false,
47
+ mediaUploadBehavior: "first",
48
+ mediaUploadFallback: false,
49
+ mirrorTimeout: 5000,
50
+ };
51
+
52
+ /**
53
+ * Creates an AsyncGenerator that can be used to upload a blob to multiple servers
54
+ * @param servers A Set or Array of servers to upload to
55
+ * @param blob The blob to be uploaded
56
+ * @param signer An async function used for signing nostr events
57
+ * @returns The BlobDescriptor if successful
58
+ *
59
+ * ```mermaid
60
+ * flowchart LR
61
+ * isMedia{"isMedia"} -- yes --> media["/media"]
62
+ * isMedia -- no --> upload["/upload"]
63
+ * media --> ifmedia{"Successful"}
64
+ * ifmedia -- yes --> next["Next server"]
65
+ * ifmedia -- no --> iffallback{"fallback"}
66
+ * iffallback -- yes --> upload
67
+ * iffallback -- no --> abort
68
+ * upload -- complete --> next
69
+ * next --> uploaded{"Uploaded"}
70
+ * uploaded -- yes --> mirror["/mirror"]
71
+ * uploaded -- no --> upload
72
+ * mirror --> isMirror{"Successful"}
73
+ * isMirror -- yes --> next
74
+ * isMirror -- no --> ifMediaAbort{"isMedia"}
75
+ * ifMediaAbort -- no --> upload
76
+ * ifMediaAbort -- yes --> next
77
+ * ```
78
+ */
79
+ export async function multiServerUpload<S extends ServerType, B extends UploadType>(
80
+ servers: Iterable<S>,
81
+ blob: B,
82
+ opts?: MultiServerUploadOptions<S, B>,
83
+ ) {
84
+ const options = { ...defaultMultiServerOptions, ...opts };
85
+ let initialUpload: BlobDescriptor | undefined;
86
+ const results = new Map<S, BlobDescriptor>();
87
+
88
+ // reuse auth events
89
+ let authEvents = typeof options.auth === "object" ? [options.auth] : [];
90
+ const handleAuthRequest = async (server: S, sha256: string, type: "upload" | "media") => {
91
+ // check if any existing auth events match
92
+ for (const auth of authEvents) {
93
+ if (await doseAuthMatchBlob(auth, server, sha256, type)) return auth;
94
+ }
95
+
96
+ // create a new auth event
97
+ if (options.onAuth) {
98
+ const auth = await options.onAuth(server, sha256, type, blob);
99
+ authEvents.push(auth);
100
+ return auth;
101
+ } else throw new Error("Missing onAuth handler");
102
+ };
103
+
104
+ // handle payment requests for servers
105
+ const handlePaymentRequest = async (server: S, sha256: string, _blog: any, request: PaymentRequest) => {
106
+ if (!options.onPayment) throw new Error("Missing payment handler");
107
+
108
+ return options.onPayment(server, sha256, blob, request);
109
+ };
110
+
111
+ // servers to upload the blob to
112
+ const uploadServers = Array.from(servers);
113
+
114
+ // start media upload
115
+ if (options.isMedia) {
116
+ const mediaServers = options.mediaUploadBehavior === "any" ? Array.from(servers) : [Array.from(servers)[0]];
117
+
118
+ for (const server of mediaServers) {
119
+ try {
120
+ const sha256 = await getBlobSha256(blob);
121
+ options.onStart?.(server, sha256, blob);
122
+
123
+ // attempt to upload media
124
+ initialUpload = await uploadMedia(server, blob, {
125
+ // pass through abort signal
126
+ signal: options.signal,
127
+ // pass through authorization flag
128
+ auth: typeof options.auth === "boolean" ? options.auth : undefined,
129
+ onAuth: handleAuthRequest,
130
+ onPayment: handlePaymentRequest,
131
+ });
132
+
133
+ // save result
134
+ results.set(server, initialUpload);
135
+
136
+ // finished upload to server
137
+ options.onUpload?.(server, initialUpload.sha256, blob);
138
+ } catch (error) {
139
+ if (error instanceof MediaEndpointMissingError) {
140
+ // ignore error
141
+ } else if (error instanceof Error) {
142
+ const sha256 = await getBlobSha256(blob);
143
+ options.onError?.(server, sha256, blob, error);
144
+ }
145
+ }
146
+
147
+ if (initialUpload) {
148
+ // remove server from upload array
149
+ if (uploadServers.includes(server)) uploadServers.splice(uploadServers.indexOf(server), 1);
150
+
151
+ // exit on first successful media upload
152
+ break;
153
+ }
154
+ }
155
+
156
+ if (!options.mediaUploadFallback && !initialUpload) {
157
+ // failed to find a /media endpoint, abort
158
+ throw new Error("Failed to find media processing endpoint");
159
+ }
160
+ }
161
+
162
+ // start server uploads
163
+ for (const server of uploadServers) {
164
+ try {
165
+ let metadata: BlobDescriptor | undefined = undefined;
166
+
167
+ // attempt to mirror the initial upload
168
+ if (initialUpload) {
169
+ try {
170
+ options.onStart?.(server, initialUpload.sha256, blob);
171
+
172
+ metadata = await mirrorBlob(server, initialUpload, {
173
+ // pass through abort signal
174
+ signal: options.signal,
175
+ // pass through authorization flag
176
+ auth: typeof options.auth === "boolean" ? options.auth : undefined,
177
+ onAuth: (server, sha256) => handleAuthRequest(server, sha256, "upload"),
178
+ onPayment: handlePaymentRequest,
179
+ timeout: options.mirrorTimeout,
180
+ });
181
+ } catch (error) {
182
+ // mirror failed, if isMedia skip server since we don't want to upload two versions of the blob
183
+ if (options.isMedia) continue;
184
+ }
185
+ }
186
+
187
+ // attempt to upload if first upload or mirror failed
188
+ if (!metadata) {
189
+ const sha256 = await getBlobSha256(blob);
190
+ options.onStart?.(server, sha256, blob);
191
+
192
+ metadata = await uploadBlob(server, blob, {
193
+ // pass through abort signal
194
+ signal: options.signal,
195
+ // pass through authorization flag
196
+ auth: typeof options.auth === "boolean" ? options.auth : undefined,
197
+ onAuth: handleAuthRequest,
198
+ onPayment: handlePaymentRequest,
199
+ timeout: options.mirrorTimeout,
200
+ });
201
+
202
+ // save first upload
203
+ if (!initialUpload) initialUpload = metadata;
204
+ }
205
+
206
+ // save result
207
+ results.set(server, metadata);
208
+
209
+ // finished upload to server
210
+ options.onUpload?.(server, metadata.sha256, blob);
211
+ } catch (error) {
212
+ // failed to upload to server
213
+ if (error instanceof Error) options.onError?.(server, await getBlobSha256(blob), blob, error);
214
+ }
215
+ }
216
+
217
+ return results;
218
+ }
@@ -0,0 +1,140 @@
1
+ import { encodeAuthorizationHeader } from "../auth.js";
2
+ import { ServerType, UploadType } from "../client.js";
3
+ import HTTPError from "../error.js";
4
+ import { fetchWithTimeout, getBlobSha256, getBlobSize, getBlobType } from "../helpers/index.js";
5
+ import { BlobDescriptor, PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
6
+
7
+ export type UploadOptions<S extends ServerType, B extends UploadType> = {
8
+ /** AbortSignal to cancel the action */
9
+ signal?: AbortSignal;
10
+ /** Override authorization event, or true to always use authorization, false to disable authorization */
11
+ auth?: SignedEvent | boolean;
12
+ /** Request timeout */
13
+ timeout?: number;
14
+ /**
15
+ * A method used to request payment when uploading or mirroring a blob
16
+ * @param server the server requiring payment
17
+ * @param sha256 the sha256 of the blob being uploaded or mirrored
18
+ * @param blob the original blob
19
+ * @param request the payment request
20
+ */
21
+ onPayment?: (server: S, sha256: string, blob: B, request: PaymentRequest) => Promise<PaymentToken>;
22
+ /**
23
+ * A method used to request a signed auth event for a server and sha256
24
+ * @param server the server requesting the auth
25
+ * @param sha256 the sha256 of the blob being upload or mirror to the server
26
+ * @param blob the original blob passed to the method
27
+ */
28
+ onAuth?: (server: S, sha256: string, authType: "upload" | "media", blob: B) => Promise<SignedEvent>;
29
+ };
30
+
31
+ /** Upload a blob to a server, handles payment and auth */
32
+ export async function uploadBlob<S extends ServerType, B extends UploadType>(
33
+ server: S,
34
+ blob: B,
35
+ opts?: UploadOptions<S, B>,
36
+ ): Promise<BlobDescriptor> {
37
+ const url = new URL("/upload", server);
38
+ const sha256 = await getBlobSha256(blob);
39
+
40
+ const headers: Record<string, string> = {
41
+ "X-SHA-256": sha256,
42
+ };
43
+
44
+ // attach the authorization if its already set
45
+ if (opts?.auth) {
46
+ if (typeof opts.auth === "boolean") {
47
+ if (!opts.onAuth) throw new Error("Missing onAuth handler");
48
+ headers["Authorization"] = encodeAuthorizationHeader(await opts.onAuth(server, sha256, "upload", blob));
49
+ } else {
50
+ headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
51
+ }
52
+ }
53
+
54
+ // build check headers
55
+ const checkHeaders: Record<string, string> = {
56
+ ...headers,
57
+ "X-Content-Length": String(getBlobSize(blob)),
58
+ };
59
+ const type = getBlobType(blob);
60
+ if (type) checkHeaders["X-Content-Type"] = type;
61
+
62
+ // check upload with HEAD /upload
63
+ let firstTry = await fetchWithTimeout(url, {
64
+ method: "HEAD",
65
+ signal: opts?.signal,
66
+ headers: checkHeaders,
67
+ timeout: opts?.timeout,
68
+ });
69
+
70
+ let upload: Response | undefined = undefined;
71
+
72
+ if (firstTry.status === 404) {
73
+ // BUD-06 HEAD endpoint is not supported. attempt to upload
74
+ upload = firstTry = await fetchWithTimeout(url, {
75
+ body: blob,
76
+ method: "PUT",
77
+ signal: opts?.signal,
78
+ timeout: opts?.timeout,
79
+ });
80
+ }
81
+
82
+ // handle auth and payment
83
+ switch (firstTry.status) {
84
+ case 401: {
85
+ // throw an error if auth is requested and disabled
86
+ if (opts?.auth === false) throw new Error("Authorization disabled");
87
+
88
+ // Request authorization event for this upload
89
+ const auth = await opts?.onAuth?.(server, sha256, "upload", blob);
90
+ if (!auth) throw new Error("Missing auth handler");
91
+
92
+ // Try upload with auth
93
+ upload = await fetchWithTimeout(url, {
94
+ method: "PUT",
95
+ body: blob,
96
+ headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
97
+ signal: opts?.signal,
98
+ timeout: opts?.timeout,
99
+ });
100
+ break;
101
+ }
102
+ case 402: {
103
+ if (!opts?.onPayment) throw new Error("Missing payment handler");
104
+ const { getEncodedToken } = await import("@cashu/cashu-ts");
105
+ const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
106
+ const request = getPaymentRequestFromHeaders(firstTry.headers);
107
+
108
+ const token = await opts.onPayment(server, sha256, blob, request);
109
+ const payment = getEncodedToken(token);
110
+
111
+ // Try upload with payment
112
+ upload = await fetchWithTimeout(url, {
113
+ method: "PUT",
114
+ body: blob,
115
+ headers: { ...headers, "X-Cashu": payment },
116
+ signal: opts?.signal,
117
+ timeout: opts?.timeout,
118
+ });
119
+ break;
120
+ }
121
+ }
122
+
123
+ if (firstTry.status >= 500) throw new Error("Server error");
124
+
125
+ // check passed, upload
126
+ if (!upload)
127
+ upload = await fetchWithTimeout(url, {
128
+ method: "PUT",
129
+ body: blob,
130
+ headers: { ...headers },
131
+ signal: opts?.signal,
132
+ timeout: opts?.timeout,
133
+ });
134
+
135
+ // handle errors
136
+ await HTTPError.handleErrorResponse(upload);
137
+
138
+ // return blob descriptor
139
+ return upload.json();
140
+ }
package/src/auth.ts ADDED
@@ -0,0 +1,145 @@
1
+ import { ServerType, UploadType } from "./client.js";
2
+ import { AUTH_EVENT_KIND } from "./const.js";
3
+ import { getBlobSha256, isSha256 } from "./helpers/blob.js";
4
+ import { areServersEqual } from "./helpers/url.js";
5
+ import { EventTemplate, SignedEvent, Signer } from "./types.js";
6
+
7
+ export const now = () => Math.floor(new Date().valueOf() / 1000);
8
+ export const oneHour = () => now() + 60 * 60;
9
+
10
+ /** Encodes an auth event into a nostr authorization header */
11
+ export function encodeAuthorizationHeader(event: SignedEvent) {
12
+ return "Nostr " + btoa(JSON.stringify(event));
13
+ }
14
+
15
+ /** Checks if an auth event matches a server / blob upload */
16
+ export async function doseAuthMatchBlob(
17
+ auth: SignedEvent,
18
+ server: ServerType,
19
+ blob: string | UploadType,
20
+ type: string = "upload",
21
+ ) {
22
+ const authType = auth.tags.find((t) => t[0] === "t")?.[1];
23
+ if (authType !== type) return false;
24
+
25
+ const sha256 = typeof blob === "string" ? blob : await getBlobSha256(blob);
26
+
27
+ for (const tag of auth.tags) {
28
+ switch (tag[0]) {
29
+ case "x":
30
+ if (tag[1] === sha256) return true;
31
+ break;
32
+ case "server":
33
+ if (areServersEqual(tag[1], server)) return true;
34
+ break;
35
+ }
36
+ }
37
+
38
+ return false;
39
+ }
40
+
41
+ /** @deprecated Use `doseAuthMatchBlob` instead */
42
+ export const doseAuthMatchUpload = doseAuthMatchBlob;
43
+
44
+ async function normalizeToHash(blob: string | UploadType) {
45
+ return typeof blob === "string" ? blob : getBlobSha256(blob);
46
+ }
47
+
48
+ export type AuthType = "upload" | "list" | "delete" | "get" | "media";
49
+ export type AuthEventOptions = {
50
+ blobs?: string | string[] | UploadType | UploadType[];
51
+ servers?: string | string[];
52
+ message?: string;
53
+ expiration?: number;
54
+ };
55
+
56
+ /** Generic auth event builder */
57
+ export async function createAuthEvent(signer: Signer, type: AuthType, options?: AuthEventOptions) {
58
+ const draft: EventTemplate = {
59
+ created_at: now(),
60
+ kind: AUTH_EVENT_KIND,
61
+ content: options?.message ?? "",
62
+ tags: [
63
+ ["t", type],
64
+ // attach NIP-40 expiration
65
+ ["expiration", String(options?.expiration ?? oneHour())],
66
+ ],
67
+ };
68
+
69
+ // add blob tags
70
+ if (options?.blobs) {
71
+ if (Array.isArray(options.blobs)) {
72
+ const seen = new Set<string>();
73
+ for (const blob of options.blobs) {
74
+ const hash = await normalizeToHash(blob);
75
+ if (!seen.has(hash)) {
76
+ draft.tags.push(["x", hash]);
77
+ seen.add(hash);
78
+ }
79
+ }
80
+ } else draft.tags.push(["x", await normalizeToHash(options.blobs)]);
81
+ }
82
+
83
+ // add server tags
84
+ if (options?.servers) {
85
+ if (Array.isArray(options.servers))
86
+ for (const server of new Set(options.servers)) draft.tags.push(["server", server]);
87
+ else draft.tags.push(["server", options.servers]);
88
+ }
89
+
90
+ return await signer(draft);
91
+ }
92
+
93
+ export type DownloadAuthOptions = Omit<AuthEventOptions, "blobs" | "servers">;
94
+ /** Creates a GET auth event */
95
+ export async function createDownloadAuth(
96
+ signer: Signer,
97
+ serverOrHash: string | string[] | UploadType | UploadType[],
98
+ options?: DownloadAuthOptions,
99
+ ) {
100
+ if (!Array.isArray(serverOrHash)) serverOrHash = [serverOrHash] as string[] | UploadType[];
101
+
102
+ return await createAuthEvent(signer, "get", {
103
+ message: "Download Blob",
104
+ ...options,
105
+ blobs: serverOrHash.filter((s) => (typeof s === "string" ? isSha256(s) : true)) as string[] | UploadType[],
106
+ servers: serverOrHash.filter((s) => typeof s === "string" && !isSha256(s) && URL.canParse(s)) as string[],
107
+ });
108
+ }
109
+
110
+ export type UploadAuthOptions = Omit<AuthEventOptions, "blobs"> & { type?: "upload" | "media" };
111
+ /** Creates an upload or media upload auth event */
112
+ export async function createUploadAuth(
113
+ signer: Signer,
114
+ blobs: string | string[] | UploadType | UploadType[],
115
+ options?: UploadAuthOptions,
116
+ ) {
117
+ return await createAuthEvent(signer, options?.type ?? "upload", { message: "Upload Blob", ...options, blobs });
118
+ }
119
+
120
+ export type MirrorAuthOptions = Omit<AuthEventOptions, "blobs">;
121
+ /** Creates an upload or media upload auth event */
122
+ export async function createMirrorAuth(
123
+ signer: Signer,
124
+ blobs: string | string[] | UploadType | UploadType[],
125
+ options?: MirrorAuthOptions,
126
+ ) {
127
+ // The /mirror endpoint uses "upload" type
128
+ return await createAuthEvent(signer, "upload", { message: "Mirror Blob", ...options, blobs });
129
+ }
130
+
131
+ export type ListAuthOptions = Omit<AuthEventOptions, "blobs">;
132
+ /** Creates a list auth event */
133
+ export async function createListAuth(signer: Signer, options?: ListAuthOptions) {
134
+ return await createAuthEvent(signer, "list", { message: "List Blobs", ...options });
135
+ }
136
+
137
+ export type DeleteAuthOptions = Omit<AuthEventOptions, "blobs">;
138
+ /** Creates a "delete" auth event for a specific hash */
139
+ export async function createDeleteAuth(
140
+ signer: Signer,
141
+ blobs: string | string[] | UploadType | UploadType[],
142
+ options?: DeleteAuthOptions,
143
+ ) {
144
+ return await createAuthEvent(signer, "delete", { message: "Delete Blob", ...options, blobs });
145
+ }