@coda-console/friends 0.5.0 → 0.7.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/lib/gateway.mjs CHANGED
@@ -1,24 +1,22 @@
1
1
  // 抽象社交网关:实现 friends/social@1。业务无关——只认 kind、id、body;签名写入与记录查询全部透传 coda/accord@1,
2
2
  // 自己不建第二份目录库,只在 outbox.json 里留还没发出去的 body(同步成功即释放)。所有会写盘、会外发的动作排成一条队,
3
3
  // 发布、撤回、证书变化引起的冲洗互不交叉。
4
- import { CARD_KIND, PROFILE_ID, PROFILE_KIND, mergeFriendRows, normalizeCardInput, statusOf } from './friends.mjs';
5
- import { readNotes } from './notes.mjs';
6
- import { canSkip, canonicalHash, certStateOf, checkId, checkKind, checkPublish, entryKey, holdState, keyOf, retractKey, invalid, isPending, markRejected, markSynced,
4
+ import { mergeFriendRows, statusOf } from './friends.mjs';
5
+ import { MAX_BODY_BYTES, canSkip, canonicalHash, certStateOf, checkId, checkKind, checkPublish, entryKey, holdState, keyOf, retractKey, invalid, isPending, markRejected, markSynced,
7
6
  nextSeq, queuePublish, queueRetract, readOutbox, withState, writeOutbox } from './outbox.mjs';
8
7
  import { readPolicy, setKindPaused } from './policy.mjs';
9
- import { DM_KIND, FEED_KIND, createStreamHub, frameOf, normalizeDmInput, normalizeFeedInput, projectDmRecords, projectFeedRecords, snapshotFrames, subjectOf } from './social-streams.mjs';
8
+ import { KIND_CALL, RPC_KINDS, isAuthor, isRpcKind, machineOf, senderField, signerOf } from './rpc-format.mjs';
10
9
 
11
10
  const ACCORD = { kind: 'coda/accord@1', id: 'local' };
12
11
  const SOCIAL = 'friends/social@1';
13
12
  const MAX_PAGES = 50;
14
- const HEARTBEAT_MS = 30_000;
15
13
  const REJECTED = new Set(['invalid_input', 'forbidden']);
16
14
  const message = e => String(e?.message ?? e);
17
15
  const interrupted = effects => Object.assign(new Error('好友网关已停止'), { code: 'interrupted', effects });
18
16
 
19
17
  export function createGateway(coda, dir) {
20
18
  let stopped = false, watching = null, chain = Promise.resolve();
21
- const handles = [];
19
+ const handles = [], accordListeners = new Set();
22
20
  const stateDir = () => {
23
21
  if (!dir) throw new Error('这台机器没有插件状态目录,网关的待发队列存不下');
24
22
  return dir;
@@ -40,19 +38,20 @@ export function createGateway(coda, dir) {
40
38
  return { accord, author: accord?.spec?.author ?? null, certState: certStateOf(accord) };
41
39
  }
42
40
 
43
- // 翻页读 coda/accord@1 的记录,至多 `maxPages` 页;cursor 重复就停,不会原地打转。
41
+ // 翻页读 coda/accord@1 的记录,至多 `maxPages` 页;cursor 重复就停,不会原地打转。`input.cursor` 给了就从那一页续读。
42
+ // 页数用完还没读全时带 `nextCursor`,下次从那里接着读;游标缺失或重复(续不上)时没有。
44
43
  async function pages(input, maxPages = MAX_PAGES) {
45
44
  const records = [], seen = new Set();
46
- let cursor;
45
+ let cursor = input.cursor;
47
46
  for (let page = 0; page < maxPages; page++) {
48
47
  const read = await coda.query(ACCORD, 'records', { ...input, limit: 200, ...(cursor ? { cursor } : {}) });
49
48
  records.push(...(read?.records ?? []));
50
49
  cursor = read?.nextCursor;
51
50
  if (!read?.truncated) return { records, truncated: false };
52
- if (!cursor || seen.has(cursor)) break;
51
+ if (!cursor || seen.has(cursor)) return { records, truncated: true };
53
52
  seen.add(cursor);
54
53
  }
55
- return { records, truncated: true };
54
+ return { records, truncated: true, nextCursor: cursor };
56
55
  }
57
56
 
58
57
  // 本机在 Accord 里有没有这条记录。
@@ -64,11 +63,6 @@ export function createGateway(coda, dir) {
64
63
  // 把一条待发或待撤的条目交给 coda/accord@1 发出去(撤回是 body 为空、audience 为空的发布)。
65
64
  async function attempt(entry, author) {
66
65
  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
- }
72
66
  const input = entry.desired === 'publish' ? { kind: entry.kind, id: entry.id, body: entry.body, audience: entry.audience }
73
67
  : { kind: entry.kind, id: entry.id, body: {}, audience: [] };
74
68
  try {
@@ -81,9 +75,16 @@ export function createGateway(coda, dir) {
81
75
  }
82
76
  }
83
77
 
78
+ // 读出待发队列;旧版残留的保留类型条目(如 friends/card、升级前入队的 friends/rpc-*)已被读表丢掉,这里把清理落盘,之后不再补发,也不挡着别的条目。
79
+ async function purgeReserved() {
80
+ const outbox = await readOutbox(stateDir());
81
+ if (outbox.dropped) await persist(outbox);
82
+ return outbox;
83
+ }
84
+
84
85
  // 冲洗:能发的待发、待撤条目发出去;证书不对或 kind 暂停的只更新状态。
85
86
  async function flushNow() {
86
- const d = stateDir(), outbox = await readOutbox(d);
87
+ const d = stateDir(), outbox = await purgeReserved();
87
88
  if (!Object.values(outbox).some(isPending)) return;
88
89
  const [{ author, certState }, { pausedKinds }] = await Promise.all([accordState(), readPolicy(d)]);
89
90
  let changed = false;
@@ -157,22 +158,19 @@ export function createGateway(coda, dir) {
157
158
  if (!stopped) await coda.put({ kind: SOCIAL, key: 'local' }, { spec: { version: 1 }, status });
158
159
  } catch { /* 状态记录下一次动作会再写 */ }
159
160
  }
160
- const mutate = work => serial(async () => { try { return await work(); } finally { await refreshNow(); pullWatched(); } });
161
+ const mutate = work => serial(async () => { try { return await work(); } finally { await refreshNow(); } });
161
162
 
162
163
  // ---- friends/social@1 的操作 ----
163
164
 
164
165
  async function friends({ includePending = false } = {}) {
165
166
  const { accord, author, certState } = await accordState();
166
167
  const list = Array.isArray(accord?.status?.friends) ? accord.status.friends : [];
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];
169
- const notes = dir ? await readNotes(dir) : {};
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 };
168
+ return { selfAuthor: author, certState, friends: mergeFriendRows(list).filter(row => includePending || row.status === 'bound') };
172
169
  }
173
170
 
174
171
  function records({ kind, author, id, limit, cursor, includeAudience }) {
175
172
  if (kind === 'binding') throw invalid('kind「binding」是保留类型,网关不读它');
173
+ if (isRpcKind(kind)) throw invalid(`kind「${kind}」是保留类型,网关不读它`);
176
174
  if (id !== undefined) checkId(id, { query: true });
177
175
  return coda.query(ACCORD, 'records', { kind, ...(author === undefined ? {} : { author }), ...(id === undefined ? {} : { id }),
178
176
  ...(limit === undefined ? {} : { limit }), ...(cursor === undefined ? {} : { cursor }), ...(includeAudience === undefined ? {} : { includeAudience }) });
@@ -222,49 +220,6 @@ export function createGateway(coda, dir) {
222
220
  return { state: done.state, author, error: done.error };
223
221
  }
224
222
 
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 };
256
- });
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
- }
267
-
268
223
  function retract({ kind, id } = {}) {
269
224
  checkKind(kind);
270
225
  if (id !== undefined) checkId(id);
@@ -356,108 +311,66 @@ export function createGateway(coda, dir) {
356
311
  return { author, certState, pausedKinds, pendingCount: Object.values(entries).filter(isPending).length, items };
357
312
  }
358
313
 
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(() => {}); };
314
+ // ---- 内部签名入口 ----
315
+ // 只给好友插件自己的持有方、调用方用,不登记成 friends/social@1 的操作、也不经 coda self:签 friends/rpc-grant、rpc-call、rpc-answer。
316
+ // 受众必须是单人;发送方取自正文(grant、answer 是 holder,call 是 caller),先与本机此刻该署的作者核对,不符当场失败;符合就把它作为
317
+ // expectAuthor 传给 coda/accord@1.publish,实际署名的作者不符 Accord 拒签;不进待发队列。
318
+ // 该署谁按种类分(signingAs):
319
+ // - 授权记录与回答是持有方发的,持有方始终以机器出现:带 `signer: "machine"` 用本机机器钥匙签,不看有没有绑个人身份、证书是否有效;
320
+ // - 调用请求署本机此刻的作者(signerOf):机器作者(没绑个人身份)用机器钥匙签,不看证书;个人作者的证书不是 active(已过期、未生效)当场失败,什么也不发。
321
+ async function signingAs(kind) {
322
+ const { accord } = await accordState();
323
+ live();
324
+ if (kind === KIND_CALL) return signerOf(accord);
325
+ const machine = machineOf(accord);
326
+ return { author: machine, canSign: machine !== null, signer: 'machine' };
327
+ }
328
+ const missing = kind => kind === KIND_CALL ? '本机没有可用的签名证书' : '读不出本机的机器钥匙';
397
329
 
