@propelauth/nextjs 0.0.63 → 0.0.67

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.
@@ -0,0 +1,75 @@
1
+ import { NextRequest } from 'next/server';
2
+
3
+ declare class UnauthorizedException extends Error {
4
+ readonly message: string;
5
+ readonly status: number;
6
+ constructor(message: string);
7
+ }
8
+ declare class ConfigurationException extends Error {
9
+ readonly message: string;
10
+ readonly status: number;
11
+ constructor(message: string);
12
+ }
13
+
14
+ declare class User {
15
+ userId: string;
16
+ orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo;
17
+ email: string;
18
+ firstName?: string;
19
+ lastName?: string;
20
+ username?: string;
21
+ legacyUserId?: string;
22
+ impersonatorUserId?: string;
23
+ constructor(userId: string, email: string, orgIdToOrgMemberInfo?: OrgIdToOrgMemberInfo, firstName?: string, lastName?: string, username?: string, legacyUserId?: string, impersonatorUserId?: string);
24
+ getOrg(orgId: string): OrgMemberInfo | undefined;
25
+ getOrgByName(orgName: string): OrgMemberInfo | undefined;
26
+ getOrgs(): OrgMemberInfo[];
27
+ isImpersonating(): boolean;
28
+ static fromJSON(json: string): User;
29
+ }
30
+ type OrgIdToOrgMemberInfo = {
31
+ [orgId: string]: OrgMemberInfo;
32
+ };
33
+ declare class OrgMemberInfo {
34
+ orgId: string;
35
+ orgName: string;
36
+ orgMetadata: {
37
+ [key: string]: any;
38
+ };
39
+ urlSafeOrgName: string;
40
+ private userAssignedRole;
41
+ private userInheritedRolesPlusCurrentRole;
42
+ private userPermissions;
43
+ constructor(orgId: string, orgName: string, orgMetadata: {
44
+ [key: string]: any;
45
+ }, urlSafeOrgName: string, userAssignedRole: string, userInheritedRolesPlusCurrentRole: string[], userPermissions: string[]);
46
+ isRole(role: string): boolean;
47
+ isAtLeastRole(role: string): boolean;
48
+ hasPermission(permission: string): boolean;
49
+ hasAllPermissions(permissions: string[]): boolean;
50
+ static fromJSON(json: string): OrgMemberInfo;
51
+ get assignedRole(): string;
52
+ get inheritedRolesPlusCurrentRole(): string[];
53
+ get permissions(): string[];
54
+ }
55
+
56
+ declare function getUserOrRedirect(): Promise<User>;
57
+ declare function getUser(): Promise<User | undefined>;
58
+ declare function authMiddleware(req: NextRequest): Promise<Response>;
59
+ type RouteHandlerArgs = {
60
+ postLoginRedirectPathFn?: (user: User, req: NextRequest) => string;
61
+ };
62
+ declare function getRouteHandlers(args?: RouteHandlerArgs): {
63
+ getRouteHandler: (req: NextRequest, { params }: {
64
+ params: {
65
+ slug: string;
66
+ };
67
+ }) => Response | Promise<Response>;
68
+ postRouteHandler: (req: NextRequest, { params }: {
69
+ params: {
70
+ slug: string;
71
+ };
72
+ }) => Response | Promise<Response>;
73
+ };
74
+
75
+ export { ConfigurationException, RouteHandlerArgs, UnauthorizedException, authMiddleware, getRouteHandlers, getUser, getUserOrRedirect };
@@ -0,0 +1,624 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var __async = (__this, __arguments, generator) => {
30
+ return new Promise((resolve, reject) => {
31
+ var fulfilled = (value) => {
32
+ try {
33
+ step(generator.next(value));
34
+ } catch (e) {
35
+ reject(e);
36
+ }
37
+ };
38
+ var rejected = (value) => {
39
+ try {
40
+ step(generator.throw(value));
41
+ } catch (e) {
42
+ reject(e);
43
+ }
44
+ };
45
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
46
+ step((generator = generator.apply(__this, __arguments)).next());
47
+ });
48
+ };
49
+
50
+ // src/server/app-router-index.ts
51
+ var app_router_index_exports = {};
52
+ __export(app_router_index_exports, {
53
+ ConfigurationException: () => ConfigurationException,
54
+ UnauthorizedException: () => UnauthorizedException,
55
+ authMiddleware: () => authMiddleware,
56
+ getRouteHandlers: () => getRouteHandlers,
57
+ getUser: () => getUser,
58
+ getUserOrRedirect: () => getUserOrRedirect
59
+ });
60
+ module.exports = __toCommonJS(app_router_index_exports);
61
+
62
+ // src/server/exceptions.ts
63
+ var UnauthorizedException = class extends Error {
64
+ constructor(message) {
65
+ super(message);
66
+ this.message = message;
67
+ this.status = 401;
68
+ }
69
+ };
70
+ var ConfigurationException = class extends Error {
71
+ constructor(message) {
72
+ super(message);
73
+ this.message = message;
74
+ this.status = 500;
75
+ }
76
+ };
77
+
78
+ // src/user.ts
79
+ var User = class {
80
+ constructor(userId, email, orgIdToOrgMemberInfo, firstName, lastName, username, legacyUserId, impersonatorUserId) {
81
+ this.userId = userId;
82
+ this.orgIdToOrgMemberInfo = orgIdToOrgMemberInfo;
83
+ this.email = email;
84
+ this.firstName = firstName;
85
+ this.lastName = lastName;
86
+ this.username = username;
87
+ this.legacyUserId = legacyUserId;
88
+ this.impersonatorUserId = impersonatorUserId;
89
+ }
90
+ getOrg(orgId) {
91
+ if (!this.orgIdToOrgMemberInfo) {
92
+ return void 0;
93
+ }
94
+ return this.orgIdToOrgMemberInfo[orgId];
95
+ }
96
+ getOrgByName(orgName) {
97
+ if (!this.orgIdToOrgMemberInfo) {
98
+ return void 0;
99
+ }
100
+ const urlSafeOrgName = orgName.toLowerCase().replace(/ /g, "-");
101
+ for (const orgId in this.orgIdToOrgMemberInfo) {
102
+ const orgMemberInfo = this.orgIdToOrgMemberInfo[orgId];
103
+ if (orgMemberInfo.urlSafeOrgName === urlSafeOrgName) {
104
+ return orgMemberInfo;
105
+ }
106
+ }
107
+ return void 0;
108
+ }
109
+ getOrgs() {
110
+ if (!this.orgIdToOrgMemberInfo) {
111
+ return [];
112
+ }
113
+ return Object.values(this.orgIdToOrgMemberInfo);
114
+ }
115
+ isImpersonating() {
116
+ return !!this.impersonatorUserId;
117
+ }
118
+ static fromJSON(json) {
119
+ const obj = JSON.parse(json);
120
+ const orgIdToOrgMemberInfo = {};
121
+ for (const orgId in obj.orgIdToOrgMemberInfo) {
122
+ orgIdToOrgMemberInfo[orgId] = OrgMemberInfo.fromJSON(
123
+ JSON.stringify(obj.orgIdToOrgMemberInfo[orgId])
124
+ );
125
+ }
126
+ return new User(
127
+ obj.userId,
128
+ obj.email,
129
+ orgIdToOrgMemberInfo,
130
+ obj.firstName,
131
+ obj.lastName,
132
+ obj.username,
133
+ obj.legacyUserId,
134
+ obj.impersonatorUserId
135
+ );
136
+ }
137
+ };
138
+ var OrgMemberInfo = class {
139
+ constructor(orgId, orgName, orgMetadata, urlSafeOrgName, userAssignedRole, userInheritedRolesPlusCurrentRole, userPermissions) {
140
+ this.orgId = orgId;
141
+ this.orgName = orgName;
142
+ this.orgMetadata = orgMetadata;
143
+ this.urlSafeOrgName = urlSafeOrgName;
144
+ this.userAssignedRole = userAssignedRole;
145
+ this.userInheritedRolesPlusCurrentRole = userInheritedRolesPlusCurrentRole;
146
+ this.userPermissions = userPermissions;
147
+ }
148
+ // validation methods
149
+ isRole(role) {
150
+ return this.userAssignedRole === role;
151
+ }
152
+ isAtLeastRole(role) {
153
+ return this.userInheritedRolesPlusCurrentRole.includes(role);
154
+ }
155
+ hasPermission(permission) {
156
+ return this.userPermissions.includes(permission);
157
+ }
158
+ hasAllPermissions(permissions) {
159
+ return permissions.every((permission) => this.hasPermission(permission));
160
+ }
161
+ static fromJSON(json) {
162
+ const obj = JSON.parse(json);
163
+ return new OrgMemberInfo(
164
+ obj.orgId,
165
+ obj.orgName,
166
+ obj.orgMetadata,
167
+ obj.urlSafeOrgName,
168
+ obj.userAssignedRole,
169
+ obj.userInheritedRolesPlusCurrentRole,
170
+ obj.userPermissions
171
+ );
172
+ }
173
+ // getters for the private fields
174
+ get assignedRole() {
175
+ return this.userAssignedRole;
176
+ }
177
+ get inheritedRolesPlusCurrentRole() {
178
+ return this.userInheritedRolesPlusCurrentRole;
179
+ }
180
+ get permissions() {
181
+ return this.userPermissions;
182
+ }
183
+ };
184
+ function toUser(snake_case) {
185
+ return new User(
186
+ snake_case.user_id,
187
+ snake_case.email,
188
+ toOrgIdToOrgMemberInfo(snake_case.org_id_to_org_member_info),
189
+ snake_case.first_name,
190
+ snake_case.last_name,
191
+ snake_case.username,
192
+ snake_case.legacy_user_id,
193
+ snake_case.impersonatorUserId
194
+ );
195
+ }
196
+ function toOrgIdToOrgMemberInfo(snake_case) {
197
+ if (snake_case === void 0) {
198
+ return void 0;
199
+ }
200
+ const camelCase = {};
201
+ for (const key of Object.keys(snake_case)) {
202
+ const snakeCaseValue = snake_case[key];
203
+ if (snakeCaseValue) {
204
+ camelCase[key] = new OrgMemberInfo(
205
+ snakeCaseValue.org_id,
206
+ snakeCaseValue.org_name,
207
+ snakeCaseValue.org_metadata,
208
+ snakeCaseValue.url_safe_org_name,
209
+ snakeCaseValue.user_role,
210
+ snakeCaseValue.inherited_user_roles_plus_current_role,
211
+ snakeCaseValue.user_permissions
212
+ );
213
+ }
214
+ }
215
+ return camelCase;
216
+ }
217
+
218
+ // src/server/app-router.ts
219
+ var import_navigation = require("next/navigation");
220
+ var import_headers = require("next/headers");
221
+ var import_server = require("next/server");
222
+
223
+ // src/server/shared.ts
224
+ var jose = __toESM(require("jose"));
225
+ var LOGIN_PATH = "/api/auth/login";
226
+ var CALLBACK_PATH = "/api/auth/callback";
227
+ var USERINFO_PATH = "/api/auth/userinfo";
228
+ var LOGOUT_PATH = "/api/auth/logout";
229
+ var ACCESS_TOKEN_COOKIE_NAME = "__pa_at";
230
+ var REFRESH_TOKEN_COOKIE_NAME = "__pa_rt";
231
+ var STATE_COOKIE_NAME = "__pa_state";
232
+ var CUSTOM_HEADER_FOR_ACCESS_TOKEN = "x-propelauth-access-token";
233
+ var COOKIE_OPTIONS = {
234
+ httpOnly: true,
235
+ sameSite: "lax",
236
+ secure: true,
237
+ path: "/"
238
+ };
239
+ function getAuthUrlOrigin() {
240
+ const authUrl = process.env.NEXT_PUBLIC_AUTH_URL;
241
+ if (!authUrl) {
242
+ throw new Error("NEXT_PUBLIC_AUTH_URL is not set");
243
+ }
244
+ return new URL(authUrl).origin;
245
+ }
246
+ function getRedirectUri() {
247
+ const redirectUri = process.env.REDIRECT_URI;
248
+ if (!redirectUri) {
249
+ throw new Error("REDIRECT_URI is not set");
250
+ }
251
+ return redirectUri;
252
+ }
253
+ function getIntegrationApiKey() {
254
+ const integrationApiKey = process.env.PROPELAUTH_API_KEY;
255
+ if (!integrationApiKey) {
256
+ throw new Error("PROPELAUTH_API_KEY is not set");
257
+ }
258
+ return integrationApiKey;
259
+ }
260
+ function getVerifierKey() {
261
+ const verifierKey = process.env.VERIFIER_KEY;
262
+ if (!verifierKey) {
263
+ throw new Error("VERIFIER_KEY is not set");
264
+ }
265
+ return verifierKey.replace(/\\n/g, "\n");
266
+ }
267
+ function refreshTokenWithAccessAndRefreshToken(refreshToken) {
268
+ return __async(this, null, function* () {
269
+ const body = {
270
+ refresh_token: refreshToken
271
+ };
272
+ const url = `${getAuthUrlOrigin()}/api/backend/v1/refresh_token`;
273
+ const response = yield fetch(url, {
274
+ method: "POST",
275
+ body: JSON.stringify(body),
276
+ headers: {
277
+ "Content-Type": "application/json",
278
+ Authorization: "Bearer " + getIntegrationApiKey()
279
+ }
280
+ });
281
+ if (response.ok) {
282
+ const data = yield response.json();
283
+ const newRefreshToken = data.refresh_token;
284
+ const {
285
+ access_token: accessToken,
286
+ expires_at_seconds: expiresAtSeconds
287
+ } = data.access_token;
288
+ return {
289
+ refreshToken: newRefreshToken,
290
+ accessToken,
291
+ error: "none"
292
+ };
293
+ } else if (response.status === 400) {
294
+ return { error: "unauthorized" };
295
+ } else {
296
+ return { error: "unexpected" };
297
+ }
298
+ });
299
+ }
300
+ function validateAccessTokenOrUndefined(accessToken) {
301
+ return __async(this, null, function* () {
302
+ try {
303
+ return yield validateAccessToken(accessToken);
304
+ } catch (err) {
305
+ if (err instanceof ConfigurationException) {
306
+ throw err;
307
+ } else if (err instanceof UnauthorizedException) {
308
+ return void 0;
309
+ } else {
310
+ console.log("Error validating access token", err);
311
+ return void 0;
312
+ }
313
+ }
314
+ });
315
+ }
316
+ function validateAccessToken(accessToken) {
317
+ return __async(this, null, function* () {
318
+ let publicKey;
319
+ try {
320
+ publicKey = yield jose.importSPKI(getVerifierKey(), "RS256");
321
+ } catch (err) {
322
+ console.error("Verifier key is invalid. Make sure it's specified correctly, including the newlines.", err);
323
+ throw new ConfigurationException("Invalid verifier key");
324
+ }
325
+ if (!accessToken) {
326
+ throw new UnauthorizedException("No access token provided");
327
+ }
328
+ let accessTokenWithoutBearer = accessToken;
329
+ if (accessToken.toLowerCase().startsWith("bearer ")) {
330
+ accessTokenWithoutBearer = accessToken.substring("bearer ".length);
331
+ }
332
+ try {
333
+ const { payload } = yield jose.jwtVerify(accessTokenWithoutBearer, publicKey, {
334
+ issuer: getAuthUrlOrigin(),
335
+ algorithms: ["RS256"]
336
+ });
337
+ return toUser(payload);
338
+ } catch (e) {
339
+ if (e instanceof Error) {
340
+ throw new UnauthorizedException(e.message);
341
+ } else {
342
+ throw new UnauthorizedException("Unable to decode jwt");
343
+ }
344
+ }
345
+ });
346
+ }
347
+
348
+ // src/server/app-router.ts
349
+ function getUserOrRedirect() {
350
+ return __async(this, null, function* () {
351
+ const user = yield getUser();
352
+ if (user) {
353
+ return user;
354
+ } else {
355
+ (0, import_navigation.redirect)(LOGIN_PATH);
356
+ throw new Error("Redirecting to login");
357
+ }
358
+ });
359
+ }
360
+ function getUser() {
361
+ return __async(this, null, function* () {
362
+ var _a;
363
+ const accessToken = (0, import_headers.headers)().get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || ((_a = (0, import_headers.cookies)().get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value);
364
+ if (accessToken) {
365
+ const user = yield validateAccessTokenOrUndefined(accessToken);
366
+ if (user) {
367
+ return user;
368
+ }
369
+ }
370
+ return void 0;
371
+ });
372
+ }
373
+ function authMiddleware(req) {
374
+ return __async(this, null, function* () {
375
+ var _a, _b;
376
+ if (req.headers.has(CUSTOM_HEADER_FOR_ACCESS_TOKEN)) {
377
+ throw new Error(`${CUSTOM_HEADER_FOR_ACCESS_TOKEN} is set which is for internal use only`);
378
+ } else if (req.nextUrl.pathname === CALLBACK_PATH || req.nextUrl.pathname === LOGOUT_PATH) {
379
+ return import_server.NextResponse.next();
380
+ }
381
+ const accessToken = (_a = req.cookies.get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value;
382
+ const refreshToken = (_b = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)) == null ? void 0 : _b.value;
383
+ if (req.nextUrl.pathname === USERINFO_PATH && refreshToken) {
384
+ const response = yield refreshTokenWithAccessAndRefreshToken(refreshToken);
385
+ if (response.error === "unexpected") {
386
+ throw new Error("Unexpected error while refreshing access token");
387
+ } else if (response.error === "unauthorized") {
388
+ const headers2 = new Headers();
389
+ headers2.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
390
+ headers2.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
391
+ return new Response("Unauthorized", { status: 401, headers: headers2 });
392
+ } else {
393
+ const headers2 = new Headers(req.headers);
394
+ headers2.append(CUSTOM_HEADER_FOR_ACCESS_TOKEN, response.accessToken);
395
+ const nextResponse = import_server.NextResponse.next({
396
+ request: {
397
+ headers: headers2
398
+ }
399
+ });
400
+ nextResponse.cookies.set(ACCESS_TOKEN_COOKIE_NAME, response.accessToken, COOKIE_OPTIONS);
401
+ nextResponse.cookies.set(REFRESH_TOKEN_COOKIE_NAME, response.refreshToken, COOKIE_OPTIONS);
402
+ return nextResponse;
403
+ }
404
+ }
405
+ if (accessToken) {
406
+ const user = yield validateAccessTokenOrUndefined(accessToken);
407
+ if (user) {
408
+ return import_server.NextResponse.next();
409
+ }
410
+ }
411
+ if (refreshToken) {
412
+ const response = yield refreshTokenWithAccessAndRefreshToken(refreshToken);
413
+ if (response.error === "unexpected") {
414
+ throw new Error("Unexpected error while refreshing access token");
415
+ } else if (response.error === "unauthorized") {
416
+ const response2 = import_server.NextResponse.next();
417
+ response2.cookies.delete(ACCESS_TOKEN_COOKIE_NAME);
418
+ response2.cookies.delete(REFRESH_TOKEN_COOKIE_NAME);
419
+ return response2;
420
+ } else {
421
+ const headers2 = new Headers(req.headers);
422
+ headers2.append(CUSTOM_HEADER_FOR_ACCESS_TOKEN, response.accessToken);
423
+ const nextResponse = import_server.NextResponse.next({
424
+ request: {
425
+ headers: headers2
426
+ }
427
+ });
428
+ nextResponse.cookies.set(ACCESS_TOKEN_COOKIE_NAME, response.accessToken, COOKIE_OPTIONS);
429
+ nextResponse.cookies.set(REFRESH_TOKEN_COOKIE_NAME, response.refreshToken, COOKIE_OPTIONS);
430
+ return nextResponse;
431
+ }
432
+ }
433
+ return import_server.NextResponse.next();
434
+ });
435
+ }
436
+ function getRouteHandlers(args) {
437
+ const authUrlOrigin = getAuthUrlOrigin();
438
+ const redirectUri = getRedirectUri();
439
+ const integrationApiKey = getIntegrationApiKey();
440
+ function loginGetHandler() {
441
+ const state = randomState();
442
+ const authorize_url = authUrlOrigin + "/propelauth/ssr/authorize?redirect_uri=" + redirectUri + "&state=" + state;
443
+ return new Response(null, {
444
+ status: 302,
445
+ headers: {
446
+ Location: authorize_url,
447
+ "Set-Cookie": `${STATE_COOKIE_NAME}=${state}; Path=/; HttpOnly; Secure; SameSite=Lax`
448
+ }
449
+ });
450
+ }
451
+ function signupGetHandler() {
452
+ const state = randomState();
453
+ const authorize_url = getAuthUrlOrigin() + "/propelauth/ssr/authorize?redirect_uri=" + redirectUri + "&state=" + state + "&signup=true";
454
+ return new Response(null, {
455
+ status: 302,
456
+ headers: {
457
+ Location: authorize_url,
458
+ "Set-Cookie": `${STATE_COOKIE_NAME}=${state}; Path=/; HttpOnly; Secure; SameSite=Lax`
459
+ }
460
+ });
461
+ }
462
+ function callbackGetHandler(req) {
463
+ return __async(this, null, function* () {
464
+ var _a;
465
+ const oauthState = (_a = req.cookies.get(STATE_COOKIE_NAME)) == null ? void 0 : _a.value;
466
+ if (!oauthState || oauthState.length !== 64) {
467
+ console.log("No oauth state found");
468
+ return new Response(null, { status: 302, headers: { Location: LOGIN_PATH } });
469
+ }
470
+ const queryParams = req.nextUrl.searchParams;
471
+ const state = queryParams.get("state");
472
+ const code = queryParams.get("code");
473
+ if (state !== oauthState) {
474
+ console.log("Mismatch between states, redirecting to login");
475
+ return new Response(null, { status: 302, headers: { Location: LOGIN_PATH } });
476
+ }
477
+ const oauth_token_body = {
478
+ redirect_uri: redirectUri,
479
+ code
480
+ };
481
+ const url = `${authUrlOrigin}/propelauth/ssr/token`;
482
+ const response = yield fetch(url, {
483
+ method: "POST",
484
+ body: JSON.stringify(oauth_token_body),
485
+ headers: {
486
+ "Content-Type": "application/json",
487
+ Authorization: "Bearer " + integrationApiKey
488
+ }
489
+ });
490
+ if (response.ok) {
491
+ const data = yield response.json();
492
+ const accessToken = data.access_token;
493
+ const user = yield validateAccessToken(accessToken);
494
+ const path = (args == null ? void 0 : args.postLoginRedirectPathFn) ? args.postLoginRedirectPathFn(user, req) : "/";
495
+ if (!path) {
496
+ console.log("postLoginPathFn returned undefined");
497
+ return new Response("Unexpected error", { status: 500 });
498
+ }
499
+ const headers2 = new Headers();
500
+ headers2.append("Location", path);
501
+ headers2.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=${accessToken}; Path=/; HttpOnly; Secure; SameSite=Lax`);
502
+ headers2.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=${data.refresh_token}; Path=/; HttpOnly; Secure; SameSite=Lax`);
503
+ return new Response(null, {
504
+ status: 302,
505
+ headers: headers2
506
+ });
507
+ } else if (response.status === 401) {
508
+ return new Response("Unexpected error", { status: 500 });
509
+ } else {
510
+ return new Response("Unexpected error", { status: 500 });
511
+ }
512
+ });
513
+ }
514
+ function userinfoGetHandler(req) {
515
+ return __async(this, null, function* () {
516
+ var _a;
517
+ const accessToken = req.headers.get(CUSTOM_HEADER_FOR_ACCESS_TOKEN) || ((_a = req.cookies.get(ACCESS_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value);
518
+ if (accessToken) {
519
+ const path = `${authUrlOrigin}/propelauth/oauth/userinfo`;
520
+ const response = yield fetch(path, {
521
+ headers: {
522
+ "Content-Type": "application/json",
523
+ "Authorization": "Bearer " + accessToken
524
+ }
525
+ });
526
+ if (response.ok) {
527
+ const data = yield response.json();
528
+ const user = new User(
529
+ data.user_id,
530
+ data.email,
531
+ toOrgIdToOrgMemberInfo(data.org_id_to_org_info),
532
+ data.first_name,
533
+ data.last_name,
534
+ data.username,
535
+ data.legacy_user_id,
536
+ data.impersonator_user_id
537
+ );
538
+ return new Response(JSON.stringify(user), {
539
+ status: 200,
540
+ headers: {
541
+ "Content-Type": "application/json"
542
+ }
543
+ });
544
+ } else if (response.status === 401) {
545
+ return new Response(null, { status: 401 });
546
+ } else {
547
+ return new Response(null, { status: 500 });
548
+ }
549
+ }
550
+ return new Response(null, { status: 401 });
551
+ });
552
+ }
553
+ function logoutPostHandler(req) {
554
+ return __async(this, null, function* () {
555
+ var _a;
556
+ const refresh_token = (_a = req.cookies.get(REFRESH_TOKEN_COOKIE_NAME)) == null ? void 0 : _a.value;
557
+ if (!refresh_token) {
558
+ const headers3 = new Headers();
559
+ headers3.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
560
+ headers3.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
561
+ return new Response(null, { status: 200, headers: headers3 });
562
+ }
563
+ const logoutBody = { refresh_token };
564
+ const url = `${authUrlOrigin}/api/backend/v1/logout`;
565
+ const response = yield fetch(url, {
566
+ method: "POST",
567
+ body: JSON.stringify(logoutBody),
568
+ headers: {
569
+ "Content-Type": "application/json",
570
+ Authorization: "Bearer " + integrationApiKey
571
+ }
572
+ });
573
+ if (!response.ok) {
574
+ console.log(
575
+ "Unable to logout, clearing cookies and continuing anyway",
576
+ response.status,
577
+ response.statusText
578
+ );
579
+ }
580
+ const headers2 = new Headers();
581
+ headers2.append("Set-Cookie", `${ACCESS_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
582
+ headers2.append("Set-Cookie", `${REFRESH_TOKEN_COOKIE_NAME}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`);
583
+ return new Response(null, { status: 200, headers: headers2 });
584
+ });
585
+ }
586
+ function getRouteHandler(req, { params }) {
587
+ if (params.slug === "login") {
588
+ return loginGetHandler();
589
+ } else if (params.slug === "signup") {
590
+ return signupGetHandler();
591
+ } else if (params.slug === "callback") {
592
+ return callbackGetHandler(req);
593
+ } else if (params.slug === "userinfo") {
594
+ return userinfoGetHandler(req);
595
+ } else {
596
+ return new Response("", { status: 404 });
597
+ }
598
+ }
599
+ function postRouteHandler(req, { params }) {
600
+ if (params.slug === "logout") {
601
+ return logoutPostHandler(req);
602
+ } else {
603
+ return new Response("", { status: 404 });
604
+ }
605
+ }
606
+ return {
607
+ getRouteHandler,
608
+ postRouteHandler
609
+ };
610
+ }
611
+ function randomState() {
612
+ const randomBytes = crypto.getRandomValues(new Uint8Array(32));
613
+ return Array.from(randomBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
614
+ }
615
+ // Annotate the CommonJS export names for ESM import in node:
616
+ 0 && (module.exports = {
617
+ ConfigurationException,
618
+ UnauthorizedException,
619
+ authMiddleware,
620
+ getRouteHandlers,
621
+ getUser,
622
+ getUserOrRedirect
623
+ });
624
+ //# sourceMappingURL=index.js.map