@coda-console/friends 0.1.0 → 0.2.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,9 +2,26 @@
2
2
 
3
3
  管理本机的 Accord 身份、个人名片与熟人好友通道(`coda/accord@1`)。
4
4
 
5
- - **我的身份与名片**:显示本机公钥短码,可复制公钥;昵称、头像 Emoji、主题色以公开的 `profile` / `self` 记录发布(与 token-board 约定的同一格式,两个插件互不依赖)。
5
+ - **我的身份与名片**:显示本机公钥短码,可复制公钥;昵称、头像 Emoji、主题色以公开的 `profile` / `self` 记录发布。
6
6
  - **添加好友**:粘贴对方给的邀请(JSON、`coda-friend://` 链接或多行 `key=value`),接受后自动尝试互认。暂需由对方提供 friend 角色入网码。
7
7
  - **好友列表**:实时跟随好友表变化;可备注、重新互认、移除。
8
+ - **社交网关 `friends/social@1`**:业务无关,别的插件(在 `optionalUses` 里声明)经它读好友与好友分享的记录、向好友发布与撤回记录,不必各自处理没有身份、证书过期和重试。
9
+
10
+ ## 社交网关
11
+
12
+ 签名写入与记录查询全部透传 `coda/accord@1`,网关自己没有第二份目录库。本机网关记录(`friends/social@1`,key `local`)的 `status` 给出作者、证书状态(`no_identity` / `needs_cert` / `active`)、好友数、待发数与暂停的 kind。
13
+
14
+ | 操作 | 作用 |
15
+ | --- | --- |
16
+ | `friends`(读) | 互认的好友(`includePending` 带上待互认与冲突的),合并名片与本地备注 |
17
+ | `records`(读) | 按 `kind`、`author`、`id`、`cursor` 读好友分享的记录,不读 `binding` |
18
+ | `publish` | 发布 `{ kind, id, body, audience? }`;同作者同内容不重发,换作者重发 |
19
+ | `retract` | 撤回一条,或省略 `id` 撤回本机在这个 `kind` 下的全部(含队列里还没发出去的) |
20
+ | `outbox`(读) | 待发与已同步条目的状态,从不给出 `body` |
21
+
22
+ - `publish`、`retract` 拒绝保留类型 `binding`、`profile`、`friends`、`coda/profile`、`coda/friends`;`kind` 须是 Accord 的格式,`id` 至多 200 个字符、256 字节,`body` 是对象且 JSON 至多 64 KiB,`audience` 每项是 `public` 或 `ed25519:` 加 64 位十六进制,至多 500 项。
23
+ - 没有身份、证书过期(或发布遇到 `invalid_state`)、`kind` 被暂停、发布失败时,待发的 `body` 暂存在本机 `outbox.json`;同步成功就释放 `body`,只留去重用的 `lastAuthor`、`lastSyncedHash`、`lastSyncedAt`;撤回完成就删掉条目。证书恢复后自动补发、补撤;待撤的条目记着排队时的作者(`targetAuthor`),换了作者不会替新作者撤,没有身份时的撤回只清本机未发出的待发,不排待撤。意图先落盘再签名,签名成功立即落盘确认;`outbox.json`、`policy.json` 读不出来(不是缺失或损坏)就报错,不当空表。
24
+ - 暂停与恢复某个 `kind` 的外发:`coda self policy.setKind '{"kind":"…","paused":true}'`,`coda self policy.get` 读现状(`policy.json`);暂停只拦发布,不拦撤回。
8
25
 
9
26
  ## 权限与数据边界
10
27
 
@@ -12,4 +29,5 @@
12
29
  - 入网码(`authKey`)是凭据:只在提交时用一次,提交后立即清空输入框,不写入任何文件、日志或页面状态。
13
30
  - 本地备注只存在插件自己的持久目录 `notes.json`(卸载后保留),不发给好友,也不进 Accord 目录。
14
31
  - 好友发来的昵称、Emoji、颜色按同一套规则清洗,只当文本渲染(`textContent`),不当指令或 HTML。
15
- - `activate` 不调用 Accord,所有 Accord 读写都在页面交互时发起。
32
+ - 好友页的 Accord 读写在页面交互时发起;模块只在 `activate` 时监听本机 Accord 记录(证书、好友表),用来刷新网关记录、证书恢复后冲洗待发队列。
33
+ - `uses` 的 `publish` 也供网关代别的插件向好友发布;待发的 `body` 只在本机 `outbox.json`,不经别处。
@@ -0,0 +1,338 @@
1
+ // 抽象社交网关:实现 friends/social@1。业务无关——只认 kind、id、body;签名写入与记录查询全部透传 coda/accord@1,
2
+ // 自己不建第二份目录库,只在 outbox.json 里留还没发出去的 body(同步成功即释放)。所有会写盘、会外发的动作排成一条队,
3
+ // 发布、撤回、证书变化引起的冲洗互不交叉。
4
+ import { PROFILE_KIND, mergeFriendRows, 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,
7
+ nextSeq, queuePublish, queueRetract, readOutbox, withState, writeOutbox } from './outbox.mjs';
8
+ import { readPolicy, setKindPaused } from './policy.mjs';
9
+
10
+ const ACCORD = { kind: 'coda/accord@1', id: 'local' };
11
+ const SOCIAL = 'friends/social@1';
12
+ const MAX_PAGES = 50;
13
+ const REJECTED = new Set(['invalid_input', 'forbidden']);
14
+ const message = e => String(e?.message ?? e);
15
+ const interrupted = effects => Object.assign(new Error('好友网关已停止'), { code: 'interrupted', effects });
16
+
17
+ export function createGateway(coda, dir) {
18
+ let stopped = false, watching = null, chain = Promise.resolve();
19
+ const handles = [];
20
+ const stateDir = () => {
21
+ if (!dir) throw new Error('这台机器没有插件状态目录,网关的待发队列存不下');
22
+ return dir;
23
+ };
24
+ // 停了以后不再发起新的签名写入、策略写入:每个副作用之前、每次 await 回来都过一下它。
25
+ const live = (effects = 'none') => { if (stopped) throw interrupted(effects); };
26
+ // 所有写盘与外发排成一条队;停了以后排着的活不再做。
27
+ const serial = work => {
28
+ const run = chain.then(() => { live(); return work(); });
29
+ chain = run.then(() => {}, () => {});
30
+ return run;
31
+ };
32
+ // `save` 落待处理的意图,在签名之前;停了就不写。`persist` 落已经确认的结果(签名已成功,磁盘不能比远端旧),停了也要写。
33
+ const save = async outbox => { live(); await writeOutbox(stateDir(), outbox); };
34
+ const persist = outbox => writeOutbox(stateDir(), outbox);
35
+
36
+ async function accordState() {
37
+ const accord = await coda.get(ACCORD);
38
+ return { accord, author: accord?.spec?.author ?? null, certState: certStateOf(accord) };
39
+ }
40
+
41
+ // 翻页读 coda/accord@1 的记录;cursor 重复就停,不会原地打转。
42
+ async function pages(input) {
43
+ const records = [], seen = new Set();
44
+ let cursor;
45
+ for (let page = 0; page < MAX_PAGES; page++) {
46
+ const read = await coda.query(ACCORD, 'records', { ...input, limit: 200, ...(cursor ? { cursor } : {}) });
47
+ records.push(...(read?.records ?? []));
48
+ cursor = read?.nextCursor;
49
+ if (!read?.truncated) return { records, truncated: false };
50
+ if (!cursor || seen.has(cursor)) break;
51
+ seen.add(cursor);
52
+ }
53
+ return { records, truncated: true };
54
+ }
55
+
56
+ // 本机在 Accord 里有没有这条记录。
57
+ async function holds(kind, author, id) {
58
+ const read = await coda.query(ACCORD, 'records', { kind, author, id, limit: 1 });
59
+ return (read?.records ?? []).some(record => record?.local === true && record.id === id);
60
+ }
61
+
62
+ // 把一条待发或待撤的条目交给 coda/accord@1 发出去(撤回是 body 为空、audience 为空的发布)。
63
+ async function attempt(entry, author) {
64
+ live();
65
+ const input = entry.desired === 'publish' ? { kind: entry.kind, id: entry.id, body: entry.body, audience: entry.audience }
66
+ : { kind: entry.kind, id: entry.id, body: {}, audience: [] };
67
+ try {
68
+ const result = await coda.call(ACCORD, 'publish', input);
69
+ return entry.desired === 'publish' ? { state: 'synced', entry: markSynced(entry, result?.author ?? author, Date.now()), result } : { state: 'retracted', entry: null };
70
+ } catch (e) {
71
+ if (e?.code === 'invalid_state') return { state: 'needs_cert', entry: withState(entry, 'needs_cert', message(e)), error: message(e) };
72
+ if (REJECTED.has(e?.code)) return { state: 'error', entry: markRejected(entry, message(e)), error: message(e) };
73
+ return { state: 'queued', entry: withState(entry, 'queued', message(e)), error: message(e) };
74
+ }
75
+ }
76
+
77
+ // 冲洗:能发的待发、待撤条目发出去;证书不对或 kind 暂停的只更新状态。
78
+ async function flushNow() {
79
+ const d = stateDir(), outbox = await readOutbox(d);
80
+ if (!Object.values(outbox).some(isPending)) return;
81
+ const [{ author, certState }, { pausedKinds }] = await Promise.all([accordState(), readPolicy(d)]);
82
+ let changed = false;
83
+ for (const entry of Object.values(outbox).sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))) {
84
+ live();
85
+ if (!isPending(entry)) continue;
86
+ const key = keyOf(entry), hold = holdState(entry, certState, pausedKinds);
87
+ if (hold) {
88
+ if (entry.state !== hold) { outbox[key] = withState(entry, hold, entry.lastError); changed = true; }
89
+ continue;
90
+ }
91
+ // 待撤的条目只替排队时的作者撤:作者换了,同一个 id 可能是另一个人的记录。
92
+ // 没同步过的待撤条目,先确认本机在 Accord 里真有这条记录再签名;没有就清掉,不为从未发布的 id 生成墓碑。
93
+ if (entry.desired === 'retract') {
94
+ if (entry.targetAuthor !== author) continue;
95
+ // 同一条记录之后有更晚的发布,这条旧撤回已被取代:那条发布这位作者已经同步了,旧撤回直接删;还待发的,旧撤回先留着不执行,
96
+ // 等它发布成功时和 synced 一起落盘删除(被拒或中途停用,旧撤回就还在盘上)。
97
+ const later = outbox[entryKey(entry.kind, entry.id)];
98
+ if (later?.desired === 'publish' && (later.seq ?? 0) > (entry.seq ?? 0)) {
99
+ if (later.state === 'synced' && later.lastAuthor === author) {
100
+ live();
101
+ delete outbox[key];
102
+ await save(outbox);
103
+ changed = false;
104
+ continue;
105
+ }
106
+ if (isPending(later)) continue;
107
+ }
108
+ if (entry.lastSyncedHash === undefined) {
109
+ let held;
110
+ try { held = await holds(entry.kind, author, entry.id); } catch (e) {
111
+ // 一条查不出来是临时故障,不拦着后面不相干的条目:它留作 queued 并记下错误,下一次冲洗再试。
112
+ if (stopped) return;
113
+ outbox[key] = withState(entry, 'queued', message(e));
114
+ await persist(outbox);
115
+ changed = false;
116
+ continue;
117
+ }
118
+ if (stopped) return;
119
+ if (!held) {
120
+ delete outbox[key];
121
+ await persist(outbox);
122
+ changed = false;
123
+ continue;
124
+ }
125
+ }
126
+ }
127
+ const done = await attempt(entry, author);
128
+ if (done.entry) outbox[key] = done.entry; else delete outbox[key];
129
+ if (done.state === 'synced') {
130
+ const old = outbox[retractKey(done.entry.lastAuthor, entry.kind, entry.id)];
131
+ if (old && (old.seq ?? 0) < (entry.seq ?? 0)) delete outbox[keyOf(old)];
132
+ }
133
+ await persist(outbox);
134
+ changed = false;
135
+ if (done.state === 'needs_cert') break;
136
+ }
137
+ if (changed) await persist(outbox);
138
+ }
139
+
140
+ // 本机网关记录:别的插件读它就知道网关在不在、证书和待发队列的情况。读不到 Accord 就不更新。
141
+ async function refreshNow() {
142
+ if (stopped) return;
143
+ try {
144
+ const { accord, author, certState } = await accordState();
145
+ const outbox = dir ? await readOutbox(dir) : {}, { pausedKinds } = dir ? await readPolicy(dir) : { pausedKinds: [] };
146
+ const until = accord?.status?.certificate?.until;
147
+ const friends = Array.isArray(accord?.status?.friends) ? accord.status.friends : [];
148
+ const status = { author, certState, ...(Number.isSafeInteger(until) && until >= 0 ? { certUntil: until } : {}),
149
+ friendCount: friends.filter(friend => statusOf(friend) === 'bound').length, pendingCount: Object.values(outbox).filter(isPending).length, pausedKinds };
150
+ if (!stopped) await coda.put({ kind: SOCIAL, key: 'local' }, { spec: { version: 1 }, status });
151
+ } catch { /* 状态记录下一次动作会再写 */ }
152
+ }
153
+ const mutate = work => serial(async () => { try { return await work(); } finally { await refreshNow(); } });
154
+
155
+ // ---- friends/social@1 的操作 ----
156
+
157
+ async function friends({ includePending = false } = {}) {
158
+ const { accord, author, certState } = await accordState();
159
+ const list = Array.isArray(accord?.status?.friends) ? accord.status.friends : [];
160
+ const { records, truncated } = list.length ? await pages({ kind: PROFILE_KIND }) : { records: [], truncated: false };
161
+ 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 };
164
+ }
165
+
166
+ function records({ kind, author, id, limit, cursor, includeAudience }) {
167
+ if (kind === 'binding') throw invalid('kind「binding」是保留类型,网关不读它');
168
+ if (id !== undefined) checkId(id, { query: true });
169
+ return coda.query(ACCORD, 'records', { kind, ...(author === undefined ? {} : { author }), ...(id === undefined ? {} : { id }),
170
+ ...(limit === undefined ? {} : { limit }), ...(cursor === undefined ? {} : { cursor }), ...(includeAudience === undefined ? {} : { includeAudience }) });
171
+ }
172
+
173
+ function publish(input) {
174
+ 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;
198
+ delete outbox[queuedRetract];
199
+ 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;
208
+ 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 };
211
+ });
212
+ }
213
+
214
+ function retract({ kind, id } = {}) {
215
+ checkKind(kind);
216
+ if (id !== undefined) checkId(id);
217
+ return mutate(async () => {
218
+ const d = stateDir(), outbox = await readOutbox(d);
219
+ // 网关替这个作者同步过这条记录的痕迹:发布条目是这个作者同步的,或这个作者先前排过的待撤。
220
+ const history = (entries, author, one) => {
221
+ const published = entries[entryKey(kind, one)];
222
+ return (published?.lastAuthor === author ? published : entries[retractKey(author, kind, one)])?.lastSyncedHash;
223
+ };
224
+ // `remote`:Accord 里本机已有的记录 id;`confirmed`:这份清单是读全了的(读全了又不在里面,才算远端没有)。
225
+ let current, remote = new Set(), confirmed = false, truncated = false;
226
+ try {
227
+ current = await accordState();
228
+ if (current.certState !== 'no_identity') {
229
+ if (id === undefined) {
230
+ const own = await pages({ kind, author: current.author });
231
+ truncated = own.truncated;
232
+ confirmed = !truncated;
233
+ remote = new Set(own.records.filter(record => record?.local === true && typeof record.id === 'string').map(record => record.id));
234
+ } else if (current.certState === 'active' && !history(outbox, current.author, id)) {
235
+ confirmed = true;
236
+ if (await holds(kind, current.author, id)) remote = new Set([id]);
237
+ }
238
+ }
239
+ } catch (e) {
240
+ live();
241
+ return { state: 'error', count: 0, error: message(e) };
242
+ }
243
+ live();
244
+ const { author } = current;
245
+ let { certState } = current, count = 0, queued = 0, rejected, failed;
246
+ // 没有身份:没有可撤的作者,只清本机还没发出去的待发;不排无主的待撤条目,免得将来换了身份被误撤。
247
+ if (certState === 'no_identity') {
248
+ const local = Object.entries(outbox).filter(([, entry]) => entry.kind === kind && (id === undefined || entry.id === id) && entry.desired === 'publish' && isPending(entry));
249
+ for (const [key] of local) delete outbox[key];
250
+ if (local.length) await save(outbox);
251
+ return { state: 'no_identity', count: 0 };
252
+ }
253
+ // 别的作者排下的待撤条目不是这次的:不纳入、不删、不计数。
254
+ const ids = id === undefined
255
+ ? new Set([...Object.values(outbox).filter(entry => entry.kind === kind && (entry.desired === 'publish' || entry.targetAuthor === author)).map(entry => entry.id), ...remote])
256
+ : new Set([id]);
257
+ const sends = [];
258
+ // 先把待撤的意图一次落盘,再逐条签名;每条撤完立刻落盘确认,中途停下也不会把已撤的当成还同步着。
259
+ for (const one of ids) {
260
+ const pubKey = entryKey(kind, one), key = retractKey(author, kind, one), published = outbox[pubKey], prevRetract = outbox[key];
261
+ // 排下的待撤盖过这个作者没发出去的待发、或自己同步过的发布条目;别的作者同步的发布条目不动。
262
+ const superseded = published && (isPending(published) || published.lastAuthor === author);
263
+ // 网关没同步过它、远端也确认没有:只剩本机的待发条目,删掉就是撤回。
264
+ if (history(outbox, author, one) === undefined && confirmed && !remote.has(one)) {
265
+ if (superseded || prevRetract) { if (superseded) delete outbox[pubKey]; delete outbox[key]; count++; }
266
+ continue;
267
+ }
268
+ const entry = queueRetract(published?.lastAuthor === author ? published : prevRetract, kind, one, author, nextSeq(outbox));
269
+ if (superseded) delete outbox[pubKey];
270
+ if (certState === 'active') { outbox[key] = entry; sends.push([one, superseded ? published : undefined, prevRetract]); } else { outbox[key] = withState(entry, certState); queued++; }
271
+ }
272
+ await save(outbox);
273
+ // 意图已落盘,从这里起停用就不是什么都没做:effects 说 some。
274
+ for (const [one, published, prevRetract] of sends) {
275
+ live('some');
276
+ const key = retractKey(author, kind, one), entry = outbox[key];
277
+ if (certState !== 'active') { outbox[key] = withState(entry, certState); queued++; await persist(outbox); continue; }
278
+ const done = await attempt(entry, author);
279
+ if (done.state === 'retracted') { delete outbox[key]; count++; }
280
+ else if (done.state === 'error') {
281
+ rejected ??= done.error;
282
+ if (prevRetract) outbox[key] = prevRetract; else delete outbox[key];
283
+ if (published) outbox[entryKey(kind, one)] = published;
284
+ }
285
+ else {
286
+ outbox[key] = done.entry;
287
+ queued++;
288
+ if (done.state === 'needs_cert') certState = 'needs_cert'; else failed ??= done.error;
289
+ }
290
+ await persist(outbox);
291
+ }
292
+ const state = rejected ? 'error' : queued ? (certState === 'active' ? 'queued' : certState) : 'retracted', error = rejected ?? failed;
293
+ return { state, count, ...(queued ? { queued } : {}), ...(truncated ? { truncated } : {}), ...(error ? { error } : {}) };
294
+ });
295
+ }
296
+
297
+ async function outbox({ kind } = {}) {
298
+ const d = stateDir(), [{ author, certState }, { pausedKinds }, entries] = await Promise.all([accordState(), readPolicy(d), readOutbox(d)]);
299
+ const items = Object.values(entries).filter(entry => kind === undefined || entry.kind === kind).map(entry =>
300
+ ({ kind: entry.kind, id: entry.id, desired: entry.desired, state: entry.state,
301
+ ...(entry.lastSyncedAt === undefined ? {} : { lastSyncedAt: entry.lastSyncedAt }), ...(entry.lastError === undefined ? {} : { lastError: entry.lastError }) }));
302
+ return { author, certState, pausedKinds, pendingCount: Object.values(entries).filter(isPending).length, items };
303
+ }
304
+
305
+ const protocolHandlers = { friends, records, publish, retract, outbox };
306
+ for (const [name, fn] of Object.entries(protocolHandlers)) handles.push(coda.handle(SOCIAL, name, input => fn(input ?? {})));
307
+
308
+ // 证书变成可用就冲洗待发队列;任何变化都刷新网关记录。
309
+ const onChange = ({ type, entry } = {}) => {
310
+ const ready = type !== 'DELETED' && certStateOf(entry) === 'active';
311
+ serial(async () => { if (ready) await flushNow(); await refreshNow(); }).catch(() => {});
312
+ };
313
+
314
+ return {
315
+ // `coda self policy.get|policy.setKind` 的处理函数。
316
+ policy: {
317
+ 'policy.get': () => readPolicy(stateDir()),
318
+ 'policy.setKind': ({ kind, paused } = {}) => {
319
+ if (typeof paused !== 'boolean') throw invalid('paused 须是 true 或 false');
320
+ return mutate(async () => {
321
+ const policy = await setKindPaused(stateDir(), kind, paused, live);
322
+ await flushNow();
323
+ return policy;
324
+ });
325
+ },
326
+ },
327
+ async start() {
328
+ try { watching = await coda.watch(ACCORD.kind, onChange, { id: ACCORD.id }); } catch { /* 没有 Accord:网关记录照样写 */ }
329
+ await serial(refreshNow).catch(() => {});
330
+ },
331
+ stop() {
332
+ stopped = true;
333
+ for (const handle of handles.splice(0)) handle?.dispose?.();
334
+ watching?.dispose?.();
335
+ watching = null;
336
+ },
337
+ };
338
+ }
@@ -0,0 +1,25 @@
1
+ // 插件状态目录里的 JSON 文件:不存在或不是合法 JSON 读成 null;其他读取错误(EACCES、EISDIR、EIO……)原样抛出,
2
+ // 免得读不出来的文件被当成空表绕过策略、覆盖队列。写入原子(临时文件 + rename)。调用方自己保证同一文件的读改写不交叉。
3
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+
6
+ export async function readJson(dir, name) {
7
+ let text;
8
+ try { text = await readFile(join(dir, name), 'utf8'); } catch (e) {
9
+ if (e?.code === 'ENOENT') return null;
10
+ throw e;
11
+ }
12
+ try { return JSON.parse(text); } catch { return null; }
13
+ }
14
+
15
+ let counter = 0;
16
+ // `beforeWrite` 在动第一个字节之前调用(它抛错就不写),前面只隔着建目录这一步。
17
+ export async function writeJson(dir, name, value, beforeWrite) {
18
+ await mkdir(dir, { recursive: true });
19
+ beforeWrite?.();
20
+ const target = join(dir, name), temporary = join(dir, `${name}.${process.pid}.${++counter}.tmp`);
21
+ try {
22
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
23
+ await rename(temporary, target);
24
+ } catch (e) { await rm(temporary, { force: true }).catch(() => {}); throw e; }
25
+ }
package/lib/outbox.mjs ADDED
@@ -0,0 +1,141 @@
1
+ // 网关的纯逻辑:入参校验、保留类型、证书状态、规范哈希,以及待发队列(outbox.json)的条目与状态转换。不碰 Coda。
2
+ // 不另建目录库:签名写入与记录查询都由 coda/accord@1 完成;这里只在记录待发、暂停或失败排队时留着待发的 body,
3
+ // 同步成功就释放 body,只留去重用的轻量元数据;撤回完成就删掉条目。
4
+ import { createHash } from 'node:crypto';
5
+ import { readJson, writeJson } from './json-file.mjs';
6
+
7
+ /** 网关不替业务发布、撤回的类型:好友关系、名片等 Accord 自己的记录。 */
8
+ export const RESERVED_KINDS = new Set(['binding', 'profile', 'friends', 'coda/profile', 'coda/friends']);
9
+ export const MAX_ID_CHARS = 200, MAX_ID_BYTES = 256, MAX_BODY_BYTES = 65536, MAX_AUDIENCE = 500;
10
+ const KIND = /^[a-z][a-z0-9-]{0,63}(?:\/[a-z][a-z0-9-]{0,63})?$/;
11
+ const AUDIENCE = /^(?:public|ed25519:[0-9a-f]{64})$/;
12
+
13
+ export const invalid = message => Object.assign(new Error(message), { code: 'invalid_input', effects: 'none' });
14
+ const isPlain = value => {
15
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
16
+ const proto = Object.getPrototypeOf(value);
17
+ return proto === Object.prototype || proto === null;
18
+ };
19
+
20
+ export const validKind = kind => typeof kind === 'string' && KIND.test(kind) && !RESERVED_KINDS.has(kind);
21
+
22
+ /** kind 须符合 Accord 的格式,且不是保留类型。 */
23
+ export function checkKind(kind) {
24
+ if (typeof kind !== 'string' || !KIND.test(kind)) throw invalid('kind 须是小写字母开头的 name 或 ns/name(只含小写字母、数字、连字符,各段最长 64 位)');
25
+ if (RESERVED_KINDS.has(kind)) throw invalid(`kind「${kind}」是保留类型,网关不发布也不撤回它`);
26
+ return kind;
27
+ }
28
+
29
+ /** id 非空、合法 UTF-8、至多 256 字节;发布与撤回再限 200 个字符(`query: true` 的记录查询只管字节)。 */
30
+ export function checkId(id, { query = false } = {}) {
31
+ if (typeof id !== 'string' || !id || !id.isWellFormed()) throw invalid('id 须是非空的文本');
32
+ if (Buffer.byteLength(id) > MAX_ID_BYTES) throw invalid(`id 最多 ${MAX_ID_BYTES} 字节`);
33
+ if (!query && [...id].length > MAX_ID_CHARS) throw invalid(`id 最多 ${MAX_ID_CHARS} 个字符`);
34
+ return id;
35
+ }
36
+
37
+ /** 校验并规范发布的入参:`{ kind, id, body, audience }`,audience 缺省 `['public']`;body 复制一份纯 JSON。 */
38
+ export function checkPublish({ kind, id, body, audience = ['public'] } = {}) {
39
+ checkKind(kind);
40
+ checkId(id);
41
+ if (!isPlain(body)) throw invalid('body 须是对象');
42
+ let text;
43
+ try { text = JSON.stringify(body); } catch { throw invalid('body 须能转成 JSON'); }
44
+ if (Buffer.byteLength(text) > MAX_BODY_BYTES) throw invalid(`body 最多 ${MAX_BODY_BYTES} 字节`);
45
+ if (!Array.isArray(audience) || audience.length > MAX_AUDIENCE) throw invalid(`audience 须是至多 ${MAX_AUDIENCE} 项的数组`);
46
+ if (!audience.every(item => typeof item === 'string' && AUDIENCE.test(item))) throw invalid("audience 每项须是 'public' 或 ed25519:<64 位十六进制>");
47
+ return { kind, id, body: JSON.parse(text), audience: [...audience] };
48
+ }
49
+
50
+ /**
51
+ * 本机 Accord 记录(`coda/accord@1` 的 local)的证书状态:状态里写了 `certificate` 的按它判:null 没有身份,
52
+ * `active` 为 true 才是可发布,其余要换证书;旧宿主不写这个键,有作者就当可发布(发布遇 invalid_state 再落到需要证书)。
53
+ */
54
+ export function certStateOf(accord) {
55
+ const status = accord?.status;
56
+ if (status && typeof status === 'object' && Object.hasOwn(status, 'certificate')) {
57
+ if (status.certificate === null) return 'no_identity';
58
+ return status.certificate?.active === true ? 'active' : 'needs_cert';
59
+ }
60
+ return accord?.spec?.author ? 'active' : 'no_identity';
61
+ }
62
+
63
+ const canonical = value => {
64
+ if (Array.isArray(value)) return value.map(canonical);
65
+ if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])]));
66
+ return value;
67
+ };
68
+ /** 规范化哈希:对象键递归按字典序排,再取 JSON 的 SHA-256(十六进制);键序不同的同一内容哈希相同。 */
69
+ export const canonicalHash = value => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
70
+
71
+ // ---- 条目与状态转换 ----
72
+ // 发布条目按 `p:${kind}:${id}` 索引,待撤条目按 `r:${targetAuthor}:${kind}:${id}` 索引(kind 不含冒号,两类前缀互斥,键不会撞):
73
+ // 不同作者对同一个 (kind, id) 排下的待撤互不相干,也不挡着对方撤自己的记录。
74
+ // 每次写入发布或撤回的意图都领一个递增的整数 `seq`(落在条目里,不看系统时钟):冲洗按它的先后执行,并据它判断旧撤回是否已被更晚的发布取代。
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)
77
+ // 待撤 { seq, kind, id, desired: 'retract', state: queued|no_identity|needs_cert, targetAuthor, lastError?, + 上次同步的元数据 }
78
+ // targetAuthor 是排队时的作者:换了作者就不再替新作者撤,等原作者回来
79
+ // 被拒 { …, state: 'error', lastError }:Accord 明确拒绝,不再自动重试;下一次发布或撤回同一条会替换它
80
+ export const entryKey = (kind, id) => `p:${kind}:${id}`;
81
+ export const retractKey = (author, kind, id) => `r:${author}:${kind}:${id}`;
82
+ // 序号计数器挂在整张表上(不可枚举,不算条目),随表一起写进 `outbox.json` 顶层:条目删了、发布被拒了,序号也不会倒退。
83
+ const withSeq = (entries, seq) => Object.defineProperty(entries, 'seq', { value: seq, writable: true, configurable: true });
84
+ /** 分配下一个意图序号:严格大于此前分配过的所有序号,随下一次写盘落地。 */
85
+ export const nextSeq = entries => withSeq(entries, (entries.seq ?? 0) + 1).seq;
86
+ export const keyOf = entry => entry.desired === 'retract' ? retractKey(entry.targetAuthor, entry.kind, entry.id) : entryKey(entry.kind, entry.id);
87
+ /** 等着发出去的状态(被拒的 error 不算,已同步的也不算)。 */
88
+ export const isPending = entry => ['queued', 'paused', 'no_identity', 'needs_cert'].includes(entry?.state);
89
+
90
+ const synced = prev => ({ ...(prev?.lastAuthor === undefined ? {} : { lastAuthor: prev.lastAuthor }),
91
+ ...(prev?.lastSyncedHash === undefined ? {} : { lastSyncedHash: prev.lastSyncedHash }), ...(prev?.lastSyncedAt === undefined ? {} : { lastSyncedAt: prev.lastSyncedAt }) });
92
+
93
+ /** 同作者、同内容、已同步的发布不用再发。作者换了(`lastAuthor !== author`)必须重发。 */
94
+ export const canSkip = (prev, hash, author) =>
95
+ !!author && prev?.desired === 'publish' && prev.state === 'synced' && prev.lastAuthor === author && prev.lastSyncedHash === hash;
96
+
97
+ /** 一次发布的待发条目(带 body),保留上一次同步的元数据。 */
98
+ export const queuePublish = (prev, { kind, id, body, audience }, seq) =>
99
+ ({ seq, kind, id, desired: 'publish', state: 'queued', body, audience, hash: canonicalHash({ body, audience }), ...synced(prev) });
100
+
101
+ /** 一次撤回的待撤条目:记下要撤的是哪个作者的记录,保留上一次同步的元数据。 */
102
+ export const queueRetract = (prev, kind, id, targetAuthor, seq) => ({ seq, kind, id, desired: 'retract', state: 'queued', targetAuthor, ...synced(prev) });
103
+
104
+ /** 换状态;`error` 是这次失败的原因,不给就清掉旧的。 */
105
+ export function withState(entry, state, error) {
106
+ const { lastError, ...rest } = entry;
107
+ return { ...rest, state, ...(error ? { lastError: error } : {}) };
108
+ }
109
+
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 });
113
+
114
+ /** Accord 明确拒绝:不再留 body 和 audience,只留元数据与原因。 */
115
+ export const markRejected = (entry, message) =>
116
+ ({ kind: entry.kind, id: entry.id, desired: entry.desired, state: 'error', lastError: message, ...(entry.hash === undefined ? {} : { hash: entry.hash }), ...synced(entry) });
117
+
118
+ /** 现在拦着这个条目、不让它外发的状态:暂停(只管发布,撤回不拦)、没有身份、需要证书;没有就是 null,可以发。 */
119
+ export function holdState(entry, certState, pausedKinds) {
120
+ if (entry.desired === 'publish' && pausedKinds.includes(entry.kind)) return 'paused';
121
+ return certState === 'active' ? null : certState;
122
+ }
123
+
124
+ // ---- 持久化 ----
125
+
126
+ /**
127
+ * 读出整张表 `{ 键: 条目 }`(磁盘上是 `{ seq, entries }`,旧版是直接平铺的条目);键按条目内容重新规范(兼容旧键名),
128
+ * 缺失、损坏、条目不成样子的都丢掉。序号计数器取顶层 `seq` 与现存条目最大序号中较大的。
129
+ */
130
+ export async function readOutbox(dir) {
131
+ const parsed = await readJson(dir, 'outbox.json'), entries = withSeq({}, 0);
132
+ if (!isPlain(parsed)) return entries;
133
+ const stored = isPlain(parsed.entries) ? parsed.entries : parsed;
134
+ for (const entry of Object.values(stored)) {
135
+ if (isPlain(entry) && typeof entry.kind === 'string' && typeof entry.id === 'string' && ['publish', 'retract'].includes(entry.desired) && typeof entry.state === 'string'
136
+ && (entry.desired === 'publish' || typeof entry.targetAuthor === 'string')) entries[keyOf(entry)] = entry;
137
+ }
138
+ return withSeq(entries, Math.max(Number.isSafeInteger(parsed.seq) ? parsed.seq : 0, ...Object.values(entries).map(entry => entry.seq ?? 0)));
139
+ }
140
+
141
+ export const writeOutbox = (dir, entries) => writeJson(dir, 'outbox.json', { seq: entries.seq ?? 0, entries });
package/lib/policy.mjs ADDED
@@ -0,0 +1,22 @@
1
+ // 网关的本机策略:哪些 kind 暂停外发。存在插件状态目录的 policy.json(卸载后保留);缺失或损坏时当 `{ pausedKinds: [] }`。
2
+ import { readJson, writeJson } from './json-file.mjs';
3
+ import { checkKind, validKind } from './outbox.mjs';
4
+
5
+ const NAME = 'policy.json';
6
+
7
+ /** 读出 `{ pausedKinds }`:只留合法且非保留的 kind,去重排序。 */
8
+ export async function readPolicy(dir) {
9
+ const parsed = await readJson(dir, NAME);
10
+ const kinds = Array.isArray(parsed?.pausedKinds) ? parsed.pausedKinds.filter(validKind) : [];
11
+ return { pausedKinds: [...new Set(kinds)].sort() };
12
+ }
13
+
14
+ /** 暂停或恢复一个 kind 的外发;kind 不合法或是保留类型就抛错。`beforeWrite` 在写第一个字节前调用(它抛错就不写)。返回现在的策略。 */
15
+ export async function setKindPaused(dir, kind, paused, beforeWrite) {
16
+ checkKind(kind);
17
+ const { pausedKinds } = await readPolicy(dir), next = new Set(pausedKinds);
18
+ if (paused) next.add(kind); else next.delete(kind);
19
+ const policy = { pausedKinds: [...next].sort() };
20
+ await writeJson(dir, NAME, policy, beforeWrite);
21
+ return policy;
22
+ }
package/main.mjs CHANGED
@@ -1,12 +1,16 @@
1
- // 好友插件的模块(Coda 的 docs/plugins.md「插件宿主」)。Accord 的读写全在页面里发起(页面用自己的 coda.query / coda.call /
2
- // coda.watch);模块只管好友的本地备注:存在插件自己的持久目录 notes.json 里,不外发,页面通过视图消息读写,
3
- // 也能用 `coda self notes.list|notes.set|notes.delete` 读写。activate 里不碰 Accord。
1
+ // 好友插件的模块(Coda 的 docs/plugins.md「插件宿主」)。好友页自己的 Accord 读写在页面里发起(页面用自己的 coda.query /
2
+ // coda.call / coda.watch);模块管两件事:
3
+ // - 好友的本地备注:存在插件自己的持久目录 notes.json 里,不外发,页面通过视图消息读写,
4
+ // 也能用 `coda self notes.list|notes.set|notes.delete` 读写;
5
+ // - 业务无关的社交网关 friends/social@1(lib/gateway.mjs):别的插件经它读好友、发布与撤回记录,全部透传 coda/accord@1;
6
+ // 发布策略用 `coda self policy.get|policy.setKind` 读写。
7
+ import { createGateway } from './lib/gateway.mjs';
4
8
  import { deleteNote, readNotes, setNote } from './lib/notes.mjs';
5
9
 
6
- let dir = null;
10
+ let dir = null, gateway = null;
7
11
  const handles = [];
8
12
 
9
- export function activate(coda) {
13
+ export async function activate(coda) {
10
14
  dir = coda.plugin.state;
11
15
  const actions = {
12
16
  'notes.list': () => readNotes(dir),
@@ -28,9 +32,14 @@ export function activate(coda) {
28
32
  });
29
33
  },
30
34
  });
35
+ gateway = createGateway(coda, dir);
36
+ for (const [name, fn] of Object.entries(gateway.policy)) handles.push(coda.self.handle(name, input => fn(input ?? {})));
37
+ await gateway.start();
31
38
  }
32
39
 
33
40
  export function deactivate() {
41
+ gateway?.stop();
42
+ gateway = null;
34
43
  for (const handle of handles.splice(0)) handle?.dispose?.();
35
44
  dir = null;
36
45
  }
package/package.json CHANGED
@@ -4,12 +4,13 @@
4
4
  "displayName": "好友",
5
5
  "description": "管理 Accord 身份、个人名片与熟人好友通道",
6
6
  "icon": { "symbol": "person.2.fill", "color": "blue" },
7
- "version": "0.1.0",
7
+ "version": "0.2.0",
8
8
  "categories": [
9
9
  "Skills 与工具"
10
10
  ],
11
+ "type": "module",
11
12
  "engines": {
12
- "coda": 5
13
+ "coda": 13
13
14
  },
14
15
  "main": "main.mjs",
15
16
  "activationEvents": [
@@ -34,6 +35,175 @@
34
35
  "icon": "person.2.fill",
35
36
  "frame": "document"
36
37
  }
38
+ ],
39
+ "protocols": [
40
+ {
41
+ "name": "friends/social@1",
42
+ "title": "好友社交网关",
43
+ "description": "业务无关的好友网关:读好友与好友分享的记录,向好友发布、撤回记录;签名与记录全部透传 coda/accord@1,没有身份或证书过期时在本机排队,恢复后自动补发。",
44
+ "spec": {
45
+ "type": "object",
46
+ "properties": { "version": { "const": 1 } },
47
+ "required": ["version"],
48
+ "additionalProperties": false
49
+ },
50
+ "status": {
51
+ "type": "object",
52
+ "properties": {
53
+ "author": { "type": ["string", "null"] },
54
+ "certState": { "enum": ["no_identity", "needs_cert", "active"] },
55
+ "certUntil": { "type": "integer", "minimum": 0 },
56
+ "friendCount": { "type": "integer", "minimum": 0 },
57
+ "pendingCount": { "type": "integer", "minimum": 0 },
58
+ "pausedKinds": { "type": "array", "items": { "type": "string" } }
59
+ },
60
+ "required": ["author", "certState", "friendCount", "pendingCount", "pausedKinds"],
61
+ "additionalProperties": false
62
+ },
63
+ "operations": {
64
+ "friends": {
65
+ "safe": true,
66
+ "input": {
67
+ "type": "object",
68
+ "properties": { "includePending": { "type": "boolean" } },
69
+ "additionalProperties": false
70
+ },
71
+ "result": {
72
+ "type": "object",
73
+ "properties": {
74
+ "selfAuthor": { "type": ["string", "null"] },
75
+ "certState": { "enum": ["no_identity", "needs_cert", "active"] },
76
+ "friends": { "type": "array", "items": { "type": "object" } },
77
+ "truncated": { "type": "boolean" }
78
+ },
79
+ "required": ["selfAuthor", "certState", "friends", "truncated"],
80
+ "additionalProperties": false
81
+ }
82
+ },
83
+ "records": {
84
+ "safe": true,
85
+ "input": {
86
+ "type": "object",
87
+ "properties": {
88
+ "kind": { "type": "string", "minLength": 1 },
89
+ "author": { "type": "string" },
90
+ "id": { "type": "string", "minLength": 1, "maxLength": 256 },
91
+ "limit": { "type": "integer", "minimum": 1, "maximum": 200 },
92
+ "cursor": { "type": "string" },
93
+ "includeAudience": { "type": "boolean" }
94
+ },
95
+ "required": ["kind"],
96
+ "additionalProperties": false
97
+ },
98
+ "result": {
99
+ "type": "object",
100
+ "properties": {
101
+ "records": { "type": "array", "items": { "type": "object" } },
102
+ "truncated": { "type": "boolean" },
103
+ "nextCursor": { "type": "string" }
104
+ },
105
+ "required": ["records", "truncated"]
106
+ }
107
+ },
108
+ "publish": {
109
+ "idempotent": true,
110
+ "input": {
111
+ "type": "object",
112
+ "properties": {
113
+ "kind": { "type": "string", "pattern": "^[a-z][a-z0-9-]{0,63}(?:/[a-z][a-z0-9-]{0,63})?$" },
114
+ "id": { "type": "string", "minLength": 1, "maxLength": 256 },
115
+ "body": { "type": "object" },
116
+ "audience": {
117
+ "type": "array",
118
+ "items": { "type": "string", "pattern": "^(?:public|ed25519:[0-9a-f]{64})$" },
119
+ "maxItems": 500,
120
+ "default": ["public"]
121
+ }
122
+ },
123
+ "required": ["kind", "id", "body"],
124
+ "additionalProperties": false
125
+ },
126
+ "result": {
127
+ "type": "object",
128
+ "properties": {
129
+ "state": { "enum": ["synced", "queued", "paused", "no_identity", "needs_cert", "error"] },
130
+ "skipped": { "type": "boolean" },
131
+ "author": { "type": ["string", "null"] },
132
+ "version": { "type": "integer", "minimum": 0 },
133
+ "error": { "type": "string" }
134
+ },
135
+ "required": ["state"],
136
+ "additionalProperties": false
137
+ }
138
+ },
139
+ "retract": {
140
+ "idempotent": true,
141
+ "input": {
142
+ "type": "object",
143
+ "properties": {
144
+ "kind": { "type": "string", "pattern": "^[a-z][a-z0-9-]{0,63}(?:/[a-z][a-z0-9-]{0,63})?$" },
145
+ "id": { "type": "string", "minLength": 1, "maxLength": 256 }
146
+ },
147
+ "required": ["kind"],
148
+ "additionalProperties": false
149
+ },
150
+ "result": {
151
+ "type": "object",
152
+ "properties": {
153
+ "state": { "enum": ["retracted", "queued", "no_identity", "needs_cert", "error"] },
154
+ "count": { "type": "integer", "minimum": 0 },
155
+ "queued": { "type": "integer", "minimum": 0 },
156
+ "truncated": { "type": "boolean" },
157
+ "error": { "type": "string" }
158
+ },
159
+ "required": ["state", "count"],
160
+ "additionalProperties": false
161
+ }
162
+ },
163
+ "outbox": {
164
+ "safe": true,
165
+ "input": {
166
+ "type": "object",
167
+ "properties": { "kind": { "type": "string" } },
168
+ "additionalProperties": false
169
+ },
170
+ "result": {
171
+ "type": "object",
172
+ "properties": {
173
+ "author": { "type": ["string", "null"] },
174
+ "certState": { "enum": ["no_identity", "needs_cert", "active"] },
175
+ "pausedKinds": { "type": "array", "items": { "type": "string" } },
176
+ "pendingCount": { "type": "integer", "minimum": 0 },
177
+ "items": {
178
+ "type": "array",
179
+ "items": {
180
+ "type": "object",
181
+ "properties": {
182
+ "kind": { "type": "string" },
183
+ "id": { "type": "string" },
184
+ "desired": { "enum": ["publish", "retract"] },
185
+ "state": { "type": "string" },
186
+ "lastSyncedAt": { "type": "integer", "minimum": 0 },
187
+ "lastError": { "type": "string" }
188
+ },
189
+ "required": ["kind", "id", "desired", "state"],
190
+ "additionalProperties": false
191
+ }
192
+ }
193
+ },
194
+ "required": ["author", "certState", "pausedKinds", "pendingCount", "items"],
195
+ "additionalProperties": false
196
+ }
197
+ }
198
+ },
199
+ "permissions": {
200
+ "read": { "title": "查看好友列表与读取好友分享的记录", "read": true, "operations": ["friends", "records"] },
201
+ "publish": { "title": "通过好友网关发布、撤回记录与查看待发队列", "operations": ["publish", "retract", "outbox"] }
202
+ }
203
+ }
204
+ ],
205
+ "protocolImplementations": [
206
+ "friends/social@1"
37
207
  ]
38
208
  },
39
209
  "license": "MIT",