@vite-hub/auth 0.1.0 → 0.3.0

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 (89) hide show
  1. package/README.md +333 -49
  2. package/dist/abilities-DfAnFYwG.d.ts +93 -0
  3. package/dist/abilities.d.ts +2 -0
  4. package/dist/abilities.js +43 -0
  5. package/dist/ability-error-CqgBrBfR.js +91 -0
  6. package/dist/ability-error-DcgChwCN.d.ts +34 -0
  7. package/dist/admin-claim-code-CDipqeAU.js +22 -0
  8. package/dist/agent.d.ts +5 -5
  9. package/dist/agent.js +17 -9
  10. package/dist/application-path-DuTpfGFj.js +62 -0
  11. package/dist/auth-instance-CR6b1W80.js +1168 -0
  12. package/dist/bun-sqlite.d.ts +8 -0
  13. package/dist/cli-ubYJpAL_.d.ts +163 -0
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.js +47 -7
  16. package/dist/console-runtime-DTopBP-x.d.ts +71 -0
  17. package/dist/console-runtime-J9_Vx9pT.js +1166 -0
  18. package/dist/console-runtime.d.ts +3 -3
  19. package/dist/console-runtime.js +2 -819
  20. package/dist/console.d.ts +215 -3
  21. package/dist/console.js +1 -1
  22. package/dist/database-options-BRNef9oy.js +29 -0
  23. package/dist/database-schema-options-ENuRMduM.js +12 -0
  24. package/dist/database.d.ts +12 -0
  25. package/dist/database.js +45 -0
  26. package/dist/definition-CqQMcDEK.js +280 -0
  27. package/dist/error-diagnostics-C8XtVz0i.js +138 -0
  28. package/dist/{events-P7mI4IQb.js → events-ByzenEVj.js} +122 -4
  29. package/dist/forward.d.ts +50 -0
  30. package/dist/forward.js +120 -0
  31. package/dist/host-declarations.d.ts +2 -1
  32. package/dist/index.d.ts +24 -3
  33. package/dist/index.js +3 -102
  34. package/dist/internal/server.d.ts +5 -0
  35. package/dist/internal/server.js +858 -0
  36. package/dist/invariant-D8_xBqmZ.js +22 -0
  37. package/dist/mcp.d.ts +187 -0
  38. package/dist/mcp.js +353 -0
  39. package/dist/members-D9lfaEO_.js +533 -0
  40. package/dist/nuxt-bridge-Cl988STZ.js +44 -0
  41. package/dist/nuxt.d.ts +13 -5
  42. package/dist/nuxt.js +90 -13
  43. package/dist/object-Da1zyPCR.js +11 -0
  44. package/dist/page-tools-shared-l4eyj53D.js +19 -0
  45. package/dist/presets.js +1 -1
  46. package/dist/request-z6DHHmrb.js +47 -0
  47. package/dist/runtime/console.d.ts +3 -7
  48. package/dist/runtime/console.js +4 -42
  49. package/dist/runtime/empty-abilities.d.ts +5 -0
  50. package/dist/runtime/empty-abilities.js +4 -0
  51. package/dist/runtime/empty-client.d.ts +6 -0
  52. package/dist/runtime/empty-client.js +5 -0
  53. package/dist/runtime/empty-definition.d.ts +1 -1
  54. package/dist/runtime/nuxt.js +1 -1
  55. package/dist/runtime/server.d.ts +2 -0
  56. package/dist/runtime/server.js +77 -0
  57. package/dist/runtime/vue-nuxt.d.ts +3 -2
  58. package/dist/runtime/vue-nuxt.js +157 -5
  59. package/dist/runtime-state-ojQCzKOc.js +25 -0
  60. package/dist/schema.d.ts +137 -0
  61. package/dist/schema.js +147 -0
  62. package/dist/server-C0qnKN2W.d.ts +143 -0
  63. package/dist/server-bQGzVQ--.d.ts +41 -0
  64. package/dist/server.d.ts +3 -2
  65. package/dist/server.js +3 -3
  66. package/dist/session-cookies-BbH3UR2m.js +227 -0
  67. package/dist/{set-cookie-2as_DbHe.js → set-cookie-C8NOhdRE.js} +27 -12
  68. package/dist/{shared-DnpgYiLF.js → shared-BwcdRGxD.js} +2 -5
  69. package/dist/table-specs-8gq_FCaq.js +771 -0
  70. package/dist/table-specs-DbXyaXWs.d.ts +842 -0
  71. package/dist/test.d.ts +26 -0
  72. package/dist/test.js +25 -0
  73. package/dist/{events-BkmK2dFY.d.ts → types-CNaeH2Fd.d.ts} +240 -157
  74. package/dist/vite-CV400XXY.js +1556 -0
  75. package/dist/vite.d.ts +138 -20
  76. package/dist/vite.js +2 -2
  77. package/dist/vue.d.ts +330 -21
  78. package/dist/vue.js +583 -36
  79. package/package.json +84 -15
  80. package/dist/application-path-C290OAIs.js +0 -18
  81. package/dist/cli-mgXvsBtA.d.ts +0 -85
  82. package/dist/console-B7eERmGv.d.ts +0 -180
  83. package/dist/console-runtime-bZQtnX2Y.d.ts +0 -39
  84. package/dist/error-diagnostics-CL0yjHiM.js +0 -79
  85. package/dist/events-config-CjcFOhTE.js +0 -177
  86. package/dist/inspect-DPtsW8dB.d.ts +0 -36
  87. package/dist/server-B7LU19dS.js +0 -1730
  88. package/dist/server-CTD_JAww.d.ts +0 -77
  89. package/dist/vite-COWkwxsj.js +0 -990
