@coda-console/friends 0.2.0 → 0.3.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/README.md CHANGED
@@ -2,10 +2,10 @@
2
2
 
3
3
  管理本机的 Accord 身份、个人名片与熟人好友通道(`coda/accord@1`)。
4
4
 
5
- - **我的身份与名片**:显示本机公钥短码,可复制公钥;昵称、头像 Emoji、主题色以公开的 `profile` / `self` 记录发布。
5
+ - **我的身份与名片**:显示本机公钥短码,可复制公钥;昵称、头像 Emoji、主题色以公开的 `profile` / `self` 记录发布;本机绑定了代签证书、`profile` 被拒(`forbidden`)时改发可代签的社交名片 `friends/card` / `self`。
6
6
  - **添加好友**:粘贴对方给的邀请(JSON、`coda-friend://` 链接或多行 `key=value`),接受后自动尝试互认。暂需由对方提供 friend 角色入网码。
7
7
  - **好友列表**:实时跟随好友表变化;可备注、重新互认、移除。
8
- - **社交网关 `friends/social@1`**:业务无关,别的插件(在 `optionalUses` 里声明)经它读好友与好友分享的记录、向好友发布与撤回记录,不必各自处理没有身份、证书过期和重试。
8
+ - **社交网关 `friends/social@1`**:业务无关,别的插件(在 `optionalUses` 里声明)经它读好友与好友分享的记录、向好友发布与撤回记录、发私信与动态、实时跟随私信与动态,不必各自处理没有身份、证书过期和重试。
9
9
 
10
10
  ## 社交网关
11
11
 
@@ -13,18 +13,42 @@
13
13
 
14
14
  | 操作 | 作用 |
15
15
  | --- | --- |
16
- | `friends`(读) | 互认的好友(`includePending` 带上待互认与冲突的),合并名片与本地备注 |
16
+ | `friends`(读) | 互认的好友(`includePending` 带上待互认与冲突的),合并 `profile`、`friends/card`(逐字段 `profile` 优先)与本地备注;每行带 `avatar`(`content/<sha256>` 指针或 `null`) |
17
17
  | `records`(读) | 按 `kind`、`author`、`id`、`cursor` 读好友分享的记录,不读 `binding` |
18
18
  | `publish` | 发布 `{ kind, id, body, audience? }`;同作者同内容不重发,换作者重发 |
19
+ | `set-card` | 发布本机社交名片 `friends/card` / `self`:`{ name, emoji?, color?, avatar? }`,`avatar` 只收 `content/<sha256>` 指针(至多 5 MiB),`null` 清除;与 `publish` 同一条队 |
20
+ | `send-dm` | 发一条私信 `friends/dm`:`{ to, id?, text?, attachments?, replyTo? }`,受众只有 `to` 一人(不收 `public`、不收自己);结果带最终用的 `id` |
21
+ | `post-feed` | 发一条动态 `friends/feed`:`{ id?, text?, media?, audience? }`,`audience` 缺省 `['public']`,写了须是 1–500 项(去重);结果带最终用的 `id` |
19
22
  | `retract` | 撤回一条,或省略 `id` 撤回本机在这个 `kind` 下的全部(含队列里还没发出去的) |
20
23
  | `outbox`(读) | 待发与已同步条目的状态,从不给出 `body` |
21
24
 
22
25
  - `publish`、`retract` 拒绝保留类型 `binding`、`profile`、`friends`、`coda/profile`、`coda/friends`;`kind` 须是 Accord 的格式,`id` 至多 200 个字符、256 字节,`body` 是对象且 JSON 至多 64 KiB,`audience` 每项是 `public` 或 `ed25519:` 加 64 位十六进制,至多 500 项。
23
26
  - 没有身份、证书过期(或发布遇到 `invalid_state`)、`kind` 被暂停、发布失败时,待发的 `body` 暂存在本机 `outbox.json`;同步成功就释放 `body`,只留去重用的 `lastAuthor`、`lastSyncedHash`、`lastSyncedAt`;撤回完成就删掉条目。证书恢复后自动补发、补撤;待撤的条目记着排队时的作者(`targetAuthor`),换了作者不会替新作者撤,没有身份时的撤回只清本机未发出的待发,不排待撤。意图先落盘再签名,签名成功立即落盘确认;`outbox.json`、`policy.json` 读不出来(不是缺失或损坏)就报错,不当空表。
27
+ - 操作名照协议包的规定用小写加连字符(`set-card`、`send-dm`、`post-feed`)。
24
28
  - 暂停与恢复某个 `kind` 的外发:`coda self policy.setKind '{"kind":"…","paused":true}'`,`coda self policy.get` 读现状(`policy.json`);暂停只拦发布,不拦撤回。
25
29
 
30
+ ## 私信与动态
31
+
32
+ 两类记录都由 Accord 签名与保存,网关只清洗与投影,没有第二套目录库;没有身份或证书过期时在 `outbox.json` 排队、恢复后补发,撤回统一走 `retract({ kind: 'friends/dm' | 'friends/feed', id })`。
33
+
34
+ - **正文**:`text` 按原样(含首尾空白)至多 8000 个字(码点,与 schema 的 `maxLength` 一致),发布时去首尾空白;图片指针(`attachments` / `media`)1–4 个,只收 `content/<sha256>`;两者不能都空。`id` 省略时网关生成 UUID,给了须是至多 200 个字符、且 UTF-8 至多 256 字节(与 Accord 一致;schema 表达不了字节数,超了由网关以 `invalid_input` 拒绝)、不含控制字符,去首尾空白后不能为空;`replyTo` 同。
35
+ - **只发给别人**:私信的 `to` 不能是本人。排队时还没有身份、后来绑定的身份正好是收件人的,补发时按实际签名的作者再判一次,标成被拒(`error`),不签。
36
+ - **幂等重试**:`body.createdAt` 先沿用同一 `id` 已有的:`outbox.json` 里待发条目的,或已同步条目留下的 `lastCreatedAt`;队列里没有才查本机在 Accord 里的那条,查明没有才取当前时间,查询失败报可重试的 `unavailable`,不拿新时间戳重签。所以同一 `id`、同样内容的重试按 `publish` 的去重返回 `skipped: true`,不会重签。
37
+ - **投影**:每个 `(author, id)` 只取 `version` 最大的一条,它若是撤回(空 `body`)或畸形,整条就没了,不回落旧版本。私信只收本机发出(本人签、发给别人)或发给本机(别人签、`to` 是本人)的,`peer` 是对面那个人;串线、伪造的丢掉。私信按 `(createdAt, version, author, id)` 升序,动态降序。
38
+
39
+ ### 实时流 `dm`、`feed`
40
+
41
+ 两条都是 `read` 形状的帧流(`application/x-ndjson`,30 秒没东西写一个空行心跳),参数走查询串:`dm` 收 `peer`(只看与这位好友的),`feed` 收 `author`(只看这一位的),都收 `after`(上次拿到的游标)。
42
+
43
+ - 快照分片发出:每帧 `{ type: 'snapshot', cursor, items, more }`,单帧 JSON 至多 256 KiB(远低于 `readFrames` 默认的一行 1 MiB);后面还有分片的 `more` 为 `true`,最后一片(空快照也有这一片,`items: []`)为 `false`。客户端把各片的 `items` 依次拼起来,收到 `more: false` 才落定整份快照与游标。
44
+ - 之后每次变化一帧 `{ type: 'upsert', cursor, item }` 或 `{ type: 'retract', cursor, author, id, peer? }`。同一条私信改投新收件人时,旧会话先收到 `retract`(`peer` 是旧收件人),新会话再收到 `upsert`。
45
+ - 游标是 `<epoch>:<seq>`:`epoch` 每次网关启动重新生成,`seq` 单调递增。网关在内存里留最近 500 次变化;`after` 有效时只补它之后的增量(含撤回,不重复)。`after` 缺失、不合法、来自上一次启动、比现在还新或已被挤出这 500 条的,回到全量快照。
46
+ - 只在有订阅者或新流连入时才翻页读 Accord,随本机 Accord 记录的变化和本机的发布、撤回刷新;刷新排成一条队,不会交错。每次都翻页读到底,读不全(翻页截断、查询失败)就不动内存里上一份完整的投影,不推虚假的快照或撤回;还从没读全过时新连入的流在第一个字节之前以 `unavailable` 失败。
47
+ - 调用方中止请求、取消应答体,或插件停用时,流当场收尾,订阅与监听随之释放(不等下一帧、也不管调用方读没读)。
48
+
26
49
  ## 权限与数据边界
27
50
 
51
+ - `friends/social@1` 的权限组:`read` 管 `friends`、`records` 和 `dm`、`feed` 两条流;`publish` 管 `publish`、`set-card`、`send-dm`、`post-feed`、`retract`、`outbox`。
28
52
  - `uses`:`coda/accord@1` 的 `read`(读好友表与名片)、`publish`(发布名片)、`manage`(接受邀请、互认、移除)。
29
53
  - 入网码(`authKey`)是凭据:只在提交时用一次,提交后立即清空输入框,不写入任何文件、日志或页面状态。
30
54
  - 本地备注只存在插件自己的持久目录 `notes.json`(卸载后保留),不发给好友,也不进 Accord 目录。
package/lib/friends.mjs CHANGED
@@ -4,13 +4,15 @@
4
4
  export const COLORS = ['blue', 'orange', 'green', 'purple', 'pink', 'teal', 'gray'];
5
5
  export const PROFILE_KIND = 'profile';
6
6
  export const PROFILE_ID = 'self';
7
+ // 可代签的社交名片:和 profile 同形,id 也是 self;profile 须客户端根签,绑定代签证书后用它。
8
+ export const CARD_KIND = 'friends/card';
7
9
  const MAX_NAME = 40, MAX_EMOJI = 8;
8
10
  // 邀请各字段的上限,与 coda/accord@1 的 accept 输入一致。
9
- const LIMITS = { control: 500, authKey: 500, linkId: 64, scope: 200, hostname: 100, peerNode: 100 };
10
- const LABELS = { control: '入网地址 control', authKey: '入网码 authKey', linkId: 'linkId', scope: 'scope', hostname: 'hostname', peerNode: 'peerNode' };
11
+ const LIMITS = { control: 500, authKey: 500, linkId: 64, scope: 520, hostname: 100, peerNode: 100 };
12
+ const LABELS = { control: '入网地址 control', authKey: '入网码 authKey', linkId: 'linkId', scope: 'scope', hostname: 'hostname', peerNode: 'peerNode', peerPort: 'peerPort' };
11
13
  const LINK_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
