@aphexcms/auth 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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance.d.ts","sourceRoot":"","sources":["../src/instance.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAkBlD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BA4HC,CAAC;;;;;;;;;;;;;;gCAclD,CAAC;uCAAiD,CAAA;;;;;+DAKpD,CAAC;;;;gDAGP,CAAC;;;;;;;;;;;yCAKiB,CAAC;yCACnB,CAAF;;;;;;;;;qCAQW,CAAC;;;;;;;;;;;yCAIqC,CAAC;yCAC5B,CAAC;;;;;;;;;qCAOoB,CAAC;;;;;;;;;;;yCAMpB,CAAA;yCAEY,CAAC;;;;;;;;;qCAK+D,CAAC;;;;;;;;;;;;;;iFAoBhG,CAAF;;;;;;;;;;;;;;gCAkBS,CAAC;;;;;;;;;;;;;;;;;;;uCA0BU,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;yBAuH8zH,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qCAA2wC,CAAC;qCAAkD,CAAC;;;;;;;;;iCAA8Q,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAC,OAAO,kBAAkB,CAAC,CAAC"}
@@ -0,0 +1,348 @@
1
+ import { betterAuth } from 'better-auth';
2
+ import { apiKey } from '@better-auth/api-key';
3
+ import { twoFactor as twoFactorPlugin } from 'better-auth/plugins';
4
+ import { drizzleAdapter } from 'better-auth/adapters/drizzle';
5
+ import { APIError, createAuthMiddleware } from 'better-auth/api';
6
+ import { cmsLogger, emitUserDeleted } from '@aphexcms/cms-core';
7
+ import { assertAccountDeletable, assertSignUpAllowed, AccountDeletionBlockedError, createUserProfileWithBootstrap, detachUserFromOrganizations, SignUpBlockedError } from '@aphexcms/cms-core/server';
8
+ import { resolveBootstrapPolicy } from './bootstrap-policy.js';
9
+ import { defaultTwoFactorOtpEmail } from './email/two-factor-otp.js';
10
+ /** Per-address cooldown between verification emails, in seconds. */
11
+ const VERIFICATION_EMAIL_COOLDOWN = 60;
12
+ function buildCacheStorage(cache) {
13
+ return {
14
+ storage: 'secondary-storage',
15
+ fallbackToDatabase: true,
16
+ customStorage: {
17
+ get: async (key) => cache.get(key),
18
+ set: async (key, value, ttl) => cache.set(key, value, ttl),
19
+ delete: async (key) => cache.delete(key)
20
+ }
21
+ };
22
+ }
23
+ /**
24
+ * Builds the better-auth instance from an app's adapters.
25
+ *
26
+ * Everything the studio used to configure by hand lives here — session cookie
27
+ * cache, API-key plugin, rate limits, the CMS user-profile sync, and the
28
+ * password-reset / verification email flows.
29
+ */
30
+ export function createAuthInstance(config) {
31
+ const { database: db, drizzleDb, dialect, building = false, emailAdapter, email: emailConfig, cache, socialProviders, twoFactor, appName, betterAuth: extend } = config;
32
+ const { requireEmailVerification = false, inviteOnly = true, allowAccountDeletion = false, twoFactorMethods = ['totp', 'email'] } = config.options ?? {};
33
+ // betterAuth() throws without these, and SvelteKit's analyse pass imports every
34
+ // server module without ever serving a request. Placeholders keep the build
35
+ // green; at runtime `building` is false and a missing secret fails loudly.
36
+ const secret = config.secret || (building ? 'build-placeholder-secret' : undefined);
37
+ const baseURL = config.baseURL || (building ? 'http://localhost:3000' : undefined);
38
+ const trustedOrigins = config.trustedOrigins?.length
39
+ ? config.trustedOrigins
40
+ : baseURL
41
+ ? [baseURL]
42
+ : [];
43
+ /** Sends one auth email, tolerating an unconfigured adapter. */
44
+ async function sendAuthEmail(template, to, userName,
45
+ // A link for the first two templates, a six-digit code for `twoFactorOtp`.
46
+ url) {
47
+ if (!emailAdapter || !emailConfig) {
48
+ cmsLogger.warn('[Auth]', `Email adapter not configured. ${template} email not sent.`);
49
+ return;
50
+ }
51
+ // Only the OTP template has a built-in fallback — the other two carry links
52
+ // into app-specific routes, so there is nothing generic to send for them.
53
+ const resolved = emailConfig[template] ?? (template === 'twoFactorOtp' ? defaultTwoFactorOtpEmail : undefined);
54
+ if (!resolved) {
55
+ cmsLogger.warn('[Auth]', `No ${template} email template configured. Email not sent.`);
56
+ return;
57
+ }
58
+ try {
59
+ const { subject, render } = resolved;
60
+ const { html, text } = await render(userName, url);
61
+ const result = await emailAdapter.send({ from: emailConfig.from, to, subject, html, text });
62
+ if (result.error) {
63
+ cmsLogger.error('[Auth]', `Failed to send ${template} email:`, result.error);
64
+ }
65
+ else {
66
+ cmsLogger.info('[Auth]', `${template} email sent`);
67
+ }
68
+ }
69
+ catch (error) {
70
+ cmsLogger.error('[Auth]', `Error sending ${template} email:`, error);
71
+ }
72
+ }
73
+ const bootstrapPolicy = resolveBootstrapPolicy(config.bootstrap);
74
+ // Keeps the CMS's own user tables in step with better-auth's.
75
+ const userSyncHooks = createAuthMiddleware(async (ctx) => {
76
+ if (ctx.path === '/sign-up/email' && ctx.context.user) {
77
+ try {
78
+ // Routed through the shared helper rather than writing the row here.
79
+ // This used to insert a hard-coded `role: 'editor'`, which quietly
80
+ // disabled the entire bootstrap policy: `AuthService.getSession` only
81
+ // runs `createUserProfileWithBootstrap` when no profile exists, so a row
82
+ // written at sign-up meant `openFirstUser`, `claimCode` and
83
+ // `allowlistEmail` never got to promote anyone — a fresh instance ended
84
+ // up with no administrator at all.
85
+ //
86
+ // Creating it *here* rather than leaving it to that lazy sync also keeps
87
+ // the profile row — which is what `isInstanceEmpty` counts — in place
88
+ // from the moment the account exists. Deferring it would leave the
89
+ // instance reading as empty until the new user's first page load, and
90
+ // `assertSignUpAllowed` treats an empty instance as the one case where
91
+ // invite-only doesn't apply.
92
+ await createUserProfileWithBootstrap({
93
+ db,
94
+ user: {
95
+ id: ctx.context.user.id,
96
+ email: ctx.context.user.email,
97
+ emailVerified: ctx.context.user.emailVerified === true
98
+ },
99
+ request: ctx.request,
100
+ bootstrap: bootstrapPolicy
101
+ });
102
+ }
103
+ catch (error) {
104
+ cmsLogger.error('[Auth]', 'Error creating user profile:', error);
105
+ }
106
+ }
107
+ // better-auth mounts this as `/delete-user`, not `/user/delete-user`.
108
+ if (ctx.path === '/delete-user' && ctx.context.user) {
109
+ const deleted = ctx.context.user;
110
+ try {
111
+ // Memberships are read first: deleting the profile is what removes them, and
112
+ // after that there's nothing left to say which organizations this account
113
+ // left data in.
114
+ const memberships = await db.findUserOrganizations(deleted.id);
115
+ const organizationIds = memberships.map((m) => m.organization.id);
116
+ // One transaction, so the erasure events can't go missing for an account
117
+ // that is already gone. That's the whole point of the outbox here: after
118
+ // this commits, the only remaining pointer to the user's avatar is the
119
+ // event, and a consumer will act on it even if this process dies now.
120
+ await db.withTransaction(async (tx) => {
121
+ await emitUserDeleted(tx, organizationIds, {
122
+ id: deleted.id,
123
+ email: deleted.email,
124
+ image: deleted.image
125
+ });
126
+ // Memberships don't cascade — `cms_organization_members.user_id` points
127
+ // at the auth layer's user, which cms-core doesn't own — so without this
128
+ // a deleted account keeps showing up in member lists holding its old role.
129
+ await detachUserFromOrganizations(tx, deleted.id, organizationIds);
130
+ await tx.deleteUserProfile(deleted.id);
131
+ });
132
+ cmsLogger.info('[Auth]', `Deleted user profile and queued erasure for ${deleted.id}`);
133
+ }
134
+ catch (error) {
135
+ cmsLogger.error('[Auth]', 'Error deleting user profile:', error);
136
+ }
137
+ }
138
+ });
139
+ /**
140
+ * Closes better-auth's own API-key endpoints to the network.
141
+ *
142
+ * The api-key plugin mounts `/api-key/create`, `/update`, `/delete` and
143
+ * `/list` under the auth handler, and the CMS auth hook lets everything under
144
+ * `/api/auth` through untouched so better-auth can own its own routes. That
145
+ * combination meant any signed-in user — a viewer included — could mint or
146
+ * revoke keys by POSTing directly, bypassing the `apiKey.manage` capability
147
+ * check on the CMS's `/api/settings/api-keys` route, and could write whatever
148
+ * they liked into the client-writable metadata.
149
+ *
150
+ * `ctx.request` is only populated when a call arrived over HTTP; the CMS's own
151
+ * server-side `auth.api.createApiKey` / `verifyApiKey` calls pass just a body,
152
+ * so they keep working. That makes the CMS route the single authorized way in,
153
+ * which is where the capability check and the org binding already live.
154
+ */
155
+ const blockDirectApiKeyEndpoints = createAuthMiddleware(async (ctx) => {
156
+ if (ctx.path.startsWith('/api-key/') && ctx.request) {
157
+ throw new APIError('NOT_FOUND', {
158
+ message: 'API keys are managed through the CMS, not through the auth endpoint.'
159
+ });
160
+ }
161
+ });
162
+ // better-auth reads `appName` as the default TOTP issuer, so it's what shows up
163
+ // beside the code in the user's authenticator app.
164
+ // Defaults to `{}` rather than `undefined` on purpose: the plugin is registered
165
+ // unconditionally (see the tuple note below), so `config.twoFactor` being unset
166
+ // means "take the defaults", not "no 2FA". Gating anything on its presence
167
+ // would skip that wiring for every app that never wrote a `twoFactor` block —
168
+ // which is most of them, since 2FA works without one.
169
+ const baseTwoFactorOptions = twoFactor === true || !twoFactor ? {} : twoFactor;
170
+ /**
171
+ * Email delivery for the OTP second factor.
172
+ *
173
+ * Gated on the flag *and* on there being somewhere to send mail, because
174
+ * better-auth advertises `otp` in `twoFactorMethods` purely from whether
175
+ * `sendOTP` exists. Registering one that can't deliver would show users an
176
+ * "email me a code" button leading to a code that never arrives — the one
177
+ * failure mode that locks someone out of their own account.
178
+ *
179
+ * An explicit `otpOptions` in the app's config still wins, so this is a
180
+ * default rather than a ceiling.
181
+ */
182
+ const wantsEmailOtp = twoFactorMethods.includes('email');
183
+ const canSendOtpEmail = wantsEmailOtp && Boolean(emailAdapter && emailConfig);
184
+ if (wantsEmailOtp && !canSendOtpEmail && !building) {
185
+ cmsLogger.warn('[Auth]', "twoFactorMethods includes 'email' but no email adapter is configured — email codes are unavailable.");
186
+ }
187
+ // Falling back rather than honouring an empty list: a user who enabled 2FA
188
+ // against a config that offers nothing could never sign in again.
189
+ const offersTotp = twoFactorMethods.includes('totp') || !canSendOtpEmail;
190
+ const twoFactorOptions = {
191
+ ...baseTwoFactorOptions,
192
+ // Enrolment normally ends with the user proving they scanned the QR. With
193
+ // no authenticator in the picture there is nothing to prove, so enabling
194
+ // has to complete on its own or 2FA could never be turned on at all.
195
+ ...(offersTotp ? {} : { skipVerificationOnEnable: true }),
196
+ ...(canSendOtpEmail && !baseTwoFactorOptions.otpOptions
197
+ ? {
198
+ otpOptions: {
199
+ async sendOTP({ user, otp }) {
200
+ await sendAuthEmail('twoFactorOtp', user.email, user.name || user.email, otp);
201
+ }
202
+ }
203
+ }
204
+ : {})
205
+ };
206
+ const base = {
207
+ baseURL,
208
+ secret,
209
+ trustedOrigins,
210
+ ...(appName ? { appName } : {}),
211
+ session: {
212
+ // Verifies the cookie signature without a DB hit. The short maxAge keeps
213
+ // revocation lag tight for role/membership changes, which the per-request
214
+ // RBAC chain re-reads on top of this.
215
+ cookieCache: { enabled: true, maxAge: 60 }
216
+ },
217
+ // Opt-in: mounting `/delete-user` makes account deletion reachable over HTTP for
218
+ // anyone holding a session, and it's irreversible. The `user.deleted` erasure
219
+ // events below only ever fire through this endpoint, so an app that wants
220
+ // right-to-erasure has to turn it on deliberately.
221
+ ...(allowAccountDeletion
222
+ ? {
223
+ user: {
224
+ deleteUser: {
225
+ enabled: true,
226
+ // Runs before better-auth touches the user row, so refusing here
227
+ // leaves the account fully intact. The rule itself lives in
228
+ // cms-core so it holds for any provider.
229
+ beforeDelete: async (user) => {
230
+ try {
231
+ await assertAccountDeletable(db, user.id);
232
+ }
233
+ catch (error) {
234
+ if (error instanceof AccountDeletionBlockedError) {
235
+ throw new APIError('BAD_REQUEST', { message: error.message });
236
+ }
237
+ throw error;
238
+ }
239
+ }
240
+ }
241
+ }
242
+ }
243
+ : {}),
244
+ advanced: {
245
+ backgroundTasks: {
246
+ handler: (task) => {
247
+ Promise.resolve(typeof task === 'function' ? task() : task).catch(() => { });
248
+ }
249
+ }
250
+ },
251
+ database: drizzleAdapter(drizzleDb, { provider: dialect }),
252
+ databaseHooks: {
253
+ user: {
254
+ create: {
255
+ // The rule itself lives in cms-core so every AuthProvider enforces the
256
+ // same one. This hook only supplies Better Auth's lifecycle and error
257
+ // type — running *before* the row is written, so a direct POST to the
258
+ // sign-up endpoint is rejected exactly like a form submission.
259
+ before: async (user) => {
260
+ try {
261
+ await assertSignUpAllowed({ db, email: user.email, inviteOnly });
262
+ }
263
+ catch (error) {
264
+ if (error instanceof SignUpBlockedError) {
265
+ throw new APIError('FORBIDDEN', { message: error.message });
266
+ }
267
+ throw error;
268
+ }
269
+ return { data: user };
270
+ }
271
+ }
272
+ }
273
+ },
274
+ emailAndPassword: {
275
+ enabled: true,
276
+ requireEmailVerification,
277
+ revokeSessionsOnPasswordReset: true,
278
+ sendResetPassword: async ({ user, token }) => {
279
+ // better-auth's default link is /reset-password?token=…; the apps route
280
+ // the token as a path segment instead.
281
+ const resetUrl = `${baseURL || 'http://localhost:5173'}/reset-password/${token}`;
282
+ await sendAuthEmail('passwordReset', user.email, user.name || user.email, resetUrl);
283
+ }
284
+ },
285
+ emailVerification: {
286
+ enabled: true,
287
+ sendOnSignUp: requireEmailVerification,
288
+ autoSignInAfterVerification: true,
289
+ verifyEmailPath: '/verify-email',
290
+ sendVerificationEmail: async ({ user, url }) => {
291
+ // Per-address throttle. The IP rate limit below stops scripted abuse;
292
+ // this caps the damage once an attacker rotates IPs, so a victim's
293
+ // inbox (and the email quota) can't be flooded.
294
+ if (cache) {
295
+ const throttleKey = `verify-email-throttle:${user.email.toLowerCase()}`;
296
+ if (await cache.get(throttleKey)) {
297
+ cmsLogger.info('[Auth]', `Skipping verification email — throttled (${user.email})`);
298
+ return;
299
+ }
300
+ await cache.set(throttleKey, Date.now(), VERIFICATION_EMAIL_COOLDOWN);
301
+ }
302
+ await sendAuthEmail('emailVerification', user.email, user.name || user.email, url);
303
+ }
304
+ },
305
+ rateLimit: {
306
+ // better-auth only rate-limits in production by default; enabled explicitly
307
+ // so the per-endpoint rules below also apply in dev.
308
+ enabled: true,
309
+ window: 60,
310
+ max: 100,
311
+ customRules: {
312
+ '/send-verification-email': { window: 60, max: 2 },
313
+ // The endpoint is `/request-password-reset`; `/forget-password` is the
314
+ // legacy alias. Keying only on the alias — as this did — left the real
315
+ // endpoint on the generic 100/minute allowance, which is no throttle at
316
+ // all for an email-sending route.
317
+ '/request-password-reset': { window: 60, max: 2 },
318
+ '/forget-password': { window: 60, max: 2 }
319
+ }
320
+ },
321
+ ...(socialProviders ? { socialProviders } : {}),
322
+ hooks: { before: blockDirectApiKeyEndpoints, after: userSyncHooks }
323
+ };
324
+ const apiKeyPlugin = apiKey({
325
+ apiKeyHeaders: ['x-api-key'],
326
+ deferUpdates: true,
327
+ rateLimit: { enabled: true, timeWindow: 1000 * 60 * 60 * 24, maxRequests: 10000 },
328
+ enableMetadata: true,
329
+ ...(cache ? buildCacheStorage(cache) : {})
330
+ });
331
+ // One call with a fixed plugin tuple, deliberately. better-auth derives the
332
+ // whole `auth.api.*` surface from the exact tuple it's given: a conditional
333
+ // spread widens it to `(A | B)[]`, and branching into two calls makes the
334
+ // return type a union — both erase the typed endpoints, so `deleteApiKey()`
335
+ // degrades to a bare `Response` and callers lose `.success`.
336
+ //
337
+ // So the 2FA plugin is always registered, and `config.twoFactor` decides its
338
+ // options rather than its presence. Mounting /two-factor/* costs nothing on
339
+ // its own: the behaviour that needs a verification screen only engages for a
340
+ // user who has *enabled* 2FA, which requires the app to have built that UI to
341
+ // call `twoFactor.enable` in the first place.
342
+ const options = {
343
+ ...base,
344
+ plugins: [apiKeyPlugin, twoFactorPlugin(twoFactorOptions ?? {})]
345
+ };
346
+ return betterAuth(extend ? extend(options) : options);
347
+ }
348
+ //# sourceMappingURL=instance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance.js","sourceRoot":"","sources":["../src/instance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,SAAS,IAAI,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,QAAQ,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EACN,sBAAsB,EACtB,mBAAmB,EACnB,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC3B,kBAAkB,EAElB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAE/D,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAErE,oEAAoE;AACpE,MAAM,2BAA2B,GAAG,EAAE,CAAC;AAEvC,SAAS,iBAAiB,CAAC,KAAmB;IAC7C,OAAO;QACN,OAAO,EAAE,mBAA4B;QACrC,kBAAkB,EAAE,IAAI;QACxB,aAAa,EAAE;YACd,GAAG,EAAE,KAAK,EAAE,GAAW,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC;YAC1C,GAAG,EAAE,KAAK,EAAE,GAAW,EAAE,KAAa,EAAE,GAAY,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,CAAC;YACnF,MAAM,EAAE,KAAK,EAAE,GAAW,EAAE,EAAE,CAAC,KAAK,CAAC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