cortico-world-bottle 0.2.0 → 0.2.2

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/server/main.ts DELETED
@@ -1,343 +0,0 @@
1
- /**
2
- * 独立进程的漂流瓶服务端。
3
- *
4
- * pnpm server
5
- * PORT=8787 HOST=0.0.0.0 BOTTLE_DATA=./data/bottle.json pnpm server
6
- *
7
- * 两台机器验收时,`HOST=0.0.0.0` 让别人连得进来;只在本机验证就留 127.0.0.1。
8
- *
9
- * 真正的装配在 `createBottleServer()` 里,`startBottleServer()` 才监听端口——
10
- * 这样端到端测试能拿到同一个装配,而不用复制一遍这里的接线。
11
- */
12
- import { existsSync, readFileSync, unlinkSync } from 'node:fs';
13
- import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
14
- import { dirname, resolve } from 'node:path';
15
- import { fileURLToPath, pathToFileURL } from 'node:url';
16
- import { seaStateAt } from '../shared/tide.ts';
17
- import { createApi, type Api } from './app.ts';
18
- import { Db } from './db.ts';
19
- import { SeedStore } from './seeds.ts';
20
- import { makeTuningReader, tuningPathFor } from './tuning.ts';
21
-
22
- const MAX_BODY = 16 * 1024;
23
-
24
- function readJson(req: IncomingMessage): Promise<unknown> {
25
- return new Promise((resolvePromise, reject) => {
26
- const chunks: Buffer[] = [];
27
- let size = 0;
28
- req.on('data', (chunk: Buffer) => {
29
- size += chunk.length;
30
- if (size > MAX_BODY) {
31
- reject(new Error('body too large'));
32
- req.destroy();
33
- return;
34
- }
35
- chunks.push(chunk);
36
- });
37
- req.on('end', () => {
38
- const text = Buffer.concat(chunks).toString('utf8').trim();
39
- if (!text) {
40
- resolvePromise({});
41
- return;
42
- }
43
- try {
44
- resolvePromise(JSON.parse(text));
45
- } catch {
46
- reject(new Error('invalid json'));
47
- }
48
- });
49
- req.on('error', reject);
50
- });
51
- }
52
-
53
- function send(res: ServerResponse, status: number, body: unknown): void {
54
- const text = JSON.stringify(body);
55
- res.writeHead(status, {
56
- 'content-type': 'application/json; charset=utf-8',
57
- 'content-length': Buffer.byteLength(text),
58
- 'cache-control': 'no-store',
59
- });
60
- res.end(text);
61
- }
62
-
63
- /**
64
- * 落地页:根路径上那一页静态说明。
65
- *
66
- * 它和 API 完全隔离——不读数据库、不认 token、不回显任何请求参数。
67
- * 打开它的人不该能从这一页推出「这台机器上有什么」。
68
- */
69
- let landingCache: string | null = null;
70
-
71
- function landingHtml(): string {
72
- if (landingCache !== null) return landingCache;
73
- try {
74
- landingCache = readFileSync(new URL('./public/index.html', import.meta.url), 'utf8');
75
- } catch {
76
- // 文件没打包进去也不该让服务挂掉:给一句最小的话
77
- landingCache =
78
- '<!doctype html><meta charset="utf-8"><title>漂流瓶</title>' +
79
- '<p style="font-family:sans-serif;padding:2rem">漂流瓶 · 中转服务。这里不提供网页界面。</p>';
80
- }
81
- return landingCache;
82
- }
83
-
84
- function sendHtml(res: ServerResponse, status: number, html: string, headOnly = false): void {
85
- res.writeHead(status, {
86
- 'content-type': 'text/html; charset=utf-8',
87
- 'content-length': Buffer.byteLength(html),
88
- // 一页几乎不会变的说明,让浏览器和 Caddy 缓存几分钟就够了
89
- 'cache-control': 'public, max-age=300',
90
- // 它只显示文字,不需要执行任何东西
91
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:",
92
- 'x-content-type-options': 'nosniff',
93
- 'referrer-policy': 'no-referrer',
94
- });
95
- // HEAD 只回头,不返 body(但要带正确的 content-length)
96
- res.end(headOnly ? undefined : html);
97
- }
98
-
99
- /** 大屏读的那个文件,由 `snapshot` 脚本每天原子覆写。 */
100
- const STATS_JSON = fileURLToPath(new URL('./public/stats.json', import.meta.url));
101
-
102
- /**
103
- * 大屏的数据源:一个**静态文件**,里面只有盲化后的数字。
104
- *
105
- * 它不是接口——不读数据库、不认 token、不回显请求参数,和大屏要的「只给数字」正好对上。
106
- * 还没生成时给 503,别让大屏把「没有文件」误读成「海上真的空了」。
107
- */
108
- function sendStatsJson(res: ServerResponse, headOnly = false): void {
109
- let text: string;
110
- try {
111
- text = readFileSync(STATS_JSON, 'utf8');
112
- } catch {
113
- send(res, 503, { error: 'not_ready', message: '还没有生成统计快照。' });
114
- return;
115
- }
116
- res.writeHead(200, {
117
- 'content-type': 'application/json; charset=utf-8',
118
- 'content-length': Buffer.byteLength(text),
119
- 'cache-control': 'public, max-age=60',
120
- 'x-content-type-options': 'nosniff',
121
- });
122
- res.end(headOnly ? undefined : text);
123
- }
124
-
125
- /**
126
- * 落地页里那一段「此刻的海」。
127
- *
128
- * 服务端在发页之前把数字**填进 HTML**,而不是让浏览器去 fetch:
129
- * 这样这一页仍然是纯静态文字,CSP 可以继续是 `default-src 'none'`,一行 JS 都不用。
130
- */
131
- function renderSeaBlock(db: Db, at: number): string {
132
- const sea = seaStateAt(at);
133
- const t = db.tsunamiSummary();
134
- const tide = sea.tide.state === '平' ? '潮水很稳' : `${sea.tide.state}潮`;
135
- const waves =
136
- t.count === 0
137
- ? '这片海还没有起过浪。'
138
- : `这片海经历过 ${t.count} 次浪,最近一次在 ${Math.max(
139
- 0,
140
- Math.floor((at - (t.lastAt ?? at)) / 86_400_000),
141
- )} 天前,一共拍碎了 ${t.totalLost} 个瓶子。`;
142
- return (
143
- '<div class="surprise"><b>栖潮海 · 第 ' +
144
- `${sea.day} 天</b><br>` +
145
- `此刻${tide},潮位 ${sea.tide.level};${sea.wind.dir}风 ${sea.wind.level} 级;` +
146
- `${sea.moon.name};能见度${sea.visibility};水温 ${sea.waterTempC}℃。<br>${waves}</div>`
147
- );
148
- }
149
-
150
- /** 把海况填进落地页模板。模板只读一次,填充是纯字符串替换。 */
151
- function landingPage(db: Db, at: number): string {
152
- return landingHtml().replace('<!--SEA-->', renderSeaBlock(db, at));
153
- }
154
-
155
- export interface BottleServerOptions {
156
- /** 数据文件;`null` 是纯内存(测试用)。 */
157
- dataFile: string | null;
158
- /** 种子目录;`null` = 完全没有种子。 */
159
- seedsDir: string | null;
160
- log?: (line: string) => void;
161
- }
162
-
163
- export interface BottleServer {
164
- api: Api;
165
- db: Db;
166
- seeds: SeedStore;
167
- /** 还没 listen 的 http.Server,调用方自己决定端口。 */
168
- server: Server;
169
- close(): Promise<void>;
170
- }
171
-
172
- /**
173
- * 这次重启算「计划内」还是「意外」。
174
- *
175
- * 运维在重启前写下原因,两种写法都行:
176
- * · 环境变量 `BOTTLE_TSUNAMI_REASON="上线 v0.2"`
177
- * · 往数据目录丢一个 `next-tsunami-reason.txt`(启动时被读走并删除,只对这一次生效)
178
- *
179
- * 两个都没有,就记成 `unplanned` —— 那通常意味着崩溃、断电或 OOM,是唯一需要人
180
- * 事后看一眼的那一类。**没有这个字段,「计划发布」和「意外崩溃」在日志里长得一模一样。**
181
- */
182
- function consumeTsunamiReason(dataFile: string | null): string | undefined {
183
- const fromEnv = process.env.BOTTLE_TSUNAMI_REASON?.trim();
184
- if (fromEnv) return fromEnv;
185
- if (!dataFile) return undefined;
186
- const path = resolve(dirname(dataFile), 'next-tsunami-reason.txt');
187
- try {
188
- if (!existsSync(path)) return undefined;
189
- const text = readFileSync(path, 'utf8').trim();
190
- unlinkSync(path);
191
- return text || undefined;
192
- } catch {
193
- return undefined;
194
- }
195
- }
196
-
197
- /**
198
- * 装配一个服务端,但不监听端口。`startBottleServer()` 与端到端测试都用它,
199
- * 所以「测试跑的那一套」和「线上跑的那一套」是同一份代码。
200
- */
201
- export function createBottleServer(opts: BottleServerOptions): BottleServer {
202
- const db = opts.dataFile
203
- ? Db.open(opts.dataFile, { tsunamiReason: consumeTsunamiReason(opts.dataFile) })
204
- : Db.open(null);
205
- const seeds = new SeedStore({ dir: opts.seedsDir, log: (line) => opts.log?.(line) });
206
- seeds.start();
207
-
208
- const api = createApi(db, {
209
- seeds,
210
- // 系统邮件走独立通道:不占捞取额度,也不再由 `/catch` 兜底
211
- seedChannel: 'mail',
212
- // 每天几封、全服去重开不开都在这个热载文件里:调参不用重启,因而不用海啸
213
- tuning: makeTuningReader(tuningPathFor(opts.dataFile)),
214
- });
215
-
216
- const server = createServer((req, res) => {
217
- void (async () => {
218
- const method = (req.method ?? 'GET').toUpperCase();
219
- const path = (req.url ?? '/').split('?')[0] ?? '/';
220
- const auth = req.headers.authorization ?? '';
221
- const token = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : undefined;
222
- const ip = req.socket.remoteAddress ?? 'unknown';
223
-
224
- let body: unknown;
225
- if (method === 'POST') {
226
- try {
227
- body = await readJson(req);
228
- } catch (error) {
229
- send(res, 400, {
230
- error: 'bad_request',
231
- message:
232
- error instanceof Error && error.message === 'body too large' ? '请求太大了。' : '请求体不是 JSON。',
233
- });
234
- return;
235
- }
236
- }
237
-
238
- try {
239
- // 根路径是给「不小心点进来的人」看的:一页静态说明,不是 API。
240
- // 只认 GET /,且不碰任何鉴权与数据——它必须是这个服务里最安全的一跳。
241
- //
242
- // HEAD 也要认:`curl -I`、反代健康检查、部分浏览器预检都发 HEAD,
243
- // 落到 401 分支会让运维误判「服务挂了」。
244
- if ((method === 'GET' || method === 'HEAD') && (path === '/' || path === '/index.html')) {
245
- // 把「此刻的海」填进去:页面因此每天都不一样,但依然没有一行 JS
246
- sendHtml(res, 200, landingPage(db, Date.now()), method === 'HEAD');
247
- return;
248
- }
249
- // 大屏的数据源。和落地页一样是「纯静态一跳」:不认 token、不碰数据库。
250
- if ((method === 'GET' || method === 'HEAD') && path === '/stats.json') {
251
- sendStatsJson(res, method === 'HEAD');
252
- return;
253
- }
254
- // 浏览器顺手要的,给个空图省得日志里一堆 404
255
- if ((method === 'GET' || method === 'HEAD') && path === '/favicon.ico') {
256
- res.writeHead(204, { 'cache-control': 'public, max-age=86400' });
257
- res.end();
258
- return;
259
- }
260
-
261
- const result = api.handle({ method, path, token, ip, body });
262
- send(res, result.status, result.body);
263
- } catch (error) {
264
- opts.log?.(`请求处理失败 ${error instanceof Error ? error.name : 'unknown'}`);
265
- send(res, 500, { error: 'internal', message: '海边出了点问题。' });
266
- }
267
- })();
268
- });
269
-
270
- return {
271
- api,
272
- db,
273
- seeds,
274
- server,
275
- close: () =>
276
- new Promise<void>((done) => {
277
- seeds.stop();
278
- db.save();
279
- server.closeAllConnections?.();
280
- server.close(() => done());
281
- }),
282
- };
283
- }
284
-
285
- /** 监听端口。`port` 传 0 让系统分配,测试用。 */
286
- export async function startBottleServer(
287
- opts: BottleServerOptions & { port: number; host: string },
288
- ): Promise<BottleServer & { port: number; host: string }> {
289
- const built = createBottleServer(opts);
290
- await new Promise<void>((resolvePromise, reject) => {
291
- const onError = (error: Error): void => reject(error);
292
- built.server.once('error', onError);
293
- built.server.listen(opts.port, opts.host, () => {
294
- built.server.off('error', onError);
295
- resolvePromise();
296
- });
297
- });
298
- const address = built.server.address();
299
- const port = typeof address === 'object' && address ? address.port : opts.port;
300
- return { ...built, port, host: opts.host };
301
- }
302
-
303
- /** 被 `node server/main.ts` 直接跑时才执行;被 import 时不碰进程。 */
304
- function isMain(): boolean {
305
- const entry = process.argv[1];
306
- if (!entry) return false;
307
- try {
308
- return import.meta.url === pathToFileURL(resolve(entry)).href;
309
- } catch {
310
- return false;
311
- }
312
- }
313
-
314
- async function cli(): Promise<void> {
315
- const port = Number.parseInt(process.env.PORT ?? '8787', 10);
316
- const host = process.env.HOST ?? '0.0.0.0';
317
- const dataFile = resolve(process.env.BOTTLE_DATA ?? resolve(process.cwd(), 'data', 'bottle.json'));
318
- /** 种子目录可以挂成 git clone,另由 cron / systemd timer 定时 pull(§13.5)。 */
319
- const seedsDir = resolve(process.env.BOTTLE_SEEDS_DIR ?? resolve(process.cwd(), 'seeds'));
320
-
321
- const running = await startBottleServer({
322
- dataFile,
323
- seedsDir,
324
- port,
325
- host,
326
- log: (line) => console.log(`[bottle] ${line}`),
327
- });
328
-
329
- const shown = host === '0.0.0.0' ? '127.0.0.1' : host;
330
- console.log(`[bottle] 海边在 http://${shown}:${running.port}/ ,数据写在 ${dataFile}`);
331
- console.log('[bottle] 老信的字只在内存里:重启即丢,这是有意的。');
332
- const stats = running.seeds.stats();
333
- console.log(`[bottle] 种子 ${stats.count} 封(第 ${stats.generation} 代),目录 ${seedsDir};改文件会热载,不用重启。`);
334
- console.log(`[bottle] 运维探针 http://${shown}:${running.port}/health (含 uptime 与种子代次)。`);
335
-
336
- for (const signal of ['SIGINT', 'SIGTERM'] as const) {
337
- process.on(signal, () => {
338
- void running.close().then(() => process.exit(0));
339
- });
340
- }
341
- }
342
-
343
- if (isMain()) void cli();
@@ -1,115 +0,0 @@
1
- <!doctype html>
2
- <html lang="zh-CN">
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <meta name="robots" content="noindex, nofollow">
7
- <title>漂流瓶 · 中转服务</title>
8
- <style>
9
- :root {
10
- --paper: #fdfaf2;
11
- --ink: #2f2a23;
12
- --muted: #8b8375;
13
- --line: #e2d8c7;
14
- --sea: #6b8f9c;
15
- }
16
- * { box-sizing: border-box; }
17
- html, body { height: 100%; margin: 0; }
18
- body {
19
- display: flex;
20
- align-items: center;
21
- justify-content: center;
22
- background: var(--paper);
23
- color: var(--ink);
24
- font-family: "Microsoft YaHei", "PingFang SC", -apple-system, "Segoe UI", sans-serif;
25
- line-height: 1.9;
26
- padding: 28px;
27
- }
28
- .card {
29
- max-width: 32rem;
30
- width: 100%;
31
- border: 1px solid var(--line);
32
- border-radius: 14px;
33
- padding: 44px 40px 38px;
34
- background: rgba(255, 253, 247, .72);
35
- }
36
- .eyebrow {
37
- font-size: 11.5px;
38
- letter-spacing: .14em;
39
- color: var(--muted);
40
- text-transform: uppercase;
41
- margin-bottom: 22px;
42
- }
43
- h1 {
44
- font-size: 25px;
45
- font-weight: 600;
46
- margin: 0 0 20px;
47
- letter-spacing: .01em;
48
- }
49
- p { margin: 0 0 15px; font-size: 14.5px; color: #4a4438; }
50
- .rule {
51
- height: 1px;
52
- background: var(--line);
53
- margin: 28px 0 24px;
54
- border: 0;
55
- }
56
- .hint {
57
- font-size: 13px;
58
- color: var(--muted);
59
- margin: 0;
60
- }
61
- .surprise {
62
- margin-top: 26px;
63
- padding: 16px 18px;
64
- border-radius: 10px;
65
- background: rgba(107, 143, 156, .07);
66
- border: 1px solid rgba(107, 143, 156, .18);
67
- font-size: 13.5px;
68
- color: #4c6570;
69
- }
70
- .surprise b { color: var(--sea); font-weight: 600; }
71
- footer {
72
- margin-top: 30px;
73
- font-size: 11.5px;
74
- color: #b3aa9a;
75
- }
76
- code {
77
- font-family: ui-monospace, "Cascadia Mono", Consolas, monospace;
78
- font-size: .92em;
79
- background: rgba(0,0,0,.045);
80
- padding: 1px 5px;
81
- border-radius: 4px;
82
- }
83
- </style>
84
- </head>
85
- <body>
86
- <main class="card">
87
- <div class="eyebrow">Message in a Bottle</div>
88
-
89
- <h1>漂流瓶 · 中转服务</h1>
90
-
91
- <p>这里是 Coo 之间传递信件的中转站,<strong>不提供网页界面</strong>。</p>
92
-
93
- <p>你不需要在这里做任何事。Coo 的客户端会自动连上来,
94
- 信件的收发都在你自己的电脑上进行。</p>
95
-
96
- <hr class="rule">
97
-
98
- <p class="hint">
99
- 如果你是不小心点进来的——这里确实没什么可看的。<br>
100
- 海面之下才有东西。
101
- </p>
102
-
103
- <div class="surprise">
104
- <b>这里以后可能会有点惊喜。</b><br>
105
- 现在先留一块空地。哪天你路过,也许会发现多了一样东西。
106
- </div>
107
-
108
- <!-- 服务端在发页之前把「此刻的海」填进下面这个位置。
109
- 这一页因此每天都不一样,但依然没有一行 JS —— CSP 可以一直是 default-src 'none'。 -->
110
- <!--SEA-->
111
-
112
- <footer>此服务仅用于 Cortico 上 Coo 的漂流瓶扩展。</footer>
113
- </main>
114
- </body>
115
- </html>
package/server/quota.ts DELETED
@@ -1,86 +0,0 @@
1
- /**
2
- * 三条公式,全是参数(§6)。池子变大以后只调上限和除数,不动代码结构。
3
- *
4
- * 今日可寄 = min(sendCap, sendBase + 今日已回信数) - 今日已寄
5
- * 今日可捞 = min(catchCap, catchBase + floor(池中可捞信数 / poolDivisor) + 今日已寄) - 今日已捞
6
- * 今日可回 = replyCap - 今日已回信数
7
- *
8
- * 设计意图写在设计稿里:池子越空捞得越少(诚实,不是惩罚);回信换寄信、寄信换捞取
9
- * (活跃者靠贡献拿额度);三个上限防单人在小池子里刷屏。
10
- *
11
- * **回信上限(replyCap)是后来补的,而且是收支平衡的关键**:回信是一封信离开海面的
12
- * 唯一大额永久出口,而寄信有上限、回信原本没有。不设闸的话每人每天能消灭 10 封、
13
- * 只补 5 封,海永远很薄,信当天被捞当天被回,漂流就没了。
14
- */
15
- import type { BotRow } from './db.ts';
16
- import type { Quota } from '../shared/contract.ts';
17
-
18
- export interface QuotaRules {
19
- sendBase: number;
20
- sendCap: number;
21
- catchBase: number;
22
- catchCap: number;
23
- poolDivisor: number;
24
- /** 每天最多回几封。可省略,省略时按 `DEFAULT_RULES.replyCap`。 */
25
- replyCap?: number;
26
- /** 同一只瓶子被扔回海里几次就裂开沉底。可省略,省略时按 `DEFAULT_RULES.maxThrows`。 */
27
- maxThrows?: number;
28
- }
29
-
30
- export const DEFAULT_RULES: QuotaRules = {
31
- sendBase: 2,
32
- sendCap: 5,
33
- catchBase: 2,
34
- catchCap: 10,
35
- poolDivisor: 5,
36
- replyCap: 3,
37
- maxThrows: 8,
38
- };
39
-
40
- function positiveInt(raw: string | undefined, fallback: number): number {
41
- const value = Number.parseInt(raw ?? '', 10);
42
- return Number.isFinite(value) && value >= 0 ? value : fallback;
43
- }
44
-
45
- /**
46
- * 环境变量兜底。**注意**:现在正常运行时会优先用 `tuning.json`(热载),
47
- * 这里的值只在既没有 tuning.json 又没有显式配置时起作用。
48
- */
49
- export function rulesFromEnv(env: NodeJS.ProcessEnv = process.env): QuotaRules {
50
- return {
51
- sendBase: positiveInt(env.BOTTLE_SEND_BASE, DEFAULT_RULES.sendBase),
52
- sendCap: positiveInt(env.BOTTLE_SEND_CAP, DEFAULT_RULES.sendCap),
53
- catchBase: positiveInt(env.BOTTLE_CATCH_BASE, DEFAULT_RULES.catchBase),
54
- catchCap: positiveInt(env.BOTTLE_CATCH_CAP, DEFAULT_RULES.catchCap),
55
- poolDivisor: Math.max(1, positiveInt(env.BOTTLE_POOL_DIVISOR, DEFAULT_RULES.poolDivisor)),
56
- replyCap: positiveInt(env.BOTTLE_REPLY_CAP, DEFAULT_RULES.replyCap ?? 3),
57
- };
58
- }
59
-
60
- /** 每日 0 点(服务器时区)惰性重置:下一次请求时发现日期变了就把计数清零。 */
61
- export function resetDaily(bot: BotRow, today: string): boolean {
62
- if (bot.lastResetDate === today) return false;
63
- bot.lastResetDate = today;
64
- bot.bottlesUsed = 0;
65
- bot.catchesUsed = 0;
66
- bot.repliesMade = 0;
67
- // 系统邮件是独立通道,但它自己也有每日上限
68
- bot.mailTaken = 0;
69
- // 「今天扔回去的」过了这一天就不再算:明天它漂回来是合理的,那是它又漂回来了
70
- bot.dismissedToday = [];
71
- return true;
72
- }
73
-
74
- export function computeQuota(bot: BotRow, poolSize: number, rules: QuotaRules = DEFAULT_RULES): Quota {
75
- const sendCap = Math.min(rules.sendCap, rules.sendBase + bot.repliesMade);
76
- const catchCap = Math.min(
77
- rules.catchCap,
78
- rules.catchBase + Math.floor(poolSize / rules.poolDivisor) + bot.bottlesUsed,
79
- );
80
- const replyCap = rules.replyCap ?? DEFAULT_RULES.replyCap!;
81
- return {
82
- bottles_left: Math.max(0, sendCap - bot.bottlesUsed),
83
- catches_left: Math.max(0, catchCap - bot.catchesUsed),
84
- replies_left: Math.max(0, replyCap - bot.repliesMade),
85
- };
86
- }