@softistx/s3 0.0.0-stage → 0.13.1

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.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +609 -2
  3. package/dist/bucket/bind-bucket.d.ts +42 -0
  4. package/dist/bucket/bind-bucket.d.ts.map +1 -0
  5. package/dist/bucket/bound-bucket.d.ts +119 -0
  6. package/dist/bucket/bound-bucket.d.ts.map +1 -0
  7. package/dist/bucket/context.d.ts +55 -0
  8. package/dist/bucket/context.d.ts.map +1 -0
  9. package/dist/bucket/define-bucket.d.ts +16 -0
  10. package/dist/bucket/define-bucket.d.ts.map +1 -0
  11. package/dist/bucket/disposition.d.ts +9 -0
  12. package/dist/bucket/disposition.d.ts.map +1 -0
  13. package/dist/bucket/guards.d.ts +38 -0
  14. package/dist/bucket/guards.d.ts.map +1 -0
  15. package/dist/bucket/operations/counted-stream.d.ts +26 -0
  16. package/dist/bucket/operations/counted-stream.d.ts.map +1 -0
  17. package/dist/bucket/operations/deadline.d.ts +21 -0
  18. package/dist/bucket/operations/deadline.d.ts.map +1 -0
  19. package/dist/bucket/operations/fetch-object.d.ts +68 -0
  20. package/dist/bucket/operations/fetch-object.d.ts.map +1 -0
  21. package/dist/bucket/operations/list-xml.d.ts +18 -0
  22. package/dist/bucket/operations/list-xml.d.ts.map +1 -0
  23. package/dist/bucket/operations/list.d.ts +12 -0
  24. package/dist/bucket/operations/list.d.ts.map +1 -0
  25. package/dist/bucket/operations/open-answer.d.ts +5 -0
  26. package/dist/bucket/operations/open-answer.d.ts.map +1 -0
  27. package/dist/bucket/operations/open-range.d.ts +10 -0
  28. package/dist/bucket/operations/open-range.d.ts.map +1 -0
  29. package/dist/bucket/operations/open-relay.d.ts +8 -0
  30. package/dist/bucket/operations/open-relay.d.ts.map +1 -0
  31. package/dist/bucket/operations/open.d.ts +4 -0
  32. package/dist/bucket/operations/open.d.ts.map +1 -0
  33. package/dist/bucket/operations/post-policy.d.ts +77 -0
  34. package/dist/bucket/operations/post-policy.d.ts.map +1 -0
  35. package/dist/bucket/operations/post-signer.d.ts +21 -0
  36. package/dist/bucket/operations/post-signer.d.ts.map +1 -0
  37. package/dist/bucket/operations/presign-post.d.ts +44 -0
  38. package/dist/bucket/operations/presign-post.d.ts.map +1 -0
  39. package/dist/bucket/operations/presign.d.ts +34 -0
  40. package/dist/bucket/operations/presign.d.ts.map +1 -0
  41. package/dist/bucket/operations/put-body.d.ts +13 -0
  42. package/dist/bucket/operations/put-body.d.ts.map +1 -0
  43. package/dist/bucket/operations/query-sign.d.ts +15 -0
  44. package/dist/bucket/operations/query-sign.d.ts.map +1 -0
  45. package/dist/bucket/operations/reads.d.ts +8 -0
  46. package/dist/bucket/operations/reads.d.ts.map +1 -0
  47. package/dist/bucket/operations/sized-body.d.ts +24 -0
  48. package/dist/bucket/operations/sized-body.d.ts.map +1 -0
  49. package/dist/bucket/operations/slice.d.ts +4 -0
  50. package/dist/bucket/operations/slice.d.ts.map +1 -0
  51. package/dist/bucket/operations/writes.d.ts +10 -0
  52. package/dist/bucket/operations/writes.d.ts.map +1 -0
  53. package/dist/bucket/shape.d.ts +6 -0
  54. package/dist/bucket/shape.d.ts.map +1 -0
  55. package/dist/bucket/types.d.ts +164 -0
  56. package/dist/bucket/types.d.ts.map +1 -0
  57. package/dist/chunks/index-jgjey570.js +118 -0
  58. package/dist/chunks/index-jgjey570.js.map +13 -0
  59. package/dist/errors/is-bucket-unavailable.d.ts +18 -0
  60. package/dist/errors/is-bucket-unavailable.d.ts.map +1 -0
  61. package/dist/errors/s3-error.d.ts +80 -0
  62. package/dist/errors/s3-error.d.ts.map +1 -0
  63. package/dist/index.d.ts +8 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +1288 -0
  66. package/dist/index.js.map +32 -0
  67. package/dist/testing/fetch-archive.d.ts +8 -0
  68. package/dist/testing/fetch-archive.d.ts.map +1 -0
  69. package/dist/testing/index.d.ts +6 -0
  70. package/dist/testing/index.d.ts.map +1 -0
  71. package/dist/testing/index.js +416 -0
  72. package/dist/testing/index.js.map +16 -0
  73. package/dist/testing/ports.d.ts +15 -0
  74. package/dist/testing/ports.d.ts.map +1 -0
  75. package/dist/testing/ready.d.ts +49 -0
  76. package/dist/testing/ready.d.ts.map +1 -0
  77. package/dist/testing/reaper.d.ts +4 -0
  78. package/dist/testing/reaper.d.ts.map +1 -0
  79. package/dist/testing/seaweedfs.d.ts +64 -0
  80. package/dist/testing/seaweedfs.d.ts.map +1 -0
  81. package/dist/testing/test-s3.d.ts +35 -0
  82. package/dist/testing/test-s3.d.ts.map +1 -0
  83. package/dist/testing/weed.d.ts +17 -0
  84. package/dist/testing/weed.d.ts.map +1 -0
  85. package/docs/README.md +17 -0
  86. package/docs/guide/buckets.md +220 -0
  87. package/docs/guide/presigned-urls.md +403 -0
  88. package/docs/guide/reads.md +417 -0
  89. package/docs/guide/testing.md +151 -0
  90. package/docs/guide/writes.md +374 -0
  91. package/docs/roadmap.md +116 -0
  92. package/docs/troubleshooting.md +982 -0
  93. package/package.json +61 -5
