@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
@@ -0,0 +1,200 @@
1
+ import { externalExpiryStorageKey, userStorageKey } from "../../types.js";
2
+ export class ElectronAuth {
3
+ scheme;
4
+ callbackPath;
5
+ publicServerUrl;
6
+ getSession;
7
+ getWindow;
8
+ getActiveUserId;
9
+ sessionCookieOpts;
10
+ sessionExpiresAt;
11
+ cookiePrefix;
12
+ userIdCookieName;
13
+ useSecureCookies;
14
+ logger;
15
+ userSchema;
16
+ onFinishLogin;
17
+ /** Sessions whose cookie changes are already watched, so a window switch does not watch twice. */
18
+ watchedSessions = /* @__PURE__ */ new WeakSet();
19
+ constructor({
20
+ scheme,
21
+ userSchema,
22
+ callbackPath,
23
+ publicServerUrl,
24
+ getSession,
25
+ getWindow,
26
+ getActiveUserId,
27
+ sessionCookieOpts,
28
+ sessionExpiresAt,
29
+ cookiePrefix = "better-auth",
30
+ userIdCookieName = "userId",
31
+ logger,
32
+ onFinishLogin
33
+ }, rc) {
34
+ this.scheme = scheme;
35
+ this.userSchema = userSchema;
36
+ this.callbackPath = callbackPath;
37
+ this.publicServerUrl = publicServerUrl;
38
+ this.getSession = getSession;
39
+ this.getWindow = getWindow;
40
+ this.getActiveUserId = getActiveUserId;
41
+ const resolvedSessionCookieOpts = rc?.sessionCookieOpts ?? sessionCookieOpts;
42
+ const resolvedSessionExpiresAt = rc?.sessionExpiresAt ?? sessionExpiresAt;
43
+ if (!resolvedSessionCookieOpts || resolvedSessionExpiresAt === void 0) {
44
+ throw new Error("ElectronAuth: sessionCookieOpts and sessionExpiresAt are required, pass them directly or pass rc.auth as the second argument.");
45
+ }
46
+ this.sessionCookieOpts = resolvedSessionCookieOpts;
47
+ this.sessionExpiresAt = resolvedSessionExpiresAt;
48
+ this.cookiePrefix = rc?.cookiePrefix ?? cookiePrefix;
49
+ this.userIdCookieName = userIdCookieName;
50
+ this.useSecureCookies = new URL(publicServerUrl).protocol === "https:";
51
+ this.logger = logger;
52
+ this.onFinishLogin = onFinishLogin;
53
+ }
54
+ /** Electron spells `sameSite: "none"` as `"no_restriction"`. */
55
+ get _cookieSetOpts() {
56
+ const { sameSite, ...rest } = this.sessionCookieOpts;
57
+ return sameSite ? { ...rest, sameSite: sameSite === "none" ? "no_restriction" : sameSite } : rest;
58
+ }
59
+ get _sessionCookieName() {
60
+ return `${this.useSecureCookies ? "__Secure-" : ""}${this.cookiePrefix}.session_token`;
61
+ }
62
+ _parseToken(url) {
63
+ let parsed;
64
+ try {
65
+ parsed = new URL(url);
66
+ } catch {
67
+ return null;
68
+ }
69
+ if (parsed.protocol !== `${this.scheme}:`) return null;
70
+ if (`/${parsed.hostname}${parsed.pathname}` !== this.callbackPath) return null;
71
+ if (parsed.hash.startsWith("#token=")) return parsed.hash.slice("#token=".length);
72
+ return parsed.searchParams.get("access_token");
73
+ }
74
+ async _loadCallback(win, token) {
75
+ const windowUrl = new URL(win.webContents.getURL());
76
+ const base = windowUrl.origin === "null" ? `${windowUrl.protocol}//${windowUrl.host}` : windowUrl.origin;
77
+ const url = new URL(this.callbackPath, base);
78
+ for (const [name, value] of windowUrl.searchParams) url.searchParams.set(name, value);
79
+ url.searchParams.set("access_token", token);
80
+ this.logger?.debug({ ns: "auth:deeplink" });
81
+ await win.webContents.loadURL(url.toString());
82
+ }
83
+ /**
84
+ * Intake for scheme urls from second-instance and open-url, which only fire while the
85
+ * app is already open, so there is always a window and a session to load into.
86
+ */
87
+ async handleUrl(url) {
88
+ const token = this._parseToken(url);
89
+ if (!token) return false;
90
+ const win = this.getWindow();
91
+ if (!win || !this.getSession()) return false;
92
+ await this._loadCallback(win, token);
93
+ return true;
94
+ }
95
+ /** Window-side session cookie check for an external user. */
96
+ async getHasCookies() {
97
+ const ses = this.getSession();
98
+ if (!ses) return false;
99
+ const hasAuthCookie = (await ses.cookies.get({ name: this._sessionCookieName }))[0];
100
+ const hasUserCookie = (await ses.cookies.get({ name: this.userIdCookieName }))[0];
101
+ return !!(hasAuthCookie && hasUserCookie);
102
+ }
103
+ /**
104
+ * Cookie url, always the server origin. Chromium only stores cookies for
105
+ * http(s) schemes, so a window loaded over `app://bundle` or `file://` can
106
+ * never hold one. The window's session still carries the cookie, and the
107
+ * proxy is what sends it to the server.
108
+ */
109
+ _cookieUrl() {
110
+ const { protocol, host, hostname } = new URL(this.publicServerUrl);
111
+ if (protocol === "http:" && !["localhost", "127.0.0.1", "::1"].includes(hostname)) {
112
+ this.logger?.warn({
113
+ ns: "auth:cookieUrl",
114
+ message: `publicServerUrl "${this.publicServerUrl}" is not https, the session cookie will be sent unencrypted.`
115
+ });
116
+ }
117
+ if (!host || protocol !== "http:" && protocol !== "https:") {
118
+ throw new Error(
119
+ `ElectronAuth: cannot store the session cookie for publicServerUrl "${this.publicServerUrl}". Cookies need an http(s) origin, from getPaths().publicServerUrl for example.`
120
+ );
121
+ }
122
+ return `${protocol}//${host}/`;
123
+ }
124
+ /**
125
+ * Generic post-exchange persistence: mirrors the session cookie into the
126
+ * window session (`httpOnly`), the user into window `localStorage` and the
127
+ * cookie's expiry next to it.
128
+ * Returns, the app does whatever post-login it needs (user switching,
129
+ * folder setup, reload) after the await. No hooks, the class stays
130
+ * unaware of app details.
131
+ */
132
+ async finishLogin(win, { user, sessionToken, expiresAt = Date.now() + this.sessionExpiresAt }) {
133
+ const ses = this.getSession();
134
+ if (!ses) throw new Error("ElectronAuth: finishLogin called before the window session existed");
135
+ const parsedUser = this._parseUser(user);
136
+ const cookieUrl = this._cookieUrl();
137
+ const cookieExpiry = Math.floor(expiresAt / 1e3);
138
+ await ses.cookies.set({
139
+ url: cookieUrl,
140
+ name: this._sessionCookieName,
141
+ value: sessionToken,
142
+ secure: this.useSecureCookies,
143
+ ...this._cookieSetOpts,
144
+ expirationDate: cookieExpiry,
145
+ httpOnly: true
146
+ });
147
+ await ses.cookies.set({
148
+ url: cookieUrl,
149
+ name: this.userIdCookieName,
150
+ value: parsedUser.id,
151
+ secure: this.useSecureCookies,
152
+ ...this._cookieSetOpts,
153
+ expirationDate: cookieExpiry,
154
+ httpOnly: true
155
+ });
156
+ await win.webContents.executeJavaScript(
157
+ `localStorage.setItem(${JSON.stringify(userStorageKey)}, ${JSON.stringify(JSON.stringify({ ...parsedUser, type: "external" }))});localStorage.setItem(${JSON.stringify(externalExpiryStorageKey)}, ${JSON.stringify(String(expiresAt))})`
158
+ );
159
+ this._watchSessionCookies(ses);
160
+ this.logger?.debug({ ns: "auth:finishLogin", win: win.id });
161
+ const { id, username } = parsedUser;
162
+ await this.onFinishLogin?.({ win, user: { id, username } });
163
+ }
164
+ /** Injects a local-only user into the window as the active user. */
165
+ async saveLocalUserSession(win, authUser) {
166
+ const parsedUser = this._parseUser(authUser);
167
+ if (parsedUser.id !== this.getActiveUserId()) {
168
+ throw new Error(`ElectronAuth: cannot save credentials for user ${parsedUser.id}, the active user is ${this.getActiveUserId()}.`);
169
+ }
170
+ await win.webContents.executeJavaScript(
171
+ `localStorage.setItem(${JSON.stringify(userStorageKey)}, ${JSON.stringify(JSON.stringify({ ...parsedUser, type: "local" }))})`
172
+ );
173
+ }
174
+ _parseUser(value) {
175
+ const result = this.userSchema["~standard"].validate(value);
176
+ if (result instanceof Promise) throw new Error("ElectronAuth: async schemas cannot parse a user.");
177
+ if (result.issues) throw new Error(`ElectronAuth: invalid user, ${result.issues.map((issue) => issue.message).join(", ")}`);
178
+ return result.value;
179
+ }
180
+ /**
181
+ * Keeps the expiry key in step with the cookie, for the session the server rolls or
182
+ * replaces. Chromium reports a cookie set by us as `explicit` and its removal as one of
183
+ * the other causes, so those are ignored and the last expiry stays, which keeps the clock
184
+ * comparison answering true once it has passed.
185
+ */
186
+ _watchSessionCookies(ses) {
187
+ if (this.watchedSessions.has(ses)) return;
188
+ this.watchedSessions.add(ses);
189
+ ses.cookies.on("changed", (_event, cookie, cause, removed) => {
190
+ if (removed || cause !== "explicit" || cookie.name !== this._sessionCookieName) return;
191
+ if (cookie.expirationDate === void 0) return;
192
+ const win = this.getWindow();
193
+ if (!win) return;
194
+ const expiresAt = cookie.expirationDate * 1e3;
195
+ void win.webContents.executeJavaScript(
196
+ `localStorage.setItem(${JSON.stringify(externalExpiryStorageKey)}, ${JSON.stringify(String(expiresAt))})`
197
+ ).catch(() => void 0);
198
+ });
199
+ }
200
+ }
@@ -0,0 +1,2 @@
1
+ export { ElectronAuth } from "./ElectronAuth.js";
2
+ export { setupElectronAuthMain } from "./setupElectronAuthMain.js";
@@ -0,0 +1,2 @@
1
+ export { ElectronAuth } from "./ElectronAuth.js";
2
+ export { setupElectronAuthMain } from "./setupElectronAuthMain.js";