| 1 | import { AwsClient } from "aws4fetch"; |
| 2 | |
| 3 | export const signStorageRead = (config: { |
| 4 | endpoint: string; |
| 5 | region: string; |
| 6 | accessKeyId: string; |
| 7 | secretAccessKey: string; |
| 8 | }) => |
| 9 | new AwsClient({ |
| 10 | accessKeyId: config.accessKeyId, |
| 11 | secretAccessKey: config.secretAccessKey, |
| 12 | region: config.region, |
| 13 | service: "s3", |
| 14 | }).sign(config.endpoint); |
| 15 | |
| 16 | export default { |
| 17 | async fetch(request: Request) { |
| 18 | if ( |
| 19 | request.headers.get("authorization") !== `Bearer ${process.env.APP_TOKEN}` |
| 20 | ) |
| 21 | return new Response("Unauthorized", { status: 401 }); |
| 22 | const client = new AwsClient({ |
| 23 | region: process.env.AWS_REGION!, |
| 24 | service: "s3", |
| 25 | accessKeyId: process.env.AWS_ACCESS_KEY_ID!, |
| 26 | secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!, |
| 27 | }); |
| 28 | const url = `${process.env.AWS_ENDPOINT_URL_S3!.replace(/\/$/, "")}/${encodeURIComponent(process.env.BUCKET_NAME!)}/native.txt`; |
| 29 | if (new URL(request.url).pathname === "/presign") { |
| 30 | const target = new URL(url); |
| 31 | target.searchParams.set("X-Amz-Expires", "60"); |
| 32 | const signed = await client.sign(target, { |
| 33 | method: "PUT", |
| 34 | aws: { signQuery: true }, |
| 35 | }); |
| 36 | return Response.json({ url: signed.url }); |
| 37 | } |
| 38 | if (request.method === "PUT") |
| 39 | return client.fetch(url, { |
| 40 | method: "PUT", |
| 41 | body: await request.arrayBuffer(), |
| 42 | }); |
| 43 | return client.fetch(url); |
| 44 | }, |
| 45 | }; |