@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,93 @@
1
+ import { sha256 } from "@oslojs/crypto/sha2";
2
+ import { encodeBase32LowerCaseNoPadding, encodeHexLowerCase } from "@oslojs/encoding";
3
+ import { eq } from "drizzle-orm";
4
+ export const defaultSessionCookieName = "authSession";
5
+ export class SessionManager {
6
+ options;
7
+ db;
8
+ sessionTable;
9
+ userTable;
10
+ constructor(rc, db, sessionTable, userTable, options = {}) {
11
+ this.db = db;
12
+ this.sessionTable = sessionTable;
13
+ this.userTable = userTable;
14
+ this.options = {
15
+ expiresAt: rc.public.auth.sessionExpiresAt,
16
+ ...options,
17
+ sessionCookie: {
18
+ name: defaultSessionCookieName,
19
+ ...options.sessionCookie,
20
+ attributes: {
21
+ secure: rc.public.auth.isSecure,
22
+ ...rc.public.auth.sessionCookieOpts ?? {},
23
+ ...options.sessionCookie?.attributes
24
+ }
25
+ }
26
+ };
27
+ }
28
+ generateSessionToken() {
29
+ const bytes = new Uint8Array(20);
30
+ crypto.getRandomValues(bytes);
31
+ const token = encodeBase32LowerCaseNoPadding(bytes);
32
+ return token;
33
+ }
34
+ async createSession(token, userId) {
35
+ const hashedSessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
36
+ const session = {
37
+ id: hashedSessionId,
38
+ userId,
39
+ expiresAt: new Date(Date.now() + this.options.expiresAt)
40
+ };
41
+ await this.db.insert(this.sessionTable).values(session);
42
+ return session;
43
+ }
44
+ createSessionCookie(sessionId) {
45
+ return {
46
+ name: this.options.sessionCookie.name,
47
+ value: sessionId,
48
+ attributes: {
49
+ ...this.options.sessionCookie.attributes,
50
+ maxAge: (/* @__PURE__ */ new Date()).getTime() + this.options.expiresAt
51
+ }
52
+ };
53
+ }
54
+ createBlankSessionCookie() {
55
+ return {
56
+ name: this.options.sessionCookie.name,
57
+ value: "",
58
+ attributes: {
59
+ ...this.options.sessionCookie.attributes,
60
+ maxAge: 0
61
+ }
62
+ };
63
+ }
64
+ async validateSessionToken(token) {
65
+ const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
66
+ const result = await this.db.select({ user: this.userTable, session: this.sessionTable }).from(this.sessionTable).innerJoin(this.userTable, eq(this.sessionTable.userId, this.userTable.id)).where(eq(this.sessionTable.id, sessionId));
67
+ if (result.length < 1) {
68
+ return { session: null, user: null, fresh: false };
69
+ }
70
+ const { user, session } = result[0];
71
+ const expired = Date.now() >= session.expiresAt.getTime();
72
+ if (expired) {
73
+ await this.db.delete(this.sessionTable).where(eq(this.sessionTable.id, session.id));
74
+ return { session: null, user: null, fresh: false };
75
+ }
76
+ const canBeExtended = Date.now() >= session.expiresAt.getTime() - this.options.expiresAt / 2;
77
+ if (canBeExtended) {
78
+ session.expiresAt = new Date(Date.now() + this.options.expiresAt);
79
+ await this.db.update(this.sessionTable).set({
80
+ expiresAt: session.expiresAt
81
+ }).where(eq(this.sessionTable.id, session.id));
82
+ }
83
+ return {
84
+ session,
85
+ user,
86
+ // cast because it contains extra attributes
87
+ fresh: canBeExtended
88
+ };
89
+ }
90
+ async invalidateSession(sessionId) {
91
+ await this.db.delete(this.sessionTable).where(eq(this.sessionTable.id, sessionId));
92
+ }
93
+ }
@@ -0,0 +1,8 @@
1
+ import type { BaseLogger } from "@witchcraft/nuxt-logger/createUseLogger";
2
+ import type { PgDatabase } from "drizzle-orm/pg-core";
3
+ import type { EventHandler } from "h3";
4
+ import type { RuntimeConfig } from "nuxt/schema";
5
+ import type { AuthAccountsTable, UserTable } from "./createAuthSchema.js.js";
6
+ import type { SessionManager } from "./SessionManager.js.js";
7
+ import type { AuthHandlerOptions } from "../../types.js.js";
8
+ export declare function createAuthHandler(rc: RuntimeConfig, db: PgDatabase<any, any, any>, usersTable: UserTable, authAccountsTable: AuthAccountsTable, sessionManager: SessionManager, opts?: Partial<AuthHandlerOptions>, logger?: BaseLogger): EventHandler;
@@ -0,0 +1,29 @@
1
+ import { Auth } from "./Auth.js";
2
+ import github from "#auth/core/providers/github.js";
3
+ import google from "#auth/core/providers/google.js";
4
+ import { createRouter } from "#imports";
5
+ export function createAuthHandler(rc, db, usersTable, authAccountsTable, sessionManager, opts = {}, logger = console) {
6
+ const router = createRouter();
7
+ const auth = new Auth(
8
+ rc,
9
+ db,
10
+ usersTable,
11
+ authAccountsTable,
12
+ sessionManager,
13
+ router,
14
+ {
15
+ ...opts,
16
+ enabledProviders: rc.public.auth.enabledProviders,
17
+ handlers: {
18
+ github,
19
+ google,
20
+ ...opts.customProviders ?? {}
21
+ },
22
+ runtimeConfig: rc.public
23
+ },
24
+ rc,
25
+ // for the env vars
26
+ logger
27
+ );
28
+ return auth.eventHandler;
29
+ }
@@ -0,0 +1,10 @@
1
+ import type { BaseLogger } from "@witchcraft/nuxt-logger/createUseLogger";
2
+ import type { SessionManager } from "./SessionManager.js.js";
3
+ import type { AuthSession, AuthUser } from "../../types.js.js";
4
+ export declare function createAuthMiddleware(sessionManager: SessionManager, logger?: BaseLogger): any;
5
+ declare module "h3" {
6
+ interface H3EventContext {
7
+ user: AuthUser | null;
8
+ session: AuthSession | null;
9
+ }
10
+ }
@@ -0,0 +1,28 @@
1
+ import { defineEventHandler, getCookie, setCookie } from "#imports";
2
+ export function createAuthMiddleware(sessionManager, logger = console) {
3
+ return defineEventHandler(async (event) => {
4
+ const sessionId = getCookie(event, sessionManager.options.sessionCookie.name) ?? null;
5
+ if (!sessionId) {
6
+ event.context.session = null;
7
+ event.context.user = null;
8
+ return;
9
+ }
10
+ const { session, user, fresh } = await sessionManager.validateSessionToken(sessionId);
11
+ logger.debug({
12
+ ns: "auth:middleware:session",
13
+ user,
14
+ fresh,
15
+ redact: { sessionId, session }
16
+ });
17
+ if (fresh) {
18
+ const cookie = sessionManager.createSessionCookie(session.id);
19
+ setCookie(event, cookie.name, cookie.value, cookie.attributes);
20
+ }
21
+ if (!session) {
22
+ const cookie = sessionManager.createBlankSessionCookie();
23
+ setCookie(event, cookie.name, cookie.value, cookie.attributes);
24
+ }
25
+ event.context.session = session;
26
+ event.context.user = user;
27
+ });
28
+ }
@@ -0,0 +1,244 @@
1
+ import { type PgColumn, type PgTableWithColumns } from "drizzle-orm/pg-core";
2
+ export declare const authUserFields: {
3
+ email: import("drizzle-orm").NotNull<import("drizzle-orm/pg-core").PgTextBuilderInitial<"email", [string, ...string[]]>>;
4
+ isRegistered: import("drizzle-orm").NotNull<import("drizzle-orm").HasDefault<import("drizzle-orm/pg-core").PgBooleanBuilderInitial<"isRegistered">>>;
5
+ };
6
+ export type AuthUserFields = {
7
+ id: string;
8
+ email: string;
9
+ isRegistered: boolean;
10
+ };
11
+ export declare function createAuthSchema(users: AuthUsersTable): {
12
+ authSessions: PgTableWithColumns<{
13
+ name: "authSessions";
14
+ schema: undefined;
15
+ columns: {
16
+ id: PgColumn<{
17
+ name: "id";
18
+ tableName: "authSessions";
19
+ dataType: "string";
20
+ columnType: "PgText";
21
+ data: string;
22
+ driverParam: string;
23
+ notNull: true;
24
+ hasDefault: false;
25
+ isPrimaryKey: true;
26
+ isAutoincrement: false;
27
+ hasRuntimeDefault: false;
28
+ enumValues: [string, ...string[]];
29
+ baseColumn: never;
30
+ identity: undefined;
31
+ generated: undefined;
32
+ }, {}, {}>;
33
+ userId: PgColumn<{
34
+ name: "userId";
35
+ tableName: "authSessions";
36
+ dataType: "string";
37
+ columnType: "PgUUID";
38
+ data: string;
39
+ driverParam: string;
40
+ notNull: true;
41
+ hasDefault: false;
42
+ isPrimaryKey: false;
43
+ isAutoincrement: false;
44
+ hasRuntimeDefault: false;
45
+ enumValues: undefined;
46
+ baseColumn: never;
47
+ identity: undefined;
48
+ generated: undefined;
49
+ }, {}, {}>;
50
+ expiresAt: PgColumn<{
51
+ name: "expiresAt";
52
+ tableName: "authSessions";
53
+ dataType: "date";
54
+ columnType: "PgTimestamp";
55
+ data: Date;
56
+ driverParam: string;
57
+ notNull: true;
58
+ hasDefault: false;
59
+ isPrimaryKey: false;
60
+ isAutoincrement: false;
61
+ hasRuntimeDefault: false;
62
+ enumValues: undefined;
63
+ baseColumn: never;
64
+ identity: undefined;
65
+ generated: undefined;
66
+ }, {}, {}>;
67
+ };
68
+ dialect: "pg";
69
+ }>;
70
+ authSessionRelations: import("drizzle-orm").Relations<"authSessions", {
71
+ user: import("drizzle-orm").One<any, true>;
72
+ }>;
73
+ authAccounts: PgTableWithColumns<{
74
+ name: "authAccounts";
75
+ schema: undefined;
76
+ columns: {
77
+ providerId: PgColumn<{
78
+ name: "providerId";
79
+ tableName: "authAccounts";
80
+ dataType: "string";
81
+ columnType: "PgText";
82
+ data: string;
83
+ driverParam: string;
84
+ notNull: true;
85
+ hasDefault: false;
86
+ isPrimaryKey: false;
87
+ isAutoincrement: false;
88
+ hasRuntimeDefault: false;
89
+ enumValues: [string, ...string[]];
90
+ baseColumn: never;
91
+ identity: undefined;
92
+ generated: undefined;
93
+ }, {}, {}>;
94
+ userId: PgColumn<{
95
+ name: "userId";
96
+ tableName: "authAccounts";
97
+ dataType: "string";
98
+ columnType: "PgUUID";
99
+ data: string;
100
+ driverParam: string;
101
+ notNull: true;
102
+ hasDefault: false;
103
+ isPrimaryKey: false;
104
+ isAutoincrement: false;
105
+ hasRuntimeDefault: false;
106
+ enumValues: undefined;
107
+ baseColumn: never;
108
+ identity: undefined;
109
+ generated: undefined;
110
+ }, {}, {}>;
111
+ provider: PgColumn<{
112
+ name: "provider";
113
+ tableName: "authAccounts";
114
+ dataType: "string";
115
+ columnType: "PgText";
116
+ data: string;
117
+ driverParam: string;
118
+ notNull: true;
119
+ hasDefault: false;
120
+ isPrimaryKey: false;
121
+ isAutoincrement: false;
122
+ hasRuntimeDefault: false;
123
+ enumValues: [string, ...string[]];
124
+ baseColumn: never;
125
+ identity: undefined;
126
+ generated: undefined;
127
+ }, {}, {}>;
128
+ name: PgColumn<{
129
+ name: "name";
130
+ tableName: "authAccounts";
131
+ dataType: "string";
132
+ columnType: "PgText";
133
+ data: string;
134
+ driverParam: string;
135
+ notNull: true;
136
+ hasDefault: false;
137
+ isPrimaryKey: false;
138
+ isAutoincrement: false;
139
+ hasRuntimeDefault: false;
140
+ enumValues: [string, ...string[]];
141
+ baseColumn: never;
142
+ identity: undefined;
143
+ generated: undefined;
144
+ }, {}, {}>;
145
+ info: PgColumn<{
146
+ name: "info";
147
+ tableName: "authAccounts";
148
+ dataType: "json";
149
+ columnType: "PgJsonb";
150
+ data: never;
151
+ driverParam: unknown;
152
+ notNull: false;
153
+ hasDefault: true;
154
+ isPrimaryKey: false;
155
+ isAutoincrement: false;
156
+ hasRuntimeDefault: false;
157
+ enumValues: undefined;
158
+ baseColumn: never;
159
+ identity: undefined;
160
+ generated: undefined;
161
+ }, {}, {
162
+ $type: never;
163
+ }>;
164
+ };
165
+ dialect: "pg";
166
+ }>;
167
+ authProvidersRelations: import("drizzle-orm").Relations<"authAccounts", {
168
+ user: import("drizzle-orm").One<any, true>;
169
+ }>;
170
+ };
171
+ export type AuthAccountsTable = ReturnType<typeof createAuthSchema>["authAccounts"];
172
+ export type AuthSessionsTable = ReturnType<typeof createAuthSchema>["authSessions"];
173
+ export type AuthSessionRelations = ReturnType<typeof createAuthSchema>["authSessionRelations"];
174
+ export type AuthProvidersRelations = ReturnType<typeof createAuthSchema>["authProvidersRelations"];
175
+ export type AuthAccount = ReturnType<typeof createAuthSchema>["authAccounts"]["$inferSelect"];
176
+ export type AuthSession = ReturnType<typeof createAuthSchema>["authSessions"]["$inferSelect"];
177
+ type BaseColumn = {
178
+ name: any;
179
+ tableName: any;
180
+ dataType: any;
181
+ columnType: any;
182
+ driverParam: any;
183
+ hasDefault: boolean;
184
+ enumValues: any;
185
+ baseColumn: any;
186
+ isPrimaryKey: any;
187
+ isAutoincrement: any;
188
+ hasRuntimeDefault: any;
189
+ generated: any;
190
+ };
191
+ export type UserTable = PgTableWithColumns<{
192
+ dialect: "pg";
193
+ schema: any;
194
+ name: any;
195
+ columns: {
196
+ id: PgColumn<{
197
+ notNull: true;
198
+ hasDefault: boolean;
199
+ dataType: "string";
200
+ data: string;
201
+ } & Omit<BaseColumn, "hasDefault">>;
202
+ username: PgColumn<{
203
+ notNull: false;
204
+ hasDefault: false;
205
+ dataType: "string";
206
+ data: string;
207
+ } & Omit<BaseColumn, "username">>;
208
+ email: PgColumn<{
209
+ notNull: true;
210
+ dataType: "string";
211
+ data: string;
212
+ } & BaseColumn>;
213
+ isRegistered: PgColumn<{
214
+ notNull: true;
215
+ dataType: "boolean";
216
+ data: boolean;
217
+ hasDefault: true;
218
+ } & Omit<BaseColumn, "hasDefault">>;
219
+ };
220
+ }>;
221
+ export type AuthUsersTable = PgTableWithColumns<{
222
+ dialect: "pg";
223
+ columns: {
224
+ id: PgColumn<{
225
+ name: any;
226
+ tableName: any;
227
+ dataType: any;
228
+ columnType: any;
229
+ data: string;
230
+ driverParam: any;
231
+ notNull: true;
232
+ hasDefault: boolean;
233
+ enumValues: any;
234
+ baseColumn: any;
235
+ isPrimaryKey: any;
236
+ isAutoincrement: any;
237
+ hasRuntimeDefault: any;
238
+ generated: any;
239
+ }, object>;
240
+ };
241
+ schema: any;
242
+ name: any;
243
+ }>;
244
+ export {};
@@ -0,0 +1,43 @@
1
+ import { boolean, jsonb, pgTable, primaryKey, text, timestamp, uuid } from "drizzle-orm/pg-core";
2
+ import { relations } from "drizzle-orm/relations";
3
+ export const authUserFields = {
4
+ email: text("email").notNull().unique(),
5
+ isRegistered: boolean("isRegistered").default(false).notNull()
6
+ };
7
+ export function createAuthSchema(users) {
8
+ const authSessions = pgTable("authSessions", {
9
+ id: text("id").primaryKey(),
10
+ userId: uuid("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
11
+ expiresAt: timestamp("expiresAt", {
12
+ mode: "date"
13
+ }).notNull()
14
+ });
15
+ const authSessionRelations = relations(authSessions, ({ one }) => ({
16
+ user: one(users, {
17
+ fields: [authSessions.userId],
18
+ references: [users.id]
19
+ })
20
+ }));
21
+ const authAccounts = pgTable("authAccounts", {
22
+ // we can't be sure the email won't be changed
23
+ providerId: text("providerId").notNull(),
24
+ userId: uuid("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
25
+ provider: text("provider").notNull(),
26
+ name: text("name").notNull(),
27
+ info: jsonb("info").default({}).$type()
28
+ }, (t) => ({
29
+ id: primaryKey({ columns: [t.provider, t.providerId] })
30
+ }));
31
+ const authProvidersRelations = relations(authAccounts, ({ one }) => ({
32
+ user: one(users, {
33
+ fields: [authAccounts.userId],
34
+ references: [users.id]
35
+ })
36
+ }));
37
+ return {
38
+ authSessions,
39
+ authSessionRelations,
40
+ authAccounts,
41
+ authProvidersRelations
42
+ };
43
+ }