@propelauth/nextjs 0.0.114 → 0.0.118

Sign up to get free protection for your applications and to get access to all the features.
@@ -11,6 +11,55 @@ declare class ConfigurationException extends Error {
11
11
  constructor(message: string);
12
12
  }
13
13
 
14
+ declare enum SocialLoginProvider {
15
+ Google = "Google",
16
+ GitHub = "GitHub",
17
+ Microsoft = "Microsoft",
18
+ Slack = "Slack",
19
+ LinkedIn = "LinkedIn",
20
+ Salesforce = "Salesforce",
21
+ Xero = "Xero",
22
+ QuickBooksOnline = "QuickBooks Online"
23
+ }
24
+ declare enum SamlLoginProvider {
25
+ Google = "Google",
26
+ Rippling = "Rippling",
27
+ OneLogin = "OneLogin",
28
+ JumpCloud = "JumpCloud",
29
+ Okta = "Okta",
30
+ Azure = "Azure",
31
+ Duo = "Duo",
32
+ Generic = "Generic"
33
+ }
34
+ type PasswordLoginMethod = {
35
+ loginMethod: 'password';
36
+ };
37
+ type MagicLinkLoginMethod = {
38
+ loginMethod: 'magic_link';
39
+ };
40
+ type SocialSsoLoginMethod = {
41
+ loginMethod: 'social_sso';
42
+ provider: SocialLoginProvider;
43
+ };
44
+ type EmailConfirmationLinkLoginMethod = {
45
+ loginMethod: 'email_confirmation_link';
46
+ };
47
+ type SamlSsoLoginMethod = {
48
+ loginMethod: 'saml_sso';
49
+ provider: SamlLoginProvider;
50
+ orgId: string;
51
+ };
52
+ type ImpersonationLoginMethod = {
53
+ loginMethod: 'impersonation';
54
+ };
55
+ type GeneratedFromBackendApiLoginMethod = {
56
+ loginMethod: 'generated_from_backend_api';
57
+ };
58
+ type UnknownLoginMethod = {
59
+ loginMethod: 'unknown';
60
+ };
61
+ type LoginMethod = PasswordLoginMethod | MagicLinkLoginMethod | SocialSsoLoginMethod | EmailConfirmationLinkLoginMethod | SamlSsoLoginMethod | ImpersonationLoginMethod | GeneratedFromBackendApiLoginMethod | UnknownLoginMethod;
62
+
14
63
  declare class UserFromToken {
15
64
  userId: string;
16
65
  orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo;
@@ -21,11 +70,12 @@ declare class UserFromToken {
21
70
  properties?: {
22
71
  [key: string]: unknown;
23
72
  };
73
+ loginMethod?: LoginMethod;
24
74
  legacyUserId?: string;
25
75
  impersonatorUserId?: string;
26
76
  constructor(userId: string, email: string, orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo, firstName?: string, lastName?: string, username?: string, legacyUserId?: string, impersonatorUserId?: string, properties?: {
27
77
  [key: string]: unknown;
28
- });
78
+ }, loginMethod?: LoginMethod);
29
79
  getOrg(orgId: string): OrgMemberInfo | undefined;
30
80
  getOrgByName(orgName: string): OrgMemberInfo | undefined;
31
81
  getOrgs(): OrgMemberInfo[];
@@ -81,9 +81,34 @@ var import_navigation = require("next/navigation.js");
81
81
  var import_headers = require("next/headers.js");
82
82
  var import_server = require("next/server.js");
83
83
 
84
+ // src/loginMethod.ts
85
+ function toLoginMethod(snake_case) {
86
+ if (!snake_case) {
87
+ return { loginMethod: "unknown" };
88
+ }
89
+ switch (snake_case.login_method) {
90
+ case "password":
91
+ return { loginMethod: "password" };
92
+ case "magic_link":
93
+ return { loginMethod: "magic_link" };
94
+ case "social_sso":
95
+ return { loginMethod: "social_sso", provider: snake_case.provider };
96
+ case "email_confirmation_link":
97
+ return { loginMethod: "email_confirmation_link" };
98
+ case "saml_sso":
99
+ return { loginMethod: "saml_sso", provider: snake_case.provider, orgId: snake_case.org_id };
100
+ case "impersonation":
101
+ return { loginMethod: "impersonation" };
102
+ case "generated_from_backend_api":
103
+ return { loginMethod: "generated_from_backend_api" };
104
+ default:
105
+ return { loginMethod: "unknown" };
106
+ }
107
+ }
108
+
84
109
  // src/user.ts
85
110
  var UserFromToken = class {
86
- constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId, properties) {
111
+ constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId, properties, loginMethod) {
87
112
  this.userId = userId;
88
113
  this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo;
89
114
  this.email = email;
@@ -93,6 +118,7 @@ var UserFromToken = class {
93
118
  this.legacyUserId = legacyUserId;
94
119
  this.impersonatorUserId = impersonatorUserId;
95
120
  this.properties = properties;
121
+ this.loginMethod = loginMethod;
96
122
  }
97
123
  getOrg(orgId) {
98
124
  if (!this.orgIdToOrgMemberInfo) {
@@ -126,9 +152,7 @@ var UserFromToken = class {
126
152
  const obj = JSON.parse(json);
127
153
  const orgIdToOrgMemberInfo = {};
128
154
  for (const orgId in obj.orgIdToOrgMemberInfo) {
129
- orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(
130
- JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])
131
- );
155
+ orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(JSON.stringify(obj.orgIdToOrgMemberInfo[orgId]));
132
156
  }
133
157
  return new UserFromToken(
134
158
  obj.userId,
@@ -139,7 +163,8 @@ var UserFromToken = class {
139
163
  obj.username,
140
164
  obj.legacyUserId,
141
165
  obj.impersonatorUserId,
142
- obj.properties
166
+ obj.properties,
167
+ obj.loginMethod
143
168
  );
144
169
  }
145
170
  };
@@ -199,7 +224,8 @@ function toUser(snake_case) {
199
224
  snake_case.username,
200
225
  snake_case.legacy_user_id,
201
226
  snake_case.impersonatorUserId,
202
- snake_case.properties
227
+ snake_case.properties,
228
+ toLoginMethod(snake_case.login_method)
203
229
  );
204
230
  }
