deneljs 0.0.0-stage → 1.0.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 +21 -0
- package/README.md +57 -2
- package/drizzle/0000_lonely_reptil.sql +27 -0
- package/drizzle/0001_misty_wendigo.sql +74 -0
- package/drizzle/meta/0000_snapshot.json +179 -0
- package/drizzle/meta/0001_snapshot.json +492 -0
- package/drizzle/meta/_journal.json +20 -0
- package/package.json +55 -4
- package/src/admin/auth.ts +851 -0
- package/src/admin/layout.ts +419 -0
- package/src/admin/pages/categories.ts +223 -0
- package/src/admin/pages/dashboard.ts +192 -0
- package/src/admin/pages/media.ts +270 -0
- package/src/admin/pages/posts.ts +804 -0
- package/src/admin/pages/settings.ts +169 -0
- package/src/admin/pages/themes.ts +461 -0
- package/src/admin/pages/users.ts +501 -0
- package/src/admin/routes.ts +455 -0
- package/src/admin/tiptap-bundle.ts +48 -0
- package/src/admin/tiptap-entry.ts +226 -0
- package/src/ai/generator.ts +296 -0
- package/src/ai/index.ts +22 -0
- package/src/ai/schema.ts +13 -0
- package/src/ai/spec.ts +193 -0
- package/src/cli.ts +151 -0
- package/src/db/index.ts +278 -0
- package/src/db/schema.ts +115 -0
- package/src/engine/index.ts +52 -0
- package/src/engine/renderer.ts +533 -0
- package/src/engine/sandbox.ts +108 -0
- package/src/engine/schema.ts +71 -0
- package/src/engine/validator.ts +404 -0
- package/src/routes/admin-api.ts +1035 -0
- package/src/routes/posts.ts +294 -0
- package/src/routes/uploads.ts +119 -0
- package/src/server.ts +672 -0
- package/src/utils/sanitize-html.ts +145 -0
- package/themes/.gitkeep +1 -0
- package/themes/default/assets/style.css +799 -0
- package/themes/default/layouts/base.liquid +31 -0
- package/themes/default/layouts/home.liquid +180 -0
- package/themes/default/layouts/page.liquid +21 -0
- package/themes/default/layouts/post.liquid +55 -0
- package/themes/default/partials/footer.liquid +33 -0
- package/themes/default/partials/navbar.liquid +49 -0
- package/themes/default/theme.json +59 -0
|
@@ -0,0 +1,851 @@
|
|
|
1
|
+
import { eq } from "drizzle-orm";
|
|
2
|
+
import { Elysia, t } from "elysia";
|
|
3
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
4
|
+
import { db, getSiteSettings, hasAdminAccount, schema, sqlite } from "../db";
|
|
5
|
+
import type { UserRole, UserStatus } from "../db/schema";
|
|
6
|
+
|
|
7
|
+
export const SESSION_COOKIE_NAME = "cms_session";
|
|
8
|
+
const SESSION_TTL_SECONDS = 7 * 24 * 60 * 60;
|
|
9
|
+
const INTERNAL_SECRET_KEY = "_internal_session_secret";
|
|
10
|
+
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
11
|
+
|
|
12
|
+
export interface CurrentUser {
|
|
13
|
+
id: number;
|
|
14
|
+
name: string;
|
|
15
|
+
email: string;
|
|
16
|
+
role: UserRole;
|
|
17
|
+
avatar_url: string;
|
|
18
|
+
status: UserStatus;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface SessionPayload {
|
|
22
|
+
sub: number;
|
|
23
|
+
exp: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const secretCache = new WeakMap<object, string>();
|
|
27
|
+
|
|
28
|
+
function getSigningSecret(): string {
|
|
29
|
+
const envSecret = process.env.SESSION_SECRET?.trim();
|
|
30
|
+
if (envSecret) {
|
|
31
|
+
return envSecret;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const cached = secretCache.get(sqlite);
|
|
35
|
+
if (cached) {
|
|
36
|
+
return cached;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const existing = db
|
|
40
|
+
.select({ value: schema.settings.value })
|
|
41
|
+
.from(schema.settings)
|
|
42
|
+
.where(eq(schema.settings.key, INTERNAL_SECRET_KEY))
|
|
43
|
+
.get();
|
|
44
|
+
|
|
45
|
+
if (existing?.value) {
|
|
46
|
+
secretCache.set(sqlite, existing.value);
|
|
47
|
+
return existing.value;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const generated = randomBytes(32).toString("hex");
|
|
51
|
+
db.insert(schema.settings)
|
|
52
|
+
.values({ key: INTERNAL_SECRET_KEY, value: generated })
|
|
53
|
+
.onConflictDoNothing({ target: schema.settings.key })
|
|
54
|
+
.run();
|
|
55
|
+
|
|
56
|
+
const stored = db
|
|
57
|
+
.select({ value: schema.settings.value })
|
|
58
|
+
.from(schema.settings)
|
|
59
|
+
.where(eq(schema.settings.key, INTERNAL_SECRET_KEY))
|
|
60
|
+
.get();
|
|
61
|
+
|
|
62
|
+
const secret = stored?.value || generated;
|
|
63
|
+
secretCache.set(sqlite, secret);
|
|
64
|
+
return secret;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function base64UrlEncode(input: string | Uint8Array): string {
|
|
68
|
+
return Buffer.from(input).toString("base64url");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function base64UrlDecode(input: string): string {
|
|
72
|
+
return Buffer.from(input, "base64url").toString("utf8");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Create a signed HMAC-SHA256 session token for a user ID.
|
|
77
|
+
*/
|
|
78
|
+
export function signSessionToken(userId: number): string {
|
|
79
|
+
const header = base64UrlEncode(JSON.stringify({ alg: "HS256", typ: "JWT" }));
|
|
80
|
+
const payload: SessionPayload = {
|
|
81
|
+
sub: userId,
|
|
82
|
+
exp: Math.floor(Date.now() / 1000) + SESSION_TTL_SECONDS,
|
|
83
|
+
};
|
|
84
|
+
const encodedPayload = base64UrlEncode(JSON.stringify(payload));
|
|
85
|
+
const data = `${header}.${encodedPayload}`;
|
|
86
|
+
const sig = createHmac("sha256", getSigningSecret()).update(data).digest("base64url");
|
|
87
|
+
return `${data}.${sig}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Verify a signed session token and return its payload if valid and unexpired.
|
|
92
|
+
*/
|
|
93
|
+
export function verifySessionToken(token: string): SessionPayload | null {
|
|
94
|
+
const parts = token.split(".");
|
|
95
|
+
if (parts.length !== 3) {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const [header, encodedPayload, signature] = parts;
|
|
100
|
+
if (!header || !encodedPayload || !signature) {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const data = `${header}.${encodedPayload}`;
|
|
105
|
+
const expectedSig = createHmac("sha256", getSigningSecret())
|
|
106
|
+
.update(data)
|
|
107
|
+
.digest("base64url");
|
|
108
|
+
|
|
109
|
+
const sigBuf = Buffer.from(signature);
|
|
110
|
+
const expectedBuf = Buffer.from(expectedSig);
|
|
111
|
+
if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
try {
|
|
116
|
+
const parsed = JSON.parse(base64UrlDecode(encodedPayload)) as Partial<SessionPayload>;
|
|
117
|
+
if (
|
|
118
|
+
typeof parsed.sub !== "number" ||
|
|
119
|
+
!Number.isInteger(parsed.sub) ||
|
|
120
|
+
typeof parsed.exp !== "number"
|
|
121
|
+
) {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
if (parsed.exp <= Math.floor(Date.now() / 1000)) {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
return { sub: parsed.sub, exp: parsed.exp };
|
|
128
|
+
} catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function parseCookieValue(cookieHeader: string | null, name: string): string | null {
|
|
134
|
+
if (!cookieHeader) {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
for (const part of cookieHeader.split(";")) {
|
|
139
|
+
const idx = part.indexOf("=");
|
|
140
|
+
if (idx === -1) continue;
|
|
141
|
+
const key = part.slice(0, idx).trim();
|
|
142
|
+
if (key === name) {
|
|
143
|
+
const val = part.slice(idx + 1).trim();
|
|
144
|
+
try {
|
|
145
|
+
return decodeURIComponent(val);
|
|
146
|
+
} catch {
|
|
147
|
+
return val;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Resolve the authenticated active user from the request's session cookie.
|
|
157
|
+
*/
|
|
158
|
+
export function resolveCurrentUser(request: Request): CurrentUser | null {
|
|
159
|
+
const token = parseCookieValue(request.headers.get("cookie"), SESSION_COOKIE_NAME);
|
|
160
|
+
if (!token) {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const payload = verifySessionToken(token);
|
|
165
|
+
if (!payload) {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const user = db
|
|
170
|
+
.select({
|
|
171
|
+
id: schema.users.id,
|
|
172
|
+
name: schema.users.name,
|
|
173
|
+
email: schema.users.email,
|
|
174
|
+
role: schema.users.role,
|
|
175
|
+
avatar_url: schema.users.avatar_url,
|
|
176
|
+
status: schema.users.status,
|
|
177
|
+
})
|
|
178
|
+
.from(schema.users)
|
|
179
|
+
.where(eq(schema.users.id, payload.sub))
|
|
180
|
+
.get();
|
|
181
|
+
|
|
182
|
+
if (!user || user.status !== "active") {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return user;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function isSecureRequest(request: Request): boolean {
|
|
190
|
+
const forwarded = request.headers.get("x-forwarded-proto");
|
|
191
|
+
if (forwarded) {
|
|
192
|
+
return forwarded.split(",")[0]?.trim().toLowerCase() === "https";
|
|
193
|
+
}
|
|
194
|
+
return request.url.startsWith("https://");
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function buildCookieHeader(value: string, maxAge: number, secure: boolean): string {
|
|
198
|
+
const parts = [
|
|
199
|
+
`${SESSION_COOKIE_NAME}=${encodeURIComponent(value)}`,
|
|
200
|
+
"HttpOnly",
|
|
201
|
+
"Path=/",
|
|
202
|
+
"SameSite=Lax",
|
|
203
|
+
`Max-Age=${maxAge}`,
|
|
204
|
+
];
|
|
205
|
+
if (secure) {
|
|
206
|
+
parts.push("Secure");
|
|
207
|
+
}
|
|
208
|
+
return parts.join("; ");
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function escapeHtml(value: string): string {
|
|
212
|
+
return value
|
|
213
|
+
.replace(/&/g, "&")
|
|
214
|
+
.replace(/</g, "<")
|
|
215
|
+
.replace(/>/g, ">")
|
|
216
|
+
.replace(/"/g, """)
|
|
217
|
+
.replace(/'/g, "'");
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function toSafeUser(user: typeof schema.users.$inferSelect): CurrentUser {
|
|
221
|
+
return {
|
|
222
|
+
id: user.id,
|
|
223
|
+
name: user.name,
|
|
224
|
+
email: user.email,
|
|
225
|
+
role: user.role,
|
|
226
|
+
avatar_url: user.avatar_url,
|
|
227
|
+
status: user.status,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function renderAuthShell(options: {
|
|
232
|
+
pageTitle: string;
|
|
233
|
+
siteTitle: string;
|
|
234
|
+
subtitle: string;
|
|
235
|
+
icon: string;
|
|
236
|
+
badge?: string;
|
|
237
|
+
cardHtml: string;
|
|
238
|
+
}): string {
|
|
239
|
+
const safePageTitle = escapeHtml(options.pageTitle);
|
|
240
|
+
const safeSiteTitle = escapeHtml(options.siteTitle);
|
|
241
|
+
const safeSubtitle = escapeHtml(options.subtitle);
|
|
242
|
+
|
|
243
|
+
return `<!DOCTYPE html>
|
|
244
|
+
<html lang="en">
|
|
245
|
+
<head>
|
|
246
|
+
<meta charset="UTF-8">
|
|
247
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
248
|
+
<title>${safePageTitle} — ${safeSiteTitle}</title>
|
|
249
|
+
<script src="https://cdn.tailwindcss.com"></script>
|
|
250
|
+
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js"></script>
|
|
251
|
+
<script src="https://unpkg.com/lucide@latest"></script>
|
|
252
|
+
<style>[x-cloak]{display:none!important;}</style>
|
|
253
|
+
</head>
|
|
254
|
+
<body class="min-h-screen bg-slate-950 flex items-center justify-center p-4 antialiased">
|
|
255
|
+
<div class="w-full max-w-md bg-white rounded-2xl shadow-2xl border border-slate-200 p-8 space-y-6">
|
|
256
|
+
<div class="text-center space-y-2">
|
|
257
|
+
<div class="w-12 h-12 rounded-xl bg-slate-900 text-white mx-auto flex items-center justify-center">
|
|
258
|
+
<i data-lucide="${escapeHtml(options.icon)}" class="w-6 h-6"></i>
|
|
259
|
+
</div>
|
|
260
|
+
${
|
|
261
|
+
options.badge
|
|
262
|
+
? `<span class="inline-flex px-2.5 py-0.5 rounded-full text-[11px] font-semibold uppercase tracking-wide bg-blue-50 text-blue-700 border border-blue-200">${escapeHtml(options.badge)}</span>`
|
|
263
|
+
: ""
|
|
264
|
+
}
|
|
265
|
+
<h1 class="text-xl font-bold text-slate-900">${safeSiteTitle}</h1>
|
|
266
|
+
<p class="text-sm text-slate-500">${safeSubtitle}</p>
|
|
267
|
+
</div>
|
|
268
|
+
|
|
269
|
+
${options.cardHtml}
|
|
270
|
+
|
|
271
|
+
<div class="pt-2 border-t border-slate-100 text-center">
|
|
272
|
+
<a href="/" class="text-xs font-medium text-slate-500 hover:text-slate-900">← Back to live site</a>
|
|
273
|
+
</div>
|
|
274
|
+
</div>
|
|
275
|
+
<script>document.addEventListener("DOMContentLoaded", () => window.lucide?.createIcons());</script>
|
|
276
|
+
</body>
|
|
277
|
+
</html>`;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function renderAdminSetupHtml(siteTitle: string): string {
|
|
281
|
+
return renderAuthShell({
|
|
282
|
+
pageTitle: "Create Admin Account",
|
|
283
|
+
siteTitle,
|
|
284
|
+
subtitle: "No administrator account exists yet. Create your first admin account to get started.",
|
|
285
|
+
icon: "user-cog",
|
|
286
|
+
badge: "Initial Setup",
|
|
287
|
+
cardHtml: `
|
|
288
|
+
<div
|
|
289
|
+
x-data="{
|
|
290
|
+
name: '',
|
|
291
|
+
email: '',
|
|
292
|
+
password: '',
|
|
293
|
+
confirmPassword: '',
|
|
294
|
+
loading: false,
|
|
295
|
+
error: '',
|
|
296
|
+
async submit() {
|
|
297
|
+
this.error = '';
|
|
298
|
+
if (this.password.length < 6) {
|
|
299
|
+
this.error = 'Password must be at least 6 characters.';
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (this.password !== this.confirmPassword) {
|
|
303
|
+
this.error = 'Passwords do not match.';
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
this.loading = true;
|
|
307
|
+
try {
|
|
308
|
+
const res = await fetch('/api/auth/setup-admin', {
|
|
309
|
+
method: 'POST',
|
|
310
|
+
headers: { 'content-type': 'application/json' },
|
|
311
|
+
body: JSON.stringify({ name: this.name, email: this.email, password: this.password })
|
|
312
|
+
});
|
|
313
|
+
const data = await res.json();
|
|
314
|
+
if (!res.ok || !data.success) {
|
|
315
|
+
this.error = (data.errors && data.errors[0]) || data.error || 'Failed to create admin account.';
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
window.location.href = '/admin';
|
|
319
|
+
} catch {
|
|
320
|
+
this.error = 'Network error while creating admin account.';
|
|
321
|
+
} finally {
|
|
322
|
+
this.loading = false;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}"
|
|
326
|
+
class="space-y-4"
|
|
327
|
+
>
|
|
328
|
+
<div x-show="error" x-cloak class="rounded-lg bg-red-50 border border-red-200 px-3.5 py-2.5 text-xs text-red-700" x-text="error"></div>
|
|
329
|
+
|
|
330
|
+
<form @submit.prevent="submit()" class="space-y-4">
|
|
331
|
+
<div>
|
|
332
|
+
<label for="setup-name" class="block text-xs font-semibold text-slate-700 mb-1">Admin Name</label>
|
|
333
|
+
<input id="setup-name" type="text" required autocomplete="name" x-model="name" placeholder="Site Administrator" class="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
|
|
334
|
+
</div>
|
|
335
|
+
<div>
|
|
336
|
+
<label for="setup-email" class="block text-xs font-semibold text-slate-700 mb-1">Admin Email</label>
|
|
337
|
+
<input id="setup-email" type="email" required autocomplete="email" x-model="email" placeholder="admin@example.com" class="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
|
|
338
|
+
</div>
|
|
339
|
+
<div>
|
|
340
|
+
<label for="setup-password" class="block text-xs font-semibold text-slate-700 mb-1">Password (min 6 characters)</label>
|
|
341
|
+
<input id="setup-password" type="password" required minlength="6" autocomplete="new-password" x-model="password" placeholder="••••••••" class="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
|
|
342
|
+
</div>
|
|
343
|
+
<div>
|
|
344
|
+
<label for="setup-confirm" class="block text-xs font-semibold text-slate-700 mb-1">Confirm Password</label>
|
|
345
|
+
<input id="setup-confirm" type="password" required minlength="6" autocomplete="new-password" x-model="confirmPassword" placeholder="••••••••" class="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
|
|
346
|
+
</div>
|
|
347
|
+
|
|
348
|
+
<button type="submit" :disabled="loading" class="w-full py-2.5 px-4 rounded-lg bg-blue-600 text-white text-sm font-semibold hover:bg-blue-700 disabled:opacity-50 transition" x-text="loading ? 'Creating Admin...' : 'Create Admin Account'"></button>
|
|
349
|
+
</form>
|
|
350
|
+
</div>
|
|
351
|
+
`,
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function renderLoginHtml(siteTitle: string): string {
|
|
356
|
+
return renderAuthShell({
|
|
357
|
+
pageTitle: "Sign In",
|
|
358
|
+
siteTitle,
|
|
359
|
+
subtitle: "Sign in to your account",
|
|
360
|
+
icon: "shield-check",
|
|
361
|
+
cardHtml: `
|
|
362
|
+
<div
|
|
363
|
+
x-data="{
|
|
364
|
+
email: '',
|
|
365
|
+
password: '',
|
|
366
|
+
loading: false,
|
|
367
|
+
error: '',
|
|
368
|
+
async submit() {
|
|
369
|
+
this.loading = true;
|
|
370
|
+
this.error = '';
|
|
371
|
+
try {
|
|
372
|
+
const res = await fetch('/api/auth/login', {
|
|
373
|
+
method: 'POST',
|
|
374
|
+
headers: { 'content-type': 'application/json' },
|
|
375
|
+
body: JSON.stringify({ email: this.email, password: this.password })
|
|
376
|
+
});
|
|
377
|
+
const data = await res.json();
|
|
378
|
+
if (!res.ok || !data.success) {
|
|
379
|
+
this.error = (data.errors && data.errors[0]) || data.error || 'Invalid credentials.';
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
window.location.href = '/admin';
|
|
383
|
+
} catch {
|
|
384
|
+
this.error = 'Network error while signing in.';
|
|
385
|
+
} finally {
|
|
386
|
+
this.loading = false;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}"
|
|
390
|
+
class="space-y-4"
|
|
391
|
+
>
|
|
392
|
+
<div x-show="error" x-cloak class="rounded-lg bg-red-50 border border-red-200 px-3.5 py-2.5 text-xs text-red-700" x-text="error"></div>
|
|
393
|
+
|
|
394
|
+
<form @submit.prevent="submit()" class="space-y-4">
|
|
395
|
+
<div>
|
|
396
|
+
<label for="login-email" class="block text-xs font-semibold text-slate-700 mb-1">Email</label>
|
|
397
|
+
<input id="login-email" type="email" required autocomplete="email" x-model="email" placeholder="you@example.com" class="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
|
|
398
|
+
</div>
|
|
399
|
+
|
|
400
|
+
<div>
|
|
401
|
+
<label for="login-password" class="block text-xs font-semibold text-slate-700 mb-1">Password</label>
|
|
402
|
+
<input id="login-password" type="password" required autocomplete="current-password" x-model="password" placeholder="••••••••" class="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
|
|
403
|
+
</div>
|
|
404
|
+
|
|
405
|
+
<button type="submit" :disabled="loading" class="w-full py-2.5 px-4 rounded-lg bg-slate-900 text-white text-sm font-semibold hover:bg-slate-800 disabled:opacity-50 transition" x-text="loading ? 'Signing in...' : 'Sign In'"></button>
|
|
406
|
+
</form>
|
|
407
|
+
|
|
408
|
+
<p class="text-center text-xs text-slate-500">
|
|
409
|
+
Don't have an account?
|
|
410
|
+
<a href="/register" class="font-semibold text-blue-600 hover:underline">Register</a>
|
|
411
|
+
</p>
|
|
412
|
+
</div>
|
|
413
|
+
`,
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function renderRegisterHtml(siteTitle: string): string {
|
|
418
|
+
return renderAuthShell({
|
|
419
|
+
pageTitle: "Create Account",
|
|
420
|
+
siteTitle,
|
|
421
|
+
subtitle: "Register a new author account",
|
|
422
|
+
icon: "user-plus",
|
|
423
|
+
cardHtml: `
|
|
424
|
+
<div
|
|
425
|
+
x-data="{
|
|
426
|
+
name: '',
|
|
427
|
+
email: '',
|
|
428
|
+
password: '',
|
|
429
|
+
confirmPassword: '',
|
|
430
|
+
loading: false,
|
|
431
|
+
error: '',
|
|
432
|
+
async submit() {
|
|
433
|
+
this.error = '';
|
|
434
|
+
if (this.password.length < 6) {
|
|
435
|
+
this.error = 'Password must be at least 6 characters.';
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
if (this.password !== this.confirmPassword) {
|
|
439
|
+
this.error = 'Passwords do not match.';
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
this.loading = true;
|
|
443
|
+
try {
|
|
444
|
+
const res = await fetch('/api/auth/register', {
|
|
445
|
+
method: 'POST',
|
|
446
|
+
headers: { 'content-type': 'application/json' },
|
|
447
|
+
body: JSON.stringify({ name: this.name, email: this.email, password: this.password })
|
|
448
|
+
});
|
|
449
|
+
const data = await res.json();
|
|
450
|
+
if (!res.ok || !data.success) {
|
|
451
|
+
this.error = (data.errors && data.errors[0]) || data.error || 'Registration failed.';
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
window.location.href = '/admin';
|
|
455
|
+
} catch {
|
|
456
|
+
this.error = 'Network error while creating account.';
|
|
457
|
+
} finally {
|
|
458
|
+
this.loading = false;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
}"
|
|
462
|
+
class="space-y-4"
|
|
463
|
+
>
|
|
464
|
+
<div x-show="error" x-cloak class="rounded-lg bg-red-50 border border-red-200 px-3.5 py-2.5 text-xs text-red-700" x-text="error"></div>
|
|
465
|
+
|
|
466
|
+
<form @submit.prevent="submit()" class="space-y-4">
|
|
467
|
+
<div>
|
|
468
|
+
<label for="reg-name" class="block text-xs font-semibold text-slate-700 mb-1">Full Name</label>
|
|
469
|
+
<input id="reg-name" type="text" required autocomplete="name" x-model="name" placeholder="Jane Doe" class="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
|
|
470
|
+
</div>
|
|
471
|
+
<div>
|
|
472
|
+
<label for="reg-email" class="block text-xs font-semibold text-slate-700 mb-1">Email</label>
|
|
473
|
+
<input id="reg-email" type="email" required autocomplete="email" x-model="email" placeholder="jane@example.com" class="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
|
|
474
|
+
</div>
|
|
475
|
+
<div>
|
|
476
|
+
<label for="reg-password" class="block text-xs font-semibold text-slate-700 mb-1">Password (min 6 characters)</label>
|
|
477
|
+
<input id="reg-password" type="password" required minlength="6" autocomplete="new-password" x-model="password" placeholder="••••••••" class="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
|
|
478
|
+
</div>
|
|
479
|
+
<div>
|
|
480
|
+
<label for="reg-confirm" class="block text-xs font-semibold text-slate-700 mb-1">Confirm Password</label>
|
|
481
|
+
<input id="reg-confirm" type="password" required minlength="6" autocomplete="new-password" x-model="confirmPassword" placeholder="••••••••" class="w-full rounded-lg border border-slate-300 px-3.5 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
|
|
482
|
+
</div>
|
|
483
|
+
|
|
484
|
+
<button type="submit" :disabled="loading" class="w-full py-2.5 px-4 rounded-lg bg-slate-900 text-white text-sm font-semibold hover:bg-slate-800 disabled:opacity-50 transition" x-text="loading ? 'Creating account...' : 'Create Account'"></button>
|
|
485
|
+
</form>
|
|
486
|
+
|
|
487
|
+
<p class="text-center text-xs text-slate-500">
|
|
488
|
+
Already have an account?
|
|
489
|
+
<a href="/login" class="font-semibold text-blue-600 hover:underline">Sign In</a>
|
|
490
|
+
</p>
|
|
491
|
+
</div>
|
|
492
|
+
`,
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function redirect(location: string): Response {
|
|
497
|
+
return new Response(null, { status: 302, headers: { location } });
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function handleSetupPageRequest(request: Request): Response {
|
|
501
|
+
if (hasAdminAccount()) {
|
|
502
|
+
const current = resolveCurrentUser(request);
|
|
503
|
+
return redirect(current ? "/admin" : "/admin/login");
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
const site = getSiteSettings();
|
|
507
|
+
return new Response(renderAdminSetupHtml(site.site_title), {
|
|
508
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function handleLoginPageRequest(request: Request): Response {
|
|
513
|
+
if (!hasAdminAccount()) {
|
|
514
|
+
return redirect("/admin/setup");
|
|
515
|
+
}
|
|
516
|
+
if (resolveCurrentUser(request)) {
|
|
517
|
+
return redirect("/admin");
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const site = getSiteSettings();
|
|
521
|
+
return new Response(renderLoginHtml(site.site_title), {
|
|
522
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function handleRegisterPageRequest(request: Request): Response {
|
|
527
|
+
if (!hasAdminAccount()) {
|
|
528
|
+
return redirect("/admin/setup");
|
|
529
|
+
}
|
|
530
|
+
if (resolveCurrentUser(request)) {
|
|
531
|
+
return redirect("/admin");
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const site = getSiteSettings();
|
|
535
|
+
return new Response(renderRegisterHtml(site.site_title), {
|
|
536
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Auth UI & API routes (/admin/setup, /setup, /login, /admin/login, /register, /api/auth/*).
|
|
542
|
+
*/
|
|
543
|
+
export const authRoutes = new Elysia()
|
|
544
|
+
.get("/admin/setup", ({ request }) => handleSetupPageRequest(request))
|
|
545
|
+
.get("/setup", ({ request }) => handleSetupPageRequest(request))
|
|
546
|
+
.get("/admin/login", ({ request }) => handleLoginPageRequest(request))
|
|
547
|
+
.get("/login", ({ request }) => handleLoginPageRequest(request))
|
|
548
|
+
.get("/register", ({ request }) => handleRegisterPageRequest(request))
|
|
549
|
+
.post(
|
|
550
|
+
"/api/auth/setup-admin",
|
|
551
|
+
async ({ body, request, set }) => {
|
|
552
|
+
if (hasAdminAccount()) {
|
|
553
|
+
set.status = 403;
|
|
554
|
+
return {
|
|
555
|
+
success: false,
|
|
556
|
+
errors: ["An admin account already exists. Setup is disabled."],
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
const name = body.name.trim();
|
|
561
|
+
const email = body.email.trim().toLowerCase();
|
|
562
|
+
if (!name) {
|
|
563
|
+
set.status = 400;
|
|
564
|
+
return { success: false, errors: ["Name is required."] };
|
|
565
|
+
}
|
|
566
|
+
if (!EMAIL_REGEX.test(email)) {
|
|
567
|
+
set.status = 400;
|
|
568
|
+
return { success: false, errors: ["Valid email address is required."] };
|
|
569
|
+
}
|
|
570
|
+
if (body.password.length < 6) {
|
|
571
|
+
set.status = 400;
|
|
572
|
+
return { success: false, errors: ["Password must be at least 6 characters."] };
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const passwordHash = await Bun.password.hash(body.password);
|
|
576
|
+
|
|
577
|
+
const outcome = db.transaction(
|
|
578
|
+
(
|
|
579
|
+
tx,
|
|
580
|
+
):
|
|
581
|
+
| { ok: true; user: typeof schema.users.$inferSelect }
|
|
582
|
+
| { ok: false; status: 403 | 409; error: string } => {
|
|
583
|
+
const existingAdmin = tx
|
|
584
|
+
.select({ id: schema.users.id })
|
|
585
|
+
.from(schema.users)
|
|
586
|
+
.where(eq(schema.users.role, "admin"))
|
|
587
|
+
.limit(1)
|
|
588
|
+
.get();
|
|
589
|
+
|
|
590
|
+
if (existingAdmin) {
|
|
591
|
+
return {
|
|
592
|
+
ok: false,
|
|
593
|
+
status: 403,
|
|
594
|
+
error: "An admin account already exists. Setup is disabled.",
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const duplicateEmail = tx
|
|
599
|
+
.select({ id: schema.users.id })
|
|
600
|
+
.from(schema.users)
|
|
601
|
+
.where(eq(schema.users.email, email))
|
|
602
|
+
.get();
|
|
603
|
+
|
|
604
|
+
if (duplicateEmail) {
|
|
605
|
+
return {
|
|
606
|
+
ok: false,
|
|
607
|
+
status: 409,
|
|
608
|
+
error: `A user with email "${email}" already exists.`,
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const created = tx
|
|
613
|
+
.insert(schema.users)
|
|
614
|
+
.values({
|
|
615
|
+
name,
|
|
616
|
+
email,
|
|
617
|
+
password_hash: passwordHash,
|
|
618
|
+
role: "admin",
|
|
619
|
+
avatar_url: "",
|
|
620
|
+
status: "active",
|
|
621
|
+
})
|
|
622
|
+
.returning()
|
|
623
|
+
.get();
|
|
624
|
+
|
|
625
|
+
return { ok: true, user: created };
|
|
626
|
+
},
|
|
627
|
+
);
|
|
628
|
+
|
|
629
|
+
if (!outcome.ok) {
|
|
630
|
+
set.status = outcome.status;
|
|
631
|
+
return { success: false, errors: [outcome.error] };
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
const token = signSessionToken(outcome.user.id);
|
|
635
|
+
set.headers["set-cookie"] = buildCookieHeader(
|
|
636
|
+
token,
|
|
637
|
+
SESSION_TTL_SECONDS,
|
|
638
|
+
isSecureRequest(request),
|
|
639
|
+
);
|
|
640
|
+
set.status = 201;
|
|
641
|
+
|
|
642
|
+
return {
|
|
643
|
+
success: true,
|
|
644
|
+
user: toSafeUser(outcome.user),
|
|
645
|
+
};
|
|
646
|
+
},
|
|
647
|
+
{
|
|
648
|
+
body: t.Object({
|
|
649
|
+
name: t.String({ minLength: 1 }),
|
|
650
|
+
email: t.String({ minLength: 3 }),
|
|
651
|
+
password: t.String({ minLength: 6 }),
|
|
652
|
+
}),
|
|
653
|
+
},
|
|
654
|
+
)
|
|
655
|
+
.post(
|
|
656
|
+
"/api/auth/register",
|
|
657
|
+
async ({ body, request, set }) => {
|
|
658
|
+
if (!hasAdminAccount()) {
|
|
659
|
+
set.status = 400;
|
|
660
|
+
return {
|
|
661
|
+
success: false,
|
|
662
|
+
errors: ["Please create the initial admin account at /admin/setup first."],
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const name = body.name.trim();
|
|
667
|
+
const email = body.email.trim().toLowerCase();
|
|
668
|
+
if (!name) {
|
|
669
|
+
set.status = 400;
|
|
670
|
+
return { success: false, errors: ["Name is required."] };
|
|
671
|
+
}
|
|
672
|
+
if (!EMAIL_REGEX.test(email)) {
|
|
673
|
+
set.status = 400;
|
|
674
|
+
return { success: false, errors: ["Valid email address is required."] };
|
|
675
|
+
}
|
|
676
|
+
if (body.password.length < 6) {
|
|
677
|
+
set.status = 400;
|
|
678
|
+
return { success: false, errors: ["Password must be at least 6 characters."] };
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
const duplicate = db
|
|
682
|
+
.select({ id: schema.users.id })
|
|
683
|
+
.from(schema.users)
|
|
684
|
+
.where(eq(schema.users.email, email))
|
|
685
|
+
.get();
|
|
686
|
+
if (duplicate) {
|
|
687
|
+
set.status = 409;
|
|
688
|
+
return { success: false, errors: ["An account with this email already exists."] };
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
const passwordHash = await Bun.password.hash(body.password);
|
|
692
|
+
const created = db
|
|
693
|
+
.insert(schema.users)
|
|
694
|
+
.values({
|
|
695
|
+
name,
|
|
696
|
+
email,
|
|
697
|
+
password_hash: passwordHash,
|
|
698
|
+
role: "author",
|
|
699
|
+
avatar_url: "",
|
|
700
|
+
status: "active",
|
|
701
|
+
})
|
|
702
|
+
.returning()
|
|
703
|
+
.get();
|
|
704
|
+
|
|
705
|
+
const token = signSessionToken(created.id);
|
|
706
|
+
set.headers["set-cookie"] = buildCookieHeader(
|
|
707
|
+
token,
|
|
708
|
+
SESSION_TTL_SECONDS,
|
|
709
|
+
isSecureRequest(request),
|
|
710
|
+
);
|
|
711
|
+
set.status = 201;
|
|
712
|
+
|
|
713
|
+
return {
|
|
714
|
+
success: true,
|
|
715
|
+
user: toSafeUser(created),
|
|
716
|
+
};
|
|
717
|
+
},
|
|
718
|
+
{
|
|
719
|
+
body: t.Object({
|
|
720
|
+
name: t.String({ minLength: 1 }),
|
|
721
|
+
email: t.String({ minLength: 3 }),
|
|
722
|
+
password: t.String({ minLength: 6 }),
|
|
723
|
+
}),
|
|
724
|
+
},
|
|
725
|
+
)
|
|
726
|
+
.post(
|
|
727
|
+
"/api/auth/login",
|
|
728
|
+
async ({ body, request, set }) => {
|
|
729
|
+
const email = body.email.trim().toLowerCase();
|
|
730
|
+
const user = db
|
|
731
|
+
.select()
|
|
732
|
+
.from(schema.users)
|
|
733
|
+
.where(eq(schema.users.email, email))
|
|
734
|
+
.get();
|
|
735
|
+
|
|
736
|
+
if (!user) {
|
|
737
|
+
set.status = 401;
|
|
738
|
+
return { success: false, errors: ["Invalid email or password."] };
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
const validPassword = await Bun.password.verify(body.password, user.password_hash);
|
|
742
|
+
if (!validPassword) {
|
|
743
|
+
set.status = 401;
|
|
744
|
+
return { success: false, errors: ["Invalid email or password."] };
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
if (user.status !== "active") {
|
|
748
|
+
set.status = 403;
|
|
749
|
+
return { success: false, errors: ["Account is suspended."] };
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
const token = signSessionToken(user.id);
|
|
753
|
+
set.headers["set-cookie"] = buildCookieHeader(
|
|
754
|
+
token,
|
|
755
|
+
SESSION_TTL_SECONDS,
|
|
756
|
+
isSecureRequest(request),
|
|
757
|
+
);
|
|
758
|
+
|
|
759
|
+
return {
|
|
760
|
+
success: true,
|
|
761
|
+
user: toSafeUser(user),
|
|
762
|
+
};
|
|
763
|
+
},
|
|
764
|
+
{
|
|
765
|
+
body: t.Object({
|
|
766
|
+
email: t.String({ minLength: 3 }),
|
|
767
|
+
password: t.String({ minLength: 1 }),
|
|
768
|
+
}),
|
|
769
|
+
},
|
|
770
|
+
)
|
|
771
|
+
.post("/api/auth/logout", ({ request, set }) => {
|
|
772
|
+
set.headers["set-cookie"] = buildCookieHeader("", 0, isSecureRequest(request));
|
|
773
|
+
return { success: true };
|
|
774
|
+
})
|
|
775
|
+
.get("/api/auth/me", ({ request }) => {
|
|
776
|
+
const user = resolveCurrentUser(request);
|
|
777
|
+
return {
|
|
778
|
+
authenticated: Boolean(user),
|
|
779
|
+
hasAdmin: hasAdminAccount(),
|
|
780
|
+
user,
|
|
781
|
+
};
|
|
782
|
+
})
|
|
783
|
+
.post(
|
|
784
|
+
"/api/auth/profile",
|
|
785
|
+
async ({ body, request, set }) => {
|
|
786
|
+
const current = resolveCurrentUser(request);
|
|
787
|
+
if (!current) {
|
|
788
|
+
set.status = 401;
|
|
789
|
+
return { success: false, errors: ["Authentication required."] };
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
const name = body.name.trim();
|
|
793
|
+
if (!name) {
|
|
794
|
+
set.status = 400;
|
|
795
|
+
return { success: false, errors: ["Name cannot be empty."] };
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const existing = db
|
|
799
|
+
.select()
|
|
800
|
+
.from(schema.users)
|
|
801
|
+
.where(eq(schema.users.id, current.id))
|
|
802
|
+
.get();
|
|
803
|
+
if (!existing) {
|
|
804
|
+
set.status = 404;
|
|
805
|
+
return { success: false, errors: ["User not found."] };
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
let passwordHash = existing.password_hash;
|
|
809
|
+
if (body.new_password && body.new_password.length > 0) {
|
|
810
|
+
if (body.new_password.length < 6) {
|
|
811
|
+
set.status = 400;
|
|
812
|
+
return { success: false, errors: ["New password must be at least 6 characters."] };
|
|
813
|
+
}
|
|
814
|
+
if (!body.current_password) {
|
|
815
|
+
set.status = 400;
|
|
816
|
+
return {
|
|
817
|
+
success: false,
|
|
818
|
+
errors: ["Current password is required to set a new password."],
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
const verified = await Bun.password.verify(
|
|
822
|
+
body.current_password,
|
|
823
|
+
existing.password_hash,
|
|
824
|
+
);
|
|
825
|
+
if (!verified) {
|
|
826
|
+
set.status = 400;
|
|
827
|
+
return { success: false, errors: ["Current password is incorrect."] };
|
|
828
|
+
}
|
|
829
|
+
passwordHash = await Bun.password.hash(body.new_password);
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
const updated = db
|
|
833
|
+
.update(schema.users)
|
|
834
|
+
.set({ name, password_hash: passwordHash })
|
|
835
|
+
.where(eq(schema.users.id, current.id))
|
|
836
|
+
.returning()
|
|
837
|
+
.get();
|
|
838
|
+
|
|
839
|
+
return {
|
|
840
|
+
success: true,
|
|
841
|
+
user: toSafeUser(updated),
|
|
842
|
+
};
|
|
843
|
+
},
|
|
844
|
+
{
|
|
845
|
+
body: t.Object({
|
|
846
|
+
name: t.String({ minLength: 1 }),
|
|
847
|
+
current_password: t.Optional(t.String()),
|
|
848
|
+
new_password: t.Optional(t.String()),
|
|
849
|
+
}),
|
|
850
|
+
},
|
|
851
|
+
);
|