@boldare/askdare-s3 0.0.0-placeholder
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 +21 -0
- package/README.md +188 -0
- package/dist/index.d.ts +59 -0
- package/dist/index.js +448 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Boldare S.A.
|
|
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
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# @boldare/askdare-s3
|
|
2
|
+
|
|
3
|
+
A file store for [`@boldare/askdare`](https://www.npmjs.com/package/@boldare/askdare): visitors' attachments in your own private bucket on AWS S3, Cloudflare R2 or MinIO, instead of OpenAI Files.
|
|
4
|
+
|
|
5
|
+
**[askdare website and docs](https://askdare.vercel.app)** · [GitHub](https://github.com/boldare/askdare/tree/main/packages/askdare-s3)
|
|
6
|
+
|
|
7
|
+
By default askdare uploads visitors' images and PDFs to OpenAI Files, which keeps them until they are deleted and isn't eligible for Zero Data Retention. With a file store, askdare keeps the bytes in your bucket and sends them inline with each model request, so nothing stays at OpenAI ([ADR-0037](https://github.com/boldare/askdare/blob/main/docs/adr/0037-file-store.md)). It needs a conversation store that replays, such as `postgresConversations()` from `@boldare/askdare-postgres`.
|
|
8
|
+
|
|
9
|
+
The add-on speaks the S3 API over `fetch` with its own small SigV4 signer. It has no dependencies; no AWS SDK.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install @boldare/askdare-s3
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Use
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
// app/api/chat/[...path]/route.ts
|
|
21
|
+
import { createChatHandler } from '@boldare/askdare/next';
|
|
22
|
+
import { postgresConversations } from '@boldare/askdare-postgres';
|
|
23
|
+
import { s3Files } from '@boldare/askdare-s3';
|
|
24
|
+
import { bots } from '../../../../askdare.config';
|
|
25
|
+
|
|
26
|
+
export const maxDuration = 300;
|
|
27
|
+
|
|
28
|
+
export const { GET, POST, DELETE } = createChatHandler({
|
|
29
|
+
bots,
|
|
30
|
+
conversations: postgresConversations(),
|
|
31
|
+
files: {
|
|
32
|
+
store: s3Files({
|
|
33
|
+
bucket: process.env.S3_BUCKET ?? '',
|
|
34
|
+
region: process.env.S3_REGION,
|
|
35
|
+
credentials: {
|
|
36
|
+
accessKeyId: process.env.S3_ACCESS_KEY_ID ?? '',
|
|
37
|
+
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY ?? '',
|
|
38
|
+
},
|
|
39
|
+
}),
|
|
40
|
+
retentionDays: 30,
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Then check it with `npx @boldare/askdare doctor`: it writes, reads, lists and deletes one test file, and names the S3 error code and what to do if a step fails.
|
|
46
|
+
|
|
47
|
+
## Options
|
|
48
|
+
|
|
49
|
+
| Option | Default | What it does |
|
|
50
|
+
| --- | --- | --- |
|
|
51
|
+
| `bucket` | required | The bucket's name. It must exist; the add-on never creates or configures it. |
|
|
52
|
+
| `credentials` | required | `{ accessKeyId, secretAccessKey, sessionToken? }`, or a function that resolves them before each request ([IAM roles](#iam-roles-and-temporary-credentials)). |
|
|
53
|
+
| `region` | `us-east-1` | The bucket's region; every request is signed for it. `auto` on R2. |
|
|
54
|
+
| `endpoint` | AWS S3 in `region` | The S3 API's origin, with no path. R2: `https://<account ID>.r2.cloudflarestorage.com`. MinIO: its URL, such as `http://localhost:9000`. |
|
|
55
|
+
| `forcePathStyle` | `false` | `<endpoint>/<bucket>/<key>` URLs instead of `<bucket>.<endpoint host>/<key>`. MinIO usually needs `true`, and so do an endpoint on `localhost` or an IP address and a bucket name with dots over https. |
|
|
56
|
+
| `prefix` | `askdare-files/` | Put before every object key. Not empty; letters, digits, `.`, `_`, `-` and `/`. |
|
|
57
|
+
|
|
58
|
+
Every request has a 30-second timeout, and stops sooner when askdare aborts it (the visitor left, the turn timed out).
|
|
59
|
+
|
|
60
|
+
## What is stored, and what isn't
|
|
61
|
+
|
|
62
|
+
- **One object per file**, under `<prefix><id>`. The ID is 128 random bits (22 characters of letters, digits, `_` and `-`), chosen by the store: the key names no bot, visitor, conversation or file.
|
|
63
|
+
- **The bytes** in the object, **the type** in its `Content-Type`, and **the visitor's file name** in its metadata (`x-amz-meta-name`, percent-encoded, since S3 metadata is ASCII). The name is visible to anyone who can read the bucket's metadata, as the bytes are.
|
|
64
|
+
- **No public access:** askdare never builds a URL to an object or hands one to the browser. The bucket stays private, and it can sit on a network OpenAI can't reach.
|
|
65
|
+
- **Deletion:** a conversation's files are deleted with it (`DELETE <basePath>/conversation`, the admin console, `sweep()`), and `sweep()` also deletes every file older than `files.retentionDays`. It deletes only keys of askdare's shape directly under the prefix, never other objects, but give askdare a prefix of its own anyway.
|
|
66
|
+
- **Nothing in logs:** the add-on logs nothing. Its errors carry the operation, the HTTP status, S3's error code and request ID only: never a key, a file name, bytes or credentials.
|
|
67
|
+
|
|
68
|
+
## Set up the bucket
|
|
69
|
+
|
|
70
|
+
Whatever the provider, the bucket needs:
|
|
71
|
+
1. **No public access.**
|
|
72
|
+
2. **Server-side encryption** on.
|
|
73
|
+
3. **A lifecycle rule** that deletes objects under the prefix after the same number of days as `files.retentionDays`, as a backstop if `sweep()` stops running.
|
|
74
|
+
4. **No versioning**, or a lifecycle rule that also expires noncurrent versions: with versioning, a delete only hides a file, and its bytes stay.
|
|
75
|
+
5. **Credentials allowed four calls only:** `PutObject`, `GetObject` and `DeleteObject` (which `DeleteObjects` uses) on the prefix, and `ListBucket` on the bucket for that prefix.
|
|
76
|
+
|
|
77
|
+
### AWS S3
|
|
78
|
+
|
|
79
|
+
1. Create the bucket in your region. New buckets block public access and encrypt every object with SSE-S3 by default; keep both, or pick SSE-KMS with your own key (then also allow `kms:GenerateDataKey` and `kms:Decrypt` on it).
|
|
80
|
+
2. Add the lifecycle rule (Management → Create lifecycle rule): filter by the prefix `askdare-files/`, "Expire current versions of objects" after 30 days. S3 runs lifecycle rules once a day, so objects can live up to a day longer.
|
|
81
|
+
3. Create an IAM user or role for the app, with this policy (replace the bucket name and prefix):
|
|
82
|
+
|
|
83
|
+
```json
|
|
84
|
+
{
|
|
85
|
+
"Version": "2012-10-17",
|
|
86
|
+
"Statement": [
|
|
87
|
+
{
|
|
88
|
+
"Sid": "AskdareFiles",
|
|
89
|
+
"Effect": "Allow",
|
|
90
|
+
"Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject"],
|
|
91
|
+
"Resource": "arn:aws:s3:::acme-askdare/askdare-files/*"
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
"Sid": "AskdareSweep",
|
|
95
|
+
"Effect": "Allow",
|
|
96
|
+
"Action": "s3:ListBucket",
|
|
97
|
+
"Resource": "arn:aws:s3:::acme-askdare",
|
|
98
|
+
"Condition": { "StringLike": { "s3:prefix": ["askdare-files/*"] } }
|
|
99
|
+
}
|
|
100
|
+
]
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`s3:ListBucket` is what `sweep()` needs, and without it S3 answers a deleted file with `AccessDenied` rather than "not found", which would break a conversation whose file has expired. `doctor` checks both.
|
|
105
|
+
4. Pass `bucket`, `region` and the credentials. On Vercel, set them as environment variables (the secret as Sensitive).
|
|
106
|
+
|
|
107
|
+
### Cloudflare R2
|
|
108
|
+
|
|
109
|
+
1. Create the bucket (R2 → Create bucket). R2 buckets are private unless you connect a public domain or turn on the r2.dev URL: do neither. R2 encrypts every object at rest.
|
|
110
|
+
2. Add the lifecycle rule (the bucket's Settings → Object lifecycle rules): prefix `askdare-files/`, delete objects after 30 days.
|
|
111
|
+
3. Create an API token (R2 → Manage API tokens) with **Object Read & Write**, limited to this bucket. Use its access key ID and secret access key.
|
|
112
|
+
4. Configure:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
s3Files({
|
|
116
|
+
bucket: 'acme-askdare',
|
|
117
|
+
endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
|
|
118
|
+
region: 'auto',
|
|
119
|
+
credentials: {
|
|
120
|
+
accessKeyId: process.env.R2_ACCESS_KEY_ID ?? '',
|
|
121
|
+
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY ?? '',
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
For a bucket with a jurisdiction (such as the EU), the endpoint is `https://<account ID>.eu.r2.cloudflarestorage.com`.
|
|
127
|
+
|
|
128
|
+
### MinIO
|
|
129
|
+
|
|
130
|
+
MinIO uses path-style URLs:
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
s3Files({
|
|
134
|
+
bucket: 'askdare',
|
|
135
|
+
endpoint: 'https://minio.internal.example.com',
|
|
136
|
+
forcePathStyle: true,
|
|
137
|
+
credentials: {
|
|
138
|
+
accessKeyId: process.env.MINIO_ACCESS_KEY ?? '',
|
|
139
|
+
secretAccessKey: process.env.MINIO_SECRET_KEY ?? '',
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
With the MinIO client (`mc`), for an alias `local`:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
mc mb local/askdare
|
|
148
|
+
mc encrypt set sse-s3 local/askdare # needs a KMS configured on the server
|
|
149
|
+
mc ilm rule add --prefix askdare-files/ --expire-days 30 local/askdare
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Then create a user with a policy like the AWS one above (`arn:aws:s3:::askdare/askdare-files/*`), and use its keys, not the root user's. Use `https` for anything but a local test server: over `http`, the requests are signed, but the files travel unencrypted.
|
|
153
|
+
|
|
154
|
+
### IAM roles and temporary credentials
|
|
155
|
+
|
|
156
|
+
`credentials` can be a function. askdare calls it before each request, so it can hand out credentials that rotate, such as an IAM role's on AWS (ECS, EKS, Lambda, EC2). The AWS SDK's providers fit and cache by themselves:
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
|
|
160
|
+
|
|
161
|
+
s3Files({ bucket: 'acme-askdare', region: 'eu-central-1', credentials: fromNodeProviderChain() });
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
The add-on doesn't depend on the AWS SDK; install `@aws-sdk/credential-providers` yourself if you use it. A function you write should cache its result and refresh it before it expires, since it runs on every request.
|
|
165
|
+
|
|
166
|
+
## Tests
|
|
167
|
+
|
|
168
|
+
The add-on passes `fileStoreContract` from `@boldare/askdare/testing`: in CI against MinIO, and before each release against AWS S3 and R2. Running your own S3-compatible server? Run the same suite against it, with a bucket or prefix of its own:
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
import { s3Files } from '@boldare/askdare-s3';
|
|
172
|
+
import { fileStoreContract } from '@boldare/askdare/testing';
|
|
173
|
+
import { describe, expect, it } from 'vitest';
|
|
174
|
+
|
|
175
|
+
fileStoreContract('my S3', () => s3Files({ /* … */, prefix: `test/${crypto.randomUUID()}/` }), {
|
|
176
|
+
describe,
|
|
177
|
+
it,
|
|
178
|
+
expect,
|
|
179
|
+
timeoutMs: 30_000,
|
|
180
|
+
});
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
To run this package's own tests against MinIO, start it with the `docker-compose.yml` in this folder (port 54390) and set `ASKDARE_S3_TEST_ENDPOINT`:
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
docker compose -f packages/askdare-s3/docker-compose.yml up -d --wait
|
|
187
|
+
ASKDARE_S3_TEST_ENDPOINT=http://127.0.0.1:54390 pnpm test packages/askdare-s3
|
|
188
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { FileStore } from "@boldare/askdare";
|
|
2
|
+
/** Keys for the bucket: an access key and its secret, and a session token for temporary ones. */
|
|
3
|
+
interface S3Credentials {
|
|
4
|
+
readonly accessKeyId: string;
|
|
5
|
+
readonly secretAccessKey: string;
|
|
6
|
+
/** For temporary credentials, such as an IAM role's. */
|
|
7
|
+
readonly sessionToken?: string | undefined;
|
|
8
|
+
}
|
|
9
|
+
/** Credentials, or a function that resolves them before each request, such as the AWS SDK's providers. */
|
|
10
|
+
type S3CredentialsInput = S3Credentials | (() => S3Credentials | Promise<S3Credentials>);
|
|
11
|
+
interface S3FilesOptions {
|
|
12
|
+
/** The bucket's name. It must exist and stay private; askdare never creates or configures it. */
|
|
13
|
+
readonly bucket: string;
|
|
14
|
+
/**
|
|
15
|
+
* Put before every object key: keys are `<prefix><id>`. Default `askdare-files/`. Not empty;
|
|
16
|
+
* letters, digits, `.`, `_`, `-` and `/`. `sweep` deletes only keys of this shape directly under
|
|
17
|
+
* it, so give askdare a prefix of its own.
|
|
18
|
+
*/
|
|
19
|
+
readonly prefix?: string | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* The S3 API's origin. Default AWS S3 in `region`. For Cloudflare R2,
|
|
22
|
+
* `https://<account ID>.r2.cloudflarestorage.com`; for MinIO, its URL, such as
|
|
23
|
+
* `http://localhost:9000`.
|
|
24
|
+
*/
|
|
25
|
+
readonly endpoint?: string | undefined;
|
|
26
|
+
/** The bucket's region, which signs every request. Default `us-east-1`; `auto` on R2. */
|
|
27
|
+
readonly region?: string | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* An access key and its secret, or a function that resolves them before each request, such as
|
|
30
|
+
* an AWS SDK credential provider for an IAM role. Keep them in environment variables.
|
|
31
|
+
*/
|
|
32
|
+
readonly credentials: S3CredentialsInput;
|
|
33
|
+
/**
|
|
34
|
+
* Path-style URLs (`<endpoint>/<bucket>/<key>`) instead of virtual-hosted ones
|
|
35
|
+
* (`<bucket>.<endpoint host>/<key>`). Default false; MinIO usually needs true.
|
|
36
|
+
*/
|
|
37
|
+
readonly forcePathStyle?: boolean | undefined;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Visitors' attachments in your own S3 bucket (ADR-0037): AWS S3, Cloudflare R2, MinIO or another
|
|
41
|
+
* S3-compatible server. Bytes go in the object, the type in its `Content-Type` and the name in its
|
|
42
|
+
* metadata. Turn on the bucket's server-side encryption and add a lifecycle rule as old as
|
|
43
|
+
* `files.retentionDays`; the README shows both and a least-privilege policy.
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* import { s3Files } from '@boldare/askdare-s3';
|
|
47
|
+
*
|
|
48
|
+
* const files = s3Files({
|
|
49
|
+
* bucket: 'acme-askdare',
|
|
50
|
+
* region: 'eu-central-1',
|
|
51
|
+
* credentials: {
|
|
52
|
+
* accessKeyId: process.env.S3_ACCESS_KEY_ID ?? '',
|
|
53
|
+
* secretAccessKey: process.env.S3_SECRET_ACCESS_KEY ?? '',
|
|
54
|
+
* },
|
|
55
|
+
* });
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
export declare function s3Files(options: S3FilesOptions): FileStore & Required<Pick<FileStore, "sweep" | "diagnose">>;
|
|
59
|
+
export type { S3Credentials, S3FilesOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes } from "node:crypto";
|
|
2
|
+
// src/sigv4.ts
|
|
3
|
+
/** Hex SHA-256 of a body, for `x-amz-content-sha256`. */
|
|
4
|
+
const sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
|
|
5
|
+
const hmac = (key, data) => createHmac("sha256", key).update(data).digest();
|
|
6
|
+
/**
|
|
7
|
+
* RFC 3986 encoding as SigV4 wants it: everything but `A-Z a-z 0-9 - . _ ~` as `%XX` in upper
|
|
8
|
+
* case. `encodeURIComponent` leaves `! ' ( ) *` alone, so they are encoded here.
|
|
9
|
+
*/
|
|
10
|
+
const uriEncode = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
11
|
+
/** By code unit, as AWS sorts: encoded names are ASCII. */
|
|
12
|
+
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
13
|
+
/** `20130524T000000Z` */
|
|
14
|
+
const amzDate = (now) => now.toISOString().replace(/[-:]/g, "").replace(/\.\d+/, "");
|
|
15
|
+
/**
|
|
16
|
+
* The headers that sign one request: the given ones plus `x-amz-date`, `x-amz-content-sha256`,
|
|
17
|
+
* `x-amz-security-token` (with a session token) and `authorization`. `host` is signed but not
|
|
18
|
+
* returned, since fetch sets it from the URL. The URL's path and query must already be encoded
|
|
19
|
+
* with `uriEncode`, as S3 signs them once-encoded.
|
|
20
|
+
*/
|
|
21
|
+
function signRequest(input) {
|
|
22
|
+
const { credentials, region } = input;
|
|
23
|
+
const datetime = amzDate(input.now);
|
|
24
|
+
const date = datetime.slice(0, 8);
|
|
25
|
+
const headers = {
|
|
26
|
+
...input.headers,
|
|
27
|
+
"x-amz-content-sha256": input.payloadHash,
|
|
28
|
+
"x-amz-date": datetime
|
|
29
|
+
};
|
|
30
|
+
if (credentials.sessionToken) headers["x-amz-security-token"] = credentials.sessionToken;
|
|
31
|
+
const signed = {};
|
|
32
|
+
for (const [name, value] of Object.entries(headers)) signed[name.toLowerCase()] = value;
|
|
33
|
+
signed["host"] = input.url.host;
|
|
34
|
+
const names = Object.keys(signed).sort();
|
|
35
|
+
const canonicalHeaders = names.map((name) => `${name}:${(signed[name] ?? "").trim().replace(/\s+/g, " ")}\n`).join("");
|
|
36
|
+
const signedHeaders = names.join(";");
|
|
37
|
+
const query = input.url.search.slice(1).split("&").filter((pair) => pair !== "").map((pair) => {
|
|
38
|
+
const at = pair.indexOf("=");
|
|
39
|
+
return at === -1 ? [pair, ""] : [pair.slice(0, at), pair.slice(at + 1)];
|
|
40
|
+
}).sort(([a, x], [b, y]) => a === b ? compare(x, y) : compare(a, b)).map(([name, value]) => `${name}=${value}`).join("&");
|
|
41
|
+
const canonicalRequest = [
|
|
42
|
+
input.method,
|
|
43
|
+
input.url.pathname,
|
|
44
|
+
query,
|
|
45
|
+
canonicalHeaders,
|
|
46
|
+
signedHeaders,
|
|
47
|
+
input.payloadHash
|
|
48
|
+
].join("\n");
|
|
49
|
+
const scope = `${date}/${region}/s3/aws4_request`;
|
|
50
|
+
const stringToSign = [
|
|
51
|
+
"AWS4-HMAC-SHA256",
|
|
52
|
+
datetime,
|
|
53
|
+
scope,
|
|
54
|
+
sha256Hex(canonicalRequest)
|
|
55
|
+
].join("\n");
|
|
56
|
+
const key = hmac(hmac(hmac(hmac(`AWS4${credentials.secretAccessKey}`, date), region), "s3"), "aws4_request");
|
|
57
|
+
const signature = createHmac("sha256", key).update(stringToSign).digest("hex");
|
|
58
|
+
headers["authorization"] = `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
|
|
59
|
+
return headers;
|
|
60
|
+
}
|
|
61
|
+
// src/client.ts
|
|
62
|
+
/** A bound for every call (typescript-conventions: every network await has one). */
|
|
63
|
+
const REQUEST_TIMEOUT_MS = 3e4;
|
|
64
|
+
/** S3 error codes are letters, digits and dots; anything else is not repeated in messages. */
|
|
65
|
+
const ERROR_CODE = /^[A-Za-z0-9.]{1,64}$/;
|
|
66
|
+
const REQUEST_ID = /^[A-Za-z0-9+/=_-]{1,128}$/;
|
|
67
|
+
/**
|
|
68
|
+
* A failed S3 call. Its message holds the operation, the HTTP status, S3's error code and request
|
|
69
|
+
* ID only: never a key, a file name, bytes, credentials or a signature (ADR-0004).
|
|
70
|
+
*/
|
|
71
|
+
var S3Error = class extends Error {
|
|
72
|
+
operation;
|
|
73
|
+
/** S3's error code, such as `AccessDenied`, or `network`, `timeout` and `aborted`. */
|
|
74
|
+
code;
|
|
75
|
+
status;
|
|
76
|
+
constructor(operation, code, status, requestId, detail) {
|
|
77
|
+
const http = status === void 0 ? "" : ` HTTP ${status}`;
|
|
78
|
+
const id = requestId && REQUEST_ID.test(requestId) ? ` (request ID ${requestId})` : "";
|
|
79
|
+
super(`[askdare-s3] ${operation} failed:${http} ${code}${detail ? `, ${detail}` : ""}${id}.`);
|
|
80
|
+
this.name = "S3Error";
|
|
81
|
+
this.operation = operation;
|
|
82
|
+
this.code = code;
|
|
83
|
+
this.status = status;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const ENTITIES = {
|
|
87
|
+
amp: "&",
|
|
88
|
+
lt: "<",
|
|
89
|
+
gt: ">",
|
|
90
|
+
quot: "\"",
|
|
91
|
+
apos: "'"
|
|
92
|
+
};
|
|
93
|
+
/** Text with XML's entities resolved. */
|
|
94
|
+
const xmlDecode = (text) => text.replace(/&(#x[0-9a-fA-F]+|#\d+|[a-z]+);/g, (whole, entity) => {
|
|
95
|
+
if (entity.startsWith("#x")) return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
|
|
96
|
+
if (entity.startsWith("#")) return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
|
|
97
|
+
return ENTITIES[entity] ?? whole;
|
|
98
|
+
});
|
|
99
|
+
/** Text for an XML element. */
|
|
100
|
+
const xmlEncode = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
|
|
101
|
+
/** The inner XML of every `<tag>…</tag>`. S3's responses don't nest a tag inside itself. */
|
|
102
|
+
const xmlBlocks = (xml, tag) => [...xml.matchAll(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`, "g"))].map((match) => match[1] ?? "");
|
|
103
|
+
/** The decoded text of the first `<tag>…</tag>`, or undefined. */
|
|
104
|
+
const xmlText = (xml, tag) => {
|
|
105
|
+
const [inner] = xmlBlocks(xml, tag);
|
|
106
|
+
return inner === void 0 ? void 0 : xmlDecode(inner);
|
|
107
|
+
};
|
|
108
|
+
/** S3's error code from an error body, or the status when the body has none (HEAD, proxies). */
|
|
109
|
+
const errorCode = (body, status) => {
|
|
110
|
+
const code = xmlText(body, "Code");
|
|
111
|
+
return code && ERROR_CODE.test(code) ? code : `HTTP${status}`;
|
|
112
|
+
};
|
|
113
|
+
const resolveCredentials = async (input) => {
|
|
114
|
+
const credentials = typeof input === "function" ? await input() : input;
|
|
115
|
+
if (typeof credentials?.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string" || credentials.accessKeyId === "" || credentials.secretAccessKey === "") throw new Error("[askdare-s3] The credentials need an accessKeyId and a secretAccessKey.");
|
|
116
|
+
return credentials;
|
|
117
|
+
};
|
|
118
|
+
/** A client for one bucket. `send` resolves to the response, whatever its status. */
|
|
119
|
+
function createClient(config) {
|
|
120
|
+
const { endpoint, bucket } = config;
|
|
121
|
+
const bucketPath = config.pathStyle ? `/${uriEncode(bucket)}` : "";
|
|
122
|
+
const origin = config.pathStyle ? endpoint.origin : `${endpoint.protocol}//${bucket}.${endpoint.host}`;
|
|
123
|
+
return { async send(request) {
|
|
124
|
+
const credentials = await resolveCredentials(config.credentials);
|
|
125
|
+
const key = request.key === void 0 ? "" : request.key.split("/").map(uriEncode).join("/");
|
|
126
|
+
const path = `${bucketPath}/${key}`;
|
|
127
|
+
const query = (request.query ?? []).map(([name, value]) => `${uriEncode(name)}=${uriEncode(value)}`).join("&");
|
|
128
|
+
const url = new URL(`${origin}${path}${query ? `?${query}` : ""}`);
|
|
129
|
+
const body = request.body;
|
|
130
|
+
const headers = signRequest({
|
|
131
|
+
method: request.method,
|
|
132
|
+
url,
|
|
133
|
+
headers: request.headers ?? {},
|
|
134
|
+
payloadHash: sha256Hex(body ?? ""),
|
|
135
|
+
region: config.region,
|
|
136
|
+
credentials,
|
|
137
|
+
now: /* @__PURE__ */ new Date()
|
|
138
|
+
});
|
|
139
|
+
const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
|
|
140
|
+
const signal = request.signal ? AbortSignal.any([request.signal, timeout]) : timeout;
|
|
141
|
+
try {
|
|
142
|
+
return await fetch(url, {
|
|
143
|
+
method: request.method,
|
|
144
|
+
headers,
|
|
145
|
+
...body ? { body: new Uint8Array(body) } : {},
|
|
146
|
+
signal,
|
|
147
|
+
redirect: "error"
|
|
148
|
+
});
|
|
149
|
+
} catch {
|
|
150
|
+
if (request.signal?.aborted) throw request.signal.reason;
|
|
151
|
+
throw new S3Error(request.operation, timeout.aborted ? "timeout" : "network");
|
|
152
|
+
}
|
|
153
|
+
} };
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Reads a response's body under the request's signal: the caller's abort rethrows its reason, and
|
|
157
|
+
* the timeout or a dropped connection becomes an `S3Error`, as they do before the headers arrive.
|
|
158
|
+
*/
|
|
159
|
+
async function readBody(operation, signal, read) {
|
|
160
|
+
try {
|
|
161
|
+
return await read();
|
|
162
|
+
} catch (error) {
|
|
163
|
+
if (signal?.aborted) throw signal.reason;
|
|
164
|
+
throw new S3Error(operation, error instanceof DOMException && error.name === "TimeoutError" ? "timeout" : "network");
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/** Throws an `S3Error` for a response that isn't 2xx, after reading its body for the code. */
|
|
168
|
+
async function ensureOk(operation, response) {
|
|
169
|
+
if (response.ok) return;
|
|
170
|
+
throw new S3Error(operation, errorCode(await response.text().catch(() => ""), response.status), response.status, response.headers.get("x-amz-request-id"));
|
|
171
|
+
}
|
|
172
|
+
// src/store.ts
|
|
173
|
+
/** What the store chooses: 128 random bits, base64url, 22 characters. */
|
|
174
|
+
const ID_SHAPE = /^[A-Za-z0-9_-]{22}$/;
|
|
175
|
+
const DEFAULT_PREFIX = "askdare-files/";
|
|
176
|
+
/** Segments of letters, digits, `.`, `_` and `-`, each followed by `/`, then maybe one more. */
|
|
177
|
+
const PREFIX_SHAPE = /^(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]*$/;
|
|
178
|
+
const MAX_PREFIX = 256;
|
|
179
|
+
const BUCKET_SHAPE = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/;
|
|
180
|
+
const REGION_SHAPE = /^[a-z0-9-]{1,32}$/;
|
|
181
|
+
/** DeleteObjects takes at most 1,000 keys a request. */
|
|
182
|
+
const DELETE_BATCH = 1e3;
|
|
183
|
+
const NAME_HEADER = "x-amz-meta-name";
|
|
184
|
+
const XMLNS = "http://s3.amazonaws.com/doc/2006-03-01/";
|
|
185
|
+
const newId = () => randomBytes(16).toString("base64url");
|
|
186
|
+
/**
|
|
187
|
+
* The name as metadata: S3 sends user metadata in HTTP headers, so it must be ASCII. Percent
|
|
188
|
+
* encoding keeps ASCII names readable in the bucket's console.
|
|
189
|
+
*/
|
|
190
|
+
const encodeName = (name) => encodeURIComponent(name);
|
|
191
|
+
const decodeName = (value) => {
|
|
192
|
+
try {
|
|
193
|
+
return decodeURIComponent(value);
|
|
194
|
+
} catch {
|
|
195
|
+
return value;
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
/** Hosts with no subdomains for buckets: localhost, and IPv4 or IPv6 addresses. */
|
|
199
|
+
const isLocalOrIp = (hostname) => hostname === "localhost" || hostname.endsWith(".localhost") || hostname.startsWith("[") || /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname);
|
|
200
|
+
const fail = (message) => {
|
|
201
|
+
throw new Error(`[askdare-s3] ${message}`);
|
|
202
|
+
};
|
|
203
|
+
const parseEndpoint = (endpoint, region) => {
|
|
204
|
+
if (endpoint === void 0) {
|
|
205
|
+
if (region === "auto") fail("Set endpoint for region \"auto\", such as your R2 endpoint.");
|
|
206
|
+
return new URL(`https://s3.${region}.amazonaws.com`);
|
|
207
|
+
}
|
|
208
|
+
let url;
|
|
209
|
+
try {
|
|
210
|
+
url = new URL(endpoint);
|
|
211
|
+
} catch {
|
|
212
|
+
return fail("endpoint must be a URL, such as https://s3.eu-central-1.amazonaws.com.");
|
|
213
|
+
}
|
|
214
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") fail("endpoint must be http or https.");
|
|
215
|
+
if (url.username || url.password || url.search || url.hash || url.pathname !== "/") fail("endpoint must be an origin only: no path, query or credentials.");
|
|
216
|
+
return url;
|
|
217
|
+
};
|
|
218
|
+
/**
|
|
219
|
+
* Visitors' attachments in your own S3 bucket (ADR-0037): AWS S3, Cloudflare R2, MinIO or another
|
|
220
|
+
* S3-compatible server. Bytes go in the object, the type in its `Content-Type` and the name in its
|
|
221
|
+
* metadata. Turn on the bucket's server-side encryption and add a lifecycle rule as old as
|
|
222
|
+
* `files.retentionDays`; the README shows both and a least-privilege policy.
|
|
223
|
+
*
|
|
224
|
+
* ```ts
|
|
225
|
+
* import { s3Files } from '@boldare/askdare-s3';
|
|
226
|
+
*
|
|
227
|
+
* const files = s3Files({
|
|
228
|
+
* bucket: 'acme-askdare',
|
|
229
|
+
* region: 'eu-central-1',
|
|
230
|
+
* credentials: {
|
|
231
|
+
* accessKeyId: process.env.S3_ACCESS_KEY_ID ?? '',
|
|
232
|
+
* secretAccessKey: process.env.S3_SECRET_ACCESS_KEY ?? '',
|
|
233
|
+
* },
|
|
234
|
+
* });
|
|
235
|
+
* ```
|
|
236
|
+
*/
|
|
237
|
+
function s3Files(options) {
|
|
238
|
+
const { bucket } = options;
|
|
239
|
+
const prefix = options.prefix ?? DEFAULT_PREFIX;
|
|
240
|
+
const region = options.region ?? "us-east-1";
|
|
241
|
+
if (typeof bucket !== "string" || !BUCKET_SHAPE.test(bucket) || bucket.includes("..")) fail("bucket must be a valid bucket name: 3 to 63 lower-case letters, digits, dots and hyphens.");
|
|
242
|
+
if (prefix === "" || prefix.length > MAX_PREFIX || !PREFIX_SHAPE.test(prefix) || prefix.split("/").some((segment) => segment === "." || segment === "..")) fail("prefix must not be empty, may hold letters, digits, \".\", \"_\", \"-\" and \"/\", and no \".\" or \"..\" segments.");
|
|
243
|
+
if (!REGION_SHAPE.test(region)) fail("region must look like eu-central-1, or auto on R2.");
|
|
244
|
+
const endpoint = parseEndpoint(options.endpoint, region);
|
|
245
|
+
const pathStyle = options.forcePathStyle ?? false;
|
|
246
|
+
if (!pathStyle && isLocalOrIp(endpoint.hostname)) fail("An endpoint on localhost or an IP address needs forcePathStyle: true.");
|
|
247
|
+
if (!pathStyle && endpoint.protocol === "https:" && bucket.includes(".")) fail("A bucket name with dots needs forcePathStyle: true over https.");
|
|
248
|
+
const client = createClient({
|
|
249
|
+
bucket,
|
|
250
|
+
endpoint,
|
|
251
|
+
region,
|
|
252
|
+
pathStyle,
|
|
253
|
+
credentials: options.credentials
|
|
254
|
+
});
|
|
255
|
+
const keyOf = (id) => `${prefix}${id}`;
|
|
256
|
+
/** Deletes up to 1,000 of our IDs in one request; resolves to how many S3 deleted. */
|
|
257
|
+
const deleteBatch = async (ids, signal) => {
|
|
258
|
+
const objects = ids.map((id) => `<Object><Key>${xmlEncode(keyOf(id))}</Key></Object>`);
|
|
259
|
+
const body = new TextEncoder().encode(`<?xml version="1.0" encoding="UTF-8"?><Delete xmlns="${XMLNS}"><Quiet>true</Quiet>${objects.join("")}</Delete>`);
|
|
260
|
+
const response = await client.send({
|
|
261
|
+
operation: "DeleteObjects",
|
|
262
|
+
method: "POST",
|
|
263
|
+
query: [["delete", ""]],
|
|
264
|
+
headers: {
|
|
265
|
+
"content-type": "application/xml",
|
|
266
|
+
"content-md5": createHash("md5").update(body).digest("base64")
|
|
267
|
+
},
|
|
268
|
+
body,
|
|
269
|
+
signal
|
|
270
|
+
});
|
|
271
|
+
await ensureOk("DeleteObjects", response);
|
|
272
|
+
const errors = xmlBlocks(await readBody("DeleteObjects", signal, () => response.text()), "Error");
|
|
273
|
+
if (errors.length > 0) throw new S3Error("DeleteObjects", errorCode(errors[0] ?? "", 200), 200, response.headers.get("x-amz-request-id"), `${errors.length} of ${ids.length} not deleted`);
|
|
274
|
+
return ids.length;
|
|
275
|
+
};
|
|
276
|
+
/** One page of `ListObjectsV2` under the prefix: our IDs with their times. */
|
|
277
|
+
const listPage = async (continuationToken, maxKeys, signal) => {
|
|
278
|
+
const query = [
|
|
279
|
+
["list-type", "2"],
|
|
280
|
+
["prefix", prefix],
|
|
281
|
+
["delimiter", "/"],
|
|
282
|
+
["encoding-type", "url"],
|
|
283
|
+
["max-keys", String(maxKeys)]
|
|
284
|
+
];
|
|
285
|
+
if (continuationToken !== void 0) query.push(["continuation-token", continuationToken]);
|
|
286
|
+
const response = await client.send({
|
|
287
|
+
operation: "ListObjectsV2",
|
|
288
|
+
method: "GET",
|
|
289
|
+
query,
|
|
290
|
+
signal
|
|
291
|
+
});
|
|
292
|
+
await ensureOk("ListObjectsV2", response);
|
|
293
|
+
const xml = await readBody("ListObjectsV2", signal, () => response.text());
|
|
294
|
+
const files = [];
|
|
295
|
+
for (const entry of xmlBlocks(xml, "Contents")) {
|
|
296
|
+
let key;
|
|
297
|
+
try {
|
|
298
|
+
key = decodeURIComponent(xmlText(entry, "Key") ?? "");
|
|
299
|
+
} catch {
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
const id = key.slice(prefix.length);
|
|
303
|
+
const modified = Date.parse(xmlText(entry, "LastModified") ?? "");
|
|
304
|
+
if (!key.startsWith(prefix) || !ID_SHAPE.test(id) || Number.isNaN(modified)) continue;
|
|
305
|
+
files.push({
|
|
306
|
+
id,
|
|
307
|
+
modified
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
return {
|
|
311
|
+
files,
|
|
312
|
+
next: xmlText(xml, "IsTruncated") === "true" ? xmlText(xml, "NextContinuationToken") : void 0
|
|
313
|
+
};
|
|
314
|
+
};
|
|
315
|
+
const store = {
|
|
316
|
+
async put(file, callOptions) {
|
|
317
|
+
const id = newId();
|
|
318
|
+
const response = await client.send({
|
|
319
|
+
operation: "PutObject",
|
|
320
|
+
method: "PUT",
|
|
321
|
+
key: keyOf(id),
|
|
322
|
+
headers: {
|
|
323
|
+
"content-type": file.mime,
|
|
324
|
+
[NAME_HEADER]: encodeName(file.name)
|
|
325
|
+
},
|
|
326
|
+
body: file.bytes,
|
|
327
|
+
signal: callOptions?.signal
|
|
328
|
+
});
|
|
329
|
+
await ensureOk("PutObject", response);
|
|
330
|
+
await readBody("PutObject", callOptions?.signal, () => response.arrayBuffer());
|
|
331
|
+
return id;
|
|
332
|
+
},
|
|
333
|
+
async get(id, callOptions) {
|
|
334
|
+
if (!ID_SHAPE.test(id)) return void 0;
|
|
335
|
+
const response = await client.send({
|
|
336
|
+
operation: "GetObject",
|
|
337
|
+
method: "GET",
|
|
338
|
+
key: keyOf(id),
|
|
339
|
+
signal: callOptions?.signal
|
|
340
|
+
});
|
|
341
|
+
if (response.status === 404) {
|
|
342
|
+
const body = await response.text().catch(() => "");
|
|
343
|
+
if (xmlText(body, "Code") !== "NoSuchBucket") return void 0;
|
|
344
|
+
throw new S3Error("GetObject", "NoSuchBucket", 404, response.headers.get("x-amz-request-id"));
|
|
345
|
+
}
|
|
346
|
+
await ensureOk("GetObject", response);
|
|
347
|
+
const bytes = new Uint8Array(await readBody("GetObject", callOptions?.signal, () => response.arrayBuffer()));
|
|
348
|
+
const storedAt = new Date(response.headers.get("last-modified") ?? "");
|
|
349
|
+
if (Number.isNaN(storedAt.getTime())) throw new S3Error("GetObject", "NoLastModified");
|
|
350
|
+
return {
|
|
351
|
+
bytes,
|
|
352
|
+
mime: response.headers.get("content-type") ?? "application/octet-stream",
|
|
353
|
+
name: decodeName(response.headers.get(NAME_HEADER) ?? ""),
|
|
354
|
+
storedAt
|
|
355
|
+
};
|
|
356
|
+
},
|
|
357
|
+
async delete(ids, callOptions) {
|
|
358
|
+
const ours = [...new Set(ids.filter((id) => ID_SHAPE.test(id)))];
|
|
359
|
+
for (let start = 0; start < ours.length; start += DELETE_BATCH) {
|
|
360
|
+
callOptions?.signal?.throwIfAborted();
|
|
361
|
+
await deleteBatch(ours.slice(start, start + DELETE_BATCH), callOptions?.signal);
|
|
362
|
+
}
|
|
363
|
+
},
|
|
364
|
+
async sweep(before, limit, callOptions) {
|
|
365
|
+
const signal = callOptions?.signal;
|
|
366
|
+
const cutoff = before.getTime();
|
|
367
|
+
const max = Math.floor(limit);
|
|
368
|
+
let deleted = 0;
|
|
369
|
+
let token;
|
|
370
|
+
while (deleted < max) {
|
|
371
|
+
signal?.throwIfAborted();
|
|
372
|
+
const page = await listPage(token, DELETE_BATCH, signal);
|
|
373
|
+
const old = page.files.filter((file) => file.modified < cutoff).slice(0, max - deleted).map((file) => file.id);
|
|
374
|
+
if (old.length > 0) {
|
|
375
|
+
signal?.throwIfAborted();
|
|
376
|
+
deleted += await deleteBatch(old, signal);
|
|
377
|
+
}
|
|
378
|
+
if (page.next === void 0 || page.next === token) break;
|
|
379
|
+
token = page.next;
|
|
380
|
+
}
|
|
381
|
+
return deleted;
|
|
382
|
+
},
|
|
383
|
+
async diagnose(callOptions) {
|
|
384
|
+
const signal = callOptions?.signal;
|
|
385
|
+
const where = `S3 file store (bucket ${bucket})`;
|
|
386
|
+
const probe = Uint8Array.of(97, 115, 107, 100, 97, 114, 101, 255);
|
|
387
|
+
let id;
|
|
388
|
+
try {
|
|
389
|
+
id = await store.put({
|
|
390
|
+
bytes: probe,
|
|
391
|
+
mime: "application/octet-stream",
|
|
392
|
+
name: "askdare-doctor"
|
|
393
|
+
}, { signal });
|
|
394
|
+
const read = await store.get(id, { signal });
|
|
395
|
+
if (!read || read.bytes.length !== probe.length || read.bytes.some((b, i) => b !== probe[i])) return [{
|
|
396
|
+
status: "fail",
|
|
397
|
+
title: `${where}: a test file came back different from what was written.`,
|
|
398
|
+
fix: "Check that endpoint points at an S3-compatible server and nothing rewrites objects in between."
|
|
399
|
+
}];
|
|
400
|
+
await store.delete([id], { signal });
|
|
401
|
+
const deleted = id;
|
|
402
|
+
id = void 0;
|
|
403
|
+
if (await store.get(deleted, { signal }) !== void 0) return [{
|
|
404
|
+
status: "fail",
|
|
405
|
+
title: `${where}: a deleted test file could still be read.`,
|
|
406
|
+
fix: "Check that nothing in front of the bucket caches objects, and that versioning does not serve old versions."
|
|
407
|
+
}];
|
|
408
|
+
await listPage(void 0, 1, signal);
|
|
409
|
+
return [{
|
|
410
|
+
status: "ok",
|
|
411
|
+
title: `${where}: wrote, read, listed and deleted a test file.`
|
|
412
|
+
}];
|
|
413
|
+
} catch (error) {
|
|
414
|
+
if (signal?.aborted) throw error;
|
|
415
|
+
return [checkFor(where, error)];
|
|
416
|
+
} finally {
|
|
417
|
+
if (id !== void 0) await store.delete([id]).catch(() => void 0);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
return store;
|
|
422
|
+
}
|
|
423
|
+
const FIXES = {
|
|
424
|
+
AccessDenied: "Allow s3:PutObject, s3:GetObject and s3:DeleteObject on the prefix, and s3:ListBucket on the bucket, for these credentials (see the README for a policy). Without s3:ListBucket, S3 answers a missing file with AccessDenied.",
|
|
425
|
+
NoSuchBucket: "Create the bucket, or check bucket, region and endpoint.",
|
|
426
|
+
InvalidAccessKeyId: "Check the access key ID: the server does not know it.",
|
|
427
|
+
SignatureDoesNotMatch: "Check the secret access key, and that region is the bucket region.",
|
|
428
|
+
AuthorizationHeaderMalformed: "Set region to the bucket region.",
|
|
429
|
+
PermanentRedirect: "Set region to the bucket region, or endpoint to its regional endpoint.",
|
|
430
|
+
RequestTimeTooSkewed: "Sync this server's clock: S3 refuses requests more than 15 minutes off.",
|
|
431
|
+
ExpiredToken: "The session token expired: pass credentials as a function that refreshes them.",
|
|
432
|
+
network: "Check endpoint, and that this server can reach it.",
|
|
433
|
+
timeout: "The server did not answer in 30 seconds. Check endpoint and the network."
|
|
434
|
+
};
|
|
435
|
+
/** A failed check with S3's error code and what to do about it; never the error's own message. */
|
|
436
|
+
const checkFor = (where, error) => {
|
|
437
|
+
if (error instanceof S3Error) return {
|
|
438
|
+
status: "fail",
|
|
439
|
+
title: `${where}: ${error.operation} failed (${error.code}).`,
|
|
440
|
+
fix: FIXES[error.code] ?? "Check bucket, region, endpoint and credentials."
|
|
441
|
+
};
|
|
442
|
+
return {
|
|
443
|
+
status: "fail",
|
|
444
|
+
title: `${where}: ${error instanceof Error && error.message.startsWith("[askdare-s3] ") ? error.message.slice(13) : "the check failed."}`,
|
|
445
|
+
fix: "Check the credentials you pass to s3Files."
|
|
446
|
+
};
|
|
447
|
+
};
|
|
448
|
+
export { s3Files };
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@boldare/askdare-s3",
|
|
3
|
+
"version": "0.0.0-placeholder",
|
|
4
|
+
"description": "A file store for @boldare/askdare: visitors' attachments in your own bucket on AWS S3, Cloudflare R2 or MinIO.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": {
|
|
7
|
+
"name": "Boldare",
|
|
8
|
+
"url": "https://www.boldare.com"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/boldare/askdare/tree/main/packages/askdare-s3#readme",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/boldare/askdare.git",
|
|
14
|
+
"directory": "packages/askdare-s3"
|
|
15
|
+
},
|
|
16
|
+
"bugs": "https://github.com/boldare/askdare/issues",
|
|
17
|
+
"keywords": [
|
|
18
|
+
"askdare",
|
|
19
|
+
"s3",
|
|
20
|
+
"r2",
|
|
21
|
+
"minio",
|
|
22
|
+
"attachments"
|
|
23
|
+
],
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=22"
|
|
28
|
+
},
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./package.json": "./package.json"
|
|
35
|
+
},
|
|
36
|
+
"types": "./dist/index.d.ts",
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"LICENSE",
|
|
40
|
+
"CHANGELOG.md"
|
|
41
|
+
],
|
|
42
|
+
"peerDependencies": {
|
|
43
|
+
"@boldare/askdare": "^0.7.1"
|
|
44
|
+
},
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public",
|
|
47
|
+
"provenance": true
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
51
|
+
"@boldare/askdare": "^0.7.1",
|
|
52
|
+
"publint": "^0.3.25",
|
|
53
|
+
"tsdown": "^0.23.7"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"build": "tsdown && node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\"",
|
|
57
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
58
|
+
"check:package": "publint --strict && attw --pack . --profile esm-only && node ../../scripts/check-dts-no-leak.mjs dist"
|
|
59
|
+
}
|
|
60
|
+
}
|