@tansy/storage-bunny 0.0.0-stage → 0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Salah
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @tansy/storage-bunny
4
+
5
+ Bunny Storage for tansy file storage.
6
+
7
+ ```bash
8
+ npm install @tansy/storage-bunny
9
+ ```
10
+
11
+ Add it to `tansy.config.ts`. See [the storage guide](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/guides/storage.md) for what it adds and the options it takes.
12
+
13
+ A first-party plugin for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
package/index.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { type StorageAdapter, type ThumbnailOptions } from "tansy/storage";
2
+ /** Each Bunny Storage region's API host. */
3
+ declare const REGIONS: {
4
+ readonly de: "storage.bunnycdn.com";
5
+ readonly uk: "uk.storage.bunnycdn.com";
6
+ readonly se: "se.storage.bunnycdn.com";
7
+ readonly ny: "ny.storage.bunnycdn.com";
8
+ readonly la: "la.storage.bunnycdn.com";
9
+ readonly sg: "sg.storage.bunnycdn.com";
10
+ readonly syd: "syd.storage.bunnycdn.com";
11
+ readonly br: "br.storage.bunnycdn.com";
12
+ readonly jh: "jh.storage.bunnycdn.com";
13
+ };
14
+ export interface BunnyStorageOptions {
15
+ storageZone: string;
16
+ /** The storage zone's password, under FTP & API Access. Not the account's API key. */
17
+ accessKey: string;
18
+ /** The storage zone's main region. Defaults to "de" (Falkenstein). */
19
+ region?: keyof typeof REGIONS;
20
+ /**
21
+ * A pull zone serving this storage zone, with Bunny Optimizer and token authentication
22
+ * turned on. Bunny then makes thumbnails, and browsers fetch them from it directly.
23
+ * Without it, core makes and stores thumbnails itself.
24
+ */
25
+ cdn?: {
26
+ /** Such as https://example.b-cdn.net. Add it to `csp.img` in tansy.config.ts. */
27
+ url: string;
28
+ /** The pull zone's URL token authentication key, under Security → Token Authentication. */
29
+ tokenKey: string;
30
+ };
31
+ /** A folder holding every key, to keep several sites in one zone. */
32
+ prefix?: string;
33
+ /** Needed only when two zones are in use at once, such as during a move. */
34
+ name?: string;
35
+ }
36
+ /**
37
+ * Signs a pull zone URL with token authentication: an HMAC-SHA256 of the path, the expiry
38
+ * and the sorted query parameters, so Bunny refuses it after `expires` or with any change.
39
+ */
40
+ export declare function signBunnyUrl(url: URL, tokenKey: string, expires: number): string;
41
+ /**
42
+ * Bunny Optimizer's resize parameters. A ratio crops to it from the centre. `quality` makes
43
+ * Bunny treat the file as an image although its key has no extension.
44
+ */
45
+ export declare function bunnyResize({ width, height, fit }: Pick<ThumbnailOptions, "width" | "height" | "fit">): Record<string, string>;
46
+ /**
47
+ * Bunny Storage, through its Edge Storage API. The storage API needs the zone's
48
+ * password for every read, so files are served by the CMS after its access checks.
49
+ * With `cdn`, thumbnails go to Bunny Optimizer through short-lived signed URLs.
50
+ */
51
+ export declare function bunnyStorage(options: BunnyStorageOptions, fetcher?: typeof fetch): StorageAdapter;
52
+ export {};
package/index.js ADDED
@@ -0,0 +1,119 @@
1
+ import { createHmac } from "node:crypto";
2
+ import { callProvider, rangeOf } from "tansy/storage";
3
+ /** Each Bunny Storage region's API host. */
4
+ const REGIONS = {
5
+ de: "storage.bunnycdn.com",
6
+ uk: "uk.storage.bunnycdn.com",
7
+ se: "se.storage.bunnycdn.com",
8
+ ny: "ny.storage.bunnycdn.com",
9
+ la: "la.storage.bunnycdn.com",
10
+ sg: "sg.storage.bunnycdn.com",
11
+ syd: "syd.storage.bunnycdn.com",
12
+ br: "br.storage.bunnycdn.com",
13
+ jh: "jh.storage.bunnycdn.com",
14
+ };
15
+ const PROVIDER = "Bunny Storage";
16
+ const ZONE = /^[A-Za-z0-9-]{1,64}$/;
17
+ const encodeKey = (key) => key.split("/").map(encodeURIComponent).join("/");
18
+ /**
19
+ * Signs a pull zone URL with token authentication: an HMAC-SHA256 of the path, the expiry
20
+ * and the sorted query parameters, so Bunny refuses it after `expires` or with any change.
21
+ */
22
+ export function signBunnyUrl(url, tokenKey, expires) {
23
+ const params = [...url.searchParams].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
24
+ const signing = params.map(([key, value]) => `${key}=${value}`).join("&");
25
+ const token = createHmac("sha256", tokenKey).update(url.pathname).update(String(expires)).update(signing).digest("base64url");
26
+ const query = params.map(([key, value]) => `&${key}=${encodeURIComponent(value)}`).join("");
27
+ return `${url.origin}${url.pathname}?token=HS256-${token}${query}&expires=${expires}`;
28
+ }
29
+ /**
30
+ * Bunny Optimizer's resize parameters. A ratio crops to it from the centre. `quality` makes
31
+ * Bunny treat the file as an image although its key has no extension.
32
+ */
33
+ export function bunnyResize({ width, height, fit }) {
34
+ return { width: String(width), ...(fit === "cover" && height ? { aspect_ratio: `${width}:${height}` } : {}), quality: "80" };
35
+ }
36
+ /**
37
+ * Bunny Storage, through its Edge Storage API. The storage API needs the zone's
38
+ * password for every read, so files are served by the CMS after its access checks.
39
+ * With `cdn`, thumbnails go to Bunny Optimizer through short-lived signed URLs.
40
+ */
41
+ export function bunnyStorage(options, fetcher = fetch) {
42
+ const { storageZone, accessKey, region = "de", cdn, prefix = "", name = "bunny" } = options;
43
+ const keyPrefix = prefix ? `${prefix.replace(/^\/+|\/+$/g, "")}/` : "";
44
+ const zoneUrl = (path) => `https://${REGIONS[region]}/${storageZone}/${encodeKey(keyPrefix + path)}`;
45
+ const call = (action, url, init) => callProvider(PROVIDER, action, url, { ...init, headers: { ...init?.headers, accesskey: accessKey } }, fetcher);
46
+ /** Every file below a folder of the zone, as zone paths. */
47
+ const walk = async (folder, found) => {
48
+ const response = await call("list", `https://${REGIONS[region]}/${storageZone}/${encodeKey(folder)}`, { headers: { accept: "application/json" }, allow: [404] });
49
+ if (response.status === 404) {
50
+ await response.body?.cancel();
51
+ return;
52
+ }
53
+ const entries = (await response.json());
54
+ for (const { ObjectName: object, IsDirectory: directory, Length: length } of Array.isArray(entries) ? entries : []) {
55
+ if (typeof object !== "string" || !object || object.includes("/"))
56
+ continue;
57
+ if (directory === true)
58
+ await walk(`${folder}${object}/`, found);
59
+ else
60
+ found.push({ key: folder + object, size: Number(length) || 0 });
61
+ }
62
+ };
63
+ const adapter = {
64
+ name,
65
+ assertUsable() {
66
+ if (!ZONE.test(storageZone ?? ""))
67
+ throw new Error("Bunny Storage needs the storage zone's name: letters, digits and -.");
68
+ if (!accessKey)
69
+ throw new Error("Bunny Storage needs the storage zone's password.");
70
+ if (!(region in REGIONS))
71
+ throw new Error(`Bunny Storage's region must be one of ${Object.keys(REGIONS).join(", ")}.`);
72
+ if (cdn) {
73
+ const url = new URL(cdn.url);
74
+ if (url.protocol !== "https:" || url.pathname !== "/" || url.search || url.username || url.password)
75
+ throw new Error("Bunny's CDN url must be an https origin, such as https://example.b-cdn.net.");
76
+ if (!cdn.tokenKey)
77
+ throw new Error("Bunny's CDN needs its token authentication key, or anyone could read files from it.");
78
+ }
79
+ },
80
+ async put(key, body, { size }) {
81
+ const response = await call("upload", zoneUrl(key), {
82
+ method: "PUT",
83
+ // Bunny serves a stored file with the type its name suggests, and these keys have none.
84
+ headers: { "content-type": "application/octet-stream", "content-length": String(size) },
85
+ body,
86
+ });
87
+ await response.body?.cancel();
88
+ },
89
+ async get(key, range) {
90
+ const response = await call("read", zoneUrl(key), { headers: range ? { range: `bytes=${range.start}-${range.end}` } : {}, allow: [404] });
91
+ if (response.status === 404 || !response.body) {
92
+ await response.body?.cancel();
93
+ return null;
94
+ }
95
+ return rangeOf(response, range);
96
+ },
97
+ async delete(key) {
98
+ const response = await call("delete", zoneUrl(key), { method: "DELETE", allow: [404] });
99
+ await response.body?.cancel();
100
+ },
101
+ async list(listPrefix) {
102
+ const full = keyPrefix + listPrefix;
103
+ const found = [];
104
+ // Bunny lists one folder at a time, so the walk starts at the prefix's folder.
105
+ await walk(full.slice(0, full.lastIndexOf("/") + 1), found);
106
+ return found.filter(({ key }) => key.startsWith(full)).map(({ key, size }) => ({ key: key.slice(keyPrefix.length), size }));
107
+ },
108
+ };
109
+ if (cdn) {
110
+ adapter.thumbnailUrl = async (key, thumbnail) => {
111
+ const url = new URL(`${new URL(cdn.url).origin}/${encodeKey(keyPrefix + key)}`);
112
+ for (const [param, value] of Object.entries(bunnyResize(thumbnail)))
113
+ url.searchParams.set(param, value);
114
+ return signBunnyUrl(url, cdn.tokenKey, Math.floor(Date.now() / 1000) + thumbnail.expiresIn);
115
+ };
116
+ Object.assign(adapter, { thumbnailUrlsExpire: true });
117
+ }
118
+ return adapter;
119
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@tansy/storage-bunny",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Bunny Storage for tansy file storage.",
5
+ "keywords": [
6
+ "tansy",
7
+ "tansy-storage-adapter"
8
+ ],
9
+ "license": "MIT",
10
+ "author": "Mohamed Salah <mohamedsalahsebai@gmail.com>",
11
+ "homepage": "https://github.com/mhmdsalahsebai/tansy",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/mhmdsalahsebai/tansy.git",
15
+ "directory": "plugins/storage-bunny"
16
+ },
17
+ "bugs": "https://github.com/mhmdsalahsebai/tansy/issues",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./index.d.ts",
21
+ "default": "./index.js"
22
+ }
23
+ },
24
+ "peerDependencies": {
25
+ "tansy": "^0.1.0"
26
+ }
27
+ }