@krizaka/storage 0.0.0-stage → 0.2.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 +201 -0
- package/README.md +23 -2
- package/dist/chunk-3E2PZNBG.js +343 -0
- package/dist/chunk-3E2PZNBG.js.map +1 -0
- package/dist/index.d.ts +83 -0
- package/dist/index.js +114 -0
- package/dist/index.js.map +1 -0
- package/dist/port-CUTAx9CD.d.ts +62 -0
- package/dist/settings.d.ts +68 -0
- package/dist/settings.js +80 -0
- package/dist/settings.js.map +1 -0
- package/dist/storage-7cUuR_Z5.d.ts +73 -0
- package/dist/testkit.d.ts +6 -0
- package/dist/testkit.js +44 -0
- package/dist/testkit.js.map +1 -0
- package/package.json +82 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @krizaka/storage
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Files behind one port for every Krizaka product. The port is named by what it does (`ObjectStore`), the provider is a value the admin chooses. No vendor SDK (plain HTTP through an injected `fetch`), no environment variable, no wall clock.
|
|
4
|
+
|
|
5
|
+
- **The port.** `put`, `get`, `head`, `delete`, `list(prefix)`, `signedUrl(key, ttl)` for a private zone, `publicUrl(key)` when a pull zone or CDN exists.
|
|
6
|
+
- **Adapters.** `remoteStore` (an HTTP zone with the shape of Bunny Storage: `AccessKey` header, `PUT`/`GET`/`DELETE`, a directory listed by its path with a trailing slash, a pull zone with token-signed links), `bucketStore` (any S3-compatible service: Signature V4, presigned GET, `ListObjectsV2`, no SDK), `folderStore` (a folder, for development, tests and the Mac apps; a key never leaves the root), `memoryObjectStore`. All run `objectStoreContract` (`@krizaka/storage/testkit`).
|
|
7
|
+
- **Rules every upload obeys** (`createStorage`): the size limit is passed in, the prefix must be declared in a `defineLayout` (an unknown prefix is refused), the bytes are checked by magic number (`sniffType`: png, jpeg, gif, webp, pdf, mp4, webm, svg), never by the extension, and a declared type that contradicts the bytes is refused. The stored name is content-hashed, `<name>.<sha10>.<ext>`, so a URL never changes content.
|
|
8
|
+
- **The admin chooses** (`@krizaka/storage/settings`): `storage.provider` (`local`, `http`, `s3`), `storage.maxMegabytes`, `storage.signedUrlSeconds`, and the non-secret coordinates (`endpoint`, `region`, `bucket`, `zone`, `prefix`, `pullHostname`, `publicBaseUrl`). Keys stay in the environment; `storeFromSettings` takes them as parameters and refuses a provider chosen without what it needs, instead of falling back to another. An admin-typed S3 endpoint goes through `checkEndpoint` (https only, no credentials, no local or private address).
|
|
9
|
+
- **Signatures.** SigV4 is checked against AWS's published vectors. The token form of the HTTP zone's signed links (SHA-256 of key + path + expires, URL-safe base64) is the one Yomizaka and Orochia run against Bunny's pull zones; Bunny's documentation publishes no expected output for it.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createStorage, defineLayout, folderStore } from "@krizaka/storage";
|
|
13
|
+
import { limitsOf, readStorageSettings, storeFromSettings } from "@krizaka/storage/settings";
|
|
14
|
+
|
|
15
|
+
const settings = await readStorageSettings((key) => service.get(key, ctx));
|
|
16
|
+
const storage = createStorage({
|
|
17
|
+
store: storeFromSettings(settings, { accessKeyId: env.MEDIA_STORAGE_ACCESS_KEY_ID, secretAccessKey: env.MEDIA_STORAGE_SECRET }, { fetch, clock }),
|
|
18
|
+
layout: defineLayout(["people/", "site/home/"]),
|
|
19
|
+
limits: () => readStorageSettings(read).then(limitsOf),
|
|
20
|
+
});
|
|
21
|
+
const { key, url } = await storage.upload({ prefix: "people/", name: "ana.jpg", bytes, allow: ["image/jpeg", "image/png"], declaredType: file.type });
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Apache-2.0.
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
// src/port.ts
|
|
2
|
+
var STORAGE_CODE = {
|
|
3
|
+
badKey: "STORAGE_BAD_KEY",
|
|
4
|
+
badPrefix: "STORAGE_BAD_PREFIX",
|
|
5
|
+
tooBig: "STORAGE_TOO_BIG",
|
|
6
|
+
badType: "STORAGE_BAD_TYPE",
|
|
7
|
+
typeMismatch: "STORAGE_TYPE_MISMATCH",
|
|
8
|
+
provider: "STORAGE_PROVIDER_FAILED",
|
|
9
|
+
badConfig: "STORAGE_BAD_CONFIG",
|
|
10
|
+
badEndpoint: "STORAGE_BAD_ENDPOINT"
|
|
11
|
+
};
|
|
12
|
+
var StorageError = class extends Error {
|
|
13
|
+
constructor(code, message) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.name = "StorageError";
|
|
17
|
+
}
|
|
18
|
+
code;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// src/keys.ts
|
|
22
|
+
import { createHash } from "crypto";
|
|
23
|
+
var MAX_KEY = 1024;
|
|
24
|
+
var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._ ()@+=,~-]*$/;
|
|
25
|
+
function trimSlashes(value, ends = "both") {
|
|
26
|
+
let start = 0;
|
|
27
|
+
let end = value.length;
|
|
28
|
+
if (ends === "both") while (start < end && value[start] === "/") start += 1;
|
|
29
|
+
while (end > start && value[end - 1] === "/") end -= 1;
|
|
30
|
+
return value.slice(start, end);
|
|
31
|
+
}
|
|
32
|
+
function assertKey(key) {
|
|
33
|
+
const bad = (why) => new StorageError(STORAGE_CODE.badKey, `${why}: \xAB ${key.slice(0, 80)} \xBB`);
|
|
34
|
+
if (typeof key !== "string" || key === "" || key.length > MAX_KEY) throw bad("a key is 1 to 1024 characters");
|
|
35
|
+
for (const segment of key.split("/")) {
|
|
36
|
+
if (segment === "." || segment === "..") throw bad("a key has no . or .. segment");
|
|
37
|
+
if (!SEGMENT.test(segment)) throw bad("a key segment is empty or has a character storage services refuse");
|
|
38
|
+
}
|
|
39
|
+
return key;
|
|
40
|
+
}
|
|
41
|
+
var hashOf = (bytes) => createHash("sha256").update(bytes).digest("hex").slice(0, 10);
|
|
42
|
+
function hashedName(name, bytes) {
|
|
43
|
+
const dot = name.lastIndexOf(".");
|
|
44
|
+
const base = dot > 0 ? name.slice(0, dot) : name;
|
|
45
|
+
const ext = dot > 0 ? name.slice(dot) : "";
|
|
46
|
+
return `${base}.${hashOf(bytes)}${ext}`;
|
|
47
|
+
}
|
|
48
|
+
function defineLayout(prefixes) {
|
|
49
|
+
for (const p of prefixes) if (!p.endsWith("/")) throw new StorageError(STORAGE_CODE.badPrefix, `layout prefix \xAB ${p} \xBB must end with a slash`);
|
|
50
|
+
const sorted = [...prefixes].sort((a, b) => b.length - a.length);
|
|
51
|
+
const prefixOf = (key) => sorted.find((p) => key.startsWith(p)) ?? null;
|
|
52
|
+
return {
|
|
53
|
+
prefixes,
|
|
54
|
+
prefixOf,
|
|
55
|
+
check(key) {
|
|
56
|
+
assertKey(key);
|
|
57
|
+
if (prefixOf(key) === null) throw new StorageError(STORAGE_CODE.badPrefix, `\xAB ${key.slice(0, 80)} \xBB is under no declared prefix`);
|
|
58
|
+
return key;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
var TYPES = {
|
|
63
|
+
png: "image/png",
|
|
64
|
+
jpg: "image/jpeg",
|
|
65
|
+
jpeg: "image/jpeg",
|
|
66
|
+
gif: "image/gif",
|
|
67
|
+
webp: "image/webp",
|
|
68
|
+
svg: "image/svg+xml",
|
|
69
|
+
pdf: "application/pdf",
|
|
70
|
+
mp4: "video/mp4",
|
|
71
|
+
webm: "video/webm",
|
|
72
|
+
json: "application/json",
|
|
73
|
+
txt: "text/plain",
|
|
74
|
+
vtt: "text/vtt"
|
|
75
|
+
};
|
|
76
|
+
var typeOfName = (key) => TYPES[key.split(".").pop()?.toLowerCase() ?? ""] ?? "application/octet-stream";
|
|
77
|
+
|
|
78
|
+
// src/request-signing.ts
|
|
79
|
+
import crypto from "crypto";
|
|
80
|
+
var sha256 = (data) => crypto.createHash("sha256").update(data).digest("hex");
|
|
81
|
+
var hmac = (key, data) => crypto.createHmac("sha256", key).update(data).digest();
|
|
82
|
+
var EMPTY_SHA256 = sha256("");
|
|
83
|
+
var hashPayload = (bytes) => sha256(bytes);
|
|
84
|
+
var stamp = (now) => now.toISOString().replace(/[:-]|\.\d{3}/g, "");
|
|
85
|
+
var encode = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
86
|
+
var canonicalPath = (url) => url.pathname.split("/").map((seg) => encode(decodeURIComponent(seg))).join("/") || "/";
|
|
87
|
+
var byNameThenValue = ([a, av], [b, bv]) => {
|
|
88
|
+
if (a === b) return av < bv ? -1 : 1;
|
|
89
|
+
return a < b ? -1 : 1;
|
|
90
|
+
};
|
|
91
|
+
var canonicalQuery = (url) => [...url.searchParams.entries()].map(([k, v]) => [encode(k), encode(v)]).sort(byNameThenValue).map(([k, v]) => `${k}=${v}`).join("&");
|
|
92
|
+
function signingKey(c, date) {
|
|
93
|
+
return hmac(hmac(hmac(hmac(`AWS4${c.secretAccessKey}`, date), c.region), c.service), "aws4_request");
|
|
94
|
+
}
|
|
95
|
+
function signature(c, method, url, headers, payloadHash, amzDate) {
|
|
96
|
+
const names = Object.keys(headers).map((h) => h.toLowerCase()).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
97
|
+
const lower = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v.trim().replace(/\s+/g, " ")]));
|
|
98
|
+
const canonical = [method, canonicalPath(url), canonicalQuery(url), names.map((n) => `${n}:${lower[n]}
|
|
99
|
+
`).join(""), names.join(";"), payloadHash].join("\n");
|
|
100
|
+
const scope = `${amzDate.slice(0, 8)}/${c.region}/${c.service}/aws4_request`;
|
|
101
|
+
const toSign = ["AWS4-HMAC-SHA256", amzDate, scope, sha256(canonical)].join("\n");
|
|
102
|
+
return { signed: names.join(";"), scope, value: crypto.createHmac("sha256", signingKey(c, amzDate.slice(0, 8))).update(toSign).digest("hex") };
|
|
103
|
+
}
|
|
104
|
+
function signRequest(c, req) {
|
|
105
|
+
const url = new URL(req.url);
|
|
106
|
+
const amzDate = stamp(req.now);
|
|
107
|
+
const extra = c.service === "s3" ? { "x-amz-content-sha256": req.payloadHash } : {};
|
|
108
|
+
const s = signature(c, req.method, url, { ...req.headers, host: url.host, "x-amz-date": amzDate, ...extra }, req.payloadHash, amzDate);
|
|
109
|
+
return { ...req.headers, "x-amz-date": amzDate, ...extra, authorization: `AWS4-HMAC-SHA256 Credential=${c.accessKeyId}/${s.scope}, SignedHeaders=${s.signed}, Signature=${s.value}` };
|
|
110
|
+
}
|
|
111
|
+
function presignGet(c, url, ttlSeconds, now) {
|
|
112
|
+
const u = new URL(url);
|
|
113
|
+
const amzDate = stamp(now);
|
|
114
|
+
u.searchParams.set("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
|
|
115
|
+
u.searchParams.set("X-Amz-Credential", `${c.accessKeyId}/${amzDate.slice(0, 8)}/${c.region}/${c.service}/aws4_request`);
|
|
116
|
+
u.searchParams.set("X-Amz-Date", amzDate);
|
|
117
|
+
u.searchParams.set("X-Amz-Expires", String(ttlSeconds));
|
|
118
|
+
u.searchParams.set("X-Amz-SignedHeaders", "host");
|
|
119
|
+
const s = signature(c, "GET", u, { host: u.host }, "UNSIGNED-PAYLOAD", amzDate);
|
|
120
|
+
u.searchParams.set("X-Amz-Signature", s.value);
|
|
121
|
+
return u.toString();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// src/bucket-store.ts
|
|
125
|
+
var fail = (what, status) => new StorageError(STORAGE_CODE.provider, `the bucket refused the ${what} (${status})`);
|
|
126
|
+
var unescapeXml = (s) => s.replaceAll("<", "<").replaceAll(">", ">").replaceAll(""", '"').replaceAll("'", "'").replaceAll("&", "&");
|
|
127
|
+
var tag = (xml, name) => new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(xml)?.[1];
|
|
128
|
+
function bucketStore(options) {
|
|
129
|
+
const creds = { accessKeyId: options.accessKeyId, secretAccessKey: options.secretAccessKey, region: options.region, service: "s3" };
|
|
130
|
+
const prefix = trimSlashes(options.prefix ?? "");
|
|
131
|
+
const inBucket = (key) => (prefix === "" ? "" : `${prefix}/`) + key;
|
|
132
|
+
const origin = trimSlashes(options.endpoint, "end");
|
|
133
|
+
const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/");
|
|
134
|
+
const urlOf = (key) => `${origin}/${options.bucket}/${encodePath(inBucket(assertKey(key)))}`;
|
|
135
|
+
const send = (method, url, body, extra = {}) => {
|
|
136
|
+
const headers = signRequest(creds, { method, url, headers: extra, payloadHash: hashPayload(body ?? new Uint8Array()), now: options.clock.now() });
|
|
137
|
+
return options.fetch(url, { method, headers, ...body ? { body } : {} });
|
|
138
|
+
};
|
|
139
|
+
const list = async (p) => {
|
|
140
|
+
const out = [];
|
|
141
|
+
let token;
|
|
142
|
+
do {
|
|
143
|
+
const q = new URL(`${origin}/${options.bucket}`);
|
|
144
|
+
q.searchParams.set("list-type", "2");
|
|
145
|
+
q.searchParams.set("prefix", inBucket(p));
|
|
146
|
+
if (token) q.searchParams.set("continuation-token", token);
|
|
147
|
+
const res = await send("GET", q.toString());
|
|
148
|
+
if (!res.ok) throw fail("listing", res.status);
|
|
149
|
+
const xml = await res.text();
|
|
150
|
+
for (const block of xml.split("<Contents>").slice(1)) {
|
|
151
|
+
const key = unescapeXml(tag(block, "Key") ?? "");
|
|
152
|
+
out.push({ key: prefix === "" ? key : key.slice(prefix.length + 1), size: Number(tag(block, "Size") ?? 0) });
|
|
153
|
+
}
|
|
154
|
+
token = tag(xml, "IsTruncated") === "true" ? unescapeXml(tag(xml, "NextContinuationToken") ?? "") || void 0 : void 0;
|
|
155
|
+
} while (token);
|
|
156
|
+
return out.sort((a, b) => a.key.localeCompare(b.key));
|
|
157
|
+
};
|
|
158
|
+
return {
|
|
159
|
+
async put(key, bytes, meta) {
|
|
160
|
+
const res = await send("PUT", urlOf(key), bytes, { "content-type": meta.contentType, ...options.serverSideEncryption ? { "x-amz-server-side-encryption": "AES256" } : {} });
|
|
161
|
+
if (!res.ok) throw fail("write", res.status);
|
|
162
|
+
},
|
|
163
|
+
async get(key) {
|
|
164
|
+
const res = await send("GET", urlOf(key));
|
|
165
|
+
if (res.status === 404) return null;
|
|
166
|
+
if (!res.ok) throw fail("read", res.status);
|
|
167
|
+
return { bytes: new Uint8Array(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? typeOfName(key) };
|
|
168
|
+
},
|
|
169
|
+
async head(key) {
|
|
170
|
+
const res = await send("HEAD", urlOf(key));
|
|
171
|
+
if (res.status === 404) return null;
|
|
172
|
+
if (!res.ok) throw fail("head", res.status);
|
|
173
|
+
return { key, size: Number(res.headers.get("content-length") ?? 0) };
|
|
174
|
+
},
|
|
175
|
+
async delete(key) {
|
|
176
|
+
const res = await send("DELETE", urlOf(key));
|
|
177
|
+
if (!res.ok && res.status !== 404) throw fail("delete", res.status);
|
|
178
|
+
},
|
|
179
|
+
list,
|
|
180
|
+
async signedUrl(key, ttlSeconds) {
|
|
181
|
+
return presignGet(creds, urlOf(key), ttlSeconds, options.clock.now());
|
|
182
|
+
},
|
|
183
|
+
publicUrl: (key) => options.publicBaseUrl ? `${trimSlashes(options.publicBaseUrl, "end")}/${assertKey(key)}` : null
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// src/endpoint.ts
|
|
188
|
+
var PRIVATE_V4 = [/^10\./, /^127\./, /^169\.254\./, /^172\.(1[6-9]|2\d|3[01])\./, /^192\.168\./, /^0\./];
|
|
189
|
+
function checkEndpoint(endpoint, options = {}) {
|
|
190
|
+
const bad = (why) => new StorageError(STORAGE_CODE.badEndpoint, `endpoint ${why}`);
|
|
191
|
+
let url;
|
|
192
|
+
try {
|
|
193
|
+
url = new URL(endpoint);
|
|
194
|
+
} catch {
|
|
195
|
+
throw bad("is not a URL");
|
|
196
|
+
}
|
|
197
|
+
if (url.username !== "" || url.password !== "") throw bad("must not carry credentials");
|
|
198
|
+
if (options.allowLocal) return url.origin;
|
|
199
|
+
if (url.protocol !== "https:") throw bad("must be https");
|
|
200
|
+
const host = url.hostname.toLowerCase();
|
|
201
|
+
if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".internal") || host.endsWith(".local")) throw bad("must not be a local name");
|
|
202
|
+
if (PRIVATE_V4.some((re) => re.test(host))) throw bad("must not be a private address");
|
|
203
|
+
if (host.startsWith("[") && (host === "[::1]" || host.startsWith("[fc") || host.startsWith("[fd") || host.startsWith("[fe80") || host.startsWith("[::ffff:"))) throw bad("must not be a private address");
|
|
204
|
+
return url.origin;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// src/folder-store.ts
|
|
208
|
+
import { mkdir, readdir, readFile, rm, stat, writeFile } from "fs/promises";
|
|
209
|
+
import { dirname, join, resolve, sep } from "path";
|
|
210
|
+
function folderStore(options) {
|
|
211
|
+
const root = resolve(options.root);
|
|
212
|
+
const pathOf = (key) => {
|
|
213
|
+
const path = resolve(join(root, assertKey(key)));
|
|
214
|
+
if (!path.startsWith(root + sep)) throw new Error("a key cannot leave the root");
|
|
215
|
+
return path;
|
|
216
|
+
};
|
|
217
|
+
const walk = async (dir, base) => {
|
|
218
|
+
let entries;
|
|
219
|
+
try {
|
|
220
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
221
|
+
} catch {
|
|
222
|
+
return [];
|
|
223
|
+
}
|
|
224
|
+
const out = [];
|
|
225
|
+
for (const entry of entries) {
|
|
226
|
+
const key = base === "" ? entry.name : `${base}/${entry.name}`;
|
|
227
|
+
if (entry.isDirectory()) out.push(...await walk(join(dir, entry.name), key));
|
|
228
|
+
else out.push({ key, size: (await stat(join(dir, entry.name))).size });
|
|
229
|
+
}
|
|
230
|
+
return out;
|
|
231
|
+
};
|
|
232
|
+
return {
|
|
233
|
+
async put(key, bytes) {
|
|
234
|
+
const path = pathOf(key);
|
|
235
|
+
await mkdir(dirname(path), { recursive: true });
|
|
236
|
+
await writeFile(path, bytes);
|
|
237
|
+
},
|
|
238
|
+
async get(key) {
|
|
239
|
+
try {
|
|
240
|
+
return { bytes: new Uint8Array(await readFile(pathOf(key))), contentType: typeOfName(key) };
|
|
241
|
+
} catch (error) {
|
|
242
|
+
if (error.code === "ENOENT" || error.code === "EISDIR") return null;
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
async head(key) {
|
|
247
|
+
try {
|
|
248
|
+
const s = await stat(pathOf(key));
|
|
249
|
+
return s.isFile() ? { key, size: s.size } : null;
|
|
250
|
+
} catch (error) {
|
|
251
|
+
if (error.code === "ENOENT") return null;
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
async delete(key) {
|
|
256
|
+
await rm(pathOf(key), { force: true });
|
|
257
|
+
},
|
|
258
|
+
async list(prefix) {
|
|
259
|
+
const slash = prefix.lastIndexOf("/");
|
|
260
|
+
const dir = slash < 0 ? "" : prefix.slice(0, slash);
|
|
261
|
+
const found = await walk(dir === "" ? root : join(root, dir), dir);
|
|
262
|
+
return found.filter((f) => f.key.startsWith(prefix)).sort((a, b) => a.key.localeCompare(b.key));
|
|
263
|
+
},
|
|
264
|
+
async signedUrl() {
|
|
265
|
+
return null;
|
|
266
|
+
},
|
|
267
|
+
publicUrl: (key) => options.publicBaseUrl ? `${trimSlashes(options.publicBaseUrl, "end")}/${assertKey(key)}` : null
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// src/remote-store.ts
|
|
272
|
+
import { createHash as createHash2 } from "crypto";
|
|
273
|
+
var fail2 = (what, status) => new StorageError(STORAGE_CODE.provider, `the storage refused the ${what} (${status})`);
|
|
274
|
+
function remoteStore(options) {
|
|
275
|
+
const prefix = trimSlashes(options.prefix ?? "");
|
|
276
|
+
const inZone = (key) => (prefix === "" ? "" : `${prefix}/`) + key;
|
|
277
|
+
const base = `https://${options.endpoint}/${options.zone}`;
|
|
278
|
+
const headers = { AccessKey: options.accessKey };
|
|
279
|
+
const url = (key) => `${base}/${inZone(assertKey(key))}`;
|
|
280
|
+
const listDir = async (dir) => {
|
|
281
|
+
const root = prefix === "" ? "" : `${prefix}/`;
|
|
282
|
+
const res = await options.fetch(dir === "" ? `${base}/${root}` : `${base}/${inZone(dir)}/`, { method: "GET", headers });
|
|
283
|
+
if (res.status === 404) return [];
|
|
284
|
+
if (!res.ok) throw fail2("listing", res.status);
|
|
285
|
+
const entries = JSON.parse(await res.text());
|
|
286
|
+
const out = [];
|
|
287
|
+
for (const e of entries) {
|
|
288
|
+
const key = dir === "" ? e.ObjectName : `${dir}/${e.ObjectName}`;
|
|
289
|
+
if (e.IsDirectory) out.push(...await listDir(key));
|
|
290
|
+
else out.push({ key, size: e.Length ?? 0 });
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
};
|
|
294
|
+
const list = async (p) => {
|
|
295
|
+
const slash = p.lastIndexOf("/");
|
|
296
|
+
return (await listDir(slash < 0 ? "" : p.slice(0, slash))).filter((f) => f.key.startsWith(p)).sort((a, b) => a.key.localeCompare(b.key));
|
|
297
|
+
};
|
|
298
|
+
return {
|
|
299
|
+
async put(key, bytes, meta) {
|
|
300
|
+
const res = await options.fetch(url(key), { method: "PUT", headers: { ...headers, "content-type": meta.contentType }, body: bytes });
|
|
301
|
+
if (!res.ok) throw fail2("write", res.status);
|
|
302
|
+
},
|
|
303
|
+
async get(key) {
|
|
304
|
+
const res = await options.fetch(url(key), { method: "GET", headers });
|
|
305
|
+
if (res.status === 404) return null;
|
|
306
|
+
if (!res.ok) throw fail2("read", res.status);
|
|
307
|
+
return { bytes: new Uint8Array(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? typeOfName(key) };
|
|
308
|
+
},
|
|
309
|
+
async head(key) {
|
|
310
|
+
assertKey(key);
|
|
311
|
+
return (await list(key)).find((f) => f.key === key) ?? null;
|
|
312
|
+
},
|
|
313
|
+
async delete(key) {
|
|
314
|
+
const res = await options.fetch(url(key), { method: "DELETE", headers });
|
|
315
|
+
if (!res.ok && res.status !== 404) throw fail2("delete", res.status);
|
|
316
|
+
},
|
|
317
|
+
list,
|
|
318
|
+
async signedUrl(key, ttlSeconds) {
|
|
319
|
+
if (!options.pullHostname || !options.tokenKey) return null;
|
|
320
|
+
const path = `/${inZone(assertKey(key))}`;
|
|
321
|
+
const expires = Math.floor(options.clock.now().valueOf() / 1e3) + ttlSeconds;
|
|
322
|
+
const token = createHash2("sha256").update(`${options.tokenKey}${path}${expires}`).digest("base64").replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
|
|
323
|
+
return `https://${options.pullHostname}${path}?token=${token}&expires=${expires}`;
|
|
324
|
+
},
|
|
325
|
+
publicUrl: (key) => options.pullHostname ? `https://${options.pullHostname}/${inZone(assertKey(key))}` : null
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export {
|
|
330
|
+
STORAGE_CODE,
|
|
331
|
+
StorageError,
|
|
332
|
+
trimSlashes,
|
|
333
|
+
assertKey,
|
|
334
|
+
hashOf,
|
|
335
|
+
hashedName,
|
|
336
|
+
defineLayout,
|
|
337
|
+
typeOfName,
|
|
338
|
+
bucketStore,
|
|
339
|
+
checkEndpoint,
|
|
340
|
+
folderStore,
|
|
341
|
+
remoteStore
|
|
342
|
+
};
|
|
343
|
+
//# sourceMappingURL=chunk-3E2PZNBG.js.map
|