@vite-hub/auth 0.0.3 → 0.1.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 (50) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +213 -41
  3. package/dist/agent.d.ts +25 -13
  4. package/dist/agent.js +19 -5
  5. package/dist/application-path-C290OAIs.js +18 -0
  6. package/dist/cli-mgXvsBtA.d.ts +85 -0
  7. package/dist/cli.d.ts +7 -0
  8. package/dist/cli.js +68 -0
  9. package/dist/console-B7eERmGv.d.ts +180 -0
  10. package/dist/console-runtime-bZQtnX2Y.d.ts +39 -0
  11. package/dist/console-runtime.d.ts +3 -0
  12. package/dist/console-runtime.js +819 -0
  13. package/dist/console-types-CmmnKGMx.js +38 -0
  14. package/dist/console.d.ts +7 -0
  15. package/dist/console.js +15 -0
  16. package/dist/error-diagnostics-CL0yjHiM.js +79 -0
  17. package/dist/events-BkmK2dFY.d.ts +486 -0
  18. package/dist/events-P7mI4IQb.js +196 -0
  19. package/dist/events-config-CjcFOhTE.js +177 -0
  20. package/dist/host-declarations.d.ts +17 -0
  21. package/dist/index.d.ts +6 -5
  22. package/dist/index.js +40 -28
  23. package/dist/inspect-DPtsW8dB.d.ts +36 -0
  24. package/dist/nuxt.d.ts +59 -0
  25. package/dist/nuxt.js +93 -0
  26. package/dist/presets-BGZi6Dfu.d.ts +25 -0
  27. package/dist/presets.d.ts +2 -0
  28. package/dist/presets.js +32 -0
  29. package/dist/runtime/console.d.ts +7 -0
  30. package/dist/runtime/console.js +42 -0
  31. package/dist/runtime/empty-definition.d.ts +1 -2
  32. package/dist/runtime/nuxt.d.ts +3 -0
  33. package/dist/runtime/nuxt.js +9 -0
  34. package/dist/runtime/vue-nuxt.d.ts +3 -0
  35. package/dist/runtime/vue-nuxt.js +8 -0
  36. package/dist/server-B7LU19dS.js +1730 -0
  37. package/dist/server-CTD_JAww.d.ts +77 -0
  38. package/dist/server.d.ts +3 -20
  39. package/dist/server.js +3 -2
  40. package/dist/set-cookie-2as_DbHe.js +75 -0
  41. package/dist/shared-DnpgYiLF.js +15 -0
  42. package/dist/vite-COWkwxsj.js +990 -0
  43. package/dist/vite.d.ts +34 -10
  44. package/dist/vite.js +2 -995
  45. package/dist/vue.d.ts +55 -0
  46. package/dist/vue.js +112 -0
  47. package/package.json +92 -17
  48. package/dist/server-Diw3mAbX.js +0 -322
  49. package/dist/shared-QSYBHaMG.js +0 -12
  50. package/dist/types-B0fg9XFd.d.ts +0 -106
