@vite-hub/auth 0.6.1 → 0.8.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 (78) hide show
  1. package/README.md +86 -12
  2. package/dist/{abilities-BYOcyQ9B.d.ts → abilities-IOwpkcz4.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-D3-u8k1A.js → ability-error-DgR91Jwc.js} +1 -1
  5. package/dist/{access-pages-9aKr6z-k.js → access-pages-C69nwa99.js} +10 -3
  6. package/dist/agent.d.ts +2 -3
  7. package/dist/agent.js +31 -12
  8. package/dist/{auth-instance-BWiRS9QZ.js → auth-instance-WeEK1zDd.js} +174 -64
  9. package/dist/{cli-C5pAfY4x.d.ts → cli-DL7uCAvz.d.ts} +15 -0
  10. package/dist/cli.d.ts +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/client-extension-BgUlm6hy.d.ts +33 -0
  13. package/dist/client-request-B1DCz3a9.js +29 -0
  14. package/dist/{console-runtime-DMH1I2fl.d.ts → console-runtime-C71weVrt.d.ts} +1 -1
  15. package/dist/{console-runtime-CaIXVtB_.js → console-runtime-Dk3j4Jmz.js} +5 -3
  16. package/dist/console-runtime.d.ts +2 -2
  17. package/dist/console-runtime.js +1 -1
  18. package/dist/console.d.ts +1 -1
  19. package/dist/database-options-Cms7BI3c.js +36 -0
  20. package/dist/{database-schema-options-peXHNLkJ.js → database-schema-options-IlHEeUBK.js} +1 -1
  21. package/dist/database.d.ts +1 -1
  22. package/dist/database.js +13 -8
  23. package/dist/{definition-BypPLIbI.js → definition-EpeI5LUG.js} +18 -4
  24. package/dist/{error-diagnostics-CUPwukgE.js → error-diagnostics-DZHuHXPP.js} +46 -5
  25. package/dist/{events-BXU1_9mc.js → events-Cm7Iwq47.js} +1 -1
  26. package/dist/extension-BWmjJhoN.d.ts +59 -0
  27. package/dist/extension-mCx4TrsO.js +133 -0
  28. package/dist/forward.js +1 -1
  29. package/dist/index.d.ts +4 -3
  30. package/dist/index.js +5 -3
  31. package/dist/internal/server.d.ts +3 -3
  32. package/dist/internal/server.js +5 -4
  33. package/dist/{mcp-config-C7srUMIZ.js → mcp-config-Bbr8kQxm.js} +9 -1
  34. package/dist/{mcp-token-CuqdbBy8.js → mcp-token-BleQZK6H.js} +52 -11
  35. package/dist/{mcp-token-CmQbXbTu.d.ts → mcp-token-CxpopXmK.d.ts} +5 -2
  36. package/dist/mcp.d.ts +2 -2
  37. package/dist/mcp.js +27 -6
  38. package/dist/{members-CwPIx10t.js → members-7OMdqha_.js} +188 -152
  39. package/dist/nuxt.d.ts +4 -14
  40. package/dist/nuxt.js +53 -20
  41. package/dist/{own-access-BNcxKrDl.d.ts → own-access-CGiai2L3.d.ts} +1 -1
  42. package/dist/{page-tools-shared-CtoKaNQZ.js → page-tools-shared-dVJBPPTk.js} +8 -0
  43. package/dist/presets.js +1 -1
  44. package/dist/roles-BGi8CyBG.js +17 -0
  45. package/dist/runtime/client-request-plugin.d.ts +2 -1
  46. package/dist/runtime/client-request-plugin.js +8 -5
  47. package/dist/runtime/console.d.ts +1 -1
  48. package/dist/runtime/console.js +2 -2
  49. package/dist/runtime/empty-abilities.d.ts +1 -1
  50. package/dist/runtime/empty-client.d.ts +3 -0
  51. package/dist/runtime/empty-client.js +3 -1
  52. package/dist/runtime/empty-definition.d.ts +1 -1
  53. package/dist/runtime/server.d.ts +4 -3
  54. package/dist/runtime/server.js +7 -4
  55. package/dist/runtime/vue-nuxt.js +27 -11
  56. package/dist/schema.d.ts +32 -14
  57. package/dist/schema.js +21 -14
  58. package/dist/{server-Iru6jcnW.js → server-5t-HA7I1.js} +80 -328
  59. package/dist/{server-C4Kni3Vj.d.ts → server-DyP1v-sZ.d.ts} +39 -7
  60. package/dist/{server-BHniJi2m.d.ts → server-mmp8EfcE.d.ts} +4 -2
  61. package/dist/server.d.ts +6 -3
  62. package/dist/server.js +9 -3
  63. package/dist/{session-cookies-fR6Pv4kD.js → session-cookies-BNtY3hMp.js} +4 -16
  64. package/dist/{set-cookie-DVfi-nJX.js → set-cookie-Bva-P-_C.js} +1 -1
  65. package/dist/{table-specs-CCSY4tiS.js → table-specs-Bm7QJCbu.js} +1 -1
  66. package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-BxKeFD_y.d.ts} +5 -0
  67. package/dist/test.d.ts +1 -1
  68. package/dist/test.js +2 -2
  69. package/dist/{types-DmH31d2t.d.ts → types-CnO5bHEF.d.ts} +40 -6
  70. package/dist/{vite-CpWhT1Wi.js → vite-7I1bJvqA.js} +686 -244
  71. package/dist/vite-CZ_Z6IR3.d.ts +28 -0
  72. package/dist/vite.d.ts +41 -6
  73. package/dist/vite.js +1 -1
  74. package/dist/vue.d.ts +4 -3
  75. package/dist/vue.js +39 -4
  76. package/package.json +9 -8
  77. package/dist/client-request-BzMKtfCY.js +0 -52
  78. package/dist/database-options-B87hDU4j.js +0 -28
