@witchcraft/nuxt-auth 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +693 -0
  2. package/dist/module.d.mts +170 -0
  3. package/dist/module.json +9 -0
  4. package/dist/module.mjs +146 -0
  5. package/dist/runtime/build/genAuthSecretKeys.d.ts +6 -0
  6. package/dist/runtime/build/genAuthSecretKeys.js +10 -0
  7. package/dist/runtime/components/ExternalCallback.d.vue.ts +7 -0
  8. package/dist/runtime/components/ExternalCallback.vue +96 -0
  9. package/dist/runtime/components/ExternalCallback.vue.d.ts +7 -0
  10. package/dist/runtime/components/ExternalCode.d.vue.ts +11 -0
  11. package/dist/runtime/components/ExternalCode.vue +77 -0
  12. package/dist/runtime/components/ExternalCode.vue.d.ts +11 -0
  13. package/dist/runtime/components/LoginProviderButtons.client.d.vue.ts +15 -0
  14. package/dist/runtime/components/LoginProviderButtons.client.vue +66 -0
  15. package/dist/runtime/components/LoginProviderButtons.client.vue.d.ts +15 -0
  16. package/dist/runtime/components/Mocker.d.vue.ts +2 -0
  17. package/dist/runtime/components/Mocker.vue +39 -0
  18. package/dist/runtime/components/Mocker.vue.d.ts +2 -0
  19. package/dist/runtime/components/SessionStatus.d.vue.ts +35 -0
  20. package/dist/runtime/components/SessionStatus.vue +85 -0
  21. package/dist/runtime/components/SessionStatus.vue.d.ts +35 -0
  22. package/dist/runtime/components/UserRegistration.d.vue.ts +35 -0
  23. package/dist/runtime/components/UserRegistration.vue +158 -0
  24. package/dist/runtime/components/UserRegistration.vue.d.ts +35 -0
  25. package/dist/runtime/composables/useAuth.d.ts +27 -0
  26. package/dist/runtime/composables/useAuth.js +73 -0
  27. package/dist/runtime/core/providerStyles.d.ts +2 -0
  28. package/dist/runtime/core/providerStyles.js +6 -0
  29. package/dist/runtime/core/providers/github.d.ts +89 -0
  30. package/dist/runtime/core/providers/github.js +60 -0
  31. package/dist/runtime/core/providers/google.d.ts +70 -0
  32. package/dist/runtime/core/providers/google.js +54 -0
  33. package/dist/runtime/middleware/authGlobal.d.ts +2 -0
  34. package/dist/runtime/middleware/authGlobal.js +34 -0
  35. package/dist/runtime/middleware/authProtected.d.ts +2 -0
  36. package/dist/runtime/middleware/authProtected.js +38 -0
  37. package/dist/runtime/server/helpers/getSafeSecretsInfo.d.ts +4 -0
  38. package/dist/runtime/server/helpers/getSafeSecretsInfo.js +10 -0
  39. package/dist/runtime/server/helpers/logSafeRoute.d.ts +1 -0
  40. package/dist/runtime/server/helpers/logSafeRoute.js +3 -0
  41. package/dist/runtime/server/helpers/signJwt.d.ts +5 -0
  42. package/dist/runtime/server/helpers/signJwt.js +16 -0
  43. package/dist/runtime/server/helpers/verifyJwt.d.ts +5 -0
  44. package/dist/runtime/server/helpers/verifyJwt.js +19 -0
  45. package/dist/runtime/server/tsconfig.json +3 -0
  46. package/dist/runtime/server/utils/Auth.d.ts +83 -0
  47. package/dist/runtime/server/utils/Auth.js +653 -0
  48. package/dist/runtime/server/utils/SessionManager.d.ts +25 -0
  49. package/dist/runtime/server/utils/SessionManager.js +93 -0
  50. package/dist/runtime/server/utils/createAuthHandler.d.ts +8 -0
  51. package/dist/runtime/server/utils/createAuthHandler.js +29 -0
  52. package/dist/runtime/server/utils/createAuthMiddleware.d.ts +10 -0
  53. package/dist/runtime/server/utils/createAuthMiddleware.js +28 -0
  54. package/dist/runtime/server/utils/createAuthSchema.d.ts +244 -0
  55. package/dist/runtime/server/utils/createAuthSchema.js +43 -0
  56. package/dist/runtime/types.d.ts +239 -0
  57. package/dist/runtime/types.js +15 -0
  58. package/dist/runtime/utils/createExternalAuthHandler.d.ts +36 -0
  59. package/dist/runtime/utils/createExternalAuthHandler.js +25 -0
  60. package/dist/runtime/utils/decodeQueryUri.d.ts +2 -0
  61. package/dist/runtime/utils/decodeQueryUri.js +4 -0
  62. package/dist/runtime/utils/getAuthApiRoute.d.ts +3 -0
  63. package/dist/runtime/utils/getAuthApiRoute.js +14 -0
  64. package/dist/types.d.mts +13 -0
  65. package/package.json +101 -0