@@ -0,0 +1,196 @@
1
+ import { sql } from "drizzle-orm";
2
+ import * as v from "valibot";
3
+ //#region src/events.ts
4
+ const authEventTypes = [
5
+ "user.signed_up",
6
+ "user.signed_in",
7
+ "user.signed_out",
8
+ "sign_in.failed",
9
+ "session.revoked",
10
+ "user.banned",
11
+ "user.unbanned",
12
+ "user.role_changed",
13
+ "user.updated",
14
+ "user.removed",
15
+ "impersonation.started",
16
+ "impersonation.stopped",
17
+ "oauth.consent_granted",
18
+ "oauth.consent_revoked",
19
+ "organization.member_added",
20
+ "organization.member_removed",
21
+ "organization.member_role_changed"
22
+ ];
23
+ const text = v.pipe(v.string(), v.minLength(1), v.maxLength(256));
24
+ const timestamp = v.pipe(v.string(), v.isoTimestamp());
25
+ const actor = v.custom((value) => typeof value === "string" && value.length <= 512 && /^(system|user:.+)$/.test(value));
26
+ const metadata = v.object({
27
+ method: v.optional(v.pipe(text, v.regex(/^[a-zA-Z0-9_.:-]+$/))),
28
+ device: v.optional(v.picklist([
29
+ "desktop",
30
+ "mobile",
31
+ "tablet",
32
+ "bot",
33
+ "unknown"
34
+ ])),
35
+ sessionId: v.optional(text),
36
+ fields: v.optional(v.pipe(v.array(v.pipe(text, v.regex(/^[a-zA-Z][a-zA-Z0-9_]*$/))), v.maxLength(100))),
37
+ role: v.optional(text),
38
+ clientId: v.optional(text),
39
+ organizationId: v.optional(text),
40
+ memberId: v.optional(text)
41
+ });
42
+ const eventSchema = v.object({
43
+ id: text,
44
+ type: v.picklist(authEventTypes),
45
+ time: timestamp,
46
+ actor,
47
+ userId: v.nullable(text),
48
+ metadata
49
+ });
50
+ const rowSchema = v.object({ payload: v.string() });
51
+ const cursorSchema = v.tuple([timestamp, text]);
52
+ const listSchema = v.object({
53
+ type: v.optional(v.union([v.picklist(authEventTypes), v.pipe(v.array(v.picklist(authEventTypes)), v.minLength(1), v.maxLength(authEventTypes.length))])),
54
+ userId: v.optional(text),
55
+ actor: v.optional(actor),
56
+ from: v.optional(timestamp),
57
+ to: v.optional(timestamp),
58
+ cursor: v.optional(v.pipe(v.string(), v.maxLength(2048))),
59
+ limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(200)))
60
+ });
61
+ function parseAuthEventList(input) {
62
+ const query = v.parse(listSchema, input);
63
+ const before = query.cursor ? v.parse(cursorSchema, JSON.parse(decodeURIComponent(query.cursor))) : void 0;
64
+ if (query.from && query.to && Date.parse(query.from) >= Date.parse(query.to)) throw new TypeError("Auth event from must be before to.");
65
+ return {
66
+ query,
67
+ before
68
+ };
69
+ }
70
+ function parseAuthEventWindow(window) {
71
+ const from = new Date(v.parse(timestamp, window.from)).toISOString();
72
+ const to = new Date(v.parse(timestamp, window.to)).toISOString();
73
+ if (from >= to || Date.parse(to) - Date.parse(from) > 316224e5) throw new TypeError("Auth event windows must be positive and at most 366 days.");
74
+ return {
75
+ from,
76
+ to
77
+ };
78
+ }
79
+ const defaultAuthEventRetention = {
80
+ maxAgeMs: 7776e6,
81
+ maxRecords: 1e5
82
+ };
83
+ /** One SQLite store contract for Node SQLite, libSQL, and Cloudflare D1 Drizzle databases. */
84
+ function createDatabaseAuthEventStore(options) {
85
+ const { db } = options;
86
+ const retention = options.retention === false ? false : {
87
+ ...defaultAuthEventRetention,
88
+ ...options.retention
89
+ };
90
+ if (retention && Object.values(retention).some((value) => !Number.isSafeInteger(value) || value < 1)) throw new TypeError("Auth event retention limits must be positive integers.");
91
+ let ready;
92
+ const initialize = () => ready ??= (async () => {
93
+ await db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_auth_events (id TEXT PRIMARY KEY, type TEXT NOT NULL, time TEXT NOT NULL, actor TEXT NOT NULL, user_id TEXT, method TEXT, payload TEXT NOT NULL)`);
94
+ await db.run(sql`CREATE INDEX IF NOT EXISTS vitehub_auth_events_time ON vitehub_auth_events (time, id)`);
95
+ await db.run(sql`CREATE INDEX IF NOT EXISTS vitehub_auth_events_type ON vitehub_auth_events (type, time, id)`);
96
+ await db.run(sql`CREATE INDEX IF NOT EXISTS vitehub_auth_events_user ON vitehub_auth_events (user_id, time, id)`);
97
+ await db.run(sql`CREATE INDEX IF NOT EXISTS vitehub_auth_events_actor ON vitehub_auth_events (actor, time, id)`);
98
+ })().catch((error) => {
99
+ ready = void 0;
100
+ throw error;
101
+ });
102
+ const cutoff = () => new Date(Math.max(0, Date.now() - (retention ? retention.maxAgeMs : Date.now()))).toISOString();
103
+ const visible = () => retention ? sql`time >= ${cutoff()}` : sql`1 = 1`;
104
+ return {
105
+ async append(input) {
106
+ const event = v.parse(eventSchema, input);
107
+ event.time = new Date(event.time).toISOString();
108
+ await initialize();
109
+ await db.run(sql`INSERT INTO vitehub_auth_events (id, type, time, actor, user_id, method, payload) VALUES (${event.id}, ${event.type}, ${event.time}, ${event.actor}, ${event.userId}, ${event.metadata.method ?? null}, ${JSON.stringify(event)}) ON CONFLICT (id) DO NOTHING`);
110
+ if (retention) await db.run(sql`DELETE FROM vitehub_auth_events WHERE time < ${cutoff()} OR (time, id) <= (SELECT time, id FROM vitehub_auth_events ORDER BY time DESC, id DESC LIMIT 1 OFFSET ${retention.maxRecords})`);
111
+ },
112
+ async list(input = {}) {
113
+ const { query, before } = parseAuthEventList(input);
114
+ const limit = query.limit ?? 50;
115
+ await initialize();
116
+ const rows = await db.all(sql`SELECT payload FROM vitehub_auth_events WHERE ${visible()}
117
+ ${query.type ? sql`AND type IN (${sql.join((typeof query.type === "string" ? [query.type] : query.type).map((type) => sql`${type}`), sql`, `)})` : sql``}
118
+ ${query.userId ? sql`AND user_id = ${query.userId}` : sql``}
119
+ ${query.actor ? sql`AND actor = ${query.actor}` : sql``}
120
+ ${query.from ? sql`AND time >= ${new Date(query.from).toISOString()}` : sql``}
121
+ ${query.to ? sql`AND time < ${new Date(query.to).toISOString()}` : sql``}
122
+ ${before ? sql`AND (time, id) < (${before[0]}, ${before[1]})` : sql``}
123
+ ORDER BY time DESC, id DESC LIMIT ${limit + 1}`);
124
+ const events = rows.slice(0, limit).map((row) => v.parse(eventSchema, JSON.parse(v.parse(rowSchema, row).payload)));
125
+ const last = events.at(-1);
126
+ return {
127
+ events,
128
+ ...rows.length > limit && last ? { nextCursor: encodeURIComponent(JSON.stringify([last.time, last.id])) } : {}
129
+ };
130
+ },
131
+ async aggregate(window) {
132
+ const { from, to } = parseAuthEventWindow(window);
133
+ await initialize();
134
+ const where = sql`${visible()} AND time >= ${from} AND time < ${to} AND type IN ('user.signed_up', 'user.signed_in')`;
135
+ const counts = sql`SUM(CASE WHEN type = 'user.signed_up' THEN 1 ELSE 0 END) AS signUps, SUM(CASE WHEN type = 'user.signed_in' THEN 1 ELSE 0 END) AS signIns, COUNT(DISTINCT CASE WHEN type = 'user.signed_in' THEN user_id END) AS activeUsers`;
136
+ const rows = await db.all(sql`SELECT substr(time, 1, 10) AS day, ${counts}, NULL AS method, NULL AS count FROM vitehub_auth_events WHERE ${where} GROUP BY day
137
+ UNION ALL SELECT NULL AS day, ${counts}, NULL AS method, NULL AS count FROM vitehub_auth_events WHERE ${where}
138
+ UNION ALL SELECT substr(time, 1, 10) AS day, NULL AS signUps, NULL AS signIns, NULL AS activeUsers, method, COUNT(*) AS count FROM vitehub_auth_events WHERE ${where} AND type = 'user.signed_in' GROUP BY day, method`);
139
+ const methods = rows.filter((row) => row.count !== null);
140
+ const empty = () => ({
141
+ signUps: 0,
142
+ signIns: 0,
143
+ activeUsers: 0,
144
+ methods: {}
145
+ });
146
+ const days = /* @__PURE__ */ new Map();
147
+ for (let time = Date.parse(`${from.slice(0, 10)}T00:00:00.000Z`); time < Date.parse(to); time += 864e5) days.set(new Date(time).toISOString().slice(0, 10), empty());
148
+ let totals = empty();
149
+ const countSchema = v.object({
150
+ day: v.nullable(v.string()),
151
+ signUps: v.nullable(v.number()),
152
+ signIns: v.nullable(v.number()),
153
+ activeUsers: v.number()
154
+ });
155
+ for (const row of rows.filter((row) => row.count === null)) {
156
+ const item = v.parse(countSchema, row);
157
+ const value = {
158
+ signUps: item.signUps ?? 0,
159
+ signIns: item.signIns ?? 0,
160
+ activeUsers: item.activeUsers,
161
+ methods: {}
162
+ };
163
+ if (item.day) days.set(item.day, value);
164
+ else totals = value;
165
+ }
166
+ for (const row of methods) {
167
+ const item = v.parse(v.object({
168
+ day: v.string(),
169
+ method: v.nullable(v.string()),
170
+ count: v.number()
171
+ }), row);
172
+ const method = item.method ?? "unknown";
173
+ const day = days.get(item.day);
174
+ if (day) Object.defineProperty(day.methods, method, {
175
+ value: item.count,
176
+ enumerable: true,
177
+ configurable: true
178
+ });
179
+ Object.defineProperty(totals.methods, method, {
180
+ value: (Object.hasOwn(totals.methods, method) ? totals.methods[method] : 0) + item.count,
181
+ enumerable: true,
182
+ configurable: true
183
+ });
184
+ }
185
+ return {
186
+ days: [...days].map(([day, value]) => ({
187
+ day,
188
+ ...value
189
+ })),
190
+ totals
191
+ };
192
+ }
193
+ };
194
+ }
195
+ //#endregion
196
+ export { parseAuthEventWindow as a, parseAuthEventList as i, createDatabaseAuthEventStore as n, defaultAuthEventRetention as r, authEventTypes as t };
@@ -0,0 +1,177 @@
1
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CL0yjHiM.js";
2
+ //#region src/stateless-user-id.ts
3
+ const pendingUserIds = /* @__PURE__ */ new WeakMap();
4
+ /** The user ID of one provider account: the first 32 hex digits of SHA-256 over the provider ID and the account ID. */
5
+ async function statelessUserId(providerId, accountId) {
6
+ const input = new TextEncoder().encode(JSON.stringify([
7
+ "vitehub:auth:user",
8
+ providerId,
9
+ accountId
10
+ ]));
11
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", input));
12
+ return Array.from(digest.slice(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
13
+ }
14
+ /** The account ID that Better Auth stores for this provider profile, from the provider's own `accountSubject`. */
15
+ async function accountSubject(context, providerId, profile) {
16
+ const subject = await context.context.socialProviders.find((candidate) => candidate.id === providerId)?.accountSubject({
17
+ profile,
18
+ tokens: {}
19
+ });
20
+ return subject === void 0 || subject === null || String(subject).trim() === "" ? void 0 : String(subject);
21
+ }
22
+ /**
23
+ * Without a database, Better Auth creates a new user at each sign-in. These hooks give that user an ID derived from
24
+ * the provider account, so the same account gets the same `user.id` on every sign-in, instance, and restart.
25
+ * They wrap the application's own `user.validateUserInfo` and `databaseHooks.user.create.before`.
26
+ */
27
+ function withStatelessUserId(options) {
28
+ const user = options.user ?? {};
29
+ const databaseHooks = options.databaseHooks ?? {};
30
+ const validateUserInfo = user.validateUserInfo;
31
+ const createBefore = databaseHooks.user?.create?.before;
32
+ const validate = async (data, context) => {
33
+ const { source } = data;
34
+ if (source.action === "create-user" && source.method === "oauth" && source.oauth) {
35
+ const accountId = await accountSubject(context, source.oauth.providerId, source.oauth.profile ?? {});
36
+ if (accountId === void 0) return {
37
+ error: "vitehub_account_subject_missing",
38
+ errorDescription: "The provider did not return an account ID."
39
+ };
40
+ pendingUserIds.set(context, await statelessUserId(source.oauth.providerId, accountId));
41
+ }
42
+ return validateUserInfo?.(data, context);
43
+ };
44
+ const before = async (data, context) => {
45
+ const result = createBefore ? await createBefore(data, context) : void 0;
46
+ const id = context ? pendingUserIds.get(context) : void 0;
47
+ if (result === false || id === void 0) return result;
48
+ if (context) pendingUserIds.delete(context);
49
+ return { data: {
50
+ ...typeof result === "object" ? result.data : {},
51
+ id
52
+ } };
53
+ };
54
+ return {
55
+ databaseHooks: {
56
+ ...databaseHooks,
57
+ user: {
58
+ ...databaseHooks.user,
59
+ create: {
60
+ ...databaseHooks.user?.create,
61
+ before
62
+ }
63
+ }
64
+ },
65
+ user: {
66
+ ...user,
67
+ validateUserInfo: validate
68
+ }
69
+ };
70
+ }
71
+ //#endregion
72
+ //#region src/preset-options.ts
73
+ const verificationPluginIds = /* @__PURE__ */ new Set([
74
+ "email-otp",
75
+ "magic-link",
76
+ "one-time-token"
77
+ ]);
78
+ const statelessOwnedOptions = [
79
+ ["session", "expiresIn"],
80
+ [
81
+ "session",
82
+ "cookieCache",
83
+ "enabled"
84
+ ],
85
+ [
86
+ "session",
87
+ "cookieCache",
88
+ "maxAge"
89
+ ],
90
+ [
91
+ "session",
92
+ "cookieCache",
93
+ "refreshCache"
94
+ ],
95
+ [
96
+ "session",
97
+ "cookieCache",
98
+ "strategy"
99
+ ],
100
+ ["account", "storeAccountCookie"],
101
+ ["account", "storeStateStrategy"]
102
+ ];
103
+ function isPlainObject(value) {
104
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
105
+ }
106
+ function readPath(value, path) {
107
+ let current = value;
108
+ for (const key of path) {
109
+ if (!isPlainObject(current) || !Object.hasOwn(current, key)) return void 0;
110
+ current = current[key];
111
+ }
112
+ return current;
113
+ }
114
+ function readStatelessPreset(value) {
115
+ if (isPlainObject(value) && value.name === "stateless" && typeof value.maxAge === "number" && Number.isSafeInteger(value.maxAge) && value.maxAge > 0) return {
116
+ name: "stateless",
117
+ maxAge: value.maxAge
118
+ };
119
+ throw authErrorDiagnostics.AUTH_C0043({ message: "`defineAuth()` preset must be a preset such as `stateless()` from `@vite-hub/auth/presets`." });
120
+ }
121
+ function storedPluginId(plugin) {
122
+ if (!isPlainObject(plugin)) return;
123
+ const id = typeof plugin.id === "string" ? plugin.id : "unknown";
124
+ if (isPlainObject(plugin.schema) && Object.keys(plugin.schema).length > 0) return id;
125
+ if (verificationPluginIds.has(id)) return id;
126
+ }
127
+ /** Checks that the options can run with `stateless()` and returns the Better Auth options it sets. */
128
+ function applyStatelessPreset(preset, options) {
129
+ if (options.database !== void 0) throw authErrorDiagnostics.AUTH_C0044({ message: "`stateless()` keeps sessions in cookies and cannot use `database`. Remove `database`, or remove the preset to store sessions in a database." });
130
+ if (options.secondaryStorage !== void 0) throw authErrorDiagnostics.AUTH_C0045({ message: "`stateless()` keeps sessions in cookies and cannot use `secondaryStorage`. Remove `secondaryStorage`, or remove the preset to store sessions on the server." });
131
+ if (readPath(options, ["emailAndPassword", "enabled"]) === true) throw authErrorDiagnostics.AUTH_C0046({ message: "`stateless()` has no database to store users and passwords, so `emailAndPassword` cannot be enabled. Use `socialProviders`, or remove the preset and configure a database." });
132
+ const plugin = Array.isArray(options.plugins) ? options.plugins.map(storedPluginId).find(Boolean) : void 0;
133
+ if (plugin) throw authErrorDiagnostics.AUTH_C0047({ message: `\`stateless()\` has no database, and the Better Auth plugin "${plugin}" stores data in one. Remove the plugin, or remove the preset and configure a database.` });
134
+ const owned = statelessOwnedOptions.find((path) => readPath(options, path) !== void 0);
135
+ if (owned) throw authErrorDiagnostics.AUTH_C0048({ message: `\`stateless()\` sets \`${owned.join(".")}\`. Remove it from the Auth Definition, and pass \`maxAge\` to \`stateless()\` to change the session lifetime.` });
136
+ const session = isPlainObject(options.session) ? options.session : {};
137
+ const cookieCache = isPlainObject(session.cookieCache) ? session.cookieCache : {};
138
+ const account = isPlainObject(options.account) ? options.account : {};
139
+ return {
140
+ ...options,
141
+ ...withStatelessUserId(options),
142
+ account: {
143
+ ...account,
144
+ storeAccountCookie: true,
145
+ storeStateStrategy: "cookie"
146
+ },
147
+ session: {
148
+ ...session,
149
+ cookieCache: {
150
+ ...cookieCache,
151
+ enabled: true,
152
+ maxAge: preset.maxAge,
153
+ refreshCache: true,
154
+ strategy: "jwe"
155
+ },
156
+ expiresIn: preset.maxAge
157
+ }
158
+ };
159
+ }
160
+ /** Validates the `preset` option and returns the options with the preset's Better Auth options applied. */
161
+ function applyAuthPreset(options) {
162
+ if (options.preset === void 0) return options;
163
+ const { preset, ...rest } = options;
164
+ return applyStatelessPreset(readStatelessPreset(preset), rest);
165
+ }
166
+ //#endregion
167
+ //#region src/events-config.ts
168
+ function validateAuthEvents(value) {
169
+ if (value === void 0 || value === false) return;
170
+ if (!value || typeof value !== "object" || !("store" in value) || !value.store || typeof value.store !== "object" || ![
171
+ "append",
172
+ "list",
173
+ "aggregate"
174
+ ].every((key) => typeof Reflect.get(value.store, key) === "function") || "authorize" in value && value.authorize !== void 0 && typeof value.authorize !== "function") throw authErrorDiagnostics.AUTH_C0050({ message: "`defineAuth()` events needs a store with append, list, and aggregate methods. events.authorize must be a function. Set events to false to disable the log." });
175
+ }
176
+ //#endregion
177
+ export { applyAuthPreset as n, validateAuthEvents as t };
@@ -0,0 +1,17 @@
1
+ /// <reference types="node" />
2
+
3
+ import "bun-types/sqlite.d.ts"
4
+
5
+ declare global {
6
+ interface Timer {
7
+ ref(): Timer
8
+ unref(): Timer
9
+ hasRef(): boolean
10
+ refresh(): Timer
11
+ [Symbol.toPrimitive](): number
12
+ }
13
+ }
14
+
15
+ declare module "#app" {
16
+ export function tryUseNuxtApp(): unknown
17
+ }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import { A as ResolvedAuthSecondaryStorageConfiguration, C as AuthRuntimeOptionsResolver, D as AuthViteHubOptions, E as AuthSignInConfiguration, M as ViteHubAuth, O as DiscoveredAuthDefinition, S as AuthRuntimeOptions, T as AuthSecondaryStorageReference, _ as AuthRuntimeConfiguration, a as AuthBetterAuthRuntimeOptions, b as AuthRuntimeOnlyOptions, c as AuthDefinition, d as AuthDefinitionResolver, f as AuthModuleOptions, g as AuthResolvedDefinitionOptions, h as AuthReservedOption, i as AuthBetterAuthOptions, j as ResolvedAuthViteConfig, k as ResolvedAuthDatabaseConfiguration, l as AuthDefinitionInput, n as AuthAccessRoute, o as AuthDatabaseConfiguration, p as AuthRequest, r as AuthAccessRouteConfiguration, s as AuthDatabaseReference, t as AuthAccessConfiguration, u as AuthDefinitionOptions, v as AuthRuntimeContext, w as AuthSecondaryStorageConfiguration, x as AuthRuntimeOption, y as AuthRuntimeEnv } from "./types-B0fg9XFd.js";
2
-
1
+ /// <reference path="./host-declarations.d.ts" />
2
+ import { $ as AuthSessionRefreshContext, A as AuthDefinitionOptions, B as AuthReservedOption, C as AuthAuthorization, D as AuthDatabaseReference, Dt as AuthConsoleOptions, E as AuthDatabaseConfiguration, F as AuthModuleOptions, G as AuthRuntimeOnlyOptions, H as AuthRuntimeConfiguration, I as AuthNodeRequest, J as AuthRuntimeOptionsResolver, K as AuthRuntimeOption, L as AuthNodeRequestEvent, M as AuthFor, Mt as AuthConsolePolicy, N as AuthGuardedHandler, O as AuthDefinition, P as AuthMiddleware, Q as AuthSessionRefresh, R as AuthRequest, S as AuthAccessRouteConfiguration, T as AuthBetterAuthRuntimeOptions, U as AuthRuntimeContext, V as AuthResolvedDefinitionOptions, W as AuthRuntimeEnv, X as AuthSecondaryStorageReference, Y as AuthSecondaryStorageConfiguration, Z as AuthSessionOptions, _ as AuthAccessAuthorizationContext, a as AuthEventCounts, b as AuthAccessConfiguration, c as AuthEventPage, ct as ResolvedAuthViteConfig, d as AuthEventType, et as AuthSessionRefreshFields, f as AuthEventWindow, g as defaultAuthEventRetention, h as createDatabaseAuthEventStore, ht as AuthConsoleColumn, i as AuthEventAggregates, it as RegisteredAuth, j as AuthDefinitionResolver, k as AuthDefinitionInput, l as AuthEventRetention, lt as ViteHubAuth, m as authEventTypes, n as AuthEvent, nt as AuthViteHubOptions, o as AuthEventListInput, ot as ResolvedAuthDatabaseConfiguration, p as AuthEventsConfiguration, q as AuthRuntimeOptions, r as AuthEventActor, rt as DiscoveredAuthDefinition, s as AuthEventMetadata, st as ResolvedAuthSecondaryStorageConfiguration, t as AuthDevice, tt as AuthSignInConfiguration, u as AuthEventStore, v as AuthAccessAuthorize, w as AuthBetterAuthOptions, x as AuthAccessRoute, xt as AuthConsoleFieldPolicy, y as AuthAccessAuthorizeResult } from "./events-BkmK2dFY.js";
3
+ import { i as AuthStatelessPresetOptions, n as AuthPreset, r as AuthStatelessPreset, t as AuthDuration } from "./presets-BGZi6Dfu.js";
3
4
  //#region src/definition.d.ts