package/dist/nuxt.js CHANGED
@@ -1,18 +1,30 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-CL0yjHiM.js";
2
- import { a as hubAuth, c as resolveAuthViteConfig, i as createAuthNitroConfig, l as resolveNuxtServerDirs, u as resolveViteHubProjectRoot } from "./vite-COWkwxsj.js";
3
- import { resolve } from "node:path";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
2
+ import { c as resolveAuthViteConfig, d as resolveViteHubProjectRoot, l as authAbilitiesCandidates, o as createAuthNitroConfig, s as hubAuth, u as resolveNuxtServerDirs } from "./vite-CV400XXY.js";
3
+ import { realpathSync } from "node:fs";
4
+ import { dirname, resolve } from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { createEnvImportAliases, hubEnv } from "@vite-hub/env/vite";
6
7
  //#region src/nuxt.ts
7
8
  const composables = [
9
+ "useAbility",
8
10
  "useAuthClient",
9
11
  "useSession",
10
- "useSignIn",
11
- "useSignUp",
12
12
  "useUserSession"
13
13
  ];
14
14
  const nitroRegistered = /* @__PURE__ */ new WeakSet();
15
15
  const vueBridgeRegistered = /* @__PURE__ */ new WeakSet();
16
+ const pageMetaRegistered = /* @__PURE__ */ new WeakSet();
17
+ const componentsRegistered = /* @__PURE__ */ new WeakSet();
18
+ const abilitiesWatchRegistered = /* @__PURE__ */ new WeakSet();
19
+ const manifestRegistered = /* @__PURE__ */ new WeakSet();
20
+ /** Better Auth's Vue client file, which `createAuthClient()` imports on first use. */
21
+ function resolveBetterAuthVueClient() {
22
+ try {
23
+ return realpathSync(fileURLToPath(import.meta.resolve("better-auth/vue")));
24
+ } catch {
25
+ return;
26
+ }
27
+ }
16
28
  function hubAuthNuxt(options = {}, nuxt) {
17
29
  if (!nuxt) return;
18
30
  nuxt.options.plugins ??= [];
@@ -43,22 +55,26 @@ function hubAuthNuxt(options = {}, nuxt) {
43
55
  };
44
56
  const authPlugin = vitePlugins.find((plugin) => plugin?.name === "@vite-hub/auth/vite") || hubAuth(options.auth);
45
57
  if (!vitePlugins.some((plugin) => plugin?.name === "@vite-hub/auth/vite")) nuxt.options.vite.plugins.push(authPlugin);
58
+ const resolveAuthOptions = () => options.auth;
59
+ const resolveAuthConfig = () => {
60
+ const configRoot = resolve(viteRoot);
61
+ const serverDirs = resolveNuxtServerDirs(nuxt.options);
62
+ const authOptions = resolveAuthOptions();
63
+ return resolveAuthViteConfig(authOptions, configRoot, { serverDirs }) ?? resolveAuthViteConfig(authOptions, resolveViteHubProjectRoot(configRoot), { serverDirs });
64
+ };
46
65
  if (options.nitro !== false && !nitroRegistered.has(nuxt)) {
47
66
  nitroRegistered.add(nuxt);
48
67
  nuxt.hook?.("nitro:config", async (nitroConfig) => {
49
- const configRoot = resolve(viteRoot);
50
- const serverDirs = resolveNuxtServerDirs(nuxt.options);
51
- const authOptions = nuxt.options.vite?.auth ?? options.auth;
52
- const definitionHandler = (resolveAuthViteConfig(authOptions, configRoot, { serverDirs }) ?? resolveAuthViteConfig(authOptions, resolveViteHubProjectRoot(configRoot), { serverDirs }))?.definition.handler;
53
- if (definitionHandler) nitroConfig.alias = {
68
+ const authConfig = resolveAuthConfig();
69
+ if (authConfig) nitroConfig.alias = {
54
70
  ...nitroConfig.alias,
55
- "#vitehub/auth/definition": definitionHandler
71
+ "#vitehub/auth/definition": authConfig.definition.handler,
72
+ ...authConfig.abilities ? { "#vitehub/auth/abilities": authConfig.abilities } : {}
56
73
  };
57
74
  Object.assign(nitroConfig, createAuthNitroConfig(authPlugin, {
58
75
  nitro: nitroConfig,
59
76
  projectRoot: viteRoot,
60
- serverDirs: resolveNuxtServerDirs(nuxt.options),
61
- viteAuth: nuxt.options.vite?.auth
77
+ serverDirs: resolveNuxtServerDirs(nuxt.options)
62
78
  }));
63
79
  });
64
80
  }
@@ -68,12 +84,73 @@ function hubAuthNuxt(options = {}, nuxt) {
68
84
  ensureVueRuntimePlugin();
69
85
  });
70
86
  }
