@vite-hub/auth 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +333 -49
  2. package/dist/abilities-DfAnFYwG.d.ts +93 -0
  3. package/dist/abilities.d.ts +2 -0
  4. package/dist/abilities.js +43 -0
  5. package/dist/ability-error-CqgBrBfR.js +91 -0
  6. package/dist/ability-error-DcgChwCN.d.ts +34 -0
  7. package/dist/admin-claim-code-CDipqeAU.js +22 -0
  8. package/dist/agent.d.ts +5 -5
  9. package/dist/agent.js +17 -9
  10. package/dist/application-path-DuTpfGFj.js +62 -0
  11. package/dist/auth-instance-CR6b1W80.js +1168 -0
  12. package/dist/bun-sqlite.d.ts +8 -0
  13. package/dist/cli-ubYJpAL_.d.ts +163 -0
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.js +47 -7
  16. package/dist/console-runtime-DTopBP-x.d.ts +71 -0
  17. package/dist/console-runtime-J9_Vx9pT.js +1166 -0
  18. package/dist/console-runtime.d.ts +3 -3
  19. package/dist/console-runtime.js +2 -819
  20. package/dist/console.d.ts +215 -3
  21. package/dist/console.js +1 -1
  22. package/dist/database-options-BRNef9oy.js +29 -0
  23. package/dist/database-schema-options-ENuRMduM.js +12 -0
  24. package/dist/database.d.ts +12 -0
  25. package/dist/database.js +45 -0
  26. package/dist/definition-CqQMcDEK.js +280 -0
  27. package/dist/error-diagnostics-C8XtVz0i.js +138 -0
  28. package/dist/{events-P7mI4IQb.js → events-ByzenEVj.js} +122 -4
  29. package/dist/forward.d.ts +50 -0
  30. package/dist/forward.js +120 -0
  31. package/dist/host-declarations.d.ts +2 -1
  32. package/dist/index.d.ts +24 -3
  33. package/dist/index.js +3 -102
  34. package/dist/internal/server.d.ts +5 -0
  35. package/dist/internal/server.js +858 -0
  36. package/dist/invariant-D8_xBqmZ.js +22 -0
  37. package/dist/mcp.d.ts +187 -0
  38. package/dist/mcp.js +353 -0
  39. package/dist/members-D9lfaEO_.js +533 -0
  40. package/dist/nuxt-bridge-Cl988STZ.js +44 -0
  41. package/dist/nuxt.d.ts +13 -5
  42. package/dist/nuxt.js +90 -13
  43. package/dist/object-Da1zyPCR.js +11 -0
  44. package/dist/page-tools-shared-l4eyj53D.js +19 -0
  45. package/dist/presets.js +1 -1
  46. package/dist/request-z6DHHmrb.js +47 -0
  47. package/dist/runtime/console.d.ts +3 -7
  48. package/dist/runtime/console.js +4 -42
  49. package/dist/runtime/empty-abilities.d.ts +5 -0
  50. package/dist/runtime/empty-abilities.js +4 -0
  51. package/dist/runtime/empty-client.d.ts +6 -0
  52. package/dist/runtime/empty-client.js +5 -0
  53. package/dist/runtime/empty-definition.d.ts +1 -1
  54. package/dist/runtime/nuxt.js +1 -1
  55. package/dist/runtime/server.d.ts +2 -0
  56. package/dist/runtime/server.js +77 -0
  57. package/dist/runtime/vue-nuxt.d.ts +3 -2
  58. package/dist/runtime/vue-nuxt.js +157 -5
  59. package/dist/runtime-state-ojQCzKOc.js +25 -0
  60. package/dist/schema.d.ts +137 -0
  61. package/dist/schema.js +147 -0
  62. package/dist/server-C0qnKN2W.d.ts +143 -0
  63. package/dist/server-bQGzVQ--.d.ts +41 -0
  64. package/dist/server.d.ts +3 -2
  65. package/dist/server.js +3 -3
  66. package/dist/session-cookies-BbH3UR2m.js +227 -0
  67. package/dist/{set-cookie-2as_DbHe.js → set-cookie-C8NOhdRE.js} +27 -12
  68. package/dist/{shared-DnpgYiLF.js → shared-BwcdRGxD.js} +2 -5
  69. package/dist/table-specs-8gq_FCaq.js +771 -0
  70. package/dist/table-specs-DbXyaXWs.d.ts +842 -0
  71. package/dist/test.d.ts +26 -0
  72. package/dist/test.js +25 -0
  73. package/dist/{events-BkmK2dFY.d.ts → types-CNaeH2Fd.d.ts} +240 -157
  74. package/dist/vite-CV400XXY.js +1556 -0
  75. package/dist/vite.d.ts +138 -20
  76. package/dist/vite.js +2 -2
  77. package/dist/vue.d.ts +330 -21
  78. package/dist/vue.js +583 -36
  79. package/package.json +84 -15
  80. package/dist/application-path-C290OAIs.js +0 -18
  81. package/dist/cli-mgXvsBtA.d.ts +0 -85
  82. package/dist/console-B7eERmGv.d.ts +0 -180
  83. package/dist/console-runtime-bZQtnX2Y.d.ts +0 -39
  84. package/dist/error-diagnostics-CL0yjHiM.js +0 -79
  85. package/dist/events-config-CjcFOhTE.js +0 -177
  86. package/dist/inspect-DPtsW8dB.d.ts +0 -36
  87. package/dist/server-B7LU19dS.js +0 -1730
  88. package/dist/server-CTD_JAww.d.ts +0 -77
  89. package/dist/vite-COWkwxsj.js +0 -990
