@lunora/auth 1.0.0-alpha.3 → 1.0.0-alpha.30

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.
@@ -1,249 +0,0 @@
1
- class LunoraAuthAdminError extends Error {
2
- code;
3
- constructor(message, code) {
4
- super(message);
5
- this.name = "LunoraAuthAdminError";
6
- this.code = code;
7
- }
8
- }
9
- const DEFAULT_LIMIT = 50;
10
- const MAX_LIMIT = 500;
11
- const DEFAULT_IMPERSONATION_SECONDS = 3600;
12
- const MAX_IMPERSONATION_SECONDS = DEFAULT_IMPERSONATION_SECONDS * 24;
13
- const MAX_BAN_SECONDS = 100 * 365 * 24 * 60 * 60;
14
- const SENSITIVE_FIELDS = /* @__PURE__ */ new Set(["accessToken", "backupCodes", "idToken", "password", "publicKey", "refreshToken", "secret", "token"]);
15
- const clampLimit = (limit) => Math.min(Math.max(Math.trunc(limit ?? DEFAULT_LIMIT), 1), MAX_LIMIT);
16
- const clampOffset = (offset) => Math.max(0, Math.trunc(offset ?? 0));
17
- const normalizeRow = (row) => {
18
- const out = {};
19
- for (const [key, value] of Object.entries(row)) {
20
- if (SENSITIVE_FIELDS.has(key)) {
21
- continue;
22
- }
23
- out[key] = value instanceof Date ? value.getTime() : value;
24
- }
25
- return out;
26
- };
27
- const serializeRole = (role) => Array.isArray(role) ? role.join(",") : role;
28
- const asAdminError = (error) => {
29
- if (error instanceof LunoraAuthAdminError) {
30
- return error;
31
- }
32
- const candidate = error;
33
- const code = candidate?.body?.code ?? candidate?.code ?? "AUTH_ADMIN_ERROR";
34
- const message = candidate?.body?.message ?? candidate?.message ?? "auth admin operation failed";
35
- return new LunoraAuthAdminError(message, code);
36
- };
37
- const createAuthAdmin = (auth, options = {}) => {
38
- const context = auth.$context;
39
- const features = options.features ?? {};
40
- const withContext = async (function_) => {
41
- try {
42
- return await function_(await context);
43
- } catch (error) {
44
- throw asAdminError(error);
45
- }
46
- };
47
- const toUser = (row) => normalizeRow(row);
48
- const page = async (context_, model, options_) => {
49
- const where = options_.where && options_.where.length > 0 ? options_.where : void 0;
50
- const [rows, total] = await Promise.all([
51
- context_.adapter.findMany({
52
- limit: clampLimit(options_.limit),
53
- model,
54
- offset: clampOffset(options_.offset),
55
- sortBy: options_.sortBy,
56
- where
57
- }),
58
- context_.adapter.count({ model, where })
59
- ]);
60
- return { rows: rows.map((row) => normalizeRow(row)), total };
61
- };
62
- return {
63
- banUser: ({ expiresInSeconds, reason, userId }) => withContext(async (context_) => {
64
- const seconds = typeof expiresInSeconds === "number" && Number.isFinite(expiresInSeconds) ? Math.min(Math.trunc(expiresInSeconds), MAX_BAN_SECONDS) : 0;
65
- const banExpires = seconds > 0 ? new Date(Date.now() + seconds * 1e3) : void 0;
66
- const user = await context_.internalAdapter.updateUser(userId, {
67
- banExpires,
68
- banned: true,
69
- banReason: reason ?? "No reason"
70
- });
71
- await context_.internalAdapter.deleteUserSessions(userId);
72
- return toUser(user);
73
- }),
74
- cancelInvitation: ({ invitationId }) => withContext(async (context_) => {
75
- await context_.adapter.delete({ model: "invitation", where: [{ field: "id", value: invitationId }] });
76
- }),
77
- capabilities: () => withContext((context_) => {
78
- const ids = new Set((context_.options.plugins ?? []).map((plugin) => plugin.id));
79
- const has = (id) => ids.has(id);
80
- return Promise.resolve({
81
- accounts: features.accounts ?? true,
82
- admin: features.admin ?? has("admin"),
83
- organization: features.organization ?? has("organization"),
84
- passkey: features.passkey ?? has("passkey"),
85
- twoFactor: features.twoFactor ?? has("two-factor")
86
- });
87
- }),
88
- // The one op that genuinely builds a row rather than mutating one. Replicates
89
- // the plugin's create-user handler over `internalAdapter` (lowercase + dedupe
90
- // email, create the row, then link a credential account when a password is given).
91
- createUser: ({ data, email, name, password, role }) => withContext(async (context_) => {
92
- const normalizedEmail = email.toLowerCase();
93
- if (await context_.internalAdapter.findUserByEmail(normalizedEmail)) {
94
- throw new LunoraAuthAdminError("a user with this email already exists", "USER_ALREADY_EXISTS");
95
- }
96
- const user = await context_.internalAdapter.createUser({
97
- email: normalizedEmail,
98
- name,
99
- role: role === void 0 ? void 0 : serializeRole(role),
100
- ...data
101
- });
102
- if (password !== void 0 && password !== "") {
103
- const hashed = await context_.password.hash(password);
104
- await context_.internalAdapter.linkAccount({
105
- accountId: user.id,
106
- password: hashed,
107
- providerId: "credential",
108
- userId: user.id
109
- });
110
- }
111
- return toUser(user);
112
- }),
113
- deletePasskey: ({ passkeyId }) => withContext(async (context_) => {
114
- await context_.adapter.delete({ model: "passkey", where: [{ field: "id", value: passkeyId }] });
115
- }),
116
- disableTwoFactor: ({ userId }) => withContext(async (context_) => {
117
- await context_.adapter.deleteMany({ model: "twoFactor", where: [{ field: "userId", value: userId }] });
118
- await context_.internalAdapter.updateUser(userId, { twoFactorEnabled: false });
119
- }),
120
- impersonateUser: ({ userId }) => withContext(async (context_) => {
121
- const user = await context_.internalAdapter.findUserById(userId);
122
- if (!user) {
123
- throw new LunoraAuthAdminError("user not found", "USER_NOT_FOUND");
124
- }
125
- const rawSeconds = options.impersonationSeconds;
126
- let ttlSeconds = DEFAULT_IMPERSONATION_SECONDS;
127
- if (rawSeconds !== void 0) {
128
- if (!Number.isInteger(rawSeconds) || !Number.isFinite(rawSeconds) || rawSeconds <= 0) {
129
- throw new LunoraAuthAdminError("impersonationSeconds must be a positive finite integer", "INVALID_IMPERSONATION_SECONDS");
130
- }
131
- ttlSeconds = Math.min(rawSeconds, MAX_IMPERSONATION_SECONDS);
132
- }
133
- const expiresAt = new Date(Date.now() + ttlSeconds * 1e3);
134
- const session = await context_.internalAdapter.createSession(
135
- userId,
136
- true,
137
- { expiresAt, impersonatedBy: options.impersonatedBy ?? userId },
138
- true
139
- );
140
- return {
141
- expiresAt: session.expiresAt instanceof Date ? session.expiresAt.getTime() : expiresAt.getTime(),
142
- token: session.token,
143
- user: toUser(user)
144
- };
145
- }),
146
- listAccounts: ({ userId }) => withContext(async (context_) => {
147
- const rows = await context_.adapter.findMany({ model: "account", where: [{ field: "userId", value: userId }] });
148
- return rows.map((row) => normalizeRow(row));
149
- }),
150
- listInvitations: ({ limit, offset, organizationId }) => withContext(
151
- (context_) => page(context_, "invitation", {
152
- limit,
153
- offset,
154
- where: [{ field: "organizationId", value: organizationId }]
155
- })
156
- ),
157
- listMembers: ({ limit, offset, organizationId }) => withContext(
158
- (context_) => page(context_, "member", {
159
- limit,
160
- offset,
161
- sortBy: { direction: "desc", field: "createdAt" },
162
- where: [{ field: "organizationId", value: organizationId }]
163
- })
164
- ),
165
- listOrganizations: ({ limit, offset }) => withContext((context_) => page(context_, "organization", { limit, offset, sortBy: { direction: "desc", field: "createdAt" } })),
166
- listPasskeys: ({ userId }) => withContext(async (context_) => {
167
- const rows = await context_.adapter.findMany({ model: "passkey", where: [{ field: "userId", value: userId }] });
168
- return rows.map((row) => normalizeRow(row));
169
- }),
170
- listSessions: ({ limit, offset, userId }) => withContext(
171
- (context_) => page(context_, "session", {
172
- limit,
173
- offset,
174
- sortBy: { direction: "desc", field: "createdAt" },
175
- where: userId === void 0 || userId === "" ? void 0 : [{ field: "userId", value: userId }]
176
- })
177
- ),
178
- listUsers: ({ filterField, filterValue, limit, offset, search, searchField, sortBy, sortDirection }) => withContext((context_) => {
179
- const where = [];
180
- if (search !== void 0 && search !== "") {
181
- where.push({ field: searchField ?? "email", operator: "contains", value: search });
182
- }
183
- if (filterValue !== void 0) {
184
- where.push({ field: filterField ?? "email", operator: "eq", value: filterValue });
185
- }
186
- return page(context_, "user", {
187
- limit,
188
- offset,
189
- sortBy: { direction: sortDirection ?? "desc", field: sortBy ?? "createdAt" },
190
- where
191
- });
192
- }),
193
- removeMember: ({ memberId }) => withContext(async (context_) => {
194
- await context_.adapter.delete({ model: "member", where: [{ field: "id", value: memberId }] });
195
- }),
196
- removeUser: ({ userId }) => withContext(async (context_) => {
197
- await context_.internalAdapter.deleteUserSessions(userId);
198
- await context_.internalAdapter.deleteUser(userId);
199
- }),
200
- // Keyed on the session *id*, not its token: tokens are bearer credentials we
201
- // deliberately never surface to the studio. Resolve the row to recover its
202
- // token, then delete via `internalAdapter.deleteSession` — which also clears
203
- // secondary (KV) storage, unlike a raw `adapter.delete` on the DB row.
204
- revokeUserSession: ({ sessionId }) => withContext(async (context_) => {
205
- const session = await context_.adapter.findOne({ model: "session", where: [{ field: "id", value: sessionId }] });
206
- if (session?.token) {
207
- await context_.internalAdapter.deleteSession(session.token);
208
- }
209
- }),
210
- revokeUserSessions: ({ userId }) => withContext(async (context_) => {
211
- await context_.internalAdapter.deleteUserSessions(userId);
212
- }),
213
- setRole: ({ role, userId }) => withContext(async (context_) => {
214
- const user = await context_.internalAdapter.updateUser(userId, { role: serializeRole(role) });
215
- return toUser(user);
216
- }),
217
- setUserPassword: ({ newPassword, userId }) => withContext(async (context_) => {
218
- const min = context_.password.config.minPasswordLength;
219
- const max = context_.password.config.maxPasswordLength;
220
- if (newPassword.length < min) {
221
- throw new LunoraAuthAdminError(`password must be at least ${min.toString()} characters`, "PASSWORD_TOO_SHORT");
222
- }
223
- if (newPassword.length > max) {
224
- throw new LunoraAuthAdminError(`password must be at most ${max.toString()} characters`, "PASSWORD_TOO_LONG");
225
- }
226
- const hashed = await context_.password.hash(newPassword);
227
- await context_.internalAdapter.updatePassword(userId, hashed);
228
- }),
229
- unbanUser: ({ userId }) => withContext(async (context_) => {
230
- const user = await context_.internalAdapter.updateUser(userId, { banExpires: null, banned: false, banReason: null });
231
- return toUser(user);
232
- }),
233
- unlinkAccount: ({ accountId, userId }) => withContext(async (context_) => {
234
- await context_.adapter.delete({
235
- model: "account",
236
- where: [
237
- { field: "id", value: accountId },
238
- { connector: "AND", field: "userId", value: userId }
239
- ]
240
- });
241
- }),
242
- updateUser: ({ data, userId }) => withContext(async (context_) => {
243
- const user = await context_.internalAdapter.updateUser(userId, data);
244
- return toUser(user);
245
- })
246
- };
247
- };
248
-
249
- export { LunoraAuthAdminError, createAuthAdmin };
@@ -1,58 +0,0 @@
1
- import { betterAuth, BetterAuthOptions } from 'better-auth';
2
- /**
3
- * Lunora's options pass straight through to better-auth — the only thing we add
4
- * is requiring `secret` up front so a misconfigured deployment fails loudly
5
- * instead of at the first sign-in.
6
- *
7
- * For `database`, prefer `lunoraD1Adapter` (`database: lunoraD1Adapter(env.DB)`)
8
- * over passing the raw `env.DB`. better-auth *does* accept a D1Database directly,
9
- * but it then resolves its Kysely adapter via a runtime `await import(...)` inside
10
- * `auth.$context` — and that import never settles under `@cloudflare/vite-plugin`'s
11
- * worker runner, hanging every auth request in `pnpm dev`. The explicit adapter
12
- * skips it, so dev and prod behave the same. (Raw `env.DB` is still correct for
13
- * the migration-only instance — see `lunoraD1Adapter`'s note.)
14
- *
15
- * Session rotation / richer session policies are configured via the `session`
16
- * field (a `SessionPolicy`); Lunora validates it for obviously-broken
17
- * durations and forwards it verbatim to better-auth. See `sessionPresets`
18
- * for ready-made rotation/expiry trade-offs.
19
- *
20
- * ## Serverless background tasks (Cloudflare Workers)
21
- *
22
- * better-auth runs some work *after* sending the response — most importantly the
23
- * password-reset email, whose background send is what keeps reset responses
24
- * constant-time (a timing-attack defence: the response doesn't reveal whether
25
- * the account exists). On Cloudflare Workers a promise that isn't handed to
26
- * `ctx.waitUntil` can be cancelled the moment the response returns, dropping
27
- * that send and weakening the guarantee. Wire your request's `ctx.waitUntil`
28
- * into better-auth's background handler so the work survives:
29
- *
30
- * ```ts
31
- * // in your worker fetch handler, where `ctx: ExecutionContext` is in scope
32
- * const auth = createAuth({
33
- * secret: env.AUTH_SECRET,
34
- * database: lunoraD1Adapter(env.DB),
35
- * advanced: {
36
- * backgroundTasks: { handler: (promise) => ctx.waitUntil(promise) },
37
- * },
38
- * });
39
- * ```
40
- *
41
- * (Lunora can't set this for you — `ctx.waitUntil` is per-request, but
42
- * `createAuth` runs once at worker setup.)
43
- */
44
- type LunoraAuthOptions = BetterAuthOptions;
45
- /**
46
- * The full better-auth instance: `auth.handler` accepts a `Request` and
47
- * returns a `Response` (used by `handleAuthRequest`); `auth.api`
48
- * exposes the typed endpoint surface for server-side calls (e.g.
49
- * `auth.api.getSession({ headers })` inside a query/mutation).
50
- */
51
- type LunoraAuth = ReturnType<typeof betterAuth>;
52
- /**
53
- * Create the auth instance. Thin wrapper around `betterAuth` that enforces
54
- * the `secret` requirement at construction time so misconfigured deployments
55
- * fail loudly at the first fetch rather than the first sign-in attempt.
56
- */
57
- declare const createAuth: (options: LunoraAuthOptions) => LunoraAuth;
58
- export { LunoraAuth as L, LunoraAuthOptions as a, createAuth as c };
@@ -1,58 +0,0 @@
1
- import { betterAuth, BetterAuthOptions } from 'better-auth';
2
- /**
3
- * Lunora's options pass straight through to better-auth — the only thing we add
4
- * is requiring `secret` up front so a misconfigured deployment fails loudly
5
- * instead of at the first sign-in.
6
- *
7
- * For `database`, prefer `lunoraD1Adapter` (`database: lunoraD1Adapter(env.DB)`)
8
- * over passing the raw `env.DB`. better-auth *does* accept a D1Database directly,
9
- * but it then resolves its Kysely adapter via a runtime `await import(...)` inside
10
- * `auth.$context` — and that import never settles under `@cloudflare/vite-plugin`'s
11
- * worker runner, hanging every auth request in `pnpm dev`. The explicit adapter
12
- * skips it, so dev and prod behave the same. (Raw `env.DB` is still correct for
13
- * the migration-only instance — see `lunoraD1Adapter`'s note.)
14
- *
15
- * Session rotation / richer session policies are configured via the `session`
16
- * field (a `SessionPolicy`); Lunora validates it for obviously-broken
17
- * durations and forwards it verbatim to better-auth. See `sessionPresets`
18
- * for ready-made rotation/expiry trade-offs.
19
- *
20
- * ## Serverless background tasks (Cloudflare Workers)
21
- *
22
- * better-auth runs some work *after* sending the response — most importantly the
23
- * password-reset email, whose background send is what keeps reset responses
24
- * constant-time (a timing-attack defence: the response doesn't reveal whether
25
- * the account exists). On Cloudflare Workers a promise that isn't handed to
26
- * `ctx.waitUntil` can be cancelled the moment the response returns, dropping
27
- * that send and weakening the guarantee. Wire your request's `ctx.waitUntil`
28
- * into better-auth's background handler so the work survives:
29
- *
30
- * ```ts
31
- * // in your worker fetch handler, where `ctx: ExecutionContext` is in scope
32
- * const auth = createAuth({
33
- * secret: env.AUTH_SECRET,
34
- * database: lunoraD1Adapter(env.DB),
35
- * advanced: {
36
- * backgroundTasks: { handler: (promise) => ctx.waitUntil(promise) },
37
- * },
38
- * });
39
- * ```
40
- *
41
- * (Lunora can't set this for you — `ctx.waitUntil` is per-request, but
42
- * `createAuth` runs once at worker setup.)
43
- */
44
- type LunoraAuthOptions = BetterAuthOptions;
45
- /**
46
- * The full better-auth instance: `auth.handler` accepts a `Request` and
47
- * returns a `Response` (used by `handleAuthRequest`); `auth.api`
48
- * exposes the typed endpoint surface for server-side calls (e.g.
49
- * `auth.api.getSession({ headers })` inside a query/mutation).
50
- */
51
- type LunoraAuth = ReturnType<typeof betterAuth>;
52
- /**
53
- * Create the auth instance. Thin wrapper around `betterAuth` that enforces
54
- * the `secret` requirement at construction time so misconfigured deployments
55
- * fail loudly at the first fetch rather than the first sign-in attempt.
56
- */
57
- declare const createAuth: (options: LunoraAuthOptions) => LunoraAuth;
58
- export { LunoraAuth as L, LunoraAuthOptions as a, createAuth as c };