@edgestore/server 1.0.0 → 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 (57) hide show
  1. package/README.md +2 -0
  2. package/agent-docs/README.md +1 -1
  3. package/agent-docs/configuration.md +3 -2
  4. package/agent-docs/provider-custom.md +5 -0
  5. package/dist/adapters/astro/index.d.ts.map +1 -1
  6. package/dist/adapters/astro/index.js +1 -0
  7. package/dist/adapters/dispatcher.d.ts +1 -0
  8. package/dist/adapters/dispatcher.d.ts.map +1 -1
  9. package/dist/adapters/dispatcher.js +11 -1
  10. package/dist/adapters/express/index.d.ts.map +1 -1
  11. package/dist/adapters/express/index.js +1 -0
  12. package/dist/adapters/fastify/index.d.ts.map +1 -1
  13. package/dist/adapters/fastify/index.js +1 -0
  14. package/dist/adapters/hono/index.d.ts.map +1 -1
  15. package/dist/adapters/hono/index.js +1 -0
  16. package/dist/adapters/next/app/index.d.ts.map +1 -1
  17. package/dist/adapters/next/app/index.js +1 -0
  18. package/dist/adapters/next/pages/index.d.ts.map +1 -1
  19. package/dist/adapters/next/pages/index.js +1 -0
  20. package/dist/adapters/remix/index.d.ts.map +1 -1
  21. package/dist/adapters/remix/index.js +1 -0
  22. package/dist/adapters/shared.d.ts +11 -4
  23. package/dist/adapters/shared.d.ts.map +1 -1
  24. package/dist/adapters/shared.js +75 -27
  25. package/dist/adapters/start/index.d.ts.map +1 -1
  26. package/dist/adapters/start/index.js +1 -0
  27. package/dist/libs/env.d.ts +1 -0
  28. package/dist/libs/env.d.ts.map +1 -1
  29. package/dist/libs/env.js +4 -1
  30. package/dist/providers/azure-blob/index.d.ts.map +1 -1
  31. package/dist/providers/azure-blob/index.js +27 -12
  32. package/dist/providers/edgestore/index.d.ts +1 -1
  33. package/dist/providers/edgestore/index.d.ts.map +1 -1
  34. package/dist/providers/edgestore/index.js +37 -14
  35. package/dist/providers/s3/index.d.ts.map +1 -1
  36. package/dist/providers/s3/index.js +34 -16
  37. package/dist/providers/storage/objectKeys.d.ts +8 -0
  38. package/dist/providers/storage/objectKeys.d.ts.map +1 -1
  39. package/dist/providers/storage/objectKeys.js +18 -1
  40. package/dist/version.d.ts +1 -1
  41. package/package.json +4 -4
  42. package/src/adapters/astro/index.ts +1 -0
  43. package/src/adapters/dispatcher.ts +12 -0
  44. package/src/adapters/express/index.ts +1 -0
  45. package/src/adapters/fastify/index.ts +1 -0
  46. package/src/adapters/hono/index.ts +1 -0
  47. package/src/adapters/next/app/index.ts +1 -0
  48. package/src/adapters/next/pages/index.ts +1 -0
  49. package/src/adapters/remix/index.ts +1 -0
  50. package/src/adapters/shared.ts +125 -34
  51. package/src/adapters/start/index.ts +1 -0
  52. package/src/libs/env.ts +4 -0
  53. package/src/providers/azure-blob/index.ts +32 -11
  54. package/src/providers/edgestore/index.ts +42 -20
  55. package/src/providers/s3/index.ts +41 -14
  56. package/src/providers/storage/objectKeys.ts +21 -0
  57. package/src/version.ts +1 -1
@@ -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,oEAAoE;AACpE,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,gBAAgB,KAAK,YAAY,CAAC,MAAM,CAAC,CAAC;AAE5E,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;uBAGjC,MAAM;gCA2C3B,MAAM,QACZ;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE;qCAoBlB,MAAM,YACjB,mBAAmB,CAAC,UAAU,CAAC,SAClC,YAAY;;;;;;;;;;;;;;;;;;;;;EAsBtB"}
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,oEAAoE;AACpE,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,gBAAgB,KAAK,YAAY,CAAC,MAAM,CAAC,CAAC;AAE5E,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;uBAGjC,MAAM;gCA2C3B,MAAM,QACZ;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE;qCAoBlB,MAAM,YACjB,mBAAmB,CAAC,UAAU,CAAC,SAClC,YAAY;;;;;;;;;;;;;;;;;;;;;EAsBtB;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,mBAAmB,CAAC,UAAU,CAAC,EACzC,UAAU,EAAE,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";
2
+ export declare const EDGE_STORE_PACKAGE_VERSION = "1.0.1";
3
3
  //# sourceMappingURL=version.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@edgestore/server",