@@ -0,0 +1,653 @@
1
+ import { capitalize } from "@alanscodelog/utils/capitalize";
2
+ import { unreachable } from "@alanscodelog/utils/unreachable";
3
+ import { generateState } from "arctic";
4
+ import { and, eq } from "drizzle-orm";
5
+ import {
6
+ defineEventHandler,
7
+ deleteCookie,
8
+ getCookie,
9
+ getQuery,
10
+ getRequestHeader,
11
+ getValidatedQuery,
12
+ sendRedirect,
13
+ setCookie,
14
+ useBase
15
+ } from "h3";
16
+ import { z } from "zod";
17
+ import { createError, useRuntimeConfig } from "#imports";
18
+ import { AUTH_ERROR } from "../../types.js";
19
+ import { getAuthApiRoute } from "../../utils/getAuthApiRoute.js";
20
+ import { getSafeSecretsInfo } from "../helpers/getSafeSecretsInfo.js";
21
+ import { logSafeRoute } from "../helpers/logSafeRoute.js";
22
+ import { signJwt } from "../helpers/signJwt.js";
23
+ import { verifyJwt as jwtVerify } from "../helpers/verifyJwt.js";
24
+ export const zState = z.object({
25
+ oauthState: z.string(),
26
+ additionalState: z.any(),
27
+ deeplink: z.string().optional()
28
+ });
29
+ const zLoginQuery = z.object({
30
+ devBypass: z.enum(["true", "false"]).optional(),
31
+ deeplink: z.string().optional()
32
+ });
33
+ export const oauth2CallbackQuery = z.object({
34
+ code: z.string(),
35
+ state: z.string()
36
+ });
37
+ export class Auth {
38
+ validRoutes = [];
39
+ providers;
40
+ handlers;
41
+ externalAccessTokenExpiresIn = "10m";
42
+ deeplinkSchemes;
43
+ onRegister;
44
+ eventHandler;
45
+ getAdditionalState;
46
+ modifyCallbackRedirect;
47
+ devBypassAuth;
48
+ createMockUser;
49
+ generateUser;
50
+ static defaultCreateMockUser(_username, id, provider) {
51
+ if (!id && !_username) throw new Error("Either id or username must be provided");
52
+ const username = _username ?? `username-${id}`;
53
+ return {
54
+ provider,
55
+ providerId: `dev-${provider}-${username}`,
56
+ email: `dev-${provider}-${username}@dev.com`,
57
+ isVerified: true,
58
+ name: `Dev ${username}`,
59
+ info: null
60
+ };
61
+ }
62
+ db;
63
+ usersTable;
64
+ authAccountsTable;
65
+ sessionManager;
66
+ router;
67
+ logger;
68
+ rc;
69
+ providerCookieOpts;
70
+ constructor(runtimeConfig, db, usersTable, authAccountsTable, sessionManager, router, opts, env, logger) {
71
+ this.rc = runtimeConfig;
72
+ this.providerCookieOpts = {
73
+ secure: this.rc.public.auth.isSecure,
74
+ ...this.rc.public.auth.providerCookieOpts
75
+ };
76
+ this.logger = logger ?? console;
77
+ this.db = db;
78
+ this.usersTable = usersTable;
79
+ this.authAccountsTable = authAccountsTable;
80
+ this.sessionManager = sessionManager;
81
+ this.router = router;
82
+ this.onRegister = opts.onRegister;
83
+ if (opts.additionalState) {
84
+ this.getAdditionalState = opts.additionalState;
85
+ }
86
+ if (opts.devBypassAuth) this.devBypassAuth = opts.devBypassAuth && import.meta.dev;
87
+ this.generateUser = opts.generateUser;
88
+ this.createMockUser = opts.createMockUser ?? Auth.defaultCreateMockUser;
89
+ this.modifyCallbackRedirect = opts.modifyCallbackRedirect;
90
+ this.deeplinkSchemes = opts.deeplinkSchemes ?? {};
91
+ for (const val of Object.values(this.deeplinkSchemes)) {
92
+ if (!val.endsWith(":")) {
93
+ throw createError({
94
+ status: 500,
95
+ statusMessage: "Invalid deeplink scheme. Scheme protocol should end with a colon.",
96
+ data: { code: AUTH_ERROR.INVALID_DEEPLINK }
97
+ });
98
+ }
99
+ }
100
+ const {
101
+ appUrl,
102
+ handlers,
103
+ providerOptions,
104
+ enabledProviders
105
+ } = {
106
+ ...opts
107
+ };
108
+ if (appUrl === void 0) {
109
+ throw createError({
110
+ status: 500,
111
+ statusMessage: "No appUrl defined."
112
+ });
113
+ }
114
+ this.handlers = handlers;
115
+ this.providers = {};
116
+ for (const provider of enabledProviders) {
117
+ const capitalized = capitalize(provider);
118
+ const clientId = env[`auth${capitalized}ClientId`];
119
+ const clientSecret = env[`auth${capitalized}ClientSecret`];
120
+ if (!clientId || !clientSecret) {
121
+ this.logger.warn({
122
+ ns: "auth:init:missingSecrets",
123
+ env,
124
+ error: `Missing auth${capitalized}ClientId or auth${capitalized}ClientSecret for ${capitalized}. Disabling.`
125
+ });
126
+ continue;
127
+ }
128
+ const options = providerOptions?.[provider];
129
+ const redirectUri = appUrl + getAuthApiRoute(useRuntimeConfig().public, "callback", { provider: provider.toLowerCase() });
130
+ const providerClass = this.handlers[provider];
131
+ if (!providerClass) {
132
+ this.logger.error({
133
+ ns: "auth:init",
134
+ provider
135
+ });
136
+ throw createError({
137
+ status: 500,
138
+ statusMessage: `Unknown provider: ${provider}`,
139
+ data: { code: AUTH_ERROR.UNKNOWN_PROVIDER }
140
+ });
141
+ }
142
+ this.providers[provider] = new providerClass({ clientId, clientSecret, redirectUri }, options);
143
+ }
144
+ this.logger.info({
145
+ ns: "auth:init",
146
+ enabledProviders,
147
+ registeredProviders: Object.keys(this.providers),
148
+ appUrl,
149
+ isSecure: useRuntimeConfig().public.auth.isSecure,
150
+ ...getSafeSecretsInfo()
151
+ });
152
+ const apiRoutes = this.rc.public.auth.authApiRoutes;
153
+ const authRoutes = this.rc.public.auth.authRoutes;
154
+ router.get(apiRoutes.usersInfo, defineEventHandler((event) => {
155
+ const user = event.context.user;
156
+ const id = getCookie(event, "userId");
157
+ this.logger.debug({
158
+ ns: "auth:users/info",
159
+ userExists: !!user,
160
+ redact: { user, id, authSession: getCookie(event, "authSession") }
161
+ });
162
+ return user ?? false;
163
+ }));
164
+ router.get(apiRoutes.externalExchange, defineEventHandler(async (event) => {
165
+ const accessToken = getRequestHeader(event, "Authorization")?.slice("Bearer ".length);
166
+ const decoded = await this.verifyAccessToken(accessToken).catch((err) => createError({
167
+ status: 400,
168
+ statusMessage: err.message,
169
+ data: { code: AUTH_ERROR.INVALID_ACCESS_TOKEN }
170
+ }));
171
+ if (decoded instanceof Error) throw decoded;
172
+ const res = await this.createSession(event, decoded.userId);
173
+ this.logger.debug({
174
+ ns: "auth:callback:createdSession",
175
+ redact: { res, decoded }
176
+ });
177
+ return { token: res.token };
178
+ }));
179
+ router.get(apiRoutes.usersIdAccounts, defineEventHandler(async (event) => {
180
+ const id = event.context.user?.id;
181
+ Auth.assertAuthorizedUserAndId(event.context.user, id);
182
+ this.logger.trace({
183
+ ns: "auth:users/:id/account"
184
+ });
185
+ const accounts = await this.db.select().from(this.authAccountsTable).where(and(
186
+ eq(this.authAccountsTable.userId, id)
187
+ ));
188
+ return accounts;
189
+ }));
190
+ router.post(apiRoutes.logout, defineEventHandler(async (event) => {
191
+ this.logger.trace({
192
+ ns: "auth:users/logout",
193
+ session: event.context.session !== void 0
194
+ });
195
+ if (!event.context.session) {
196
+ throw createError({
197
+ statusCode: 403,
198
+ statusMessage: "Not logged in."
199
+ });
200
+ }
201
+ await this.sessionManager.invalidateSession(event.context.session.id);
202
+ const emptyCookie = this.sessionManager.createBlankSessionCookie();
203
+ deleteCookie(event, `userId`, emptyCookie.attributes);
204
+ deleteCookie(event, emptyCookie.name, emptyCookie.attributes);
205
+ return true;
206
+ }));
207
+ router.get(apiRoutes.login, defineEventHandler(async (event) => {
208
+ const providerName = event.context.params.provider;
209
+ this.assertValidProvider(providerName);
210
+ const query = zLoginQuery.parse(getQuery(event));
211
+ const devBypassAuth = query.devBypass === "true" && this.devBypassAuth === true;
212
+ const deeplink = query.deeplink;
213
+ if (devBypassAuth) {
214
+ return sendRedirect(event, `${authRoutes.mockAuth}?provider=${providerName}${deeplink ? `&deeplink=${deeplink}` : ""}`);
215
+ }
216
+ const state = {
217
+ oauthState: generateState(),
218
+ additionalState: this.getAdditionalState?.(event),
219
+ deeplink: typeof deeplink === "string" ? deeplink : void 0
220
+ };
221
+ const encodedState = this.encodeState(state);
222
+ const info = this.getProvider(providerName).getLoginInfo(encodedState);
223
+ this.logger.debug({
224
+ ns: "auth:login",
225
+ provider: providerName,
226
+ redact: {
227
+ url: info.url.toString(),
228
+ state,
229
+ encodedState,
230
+ codeVerifier: "codeVerifier" in info && info.codeVerifier,
231
+ deeplink
232
+ }
233
+ });
234
+ try {
235
+ if (info.type === "oauth2" || info.type === "oauth2_pcke") {
236
+ setCookie(event, `${providerName}_oauth_state`, state.oauthState, this.providerCookieOpts);
237
+ }
238
+ if (info.type === "oauth2_pcke") {
239
+ setCookie(event, `${providerName}_oauth_code_verifier`, info.codeVerifier, this.providerCookieOpts);
240
+ }
241
+ } catch (e) {
242
+ this.logger.error({
243
+ ns: "auth:login:setCookieError",
244
+ error: e instanceof Error ? e.message : "Not an error type.",
245
+ redact: {
246
+ error: e,
247
+ oauth2: [event, `${providerName}_oauth_state`, state.oauthState, this.providerCookieOpts],
248
+ oauth2_pcke: [event, `_oauth_code_verifier ${providerName}`, info.type === "oauth2_pcke" ? info.codeVerifier : void 0, this.providerCookieOpts]
249
+ }
250
+ });
251
+ }
252
+ return sendRedirect(event, info.url.toString());
253
+ }));
254
+ router.get(apiRoutes.callback, defineEventHandler(async (event) => {
255
+ const providerName = event.context.params.provider;
256
+ this.assertValidProvider(providerName);
257
+ const provider = this.getProvider(providerName);
258
+ if (!this.rc.public.auth.authRoutes.login) {
259
+ throw createError({
260
+ status: 500,
261
+ statusMessage: "No login route defined.",
262
+ data: { code: AUTH_ERROR.INTERNAL_ERROR }
263
+ });
264
+ }
265
+ const redirectToLogin = { redirect: this.rc.public.auth.authRoutes.login };
266
+ const query = getQuery(event);
267
+ const devBypassAuth = this.devBypassAuth && query.devBypass === "true";
268
+ const bypassDeeplink = devBypassAuth ? query.deeplink : void 0;
269
+ const bypassUser = devBypassAuth ? query.username : void 0;
270
+ const bypassId = devBypassAuth ? query.id : void 0;
271
+ let bypassRegistration = devBypassAuth ? query.devBypassRegistration === "true" : false;
272
+ const res = devBypassAuth ? { tokens: void 0, additionalState: void 0, deeplink: bypassDeeplink } : provider.type === "oauth2" ? await this.handleOAuth2(event, provider, redirectToLogin) : await this.handleOAuth2Pcke(event, provider, redirectToLogin);
273
+ const { tokens, additionalState, deeplink } = res;
274
+ const mockUser = devBypassAuth ? {
275
+ ...Auth.defaultCreateMockUser(bypassUser, bypassId, providerName),
276
+ ...await this.createMockUser(bypassUser, bypassId, providerName) ?? {}
277
+ } : void 0;
278
+ const userInfo = devBypassAuth ? mockUser : await provider.getAccountInfo(tokens).catch((e) => {
279
+ this.logger.error({
280
+ ns: "auth:callback:getUserInfoError",
281
+ redact: {
282
+ error: e
283
+ },
284
+ error: e.message
285
+ });
286
+ throw createError({
287
+ status: 400,
288
+ statusMessage: "Error fetching provider user info.",
289
+ data: { ...redirectToLogin }
290
+ });
291
+ });
292
+ if (!userInfo) unreachable();
293
+ const existingProviderAccount = (await this.db.select({
294
+ id: this.authAccountsTable.userId
295
+ }).from(this.authAccountsTable).where(
296
+ and(
297
+ eq(this.authAccountsTable.provider, provider.name),
298
+ eq(this.authAccountsTable.providerId, userInfo.providerId)
299
+ )
300
+ ))[0];
301
+ const existingUserAccount = (await this.db.select({
302
+ id: this.usersTable.id,
303
+ isRegistered: this.usersTable.isRegistered
304
+ }).from(this.usersTable).where(
305
+ eq(this.usersTable.email, userInfo.email)
306
+ ))[0];
307
+ const isRegistered = existingUserAccount?.isRegistered ?? false;
308
+ bypassRegistration = bypassRegistration ? true : isRegistered;
309
+ let sessionUserId = existingProviderAccount?.id ?? existingUserAccount?.id;
310
+ this.logger.debug({
311
+ ns: "auth:callback",
312
+ provider: providerName,
313
+ redact: {
314
+ userInfo,
315
+ existingProviderAccount: !!existingProviderAccount,
316
+ existingUserAccount: !!existingUserAccount,
317
+ isRegistered,
318
+ sessionUserId,
319
+ additionalState,
320
+ deeplink,
321
+ tokens,
322
+ devBypassAuth,
323
+ bypassDeeplink,
324
+ bypassUser,
325
+ bypassRegistration
326
+ }
327
+ });
328
+ if (event.context.user && existingProviderAccount) {
329
+ this.logger.debug({
330
+ ns: "auth:callback:existingProviderAccount"
331
+ });
332
+ return this.createRedirect(
333
+ event,
334
+ sessionUserId,
335
+ isRegistered,
336
+ additionalState,
337
+ deeplink
338
+ );
339
+ }
340
+ if (existingProviderAccount) {
341
+ this.logger.debug({
342
+ ns: "auth:callback:existingUser:existingAccount"
343
+ });
344
+ } else if (existingUserAccount) {
345
+ this.logger.debug({
346
+ ns: "auth:callback:existingUser:newProvider",
347
+ isRegistered
348
+ });
349
+ await this.db.insert(this.authAccountsTable).values({
350
+ userId: sessionUserId,
351
+ ...userInfo,
352
+ ...isRegistered ? {} : { info: userInfo.info }
353
+ }).catch((e) => {
354
+ const data = { ...redirectToLogin, code: AUTH_ERROR.FAILED_TO_ADD_PROVIDER_ACCOUNT };
355
+ logger.error({
356
+ ns: "auth:callback:existingUser:newProvider:failed",
357
+ error: e instanceof Error ? e.message : e,
358
+ data
359
+ });
360
+ throw createError({
361
+ statusMessage: `Failed to add provider account ${provider.name}`,
362
+ status: 500,
363
+ data
364
+ });
365
+ });
366
+ } else {
367
+ this.logger.debug({
368
+ ns: "auth:callback:newUser",
369
+ existingUserAccount,
370
+ existingProviderAccount
371
+ });
372
+ const userId = await this.db.transaction(async (tx) => {
373
+ const userId2 = (await tx.insert(this.usersTable).values({
374
+ ...this.generateUser?.() ?? {},
375
+ email: userInfo.email,
376
+ isRegistered: bypassRegistration,
377
+ ...bypassRegistration ? { username: bypassUser } : {}
378
+ }).returning({ userId: this.usersTable.id }))[0]?.userId;
379
+ if (!userId2) {
380
+ tx.rollback();
381
+ return;
382
+ }
383
+ await tx.insert(this.authAccountsTable).values({
384
+ userId: userId2,
385
+ ...userInfo
386
+ });
387
+ return userId2;
388
+ });
389
+ if (!userId) {
390
+ this.logger.error({
391
+ ns: "auth:callback:newUser:failed"
392
+ });
393
+ throw createError({
394
+ statusMessage: "Failed to create user.",
395
+ status: 500,
396
+ data: { ...redirectToLogin, code: AUTH_ERROR.FAILED_TO_CREATE_USER }
397
+ });
398
+ }
399
+ sessionUserId = userId;
400
+ }
401
+ if (!sessionUserId || typeof sessionUserId !== "string") unreachable();
402
+ await this.createSession(event, sessionUserId);
403
+ return this.createRedirect(
404
+ event,
405
+ sessionUserId,
406
+ bypassRegistration ?? isRegistered,
407
+ additionalState,
408
+ deeplink
409
+ );
410
+ }));
411
+ router.post(apiRoutes.register, defineEventHandler(async (event) => {
412
+ if (!this.onRegister) {
413
+ throw createError({ status: 500, statusMessage: "No onRegister handler." });
414
+ }
415
+ Auth.assertAuthorizedUser(event.context.user);
416
+ if (event.context.user?.isRegistered) {
417
+ throw createError({
418
+ status: 400,
419
+ statusMessage: "User is already registered.",
420
+ data: { code: AUTH_ERROR.USER_ALREADY_REGISTERED }
421
+ });
422
+ }
423
+ let deeplink = getQuery(event).deeplink;
424
+ deeplink = typeof deeplink === "string" ? deeplink : void 0;
425
+ const route = deeplink ? this.rc.public.auth.authRoutes.externalCode : this.rc.public.auth.authRoutes.postRegisteredLogin;
426
+ if (!route) {
427
+ throw createError({
428
+ status: 500,
429
+ statusMessage: "No postRegisteredLogin/externalCode route defined.",
430
+ data: { code: AUTH_ERROR.INTERNAL_ERROR }
431
+ });
432
+ }
433
+ const res = await this.onRegister(event, route, deeplink);
434
+ if (res === void 0 || !res) {
435
+ return {
436
+ redirectUrl: this.getRedirect(route, true, deeplink, await this.createAccessToken(event.context.user.id))
437
+ };
438
+ } else {
439
+ return res;
440
+ }
441
+ }));
442
+ opts.extendRouter?.(router);
443
+ this.logger.debug({
444
+ ns: "auth:routes",
445
+ apiRoutes
446
+ });
447
+ if (import.meta.dev) {
448
+ router.get("/test", defineEventHandler(async (_event) => "Dev Only Route: Api router working."));
449
+ }
450
+ this.eventHandler = useBase(apiRoutes.base, (event) => {
451
+ const routePath = event.context.params?._;
452
+ this.logger.debug({
453
+ ns: "auth:route",
454
+ route: routePath && logSafeRoute(routePath)
455
+ });
456
+ return router.handler(event);
457
+ });
458
+ }
459
+ assertValidProvider(provider) {
460
+ if (!provider || this.providers[provider] === void 0) {
461
+ this.logger.error({
462
+ ns: "auth:assertValidProvider",
463
+ provider
464
+ });
465
+ throw createError({
466
+ status: 400,
467
+ statusMessage: `Invalid provider: ${provider}, known: ${Object.keys(this.providers).join(", ")}`,
468
+ data: { code: AUTH_ERROR.UNKNOWN_PROVIDER }
469
+ });
470
+ }
471
+ }
472
+ getProvider(provider) {
473
+ return this.providers[provider];
474
+ }
475
+ static assertAuthorizedUser(user) {
476
+ if (!user) {
477
+ throw createError({
478
+ statusCode: 401,
479
+ statusMessage: "Unauthorized"
480
+ });
481
+ }
482
+ }
483
+ static assertEventWithAuthorizedUser(event) {
484
+ const user = event.context.user;
485
+ if (!user) {
486
+ throw createError({
487
+ statusCode: 401,
488
+ statusMessage: "Unauthorized"
489
+ });
490
+ }
491
+ }
492
+ static assertAuthorizedUserAndId(user, id) {
493
+ if (!user || (!id || id !== user?.id)) {
494
+ throw createError({
495
+ statusCode: 401,
496
+ statusMessage: "Unauthorized"
497
+ });
498
+ }
499
+ }
500
+ encodeState(state) {
501
+ return encodeURIComponent(JSON.stringify(state));
502
+ }
503
+ decodeState(state) {
504
+ try {
505
+ return zState.parse(JSON.parse(decodeURIComponent(state)));
506
+ } catch (e) {
507
+ this.logger.error({
508
+ ns: "auth:decodeState",
509
+ redact: {
510
+ state,
511
+ error: e
512
+ }
513
+ });
514
+ throw createError({
515
+ status: 500,
516
+ statusMessage: "Failed to decode state.",
517
+ data: { code: AUTH_ERROR.INTERNAL_ERROR }
518
+ });
519
+ }
520
+ }
521
+ async handleOAuth2(event, provider, redirectToLogin) {
522
+ const query = await getValidatedQuery(event, oauth2CallbackQuery.parse);
523
+ const state = this.decodeState(query.state);
524
+ const storedState = getCookie(event, `${provider.name}_oauth_state`);
525
+ const valid = !!storedState && state.oauthState === storedState;
526
+ const tokens = valid && await provider.provider.validateAuthorizationCode(query.code).catch((e) => e);
527
+ await this.handleMaybeTokenError(valid, tokens, redirectToLogin);
528
+ return {
529
+ tokens,
530
+ additionalState: state.additionalState,
531
+ deeplink: state.deeplink
532
+ };
533
+ }
534
+ async handleOAuth2Pcke(event, provider, redirectToLogin) {
535
+ const query = await getValidatedQuery(event, oauth2CallbackQuery.parse);
536
+ const state = this.decodeState(query.state);
537
+ const storedState = getCookie(event, `${provider.name}_oauth_state`);
538
+ const storedCodeVerifier = getCookie(event, `${provider.name}_oauth_code_verifier`);
539
+ const valid = !!query.code && !!storedState && !!storedCodeVerifier && state.oauthState === storedState;
540
+ const tokens = valid && await provider.provider.validateAuthorizationCode(query.code, storedCodeVerifier).catch((e) => e);
541
+ await this.handleMaybeTokenError(valid, tokens, redirectToLogin);
542
+ return {
543
+ tokens,
544
+ additionalState: state.additionalState,
545
+ deeplink: state.deeplink
546
+ };
547
+ }
548
+ async handleMaybeTokenError(valid, tokens, redirectToLogin = {}) {
549
+ if (!valid || typeof tokens !== "object") {
550
+ this.logger.error({
551
+ ns: "auth:callback:oauth2RequestError",
552
+ redact: {
553
+ tokens,
554
+ valid
555
+ }
556
+ });
557
+ throw createError({
558
+ status: 400,
559
+ statusMessage: "Invalid auth callback.",
560
+ data: { ...redirectToLogin, code: AUTH_ERROR.INVALID_AUTH_CALLBACK }
561
+ });
562
+ }
563
+ }
564
+ async createSession(event, sessionUserId) {
565
+ const token = this.sessionManager.generateSessionToken();
566
+ const session = await this.sessionManager.createSession(token, sessionUserId);
567
+ const sessionCookie = this.sessionManager.createSessionCookie(token);
568
+ this.logger.debug({
569
+ ns: "auth:createSession",
570
+ redact: {
571
+ sessionCookie,
572
+ sessionUserId
573
+ }
574
+ });
575
+ setCookie(event, sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
576
+ setCookie(event, `userId`, sessionUserId, sessionCookie.attributes);
577
+ return { session, token };
578
+ }
579
+ async createRedirect(event, userId, isRegistered, additionalState, deeplink) {
580
+ let redirect = isRegistered ? this.rc.public.auth.authRoutes.postRegisteredLogin : this.rc.public.auth.authRoutes.register;
581
+ if (!redirect) {
582
+ throw createError({
583
+ status: 500,
584
+ statusMessage: "No register/postRegisteredLogin route defined.",
585
+ data: { code: AUTH_ERROR.INTERNAL_ERROR }
586
+ });
587
+ }
588
+ const modified = this.modifyCallbackRedirect?.(
589
+ event,
590
+ redirect,
591
+ userId,
592
+ isRegistered,
593
+ additionalState,
594
+ deeplink
595
+ );
596
+ redirect = modified ?? redirect;
597
+ if (!modified) {
598
+ redirect = this.getRedirect(
599
+ redirect,
600
+ isRegistered,
601
+ deeplink,
602
+ await this.createAccessToken(userId)
603
+ );
604
+ }
605
+ this.logger.debug({
606
+ ns: "auth:callback:createdSessionAndRedirecting",
607
+ modified,
608
+ deeplink,
609
+ redirect,
610
+ isRegistered,
611
+ redact: { additionalState }
612
+ });
613
+ return sendRedirect(event, redirect);
614
+ }
615
+ getRedirect(route, isRegistered, deeplink, accessToken) {
616
+ if (!deeplink) return route;
617
+ if (!isRegistered) {
618
+ return `${route}?${new URLSearchParams({ deeplink }).toString()}`;
619
+ }
620
+ const deeplinkUri = `${this.getDeeplinkScheme(deeplink)}?${new URLSearchParams({
621
+ access_token: accessToken
622
+ })}`;
623
+ return `${this.rc.public.auth.authRoutes.externalCode}?${new URLSearchParams({
624
+ access_token: accessToken,
625
+ deeplinkUri
626
+ }).toString()}`;
627
+ }
628
+ getDeeplinkScheme(deeplink) {
629
+ const scheme = this.deeplinkSchemes[deeplink];
630
+ if (!scheme) {
631
+ throw createError({
632
+ status: 500,
633
+ statusMessage: `Invalid deeplink ${deeplink}. Please specify the "deeplinkSchemes" option when creating the auth handler.`,
634
+ data: { code: AUTH_ERROR.INVALID_DEEPLINK }
635
+ });
636
+ }
637
+ return `${scheme}${this.rc.public.auth.authRoutes.deeplink}`;
638
+ }
639
+ async verifyAccessToken(accessToken) {
640
+ return jwtVerify(accessToken, this.rc.authSecret, {}).catch((err) => {
641
+ throw createError({
642
+ status: 400,
643
+ statusMessage: err.message,
644
+ data: { code: AUTH_ERROR.INVALID_ACCESS_TOKEN }
645
+ });
646
+ });
647
+ }
648
+ async createAccessToken(userId, payload = {}) {
649
+ return signJwt({ ...payload, userId }, this.rc.authSecret, {
650
+ expiresIn: this.externalAccessTokenExpiresIn
651
+ });
652
+ }
653
+ }
@@ -0,0 +1,25 @@
1
+ import type { DeepPartial } from "@alanscodelog/utils";
2
+ import type { PgDatabase } from "drizzle-orm/pg-core";
3
+ import type { RuntimeConfig } from "nuxt/schema";
4
+ import type { AuthSessionsTable, AuthUsersTable } from "./createAuthSchema.js.js";
5
+ import type { AuthSession, SessionCookie, SessionCookieOptions, SessionValidationResult } from "../../types.js.js";
6
+ export declare const defaultSessionCookieName = "authSession";
7
+ export declare class SessionManager {
8
+ options: {
9
+ expiresAt: number;
10
+ sessionCookie: {
11
+ name: string;
12
+ attributes: Omit<SessionCookieOptions, "maxAge">;
13
+ };
14
+ };
15
+ db: PgDatabase<any, any, any>;
16
+ sessionTable: AuthSessionsTable;
17
+ userTable: AuthUsersTable;
18
+ constructor(rc: RuntimeConfig, db: SessionManager["db"], sessionTable: SessionManager["sessionTable"], userTable: SessionManager["userTable"], options?: DeepPartial<SessionManager["options"]>);
19
+ generateSessionToken(): string;
20
+ createSession<TId = string>(token: string, userId: TId): Promise<AuthSession>;
21
+ createSessionCookie(sessionId: string): SessionCookie;
22
+ createBlankSessionCookie(): SessionCookie;
23
+ validateSessionToken(token: string): Promise<SessionValidationResult>;
24
+ invalidateSession(sessionId: string): Promise<void>;
25
+ }