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