398
- // 一条流的应答:先给快照(分片,或按 after 续上的增量),之后每次变化一帧。连入时读不出完整的投影:hub 已有完整的就用它,
399
- // 还没有就在第一个字节之前报错,不发残缺的快照。调用方中止、取消应答体、网关停了都走同一个 cleanup:订阅、监听当场释放,
400
- // 等着的 next 被唤醒结束。用手写的迭代器而不是 async generator:后者停在 yield 或 await 上时 return() 要排队等它。
401
- // frames.write 的流外面再包一层:cleanup 当场取消里面那层(连同它的心跳定时器),哪怕首帧还没人读、正卡在背压上。
402
- async function serveStream(name, { input = {}, signal }) {
330
+ // `beforePublish`(可省):读完签名身份、真正发布之前最后调一次,它抛错就什么也不发(调用方在这里看取消与期限)。
331
+ async function signRpc({ kind, id, body, audience } = {}, { beforePublish } = {}) {
403
332
  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
- }
333
+ if (!RPC_KINDS.includes(kind)) throw invalid(`只能签 ${RPC_KINDS.join('、')}`);
334
+ checkId(id);
335
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw invalid('body 须是对象');
336
+ if (Buffer.byteLength(JSON.stringify(body)) > MAX_BODY_BYTES) throw invalid(`body 最多 ${MAX_BODY_BYTES} 字节`);
337
+ if (!Array.isArray(audience) || audience.length !== 1 || !isAuthor(audience[0])) throw invalid('audience 须恰好是一位好友的公钥');
338
+ const sender = body[senderField(kind)];
339
+ if (!isAuthor(sender)) throw invalid(`body.${senderField(kind)} 须写明发送方的公钥`);
340
+ const { author, canSign, signer } = await signingAs(kind);
341
+ if (!canSign) throw coda.error('invalid_state', `${missing(kind)},好友调用的记录没有发出`, { effects: 'none' });
342
+ if (author !== sender) throw coda.error('invalid_state', '本机此刻该署的作者不是这条记录写的发送方,好友调用的记录没有发出', { effects: 'none' });
343
+ beforePublish?.();
344
+ return coda.call(ACCORD, 'publish', { kind, id, body, audience, ...(signer ? { signer } : {}), expectAuthor: sender });
345
+ }
346
+
347
+ // 撤回同一入口签过的一条:同一种类、同一 id,正文为空、受众为空。`author` 是这条该署的作者(授权记录与回答是本机机器钥匙,
348
+ // 调用请求是本机此刻的作者),作为 expectAuthor 传下去;只撤这个作者署名的、Accord 里还在的记录:没有就给 `{ state: 'absent' }`,
349
+ // 不为从没发过的 id 生成墓碑。签不了(见 signRpc)、或此刻该署的不是 `author`,当场失败(invalid_state),什么也不发。
350
+ async function retractRpc({ kind, id, author } = {}) {
408
351
  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' } });
352
+ if (!RPC_KINDS.includes(kind)) throw invalid(`只能撤 ${RPC_KINDS.join('、')}`);
353
+ checkId(id);
354
+ if (!isAuthor(author)) throw invalid('author 须是本机此刻应署的作者');
355
+ const current = await signingAs(kind);
356
+ if (!current.canSign) throw coda.error('invalid_state', `${missing(kind)},好友调用的记录没有撤回`, { effects: 'none' });
357
+ if (current.author !== author) throw coda.error('invalid_state', '本机此刻该署的作者不是这条记录的作者,好友调用的记录没有撤回', { effects: 'none' });
358
+ const read = await coda.query(ACCORD, 'records', { kind, author, id, limit: 1 });
359
+ const held = (read?.records ?? []).some(record => record?.local === true && record.author === author && record.id === id && Object.keys(record.body ?? {}).length > 0);
360
+ live();
361
+ if (!held) return { state: 'absent' };
362
+ const result = await coda.call(ACCORD, 'publish', { kind, id, body: {}, audience: [], ...(current.signer ? { signer: current.signer } : {}), expectAuthor: author });
363
+ return { state: 'retracted', ...(Number.isSafeInteger(result?.version) ? { version: result.version } : {}) };
451
364
  }
