@witchcraft/nuxt-auth 0.5.1 → 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 +189 -337
  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 +12 -11
  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,27 +1,390 @@
1
- import type { AuthUser, ProviderNames, UseAuthComposableOptions } from "../types.js";
2
- type AuthListenerHook = () => void;
3
- type AuthListenerHooks = "beforeLogout";
4
- export declare const useAuth: ({ handleActions }?: UseAuthComposableOptions) => {
5
- on: (hook: AuthListenerHooks, listener: AuthListenerHook) => void;
6
- off: (hook: AuthListenerHooks, listener: AuthListenerHook) => void;
7
- user: import("vue").Ref<AuthUser | null, AuthUser | null>;
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ import type { BetterAuthClientOptions } from "better-auth";
3
+ import type { AuthUser } from "../types.js";
4
+ type AuthListenerHook = (options: {
5
+ scope?: "all" | "others";
6
+ }) => void;
7
+ type AuthListenerHooks = "beforeLogout" | "beforeDelete" | "afterDelete";
8
+ declare const hooks: {
9
+ beforeLogout: AuthListenerHook[];
10
+ beforeDelete: (({ id }: {
11
+ id: string;
12
+ }) => void)[];
13
+ afterDelete: (({ id }: {
14
+ id: string;
15
+ }) => void)[];
16
+ };
17
+ export declare const useAuth: ({ usernameSchema, userSchema, clientOptions }?: {
18
+ /** Username schema used when a local-only user checks availability locally. */
19
+ usernameSchema?: StandardSchemaV1<string, string>;
20
+ /** Validates users read from storage, e.g. `zAuthUserStored`. */
21
+ userSchema?: StandardSchemaV1;
22
+ /** Options passed to the better-auth client in full, merged over the module defaults with `defu`. */
23
+ clientOptions?: BetterAuthClientOptions;
24
+ }) => {
25
+ on: <TKey extends AuthListenerHooks>(hook: TKey, listener: (typeof hooks)[TKey][number]) => void;
26
+ off: <TKey extends AuthListenerHooks>(hook: TKey, listener: (typeof hooks)[TKey][number]) => void;
27
+ user: import("vue").Ref<{
28
+ id: string;
29
+ email: string;
30
+ emailVerified: boolean;
31
+ name: string;
32
+ image: string | null;
33
+ isRegistered: boolean;
34
+ createdAt: Date;
35
+ updatedAt: Date;
36
+ type: "local";
37
+ username: string;
38
+ } | {
39
+ id: string;
40
+ email: string;
41
+ emailVerified: boolean;
42
+ name: string;
43
+ image: string | null;
44
+ isRegistered: boolean;
45
+ createdAt: Date;
46
+ updatedAt: Date;
47
+ username: string | null;
48
+ type?: "external" | undefined;
49
+ } | undefined, {
50
+ id: string;
51
+ email: string;
52
+ emailVerified: boolean;
53
+ name: string;
54
+ image: string | null;
55
+ isRegistered: boolean;
56
+ createdAt: Date;
57
+ updatedAt: Date;
58
+ type: "local";
59
+ username: string;
60
+ } | {
61
+ id: string;
62
+ email: string;
63
+ emailVerified: boolean;
64
+ name: string;
65
+ image: string | null;
66
+ isRegistered: boolean;
67
+ createdAt: Date;
68
+ updatedAt: Date;
69
+ username: string | null;
70
+ type?: "external" | undefined;
71
+ } | undefined>;
8
72
  setFetchUserOnNavigation: (value?: boolean) => void;
9
- login: (provider: ProviderNames, { devBypass }?: {
73
+ login: (provider: string, { devBypass, devBypassRegistration, username }?: {
10
74
  /** Send the request with the devBypass query param (This will only actually bypass auth if the server permits it). */
11
75
  devBypass?: boolean;
76
+ /** Create the mock user already registered, so the app skips the registration page. */
77
+ devBypassRegistration?: boolean;
78
+ /** The username to sign in as when using dev bypass, or the stored local user to sign in to (required when `provider` is `local`). */
79
+ username?: string;
80
+ }) => Promise<void>;
81
+ logout: ({ scope }?: {
82
+ scope?: "all" | "others";
12
83
  }) => Promise<void>;
13
- logout: () => Promise<void>;
14
- authRoutes: {
15
- login: string | undefined;
16
- unauthenticated?: string | undefined;
17
- register?: string | undefined;
18
- postRegisteredLogin?: string | undefined;
19
- externalCode?: string | undefined;
20
- deeplink?: string | undefined;
21
- mockAuth?: string | undefined;
22
- };
84
+ authRoutes: any;
23
85
  isAuthenticated: import("vue").ComputedRef<boolean>;
24
86
  isRegistered: import("vue").ComputedRef<boolean>;
25
- isSemiAuthed: import("vue").Ref<boolean, boolean>;
87
+ isExpired: () => boolean;
88
+ isExternal: import("vue").ComputedRef<boolean>;
89
+ delete: (id?: string) => Promise<void>;
90
+ update: (patch: {
91
+ username?: string;
92
+ name?: string;
93
+ image?: string;
94
+ }) => Promise<void>;
95
+ isUsernameAvailable: ({ username, local }: {
96
+ username: string;
97
+ local: boolean;
98
+ }) => Promise<boolean>;
99
+ list: () => Promise<AuthUser[]>;
100
+ client: import("better-auth/vue").VueAuthClient<{
101
+ baseURL: any;
102
+ fetchOptions: {
103
+ headers: {
104
+ cookie?: string | undefined;
105
+ } | undefined;
106
+ customFetchImpl: ((input: any, init?: any) => Promise<Response>) | undefined;
107
+ };
108
+ plugins: ({
109
+ id: "electron-proxy";
110
+ version: string;
111
+ getActions: () => {
112
+ electron: {
113
+ getAuthorizationCode: () => string | null;
114
+ };
115
+ ensureElectronRedirect: (cfg?: {
116
+ timeout?: number | undefined;
117
+ interval?: number | undefined;
118
+ } | undefined) => NodeJS.Timeout;
119
+ };
120
+ pathMethods: {
121
+ "/electron/transfer-user": "POST";
122
+ };
123
+ $InferServerPlugin: ReturnType<typeof import("@better-auth/electron").electron>;
124
+ } | {
125
+ id: "username";
126
+ version: string;
127
+ $InferServerPlugin: {
128
+ id: "username";
129
+ version: string;
130
+ init(ctx: import("better-auth").AuthContext): {
131
+ options: {
132
+ databaseHooks: {
133
+ user: {
134
+ create: {
135
+ before(user: {
136
+ id: string;
137
+ createdAt: Date;
138
+ updatedAt: Date;
139
+ email: string;
140
+ emailVerified: boolean;
141
+ name: string;
142
+ image?: string | null | undefined;
143
+ } & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null): Promise<{
144
+ data: {
145
+ displayUsername?: string | undefined;
146
+ username: string;
147
+ id: string;
148
+ createdAt: Date;
149
+ updatedAt: Date;
150
+ email: string;
151
+ emailVerified: boolean;
152
+ name: string;
153
+ image?: string | null | undefined;
154
+ };
155
+ } | {
156
+ data: {
157
+ displayUsername?: string | undefined;
158
+ id: string;
159
+ createdAt: Date;
160
+ updatedAt: Date;
161
+ email: string;
162
+ emailVerified: boolean;
163
+ name: string;
164
+ image?: string | null | undefined;
165
+ };
166
+ }>;
167
+ };
168
+ update: {
169
+ before(user: Partial<{
170
+ id: string;
171
+ createdAt: Date;
172
+ updatedAt: Date;
173
+ email: string;
174
+ emailVerified: boolean;
175
+ name: string;
176
+ image?: string | null | undefined;
177
+ }> & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null): Promise<{
178
+ data: {
179
+ displayUsername?: string | undefined;
180
+ username: string;
181
+ id?: string | undefined;
182
+ createdAt?: Date | undefined;
183
+ updatedAt?: Date | undefined;
184
+ email?: string | undefined;
185
+ emailVerified?: boolean | undefined;
186
+ name?: string | undefined;
187
+ image?: string | null | undefined;
188
+ };
189
+ } | {
190
+ data: {
191
+ displayUsername?: string | undefined;
192
+ id?: string | undefined;
193
+ createdAt?: Date | undefined;
194
+ updatedAt?: Date | undefined;
195
+ email?: string | undefined;
196
+ emailVerified?: boolean | undefined;
197
+ name?: string | undefined;
198
+ image?: string | null | undefined;
199
+ };
200
+ }>;
201
+ };
202
+ };
203
+ };
204
+ };
205
+ };
206
+ endpoints: {
207
+ signInUsername: import("better-auth").StrictEndpoint<"/sign-in/username", {
208
+ method: "POST";
209
+ body: import("zod").ZodObject<{
210
+ username: import("zod").ZodString;
211
+ password: import("zod").ZodString;
212
+ rememberMe: import("zod").ZodOptional<import("zod").ZodBoolean>;
213
+ callbackURL: import("zod").ZodOptional<import("zod").ZodString>;
214
+ }, import("zod/v4/core").$strip>;
215
+ metadata: {
216
+ openapi: {
217
+ summary: string;
218
+ description: string;
219
+ responses: {
220
+ 200: {
221
+ description: string;
222
+ content: {
223
+ "application/json": {
224
+ schema: {
225
+ type: "object";
226
+ properties: {
227
+ redirect: {
228
+ type: string;
229
+ description: string;
230
+ };
231
+ token: {
232
+ type: string;
233
+ description: string;
234
+ };
235
+ url: {
236
+ type: string;
237
+ nullable: boolean;
238
+ description: string;
239
+ };
240
+ user: {
241
+ $ref: string;
242
+ };
243
+ };
244
+ required: string[];
245
+ };
246
+ };
247
+ };
248
+ };
249
+ 422: {
250
+ description: string;
251
+ content: {
252
+ "application/json": {
253
+ schema: {
254
+ type: "object";
255
+ properties: {
256
+ message: {
257
+ type: string;
258
+ };
259
+ };
260
+ };
261
+ };
262
+ };
263
+ };
264
+ };
265
+ };
266
+ };
267
+ }, {
268
+ redirect: boolean;
269
+ token: string;
270
+ url: string | undefined;
271
+ user: {
272
+ id: string;
273
+ createdAt: Date;
274
+ updatedAt: Date;
275
+ email: string;
276
+ emailVerified: boolean;
277
+ name: string;
278
+ image?: string | null | undefined;
279
+ } & {
280
+ username: string;
281
+ displayUsername: string;
282
+ };
283
+ }>;
284
+ isUsernameAvailable: import("better-auth").StrictEndpoint<"/is-username-available", {
285
+ method: "POST";
286
+ body: import("zod").ZodObject<{
287
+ username: import("zod").ZodString;
288
+ }, import("zod/v4/core").$strip>;
289
+ }, {
290
+ available: boolean;
291
+ }>;
292
+ };
293
+ schema: {
294
+ user: {
295
+ fields: {
296
+ username: {
297
+ type: "string";
298
+ required: false;
299
+ sortable: true;
300
+ unique: true;
301
+ returned: true;
302
+ transform: {
303
+ input(value: import("better-auth").DBPrimitive): string | number | boolean | Date | unknown[] | Record<string, unknown> | null | undefined;
304
+ };
305
+ };
306
+ displayUsername: {
307
+ type: "string";
308
+ required: false;
309
+ transform: {
310
+ input(value: import("better-auth").DBPrimitive): string | number | boolean | Date | unknown[] | Record<string, unknown> | null | undefined;
311
+ };
312
+ };
313
+ };
314
+ };
315
+ };
316
+ hooks: {
317
+ before: {
318
+ matcher(context: import("better-auth").HookEndpointContext): boolean;
319
+ handler: import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<void>>;
320
+ }[];
321
+ };
322
+ options: import("better-auth/plugins").UsernameOptions | undefined;
323
+ $ERROR_CODES: {
324
+ EMAIL_NOT_VERIFIED: import("better-auth").RawError<"EMAIL_NOT_VERIFIED">;
325
+ UNEXPECTED_ERROR: import("better-auth").RawError<"UNEXPECTED_ERROR">;
326
+ INVALID_USERNAME_OR_PASSWORD: import("better-auth").RawError<"INVALID_USERNAME_OR_PASSWORD">;
327
+ USERNAME_IS_ALREADY_TAKEN: import("better-auth").RawError<"USERNAME_IS_ALREADY_TAKEN">;
328
+ USERNAME_TOO_SHORT: import("better-auth").RawError<"USERNAME_TOO_SHORT">;
329
+ USERNAME_TOO_LONG: import("better-auth").RawError<"USERNAME_TOO_LONG">;
330
+ INVALID_USERNAME: import("better-auth").RawError<"INVALID_USERNAME">;
331
+ INVALID_DISPLAY_USERNAME: import("better-auth").RawError<"INVALID_DISPLAY_USERNAME">;
332
+ USERNAME_IS_IMMUTABLE: import("better-auth").RawError<"USERNAME_IS_IMMUTABLE">;
333
+ };
334
+ };
335
+ atomListeners: {
336
+ matcher: (path: string) => path is "/sign-in/username";
337
+ signal: "$sessionSignal";
338
+ }[];
339
+ $ERROR_CODES: {
340
+ EMAIL_NOT_VERIFIED: import("better-auth").RawError<"EMAIL_NOT_VERIFIED">;
341
+ UNEXPECTED_ERROR: import("better-auth").RawError<"UNEXPECTED_ERROR">;
342
+ INVALID_USERNAME_OR_PASSWORD: import("better-auth").RawError<"INVALID_USERNAME_OR_PASSWORD">;
343
+ USERNAME_IS_ALREADY_TAKEN: import("better-auth").RawError<"USERNAME_IS_ALREADY_TAKEN">;
344
+ USERNAME_TOO_SHORT: import("better-auth").RawError<"USERNAME_TOO_SHORT">;
345
+ USERNAME_TOO_LONG: import("better-auth").RawError<"USERNAME_TOO_LONG">;
346
+ INVALID_USERNAME: import("better-auth").RawError<"INVALID_USERNAME">;
347
+ INVALID_DISPLAY_USERNAME: import("better-auth").RawError<"INVALID_DISPLAY_USERNAME">;
348
+ USERNAME_IS_IMMUTABLE: import("better-auth").RawError<"USERNAME_IS_IMMUTABLE">;
349
+ };
350
+ } | {
351
+ id: "additional-fields-client";
352
+ version: string;
353
+ $InferServerPlugin: {
354
+ id: "additional-fields-client";
355
+ version: string;
356
+ schema: {
357
+ user: {
358
+ fields: {
359
+ isRegistered: {
360
+ type: "boolean";
361
+ };
362
+ };
363
+ };
364
+ session: {
365
+ fields: {};
366
+ };
367
+ };
368
+ };
369
+ } | {
370
+ id: "local-only-users";
371
+ getActions: () => {
372
+ localOnlyUsers: {
373
+ list: () => AuthUser[];
374
+ create: (username: string, { switch: doSwitch }?: {
375
+ switch?: boolean;
376
+ }) => AuthUser;
377
+ activate: (username: string) => AuthUser | undefined;
378
+ update: (id: string, patch: {
379
+ username?: string;
380
+ name?: string;
381
+ image?: string;
382
+ }) => AuthUser | undefined;
383
+ delete: (id: string) => void;
384
+ logout: () => void;
385
+ };
386
+ };
387
+ })[];
388
+ }>;
26
389
  };
27
390
  export {};
@@ -1,62 +1,219 @@
1
+ import { electronProxyClient } from "@better-auth/electron/proxy";
2
+ import { inferAdditionalFields, usernameClient } from "better-auth/client/plugins";
3
+ import { createAuthClient } from "better-auth/vue";
4
+ import { defu } from "defu";
1
5
  import {
2
6
  navigateTo,
7
+ useRequestHeaders,
8
+ useRequestURL,
3
9
  useRuntimeConfig,
4
10
  useState
5
11
  } from "#app";
6
12
  import { computed } from "#imports";
7
- import { getAuthApiRoute } from "../utils/getAuthApiRoute.js";
13
+ import { localOnlyUsers } from "../plugins/client/localOnlyUsers.js";
14
+ import { defaultZodUsernameSchema, externalExpiryStorageKey, fetchStateKey, userStorageKey } from "../types.js";
8
15
  const hooks = {
9
- beforeLogout: []
16
+ beforeLogout: [],
17
+ beforeDelete: [],
18
+ afterDelete: []
10
19
  };
11
- export const useAuth = ({ handleActions } = {}) => {
20
+ export const useAuth = ({ usernameSchema = defaultZodUsernameSchema, userSchema, clientOptions } = {}) => {
12
21
  const config = useRuntimeConfig().public.auth;
13
- const doFetch = useState("auth:_fetch");
14
- const userData = useState("auth:user", () => null);
15
- const isSemiAuthed = useState("auth:semiAuthed", () => false);
22
+ const doFetch = useState(fetchStateKey);
23
+ const userData = useState(userStorageKey, () => void 0);
16
24
  const isAuthenticated = computed(() => !!userData.value);
17
25
  const isRegistered = computed(() => !!userData.value?.isRegistered);
18
26
  const authRoutes = {
19
27
  ...config.authRoutes,
20
28
  login: config.authRoutes.login
21
29
  };
30
+ const defaultClientOptions = {
31
+ baseURL: import.meta.server ? useRequestURL().origin : config.publicServerUrl,
32
+ fetchOptions: {
33
+ headers: import.meta.server ? useRequestHeaders(["cookie"]) : void 0,
34
+ // on electron, the relative paths used resolve to app://... instead of publicServerUrl
35
+ // this would be fine (electron proxies the requests to the app) except better auth errors on such a schema
36
+ // so we have to write the url for it to fetch from
37
+ customFetchImpl: config.publicServerUrl ? (input, init) => {
38
+ const url = new URL(
39
+ typeof input === "string" ? input : input.url ?? String(input),
40
+ config.publicServerUrl
41
+ );
42
+ return fetch(`${url.pathname}${url.search}`, init);
43
+ } : void 0
44
+ },
45
+ plugins: [
46
+ ...config.deeplinkSchemes?.electron ? [electronProxyClient({
47
+ protocol: config.deeplinkSchemes.electron,
48
+ callbackPath: config.authRoutes.deeplink,
49
+ cookiePrefix: config.cookiePrefix
50
+ })] : [],
51
+ usernameClient(),
52
+ inferAdditionalFields({
53
+ user: {
54
+ isRegistered: { type: "boolean" }
55
+ }
56
+ }),
57
+ localOnlyUsers({
58
+ userSchema
59
+ })
60
+ ]
61
+ };
62
+ const merged = defu(clientOptions, defaultClientOptions);
63
+ const client = createAuthClient(merged);
64
+ function getExternal() {
65
+ if (import.meta.server) return void 0;
66
+ for (const plugin of merged.plugins ?? []) {
67
+ const key = "externalApiActionsKey" in plugin ? plugin.externalApiActionsKey : void 0;
68
+ if (typeof key !== "string") continue;
69
+ const actions = client[key];
70
+ if (actions.isActive() === true && typeof actions.login === "function") return actions;
71
+ }
72
+ return void 0;
73
+ }
74
+ const external = getExternal();
75
+ const isExternal = computed(() => external !== void 0);
22
76
  function setFetchUserOnNavigation(value = true) {
23
77
  doFetch.value = value;
24
78
  }
79
+ function assertIsOnClient(method) {
80
+ if (import.meta.server) throw new Error(`${method}: only available in the browser.`);
81
+ }
25
82
  async function login(provider, {
26
- devBypass = false
83
+ devBypass = false,
84
+ devBypassRegistration = false,
85
+ username
27
86
  } = {}) {
87
+ if (provider === "local") {
88
+ assertIsOnClient("login");
89
+ if (username === void 0) throw new Error("login: signing in to a local user needs a username.");
90
+ const stored = external?.local ? await external.local.list() : client.localOnlyUsers.list();
91
+ const entry = stored.find((item) => item.username === username);
92
+ if (!entry) {
93
+ const parsed = await usernameSchema["~standard"].validate(username);
94
+ if (parsed.issues) throw new Error(`login: cannot create a local user, "${username}" is not a valid username.`);
95
+ }
96
+ if (external?.local) {
97
+ if (entry) await external.local.activate(entry.id);
98
+ else await external.local.create({ id: crypto.randomUUID(), username });
99
+ return;
100
+ }
101
+ if (entry) client.localOnlyUsers.activate(username);
102
+ else client.localOnlyUsers.create(username);
103
+ await navigateTo(authRoutes.postRegisteredLogin);
104
+ return;
105
+ }
28
106
  setFetchUserOnNavigation();
29
- const loginRoute = getAuthApiRoute(useRuntimeConfig().public, "login", { provider: provider.toLowerCase() }, { devBypass });
30
- const external = provider ? true : void 0;
31
- const handled = handleActions?.("login", loginRoute, provider);
32
- if (!handled) {
33
- await navigateTo(loginRoute, { external });
107
+ if (external) {
108
+ await external.login({
109
+ provider,
110
+ isDevBypass: devBypass,
111
+ username,
112
+ isDevBypassRegistration: devBypassRegistration
113
+ });
114
+ return;
115
+ }
116
+ if (devBypass) {
117
+ await navigateTo(`${authRoutes.mockAuth}?provider=${provider}`);
118
+ return;
34
119
  }
120
+ if (userData.value) throw new Error("login is not available while a user is signed in.");
121
+ await client.signIn.social({
122
+ provider,
123
+ callbackURL: authRoutes.postRegisteredLogin
124
+ });
35
125
  }
36
- async function logout() {
126
+ async function logout({ scope } = {}) {
127
+ assertIsOnClient("logout");
37
128
  setFetchUserOnNavigation();
38
- const wasSemiAuthed = isSemiAuthed.value;
39
- await Promise.allSettled(hooks.beforeLogout.map((listener) => listener()));
40
- const handled = handleActions?.("logout", getAuthApiRoute(useRuntimeConfig().public, "logout"));
41
- userData.value = null;
42
- if (!handled) {
43
- localStorage.removeItem("auth:user");
44
- const res = wasSemiAuthed ? true : await $fetch(getAuthApiRoute(useRuntimeConfig().public, "logout"), {
45
- cache: "no-store",
46
- method: "post"
47
- });
48
- if (res) {
49
- await navigateTo(authRoutes.unauthenticated, { external: true });
129
+ const isLocal = userData.value?.type === "local";
130
+ await Promise.allSettled(hooks.beforeLogout.map((listener) => listener({ scope })));
131
+ if (scope === "others") {
132
+ if (!isLocal) {
133
+ await client.revokeOtherSessions();
134
+ }
135
+ return;
136
+ }
137
+ if (isLocal) {
138
+ client.localOnlyUsers.logout();
139
+ }
140
+ if (!isLocal) {
141
+ await (scope === "all" ? client.revokeSessions() : client.signOut()).catch(() => void 0).finally(() => navigateTo(authRoutes.unauthenticated, { external: true }));
142
+ }
143
+ userData.value = void 0;
144
+ localStorage.removeItem(externalExpiryStorageKey);
145
+ await navigateTo(authRoutes.unauthenticated, { external: true });
146
+ }
147
+ function isExpired() {
148
+ assertIsOnClient("isExpired");
149
+ const type = userData.value?.type;
150
+ if (type !== "external") {
151
+ throw new Error(`isExpired: only an external user has an expiry, the active user is ${type ?? "a server user"}.`);
152
+ }
153
+ const expiresAt = localStorage.getItem(externalExpiryStorageKey);
154
+ if (!expiresAt) return false;
155
+ return Date.now() >= Number(expiresAt);
156
+ }
157
+ async function deleteUser(id) {
158
+ const current = userData.value;
159
+ if (id !== void 0 && current?.type === "external" && id !== current.id) {
160
+ throw new Error("delete: an id can only name a local user, or the active user.");
161
+ }
162
+ const target = id ?? current?.id;
163
+ if (!target) throw new Error("delete: there is no active user and no id was given.");
164
+ const isLocal = target === current?.id ? current.type === "local" : true;
165
+ setFetchUserOnNavigation();
166
+ await Promise.allSettled(hooks.beforeDelete.map((listener) => listener({ id: target })));
167
+ if (isLocal) {
168
+ assertIsOnClient("delete");
169
+ if (external?.local) await external.local.delete(target);
170
+ else client.localOnlyUsers.delete(target);
171
+ } else {
172
+ await client.deleteUser();
173
+ }
174
+ if (target === current?.id) {
175
+ userData.value = void 0;
176
+ await navigateTo(authRoutes.unauthenticated, { external: true });
177
+ }
178
+ await Promise.allSettled(hooks.afterDelete.map((listener) => listener({ id: target })));
179
+ }
180
+ async function update(patch) {
181
+ const current = userData.value;
182
+ if (!current) throw new Error("update: there is no active user.");
183
+ if (current.type === "local") {
184
+ assertIsOnClient("update");
185
+ if (external?.local) {
186
+ await external.local.update(current.id, patch);
187
+ return;
50
188
  }
189
+ const updated = client.localOnlyUsers.update(current.id, patch);
190
+ if (!updated) throw new Error("update: the stored user no longer exists.");
191
+ return;
51
192
  }
193
+ await client.updateUser(patch, { throw: true });
194
+ await external?.onUserUpdate(current.id, patch);
195
+ }
196
+ async function isUsernameAvailable({ username, local }) {
197
+ if (!local) return (await client.isUsernameAvailable({ username }, { throw: true })).available;
198
+ assertIsOnClient("isUsernameAvailable");
199
+ const parsed = await usernameSchema["~standard"].validate(username);
200
+ if (parsed.issues) return false;
201
+ const users = external?.local ? await external.local.list() : client.localOnlyUsers.list();
202
+ return !users.some((entry) => entry.username === parsed.value);
203
+ }
204
+ async function list() {
205
+ assertIsOnClient("list");
206
+ if (external?.local) return await external.local.list();
207
+ return client.localOnlyUsers.list();
52
208
  }
53
209
  function on(hook, listener) {
54
210
  hooks[hook].push(listener);
55
211
  }
56
212
  function off(hook, listener) {
57
- const index = hooks[hook].indexOf(listener);
213
+ const listeners = hooks[hook];
214
+ const index = listeners.indexOf(listener);
58
215
  if (index > -1) {
59
- hooks[hook].splice(index, 1);
216
+ listeners.splice(index, 1);
60
217
  }
61
218
  }
62
219
  return {
@@ -69,6 +226,12 @@ export const useAuth = ({ handleActions } = {}) => {
69
226
  authRoutes,
70
227
  isAuthenticated,
71
228
  isRegistered,
72
- isSemiAuthed
229
+ isExpired,
230
+ isExternal,
231
+ delete: deleteUser,
232
+ update,
233
+ isUsernameAvailable,
234
+ list,
235
+ client
73
236
  };
74
237
  };