@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Benjamin Sinidol
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,12 @@
1
+ import { type BootstrapPolicy } from '@aphexcms/cms-core/server';
2
+ /**
3
+ * Resolves the configured first-administrator policy, or the default.
4
+ *
5
+ * Lives in its own module because two call sites need the same answer: the auth
6
+ * instance creates a profile in its `/sign-up/email` hook, and the auth service
7
+ * creates one lazily in `getSession` for any user who somehow reaches a request
8
+ * without one. If those two disagreed about the default, who becomes the first
9
+ * administrator would depend on which path happened to run first.
10
+ */
11
+ export declare function resolveBootstrapPolicy(policy?: BootstrapPolicy): BootstrapPolicy;
12
+ //# sourceMappingURL=bootstrap-policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap-policy.d.ts","sourceRoot":"","sources":["../src/bootstrap-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,KAAK,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAEhF;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,CAAC,EAAE,eAAe,GAAG,eAAe,CAEhF"}
@@ -0,0 +1,14 @@
1
+ import { openFirstUser } from '@aphexcms/cms-core/server';
2
+ /**
3
+ * Resolves the configured first-administrator policy, or the default.
4
+ *
5
+ * Lives in its own module because two call sites need the same answer: the auth
6
+ * instance creates a profile in its `/sign-up/email` hook, and the auth service
7
+ * creates one lazily in `getSession` for any user who somehow reaches a request
8
+ * without one. If those two disagreed about the default, who becomes the first
9
+ * administrator would depend on which path happened to run first.
10
+ */
11
+ export function resolveBootstrapPolicy(policy) {
12
+ return policy ?? openFirstUser();
13
+ }
14
+ //# sourceMappingURL=bootstrap-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap-policy.js","sourceRoot":"","sources":["../src/bootstrap-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAwB,MAAM,2BAA2B,CAAC;AAEhF;;;;;;;;GAQG;AACH,MAAM,UAAU,sBAAsB,CAAC,MAAwB;IAC9D,OAAO,MAAM,IAAI,aAAa,EAAE,CAAC;AAClC,CAAC"}
@@ -0,0 +1,105 @@
1
+ import { type DatabaseAdapter } from '@aphexcms/cms-core/server';
2
+ /** Instance-level role a bootstrap policy may grant. */
3
+ export type InstanceRole = 'super_admin' | 'admin' | 'editor' | 'viewer';
4
+ export interface BootstrapContext {
5
+ user: {
6
+ id: string;
7
+ email: string;
8
+ emailVerified: boolean;
9
+ };
10
+ /**
11
+ * True only when the system is *provably* empty.
12
+ *
13
+ * Never inferred from a missing capability: an adapter that can't answer the
14
+ * question yields `false`, so an unanswerable check can't be mistaken for
15
+ * "nobody is here yet, promote this person".
16
+ */
17
+ isFirstUser: boolean;
18
+ /** The request that triggered profile creation, when there is one. */
19
+ request?: Request;
20
+ db: DatabaseAdapter;
21
+ }
22
+ /**
23
+ * Decides what instance role a brand-new user profile gets.
24
+ *
25
+ * Bootstrapping is a policy decision, not a library one — how you claim a fresh
26
+ * instance depends on how you deploy it. Return `null` for "no promotion"; the
27
+ * caller falls back to the ordinary `editor` role.
28
+ */
29
+ export interface BootstrapPolicy {
30
+ (ctx: BootstrapContext): Promise<InstanceRole | null>;
31
+ /**
32
+ * Optional one-off startup step, run before any request is served.
33
+ *
34
+ * Lets a recipe own its own setup instead of making the app wire it: only
35
+ * `claimCode()` needs one (to generate and log its code), and an app that
36
+ * swaps recipes shouldn't have to remember to delete a hook. Callers invoke
37
+ * it as `policy.prepare?.(db)` — recipes without setup simply omit it.
38
+ */
39
+ prepare?: (db: DatabaseAdapter) => Promise<void>;
40
+ }
41
+ /**
42
+ * Ensure an unclaimed instance has a pending claim code, and log it.
43
+ *
44
+ * Only the **hash** is persisted: a leaked database dump or backup shouldn't be
45
+ * enough to claim the instance. Called at startup by `claimCode()` consumers.
46
+ */
47
+ export declare function ensureClaimCode(db: DatabaseAdapter): Promise<void>;
48
+ /**
49
+ * True when nobody has claimed this instance yet and a code is waiting to be
50
+ * used. Drives the sign-up form's claim-code field: without this the code has
51
+ * nowhere to go but a hand-set cookie, which is not a flow anyone can follow.
52
+ *
53
+ * Deliberately narrow. It reveals only that an instance is unclaimed — never the
54
+ * code or its hash — so it is safe to hand to an unauthenticated page. That fact
55
+ * is already obvious to anyone who can reach a CMS with no users in it.
56
+ */
57
+ export declare function isInstanceUnclaimed(db: DatabaseAdapter): Promise<boolean>;
58
+ /**
59
+ * The default. Keeps the familiar first-run wizard, but promotion requires a
60
+ * code printed to the server log at startup — so arriving first isn't enough,
61
+ * you also have to control the deployment. Same shape as Jupyter's `?token=`
62
+ * and GitLab's generated root password.
63
+ *
64
+ * The code is single-use, but not mutually exclusive: it's cleared as its own
65
+ * write rather than atomically with the profile insert. Two concurrent claims
66
+ * can therefore both read the hash before either clears it, and a claim can be
67
+ * spent by a request whose profile insert then fails.
68
+ *
69
+ * That's a deliberate trade. Wrapping both in one transaction holds SQLite's
70
+ * single write lock across the auth provider's own concurrent user/session
71
+ * inserts, which fails the whole sign-up with SQLITE_BUSY. Closing the race
72
+ * properly needs a uniqueness constraint on "one super admin" at the database
73
+ * level, not a longer lock. In practice every racer must already hold the code,
74
+ * so the exposure is a duplicate admin, never an unauthorised one.
75
+ */
76
+ export declare function claimCode(options?: {
77
+ readCode?: (request?: Request) => string | undefined;
78
+ }): BootstrapPolicy;
79
+ /**
80
+ * First user whose address is on the allowlist becomes super admin — Discourse's
81
+ * `DISCOURSE_DEVELOPER_EMAILS`. Good when you know the owner's address at deploy
82
+ * time and would rather not read logs.
83
+ *
84
+ * This recipe is only as strong as the address is trustworthy, so pair it with
85
+ * `requireEmailVerification`. That's enforced at the auth layer — better-auth
86
+ * refuses to complete sign-in for an unconfirmed address, so an unverified user
87
+ * never reaches profile creation at all. Re-checking it here would be dead code
88
+ * when verification is on, and would brick a fresh install when it's off.
89
+ */
90
+ export declare function allowlistEmail(emails: string | readonly string[] | undefined): BootstrapPolicy;
91
+ /**
92
+ * Whoever signs up first becomes super admin, with nothing else required.
93
+ *
94
+ * This is what WordPress, Ghost, Strapi and Payload do, and it's fine when you
95
+ * install immediately after deploying. It is **not** fine for an instance that
96
+ * sits reachable before anyone signs in: the first stranger to find the URL owns
97
+ * it. Opt in deliberately.
98
+ */
99
+ export declare function openFirstUser(): BootstrapPolicy;
100
+ /**
101
+ * Never promote anyone. Provision the first administrator out of band — a seed
102
+ * script, a migration, or a direct row — the way Directus and Keycloak do.
103
+ */
104
+ export declare function never(): BootstrapPolicy;
105
+ //# sourceMappingURL=bootstrap.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap.d.ts","sourceRoot":"","sources":["../src/bootstrap.ts"],"names":[],"mappings":"AAEA,OAAO,EAAmB,KAAK,eAAe,EA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Ae,CAEvC"}
@@ -0,0 +1,164 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import { cmsLogger } from '@aphexcms/cms-core';
3
+ import { isInstanceEmpty } from '@aphexcms/cms-core/server';
4
+ /** Where the claim-code hash lives inside the instance-settings blob. */
5
+ const CLAIM_CODE_KEY = 'bootstrapClaimCodeHash';
6
+ function hashCode(code) {
7
+ return createHash('sha256').update(code).digest('hex');
8
+ }
9
+ /** Constant-time compare of two hex digests of equal length. */
10
+ function digestsMatch(a, b) {
11
+ const left = Buffer.from(a, 'hex');
12
+ const right = Buffer.from(b, 'hex');
13
+ if (left.length !== right.length || left.length === 0)
14
+ return false;
15
+ return timingSafeEqual(left, right);
16
+ }
17
+ /**
18
+ * Ensure an unclaimed instance has a pending claim code, and log it.
19
+ *
20
+ * Only the **hash** is persisted: a leaked database dump or backup shouldn't be
21
+ * enough to claim the instance. Called at startup by `claimCode()` consumers.
22
+ */
23
+ export async function ensureClaimCode(db) {
24
+ if (!(await isInstanceEmpty(db)))
25
+ return;
26
+ const settings = await db.getInstanceSettings();
27
+ if (typeof settings[CLAIM_CODE_KEY] === 'string')
28
+ return;
29
+ const code = randomBytes(24).toString('base64url');
30
+ await db.updateInstanceSettings({ [CLAIM_CODE_KEY]: hashCode(code) });
31
+ cmsLogger.info('[Bootstrap]', `\n\n This instance has no administrator yet.\n` +
32
+ ` Sign up at /admin and enter this claim code to become the super admin:\n\n` +
33
+ ` ${code}\n\n` +
34
+ ` It is single-use and is not stored in recoverable form. If you lose it,\n` +
35
+ ` clear "${CLAIM_CODE_KEY}" from instance settings and restart to get a new one.\n`);
36
+ }
37
+ /**
38
+ * True when nobody has claimed this instance yet and a code is waiting to be
39
+ * used. Drives the sign-up form's claim-code field: without this the code has
40
+ * nowhere to go but a hand-set cookie, which is not a flow anyone can follow.
41
+ *
42
+ * Deliberately narrow. It reveals only that an instance is unclaimed — never the
43
+ * code or its hash — so it is safe to hand to an unauthenticated page. That fact
44
+ * is already obvious to anyone who can reach a CMS with no users in it.
45
+ */
46
+ export async function isInstanceUnclaimed(db) {
47
+ if (!(await isInstanceEmpty(db)))
48
+ return false;
49
+ const settings = await db.getInstanceSettings();
50
+ return typeof settings[CLAIM_CODE_KEY] === 'string';
51
+ }
52
+ /**
53
+ * The default. Keeps the familiar first-run wizard, but promotion requires a
54
+ * code printed to the server log at startup — so arriving first isn't enough,
55
+ * you also have to control the deployment. Same shape as Jupyter's `?token=`
56
+ * and GitLab's generated root password.
57
+ *
58
+ * The code is single-use, but not mutually exclusive: it's cleared as its own
59
+ * write rather than atomically with the profile insert. Two concurrent claims
60
+ * can therefore both read the hash before either clears it, and a claim can be
61
+ * spent by a request whose profile insert then fails.
62
+ *
63
+ * That's a deliberate trade. Wrapping both in one transaction holds SQLite's
64
+ * single write lock across the auth provider's own concurrent user/session
65
+ * inserts, which fails the whole sign-up with SQLITE_BUSY. Closing the race
66
+ * properly needs a uniqueness constraint on "one super admin" at the database
67
+ * level, not a longer lock. In practice every racer must already hold the code,
68
+ * so the exposure is a duplicate admin, never an unauthorised one.
69
+ */
70
+ export function claimCode(options = {}) {
71
+ /**
72
+ * Header, `?claim=` query param, or an `aphex_bootstrap_code` cookie — in that
73
+ * order. The profile is created on the first authenticated request after
74
+ * sign-up, which may be a redirect the signup form doesn't control, so a
75
+ * header alone would be unreachable from a plain HTML flow. Override
76
+ * `readCode` if you want to accept it somewhere else.
77
+ */
78
+ const readCode = options.readCode ??
79
+ ((request) => {
80
+ if (!request)
81
+ return undefined;
82
+ const header = request.headers.get('x-aphex-bootstrap-code');
83
+ if (header)
84
+ return header;
85
+ const fromQuery = new URL(request.url).searchParams.get('claim');
86
+ if (fromQuery)
87
+ return fromQuery;
88
+ const cookie = request.headers.get('cookie');
89
+ const raw = cookie?.match(/(?:^|;\s*)aphex_bootstrap_code=([^;]+)/)?.[1];
90
+ // The sign-up form percent-encodes the value. A generated base64url code
91
+ // has nothing to decode, but a custom one may.
92
+ return raw === undefined ? undefined : decodeURIComponent(raw);
93
+ });
94
+ const policy = async ({ isFirstUser, request, db }) => {
95
+ if (!isFirstUser)
96
+ return null;
97
+ const supplied = readCode(request)?.trim();
98
+ if (!supplied)
99
+ return null;
100
+ const settings = await db.getInstanceSettings();
101
+ const expected = settings[CLAIM_CODE_KEY];
102
+ if (typeof expected !== 'string')
103
+ return null;
104
+ if (!digestsMatch(hashCode(supplied), expected)) {
105
+ cmsLogger.warn('[Bootstrap]', 'Rejected claim attempt — code did not match');
106
+ return null;
107
+ }
108
+ // Single-use: clearing the hash is what makes a second claimant lose.
109
+ await db.updateInstanceSettings({ [CLAIM_CODE_KEY]: null });
110
+ cmsLogger.info('[Bootstrap]', 'Instance claimed — super admin created');
111
+ return 'super_admin';
112
+ };
113
+ // The code only exists because this recipe was chosen, so this recipe is what
114
+ // generates it. Swapping to another recipe takes the startup step with it.
115
+ policy.prepare = ensureClaimCode;
116
+ return policy;
117
+ }
118
+ /**
119
+ * First user whose address is on the allowlist becomes super admin — Discourse's
120
+ * `DISCOURSE_DEVELOPER_EMAILS`. Good when you know the owner's address at deploy
121
+ * time and would rather not read logs.
122
+ *
123
+ * This recipe is only as strong as the address is trustworthy, so pair it with
124
+ * `requireEmailVerification`. That's enforced at the auth layer — better-auth
125
+ * refuses to complete sign-in for an unconfirmed address, so an unverified user
126
+ * never reaches profile creation at all. Re-checking it here would be dead code
127
+ * when verification is on, and would brick a fresh install when it's off.
128
+ */
129
+ export function allowlistEmail(emails) {
130
+ const allowed = new Set((typeof emails === 'string' ? emails.split(',') : (emails ?? []))
131
+ .map((email) => email.trim().toLowerCase())
132
+ .filter(Boolean));
133
+ return async ({ isFirstUser, user }) => {
134
+ if (!isFirstUser || allowed.size === 0)
135
+ return null;
136
+ if (!allowed.has(user.email.trim().toLowerCase()))
137
+ return null;
138
+ if (!user.emailVerified) {
139
+ // Advice, not enforcement — the decision belongs to the auth layer.
140
+ cmsLogger.warn('[Bootstrap]', `Promoting ${user.email} on an unverified address. Set ` +
141
+ `AUTH_REQUIRE_EMAIL_VERIFICATION=true so the address has to be proven.`);
142
+ }
143
+ return 'super_admin';
144
+ };
145
+ }
146
+ /**
147
+ * Whoever signs up first becomes super admin, with nothing else required.
148
+ *
149
+ * This is what WordPress, Ghost, Strapi and Payload do, and it's fine when you
150
+ * install immediately after deploying. It is **not** fine for an instance that
151
+ * sits reachable before anyone signs in: the first stranger to find the URL owns
152
+ * it. Opt in deliberately.
153
+ */
154
+ export function openFirstUser() {
155
+ return async ({ isFirstUser }) => (isFirstUser ? 'super_admin' : null);
156
+ }
157
+ /**
158
+ * Never promote anyone. Provision the first administrator out of band — a seed
159
+ * script, a migration, or a direct row — the way Directus and Keycloak do.
160
+ */
161
+ export function never() {
162
+ return async () => null;
163
+ }
164
+ //# sourceMappingURL=bootstrap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../src/bootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAwB,MAAM,2BAA2B,CAAC;AAKlF,yEAAyE;AACzE,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAqChD,SAAS,QAAQ,CAAC,IAAY;IAC7B,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACxD,CAAC;AAED,gEAAgE;AAChE,SAAS,YAAY,CAAC,CAAS,EAAE,CAAS;IACzC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;IACnC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;IACpC,IAAI,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM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AC;IACtB,CAAC,CAAC;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa;IAC5B,OAAO,KAAK,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;AACxE,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,KAAK;IACpB,OAAO,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC;AACzB,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { AuthCodeEmailTemplate } from '../types.js';
2
+ /**
3
+ * The built-in second-factor code email.
4
+ *
5
+ * Deliberately plain HTML with inline styles and no dependencies: this package
6
+ * can't render an app's Svelte components, and a 2FA code needs to arrive
7
+ * whether or not anyone has got around to branding it. Apps that care supply
8
+ * `email.twoFactorOtp` and this is never used.
9
+ *
10
+ * No link and no button — a code you type back into a page you already have
11
+ * open can't be phished by a lookalike URL, and putting one here would train
12
+ * people to click their way through a security step.
13
+ */
14
+ export declare const defaultTwoFactorOtpEmail: AuthCodeEmailTemplate;
15
+ //# sourceMappingURL=two-factor-otp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"two-factor-otp.d.ts","sourceRoot":"","sources":["../../src/email/two-factor-otp.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEzD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,wBAAwB,EAAE,qBA4BtC,CAAC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The built-in second-factor code email.
3
+ *
4
+ * Deliberately plain HTML with inline styles and no dependencies: this package
5
+ * can't render an app's Svelte components, and a 2FA code needs to arrive
6
+ * whether or not anyone has got around to branding it. Apps that care supply
7
+ * `email.twoFactorOtp` and this is never used.
8
+ *
9
+ * No link and no button — a code you type back into a page you already have
10
+ * open can't be phished by a lookalike URL, and putting one here would train
11
+ * people to click their way through a security step.
12
+ */
13
+ export const defaultTwoFactorOtpEmail = {
14
+ subject: 'Your sign-in code',
15
+ render: async (userName, code) => {
16
+ const text = [
17
+ `Hi ${userName},`,
18
+ '',
19
+ `Your sign-in code is: ${code}`,
20
+ '',
21
+ 'It expires in a few minutes.',
22
+ "If you didn't try to sign in, someone may have your password. Change it as soon as you can."
23
+ ].join('\n');
24
+ const html = `<!doctype html>
25
+ <html>
26
+ <body style="margin:0;padding:24px;background:#f9fafb;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;color:#374151;">
27
+ <div style="max-width:480px;margin:0 auto;background:#ffffff;border-radius:12px;padding:32px;">
28
+ <h1 style="margin:0 0 16px;font-size:24px;color:#1f2937;">Your sign-in code</h1>
29
+ <p style="margin:0 0 16px;font-size:16px;">Hi ${escapeHtml(userName)},</p>
30
+ <p style="margin:0 0 24px;font-size:16px;">Enter this code to finish signing in:</p>
31
+ <p style="margin:0 0 24px;padding:16px;background:#f3f4f6;border-radius:8px;text-align:center;font-size:32px;font-weight:bold;letter-spacing:8px;color:#1f2937;">${escapeHtml(code)}</p>
32
+ <p style="margin:0 0 8px;font-size:14px;color:#6b7280;">This code expires in a few minutes.</p>
33
+ <p style="margin:0;font-size:14px;color:#6b7280;">If you didn't try to sign in, someone may have your password. Change it as soon as you can.</p>
34
+ </div>
35
+ </body>
36
+ </html>`;
37
+ return { html, text };
38
+ }
39
+ };
40
+ /** The name is interpolated into HTML, and a user controls it. */
41
+ function escapeHtml(value) {
42
+ return value
43
+ .replace(/&/g, '&amp;')
44
+ .replace(/</g, '&lt;')
45
+ .replace(/>/g, '&gt;')
46
+ .replace(/"/g, '&quot;')
47
+ .replace(/'/g, '&#39;');
48
+ }
49
+ //# sourceMappingURL=two-factor-otp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"two-factor-otp.js","sourceRoot":"","sources":["../../src/email/two-factor-otp.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAA0B;IAC9D,OAAO,EAAE,mBAAmB;IAC5B,MAAM,EAAE,KAAK,EAAE,QAAgB,EAAE,IAAY,EAAE,EAAE;QAChD,MAAM,IAAI,GAAG;YACZ,MAAM,QAAQ,GAAG;YACjB,EAAE;YACF,yBAAyB,IAAI,EAAE;YAC/B,EAAE;YACF,8BAA8B;YAC9B,6FAA6F;SAC7F,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEb,MAAM,IAAI,GAAG;;;;;sDAKuC,UAAU,CAAC,QAAQ,CAAC;;yKAE+F,UAAU,CAAC,IAAI,CAAC;;;;;QAKjL,CAAC;QAEP,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IACvB,CAAC;CACD,CAAC;AAEF,kEAAkE;AAClE,SAAS,UAAU,CAAC,KAAa;IAChC,OAAO,KAAK;SACV,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC;SACtB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;SACvB,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAC1B,CAAC"}
@@ -0,0 +1,46 @@
1
+ import type { AuthProvider } from '@aphexcms/cms-core/server';
2
+ import { type AphexAuthInstance } from './instance.js';
3
+ import { type AuthService } from './service.js';
4
+ import type { AphexAuthConfig } from './types.js';
5
+ export type { AphexAuthConfig, AuthOptions, AuthEmailConfig, AuthEmailTemplate } from './types.js';
6
+ export type { AphexAuthInstance } from './instance.js';
7
+ export type { AuthService, ApiKey, ApiKeyWithSecret, CreateApiKeyData } from './service.js';
8
+ export { ApiKeyRevocationError } from './service.js';
9
+ export interface AphexAuth {
10
+ /**
11
+ * The underlying better-auth instance. Exposed deliberately — better-auth is a
12
+ * peer dependency, so anything it can do is reachable here without this
13
+ * package needing to grow an option for it.
14
+ */
15
+ auth: AphexAuthInstance;
16
+ /** Server-side operations: sessions, API keys, user lookups, password reset. */
17
+ service: AuthService;
18
+ /** Ready to hand to `createCMSConfig({ auth: { provider } })`. */
19
+ provider: AuthProvider;
20
+ }
21
+ /**
22
+ * Assembles auth for an Aphex app in one call.
23
+ *
24
+ * Replaces the ~975 lines every app used to copy: the better-auth instance, the
25
+ * auth service, the `AuthProvider` adapter, and the dialect-split Drizzle tables.
26
+ *
27
+ * ```ts
28
+ * export const { auth, service, provider } = createAphexAuth({
29
+ * database: db,
30
+ * drizzleDb,
31
+ * dialect: dbDialect,
32
+ * secret: env.AUTH_SECRET,
33
+ * baseURL: env.AUTH_URL,
34
+ * emailAdapter: email,
35
+ * email: emailConfig,
36
+ * cache: cacheAdapter,
37
+ * options: { requireEmailVerification: env.AUTH_REQUIRE_EMAIL_VERIFICATION === 'true' }
38
+ * });
39
+ * ```
40
+ *
41
+ * The app still owns its `/login`, `/reset-password/[token]` and `/verify-email`
42
+ * pages — those are the parts worth customising, and baking them in would mean
43
+ * every site looked the same.
44
+ */
45
+ export declare function createAphexAuth(config: AphexAuthConfig): AphexAuth;
46
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAsB,KAAK,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAC3E,OAAO,EAAqB,KAAK,WAAW,EAAE,MAAM,cAAc,CAAC;AAGnE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,YAAY,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAInG,YAAY,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvD,YAAY,EAAE,WAAW,EAAE,MAAM,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAG5F,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAErD,MAAM,WAAW,SAAS;IACzB;;;;OAIG;IACH,IAAI,EAAE,iBAAiB,CAAC;IACxB,gFAAgF;IAChF,OAAO,EAAE,WAAW,CAAC;IACrB,kEAAkE;IAClE,QAAQ,EAAE,YAAY,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS,CAgClE"}
package/dist/index.js ADDED
@@ -0,0 +1,62 @@
1
+ import { createAuthInstance } from './instance.js';
2
+ import { createAuthService } from './service.js';
3
+ import * as pgSchema from './schema/pg.js';
4
+ import * as sqliteSchema from './schema/sqlite.js';
5
+ // A value, not a type: route handlers need `instanceof` to tell an incomplete revocation
6
+ // (row gone, cache copy still live) from an ordinary delete failure.
7
+ export { ApiKeyRevocationError } from './service.js';
8
+ /**
9
+ * Assembles auth for an Aphex app in one call.
10
+ *
11
+ * Replaces the ~975 lines every app used to copy: the better-auth instance, the
12
+ * auth service, the `AuthProvider` adapter, and the dialect-split Drizzle tables.
13
+ *
14
+ * ```ts
15
+ * export const { auth, service, provider } = createAphexAuth({
16
+ * database: db,
17
+ * drizzleDb,
18
+ * dialect: dbDialect,
19
+ * secret: env.AUTH_SECRET,
20
+ * baseURL: env.AUTH_URL,
21
+ * emailAdapter: email,
22
+ * email: emailConfig,
23
+ * cache: cacheAdapter,
24
+ * options: { requireEmailVerification: env.AUTH_REQUIRE_EMAIL_VERIFICATION === 'true' }
25
+ * });
26
+ * ```
27
+ *
28
+ * The app still owns its `/login`, `/reset-password/[token]` and `/verify-email`
29
+ * pages — those are the parts worth customising, and baking them in would mean
30
+ * every site looked the same.
31
+ */
32
+ export function createAphexAuth(config) {
33
+ const auth = createAuthInstance(config);
34
+ // Match the tables to the dialect the caller's Drizzle client actually speaks;
35
+ // mixing them produces queries that compile but fail at runtime.
36
+ const schema = config.dialect === 'sqlite' ? sqliteSchema : pgSchema;
37
+ const service = createAuthService({
38
+ auth,
39
+ drizzleDb: config.drizzleDb,
40
+ schema,
41
+ // The same cache the api-key plugin uses as secondary storage, so revoking
42
+ // a key can evict it there too rather than leaving a live copy behind.
43
+ cache: config.cache,
44
+ bootstrap: config.bootstrap
45
+ });
46
+ // cms-core talks to auth exclusively through this port, so an app that swaps
47
+ // this package for its own implementation needs nothing else to change.
48
+ const provider = {
49
+ getSession: (request, db) => service.getSession(request, db),
50
+ requireSession: (request, db) => service.requireSession(request, db),
51
+ validateApiKey: (request, db) => service.validateApiKey(request, db),
52
+ requireApiKey: (request, db, permission) => service.requireApiKey(request, db, permission),
53
+ getUserById: (userId) => service.getUserById(userId),
54
+ getUserByEmail: (email) => service.getUserByEmail(email),
55
+ changeUserName: (userId, name) => service.changeUserName(userId, name),
56
+ changeUserImage: (userId, image) => service.changeUserImage(userId, image),
57
+ requestPasswordReset: (email, redirectTo) => service.requestPasswordReset(email, redirectTo),
58
+ resetPassword: (token, newPassword) => service.resetPassword(token, newPassword)
59
+ };
60
+ return { auth, service, provider };
61
+ }
62
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAA0B,MAAM,eAAe,CAAC;AAC3E,OAAO,EAAE,iBAAiB,EAAoB,MAAM,cAAc,CAAC;AACnE,OAAO,KAAK,QAAQ,MAAM,gBAAgB,CAAC;AAC3C,OAAO,KAAK,YAAY,MAAM,oBAAoB,CAAC;AASnD,yFAAyF;AACzF,qEAAqE;AACrE,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAerD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,eAAe,CAAC,MAAuB;IACtD,MAAM,IAAI,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;IAExC,+EAA+E;IAC/E,iEAAiE;IACjE,MAA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