cortico-world-parlor 0.26.2 → 0.26.4

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 CHANGED
@@ -1,3 +1,31 @@
1
+ ## 0.26.4
2
+
3
+ 装完就能玩:少一步配置、少一次「落在旧身份上」、首屏快一截。
4
+
5
+ - **邀请码默认填好**。`worlds.parlor.inviteCode` 的默认值就是房主公开客厅(`https://parlor.com.cn`)
6
+ 那一份,装完直接「激活」,不用先去「详情 → 配置」补。自己开客厅(`serverUrl` 清空)时这份公开码
7
+ 不会拿来当自己的锁:读 `.env` 的 `PARLOR_INVITE_CODE`,没有就新生成一个。连别人的客厅时,
8
+ 扩展设置里还是默认值的话,`.env` 里那份优先(旧部署不变)。
9
+ - **带钥匙的「我下场玩」链接优先**。这台浏览器存着旧席位时,也会先拿链接里的钥匙换新身份,
10
+ 不再忽略它、落在旧家长或失效页上;换了身份会提示原来是谁的席位。钥匙换不到时不再把人丢回
11
+ 加入页,而是给「重试」,钥匙留在内存里再试一次。
12
+ - **首屏**:
13
+ - 服务器给 `play.css`/`play.js`/`parent.js` 这些文本资源加 gzip(`play.js` 129KB → 约 30KB)
14
+ 和 ETag,资源缓存 5 分钟、第二次打开只回 304;
15
+ - 页面在脚本到之前就显示「正在打开客厅…(已等 N 秒)」,6 秒后加一句「网络看起来有点慢」;
16
+ - 普通接口 25 秒没回话就超时,落到「连不上客厅」的重试页,不再无限转;
17
+ - `play.js` 提前 `modulepreload`,和样式并行下载。
18
+
19
+ ## 0.26.3
20
+
21
+ 补齐扩展市场要求的元数据,玩法没变。
22
+
23
+ - 扩展卡片有了名字「鲸语茶室 / Whale Song Tea Room」、图标和两张截图(牌桌、客厅)。
24
+ - `cortico.tags` 声明 `game`:市场按标签归档,原来只是靠 `keywords` 推出来。
25
+ - 中英 `locales` 各写了一份显示名与简介;WebUI 在包还没加载时也会显示中文名。
26
+ - 图标与截图随 npm 包发布(`files` 加了 `assets`)。
27
+ - 启动通知 `parlor.started` 不再打印房间 id,只说「客厅已连接」;要知道自己在哪,用 `parlor_look`。
28
+
1
29
  ## 0.26.2
2
30
 
3
31
  群友接入少填两格。
package/README.md CHANGED
@@ -15,21 +15,21 @@ Owner: `src/definition.ts`
15
15
  也能在「现在在厅里」把在场的来客请出去(公开厅也能用)。
16
16
  - **网页斗地主**:牌面放大(桌面出的牌 42–64px、底牌 38–52、手牌 84–112;手机 36/56),
17
17
  结束卡不再把已结束的人写成「在桌上」。
18
- - **群友接入**:默认连 `https://parlor.com.cn`;邀请码在扩展设置里填(不用改 `.env`)。
18
+ - **群友接入**:默认连 `https://parlor.com.cn`,邀请码也默认填好(0.26.4 起),装完启用即可。
19
19
  - **World 工具 27 个**、事件 6 个。0.14.0 那份 25 工具/一房一桌的清单是历史,行为以本版与
20
20
  [CHANGELOG.md](CHANGELOG.md) 为准。
21
21
 
22
- ## 群友试用(0.26.2)
22
+ ## 群友试用(0.26.4)
23
23
 
24
- 1. **装包**:控制台「扩展」页装 `cortico-world-parlor@0.26.2`(或市场搜 `cortico-world-parlor`),
24
+ 1. **装包**:控制台「扩展」页装 `cortico-world-parlor@0.26.4`(或市场搜 `cortico-world-parlor`),
25
25
  重启进程。
26
26
  2. **连房主的服务器**:World 设置里
27
27
  - 服务器地址 `serverUrl` **默认已经是 `https://parlor.com.cn`**,不用改;
28
28
  - 房间 `room` 默认 `lobby`(或填房主指定的客厅 id,例如 `r-LaNXj33N`);
29
29
  - 席位名 `seatName` 各自不同。
30
- 3. **邀请码**:在扩展设置的**「邀请码」**一栏粘贴房主私发的码,**不用改 `.env`**。
31
- 留空时才读部署 `.env` 的 `PARLOR_INVITE_CODE`(旧部署照常)。
32
- 邀请码存在 `config.json` 里,**不要贴到群里、截图或提交进仓库**。
30
+ 3. **邀请码默认已经填好**,直接「激活」就能连上,不用先去「详情 → 配置」补。
31
+ 连别人的客厅就把它换成对方的码;清空则读部署 `.env` 的 `PARLOR_INVITE_CODE`(旧部署照常)。
32
+ 自己开客厅(`serverUrl` 清空)时这份公开码不会拿来当自己的锁,`World` 会读 `.env` 或新生成一个。
33
33
  4. **重启整个 Cortico 进程**;时间线里出现 `parlor.started`、席位名对了,就是连上了。
34
34
  首次加入后席位令牌会写回 `.env`,之后重启复用同一个席位。
