@vite-hub/auth 0.4.0 → 0.5.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 (66) hide show
  1. package/README.md +31 -7
  2. package/dist/{abilities-CbmTAoS_.d.ts → abilities-9jC7iuN0.d.ts} +2 -2
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-DcgChwCN.d.ts → ability-error-DUWJ6Q1W.d.ts} +1 -1
  5. package/dist/{ability-error-IeZQBr_-.js → ability-error-DmnUGicq.js} +1 -1
  6. package/dist/access-pages-FNQTyGRD.js +96 -0
  7. package/dist/agent.js +3 -3
  8. package/dist/{auth-instance-CmDogt4D.js → auth-instance-zYMjldPG.js} +227 -25
  9. package/dist/{cli-ubYJpAL_.d.ts → cli-NCtitmny.d.ts} +1 -0
  10. package/dist/cli.d.ts +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/{console-runtime-_LrpyCYY.js → console-runtime-CuXRDhGy.js} +67 -33
  13. package/dist/{console-runtime-D2ai-Et5.d.ts → console-runtime-Dqidb3zF.d.ts} +13 -11
  14. package/dist/console-runtime.d.ts +2 -2
  15. package/dist/console-runtime.js +1 -1
  16. package/dist/console.d.ts +1 -1
  17. package/dist/{database-options-DpOVjUti.js → database-options-CcjUG-us.js} +1 -1
  18. package/dist/{database-schema-options-Sk-1Bvyu.js → database-schema-options-CTKCAfqW.js} +1 -1
  19. package/dist/database.d.ts +1 -1
  20. package/dist/database.js +4 -4
  21. package/dist/{definition-BCaLA9kW.js → definition-BFT9T6In.js} +12 -4
  22. package/dist/{error-diagnostics-Dymr-S_n.js → error-diagnostics-uEbxSY2G.js} +8 -2
  23. package/dist/{events-DCfuicoo.js → events-DJmO9a9I.js} +1 -1
  24. package/dist/forward.js +1 -1
  25. package/dist/index.d.ts +3 -2
  26. package/dist/index.js +4 -3
  27. package/dist/internal/server.d.ts +4 -4
  28. package/dist/internal/server.js +4 -4
  29. package/dist/{invariant-D8_xBqmZ.js → invariant-DolT9EEx.js} +1 -1
  30. package/dist/{mcp-token-CpxLyl_p.js → mcp-token-BhonlK9C.js} +2 -2
  31. package/dist/mcp.js +1 -1
  32. package/dist/{members-DdlsS8kJ.js → members-Cl3hFRjk.js} +3 -3
  33. package/dist/nitro-kit-32CVgbWS.js +44 -0
  34. package/dist/nuxt.d.ts +32 -19
  35. package/dist/nuxt.js +337 -16
  36. package/dist/own-access-C8pwo_Kn.js +31 -0
  37. package/dist/own-access-CdgEICjO.d.ts +20 -0
  38. package/dist/presets.js +1 -1
  39. package/dist/runtime/console.d.ts +1 -1
  40. package/dist/runtime/console.js +2 -2
  41. package/dist/runtime/empty-abilities.d.ts +1 -1
  42. package/dist/runtime/empty-definition.d.ts +1 -1
  43. package/dist/runtime/server.d.ts +3 -2
  44. package/dist/runtime/server.js +23 -14
  45. package/dist/runtime/vue-nuxt.js +70 -28
  46. package/dist/schema.d.ts +71 -19
  47. package/dist/schema.js +5 -3
  48. package/dist/{server-C8TlOrSy.d.ts → server-B-zNtSvm.d.ts} +9 -10
  49. package/dist/{server-BM-RSf1T.d.ts → server-Ci2i6p1S.d.ts} +7 -6
  50. package/dist/{server-BG_MFd4q.js → server-CyqLFm3L.js} +45 -25
  51. package/dist/server.d.ts +2 -2
  52. package/dist/server.js +2 -2
  53. package/dist/{session-cookies-DVzjOKc7.js → session-cookies-CZmZS5QF.js} +2 -2
  54. package/dist/{set-cookie-DmqWq6kj.js → set-cookie-DWIyCCJO.js} +1 -1
  55. package/dist/{table-specs-DbXyaXWs.d.ts → table-specs-BhWz_U0M.d.ts} +255 -1
  56. package/dist/{table-specs-CURphR3n.js → table-specs-D0VLp1U4.js} +43 -43
  57. package/dist/test.d.ts +1 -1
  58. package/dist/test.js +2 -2
  59. package/dist/{types-CruflEFI.d.ts → types-gl-myjZc.d.ts} +51 -4
  60. package/dist/{vite-Dy0Xhq4H.js → vite-QKjsPLwP.js} +349 -120
  61. package/dist/vite.d.ts +6 -2
  62. package/dist/vite.js +1 -1
  63. package/dist/vue.d.ts +17 -68
  64. package/dist/vue.js +22 -69
  65. package/package.json +13 -9
  66. package/dist/shared-DRtfuFsV.js +0 -12
package/dist/nuxt.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { C as AuthOptions } from "./types-CruflEFI.js";
2
+ import { Dt as AuthPages, Et as AuthPageMode, Tt as AuthPageMeta, w as AuthOptions } from "./types-gl-myjZc.js";
3
3
  import "vite";
4
4
  //#region ../internal/src/build/paths.d.ts
5
5
  interface NuxtLayerDirectoryConfig {
@@ -15,17 +15,22 @@ interface NuxtServerDirOptions extends NuxtLayerDirectoryConfig {
15
15
  }>;
16
16
  }
17
17
  //#endregion
18
- //#region src/nuxt-types.d.ts
19
- /** Who may open a page: signed-in users (`user`) or signed-out visitors (`guest`). */
20
- type AuthPageMode = "guest" | "user";
21
- /**
22
- * The `auth` key of `definePageMeta()` in Nuxt. `'user'` or `true` sends visitors without a session to the login
23
- * page. `'guest'` sends signed-in users away, for example from the login page. `false` turns the guard off.
24
- */
25
- type AuthPageMeta = boolean | AuthPageMode | {
26
- only?: AuthPageMode;
27
- /** Where to send the visitor instead of the configured redirect. */
28
- redirectTo?: string;
18
+ //#region ../internal/src/build/nuxt-vue-imports.d.ts
19
+ type VueImport = {
20
+ as?: string;
21
+ disabled?: boolean;
22
+ from: string;
23
+ name: string;
24
+ type?: boolean;
25
+ };
26
+ type NuxtVueImportContext = {
27
+ getImports: () => Promise<unknown>;
28
+ getInternalContext: () => {
29
+ addons: Array<{
30
+ name?: string;
31
+ extendImports?: (imports: VueImport[]) => void;
32
+ }>;
33
+ };
29
34
  };
30
35
  //#endregion
31
36
  //#region src/nuxt.d.ts
@@ -39,7 +44,10 @@ export interface AuthNuxtModuleOptions {
39
44
  }
40
45
  type NuxtLike = {
41
46
  callHook?: (name: "restart") => Promise<void>;
42
- hook?: (name: "nitro:config", handler: (nitroConfig: Record<string, unknown>) => Promise<void>) => void;
47
+ hook?: {
48
+ (name: "nitro:config", handler: (nitroConfig: Record<string, unknown>) => Promise<void>): void;
49
+ (name: "imports:context", handler: (context: NuxtVueImportContext) => Promise<void>): void;
50
+ };
43
51
  options: {
44
52
  dev?: boolean;
45
53
  watch?: string[];
@@ -55,19 +63,24 @@ type NuxtLike = {
55
63
  app?: {
56
64
  baseURL?: string;
57
65
  };
58
- imports?: {
59
- imports?: Array<{
60
- from: string;
61
- name: string;
62
- }>;
66
+ experimental?: {
67
+ extraPageMetaExtractionKeys?: string[];
63
68
  };
64
69
  nitro?: {
65
70
  alias?: Record<string, string>;
66
71
  plugins?: string[];
67
72
  };
68
73
  rootDir?: string;
74
+ routeRules?: Record<string, Record<string, unknown>>;
75
+ router?: {
76
+ options?: {
77
+ sensitive?: boolean;
78
+ strict?: boolean;
79
+ };
80
+ };
69
81
  serverDir?: string;
70
82
  srcDir?: string;
83
+ ssr?: boolean;
71
84
  vite?: {
72
85
  define?: Record<string, unknown>;
73
86
  plugins?: unknown[];
@@ -77,4 +90,4 @@ type NuxtLike = {
77
90
  };
78
91
  export default function hubAuthNuxt(options?: AuthNuxtModuleOptions, nuxt?: NuxtLike): void;
79
92
  //#endregion
80
- export type { AuthPageMeta, AuthPageMode };
93
+ export type { AuthPageMeta, AuthPageMode, AuthPages };
package/dist/nuxt.js CHANGED
@@ -1,21 +1,248 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
2
- import { c as writeNuxtAuthDefinition, d as resolveNuxtServerDirs, f as resolveViteHubProjectRoot, l as resolveAuthViteConfig, o as createAuthNitroConfig, s as hubAuth, u as authAbilitiesCandidates } from "./vite-Dy0Xhq4H.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-uEbxSY2G.js";
2
+ import { i as normalizePagePath, r as createAccessPageMatcher, t as accessPageBeats } from "./access-pages-FNQTyGRD.js";
3
+ import { c as writeNuxtAuthDefinition, d as cachingRuleNames, f as createCachingRouteRuleFinder, h as resolveViteHubProjectRoot, l as resolveAuthViteConfig, m as resolveNuxtServerDirs, o as createAuthNitroConfig, p as methodOrder, s as hubAuth, u as authAbilitiesCandidates } from "./vite-QKjsPLwP.js";
3
4
  import { realpathSync } from "node:fs";
4
- import { dirname, resolve } from "node:path";
5
+ import { dirname, isAbsolute, relative, resolve } from "node:path";
5
6
  import { fileURLToPath } from "node:url";
7
+ import { kebabCase, pascalCase, splitByCase } from "scule";
6
8
  import { createEnvImportAliases, hubEnv } from "@vite-hub/env/vite";
9
+ //#region ../internal/src/build/nuxt-vue-imports.ts
10
+ const fallbacksByApp = /* @__PURE__ */ new WeakMap();
11
+ function addNuxtVueImports(nuxt, from, names) {
12
+ let fallbacks = fallbacksByApp.get(nuxt);
13
+ if (!fallbacks) {
14
+ const importsByName = /* @__PURE__ */ new Map();
15
+ fallbacks = importsByName;
16
+ fallbacksByApp.set(nuxt, importsByName);
17
+ const warned = /* @__PURE__ */ new Set();
18
+ nuxt.hook?.("imports:context", async (context) => {
19
+ await context.getImports();
20
+ context.getInternalContext().addons.push({
21
+ name: "vitehub:vue-imports",
22
+ extendImports(imports) {
23
+ const owners = new Map(imports.filter((entry) => !entry.disabled && !entry.type).map((entry) => [entry.as ?? entry.name, entry.from]));
24
+ for (const [name, fallback] of importsByName) {
25
+ const owner = owners.get(name);
26
+ if (owner === void 0) imports.push({
27
+ as: name,
28
+ from: fallback,
29
+ name
30
+ });
31
+ else if (owner !== fallback && !warned.has(name)) {
32
+ warned.add(name);
33
+ const source = isAbsolute(owner) ? relative(nuxt.options.rootDir || process.cwd(), owner) : owner;
34
+ console.warn(`[vitehub] ${source} already auto-imports \`${name}\`, so ViteHub does not auto-import it from ${fallback}. Import ViteHub's composable from "${fallback}" where you need it.`);
35
+ }
36
+ }
37
+ }
38
+ });
39
+ });
40
+ }
41
+ for (const name of names) if (!fallbacks.has(name)) fallbacks.set(name, from);
42
+ }
43
+ //#endregion
44
+ //#region src/page-guard-cache.ts
45
+ /**
46
+ * Nuxt prerenders a page when it builds, without the cookie of a visitor. A guest page then renders for a signed-out
47
+ * visitor, which is correct for every visitor until the browser reads the session: the page guard runs again in the
48
+ * browser and sends a signed-in user away. A cache that renders the page for the first visitor can keep a redirect.
49
+ */
50
+ const guestCachingRuleNames = cachingRuleNames.filter((name) => name !== "prerender");
51
+ /** A child page path is relative to the path of its parent. An empty child path is the parent path. */
52
+ function joinPagePath(prefix, path) {
53
+ if (path.startsWith("/")) return path;
54
+ if (!path) return prefix;
55
+ return `${prefix.replace(/\/$/, "")}/${path}`;
56
+ }
57
+ /** The page guard reads `'guest'` and `{ only: 'guest' }` as a guest page, and every other value as a user page. */
58
+ function isGuestGuard(auth) {
59
+ return auth === "guest" || typeof auth === "object" && auth !== null && Reflect.get(auth, "only") === "guest";
60
+ }
61
+ function isGuarded(auth) {
62
+ return auth !== void 0 && auth !== false;
63
+ }
64
+ /** A static page path has no parameter, no regular expression, no repeat modifier, and no catch-all. */
65
+ function isStaticPath(path) {
66
+ return !/[\\:()*?+]/.test(path);
67
+ }
68
+ /**
69
+ * Nuxt renders the payload of a page at `<page>/_payload.json`. A catch-all pattern already matches the payload paths
70
+ * below it.
71
+ */
72
+ function payloadPattern(pattern) {
73
+ if (/\/\*\*(?::\w+)?$/.test(pattern)) return void 0;
74
+ return `${pattern.replace(/\/$/, "")}/_payload.json`;
75
+ }
76
+ function parentPath(pattern) {
77
+ return pattern.replace(/\/[^/]*$/, "") || "/";
78
+ }
79
+ /**
80
+ * The page paths whose payloads a rou3 pattern matches. A last segment that matches one segment, such as `:file` or
81
+ * `*`, also matches the payload of the parent path.
82
+ */
83
+ function payloadPages(pattern) {
84
+ if (pattern.endsWith("/_payload.json")) return [parentPath(pattern)];
85
+ if (/\/(?:\*|:\w+(?:\([^)]*\))?)$/.test(pattern)) return [pattern, parentPath(pattern)];
86
+ return [pattern];
87
+ }
88
+ /**
89
+ * Normalizes the literal text of a rou3 pattern as Nuxt does for route rules. Parameter names, constraints, and
90
+ * escaped characters are not path text.
91
+ */
92
+ function normalizePattern(pattern, sensitive) {
93
+ return pattern.replace(/\\.|:\w+(?:\([^)]*\))?|[^\\:]+/g, (token) => token[0] === "\\" || token[0] === ":" ? token : normalizePagePath(token, sensitive));
94
+ }
95
+ /**
96
+ * The page and payload patterns of every page, with the `auth` that applies on them. Vue Router merges the meta of a
97
+ * page into the meta of its child pages, so a child page without `auth` has the guard of its parent. A page with an
98
+ * empty child path does not render its own path: Vue Router selects the empty child page there. A page path or alias
99
+ * that rou3 cannot read exactly becomes a wider pattern, as Nuxt does for the route rules of `defineRouteRules()`.
100
+ */
101
+ function pageTargets(pages, toPatterns, prefixes = ["/"], inherited) {
102
+ const targets = [];
103
+ for (const page of pages) {
104
+ const auth = page.meta?.auth === void 0 ? inherited : page.meta.auth;
105
+ const paths = [page.path, ...[page.alias ?? []].flat()].flatMap((path) => path.startsWith("/") ? [path] : prefixes.map((prefix) => joinPagePath(prefix, path)));
106
+ if (!page.children?.some((child) => child.path === "")) for (const path of paths) for (const pattern of toPatterns(path)) {
107
+ targets.push({
108
+ pattern,
109
+ path,
110
+ auth,
111
+ payload: false
112
+ });
113
+ const payload = payloadPattern(pattern);
114
+ if (payload) targets.push({
115
+ pattern: payload,
116
+ path,
117
+ auth,
118
+ payload: true
119
+ });
120
+ }
121
+ if (page.children?.length) targets.push(...pageTargets(page.children, toPatterns, paths, auth));
122
+ }
123
+ return targets;
124
+ }
125
+ /**
126
+ * Stops the build when a route rule caches or prerenders a page that `definePageMeta({ auth })` or `access.pages`
127
+ * guards, or its payload.
128
+ * The page guard runs when the server renders the page, so a cached page keeps the render, or the redirect, of one
129
+ * visitor and serves it to all visitors. The check reads `auth` only when Nuxt reads it at build time, that is when
130
+ * `definePageMeta()` sets it to a literal value.
131
+ *
132
+ * A rule that caches does not count when it keeps no guarded response:
133
+ * - the rule key is the static path of a public page, or the payload of that path. Vue Router selects a static page
134
+ * before a dynamic page. A public page with a dynamic path does not exempt a rule, because rou3 can read its path
135
+ * only as a wider pattern, or
136
+ * - the server does not render the cached paths, because `ssr: false` applies on them for the request method.
137
+ */
138
+ async function assertNoCachedPageGuards(pages, routeRules, options = {}) {
139
+ if (!pages.length || !Object.keys(routeRules).length) return;
140
+ const [{ vueRouterToRou3 }, { compareRoutes, routesOverlap }] = await Promise.all([import("unrouting"), import("rou3")]);
141
+ const normalize = (pattern) => normalizePattern(pattern, options.sensitive);
142
+ const targets = pageTargets(pages, (path) => vueRouterToRou3(path, { collapse: true }).patterns.map(normalize));
143
+ const covers = (pattern, other) => ["equal", "superset"].includes(compareRoutes(pattern, other));
144
+ const accessPages = Object.entries(options.accessPages ?? {}).flatMap(([key, mode]) => {
145
+ const pattern = normalize(key);
146
+ const payload = payloadPattern(pattern);
147
+ return [pattern, ...payload ? [payload] : []].map((paths) => ({
148
+ key,
149
+ pattern,
150
+ paths,
151
+ mode
152
+ }));
153
+ });
154
+ const accessGuards = accessPages.filter((page) => page.mode);
155
+ for (const target of targets) {
156
+ if (target.auth !== void 0) continue;
157
+ const on = accessGuards.filter((guard) => routesOverlap(guard.paths, target.pattern));
158
+ const source = on.find((guard) => guard.mode === "user") ?? on[0];
159
+ if (!source) continue;
160
+ target.auth = source.mode;
161
+ target.accessPage = source.key;
162
+ }
163
+ const guards = targets.filter((target) => isGuarded(target.auth));
164
+ if (!guards.length) return;
165
+ const open = new Set(targets.filter((target) => !isGuarded(target.auth) && isStaticPath(target.path)).map((target) => target.pattern));
166
+ const findCachingRule = await createCachingRouteRuleFinder(routeRules, normalize);
167
+ const mergesAfter = (on, off) => {
168
+ const relation = compareRoutes(on.pattern, off.pattern);
169
+ return relation !== "superset" && (relation !== "equal" || methodOrder.indexOf(on.method) > methodOrder.indexOf(off.method));
170
+ };
171
+ for (const guard of guards) {
172
+ const exempt = (entry, applied, name) => {
173
+ if (open.has(entry.pattern) && entry.pattern !== guard.pattern) return true;
174
+ if (guard.accessPage) {
175
+ const on = accessGuards.filter((on) => routesOverlap(on.paths, entry.pattern) && routesOverlap(on.paths, guard.pattern));
176
+ const pages = [payloadPages(entry.pattern), [guard.payload ? parentPath(guard.pattern) : guard.pattern]];
177
+ const unguards = (off) => off.mode === false || off.mode === "guest" && name === "prerender";
178
+ if (!on.length || accessPages.some((off) => unguards(off) && pages.some((paths) => paths.every((path) => covers(off.pattern, path))) && on.every((on) => on.key === off.key || accessPageBeats(off.pattern, on.pattern)))) return true;
179
+ }
180
+ return applied.some((off) => off.rules.ssr === false && (covers(off.pattern, entry.pattern) || covers(off.pattern, guard.pattern)) && !applied.some((on) => on.rules.ssr === true && routesOverlap(on.pattern, entry.pattern) && routesOverlap(on.pattern, guard.pattern) && mergesAfter(on, off)));
181
+ };
182
+ const cached = findCachingRule(guard.pattern, {
183
+ names: isGuestGuard(guard.auth) ? guestCachingRuleNames : cachingRuleNames,
184
+ exempt
185
+ });
186
+ if (!cached) continue;
187
+ throw authErrorDiagnostics.AUTH_GUARDED_PAGE_CACHED({ message: `[vitehub] Route rule ${JSON.stringify(cached.key)} sets \`${cached.name}\` on ${cached.method} requests to the ${guard.payload ? "payload of the " : ""}page ${JSON.stringify(guard.path)}, which ${guard.accessPage ? `\`access.pages\` ${JSON.stringify(guard.accessPage)}` : "`definePageMeta({ auth })`"} guards. A cached or prerendered page is rendered for one visitor and served to all visitors.` });
188
+ }
189
+ }
190
+ /**
191
+ * Stops the build when an `access.pages` `'user'` pattern guards the sign-in page, or the `redirectTo` page of a page
192
+ * guard. The guard sends signed-out visitors there, then answers 401 because the page needs a session, so they can never
193
+ * sign in. `definePageMeta({ auth })` of the page wins over `access.pages`, when Nuxt reads it at build time.
194
+ */
195
+ async function assertSignInPagesOpen(pages, signInPage, options = {}) {
196
+ const accessPages = options.accessPages;
197
+ if (!accessPages || !Object.values(accessPages).includes("user")) return;
198
+ const [{ createRouterMatcher, START_LOCATION }, accessPageOf] = await Promise.all([import("vue-router"), createAccessPageMatcher(accessPages, options.sensitive)]);
199
+ const toRoute = (page) => ({
200
+ path: page.path,
201
+ alias: page.alias ?? [],
202
+ name: Symbol(),
203
+ meta: page.meta,
204
+ children: page.children?.map(toRoute) ?? []
205
+ });
206
+ const matcher = createRouterMatcher(pages.map(toRoute), {
207
+ sensitive: options.sensitive,
208
+ strict: options.strict
209
+ });
210
+ const redirects = pageTargets(pages, (path) => [path]).flatMap((target) => {
211
+ if (target.payload || isGuestGuard(target.auth) || typeof target.auth !== "object" || target.auth === null) return [];
212
+ const redirectTo = Reflect.get(target.auth, "redirectTo");
213
+ return typeof redirectTo === "string" ? [{
214
+ path: redirectTo,
215
+ source: `the \`redirectTo\` of the page ${JSON.stringify(target.path)}`
216
+ }] : [];
217
+ });
218
+ for (const { path, source } of [...signInPage ? [{
219
+ path: signInPage,
220
+ source: "`access.signIn`"
221
+ }] : [], ...redirects]) {
222
+ const page = path.replace(/[?#].*$/, "");
223
+ if (!page.startsWith("/") || page.startsWith("//")) continue;
224
+ const key = accessPageOf(page);
225
+ if (key === void 0 || Reflect.get(accessPages, key) !== "user") continue;
226
+ if (matcher.resolve({ path: page }, START_LOCATION).meta.auth !== void 0) continue;
227
+ throw authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: `\`defineAuth()\` access.pages has ${JSON.stringify(key)}: "user", which guards the sign-in page ${JSON.stringify(page)} of ${source}. The page guard sends signed-out visitors there, and they cannot open it. Add ${JSON.stringify(page)}: "guest" or false to access.pages, or set \`definePageMeta({ auth: 'guest' })\` on the page.` });
228
+ }
229
+ }
230
+ //#endregion
7
231
  //#region src/nuxt.ts
8
232
  const composables = [
9
233
  "useAbility",
10
234
  "useAuthClient",
11
235
  "useUserSession"
12
236
  ];
237
+ /** The components of `@vite-hub/auth/vue` that check the rules of `shared/abilities.ts`, by export name. */
238
+ const abilityComponents = ["AuthPermission"];
13
239
  const nitroRegistered = /* @__PURE__ */ new WeakSet();
14
240
  const vueBridgeRegistered = /* @__PURE__ */ new WeakSet();
15
241
  const pageMetaRegistered = /* @__PURE__ */ new WeakSet();
16
242
  const componentsRegistered = /* @__PURE__ */ new WeakSet();
17
243
  const abilitiesWatchRegistered = /* @__PURE__ */ new WeakSet();
18
244
  const manifestRegistered = /* @__PURE__ */ new WeakSet();
245
+ const pageCacheCheckRegistered = /* @__PURE__ */ new WeakSet();
19
246
  /** Better Auth's Vue client file, which `createAuthClient()` imports on first use. */
20
247
  function resolveBetterAuthVueClient() {
21
248
  try {
@@ -24,6 +251,49 @@ function resolveBetterAuthVueClient() {
24
251
  return;
25
252
  }
26
253
  }
254
+ /**
255
+ * Attaches the page guard to the pages of `access.pages` with the `appMiddleware` route rule. Nuxt runs it on the server
256
+ * render and on navigation in the browser. Nuxt merges the rules of all matching patterns and the most specific pattern
257
+ * wins, so each rule sets both modes: `false` and a narrower other mode remove the mode of a wider pattern.
258
+ * `assertAuthPages()` accepts only the patterns that keep this order.
259
+ */
260
+ function guardPages(routeRules, pages) {
261
+ for (const [path, mode] of Object.entries(pages)) {
262
+ const rule = routeRules[path] ??= {};
263
+ rule.appMiddleware = {
264
+ ...appMiddlewareRecord(rule.appMiddleware),
265
+ "vitehub-auth-user": mode === "user",
266
+ "vitehub-auth-guest": mode === "guest"
267
+ };
268
+ }
269
+ }
270
+ /** `appMiddleware` as a record. Nuxt reads a name or a list as `{ [name]: true }`. */
271
+ function appMiddlewareRecord(value) {
272
+ if (typeof value === "string" || Array.isArray(value)) return Object.fromEntries([value].flat().map((name) => [name, true]));
273
+ return typeof value === "object" && value !== null ? value : void 0;
274
+ }
275
+ /**
276
+ * Nuxt merges the `defineRouteRules()` of a page over the rule of each rou3 pattern of the page with `defu`. On the
277
+ * pattern of an `access.pages` key, a name or a list then replaces the guard record, and a record merges with it. Other
278
+ * patterns keep the value of the page, because `defu` joins two lists. A page with an optional parameter has several
279
+ * patterns, and a record of the page would replace a name or a list of the app on the others, so they become records.
280
+ * Keys match the rou3 patterns exactly: Nuxt turns the lists into records before it merges keys that differ only in a
281
+ * parameter name, such as `/team/:id` and `/team/:_0`.
282
+ */
283
+ function expandPageMiddleware(pages, patternsOf, keys, routeRules, prefix = "") {
284
+ for (const page of pages) {
285
+ const middleware = page.rules?.appMiddleware;
286
+ const patterns = patternsOf(prefix + page.path);
287
+ if (page.rules && (typeof middleware === "string" || Array.isArray(middleware)) && patterns.some((pattern) => keys.has(pattern))) {
288
+ page.rules.appMiddleware = appMiddlewareRecord(middleware);
289
+ for (const pattern of patterns) {
290
+ const rule = routeRules[pattern];
291
+ if (typeof rule?.appMiddleware === "string" || Array.isArray(rule?.appMiddleware)) rule.appMiddleware = appMiddlewareRecord(rule.appMiddleware);
292
+ }
293
+ }
294
+ if (page.children) expandPageMiddleware(page.children, patternsOf, keys, routeRules, `${prefix}${page.path}/`);
295
+ }
296
+ }
27
297
  function hubAuthNuxt(options = {}, nuxt) {
28
298
  if (!nuxt) return;
29
299
  nuxt.options.plugins ??= [];
@@ -85,34 +355,45 @@ function hubAuthNuxt(options = {}, nuxt) {
85
355
  }
86
356
  const authConfig = resolveAuthOptions() === false ? void 0 : resolveAuthConfig();
87
357
  const signIn = authConfig?.access.signIn;
358
+ const signInPage = signIn && "provider" in signIn ? null : signIn?.page ?? "/login";
88
359
  nuxt.options.runtimeConfig ??= {};
89
360
  nuxt.options.runtimeConfig.public ??= {};
90
361
  nuxt.options.runtimeConfig.public.vitehubAuth = resolveAuthOptions() === false ? false : {
91
362
  basePath: authConfig?.basePath ?? "/api/auth",
92
- signInPage: signIn && "provider" in signIn ? null : signIn?.page ?? "/login",
363
+ signInPage,
93
364
  afterSignIn: authConfig?.access.afterSignIn ?? "/"
94
365
  };
366
+ const accessPages = authConfig?.access.pages;
367
+ if (accessPages) {
368
+ guardPages(nuxt.options.routeRules ??= {}, accessPages);
369
+ if (nuxt.hook) nuxt.hook("pages:resolved", async (pages) => {
370
+ const { vueRouterToRou3 } = await import("unrouting");
371
+ expandPageMiddleware(pages, (path) => vueRouterToRou3(path, { collapse: true }).patterns, new Set(Object.keys(accessPages)), nuxt.options.routeRules ??= {});
372
+ });
373
+ }
95
374
  if (!pageMetaRegistered.has(nuxt) && nuxt.hook) {
96
375
  pageMetaRegistered.add(nuxt);
97
376
  nuxt.hook("prepare:types", ({ declarations }) => {
98
377
  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}`);
99
378
  });
100
379
  }
101
- if (!componentsRegistered.has(nuxt) && nuxt.hook) {
380
+ if (authConfig?.abilities && !componentsRegistered.has(nuxt) && nuxt.hook) {
102
381
  componentsRegistered.add(nuxt);
103
382
  const filePath = options.importsFrom || "@vite-hub/auth/vue";
383
+ const prefix = authConfig.components?.prefix ?? "";
104
384
  nuxt.hook("components:extend", (components) => {
105
- for (const name of ["Can", "Cannot"]) {
106
- if (components.some((component) => component.pascalName === name)) continue;
385
+ for (const name of abilityComponents) {
386
+ const { kebabName, pascalName } = componentNames(prefix, name);
387
+ if (components.some((component) => component.pascalName === pascalName)) continue;
107
388
  components.push({
108
- chunkName: `components/${name.toLowerCase()}`,
389
+ chunkName: `components/${kebabName}`,
109
390
  export: name,
110
391
  filePath,
111
392
  global: false,
112
- kebabName: name.toLowerCase(),
393
+ kebabName,
113
394
  meta: {},
114
395
  mode: "all",
115
- pascalName: name,
396
+ pascalName,
116
397
  prefetch: false,
117
398
  preload: false,
118
399
  priority: 0,
@@ -131,12 +412,29 @@ function hubAuthNuxt(options = {}, nuxt) {
131
412
  for (const chunk of Object.values(manifest)) chunk.dynamicImports &&= chunk.dynamicImports.filter((id) => !keys.has(id));
132
413
  });
133
414
  }
134
- nuxt.options.imports ??= {};
135
- nuxt.options.imports.imports ??= [];
136
- for (const name of composables) if (!nuxt.options.imports.imports.some((entry) => entry.name === name)) nuxt.options.imports.imports.push({
137
- from: options.importsFrom || "@vite-hub/auth/vue",
138
- name
139
- });
415
+ if (resolveAuthOptions() !== false && !pageCacheCheckRegistered.has(nuxt) && nuxt.hook) {
416
+ pageCacheCheckRegistered.add(nuxt);
417
+ nuxt.options.experimental ??= {};
418
+ const extractionKeys = nuxt.options.experimental.extraPageMetaExtractionKeys ??= [];
419
+ if (!extractionKeys.includes("auth")) extractionKeys.push("auth");
420
+ let pages = [];
421
+ nuxt.hook("pages:resolved", (resolved) => {
422
+ pages = resolved;
423
+ });
424
+ nuxt.hook("nitro:init", (nitro) => {
425
+ nitro.hooks.hook("build:config", async () => {
426
+ const { sensitive, strict } = nuxt.options.router?.options ?? {};
427
+ const options = {
428
+ sensitive,
429
+ strict,
430
+ accessPages: authConfig?.access.pages
431
+ };
432
+ await assertSignInPagesOpen(pages, signInPage, options);
433
+ if (nuxt.options.ssr !== false) await assertNoCachedPageGuards(pages, nitro.options.routeRules, options);
434
+ });
435
+ });
436
+ }
437
+ addNuxtVueImports(nuxt, options.importsFrom || "@vite-hub/auth/vue", composables);
140
438
  if (nuxt.options.dev && options.auth !== false && nuxt.hook && !abilitiesWatchRegistered.has(nuxt)) {
141
439
  abilitiesWatchRegistered.add(nuxt);
142
440
  const files = authAbilitiesCandidates(viteRoot, { serverDirs: resolveNuxtServerDirs(nuxt.options) });
@@ -163,5 +461,28 @@ function hubAuthNuxt(options = {}, nuxt) {
163
461
  nuxt.options.nitro.plugins ??= [];
164
462
  if (!nuxt.options.nitro.plugins.includes(runtimePlugin)) nuxt.options.nitro.plugins.push(runtimePlugin);
165
463
  }
464
+ /**
465
+ * The Nuxt names of a component export under a prefix: the names that `<name>.vue` gets in a directory of
466
+ * `components: [{ path, prefix }]`. As in Nuxt's `resolveComponentNameSegments()`, the prefix words that the name starts
467
+ * with are dropped, so the prefix `MyAuth` gives `MyAuthPermission`.
468
+ *
469
+ * @example
470
+ * componentNames("custom", "AuthPermission") // { kebabName: "custom-auth-permission", pascalName: "CustomAuthPermission" }
471
+ */
472
+ function componentNames(prefix, name) {
473
+ const prefixWords = splitByCase(prefix).filter(Boolean);
474
+ const nameWords = splitByCase(name);
475
+ const nameContent = nameWords.join("/").toLowerCase();
476
+ let kept = prefixWords.length;
477
+ for (let index = prefixWords.length - 1; index >= 0; index--) {
478
+ const overlap = prefixWords.slice(index).join("/").toLowerCase();
479
+ if (nameContent === overlap || nameContent.startsWith(`${overlap}/`)) kept = index;
480
+ }
481
+ const words = [...prefixWords.slice(0, kept), ...nameWords];
482
+ return {
483
+ kebabName: kebabCase(words),
484
+ pascalName: pascalCase(words)
485
+ };
486
+ }
166
487
  //#endregion
167
488
  export { hubAuthNuxt as default };
@@ -0,0 +1,31 @@
1
+ import { t as isRecord } from "./object-Da1zyPCR.js";
2
+ import { n as ownAccessHandlerMeta, r as ownAccessRouteMeta } from "./nitro-kit-32CVgbWS.js";
3
+ //#region src/own-access.ts
4
+ /**
5
+ * The Nitro route `meta` of a handler that checks its own access, such as the ViteHub Console route. The access routes
6
+ * leave a request to the handler that Nitro routed it to when that handler has this meta, whatever its path and method.
7
+ * The exception follows the dispatch, so an app route file on the same path keeps the access routes.
8
+ */
9
+ const authAccessHandlerMeta = ownAccessHandlerMeta;
10
+ function matchedRouteMeta(input) {
11
+ if (!("context" in input) || !isRecord(input.context)) return void 0;
12
+ const route = input.context.matchedRoute;
13
+ return isRecord(route) && isRecord(route.meta) ? route.meta : void 0;
14
+ }
15
+ /** Whether Nitro routed the request event to a handler with `authAccessHandlerMeta`. A plain Request has no route. */
16
+ function routedToAccessHandler(input) {
17
+ return matchedRouteMeta(input)?.vitehubAuthAccess === authAccessHandlerMeta.vitehubAuthAccess;
18
+ }
19
+ /**
20
+ * Whether Nitro routed the request event to a ViteHub route that checks access on every request, such as the Console,
21
+ * Realtime, Comments, a signed Blob link, or the Content GitHub webhook. App middleware that guards the whole app can
22
+ * skip these requests, instead of a list of ViteHub paths. Auth access routes still apply to them, except to the
23
+ * Console. An open route, such as `/_vitehub/browser-errors`, gets `false`. A plain Request has no route, so it gets
24
+ * `false` too.
25
+ */
26
+ function checksOwnAccess(input) {
27
+ if (routedToAccessHandler(input)) return true;
28
+ return matchedRouteMeta(input)?.vitehubOwnAccess === ownAccessRouteMeta.vitehubOwnAccess;
29
+ }
30
+ //#endregion
31
+ export { checksOwnAccess as n, routedToAccessHandler as r, authAccessHandlerMeta as t };
@@ -0,0 +1,20 @@
1
+ import { E as AuthRequestInput } from "./types-gl-myjZc.js";
2
+ //#region src/own-access.d.ts
3
+ /**
4
+ * The Nitro route `meta` of a handler that checks its own access, such as the ViteHub Console route. The access routes
5
+ * leave a request to the handler that Nitro routed it to when that handler has this meta, whatever its path and method.
6
+ * The exception follows the dispatch, so an app route file on the same path keeps the access routes.
7
+ */
8
+ declare const authAccessHandlerMeta: Readonly<{
9
+ vitehubAuthAccess: "handler";
10
+ }>;
11
+ /**
12
+ * Whether Nitro routed the request event to a ViteHub route that checks access on every request, such as the Console,
13
+ * Realtime, Comments, a signed Blob link, or the Content GitHub webhook. App middleware that guards the whole app can
14
+ * skip these requests, instead of a list of ViteHub paths. Auth access routes still apply to them, except to the
15
+ * Console. An open route, such as `/_vitehub/browser-errors`, gets `false`. A plain Request has no route, so it gets
16
+ * `false` too.
17
+ */
18
+ declare function checksOwnAccess(input: AuthRequestInput): boolean;
19
+ //#endregion
20
+ export { checksOwnAccess as n, authAccessHandlerMeta as t };
package/dist/presets.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-uEbxSY2G.js";
2
2
  import { parseDuration } from "@vite-hub/runtime";
3
3
  //#region src/presets.ts
4
4
  const defaultStatelessMaxAge = 604800;
@@ -1,3 +1,3 @@
1
- import { A as authForRequest, r as aggregateAuthEvents, v as listAuthEvents } from "../server-BM-RSf1T.js";
1
+ import { A as authForRequest, r as aggregateAuthEvents, v as listAuthEvents } from "../server-Ci2i6p1S.js";
2
2
  import "../server.js";
3
3
  export { aggregateAuthEvents, authForRequest, listAuthEvents };
@@ -1,4 +1,4 @@
1
- import { t as authForRequest } from "../auth-instance-CmDogt4D.js";
2
- import { g as listAuthEvents, t as aggregateAuthEvents } from "../server-BG_MFd4q.js";
1
+ import { t as authForRequest } from "../auth-instance-zYMjldPG.js";
2
+ import { g as listAuthEvents, t as aggregateAuthEvents } from "../server-CyqLFm3L.js";
3
3
  import "../server.js";
4
4
  export { aggregateAuthEvents, authForRequest, listAuthEvents };
@@ -1,4 +1,4 @@
1
- import { s as AbilityRules } from "../abilities-CbmTAoS_.js";
1
+ import { s as AbilityRules } from "../abilities-9jC7iuN0.js";
2
2
  //#region src/runtime/empty-abilities.d.ts
3
3
  declare const abilities: AbilityRules;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { g as AuthDefinition } from "../types-CruflEFI.js";
1
+ import { _ as AuthDefinition } from "../types-gl-myjZc.js";
2
2
  //#region src/runtime/empty-definition.d.ts
3
3
  declare const definition: AuthDefinition | undefined;
4
4
  export declare function getAuthApp(): object | undefined;
@@ -1,2 +1,3 @@
1
- import { a as setAuthAccessIdentityResolver, i as createLazyAuthAccessHandler, n as authAccessHandlerMeta, o as setAuthRuntimeEnvResolver, r as createAuthAccessRouteMatcher, t as AuthAccessRouteMatch } from "../server-C8TlOrSy.js";
2
- export { AuthAccessRouteMatch, authAccessHandlerMeta, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
1
+ import { t as authAccessHandlerMeta } from "../own-access-CdgEICjO.js";
2
+ import { a as setAuthAccessIdentityResolver, i as createLazyAuthAccessHandler, n as checkBuiltAuthPages, o as setAuthRuntimeEnvResolver, r as createAuthAccessRouteMatcher, t as AuthAccessRouteMatch } from "../server-B-zNtSvm.js";
3
+ export { AuthAccessRouteMatch, authAccessHandlerMeta, checkBuiltAuthPages, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };