@glw907/cairn-cms 0.3.0 → 0.4.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/README.md +14 -6
- package/dist/auth/admins.d.ts +33 -0
- package/dist/auth/admins.d.ts.map +1 -0
- package/dist/auth/admins.js +90 -0
- package/dist/auth/config.d.ts +2097 -0
- package/dist/auth/config.d.ts.map +1 -0
- package/dist/auth/config.js +78 -0
- package/dist/auth/guard.d.ts +34 -0
- package/dist/auth/guard.d.ts.map +1 -0
- package/dist/auth/guard.js +47 -0
- package/dist/auth/index.d.ts +4 -0
- package/dist/auth/index.d.ts.map +1 -0
- package/dist/auth/index.js +6 -0
- package/dist/auth/schema.d.ts +750 -0
- package/dist/auth/schema.d.ts.map +1 -0
- package/dist/auth/schema.js +93 -0
- package/dist/components/AdminLayout.svelte +6 -6
- package/dist/components/AdminLayout.svelte.d.ts +2 -2
- package/dist/components/AdminLayout.svelte.d.ts.map +1 -1
- package/dist/components/ConfirmPage.svelte +31 -0
- package/dist/components/ConfirmPage.svelte.d.ts +11 -0
- package/dist/components/ConfirmPage.svelte.d.ts.map +1 -0
- package/dist/components/LoginPage.svelte +35 -18
- package/dist/components/LoginPage.svelte.d.ts +0 -2
- package/dist/components/LoginPage.svelte.d.ts.map +1 -1
- package/dist/components/ManageAdmins.svelte +1 -1
- package/dist/components/ManageAdmins.svelte.d.ts +1 -1
- package/dist/components/ManageAdmins.svelte.d.ts.map +1 -1
- package/dist/components/index.d.ts +1 -0
- package/dist/components/index.d.ts.map +1 -1
- package/dist/components/index.js +1 -0
- package/dist/email.d.ts.map +1 -1
- package/dist/email.js +15 -7
- package/dist/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/sveltekit/index.d.ts +7 -60
- package/dist/sveltekit/index.d.ts.map +1 -1
- package/dist/sveltekit/index.js +37 -157
- package/package.json +34 -4
- package/src/lib/auth/admins.ts +106 -0
- package/src/lib/auth/config.ts +108 -0
- package/src/lib/auth/guard.ts +60 -0
- package/src/lib/auth/index.ts +6 -0
- package/src/lib/auth/schema.ts +112 -0
- package/src/lib/components/AdminLayout.svelte +6 -6
- package/src/lib/components/ConfirmPage.svelte +31 -0
- package/src/lib/components/LoginPage.svelte +35 -18
- package/src/lib/components/ManageAdmins.svelte +1 -1
- package/src/lib/components/index.ts +1 -0
- package/src/lib/email.ts +14 -7
- package/src/lib/index.ts +2 -2
- package/src/lib/sveltekit/index.ts +46 -228
- package/dist/auth.d.ts +0 -25
- package/dist/auth.d.ts.map +0 -1
- package/dist/auth.js +0 -132
- package/src/lib/auth.ts +0 -185
package/dist/sveltekit/index.js
CHANGED
|
@@ -1,20 +1,41 @@
|
|
|
1
|
-
// cairn-core: the SvelteKit route server logic, extracted so each site's `admin/**`
|
|
2
|
-
// files are thin shims (`export const load = (event) => editLoad(event, cairn)`).
|
|
1
|
+
// cairn-core: the SvelteKit content-route server logic, extracted so each site's `admin/**`
|
|
2
|
+
// route files are thin shims (`export const load = (event) => editLoad(event, cairn)`).
|
|
3
3
|
//
|
|
4
4
|
// SvelteKit's filesystem routing requires the route *files* to live in each site's
|
|
5
5
|
// `src/routes/`, but their bodies are identical across sites — only the adapter differs.
|
|
6
6
|
// These functions take the SvelteKit event (typed structurally, to avoid depending on the
|
|
7
7
|
// site-generated `App.*` ambient types) plus the site `CairnAdapter`, and throw
|
|
8
|
-
// `redirect`/`error` from `@sveltejs/kit
|
|
9
|
-
//
|
|
8
|
+
// `redirect`/`error` from `@sveltejs/kit` (a peer dependency, so the thrown objects share
|
|
9
|
+
// class identity with the host's runtime — else the redirect 500s). Auth/session/manage-editors
|
|
10
|
+
// logic lives under `@glw907/cairn-cms/auth`; this module is content-only (list/edit/save).
|
|
10
11
|
import { redirect, error } from '@sveltejs/kit';
|
|
11
12
|
import matter from 'gray-matter';
|
|
12
|
-
import { createMagicLink, redeemMagicToken, createSession, lookupEditor, listEditors, setEditor, removeEditor, SESSION_COOKIE, SESSION_MAX_AGE, } from '../auth';
|
|
13
|
-
import { sendMagicLink } from '../email';
|
|
14
13
|
import { listMarkdown, readRaw, commitFile, installationToken } from '../github';
|
|
15
14
|
import { serializeMarkdown } from '../content';
|
|
16
15
|
import { findCollection, frontmatterFromForm } from '../adapter';
|
|
17
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Mint a GitHub App installation token for *reads* when the App is configured, else undefined
|
|
18
|
+
* (reads then fall back to anonymous). Authenticated reads get the 5000/hr limit; anonymous
|
|
19
|
+
* reads share GitHub's 60/hr-per-IP budget across Cloudflare's egress IPs, so they 403 in prod.
|
|
20
|
+
* A mint failure degrades gracefully to anonymous rather than 500ing — unlike the commit path,
|
|
21
|
+
* where a missing App is fatal, a read can still succeed unauthenticated.
|
|
22
|
+
*/
|
|
23
|
+
async function readToken(env) {
|
|
24
|
+
if (!env?.GITHUB_APP_ID || !env.GITHUB_APP_INSTALLATION_ID || !env.GITHUB_APP_PRIVATE_KEY_B64) {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
return await installationToken({
|
|
29
|
+
appId: env.GITHUB_APP_ID,
|
|
30
|
+
installationId: env.GITHUB_APP_INSTALLATION_ID,
|
|
31
|
+
privateKeyB64: env.GITHUB_APP_PRIVATE_KEY_B64,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
console.error('read token mint failed; falling back to anonymous read:', err);
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
18
39
|
/**
|
|
19
40
|
* Branding + session for every admin page. `siteName` flows from the adapter without pulling
|
|
20
41
|
* its plugin graph into client bundles — the import stays server-side in the layout load.
|
|
@@ -23,13 +44,14 @@ const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
|
|
|
23
44
|
* package); reading `event.url` here also opts the layout load into rerunning on navigation.
|
|
24
45
|
*/
|
|
25
46
|
export function adminLayoutLoad(event, adapter) {
|
|
26
|
-
return {
|
|
47
|
+
return { user: event.locals.user, siteName: adapter.siteName, pathname: event.url.pathname };
|
|
27
48
|
}
|
|
28
49
|
/** List every collection's markdown files. A failed listing degrades to an inline error. */
|
|
29
|
-
export async function adminListLoad(adapter) {
|
|
50
|
+
export async function adminListLoad(event, adapter) {
|
|
51
|
+
const token = await readToken(event.platform?.env);
|
|
30
52
|
const collections = await Promise.all(adapter.collections.map(async ({ type, label, dir }) => {
|
|
31
53
|
try {
|
|
32
|
-
return { type, label, files: await listMarkdown(adapter.backend, dir) };
|
|
54
|
+
return { type, label, files: await listMarkdown(adapter.backend, dir, token) };
|
|
33
55
|
}
|
|
34
56
|
catch (err) {
|
|
35
57
|
// A failed listing (rate limit, network) shouldn't 500 the whole admin.
|
|
@@ -38,19 +60,13 @@ export async function adminListLoad(adapter) {
|
|
|
38
60
|
}));
|
|
39
61
|
return { collections };
|
|
40
62
|
}
|
|
41
|
-
export function loginLoad(event) {
|
|
42
|
-
return {
|
|
43
|
-
sent: event.url.searchParams.get('sent') === '1',
|
|
44
|
-
error: event.url.searchParams.get('error'),
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
63
|
export async function editLoad(event, adapter) {
|
|
48
64
|
const collection = findCollection(adapter, event.params.type);
|
|
49
65
|
if (!collection)
|
|
50
66
|
throw error(404, 'Unknown collection');
|
|
51
|
-
|
|
67
|
+
const token = await readToken(event.platform?.env);
|
|
52
68
|
const path = `${collection.dir}/${event.params.id}.md`;
|
|
53
|
-
const raw = await readRaw(adapter.backend, path);
|
|
69
|
+
const raw = await readRaw(adapter.backend, path, token);
|
|
54
70
|
if (raw === null)
|
|
55
71
|
throw error(404, 'Content not found');
|
|
56
72
|
// Split frontmatter from body server-side; the editor form binds to the frontmatter and
|
|
@@ -69,70 +85,10 @@ export async function editLoad(event, adapter) {
|
|
|
69
85
|
error: event.url.searchParams.get('error'),
|
|
70
86
|
};
|
|
71
87
|
}
|
|
72
|
-
// ── /admin/auth/request (POST) ──────────────────────────────────────────────
|
|
73
|
-
export async function authRequest(event, adapter) {
|
|
74
|
-
const env = event.platform?.env;
|
|
75
|
-
if (!env?.AUTH_KV || !env.MAGIC_LINK_SECRET || !env.EMAIL) {
|
|
76
|
-
throw redirect(303, '/admin/login?error=config');
|
|
77
|
-
}
|
|
78
|
-
const form = await event.request.formData();
|
|
79
|
-
const email = String(form.get('email') ?? '').trim().toLowerCase();
|
|
80
|
-
if (!EMAIL_RE.test(email)) {
|
|
81
|
-
throw redirect(303, '/admin/login?error=invalid');
|
|
82
|
-
}
|
|
83
|
-
const editor = await lookupEditor(email, env.AUTH_KV);
|
|
84
|
-
if (!editor) {
|
|
85
|
-
throw redirect(303, '/admin/login?error=denied');
|
|
86
|
-
}
|
|
87
|
-
const token = await createMagicLink(email, env.MAGIC_LINK_SECRET, env.AUTH_KV);
|
|
88
|
-
// PUBLIC_ORIGIN overrides url.origin for local dev (where wrangler's custom-domain
|
|
89
|
-
// route makes url.origin the production host); unset in prod → url.origin is correct.
|
|
90
|
-
const origin = env.PUBLIC_ORIGIN || event.url.origin;
|
|
91
|
-
const link = `${origin}/admin/auth/callback?token=${encodeURIComponent(token)}`;
|
|
92
|
-
try {
|
|
93
|
-
await sendMagicLink(env.EMAIL, email, link, adapter.siteName, adapter.sender);
|
|
94
|
-
}
|
|
95
|
-
catch (err) {
|
|
96
|
-
console.error('magic-link send failed:', err);
|
|
97
|
-
throw redirect(303, '/admin/login?error=config');
|
|
98
|
-
}
|
|
99
|
-
throw redirect(303, '/admin/login?sent=1');
|
|
100
|
-
}
|
|
101
|
-
// ── /admin/auth/callback (GET) ──────────────────────────────────────────────
|
|
102
|
-
export async function authCallback(event) {
|
|
103
|
-
const env = event.platform?.env;
|
|
104
|
-
if (!env?.AUTH_KV || !env.MAGIC_LINK_SECRET || !env.SESSION_SECRET) {
|
|
105
|
-
throw redirect(303, '/admin/login?error=config');
|
|
106
|
-
}
|
|
107
|
-
const token = event.url.searchParams.get('token') ?? '';
|
|
108
|
-
const email = await redeemMagicToken(token, env.MAGIC_LINK_SECRET, env.AUTH_KV);
|
|
109
|
-
if (!email) {
|
|
110
|
-
throw redirect(303, '/admin/login?error=expired');
|
|
111
|
-
}
|
|
112
|
-
// Re-check the allowlist at redemption — membership may have changed since issue.
|
|
113
|
-
const editor = await lookupEditor(email, env.AUTH_KV);
|
|
114
|
-
if (!editor) {
|
|
115
|
-
throw redirect(303, '/admin/login?error=denied');
|
|
116
|
-
}
|
|
117
|
-
const session = await createSession(editor, env.SESSION_SECRET);
|
|
118
|
-
event.cookies.set(SESSION_COOKIE, session, {
|
|
119
|
-
path: '/',
|
|
120
|
-
httpOnly: true,
|
|
121
|
-
secure: event.url.protocol === 'https:',
|
|
122
|
-
sameSite: 'lax',
|
|
123
|
-
maxAge: SESSION_MAX_AGE,
|
|
124
|
-
});
|
|
125
|
-
throw redirect(303, '/admin');
|
|
126
|
-
}
|
|
127
|
-
// ── /admin/auth/logout (POST) ───────────────────────────────────────────────
|
|
128
|
-
export function logout(event) {
|
|
129
|
-
event.cookies.delete(SESSION_COOKIE, { path: '/' });
|
|
130
|
-
throw redirect(303, '/admin/login');
|
|
131
|
-
}
|
|
132
88
|
// ── /admin/save (POST) ──────────────────────────────────────────────────────
|
|
133
89
|
export async function saveCommit(event, adapter) {
|
|
134
|
-
const
|
|
135
|
-
if (!
|
|
90
|
+
const user = event.locals.user;
|
|
91
|
+
if (!user)
|
|
136
92
|
throw error(401, 'Not signed in');
|
|
137
93
|
const env = event.platform?.env;
|
|
138
94
|
if (!env?.GITHUB_APP_ID || !env.GITHUB_APP_INSTALLATION_ID || !env.GITHUB_APP_PRIVATE_KEY_B64) {
|
|
@@ -161,82 +117,6 @@ export async function saveCommit(event, adapter) {
|
|
|
161
117
|
installationId: env.GITHUB_APP_INSTALLATION_ID,
|
|
162
118
|
privateKeyB64: env.GITHUB_APP_PRIVATE_KEY_B64,
|
|
163
119
|
});
|
|
164
|
-
await commitFile(adapter.backend, `${collection.dir}/${id}.md`, markdown, { message: `Update ${collection.label.toLowerCase()}: ${id}`, author: { name:
|
|
120
|
+
await commitFile(adapter.backend, `${collection.dir}/${id}.md`, markdown, { message: `Update ${collection.label.toLowerCase()}: ${id}`, author: { name: user.name, email: user.email } }, token);
|
|
165
121
|
throw redirect(303, `/admin/edit/${type}/${id}?saved=1`);
|
|
166
122
|
}
|
|
167
|
-
// ── /admin/admins (owner-gated editor management) ────────────────────────────
|
|
168
|
-
/**
|
|
169
|
-
* The privilege-escalation gate for the manage-admins surface: only `owner`s may load it or
|
|
170
|
-
* run its actions. Returns the acting owner (so callers can guard self-targeted mutations).
|
|
171
|
-
*/
|
|
172
|
-
function requireOwner(event) {
|
|
173
|
-
const editor = event.locals.editor;
|
|
174
|
-
if (!editor)
|
|
175
|
-
throw error(401, 'Not signed in');
|
|
176
|
-
if (editor.role !== 'owner')
|
|
177
|
-
throw error(403, 'Owner access required');
|
|
178
|
-
return editor;
|
|
179
|
-
}
|
|
180
|
-
/** Resolve AUTH_KV or fail loudly — the management surface is useless without it. */
|
|
181
|
-
function ownerKv(event) {
|
|
182
|
-
const kv = event.platform?.env?.AUTH_KV;
|
|
183
|
-
if (!kv)
|
|
184
|
-
throw error(500, 'Editor allowlist is not configured');
|
|
185
|
-
return kv;
|
|
186
|
-
}
|
|
187
|
-
/** List the allowlist for the manage-admins page. Owner-only. */
|
|
188
|
-
export async function adminsLoad(event) {
|
|
189
|
-
const owner = requireOwner(event);
|
|
190
|
-
const admins = await listEditors(ownerKv(event));
|
|
191
|
-
return {
|
|
192
|
-
admins,
|
|
193
|
-
self: owner.email,
|
|
194
|
-
saved: event.url.searchParams.get('saved') === '1',
|
|
195
|
-
error: event.url.searchParams.get('error'),
|
|
196
|
-
};
|
|
197
|
-
}
|
|
198
|
-
function parseRole(value) {
|
|
199
|
-
return value === 'owner' ? 'owner' : 'editor';
|
|
200
|
-
}
|
|
201
|
-
/** Add (or update) an allowlist entry. Owner-only. */
|
|
202
|
-
export async function addAdmin(event) {
|
|
203
|
-
requireOwner(event);
|
|
204
|
-
const kv = ownerKv(event);
|
|
205
|
-
const form = await event.request.formData();
|
|
206
|
-
const email = String(form.get('email') ?? '').trim().toLowerCase();
|
|
207
|
-
const name = String(form.get('name') ?? '').trim();
|
|
208
|
-
if (!EMAIL_RE.test(email) || !name) {
|
|
209
|
-
throw redirect(303, `/admin/admins?error=${encodeURIComponent('Enter a valid email and name')}`);
|
|
210
|
-
}
|
|
211
|
-
await setEditor(email, name, parseRole(form.get('role')), kv);
|
|
212
|
-
throw redirect(303, '/admin/admins?saved=1');
|
|
213
|
-
}
|
|
214
|
-
/** Remove an allowlist entry. Owner-only; owners can't remove themselves (anti-lockout). */
|
|
215
|
-
export async function removeAdmin(event) {
|
|
216
|
-
const owner = requireOwner(event);
|
|
217
|
-
const kv = ownerKv(event);
|
|
218
|
-
const form = await event.request.formData();
|
|
219
|
-
const email = String(form.get('email') ?? '').trim().toLowerCase();
|
|
220
|
-
if (email === owner.email) {
|
|
221
|
-
throw redirect(303, `/admin/admins?error=${encodeURIComponent("You can't remove yourself")}`);
|
|
222
|
-
}
|
|
223
|
-
await removeEditor(email, kv);
|
|
224
|
-
throw redirect(303, '/admin/admins?saved=1');
|
|
225
|
-
}
|
|
226
|
-
/** Change an editor's role. Owner-only; owners can't demote themselves (anti-lockout). */
|
|
227
|
-
export async function setAdminRole(event) {
|
|
228
|
-
const owner = requireOwner(event);
|
|
229
|
-
const kv = ownerKv(event);
|
|
230
|
-
const form = await event.request.formData();
|
|
231
|
-
const email = String(form.get('email') ?? '').trim().toLowerCase();
|
|
232
|
-
const role = parseRole(form.get('role'));
|
|
233
|
-
if (email === owner.email && role !== 'owner') {
|
|
234
|
-
throw redirect(303, `/admin/admins?error=${encodeURIComponent("You can't demote yourself")}`);
|
|
235
|
-
}
|
|
236
|
-
const existing = await lookupEditor(email, kv);
|
|
237
|
-
if (!existing) {
|
|
238
|
-
throw redirect(303, `/admin/admins?error=${encodeURIComponent('No such editor')}`);
|
|
239
|
-
}
|
|
240
|
-
await setEditor(email, existing.name, role, kv);
|
|
241
|
-
throw redirect(303, '/admin/admins?saved=1');
|
|
242
|
-
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glw907/cairn-cms",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Embedded, magic-link, GitHub-committing CMS for SvelteKit/Cloudflare sites.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -9,13 +9,22 @@
|
|
|
9
9
|
"type": "git",
|
|
10
10
|
"url": "git+https://github.com/glw907/cairn-cms.git"
|
|
11
11
|
},
|
|
12
|
-
"keywords": [
|
|
12
|
+
"keywords": [
|
|
13
|
+
"cms",
|
|
14
|
+
"sveltekit",
|
|
15
|
+
"cloudflare",
|
|
16
|
+
"github",
|
|
17
|
+
"magic-link",
|
|
18
|
+
"markdown"
|
|
19
|
+
],
|
|
13
20
|
"scripts": {
|
|
14
21
|
"package": "svelte-package",
|
|
15
22
|
"package:watch": "svelte-package --watch",
|
|
16
23
|
"prepublishOnly": "svelte-package",
|
|
17
24
|
"test": "vitest run",
|
|
18
|
-
"test:watch": "vitest"
|
|
25
|
+
"test:watch": "vitest",
|
|
26
|
+
"auth:schema": "better-auth generate --config auth.cli.ts --output src/lib/auth/schema.ts -y",
|
|
27
|
+
"auth:sql": "drizzle-kit generate"
|
|
19
28
|
},
|
|
20
29
|
"exports": {
|
|
21
30
|
".": {
|
|
@@ -33,6 +42,11 @@
|
|
|
33
42
|
"svelte": "./src/lib/components/index.ts",
|
|
34
43
|
"default": "./src/lib/components/index.ts"
|
|
35
44
|
},
|
|
45
|
+
"./auth": {
|
|
46
|
+
"types": "./src/lib/auth/index.ts",
|
|
47
|
+
"svelte": "./src/lib/auth/index.ts",
|
|
48
|
+
"default": "./src/lib/auth/index.ts"
|
|
49
|
+
},
|
|
36
50
|
"./package.json": "./package.json"
|
|
37
51
|
},
|
|
38
52
|
"publishConfig": {
|
|
@@ -52,24 +66,40 @@
|
|
|
52
66
|
"svelte": "./dist/components/index.js",
|
|
53
67
|
"default": "./dist/components/index.js"
|
|
54
68
|
},
|
|
69
|
+
"./auth": {
|
|
70
|
+
"types": "./dist/auth/index.d.ts",
|
|
71
|
+
"svelte": "./dist/auth/index.js",
|
|
72
|
+
"default": "./dist/auth/index.js"
|
|
73
|
+
},
|
|
55
74
|
"./package.json": "./package.json"
|
|
56
75
|
}
|
|
57
76
|
},
|
|
58
|
-
"files": [
|
|
77
|
+
"files": [
|
|
78
|
+
"dist",
|
|
79
|
+
"src/lib"
|
|
80
|
+
],
|
|
59
81
|
"peerDependencies": {
|
|
60
82
|
"@sveltejs/kit": "^2",
|
|
83
|
+
"better-auth": "^1.6",
|
|
61
84
|
"carta-md": "^4.11",
|
|
85
|
+
"drizzle-orm": ">=0.40 <1",
|
|
62
86
|
"svelte": "^5.0.0"
|
|
63
87
|
},
|
|
64
88
|
"dependencies": {
|
|
65
89
|
"gray-matter": "^4"
|
|
66
90
|
},
|
|
67
91
|
"devDependencies": {
|
|
92
|
+
"@better-auth/cli": "^1.4.21",
|
|
68
93
|
"@cloudflare/workers-types": "^4.20260405.1",
|
|
69
94
|
"@sveltejs/kit": "^2",
|
|
70
95
|
"@sveltejs/package": "^2",
|
|
71
96
|
"@sveltejs/vite-plugin-svelte": "^7",
|
|
97
|
+
"@types/better-sqlite3": "^7.6.13",
|
|
98
|
+
"better-auth": "^1.6.11",
|
|
99
|
+
"better-sqlite3": "^12.10.0",
|
|
72
100
|
"carta-md": "^4.11",
|
|
101
|
+
"drizzle-kit": "^0.31.10",
|
|
102
|
+
"drizzle-orm": "^0.45.2",
|
|
73
103
|
"svelte": "^5",
|
|
74
104
|
"svelte-check": "^4",
|
|
75
105
|
"typescript": "^6.0.3",
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// cairn-core: owner-gated editor management, on better-auth's admin API. The `user` table IS
|
|
2
|
+
// the allowlist (disableSignUp ⇒ only listed emails can sign in), so add/remove editor = create/
|
|
3
|
+
// remove user; role flips go through the admin plugin's access-control roles (owner/editor).
|
|
4
|
+
// These run as SvelteKit form actions; each verifies the acting user is an owner first.
|
|
5
|
+
import { redirect, error } from '@sveltejs/kit';
|
|
6
|
+
import type { Auth } from './config';
|
|
7
|
+
import type { CairnUser } from './guard';
|
|
8
|
+
|
|
9
|
+
export interface AdminsData {
|
|
10
|
+
admins: CairnUser[];
|
|
11
|
+
/** Acting owner's email, so the UI can disable self-targeted remove/demote. */
|
|
12
|
+
self: string;
|
|
13
|
+
saved: boolean;
|
|
14
|
+
error: string | null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The privilege-escalation gate. better-auth's admin API also enforces this server-side (only
|
|
21
|
+
* `owner` holds the admin statements), but checking `locals.user` here gives clean redirect/403
|
|
22
|
+
* UX and lets the mutations guard self-lockout before calling the API. Returns the acting owner.
|
|
23
|
+
*/
|
|
24
|
+
export function requireOwner(user: CairnUser | null): CairnUser {
|
|
25
|
+
if (!user) throw error(401, 'Not signed in');
|
|
26
|
+
if (user.role !== 'owner') throw error(403, 'Owner access required');
|
|
27
|
+
return user;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
type Ev = { locals: { auth: Auth; user: CairnUser | null }; request: Request; url: URL };
|
|
31
|
+
|
|
32
|
+
function asCairnUser(u: { id: string; email: string; name: string; role?: string | null }): CairnUser {
|
|
33
|
+
return { id: u.id, email: u.email, name: u.name, role: u.role === 'owner' ? 'owner' : 'editor' };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Find an editor by exact (lowercased) email, or undefined. */
|
|
37
|
+
async function findByEmail(event: Ev, email: string): Promise<CairnUser | undefined> {
|
|
38
|
+
const res = await event.locals.auth.api.listUsers({
|
|
39
|
+
query: { searchValue: email, searchField: 'email', limit: 100 },
|
|
40
|
+
headers: event.request.headers,
|
|
41
|
+
});
|
|
42
|
+
const match = (res.users ?? []).find((u) => u.email.toLowerCase() === email);
|
|
43
|
+
return match ? asCairnUser(match) : undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** List the allowlist for the manage-editors page. Owner-only. */
|
|
47
|
+
export async function adminsLoad(event: Ev): Promise<AdminsData> {
|
|
48
|
+
const owner = requireOwner(event.locals.user);
|
|
49
|
+
const res = await event.locals.auth.api.listUsers({
|
|
50
|
+
query: { limit: 200 },
|
|
51
|
+
headers: event.request.headers,
|
|
52
|
+
});
|
|
53
|
+
const admins = (res.users ?? []).map(asCairnUser).sort((a, b) => a.email.localeCompare(b.email));
|
|
54
|
+
return {
|
|
55
|
+
admins,
|
|
56
|
+
self: owner.email,
|
|
57
|
+
saved: event.url.searchParams.get('saved') === '1',
|
|
58
|
+
error: event.url.searchParams.get('error'),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Add an editor (create the user). Owner-only. */
|
|
63
|
+
export async function addAdmin(event: Ev): Promise<never> {
|
|
64
|
+
requireOwner(event.locals.user);
|
|
65
|
+
const form = await event.request.formData();
|
|
66
|
+
const email = String(form.get('email') ?? '').trim().toLowerCase();
|
|
67
|
+
const name = String(form.get('name') ?? '').trim();
|
|
68
|
+
const role = form.get('role') === 'owner' ? 'owner' : 'editor';
|
|
69
|
+
if (!EMAIL_RE.test(email) || !name) {
|
|
70
|
+
throw redirect(303, `/admin/admins?error=${encodeURIComponent('Enter a valid email and name')}`);
|
|
71
|
+
}
|
|
72
|
+
// No password: a magic-link-only user (no credential account), per better-auth's createUser.
|
|
73
|
+
await event.locals.auth.api.createUser({ body: { email, name, role }, headers: event.request.headers });
|
|
74
|
+
throw redirect(303, '/admin/admins?saved=1');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Remove an editor (delete the user). Owner-only; owners can't remove themselves (anti-lockout). */
|
|
78
|
+
export async function removeAdmin(event: Ev): Promise<never> {
|
|
79
|
+
const owner = requireOwner(event.locals.user);
|
|
80
|
+
const form = await event.request.formData();
|
|
81
|
+
const email = String(form.get('email') ?? '').trim().toLowerCase();
|
|
82
|
+
if (email === owner.email) {
|
|
83
|
+
throw redirect(303, `/admin/admins?error=${encodeURIComponent("You can't remove yourself")}`);
|
|
84
|
+
}
|
|
85
|
+
const target = await findByEmail(event, email);
|
|
86
|
+
if (!target) throw redirect(303, `/admin/admins?error=${encodeURIComponent('No such editor')}`);
|
|
87
|
+
await event.locals.auth.api.removeUser({ body: { userId: target.id }, headers: event.request.headers });
|
|
88
|
+
throw redirect(303, '/admin/admins?saved=1');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Change an editor's role. Owner-only; owners can't demote themselves (anti-lockout). */
|
|
92
|
+
export async function setAdminRole(event: Ev): Promise<never> {
|
|
93
|
+
const owner = requireOwner(event.locals.user);
|
|
94
|
+
const form = await event.request.formData();
|
|
95
|
+
const email = String(form.get('email') ?? '').trim().toLowerCase();
|
|
96
|
+
const role = form.get('role') === 'owner' ? 'owner' : 'editor';
|
|
97
|
+
if (email === owner.email && role !== 'owner') {
|
|
98
|
+
throw redirect(303, `/admin/admins?error=${encodeURIComponent("You can't demote yourself")}`);
|
|
99
|
+
}
|
|
100
|
+
const target = await findByEmail(event, email);
|
|
101
|
+
if (!target) throw redirect(303, `/admin/admins?error=${encodeURIComponent('No such editor')}`);
|
|
102
|
+
await event.locals.auth.api.setRole({ body: { userId: target.id, role }, headers: event.request.headers });
|
|
103
|
+
// M3: revoke a demoted editor's live sessions so the privilege drop takes effect immediately.
|
|
104
|
+
await event.locals.auth.api.revokeUserSessions({ body: { userId: target.id }, headers: event.request.headers });
|
|
105
|
+
throw redirect(303, '/admin/admins?saved=1');
|
|
106
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// cairn-core: the better-auth instance. Auth is engine code (engine-fat rule), so the whole
|
|
2
|
+
// config — Drizzle/D1 adapter, magic-link (POST-confirm-shaped send), admin roles — lives here.
|
|
3
|
+
// Instantiated PER REQUEST in hooks.server.ts (the D1 binding is request-scoped); the factory
|
|
4
|
+
// is cheap (no I/O at construction).
|
|
5
|
+
import { betterAuth } from 'better-auth';
|
|
6
|
+
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
|
|
7
|
+
import { drizzle } from 'drizzle-orm/d1';
|
|
8
|
+
import { magicLink, admin } from 'better-auth/plugins';
|
|
9
|
+
import { createAccessControl } from 'better-auth/plugins/access';
|
|
10
|
+
import { defaultStatements } from 'better-auth/plugins/admin/access';
|
|
11
|
+
import type { D1Database } from '@cloudflare/workers-types';
|
|
12
|
+
import { sendMagicLink, type EmailSender } from '../email';
|
|
13
|
+
import * as schema from './schema';
|
|
14
|
+
|
|
15
|
+
// Two-tier roles on the admin plugin's access-control system: `owner` holds every admin
|
|
16
|
+
// statement (manage editors, revoke sessions); `editor` holds none (content-only). `adminRoles`
|
|
17
|
+
// must name a role defined here, so owner — not the plugin's built-in `admin` — is the gate.
|
|
18
|
+
const ac = createAccessControl(defaultStatements);
|
|
19
|
+
const owner = ac.newRole(defaultStatements);
|
|
20
|
+
const editor = ac.newRole({});
|
|
21
|
+
|
|
22
|
+
/** Worker bindings + vars the auth layer reads (a structural subset of `Platform.env`). */
|
|
23
|
+
export interface AuthEnv {
|
|
24
|
+
AUTH_DB?: D1Database;
|
|
25
|
+
AUTH_SECRET?: string;
|
|
26
|
+
/** Canonical origin; `BETTER_AUTH_URL` is accepted as a legacy alias. */
|
|
27
|
+
PUBLIC_ORIGIN?: string;
|
|
28
|
+
/** Legacy alias for `PUBLIC_ORIGIN`; `PUBLIC_ORIGIN` takes precedence when both are set. */
|
|
29
|
+
BETTER_AUTH_URL?: string;
|
|
30
|
+
EMAIL?: EmailSender;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Branding the magic-link email needs; threaded from the site adapter via hooks. */
|
|
34
|
+
export interface AuthBranding {
|
|
35
|
+
siteName: string;
|
|
36
|
+
/** The `From:` address used when sending magic-link emails. */
|
|
37
|
+
sender: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The drizzle adapter result `betterAuth` consumes — the same provider/schema everywhere. */
|
|
41
|
+
type DrizzleDb = Parameters<typeof drizzleAdapter>[0];
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The shared better-auth config. Kept separate from `createAuth` so the test harness can run
|
|
45
|
+
* the EXACT plugin set (allowlist semantics, expiry, POST-confirm send) over an in-memory
|
|
46
|
+
* SQLite instead of D1. `disableSignUp:true` makes the `user` table the editor allowlist —
|
|
47
|
+
* magic-link never auto-creates, so the only way in is the owner-gated admin `createUser`
|
|
48
|
+
* (see auth/admins.ts). `adminRoles:['owner']` lets owners (not the default `admin` role)
|
|
49
|
+
* drive the admin API. Tokens are stored hashed and consumed atomically on first verify
|
|
50
|
+
* (better-auth GHSA-hc7v-rggr-4hvx) — single-use by construction (C1).
|
|
51
|
+
*/
|
|
52
|
+
export function buildAuth(opts: {
|
|
53
|
+
database: DrizzleDb;
|
|
54
|
+
baseURL: string;
|
|
55
|
+
secret: string | undefined;
|
|
56
|
+
branding: AuthBranding;
|
|
57
|
+
sendLink: (email: string, token: string) => Promise<void>;
|
|
58
|
+
}) {
|
|
59
|
+
return betterAuth({
|
|
60
|
+
appName: opts.branding.siteName,
|
|
61
|
+
secret: opts.secret,
|
|
62
|
+
baseURL: opts.baseURL,
|
|
63
|
+
trustedOrigins: [opts.baseURL],
|
|
64
|
+
database: opts.database,
|
|
65
|
+
plugins: [
|
|
66
|
+
magicLink({
|
|
67
|
+
disableSignUp: true,
|
|
68
|
+
expiresIn: 600,
|
|
69
|
+
storeToken: 'hashed',
|
|
70
|
+
sendMagicLink: async ({ email, token }, ctx) => {
|
|
71
|
+
// Allowlist gate: better-auth always fires this callback (even for unknown emails, to
|
|
72
|
+
// avoid enumeration) and only blocks user creation at verify. So gate the actual send
|
|
73
|
+
// here — never email a non-editor. The login UI shows neutral copy either way, so this
|
|
74
|
+
// leaks nothing; it just stops strangers receiving a dead link.
|
|
75
|
+
const existing = await ctx?.context.internalAdapter.findUserByEmail(email);
|
|
76
|
+
if (!existing?.user) return;
|
|
77
|
+
await opts.sendLink(email, token);
|
|
78
|
+
},
|
|
79
|
+
}),
|
|
80
|
+
admin({ ac, roles: { owner, editor }, defaultRole: 'editor', adminRoles: ['owner'] }),
|
|
81
|
+
],
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Build the per-request better-auth instance over the site's D1 binding. The magic-link email
|
|
87
|
+
* points at OUR confirm page carrying only the token; consumption happens when the user clicks
|
|
88
|
+
* "Confirm sign-in" there (a POST), never on a scanner GET (C2 / POST-confirm). The origin is
|
|
89
|
+
* config-derived (`PUBLIC_ORIGIN`/`BETTER_AUTH_URL`), never request-derived (H3).
|
|
90
|
+
*/
|
|
91
|
+
export function createAuth(env: AuthEnv, branding: AuthBranding) {
|
|
92
|
+
if (!env.AUTH_DB) throw new Error('AUTH_DB (D1) binding is required');
|
|
93
|
+
const origin = env.PUBLIC_ORIGIN || env.BETTER_AUTH_URL || 'http://localhost';
|
|
94
|
+
const db = drizzle(env.AUTH_DB, { schema });
|
|
95
|
+
return buildAuth({
|
|
96
|
+
database: drizzleAdapter(db, { provider: 'sqlite', schema }),
|
|
97
|
+
baseURL: origin,
|
|
98
|
+
secret: env.AUTH_SECRET,
|
|
99
|
+
branding,
|
|
100
|
+
sendLink: async (email, token) => {
|
|
101
|
+
if (!env.EMAIL) throw new Error('EMAIL binding is required to send magic links');
|
|
102
|
+
const link = `${origin}/admin/auth/confirm?token=${encodeURIComponent(token)}`;
|
|
103
|
+
await sendMagicLink(env.EMAIL, email, link, branding.siteName, branding.sender);
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export type Auth = ReturnType<typeof createAuth>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// cairn-core: server-side auth helpers the site route shims delegate to. Each takes the
|
|
2
|
+
// SvelteKit event (typed structurally, so the package never depends on a site's generated
|
|
3
|
+
// `App.*` ambient types) plus the per-request `Auth` from `locals`.
|
|
4
|
+
import { redirect } from '@sveltejs/kit';
|
|
5
|
+
import type { Auth } from './config';
|
|
6
|
+
|
|
7
|
+
/** The session shape the whole admin reads — layout, guards, content fns, manage-editors. */
|
|
8
|
+
export interface CairnUser {
|
|
9
|
+
id: string;
|
|
10
|
+
email: string;
|
|
11
|
+
name: string;
|
|
12
|
+
role: 'owner' | 'editor';
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Read the better-auth session into a cairn user (or null). */
|
|
16
|
+
export async function loadSession(auth: Auth, request: Request): Promise<CairnUser | null> {
|
|
17
|
+
const session = await auth.api.getSession({ headers: request.headers });
|
|
18
|
+
if (!session?.user) return null;
|
|
19
|
+
const u = session.user as { id: string; email: string; name: string; role?: string | null };
|
|
20
|
+
return { id: u.id, email: u.email, name: u.name, role: u.role === 'owner' ? 'owner' : 'editor' };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function requireSession(user: CairnUser | null): CairnUser {
|
|
24
|
+
if (!user) throw redirect(303, '/admin/login');
|
|
25
|
+
return user;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type ConfirmEvent = { request: Request; locals: { auth: Auth }; url: URL };
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* POST-confirm verification (C2). Invoked from the confirm page's POST action: proxies the
|
|
32
|
+
* token to better-auth's GET verify endpoint via the per-request handler, then forwards the
|
|
33
|
+
* resulting Set-Cookie(s) onto a 303 to /admin. Scanners GET the confirm *page* (nothing is
|
|
34
|
+
* consumed); only this explicit POST consumes the token.
|
|
35
|
+
*/
|
|
36
|
+
export async function confirmSignIn(event: ConfirmEvent): Promise<Response> {
|
|
37
|
+
const form = await event.request.formData();
|
|
38
|
+
const token = String(form.get('token') ?? '');
|
|
39
|
+
if (!token) throw redirect(303, '/admin/login?error=expired');
|
|
40
|
+
|
|
41
|
+
const verifyUrl = `${event.url.origin}/api/auth/magic-link/verify?token=${encodeURIComponent(token)}&callbackURL=/admin`;
|
|
42
|
+
const res = await event.locals.auth.handler(new Request(verifyUrl, { headers: event.request.headers }));
|
|
43
|
+
const cookies = res.headers.getSetCookie();
|
|
44
|
+
if (cookies.length === 0) throw redirect(303, '/admin/login?error=expired');
|
|
45
|
+
|
|
46
|
+
const headers = new Headers({ location: '/admin' });
|
|
47
|
+
for (const cookie of cookies) headers.append('set-cookie', cookie);
|
|
48
|
+
return new Response(null, { status: 303, headers });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Sign out via better-auth, forwarding the session-clearing cookies, then 303 to login. */
|
|
52
|
+
export async function signOut(event: { request: Request; locals: { auth: Auth } }): Promise<Response> {
|
|
53
|
+
const origin = new URL(event.request.url).origin;
|
|
54
|
+
const res = await event.locals.auth.handler(
|
|
55
|
+
new Request(`${origin}/api/auth/sign-out`, { method: 'POST', headers: event.request.headers }),
|
|
56
|
+
);
|
|
57
|
+
const headers = new Headers({ location: '/admin/login' });
|
|
58
|
+
for (const cookie of res.headers.getSetCookie()) headers.append('set-cookie', cookie);
|
|
59
|
+
return new Response(null, { status: 303, headers });
|
|
60
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Public surface of `@glw907/cairn-cms/auth`: the per-request factory + server-side helpers
|
|
2
|
+
// the site route shims and hooks delegate to. The browser client is intentionally NOT here
|
|
3
|
+
// (it lives component-local in LoginPage to keep better-auth's deep client types out of dist).
|
|
4
|
+
export { createAuth, type Auth, type AuthEnv, type AuthBranding } from './config';
|
|
5
|
+
export { loadSession, requireSession, confirmSignIn, signOut, type CairnUser } from './guard';
|
|
6
|
+
export { adminsLoad, addAdmin, removeAdmin, setAdminRole, requireOwner, type AdminsData } from './admins';
|