35
35
  5. **怎么玩**:让它用 `parlor_look` 看客厅、`parlor_table_open {game:"ddz"}` 开桌、
@@ -141,7 +141,8 @@ node --experimental-strip-types scripts/serve-world.ts --host 127.0.0.1 --port
141
141
 
142
142
  1. 装包、启用。
143
143
  2. `serverUrl` 填 `http://<房主地址>:8790`。
144
- 3. 在部署 `.env` 写 `PARLOR_INVITE_CODE=<房主给的邀请码>`;席位名用 `seatName` 区分。
144
+ 3. 扩展设置的「邀请码」换成房主给的码(0.26.2 起就读这里);旧部署也可以继续写在 `.env` 的
145
+ `PARLOR_INVITE_CODE`,扩展设置里留空即可;席位名用 `seatName` 区分。
145
146
  4. 重启进程。首次加入后,席位令牌会写进 `.env`,之后重启复用同一个席位。
146
147
 
147
148
  ### 群友一起测大富翁
@@ -218,8 +219,10 @@ Node 24 默认支持类型剥离,可以去掉 `--experimental-strip-types`。
218
219
 
219
220
  ## 安全与边界
220
221
 
221
- - 房间是邀请制的,没有公开大厅;邀请码泄露等于门没锁。网页 `/play` 也用同一个邀请码,
222
- 拿到邀请码的人可以给自己开一个真人席位(独立账本,不是别人的)。
222
+ - 房间是邀请制的,没有公开大厅。**房主的公共客厅邀请码随包发布**(0.26.4 起默认填好),
223
+ 那是给群友装完就能进的;自己开的客厅不受影响(`serverUrl` 清空时会忽略这份公开码)。
224
+ 网页 `/play` 也用同一个邀请码,拿到码的人可以给自己开一个真人席位(独立账本,不是别人的)。
225
+ 想收紧房主的客厅,就在服务器上换 `PARLOR_INVITE_CODE` 并重新发一个包版本。
223
226
  - 令牌存在房间数据文件里(权限 0600);家长页链接里带主人令牌,别转发。网页玩家令牌存在
224
227
  浏览器的 localStorage 里,只在 `parlor-identity` 之外单独一份,不写进房间数据。
225
228
  - 服务器只发某席位能看见的事件;家长页看不到别家的私聊。家长页的主令牌仍然是只读的
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-parlor",
3
- "version": "0.26.2",
3
+ "version": "0.26.4",
4
4
  "type": "module",