205
231
  function toOrgIdToOrgMemberInfo(snake_case) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/server/app-router-index.ts","../../../src/server/exceptions.ts","../../../src/server/app-router.ts","../../../src/user.ts","../../../src/server/shared.ts"],"sourcesContent":["export {UnauthorizedException, ConfigurationException} from \"./exceptions\"\nexport {getRouteHandlers, getUser, getUserOrRedirect, getAccessToken, authMiddleware} from \"./app-router\"\nexport type {RouteHandlerArgs} from \"./app-router\"\n","export class UnauthorizedException extends Error {\n readonly message: string\n readonly status: number\n\n constructor(message: string) {\n super(message)\n this.message = message\n this.status = 401\n }\n}\n\nexport class ConfigurationException extends Error {\n readonly message: string\n readonly status: number\n\n constructor(message: string) {\n super(message)\n this.message = message\n this.status = 500\n }\n}\n","import { redirect } from 'next/navigation.js'\nimport { cookies, headers } from 'next/headers.js'\nimport { NextRequest, NextResponse } from 'next/server.js'\nimport {\n ACCESS_TOKEN_COOKIE_NAME,\n CALLBACK_PATH,\n COOKIE_OPTIONS,\n CUSTOM_HEADER_FOR_ACCESS_TOKEN,\n getAuthUrlOrigin,\n getIntegrationApiKey,\n getRedirectUri,\n LOGIN_PATH,\n LOGOUT_PATH,\n REFRESH_TOKEN_COOKIE_NAME,\n refreshTokenWithAccessAndRefreshToken,\n RETURN_TO_PATH_COOKIE_NAME,\n STATE_COOKIE_NAME,\n USERINFO_PATH,\n validateAccessToken,\n validateAccessTokenOrUndefined,\n} from './shared'\nimport { UserFromToken } from './index'\n\nexport async function getUserOrRedirect(): Promise<UserFromToken> {\n const user = await getUser()\n if (user) {\n return user\n } else {\n redirect(LOGIN_PATH)\n throw new Error('Redirecting to login')\n }\n}\n\nexport async function getUser(): Promise<UserFromToken | undefined> {\n const accessToken = headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || cookies().get(ACCESS_TOKEN_COOKIE_NAME)?.value\n if (accessToken) {\n const user = await validateAccessTokenOrUndefined(accessToken)\n if (user) {\n return user\n }\n }\n return undefined\n}\n\nexport async function getAccessToken(): Promise<string | undefined> {\n return headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || cookies().get(ACCESS_TOKEN_COOKIE_NAME)?.value\n}\n\n// Purpose of this middleware is just to keep the access token cookie alive\n// In an ideal world, this could be done in `getUser`, however, you can't\n// set a cookie in a server component.\n// There also doesn't seem to be any way right now to set a cookie in a\n// middleware and pass it forward (you can only set them on the response).\n// You CAN, however, pass in custom headers,\n// so we'll use CUSTOM_HEADER_FOR_ACCESS_TOKEN as a workaround\nexport async function authMiddleware(req: NextRequest): Promise<Response> {\n if (req.headers.has(CUSTOM_HEADER_FOR_ACCESS_TOKEN)) {\n throw new Error(`${CUSTOM_HEADER_FOR_ACCESS_TOKEN} is set which is for internal use only`)\n } else if (\n req.nextUrl.pathname === CALLBACK_PATH ||\n req.nextUrl.pathname === LOGOUT_PATH ||\n req.nextUrl.pathname === USERINFO_PATH\n ) {\n // Don't do anything for the callback, logout, or userinfo paths, as they will modify the cookies themselves\n return NextResponse.next()\n }\n\n const accessToken = req.cookies.get(ACCESS_TOKEN_COOKIE_NAME)?.value\n const refreshToken = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n\n // If we are authenticated, we can continue\n if (accessToken) {\n const user = await validateAccessTokenOrUndefined(accessToken)\n if (user) {\n return NextResponse.next()\n }\n }\n\n // Otherwise, we need to refresh the access token\n if (refreshToken) {\n const response = await refreshTokenWithAccessAndRefreshToken(refreshToken)\n if (response.error === 'unexpected') {\n throw new Error('Unexpected error while refreshing access token')\n } else if (response.error === 'unauthorized') {\n const response = NextResponse.next()\n response.cookies.delete(ACCESS_TOKEN_COOKIE_NAME)\n response.cookies.delete(REFRESH_TOKEN_COOKIE_NAME)\n return response\n } else {\n const headers = new Headers(req.headers)\n // Pass along the new access token in a header since cookies don't work\n headers.append(CUSTOM_HEADER_FOR_ACCESS_TOKEN, response.accessToken)\n const nextResponse = NextResponse.next({\n request: {\n headers,\n },\n })\n nextResponse.cookies.set(ACCESS_TOKEN_COOKIE_NAME, response.accessToken, COOKIE_OPTIONS)\n nextResponse.cookies.set(REFRESH_TOKEN_COOKIE_NAME, response.refreshToken, COOKIE_OPTIONS)\n return nextResponse\n }\n }\n\n return NextResponse.next()\n}\n\nexport type RouteHandlerArgs = {\n postLoginRedirectPathFn?: (req: NextRequest) => string\n}\n\nexport function getRouteHandlers(args?: RouteHandlerArgs) {\n function loginGetHandler(req: NextRequest) {\n return signupOrLoginHandler(req, false)\n }\n\n function signupGetHandler(req: NextRequest) {\n return signupOrLoginHandler(req, true)\n }\n\n function signupOrLoginHandler(req: NextRequest, isSignup: boolean) {\n const returnToPath = req.nextUrl.searchParams.get('return_to_path')\n const state = randomState()\n const redirectUri = getRedirectUri()\n\n const authorizeUrlSearchParams = new URLSearchParams({\n redirect_uri: redirectUri,\n state,\n signup: isSignup ? 'true' : 'false',\n })\n const authorize_url = getAuthUrlOrigin() + '/propelauth/ssr/authorize?' + authorizeUrlSearchParams.toString()\n\n const headers = new Headers()\n headers.append('Location', authorize_url)\n headers.append('Set-Cookie', `${STATE_COOKIE_NAME}=${state}; Path=/; HttpOnly; Secure; SameSite=Lax`)\n if (returnToPath) {\n if (returnToPath.startsWith('/')) {\n headers.append(\n 'Set-Cookie',\n `${RETURN_TO_PATH_COOKIE_NAME}=${returnToPath}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=600`\n )\n } else {\n console.warn('return_to_path must start with /')\n }\n }\n\n return new Response(null, {\n status: 302,\n headers,\n })\n }\n\n async function callbackGetHandler(req: NextRequest) {\n const oauthState = req.cookies.get(STATE_COOKIE_NAME)?.value\n if (!oauthState || oauthState.length !== 64) {\n return new Response(null, { status: 302, headers: { Location: LOGIN_PATH } })\n }\n\n const queryParams = req.nextUrl.searchParams\n const state = queryParams.get('state')\n const code = queryParams.get('code')\n if (state !== oauthState) {\n return new Response(null, { status: 302, headers: { Location: LOGIN_PATH } })\n }\n\n const authUrlOrigin = getAuthUrlOrigin()\n const redirectUri = getRedirectUri()\n const integrationApiKey = getIntegrationApiKey()\n const oauth_token_body = {\n redirect_uri: redirectUri,\n code,\n }\n const url = `${authUrlOrigin}/propelauth/ssr/token`\n const response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(oauth_token_body),\n headers: {\n 'Content-Type': 'application/json',\n Authorization: 'Bearer ' + integrationApiKey,\n },\n })\n\n if (response.ok) {\n const data = await response.json()\n\n const accessToken = data.access_token\n\n // If we have a return_to_path cookie, we'll use that\n // Otherwise, we'll use the postLoginRedirectPathFn\n const returnToPathFromCookie = req.cookies.get(RETURN_TO_PATH_COOKIE_NAME)?.value\n const returnToPath =\n returnToPathFromCookie ?? (args?.postLoginRedirectPathFn ? args.postLoginRedirectPathFn(req) : '/')\n if (!returnToPath) {\n console.error('postLoginRedirectPathFn returned undefined')\n return new Response('Unexpected error', { status: 500 })\n }\n\n const headers = new Headers()\n headers.append('Location', returnToPath)\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=${data.refresh_token}; Path=/; HttpOnly; Secure; SameSite=Lax`\n )\n headers.append(\n 'Set-Cookie',\n `${RETURN_TO_PATH_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response(null, {\n status: 302,\n headers,\n })\n } else if (response.status === 401) {\n console.error(\n \"Couldn't finish the login process for this user. This is most likely caused by an incorrect PROPELAUTH_API_KEY.\"\n )\n return new Response('Unexpected error', { status: 500 })\n } else {\n return new Response('Unexpected error', { status: 500 })\n }\n }\n\n async function userinfoGetHandler(req: NextRequest) {\n const oldRefreshToken = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n\n // For the userinfo endpoint, we want to get the most up-to-date info, so we'll refresh the access token\n if (oldRefreshToken) {\n const refreshResponse = await refreshTokenWithAccessAndRefreshToken(oldRefreshToken)\n if (refreshResponse.error === 'unexpected') {\n throw new Error('Unexpected error while refreshing access token')\n } else if (refreshResponse.error === 'unauthorized') {\n const headers = new Headers()\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response('Unauthorized', { status: 401, headers })\n }\n\n const refreshToken = refreshResponse.refreshToken\n const accessToken = refreshResponse.accessToken\n\n const authUrlOrigin = getAuthUrlOrigin()\n const path = `${authUrlOrigin}/propelauth/oauth/userinfo`\n const response = await fetch(path, {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: 'Bearer ' + accessToken,\n },\n })\n if (response.ok) {\n const userFromToken = await validateAccessToken(accessToken)\n const data = await response.json()\n const jsonResponse = {\n userinfo: data,\n accessToken,\n impersonatorUserId: userFromToken.impersonatorUserId,\n }\n\n const headers = new Headers()\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=${refreshToken}; Path=/; HttpOnly; Secure; SameSite=Lax`\n )\n headers.append('Content-Type', 'application/json')\n return new Response(JSON.stringify(jsonResponse), {\n status: 200,\n headers,\n })\n } else if (response.status === 401) {\n const headers = new Headers()\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response(null, {\n status: 401,\n headers,\n })\n } else {\n return new Response(null, { status: 500 })\n }\n }\n\n const headers = new Headers()\n headers.append('Set-Cookie', `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n headers.append('Set-Cookie', `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n return new Response(null, { status: 401 })\n }\n\n async function logoutGetHandler(req: NextRequest) {\n // Real logout requests will go to the logout POST handler\n // This endpoint is a landing page for when people logout from the hosted UIs\n // Instead of doing a logout we'll check the refresh token.\n // If it's invalid, we'll clear the cookies and redirect using the postLoginRedirectPathFn\n const path = args?.postLoginRedirectPathFn ? args.postLoginRedirectPathFn(req) : '/'\n if (!path) {\n console.error('postLoginPathFn returned undefined')\n return new Response('Unexpected error', { status: 500 })\n }\n\n const refreshToken = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n if (!refreshToken) {\n const headers = new Headers()\n headers.append('Location', path)\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response(null, {\n status: 302,\n headers,\n })\n }\n\n const refreshResponse = await refreshTokenWithAccessAndRefreshToken(refreshToken)\n if (refreshResponse.error === 'unexpected') {\n console.error('Unexpected error while refreshing access token')\n return new Response('Unexpected error', { status: 500 })\n } else if (refreshResponse.error === 'unauthorized') {\n const headers = new Headers()\n headers.append('Location', path)\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response(null, {\n status: 302,\n headers,\n })\n } else {\n const headers = new Headers()\n headers.append('Location', path)\n return new Response(null, {\n status: 302,\n headers,\n })\n }\n }\n\n async function logoutPostHandler(req: NextRequest) {\n const refreshToken = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n if (!refreshToken) {\n const headers = new Headers()\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response(null, { status: 200, headers })\n }\n\n const authUrlOrigin = getAuthUrlOrigin()\n const integrationApiKey = getIntegrationApiKey()\n const logoutBody = { refresh_token: refreshToken }\n const url = `${authUrlOrigin}/api/backend/v1/logout`\n const response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(logoutBody),\n headers: {\n 'Content-Type': 'application/json',\n Authorization: 'Bearer ' + integrationApiKey,\n },\n })\n\n if (!response.ok) {\n console.warn(\n 'Unable to logout, clearing cookies and continuing anyway',\n response.status,\n response.statusText\n )\n }\n const headers = new Headers()\n headers.append('Set-Cookie', `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n headers.append('Set-Cookie', `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n return new Response(null, { status: 200, headers })\n }\n\n function getRouteHandler(req: NextRequest, { params }: { params: { slug: string } }) {\n if (params.slug === 'login') {\n return loginGetHandler(req)\n } else if (params.slug === 'signup') {\n return signupGetHandler(req)\n } else if (params.slug === 'callback') {\n return callbackGetHandler(req)\n } else if (params.slug === 'userinfo') {\n return userinfoGetHandler(req)\n } else if (params.slug === 'logout') {\n return logoutGetHandler(req)\n } else {\n return new Response('', { status: 404 })\n }\n }\n\n function postRouteHandler(req: NextRequest, { params }: { params: { slug: string } }) {\n if (params.slug === 'logout') {\n return logoutPostHandler(req)\n } else {\n return new Response('', { status: 404 })\n }\n }\n\n return {\n getRouteHandler,\n postRouteHandler,\n }\n}\n\nfunction randomState(): string {\n const randomBytes = crypto.getRandomValues(new Uint8Array(32))\n return Array.from(randomBytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n","export class UserFromToken {\n public userId: string\n public orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo\n\n // Metadata about the user\n public email: string\n public firstName?: string\n public lastName?: string\n public username?: string\n public properties?: { [key: string]: unknown }\n\n // If you used our migration APIs to migrate this user from a different system,\n // this is their original ID from that system.\n public legacyUserId?: string\n public impersonatorUserId?: string\n\n constructor(\n userId: string,\n email: string,\n orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo,\n firstName?: string,\n lastName?: string,\n username?: string,\n legacyUserId?: string,\n impersonatorUserId?: string,\n properties?: { [key: string]: unknown },\n ) {\n this.userId = userId\n this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo\n\n this.email = email\n this.firstName = firstName\n this.lastName = lastName\n this.username = username\n\n this.legacyUserId = legacyUserId\n this.impersonatorUserId = impersonatorUserId\n\n this.properties = properties\n }\n\n public getOrg(orgId: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n return this.orgIdToOrgMemberInfo[orgId]\n }\n\n public getOrgByName(orgName: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n const urlSafeOrgName = orgName.toLowerCase().replace(/ /g, \"-\")\n for (const orgId in this.orgIdToOrgMemberInfo) {\n const orgMemberInfo = this.orgIdToOrgMemberInfo[orgId]\n if (orgMemberInfo.urlSafeOrgName === urlSafeOrgName) {\n return orgMemberInfo\n }\n }\n\n return undefined\n }\n\n public getOrgs(): OrgMemberInfo[] {\n if (!this.orgIdToOrgMemberInfo) {\n return []\n }\n\n return Object.values(this.orgIdToOrgMemberInfo)\n }\n\n public isImpersonating(): boolean {\n return !!this.impersonatorUserId\n }\n\n public static fromJSON(json: string): UserFromToken {\n const obj = JSON.parse(json)\n const orgIdToOrgMemberInfo: OrgIdToOrgMemberInfo = {}\n for (const orgId in obj.orgIdToOrgMemberInfo) {\n orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(\n JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])\n )\n }\n return new UserFromToken(\n obj.userId,\n obj.email,\n orgIdToOrgMemberInfo,\n obj.firstName,\n obj.lastName,\n obj.username,\n obj.legacyUserId,\n obj.impersonatorUserId,\n obj.properties,\n )\n }\n}\n\nexport type OrgIdToOrgMemberInfo = {\n [orgId: string]: OrgMemberInfo\n}\n\nexport class OrgMemberInfo {\n public orgId: string\n public orgName: string\n public orgMetadata: { [key: string]: any }\n public urlSafeOrgName: string\n\n public userAssignedRole: string\n public userInheritedRolesPlusCurrentRole: string[]\n public userPermissions: string[]\n\n constructor(\n orgId: string,\n orgName: string,\n orgMetadata: { [key: string]: any },\n urlSafeOrgName: string,\n userAssignedRole: string,\n userInheritedRolesPlusCurrentRole: string[],\n userPermissions: string[]\n ) {\n this.orgId = orgId\n this.orgName = orgName\n this.orgMetadata = orgMetadata\n this.urlSafeOrgName = urlSafeOrgName\n\n this.userAssignedRole = userAssignedRole\n this.userInheritedRolesPlusCurrentRole = userInheritedRolesPlusCurrentRole\n this.userPermissions = userPermissions\n }\n\n // validation methods\n\n public isRole(role: string): boolean {\n return this.userAssignedRole === role\n }\n\n public isAtLeastRole(role: string): boolean {\n return this.userInheritedRolesPlusCurrentRole.includes(role)\n }\n\n public hasPermission(permission: string): boolean {\n return this.userPermissions.includes(permission)\n }\n\n public hasAllPermissions(permissions: string[]): boolean {\n return permissions.every((permission) => this.hasPermission(permission))\n }\n\n public static fromJSON(json: string): OrgMemberInfo {\n const obj = JSON.parse(json)\n return new OrgMemberInfo(\n obj.orgId,\n obj.orgName,\n obj.orgMetadata,\n obj.urlSafeOrgName,\n obj.userAssignedRole,\n obj.userInheritedRolesPlusCurrentRole,\n obj.userPermissions\n )\n }\n\n // getters for the private fields\n\n get assignedRole(): string {\n return this.userAssignedRole\n }\n\n get inheritedRolesPlusCurrentRole(): string[] {\n return this.userInheritedRolesPlusCurrentRole\n }\n\n get permissions(): string[] {\n return this.userPermissions\n }\n}\n\n// These Internal types exist since the server returns snake case, but typescript/javascript\n// convention is camelCase.\nexport type InternalOrgMemberInfo = {\n org_id: string\n org_name: string\n org_metadata: { [key: string]: any }\n url_safe_org_name: string\n user_role: string\n inherited_user_roles_plus_current_role: string[]\n user_permissions: string[]\n}\nexport type InternalUser = {\n user_id: string\n org_id_to_org_member_info?: { [org_id: string]: InternalOrgMemberInfo }\n\n email: string\n first_name?: string\n last_name?: string\n username?: string\n properties?: { [key: string]: unknown }\n\n // If you used our migration APIs to migrate this user from a different system, this is their original ID from that system.\n legacy_user_id?: string\n impersonatorUserId?: string\n}\n\nexport function toUser(snake_case: InternalUser): UserFromToken {\n return new UserFromToken(\n snake_case.user_id,\n snake_case.email,\n toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),\n snake_case.first_name,\n snake_case.last_name,\n snake_case.username,\n snake_case.legacy_user_id,\n snake_case.impersonatorUserId,\n snake_case.properties,\n )\n}\n\nexport function toOrgIdToOrgMemberInfo(snake_case?: {\n [org_id: string]: InternalOrgMemberInfo\n}): OrgIdToOrgMemberInfo | undefined {\n if (snake_case === undefined) {\n return undefined\n }\n const camelCase: OrgIdToOrgMemberInfo = {}\n\n for (const key of Object.keys(snake_case)) {\n const snakeCaseValue = snake_case[key]\n if (snakeCaseValue) {\n camelCase[key] = new OrgMemberInfo(\n snakeCaseValue.org_id,\n snakeCaseValue.org_name,\n snakeCaseValue.org_metadata,\n snakeCaseValue.url_safe_org_name,\n snakeCaseValue.user_role,\n snakeCaseValue.inherited_user_roles_plus_current_role,\n snakeCaseValue.user_permissions\n )\n }\n }\n\n return camelCase\n}\n","import {ResponseCookie} from \"next/dist/compiled/@edge-runtime/cookies\";\nimport {InternalUser, toUser, UserFromToken} from \"../user\";\nimport {ConfigurationException, UnauthorizedException} from \"./exceptions\";\nimport * as jose from \"jose\";\n\ntype RefreshAndAccessTokens = {\n refreshToken: string\n accessToken: string\n error: \"none\"\n}\n\ntype RefreshAndAccessTokensUnauthorizedError = {\n error: \"unauthorized\"\n}\n\ntype RefreshAndAccessTokensUnexpectedError = {\n error: \"unexpected\"\n}\n\nexport type RefreshTokenResponse =\n RefreshAndAccessTokens\n | RefreshAndAccessTokensUnauthorizedError\n | RefreshAndAccessTokensUnexpectedError\n\nexport const LOGIN_PATH = \"/api/auth/login\"\nexport const CALLBACK_PATH = \"/api/auth/callback\"\nexport const USERINFO_PATH = \"/api/auth/userinfo\"\nexport const LOGOUT_PATH = \"/api/auth/logout\"\nexport const ACCESS_TOKEN_COOKIE_NAME = \"__pa_at\"\nexport const REFRESH_TOKEN_COOKIE_NAME = \"__pa_rt\"\nexport const STATE_COOKIE_NAME = \"__pa_state\"\nexport const CUSTOM_HEADER_FOR_ACCESS_TOKEN = \"x-propelauth-access-token\"\nexport const RETURN_TO_PATH_COOKIE_NAME = \"__pa_return_to_path\"\n\nexport const COOKIE_OPTIONS: Partial<ResponseCookie> = {\n httpOnly: true,\n sameSite: \"lax\",\n secure: true,\n path: \"/\",\n}\n\nexport function getAuthUrlOrigin() {\n return getAuthUrl().origin\n}\n\nexport function getAuthUrl() {\n const authUrl = process.env.NEXT_PUBLIC_AUTH_URL\n if (!authUrl) {\n throw new Error(\"NEXT_PUBLIC_AUTH_URL is not set\")\n }\n return new URL(authUrl)\n}\n\nexport function getRedirectUri() {\n const redirectUri = process.env.PROPELAUTH_REDIRECT_URI\n if (!redirectUri) {\n throw new Error(\"PROPELAUTH_REDIRECT_URI is not set\")\n }\n return redirectUri\n}\n\nexport function getIntegrationApiKey() {\n const integrationApiKey = process.env.PROPELAUTH_API_KEY\n if (!integrationApiKey) {\n throw new Error(\"PROPELAUTH_API_KEY is not set\")\n }\n return integrationApiKey\n}\n\nexport function getVerifierKey() {\n const verifierKey = process.env.PROPELAUTH_VERIFIER_KEY\n if (!verifierKey) {\n throw new Error(\"PROPELAUTH_VERIFIER_KEY is not set\")\n }\n return verifierKey.replace(/\\\\n/g, \"\\n\")\n}\n\nexport async function refreshTokenWithAccessAndRefreshToken(refreshToken: string): Promise<RefreshTokenResponse> {\n const body = {\n refresh_token: refreshToken,\n }\n const url = `${getAuthUrlOrigin()}/api/backend/v1/refresh_token`\n const response = await fetch(url, {\n method: \"POST\",\n body: JSON.stringify(body),\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer \" + getIntegrationApiKey(),\n },\n })\n\n if (response.ok) {\n const data = await response.json()\n const newRefreshToken = data.refresh_token\n const {\n access_token: accessToken,\n expires_at_seconds: expiresAtSeconds,\n } = data.access_token\n\n return {\n refreshToken: newRefreshToken,\n accessToken,\n error: \"none\",\n }\n } else if (response.status === 400 || response.status === 401) {\n return {error: \"unauthorized\"}\n } else {\n return {error: \"unexpected\"}\n }\n}\n\nexport async function validateAccessTokenOrUndefined(accessToken: string | undefined): Promise<UserFromToken | undefined> {\n try {\n return await validateAccessToken(accessToken)\n } catch (err) {\n if (err instanceof ConfigurationException) {\n throw err\n } else if (err instanceof UnauthorizedException) {\n return undefined\n } else {\n console.info(\"Error validating access token\", err)\n return undefined\n }\n }\n}\n\nexport async function validateAccessToken(accessToken: string | undefined): Promise<UserFromToken> {\n let publicKey\n try {\n publicKey = await jose.importSPKI(getVerifierKey(), \"RS256\")\n } catch (err) {\n console.error(\"Verifier key is invalid. Make sure it's specified correctly, including the newlines.\", err)\n throw new ConfigurationException(\"Invalid verifier key\")\n }\n\n if (!accessToken) {\n throw new UnauthorizedException(\"No access token provided\")\n }\n\n let accessTokenWithoutBearer = accessToken\n if (accessToken.toLowerCase().startsWith(\"bearer \")) {\n accessTokenWithoutBearer = accessToken.substring(\"bearer \".length)\n }\n\n try {\n const {payload} = await jose.jwtVerify(accessTokenWithoutBearer, publicKey, {\n issuer: getAuthUrlOrigin(),\n algorithms: [\"RS256\"],\n })\n\n return toUser(<InternalUser>payload)\n } catch (e) {\n if (e instanceof Error) {\n throw new UnauthorizedException(e.message)\n } else {\n throw new UnauthorizedException(\"Unable to decode jwt\")\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAI7C,YAAY,SAAiB;AACzB,UAAM,OAAO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AA,IAC/B,OAAO;AACH,aAAO,IAAI,SAAS,IAAI,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC3C;AAAA,EACJ;AAEA,WAAS,iBAAiB,KAAkB,EAAE,OAAO,GAAiC;AAClF,QAAI,OAAO,SAAS,UAAU;AAC1B,aAAO,kBAAkB,GAAG;AAAA,IAChC,OAAO;AACH,aAAO,IAAI,SAAS,IAAI,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC3C;AAAA,EACJ;AAEA,SAAO;AAAA,IACH;AAAA,IACA;AAAA,EACJ;AACJ;AAEA,SAAS,cAAsB;AAC3B,QAAM,cAAc,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC;AAC7D,SAAO,MAAM,KAAK,WAAW,EACxB,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAC1C,KAAK,EAAE;AAChB;","names":["response","headers"]}