452
365
 
453
- const protocolHandlers = { friends, records, publish, 'set-card': setCard, 'send-dm': sendDm, 'post-feed': postFeed, retract, outbox };
366
+ const protocolHandlers = { friends, records, publish, retract, outbox };
454
367
  for (const [name, fn] of Object.entries(protocolHandlers)) handles.push(coda.handle(SOCIAL, name, input => fn(input ?? {})));
455
368
 
456
369
  // 证书变成可用就冲洗待发队列;任何变化都刷新网关记录。
457
370
  const onChange = ({ type, entry } = {}) => {
458
371
  const ready = type !== 'DELETED' && certStateOf(entry) === 'active';
459
372
  serial(async () => { if (ready) await flushNow(); await refreshNow(); }).catch(() => {});
460
- pullWatched();
373
+ for (const listener of accordListeners) { try { listener({ type, entry }); } catch { /* 听的人出错不影响网关 */ } }
461
374
  };
462
375
 
463
376
  return {
@@ -473,13 +386,14 @@ export function createGateway(coda, dir) {
473
386
  });
474
387
  },
475
388
  },
476
- // 实时流此刻的订阅者数,`{ dm, feed }`。
477
- subscriberCount: () => ({ dm: hubs.dm.subs.size, feed: hubs.feed.subs.size }),
389
+ // 内部签名、撤回入口,见上;不对外登记。
390
+ signRpc, retractRpc,
391
+ // 翻页读 Accord 记录(见上),持有方扫请求用。
392
+ pages,
393
+ // 本机 Accord 记录的变化(网关已在 watch 它),转告给持有方等内部的听众;给回 dispose。
394
+ onAccord(listener) { accordListeners.add(listener); return { dispose: () => accordListeners.delete(listener) }; },
478
395
  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
