qarpeo 0.1.32 → 0.1.34

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.
Files changed (57) hide show
  1. package/README.md +5 -7
  2. package/dist/chunks/auth-schema.mjs +12 -10
  3. package/dist/chunks/wrangler.mjs +1 -1
  4. package/dist/module.d.ts +1 -0
  5. package/dist/module.mjs +284 -100
  6. package/dist/runtime/app/components/Comments.vue +411 -0
  7. package/dist/runtime/app/composables/cms.d.ts +11 -7
  8. package/dist/runtime/app/composables/cms.mjs +36 -68
  9. package/dist/runtime/app/composables/comments.d.ts +45 -0
  10. package/dist/runtime/app/composables/comments.mjs +150 -0
  11. package/dist/runtime/app/composables/organization.d.ts +3 -3
  12. package/dist/runtime/server/db/cms-schema.d.ts +1 -1
  13. package/dist/runtime/server/db/cms-schema.mjs +1 -2
  14. package/dist/runtime/server/routes/cms/[collection]/index.get.mjs +2 -0
  15. package/dist/runtime/server/routes/cms/publish-scheduled.post.mjs +7 -4
  16. package/dist/runtime/server/routes/cms/subscribers/[id].patch.mjs +9 -2
  17. package/dist/runtime/server/routes/cms/webhooks/[provider].post.mjs +41 -28
  18. package/dist/runtime/server/routes/comments/[id]/react.post.d.ts +6 -0
  19. package/dist/runtime/server/routes/comments/[id]/react.post.mjs +35 -0
  20. package/dist/runtime/server/routes/{cms/comments/[id].patch.d.ts → comments/[id]/report.post.d.ts} +1 -2
  21. package/dist/runtime/server/routes/comments/[id]/report.post.mjs +50 -0
  22. package/dist/runtime/server/routes/{cms/comments → comments}/[id].delete.d.ts +0 -1
  23. package/dist/runtime/server/routes/comments/[id].delete.mjs +27 -0
  24. package/dist/runtime/server/routes/{cms/comments → comments}/[id].get.d.ts +1 -1
  25. package/dist/runtime/server/routes/comments/[id].get.mjs +14 -0
  26. package/dist/runtime/server/routes/comments/[id].patch.d.ts +4 -0
  27. package/dist/runtime/server/routes/comments/[id].patch.mjs +37 -0
  28. package/dist/runtime/server/routes/{cms/comments.get.d.ts → comments/index.get.d.ts} +1 -1
  29. package/dist/runtime/server/routes/comments/index.get.mjs +34 -0
  30. package/dist/runtime/server/routes/comments/index.post.d.ts +4 -0
  31. package/dist/runtime/server/routes/comments/index.post.mjs +36 -0
  32. package/dist/runtime/server/utils/audit.d.ts +3 -3
  33. package/dist/runtime/server/utils/audit.mjs +43 -17
  34. package/dist/runtime/server/utils/auth.d.ts +55 -0
  35. package/dist/runtime/server/utils/auth.mjs +92 -10
  36. package/dist/runtime/server/utils/cms/git.mjs +2 -6
  37. package/dist/runtime/server/utils/cms.d.ts +17 -22
  38. package/dist/runtime/server/utils/cms.mjs +144 -309
  39. package/dist/runtime/server/utils/comments.d.ts +112 -0
  40. package/dist/runtime/server/utils/comments.mjs +450 -0
  41. package/dist/runtime/server/utils/config.d.ts +2 -1
  42. package/dist/runtime/server/utils/config.mjs +1 -0
  43. package/dist/runtime/server/utils/urn.d.ts +15 -0
  44. package/dist/runtime/server/utils/urn.mjs +20 -0
  45. package/dist/runtime/server.d.ts +4 -0
  46. package/dist/runtime/server.mjs +5 -0
  47. package/dist/runtime/types/auth.d.ts +12 -1
  48. package/dist/types.d.ts +67 -27
  49. package/dist/utils/comments-schema.d.ts +13 -0
  50. package/package.json +4 -4
  51. package/dist/runtime/app/components/CMSComments.vue +0 -202
  52. package/dist/runtime/server/routes/cms/comments/[id].delete.mjs +0 -12
  53. package/dist/runtime/server/routes/cms/comments/[id].get.mjs +0 -13
  54. package/dist/runtime/server/routes/cms/comments/[id].patch.mjs +0 -17
  55. package/dist/runtime/server/routes/cms/comments.get.mjs +0 -43
  56. package/dist/runtime/server/routes/cms/comments.post.d.ts +0 -17
  57. package/dist/runtime/server/routes/cms/comments.post.mjs +0 -46