1
+ {"version":3,"sources":["../../../src/server/app-router-index.ts","../../../src/server/exceptions.ts","../../../src/server/app-router.ts","../../../src/loginMethod.ts","../../../src/user.ts","../../../src/server/shared.ts"],"sourcesContent":["export {UnauthorizedException, ConfigurationException} from \"./exceptions\"\nexport {getRouteHandlers, getUser, getUserOrRedirect, getAccessToken, authMiddleware} from \"./app-router\"\nexport type {RouteHandlerArgs} from \"./app-router\"\n","export class UnauthorizedException extends Error {\n readonly message: string\n readonly status: number\n\n constructor(message: string) {\n super(message)\n this.message = message\n this.status = 401\n }\n}\n\nexport class ConfigurationException extends Error {\n readonly message: string\n readonly status: number\n\n constructor(message: string) {\n super(message)\n this.message = message\n this.status = 500\n }\n}\n","import { redirect } from 'next/navigation.js'\nimport { cookies, headers } from 'next/headers.js'\nimport { NextRequest, NextResponse } from 'next/server.js'\nimport {\n ACCESS_TOKEN_COOKIE_NAME,\n CALLBACK_PATH,\n COOKIE_OPTIONS,\n CUSTOM_HEADER_FOR_ACCESS_TOKEN,\n getAuthUrlOrigin,\n getIntegrationApiKey,\n getRedirectUri,\n LOGIN_PATH,\n LOGOUT_PATH,\n REFRESH_TOKEN_COOKIE_NAME,\n refreshTokenWithAccessAndRefreshToken,\n RETURN_TO_PATH_COOKIE_NAME,\n STATE_COOKIE_NAME,\n USERINFO_PATH,\n validateAccessToken,\n validateAccessTokenOrUndefined,\n} from './shared'\nimport { UserFromToken } from './index'\n\nexport async function getUserOrRedirect(): Promise<UserFromToken> {\n const user = await getUser()\n if (user) {\n return user\n } else {\n redirect(LOGIN_PATH)\n throw new Error('Redirecting to login')\n }\n}\n\nexport async function getUser(): Promise<UserFromToken | undefined> {\n const accessToken = headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || cookies().get(ACCESS_TOKEN_COOKIE_NAME)?.value\n if (accessToken) {\n const user = await validateAccessTokenOrUndefined(accessToken)\n if (user) {\n return user\n }\n }\n return undefined\n}\n\nexport async function getAccessToken(): Promise<string | undefined> {\n return headers().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || cookies().get(ACCESS_TOKEN_COOKIE_NAME)?.value\n}\n\n// Purpose of this middleware is just to keep the access token cookie alive\n// In an ideal world, this could be done in `getUser`, however, you can't\n// set a cookie in a server component.\n// There also doesn't seem to be any way right now to set a cookie in a\n// middleware and pass it forward (you can only set them on the response).\n// You CAN, however, pass in custom headers,\n// so we'll use CUSTOM_HEADER_FOR_ACCESS_TOKEN as a workaround\nexport async function authMiddleware(req: NextRequest): Promise<Response> {\n if (req.headers.has(CUSTOM_HEADER_FOR_ACCESS_TOKEN)) {\n throw new Error(`${CUSTOM_HEADER_FOR_ACCESS_TOKEN} is set which is for internal use only`)\n } else if (\n req.nextUrl.pathname === CALLBACK_PATH ||\n req.nextUrl.pathname === LOGOUT_PATH ||\n req.nextUrl.pathname === USERINFO_PATH\n ) {\n // Don't do anything for the callback, logout, or userinfo paths, as they will modify the cookies themselves\n return NextResponse.next()\n }\n\n const accessToken = req.cookies.get(ACCESS_TOKEN_COOKIE_NAME)?.value\n const refreshToken = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n\n // If we are authenticated, we can continue\n if (accessToken) {\n const user = await validateAccessTokenOrUndefined(accessToken)\n if (user) {\n return NextResponse.next()\n }\n }\n\n // Otherwise, we need to refresh the access token\n if (refreshToken) {\n const response = await refreshTokenWithAccessAndRefreshToken(refreshToken)\n if (response.error === 'unexpected') {\n throw new Error('Unexpected error while refreshing access token')\n } else if (response.error === 'unauthorized') {\n const response = NextResponse.next()\n response.cookies.delete(ACCESS_TOKEN_COOKIE_NAME)\n response.cookies.delete(REFRESH_TOKEN_COOKIE_NAME)\n return response\n } else {\n const headers = new Headers(req.headers)\n // Pass along the new access token in a header since cookies don't work\n headers.append(CUSTOM_HEADER_FOR_ACCESS_TOKEN, response.accessToken)\n const nextResponse = NextResponse.next({\n request: {\n headers,\n },\n })\n nextResponse.cookies.set(ACCESS_TOKEN_COOKIE_NAME, response.accessToken, COOKIE_OPTIONS)\n nextResponse.cookies.set(REFRESH_TOKEN_COOKIE_NAME, response.refreshToken, COOKIE_OPTIONS)\n return nextResponse\n }\n }\n\n return NextResponse.next()\n}\n\nexport type RouteHandlerArgs = {\n postLoginRedirectPathFn?: (req: NextRequest) => string\n}\n\nexport function getRouteHandlers(args?: RouteHandlerArgs) {\n function loginGetHandler(req: NextRequest) {\n return signupOrLoginHandler(req, false)\n }\n\n function signupGetHandler(req: NextRequest) {\n return signupOrLoginHandler(req, true)\n }\n\n function signupOrLoginHandler(req: NextRequest, isSignup: boolean) {\n const returnToPath = req.nextUrl.searchParams.get('return_to_path')\n const state = randomState()\n const redirectUri = getRedirectUri()\n\n const authorizeUrlSearchParams = new URLSearchParams({\n redirect_uri: redirectUri,\n state,\n signup: isSignup ? 'true' : 'false',\n })\n const authorize_url = getAuthUrlOrigin() + '/propelauth/ssr/authorize?' + authorizeUrlSearchParams.toString()\n\n const headers = new Headers()\n headers.append('Location', authorize_url)\n headers.append('Set-Cookie', `${STATE_COOKIE_NAME}=${state}; Path=/; HttpOnly; Secure; SameSite=Lax`)\n if (returnToPath) {\n if (returnToPath.startsWith('/')) {\n headers.append(\n 'Set-Cookie',\n `${RETURN_TO_PATH_COOKIE_NAME}=${returnToPath}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=600`\n )\n } else {\n console.warn('return_to_path must start with /')\n }\n }\n\n return new Response(null, {\n status: 302,\n headers,\n })\n }\n\n async function callbackGetHandler(req: NextRequest) {\n const oauthState = req.cookies.get(STATE_COOKIE_NAME)?.value\n if (!oauthState || oauthState.length !== 64) {\n return new Response(null, { status: 302, headers: { Location: LOGIN_PATH } })\n }\n\n const queryParams = req.nextUrl.searchParams\n const state = queryParams.get('state')\n const code = queryParams.get('code')\n if (state !== oauthState) {\n return new Response(null, { status: 302, headers: { Location: LOGIN_PATH } })\n }\n\n const authUrlOrigin = getAuthUrlOrigin()\n const redirectUri = getRedirectUri()\n const integrationApiKey = getIntegrationApiKey()\n const oauth_token_body = {\n redirect_uri: redirectUri,\n code,\n }\n const url = `${authUrlOrigin}/propelauth/ssr/token`\n const response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(oauth_token_body),\n headers: {\n 'Content-Type': 'application/json',\n Authorization: 'Bearer ' + integrationApiKey,\n },\n })\n\n if (response.ok) {\n const data = await response.json()\n\n const accessToken = data.access_token\n\n // If we have a return_to_path cookie, we'll use that\n // Otherwise, we'll use the postLoginRedirectPathFn\n const returnToPathFromCookie = req.cookies.get(RETURN_TO_PATH_COOKIE_NAME)?.value\n const returnToPath =\n returnToPathFromCookie ?? (args?.postLoginRedirectPathFn ? args.postLoginRedirectPathFn(req) : '/')\n if (!returnToPath) {\n console.error('postLoginRedirectPathFn returned undefined')\n return new Response('Unexpected error', { status: 500 })\n }\n\n const headers = new Headers()\n headers.append('Location', returnToPath)\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=${data.refresh_token}; Path=/; HttpOnly; Secure; SameSite=Lax`\n )\n headers.append(\n 'Set-Cookie',\n `${RETURN_TO_PATH_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response(null, {\n status: 302,\n headers,\n })\n } else if (response.status === 401) {\n console.error(\n \"Couldn't finish the login process for this user. This is most likely caused by an incorrect PROPELAUTH_API_KEY.\"\n )\n return new Response('Unexpected error', { status: 500 })\n } else {\n return new Response('Unexpected error', { status: 500 })\n }\n }\n\n async function userinfoGetHandler(req: NextRequest) {\n const oldRefreshToken = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n\n // For the userinfo endpoint, we want to get the most up-to-date info, so we'll refresh the access token\n if (oldRefreshToken) {\n const refreshResponse = await refreshTokenWithAccessAndRefreshToken(oldRefreshToken)\n if (refreshResponse.error === 'unexpected') {\n throw new Error('Unexpected error while refreshing access token')\n } else if (refreshResponse.error === 'unauthorized') {\n const headers = new Headers()\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response('Unauthorized', { status: 401, headers })\n }\n\n const refreshToken = refreshResponse.refreshToken\n const accessToken = refreshResponse.accessToken\n\n const authUrlOrigin = getAuthUrlOrigin()\n const path = `${authUrlOrigin}/propelauth/oauth/userinfo`\n const response = await fetch(path, {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: 'Bearer ' + accessToken,\n },\n })\n if (response.ok) {\n const userFromToken = await validateAccessToken(accessToken)\n const data = await response.json()\n const jsonResponse = {\n userinfo: data,\n accessToken,\n impersonatorUserId: userFromToken.impersonatorUserId,\n }\n\n const headers = new Headers()\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=${refreshToken}; Path=/; HttpOnly; Secure; SameSite=Lax`\n )\n headers.append('Content-Type', 'application/json')\n return new Response(JSON.stringify(jsonResponse), {\n status: 200,\n headers,\n })\n } else if (response.status === 401) {\n const headers = new Headers()\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response(null, {\n status: 401,\n headers,\n })\n } else {\n return new Response(null, { status: 500 })\n }\n }\n\n const headers = new Headers()\n headers.append('Set-Cookie', `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n headers.append('Set-Cookie', `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n return new Response(null, { status: 401 })\n }\n\n async function logoutGetHandler(req: NextRequest) {\n // Real logout requests will go to the logout POST handler\n // This endpoint is a landing page for when people logout from the hosted UIs\n // Instead of doing a logout we'll check the refresh token.\n // If it's invalid, we'll clear the cookies and redirect using the postLoginRedirectPathFn\n const path = args?.postLoginRedirectPathFn ? args.postLoginRedirectPathFn(req) : '/'\n if (!path) {\n console.error('postLoginPathFn returned undefined')\n return new Response('Unexpected error', { status: 500 })\n }\n\n const refreshToken = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n if (!refreshToken) {\n const headers = new Headers()\n headers.append('Location', path)\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response(null, {\n status: 302,\n headers,\n })\n }\n\n const refreshResponse = await refreshTokenWithAccessAndRefreshToken(refreshToken)\n if (refreshResponse.error === 'unexpected') {\n console.error('Unexpected error while refreshing access token')\n return new Response('Unexpected error', { status: 500 })\n } else if (refreshResponse.error === 'unauthorized') {\n const headers = new Headers()\n headers.append('Location', path)\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response(null, {\n status: 302,\n headers,\n })\n } else {\n const headers = new Headers()\n headers.append('Location', path)\n return new Response(null, {\n status: 302,\n headers,\n })\n }\n }\n\n async function logoutPostHandler(req: NextRequest) {\n const refreshToken = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)?.value\n if (!refreshToken) {\n const headers = new Headers()\n headers.append(\n 'Set-Cookie',\n `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n headers.append(\n 'Set-Cookie',\n `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`\n )\n return new Response(null, { status: 200, headers })\n }\n\n const authUrlOrigin = getAuthUrlOrigin()\n const integrationApiKey = getIntegrationApiKey()\n const logoutBody = { refresh_token: refreshToken }\n const url = `${authUrlOrigin}/api/backend/v1/logout`\n const response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(logoutBody),\n headers: {\n 'Content-Type': 'application/json',\n Authorization: 'Bearer ' + integrationApiKey,\n },\n })\n\n if (!response.ok) {\n console.warn(\n 'Unable to logout, clearing cookies and continuing anyway',\n response.status,\n response.statusText\n )\n }\n const headers = new Headers()\n headers.append('Set-Cookie', `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n headers.append('Set-Cookie', `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`)\n return new Response(null, { status: 200, headers })\n }\n\n function getRouteHandler(req: NextRequest, { params }: { params: { slug: string } }) {\n if (params.slug === 'login') {\n return loginGetHandler(req)\n } else if (params.slug === 'signup') {\n return signupGetHandler(req)\n } else if (params.slug === 'callback') {\n return callbackGetHandler(req)\n } else if (params.slug === 'userinfo') {\n return userinfoGetHandler(req)\n } else if (params.slug === 'logout') {\n return logoutGetHandler(req)\n } else {\n return new Response('', { status: 404 })\n }\n }\n\n function postRouteHandler(req: NextRequest, { params }: { params: { slug: string } }) {\n if (params.slug === 'logout') {\n return logoutPostHandler(req)\n } else {\n return new Response('', { status: 404 })\n }\n }\n\n return {\n getRouteHandler,\n postRouteHandler,\n }\n}\n\nfunction randomState(): string {\n const randomBytes = crypto.getRandomValues(new Uint8Array(32))\n return Array.from(randomBytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n","export enum SocialLoginProvider {\n Google = 'Google',\n GitHub = 'GitHub',\n Microsoft = 'Microsoft',\n Slack = 'Slack',\n LinkedIn = 'LinkedIn',\n Salesforce = 'Salesforce',\n Xero = 'Xero',\n QuickBooksOnline = 'QuickBooks Online',\n}\n\nexport enum SamlLoginProvider {\n Google = 'Google',\n Rippling = 'Rippling',\n OneLogin = 'OneLogin',\n JumpCloud = 'JumpCloud',\n Okta = 'Okta',\n Azure = 'Azure',\n Duo = 'Duo',\n Generic = 'Generic',\n}\n\ntype InternalPasswordLoginMethod = {\n login_method: 'password'\n}\n\ntype InternalMagicLinkLoginMethod = {\n login_method: 'magic_link'\n}\n\ntype InternalSocialSsoLoginMethod = {\n login_method: 'social_sso'\n provider: SocialLoginProvider\n}\n\ntype InternalEmailConfirmationLinkLoginMethod = {\n login_method: 'email_confirmation_link'\n}\n\ntype InternalSamlSsoLoginMethod = {\n login_method: 'saml_sso'\n provider: SamlLoginProvider\n org_id: string\n}\n\ntype InternalImpersonationLoginMethod = {\n login_method: 'impersonation'\n}\n\ntype InternalGeneratedFromBackendApiLoginMethod = {\n login_method: 'generated_from_backend_api'\n}\n\ntype InternalUnknownLoginMethod = {\n login_method: 'unknown'\n}\n\nexport type InternalLoginMethod =\n | InternalPasswordLoginMethod\n | InternalMagicLinkLoginMethod\n | InternalSocialSsoLoginMethod\n | InternalEmailConfirmationLinkLoginMethod\n | InternalSamlSsoLoginMethod\n | InternalImpersonationLoginMethod\n | InternalGeneratedFromBackendApiLoginMethod\n | InternalUnknownLoginMethod\n\ntype PasswordLoginMethod = {\n loginMethod: 'password'\n}\n\ntype MagicLinkLoginMethod = {\n loginMethod: 'magic_link'\n}\n\ntype SocialSsoLoginMethod = {\n loginMethod: 'social_sso'\n provider: SocialLoginProvider\n}\n\ntype EmailConfirmationLinkLoginMethod = {\n loginMethod: 'email_confirmation_link'\n}\n\ntype SamlSsoLoginMethod = {\n loginMethod: 'saml_sso'\n provider: SamlLoginProvider\n orgId: string\n}\n\ntype ImpersonationLoginMethod = {\n loginMethod: 'impersonation'\n}\n\ntype GeneratedFromBackendApiLoginMethod = {\n loginMethod: 'generated_from_backend_api'\n}\n\ntype UnknownLoginMethod = {\n loginMethod: 'unknown'\n}\n\nexport type LoginMethod =\n | PasswordLoginMethod\n | MagicLinkLoginMethod\n | SocialSsoLoginMethod\n | EmailConfirmationLinkLoginMethod\n | SamlSsoLoginMethod\n | ImpersonationLoginMethod\n | GeneratedFromBackendApiLoginMethod\n | UnknownLoginMethod\n\nexport function toLoginMethod(snake_case?: InternalLoginMethod): LoginMethod {\n if (!snake_case) {\n return { loginMethod: 'unknown' }\n }\n\n switch (snake_case.login_method) {\n case 'password':\n return { loginMethod: 'password' }\n case 'magic_link':\n return { loginMethod: 'magic_link' }\n case 'social_sso':\n return { loginMethod: 'social_sso', provider: snake_case.provider }\n case 'email_confirmation_link':\n return { loginMethod: 'email_confirmation_link' }\n case 'saml_sso':\n return { loginMethod: 'saml_sso', provider: snake_case.provider, orgId: snake_case.org_id }\n case 'impersonation':\n return { loginMethod: 'impersonation' }\n case 'generated_from_backend_api':\n return { loginMethod: 'generated_from_backend_api' }\n default:\n return { loginMethod: 'unknown' }\n }\n}\n","import { InternalLoginMethod, LoginMethod, toLoginMethod } from './loginMethod'\n\nexport class UserFromToken {\n public userId: string\n public orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo\n\n // Metadata about the user\n public email: string\n public firstName?: string\n public lastName?: string\n public username?: string\n public properties?: { [key: string]: unknown }\n public loginMethod?: LoginMethod\n\n // If you used our migration APIs to migrate this user from a different system,\n // this is their original ID from that system.\n public legacyUserId?: string\n public impersonatorUserId?: string\n\n constructor(\n userId: string,\n email: string,\n orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo,\n firstName?: string,\n lastName?: string,\n username?: string,\n legacyUserId?: string,\n impersonatorUserId?: string,\n properties?: { [key: string]: unknown },\n loginMethod?: LoginMethod\n ) {\n this.userId = userId\n this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo\n\n this.email = email\n this.firstName = firstName\n this.lastName = lastName\n this.username = username\n\n this.legacyUserId = legacyUserId\n this.impersonatorUserId = impersonatorUserId\n\n this.properties = properties\n this.loginMethod = loginMethod\n }\n\n public getOrg(orgId: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n return this.orgIdToOrgMemberInfo[orgId]\n }\n\n public getOrgByName(orgName: string): OrgMemberInfo | undefined {\n if (!this.orgIdToOrgMemberInfo) {\n return undefined\n }\n\n const urlSafeOrgName = orgName.toLowerCase().replace(/ /g, '-')\n for (const orgId in this.orgIdToOrgMemberInfo) {\n const orgMemberInfo = this.orgIdToOrgMemberInfo[orgId]\n if (orgMemberInfo.urlSafeOrgName === urlSafeOrgName) {\n return orgMemberInfo\n }\n }\n\n return undefined\n }\n\n public getOrgs(): OrgMemberInfo[] {\n if (!this.orgIdToOrgMemberInfo) {\n return []\n }\n\n return Object.values(this.orgIdToOrgMemberInfo)\n }\n\n public isImpersonating(): boolean {\n return !!this.impersonatorUserId\n }\n\n public static fromJSON(json: string): UserFromToken {\n const obj = JSON.parse(json)\n const orgIdToOrgMemberInfo: OrgIdToOrgMemberInfo = {}\n for (const orgId in obj.orgIdToOrgMemberInfo) {\n orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(JSON.stringify(obj.orgIdToOrgMemberInfo[orgId]))\n }\n return new UserFromToken(\n obj.userId,\n obj.email,\n orgIdToOrgMemberInfo,\n obj.firstName,\n obj.lastName,\n obj.username,\n obj.legacyUserId,\n obj.impersonatorUserId,\n obj.properties,\n obj.loginMethod\n )\n }\n}\n\nexport type OrgIdToOrgMemberInfo = {\n [orgId: string]: OrgMemberInfo\n}\n\nexport class OrgMemberInfo {\n public orgId: string\n public orgName: string\n public orgMetadata: { [key: string]: any }\n public urlSafeOrgName: string\n\n public userAssignedRole: string\n public userInheritedRolesPlusCurrentRole: string[]\n public userPermissions: string[]\n\n constructor(\n orgId: string,\n orgName: string,\n orgMetadata: { [key: string]: any },\n urlSafeOrgName: string,\n userAssignedRole: string,\n userInheritedRolesPlusCurrentRole: string[],\n userPermissions: string[]\n ) {\n this.orgId = orgId\n this.orgName = orgName\n this.orgMetadata = orgMetadata\n this.urlSafeOrgName = urlSafeOrgName\n\n this.userAssignedRole = userAssignedRole\n this.userInheritedRolesPlusCurrentRole = userInheritedRolesPlusCurrentRole\n this.userPermissions = userPermissions\n }\n\n // validation methods\n\n public isRole(role: string): boolean {\n return this.userAssignedRole === role\n }\n\n public isAtLeastRole(role: string): boolean {\n return this.userInheritedRolesPlusCurrentRole.includes(role)\n }\n\n public hasPermission(permission: string): boolean {\n return this.userPermissions.includes(permission)\n }\n\n public hasAllPermissions(permissions: string[]): boolean {\n return permissions.every((permission) => this.hasPermission(permission))\n }\n\n public static fromJSON(json: string): OrgMemberInfo {\n const obj = JSON.parse(json)\n return new OrgMemberInfo(\n obj.orgId,\n obj.orgName,\n obj.orgMetadata,\n obj.urlSafeOrgName,\n obj.userAssignedRole,\n obj.userInheritedRolesPlusCurrentRole,\n obj.userPermissions\n )\n }\n\n // getters for the private fields\n\n get assignedRole(): string {\n return this.userAssignedRole\n }\n\n get inheritedRolesPlusCurrentRole(): string[] {\n return this.userInheritedRolesPlusCurrentRole\n }\n\n get permissions(): string[] {\n return this.userPermissions\n }\n}\n\n// These Internal types exist since the server returns snake case, but typescript/javascript\n// convention is camelCase.\nexport type InternalOrgMemberInfo = {\n org_id: string\n org_name: string\n org_metadata: { [key: string]: any }\n url_safe_org_name: string\n user_role: string\n inherited_user_roles_plus_current_role: string[]\n user_permissions: string[]\n}\n\nexport type InternalUser = {\n user_id: string\n org_id_to_org_member_info?: { [org_id: string]: InternalOrgMemberInfo }\n\n email: string\n first_name?: string\n last_name?: string\n username?: string\n properties?: { [key: string]: unknown }\n login_method?: InternalLoginMethod\n\n // If you used our migration APIs to migrate this user from a different system, this is their original ID from that system.\n legacy_user_id?: string\n impersonatorUserId?: string\n}\n\nexport function toUser(snake_case: InternalUser): UserFromToken {\n return new UserFromToken(\n snake_case.user_id,\n snake_case.email,\n toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),\n snake_case.first_name,\n snake_case.last_name,\n snake_case.username,\n snake_case.legacy_user_id,\n snake_case.impersonatorUserId,\n snake_case.properties,\n toLoginMethod(snake_case.login_method)\n )\n}\n\nexport function toOrgIdToOrgMemberInfo(snake_case?: {\n [org_id: string]: InternalOrgMemberInfo\n}): OrgIdToOrgMemberInfo | undefined {\n if (snake_case === undefined) {\n return undefined\n }\n const camelCase: OrgIdToOrgMemberInfo = {}\n\n for (const key of Object.keys(snake_case)) {\n const snakeCaseValue = snake_case[key]\n if (snakeCaseValue) {\n camelCase[key] = new OrgMemberInfo(\n snakeCaseValue.org_id,\n snakeCaseValue.org_name,\n snakeCaseValue.org_metadata,\n snakeCaseValue.url_safe_org_name,\n snakeCaseValue.user_role,\n snakeCaseValue.inherited_user_roles_plus_current_role,\n snakeCaseValue.user_permissions\n )\n }\n }\n\n return camelCase\n}\n","import {ResponseCookie} from \"next/dist/compiled/@edge-runtime/cookies\";\nimport {InternalUser, toUser, UserFromToken} from \"../user\";\nimport {ConfigurationException, UnauthorizedException} from \"./exceptions\";\nimport * as jose from \"jose\";\n\ntype RefreshAndAccessTokens = {\n refreshToken: string\n accessToken: string\n error: \"none\"\n}\n\ntype RefreshAndAccessTokensUnauthorizedError = {\n error: \"unauthorized\"\n}\n\ntype RefreshAndAccessTokensUnexpectedError = {\n error: \"unexpected\"\n}\n\nexport type RefreshTokenResponse =\n RefreshAndAccessTokens\n | RefreshAndAccessTokensUnauthorizedError\n | RefreshAndAccessTokensUnexpectedError\n\nexport const LOGIN_PATH = \"/api/auth/login\"\nexport const CALLBACK_PATH = \"/api/auth/callback\"\nexport const USERINFO_PATH = \"/api/auth/userinfo\"\nexport const LOGOUT_PATH = \"/api/auth/logout\"\nexport const ACCESS_TOKEN_COOKIE_NAME = \"__pa_at\"\nexport const REFRESH_TOKEN_COOKIE_NAME = \"__pa_rt\"\nexport const STATE_COOKIE_NAME = \"__pa_state\"\nexport const CUSTOM_HEADER_FOR_ACCESS_TOKEN = \"x-propelauth-access-token\"\nexport const RETURN_TO_PATH_COOKIE_NAME = \"__pa_return_to_path\"\n\nexport const COOKIE_OPTIONS: Partial<ResponseCookie> = {\n httpOnly: true,\n sameSite: \"lax\",\n secure: true,\n path: \"/\",\n}\n\nexport function getAuthUrlOrigin() {\n return getAuthUrl().origin\n}\n\nexport function getAuthUrl() {\n const authUrl = process.env.NEXT_PUBLIC_AUTH_URL\n if (!authUrl) {\n throw new Error(\"NEXT_PUBLIC_AUTH_URL is not set\")\n }\n return new URL(authUrl)\n}\n\nexport function getRedirectUri() {\n const redirectUri = process.env.PROPELAUTH_REDIRECT_URI\n if (!redirectUri) {\n throw new Error(\"PROPELAUTH_REDIRECT_URI is not set\")\n }\n return redirectUri\n}\n\nexport function getIntegrationApiKey() {\n const integrationApiKey = process.env.PROPELAUTH_API_KEY\n if (!integrationApiKey) {\n throw new Error(\"PROPELAUTH_API_KEY is not set\")\n }\n return integrationApiKey\n}\n\nexport function getVerifierKey() {\n const verifierKey = process.env.PROPELAUTH_VERIFIER_KEY\n if (!verifierKey) {\n throw new Error(\"PROPELAUTH_VERIFIER_KEY is not set\")\n }\n return verifierKey.replace(/\\\\n/g, \"\\n\")\n}\n\nexport async function refreshTokenWithAccessAndRefreshToken(refreshToken: string): Promise<RefreshTokenResponse> {\n const body = {\n refresh_token: refreshToken,\n }\n const url = `${getAuthUrlOrigin()}/api/backend/v1/refresh_token`\n const response = await fetch(url, {\n method: \"POST\",\n body: JSON.stringify(body),\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \"Bearer \" + getIntegrationApiKey(),\n },\n })\n\n if (response.ok) {\n const data = await response.json()\n const newRefreshToken = data.refresh_token\n const {\n access_token: accessToken,\n expires_at_seconds: expiresAtSeconds,\n } = data.access_token\n\n return {\n refreshToken: newRefreshToken,\n accessToken,\n error: \"none\",\n }\n } else if (response.status === 400 || response.status === 401) {\n return {error: \"unauthorized\"}\n } else {\n return {error: \"unexpected\"}\n }\n}\n\nexport async function validateAccessTokenOrUndefined(accessToken: string | undefined): Promise<UserFromToken | undefined> {\n try {\n return await validateAccessToken(accessToken)\n } catch (err) {\n if (err instanceof ConfigurationException) {\n throw err\n } else if (err instanceof UnauthorizedException) {\n return undefined\n } else {\n console.info(\"Error validating access token\", err)\n return undefined\n }\n }\n}\n\nexport async function validateAccessToken(accessToken: string | undefined): Promise<UserFromToken> {\n let publicKey\n try {\n publicKey = await jose.importSPKI(getVerifierKey(), \"RS256\")\n } catch (err) {\n console.error(\"Verifier key is invalid. Make sure it's specified correctly, including the newlines.\", err)\n throw new ConfigurationException(\"Invalid verifier key\")\n }\n\n if (!accessToken) {\n throw new UnauthorizedException(\"No access token provided\")\n }\n\n let accessTokenWithoutBearer = accessToken\n if (accessToken.toLowerCase().startsWith(\"bearer \")) {\n accessTokenWithoutBearer = accessToken.substring(\"bearer \".length)\n }\n\n try {\n const {payload} = await jose.jwtVerify(accessTokenWithoutBearer, publicKey, {\n issuer: getAuthUrlOrigin(),\n algorithms: [\"RS256\"],\n })\n\n return toUser(<InternalUser>payload)\n } catch (e) {\n if (e instanceof Error) {\n throw new UnauthorizedException(e.message)\n } else {\n throw new UnauthorizedException(\"Unable to decode jwt\")\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAI7C,YAAY,SAAiB;AACzB,UAAM,OAAO;AACb,SAAK,UAAU;AACf,SAAK,SAAS;AAAA,EAClB;AACJ;AAEO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EAI9C,YAAY,SAAiB;AACzB,UAAM,OAAO;AACb,SAAK,UAAU;AACf,SAAK,SAAS;AAAA,EAClB;AACJ;;;ACpBA,wBAAyB;AACzB,qBAAiC;AACjC,oBAA0C;;;AC8GnC,SAAS,cAAc,YAA+C;AACzE,MAAI,CAAC,YAAY;AACb,WAAO,EAAE,aAAa,UAAU;AAAA,EACpC;AAEA,UAAQ,WAAW,cAAc;AAAA,IAC7B,KAAK;AACD,aAAO,EAAE,aAAa,WAAW;AAAA,IACrC,KAAK;AACD,aAAO,EAAE,aAAa,aAAa;AAAA,IACvC,KAAK;AACD,aAAO,EAAE,aAAa,cAAc,UAAU,WAAW,SAAS;AAAA,IACtE,KAAK;AACD,aAAO,EAAE,aAAa,0BAA0B;AAAA,IACpD,KAAK;AACD,aAAO,EAAE,aAAa,YAAY,UAAU,WAAW,UAAU,OAAO,WAAW,OAAO;AAAA,IAC9F,KAAK;AACD,aAAO,E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AAI,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC3C;AAAA,EACJ;AAEA,WAAS,iBAAiB,KAAkB,EAAE,OAAO,GAAiC;AAClF,QAAI,OAAO,SAAS,UAAU;AAC1B,aAAO,kBAAkB,GAAG;AAAA,IAChC,OAAO;AACH,aAAO,IAAI,SAAS,IAAI,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC3C;AAAA,EACJ;AAEA,SAAO;AAAA,IACH;AAAA,IACA;AAAA,EACJ;AACJ;AAEA,SAAS,cAAsB;AAC3B,QAAM,cAAc,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC;AAC7D,SAAO,MAAM,KAAK,WAAW,EACxB,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAC1C,KAAK,EAAE;AAChB;","names":["response","headers"]}
@@ -40,9 +40,34 @@ import { redirect } from "next/navigation.js";
40
40
  import { cookies, headers } from "next/headers.js";
41
41
  import { NextResponse } from "next/server.js";
42
42
 
43
+ // src/loginMethod.ts
44
+ function toLoginMethod(snake_case) {
45
+ if (!snake_case) {
46
+ return { loginMethod: "unknown" };
47
+ }
48
+ switch (snake_case.login_method) {
49
+ case "password":
50
+ return { loginMethod: "password" };
51
+ case "magic_link":
52
+ return { loginMethod: "magic_link" };
53
+ case "social_sso":
54
+ return { loginMethod: "social_sso", provider: snake_case.provider };
55
+ case "email_confirmation_link":
56
+ return { loginMethod: "email_confirmation_link" };
57
+ case "saml_sso":
58
+ return { loginMethod: "saml_sso", provider: snake_case.provider, orgId: snake_case.org_id };
59
+ case "impersonation":
60
+ return { loginMethod: "impersonation" };
61
+ case "generated_from_backend_api":
62
+ return { loginMethod: "generated_from_backend_api" };
63
+ default:
64
+ return { loginMethod: "unknown" };
65
+ }
66
+ }
67
+
43
68
  // src/user.ts
44
69
  var UserFromToken = class {
45
- constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId, properties) {
70
+ constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId, properties, loginMethod) {
46
71
  this.userId = userId;
47
72
  this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo;
48
73
  this.email = email;
@@ -52,6 +77,7 @@ var UserFromToken = class {
52
77
  this.legacyUserId = legacyUserId;
53
78
  this.impersonatorUserId = impersonatorUserId;
54
79
  this.properties = properties;
80
+ this.loginMethod = loginMethod;
55
81
  }
56
82
  getOrg(orgId) {
57
83
  if (!this.orgIdToOrgMemberInfo) {
@@ -85,9 +111,7 @@ var UserFromToken = class {
85
111
  const obj = JSON.parse(json);
86
112
  const orgIdToOrgMemberInfo = {};
87
113
  for (const orgId in obj.orgIdToOrgMemberInfo) {
88
- orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(
89
- JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])
90
- );
114
+ orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(JSON.stringify(obj.orgIdToOrgMemberInfo[orgId]));
91
115
  }
92
116
  return new UserFromToken(
93
117
  obj.userId,
@@ -98,7 +122,8 @@ var UserFromToken = class {
98
122
  obj.username,
99
123
  obj.legacyUserId,
100
124
  obj.impersonatorUserId,
101
- obj.properties
125
+ obj.properties,
126
+ obj.loginMethod
102
127
  );
103
128
  }
104
129
  };
@@ -158,7 +183,8 @@ function toUser(snake_case) {
158
183
  snake_case.username,
159
184
  snake_case.legacy_user_id,
160
185
  snake_case.impersonatorUserId,
161
- snake_case.properties
186
+ snake_case.properties,
187
+ toLoginMethod(snake_case.login_method)
162
188
  );
163
189
  }
164
190
  function toOrgIdToOrgMemberInfo(snake_case) {