@convex-dev/better-auth 0.7.9 → 0.7.11

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 (41) hide show
  1. package/README.md +7 -1
  2. package/dist/commonjs/client/index.d.ts.map +1 -1
  3. package/dist/commonjs/client/index.js +5 -7
  4. package/dist/commonjs/client/index.js.map +1 -1
  5. package/dist/commonjs/plugins/convex/index.d.ts +27 -13
  6. package/dist/commonjs/plugins/convex/index.d.ts.map +1 -1
  7. package/dist/commonjs/plugins/convex/index.js +3 -1
  8. package/dist/commonjs/plugins/convex/index.js.map +1 -1
  9. package/dist/commonjs/react-start/index.d.ts.map +1 -1
  10. package/dist/commonjs/react-start/index.js +11 -0
  11. package/dist/commonjs/react-start/index.js.map +1 -1
  12. package/dist/esm/client/index.d.ts.map +1 -1
  13. package/dist/esm/client/index.js +5 -7
  14. package/dist/esm/client/index.js.map +1 -1
  15. package/dist/esm/plugins/convex/index.d.ts +27 -13
  16. package/dist/esm/plugins/convex/index.d.ts.map +1 -1
  17. package/dist/esm/plugins/convex/index.js +3 -1
  18. package/dist/esm/plugins/convex/index.js.map +1 -1
  19. package/dist/esm/react-start/index.d.ts.map +1 -1
  20. package/dist/esm/react-start/index.js +11 -0
  21. package/dist/esm/react-start/index.js.map +1 -1
  22. package/package.json +8 -19
  23. package/src/client/index.ts +5 -7
  24. package/src/plugins/convex/index.ts +11 -4
  25. package/src/react-start/index.ts +13 -0
  26. package/dist/commonjs/client/cors.d.ts +0 -77
  27. package/dist/commonjs/client/cors.d.ts.map +0 -1
  28. package/dist/commonjs/client/cors.js +0 -297
  29. package/dist/commonjs/client/cors.js.map +0 -1
  30. package/dist/commonjs/util.d.ts +0 -2
  31. package/dist/commonjs/util.d.ts.map +0 -1
  32. package/dist/commonjs/util.js +0 -8
  33. package/dist/commonjs/util.js.map +0 -1
  34. package/dist/esm/client/cors.d.ts +0 -77
  35. package/dist/esm/client/cors.d.ts.map +0 -1
  36. package/dist/esm/client/cors.js +0 -297
  37. package/dist/esm/client/cors.js.map +0 -1
  38. package/dist/esm/util.d.ts +0 -2
  39. package/dist/esm/util.d.ts.map +0 -1
  40. package/dist/esm/util.js +0 -8
  41. package/dist/esm/util.js.map +0 -1
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "bugs": {
7
7
  "url": "https://github.com/get-convex/better-auth/issues"
8
8
  },
9
- "version": "0.7.9",
9
+ "version": "0.7.11",
10
10
  "license": "Apache-2.0",
11
11
  "keywords": [
12
12
  "convex",
@@ -18,9 +18,12 @@
18
18
  ],
19
19
  "type": "module",