@@ -0,0 +1,403 @@
1
+ # Presigned URLs
2
+
3
+ Handing a browser or another service a URL that reads or writes one object,
4
+ for a while, without ever handing over a credential.
5
+
6
+ ## The smallest thing that works
7
+
8
+ ```ts
9
+ import { bindBucket, defineBucket } from '@softistx/s3';
10
+
11
+ const avatars = defineBucket({
12
+ bucket: 'avatars',
13
+ key: (p: { userId: string }) => `${p.userId}.png`,
14
+ contentType: ['image/png', 'image/jpeg'],
15
+ maxSize: 2 * 1024 * 1024,
16
+ });
17
+
18
+ const store = bindBucket(avatars);
19
+
20
+ const download = store.presignGet({ userId: 'u1' }, { expiresIn: 300 }); // seconds
21
+ const upload = store.presignPut({ userId: 'u1' }, { expiresIn: 300 });
22
+ ```
23
+
24
+ Both are synchronous: signing is arithmetic, not a request. The key comes
25
+ from the definition, so a signed URL and a `put` can never disagree about
26
+ which object they mean — see [Buckets](buckets.md).
27
+
28
+ ## The signatures
29
+
30
+ ```ts
31
+ import type { S3Options } from 'bun';
32
+
33
+ presignGet(params: P, options?: PresignGetOptions): string;
34
+ presignPut(params: P, options?: PresignOptions): string;
35
+
36
+ interface PresignOptions {
37
+ expiresIn?: number | undefined;
38
+ acl?: S3Options['acl'];
39
+ }
40
+
41
+ interface PresignGetOptions extends PresignOptions {
42
+ contentDisposition?: string | undefined;
43
+ }
44
+ ```
45
+
46
+ ## Options
47
+
48
+ | Option | Type | Default | Effect |
49
+ | --- | --- | --- | --- |
50
+ | `expiresIn` | `number` | Bun's, one day | **seconds** until the URL expires. Always pass one. Above 604 800 (seven days, S3's own limit), at or below zero, or anything that is not a finite number is an `S3Error` with `code: 'WRONG_OPTION'` |
51
+ | `acl` | `'private' \| 'public-read' \| …` | none | the ACL the URL is signed for, where the service honours it |
52
+ | `contentDisposition` | `string` | none | **`presignGet` only.** Signed as `response-content-disposition`: the service serves this URL with that header, whatever the object stored. Printable ASCII, non-empty; else `WRONG_OPTION`. `presignPut` takes none |
53
+
54
+ `acl` goes through the same allowlist a `put` is held to, so a value the
55
+ service does not accept is an `S3Error` with `code: 'WRONG_OPTION'` and no
56
+ URL is signed:
57
+
58
+ ```ts
59
+ import { S3Error } from '@softistx/s3';
60
+
61
+ try {
62
+ store.presignPut({ userId: 'u1' }, { acl: 'everyone' as never });
63
+ } catch (error) {
64
+ if (error instanceof S3Error && error.code === 'WRONG_OPTION') {
65
+ error.key; // 'u1.png' — the object it was about
66
+ }
67
+ }
68
+ ```
69
+
70
+ `expiresIn` goes through the same check. Measured on bun 1.4.2, the client
71
+ refuses `0` and below itself, and **signs** an `expiresIn` of `1e12`
72
+ happily — a URL S3 then rejects at use time, which is the one thing this
73
+ package exists not to do. Both ends are refused here now, before anything is
74
+ signed.
75
+
76
+ Before 0.3.0 the values went straight to the client: the same mistake was two
77
+ different classes depending on whether it reached a `put` or a `presign`.
78
+ There is no `storageClass` here — signing a URL stores nothing, so there is
79
+ no class to name.
80
+
81
+ A day is a long time for a URL that anyone can forward. Sign for the time the
82
+ page actually needs:
83
+
84
+ ```ts
85
+ const url = store.presignGet({ userId: 'u1' }, { expiresIn: 60 });
86
+ const answer = await fetch(url);
87
+ answer.status; // 200 — it really reads the object
88
+ ```
89
+
90
+ ## Download with a filename
91
+
92
+ A link that saves the file under a chosen name asks the service to serve the
93
+ object as an attachment. Give `presignGet` a `contentDisposition`; for a name
94
+ that is not plain ASCII, use RFC 6266's `filename*`:
95
+
96
+ ```ts
97
+ const url = store.presignGet(
98
+ { userId: 'u1' },
99
+ { expiresIn: 300, contentDisposition: "attachment; filename*=UTF-8''report.pdf" },
100
+ );
101
+ const answer = await fetch(url);
102
+ answer.headers.get('content-disposition'); // attachment; filename*=UTF-8''report.pdf
103
+ ```
104
+
105
+ Measured against SeaweedFS 4.47: the answer carries the signed header, and it
106
+ wins over the one the object was stored with; a plain `presignGet` of the same
107
+ object still returns the stored one. The override belongs to that link alone.
108
+
109
+ The value is held to one header value before anything is signed: a non-empty
110
+ string of printable ASCII, no CR, LF, NUL or other control character, else an
111
+ `S3Error` with `code: 'WRONG_OPTION'` (`put` and `presignPost` are held to it
112
+ too). A name with `é` or `東京` goes in as `filename*=UTF-8''%C3%A9.pdf`,
113
+ percent-encoded. `presignPut` takes none: the header only describes a
114
+ download.
115
+
116
+ For an upload, `presignPost` takes the same option and pins it in the policy
117
+ (`["eq", "$Content-Disposition", …]`, and a `Content-Disposition` field in
118
+ `fields`), so the object is stored with it and every download carries it.
119
+
120
+ ## A presigned PUT constrains the key and the deadline, and nothing else
121
+
122
+ Not the size. Not the content type.
123
+
124
+ ```ts
125
+ const url = store.presignPut({ userId: 'u1' }, { expiresIn: 60 });
126
+
127
+ await fetch(url, {
128
+ method: 'PUT',
129
+ body: Bun.file('archive.zip'),
130
+ headers: { 'content-type': 'application/zip' },
131
+ });
132
+ // 200 — stored, in a bucket whose definition says image/png only
133
+ ```
134
+
135
+ That is why `presignPut` takes no `type`: it would read as a guarantee it
136
+ cannot make. Measured on bun 1.4.2, `presign`'s `type` only adds
137
+ `response-content-type` — S3's override for what a *download* is labelled —
138
+ and `X-Amz-SignedHeaders` stays `host`, so the uploader's `Content-Type` is
139
+ never signed.
140
+
141
+ The bucket's `contentType` and `maxSize` are [`put`'s guards](writes.md),
142
+ and whoever holds a signed URL is not going through `put`. Where it matters:
143
+
144
+ - use a [presigned POST](#a-presigned-post-the-service-holds-the-size-and-the-type)
145
+ instead, whose policy the service enforces, or
146
+ - check with `stat` after the upload and delete what does not belong, or
147
+ - enforce it in the service's own bucket policy.
148
+
149
+ ```ts
150
+ const found = await store.stat({ userId: 'u1' });
151
+ if (!found || !found.type.startsWith('image/')) {
152
+ await store.delete({ userId: 'u1' });
153
+ }
154
+ ```
155
+
156
+ ## A presigned POST: the service holds the size and the type
157
+
158
+ `presignPost` signs an S3 **POST policy** — the form AWS calls a
159
+ browser-based upload. The browser posts a `multipart/form-data` form straight
160
+ to the bucket, and the **service** checks it against the policy before it
161
+ stores anything: the key, a size range and the content type.
162
+
163
+ ```ts
164
+ presignPost(params: P, options?: PresignPostOptions): PresignedPost;
165
+
166
+ interface PresignPostOptions {
167
+ expiresIn?: number; // seconds, above 0, at most 604800; a day by default
168
+ maxSize?: number; // bytes; the bucket's maxSize by default
169
+ minSize?: number; // bytes; 0 by default
170
+ type?: string | { startsWith: string }; // the bucket's single type by default
171
+ acl?: S3Options['acl'];
172
+ contentDisposition?: string; // a Content-Disposition field, pinned with eq
173
+ }
174
+
175
+ interface PresignedPost {
176
+ url: string; // the bucket's own URL
177
+ fields: Record<string, string>; // post these, then the file
178
+ }
179
+ ```
180
+
181
+ It is synchronous, like the other two: signing is arithmetic. The key comes
182
+ from the definition, as for every other call.
183
+
184
+ ### On the server
185
+
186
+ ```ts
187
+ const form = store.presignPost(
188
+ { userId: 'u1' },
189
+ { type: 'image/png', expiresIn: 300 },
190
+ );
191
+ // form.url → 'https://…/avatars/'
192
+ // form.fields → { key: 'u1.png', 'Content-Type': 'image/png',
193
+ // 'x-amz-algorithm', 'x-amz-credential', 'x-amz-date',
194
+ // policy, 'x-amz-signature' }
195
+ ```
196
+
197
+ ### In the browser
198
+
199
+ ```ts
200
+ const body = new FormData();
201
+ for (const [name, value] of Object.entries(form.fields)) body.append(name, value);
202
+ body.append('file', file); // last: S3 ignores fields after it
203
+ const response = await fetch(form.url, { method: 'POST', body });
204
+ response.status; // 204 when stored
205
+ ```
206
+
207
+ `fields` carries the access key id, in `x-amz-credential`, and a session
208
+ token when one is set, in `x-amz-security-token` — as a presigned URL carries
209
+ them in its query string. Never the secret: the policy is signed with it, and
210
+ the signature is all that travels.
211
+
212
+ On a bucket that names no type, with no `type` given, `fields` has no
213
+ `Content-Type`, and the form posts as written: measured, `204`. The object is
214
+ stored as `application/octet-stream` — SeaweedFS does not take the file part's
215
+ own type — so append `body.append('Content-Type', file.type)` before the file
216
+ when the type matters. With `{ startsWith }` that field is **required**:
217
+ measured, a form posted without it is refused `403 AccessDenied`.
218
+
219
+ ### What each option becomes
220
+
221
+ | Option | Condition in the policy | Default |
222
+ | --- | --- | --- |
223
+ | the params | `["eq", "$key", "<the definition's key>"]` | — |
224
+ | `maxSize`, `minSize` | `["content-length-range", minSize, maxSize]` | the bucket's `maxSize`, and `0` |
225
+ | `type: 'image/png'` | `["eq", "$Content-Type", "image/png"]`, and the field in `fields` | the bucket's `contentType` when it is one type |
226
+ | `type: { startsWith: 'image/' }` | `["starts-with", "$Content-Type", "image/"]`, **no** field — the page's code appends `Content-Type` before the file; a browser adds none by itself | — |
227
+ | no `type`, on a bucket that names none | `["starts-with", "$Content-Type", ""]`: the browser may name any type | — |
228
+ | `acl` | `["eq", "$acl", "public-read"]`, and the field | none |
229
+ | `contentDisposition` | `["eq", "$Content-Disposition", "attachment; …"]`, and the field: another value is `403` | none |
230
+ | `expiresIn` | the policy's `expiration` | a day, as Bun's for the other two |
231
+
232
+ The bounds can only tighten the definition, never loosen it:
233
+
234
+ - a bucket **without** a `maxSize` requires one here — the point of a POST is
235
+ the bound, and a form with none would be a presigned PUT with extra steps;
236
+ - a `maxSize` above the bucket's own is refused, and so is a `minSize` above
237
+ the `maxSize`;
238
+ - a `type` is checked against the bucket's `contentType` exactly as a `put`'s
239
+ is, and a bucket that names **several** needs one of them: the policy holds
240
+ one;
241
+ - a `{ startsWith }` prefix is refused on a bucket that names its types — a
242
+ prefix would let another type through.
243
+
244
+ Each refusal is an `S3Error`, raised before anything is signed: `WRONG_OPTION`
245
+ for a size, a `type` of the wrong shape, an `expiresIn`, an `acl` or a
246
+ `contentDisposition`, and
247
+ `WRONG_TYPE` for a type the bucket does not accept. See
248
+ [Troubleshooting](../troubleshooting.md).
249
+
250
+ ### What the service answers
251
+
252
+ Measured against SeaweedFS 4.47's S3 gateway, each one pinned in
253
+ [`presign-post.spec.ts`](https://github.com/softistx/nxgt-data/blob/develop/packages/s3/src/bucket/operations/presign-post.spec.ts) in the repository:
254
+
255
+ | The upload | Status | `<Code>` | `<Message>` |
256
+ | --- | --- | --- | --- |
257
+ | within the policy | `204` | — | — |
258
+ | over `maxSize` | `400` | `EntityTooLarge` | `Your proposed upload exceeds the maximum allowed object size.` |
259
+ | under `minSize` | `400` | `EntityTooSmall` | `Your proposed upload is smaller than the minimum allowed object size.` |
260
+ | another `Content-Type` (another case, a `;charset`), none where the policy names one, another `key`, another `acl` | `403` | `AccessDenied` | `Invalid according to Policy: Policy Condition failed` |
261
+ | a field the policy does not name | `403` | `AccessDenied` | `Invalid according to Policy: Extra input fields: X-Amz-Meta-Foo` |
262
+ | after `expiresIn` | `403` | `AccessDenied` | `Invalid according to Policy: Policy expired` |
263
+
264
+ `maxSize` is inclusive: exactly `maxSize` bytes is stored. The type is
265
+ compared **exactly** — `IMAGE/PNG` is refused for `image/png`, and a charset
266
+ parameter makes another type — so post the `Content-Type` field as `fields`
267
+ gives it. `put`'s own guard, which compares on the essence, is the lenient
268
+ one.
269
+
270
+ ### Where it is signed for
271
+
272
+ Bun's `S3Client` presigns a GET, a PUT, a HEAD and a DELETE, and has no POST
273
+ presigning at all, so this package signs the policy itself: SigV4, HMAC-SHA256
274
+ from `node:crypto`. The endpoint, the region and the access key are read off
275
+ a URL Bun itself signs, so a presigned POST goes exactly where a presigned PUT
276
+ would — Bun signs for region `auto` at an endpoint that is not AWS's, and puts
277
+ the bucket in the host with `virtualHostedStyle`. The secret is the one
278
+ `bindBucket` was given, or Bun's own environment variables
279
+ (`S3_SECRET_ACCESS_KEY`, then `AWS_SECRET_ACCESS_KEY`), and a `sessionToken`
280
+ travels as `x-amz-security-token`.
281
+
282
+ Bun reads those variables **once, when the process starts**, and this package
283
+ reads them when the bucket is bound, so a variable changed or deleted in
284
+ between would leave the two with different secrets. Before signing, then,
285
+ `presignPost` checks its secret against Bun's, and refuses — a form the
286
+ service would refuse is never handed out:
287
+
288
+ - a variable **changed** since the process started: `presignPost` recomputes
289
+ the signature Bun put on its throwaway URL with its own secret, and refuses
290
+ with a `TypeError` when they differ
291
+ ([the secret … is not the one Bun signs with](../troubleshooting.md#presignpost-on-avatars-the-secret-access-key-this-package-would-sign-with-is-not-the-one-bun-signs-with-so-the-service-would-refuse-the-form-));
292
+ - a variable **deleted** since: Bun still signs with the secret it read, this
293
+ package has none, and `presignPost` refuses with a `TypeError`
294
+ ([no secret access key to sign with, while Bun has one](../troubleshooting.md#presignpost-on-avatars-no-secret-access-key-to-sign-with-while-bun-has-one-)).
295
+
296
+ Passing `secretAccessKey` to `bindBucket` keeps the environment out of both.
297
+
298
+ Reading that throwaway URL can fail too. When it has no credential scope, no
299
+ probe key at the end of its path, or a query value that is a malformed `%`
300
+ escape — an access key id holding a `%` that is not an escape (`AK%zz`), which
301
+ Bun writes into the URL unencoded, or a Bun that signs differently from the
302
+ 1.4.2 this package was measured on — `presignPost` throws a plain `Error`
303
+ rather than guess where to post the form or as whom
304
+ ([the URL Bun signed has no credential scope](../troubleshooting.md#presignpost-on-avatars-the-url-bun-signed-has-no-credential-scope-or-not-the-key-at-the-end-of-its-path-so-there-is-nowhere-to-post-the-form-)).
305
+ None of the three is an `S3Error`: none is the caller's input.
306
+
307
+ ## A public origin for browsers, an internal one for the server
308
+
309
+ A presigned URL is bound to the host it was signed for, and the browser opens
310
+ it. Behind a reverse proxy the browser reaches the service at one origin
311
+ (`https://media.example.com`) and the server at another
312
+ (`http://minio:9000`). Give both to `bindBucket`:
313
+
314
+ ```ts
315
+ const store = bindBucket(avatars, {
316
+ endpoint: 'http://minio:9000', // exists, put, bytes, delete, list
317
+ publicEndpoint: 'https://media.example.com', // presignGet, presignPut, presignPost
318
+ accessKeyId: process.env.S3_KEY,
319
+ secretAccessKey: process.env.S3_SECRET,
320
+ });
321
+
322
+ store.presignGet({ userId: 'u1' }); // https://media.example.com/avatars/u1.png?X-Amz-…
323
+ await store.exists({ userId: 'u1' }); // goes to http://minio:9000, no hairpin
324
+ ```
325
+
326
+ The credentials, region and bucket are the same for both; only the origin
327
+ differs. Left out (or equal to `endpoint`), everything uses `endpoint`. The
328
+ proxy must forward the `Host` header it received, since the signature covers it.
329
+
330
+ ## A URL is signed for the bound bucket, whatever the options say
331
+
332
+ `PresignOptions` carries no `bucket`, `endpoint`, `region` or credential, and
333
+ the run time signs with only the keys above — `expiresIn` and `acl`, plus
334
+ `contentDisposition` on `presignGet` (`PresignGetOptions`) — anything else is
335
+ dropped.
336
+
337
+ ```ts
338
+ import type { PresignOptions } from '@softistx/s3';
339
+
340
+ // A bag off a request body never met the types.
341
+ const bag = { expiresIn: 60, bucket: 'somewhere-else' } as PresignOptions;
342
+
343
+ store.presignGet({ userId: 'u1' }, bag); // …/avatars/u1.png, on this bucket's presign origin (`publicEndpoint` when set, else `endpoint`)
344
+ ```
345
+
346
+ Measured before that filter existed, such a bag redirected the URL: a
347
+ `bucket` key signed it for another bucket, and a credential key signed it
348
+ against another endpoint entirely.
349
+
350
+ `presignPost` reads only the options it knows, so the same bag is harmless
351
+ there too: `form.url` is still the bound bucket's.
352
+
353
+ ## A real one: upload from the browser, read it back
354
+
355
+ ```ts
356
+ import { Hono } from 'hono';
357
+ import { bindBucket, defineBucket, S3Error } from '@softistx/s3';
358
+
359
+ const avatars = defineBucket({
360
+ bucket: 'avatars',
361
+ key: (p: { userId: string }) => `${p.userId}.png`,
362
+ contentType: ['image/png', 'image/jpeg'],
363
+ maxSize: 2 * 1024 * 1024,
364
+ });
365
+
366
+ const store = bindBucket(avatars);
367
+ const app = new Hono();
368
+
369
+ // The browser posts the file straight to the service: no body through here,
370
+ // and the service refuses anything over 2 MiB or of another type.
371
+ app.post('/users/:id/avatar/upload-form', async (c) => {
372
+ const userId = c.req.param('id');
373
+ const { type } = await c.req.json<{ type: string }>();
374
+ try {
375
+ return c.json(store.presignPost({ userId }, { type, expiresIn: 120 }));
376
+ } catch (error) {
377
+ // A type off the request body the bucket does not accept.
378
+ if (error instanceof S3Error) return c.json({ error: error.code }, 400);
379
+ throw error;
380
+ }
381
+ });
382
+
383
+ // …and the browser is told, later, where to read it.
384
+ app.get('/users/:id/avatar', async (c) => {
385
+ const userId = c.req.param('id');
386
+ if (!(await store.exists({ userId }))) {
387
+ return c.json({ error: 'No avatar' }, 404);
388
+ }
389
+ return c.redirect(store.presignGet({ userId }, { expiresIn: 300 }));
390
+ });
391
+ ```
392
+
393
+ The upload route authorises the *user*; the form it hands back authorises
394
+ nothing else. `type` comes off the request body, so a type the bucket does not
395
+ accept is an `S3Error` with `code: 'WRONG_TYPE'` — answer it with a 400. Keep
396
+ `expiresIn` close to how long an upload should take.
397
+
398
+ ## Next
399
+
400
+ - [Writing](writes.md) — the guards a presigned PUT bypasses, and a POST
401
+ hands to the service.
402
+ - [Reading](reads.md) — `stat` and `exists`, for checking what was uploaded.
403
+ - [Troubleshooting](../troubleshooting.md) — a URL that 403s or expired.