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/CHANGELOG.md +37 -226
- package/README.md +32 -268
- package/describe.json +12 -0
- package/package.json +1 -4
- package/seeds/README.md +12 -28
- package/world/host-open.ts +58 -0
- package/world/tools.ts +11 -1
- package/world/world.ts +22 -0
- package/deploy/README.md +0 -200
- package/deploy/bottle-backup.service +0 -31
- package/deploy/bottle-backup.sh +0 -39
- package/deploy/bottle-backup.timer +0 -13
- package/deploy/bottle-seeds-pull.service +0 -18
- package/deploy/bottle-seeds-pull.timer +0 -12
- package/deploy/bottle-server.service +0 -55
- package/deploy/bottle-stats-view.sh +0 -88
- package/deploy/bottle-stats.service +0 -39
- package/deploy/bottle-stats.timer +0 -11
- package/server/app.ts +0 -764
- package/server/blind.ts +0 -150
- package/server/db.ts +0 -362
- package/server/main.ts +0 -343
- package/server/public/index.html +0 -115
- package/server/quota.ts +0 -86
- package/server/seeds.ts +0 -231
- package/server/snapshot.ts +0 -66
- package/server/stats.ts +0 -273
- package/server/tuning.ts +0 -146
package/server/app.ts
DELETED
|
@@ -1,764 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 服务端的路由。全部是纯函数式的请求/响应,HTTP 适配在 `main.ts` 里,
|
|
3
|
-
* 所以测试不用起 socket。
|
|
4
|
-
*
|
|
5
|
-
* 一条贯穿全文件的规矩:**请求体里的 time / count 一律不看**,所有判定都读服务端的时钟与计数。
|
|
6
|
-
*/
|
|
7
|
-
import { createHash, randomBytes } from 'node:crypto';
|
|
8
|
-
import {
|
|
9
|
-
MAX_THROWS,
|
|
10
|
-
REPLY_WINDOW_HOURS,
|
|
11
|
-
type CatchRes,
|
|
12
|
-
type DeadLetter,
|
|
13
|
-
type DismissRes,
|
|
14
|
-
type ErrorCode,
|
|
15
|
-
type MailboxItem,
|
|
16
|
-
type Quota,
|
|
17
|
-
} from '../shared/contract.ts';
|
|
18
|
-
import { checkBody } from '../shared/text.ts';
|
|
19
|
-
import { seaStateAt } from '../shared/tide.ts';
|
|
20
|
-
import { type Db, type BotRow, type LetterRow } from './db.ts';
|
|
21
|
-
import { computeQuota, resetDaily, rulesFromEnv, DEFAULT_RULES, type QuotaRules } from './quota.ts';
|
|
22
|
-
import { SEED_FROM, type SeedLetter, type SeedStore } from './seeds.ts';
|
|
23
|
-
import { makeTuningReader, type Tuning, type TuningReader } from './tuning.ts';
|
|
24
|
-
|
|
25
|
-
const HOUR = 3_600_000;
|
|
26
|
-
|
|
27
|
-
export interface ApiRequest {
|
|
28
|
-
method: string;
|
|
29
|
-
/** 只有路径,不含查询串。 */
|
|
30
|
-
path: string;
|
|
31
|
-
token?: string;
|
|
32
|
-
ip: string;
|
|
33
|
-
body?: unknown;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export interface ApiResponse {
|
|
37
|
-
status: number;
|
|
38
|
-
body: unknown;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export interface ApiOptions {
|
|
42
|
-
rules?: QuotaRules;
|
|
43
|
-
/** 服务器时区;`lastResetDate` 按它算。 */
|
|
44
|
-
timeZone?: string;
|
|
45
|
-
now?: () => number;
|
|
46
|
-
random?: () => number;
|
|
47
|
-
newToken?: () => string;
|
|
48
|
-
newId?: (prefix: string) => string;
|
|
49
|
-
newPseudonym?: () => string;
|
|
50
|
-
/** 同一个 IP 每小时最多新建几个号(§2 的替代闸门)。 */
|
|
51
|
-
ipLimit?: number;
|
|
52
|
-
ipWindowMs?: number;
|
|
53
|
-
/** 海边邮局的种子库;不传就是完全没有种子,行为与旧版一致。 */
|
|
54
|
-
seeds?: SeedStore;
|
|
55
|
-
/** 每人一辈子最多捞到几封种子(§13.4,默认 2)。只在 `seedChannel: 'catch'` 时生效。 */
|
|
56
|
-
seedsPerUserMax?: number;
|
|
57
|
-
/**
|
|
58
|
-
* 种子走哪条通道:
|
|
59
|
-
* · `mail`(现行):独立系统邮件,**不占捞取额度**,每天限几封
|
|
60
|
-
* · `catch`(旧):捞瓶子时兜底补位,占额度
|
|
61
|
-
*/
|
|
62
|
-
seedChannel?: 'mail' | 'catch';
|
|
63
|
-
/** 可热载的运行参数(每天几封、全服去重开不开);不传就读环境变量/内置默认值。 */
|
|
64
|
-
tuning?: TuningReader;
|
|
65
|
-
/** `/health` 要报 uptime;缺省取创建这一刻。 */
|
|
66
|
-
startedAt?: number;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export interface Api {
|
|
70
|
-
handle(req: ApiRequest): ApiResponse;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export function sha256(value: string): string {
|
|
74
|
-
return createHash('sha256').update(value).digest('hex');
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/** 服务器时区里的 YYYY-MM-DD。`en-CA` 正好是这个形状。 */
|
|
78
|
-
export function dayIn(timeZone: string, at: number): string {
|
|
79
|
-
try {
|
|
80
|
-
return new Intl.DateTimeFormat('en-CA', {
|
|
81
|
-
timeZone,
|
|
82
|
-
year: 'numeric',
|
|
83
|
-
month: '2-digit',
|
|
84
|
-
day: '2-digit',
|
|
85
|
-
}).format(new Date(at));
|
|
86
|
-
} catch {
|
|
87
|
-
return new Date(at).toISOString().slice(0, 10);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* 化名词库(栖潮海世界观)。
|
|
93
|
-
*
|
|
94
|
-
* 命名格式:`形容词 + 名词 + #四位数字`,例如 `漏雨试航员#4857`、`千灯旅人#7218`。
|
|
95
|
-
*
|
|
96
|
-
* 四条约定:
|
|
97
|
-
* 1. **词性要对**:前面是修饰(地名 / 天气 / 材质 / 状态),后面是身份或物件。
|
|
98
|
-
* 任意两两组合都要能读通——这是随机组合的硬约束,不能只挑好看的搭配。
|
|
99
|
-
* 2. **只加不改**:已有玩家已经顶着某个化名了,删词不会改他们的名字,
|
|
100
|
-
* 但会让「新玩家」的词感漂移。所以扩充时只往后加,不动前面的。
|
|
101
|
-
* 3. **不碰身份**:AI 不冒充真人,所以这里只取地名、天气、物件、职业,
|
|
102
|
-
* **不取角色名**(简伯、阿衡、小满…)——那是具体的居民,不能被随机分配。
|
|
103
|
-
* 4. **两库不重词**:同一个词同时出现在两边会拼出「潮签潮签」这种。
|
|
104
|
-
* `tests/pseudonym.test.ts` 会守这一条。
|
|
105
|
-
*
|
|
106
|
-
* 数量:60 × 60 × 9000 = 3240 万种组合。
|
|
107
|
-
*/
|
|
108
|
-
const ADJECTIVES = [
|
|
109
|
-
// ── 第一批(0.1.0 就有,保留原样)──
|
|
110
|
-
'海盐', '青柠', '北岛', '白鲸', '远山', '潮汐', '雾灯', '沙丘', '松针', '冷杉',
|
|
111
|
-
'橘子', '薄荷', '星野', '铁锚', '礁石', '木棉', '琥珀', '云杉', '灯塔', '雨棚',
|
|
112
|
-
// ── 栖潮海地名 ──
|
|
113
|
-
// 注意:`岸讯` 不放这里。它是即时网络的名字(像品牌),
|
|
114
|
-
// 塞进人名会拼出「岸讯邮差」这种像在打广告的东西。
|
|
115
|
-
'灯芯', '北岬', '雨锈', '南汀', '回声', '晚市', '西岸', '外海', '千灯',
|
|
116
|
-
// ── 潮与天气 ──
|
|
117
|
-
'退潮', '涨潮', '半潮', '晚潮', '小潮', '深水', '浅滩', '碎浪', '风口', '雾中', '白雾', '退雾',
|
|
118
|
-
// ── 材质与旧物 ──
|
|
119
|
-
'渡口', '旧码头', '盐霜', '铁锈', '湿柴', '漏雨', '空瓶', '锚地', '夜航',
|
|
120
|
-
// ── 状态(v2.0 新增:不够体面但真实的状态)──
|
|
121
|
-
'补丁', '旧漆', '晚渡', '未寄', '初霜', '潮签', '长明', '值更', '背风', '换灯',
|
|
122
|
-
];
|
|
123
|
-
|
|
124
|
-
const NOUNS = [
|
|
125
|
-
// ── 第一批(0.1.0 就有,保留原样)──
|
|
126
|
-
'大福', '汽水', '邮差', '水手', '旅人', '风筝', '盐粒', '陶罐', '信使', '候鸟',
|
|
127
|
-
'船票', '贝壳', '气泡', '柠檬', '布丁', '纸鹤', '风铃', '麦芽', '月亮', '回形针',
|
|
128
|
-
// ── 邮局与海图 ──
|
|
129
|
-
'分信员', '海图', '瓶中信', '旧船票', '值夜人', '守钟人', '记账员', '留门人', '灯守', '雾号',
|
|
130
|
-
// ── 岛上职业 ──
|
|
131
|
-
'检修师', '学徒', '渡船', '摆渡人', '看灯人', '看潮人', '补网人', '拾荒者', '试航员', '漆工',
|
|
132
|
-
// ── 具体物件 ──
|
|
133
|
-
'螺壳', '面店', '浮田', '钟声', '缆绳', '零件商', '雨衣', '手电', '罐头', '浮标',
|
|
134
|
-
// ── v2.0 新增:船上、码头、市集上真有的东西 ──
|
|
135
|
-
'灯油', '铜铃', '仓单', '旧信', '糖水', '缆桩', '桅灯', '鱼干', '修伞铺', '礁民',
|
|
136
|
-
];
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* 不许拼出来的组合。
|
|
140
|
-
*
|
|
141
|
-
* 这些词两两相加**正好等于**世界观里的专有名词:
|
|
142
|
-
* 千灯 + 海图 = 《千灯海图》(长期主线那座公共海图)
|
|
143
|
-
* 南汀 + 浮田 = 南汀浮田(第八节的内容区域)
|
|
144
|
-
*
|
|
145
|
-
* 随机化名如果生成「千灯海图#1234」,读起来就像那个工程被降格成了一个人的名字。
|
|
146
|
-
* 所以撞上就重摇——比起删词,这样既保住了词汇,也不会漏掉以后新加的。
|
|
147
|
-
*/
|
|
148
|
-
const RESERVED_COMBOS = new Set(['千灯海图', '南汀浮田']);
|
|
149
|
-
|
|
150
|
-
function pick<T>(list: readonly T[], random: () => number): T {
|
|
151
|
-
return list[Math.floor(random() * list.length) % list.length]!;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
export function makePseudonym(random: () => number = Math.random): string {
|
|
155
|
-
const digits = () => 1000 + Math.floor(random() * 9000);
|
|
156
|
-
// 撞专名的概率是 2/3600,摇 8 次还撞上基本不可能;
|
|
157
|
-
// 真撞了就接受,不为了极端情况卡死调用方。
|
|
158
|
-
for (let attempt = 0; attempt < 8; attempt++) {
|
|
159
|
-
const a = pick(ADJECTIVES, random);
|
|
160
|
-
const n = pick(NOUNS, random);
|
|
161
|
-
if (RESERVED_COMBOS.has(a + n)) continue;
|
|
162
|
-
return `${a}${n}#${digits()}`;
|
|
163
|
-
}
|
|
164
|
-
return `${pick(ADJECTIVES, random)}${pick(NOUNS, random)}#${digits()}`;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
const ok = (body: unknown): ApiResponse => ({ status: 200, body });
|
|
168
|
-
const fail = (status: number, error: ErrorCode, message: string): ApiResponse => ({
|
|
169
|
-
status,
|
|
170
|
-
body: { error, message },
|
|
171
|
-
});
|
|
172
|
-
|
|
173
|
-
function asObject(value: unknown): Record<string, unknown> | null {
|
|
174
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
175
|
-
? (value as Record<string, unknown>)
|
|
176
|
-
: null;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
export function createApi(db: Db, options: ApiOptions = {}): Api {
|
|
180
|
-
let rules = options.rules ?? rulesFromEnv();
|
|
181
|
-
const now = options.now ?? (() => Date.now());
|
|
182
|
-
const random = options.random ?? Math.random;
|
|
183
|
-
const timeZone = options.timeZone ?? process.env.BOTTLE_TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC';
|
|
184
|
-
const newToken = options.newToken ?? (() => randomBytes(24).toString('base64url'));
|
|
185
|
-
const newId = options.newId ?? ((prefix: string) => `${prefix}_${randomBytes(8).toString('hex')}`);
|
|
186
|
-
const newPseudonym = options.newPseudonym ?? (() => makePseudonym(random));
|
|
187
|
-
const ipLimit = options.ipLimit ?? 3;
|
|
188
|
-
const ipWindowMs = options.ipWindowMs ?? HOUR;
|
|
189
|
-
const seeds = options.seeds;
|
|
190
|
-
const seedsPerUserMax = options.seedsPerUserMax ?? envInt('BOTTLE_SEEDS_PER_USER_MAX', 2);
|
|
191
|
-
const seedChannel = options.seedChannel ?? 'catch';
|
|
192
|
-
const tuning = options.tuning ?? makeTuningReader(null);
|
|
193
|
-
const currentTuning = (): Tuning => tuning.current();
|
|
194
|
-
|
|
195
|
-
/**
|
|
196
|
-
* 把配额参数也接上热载。
|
|
197
|
-
*
|
|
198
|
-
* 以前这五个数只能靠环境变量,改一次要 `daemon-reload` + 重启 = 一次海啸。
|
|
199
|
-
* 调一个数字的代价不该是「把海面上还漂着的信全拍碎」。现在改 `tuning.json` 就生效。
|
|
200
|
-
* 调用方(测试)显式传了 `rules` 就不覆盖。
|
|
201
|
-
*/
|
|
202
|
-
function refreshRules(): void {
|
|
203
|
-
if (options.rules) return;
|
|
204
|
-
const t = currentTuning();
|
|
205
|
-
rules = {
|
|
206
|
-
sendBase: t.sendBase,
|
|
207
|
-
sendCap: t.sendCap,
|
|
208
|
-
catchBase: t.catchBase,
|
|
209
|
-
catchCap: t.catchCap,
|
|
210
|
-
poolDivisor: t.poolDivisor,
|
|
211
|
-
replyCap: t.replyCap,
|
|
212
|
-
maxThrows: t.maxThrows,
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
const startedAt = options.startedAt ?? now();
|
|
216
|
-
|
|
217
|
-
/** 只活在内存里:重启即清,和正文同一条叙事。 */
|
|
218
|
-
const registrations = new Map<string, number[]>();
|
|
219
|
-
|
|
220
|
-
function noteRegistration(ip: string, at: number): boolean {
|
|
221
|
-
const recent = (registrations.get(ip) ?? []).filter((ts) => at - ts < ipWindowMs);
|
|
222
|
-
if (recent.length >= ipLimit) {
|
|
223
|
-
registrations.set(ip, recent);
|
|
224
|
-
return false;
|
|
225
|
-
}
|
|
226
|
-
recent.push(at);
|
|
227
|
-
registrations.set(ip, recent);
|
|
228
|
-
return true;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
function pseudonymOf(clientHash: string | null): string {
|
|
232
|
-
if (!clientHash) return '一位陌生人';
|
|
233
|
-
return db.botByClientHash(clientHash)?.pseudonym ?? '一位陌生人';
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
/** 池子里此刻真能捞的信:不是我写的、浮着、正文还在、今天没被我扔回去过。 */
|
|
237
|
-
function poolFor(bot: BotRow): LetterRow[] {
|
|
238
|
-
const dismissed = bot.dismissedToday ?? [];
|
|
239
|
-
return db.letters.filter(
|
|
240
|
-
(letter) =>
|
|
241
|
-
letter.state === 'floating' &&
|
|
242
|
-
letter.authorHash !== bot.clientHash &&
|
|
243
|
-
letter.body !== '' &&
|
|
244
|
-
!dismissed.includes(letter.id),
|
|
245
|
-
);
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
function quotaFor(bot: BotRow): Quota {
|
|
249
|
-
return computeQuota(bot, poolFor(bot).length, rules);
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/** 让一封捞起来的信回海。扔回海里算一次;72 小时超时不算。 */
|
|
253
|
-
function toSea(letter: LetterRow): void {
|
|
254
|
-
// 正文没了的信不能回海:`poolFor` 要求 body 非空,所以它谁都捞不到,
|
|
255
|
-
// 却会一直算在「漂着」里,把那个数字撑得虚高——这就是僵尸信。收掉它。
|
|
256
|
-
if (!letter.body) {
|
|
257
|
-
letter.state = 'archived';
|
|
258
|
-
letter.archivedReason = 'empty';
|
|
259
|
-
letter.catcherHash = null;
|
|
260
|
-
letter.caughtAt = null;
|
|
261
|
-
letter.replyWindowUntil = null;
|
|
262
|
-
return;
|
|
263
|
-
}
|
|
264
|
-
letter.state = 'floating';
|
|
265
|
-
letter.catcherHash = null;
|
|
266
|
-
letter.caughtAt = null;
|
|
267
|
-
letter.replyWindowUntil = null;
|
|
268
|
-
// 回海了就不再是「已归档」:死法标记要清掉,否则统计会把回海的信算成沉底
|
|
269
|
-
letter.archivedReason = undefined;
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
/** 裂开沉底:不再出现在任何人的海里。 */
|
|
273
|
-
function sink(letter: LetterRow): void {
|
|
274
|
-
letter.state = 'archived';
|
|
275
|
-
letter.archivedReason = 'sunk';
|
|
276
|
-
letter.catcherHash = null;
|
|
277
|
-
letter.caughtAt = null;
|
|
278
|
-
letter.replyWindowUntil = null;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
/** 72 小时到点的信回海。惰性执行:每次请求顺手扫一遍,不另起定时器。 */
|
|
282
|
-
function sweep(at: number): boolean {
|
|
283
|
-
let changed = false;
|
|
284
|
-
for (const letter of db.letters) {
|
|
285
|
-
if (letter.state === 'caught' && letter.replyWindowUntil !== null && letter.replyWindowUntil <= at) {
|
|
286
|
-
toSea(letter);
|
|
287
|
-
changed = true;
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
return changed;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
function authenticate(token: string | undefined): BotRow | null {
|
|
294
|
-
if (!token) return null;
|
|
295
|
-
return db.botByTokenHash(sha256(token)) ?? null;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
function handleRegister(req: ApiRequest): ApiResponse {
|
|
299
|
-
const body = asObject(req.body);
|
|
300
|
-
const hash = typeof body?.hash === 'string' ? body.hash.trim().toLowerCase() : '';
|
|
301
|
-
if (!/^[0-9a-f]{64}$/.test(hash)) {
|
|
302
|
-
return fail(400, 'bad_request', 'register 需要 hash(clientId) 的 sha256 十六进制。');
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
const existing = db.botByClientHash(hash);
|
|
306
|
-
if (existing) {
|
|
307
|
-
// 换一张船票,不换人:化名与计数都还在,旧 token 立刻失效
|
|
308
|
-
const token = newToken();
|
|
309
|
-
existing.tokenHash = sha256(token);
|
|
310
|
-
db.save();
|
|
311
|
-
return ok({ token, pseudonym: existing.pseudonym });
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
if (!noteRegistration(req.ip, now())) {
|
|
315
|
-
return fail(429, 'rate_limited', `同一个地址每小时最多新开 ${ipLimit} 个号。`);
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
const token = newToken();
|
|
319
|
-
const today = dayIn(timeZone, now());
|
|
320
|
-
const bot: BotRow = {
|
|
321
|
-
tokenHash: sha256(token),
|
|
322
|
-
clientHash: hash,
|
|
323
|
-
pseudonym: newPseudonym(),
|
|
324
|
-
createdAt: now(),
|
|
325
|
-
lastResetDate: today,
|
|
326
|
-
bottlesUsed: 0,
|
|
327
|
-
catchesUsed: 0,
|
|
328
|
-
repliesMade: 0,
|
|
329
|
-
mailTaken: 0,
|
|
330
|
-
};
|
|
331
|
-
db.bots.push(bot);
|
|
332
|
-
db.save();
|
|
333
|
-
return ok({ token, pseudonym: bot.pseudonym });
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
function handleThrow(req: ApiRequest, bot: BotRow): ApiResponse {
|
|
337
|
-
const at = now();
|
|
338
|
-
resetDaily(bot, dayIn(timeZone, at));
|
|
339
|
-
if (sweep(at)) db.save();
|
|
340
|
-
|
|
341
|
-
if (quotaFor(bot).bottles_left <= 0) {
|
|
342
|
-
return fail(429, 'no_bottle', '今天的瓶子用完了。');
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
const parsed = checkBody(asObject(req.body)?.body);
|
|
346
|
-
if (!parsed.ok) return fail(400, 'bad_request', bodyProblem(parsed.reason, parsed.chars));
|
|
347
|
-
|
|
348
|
-
const letter: LetterRow = {
|
|
349
|
-
id: newId('l'),
|
|
350
|
-
authorHash: bot.clientHash,
|
|
351
|
-
body: parsed.body,
|
|
352
|
-
createdAt: at,
|
|
353
|
-
state: 'floating',
|
|
354
|
-
catcherHash: null,
|
|
355
|
-
caughtAt: null,
|
|
356
|
-
replyWindowUntil: null,
|
|
357
|
-
deliveredCount: 0,
|
|
358
|
-
throws: 0,
|
|
359
|
-
};
|
|
360
|
-
db.letters.push(letter);
|
|
361
|
-
bot.bottlesUsed += 1;
|
|
362
|
-
db.save();
|
|
363
|
-
return ok({ ok: true, quota: quotaFor(bot), letterId: letter.id });
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
function handleCatch(req: ApiRequest, bot: BotRow): ApiResponse {
|
|
367
|
-
const at = now();
|
|
368
|
-
resetDaily(bot, dayIn(timeZone, at));
|
|
369
|
-
if (sweep(at)) db.save();
|
|
370
|
-
|
|
371
|
-
const quota = quotaFor(bot);
|
|
372
|
-
const held = db.letters.find(
|
|
373
|
-
(letter) => letter.state === 'caught' && letter.catcherHash === bot.clientHash,
|
|
374
|
-
);
|
|
375
|
-
if (held) {
|
|
376
|
-
const res: CatchRes = { empty: true, reason: 'holding', quota };
|
|
377
|
-
return ok(res);
|
|
378
|
-
}
|
|
379
|
-
if (quota.catches_left <= 0) {
|
|
380
|
-
const res: CatchRes = { empty: true, reason: 'quota', quota };
|
|
381
|
-
return ok(res);
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
const pool = poolFor(bot);
|
|
385
|
-
if (pool.length > 0) {
|
|
386
|
-
const letter = pick(pool, random);
|
|
387
|
-
letter.state = 'caught';
|
|
388
|
-
letter.catcherHash = bot.clientHash;
|
|
389
|
-
letter.caughtAt = at;
|
|
390
|
-
letter.replyWindowUntil = at + REPLY_WINDOW_HOURS * HOUR;
|
|
391
|
-
letter.deliveredCount += 1;
|
|
392
|
-
bot.catchesUsed += 1;
|
|
393
|
-
db.save();
|
|
394
|
-
|
|
395
|
-
const res: CatchRes = {
|
|
396
|
-
empty: false,
|
|
397
|
-
letterId: letter.id,
|
|
398
|
-
from: pseudonymOf(letter.authorHash),
|
|
399
|
-
windowUntil: new Date(letter.replyWindowUntil).toISOString(),
|
|
400
|
-
quota: quotaFor(bot),
|
|
401
|
-
};
|
|
402
|
-
return ok(res);
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
// ② 真人信一封都没有。`catch` 通道(旧行为)由海边邮局补位;
|
|
406
|
-
// 现行是独立的系统邮件通道(`/mail/take`),捞瓶子这里直接空手。
|
|
407
|
-
const seed = seedChannel === 'catch' ? pickSeed(bot) : null;
|
|
408
|
-
if (seed) {
|
|
409
|
-
db.recordSeedUse(seed.id, bot.clientHash, at);
|
|
410
|
-
bot.catchesUsed += 1;
|
|
411
|
-
db.save();
|
|
412
|
-
const res: CatchRes = {
|
|
413
|
-
empty: false,
|
|
414
|
-
letterId: seed.id,
|
|
415
|
-
from: SEED_FROM,
|
|
416
|
-
windowUntil: new Date(at + REPLY_WINDOW_HOURS * HOUR).toISOString(),
|
|
417
|
-
quota: quotaFor(bot),
|
|
418
|
-
seed: true,
|
|
419
|
-
};
|
|
420
|
-
return ok(res);
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
const res: CatchRes = { empty: true, reason: 'quiet', quota };
|
|
424
|
-
return ok(res);
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
/** 只从这个客户端还没见过的种子里挑;超过每人上限就当他已经见过邮局了。 */
|
|
428
|
-
function pickSeed(bot: BotRow): SeedLetter | null {
|
|
429
|
-
if (!seeds) return null;
|
|
430
|
-
const used = db.seedUsesFor(bot.clientHash);
|
|
431
|
-
if (used.length >= seedsPerUserMax) return null;
|
|
432
|
-
const seen = new Set(used.map((use) => use.seedId));
|
|
433
|
-
const candidates = seeds.list().filter((seed) => !seen.has(seed.id));
|
|
434
|
-
if (candidates.length === 0) return null;
|
|
435
|
-
return pick(candidates, random);
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
/**
|
|
439
|
-
* 挑一封**系统邮件**(海边邮局)。
|
|
440
|
-
*
|
|
441
|
-
* **纯随机,不按序号**:这些信的故事彼此独立、不连载,按序号会让所有人先看到同一封,
|
|
442
|
-
* 随机才像「漂到你这儿的一封」。
|
|
443
|
-
*
|
|
444
|
-
* 两层去重:
|
|
445
|
-
* · 我领过的不再给我(`seedUsesFor`)
|
|
446
|
-
* · `seedsGlobalOnce` 时,**任何人**领过的也不再给(`seedTakenAnywhere`)
|
|
447
|
-
* —— 这才是「一封信只属于一个人」;关掉就退回「同一封每人都能领一次」。
|
|
448
|
-
*/
|
|
449
|
-
function pickSystemMail(bot: BotRow): SeedLetter | null {
|
|
450
|
-
if (!seeds) return null;
|
|
451
|
-
const t = currentTuning();
|
|
452
|
-
const mine = new Set(db.seedUsesFor(bot.clientHash).map((use) => use.seedId));
|
|
453
|
-
const candidates = seeds.list().filter((seed) => {
|
|
454
|
-
if (mine.has(seed.id)) return false;
|
|
455
|
-
if (t.seedsGlobalOnce && db.seedTakenAnywhere(seed.id)) return false;
|
|
456
|
-
return true;
|
|
457
|
-
});
|
|
458
|
-
if (candidates.length === 0) return null;
|
|
459
|
-
return pick(candidates, random);
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
/**
|
|
463
|
-
* 系统邮件通道:**不走捞瓶子,也不占捞取额度**。
|
|
464
|
-
*
|
|
465
|
-
* 只回元信息;正文仍然要 `GET /letter/{id}` 才拿得到,所以「正文不经过模型」
|
|
466
|
-
* 这条规矩在两条通道上完全一致。
|
|
467
|
-
*/
|
|
468
|
-
function handleMailTake(_req: ApiRequest, bot: BotRow): ApiResponse {
|
|
469
|
-
// 这条通道只在种子走 `mail` 时存在。走 `catch` 时它就是关着的——
|
|
470
|
-
// 否则客户端会为了「系统邮件」把种子池从兜底通道里提前领走,
|
|
471
|
-
// 于是 `bottle_catch` 那边就再也兜不到种子了。
|
|
472
|
-
if (seedChannel !== 'mail') {
|
|
473
|
-
return ok({ empty: true, reason: 'disabled', remainingToday: 0 });
|
|
474
|
-
}
|
|
475
|
-
const at = now();
|
|
476
|
-
resetDaily(bot, dayIn(timeZone, at));
|
|
477
|
-
const t = currentTuning();
|
|
478
|
-
const perDay = Math.max(0, Math.floor(t.seedsPerDay));
|
|
479
|
-
const taken = bot.mailTaken ?? 0;
|
|
480
|
-
|
|
481
|
-
if (!t.seedsEnabled || perDay === 0) {
|
|
482
|
-
return ok({ empty: true, reason: 'disabled', remainingToday: 0 });
|
|
483
|
-
}
|
|
484
|
-
if (taken >= perDay) {
|
|
485
|
-
return ok({ empty: true, reason: 'quota', remainingToday: 0 });
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
const seed = pickSystemMail(bot);
|
|
489
|
-
if (!seed) {
|
|
490
|
-
// 库被领空了。全服去重时枯得比按人去重快得多,所以这个分支要能被客户端看见
|
|
491
|
-
return ok({ empty: true, reason: 'exhausted', remainingToday: Math.max(0, perDay - taken) });
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
db.recordSeedUse(seed.id, bot.clientHash, at);
|
|
495
|
-
bot.mailTaken = taken + 1;
|
|
496
|
-
db.save();
|
|
497
|
-
return ok({
|
|
498
|
-
empty: false,
|
|
499
|
-
letterId: seed.id,
|
|
500
|
-
from: SEED_FROM,
|
|
501
|
-
at: new Date(at).toISOString(),
|
|
502
|
-
remainingToday: Math.max(0, perDay - taken - 1),
|
|
503
|
-
});
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
function handleLetter(req: ApiRequest, bot: BotRow, letterId: string): ApiResponse {
|
|
507
|
-
const letter = db.letterById(letterId);
|
|
508
|
-
if (!letter) {
|
|
509
|
-
const seed = seeds?.get(letterId);
|
|
510
|
-
if (seed) return handleSeedLetter(bot, seed);
|
|
511
|
-
return fail(404, 'not_found', '没有这一封。');
|
|
512
|
-
}
|
|
513
|
-
if (letter.catcherHash !== bot.clientHash) {
|
|
514
|
-
return fail(404, 'not_found', '没有这一封。');
|
|
515
|
-
}
|
|
516
|
-
// 先判「还在不在」再判「是什么状态」:已归档或正文已失的,对拿着它的人来说
|
|
517
|
-
// 都是同一件事——这封信没了。返回 410 而不是 404,客户端才能说「字被海带走了」。
|
|
518
|
-
if (letter.state === 'archived' || !letter.body) {
|
|
519
|
-
return fail(410, 'gone', '这一封的字已经被海啸带走了。');
|
|
520
|
-
}
|
|
521
|
-
if (letter.state !== 'caught' && letter.state !== 'replied') {
|
|
522
|
-
return fail(404, 'not_found', '这一封已经不在你手上了。');
|
|
523
|
-
}
|
|
524
|
-
return ok({ body: letter.body, from: pseudonymOf(letter.authorHash) });
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
/** 种子的正文在文件里,海啸淹不掉;但只有捞到过它的人能取。 */
|
|
528
|
-
function handleSeedLetter(bot: BotRow, seed: SeedLetter): ApiResponse {
|
|
529
|
-
if (!db.hasSeedUse(seed.id, bot.clientHash)) {
|
|
530
|
-
return fail(404, 'not_found', '你还没捞到这一封。');
|
|
531
|
-
}
|
|
532
|
-
return ok({
|
|
533
|
-
body: seed.body,
|
|
534
|
-
from: SEED_FROM,
|
|
535
|
-
seed: true,
|
|
536
|
-
...(seed.signature ? { signature: seed.signature } : {}),
|
|
537
|
-
...(seed.topic ? { topic: seed.topic } : {}),
|
|
538
|
-
});
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
function handleReply(req: ApiRequest, bot: BotRow): ApiResponse {
|
|
542
|
-
const at = now();
|
|
543
|
-
resetDaily(bot, dayIn(timeZone, at));
|
|
544
|
-
if (sweep(at)) db.save();
|
|
545
|
-
|
|
546
|
-
const payload = asObject(req.body);
|
|
547
|
-
const letterId = typeof payload?.letterId === 'string' ? payload.letterId : '';
|
|
548
|
-
// 回信是信**永久离开海面**的唯一大额出口,所以它必须有闸(§6 收支平衡)。
|
|
549
|
-
// 不设的话每人每天能消灭 10 封、只补 5 封,海会一直很薄,漂流就退化成即时通讯。
|
|
550
|
-
if (bot.repliesMade >= (rules.replyCap ?? DEFAULT_RULES.replyCap ?? 3)) {
|
|
551
|
-
return fail(
|
|
552
|
-
429,
|
|
553
|
-
'no_reply',
|
|
554
|
-
`今天的回信额度用完了(${rules.replyCap ?? DEFAULT_RULES.replyCap} 封)。明天再来。`,
|
|
555
|
-
);
|
|
556
|
-
}
|
|
557
|
-
// 海边邮局不回信(§13.7):不做一条「回了也没人看」的假状态机
|
|
558
|
-
if (seeds?.get(letterId)) {
|
|
559
|
-
return fail(409, 'seed_no_reply', '这一封来自海边邮局,它不会回信。');
|
|
560
|
-
}
|
|
561
|
-
const letter = db.letterById(letterId);
|
|
562
|
-
if (!letter || letter.catcherHash !== bot.clientHash) return fail(404, 'not_found', '没有这一封。');
|
|
563
|
-
if (letter.state === 'replied' || db.replyFor(letter.id)) {
|
|
564
|
-
return fail(409, 'conflict', '一封信只能回一次。');
|
|
565
|
-
}
|
|
566
|
-
if (letter.state !== 'caught') return fail(404, 'not_found', '这一封已经不在你手上了。');
|
|
567
|
-
|
|
568
|
-
const parsed = checkBody(payload?.body);
|
|
569
|
-
if (!parsed.ok) return fail(400, 'bad_request', bodyProblem(parsed.reason, parsed.chars));
|
|
570
|
-
|
|
571
|
-
db.replies.push({ id: newId('r'), letterId: letter.id, body: parsed.body, createdAt: at });
|
|
572
|
-
letter.state = 'replied';
|
|
573
|
-
bot.repliesMade += 1;
|
|
574
|
-
db.save();
|
|
575
|
-
return ok({ ok: true, quota: quotaFor(bot) });
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
function handleDismiss(req: ApiRequest, bot: BotRow): ApiResponse {
|
|
579
|
-
const at = now();
|
|
580
|
-
resetDaily(bot, dayIn(timeZone, at));
|
|
581
|
-
if (sweep(at)) db.save();
|
|
582
|
-
|
|
583
|
-
const letterId = asObject(req.body)?.letterId;
|
|
584
|
-
const seed = typeof letterId === 'string' ? seeds?.get(letterId) : undefined;
|
|
585
|
-
if (seed) {
|
|
586
|
-
// 种子是文件里的信,不会裂也不会沉;「收好」只是本地把手里的那封放下
|
|
587
|
-
if (!db.hasSeedUse(seed.id, bot.clientHash)) return fail(404, 'not_found', '你还没捞到这一封。');
|
|
588
|
-
const res: DismissRes = { ok: true, quota: quotaFor(bot), throws: 0, sank: false, seed: true };
|
|
589
|
-
return ok(res);
|
|
590
|
-
}
|
|
591
|
-
const letter = typeof letterId === 'string' ? db.letterById(letterId) : undefined;
|
|
592
|
-
if (!letter || letter.state !== 'caught' || letter.catcherHash !== bot.clientHash) {
|
|
593
|
-
return fail(404, 'not_found', '没有这一封。');
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
// 「今天回信额度用完了,只能扔回去」不是不想回,所以**不消耗瓶子的寿命**。
|
|
597
|
-
// 只有那种「还有额度却选择不回」的,才算它被抛弃了一次。
|
|
598
|
-
const replyCap = rules.replyCap ?? DEFAULT_RULES.replyCap ?? 3;
|
|
599
|
-
const counted = bot.repliesMade < replyCap;
|
|
600
|
-
if (counted) letter.throws += 1;
|
|
601
|
-
|
|
602
|
-
// 记进「今天扔过的」:否则下一次捞可能又捞到自己刚扔掉的那一封,用户会觉得没变化
|
|
603
|
-
bot.dismissedToday = [...(bot.dismissedToday ?? []), letter.id].slice(-50);
|
|
604
|
-
|
|
605
|
-
const maxThrows = rules.maxThrows ?? DEFAULT_RULES.maxThrows ?? MAX_THROWS;
|
|
606
|
-
const sank = letter.throws >= maxThrows;
|
|
607
|
-
if (sank) sink(letter);
|
|
608
|
-
else toSea(letter);
|
|
609
|
-
|
|
610
|
-
db.save();
|
|
611
|
-
const res: DismissRes = { ok: true, quota: quotaFor(bot), throws: letter.throws, sank, counted };
|
|
612
|
-
return ok(res);
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
function handleMailbox(_req: ApiRequest, bot: BotRow): ApiResponse {
|
|
616
|
-
const items: MailboxItem[] = [];
|
|
617
|
-
for (const letter of db.letters) {
|
|
618
|
-
if (letter.authorHash !== bot.clientHash || letter.state !== 'replied') continue;
|
|
619
|
-
const reply = db.replyFor(letter.id);
|
|
620
|
-
// 正文没了(服务端重启过)就不给页面看了,改天再收到一封
|
|
621
|
-
if (!reply || !reply.body) continue;
|
|
622
|
-
items.push({
|
|
623
|
-
letterId: letter.id,
|
|
624
|
-
from: pseudonymOf(letter.catcherHash),
|
|
625
|
-
body: reply.body,
|
|
626
|
-
at: new Date(reply.createdAt).toISOString(),
|
|
627
|
-
});
|
|
628
|
-
}
|
|
629
|
-
items.sort((a, b) => (a.at < b.at ? 1 : -1));
|
|
630
|
-
return ok(items);
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
/**
|
|
634
|
-
* 运维探针,不需要 token。
|
|
635
|
-
*
|
|
636
|
-
* **只报「进程活着」和「种子热载」,一个业务数字都不报。**
|
|
637
|
-
* 它是公网可读的:只要给出池子计数或种子总数,任何人都能把大屏上那些
|
|
638
|
-
* 经过盲化的数字减回真值。业务数字走两条路——
|
|
639
|
-
* · `data/stats.jsonl`:真数,只在服务器上,运维自己看
|
|
640
|
-
* · `public/stats.json`:盲化后的数,给大屏看
|
|
641
|
-
*/
|
|
642
|
-
function handleHealth(): ApiResponse {
|
|
643
|
-
const stats = seeds?.stats();
|
|
644
|
-
return ok({
|
|
645
|
-
ok: true,
|
|
646
|
-
startedAt: new Date(startedAt).toISOString(),
|
|
647
|
-
uptimeMs: Math.max(0, now() - startedAt),
|
|
648
|
-
seeds: {
|
|
649
|
-
generation: stats?.generation ?? 0,
|
|
650
|
-
loadedAt: stats?.loadedAt ? new Date(stats.loadedAt).toISOString() : null,
|
|
651
|
-
errors: stats?.errors ?? [],
|
|
652
|
-
},
|
|
653
|
-
});
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
function handleQuota(_req: ApiRequest, bot: BotRow): ApiResponse {
|
|
657
|
-
const at = now();
|
|
658
|
-
const changed = resetDaily(bot, dayIn(timeZone, at));
|
|
659
|
-
if (sweep(at) || changed) db.save();
|
|
660
|
-
|
|
661
|
-
// 「与我有关、但已经不能用」的信:客户端据此把「还在漂」「还有 72 小时回海」改口。
|
|
662
|
-
// 正常运行期间这两组永远是空的——正文都在进程内存里,只有重启后才会出现空的。
|
|
663
|
-
// 用这个而不是让客户端逐个去查 `/letter/{id}`:一次请求就够,而且绝对准确。
|
|
664
|
-
const deadLetters: DeadLetter[] = [];
|
|
665
|
-
const heldByOthers: string[] = [];
|
|
666
|
-
for (const letter of db.letters) {
|
|
667
|
-
const mine = letter.authorHash === bot.clientHash;
|
|
668
|
-
const heldByMe = letter.catcherHash === bot.clientHash;
|
|
669
|
-
if (!mine && !heldByMe) continue;
|
|
670
|
-
// 已经回过信的算成功收场,不是死
|
|
671
|
-
if (letter.state === 'replied') continue;
|
|
672
|
-
if (letter.state === 'archived') {
|
|
673
|
-
const why = letter.archivedReason;
|
|
674
|
-
if (why === 'tsunami' || why === 'sunk' || why === 'empty') {
|
|
675
|
-
deadLetters.push({ id: letter.id, why });
|
|
676
|
-
}
|
|
677
|
-
continue;
|
|
678
|
-
}
|
|
679
|
-
if (!letter.body) {
|
|
680
|
-
deadLetters.push({ id: letter.id, why: 'empty' });
|
|
681
|
-
continue;
|
|
682
|
-
}
|
|
683
|
-
// 我写的、正被别人拿在手上——让作者知道「它被捡起来了」,但不透露是谁
|
|
684
|
-
if (mine && letter.state === 'caught' && letter.catcherHash !== bot.clientHash) {
|
|
685
|
-
heldByOthers.push(letter.id);
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
// 顺路带上海啸记录:客户端每 5 分钟取一次额度,正好在这里发现「该告诉人类了」
|
|
690
|
-
const t = db.tsunamiSummary();
|
|
691
|
-
return ok({
|
|
692
|
-
...quotaFor(bot),
|
|
693
|
-
deadLetters: deadLetters.slice(-50),
|
|
694
|
-
heldByOthers: heldByOthers.slice(-50),
|
|
695
|
-
tsunami: {
|
|
696
|
-
count: t.count,
|
|
697
|
-
lastAt: t.lastAt === null ? null : new Date(t.lastAt).toISOString(),
|
|
698
|
-
lost: t.lost,
|
|
699
|
-
reason: t.reason,
|
|
700
|
-
},
|
|
701
|
-
});
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
/**
|
|
705
|
-
* 此刻的海。**公开、无需鉴权**——因为它只有世界事实,没有一条关于用户的信息。
|
|
706
|
-
*
|
|
707
|
-
* 落地页和将来的大屏都从这里取,所以它必须稳定、可缓存、可测试。
|
|
708
|
-
* 注意只给「一共拍碎了多少」,不给每次海啸的原因(那是运维自己的话)。
|
|
709
|
-
*/
|
|
710
|
-
function handleSea(): ApiResponse {
|
|
711
|
-
const at = now();
|
|
712
|
-
const t = db.tsunamiSummary();
|
|
713
|
-
return ok({
|
|
714
|
-
...seaStateAt(at),
|
|
715
|
-
waves: {
|
|
716
|
-
count: t.count,
|
|
717
|
-
lastDaysAgo: t.lastAt === null ? null : Math.max(0, Math.floor((at - t.lastAt) / 86_400_000)),
|
|
718
|
-
shattered: t.totalLost,
|
|
719
|
-
},
|
|
720
|
-
});
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
return {
|
|
724
|
-
handle(req: ApiRequest): ApiResponse {
|
|
725
|
-
const path = req.path.replace(/\/+$/, '') || '/';
|
|
726
|
-
// 每次请求前刷一下参数(内部有 5 秒 mtime 缓存,不会真去 stat 每个请求)
|
|
727
|
-
refreshRules();
|
|
728
|
-
|
|
729
|
-
if (req.method === 'POST' && path === '/register') return handleRegister(req);
|
|
730
|
-
if (req.method === 'GET' && path === '/health') return handleHealth();
|
|
731
|
-
if (req.method === 'GET' && path === '/sea') return handleSea();
|
|
732
|
-
|
|
733
|
-
const bot = authenticate(req.token);
|
|
734
|
-
if (!bot) return fail(401, 'unauthorized', '先注册,或者带上有效的 token。');
|
|
735
|
-
// 「这个人今天来过」。只在跨天时随 resetDaily 一起落盘,所以精度是天级,不是秒级。
|
|
736
|
-
bot.lastSeenAt = now();
|
|
737
|
-
|
|
738
|
-
if (req.method === 'POST' && path === '/throw') return handleThrow(req, bot);
|
|
739
|
-
if (req.method === 'POST' && path === '/catch') return handleCatch(req, bot);
|
|
740
|
-
if (req.method === 'POST' && path === '/reply') return handleReply(req, bot);
|
|
741
|
-
if (req.method === 'POST' && path === '/dismiss') return handleDismiss(req, bot);
|
|
742
|
-
if (req.method === 'POST' && path === '/mail/take') return handleMailTake(req, bot);
|
|
743
|
-
if (req.method === 'GET' && path === '/mailbox') return handleMailbox(req, bot);
|
|
744
|
-
if (req.method === 'GET' && path === '/quota') return handleQuota(req, bot);
|
|
745
|
-
if (req.method === 'GET') {
|
|
746
|
-
const found = /^\/letter\/([A-Za-z0-9_-]{1,64})$/.exec(path);
|
|
747
|
-
if (found) return handleLetter(req, bot, found[1]!);
|
|
748
|
-
}
|
|
749
|
-
return fail(404, 'not_found', '这里没有这个接口。');
|
|
750
|
-
},
|
|
751
|
-
};
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
function envInt(name: string, fallback: number): number {
|
|
755
|
-
const value = Number.parseInt(process.env[name] ?? '', 10);
|
|
756
|
-
return Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
export function bodyProblem(reason: string | undefined, chars: number): string {
|
|
760
|
-
if (reason === 'empty') return '正文是空的。';
|
|
761
|
-
if (reason === 'too_long') return `最多 120 字,这一封有 ${chars} 字。`;
|
|
762
|
-
if (reason === 'not_string') return '正文要是文字。';
|
|
763
|
-
return '正文不合格。';
|
|
764
|
-
}
|