@opensaas/stack-storage-vercel 0.30.0 → 0.31.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/.turbo/turbo-build.log +1 -1
- package/CHANGELOG.md +55 -0
- package/README.md +72 -4
- package/dist/index.d.ts +64 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +149 -33
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +189 -39
- package/tests/vercel-blob-provider.test.ts +514 -93
package/src/index.ts
CHANGED
|
@@ -1,16 +1,57 @@
|
|
|
1
|
-
import { put, del,
|
|
1
|
+
import { put, del, get, issueSignedToken, presignUrl, BlobNotFoundError } from '@vercel/blob'
|
|
2
|
+
import type { PutCommandOptions } from '@vercel/blob'
|
|
2
3
|
import { randomBytes } from 'node:crypto'
|
|
4
|
+
import path from 'node:path'
|
|
3
5
|
import type { StorageProvider, UploadOptions, UploadResult } from '@opensaas/stack-storage'
|
|
4
6
|
|
|
7
|
+
/**
|
|
8
|
+
* Derives the store ID embedded in a Vercel Blob read-write token
|
|
9
|
+
* (`vercel_blob_rw_<storeId>_<secret>`), the same way `@vercel/blob` derives
|
|
10
|
+
* it internally to build blob URLs. This format is undocumented and not a
|
|
11
|
+
* stable public API — it's parity with the SDK's internal parsing, not a
|
|
12
|
+
* contract Vercel guarantees. Returns `''` if the token doesn't match the
|
|
13
|
+
* expected shape.
|
|
14
|
+
*/
|
|
15
|
+
function parseStoreIdFromToken(token: string): string {
|
|
16
|
+
const segments = token.split('_')
|
|
17
|
+
return segments.length >= 4 ? segments[3] : ''
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Strips the `store_` prefix some store ID values are given with. */
|
|
21
|
+
function normalizeStoreId(storeId: string): string {
|
|
22
|
+
return storeId.startsWith('store_') ? storeId.slice('store_'.length) : storeId
|
|
23
|
+
}
|
|
24
|
+
|
|
5
25
|
/**
|
|
6
26
|
* Configuration for Vercel Blob storage
|
|
7
27
|
*/
|
|
8
28
|
export interface VercelBlobStorageConfig {
|
|
9
29
|
type: 'vercel-blob'
|
|
10
|
-
/**
|
|
30
|
+
/**
|
|
31
|
+
* Vercel Blob read-write token (can also be set via BLOB_READ_WRITE_TOKEN env var).
|
|
32
|
+
* Optional when using Vercel OIDC auth (`storeId`/`BLOB_STORE_ID`).
|
|
33
|
+
*/
|
|
11
34
|
token?: string
|
|
35
|
+
/**
|
|
36
|
+
* Blob store id for Vercel OIDC auth (overrides the BLOB_STORE_ID env var).
|
|
37
|
+
* When an OIDC token is available (VERCEL_OIDC_TOKEN or `oidcToken`) and a
|
|
38
|
+
* store id is set, no static read-write token is needed.
|
|
39
|
+
*/
|
|
40
|
+
storeId?: string
|
|
41
|
+
/**
|
|
42
|
+
* Explicit Vercel OIDC token (overrides the VERCEL_OIDC_TOKEN env var).
|
|
43
|
+
* Requires `storeId` or BLOB_STORE_ID.
|
|
44
|
+
*/
|
|
45
|
+
oidcToken?: string
|
|
12
46
|
/** Whether to generate unique filenames (default: true) */
|
|
13
47
|
generateUniqueFilenames?: boolean
|
|
48
|
+
/**
|
|
49
|
+
* Whether to allow overwriting an existing blob at the same pathname.
|
|
50
|
+
* The Blob API rejects overwrites unless this is sent. Defaults to `true`
|
|
51
|
+
* when `generateUniqueFilenames` is `false` (stable filenames imply replace
|
|
52
|
+
* semantics), and `false` otherwise. An explicit setting always wins.
|
|
53
|
+
*/
|
|
54
|
+
allowOverwrite?: boolean
|
|
14
55
|
/** Path prefix for all uploaded files */
|
|
15
56
|
pathPrefix?: string
|
|
16
57
|
/** Whether files should be publicly accessible (default: true) */
|
|
@@ -29,13 +70,23 @@ export class VercelBlobStorageProvider implements StorageProvider {
|
|
|
29
70
|
|
|
30
71
|
constructor(config: VercelBlobStorageConfig) {
|
|
31
72
|
this.config = config
|
|
73
|
+
// Credential resolution is delegated to the @vercel/blob SDK at call time.
|
|
74
|
+
// Eagerly requiring a static token here would break Vercel OIDC auth, where
|
|
75
|
+
// no token/BLOB_READ_WRITE_TOKEN exists and the SDK resolves credentials
|
|
76
|
+
// from VERCEL_OIDC_TOKEN (or the request context) plus storeId/BLOB_STORE_ID.
|
|
77
|
+
}
|
|
32
78
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Credential options passed to every SDK call. The SDK's precedence is:
|
|
81
|
+
* explicit `token` → OIDC token + store id → BLOB_READ_WRITE_TOKEN env var;
|
|
82
|
+
* it throws a descriptive error when none of these are available.
|
|
83
|
+
*/
|
|
84
|
+
private authOptions(): { token?: string; storeId?: string; oidcToken?: string } {
|
|
85
|
+
const auth: { token?: string; storeId?: string; oidcToken?: string } = {}
|
|
86
|
+
if (this.config.token) auth.token = this.config.token
|
|
87
|
+
if (this.config.storeId) auth.storeId = this.config.storeId
|
|
88
|
+
if (this.config.oidcToken) auth.oidcToken = this.config.oidcToken
|
|
89
|
+
return auth
|
|
39
90
|
}
|
|
40
91
|
|
|
41
92
|
/**
|
|
@@ -46,7 +97,7 @@ export class VercelBlobStorageProvider implements StorageProvider {
|
|
|
46
97
|
return originalFilename
|
|
47
98
|
}
|
|
48
99
|
|
|
49
|
-
const ext =
|
|
100
|
+
const ext = path.extname(originalFilename)
|
|
50
101
|
const uniqueId = randomBytes(16).toString('hex')
|
|
51
102
|
const timestamp = Date.now()
|
|
52
103
|
return `${timestamp}-${uniqueId}${ext}`
|
|
@@ -62,6 +113,72 @@ export class VercelBlobStorageProvider implements StorageProvider {
|
|
|
62
113
|
return filename
|
|
63
114
|
}
|
|
64
115
|
|
|
116
|
+
/**
|
|
117
|
+
* Resolves whether uploads may overwrite an existing blob at the same
|
|
118
|
+
* pathname. An explicit `allowOverwrite` always wins; otherwise stable
|
|
119
|
+
* filenames (`generateUniqueFilenames: false`) imply replace semantics and
|
|
120
|
+
* default to `true`. With generated filenames collisions aren't expected,
|
|
121
|
+
* so the key is left unset and the Blob API's own reject-by-default
|
|
122
|
+
* behavior applies.
|
|
123
|
+
*/
|
|
124
|
+
private resolveAllowOverwrite(): boolean | undefined {
|
|
125
|
+
if (this.config.allowOverwrite !== undefined) {
|
|
126
|
+
return this.config.allowOverwrite
|
|
127
|
+
}
|
|
128
|
+
return this.config.generateUniqueFilenames === false ? true : undefined
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Resolves the blob access level for this provider instance.
|
|
133
|
+
* `public` is a provider-wide config setting, so every blob uploaded
|
|
134
|
+
* (and later read) through this instance uses the same access level.
|
|
135
|
+
*/
|
|
136
|
+
private getAccess(): 'public' | 'private' {
|
|
137
|
+
return this.config.public !== false ? 'public' : 'private'
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Resolves the Vercel Blob store ID used to construct blob URLs, mirroring
|
|
142
|
+
* the SDK's own credential precedence: an explicit read-write token wins
|
|
143
|
+
* (its embedded store ID is authoritative), otherwise an explicit/env store
|
|
144
|
+
* ID is used, otherwise the store ID is parsed from the env read-write
|
|
145
|
+
* token.
|
|
146
|
+
*/
|
|
147
|
+
private resolveStoreId(): string {
|
|
148
|
+
const token = this.config.token ?? process.env.BLOB_READ_WRITE_TOKEN?.trim()
|
|
149
|
+
if (this.config.token) {
|
|
150
|
+
const storeId = parseStoreIdFromToken(this.config.token)
|
|
151
|
+
if (!storeId) {
|
|
152
|
+
throw new Error(
|
|
153
|
+
'Cannot determine the Vercel Blob store ID: the configured `token` does not match the ' +
|
|
154
|
+
'expected "vercel_blob_rw_<storeId>_<secret>" format. Pass `storeId` explicitly to construct blob URLs.',
|
|
155
|
+
)
|
|
156
|
+
}
|
|
157
|
+
return storeId
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const storeId = this.config.storeId?.trim() || process.env.BLOB_STORE_ID?.trim()
|
|
161
|
+
if (storeId) {
|
|
162
|
+
return normalizeStoreId(storeId)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (token) {
|
|
166
|
+
const parsedStoreId = parseStoreIdFromToken(token)
|
|
167
|
+
if (!parsedStoreId) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
'Cannot determine the Vercel Blob store ID: BLOB_READ_WRITE_TOKEN does not match the ' +
|
|
170
|
+
'expected "vercel_blob_rw_<storeId>_<secret>" format. Pass `storeId` explicitly to construct blob URLs.',
|
|
171
|
+
)
|
|
172
|
+
}
|
|
173
|
+
return parsedStoreId
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
throw new Error(
|
|
177
|
+
'Cannot determine the Vercel Blob store ID: configure `token`, `storeId`, BLOB_STORE_ID, or ' +
|
|
178
|
+
'BLOB_READ_WRITE_TOKEN to construct blob URLs.',
|
|
179
|
+
)
|
|
180
|
+
}
|
|
181
|
+
|
|
65
182
|
async upload(
|
|
66
183
|
file: Buffer | Uint8Array,
|
|
67
184
|
filename: string,
|
|
@@ -75,17 +192,18 @@ export class VercelBlobStorageProvider implements StorageProvider {
|
|
|
75
192
|
|
|
76
193
|
// Upload to Vercel Blob
|
|
77
194
|
const uploadOptions: PutCommandOptions = {
|
|
78
|
-
access:
|
|
79
|
-
token: this.config.token,
|
|
195
|
+
access: this.getAccess(),
|
|
80
196
|
contentType: options?.contentType,
|
|
197
|
+
...this.authOptions(),
|
|
81
198
|
}
|
|
82
199
|
|
|
83
|
-
if (this.config.
|
|
84
|
-
uploadOptions.
|
|
200
|
+
if (this.config.cacheControlMaxAge !== undefined) {
|
|
201
|
+
uploadOptions.cacheControlMaxAge = this.config.cacheControlMaxAge
|
|
85
202
|
}
|
|
86
203
|
|
|
87
|
-
|
|
88
|
-
|
|
204
|
+
const allowOverwrite = this.resolveAllowOverwrite()
|
|
205
|
+
if (allowOverwrite !== undefined) {
|
|
206
|
+
uploadOptions.allowOverwrite = allowOverwrite
|
|
89
207
|
}
|
|
90
208
|
|
|
91
209
|
const blob = await put(pathname, buffer, uploadOptions)
|
|
@@ -106,46 +224,66 @@ export class VercelBlobStorageProvider implements StorageProvider {
|
|
|
106
224
|
async download(filename: string): Promise<Buffer> {
|
|
107
225
|
const pathname = this.getFullPath(filename)
|
|
108
226
|
|
|
109
|
-
//
|
|
110
|
-
|
|
111
|
-
|
|
227
|
+
// Fetch the blob content through the SDK's authorized read path. This
|
|
228
|
+
// works for both public and private blobs (private blobs cannot be
|
|
229
|
+
// read via a plain `fetch(url)`, since the request needs a bearer
|
|
230
|
+
// token) and resolves `null` for a missing blob instead of throwing.
|
|
231
|
+
const result = await get(pathname, {
|
|
232
|
+
access: this.getAccess(),
|
|
233
|
+
...this.authOptions(),
|
|
112
234
|
})
|
|
113
235
|
|
|
114
|
-
if (!
|
|
236
|
+
if (!result) {
|
|
115
237
|
throw new Error(`File not found: ${filename}`)
|
|
116
238
|
}
|
|
117
239
|
|
|
118
|
-
|
|
119
|
-
const response = await fetch(metadata.url)
|
|
120
|
-
|
|
121
|
-
if (!response.ok) {
|
|
122
|
-
throw new Error(`Failed to download file: ${response.statusText}`)
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
const arrayBuffer = await response.arrayBuffer()
|
|
240
|
+
const arrayBuffer = await new Response(result.stream).arrayBuffer()
|
|
126
241
|
return Buffer.from(arrayBuffer)
|
|
127
242
|
}
|
|
128
243
|
|
|
129
244
|
async delete(filename: string): Promise<void> {
|
|
130
245
|
const pathname = this.getFullPath(filename)
|
|
131
246
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
await del(metadata.url, {
|
|
139
|
-
token: this.config.token,
|
|
140
|
-
})
|
|
247
|
+
try {
|
|
248
|
+
await del(pathname, this.authOptions())
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if (!(error instanceof BlobNotFoundError)) {
|
|
251
|
+
throw error
|
|
252
|
+
}
|
|
141
253
|
}
|
|
142
254
|
}
|
|
143
255
|
|
|
144
256
|
getUrl(filename: string): string {
|
|
145
|
-
// For Vercel Blob, we need to have uploaded the file first to get the URL
|
|
146
|
-
// This method is less useful for Vercel Blob, but we provide a pathname
|
|
147
257
|
const pathname = this.getFullPath(filename)
|
|
148
|
-
|
|
258
|
+
const storeId = this.resolveStoreId()
|
|
259
|
+
return `https://${storeId}.${this.getAccess()}.blob.vercel-storage.com/${pathname}`
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async getSignedUrl(filename: string, expiresIn: number = 3600): Promise<string> {
|
|
263
|
+
const pathname = this.getFullPath(filename)
|
|
264
|
+
const validUntil = Date.now() + expiresIn * 1000
|
|
265
|
+
|
|
266
|
+
const signedToken = await issueSignedToken({
|
|
267
|
+
pathname,
|
|
268
|
+
operations: ['get'],
|
|
269
|
+
validUntil,
|
|
270
|
+
...this.authOptions(),
|
|
271
|
+
})
|
|
272
|
+
|
|
273
|
+
const { presignedUrl } = await presignUrl(
|
|
274
|
+
{
|
|
275
|
+
delegationToken: signedToken.delegationToken,
|
|
276
|
+
clientSigningToken: signedToken.clientSigningToken,
|
|
277
|
+
},
|
|
278
|
+
{
|
|
279
|
+
operation: 'get',
|
|
280
|
+
pathname,
|
|
281
|
+
validUntil,
|
|
282
|
+
access: this.getAccess(),
|
|
283
|
+
},
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
return presignedUrl
|
|
149
287
|
}
|
|
150
288
|
}
|
|
151
289
|
|
|
@@ -154,6 +292,7 @@ export class VercelBlobStorageProvider implements StorageProvider {
|
|
|
154
292
|
*
|
|
155
293
|
* @example
|
|
156
294
|
* ```typescript
|
|
295
|
+
* // Static read-write token
|
|
157
296
|
* const config = config({
|
|
158
297
|
* storage: {
|
|
159
298
|
* avatars: vercelBlobStorage({
|
|
@@ -162,6 +301,17 @@ export class VercelBlobStorageProvider implements StorageProvider {
|
|
|
162
301
|
* }),
|
|
163
302
|
* },
|
|
164
303
|
* })
|
|
304
|
+
*
|
|
305
|
+
* // Vercel OIDC auth — no static token; the SDK resolves credentials from
|
|
306
|
+
* // VERCEL_OIDC_TOKEN plus the store id (config.storeId or BLOB_STORE_ID env)
|
|
307
|
+
* const config = config({
|
|
308
|
+
* storage: {
|
|
309
|
+
* avatars: vercelBlobStorage({
|
|
310
|
+
* storeId: process.env.BLOB_STORE_ID,
|
|
311
|
+
* pathPrefix: 'avatars',
|
|
312
|
+
* }),
|
|
313
|
+
* },
|
|
314
|
+
* })
|
|
165
315
|
* ```
|
|
166
316
|
*/
|
|
167
317
|
export function vercelBlobStorage(
|