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