@cedarjs/auth-dbauth-middleware 9.0.0-canary.1784 → 9.0.0-canary.3124

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 CHANGED
@@ -39,6 +39,27 @@ export const ServerEntry: React.FC<Props> = ({ css, meta }) => {
39
39
  }
40
40
  ```
41
41
 
42
+ ### OAuth routing
43
+
44
+ Apps using [`@cedarjs/auth-dbauth-oauth`](../oauth) opt in by also passing an `oauthHandler`, built the same way `dbAuthHandler` is — by wrapping `OAuthHandler`'s `invoke()`:
45
+
46
+ ```tsx
47
+ import { OAuthHandler } from '@cedarjs/auth-dbauth-oauth'
48
+
49
+ import { handler as dbAuthHandler } from '$api/src/functions/auth'
50
+ import { oauthOptions } from '$api/src/lib/auth'
51
+
52
+ const authMw = initDbAuthMiddleware({
53
+ dbAuthHandler,
54
+ getCurrentUser,
55
+ oauthHandler: (req, context) =>
56
+ new OAuthHandler(req, context, oauthOptions).invoke(),
57
+ // oauthUrl? optional, defaults to '/auth/oauth' (OAuthHandlerOptions.basePath's default)
58
+ })
59
+ ```
60
+
61
+ Requests whose URL falls under `oauthUrl` (`authorize`/`callback`/`unlink`) are dispatched to `oauthHandler` instead of the normal dbAuth session-validation path; its 302 redirects, `Set-Cookie` headers (session, `auth-provider`, and the OAuth transaction cookie), and JSON bodies are carried over to the middleware response unchanged. Omitting `oauthHandler` entirely disables OAuth routing — requests under `oauthUrl` simply fall through to the normal dbAuth handling below.
62
+
42
63
  ### Roles handling
43
64
 
44
65
  By default the middleware assumes your roles will be in `currentUser.roles` - either as a string or an array of strings.
package/dist/index.d.ts CHANGED
@@ -1,14 +1,38 @@
1
1
  import type { APIGatewayProxyEvent, Context } from 'aws-lambda';
2
- import type { DbAuthResponse } from '@cedarjs/auth-dbauth-api';
2
+ import type { DbAuthResponse } from '@cedarjs/auth-dbauth-api' with {
3
+ 'resolution-mode': 'import'
4
+ };
3
5
  import type { GetCurrentUser } from '@cedarjs/graphql-server';
4
6
  import type { Middleware } from '@cedarjs/web/middleware';
5
7
  export interface DbAuthMiddlewareOptions {
6
8
  cookieName?: string;
7
9
  dbAuthUrl?: string;
8
10
  dbAuthHandler: (req: Request | APIGatewayProxyEvent, context?: Context) => DbAuthResponse;
9
- getRoles?: (decoded: any) => string[];
11
+ /**
12
+ * Handler for dbAuth's OAuth routes (`/auth/oauth/...` by default),
13
+ * mirroring `dbAuthHandler`. Typically built by wrapping `OAuthHandler`
14
+ * from `@cedarjs/auth-dbauth-oauth`:
15
+ *
16
+ * ```ts
17
+ * oauthHandler: (req, context) =>
18
+ * new OAuthHandler(req, context, oauthOptions).invoke()
19
+ * ```
20
+ *
21
+ * Omitting this option leaves OAuth routing disabled entirely — requests
22
+ * under `oauthUrl` simply fall through to the normal dbAuth handling
23
+ * below.
24
+ */
25
+ oauthHandler?: (req: Request | APIGatewayProxyEvent, context?: Context) => DbAuthResponse;
26
+ /**
27
+ * URL segment routed to `oauthHandler`. Defaults to `/auth/oauth`,
28
+ * matching `OAuthHandlerOptions.basePath`'s default in
29
+ * `@cedarjs/auth-dbauth-oauth`. Only takes effect when `oauthHandler` is
30
+ * set.
31
+ */
32
+ oauthUrl?: string;
33
+ getRoles?: (decoded: Parameters<GetCurrentUser>[0]) => string[];
10
34
  getCurrentUser: GetCurrentUser;
11
35
  }
12
- export declare const initDbAuthMiddleware: ({ dbAuthHandler, getCurrentUser, getRoles, cookieName, dbAuthUrl, }: DbAuthMiddlewareOptions) => [Middleware, "*"];
36
+ export declare const initDbAuthMiddleware: ({ dbAuthHandler, oauthHandler, oauthUrl, getCurrentUser, getRoles, cookieName, dbAuthUrl, }: DbAuthMiddlewareOptions) => [Middleware, "*"];
13
37
  export default initDbAuthMiddleware;
14
38
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAE/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AAI9D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAE7D,OAAO,KAAK,EAAE,UAAU,EAAqB,MAAM,yBAAyB,CAAA;AAI5E,MAAM,WAAW,uBAAuB;IACtC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAGlB,aAAa,EAAE,CACb,GAAG,EAAE,OAAO,GAAG,oBAAoB,EACnC,OAAO,CAAC,EAAE,OAAO,KACd,cAAc,CAAA;IACnB,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,MAAM,EAAE,CAAA;IACrC,cAAc,EAAE,cAAc,CAAA;CAC/B;AAED,eAAO,MAAM,oBAAoB,GAAI,qEAMlC,uBAAuB,KAAG,CAAC,UAAU,EAAE,GAAG,CAkG5C,CAAA;AA8DD,eAAe,oBAAoB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAE/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;IAC7D,iBAAiB,EAAE,QAAQ;CAC5B,CAAA;AACD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAE7D,OAAO,KAAK,EAAE,UAAU,EAAqB,MAAM,yBAAyB,CAAA;AAI5E,MAAM,WAAW,uBAAuB;IACtC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAGlB,aAAa,EAAE,CACb,GAAG,EAAE,OAAO,GAAG,oBAAoB,EACnC,OAAO,CAAC,EAAE,OAAO,KACd,cAAc,CAAA;IACnB;;;;;;;;;;;;;OAaG;IACH,YAAY,CAAC,EAAE,CACb,GAAG,EAAE,OAAO,GAAG,oBAAoB,EACnC,OAAO,CAAC,EAAE,OAAO,KACd,cAAc,CAAA;IACnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE,CAAA;IAC/D,cAAc,EAAE,cAAc,CAAA;CAC/B;AA6BD,eAAO,MAAM,oBAAoB,GAAI,6FAQlC,uBAAuB,KAAG,CAAC,UAAU,EAAE,GAAG,CA+G5C,CAAA;AA8DD,eAAe,oBAAoB,CAAA"}
package/dist/index.js CHANGED
@@ -1,9 +1,23 @@
1
- import dbAuthApi from "@cedarjs/auth-dbauth-api";
2
- const { dbAuthSession, generateCookieName } = dbAuthApi;
3
1
  import { MiddlewareResponse } from "@cedarjs/web/middleware";
4
2
  import { defaultGetRoles } from "./defaultGetRoles.js";
3
+ function toMiddlewareResponse(output) {
4
+ const finalHeaders = new Headers();
5
+ Object.entries(output.headers).forEach(([key, value]) => {
6
+ if (Array.isArray(value)) {
7
+ value.forEach((mvhHeader) => finalHeaders.append(key, mvhHeader));
8
+ } else {
9
+ finalHeaders.append(key, value);
10
+ }
11
+ });
12
+ return new MiddlewareResponse(output.body, {
13
+ headers: finalHeaders,
14
+ status: output.statusCode
15
+ });
16
+ }
5
17
  const initDbAuthMiddleware = ({
6
18
  dbAuthHandler,
19
+ oauthHandler,
20
+ oauthUrl = "/auth/oauth",
7
21
  getCurrentUser,
8
22
  getRoles = defaultGetRoles,
9
23
  cookieName,
@@ -12,6 +26,15 @@ const initDbAuthMiddleware = ({
12
26
  const mw = async (req, res = MiddlewareResponse.next()) => {
13
27
  console.log("dbAuthUrl", dbAuthUrl);
14
28
  console.log("req.url", req.url);
29
+ const pathname = new URL(req.url).pathname;
30
+ let oauthBasePath = oauthUrl;
31
+ while (oauthBasePath.length > 1 && oauthBasePath.endsWith("/")) {
32
+ oauthBasePath = oauthBasePath.slice(0, -1);
33
+ }
34
+ if (oauthHandler && (pathname === oauthBasePath || pathname.startsWith(`${oauthBasePath}/`))) {
35
+ const output = await oauthHandler(req);
36
+ return toMiddlewareResponse(output);
37
+ }
15
38
  if (req.url.includes(dbAuthUrl)) {
16
39
  if (req.url.includes(`${dbAuthUrl}/currentUser`)) {
17
40
  const validatedSession2 = await validateSession({
@@ -29,18 +52,7 @@ const initDbAuthMiddleware = ({
29
52
  } else {
30
53
  const output = await dbAuthHandler(req);
31
54
  console.log("output", output);
32
- const finalHeaders = new Headers();
33
- Object.entries(output.headers).forEach(([key, value]) => {
34
- if (Array.isArray(value)) {
35
- value.forEach((mvhHeader) => finalHeaders.append(key, mvhHeader));
36
- } else {
37
- finalHeaders.append(key, value);
38
- }
39
- });
40
- return new MiddlewareResponse(output.body, {
41
- headers: finalHeaders,
42
- status: output.statusCode
43
- });
55
+ return toMiddlewareResponse(output);
44
56
  }
45
57
  }
46
58
  const cookieHeader = req.headers.get("Cookie");
@@ -66,6 +78,7 @@ const initDbAuthMiddleware = ({
66
78
  });
67
79
  } else {
68
80
  req.serverAuthState.clear();
81
+ const { generateCookieName } = await import("@cedarjs/auth-dbauth-api");
69
82
  res.cookies.unset(generateCookieName(cookieName));
70
83
  res.cookies.unset("auth-provider");
71
84
  }
@@ -79,11 +92,9 @@ async function validateSession({
79
92
  getCurrentUser
80
93
  }) {
81
94
  let decryptedSession;
95
+ const { dbAuthSession, generateCookieName } = await import("@cedarjs/auth-dbauth-api");
82
96
  try {
83
- decryptedSession = dbAuthSession(
84
- req,
85
- generateCookieName(cookieName)
86
- );
97
+ decryptedSession = dbAuthSession(req, generateCookieName(cookieName));
87
98
  } catch (e) {
88
99
  if (process.env.NODE_ENV === "development") {
89
100
  console.debug("Could not decrypt dbAuth session", e);
@@ -111,14 +122,14 @@ async function validateSession({
111
122
  token: req.headers.get("Cookie")
112
123
  },
113
124
  {
114
- // MWRequest is a superset of Request
115
- event: req
125
+ event: req,
126
+ request: req
116
127
  }
117
128
  );
118
129
  return { currentUser, decryptedSession };
119
130
  }
120
- var src_default = initDbAuthMiddleware;
131
+ var index_default = initDbAuthMiddleware;
121
132
  export {
122
- src_default as default,
133
+ index_default as default,
123
134
  initDbAuthMiddleware
124
135
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cedarjs/auth-dbauth-middleware",
3
- "version": "9.0.0-canary.1784+baa47810a",
3
+ "version": "9.0.0-canary.3124",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/cedarjs/cedar.git",
@@ -10,13 +10,9 @@
10
10
  "type": "module",
11
11
  "exports": {
12
12
  ".": {
13
- "import": {
13
+ "default": {
14
14
  "types": "./dist/index.d.ts",
15
15
  "default": "./dist/index.js"
16
- },
17
- "require": {
18
- "types": "./dist/cjs/index.d.ts",
19
- "default": "./dist/cjs/index.js"
20
16
  }
21
17
  }
22
18
  },
@@ -26,35 +22,36 @@
26
22
  "dist"
27
23
  ],
28
24
  "scripts": {
29
- "build": "tsx ./build.mts",
25
+ "build": "node ./build.mts",
30
26
  "build:pack": "yarn pack -o cedarjs-auth-dbauth-middleware.tgz",
31
27
  "build:types": "tsc --build --verbose ./tsconfig.build.json",
32
- "build:types-cjs": "tsc --build --verbose tsconfig.cjs.json",
33
- "check:attw": "yarn attw -P",
28
+ "check:attw": "yarn cedar-fwtools-attw",
34
29
  "check:package": "concurrently npm:check:attw yarn:publint",
35
30
  "prepublishOnly": "NODE_ENV=production yarn build",
36
31
  "test": "vitest run",
37
32
  "test:watch": "vitest watch"
38
33
  },
39
34
  "dependencies": {
40
- "@cedarjs/auth-dbauth-api": "9.0.0-canary.1784",
41
- "@cedarjs/web": "9.0.0-canary.1784"
35
+ "@cedarjs/auth-dbauth-api": "9.0.0-canary.3124",
36
+ "@cedarjs/web": "9.0.0-canary.3124"
42
37
  },
43
38
  "devDependencies": {
44
- "@arethetypeswrong/cli": "0.18.2",
45
- "@cedarjs/api": "9.0.0-canary.1784",
46
- "@cedarjs/framework-tools": "9.0.0-canary.1784",
47
- "@cedarjs/graphql-server": "9.0.0-canary.1784",
48
- "@types/aws-lambda": "8.10.160",
49
- "concurrently": "9.2.1",
50
- "publint": "0.3.17",
39
+ "@cedarjs/api": "9.0.0-canary.3124",
40
+ "@cedarjs/auth-dbauth-oauth": "9.0.0-canary.3124",
41
+ "@cedarjs/framework-tools": "9.0.0-canary.3124",
42
+ "@cedarjs/graphql-server": "9.0.0-canary.3124",
43
+ "@types/aws-lambda": "8.10.163",
44
+ "concurrently": "9.2.4",
45
+ "publint": "0.3.24",
51
46
  "ts-toolbelt": "9.6.0",
52
- "tsx": "4.21.0",
53
47
  "typescript": "5.9.3",
54
- "vitest": "3.2.4"
48
+ "vitest": "4.1.11"
49
+ },
50
+ "engines": {
51
+ "node": ">=24"
55
52
  },
56
53
  "publishConfig": {
57
54
  "access": "public"
58
55
  },
59
- "gitHead": "baa47810a7defb73de27fdf513b815d679509b5e"
56
+ "gitHead": "3905ed045508b861b495f8d5630d76c7a157d8f1"
60
57
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Cedar
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,2 +0,0 @@
1
- export declare const defaultGetRoles: (decoded: Record<string, any> | undefined | null) => string[];
2
- //# sourceMappingURL=defaultGetRoles.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"defaultGetRoles.d.ts","sourceRoot":"","sources":["../../src/defaultGetRoles.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,eAAe,GAC1B,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,SAAS,GAAG,IAAI,KAC9C,MAAM,EAYR,CAAA"}
@@ -1,39 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var defaultGetRoles_exports = {};
20
- __export(defaultGetRoles_exports, {
21
- defaultGetRoles: () => defaultGetRoles
22
- });
23
- module.exports = __toCommonJS(defaultGetRoles_exports);
24
- const defaultGetRoles = (decoded) => {
25
- try {
26
- const roles = decoded?.currentUser?.roles;
27
- if (Array.isArray(roles)) {
28
- return roles;
29
- } else {
30
- return roles ? [roles] : [];
31
- }
32
- } catch {
33
- return [];
34
- }
35
- };
36
- // Annotate the CommonJS export names for ESM import in node:
37
- 0 && (module.exports = {
38
- defaultGetRoles
39
- });
@@ -1,14 +0,0 @@
1
- import type { APIGatewayProxyEvent, Context } from 'aws-lambda';
2
- import type { DbAuthResponse } from '@cedarjs/auth-dbauth-api';
3
- import type { GetCurrentUser } from '@cedarjs/graphql-server';
4
- import type { Middleware } from '@cedarjs/web/middleware';
5
- export interface DbAuthMiddlewareOptions {
6
- cookieName?: string;
7
- dbAuthUrl?: string;
8
- dbAuthHandler: (req: Request | APIGatewayProxyEvent, context?: Context) => DbAuthResponse;
9
- getRoles?: (decoded: any) => string[];
10
- getCurrentUser: GetCurrentUser;
11
- }
12
- export declare const initDbAuthMiddleware: ({ dbAuthHandler, getCurrentUser, getRoles, cookieName, dbAuthUrl, }: DbAuthMiddlewareOptions) => [Middleware, "*"];
13
- export default initDbAuthMiddleware;
14
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAE/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AAI9D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAE7D,OAAO,KAAK,EAAE,UAAU,EAAqB,MAAM,yBAAyB,CAAA;AAI5E,MAAM,WAAW,uBAAuB;IACtC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,SAAS,CAAC,EAAE,MAAM,CAAA;IAGlB,aAAa,EAAE,CACb,GAAG,EAAE,OAAO,GAAG,oBAAoB,EACnC,OAAO,CAAC,EAAE,OAAO,KACd,cAAc,CAAA;IACnB,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,MAAM,EAAE,CAAA;IACrC,cAAc,EAAE,cAAc,CAAA;CAC/B;AAED,eAAO,MAAM,oBAAoB,GAAI,qEAMlC,uBAAuB,KAAG,CAAC,UAAU,EAAE,GAAG,CAkG5C,CAAA;AA8DD,eAAe,oBAAoB,CAAA"}
package/dist/cjs/index.js DELETED
@@ -1,158 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var src_exports = {};
30
- __export(src_exports, {
31
- default: () => src_default,
32
- initDbAuthMiddleware: () => initDbAuthMiddleware
33
- });
34
- module.exports = __toCommonJS(src_exports);
35
- var import_auth_dbauth_api = __toESM(require("@cedarjs/auth-dbauth-api"), 1);
36
- var import_middleware = require("@cedarjs/web/middleware");
37
- var import_defaultGetRoles = require("./defaultGetRoles.js");
38
- const { dbAuthSession, generateCookieName } = import_auth_dbauth_api.default;
39
- const initDbAuthMiddleware = ({
40
- dbAuthHandler,
41
- getCurrentUser,
42
- getRoles = import_defaultGetRoles.defaultGetRoles,
43
- cookieName,
44
- dbAuthUrl = "/middleware/dbauth"
45
- }) => {
46
- const mw = async (req, res = import_middleware.MiddlewareResponse.next()) => {
47
- console.log("dbAuthUrl", dbAuthUrl);
48
- console.log("req.url", req.url);
49
- if (req.url.includes(dbAuthUrl)) {
50
- if (req.url.includes(`${dbAuthUrl}/currentUser`)) {
51
- const validatedSession2 = await validateSession({
52
- req,
53
- cookieName,
54
- getCurrentUser
55
- });
56
- if (validatedSession2) {
57
- return new import_middleware.MiddlewareResponse(
58
- JSON.stringify({ currentUser: validatedSession2.currentUser })
59
- );
60
- } else {
61
- return new import_middleware.MiddlewareResponse(JSON.stringify({ currentUser: null }));
62
- }
63
- } else {
64
- const output = await dbAuthHandler(req);
65
- console.log("output", output);
66
- const finalHeaders = new Headers();
67
- Object.entries(output.headers).forEach(([key, value]) => {
68
- if (Array.isArray(value)) {
69
- value.forEach((mvhHeader) => finalHeaders.append(key, mvhHeader));
70
- } else {
71
- finalHeaders.append(key, value);
72
- }
73
- });
74
- return new import_middleware.MiddlewareResponse(output.body, {
75
- headers: finalHeaders,
76
- status: output.statusCode
77
- });
78
- }
79
- }
80
- const cookieHeader = req.headers.get("Cookie");
81
- if (!cookieHeader?.includes("auth-provider")) {
82
- return res;
83
- }
84
- const validatedSession = await validateSession({
85
- req,
86
- cookieName,
87
- getCurrentUser
88
- });
89
- if (validatedSession) {
90
- const { currentUser, decryptedSession } = validatedSession;
91
- req.serverAuthState.set({
92
- currentUser,
93
- loading: false,
94
- isAuthenticated: !!currentUser,
95
- hasError: false,
96
- userMetadata: currentUser,
97
- // dbAuth doesn't have userMetadata
98
- cookieHeader,
99
- roles: getRoles(decryptedSession)
100
- });
101
- } else {
102
- req.serverAuthState.clear();
103
- res.cookies.unset(generateCookieName(cookieName));
104
- res.cookies.unset("auth-provider");
105
- }
106
- return res;
107
- };
108
- return [mw, "*"];
109
- };
110
- async function validateSession({
111
- req,
112
- cookieName,
113
- getCurrentUser
114
- }) {
115
- let decryptedSession;
116
- try {
117
- decryptedSession = dbAuthSession(
118
- req,
119
- generateCookieName(cookieName)
120
- );
121
- } catch (e) {
122
- if (process.env.NODE_ENV === "development") {
123
- console.debug("Could not decrypt dbAuth session", e);
124
- }
125
- return void 0;
126
- }
127
- if (!decryptedSession) {
128
- if (process.env.NODE_ENV === "development") {
129
- console.debug(
130
- "No dbAuth session cookie found. Looking for a cookie named:",
131
- cookieName
132
- );
133
- }
134
- return void 0;
135
- }
136
- const currentUser = await getCurrentUser(
137
- decryptedSession,
138
- {
139
- type: "dbAuth",
140
- schema: "cookie",
141
- // @MARK: We pass the entire cookie header as a token. This isn't
142
- // actually the token!
143
- // At this point the Cookie header is guaranteed, because otherwise a
144
- // decryptionError would have been thrown
145
- token: req.headers.get("Cookie")
146
- },
147
- {
148
- // MWRequest is a superset of Request
149
- event: req
150
- }
151
- );
152
- return { currentUser, decryptedSession };
153
- }
154
- var src_default = initDbAuthMiddleware;
155
- // Annotate the CommonJS export names for ESM import in node:
156
- 0 && (module.exports = {
157
- initDbAuthMiddleware
158
- });
@@ -1 +0,0 @@
1
- {"type":"commonjs"}