@vite-hub/auth 0.3.1 → 0.4.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 (61) hide show
  1. package/README.md +49 -34
  2. package/dist/{abilities-DfAnFYwG.d.ts → abilities-CbmTAoS_.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-CqgBrBfR.js → ability-error-IeZQBr_-.js} +1 -1
  5. package/dist/agent.js +6 -5
  6. package/dist/{auth-instance-CR6b1W80.js → auth-instance-CmDogt4D.js} +20 -13
  7. package/dist/cli.js +1 -1
  8. package/dist/{console-runtime-DTopBP-x.d.ts → console-runtime-D2ai-Et5.d.ts} +1 -1
  9. package/dist/{console-runtime-J9_Vx9pT.js → console-runtime-_LrpyCYY.js} +2 -2
  10. package/dist/console-runtime.d.ts +2 -2
  11. package/dist/console-runtime.js +1 -1
  12. package/dist/console.d.ts +1 -1
  13. package/dist/{database-options-BRNef9oy.js → database-options-DpOVjUti.js} +1 -1
  14. package/dist/{database-schema-options-ENuRMduM.js → database-schema-options-Sk-1Bvyu.js} +1 -1
  15. package/dist/database.d.ts +1 -1
  16. package/dist/database.js +3 -3
  17. package/dist/{definition-CqQMcDEK.js → definition-BCaLA9kW.js} +146 -8
  18. package/dist/{error-diagnostics-C8XtVz0i.js → error-diagnostics-Dymr-S_n.js} +40 -4
  19. package/dist/{events-ByzenEVj.js → events-DCfuicoo.js} +6 -14
  20. package/dist/forward.js +1 -1
  21. package/dist/index.d.ts +3 -8
  22. package/dist/index.js +3 -3
  23. package/dist/internal/server.d.ts +3 -3
  24. package/dist/internal/server.js +6 -858
  25. package/dist/mcp-config-DRRlCAWN.js +18 -0
  26. package/dist/mcp-token-CpxLyl_p.js +222 -0
  27. package/dist/mcp.d.ts +96 -85
  28. package/dist/mcp.js +3 -184
  29. package/dist/{members-D9lfaEO_.js → members-DdlsS8kJ.js} +5 -5
  30. package/dist/nuxt.d.ts +15 -2
  31. package/dist/nuxt.js +9 -12
  32. package/dist/{presets-BGZi6Dfu.d.ts → presets-CHndEv5i.d.ts} +3 -4
  33. package/dist/presets.d.ts +2 -2
  34. package/dist/presets.js +3 -13
  35. package/dist/runtime/console.d.ts +1 -1
  36. package/dist/runtime/console.js +2 -2
  37. package/dist/runtime/empty-abilities.d.ts +1 -1
  38. package/dist/runtime/empty-definition.d.ts +2 -1
  39. package/dist/runtime/empty-definition.js +2 -1
  40. package/dist/runtime/nuxt.js +2 -2
  41. package/dist/runtime/server.d.ts +1 -1
  42. package/dist/runtime/vue-nuxt.js +15 -7
  43. package/dist/schema.js +1 -1
  44. package/dist/server-BG_MFd4q.js +980 -0
  45. package/dist/{server-C0qnKN2W.d.ts → server-BM-RSf1T.d.ts} +76 -15
  46. package/dist/{server-bQGzVQ--.d.ts → server-C8TlOrSy.d.ts} +3 -3
  47. package/dist/server.d.ts +2 -2
  48. package/dist/server.js +3 -3
  49. package/dist/{session-cookies-BbH3UR2m.js → session-cookies-DVzjOKc7.js} +69 -5
  50. package/dist/{set-cookie-C8NOhdRE.js → set-cookie-DmqWq6kj.js} +1 -1
  51. package/dist/{shared-BwcdRGxD.js → shared-DRtfuFsV.js} +1 -1
  52. package/dist/{table-specs-8gq_FCaq.js → table-specs-CURphR3n.js} +1 -1
  53. package/dist/test.d.ts +1 -1
  54. package/dist/test.js +2 -2
  55. package/dist/{types-CNaeH2Fd.d.ts → types-CruflEFI.d.ts} +62 -43
  56. package/dist/{vite-CV400XXY.js → vite-Dy0Xhq4H.js} +195 -149
  57. package/dist/vite.d.ts +2 -1
  58. package/dist/vite.js +2 -2
  59. package/dist/vue.d.ts +4 -19
  60. package/dist/vue.js +6 -9
  61. package/package.json +9 -9
