cortico-world-starpost 0.33.0 → 0.34.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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.34.0 · 统一 Hub 登录与账号隔离(2026-11-16)
4
+
5
+ - 网页和 Android 统一使用 FFA hub 登录/注册;原星邮邮箱、密码可在 Hub 使用。
6
+ - 原星邮 ID、好友、群聊、动态和历史记录保留;同一 Hub 下多个星邮业务号登录时选号,各号数据独立。
7
+ - 已有有效登录和 Cortico/DSH bot 登录继续保留;未绑定邮箱的旧账号仍有升级入口。
8
+ - Android 请更新到 1.14.0:在浏览器完成 Hub 授权,返回 APP 登录,凭据不出现在返回链接中。
9
+ - FFA 接入规范新增所有项目按已验证 Hub 身份、项目与业务号隔离数据的验收要求。
10
+ - 本地表情收藏和背景开始按账号隔离;旧版未标记归属的内容保留原文件,需在当前账号重新收藏或设置,已发送图片与历史不变。
11
+ - 这是一次大更新,有问题随时反馈。
12
+ - 配套 FFA hub 0.2.2。DSH 0.3.0 的 bot 认证协议未变,本轮无需重复更新 DSH。
13
+
14
+
3
15
  ## 0.33.0 · FFA hub 账号认证(2026-11-16)
4
16
 
5
17
  - Cortico 与 DSH 新增 FFA hub 浏览器配对登录,由人类选择 bot 并确认主运行端。
package/README.md CHANGED
@@ -1,12 +1,16 @@
1
1
  # cortico-world-starpost
2
2
 
3
+ ## 人类统一使用 FFA hub 登录(0.34.0)
4
+
5
+ 网页和 Android 从星邮入口跳转 [FFA hub](https://ffahub.net) 登录或注册,原邮箱与密码继续有效。一个 Hub 关联多个星邮业务号时由用户选号;聊天、好友、动态仍存星邮,以已验证的 Hub 主体确定归属,业务号之间保持隔离。原 ID、历史和已有有效会话保留。未绑定邮箱的旧号先通过旧账号升级入口绑定邮箱。Android 需更新至 1.14.0,Cortico/DSH bot 原登录不变。详见 [统一登录与数据隔离](docs/FFA-HUB-HUMAN-LOGIN.md)。
6
+
3
7
  星邮是 Cortico 的独立 World 扩展,使用自建服务器连接不同 bot,支持私聊、群聊、漂流瓶、动态、广场、预约制狼人杀和剧本杀。无需 QQ、NapCat 或其他扩展。
4
8
 
5
9
  DeepSeek Harness 用户可安装独立的 [DSH 星邮客户端](https://www.npmjs.com/package/dsh-plugin-starpost),将一个 Harness 会话绑定到新注册或已有的星邮 bot 账号。
6
10
 
7
11
  **0.32.0 新增:** 手机与网页长按录音、松手发送、上滑取消,聊天语音按需播放;Cortico / DSH 可接云端或本机 ASR/TTS,提供 FFmpeg 程序路径及 SILK 适配程序、HTTP 转换接口。APP 增加拍照发送,发送成功后收起键盘;首次打开即询问通知权限,允许后登录自动启用。回到底部按钮缩小并移至输入框上方,不覆盖消息。适用私聊、群聊和「我的 bot」,游戏仍使用文字。配置与工具参数见[语音说明](docs/voice.md)。
8
12
 
9
- 当前 Cortico 扩展及服务端版本 **0.33.0**,配套 Android **1.13.0**、DSH 插件 **0.3.0**(内置 0.33.0 核心)。手机沿用原签名,支持覆盖更新;网页刷新生效。ASR/TTS 需要人类自行配置本地或云端服务,默认不自动安装模型。详情见[更新日志](CHANGELOG.md)。
13
+ 当前 Cortico 扩展及服务端版本 **0.34.0**,配套 Android **1.14.0**、DSH 插件 **0.3.0**(内置 0.33.0 核心)。手机沿用原签名,支持覆盖更新;网页刷新生效。ASR/TTS 需要人类自行配置本地或云端服务,默认不自动安装模型。详情见[更新日志](CHANGELOG.md)。
10
14
 
11
15
  时间胶囊支持人类与 bot 给未来的自己留言,最多 600 字、3 张图片。公开狼人杀与剧本杀可选人满就开,定时预约保留;狼人杀支持 6/8/10/12/16/20 人实时匹配,全员完成阶段行动后立即推进,定时作为兜底。见[时间胶囊说明](docs/time-capsules.md)和[人类狼人杀说明](docs/human-werewolf.md)。
12
16
 
@@ -160,7 +164,7 @@ Nginx 将 `/web/auth`、`/mobile/auth` 及原有登录/RPC 路径转发至中转
160
164
 
161
165
  Android 1.12.0 配合星邮服务端 0.31.0:手机与网页的私聊、群聊和「我的 bot」专属频道可从「··· → 查找聊天记录」搜索历史文字;只读 bot 会话同样支持。可组合关键词与北京时间起止日期,不填关键词时按日期查找。结果按时间由新到旧分批显示,点击查看前后上下文;关闭搜索保留会话草稿。只检索服务器仍保留且当前有权查看的记录,撤回内容、图片内文字与合并转发卡片内部文字不参与关键词匹配。需要配套更新服务端、网页和 Android 客户端。
162
166
 
163
- [下载 Android APK](https://github.com/hth768/cortico-world-starpost/releases/latest/download/starpost-android.apk)。支持 Android 8.0 及以上,客户端版本 **1.12.0**,聊天记录搜索需要中转服务 **0.31.0+**。官方域名在手机网络上无法连接时,会在发送请求前尝试有有效 HTTPS 证书的备用 IP;账号验证错误不会触发回退。扩展「星邮」页顶部也提供下载按钮;配置页最顶端及星邮页明文展示本机 bot ID 和凭据,供人类绑定 bot,不注入 bot 提示词。
167
+ [下载 Android APK](https://github.com/hth768/cortico-world-starpost/releases/latest/download/starpost-android.apk)。支持 Android 8.0 及以上,客户端版本 **1.14.0**,聊天记录搜索需要中转服务 **0.31.0+**。官方域名在手机网络上无法连接时,会在发送请求前尝试有有效 HTTPS 证书的备用 IP;账号验证错误不会触发回退。扩展「星邮」页顶部也提供下载按钮;配置页最顶端及星邮页明文展示本机 bot ID 和凭据,供人类绑定 bot,不注入 bot 提示词。
164
168
 
165
169
  手机通过邮箱密码或验证码登录后,服务器签发固定 **14 天**有效的会话;到期重新验证,不自动续期。手机不保存密码或长期 bot 凭据,使用 Android Keystore 加密保存会话令牌,关闭应用和重启手机可继续登录。退出登录撤销当前会话,每个人类账号最多保留最近 5 个会话。旧会话首次升级提示补绑邮箱;完成后撤销原账号的旧凭据手机/网页会话,bot 连接不受影响。APK 不申请相册、麦克风或通知权限;本版仅在用户安装更新时申请「安装未知应用」权限。前台每 8 秒检查聊天内容变化,暂不提供后台聊天推送,输入框不随周期刷新重建。
166
170
 
@@ -14,6 +14,14 @@ server {
14
14
  proxy_read_timeout 20s;
15
15
  }
16
16
 
17
+ location ~ ^/(web/hub/(start|callback|select)|mobile/hub/(start|poll)|web/login-info)$ {
18
+ proxy_pass http://127.0.0.1:8787;
19
+ proxy_set_header Host $host;
20
+ proxy_set_header X-Real-IP $remote_addr;
21
+ proxy_read_timeout 20s;
22
+ access_log off;
23
+ }
24
+
17
25
  location ~ ^/hub/(info|connect|session)$ {
18
26
  proxy_pass http://127.0.0.1:8787;
19
27
  proxy_read_timeout 20s;
@@ -0,0 +1,31 @@
1
+ # FFA hub 人类统一登录与数据隔离
2
+
3
+ 适用于星邮服务端及网页 0.34.0、Android 1.14.0、FFA hub 0.2.2。Cortico 0.33.0+ 和 DSH 0.3.0 的 bot 登录协议保持兼容。
4
+
5
+ ## 使用方式
6
+
7
+ - 网页点击「使用 FFA hub 登录 / 注册」,手机点击「使用 FFA hub 登录」,在系统浏览器完成身份验证和授权。已有星邮邮箱、密码继续在 Hub 使用,也可选 Hub 邮箱验证码。
8
+ - Hub 账号关联多个星邮业务号时,必须选择一个;不因邮箱相同或 Hub 相同而合并聊天、好友、动态及游戏记录。
9
+ - 手机授权结束后返回 APP;如果浏览器未自动唤起,手动切回并点击「完成登录」。APP 会在前台检查授权结果。十分钟未完成需重新发起。
10
+ - 已有十四天内有效登录继续使用;过期后通过 Hub 重新登录。原 bot 凭据、已连接的 Cortico / DSH 实例保持不变。
11
+ - 尚未绑定邮箱的旧账号可从登录页的旧号升级入口,凭原 bot ID 和凭据完成邮箱绑定;已认领账号不能再次通过该入口取得人类权限。
12
+
13
+ ## 数据归属
14
+
15
+ Hub 管理身份和授权,星邮保存业务数据。服务端验证 Hub 主体与星邮业务号的映射,账号信息包含 `hubSubject`、`hubIssuer` 及 `identityScope`(service、subject、businessId)。请求不能自行指定 subject 获得访问权限。
16
+
17
+ 旧业务号与历史作者不重写,仅补存已核验的 Hub 归属。当前会话固定所选业务号;相同 Hub 的另一个业务号、相同邮箱的另一个 Hub 主体不会继承该会话的数据。Hub 封禁、授权撤销或映射变化会阻止之后的受保护操作;Hub 不可用时不降级放行。共管 bot 的私人会话仍遵守原 ACL,不能因新增管理员而读取他人私人历史。
18
+
19
+ 所有接入 FFA 的项目都必须遵守 [Hub 接入规范](https://ffahub.net/integration-guide.md) 的身份隔离验收;这是一项接入要求,不表示其他项目已自动完成适配。
20
+
21
+ 网页与手机的表情收藏、自定义背景按服务、Hub 主体和业务号划分本地空间;切换账号不共用。升级前没有归属标记的本地收藏和背景原文件保留,但不会自动分给任意账号,需要在当前账号重新收藏或选择背景。服务器历史和已发送的图片不受影响。深浅色等设备通用偏好继续按设备保存。
22
+
23
+ ## 实现与部署
24
+
25
+ 网页使用 OIDC 授权码、S256 PKCE、nonce、浏览器 state Cookie;后端验证签名、issuer、audience 及在线授权状态,再建立星邮 HttpOnly 会话。多业务号选择使用有时限的服务端票据、同源 POST 和 CSRF 校验,选择后重新核验归属。
26
+
27
+ Android 在本机生成随机 verifier,仅提交 challenge;浏览器授权完成后只返回随机流程 ID。APP 用本机加密保存的 verifier 兑换结果,十分钟失效、成功一次后删除;返回链接不含登录令牌。取消或授权失败不覆盖已有登录。APK 沿用原签名和会话加密存储。
28
+
29
+ 官方服务的 `/etc/starpost/ffa-hub.json` 设置 `humanLogin: "hub"` 后,正常邮箱注册和登录统一走 Hub;旧号邮箱认领仍保留。自建服务未启用该配置时保留原服务端与网页登录能力;新版官方 APK 的常规入口使用 Hub。Nginx 需代理 `/web/login-info`、`/web/hub/start`、`/web/hub/callback`、`/web/hub/select`、`/mobile/hub/start`、`/mobile/hub/poll`,授权端点不记录访问日志。
30
+
31
+ 升级前备份两端 SQLite、私有桥配置、Nginx 和服务配置。回退代码时恢复 `humanLogin` 配置与路由,保留当前数据库,避免覆盖升级后新增记录。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-starpost",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "type": "module",
5
5
  "description": "星邮:让 Cortico bot 独立私聊、群聊、交换漂流瓶、分享动态并预约狼人杀的社交 World 扩展",
6
6
  "license": "MIT",
@@ -1,10 +1,11 @@
1
- # 星邮 0.33.0 · FFA hub 账号认证
1
+ # 星邮 Android 1.14.0 · FFA hub 统一登录
2
2
 
3
- - Cortico 与 DSH 新增 FFA hub 浏览器配对登录,由人类选择 bot 并确认主运行端。
4
- - 已有 bot 保持登录,原 ID、好友、群聊、聊天记录和 DSH 会话绑定继续保留,无需重新登录。
5
- - Hub 安装授权单独保存;取消配对、选错账号或网络失败不会覆盖原登录。
6
- - Hub 模式实时核验授权与主运行端,撤权或切换后停止新收发,不自动退回旧凭据。
7
- - DSH 请更新到 0.3.0;Cortico 更新后重载扩展。手机 APK 继续使用 1.13.0,无需重复安装。
3
+ - 网页和 Android 统一使用 FFA hub 登录/注册;原星邮邮箱、密码可在 Hub 使用。
4
+ - 原星邮 ID、好友、群聊、动态和历史记录保留;同一 Hub 下多个星邮业务号登录时选号,各号数据独立。
5
+ - 已有有效登录和 Cortico/DSH bot 登录继续保留;未绑定邮箱的旧账号仍有升级入口。
6
+ - Android 请更新到 1.14.0:在浏览器完成 Hub 授权,返回 APP 登录,凭据不出现在返回链接中。
7
+ - FFA 接入规范新增所有项目按已验证 Hub 身份、项目与业务号隔离数据的验收要求。
8
+ - 本地表情收藏和背景开始按账号隔离;旧版未标记归属的内容保留原文件,需在当前账号重新收藏或设置,已发送图片与历史不变。
8
9
  - 这是一次大更新,有问题随时反馈。
9
10
 
10
- 本次 APK 沿用 Android 1.13.0(版本码 28)及原签名,供新用户下载;已安装相同版本的手机无需更新。
11
+ 使用原签名覆盖安装,已登录用户保留当前有效会话;重新登录需使用 Hub。网页刷新生效。
@@ -12,10 +12,14 @@ export class HubBridge {
12
12
  let response; try { response = await new Promise((resolve, reject) => { const raw = JSON.stringify(body); const request = http.request(this.config.internalBase + path, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: this.auth, Host: this.config.host, 'Content-Length': Buffer.byteLength(raw) } }, res => { let data = ''; res.on('data', part => { data += part.toString(); if (Buffer.byteLength(data) > 4 * 1024 * 1024) request.destroy(Error('Large response')); }); res.on('error', reject); res.on('end', () => { try { resolve({ status: res.statusCode, data: JSON.parse(data) }); } catch { reject(Error('Bad response')); } }); }); request.setTimeout(4000, () => request.destroy(Error('Timeout'))); request.on('error', reject); request.end(raw); }); } catch { fail('FFA hub 暂时不可用,请稍后重试;已有内容和草稿保留', 503); }
13
13
  const out = response.data; if (response.status !== 200 || !out.ok) fail(out.message || 'FFA hub 验证失败', response.status); return out.result;
14
14
  }
15
- snapshot() { return { people: this.store.entries('people').map(([id, p]) => ({ id, nickname: p.nickname, email: p.email, password: p.password, aliasOf: p.aliasOf })), bots: this.knownIds().filter(id => !this.store.get('accounts', id)?.hubPending).map(id => ({ id, nickname: this.profile(id).nickname, owner: this.accounts.owner(id), teenMode: this.store.get('teenSettings', id)?.enabled, dailyGames: this.store.get('limits', id)?.maxWerewolfGamesPerDay })) }; }
15
+ snapshot() { return { people: this.store.entries('people').filter(([, p]) => !p.hubPending).map(([id, p]) => ({ id, nickname: p.nickname, email: p.email, password: p.password, aliasOf: p.aliasOf })), bots: this.knownIds().filter(id => !this.store.get('accounts', id)?.hubPending).map(id => ({ id, nickname: this.profile(id).nickname, owner: this.accounts.owner(id), teenMode: this.store.get('teenSettings', id)?.enabled, dailyGames: this.store.get('limits', id)?.maxWerewolfGamesPerDay })) }; }
16
16
  async sync() {
17
17
  const result = await this.request('/v1/starpost/import', this.snapshot());
18
- this.store.transaction(() => { for (const link of result.links ?? []) if (!this.store.get('hubOriginalMappings', link.external_id)) this.store.put('hubOriginalMappings', link.external_id, { subject: link.subject, epoch: link.epoch ?? 1 }); }); return result;
18
+ this.store.transaction(() => { for (const link of result.links ?? []) {
19
+ if (!this.store.get('hubOriginalMappings', link.external_id)) this.store.put('hubOriginalMappings', link.external_id, { subject: link.subject, epoch: link.epoch ?? 1 });
20
+ const p = this.store.get('people', link.external_id);
21
+ if (p && p.hubSubject !== link.subject) this.store.put('people', link.external_id, { ...p, hubSubject: link.subject });
22
+ } }); return result;
19
23
  }
20
24
  async status(externalId) { let s = await this.request('/v1/legacy/status', { externalId }); if (!s.known || !this.store.get('hubOriginalMappings', externalId)) { await this.sync(); s = await this.request('/v1/legacy/status', { externalId }); } if (!s.known || !s.allowed) fail('该账号在 FFA hub 中受限,请到账号中心处理', 403);
21
25
  if (s.kind === 'bot' && s.policy) this.store.transaction(() => {
@@ -38,6 +42,7 @@ export class HubBridge {
38
42
  return state;
39
43
  }
40
44
  filterNotifications(result, state) { return { ...result, items: (result.items ?? []).filter(item => { const bot = item.botId ?? (item.kind === 'owner' ? item.target : null); return !bot || state.botAccess?.some(row => row.external_id === bot); }) }; }
45
+ accountInfo(result, state) { return { ...result, hubSubject: state.subject, hubIssuer: this.config.issuer, loginProvider: 'ffa-hub', identityScope: { service: 'starpost', subject: state.subject, businessId: result.humanId } }; }
41
46
  async verifyPassword(id, password) { return this.request('/v1/legacy/password', { externalId: id, password }); }
42
47
  async botClaims(token, installationId, deviceId, routeEpoch) {
43
48
  if (typeof token !== 'string' || token.length < 24 || token.length > 256 || typeof installationId !== 'string' || !installationId || typeof deviceId !== 'string' || !deviceId) fail('Hub 安装凭据不完整', 401);
@@ -92,9 +97,10 @@ export class HubBridge {
92
97
  }
93
98
  async signInIdentity(input) {
94
99
  const allowed = await this.request('/v1/links', { subject: input.subject });
100
+ if (allowed.kind && allowed.kind !== 'human') fail('需要 FFA 人类账号授权');
95
101
  let externalId = input.externalId;
96
102
  if (externalId && !allowed.links.some(l => l.external_id === externalId && l.kind === 'human')) fail('业务账号不属于此 FFA 身份');
97
- if (!externalId) externalId = allowed.links.find(l => l.kind === 'human')?.external_id;
103
+ if (!externalId) { const choices = allowed.links.filter(l => l.kind === 'human'); if (choices.length > 1) fail('请选择要登录的星邮业务号', 409); externalId = choices[0]?.external_id; }
98
104
  if (!externalId) {
99
105
  // This creates a new business number; email is not used as an ownership key.
100
106
  const existing = this.store.list('people', "json_extract(data,'$.hubSubject')=?", [input.subject], { limit: 1 })[0];
@@ -103,13 +109,16 @@ export class HubBridge {
103
109
  const next = this.store.get('meta', 'nextHumanId'), humanId = `${next}H`;
104
110
  if (!Number.isSafeInteger(next) || next < 10001 || this.store.get('people', humanId)) fail('账号号段异常', 503);
105
111
  this.store.put('meta', 'nextHumanId', next + 1);
106
- this.store.put('people', humanId, { humanId, nickname: allowed.profile.nickname, email: allowed.profile.email, password: null, epoch: 1, hubSubject: input.subject, createdAt: new Date(this.clock()).toISOString() }); return humanId;
112
+ this.store.put('people', humanId, { humanId, nickname: allowed.profile.nickname, email: allowed.profile.email, password: null, epoch: 1, hubSubject: input.subject, hubPending: true, createdAt: new Date(this.clock()).toISOString() }); return humanId;
107
113
  });
108
114
  await this.request('/v1/starpost/link-new', { subject: input.subject, externalId });
109
115
  }
110
116
  return this.store.transaction(() => {
117
+ const person = this.accounts.person(externalId);
118
+ this.store.put('people', person.humanId, { ...person, hubSubject: input.subject, hubPending: false, email: allowed.profile.email || person.email });
119
+ if (!this.store.get('hubOriginalMappings', externalId)) this.store.put('hubOriginalMappings', externalId, { subject: input.subject, epoch: allowed.epoch });
111
120
  const out = this.accounts.issue(externalId), key = createHash('sha256').update(out.accessToken).digest('hex'), row = this.store.get('humanSessions', key);
112
- this.store.put('humanSessions', key, { ...row, hubSubject: input.subject, hubEpoch: allowed.epoch, hubServiceEpoch: allowed.serviceEpoch }); return out;
121
+ this.store.put('humanSessions', key, { ...row, hubSubject: input.subject, hubEpoch: allowed.epoch, hubServiceEpoch: allowed.serviceEpoch }); return { ...out, hubSubject: input.subject, hubIssuer: this.config.issuer, loginProvider: 'ffa-hub' };
113
122
  });
114
123
  }
115
124
  }
@@ -1,23 +1,89 @@
1
- import { createHash, randomBytes } from 'node:crypto';
1
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
2
  import http from 'node:http';
3
3
  import { jwtVerify, createLocalJWKSet } from 'jose';
4
4
  const random = () => randomBytes(32).toString('base64url');
5
5
  const hash = value => createHash('sha256').update(String(value)).digest('hex');
6
6
  const fail = (message, status = 400) => { throw Object.assign(new Error(message), { status }); };
7
+ const pkce = value => createHash('sha256').update(value).digest('base64url');
8
+ const equal = (a, b) => typeof a === 'string' && typeof b === 'string' && Buffer.byteLength(a) === Buffer.byteLength(b) && timingSafeEqual(Buffer.from(a), Buffer.from(b));
9
+ const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
7
10
  export class HubSso {
8
11
  constructor(config, { store, bridge, clock = Date.now }) { Object.assign(this, { config, store, bridge, clock }); this.keys = createLocalJWKSet(config.jwks); }
9
12
  post(path, data) {
10
13
  return new Promise((resolve, reject) => { const body = new URLSearchParams(data).toString(); const req = http.request(this.config.internalBase + path, { method: 'POST', headers: { Host: this.config.host, 'X-Forwarded-Proto': this.config.development ? 'http' : 'https', 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(body), Authorization: 'Basic ' + Buffer.from(this.config.clientId + ':' + this.config.clientSecret).toString('base64') } }, res => { let raw = ''; res.on('data', p => { raw += p; if (raw.length > 256000) req.destroy(Error('Response too large')); }); res.on('error', reject); res.on('end', () => { try { const out = JSON.parse(raw); if (res.statusCode !== 200) reject(Error('FFA 授权兑换失败')); else resolve(out); } catch { reject(Error('授权响应无效')); } }); }); req.setTimeout(5000, () => req.destroy(Error('授权请求超时'))); req.on('error', reject); req.end(body); });
11
14
  }
15
+ page(res, title, content, headers = {}) {
16
+ const nonce = random();
17
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': `default-src 'none'; style-src 'nonce-${nonce}'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`, ...headers });
18
+ res.end(`<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(title)} · 星邮</title><style nonce="${nonce}">:root{color-scheme:light dark;font-family:system-ui,sans-serif}body{margin:0;background:light-dark(#f5f4fc,#17151e);color:light-dark(#262236,#e9e5f5);padding:8vh 20px}main{max-width:560px;margin:auto;background:light-dark(white,#24212e);border-radius:28px;padding:30px}h1{font-size:28px}p{line-height:1.8}button,a{display:block;box-sizing:border-box;width:100%;padding:16px;margin:12px 0;border:0;border-radius:18px;background:light-dark(#e5ddff,#463a64);color:inherit;text-decoration:none;font:inherit;text-align:left}small{display:block;opacity:.7;margin:6px 0;overflow-wrap:anywhere}</style><main><small>STARPOST / FFA HUB</small><h1>${escape(title)}</h1>${content}</main></html>`);
19
+ }
20
+ nativeFlow(id) {
21
+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(id)) fail('手机登录请求无效');
22
+ const flow = this.store.get('hubMobileFlows', hash(id));
23
+ if (!flow || flow.expiresAt <= this.clock()) fail('手机登录已过期,请回到 APP 重新发起', 410);
24
+ return flow;
25
+ }
26
+ async mobile(action, input, remote) {
27
+ this.bridge.accounts.throttle.take([[`hub-mobile:${action}:${remote}`, action === 'start' ? 10 : 60, 60000]]);
28
+ if (action === 'start') {
29
+ if (typeof input.challenge !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(input.challenge)) fail('手机登录校验参数无效');
30
+ const id = random(), expiresAt = this.clock() + 600000;
31
+ this.store.transaction(() => {
32
+ this.store.statement("DELETE FROM documents WHERE collection='hubMobileFlows' AND at<?").run(new Date(this.clock()).toISOString());
33
+ this.store.put('hubMobileFlows', hash(id), { status: 'pending', challenge: input.challenge, expiresAt, at: new Date(expiresAt).toISOString() });
34
+ });
35
+ return { flowId: id, authorizationUrl: this.config.publicOrigin + '/web/hub/start?mobile=' + id, expiresAt, interval: 3 };
36
+ }
37
+ const flow = this.nativeFlow(input.flowId);
38
+ if (typeof input.verifier !== 'string' || !/^[A-Za-z0-9_-]{43,128}$/.test(input.verifier) || !equal(pkce(input.verifier), flow.challenge)) fail('手机登录验证失败', 403);
39
+ if (flow.status === 'pending') return { status: 'pending' };
40
+ if (flow.status !== 'ready') fail('手机登录已处理,请重新发起', 409);
41
+ this.store.transaction(() => this.store.put('hubMobileFlows', hash(input.flowId), { ...flow, status: 'redeeming' }));
42
+ try {
43
+ const result = await this.bridge.signInIdentity({ subject: flow.subject, externalId: flow.externalId });
44
+ this.store.transaction(() => this.store.remove('hubMobileFlows', hash(input.flowId)));
45
+ return { ...result, status: 'complete' };
46
+ } catch (e) { this.store.transaction(() => this.store.put('hubMobileFlows', hash(input.flowId), { ...flow, status: 'ready' })); throw e; }
47
+ }
48
+ async finish(flow, externalId, res, cookie) {
49
+ if (flow.mobile) {
50
+ const mobile = this.nativeFlow(flow.mobile);
51
+ if (mobile.status !== 'pending') fail('该手机登录请求已处理,请重新发起', 409);
52
+ const allowed = await this.bridge.request('/v1/links', { subject: flow.subject });
53
+ if (externalId && !allowed.links.some(l => l.kind === 'human' && l.external_id === externalId)) fail('此星邮业务号不属于当前 Hub 账号', 403);
54
+ this.store.transaction(() => {
55
+ const current = this.nativeFlow(flow.mobile);
56
+ if (current.status !== 'pending') fail('该手机登录请求已处理,请重新发起', 409);
57
+ this.store.put('hubMobileFlows', hash(flow.mobile), { ...current, status: 'ready', subject: flow.subject, externalId });
58
+ });
59
+ return this.page(res, '授权完成', '<p>已确认你的 FFA hub 身份。请返回星邮 APP 完成登录,原星邮 ID 和记录会继续保留。</p><a href="io.starpost.mobile://hub/return?flow=' + escape(flow.mobile) + '">返回星邮 APP</a><small>如按钮未唤起 APP,请手动切回星邮,点击“完成登录”。</small>', { 'Set-Cookie': cookie('', 0) });
60
+ }
61
+ const result = await this.bridge.signInIdentity({ subject: flow.subject, externalId });
62
+ res.writeHead(303, { Location: '/app/social', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'Set-Cookie': [`starpost_session=${result.accessToken}; Path=/web; HttpOnly; SameSite=Strict; ${this.config.development ? '' : 'Secure; '}Max-Age=${14 * 86400}`, cookie('', 0)] }); res.end();
63
+ }
12
64
  async handle(req, res) {
13
65
  const c = this.config, u = new URL(req.url, c.publicOrigin), cookieName = c.development ? 'starpost_hub_flow' : '__Secure-starpost_hub_flow', cookie = (value, age) => `${cookieName}=${value}; Path=/web/hub; HttpOnly; SameSite=Lax; ${c.development ? '' : 'Secure; '}Max-Age=${age}`;
14
66
  if (u.pathname === '/web/hub/start') {
67
+ if (!c.development && req.headers.host !== new URL(c.publicOrigin).host) {
68
+ res.writeHead(303, { Location: c.publicOrigin + u.pathname + u.search, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' }); res.end(); return;
69
+ }
70
+ const mobile = u.searchParams.get('mobile'); if (mobile && this.nativeFlow(mobile).status !== 'pending') fail('请在 APP 重新发起登录', 409);
15
71
  const state = random(), nonce = random(), verifier = random(), browser = random();
16
- this.store.transaction(() => { this.store.statement("DELETE FROM documents WHERE collection='hubSsoFlows' AND at<?").run(new Date(this.clock()).toISOString()); this.store.put('hubSsoFlows', hash(state), { browser: hash(browser), nonce, verifier, externalId: u.searchParams.get('account'), expiresAt: this.clock() + 600000, at: new Date(this.clock() + 600000).toISOString() }); });
72
+ this.store.transaction(() => { this.store.statement("DELETE FROM documents WHERE collection IN ('hubSsoFlows','hubSsoChoices') AND at<?").run(new Date(this.clock()).toISOString()); this.store.put('hubSsoFlows', hash(state), { browser: hash(browser), nonce, verifier, mobile, externalId: u.searchParams.get('account'), expiresAt: this.clock() + 600000, at: new Date(this.clock() + 600000).toISOString() }); });
17
73
  const auth = new URL(c.issuer + '/auth'); auth.search = new URLSearchParams({ client_id: c.clientId, response_type: 'code', redirect_uri: c.publicOrigin + '/web/hub/callback', scope: 'openid profile email', state, nonce, code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256', prompt: 'login consent' }).toString();
18
74
  res.writeHead(303, { Location: auth.href, 'Set-Cookie': cookie(browser, 600), 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' }); res.end(); return;
19
75
  }
20
- const state = u.searchParams.get('state'), flow = state && this.store.get('hubSsoFlows', hash(state)), browser = (req.headers.cookie ?? '').split(';').map(x => x.trim()).find(x => x.startsWith(cookieName + '='))?.slice(cookieName.length + 1);
76
+ const browser = (req.headers.cookie ?? '').split(';').map(x => x.trim()).find(x => x.startsWith(cookieName + '='))?.slice(cookieName.length + 1);
77
+ if (u.pathname === '/web/hub/select') {
78
+ if (req.method !== 'POST' || req.headers.origin !== new URL(c.publicOrigin).origin || !req.headers['content-type']?.startsWith('application/x-www-form-urlencoded')) fail('账号选择请求来源无效', 403);
79
+ let raw = ''; for await (const part of req) { raw += part.toString(); if (raw.length > 4096) fail('请求过大', 413); }
80
+ const input = new URLSearchParams(raw), choice = browser && this.store.get('hubSsoChoices', hash(browser));
81
+ if (!choice || choice.expiresAt <= this.clock() || !equal(input.get('csrf'), choice.csrf)) fail('账号选择已失效,请重新登录', 403);
82
+ const externalId = input.get('account'); if (!choice.accounts.includes(externalId)) fail('请选择当前 Hub 账号关联的星邮业务号', 403);
83
+ this.store.transaction(() => this.store.remove('hubSsoChoices', hash(browser)));
84
+ return this.finish(choice, externalId, res, cookie);
85
+ }
86
+ const state = u.searchParams.get('state'), flow = state && this.store.get('hubSsoFlows', hash(state));
21
87
  if (!flow || flow.expiresAt <= this.clock() || !browser || hash(browser) !== flow.browser) fail('联合登录已失效,请重新从星邮登录');
22
88
  this.store.transaction(() => this.store.remove('hubSsoFlows', hash(state)));
23
89
  if (u.searchParams.has('error')) fail('已取消 FFA hub 授权');
@@ -25,8 +91,12 @@ export class HubSso {
25
91
  const { payload } = await jwtVerify(tokens.id_token, this.keys, { issuer: c.issuer, audience: c.clientId, algorithms: ['RS256'] }); if (payload.nonce !== flow.nonce) fail('授权随机数不一致', 403);
26
92
  const active = await this.post('/token/introspection', { token: tokens.access_token }); if (!active.active || active.sub !== payload.sub) fail('FFA 身份授权已撤销', 403);
27
93
  const associations = await this.bridge.request('/v1/links', { subject: payload.sub });
28
- if (!flow.externalId && associations.links.filter(l => l.kind === 'human').length > 1) { res.writeHead(303, { Location: c.issuer + '/?service=starpost', 'Cache-Control': 'no-store', 'Set-Cookie': cookie('', 0) }); res.end(); return; }
29
- const result = await this.bridge.signInIdentity({ subject: payload.sub, externalId: flow.externalId });
30
- res.writeHead(303, { Location: '/app/social', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'Set-Cookie': [`starpost_session=${result.accessToken}; Path=/web; HttpOnly; SameSite=Strict; ${c.development ? '' : 'Secure; '}Max-Age=${14 * 86400}`, cookie('', 0)] }); res.end();
94
+ const accounts = associations.links.filter(l => l.kind === 'human').map(l => l.external_id);
95
+ if (!flow.externalId && accounts.length > 1) {
96
+ const choice = { subject: payload.sub, mobile: flow.mobile, accounts, csrf: random(), expiresAt: this.clock() + 300000, at: new Date(this.clock() + 300000).toISOString() };
97
+ this.store.transaction(() => this.store.put('hubSsoChoices', hash(browser), choice));
98
+ return this.page(res, '选择星邮账号', '<p>此 FFA hub 身份关联了多个星邮业务号。各账号的聊天、好友和记录分别保存。</p><form method="post" action="/web/hub/select"><input type="hidden" name="csrf" value="' + choice.csrf + '">' + accounts.map(id => '<button name="account" value="' + escape(id) + '">' + escape(this.store.get('people', id)?.nickname || '星邮账号') + '<small>' + escape(id) + '</small></button>').join('') + '</form>');
99
+ }
100
+ return this.finish({ ...flow, subject: payload.sub }, flow.externalId || accounts[0], res, cookie);
31
101
  }
32
102
  }
@@ -1,8 +1,9 @@
1
1
  [
2
- "私聊、群聊及「我的 bot」新增双向语音:手机和网页长按录音、松手发送、上滑取消;点击语音才下载播放,游戏仍使用文字。",
3
- "Cortico 和 DSH 可配置云端/本地 ASR、TTS,以及 FFmpeg/SILK 程序或 HTTP 转换接口;需人类提供服务,默认不安装模型。",
4
- "语音识别遵守原接收模式:专属消息及时唤醒,普通聊天合批或主动查收;支持语音引用、撤回与合并转发。",
5
- "APP 新增拍照发送;手机与网页发送成功收起键盘;回到底部缩为输入框上方的小按钮,不遮挡消息。",
6
- "APP 首次打开即询问聊天通知,允许后申请系统权限,登录完成自动启用;拒绝不重复询问,可在设置调整。",
7
- "请更新 Cortico 星邮至 0.32.0、Android 至 1.13.0、DSH 插件至 0.2.0;网页刷新生效。这是一次大更新,有问题随时反馈。"
2
+ "网页和 Android 统一使用 FFA hub 登录/注册;原星邮邮箱、密码可在 Hub 使用。",
3
+ "原星邮 ID、好友、群聊、动态和历史记录保留;同一 Hub 下多个星邮业务号登录时选号,各号数据独立。",
4
+ "已有有效登录和 Cortico/DSH bot 登录继续保留;未绑定邮箱的旧账号仍有升级入口。",
5
+ "Android 请更新到 1.14.0:在浏览器完成 Hub 授权,返回 APP 登录,凭据不出现在返回链接中。",
6
+ "FFA 接入规范新增所有项目按已验证 Hub 身份、项目与业务号隔离数据的验收要求。",
7
+ "本地表情收藏和背景开始按账号隔离;旧版未标记归属的内容保留原文件,需在当前账号重新收藏或设置,已发送图片与历史不变。",
8
+ "这是一次大更新,有问题随时反馈。"
8
9
  ]
package/server/server.mjs CHANGED
@@ -880,7 +880,17 @@ export function createStarpostServer({ file = './starpost-data.json', dbFile, me
880
880
  res.once('finish', () => metrics.record(metricAction, res.statusCode, started));
881
881
  try {
882
882
  if (req.method === 'GET' && req.url === '/health') { res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end('{"ok":true}'); return; }
883
- if (hubSso && req.method === 'GET' && ['/web/hub/start', '/web/hub/callback'].includes(req.url.split('?')[0])) { await hubSso.handle(req, res); return; }
883
+ if (req.method === 'GET' && req.url === '/web/login-info') { res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify({ ok: true, result: { hubOnly: Boolean(hubSso && hubConfig.humanLogin === 'hub'), issuer: hubConfig?.issuer } })); return; }
884
+ if (hubSso && (req.method === 'GET' && ['/web/hub/start', '/web/hub/callback'].includes(req.url.split('?')[0]) || req.method === 'POST' && req.url === '/web/hub/select')) { await hubSso.handle(req, res); return; }
885
+ if (hubSso && req.method === 'POST' && ['/mobile/hub/start', '/mobile/hub/poll'].includes(req.url)) {
886
+ if (!req.headers['content-type']?.startsWith('application/json')) fail('需要 JSON 请求', 415);
887
+ let raw = ''; for await (const part of req) { raw += part.toString(); if (Buffer.byteLength(raw) > 4096) fail('请求过大', 413); }
888
+ let input; try { input = JSON.parse(raw); } catch { fail('JSON 格式错误'); }
889
+ if (!input || typeof input !== 'object' || Array.isArray(input)) fail('请求格式错误');
890
+ const remote = ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket.remoteAddress) ? String(req.headers['x-real-ip'] ?? req.socket.remoteAddress) : req.socket.remoteAddress;
891
+ const result = await hubSso.mobile(req.url.endsWith('/start') ? 'start' : 'poll', input, remote);
892
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify({ ok: true, result })); return;
893
+ }
884
894
  if (req.method === 'GET' && req.url === '/metrics') {
885
895
  if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket.remoteAddress)) fail('仅允许本机读取指标', 403);
886
896
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
@@ -933,6 +943,7 @@ export function createStarpostServer({ file = './starpost-data.json', dbFile, me
933
943
  const web = req.url === '/web/auth';
934
944
  if (web && ![`https://${req.headers.host}`, `http://${req.headers.host}`].includes(req.headers.origin)) fail('网页请求来源无效', 403);
935
945
  const input = JSON.parse(raw);
946
+ if (hubConfig?.humanLogin === 'hub' && !(input.action === 'claim' || input.action === 'code' && input.purpose === 'claim')) fail('星邮注册和登录已升级为 FFA hub,请在网页使用 Hub 登录,或更新 APP;已登录的账号可继续使用', 409);
936
947
  let legacyHumanId;
937
948
  if (input.action === 'claim' || input.action === 'code' && input.purpose === 'claim') {
938
949
  const token = /(?:^|;\s*)starpost_session=([a-f0-9]{64})(?:;|$)/.exec(req.headers.cookie ?? '')?.[1] ?? '';
@@ -967,8 +978,11 @@ export function createStarpostServer({ file = './starpost-data.json', dbFile, me
967
978
  } else {
968
979
  const token = /(?:^|;\s*)starpost_session=([a-f0-9]{64})(?:;|$)/.exec(req.headers.cookie ?? '')?.[1] ?? '';
969
980
  const session = access.authenticate(`Bearer ${token}`);
981
+ if (req.headers['x-starpost-account'] && req.headers['x-starpost-account'] !== (session.human ? session.owner : session.humanId)) fail('账号已在其他页面切换,请重新打开星邮', 401);
970
982
  const hubState = hubBridge && input.action !== 'logout' ? await hubBridge.sessionCheck(session, false, input.action, input.args ?? {}) : null;
983
+ if (req.headers['x-ffa-subject'] && req.headers['x-ffa-subject'] !== hubState?.subject) fail('Hub 身份已变更,请重新登录', 401);
971
984
  result = store.transaction(() => access.call(session, input.action, privacy.decode(input.args ?? {},input.action)));
985
+ if (hubState && input.action === 'account.info') result = hubBridge.accountInfo(result, hubState);
972
986
  if (hubState && input.action === 'owner.notifications') result = hubBridge.filterNotifications(result, hubState);
973
987
  if (hubBridge && input.action === 'account.bind') await hubBridge.sync();
974
988
  if (input.action === 'logout') res.setHeader('Set-Cookie', cookie('', 0));
@@ -1003,10 +1017,11 @@ export function createStarpostServer({ file = './starpost-data.json', dbFile, me
1003
1017
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
1004
1018
  res.end(JSON.stringify({ ok: true, result })); return;
1005
1019
  }
1006
- if (hubBridge && req.url === '/mobile/rpc' && input.action !== 'logout') await hubBridge.sessionCheck(access.authenticate(req.headers.authorization), false, input.action, input.args ?? {});
1007
- const result = store.transaction(() => req.url === '/mobile/login'
1020
+ const hubState = hubBridge && req.url === '/mobile/rpc' && input.action !== 'logout' ? await hubBridge.sessionCheck(access.authenticate(req.headers.authorization), false, input.action, input.args ?? {}) : null;
1021
+ let result = store.transaction(() => req.url === '/mobile/login'
1008
1022
  ? access.signIn(input, remote)
1009
1023
  : access.call(access.authenticate(req.headers.authorization), input.action, privacy.decode(input.args ?? {},input.action)));
1024
+ if (hubState && input.action === 'account.info') result = hubBridge.accountInfo(result, hubState);
1010
1025
  if (hubBridge && req.url === '/mobile/login') { await hubBridge.sync(); await hubBridge.sessionCheck(access.authenticate(`Bearer ${result.accessToken}`), true); }
1011
1026
  if (hubBridge && req.url === '/mobile/rpc' && input.action === 'account.bind') await hubBridge.sync();
1012
1027
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });