@kidecms/core 0.1.10 → 0.13.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/admin/components/AssetsGrid.tsx +366 -173
- package/admin/components/BlockEditor.tsx +260 -679
- package/admin/components/CheckboxField.tsx +2 -2
- package/admin/components/CollaborationReviewBar.tsx +384 -0
- package/admin/components/ColorField.tsx +87 -0
- package/admin/components/CommandPalette.tsx +169 -0
- package/admin/components/ContentEditor.tsx +687 -0
- package/admin/components/DocumentActions.tsx +4 -2
- package/admin/components/DocumentsDataTable.tsx +91 -10
- package/admin/components/FieldControl.astro +151 -26
- package/admin/components/FocalPointSelector.tsx +27 -1
- package/admin/components/InternalLinkPicker.tsx +4 -3
- package/admin/components/LinkField.tsx +126 -0
- package/admin/components/RelationField.tsx +105 -26
- package/admin/components/RepeaterInput.tsx +46 -0
- package/admin/components/RichTextEditor.tsx +44 -9
- package/admin/components/SharedSectionBlockField.tsx +93 -0
- package/admin/components/SidebarUserMenu.tsx +1 -1
- package/admin/components/Toast.astro +1 -1
- package/admin/components/TreeItemsEditor.tsx +20 -19
- package/admin/components/TreeSelect.tsx +2 -2
- package/admin/components/YoutubeField.tsx +48 -0
- package/admin/components/block-fields.tsx +777 -0
- package/admin/components/content-block-spec.ts +114 -0
- package/admin/components/slash-command.tsx +242 -0
- package/admin/components/tree-utils.ts +14 -2
- package/admin/components/ui/badge.tsx +2 -3
- package/admin/components/ui/button.tsx +5 -4
- package/admin/components/ui/checkbox.tsx +1 -1
- package/admin/components/ui/input.tsx +1 -1
- package/admin/components/ui/select.tsx +1 -1
- package/admin/components/ui/table.tsx +1 -1
- package/admin/components/ui/textarea.tsx +1 -1
- package/admin/layouts/AdminLayout.astro +323 -123
- package/admin/lib/access.ts +54 -0
- package/admin/lib/collaboration.ts +178 -0
- package/admin/lib/edit-data.ts +448 -0
- package/admin/views/AccessDeniedView.astro +8 -0
- package/admin/views/EditView.astro +706 -0
- package/admin/views/ListView.astro +202 -0
- package/admin/views/RecentView.astro +76 -0
- package/admin/views/SinglesView.astro +65 -0
- package/admin/views/edit/EditScripts.astro +145 -0
- package/admin/views/edit/ReverseReferencesList.astro +68 -0
- package/core/admin.ts +193 -0
- package/core/ai.ts +87 -0
- package/core/api.ts +1392 -0
- package/core/assets.ts +336 -0
- package/core/audit.ts +84 -0
- package/core/auth-config.ts +44 -0
- package/core/auth.ts +303 -0
- package/core/collaboration.ts +276 -0
- package/core/content.ts +27 -0
- package/core/create-admin.ts +28 -0
- package/core/define.ts +625 -0
- package/core/field-model.ts +172 -0
- package/core/generator.ts +519 -0
- package/core/http.ts +42 -0
- package/core/image.ts +219 -0
- package/core/index.ts +211 -0
- package/core/locks.ts +52 -0
- package/core/log.ts +37 -0
- package/core/migrate.ts +278 -0
- package/core/rate-limit.ts +110 -0
- package/core/request-scope.ts +33 -0
- package/core/richtext.ts +1 -0
- package/core/runtime.ts +63 -0
- package/core/schema.ts +32 -0
- package/core/search.ts +489 -0
- package/core/seed.ts +101 -0
- package/core/shared-sections.ts +96 -0
- package/core/tasks.ts +176 -0
- package/core/values.ts +433 -0
- package/core/webhooks.ts +85 -0
- package/core/youtube.ts +39 -0
- package/internals/cli.mjs +34 -0
- package/internals/context.ts +67 -0
- package/internals/create-admin.ts +40 -0
- package/internals/describe.ts +25 -0
- package/internals/eject.ts +144 -0
- package/internals/generator.ts +11 -0
- package/internals/integration.ts +481 -0
- package/internals/mcp.ts +397 -0
- package/internals/project.ts +26 -0
- package/internals/push.ts +160 -0
- package/internals/reindex.ts +11 -0
- package/internals/restore.ts +257 -0
- package/internals/seed.data.ts +7 -0
- package/internals/seed.ts +11 -0
- package/internals/upgrade.ts +776 -0
- package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
- package/middleware/auth.ts +130 -17
- package/middleware/push.ts +121 -0
- package/package.json +55 -67
- package/platform/cloudflare/cf-env.ts +60 -0
- package/platform/cloudflare/database.ts +28 -0
- package/platform/cloudflare/globals.d.ts +5 -0
- package/platform/cloudflare/storage.ts +33 -0
- package/platform/cloudflare/uploads-route.ts +37 -0
- package/platform/node/database.ts +39 -0
- package/platform/node/storage.ts +52 -0
- package/routes/admin/[...path].astro +71 -0
- package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
- package/routes/admin/assets/index.astro +90 -0
- package/routes/admin/forgot-password.astro +60 -0
- package/routes/{pages/admin → admin}/invite.astro +7 -6
- package/routes/admin/login.astro +103 -0
- package/routes/admin/reset-password.astro +73 -0
- package/routes/{pages/admin → admin}/setup.astro +32 -8
- package/routes/api/{cms/[collection] → [collection]}/[...path].ts +66 -14
- package/routes/api/admin/search.ts +89 -0
- package/routes/api/{cms/assets → assets}/[id].ts +24 -14
- package/routes/api/{cms/assets → assets}/index.ts +4 -2
- package/routes/api/assets/upload.ts +147 -0
- package/routes/api/auth/forgot-password.ts +77 -0
- package/routes/api/{cms/auth → auth}/invite.ts +41 -9
- package/routes/api/auth/login.ts +167 -0
- package/routes/api/{cms/auth → auth}/logout.ts +11 -2
- package/routes/api/auth/reset-password.ts +85 -0
- package/routes/api/auth/setup.ts +110 -0
- package/routes/api/auth/sso/[provider]/start.ts +34 -0
- package/routes/api/collaboration/index.ts +106 -0
- package/routes/api/cron/_authorize.ts +25 -0
- package/routes/api/{cms/cron → cron}/publish.ts +3 -9
- package/routes/api/cron/tasks.ts +33 -0
- package/routes/api/forms/submit/[slug].ts +143 -0
- package/routes/api/img/[...path].ts +65 -0
- package/routes/api/{cms/preview → preview}/render.ts +8 -3
- package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
- package/routes/api/webhooks/[provider].ts +54 -0
- package/README.md +0 -28
- package/dist/admin.d.ts +0 -33
- package/dist/admin.js +0 -92
- package/dist/ai.d.ts +0 -15
- package/dist/ai.js +0 -70
- package/dist/api.d.ts +0 -14
- package/dist/api.js +0 -833
- package/dist/assets.d.ts +0 -51
- package/dist/assets.js +0 -163
- package/dist/auth.d.ts +0 -30
- package/dist/auth.js +0 -132
- package/dist/content.d.ts +0 -3
- package/dist/content.js +0 -29
- package/dist/create-admin.d.ts +0 -5
- package/dist/create-admin.js +0 -23
- package/dist/define.d.ts +0 -254
- package/dist/define.js +0 -36
- package/dist/generator.d.ts +0 -9
- package/dist/generator.js +0 -370
- package/dist/image.d.ts +0 -9
- package/dist/image.js +0 -69
- package/dist/index.d.ts +0 -28
- package/dist/index.js +0 -16
- package/dist/integration.d.ts +0 -14
- package/dist/integration.js +0 -327
- package/dist/locks.d.ts +0 -7
- package/dist/locks.js +0 -37
- package/dist/richtext.d.ts +0 -1
- package/dist/richtext.js +0 -1
- package/dist/runtime.d.ts +0 -24
- package/dist/runtime.js +0 -26
- package/dist/schema.d.ts +0 -17
- package/dist/schema.js +0 -13
- package/dist/seed.d.ts +0 -2
- package/dist/seed.js +0 -84
- package/dist/values.d.ts +0 -8
- package/dist/values.js +0 -102
- package/dist/webhooks.d.ts +0 -2
- package/dist/webhooks.js +0 -73
- package/routes/api/cms/assets/upload.ts +0 -112
- package/routes/api/cms/auth/login.ts +0 -124
- package/routes/api/cms/auth/setup.ts +0 -77
- package/routes/api/cms/img/[...path].ts +0 -24
- package/routes/pages/admin/[...path].astro +0 -1107
- package/routes/pages/admin/assets/index.astro +0 -63
- package/routes/pages/admin/login.astro +0 -57
- /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
- /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
- /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
- /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
- /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
package/core/auth.ts
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { and, eq, gt, isNull } from "drizzle-orm";
|
|
2
|
+
import { nanoid } from "nanoid";
|
|
3
|
+
|
|
4
|
+
import { getDb } from "./runtime";
|
|
5
|
+
import { getSchema } from "./schema";
|
|
6
|
+
|
|
7
|
+
// 600k per OWASP. Iteration count is stored per-hash, so existing 100k hashes still verify.
|
|
8
|
+
const ITERATIONS = 600_000;
|
|
9
|
+
const HASH_LENGTH = 32;
|
|
10
|
+
const SALT_LENGTH = 16;
|
|
11
|
+
|
|
12
|
+
export const MIN_PASSWORD_LENGTH = 12;
|
|
13
|
+
|
|
14
|
+
const encode = (buffer: ArrayBuffer) => btoa(String.fromCharCode(...new Uint8Array(buffer)));
|
|
15
|
+
|
|
16
|
+
const deriveKey = async (plain: string, salt: Uint8Array) => {
|
|
17
|
+
const keyMaterial = await crypto.subtle.importKey("raw", new TextEncoder().encode(plain), "PBKDF2", false, [
|
|
18
|
+
"deriveBits",
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
return crypto.subtle.deriveBits(
|
|
22
|
+
{ name: "PBKDF2", salt: salt.buffer as ArrayBuffer, iterations: ITERATIONS, hash: "SHA-256" },
|
|
23
|
+
keyMaterial,
|
|
24
|
+
HASH_LENGTH * 8,
|
|
25
|
+
);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// Upper bounds so a malformed/hostile stored hash or an oversized password can't turn
|
|
29
|
+
// hashing/verification into a CPU DoS (a huge iteration count would spin deriveBits
|
|
30
|
+
// indefinitely; an unbounded password is wasted work).
|
|
31
|
+
const MAX_PASSWORD_LENGTH = 4096;
|
|
32
|
+
const MAX_PBKDF2_ITERATIONS = 1_000_000;
|
|
33
|
+
const MAX_ENCODED_LENGTH = 512; // generous cap on a base64 salt/digest segment
|
|
34
|
+
|
|
35
|
+
const safeDecode = (base64: string): Uint8Array<ArrayBuffer> | null => {
|
|
36
|
+
if (base64.length > MAX_ENCODED_LENGTH) return null;
|
|
37
|
+
try {
|
|
38
|
+
const bytes = new Uint8Array(base64.length);
|
|
39
|
+
const binary = atob(base64);
|
|
40
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
41
|
+
return bytes.subarray(0, binary.length) as Uint8Array<ArrayBuffer>;
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export const hashPassword = async (plain: string): Promise<string> => {
|
|
48
|
+
if (plain.length > MAX_PASSWORD_LENGTH) throw new Error("Password exceeds the maximum length.");
|
|
49
|
+
const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
|
|
50
|
+
const derived = await deriveKey(plain, salt);
|
|
51
|
+
return `pbkdf2:${ITERATIONS}:${encode(salt.buffer as ArrayBuffer)}:${encode(derived)}`;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export const verifyPassword = async (hash: string, plain: string): Promise<boolean> => {
|
|
55
|
+
if (plain.length > MAX_PASSWORD_LENGTH) return false;
|
|
56
|
+
const [scheme, iterStr, saltB64, hashB64] = hash.split(":");
|
|
57
|
+
if (scheme !== "pbkdf2" || !iterStr || !saltB64 || !hashB64) return false;
|
|
58
|
+
|
|
59
|
+
const iterations = Number(iterStr);
|
|
60
|
+
if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_PBKDF2_ITERATIONS) return false;
|
|
61
|
+
|
|
62
|
+
const salt = safeDecode(saltB64);
|
|
63
|
+
const expected = safeDecode(hashB64);
|
|
64
|
+
if (!salt || !expected || expected.length === 0) return false;
|
|
65
|
+
|
|
66
|
+
const keyMaterial = await crypto.subtle.importKey("raw", new TextEncoder().encode(plain), "PBKDF2", false, [
|
|
67
|
+
"deriveBits",
|
|
68
|
+
]);
|
|
69
|
+
const derived = new Uint8Array(
|
|
70
|
+
await crypto.subtle.deriveBits(
|
|
71
|
+
{ name: "PBKDF2", salt, iterations, hash: "SHA-256" },
|
|
72
|
+
keyMaterial,
|
|
73
|
+
expected.length * 8,
|
|
74
|
+
),
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
if (derived.length !== expected.length) return false;
|
|
78
|
+
let diff = 0;
|
|
79
|
+
for (let i = 0; i < derived.length; i++) diff |= derived[i] ^ expected[i];
|
|
80
|
+
return diff === 0;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// One-way reference used to store session/invite/reset tokens at rest. The raw token
|
|
84
|
+
// lives only in the cookie / email link / invite URL; the DB keeps only SHA-256(token),
|
|
85
|
+
// so a database read yields no usable credential. Web Crypto → edge-safe on both targets.
|
|
86
|
+
export const hashToken = async (token: string): Promise<string> => {
|
|
87
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
|
|
88
|
+
const hex = [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
89
|
+
return `sha256:${hex}`;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export const createSession = async (userId: string): Promise<{ token: string; expiresAt: string }> => {
|
|
93
|
+
const db = await getDb();
|
|
94
|
+
const schema = getSchema();
|
|
95
|
+
const token = nanoid(32);
|
|
96
|
+
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
|
|
97
|
+
|
|
98
|
+
await db.insert(schema.cmsSessions).values({
|
|
99
|
+
_id: await hashToken(token),
|
|
100
|
+
userId,
|
|
101
|
+
expiresAt,
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
return { token, expiresAt };
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export const validateSession = async (token: string): Promise<{ userId: string; expiresAt: string } | null> => {
|
|
108
|
+
const db = await getDb();
|
|
109
|
+
const schema = getSchema();
|
|
110
|
+
const tokenHash = await hashToken(token);
|
|
111
|
+
const rows = await db.select().from(schema.cmsSessions).where(eq(schema.cmsSessions._id, tokenHash)).limit(1);
|
|
112
|
+
|
|
113
|
+
if (rows.length === 0) return null;
|
|
114
|
+
|
|
115
|
+
const session = rows[0] as { _id: string; userId: string; expiresAt: string };
|
|
116
|
+
if (new Date(session.expiresAt) < new Date()) {
|
|
117
|
+
await db.delete(schema.cmsSessions).where(eq(schema.cmsSessions._id, tokenHash));
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return { userId: session.userId, expiresAt: session.expiresAt };
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
export const destroySession = async (token: string) => {
|
|
125
|
+
const db = await getDb();
|
|
126
|
+
const schema = getSchema();
|
|
127
|
+
await db.delete(schema.cmsSessions).where(eq(schema.cmsSessions._id, await hashToken(token)));
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
export type SessionUser = {
|
|
131
|
+
id: string;
|
|
132
|
+
email: string;
|
|
133
|
+
name: string;
|
|
134
|
+
role: string;
|
|
135
|
+
[key: string]: unknown;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const parseSessionValue = (value: unknown) => {
|
|
139
|
+
if (typeof value !== "string") return value;
|
|
140
|
+
const trimmed = value.trim();
|
|
141
|
+
if (!trimmed.startsWith("[") && !trimmed.startsWith("{")) return value;
|
|
142
|
+
try {
|
|
143
|
+
return JSON.parse(trimmed);
|
|
144
|
+
} catch {
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
export const getSessionUser = async (request: Request): Promise<SessionUser | null> => {
|
|
150
|
+
const cookieHeader = request.headers.get("cookie") ?? "";
|
|
151
|
+
const match = cookieHeader.match(/cms_session=([^;]+)/);
|
|
152
|
+
if (!match) return null;
|
|
153
|
+
|
|
154
|
+
const session = await validateSession(match[1]);
|
|
155
|
+
if (!session) return null;
|
|
156
|
+
|
|
157
|
+
const db = await getDb();
|
|
158
|
+
const schema = getSchema();
|
|
159
|
+
const tables = schema.cmsTables as Record<string, { main: any }>;
|
|
160
|
+
|
|
161
|
+
if (!tables.users) return null;
|
|
162
|
+
|
|
163
|
+
const userRows = await db.select().from(tables.users.main).where(eq(tables.users.main._id, session.userId)).limit(1);
|
|
164
|
+
if (userRows.length === 0) return null;
|
|
165
|
+
|
|
166
|
+
const user = userRows[0] as Record<string, unknown>;
|
|
167
|
+
const publicFields = Object.fromEntries(
|
|
168
|
+
Object.entries(user)
|
|
169
|
+
.filter(([key]) => key !== "_id" && key !== "password")
|
|
170
|
+
.map(([key, value]) => [key, parseSessionValue(value)]),
|
|
171
|
+
);
|
|
172
|
+
return {
|
|
173
|
+
...publicFields,
|
|
174
|
+
id: String(user._id),
|
|
175
|
+
email: String(user.email),
|
|
176
|
+
name: String(user.name),
|
|
177
|
+
role: String(user.role),
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const INVITE_EXPIRY_DAYS = 7;
|
|
182
|
+
const PASSWORD_RESET_EXPIRY_HOURS = 1;
|
|
183
|
+
|
|
184
|
+
export const createInvite = async (userId: string): Promise<{ token: string; expiresAt: string }> => {
|
|
185
|
+
const db = await getDb();
|
|
186
|
+
const schema = getSchema();
|
|
187
|
+
const token = nanoid(32);
|
|
188
|
+
const expiresAt = new Date(Date.now() + INVITE_EXPIRY_DAYS * 24 * 60 * 60 * 1000).toISOString();
|
|
189
|
+
|
|
190
|
+
await db.insert(schema.cmsInvites).values({
|
|
191
|
+
_id: nanoid(),
|
|
192
|
+
userId,
|
|
193
|
+
token: await hashToken(token),
|
|
194
|
+
expiresAt,
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
return { token, expiresAt };
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/** Read-only check for rendering the accept page. Does NOT consume — see consumeInvite. */
|
|
201
|
+
export const validateInvite = async (token: string): Promise<{ userId: string; expiresAt: string } | null> => {
|
|
202
|
+
const db = await getDb();
|
|
203
|
+
const schema = getSchema();
|
|
204
|
+
const rows = await db
|
|
205
|
+
.select()
|
|
206
|
+
.from(schema.cmsInvites)
|
|
207
|
+
.where(eq(schema.cmsInvites.token, await hashToken(token)))
|
|
208
|
+
.limit(1);
|
|
209
|
+
|
|
210
|
+
if (rows.length === 0) return null;
|
|
211
|
+
|
|
212
|
+
const invite = rows[0] as { userId: string; expiresAt: string; usedAt: string | null };
|
|
213
|
+
if (invite.usedAt) return null;
|
|
214
|
+
if (new Date(invite.expiresAt) < new Date()) return null;
|
|
215
|
+
|
|
216
|
+
return { userId: invite.userId, expiresAt: invite.expiresAt };
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Atomically claim an invite: mark it used and return the userId only if it was still
|
|
221
|
+
* valid, unexpired, and unused. Consume-before-mutate — the `usedAt IS NULL` guard plus
|
|
222
|
+
* RETURNING means concurrent accepts can't both win. Returns null when already used/expired.
|
|
223
|
+
*/
|
|
224
|
+
export const consumeInvite = async (token: string): Promise<{ userId: string } | null> => {
|
|
225
|
+
const db = await getDb();
|
|
226
|
+
const schema = getSchema();
|
|
227
|
+
const now = new Date().toISOString();
|
|
228
|
+
const rows = await db
|
|
229
|
+
.update(schema.cmsInvites)
|
|
230
|
+
.set({ usedAt: now })
|
|
231
|
+
.where(
|
|
232
|
+
and(
|
|
233
|
+
eq(schema.cmsInvites.token, await hashToken(token)),
|
|
234
|
+
isNull(schema.cmsInvites.usedAt),
|
|
235
|
+
gt(schema.cmsInvites.expiresAt, now),
|
|
236
|
+
),
|
|
237
|
+
)
|
|
238
|
+
.returning({ userId: schema.cmsInvites.userId });
|
|
239
|
+
return rows.length > 0 ? { userId: rows[0].userId as string } : null;
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
export const createPasswordReset = async (userId: string): Promise<{ token: string; expiresAt: string }> => {
|
|
243
|
+
const db = await getDb();
|
|
244
|
+
const schema = getSchema();
|
|
245
|
+
const token = nanoid(40);
|
|
246
|
+
const expiresAt = new Date(Date.now() + PASSWORD_RESET_EXPIRY_HOURS * 60 * 60 * 1000).toISOString();
|
|
247
|
+
|
|
248
|
+
await db.insert(schema.cmsPasswordResets).values({
|
|
249
|
+
_id: nanoid(),
|
|
250
|
+
userId,
|
|
251
|
+
token: await hashToken(token),
|
|
252
|
+
expiresAt,
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
return { token, expiresAt };
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
/** Read-only check for rendering the reset page. Does NOT consume — see consumePasswordReset. */
|
|
259
|
+
export const validatePasswordReset = async (token: string): Promise<{ userId: string; expiresAt: string } | null> => {
|
|
260
|
+
const db = await getDb();
|
|
261
|
+
const schema = getSchema();
|
|
262
|
+
const rows = await db
|
|
263
|
+
.select()
|
|
264
|
+
.from(schema.cmsPasswordResets)
|
|
265
|
+
.where(eq(schema.cmsPasswordResets.token, await hashToken(token)))
|
|
266
|
+
.limit(1);
|
|
267
|
+
|
|
268
|
+
if (rows.length === 0) return null;
|
|
269
|
+
|
|
270
|
+
const reset = rows[0] as { userId: string; expiresAt: string; usedAt: string | null };
|
|
271
|
+
if (reset.usedAt) return null;
|
|
272
|
+
if (new Date(reset.expiresAt) < new Date()) return null;
|
|
273
|
+
|
|
274
|
+
return { userId: reset.userId, expiresAt: reset.expiresAt };
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
/** Atomically claim a reset token; returns the userId only if it won the race. */
|
|
278
|
+
export const consumePasswordReset = async (token: string): Promise<{ userId: string } | null> => {
|
|
279
|
+
const db = await getDb();
|
|
280
|
+
const schema = getSchema();
|
|
281
|
+
const now = new Date().toISOString();
|
|
282
|
+
const rows = await db
|
|
283
|
+
.update(schema.cmsPasswordResets)
|
|
284
|
+
.set({ usedAt: now })
|
|
285
|
+
.where(
|
|
286
|
+
and(
|
|
287
|
+
eq(schema.cmsPasswordResets.token, await hashToken(token)),
|
|
288
|
+
isNull(schema.cmsPasswordResets.usedAt),
|
|
289
|
+
gt(schema.cmsPasswordResets.expiresAt, now),
|
|
290
|
+
),
|
|
291
|
+
)
|
|
292
|
+
.returning({ userId: schema.cmsPasswordResets.userId });
|
|
293
|
+
return rows.length > 0 ? { userId: rows[0].userId as string } : null;
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
export const SESSION_COOKIE_NAME = "cms_session";
|
|
297
|
+
|
|
298
|
+
export const setSessionCookie = (token: string, expiresAt: string) => {
|
|
299
|
+
const secure = process.env.NODE_ENV === "production" ? "; Secure" : "";
|
|
300
|
+
return `${SESSION_COOKIE_NAME}=${token}; Path=/; HttpOnly; SameSite=Strict${secure}; Expires=${new Date(expiresAt).toUTCString()}`;
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
export const clearSessionCookie = () => `${SESSION_COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`;
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { and, desc, eq, inArray } from "drizzle-orm";
|
|
2
|
+
import { nanoid } from "nanoid";
|
|
3
|
+
|
|
4
|
+
import { recordAudit, type AuditActor } from "./audit";
|
|
5
|
+
import { getDb } from "./runtime";
|
|
6
|
+
import { getSchema } from "./schema";
|
|
7
|
+
|
|
8
|
+
// `in_progress` is the default before any collaboration row exists.
|
|
9
|
+
export const REVIEW_STATES = ["in_progress", "ready_for_review", "changes_requested", "approved"] as const;
|
|
10
|
+
export type ReviewState = (typeof REVIEW_STATES)[number];
|
|
11
|
+
|
|
12
|
+
const DEFAULT_STATE: ReviewState = "in_progress";
|
|
13
|
+
|
|
14
|
+
// Approval is role-based (see isApprover), not per-document.
|
|
15
|
+
export type CollaborationState = { reviewState: ReviewState; editor: string | null };
|
|
16
|
+
|
|
17
|
+
export type CommentRecord = {
|
|
18
|
+
_id: string;
|
|
19
|
+
collection: string;
|
|
20
|
+
documentId: string;
|
|
21
|
+
field: string | null;
|
|
22
|
+
body: string;
|
|
23
|
+
authorId: string | null;
|
|
24
|
+
authorEmail: string | null;
|
|
25
|
+
resolved: boolean;
|
|
26
|
+
createdAt: string;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export type ActivityRecord = {
|
|
30
|
+
action: string;
|
|
31
|
+
actorId: string | null;
|
|
32
|
+
actorEmail: string | null;
|
|
33
|
+
timestamp: number;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export const isReviewState = (value: unknown): value is ReviewState => REVIEW_STATES.includes(value as ReviewState);
|
|
37
|
+
|
|
38
|
+
const rowToState = (row: any): CollaborationState => ({
|
|
39
|
+
reviewState: isReviewState(row?.reviewState) ? row.reviewState : DEFAULT_STATE,
|
|
40
|
+
editor: row?.editor ?? null,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const upsertState = async (collection: string, documentId: string, patch: Partial<CollaborationState>) => {
|
|
44
|
+
const db = await getDb();
|
|
45
|
+
const schema = getSchema();
|
|
46
|
+
const current = await collaboration.getState(collection, documentId);
|
|
47
|
+
const next: CollaborationState = {
|
|
48
|
+
reviewState: patch.reviewState ?? current.reviewState,
|
|
49
|
+
editor: patch.editor !== undefined ? patch.editor : current.editor,
|
|
50
|
+
};
|
|
51
|
+
const now = new Date().toISOString();
|
|
52
|
+
await db
|
|
53
|
+
.insert(schema.cmsCollaboration)
|
|
54
|
+
.values({ collection, documentId, reviewState: next.reviewState, editor: next.editor, updatedAt: now })
|
|
55
|
+
.onConflictDoUpdate({
|
|
56
|
+
target: [schema.cmsCollaboration.collection, schema.cmsCollaboration.documentId],
|
|
57
|
+
set: { reviewState: next.reviewState, editor: next.editor, updatedAt: now },
|
|
58
|
+
});
|
|
59
|
+
return next;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export const collaboration = {
|
|
63
|
+
// --- Review state + assignee ---
|
|
64
|
+
|
|
65
|
+
async getState(collection: string, documentId: string): Promise<CollaborationState> {
|
|
66
|
+
const db = await getDb();
|
|
67
|
+
const schema = getSchema();
|
|
68
|
+
const rows = await db
|
|
69
|
+
.select()
|
|
70
|
+
.from(schema.cmsCollaboration)
|
|
71
|
+
.where(
|
|
72
|
+
and(eq(schema.cmsCollaboration.collection, collection), eq(schema.cmsCollaboration.documentId, documentId)),
|
|
73
|
+
)
|
|
74
|
+
.limit(1);
|
|
75
|
+
return rowToState(rows[0]);
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
async getStatesForDocs(collection: string, documentIds: string[]): Promise<Record<string, CollaborationState>> {
|
|
79
|
+
const result: Record<string, CollaborationState> = {};
|
|
80
|
+
if (documentIds.length === 0) return result;
|
|
81
|
+
const db = await getDb();
|
|
82
|
+
const schema = getSchema();
|
|
83
|
+
const rows = await db
|
|
84
|
+
.select()
|
|
85
|
+
.from(schema.cmsCollaboration)
|
|
86
|
+
.where(
|
|
87
|
+
and(
|
|
88
|
+
eq(schema.cmsCollaboration.collection, collection),
|
|
89
|
+
inArray(schema.cmsCollaboration.documentId, documentIds),
|
|
90
|
+
),
|
|
91
|
+
);
|
|
92
|
+
for (const row of rows as any[]) result[String(row.documentId)] = rowToState(row);
|
|
93
|
+
return result;
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
// Docs this user is the editor of, across collections.
|
|
97
|
+
async assignedTo(
|
|
98
|
+
userId: string,
|
|
99
|
+
): Promise<Array<{ collection: string; documentId: string; reviewState: ReviewState }>> {
|
|
100
|
+
const db = await getDb();
|
|
101
|
+
const schema = getSchema();
|
|
102
|
+
const rows = await db.select().from(schema.cmsCollaboration).where(eq(schema.cmsCollaboration.editor, userId));
|
|
103
|
+
return (rows as any[]).map((r) => ({
|
|
104
|
+
collection: String(r.collection),
|
|
105
|
+
documentId: String(r.documentId),
|
|
106
|
+
reviewState: isReviewState(r.reviewState) ? r.reviewState : DEFAULT_STATE,
|
|
107
|
+
}));
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
async setReviewState(
|
|
111
|
+
collection: string,
|
|
112
|
+
documentId: string,
|
|
113
|
+
reviewState: ReviewState,
|
|
114
|
+
actor: AuditActor,
|
|
115
|
+
): Promise<CollaborationState> {
|
|
116
|
+
if (!isReviewState(reviewState)) throw new Error(`Invalid review state "${reviewState}".`);
|
|
117
|
+
const next = await upsertState(collection, documentId, { reviewState });
|
|
118
|
+
await recordAudit({
|
|
119
|
+
action: `collab.review.${reviewState}`,
|
|
120
|
+
resourceType: "content",
|
|
121
|
+
resourceCollection: collection,
|
|
122
|
+
resourceId: documentId,
|
|
123
|
+
actor,
|
|
124
|
+
});
|
|
125
|
+
return next;
|
|
126
|
+
},
|
|
127
|
+
|
|
128
|
+
// Submit for review; claim editor if unset.
|
|
129
|
+
async submitForReview(collection: string, documentId: string, actor: AuditActor): Promise<CollaborationState> {
|
|
130
|
+
const current = await collaboration.getState(collection, documentId);
|
|
131
|
+
const next = await upsertState(collection, documentId, {
|
|
132
|
+
editor: current.editor ?? actor?.id ?? null,
|
|
133
|
+
reviewState: "ready_for_review",
|
|
134
|
+
});
|
|
135
|
+
await recordAudit({
|
|
136
|
+
action: "collab.review.ready_for_review",
|
|
137
|
+
resourceType: "content",
|
|
138
|
+
resourceCollection: collection,
|
|
139
|
+
resourceId: documentId,
|
|
140
|
+
actor,
|
|
141
|
+
});
|
|
142
|
+
return next;
|
|
143
|
+
},
|
|
144
|
+
|
|
145
|
+
async setEditor(
|
|
146
|
+
collection: string,
|
|
147
|
+
documentId: string,
|
|
148
|
+
editor: string | null,
|
|
149
|
+
actor: AuditActor,
|
|
150
|
+
): Promise<CollaborationState> {
|
|
151
|
+
const next = await upsertState(collection, documentId, { editor: editor || null });
|
|
152
|
+
await recordAudit({
|
|
153
|
+
action: editor ? "collab.editor.set" : "collab.editor.clear",
|
|
154
|
+
resourceType: "content",
|
|
155
|
+
resourceCollection: collection,
|
|
156
|
+
resourceId: documentId,
|
|
157
|
+
actor,
|
|
158
|
+
});
|
|
159
|
+
return next;
|
|
160
|
+
},
|
|
161
|
+
|
|
162
|
+
// --- Comments ---
|
|
163
|
+
|
|
164
|
+
async listComments(collection: string, documentId: string): Promise<CommentRecord[]> {
|
|
165
|
+
const db = await getDb();
|
|
166
|
+
const schema = getSchema();
|
|
167
|
+
const rows = await db
|
|
168
|
+
.select()
|
|
169
|
+
.from(schema.cmsComments)
|
|
170
|
+
.where(and(eq(schema.cmsComments.collection, collection), eq(schema.cmsComments.documentId, documentId)))
|
|
171
|
+
.orderBy(desc(schema.cmsComments.createdAt));
|
|
172
|
+
return rows as CommentRecord[];
|
|
173
|
+
},
|
|
174
|
+
|
|
175
|
+
async addComment(
|
|
176
|
+
collection: string,
|
|
177
|
+
documentId: string,
|
|
178
|
+
input: { body: string; field?: string | null },
|
|
179
|
+
actor: AuditActor,
|
|
180
|
+
): Promise<CommentRecord> {
|
|
181
|
+
const body = input.body.trim();
|
|
182
|
+
if (!body) throw new Error("Comment body is required.");
|
|
183
|
+
const db = await getDb();
|
|
184
|
+
const schema = getSchema();
|
|
185
|
+
const record: CommentRecord = {
|
|
186
|
+
_id: nanoid(),
|
|
187
|
+
collection,
|
|
188
|
+
documentId,
|
|
189
|
+
field: input.field ?? null,
|
|
190
|
+
body,
|
|
191
|
+
authorId: actor?.id ?? null,
|
|
192
|
+
authorEmail: actor?.email ?? null,
|
|
193
|
+
resolved: false,
|
|
194
|
+
createdAt: new Date().toISOString(),
|
|
195
|
+
};
|
|
196
|
+
await db.insert(schema.cmsComments).values(record);
|
|
197
|
+
await recordAudit({
|
|
198
|
+
action: "collab.comment",
|
|
199
|
+
resourceType: "content",
|
|
200
|
+
resourceCollection: collection,
|
|
201
|
+
resourceId: documentId,
|
|
202
|
+
actor,
|
|
203
|
+
});
|
|
204
|
+
return record;
|
|
205
|
+
},
|
|
206
|
+
|
|
207
|
+
async getComment(id: string): Promise<CommentRecord | null> {
|
|
208
|
+
const db = await getDb();
|
|
209
|
+
const schema = getSchema();
|
|
210
|
+
const rows = await db.select().from(schema.cmsComments).where(eq(schema.cmsComments._id, id)).limit(1);
|
|
211
|
+
const row = rows[0] as any;
|
|
212
|
+
if (!row) return null;
|
|
213
|
+
return {
|
|
214
|
+
_id: row._id,
|
|
215
|
+
collection: row.collection,
|
|
216
|
+
documentId: row.documentId,
|
|
217
|
+
field: row.field ?? null,
|
|
218
|
+
body: row.body,
|
|
219
|
+
authorId: row.authorId ?? null,
|
|
220
|
+
authorEmail: row.authorEmail ?? null,
|
|
221
|
+
resolved: !!row.resolved,
|
|
222
|
+
createdAt: row.createdAt,
|
|
223
|
+
};
|
|
224
|
+
},
|
|
225
|
+
|
|
226
|
+
async resolveComment(id: string, resolved: boolean, actor: AuditActor): Promise<void> {
|
|
227
|
+
const db = await getDb();
|
|
228
|
+
const schema = getSchema();
|
|
229
|
+
const rows = await db.select().from(schema.cmsComments).where(eq(schema.cmsComments._id, id)).limit(1);
|
|
230
|
+
const row = rows[0] as any;
|
|
231
|
+
if (!row) throw new Error("Comment not found.");
|
|
232
|
+
await db.update(schema.cmsComments).set({ resolved }).where(eq(schema.cmsComments._id, id));
|
|
233
|
+
await recordAudit({
|
|
234
|
+
action: resolved ? "collab.comment.resolve" : "collab.comment.reopen",
|
|
235
|
+
resourceType: "content",
|
|
236
|
+
resourceCollection: row.collection,
|
|
237
|
+
resourceId: row.documentId,
|
|
238
|
+
actor,
|
|
239
|
+
});
|
|
240
|
+
},
|
|
241
|
+
|
|
242
|
+
async deleteComment(id: string, actor: AuditActor): Promise<void> {
|
|
243
|
+
const db = await getDb();
|
|
244
|
+
const schema = getSchema();
|
|
245
|
+
const rows = await db.select().from(schema.cmsComments).where(eq(schema.cmsComments._id, id)).limit(1);
|
|
246
|
+
const row = rows[0] as any;
|
|
247
|
+
if (!row) return;
|
|
248
|
+
await db.delete(schema.cmsComments).where(eq(schema.cmsComments._id, id));
|
|
249
|
+
await recordAudit({
|
|
250
|
+
action: "collab.comment.delete",
|
|
251
|
+
resourceType: "content",
|
|
252
|
+
resourceCollection: row.collection,
|
|
253
|
+
resourceId: row.documentId,
|
|
254
|
+
actor,
|
|
255
|
+
});
|
|
256
|
+
},
|
|
257
|
+
|
|
258
|
+
// --- Activity (derived from the audit log for this document) ---
|
|
259
|
+
|
|
260
|
+
async getActivity(collection: string, documentId: string, limit = 25): Promise<ActivityRecord[]> {
|
|
261
|
+
const db = await getDb();
|
|
262
|
+
const schema = getSchema();
|
|
263
|
+
const rows = await db
|
|
264
|
+
.select({
|
|
265
|
+
action: schema.cmsAuditLog.action,
|
|
266
|
+
actorId: schema.cmsAuditLog.actorId,
|
|
267
|
+
actorEmail: schema.cmsAuditLog.actorEmail,
|
|
268
|
+
timestamp: schema.cmsAuditLog.timestamp,
|
|
269
|
+
})
|
|
270
|
+
.from(schema.cmsAuditLog)
|
|
271
|
+
.where(and(eq(schema.cmsAuditLog.resourceCollection, collection), eq(schema.cmsAuditLog.resourceId, documentId)))
|
|
272
|
+
.orderBy(desc(schema.cmsAuditLog.timestamp))
|
|
273
|
+
.limit(limit);
|
|
274
|
+
return rows as ActivityRecord[];
|
|
275
|
+
},
|
|
276
|
+
};
|
package/core/content.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export function parseBlocks(value: unknown): Array<Record<string, any>> {
|
|
2
|
+
if (!value) return [];
|
|
3
|
+
try {
|
|
4
|
+
const parsed = typeof value === "string" ? JSON.parse(value) : value;
|
|
5
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
6
|
+
} catch {
|
|
7
|
+
return [];
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function parseList<T = Record<string, any>>(value: unknown): T[] {
|
|
12
|
+
if (Array.isArray(value)) return value as T[];
|
|
13
|
+
if (typeof value === "string") {
|
|
14
|
+
try {
|
|
15
|
+
const parsed = JSON.parse(value);
|
|
16
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
17
|
+
} catch {
|
|
18
|
+
return [];
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function cacheTags(collection: string, docId: string): string[] {
|
|
25
|
+
const singular = collection.endsWith("s") ? collection.slice(0, -1) : collection;
|
|
26
|
+
return [collection, `${singular}:${docId}`];
|
|
27
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { nanoid } from "nanoid";
|
|
2
|
+
|
|
3
|
+
import { hashPassword } from "./auth";
|
|
4
|
+
import { getDb } from "./runtime";
|
|
5
|
+
import { getSchema } from "./schema";
|
|
6
|
+
|
|
7
|
+
export const createAdminUser = async (input: { name: string; email: string; password: string }) => {
|
|
8
|
+
const db = await getDb();
|
|
9
|
+
const schema = getSchema();
|
|
10
|
+
const tables = schema.cmsTables as Record<string, { main: any }>;
|
|
11
|
+
|
|
12
|
+
if (!tables.users) {
|
|
13
|
+
throw new Error("No users collection found.");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const now = new Date().toISOString();
|
|
17
|
+
const hashedPassword = await hashPassword(input.password);
|
|
18
|
+
|
|
19
|
+
await db.insert(tables.users.main).values({
|
|
20
|
+
_id: nanoid(),
|
|
21
|
+
name: input.name,
|
|
22
|
+
email: input.email,
|
|
23
|
+
password: hashedPassword,
|
|
24
|
+
role: "admin",
|
|
25
|
+
_createdAt: now,
|
|
26
|
+
_updatedAt: now,
|
|
27
|
+
});
|
|
28
|
+
};
|