@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
@@ -1,8 +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
2
  import { t as isRecord } from "./object-Da1zyPCR.js";
3
3
  import { t as accessRouteSyntaxError } from "./application-path-DuTpfGFj.js";
4
- import { t as normalizeAuthBasePath } from "./shared-BwcdRGxD.js";
5
- import { r as authDatabaseName } from "./database-options-BRNef9oy.js";
4
+ import { t as normalizeAuthBasePath } from "./shared-DRtfuFsV.js";
5
+ import { r as authDatabaseName } from "./database-options-DpOVjUti.js";
6
+ import { parseDuration } from "@vite-hub/runtime";
6
7
  //#region src/stateless-user-id.ts
7
8
  const pendingUserIds = /* @__PURE__ */ new WeakMap();
8
9
  /** The user ID of one provider account: the first 32 hex digits of SHA-256 over the provider ID and the account ID. */
@@ -175,6 +176,133 @@ function validateAuthEvents(value) {
175
176
  ].every((key) => typeof Reflect.get(value.store, key) === "function") || "authorize" in value && value.authorize !== void 0 && typeof value.authorize !== "function" || "onEvent" in value && value.onEvent !== void 0 && typeof value.onEvent !== "function") throw authErrorDiagnostics.AUTH_C0050({ message: "`defineAuth()` events needs a store with append, list, and aggregate methods. events.authorize and events.onEvent must be functions. Set events to false to disable the log." });
176
177
  }
177
178
  //#endregion
179
+ //#region ../internal/src/runtime/user-data.ts
180
+ const stateKey = Symbol.for("vitehub.user-data");
181
+ const scope = globalThis;
182
+ /** The registered owners, by owner name. */
183
+ function viteHubUserData(app) {
184
+ return [...(app && scope[stateKey]?.get(app))?.values() ?? []].sort((left, right) => left.owner.localeCompare(right.owner));
185
+ }
186
+ //#endregion
187
+ //#region src/delete-account.ts
188
+ /** Also checked when a Definition callback returns the options. */
189
+ function validateDeleteAccount(options) {
190
+ if (isRecord(options.user) && options.user.deleteUser !== void 0) throw authErrorDiagnostics.AUTH_DELETE_USER_UNSUPPORTED();
191
+ const value = options.deleteAccount;
192
+ if (value === void 0) return;
193
+ if (value !== true && (!isRecord(value) || Object.hasOwn(value, "enabled") || value.beforeDelete !== void 0 && typeof value.beforeDelete !== "function" || value.afterDelete !== void 0 && typeof value.afterDelete !== "function" || value.userApiKeyConfigIds !== void 0 && (!Array.isArray(value.userApiKeyConfigIds) || value.userApiKeyConfigIds.some((id) => typeof id !== "string" || !id)))) throw authErrorDiagnostics.AUTH_DELETE_ACCOUNT_INVALID();
194
+ const session = options.session;
195
+ if (options.preset !== void 0 || isRecord(session) && isRecord(session.cookieCache) && session.cookieCache.enabled === true) throw authErrorDiagnostics.AUTH_DELETE_ACCOUNT_SESSION();
196
+ }
197
+ const betterAuthModels = /* @__PURE__ */ new Set([
198
+ "user",
199
+ "session",
200
+ "account"
201
+ ]);
202
+ /**
203
+ * The rows of the Better Auth tables that name the user, such as passkeys, organization members, and MCP tokens. A
204
+ * Database deletes them through `on delete cascade`, but an app schema can lack the foreign keys. The `apikey` table of
205
+ * `apiKey()` names its owner in `referenceId`, without a foreign key.
206
+ */
207
+ async function deleteAuthRows(context, user, userApiKeyConfigIds) {
208
+ const userModel = context.tables.user?.modelName ?? "user";
209
+ let storedUser;
210
+ for (const [model, table] of Object.entries(context.tables)) {
211
+ if (betterAuthModels.has(model)) continue;
212
+ for (const [field, attribute] of Object.entries(table.fields)) {
213
+ const reference = attribute.references;
214
+ if (!reference || reference.model !== "user" && reference.model !== userModel) continue;
215
+ const userField = Object.hasOwn(context.tables.user?.fields ?? {}, reference.field) ? reference.field : Object.entries(context.tables.user?.fields ?? {}).find(([, attribute]) => attribute.fieldName === reference.field)?.[0] ?? reference.field;
216
+ if (userField !== "id") storedUser ??= context.adapter.findOne({
217
+ model: "user",
218
+ where: [{
219
+ field: "id",
220
+ value: user.id
221
+ }]
222
+ });
223
+ const value = userField === "id" ? user.id : (await storedUser)?.[userField];
224
+ if (value == null) continue;
225
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean" && !(value instanceof Date)) throw authErrorDiagnostics.AUTH_DELETE_ACCOUNT_REFERENCE_UNSUPPORTED({
226
+ model,
227
+ field,
228
+ userField
229
+ });
230
+ const where = [{
231
+ field,
232
+ value
233
+ }];
234
+ if (reference.onDelete === "set null") await context.adapter.updateMany({
235
+ model,
236
+ where,
237
+ update: { [field]: null }
238
+ });
239
+ else await context.adapter.deleteMany({
240
+ model,
241
+ where
242
+ });
243
+ }
244
+ }
245
+ if (userApiKeyConfigIds.length && context.tables.apikey?.fields.referenceId && context.tables.apikey.fields.configId) {
246
+ const owner = {
247
+ field: "referenceId",
248
+ value: user.id
249
+ };
250
+ await context.adapter.deleteMany({
251
+ model: "apikey",
252
+ where: [owner, {
253
+ field: "configId",
254
+ operator: "in",
255
+ value: [...userApiKeyConfigIds]
256
+ }]
257
+ });
258
+ if (userApiKeyConfigIds.includes("default")) await context.adapter.deleteMany({
259
+ model: "apikey",
260
+ where: [owner, {
261
+ field: "configId",
262
+ value: null
263
+ }]
264
+ });
265
+ }
266
+ }
267
+ async function deleting(owner, run) {
268
+ try {
269
+ await run();
270
+ } catch (cause) {
271
+ throw authErrorDiagnostics.AUTH_DELETE_ACCOUNT_FAILED({
272
+ owner,
273
+ cause
274
+ });
275
+ }
276
+ }
277
+ /**
278
+ * Better Auth `user.deleteUser` for `deleteAccount`, and the plugin that gives it the Auth tables. The app's
279
+ * `beforeDelete` runs first, so it can still keep the account. Then each Server Primitive deletes the rows of the user,
280
+ * then Auth the rows of the other Better Auth tables, and last Better Auth deletes the user, its sessions, and its
281
+ * accounts. When a step fails, the account stays, so the user can try again.
282
+ */
283
+ function createDeleteAccount(option, app) {
284
+ const { beforeDelete, userApiKeyConfigIds = [], ...rest } = option === true ? {} : option;
285
+ let context;
286
+ return {
287
+ plugin: {
288
+ id: "vitehub-delete-account",
289
+ init(ctx) {
290
+ context = ctx;
291
+ }
292
+ },
293
+ deleteUser: {
294
+ ...rest,
295
+ enabled: true,
296
+ async beforeDelete(user, request) {
297
+ await beforeDelete?.(user, request);
298
+ for (const data of viteHubUserData(app)) await deleting(data.owner, () => data.delete(user.id));
299
+ const auth = context;
300
+ if (auth) await deleting("auth", () => deleteAuthRows(auth, user, userApiKeyConfigIds));
301
+ }
302
+ }
303
+ };
304
+ }
305
+ //#endregion
178
306
  //#region src/definition.ts