- }
396
+ if (dir) await serial(purgeReserved).catch(() => {});
483
397
  try { watching = await coda.watch(ACCORD.kind, onChange, { id: ACCORD.id }); } catch { /* 没有 Accord:网关记录照样写 */ }
484
398
  await serial(refreshNow).catch(() => {});
485
399
  },
@@ -488,7 +402,7 @@ export function createGateway(coda, dir) {
488
402
  for (const handle of handles.splice(0)) handle?.dispose?.();
489
403
  watching?.dispose?.();
490
404
  watching = null;
491
- for (const one of Object.values(hubs)) for (const sub of [...one.subs]) sub.close();
405
+ accordListeners.clear();
492
406
  },
493
407
  };
494
408
  }
@@ -0,0 +1,43 @@
1
+ // 由 Accord 公钥派生展示昵称(算法见 coda#3040):浏览器与 Node 通用,只用纯 JS 与 Uint8Array,不碰 Buffer 或 node:*。
2
+
3
+ const AUTHOR = /^ed25519:([0-9a-f]{64})$/;
4
+ const GROUPS = 36;
5
+
6
+ /** 密钥的短码:`ed25519:` 之后的前 8 位(没有就空串)。 */
7
+ export function shortAuthor(author) {
8
+ const match = AUTHOR.exec(author ?? '');
9
+ return match ? match[1].slice(0, 8) : '';
10
+ }
11
+
12
+ /**
13
+ * 32 字节公钥的昵称:256 位从第 0 字节最高位起每 7 位一组,至多 36 组。0–77 是字母(v % 26),78–87 是数字,
14
+ * 88–127 是结束符:已有不足 2 位时跳过,够 2 位就结束。读完仍不足 2 位给空串。
15
+ */
16
+ export function nicknameOf(key) {
17
+ let name = '';
18
+ for (let group = 0; group < GROUPS; group++) {
19
+ let v = 0;
20
+ for (let bit = group * 7; bit < group * 7 + 7; bit++) v = (v << 1) | ((key[bit >> 3] >> (7 - (bit & 7))) & 1);
21
+ if (v < 78) name += String.fromCharCode(97 + (v % 26));
22
+ else if (v < 88) name += String(v - 78);
23
+ else if (name.length >= 2) return name;
24
+ }
25
+ return name.length >= 2 ? name : '';
26
+ }
27
+
28
+ /** 32 字节公钥按大端无符号整数转成十进制,左侧补零到 78 位。 */
29
+ export const tailOf = key => BigInt(`0x${[...key].map(byte => byte.toString(16).padStart(2, '0')).join('')}`).toString().padStart(78, '0');
30
+
31
+ /**
32
+ * 好友与本机身份的展示名:合法公钥且解得出昵称给 `昵称 #尾号`(尾号是 tail 的末 4 位);合法公钥解不出昵称给公钥短码;
33
+ * 没有合法公钥(如待互认的好友)给 fallbackNode。
34
+ */
35
+ export function identityTitle(author, fallbackNode = '') {
36
+ const hex = AUTHOR.exec(author ?? '')?.[1];
37
+ if (hex) {
38
+ const key = Uint8Array.from({ length: 32 }, (_, i) => parseInt(hex.slice(i * 2, i * 2 + 2), 16));
39
+ const name = nicknameOf(key);
40
+ return name ? `${name} #${tailOf(key).slice(-4)}` : shortAuthor(author);
41
+ }
42
+ return fallbackNode;
43
+ }
package/lib/outbox.mjs CHANGED
@@ -3,9 +3,14 @@
3
3
  // 同步成功就释放 body,只留去重用的轻量元数据;撤回完成就删掉条目。