87
+ const authOptions = resolveAuthOptions();
88
+ const redirects = authOptions ? authOptions.redirects : void 0;
89
+ nuxt.options.runtimeConfig ??= {};
90
+ nuxt.options.runtimeConfig.public ??= {};
91
+ nuxt.options.runtimeConfig.public.vitehubAuth = authOptions === false ? false : {
92
+ basePath: resolveAuthConfig()?.basePath ?? "/api/auth",
93
+ redirects: {
94
+ login: redirects?.login ?? "/login",
95
+ guest: redirects?.guest ?? "/"
96
+ }
97
+ };
98
+ if (!pageMetaRegistered.has(nuxt) && nuxt.hook) {
99
+ pageMetaRegistered.add(nuxt);
100
+ nuxt.hook("prepare:types", ({ declarations }) => {
101
+ declarations.push(`declare module "#app" {\n interface PageMeta {\n /** Who may open the page. See https://vitehub.dev/docs/auth/protect-pages. */\n auth?: import("@vite-hub/auth/nuxt").AuthPageMeta\n }\n}`);
102
+ });
103
+ }
104
+ if (!componentsRegistered.has(nuxt) && nuxt.hook) {
105
+ componentsRegistered.add(nuxt);
106
+ const filePath = options.importsFrom || "@vite-hub/auth/vue";
107
+ nuxt.hook("components:extend", (components) => {
108
+ for (const name of ["Can", "Cannot"]) {
109
+ if (components.some((component) => component.pascalName === name)) continue;
110
+ components.push({
111
+ chunkName: `components/${name.toLowerCase()}`,
112
+ export: name,
113
+ filePath,
114
+ global: false,
115
+ kebabName: name.toLowerCase(),
116
+ meta: {},
117
+ mode: "all",
118
+ pascalName: name,
119
+ prefetch: false,
120
+ preload: false,
121
+ priority: 0,
122
+ shortPath: filePath
123
+ });
124
+ }
125
+ });
126
+ }
127
+ if (!manifestRegistered.has(nuxt) && nuxt.hook) {
128
+ manifestRegistered.add(nuxt);
129
+ nuxt.hook("build:manifest", (manifest) => {
130
+ const lazy = /* @__PURE__ */ new Set([resolveBetterAuthVueClient(), fileURLToPath(new URL("./vue.js", import.meta.url))]);
131
+ const root = nuxt.options.vite?.root || nuxt.options.srcDir || nuxt.options.rootDir || process.cwd();
132
+ const keys = new Set(Object.keys(manifest).filter((id) => lazy.has(resolve(root, id))));
133
+ if (!keys.size) return;
134
+ for (const chunk of Object.values(manifest)) chunk.dynamicImports &&= chunk.dynamicImports.filter((id) => !keys.has(id));
135
+ });
136
+ }
71
137
  nuxt.options.imports ??= {};
72
138
  nuxt.options.imports.imports ??= [];
73
139
  for (const name of composables) if (!nuxt.options.imports.imports.some((entry) => entry.name === name)) nuxt.options.imports.imports.push({
74
140
  from: options.importsFrom || "@vite-hub/auth/vue",
75
141
  name
76
142
  });
143
+ if (nuxt.options.dev && options.auth !== false && nuxt.hook && !abilitiesWatchRegistered.has(nuxt)) {
144
+ abilitiesWatchRegistered.add(nuxt);
145
+ const files = authAbilitiesCandidates(viteRoot, { serverDirs: resolveNuxtServerDirs(nuxt.options) });
146
+ nuxt.options.watch ??= [];
147
+ for (const directory of new Set([...files.app, ...files.layers].map(dirname))) if (!nuxt.options.watch.includes(directory)) nuxt.options.watch.push(directory);
148
+ nuxt.hook("builder:watch", async (event, path) => {
149
+ if (event !== "add" && event !== "unlink") return;
150
+ const candidates = authAbilitiesCandidates(viteRoot, { serverDirs: resolveNuxtServerDirs(nuxt.options) });
151
+ if ([...candidates.app, ...candidates.layers].includes(resolve(nuxt.options.rootDir || viteRoot, path))) await nuxt.callHook?.("restart");
152
+ });
153
+ }
77
154
  if (options.env === false) return;
78
155
  const envAliases = createEnvImportAliases({ projectRoot: envProjectRoot });