@@ -0,0 +1,112 @@
1
+ import type { RequestEvent } from "nuxt/server";
2
+ import type { CommentsOptions } from "../../../types";
3
+ export { isValidTargetUrn, validateTargetUrn } from "./urn";
4
+ export type CommentStatus = "pending" | "approved" | "spam" | "deleted";
5
+ export type ReportReason = "spam" | "harassment" | "off-topic" | "misinformation" | "other";
6
+ export interface Comment {
7
+ id: string;
8
+ targetUrn: string;
9
+ tenantId?: string;
10
+ parentId?: string;
11
+ path: string;
12
+ depth: number;
13
+ authorName: string;
14
+ authorEmail?: string;
15
+ authorAvatar?: string;
16
+ content: string;
17
+ status: CommentStatus;
18
+ deletedAt?: number;
19
+ reportCount: number;
20
+ reactionCounts: Record<string, number>;
21
+ metadata: Record<string, unknown>;
22
+ createdAt: number;
23
+ updatedAt: number;
24
+ replies?: Comment[];
25
+ }
26
+ export interface CommentReport {
27
+ id: string;
28
+ commentId: string;
29
+ reporterIp?: string;
30
+ reporterUserId?: string;
31
+ reason: ReportReason;
32
+ note?: string;
33
+ createdAt: number;
34
+ }
35
+ export interface CommentReaction {
36
+ id: string;
37
+ commentId: string;
38
+ userId?: string;
39
+ ip?: string;
40
+ reaction: string;
41
+ createdAt: number;
42
+ }
43
+ export interface CreateCommentInput {
44
+ targetUrn: string;
45
+ parentId?: string;
46
+ authorName: string;
47
+ authorEmail?: string;
48
+ content: string;
49
+ tenantId?: string;
50
+ metadata?: Record<string, unknown>;
51
+ turnstileToken?: string;
52
+ }
53
+ export interface QueryCommentsOptions {
54
+ targetUrn: string;
55
+ status?: CommentStatus | CommentStatus[];
56
+ parentId?: string | null;
57
+ tenantId?: string;
58
+ limit?: number;
59
+ offset?: number;
60
+ orderBy?: "asc" | "desc";
61
+ /** Whether to include replies nested under each root comment */
62
+ threaded?: boolean;
63
+ }
64
+ export declare function getCommentsConfig(event?: RequestEvent): CommentsOptions & {
65
+ prefix?: string;
66
+ };
67
+ /**
68
+ * Creates all three comments tables if they do not already exist.
69
+ * Uses a module-level promise cache so the 10+ SQL statements only execute once
70
+ * per Worker isolate — subsequent calls are free no-ops.
71
+ */
72
+ export declare function ensureCommentsTables(event?: RequestEvent): Promise<void>;
73
+ /**
74
+ * Fetches comments for a target URN. Supports flat or threaded (nested replies) output.
75
+ */
76
+ export declare function queryComments(opts: QueryCommentsOptions, event?: RequestEvent): Promise<{
77
+ comments: Comment[];
78
+ total: number;
79
+ }>;
80
+ export declare function getComment(id: string, event?: RequestEvent): Promise<Comment | null>;
81
+ /**
82
+ * Creates a new comment with rate limiting, auth checks, length validation,
83
+ * materialized path threading, and avatar generation.
84
+ */
85
+ export declare function createComment(input: CreateCommentInput, event?: RequestEvent): Promise<Comment>;
86
+ export declare function updateCommentStatus(id: string, status: CommentStatus, event?: RequestEvent): Promise<Comment | null>;
87
+ /**
88
+ * Soft-deletes a comment, retaining tree structure.
89
+ * Sets `deletedAt`, `status = "deleted"`, and clears PII fields.
90
+ * Content is replaced with "[deleted]" at read time.
91
+ */
92
+ export declare function deleteComment(id: string, event?: RequestEvent): Promise<void>;
93
+ /**
94
+ * Submits a community report for a comment.
95
+ * Auto-hides the comment when the report count exceeds the configured threshold.
96
+ */
97
+ export declare function reportComment(commentId: string, reason: ReportReason, opts?: {
98
+ note?: string;
99
+ userId?: string;
100
+ }, event?: RequestEvent): Promise<CommentReport>;
101
+ /**
102
+ * Toggles a reaction on a comment (adds if not present, removes if already reacted).
103
+ * Updates the `reaction_counts` JSON denormalisation on the comment row.
104
+ *
105
+ * @returns The updated reaction counts map.
106
+ */
107
+ export declare function reactToComment(commentId: string, reaction: string, opts?: {
108
+ userId?: string;
109
+ }, event?: RequestEvent): Promise<{
110
+ added: boolean;
111
+ reactionCounts: Record<string, number>;
112
+ }>;
@@ -0,0 +1,450 @@
1
+ import { createError, getRequestHeader } from "nuxt/server";
2
+ import { getCloudflareEnv } from "../../bindings.mjs";
3
+ import { getQarpeoConfig } from "./config.mjs";
4
+ import { assertRateLimit } from "./ratelimit.mjs";
5
+ import { getAuthContext } from "./context.mjs";
6
+ import { nanoid } from "./crypto.mjs";
7
+ import { validateTargetUrn } from "./urn.mjs";
8
+ export { isValidTargetUrn, validateTargetUrn } from "./urn.mjs";
9
+ function getD1(event) {
10
+ const env = getCloudflareEnv(event);
11
+ const bindingName = env.QARPEO_DEFAULT_DB_BINDING || process.env.QARPEO_DEFAULT_DB_BINDING || "DB";
12
+ const db = env[bindingName];
13
+ if (!db) throw new Error("[qarpeo/comments] D1 database binding not found");
14
+ return db;
15
+ }
16
+ function getTable() {
17
+ return "_qarpeo_comments";
18
+ }
19
+ function getReportsTable() {
20
+ return "_qarpeo_comment_reports";
21
+ }
22
+ function getReactionsTable() {
23
+ return "_qarpeo_comment_reactions";
24
+ }
25
+ export function getCommentsConfig(event) {
26
+ const cfg = getQarpeoConfig(event).comments || {};
27
+ return {
28
+ requireAuth: cfg.requireAuth ?? process.env.QARPEO_COMMENTS_REQUIRE_AUTH === "1",
29
+ defaultStatus: (cfg.defaultStatus ?? process.env.QARPEO_COMMENTS_DEFAULT_STATUS) || "pending",
30
+ autoApproveAuth: cfg.autoApproveAuth ?? process.env.QARPEO_COMMENTS_AUTO_APPROVE_AUTH === "1",
31
+ threadDepth: Number(cfg.threadDepth) || Number(process.env.QARPEO_COMMENTS_THREAD_DEPTH) || 3,
32
+ maxLength: Number(cfg.maxLength) || Number(process.env.QARPEO_COMMENTS_MAX_LENGTH) || 5e3,
33
+ reporting: cfg.reporting || {
34
+ autoHideThreshold: Number(process.env.QARPEO_COMMENTS_AUTO_HIDE_THRESHOLD) || 5
35
+ },
36
+ rateLimit: cfg.rateLimit,
37
+ turnstile: cfg.turnstile,
38
+ reactions: cfg.reactions,
39
+ roles: cfg.roles,
40
+ prefix: cfg.prefix || "/api/comments"
41
+ };
42
+ }
43
+ function getDefaultStatus(event) {
44
+ return getCommentsConfig(event).defaultStatus || "pending";
45
+ }
46
+ function getThreadDepth(event) {
47
+ return getCommentsConfig(event).threadDepth || 3;
48
+ }
49
+ function getMaxLength(event) {
50
+ return getCommentsConfig(event).maxLength || 5e3;
51
+ }
52
+ function getAutoHideThreshold(event) {
53
+ const cfg = getCommentsConfig(event);
54
+ if (typeof cfg.reporting === "object" && cfg.reporting?.autoHideThreshold) {
55
+ return Number(cfg.reporting.autoHideThreshold);
56
+ }
57
+ return Number(process.env.QARPEO_COMMENTS_AUTO_HIDE_THRESHOLD) || 5;
58
+ }
59
+ function getRequireAuth(event) {
60
+ return Boolean(getCommentsConfig(event).requireAuth);
61
+ }
62
+ function getCallerIp(event) {
63
+ if (!event) return "unknown";
64
+ const forwarded = getRequestHeader(event, "x-forwarded-for") || "";
65
+ return forwarded.split(",")[0]?.trim() || getRequestHeader(event, "cf-connecting-ip") || "unknown";
66
+ }
67
+ function rowToComment(row) {
68
+ return {
69
+ id: row.id,
70
+ targetUrn: row.target_urn,
71
+ tenantId: row.tenant_id ?? void 0,
72
+ parentId: row.parent_id ?? void 0,
73
+ path: row.path,
74
+ depth: row.depth,
75
+ authorName: row.author_name,
76
+ authorEmail: row.author_email ?? void 0,
77
+ authorAvatar: row.author_avatar ?? void 0,
78
+ content: row.deleted_at ? "[deleted]" : row.content,
79
+ status: row.status,
80
+ deletedAt: row.deleted_at ?? void 0,
81
+ reportCount: row.report_count,
82
+ reactionCounts: safeJsonParse(row.reaction_counts, {}),
83
+ metadata: safeJsonParse(row.metadata_json, {}),
84
+ createdAt: row.created_at,
85
+ updatedAt: row.updated_at
86
+ };
87
+ }
88
+ function safeJsonParse(raw, fallback) {
89
+ if (!raw) return fallback;
90
+ try {
91
+ return JSON.parse(raw);
92
+ } catch {
93
+ return fallback;
94
+ }
95
+ }
96
+ function generateAvatarSvg(name) {
97
+ const initials = name.split(/\s+/).slice(0, 2).map((w) => w[0]?.toUpperCase() ?? "").join("");
98
+ let hash = 0;
99
+ for (let i = 0; i < name.length; i++) {
100
+ hash = (hash << 5) - hash + name.charCodeAt(i) | 0;
101
+ }
102
+ const hue = Math.abs(hash) % 360;
103
+ const bg = `hsl(${hue},60%,45%)`;
104
+ const fg = "#ffffff";
105
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40"><circle cx="20" cy="20" r="20" fill="${bg}"/><text x="20" y="25" text-anchor="middle" font-family="system-ui,sans-serif" font-size="16" font-weight="600" fill="${fg}">${initials}</text></svg>`;
106
+ return `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
107
+ }
108
+ function buildPath(parentPath, siblingIndex) {
109
+ const segment = String(siblingIndex + 1).padStart(4, "0");
110
+ return `${parentPath}${segment}/`;
111
+ }
112
+ let _ensureCommentsTablesPromise = null;
113
+ export async function ensureCommentsTables(event) {
114
+ if (_ensureCommentsTablesPromise) return _ensureCommentsTablesPromise;
115
+ const db = getD1(event);
116
+ const t = getTable();
117
+ const rt = getReportsTable();
118
+ const rxt = getReactionsTable();
119
+ _ensureCommentsTablesPromise = db.batch([
120
+ db.prepare(`CREATE TABLE IF NOT EXISTS ${t} (
121
+ id TEXT PRIMARY KEY,
122
+ target_urn TEXT NOT NULL,
123
+ tenant_id TEXT,
124
+ parent_id TEXT,
125
+ path TEXT NOT NULL DEFAULT '/',
126
+ depth INTEGER NOT NULL DEFAULT 0,
127
+ author_name TEXT NOT NULL,
128
+ author_email TEXT,
129
+ author_avatar TEXT,
130
+ author_ip TEXT,
131
+ content TEXT NOT NULL,
132
+ status TEXT NOT NULL DEFAULT 'pending',
133
+ deleted_at INTEGER,
134
+ report_count INTEGER NOT NULL DEFAULT 0,
135
+ reaction_counts TEXT NOT NULL DEFAULT '{}',
136
+ metadata_json TEXT NOT NULL DEFAULT '{}',
137
+ created_at INTEGER NOT NULL,
138
+ updated_at INTEGER NOT NULL
139
+ )`),
140
+ db.prepare(
141
+ `CREATE INDEX IF NOT EXISTS idx_qarpeo_comments_target ON ${t}(target_urn, status, created_at DESC)`
142
+ ),
143
+ db.prepare(`CREATE INDEX IF NOT EXISTS idx_qarpeo_comments_parent ON ${t}(parent_id)`),
144
+ db.prepare(`CREATE INDEX IF NOT EXISTS idx_qarpeo_comments_path ON ${t}(path)`),
145
+ db.prepare(`CREATE INDEX IF NOT EXISTS idx_qarpeo_comments_tenant ON ${t}(tenant_id)`),
146
+ db.prepare(`CREATE TABLE IF NOT EXISTS ${rt} (
147
+ id TEXT PRIMARY KEY,
148
+ comment_id TEXT NOT NULL,
149
+ reporter_ip TEXT,
150
+ reporter_user_id TEXT,
151
+ reason TEXT NOT NULL,
152
+ note TEXT,
153
+ created_at INTEGER NOT NULL
154
+ )`),
155
+ db.prepare(
156
+ `CREATE INDEX IF NOT EXISTS idx_qarpeo_reports_comment ON ${rt}(comment_id)`
157
+ ),
158
+ db.prepare(`CREATE TABLE IF NOT EXISTS ${rxt} (
159
+ id TEXT PRIMARY KEY,
160
+ comment_id TEXT NOT NULL,
161
+ user_id TEXT,
162
+ ip TEXT,
163
+ reaction TEXT NOT NULL,
164
+ created_at INTEGER NOT NULL
165
+ )`),
166
+ db.prepare(
167
+ `CREATE INDEX IF NOT EXISTS idx_qarpeo_reactions_comment ON ${rxt}(comment_id)`
168
+ )
169
+ ]).then(() => void 0).catch((err) => {
170
+ _ensureCommentsTablesPromise = null;
171
+ throw err;
172
+ });
173
+ return _ensureCommentsTablesPromise;
174
+ }
175
+ export async function queryComments(opts, event) {
176
+ validateTargetUrn(opts.targetUrn);
177
+ const db = getD1(event);
178
+ const t = getTable();
179
+ const statuses = opts.status ? Array.isArray(opts.status) ? opts.status : [opts.status] : ["approved"];
180
+ const placeholders = statuses.map(() => "?").join(", ");
181
+ const limit = Math.min(opts.limit ?? 50, 200);
182
+ const offset = opts.offset ?? 0;
183
+ const order = opts.orderBy === "asc" ? "ASC" : "DESC";
184
+ let whereClause = `target_urn = ? AND status IN (${placeholders})`;
185
+ const params = [opts.targetUrn, ...statuses];
186
+ if (opts.tenantId !== void 0) {
187
+ whereClause += " AND tenant_id = ?";
188
+ params.push(opts.tenantId);
189
+ }
190
+ if (opts.threaded) {
191
+ whereClause += " AND parent_id IS NULL";
192
+ } else if (opts.parentId !== void 0) {
193
+ if (opts.parentId === null) {
194
+ whereClause += " AND parent_id IS NULL";
195
+ } else {
196
+ whereClause += " AND parent_id = ?";
197
+ params.push(opts.parentId);
198
+ }
199
+ }
200
+ const countResult = await db.prepare(`SELECT COUNT(*) as cnt FROM ${t} WHERE ${whereClause}`).bind(...params).first();
201
+ const total = countResult?.cnt ?? 0;
202
+ const rows = await db.prepare(
203
+ `SELECT * FROM ${t} WHERE ${whereClause} ORDER BY created_at ${order} LIMIT ? OFFSET ?`
204
+ ).bind(...params, limit, offset).all();
205
+ const rootComments = (rows.results ?? []).map(rowToComment);
206
+ if (!opts.threaded) {
207
+ await populateReactionCounts(db, rootComments);
208
+ return { comments: rootComments, total };
209
+ }
210
+ if (rootComments.length === 0) return { comments: [], total };
211
+ const maxDepth = getThreadDepth(event);
212
+ const pathConditions = rootComments.map(() => `path LIKE ?`).join(" OR ");
213
+ const pathParams = rootComments.map((c) => `${c.path}%`);
214
+ const descendantStatuses = statuses;
215
+ const descendantPlaceholders = descendantStatuses.map(() => "?").join(", ");
216
+ const descendantRows = await db.prepare(
217
+ `SELECT * FROM ${t} WHERE (${pathConditions}) AND status IN (${descendantPlaceholders}) AND depth <= ? AND parent_id IS NOT NULL ORDER BY path ASC, created_at ASC`
218
+ ).bind(...pathParams, ...descendantStatuses, maxDepth).all();
219
+ const allDescendants = (descendantRows.results ?? []).map(rowToComment);
220
+ const byId = /* @__PURE__ */ new Map();
221
+ for (const c of rootComments) byId.set(c.id, { ...c, replies: [] });
222
+ for (const c of allDescendants) byId.set(c.id, { ...c, replies: [] });
223
+ await populateReactionCounts(db, [...byId.values()]);
224
+ const roots = [];
225
+ for (const c of rootComments) roots.push(byId.get(c.id));
226
+ for (const c of allDescendants) {
227
+ if (c.parentId && byId.has(c.parentId)) {
228
+ byId.get(c.parentId).replies.push(byId.get(c.id));
229
+ }
230
+ }
231
+ return { comments: roots, total };
232
+ }
233
+ async function populateReactionCounts(db, comments) {
234
+ if (comments.length === 0) return;
235
+ const ids = comments.map((c) => c.id);
236
+ const placeholders = ids.map(() => "?").join(", ");
237
+ const rxRows = await db.prepare(
238
+ `SELECT comment_id, reaction, COUNT(*) as cnt FROM ${getReactionsTable()} WHERE comment_id IN (${placeholders}) GROUP BY comment_id, reaction`
239
+ ).bind(...ids).all().catch(() => ({ results: [] }));
240
+ const countsMap = /* @__PURE__ */ new Map();
241
+ for (const r of rxRows.results ?? []) {
242
+ if (!countsMap.has(r.comment_id)) countsMap.set(r.comment_id, {});
243
+ countsMap.get(r.comment_id)[r.reaction] = r.cnt;
244
+ }
245
+ for (const c of comments) {
246
+ c.reactionCounts = countsMap.get(c.id) || {};
247
+ }
248
+ }
249
+ export async function getComment(id, event) {
250
+ const db = getD1(event);
251
+ const row = await db.prepare(`SELECT * FROM ${getTable()} WHERE id = ?`).bind(id).first();
252
+ if (!row) return null;
253
+ const comment = rowToComment(row);
254
+ await populateReactionCounts(db, [comment]);
255
+ return comment;
256
+ }
257
+ export async function createComment(input, event) {
258
+ validateTargetUrn(input.targetUrn);
259
+ const cfg = getCommentsConfig(event);
260
+ const requireAuth = getRequireAuth(event);
261
+ const maxLength = getMaxLength(event);
262
+ const t = getTable();
263
+ const auth = event ? await getAuthContext(event).catch(() => null) : null;
264
+ if (requireAuth && !auth?.user?.id) {
265
+ throw createError({ statusCode: 401, statusMessage: "Authentication required to comment." });
266
+ }
267
+ if (event) {
268
+ const ip2 = getCallerIp(event);
269
+ await assertRateLimit(event, {
270
+ key: `comments:create:${ip2}`,
271
+ max: cfg.rateLimit?.max || Number(process.env.QARPEO_COMMENTS_RATE_LIMIT_MAX) || 5,
272
+ window: cfg.rateLimit?.window || "1m",
273
+ message: "You are posting too quickly. Please wait before submitting another comment."
274
+ });
275
+ }
276
+ const content = (input.content ?? "").trim();
277
+ if (!content) {
278
+ throw createError({ statusCode: 400, statusMessage: "Comment content is required." });
279
+ }
280
+ if (content.length > maxLength) {
281
+ throw createError({
282
+ statusCode: 400,
283
+ statusMessage: `Comment must be ${maxLength} characters or fewer.`
284
+ });
285
+ }
286
+ const authorName = (input.authorName ?? auth?.user?.name ?? "Anonymous").trim();
287
+ if (!authorName) {
288
+ throw createError({ statusCode: 400, statusMessage: "Author name is required." });
289
+ }
290
+ if (input.turnstileToken && process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY) {
291
+ const cfRes = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
292
+ method: "POST",
293
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
294
+ body: new URLSearchParams({
295
+ secret: process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY,
296
+ response: input.turnstileToken
297
+ })
298
+ });
299
+ const cfJson = await cfRes.json();
300
+ if (!cfJson.success) {
301
+ throw createError({ statusCode: 403, statusMessage: "Turnstile verification failed." });
302
+ }
303
+ }
304
+ const db = getD1(event);
305
+ const id = nanoid();
306
+ const now = Date.now();
307
+ let path = "/";
308
+ let depth = 0;
309
+ if (input.parentId) {
310
+ const parent = await db.prepare(`SELECT id, path, depth, status FROM ${t} WHERE id = ?`).bind(input.parentId).first();
311
+ if (!parent) {
312
+ throw createError({ statusCode: 404, statusMessage: "Parent comment not found." });
313
+ }
314
+ if (parent.status === "deleted" || parent.status === "spam") {
315
+ throw createError({ statusCode: 400, statusMessage: "Cannot reply to a deleted comment." });
316
+ }
317
+ if (parent.depth >= getThreadDepth(event) - 1) {
318
+ throw createError({
319
+ statusCode: 400,
320
+ statusMessage: `Maximum thread depth of ${getThreadDepth(event)} reached.`
321
+ });
322
+ }
323
+ const siblingResult = await db.prepare(`SELECT COUNT(*) as cnt FROM ${t} WHERE parent_id = ?`).bind(input.parentId).first();
324
+ const siblingCount = siblingResult?.cnt ?? 0;
325
+ path = buildPath(parent.path, siblingCount);
326
+ depth = parent.depth + 1;
327
+ } else {
328
+ const siblingResult = await db.prepare(`SELECT COUNT(*) as cnt FROM ${t} WHERE target_urn = ? AND parent_id IS NULL`).bind(input.targetUrn).first();
329
+ const siblingCount = siblingResult?.cnt ?? 0;
330
+ path = buildPath("/", siblingCount);
331
+ }
332
+ let status = getDefaultStatus(event);
333
+ if (auth?.user?.id) {
334
+ const autoApprove = cfg.autoApproveAuth ?? process.env.QARPEO_COMMENTS_AUTO_APPROVE_AUTH === "1";
335
+ if (autoApprove) status = "approved";
336
+ const role = auth.user?.role || "";
337
+ if (role === "admin" || role === "super_admin" || role === "moderator") {
338
+ status = "approved";
339
+ }
340
+ }
341
+ const avatar = generateAvatarSvg(authorName);
342
+ const ip = event ? getCallerIp(event) : void 0;
343
+ await db.prepare(
344
+ `INSERT INTO ${t}
345
+ (id, target_urn, tenant_id, parent_id, path, depth,
346
+ author_name, author_email, author_avatar, author_ip,
347
+ content, status, report_count, reaction_counts, metadata_json,
348
+ created_at, updated_at)
349
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, '{}', ?, ?, ?)`
350
+ ).bind(
351
+ id,
352
+ input.targetUrn,
353
+ input.tenantId ?? null,
354
+ input.parentId ?? null,
355
+ path,
356
+ depth,
357
+ authorName,
358
+ input.authorEmail ?? null,
359
+ avatar,
360
+ ip ?? null,
361
+ content,
362
+ status,
363
+ JSON.stringify(input.metadata ?? {}),
364
+ now,
365
+ now
366
+ ).run();
367
+ return await getComment(id, event);
368
+ }
369
+ export async function updateCommentStatus(id, status, event) {
370
+ const db = getD1(event);
371
+ const now = Date.now();
372
+ await db.prepare(`UPDATE ${getTable()} SET status = ?, updated_at = ? WHERE id = ?`).bind(status, now, id).run();
373
+ return getComment(id, event);
374
+ }
375
+ export async function deleteComment(id, event) {
376
+ const db = getD1(event);
377
+ const now = Date.now();
378
+ const replyResult = await db.prepare(`SELECT COUNT(*) as cnt FROM ${getTable()} WHERE parent_id = ?`).bind(id).first();
379
+ const hasReplies = (replyResult?.cnt ?? 0) > 0;
380
+ if (hasReplies) {
381
+ await db.prepare(
382
+ `UPDATE ${getTable()}
383
+ SET status = 'deleted', deleted_at = ?, updated_at = ?,
384
+ content = '[deleted]', author_email = NULL, author_ip = NULL
385
+ WHERE id = ?`
386
+ ).bind(now, now, id).run();
387
+ } else {
388
+ await db.prepare(`DELETE FROM ${getTable()} WHERE id = ?`).bind(id).run();
389
+ await db.prepare(`DELETE FROM ${getReactionsTable()} WHERE comment_id = ?`).bind(id).run();
390
+ }
391
+ }
392
+ export async function reportComment(commentId, reason, opts, event) {
393
+ const db = getD1(event);
394
+ const id = nanoid();
395
+ const now = Date.now();
396
+ const ip = event ? getCallerIp(event) : void 0;
397
+ await db.prepare(
398
+ `INSERT INTO ${getReportsTable()} (id, comment_id, reporter_ip, reporter_user_id, reason, note, created_at)
399
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
400
+ ).bind(id, commentId, ip ?? null, opts?.userId ?? null, reason, opts?.note ?? null, now).run();
401
+ const updated = await db.prepare(
402
+ `UPDATE ${getTable()} SET report_count = report_count + 1, updated_at = ? WHERE id = ? RETURNING report_count`
403
+ ).bind(now, commentId).first();
404
+ if ((updated?.report_count ?? 0) >= getAutoHideThreshold(event)) {
405
+ await db.prepare(`UPDATE ${getTable()} SET status = 'spam', updated_at = ? WHERE id = ? AND status = 'approved'`).bind(now, commentId).run();
406
+ }
407
+ return { id, commentId, reporterIp: ip, reporterUserId: opts?.userId, reason, note: opts?.note, createdAt: now };
408
+ }
409
+ export async function reactToComment(commentId, reaction, opts, event) {
410
+ const db = getD1(event);
411
+ const ip = event ? getCallerIp(event) : void 0;
412
+ const now = Date.now();
413
+ const allowedReactions = process.env.QARPEO_COMMENTS_REACTIONS ? JSON.parse(process.env.QARPEO_COMMENTS_REACTIONS) : ["like", "heart", "fire", "unicorn"];
414
+ if (!allowedReactions.includes(reaction)) {
415
+ throw createError({
416
+ statusCode: 400,
417
+ statusMessage: `Reaction "${reaction}" is not allowed. Allowed: ${allowedReactions.join(", ")}`
418
+ });
419
+ }
420
+ let existing = null;
421
+ if (opts?.userId) {
422
+ existing = await db.prepare(
423
+ `SELECT id FROM ${getReactionsTable()} WHERE comment_id = ? AND user_id = ? AND reaction = ?`
424
+ ).bind(commentId, opts.userId, reaction).first();
425
+ } else if (ip) {
426
+ existing = await db.prepare(
427
+ `SELECT id FROM ${getReactionsTable()} WHERE comment_id = ? AND ip = ? AND reaction = ? AND user_id IS NULL`
428
+ ).bind(commentId, ip, reaction).first();
429
+ }
430
+ let added;
431
+ if (existing) {
432
+ await db.prepare(`DELETE FROM ${getReactionsTable()} WHERE id = ?`).bind(existing.id).run();
433
+ added = false;
434
+ } else {
435
+ await db.prepare(
436
+ `INSERT INTO ${getReactionsTable()} (id, comment_id, user_id, ip, reaction, created_at)
437
+ VALUES (?, ?, ?, ?, ?, ?)`
438
+ ).bind(nanoid(), commentId, opts?.userId ?? null, ip ?? null, reaction, now).run();
439
+ added = true;
440
+ }
441
+ const rows = await db.prepare(
442
+ `SELECT reaction, COUNT(*) as cnt FROM ${getReactionsTable()} WHERE comment_id = ? GROUP BY reaction`
443
+ ).bind(commentId).all();
444
+ const counts = {};
445
+ for (const r of rows.results ?? []) {
446
+ counts[r.reaction] = r.cnt;
447
+ }
448
+ await db.prepare(`UPDATE ${getTable()} SET reaction_counts = ?, updated_at = ? WHERE id = ?`).bind(JSON.stringify(counts), now, commentId).run();
449
+ return { added, reactionCounts: counts };
450
+ }
@@ -1,10 +1,11 @@
1
1
  import { type RequestEvent } from "nuxt/server";
2
- import type { AuthOptions, BlobOptions, CMSOptions, PaymentsOptions, AppRateLimitOptions, RealtimeOptions, MailOptions, AnalyticsOptions, MultitenantOptions } from "../../../types";
2
+ import type { AuthOptions, BlobOptions, CMSOptions, CommentsOptions, PaymentsOptions, AppRateLimitOptions, RealtimeOptions, MailOptions, AnalyticsOptions, MultitenantOptions } from "../../../types";
3
3
  export interface QarpeoRuntimeConfig {
4
4
  auth: AuthOptions;
5
5
  blob: BlobOptions;
6
6
  storage: BlobOptions;
7
7
  cms: CMSOptions;
8
+ comments: CommentsOptions;
8
9
  payments: PaymentsOptions;
9
10
  ratelimit: AppRateLimitOptions;
10
11
  realtime: RealtimeOptions;
@@ -15,6 +15,7 @@ export function getQarpeoConfig(event) {
15
15
  blob: q.blob || q.storage || {},
16
16
  storage: q.storage || q.blob || {},
17
17
  cms: q.cms || {},
18
+ comments: q.comments || {},
18
19
  payments: q.payments || {},
19
20
  ratelimit: q.ratelimit || {},
20
21
  realtime: q.realtime || {},
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Returns true if the given string is a valid, safe targetUrn.
3
+ * Does NOT throw — callers decide how to surface the error.
4
+ */
5
+ export declare function isValidTargetUrn(urn: string): boolean;
6
+ /**
7
+ * Validates that a targetUrn is a safe, structured identifier.
8
+ * Throws an HTTP 400 createError if invalid.
9
+ */
10
+ export declare function validateTargetUrn(urn: string): void;
11
+ /**
12
+ * Throws a plain Error if the targetUrn is invalid.
13
+ * Convenient in test or non-HTTP contexts.
14
+ */
15
+ export declare function assertValidTargetUrn(urn: string): void;
@@ -0,0 +1,20 @@
1
+ import { createError } from "nuxt/server";
2
+ const TARGET_URN_RE = /^[a-zA-Z0-9:._-]{1,512}$/;
3
+ export function isValidTargetUrn(urn) {
4
+ return Boolean(urn && TARGET_URN_RE.test(urn));
5
+ }
6
+ export function validateTargetUrn(urn) {
7
+ if (!isValidTargetUrn(urn)) {
8
+ throw createError({
9
+ statusCode: 400,
10
+ statusMessage: "Invalid targetUrn. Must be a safe identifier (alphanumeric, colon, dot, hyphen, underscore; max 512 chars)."
11
+ });
12
+ }
13
+ }
14
+ export function assertValidTargetUrn(urn) {
15
+ if (!isValidTargetUrn(urn)) {
16
+ throw new Error(
17
+ "Invalid targetUrn. Must be a safe identifier (alphanumeric, colon, dot, hyphen, underscore; max 512 chars)."
18
+ );
19
+ }
20
+ }
@@ -15,6 +15,9 @@
15
15
  * return { ok: true }
16
16
  * })