package/dist/mcp.js CHANGED
@@ -1,44 +1,10 @@
1
+ import { a as pathOf, n as baseScopes, o as stateOf, r as deleteUnusedMcpClients, s as verifyMcpRequest, t as appAuth } from "./mcp-token-CpxLyl_p.js";
1
2
  import { t as isRecord } from "./object-Da1zyPCR.js";
2
- import { l as findAccessPolicyPlugin } from "./members-D9lfaEO_.js";
3
- import { t as authForRequest } from "./auth-instance-CR6b1W80.js";
4
- import { defineErrors } from "@vite-hub/runtime";
3
+ import { r as mcpRegistrationPluginId } from "./mcp-config-DRRlCAWN.js";
5
4
  import { APIError, createAuthMiddleware } from "better-auth/api";
6
- import { verifyJwsAccessToken } from "better-auth/oauth2";
7
5
  import { oauthProvider, oauthProviderAuthServerMetadata, oauthProviderOpenIdConfigMetadata } from "@better-auth/oauth-provider";
8
6
  import { jwt } from "better-auth/plugins";
9
7
  //#region src/mcp.ts
10
- /**
11
- * OAuth 2.1 sign-in for an MCP server of the app, with Better Auth as the authorization server. `mcpOAuth()` adds the
12
- * plugins, `serveMcpOAuthDiscovery()` answers the well-known documents at the origin root, `verifyMcpRequest()` checks the
13
- * access token of a request, and `deleteUnusedMcpClients()` removes registrations that never signed anyone in.
14
- */
15
- const mcpErrors = /*#__PURE__*/ defineErrors({
16
- docs: "https://vitehub.dev/docs/auth/diagnostics",
17
- codes: {
18
- AUTH_MCP_OAUTH_MISSING: {
19
- why: "The Auth has no MCP OAuth: its plugins do not include `oauthProvider()` with `resources`.",
20
- fix: "Add `...mcpOAuth({ resource, loginPage })` from `vite-hub/auth/mcp` to the `plugins` of `defineAuth()`."
21
- },
22
- AUTH_MCP_TOKEN_MISSING: {
23
- why: "The request has no `Authorization: Bearer` access token.",
24
- fix: "Answer `401` with `WWW-Authenticate: Bearer resource_metadata=\"…\"`, so the MCP client starts the OAuth flow."
25
- },
26
- AUTH_MCP_TOKEN_INVALID: {
27
- why: ({ reason }) => `The access token is not valid: ${reason}`,
28
- fix: "Answer `401` with `error=\"invalid_token\"`, so the MCP client signs in again."
29
- },
30
- AUTH_MCP_CLEANUP_FAILED: {
31
- why: "The Auth database could not list or delete OAuth clients.",
32
- fix: "Read `error.cause` for the database error, then run the cleanup again."
33
- }
34
- }
35
- });
36
- const baseScopes = [
37
- "openid",
38
- "profile",
39
- "email",
40
- "offline_access"
41
- ];
42
8
  const registerPath = "/oauth2/register";
43
9
  /** Bounds RFC 7591 client metadata without restricting the private-use redirect schemes of native MCP clients. */
44
10
  function registrationProblem(body, maxBytes) {
@@ -93,7 +59,7 @@ function registrationLimits(options) {
93
59
  }),
94
60
  matcher: (context) => context.path === registerPath
95
61
  }] },