4
- declare function defineAuth<const TOptions extends AuthBetterAuthOptions>(options: AuthDefinitionOptions<TOptions>): AuthDefinition<AuthDefinitionOptions<TOptions>>;
5
- declare function defineAuth<const TOptions extends AuthResolvedDefinitionOptions>(options: AuthDefinitionResolver<TOptions>): AuthDefinition<AuthDefinitionResolver<TOptions>>;
5
+ export declare function defineAuth<const TOptions extends AuthResolvedDefinitionOptions>(options: AuthDefinitionResolver<TOptions>): AuthDefinition<AuthDefinitionResolver<TOptions>>;
6
+ export declare function defineAuth<const TOptions extends AuthBetterAuthOptions & Pick<AuthViteHubOptions, "runtime">>(options: AuthDefinitionOptions<TOptions>): AuthDefinition<AuthDefinitionOptions<TOptions>>;
6
7
  //#endregion
7
- export { type AuthAccessConfiguration, type AuthAccessRoute, type AuthAccessRouteConfiguration, type AuthBetterAuthOptions, type AuthBetterAuthRuntimeOptions, type AuthDatabaseConfiguration, type AuthDatabaseReference, type AuthDefinition, type AuthDefinitionInput, type AuthDefinitionOptions, type AuthDefinitionResolver, type AuthModuleOptions, type AuthRequest, type AuthReservedOption, type AuthResolvedDefinitionOptions, type AuthRuntimeConfiguration, type AuthRuntimeContext, type AuthRuntimeEnv, type AuthRuntimeOnlyOptions, type AuthRuntimeOption, type AuthRuntimeOptions, type AuthRuntimeOptionsResolver, type AuthSecondaryStorageConfiguration, type AuthSecondaryStorageReference, type AuthSignInConfiguration, type AuthViteHubOptions, type DiscoveredAuthDefinition, type ResolvedAuthDatabaseConfiguration, type ResolvedAuthSecondaryStorageConfiguration, type ResolvedAuthViteConfig, type ViteHubAuth, defineAuth };
8
+ export { type AuthAccessAuthorizationContext, type AuthAccessAuthorize, type AuthAccessAuthorizeResult, type AuthAccessConfiguration, type AuthAccessRoute, type AuthAccessRouteConfiguration, type AuthAuthorization, type AuthBetterAuthOptions, type AuthBetterAuthRuntimeOptions, type AuthConsoleColumn, type AuthConsoleFieldPolicy, type AuthConsoleOptions, type AuthConsolePolicy, type AuthDatabaseConfiguration, type AuthDatabaseReference, 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 AuthMiddleware, type AuthModuleOptions, type AuthNodeRequest, type AuthNodeRequestEvent, type AuthPreset, type AuthRequest, type AuthReservedOption, type AuthResolvedDefinitionOptions, type AuthRuntimeConfiguration, type AuthRuntimeContext, type AuthRuntimeEnv, type AuthRuntimeOnlyOptions, type AuthRuntimeOption, type AuthRuntimeOptions, type AuthRuntimeOptionsResolver, type AuthSecondaryStorageConfiguration, type AuthSecondaryStorageReference, type AuthSessionOptions, type AuthSessionRefresh, type AuthSessionRefreshContext, type AuthSessionRefreshFields, type AuthSignInConfiguration, type AuthStatelessPreset, type AuthStatelessPresetOptions, type AuthViteHubOptions, type DiscoveredAuthDefinition, type RegisteredAuth, type ResolvedAuthDatabaseConfiguration, type ResolvedAuthSecondaryStorageConfiguration, type ResolvedAuthViteConfig, type ViteHubAuth, authEventTypes, createDatabaseAuthEventStore, defaultAuthEventRetention };
package/dist/index.js CHANGED
@@ -1,67 +1,75 @@
1
- import { n as normalizeAuthBasePath } from "./shared-QSYBHaMG.js";
1
+ import { n as createDatabaseAuthEventStore, r as defaultAuthEventRetention, t as authEventTypes } from "./events-P7mI4IQb.js";
2
+ import { t as authErrorDiagnostics } from "./error-diagnostics-CL0yjHiM.js";
3
+ import { n as normalizeAuthBasePath } from "./shared-DnpgYiLF.js";
4
+ import { n as applyAuthPreset, t as validateAuthEvents } from "./events-config-CjcFOhTE.js";
2
5
  //#region src/definition.ts