3
- "version": "1.0.0",
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",
111
- "@edgestore/shared": "1.0.0",
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: () =>
@@ -45,6 +45,7 @@ export function createEdgeStoreNextHandler<TCtx extends AnyContext>(
45
45
  request: {
46
46
  pathname: url.pathname,
47
47
  readJson: async () => req.body,
48
+ contentType: req.headers['content-type'],
48
49
  cookieHeader: req.headers.cookie,
49
50
  cookies: req.cookies,
50
51
  createContext: () =>
@@ -32,6 +32,7 @@ export function createEdgeStoreRemixHandler<TCtx extends AnyContext>(
32
32
  request: {
33
33
  pathname: url.pathname,
34
34
  readJson: () => req.json(),
35
+ contentType: req.headers.get('content-type') ?? undefined,
35
36
  cookieHeader: req.headers.get('cookie') ?? undefined,
36
37
  createContext: () =>
37
38
  resolveContext<TCtx, CreateContextOptions>(config, {
@@ -2,6 +2,7 @@ import {
2
2
  EdgeStoreError,
3
3
  type AnyContext,
4
4
  type AnyEdgeStoreProvider,
5
+ type BackendFile,
5
6
  type EdgeStoreRouter,
6
7
  type ProviderFileMutationResult,
7
8
  type SharedConfirmUploadsRes,
@@ -20,7 +21,7 @@ import {
20
21
  } from '../core/provider';
21
22
  import { buildPath, parseBucketInput, parsePath } from '../core/routerRules';
22
23
  import { validateFileForBucket } from '../core/validateFile';
23
- import { getEnv } from '../libs/env';
24
+ import { getEnv, isProduction } from '../libs/env';
24
25
  import type { LoggerLike } from '../libs/logger';
25
26
 
26
27
  // TODO: change it to 1 hour when we have a way to refresh the token
@@ -37,7 +38,8 @@ export type CookieOptions = {
37
38
  */
38
39
  path?: string;
39
40
  /**
40
- * Cookie max age in seconds
41
+ * Cookie max age in seconds. The encrypted context token expires at the
42
+ * same time.
41
43
  * @default 2592000 (30 days)
42
44
  */
43
45
  maxAge?: number;
@@ -46,15 +48,19 @@ export type CookieOptions = {
46
48
  */
47
49
  domain?: string;
48
50
  /**
49
- * Cookie same site policy
51
+ * Cookie same site policy. Use `'none'` (with `secure: true`) only when the
52
+ * frontend calls the EdgeStore API from a different site.
53
+ * @default "lax"
50
54
  */
51
55
  sameSite?: 'strict' | 'lax' | 'none';
52
56
  /**
53
57
  * Cookie secure flag
58
+ * @default true when NODE_ENV is "production", otherwise false
54
59
  */
55
60
  secure?: boolean;
56
61
  /**
57
62
  * Cookie http only flag
63
+ * @default true
58
64
  */
59
65
  httpOnly?: boolean;
60
66
  };
@@ -79,12 +85,12 @@ export type CookieConfig = {
79
85
  type ResolvedCookieConfig = {
80
86
  ctx: {
81
87
  name: string;
82
- options: CookieOptions;
88
+ options: CookieOptions & { maxAge: number };
83
89
  };
84
90
  };
85
91
 
86
92
  /**
87
- * Merges the provided cookie configuration with default values
93
+ * Merges the provided cookie configuration with default values.
88
94
  */
89
95
  export function getCookieConfig(
90
96
  cookieConfig?: CookieConfig,
@@ -99,7 +105,14 @@ export function getCookieConfig(
99
105
  return {
100
106
  ctx: {
101
107
  name: cookieConfig?.ctx?.name ?? 'edgestore-ctx',
102
- options: { path: '/', maxAge: DEFAULT_MAX_AGE, ...configured },
108
+ options: {
109
+ path: '/',
110
+ maxAge: DEFAULT_MAX_AGE,
111
+ sameSite: 'lax',
112
+ httpOnly: true,
113
+ secure: isProduction(),
114
+ ...configured,
115
+ },
103
116
  },
104
117
  };
105
118
  }
@@ -116,7 +129,10 @@ export async function init<TCtx extends AnyContext>(params: {
116
129
 
117
130
  const resolvedCookieConfig = getCookieConfig(cookieConfig);
118
131
 
119
- const ctxToken = await encryptJWT(ctx);
132
+ const ctxToken = await encryptJWT(
133
+ ctx,
134
+ resolvedCookieConfig.ctx.options.maxAge,
135
+ );
120
136
  const { clientInit } = await provider.init({ ctx, router });
121
137
  const newCookies = [
122
138
  stringifySetCookie({
@@ -194,6 +210,35 @@ export async function requestUpload<TCtx extends AnyContext>(params: {
194
210
 
195
211
  validateFileForBucket({ bucket, fileInfo });
196
212
 
213
+ // Replacing or overwriting a file deletes it, so it needs the same
214
+ // authorization as deleting it.
215
+ const authorizeReplacement =
216
+ (action: string, refusal: string) => async (file: BackendFile) => {
217
+ const beforeDelete = requireBeforeDelete(bucket, action);
218
+ if (
219
+ !(await canDelete({
220
+ provider,
221
+ bucket,
222
+ ctx,
223
+ beforeDelete,
224
+ files: [file],
225
+ }))
226
+ ) {
227
+ throw new EdgeStoreError({
228
+ message: refusal,
229
+ code: 'UPLOAD_NOT_ALLOWED',
230
+ });
231
+ }
232
+ };
233
+ if (fileInfo.replaceTargetUrl) {
234
+ // The lookup is scoped to this bucket, so targets elsewhere are rejected.
235
+ const file = await referenceFromUrl(provider, fileInfo.replaceTargetUrl);
236
+ await authorizeReplacement(
237
+ 'replace files',
238
+ 'Replacing this file is not allowed for the current context',
239
+ )(await provider.files.get({ bucketName, file }));
240
+ }
241
+
197
242
  const path = buildPath({
198
243
  bucket,
199
244
  pathAttrs: { ctx, input: parsedInput },
@@ -223,6 +268,13 @@ export async function requestUpload<TCtx extends AnyContext>(params: {
223
268
  metadata,
224
269
  },
225
270
  autoSignedUrls,
271
+ ...(fileInfo.fileName !== undefined && {
272
+ // A client-chosen name can match an existing file.
273
+ authorizeOverwrite: authorizeReplacement(
274
+ `overwrite the existing file "${fileInfo.fileName}"`,
275
+ `A file named "${fileInfo.fileName}" already exists, and the current context may not overwrite it`,
276
+ ),
277
+ }),
226
278
  });
227
279
  const { parsedPath, pathOrder } = parsePath(path);
228
280
  const statusToken =
@@ -479,14 +531,7 @@ export async function deleteFiles<TCtx extends AnyContext>(params: {
479
531
 
480
532
  const ctx = await getContext(ctxToken);
481
533
  const bucket = getBucket(router, bucketName);
482
-
483
- if (!bucket._def.beforeDelete) {
484
- throw new EdgeStoreError({
485
- message:
486
- 'You need to define beforeDelete if you want to delete files directly from the frontend.',
487
- code: 'SERVER_ERROR',
488
- });
489
- }
534
+ const beforeDelete = requireBeforeDelete(bucket, 'delete files directly');
490
535
 
491
536
  if (!provider.files.delete) {
492
537
  throw new EdgeStoreError({
@@ -502,8 +547,65 @@ export async function deleteFiles<TCtx extends AnyContext>(params: {
502
547
  Promise.resolve(provider.files.get({ bucketName, file })),
503
548
  ),
504
549
  );
550
+ if (
551
+ !(await canDelete({
552
+ provider,
553
+ bucket,
554
+ ctx,
555
+ beforeDelete,
556
+ files: fileRecords,
557
+ }))
558
+ ) {
559
+ throw new EdgeStoreError({
560
+ message: 'Delete not allowed for the current context',
561
+ code: 'DELETE_NOT_ALLOWED',
562
+ });
563
+ }
564
+ const result = await provider.files.delete({
565
+ bucketName,
566
+ files,
567
+ });
568
+
569
+ logger.debug('Finished [deleteFiles]');
570
+
571
+ return mapFrontendMutationResult(urls, result);
572
+ }
573
+
574
+ type Bucket<TCtx extends AnyContext> = EdgeStoreRouter<TCtx>['buckets'][string];
575
+ type BeforeDelete<TCtx extends AnyContext> = NonNullable<
576
+ Bucket<TCtx>['_def']['beforeDelete']
577
+ >;
578
+
579
+ function requireBeforeDelete<TCtx extends AnyContext>(
580
+ bucket: Bucket<TCtx>,
581
+ action: string,
582
+ ) {
583
+ const { beforeDelete } = bucket._def;
584
+ if (!beforeDelete) {
585
+ throw new EdgeStoreError({
586
+ message: `You need to define beforeDelete if you want to ${action} from the frontend.`,
587
+ code: 'SERVER_ERROR',
588
+ });
589
+ }
590
+ return beforeDelete;
591
+ }
592
+
593
+ /** Runs `beforeDelete` for every file and reports whether all are allowed. */
594
+ async function canDelete<TCtx extends AnyContext>({
595
+ provider,
596
+ bucket,
597
+ ctx,
598
+ beforeDelete,
599
+ files,
600
+ }: {
601
+ provider: AnyEdgeStoreProvider;
602
+ bucket: Bucket<TCtx>;
603
+ ctx: AnyContext;
604
+ beforeDelete: BeforeDelete<TCtx>;
605
+ files: BackendFile[];
606
+ }) {
505
607
  const authorizations = await Promise.all(
506
- fileRecords.map((file) => {
608
+ files.map((file) => {
507
609
  if (file.path === undefined && bucket._def.path.length > 0) {
508
610
  throw new EdgeStoreError({
509
611
  message: `Provider ${provider.name} must return path from files.get to authorize frontend deletion for a bucket with configured path fields.`,
@@ -517,7 +619,7 @@ export async function deleteFiles<TCtx extends AnyContext>(params: {
517
619
  });
518
620
  }
519
621
  return Promise.resolve(
520
- bucket._def.beforeDelete!({
622
+ beforeDelete({
521
623
  ctx,
522
624
  fileInfo: {
523
625
  url: file.url,
@@ -530,20 +632,7 @@ export async function deleteFiles<TCtx extends AnyContext>(params: {
530
632
  );
531
633
  }),
532
634
  );
533
- if (authorizations.some((allowed) => !allowed)) {
534
- throw new EdgeStoreError({
535
- message: 'Delete not allowed for the current context',
536
- code: 'DELETE_NOT_ALLOWED',
537
- });
538
- }
539
- const result = await provider.files.delete({
540
- bucketName,
541
- files,
542
- });
543
-
544
- logger.debug('Finished [deleteFiles]');
545
-
546
- return mapFrontendMutationResult(urls, result);
635
+ return authorizations.every(Boolean);
547
636
  }
548
637
 
549
638
  function mapFrontendMutationResult(
@@ -579,11 +668,12 @@ function getBucket<TCtx extends AnyContext>(
579
668
  return bucket;
580
669
  }
581
670
 
582
- async function encryptJWT(ctx: AnyContext) {
671
+ /** Encrypts the context into a token that expires with its cookie. */
672
+ async function encryptJWT(ctx: AnyContext, maxAge: number) {
583
673
  return await new EncryptJWT({ ctx })
584
674
  .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
585
675
  .setIssuedAt()
586
- .setExpirationTime(Date.now() / 1000 + DEFAULT_MAX_AGE)
676
+ .setExpirationTime(Date.now() / 1000 + maxAge)
587
677
  .setJti(crypto.randomUUID())
588
678
  .encrypt(await getEncryptionKey());
589
679
  }
@@ -631,7 +721,8 @@ const contextPayloadSchema = z.object({
631
721
  async function getContext(token: string | undefined) {
632
722
  if (!token) {
633
723
  throw new EdgeStoreError({
634
- message: 'Missing edgestore-ctx cookie',
724
+ message:
725
+ '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.',
635
726
  code: 'UNAUTHORIZED',
636
727
  });
637
728
  }
@@ -32,6 +32,7 @@ export function createEdgeStoreStartHandler<TCtx extends AnyContext>(
32
32
  request: {
33
33
  pathname: url.pathname,
34
34
  readJson: () => request.json(),
35
+ contentType: request.headers.get('content-type') ?? undefined,
35
36
  cookieHeader: request.headers.get('cookie') ?? undefined,
36
37
  createContext: () =>
37
38
  resolveContext<TCtx, CreateContextOptions>(config, {
package/src/libs/env.ts CHANGED
@@ -23,3 +23,7 @@ export function isDev(): boolean {
23
23
  import.meta.env?.DEV
24
24
  );
25
25
  }
26
+
27
+ export function isProduction(): boolean {
28
+ return getEnv('NODE_ENV') === 'production';
29
+ }