79
156
  const runtimePlugin = fileURLToPath(new URL("./runtime/nuxt.js", import.meta.url));
@@ -0,0 +1,11 @@
1
+ //#region ../internal/src/object.ts
2
+ /** A non-null object that is not an array. Functions do not pass. */
3
+ function isRecord(value) {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+ /** A non-null object or a function that is not an array. */
7
+ function isRecordOrFunction(value) {
8
+ return Object(value) === value && !Array.isArray(value);
9
+ }
10
+ //#endregion
11
+ export { isRecordOrFunction as n, isRecord as t };
@@ -0,0 +1,19 @@
1
+ //#region ../internal/src/runtime/page-tools-shared.ts
2
+ /**
3
+ * The cookie that remembers the session route's answer for this browser: `1` when a tool allows the person, `0` when
4
+ * none does or the person turned the tools off. It is a hint, never a credential, and it is not HttpOnly, because the
5
+ * page's bootstrap script reads it.
6
+ */
7
+ const viteHubPageToolsCookie = "vitehub-tools";
8
+ /**
9
+ * The cookie that tells page scripts that an app Auth session exists. `@vite-hub/auth` sets it to `1` next to the
10
+ * session cookie and clears it on sign-out. It is not HttpOnly and holds no secret.
11
+ */
12
+ const viteHubSessionMarkerCookie = "vitehub_session";
13
+ /**
14
+ * The `Set-Cookie` value that forgets the session route's answer. Auth sends it when a session starts or ends, so the
15
+ * next page asks the session route again for the new person.
16
+ */
17
+ const viteHubPageToolsResetCookie = `${viteHubPageToolsCookie}=; Path=/; Max-Age=0; SameSite=Lax`;
18
+ //#endregion
19
+ export { viteHubPageToolsResetCookie as n, viteHubSessionMarkerCookie as r, viteHubPageToolsCookie as t };
package/dist/presets.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-CL0yjHiM.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
2
2
  //#region src/presets.ts
3
3
  const durationUnits = {
4
4
  s: 1,
@@ -0,0 +1,47 @@
1
+ import { getStandardContext } from "@vite-hub/runtime/internal/h3";
2
+ //#region ../internal/src/runtime/cloudflare-env-lookup.ts
3
+ /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
4
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
5
+ let activeEnv;
6
+ /** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
7
+ function getScopedCloudflareEnv() {
8
+ return globalThis[activeEnvStorageKey]?.getStore();
9
+ }
10
+ function getActiveCloudflareEnv() {
11
+ const scoped = getScopedCloudflareEnv();
12
+ if (scoped) return scoped.env;
13
+ const host = globalThis;
14
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
15
+ }
16
+ //#endregion
17
+ //#region src/request.ts
18
+ function isObjectLike(value) {
19
+ return value !== null && (typeof value === "object" || typeof value === "function");
20
+ }
21
+ /** A Web Request, also from another realm. A request event has no string `url` and `method` of its own. */
22
+ function isAuthRequest(input) {
23
+ if (input instanceof Request) return true;
24
+ if ("~standard" in input) return false;
25
+ const headers = Reflect.get(input, "headers");
26
+ return typeof Reflect.get(input, "url") === "string" && typeof Reflect.get(input, "method") === "string" && isObjectLike(headers) && typeof Reflect.get(headers, "get") === "function";
27
+ }
28
+ /** Return a Web Request itself, or the request in the Standard Context of a request event. */
29
+ function unwrapAuthRequest(input) {
30
+ return isAuthRequest(input) ? input : getStandardContext(input).req;
31
+ }
32
+ /**
33
+ * Return the object that carries the Standard Context of an Auth input: the request event, or the Web Request itself.
34
+ * A Request that no framework wrapped gets a Standard Context that reads the host data on it, such as srvx `ip` and
35
+ * `runtime.cloudflare`.
36
+ */
37
+ function authRequestEvent(input) {
38
+ const value = input;
39
+ getStandardContext(value);
40
+ return value;
41
+ }
42
+ /** The Cloudflare bindings in the Standard Context of `event`, else the bindings of the active Cloudflare request. */
43
+ function authCloudflareEnv(event) {
44
+ return (event ? getStandardContext(event).runtime?.cloudflare?.env : void 0) ?? getActiveCloudflareEnv();
45
+ }
46
+ //#endregion
47
+ export { authRequestEvent as n, unwrapAuthRequest as r, authCloudflareEnv as t };
@@ -1,7 +1,3 @@
1
- import { n as ViteHubConsoleRuntimeRecordReader } from "../console-B7eERmGv.js";
2
- import { t as aggregateAuthEvents, v as listAuthEvents } from "../server-CTD_JAww.js";
3
- //#region src/runtime/console.d.ts
4
- /** Owner runtime reader. The Console must authorize access before it calls this export. */
5
- export declare const readAuthEventConsoleRecords: ViteHubConsoleRuntimeRecordReader;
6
- //#endregion
7
- export { aggregateAuthEvents, listAuthEvents };
1
+ import { k as authForRequest, n as aggregateAuthEvents, v as listAuthEvents } from "../server-C0qnKN2W.js";
2
+ import "../server.js";
3
+ export { aggregateAuthEvents, authForRequest, listAuthEvents };
@@ -1,42 +1,4 @@
1
- import { f as getAuthEvents, t as aggregateAuthEvents, v as listAuthEvents } from "../server-B7LU19dS.js";
2
- //#region src/runtime/console.ts
3
- /** Owner runtime reader. The Console must authorize access before it calls this export. */
4
- const readAuthEventConsoleRecords = async () => {
5
- const store = getAuthEvents();
6
- if (!store) return [];
7
- const { events } = await store.list();
8
- return events.map((event) => ({
9
- id: event.id,
10
- cells: {
11
- type: event.type,
12
- time: event.time,
13
- actor: event.actor,
14
- user: event.userId ?? "",
15
- method: event.metadata.method ?? ""
16
- },
17
- fields: [
18
- {
19
- label: "Type",
20
- value: event.type
21
- },
22
- {
23
- label: "Time",
24
- value: event.time
25
- },
26
- {
27
- label: "Actor",
28
- value: event.actor
29
- },
30
- {
31
- label: "User",
32
- value: event.userId ?? "Unknown"
33
- },
34
- {
35
- label: "Metadata",
36
- value: JSON.stringify(event.metadata)
37
- }
38
- ]
39
- }));
40
- };
41
- //#endregion
42
- export { aggregateAuthEvents, listAuthEvents, readAuthEventConsoleRecords };
1
+ import { t as authForRequest } from "../auth-instance-CR6b1W80.js";
2
+ import { aggregateAuthEvents, listAuthEvents } from "../internal/server.js";
3
+ import "../server.js";
4
+ export { aggregateAuthEvents, authForRequest, listAuthEvents };
@@ -0,0 +1,5 @@
1
+ import { s as AbilityRules } from "../abilities-DfAnFYwG.js";
2
+ //#region src/runtime/empty-abilities.d.ts
3
+ declare const abilities: AbilityRules;
4
+ //#endregion
5
+ export { abilities as default };
@@ -0,0 +1,4 @@
1
+ //#region src/runtime/empty-abilities.ts
2
+ const abilities = {};
3
+ //#endregion
4
+ export { abilities as default };
@@ -0,0 +1,6 @@
1
+ import { BetterAuthClientOptions } from "better-auth";
2
+ //#region src/runtime/empty-client.d.ts
3
+ /** The options of the default Auth client when the app has no `auth.client.ts`. */
4
+ declare const options: BetterAuthClientOptions | undefined;
5
+ //#endregion
6
+ export { options as default };
@@ -0,0 +1,5 @@
1
+ //#region src/runtime/empty-client.ts
2
+ /** The options of the default Auth client when the app has no `auth.client.ts`. */
3
+ const options = void 0;
4
+ //#endregion
5
+ export { options as default };
@@ -1,4 +1,4 @@
1
- import { O as AuthDefinition } from "../events-BkmK2dFY.js";
1
+ import { g as AuthDefinition } from "../types-CNaeH2Fd.js";
2
2
  //#region src/runtime/empty-definition.d.ts
3
3
  declare const definition: AuthDefinition | undefined;
4
4
  //#endregion
@@ -1,6 +1,6 @@
1
1
  import discoveredDefinition from "#vitehub/auth/definition";
2
2
  import { useServerEnv } from "#vitehub/env/server";
3
- import { setAuthRuntimeEnvResolver } from "@vite-hub/auth/server";
3
+ import { setAuthRuntimeEnvResolver } from "@vite-hub/auth/runtime/server";
4
4
  //#region src/runtime/nuxt.ts
5
5
  function viteHubAuthNuxtRuntime() {
6
6
  setAuthRuntimeEnvResolver(useServerEnv, discoveredDefinition);
@@ -0,0 +1,2 @@
1
+ import { a as setAuthAccessIdentityResolver, i as createLazyAuthAccessHandler, n as authAccessHandlerMeta, o as setAuthRuntimeEnvResolver, r as createAuthAccessRouteMatcher, t as AuthAccessRouteMatch } from "../server-bQGzVQ--.js";
2
+ export { AuthAccessRouteMatch, authAccessHandlerMeta, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
@@ -0,0 +1,77 @@
1
+ import { r as unwrapAuthRequest } from "../request-z6DHHmrb.js";
2
+ import { n as getAuthRuntimeState } from "../runtime-state-ojQCzKOc.js";
3
+ import { n as canonicalAccessPath, r as resolveAccessRoutePath } from "../application-path-DuTpfGFj.js";
4
+ //#region src/runtime/server.ts
5
+ function setAuthRuntimeEnvResolver(resolver, definition) {
6
+ const state = getAuthRuntimeState();
7
+ if (definition) state.envResolvers?.set(definition, resolver);
8
+ else state.envResolver = resolver;
9
+ }
10
+ /**
11
+ * Let a trusted server integration authenticate one exact mounted path without a browser session.
12
+ * Resolved users still pass every matching Auth access route's authorize callback, with an empty session.
13
+ */
14
+ function setAuthAccessIdentityResolver(path, resolver) {
15
+ const state = getAuthRuntimeState();
16
+ state.accessIdentityResolvers ??= /* @__PURE__ */ new Map();
17
+ if (resolver) state.accessIdentityResolvers.set(path, resolver);
18
+ else state.accessIdentityResolvers.delete(path);
19
+ }
20
+ /**
21
+ * The Nitro route `meta` of a handler that checks its own access, such as the ViteHub Console route. The access routes
22
+ * leave a request to the handler that Nitro routed it to when that handler has this meta, whatever its path and method.
23
+ * The exception follows the dispatch, so an app route file on the same path keeps the access routes.
24
+ */
25
+ const authAccessHandlerMeta = Object.freeze({ vitehubAuthAccess: "handler" });
26
+ /** Whether Nitro routed the request event to a handler with `authAccessHandlerMeta`. A plain Request has no route. */
27
+ function routedToAccessHandler(input) {
28
+ if (!("context" in input) || !(input.context instanceof Object)) return false;
29
+ const route = Reflect.get(input.context, "matchedRoute");
30
+ const meta = route instanceof Object ? Reflect.get(route, "meta") : void 0;
31
+ return meta instanceof Object && Reflect.get(meta, "vitehubAuthAccess") === authAccessHandlerMeta.vitehubAuthAccess;
32
+ }
33
+ function matchesPath(rule, pathname) {
34
+ return pathname === rule.path || rule.recursive && (rule.path === "" || pathname.startsWith(`${rule.path}/`));
35
+ }
36
+ /**
37
+ * Return a function that lists the access routes that match a request, in Definition order. A request to a path of
38
+ * `publicRoutes` matches no access route.
39
+ */
40
+ function createAuthAccessRouteMatcher(routes, publicRoutes = []) {
41
+ const rules = routes.map((route, index) => ({
42
+ index,
43
+ authorize: route.authorize === true,
44
+ method: route.method?.toUpperCase(),
45
+ ...resolveAccessRoutePath(route.route)
46
+ }));
47
+ const exceptions = publicRoutes.map((route) => resolveAccessRoutePath(route));
48
+ return (input) => {
49
+ if (routedToAccessHandler(input)) return [];
50
+ const request = unwrapAuthRequest(input);
51
+ const pathname = canonicalAccessPath(new URL(request.url).pathname);
52
+ if (exceptions.some((rule) => matchesPath(rule, pathname))) return [];
53
+ const method = request.method.toUpperCase();
54
+ return rules.filter((rule) => (!rule.method || rule.method === method || rule.method === "GET" && method === "HEAD") && matchesPath(rule, pathname)).map((rule) => ({
55
+ index: rule.index,
56
+ authorize: rule.authorize
57
+ }));
58
+ };
59
+ }
60
+ /**
61
+ * The access middleware of generated hosts. A request that no access route matches returns without loading `load()`,
62
+ * so the server starts without Better Auth.
63
+ */
64
+ function createLazyAuthAccessHandler(routes, load, publicRoutes = []) {
65
+ const match = createAuthAccessRouteMatcher(routes, publicRoutes);
66
+ let handler;
67
+ return async (input) => {
68
+ if (match(input).length === 0) return;
69
+ handler ??= load().then((module) => module.createAuthAccessHandler(routes, void 0, publicRoutes)).catch((error) => {
70
+ handler = void 0;
71
+ throw error;
72
+ });
73
+ return await (await handler)(input);
74
+ };
75
+ }
76
+ //#endregion
77
+ export { authAccessHandlerMeta, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
@@ -1,3 +1,4 @@
1
1
  //#region src/runtime/vue-nuxt.d.ts
2
- export default function viteHubAuthVueNuxtRuntime(): void;
3
- //#endregion
2
+ declare const viteHubAuthPlugin: unknown;
3
+ //#endregion
4
+ export { viteHubAuthPlugin as default };
@@ -1,8 +1,160 @@
1
- import { setNuxtAppResolver } from "../vue.js";
2
- import { tryUseNuxtApp } from "#app";
1
+ import { i as resolveAuthMountPath } from "../application-path-DuTpfGFj.js";
2
+ import "../page-tools-shared-l4eyj53D.js";
3
+ import { a as setRequestFetchResolver, i as setNuxtErrorFactory, n as setDefaultAuthBasePath, o as setSessionSeedResolver, r as setNuxtAppResolver, s as setSignOutHandler } from "../nuxt-bridge-Cl988STZ.js";
4
+ import { addRouteMiddleware, createError, defineNuxtPlugin, navigateTo, tryUseNuxtApp, useRequestEvent, useRequestFetch, useRequestURL, useRouter, useRuntimeConfig, useState } from "#app";
3
5
  //#region src/runtime/vue-nuxt.ts
4
- function viteHubAuthVueNuxtRuntime() {
5
- setNuxtAppResolver(() => tryUseNuxtApp());
6
+ const stateKey = "vitehub:auth:session";
7
+ /**
8
+ * True when the request may have a session: ViteHub's `vitehub_session` marker cookie, which Auth sets next to the
9
+ * session cookie, or Better Auth's own `<prefix>.session_token` and `<prefix>.session_data` cookies.
10
+ */
11
+ function hasSessionCookie(cookie) {
12
+ if (!cookie) return false;
13
+ return cookie.split(";").map((part) => part.split("=")[0]?.trim() ?? "").some((name) => name === "vitehub_session" || /(?:^|\.)session_(?:token|data)$/.test(name));
6
14
  }
15
+ const isoDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
16
+ /** Better Auth's client returns dates as `Date`. Revive them so the server's session has the same shape. */
17
+ function reviveDates(value) {
18
+ if (typeof value === "string" && isoDate.test(value)) return new Date(value);
19
+ if (Array.isArray(value)) return value.map(reviveDates);
20
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, reviveDates(entry)]));
21
+ return value;
22
+ }
23
+ /** Forward Better Auth's `Set-Cookie` headers, such as a refreshed session, to the page response. */
24
+ function appendSetCookies(event, response) {
25
+ for (const cookie of response.headers.getSetCookie?.() ?? []) event.res?.headers?.append("set-cookie", cookie);
26
+ }
27
+ /**
28
+ * The path and query of a URL that Better Auth's client built. The client can build an absolute URL from a variable
29
+ * such as `VERCEL_URL`, and that URL would leave the process.
30
+ */
31
+ function pathOf(input) {
32
+ const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost");
33
+ return url.pathname + url.search;
34
+ }
35
+ /**
36
+ * The fetch of the current page request for Better Auth's client, or `undefined` outside a request. Nuxt's request fetch
37
+ * calls the app in-process with the headers of the page request, such as the cookie, and its `native` form answers with
38
+ * the `Response` that Better Auth reads.
39
+ */
40
+ function currentRequestFetch() {
41
+ const nuxtApp = tryUseNuxtApp();
42
+ const event = nuxtApp ? useRequestEvent() : void 0;
43
+ if (!nuxtApp || !event) return void 0;
44
+ const { native } = useRequestFetch();
45
+ const requestFetch = async (input, init) => {
46
+ const response = await native(pathOf(input), init);
47
+ appendSetCookies(event, response);
48
+ return response;
49
+ };
50
+ return {
51
+ request: nuxtApp,
52
+ origin: useRequestURL().origin,
53
+ fetch: requestFetch
54
+ };
55
+ }
56
+ /**
57
+ * Reads the session of the request, so server rendering and hydration start signed in or signed out. Returns `null` at
58
+ * once when the request has no session cookie, else a promise. Call it in a Nuxt context.
59
+ */
60
+ function readServerSession(basePath) {
61
+ const event = useRequestEvent();
62
+ if (!event) return void 0;
63
+ if (!hasSessionCookie(event.req?.headers?.get("cookie") ?? void 0)) return null;
64
+ return fetchServerSession(event, useRequestFetch(), basePath);
65
+ }
66
+ /** Asks Better Auth for the session with Nuxt's request fetch, which the caller got in a Nuxt context. */
67
+ async function fetchServerSession(event, fetch, basePath) {
68
+ try {
69
+ const data = await fetch(`${basePath}/get-session`, {
70
+ baseURL: "/",
71
+ onResponse: ({ response }) => appendSetCookies(event, response)
72
+ });
73
+ if (typeof data !== "object" || data === null) return null;
74
+ const session = Reflect.get(data, "session");
75
+ const user = Reflect.get(data, "user");
76
+ if (typeof session !== "object" || session === null || !user) return null;
77
+ const { token: _token, ...safeSession } = session;
78
+ return reviveDates({
79
+ session: safeSession,
80
+ user
81
+ });
82
+ } catch {
83
+ return;
84
+ }
85
+ }
86
+ /** The session read of each server request, so the page guard and all components share one read. */
87
+ const serverReads = /* @__PURE__ */ new WeakMap();
88
+ const viteHubAuthPlugin = defineNuxtPlugin({
89
+ name: "vitehub:auth",
90
+ enforce: "pre",
91
+ setup(nuxtApp) {
92
+ setNuxtAppResolver(() => tryUseNuxtApp());
93
+ setNuxtErrorFactory(createError);
94
+ if (!("window" in globalThis)) setRequestFetchResolver(currentRequestFetch);
95
+ const runtimeConfig = useRuntimeConfig();
96
+ const config = runtimeConfig.public?.vitehubAuth;
97
+ const redirects = (config || void 0)?.redirects ?? {};
98
+ /** The page guard of `to`: where a visitor goes, or nothing when the page has no guard. */
99
+ const guardOf = (to) => {
100
+ const meta = to.meta.auth;
101
+ if (config === false || meta === void 0 || meta === false) return;
102
+ const mode = typeof meta === "string" ? meta : meta === true ? "user" : meta.only ?? "user";
103
+ const redirectTo = typeof meta === "object" ? meta.redirectTo : void 0;
104
+ return (loggedIn) => {
105
+ if (mode === "guest") return loggedIn ? navigateTo(redirectTo ?? redirects.guest ?? "/") : void 0;
106
+ if (!loggedIn) return navigateTo({
107
+ path: redirectTo ?? redirects.login ?? "/login",
108
+ query: { redirect: to.fullPath }
109
+ });
110
+ };
111
+ };
112
+ if ("window" in globalThis) setSignOutHandler((redirectTo) => nuxtApp.runWithContext(() => {
113
+ const seed = useState(stateKey, () => void 0);
114
+ seed.value = null;
115
+ if (redirectTo) return navigateTo(redirectTo, { external: /^(?:[\w+.-]{2,}:|[/\\]{2})/.test(redirectTo) });
116
+ return guardOf(useRouter().currentRoute.value)?.(false);
117
+ }));
118
+ if (config === false) return;
119
+ const basePath = resolveAuthMountPath(config?.basePath ?? "/api/auth", "window" in globalThis ? runtimeConfig.app?.baseURL : void 0);
120
+ setDefaultAuthBasePath(basePath);
121
+ let serverSession;
122
+ if (!("window" in globalThis)) {
123
+ let read = false;
124
+ let session;
125
+ serverSession = () => {
126
+ if (read) return session;
127
+ read = true;
128
+ const seed = useState(stateKey);
129
+ session = seed.value !== void 0 ? seed.value : readServerSession(basePath);
130
+ if (session instanceof Promise) session = session.then((value) => session = seed.value = value);
131
+ else seed.value = session;
132
+ return session;
133
+ };
134
+ serverReads.set(nuxtApp, serverSession);
135
+ }
136
+ const stale = "window" in globalThis && Boolean(nuxtApp.payload.prerenderedAt || nuxtApp.payload.isCached);
137
+ setSessionSeedResolver((read) => {
138
+ if (stale) return void 0;
139
+ try {
140
+ const app = read ? tryUseNuxtApp() : void 0;
141
+ const readRequest = app && serverReads.get(app);
142
+ return readRequest ? readRequest() : useState(stateKey).value;
143
+ } catch {
144
+ return;
145
+ }
146
+ });
147
+ addRouteMiddleware("vitehub-auth", (to) => {
148
+ const decide = guardOf(to);
149
+ if (!decide) return;
150
+ const session = serverSession?.();
151
+ const app = tryUseNuxtApp();
152
+ const inApp = (run) => app ? app.runWithContext(run) : run();
153
+ const loggedIn = !serverSession ? import("../vue.js").then(({ useUserSession }) => inApp(() => useUserSession().refresh())).then((current) => Boolean(current?.session && current?.user)) : session instanceof Promise ? session.then(Boolean) : Boolean(session);
154
+ if (typeof loggedIn === "boolean") return decide(loggedIn);
155
+ return loggedIn.then((value) => inApp(() => decide(value)));
156
+ }, { global: true });
157
+ }
158
+ });
7
159
  //#endregion
8
- export { viteHubAuthVueNuxtRuntime as default };
160
+ export { viteHubAuthPlugin as default };
@@ -0,0 +1,25 @@
1
+ //#region src/runtime-state.ts
2
+ const authRuntimeStateKey = Symbol.for("vitehub.auth.runtime");
3
+ /**
4
+ * Marks the database that Auth adds to a Definition without one. It keeps rows in the memory of one process, so a value
5
+ * that another instance must see, such as a one-time ticket, cannot live there.
6
+ */
7
+ const authProcessMemoryDatabase = Symbol.for("vitehub.auth.processMemoryDatabase");
8
+ /** Whether a Better Auth `database` option is the process memory database that Auth adds. */
9
+ function isAuthProcessMemoryDatabase(database) {
10
+ return database instanceof Object && Reflect.get(database, authProcessMemoryDatabase) === true;
11
+ }
12
+ function getAuthRuntimeState() {
13
+ const globalScope = globalThis;
14
+ globalScope[authRuntimeStateKey] ??= {};
15
+ globalScope[authRuntimeStateKey].envResolvers ??= /* @__PURE__ */ new WeakMap();
16
+ return globalScope[authRuntimeStateKey];
17
+ }
18
+ function resetAuth() {
19
+ const state = getAuthRuntimeState();
20
+ state.auth = void 0;
21
+ state.definition = void 0;
22
+ state.providers = void 0;
23
+ }
24
+ //#endregion
25
+ export { resetAuth as i, getAuthRuntimeState as n, isAuthProcessMemoryDatabase as r, authProcessMemoryDatabase as t };