96
- id: "vitehub-mcp-registration",
62
+ id: mcpRegistrationPluginId,
97
63
  async onRequest(request) {
98
64
  if (request.method !== "POST" || !new URL(request.url).pathname.replace(/\/+$/, "").endsWith(registerPath)) return;
99
65
  if (await exceedsBytes(request, maxBytes)) return { response: metadataError(413, "Client metadata is too large.") };
@@ -139,23 +105,6 @@ function mcpOAuth(options) {
139
105
  registrationLimits(options)
140
106
  ];
141
107
  }
142
- async function stateOf(auth) {
143
- const context = await auth.$context;
144
- const plugins = context.options.plugins ?? [];
145
- const provider = plugins.find((plugin) => plugin.id === "oauth-provider")?.options;
146
- const resources = isRecord(provider) && Array.isArray(provider.resources) ? provider.resources.flatMap((entry) => typeof entry === "string" ? [entry] : isRecord(entry) && typeof entry.identifier === "string" ? [entry.identifier] : []) : [];
147
- if (!resources.length) throw mcpErrors.AUTH_MCP_OAUTH_MISSING();
148
- const jwtOptions = plugins.find((plugin) => plugin.id === "jwt")?.options;
149
- const issuer = isRecord(jwtOptions) && isRecord(jwtOptions.jwt) && typeof jwtOptions.jwt.issuer === "string" ? jwtOptions.jwt.issuer : context.baseURL;
150
- const scopes = isRecord(provider) && Array.isArray(provider.scopes) ? provider.scopes.filter((scope) => typeof scope === "string") : baseScopes;
151
- return {
152
- issuer: issuer.replace(/\/+$/, ""),
153
- resources,
154
- scopes
155
- };
156
- }
157
- const pathOf = (url) => new URL(url).pathname.replace(/\/+$/, "");
158
- const appAuth = (request) => authForRequest(request);
159
108
  const discoveryCors = {
160
109
  "access-control-allow-headers": "*",
161
110
  "access-control-allow-methods": "GET, HEAD, OPTIONS",
@@ -219,135 +168,5 @@ async function discoveryDocument(request, document, options) {
219
168
  if (suffix && suffix !== pathOf(state.issuer)) return void 0;
220
169
  return (document === "oauth-authorization-server" ? oauthProviderAuthServerMetadata(auth) : oauthProviderOpenIdConfigMetadata(auth))(request);
221
170
  }
222
- const clockToleranceSeconds = 30;
223
- function banned(user) {
224
- if (user.banned !== true) return false;
225
- const expires = user.banExpires;
226
- const until = expires instanceof Date ? expires.getTime() : typeof expires === "string" || typeof expires === "number" ? new Date(expires).getTime() : NaN;
227
- return Number.isNaN(until) || until > Date.now();
228
- }
229
- /**
230
- * Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
231
- * authorization server. The signature algorithm is pinned to the keys, and the issuer, the audience (the resource), and
232
- * the expiry are checked with 30 seconds of tolerance. The client must still be enabled and, when the token names a
233
- * session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
234
- * use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
235
- * access token it mints. Sender-constrained tokens, including DPoP-bound tokens, are rejected even when presented as
236
- * bearer tokens. It reads only the URL and the headers, so pass the Request of a Fetchable route, H3's `event.req`, or
237
- * any value with `url` and `headers`, and the body stays for the MCP handler. Returns `AUTH_MCP_TOKEN_MISSING` without a
238
- * bearer token and `AUTH_MCP_TOKEN_INVALID` for a token that fails a check. Throws `AUTH_MCP_OAUTH_MISSING` when the Auth has no `mcpOAuth()`.
239
- */
240
- async function verifyMcpRequest(request, options = {}) {
241
- const token = /^Bearer\s+(\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1];
242
- if (!token) return [mcpErrors.AUTH_MCP_TOKEN_MISSING(), void 0];
243
- const auth = options.auth ?? appAuth(request);
244
- const state = await stateOf(auth);
245
- const url = new URL(request.url);
246
- const resource = options.resource ?? state.resources.find((entry) => new URL(entry).origin === url.origin && pathOf(entry) === url.pathname.replace(/\/+$/, ""));
247
- if (!resource) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: `${url.pathname} is not a resource of \`mcpOAuth()\`.` }), void 0];
248
- const jwks = await auth.api.getJwks();
249
- const keys = isRecord(jwks) && Array.isArray(jwks.keys) ? jwks.keys.filter(isRecord) : [];
250
- const algorithms = [...new Set(keys.flatMap((key) => typeof key.alg === "string" ? [key.alg] : []))];
251
- if (!algorithms.length) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the Auth has no signing keys." }), void 0];
252
- let payload;
253
- try {
254
- payload = await verifyJwsAccessToken(token, {
255
- jwksFetch: async () => jwks,
256
- verifyOptions: {
257
- algorithms,
258
- audience: resource,
259
- clockTolerance: clockToleranceSeconds,
260
- issuer: state.issuer,
261
- requiredClaims: ["exp", "sub"]
262
- }
263
- });
264
- } catch (error) {
265
- return [mcpErrors.AUTH_MCP_TOKEN_INVALID({
266
- cause: error,
267
- reason: error instanceof Error ? error.message : "the signature or a claim does not match."
268
- }), void 0];
269
- }
270
- if (payload.cnf !== void 0) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "sender-constrained access tokens are not supported; use a bearer token." }), void 0];
271
- const context = await auth.$context;
272
- const user = await context.internalAdapter.findUserById(String(payload.sub));
273
- if (!isRecord(user) || typeof user.id !== "string" || banned(user)) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the user does not exist or is banned." }), void 0];
274
- const policy = findAccessPolicyPlugin(context.options.plugins);
275
- if (policy && !await policy.allows(user, `mcp:${user.id}`)) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "`access.policy` or `VITEHUB_MEMBERS` does not allow the user." }), void 0];
276
- const clientId = typeof payload.azp === "string" ? payload.azp : typeof payload.client_id === "string" ? payload.client_id : void 0;
277
- const client = clientId ? await context.adapter.findOne({
278
- model: "oauthClient",
279
- where: [{
280
- field: "clientId",
281
- value: clientId
282
- }]
283
- }) : void 0;
284
- if (!isRecord(client) || client.disabled) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the OAuth client does not exist or is disabled." }), void 0];
285
- const scope = payload.scope;
286
- const scopes = typeof scope === "string" ? scope.split(/\s+/).filter(Boolean) : Array.isArray(scope) ? scope.filter((entry) => typeof entry === "string") : [];
287
- if (typeof payload.sid === "string" && !scopes.includes("offline_access")) {
288
- const session = await context.adapter.findOne({
289
- model: "session",
290
- where: [{
291
- field: "id",
292
- value: payload.sid
293
- }]
294
- });
295
- if (!isRecord(session) || !(session.expiresAt instanceof Date) || session.expiresAt.getTime() <= Date.now()) return [mcpErrors.AUTH_MCP_TOKEN_INVALID({ reason: "the session does not exist or has expired." }), void 0];
296
- }
297
- return [void 0, {
298
- clientId,
299
- clientName: typeof client.name === "string" && client.name ? client.name : void 0,
300
- scopes,
301
- user
302
- }];
303
- }
304
- /**
305
- * Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
306
- * token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
307
- * of deleted clients.
308
- */
309
- async function deleteUnusedMcpClients(options = {}) {
310
- const auth = options.auth ?? appAuth(new Request("http://localhost/"));
311
- try {
312
- const { adapter } = await auth.$context;
313
- const cutoff = new Date(Date.now() - (options.olderThan ?? 864e5));
314
- const clients = await adapter.findMany({
315
- limit: options.limit ?? 500,
316
- model: "oauthClient",
317
- where: [{
318
- field: "createdAt",
319
- operator: "lt",
320
- value: cutoff
321
- }]
322
- });
323
- let deleted = 0;
324
- for (const client of clients) {
325
- if (!isRecord(client) || typeof client.clientId !== "string") continue;
326
- const where = [{
327
- field: "clientId",
328
- value: client.clientId
329
- }];
330
- if ((await Promise.all([
331
- "oauthConsent",
332
- "oauthAccessToken",
333
- "oauthRefreshToken"
334
- ].map((model) => adapter.count({
335
- model,
336
- where
337
- })))).some((count) => count > 0)) continue;
338
- await adapter.deleteMany({
339
- model: "oauthClientResource",
340
- where
341
- });
342
- deleted += await adapter.deleteMany({
343
- model: "oauthClient",
344
- where
345
- });
346
- }
347
- return [void 0, { deleted }];
348
- } catch (error) {
349
- return [mcpErrors.AUTH_MCP_CLEANUP_FAILED({ cause: error }), void 0];
350
- }
351
- }
352
171
  //#endregion