3
- const authRuntimeOptionNames = new Set([
6
+ const authRuntimeOptionNames = /* @__PURE__ */ new Set([
4
7
  "baseURL",
5
8
  "secret",
6
9
  "secrets"
7
10
  ]);
8
- const accessRouteKeys = new Set(["method", "route"]);
9
- const databaseReferenceKeys = new Set(["dedicated", "name"]);
10
- const secondaryStorageReferenceKeys = new Set(["store"]);
11
+ const accessRouteKeys = /* @__PURE__ */ new Set([
12
+ "authorize",
13
+ "method",
14
+ "route"
15
+ ]);
16
+ const databaseReferenceKeys = /* @__PURE__ */ new Set(["dedicated", "name"]);
17
+ const secondaryStorageReferenceKeys = /* @__PURE__ */ new Set(["store"]);
11
18
  function isPlainObject(value) {
12
19
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
13
20
  }
14
21
  function validateNamedString(value, label) {
15
- if (typeof value !== "string" || value.trim().length === 0 || value !== value.trim()) throw new TypeError(`\`defineAuth()\` ${label} must be a non-empty trimmed string.`);
22
+ if (typeof value !== "string" || value.trim().length === 0 || value !== value.trim()) throw authErrorDiagnostics.AUTH_C0020({ message: `\`defineAuth()\` ${label} must be a non-empty trimmed string.` });
16
23
  }
17
24
  function validateAuthDatabase(value) {
18
25
  if (typeof value === "undefined" || value === true) return;
19
- if (!isPlainObject(value)) throw new TypeError("`defineAuth()` database must be `true` or an inline object with `name`.");
26
+ if (!isPlainObject(value)) throw authErrorDiagnostics.AUTH_C0021({ message: "`defineAuth()` database must be `true` or an inline object with `name`." });
20
27
  const unknownKey = Object.keys(value).find((key) => !databaseReferenceKeys.has(key));
21
- if (unknownKey) throw new TypeError(`\`defineAuth()\` database does not support the "${unknownKey}" option.`);
22
- validateNamedString(value.name, "database.name");
23
- if (typeof value.dedicated !== "undefined" && typeof value.dedicated !== "boolean") throw new TypeError("`defineAuth()` database.dedicated must be a boolean.");
28
+ if (unknownKey) throw authErrorDiagnostics.AUTH_C0022({ message: `\`defineAuth()\` database does not support the "${unknownKey}" option.` });
29
+ validateNamedString(Object.hasOwn(value, "name") ? value.name : void 0, "database.name");
30
+ if (Object.hasOwn(value, "dedicated") && typeof value.dedicated !== "undefined" && typeof value.dedicated !== "boolean") throw authErrorDiagnostics.AUTH_C0023({ message: "`defineAuth()` database.dedicated must be a boolean." });
24
31
  }
25
32
  function validateAuthSecondaryStorage(value) {
26
33
  if (typeof value === "undefined" || value === true) return;
27
- if (!isPlainObject(value)) throw new TypeError("`defineAuth()` secondaryStorage must be `true` or an inline object with `store`.");
34
+ if (!isPlainObject(value)) throw authErrorDiagnostics.AUTH_C0024({ message: "`defineAuth()` secondaryStorage must be `true` or an inline object with `store`." });
28
35
  const unknownKey = Object.keys(value).find((key) => !secondaryStorageReferenceKeys.has(key));
29
- if (unknownKey) throw new TypeError(`\`defineAuth()\` secondaryStorage does not support the "${unknownKey}" option.`);
30
- validateNamedString(value.store, "secondaryStorage.store");
36
+ if (unknownKey) throw authErrorDiagnostics.AUTH_C0025({ message: `\`defineAuth()\` secondaryStorage does not support the "${unknownKey}" option.` });
37
+ validateNamedString(Object.hasOwn(value, "store") ? value.store : void 0, "secondaryStorage.store");
31
38
  }
32
39
  function validateStringValue(value, label) {
33
- if (typeof value !== "string" || value.trim().length === 0) throw new TypeError(`\`defineAuth()\` ${label} must be a non-empty string.`);
40
+ if (typeof value !== "string" || value.trim().length === 0) throw authErrorDiagnostics.AUTH_C0026({ message: `\`defineAuth()\` ${label} must be a non-empty string.` });
34
41
  }
35
42
  function validateRouteValue(value, label) {
36
43
  validateStringValue(value, label);
37
- if (typeof value === "string" && !value.startsWith("/")) throw new TypeError(`\`defineAuth()\` ${label} must start with \`/\`.`);
44
+ if (typeof value === "string" && !value.startsWith("/")) throw authErrorDiagnostics.AUTH_C0027({ message: `\`defineAuth()\` ${label} must start with \`/\`.` });
38
45
  }
39
46
  function validateAuthSignIn(value) {
40
47
  if (typeof value === "undefined") return;
41
- if (!isPlainObject(value)) throw new TypeError("`defineAuth()` access.signIn must be an object.");
48
+ if (!isPlainObject(value)) throw authErrorDiagnostics.AUTH_C0028({ message: "`defineAuth()` access.signIn must be an object." });
42
49
  validateStringValue(value.provider, "access.signIn.provider");
43
50
  if (typeof value.callbackURL !== "undefined") validateStringValue(value.callbackURL, "access.signIn.callbackURL");
44
51
  if (typeof value.errorCallbackURL !== "undefined") validateStringValue(value.errorCallbackURL, "access.signIn.errorCallbackURL");
45
- if (typeof value.requestSignUp !== "undefined" && typeof value.requestSignUp !== "boolean") throw new TypeError("`defineAuth()` access.signIn.requestSignUp must be a boolean.");
46
- if (typeof value.scopes !== "undefined" && (!Array.isArray(value.scopes) || value.scopes.some((scope) => typeof scope !== "string"))) throw new TypeError("`defineAuth()` access.signIn.scopes must be an array of strings.");
52
+ if (typeof value.requestSignUp !== "undefined" && typeof value.requestSignUp !== "boolean") throw authErrorDiagnostics.AUTH_C0029({ message: "`defineAuth()` access.signIn.requestSignUp must be a boolean." });
53
+ 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." });
47
54
  }
48
55
  function validateAuthAccessRoute(value, label) {
49
56
  if (typeof value === "string") {
50
57
  validateRouteValue(value, label);
51
58
  return;
52
59
  }
53
- if (!isPlainObject(value)) throw new TypeError(`\`defineAuth()\` ${label} must be a route string or route object.`);
60
+ if (!isPlainObject(value)) throw authErrorDiagnostics.AUTH_C0031({ message: `\`defineAuth()\` ${label} must be a route string or route object.` });
54
61
  const unknownKey = Object.keys(value).find((key) => !accessRouteKeys.has(key));
55
- if (unknownKey) throw new TypeError(`\`defineAuth()\` ${label} does not support the "${unknownKey}" option.`);
62
+ if (unknownKey) throw authErrorDiagnostics.AUTH_C0032({ message: `\`defineAuth()\` ${label} does not support the "${unknownKey}" option.` });
56
63
  validateRouteValue(value.route, `${label}.route`);
64
+ if (typeof value.authorize !== "undefined" && typeof value.authorize !== "function") throw authErrorDiagnostics.AUTH_C0033({ message: `\`defineAuth()\` ${label}.authorize must be a function.` });
57
65
  if (typeof value.method !== "undefined") validateStringValue(value.method, `${label}.method`);
58
66
  }
59
67
  function validateAuthAccess(value) {
60
68
  if (typeof value === "undefined") return;
61
- if (!isPlainObject(value)) throw new TypeError("`defineAuth()` access must be an object.");
69
+ if (!isPlainObject(value)) throw authErrorDiagnostics.AUTH_C0034({ message: "`defineAuth()` access must be an object." });
62
70
  const access = value;
63
71
  if (typeof access.routes !== "undefined") {
64
- if (!Array.isArray(access.routes)) throw new TypeError("`defineAuth()` access.routes must be an array.");
72
+ if (!Array.isArray(access.routes)) throw authErrorDiagnostics.AUTH_C0035({ message: "`defineAuth()` access.routes must be an array." });
65
73
  access.routes.forEach((route, index) => validateAuthAccessRoute(route, `access.routes[${index}]`));
66
74
  }
67
75
  validateAuthSignIn(access.signIn);
@@ -71,20 +79,24 @@ function defineAuth(options) {
71
79
  }
72
80
  function defineAuthOptions(options) {
73
81
  if (typeof options === "function") return { options };
74
- if (!isPlainObject(options)) throw new TypeError("`defineAuth()` expects an object or a callback.");
82
+ if (!isPlainObject(options)) throw authErrorDiagnostics.AUTH_C0036({ message: "`defineAuth()` expects an object or a callback." });
75
83
  const viteHubOptions = options;
76
84
  const runtimeOption = Object.keys(options).find((key) => authRuntimeOptionNames.has(key));
77
- if (runtimeOption) throw new TypeError(`\`defineAuth()\` ${runtimeOption} is resolved at runtime and cannot be defined in the Auth Definition.`);
78
- if (typeof viteHubOptions.route !== "undefined" && viteHubOptions.route !== false) throw new TypeError("`defineAuth()` route can only be `false` when provided.");
79
- if (typeof viteHubOptions.runtime !== "undefined" && typeof viteHubOptions.runtime !== "function" && !isPlainObject(viteHubOptions.runtime)) throw new TypeError("`defineAuth()` runtime must be an object or a function.");
85
+ if (runtimeOption) throw authErrorDiagnostics.AUTH_C0037({ message: `\`defineAuth()\` ${runtimeOption} is resolved at runtime and cannot be defined in the Auth Definition.` });
86
+ if (typeof viteHubOptions.route !== "undefined" && viteHubOptions.route !== false) throw authErrorDiagnostics.AUTH_C0038({ message: "`defineAuth()` route can only be `false` when provided." });
87
+ if (typeof viteHubOptions.runtime !== "undefined" && typeof viteHubOptions.runtime !== "function" && !isPlainObject(viteHubOptions.runtime)) throw authErrorDiagnostics.AUTH_C0039({ message: "`defineAuth()` runtime must be an object or a function." });
80
88
  if (typeof viteHubOptions.basePath !== "undefined") {
81
- if (typeof viteHubOptions.basePath !== "string") throw new TypeError("`defineAuth()` basePath must be a string.");
89
+ if (typeof viteHubOptions.basePath !== "string") throw authErrorDiagnostics.AUTH_C0040({ message: "`defineAuth()` basePath must be a string." });
82
90
  normalizeAuthBasePath(viteHubOptions.basePath);
83
91
  }
92
+ const session = options.session;
93
+ if (isPlainObject(session) && typeof session.onRefresh !== "undefined" && typeof session.onRefresh !== "function") throw authErrorDiagnostics.AUTH_C0041({ message: "`defineAuth()` session.onRefresh must be a function." });
94
+ validateAuthEvents(options.events);
84
95
  validateAuthDatabase(viteHubOptions.database);
85
96
  validateAuthSecondaryStorage(viteHubOptions.secondaryStorage);
86
97
  validateAuthAccess(viteHubOptions.access);
98
+ applyAuthPreset(options);
87
99
  return { options };
88
100
  }
89
101
  //#endregion
90
- export { defineAuth };
102
+ export { authEventTypes, createDatabaseAuthEventStore, defaultAuthEventRetention, defineAuth };
@@ -0,0 +1,36 @@
1
+ //#region ../internal/src/inspect.d.ts
2
+ interface ViteHubDefinitionField {
3
+ label: string;
4
+ value: string;
5
+ }
6
+ /** Serializable summary of one discovered Definition. Files are relative to the project root. */
7
+ interface ViteHubDefinitionSummary {
8
+ fields: readonly ViteHubDefinitionField[];
9
+ file: string;
10
+ name: string;
11
+ source: string;
12
+ }
13
+ /** Lists the Definitions that one owner package discovered for the resolved Vite config. */
14
+ interface ViteHubDefinitionInspector {
15
+ /** Stable singular kind, for example `queue` or `rate-limit`. */
16
+ kind: string;
17
+ label: string;
18
+ list: () => Promise<readonly ViteHubDefinitionSummary[]> | readonly ViteHubDefinitionSummary[];
19
+ }
20
+ /** One generated Provider Output file or directory that an owner package can write. */
21
+ interface ViteHubProviderOutputEntry {
22
+ description: string;
23
+ owner: string;
24
+ /** Absolute path. */
25
+ path: string;
26
+ }
27
+ interface ViteHubInspectionContributor {
28
+ definitions?: readonly ViteHubDefinitionInspector[];
29
+ providerOutput?: readonly ViteHubProviderOutputEntry[];
30
+ }
31
+ type ViteHubInspectionContributorFactory = () => ViteHubInspectionContributor | undefined | Promise<ViteHubInspectionContributor | undefined>;
32
+ interface ViteHubInspectionPluginMetadata {
33
+ inspect?: ViteHubInspectionContributor | ViteHubInspectionContributorFactory;
34
+ }
35
+ //#endregion
36
+ export { ViteHubDefinitionSummary as n, ViteHubInspectionPluginMetadata as r, ViteHubDefinitionField as t };
package/dist/nuxt.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ /// <reference path="./host-declarations.d.ts" />
2
+ import { F as AuthModuleOptions } from "./events-BkmK2dFY.js";
3
+ //#region ../internal/src/build/vite.d.ts
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
+ }
16
+ //#endregion
17
+ //#region src/nuxt.d.ts
18
+ export interface AuthNuxtModuleOptions {
19
+ auth?: AuthModuleOptions;
20
+ env?: false | {
21
+ projectRoot?: string;
22
+ };
23
+ importsFrom?: string;
24
+ nitro?: boolean;
25
+ }
26
+ type NuxtLike = {
27
+ hook?: (name: "nitro:config", handler: (nitroConfig: Record<string, unknown>) => Promise<void>) => void;
28
+ options: {
29
+ plugins?: Array<string | {
30
+ src: string;
31
+ order?: number;
32
+ }>;
33
+ _layers?: NuxtServerDirOptions["_layers"];
34
+ alias?: Record<string, string>;
35
+ app?: {
36
+ baseURL?: string;
37
+ };
38
+ imports?: {
39
+ imports?: Array<{
40
+ from: string;
41
+ name: string;
42
+ }>;
43
+ };
44
+ nitro?: {
45
+ alias?: Record<string, string>;
46
+ plugins?: string[];
47
+ };
48
+ rootDir?: string;
49
+ serverDir?: string;
50
+ vite?: {
51
+ auth?: AuthModuleOptions;
52
+ define?: Record<string, unknown>;
53
+ plugins?: unknown[];
54
+ root?: string;
55
+ };
56
+ };
57
+ };
58
+ export default function hubAuthNuxt(options?: AuthNuxtModuleOptions, nuxt?: NuxtLike): void;
59
+ //#endregion