@eutobias/serenojs 0.0.0-stage → 0.1.1
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 +682 -2
- package/admin-dist/assets/index-B3EgqtT6.js +9 -0
- package/admin-dist/assets/index-D2m0Eb4k.css +2 -0
- package/admin-dist/index.html +17 -0
- package/dist/auth/auth.server.d.ts +31 -0
- package/dist/auth/auth.server.js +141 -0
- package/dist/auth/config.d.ts +32 -0
- package/dist/auth/config.js +25 -0
- package/dist/auth/cookies.server.d.ts +7 -0
- package/dist/auth/cookies.server.js +65 -0
- package/dist/auth/http.server.d.ts +8 -0
- package/dist/auth/http.server.js +30 -0
- package/dist/auth/password.server.d.ts +2 -0
- package/dist/auth/password.server.js +21 -0
- package/dist/auth/session.server.d.ts +2 -0
- package/dist/auth/session.server.js +14 -0
- package/dist/auth/users.server.d.ts +16 -0
- package/dist/auth/users.server.js +123 -0
- package/dist/config.d.ts +91 -0
- package/dist/config.js +39 -0
- package/dist/core/backup.server.d.ts +52 -0
- package/dist/core/backup.server.js +349 -0
- package/dist/core/db.server.d.ts +24 -0
- package/dist/core/db.server.js +526 -0
- package/dist/core/media.d.ts +22 -0
- package/dist/core/media.js +76 -0
- package/dist/core/media.server.d.ts +18 -0
- package/dist/core/media.server.js +102 -0
- package/dist/core/schema.d.ts +26 -0
- package/dist/core/schema.js +99 -0
- package/dist/core/types.d.ts +143 -0
- package/dist/core/types.js +1 -0
- package/dist/core/validation.d.ts +16 -0
- package/dist/core/validation.js +192 -0
- package/dist/locale.d.ts +2 -0
- package/dist/locale.js +14 -0
- package/dist/runtime.d.ts +8 -0
- package/dist/runtime.js +37 -0
- package/dist/server/app.d.ts +20 -0
- package/dist/server/app.js +661 -0
- package/dist/ui/admin/admin-shell.d.ts +16 -0
- package/dist/ui/admin/admin-shell.js +38 -0
- package/dist/ui/admin/backup-manager.d.ts +5 -0
- package/dist/ui/admin/backup-manager.js +165 -0
- package/dist/ui/admin/collection-icon.d.ts +22 -0
- package/dist/ui/admin/collection-icon.js +34 -0
- package/dist/ui/admin/collection-manager.d.ts +7 -0
- package/dist/ui/admin/collection-manager.js +212 -0
- package/dist/ui/admin/display.d.ts +7 -0
- package/dist/ui/admin/display.js +65 -0
- package/dist/ui/admin/field-control.d.ts +14 -0
- package/dist/ui/admin/field-control.js +58 -0
- package/dist/ui/admin/i18n.d.ts +27 -0
- package/dist/ui/admin/i18n.js +324 -0
- package/dist/ui/admin/item-form.d.ts +20 -0
- package/dist/ui/admin/item-form.js +60 -0
- package/dist/ui/admin/list-control.d.ts +13 -0
- package/dist/ui/admin/list-control.js +31 -0
- package/dist/ui/admin/locales.d.ts +4 -0
- package/dist/ui/admin/locales.js +8 -0
- package/dist/ui/admin/login-form.d.ts +3 -0
- package/dist/ui/admin/login-form.js +52 -0
- package/dist/ui/admin/media-control.d.ts +14 -0
- package/dist/ui/admin/media-control.js +74 -0
- package/dist/ui/admin/media-list-control.d.ts +14 -0
- package/dist/ui/admin/media-list-control.js +91 -0
- package/dist/ui/admin/pagination.d.ts +11 -0
- package/dist/ui/admin/pagination.js +14 -0
- package/dist/ui/admin/relation-control.d.ts +14 -0
- package/dist/ui/admin/relation-control.js +33 -0
- package/dist/ui/admin/router.d.ts +17 -0
- package/dist/ui/admin/router.js +58 -0
- package/dist/ui/admin/runtime.d.ts +28 -0
- package/dist/ui/admin/runtime.js +29 -0
- package/dist/ui/admin/sidebar.d.ts +13 -0
- package/dist/ui/admin/sidebar.js +29 -0
- package/dist/ui/admin/standalone-manager.d.ts +11 -0
- package/dist/ui/admin/standalone-manager.js +51 -0
- package/dist/ui/admin/table.d.ts +21 -0
- package/dist/ui/admin/table.js +23 -0
- package/dist/ui/admin/toast.d.ts +16 -0
- package/dist/ui/admin/toast.js +59 -0
- package/dist/ui/admin/users-manager.d.ts +6 -0
- package/dist/ui/admin/users-manager.js +157 -0
- package/dist/ui/badge.d.ts +9 -0
- package/dist/ui/badge.js +14 -0
- package/dist/ui/box.d.ts +17 -0
- package/dist/ui/box.js +14 -0
- package/dist/ui/button.d.ts +25 -0
- package/dist/ui/button.js +28 -0
- package/dist/ui/card.d.ts +45 -0
- package/dist/ui/card.js +49 -0
- package/dist/ui/container.d.ts +13 -0
- package/dist/ui/container.js +13 -0
- package/dist/ui/drawer.d.ts +15 -0
- package/dist/ui/drawer.js +31 -0
- package/dist/ui/field-wrapper.d.ts +15 -0
- package/dist/ui/field-wrapper.js +11 -0
- package/dist/ui/index.d.ts +8 -0
- package/dist/ui/index.js +8 -0
- package/dist/ui/text.d.ts +19 -0
- package/dist/ui/text.js +40 -0
- package/package.json +81 -3
- package/src/admin/app.tsx +371 -0
- package/src/admin/index.html +16 -0
- package/src/admin/main.tsx +42 -0
- package/src/admin/styles.css +9 -0
- package/src/auth/auth.server.ts +203 -0
- package/src/auth/config.ts +46 -0
- package/src/auth/cookies.server.ts +84 -0
- package/src/auth/http.server.ts +32 -0
- package/src/auth/password.server.ts +25 -0
- package/src/auth/session.server.ts +16 -0
- package/src/auth/users.server.ts +159 -0
- package/src/config.ts +120 -0
- package/src/core/backup.server.ts +446 -0
- package/src/core/db.server.ts +685 -0
- package/src/core/media.server.ts +136 -0
- package/src/core/media.ts +91 -0
- package/src/core/schema.ts +126 -0
- package/src/core/types.ts +194 -0
- package/src/core/validation.ts +215 -0
- package/src/global.d.ts +1 -0
- package/src/locale.ts +16 -0
- package/src/runtime.ts +54 -0
- package/src/server/app.ts +737 -0
- package/src/ui/admin/admin-shell.tsx +106 -0
- package/src/ui/admin/backup-manager.tsx +327 -0
- package/src/ui/admin/collection-icon.tsx +69 -0
- package/src/ui/admin/collection-manager.tsx +408 -0
- package/src/ui/admin/display.tsx +138 -0
- package/src/ui/admin/field-control.tsx +214 -0
- package/src/ui/admin/i18n.tsx +401 -0
- package/src/ui/admin/item-form.tsx +200 -0
- package/src/ui/admin/list-control.tsx +121 -0
- package/src/ui/admin/locales.ts +12 -0
- package/src/ui/admin/login-form.tsx +98 -0
- package/src/ui/admin/media-control.tsx +161 -0
- package/src/ui/admin/media-list-control.tsx +242 -0
- package/src/ui/admin/pagination.tsx +58 -0
- package/src/ui/admin/relation-control.tsx +142 -0
- package/src/ui/admin/router.tsx +105 -0
- package/src/ui/admin/runtime.tsx +58 -0
- package/src/ui/admin/sidebar.tsx +178 -0
- package/src/ui/admin/standalone-manager.tsx +103 -0
- package/src/ui/admin/table.tsx +129 -0
- package/src/ui/admin/toast.tsx +126 -0
- package/src/ui/admin/users-manager.tsx +344 -0
- package/src/ui/badge.tsx +27 -0
- package/src/ui/box.tsx +33 -0
- package/src/ui/button.tsx +77 -0
- package/src/ui/card.tsx +92 -0
- package/src/ui/container.tsx +28 -0
- package/src/ui/drawer.tsx +104 -0
- package/src/ui/field-wrapper.tsx +54 -0
- package/src/ui/index.ts +8 -0
- package/src/ui/text.tsx +93 -0
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The whole server surface of the CMS, mounted as a single Hono middleware.
|
|
3
|
+
*
|
|
4
|
+
* `createCmsMiddleware(config)` returns the factory Waku expects from
|
|
5
|
+
* `src/middleware/*.ts`. Requests that belong to the CMS (admin SPA, REST API,
|
|
6
|
+
* auth, media, uploads and backups) are answered here; everything else falls
|
|
7
|
+
* through to the host's Waku pages.
|
|
8
|
+
*/
|
|
9
|
+
import { readFileSync, statSync } from "node:fs";
|
|
10
|
+
import { extname, join, normalize, resolve } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { createRequire } from "node:module";
|
|
13
|
+
import { dirname } from "node:path";
|
|
14
|
+
|
|
15
|
+
import { Hono, type Context, type MiddlewareHandler } from "hono";
|
|
16
|
+
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
|
17
|
+
|
|
18
|
+
import { getCollection } from "../core/schema.js";
|
|
19
|
+
import { getCmsConfig } from "../runtime.js";
|
|
20
|
+
import type { CmsConfig, CollectionDef } from "../config.js";
|
|
21
|
+
import { configureCms } from "../runtime.js";
|
|
22
|
+
|
|
23
|
+
import {
|
|
24
|
+
checkRelationTargets,
|
|
25
|
+
createItem,
|
|
26
|
+
deleteItem,
|
|
27
|
+
getItem,
|
|
28
|
+
getStandalone,
|
|
29
|
+
listItems,
|
|
30
|
+
saveStandalone,
|
|
31
|
+
updateItem,
|
|
32
|
+
} from "../core/db.server.js";
|
|
33
|
+
import { coerceInput } from "../core/validation.js";
|
|
34
|
+
import { itemLabel } from "../core/schema.js";
|
|
35
|
+
import { contentTypeFor, readUpload } from "../core/media.server.js";
|
|
36
|
+
import { MediaError, deleteByUrl, saveUpload } from "../core/media.server.js";
|
|
37
|
+
import {
|
|
38
|
+
BackupError,
|
|
39
|
+
createBackup,
|
|
40
|
+
createBackupBuffer,
|
|
41
|
+
deleteBackup,
|
|
42
|
+
listBackups,
|
|
43
|
+
readBackup,
|
|
44
|
+
restoreBackup,
|
|
45
|
+
startBackupScheduler,
|
|
46
|
+
} from "../core/backup.server.js";
|
|
47
|
+
|
|
48
|
+
import { createSession, getUserByAccessToken, revokeUserSessions, rotateSession, verifyCredentials } from "../auth/auth.server.js";
|
|
49
|
+
import {
|
|
50
|
+
ACCESS_COOKIE,
|
|
51
|
+
ACCESS_TTL_SECONDS,
|
|
52
|
+
COOKIE_SECURE,
|
|
53
|
+
REFRESH_COOKIE,
|
|
54
|
+
REFRESH_TTL_SECONDS,
|
|
55
|
+
isSafeMethod,
|
|
56
|
+
} from "../auth/config.js";
|
|
57
|
+
import type { AuthUser, UserSummary } from "../auth/config.js";
|
|
58
|
+
import { readBody } from "../auth/http.server.js";
|
|
59
|
+
import { createUser, deleteUser, getUser, listUsers, updateUser } from "../auth/users.server.js";
|
|
60
|
+
|
|
61
|
+
const ADMIN_ASSETS_PREFIX = "/_serenojs/admin";
|
|
62
|
+
/**
|
|
63
|
+
* Locate the package's built admin bundle. In development the CMS source is
|
|
64
|
+
* bundled into the host's `dist/server`, so `import.meta.url` no longer points
|
|
65
|
+
* at the package. Resolve through the host's `node_modules` first and fall
|
|
66
|
+
* back to the source-relative path.
|
|
67
|
+
*/
|
|
68
|
+
function adminDist(): string {
|
|
69
|
+
try {
|
|
70
|
+
const req = createRequire(resolve(process.cwd(), "package.json"));
|
|
71
|
+
return join(dirname(req.resolve("@eutobias/serenojs/package.json")), "admin-dist");
|
|
72
|
+
} catch {
|
|
73
|
+
return fileURLToPath(new URL("../../admin-dist/", import.meta.url));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
type Env = { Variables: { user: AuthUser } };
|
|
78
|
+
|
|
79
|
+
const MIME: Record<string, string> = {
|
|
80
|
+
html: "text/html; charset=utf-8",
|
|
81
|
+
js: "text/javascript; charset=utf-8",
|
|
82
|
+
mjs: "text/javascript; charset=utf-8",
|
|
83
|
+
css: "text/css; charset=utf-8",
|
|
84
|
+
json: "application/json; charset=utf-8",
|
|
85
|
+
map: "application/json; charset=utf-8",
|
|
86
|
+
svg: "image/svg+xml",
|
|
87
|
+
png: "image/png",
|
|
88
|
+
jpg: "image/jpeg",
|
|
89
|
+
jpeg: "image/jpeg",
|
|
90
|
+
gif: "image/gif",
|
|
91
|
+
webp: "image/webp",
|
|
92
|
+
ico: "image/x-icon",
|
|
93
|
+
woff: "font/woff",
|
|
94
|
+
woff2: "font/woff2",
|
|
95
|
+
txt: "text/plain; charset=utf-8",
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
function mimeFor(path: string): string {
|
|
99
|
+
return MIME[extname(path).slice(1).toLowerCase()] ?? "application/octet-stream";
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function isUnsafe(req: { method: string; header: (name: string) => string | undefined }): boolean {
|
|
103
|
+
return !isSafeMethod(req.method);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function methodKey(method: string): "read" | "create" | "update" | "delete" {
|
|
107
|
+
const m = method.toUpperCase();
|
|
108
|
+
if (m === "POST") return "create";
|
|
109
|
+
if (m === "PATCH" || m === "PUT") return "update";
|
|
110
|
+
if (m === "DELETE") return "delete";
|
|
111
|
+
return "read";
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const ACCESS_DEFAULTS: Record<"read" | "create" | "update" | "delete", "public" | "private"> = {
|
|
115
|
+
read: "public",
|
|
116
|
+
create: "private",
|
|
117
|
+
update: "private",
|
|
118
|
+
delete: "private",
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
function accessFor(collection: CollectionDef | undefined, method: string): "public" | "private" {
|
|
122
|
+
const key = methodKey(method);
|
|
123
|
+
return (collection?.access?.[key] ?? ACCESS_DEFAULTS[key]) === "public"
|
|
124
|
+
? "public"
|
|
125
|
+
: "private";
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function jsonError(message: string, status: number): Response {
|
|
129
|
+
return Response.json({ message }, { status });
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/* -------------------------------------------------------------------------- */
|
|
133
|
+
/* Auth helpers */
|
|
134
|
+
/* -------------------------------------------------------------------------- */
|
|
135
|
+
|
|
136
|
+
function setAuthCookies(c: Context<Env>, tokens: { accessToken: string; refreshToken: string }): void {
|
|
137
|
+
setCookie(c, ACCESS_COOKIE, tokens.accessToken, {
|
|
138
|
+
httpOnly: true,
|
|
139
|
+
path: "/",
|
|
140
|
+
sameSite: "Lax",
|
|
141
|
+
secure: COOKIE_SECURE,
|
|
142
|
+
maxAge: ACCESS_TTL_SECONDS,
|
|
143
|
+
});
|
|
144
|
+
setCookie(c, REFRESH_COOKIE, tokens.refreshToken, {
|
|
145
|
+
httpOnly: true,
|
|
146
|
+
path: "/",
|
|
147
|
+
sameSite: "Lax",
|
|
148
|
+
secure: COOKIE_SECURE,
|
|
149
|
+
maxAge: REFRESH_TTL_SECONDS,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function clearAuthCookies(c: Context<Env>): void {
|
|
154
|
+
deleteCookie(c, ACCESS_COOKIE, { path: "/" });
|
|
155
|
+
deleteCookie(c, REFRESH_COOKIE, { path: "/" });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function currentUser(c: Context<Env>): AuthUser | null {
|
|
159
|
+
const token = getCookie(c, ACCESS_COOKIE);
|
|
160
|
+
return token ? getUserByAccessToken(token) : null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Require a valid access token, transparently rotating a valid refresh. */
|
|
164
|
+
const requireAuth: MiddlewareHandler<Env> = async (c, next) => {
|
|
165
|
+
if (isUnsafe(c.req) && isCrossOrigin(c)) {
|
|
166
|
+
return jsonError("Origem não permitida.", 403);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const user = currentUser(c);
|
|
170
|
+
if (user) {
|
|
171
|
+
c.set("user", user);
|
|
172
|
+
return next();
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const refresh = getCookie(c, REFRESH_COOKIE);
|
|
176
|
+
const rotated = refresh ? rotateSession(refresh) : null;
|
|
177
|
+
if (rotated) {
|
|
178
|
+
setAuthCookies(c, rotated.tokens);
|
|
179
|
+
c.set("user", rotated.user);
|
|
180
|
+
return next();
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return jsonError("Não autenticado.", 401);
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
function isCrossOrigin(c: Context<Env>): boolean {
|
|
187
|
+
const origin = c.req.header("origin");
|
|
188
|
+
if (!origin) return false;
|
|
189
|
+
const host = c.req.header("host");
|
|
190
|
+
if (!host) return true;
|
|
191
|
+
try {
|
|
192
|
+
return new URL(origin).host !== host;
|
|
193
|
+
} catch {
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/* -------------------------------------------------------------------------- */
|
|
199
|
+
/* REST API */
|
|
200
|
+
/* -------------------------------------------------------------------------- */
|
|
201
|
+
|
|
202
|
+
function collectionName(c: Context<Env>): string {
|
|
203
|
+
const param = c.req.param("collection");
|
|
204
|
+
if (param) return String(param);
|
|
205
|
+
// Middleware (`use`) does not always expose route params; derive the slug
|
|
206
|
+
// from the mounted path instead.
|
|
207
|
+
const base = getCmsConfig().api.path;
|
|
208
|
+
const rest = c.req.path.startsWith(`${base}/`)
|
|
209
|
+
? c.req.path.slice(base.length + 1)
|
|
210
|
+
: c.req.path;
|
|
211
|
+
return rest.split("/")[0] ?? "";
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const cms = new Hono<Env>();
|
|
215
|
+
|
|
216
|
+
// Gate every API request using the collection's access descriptor.
|
|
217
|
+
cms.use("*", async (c, next) => {
|
|
218
|
+
const collection = getCollection(collectionName(c));
|
|
219
|
+
if (accessFor(collection, c.req.method) === "private") {
|
|
220
|
+
return requireAuth(c, next);
|
|
221
|
+
}
|
|
222
|
+
if (isUnsafe(c.req) && isCrossOrigin(c)) {
|
|
223
|
+
return jsonError("Origem não permitida.", 403);
|
|
224
|
+
}
|
|
225
|
+
return next();
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
cms.get("/:collection/relations", requireAuth, (c) => {
|
|
229
|
+
const collection = getCollection(collectionName(c));
|
|
230
|
+
if (!collection) return jsonError("Coleção não encontrada.", 404);
|
|
231
|
+
|
|
232
|
+
const options: Record<string, { id: number; label: string }[]> = {};
|
|
233
|
+
for (const field of collection.fields) {
|
|
234
|
+
if (field.type !== "relation" || !field.relation) continue;
|
|
235
|
+
const target = getCollection(field.relation.to);
|
|
236
|
+
options[field.name] = target
|
|
237
|
+
? listItems(target, { limit: 100 }).items.map((item) => ({
|
|
238
|
+
id: item.id,
|
|
239
|
+
label: itemLabel(target, item),
|
|
240
|
+
}))
|
|
241
|
+
: [];
|
|
242
|
+
}
|
|
243
|
+
return c.json({ options });
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
cms.get("/:collection", (c) => {
|
|
247
|
+
const collection = getCollection(collectionName(c));
|
|
248
|
+
if (!collection) return jsonError("Coleção não encontrada.", 404);
|
|
249
|
+
|
|
250
|
+
if (collection.standalone) {
|
|
251
|
+
return c.json({ item: getStandalone(collection) });
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const url = new URL(c.req.url);
|
|
255
|
+
const page = Number(url.searchParams.get("page") ?? "1") || 1;
|
|
256
|
+
const limit = Number(url.searchParams.get("limit") ?? "10") || 10;
|
|
257
|
+
const q = url.searchParams.get("q") ?? "";
|
|
258
|
+
return c.json(listItems(collection, { page, limit, q }));
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
cms.post("/:collection", async (c) => {
|
|
262
|
+
const collection = getCollection(collectionName(c));
|
|
263
|
+
if (!collection) return jsonError("Coleção não encontrada.", 404);
|
|
264
|
+
if (collection.standalone) {
|
|
265
|
+
return jsonError(
|
|
266
|
+
"Coleção standalone possui um único registro; use PATCH para atualizá-lo.",
|
|
267
|
+
405,
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
let body: unknown;
|
|
272
|
+
try {
|
|
273
|
+
body = await c.req.json();
|
|
274
|
+
} catch {
|
|
275
|
+
return jsonError("JSON inválido.", 400);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const result = coerceInput(collection, body, { partial: false });
|
|
279
|
+
if (!result.ok) {
|
|
280
|
+
return Response.json({ message: "Dados inválidos.", errors: result.errors }, { status: 422 });
|
|
281
|
+
}
|
|
282
|
+
const relationErrors = checkRelationTargets(collection, result.values);
|
|
283
|
+
if (Object.keys(relationErrors).length > 0) {
|
|
284
|
+
return Response.json({ message: "Dados inválidos.", errors: relationErrors }, { status: 422 });
|
|
285
|
+
}
|
|
286
|
+
return Response.json({ item: createItem(collection, result.values) }, { status: 201 });
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
cms.patch("/:collection", async (c) => {
|
|
290
|
+
const collection = getCollection(collectionName(c));
|
|
291
|
+
if (!collection) return jsonError("Coleção não encontrada.", 404);
|
|
292
|
+
if (!collection.standalone) {
|
|
293
|
+
return jsonError(
|
|
294
|
+
`Use PATCH ${getCmsConfig().api.path}/:collection/:id para atualizar itens desta coleção.`,
|
|
295
|
+
405,
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
let body: unknown;
|
|
300
|
+
try {
|
|
301
|
+
body = await c.req.json();
|
|
302
|
+
} catch {
|
|
303
|
+
return jsonError("JSON inválido.", 400);
|
|
304
|
+
}
|
|
305
|
+
const result = coerceInput(collection, body, { partial: true });
|
|
306
|
+
if (!result.ok) {
|
|
307
|
+
return Response.json({ message: "Dados inválidos.", errors: result.errors }, { status: 422 });
|
|
308
|
+
}
|
|
309
|
+
const relationErrors = checkRelationTargets(collection, result.values);
|
|
310
|
+
if (Object.keys(relationErrors).length > 0) {
|
|
311
|
+
return Response.json({ message: "Dados inválidos.", errors: relationErrors }, { status: 422 });
|
|
312
|
+
}
|
|
313
|
+
return c.json({ item: saveStandalone(collection, result.values) });
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
function cmsItem(c: Context<Env>): { collection: CollectionDef; id: number } | Response {
|
|
317
|
+
const collection = getCollection(collectionName(c));
|
|
318
|
+
const id = Number(c.req.param("id"));
|
|
319
|
+
if (!collection) return jsonError("Coleção não encontrada.", 404);
|
|
320
|
+
if (!Number.isInteger(id) || id <= 0) return jsonError("ID inválido.", 400);
|
|
321
|
+
return { collection, id };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
cms.get("/:collection/:id", (c) => {
|
|
325
|
+
const resolved = cmsItem(c);
|
|
326
|
+
if (resolved instanceof Response) return resolved;
|
|
327
|
+
const item = getItem(resolved.collection, resolved.id);
|
|
328
|
+
return item ? c.json({ item }) : jsonError("Item não encontrado.", 404);
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
async function updateHandler(c: Context<Env>): Promise<Response> {
|
|
332
|
+
const resolved = cmsItem(c);
|
|
333
|
+
if (resolved instanceof Response) return resolved;
|
|
334
|
+
if (!getItem(resolved.collection, resolved.id)) {
|
|
335
|
+
return jsonError("Item não encontrado.", 404);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
let body: unknown;
|
|
339
|
+
try {
|
|
340
|
+
body = await c.req.json();
|
|
341
|
+
} catch {
|
|
342
|
+
return jsonError("JSON inválido.", 400);
|
|
343
|
+
}
|
|
344
|
+
const result = coerceInput(resolved.collection, body, { partial: true });
|
|
345
|
+
if (!result.ok) {
|
|
346
|
+
return Response.json({ message: "Dados inválidos.", errors: result.errors }, { status: 422 });
|
|
347
|
+
}
|
|
348
|
+
const relationErrors = checkRelationTargets(resolved.collection, result.values);
|
|
349
|
+
if (Object.keys(relationErrors).length > 0) {
|
|
350
|
+
return Response.json({ message: "Dados inválidos.", errors: relationErrors }, { status: 422 });
|
|
351
|
+
}
|
|
352
|
+
return c.json({ item: updateItem(resolved.collection, resolved.id, result.values) });
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
cms.patch("/:collection/:id", updateHandler);
|
|
356
|
+
cms.put("/:collection/:id", updateHandler);
|
|
357
|
+
|
|
358
|
+
cms.delete("/:collection/:id", (c) => {
|
|
359
|
+
const resolved = cmsItem(c);
|
|
360
|
+
if (resolved instanceof Response) return resolved;
|
|
361
|
+
if (!deleteItem(resolved.collection, resolved.id)) {
|
|
362
|
+
return jsonError("Item não encontrado.", 404);
|
|
363
|
+
}
|
|
364
|
+
return c.json({ ok: true });
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
/* -------------------------------------------------------------------------- */
|
|
368
|
+
/* Auth API */
|
|
369
|
+
/* -------------------------------------------------------------------------- */
|
|
370
|
+
|
|
371
|
+
const auth = new Hono<Env>();
|
|
372
|
+
|
|
373
|
+
auth.post("/login", async (c) => {
|
|
374
|
+
if (isCrossOrigin(c)) return jsonError("Origem não permitida.", 403);
|
|
375
|
+
const body = await readBody(c.req.raw);
|
|
376
|
+
const email = String(body.email ?? "").trim();
|
|
377
|
+
const password = String(body.password ?? "");
|
|
378
|
+
const user = email && password ? verifyCredentials(email, password) : null;
|
|
379
|
+
if (!user) return jsonError("E-mail ou senha inválidos.", 401);
|
|
380
|
+
|
|
381
|
+
setAuthCookies(c, createSession(user.id));
|
|
382
|
+
return c.json({ user });
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
auth.post("/logout", async (c) => {
|
|
386
|
+
if (isCrossOrigin(c)) return jsonError("Origem não permitida.", 403);
|
|
387
|
+
const user = currentUser(c);
|
|
388
|
+
if (user) revokeUserSessions(user.id);
|
|
389
|
+
clearAuthCookies(c);
|
|
390
|
+
return c.json({ ok: true });
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
auth.post("/refresh", async (c) => {
|
|
394
|
+
if (isCrossOrigin(c)) return jsonError("Origem não permitida.", 403);
|
|
395
|
+
const refresh = getCookie(c, REFRESH_COOKIE);
|
|
396
|
+
const rotated = refresh ? rotateSession(refresh) : null;
|
|
397
|
+
if (!rotated) {
|
|
398
|
+
clearAuthCookies(c);
|
|
399
|
+
return jsonError("Sessão expirada. Faça login novamente.", 401);
|
|
400
|
+
}
|
|
401
|
+
setAuthCookies(c, rotated.tokens);
|
|
402
|
+
return c.json({ user: rotated.user });
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
auth.get("/me", requireAuth, (c) => c.json({ user: c.get("user") }));
|
|
406
|
+
|
|
407
|
+
auth.get("/users", requireAuth, (c) => c.json({ users: listUsers() }));
|
|
408
|
+
|
|
409
|
+
auth.post("/users", requireAuth, async (c) => {
|
|
410
|
+
const result = createUser(await readBody(c.req.raw));
|
|
411
|
+
if (!result.ok) {
|
|
412
|
+
return Response.json({ message: "Dados inválidos.", errors: result.errors }, { status: 422 });
|
|
413
|
+
}
|
|
414
|
+
return Response.json({ user: result.value }, { status: 201 });
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
function userId(c: Context<Env>): number | null {
|
|
418
|
+
const id = Number(c.req.param("id"));
|
|
419
|
+
return Number.isInteger(id) && id > 0 ? id : null;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
auth.get("/users/:id", requireAuth, (c) => {
|
|
423
|
+
const id = userId(c);
|
|
424
|
+
if (id === null) return jsonError("ID inválido.", 400);
|
|
425
|
+
const user = getUser(id);
|
|
426
|
+
return user ? c.json({ user }) : jsonError("Usuário não encontrado.", 404);
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
async function updateUserHandler(c: Context<Env>): Promise<Response> {
|
|
430
|
+
const id = userId(c);
|
|
431
|
+
if (id === null) return jsonError("ID inválido.", 400);
|
|
432
|
+
const result = updateUser(id, await readBody(c.req.raw));
|
|
433
|
+
if (result === null) return jsonError("Usuário não encontrado.", 404);
|
|
434
|
+
if (!result.ok) {
|
|
435
|
+
return Response.json({ message: "Dados inválidos.", errors: result.errors }, { status: 422 });
|
|
436
|
+
}
|
|
437
|
+
return c.json({ user: result.value });
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
auth.patch("/users/:id", requireAuth, updateUserHandler);
|
|
441
|
+
auth.put("/users/:id", requireAuth, updateUserHandler);
|
|
442
|
+
|
|
443
|
+
auth.delete("/users/:id", requireAuth, (c) => {
|
|
444
|
+
const id = userId(c);
|
|
445
|
+
if (id === null) return jsonError("ID inválido.", 400);
|
|
446
|
+
const requester = c.get("user") as AuthUser;
|
|
447
|
+
const result = deleteUser(id, requester.id);
|
|
448
|
+
if (result === "not_found") return jsonError("Usuário não encontrado.", 404);
|
|
449
|
+
if (result === "self") return jsonError("Você não pode remover o próprio usuário.", 409);
|
|
450
|
+
if (result === "last") return jsonError("Não é possível remover o último usuário.", 409);
|
|
451
|
+
return c.json({ ok: true });
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
/* -------------------------------------------------------------------------- */
|
|
455
|
+
/* Media / files / backup */
|
|
456
|
+
/* -------------------------------------------------------------------------- */
|
|
457
|
+
|
|
458
|
+
function resolveMediaField(collection: CollectionDef | undefined, name: string) {
|
|
459
|
+
if (!collection) return null;
|
|
460
|
+
return (
|
|
461
|
+
collection.fields.find(
|
|
462
|
+
(field) => field.name === name && (field.type === "media" || field.type === "media-list"),
|
|
463
|
+
) ?? null
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const media = new Hono<Env>();
|
|
468
|
+
media.use("*", requireAuth);
|
|
469
|
+
|
|
470
|
+
media.post("/", async (c) => {
|
|
471
|
+
const url = new URL(c.req.url);
|
|
472
|
+
const field = resolveMediaField(
|
|
473
|
+
getCollection(url.searchParams.get("collection") ?? ""),
|
|
474
|
+
url.searchParams.get("field") ?? "",
|
|
475
|
+
);
|
|
476
|
+
if (!field) return jsonError("Campo de mídia não encontrado.", 400);
|
|
477
|
+
|
|
478
|
+
let form: FormData;
|
|
479
|
+
try {
|
|
480
|
+
form = await c.req.formData();
|
|
481
|
+
} catch {
|
|
482
|
+
return jsonError("Upload inválido.", 400);
|
|
483
|
+
}
|
|
484
|
+
const file = form.get("file");
|
|
485
|
+
if (!(file instanceof File)) return jsonError("Nenhum arquivo enviado.", 400);
|
|
486
|
+
|
|
487
|
+
try {
|
|
488
|
+
return c.json({ media: await saveUpload(file, field) }, 201);
|
|
489
|
+
} catch (error) {
|
|
490
|
+
if (error instanceof MediaError) return jsonError(error.message, error.status);
|
|
491
|
+
throw error;
|
|
492
|
+
}
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
media.delete("/", (c) => {
|
|
496
|
+
const target = new URL(c.req.url).searchParams.get("url");
|
|
497
|
+
if (!target) return jsonError("URL ausente.", 400);
|
|
498
|
+
deleteByUrl(target);
|
|
499
|
+
return c.json({ ok: true });
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
const files = new Hono<Env>();
|
|
503
|
+
files.get("/*", (c) => {
|
|
504
|
+
const raw = c.req.path.slice(getCmsConfig().files.path.length);
|
|
505
|
+
const name = decodeURIComponent(raw.replace(/^\/+/, ""));
|
|
506
|
+
const data = readUpload(name);
|
|
507
|
+
if (!data) return new Response("Not found", { status: 404 });
|
|
508
|
+
return new Response(new Uint8Array(data), {
|
|
509
|
+
headers: {
|
|
510
|
+
"Content-Type": contentTypeFor(name),
|
|
511
|
+
"Content-Length": String(data.length),
|
|
512
|
+
"Cache-Control": "public, max-age=31536000, immutable",
|
|
513
|
+
"X-Content-Type-Options": "nosniff",
|
|
514
|
+
"Content-Security-Policy": "default-src 'none'; sandbox",
|
|
515
|
+
},
|
|
516
|
+
});
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
const backup = new Hono<Env>();
|
|
520
|
+
backup.use("*", requireAuth);
|
|
521
|
+
|
|
522
|
+
function backupError(error: unknown): Response {
|
|
523
|
+
if (error instanceof BackupError) return jsonError(error.message, error.status);
|
|
524
|
+
console.error("[backup] erro inesperado:", error);
|
|
525
|
+
return jsonError("Não foi possível concluir a operação de backup.", 500);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function attachment(buffer: Buffer, name: string): Response {
|
|
529
|
+
return new Response(new Uint8Array(buffer), {
|
|
530
|
+
headers: {
|
|
531
|
+
"Content-Type": "application/gzip",
|
|
532
|
+
"Content-Disposition": `attachment; filename="${name}"`,
|
|
533
|
+
"Content-Length": String(buffer.length),
|
|
534
|
+
"Cache-Control": "no-store",
|
|
535
|
+
"X-Content-Type-Options": "nosniff",
|
|
536
|
+
},
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
backup.get("/", (c) => {
|
|
541
|
+
const params = new URL(c.req.url).searchParams;
|
|
542
|
+
const name = params.get("name");
|
|
543
|
+
try {
|
|
544
|
+
if (name) {
|
|
545
|
+
const { info, buffer } = readBackup(name);
|
|
546
|
+
return attachment(buffer, info.name);
|
|
547
|
+
}
|
|
548
|
+
if (params.get("latest")) {
|
|
549
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
550
|
+
return attachment(createBackupBuffer(), `backup-${stamp}.serenojs`);
|
|
551
|
+
}
|
|
552
|
+
return c.json({ backups: listBackups() });
|
|
553
|
+
} catch (error) {
|
|
554
|
+
return backupError(error);
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
|
|
558
|
+
backup.post("/", (c) => {
|
|
559
|
+
try {
|
|
560
|
+
return c.json({ backup: createBackup() }, 201);
|
|
561
|
+
} catch (error) {
|
|
562
|
+
return backupError(error);
|
|
563
|
+
}
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
backup.put("/", async (c) => {
|
|
567
|
+
let buffer: Buffer;
|
|
568
|
+
try {
|
|
569
|
+
buffer = Buffer.from(await c.req.arrayBuffer());
|
|
570
|
+
} catch {
|
|
571
|
+
return jsonError("Upload inválido.", 400);
|
|
572
|
+
}
|
|
573
|
+
if (buffer.length === 0) return jsonError("Nenhum arquivo enviado.", 400);
|
|
574
|
+
try {
|
|
575
|
+
return c.json({ manifest: restoreBackup(buffer) });
|
|
576
|
+
} catch (error) {
|
|
577
|
+
return backupError(error);
|
|
578
|
+
}
|
|
579
|
+
});
|
|
580
|
+
|
|
581
|
+
backup.delete("/", (c) => {
|
|
582
|
+
const name = new URL(c.req.url).searchParams.get("name");
|
|
583
|
+
if (!name) return jsonError("Nome do backup ausente.", 400);
|
|
584
|
+
try {
|
|
585
|
+
deleteBackup(name);
|
|
586
|
+
return c.json({ ok: true });
|
|
587
|
+
} catch (error) {
|
|
588
|
+
return backupError(error);
|
|
589
|
+
}
|
|
590
|
+
});
|
|
591
|
+
|
|
592
|
+
/* -------------------------------------------------------------------------- */
|
|
593
|
+
/* Admin SPA */
|
|
594
|
+
/* -------------------------------------------------------------------------- */
|
|
595
|
+
|
|
596
|
+
function readAdminIndex(): string | null {
|
|
597
|
+
try {
|
|
598
|
+
return readFileSync(join(adminDist(), "index.html"), "utf8");
|
|
599
|
+
} catch {
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function runtimePayload() {
|
|
605
|
+
const config = getCmsConfig();
|
|
606
|
+
return {
|
|
607
|
+
title: config.title,
|
|
608
|
+
adminPath: config.admin.path,
|
|
609
|
+
apiPath: config.api.path,
|
|
610
|
+
authPath: config.auth.path,
|
|
611
|
+
mediaPath: config.media.path,
|
|
612
|
+
filesPath: config.files.path,
|
|
613
|
+
backupPath: config.backup.path,
|
|
614
|
+
collections: config.collections,
|
|
615
|
+
locales: config.locales,
|
|
616
|
+
defaultLocale: config.defaultLocale,
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function adminHeaders(): HeadersInit {
|
|
621
|
+
const config = getCmsConfig();
|
|
622
|
+
return {
|
|
623
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
624
|
+
"Cache-Control": "no-store",
|
|
625
|
+
...(config.admin.noindex
|
|
626
|
+
? { "X-Robots-Tag": "noindex, nofollow", "X-Frame-Options": "SAMEORIGIN" }
|
|
627
|
+
: {}),
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
function serveAdminIndex(): Response {
|
|
632
|
+
const template = readAdminIndex();
|
|
633
|
+
if (!template) {
|
|
634
|
+
return new Response(
|
|
635
|
+
"Admin bundle ausente. Rode `pnpm build:admin` para gerar packages/serenojs/admin-dist.",
|
|
636
|
+
{ status: 503, headers: { "Content-Type": "text/plain; charset=utf-8" } },
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
const config = getCmsConfig();
|
|
640
|
+
const payload = JSON.stringify(runtimePayload()).replace(/</g, "\\u003c");
|
|
641
|
+
const html = template
|
|
642
|
+
.replaceAll("__SERENOJS_CONFIG__", payload)
|
|
643
|
+
.replaceAll("%SERENOJS_TITLE%", config.title);
|
|
644
|
+
return new Response(html, { headers: adminHeaders() });
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function buildApp(): Hono<Env> {
|
|
648
|
+
const root = new Hono<Env>();
|
|
649
|
+
|
|
650
|
+
// Admin SPA assets live at a fixed internal path so history routing works at
|
|
651
|
+
// any configured admin mount path.
|
|
652
|
+
root.get(`${ADMIN_ASSETS_PREFIX}/*`, (c) => {
|
|
653
|
+
if (!getCmsConfig().admin.enabled) return new Response("Not found", { status: 404 });
|
|
654
|
+
const relative = c.req.path.slice(ADMIN_ASSETS_PREFIX.length).replace(/^\/+/, "");
|
|
655
|
+
const target = normalize(join(adminDist(), relative));
|
|
656
|
+
if (!target.startsWith(normalize(adminDist()))) return new Response("Not found", { status: 404 });
|
|
657
|
+
try {
|
|
658
|
+
if (!statSync(target).isFile()) return new Response("Not found", { status: 404 });
|
|
659
|
+
const data = readFileSync(target);
|
|
660
|
+
return new Response(new Uint8Array(data), {
|
|
661
|
+
headers: {
|
|
662
|
+
"Content-Type": mimeFor(target),
|
|
663
|
+
"Cache-Control": relative.startsWith("assets/")
|
|
664
|
+
? "public, max-age=31536000, immutable"
|
|
665
|
+
: "no-cache",
|
|
666
|
+
"X-Content-Type-Options": "nosniff",
|
|
667
|
+
},
|
|
668
|
+
});
|
|
669
|
+
} catch {
|
|
670
|
+
return new Response("Not found", { status: 404 });
|
|
671
|
+
}
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
root.route(getCmsConfig().api.path, cms);
|
|
675
|
+
root.route(getCmsConfig().auth.path, auth);
|
|
676
|
+
root.route(getCmsConfig().media.path, media);
|
|
677
|
+
root.route(getCmsConfig().files.path, files);
|
|
678
|
+
root.route(getCmsConfig().backup.path, backup);
|
|
679
|
+
|
|
680
|
+
// History routing: every path under the admin mount serves the SPA shell.
|
|
681
|
+
// Registered after the routers so it only handles the admin prefix.
|
|
682
|
+
root.get("*", (c, next) => {
|
|
683
|
+
const config = getCmsConfig();
|
|
684
|
+
const path = c.req.path;
|
|
685
|
+
const isAdmin =
|
|
686
|
+
path === config.admin.path || path.startsWith(`${config.admin.path}/`);
|
|
687
|
+
if (!isAdmin) return next();
|
|
688
|
+
if (!config.admin.enabled) return new Response("Not found", { status: 404 });
|
|
689
|
+
return serveAdminIndex();
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
return root;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/** Whether a request path belongs to the CMS (and must not reach Waku). */
|
|
696
|
+
function owns(path: string): boolean {
|
|
697
|
+
const config = getCmsConfig();
|
|
698
|
+
if (path === ADMIN_ASSETS_PREFIX || path.startsWith(`${ADMIN_ASSETS_PREFIX}/`)) {
|
|
699
|
+
return true;
|
|
700
|
+
}
|
|
701
|
+
const check = (base: string) => path === base || path.startsWith(`${base}/`);
|
|
702
|
+
return (
|
|
703
|
+
check(config.admin.path) ||
|
|
704
|
+
check(config.api.path) ||
|
|
705
|
+
check(config.auth.path) ||
|
|
706
|
+
check(config.media.path) ||
|
|
707
|
+
check(config.files.path) ||
|
|
708
|
+
check(config.backup.path)
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* Waku middleware factory.
|
|
714
|
+
*
|
|
715
|
+
* @example
|
|
716
|
+
* // src/middleware/serenojs.ts
|
|
717
|
+
* import config from "../../serenojs.config.js";
|
|
718
|
+
* import { createCmsMiddleware } from "@eutobias/serenojs/server";
|
|
719
|
+
* export default createCmsMiddleware(config);
|
|
720
|
+
*/
|
|
721
|
+
export function createCmsMiddleware(config: CmsConfig) {
|
|
722
|
+
configureCms(config);
|
|
723
|
+
startBackupScheduler();
|
|
724
|
+
|
|
725
|
+
const app = buildApp();
|
|
726
|
+
const handler = app.fetch.bind(app);
|
|
727
|
+
|
|
728
|
+
return (_opts?: unknown): MiddlewareHandler => {
|
|
729
|
+
return async (c, next) => {
|
|
730
|
+
const path = new URL(c.req.url).pathname;
|
|
731
|
+
if (!owns(path)) return next();
|
|
732
|
+
return handler(c.req.raw);
|
|
733
|
+
};
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
export { buildApp as createCmsApp };
|