@edgestore/server 1.0.0-rc.7 → 1.0.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 (70) hide show
  1. package/README.md +2 -0
  2. package/agent-docs/README.md +1 -1
  3. package/agent-docs/astro.md +2 -2
  4. package/agent-docs/backend-client.md +5 -2
  5. package/agent-docs/configuration.md +6 -5
  6. package/agent-docs/express.md +3 -3
  7. package/agent-docs/fastify.md +3 -3
  8. package/agent-docs/hono.md +3 -3
  9. package/agent-docs/next.md +2 -2
  10. package/agent-docs/provider-azure-blob.md +1 -1
  11. package/agent-docs/provider-custom.md +6 -1
  12. package/agent-docs/provider-edgestore.md +1 -1
  13. package/agent-docs/provider-s3.md +1 -1
  14. package/agent-docs/remix.md +3 -3
  15. package/agent-docs/tanstack-start.md +3 -3
  16. package/agent-docs/troubleshooting.md +4 -4
  17. package/dist/adapters/astro/index.d.ts.map +1 -1
  18. package/dist/adapters/astro/index.js +1 -0
  19. package/dist/adapters/dispatcher.d.ts +1 -0
  20. package/dist/adapters/dispatcher.d.ts.map +1 -1
  21. package/dist/adapters/dispatcher.js +11 -1
  22. package/dist/adapters/express/index.d.ts.map +1 -1
  23. package/dist/adapters/express/index.js +1 -0
  24. package/dist/adapters/fastify/index.d.ts.map +1 -1
  25. package/dist/adapters/fastify/index.js +1 -0
  26. package/dist/adapters/hono/index.d.ts.map +1 -1
  27. package/dist/adapters/hono/index.js +1 -0
  28. package/dist/adapters/next/app/index.d.ts.map +1 -1
  29. package/dist/adapters/next/app/index.js +1 -0
  30. package/dist/adapters/next/pages/index.d.ts.map +1 -1
  31. package/dist/adapters/next/pages/index.js +1 -0
  32. package/dist/adapters/remix/index.d.ts.map +1 -1
  33. package/dist/adapters/remix/index.js +1 -0
  34. package/dist/adapters/shared.d.ts +11 -4
  35. package/dist/adapters/shared.d.ts.map +1 -1
  36. package/dist/adapters/shared.js +75 -27
  37. package/dist/adapters/start/index.d.ts.map +1 -1
  38. package/dist/adapters/start/index.js +1 -0
  39. package/dist/libs/env.d.ts +1 -0
  40. package/dist/libs/env.d.ts.map +1 -1
  41. package/dist/libs/env.js +4 -1
  42. package/dist/providers/azure-blob/index.d.ts.map +1 -1
  43. package/dist/providers/azure-blob/index.js +27 -12
  44. package/dist/providers/edgestore/index.d.ts +1 -1
  45. package/dist/providers/edgestore/index.d.ts.map +1 -1
  46. package/dist/providers/edgestore/index.js +37 -14
  47. package/dist/providers/s3/index.d.ts.map +1 -1
  48. package/dist/providers/s3/index.js +34 -16
  49. package/dist/providers/storage/objectKeys.d.ts +8 -0
  50. package/dist/providers/storage/objectKeys.d.ts.map +1 -1
  51. package/dist/providers/storage/objectKeys.js +18 -1
  52. package/dist/version.d.ts +1 -1
  53. package/dist/version.d.ts.map +1 -1
  54. package/package.json +4 -4
  55. package/src/adapters/astro/index.ts +1 -0
  56. package/src/adapters/dispatcher.ts +12 -0
  57. package/src/adapters/express/index.ts +1 -0
  58. package/src/adapters/fastify/index.ts +1 -0
  59. package/src/adapters/hono/index.ts +1 -0
  60. package/src/adapters/next/app/index.ts +1 -0
  61. package/src/adapters/next/pages/index.ts +1 -0
  62. package/src/adapters/remix/index.ts +1 -0
  63. package/src/adapters/shared.ts +125 -34
  64. package/src/adapters/start/index.ts +1 -0
  65. package/src/libs/env.ts +4 -0
  66. package/src/providers/azure-blob/index.ts +32 -11
  67. package/src/providers/edgestore/index.ts +42 -20
  68. package/src/providers/s3/index.ts +41 -14
  69. package/src/providers/storage/objectKeys.ts +21 -0
  70. package/src/version.ts +1 -1
@@ -5,12 +5,12 @@ import { z } from 'zod';
5
5
  import { assertSupportedUploadOptions, referenceFromUrl } from '../core/provider.js';
6
6
  import { parseBucketInput, buildPath, parsePath } from '../core/routerRules.js';
7
7
  import { validateFileForBucket } from '../core/validateFile.js';
8
- import { getEnv } from '../libs/env.js';
8
+ import { isProduction, getEnv } from '../libs/env.js';
9
9
 
10
10
  // TODO: change it to 1 hour when we have a way to refresh the token
11
11
  const DEFAULT_MAX_AGE = 30 * 24 * 60 * 60; // 30 days
12
12
  /**
13
- * Merges the provided cookie configuration with default values
13
+ * Merges the provided cookie configuration with default values.
14
14
  */ function getCookieConfig(cookieConfig) {
15
15
  // Explicit `undefined` options keep their defaults.
16
16
  const configured = Object.fromEntries(Object.entries(cookieConfig?.ctx?.options ?? {}).filter(([, value])=>value !== undefined));
@@ -20,6 +20,9 @@ const DEFAULT_MAX_AGE = 30 * 24 * 60 * 60; // 30 days
20
20
  options: {
21
21
  path: '/',
22
22
  maxAge: DEFAULT_MAX_AGE,
23
+ sameSite: 'lax',
24
+ httpOnly: true,
25
+ secure: isProduction(),
23
26
  ...configured
24
27
  }
25
28
  }
@@ -31,7 +34,7 @@ async function init(params) {
31
34
  ctx
32
35
  });
33
36
  const resolvedCookieConfig = getCookieConfig(cookieConfig);
34
- const ctxToken = await encryptJWT(ctx);
37
+ const ctxToken = await encryptJWT(ctx, resolvedCookieConfig.ctx.options.maxAge);
35
38
  const { clientInit } = await provider.init({
36
39
  ctx,
37
40
  router
@@ -108,6 +111,33 @@ async function requestUpload(params) {
108
111
  bucket,
109
112
  fileInfo
110
113
  });
114
+ // Replacing or overwriting a file deletes it, so it needs the same
115
+ // authorization as deleting it.
116
+ const authorizeReplacement = (action, refusal)=>async (file)=>{
117
+ const beforeDelete = requireBeforeDelete(bucket, action);
118
+ if (!await canDelete({
119
+ provider,
120
+ bucket,
121
+ ctx,
122
+ beforeDelete,
123
+ files: [
124
+ file
125
+ ]
126
+ })) {
127
+ throw new EdgeStoreError({
128
+ message: refusal,
129
+ code: 'UPLOAD_NOT_ALLOWED'
130
+ });
131
+ }
132
+ };
133
+ if (fileInfo.replaceTargetUrl) {
134
+ // The lookup is scoped to this bucket, so targets elsewhere are rejected.
135
+ const file = await referenceFromUrl(provider, fileInfo.replaceTargetUrl);
136
+ await authorizeReplacement('replace files', 'Replacing this file is not allowed for the current context')(await provider.files.get({
137
+ bucketName,
138
+ file
139
+ }));
140
+ }
111
141
  const path = buildPath({
112
142
  bucket,
113
143
  pathAttrs: {
@@ -136,7 +166,11 @@ async function requestUpload(params) {
136
166
  isPublic,
137
167
  metadata
138
168
  },
139
- autoSignedUrls
169
+ autoSignedUrls,
170
+ ...fileInfo.fileName !== undefined && {
171
+ // A client-chosen name can match an existing file.
172
+ authorizeOverwrite: authorizeReplacement(`overwrite the existing file "${fileInfo.fileName}"`, `A file named "${fileInfo.fileName}" already exists, and the current context may not overwrite it`)
173
+ }
140
174
  });
141
175
  const { parsedPath, pathOrder } = parsePath(path);
142
176
  const statusToken = provider.uploads.getStatus && requestUploadRes.id ? await encryptStatusToken({
@@ -321,12 +355,7 @@ async function deleteFiles(params) {
321
355
  });
322
356
  const ctx = await getContext(ctxToken);
323
357
  const bucket = getBucket(router, bucketName);
324
- if (!bucket._def.beforeDelete) {
325
- throw new EdgeStoreError({
326
- message: 'You need to define beforeDelete if you want to delete files directly from the frontend.',
327
- code: 'SERVER_ERROR'
328
- });
329
- }
358
+ const beforeDelete = requireBeforeDelete(bucket, 'delete files directly');
330
359
  if (!provider.files.delete) {
331
360
  throw new EdgeStoreError({
332
361
  message: `Provider ${provider.name} does not support file deletion.`,
@@ -338,7 +367,37 @@ async function deleteFiles(params) {
338
367
  bucketName,
339
368
  file
340
369
  }))));
341
- const authorizations = await Promise.all(fileRecords.map((file)=>{
370
+ if (!await canDelete({
371
+ provider,
372
+ bucket,
373
+ ctx,
374
+ beforeDelete,
375
+ files: fileRecords
376
+ })) {
377
+ throw new EdgeStoreError({
378
+ message: 'Delete not allowed for the current context',
379
+ code: 'DELETE_NOT_ALLOWED'
380
+ });
381
+ }
382
+ const result = await provider.files.delete({
383
+ bucketName,
384
+ files
385
+ });
386
+ logger.debug('Finished [deleteFiles]');
387
+ return mapFrontendMutationResult(urls, result);
388
+ }
389
+ function requireBeforeDelete(bucket, action) {
390
+ const { beforeDelete } = bucket._def;
391
+ if (!beforeDelete) {
392
+ throw new EdgeStoreError({
393
+ message: `You need to define beforeDelete if you want to ${action} from the frontend.`,
394
+ code: 'SERVER_ERROR'
395
+ });
396
+ }
397
+ return beforeDelete;
398
+ }
399
+ /** Runs `beforeDelete` for every file and reports whether all are allowed. */ async function canDelete({ provider, bucket, ctx, beforeDelete, files }) {
400
+ const authorizations = await Promise.all(files.map((file)=>{
342
401
  if (file.path === undefined && bucket._def.path.length > 0) {
343
402
  throw new EdgeStoreError({
344
403
  message: `Provider ${provider.name} must return path from files.get to authorize frontend deletion for a bucket with configured path fields.`,
@@ -351,7 +410,7 @@ async function deleteFiles(params) {
351
410
  code: 'SERVER_ERROR'
352
411
  });
353
412
  }
354
- return Promise.resolve(bucket._def.beforeDelete({
413
+ return Promise.resolve(beforeDelete({
355
414
  ctx,
356
415
  fileInfo: {
357
416
  url: file.url,
@@ -362,18 +421,7 @@ async function deleteFiles(params) {
362
421
  }
363
422
  }));
364
423
  }));
365
- if (authorizations.some((allowed)=>!allowed)) {
366
- throw new EdgeStoreError({
367
- message: 'Delete not allowed for the current context',
368
- code: 'DELETE_NOT_ALLOWED'
369
- });
370
- }
371
- const result = await provider.files.delete({
372
- bucketName,
373
- files
374
- });
375
- logger.debug('Finished [deleteFiles]');
376
- return mapFrontendMutationResult(urls, result);
424
+ return authorizations.every(Boolean);
377
425
  }
378
426
  function mapFrontendMutationResult(urls, result) {
379
427
  if (result.results.length !== urls.length) {
@@ -404,13 +452,13 @@ function getBucket(router, bucketName) {
404
452
  }
405
453
  return bucket;
406
454
  }
407
- async function encryptJWT(ctx) {
455
+ /** Encrypts the context into a token that expires with its cookie. */ async function encryptJWT(ctx, maxAge) {
408
456
  return await new EncryptJWT({
409
457
  ctx
410
458
  }).setProtectedHeader({
411
459
  alg: 'dir',
412
460
  enc: 'A256GCM'
413
- }).setIssuedAt().setExpirationTime(Date.now() / 1000 + DEFAULT_MAX_AGE).setJti(crypto.randomUUID()).encrypt(await getEncryptionKey());
461
+ }).setIssuedAt().setExpirationTime(Date.now() / 1000 + maxAge).setJti(crypto.randomUUID()).encrypt(await getEncryptionKey());
414
462
  }
415
463
  /**
416
464
  * Status tokens bind one upload to the browser that requested it. They never
@@ -449,7 +497,7 @@ const contextPayloadSchema = z.object({
449
497
  /** Decrypts and validates the `edgestore-ctx` cookie set by `/init`. */ async function getContext(token) {
450
498
  if (!token) {
451
499
  throw new EdgeStoreError({
452
- message: 'Missing edgestore-ctx cookie',
500
+ message: 'Missing edgestore-ctx cookie. When NODE_ENV is production the cookie is Secure, so browsers drop it over plain HTTP (Safari even on localhost). To test a production build over HTTP, set cookieConfig.ctx.options.secure to false.',
453
501
  code: 'UNAUTHORIZED'
454
502
  });
455
503
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/adapters/start/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAe,EAAE,KAAK,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAGL,KAAK,mBAAmB,EACzB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE7D,MAAM,MAAM,oBAAoB,GAAG;IACjC,GAAG,EAAE,OAAO,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,MAAM,CAAC,IAAI,SAAS,UAAU,IAAI;IAC5C,MAAM,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;IAC5B,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B,GAAG,mBAAmB,CAAC,IAAI,EAAE,oBAAoB,CAAC,CAAC;AAEpD,wBAAgB,2BAA2B,CAAC,IAAI,SAAS,UAAU,EACjE,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,IAKN,aAAa;IAAE,OAAO,EAAE,OAAO,CAAA;CAAE,uBAiBhD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/adapters/start/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAe,EAAE,KAAK,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAGL,KAAK,mBAAmB,EACzB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE7D,MAAM,MAAM,oBAAoB,GAAG;IACjC,GAAG,EAAE,OAAO,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,MAAM,CAAC,IAAI,SAAS,UAAU,IAAI;IAC5C,MAAM,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;IAC5B,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B,GAAG,mBAAmB,CAAC,IAAI,EAAE,oBAAoB,CAAC,CAAC;AAEpD,wBAAgB,2BAA2B,CAAC,IAAI,SAAS,UAAU,EACjE,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,IAKN,aAAa;IAAE,OAAO,EAAE,OAAO,CAAA;CAAE,uBAkBhD"}
@@ -13,6 +13,7 @@ function createEdgeStoreStartHandler(config) {
13
13
  request: {
14
14
  pathname: url.pathname,
15
15
  readJson: ()=>request.json(),
16
+ contentType: request.headers.get('content-type') ?? undefined,
16
17
  cookieHeader: request.headers.get('cookie') ?? undefined,
17
18
  createContext: ()=>resolveContext(config, {
18
19
  req: request
@@ -1,3 +1,4 @@
1
1
  export declare function getEnv(key: string): string | undefined;
2
2
  export declare function isDev(): boolean;
3
+ export declare function isProduction(): boolean;
3
4
  //# sourceMappingURL=env.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../../src/libs/env.ts"],"names":[],"mappings":"AAAA,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOtD;AAWD,wBAAgB,KAAK,IAAI,OAAO,CAM/B"}
1
+ {"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../../src/libs/env.ts"],"names":[],"mappings":"AAAA,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOtD;AAWD,wBAAgB,KAAK,IAAI,OAAO,CAM/B;AAED,wBAAgB,YAAY,IAAI,OAAO,CAEtC"}
package/dist/libs/env.js CHANGED
@@ -13,5 +13,8 @@ function isDev() {
13
13
  return process?.env?.NODE_ENV === 'development' || // @ts-expect-error - In Vite/Astro, env variables are available on import.meta.
14
14
  import.meta.env?.DEV;
15
15
  }
16
+ function isProduction() {
17
+ return getEnv('NODE_ENV') === 'production';
18
+ }
16
19
 
17
- export { getEnv, isDev };
20
+ export { getEnv, isDev, isProduction };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/providers/azure-blob/index.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EACV,YAAY,EACZ,mBAAmB,EACnB,gBAAgB,EACjB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACtB,MAAM,uBAAuB,CAAC;AAY/B,2DAA2D;AAC3D,MAAM,MAAM,sBAAsB,GAAG;IACnC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACnC,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG;IACrC;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;;OAKG;IACH,QAAQ,C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AAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACnC,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG;IACrC;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,IAAI,CAAC,EAAE,YAAY,CAAC;IACpB,2DAA2D;IAC3D,aAAa,CAAC,EACV,sBAAsB,GACtB,CAAC,CAAC,IAAI,EAAE,gBAAgB,KAAK,YAAY,CAAC,sBAAsB,CAAC,CAAC,CAAC;IACvE,qDAAqD;IACrD,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,0DAA0D;IAC1D,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,gDAAgD;IAChD,SAAS,CAAC,EAAE;QACV,6DAA6D;QAC7D,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,+DAA+D;QAC/D,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB;;;WAGG;QACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;KAC3B,CAAC;CACH,CAAC;AAUF,wBAAgB,SAAS,CAAC,OAAO,GAAE,wBAA6B;;;;;;;;;;;;;;;;;;2DAwLnC,OAAO,CAAC,gBAAgB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+FrD"}
@@ -1,10 +1,10 @@
1
- import { generateBlobSASQueryParameters, SASProtocol, BlobSASPermissions, StorageSharedKeyCredential, BlobServiceClient } from '@azure/storage-blob';
1
+ import { RestError, generateBlobSASQueryParameters, SASProtocol, BlobSASPermissions, StorageSharedKeyCredential, BlobServiceClient } from '@azure/storage-blob';
2
2
  import { planMultipartUpload } from '@edgestore/sdk';
3
3
  import { z } from 'zod';
4
4
  import { defineProvider } from '../../core/provider.js';
5
5
  import { getEnv } from '../../libs/env.js';
6
6
  import { createMultipartSessions } from '../storage/multipartSession.js';
7
- import { createObjectKeys } from '../storage/objectKeys.js';
7
+ import { createObjectKeys, pathFromDefaultKey } from '../storage/objectKeys.js';
8
8
  import { runConcurrently, assertSignedUrlAccessControl, signedUrlLifetime } from '../storage/transfer.js';
9
9
  import { createBlockUploads, uploadBlob } from './blocks.js';
10
10
 
@@ -76,6 +76,29 @@ function azureBlob(options = {}) {
76
76
  expiresIn: ttl
77
77
  };
78
78
  }
79
+ async function describeBlob(key) {
80
+ const { contentLength, lastModified } = await blob(key).getProperties();
81
+ if (contentLength === undefined || !lastModified) throw new Error('File not found');
82
+ return {
83
+ key,
84
+ url: keys.toUrl(key),
85
+ sizeBytes: contentLength,
86
+ uploadedAt: lastModified,
87
+ updatedAt: lastModified
88
+ };
89
+ }
90
+ /** Authorizes overwriting the blob at `key`, if one exists. */ async function authorizeOverwrite(key, params) {
91
+ if (!params.authorizeOverwrite) return;
92
+ const existing = await describeBlob(key).catch((error)=>{
93
+ if (error instanceof RestError && error.statusCode === 404) return undefined;
94
+ throw error;
95
+ });
96
+ if (!existing) return;
97
+ await params.authorizeOverwrite({
98
+ ...existing,
99
+ path: pathFromDefaultKey(params.fileInfo, options.path)
100
+ });
101
+ }
79
102
  function readForUpload(key, params) {
80
103
  if (params.fileInfo.isPublic || !params.autoSignedUrls) return undefined;
81
104
  return signedRead(key, params.autoSignedUrls.expiresIn);
@@ -134,6 +157,7 @@ function azureBlob(options = {}) {
134
157
  },
135
158
  async request (params) {
136
159
  const { key, commit, plan } = await prepare(params);
160
+ await authorizeOverwrite(key, params);
137
161
  const signedReadUrl = readForUpload(key, params);
138
162
  const access = {
139
163
  key,
@@ -194,16 +218,7 @@ function azureBlob(options = {}) {
194
218
  },
195
219
  files: {
196
220
  async get ({ bucketName, file }) {
197
- const key = keys.fromReference(bucketName, file);
198
- const { contentLength, lastModified } = await blob(key).getProperties();
199
- if (contentLength === undefined || !lastModified) throw new Error('File not found');
200
- return {
201
- key,
202
- url: keys.toUrl(key),
203
- sizeBytes: contentLength,
204
- uploadedAt: lastModified,
205
- updatedAt: lastModified
206
- };
221
+ return describeBlob(keys.fromReference(bucketName, file));
207
222
  },
208
223
  async getSignedUrls ({ bucketName, files, expiresIn }) {
209
224
  return files.map((file)=>signedRead(keys.fromReference(bucketName, file), expiresIn));
@@ -68,7 +68,7 @@ export declare function edgestore(options?: EdgeStoreProviderOptions): {
68
68
  };
69
69
  }>;
70
70
  readonly uploads: {
71
- readonly request: ({ bucketName, bucketType, fileInfo, autoSignedUrls, }: RequestUploadParams) => Promise<RequestUploadRes>;
71
+ readonly request: ({ bucketName, bucketType, fileInfo, autoSignedUrls, authorizeOverwrite, }: RequestUploadParams) => Promise<RequestUploadRes>;
72
72
  readonly multipart: {
73
73
  readonly requestParts: ({ uploadId, parts }: import("@edgestore/shared").RequestUploadPartsParams) => Promise<{
74
74
  parts: {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/providers/edgestore/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,0BAA0B,EAC/B,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAqBxB,KAAK,8BAA8B,GAAG;IACpC,wCAAwC;IACxC,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,KAAK,+BAA+B,GAAG;IACrC;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM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AAK,CAAC;IACd,OAAO,CAAC,EAAE,KAAK,CAAC;CACjB,CAAC;AAEF,KAAK,8BAA8B,GAAG;IACpC,yDAAyD;IACzD,KAAK,EAAE,MAAM,CAAC;IACd,qDAAqD;IACrD,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,KAAK,CAAC;IAClB,SAAS,CAAC,EAAE,KAAK,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG,8BAA8B,GACnE,CAAC,+BAA+B,GAAG,8BAA8B,CAAC,CAAC;AAErE,wBAAgB,SAAS,CAAC,OAAO,CAAC,EAAE,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8HAiElD,OAAO,CAAC,gBAAgB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAiLlC;AAED,MAAM,MAAM,wBAAwB,GAAG,UAAU,CAAC,OAAO,SAAS,CAAC,CAAC"}
@@ -1,4 +1,4 @@
1
- import { planMultipartUpload, createEdgeStoreSdk } from '@edgestore/sdk';
1
+ import { planMultipartUpload, EdgeStoreApiError, createEdgeStoreSdk } from '@edgestore/sdk';
2
2
  import { EdgeStoreError } from '@edgestore/shared';
3
3
  import { z } from 'zod';
4
4
  import { defineProvider, INITIAL_MULTIPART_PART_URLS } from '../../core/provider.js';
@@ -69,26 +69,36 @@ function edgestore(options) {
69
69
  };
70
70
  },
71
71
  uploads: {
72
- async request ({ bucketName, bucketType, fileInfo, autoSignedUrls }) {
72
+ async request ({ bucketName, bucketType, fileInfo, autoSignedUrls, authorizeOverwrite }) {
73
73
  const multipartPlan = planMultipartUpload({
74
74
  sizeBytes: fileInfo.size
75
75
  });
76
- if (multipartPlan) {
77
- return mapUploadResponse(await runtime.uploads.request({
78
- bucket: bucketName,
79
- ...mapRawUploadRequest(bucketType, fileInfo, autoSignedUrls),
76
+ const res = await runtime.uploads.request({
77
+ bucket: bucketName,
78
+ ...mapRawUploadRequest(bucketType, fileInfo, autoSignedUrls),
79
+ ...multipartPlan && {
80
80
  multipart: {
81
81
  partNumbers: multipartPlan.partNumbers.slice(0, INITIAL_MULTIPART_PART_URLS)
82
82
  }
83
- }), {
84
- partSize: multipartPlan.partSizeBytes,
85
- totalParts: multipartPlan.totalParts
86
- });
83
+ }
84
+ });
85
+ if (authorizeOverwrite) {
86
+ // The upload supersedes an uploaded file at the same key once it
87
+ // completes, so cancel it unless the requester may delete that file.
88
+ try {
89
+ const existing = await findFile(bucketName, res.file.key);
90
+ if (existing) await authorizeOverwrite(mapFile(existing));
91
+ } catch (error) {
92
+ await runtime.uploads.cancel({
93
+ uploadId: res.file.id
94
+ }).catch(()=>undefined);
95
+ throw error;
96
+ }
87
97
  }
88
- return mapUploadResponse(await runtime.uploads.request({
89
- bucket: bucketName,
90
- ...mapRawUploadRequest(bucketType, fileInfo, autoSignedUrls)
91
- }));
98
+ return mapUploadResponse(res, multipartPlan ? {
99
+ partSize: multipartPlan.partSizeBytes,
100
+ totalParts: multipartPlan.totalParts
101
+ } : undefined);
92
102
  },
93
103
  multipart: {
94
104
  requestParts: async ({ uploadId, parts })=>{
@@ -211,6 +221,19 @@ function edgestore(options) {
211
221
  }
212
222
  }
213
223
  });
224
+ async function findFile(bucketName, key) {
225
+ try {
226
+ return (await runtime.files.lookup({
227
+ bucketName,
228
+ file: {
229
+ key
230
+ }
231
+ })).file;
232
+ } catch (error) {
233
+ if (error instanceof EdgeStoreApiError && error.code === 'file_not_found') return undefined;
234
+ throw error;
235
+ }
236
+ }
214
237
  return provider;
215
238
  }
216
239
  function createProviderRuntime(options) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/providers/s3/index.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAYxB,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAEnD,YAAY,EACV,eAAe,EACf,QAAQ,EACR,YAAY,EACZ,iBAAiB,GAClB,MAAM,WAAW,CAAC;AAInB,wBAAgB,EAAE,CAAC,OAAO,GAAE,iBAAsB;;;;;;;;;;;;;;;;;;2DA2JrB,OAAO,CAAC,gBAAgB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoJrD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/providers/s3/index.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAYxB,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAEnD,YAAY,EACV,eAAe,EACf,QAAQ,EACR,YAAY,EACZ,iBAAiB,GAClB,MAAM,WAAW,CAAC;AAInB,wBAAgB,EAAE,CAAC,OAAO,GAAE,iBAAsB;;;;;;;;;;;;;;;;;;2DA+LrB,OAAO,CAAC,gBAAgB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA0IrD"}
@@ -1,11 +1,11 @@
1
- import { S3Client, DeleteObjectsCommand, HeadObjectCommand, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';
1
+ import { S3Client, DeleteObjectsCommand, PutObjectCommand, GetObjectCommand, HeadObjectCommand, S3ServiceException } from '@aws-sdk/client-s3';
2
2
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
3
3
  import { planMultipartUpload } from '@edgestore/sdk';
4
4
  import { z } from 'zod';
5
5
  import { defineProvider } from '../../core/provider.js';
6
6
  import { getEnv } from '../../libs/env.js';
7
7
  import { createMultipartSessions } from '../storage/multipartSession.js';
8
- import { createObjectKeys } from '../storage/objectKeys.js';
8
+ import { createObjectKeys, pathFromDefaultKey } from '../storage/objectKeys.js';
9
9
  import { assertSignedUrlAccessControl, signedUrlLifetime } from '../storage/transfer.js';
10
10
  import { uploadObject } from './backendUpload.js';
11
11
  import { createMultipartUploads } from './multipart.js';
@@ -103,6 +103,36 @@ function s3(options = {}) {
103
103
  }
104
104
  })());
105
105
  }
106
+ async function describeObject(key) {
107
+ const { ContentLength, LastModified } = await client.send(new HeadObjectCommand({
108
+ Bucket: bucket(),
109
+ Key: key
110
+ }));
111
+ if (ContentLength === undefined || !LastModified) throw new Error('File not found');
112
+ return {
113
+ key,
114
+ url: (await keys()).toUrl(key),
115
+ sizeBytes: ContentLength,
116
+ uploadedAt: LastModified,
117
+ updatedAt: LastModified
118
+ };
119
+ }
120
+ /** Authorizes overwriting the object at `key`, if one exists. */ async function authorizeOverwrite(key, params) {
121
+ if (!params.authorizeOverwrite) return;
122
+ const existing = await describeObject(key).catch((error)=>{
123
+ // Without s3:ListBucket, S3 reports a missing key as 403, not 404.
124
+ // Credentials without s3:GetObject can't detect overwrites; the
125
+ // documented policy grants it.
126
+ const status = error instanceof S3ServiceException ? error.$metadata.httpStatusCode : undefined;
127
+ if (status === 403 || status === 404) return undefined;
128
+ throw error;
129
+ });
130
+ if (!existing) return;
131
+ await params.authorizeOverwrite({
132
+ ...existing,
133
+ path: pathFromDefaultKey(params.fileInfo, options.path)
134
+ });
135
+ }
106
136
  async function readForUpload(key, params) {
107
137
  if (params.fileInfo.isPublic || !params.autoSignedUrls) return undefined;
108
138
  return signedRead(key, params.autoSignedUrls.expiresIn);
@@ -135,6 +165,7 @@ function s3(options = {}) {
135
165
  async request (params) {
136
166
  await assertPresignableClient();
137
167
  const prepared = await prepare(params);
168
+ await authorizeOverwrite(prepared.key, params);
138
169
  const read = await readForUpload(prepared.key, params);
139
170
  const access = {
140
171
  key: prepared.key,
@@ -204,20 +235,7 @@ function s3(options = {}) {
204
235
  },
205
236
  files: {
206
237
  async get ({ bucketName: logicalBucket, file }) {
207
- const objectKeys = await keys();
208
- const key = objectKeys.fromReference(logicalBucket, file);
209
- const { ContentLength, LastModified } = await client.send(new HeadObjectCommand({
210
- Bucket: bucket(),
211
- Key: key
212
- }));
213
- if (ContentLength === undefined || !LastModified) throw new Error('File not found');
214
- return {
215
- key,
216
- url: objectKeys.toUrl(key),
217
- sizeBytes: ContentLength,
218
- uploadedAt: LastModified,
219
- updatedAt: LastModified
220
- };
238
+ return describeObject((await keys()).fromReference(logicalBucket, file));
221
239
  },
222
240
  async getSignedUrls ({ bucketName: logicalBucket, files, expiresIn }) {
223
241
  const objectKeys = await keys();
@@ -38,4 +38,12 @@ export declare function createObjectKeys(providerName: string, baseUrl: string):
38
38
  };
39
39
  }>;
40
40
  };
41
+ /**
42
+ * Path values of an existing object at an upload's key, when the key proves
43
+ * them. Only the default layout encodes the path, and a `/` inside a path
44
+ * value or the file name makes its segment boundaries ambiguous.
45
+ */
46
+ export declare function pathFromDefaultKey(fileInfo: RequestUploadParams['fileInfo'], customPath: ObjectPathFn | undefined): {
47
+ [k: string]: string;
48
+ } | undefined;
41
49
  //# sourceMappingURL=objectKeys.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"objectKeys.d.ts","sourceRoot":"","sources":["../../../src/providers/storage/objectKeys.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAE3E,MAAM,MAAM,gBAAgB,GAAG;IAC7B,4CAA4C;IAC5C,mBAAmB,EAAE,MAAM,CAAC;IAC5B,8DAA8D;IAC9D,QAAQ,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC;IAC1C,iEAAiE;IACjE,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF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E,YAAY,GAAG,SAAS;;cAYrC"}
@@ -63,5 +63,22 @@ function createObjectKeys(providerName, baseUrl) {
63
63
  forUpload
64
64
  };
65
65
  }
66
+ /**
67
+ * Path values of an existing object at an upload's key, when the key proves
68
+ * them. Only the default layout encodes the path, and a `/` inside a path
69
+ * value or the file name makes its segment boundaries ambiguous.
70
+ */ function pathFromDefaultKey(fileInfo, customPath) {
71
+ const segments = [
72
+ ...fileInfo.path.map(({ value })=>value),
73
+ fileInfo.fileName ?? ''
74
+ ];
75
+ if (customPath || segments.some((segment)=>segment.includes('/'))) {
76
+ return undefined;
77
+ }
78
+ return Object.fromEntries(fileInfo.path.map(({ key, value })=>[
79
+ key,
80
+ value
81
+ ]));
82
+ }
66
83
 
67
- export { createObjectKeys };
84
+ export { createObjectKeys, pathFromDefaultKey };
package/dist/version.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export declare const EDGE_STORE_PACKAGE_NAME = "@edgestore/server";
2
- export declare const EDGE_STORE_PACKAGE_VERSION = "1.0.0-rc.7";
2
+ export declare const EDGE_STORE_PACKAGE_VERSION = "1.0.1";
3
3
  //# sourceMappingURL=version.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,uBAAuB,sBAAsB,CAAC;AAC3D,eAAO,MAAM,0BAA0B,eAAe,CAAC"}
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,uBAAuB,sBAAsB,CAAC;AAC3D,eAAO,MAAM,0BAA0B,UAAU,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@edgestore/server",
3
- "version": "1.0.0-rc.7",
3
+ "version": "1.0.1",
4
4
  "description": "Upload files with ease from React/Next.js",
5
5
  "homepage": "https://edgestore.dev",
6
6
  "license": "MIT",
@@ -107,8 +107,8 @@
107
107
  "!**/__tests__"
108
108
  ],
109
109
  "dependencies": {
110
- "@edgestore/sdk": "1.0.0-rc.7",
111
- "@edgestore/shared": "1.0.0-rc.7",
110
+ "@edgestore/sdk": "1.0.1",
111
+ "@edgestore/shared": "1.0.1",
112
112
  "@standard-schema/spec": "^1.1.0",
113
113
  "cookie": "^2.0.1",
114
114
  "jose": "^6.2.3",
@@ -141,7 +141,7 @@
141
141
  "express": "5.2.1",
142
142
  "fastify": "5.10.0",
143
143
  "hono": "4.12.31",
144
- "next": "16.2.10",
144
+ "next": "16.4.1",
145
145
  "react": "19.2.7",
146
146
  "react-dom": "19.2.7",
147
147
  "tsx": "4.23.1",
@@ -30,6 +30,7 @@ export function createEdgeStoreAstroHandler<TCtx extends AnyContext>(
30
30
  request: {
31
31
  pathname: url.pathname,
32
32
  readJson: () => request.json(),
33
+ contentType: request.headers.get('content-type') ?? undefined,
33
34
  cookieHeader: request.headers.get('cookie') ?? undefined,
34
35
  createContext: () => resolveContext<TCtx, APIContext>(config, context),
35
36
  },
@@ -33,6 +33,7 @@ import {
33
33
  export type EdgeStoreDispatchRequest<TCtx extends AnyContext> = {
34
34
  pathname: string;
35
35
  readJson: () => Promise<unknown>;
36
+ contentType?: string;
36
37
  cookieHeader?: string;
37
38
  cookies?: Readonly<Record<string, string | undefined>>;
38
39
  createContext: () => MaybePromise<TCtx>;
@@ -250,10 +251,21 @@ function jsonResponse(body: unknown, status = 200) {
250
251
  });
251
252
  }
252
253
 
254
+ /**
255
+ * Requiring a JSON body makes browsers send a CORS preflight before any
256
+ * cross-origin request, so other sites cannot submit forms to these routes.
257
+ */
253
258
  async function parseRequestBody<TSchema extends z.ZodTypeAny>(
254
259
  request: EdgeStoreDispatchRequest<AnyContext>,
255
260
  schema: TSchema,
256
261
  ): Promise<z.output<TSchema>> {
262
+ const mediaType = request.contentType?.split(';')[0]?.trim().toLowerCase();
263
+ if (mediaType !== 'application/json') {
264
+ throw new EdgeStoreError({
265
+ message: 'Content-Type must be application/json',
266
+ code: 'BAD_REQUEST',
267
+ });
268
+ }
257
269
  try {
258
270
  return await schema.parseAsync(await request.readJson());
259
271
  } catch (error) {
@@ -35,6 +35,7 @@ export function createEdgeStoreExpressHandler<TCtx extends AnyContext>(
35
35
  request: {
36
36
  pathname: url.pathname,
37
37
  readJson: async () => req.body,
38
+ contentType: req.headers['content-type'],
38
39
  cookieHeader: req.headers.cookie,
39
40
  cookies: req.cookies as Record<string, string>,
40
41
  createContext: () =>
@@ -35,6 +35,7 @@ export function createEdgeStoreFastifyHandler<TCtx extends AnyContext>(
35
35
  request: {
36
36
  pathname: url.pathname,
37
37
  readJson: async () => req.body,
38
+ contentType: req.headers['content-type'],
38
39
  cookieHeader: req.headers.cookie,
39
40
  cookies:
40
41
  'cookies' in req
@@ -33,6 +33,7 @@ export function createEdgeStoreHonoHandler<TCtx extends AnyContext>(
33
33
  request: {
34
34
  pathname: new URL(c.req.url).pathname,
35
35
  readJson: () => c.req.json(),
36
+ contentType: c.req.header('content-type'),
36
37
  cookieHeader: c.req.header('cookie'),
37
38
  createContext: () =>
38
39
  resolveContext<TCtx, CreateContextOptions>(config, {
@@ -42,6 +42,7 @@ export function createEdgeStoreNextHandler<TCtx extends AnyContext>(
42
42
  request: {
43
43
  pathname: req.nextUrl.pathname,
44
44
  readJson: () => req.json(),
45
+ contentType: req.headers?.get('content-type') ?? undefined,
45
46
  cookieHeader:
46
47
  req.headers?.get('cookie') ?? (req.cookies.toString() || undefined),
47
48
  createContext: () =>