179
307
  const authRuntimeOptionNames = /* @__PURE__ */ new Set([
180
308
  "baseURL",
@@ -210,10 +338,14 @@ function validateRouteValue(value, label) {
210
338
  if (syntaxError) throw authErrorDiagnostics.AUTH_C0068({ message: syntaxError });
211
339
  }
212
340
  function validateAuthSignIn(value) {
341
+ if (typeof value === "string") {
342
+ if (!isAppPath(value)) throw authErrorDiagnostics.AUTH_C0028({ message: "`defineAuth()` access.signIn must be a path that starts with one `/`, or an object." });
343
+ return;
344
+ }
213
345
  if (typeof value === "undefined") return;
214
- if (!isRecord(value)) throw authErrorDiagnostics.AUTH_C0028({ message: "`defineAuth()` access.signIn must be an object." });
346
+ if (!isRecord(value)) throw authErrorDiagnostics.AUTH_C0028({ message: "`defineAuth()` access.signIn must be a path or an object." });
215
347
  validateStringValue(value.provider, "access.signIn.provider");
216
- if (typeof value.callbackURL !== "undefined") validateStringValue(value.callbackURL, "access.signIn.callbackURL");
348
+ if ("callbackURL" in value) throw authErrorDiagnostics.AUTH_SIGN_IN_CALLBACK_URL_MOVED();
217
349
  if (typeof value.errorCallbackURL !== "undefined") validateStringValue(value.errorCallbackURL, "access.signIn.errorCallbackURL");
218
350
  if (typeof value.requestSignUp !== "undefined" && typeof value.requestSignUp !== "boolean") throw authErrorDiagnostics.AUTH_C0029({ message: "`defineAuth()` access.signIn.requestSignUp must be a boolean." });
219
351
  if (typeof value.scopes !== "undefined" && (!Array.isArray(value.scopes) || value.scopes.some((scope) => typeof scope !== "string"))) throw authErrorDiagnostics.AUTH_C0030({ message: "`defineAuth()` access.signIn.scopes must be an array of strings." });
@@ -241,6 +373,11 @@ function validateAuthAccess(value) {
241
373
  validateAuthAccessPublic(access.public);
242
374
  validateAuthAccessPolicy(access.policy);
243
375
  validateAuthSignIn(access.signIn);
376
+ if (typeof access.afterSignIn !== "undefined" && !isAppPath(access.afterSignIn)) throw authErrorDiagnostics.AUTH_AFTER_SIGN_IN_INVALID();
377
+ }
378
+ /** A path of the app: one `/`, then no `/` or `\`, so it cannot name another site. */
379
+ function isAppPath(value) {
380
+ return typeof value === "string" && /^\/(?![/\\])/.test(value);
244
381
  }
245
382
  function validateAuthAccessPublic(value) {
246
383
  if (typeof value === "undefined") return;
@@ -249,8 +386,8 @@ function validateAuthAccessPublic(value) {
249
386
  /** Also checked when a Definition callback returns the options. */
250
387
  function validateAuthAccessPolicy(value) {
251
388
  if (typeof value === "undefined") return;
252
- const recheck = isRecord(value) ? value.recheck : void 0;
253
- if (!isRecord(value) || typeof value.allow !== "function" || typeof recheck !== "undefined" && (typeof recheck !== "number" || !Number.isFinite(recheck) || recheck < 0)) throw authErrorDiagnostics.AUTH_C0065({ message: "`defineAuth()` access.policy must be an object with an `allow` function and an optional `recheck` of 0 or more milliseconds." });
389
+ if (!isRecord(value) || typeof value.allow !== "function") throw authErrorDiagnostics.AUTH_C0065({ message: "`defineAuth()` access.policy must be an object with an `allow` function and an optional `recheck` duration such as \"5m\"." });
390
+ if (value.recheck !== void 0) parseDuration(value.recheck, "recheck");
254
391
  }
255
392
  function defineAuth(options) {
256
393
  return defineAuthOptions(options);
@@ -270,6 +407,7 @@ function defineAuthOptions(options) {
270
407
  const session = options.session;
271
408
  if (isRecord(session) && typeof session.onRefresh !== "undefined" && typeof session.onRefresh !== "function") throw authErrorDiagnostics.AUTH_C0041({ message: "`defineAuth()` session.onRefresh must be a function." });
272
409
  validateAuthEvents(options.events);
410
+ validateDeleteAccount(options);
273
411
  validateAuthDatabase(viteHubOptions.database);
274
412
  validateAuthSecondaryStorage(viteHubOptions.secondaryStorage);
275
413
  validateAuthAccess(viteHubOptions.access);
@@ -277,4 +415,4 @@ function defineAuthOptions(options) {
277
415
  return { options };
278
416
  }
279
417
  //#endregion
280
- export { applyAuthPreset as a, validateAuthEvents as i, defineAuth as n, validateAuthAccessPolicy as r, assertNoRuntimeOption as t };
418
+ export { validateDeleteAccount as a, createDeleteAccount as i, defineAuth as n, validateAuthEvents as o, validateAuthAccessPolicy as r, applyAuthPreset as s, assertNoRuntimeOption as t };
@@ -9,13 +9,37 @@ const withFix = (fix) => ({
9
9
  const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
10
10
  docsBase: "https://vitehub.dev/docs/auth/diagnostics",
11
11
  codes: {
12
+ AUTH_DELETE_ACCOUNT_FAILED: {
13
+ why: ({ owner }) => `Auth could not delete the ${owner} data of the user, so it kept the account.`,
14
+ fix: "Read `error.cause` for the error of the Server Primitive, such as a missing table or a Database that does not answer. Fix it, then let the user delete the account again. Rows that Auth already deleted stay deleted."
15
+ },
16
+ AUTH_DELETE_ACCOUNT_INVALID: {
17
+ why: "`defineAuth()` deleteAccount must be `true` or an object of Better Auth `user.deleteUser` options without `enabled`.",
18
+ fix: "Pass `deleteAccount: true` or an options object. If specifying `userApiKeyConfigIds`, pass an array of nonempty configuration IDs."
19
+ },
20
+ AUTH_DELETE_ACCOUNT_REFERENCE_UNSUPPORTED: {
21
+ why: ({ model, field, userField }) => `Auth cannot match ${model}.${field} to user.${userField}: the stored user field is not a string, number, boolean, or date.`,
22
+ fix: "Point the Better Auth plugin field at `user.id` or another user field stored as a string, number, boolean, or date."
23
+ },
24
+ AUTH_DELETE_ACCOUNT_SESSION: {
25
+ why: "`defineAuth()` deleteAccount cannot revoke sessions that Auth accepts from cookies alone.",
26
+ fix: "Use stored Auth without `stateless()` or `session.cookieCache.enabled` to enable account deletion."
27
+ },
28
+ AUTH_DELETE_USER_UNSUPPORTED: {
29
+ why: "`defineAuth()` does not take Better Auth `user.deleteUser`, because it would delete the user without the user's rows in ViteHub Server Primitives.",
30
+ fix: "Move the options to `deleteAccount`, without `enabled`: `user: { deleteUser: { enabled: true, beforeDelete } }` becomes `deleteAccount: { beforeDelete }`."
31
+ },
12
32
  AUTH_EVENT_CALLBACK_FAILED: {
13
33
  why: ({ type }) => `\`events.onEvent\` failed for the ${JSON.stringify(type)} auth event. Auth kept the change and the stored event.`,
14
34
  fix: "Read `error.cause` for the error of your callback. Catch errors inside `events.onEvent`, and retry the outside call there if it can fail."
15
35
  },
16
36
  AUTH_EVENT_QUERY_INVALID: {
17
- why: ({ problem }) => problem === "order" ? "Auth event from must be before to." : "Auth event windows must be positive and at most 366 days.",
18
- fix: "Pass `from` before `to`, as ISO timestamps, and keep an aggregate window at most 366 days long."
37
+ why: ({ problem }) => problem === "order" ? "Auth event from must be before to." : problem === "window" ? "Auth event windows must be positive and at most 366 days." : "Auth event filters are not valid. `error.cause` tells which value failed.",
38
+ fix: "Pass `from` before `to`, as ISO timestamps, and keep an aggregate window at most 366 days long. Pass a known event `type`, a `limit` from 1 to 200, and the `nextCursor` of the previous page without changes."
39
+ },
40
+ AUTH_EVENT_READ_FAILED: {
41
+ why: "The Auth event store failed to read the events.",
42
+ fix: "Read `error.cause` for the store error. Check that the database of `events.store` is reachable, then read again."
19
43
  },
20
44
  AUTH_EVENT_RETENTION_INVALID: {
21
45
  why: "Auth event retention limits must be positive integers.",
@@ -29,6 +53,18 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
29
53
  why: ({ redirectTo }) => `\`signOut()\` redirects only to a path of the app, not to ${JSON.stringify(redirectTo)}.`,
30
54
  fix: "Pass a path that starts with one `/`, for example `signOut(event, { redirectTo: '/login' })`. A value from the query string can point to another site, so check it against your own pages first."
31
55
  },
56
+ AUTH_AFTER_SIGN_IN_INVALID: {
57
+ why: "`defineAuth()` access.afterSignIn must be an inline path of the app that starts with one `/`.",
58
+ fix: "Set `access.afterSignIn` to a string literal path, for example `afterSignIn: '/dashboard'`. The Nuxt page guard reads it at build time."
59
+ },
60
+ AUTH_REDIRECTS_MOVED: {
61
+ why: "`vitehub({ auth })` takes only `true` or `false`. The `redirects` option moved to the Auth Definition.",
62
+ fix: "Remove the object from `auth` in `vitehub()`. In `server/auth.ts`, set `access: { signIn: '/login', afterSignIn: '/' }`: `redirects.login` is now `signIn`, and `redirects.guest` is now `afterSignIn`. `vitehub migrate` moves them."
63
+ },
64
+ AUTH_SIGN_IN_CALLBACK_URL_MOVED: {
65
+ why: "`defineAuth()` access.signIn.callbackURL moved to `access.afterSignIn`.",
66
+ fix: "Move the value to `access.afterSignIn`, for example `access: { signIn: { provider: 'github' }, afterSignIn: '/dashboard' }`. The page guard also sends signed-in users there from `auth: 'guest'` pages. `vitehub migrate` moves it."
67
+ },
32
68
  AUTH_TEST_SIGN_IN_STATELESS: {
33
69
  why: "`signIn()` writes the user and the session to the Auth database, and a Definition with the `stateless()` preset has none.",
34
70
  fix: "Test the routes of a `stateless()` Definition through its social sign-in flow, or give the test app `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'`."
@@ -53,7 +89,7 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
53
89
  AUTH_C0024: withFix("Remove `secondaryStorage` from the static options. Return a Better Auth `secondaryStorage` adapter, an object with `get`, `set`, and `delete`, from the Definition callback."),
54
90
  AUTH_C0026: withFix("Set the option to a non-empty string, for example `provider: 'github'` or `method: 'GET'`."),
55
91
  AUTH_C0027: withFix("Start the path with `/`, for example `/admin/**` or `/auth`."),
56
- AUTH_C0028: withFix("Set `access.signIn` to an object, for example `signIn: { provider: 'github' }`."),
92
+ AUTH_C0028: withFix("Set `access.signIn` to the inline path of a sign-in page, for example `signIn: '/login'`, or to a provider, for example `signIn: { provider: 'github' }`."),
57
93
  AUTH_C0029: withFix("Set `access.signIn.requestSignUp` to `true` or `false`, or remove it."),
58
94
  AUTH_C0030: withFix("Set `access.signIn.scopes` to an array of strings, for example `scopes: ['read:org']`."),
59
95
  AUTH_C0031: withFix("Write each entry of `access.routes` as a route string or an object, for example `'/admin/**'` or `{ route: '/api/admin/**', authorize }`."),
@@ -93,7 +129,7 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
93
129
  AUTH_C0062: withFix("Return a Better Auth `secondaryStorage` adapter, an object with `get`, `set`, and `delete`, or remove `secondaryStorage`."),
94
130
  AUTH_C0063: withFix("Set `database: authDatabase()` with `import { authDatabase } from 'vite-hub/auth/database'` to keep users in the app Database. Use `preset: stateless()` for social sign-in without a database. Set `database: \"memory\"` only when one server process may keep users until it restarts."),
95
131
  AUTH_C0064: withFix("Write `access.public` as an inline array of route strings, for example `public: ['/', '/login', '/api/health']`. The Vite plugin reads it at build time."),
96
- AUTH_C0065: withFix("Set `access.policy` to an object with an `allow` function, for example `policy: { allow: ({ user }) => user.emailVerified === true, recheck: 300_000 }`. `recheck` is a number of milliseconds, 0 or more."),
132
+ AUTH_C0065: withFix("Set `access.policy` to an object with an `allow` function, for example `policy: { allow: ({ user }) => user.emailVerified === true, recheck: \"5m\" }`. `recheck` is a duration string, such as `\"30s\"` or `\"5m\"`."),
97
133
  AUTH_C0066: withFix("Return `database: authDatabase()` or another Better Auth adapter, or a `secondaryStorage` adapter. `access.policy` ends sessions, so Auth must store them."),
98
134
  AUTH_C0067: withFix("Pass both options, for example `forwardAuth({ header: 'x-auth-request-access-token', verify: async ({ value }) => lookUpIdentity(value) })`. `verify` must prove the header, for example with the provider or a secret that only the proxy sends."),
99
135
  AUTH_C0068: withFix("Write each access route as a literal path, without percent-encoded pattern syntax or `.` and `..` segments. To guard a path and every path below it, end the route with `/**`, for example `/api/users/**` in place of `/api/users/:id` or `/api/admin/*`. Check the parameter in the handler."),
@@ -1,4 +1,4 @@
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 isRecord } from "./object-Da1zyPCR.js";
3
3
  import { defineErrors } from "@vite-hub/runtime";
4
4
  import { sql } from "drizzle-orm";
@@ -108,15 +108,6 @@ async function checkGitHubOrgMember(accessToken, org, options = {}) {
108
108
  }
109
109
  return result;
110
110
  }
111
- /**
112
- * Returns `true` when the GitHub user of `accessToken` is an active member of `org`. The token needs the `read:org` scope.
113
- * Every failure returns `false`. Use `checkGitHubOrgMember()` to know why.
114
- */
115
- async function isGitHubOrgMember(accessToken, org, options = {}) {
116
- if (!org) return false;
117
- const [error] = await checkGitHubOrgMember(accessToken, org, options);
118
- return !error;
119
- }
120
111
  //#endregion
121
112
  //#region src/events.ts
122
113
  const authEventTypes = [
@@ -140,6 +131,7 @@ const authEventTypes = [
140
131
  ];
141
132
  const text = v.pipe(v.string(), v.minLength(1), v.maxLength(256));
142
133
  const timestamp = v.pipe(v.string(), v.isoTimestamp());
134
+ const queryTimestamp = v.pipe(timestamp, v.check((value) => Number.isFinite(Date.parse(value))));
143
135
  const actor = v.custom((value) => typeof value === "string" && value.length <= 512 && /^(system|user:.+)$/.test(value));
144
136
  const metadata = v.object({
145
137
  method: v.optional(v.pipe(text, v.regex(/^[a-zA-Z0-9_.:-]+$/))),
@@ -166,13 +158,13 @@ const eventSchema = v.object({
166
158
  metadata
167
159
  });
168
160
  const rowSchema = v.object({ payload: v.string() });
169
- const cursorSchema = v.tuple([timestamp, text]);
161
+ const cursorSchema = v.tuple([queryTimestamp, text]);
170
162
  const listSchema = v.object({
171
163
  type: v.optional(v.union([v.picklist(authEventTypes), v.pipe(v.array(v.picklist(authEventTypes)), v.minLength(1), v.maxLength(authEventTypes.length))])),
172
164
  userId: v.optional(text),
173
165
  actor: v.optional(actor),
174
- from: v.optional(timestamp),
175
- to: v.optional(timestamp),
166
+ from: v.optional(queryTimestamp),
167
+ to: v.optional(queryTimestamp),
176
168
  cursor: v.optional(v.pipe(v.string(), v.maxLength(2048))),
177
169
  limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(200)))
178
170
  });
@@ -311,4 +303,4 @@ function createDatabaseAuthEventStore(options) {
311
303
  };
312
304
  }
313
305
  //#endregion
314
- export { checkGitHubOrgMember as a, parseAuthEventWindow as i, defaultAuthEventRetention as n, isGitHubOrgMember as o, parseAuthEventList as r, createDatabaseAuthEventStore as t };
306
+ export { checkGitHubOrgMember as a, parseAuthEventWindow as i, defaultAuthEventRetention as n, parseAuthEventList as r, createDatabaseAuthEventStore as t };
package/dist/forward.js CHANGED
@@ -1,4 +1,4 @@
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 { createAuthMiddleware } from "better-auth/api";
3
3
  import { applySetCookies, deleteSessionCookie, setSessionCookie } from "better-auth/cookies";
4
4
  import { handleOAuthUserInfo, setTokenUtil } from "better-auth/oauth2";
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /// <reference path="./host-declarations.d.ts" />
2
- import { A as AuthRuntimeOption, At as AuthEventCounts, Bt as defaultAuthEventRetention, C as AuthRequest, D as AuthRuntimeContext, Dt as AuthEvent, E as AuthResolvedDefinitionOptions, Et as AuthDevice, F as AuthSessionRefreshFields, Ft as AuthEventStore, H as ViteHubAuth, I as AuthSignInConfiguration, It as AuthEventType, J as AuthConsoleColumn, L as AuthViteHubOptions, Lt as AuthEventWindow, M as AuthSessionOptions, Mt as AuthEventMetadata, N as AuthSessionRefresh, Nt as AuthEventPage, O as AuthRuntimeEnv, Ot as AuthEventActor, P as AuthSessionRefreshContext, Pt as AuthEventRetention, R as DiscoveredAuthDefinition, Rt as AuthEventsConfiguration, S as AuthOptions, T as AuthReservedOption, V as ResolvedAuthViteConfig, _ as AuthDefinitionInput, a as AuthAccessPolicy, b as AuthFor, c as AuthAccessRouteConfiguration, ct as AuthConsoleOptions, d as AuthAnonymousGuardedHandler, et as AuthConsoleFieldPolicy, g as AuthDefinition, h as AuthBetterAuthRuntimeOptions, ht as AuthConsoleRoles, i as AuthAccessConfiguration, j as AuthRuntimeOptions, jt as AuthEventListInput, k as AuthRuntimeOnlyOptions, kt as AuthEventAggregates, l as AuthAnonymousAuthorization, m as AuthBetterAuthOptions, n as AuthAccessAuthorize, o as AuthAccessPolicyContext, p as AuthAuthorization, pt as AuthConsolePolicy, r as AuthAccessAuthorizeResult, s as AuthAccessRoute, t as AuthAccessAuthorizationContext, u as AuthAnonymousAuthorize, v as AuthDefinitionOptions, x as AuthGuardedHandler, y as AuthDefinitionResolver, z as RegisteredAuth, zt as createDatabaseAuthEventStore } from "./types-CNaeH2Fd.js";
3
- import { i as AuthStatelessPresetOptions, n as AuthPreset, r as AuthStatelessPreset, t as AuthDuration } from "./presets-BGZi6Dfu.js";
2
+ import { A as AuthRuntimeOnlyOptions, At as AuthEventMetadata, B as RegisteredAuth, C as AuthOptions, D as AuthResolvedDefinitionOptions, Dt as AuthEventAggregates, E as AuthReservedOption, Et as AuthEventActor, F as AuthSessionRefreshContext, Ft as AuthEventWindow, H as ResolvedAuthViteConfig, I as AuthSessionRefreshFields, It as AuthEventsConfiguration, L as AuthSignInConfiguration, Lt as createDatabaseAuthEventStore, M as AuthRuntimeOptions, Mt as AuthEventRetention, N as AuthSessionOptions, Nt as AuthEventStore, O as AuthRuntimeContext, Ot as AuthEventCounts, P as AuthSessionRefresh, Pt as AuthEventType, R as AuthViteHubOptions, Rt as defaultAuthEventRetention, S as AuthGuardedHandler, Tt as AuthEvent, U as ViteHubAuth, Y as AuthConsoleColumn, _ as AuthDefinitionInput, a as AuthAccessPolicy, b as AuthDeleteAccountOptions, c as AuthAccessRouteConfiguration, d as AuthAnonymousGuardedHandler, g as AuthDefinition, gt as AuthConsoleRoles, h as AuthBetterAuthRuntimeOptions, i as AuthAccessConfiguration, j as AuthRuntimeOption, jt as AuthEventPage, k as AuthRuntimeEnv, kt as AuthEventListInput, l as AuthAnonymousAuthorization, lt as AuthConsoleOptions, m as AuthBetterAuthOptions, mt as AuthConsolePolicy, n as AuthAccessAuthorize, o as AuthAccessPolicyContext, p as AuthAuthorization, r as AuthAccessAuthorizeResult, s as AuthAccessRoute, t as AuthAccessAuthorizationContext, tt as AuthConsoleFieldPolicy, u as AuthAnonymousAuthorize, v as AuthDefinitionOptions, w as AuthRequest, wt as AuthDevice, x as AuthFor, y as AuthDefinitionResolver, z as DiscoveredAuthDefinition } from "./types-CruflEFI.js";
3
+ import { n as AuthStatelessPreset, r as AuthStatelessPresetOptions, t as AuthPreset } from "./presets-CHndEv5i.js";
4
4
  import { Result } from "@vite-hub/runtime";
5
5
  //#region src/definition.d.ts
6
6
  export declare function defineAuth<const TOptions extends AuthResolvedDefinitionOptions>(options: AuthDefinitionResolver<TOptions>): AuthDefinition<AuthDefinitionResolver<TOptions>>;
@@ -20,10 +20,5 @@ type GitHubOrgMemberErrorCode = "AUTH_GITHUB_NOT_ORG_MEMBER" | "AUTH_GITHUB_ORG_
20
20
  * Returns `[undefined, undefined]` for an active membership, else the error that says why it could not confirm one.
21
21
  */
22
22
  export declare function checkGitHubOrgMember(accessToken: string | null | undefined, org: string, options?: GitHubOrgMemberOptions): Promise<Result<void, GitHubOrgMemberErrorCode>>;
23
- /**
24
- * Returns `true` when the GitHub user of `accessToken` is an active member of `org`. The token needs the `read:org` scope.
25
- * Every failure returns `false`. Use `checkGitHubOrgMember()` to know why.
26
- */
27
- export declare function isGitHubOrgMember(accessToken: string | null | undefined, org: string, options?: GitHubOrgMemberOptions): Promise<boolean>;
28
23
  //#endregion
29
- export { type AuthAccessAuthorizationContext, type AuthAccessAuthorize, type AuthAccessAuthorizeResult, type AuthAccessConfiguration, type AuthAccessPolicy, type AuthAccessPolicyContext, type AuthAccessRoute, type AuthAccessRouteConfiguration, type AuthAnonymousAuthorization, type AuthAnonymousAuthorize, type AuthAnonymousGuardedHandler, type AuthAuthorization, type AuthBetterAuthOptions, type AuthBetterAuthRuntimeOptions, type AuthConsoleColumn, type AuthConsoleFieldPolicy, type AuthConsoleOptions, type AuthConsolePolicy, type AuthConsoleRoles, type AuthDefinition, type AuthDefinitionInput, type AuthDefinitionOptions, type AuthDefinitionResolver, type AuthDevice, type AuthDuration, type AuthEvent, type AuthEventActor, type AuthEventAggregates, type AuthEventCounts, type AuthEventListInput, type AuthEventMetadata, type AuthEventPage, type AuthEventRetention, type AuthEventStore, type AuthEventType, type AuthEventWindow, type AuthEventsConfiguration, type AuthFor, type AuthGuardedHandler, type AuthOptions, type AuthPreset, type AuthRequest, type AuthReservedOption, type AuthResolvedDefinitionOptions, type AuthRuntimeContext, type AuthRuntimeEnv, type AuthRuntimeOnlyOptions, type AuthRuntimeOption, type AuthRuntimeOptions, type AuthSessionOptions, type AuthSessionRefresh, type AuthSessionRefreshContext, type AuthSessionRefreshFields, type AuthSignInConfiguration, type AuthStatelessPreset, type AuthStatelessPresetOptions, type AuthViteHubOptions, type DiscoveredAuthDefinition, type GitHubOrgMemberErrorCode, type GitHubOrgMemberOptions, type RegisteredAuth, type ResolvedAuthViteConfig, type ViteHubAuth, createDatabaseAuthEventStore, defaultAuthEventRetention };
24
+ export { type AuthAccessAuthorizationContext, type AuthAccessAuthorize, type AuthAccessAuthorizeResult, type AuthAccessConfiguration, type AuthAccessPolicy, type AuthAccessPolicyContext, type AuthAccessRoute, type AuthAccessRouteConfiguration, type AuthAnonymousAuthorization, type AuthAnonymousAuthorize, type AuthAnonymousGuardedHandler, type AuthAuthorization, type AuthBetterAuthOptions, type AuthBetterAuthRuntimeOptions, type AuthConsoleColumn, type AuthConsoleFieldPolicy, type AuthConsoleOptions, type AuthConsolePolicy, type AuthConsoleRoles, type AuthDefinition, type AuthDefinitionInput, type AuthDefinitionOptions, type AuthDefinitionResolver, type AuthDeleteAccountOptions, type AuthDevice, type AuthEvent, type AuthEventActor, type AuthEventAggregates, type AuthEventCounts, type AuthEventListInput, type AuthEventMetadata, type AuthEventPage, type AuthEventRetention, type AuthEventStore, type AuthEventType, type AuthEventWindow, type AuthEventsConfiguration, type AuthFor, type AuthGuardedHandler, type AuthOptions, type AuthPreset, type AuthRequest, type AuthReservedOption, type AuthResolvedDefinitionOptions, type AuthRuntimeContext, type AuthRuntimeEnv, type AuthRuntimeOnlyOptions, type AuthRuntimeOption, type AuthRuntimeOptions, type AuthSessionOptions, type AuthSessionRefresh, type AuthSessionRefreshContext, type AuthSessionRefreshFields, type AuthSignInConfiguration, type AuthStatelessPreset, type AuthStatelessPresetOptions, type AuthViteHubOptions, type DiscoveredAuthDefinition, type GitHubOrgMemberErrorCode, type GitHubOrgMemberOptions, type RegisteredAuth, type ResolvedAuthViteConfig, type ViteHubAuth, createDatabaseAuthEventStore, defaultAuthEventRetention };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { a as checkGitHubOrgMember, n as defaultAuthEventRetention, o as isGitHubOrgMember, t as createDatabaseAuthEventStore } from "./events-ByzenEVj.js";
2
- import { n as defineAuth } from "./definition-CqQMcDEK.js";
3
- export { checkGitHubOrgMember, createDatabaseAuthEventStore, defaultAuthEventRetention, defineAuth, isGitHubOrgMember };
1
+ import { a as checkGitHubOrgMember, n as defaultAuthEventRetention, t as createDatabaseAuthEventStore } from "./events-DCfuicoo.js";
2
+ import { n as defineAuth } from "./definition-BCaLA9kW.js";
3
+ export { checkGitHubOrgMember, createDatabaseAuthEventStore, defaultAuthEventRetention, defineAuth };
@@ -1,5 +1,5 @@
1
1
  /// <reference path="../host-declarations.d.ts" />
2
- import { A as createBetterAuthOptions, C as signOut, D as withAuth, E as withAnonymousAuthorization, O as withAuthorization, S as requireAuthorization, T as useAuth, _ as handleAuthRequest, a as authRoute, b as requireAuth, c as createAuth, d as createAuthHandler, f as createAuthRequestRuntimeOptions, g as handleAuth, h as getAuthEvents, i as auth, j as getAuthForDefinition, l as createAuthAccessHandler, m as getAuthConsoleForRequest, n as aggregateAuthEvents, o as can, p as getAuth, r as assertAuthOrigin, s as checkAuthMember, t as AuthSignOutOptions, u as createAuthForRequest, v as listAuthEvents, w as toAuthRequest, x as requireAuthAccessRoutes, y as requireAbility } from "../server-C0qnKN2W.js";
3
- import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-bQGzVQ--.js";
2
+ import { C as requireCaller, D as withAnonymousAuthorization, E as useAuth, M as getAuthForDefinition, O as withAuth, S as requireAuthorization, T as toAuthRequest, _ as handleAuthRequest, a as authRoute, b as requireAuth, c as createAuth, d as createAuthHandler, f as createAuthRequestRuntimeOptions, g as handleAuth, h as getAuthEvents, i as assertAuthOrigin, j as createBetterAuthOptions, k as withAuthorization, l as createAuthAccessHandler, m as getAuthConsoleForRequest, n as AuthSignOutOptions, o as can, p as getAuth, r as aggregateAuthEvents, s as checkAuthMember, t as AuthEventReadErrorCode, u as createAuthForRequest, v as listAuthEvents, w as signOut, x as requireAuthAccessRoutes, y as requireAbility } from "../server-BM-RSf1T.js";
3
+ import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-C8TlOrSy.js";
4
4
  import { n as AbilityErrorData, t as AbilityError } from "../ability-error-DcgChwCN.js";
5
- export { AbilityError, type AbilityErrorData, AuthSignOutOptions, aggregateAuthEvents, assertAuthOrigin, auth, can, checkAuthMember, createAuth, createAuthAccessHandler, createAuthForRequest, createAuthHandler, createAuthRequestRuntimeOptions, createBetterAuthOptions, authRoute as default, getAuth, getAuthConsoleForRequest, getAuthEvents, getAuthForDefinition, handleAuth, handleAuthRequest, listAuthEvents, requireAbility, requireAuth, requireAuthAccessRoutes, requireAuthorization, resetAuth, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
5
+ export { AbilityError, type AbilityErrorData, AuthEventReadErrorCode, AuthSignOutOptions, aggregateAuthEvents, assertAuthOrigin, can, checkAuthMember, createAuth, createAuthAccessHandler, createAuthForRequest, createAuthHandler, createAuthRequestRuntimeOptions, createBetterAuthOptions, authRoute as default, getAuth, getAuthConsoleForRequest, getAuthEvents, getAuthForDefinition, handleAuth, handleAuthRequest, listAuthEvents, requireAbility, requireAuth, requireAuthAccessRoutes, requireAuthorization, requireCaller, resetAuth, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };