@coda-console/friends 0.0.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
@@ -1,3 +1,33 @@
1
- # @coda-console/friends
1
+ # 好友
2
2
 
3
- Bootstrap placeholder. The usable release will be published by coda-console/coda-plugins.
3
+ 管理本机的 Accord 身份、个人名片与熟人好友通道(`coda/accord@1`)。
4
+
5
+ - **我的身份与名片**:显示本机公钥短码,可复制公钥;昵称、头像 Emoji、主题色以公开的 `profile` / `self` 记录发布。
6
+ - **添加好友**:粘贴对方给的邀请(JSON、`coda-friend://` 链接或多行 `key=value`),接受后自动尝试互认。暂需由对方提供 friend 角色入网码。
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`);暂停只拦发布,不拦撤回。
25
+
26
+ ## 权限与数据边界
27
+
28
+ - `uses`:`coda/accord@1` 的 `read`(读好友表与名片)、`publish`(发布名片)、`manage`(接受邀请、互认、移除)。
29
+ - 入网码(`authKey`)是凭据:只在提交时用一次,提交后立即清空输入框,不写入任何文件、日志或页面状态。
30
+ - 本地备注只存在插件自己的持久目录 `notes.json`(卸载后保留),不发给好友,也不进 Accord 目录。
31
+ - 好友发来的昵称、Emoji、颜色按同一套规则清洗,只当文本渲染(`textContent`),不当指令或 HTML。
32
+ - 好友页的 Accord 读写在页面交互时发起;模块只在 `activate` 时监听本机 Accord 记录(证书、好友表),用来刷新网关记录、证书恢复后冲洗待发队列。
33
+ - `uses` 的 `publish` 也供网关代别的插件向好友发布;待发的 `body` 只在本机 `outbox.json`,不经别处。
@@ -0,0 +1,159 @@
1
+ // 好友页的纯逻辑:解析邀请、名片的清洗与读取、把好友表与名片、本地备注合成列表行。不碰 Coda,也不碰磁盘。
2
+ // 页面也加载它,所以只用浏览器和 Node 都有的 API。
3
+
4
+ export const COLORS = ['blue', 'orange', 'green', 'purple', 'pink', 'teal', 'gray'];
5
+ export const PROFILE_KIND = 'profile';
6
+ export const PROFILE_ID = 'self';
7
+ const MAX_NAME = 40, MAX_EMOJI = 8;
8
+ // 邀请各字段的上限,与 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 LINK_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
12
+ 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' };
14
+ const CONTROL_CHARS = /[\p{Cc}\u2028\u2029]/gu;
15
+ const length = text => [...text].length;
16
+
17
+ const clean = text => typeof text === 'string' ? text.replace(CONTROL_CHARS, '').trim() : '';
18
+
19
+ // ---- 邀请 ----
20
+
21
+ const fail = message => { throw new Error(message); };
22
+ const field = key => ALIASES[key] ?? ALIASES[key.toLowerCase()] ?? (Object.hasOwn(LIMITS, key) ? key : null);
23
+
24
+ function fromObject(object) {
25
+ const found = {};
26
+ for (const [key, value] of Object.entries(object)) {
27
+ const name = field(key);
28
+ if (!name || value === undefined || value === null) continue;
29
+ if (typeof value !== 'string' && typeof value !== 'number') fail(`${LABELS[name]} 须是文本`);
30
+ found[name] = String(value);
31
+ }
32
+ return found;
33
+ }
34
+
35
+ function fromUrl(text) {
36
+ let url;
37
+ try { url = new URL(text); } catch { return null; }
38
+ const found = fromObject(Object.fromEntries(url.searchParams));
39
+ // coda-friend://host/path?authKey=… 没有写 control 时,用它的地址当入网地址。
40
+ if (!found.control && url.protocol === 'coda-friend:' && url.host) found.control = `https://${url.host}${url.pathname === '/' ? '' : url.pathname}`;
41
+ return found;
42
+ }
43
+
44
+ function fromLines(text) {
45
+ const found = {};
46
+ for (const line of text.split(/\r?\n|&/)) {
47
+ const at = line.search(/[=::]/);
48
+ if (at < 1) continue;
49
+ const key = line.slice(0, at).trim(), name = field(key);
50
+ // 值里自带的冒号(如 https://)只在第一个分隔符处切开。
51
+ if (name) found[name] = line.slice(at + 1).trim();
52
+ }
53
+ return found;
54
+ }
55
+
56
+ /**
57
+ * 把粘贴的邀请解析成 accept 的入参:`{ linkId, control, authKey, scope?, hostname?, peerNode? }`。
58
+ * 接受 JSON 对象、coda-friend:// 或带查询串的链接、多行 key=value;错误抛出清晰的中文提示。
59
+ */
60
+ export function parseInvite(raw) {
61
+ if (typeof raw !== 'string' || !raw.trim()) fail('请先粘贴邀请内容');
62
+ const text = raw.trim();
63
+ if (text.includes('\0')) fail('邀请内容含有不合法的字符');
64
+ let found;
65
+ if (/^[{[]/.test(text)) {
66
+ let object;
67
+ try { object = JSON.parse(text); } catch { fail('邀请不是合法的 JSON'); }
68
+ if (!object || typeof object !== 'object' || Array.isArray(object)) fail('邀请 JSON 须是对象');
69
+ found = fromObject(object);
70
+ } else {
71
+ found = /^[a-z][a-z0-9+.-]*:\/\/\S+$/i.test(text) ? fromUrl(text) : null;
72
+ if (!found || !Object.keys(found).length) found = fromLines(text);
73
+ }
74
+ const invite = {};
75
+ for (const [name, value] of Object.entries(found)) {
76
+ const one = value.trim();
77
+ if (/[\0]/.test(value)) fail(`${LABELS[name]} 含有不合法的字符`);
78
+ if (one) invite[name] = one;
79
+ }
80
+ return checked(invite);
81
+ }
82
+
83
+ /** 校验一份邀请(分字段表单也走这里)。 */
84
+ export function checked(input) {
85
+ const invite = {};
86
+ for (const name of Object.keys(LIMITS)) {
87
+ const value = typeof input?.[name] === 'string' ? input[name].trim() : '';
88
+ if (/[\0]/.test(value)) fail(`${LABELS[name]} 含有不合法的字符`);
89
+ if (value) invite[name] = value;
90
+ }
91
+ if (!invite.control) fail('邀请缺少 control(入网地址)');
92
+ if (!invite.authKey) fail('邀请缺少 authKey(入网码)');
93
+ for (const [name, max] of Object.entries(LIMITS)) if (invite[name] && length(invite[name]) > max) fail(`${LABELS[name]} 太长(最多 ${max} 字)`);
94
+ if (invite.linkId && !LINK_ID.test(invite.linkId)) fail('linkId 须以小写字母或数字开头,只能含小写字母、数字、下划线和连字符,最长 64 位');
95
+ invite.linkId ??= `f-${[...globalThis.crypto.getRandomValues(new Uint8Array(4))].map(n => n.toString(16).padStart(2, '0')).join('')}`;
96
+ return invite;
97
+ }
98
+
99
+ // ---- 名片 ----
100
+
101
+ /** 名片输入的清洗:昵称 1–40 字,emoji 最多 8 字,颜色须在白名单里。不合法的昵称、emoji 抛错;不认识的颜色丢掉。 */
102
+ export function normalizeProfileInput({ name, emoji, color } = {}) {
103
+ const body = { name: clean(name) };
104
+ if (!body.name) fail('昵称不能为空');
105
+ if (length(body.name) > MAX_NAME) fail(`昵称最多 ${MAX_NAME} 个字`);
106
+ const mark = clean(emoji);
107
+ if (mark) { if (length(mark) > MAX_EMOJI) fail(`头像最多 ${MAX_EMOJI} 个字符`); body.emoji = mark; }
108
+ if (typeof color === 'string' && COLORS.includes(color)) body.color = color;
109
+ return body;
110
+ }
111
+
112
+ /**
113
+ * 读 Accord 记录里的名片,来自好友的外来数据:按同样的规则清洗,不合法的字段忽略,昵称不合法整张忽略(null)。
114
+ * 结果只当文本用,不当指令或 HTML。
115
+ */
116
+ export function readProfileRecord(record) {
117
+ if (!record || record.kind !== PROFILE_KIND || record.id !== PROFILE_ID) return null;
118
+ const body = record.body;
119
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return null;
120
+ const name = clean(body.name);
121
+ if (!name || length(name) > MAX_NAME) return null;
122
+ const profile = { author: typeof record.author === 'string' ? record.author : null, version: Number.isFinite(record.version) ? record.version : 0, name };
123
+ const emoji = clean(body.emoji);
124
+ if (emoji && length(emoji) <= MAX_EMOJI) profile.emoji = emoji;
125
+ if (typeof body.color === 'string' && COLORS.includes(body.color)) profile.color = body.color;
126
+ return profile;
127
+ }
128
+
129
+ /** 密钥的短码:`ed25519:` 之后的前 8 位(没有就空串)。 */
130
+ export function shortAuthor(author) {
131
+ const match = /^ed25519:([0-9a-f]{64})$/.exec(author ?? '');
132
+ return match ? match[1].slice(0, 8) : '';
133
+ }
134
+
135
+ // ---- 好友列表 ----
136
+
137
+ const RANK = { conflict: 0, pending: 1, bound: 2 };
138
+ export const statusOf = friend => friend.conflict ? 'conflict' : friend.bound ? 'bound' : 'pending';
139
+
140
+ /**
141
+ * 好友表(`status.friends`)、好友的名片记录(取每把钥匙 version 最大的)和本地备注(按 node,没有再按 author)合成的行,
142
+ * 按状态(冲突、待互认、已互认)再按更新时间新的在前排序,同样的输入排出同样的顺序。
143
+ */
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
+ }
150
+ const note = friend => (Object.hasOwn(notes, friend.node) ? notes[friend.node] : friend.author && Object.hasOwn(notes, friend.author) ? notes[friend.author] : '');
151
+ 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);
154
+ 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) };
157
+ });
158
+ 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
+ }
@@ -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/notes.mjs ADDED
@@ -0,0 +1,65 @@
1
+ // 好友的本地备注:只存在本机插件的持久目录里(notes.json,卸载后保留),不发给好友,也不进 Accord 目录。
2
+ // 按好友的 node 记名,原子写盘(临时文件 + rename);文件缺失或损坏时当空表。
3
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+
6
+ export const MAX_NOTE = 40;
7
+ const MAX_KEY = 200;
8
+ const CONTROL = /[\p{Cc}\u2028\u2029]/gu, HAS_CONTROL = /[\p{Cc}\u2028\u2029]/u;
9
+
10
+ /** 去掉控制字符、两端空白,最多 40 个字符(按码点)。 */
11
+ export function cleanNote(text) {
12
+ if (typeof text !== 'string') return '';
13
+ return [...text.replace(CONTROL, '').trim()].slice(0, MAX_NOTE).join('').trim();
14
+ }
15
+
16
+ function validKey(key) {
17
+ return typeof key === 'string' && key !== '' && [...key].length <= MAX_KEY && !HAS_CONTROL.test(key);
18
+ }
19
+
20
+ /** 从磁盘读出 `{ key: 备注 }`;缺失、损坏、不是对象时为空表。 */
21
+ export async function readNotes(dir) {
22
+ let parsed;
23
+ try { parsed = JSON.parse(await readFile(join(dir, 'notes.json'), 'utf8')); } catch { return {}; }
24
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
25
+ const notes = Object.create(null);
26
+ for (const [key, value] of Object.entries(parsed)) {
27
+ const note = cleanNote(value);
28
+ if (validKey(key) && note) notes[key] = note;
29
+ }
30
+ return { ...notes };
31
+ }
32
+
33
+ let counter = 0;
34
+ async function writeNotes(dir, notes) {
35
+ await mkdir(dir, { recursive: true });
36
+ const target = join(dir, 'notes.json'), temporary = join(dir, `notes.json.${process.pid}.${++counter}.tmp`);
37
+ try {
38
+ await writeFile(temporary, `${JSON.stringify(notes, null, 2)}\n`, { mode: 0o600 });
39
+ await rename(temporary, target);
40
+ } catch (e) { await rm(temporary, { force: true }).catch(() => {}); throw e; }
41
+ }
42
+
43
+ // 同一目录的写入排队,读改写不会互相覆盖。
44
+ const queues = new Map();
45
+ function exclusive(dir, work) {
46
+ const run = (queues.get(dir) ?? Promise.resolve()).then(work, work);
47
+ const tail = run.catch(() => {});
48
+ queues.set(dir, tail);
49
+ tail.then(() => { if (queues.get(dir) === tail) queues.delete(dir); });
50
+ return run;
51
+ }
52
+
53
+ /** 设置一个好友的备注;清洗后为空串就是删除。返回现在的整张表。 */
54
+ export function setNote(dir, key, text) {
55
+ if (!validKey(key)) return Promise.reject(new Error('好友标识不合法'));
56
+ return exclusive(dir, async () => {
57
+ const notes = await readNotes(dir), note = cleanNote(text);
58
+ if (note) notes[key] = note; else delete notes[key];
59
+ await writeNotes(dir, notes);
60
+ return notes;
61
+ });
62
+ }
63
+
64
+ /** 删除一个好友的备注。返回现在的整张表。 */
65
+ export function deleteNote(dir, key) { return setNote(dir, key, ''); }