@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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kiriti999
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,144 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kiriti/comments-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Threaded comments API for Express (4 or 5): MongoDB storage, Google sign-in, comments per slug, likes and reporting.
|
|
4
|
+
Pairs with [`@kiriti/comments-react`](https://www.npmjs.com/package/@kiriti/comments-react).
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm i @kiriti/comments-server express
|
|
8
|
+
npx @kiriti/comments-server init # interactive setup (see below)
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import express from "express";
|
|
13
|
+
import { createCommentsRouter } from "@kiriti/comments-server";
|
|
14
|
+
|
|
15
|
+
const app = express();
|
|
16
|
+
app.use("/api/comments", await createCommentsRouter({})); // reads COMMENTS_* from the environment
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Setup and credentials
|
|
20
|
+
|
|
21
|
+
Everything is configured when the server starts, never at `npm install` (installs are often non-interactive, and
|
|
22
|
+
install scripts are commonly disabled). Each consumer uses **their own** MongoDB and **their own** Google OAuth client.
|
|
23
|
+
|
|
24
|
+
| Setting | Env variable | Sensitive? |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| MongoDB URL | `COMMENTS_MONGO_URL` | **Yes**: contains the database password |
|
|
27
|
+
| Session secret | `COMMENTS_SESSION_SECRET` | **Yes**: signs sessions |
|
|
28
|
+
| Google client ID | `COMMENTS_GOOGLE_CLIENT_ID` | No: public by design (it's sent to browsers) |
|
|
29
|
+
| Allowed sites | `COMMENTS_ALLOWED_ORIGINS` | No |
|
|
30
|
+
| Moderators | `COMMENTS_MODERATOR_EMAILS` | No |
|
|
31
|
+
| Database name | `COMMENTS_DB` | No |
|
|
32
|
+
|
|
33
|
+
No Google **client secret** is used: the sign-in popup returns an ID token that the server verifies with Google's public keys.
|
|
34
|
+
Keep the sensitive values in your host's secret store (Vercel/Netlify env vars, Docker secrets, AWS Secrets Manager…),
|
|
35
|
+
not in code or in the database. Options passed to `createCommentsRouter` override the environment.
|
|
36
|
+
|
|
37
|
+
**`npx @kiriti/comments-server init`** asks for the MongoDB URL (and tests the connection), the client ID, your sites
|
|
38
|
+
and moderators, and generates the session secret. It **appends only missing keys** to `.env` (existing values are never
|
|
39
|
+
changed; re-running is safe), adds `.env` to `.gitignore` if needed, and prints the Google Console steps for your exact
|
|
40
|
+
sites plus how to copy the values to Vercel/Docker. Options: `--dir <project>`, `--file .env.local`.
|
|
41
|
+
|
|
42
|
+
**Google Console:** Google Auth Platform → Clients → your *Web application* client → add every site under
|
|
43
|
+
**Authorized JavaScript origins** (e.g. `https://example.com`, `http://localhost:5173`). No redirect URIs are needed.
|
|
44
|
+
If the widget runs on a site not in `allowedOrigins`, it shows a notice instead of a sign-in button that would fail.
|
|
45
|
+
|
|
46
|
+
Add CORS for the sites that show the widget if the API is on another origin.
|
|
47
|
+
|
|
48
|
+
### Serverless / no Express app: `createCommentsHandler`
|
|
49
|
+
|
|
50
|
+
A drop-in Node handler (Vercel functions, Next.js API routes, `http.createServer`). It starts on the first request,
|
|
51
|
+
reuses the MongoDB connection while warm, and copes with platforms that pre-parse the body.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
// api/comments/[...path].ts (Vercel) — or pages/api/comments/[...path].ts (Next.js)
|
|
55
|
+
import { createCommentsHandler } from "@kiriti/comments-server";
|
|
56
|
+
export default createCommentsHandler({ rateLimit: { store: "mongo" } }); // settings from COMMENTS_* env vars
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Out of function slots? Point a rewrite at an existing function and let it delegate:
|
|
60
|
+
|
|
61
|
+
```jsonc
|
|
62
|
+
// vercel.json
|
|
63
|
+
{ "source": "/api/comments/:path*", "destination": "/api/existing?action=comments&path=:path*" }
|
|
64
|
+
```
|
|
65
|
+
```ts
|
|
66
|
+
// inside api/existing.ts
|
|
67
|
+
const comments = createCommentsHandler({ stripParams: ["action"] });
|
|
68
|
+
if (req.query.action === "comments") return comments(req, res);
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Options: everything `createCommentsRouter` takes, plus `basePath` (default `/api/comments`), `pathParam`
|
|
72
|
+
(default `path`) and `stripParams`.
|
|
73
|
+
|
|
74
|
+
## Options
|
|
75
|
+
|
|
76
|
+
| Option | Default | |
|
|
77
|
+
|---|---|---|
|
|
78
|
+
| `mongoUrl` | `COMMENTS_MONGO_URL` | MongoDB connection string (required unless `client` is passed) |
|
|
79
|
+
| `client` | — | Existing `MongoClient` to reuse (never closed by the package) |
|
|
80
|
+
| `dbName` | `"comments"` / `COMMENTS_DB` | Database name |
|
|
81
|
+
| `collectionPrefix` | `""` | Prefix for the `comments` and `comment_users` collections |
|
|
82
|
+
| `googleClientId` | `COMMENTS_GOOGLE_CLIENT_ID` | Google OAuth **Web** client id (required) |
|
|
83
|
+
| `sessionSecret` | `COMMENTS_SESSION_SECRET` | 32+ characters; signs session tokens (required) |
|
|
84
|
+
| `allowedOrigins` | `COMMENTS_ALLOWED_ORIGINS` | Sites that show the widget (published at `/config` so the widget can warn elsewhere) |
|
|
85
|
+
| `quiet` | `false` | Hide the setup checklist logged at startup |
|
|
86
|
+
| `sessionTtl` | `"7d"` | Session length (`"12h"`, `"30d"`…) |
|
|
87
|
+
| `threading` | `{ enabled: true, maxDepth: 3 }` | `false` for flat comments; `maxDepth` = reply levels (1–10) |
|
|
88
|
+
| `flagThreshold` | `5` | Hide a comment once this many different users report it |
|
|
89
|
+
| `maxLength` | `2000` | Max characters per comment |
|
|
90
|
+
| `pageSize` | `20` | Top-level comments per page (max 50) |
|
|
91
|
+
| `moderatorEmails` | `COMMENTS_MODERATOR_EMAILS` | Google account emails that can moderate (checked at sign-in, never stored) |
|
|
92
|
+
| `editWindowMinutes` | `null` | Minutes after posting that authors may edit; `null` = any time |
|
|
93
|
+
| `rateLimit` | see below | Spam protection; `false` turns it off |
|
|
94
|
+
|
|
95
|
+
### Rate limiting
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
rateLimit: {
|
|
99
|
+
comment: { max: 5, windowMs: 60_000 }, // new comments per user
|
|
100
|
+
action: { max: 60, windowMs: 60_000 }, // likes, reports, edits, deletes per user
|
|
101
|
+
signIn: { max: 20, windowMs: 15 * 60_000 }, // sign-ins per IP
|
|
102
|
+
store: "memory", // "mongo" when running several instances, or your own RateLimitStore
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Any rule can be `false`. Over the limit returns `429` with `Retry-After`. The same text posted twice on the same page
|
|
107
|
+
within a minute returns `409 duplicate`. Behind a proxy, set Express's `trust proxy` so sign-in limits use the real IP.
|
|
108
|
+
|
|
109
|
+
Invalid options throw at startup. Indexes are created automatically.
|
|
110
|
+
|
|
111
|
+
## Endpoints
|
|
112
|
+
|
|
113
|
+
| | |
|
|
114
|
+
|---|---|
|
|
115
|
+
| `GET /config` | Public settings for the UI (Google client id, threading, max length) |
|
|
116
|
+
| `POST /auth/google` `{ credential }` | Verify a Google sign-in, returns `{ token, user }` |
|
|
117
|
+
| `GET /me` | Signed-in user (`Authorization: Bearer <token>`) |
|
|
118
|
+
| `GET /threads?slug=&sort=newest\|oldest\|top&offset=&limit=` | Top-level comments with their replies, flat (`nextOffset` for paging) |
|
|
119
|
+
| `POST /comments` `{ slug, content, parentId? }` | Create a comment or reply (signed in) |
|
|
120
|
+
| `PATCH /comments/:id` `{ content }` | Author edits (within `editWindowMinutes`) |
|
|
121
|
+
| `DELETE /comments/:id` | Author or moderator |
|
|
122
|
+
| `POST /comments/:id/like` · `/unlike` · `/flag` | Signed in; each user counts once |
|
|
123
|
+
| `GET /moderation/queue?status=flagged\|hidden\|recent&offset=` | Moderators: comments across all slugs, with text, report count and author status |
|
|
124
|
+
| `POST /moderation/comments/:id/approve` · `/hide` · `/unhide` · `/delete` | Moderators |
|
|
125
|
+
| `POST /moderation/users/:id/ban` · `/unban` | Moderators |
|
|
126
|
+
|
|
127
|
+
Errors are JSON: `{ error, code }` with a matching HTTP status.
|
|
128
|
+
|
|
129
|
+
## Behaviour
|
|
130
|
+
|
|
131
|
+
- **Threading:** a reply nests under its parent up to `maxDepth`. Replying deeper attaches the reply at the deepest
|
|
132
|
+
level and records who it answered (`replyToName`), so nothing is rejected or lost. With threading off, replies return
|
|
133
|
+
`400 threading_disabled`.
|
|
134
|
+
- **Likes:** a single atomic update per click, guarded so a user can only be counted once, even with concurrent requests.
|
|
135
|
+
- **Reports:** one per user; at `flagThreshold` the comment is hidden. Hidden comments with visible replies stay as
|
|
136
|
+
"hidden" placeholders so the conversation still makes sense; hidden comments without replies disappear.
|
|
137
|
+
- **Edit / delete:** authors edit their own visible comments (marked "edited"). Deleting keeps a "deleted" placeholder
|
|
138
|
+
while the comment has replies, otherwise it disappears. Moderators can delete any comment.
|
|
139
|
+
- **Moderation:** *approve* clears reports and stops further reports from auto-hiding the comment; *hide*/*unhide*;
|
|
140
|
+
*ban* blocks the user from posting, liking and reporting and hides their visible comments (unban lets them write again;
|
|
141
|
+
hidden comments stay hidden for review). Moderator status and bans are re-checked in the database on every request.
|
|
142
|
+
- **Privacy:** only the Google account id, name and photo are stored. The host app never passes user ids.
|
|
143
|
+
|
|
144
|
+
Lower-level building blocks (`openStore`, `createCommentsService`) are exported for custom frameworks.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// src/options.ts
|
|
2
|
+
import { DEFAULT_MAX_LENGTH, resolveThreading } from "@kiriti/comments-core";
|
|
3
|
+
var DEFAULT_LIMITS = {
|
|
4
|
+
comment: { max: 5, windowMs: 6e4 },
|
|
5
|
+
action: { max: 60, windowMs: 6e4 },
|
|
6
|
+
signIn: { max: 20, windowMs: 15 * 6e4 }
|
|
7
|
+
};
|
|
8
|
+
var rule = (value, fallback) => {
|
|
9
|
+
if (value === false) return void 0;
|
|
10
|
+
const r = value ?? fallback;
|
|
11
|
+
if (!(r.max > 0) || !(r.windowMs > 0)) throw new Error("comments-server: rate limit rules need positive `max` and `windowMs`.");
|
|
12
|
+
return r;
|
|
13
|
+
};
|
|
14
|
+
var resolveRateLimit = (o) => o === false ? { store: "memory" } : {
|
|
15
|
+
comment: rule(o?.comment, DEFAULT_LIMITS.comment),
|
|
16
|
+
action: rule(o?.action, DEFAULT_LIMITS.action),
|
|
17
|
+
signIn: rule(o?.signIn, DEFAULT_LIMITS.signIn),
|
|
18
|
+
store: o?.store ?? "memory"
|
|
19
|
+
};
|
|
20
|
+
var MIN_SECRET_LENGTH = 32;
|
|
21
|
+
var CLIENT_ID_PATTERN = /^[\w-]+\.apps\.googleusercontent\.com$/;
|
|
22
|
+
var SETUP_HINT = "Run `npx @kiriti/comments-server init` to create these settings.";
|
|
23
|
+
var list = (value) => value === void 0 ? void 0 : value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
24
|
+
var normalizeOrigin = (input) => {
|
|
25
|
+
let url;
|
|
26
|
+
try {
|
|
27
|
+
url = new URL(input.trim());
|
|
28
|
+
} catch {
|
|
29
|
+
throw new Error(`comments-server: "${input}" in allowedOrigins isn't a valid URL (e.g. https://example.com).`);
|
|
30
|
+
}
|
|
31
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`comments-server: "${input}" must start with https:// or http://.`);
|
|
32
|
+
return url.origin;
|
|
33
|
+
};
|
|
34
|
+
var configError = (message) => new Error(`comments-server: ${message} ${SETUP_HINT}`);
|
|
35
|
+
var resolveOptions = (input, env = typeof process !== "undefined" ? process.env : {}) => {
|
|
36
|
+
const o = {
|
|
37
|
+
...input,
|
|
38
|
+
mongoUrl: input.mongoUrl ?? env.COMMENTS_MONGO_URL,
|
|
39
|
+
dbName: input.dbName ?? env.COMMENTS_DB,
|
|
40
|
+
googleClientId: input.googleClientId ?? env.COMMENTS_GOOGLE_CLIENT_ID,
|
|
41
|
+
sessionSecret: input.sessionSecret ?? env.COMMENTS_SESSION_SECRET,
|
|
42
|
+
allowedOrigins: input.allowedOrigins ?? list(env.COMMENTS_ALLOWED_ORIGINS),
|
|
43
|
+
moderatorEmails: input.moderatorEmails ?? list(env.COMMENTS_MODERATOR_EMAILS)
|
|
44
|
+
};
|
|
45
|
+
if (!o.client && !o.mongoUrl) throw configError("missing MongoDB connection: pass `mongoUrl` (or `client`) or set COMMENTS_MONGO_URL.");
|
|
46
|
+
if (!o.googleClientId) throw configError("missing Google client id: pass `googleClientId` or set COMMENTS_GOOGLE_CLIENT_ID.");
|
|
47
|
+
if (!CLIENT_ID_PATTERN.test(o.googleClientId.trim())) {
|
|
48
|
+
throw configError(`"${o.googleClientId}" doesn't look like a Google OAuth client id (it ends in .apps.googleusercontent.com).`);
|
|
49
|
+
}
|
|
50
|
+
if (!o.sessionSecret || o.sessionSecret.length < MIN_SECRET_LENGTH) {
|
|
51
|
+
throw configError(`\`sessionSecret\` (COMMENTS_SESSION_SECRET) must be at least ${MIN_SECRET_LENGTH} characters.`);
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
mongoUrl: o.mongoUrl,
|
|
55
|
+
allowedOrigins: [...new Set((o.allowedOrigins ?? []).map(normalizeOrigin))],
|
|
56
|
+
quiet: Boolean(o.quiet),
|
|
57
|
+
dbName: o.dbName ?? "comments",
|
|
58
|
+
collectionPrefix: o.collectionPrefix ?? "",
|
|
59
|
+
googleClientId: o.googleClientId.trim(),
|
|
60
|
+
sessionSecret: o.sessionSecret,
|
|
61
|
+
sessionTtl: o.sessionTtl ?? "7d",
|
|
62
|
+
threading: resolveThreading(o.threading),
|
|
63
|
+
flagThreshold: Math.max(1, Math.round(o.flagThreshold ?? 5)),
|
|
64
|
+
maxLength: Math.max(1, Math.round(o.maxLength ?? DEFAULT_MAX_LENGTH)),
|
|
65
|
+
pageSize: Math.min(50, Math.max(1, Math.round(o.pageSize ?? 20))),
|
|
66
|
+
moderatorEmails: new Set((o.moderatorEmails ?? []).map((e) => e.trim().toLowerCase()).filter(Boolean)),
|
|
67
|
+
editWindowMinutes: o.editWindowMinutes && o.editWindowMinutes > 0 ? o.editWindowMinutes : null,
|
|
68
|
+
rateLimit: resolveRateLimit(o.rateLimit)
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export {
|
|
73
|
+
normalizeOrigin,
|
|
74
|
+
resolveOptions
|
|
75
|
+
};
|
package/dist/cli.cjs
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/cli.ts
|
|
5
|
+
var import_node_crypto = require("crypto");
|
|
6
|
+
var import_node_fs = require("fs");
|
|
7
|
+
var import_node_path = require("path");
|
|
8
|
+
var import_node_readline = require("readline");
|
|
9
|
+
var import_node_process = require("process");
|
|
10
|
+
var import_mongodb = require("mongodb");
|
|
11
|
+
|
|
12
|
+
// src/options.ts
|
|
13
|
+
var import_comments_core = require("@kiriti/comments-core");
|
|
14
|
+
var DEFAULT_LIMITS = {
|
|
15
|
+
comment: { max: 5, windowMs: 6e4 },
|
|
16
|
+
action: { max: 60, windowMs: 6e4 },
|
|
17
|
+
signIn: { max: 20, windowMs: 15 * 6e4 }
|
|
18
|
+
};
|
|
19
|
+
var normalizeOrigin = (input) => {
|
|
20
|
+
let url;
|
|
21
|
+
try {
|
|
22
|
+
url = new URL(input.trim());
|
|
23
|
+
} catch {
|
|
24
|
+
throw new Error(`comments-server: "${input}" in allowedOrigins isn't a valid URL (e.g. https://example.com).`);
|
|
25
|
+
}
|
|
26
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`comments-server: "${input}" must start with https:// or http://.`);
|
|
27
|
+
return url.origin;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// src/setup.ts
|
|
31
|
+
var ENV_KEYS = {
|
|
32
|
+
mongoUrl: "COMMENTS_MONGO_URL",
|
|
33
|
+
db: "COMMENTS_DB",
|
|
34
|
+
googleClientId: "COMMENTS_GOOGLE_CLIENT_ID",
|
|
35
|
+
sessionSecret: "COMMENTS_SESSION_SECRET",
|
|
36
|
+
allowedOrigins: "COMMENTS_ALLOWED_ORIGINS",
|
|
37
|
+
moderatorEmails: "COMMENTS_MODERATOR_EMAILS"
|
|
38
|
+
};
|
|
39
|
+
var envKeys = (text) => new Set(
|
|
40
|
+
text.split(/\r?\n/).map((line) => line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[1]).filter((key) => Boolean(key))
|
|
41
|
+
);
|
|
42
|
+
var envValue = (value) => /[\s#"'`$\\]/.test(value) ? `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : value;
|
|
43
|
+
var mergeEnv = (existing, values) => {
|
|
44
|
+
const present = envKeys(existing);
|
|
45
|
+
const added = Object.keys(values).filter((key) => !present.has(key));
|
|
46
|
+
const kept = Object.keys(values).filter((key) => present.has(key));
|
|
47
|
+
if (added.length === 0) return { text: existing, added, kept };
|
|
48
|
+
const block = [
|
|
49
|
+
"# @kiriti/comments-server (added by `comments-server init`) \u2014 keep this file out of git",
|
|
50
|
+
...added.map((key) => `${key}=${envValue(values[key])}`)
|
|
51
|
+
].join("\n");
|
|
52
|
+
const separator = existing === "" ? "" : existing.endsWith("\n\n") ? "" : existing.endsWith("\n") ? "\n" : "\n\n";
|
|
53
|
+
return { text: `${existing}${separator}${block}
|
|
54
|
+
`, added, kept };
|
|
55
|
+
};
|
|
56
|
+
var ignoresEnv = (gitignore) => gitignore.split(/\r?\n/).map((line) => line.trim()).some((line) => [".env", "/.env", ".env*", "/.env*", "*.env"].includes(line));
|
|
57
|
+
var ensureGitignore = (gitignore) => {
|
|
58
|
+
const current = gitignore ?? "";
|
|
59
|
+
if (ignoresEnv(current)) return { text: current, changed: false };
|
|
60
|
+
const separator = current === "" || current.endsWith("\n") ? "" : "\n";
|
|
61
|
+
return { text: `${current}${separator}# secrets (comments-server)
|
|
62
|
+
.env
|
|
63
|
+
`, changed: true };
|
|
64
|
+
};
|
|
65
|
+
var googleSteps = (origins) => [
|
|
66
|
+
"Google sign-in setup (one time):",
|
|
67
|
+
' 1. Open https://console.cloud.google.com/auth/clients and pick (or create) a client of type "Web application".',
|
|
68
|
+
' 2. Under "Authorized JavaScript origins", add each site that shows the comments:',
|
|
69
|
+
...origins.length ? origins.map((o) => ` ${o}`) : [" (your site, e.g. https://example.com \u2014 and http://localhost:5173 for local testing)"],
|
|
70
|
+
` 3. Leave "Authorized redirect URIs" empty \u2014 the sign-in popup doesn't use a callback URL.`,
|
|
71
|
+
" 4. Save. Google can take a few minutes to apply origin changes.",
|
|
72
|
+
" No client secret is needed; only the client ID is used, and it is not confidential."
|
|
73
|
+
].join("\n");
|
|
74
|
+
var deploySteps = (keys) => [
|
|
75
|
+
"Deploying: set the same variables on your host (never commit .env):",
|
|
76
|
+
` Vercel: ${keys.map((k) => `vercel env add ${k}`).join(" && ")}`,
|
|
77
|
+
" Docker: docker run --env-file .env \u2026 (or `env_file: .env` in docker-compose)",
|
|
78
|
+
" Others: add them in your platform's environment / secrets settings (Netlify, Render, Railway, Fly: `fly secrets set KEY=value`).",
|
|
79
|
+
" The server reads them automatically: `await createCommentsRouter({})`."
|
|
80
|
+
].join("\n");
|
|
81
|
+
|
|
82
|
+
// src/cli.ts
|
|
83
|
+
var CLIENT_ID_PATTERN = /^[\w-]+\.apps\.googleusercontent\.com$/;
|
|
84
|
+
var args = process.argv.slice(2);
|
|
85
|
+
var flag = (name, fallback) => {
|
|
86
|
+
const i = args.indexOf(name);
|
|
87
|
+
return i >= 0 && args[i + 1] ? args[i + 1] : fallback;
|
|
88
|
+
};
|
|
89
|
+
var usage = () => {
|
|
90
|
+
console.log("Usage: npx @kiriti/comments-server init [--dir <project folder>] [--file .env]");
|
|
91
|
+
process.exit(args.includes("--help") ? 0 : 1);
|
|
92
|
+
};
|
|
93
|
+
var rl = (0, import_node_readline.createInterface)({ input: import_node_process.stdin, terminal: false });
|
|
94
|
+
var lines = [];
|
|
95
|
+
var waiting = null;
|
|
96
|
+
var closed = false;
|
|
97
|
+
rl.on("line", (line) => {
|
|
98
|
+
if (waiting) {
|
|
99
|
+
const resolveLine = waiting;
|
|
100
|
+
waiting = null;
|
|
101
|
+
resolveLine(line);
|
|
102
|
+
} else {
|
|
103
|
+
lines.push(line);
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
rl.on("close", () => {
|
|
107
|
+
closed = true;
|
|
108
|
+
waiting?.(null);
|
|
109
|
+
});
|
|
110
|
+
var nextLine = () => {
|
|
111
|
+
if (lines.length) return Promise.resolve(lines.shift());
|
|
112
|
+
if (closed) return Promise.resolve(null);
|
|
113
|
+
return new Promise((r) => {
|
|
114
|
+
waiting = r;
|
|
115
|
+
});
|
|
116
|
+
};
|
|
117
|
+
var ask = async (question, fallback = "") => {
|
|
118
|
+
import_node_process.stdout.write(fallback ? `${question} [${fallback}]: ` : `${question}: `);
|
|
119
|
+
const line = await nextLine();
|
|
120
|
+
if (line === null) throw new Error("Input ended before setup finished. Nothing was written.");
|
|
121
|
+
if (!import_node_process.stdin.isTTY) import_node_process.stdout.write(`${line}
|
|
122
|
+
`);
|
|
123
|
+
return line.trim() || fallback;
|
|
124
|
+
};
|
|
125
|
+
var confirm = async (question) => /^y(es)?$/i.test(await ask(`${question} (y/N)`));
|
|
126
|
+
var askValid = async (question, validate, fallback = "") => {
|
|
127
|
+
for (; ; ) {
|
|
128
|
+
const value = await ask(question, fallback);
|
|
129
|
+
const error = validate(value);
|
|
130
|
+
if (!error) return value;
|
|
131
|
+
console.log(` \u2717 ${error}`);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
var canConnect = async (url) => {
|
|
135
|
+
const client = new import_mongodb.MongoClient(url, { serverSelectionTimeoutMS: 5e3 });
|
|
136
|
+
try {
|
|
137
|
+
await client.connect();
|
|
138
|
+
await client.db("admin").command({ ping: 1 });
|
|
139
|
+
return null;
|
|
140
|
+
} catch (e) {
|
|
141
|
+
return e instanceof Error ? e.message : String(e);
|
|
142
|
+
} finally {
|
|
143
|
+
await client.close().catch(() => void 0);
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
var askMongo = async () => {
|
|
147
|
+
for (; ; ) {
|
|
148
|
+
const url = await askValid("MongoDB connection string (mongodb:// or mongodb+srv://)", (v) => /^mongodb(\+srv)?:\/\//.test(v) ? null : "It should start with mongodb:// or mongodb+srv://");
|
|
149
|
+
process.stdout.write(" Checking connection\u2026 ");
|
|
150
|
+
const error = await canConnect(url);
|
|
151
|
+
if (!error) {
|
|
152
|
+
console.log("\u2713 connected");
|
|
153
|
+
return url;
|
|
154
|
+
}
|
|
155
|
+
console.log(`\u2717 ${error}`);
|
|
156
|
+
if (await confirm(" Save it anyway (e.g. the database isn't reachable from this machine)?")) return url;
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
var parseOrigins = (value) => {
|
|
160
|
+
try {
|
|
161
|
+
value.split(",").map((v) => v.trim()).filter(Boolean).forEach(normalizeOrigin);
|
|
162
|
+
return null;
|
|
163
|
+
} catch (e) {
|
|
164
|
+
return e.message.replace("comments-server: ", "");
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
var collect = async (present) => {
|
|
168
|
+
const values = {};
|
|
169
|
+
const skip = (key) => {
|
|
170
|
+
if (!present.has(key)) return false;
|
|
171
|
+
console.log(`\u2022 ${key} is already in the file \u2014 keeping it.`);
|
|
172
|
+
return true;
|
|
173
|
+
};
|
|
174
|
+
if (!skip(ENV_KEYS.mongoUrl)) values[ENV_KEYS.mongoUrl] = await askMongo();
|
|
175
|
+
if (!skip(ENV_KEYS.db)) values[ENV_KEYS.db] = await ask("Database name", "comments");
|
|
176
|
+
if (!skip(ENV_KEYS.googleClientId)) {
|
|
177
|
+
values[ENV_KEYS.googleClientId] = await askValid("Google OAuth client ID (\u2026apps.googleusercontent.com)", (v) => CLIENT_ID_PATTERN.test(v) ? null : "That doesn't look like a client ID. Copy it from Google Cloud \u2192 Google Auth Platform \u2192 Clients.");
|
|
178
|
+
}
|
|
179
|
+
let origins = [];
|
|
180
|
+
if (!skip(ENV_KEYS.allowedOrigins)) {
|
|
181
|
+
const raw = await askValid("Sites that will show comments, comma-separated (e.g. https://example.com,http://localhost:5173)", parseOrigins);
|
|
182
|
+
origins = [...new Set(raw.split(",").map((v) => v.trim()).filter(Boolean).map(normalizeOrigin))];
|
|
183
|
+
values[ENV_KEYS.allowedOrigins] = origins.join(",");
|
|
184
|
+
}
|
|
185
|
+
if (!skip(ENV_KEYS.moderatorEmails)) {
|
|
186
|
+
const emails = await ask("Moderator Google emails, comma-separated (optional)");
|
|
187
|
+
if (emails) values[ENV_KEYS.moderatorEmails] = emails.split(",").map((e) => e.trim().toLowerCase()).filter(Boolean).join(",");
|
|
188
|
+
}
|
|
189
|
+
if (!skip(ENV_KEYS.sessionSecret)) {
|
|
190
|
+
values[ENV_KEYS.sessionSecret] = (0, import_node_crypto.randomBytes)(48).toString("base64url");
|
|
191
|
+
console.log(`\u2022 Generated ${ENV_KEYS.sessionSecret} (64 random characters).`);
|
|
192
|
+
}
|
|
193
|
+
return { values, origins };
|
|
194
|
+
};
|
|
195
|
+
var main = async () => {
|
|
196
|
+
if (args[0] !== "init" || args.includes("--help")) return usage();
|
|
197
|
+
const dir = (0, import_node_path.resolve)(flag("--dir", "."));
|
|
198
|
+
const envPath = (0, import_node_path.resolve)(dir, flag("--file", ".env"));
|
|
199
|
+
const existing = (0, import_node_fs.existsSync)(envPath) ? (0, import_node_fs.readFileSync)(envPath, "utf8") : "";
|
|
200
|
+
console.log(`
|
|
201
|
+
Setting up @kiriti/comments-server in ${envPath}
|
|
202
|
+
Nothing already in the file will be changed.
|
|
203
|
+
`);
|
|
204
|
+
const { values, origins } = await collect(envKeys(existing));
|
|
205
|
+
const merged = mergeEnv(existing, values);
|
|
206
|
+
if (merged.added.length) (0, import_node_fs.writeFileSync)(envPath, merged.text, { mode: 384 });
|
|
207
|
+
const gitignorePath = (0, import_node_path.resolve)(dir, ".gitignore");
|
|
208
|
+
const gitignore = ensureGitignore((0, import_node_fs.existsSync)(gitignorePath) ? (0, import_node_fs.readFileSync)(gitignorePath, "utf8") : null);
|
|
209
|
+
if (gitignore.changed) (0, import_node_fs.writeFileSync)(gitignorePath, gitignore.text);
|
|
210
|
+
console.log("");
|
|
211
|
+
console.log(merged.added.length ? `\u2713 Added to ${envPath}: ${merged.added.join(", ")}` : `\u2713 ${envPath} already had every setting; nothing written.`);
|
|
212
|
+
console.log(gitignore.changed ? "\u2713 Added .env to .gitignore" : "\u2713 .env is already git-ignored");
|
|
213
|
+
console.log(`
|
|
214
|
+
${googleSteps(origins)}
|
|
215
|
+
|
|
216
|
+
${deploySteps(merged.added.length ? merged.added : Object.values(ENV_KEYS))}
|
|
217
|
+
`);
|
|
218
|
+
};
|
|
219
|
+
main().catch((e) => {
|
|
220
|
+
console.error(`
|
|
221
|
+
\u2717 ${e instanceof Error ? e.message : String(e)}`);
|
|
222
|
+
process.exitCode = 1;
|
|
223
|
+
}).finally(() => rl.close());
|
package/dist/cli.d.cts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|