@vite-hub/auth 0.4.1 → 0.5.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 (89) hide show
  1. package/README.md +32 -8
  2. package/dist/{abilities-CbmTAoS_.d.ts → abilities-3L1Y5Pnw.d.ts} +2 -4
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/abilities.js +1 -2
  5. package/dist/{ability-error-IeZQBr_-.js → ability-error-BHhPkrZd.js} +3 -5
  6. package/dist/{ability-error-DcgChwCN.d.ts → ability-error-C1c30O6E.d.ts} +1 -5
  7. package/dist/access-pages-BwImVHN_.js +94 -0
  8. package/dist/{admin-claim-code-CDipqeAU.js → admin-claim-code-C3X_U43x.js} +1 -2
  9. package/dist/agent.d.ts +1 -3
  10. package/dist/agent.js +5 -6
  11. package/dist/{application-path-DuTpfGFj.js → application-path-zKi7NrvK.js} +1 -2
  12. package/dist/{auth-instance-CmDogt4D.js → auth-instance-_J7R9Qs1.js} +239 -50
  13. package/dist/{cli-ubYJpAL_.d.ts → cli-C5pAfY4x.d.ts} +1 -6
  14. package/dist/cli.d.ts +2 -4
  15. package/dist/cli.js +3 -4
  16. package/dist/{console-runtime-D2ai-Et5.d.ts → console-runtime-BP1ZKJB0.d.ts} +13 -13
  17. package/dist/{console-runtime-_LrpyCYY.js → console-runtime-vc3JQEuq.js} +72 -40
  18. package/dist/console-runtime.d.ts +2 -2
  19. package/dist/console-runtime.js +1 -2
  20. package/dist/{console-types-CmmnKGMx.js → console-types-51lkf0lk.js} +1 -2
  21. package/dist/console.d.ts +1 -5
  22. package/dist/console.js +2 -3
  23. package/dist/{database-options-DpOVjUti.js → database-options-DQ-8qYMl.js} +2 -3
  24. package/dist/{database-schema-options-Sk-1Bvyu.js → database-schema-options-CkSeU9V3.js} +2 -3
  25. package/dist/database.d.ts +1 -3
  26. package/dist/database.js +5 -6
  27. package/dist/{definition-BCaLA9kW.js → definition-MDGMNKrK.js} +20 -18
  28. package/dist/{error-diagnostics-Dymr-S_n.js → error-diagnostics-BssJr_2t.js} +9 -4
  29. package/dist/{events-DCfuicoo.js → events-DZqMiae_.js} +4 -6
  30. package/dist/forward.d.ts +1 -3
  31. package/dist/forward.js +2 -3
  32. package/dist/index.d.ts +4 -7
  33. package/dist/index.js +4 -3
  34. package/dist/internal/server.d.ts +4 -4
  35. package/dist/internal/server.js +5 -5
  36. package/dist/{invariant-D8_xBqmZ.js → invariant-Dj2R1eMr.js} +2 -3
  37. package/dist/{mcp-config-DRRlCAWN.js → mcp-config-C7srUMIZ.js} +2 -3
  38. package/dist/{mcp-token-CpxLyl_p.js → mcp-token--KuLYEub.js} +7 -18
  39. package/dist/mcp.d.ts +0 -4
  40. package/dist/mcp.js +4 -5
  41. package/dist/{members-DdlsS8kJ.js → members-D3_Q5XJb.js} +10 -14
  42. package/dist/nitro-kit-Bg4xUZAI.js +43 -0
  43. package/dist/{nuxt-bridge-Cl988STZ.js → nuxt-bridge-pRyfYD5c.js} +1 -2
  44. package/dist/nuxt.d.ts +31 -24
  45. package/dist/nuxt.js +336 -18
  46. package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
  47. package/dist/own-access-C22hSIuF.d.ts +18 -0
  48. package/dist/own-access-DQgqxTbI.js +30 -0
  49. package/dist/{page-tools-shared-l4eyj53D.js → page-tools-shared-CtoKaNQZ.js} +1 -2
  50. package/dist/{presets-CHndEv5i.d.ts → presets-C6AtiRdI.d.ts} +0 -2
  51. package/dist/presets.d.ts +1 -1
  52. package/dist/presets.js +2 -3
  53. package/dist/{request-z6DHHmrb.js → request-Dpq7GO8B.js} +2 -4
  54. package/dist/runtime/console.d.ts +1 -1
  55. package/dist/runtime/console.js +2 -2
  56. package/dist/runtime/empty-abilities.d.ts +1 -3
  57. package/dist/runtime/empty-abilities.js +1 -2
  58. package/dist/runtime/empty-client.d.ts +0 -2
  59. package/dist/runtime/empty-client.js +1 -2
  60. package/dist/runtime/empty-definition.d.ts +1 -3
  61. package/dist/runtime/empty-definition.js +1 -2
  62. package/dist/runtime/nuxt.d.ts +1 -3
  63. package/dist/runtime/nuxt.js +1 -2
  64. package/dist/runtime/server.d.ts +3 -2
  65. package/dist/runtime/server.js +27 -19
  66. package/dist/runtime/vue-nuxt.d.ts +0 -2
  67. package/dist/runtime/vue-nuxt.js +74 -33
  68. package/dist/{runtime-state-ojQCzKOc.js → runtime-state-DtKUfxKq.js} +1 -2
  69. package/dist/schema.d.ts +71 -23
  70. package/dist/schema.js +6 -5
  71. package/dist/{server-BM-RSf1T.d.ts → server-CFWlYQJb.d.ts} +7 -14
  72. package/dist/{server-BG_MFd4q.js → server-D4Hi4TBI.js} +51 -33
  73. package/dist/{server-C8TlOrSy.d.ts → server-DCsgxFPP.d.ts} +9 -14
  74. package/dist/server.d.ts +2 -2
  75. package/dist/server.js +2 -2
  76. package/dist/{session-cookies-DVzjOKc7.js → session-cookies-1FMcMnRh.js} +6 -8
  77. package/dist/{set-cookie-DmqWq6kj.js → set-cookie-DkqM1kvj.js} +3 -5
  78. package/dist/{table-specs-DbXyaXWs.d.ts → table-specs-BLm_Zlss.d.ts} +255 -3
  79. package/dist/{table-specs-CURphR3n.js → table-specs-jw0jjU6l.js} +43 -44
  80. package/dist/test.d.ts +2 -4
  81. package/dist/test.js +3 -4
  82. package/dist/{types-CruflEFI.d.ts → types-BHSgxyvV.d.ts} +50 -11
  83. package/dist/{vite-Dy0Xhq4H.js → vite-D1xC9n1O.js} +365 -152
  84. package/dist/vite.d.ts +7 -14
  85. package/dist/vite.js +1 -2
  86. package/dist/vue.d.ts +17 -72
  87. package/dist/vue.js +25 -73
  88. package/package.json +35 -30
  89. package/dist/shared-DRtfuFsV.js +0 -12