12
14
  const ALIASES = { controlurl: 'control', control_url: 'control', authkey: 'authKey', auth_key: 'authKey', linkid: 'linkId', link_id: 'linkId',
13
- link: 'linkId', peernode: 'peerNode', peer_node: 'peerNode' };
15
+ link: 'linkId', peernode: 'peerNode', peer_node: 'peerNode', peerport: 'peerPort', peer_port: 'peerPort' };
14
16
  const CONTROL_CHARS = /[\p{Cc}\u2028\u2029]/gu;
15
17
  const length = text => [...text].length;
16
18
 
@@ -19,7 +21,7 @@ const clean = text => typeof text === 'string' ? text.replace(CONTROL_CHARS, '')
19
21
  // ---- 邀请 ----
20
22
 
21
23
  const fail = message => { throw new Error(message); };
22
- const field = key => ALIASES[key] ?? ALIASES[key.toLowerCase()] ?? (Object.hasOwn(LIMITS, key) ? key : null);
24
+ const field = key => ALIASES[key] ?? ALIASES[key.toLowerCase()] ?? (Object.hasOwn(LABELS, key) ? key : null);
23
25
 
24
26
  function fromObject(object) {
25
27
  const found = {};
@@ -54,7 +56,7 @@ function fromLines(text) {
54
56
  }
55
57
 
56
58
  /**
57
- * 把粘贴的邀请解析成 accept 的入参:`{ linkId, control, authKey, scope?, hostname?, peerNode? }`。
59
+ * 把粘贴的邀请解析成 accept 的入参:`{ linkId, control, authKey, scope?, hostname?, peerNode?, peerPort? }`。
58
60
  * 接受 JSON 对象、coda-friend:// 或带查询串的链接、多行 key=value;错误抛出清晰的中文提示。
59
61
  */
60
62
  export function parseInvite(raw) {
@@ -91,30 +93,90 @@ export function checked(input) {
91
93
  if (!invite.control) fail('邀请缺少 control(入网地址)');
92
94
  if (!invite.authKey) fail('邀请缺少 authKey(入网码)');
93
95
  for (const [name, max] of Object.entries(LIMITS)) if (invite[name] && length(invite[name]) > max) fail(`${LABELS[name]} 太长(最多 ${max} 字)`);
96
+ const raw = input?.peerPort;
97
+ if (raw !== undefined && raw !== null && typeof raw !== 'number' && typeof raw !== 'string') fail('peerPort 须是 1–65535 的整数');
98
+ const port = typeof raw === 'string' ? raw.trim() : raw;
99
+ if (port !== undefined && port !== null && port !== '') {
100
+ const number = typeof port === 'number' ? port : /^\d+$/.test(port) ? Number(port) : NaN;
101
+ if (!Number.isInteger(number) || number < 1 || number > 65535) fail('peerPort 须是 1–65535 的整数');
102
+ invite.peerPort = number;
103
+ }
94
104
  if (invite.linkId && !LINK_ID.test(invite.linkId)) fail('linkId 须以小写字母或数字开头,只能含小写字母、数字、下划线和连字符,最长 64 位');
95
105
  invite.linkId ??= `f-${[...globalThis.crypto.getRandomValues(new Uint8Array(4))].map(n => n.toString(16).padStart(2, '0')).join('')}`;
96
106
  return invite;
97
107
  }
98
108
 
109
+ // ---- 头像指针 ----
110
+
111
+ const MAX_BLOB = 5 * 1024 * 1024, MAX_MIME = 128, MAX_FILE_NAME = 200;
112
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
113
+ const CONTENT_PATH = /^content\/([0-9a-f]{64})$/;
114
+ const MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;
115
+ const POINTER_KEYS = new Set(['owner', 'path', 'sha256', 'mime', 'size', 'name']);
116
+
117
+ /**
118
+ * 内容寻址的图片指针(BlobPointer,`path` 只收 `content/<sha256>`)的校验:`{ owner, path, sha256, mime?, size?, name? }`,
119
+ * 不许别的键,`sha256` 须与 `path` 里的一致,`size` 至多 5 MiB。合法返回只含这些字段的新对象,不合法抛出中文错误。
120
+ */
121
+ export function normalizeContentPointer(pointer) {
122
+ if (!pointer || typeof pointer !== 'object' || Array.isArray(pointer)) fail('头像须是图片指针对象');
123
+ for (const key of Object.keys(pointer)) if (!POINTER_KEYS.has(key)) fail(`头像指针不认识的字段:${key}`);
124
+ const { owner, path, sha256, mime, size, name } = pointer;
125
+ if (typeof owner !== 'string' || !UUID.test(owner)) fail('头像指针的 owner 须是小写 UUID');
126
+ const match = typeof path === 'string' ? CONTENT_PATH.exec(path) : null;
127
+ if (!match) fail('头像指针的 path 须是 content/<64 位小写十六进制 SHA-256>');
128
+ if (sha256 !== match[1]) fail('头像指针的 sha256 须与 path 里的一致');
129
+ const out = { owner, path, sha256 };
130
+ if (mime !== undefined) {
131
+ if (typeof mime !== 'string' || !mime || mime.length > MAX_MIME || !MIME.test(mime)) fail(`头像指针的 mime 须是合法的 MIME 类型(最多 ${MAX_MIME} 字)`);
132
+ out.mime = mime;
133
+ }
134
+ if (size !== undefined) {
135
+ if (!Number.isSafeInteger(size) || size < 0 || size > MAX_BLOB) fail('头像指针的 size 须是 0 到 5 MiB 之间的整数');
136
+ out.size = size;
137
+ }
138
+ if (name !== undefined) {
139
+ const text = clean(name);
140
+ if (!text || length(text) > MAX_FILE_NAME) fail(`头像指针的 name 须是非空文本(最多 ${MAX_FILE_NAME} 字)`);
141
+ out.name = text;
142
+ }
143
+ return out;
144
+ }
145
+
146
+ /** 读外来记录里的图片指针:合法给规范化的指针,不合法给 null,从不抛错。 */
147
+ export function readContentPointer(pointer) {
148
+ try { return normalizeContentPointer(pointer); } catch { return null; }
149
+ }
150
+
99
151
  // ---- 名片 ----
100
152
 
101
- /** 名片输入的清洗:昵称 1–40 字,emoji 最多 8 字,颜色须在白名单里。不合法的昵称、emoji 抛错;不认识的颜色丢掉。 */
102
- export function normalizeProfileInput({ name, emoji, color } = {}) {
153
+ /**
154
+ * 名片输入的清洗(profile 与 friends/card 同形):昵称 1–40 字,emoji 最多 8 字,颜色须在白名单里;
155
+ * avatar 省略不写,null 表示清除,否则须是合法的 content 指针。不合法的昵称、emoji、头像抛错;不认识的颜色丢掉。
156
+ */
157
+ export function normalizeCardInput({ name, emoji, color, avatar } = {}) {
103
158
  const body = { name: clean(name) };
104
159
  if (!body.name) fail('昵称不能为空');
105
160
  if (length(body.name) > MAX_NAME) fail(`昵称最多 ${MAX_NAME} 个字`);
106
161
  const mark = clean(emoji);
107
162
  if (mark) { if (length(mark) > MAX_EMOJI) fail(`头像最多 ${MAX_EMOJI} 个字符`); body.emoji = mark; }
108
163
  if (typeof color === 'string' && COLORS.includes(color)) body.color = color;
164
+ if (avatar !== undefined) body.avatar = avatar === null ? null : normalizeContentPointer(avatar);
109
165
  return body;
110
166
  }
167
+ export const normalizeProfileInput = normalizeCardInput;
111
168
 
112
169
  /**
113
170
  * 读 Accord 记录里的名片,来自好友的外来数据:按同样的规则清洗,不合法的字段忽略,昵称不合法整张忽略(null)。
171
+ * 头像分三种:没写或畸形是 `avatarPresent: false`;显式清除(`avatar: null`)与合法指针是 `avatarPresent: true`,`avatar` 为 null 或指针。
114
172
  * 结果只当文本用,不当指令或 HTML。
115
173
  */
116
- export function readProfileRecord(record) {
117
- if (!record || record.kind !== PROFILE_KIND || record.id !== PROFILE_ID) return null;
174
+ export const readProfileRecord = record => readNameRecord(record, PROFILE_KIND);
175
+ /** 同 readProfileRecord,读 friends/card 记录。 */
176
+ export const readCardRecord = record => readNameRecord(record, CARD_KIND);
177
+
178
+ function readNameRecord(record, kind) {
179
+ if (!record || record.kind !== kind || record.id !== PROFILE_ID) return null;
118
180
  const body = record.body;
119
181
  if (!body || typeof body !== 'object' || Array.isArray(body)) return null;
120
182
  const name = clean(body.name);
@@ -123,9 +185,32 @@ export function readProfileRecord(record) {
123
185
  const emoji = clean(body.emoji);
124
186
  if (emoji && length(emoji) <= MAX_EMOJI) profile.emoji = emoji;
125
187
  if (typeof body.color === 'string' && COLORS.includes(body.color)) profile.color = body.color;
188
+ const avatar = body.avatar === null ? null : readContentPointer(body.avatar);
189
+ profile.avatar = avatar;
190
+ profile.avatarPresent = body.avatar === null || avatar !== null;
126
191
  return profile;
127
192
  }
128
193
 
194
+ /**
195
+ * 同一作者的 profile(根私钥签名)与 friends/card(可代签)合成一张名片:profile 写了的字段优先,免得代签的机器盖过根签的资料;
196
+ * profile 没写的由 friends/card 补。头像看 `avatarPresent`:profile 写了(含显式清除的 null)就用 profile 的。两张都没有给 null。
197
+ */
198
+ export function mergeProfileAndCard(profile, card) {
199
+ if (!profile && !card) return null;
200
+ const pick = key => profile?.[key] ?? card?.[key];
201
+ const from = profile?.avatarPresent ? profile : card?.avatarPresent ? card : null;
202
+ return { name: pick('name'), emoji: pick('emoji'), color: pick('color'), avatar: from ? from.avatar : null, avatarPresent: Boolean(from) };
203
+ }
204
+
205
+ /**
206
+ * 代签回退发布了 friends/card 之后的提示:`true` 已确认有根签的 profile,如实说明好友看到的仍以它为准;`false` 已确认没有;
207
+ * `null` / `undefined` 没读出来,不承诺好友看到的是哪张。
208
+ */
209
+ export const cardFallbackNotice = hasRootProfile => hasRootProfile === true
210
+ ? '社交名片已保存,但你已有根私钥签名的名片,昵称等已有项仍以根签名为准(未设项由社交名片补充)'
211
+ : hasRootProfile === false ? '本机用的是代签证书,名片已改作社交名片(friends/card)发布,好友会看到它'
212
+ : '社交名片已保存;若你曾用根私钥发布过名片,昵称等已有项仍以根签名为准';
213
+
129
214
  /** 密钥的短码:`ed25519:` 之后的前 8 位(没有就空串)。 */
130
215
  export function shortAuthor(author) {
131
216
  const match = /^ed25519:([0-9a-f]{64})$/.exec(author ?? '');
@@ -138,22 +223,27 @@ const RANK = { conflict: 0, pending: 1, bound: 2 };
138
223
  export const statusOf = friend => friend.conflict ? 'conflict' : friend.bound ? 'bound' : 'pending';
139
224
 
140
225
  /**
141
- * 好友表(`status.friends`)、好友的名片记录(取每把钥匙 version 最大的)和本地备注(按 node,没有再按 author)合成的行,
142
- * 按状态(冲突、待互认、已互认)再按更新时间新的在前排序,同样的输入排出同样的顺序。
226
+ * 好友表(`status.friends`)、好友的名片记录(profile 与 friends/card 各取每把钥匙 version 最大的,按 mergeProfileAndCard
227
+ * 合成)和本地备注(按 node,没有再按 author)合成的行,按状态(冲突、待互认、已互认)再按更新时间新的在前排序,
228
+ * 同样的输入排出同样的顺序。
143
229
  */
144
- export function mergeFriendRows({ friends = [], profiles = [], notes = {} } = {}) {
145
- const latest = new Map();
146
- for (const record of profiles) {
147
- const profile = readProfileRecord(record);
148
- if (profile?.author && (!latest.has(profile.author) || profile.version > latest.get(profile.author).version)) latest.set(profile.author, profile);
149
- }
230
+ export function mergeFriendRows({ friends = [], profiles = [], cards = [], notes = {} } = {}) {
231
+ const latestOf = (records, read) => {
232
+ const latest = new Map();
233
+ for (const record of records) {
234
+ const one = read(record);
235
+ if (one?.author && (!latest.has(one.author) || one.version > latest.get(one.author).version)) latest.set(one.author, one);
236
+ }
237
+ return latest;
238
+ };
239
+ const byProfile = latestOf(profiles, readProfileRecord), byCard = latestOf(cards, readCardRecord);
150
240
  const note = friend => (Object.hasOwn(notes, friend.node) ? notes[friend.node] : friend.author && Object.hasOwn(notes, friend.author) ? notes[friend.author] : '');
151
241
  const rows = friends.map(friend => {
152
- const profile = friend.author ? latest.get(friend.author) ?? null : null, status = statusOf(friend), remark = clean(note(friend));
153
- const short = shortAuthor(friend.author);
242
+ const card = friend.author ? mergeProfileAndCard(byProfile.get(friend.author), byCard.get(friend.author)) : null;
243
+ const status = statusOf(friend), remark = clean(note(friend)), short = shortAuthor(friend.author), name = card?.name;
154
244
  return { node: friend.node, author: friend.author ?? null, short, status, peerNode: friend.peerNode ?? null, scope: friend.scope, updatedAt: friend.updatedAt ?? 0,
155
- note: remark, profileName: profile?.name ?? '', emoji: profile?.emoji ?? '', color: profile?.color ?? 'gray',
156
- title: remark || profile?.name || (short ? `好友 ${short}` : friend.node) };
245
+ note: remark, profileName: name ?? '', emoji: card?.emoji ?? '', color: card?.color ?? 'gray', avatar: card?.avatar ?? null,
246
+ title: remark || name || (short ? `好友 ${short}` : friend.node) };
157
247
  });
158
248
  return rows.sort((a, b) => RANK[a.status] - RANK[b.status] || b.updatedAt - a.updatedAt || (a.node < b.node ? -1 : a.node > b.node ? 1 : 0));
159
249
  }
package/lib/gateway.mjs CHANGED
@@ -1,15 +1,17 @@
1
1
  // 抽象社交网关:实现 friends/social@1。业务无关——只认 kind、id、body;签名写入与记录查询全部透传 coda/accord@1,
2
2
  // 自己不建第二份目录库,只在 outbox.json 里留还没发出去的 body(同步成功即释放)。所有会写盘、会外发的动作排成一条队,
3
3
  // 发布、撤回、证书变化引起的冲洗互不交叉。
4
- import { PROFILE_KIND, mergeFriendRows, statusOf } from './friends.mjs';
4
+ import { CARD_KIND, PROFILE_ID, PROFILE_KIND, mergeFriendRows, normalizeCardInput, statusOf } from './friends.mjs';
5
5
  import { readNotes } from './notes.mjs';
6
6
  import { canSkip, canonicalHash, certStateOf, checkId, checkKind, checkPublish, entryKey, holdState, keyOf, retractKey, invalid, isPending, markRejected, markSynced,
7
7
  nextSeq, queuePublish, queueRetract, readOutbox, withState, writeOutbox } from './outbox.mjs';
8
8
  import { readPolicy, setKindPaused } from './policy.mjs';
9
+ import { DM_KIND, FEED_KIND, createStreamHub, frameOf, normalizeDmInput, normalizeFeedInput, projectDmRecords, projectFeedRecords, snapshotFrames, subjectOf } from './social-streams.mjs';
9
10
 
10
11
  const ACCORD = { kind: 'coda/accord@1', id: 'local' };
11
12
  const SOCIAL = 'friends/social@1';
12
13
  const MAX_PAGES = 50;
14
+ const HEARTBEAT_MS = 30_000;
13
15
  const REJECTED = new Set(['invalid_input', 'forbidden']);
14
16
  const message = e => String(e?.message ?? e);
15
17
  const interrupted = effects => Object.assign(new Error('好友网关已停止'), { code: 'interrupted', effects });
@@ -38,11 +40,11 @@ export function createGateway(coda, dir) {
38
40
  return { accord, author: accord?.spec?.author ?? null, certState: certStateOf(accord) };
39
41
  }
40
42
 
41
- // 翻页读 coda/accord@1 的记录;cursor 重复就停,不会原地打转。
42
- async function pages(input) {
43
+ // 翻页读 coda/accord@1 的记录,至多 `maxPages` 页;cursor 重复就停,不会原地打转。
44
+ async function pages(input, maxPages = MAX_PAGES) {
43
45
  const records = [], seen = new Set();
44
46
  let cursor;
45
- for (let page = 0; page < MAX_PAGES; page++) {
47
+ for (let page = 0; page < maxPages; page++) {
46
48
  const read = await coda.query(ACCORD, 'records', { ...input, limit: 200, ...(cursor ? { cursor } : {}) });
47
49
  records.push(...(read?.records ?? []));
48
50
  cursor = read?.nextCursor;
@@ -62,6 +64,11 @@ export function createGateway(coda, dir) {
62
64
  // 把一条待发或待撤的条目交给 coda/accord@1 发出去(撤回是 body 为空、audience 为空的发布)。
63
65
  async function attempt(entry, author) {
64
66
  live();
67
+ // 私信不签给自己:按此刻真正签名的作者判,排队时还没有身份、后来绑成了收件人的也拦下,标成被拒。
68
+ if (entry.desired === 'publish' && entry.kind === DM_KIND && entry.body?.to === author) {
69
+ const error = '不能给自己发私信';
70
+ return { state: 'error', entry: markRejected(entry, error), error };
71
+ }
65
72
  const input = entry.desired === 'publish' ? { kind: entry.kind, id: entry.id, body: entry.body, audience: entry.audience }
66
73
  : { kind: entry.kind, id: entry.id, body: {}, audience: [] };
67
74
  try {
@@ -150,17 +157,18 @@ export function createGateway(coda, dir) {
150
157
  if (!stopped) await coda.put({ kind: SOCIAL, key: 'local' }, { spec: { version: 1 }, status });
151
158
  } catch { /* 状态记录下一次动作会再写 */ }
152
159
  }
153
- const mutate = work => serial(async () => { try { return await work(); } finally { await refreshNow(); } });
160
+ const mutate = work => serial(async () => { try { return await work(); } finally { await refreshNow(); pullWatched(); } });
154
161
 
155
162
  // ---- friends/social@1 的操作 ----
156
163
 
157
164
  async function friends({ includePending = false } = {}) {
158
165
  const { accord, author, certState } = await accordState();
159
166
  const list = Array.isArray(accord?.status?.friends) ? accord.status.friends : [];
160
- const { records, truncated } = list.length ? await pages({ kind: PROFILE_KIND }) : { records: [], truncated: false };
167
+ const none = { records: [], truncated: false };
168
+ const [profiles, cards] = list.length ? await Promise.all([pages({ kind: PROFILE_KIND }), pages({ kind: CARD_KIND })]) : [none, none];
161
169
  const notes = dir ? await readNotes(dir) : {};
162
- const rows = mergeFriendRows({ friends: list, profiles: records, notes }).filter(row => includePending || row.status === 'bound');
163
- return { selfAuthor: author, certState, friends: rows, truncated };
170
+ const rows = mergeFriendRows({ friends: list, profiles: profiles.records, cards: cards.records, notes }).filter(row => includePending || row.status === 'bound');
171
+ return { selfAuthor: author, certState, friends: rows, truncated: profiles.truncated || cards.truncated };
164
172
  }
165
173
 
166
174
  function records({ kind, author, id, limit, cursor, includeAudience }) {
@@ -172,44 +180,90 @@ export function createGateway(coda, dir) {
172
180
 
173
181
  function publish(input) {
174
182
  const item = checkPublish(input);
175
- return mutate(async () => {
176
- const d = stateDir(), key = entryKey(item.kind, item.id), outbox = await readOutbox(d), prev = outbox[key];
177
- let current;
178
- try { current = await accordState(); } catch (e) {
179
- outbox[key] = withState(queuePublish(prev, item, nextSeq(outbox)), 'queued', message(e));
180
- await save(outbox);
181
- return { state: 'queued', error: message(e) };
182
- }
183
- live();
184
- const { author, certState } = current;
185
- // 新发布盖过这个作者排着的待撤,免得旧的待撤之后又把新内容撤了。
186
- const queuedRetract = author ? retractKey(author, item.kind, item.id) : null, prevRetract = outbox[queuedRetract];
187
- if (canSkip(prev, canonicalHash({ body: item.body, audience: item.audience }), author)) return { state: 'synced', skipped: true, author };
188
- const entry = queuePublish(prev, item, nextSeq(outbox)), hold = holdState(entry, certState, (await readPolicy(d)).pausedKinds);
189
- live();
190
- if (hold) {
191
- outbox[key] = withState(entry, hold);
192
- delete outbox[queuedRetract];
193
- await save(outbox);
194
- return { state: hold, author };
195
- }
196
- // 先把新内容的意图落盘(旧的已同步标记随之作废),再签名;签名后落盘失败,磁盘上也不会还当旧内容已同步。
197
- outbox[key] = entry;
183
+ return mutate(() => publishItem(item));
184
+ }
185
+
186
+ // publish 的本体,须已在队里(mutate)。
187
+ async function publishItem(item) {
188
+ const d = stateDir(), key = entryKey(item.kind, item.id), outbox = await readOutbox(d), prev = outbox[key];
189
+ let current;
190
+ try { current = await accordState(); } catch (e) {
191
+ outbox[key] = withState(queuePublish(prev, item, nextSeq(outbox)), 'queued', message(e));
192
+ await save(outbox);
193
+ return { state: 'queued', error: message(e) };
194
+ }
195
+ live();
196
+ const { author, certState } = current;
197
+ // 新发布盖过这个作者排着的待撤,免得旧的待撤之后又把新内容撤了。
198
+ const queuedRetract = author ? retractKey(author, item.kind, item.id) : null, prevRetract = outbox[queuedRetract];
199
+ if (canSkip(prev, canonicalHash({ body: item.body, audience: item.audience }), author)) return { state: 'synced', skipped: true, author };
200
+ const entry = queuePublish(prev, item, nextSeq(outbox)), hold = holdState(entry, certState, (await readPolicy(d)).pausedKinds);
201
+ live();
202
+ if (hold) {
203
+ outbox[key] = withState(entry, hold);
198
204
  delete outbox[queuedRetract];
199
205
  await save(outbox);
200
- const done = await attempt(entry, author);
201
- if (done.state === 'error') {
202
- if (prev) outbox[key] = prev; else delete outbox[key];
203
- if (prevRetract) outbox[queuedRetract] = prevRetract;
204
- await persist(outbox);
205
- return { state: 'error', author, error: done.error };
206
- }
207
- outbox[key] = done.entry;
206
+ return { state: hold, author };
207
+ }
208
+ // 先把新内容的意图落盘(旧的已同步标记随之作废),再签名;签名后落盘失败,磁盘上也不会还当旧内容已同步。
209
+ outbox[key] = entry;
210
+ delete outbox[queuedRetract];
211
+ await save(outbox);
212
+ const done = await attempt(entry, author);
213
+ if (done.state === 'error') {
214
+ if (prev) outbox[key] = prev; else delete outbox[key];
215
+ if (prevRetract) outbox[queuedRetract] = prevRetract;
208
216
  await persist(outbox);
209
- if (done.state === 'synced') return { state: 'synced', author: done.entry.lastAuthor, ...(Number.isSafeInteger(done.result?.version) ? { version: done.result.version } : {}) };
210
- return { state: done.state, author, error: done.error };
217
+ return { state: 'error', author, error: done.error };
218
+ }
219
+ outbox[key] = done.entry;
220
+ await persist(outbox);
221
+ if (done.state === 'synced') return { state: 'synced', author: done.entry.lastAuthor, ...(Number.isSafeInteger(done.result?.version) ? { version: done.result.version } : {}) };
222
+ return { state: done.state, author, error: done.error };
223
+ }
224
+
225
+ // 同一 id 已有的 createdAt:待发条目 body 里的,或这位作者自己同步过的条目留下的 lastCreatedAt(别的作者同步的不算);
226
+ // 都没有才按当前作者查本机在 Accord 里的那条。查不了(读不到 Accord、查询失败)就报可重试的错,不拿新时间戳重签;查明没有才给 undefined。
227
+ async function existingCreatedAt(kind, id, current) {
228
+ const entry = (await readOutbox(stateDir()))[entryKey(kind, id)];
229
+ const known = entry?.body?.createdAt ?? (current?.author && entry?.lastAuthor === current.author ? entry.lastCreatedAt : undefined);
230
+ if (known !== undefined) return known;
231
+ let read;
232
+ try {
233
+ const { author } = current ?? await accordState();
234
+ if (!author) return undefined;
235
+ read = await coda.query(ACCORD, 'records', { kind, author, id, limit: 1 });
236
+ } catch (e) {
237
+ throw coda.error('unavailable', `查不到这个 id 已发过的内容,稍后重试:${message(e)}`, { effects: 'none' });
238
+ }
239
+ return (read?.records ?? []).find(record => record?.local === true && record.id === id)?.body?.createdAt;
240
+ }
241
+
242
+ // 私信与动态:清洗后走 publish 的同一条队(没有身份、证书过期一样排队、恢复后补发),结果带上最终用的 id。
243
+ function sendSocial(kind, input, normalize) {
244
+ return mutate(async () => {
245
+ let current = null;
246
+ try { current = await accordState(); } catch { /* 读不到身份:没给 id 的照样排队;给了 id 的下面查不了已有的 createdAt 就报错 */ }
247
+ const check = more => { try { return normalize(input, { selfAuthor: current?.author ?? null, now: Date.now(), ...more }); } catch (e) { throw invalid(message(e)); } };
248
+ let item = check({});
249
+ if (item.id !== undefined) {
250
+ const existing = await existingCreatedAt(kind, item.id, current);
251
+ if (existing !== undefined) item = check({ existingCreatedAt: existing });
252
+ }
253
+ live();
254
+ const id = item.id ?? globalThis.crypto.randomUUID();
255
+ return { ...await publishItem(checkPublish({ kind, id, body: item.body, audience: item.audience })), id };
211
256
  });
212
257
  }
258
+ const sendDm = input => sendSocial(DM_KIND, input, normalizeDmInput);
259
+ const postFeed = input => sendSocial(FEED_KIND, input, normalizeFeedInput);
260
+
261
+ // 可代签的社交名片:清洗后走 publish 的同一条队,没有身份或证书过期一样排队、恢复后补发。
262
+ function setCard(input) {
263
+ let body;
264
+ try { body = normalizeCardInput(input); } catch (e) { throw invalid(message(e)); }
265
+ return publish({ kind: CARD_KIND, id: PROFILE_ID, body, audience: ['public'] });
266
+ }
213
267
 
214
268
  function retract({ kind, id } = {}) {
215
269
  checkKind(kind);
@@ -302,13 +356,108 @@ export function createGateway(coda, dir) {
302
356
  return { author, certState, pausedKinds, pendingCount: Object.values(entries).filter(isPending).length, items };
303
357
  }
304
358
 
305
- const protocolHandlers = { friends, records, publish, retract, outbox };
359
+ // ---- 实时流 dm、feed ----
360
+ // 每条流一个 hub(内存里的投影与变化环缓冲)和它的订阅者;有订阅者、或新流连入时才翻页读 Accord,读全了才比对出增量推给订阅者,
361
+ // 读不全(截断、查询失败)不动 hub,留着上一份完整的投影。`ready`:hub 里已有过一份完整的投影。
362
+ // 私信的投影取决于本机作者:dm 的 `author` 是这份投影确认过的作者;换了作者就换一个新 hub(新 epoch、未就绪)、
363
+ // 关掉旧作者的订阅,读不出本机作者时也不算就绪,绝不把上一位作者的私信给新连入的流。
364
+ // 刷新排成一条队(和发布的队分开),先后两次刷新不会交错。
365
+ const hubs = {
366
+ dm: { kind: DM_KIND, hub: createStreamHub(), subs: new Set(), author: null, project: (records, author) => projectDmRecords(records, { selfAuthor: author }),
367
+ match: ({ peer }) => peer === undefined ? () => true : one => one.peer === peer },
368
+ feed: { kind: FEED_KIND, hub: createStreamHub(), subs: new Set(), project: records => projectFeedRecords(records),
369
+ match: ({ author }) => author === undefined ? () => true : one => one.author === author },
370
+ };
371
+ let pulling = Promise.resolve();
372
+ const pull = name => {
373
+ const run = pulling.then(async () => {
374
+ if (stopped) return;
375
+ const one = hubs[name];
376
+ let author = null;
377
+ if (name === 'dm') {
378
+ try { ({ author } = await accordState()); } catch (e) { one.ready = false; throw e; }
379
+ if (one.author !== author) {
380
+ Object.assign(one, { hub: createStreamHub(), ready: false, author });
381
+ for (const sub of [...one.subs]) sub.close();
382
+ }
383
+ }
384
+ const { records, truncated } = await pages({ kind: one.kind }, Infinity);
385
+ if (truncated) throw new Error(`${one.kind} 的记录翻页没有读全`);
386
+ if (stopped) return;
387
+ // hub 整份换上(投影、seq、历史)之后才算就绪、才通知订阅者。
388
+ const events = one.hub.applySnapshot(one.project(records, author));
389
+ one.ready = true;
390
+ for (const event of events)
391
+ for (const sub of one.subs) if (sub.match(subjectOf(event))) { sub.queue.push(event); sub.wake?.(); }
392
+ });
393
+ pulling = run.catch(() => {});
394
+ return run;
395
+ };
396
+ const pullWatched = () => { for (const [name, one] of Object.entries(hubs)) if (one.subs.size) pull(name).catch(() => {}); };
397
+
398
+ // 一条流的应答:先给快照(分片,或按 after 续上的增量),之后每次变化一帧。连入时读不出完整的投影:hub 已有完整的就用它,
399
+ // 还没有就在第一个字节之前报错,不发残缺的快照。调用方中止、取消应答体、网关停了都走同一个 cleanup:订阅、监听当场释放,
400
+ // 等着的 next 被唤醒结束。用手写的迭代器而不是 async generator:后者停在 yield 或 await 上时 return() 要排队等它。
401
+ // frames.write 的流外面再包一层:cleanup 当场取消里面那层(连同它的心跳定时器),哪怕首帧还没人读、正卡在背压上。
402
+ async function serveStream(name, { input = {}, signal }) {
403
+ live();
404
+ const one = hubs[name], match = one.match(input);
405
+ try { await pull(name); } catch (e) {
406
+ if (!one.ready) throw coda.error('unavailable', `读不出完整的${name === 'dm' ? '私信' : '动态'},稍后重连:${message(e)}`, { effects: 'none' });
407
+ }
408
+ live();
409
+ const start = one.hub.resume(input.after, match), epoch = one.hub.epoch;
410
+ const ahead = start.mode === 'snapshot' ? snapshotFrames(start.cursor, start.items) : start.events.map(event => frameOf(epoch, event));
411
+ let closed = false, outer = null;
412
+ const sub = { match, queue: [], wake: null };
413
+ const frames = {
414
+ async next() {
415
+ for (;;) {
416
+ if (closed) return { done: true, value: undefined };
417
+ if (ahead.length) return { done: false, value: ahead.shift() };
418
+ if (sub.queue.length) return { done: false, value: frameOf(epoch, sub.queue.shift()) };
419
+ await new Promise(resolve => { sub.wake = resolve; });
420
+ sub.wake = null;
421
+ }
422
+ },
423
+ async return() { cleanup(); return { done: true, value: undefined }; },
424
+ [Symbol.asyncIterator]() { return this; },
425
+ };
426
+ const reader = coda.frames.write(frames, { heartbeatMs: HEARTBEAT_MS }).getReader();
427
+ const cleanup = () => {
428
+ if (closed) return;
429
+ closed = true;
430
+ one.subs.delete(sub);
431
+ signal?.removeEventListener('abort', cleanup);
432
+ sub.wake?.();
433
+ reader.cancel().catch(() => {});
434
+ outer?.close();
435
+ };
436
+ const body = new ReadableStream({
437
+ start(controller) { outer = controller; },
438
+ async pull(controller) {
439
+ const { done, value } = await reader.read();
440
+ if (done) cleanup(); else if (!closed) controller.enqueue(value);
441
+ },
442
+ // 调用方取消了应答体:这一层已经关了,cleanup 不再去关它。
443
+ cancel() { outer = null; cleanup(); },
444
+ });
445
+ sub.close = cleanup;
446
+ one.subs.add(sub);
447
+ signal?.addEventListener('abort', cleanup);
448
+ if (signal?.aborted) cleanup();
449
+ return new Response(body,
450
+ { status: 200, headers: { 'content-type': 'application/x-ndjson', 'cache-control': 'no-store' } });
451
+ }
452
+
453
+ const protocolHandlers = { friends, records, publish, 'set-card': setCard, 'send-dm': sendDm, 'post-feed': postFeed, retract, outbox };
306
454
  for (const [name, fn] of Object.entries(protocolHandlers)) handles.push(coda.handle(SOCIAL, name, input => fn(input ?? {})));
307
455
 
308
456
  // 证书变成可用就冲洗待发队列;任何变化都刷新网关记录。
309
457
  const onChange = ({ type, entry } = {}) => {
310
458
  const ready = type !== 'DELETED' && certStateOf(entry) === 'active';
311
459
  serial(async () => { if (ready) await flushNow(); await refreshNow(); }).catch(() => {});
460
+ pullWatched();
312
461
  };
313
462
 
314
463
  return {
@@ -324,7 +473,13 @@ export function createGateway(coda, dir) {
324
473
  });
325
474
  },
326
475
  },
476
+ // 实时流此刻的订阅者数,`{ dm, feed }`。
477
+ subscriberCount: () => ({ dm: hubs.dm.subs.size, feed: hubs.feed.subs.size }),
327
478
  async start() {
479
+ for (const name of Object.keys(hubs)) {
480
+ const handle = await coda.stream(SOCIAL, name, (request, ctx) => serveStream(name, ctx));
481
+ if (stopped) handle?.dispose?.(); else handles.push(handle);
482
+ }
328
483
  try { watching = await coda.watch(ACCORD.kind, onChange, { id: ACCORD.id }); } catch { /* 没有 Accord:网关记录照样写 */ }
329
484
  await serial(refreshNow).catch(() => {});
330
485
  },
@@ -333,6 +488,7 @@ export function createGateway(coda, dir) {
333
488
  for (const handle of handles.splice(0)) handle?.dispose?.();
334
489
  watching?.dispose?.();
335
490
  watching = null;
491
+ for (const one of Object.values(hubs)) for (const sub of [...one.subs]) sub.close();
336
492
  },
337
493
  };
338
494
  }
package/lib/outbox.mjs CHANGED
@@ -73,7 +73,8 @@ export const canonicalHash = value => createHash('sha256').update(JSON.stringify
73
73
  // 不同作者对同一个 (kind, id) 排下的待撤互不相干,也不挡着对方撤自己的记录。
74
74
  // 每次写入发布或撤回的意图都领一个递增的整数 `seq`(落在条目里,不看系统时钟):冲洗按它的先后执行,并据它判断旧撤回是否已被更晚的发布取代。
75
75
  // 待发 { seq, kind, id, desired: 'publish', state: queued|paused|no_identity|needs_cert, body, audience, hash, lastError?, + 上次同步的元数据 }
76
- // 已同步 { seq, kind, id, desired: 'publish', state: 'synced', hash, audience, lastAuthor, lastSyncedHash, lastSyncedAt }(没有 body)
76
+ // 已同步 { seq, kind, id, desired: 'publish', state: 'synced', hash, audience, lastAuthor, lastSyncedHash, lastSyncedAt, lastCreatedAt? }(没有 body;
77
+ // lastCreatedAt 是 body.createdAt,同一 id 重试时沿用它,不必再查 Accord)
77
78
  // 待撤 { seq, kind, id, desired: 'retract', state: queued|no_identity|needs_cert, targetAuthor, lastError?, + 上次同步的元数据 }
78
79
  // targetAuthor 是排队时的作者:换了作者就不再替新作者撤,等原作者回来
79
80
  // 被拒 { …, state: 'error', lastError }:Accord 明确拒绝,不再自动重试;下一次发布或撤回同一条会替换它
@@ -107,9 +108,12 @@ export function withState(entry, state, error) {
107
108
  return { ...rest, state, ...(error ? { lastError: error } : {}) };
108
109
  }
109
110
 
110
- /** 发布成功:释放 body,只留 `{ seq, kind, id, desired, state: 'synced', hash, audience, lastAuthor, lastSyncedHash, lastSyncedAt }`。 */
111
- export const markSynced = (entry, author, now) =>
112
- ({ seq: entry.seq, kind: entry.kind, id: entry.id, desired: 'publish', state: 'synced', hash: entry.hash, audience: entry.audience, lastAuthor: author, lastSyncedHash: entry.hash, lastSyncedAt: now });
111
+ /** 发布成功:释放 body,只留 `{ seq, kind, id, desired, state: 'synced', hash, audience, lastAuthor, lastSyncedHash, lastSyncedAt }`,body 有合法的 createdAt 再留 `lastCreatedAt`。 */
112
+ export const markSynced = (entry, author, now) => {
113
+ const createdAt = entry.body?.createdAt;
114
+ return { seq: entry.seq, kind: entry.kind, id: entry.id, desired: 'publish', state: 'synced', hash: entry.hash, audience: entry.audience, lastAuthor: author, lastSyncedHash: entry.hash,
115
+ lastSyncedAt: now, ...(Number.isSafeInteger(createdAt) && createdAt >= 0 ? { lastCreatedAt: createdAt } : {}) };
116
+ };
113
117
 
114
118
  /** Accord 明确拒绝:不再留 body 和 audience,只留元数据与原因。 */
115
119
  export const markRejected = (entry, message) =>
@@ -0,0 +1,218 @@
1
+ // 私信 friends/dm 与好友动态 friends/feed 的纯逻辑:发布入参的清洗、Accord 记录的投影,以及实时流的变更集与游标。不碰 Coda,也不碰磁盘。
2
+ // 记录照旧由 coda/accord@1 签名与保存;这里只把一页页读回来的记录投影成规范项,并在内存里比对前后两份投影,算出增量帧。
3
+ import { normalizeContentPointer, readContentPointer } from './friends.mjs';
4
+
5
+ export const DM_KIND = 'friends/dm', FEED_KIND = 'friends/feed';
6
+ export const MAX_TEXT = 8000, MAX_MEDIA = 4, MAX_HISTORY = 500;
7
+ // 快照一帧的字节上限,远低于 readFrames 默认的一行 1 MiB:快照按它分片。
8
+ export const MAX_SNAPSHOT_FRAME_BYTES = 256 * 1024;
9
+ const MAX_ID = 200, MAX_ID_BYTES = 256, MAX_AUDIENCE = 500;
10
+ const AUTHOR = /^ed25519:[0-9a-f]{64}$/, AUDIENCE = /^(?:public|ed25519:[0-9a-f]{64})$/;
11
+ const CONTROL = /[\p{Cc}]/u;
12
+ const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
13
+ const CURSOR = new RegExp(`^(${UUID}):(0|[1-9][0-9]*)$`);
14
+
15
+ const fail = message => { throw new Error(message); };
16
+ const length = text => [...text].length;
17
+ const encoder = new TextEncoder();
18
+ const bytes = text => encoder.encode(text).length;
19
+ const isPlain = value => value !== null && typeof value === 'object' && !Array.isArray(value);
20
+ const isTime = value => Number.isSafeInteger(value) && value >= 0;
21
+ const validLabel = text => typeof text === 'string' && text.length > 0 && length(text) <= MAX_ID && !CONTROL.test(text);
22
+ export const isAuthor = value => typeof value === 'string' && AUTHOR.test(value);
23
+
24
+ // ---- 发布入参 ----
25
+
26
+ /**
27
+ * 可选的 id、replyTo:原样至多 200 个字符(与 schema 的 maxLength 同样按码点数)、UTF-8 至多 256 字节(与 Accord 一致)、
28
+ * 不含控制字符,去首尾空白后不能是空的;省略给 undefined(id 由调用方生成)。
29
+ */
30
+ function readLabel(value, name) {
31
+ if (value === undefined) return undefined;
32
+ if (typeof value !== 'string' || length(value) > MAX_ID || bytes(value) > MAX_ID_BYTES || CONTROL.test(value) || !value.trim())
33
+ fail(`${name} 须是 1–${MAX_ID} 个字符、UTF-8 至多 ${MAX_ID_BYTES} 字节的文本,不含控制字符`);
34
+ return value.trim();
35
+ }
36
+
37
+ /** text 原样至多 8000 个字(码点,与 schema 一致),再去首尾空白。 */
38
+ function readText(text) {
39
+ if (text === undefined) return '';
40
+ if (typeof text !== 'string') fail('text 须是文本');
41
+ if (length(text) > MAX_TEXT) fail(`text 最多 ${MAX_TEXT} 个字`);
42
+ return text.trim();
43
+ }
44
+
45
+ function readPointers(list, name) {
46
+ if (list === undefined) return [];
47
+ if (!Array.isArray(list) || !list.length || list.length > MAX_MEDIA) fail(`${name} 须是 1–${MAX_MEDIA} 项的数组`);
48
+ return list.map(normalizeContentPointer);
49
+ }
50
+
51
+ const createdAtOf = (existingCreatedAt, now) => {
52
+ const at = isTime(existingCreatedAt) ? existingCreatedAt : now;
53
+ if (!isTime(at)) fail('createdAt 须是非负整数');
54
+ return at;
55
+ };
56
+
57
+ /**
58
+ * 私信的入参 `{ to, id?, text?, attachments?, replyTo? }` → `{ id, to, audience: [to], body }`。只发给一个人,不能发给 public 或自己;
59
+ * text 与 attachments 不能都空。createdAt 先用同一 id 已有记录的(重试时内容不变,才能按幂等跳过),没有再取 now。
60
+ */
61
+ export function normalizeDmInput(input, { selfAuthor, existingCreatedAt, now = Date.now() } = {}) {
62
+ if (!isPlain(input)) fail('私信须是对象');
63
+ const { to } = input;
64
+ if (!isAuthor(to)) fail('to 须是一位好友的公钥 ed25519:<64 位小写十六进制>');
65
+ if (to === selfAuthor) fail('不能给自己发私信');
66
+ const id = readLabel(input.id, 'id'), text = readText(input.text), attachments = readPointers(input.attachments, 'attachments');
67
+ if (!text && !attachments.length) fail('私信的 text 与 attachments 不能都空');
68
+ const replyTo = readLabel(input.replyTo, 'replyTo'), createdAt = createdAtOf(existingCreatedAt, now);
69
+ return { id, to, audience: [to], body: { to, text, ...(attachments.length ? { attachments } : {}), ...(replyTo ? { replyTo } : {}), createdAt } };
70
+ }
71
+
72
+ /**
73
+ * 动态的入参 `{ id?, text?, media?, audience? }` → `{ id, audience, body }`。audience 省略是 `['public']`,写了须是 1–500 项、
74
+ * 每项 public 或公钥,去重;`[]` 不收(撤回走 retract)。text 与 media 不能都空;createdAt 同私信。
75
+ */
76
+ export function normalizeFeedInput(input, { existingCreatedAt, now = Date.now() } = {}) {
77
+ if (!isPlain(input)) fail('动态须是对象');
78
+ const id = readLabel(input.id, 'id'), text = readText(input.text), media = readPointers(input.media, 'media');
79
+ if (!text && !media.length) fail('动态的 text 与 media 不能都空');
80
+ const { audience = ['public'] } = input;
81
+ if (!Array.isArray(audience) || !audience.length || audience.length > MAX_AUDIENCE) fail(`audience 须是 1–${MAX_AUDIENCE} 项的数组;撤回用 retract`);
82
+ if (!audience.every(item => typeof item === 'string' && AUDIENCE.test(item))) fail("audience 每项须是 'public' 或 ed25519:<64 位小写十六进制>");
83
+ return { id, audience: [...new Set(audience)], body: { text, ...(media.length ? { media } : {}), createdAt: createdAtOf(existingCreatedAt, now) } };
84
+ }
85
+
86
+ // ---- 记录投影 ----
87
+
88
+ // 每个 (author, id) 只留 version 最大的一条:最新的是撤回(空 body)或畸形,整条就算没了,不回落到旧版本。
89
+ function latest(records) {
90
+ const top = new Map();
91
+ for (const record of records ?? []) {
92
+ if (!isPlain(record) || typeof record.author !== 'string' || typeof record.id !== 'string') continue;
93
+ const key = JSON.stringify([record.author, record.id]), version = Number.isSafeInteger(record.version) ? record.version : 0;
94
+ if (!top.has(key) || version > top.get(key).version) top.set(key, { record, version });
95
+ }
96
+ return [...top.values()];
97
+ }
98
+
99
+ // 外来正文:text 是至多 8000 字的文本(不合法当空),图片指针只留校验通过的、至多 4 个;两样都空、或 createdAt 不对就是畸形(null)。
100
+ function readBody(body, pointersKey) {
101
+ if (!isPlain(body) || !isTime(body.createdAt)) return null;
102
+ const text = typeof body.text === 'string' && length(body.text) <= MAX_TEXT ? body.text.trim() : '';
103
+ const pointers = Array.isArray(body[pointersKey]) ? body[pointersKey].map(readContentPointer).filter(Boolean).slice(0, MAX_MEDIA) : [];
104
+ return text || pointers.length ? { text, pointers, createdAt: body.createdAt } : null;
105
+ }
106
+
107
+ const compare = (a, b) => a.createdAt - b.createdAt || a.version - b.version || (a.author < b.author ? -1 : a.author > b.author ? 1 : 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
108
+
109
+ /**
110
+ * Accord 的 friends/dm 记录 → 私信规范项,按 (createdAt, version, author, id) 升序。只收真是本机与对方之间的:本机发出的须是本人签的、
111
+ * 发给别人;收到的须是别人签的、发给本人。`peer` 是对面那个人。
112
+ */
113
+ export function projectDmRecords(records, { selfAuthor } = {}) {
114
+ const items = [];
115
+ for (const { record, version } of latest(records)) {
116
+ const body = readBody(record.body, 'attachments'), to = record.body?.to;
117
+ if (!body || !isAuthor(to)) continue;
118
+ let peer;
119
+ if (record.local === true && record.author === selfAuthor && to !== selfAuthor) peer = to;
120
+ else if (record.local === false && record.author !== selfAuthor && to === selfAuthor) peer = record.author;
121
+ else continue;
122
+ const { replyTo } = record.body;
123
+ items.push({ author: record.author, id: record.id, version, local: record.local, peer, to, text: body.text, attachments: body.pointers,
124
+ ...(validLabel(replyTo) ? { replyTo } : {}), createdAt: body.createdAt });
125
+ }
126
+ return items.sort(compare);
127
+ }
128
+
129
+ /** Accord 的 friends/feed 记录 → 动态规范项,按 (createdAt, version, author, id) 降序(新的在前)。 */
130
+ export function projectFeedRecords(records) {
131
+ const items = [];
132
+ for (const { record, version } of latest(records)) {
133
+ const body = readBody(record.body, 'media');
134
+ if (body) items.push({ author: record.author, id: record.id, version, local: record.local === true, text: body.text, media: body.pointers, createdAt: body.createdAt });
135
+ }
136
+ return items.sort((a, b) => compare(b, a));
137
+ }
138
+
139
+ // ---- 变更集与游标 ----
140
+
141
+ /** 游标 `${epoch}:${seq}` → `{ epoch, seq }`;不合法给 null。 */
142
+ export function parseCursor(after) {
143
+ const match = typeof after === 'string' ? CURSOR.exec(after) : null;
144
+ if (!match) return null;
145
+ const seq = Number(match[2]);
146
+ return Number.isSafeInteger(seq) ? { epoch: match[1], seq } : null;
147
+ }
148
+
149
+ const keyOf = item => JSON.stringify([item.author, item.id]);
150
+ /** 一次变化里用来过滤的那一项:upsert 看它的 item,retract 看它自己(带 author、peer)。 */
151
+ export const subjectOf = event => event.type === 'upsert' ? event.item : event;
152
+ /** 变化 → 帧:seq 换成游标。 */
153
+ export const frameOf = (epoch, { seq, ...event }) => ({ ...event, cursor: `${epoch}:${seq}` });
154
+
155
+ /**
156
+ * 快照的帧:items 按序切成每帧 JSON 至多 `maxBytes` 字节的几片,`{ type: 'snapshot', cursor, items, more }`,还有后续分片的
157
+ * `more` 为 true,最后一片(空快照也有这一片,`items: []`)为 false;客户端收到 more 为 false 才把整份快照与游标落定。
158
+ */
159
+ export function snapshotFrames(cursor, items, maxBytes = MAX_SNAPSHOT_FRAME_BYTES) {
160
+ const empty = bytes(JSON.stringify({ type: 'snapshot', cursor, items: [], more: false })), chunks = [[]];
161
+ let size = empty;
162
+ for (const item of items) {
163
+ const one = bytes(JSON.stringify(item)) + 1;
164
+ if (chunks.at(-1).length && size + one > maxBytes) { chunks.push([]); size = empty; }
165
+ chunks.at(-1).push(item);
166
+ size += one;
167
+ }
168
+ return chunks.map((chunk, i) => ({ type: 'snapshot', cursor, items: chunk, more: i < chunks.length - 1 }));
169
+ }
170
+
171
+ /**
172
+ * 一条流的内存状态:启动时的 epoch、单调的 seq、当前投影(按 (author, id))、至多 `maxHistory` 条变化的环缓冲。
173
+ * `applySnapshot` 换上新一份投影并给出这次的变化;`resume(after, match)` 按游标给出续上的增量,续不上就给全量快照。
174
+ */
175
+ export function createStreamHub({ epoch = globalThis.crypto.randomUUID(), maxHistory = MAX_HISTORY } = {}) {
176
+ let seq = 0, current = new Map(), history = [];
177
+ const oldestSeq = () => history.length ? history[0].seq : seq + 1;
178
+ const cursor = () => `${epoch}:${seq}`;
179
+ return {
180
+ epoch,
181
+ get seq() { return seq; },
182
+ get oldestSeq() { return oldestSeq(); },
183
+ cursor,
184
+ items: () => [...current.values()],
185
+ // 先在局部算好这次的变化,最后一并换上投影、seq 与历史:中途出错,hub 还是原来那份。
186
+ applySnapshot(nextItems) {
187
+ const next = new Map(nextItems.map(item => [keyOf(item), item])), events = [];
188
+ let at = seq;
189
+ for (const [key, item] of current) {
190
+ if (!next.has(key)) events.push({ seq: ++at, type: 'retract', author: item.author, id: item.id, ...(item.peer ? { peer: item.peer } : {}) });
191
+ }
192
+ for (const [key, item] of next) {
193
+ const old = current.get(key);
194
+ if (old && old.version === item.version && JSON.stringify(old) === JSON.stringify(item)) continue;
195
+ // 同一条私信换了收件人:旧会话那边先撤掉,新会话再收到它。
196
+ if (old?.peer && old.peer !== item.peer) events.push({ seq: ++at, type: 'retract', author: old.author, id: old.id, peer: old.peer });
197
+ events.push({ seq: ++at, type: 'upsert', item });
198
+ }
199
+ // 不把 events 展开成实参(一次几十万条会超出实参上限):够多就只取最后 maxHistory 条,否则逐条追加再裁。
200
+ let kept;
201
+ if (events.length >= maxHistory) kept = events.slice(-maxHistory);
202
+ else {
203
+ kept = history.slice();
204
+ for (const event of events) kept.push(event);
205
+ if (kept.length > maxHistory) kept.splice(0, kept.length - maxHistory);
206
+ }
207
+ current = next;
208
+ seq = at;
209
+ history = kept;
210
+ return events;
211
+ },
212
+ resume(after, match = () => true) {
213
+ const at = parseCursor(after);
214
+ if (!at || at.epoch !== epoch || at.seq > seq || at.seq < oldestSeq() - 1) return { mode: 'snapshot', cursor: cursor(), items: [...current.values()].filter(match) };
215
+ return { mode: 'delta', cursor: cursor(), events: history.filter(event => event.seq > at.seq && match(subjectOf(event))) };
216
+ },
217
+ };
218
+ }
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "displayName": "好友",
5
5
  "description": "管理 Accord 身份、个人名片与熟人好友通道",
6
6
  "icon": { "symbol": "person.2.fill", "color": "blue" },
7
- "version": "0.2.0",
7
+ "version": "0.3.0",
8
8
  "categories": [
9
9
  "Skills 与工具"
10
10
  ],
@@ -40,7 +40,7 @@
40
40
  {
41
41
  "name": "friends/social@1",
42
42
  "title": "好友社交网关",
43
- "description": "业务无关的好友网关:读好友与好友分享的记录,向好友发布、撤回记录;签名与记录全部透传 coda/accord@1,没有身份或证书过期时在本机排队,恢复后自动补发。",
43
+ "description": "业务无关的好友网关:读好友与好友分享的记录,向好友发布、撤回记录,设置可代签的社交名片 friends/card,发私信 friends/dm、好友动态 friends/feed,并以 dm、feed 两条帧流实时跟随;签名与记录全部透传 coda/accord@1,没有身份或证书过期时在本机排队,恢复后自动补发。",
44
44
  "spec": {
45
45
  "type": "object",
46
46
  "properties": { "version": { "const": 1 } },
@@ -136,6 +136,145 @@
136
136
  "additionalProperties": false
137
137
  }
138
138
  },
139
+ "set-card": {
140
+ "idempotent": true,
141
+ "input": {
142
+ "type": "object",
143
+ "properties": {
144
+ "name": { "type": "string", "minLength": 1, "maxLength": 40 },
145
+ "emoji": { "type": "string", "maxLength": 8 },
146
+ "color": { "enum": ["blue", "orange", "green", "purple", "pink", "teal", "gray"] },
147
+ "avatar": {
148
+ "anyOf": [
149
+ {
150
+ "type": "object",
151
+ "description": "内容寻址的图片指针(BlobPointer):path 只收 content/<sha256>,sha256 须与 path 里的一致",
152
+ "properties": {
153
+ "owner": { "type": "string", "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" },
154
+ "path": { "type": "string", "pattern": "^content/[0-9a-f]{64}$" },
155
+ "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },
156
+ "mime": { "type": "string", "minLength": 1, "maxLength": 128 },
157
+ "size": { "type": "integer", "minimum": 0, "maximum": 5242880 },
158
+ "name": { "type": "string", "minLength": 1, "maxLength": 200 }
159
+ },
160
+ "required": ["owner", "path", "sha256"],
161
+ "additionalProperties": false
162
+ },
163
+ { "type": "null" }
164
+ ]
165
+ }
166
+ },
167
+ "required": ["name"],
168
+ "additionalProperties": false
169
+ },
170
+ "result": {
171
+ "type": "object",
172
+ "properties": {
173
+ "state": { "enum": ["synced", "queued", "paused", "no_identity", "needs_cert", "error"] },
174
+ "skipped": { "type": "boolean" },
175
+ "author": { "type": ["string", "null"] },
176
+ "version": { "type": "integer", "minimum": 0 },
177
+ "error": { "type": "string" }
178
+ },
179
+ "required": ["state"],
180
+ "additionalProperties": false
181
+ }
182
+ },
183
+ "send-dm": {
184
+ "idempotent": true,
185
+ "input": {
186
+ "type": "object",
187
+ "properties": {
188
+ "to": { "type": "string", "pattern": "^ed25519:[0-9a-f]{64}$" },
189
+ "id": { "type": "string", "minLength": 1, "maxLength": 200, "pattern": "^[^\\u0000-\\u001f\\u007f-\\u009f]*[^\\s\\u0000-\\u001f\\u007f-\\u009f][^\\u0000-\\u001f\\u007f-\\u009f]*$", "description": "至多 200 个字符且 UTF-8 至多 256 字节,不含控制字符,去首尾空白后不能为空;省略由网关生成 UUID" },
190
+ "text": { "type": "string", "maxLength": 8000, "description": "至多 8000 个字符(码点,按原样计,含首尾空白),发布时去首尾空白" },
191
+ "attachments": {
192
+ "type": "array",
193
+ "minItems": 1,
194
+ "maxItems": 4,
195
+ "items": {
196
+ "type": "object",
197
+ "description": "内容寻址的图片指针(BlobPointer):path 只收 content/<sha256>,sha256 须与 path 里的一致",
198
+ "properties": {
199
+ "owner": { "type": "string", "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" },
200
+ "path": { "type": "string", "pattern": "^content/[0-9a-f]{64}$" },
201
+ "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },
202
+ "mime": { "type": "string", "minLength": 1, "maxLength": 128 },
203
+ "size": { "type": "integer", "minimum": 0, "maximum": 5242880 },
204
+ "name": { "type": "string", "minLength": 1, "maxLength": 200 }
205
+ },
206
+ "required": ["owner", "path", "sha256"],
207
+ "additionalProperties": false
208
+ }
209
+ },
210
+ "replyTo": { "type": "string", "minLength": 1, "maxLength": 200, "pattern": "^[^\\u0000-\\u001f\\u007f-\\u009f]*[^\\s\\u0000-\\u001f\\u007f-\\u009f][^\\u0000-\\u001f\\u007f-\\u009f]*$", "description": "所回复私信的 id:与 id 同样至多 200 个字符且 UTF-8 至多 256 字节,不含控制字符" }
211
+ },
212
+ "required": ["to"],
213
+ "additionalProperties": false
214
+ },
215
+ "result": {
216
+ "type": "object",
217
+ "properties": {
218
+ "state": { "enum": ["synced", "queued", "paused", "no_identity", "needs_cert", "error"] },
219
+ "id": { "type": "string" },
220
+ "skipped": { "type": "boolean" },
221
+ "author": { "type": ["string", "null"] },
222
+ "version": { "type": "integer", "minimum": 0 },
223
+ "error": { "type": "string" }
224
+ },
225
+ "required": ["state"],
226
+ "additionalProperties": false
227
+ }
228
+ },
229
+ "post-feed": {
230
+ "idempotent": true,
231
+ "input": {
232
+ "type": "object",
233
+ "properties": {
234
+ "id": { "type": "string", "minLength": 1, "maxLength": 200, "pattern": "^[^\\u0000-\\u001f\\u007f-\\u009f]*[^\\s\\u0000-\\u001f\\u007f-\\u009f][^\\u0000-\\u001f\\u007f-\\u009f]*$", "description": "至多 200 个字符且 UTF-8 至多 256 字节,不含控制字符,去首尾空白后不能为空;省略由网关生成 UUID" },
235
+ "text": { "type": "string", "maxLength": 8000, "description": "至多 8000 个字符(码点,按原样计,含首尾空白),发布时去首尾空白" },
236
+ "media": {
237
+ "type": "array",
238
+ "minItems": 1,
239
+ "maxItems": 4,
240
+ "items": {
241
+ "type": "object",
242
+ "description": "内容寻址的图片指针(BlobPointer):path 只收 content/<sha256>,sha256 须与 path 里的一致",
243
+ "properties": {
244
+ "owner": { "type": "string", "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" },
245
+ "path": { "type": "string", "pattern": "^content/[0-9a-f]{64}$" },
246
+ "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },
247
+ "mime": { "type": "string", "minLength": 1, "maxLength": 128 },
248
+ "size": { "type": "integer", "minimum": 0, "maximum": 5242880 },
249
+ "name": { "type": "string", "minLength": 1, "maxLength": 200 }
250
+ },
251
+ "required": ["owner", "path", "sha256"],
252
+ "additionalProperties": false
253
+ }
254
+ },
255
+ "audience": {
256
+ "type": "array",
257
+ "items": { "type": "string", "pattern": "^(?:public|ed25519:[0-9a-f]{64})$" },
258
+ "minItems": 1,
259
+ "maxItems": 500
260
+ }
261
+ },
262
+ "additionalProperties": false
263
+ },
264
+ "result": {
265
+ "type": "object",
266
+ "properties": {
267
+ "state": { "enum": ["synced", "queued", "paused", "no_identity", "needs_cert", "error"] },
268
+ "id": { "type": "string" },
269
+ "skipped": { "type": "boolean" },
270
+ "author": { "type": ["string", "null"] },
271
+ "version": { "type": "integer", "minimum": 0 },
272
+ "error": { "type": "string" }
273
+ },
274
+ "required": ["state"],
275
+ "additionalProperties": false
276
+ }
277
+ },
139
278
  "retract": {
140
279
  "idempotent": true,
141
280
  "input": {
@@ -196,9 +335,37 @@
196
335
  }
197
336
  }
198
337
  },
338
+ "streams": {
339
+ "dm": {
340
+ "shape": "read",
341
+ "frames": true,
342
+ "description": "私信的实时帧流:首帧 { type: 'snapshot', cursor, items }(按 createdAt 升序),之后每次变化一帧 { type: 'upsert', cursor, item } 或 { type: 'retract', cursor, author, id, peer };peer 只看与这位好友的私信,after 给上次的 cursor 只补增量,续不上回到快照",
343
+ "input": {
344
+ "type": "object",
345
+ "properties": {
346
+ "peer": { "type": "string", "pattern": "^ed25519:[0-9a-f]{64}$" },
347
+ "after": { "type": "string", "minLength": 1, "maxLength": 128 }
348
+ },
349
+ "additionalProperties": false
350
+ }
351
+ },
352
+ "feed": {
353
+ "shape": "read",
354
+ "frames": true,
355
+ "description": "好友动态的实时帧流:首帧 { type: 'snapshot', cursor, items }(按 createdAt 降序),之后每次变化一帧 { type: 'upsert', cursor, item } 或 { type: 'retract', cursor, author, id };author 只看这一位的,after 给上次的 cursor 只补增量,续不上回到快照",
356
+ "input": {
357
+ "type": "object",
358
+ "properties": {
359
+ "author": { "type": "string", "pattern": "^ed25519:[0-9a-f]{64}$" },
360
+ "after": { "type": "string", "minLength": 1, "maxLength": 128 }
361
+ },
362
+ "additionalProperties": false
363
+ }
364
+ }
365
+ },
199
366
  "permissions": {
200
- "read": { "title": "查看好友列表与读取好友分享的记录", "read": true, "operations": ["friends", "records"] },
201
- "publish": { "title": "通过好友网关发布、撤回记录与查看待发队列", "operations": ["publish", "retract", "outbox"] }
367
+ "read": { "title": "查看好友列表、读取好友分享的记录与实时私信、动态", "read": true, "operations": ["friends", "records"], "streams": ["dm", "feed"] },
368
+ "publish": { "title": "通过好友网关发布、撤回记录、设置社交名片、发私信与动态、查看待发队列", "operations": ["publish", "set-card", "send-dm", "post-feed", "retract", "outbox"] }
202
369
  }
203
370
  }
204
371
  ],
package/view/app.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  // 好友页:本机 Accord 身份与名片、接受好友邀请、好友列表。Accord 的读写(coda/accord@1)都在这里按交互发起;
2
2
  // 备注只经模块存在本机。好友的昵称、备注、节点名等外来数据一律用 textContent / DOM API 渲染,不进 innerHTML。
3
3
  import { Bridge } from 'coda-view://lib/v1/bridge.js';
4
- import { COLORS, checked, mergeFriendRows, normalizeProfileInput, parseInvite, readProfileRecord, shortAuthor } from '../lib/friends.mjs';
4
+ import { CARD_KIND, COLORS, cardFallbackNotice, checked, mergeFriendRows, mergeProfileAndCard, normalizeProfileInput, parseInvite, readCardRecord, readProfileRecord,
5
+ shortAuthor } from '../lib/friends.mjs';
5
6
 
6
7
  const ACCORD = 'coda/accord@1', LOCAL = { kind: ACCORD, id: 'local' };
7
8
  const coda = window.coda, bridge = new Bridge();
@@ -19,7 +20,7 @@ const h = (tag, attrs = {}, ...children) => {
19
20
  return node;
20
21
  };
21
22
 
22
- const state = { author: null, friends: [], profiles: [], notes: {}, loaded: false, problem: null, editing: null, removing: null, busy: new Set(), notice: new Map() };
23
+ const state = { author: null, friends: [], profiles: [], cards: [], notes: {}, loaded: false, problem: null, editing: null, removing: null, busy: new Set(), notice: new Map() };
23
24
 
24
25
  // ---- 备注:经模块存在本机 ----
25
26
  const pendingReplies = new Map();
@@ -41,22 +42,25 @@ function ask(type, input = {}) {
41
42
 
42
43
  // ---- 读本机 Accord ----
43
44
  let reading = 0;
45
+ // profile 与 friends/card 各读各的:一种读不到或没有记录,不挡另一种。
44
46
  async function readProfiles() {
45
47
  const mine = ++reading;
46
- try {
47
- const { records } = await coda.query(LOCAL, 'records', { kind: 'profile', limit: 200 });
48
- if (mine !== reading) return;
49
- state.profiles = records;
50
- state.problem = null;
51
- if (!own.touched) loadOwn();
52
- } catch (e) { if (mine === reading) state.problem = `读不到好友名片:${e.message}`; }
48
+ const [profiles, cards] = await Promise.allSettled(['profile', CARD_KIND].map(kind => coda.query(LOCAL, 'records', { kind, limit: 200 })));
49
+ if (mine !== reading) return;
50
+ if (profiles.status === 'fulfilled') state.profiles = profiles.value?.records ?? [];
51
+ if (cards.status === 'fulfilled') state.cards = cards.value?.records ?? [];
52
+ const failed = [profiles, cards].find(read => read.status === 'rejected');
53
+ state.problem = failed ? `读不到好友名片:${failed.reason?.message ?? failed.reason}` : null;
54
+ if (!own.touched) loadOwn();
53
55
  draw();
54
56
  }
55
- const own = { touched: false, name: '', emoji: '', color: 'blue' };
57
+ const own = { touched: false, name: '', emoji: '', color: 'blue', avatar: undefined };
58
+ const latestOwn = (records, read) => records.map(read).filter(p => p && p.author === state.author).sort((a, b) => b.version - a.version)[0];
59
+ // 本机名片:与好友列表同一条合并规则(profile 写了的优先,缺的由 friends/card 补);头像随表单带着,重新发布不会把它丢掉或带回已清除的。
56
60
  function loadOwn() {
57
- const mine = state.profiles.map(readProfileRecord).filter(p => p && p.author === state.author).sort((a, b) => b.version - a.version)[0];
61
+ const mine = mergeProfileAndCard(latestOwn(state.profiles, readProfileRecord), latestOwn(state.cards, readCardRecord));
58
62
  if (!mine) return;
59
- Object.assign(own, { name: mine.name, emoji: mine.emoji ?? '', color: mine.color ?? 'blue' });
63
+ Object.assign(own, { name: mine.name, emoji: mine.emoji ?? '', color: mine.color ?? 'blue', avatar: mine.avatarPresent ? mine.avatar : undefined });
60
64
  syncOwnForm();
61
65
  }
62
66
 
@@ -99,8 +103,18 @@ async function publishProfile() {
99
103
  ownForm.button.disabled = true;
100
104
  say(ownForm.message, '正在发布…', 'progress');
101
105
  try {
102
- await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] });
103
- say(ownForm.message, '名片已发布,好友会看到它', 'ok');
106
+ try {
107
+ await coda.call(LOCAL, 'publish', { kind: 'profile', id: 'self', body, audience: ['public'] });
108
+ say(ownForm.message, '名片已发布,好友会看到它', 'ok');
109
+ } catch (e) {
110
+ // 绑定了代签证书时 profile 须由客户端根签,这里发不了:改发可代签的社交名片 friends/card,好友一样看得到。
111
+ if (e?.code !== 'forbidden') throw e;
112
+ await coda.call(LOCAL, 'publish', { kind: CARD_KIND, id: 'self', body, audience: ['public'] });
113
+ // 缓存的 state.profiles 可能还没读完或读失败了:现查一次本机作者的根签 profile,查不出来就不承诺。
114
+ let rooted = null;
115
+ try { rooted = ((await coda.query(LOCAL, 'records', { kind: 'profile', author: state.author, limit: 1 }))?.records ?? []).some(record => readProfileRecord(record)); } catch { /* 按没读出来提示 */ }
116
+ say(ownForm.message, cardFallbackNotice(rooted), 'ok');
117
+ }
104
118
  readProfiles();
105
119
  } catch (e) { say(ownForm.message, `没有发布成功:${e.message}`, 'error'); }
106
120
  ownForm.button.disabled = false;
@@ -114,8 +128,8 @@ async function copyKey() {
114
128
  // ---- 添加好友 ----
115
129
  const invite = {
116
130
  paste: h('textarea', { placeholder: '粘贴邀请:JSON、coda-friend:// 链接,或多行 control=… / authKey=…', autocomplete: 'off', spellcheck: 'false', oninput: parsePaste }),
117
- control: h('input', { type: 'text', autocomplete: 'off', spellcheck: 'false', placeholder: 'https://…' }),
118
- authKey: h('input', { type: 'password', autocomplete: 'off', spellcheck: 'false', placeholder: '入网码,提交后立即清空' }),
131
+ control: h('input', { type: 'text', autocomplete: 'off', spellcheck: 'false', placeholder: 'https://…', oninput: dropHidden }),
132
+ authKey: h('input', { type: 'password', autocomplete: 'off', spellcheck: 'false', placeholder: '入网码,提交后立即清空', oninput: dropHidden }),
119
133
  linkId: h('input', { type: 'text', autocomplete: 'off', placeholder: '留空自动生成' }),
120
134
  scope: h('input', { type: 'text', autocomplete: 'off', placeholder: '留空用本机空间' }),
121
135
  peerNode: h('input', { type: 'text', autocomplete: 'off', placeholder: '可选' }),
@@ -123,14 +137,17 @@ const invite = {
123
137
  button: h('button', { class: 'btn', type: 'button', onclick: submitInvite }, '接受邀请'),
124
138
  hidden: {},
125
139
  };
140
+ // hostname、peerPort 只随识别出的那份邀请:手改入网地址或入网码就是另一份邀请了,丢掉;改 linkId、scope、peerNode 不算。
141
+ function dropHidden() { invite.hidden = {}; }
126
142
  function parsePaste() {
143
+ invite.hidden = {};
127
144
  const text = invite.paste.value;
128
145
  if (!text.trim()) return say(invite.message, '', 'hint');
129
146
  try {
130
147
  const found = parseInvite(text);
131
148
  for (const name of ['control', 'authKey', 'scope', 'peerNode']) if (found[name]) invite[name].value = found[name];
132
149
  if (found.linkId && !/^f-[0-9a-f]{8}$/.test(found.linkId)) invite.linkId.value = found.linkId;
133
- invite.hidden.hostname = found.hostname ?? '';
150
+ invite.hidden = { hostname: found.hostname ?? '', peerPort: found.peerPort };
134
151
  say(invite.message, '已识别邀请,核对后点「接受邀请」', 'ok');
135
152
  } catch (e) { say(invite.message, e.message, 'error'); }
136
153
  }
@@ -142,7 +159,7 @@ async function submitInvite() {
142
159
  let input;
143
160
  try {
144
161
  input = checked({ control: invite.control.value, authKey: invite.authKey.value, linkId: invite.linkId.value, scope: invite.scope.value,
145
- peerNode: invite.peerNode.value, hostname: invite.hidden.hostname });
162
+ peerNode: invite.peerNode.value, hostname: invite.hidden.hostname, peerPort: invite.hidden.peerPort });
146
163
  } catch (e) {
147
164
  // 只填了粘贴区、还没有识别出来:再试着从粘贴区解析一次。
148
165
  try { input = parseInvite(invite.paste.value); } catch { return say(invite.message, e.message, 'error'); }
@@ -168,7 +185,7 @@ async function submitInvite() {
168
185
  // ---- 好友列表 ----
169
186
  const list = h('div');
170
187
  const countBadge = h('span', { class: 'count' });
171
- function rows() { return mergeFriendRows({ friends: state.friends, profiles: state.profiles, notes: state.notes }); }
188
+ function rows() { return mergeFriendRows({ friends: state.friends, profiles: state.profiles, cards: state.cards, notes: state.notes }); }
172
189
 
173
190
  async function handshake(row) {
174
191
  state.busy.add(row.node); state.notice.set(row.node, { kind: 'progress', text: '正在互认…' }); draw();