@kiriti/comments-server 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +143 -2
- package/dist/chunk-MHK3GDPA.js +75 -0
- package/dist/cli.cjs +223 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +207 -0
- package/dist/index.cjs +765 -0
- package/dist/index.d.cts +246 -0
- package/dist/index.d.ts +246 -0
- package/dist/index.js +657 -0
- package/package.json +53 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,765 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
CommentsError: () => CommentsError,
|
|
34
|
+
createCommentsHandler: () => createCommentsHandler,
|
|
35
|
+
createCommentsRouter: () => createCommentsRouter,
|
|
36
|
+
createCommentsService: () => createCommentsService,
|
|
37
|
+
createMemoryRateLimitStore: () => createMemoryRateLimitStore,
|
|
38
|
+
createMongoRateLimitStore: () => createMongoRateLimitStore,
|
|
39
|
+
openStore: () => openStore,
|
|
40
|
+
resolveOptions: () => resolveOptions
|
|
41
|
+
});
|
|
42
|
+
module.exports = __toCommonJS(index_exports);
|
|
43
|
+
|
|
44
|
+
// src/router.ts
|
|
45
|
+
var import_express = __toESM(require("express"), 1);
|
|
46
|
+
var import_comments_core3 = require("@kiriti/comments-core");
|
|
47
|
+
|
|
48
|
+
// src/auth.ts
|
|
49
|
+
var import_jose = require("jose");
|
|
50
|
+
|
|
51
|
+
// src/errors.ts
|
|
52
|
+
var CommentsError = class extends Error {
|
|
53
|
+
constructor(status, code, message, retryAfter) {
|
|
54
|
+
super(message);
|
|
55
|
+
this.status = status;
|
|
56
|
+
this.code = code;
|
|
57
|
+
this.retryAfter = retryAfter;
|
|
58
|
+
this.name = "CommentsError";
|
|
59
|
+
}
|
|
60
|
+
status;
|
|
61
|
+
code;
|
|
62
|
+
retryAfter;
|
|
63
|
+
};
|
|
64
|
+
var badRequest = (code, message) => new CommentsError(400, code, message);
|
|
65
|
+
var unauthorized = (message = "Sign in to continue.") => new CommentsError(401, "unauthorized", message);
|
|
66
|
+
var forbidden = (code, message) => new CommentsError(403, code, message);
|
|
67
|
+
var notFound = (message = "Comment not found.") => new CommentsError(404, "not_found", message);
|
|
68
|
+
|
|
69
|
+
// src/auth.ts
|
|
70
|
+
var GOOGLE_JWKS = (0, import_jose.createRemoteJWKSet)(new URL("https://www.googleapis.com/oauth2/v3/certs"));
|
|
71
|
+
var GOOGLE_ISSUERS = ["https://accounts.google.com", "accounts.google.com"];
|
|
72
|
+
var SESSION_ISSUER = "kiriti-comments";
|
|
73
|
+
var createGoogleVerifier = (clientId) => async (credential) => {
|
|
74
|
+
try {
|
|
75
|
+
const { payload } = await (0, import_jose.jwtVerify)(credential, GOOGLE_JWKS, { issuer: GOOGLE_ISSUERS, audience: clientId });
|
|
76
|
+
if (!payload.sub) throw new Error("missing sub");
|
|
77
|
+
const name = typeof payload.name === "string" && payload.name.trim() ? payload.name.trim() : "Google user";
|
|
78
|
+
const picture = typeof payload.picture === "string" ? payload.picture : null;
|
|
79
|
+
const email = payload.email_verified === true && typeof payload.email === "string" ? payload.email.toLowerCase() : void 0;
|
|
80
|
+
return { sub: payload.sub, name: name.slice(0, 80), picture, email };
|
|
81
|
+
} catch {
|
|
82
|
+
throw unauthorized("Google sign-in failed. Please try again.");
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
var createSessions = (secret, ttl) => {
|
|
86
|
+
const key = new TextEncoder().encode(secret);
|
|
87
|
+
return {
|
|
88
|
+
sign: (user) => new import_jose.SignJWT({ name: user.name, picture: user.picture, mod: user.isModerator }).setProtectedHeader({ alg: "HS256" }).setSubject(user.id).setIssuer(SESSION_ISSUER).setIssuedAt().setExpirationTime(ttl).sign(key),
|
|
89
|
+
verify: async (token) => {
|
|
90
|
+
try {
|
|
91
|
+
const { payload } = await (0, import_jose.jwtVerify)(token, key, { issuer: SESSION_ISSUER, algorithms: ["HS256"] });
|
|
92
|
+
return {
|
|
93
|
+
id: payload.sub,
|
|
94
|
+
name: typeof payload.name === "string" ? payload.name : "User",
|
|
95
|
+
picture: typeof payload.picture === "string" ? payload.picture : null,
|
|
96
|
+
isModerator: payload.mod === true
|
|
97
|
+
};
|
|
98
|
+
} catch {
|
|
99
|
+
throw unauthorized("Your session expired. Please sign in again.");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// src/db.ts
|
|
106
|
+
var import_mongodb = require("mongodb");
|
|
107
|
+
var ensureIndexes = async (comments, users) => {
|
|
108
|
+
await Promise.all([
|
|
109
|
+
comments.createIndex({ slug: 1, depth: 1, createdAt: -1 }),
|
|
110
|
+
comments.createIndex({ slug: 1, depth: 1, likes: -1, createdAt: -1 }),
|
|
111
|
+
comments.createIndex({ rootId: 1, createdAt: 1 }),
|
|
112
|
+
comments.createIndex({ authorId: 1, createdAt: -1 }),
|
|
113
|
+
comments.createIndex({ flags: -1, createdAt: -1 }, { partialFilterExpression: { flags: { $gt: 0 } } }),
|
|
114
|
+
comments.createIndex({ hidden: 1, createdAt: -1 }),
|
|
115
|
+
users.createIndex({ googleSub: 1 }, { unique: true })
|
|
116
|
+
]);
|
|
117
|
+
};
|
|
118
|
+
var openStore = async (opts, mongoUrl, client) => {
|
|
119
|
+
const owned = !client;
|
|
120
|
+
const mongo = client ?? new import_mongodb.MongoClient(mongoUrl);
|
|
121
|
+
if (owned) await mongo.connect();
|
|
122
|
+
const db = mongo.db(opts.dbName);
|
|
123
|
+
const comments = db.collection(`${opts.collectionPrefix}comments`);
|
|
124
|
+
const users = db.collection(`${opts.collectionPrefix}comment_users`);
|
|
125
|
+
await ensureIndexes(comments, users);
|
|
126
|
+
return { comments, users, db, close: async () => {
|
|
127
|
+
if (owned) await mongo.close();
|
|
128
|
+
} };
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
// src/options.ts
|
|
132
|
+
var import_comments_core = require("@kiriti/comments-core");
|
|
133
|
+
var DEFAULT_LIMITS = {
|
|
134
|
+
comment: { max: 5, windowMs: 6e4 },
|
|
135
|
+
action: { max: 60, windowMs: 6e4 },
|
|
136
|
+
signIn: { max: 20, windowMs: 15 * 6e4 }
|
|
137
|
+
};
|
|
138
|
+
var rule = (value, fallback) => {
|
|
139
|
+
if (value === false) return void 0;
|
|
140
|
+
const r = value ?? fallback;
|
|
141
|
+
if (!(r.max > 0) || !(r.windowMs > 0)) throw new Error("comments-server: rate limit rules need positive `max` and `windowMs`.");
|
|
142
|
+
return r;
|
|
143
|
+
};
|
|
144
|
+
var resolveRateLimit = (o) => o === false ? { store: "memory" } : {
|
|
145
|
+
comment: rule(o?.comment, DEFAULT_LIMITS.comment),
|
|
146
|
+
action: rule(o?.action, DEFAULT_LIMITS.action),
|
|
147
|
+
signIn: rule(o?.signIn, DEFAULT_LIMITS.signIn),
|
|
148
|
+
store: o?.store ?? "memory"
|
|
149
|
+
};
|
|
150
|
+
var MIN_SECRET_LENGTH = 32;
|
|
151
|
+
var CLIENT_ID_PATTERN = /^[\w-]+\.apps\.googleusercontent\.com$/;
|
|
152
|
+
var SETUP_HINT = "Run `npx @kiriti/comments-server init` to create these settings.";
|
|
153
|
+
var list = (value) => value === void 0 ? void 0 : value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
154
|
+
var normalizeOrigin = (input) => {
|
|
155
|
+
let url;
|
|
156
|
+
try {
|
|
157
|
+
url = new URL(input.trim());
|
|
158
|
+
} catch {
|
|
159
|
+
throw new Error(`comments-server: "${input}" in allowedOrigins isn't a valid URL (e.g. https://example.com).`);
|
|
160
|
+
}
|
|
161
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`comments-server: "${input}" must start with https:// or http://.`);
|
|
162
|
+
return url.origin;
|
|
163
|
+
};
|
|
164
|
+
var configError = (message) => new Error(`comments-server: ${message} ${SETUP_HINT}`);
|
|
165
|
+
var resolveOptions = (input, env = typeof process !== "undefined" ? process.env : {}) => {
|
|
166
|
+
const o = {
|
|
167
|
+
...input,
|
|
168
|
+
mongoUrl: input.mongoUrl ?? env.COMMENTS_MONGO_URL,
|
|
169
|
+
dbName: input.dbName ?? env.COMMENTS_DB,
|
|
170
|
+
googleClientId: input.googleClientId ?? env.COMMENTS_GOOGLE_CLIENT_ID,
|
|
171
|
+
sessionSecret: input.sessionSecret ?? env.COMMENTS_SESSION_SECRET,
|
|
172
|
+
allowedOrigins: input.allowedOrigins ?? list(env.COMMENTS_ALLOWED_ORIGINS),
|
|
173
|
+
moderatorEmails: input.moderatorEmails ?? list(env.COMMENTS_MODERATOR_EMAILS)
|
|
174
|
+
};
|
|
175
|
+
if (!o.client && !o.mongoUrl) throw configError("missing MongoDB connection: pass `mongoUrl` (or `client`) or set COMMENTS_MONGO_URL.");
|
|
176
|
+
if (!o.googleClientId) throw configError("missing Google client id: pass `googleClientId` or set COMMENTS_GOOGLE_CLIENT_ID.");
|
|
177
|
+
if (!CLIENT_ID_PATTERN.test(o.googleClientId.trim())) {
|
|
178
|
+
throw configError(`"${o.googleClientId}" doesn't look like a Google OAuth client id (it ends in .apps.googleusercontent.com).`);
|
|
179
|
+
}
|
|
180
|
+
if (!o.sessionSecret || o.sessionSecret.length < MIN_SECRET_LENGTH) {
|
|
181
|
+
throw configError(`\`sessionSecret\` (COMMENTS_SESSION_SECRET) must be at least ${MIN_SECRET_LENGTH} characters.`);
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
mongoUrl: o.mongoUrl,
|
|
185
|
+
allowedOrigins: [...new Set((o.allowedOrigins ?? []).map(normalizeOrigin))],
|
|
186
|
+
quiet: Boolean(o.quiet),
|
|
187
|
+
dbName: o.dbName ?? "comments",
|
|
188
|
+
collectionPrefix: o.collectionPrefix ?? "",
|
|
189
|
+
googleClientId: o.googleClientId.trim(),
|
|
190
|
+
sessionSecret: o.sessionSecret,
|
|
191
|
+
sessionTtl: o.sessionTtl ?? "7d",
|
|
192
|
+
threading: (0, import_comments_core.resolveThreading)(o.threading),
|
|
193
|
+
flagThreshold: Math.max(1, Math.round(o.flagThreshold ?? 5)),
|
|
194
|
+
maxLength: Math.max(1, Math.round(o.maxLength ?? import_comments_core.DEFAULT_MAX_LENGTH)),
|
|
195
|
+
pageSize: Math.min(50, Math.max(1, Math.round(o.pageSize ?? 20))),
|
|
196
|
+
moderatorEmails: new Set((o.moderatorEmails ?? []).map((e) => e.trim().toLowerCase()).filter(Boolean)),
|
|
197
|
+
editWindowMinutes: o.editWindowMinutes && o.editWindowMinutes > 0 ? o.editWindowMinutes : null,
|
|
198
|
+
rateLimit: resolveRateLimit(o.rateLimit)
|
|
199
|
+
};
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
// src/rateLimit.ts
|
|
203
|
+
var createMemoryRateLimitStore = () => {
|
|
204
|
+
const hits = /* @__PURE__ */ new Map();
|
|
205
|
+
const sweep = setInterval(() => {
|
|
206
|
+
const now = Date.now();
|
|
207
|
+
for (const [key, entry] of hits) if (entry.resetAt <= now) hits.delete(key);
|
|
208
|
+
}, 6e4);
|
|
209
|
+
sweep.unref?.();
|
|
210
|
+
return {
|
|
211
|
+
increment: async (key, windowMs) => {
|
|
212
|
+
const now = Date.now();
|
|
213
|
+
const entry = hits.get(key);
|
|
214
|
+
if (!entry || entry.resetAt <= now) {
|
|
215
|
+
const fresh = { count: 1, resetAt: now + windowMs };
|
|
216
|
+
hits.set(key, fresh);
|
|
217
|
+
return fresh;
|
|
218
|
+
}
|
|
219
|
+
entry.count += 1;
|
|
220
|
+
return entry;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
};
|
|
224
|
+
var createMongoRateLimitStore = async (db, collectionName = "comment_rate_limits") => {
|
|
225
|
+
const col = db.collection(collectionName);
|
|
226
|
+
await col.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });
|
|
227
|
+
return {
|
|
228
|
+
increment: async (key, windowMs) => {
|
|
229
|
+
const windowStart = Math.floor(Date.now() / windowMs) * windowMs;
|
|
230
|
+
const resetAt = windowStart + windowMs;
|
|
231
|
+
const doc = await col.findOneAndUpdate(
|
|
232
|
+
{ _id: `${key}:${windowStart}` },
|
|
233
|
+
{ $inc: { count: 1 }, $setOnInsert: { expiresAt: new Date(resetAt) } },
|
|
234
|
+
{ upsert: true, returnDocument: "after" }
|
|
235
|
+
);
|
|
236
|
+
return { count: doc?.count ?? 1, resetAt };
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
};
|
|
240
|
+
var LABELS = {
|
|
241
|
+
comment: "You're commenting too fast.",
|
|
242
|
+
action: "You're doing that too fast.",
|
|
243
|
+
signIn: "Too many sign-in attempts."
|
|
244
|
+
};
|
|
245
|
+
var createLimiter = (store) => async (bucket, key, rule2) => {
|
|
246
|
+
if (!rule2) return;
|
|
247
|
+
const { count, resetAt } = await store.increment(`${bucket}:${key}`, rule2.windowMs);
|
|
248
|
+
if (count <= rule2.max) return;
|
|
249
|
+
const retryAfter = Math.max(1, Math.ceil((resetAt - Date.now()) / 1e3));
|
|
250
|
+
throw new CommentsError(429, "rate_limited", `${LABELS[bucket] ?? "Too many requests."} Try again in ${retryAfter}s.`, retryAfter);
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
// src/service.ts
|
|
254
|
+
var import_mongodb2 = require("mongodb");
|
|
255
|
+
var import_comments_core2 = require("@kiriti/comments-core");
|
|
256
|
+
var MAX_REPLIES_PER_PAGE = 1e3;
|
|
257
|
+
var DUPLICATE_WINDOW_MS = 6e4;
|
|
258
|
+
var MODERATION_PAGE_SIZE = 25;
|
|
259
|
+
var SORTS = {
|
|
260
|
+
newest: { createdAt: -1, _id: -1 },
|
|
261
|
+
oldest: { createdAt: 1, _id: 1 },
|
|
262
|
+
top: { likes: -1, createdAt: -1, _id: -1 }
|
|
263
|
+
};
|
|
264
|
+
var PUBLIC_FIELDS = { likedBy: 0, flaggedBy: 0 };
|
|
265
|
+
var NOT_DELETED = { deleted: { $ne: true } };
|
|
266
|
+
var toObjectId = (id, what = "comment") => {
|
|
267
|
+
if (typeof id !== "string" || !import_mongodb2.ObjectId.isValid(id)) throw badRequest("invalid_id", `Invalid ${what} id.`);
|
|
268
|
+
return new import_mongodb2.ObjectId(id);
|
|
269
|
+
};
|
|
270
|
+
var requireSlug = (input) => {
|
|
271
|
+
const slug = (0, import_comments_core2.normalizeSlug)(input);
|
|
272
|
+
if (!slug) throw badRequest("invalid_slug", "A valid slug is required (letters, numbers and / _ . : -).");
|
|
273
|
+
return slug;
|
|
274
|
+
};
|
|
275
|
+
var baseDTO = (doc, revealText = false) => {
|
|
276
|
+
const removed = doc.hidden || Boolean(doc.deleted);
|
|
277
|
+
return {
|
|
278
|
+
id: doc._id.toHexString(),
|
|
279
|
+
slug: doc.slug,
|
|
280
|
+
parentId: doc.parentId?.toHexString() ?? null,
|
|
281
|
+
rootId: doc.rootId.toHexString(),
|
|
282
|
+
depth: doc.depth,
|
|
283
|
+
content: removed && !revealText ? "" : doc.content,
|
|
284
|
+
author: { id: doc.authorId.toHexString(), name: doc.authorName, picture: doc.authorPicture },
|
|
285
|
+
replyToName: doc.replyToName,
|
|
286
|
+
likes: doc.likes,
|
|
287
|
+
hidden: doc.hidden,
|
|
288
|
+
deleted: Boolean(doc.deleted),
|
|
289
|
+
createdAt: doc.createdAt.toISOString(),
|
|
290
|
+
editedAt: doc.editedAt?.toISOString() ?? null
|
|
291
|
+
};
|
|
292
|
+
};
|
|
293
|
+
var toDTO = (doc, viewer) => {
|
|
294
|
+
const id = doc._id.toHexString();
|
|
295
|
+
return { ...baseDTO(doc), likedByMe: viewer.liked.has(id), flaggedByMe: viewer.flagged.has(id) };
|
|
296
|
+
};
|
|
297
|
+
var isRemoved = (d) => d.hidden || Boolean(d.deleted);
|
|
298
|
+
var dropRemovedLeaves = (docs) => {
|
|
299
|
+
const keep = new Set(docs.filter((d) => !isRemoved(d)).map((d) => d._id.toHexString()));
|
|
300
|
+
let changed = true;
|
|
301
|
+
while (changed) {
|
|
302
|
+
changed = false;
|
|
303
|
+
for (const d of docs) {
|
|
304
|
+
const parent = d.parentId?.toHexString();
|
|
305
|
+
if (keep.has(d._id.toHexString()) && parent && !keep.has(parent)) {
|
|
306
|
+
keep.add(parent);
|
|
307
|
+
changed = true;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return docs.filter((d) => keep.has(d._id.toHexString()));
|
|
312
|
+
};
|
|
313
|
+
var MODERATION_FILTERS = {
|
|
314
|
+
flagged: { flags: { $gt: 0 }, approved: { $ne: true }, ...NOT_DELETED },
|
|
315
|
+
hidden: { hidden: true, ...NOT_DELETED },
|
|
316
|
+
recent: { ...NOT_DELETED }
|
|
317
|
+
};
|
|
318
|
+
var MODERATION_SORTS = {
|
|
319
|
+
flagged: { flags: -1, createdAt: -1 },
|
|
320
|
+
hidden: { createdAt: -1 },
|
|
321
|
+
recent: { createdAt: -1 }
|
|
322
|
+
};
|
|
323
|
+
var createCommentsService = (store, opts) => {
|
|
324
|
+
const { comments, users } = store;
|
|
325
|
+
const viewerState = async (ids, viewerId) => {
|
|
326
|
+
const empty = { liked: /* @__PURE__ */ new Set(), flagged: /* @__PURE__ */ new Set() };
|
|
327
|
+
if (!viewerId || !import_mongodb2.ObjectId.isValid(viewerId) || ids.length === 0) return empty;
|
|
328
|
+
const uid = new import_mongodb2.ObjectId(viewerId);
|
|
329
|
+
const [liked, flagged] = await Promise.all([
|
|
330
|
+
comments.find({ _id: { $in: ids }, likedBy: uid }, { projection: { _id: 1 } }).toArray(),
|
|
331
|
+
comments.find({ _id: { $in: ids }, flaggedBy: uid }, { projection: { _id: 1 } }).toArray()
|
|
332
|
+
]);
|
|
333
|
+
return { liked: new Set(liked.map((d) => d._id.toHexString())), flagged: new Set(flagged.map((d) => d._id.toHexString())) };
|
|
334
|
+
};
|
|
335
|
+
const assertCanWrite = async (user) => {
|
|
336
|
+
const doc = await users.findOne({ _id: toObjectId(user.id, "user") }, { projection: { banned: 1 } });
|
|
337
|
+
if (doc?.banned) throw forbidden("banned", "Your account can't post or react to comments.");
|
|
338
|
+
};
|
|
339
|
+
const assertModerator = async (user) => {
|
|
340
|
+
const doc = await users.findOne({ _id: toObjectId(user.id, "user") }, { projection: { isModerator: 1 } });
|
|
341
|
+
if (!doc?.isModerator) throw forbidden("not_moderator", "Only moderators can do that.");
|
|
342
|
+
};
|
|
343
|
+
const listThreads = async ({ slug: rawSlug, sort = "newest", offset = 0, limit, viewerId }) => {
|
|
344
|
+
const slug = requireSlug(rawSlug);
|
|
345
|
+
const pageSize = Math.min(opts.pageSize, Math.max(1, Math.round(limit ?? opts.pageSize)));
|
|
346
|
+
const skip = Math.max(0, Math.round(offset));
|
|
347
|
+
const [tops, total] = await Promise.all([
|
|
348
|
+
comments.find({ slug, depth: 0 }, { projection: PUBLIC_FIELDS }).sort(SORTS[sort]).skip(skip).limit(pageSize + 1).toArray(),
|
|
349
|
+
comments.countDocuments({ slug, hidden: false, ...NOT_DELETED })
|
|
350
|
+
]);
|
|
351
|
+
const pageTops = tops.slice(0, pageSize);
|
|
352
|
+
const replies = pageTops.length && opts.threading.enabled ? await comments.find({ rootId: { $in: pageTops.map((t) => t._id) }, depth: { $gt: 0 } }, { projection: PUBLIC_FIELDS }).sort({ createdAt: 1 }).limit(MAX_REPLIES_PER_PAGE).toArray() : [];
|
|
353
|
+
const visible = dropRemovedLeaves([...pageTops, ...replies]);
|
|
354
|
+
const viewer = await viewerState(visible.map((d) => d._id), viewerId);
|
|
355
|
+
const hasMore = tops.length > pageSize;
|
|
356
|
+
return { comments: visible.map((d) => toDTO(d, viewer)), total, hasMore, nextOffset: hasMore ? skip + pageSize : null };
|
|
357
|
+
};
|
|
358
|
+
const placeReply = async (parentId, slug) => {
|
|
359
|
+
if (!opts.threading.enabled) throw badRequest("threading_disabled", "Replies are turned off for these comments.");
|
|
360
|
+
const parent = await comments.findOne({ _id: toObjectId(parentId, "parent") }, { projection: PUBLIC_FIELDS });
|
|
361
|
+
if (!parent || parent.slug !== slug || parent.deleted) throw notFound("The comment you're replying to no longer exists.");
|
|
362
|
+
if (parent.depth < opts.threading.maxDepth) {
|
|
363
|
+
return { parentId: parent._id, rootId: parent.rootId, depth: parent.depth + 1, replyToName: null };
|
|
364
|
+
}
|
|
365
|
+
return { parentId: parent.parentId, rootId: parent.rootId, depth: parent.depth, replyToName: parent.authorName };
|
|
366
|
+
};
|
|
367
|
+
const assertNotDuplicate = async (authorId, slug, content) => {
|
|
368
|
+
const recent = await comments.findOne(
|
|
369
|
+
{ authorId, slug, content, createdAt: { $gt: new Date(Date.now() - DUPLICATE_WINDOW_MS) }, ...NOT_DELETED },
|
|
370
|
+
{ projection: { _id: 1 } }
|
|
371
|
+
);
|
|
372
|
+
if (recent) throw new CommentsError(409, "duplicate", "You just posted that comment.");
|
|
373
|
+
};
|
|
374
|
+
const createComment = async (input, author) => {
|
|
375
|
+
const slug = requireSlug(input.slug);
|
|
376
|
+
const text = (0, import_comments_core2.validateContent)(input.content, opts.maxLength);
|
|
377
|
+
if (!text.ok) throw badRequest("invalid_content", text.error);
|
|
378
|
+
await assertCanWrite(author);
|
|
379
|
+
const authorId = toObjectId(author.id, "user");
|
|
380
|
+
await assertNotDuplicate(authorId, slug, text.content);
|
|
381
|
+
const _id = new import_mongodb2.ObjectId();
|
|
382
|
+
const placement = input.parentId ? await placeReply(input.parentId, slug) : { parentId: null, rootId: _id, depth: 0, replyToName: null };
|
|
383
|
+
const now = /* @__PURE__ */ new Date();
|
|
384
|
+
const doc = {
|
|
385
|
+
_id,
|
|
386
|
+
slug,
|
|
387
|
+
...placement,
|
|
388
|
+
content: text.content,
|
|
389
|
+
authorId,
|
|
390
|
+
authorName: author.name,
|
|
391
|
+
authorPicture: author.picture,
|
|
392
|
+
likes: 0,
|
|
393
|
+
likedBy: [],
|
|
394
|
+
flags: 0,
|
|
395
|
+
flaggedBy: [],
|
|
396
|
+
hidden: false,
|
|
397
|
+
approved: false,
|
|
398
|
+
deleted: false,
|
|
399
|
+
editedAt: null,
|
|
400
|
+
createdAt: now,
|
|
401
|
+
updatedAt: now
|
|
402
|
+
};
|
|
403
|
+
await comments.insertOne(doc);
|
|
404
|
+
return toDTO(doc, { liked: /* @__PURE__ */ new Set(), flagged: /* @__PURE__ */ new Set() });
|
|
405
|
+
};
|
|
406
|
+
const reload = async (id, viewerId) => {
|
|
407
|
+
const doc = await comments.findOne({ _id: id }, { projection: PUBLIC_FIELDS });
|
|
408
|
+
if (!doc) throw notFound();
|
|
409
|
+
return toDTO(doc, await viewerState([id], viewerId));
|
|
410
|
+
};
|
|
411
|
+
const loadLive = async (id) => {
|
|
412
|
+
const doc = await comments.findOne({ _id: id, ...NOT_DELETED }, { projection: PUBLIC_FIELDS });
|
|
413
|
+
if (!doc) throw notFound();
|
|
414
|
+
return doc;
|
|
415
|
+
};
|
|
416
|
+
const editComment = async (commentId, content, user) => {
|
|
417
|
+
const id = toObjectId(commentId);
|
|
418
|
+
const text = (0, import_comments_core2.validateContent)(content, opts.maxLength);
|
|
419
|
+
if (!text.ok) throw badRequest("invalid_content", text.error);
|
|
420
|
+
await assertCanWrite(user);
|
|
421
|
+
const doc = await loadLive(id);
|
|
422
|
+
if (doc.authorId.toHexString() !== user.id) throw forbidden("not_author", "You can only edit your own comments.");
|
|
423
|
+
if (doc.hidden) throw forbidden("hidden", "Hidden comments can't be edited.");
|
|
424
|
+
if (opts.editWindowMinutes !== null && Date.now() - doc.createdAt.getTime() > opts.editWindowMinutes * 6e4) {
|
|
425
|
+
throw forbidden("edit_window_closed", `Comments can only be edited within ${opts.editWindowMinutes} minutes of posting.`);
|
|
426
|
+
}
|
|
427
|
+
if (doc.content !== text.content) {
|
|
428
|
+
const now = /* @__PURE__ */ new Date();
|
|
429
|
+
await comments.updateOne({ _id: id }, { $set: { content: text.content, editedAt: now, updatedAt: now } });
|
|
430
|
+
}
|
|
431
|
+
return reload(id, user.id);
|
|
432
|
+
};
|
|
433
|
+
const removeComment = async (id, by) => {
|
|
434
|
+
const now = /* @__PURE__ */ new Date();
|
|
435
|
+
await comments.updateOne({ _id: id }, { $set: { deleted: true, deletedBy: by, content: "", updatedAt: now } });
|
|
436
|
+
};
|
|
437
|
+
const deleteComment = async (commentId, user) => {
|
|
438
|
+
const id = toObjectId(commentId);
|
|
439
|
+
const doc = await loadLive(id);
|
|
440
|
+
const isAuthor = doc.authorId.toHexString() === user.id;
|
|
441
|
+
if (!isAuthor) await assertModerator(user);
|
|
442
|
+
await removeComment(id, isAuthor ? "author" : "moderator");
|
|
443
|
+
};
|
|
444
|
+
const like = async (commentId, user) => {
|
|
445
|
+
const id = toObjectId(commentId);
|
|
446
|
+
const uid = toObjectId(user.id, "user");
|
|
447
|
+
await assertCanWrite(user);
|
|
448
|
+
const res = await comments.updateOne({ _id: id, likedBy: { $ne: uid }, ...NOT_DELETED }, { $addToSet: { likedBy: uid }, $inc: { likes: 1 } });
|
|
449
|
+
if (res.matchedCount === 0) await loadLive(id);
|
|
450
|
+
return reload(id, user.id);
|
|
451
|
+
};
|
|
452
|
+
const unlike = async (commentId, user) => {
|
|
453
|
+
const id = toObjectId(commentId);
|
|
454
|
+
const uid = toObjectId(user.id, "user");
|
|
455
|
+
const res = await comments.updateOne({ _id: id, likedBy: uid }, { $pull: { likedBy: uid }, $inc: { likes: -1 } });
|
|
456
|
+
if (res.matchedCount === 0) await loadLive(id);
|
|
457
|
+
return reload(id, user.id);
|
|
458
|
+
};
|
|
459
|
+
const flag = async (commentId, user) => {
|
|
460
|
+
const id = toObjectId(commentId);
|
|
461
|
+
const uid = toObjectId(user.id, "user");
|
|
462
|
+
await assertCanWrite(user);
|
|
463
|
+
const updated = await comments.findOneAndUpdate(
|
|
464
|
+
{ _id: id, flaggedBy: { $ne: uid }, ...NOT_DELETED },
|
|
465
|
+
{ $addToSet: { flaggedBy: uid }, $inc: { flags: 1 } },
|
|
466
|
+
{ returnDocument: "after", projection: { flags: 1, approved: 1 } }
|
|
467
|
+
);
|
|
468
|
+
if (!updated) await loadLive(id);
|
|
469
|
+
if (updated && !updated.approved && updated.flags >= opts.flagThreshold) {
|
|
470
|
+
await comments.updateOne({ _id: id, hidden: false }, { $set: { hidden: true, updatedAt: /* @__PURE__ */ new Date() } });
|
|
471
|
+
}
|
|
472
|
+
return reload(id, user.id);
|
|
473
|
+
};
|
|
474
|
+
const upsertGoogleUser = async (identity) => {
|
|
475
|
+
const now = /* @__PURE__ */ new Date();
|
|
476
|
+
const isModerator = Boolean(identity.email && opts.moderatorEmails.has(identity.email));
|
|
477
|
+
const doc = await users.findOneAndUpdate(
|
|
478
|
+
{ googleSub: identity.sub },
|
|
479
|
+
{
|
|
480
|
+
$set: { name: identity.name, picture: identity.picture, lastLoginAt: now, isModerator },
|
|
481
|
+
$setOnInsert: { createdAt: now, banned: false }
|
|
482
|
+
},
|
|
483
|
+
{ upsert: true, returnDocument: "after" }
|
|
484
|
+
);
|
|
485
|
+
if (!doc) throw new Error("user upsert failed");
|
|
486
|
+
return { id: doc._id.toHexString(), name: doc.name, picture: doc.picture, isModerator: Boolean(doc.isModerator) };
|
|
487
|
+
};
|
|
488
|
+
const listModerationQueue = async (user, status, offset = 0) => {
|
|
489
|
+
await assertModerator(user);
|
|
490
|
+
const skip = Math.max(0, Math.round(offset));
|
|
491
|
+
const docs = await comments.find(MODERATION_FILTERS[status], { projection: PUBLIC_FIELDS }).sort(MODERATION_SORTS[status]).skip(skip).limit(MODERATION_PAGE_SIZE + 1).toArray();
|
|
492
|
+
const page = docs.slice(0, MODERATION_PAGE_SIZE);
|
|
493
|
+
const banned = await users.find({ _id: { $in: [...new Set(page.map((d) => d.authorId.toHexString()))].map((id) => new import_mongodb2.ObjectId(id)) }, banned: true }, { projection: { _id: 1 } }).toArray();
|
|
494
|
+
const bannedIds = new Set(banned.map((u) => u._id.toHexString()));
|
|
495
|
+
const items = page.map((d) => ({
|
|
496
|
+
...baseDTO(d, true),
|
|
497
|
+
flags: d.flags,
|
|
498
|
+
approved: Boolean(d.approved),
|
|
499
|
+
authorBanned: bannedIds.has(d.authorId.toHexString())
|
|
500
|
+
}));
|
|
501
|
+
const hasMore = docs.length > MODERATION_PAGE_SIZE;
|
|
502
|
+
return { items, nextOffset: hasMore ? skip + MODERATION_PAGE_SIZE : null };
|
|
503
|
+
};
|
|
504
|
+
const MODERATION_UPDATES = {
|
|
505
|
+
// Reviewed and fine: clear reports and stop future reports from auto-hiding it.
|
|
506
|
+
approve: { $set: { hidden: false, approved: true, flags: 0, flaggedBy: [] } },
|
|
507
|
+
hide: { $set: { hidden: true } },
|
|
508
|
+
unhide: { $set: { hidden: false, approved: true } }
|
|
509
|
+
};
|
|
510
|
+
const moderateComment = async (commentId, action, user) => {
|
|
511
|
+
await assertModerator(user);
|
|
512
|
+
const id = toObjectId(commentId);
|
|
513
|
+
await loadLive(id);
|
|
514
|
+
if (action === "delete") return removeComment(id, "moderator");
|
|
515
|
+
const update = MODERATION_UPDATES[action];
|
|
516
|
+
await comments.updateOne({ _id: id }, { $set: { ...update.$set, updatedAt: /* @__PURE__ */ new Date() } });
|
|
517
|
+
};
|
|
518
|
+
const setUserBanned = async (userId, banned, moderator) => {
|
|
519
|
+
await assertModerator(moderator);
|
|
520
|
+
const id = toObjectId(userId, "user");
|
|
521
|
+
if (id.toHexString() === moderator.id) throw badRequest("self_ban", "You can't ban yourself.");
|
|
522
|
+
const res = await users.updateOne({ _id: id }, { $set: { banned, bannedAt: banned ? /* @__PURE__ */ new Date() : null } });
|
|
523
|
+
if (res.matchedCount === 0) throw notFound("User not found.");
|
|
524
|
+
if (banned) await comments.updateMany({ authorId: id, hidden: false, ...NOT_DELETED }, { $set: { hidden: true, updatedAt: /* @__PURE__ */ new Date() } });
|
|
525
|
+
};
|
|
526
|
+
return {
|
|
527
|
+
listThreads,
|
|
528
|
+
createComment,
|
|
529
|
+
editComment,
|
|
530
|
+
deleteComment,
|
|
531
|
+
like,
|
|
532
|
+
unlike,
|
|
533
|
+
flag,
|
|
534
|
+
upsertGoogleUser,
|
|
535
|
+
listModerationQueue,
|
|
536
|
+
moderateComment,
|
|
537
|
+
setUserBanned
|
|
538
|
+
};
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
// src/router.ts
|
|
542
|
+
var route = (fn) => (req, res, next) => {
|
|
543
|
+
fn(req, res).catch(next);
|
|
544
|
+
};
|
|
545
|
+
var bearer = (req) => {
|
|
546
|
+
const header = req.get("authorization") ?? "";
|
|
547
|
+
return header.startsWith("Bearer ") ? header.slice(7).trim() || null : null;
|
|
548
|
+
};
|
|
549
|
+
var intQuery = (value) => {
|
|
550
|
+
const n = Number(value);
|
|
551
|
+
return Number.isFinite(n) ? n : void 0;
|
|
552
|
+
};
|
|
553
|
+
var MODERATION_STATUSES = ["flagged", "hidden", "recent"];
|
|
554
|
+
var MODERATION_ACTIONS = ["approve", "hide", "unhide", "delete"];
|
|
555
|
+
var rateLimitStore = async (opts, store) => {
|
|
556
|
+
const choice = opts.rateLimit.store;
|
|
557
|
+
if (choice === "memory") return createMemoryRateLimitStore();
|
|
558
|
+
if (choice === "mongo") return createMongoRateLimitStore(store.db, `${opts.collectionPrefix}comment_rate_limits`);
|
|
559
|
+
return choice;
|
|
560
|
+
};
|
|
561
|
+
var logSetupChecklist = (opts) => {
|
|
562
|
+
const origins = opts.allowedOrigins.length ? opts.allowedOrigins.map((o) => ` - ${o}`).join("\n") : " (none set \u2014 pass `allowedOrigins` or COMMENTS_ALLOWED_ORIGINS so the widget can warn about unlisted sites)";
|
|
563
|
+
console.info([
|
|
564
|
+
"[comments-server] ready.",
|
|
565
|
+
' Google sign-in only works on sites listed under "Authorized JavaScript origins" of your OAuth client:',
|
|
566
|
+
" https://console.cloud.google.com/auth/clients",
|
|
567
|
+
" Allowed origins configured here:",
|
|
568
|
+
origins,
|
|
569
|
+
opts.moderatorEmails.size ? ` Moderators: ${[...opts.moderatorEmails].join(", ")}` : " No moderators set (moderatorEmails / COMMENTS_MODERATOR_EMAILS).",
|
|
570
|
+
" Pass `quiet: true` to hide this message."
|
|
571
|
+
].join("\n"));
|
|
572
|
+
};
|
|
573
|
+
var createCommentsRouter = async (options) => {
|
|
574
|
+
const opts = resolveOptions(options);
|
|
575
|
+
const store = await openStore(opts, opts.mongoUrl, options.client);
|
|
576
|
+
if (!opts.quiet) logSetupChecklist(opts);
|
|
577
|
+
const service = createCommentsService(store, opts);
|
|
578
|
+
const sessions = createSessions(opts.sessionSecret, opts.sessionTtl);
|
|
579
|
+
const verifyGoogle = options.verifyGoogleCredential ?? createGoogleVerifier(opts.googleClientId);
|
|
580
|
+
const limit = createLimiter(await rateLimitStore(opts, store));
|
|
581
|
+
const limits = opts.rateLimit;
|
|
582
|
+
const optionalUser = async (req) => {
|
|
583
|
+
const token = bearer(req);
|
|
584
|
+
return token ? sessions.verify(token).catch(() => null) : null;
|
|
585
|
+
};
|
|
586
|
+
const requireUser = async (req) => {
|
|
587
|
+
const token = bearer(req);
|
|
588
|
+
if (!token) throw unauthorized();
|
|
589
|
+
return sessions.verify(token);
|
|
590
|
+
};
|
|
591
|
+
const actingUser = async (req) => {
|
|
592
|
+
const user = await requireUser(req);
|
|
593
|
+
await limit("action", user.id, limits.action);
|
|
594
|
+
return user;
|
|
595
|
+
};
|
|
596
|
+
const router = import_express.default.Router();
|
|
597
|
+
router.use(import_express.default.json({ limit: "16kb" }));
|
|
598
|
+
const publicConfig = {
|
|
599
|
+
googleClientId: opts.googleClientId,
|
|
600
|
+
threading: opts.threading,
|
|
601
|
+
maxLength: opts.maxLength,
|
|
602
|
+
editWindowMinutes: opts.editWindowMinutes,
|
|
603
|
+
allowedOrigins: opts.allowedOrigins
|
|
604
|
+
};
|
|
605
|
+
router.get("/config", (_req, res) => {
|
|
606
|
+
res.set("Cache-Control", "public, max-age=300").json(publicConfig);
|
|
607
|
+
});
|
|
608
|
+
router.post("/auth/google", route(async (req, res) => {
|
|
609
|
+
await limit("signIn", req.ip ?? "unknown", limits.signIn);
|
|
610
|
+
const credential = req.body?.credential;
|
|
611
|
+
if (typeof credential !== "string" || !credential) throw badRequest("invalid_credential", "Missing Google credential.");
|
|
612
|
+
const identity = await verifyGoogle(credential).catch((err) => {
|
|
613
|
+
throw err instanceof CommentsError ? err : unauthorized("Google sign-in failed. Please try again.");
|
|
614
|
+
});
|
|
615
|
+
const user = await service.upsertGoogleUser(identity);
|
|
616
|
+
res.json({ token: await sessions.sign(user), user });
|
|
617
|
+
}));
|
|
618
|
+
router.get("/me", route(async (req, res) => {
|
|
619
|
+
res.json({ user: await requireUser(req) });
|
|
620
|
+
}));
|
|
621
|
+
router.get("/threads", route(async (req, res) => {
|
|
622
|
+
const sort = (0, import_comments_core3.isSort)(req.query.sort) ? req.query.sort : "newest";
|
|
623
|
+
const viewer = await optionalUser(req);
|
|
624
|
+
const page = await service.listThreads({
|
|
625
|
+
slug: req.query.slug,
|
|
626
|
+
sort,
|
|
627
|
+
offset: intQuery(req.query.offset),
|
|
628
|
+
limit: intQuery(req.query.limit),
|
|
629
|
+
viewerId: viewer?.id
|
|
630
|
+
});
|
|
631
|
+
res.set("Cache-Control", "no-store").json(page);
|
|
632
|
+
}));
|
|
633
|
+
router.post("/comments", route(async (req, res) => {
|
|
634
|
+
const user = await requireUser(req);
|
|
635
|
+
await limit("comment", user.id, limits.comment);
|
|
636
|
+
const { slug, content, parentId } = req.body ?? {};
|
|
637
|
+
res.status(201).json(await service.createComment({ slug, content, parentId }, user));
|
|
638
|
+
}));
|
|
639
|
+
router.patch("/comments/:id", route(async (req, res) => {
|
|
640
|
+
res.json(await service.editComment(req.params.id, req.body?.content, await actingUser(req)));
|
|
641
|
+
}));
|
|
642
|
+
router.delete("/comments/:id", route(async (req, res) => {
|
|
643
|
+
await service.deleteComment(req.params.id, await actingUser(req));
|
|
644
|
+
res.status(204).end();
|
|
645
|
+
}));
|
|
646
|
+
const action = (fn) => route(async (req, res) => {
|
|
647
|
+
res.json(await fn(req.params.id, await actingUser(req)));
|
|
648
|
+
});
|
|
649
|
+
router.post("/comments/:id/like", action(service.like));
|
|
650
|
+
router.post("/comments/:id/unlike", action(service.unlike));
|
|
651
|
+
router.post("/comments/:id/flag", action(service.flag));
|
|
652
|
+
router.get("/moderation/queue", route(async (req, res) => {
|
|
653
|
+
const status = MODERATION_STATUSES.find((s) => s === req.query.status) ?? "flagged";
|
|
654
|
+
const page = await service.listModerationQueue(await requireUser(req), status, intQuery(req.query.offset));
|
|
655
|
+
res.set("Cache-Control", "no-store").json(page);
|
|
656
|
+
}));
|
|
657
|
+
router.post("/moderation/comments/:id/:action", route(async (req, res) => {
|
|
658
|
+
const act = MODERATION_ACTIONS.find((a) => a === req.params.action);
|
|
659
|
+
if (!act) throw badRequest("invalid_action", "Unknown moderation action.");
|
|
660
|
+
await service.moderateComment(req.params.id, act, await actingUser(req));
|
|
661
|
+
res.status(204).end();
|
|
662
|
+
}));
|
|
663
|
+
const ban = (banned) => route(async (req, res) => {
|
|
664
|
+
await service.setUserBanned(req.params.id, banned, await actingUser(req));
|
|
665
|
+
res.status(204).end();
|
|
666
|
+
});
|
|
667
|
+
router.post("/moderation/users/:id/ban", ban(true));
|
|
668
|
+
router.post("/moderation/users/:id/unban", ban(false));
|
|
669
|
+
router.use((err, _req, res, _next) => {
|
|
670
|
+
if (err instanceof CommentsError) {
|
|
671
|
+
if (err.retryAfter) res.set("Retry-After", String(err.retryAfter));
|
|
672
|
+
res.status(err.status).json({ error: err.message, code: err.code });
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
if (err instanceof SyntaxError) {
|
|
676
|
+
res.status(400).json({ error: "Invalid JSON body.", code: "invalid_json" });
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
console.error("[comments-server]", err);
|
|
680
|
+
res.status(500).json({ error: "Something went wrong.", code: "internal" });
|
|
681
|
+
});
|
|
682
|
+
router.close = store.close;
|
|
683
|
+
return router;
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
// src/handler.ts
|
|
687
|
+
var import_express2 = __toESM(require("express"), 1);
|
|
688
|
+
var SUB_PATH = /^[a-z0-9/_-]{0,200}$/i;
|
|
689
|
+
var sendJson = (res, status, body) => {
|
|
690
|
+
if (res.writableEnded) return;
|
|
691
|
+
res.statusCode = status;
|
|
692
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
693
|
+
res.end(JSON.stringify(body));
|
|
694
|
+
};
|
|
695
|
+
var subPath = (rawUrl, basePath, pathParam, strip) => {
|
|
696
|
+
const url = new URL(rawUrl, "http://localhost");
|
|
697
|
+
let path = null;
|
|
698
|
+
if (url.pathname === basePath || url.pathname.startsWith(`${basePath}/`)) path = url.pathname.slice(basePath.length);
|
|
699
|
+
else if (url.searchParams.has(pathParam)) path = url.searchParams.get(pathParam) ?? "";
|
|
700
|
+
if (path === null) return null;
|
|
701
|
+
for (const key of [pathParam, ...strip]) url.searchParams.delete(key);
|
|
702
|
+
const query = url.searchParams.toString();
|
|
703
|
+
return `${path.replace(/^\/+/, "")}${query ? `?${query}` : ""}`;
|
|
704
|
+
};
|
|
705
|
+
var createCommentsHandler = (options = {}) => {
|
|
706
|
+
const { basePath = "/api/comments", pathParam = "path", stripParams = [], ...routerOptions } = options;
|
|
707
|
+
const base = basePath.replace(/\/+$/, "");
|
|
708
|
+
let starting = null;
|
|
709
|
+
const start = () => {
|
|
710
|
+
starting ??= createCommentsRouter(routerOptions).then((router) => {
|
|
711
|
+
const app = (0, import_express2.default)();
|
|
712
|
+
app.disable("x-powered-by");
|
|
713
|
+
app.set("trust proxy", true);
|
|
714
|
+
app.use(base, router);
|
|
715
|
+
return { app, router };
|
|
716
|
+
}).catch((error) => {
|
|
717
|
+
starting = null;
|
|
718
|
+
throw error;
|
|
719
|
+
});
|
|
720
|
+
return starting;
|
|
721
|
+
};
|
|
722
|
+
const handler = async (req, res) => {
|
|
723
|
+
const path = subPath(req.url ?? "/", base, pathParam, stripParams);
|
|
724
|
+
if (path === null || !SUB_PATH.test(path.split("?")[0] ?? "")) return sendJson(res, 404, { error: "Not found.", code: "not_found" });
|
|
725
|
+
let app;
|
|
726
|
+
try {
|
|
727
|
+
({ app } = await start());
|
|
728
|
+
} catch (error) {
|
|
729
|
+
console.error("[comments-server] failed to start:", error instanceof Error ? error.message : error);
|
|
730
|
+
return sendJson(res, 503, { error: "Comments are temporarily unavailable.", code: "unavailable" });
|
|
731
|
+
}
|
|
732
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
733
|
+
try {
|
|
734
|
+
void req.body;
|
|
735
|
+
} catch {
|
|
736
|
+
return sendJson(res, 400, { error: "Invalid JSON body.", code: "invalid_json" });
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
req.url = `${base}/${path}`;
|
|
740
|
+
await new Promise((resolve) => {
|
|
741
|
+
res.once("finish", resolve);
|
|
742
|
+
res.once("close", resolve);
|
|
743
|
+
app(req, res);
|
|
744
|
+
});
|
|
745
|
+
};
|
|
746
|
+
return Object.assign(handler, {
|
|
747
|
+
close: async () => {
|
|
748
|
+
if (!starting) return;
|
|
749
|
+
const { router } = await starting.catch(() => ({ router: null }));
|
|
750
|
+
await router?.close();
|
|
751
|
+
starting = null;
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
};
|
|
755
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
756
|
+
0 && (module.exports = {
|
|
757
|
+
CommentsError,
|
|
758
|
+
createCommentsHandler,
|
|
759
|
+
createCommentsRouter,
|
|
760
|
+
createCommentsService,
|
|
761
|
+
createMemoryRateLimitStore,
|
|
762
|
+
createMongoRateLimitStore,
|
|
763
|
+
openStore,
|
|
764
|
+
resolveOptions
|
|
765
|
+
});
|