4
4
  import { createHash } from 'node:crypto';
5
5
  import { readJson, writeJson } from './json-file.mjs';
6
+ import { isRpcKind } from './rpc-format.mjs';
6
7
 
7
- /** 网关不替业务发布、撤回的类型:好友关系、名片等 Accord 自己的记录。 */
8
- export const RESERVED_KINDS = new Set(['binding', 'profile', 'friends', 'coda/profile', 'coda/friends']);
8
+ /**
9
+ * 网关不替业务发布、撤回的类型:好友关系、名片等 Accord 自己的记录;friends/card 是已下线的旧名片,封住旧写路径。
10
+ * 另有整个 `friends/rpc-` 前缀(按前缀判,见 `isRpcKind`),只有网关的内部入口能签。
11
+ */
12
+ export const RESERVED_KINDS = new Set(['binding', 'profile', 'friends', 'coda/profile', 'coda/friends', 'friends/card']);
13
+ const isReserved = kind => RESERVED_KINDS.has(kind) || isRpcKind(kind);
9
14
  export const MAX_ID_CHARS = 200, MAX_ID_BYTES = 256, MAX_BODY_BYTES = 65536, MAX_AUDIENCE = 500;
10
15
  const KIND = /^[a-z][a-z0-9-]{0,63}(?:\/[a-z][a-z0-9-]{0,63})?$/;
11
16
  const AUDIENCE = /^(?:public|ed25519:[0-9a-f]{64})$/;
@@ -17,12 +22,12 @@ const isPlain = value => {
17
22
  return proto === Object.prototype || proto === null;
18
23
  };
19
24
 
20
- export const validKind = kind => typeof kind === 'string' && KIND.test(kind) && !RESERVED_KINDS.has(kind);
25
+ export const validKind = kind => typeof kind === 'string' && KIND.test(kind) && !isReserved(kind);
21
26
 
22
27
  /** kind 须符合 Accord 的格式,且不是保留类型。 */
23
28
  export function checkKind(kind) {
24
29
  if (typeof kind !== 'string' || !KIND.test(kind)) throw invalid('kind 须是小写字母开头的 name 或 ns/name(只含小写字母、数字、连字符,各段最长 64 位)');
25
- if (RESERVED_KINDS.has(kind)) throw invalid(`kind「${kind}」是保留类型,网关不发布也不撤回它`);
30
+ if (isReserved(kind)) throw invalid(`kind「${kind}」是保留类型,网关不发布也不撤回它`);
26
31
  return kind;
27
32
  }
28
33
 