@@ -1,28 +1,154 @@
1
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
2
2
  import { t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
3
3
  import { n as adminClaimVariable, t as adminClaimHash } from "./admin-claim-code-C3X_U43x.js";
4
- import { t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
5
4
  import { t as invariant } from "./invariant-Dj2R1eMr.js";
6
- import { a as checkGitHubOrgMember } from "./events-BXU1_9mc.js";
5
+ import { t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
6
+ import { a as checkGitHubOrgMember } from "./events-Cm7Iwq47.js";
7
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
- import { createInternalAdapter } from "better-auth/db";
11
10
  import { decryptOAuthToken } from "better-auth/oauth2";
11
+ import { createInternalAdapter } from "better-auth/db";
12
+ // src/access-policy.ts
13
+ /** The id of the Better Auth plugin that applies `access.policy` and `VITEHUB_MEMBERS`. `verifyMcpRequest()` finds the policy by it. */
14
+ const accessPolicyPluginId = "vitehub-access-policy";
15
+ const defaultRecheck = "5m";
16
+ async function digest(value) {
17
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
18
+ return [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
19
+ }
20
+ /** The request headers without the session cookies, so the endpoint and Better Auth's cookie cache see no session. */
21
+ function withoutSessionCookies(headers, names) {
22
+ const kept = [...parseCookies(headers.get("cookie") ?? "")].filter(([name]) => !names.some((prefix) => name === prefix || name.startsWith(`${prefix}.`)));
23
+ const result = new Headers(headers);
24
+ result.set("cookie", kept.map(([name, value]) => `${name}=${encodeURIComponent(value)}`).join("; "));
25
+ return result;
26
+ }
27
+ /**
28
+ * Applies `VITEHUB_MEMBERS` and `access.policy`. A session is created only when the member list lets the user in and
29
+ * `allow` returns `true`. Each Better Auth request with a session cookie or bearer credential, including every
30
+ * `getSession()` call and so every ViteHub guard, asks again once `recheck` has passed for that session. A refusal
31
+ * deletes the session and its cookies, and the request continues signed out.
32
+ */
33
+ function createAccessPolicyPlugin({ policy, members }) {
34
+ const recheck = parseDuration(policy?.recheck ?? defaultRecheck, "recheck");
35
+ const allowedUntil = /* @__PURE__ */ new Map();
36
+ let auth;
37
+ const remember = (key) => {
38
+ if (recheck <= 0) return;
39
+ const now = Date.now();
40
+ for (const [entry, until] of allowedUntil) if (until <= now) allowedUntil.delete(entry);
41
+ allowedUntil.set(key, now + recheck);
42
+ };
43
+ const askPolicy = async (context, user) => {
44
+ if (!policy) return true;
45
+ const accessToken = async (providerId) => {
46
+ const account = (await context.internalAdapter.findAccounts(user.id)).find((entry) => entry.providerId === providerId);
47
+ return account?.accessToken ? await decryptOAuthToken(account.accessToken, context) : null;
48
+ };
49
+ return await policy.allow({
50
+ user,
51
+ accessToken
52
+ }) === true;
53
+ };
54
+ const ask = async (context, user) => (!members || await members.allows(context, user)) && await askPolicy(context, user);
55
+ const allows = async (user, key, context = auth) => {
56
+ invariant(context, "Better Auth runs `init` of the access policy plugin before a request or token check reaches it");
57
+ const cacheKey = await digest(key);
58
+ if ((allowedUntil.get(cacheKey) ?? 0) > Date.now()) return true;
59
+ allowedUntil.delete(cacheKey);
60
+ const allowed = await ask(context, user);
61
+ if (allowed) remember(cacheKey);
62
+ return allowed;
63
+ };
64
+ const readToken = createAuthMiddleware(async (ctx) => ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret));
65
+ return {
66
+ id: accessPolicyPluginId,
67
+ allows,
68
+ members,
69
+ options: { members: members?.entries ?? [] },
70
+ hooks: { before: [{
71
+ matcher: (context) => Boolean(context.headers?.get("cookie") || context.headers?.get("authorization") || context.request?.headers.get("authorization")),
72
+ handler: createAuthMiddleware(async (ctx) => {
73
+ let headers = ctx.headers;
74
+ const bearer = ctx.context.options.plugins?.find((plugin) => plugin.id === "bearer");
75
+ for (const hook of bearer?.hooks?.before ?? []) {
76
+ if (!hook.matcher(ctx)) continue;
77
+ const result = await hook.handler({
78
+ ...ctx,
79
+ returnHeaders: false
80
+ });
81
+ if (typeof result !== "object" || result === null || !("context" in result)) continue;
82
+ const replacement = result.context;
83
+ if (typeof replacement === "object" && replacement !== null && "headers" in replacement && replacement.headers instanceof Headers) headers = replacement.headers;
84
+ }
85
+ const { sessionData, sessionToken } = ctx.context.authCookies;
86
+ const tokenContext = {
87
+ headers,
88
+ context: ctx.context
89
+ };
90
+ const token = await readToken(tokenContext);
91
+ if (!token) return;
92
+ const stored = await ctx.context.internalAdapter.findSession(token);
93
+ const user = stored && new Date(stored.session.expiresAt).getTime() > Date.now() ? await ctx.context.internalAdapter.findUserById(stored.session.userId) : null;
94
+ if (user && await allows(user, `session:${token}`, ctx.context)) return;
95
+ if (stored) await ctx.context.internalAdapter.deleteSession(token);
96
+ deleteSessionCookie(ctx);
97
+ ctx.context.session = null;
98
+ return { context: { headers: withoutSessionCookies(headers ?? new Headers(), [sessionToken.name, sessionData.name]) } };
99
+ })
100
+ }] },
101
+ init: (context) => {
102
+ auth = context;
103
+ return { options: { databaseHooks: {
104
+ ...members?.databaseHooks(context),
105
+ session: { create: {
106
+ before: async (session, endpoint) => {
107
+ const user = await context.internalAdapter.findUserById(session.userId);
108
+ if (!user) return false;
109
+ if (members) try {
110
+ if (!await members.allows(context, user)) throw members.refusal();
111
+ } catch (error) {
112
+ await members.cleanup(context, user.id, endpoint);
113
+ throw error;
114
+ }
115
+ if (!await askPolicy(context, user)) return false;
116
+ },
117
+ after: async (session) => {
118
+ remember(await digest(`session:${session.token}`));
119
+ }
120
+ } }
121
+ } } };
122
+ }
123
+ };
124
+ }
125
+ /** The access policy plugin of an Auth, if it has one. */
126
+ function findAccessPolicyPlugin(plugins) {
127
+ const plugin = plugins?.find((entry) => entry.id === accessPolicyPluginId);
128
+ return plugin && "allows" in plugin && typeof plugin.allows === "function" ? plugin : void 0;
129
+ }
12
130
  // src/admins.ts
13
- /** The variable that lists the provider accounts that get the admin role. */
131
+ /** The variable that lists the provider accounts and verified emails that get the admin role. */
14
132
  const adminsVariable = "VITEHUB_ADMINS";
15
133
  /** The id of the Better Auth plugin that gives the admin role. The Auth Console reads its `options.admins`. */
16
134
  const adminsPluginId = "vitehub-admins";
17
135
  const removedVariable = "VITEHUB_ADMIN_EMAILS";
136
+ const emailVerificationPaths = /* @__PURE__ */ new Set([
137
+ "/verify-email",
138
+ "/email-otp/verify-email",
139
+ "/email-otp/change-email"
140
+ ]);
141
+ const isAdminEmail = (entry) => "email" in entry;
18
142
  function invalidEntry$1(entry, reason) {
19
- return authErrorDiagnostics.AUTH_C0058({ message: `\`${adminsVariable}\` has the entry \`${entry}\`. ${reason} Each entry is \`<provider>:<account id>\`, such as \`github:22072217\`. Find a GitHub account id with \`gh api users/<login> --jq .id\`. For an app with only email and password sign-in, use a claim code.` });
143
+ return authErrorDiagnostics.AUTH_C0058({ message: `\`${adminsVariable}\` has the entry \`${entry}\`. ${reason} Each entry is \`<provider>:<account id>\`, such as \`github:22072217\`, or an email, such as \`ada@example.com\`. Find a GitHub account id with \`gh api users/<login> --jq .id\`.` });
20
144
  }
145
+ const emailPattern = /^[^\s@:,]+@[^\s@:,]+\.[^\s@:,]+$/;
21
146
  function parseEntry$1(entry) {
147
+ if (emailPattern.test(entry)) return { email: entry.toLowerCase() };
22
148
  const separator = entry.indexOf(":");
23
149
  const providerId = separator > 0 ? entry.slice(0, separator).trim().toLowerCase() : "";
24
150
  const accountId = separator > 0 ? entry.slice(separator + 1).trim() : "";
25
- if (entry.includes("@") || providerId === "email" || providerId === "credential") throw invalidEntry$1(entry, "An email does not prove who signs up with it, so an email cannot give the admin role.");
151
+ if (entry.includes("@") || providerId === "email" || providerId === "credential") throw invalidEntry$1(entry, "Write an email without a prefix, such as `ada@example.com`.");
26
152
  if (!providerId || !accountId) throw invalidEntry$1(entry, "It has no provider or no account id.");
27
153
  if (providerId === "github" && !/^\d+$/.test(accountId)) throw invalidEntry$1(entry, "A GitHub entry needs the numeric account id, not the login.");
28
154
  return {
@@ -30,20 +156,20 @@ function parseEntry$1(entry) {
30
156
  accountId
31
157
  };
32
158
  }
33
- /** The accounts in `VITEHUB_ADMINS`, separated by commas. */
159
+ /** The accounts and emails in `VITEHUB_ADMINS`, separated by commas. */
34
160
  function readAdmins(event) {
35
161
  const env = {
36
162
  ...globalThis.process?.env,
37
163
  ...authCloudflareEnv(event)
38
164
  };
39
- if (typeof env[removedVariable] === "string" && env[removedVariable].trim()) throw authErrorDiagnostics.AUTH_C0057({ message: `\`${removedVariable}\` is removed, because an email and password sign-up does not prove that the person owns the email. List the admin's GitHub or other social account in \`${adminsVariable}\`, such as \`${adminsVariable}=github:22072217\`, and unset \`${removedVariable}\`.` });
165
+ if (typeof env[removedVariable] === "string" && env[removedVariable].trim()) throw authErrorDiagnostics.AUTH_C0057({ message: `\`${removedVariable}\` is removed. List the admin's social account or email in \`${adminsVariable}\`, such as \`${adminsVariable}=github:22072217,ada@example.com\`, and unset \`${removedVariable}\`.` });
40
166
  const value = env[adminsVariable];
41
167
  if (typeof value !== "string") return [];
42
168
  const entries = value.split(",").map((entry) => entry.trim()).filter(Boolean).map(parseEntry$1);
43
- return entries.filter((entry, index) => entries.findIndex((other) => other.providerId === entry.providerId && other.accountId === entry.accountId) === index);
169
+ return entries.filter((entry, index) => entries.findIndex((other) => formatAdminEntry(other) === formatAdminEntry(entry)) === index);
44
170
  }
45
- function formatAdminAccount(account) {
46
- return `${account.providerId}:${account.accountId}`;
171
+ function formatAdminEntry(entry) {
172
+ return isAdminEmail(entry) ? entry.email : `${entry.providerId}:${entry.accountId}`;
47
173
  }
48
174
  function adminOption(admin, name) {
49
175
  const options = Reflect.get(admin, "options");
@@ -73,25 +199,32 @@ async function grantAdminRole(context, userId, grant) {
73
199
  return typeof role === "string" && role.split(",").some((name) => name.trim() === grant.role);
74
200
  }
75
201
  /**
76
- * Gives the first admin role of Better Auth's `admin()` plugin to a user with one of `admins` as a linked account.
77
- * It runs when the account is linked and on each sign-in, so an entry added later also works for an existing user.
78
- * The admin role replaces the default role of `admin()` and joins any other role. It never removes another role.
202
+ * Gives the first admin role of Better Auth's `admin()` plugin to a user with one of `admins` as a linked account, or
203
+ * with a listed email that is verified. It runs when an account is linked, when an email is verified, and on each
204
+ * sign-in, so an entry added later also works for an existing user. The admin role replaces the default role of
205
+ * `admin()` and joins any other role. It never removes another role.
79
206
  */
80
207
  function createAdminsPlugin(admins, plugins) {
81
208
  const grant = adminRoleGrant(plugins, adminsVariable);
82
- const listed = (account) => admins.some((entry) => entry.providerId === account.providerId && entry.accountId === account.accountId);
209
+ const listed = (account) => admins.some((entry) => !isAdminEmail(entry) && entry.providerId === account.providerId && entry.accountId === account.accountId);
210
+ const emails = new Set(admins.filter(isAdminEmail).map((entry) => entry.email));
211
+ const verifiedListed = (user) => Boolean(user && user.emailVerified === true && typeof user.email === "string" && emails.has(user.email.toLowerCase()));
83
212
  const linkedAdminContexts = /* @__PURE__ */ new WeakSet();
213
+ const verifiedUsers = /* @__PURE__ */ new WeakMap();
84
214
  return {
85
215
  id: adminsPluginId,
86
216
  options: {
87
- admins: admins.map(formatAdminAccount),
217
+ admins: admins.map(formatAdminEntry),
88
218
  role: grant.role
89
219
  },
90
220
  hooks: { after: [{
91
- matcher: (ctx) => Boolean((ctx.context.newSession || linkedAdminContexts.has(ctx.context)) && ctx.context.options.session?.cookieCache?.enabled),
221
+ matcher: (ctx) => verifiedUsers.has(ctx.context) || Boolean((ctx.context.newSession || linkedAdminContexts.has(ctx.context)) && ctx.context.options.session?.cookieCache?.enabled),
92
222
  handler: createAuthMiddleware(async (ctx) => {
93
223
  const session = ctx.context.newSession ?? await getSessionFromCtx(ctx, { disableRefresh: true });
94
- if (!session) return;
224
+ if (session?.session.impersonatedBy) return;
225
+ const verifiedUserId = verifiedUsers.get(ctx.context);
226
+ if (verifiedUserId && verifiedListed(await ctx.context.internalAdapter.findUserById(verifiedUserId))) await grantAdminRole(ctx.context, verifiedUserId, grant);
227
+ if (!session || !ctx.context.options.session?.cookieCache?.enabled) return;
95
228
  const user = await ctx.context.internalAdapter.findUserById(session.user.id);
96
229
  if (!user || Reflect.get(user, "role") === Reflect.get(session.user, "role")) return;
97
230
  Reflect.set(session.user, "role", Reflect.get(user, "role"));
@@ -103,12 +236,17 @@ function createAdminsPlugin(admins, plugins) {
103
236
  }] },
104
237
  init: (context) => {
105
238
  return { options: { databaseHooks: {
239
+ user: { update: { after: async (user, endpoint) => {
240
+ if (endpoint?.path && emailVerificationPaths.has(endpoint.path) && verifiedListed(user)) verifiedUsers.set(endpoint.context, user.id);
241
+ } } },
106
242
  account: { create: { after: async (account, endpoint) => {
107
243
  if (!listed(account)) return;
108
244
  await grantAdminRole(context, account.userId, grant);
109
245
  if (endpoint) linkedAdminContexts.add(endpoint.context);
110
246
  } } },
111
247
  session: { create: { after: async (session) => {
248
+ if (session.impersonatedBy) return;
249
+ if (emails.size && verifiedListed(await context.internalAdapter.findUserById(session.userId))) return void await grantAdminRole(context, session.userId, grant);
112
250
  if ((await context.internalAdapter.findAccounts(session.userId)).some(listed)) await grantAdminRole(context, session.userId, grant);
113
251
  } } }
114
252
  } } };
@@ -217,124 +355,6 @@ function createAdminClaimPlugin(hash, plugins) {
217
355
  }
218
356
  };
219
357
  }
220
- // src/access-policy.ts
221
- /** The id of the Better Auth plugin that applies `access.policy` and `VITEHUB_MEMBERS`. `verifyMcpRequest()` finds the policy by it. */
222
- const accessPolicyPluginId = "vitehub-access-policy";
223
- const defaultRecheck = "5m";
224
- async function digest(value) {
225
- const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
226
- return [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
227
- }
228
- /** The request headers without the session cookies, so the endpoint and Better Auth's cookie cache see no session. */
229
- function withoutSessionCookies(headers, names) {
230
- const kept = [...parseCookies(headers.get("cookie") ?? "")].filter(([name]) => !names.some((prefix) => name === prefix || name.startsWith(`${prefix}.`)));
231
- const result = new Headers(headers);
232
- result.set("cookie", kept.map(([name, value]) => `${name}=${encodeURIComponent(value)}`).join("; "));
233
- return result;
234
- }
235
- /**
236
- * Applies `VITEHUB_MEMBERS` and `access.policy`. A session is created only when the member list lets the user in and
237
- * `allow` returns `true`. Each Better Auth request with a session cookie or bearer credential, including every
238
- * `getSession()` call and so every ViteHub guard, asks again once `recheck` has passed for that session. A refusal
239
- * deletes the session and its cookies, and the request continues signed out.
240
- */
241
- function createAccessPolicyPlugin({ policy, members }) {
242
- const recheck = parseDuration(policy?.recheck ?? defaultRecheck, "recheck");
243
- const allowedUntil = /* @__PURE__ */ new Map();
244
- let auth;
245
- const remember = (key) => {
246
- if (recheck <= 0) return;
247
- const now = Date.now();
248
- for (const [entry, until] of allowedUntil) if (until <= now) allowedUntil.delete(entry);
249
- allowedUntil.set(key, now + recheck);
250
- };
251
- const askPolicy = async (context, user) => {
252
- if (!policy) return true;
253
- const accessToken = async (providerId) => {
254
- const account = (await context.internalAdapter.findAccounts(user.id)).find((entry) => entry.providerId === providerId);
255
- return account?.accessToken ? await decryptOAuthToken(account.accessToken, context) : null;
256
- };
257
- return await policy.allow({
258
- user,
259
- accessToken
260
- }) === true;
261
- };
262
- const ask = async (context, user) => (!members || await members.allows(context, user)) && await askPolicy(context, user);
263
- const allows = async (user, key, context = auth) => {
264
- invariant(context, "Better Auth runs `init` of the access policy plugin before a request or token check reaches it");
265
- const cacheKey = await digest(key);
266
- if ((allowedUntil.get(cacheKey) ?? 0) > Date.now()) return true;
267
- allowedUntil.delete(cacheKey);
268
- const allowed = await ask(context, user);
269
- if (allowed) remember(cacheKey);
270
- return allowed;
271
- };
272
- const readToken = createAuthMiddleware(async (ctx) => ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret));
273
- return {
274
- id: accessPolicyPluginId,
275
- allows,
276
- members,
277
- options: { members: members?.entries ?? [] },
278
- hooks: { before: [{
279
- matcher: (context) => Boolean(context.headers?.get("cookie") || context.headers?.get("authorization") || context.request?.headers.get("authorization")),
280
- handler: createAuthMiddleware(async (ctx) => {
281
- let headers = ctx.headers;
282
- const bearer = ctx.context.options.plugins?.find((plugin) => plugin.id === "bearer");
283
- for (const hook of bearer?.hooks?.before ?? []) {
284
- if (!hook.matcher(ctx)) continue;
285
- const result = await hook.handler({
286
- ...ctx,
287
- returnHeaders: false
288
- });
289
- if (typeof result !== "object" || result === null || !("context" in result)) continue;
290
- const replacement = result.context;
291
- if (typeof replacement === "object" && replacement !== null && "headers" in replacement && replacement.headers instanceof Headers) headers = replacement.headers;
292
- }
293
- const { sessionData, sessionToken } = ctx.context.authCookies;
294
- const tokenContext = {
295
- headers,
296
- context: ctx.context
297
- };
298
- const token = await readToken(tokenContext);
299
- if (!token) return;
300
- const stored = await ctx.context.internalAdapter.findSession(token);
301
- const user = stored && new Date(stored.session.expiresAt).getTime() > Date.now() ? await ctx.context.internalAdapter.findUserById(stored.session.userId) : null;
302
- if (user && await allows(user, `session:${token}`, ctx.context)) return;
303
- if (stored) await ctx.context.internalAdapter.deleteSession(token);
304
- deleteSessionCookie(ctx);
305
- ctx.context.session = null;
306
- return { context: { headers: withoutSessionCookies(headers ?? new Headers(), [sessionToken.name, sessionData.name]) } };
307
- })
308
- }] },
309
- init: (context) => {
310
- auth = context;
311
- return { options: { databaseHooks: {
312
- ...members?.databaseHooks(context),
313
- session: { create: {
314
- before: async (session, endpoint) => {
315
- const user = await context.internalAdapter.findUserById(session.userId);
316
- if (!user) return false;
317
- if (members) try {
318
- if (!await members.allows(context, user)) throw members.refusal();
319
- } catch (error) {
320
- await members.cleanup(context, user.id, endpoint);
321
- throw error;
322
- }
323
- if (!await askPolicy(context, user)) return false;
324
- },
325
- after: async (session) => {
326
- remember(await digest(`session:${session.token}`));
327
- }
328
- } }
329
- } } };
330
- }
331
- };
332
- }
333
- /** The access policy plugin of an Auth, if it has one. */
334
- function findAccessPolicyPlugin(plugins) {
335
- const plugin = plugins?.find((entry) => entry.id === accessPolicyPluginId);
336
- return plugin && "allows" in plugin && typeof plugin.allows === "function" ? plugin : void 0;
337
- }
338
358
  // src/members.ts
339
359
  const orgCacheMs = 3e5;
340
360
  /** The variable that lists who may sign up and sign in. */
@@ -446,21 +466,38 @@ const unavailable = (error) => new APIError("SERVICE_UNAVAILABLE", {
446
466
  message: error.why
447
467
  });
448
468
  /**
449
- * Builds the check of `VITEHUB_MEMBERS`. The accounts in `VITEHUB_ADMINS` and users with the admin role of `admin()`
450
- * are always members.
469
+ * Builds the check of `VITEHUB_MEMBERS`. The accounts and verified emails in `VITEHUB_ADMINS` and users with the admin
470
+ * role of `admin()` are always members.
451
471
  */
452
472
  function createMembersGate(members, admins, plugins) {
453
- const createdUsers = /* @__PURE__ */ new WeakMap();
473
+ const signUps = /* @__PURE__ */ new WeakMap();
474
+ const signUpOf = (endpoint) => {
475
+ const signUp = signUps.get(endpoint) ?? {
476
+ ids: /* @__PURE__ */ new Set(),
477
+ emails: /* @__PURE__ */ new Set()
478
+ };
479
+ signUps.set(endpoint, signUp);
480
+ return signUp;
481
+ };
482
+ const isSignUp = (endpoint, user) => {
483
+ const signUp = endpoint ? signUps.get(endpoint) : void 0;
484
+ return Boolean(signUp && (signUp.ids.has(user.id) || signUp.emails.has(user.email.toLowerCase())));
485
+ };
454
486
  const cleanup = async (context, userId, endpoint) => {
455
- if (!endpoint || !createdUsers.get(endpoint)?.delete(userId)) return;
487
+ const user = endpoint ? await context.internalAdapter.findUserById(userId) : null;
488
+ if (!endpoint || !user || !isSignUp(endpoint, user)) return;
489
+ const signUp = signUpOf(endpoint);
490
+ signUp.ids.delete(userId);
491
+ signUp.emails.delete(user.email.toLowerCase());
456
492
  await context.internalAdapter.deleteUser(userId);
457
493
  };
458
- const accounts = [...members.flatMap((entry) => entry.kind === "account" ? [entry] : []), ...admins];
494
+ const accounts = [...members.flatMap((entry) => entry.kind === "account" ? [entry] : []), ...admins.flatMap((entry) => "email" in entry ? [] : [entry])];
495
+ const adminEmails = admins.flatMap((entry) => "email" in entry ? [entry.email] : []);
459
496
  const orgs = members.flatMap((entry) => entry.kind === "github-org" ? [entry.org] : []);
460
497
  const adminRole = plugins.some((plugin) => plugin.id === "admin") ? adminRoleGrant(plugins, membersVariable).role : void 0;
461
498
  const emailListed = (email) => {
462
499
  const address = email.toLowerCase();
463
- return members.some((entry) => entry.kind === "email" && entry.email === address || entry.kind === "domain" && address.endsWith(`@${entry.domain}`));
500
+ return adminEmails.includes(address) || members.some((entry) => entry.kind === "email" && entry.email === address || entry.kind === "domain" && address.endsWith(`@${entry.domain}`));
464
501
  };
465
502
  const accountListed = (account) => accounts.some((entry) => entry.providerId === account.providerId && entry.accountId === account.accountId);
466
503
  /** `true` for an active membership of a listed organization, the GitHub outage error, or `false`. */
@@ -505,25 +542,24 @@ function createMembersGate(members, admins, plugins) {
505
542
  refusal: notMember,
506
543
  databaseHooks: (context) => ({
507
544
  user: { create: {
508
- before: async (user) => {
545
+ before: async (user, endpoint) => {
509
546
  if (!emailListed(user.email) && !adminRole && !accounts.length && !orgs.length) throw notMember();
547
+ if (endpoint && typeof user.email === "string") signUpOf(endpoint).emails.add(user.email.toLowerCase());
510
548
  },
511
549
  after: async (user, endpoint) => {
512
- if (!endpoint) return;
513
- const users = createdUsers.get(endpoint) ?? /* @__PURE__ */ new Set();
514
- users.add(user.id);
515
- createdUsers.set(endpoint, users);
550
+ if (endpoint) signUpOf(endpoint).ids.add(user.id);
516
551
  }
517
552
  } },
518
553
  account: { create: { before: async (account, endpoint) => {
519
- if (!endpoint || !createdUsers.get(endpoint)?.has(account.userId)) return;
554
+ if (!endpoint) return;
520
555
  const user = await context.internalAdapter.findUserById(account.userId);
521
- const answer = Boolean(user && (emailListed(user.email) || isAdmin(user))) || accountListed(account) || await orgMember(context, account);
556
+ if (!user || !isSignUp(endpoint, user)) return;
557
+ const answer = emailListed(user.email) || isAdmin(user) || accountListed(account) || await orgMember(context, account);
522
558
  if (answer === true) return;
523
- if (user) await cleanup(context, user.id, endpoint);
559
+ await cleanup(context, user.id, endpoint);
524
560
  throw answer ? unavailable(answer) : notMember();
525
561
  } } }
526
562
  })
527
563
  };
528
564
  }
529
- export { readMembers as a, createAccessPolicyPlugin as c, createAdminClaimPlugin as d, readAdminClaim as f, readAdmins as g, createAdminsPlugin as h, notMemberError as i, findAccessPolicyPlugin as l, adminsVariable as m, createMembersGate as n, withMemberScopes as o, adminsPluginId as p, membersVariable as r, accessPolicyPluginId as s, assertMembersSessionStore as t, adminClaimPluginId as u };
565
+ export { readMembers as a, createAdminClaimPlugin as c, adminsVariable as d, createAdminsPlugin as f, findAccessPolicyPlugin as g, createAccessPolicyPlugin as h, notMemberError as i, readAdminClaim as l, accessPolicyPluginId as m, createMembersGate as n, withMemberScopes as o, readAdmins as p, membersVariable as r, adminClaimPluginId as s, assertMembersSessionStore as t, adminsPluginId as u };
package/dist/nuxt.d.ts CHANGED
@@ -1,18 +1,6 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { Ct as AuthPageMeta, Tt as AuthPages, w as AuthOptions, wt as AuthPageMode } from "./types-DmH31d2t.js";
3
- import "vite";
4
- interface NuxtLayerDirectoryConfig {
5
- rootDir?: string;
6
- serverDir?: string;
7
- srcDir?: string;
8
- }
9
- /** The Nuxt options that locate the server directory of each layer. */
10
- interface NuxtServerDirOptions extends NuxtLayerDirectoryConfig {
11
- _layers?: ReadonlyArray<{
12
- config?: NuxtLayerDirectoryConfig;
13
- cwd?: string;
14
- }>;
15
- }
2
+ import { i as NuxtServerDirOptions, n as VITEHUB_SERVER_DIRS, r as resolveNuxtAuthDiscovery, t as VITEHUB_NUXT_AUTH_DISCOVERY } from "./vite-CZ_Z6IR3.js";
3
+ import { Et as AuthPages, Tt as AuthPageMode, w as AuthOptions, wt as AuthPageMeta } from "./types-CnO5bHEF.js";
16
4
  type VueImport = {
17
5
  as?: string;
18
6
  disabled?: boolean;
@@ -77,6 +65,8 @@ type NuxtLike = {
77
65
  srcDir?: string;
78
66
  ssr?: boolean;
79
67
  vite?: {
68
+ [VITEHUB_NUXT_AUTH_DISCOVERY]?: ReturnType<typeof resolveNuxtAuthDiscovery>;
69
+ [VITEHUB_SERVER_DIRS]?: string[];
80
70
  define?: Record<string, unknown>;
81
71
  plugins?: unknown[];
82
72
  root?: string;
package/dist/nuxt.js CHANGED
@@ -1,6 +1,6 @@
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-CpWhT1Wi.js";
2
- import { i as normalizePagePath, r as createAccessPageMatcher, t as accessPageBeats } from "./access-pages-9aKr6z-k.js";
3
- import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
1
+ import { C as resolveViteHubProjectRoot, S as resolveNuxtServerDirs, _ as createCachingRouteRuleFinder, b as VITEHUB_SERVER_DIRS, c as createAuthNitroConfig, d as resolveAuthViteConfig, g as cachingRuleNames, l as hubAuth, o as authSchemaModule, p as authAbilitiesCandidates, s as authSchemaSpecifiers, u as writeNuxtAuthDefinition, v as methodOrder, x as resolveNuxtAuthDiscovery, y as VITEHUB_NUXT_AUTH_DISCOVERY } from "./vite-7I1bJvqA.js";
2
+ import { a as normalizePagePath, i as isUserPage, r as createAccessPageMatcher, t as accessPageBeats } from "./access-pages-C69nwa99.js";
3
+ import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
4
4
  import { realpathSync } from "node:fs";
5
5
  import { dirname, isAbsolute, relative, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
@@ -154,7 +154,7 @@ async function assertNoCachedPageGuards(pages, routeRules, options = {}) {
154
154
  for (const target of targets) {
155
155
  if (target.auth !== void 0) continue;
156
156
  const on = accessGuards.filter((guard) => routesOverlap(guard.paths, target.pattern));
157
- const source = on.find((guard) => guard.mode === "user") ?? on[0];
157
+ const source = on.find((guard) => isUserPage(guard.mode)) ?? on[0];
158
158
  if (!source) continue;
159
159
  target.auth = source.mode;
160
160
  target.accessPage = source.key;
@@ -193,7 +193,7 @@ async function assertNoCachedPageGuards(pages, routeRules, options = {}) {
193
193
  */
194
194
  async function assertSignInPagesOpen(pages, signInPage, options = {}) {
195
195
  const accessPages = options.accessPages;
196
- if (!accessPages || !Object.values(accessPages).includes("user")) return;
196
+ if (!accessPages || !Object.values(accessPages).some(isUserPage)) return;
197
197
  const [{ createRouterMatcher, START_LOCATION }, accessPageOf] = await Promise.all([import("vue-router"), createAccessPageMatcher(accessPages, options.sensitive)]);
198
198
  const toRoute = (page) => ({
199
199
  path: page.path,
@@ -221,9 +221,9 @@ async function assertSignInPagesOpen(pages, signInPage, options = {}) {
221
221
  const page = path.replace(/[?#].*$/, "");
222
222
  if (!page.startsWith("/") || page.startsWith("//")) continue;
223
223
  const key = accessPageOf(page);
224
- if (key === void 0 || Reflect.get(accessPages, key) !== "user") continue;
224
+ if (key === void 0 || !isUserPage(Reflect.get(accessPages, key))) continue;
225
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.` });
226
+ throw authErrorDiagnostics.AUTH_PAGE_ROUTES_INVALID({ message: `\`defineAuth()\` access.pages has ${JSON.stringify(key)}: ${JSON.stringify(Reflect.get(accessPages, key))}, 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
227
  }
228
228
  }
229
229
  // src/nuxt.ts
@@ -252,19 +252,30 @@ function resolveBetterAuthVueClient() {
252
252
  /**
253
253
  * Attaches the page guard to the pages of `access.pages` with the `appMiddleware` route rule. Nuxt runs it on the server
254
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.
255
+ * wins, so each rule sets every mode: `false` and a narrower other mode remove the mode of a wider pattern.
256
+ * `assertAuthPages()` accepts only the patterns that keep this order. A `{ role }` value gets the middleware
257
+ * `vitehub-auth-role-<i>`, where `i` is the index of its role in `pageRoles`.
257
258
  */
258
- function guardPages(routeRules, pages) {
259
+ function guardPages(routeRules, pages, pageRoles) {
259
260
  for (const [path, mode] of Object.entries(pages)) {
260
261
  const rule = routeRules[path] ??= {};
262
+ const role = typeof mode === "object" ? pageRoleIndex(pageRoles, mode.role) : -1;
261
263
  rule.appMiddleware = {
262
264
  ...appMiddlewareRecord(rule.appMiddleware),
263
265
  "vitehub-auth-user": mode === "user",
264
- "vitehub-auth-guest": mode === "guest"
266
+ "vitehub-auth-guest": mode === "guest",
267
+ ...Object.fromEntries(pageRoles.map((_, index) => [`vitehub-auth-role-${index}`, index === role]))
265
268
  };
266
269
  }
267
270
  }
271
+ function pageRoleIndex(pageRoles, role) {
272
+ return pageRoles.findIndex((other) => JSON.stringify(other) === JSON.stringify(role));
273
+ }
274
+ function pageRolesOf(pages) {
275
+ const roles = [];
276
+ for (const mode of Object.values(pages ?? {})) if (typeof mode === "object" && pageRoleIndex(roles, mode.role) < 0) roles.push(mode.role);
277
+ return roles;
278
+ }
268
279
  /** `appMiddleware` as a record. Nuxt reads a name or a list as `{ [name]: true }`. */
269
280
  function appMiddlewareRecord(value) {
270
281
  if (typeof value === "string" || Array.isArray(value)) return Object.fromEntries([value].flat().map((name) => [name, true]));
@@ -308,6 +319,9 @@ function hubAuthNuxt(options = {}, nuxt) {
308
319
  ensureVueRuntimePlugin();
309
320
  nuxt.options.vite ??= {};
310
321
  nuxt.options.vite.plugins ??= [];
322
+ const nuxtDiscovery = resolveNuxtAuthDiscovery(nuxt.options);
323
+ nuxt.options.vite[VITEHUB_NUXT_AUTH_DISCOVERY] = nuxtDiscovery;
324
+ nuxt.options.vite[VITEHUB_SERVER_DIRS] ??= resolveNuxtServerDirs(nuxt.options);
311
325
  const vitePlugins = nuxt.options.vite.plugins.flat(Infinity);
312
326
  const viteRoot = nuxt.options.vite.root || nuxt.options.rootDir || process.cwd();
313
327
  const configuredEnvProjectRoot = resolve(viteRoot, options.env === false ? "." : options.env?.projectRoot || ".");
@@ -320,14 +334,16 @@ function hubAuthNuxt(options = {}, nuxt) {
320
334
  ...nuxt.options.vite.define,
321
335
  __VITEHUB_AUTH_APP_BASE_URL__: JSON.stringify(nuxt.options.app?.baseURL || "/")
322
336
  };
323
- const authPlugin = vitePlugins.find((plugin) => plugin?.name === "@vite-hub/auth/vite") || hubAuth(options.auth);
337
+ const authPlugin = vitePlugins.find((plugin) => plugin?.name === "@vite-hub/auth/vite") || hubAuth(options.auth, { layerAliases: nuxtDiscovery.layerAliases });
324
338
  if (!vitePlugins.some((plugin) => plugin?.name === "@vite-hub/auth/vite")) nuxt.options.vite.plugins.push(authPlugin);
325
339
  const resolveAuthOptions = () => options.auth;
326
340
  const resolveAuthConfig = () => {
327
- const configRoot = resolve(viteRoot);
328
- const serverDirs = resolveNuxtServerDirs(nuxt.options);
329
- const authOptions = resolveAuthOptions();
330
- return resolveAuthViteConfig(authOptions, configRoot, { serverDirs }) ?? resolveAuthViteConfig(authOptions, resolveViteHubProjectRoot(configRoot), { serverDirs });
341
+ const root = resolve(nuxt.options.rootDir || process.cwd());
342
+ return resolveAuthViteConfig(resolveAuthOptions(), resolve(root, viteRoot), {
343
+ projectRoot: resolveViteHubProjectRoot(root),
344
+ serverDirs: resolveNuxtServerDirs(nuxt.options),
345
+ layerAliases: nuxtDiscovery.layerAliases
346
+ });
331
347
  };
332
348
  if (options.nitro !== false && !nitroRegistered.has(nuxt)) {
333
349
  nitroRegistered.add(nuxt);
@@ -341,7 +357,8 @@ function hubAuthNuxt(options = {}, nuxt) {
341
357
  Object.assign(nitroConfig, createAuthNitroConfig(authPlugin, {
342
358
  nitro: nitroConfig,
343
359
  projectRoot: viteRoot,
344
- serverDirs: resolveNuxtServerDirs(nuxt.options)
360
+ serverDirs: resolveNuxtServerDirs(nuxt.options),
361
+ nuxtDiscovery
345
362
  }));
346
363
  });
347
364
  }
@@ -352,18 +369,34 @@ function hubAuthNuxt(options = {}, nuxt) {
352
369
  });
353
370
  }
354
371
  const authConfig = resolveAuthOptions() === false ? void 0 : resolveAuthConfig();
372
+ if (authConfig?.tables) {
373
+ const schemaAliases = Object.fromEntries(authSchemaSpecifiers.map((specifier) => [specifier, authSchemaModule(authConfig)]));
374
+ nuxt.options.alias = {
375
+ ...nuxt.options.alias,
376
+ ...schemaAliases
377
+ };
378
+ nuxt.options.nitro = {
379
+ ...nuxt.options.nitro,
380
+ alias: {
381
+ ...nuxt.options.nitro?.alias,
382
+ ...schemaAliases
383
+ }
384
+ };
385
+ }
355
386
  const signIn = authConfig?.access.signIn;
356
387
  const signInPage = signIn && "provider" in signIn ? null : signIn?.page ?? "/login";
357
388
  nuxt.options.runtimeConfig ??= {};
358
389
  nuxt.options.runtimeConfig.public ??= {};
390
+ const accessPages = authConfig?.access.pages;
391
+ const pageRoles = pageRolesOf(accessPages);
359
392
  nuxt.options.runtimeConfig.public.vitehubAuth = resolveAuthOptions() === false ? false : {
360
393
  basePath: authConfig?.basePath ?? "/api/auth",
361
394
  signInPage,
362
- afterSignIn: authConfig?.access.afterSignIn ?? "/"
395
+ afterSignIn: authConfig?.access.afterSignIn ?? "/",
396
+ ...pageRoles.length ? { pageRoles } : {}
363
397
  };
364
- const accessPages = authConfig?.access.pages;
365
398
  if (accessPages) {
366
- guardPages(nuxt.options.routeRules ??= {}, accessPages);
399
+ guardPages(nuxt.options.routeRules ??= {}, accessPages, pageRoles);
367
400
  if (nuxt.hook) nuxt.hook("pages:resolved", async (pages) => {
368
401
  const { vueRouterToRou3 } = await import("unrouting");
369
402
  expandPageMiddleware(pages, (path) => vueRouterToRou3(path, { collapse: true }).patterns, new Set(Object.keys(accessPages)), nuxt.options.routeRules ??= {});
@@ -1,4 +1,4 @@
1
- import { E as AuthRequestInput } from "./types-DmH31d2t.js";
1
+ import { E as AuthRequestInput } from "./types-CnO5bHEF.js";
2
2
  /**
3
3
  * The Nitro route `meta` of a handler that checks its own access, such as the ViteHub Console route. The access routes
4
4
  * leave a request to the handler that Nitro routed it to when that handler has this meta, whatever its path and method.