blossom-client-sdk 3.0.0 → 4.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/lib/actions/delete.d.ts +2 -3
- package/lib/actions/delete.js +2 -2
- package/lib/actions/download.d.ts +2 -3
- package/lib/actions/download.js +2 -1
- package/lib/actions/list.d.ts +2 -3
- package/lib/actions/list.js +9 -4
- package/lib/actions/media.js +2 -1
- package/lib/actions/mirror.d.ts +2 -3
- package/lib/actions/mirror.js +6 -4
- package/lib/actions/multi-server.js +1 -1
- package/lib/actions/upload.d.ts +2 -3
- package/lib/actions/upload.js +3 -2
- package/lib/auth.d.ts +1 -0
- package/lib/auth.js +13 -5
- package/lib/helpers/blob.d.ts +2 -0
- package/lib/helpers/blob.js +8 -5
- package/lib/helpers/cashu.js +14 -0
- package/lib/helpers/index.d.ts +1 -1
- package/lib/helpers/index.js +1 -1
- package/lib/helpers/signal.js +1 -1
- package/lib/image.js +25 -11
- package/lib/types.d.ts +20 -4
- package/package.json +18 -17
- package/src/actions/delete.ts +85 -0
- package/src/actions/download.ts +84 -0
- package/src/actions/index.ts +7 -0
- package/src/actions/list.ts +83 -0
- package/src/actions/media.ts +102 -0
- package/src/actions/mirror.ts +99 -0
- package/src/actions/multi-server.ts +207 -0
- package/src/actions/upload.ts +129 -0
- package/src/auth.ts +137 -0
- package/src/client.ts +221 -0
- package/src/const.ts +1 -0
- package/src/error.ts +23 -0
- package/src/helpers/blob.ts +62 -0
- package/src/helpers/cashu.ts +21 -0
- package/src/helpers/fetch.ts +16 -0
- package/src/helpers/index.ts +5 -0
- package/src/helpers/signal.ts +20 -0
- package/src/helpers/url.ts +16 -0
- package/src/image.ts +122 -0
- package/src/index.ts +9 -0
- package/src/nostr.ts +17 -0
- package/src/types.ts +63 -0
- package/lib/helpers/cachu.js +0 -6
- /package/lib/helpers/{cachu.d.ts → cashu.d.ts} +0 -0
|
@@ -0,0 +1,129 @@
|
|
|
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 auth event to use */
|
|
11
|
+
auth?: SignedEvent;
|
|
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 auth if its already set
|
|
45
|
+
if (opts?.auth) headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
|
|
46
|
+
|
|
47
|
+
// build check headers
|
|
48
|
+
const checkHeaders: Record<string, string> = {
|
|
49
|
+
...headers,
|
|
50
|
+
"X-Content-Length": String(getBlobSize(blob)),
|
|
51
|
+
};
|
|
52
|
+
const type = getBlobType(blob);
|
|
53
|
+
if (type) checkHeaders["X-Content-Type"] = type;
|
|
54
|
+
|
|
55
|
+
// check upload with HEAD /upload
|
|
56
|
+
let firstTry = await fetchWithTimeout(url, {
|
|
57
|
+
method: "HEAD",
|
|
58
|
+
signal: opts?.signal,
|
|
59
|
+
headers: checkHeaders,
|
|
60
|
+
timeout: opts?.timeout,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
let upload: Response | undefined = undefined;
|
|
64
|
+
|
|
65
|
+
if (firstTry.status === 404) {
|
|
66
|
+
// BUD-06 HEAD endpoint is not supported. attempt to upload
|
|
67
|
+
upload = firstTry = await fetchWithTimeout(url, {
|
|
68
|
+
body: blob,
|
|
69
|
+
method: "PUT",
|
|
70
|
+
signal: opts?.signal,
|
|
71
|
+
timeout: opts?.timeout,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// handle auth and payment
|
|
76
|
+
switch (firstTry.status) {
|
|
77
|
+
case 401: {
|
|
78
|
+
const auth = opts?.auth || (await opts?.onAuth?.(server, sha256, "upload", blob));
|
|
79
|
+
if (!auth) throw new Error("Missing auth handler");
|
|
80
|
+
|
|
81
|
+
// Try upload with auth
|
|
82
|
+
upload = await fetchWithTimeout(url, {
|
|
83
|
+
method: "PUT",
|
|
84
|
+
body: blob,
|
|
85
|
+
headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
|
|
86
|
+
signal: opts?.signal,
|
|
87
|
+
timeout: opts?.timeout,
|
|
88
|
+
});
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
case 402: {
|
|
92
|
+
if (!opts?.onPayment) throw new Error("Missing payment handler");
|
|
93
|
+
const { getEncodedToken } = await import("@cashu/cashu-ts");
|
|
94
|
+
const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
|
|
95
|
+
const request = getPaymentRequestFromHeaders(firstTry.headers);
|
|
96
|
+
|
|
97
|
+
const token = await opts.onPayment(server, sha256, blob, request);
|
|
98
|
+
const payment = getEncodedToken(token);
|
|
99
|
+
|
|
100
|
+
// Try upload with payment
|
|
101
|
+
upload = await fetchWithTimeout(url, {
|
|
102
|
+
method: "PUT",
|
|
103
|
+
body: blob,
|
|
104
|
+
headers: { ...headers, "X-Cashu": payment },
|
|
105
|
+
signal: opts?.signal,
|
|
106
|
+
timeout: opts?.timeout,
|
|
107
|
+
});
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (firstTry.status >= 500) throw new Error("Server error");
|
|
113
|
+
|
|
114
|
+
// check passed, upload
|
|
115
|
+
if (!upload)
|
|
116
|
+
upload = await fetchWithTimeout(url, {
|
|
117
|
+
method: "PUT",
|
|
118
|
+
body: blob,
|
|
119
|
+
headers: { ...headers },
|
|
120
|
+
signal: opts?.signal,
|
|
121
|
+
timeout: opts?.timeout,
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
// handle errors
|
|
125
|
+
await HTTPError.handleErrorResponse(upload);
|
|
126
|
+
|
|
127
|
+
// return blob descriptor
|
|
128
|
+
return upload.json();
|
|
129
|
+
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
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 doseAuthMatchUpload(auth: SignedEvent, server: ServerType, blob: string | UploadType) {
|
|
17
|
+
const type = auth.tags.find((t) => t[0] === "t")?.[1];
|
|
18
|
+
if (type !== "upload" && type !== "media") return false;
|
|
19
|
+
|
|
20
|
+
const sha256 = typeof blob === "string" ? blob : await getBlobSha256(blob);
|
|
21
|
+
|
|
22
|
+
for (const tag of auth.tags) {
|
|
23
|
+
switch (tag[0]) {
|
|
24
|
+
case "x":
|
|
25
|
+
if (tag[1] === sha256) return true;
|
|
26
|
+
break;
|
|
27
|
+
case "server":
|
|
28
|
+
if (areServersEqual(tag[1], server)) return true;
|
|
29
|
+
break;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function normalizeToHash(blob: string | UploadType) {
|
|
37
|
+
return typeof blob === "string" ? blob : getBlobSha256(blob);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type AuthType = "upload" | "list" | "delete" | "get" | "media";
|
|
41
|
+
export type AuthEventOptions = {
|
|
42
|
+
blobs?: string | string[] | UploadType | UploadType[];
|
|
43
|
+
servers?: string | string[];
|
|
44
|
+
message?: string;
|
|
45
|
+
expiration?: number;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** Generic auth event builder */
|
|
49
|
+
export async function createAuthEvent(signer: Signer, type: AuthType, options?: AuthEventOptions) {
|
|
50
|
+
const draft: EventTemplate = {
|
|
51
|
+
created_at: now(),
|
|
52
|
+
kind: AUTH_EVENT_KIND,
|
|
53
|
+
content: options?.message ?? "",
|
|
54
|
+
tags: [
|
|
55
|
+
["t", type],
|
|
56
|
+
// attach NIP-40 expiration
|
|
57
|
+
["expiration", String(options?.expiration ?? oneHour())],
|
|
58
|
+
],
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// add blob tags
|
|
62
|
+
if (options?.blobs) {
|
|
63
|
+
if (Array.isArray(options.blobs)) {
|
|
64
|
+
const seen = new Set<string>();
|
|
65
|
+
for (const blob of options.blobs) {
|
|
66
|
+
const hash = await normalizeToHash(blob);
|
|
67
|
+
if (!seen.has(hash)) {
|
|
68
|
+
draft.tags.push(["x", hash]);
|
|
69
|
+
seen.add(hash);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
} else draft.tags.push(["x", await normalizeToHash(options.blobs)]);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// add server tags
|
|
76
|
+
if (options?.servers) {
|
|
77
|
+
if (Array.isArray(options.servers))
|
|
78
|
+
for (const server of new Set(options.servers)) draft.tags.push(["server", server]);
|
|
79
|
+
else draft.tags.push(["server", options.servers]);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return await signer(draft);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export type DownloadAuthOptions = Omit<AuthEventOptions, "blobs" | "servers">;
|
|
86
|
+
/** Creates a GET auth event */
|
|
87
|
+
export async function createDownloadAuth(
|
|
88
|
+
signer: Signer,
|
|
89
|
+
serverOrHash: string | string[] | UploadType | UploadType[],
|
|
90
|
+
options?: DownloadAuthOptions,
|
|
91
|
+
) {
|
|
92
|
+
if (!Array.isArray(serverOrHash)) serverOrHash = [serverOrHash] as string[] | UploadType[];
|
|
93
|
+
|
|
94
|
+
return await createAuthEvent(signer, "get", {
|
|
95
|
+
message: "Download Blob",
|
|
96
|
+
...options,
|
|
97
|
+
blobs: serverOrHash.filter((s) => (typeof s === "string" ? isSha256(s) : true)) as string[] | UploadType[],
|
|
98
|
+
servers: serverOrHash.filter((s) => typeof s === "string" && !isSha256(s) && URL.canParse(s)) as string[],
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export type UploadAuthOptions = Omit<AuthEventOptions, "blobs"> & { type?: "upload" | "media" };
|
|
103
|
+
/** Creates an upload or media upload auth event */
|
|
104
|
+
export async function createUploadAuth(
|
|
105
|
+
signer: Signer,
|
|
106
|
+
blobs: string | string[] | UploadType | UploadType[],
|
|
107
|
+
options?: UploadAuthOptions,
|
|
108
|
+
) {
|
|
109
|
+
return await createAuthEvent(signer, options?.type ?? "upload", { message: "Upload Blob", ...options, blobs });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export type MirrorAuthOptions = Omit<AuthEventOptions, "blobs">;
|
|
113
|
+
/** Creates an upload or media upload auth event */
|
|
114
|
+
export async function createMirrorAuth(
|
|
115
|
+
signer: Signer,
|
|
116
|
+
blobs: string | string[] | UploadType | UploadType[],
|
|
117
|
+
options?: MirrorAuthOptions,
|
|
118
|
+
) {
|
|
119
|
+
// The /mirror endpoint uses "upload" type
|
|
120
|
+
return await createAuthEvent(signer, "upload", { message: "Mirror Blob", ...options, blobs });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export type ListAuthOptions = Omit<AuthEventOptions, "blobs">;
|
|
124
|
+
/** Creates a list auth event */
|
|
125
|
+
export async function createListAuth(signer: Signer, options?: ListAuthOptions) {
|
|
126
|
+
return await createAuthEvent(signer, "list", { message: "List Blobs", ...options });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export type DeleteAuthOptions = Omit<AuthEventOptions, "blobs">;
|
|
130
|
+
/** Creates a "delete" auth event for a specific hash */
|
|
131
|
+
export async function createDeleteAuth(
|
|
132
|
+
signer: Signer,
|
|
133
|
+
blobs: string | string[] | UploadType | UploadType[],
|
|
134
|
+
options?: DeleteAuthOptions,
|
|
135
|
+
) {
|
|
136
|
+
return await createAuthEvent(signer, "delete", { message: "Delete Blob", ...options, blobs });
|
|
137
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { getBlobSha256 } from "./helpers/blob.js";
|
|
2
|
+
import {
|
|
3
|
+
createDeleteAuth,
|
|
4
|
+
createDownloadAuth,
|
|
5
|
+
createListAuth,
|
|
6
|
+
createMirrorAuth,
|
|
7
|
+
createUploadAuth,
|
|
8
|
+
DeleteAuthOptions,
|
|
9
|
+
DownloadAuthOptions,
|
|
10
|
+
encodeAuthorizationHeader,
|
|
11
|
+
ListAuthOptions,
|
|
12
|
+
MirrorAuthOptions,
|
|
13
|
+
UploadAuthOptions,
|
|
14
|
+
} from "./auth.js";
|
|
15
|
+
import { BlobDescriptor, PaymentHandlers as PaymentHandler, SignedEvent, Signer } from "./types.js";
|
|
16
|
+
import { mirrorBlob, MirrorOptions } from "./actions/mirror.js";
|
|
17
|
+
import { uploadBlob, UploadOptions } from "./actions/upload.js";
|
|
18
|
+
import { listBlobs, ListOptions } from "./actions/list.js";
|
|
19
|
+
import { downloadBlob, DownloadOptions } from "./actions/download.js";
|
|
20
|
+
import { deleteBlob, DeleteOptions } from "./actions/delete.js";
|
|
21
|
+
import { uploadMedia, UploadMediaOptions } from "./actions/media.js";
|
|
22
|
+
|
|
23
|
+
export type ServerType = string | URL;
|
|
24
|
+
export type UploadType = Blob | File | Buffer;
|
|
25
|
+
|
|
26
|
+
export class BlossomClient {
|
|
27
|
+
server: URL;
|
|
28
|
+
signer?: Signer;
|
|
29
|
+
payment?: PaymentHandler<URL>;
|
|
30
|
+
|
|
31
|
+
constructor(server: string | URL, signer?: Signer) {
|
|
32
|
+
this.server = new URL("/", server);
|
|
33
|
+
this.signer = signer;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// moved to helpers.ts
|
|
37
|
+
static getFileSha256 = getBlobSha256;
|
|
38
|
+
|
|
39
|
+
// static auth methods moved to auth.ts
|
|
40
|
+
static createGetAuth = createDownloadAuth;
|
|
41
|
+
static createUploadAuth = createUploadAuth;
|
|
42
|
+
static createListAuth = createListAuth;
|
|
43
|
+
static createDeleteAuth = createDeleteAuth;
|
|
44
|
+
|
|
45
|
+
// util
|
|
46
|
+
static encodeAuthorizationHeader = encodeAuthorizationHeader;
|
|
47
|
+
|
|
48
|
+
// static blob methods moved to actions
|
|
49
|
+
static mirrorBlob = mirrorBlob;
|
|
50
|
+
static uploadBlob = uploadBlob;
|
|
51
|
+
static listBlobs = listBlobs;
|
|
52
|
+
static downloadBlob = downloadBlob;
|
|
53
|
+
static deleteBlob = deleteBlob;
|
|
54
|
+
static uploadMedia = uploadMedia;
|
|
55
|
+
|
|
56
|
+
// download blob
|
|
57
|
+
async createDownloadAuth(hash: string, options?: DownloadAuthOptions) {
|
|
58
|
+
if (!this.signer) throw new Error("Missing signer");
|
|
59
|
+
return await createDownloadAuth(this.signer, hash, options);
|
|
60
|
+
}
|
|
61
|
+
async downloadBlob(
|
|
62
|
+
hash: string,
|
|
63
|
+
opts?: Omit<DownloadOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
|
|
64
|
+
auth?: SignedEvent | boolean;
|
|
65
|
+
payment?: boolean;
|
|
66
|
+
},
|
|
67
|
+
) {
|
|
68
|
+
const options: DownloadOptions<URL> = { signal: opts?.signal };
|
|
69
|
+
|
|
70
|
+
// attach auth
|
|
71
|
+
if (opts?.auth !== false) {
|
|
72
|
+
if (this.signer)
|
|
73
|
+
options.onAuth = (_server, sha256) => this.createDownloadAuth(sha256, { message: `Download ${sha256}` });
|
|
74
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// attach payment
|
|
78
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.download;
|
|
79
|
+
|
|
80
|
+
const download = await downloadBlob(this.server, hash, options);
|
|
81
|
+
return download.blob();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// upload blob
|
|
85
|
+
async createUploadAuth(blob: string | UploadType, options?: UploadAuthOptions) {
|
|
86
|
+
if (!this.signer) throw new Error("Missing signer");
|
|
87
|
+
return await createUploadAuth(this.signer, blob, options);
|
|
88
|
+
}
|
|
89
|
+
async uploadBlob<B extends UploadType>(
|
|
90
|
+
blob: B,
|
|
91
|
+
opts?: Omit<UploadOptions<URL, B>, "onAuth" | "onPayment" | "auth"> & {
|
|
92
|
+
auth?: SignedEvent | boolean;
|
|
93
|
+
payment?: boolean;
|
|
94
|
+
},
|
|
95
|
+
) {
|
|
96
|
+
const options: UploadOptions<URL, B> = { signal: opts?.signal };
|
|
97
|
+
|
|
98
|
+
// attach auth
|
|
99
|
+
if (opts?.auth !== false) {
|
|
100
|
+
if (this.signer) options.onAuth = (_server, sha256, type) => this.createUploadAuth(sha256, { type });
|
|
101
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// attach payment
|
|
105
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.upload;
|
|
106
|
+
|
|
107
|
+
return uploadBlob(this.server, blob, options);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// mirror blob
|
|
111
|
+
async createMirrorAuth(blob: string | BlobDescriptor, options?: MirrorAuthOptions) {
|
|
112
|
+
if (!this.signer) throw new Error("Missing signer");
|
|
113
|
+
return await createMirrorAuth(this.signer, typeof blob === "string" ? blob : blob.sha256, options);
|
|
114
|
+
}
|
|
115
|
+
async mirrorBlob(
|
|
116
|
+
blob: BlobDescriptor,
|
|
117
|
+
opts?: Omit<MirrorOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
|
|
118
|
+
auth?: SignedEvent | boolean;
|
|
119
|
+
payment?: boolean;
|
|
120
|
+
},
|
|
121
|
+
) {
|
|
122
|
+
const options: MirrorOptions<URL> = { signal: opts?.signal };
|
|
123
|
+
|
|
124
|
+
// attach auth
|
|
125
|
+
if (opts?.auth !== false) {
|
|
126
|
+
if (this.signer) options.onAuth = (_server, sha256) => this.createMirrorAuth(sha256);
|
|
127
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// attach payment
|
|
131
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.mirror;
|
|
132
|
+
|
|
133
|
+
return mirrorBlob(this.server, blob, options);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// upload media
|
|
137
|
+
async createMediaAuth(blob: string | UploadType, options?: Omit<UploadAuthOptions, "type">) {
|
|
138
|
+
return await this.createUploadAuth(blob, { ...options, type: "media" });
|
|
139
|
+
}
|
|
140
|
+
async uploadMedia<B extends UploadType>(
|
|
141
|
+
blob: B,
|
|
142
|
+
opts?: Omit<UploadMediaOptions<URL, B>, "onAuth" | "onPayment" | "auth"> & {
|
|
143
|
+
auth?: SignedEvent | boolean;
|
|
144
|
+
payment?: boolean;
|
|
145
|
+
},
|
|
146
|
+
) {
|
|
147
|
+
const options: UploadMediaOptions<URL, B> = { signal: opts?.signal };
|
|
148
|
+
|
|
149
|
+
// attach auth
|
|
150
|
+
if (opts?.auth !== false) {
|
|
151
|
+
if (this.signer) options.onAuth = (_server, sha256, type) => this.createUploadAuth(sha256, { type });
|
|
152
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// attach payment
|
|
156
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.upload;
|
|
157
|
+
|
|
158
|
+
return uploadMedia(this.server, blob, options);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// has blob
|
|
162
|
+
static async hasBlob(server: ServerType, hash: string) {
|
|
163
|
+
const res = await fetch(new URL(`/` + hash, server), { method: "HEAD" });
|
|
164
|
+
return res.status !== 404;
|
|
165
|
+
}
|
|
166
|
+
async hasBlob(hash: string) {
|
|
167
|
+
return BlossomClient.hasBlob(this.server, hash);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// list blobs
|
|
171
|
+
async createListAuth(options?: ListAuthOptions) {
|
|
172
|
+
if (!this.signer) throw new Error("Missing signer");
|
|
173
|
+
return await createListAuth(this.signer, options);
|
|
174
|
+
}
|
|
175
|
+
async listBlobs(
|
|
176
|
+
pubkey: string,
|
|
177
|
+
opts?: Omit<ListOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
|
|
178
|
+
auth?: SignedEvent | boolean;
|
|
179
|
+
payment?: boolean;
|
|
180
|
+
},
|
|
181
|
+
) {
|
|
182
|
+
const options: ListOptions<URL> = { signal: opts?.signal };
|
|
183
|
+
|
|
184
|
+
// attach auth
|
|
185
|
+
if (opts?.auth !== false) {
|
|
186
|
+
if (this.signer) options.onAuth = (_server) => this.createListAuth();
|
|
187
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// attach payment
|
|
191
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.list;
|
|
192
|
+
|
|
193
|
+
return listBlobs(this.server, pubkey, options);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// delete blob
|
|
197
|
+
async createDeleteAuth(blob: string | UploadType, options?: DeleteAuthOptions) {
|
|
198
|
+
if (!this.signer) throw new Error("Missing signer");
|
|
199
|
+
return await createDeleteAuth(this.signer, blob, options);
|
|
200
|
+
}
|
|
201
|
+
async deleteBlob(
|
|
202
|
+
hash: string,
|
|
203
|
+
opts?: Omit<DeleteOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
|
|
204
|
+
auth?: SignedEvent | boolean;
|
|
205
|
+
payment?: boolean;
|
|
206
|
+
},
|
|
207
|
+
) {
|
|
208
|
+
const options: DeleteOptions<URL> = { signal: opts?.signal };
|
|
209
|
+
|
|
210
|
+
// attach auth
|
|
211
|
+
if (opts?.auth !== false) {
|
|
212
|
+
if (this.signer) options.onAuth = (_server, sha256) => this.createDeleteAuth(sha256);
|
|
213
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// attach payment
|
|
217
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.delete;
|
|
218
|
+
|
|
219
|
+
return BlossomClient.deleteBlob(this.server, hash, options);
|
|
220
|
+
}
|
|
221
|
+
}
|
package/src/const.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const AUTH_EVENT_KIND = 24242;
|
package/src/error.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export default class HTTPError extends Error {
|
|
2
|
+
response: Response;
|
|
3
|
+
status: number;
|
|
4
|
+
body?: { message: string };
|
|
5
|
+
|
|
6
|
+
constructor(response: Response, body: { message: string } | string) {
|
|
7
|
+
super(typeof body === "string" ? body : body.message);
|
|
8
|
+
this.response = response;
|
|
9
|
+
this.status = response.status;
|
|
10
|
+
|
|
11
|
+
if (typeof body == "object") this.body = body;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
static async handleErrorResponse(res: Response) {
|
|
15
|
+
if (!res.ok) {
|
|
16
|
+
try {
|
|
17
|
+
throw new HTTPError(res, res.headers.get("x-reason") || "Something went wrong");
|
|
18
|
+
} catch (e) {
|
|
19
|
+
throw e;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { bytesToHex } from "@noble/hashes/utils";
|
|
2
|
+
import { UploadType } from "../client.js";
|
|
3
|
+
|
|
4
|
+
/** Checks if a string is a 64 length hex string */
|
|
5
|
+
export function isSha256(str: string) {
|
|
6
|
+
return str.match(/^[0-9a-f]{64}$/);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** A symbol use to store the sha256 hash of a blob on a Blob instance */
|
|
10
|
+
export const BlobHashSymbol = Symbol.for("sha256");
|
|
11
|
+
|
|
12
|
+
/** gets or calculates the sha2456 of a Blob */
|
|
13
|
+
export function getBlobSha256(blob: UploadType) {
|
|
14
|
+
if (Reflect.has(blob, BlobHashSymbol)) return Reflect.get(blob, BlobHashSymbol) as string;
|
|
15
|
+
|
|
16
|
+
return computeBlobSha256(blob).then((hash) => {
|
|
17
|
+
Reflect.set(blob, BlobHashSymbol, hash);
|
|
18
|
+
return hash;
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Calculates the sha2456 of a Blob */
|
|
23
|
+
export async function computeBlobSha256(blob: UploadType) {
|
|
24
|
+
let buffer: ArrayBuffer | Buffer;
|
|
25
|
+
|
|
26
|
+
// NOTE: use typeof File !== "undefined" to check if File is supported (required to support node 18)
|
|
27
|
+
if ((typeof File !== "undefined" && blob instanceof File) || blob instanceof Blob) {
|
|
28
|
+
buffer = await blob.arrayBuffer();
|
|
29
|
+
} else {
|
|
30
|
+
// nodejs Buffer
|
|
31
|
+
buffer = blob;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
let hash: Uint8Array;
|
|
35
|
+
if (typeof crypto !== "undefined" && crypto.subtle) {
|
|
36
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
|
|
37
|
+
hash = new Uint8Array(hashBuffer);
|
|
38
|
+
} else {
|
|
39
|
+
const { sha256 } = await import("@noble/hashes/sha2");
|
|
40
|
+
hash = sha256.create().update(new Uint8Array(buffer)).digest();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return bytesToHex(hash);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Returns the size of the blob in bytes */
|
|
47
|
+
export function getBlobSize(blob: UploadType) {
|
|
48
|
+
if ((typeof File !== "undefined" && blob instanceof File) || blob instanceof Blob) {
|
|
49
|
+
return blob.size;
|
|
50
|
+
} else {
|
|
51
|
+
// nodejs Buffer
|
|
52
|
+
return blob.length;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Returns the mime type of the blob */
|
|
57
|
+
export function getBlobType(blob: UploadType) {
|
|
58
|
+
if ((typeof File !== "undefined" && blob instanceof File) || blob instanceof Blob) {
|
|
59
|
+
return blob.type;
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { decodePaymentRequest } from "@cashu/cashu-ts";
|
|
2
|
+
import { PaymentRequest } from "../types.js";
|
|
3
|
+
|
|
4
|
+
/** Extracts a cashu-ts PaymentRequest from Headers */
|
|
5
|
+
export function getPaymentRequestFromHeaders(headers: Headers): PaymentRequest;
|
|
6
|
+
export function getPaymentRequestFromHeaders(headers: Headers, quite: false): PaymentRequest;
|
|
7
|
+
export function getPaymentRequestFromHeaders(headers: Headers, quite: true): PaymentRequest | undefined;
|
|
8
|
+
export function getPaymentRequestFromHeaders(headers: Headers, quite = false) {
|
|
9
|
+
const header = headers.get("X-Cashu");
|
|
10
|
+
if (!header) {
|
|
11
|
+
if (!quite) throw new Error("Missing cashu header");
|
|
12
|
+
else return undefined;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const request = decodePaymentRequest(header);
|
|
16
|
+
|
|
17
|
+
// Clear the transport, since NUT-23 is only in-band payments
|
|
18
|
+
request.transport = [];
|
|
19
|
+
|
|
20
|
+
return request;
|
|
21
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { wrapSignalWithTimeout } from "./signal.js";
|
|
2
|
+
|
|
3
|
+
export type RequestInitWithTimeout = RequestInit & { timeout?: number; timeoutMessage?: string };
|
|
4
|
+
|
|
5
|
+
/** Make a fetch request with a timeout */
|
|
6
|
+
export function fetchWithTimeout(url: string | URL, init?: RequestInitWithTimeout): ReturnType<typeof fetch> {
|
|
7
|
+
if (init?.timeout) {
|
|
8
|
+
const { cancel, signal } = wrapSignalWithTimeout(
|
|
9
|
+
init.timeout,
|
|
10
|
+
init.timeoutMessage ?? "Timeout",
|
|
11
|
+
init.signal ?? undefined,
|
|
12
|
+
);
|
|
13
|
+
|
|
14
|
+
return fetch(url, { ...init, signal }).finally(cancel);
|
|
15
|
+
} else return fetch(url, init);
|
|
16
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export class TimeoutError extends Error {}
|
|
2
|
+
|
|
3
|
+
/** Creates and optionally wraps an AbortSignal with a timeout */
|
|
4
|
+
export function wrapSignalWithTimeout(
|
|
5
|
+
timeout: number,
|
|
6
|
+
message: string,
|
|
7
|
+
signal: AbortSignal | undefined,
|
|
8
|
+
): { cancel: () => void; signal: AbortSignal } {
|
|
9
|
+
const controller = new AbortController();
|
|
10
|
+
|
|
11
|
+
if (signal) signal.addEventListener("abort", (err) => controller.abort(err), { once: true });
|
|
12
|
+
|
|
13
|
+
const t = setTimeout(() => {
|
|
14
|
+
controller.abort(new TimeoutError(message));
|
|
15
|
+
}, timeout);
|
|
16
|
+
|
|
17
|
+
const cancel = () => clearTimeout(t);
|
|
18
|
+
|
|
19
|
+
return { cancel, signal: controller.signal };
|
|
20
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Check if two servers are the same */
|
|
2
|
+
export function areServersEqual(a: string | URL, b: string | URL) {
|
|
3
|
+
const hostnameA = a instanceof URL ? a.hostname : new URL(a).hostname;
|
|
4
|
+
const hostnameB = b instanceof URL ? b.hostname : new URL(b).hostname;
|
|
5
|
+
return hostnameA === hostnameB;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** returns the last sha256 in a URL */
|
|
9
|
+
export function getHashFromURL(url: string | URL) {
|
|
10
|
+
if (typeof url === "string") url = new URL(url);
|
|
11
|
+
|
|
12
|
+
const hashes = Array.from(url.pathname.matchAll(/[0-9a-f]{64}/gi));
|
|
13
|
+
if (hashes.length > 0) return hashes[hashes.length - 1][0];
|
|
14
|
+
|
|
15
|
+
return null;
|
|
16
|
+
}
|