@tern-secure/nextjs 4.1.0 → 4.2.0

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 (37) hide show
  1. package/dist/cjs/app-router/server/auth.js +42 -28
  2. package/dist/cjs/app-router/server/auth.js.map +1 -1
  3. package/dist/cjs/app-router/server/edge-session.js +80 -0
  4. package/dist/cjs/app-router/server/edge-session.js.map +1 -0
  5. package/dist/cjs/app-router/server/index.js +4 -0
  6. package/dist/cjs/app-router/server/index.js.map +1 -1
  7. package/dist/cjs/app-router/server/jwt.js +141 -0
  8. package/dist/cjs/app-router/server/jwt.js.map +1 -0
  9. package/dist/cjs/app-router/server/sessionTernSecure.js +14 -9
  10. package/dist/cjs/app-router/server/sessionTernSecure.js.map +1 -1
  11. package/dist/cjs/app-router/server/ternSecureMiddleware.js +134 -13
  12. package/dist/cjs/app-router/server/ternSecureMiddleware.js.map +1 -1
  13. package/dist/esm/app-router/server/auth.js +40 -28
  14. package/dist/esm/app-router/server/auth.js.map +1 -1
  15. package/dist/esm/app-router/server/edge-session.js +56 -0
  16. package/dist/esm/app-router/server/edge-session.js.map +1 -0
  17. package/dist/esm/app-router/server/index.js +4 -2
  18. package/dist/esm/app-router/server/index.js.map +1 -1
  19. package/dist/esm/app-router/server/jwt.js +117 -0
  20. package/dist/esm/app-router/server/jwt.js.map +1 -0
  21. package/dist/esm/app-router/server/sessionTernSecure.js +14 -9
  22. package/dist/esm/app-router/server/sessionTernSecure.js.map +1 -1
  23. package/dist/esm/app-router/server/ternSecureMiddleware.js +132 -13
  24. package/dist/esm/app-router/server/ternSecureMiddleware.js.map +1 -1
  25. package/dist/types/app-router/server/auth.d.ts +13 -1
  26. package/dist/types/app-router/server/auth.d.ts.map +1 -1
  27. package/dist/types/app-router/server/edge-session.d.ts +15 -0
  28. package/dist/types/app-router/server/edge-session.d.ts.map +1 -0
  29. package/dist/types/app-router/server/index.d.ts +3 -2
  30. package/dist/types/app-router/server/index.d.ts.map +1 -1
  31. package/dist/types/app-router/server/jwt.d.ts +20 -0
  32. package/dist/types/app-router/server/jwt.d.ts.map +1 -0
  33. package/dist/types/app-router/server/sessionTernSecure.d.ts +4 -1
  34. package/dist/types/app-router/server/sessionTernSecure.d.ts.map +1 -1
  35. package/dist/types/app-router/server/ternSecureMiddleware.d.ts +17 -4
  36. package/dist/types/app-router/server/ternSecureMiddleware.d.ts.map +1 -1
  37. package/package.json +2 -1
