blossom-client-sdk 0.7.0 → 0.9.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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # blossom-client-sdk
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 1a5342b: Add mirror blob methods
8
+ - 24f4e57: add "x" or "server" tag on get auth
9
+
10
+ ## 0.8.0
11
+
12
+ ### Minor Changes
13
+
14
+ - Add `handleBrokenImages` method for repairing any broken images in an app
15
+
3
16
  ## 0.7.0
4
17
 
5
18
  ### Minor Changes
package/README.md CHANGED
@@ -194,3 +194,28 @@ for (let server of servers) {
194
194
  await BlossomClient.uploadBlob(server, file, auth);
195
195
  }
196
196
  ```
197
+
198
+ ### Upload and Mirror
199
+
200
+ ```js
201
+ import { BlossomClient } from "blossom-client-sdk";
202
+
203
+ async function signer(event) {
204
+ return await window.nostr.signEvent(event);
205
+ }
206
+
207
+ const mainServer = "https://cdn.server-a.com";
208
+ const mirrorServers = ["https://cdn.example.com", "https://cdn.other.com"];
209
+ const file = new File(["testing"], "test.txt");
210
+
211
+ const auth = await BlossomClient.getUploadAuth(file, signer, "Upload test.txt");
212
+
213
+ // first upload blob to main server
214
+ const blob = await BlossomClient.uploadBlob(mainServer, file, auth);
215
+
216
+ // then tell mirror servers to download it
217
+ for (let server of mirrorServers) {
218
+ // reuse the same auth for mirroring
219
+ await BlossomClient.mirrorBlob(server, blob.url, auth);
220
+ }
221
+ ```
package/lib/client.d.ts CHANGED
@@ -39,30 +39,34 @@ export declare class BlossomClient {
39
39
  signer?: Signer;
40
40
  constructor(server: string | URL, signer?: Signer);
41
41
  static getFileSha256(file: UploadType): Promise<string>;
42
- static getGetAuth(signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
43
- static getUploadAuth(file: UploadType, signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
44
- static getDeleteAuth(hash: string, signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
45
- static getListAuth(signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
46
- getGetAuth(message?: string, expiration?: number): Promise<SignedEvent>;
47
- getUploadAuth(file: UploadType, message?: string, expiration?: number): Promise<SignedEvent>;
48
- getDeleteAuth(hash: string, message?: string, expiration?: number): Promise<SignedEvent>;
49
- getListAuth(message?: string, expiration?: number): Promise<SignedEvent>;
50
42
  static encodeAuthorizationHeader(event: SignedEvent): string;
43
+ static getGetAuth(signer: Signer, message: string, serverOrHash: string, expiration?: number): Promise<SignedEvent>;
51
44
  static getBlob(server: ServerType, hash: string, auth?: SignedEvent): Promise<Blob>;
52
- getBlob(hash: string, auth?: SignedEvent | boolean): Promise<Blob>;
53
- static hasBlob(server: ServerType, hash: string): Promise<boolean>;
54
- hasBlob(hash: string): Promise<boolean>;
45
+ static createUploadAuth(sha256: string, signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
46
+ static getUploadAuth(file: UploadType, signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
47
+ static uploadBlob(server: ServerType, file: UploadType, auth?: SignedEvent): Promise<BlobDescriptor>;
48
+ static mirrorBlob(server: ServerType, url: string | URL, auth?: SignedEvent): Promise<BlobDescriptor>;
49
+ static getListAuth(signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
55
50
  static listBlobs(server: ServerType, pubkey: string, opts?: {
56
51
  since?: number;
57
52
  until?: number;
58
53
  }, auth?: SignedEvent): Promise<BlobDescriptor[]>;
54
+ static getDeleteAuth(hash: string, signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
55
+ static deleteBlob(server: ServerType, hash: string, auth?: SignedEvent): Promise<string>;
56
+ getGetAuth(message: string, serverOrHash: string, expiration?: number): Promise<SignedEvent>;
57
+ getBlob(hash: string, auth?: SignedEvent | boolean): Promise<Blob>;
58
+ getUploadAuth(file: UploadType, message?: string, expiration?: number): Promise<SignedEvent>;
59
+ uploadBlob(file: File, auth?: SignedEvent | boolean): Promise<BlobDescriptor>;
60
+ getMirrorAuth(sha256: string, message?: string, expiration?: number): Promise<SignedEvent>;
61
+ mirrorBlob(sha256: string, url: string | URL, auth?: SignedEvent | boolean): Promise<BlobDescriptor>;
62
+ static hasBlob(server: ServerType, hash: string): Promise<boolean>;
63
+ hasBlob(hash: string): Promise<boolean>;
64
+ getListAuth(message?: string, expiration?: number): Promise<SignedEvent>;
59
65
  listBlobs(pubkey: string, opts?: {
60
66
  since?: number;
61
67
  until?: number;
62
68
  }, auth?: SignedEvent | boolean): Promise<BlobDescriptor[]>;
63
- static deleteBlob(server: ServerType, hash: string, auth?: SignedEvent): Promise<string>;
69
+ getDeleteAuth(hash: string, message?: string, expiration?: number): Promise<SignedEvent>;
64
70
  deleteBlob(hash: string, auth?: SignedEvent | boolean): Promise<string>;
65
- static uploadBlob(server: ServerType, file: UploadType, auth?: SignedEvent): Promise<BlobDescriptor>;
66
- uploadBlob(file: File, auth?: SignedEvent | boolean): Promise<BlobDescriptor>;
67
71
  }
68
72
  export {};
package/lib/client.js CHANGED
@@ -42,25 +42,35 @@ export class BlossomClient {
42
42
  }
43
43
  return bytesToHex(hash);
44
44
  }
45
- static async getGetAuth(signer, message = "Get Blobs", expiration = oneHour()) {
45
+ static encodeAuthorizationHeader(event) {
46
+ return "Nostr " + btoa(JSON.stringify(event));
47
+ }
48
+ // static get blob
49
+ static async getGetAuth(signer, message, serverOrHash, expiration = oneHour()) {
50
+ let scopeTag;
51
+ if (serverOrHash.match(/^[0-9a-f]{64}$/)) {
52
+ scopeTag = ["x", serverOrHash];
53
+ }
54
+ else
55
+ scopeTag = ["server", new URL("/", serverOrHash).toString()];
46
56
  return await signer({
47
57
  created_at: now(),
48
58
  kind: AUTH_EVENT_KIND,
49
59
  content: message,
50
- tags: [
51
- ["t", "get"],
52
- ["expiration", String(expiration)],
53
- ],
60
+ tags: [["t", "get"], ["expiration", String(expiration)], scopeTag],
54
61
  });
55
62
  }
56
- static async getUploadAuth(file, signer, message = "Upload Blob", expiration = oneHour()) {
57
- const sha256 = await BlossomClient.getFileSha256(file);
58
- // add tags
63
+ static async getBlob(server, hash, auth) {
64
+ const res = await fetch(new URL(hash, server), {
65
+ headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
66
+ });
67
+ await HTTPError.handleErrorResponse(res);
68
+ return await res.blob();
69
+ }
70
+ // static upload blob
71
+ static async createUploadAuth(sha256, signer, message = "Upload Blob", expiration = oneHour()) {
59
72
  const tags = [];
60
73
  tags.push(["t", "upload"]);
61
- if (file instanceof File)
62
- tags.push(["name", file.name]);
63
- tags.push(["size", String(file.size)]);
64
74
  tags.push(["x", sha256]);
65
75
  tags.push(["expiration", String(expiration)]);
66
76
  return await signer({
@@ -70,64 +80,108 @@ export class BlossomClient {
70
80
  tags,
71
81
  });
72
82
  }
73
- static async getDeleteAuth(hash, signer, message = "Delete Blob", expiration = oneHour()) {
83
+ static async getUploadAuth(file, signer, message = "Upload Blob", expiration = oneHour()) {
84
+ const sha256 = await BlossomClient.getFileSha256(file);
85
+ return await BlossomClient.createUploadAuth(sha256, signer, message, expiration);
86
+ }
87
+ static async uploadBlob(server, file, auth) {
88
+ const res = await fetch(new URL("/upload", server), {
89
+ method: "PUT",
90
+ body: file,
91
+ headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
92
+ });
93
+ await HTTPError.handleErrorResponse(res);
94
+ return (await res.json());
95
+ }
96
+ // static mirror blob
97
+ static async mirrorBlob(server, url, auth) {
98
+ const res = await fetch(new URL("/mirror", server), {
99
+ method: "PUT",
100
+ body: JSON.stringify({ url: url.toString() }),
101
+ headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
102
+ });
103
+ await HTTPError.handleErrorResponse(res);
104
+ return (await res.json());
105
+ }
106
+ // static list blobs
107
+ static async getListAuth(signer, message = "List Blobs", expiration = oneHour()) {
74
108
  return await signer({
75
109
  created_at: now(),
76
110
  kind: AUTH_EVENT_KIND,
77
111
  content: message,
78
112
  tags: [
79
- ["t", "delete"],
80
- ["x", hash],
113
+ ["t", "list"],
81
114
  ["expiration", String(expiration)],
82
115
  ],
83
116
  });
84
117
  }
85
- static async getListAuth(signer, message = "List Blobs", expiration = oneHour()) {
118
+ static async listBlobs(server, pubkey, opts, auth) {
119
+ const url = new URL(`/list/` + pubkey, server);
120
+ if (opts?.since)
121
+ url.searchParams.append("since", String(opts.since));
122
+ if (opts?.until)
123
+ url.searchParams.append("until", String(opts.until));
124
+ const res = await fetch(url, {
125
+ headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
126
+ });
127
+ await HTTPError.handleErrorResponse(res);
128
+ return (await res.json());
129
+ }
130
+ // static delete blob
131
+ static async getDeleteAuth(hash, signer, message = "Delete Blob", expiration = oneHour()) {
86
132
  return await signer({
87
133
  created_at: now(),
88
134
  kind: AUTH_EVENT_KIND,
89
135
  content: message,
90
136
  tags: [
91
- ["t", "list"],
137
+ ["t", "delete"],
138
+ ["x", hash],
92
139
  ["expiration", String(expiration)],
93
140
  ],
94
141
  });
95
142
  }
96
- async getGetAuth(message, expiration) {
143
+ static async deleteBlob(server, hash, auth) {
144
+ const res = await fetch(new URL("/" + hash, server), {
145
+ method: "DELETE",
146
+ headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
147
+ });
148
+ await HTTPError.handleErrorResponse(res);
149
+ return await res.text();
150
+ }
151
+ // get blob
152
+ async getGetAuth(message, serverOrHash, expiration) {
97
153
  if (!this.signer)
98
154
  throw new Error("Missing signer");
99
- return await BlossomClient.getGetAuth(this.signer, message, expiration);
155
+ return await BlossomClient.getGetAuth(this.signer, message, serverOrHash, expiration);
156
+ }
157
+ async getBlob(hash, auth = false) {
158
+ if (typeof auth === "boolean" && auth)
159
+ auth = await this.getGetAuth("Get Blob", hash);
160
+ return BlossomClient.getBlob(this.server, hash, auth ? auth : undefined);
100
161
  }
162
+ // upload blob
101
163
  async getUploadAuth(file, message, expiration) {
102
164
  if (!this.signer)
103
165
  throw new Error("Missing signer");
104
166
  return await BlossomClient.getUploadAuth(file, this.signer, message, expiration);
105
167
  }
106
- async getDeleteAuth(hash, message, expiration) {
107
- if (!this.signer)
108
- throw new Error("Missing signer");
109
- return await BlossomClient.getDeleteAuth(hash, this.signer, message, expiration);
168
+ async uploadBlob(file, auth = true) {
169
+ if (typeof auth === "boolean" && auth)
170
+ auth = await this.getUploadAuth(file);
171
+ return BlossomClient.uploadBlob(this.server, file, auth ? auth : undefined);
110
172
  }
111
- async getListAuth(message, expiration) {
173
+ // mirror blob
174
+ async getMirrorAuth(sha256, message, expiration) {
112
175
  if (!this.signer)
113
176
  throw new Error("Missing signer");
114
- return await BlossomClient.getListAuth(this.signer, message, expiration);
177
+ return await BlossomClient.createUploadAuth(sha256, this.signer, message, expiration);
115
178
  }
116
- static encodeAuthorizationHeader(event) {
117
- return "Nostr " + btoa(JSON.stringify(event));
118
- }
119
- static async getBlob(server, hash, auth) {
120
- const res = await fetch(new URL(hash, server), {
121
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
122
- });
123
- await HTTPError.handleErrorResponse(res);
124
- return await res.blob();
125
- }
126
- async getBlob(hash, auth = false) {
179
+ async mirrorBlob(sha256, url, auth = true) {
127
180
  if (typeof auth === "boolean" && auth)
128
- auth = await this.getGetAuth();
129
- return BlossomClient.getBlob(this.server, hash, auth ? auth : undefined);
181
+ auth = await this.getMirrorAuth(sha256);
182
+ return BlossomClient.mirrorBlob(this.server, url, auth ? auth : undefined);
130
183
  }
184
+ // has blob
131
185
  static async hasBlob(server, hash) {
132
186
  const res = await fetch(new URL(`/` + hash, server), { method: "HEAD" });
133
187
  await HTTPError.handleErrorResponse(res);
@@ -136,48 +190,26 @@ export class BlossomClient {
136
190
  async hasBlob(hash) {
137
191
  return BlossomClient.hasBlob(this.server, hash);
138
192
  }
139
- static async listBlobs(server, pubkey, opts, auth) {
140
- const url = new URL(`/list/` + pubkey, server);
141
- if (opts?.since)
142
- url.searchParams.append("since", String(opts.since));
143
- if (opts?.until)
144
- url.searchParams.append("until", String(opts.until));
145
- const res = await fetch(url, {
146
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
147
- });
148
- await HTTPError.handleErrorResponse(res);
149
- return (await res.json());
193
+ // list blobs
194
+ async getListAuth(message, expiration) {
195
+ if (!this.signer)
196
+ throw new Error("Missing signer");
197
+ return await BlossomClient.getListAuth(this.signer, message, expiration);
150
198
  }
151
199
  async listBlobs(pubkey, opts, auth = false) {
152
200
  if (typeof auth === "boolean" && auth)
153
201
  auth = await this.getListAuth();
154
202
  return BlossomClient.listBlobs(this.server, pubkey, opts, auth ? auth : undefined);
155
203
  }
156
- static async deleteBlob(server, hash, auth) {
157
- const res = await fetch(new URL("/" + hash, server), {
158
- method: "DELETE",
159
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
160
- });
161
- await HTTPError.handleErrorResponse(res);
162
- return await res.text();
204
+ // delete blob
205
+ async getDeleteAuth(hash, message, expiration) {
206
+ if (!this.signer)
207
+ throw new Error("Missing signer");
208
+ return await BlossomClient.getDeleteAuth(hash, this.signer, message, expiration);
163
209
  }
164
210
  async deleteBlob(hash, auth = true) {
165
211
  if (typeof auth === "boolean" && auth)
166
212
  auth = await this.getDeleteAuth(hash);
167
213
  return BlossomClient.deleteBlob(this.server, hash, auth ? auth : undefined);
168
214
  }
169
- static async uploadBlob(server, file, auth) {
170
- const res = await fetch(new URL("/upload", server), {
171
- method: "PUT",
172
- body: file,
173
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
174
- });
175
- await HTTPError.handleErrorResponse(res);
176
- return (await res.json());
177
- }
178
- async uploadBlob(file, auth = true) {
179
- if (typeof auth === "boolean" && auth)
180
- auth = await this.getUploadAuth(file);
181
- return BlossomClient.uploadBlob(this.server, file, auth ? auth : undefined);
182
- }
183
215
  }
package/lib/image.d.ts CHANGED
@@ -1,7 +1,17 @@
1
+ type GetServersMethod = (pubkey?: string) => Promise<(string | URL)[] | undefined> | undefined;
1
2
  /**
2
3
  * attaches an "error" event listener to a HTMLImageElement element to handle server fallbacks
3
4
  * @param image The image element
4
5
  * @param getServers A async method to get an ordered list of servers for a pubkey
5
- * @param pubkey An optional pubkey to set the `data-pubkey` attr on the image
6
+ * @param overridePubkey An optional pubkey to set the `data-pubkey` attr on the image
7
+ * @returns returns a method to remove the "error" event listener
6
8
  */
7
- export declare function handleImageFallbacks(image: HTMLImageElement, getServers: (pubkey?: string) => Promise<(string | URL)[] | undefined> | undefined, pubkey?: string): void;
9
+ export declare function handleImageFallbacks(image: HTMLImageElement, getServers: GetServersMethod, overridePubkey?: string): () => void;
10
+ /**
11
+ * Watch for any broken <img> elements in the tree and attempt to fix them
12
+ * @param root The root element to observe
13
+ * @param getServers A method used to get a list of servers for a specific pubkey
14
+ * @returns A MutationObserver that is observing the root element
15
+ */
16
+ export declare function handleBrokenImages(root: HTMLElement, getServers: GetServersMethod): MutationObserver;
17
+ export {};
package/lib/image.js CHANGED
@@ -3,22 +3,34 @@ import { getHashFromURL } from "./helpers.js";
3
3
  * attaches an "error" event listener to a HTMLImageElement element to handle server fallbacks
4
4
  * @param image The image element
5
5
  * @param getServers A async method to get an ordered list of servers for a pubkey
6
- * @param pubkey An optional pubkey to set the `data-pubkey` attr on the image
6
+ * @param overridePubkey An optional pubkey to set the `data-pubkey` attr on the image
7
+ * @returns returns a method to remove the "error" event listener
7
8
  */
8
- export function handleImageFallbacks(image, getServers, pubkey) {
9
- const original = new URL(image.src);
10
- const hash = getHashFromURL(original);
11
- if (!hash)
12
- return;
13
- if (pubkey)
14
- image.dataset.pubkey = pubkey;
15
- let tried = [original.hostname];
9
+ export function handleImageFallbacks(image, getServers, overridePubkey) {
10
+ let tried = [];
16
11
  let servers = undefined;
17
12
  const onError = async () => {
13
+ const hash = getHashFromURL(image.src);
14
+ if (!hash)
15
+ return;
18
16
  const url = new URL(image.src);
19
17
  const ext = url.pathname.match(/\.\w+$/i);
18
+ tried.push(url.hostname);
19
+ let pubkey = overridePubkey;
20
+ // walk up the tree looking for pubkey
21
+ let el = image;
22
+ while (!pubkey && el.parentElement) {
23
+ if (el.dataset.pubkey)
24
+ pubkey = el.dataset.pubkey;
25
+ else
26
+ el = el.parentElement;
27
+ }
28
+ if (!pubkey) {
29
+ console.warn("Failed to find pubkey for broken image", image);
30
+ return;
31
+ }
20
32
  if (!servers)
21
- servers = (await getServers(image.dataset.pubkey))?.map((s) => (s instanceof URL ? s : new URL(s)));
33
+ servers = (await getServers(pubkey))?.map((s) => (s instanceof URL ? s : new URL(s)));
22
34
  if (servers) {
23
35
  const server = servers.find((s) => !tried.includes(s.hostname));
24
36
  if (server) {
@@ -26,7 +38,6 @@ export function handleImageFallbacks(image, getServers, pubkey) {
26
38
  url.pathname = "/" + hash + ext;
27
39
  url.protocol = server.protocol;
28
40
  image.src = url.toString();
29
- tried.push(url.hostname);
30
41
  }
31
42
  else {
32
43
  // ran out of servers, stop listening for errors
@@ -35,4 +46,48 @@ export function handleImageFallbacks(image, getServers, pubkey) {
35
46
  }
36
47
  };
37
48
  image.addEventListener("error", onError);
49
+ return () => image.removeEventListener("error", onError);
50
+ }
51
+ /**
52
+ * Watch for any broken <img> elements in the tree and attempt to fix them
53
+ * @param root The root element to observe
54
+ * @param getServers A method used to get a list of servers for a specific pubkey
55
+ * @returns A MutationObserver that is observing the root element
56
+ */
57
+ export function handleBrokenImages(root, getServers) {
58
+ const listeners = new WeakMap();
59
+ const observer = new MutationObserver((changes) => {
60
+ for (const change of changes) {
61
+ if (change.type === "childList") {
62
+ // add "error" event handles to any new <img/> elements
63
+ change.addedNodes.forEach((el) => {
64
+ if (el instanceof HTMLImageElement && !listeners.has(el)) {
65
+ const listener = handleImageFallbacks(el, getServers);
66
+ listeners.set(el, listener);
67
+ }
68
+ });
69
+ // cleanup removed nodes
70
+ change.removedNodes.forEach((el) => {
71
+ if (el instanceof HTMLImageElement) {
72
+ const listener = listeners.get(el);
73
+ if (listener) {
74
+ listener();
75
+ listeners.delete(el);
76
+ }
77
+ }
78
+ });
79
+ }
80
+ }
81
+ });
82
+ // start watching root
83
+ observer.observe(root, { subtree: true, childList: true });
84
+ // find all existing images and attach error handler
85
+ const images = root.querySelectorAll("img[src]");
86
+ images.forEach((image) => {
87
+ if (image instanceof HTMLImageElement) {
88
+ const listener = handleImageFallbacks(image, getServers);
89
+ listeners.set(image, listener);
90
+ }
91
+ });
92
+ return observer;
38
93
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blossom-client-sdk",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "A simple client for manage blobs on blossom servers",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",