@edgestore/server 1.0.0-next.5 → 1.0.0-rc.7
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/README.md +2 -2
- package/agent-docs/README.md +1 -1
- package/agent-docs/astro.md +3 -3
- package/agent-docs/backend-client.md +5 -8
- package/agent-docs/express.md +3 -3
- package/agent-docs/fastify.md +3 -3
- package/agent-docs/hono.md +3 -3
- package/agent-docs/next.md +3 -3
- package/agent-docs/provider-azure-blob.md +150 -57
- package/agent-docs/provider-custom.md +29 -3
- package/agent-docs/provider-edgestore.md +2 -2
- package/agent-docs/provider-s3.md +124 -24
- package/agent-docs/remix.md +3 -3
- package/agent-docs/tanstack-start.md +3 -3
- package/dist/adapters/dispatcher.d.ts.map +1 -1
- package/dist/adapters/dispatcher.js +10 -1
- package/dist/adapters/shared.d.ts +25 -103
- package/dist/adapters/shared.d.ts.map +1 -1
- package/dist/adapters/shared.js +157 -110
- package/dist/core/client/index.d.ts +0 -4
- package/dist/core/client/index.d.ts.map +1 -1
- package/dist/core/provider.d.ts +0 -1
- package/dist/core/provider.d.ts.map +1 -1
- package/dist/core/provider.js +1 -4
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/libs/env.d.ts.map +1 -1
- package/dist/libs/env.js +3 -0
- package/dist/libs/errors/EdgeStoreCredentialsError.js +1 -1
- package/dist/providers/azure-blob/blocks.d.ts +48 -0
- package/dist/providers/azure-blob/blocks.d.ts.map +1 -0
- package/dist/providers/azure-blob/blocks.js +126 -0
- package/dist/providers/azure-blob/index.d.ts +76 -51
- package/dist/providers/azure-blob/index.d.ts.map +1 -1
- package/dist/providers/azure-blob/index.js +189 -107
- package/dist/providers/edgestore/index.d.ts +41 -24
- package/dist/providers/edgestore/index.d.ts.map +1 -1
- package/dist/providers/edgestore/index.js +33 -20
- package/dist/providers/s3/backendUpload.d.ts +2 -5
- package/dist/providers/s3/backendUpload.d.ts.map +1 -1
- package/dist/providers/s3/backendUpload.js +19 -57
- package/dist/providers/s3/index.d.ts +3 -12
- package/dist/providers/s3/index.d.ts.map +1 -1
- package/dist/providers/s3/index.js +24 -45
- package/dist/providers/s3/multipart.d.ts +3 -5
- package/dist/providers/s3/multipart.d.ts.map +1 -1
- package/dist/providers/s3/multipart.js +26 -62
- package/dist/providers/s3/options.d.ts +13 -35
- package/dist/providers/s3/options.d.ts.map +1 -1
- package/dist/providers/storage/multipartSession.d.ts +51 -0
- package/dist/providers/storage/multipartSession.d.ts.map +1 -0
- package/dist/providers/storage/multipartSession.js +83 -0
- package/dist/providers/storage/objectKeys.d.ts +41 -0
- package/dist/providers/storage/objectKeys.d.ts.map +1 -0
- package/dist/providers/{s3/keys.js → storage/objectKeys.js} +31 -4
- package/dist/providers/storage/transfer.d.ts +18 -0
- package/dist/providers/storage/transfer.d.ts.map +1 -0
- package/dist/providers/storage/transfer.js +69 -0
- package/dist/test-utils/edgestoreSmoke.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/package.json +4 -11
- package/src/adapters/dispatcher.ts +14 -0
- package/src/adapters/shared.ts +179 -127
- package/src/core/client/index.ts +0 -4
- package/src/core/provider.ts +0 -8
- package/src/index.ts +3 -8
- package/src/libs/env.ts +9 -0
- package/src/libs/errors/EdgeStoreCredentialsError.ts +1 -1
- package/src/providers/azure-blob/blocks.ts +201 -0
- package/src/providers/azure-blob/index.ts +289 -171
- package/src/providers/edgestore/index.ts +30 -26
- package/src/providers/s3/backendUpload.ts +20 -55
- package/src/providers/s3/index.ts +32 -59
- package/src/providers/s3/multipart.ts +36 -94
- package/src/providers/s3/options.ts +13 -36
- package/src/providers/storage/multipartSession.ts +145 -0
- package/src/providers/storage/objectKeys.ts +106 -0
- package/src/providers/storage/transfer.ts +105 -0
- package/src/test-utils/edgestoreSmoke.ts +3 -5
- package/src/version.ts +1 -1
- package/core/index.d.ts +0 -1
- package/core/index.js +0 -1
- package/dist/core/index.d.ts +0 -4
- package/dist/core/index.d.ts.map +0 -1
- package/dist/core/index.js +0 -3
- package/dist/providers/s3/keys.d.ts +0 -10
- package/dist/providers/s3/keys.d.ts.map +0 -1
- package/src/core/index.ts +0 -9
- package/src/providers/s3/keys.ts +0 -59
package/src/adapters/shared.ts
CHANGED
|
@@ -9,14 +9,13 @@ import {
|
|
|
9
9
|
type SharedInitRes,
|
|
10
10
|
type SharedRequestUploadPartsRes,
|
|
11
11
|
type SharedRequestUploadRes,
|
|
12
|
+
type SharedUploadStatusRes,
|
|
12
13
|
} from '@edgestore/shared';
|
|
13
|
-
import { hkdf } from '@panva/hkdf';
|
|
14
14
|
import { stringifySetCookie } from 'cookie';
|
|
15
15
|
import { EncryptJWT, jwtDecrypt } from 'jose';
|
|
16
16
|
import { z } from 'zod';
|
|
17
17
|
import {
|
|
18
18
|
assertSupportedUploadOptions,
|
|
19
|
-
getProviderBaseUrl,
|
|
20
19
|
referenceFromUrl,
|
|
21
20
|
} from '../core/provider';
|
|
22
21
|
import { buildPath, parseBucketInput, parsePath } from '../core/routerRules';
|
|
@@ -90,31 +89,17 @@ type ResolvedCookieConfig = {
|
|
|
90
89
|
export function getCookieConfig(
|
|
91
90
|
cookieConfig?: CookieConfig,
|
|
92
91
|
): ResolvedCookieConfig {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
const mergeOptions = (configOptions?: CookieOptions): CookieOptions => {
|
|
100
|
-
const merged = { ...defaultOptions };
|
|
101
|
-
|
|
102
|
-
if (configOptions) {
|
|
103
|
-
Object.keys(configOptions).forEach((key) => {
|
|
104
|
-
const value = configOptions[key as keyof CookieOptions];
|
|
105
|
-
if (value !== undefined) {
|
|
106
|
-
(merged as any)[key] = value;
|
|
107
|
-
}
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
return merged;
|
|
112
|
-
};
|
|
92
|
+
// Explicit `undefined` options keep their defaults.
|
|
93
|
+
const configured = Object.fromEntries(
|
|
94
|
+
Object.entries(cookieConfig?.ctx?.options ?? {}).filter(
|
|
95
|
+
([, value]) => value !== undefined,
|
|
96
|
+
),
|
|
97
|
+
);
|
|
113
98
|
|
|
114
99
|
return {
|
|
115
100
|
ctx: {
|
|
116
101
|
name: cookieConfig?.ctx?.name ?? 'edgestore-ctx',
|
|
117
|
-
options:
|
|
102
|
+
options: { path: '/', maxAge: DEFAULT_MAX_AGE, ...configured },
|
|
118
103
|
},
|
|
119
104
|
};
|
|
120
105
|
}
|
|
@@ -132,7 +117,7 @@ export async function init<TCtx extends AnyContext>(params: {
|
|
|
132
117
|
const resolvedCookieConfig = getCookieConfig(cookieConfig);
|
|
133
118
|
|
|
134
119
|
const ctxToken = await encryptJWT(ctx);
|
|
135
|
-
const
|
|
120
|
+
const { clientInit } = await provider.init({ ctx, router });
|
|
136
121
|
const newCookies = [
|
|
137
122
|
stringifySetCookie({
|
|
138
123
|
name: resolvedCookieConfig.ctx.name,
|
|
@@ -140,22 +125,10 @@ export async function init<TCtx extends AnyContext>(params: {
|
|
|
140
125
|
...resolvedCookieConfig.ctx.options,
|
|
141
126
|
}),
|
|
142
127
|
];
|
|
143
|
-
const baseUrl = initRes.baseUrl ?? (await getProviderBaseUrl(provider));
|
|
144
|
-
|
|
145
|
-
logger.debug('Finished [init]', {
|
|
146
|
-
ctx,
|
|
147
|
-
newCookies,
|
|
148
|
-
baseUrl,
|
|
149
|
-
providerName: provider.name,
|
|
150
|
-
clientInit: initRes.clientInit,
|
|
151
|
-
});
|
|
152
128
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
providerName: provider.name,
|
|
157
|
-
clientInit: initRes.clientInit,
|
|
158
|
-
};
|
|
129
|
+
logger.debug('Finished [init]', { ctx, newCookies, clientInit });
|
|
130
|
+
|
|
131
|
+
return { newCookies, clientInit };
|
|
159
132
|
}
|
|
160
133
|
|
|
161
134
|
const nonEmptyStringSchema = z.string().min(1);
|
|
@@ -164,7 +137,7 @@ export const requestUploadBodySchema = z.object({
|
|
|
164
137
|
bucketName: nonEmptyStringSchema,
|
|
165
138
|
input: z.unknown(),
|
|
166
139
|
fileInfo: z.object({
|
|
167
|
-
size: z.number().
|
|
140
|
+
size: z.number().int().nonnegative(),
|
|
168
141
|
type: z.string(),
|
|
169
142
|
extension: z.string(),
|
|
170
143
|
fileName: z.string().optional(),
|
|
@@ -191,23 +164,9 @@ export async function requestUpload<TCtx extends AnyContext>(params: {
|
|
|
191
164
|
} = params;
|
|
192
165
|
logger.debug('Running [requestUpload]', { bucketName, input, fileInfo });
|
|
193
166
|
|
|
194
|
-
if (!ctxToken) {
|
|
195
|
-
throw new EdgeStoreError({
|
|
196
|
-
message: 'Missing edgestore-ctx cookie',
|
|
197
|
-
code: 'UNAUTHORIZED',
|
|
198
|
-
});
|
|
199
|
-
}
|
|
200
167
|
const ctx = await getContext(ctxToken);
|
|
201
|
-
|
|
202
168
|
logger.debug('Decrypted Context', { ctx });
|
|
203
|
-
|
|
204
|
-
const bucket = router.buckets[bucketName];
|
|
205
|
-
if (!bucket) {
|
|
206
|
-
throw new EdgeStoreError({
|
|
207
|
-
message: `Bucket ${bucketName} not found`,
|
|
208
|
-
code: 'BAD_REQUEST',
|
|
209
|
-
});
|
|
210
|
-
}
|
|
169
|
+
const bucket = getBucket(router, bucketName);
|
|
211
170
|
assertSupportedUploadOptions(provider, fileInfo);
|
|
212
171
|
const parsedInput = await parseBucketInput(bucket, input);
|
|
213
172
|
if (bucket._def.beforeUpload) {
|
|
@@ -266,16 +225,77 @@ export async function requestUpload<TCtx extends AnyContext>(params: {
|
|
|
266
225
|
autoSignedUrls,
|
|
267
226
|
});
|
|
268
227
|
const { parsedPath, pathOrder } = parsePath(path);
|
|
228
|
+
const statusToken =
|
|
229
|
+
provider.uploads.getStatus && requestUploadRes.id
|
|
230
|
+
? await encryptStatusToken({ id: requestUploadRes.id, bucketName })
|
|
231
|
+
: undefined;
|
|
269
232
|
|
|
270
233
|
logger.debug('Finished [requestUpload]');
|
|
271
234
|
|
|
272
235
|
return {
|
|
273
236
|
...requestUploadRes,
|
|
274
237
|
size: fileInfo.size,
|
|
275
|
-
uploadedAt: new Date().toISOString(), // TODO: maybe delete this field since it's not the actual upload time
|
|
276
238
|
path: parsedPath,
|
|
277
239
|
pathOrder,
|
|
278
240
|
metadata,
|
|
241
|
+
statusToken,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export const uploadStatusBodySchema = z.object({
|
|
246
|
+
statusToken: nonEmptyStringSchema,
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
export type UploadStatusBody = z.infer<typeof uploadStatusBodySchema>;
|
|
250
|
+
|
|
251
|
+
/** Reports processing state for an upload authorized by its status token. */
|
|
252
|
+
export async function getUploadStatus<TCtx extends AnyContext>(params: {
|
|
253
|
+
provider: AnyEdgeStoreProvider;
|
|
254
|
+
router: EdgeStoreRouter<TCtx>;
|
|
255
|
+
ctxToken: string | undefined;
|
|
256
|
+
body: UploadStatusBody;
|
|
257
|
+
logger: LoggerLike;
|
|
258
|
+
}): Promise<SharedUploadStatusRes> {
|
|
259
|
+
const { provider, router, ctxToken, logger, body } = params;
|
|
260
|
+
|
|
261
|
+
await getContext(ctxToken);
|
|
262
|
+
const { id, bucketName } = await decryptStatusToken(body.statusToken);
|
|
263
|
+
logger.debug('Running [getUploadStatus]', { bucketName, id });
|
|
264
|
+
const bucket = getBucket(router, bucketName);
|
|
265
|
+
|
|
266
|
+
if (!provider.uploads.getStatus) {
|
|
267
|
+
throw new EdgeStoreError({
|
|
268
|
+
message: `Provider ${provider.name} does not report upload status.`,
|
|
269
|
+
code: 'BAD_REQUEST',
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
const result = await provider.uploads.getStatus({ bucketName, id });
|
|
273
|
+
|
|
274
|
+
logger.debug('Finished [getUploadStatus]', { status: result.status });
|
|
275
|
+
|
|
276
|
+
if (result.status !== 'completed') return { status: result.status };
|
|
277
|
+
const { url, key, thumbnailUrl, sizeBytes } = result.file;
|
|
278
|
+
// Processing may add a thumbnail that the upload response could not sign.
|
|
279
|
+
const { autoSignedUrls } = bucket._def;
|
|
280
|
+
const [signed] =
|
|
281
|
+
autoSignedUrls && provider.files.getSignedUrls
|
|
282
|
+
? await provider.files.getSignedUrls({
|
|
283
|
+
bucketName,
|
|
284
|
+
files: [await referenceFromUrl(provider, url)],
|
|
285
|
+
...autoSignedUrls,
|
|
286
|
+
})
|
|
287
|
+
: [];
|
|
288
|
+
return {
|
|
289
|
+
status: 'completed',
|
|
290
|
+
file: { url, key, thumbnailUrl: thumbnailUrl ?? null, size: sizeBytes },
|
|
291
|
+
...(signed && {
|
|
292
|
+
signedReadUrl: {
|
|
293
|
+
signedUrl: signed.signedUrl,
|
|
294
|
+
signedThumbnailUrl: signed.signedThumbnailUrl ?? null,
|
|
295
|
+
expiresAt: signed.expiresAt,
|
|
296
|
+
expiresIn: signed.expiresIn,
|
|
297
|
+
},
|
|
298
|
+
}),
|
|
279
299
|
};
|
|
280
300
|
}
|
|
281
301
|
|
|
@@ -300,7 +320,7 @@ export const completeMultipartUploadBodySchema =
|
|
|
300
320
|
parts: z.array(
|
|
301
321
|
z.object({
|
|
302
322
|
partNumber: z.number().int().positive(),
|
|
303
|
-
eTag: nonEmptyStringSchema,
|
|
323
|
+
eTag: nonEmptyStringSchema.optional(),
|
|
304
324
|
}),
|
|
305
325
|
),
|
|
306
326
|
});
|
|
@@ -332,19 +352,8 @@ async function getMultipartUploads<TCtx extends AnyContext>({
|
|
|
332
352
|
ctxToken,
|
|
333
353
|
body: { bucketName },
|
|
334
354
|
}: MultipartRequest<TCtx, { bucketName: string }>) {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
message: 'Missing edgestore-ctx cookie',
|
|
338
|
-
code: 'UNAUTHORIZED',
|
|
339
|
-
});
|
|
340
|
-
}
|
|
341
|
-
await getContext(ctxToken); // just to check if the token is valid
|
|
342
|
-
if (!router.buckets[bucketName]) {
|
|
343
|
-
throw new EdgeStoreError({
|
|
344
|
-
message: `Bucket ${bucketName} not found`,
|
|
345
|
-
code: 'BAD_REQUEST',
|
|
346
|
-
});
|
|
347
|
-
}
|
|
355
|
+
await getContext(ctxToken);
|
|
356
|
+
getBucket(router, bucketName);
|
|
348
357
|
const multipartUploads = provider.uploads.multipart;
|
|
349
358
|
if (!multipartUploads) {
|
|
350
359
|
throw new EdgeStoreError({
|
|
@@ -423,20 +432,8 @@ export async function confirmUploads<TCtx extends AnyContext>(params: {
|
|
|
423
432
|
|
|
424
433
|
logger.debug('Running [confirmUploads]', { bucketName, urls });
|
|
425
434
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
message: 'Missing edgestore-ctx cookie',
|
|
429
|
-
code: 'UNAUTHORIZED',
|
|
430
|
-
});
|
|
431
|
-
}
|
|
432
|
-
await getContext(ctxToken); // just to check if the token is valid
|
|
433
|
-
const bucket = router.buckets[bucketName];
|
|
434
|
-
if (!bucket) {
|
|
435
|
-
throw new EdgeStoreError({
|
|
436
|
-
message: `Bucket ${bucketName} not found`,
|
|
437
|
-
code: 'BAD_REQUEST',
|
|
438
|
-
});
|
|
439
|
-
}
|
|
435
|
+
await getContext(ctxToken);
|
|
436
|
+
getBucket(router, bucketName);
|
|
440
437
|
|
|
441
438
|
if (!provider.files.confirm) {
|
|
442
439
|
throw new EdgeStoreError({
|
|
@@ -480,20 +477,8 @@ export async function deleteFiles<TCtx extends AnyContext>(params: {
|
|
|
480
477
|
|
|
481
478
|
logger.debug('Running [deleteFiles]', { bucketName, urls });
|
|
482
479
|
|
|
483
|
-
if (!ctxToken) {
|
|
484
|
-
throw new EdgeStoreError({
|
|
485
|
-
message: 'Missing edgestore-ctx cookie',
|
|
486
|
-
code: 'UNAUTHORIZED',
|
|
487
|
-
});
|
|
488
|
-
}
|
|
489
480
|
const ctx = await getContext(ctxToken);
|
|
490
|
-
const bucket = router
|
|
491
|
-
if (!bucket) {
|
|
492
|
-
throw new EdgeStoreError({
|
|
493
|
-
message: `Bucket ${bucketName} not found`,
|
|
494
|
-
code: 'BAD_REQUEST',
|
|
495
|
-
});
|
|
496
|
-
}
|
|
481
|
+
const bucket = getBucket(router, bucketName);
|
|
497
482
|
|
|
498
483
|
if (!bucket._def.beforeDelete) {
|
|
499
484
|
throw new EdgeStoreError({
|
|
@@ -580,38 +565,88 @@ function mapFrontendMutationResult(
|
|
|
580
565
|
return { succeeded, failed };
|
|
581
566
|
}
|
|
582
567
|
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
568
|
+
function getBucket<TCtx extends AnyContext>(
|
|
569
|
+
router: EdgeStoreRouter<TCtx>,
|
|
570
|
+
bucketName: string,
|
|
571
|
+
) {
|
|
572
|
+
const bucket = router.buckets[bucketName];
|
|
573
|
+
if (!bucket) {
|
|
587
574
|
throw new EdgeStoreError({
|
|
588
|
-
message:
|
|
589
|
-
code: '
|
|
575
|
+
message: `Bucket ${bucketName} not found`,
|
|
576
|
+
code: 'BAD_REQUEST',
|
|
590
577
|
});
|
|
591
578
|
}
|
|
592
|
-
|
|
579
|
+
return bucket;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
async function encryptJWT(ctx: AnyContext) {
|
|
593
583
|
return await new EncryptJWT({ ctx })
|
|
594
584
|
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
|
|
595
585
|
.setIssuedAt()
|
|
596
586
|
.setExpirationTime(Date.now() / 1000 + DEFAULT_MAX_AGE)
|
|
597
587
|
.setJti(crypto.randomUUID())
|
|
598
|
-
.encrypt(
|
|
588
|
+
.encrypt(await getEncryptionKey());
|
|
599
589
|
}
|
|
600
590
|
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
591
|
+
/**
|
|
592
|
+
* Status tokens bind one upload to the browser that requested it. They never
|
|
593
|
+
* reach application code, so they carry no expiry: uploads can take arbitrarily
|
|
594
|
+
* long, and the client bounds how long it waits for processing.
|
|
595
|
+
*/
|
|
596
|
+
async function encryptStatusToken(upload: { id: string; bucketName: string }) {
|
|
597
|
+
return await new EncryptJWT({ upload })
|
|
598
|
+
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
|
|
599
|
+
.encrypt(await getEncryptionKey());
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const statusTokenPayloadSchema = z.object({
|
|
603
|
+
upload: z.object({
|
|
604
|
+
id: nonEmptyStringSchema,
|
|
605
|
+
bucketName: nonEmptyStringSchema,
|
|
606
|
+
}),
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
async function decryptStatusToken(token: string) {
|
|
610
|
+
const invalid = (cause?: Error) =>
|
|
611
|
+
new EdgeStoreError({
|
|
612
|
+
message: 'Invalid upload status token',
|
|
613
|
+
code: 'BAD_REQUEST',
|
|
614
|
+
cause,
|
|
615
|
+
});
|
|
616
|
+
const { payload } = await jwtDecrypt(token, await getEncryptionKey()).catch(
|
|
617
|
+
(error: unknown) => {
|
|
618
|
+
throw invalid(error instanceof Error ? error : undefined);
|
|
619
|
+
},
|
|
620
|
+
);
|
|
621
|
+
const result = statusTokenPayloadSchema.safeParse(payload);
|
|
622
|
+
if (!result.success) throw invalid(result.error);
|
|
623
|
+
return result.data.upload;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const contextPayloadSchema = z.object({
|
|
627
|
+
ctx: z.record(z.string(), z.string()),
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
/** Decrypts and validates the `edgestore-ctx` cookie set by `/init`. */
|
|
631
|
+
async function getContext(token: string | undefined) {
|
|
632
|
+
if (!token) {
|
|
605
633
|
throw new EdgeStoreError({
|
|
606
|
-
message: '
|
|
607
|
-
code: '
|
|
634
|
+
message: 'Missing edgestore-ctx cookie',
|
|
635
|
+
code: 'UNAUTHORIZED',
|
|
608
636
|
});
|
|
609
637
|
}
|
|
610
|
-
const
|
|
611
|
-
const
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
638
|
+
const key = await getEncryptionKey();
|
|
639
|
+
const payload = await jwtDecrypt(token, key, { clockTolerance: 15 }).then(
|
|
640
|
+
(result) => result.payload,
|
|
641
|
+
(error: unknown) => {
|
|
642
|
+
throw new EdgeStoreError({
|
|
643
|
+
message: 'Invalid edgestore-ctx cookie',
|
|
644
|
+
code: 'UNAUTHORIZED',
|
|
645
|
+
cause: error instanceof Error ? error : undefined,
|
|
646
|
+
});
|
|
647
|
+
},
|
|
648
|
+
);
|
|
649
|
+
const result = contextPayloadSchema.safeParse(payload);
|
|
615
650
|
if (!result.success) {
|
|
616
651
|
throw new EdgeStoreError({
|
|
617
652
|
message: 'Invalid edgestore-ctx cookie',
|
|
@@ -622,16 +657,33 @@ async function decryptJWT(token: string) {
|
|
|
622
657
|
return result.data.ctx;
|
|
623
658
|
}
|
|
624
659
|
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
660
|
+
/** Derives the context-cookie encryption key from the configured secret. */
|
|
661
|
+
async function getEncryptionKey() {
|
|
662
|
+
const secret =
|
|
663
|
+
getEnv('EDGESTORE_JWT_SECRET') ?? getEnv('EDGESTORE_SECRET_KEY');
|
|
664
|
+
if (!secret) {
|
|
665
|
+
throw new EdgeStoreError({
|
|
666
|
+
message: 'EDGESTORE_JWT_SECRET or EDGESTORE_SECRET_KEY is not defined',
|
|
667
|
+
code: 'SERVER_ERROR',
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
const encoder = new TextEncoder();
|
|
671
|
+
const material = await crypto.subtle.importKey(
|
|
672
|
+
'raw',
|
|
673
|
+
encoder.encode(secret),
|
|
674
|
+
'HKDF',
|
|
675
|
+
false,
|
|
676
|
+
['deriveBits'],
|
|
632
677
|
);
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
678
|
+
const bits = await crypto.subtle.deriveBits(
|
|
679
|
+
{
|
|
680
|
+
name: 'HKDF',
|
|
681
|
+
hash: 'SHA-256',
|
|
682
|
+
salt: new Uint8Array(),
|
|
683
|
+
info: encoder.encode('EdgeStore Generated Encryption Key'),
|
|
684
|
+
},
|
|
685
|
+
material,
|
|
686
|
+
256,
|
|
687
|
+
);
|
|
688
|
+
return new Uint8Array(bits);
|
|
637
689
|
}
|
package/src/core/client/index.ts
CHANGED
|
@@ -427,7 +427,3 @@ export type InferClientOutputs<TRouter extends { readonly client: object }> = {
|
|
|
427
427
|
>;
|
|
428
428
|
};
|
|
429
429
|
};
|
|
430
|
-
|
|
431
|
-
/** @deprecated Use {@link InferClientOutputs} instead. */
|
|
432
|
-
export type InferClientResponse<TRouter extends { readonly client: object }> =
|
|
433
|
-
InferClientOutputs<TRouter>;
|
package/src/core/provider.ts
CHANGED
|
@@ -51,14 +51,6 @@ export function assertSupportedUploadOptions(
|
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
export async function getProviderBaseUrl(
|
|
55
|
-
provider: AnyEdgeStoreProvider,
|
|
56
|
-
): Promise<string> {
|
|
57
|
-
return typeof provider.baseUrl === 'function'
|
|
58
|
-
? await provider.baseUrl()
|
|
59
|
-
: provider.baseUrl;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
54
|
export async function referenceFromUrl<TProvider extends AnyEdgeStoreProvider>(
|
|
63
55
|
provider: TProvider,
|
|
64
56
|
url: string,
|
package/src/index.ts
CHANGED
|
@@ -1,9 +1,4 @@
|
|
|
1
1
|
export { initEdgeStore, type ConfiguredRouter } from './core/router';
|
|
2
|
-
export {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
type InferClientInputs,
|
|
6
|
-
type InferClientOutputs,
|
|
7
|
-
type InferClientResponse,
|
|
8
|
-
EdgeStoreFileMutationError,
|
|
9
|
-
} from './core';
|
|
2
|
+
export { defineProvider } from './core/provider';
|
|
3
|
+
export type * from './core/client';
|
|
4
|
+
export { EdgeStoreFileMutationError } from './core/client';
|
package/src/libs/env.ts
CHANGED
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
export function getEnv(key: string): string | undefined {
|
|
2
|
+
return (
|
|
3
|
+
readEnv(key) ??
|
|
4
|
+
(key.startsWith('EDGESTORE_')
|
|
5
|
+
? readEnv(key.replace('EDGESTORE_', 'EDGE_STORE_'))
|
|
6
|
+
: undefined)
|
|
7
|
+
);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function readEnv(key: string): string | undefined {
|
|
2
11
|
if (typeof process !== 'undefined' && process.env) {
|
|
3
12
|
// @ts-expect-error - In Vite/Astro, env variables are available on import.meta.
|
|
4
13
|
return process.env[key] ?? import.meta.env?.[key];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const DEFAULT_MESSAGE = `Missing
|
|
1
|
+
const DEFAULT_MESSAGE = `Missing EDGESTORE_ACCESS_KEY or EDGESTORE_SECRET_KEY.
|
|
2
2
|
This can happen if you are trying to import something related to the backend of EdgeStore in a client component.`;
|
|
3
3
|
|
|
4
4
|
class EdgeStoreCredentialsError extends Error {
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/* eslint-disable unicorn/filename-case -- Lives in the public `azure-blob` provider directory. */
|
|
2
|
+
import type {
|
|
3
|
+
BlobHTTPHeaders,
|
|
4
|
+
BlockBlobClient,
|
|
5
|
+
Metadata,
|
|
6
|
+
} from '@azure/storage-blob';
|
|
7
|
+
import { type MultipartUploadPlan } from '@edgestore/sdk';
|
|
8
|
+
import {
|
|
9
|
+
EdgeStoreError,
|
|
10
|
+
type BackendUploadParams,
|
|
11
|
+
type ProviderMultipartUploads,
|
|
12
|
+
} from '@edgestore/shared';
|
|
13
|
+
import { z } from 'zod';
|
|
14
|
+
import {
|
|
15
|
+
assertValidParts,
|
|
16
|
+
initialPartNumbers,
|
|
17
|
+
partLength,
|
|
18
|
+
sessionFromPlan,
|
|
19
|
+
type createMultipartSessions,
|
|
20
|
+
type MultipartSession,
|
|
21
|
+
} from '../storage/multipartSession';
|
|
22
|
+
import { createProgress, readPart, runConcurrently } from '../storage/transfer';
|
|
23
|
+
|
|
24
|
+
const commitSchema = z.object({
|
|
25
|
+
blobHTTPHeaders: z.object({
|
|
26
|
+
blobContentType: z.string().optional(),
|
|
27
|
+
blobCacheControl: z.string().optional(),
|
|
28
|
+
blobContentDisposition: z.string().optional(),
|
|
29
|
+
}),
|
|
30
|
+
metadata: z.record(z.string(), z.string()).optional(),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
/** Blob properties applied when the blob is committed. */
|
|
34
|
+
export type BlobCommitOptions = {
|
|
35
|
+
blobHTTPHeaders: Pick<
|
|
36
|
+
BlobHTTPHeaders,
|
|
37
|
+
'blobContentType' | 'blobCacheControl' | 'blobContentDisposition'
|
|
38
|
+
>;
|
|
39
|
+
metadata?: Metadata;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Block IDs must be base64 strings of equal length within a blob. The session
|
|
44
|
+
* prefix keeps concurrent uploads to the same blob name from sharing blocks.
|
|
45
|
+
*/
|
|
46
|
+
export function blockId(prefix: string, partNumber: number) {
|
|
47
|
+
return btoa(`${prefix}-${String(partNumber).padStart(5, '0')}`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function newBlockPrefix() {
|
|
51
|
+
return crypto.randomUUID().replaceAll('-', '').slice(0, 16);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function allBlockIds(session: MultipartSession) {
|
|
55
|
+
return Array.from({ length: session.totalParts }, (_, index) =>
|
|
56
|
+
blockId(session.id, index + 1),
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Browser multipart uploads stage blocks with Put Block URLs and commit them
|
|
62
|
+
* with Put Block List. Azure has no upload session to cancel: uncommitted
|
|
63
|
+
* blocks are discarded automatically after seven days.
|
|
64
|
+
*/
|
|
65
|
+
export function createBlockUploads({
|
|
66
|
+
blob,
|
|
67
|
+
sessions,
|
|
68
|
+
signPartUrl,
|
|
69
|
+
}: {
|
|
70
|
+
blob: (key: string) => BlockBlobClient;
|
|
71
|
+
sessions: ReturnType<typeof createMultipartSessions>;
|
|
72
|
+
signPartUrl: (key: string, blockId: string) => string;
|
|
73
|
+
}) {
|
|
74
|
+
function signParts(session: MultipartSession, parts: number[]) {
|
|
75
|
+
assertValidParts(session, parts);
|
|
76
|
+
return parts.map((partNumber) => ({
|
|
77
|
+
partNumber,
|
|
78
|
+
uploadUrl: signPartUrl(session.key, blockId(session.id, partNumber)),
|
|
79
|
+
}));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Catches incomplete or broken uploads before the provider commits them.
|
|
84
|
+
* This is not a security boundary: a blob write SAS also permits Put Blob
|
|
85
|
+
* and Put Block List, so a browser can write its one blob directly.
|
|
86
|
+
*/
|
|
87
|
+
async function assertStagedBlocks(session: MultipartSession) {
|
|
88
|
+
const { uncommittedBlocks = [] } = await blob(session.key).getBlockList(
|
|
89
|
+
'uncommitted',
|
|
90
|
+
);
|
|
91
|
+
const sizes = new Map(
|
|
92
|
+
uncommittedBlocks.map((block) => [block.name, block.size]),
|
|
93
|
+
);
|
|
94
|
+
for (let partNumber = 1; partNumber <= session.totalParts; partNumber++) {
|
|
95
|
+
if (
|
|
96
|
+
sizes.get(blockId(session.id, partNumber)) !==
|
|
97
|
+
partLength(session, partNumber)
|
|
98
|
+
) {
|
|
99
|
+
throw new EdgeStoreError({
|
|
100
|
+
code: 'BAD_REQUEST',
|
|
101
|
+
message: `Azure block for part ${partNumber} is missing or has the wrong size.`,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const operations: ProviderMultipartUploads = {
|
|
108
|
+
async requestParts({ uploadId, key, parts }) {
|
|
109
|
+
return { parts: signParts(await sessions.read(uploadId, key), parts) };
|
|
110
|
+
},
|
|
111
|
+
async complete({ uploadId, key, parts }) {
|
|
112
|
+
const session = await sessions.read(uploadId, key);
|
|
113
|
+
assertValidParts(
|
|
114
|
+
session,
|
|
115
|
+
parts.map((part) => part.partNumber),
|
|
116
|
+
{ complete: true },
|
|
117
|
+
);
|
|
118
|
+
await assertStagedBlocks(session);
|
|
119
|
+
await blob(key).commitBlockList(
|
|
120
|
+
allBlockIds(session),
|
|
121
|
+
commitSchema.parse(session.data),
|
|
122
|
+
);
|
|
123
|
+
},
|
|
124
|
+
async abort({ uploadId, key }) {
|
|
125
|
+
await sessions.read(uploadId, key);
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
return {
|
|
130
|
+
operations,
|
|
131
|
+
async request({
|
|
132
|
+
key,
|
|
133
|
+
size,
|
|
134
|
+
plan,
|
|
135
|
+
commit,
|
|
136
|
+
}: {
|
|
137
|
+
key: string;
|
|
138
|
+
size: number;
|
|
139
|
+
plan: MultipartUploadPlan;
|
|
140
|
+
commit: BlobCommitOptions;
|
|
141
|
+
}) {
|
|
142
|
+
const session = sessionFromPlan({
|
|
143
|
+
key,
|
|
144
|
+
id: newBlockPrefix(),
|
|
145
|
+
size,
|
|
146
|
+
plan,
|
|
147
|
+
data: commit,
|
|
148
|
+
});
|
|
149
|
+
return {
|
|
150
|
+
key,
|
|
151
|
+
uploadId: await sessions.sign(session),
|
|
152
|
+
partSize: session.partSize,
|
|
153
|
+
totalParts: session.totalParts,
|
|
154
|
+
parts: signParts(session, initialPartNumbers(plan)),
|
|
155
|
+
};
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Uploads from the server with the SDK client, which owns request retries. */
|
|
161
|
+
export async function uploadBlob({
|
|
162
|
+
client,
|
|
163
|
+
commit,
|
|
164
|
+
plan,
|
|
165
|
+
source,
|
|
166
|
+
signal,
|
|
167
|
+
onProgress,
|
|
168
|
+
}: {
|
|
169
|
+
client: BlockBlobClient;
|
|
170
|
+
commit: BlobCommitOptions;
|
|
171
|
+
plan: MultipartUploadPlan | null;
|
|
172
|
+
} & Pick<BackendUploadParams, 'source' | 'signal' | 'onProgress'>) {
|
|
173
|
+
signal?.throwIfAborted();
|
|
174
|
+
const progress = createProgress(source.size, onProgress);
|
|
175
|
+
if (!plan) {
|
|
176
|
+
const body = new Uint8Array(await source.arrayBuffer());
|
|
177
|
+
await client.upload(body, body.byteLength, {
|
|
178
|
+
...commit,
|
|
179
|
+
abortSignal: signal,
|
|
180
|
+
});
|
|
181
|
+
progress(body.byteLength);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const prefix = newBlockPrefix();
|
|
186
|
+
const ids = await runConcurrently(
|
|
187
|
+
plan.partNumbers,
|
|
188
|
+
signal,
|
|
189
|
+
async (partNumber, partSignal) => {
|
|
190
|
+
const body = await readPart(source, partNumber, plan.partSizeBytes);
|
|
191
|
+
const id = blockId(prefix, partNumber);
|
|
192
|
+
await client.stageBlock(id, body, body.byteLength, {
|
|
193
|
+
abortSignal: partSignal,
|
|
194
|
+
});
|
|
195
|
+
progress(body.byteLength);
|
|
196
|
+
return id;
|
|
197
|
+
},
|
|
198
|
+
);
|
|
199
|
+
// Uncommitted blocks from a failed upload expire on their own.
|
|
200
|
+
await client.commitBlockList(ids, { ...commit, abortSignal: signal });
|
|
201
|
+
}
|