blossom-client-sdk 1.1.1 → 2.0.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 +12 -33
- package/lib/actions/delete.d.ts +11 -0
- package/lib/actions/delete.js +42 -0
- package/lib/actions/download.d.ts +11 -0
- package/lib/actions/download.js +40 -0
- package/lib/actions/index.d.ts +5 -0
- package/lib/actions/index.js +5 -0
- package/lib/actions/list.d.ts +13 -0
- package/lib/actions/list.js +44 -0
- package/lib/actions/mirror.d.ts +11 -0
- package/lib/actions/mirror.js +55 -0
- package/lib/actions/upload.d.ts +24 -0
- package/lib/actions/upload.js +145 -0
- package/lib/auth.d.ts +27 -0
- package/lib/auth.js +113 -0
- package/lib/client.d.ts +45 -79
- package/lib/client.js +107 -226
- package/lib/const.d.ts +1 -0
- package/lib/const.js +1 -0
- package/lib/error.d.ts +11 -0
- package/lib/error.js +22 -0
- package/lib/helpers.d.ts +17 -0
- package/lib/helpers.js +61 -0
- package/lib/index.d.ts +4 -1
- package/lib/index.js +4 -1
- package/lib/nostr.d.ts +3 -6
- package/lib/nostr.js +0 -5
- package/lib/types.d.ts +40 -0
- package/lib/types.js +1 -0
- package/package.json +13 -4
- package/lib/upload.d.ts +0 -13
- package/lib/upload.js +0 -37
package/README.md
CHANGED
|
@@ -153,7 +153,7 @@ async function listBlobs() {
|
|
|
153
153
|
return BlossomClient.listBlobs(server, pubkey);
|
|
154
154
|
} catch (e) {
|
|
155
155
|
if (e.status === 401) {
|
|
156
|
-
const auth = await BlossomClient.
|
|
156
|
+
const auth = await BlossomClient.createListAuth(signer, "List Blobs from " + server);
|
|
157
157
|
return BlossomClient.listBlobs(server, pubkey, undefined, auth);
|
|
158
158
|
}
|
|
159
159
|
}
|
|
@@ -188,7 +188,7 @@ async function signer(event) {
|
|
|
188
188
|
const servers = ["https://cdn.example.com", "https://cdn.other.com"];
|
|
189
189
|
const file = new File(["testing"], "test.txt");
|
|
190
190
|
|
|
191
|
-
const auth = await BlossomClient.
|
|
191
|
+
const auth = await BlossomClient.createUploadAuth(file, signer, "Upload test.txt");
|
|
192
192
|
|
|
193
193
|
for (let server of servers) {
|
|
194
194
|
await BlossomClient.uploadBlob(server, file, auth);
|
|
@@ -202,7 +202,7 @@ The `multiServerUpload` method can be used to upload a single blob to multiple s
|
|
|
202
202
|
Example of uploading to each server one at time
|
|
203
203
|
|
|
204
204
|
```ts
|
|
205
|
-
import { multiServerUpload } from "blossom-server-sdk";
|
|
205
|
+
import { multiServerUpload, createUploadAuth } from "blossom-server-sdk";
|
|
206
206
|
|
|
207
207
|
async function signer(event: any) {
|
|
208
208
|
// @ts-expect-error
|
|
@@ -213,35 +213,14 @@ const servers = ["https://cdn.server-a.com", "https://cdn.example.com", "https:/
|
|
|
213
213
|
const file = new File(["testing"], "test.txt");
|
|
214
214
|
|
|
215
215
|
// create async generator for upload
|
|
216
|
-
const
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
try {
|
|
225
|
-
result = await upload.next();
|
|
226
|
-
successful++;
|
|
227
|
-
} catch (error) {
|
|
228
|
-
if (error instanceof Error) console.log(`Failed to upload ${error.message}`);
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
if (result) {
|
|
232
|
-
// if upload was successful log progress
|
|
233
|
-
if (!result.done) {
|
|
234
|
-
console.log(`Uploaded to ${result.value.server} ${result.value.progress * 100}%`);
|
|
235
|
-
} else if (result.done && result.value) {
|
|
236
|
-
console.log(`Successfully uploaded ${result.value.sha256} to ${servers} servers`);
|
|
237
|
-
|
|
238
|
-
// exit while loop (important)
|
|
239
|
-
break;
|
|
240
|
-
} else {
|
|
241
|
-
throw Error("Failed to upload blob to any servers");
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
}
|
|
216
|
+
const results = await multiServerUpload(servers, file, {
|
|
217
|
+
onAuth: async (server, blob) => createUploadAuth(signer, blob),
|
|
218
|
+
onUpload: (server, blob) => {},
|
|
219
|
+
onError: (server, blob, error) => {
|
|
220
|
+
console.log("Failed to upload to", server);
|
|
221
|
+
console.log(error);
|
|
222
|
+
},
|
|
223
|
+
});
|
|
245
224
|
```
|
|
246
225
|
|
|
247
226
|
### Upload and Mirror manually
|
|
@@ -257,7 +236,7 @@ const mainServer = "https://cdn.server-a.com";
|
|
|
257
236
|
const mirrorServers = ["https://cdn.example.com", "https://cdn.other.com"];
|
|
258
237
|
const file = new File(["testing"], "test.txt");
|
|
259
238
|
|
|
260
|
-
const auth = await BlossomClient.
|
|
239
|
+
const auth = await BlossomClient.createUploadAuth(file, signer, "Upload test.txt");
|
|
261
240
|
|
|
262
241
|
// first upload blob to main server
|
|
263
242
|
const blob = await BlossomClient.uploadBlob(mainServer, file, auth);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Token } from "@cashu/cashu-ts";
|
|
2
|
+
import { ServerType } from "../client.js";
|
|
3
|
+
import { PaymentRequest, SignedEvent } from "../types.js";
|
|
4
|
+
export type DeleteOptions<S extends ServerType> = {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
auth?: SignedEvent;
|
|
7
|
+
onPayment?: (server: S, hash: string, request: PaymentRequest) => Promise<Token>;
|
|
8
|
+
onAuth?: (server: S, hash: string) => Promise<SignedEvent>;
|
|
9
|
+
};
|
|
10
|
+
/** Deletes a blob to a server */
|
|
11
|
+
export declare function deleteBlob<S extends ServerType>(server: S, hash: string, opts?: DeleteOptions<S>): Promise<boolean>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import HTTPError from "../error.js";
|
|
2
|
+
import { encodeAuthorizationHeader } from "../auth.js";
|
|
3
|
+
import { getPaymentRequestFromHeaders } from "../helpers.js";
|
|
4
|
+
/** Deletes a blob to a server */
|
|
5
|
+
export async function deleteBlob(server, hash, opts) {
|
|
6
|
+
const url = new URL("/" + hash, server);
|
|
7
|
+
let res = await fetch(url, { signal: opts?.signal, method: "DELETE" });
|
|
8
|
+
// handle auth and payment
|
|
9
|
+
switch (res.status) {
|
|
10
|
+
case 402: {
|
|
11
|
+
if (!opts?.onPayment)
|
|
12
|
+
throw new Error("Missing payment handler");
|
|
13
|
+
const { getEncodedToken } = await import("@cashu/cashu-ts");
|
|
14
|
+
const request = getPaymentRequestFromHeaders(res.headers);
|
|
15
|
+
const token = await opts.onPayment(server, hash, request);
|
|
16
|
+
const payment = getEncodedToken(token);
|
|
17
|
+
// Try delete with payment
|
|
18
|
+
res = await fetch(url, {
|
|
19
|
+
signal: opts?.signal,
|
|
20
|
+
method: "DELETE",
|
|
21
|
+
headers: { "X-Cashu": payment },
|
|
22
|
+
});
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
case 403: {
|
|
26
|
+
const auth = opts?.auth || (await opts?.onAuth?.(server, hash));
|
|
27
|
+
if (!auth)
|
|
28
|
+
throw new Error("Missing auth handler");
|
|
29
|
+
// Try delete with auth
|
|
30
|
+
res = await fetch(url, {
|
|
31
|
+
signal: opts?.signal,
|
|
32
|
+
method: "DELETE",
|
|
33
|
+
headers: { Authorization: encodeAuthorizationHeader(auth) },
|
|
34
|
+
});
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// handle errors
|
|
39
|
+
await HTTPError.handleErrorResponse(res);
|
|
40
|
+
// return blob descriptor
|
|
41
|
+
return res.ok;
|
|
42
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Token } from "@cashu/cashu-ts";
|
|
2
|
+
import { ServerType } from "../client.js";
|
|
3
|
+
import { PaymentRequest, SignedEvent } from "../types.js";
|
|
4
|
+
export type DownloadOptions<S extends ServerType> = {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
auth?: SignedEvent;
|
|
7
|
+
onPayment?: (server: S, hash: string, request: PaymentRequest) => Promise<Token>;
|
|
8
|
+
onAuth?: (server: S, hash: string) => Promise<SignedEvent>;
|
|
9
|
+
};
|
|
10
|
+
/** Downloads a blob from a server and returns the Response */
|
|
11
|
+
export declare function downloadBlob<S extends ServerType>(server: S, hash: string, opts?: DownloadOptions<S>): Promise<Response>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import HTTPError from "../error.js";
|
|
2
|
+
import { encodeAuthorizationHeader } from "../auth.js";
|
|
3
|
+
import { getPaymentRequestFromHeaders } from "../helpers.js";
|
|
4
|
+
/** Downloads a blob from a server and returns the Response */
|
|
5
|
+
export async function downloadBlob(server, hash, opts) {
|
|
6
|
+
const url = new URL("/" + hash, server);
|
|
7
|
+
let download = await fetch(url, { signal: opts?.signal });
|
|
8
|
+
// handle auth and payment
|
|
9
|
+
switch (download.status) {
|
|
10
|
+
case 402: {
|
|
11
|
+
if (!opts?.onPayment)
|
|
12
|
+
throw new Error("Missing payment handler");
|
|
13
|
+
const { getEncodedToken } = await import("@cashu/cashu-ts");
|
|
14
|
+
const request = getPaymentRequestFromHeaders(download.headers);
|
|
15
|
+
const token = await opts.onPayment(server, hash, request);
|
|
16
|
+
const payment = getEncodedToken(token);
|
|
17
|
+
// Try download with payment
|
|
18
|
+
download = await fetch(url, {
|
|
19
|
+
signal: opts?.signal,
|
|
20
|
+
headers: { "X-Cashu": payment },
|
|
21
|
+
});
|
|
22
|
+
break;
|
|
23
|
+
}
|
|
24
|
+
case 403: {
|
|
25
|
+
const auth = opts?.auth || (await opts?.onAuth?.(server, hash));
|
|
26
|
+
if (!auth)
|
|
27
|
+
throw new Error("Missing auth handler");
|
|
28
|
+
// Try download with auth
|
|
29
|
+
download = await fetch(url, {
|
|
30
|
+
signal: opts?.signal,
|
|
31
|
+
headers: { Authorization: encodeAuthorizationHeader(auth) },
|
|
32
|
+
});
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// check download errors
|
|
37
|
+
await HTTPError.handleErrorResponse(download);
|
|
38
|
+
// return the raw response
|
|
39
|
+
return download;
|
|
40
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Token } from "@cashu/cashu-ts";
|
|
2
|
+
import { ServerType } from "../client.js";
|
|
3
|
+
import { BlobDescriptor, PaymentRequest, SignedEvent } from "../types.js";
|
|
4
|
+
export type ListOptions<S extends ServerType> = {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
auth?: SignedEvent;
|
|
7
|
+
since?: number;
|
|
8
|
+
until?: number;
|
|
9
|
+
onPayment?: (server: S, request: PaymentRequest) => Promise<Token>;
|
|
10
|
+
onAuth?: (server: S) => Promise<SignedEvent>;
|
|
11
|
+
};
|
|
12
|
+
/** Mirrors a blob to a server */
|
|
13
|
+
export declare function listBlobs<S extends ServerType>(server: S, pubkey: string, opts?: ListOptions<S>): Promise<BlobDescriptor[]>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import HTTPError from "../error.js";
|
|
2
|
+
import { encodeAuthorizationHeader } from "../auth.js";
|
|
3
|
+
import { getPaymentRequestFromHeaders } from "../helpers.js";
|
|
4
|
+
/** Mirrors a blob to a server */
|
|
5
|
+
export async function listBlobs(server, pubkey, opts) {
|
|
6
|
+
const url = new URL(`/list/` + pubkey, server);
|
|
7
|
+
if (opts?.since)
|
|
8
|
+
url.searchParams.append("since", String(opts.since));
|
|
9
|
+
if (opts?.until)
|
|
10
|
+
url.searchParams.append("until", String(opts.until));
|
|
11
|
+
let list = await fetch(url, { signal: opts?.signal });
|
|
12
|
+
// handle auth and payments
|
|
13
|
+
switch (list.status) {
|
|
14
|
+
case 402: {
|
|
15
|
+
if (!opts?.onPayment)
|
|
16
|
+
throw new Error("Missing payment handler");
|
|
17
|
+
const { getEncodedToken } = await import("@cashu/cashu-ts");
|
|
18
|
+
const request = getPaymentRequestFromHeaders(list.headers);
|
|
19
|
+
const token = await opts.onPayment(server, request);
|
|
20
|
+
const payment = getEncodedToken(token);
|
|
21
|
+
// Try list with payment
|
|
22
|
+
list = await fetch(url, {
|
|
23
|
+
signal: opts?.signal,
|
|
24
|
+
headers: { "X-Cashu": payment },
|
|
25
|
+
});
|
|
26
|
+
break;
|
|
27
|
+
}
|
|
28
|
+
case 403: {
|
|
29
|
+
const auth = opts?.auth || (await opts?.onAuth?.(server));
|
|
30
|
+
if (!auth)
|
|
31
|
+
throw new Error("Missing auth handler");
|
|
32
|
+
// Try list with auth
|
|
33
|
+
list = await fetch(url, {
|
|
34
|
+
signal: opts?.signal,
|
|
35
|
+
headers: { Authorization: encodeAuthorizationHeader(auth) },
|
|
36
|
+
});
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
// handle errors
|
|
41
|
+
await HTTPError.handleErrorResponse(list);
|
|
42
|
+
// return blob descriptor
|
|
43
|
+
return list.json();
|
|
44
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Token } from "@cashu/cashu-ts";
|
|
2
|
+
import { ServerType } from "../client.js";
|
|
3
|
+
import { BlobDescriptor, SignedEvent, PaymentRequest } from "../types.js";
|
|
4
|
+
export type MirrorOptions<S extends ServerType> = {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
auth?: SignedEvent;
|
|
7
|
+
onPayment?: (server: S, blob: BlobDescriptor, request: PaymentRequest) => Promise<Token>;
|
|
8
|
+
onAuth?: (server: S, blob: BlobDescriptor) => Promise<SignedEvent>;
|
|
9
|
+
};
|
|
10
|
+
/** Mirrors a blob to a server */
|
|
11
|
+
export declare function mirrorBlob<S extends ServerType>(server: S, blob: BlobDescriptor, opts?: MirrorOptions<S>): Promise<BlobDescriptor>;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import HTTPError from "../error.js";
|
|
2
|
+
import { encodeAuthorizationHeader } from "../auth.js";
|
|
3
|
+
import { getPaymentRequestFromHeaders } from "../helpers.js";
|
|
4
|
+
/** Mirrors a blob to a server */
|
|
5
|
+
export async function mirrorBlob(server, blob, opts) {
|
|
6
|
+
const url = new URL("/mirror", server);
|
|
7
|
+
const headers = {
|
|
8
|
+
"X-SHA-256": blob.sha256,
|
|
9
|
+
"X-Content-Length": String(blob.size),
|
|
10
|
+
};
|
|
11
|
+
if (blob.type)
|
|
12
|
+
headers["X-Content-Type"] = blob.type;
|
|
13
|
+
const body = JSON.stringify({ url: blob.url });
|
|
14
|
+
let mirror = await fetch(url, {
|
|
15
|
+
method: "PUT",
|
|
16
|
+
signal: opts?.signal,
|
|
17
|
+
headers,
|
|
18
|
+
body,
|
|
19
|
+
});
|
|
20
|
+
switch (mirror.status) {
|
|
21
|
+
case 401: {
|
|
22
|
+
const auth = opts?.auth || (await opts?.onAuth?.(server, blob));
|
|
23
|
+
if (!auth)
|
|
24
|
+
throw new Error("Missing auth handler");
|
|
25
|
+
// Try mirror with auth
|
|
26
|
+
mirror = await fetch(url, {
|
|
27
|
+
signal: opts?.signal,
|
|
28
|
+
method: "PUT",
|
|
29
|
+
body,
|
|
30
|
+
headers: { Authorization: encodeAuthorizationHeader(auth) },
|
|
31
|
+
});
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
case 402: {
|
|
35
|
+
if (!opts?.onPayment)
|
|
36
|
+
throw new Error("Missing payment handler");
|
|
37
|
+
const { getEncodedToken } = await import("@cashu/cashu-ts");
|
|
38
|
+
const request = getPaymentRequestFromHeaders(mirror.headers);
|
|
39
|
+
const token = await opts.onPayment(server, blob, request);
|
|
40
|
+
const payment = getEncodedToken(token);
|
|
41
|
+
// Try mirror with payment
|
|
42
|
+
mirror = await fetch(url, {
|
|
43
|
+
signal: opts?.signal,
|
|
44
|
+
method: "PUT",
|
|
45
|
+
body,
|
|
46
|
+
headers: { "X-Cashu": payment },
|
|
47
|
+
});
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// handle errors
|
|
52
|
+
await HTTPError.handleErrorResponse(mirror);
|
|
53
|
+
// return blob descriptor
|
|
54
|
+
return mirror.json();
|
|
55
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type Token } from "@cashu/cashu-ts";
|
|
2
|
+
import { ServerType, UploadType } from "../client.js";
|
|
3
|
+
import { BlobDescriptor, PaymentRequest, SignedEvent } from "../types.js";
|
|
4
|
+
export type UploadOptions<S extends ServerType, B extends UploadType> = {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
auth?: SignedEvent;
|
|
7
|
+
onPayment?: (server: S, blob: B, request: PaymentRequest) => Promise<Token>;
|
|
8
|
+
onAuth?: (server: S, blob: B) => Promise<SignedEvent>;
|
|
9
|
+
};
|
|
10
|
+
/** Upload a blob to a server, handles payment and auth */
|
|
11
|
+
export declare function uploadBlob<S extends ServerType, B extends UploadType>(server: S, blob: B, opts?: UploadOptions<S, B>): Promise<BlobDescriptor>;
|
|
12
|
+
export type MultiServerUploadOptions<S extends ServerType, B extends UploadType> = UploadOptions<S, B> & {
|
|
13
|
+
onStart?: (server: S, blob: B) => void;
|
|
14
|
+
onUpload?: (server: S, blob: B) => void;
|
|
15
|
+
onError?: (server: S, blob: B, error: Error) => void;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Creates an AsyncGenerator that can be used to upload a blob to multiple servers
|
|
19
|
+
* @param servers A Set or Array of servers to upload to
|
|
20
|
+
* @param blob The blob to be uploaded
|
|
21
|
+
* @param signer An async function used for signing nostr events
|
|
22
|
+
* @returns The BlobDescriptor if successful
|
|
23
|
+
*/
|
|
24
|
+
export declare function multiServerUpload<S extends ServerType, B extends UploadType>(servers: Iterable<S>, blob: B, opts?: MultiServerUploadOptions<S, B>): Promise<Map<S, BlobDescriptor>>;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { getBlobSha256, getBlobSize, getBlobType, getPaymentRequestFromHeaders } from "../helpers.js";
|
|
2
|
+
import HTTPError from "../error.js";
|
|
3
|
+
import { doseAuthMatchUpload, encodeAuthorizationHeader } from "../auth.js";
|
|
4
|
+
import { mirrorBlob } from "./mirror.js";
|
|
5
|
+
/** Upload a blob to a server, handles payment and auth */
|
|
6
|
+
export async function uploadBlob(server, blob, opts) {
|
|
7
|
+
const url = new URL("/upload", server);
|
|
8
|
+
const hash = await getBlobSha256(blob);
|
|
9
|
+
const headers = {
|
|
10
|
+
"X-SHA-256": hash,
|
|
11
|
+
};
|
|
12
|
+
// build check headers
|
|
13
|
+
const checkHeaders = {
|
|
14
|
+
...headers,
|
|
15
|
+
"X-Content-Length": String(getBlobSize(blob)),
|
|
16
|
+
};
|
|
17
|
+
const type = getBlobType(blob);
|
|
18
|
+
if (type)
|
|
19
|
+
checkHeaders["X-Content-Type"] = type;
|
|
20
|
+
// check upload with HEAD /upload
|
|
21
|
+
let check = await fetch(url, {
|
|
22
|
+
method: "HEAD",
|
|
23
|
+
signal: opts?.signal,
|
|
24
|
+
headers: checkHeaders,
|
|
25
|
+
});
|
|
26
|
+
let upload = undefined;
|
|
27
|
+
switch (check.status) {
|
|
28
|
+
case 401: {
|
|
29
|
+
const auth = opts?.auth || (await opts?.onAuth?.(server, blob));
|
|
30
|
+
if (!auth)
|
|
31
|
+
throw new Error("Missing auth handler");
|
|
32
|
+
// Try upload with auth
|
|
33
|
+
upload = await fetch(url, {
|
|
34
|
+
signal: opts?.signal,
|
|
35
|
+
method: "PUT",
|
|
36
|
+
body: blob,
|
|
37
|
+
headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
|
|
38
|
+
});
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
case 402: {
|
|
42
|
+
if (!opts?.onPayment)
|
|
43
|
+
throw new Error("Missing payment handler");
|
|
44
|
+
const { getEncodedToken } = await import("@cashu/cashu-ts");
|
|
45
|
+
const request = getPaymentRequestFromHeaders(check.headers);
|
|
46
|
+
const token = await opts.onPayment(server, blob, request);
|
|
47
|
+
const payment = getEncodedToken(token);
|
|
48
|
+
// Try upload with payment
|
|
49
|
+
upload = await fetch(url, {
|
|
50
|
+
signal: opts?.signal,
|
|
51
|
+
method: "PUT",
|
|
52
|
+
body: blob,
|
|
53
|
+
headers: { ...headers, "X-Cashu": payment },
|
|
54
|
+
});
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (check.status >= 500)
|
|
59
|
+
throw new Error("Server error");
|
|
60
|
+
// check passed, upload
|
|
61
|
+
if (!upload)
|
|
62
|
+
upload = await fetch(url, {
|
|
63
|
+
signal: opts?.signal,
|
|
64
|
+
method: "PUT",
|
|
65
|
+
body: blob,
|
|
66
|
+
headers: { ...headers },
|
|
67
|
+
});
|
|
68
|
+
// handle errors
|
|
69
|
+
await HTTPError.handleErrorResponse(upload);
|
|
70
|
+
// check upload errors
|
|
71
|
+
await HTTPError.handleErrorResponse(upload);
|
|
72
|
+
// return blob descriptor
|
|
73
|
+
return upload.json();
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Creates an AsyncGenerator that can be used to upload a blob to multiple servers
|
|
77
|
+
* @param servers A Set or Array of servers to upload to
|
|
78
|
+
* @param blob The blob to be uploaded
|
|
79
|
+
* @param signer An async function used for signing nostr events
|
|
80
|
+
* @returns The BlobDescriptor if successful
|
|
81
|
+
*/
|
|
82
|
+
export async function multiServerUpload(servers, blob, opts) {
|
|
83
|
+
let initialUpload;
|
|
84
|
+
const results = new Map();
|
|
85
|
+
// reuse auth events
|
|
86
|
+
let authEvents = opts?.auth ? [opts?.auth] : [];
|
|
87
|
+
const handleAuthRequest = async (server) => {
|
|
88
|
+
// check if any existing auth events match
|
|
89
|
+
for (const auth of authEvents) {
|
|
90
|
+
if (await doseAuthMatchUpload(auth, server, blob))
|
|
91
|
+
return auth;
|
|
92
|
+
}
|
|
93
|
+
// create a new auth event
|
|
94
|
+
if (opts?.onAuth) {
|
|
95
|
+
const auth = await opts.onAuth(server, blob);
|
|
96
|
+
authEvents.push(auth);
|
|
97
|
+
return auth;
|
|
98
|
+
}
|
|
99
|
+
else
|
|
100
|
+
throw new Error("Missing onAuth handler");
|
|
101
|
+
};
|
|
102
|
+
// handle payment requests for servers
|
|
103
|
+
const handlePaymentRequest = async (server, _b, request) => {
|
|
104
|
+
if (!opts?.onPayment)
|
|
105
|
+
throw new Error("Missing payment handler");
|
|
106
|
+
return opts.onPayment(server, blob, request);
|
|
107
|
+
};
|
|
108
|
+
// start server uploads
|
|
109
|
+
for (const server of servers) {
|
|
110
|
+
try {
|
|
111
|
+
let metadata = undefined;
|
|
112
|
+
opts?.onStart?.(server, blob);
|
|
113
|
+
// attempt to mirror the blob
|
|
114
|
+
if (initialUpload) {
|
|
115
|
+
try {
|
|
116
|
+
metadata = await mirrorBlob(server, initialUpload, {
|
|
117
|
+
signal: opts?.signal,
|
|
118
|
+
onAuth: handleAuthRequest,
|
|
119
|
+
onPayment: handlePaymentRequest,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
catch (error) { }
|
|
123
|
+
}
|
|
124
|
+
if (!metadata) {
|
|
125
|
+
metadata = await uploadBlob(server, blob, {
|
|
126
|
+
onAuth: handleAuthRequest,
|
|
127
|
+
onPayment: handlePaymentRequest,
|
|
128
|
+
});
|
|
129
|
+
// save first upload
|
|
130
|
+
if (!initialUpload)
|
|
131
|
+
initialUpload = metadata;
|
|
132
|
+
}
|
|
133
|
+
// save result
|
|
134
|
+
results.set(server, metadata);
|
|
135
|
+
// finished upload to server
|
|
136
|
+
opts?.onUpload?.(server, blob);
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
// failed to upload to server
|
|
140
|
+
if (error instanceof Error)
|
|
141
|
+
opts?.onError?.(server, blob, error);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return results;
|
|
145
|
+
}
|
package/lib/auth.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ServerType, UploadType } from "./client.js";
|
|
2
|
+
import { SignedEvent, Signer } from "./types.js";
|
|
3
|
+
export declare const now: () => number;
|
|
4
|
+
export declare const oneHour: () => number;
|
|
5
|
+
export declare function encodeAuthorizationHeader(event: SignedEvent): string;
|
|
6
|
+
/** Checks if an auth event matches a server / blob upload */
|
|
7
|
+
export declare function doseAuthMatchUpload(auth: SignedEvent, server: ServerType, blob: UploadType): Promise<boolean>;
|
|
8
|
+
/**
|
|
9
|
+
* Creates a GET auth event
|
|
10
|
+
* @param signer the signer to use for signing the event
|
|
11
|
+
* @param message A human readable explanation of what the auth token will be used for
|
|
12
|
+
* @param serverOrHash A server URL or one or many blob hashes
|
|
13
|
+
* @param expiration The expiration time in seconds
|
|
14
|
+
* @returns {Promise<SignedEvent>}
|
|
15
|
+
*/
|
|
16
|
+
export declare function createDownloadAuth(signer: Signer, serverOrHash: string | string[], message: string, expiration?: number): Promise<SignedEvent>;
|
|
17
|
+
/**
|
|
18
|
+
* Creates an upload auth event
|
|
19
|
+
* @param blobsOrHashes one or an array of sha256 hashes
|
|
20
|
+
* @param signer the signer to use for signing the event
|
|
21
|
+
* @param message A human readable explanation of what the auth token will be used for
|
|
22
|
+
* @param expiration The expiration time in seconds
|
|
23
|
+
* @returns {Promise<SignedEvent>}
|
|
24
|
+
*/
|
|
25
|
+
export declare function createUploadAuth(signer: Signer, blobsOrHashes: string | string[] | UploadType | UploadType[], message?: string, expiration?: number): Promise<SignedEvent>;
|
|
26
|
+
export declare function createListAuth(signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
|
|
27
|
+
export declare function createDeleteAuth(signer: Signer, hash: string | string[], message?: string, expiration?: number): Promise<SignedEvent>;
|
package/lib/auth.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { AUTH_EVENT_KIND } from "./const.js";
|
|
2
|
+
import { areServersEqual, getBlobSha256 } from "./helpers.js";
|
|
3
|
+
export const now = () => Math.floor(new Date().valueOf() / 1000);
|
|
4
|
+
export const oneHour = () => now() + 60 * 60;
|
|
5
|
+
export function encodeAuthorizationHeader(event) {
|
|
6
|
+
return "Nostr " + btoa(JSON.stringify(event));
|
|
7
|
+
}
|
|
8
|
+
/** Checks if an auth event matches a server / blob upload */
|
|
9
|
+
export async function doseAuthMatchUpload(auth, server, blob) {
|
|
10
|
+
const type = auth.tags.find((t) => t[0] === "t")?.[1];
|
|
11
|
+
if (type !== "upload")
|
|
12
|
+
return false;
|
|
13
|
+
for (const tag of auth.tags) {
|
|
14
|
+
switch (tag[0]) {
|
|
15
|
+
case "x":
|
|
16
|
+
if (tag[1] === (await getBlobSha256(blob)))
|
|
17
|
+
return true;
|
|
18
|
+
break;
|
|
19
|
+
case "server":
|
|
20
|
+
if (areServersEqual(tag[1], server))
|
|
21
|
+
return true;
|
|
22
|
+
break;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Creates a GET auth event
|
|
29
|
+
* @param signer the signer to use for signing the event
|
|
30
|
+
* @param message A human readable explanation of what the auth token will be used for
|
|
31
|
+
* @param serverOrHash A server URL or one or many blob hashes
|
|
32
|
+
* @param expiration The expiration time in seconds
|
|
33
|
+
* @returns {Promise<SignedEvent>}
|
|
34
|
+
*/
|
|
35
|
+
export async function createDownloadAuth(signer, serverOrHash, message, expiration = oneHour()) {
|
|
36
|
+
const draft = {
|
|
37
|
+
created_at: now(),
|
|
38
|
+
kind: AUTH_EVENT_KIND,
|
|
39
|
+
content: message,
|
|
40
|
+
tags: [
|
|
41
|
+
["t", "get"],
|
|
42
|
+
["expiration", String(expiration)],
|
|
43
|
+
],
|
|
44
|
+
};
|
|
45
|
+
if (Array.isArray(serverOrHash)) {
|
|
46
|
+
for (const sha256 of serverOrHash)
|
|
47
|
+
draft.tags.push(["x", sha256]);
|
|
48
|
+
}
|
|
49
|
+
else if (serverOrHash.match(/^[0-9a-f]{64}$/)) {
|
|
50
|
+
draft.tags.push(["x", serverOrHash]);
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
draft.tags.push(["server", new URL("/", serverOrHash).toString()]);
|
|
54
|
+
}
|
|
55
|
+
return await signer(draft);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Creates an upload auth event
|
|
59
|
+
* @param blobsOrHashes one or an array of sha256 hashes
|
|
60
|
+
* @param signer the signer to use for signing the event
|
|
61
|
+
* @param message A human readable explanation of what the auth token will be used for
|
|
62
|
+
* @param expiration The expiration time in seconds
|
|
63
|
+
* @returns {Promise<SignedEvent>}
|
|
64
|
+
*/
|
|
65
|
+
export async function createUploadAuth(signer, blobsOrHashes, message = "Upload Blob", expiration = oneHour()) {
|
|
66
|
+
const draft = {
|
|
67
|
+
kind: AUTH_EVENT_KIND,
|
|
68
|
+
content: message,
|
|
69
|
+
created_at: now(),
|
|
70
|
+
tags: [
|
|
71
|
+
["t", "upload"],
|
|
72
|
+
["expiration", String(expiration)],
|
|
73
|
+
],
|
|
74
|
+
};
|
|
75
|
+
const getHash = (blob) => (typeof blob === "string" ? blob : getBlobSha256(blob));
|
|
76
|
+
if (Array.isArray(blobsOrHashes)) {
|
|
77
|
+
for (const blob of blobsOrHashes)
|
|
78
|
+
draft.tags.push(["x", await getHash(blob)]);
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
draft.tags.push(["x", await getHash(blobsOrHashes)]);
|
|
82
|
+
}
|
|
83
|
+
return await signer(draft);
|
|
84
|
+
}
|
|
85
|
+
export async function createListAuth(signer, message = "List Blobs", expiration = oneHour()) {
|
|
86
|
+
return await signer({
|
|
87
|
+
created_at: now(),
|
|
88
|
+
kind: AUTH_EVENT_KIND,
|
|
89
|
+
content: message,
|
|
90
|
+
tags: [
|
|
91
|
+
["t", "list"],
|
|
92
|
+
["expiration", String(expiration)],
|
|
93
|
+
],
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
export async function createDeleteAuth(signer, hash, message = "Delete Blob", expiration = oneHour()) {
|
|
97
|
+
const draft = {
|
|
98
|
+
created_at: now(),
|
|
99
|
+
kind: AUTH_EVENT_KIND,
|
|
100
|
+
content: message,
|
|
101
|
+
tags: [
|
|
102
|
+
["t", "delete"],
|
|
103
|
+
["expiration", String(expiration)],
|
|
104
|
+
],
|
|
105
|
+
};
|
|
106
|
+
if (Array.isArray(hash)) {
|
|
107
|
+
for (const x of hash)
|
|
108
|
+
draft.tags.push(["x", x]);
|
|
109
|
+
}
|
|
110
|
+
else
|
|
111
|
+
draft.tags.push(["x", hash]);
|
|
112
|
+
return await signer(draft);
|
|
113
|
+
}
|