@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/cli.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
normalizeOrigin
|
|
4
|
+
} from "./chunk-MHK3GDPA.js";
|
|
5
|
+
|
|
6
|
+
// src/cli.ts
|
|
7
|
+
import { randomBytes } from "crypto";
|
|
8
|
+
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
9
|
+
import { resolve } from "path";
|
|
10
|
+
import { createInterface } from "readline";
|
|
11
|
+
import { stdin, stdout } from "process";
|
|
12
|
+
import { MongoClient } from "mongodb";
|
|
13
|
+
|
|
14
|
+
// src/setup.ts
|
|
15
|
+
var ENV_KEYS = {
|
|
16
|
+
mongoUrl: "COMMENTS_MONGO_URL",
|
|
17
|
+
db: "COMMENTS_DB",
|
|
18
|
+
googleClientId: "COMMENTS_GOOGLE_CLIENT_ID",
|
|
19
|
+
sessionSecret: "COMMENTS_SESSION_SECRET",
|
|
20
|
+
allowedOrigins: "COMMENTS_ALLOWED_ORIGINS",
|
|
21
|
+
moderatorEmails: "COMMENTS_MODERATOR_EMAILS"
|
|
22
|
+
};
|
|
23
|
+
var envKeys = (text) => new Set(
|
|
24
|
+
text.split(/\r?\n/).map((line) => line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[1]).filter((key) => Boolean(key))
|
|
25
|
+
);
|
|
26
|
+
var envValue = (value) => /[\s#"'`$\\]/.test(value) ? `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : value;
|
|
27
|
+
var mergeEnv = (existing, values) => {
|
|
28
|
+
const present = envKeys(existing);
|
|
29
|
+
const added = Object.keys(values).filter((key) => !present.has(key));
|
|
30
|
+
const kept = Object.keys(values).filter((key) => present.has(key));
|
|
31
|
+
if (added.length === 0) return { text: existing, added, kept };
|
|
32
|
+
const block = [
|
|
33
|
+
"# @kiriti/comments-server (added by `comments-server init`) \u2014 keep this file out of git",
|
|
34
|
+
...added.map((key) => `${key}=${envValue(values[key])}`)
|
|
35
|
+
].join("\n");
|
|
36
|
+
const separator = existing === "" ? "" : existing.endsWith("\n\n") ? "" : existing.endsWith("\n") ? "\n" : "\n\n";
|
|
37
|
+
return { text: `${existing}${separator}${block}
|
|
38
|
+
`, added, kept };
|
|
39
|
+
};
|
|
40
|
+
var ignoresEnv = (gitignore) => gitignore.split(/\r?\n/).map((line) => line.trim()).some((line) => [".env", "/.env", ".env*", "/.env*", "*.env"].includes(line));
|
|
41
|
+
var ensureGitignore = (gitignore) => {
|
|
42
|
+
const current = gitignore ?? "";
|
|
43
|
+
if (ignoresEnv(current)) return { text: current, changed: false };
|
|
44
|
+
const separator = current === "" || current.endsWith("\n") ? "" : "\n";
|
|
45
|
+
return { text: `${current}${separator}# secrets (comments-server)
|
|
46
|
+
.env
|
|
47
|
+
`, changed: true };
|
|
48
|
+
};
|
|
49
|
+
var googleSteps = (origins) => [
|
|
50
|
+
"Google sign-in setup (one time):",
|
|
51
|
+
' 1. Open https://console.cloud.google.com/auth/clients and pick (or create) a client of type "Web application".',
|
|
52
|
+
' 2. Under "Authorized JavaScript origins", add each site that shows the comments:',
|
|
53
|
+
...origins.length ? origins.map((o) => ` ${o}`) : [" (your site, e.g. https://example.com \u2014 and http://localhost:5173 for local testing)"],
|
|
54
|
+
` 3. Leave "Authorized redirect URIs" empty \u2014 the sign-in popup doesn't use a callback URL.`,
|
|
55
|
+
" 4. Save. Google can take a few minutes to apply origin changes.",
|
|
56
|
+
" No client secret is needed; only the client ID is used, and it is not confidential."
|
|
57
|
+
].join("\n");
|
|
58
|
+
var deploySteps = (keys) => [
|
|
59
|
+
"Deploying: set the same variables on your host (never commit .env):",
|
|
60
|
+
` Vercel: ${keys.map((k) => `vercel env add ${k}`).join(" && ")}`,
|
|
61
|
+
" Docker: docker run --env-file .env \u2026 (or `env_file: .env` in docker-compose)",
|
|
62
|
+
" Others: add them in your platform's environment / secrets settings (Netlify, Render, Railway, Fly: `fly secrets set KEY=value`).",
|
|
63
|
+
" The server reads them automatically: `await createCommentsRouter({})`."
|
|
64
|
+
].join("\n");
|
|
65
|
+
|
|
66
|
+
// src/cli.ts
|
|
67
|
+
var CLIENT_ID_PATTERN = /^[\w-]+\.apps\.googleusercontent\.com$/;
|
|
68
|
+
var args = process.argv.slice(2);
|
|
69
|
+
var flag = (name, fallback) => {
|
|
70
|
+
const i = args.indexOf(name);
|
|
71
|
+
return i >= 0 && args[i + 1] ? args[i + 1] : fallback;
|
|
72
|
+
};
|
|
73
|
+
var usage = () => {
|
|
74
|
+
console.log("Usage: npx @kiriti/comments-server init [--dir <project folder>] [--file .env]");
|
|
75
|
+
process.exit(args.includes("--help") ? 0 : 1);
|
|
76
|
+
};
|
|
77
|
+
var rl = createInterface({ input: stdin, terminal: false });
|
|
78
|
+
var lines = [];
|
|
79
|
+
var waiting = null;
|
|
80
|
+
var closed = false;
|
|
81
|
+
rl.on("line", (line) => {
|
|
82
|
+
if (waiting) {
|
|
83
|
+
const resolveLine = waiting;
|
|
84
|
+
waiting = null;
|
|
85
|
+
resolveLine(line);
|
|
86
|
+
} else {
|
|
87
|
+
lines.push(line);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
rl.on("close", () => {
|
|
91
|
+
closed = true;
|
|
92
|
+
waiting?.(null);
|
|
93
|
+
});
|
|
94
|
+
var nextLine = () => {
|
|
95
|
+
if (lines.length) return Promise.resolve(lines.shift());
|
|
96
|
+
if (closed) return Promise.resolve(null);
|
|
97
|
+
return new Promise((r) => {
|
|
98
|
+
waiting = r;
|
|
99
|
+
});
|
|
100
|
+
};
|
|
101
|
+
var ask = async (question, fallback = "") => {
|
|
102
|
+
stdout.write(fallback ? `${question} [${fallback}]: ` : `${question}: `);
|
|
103
|
+
const line = await nextLine();
|
|
104
|
+
if (line === null) throw new Error("Input ended before setup finished. Nothing was written.");
|
|
105
|
+
if (!stdin.isTTY) stdout.write(`${line}
|
|
106
|
+
`);
|
|
107
|
+
return line.trim() || fallback;
|
|
108
|
+
};
|
|
109
|
+
var confirm = async (question) => /^y(es)?$/i.test(await ask(`${question} (y/N)`));
|
|
110
|
+
var askValid = async (question, validate, fallback = "") => {
|
|
111
|
+
for (; ; ) {
|
|
112
|
+
const value = await ask(question, fallback);
|
|
113
|
+
const error = validate(value);
|
|
114
|
+
if (!error) return value;
|
|
115
|
+
console.log(` \u2717 ${error}`);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
var canConnect = async (url) => {
|
|
119
|
+
const client = new MongoClient(url, { serverSelectionTimeoutMS: 5e3 });
|
|
120
|
+
try {
|
|
121
|
+
await client.connect();
|
|
122
|
+
await client.db("admin").command({ ping: 1 });
|
|
123
|
+
return null;
|
|
124
|
+
} catch (e) {
|
|
125
|
+
return e instanceof Error ? e.message : String(e);
|
|
126
|
+
} finally {
|
|
127
|
+
await client.close().catch(() => void 0);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
var askMongo = async () => {
|
|
131
|
+
for (; ; ) {
|
|
132
|
+
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://");
|
|
133
|
+
process.stdout.write(" Checking connection\u2026 ");
|
|
134
|
+
const error = await canConnect(url);
|
|
135
|
+
if (!error) {
|
|
136
|
+
console.log("\u2713 connected");
|
|
137
|
+
return url;
|
|
138
|
+
}
|
|
139
|
+
console.log(`\u2717 ${error}`);
|
|
140
|
+
if (await confirm(" Save it anyway (e.g. the database isn't reachable from this machine)?")) return url;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
var parseOrigins = (value) => {
|
|
144
|
+
try {
|
|
145
|
+
value.split(",").map((v) => v.trim()).filter(Boolean).forEach(normalizeOrigin);
|
|
146
|
+
return null;
|
|
147
|
+
} catch (e) {
|
|
148
|
+
return e.message.replace("comments-server: ", "");
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
var collect = async (present) => {
|
|
152
|
+
const values = {};
|
|
153
|
+
const skip = (key) => {
|
|
154
|
+
if (!present.has(key)) return false;
|
|
155
|
+
console.log(`\u2022 ${key} is already in the file \u2014 keeping it.`);
|
|
156
|
+
return true;
|
|
157
|
+
};
|
|
158
|
+
if (!skip(ENV_KEYS.mongoUrl)) values[ENV_KEYS.mongoUrl] = await askMongo();
|
|
159
|
+
if (!skip(ENV_KEYS.db)) values[ENV_KEYS.db] = await ask("Database name", "comments");
|
|
160
|
+
if (!skip(ENV_KEYS.googleClientId)) {
|
|
161
|
+
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.");
|
|
162
|
+
}
|
|
163
|
+
let origins = [];
|
|
164
|
+
if (!skip(ENV_KEYS.allowedOrigins)) {
|
|
165
|
+
const raw = await askValid("Sites that will show comments, comma-separated (e.g. https://example.com,http://localhost:5173)", parseOrigins);
|
|
166
|
+
origins = [...new Set(raw.split(",").map((v) => v.trim()).filter(Boolean).map(normalizeOrigin))];
|
|
167
|
+
values[ENV_KEYS.allowedOrigins] = origins.join(",");
|
|
168
|
+
}
|
|
169
|
+
if (!skip(ENV_KEYS.moderatorEmails)) {
|
|
170
|
+
const emails = await ask("Moderator Google emails, comma-separated (optional)");
|
|
171
|
+
if (emails) values[ENV_KEYS.moderatorEmails] = emails.split(",").map((e) => e.trim().toLowerCase()).filter(Boolean).join(",");
|
|
172
|
+
}
|
|
173
|
+
if (!skip(ENV_KEYS.sessionSecret)) {
|
|
174
|
+
values[ENV_KEYS.sessionSecret] = randomBytes(48).toString("base64url");
|
|
175
|
+
console.log(`\u2022 Generated ${ENV_KEYS.sessionSecret} (64 random characters).`);
|
|
176
|
+
}
|
|
177
|
+
return { values, origins };
|
|
178
|
+
};
|
|
179
|
+
var main = async () => {
|
|
180
|
+
if (args[0] !== "init" || args.includes("--help")) return usage();
|
|
181
|
+
const dir = resolve(flag("--dir", "."));
|
|
182
|
+
const envPath = resolve(dir, flag("--file", ".env"));
|
|
183
|
+
const existing = existsSync(envPath) ? readFileSync(envPath, "utf8") : "";
|
|
184
|
+
console.log(`
|
|
185
|
+
Setting up @kiriti/comments-server in ${envPath}
|
|
186
|
+
Nothing already in the file will be changed.
|
|
187
|
+
`);
|
|
188
|
+
const { values, origins } = await collect(envKeys(existing));
|
|
189
|
+
const merged = mergeEnv(existing, values);
|
|
190
|
+
if (merged.added.length) writeFileSync(envPath, merged.text, { mode: 384 });
|
|
191
|
+
const gitignorePath = resolve(dir, ".gitignore");
|
|
192
|
+
const gitignore = ensureGitignore(existsSync(gitignorePath) ? readFileSync(gitignorePath, "utf8") : null);
|
|
193
|
+
if (gitignore.changed) writeFileSync(gitignorePath, gitignore.text);
|
|
194
|
+
console.log("");
|
|
195
|
+
console.log(merged.added.length ? `\u2713 Added to ${envPath}: ${merged.added.join(", ")}` : `\u2713 ${envPath} already had every setting; nothing written.`);
|
|
196
|
+
console.log(gitignore.changed ? "\u2713 Added .env to .gitignore" : "\u2713 .env is already git-ignored");
|
|
197
|
+
console.log(`
|
|
198
|
+
${googleSteps(origins)}
|
|
199
|
+
|
|
200
|
+
${deploySteps(merged.added.length ? merged.added : Object.values(ENV_KEYS))}
|
|
201
|
+
`);
|
|
202
|
+
};
|
|
203
|
+
main().catch((e) => {
|
|
204
|
+
console.error(`
|
|
205
|
+
\u2717 ${e instanceof Error ? e.message : String(e)}`);
|
|
206
|
+
process.exitCode = 1;
|
|
207
|
+
}).finally(() => rl.close());
|