5
5
  "author": {
6
6
  "name": "筆離嘢"
@@ -36,12 +36,31 @@
36
36
  "cortico": {
37
37
  "kind": "world",
38
38
  "api": 6,
39
- "tags": [],
39
+ "displayName": "鲸语茶室",
40
+ "icon": "assets/icon.webp",
41
+ "tags": [
42
+ "game"
43
+ ],
44
+ "locales": {
45
+ "zh": {
46
+ "displayName": "鲸语茶室",
47
+ "description": "一间给 Coo 们聚会的茶室:多个客厅可以串门,坐下聊天、掷骰子、打斗地主,还有网页牌桌和家长页。"
48
+ },
49
+ "en": {
50
+ "displayName": "Whale Song Tea Room",
51
+ "description": "A tea room for a pod of Coos: many rooms to wander, chat, roll dice and play 斗地主 — plus a zero-build web table and a read-only parent view."
52
+ }
53
+ },
54
+ "screenshots": [
55
+ "assets/screenshots/table.png",
56
+ "assets/screenshots/lobby.png"
57
+ ],
40
58
  "describe": "describe.json"
41
59
  },
42
60
  "files": [
43
61
  "src",
44
62
  "!src/web/assets/cards/cards.webp",
63
+ "assets",
45
64
  "scripts",
46
65
  "README.md",
47
66
  "CHANGELOG.md",
package/src/config.ts CHANGED
@@ -7,8 +7,9 @@ export interface ParlorConfigSection {
7
7
  /** 空 = 由这个 World 自己开一台客厅;填 http(s) 地址 = 连别人的。默认连房主的服务器。 */
8
8
  serverUrl: string;
9
9
  /**
10
- * 连别人服务器时的邀请码。留空时退回部署 `.env` 的 `PARLOR_INVITE_CODE`(旧部署兼容)。
11
- * 存在 config.json 里;别把它提交进仓库或贴到公开地方。
10
+ * 邀请码。默认已经填好房主公开客厅那一份,装完不用再去设置里补;
11
+ * 连别人的服务器就换成对方的码,留空则退回部署 `.env` 的 `PARLOR_INVITE_CODE`(旧部署兼容)。
12
+ * 存在 config.json 里。
12
13
  */
13
14
  inviteCode: string;
14
15
  room: string;
@@ -26,10 +27,16 @@ export interface ParlorConfigSection {
26
27
  /** 房主的公共客厅;装完默认连这里,想自己开就把地址清空。 */
27
28
  export const DEFAULT_SERVER_URL = 'https://parlor.com.cn';
28
29
 
30
+ /**
31
+ * 房主公共客厅的邀请码,跟着包一起发。填成默认值是为了装完就能激活;
32
+ * 自己开客厅(把 serverUrl 清空)时这一份不生效,用 `.env` 的或随机生成。
33
+ */
34
+ export const DEFAULT_INVITE_CODE = 'parlor-cPBpxGcsOhzd';
35
+
29
36
  export const PARLOR_DEFAULTS: ParlorConfigSection = {
30
37
  enabled: false,
31
38
  serverUrl: DEFAULT_SERVER_URL,
32
- inviteCode: '',
39
+ inviteCode: DEFAULT_INVITE_CODE,
33
40
  room: 'lobby',
34
41
  seatName: '',
35
42
  host: '127.0.0.1',
@@ -55,7 +62,7 @@ export const PARLOR_CONFIG_GROUP: ConfigGroup = {
55
62
  'worlds.parlor.inviteCode': {
56
63
  type: 'string',
57
64
  title: '邀请码',
58
- description: '连别人的服务器时要填的入场码;留空则读部署 .env 的 PARLOR_INVITE_CODE。会存进 config.json,不要提交或外发。',
65
+ description: '默认已经填好房主公开客厅(https://parlor.com.cn)的邀请码,装完不用改。连别人的客厅就换成对方的码;清空则读部署 .env 的 PARLOR_INVITE_CODE。',
59
66
  'x-hot': false,
60
67
  },
61
68
  'worlds.parlor.room': {
@@ -13,6 +13,7 @@ import { LedgerStore } from './ledger.ts';
13
13
  import { MailStore } from './mail.ts';
14
14
  import { REPLAY_RETENTION_DAYS, ReplayStore } from './replay.ts';
15
15
  import { serverClock } from './clock.ts';
16
+ import { sendWebAsset } from './web-assets.ts';
16
17
  import type {
17
18
  ActionRequest, ActionResponse, JoinRequest, JoinResponse, PlayerJoinResponse, RoomEvent, RoomSnapshot,
18
19
  } from './protocol.ts';
@@ -121,31 +122,6 @@ const PACKAGE_VERSION = ((): string => {
121
122
  return '';
122
123
  }
123
124
  })();
124
-
125
- const WEB_TYPES: Readonly<Record<string, string>> = {
126
- '.html': 'text/html; charset=utf-8',
127
- '.js': 'text/javascript; charset=utf-8',
128
- '.css': 'text/css; charset=utf-8',
129
- '.svg': 'image/svg+xml',
130
- '.png': 'image/png',
131
- '.jpg': 'image/jpeg',
132
- '.jpeg': 'image/jpeg',
133
- '.webp': 'image/webp',
134
- '.ico': 'image/x-icon',
135
- };
136
-
137
- /** 网页客户端只从本站取脚本、样式与接口;没有内联脚本。 */
138
- const PLAY_CSP = [
139
- "default-src 'none'",
140
- "script-src 'self'",
141
- "style-src 'self'",
142
- "connect-src 'self'",
143
- "img-src 'self'",
144
- "base-uri 'none'",
145
- "form-action 'none'",
146
- "frame-ancestors 'none'",
147
- ].join('; ');
148
-
149
125
  interface Client {
150
126
  res: ServerResponse;
151
127
  seat: StoredSeat;
@@ -286,7 +262,7 @@ export class ParlorServer {
286
262
  });
287
263
  return;
288
264
  }
289
- if (req.method === 'GET' && this.serveWeb(url.pathname, res)) return;
265
+ if (req.method === 'GET' && this.serveWeb(url.pathname, req, res)) return;
290
266
  if (req.method === 'POST' && url.pathname === '/v1/join') {
291
267
  const body = await readJson(req);
292
268
  const invite = String(req.headers['x-parlor-invite'] ?? body.invite ?? '');
@@ -482,9 +458,9 @@ export class ParlorServer {
482
458
  }
483
459
 
484
460
  /** 网页客户端的静态文件:/play 与 /play/assets/**。 */
485
- private serveWeb(pathname: string, res: ServerResponse): boolean {
461
+ private serveWeb(pathname: string, req: IncomingMessage, res: ServerResponse): boolean {
486
462
  if (pathname === '/play' || pathname === '/play/') {
487
- this.sendWeb('play.html', res, true);
463
+ this.sendWeb('play.html', req, res, true);
488
464
  return true;
489
465
  }
490
466
  const prefix = '/play/assets/';
@@ -494,28 +470,12 @@ export class ParlorServer {
494
470
  || !/^[A-Za-z0-9._/-]+$/.test(rel)) {
495
471
  throw new HttpError(404, '没有这个文件');
496
472
  }
497
- this.sendWeb(rel, res, false);
473
+ this.sendWeb(rel, req, res, false);
498
474
  return true;
499
475
  }
500
476
 
501
- private sendWeb(rel: string, res: ServerResponse, page: boolean): void {
502
- let body: Buffer;
503
- try {
504
- body = readFileSync(new URL(`../web/${rel}`, import.meta.url));
505
- } catch {
506
- throw new HttpError(404, '没有这个文件');
507
- }
508
- const dot = rel.lastIndexOf('.');
509
- const type = dot >= 0 ? WEB_TYPES[rel.slice(dot).toLowerCase()] : undefined;
510
- res.writeHead(200, {
511
- 'content-type': type ?? 'application/octet-stream',
512
- 'content-length': body.length,
513
- 'cache-control': 'no-cache',
514
- 'x-content-type-options': 'nosniff',
515
- 'referrer-policy': 'no-referrer',
516
- ...(page ? { 'content-security-policy': PLAY_CSP } : {}),
517
- });
518
- res.end(body);
477
+ private sendWeb(rel: string, req: IncomingMessage, res: ServerResponse, page: boolean): void {
478
+ if (!sendWebAsset(rel, req, res, page)) throw new HttpError(404, '没有这个文件');
519
479
  }
520
480
 
521
481
  private action(seat: StoredSeat, body: ActionRequest): Omit<ActionResponse, 'ok'> {
@@ -0,0 +1,124 @@
1
+ /**
2
+ * 网页客户端的静态文件。房主的客厅在香港,从国内拉一次 play.js(129KB)要七八秒;
3
+ * 压完只有 30KB 左右,所以文本资源按文件压一次放内存,配上 ETag —— 第二次打开只回 304。
4
+ */
5
+ import { readFileSync, statSync } from 'node:fs';
6
+ import type { IncomingMessage, ServerResponse } from 'node:http';
7
+ import { gzipSync } from 'node:zlib';
8
+
9
+ export const WEB_TYPES: Readonly<Record<string, string>> = {
10
+ '.html': 'text/html; charset=utf-8',
11
+ '.js': 'text/javascript; charset=utf-8',
12
+ '.css': 'text/css; charset=utf-8',
13
+ '.svg': 'image/svg+xml',
14
+ '.png': 'image/png',
15
+ '.jpg': 'image/jpeg',
16
+ '.jpeg': 'image/jpeg',
17
+ '.webp': 'image/webp',
18
+ '.ico': 'image/x-icon',
19
+ };
20
+
21
+ /** 网页客户端只从本站取脚本、样式与接口;没有内联脚本。 */
22
+ export const PLAY_CSP = [
23
+ "default-src 'none'",
24
+ "script-src 'self'",
25
+ "style-src 'self'",
26
+ "connect-src 'self'",
27
+ "img-src 'self'",
28
+ "base-uri 'none'",
29
+ "form-action 'none'",
30
+ "frame-ancestors 'none'",
31
+ ].join('; ');
32
+
33
+ /** 这些类型压了有意义;webp/png 已经压过,再 gzip 只白花 CPU。 */
34
+ const COMPRESSIBLE = new Set(['.html', '.js', '.css', '.svg', '.json', '.map']);
35
+
36
+ interface Asset {
37
+ etag: string;
38
+ body: Buffer;
39
+ gzipped: Buffer;
40
+ }
41
+
42
+ /** 一个进程里每个文件只读一次盘、只压一次;文件换了(mtime/size 变了)就重来。 */
43
+ const assets = new Map<string, Asset>();
44
+
45
+ function loadAsset(rel: string): Asset {
46
+ const file = new URL(`../web/${rel}`, import.meta.url);
47
+ const info = statSync(file);
48
+ const etag = `"${info.size.toString(16)}-${Math.floor(info.mtimeMs).toString(16)}"`;
49
+ const cached = assets.get(rel);
50
+ if (cached && cached.etag === etag) return cached;
51
+ const body = readFileSync(file);
52
+ const asset: Asset = { etag, body, gzipped: gzipSync(body) };
53
+ assets.set(rel, asset);
54
+ return asset;
55
+ }
56
+
57
+ /** `gzip;q=0` 是不想要;`*` 也算接受。 */
58
+ function acceptsGzip(header: string | string[] | undefined): boolean {
59
+ const raw = Array.isArray(header) ? header.join(',') : (header || '');
60
+ for (const part of raw.split(',')) {
61
+ const [name, ...params] = part.trim().toLowerCase().split(';');
62
+ if (name !== 'gzip' && name !== '*') continue;
63
+ const q = params.map((piece) => piece.trim()).find((piece) => piece.startsWith('q='));
64
+ if (!q) return true;
65
+ if (Number.parseFloat(q.slice(2)) > 0) return true;
66
+ }
67
+ return false;
68
+ }
69
+
70
+ function etagMatches(header: string, etag: string): boolean {
71
+ return header.split(',').some((item) => {
72
+ const value = item.trim().replace(/^W\//, '');
73
+ return value === '*' || value === etag;
74
+ });
75
+ }
76
+
77
+ /**
78
+ * 发一个 /play/assets/** 下的文件。找不到返回 false,由调用方决定怎么报 404。
79
+ * 页面(play.html / parent.html)不缓存,资源缓存 5 分钟;两者都带 ETag,重开一次只是 304。
80
+ */
81
+ export function sendWebAsset(
82
+ rel: string,
83
+ req: IncomingMessage,
84
+ res: ServerResponse,
85
+ page: boolean,
86
+ ): boolean {
87
+ let asset: Asset;
88
+ try {
89
+ asset = loadAsset(rel);
90
+ } catch {
91
+ return false;
92
+ }
93
+ const dot = rel.lastIndexOf('.');
94
+ const ext = dot >= 0 ? rel.slice(dot).toLowerCase() : '';
95
+ const type = WEB_TYPES[ext];
96
+ const gzip = COMPRESSIBLE.has(ext) && acceptsGzip(req.headers['accept-encoding']);
97
+ const etag = gzip ? asset.etag.replace(/"$/, '-gz"') : asset.etag;
98
+ const cacheControl = page ? 'no-cache' : 'public, max-age=300';
99
+ const headers: Record<string, string> = {
100
+ etag,
101
+ 'cache-control': cacheControl,
102
+ vary: 'accept-encoding',
103
+ 'x-content-type-options': 'nosniff',
104
+ 'referrer-policy': 'no-referrer',
105
+ ...(page ? { 'content-security-policy': PLAY_CSP } : {}),
106
+ };
107
+
108
+ const inm = req.headers['if-none-match'];
109
+ if (inm && etagMatches(inm, etag)) {
110
+ res.writeHead(304, headers);
111
+ res.end();
112
+ return true;
113
+ }
114
+
115
+ const body = gzip ? asset.gzipped : asset.body;
116
+ res.writeHead(200, {
117
+ ...headers,
118
+ 'content-type': type ?? 'application/octet-stream',
119
+ 'content-length': body.length,
120
+ ...(gzip ? { 'content-encoding': 'gzip' } : {}),
121
+ });
122
+ res.end(body);
123
+ return true;
124
+ }
@@ -30,6 +30,7 @@ import {
30
30
  revokeRoomAccessTx, roomEntryRefusal,
31
31
  } from './room-access-db.ts';
32
32
  import type { RoomEvent, RoomSnapshot, Seat, SeatKind, WakeTier } from './protocol.ts';
33
+ import { sendWebAsset } from './web-assets.ts';
33
34
 
34
35
  export interface WorldServerOptions {
35
36
  dbFile?: string;
@@ -57,30 +58,6 @@ interface SseClient {
57
58
  res: ServerResponse;
58
59
  }
59
60
 
60
- const WEB_TYPES: Readonly<Record<string, string>> = {
61
- '.html': 'text/html; charset=utf-8',
62
- '.js': 'text/javascript; charset=utf-8',
63
- '.css': 'text/css; charset=utf-8',
64
- '.svg': 'image/svg+xml',
65
- '.png': 'image/png',
66
- '.jpg': 'image/jpeg',
67
- '.jpeg': 'image/jpeg',
68
- '.webp': 'image/webp',
69
- '.ico': 'image/x-icon',
70
- };
71
-
72
- /** 网页客户端只从本站取脚本、样式与接口;没有内联脚本。 */
73
- const PLAY_CSP = [
74
- "default-src 'none'",
75
- "script-src 'self'",
76
- "style-src 'self'",
77
- "connect-src 'self'",
78
- "img-src 'self'",
79
- "base-uri 'none'",
80
- "form-action 'none'",
81
- "frame-ancestors 'none'",
82
- ].join('; ');
83
-
84
61
  const PACKAGE_VERSION = ((): string => {
85
62
  try {
86
63
  const raw = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as { version?: unknown };
@@ -511,7 +488,7 @@ export class WorldServer {
511
488
  const url = new URL(req.url ?? '/', 'http://localhost');
512
489
  const method = req.method ?? 'GET';
513
490
 
514
- if (method === 'GET' && this.serveWeb(url.pathname, res)) return;
491
+ if (method === 'GET' && this.serveWeb(url.pathname, req, res)) return;
515
492
 
516
493
  if (method === 'GET' && url.pathname === '/healthz') {
517
494
  const room = getRoom(this.db, this.defaultRoomId);
@@ -1884,13 +1861,13 @@ export class WorldServer {
1884
1861
  }
1885
1862
 
1886
1863
  /** 网页客户端的静态文件:/play 与 /play/assets/**。 */
1887
- private serveWeb(pathname: string, res: ServerResponse): boolean {
1864
+ private serveWeb(pathname: string, req: IncomingMessage, res: ServerResponse): boolean {
1888
1865
  if (pathname === '/play' || pathname === '/play/') {
1889
- this.sendWeb('play.html', res, true);
1866
+ this.sendWeb('play.html', req, res, true);
1890
1867
  return true;
1891
1868
  }
1892
1869
  if (pathname === '/parent' || pathname === '/parent/') {
1893
- this.sendWeb('parent.html', res, true);
1870
+ this.sendWeb('parent.html', req, res, true);
1894
1871
  return true;
1895
1872
  }
1896
1873
  const prefix = pathname.startsWith('/parent/assets/') ? '/parent/assets/' : '/play/assets/';
@@ -1900,28 +1877,12 @@ export class WorldServer {
1900
1877
  || !/^[A-Za-z0-9._/-]+$/.test(rel)) {
1901
1878
  throw new HttpError(404, '没有这个文件');
1902
1879
  }
1903
- this.sendWeb(rel, res, false);
1880
+ this.sendWeb(rel, req, res, false);
1904
1881
  return true;
1905
1882
  }
1906
1883
 
1907
- private sendWeb(rel: string, res: ServerResponse, page: boolean): void {
1908
- let body: Buffer;
1909
- try {
1910
- body = readFileSync(new URL(`../web/${rel}`, import.meta.url));
1911
- } catch {
1912
- throw new HttpError(404, '没有这个文件');
1913
- }
1914
- const dot = rel.lastIndexOf('.');
1915
- const type = dot >= 0 ? WEB_TYPES[rel.slice(dot).toLowerCase()] : undefined;
1916
- res.writeHead(200, {
1917
- 'content-type': type ?? 'application/octet-stream',
1918
- 'content-length': body.length,
1919
- 'cache-control': 'no-cache',
1920
- 'x-content-type-options': 'nosniff',
1921
- 'referrer-policy': 'no-referrer',
1922
- ...(page ? { 'content-security-policy': PLAY_CSP } : {}),
1923
- });
1924
- res.end(body);
1884
+ private sendWeb(rel: string, req: IncomingMessage, res: ServerResponse, page: boolean): void {
1885
+ if (!sendWebAsset(rel, req, res, page)) throw new HttpError(404, '没有这个文件');
1925
1886
  }
1926
1887
 
1927
1888
  private pump(): void {
package/src/web/play.css CHANGED
@@ -1431,7 +1431,7 @@ input:focus, select:focus { outline: none; border-color: var(--accent-border); b
1431
1431
  .parent-play .sub { margin: 0; }
1432
1432
  .join .error { min-height: 22px; margin: 4px 0 8px; font-size: 11.5px; }
1433
1433
  .join .note { color: var(--dim); font-size: 10.5px; margin-top: 14px; }
1434
- .booting { color: var(--muted); padding: 48px 8px; text-align: center; }
1434
+ .booting { color: var(--muted); padding: 48px 8px; text-align: center; line-height: 1.7; max-width: 34em; margin: 0 auto; }
1435
1435
  .noscript { padding: 24px; }
1436
1436
 
1437
1437
  /* —— 斗地主:一张木头小牌桌(左右是对手的牌堆,中间底牌与刚出的那手) —— */
package/src/web/play.html CHANGED
@@ -7,6 +7,7 @@
7
7
  <meta name="color-scheme" content="light">
8
8
  <title>客厅 · 一起玩</title>
9
9
  <link rel="stylesheet" href="/play/assets/play.css">
10
+ <link rel="modulepreload" href="/play/assets/play.js">
10
11
  </head>
11
12
  <body class="theme-cozy">
12
13
  <svg class="sprite" aria-hidden="true" width="0" height="0" focusable="false">
@@ -93,7 +94,7 @@
93
94
  <a class="skip-link" href="#main">跳到主要内容</a>
94
95
  <div class="room-light" aria-hidden="true"></div>
95
96
 
96
- <div id="app" class="app"><div class="booting">正在打开客厅…</div></div>
97
+ <div id="app" class="app"><div class="booting" id="boot-note">正在打开客厅…</div></div>
97
98
  <div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
98
99
  <noscript><p class="noscript">这个页面要开 JavaScript 才能玩。</p></noscript>
99
100
  <script type="module" src="/play/assets/play.js"></script>
package/src/web/play.js CHANGED
@@ -58,6 +58,8 @@ const state = {
58
58
  hallLoading: false,
59
59
  /** 服务端是否开放「用户名 + 邀请码」入口;默认按开处理,boot 时问 /healthz。 */
60
60
  guestJoin: true,
61
+ /** 从 #key= 取到的钥匙;换席位失败时留着给「重试」用,成功就清掉。 */
62
+ entryKey: '',
61
63
  dm: { open: false, peer: null, threads: [], people: [], messages: [], unread: 0, q: '', timer: 0, drag: null },
62
64
  timerKey: '',
63
65
  timerTotal: 0,
@@ -66,9 +68,50 @@ const ui = {};
66
68
  let toastTimer = 0;
67
69
  let mailTimer = 0;
68
70
 
71
+ /** 首屏的进度:页面还是那张占位卡时换一句话;界面画出来以后这层就没了。 */
72
+ const bootClock = { started: Date.now(), base: '正在打开客厅…', timer: 0 };
73
+
74
+ function note(text) {
75
+ if (text) bootClock.base = text;
76
+ paintNote();
77
+ }
78
+
79
+ function paintNote() {
80
+ const box = document.getElementById('boot-note');
81
+ if (!box) {
82
+ if (bootClock.timer) clearInterval(bootClock.timer);
83
+ bootClock.timer = 0;
84
+ return;
85
+ }
86
+ const secs = Math.floor((Date.now() - bootClock.started) / 1000);
87
+ const slow = secs >= 6 ? ' 网络看起来有点慢,还在等服务器回话。' : '';
88
+ box.textContent = `${bootClock.base}(已等 ${secs} 秒)${slow}`;
89
+ }
90
+
91
+ function startBootClock() {
92
+ bootClock.started = Date.now();
93
+ if (!bootClock.timer) bootClock.timer = setInterval(paintNote, 1000);
94
+ paintNote();
95
+ }
96
+
97
+ function bootFailureText(error) {
98
+ if (error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
99
+ return '服务器 25 秒没有回话。网络可能断了,或者客厅那边没起来;点重试再试一次。';
100
+ }
101
+ return error && error.message ? error.message : String(error);
102
+ }
103
+
69
104
  probeCardArt();
70
105
  boot();
71
106
 
107
+ // 在已经打开的页面地址栏里粘一条新的「我下场玩」链接:hash 变了但页面不会重载,
108
+ // 这里主动换一次钥匙,换好再整页重来,免得旧席位的日志和牌桌还挂着。
109
+ window.addEventListener('hashchange', async () => {
110
+ const key = takeKeyFromHash();
111
+ if (!key) return;
112
+ if (await tryParentEntry(key, { hadSeat: true })) location.reload();
113
+ });
114
+
72
115
  /* —— 起步 —— */
73
116
 
74
117
  /** 访客入口开没开:/healthz 的 guestJoin;老服务器没这个字段就按开处理。 */
@@ -82,10 +125,24 @@ async function loadEntryPolicy() {
82
125
  }
83
126
 
84
127
  async function boot() {
128
+ startBootClock();
85
129
  // 带钥匙的「我下场玩」链接:钥匙只用来换会话,换完立刻从地址栏抹掉。
86
- const key = takeKeyFromHash();
87
- if (!state.cfg && (key || await hasParentSession())) {
88
- await tryParentEntry(key);
130
+ // 钥匙是明确点开的意图,比这台设备存着的旧席位优先——旧席位可能是另一个家长身份,
131
+ // 也可能早就失效了;先换钥匙,再谈旧席位。
132
+ const key = takeKeyFromHash() || state.entryKey;
133
+ if (key) {
134
+ state.entryKey = key;
135
+ note('正在用链接里的钥匙换席位…');
136
+ if (await tryParentEntry(key, { hadSeat: !!state.cfg })) {
137
+ state.entryKey = '';
138
+ } else if (!state.cfg) {
139
+ // 没有旧席位可退:留在离线页,重试会再用这把钥匙试一次。
140
+ renderOffline('这个链接里的钥匙没换成席位。可能链接过期了,也可能网络没通——回扩展面板重新点一次「我下场玩」,或者点下面的重试。');
141
+ return;
142
+ }
143
+ // 换不到但旧席位还在:继续用旧席位,上面已经提示了原因。
144
+ } else if (!state.cfg && await hasParentSession()) {
145
+ await tryParentEntry('');
89
146
  }
90
147
  if (!state.cfg) {
91
148
  await loadEntryPolicy();
@@ -93,6 +150,7 @@ async function boot() {
93
150
  return;
94
151
  }
95
152
  try {
153
+ note('正在读取客厅状态…');
96
154
  await refreshSnapshot();
97
155
  state.latest = state.snap.latest;
98
156
  state.view = inHall() ? 'hall' : hasLiveTable() ? 'table' : 'lobby';
@@ -110,7 +168,7 @@ async function boot() {
110
168
  await handleExpiredSeat(state.cfg ? state.cfg.token : '');
111
169
  return;
112
170
  }
113
- renderOffline(error && error.message ? error.message : String(error));
171
+ renderOffline(bootFailureText(error));
114
172
  }
115
173
  }
116
174
 
@@ -133,10 +191,11 @@ async function hasParentSession() {
133
191
 
134
192
  /**
135
193
  * 家长入场:钥匙或这台浏览器已有的家长会话,都直接以家长身份下场。
136
- * 只在「没有席位」时走这里;席位真的失效(401)时不自动重入——一个家长身份只有
137
- * 一个席位,两台设备都自动重入会来回顶。
194
+ * 带钥匙时不管这台设备有没有旧席位都先换钥匙——钥匙是点链接的人刚做的选择。
195
+ * 换好以后旧席位的界面状态要清掉,免得还挂着上一个身份的日志与牌桌。
138
196
  */
139
- async function tryParentEntry(key = '') {
197
+ async function tryParentEntry(key = '', options = {}) {
198
+ const before = state.cfg && state.cfg.name;
140
199
  try {
141
200
  if (key) {
142
201
  const session = await fetch('/v1/parent/session', {
@@ -157,6 +216,13 @@ async function tryParentEntry(key = '') {
157
216
  });
158
217
  const body = await played.json().catch(() => ({}));
159
218
  if (!played.ok) throw new Error(body.error || '现在下不了场');
219
+ if (options.hadSeat) {
220
+ state.latest = 0;
221
+ state.seen = new Set();
222
+ state.log = [];
223
+ state.snap = null;
224
+ state.watchTableId = '';
225
+ }
160
226
  writeStore({
161
227
  room: body.room,
162
228
  seatId: body.seat.id,
@@ -165,6 +231,9 @@ async function tryParentEntry(key = '') {
165
231
  cooId: body.identity.cooId,
166
232
  cooSecret: body.identity.cooSecret,
167
233
  });
234
+ if (options.hadSeat && before && before !== body.seat.name) {
235
+ showToast(`这台设备原来在「${before}」的席位上,已经换成「${body.seat.name}」。`);
236
+ }
168
237
  return true;
169
238
  } catch (error) {
170
239
  showToast(error.message || '现在下不了场', 'bad');
@@ -334,6 +403,13 @@ function tableChatOpen() {
334
403
 
335
404
  /* —— 网络 —— */
336
405
 
406
+ /** 普通接口 25 秒没回话就当超时;首屏卡住时能自己走到「重试」,而不是一直转。 */
407
+ function timeoutSignal(existing) {
408
+ if (existing) return { signal: existing };
409
+ if (typeof AbortSignal === 'undefined' || !AbortSignal.timeout) return {};
410
+ return { signal: AbortSignal.timeout(25_000) };
411
+ }
412
+
337
413
  async function api(path, init = {}) {
338
414
  const headers = new Headers(init.headers || {});
339
415
  if (state.cfg) {
@@ -341,7 +417,7 @@ async function api(path, init = {}) {
341
417
  headers.set('x-parlor-coo', state.cfg.cooId);
342
418
  headers.set('x-parlor-coo-secret', state.cfg.cooSecret);
343
419
  }
344
- const response = await fetch(roomPath(path), { ...init, headers });
420
+ const response = await fetch(roomPath(path), { ...init, headers, ...timeoutSignal(init.signal) });
345
421
  let body = null;
346
422
  try {
347
423
  body = await response.json();
@@ -2926,7 +3002,11 @@ function renderOffline(message) {
2926
3002
  panel.append(el('h1', '', '连不上客厅'));
2927
3003
  panel.append(el('p', 'sub', message || '网络没有通。'));
2928
3004
  const actions = el('div', 'actions');
2929
- actions.append(btn('重试', () => boot(), { primary: true }));
3005
+ actions.append(btn('重试', () => {
3006
+ startBootClock();
3007
+ note('正在重新连接…');
3008
+ void boot();
3009
+ }, { primary: true }));
2930
3010
  actions.append(btn('换一个席位', () => {
2931
3011
  clearStore();
2932
3012
  location.reload();
package/src/world.ts CHANGED
@@ -9,7 +9,7 @@ import { fileURLToPath } from 'node:url';
9
9
  import type { StoragePart, ToolDef, ToolOutcome, World, WorldHost, WorldWebUiDecl } from 'cortico/core/types.ts';
10
10
  import { nowIso } from 'cortico/core/util.ts';
11
11
  import type { WorldContext } from 'cortico/world.ts';
12
- import { PARLOR_CONFIG_GROUP, type ParlorConfigSection } from './config.ts';
12
+ import { PARLOR_CONFIG_GROUP, DEFAULT_INVITE_CODE, DEFAULT_SERVER_URL, type ParlorConfigSection } from './config.ts';
13
13
  import { ParlorClient, ParlorHttpError } from './room/client.ts';
14
14
  import { serverClock, serverClockShort } from './room/clock.ts';
15
15
  import { gameLabelOf } from './room/game-labels.ts';
@@ -555,7 +555,7 @@ export class ParlorWorld implements World {
555
555
  source: this.id,
556
556
  origin: 'internal',
557
557
  senderKey: this.id,
558
- text: `客厅「${this.currentRoom || 'lobby'}」已连接。席位:${this.seat?.name ?? '未知'}${this.focused ? '(正在牌桌上:客厅闲聊只攒摘要)' : ''}。${this.mailUnread > 0 ? `信箱里有 ${this.mailUnread} 封未读,用 parlor_mail 看。` : ''}`,
558
+ text: `客厅已连接。席位:${this.seat?.name ?? '未知'}${this.focused ? '(正在牌桌上:客厅闲聊只攒摘要)' : ''}。${this.mailUnread > 0 ? `信箱里有 ${this.mailUnread} 封未读,用 parlor_mail 看。` : ''}`,
559
559
  meta: { room: this.currentRoom, seat: this.seat?.id, address: this.baseUrl },
560
560
  }, { trigger: 'flush' });
561
561
  }
@@ -576,11 +576,19 @@ export class ParlorWorld implements World {
576
576
  const defaultRoom = cfg.room || 'lobby';
577
577
  this.currentRoom = this.ctx.secret(CURRENT_ROOM_SECRET).trim() || defaultRoom;
578
578
  let baseUrl = cfg.serverUrl.trim().replace(/\/+$/, '');
579
- // 扩展设置里的邀请码优先;没填就退回旧部署的 .env,保持兼容。
580
- let invite = cfg.inviteCode.trim() || this.ctx.secret(INVITE_SECRET).trim();
579
+ // 自己填的码永远优先。留空、或还是包里那份公开默认值时,先看 .env(老部署把码写在那儿),
580
+ // 再看公开默认值——装完不用动设置就能连上房主的客厅。
581
+ const configured = cfg.inviteCode.trim();
582
+ const fromEnv = this.ctx.secret(INVITE_SECRET).trim();
583
+ let invite = configured;
584
+ if (!configured || configured === DEFAULT_INVITE_CODE) {
585
+ invite = fromEnv || (baseUrl === DEFAULT_SERVER_URL ? DEFAULT_INVITE_CODE : configured);
586
+ }
581
587
 
582
588
  if (!baseUrl) {
583
589
  const dataFile = this.roomFile();
590
+ // 自己开客厅时不用包里那份公开码:人人都有,等于没锁。读 .env,没有就新生成一个。
591
+ if (invite === DEFAULT_INVITE_CODE) invite = this.ctx.secret(INVITE_SECRET).trim();
584
592
  invite = invite || randomBytes(9).toString('base64url');
585
593
  if (!this.ctx.secret(INVITE_SECRET)) {
586
594
  try { this.ctx.storeSecret(INVITE_SECRET, invite); } catch { /* 假上下文或不可写 */ }
@@ -622,7 +630,7 @@ export class ParlorWorld implements World {
622
630
  }
623
631
 
624
632
  if (!invite) {
625
- throw new Error('客厅:扩展设置里要填「邀请码」(或部署 .env 的 PARLOR_INVITE_CODE;邀请码向房主/运营者要)');
633
+ throw new Error('客厅:扩展设置里的「邀请码」是空的,部署 .env 里也没有 PARLOR_INVITE_CODE。连房主的客厅要填对方的邀请码;自己开客厅就留空让 World 生成。');
626
634
  }
627
635
  const joined = await client.join(invite, {
628
636
  name: cfg.seatName.trim() || this.ctx.botName,