353
172
  export { deleteUnusedMcpClients, mcpOAuth, serveMcpOAuthDiscovery, verifyMcpRequest };
@@ -1,10 +1,10 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
2
2
  import { t as authCloudflareEnv } from "./request-z6DHHmrb.js";
3
3
  import { n as adminClaimVariable, t as adminClaimHash } from "./admin-claim-code-CDipqeAU.js";
4
4
  import { n as getAuthRuntimeState } from "./runtime-state-ojQCzKOc.js";
5
5
  import { t as invariant } from "./invariant-D8_xBqmZ.js";
6
- import { a as checkGitHubOrgMember } from "./events-ByzenEVj.js";
7
- import { defineErrors } from "@vite-hub/runtime";
6
+ import { a as checkGitHubOrgMember } from "./events-DCfuicoo.js";
7
+ import { defineErrors, parseDuration } from "@vite-hub/runtime";
8
8
  import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sessionMiddleware } from "better-auth/api";
9
9
  import { createSessionStore, deleteSessionCookie, expireCookie, parseCookies } from "better-auth/cookies";
10
10
  import { createInternalAdapter } from "better-auth/db";
@@ -222,7 +222,7 @@ function createAdminClaimPlugin(hash, plugins) {
222
222
  //#region src/access-policy.ts
223
223
  /** The id of the Better Auth plugin that applies `access.policy` and `VITEHUB_MEMBERS`. `verifyMcpRequest()` finds the policy by it. */
224
224
  const accessPolicyPluginId = "vitehub-access-policy";
225
- const defaultRecheck = 3e5;
225
+ const defaultRecheck = "5m";
226
226
  async function digest(value) {
227
227
  const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
228
228
  return [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
@@ -241,7 +241,7 @@ function withoutSessionCookies(headers, names) {
241
241
  * deletes the session and its cookies, and the request continues signed out.
242
242
  */
243
243
  function createAccessPolicyPlugin({ policy, members }) {
244
- const recheck = policy?.recheck ?? defaultRecheck;
244
+ const recheck = parseDuration(policy?.recheck ?? defaultRecheck, "recheck");
245
245
  const allowedUntil = /* @__PURE__ */ new Map();
246
246
  let auth;
247
247
  const remember = (key) => {
package/dist/nuxt.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { Ct as AuthPageMeta, S as AuthOptions, Tt as AuthRedirects, wt as AuthPageMode } from "./types-CNaeH2Fd.js";
2
+ import { C as AuthOptions } from "./types-CruflEFI.js";
3
3
  import "vite";
4
4
  //#region ../internal/src/build/paths.d.ts
5
5
  interface NuxtLayerDirectoryConfig {
@@ -15,6 +15,19 @@ 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;
29
+ };
30
+ //#endregion
18
31
  //#region src/nuxt.d.ts
19
32
  export interface AuthNuxtModuleOptions {
20
33
  auth?: AuthOptions;
@@ -64,4 +77,4 @@ type NuxtLike = {
64
77
  };
65
78
  export default function hubAuthNuxt(options?: AuthNuxtModuleOptions, nuxt?: NuxtLike): void;
66
79
  //#endregion
67
- export type { AuthPageMeta, AuthPageMode, AuthRedirects };
80
+ export type { AuthPageMeta, AuthPageMode };
package/dist/nuxt.js CHANGED
@@ -1,5 +1,5 @@
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";
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";
3
3
  import { realpathSync } from "node:fs";
4
4
  import { dirname, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -8,7 +8,6 @@ import { createEnvImportAliases, hubEnv } from "@vite-hub/env/vite";
8
8
  const composables = [
9
9
  "useAbility",
10
10
  "useAuthClient",
11
- "useSession",
12
11
  "useUserSession"
13
12
  ];
14
13
  const nitroRegistered = /* @__PURE__ */ new WeakSet();
@@ -68,7 +67,7 @@ function hubAuthNuxt(options = {}, nuxt) {
68
67
  const authConfig = resolveAuthConfig();
69
68
  if (authConfig) nitroConfig.alias = {
70
69
  ...nitroConfig.alias,
71
- "#vitehub/auth/definition": authConfig.definition.handler,
70
+ "#vitehub/auth/definition": await writeNuxtAuthDefinition(viteRoot, authConfig),
72
71
  ...authConfig.abilities ? { "#vitehub/auth/abilities": authConfig.abilities } : {}
73
72
  };
74
73
  Object.assign(nitroConfig, createAuthNitroConfig(authPlugin, {
@@ -84,16 +83,14 @@ function hubAuthNuxt(options = {}, nuxt) {
84
83
  ensureVueRuntimePlugin();
85
84
  });
86
85
  }
87
- const authOptions = resolveAuthOptions();
88
- const redirects = authOptions ? authOptions.redirects : void 0;
86
+ const authConfig = resolveAuthOptions() === false ? void 0 : resolveAuthConfig();
87
+ const signIn = authConfig?.access.signIn;
89
88
  nuxt.options.runtimeConfig ??= {};
90
89
  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
- }
90
+ nuxt.options.runtimeConfig.public.vitehubAuth = resolveAuthOptions() === false ? false : {
91
+ basePath: authConfig?.basePath ?? "/api/auth",
92
+ signInPage: signIn && "provider" in signIn ? null : signIn?.page ?? "/login",
93
+ afterSignIn: authConfig?.access.afterSignIn ?? "/"
97
94
  };
98
95
  if (!pageMetaRegistered.has(nuxt) && nuxt.hook) {
99
96
  pageMetaRegistered.add(nuxt);
@@ -1,12 +1,11 @@
1
+ import { Duration } from "@vite-hub/runtime";
1
2
  //#region src/presets.d.ts
2
- /** A duration such as `"30m"`, `"12h"`, `"7d"`, or `"2w"`. */
3
- type AuthDuration = `${number}${"s" | "m" | "h" | "d" | "w"}`;
4
3
  interface AuthStatelessPresetOptions {
5
4
  /**
6
5
  * How long a session lasts after sign-in, in seconds or as a duration such as `"7d"`.
7
6
  * The session cookie and the encrypted session data use the same age. Defaults to 7 days.
8
7
  */
9
- maxAge?: number | AuthDuration;
8
+ maxAge?: number | Duration;
10
9
  }
11
10
  /** Sessions in encrypted cookies, with no database. Create it with `stateless()`. */
12
11
  interface AuthStatelessPreset {
@@ -22,4 +21,4 @@ type AuthPreset = AuthStatelessPreset;
22
21
  */
23
22
  declare function stateless(options?: AuthStatelessPresetOptions): AuthStatelessPreset;
24
23
  //#endregion
25
- export { stateless as a, AuthStatelessPresetOptions as i, AuthPreset as n, AuthStatelessPreset as r, AuthDuration as t };
24
+ 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 { a as stateless, i as AuthStatelessPresetOptions, n as AuthPreset, r as AuthStatelessPreset, t as AuthDuration } from "./presets-BGZi6Dfu.js";
2
- export { AuthDuration, AuthPreset, AuthStatelessPreset, AuthStatelessPresetOptions, stateless };
1
+ import { i as stateless, n as AuthStatelessPreset, r as AuthStatelessPresetOptions, t as AuthPreset } from "./presets-CHndEv5i.js";
2
+ export { AuthPreset, AuthStatelessPreset, AuthStatelessPresetOptions, stateless };
package/dist/presets.js CHANGED
@@ -1,19 +1,9 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-Dymr-S_n.js";
2
+ import { parseDuration } from "@vite-hub/runtime";
2
3
  //#region src/presets.ts
3
- const durationUnits = {
4
- s: 1,
5
- m: 60,
6
- h: 3600,
7
- d: 86400,
8
- w: 604800
9
- };
10
4
  const defaultStatelessMaxAge = 604800;
11
5
  function durationSeconds(value) {
12
- if (typeof value === "number") return Number.isSafeInteger(value) && value > 0 ? value : void 0;
13
- if (typeof value !== "string") return;
14
- const match = /^(\d+(?:\.\d+)?)(s|m|h|d|w)$/.exec(value.trim());
15
- if (!match) return;
16
- const seconds = Math.round(Number(match[1]) * durationUnits[match[2]]);
6
+ const seconds = typeof value === "string" ? Math.round(parseDuration(value, "maxAge") / 1e3) : value;
17
7
  return Number.isSafeInteger(seconds) && seconds > 0 ? seconds : void 0;
18
8
  }
19
9
  /**
@@ -1,3 +1,3 @@
1
- import { k as authForRequest, n as aggregateAuthEvents, v as listAuthEvents } from "../server-C0qnKN2W.js";
1
+ import { A as authForRequest, r as aggregateAuthEvents, v as listAuthEvents } from "../server-BM-RSf1T.js";
2
2
  import "../server.js";
3
3
  export { aggregateAuthEvents, authForRequest, listAuthEvents };
@@ -1,4 +1,4 @@
1
- import { t as authForRequest } from "../auth-instance-CR6b1W80.js";
2
- import { aggregateAuthEvents, listAuthEvents } from "../internal/server.js";
1
+ import { t as authForRequest } from "../auth-instance-CmDogt4D.js";
2
+ import { g as listAuthEvents, t as aggregateAuthEvents } from "../server-BG_MFd4q.js";
3
3
  import "../server.js";
4
4
  export { aggregateAuthEvents, authForRequest, listAuthEvents };
@@ -1,4 +1,4 @@
1
- import { s as AbilityRules } from "../abilities-DfAnFYwG.js";
1
+ import { s as AbilityRules } from "../abilities-CbmTAoS_.js";
2
2
  //#region src/runtime/empty-abilities.d.ts
3
3
  declare const abilities: AbilityRules;
4
4
  //#endregion
@@ -1,5 +1,6 @@
1
- import { g as AuthDefinition } from "../types-CNaeH2Fd.js";
1
+ import { g as AuthDefinition } from "../types-CruflEFI.js";
2
2
  //#region src/runtime/empty-definition.d.ts
3
3
  declare const definition: AuthDefinition | undefined;
4
+ export declare function getAuthApp(): object | undefined;
4
5
  //#endregion
5
6
  export { definition as default };
@@ -1,4 +1,5 @@
1
1
  //#region src/runtime/empty-definition.ts
2
2
  const definition = void 0;
3
+ function getAuthApp() {}
3
4
  //#endregion
4
- export { definition as default };
5
+ export { definition as default, getAuthApp };
@@ -1,9 +1,9 @@
1
- import discoveredDefinition from "#vitehub/auth/definition";
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
4
  //#region src/runtime/nuxt.ts
5
5
  function viteHubAuthNuxtRuntime() {
6
- setAuthRuntimeEnvResolver(useServerEnv, discoveredDefinition);
6
+ setAuthRuntimeEnvResolver(useServerEnv, definitionForApp);
7
7
  }
8
8
  //#endregion
9
9
  export { viteHubAuthNuxtRuntime as default };
@@ -1,2 +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";
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
2
  export { AuthAccessRouteMatch, authAccessHandlerMeta, createAuthAccessRouteMatcher, createLazyAuthAccessHandler, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver };
@@ -1,7 +1,7 @@
1
1
  import { i as resolveAuthMountPath } from "../application-path-DuTpfGFj.js";
2
2
  import "../page-tools-shared-l4eyj53D.js";
3
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";
4
+ import { addRouteMiddleware, createError, defineNuxtPlugin, navigateTo, showError, tryUseNuxtApp, useRequestEvent, useRequestFetch, useRequestURL, useRouter, useRuntimeConfig, useState } from "#app";
5
5
  //#region src/runtime/vue-nuxt.ts
6
6
  const stateKey = "vitehub:auth:session";
7
7
  /**
@@ -94,26 +94,34 @@ const viteHubAuthPlugin = defineNuxtPlugin({
94
94
  if (!("window" in globalThis)) setRequestFetchResolver(currentRequestFetch);
95
95
  const runtimeConfig = useRuntimeConfig();
96
96
  const config = runtimeConfig.public?.vitehubAuth;
97
- const redirects = (config || void 0)?.redirects ?? {};
97
+ const signInPage = config ? config.signInPage : "/login";
98
+ const afterSignIn = (config || void 0)?.afterSignIn ?? "/";
98
99
  /** The page guard of `to`: where a visitor goes, or nothing when the page has no guard. */
99
100
  const guardOf = (to) => {
100
101
  const meta = to.meta.auth;
101
102
  if (config === false || meta === void 0 || meta === false) return;
102
103
  const mode = typeof meta === "string" ? meta : meta === true ? "user" : meta.only ?? "user";
103
104
  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",
105
+ return (loggedIn, signedOut = false) => {
106
+ if (mode === "guest") return loggedIn ? navigateTo(redirectTo ?? afterSignIn) : void 0;
107
+ if (loggedIn) return;
108
+ if (redirectTo || signInPage !== null) return navigateTo({
109
+ path: redirectTo ?? signInPage ?? "/login",
108
110
  query: { redirect: to.fullPath }
109
111
  });
112
+ if (signedOut) return showError({
113
+ statusCode: 401,
114
+ statusMessage: "Signed out"
115
+ });
116
+ const signIn = `${resolveAuthMountPath(config?.basePath ?? "/api/auth", runtimeConfig.app?.baseURL)}/sign-in`;
117
+ return navigateTo(`${signIn}?${new URLSearchParams({ redirect: to.fullPath })}`, { external: true });
110
118
  };
111
119
  };
112
120
  if ("window" in globalThis) setSignOutHandler((redirectTo) => nuxtApp.runWithContext(() => {
113
121
  const seed = useState(stateKey, () => void 0);
114
122
  seed.value = null;
115
123
  if (redirectTo) return navigateTo(redirectTo, { external: /^(?:[\w+.-]{2,}:|[/\\]{2})/.test(redirectTo) });
116
- return guardOf(useRouter().currentRoute.value)?.(false);
124
+ return guardOf(useRouter().currentRoute.value)?.(false, true);
117
125
  }));
118
126
  if (config === false) return;
119
127
  const basePath = resolveAuthMountPath(config?.basePath ?? "/api/auth", "window" in globalThis ? runtimeConfig.app?.baseURL : void 0);
package/dist/schema.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as resolveAuthTableSpecs, n as authSqlName, r as authTableSpecs, t as authPluginSchemas } from "./table-specs-8gq_FCaq.js";
1
+ import { i as resolveAuthTableSpecs, n as authSqlName, r as authTableSpecs, t as authPluginSchemas } from "./table-specs-CURphR3n.js";
2
2
  import { sql } from "drizzle-orm";
3
3
  import { bigint, boolean, foreignKey, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
4
4
  import { foreignKey as foreignKey$1, index as index$1, integer as integer$1, sqliteTable, text as text$1, uniqueIndex as uniqueIndex$1 } from "drizzle-orm/sqlite-core";