@@ -62,8 +67,7 @@ export const canonicalHash = value => createHash('sha256').update(JSON.stringify
62
67
  // 不同作者对同一个 (kind, id) 排下的待撤互不相干,也不挡着对方撤自己的记录。
63
68
  // 每次写入发布或撤回的意图都领一个递增的整数 `seq`(落在条目里,不看系统时钟):冲洗按它的先后执行,并据它判断旧撤回是否已被更晚的发布取代。
64
69
  // 待发 { seq, kind, id, desired: 'publish', state: queued|paused|no_identity|needs_cert, body, audience, hash, lastError?, + 上次同步的元数据 }
65
- // 已同步 { seq, kind, id, desired: 'publish', state: 'synced', hash, audience, lastAuthor, lastSyncedHash, lastSyncedAt, lastCreatedAt? }(没有 body;
66
- // lastCreatedAt 是 body.createdAt,同一 id 重试时沿用它,不必再查 Accord)
70
+ // 已同步 { seq, kind, id, desired: 'publish', state: 'synced', hash, audience, lastAuthor, lastSyncedHash, lastSyncedAt }(没有 body)
67
71
  // 待撤 { seq, kind, id, desired: 'retract', state: queued|no_identity|needs_cert, targetAuthor, lastError?, + 上次同步的元数据 }
68
72
  // targetAuthor 是排队时的作者:换了作者就不再替新作者撤,等原作者回来
69
73
  // 被拒 { …, state: 'error', lastError }:Accord 明确拒绝,不再自动重试;下一次发布或撤回同一条会替换它
@@ -97,12 +101,10 @@ export function withState(entry, state, error) {
97
101
  return { ...rest, state, ...(error ? { lastError: error } : {}) };
98
102
  }
99
103
 
100
- /** 发布成功:释放 body,只留 `{ seq, kind, id, desired, state: 'synced', hash, audience, lastAuthor, lastSyncedHash, lastSyncedAt }`,body 有合法的 createdAt 再留 `lastCreatedAt`。 */
101
- export const markSynced = (entry, author, now) => {
102
- const createdAt = entry.body?.createdAt;
103
- 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,
104
- lastSyncedAt: now, ...(Number.isSafeInteger(createdAt) && createdAt >= 0 ? { lastCreatedAt: createdAt } : {}) };
105
- };
104
+ /** 发布成功:释放 body,只留 `{ seq, kind, id, desired, state: 'synced', hash, audience, lastAuthor, lastSyncedHash, lastSyncedAt }`。 */
105
+ export const markSynced = (entry, author, now) =>
106
+ ({ seq: entry.seq, kind: entry.kind, id: entry.id, desired: 'publish', state: 'synced', hash: entry.hash, audience: entry.audience, lastAuthor: author, lastSyncedHash: entry.hash,
107
+ lastSyncedAt: now });
106
108
 
107
109
  /** Accord 明确拒绝:不再留 body 和 audience,只留元数据与原因。 */
108
110
  export const markRejected = (entry, message) =>
@@ -118,16 +120,21 @@ export function holdState(entry, certState, pausedKinds) {
118
120
 
119
121
  /**
120
122
  * 读出整张表 `{ 键: 条目 }`(磁盘上是 `{ seq, entries }`,旧版是直接平铺的条目);键按条目内容重新规范(兼容旧键名),
121
- * 缺失、损坏、条目不成样子的都丢掉。序号计数器取顶层 `seq` 与现存条目最大序号中较大的。
123
+ * 缺失、损坏、条目不成样子的都丢掉;保留类型(含旧版残留的 friends/card 与升级前入队的 friends/rpc-*)的条目也丢掉,丢了的个数记在表上不可枚举的 `dropped`,
124
+ * 由冲洗落盘清理。序号计数器取顶层 `seq` 与现存条目最大序号中较大的。
122
125
  */
123
126
  export async function readOutbox(dir) {
124
127
  const parsed = await readJson(dir, 'outbox.json'), entries = withSeq({}, 0);
125
128
  if (!isPlain(parsed)) return entries;
129
+ let dropped = 0;
126
130
  const stored = isPlain(parsed.entries) ? parsed.entries : parsed;
127
131
  for (const entry of Object.values(stored)) {
128
132
  if (isPlain(entry) && typeof entry.kind === 'string' && typeof entry.id === 'string' && ['publish', 'retract'].includes(entry.desired) && typeof entry.state === 'string'
129
- && (entry.desired === 'publish' || typeof entry.targetAuthor === 'string')) entries[keyOf(entry)] = entry;
133
+ && (entry.desired === 'publish' || typeof entry.targetAuthor === 'string')) {
134
+ if (isReserved(entry.kind)) dropped++; else entries[keyOf(entry)] = entry;
135
+ }
130
136
  }
137
+ Object.defineProperty(entries, 'dropped', { value: dropped });
131
138
  return withSeq(entries, Math.max(Number.isSafeInteger(parsed.seq) ? parsed.seq : 0, ...Object.values(entries).map(entry => entry.seq ?? 0)));
132
139
  }
133
140