package/dist/nuxt.js CHANGED
@@ -1,21 +1,246 @@
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 { 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-D1xC9n1O.js";
2
+ import { i as normalizePagePath, r as createAccessPageMatcher, t as accessPageBeats } from "./access-pages-BwImVHN_.js";
3
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.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";
7
- //#region src/nuxt.ts
9
+ // ../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
+ // src/page-guard-cache.ts
44
+ /**
45
+ * Nuxt prerenders a page when it builds, without the cookie of a visitor. A guest page then renders for a signed-out
46
+ * visitor, which is correct for every visitor until the browser reads the session: the page guard runs again in the
47
+ * browser and sends a signed-in user away. A cache that renders the page for the first visitor can keep a redirect.
48
+ */
49
+ const guestCachingRuleNames = cachingRuleNames.filter((name) => name !== "prerender");
50
+ /** A child page path is relative to the path of its parent. An empty child path is the parent path. */
51
+ function joinPagePath(prefix, path) {
52
+ if (path.startsWith("/")) return path;
53
+ if (!path) return prefix;
54
+ return `${prefix.replace(/\/$/, "")}/${path}`;
55
+ }
56
+ /** The page guard reads `'guest'` and `{ only: 'guest' }` as a guest page, and every other value as a user page. */
57
+ function isGuestGuard(auth) {
58
+ return auth === "guest" || typeof auth === "object" && auth !== null && Reflect.get(auth, "only") === "guest";
59
+ }
60
+ function isGuarded(auth) {
61
+ return auth !== void 0 && auth !== false;
62
+ }
63
+ /** A static page path has no parameter, no regular expression, no repeat modifier, and no catch-all. */
64
+ function isStaticPath(path) {
65
+ return !/[\\:()*?+]/.test(path);
66
+ }
67
+ /**
68
+ * Nuxt renders the payload of a page at `<page>/_payload.json`. A catch-all pattern already matches the payload paths
69
+ * below it.
70
+ */
71
+ function payloadPattern(pattern) {
72
+ if (/\/\*\*(?::\w+)?$/.test(pattern)) return void 0;
73
+ return `${pattern.replace(/\/$/, "")}/_payload.json`;
74
+ }
75
+ function parentPath(pattern) {
76
+ return pattern.replace(/\/[^/]*$/, "") || "/";
77
+ }
78
+ /**
79
+ * The page paths whose payloads a rou3 pattern matches. A last segment that matches one segment, such as `:file` or
80
+ * `*`, also matches the payload of the parent path.
81
+ */
82
+ function payloadPages(pattern) {
83
+ if (pattern.endsWith("/_payload.json")) return [parentPath(pattern)];
84
+ if (/\/(?:\*|:\w+(?:\([^)]*\))?)$/.test(pattern)) return [pattern, parentPath(pattern)];
85
+ return [pattern];
86
+ }
87
+ /**
88
+ * Normalizes the literal text of a rou3 pattern as Nuxt does for route rules. Parameter names, constraints, and
89
+ * escaped characters are not path text.
90
+ */
91
+ function normalizePattern(pattern, sensitive) {
92
+ return pattern.replace(/\\.|:\w+(?:\([^)]*\))?|[^\\:]+/g, (token) => token[0] === "\\" || token[0] === ":" ? token : normalizePagePath(token, sensitive));
93
+ }
94
+ /**
95
+ * The page and payload patterns of every page, with the `auth` that applies on them. Vue Router merges the meta of a
96
+ * page into the meta of its child pages, so a child page without `auth` has the guard of its parent. A page with an
97
+ * empty child path does not render its own path: Vue Router selects the empty child page there. A page path or alias
98
+ * that rou3 cannot read exactly becomes a wider pattern, as Nuxt does for the route rules of `defineRouteRules()`.
99
+ */
100
+ function pageTargets(pages, toPatterns, prefixes = ["/"], inherited) {
101
+ const targets = [];
102
+ for (const page of pages) {
103
+ const auth = page.meta?.auth === void 0 ? inherited : page.meta.auth;
104
+ const paths = [page.path, ...[page.alias ?? []].flat()].flatMap((path) => path.startsWith("/") ? [path] : prefixes.map((prefix) => joinPagePath(prefix, path)));
105
+ if (!page.children?.some((child) => child.path === "")) for (const path of paths) for (const pattern of toPatterns(path)) {
106
+ targets.push({
107
+ pattern,
108
+ path,
109
+ auth,
110
+ payload: false
111
+ });
112
+ const payload = payloadPattern(pattern);
113
+ if (payload) targets.push({
114
+ pattern: payload,
115
+ path,
116
+ auth,
117
+ payload: true
118
+ });
119
+ }
120
+ if (page.children?.length) targets.push(...pageTargets(page.children, toPatterns, paths, auth));
121
+ }
122
+ return targets;
123
+ }
124
+ /**
125
+ * Stops the build when a route rule caches or prerenders a page that `definePageMeta({ auth })` or `access.pages`
126
+ * guards, or its payload.
127
+ * The page guard runs when the server renders the page, so a cached page keeps the render, or the redirect, of one
128
+ * visitor and serves it to all visitors. The check reads `auth` only when Nuxt reads it at build time, that is when
129
+ * `definePageMeta()` sets it to a literal value.
130
+ *
131
+ * A rule that caches does not count when it keeps no guarded response:
132
+ * - the rule key is the static path of a public page, or the payload of that path. Vue Router selects a static page
133
+ * before a dynamic page. A public page with a dynamic path does not exempt a rule, because rou3 can read its path
134
+ * only as a wider pattern, or
135
+ * - the server does not render the cached paths, because `ssr: false` applies on them for the request method.
136
+ */
137
+ async function assertNoCachedPageGuards(pages, routeRules, options = {}) {
138
+ if (!pages.length || !Object.keys(routeRules).length) return;
139
+ const [{ vueRouterToRou3 }, { compareRoutes, routesOverlap }] = await Promise.all([import("unrouting"), import("rou3")]);
140
+ const normalize = (pattern) => normalizePattern(pattern, options.sensitive);
141
+ const targets = pageTargets(pages, (path) => vueRouterToRou3(path, { collapse: true }).patterns.map(normalize));
142
+ const covers = (pattern, other) => ["equal", "superset"].includes(compareRoutes(pattern, other));
143
+ const accessPages = Object.entries(options.accessPages ?? {}).flatMap(([key, mode]) => {
144
+ const pattern = normalize(key);
145
+ const payload = payloadPattern(pattern);
146
+ return [pattern, ...payload ? [payload] : []].map((paths) => ({
147
+ key,
148
+ pattern,
149
+ paths,
150
+ mode
151
+ }));
152
+ });
153
+ const accessGuards = accessPages.filter((page) => page.mode);
154
+ for (const target of targets) {
155
+ if (target.auth !== void 0) continue;
156
+ const on = accessGuards.filter((guard) => routesOverlap(guard.paths, target.pattern));
157
+ const source = on.find((guard) => guard.mode === "user") ?? on[0];
158
+ if (!source) continue;
159
+ target.auth = source.mode;
160
+ target.accessPage = source.key;
161
+ }
162
+ const guards = targets.filter((target) => isGuarded(target.auth));
163
+ if (!guards.length) return;
164
+ const open = new Set(targets.filter((target) => !isGuarded(target.auth) && isStaticPath(target.path)).map((target) => target.pattern));
165
+ const findCachingRule = await createCachingRouteRuleFinder(routeRules, normalize);
166
+ const mergesAfter = (on, off) => {
167
+ const relation = compareRoutes(on.pattern, off.pattern);
168
+ return relation !== "superset" && (relation !== "equal" || methodOrder.indexOf(on.method) > methodOrder.indexOf(off.method));
169
+ };
170
+ for (const guard of guards) {
171
+ const exempt = (entry, applied, name) => {
172
+ if (open.has(entry.pattern) && entry.pattern !== guard.pattern) return true;
173
+ if (guard.accessPage) {
174
+ const on = accessGuards.filter((on) => routesOverlap(on.paths, entry.pattern) && routesOverlap(on.paths, guard.pattern));
175
+ const pages = [payloadPages(entry.pattern), [guard.payload ? parentPath(guard.pattern) : guard.pattern]];
176
+ const unguards = (off) => off.mode === false || off.mode === "guest" && name === "prerender";
177
+ 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;
178
+ }
179
+ 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)));
180
+ };
181
+ const cached = findCachingRule(guard.pattern, {
182
+ names: isGuestGuard(guard.auth) ? guestCachingRuleNames : cachingRuleNames,
183
+ exempt
184
+ });
185
+ if (!cached) continue;
186
+ 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.` });
187
+ }
188
+ }
189
+ /**
190
+ * Stops the build when an `access.pages` `'user'` pattern guards the sign-in page, or the `redirectTo` page of a page
191
+ * guard. The guard sends signed-out visitors there, then answers 401 because the page needs a session, so they can never
192
+ * sign in. `definePageMeta({ auth })` of the page wins over `access.pages`, when Nuxt reads it at build time.
193
+ */
194
+ async function assertSignInPagesOpen(pages, signInPage, options = {}) {
195
+ const accessPages = options.accessPages;
196
+ if (!accessPages || !Object.values(accessPages).includes("user")) return;
197
+ const [{ createRouterMatcher, START_LOCATION }, accessPageOf] = await Promise.all([import("vue-router"), createAccessPageMatcher(accessPages, options.sensitive)]);
198
+ const toRoute = (page) => ({
199
+ path: page.path,
200
+ alias: page.alias ?? [],
201
+ name: Symbol(),
202
+ meta: page.meta,
203
+ children: page.children?.map(toRoute) ?? []
204
+ });
205
+ const matcher = createRouterMatcher(pages.map(toRoute), {
206
+ sensitive: options.sensitive,
207
+ strict: options.strict
208
+ });
209
+ const redirects = pageTargets(pages, (path) => [path]).flatMap((target) => {
210
+ if (target.payload || isGuestGuard(target.auth) || typeof target.auth !== "object" || target.auth === null) return [];
211
+ const redirectTo = Reflect.get(target.auth, "redirectTo");
212
+ return typeof redirectTo === "string" ? [{
213
+ path: redirectTo,
214
+ source: `the \`redirectTo\` of the page ${JSON.stringify(target.path)}`
215
+ }] : [];
216
+ });
217
+ for (const { path, source } of [...signInPage ? [{
218
+ path: signInPage,
219
+ source: "`access.signIn`"
220
+ }] : [], ...redirects]) {
221
+ const page = path.replace(/[?#].*$/, "");
222
+ if (!page.startsWith("/") || page.startsWith("//")) continue;
223
+ const key = accessPageOf(page);
224
+ if (key === void 0 || Reflect.get(accessPages, key) !== "user") continue;
225
+ if (matcher.resolve({ path: page }, START_LOCATION).meta.auth !== void 0) continue;
226
+ 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.` });
227
+ }
228
+ }
229
+ // src/nuxt.ts
8
230
  const composables = [
9
231
  "useAbility",
10
232
  "useAuthClient",
11
233
  "useUserSession"
12
234
  ];
235
+ /** The components of `@vite-hub/auth/vue` that check the rules of `shared/abilities.ts`, by export name. */
236
+ const abilityComponents = ["AuthPermission"];
13
237
  const nitroRegistered = /* @__PURE__ */ new WeakSet();
14
238
  const vueBridgeRegistered = /* @__PURE__ */ new WeakSet();
15
239
  const pageMetaRegistered = /* @__PURE__ */ new WeakSet();
16
240
  const componentsRegistered = /* @__PURE__ */ new WeakSet();
17
241
  const abilitiesWatchRegistered = /* @__PURE__ */ new WeakSet();
18
242
  const manifestRegistered = /* @__PURE__ */ new WeakSet();
243
+ const pageCacheCheckRegistered = /* @__PURE__ */ new WeakSet();
19
244
  /** Better Auth's Vue client file, which `createAuthClient()` imports on first use. */
20
245
  function resolveBetterAuthVueClient() {
21
246
  try {
@@ -24,6 +249,49 @@ function resolveBetterAuthVueClient() {
24
249
  return;
25
250
  }
26
251
  }
252
+ /**
253
+ * Attaches the page guard to the pages of `access.pages` with the `appMiddleware` route rule. Nuxt runs it on the server
254
+ * render and on navigation in the browser. Nuxt merges the rules of all matching patterns and the most specific pattern
255
+ * wins, so each rule sets both modes: `false` and a narrower other mode remove the mode of a wider pattern.
256
+ * `assertAuthPages()` accepts only the patterns that keep this order.
257
+ */
258
+ function guardPages(routeRules, pages) {
259
+ for (const [path, mode] of Object.entries(pages)) {
260
+ const rule = routeRules[path] ??= {};
261
+ rule.appMiddleware = {
262
+ ...appMiddlewareRecord(rule.appMiddleware),
263
+ "vitehub-auth-user": mode === "user",
264
+ "vitehub-auth-guest": mode === "guest"
265
+ };
266
+ }
267
+ }
268
+ /** `appMiddleware` as a record. Nuxt reads a name or a list as `{ [name]: true }`. */
269
+ function appMiddlewareRecord(value) {
270
+ if (typeof value === "string" || Array.isArray(value)) return Object.fromEntries([value].flat().map((name) => [name, true]));
271
+ return typeof value === "object" && value !== null ? value : void 0;
272
+ }
273
+ /**
274
+ * Nuxt merges the `defineRouteRules()` of a page over the rule of each rou3 pattern of the page with `defu`. On the
275
+ * pattern of an `access.pages` key, a name or a list then replaces the guard record, and a record merges with it. Other
276
+ * patterns keep the value of the page, because `defu` joins two lists. A page with an optional parameter has several
277
+ * patterns, and a record of the page would replace a name or a list of the app on the others, so they become records.
278
+ * Keys match the rou3 patterns exactly: Nuxt turns the lists into records before it merges keys that differ only in a
279
+ * parameter name, such as `/team/:id` and `/team/:_0`.
280
+ */
281
+ function expandPageMiddleware(pages, patternsOf, keys, routeRules, prefix = "") {
282
+ for (const page of pages) {
283
+ const middleware = page.rules?.appMiddleware;
284
+ const patterns = patternsOf(prefix + page.path);
285
+ if (page.rules && (typeof middleware === "string" || Array.isArray(middleware)) && patterns.some((pattern) => keys.has(pattern))) {
286
+ page.rules.appMiddleware = appMiddlewareRecord(middleware);
287
+ for (const pattern of patterns) {
288
+ const rule = routeRules[pattern];
289
+ if (typeof rule?.appMiddleware === "string" || Array.isArray(rule?.appMiddleware)) rule.appMiddleware = appMiddlewareRecord(rule.appMiddleware);
290
+ }
291
+ }
292
+ if (page.children) expandPageMiddleware(page.children, patternsOf, keys, routeRules, `${prefix}${page.path}/`);
293
+ }
294
+ }
27
295
  function hubAuthNuxt(options = {}, nuxt) {
28
296
  if (!nuxt) return;
29
297
  nuxt.options.plugins ??= [];
@@ -85,34 +353,45 @@ function hubAuthNuxt(options = {}, nuxt) {
85
353
  }
86
354
  const authConfig = resolveAuthOptions() === false ? void 0 : resolveAuthConfig();
87
355
  const signIn = authConfig?.access.signIn;
356
+ const signInPage = signIn && "provider" in signIn ? null : signIn?.page ?? "/login";
88
357
  nuxt.options.runtimeConfig ??= {};
89
358
  nuxt.options.runtimeConfig.public ??= {};
90
359
  nuxt.options.runtimeConfig.public.vitehubAuth = resolveAuthOptions() === false ? false : {
91
360
  basePath: authConfig?.basePath ?? "/api/auth",
92
- signInPage: signIn && "provider" in signIn ? null : signIn?.page ?? "/login",
361
+ signInPage,
93
362
  afterSignIn: authConfig?.access.afterSignIn ?? "/"
94
363
  };
364
+ const accessPages = authConfig?.access.pages;
365
+ if (accessPages) {
366
+ guardPages(nuxt.options.routeRules ??= {}, accessPages);
367
+ if (nuxt.hook) nuxt.hook("pages:resolved", async (pages) => {
368
+ const { vueRouterToRou3 } = await import("unrouting");
369
+ expandPageMiddleware(pages, (path) => vueRouterToRou3(path, { collapse: true }).patterns, new Set(Object.keys(accessPages)), nuxt.options.routeRules ??= {});
370
+ });
371
+ }
95
372
  if (!pageMetaRegistered.has(nuxt) && nuxt.hook) {
96
373
  pageMetaRegistered.add(nuxt);
97
374
  nuxt.hook("prepare:types", ({ declarations }) => {
98
375
  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
376
  });
100
377
  }
101
- if (!componentsRegistered.has(nuxt) && nuxt.hook) {
378
+ if (authConfig?.abilities && !componentsRegistered.has(nuxt) && nuxt.hook) {
102
379
  componentsRegistered.add(nuxt);
103
380
  const filePath = options.importsFrom || "@vite-hub/auth/vue";
381
+ const prefix = authConfig.components?.prefix ?? "";
104
382
  nuxt.hook("components:extend", (components) => {
105
- for (const name of ["Can", "Cannot"]) {
106
- if (components.some((component) => component.pascalName === name)) continue;
383
+ for (const name of abilityComponents) {
384
+ const { kebabName, pascalName } = componentNames(prefix, name);
385
+ if (components.some((component) => component.pascalName === pascalName)) continue;
107
386
  components.push({
108
- chunkName: `components/${name.toLowerCase()}`,
387
+ chunkName: `components/${kebabName}`,
109
388
  export: name,
110
389
  filePath,
111
390
  global: false,
112
- kebabName: name.toLowerCase(),
391
+ kebabName,
113
392
  meta: {},
114
393
  mode: "all",
115
- pascalName: name,
394
+ pascalName,
116
395
  prefetch: false,
117
396
  preload: false,
118
397
  priority: 0,
@@ -131,12 +410,29 @@ function hubAuthNuxt(options = {}, nuxt) {
131
410
  for (const chunk of Object.values(manifest)) chunk.dynamicImports &&= chunk.dynamicImports.filter((id) => !keys.has(id));
132
411
  });
133
412
  }
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
- });
413
+ if (resolveAuthOptions() !== false && !pageCacheCheckRegistered.has(nuxt) && nuxt.hook) {
414
+ pageCacheCheckRegistered.add(nuxt);
415
+ nuxt.options.experimental ??= {};
416
+ const extractionKeys = nuxt.options.experimental.extraPageMetaExtractionKeys ??= [];
417
+ if (!extractionKeys.includes("auth")) extractionKeys.push("auth");
418
+ let pages = [];
419
+ nuxt.hook("pages:resolved", (resolved) => {
420
+ pages = resolved;
421
+ });
422
+ nuxt.hook("nitro:init", (nitro) => {
423
+ nitro.hooks.hook("build:config", async () => {
424
+ const { sensitive, strict } = nuxt.options.router?.options ?? {};
425
+ const options = {
426
+ sensitive,
427
+ strict,
428
+ accessPages: authConfig?.access.pages
429
+ };
430
+ await assertSignInPagesOpen(pages, signInPage, options);
431
+ if (nuxt.options.ssr !== false) await assertNoCachedPageGuards(pages, nitro.options.routeRules, options);
432
+ });
433
+ });
434
+ }
435
+ addNuxtVueImports(nuxt, options.importsFrom || "@vite-hub/auth/vue", composables);
140
436
  if (nuxt.options.dev && options.auth !== false && nuxt.hook && !abilitiesWatchRegistered.has(nuxt)) {
141
437
  abilitiesWatchRegistered.add(nuxt);
142
438
  const files = authAbilitiesCandidates(viteRoot, { serverDirs: resolveNuxtServerDirs(nuxt.options) });
@@ -163,5 +459,27 @@ function hubAuthNuxt(options = {}, nuxt) {
163
459
  nuxt.options.nitro.plugins ??= [];
164
460
  if (!nuxt.options.nitro.plugins.includes(runtimePlugin)) nuxt.options.nitro.plugins.push(runtimePlugin);
165
461
  }
166
- //#endregion
462
+ /**
463
+ * The Nuxt names of a component export under a prefix: the names that `<name>.vue` gets in a directory of
464
+ * `components: [{ path, prefix }]`. As in Nuxt's `resolveComponentNameSegments()`, the prefix words that the name starts
465
+ * with are dropped, so the prefix `MyAuth` gives `MyAuthPermission`.
466
+ *
467
+ * @example
468
+ * componentNames("custom", "AuthPermission") // { kebabName: "custom-auth-permission", pascalName: "CustomAuthPermission" }
469
+ */
470
+ function componentNames(prefix, name) {
471
+ const prefixWords = splitByCase(prefix).filter(Boolean);
472
+ const nameWords = splitByCase(name);
473
+ const nameContent = nameWords.join("/").toLowerCase();
474
+ let kept = prefixWords.length;
475
+ for (let index = prefixWords.length - 1; index >= 0; index--) {
476
+ const overlap = prefixWords.slice(index).join("/").toLowerCase();
477
+ if (nameContent === overlap || nameContent.startsWith(`${overlap}/`)) kept = index;
478
+ }
479
+ const words = [...prefixWords.slice(0, kept), ...nameWords];
480
+ return {
481
+ kebabName: kebabCase(words),
482
+ pascalName: pascalCase(words)
483
+ };
484
+ }
167
485
  export { hubAuthNuxt as default };
@@ -1,4 +1,4 @@
1
- //#region ../internal/src/object.ts
1
+ // ../internal/src/object.ts
2
2
  /** A non-null object that is not an array. Functions do not pass. */
3
3
  function isRecord(value) {
4
4
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -7,5 +7,4 @@ function isRecord(value) {
7
7
  function isRecordOrFunction(value) {
8
8
  return Object(value) === value && !Array.isArray(value);
9
9
  }
10
- //#endregion
11
10
  export { isRecordOrFunction as n, isRecord as t };
@@ -0,0 +1,18 @@
1
+ import { E as AuthRequestInput } from "./types-BHSgxyvV.js";
2
+ /**
3
+ * The Nitro route `meta` of a handler that checks its own access, such as the ViteHub Console route. The access routes
4
+ * leave a request to the handler that Nitro routed it to when that handler has this meta, whatever its path and method.
5
+ * The exception follows the dispatch, so an app route file on the same path keeps the access routes.
6
+ */
7
+ declare const authAccessHandlerMeta: Readonly<{
8
+ vitehubAuthAccess: "handler";
9
+ }>;
10
+ /**
11
+ * Whether Nitro routed the request event to a ViteHub route that checks access on every request, such as the Console,
12
+ * Realtime, Comments, a signed Blob link, or the Content GitHub webhook. App middleware that guards the whole app can
13
+ * skip these requests, instead of a list of ViteHub paths. Auth access routes still apply to them, except to the
14
+ * Console. An open route, such as `/_vitehub/browser-errors`, gets `false`. A plain Request has no route, so it gets
15
+ * `false` too.
16
+ */
17
+ declare function checksOwnAccess(input: AuthRequestInput): boolean;
18
+ export { checksOwnAccess as n, authAccessHandlerMeta as t };
@@ -0,0 +1,30 @@
1
+ import { n as ownAccessHandlerMeta, r as ownAccessRouteMeta } from "./nitro-kit-Bg4xUZAI.js";
2
+ import { t as isRecord } from "./object-CAK6UYR5.js";
3
+ // 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
+ export { checksOwnAccess as n, routedToAccessHandler as r, authAccessHandlerMeta as t };
@@ -1,4 +1,4 @@
1
- //#region ../internal/src/runtime/page-tools-shared.ts
1
+ // ../internal/src/runtime/page-tools-shared.ts
2
2
  /**
3
3
  * The cookie that remembers the session route's answer for this browser: `1` when a tool allows the person, `0` when
4
4
  * none does or the person turned the tools off. It is a hint, never a credential, and it is not HttpOnly, because the
@@ -15,5 +15,4 @@ const viteHubSessionMarkerCookie = "vitehub_session";
15
15
  * next page asks the session route again for the new person.
16
16
  */
17
17
  const viteHubPageToolsResetCookie = `${viteHubPageToolsCookie}=; Path=/; Max-Age=0; SameSite=Lax`;
18
- //#endregion
19
18
  export { viteHubPageToolsResetCookie as n, viteHubSessionMarkerCookie as r, viteHubPageToolsCookie as t };
@@ -1,5 +1,4 @@
1
1
  import { Duration } from "@vite-hub/runtime";
2
- //#region src/presets.d.ts
3
2
  interface AuthStatelessPresetOptions {
4
3
  /**
5
4
  * How long a session lasts after sign-in, in seconds or as a duration such as `"7d"`.
@@ -20,5 +19,4 @@ type AuthPreset = AuthStatelessPreset;
20
19
  * replicas and Workers when every instance uses the same secret. Use it with social providers.
21
20
  */
22
21
  declare function stateless(options?: AuthStatelessPresetOptions): AuthStatelessPreset;
23
- //#endregion
24
22
  export { stateless as i, AuthStatelessPreset as n, AuthStatelessPresetOptions as r, AuthPreset as t };
package/dist/presets.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { i as stateless, n as AuthStatelessPreset, r as AuthStatelessPresetOptions, t as AuthPreset } from "./presets-CHndEv5i.js";
1
+ import { i as stateless, n as AuthStatelessPreset, r as AuthStatelessPresetOptions, t as AuthPreset } from "./presets-C6AtiRdI.js";
2
2
  export { AuthPreset, AuthStatelessPreset, AuthStatelessPresetOptions, stateless };
package/dist/presets.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-BssJr_2t.js";
2
2
  import { parseDuration } from "@vite-hub/runtime";
3
- //#region src/presets.ts
3
+ // src/presets.ts
4
4
  const defaultStatelessMaxAge = 604800;
5
5
  function durationSeconds(value) {
6
6
  const seconds = typeof value === "string" ? Math.round(parseDuration(value, "maxAge") / 1e3) : value;
@@ -18,5 +18,4 @@ function stateless(options = {}) {
18
18
  maxAge
19
19
  };
20
20
  }
21
- //#endregion
22
21
  export { stateless };
@@ -1,5 +1,5 @@
1
1
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
2
- //#region ../internal/src/runtime/cloudflare-env-lookup.ts
2
+ // ../internal/src/runtime/cloudflare-env-lookup.ts
3
3
  /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
4
4
  const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
5
5
  let activeEnv;
@@ -13,8 +13,7 @@ function getActiveCloudflareEnv() {
13
13
  const host = globalThis;
14
14
  return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
15
15
  }
16
- //#endregion
17
- //#region src/request.ts
16
+ // src/request.ts
18
17
  function isObjectLike(value) {
19
18
  return value !== null && (typeof value === "object" || typeof value === "function");
20
19
  }
@@ -43,5 +42,4 @@ function authRequestEvent(input) {
43
42
  function authCloudflareEnv(event) {
44
43
  return (event ? getStandardContext(event).runtime?.cloudflare?.env : void 0) ?? getActiveCloudflareEnv();
45
44
  }
46
- //#endregion
47
45
  export { authRequestEvent as n, unwrapAuthRequest as r, authCloudflareEnv as t };
@@ -1,3 +1,3 @@
1
- import { A as authForRequest, r as aggregateAuthEvents, v as listAuthEvents } from "../server-BM-RSf1T.js";
2
1
  import "../server.js";
2
+ import { A as authForRequest, r as aggregateAuthEvents, v as listAuthEvents } from "../server-CFWlYQJb.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 { g as listAuthEvents, t as aggregateAuthEvents } from "../server-D4Hi4TBI.js";
2
+ import { t as authForRequest } from "../auth-instance-_J7R9Qs1.js";
3
3
  import "../server.js";
4
4
  export { aggregateAuthEvents, authForRequest, listAuthEvents };
@@ -1,5 +1,3 @@
1
- import { s as AbilityRules } from "../abilities-CbmTAoS_.js";
2
- //#region src/runtime/empty-abilities.d.ts
1
+ import { s as AbilityRules } from "../abilities-3L1Y5Pnw.js";
3
2
  declare const abilities: AbilityRules;
4
- //#endregion
5
3
  export { abilities as default };
@@ -1,4 +1,3 @@
1
- //#region src/runtime/empty-abilities.ts
1
+ // src/runtime/empty-abilities.ts
2
2
  const abilities = {};
3
- //#endregion
4
3
  export { abilities as default };
@@ -1,6 +1,4 @@
1
1
  import { BetterAuthClientOptions } from "better-auth";
2
- //#region src/runtime/empty-client.d.ts
3
2
  /** The options of the default Auth client when the app has no `auth.client.ts`. */
4
3
  declare const options: BetterAuthClientOptions | undefined;
5
- //#endregion
6
4
  export { options as default };
@@ -1,5 +1,4 @@
1
- //#region src/runtime/empty-client.ts
1
+ // src/runtime/empty-client.ts
2
2
  /** The options of the default Auth client when the app has no `auth.client.ts`. */
3
3
  const options = void 0;
4
- //#endregion
5
4
  export { options as default };
@@ -1,6 +1,4 @@
1
- import { g as AuthDefinition } from "../types-CruflEFI.js";
2
- //#region src/runtime/empty-definition.d.ts
1
+ import { _ as AuthDefinition } from "../types-BHSgxyvV.js";
3
2
  declare const definition: AuthDefinition | undefined;
4
3
  export declare function getAuthApp(): object | undefined;
5
- //#endregion
6
4
  export { definition as default };
@@ -1,5 +1,4 @@
1
- //#region src/runtime/empty-definition.ts
1
+ // src/runtime/empty-definition.ts
2
2
  const definition = void 0;
3
3
  function getAuthApp() {}
4
- //#endregion
5
4
  export { definition as default, getAuthApp };
@@ -1,3 +1 @@
1
- //#region src/runtime/nuxt.d.ts
2
- export default function viteHubAuthNuxtRuntime(): void;
3
- //#endregion
1
+ export default function viteHubAuthNuxtRuntime(): void;
@@ -1,9 +1,8 @@
1
1
  import definitionForApp from "#vitehub/auth/definition";
2
2
  import { useServerEnv } from "#vitehub/env/server";
3
3
  import { setAuthRuntimeEnvResolver } from "@vite-hub/auth/runtime/server";
4
- //#region src/runtime/nuxt.ts
4
+ // src/runtime/nuxt.ts
5
5
  function viteHubAuthNuxtRuntime() {
6
6
  setAuthRuntimeEnvResolver(useServerEnv, definitionForApp);
7
7
  }
8
- //#endregion
9
8
  export { viteHubAuthNuxtRuntime as default };
@@ -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-C22hSIuF.js";
2
+ import { a as setAuthAccessIdentityResolver, i as createLazyAuthAccessHandler, n as checkBuiltAuthPages, o as setAuthRuntimeEnvResolver, r as createAuthAccessRouteMatcher, t as AuthAccessRouteMatch } from "../server-DCsgxFPP.js";
3
+ export { AuthAccessRouteMatch, authAccessHandlerMeta, checkBuiltAuthPages, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };