|
| 1 | +import { createHash, createHmac } from 'crypto' |
1 | 2 | import { type FileUpload } from '@mjackson/form-data-parser' |
2 | 3 | import { createId } from '@paralleldrive/cuid2' |
3 | 4 |
|
4 | | -const STORAGE_ENDPOINT = process.env.STORAGE_ENDPOINT |
5 | | -const STORAGE_BUCKET = process.env.STORAGE_BUCKET |
6 | | -const STORAGE_ACCESS_KEY = process.env.STORAGE_ACCESS_KEY |
7 | | -const STORAGE_SECRET_KEY = process.env.STORAGE_SECRET_KEY |
| 5 | +const STORAGE_ENDPOINT = process.env.AWS_ENDPOINT_URL_S3 |
| 6 | +const STORAGE_BUCKET = process.env.BUCKET_NAME |
| 7 | +const STORAGE_ACCESS_KEY = process.env.AWS_ACCESS_KEY_ID |
| 8 | +const STORAGE_SECRET_KEY = process.env.AWS_SECRET_ACCESS_KEY |
| 9 | +const STORAGE_REGION = process.env.AWS_REGION |
8 | 10 |
|
9 | 11 | async function uploadToStorage(file: File | FileUpload, key: string) { |
10 | | - const url = getImageUrl(key) |
| 12 | + const { url, headers } = getSignedPutRequestInfo(file, key) |
| 13 | + |
11 | 14 | const uploadResponse = await fetch(url, { |
12 | 15 | method: 'PUT', |
13 | | - headers: { |
14 | | - 'Content-Type': file.type, |
15 | | - Authorization: `Basic ${btoa(`${STORAGE_ACCESS_KEY}:${STORAGE_SECRET_KEY}`)}`, |
16 | | - 'x-amz-meta-upload-date': new Date().toISOString(), |
17 | | - }, |
| 16 | + headers, |
18 | 17 | body: file instanceof File ? file : Buffer.from(await file.arrayBuffer()), |
19 | 18 | }) |
20 | 19 |
|
@@ -50,6 +49,123 @@ export async function uploadNoteImage( |
50 | 49 | return uploadToStorage(file, key) |
51 | 50 | } |
52 | 51 |
|
53 | | -export function getImageUrl(imageId: string) { |
| 52 | +function getImageUrl(imageId: string) { |
54 | 53 | return `${STORAGE_ENDPOINT}/${STORAGE_BUCKET}/${imageId}` |
55 | 54 | } |
| 55 | + |
| 56 | +function hmacSha256(key: string | Buffer, message: string) { |
| 57 | + const hmac = createHmac('sha256', key) |
| 58 | + hmac.update(message) |
| 59 | + return hmac.digest() |
| 60 | +} |
| 61 | + |
| 62 | +function sha256(message: string) { |
| 63 | + const hash = createHash('sha256') |
| 64 | + hash.update(message) |
| 65 | + return hash.digest('hex') |
| 66 | +} |
| 67 | + |
| 68 | +function getSignatureKey( |
| 69 | + key: string, |
| 70 | + dateStamp: string, |
| 71 | + regionName: string, |
| 72 | + serviceName: string, |
| 73 | +) { |
| 74 | + const kDate = hmacSha256(`AWS4${key}`, dateStamp) |
| 75 | + const kRegion = hmacSha256(kDate, regionName) |
| 76 | + const kService = hmacSha256(kRegion, serviceName) |
| 77 | + const kSigning = hmacSha256(kService, 'aws4_request') |
| 78 | + return kSigning |
| 79 | +} |
| 80 | + |
| 81 | +function getBaseSignedRequestInfo({ |
| 82 | + method, |
| 83 | + key, |
| 84 | + contentType, |
| 85 | + uploadDate, |
| 86 | +}: { |
| 87 | + method: 'GET' | 'PUT' |
| 88 | + key: string |
| 89 | + contentType?: string |
| 90 | + uploadDate?: string |
| 91 | +}) { |
| 92 | + const url = getImageUrl(key) |
| 93 | + const endpoint = new URL(url) |
| 94 | + |
| 95 | + // Prepare date strings |
| 96 | + const amzDate = new Date().toISOString().replace(/[:-]|\.\d{3}/g, '') |
| 97 | + const dateStamp = amzDate.slice(0, 8) |
| 98 | + |
| 99 | + // Build headers array conditionally |
| 100 | + const headers = [ |
| 101 | + ...(contentType ? [`content-type:${contentType}`] : []), |
| 102 | + `host:${endpoint.host}`, |
| 103 | + `x-amz-content-sha256:UNSIGNED-PAYLOAD`, |
| 104 | + `x-amz-date:${amzDate}`, |
| 105 | + ...(uploadDate ? [`x-amz-meta-upload-date:${uploadDate}`] : []), |
| 106 | + ] |
| 107 | + |
| 108 | + const canonicalHeaders = headers.join('\n') + '\n' |
| 109 | + const signedHeaders = headers.map((h) => h.split(':')[0]).join(';') |
| 110 | + |
| 111 | + const canonicalRequest = [ |
| 112 | + method, |
| 113 | + `/${STORAGE_BUCKET}/${key}`, |
| 114 | + '', // canonicalQueryString |
| 115 | + canonicalHeaders, |
| 116 | + signedHeaders, |
| 117 | + 'UNSIGNED-PAYLOAD', |
| 118 | + ].join('\n') |
| 119 | + |
| 120 | + // Prepare string to sign |
| 121 | + const algorithm = 'AWS4-HMAC-SHA256' |
| 122 | + const credentialScope = `${dateStamp}/${STORAGE_REGION}/s3/aws4_request` |
| 123 | + const stringToSign = [ |
| 124 | + algorithm, |
| 125 | + amzDate, |
| 126 | + credentialScope, |
| 127 | + sha256(canonicalRequest), |
| 128 | + ].join('\n') |
| 129 | + |
| 130 | + // Calculate signature |
| 131 | + const signingKey = getSignatureKey( |
| 132 | + STORAGE_SECRET_KEY, |
| 133 | + dateStamp, |
| 134 | + STORAGE_REGION, |
| 135 | + 's3', |
| 136 | + ) |
| 137 | + const signature = createHmac('sha256', signingKey) |
| 138 | + .update(stringToSign) |
| 139 | + .digest('hex') |
| 140 | + |
| 141 | + const baseHeaders = { |
| 142 | + 'X-Amz-Date': amzDate, |
| 143 | + 'X-Amz-Content-SHA256': 'UNSIGNED-PAYLOAD', |
| 144 | + Authorization: [ |
| 145 | + `${algorithm} Credential=${STORAGE_ACCESS_KEY}/${credentialScope}`, |
| 146 | + `SignedHeaders=${signedHeaders}`, |
| 147 | + `Signature=${signature}`, |
| 148 | + ].join(', '), |
| 149 | + } |
| 150 | + |
| 151 | + return { url, baseHeaders } |
| 152 | +} |
| 153 | + |
| 154 | +function getSignedPutRequestInfo(file: File | FileUpload, key: string) { |
| 155 | + const uploadDate = new Date().toISOString() |
| 156 | + const { url, baseHeaders } = getBaseSignedRequestInfo({ |
| 157 | + method: 'PUT', |
| 158 | + key, |
| 159 | + contentType: file.type, |
| 160 | + uploadDate, |
| 161 | + }) |
| 162 | + |
| 163 | + return { |
| 164 | + url, |
| 165 | + headers: { |
| 166 | + ...baseHeaders, |
| 167 | + 'Content-Type': file.type, |
| 168 | + 'X-Amz-Meta-Upload-Date': uploadDate, |
| 169 | + }, |
| 170 | + } |
| 171 | +} |
0 commit comments