20
20
  "scripts": {
21
- "build": "npm run build:esm && npm run build:cjs",
22
- "build:esm": "tsc --project ./esm.json && tsc-alias -p ./esm.json && echo '{\\n \"type\": \"module\"\\n}' > dist/esm/package.json",
23
- "build:cjs": "tsc --project ./commonjs.json && echo '{\\n \"type\": \"commonjs\"\\n}' > dist/commonjs/package.json",
21
+ "build": "npm run generate && npm run build:esm && npm run build:cjs",
22
+ "build:esm": "tsc --project ./esm.json && tsc-alias -p ./esm.json && npm run build:esm:generatePackageJson",
23
+ "build:cjs": "tsc --project ./commonjs.json && npm run build:cjs:generatePackageJson",
24
+ "build:esm:generatePackageJson": "echo '{\\n \"type\": \"module\"\\n}' > dist/esm/package.json",
25
+ "build:cjs:generatePackageJson": "echo '{\\n \"type\": \"commonjs\"\\n}' > dist/commonjs/package.json",
26
+ "build:watch": "chokidar 'tsconfig*.json' 'src/**/*.ts' -c 'npm run build' --initial",
24
27
  "typecheck": "tsc --noEmit",
25
28
  "prepare": "npm run build",
26
29
  "prepack": "node node10stubs.mjs",
@@ -40,91 +43,76 @@
40
43
  "./package.json": "./package.json",
41
44
  ".": {
42
45
  "import": {
43
- "@convex-dev/component-source": "./src/client/index.ts",
44
46
  "types": "./dist/esm/client/index.d.ts",
45
47
  "default": "./dist/esm/client/index.js"
46
48
  },
47
49
  "require": {
48
- "@convex-dev/component-source": "./src/client/index.ts",
49
50
  "types": "./dist/commonjs/client/index.d.ts",
50
51
  "default": "./dist/commonjs/client/index.js"
51
52
  }
52
53
  },
53
54
  "./client/plugins": {
54
55
  "import": {
55
- "@convex-dev/component-source": "./src/client/plugins/index.ts",
56
56
  "types": "./dist/esm/client/plugins/index.d.ts",
57
57
  "default": "./dist/esm/client/plugins/index.js"
58
58
  },
59
59
  "require": {
60
- "@convex-dev/component-source": "./src/plugins/clientPlugins.ts",
61
60
  "types": "./dist/commonjs/plugins/clientPlugins.d.ts",
62
61
  "default": "./dist/commonjs/plugins/clientPlugins.js"
63
62
  }
64
63
  },
65
64
  "./nextjs": {
66
65
  "import": {
67
- "@convex-dev/component-source": "./src/nextjs/index.ts",
68
66
  "types": "./dist/esm/nextjs/index.d.ts",
69
67
  "default": "./dist/esm/nextjs/index.js"
70
68
  },
71
69
  "require": {
72
- "@convex-dev/component-source": "./src/nextjs/index.ts",
73
70
  "types": "./dist/commonjs/nextjs/index.d.ts",
74
71
  "default": "./dist/commonjs/nextjs/index.js"
75
72
  }
76
73
  },
77
74
  "./plugins": {
78
75
  "import": {
79
- "@convex-dev/component-source": "./src/plugins/index.ts",
80
76
  "types": "./dist/esm/plugins/index.d.ts",
81
77
  "default": "./dist/esm/plugins/index.js"
82
78
  },
83
79
  "require": {
84
- "@convex-dev/component-source": "./src/plugins/index.ts",
85
80
  "types": "./dist/commonjs/plugins/index.d.ts",
86
81
  "default": "./dist/commonjs/plugins/index.js"
87
82
  }
88
83
  },
89
84
  "./react": {
90
85
  "import": {
91
- "@convex-dev/component-source": "./src/react/index.tsx",
92
86
  "types": "./dist/esm/react/index.d.ts",
93
87
  "default": "./dist/esm/react/index.js"
94
88
  },
95
89
  "require": {
96
- "@convex-dev/component-source": "./src/react/index.tsx",
97
90
  "types": "./dist/commonjs/react/index.d.ts",
98
91
  "default": "./dist/commonjs/react/index.js"
99
92
  }
100
93
  },
101
94
  "./react-start": {
102
95
  "import": {
103
- "@convex-dev/component-source": "./src/react-start/index.ts",
104
96
  "types": "./dist/esm/react-start/index.d.ts",
105
97
  "default": "./dist/esm/react-start/index.js"
106
98
  },
107
99
  "require": {
108
- "@convex-dev/component-source": "./src/react-start/index.ts",
109
100
  "types": "./dist/commonjs/react-start/index.d.ts",
110
101
  "default": "./dist/commonjs/react-start/index.js"
111
102
  }
112
103
  },
113
104
  "./utils": {
114
105
  "import": {
115
- "@convex-dev/component-source": "./src/utils/index.ts",
116
106
  "types": "./dist/esm/utils/index.d.ts",
117
107
  "default": "./dist/esm/utils/index.js"
118
108
  },
119
109
  "require": {
120
- "@convex-dev/component-source": "./src/utils/index.ts",
121
110
  "types": "./dist/commonjs/utils/index.d.ts",
122
111
  "default": "./dist/commonjs/utils/index.js"
123
112
  }
124
113
  },
125
114
  "./convex.config": {
126
115
  "import": {
127
- "@convex-dev/component-source": "./src/component/convex.config.ts",
128
116
  "types": "./dist/esm/component/convex.config.d.ts",
129
117
  "default": "./dist/esm/component/convex.config.js"
130
118
  }
@@ -155,6 +143,7 @@
155
143
  "@types/react": "19.1.6",
156
144
  "@types/react-dom": "19.1.6",
157
145
  "@types/semver": "^7.7.0",
146
+ "chokidar-cli": "^3.0.0",
158
147
  "concurrently": "^9.2.0",
159
148
  "convex-test": "^0.0.33",
160
149
  "eslint": "^9.9.1",
@@ -113,14 +113,12 @@ export class BetterAuth<UserId extends string = string> {
113
113
  }
114
114
 
115
115
  async getHeaders(ctx: RunQueryCtx & { auth: ConvexAuth }) {
116
- const identity = await ctx.auth.getUserIdentity();
117
- if (!identity) {
118
- return new Headers();
119
- }
120
116
  const session = await ctx.runQuery(this.component.lib.getCurrentSession);
121
- return new Headers({
122
- authorization: `Bearer ${session?.token}`,
123
- });
117
+ return session
118
+ ? new Headers({
119
+ authorization: `Bearer ${session.token}`,
120
+ })
121
+ : new Headers();
124
122
  }
125
123
 
126
124
  // TODO: use the proper id type for auth functions
@@ -7,15 +7,17 @@ import {
7
7
  bearer as bearerPlugin,
8
8
  oidcProvider as oidcProviderPlugin,
9
9
  } from "better-auth/plugins";
10
+ import { BetterAuthOptions } from "better-auth/types";
10
11
  import { omit } from "convex-helpers";
11
12
  import { z } from "zod";
12
13
 
13
14
  export const JWT_COOKIE_NAME = "convex_jwt";
14
15
 
15
- export const convex = (
16
+ export const convex = <O extends BetterAuthOptions>(
16
17
  opts: {
17
18
  jwtExpirationSeconds?: number;
18
19
  deleteExpiredSessionsOnLogin?: boolean;
20
+ options?: O;
19
21
  } = {}
20
22
  ) => {
21
23
  const {
@@ -23,17 +25,22 @@ export const convex = (
23
25
  deleteExpiredSessionsOnLogin = false,
24
26
  } = opts;
25
27
  const customSession = customSessionPlugin(async ({ user, session }) => {
26
- const { userId, ...userData } = omit(user, ["id"]) as typeof user & {
28
+ // Doing terrible things with types because user and session aren't actually
29
+ // objects and we need plugin inference to work
30
+ const { userId, ...userData } = omit(
31
+ user as typeof user & { id: string; userId: string },
32
+ ["id"]
33
+ ) as typeof user & {
27
34
  userId: string;
28
35
  };
29
36
  return {
30
37
  user: { ...userData, id: userId },
31
38
  session: {
32
- ...session,
39
+ ...(session as typeof session & {}),
33
40
  userId,
34
41
  },
35
42
  };
36
- });
43
+ }, opts.options);
37
44
  const oidcProvider = oidcProviderPlugin({
38
45
  loginPage: "/not-used",
39
46
  metadata: {
@@ -3,6 +3,7 @@ import { createCookieGetter } from "better-auth/cookies";
3
3
  import { betterFetch } from "@better-fetch/fetch";
4
4
  import { GenericActionCtx } from "convex/server";
5
5
  import { JWT_COOKIE_NAME } from "../plugins/convex";
6
+ import { oneLine } from "common-tags";
6
7
 
7
8
  export const getCookieName = async (
8
9
  createAuth: (ctx: GenericActionCtx<any>) => ReturnType<typeof betterAuth>
@@ -70,6 +71,18 @@ export const reactStartHelpers = (
70
71
  createAuth: (ctx: GenericActionCtx<any>) => ReturnType<typeof betterAuth>,
71
72
  opts: { convexSiteUrl: string; verbose?: boolean }
72
73
  ) => {
74
+ if (!opts.convexSiteUrl) {
75
+ throw new Error("opts.convexSiteUrl is required");
76
+ }
77
+ if (opts.convexSiteUrl.endsWith(".convex.cloud")) {
78
+ throw new Error(
79
+ oneLine(`
80
+ opts.convexSiteUrl ends with .convex.cloud, which is your cloud URL.
81
+ Use your Convex site URL instead.
82
+ https://docs.convex.dev/production/environment-variables#system-environment-variables
83
+ `)
84
+ );
85
+ }
73
86
  return {
74
87
  fetchSession: (request: Request) => fetchSession(request, opts),
75
88
  reactStartHandler: (request: Request) => reactStartHandler(request, opts),
@@ -1,77 +0,0 @@
1
- /**
2
- * This file defines a CorsHttpRouter class that extends Convex's HttpRouter.
3
- * It provides CORS (Cross-Origin Resource Sharing) support for HTTP routes.
4
- *
5
- * The CorsHttpRouter:
6
- * 1. Allows specifying allowed origins for CORS.
7
- * 2. Overrides the route method to add CORS headers to all non-OPTIONS requests.
8
- * 3. Automatically adds an OPTIONS route to handle CORS preflight requests.
9
- * 4. Uses the handleCors helper function to apply CORS headers consistently.
10
- *
11
- * This router simplifies the process of making Convex HTTP endpoints
12
- * accessible to web applications hosted on different domains while
13
- * maintaining proper CORS configuration.
14
- */
15
- import { HttpRouter, type RouteSpec } from "convex/server";
16
- export declare const DEFAULT_EXPOSED_HEADERS: string[];
17
- export type CorsConfig = {
18
- /**
19
- * Whether to allow credentials in the request.
20
- * When true, the request can include cookies and authentication headers.
21
- * @default false
22
- */
23
- allowCredentials?: boolean;
24
- /**
25
- * An array of allowed origins: what domains are allowed to make requests.
26
- * For example, ["https://example.com"] would only allow requests from
27
- * https://example.com.
28
- * You can also use wildcards to allow all subdomains of a given domain.
29
- * E.g. ["*.example.com"] would allow requests from:
30
- * - https://subdomain.example.com
31
- * - https://example.com
32
- * @default ["*"]
33
- */
34
- allowedOrigins?: string[] | ((req: Request) => Promise<string[]>);
35
- /**
36
- * An array of allowed headers: what headers are allowed to be sent in
37
- * the request.
38
- * @default ["Content-Type"]
39
- */
40
- allowedHeaders?: string[];
41
- /**
42
- * An array of exposed headers: what headers are allowed to be sent in
43
- * the response.
44
- * Note: if you pass in an empty array, it will not expose any headers.
45
- * If you want to extend the default exposed headers, you can do so by
46
- * passing in [...DEFAULT_EXPOSED_HEADERS, ...yourHeaders].
47
- * @default {@link DEFAULT_EXPOSED_HEADERS}
48
- */
49
- exposedHeaders?: string[];
50
- /**
51
- * The maximum age of the preflight request in seconds.
52
- * @default 86400 (1 day)
53
- */
54
- browserCacheMaxAge?: number;
55
- /**
56
- * Whether to block requests from origins that are not in the allowedOrigins list.
57
- * @default true
58
- */
59
- enforceAllowOrigins?: boolean;
60
- /**
61
- * Whether to log debugging information about CORS requests.
62
- * @default false
63
- */
64
- debug?: boolean;
65
- };
66
- type RouteSpecWithCors = RouteSpec & CorsConfig;
67
- /**
68
- * Factory function to create a router that adds CORS support to routes.
69
- * @param allowedOrigins An array of allowed origins for CORS.
70
- * @returns A function to use instead of http.route when you want CORS.
71
- */
72
- export declare const corsRouter: (http: HttpRouter, corsConfig?: CorsConfig) => {
73
- http: HttpRouter;
74
- route: (routeSpec: RouteSpecWithCors) => void;
75
- };
76
- export default corsRouter;
77
- //# sourceMappingURL=cors.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cors.d.ts","sourceRoot":"","sources":["../../../src/client/cors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAIL,UAAU,EAIV,KAAK,SAAS,EAGf,MAAM,eAAe,CAAC;AAEvB,eAAO,MAAM,uBAAuB,UAInC,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;;;;;;;OASG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IAClE;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B;;;OAGG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF,KAAK,iBAAiB,GAAG,SAAS,GAAG,UAAU,CAAC;AAEhD;;;;GAIG;AACH,eAAO,MAAM,UAAU,GAAI,MAAM,UAAU,EAAE,aAAa,UAAU;;uBAK7C,iBAAiB,KAAG,IAAI;CAsD9C,CAAC;AA+DF,eAAe,UAAU,CAAC"}
@@ -1,297 +0,0 @@
1
- /**
2
- * This file defines a CorsHttpRouter class that extends Convex's HttpRouter.
3
- * It provides CORS (Cross-Origin Resource Sharing) support for HTTP routes.
4
- *
5
- * The CorsHttpRouter:
6
- * 1. Allows specifying allowed origins for CORS.
7
- * 2. Overrides the route method to add CORS headers to all non-OPTIONS requests.
8
- * 3. Automatically adds an OPTIONS route to handle CORS preflight requests.
9
- * 4. Uses the handleCors helper function to apply CORS headers consistently.
10
- *
11
- * This router simplifies the process of making Convex HTTP endpoints
12
- * accessible to web applications hosted on different domains while
13
- * maintaining proper CORS configuration.
14
- */
15
- import { httpActionGeneric, httpRouter, ROUTABLE_HTTP_METHODS, } from "convex/server";
16
- export const DEFAULT_EXPOSED_HEADERS = [
17
- // For Range requests
18
- "Content-Range",
19
- "Accept-Ranges",
20
- ];
21
- /**
22
- * Factory function to create a router that adds CORS support to routes.
23
- * @param allowedOrigins An array of allowed origins for CORS.
24
- * @returns A function to use instead of http.route when you want CORS.
25
- */
26
- export const corsRouter = (http, corsConfig) => {
27
- const allowedExactMethodsByPath = new Map();
28
- const allowedPrefixMethodsByPath = new Map();
29
- return {
30
- http,
31
- route: (routeSpec) => {
32
- const tempRouter = httpRouter();
33
- tempRouter.exactRoutes = http.exactRoutes;
34
- tempRouter.prefixRoutes = http.prefixRoutes;
35
- const config = {
36
- ...corsConfig,
37
- ...routeSpec,
38
- };
39
- const httpCorsHandler = handleCors({
40
- originalHandler: routeSpec.handler,
41
- allowedMethods: [routeSpec.method],
42
- ...config,
43
- });
44
- /**
45
- * Figure out what kind of route we're adding: exact or prefix and handle
46
- * accordingly.
47
- */
48
- if ("path" in routeSpec) {
49
- let methods = allowedExactMethodsByPath.get(routeSpec.path);
50
- if (!methods) {
51
- methods = new Set();
52
- allowedExactMethodsByPath.set(routeSpec.path, methods);
53
- }
54
- methods.add(routeSpec.method);
55
- tempRouter.route({
56
- path: routeSpec.path,
57
- method: routeSpec.method,
58
- handler: httpCorsHandler,
59
- });
60
- handleExactRoute(tempRouter, routeSpec, config, Array.from(methods));
61
- }
62
- else {
63
- let methods = allowedPrefixMethodsByPath.get(routeSpec.pathPrefix);
64
- if (!methods) {
65
- methods = new Set();
66
- allowedPrefixMethodsByPath.set(routeSpec.pathPrefix, methods);
67
- }
68
- methods.add(routeSpec.method);
69
- tempRouter.route({
70
- pathPrefix: routeSpec.pathPrefix,
71
- method: routeSpec.method,
72
- handler: httpCorsHandler,
73
- });
74
- handlePrefixRoute(tempRouter, routeSpec, config, Array.from(methods));
75
- }
76
- /**
77
- * Copy the routes from the temporary router to the main router.
78
- */
79
- http.exactRoutes = new Map(tempRouter.exactRoutes);
80
- http.prefixRoutes = new Map(tempRouter.prefixRoutes);
81
- },
82
- };
83
- };
84
- /**
85
- * Handles exact route matching and adds OPTIONS handler.
86
- * @param tempRouter Temporary router instance.
87
- * @param routeSpec Route specification for exact matching.
88
- */
89
- function handleExactRoute(tempRouter, routeSpec, config, allowedMethods) {
90
- const currentMethodsForPath = tempRouter.exactRoutes.get(routeSpec.path);
91
- /**
92
- * Add the OPTIONS handler for the given path
93
- */
94
- const optionsHandler = createOptionsHandlerForMethods(allowedMethods, config);
95
- currentMethodsForPath?.set("OPTIONS", optionsHandler);
96
- tempRouter.exactRoutes.set(routeSpec.path, new Map(currentMethodsForPath));
97
- }
98
- /**
99
- * Handles prefix route matching and adds OPTIONS handler.
100
- * @param tempRouter Temporary router instance.
101
- * @param routeSpec Route specification for prefix matching.
102
- */
103
- function handlePrefixRoute(tempRouter, routeSpec, config, allowedMethods) {
104
- /**
105
- * prefixRoutes is structured differently than exactRoutes. It's defined as
106
- * a Map<string, Map<string, PublicHttpAction>> where the KEY is the
107
- * METHOD and the VALUE is a map of paths and handlers.
108
- */
109
- const optionsHandler = createOptionsHandlerForMethods(allowedMethods, config);
110
- const optionsPrefixes = tempRouter.prefixRoutes.get("OPTIONS") ||
111
- new Map();
112
- optionsPrefixes.set(routeSpec.pathPrefix, optionsHandler);
113
- tempRouter.prefixRoutes.set("OPTIONS", optionsPrefixes);
114
- }
115
- /**
116
- * Creates an OPTIONS handler for the given HTTP methods.
117
- * @param methods Array of HTTP methods to be allowed.
118
- * @returns A CORS-enabled OPTIONS handler.
119
- */
120
- function createOptionsHandlerForMethods(methods, config) {
121
- return handleCors({
122
- ...config,
123
- allowedMethods: methods,
124
- });
125
- }
126
- export default corsRouter;
127
- /**
128
- * handleCors() is a higher-order function that wraps a Convex HTTP action handler to add CORS support.
129
- * It allows for customization of allowed HTTP methods and origins for cross-origin requests.
130
- *
131
- * The function:
132
- * 1. Validates and normalizes the allowed HTTP methods.
133
- * 2. Generates appropriate CORS headers based on the provided configuration.
134
- * 3. Handles preflight OPTIONS requests automatically.
135
- * 4. Wraps the original handler to add CORS headers to its response.
136
- *
137
- * This helper simplifies the process of making Convex HTTP actions accessible
138
- * to web applications hosted on different domains.
139
- */
140
- const SECONDS_IN_A_DAY = 60 * 60 * 24;
141
- /**
142
- * Example CORS origins:
143
- * - "*" (allow all origins)
144
- * - "https://example.com" (allow a specific domain)
145
- * - "https://*.example.com" (allow all subdomains of example.com)
146
- * - "https://example1.com, https://example2.com" (allow multiple specific domains)
147
- * - "null" (allow requests from data URLs or local files)
148
- */
149
- const handleCors = ({ originalHandler, allowedMethods = ["OPTIONS"], allowedOrigins = ["*"], allowedHeaders = ["Content-Type"], exposedHeaders = DEFAULT_EXPOSED_HEADERS, allowCredentials = false, browserCacheMaxAge = SECONDS_IN_A_DAY, enforceAllowOrigins = true, debug = false, }) => {
150
- const uniqueMethods = Array.from(new Set(allowedMethods.map((method) => method.toUpperCase())));
151
- const filteredMethods = uniqueMethods.filter((method) => ROUTABLE_HTTP_METHODS.includes(method));
152
- if (filteredMethods.length === 0) {
153
- throw new Error("No valid HTTP methods provided");
154
- }
155
- /**
156
- * Ensure OPTIONS is not duplicated if it was passed in
157
- * E.g. if allowedMethods = ["GET", "OPTIONS"]
158
- */
159
- const allowMethods = filteredMethods.includes("OPTIONS")
160
- ? filteredMethods.join(", ")
161
- : [...filteredMethods].join(", ");
162
- /**
163
- * Build up the set of CORS headers
164
- */
165
- const commonHeaders = {
166
- Vary: "Origin",
167
- };
168
- if (allowCredentials) {
169
- commonHeaders["Access-Control-Allow-Credentials"] = "true";
170
- }
171
- if (exposedHeaders.length > 0) {
172
- commonHeaders["Access-Control-Expose-Headers"] = exposedHeaders.join(", ");
173
- }
174
- async function parseAllowedOrigins(request) {
175
- return Array.isArray(allowedOrigins)
176
- ? allowedOrigins
177
- : await allowedOrigins(request);
178
- }
179
- // Helper function to check if origin is allowed (including wildcard subdomain matching)
180
- async function isAllowedOrigin(request) {
181
- const requestOrigin = request.headers.get("origin");
182
- if (!requestOrigin)
183
- return false;
184
- return (await parseAllowedOrigins(request)).some((allowed) => {
185
- if (allowed === "*")
186
- return true;
187
- if (allowed === requestOrigin)
188
- return true;
189
- if (allowed.startsWith("*.")) {
190
- const wildcardDomain = allowed.slice(1); // ".bar.com"
191
- const rootDomain = allowed.slice(2); // "bar.com"
192
- try {
193
- const url = new URL(requestOrigin);
194
- return (url.protocol === "https:" &&
195
- (url.hostname.endsWith(wildcardDomain) ||
196
- url.hostname === rootDomain));
197
- }
198
- catch {
199
- return false; // Invalid URL format
200
- }
201
- }
202
- return false;
203
- });
204
- }
205
- /**
206
- * Return our modified HTTP action
207
- */
208
- return httpActionGeneric(async (ctx, request) => {
209
- if (debug) {
210
- console.log("CORS request", {
211
- path: request.url,
212
- origin: request.headers.get("origin"),
213
- headers: request.headers,
214
- method: request.method,
215
- body: request.body,
216
- });
217
- }
218
- const requestOrigin = request.headers.get("origin");
219
- const parsedAllowedOrigins = await parseAllowedOrigins(request);
220
- if (debug) {
221
- console.log("allowed origins", parsedAllowedOrigins);
222
- }
223
- // Handle origin matching
224
- let allowOrigins = null;
225
- if (parsedAllowedOrigins.includes("*") && !allowCredentials) {
226
- allowOrigins = "*";
227
- }
228
- else if (requestOrigin) {
229
- // Check if the request origin matches any of the allowed origins
230
- // (including wildcard subdomain matching if configured)
231
- if (await isAllowedOrigin(request)) {
232
- allowOrigins = requestOrigin;
233
- }
234
- }
235
- if (enforceAllowOrigins && !allowOrigins) {
236
- // Origin not allowed
237
- console.error(`Request from origin ${requestOrigin} blocked, missing from allowed origins: ${parsedAllowedOrigins.join()}`);
238
- return new Response(null, { status: 403 });
239
- }
240
- /**
241
- * OPTIONS has no handler and just returns headers
242
- */
243
- if (request.method === "OPTIONS") {
244
- const responseHeaders = new Headers({
245
- ...commonHeaders,
246
- "Access-Control-Allow-Origin": allowOrigins ?? "",
247
- "Access-Control-Allow-Methods": allowMethods,
248
- "Access-Control-Allow-Headers": allowedHeaders.join(", "),
249
- "Access-Control-Max-Age": browserCacheMaxAge.toString(),
250
- });
251
- if (debug) {
252
- console.log("CORS OPTIONS response headers", responseHeaders);
253
- }
254
- return new Response(null, {
255
- status: 204,
256
- headers: responseHeaders,
257
- });
258
- }
259
- /**
260
- * If the method is not OPTIONS, it must pass a handler
261
- */
262
- if (!originalHandler) {
263
- throw new Error("No PublicHttpAction provider to CORS handler");
264
- }
265
- /**
266
- * First, execute the original handler
267
- */
268
- const innerHandler = ("_handler" in originalHandler
269
- ? originalHandler["_handler"]
270
- : originalHandler);
271
- const originalResponse = await innerHandler(ctx, request);
272
- /**
273
- * Second, get a copy of the original response's headers
274
- */
275
- const newHeaders = new Headers(originalResponse.headers);
276
- newHeaders.set("Access-Control-Allow-Origin", allowOrigins ?? "");
277
- /**
278
- * Third, add or update our CORS headers
279
- */
280
- Object.entries(commonHeaders).forEach(([key, value]) => {
281
- newHeaders.set(key, value);
282
- });
283
- if (debug) {
284
- console.log("CORS response headers", newHeaders);
285
- }
286
- /**
287
- * Fourth, return the modified Response.
288
- * A Response object is immutable, so we create a new one to return here.
289
- */
290
- return new Response(originalResponse.body, {
291
- status: originalResponse.status,
292
- statusText: originalResponse.statusText,
293
- headers: newHeaders,
294
- });
295
- });
296
- };
297
- //# sourceMappingURL=cors.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cors.js","sourceRoot":"","sources":["../../../src/client/cors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAEL,iBAAiB,EACjB,UAAU,EAEV,qBAAqB,GAMtB,MAAM,eAAe,CAAC;AAEvB,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,qBAAqB;IACrB,eAAe;IACf,eAAe;CAChB,CAAC;AAsDF;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,IAAgB,EAAE,UAAuB,EAAE,EAAE;IACtE,MAAM,yBAAyB,GAA6B,IAAI,GAAG,EAAE,CAAC;IACtE,MAAM,0BAA0B,GAA6B,IAAI,GAAG,EAAE,CAAC;IACvE,OAAO;QACL,IAAI;QACJ,KAAK,EAAE,CAAC,SAA4B,EAAQ,EAAE;YAC5C,MAAM,UAAU,GAAG,UAAU,EAAE,CAAC;YAChC,UAAU,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;YAC1C,UAAU,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC;YAE5C,MAAM,MAAM,GAAG;gBACb,GAAG,UAAU;gBACb,GAAG,SAAS;aACb,CAAC;YAEF,MAAM,eAAe,GAAG,UAAU,CAAC;gBACjC,eAAe,EAAE,SAAS,CAAC,OAAO;gBAClC,cAAc,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC;gBAClC,GAAG,MAAM;aACV,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AAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;YACrD,UAAU,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;QAEH,IAAI,KAAK,EAAE,CAAC;YACV,OAAO,CAAC,GAAG,CAAC,uBAAuB,EAAE,UAAU,CAAC,CAAC;QACnD,CAAC;QAED;;;WAGG;QACH,OAAO,IAAI,QAAQ,CAAC,gBAAgB,CAAC,IAAI,EAAE;YACzC,MAAM,EAAE,gBAAgB,CAAC,MAAM;YAC/B,UAAU,EAAE,gBAAgB,CAAC,UAAU;YACvC,OAAO,EAAE,UAAU;SACpB,CAAC,CAAC;IACL,CAAC,CACF,CAAC;AACJ,CAAC,CAAC"}
@@ -1,2 +0,0 @@
1
- export declare const requireEnv: (name: string) => string;
2
- //# sourceMappingURL=util.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,GAAI,MAAM,MAAM,WAMtC,CAAC"}
@@ -1,8 +0,0 @@
1
- export const requireEnv = (name) => {
2
- const value = process.env[name];
3
- if (value === undefined) {
4
- throw new Error(`Missing environment variable \`${name}\``);
5
- }
6
- return value;
7
- };
8
- //# sourceMappingURL=util.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,IAAY,EAAE,EAAE;IACzC,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAChC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,kCAAkC,IAAI,IAAI,CAAC,CAAC;IAC9D,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC,CAAC"}