@@ -0,0 +1,533 @@
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-C8XtVz0i.js";
2
+ import { t as authCloudflareEnv } from "./request-z6DHHmrb.js";
3
+ import { n as adminClaimVariable, t as adminClaimHash } from "./admin-claim-code-CDipqeAU.js";
4
+ import { n as getAuthRuntimeState } from "./runtime-state-ojQCzKOc.js";
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";
8
+ import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sessionMiddleware } from "better-auth/api";
9
+ import { createSessionStore, deleteSessionCookie, expireCookie, parseCookies } from "better-auth/cookies";
10
+ import { createInternalAdapter } from "better-auth/db";
11
+ import { decryptOAuthToken } from "better-auth/oauth2";
12
+ //#region src/admins.ts
13
+ /** The variable that lists the provider accounts that get the admin role. */
14
+ const adminsVariable = "VITEHUB_ADMINS";
15
+ /** The id of the Better Auth plugin that gives the admin role. The Auth Console reads its `options.admins`. */
16
+ const adminsPluginId = "vitehub-admins";
17
+ const removedVariable = "VITEHUB_ADMIN_EMAILS";
18
+ 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.` });
20
+ }
21
+ function parseEntry$1(entry) {
22
+ const separator = entry.indexOf(":");
23
+ const providerId = separator > 0 ? entry.slice(0, separator).trim().toLowerCase() : "";
24
+ 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.");
26
+ if (!providerId || !accountId) throw invalidEntry$1(entry, "It has no provider or no account id.");
27
+ if (providerId === "github" && !/^\d+$/.test(accountId)) throw invalidEntry$1(entry, "A GitHub entry needs the numeric account id, not the login.");
28
+ return {
29
+ providerId,
30
+ accountId
31
+ };
32
+ }
33
+ /** The accounts in `VITEHUB_ADMINS`, separated by commas. */
34
+ function readAdmins(event) {
35
+ const env = {
36
+ ...globalThis.process?.env,
37
+ ...authCloudflareEnv(event)
38
+ };
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}\`.` });
40
+ const value = env[adminsVariable];
41
+ if (typeof value !== "string") return [];
42
+ 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);
44
+ }
45
+ function formatAdminAccount(account) {
46
+ return `${account.providerId}:${account.accountId}`;
47
+ }
48
+ function adminOption(admin, name) {
49
+ const options = Reflect.get(admin, "options");
50
+ return options !== null && typeof options === "object" ? Reflect.get(options, name) : void 0;
51
+ }
52
+ /** Reads the admin role from Better Auth's `admin()` plugin, which stores it in `user.role`. */
53
+ function adminRoleGrant(plugins, variable) {
54
+ const admin = plugins.find((plugin) => plugin.id === "admin");
55
+ if (!admin) throw authErrorDiagnostics.AUTH_C0051({ message: `\`${variable}\` gives the admin role, which Better Auth's \`admin()\` plugin stores in \`user.role\`. Add \`admin()\` from \`better-auth/plugins\` to the \`plugins\` of \`defineAuth()\`, or unset \`${variable}\`.` });
56
+ const roles = adminOption(admin, "adminRoles");
57
+ const first = Array.isArray(roles) ? roles[0] : typeof roles === "string" ? roles.split(",")[0] : void 0;
58
+ const fallback = adminOption(admin, "defaultRole");
59
+ return {
60
+ role: typeof first === "string" && first.trim() ? first.trim() : "admin",
61
+ replaced: typeof fallback === "string" && fallback.trim() ? fallback.trim() : "user"
62
+ };
63
+ }
64
+ /** Adds the admin role to a user. It replaces the default role and keeps the other roles. */
65
+ async function grantAdminRole(context, userId, grant) {
66
+ const user = await context.internalAdapter.findUserById(userId);
67
+ if (!user) return false;
68
+ const current = Reflect.get(user, "role");
69
+ const roles = typeof current === "string" ? current.split(",").map((name) => name.trim()).filter(Boolean) : [];
70
+ if (roles.includes(grant.role)) return true;
71
+ const updated = await context.internalAdapter.updateUser(userId, { role: [...roles.filter((name) => name !== grant.replaced), grant.role].join(",") });
72
+ const role = updated && Reflect.get(updated, "role");
73
+ return typeof role === "string" && role.split(",").some((name) => name.trim() === grant.role);
74
+ }
75
+ /**
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.
79
+ */
80
+ function createAdminsPlugin(admins, plugins) {
81
+ const grant = adminRoleGrant(plugins, adminsVariable);
82
+ const listed = (account) => admins.some((entry) => entry.providerId === account.providerId && entry.accountId === account.accountId);
83
+ const linkedAdminContexts = /* @__PURE__ */ new WeakSet();
84
+ return {
85
+ id: adminsPluginId,
86
+ options: {
87
+ admins: admins.map(formatAdminAccount),
88
+ role: grant.role
89
+ },
90
+ hooks: { after: [{
91
+ matcher: (ctx) => Boolean((ctx.context.newSession || linkedAdminContexts.has(ctx.context)) && ctx.context.options.session?.cookieCache?.enabled),
92
+ handler: createAuthMiddleware(async (ctx) => {
93
+ const session = ctx.context.newSession ?? await getSessionFromCtx(ctx, { disableRefresh: true });
94
+ if (!session) return;
95
+ const user = await ctx.context.internalAdapter.findUserById(session.user.id);
96
+ if (!user || Reflect.get(user, "role") === Reflect.get(session.user, "role")) return;
97
+ Reflect.set(session.user, "role", Reflect.get(user, "role"));
98
+ const cookie = ctx.context.authCookies.sessionData;
99
+ expireCookie(ctx, cookie);
100
+ const store = createSessionStore(cookie.name, cookie.attributes, ctx);
101
+ store.setCookies(store.clean());
102
+ })
103
+ }] },
104
+ init: (context) => {
105
+ return { options: { databaseHooks: {
106
+ account: { create: { after: async (account, endpoint) => {
107
+ if (!listed(account)) return;
108
+ await grantAdminRole(context, account.userId, grant);
109
+ if (endpoint) linkedAdminContexts.add(endpoint.context);
110
+ } } },
111
+ session: { create: { after: async (session) => {
112
+ if ((await context.internalAdapter.findAccounts(session.userId)).some(listed)) await grantAdminRole(context, session.userId, grant);
113
+ } } }
114
+ } } };
115
+ }
116
+ };
117
+ }
118
+ //#endregion
119
+ //#region src/admin-claim.ts
120
+ /** The id of the Better Auth plugin that turns a claim code into the admin role. */
121
+ const adminClaimPluginId = "vitehub-admin-claim";
122
+ /** The configured claim hash, or `undefined` when the app has no claim code. */
123
+ function readAdminClaim(event) {
124
+ const value = {
125
+ ...globalThis.process?.env,
126
+ ...authCloudflareEnv(event)
127
+ }[adminClaimVariable];
128
+ if (typeof value !== "string" || !value.trim()) return void 0;
129
+ const hash = value.trim().toLowerCase();
130
+ if (!/^sha256:[0-9a-f]{64}$/.test(hash)) throw authErrorDiagnostics.AUTH_C0059({ message: `\`${adminClaimVariable}\` must be \`sha256:\` and 64 hex characters. Run \`vitehub auth claim\` and set the value that it prints. Never set the code itself.` });
131
+ return hash;
132
+ }
133
+ function claimIdentifier(hash) {
134
+ return `vitehub-admin-claim:${hash}`;
135
+ }
136
+ function claimStorage(context) {
137
+ return createInternalAdapter(context.adapter, {
138
+ options: {
139
+ ...context.options,
140
+ secondaryStorage: void 0
141
+ },
142
+ logger: context.logger,
143
+ generateId: context.generateId,
144
+ hooks: []
145
+ });
146
+ }
147
+ async function claimUsed(storage, hash) {
148
+ return Boolean(await storage.findVerificationValue(claimIdentifier(hash)));
149
+ }
150
+ /**
151
+ * Gives the admin role to the signed-in user who sends the claim code. The code works once: the first use writes a
152
+ * row to the `verification` table, and every later use fails. Better Auth's rate limit allows five tries a minute.
153
+ */
154
+ function createAdminClaimPlugin(hash, plugins) {
155
+ const grant = adminRoleGrant(plugins, adminClaimVariable);
156
+ return {
157
+ id: adminClaimPluginId,
158
+ options: { role: grant.role },
159
+ rateLimit: [{
160
+ pathMatcher: (path) => path === "/vitehub/admin-claim",
161
+ window: 60,
162
+ max: 5
163
+ }],
164
+ endpoints: {
165
+ vitehubAdminClaimStatus: createAuthEndpoint("/vitehub/admin-claim/status", {
166
+ method: "GET",
167
+ use: [sessionMiddleware]
168
+ }, async (ctx) => {
169
+ ctx.setHeader("cache-control", "no-store");
170
+ return ctx.json({ available: !await claimUsed(claimStorage(ctx.context), hash) });
171
+ }),
172
+ vitehubAdminClaim: createAuthEndpoint("/vitehub/admin-claim", {
173
+ method: "POST",
174
+ use: [sessionMiddleware]
175
+ }, async (ctx) => {
176
+ ctx.setHeader("cache-control", "no-store");
177
+ const body = ctx.body;
178
+ const code = body !== null && typeof body === "object" ? Reflect.get(body, "code") : void 0;
179
+ if (typeof code !== "string" || await adminClaimHash(code) !== hash) throw new APIError("FORBIDDEN", { message: "The claim code is wrong." });
180
+ const userId = ctx.context.session.user.id;
181
+ const storage = claimStorage(ctx.context);
182
+ const use = async () => {
183
+ if (await claimUsed(storage, hash)) return false;
184
+ const identifier = claimIdentifier(hash);
185
+ const owner = crypto.randomUUID();
186
+ try {
187
+ if (!await storage.reserveVerificationValue({
188
+ identifier,
189
+ value: owner,
190
+ expiresAt: /* @__PURE__ */ new Date("9999-12-31T00:00:00Z")
191
+ })) return false;
192
+ if (!await grantAdminRole(ctx.context, userId, grant)) throw new APIError("INTERNAL_SERVER_ERROR", { message: "The admin role could not be granted. Try the claim code again." });
193
+ return true;
194
+ } catch (error) {
195
+ const user = await ctx.context.internalAdapter.findUserById(userId);
196
+ const role = user && Reflect.get(user, "role");
197
+ if (!(typeof role === "string" && role.split(",").some((name) => name.trim() === grant.role)) && (await storage.findVerificationValue(identifier))?.value === owner) await storage.deleteVerificationByIdentifier(identifier);
198
+ throw error;
199
+ }
200
+ };
201
+ const queues = getAuthRuntimeState().adminClaimQueues ??= /* @__PURE__ */ new Map();
202
+ const result = (queues.get(hash) ?? Promise.resolve(false)).then(use);
203
+ const settled = result.catch(() => false);
204
+ queues.set(hash, settled);
205
+ try {
206
+ if (!await result) throw new APIError("CONFLICT", { message: "The claim code was already used. Run `vitehub auth claim` for a new code." });
207
+ } finally {
208
+ if (queues.get(hash) === settled) queues.delete(hash);
209
+ }
210
+ if (ctx.context.options.session?.cookieCache?.enabled) {
211
+ const cookie = ctx.context.authCookies.sessionData;
212
+ expireCookie(ctx, cookie);
213
+ const store = createSessionStore(cookie.name, cookie.attributes, ctx);
214
+ store.setCookies(store.clean());
215
+ }
216
+ return ctx.json({ role: grant.role });
217
+ })
218
+ }
219
+ };
220
+ }
221
+ //#endregion
222
+ //#region src/access-policy.ts
223
+ /** The id of the Better Auth plugin that applies `access.policy` and `VITEHUB_MEMBERS`. `verifyMcpRequest()` finds the policy by it. */
224
+ const accessPolicyPluginId = "vitehub-access-policy";
225
+ const defaultRecheck = 3e5;
226
+ async function digest(value) {
227
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
228
+ return [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
229
+ }
230
+ /** The request headers without the session cookies, so the endpoint and Better Auth's cookie cache see no session. */
231
+ function withoutSessionCookies(headers, names) {
232
+ const kept = [...parseCookies(headers.get("cookie") ?? "")].filter(([name]) => !names.some((prefix) => name === prefix || name.startsWith(`${prefix}.`)));
233
+ const result = new Headers(headers);
234
+ result.set("cookie", kept.map(([name, value]) => `${name}=${encodeURIComponent(value)}`).join("; "));
235
+ return result;
236
+ }
237
+ /**
238
+ * Applies `VITEHUB_MEMBERS` and `access.policy`. A session is created only when the member list lets the user in and
239
+ * `allow` returns `true`. Each Better Auth request with a session cookie or bearer credential, including every
240
+ * `getSession()` call and so every ViteHub guard, asks again once `recheck` has passed for that session. A refusal
241
+ * deletes the session and its cookies, and the request continues signed out.
242
+ */
243
+ function createAccessPolicyPlugin({ policy, members }) {
244
+ const recheck = policy?.recheck ?? defaultRecheck;
245
+ const allowedUntil = /* @__PURE__ */ new Map();
246
+ let auth;
247
+ const remember = (key) => {
248
+ if (recheck <= 0) return;
249
+ const now = Date.now();
250
+ for (const [entry, until] of allowedUntil) if (until <= now) allowedUntil.delete(entry);
251
+ allowedUntil.set(key, now + recheck);
252
+ };
253
+ const askPolicy = async (context, user) => {
254
+ if (!policy) return true;
255
+ const accessToken = async (providerId) => {
256
+ const account = (await context.internalAdapter.findAccounts(user.id)).find((entry) => entry.providerId === providerId);
257
+ return account?.accessToken ? await decryptOAuthToken(account.accessToken, context) : null;
258
+ };
259
+ return await policy.allow({
260
+ user,
261
+ accessToken
262
+ }) === true;
263
+ };
264
+ const ask = async (context, user) => (!members || await members.allows(context, user)) && await askPolicy(context, user);
265
+ const allows = async (user, key, context = auth) => {
266
+ invariant(context, "Better Auth runs `init` of the access policy plugin before a request or token check reaches it");
267
+ const cacheKey = await digest(key);
268
+ if ((allowedUntil.get(cacheKey) ?? 0) > Date.now()) return true;
269
+ allowedUntil.delete(cacheKey);
270
+ const allowed = await ask(context, user);
271
+ if (allowed) remember(cacheKey);
272
+ return allowed;
273
+ };
274
+ const readToken = createAuthMiddleware(async (ctx) => ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret));
275
+ return {
276
+ id: accessPolicyPluginId,
277
+ allows,
278
+ members,
279
+ options: { members: members?.entries ?? [] },
280
+ hooks: { before: [{
281
+ matcher: (context) => Boolean(context.headers?.get("cookie") || context.headers?.get("authorization") || context.request?.headers.get("authorization")),
282
+ handler: createAuthMiddleware(async (ctx) => {
283
+ let headers = ctx.headers;
284
+ const bearer = ctx.context.options.plugins?.find((plugin) => plugin.id === "bearer");
285
+ for (const hook of bearer?.hooks?.before ?? []) {
286
+ if (!hook.matcher(ctx)) continue;
287
+ const result = await hook.handler({
288
+ ...ctx,
289
+ returnHeaders: false
290
+ });
291
+ if (typeof result !== "object" || result === null || !("context" in result)) continue;
292
+ const replacement = result.context;
293
+ if (typeof replacement === "object" && replacement !== null && "headers" in replacement && replacement.headers instanceof Headers) headers = replacement.headers;
294
+ }
295
+ const { sessionData, sessionToken } = ctx.context.authCookies;
296
+ const tokenContext = {
297
+ headers,
298
+ context: ctx.context
299
+ };
300
+ const token = await readToken(tokenContext);
301
+ if (!token) return;
302
+ const stored = await ctx.context.internalAdapter.findSession(token);
303
+ const user = stored && new Date(stored.session.expiresAt).getTime() > Date.now() ? await ctx.context.internalAdapter.findUserById(stored.session.userId) : null;
304
+ if (user && await allows(user, `session:${token}`, ctx.context)) return;
305
+ if (stored) await ctx.context.internalAdapter.deleteSession(token);
306
+ deleteSessionCookie(ctx);
307
+ ctx.context.session = null;
308
+ return { context: { headers: withoutSessionCookies(headers ?? new Headers(), [sessionToken.name, sessionData.name]) } };
309
+ })
310
+ }] },
311
+ init: (context) => {
312
+ auth = context;
313
+ return { options: { databaseHooks: {
314
+ ...members?.databaseHooks(context),
315
+ session: { create: {
316
+ before: async (session, endpoint) => {
317
+ const user = await context.internalAdapter.findUserById(session.userId);
318
+ if (!user) return false;
319
+ if (members) try {
320
+ if (!await members.allows(context, user)) throw members.refusal();
321
+ } catch (error) {
322
+ await members.cleanup(context, user.id, endpoint);
323
+ throw error;
324
+ }
325
+ if (!await askPolicy(context, user)) return false;
326
+ },
327
+ after: async (session) => {
328
+ remember(await digest(`session:${session.token}`));
329
+ }
330
+ } }
331
+ } } };
332
+ }
333
+ };
334
+ }
335
+ /** The access policy plugin of an Auth, if it has one. */
336
+ function findAccessPolicyPlugin(plugins) {
337
+ const plugin = plugins?.find((entry) => entry.id === accessPolicyPluginId);
338
+ return plugin && "allows" in plugin && typeof plugin.allows === "function" ? plugin : void 0;
339
+ }
340
+ //#endregion
341
+ //#region src/members.ts
342
+ const orgCacheMs = 3e5;
343
+ /** The variable that lists who may sign up and sign in. */
344
+ const membersVariable = "VITEHUB_MEMBERS";
345
+ const memberErrors = /*#__PURE__*/ defineErrors({
346
+ docs: "https://vitehub.dev/docs/auth/diagnostics",
347
+ codes: {
348
+ AUTH_MEMBERS_ENTRY_INVALID: {
349
+ why: ({ entry, reason }) => `\`VITEHUB_MEMBERS\` has the entry \`${entry}\`. ${reason}`,
350
+ fix: "Separate the entries with commas. Write each entry as `github:<account id>`, `<email>`, `@<email domain>`, or `github-org:<organization login>`, for example `VITEHUB_MEMBERS=github:22072217,ada@example.com,@acme.com,github-org:acme`. Run `gh api users/<login> --jq .id` to get a GitHub account id."
351
+ },
352
+ AUTH_MEMBERS_SESSION_STORE_REQUIRED: {
353
+ why: "`VITEHUB_MEMBERS` is set, but Auth has no Better Auth `database` or `secondaryStorage` adapter. Auth cannot end the session of a person who leaves the list when the session lives only in a cookie.",
354
+ fix: "Set `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'`, or return another Better Auth adapter. Or unset `VITEHUB_MEMBERS`."
355
+ },
356
+ AUTH_NOT_MEMBER: {
357
+ why: "`VITEHUB_MEMBERS` does not list this account, its verified email, its email domain, or a GitHub organization that it is an active member of.",
358
+ fix: "Add the person to `VITEHUB_MEMBERS` on the host, for example `github:22072217` or `ada@example.com`, and ask them to sign in again. An email or domain entry matches only an email that the sign-in provider verified."
359
+ }
360
+ }
361
+ });
362
+ function invalidEntry(entry, reason) {
363
+ return memberErrors.AUTH_MEMBERS_ENTRY_INVALID({
364
+ entry,
365
+ reason
366
+ });
367
+ }
368
+ function parseEntry(entry) {
369
+ if (entry.startsWith("@")) {
370
+ const domain = entry.slice(1).toLowerCase();
371
+ if (!domain || domain.includes("@")) throw invalidEntry(entry, "A domain entry is `@` and the email domain, such as `@acme.com`.");
372
+ return {
373
+ kind: "domain",
374
+ domain
375
+ };
376
+ }
377
+ if (entry.includes("@") && !entry.includes(":")) {
378
+ if (entry.indexOf("@") !== entry.lastIndexOf("@")) throw invalidEntry(entry, "An email has one `@`.");
379
+ return {
380
+ kind: "email",
381
+ email: entry.toLowerCase()
382
+ };
383
+ }
384
+ const separator = entry.indexOf(":");
385
+ const providerId = separator > 0 ? entry.slice(0, separator).trim().toLowerCase() : "";
386
+ const value = separator > 0 ? entry.slice(separator + 1).trim() : "";
387
+ if (!providerId || !value) throw invalidEntry(entry, "It is not an email, a domain, or `<provider>:<account id>`.");
388
+ if (providerId === "github-org") return {
389
+ kind: "github-org",
390
+ org: value
391
+ };
392
+ if (providerId === "email" || providerId === "credential") throw invalidEntry(entry, "Write an email entry as the email alone, such as `ada@example.com`.");
393
+ if (providerId === "github" && !/^\d+$/.test(value)) throw invalidEntry(entry, "A GitHub entry needs the numeric account id, not the login.");
394
+ return {
395
+ kind: "account",
396
+ providerId,
397
+ accountId: value
398
+ };
399
+ }
400
+ /** The entries of `VITEHUB_MEMBERS`, separated by commas. An unset or empty variable lets everyone in. */
401
+ function readMembers(event) {
402
+ const value = {
403
+ ...globalThis.process?.env,
404
+ ...authCloudflareEnv(event)
405
+ }[membersVariable];
406
+ if (typeof value !== "string") return [];
407
+ return value.split(",").map((entry) => entry.trim()).filter(Boolean).map(parseEntry);
408
+ }
409
+ function formatMemberEntry(entry) {
410
+ switch (entry.kind) {
411
+ case "account": return `${entry.providerId}:${entry.accountId}`;
412
+ case "email": return entry.email;
413
+ case "domain": return `@${entry.domain}`;
414
+ case "github-org": return `github-org:${entry.org}`;
415
+ }
416
+ }
417
+ /** Fails when `VITEHUB_MEMBERS` is set but Auth stores no sessions. */
418
+ function assertMembersSessionStore(members, hasSessionStore) {
419
+ if (members.length && !hasSessionStore) throw memberErrors.AUTH_MEMBERS_SESSION_STORE_REQUIRED();
420
+ }
421
+ /** The GitHub provider asks for `read:org` when an entry names a GitHub organization, so Auth can check the membership. */
422
+ function withMemberScopes(members, socialProviders) {
423
+ const github = socialProviders?.github;
424
+ if (!github || !members.some((entry) => entry.kind === "github-org")) return socialProviders;
425
+ const withReadOrg = (options) => options.scope?.includes("read:org") ? options : {
426
+ ...options,
427
+ scope: [...options.scope ?? [], "read:org"]
428
+ };
429
+ return {
430
+ ...socialProviders,
431
+ github: typeof github === "function" ? async () => withReadOrg(await github()) : withReadOrg(github)
432
+ };
433
+ }
434
+ /** The error of a user that `VITEHUB_MEMBERS` does not let in. */
435
+ function notMemberError() {
436
+ return memberErrors.AUTH_NOT_MEMBER();
437
+ }
438
+ /** The answer that Auth sends for a refused sign-up or sign-in. */
439
+ function notMember() {
440
+ const error = notMemberError();
441
+ return new APIError("FORBIDDEN", {
442
+ code: error.code,
443
+ message: error.why
444
+ });
445
+ }
446
+ const isGitHubUnavailable = (error) => error.code === "AUTH_GITHUB_UNAVAILABLE";
447
+ const unavailable = (error) => new APIError("SERVICE_UNAVAILABLE", {
448
+ code: error.code,
449
+ message: error.why
450
+ });
451
+ /**
452
+ * Builds the check of `VITEHUB_MEMBERS`. The accounts in `VITEHUB_ADMINS` and users with the admin role of `admin()`
453
+ * are always members.
454
+ */
455
+ function createMembersGate(members, admins, plugins) {
456
+ const createdUsers = /* @__PURE__ */ new WeakMap();
457
+ const cleanup = async (context, userId, endpoint) => {
458
+ if (!endpoint || !createdUsers.get(endpoint)?.delete(userId)) return;
459
+ await context.internalAdapter.deleteUser(userId);
460
+ };
461
+ const accounts = [...members.flatMap((entry) => entry.kind === "account" ? [entry] : []), ...admins];
462
+ const orgs = members.flatMap((entry) => entry.kind === "github-org" ? [entry.org] : []);
463
+ const adminRole = plugins.some((plugin) => plugin.id === "admin") ? adminRoleGrant(plugins, membersVariable).role : void 0;
464
+ const emailListed = (email) => {
465
+ const address = email.toLowerCase();
466
+ return members.some((entry) => entry.kind === "email" && entry.email === address || entry.kind === "domain" && address.endsWith(`@${entry.domain}`));
467
+ };
468
+ const accountListed = (account) => accounts.some((entry) => entry.providerId === account.providerId && entry.accountId === account.accountId);
469
+ /** `true` for an active membership of a listed organization, the GitHub outage error, or `false`. */
470
+ const orgMember = async (context, account) => {
471
+ if (account.providerId !== "github" || !account.accessToken || !orgs.length) return false;
472
+ const token = await decryptOAuthToken(account.accessToken, context);
473
+ let outage;
474
+ for (const org of orgs) {
475
+ const [error] = await checkGitHubOrgMember(token, org, { cacheMs: orgCacheMs });
476
+ if (!error) return true;
477
+ if (isGitHubUnavailable(error)) outage = error;
478
+ }
479
+ return outage ?? false;
480
+ };
481
+ const isAdmin = (user) => {
482
+ const role = user?.role;
483
+ return Boolean(adminRole && typeof role === "string" && role.split(",").some((name) => name.trim() === adminRole));
484
+ };
485
+ const check = async (context, user) => {
486
+ if (user.emailVerified && emailListed(user.email)) return [void 0, void 0];
487
+ if (isAdmin(user)) return [void 0, void 0];
488
+ const linked = await context.internalAdapter.findAccounts(user.id);
489
+ if (linked.some(accountListed)) return [void 0, void 0];
490
+ let outage;
491
+ for (const account of linked) {
492
+ const answer = await orgMember(context, account);
493
+ if (answer === true) return [void 0, void 0];
494
+ if (answer) outage = answer;
495
+ }
496
+ return [outage ?? notMemberError(), void 0];
497
+ };
498
+ const allows = async (context, user) => {
499
+ const [error] = await check(context, user);
500
+ if (error && isGitHubUnavailable(error)) throw unavailable(error);
501
+ return !error;
502
+ };
503
+ return {
504
+ entries: members.map(formatMemberEntry),
505
+ check,
506
+ allows,
507
+ cleanup,
508
+ refusal: notMember,
509
+ databaseHooks: (context) => ({
510
+ user: { create: {
511
+ before: async (user) => {
512
+ if (!emailListed(user.email) && !adminRole && !accounts.length && !orgs.length) throw notMember();
513
+ },
514
+ after: async (user, endpoint) => {
515
+ if (!endpoint) return;
516
+ const users = createdUsers.get(endpoint) ?? /* @__PURE__ */ new Set();
517
+ users.add(user.id);
518
+ createdUsers.set(endpoint, users);
519
+ }
520
+ } },
521
+ account: { create: { before: async (account, endpoint) => {
522
+ if (!endpoint || !createdUsers.get(endpoint)?.has(account.userId)) return;
523
+ const user = await context.internalAdapter.findUserById(account.userId);
524
+ const answer = Boolean(user && (emailListed(user.email) || isAdmin(user))) || accountListed(account) || await orgMember(context, account);
525
+ if (answer === true) return;
526
+ if (user) await cleanup(context, user.id, endpoint);
527
+ throw answer ? unavailable(answer) : notMember();
528
+ } } }
529
+ })
530
+ };
531
+ }
532
+ //#endregion
533
+ 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 };
@@ -0,0 +1,44 @@
1
+ //#region src/nuxt-bridge.ts
2
+ /** The hooks that the setters below install. The composables read them. */
3
+ const authNuxtBridge = {};
4
+ /** Internal bridge installed by the Nuxt module, without making `#app` a dependency of the Vue entry. */
5
+ function setNuxtAppResolver(resolver) {
6
+ authNuxtBridge.nuxtAppResolver = resolver;
7
+ }
8
+ /** Internal bridge installed by the Nuxt module: Nuxt's `createError()`, so a refusal of `authorize()` shows the error page. */
9
+ function setNuxtErrorFactory(factory) {
10
+ authNuxtBridge.nuxtErrorFactory = factory;
11
+ }
12
+ /**
13
+ * Internal bridge installed by the Nuxt module in the browser. `signOut()` of `useUserSession()` calls it after a
14
+ * sign-out. It forgets the session that the server read, and opens `redirectTo`, or the login page when the page on
15
+ * screen is only for signed-in visitors.
16
+ */
17
+ function setSignOutHandler(handler) {
18
+ authNuxtBridge.signOutHandler = handler;
19
+ }
20
+ /**
21
+ * Internal bridge installed by the Nuxt module: the path of Better Auth for the default `authClient`, such as
22
+ * `/app/auth` for `defineAuth({ basePath: '/auth' })` below Nuxt `app.baseURL` `/app/`. The client reads it when it
23
+ * loads Better Auth. Without it, the client uses `/api/auth` below the base path of the build.
24
+ */
25
+ function setDefaultAuthBasePath(path) {
26
+ authNuxtBridge.defaultBasePath = path;
27
+ }
28
+ /**
29
+ * Internal bridge installed by the Nuxt module. The resolver returns the session that the server read for this
30
+ * request, `null` when the request had none, or `undefined` when nobody knows yet, such as on a prerendered page.
31
+ * With `read` on the server, it reads the session if the request did not read it yet, and can return a promise of it.
32
+ */
33
+ function setSessionSeedResolver(resolver) {
34
+ authNuxtBridge.sessionSeedResolver = resolver;
35
+ }
36
+ /**
37
+ * Internal bridge installed by the Nuxt module. On the server, the resolver returns the fetch of the current request, or
38
+ * `undefined` outside a request.
39
+ */
40
+ function setRequestFetchResolver(resolver) {
41
+ authNuxtBridge.requestFetchResolver = resolver;
42
+ }
43
+ //#endregion
44
+ export { setRequestFetchResolver as a, setNuxtErrorFactory as i, setDefaultAuthBasePath as n, setSessionSeedResolver as o, setNuxtAppResolver as r, setSignOutHandler as s, authNuxtBridge as t };
package/dist/nuxt.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { F as AuthModuleOptions } from "./events-BkmK2dFY.js";
3
- //#region ../internal/src/build/vite.d.ts
2
+ import { Ct as AuthPageMeta, S as AuthOptions, Tt as AuthRedirects, wt as AuthPageMode } from "./types-CNaeH2Fd.js";
3
+ import "vite";
4
+ //#region ../internal/src/build/paths.d.ts
4
5
  interface NuxtLayerDirectoryConfig {
5
6
  rootDir?: string;
6
7
  serverDir?: string;
@@ -16,7 +17,7 @@ interface NuxtServerDirOptions extends NuxtLayerDirectoryConfig {
16
17
  //#endregion
17
18
  //#region src/nuxt.d.ts
18
19
  export interface AuthNuxtModuleOptions {
19
- auth?: AuthModuleOptions;
20
+ auth?: AuthOptions;
20
21
  env?: false | {
21
22
  projectRoot?: string;
22
23
  };
@@ -24,8 +25,14 @@ export interface AuthNuxtModuleOptions {
24
25
  nitro?: boolean;
25
26
  }
26
27
  type NuxtLike = {
28
+ callHook?: (name: "restart") => Promise<void>;
27
29
  hook?: (name: "nitro:config", handler: (nitroConfig: Record<string, unknown>) => Promise<void>) => void;
28
30
  options: {
31
+ dev?: boolean;
32
+ watch?: string[];
33
+ runtimeConfig?: {
34
+ public?: Record<string, unknown>;
35
+ };
29
36
  plugins?: Array<string | {
30
37
  src: string;
31
38
  order?: number;
@@ -47,8 +54,8 @@ type NuxtLike = {
47
54
  };
48
55
  rootDir?: string;
49
56
  serverDir?: string;
57
+ srcDir?: string;
50
58
  vite?: {
51
- auth?: AuthModuleOptions;
52
59
  define?: Record<string, unknown>;
53
60
  plugins?: unknown[];
54
61
  root?: string;
@@ -56,4 +63,5 @@ type NuxtLike = {
56
63
  };
57
64
  };
58
65
  export default function hubAuthNuxt(options?: AuthNuxtModuleOptions, nuxt?: NuxtLike): void;
59
- //#endregion
66
+ //#endregion
67
+ export type { AuthPageMeta, AuthPageMode, AuthRedirects };