@@ -19,53 +19,67 @@ var __copyProps = (to, from, except, desc) => {
19
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
20
  var auth_exports = {};
21
21
  __export(auth_exports, {
22
- auth: () => auth
22
+ auth: () => auth,
23
+ getUserInfo: () => getUserInfo,
24
+ isAuthenticated: () => isAuthenticated
23
25
  });
24
26
  module.exports = __toCommonJS(auth_exports);
25
27
  var import_headers = require("next/headers");
26
- var import_sessionTernSecure = require("./sessionTernSecure");
27
28
  async function auth() {
28
- var _a, _b, _c;
29
+ var _a, _b;
29
30
  try {
31
+ const headersList = await (0, import_headers.headers)();
30
32
  const cookieStore = await (0, import_headers.cookies)();
31
- const sessionCookie = (_a = cookieStore.get("_session_cookie")) == null ? void 0 : _a.value;
32
- if (sessionCookie) {
33
- const sessionResult = await (0, import_sessionTernSecure.verifyTernSessionCookie)(sessionCookie);
34
- if (sessionResult.valid) {
35
- return {
36
- userId: sessionResult.uid,
37
- token: sessionCookie,
38
- error: null
39
- };
40
- }
41
- }
42
- const idToken = (_b = cookieStore.get("_session_token")) == null ? void 0 : _b.value;
43
- if (idToken) {
44
- const tokenResult = await (0, import_sessionTernSecure.verifyTernIdToken)(idToken);
45
- if (tokenResult.valid) {
46
- return {
47
- userId: (_c = tokenResult.uid) != null ? _c : null,
48
- token: idToken,
49
- error: null
50
- };
51
- }
33
+ const userId = headersList.get("x-user-id");
34
+ const authTime = headersList.get("x-auth-time");
35
+ const emailVerified = headersList.get("x-auth-verified") === "true";
36
+ if (userId) {
37
+ const token = ((_a = cookieStore.get("_session_cookie")) == null ? void 0 : _a.value) || ((_b = cookieStore.get("_session_token")) == null ? void 0 : _b.value) || null;
38
+ return {
39
+ user: {
40
+ uid: userId,
41
+ email: headersList.get("x-user-email") || null,
42
+ emailVerified,
43
+ authTime: authTime ? parseInt(authTime) : void 0
44
+ },
45
+ token,
46
+ error: null
47
+ };
52
48
  }
53
49
  return {
54
- userId: null,
50
+ user: null,
55
51
  token: null,
56
52
  error: new Error("No valid session or token found")
57
53
  };
58
54
  } catch (error) {
59
- console.error("Error in auth function:", error);
55
+ console.error("Error in getAuthResult:", error);
60
56
  return {
61
- userId: null,
57
+ user: null,
62
58
  token: null,
63
59
  error: error instanceof Error ? error : new Error("An unknown error occurred")
64
60
  };
65
61
  }
66
62
  }
63
+ async function isAuthenticated() {
64
+ const authResult = await auth();
65
+ return authResult.user !== null;
66
+ }
67
+ async function getUserInfo() {
68
+ const authResult = await auth();
69
+ if (!authResult.user) {
70
+ return null;
71
+ }
72
+ return {
73
+ uid: authResult.user.uid,
74
+ email: authResult.user.email,
75
+ emailVerified: authResult.user.emailVerified,
76
+ authTime: authResult.user.authTime
77
+ };
78
+ }
67
79
  // Annotate the CommonJS export names for ESM import in node:
68
80
  0 && (module.exports = {
69
- auth
81
+ auth,
82
+ getUserInfo,
83
+ isAuthenticated
70
84
  });
71
85
  //# sourceMappingURL=auth.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/app-router/server/auth.ts"],"sourcesContent":["'use server'\n\nimport { cookies } from 'next/headers';\nimport { verifyTernIdToken, verifyTernSessionCookie } from './sessionTernSecure';\n\nexport interface AuthResult {\n userId: string | null;\n token: string | null;\n error: Error | null;\n}\n\nexport async function auth(): Promise<AuthResult> {\n try {\n const cookieStore = await cookies();\n const sessionCookie = cookieStore.get('_session_cookie')?.value;\n if (sessionCookie) {\n const sessionResult = await verifyTernSessionCookie(sessionCookie);\n if (sessionResult.valid) {\n return {\n userId: sessionResult.uid,\n token: sessionCookie,\n error: null\n };\n }\n }\n\n // If session cookie is not present or invalid, try the ID token\n const idToken = cookieStore.get('_session_token')?.value;\n if (idToken) {\n const tokenResult = await verifyTernIdToken(idToken);\n if (tokenResult.valid) {\n return {\n userId: tokenResult.uid ?? null,\n token: idToken,\n error: null\n };\n }\n }\n\n /// If both checks fail, return null values\n return {\n userId: null,\n token: null,\n error: new Error('No valid session or token found')\n };\n } catch (error) {\n console.error('Error in auth function:', error);\n return {\n userId: null,\n token: null,\n error: error instanceof Error ? error : new Error('An unknown error occurred')\n };\n }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,qBAAwB;AACxB,+BAA4D;AAQ5D,eAAsB,OAA4B;AAXlD;AAYE,MAAI;AACF,UAAM,cAAc,UAAM,wBAAQ;AAClC,UAAM,iBAAgB,iBAAY,IAAI,iBAAiB,MAAjC,mBAAoC;AAC1D,QAAI,eAAe;AACjB,YAAM,gBAAgB,UAAM,kDAAwB,aAAa;AACjE,UAAI,cAAc,OAAO;AACvB,eAAO;AAAA,UACL,QAAQ,cAAc;AAAA,UACtB,OAAO;AAAA,UACP,OAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAGA,UAAM,WAAU,iBAAY,IAAI,gBAAgB,MAAhC,mBAAmC;AACnD,QAAI,SAAS;AACX,YAAM,cAAc,UAAM,4CAAkB,OAAO;AACnD,UAAI,YAAY,OAAO;AACrB,eAAO;AAAA,UACL,SAAQ,iBAAY,QAAZ,YAAmB;AAAA,UAC3B,OAAO;AAAA,UACP,OAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAGA,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,OAAO,IAAI,MAAM,iCAAiC;AAAA,IACpD;AAAA,EACF,SAAS,OAAO;AACd,YAAQ,MAAM,2BAA2B,KAAK;AAC9C,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,2BAA2B;AAAA,IAC/E;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../../src/app-router/server/auth.ts"],"sourcesContent":["'use server'\nimport { cookies, headers } from \"next/headers\"\nimport type { UserInfo, SessionResult } from \"./edge-session\"\n\n\nexport interface AuthResult {\n user: UserInfo | null\n token: string | null\n error: Error | null\n}\n\n\n /**\n * Get the current authenticated user from the session or token\n */\n export async function auth(): Promise<AuthResult> {\n try {\n const headersList = await headers()\n const cookieStore = await cookies()\n\n const userId = headersList.get('x-user-id')\n const authTime = headersList.get('x-auth-time')\n const emailVerified = headersList.get('x-auth-verified') === 'true'\n\n if (userId) {\n const token = cookieStore.get(\"_session_cookie\")?.value || \n cookieStore.get(\"_session_token\")?.value || \n null\n \n return {\n user: {\n uid: userId,\n email: headersList.get('x-user-email') || null,\n emailVerified,\n authTime: authTime ? parseInt(authTime) : undefined\n },\n token,\n error: null\n }\n }\n\n return {\n user: null,\n token: null,\n error: new Error(\"No valid session or token found\"),\n }\n } catch (error) {\n console.error(\"Error in getAuthResult:\", error)\n return {\n user: null,\n token: null,\n error: error instanceof Error ? error : new Error(\"An unknown error occurred\"),\n }\n }\n}\n\n/**\n * Type guard to check if user is authenticated\n */\nexport async function isAuthenticated(): Promise<boolean> {\n const authResult = await auth()\n return authResult.user !== null\n}\n\n/**\n * Get user info from auth result\n */\nexport async function getUserInfo(): Promise<UserInfo | null> {\n const authResult = await auth()\n if (!authResult.user) {\n return null\n }\n\n return {\n uid: authResult.user.uid,\n email: authResult.user.email,\n emailVerified: authResult.user.emailVerified,\n authTime: authResult.user.authTime\n }\n }\n\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,qBAAiC;AAc/B,eAAsB,OAA4B;AAfpD;AAgBI,MAAI;AACF,UAAM,cAAc,UAAM,wBAAQ;AAClC,UAAM,cAAc,UAAM,wBAAQ;AAElC,UAAM,SAAS,YAAY,IAAI,WAAW;AAC1C,UAAM,WAAW,YAAY,IAAI,aAAa;AAC9C,UAAM,gBAAgB,YAAY,IAAI,iBAAiB,MAAM;AAE7D,QAAI,QAAQ;AACV,YAAM,UAAQ,iBAAY,IAAI,iBAAiB,MAAjC,mBAAoC,YACrC,iBAAY,IAAI,gBAAgB,MAAhC,mBAAmC,UACnC;AAEb,aAAO;AAAA,QACL,MAAM;AAAA,UACJ,KAAK;AAAA,UACL,OAAO,YAAY,IAAI,cAAc,KAAK;AAAA,UAC1C;AAAA,UACA,UAAU,WAAW,SAAS,QAAQ,IAAI;AAAA,QAC5C;AAAA,QACA;AAAA,QACA,OAAO;AAAA,MACT;AAAA,IACF;AAEA,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,OAAO,IAAI,MAAM,iCAAiC;AAAA,IACpD;AAAA,EACF,SAAS,OAAO;AACd,YAAQ,MAAM,2BAA2B,KAAK;AAC9C,WAAO;AAAA,MACL,MAAM;AAAA,MACN,OAAO;AAAA,MACP,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,2BAA2B;AAAA,IAC/E;AAAA,EACF;AACJ;AAKA,eAAsB,kBAAoC;AACxD,QAAM,aAAa,MAAM,KAAK;AAC9B,SAAO,WAAW,SAAS;AAC7B;AAKA,eAAsB,cAAwC;AAC5D,QAAM,aAAa,MAAM,KAAK;AAC9B,MAAI,CAAC,WAAW,MAAM;AACpB,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,KAAK,WAAW,KAAK;AAAA,IACrB,OAAO,WAAW,KAAK;AAAA,IACvB,eAAe,WAAW,KAAK;AAAA,IAC/B,UAAU,WAAW,KAAK;AAAA,EAC5B;AACA;","names":[]}
@@ -0,0 +1,80 @@
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 edge_session_exports = {};
20
+ __export(edge_session_exports, {
21
+ verifySession: () => verifySession
22
+ });
23
+ module.exports = __toCommonJS(edge_session_exports);
24
+ var import_headers = require("next/headers");
25
+ var import_jwt = require("./jwt");
26
+ async function verifySession(request) {
27
+ var _a, _b, _c, _d, _e, _f;
28
+ try {
29
+ const cookieStore = await (0, import_headers.cookies)();
30
+ const sessionCookie = (_a = cookieStore.get("_session_cookie")) == null ? void 0 : _a.value;
31
+ if (sessionCookie) {
32
+ const result = await (0, import_jwt.verifyFirebaseToken)(sessionCookie, true);
33
+ if (result.valid) {
34
+ return {
35
+ isAuthenticated: true,
36
+ user: {
37
+ uid: (_b = result.uid) != null ? _b : "",
38
+ email: result.email || null,
39
+ emailVerified: (_c = result.emailVerified) != null ? _c : false,
40
+ disabled: false
41
+ }
42
+ };
43
+ }
44
+ console.log("Session cookie verification failed:", result.error);
45
+ }
46
+ const idToken = (_d = cookieStore.get("_session_token")) == null ? void 0 : _d.value;
47
+ if (idToken) {
48
+ const result = await (0, import_jwt.verifyFirebaseToken)(idToken, false);
49
+ if (result.valid) {
50
+ return {
51
+ isAuthenticated: true,
52
+ user: {
53
+ uid: (_e = result.uid) != null ? _e : "",
54
+ email: result.email || null,
55
+ emailVerified: (_f = result.emailVerified) != null ? _f : false,
56
+ disabled: false
57
+ }
58
+ };
59
+ }
60
+ console.log("ID token verification failed:", result.error);
61
+ }
62
+ return {
63
+ isAuthenticated: false,
64
+ user: null,
65
+ error: "No valid session found"
66
+ };
67
+ } catch (error) {
68
+ console.error("Session verification error:", error);
69
+ return {
70
+ isAuthenticated: false,
71
+ user: null,
72
+ error: error instanceof Error ? error.message : "Session verification failed"
73
+ };
74
+ }
75
+ }
76
+ // Annotate the CommonJS export names for ESM import in node:
77
+ 0 && (module.exports = {
78
+ verifySession
79
+ });
80
+ //# sourceMappingURL=edge-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/app-router/server/edge-session.ts"],"sourcesContent":["import { cookies } from \"next/headers\"\nimport { verifyFirebaseToken } from \"./jwt\"\nimport type { NextRequest } from \"next/server\"\n\nexport interface UserInfo {\n uid: string\n email: string | null\n emailVerified?: boolean\n authTime?: number\n disabled?: boolean\n}\n\n\nexport interface SessionResult {\n isAuthenticated: boolean\n user: UserInfo | null\n error?: string\n}\n\nexport async function verifySession(request: NextRequest): Promise<SessionResult> {\n try {\n const cookieStore = await cookies()\n\n // First try session cookie\n const sessionCookie = cookieStore.get(\"_session_cookie\")?.value\n if (sessionCookie) {\n const result = await verifyFirebaseToken(sessionCookie, true)\n if (result.valid) {\n return {\n isAuthenticated: true,\n user: {\n uid: result.uid ?? '',\n email: result.email || null,\n emailVerified: result.emailVerified ?? false,\n disabled: false,\n },\n }\n }\n console.log(\"Session cookie verification failed:\", result.error)\n }\n\n // Then try ID token\n const idToken = cookieStore.get(\"_session_token\")?.value\n if (idToken) {\n const result = await verifyFirebaseToken(idToken, false)\n if (result.valid) {\n return {\n isAuthenticated: true,\n user: {\n uid: result.uid ?? '',\n email: result.email || null,\n emailVerified: result.emailVerified ?? false,\n disabled: false,\n },\n }\n }\n console.log(\"ID token verification failed:\", result.error)\n }\n\n return {\n isAuthenticated: false,\n user: null,\n error: \"No valid session found\",\n }\n } catch (error) {\n console.error(\"Session verification error:\", error)\n return {\n isAuthenticated: false,\n user: null,\n error: error instanceof Error ? error.message : \"Session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AAAA,EACF;AACF;","names":[]}
@@ -21,7 +21,9 @@ __export(server_exports, {
21
21
  adminTernSecureAuth: () => import_admin_init.adminTernSecureAuth,
22
22
  adminTernSecureDb: () => import_admin_init.adminTernSecureDb,
23
23
  auth: () => import_auth.auth,
24
+ createRouteMatcher: () => import_ternSecureMiddleware.createRouteMatcher,
24
25
  createSessionCookie: () => import_sessionTernSecure.createSessionCookie,
26
+ getUserInfo: () => import_auth.getUserInfo,
25
27
  ternSecureMiddleware: () => import_ternSecureMiddleware.ternSecureMiddleware,
26
28
  verifyTernSessionCookie: () => import_sessionTernSecure.verifyTernSessionCookie
27
29
  });
@@ -35,7 +37,9 @@ var import_auth = require("./auth");
35
37
  adminTernSecureAuth,
36
38
  adminTernSecureDb,
37
39
  auth,
40
+ createRouteMatcher,
38
41
  createSessionCookie,
42
+ getUserInfo,
39
43
  ternSecureMiddleware,
40
44
  verifyTernSessionCookie
41
45
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/app-router/server/index.ts"],"sourcesContent":["export { adminTernSecureAuth, adminTernSecureDb } from '../../utils/admin-init'\nexport { ternSecureMiddleware } from './ternSecureMiddleware'\nexport { verifyTernSessionCookie, createSessionCookie } from './sessionTernSecure'\nexport { auth } from './auth'"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAuD;AACvD,kCAAqC;AACrC,+BAA6D;AAC7D,kBAAqB;","names":[]}
1
+ {"version":3,"sources":["../../../../src/app-router/server/index.ts"],"sourcesContent":["export { adminTernSecureAuth, adminTernSecureDb } from '../../utils/admin-init'\nexport { ternSecureMiddleware, createRouteMatcher } from './ternSecureMiddleware'\nexport { verifyTernSessionCookie, createSessionCookie } from './sessionTernSecure'\nexport { auth, getUserInfo } from './auth'\nexport type { AuthResult } from './auth'"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAuD;AACvD,kCAAyD;AACzD,+BAA6D;AAC7D,kBAAkC;","names":[]}
@@ -0,0 +1,141 @@
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 jwt_exports = {};
20
+ __export(jwt_exports, {
21
+ verifyFirebaseToken: () => verifyFirebaseToken
22
+ });
23
+ module.exports = __toCommonJS(jwt_exports);
24
+ var import_jose = require("jose");
25
+ var import_react = require("react");
26
+ const FIREBASE_ID_TOKEN_URL = "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com";
27
+ const FIREBASE_SESSION_CERT_URL = "https://identitytoolkit.googleapis.com/v1/sessionCookiePublicKeys";
28
+ const getIdTokenJWKS = (0, import_react.cache)(() => {
29
+ return (0, import_jose.createRemoteJWKSet)(new URL(FIREBASE_ID_TOKEN_URL), {
30
+ cacheMaxAge: 36e5,
31
+ // 1 hour
32
+ timeoutDuration: 5e3,
33
+ // 5 seconds
34
+ cooldownDuration: 3e4
35
+ // 30 seconds between retries
36
+ });
37
+ });
38
+ const getSessionJWKS = (0, import_react.cache)(() => {
39
+ return (0, import_jose.createRemoteJWKSet)(new URL(FIREBASE_SESSION_CERT_URL), {
40
+ cacheMaxAge: 36e5,
41
+ // 1 hour
42
+ timeoutDuration: 5e3,
43
+ // 5 seconds
44
+ cooldownDuration: 3e4
45
+ // 30 seconds between retries
46
+ });
47
+ });
48
+ function decodeJwt(token) {
49
+ try {
50
+ const [headerB64, payloadB64] = token.split(".");
51
+ const header = JSON.parse(Buffer.from(headerB64, "base64").toString());
52
+ const payload = JSON.parse(Buffer.from(payloadB64, "base64").toString());
53
+ return { header, payload };
54
+ } catch (error) {
55
+ console.error("Error decoding JWT:", error);
56
+ return null;
57
+ }
58
+ }
59
+ async function verifyFirebaseToken(token, isSessionCookie = false) {
60
+ try {
61
+ const projectId = process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID;
62
+ if (!projectId) {
63
+ throw new Error("Firebase Project ID is not configured");
64
+ }
65
+ const decoded = decodeJwt(token);
66
+ if (!decoded) {
67
+ throw new Error("Invalid token format");
68
+ }
69
+ console.log("Token details:", {
70
+ header: decoded.header,
71
+ type: isSessionCookie ? "session_cookie" : "id_token"
72
+ });
73
+ let retries = 3;
74
+ let lastError = null;
75
+ while (retries > 0) {
76
+ try {
77
+ const JWKS = isSessionCookie ? await getSessionJWKS() : await getIdTokenJWKS();
78
+ const { payload } = await (0, import_jose.jwtVerify)(token, JWKS, {
79
+ issuer: isSessionCookie ? "https://session.firebase.google.com/" + projectId : "https://securetoken.google.com/" + projectId,
80
+ audience: projectId,
81
+ algorithms: ["RS256"]
82
+ });
83
+ const firebasePayload = payload;
84
+ const now = Math.floor(Date.now() / 1e3);
85
+ if (firebasePayload.exp <= now) {
86
+ throw new Error("Token has expired");
87
+ }
88
+ if (firebasePayload.iat > now) {
89
+ throw new Error("Token issued time is in the future");
90
+ }
91
+ if (!firebasePayload.sub) {
92
+ throw new Error("Token subject is empty");
93
+ }
94
+ if (firebasePayload.auth_time > now) {
95
+ throw new Error("Token auth time is in the future");
96
+ }
97
+ return {
98
+ valid: true,
99
+ uid: firebasePayload.sub,
100
+ email: firebasePayload.email,
101
+ emailVerified: firebasePayload.email_verified,
102
+ authTime: firebasePayload.auth_time,
103
+ issuedAt: firebasePayload.iat,
104
+ expiresAt: firebasePayload.exp
105
+ };
106
+ } catch (error) {
107
+ lastError = error;
108
+ if (error instanceof Error && error.name === "JWKSNoMatchingKey") {
109
+ console.warn(`JWKS retry attempt ${4 - retries}:`, error.message);
110
+ retries--;
111
+ if (retries > 0) {
112
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
113
+ continue;
114
+ }
115
+ }
116
+ throw error;
117
+ }
118
+ }
119
+ throw lastError || new Error("Failed to verify token after retries");
120
+ } catch (error) {
121
+ console.error("Token verification details:", {
122
+ error: error instanceof Error ? {
123
+ name: error.name,
124
+ message: error.message,
125
+ stack: error.stack
126
+ } : error,
127
+ decoded: decodeJwt(token),
128
+ //projectId,
129
+ isSessionCookie
130
+ });
131
+ return {
132
+ valid: false,
133
+ error: error instanceof Error ? error.message : "Invalid token"
134
+ };
135
+ }
136
+ }
137
+ // Annotate the CommonJS export names for ESM import in node:
138
+ 0 && (module.exports = {
139
+ verifyFirebaseToken
140
+ });
141
+ //# sourceMappingURL=jwt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/app-router/server/jwt.ts"],"sourcesContent":["import { jwtVerify, createRemoteJWKSet } from \"jose\"\nimport { cache } from \"react\"\n\ninterface FirebaseIdTokenPayload {\n iss: string\n aud: string\n auth_time: number\n user_id: string\n sub: string\n iat: number\n exp: number\n email?: string\n email_verified?: boolean\n firebase: {\n identities: {\n [key: string]: any\n }\n sign_in_provider: string\n }\n}\n\n// Firebase public key endpoints\nconst FIREBASE_ID_TOKEN_URL = \"https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com\"\nconst FIREBASE_SESSION_CERT_URL = \"https://identitytoolkit.googleapis.com/v1/sessionCookiePublicKeys\"\n\n// Cache the JWKS using React cache\nconst getIdTokenJWKS = cache(() => {\n return createRemoteJWKSet(new URL(FIREBASE_ID_TOKEN_URL), {\n cacheMaxAge: 3600000, // 1 hour\n timeoutDuration: 5000, // 5 seconds\n cooldownDuration: 30000, // 30 seconds between retries\n })\n})\n\nconst getSessionJWKS = cache(() => {\n return createRemoteJWKSet(new URL(FIREBASE_SESSION_CERT_URL), {\n cacheMaxAge: 3600000, // 1 hour\n timeoutDuration: 5000, // 5 seconds\n cooldownDuration: 30000, // 30 seconds between retries\n })\n})\n\n// Helper to decode JWT without verification\nfunction decodeJwt(token: string) {\n try {\n const [headerB64, payloadB64] = token.split(\".\")\n const header = JSON.parse(Buffer.from(headerB64, \"base64\").toString())\n const payload = JSON.parse(Buffer.from(payloadB64, \"base64\").toString())\n return { header, payload }\n } catch (error) {\n console.error(\"Error decoding JWT:\", error)\n return null\n }\n}\n\nexport async function verifyFirebaseToken(token: string, isSessionCookie = false) {\n try {\n const projectId = process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID\n if (!projectId) {\n throw new Error(\"Firebase Project ID is not configured\")\n }\n\n // Decode token for debugging and type checking\n const decoded = decodeJwt(token)\n if (!decoded) {\n throw new Error(\"Invalid token format\")\n }\n\n console.log(\"Token details:\", {\n header: decoded.header,\n type: isSessionCookie ? \"session_cookie\" : \"id_token\",\n })\n\n let retries = 3\n let lastError: Error | null = null\n\n while (retries > 0) {\n try {\n // Use different JWKS based on token type\n const JWKS = isSessionCookie ? await getSessionJWKS() : await getIdTokenJWKS()\n\n const { payload } = await jwtVerify(token, JWKS, {\n issuer: isSessionCookie\n ? \"https://session.firebase.google.com/\" + projectId\n : \"https://securetoken.google.com/\" + projectId,\n audience: projectId,\n algorithms: [\"RS256\"],\n })\n\n const firebasePayload = payload as unknown as FirebaseIdTokenPayload\n const now = Math.floor(Date.now() / 1000)\n\n // Verify token claims\n if (firebasePayload.exp <= now) {\n throw new Error(\"Token has expired\")\n }\n\n if (firebasePayload.iat > now) {\n throw new Error(\"Token issued time is in the future\")\n }\n\n if (!firebasePayload.sub) {\n throw new Error(\"Token subject is empty\")\n }\n\n if (firebasePayload.auth_time > now) {\n throw new Error(\"Token auth time is in the future\")\n }\n\n return {\n valid: true,\n uid: firebasePayload.sub,\n email: firebasePayload.email,\n emailVerified: firebasePayload.email_verified,\n authTime: firebasePayload.auth_time,\n issuedAt: firebasePayload.iat,\n expiresAt: firebasePayload.exp,\n }\n } catch (error) {\n lastError = error as Error\n if (error instanceof Error && error.name === \"JWKSNoMatchingKey\") {\n console.warn(`JWKS retry attempt ${4 - retries}:`, error.message)\n retries--\n if (retries > 0) {\n await new Promise((resolve) => setTimeout(resolve, 1000))\n continue\n }\n }\n throw error\n }\n }\n\n throw lastError || new Error(\"Failed to verify token after retries\")\n } catch (error) {\n console.error(\"Token verification details:\", {\n error:\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : error,\n decoded: decodeJwt(token),\n //projectId,\n isSessionCookie,\n })\n\n return {\n valid: false,\n error: error instanceof Error ? error.message : \"Invalid token\",\n }\n }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAA8C;AAC9C,mBAAsB;AAqBtB,MAAM,wBAAwB;AAC9B,MAAM,4BAA4B;AAGlC,MAAM,qBAAiB,oBAAM,MAAM;AACjC,aAAO,gCAAmB,IAAI,IAAI,qBAAqB,GAAG;AAAA,IACxD,aAAa;AAAA;AAAA,IACb,iBAAiB;AAAA;AAAA,IACjB,kBAAkB;AAAA;AAAA,EACpB,CAAC;AACH,CAAC;AAED,MAAM,qBAAiB,oBAAM,MAAM;AACjC,aAAO,gCAAmB,IAAI,IAAI,yBAAyB,GAAG;AAAA,IAC5D,aAAa;AAAA;AAAA,IACb,iBAAiB;AAAA;AAAA,IACjB,kBAAkB;AAAA;AAAA,EACpB,CAAC;AACH,CAAC;AAGD,SAAS,UAAU,OAAe;AAChC,MAAI;AACF,UAAM,CAAC,WAAW,UAAU,IAAI,MAAM,MAAM,GAAG;AAC/C,UAAM,SAAS,KAAK,MAAM,OAAO,KAAK,WA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ACnC,gBAAM,IAAI,MAAM,kCAAkC;AAAA,QACpD;AAEA,eAAO;AAAA,UACL,OAAO;AAAA,UACP,KAAK,gBAAgB;AAAA,UACrB,OAAO,gBAAgB;AAAA,UACvB,eAAe,gBAAgB;AAAA,UAC/B,UAAU,gBAAgB;AAAA,UAC1B,UAAU,gBAAgB;AAAA,UAC1B,WAAW,gBAAgB;AAAA,QAC7B;AAAA,MACF,SAAS,OAAO;AACd,oBAAY;AACZ,YAAI,iBAAiB,SAAS,MAAM,SAAS,qBAAqB;AAChE,kBAAQ,KAAK,sBAAsB,IAAI,OAAO,KAAK,MAAM,OAAO;AAChE;AACA,cAAI,UAAU,GAAG;AACf,kBAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,GAAI,CAAC;AACxD;AAAA,UACF;AAAA,QACF;AACA,cAAM;AAAA,MACR;AAAA,IACF;AAEA,UAAM,aAAa,IAAI,MAAM,sCAAsC;AAAA,EACrE,SAAS,OAAO;AACd,YAAQ,MAAM,+BAA+B;AAAA,MAC3C,OACE,iBAAiB,QACb;AAAA,QACE,MAAM,MAAM;AAAA,QACZ,SAAS,MAAM;AAAA,QACf,OAAO,MAAM;AAAA,MACf,IACA;AAAA,MACN,SAAS,UAAU,KAAK;AAAA;AAAA,MAExB;AAAA,IACF,CAAC;AAED,WAAO;AAAA,MACL,OAAO;AAAA,MACP,OAAO,iBAAiB,QAAQ,MAAM,UAAU;AAAA,IAClD;AAAA,EACF;AACF;","names":[]}
@@ -83,15 +83,20 @@ async function getIdToken() {
83
83
  }
84
84
  }
85
85
  async function setServerSession(token) {
86
- const cookieStore = await (0, import_headers.cookies)();
87
- cookieStore.set("_session", token, {
88
- httpOnly: true,
89
- secure: process.env.NODE_ENV === "production",
90
- sameSite: "strict",
91
- maxAge: 60 * 60,
92
- // 1 hour
93
- path: "/"
94
- });
86
+ try {
87
+ const cookieStore = await (0, import_headers.cookies)();
88
+ cookieStore.set("_session_token", token, {
89
+ httpOnly: true,
90
+ secure: process.env.NODE_ENV === "production",
91
+ sameSite: "strict",
92
+ maxAge: 60 * 60,
93
+ // 1 hour
94
+ path: "/"
95
+ });
96
+ return { success: true, message: "Session created" };
97
+ } catch {
98
+ return { success: false, message: "Failed to create session" };
99
+ }
95
100
  }
96
101
  async function verifyTernIdToken(token) {
97
102
  try {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/app-router/server/sessionTernSecure.ts"],"sourcesContent":["'use server'\n\nimport { cookies } from 'next/headers';\nimport { adminTernSecureAuth as adminAuth } from '../../utils/admin-init';\n\ninterface FirebaseAuthError extends Error {\n code?: string;\n}\n\nexport interface User {\n uid: string | null;\n email: string | null;\n }\n\nexport interface Session {\n user: User | null;\n token: string | null;\n error: Error | null;\n}\n\nexport async function createSessionCookie(idToken: string) {\n try {\n const expiresIn = 60 * 60 * 24 * 5 * 1000;\n const sessionCookie = await adminAuth.createSessionCookie(idToken, { expiresIn });\n\n const cookieStore = await cookies();\n cookieStore.set('_session_cookie', sessionCookie, {\n maxAge: expiresIn,\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n path: '/',\n });\n return { success: true, message: 'Session created' };\n } catch (error) {\n return { success: false, message: 'Failed to create session' };\n }\n}\n\n\n\nexport async function getServerSessionCookie() {\n const cookieStore = await cookies();\n const sessionCookie = cookieStore.get('_session_cookie')?.value;\n\n if (!sessionCookie) {\n throw new Error('No session cookie found')\n }\n \n try {\n const decondeClaims = await adminAuth.verifySessionCookie(sessionCookie, true)\n return {\n token: sessionCookie,\n userId: decondeClaims.uid\n }\n } catch (error) {\n console.error('Error verifying session:', error)\n throw new Error('Invalid Session')\n }\n}\n\n\nexport async function getIdToken() {\n const cookieStore = await cookies();\n const token = cookieStore.get('_session_token')?.value;\n\n if (!token) {\n throw new Error('No session cookie found')\n }\n \n try {\n const decodedClaims = await adminAuth.verifyIdToken(token)\n return {\n token: token,\n userId: decodedClaims.uid\n }\n } catch (error) {\n console.error('Error verifying session:', error)\n throw new Error('Invalid Session')\n }\n}\n\nexport async function setServerSession(token: string) {\n const cookieStore = await cookies();\n cookieStore.set('_session', token, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: 60 * 60, // 1 hour\n path: '/',\n });\n }\n\n export async function verifyTernIdToken(token: string): Promise<{ valid: boolean; uid?: string; error?: string }> {\n try {\n const decodedToken = await adminAuth.verifyIdToken(token, true);\n return { valid: true, uid: decodedToken.uid };\n } catch (error) {\n if (error instanceof Error) {\n const firebaseError = error as FirebaseAuthError;\n if (error.name === 'FirebaseAuthError') {\n // Handle specific Firebase Auth errors\n switch (firebaseError.code) {\n case 'auth/id-token-expired':\n return { valid: false, error: 'Token has expired' };\n case 'auth/id-token-revoked':\n return { valid: false, error: 'Token has been revoked' };\n case 'auth/user-disabled':\n return { valid: false, error: 'User account has been disabled' };\n default:\n return { valid: false, error: 'Invalid token' };\n }\n }\n }\n return { valid: false, error: 'Error verifying token' };\n }\n }\n \n\n export async function verifyTernSessionCookie(session: string): Promise<{ valid: boolean; uid?: any; error?: any }>{\n try {\n const res = await adminAuth.verifySessionCookie(session, true);\n if (res) {\n return { valid: true, uid: res.uid };\n } else {\n return { valid: false, error: 'Invalid session'};\n }\n } catch (error) {\n return {error: error, valid: false}\n }\n }\n\n\n export async function clearSessionCookie() {\n const cookieStore = await cookies()\n \n cookieStore.delete('_session_cookie')\n cookieStore.delete('_session_token')\n cookieStore.delete('_session')\n \n try {\n // Verify if there's an active session before revoking\n const sessionCookie = cookieStore.get('_session_cookie')?.value\n if (sessionCookie) {\n // Get the decoded claims to get the user's ID\n const decodedClaims = await adminAuth.verifySessionCookie(sessionCookie)\n \n // Revoke all sessions for the user\n await adminAuth.revokeRefreshTokens(decodedClaims.uid)\n }\n \n return { success: true, message: 'Session cleared successfully' }\n } catch (error) {\n console.error('Error clearing session:', error)\n // Still return success even if revoking fails, as cookies are cleared\n return { success: true, message: 'Session cookies cleared' }\n }\n }\n\n\n\n/*\n export async function GET(request: NextRequest) {\n const cookieStore = await cookies();\n const sessionCookie = cookieStore.get('session')?.value\n \n if (!sessionCookie) {\n return NextResponse.json({ isAuthenticated: false }, { status: 401 })\n }\n \n try {\n const decodedClaims = await adminAuth.verifySessionCookie(sessionCookie, true)\n return NextResponse.json({ isAuthenticated: true, user: decodedClaims }, { status: 200 })\n } catch (error) {\n console.error('Error verifying session cookie:', error)\n return NextResponse.json({ isAuthenticated: false }, { status: 401 })\n }\n }\n\n*/"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,qBAAwB;AACxB,wBAAiD;AAiBjD,eAAsB,oBAAoB,SAAiB;AACzD,MAAI;AACF,UAAM,YAAY,KAAK,KAAK,KAAK,IAAI;AACnC,UAAM,gBAAgB,MAAM,kBAAAA,oBAAU,oBAAoB,SAAS,EAAE,UAAU,CAAC;AAEhF,UAAM,cAAc,UAAM,wBAAQ;AAClC,gBAAY,IAAI,mBAAmB,eAAe;AAAA,MAC9C,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,QAAQ,QAAQ,IAAI,aAAa;AAAA,MACjC,MAAM;AAAA,IACV,CAAC;AACD,WAAO,EAAE,SAAS,MAAM,SAAS,kBAAkB;AAAA,EACvD,SAAS,OAAO;AACZ,WAAO,EAAE,SAAS,OAAO,SAAS,2BAA2B;AAAA,EACjE;AACF;AAIA,eAAsB,yBAAyB;AAxC/C;AAyCE,QAAM,cAAc,UAAM,wBAAQ;AAClC,QAAM,iBAAgB,iBAAY,IAAI,iBAAiB,MAAjC,mBAAoC;AAE1D,MAAI,CAAC,eAAe;AAClB,UAAM,IAAI,MAAM,yBAAyB;AAAA,EAC3C;AAEA,MAAI;AACF,UAAM,gBAAgB,MAAM,kBAAAA,oBAAU,oBAAoB,eAAe,IAAI;AAC7E,WAAO;AAAA,MACL,OAAO;AAAA,MACP,QAAQ,cAAc;AAAA,IACxB;AAAA,EACF,SAAS,OAAO;AACd,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OAAO,OAAO,gBAAgB;AAAA,QAClD;AAAA,MACF;AAAA,IACF;AACA,WAAO,EAAE,OAAO,OAAO,OAAO,wBAAwB;AAAA,EACxD;AACF;AAGA,eAAsB,wBAAwB,SAAqE;AACjH,MAAI;AACF,UAAM,MAAM,MAAM,kBAAAA,oBAAU,oBAAoB,SAAS,IAAI;AAC7D,QAAI,KAAK;AACP,aAAO,EAAE,OAAO,MAAM,KAAK,IAAI,IAAI;AAAA,IACrC,OAAO;AACL,aAAO,EAAE,OAAO,OAAO,OAAO,kBAAiB;AAAA,IACjD;AAAA,EACF,SAAS,OAAO;AACd,WAAO,EAAC,OAAc,OAAO,MAAK;AAAA,EACpC;AACF;AAGA,eAAsB,qBAAqB;AApI7C;AAqII,QAAM,cAAc,UAAM,wBAAQ;AAElC,cAAY,OAAO,iBAAiB;AACpC,cAAY,OAAO,gBAAgB;AACnC,cAAY,OAAO,UAAU;AAE7B,MAAI;AAEF,UAAM,iBAAgB,iBAAY,IAAI,iBAAiB,MAAjC,mBAAoC;AAC1D,QAAI,eAAe;AAEjB,YAAM,gBAAgB,MAAM,kBAAAA,oBAAU,oBAAoB,aAAa;AAGvE,YAAM,kBAAAA,oBAAU,oBAAoB,cAAc,GAAG;AAAA,IACvD;AAEA,WAAO,EAAE,SAAS,MAAM,SAAS,+BAA+B;AAAA,EAClE,SAAS,OAAO;AACd,YAAQ,MAAM,2BAA2B,KAAK;AAE9C,WAAO,EAAE,SAAS,MAAM,SAAS,0BAA0B;AAAA,EAC7D;AACF;","names":["adminAuth"]}
1
+ {"version":3,"sources":["../../../../src/app-router/server/sessionTernSecure.ts"],"sourcesContent":["'use server'\n\nimport { cookies } from 'next/headers';\nimport { adminTernSecureAuth as adminAuth } from '../../utils/admin-init';\n\ninterface FirebaseAuthError extends Error {\n code?: string;\n}\n\nexport interface User {\n uid: string | null;\n email: string | null;\n }\n\nexport interface Session {\n user: User | null;\n token: string | null;\n error: Error | null;\n}\n\nexport async function createSessionCookie(idToken: string) {\n try {\n const expiresIn = 60 * 60 * 24 * 5 * 1000;\n const sessionCookie = await adminAuth.createSessionCookie(idToken, { expiresIn });\n\n const cookieStore = await cookies();\n cookieStore.set('_session_cookie', sessionCookie, {\n maxAge: expiresIn,\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n path: '/',\n });\n return { success: true, message: 'Session created' };\n } catch (error) {\n return { success: false, message: 'Failed to create session' };\n }\n}\n\n\n\nexport async function getServerSessionCookie() {\n const cookieStore = await cookies();\n const sessionCookie = cookieStore.get('_session_cookie')?.value;\n\n if (!sessionCookie) {\n throw new Error('No session cookie found')\n }\n \n try {\n const decondeClaims = await adminAuth.verifySessionCookie(sessionCookie, true)\n return {\n token: sessionCookie,\n userId: decondeClaims.uid\n }\n } catch (error) {\n console.error('Error verifying session:', error)\n throw new Error('Invalid Session')\n }\n}\n\n\nexport async function getIdToken() {\n const cookieStore = await cookies();\n const token = cookieStore.get('_session_token')?.value;\n\n if (!token) {\n throw new Error('No session cookie found')\n }\n \n try {\n const decodedClaims = await adminAuth.verifyIdToken(token)\n return {\n token: token,\n userId: decodedClaims.uid\n }\n } catch (error) {\n console.error('Error verifying session:', error)\n throw new Error('Invalid Session')\n }\n}\n\nexport async function setServerSession(token: string) {\n try {\n const cookieStore = await cookies();\n cookieStore.set('_session_token', token, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: 60 * 60, // 1 hour\n path: '/',\n });\n return { success: true, message: 'Session created' };\n } catch {\n return { success: false, message: 'Failed to create session' };\n }\n}\n\n export async function verifyTernIdToken(token: string): Promise<{ valid: boolean; uid?: string; error?: string }> {\n try {\n const decodedToken = await adminAuth.verifyIdToken(token, true);\n return { valid: true, uid: decodedToken.uid };\n } catch (error) {\n if (error instanceof Error) {\n const firebaseError = error as FirebaseAuthError;\n if (error.name === 'FirebaseAuthError') {\n // Handle specific Firebase Auth errors\n switch (firebaseError.code) {\n case 'auth/id-token-expired':\n return { valid: false, error: 'Token has expired' };\n case 'auth/id-token-revoked':\n return { valid: false, error: 'Token has been revoked' };\n case 'auth/user-disabled':\n return { valid: false, error: 'User account has been disabled' };\n default:\n return { valid: false, error: 'Invalid token' };\n }\n }\n }\n return { valid: false, error: 'Error verifying token' };\n }\n }\n \n\n export async function verifyTernSessionCookie(session: string): Promise<{ valid: boolean; uid?: any; error?: any }>{\n try {\n const res = await adminAuth.verifySessionCookie(session, true);\n if (res) {\n return { valid: true, uid: res.uid };\n } else {\n return { valid: false, error: 'Invalid session'};\n }\n } catch (error) {\n return {error: error, valid: false}\n }\n }\n\n\n export async function clearSessionCookie() {\n const cookieStore = await cookies()\n \n cookieStore.delete('_session_cookie')\n cookieStore.delete('_session_token')\n cookieStore.delete('_session')\n \n try {\n // Verify if there's an active session before revoking\n const sessionCookie = cookieStore.get('_session_cookie')?.value\n if (sessionCookie) {\n // Get the decoded claims to get the user's ID\n const decodedClaims = await adminAuth.verifySessionCookie(sessionCookie)\n \n // Revoke all sessions for the user\n await adminAuth.revokeRefreshTokens(decodedClaims.uid)\n }\n \n return { success: true, message: 'Session cleared successfully' }\n } catch (error) {\n console.error('Error clearing session:', error)\n // Still return success even if revoking fails, as cookies are cleared\n return { success: true, message: 'Session cookies cleared' }\n }\n }\n\n\n\n/*\n export async function GET(request: NextRequest) {\n const cookieStore = await cookies();\n const sessionCookie = cookieStore.get('session')?.value\n \n if (!sessionCookie) {\n return NextResponse.json({ isAuthenticated: false }, { status: 401 })\n }\n \n try {\n const decodedClaims = await adminAuth.verifySessionCookie(sessionCookie, true)\n return NextResponse.json({ isAuthenticated: true, user: decodedClaims }, { status: 200 })\n } catch (error) {\n console.error('Error verifying session cookie:', error)\n return NextResponse.json({ isAuthenticated: false }, { status: 401 })\n }\n }\n\n*/"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,qBAAwB;AACxB,wBAAiD;AAiBjD,eAAsB,o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,OAAO;AACL,aAAO,EAAE,OAAO,OAAO,OAAO,kBAAiB;AAAA,IACjD;AAAA,EACF,SAAS,OAAO;AACd,WAAO,EAAC,OAAc,OAAO,MAAK;AAAA,EACpC;AACF;AAGA,eAAsB,qBAAqB;AAzI7C;AA0II,QAAM,cAAc,UAAM,wBAAQ;AAElC,cAAY,OAAO,iBAAiB;AACpC,cAAY,OAAO,gBAAgB;AACnC,cAAY,OAAO,UAAU;AAE7B,MAAI;AAEF,UAAM,iBAAgB,iBAAY,IAAI,iBAAiB,MAAjC,mBAAoC;AAC1D,QAAI,eAAe;AAEjB,YAAM,gBAAgB,MAAM,kBAAAA,oBAAU,oBAAoB,aAAa;AAGvE,YAAM,kBAAAA,oBAAU,oBAAoB,cAAc,GAAG;AAAA,IACvD;AAEA,WAAO,EAAE,SAAS,MAAM,SAAS,+BAA+B;AAAA,EAClE,SAAS,OAAO;AACd,YAAQ,MAAM,2BAA2B,KAAK;AAE9C,WAAO,EAAE,SAAS,MAAM,SAAS,0BAA0B;AAAA,EAC7D;AACF;","names":["adminAuth"]}
@@ -18,33 +18,154 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var ternSecureMiddleware_exports = {};
20
20
  __export(ternSecureMiddleware_exports, {
21
+ createRouteMatcher: () => createRouteMatcher,
22
+ runtime: () => runtime,
21
23
  ternSecureMiddleware: () => ternSecureMiddleware
22
24
  });
23
25
  module.exports = __toCommonJS(ternSecureMiddleware_exports);
24
26
  var import_server = require("next/server");
25
- var import_auth = require("./auth");
26
- function ternSecureMiddleware(options = {}) {
27
- const { publicPaths = [], redirectTo = "/login" } = options;
28
- return async function middleware(request) {
27
+ var import_headers = require("next/headers");
28
+ var import_edge_session = require("./edge-session");
29
+ var import_jwt = require("./jwt");
30
+ const runtime = "edge";
31
+ function createRouteMatcher(patterns) {
32
+ return (request) => {
33
+ const { pathname } = request.nextUrl;
34
+ return patterns.some((pattern) => {
35
+ const regexPattern = new RegExp(
36
+ `^${pattern.replace(/\*/g, ".*").replace(/\((.*)\)/, "(?:$1)?")}$`
37
+ );
38
+ return regexPattern.test(pathname);
39
+ });
40
+ };
41
+ }
42
+ async function edgeAuth(request) {
43
+ var _a, _b, _c, _d, _e, _f;
44
+ const cookieStore = await (0, import_headers.cookies)();
45
+ async function protect() {
29
46
  const { pathname } = request.nextUrl;
30
- if (publicPaths.includes(pathname)) {
31
- return import_server.NextResponse.next();
47
+ throw new Error("Unauthorized access");
48
+ }
49
+ try {
50
+ const sessionCookie = (_a = cookieStore.get("_session_cookie")) == null ? void 0 : _a.value;
51
+ if (sessionCookie) {
52
+ const userInfo = await (0, import_jwt.verifyFirebaseToken)(sessionCookie, true);
53
+ console.log("userInfo", userInfo);
54
+ if (userInfo.valid) {
55
+ return {
56
+ user: {
57
+ uid: (_b = userInfo.uid) != null ? _b : "",
58
+ email: (_c = userInfo.email) != null ? _c : null
59
+ },
60
+ token: sessionCookie,
61
+ protect: async () => {
62
+ }
63
+ };
64
+ }
65
+ }
66
+ const idToken = (_d = cookieStore.get("_session_token")) == null ? void 0 : _d.value;
67
+ if (idToken) {
68
+ const userInfo = await (0, import_jwt.verifyFirebaseToken)(idToken, false);
69
+ if (userInfo.valid) {
70
+ return {
71
+ user: {
72
+ uid: (_e = userInfo.uid) != null ? _e : "",
73
+ email: (_f = userInfo.email) != null ? _f : null
74
+ },
75
+ token: idToken,
76
+ protect: async () => {
77
+ }
78
+ };
79
+ }
32
80
  }
81
+ return {
82
+ user: null,
83
+ token: null,
84
+ protect
85
+ };
86
+ } catch (error) {
87
+ return {
88
+ user: null,
89
+ token: null,
90
+ protect
91
+ };
92
+ }
93
+ }
94
+ async function edgeAuthSecond(request) {
95
+ var _a, _b;
96
+ async function protect() {
97
+ throw new Error("Unauthorized access");
98
+ }
99
+ try {
100
+ const sessionResult = await (0, import_edge_session.verifySession)(request);
101
+ if (sessionResult.isAuthenticated && sessionResult.user) {
102
+ return {
103
+ user: sessionResult.user,
104
+ token: ((_a = request.cookies.get("_session_cookie")) == null ? void 0 : _a.value) || ((_b = request.cookies.get("_session_token")) == null ? void 0 : _b.value) || null,
105
+ protect: async () => {
106
+ }
107
+ };
108
+ }
109
+ return {
110
+ user: null,
111
+ token: null,
112
+ protect
113
+ };
114
+ } catch (error) {
115
+ console.error("Auth check error:", error);
116
+ return {
117
+ user: null,
118
+ token: null,
119
+ protect
120
+ };
121
+ }
122
+ }
123
+ function ternSecureMiddleware(callback) {
124
+ return async function middleware(request) {
33
125
  try {
34
- const { userId, token, error } = await (0, import_auth.auth)();
35
- if (error || !userId || !token) {
36
- return import_server.NextResponse.redirect(new URL(redirectTo, request.url));
126
+ const auth = await edgeAuthSecond(request);
127
+ try {
128
+ await callback(auth, request);
129
+ const response = import_server.NextResponse.next();
130
+ if (auth.user) {
131
+ response.headers.set("x-user-id", auth.user.uid);
132
+ if (auth.user.email) {
133
+ response.headers.set("x-user-email", auth.user.email);
134
+ }
135
+ if (auth.user.emailVerified !== void 0) {
136
+ response.headers.set("x-email-verified", auth.user.emailVerified.toString());
137
+ }
138
+ if (auth.user.authTime) {
139
+ response.headers.set("x-auth-time", auth.user.authTime.toString());
140
+ }
141
+ }
142
+ return response;
143
+ } catch (error) {
144
+ if (error instanceof Error && error.message === "Unauthorized access") {
145
+ const redirectUrl = new URL("/sign-in", request.url);
146
+ redirectUrl.searchParams.set("redirect", request.nextUrl.pathname);
147
+ return import_server.NextResponse.redirect(redirectUrl);
148
+ }
149
+ throw error;
37
150
  }
38
- const response = import_server.NextResponse.next();
39
- return response;
40
151
  } catch (error) {
41
- console.error("Error in ternSecureMiddleware:", error);
42
- return import_server.NextResponse.redirect(new URL(redirectTo, request.url));
152
+ console.error("Middleware error:", {
153
+ error: error instanceof Error ? {
154
+ name: error.name,
155
+ message: error.message,
156
+ stack: error.stack
157
+ } : error,
158
+ path: request.nextUrl.pathname
159
+ });
160
+ const redirectUrl = new URL("/sign-in", request.url);
161
+ return import_server.NextResponse.redirect(redirectUrl);
43
162
  }
44
163
  };
45
164
  }
46
165
  // Annotate the CommonJS export names for ESM import in node:
47
166
  0 && (module.exports = {
167
+ createRouteMatcher,
168
+ runtime,
48
169
  ternSecureMiddleware
49
170
  });
50
171
  //# sourceMappingURL=ternSecureMiddleware.js.map