17
17
  * ```
18
+ *
19
+ * NOTE: test-utils are intentionally NOT exported here to keep production bundles lean.
20
+ * Import from "qarpeo/test-utils" explicitly in test files only.
18
21
  */
19
22
  export * from "./types/index";
20
23
  export * from "./bindings";
@@ -41,3 +44,4 @@ export * from "./bots";
41
44
  export * from "./rag";
42
45
  export * from "./server/utils/string";
43
46
  export * from "./server/utils/audit";
47
+ export { resolveUserRole, checkIfExistsBeforeCreate, getRoleFromEnv, } from "./server/utils/auth";
@@ -23,3 +23,8 @@ export * from "./bots.mjs";
23
23
  export * from "./rag.mjs";
24
24
  export * from "./server/utils/string.mjs";
25
25
  export * from "./server/utils/audit.mjs";
26
+ export {
27
+ resolveUserRole,
28
+ checkIfExistsBeforeCreate,
29
+ getRoleFromEnv
30
+ } from "./server/utils/auth.mjs";
@@ -1,10 +1,21 @@
1
+ export type QarpeoRole = "super" | "admin" | "moderator" | "developer" | "user";
2
+ export interface ResolveUserRoleResult {
3
+ /** Whether the user already exists in the database */
4
+ exists: boolean;
5
+ /** The suggested role derived from QARPEO_*_EMAILS env vars (defaults to 'user') */
6
+ suggestedRole: QarpeoRole;
7
+ /** The user's current role in the database, if they exist */
8
+ currentRole?: string | null;
9
+ /** The user record from the database, if found */
10
+ user?: any | null;
11
+ }
1
12
  export interface QarpeoUser {
2
13
  id: string;
3
14
  email: string;
4
15
  name?: string | null;
5
16
  avatarUrl?: string | null;
6
17
  emailVerified?: boolean;
7
- role?: string;
18
+ role?: QarpeoRole | string;
8
19
  [key: string]: any;
9
20
  }
10
21
  export interface QarpeoOrganization {