@coda-console/friends 0.13.0 → 0.14.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
@@ -4,7 +4,7 @@
4
4
 
5
5
  - **本机身份**:身份卡显示本机的展示名、确定性几何纹头像、公钥短码(点按复制),下方状态条给出已互认好友数(有待互认、冲突时提示)与身份、证书状态。没有建身份时显示「未建身份」并提示前往客户端「设置 › 身份」创建。
6
6
  - **公钥派生的昵称与头像**:本机和好友都没有可编辑的昵称、照片、Emoji 或主题色,统一由 Accord 公钥推出。展示名是 `昵称 #尾号`:昵称按 coda#3040 的算法取公钥 256 位,从最高位起每 7 位一组(至多 36 组),`0–77` 为字母、`78–87` 为数字、`88–127` 为结束符(已有不足 2 位时跳过,够 2 位就结束,读完仍不足 2 位则没有昵称);尾号是公钥按大端整数转成十进制(补零到 78 位)后的末 4 位,同昵称且末 4 位相撞的公钥从右往左逐位加位直到区分(如 `xs #04084`、`xs #14084`)。撞号一起比的是当前页面(跨电脑时是视图里所有电脑)上的全部本人公钥与好友公钥;网关 `friends` 操作的 `title` 则由本机身份与全部好友一起比。解不出昵称时退回公钥短码(`ed25519:` 之后前 8 位),还没有公钥的待互认好友用节点名。头像是由公钥确定性生成的 5×5 几何纹,灰色,换设备也一样;没有合法公钥时取名字首字。这些算法不在插件里:页面用 WebView 标准库 `coda-view://lib/v1/accord.js`,Node 侧(网关、代理记录)用 `@coda-console/protocol/accord`,两者是同一份实现,测试用协议包的测试向量对齐。
7
- - **添加好友**:点身份卡上的「添加好友」,粘贴对方给的邀请(JSON、`coda-friend://` 链接或多行 `key=value`),接受后自动尝试互认。邀请也可以在同一个弹层里生成,见下文「生成与接受邀请」。
7
+ - **添加好友**:点身份卡上的「添加好友」打开弹层,顶部分段「邀请对方 / 接受邀请」。邀请对方是一行邀请码加二维码;接受邀请是粘贴(或扫码)对方的邀请码,识别后只显示谁邀请你、还有多久过期,点「接受」后自动尝试互认。见下文「生成与接受邀请」。
8
8
  - **同身份通道合并**:同一台电脑上,指向同一个完整公钥(`author`)的多条通道(如 `node:` + `link:`、两条 `link:`,或对方多台设备共用个人根身份)合并成一张好友卡片:状态里有冲突就算冲突(不隐藏密钥冲突),否则有已互认的算已互认,其余为待互认;多条连接时副标题写「N 条连接」,已互认的好友名下还有待互认通道时再注明「(M 待互认)」。没有公钥的待互认通道不与任何条目合并。详情里公钥与「共享」归整个好友,「连接」一节逐条列出各通道(通道键、机器、范围有差别时一并写出),每条各自有状态、重新互认和二次确认的移除,移除一条后弹层留在其余连接上;只有一条连接时详情保持原样。好友数、状态条与网关 `friends/social@1` 的 `friendCount`、`friends` 都按合并后的好友统计。
9
9
  - **好友列表**:实时跟随好友表变化,宽屏双列。点好友打开详情:昵称、几何纹头像、完整公钥(可复制)、节点名、连接状态、「共享」(见下文「把远程执行授给好友」)、重新互认、二次确认后移除。
10
10
  - **社交网关 `friends/social@1`**:业务无关,别的插件(在 `optionalUses` 里声明)经它读好友与好友分享的记录、向好友发布与撤回记录,不必各自处理没有身份、证书过期和重试。
@@ -155,8 +155,11 @@ coda self grants.restrict '{"grant":"<授权号>","restrict":{"dirs":[…]}}'
155
155
 
156
156
  ### 生成与接受邀请
157
157
 
158
- - **生成**:在「添加好友」弹层的上半点「生成邀请」(需在 Coda 客户端里打开好友页)。邀请带入网码和**一次性口令** `bindingToken`,24 小时内有效,只能用一次;它是凭据,只显示这一次,关掉弹层就清掉。
159
- - **接受**:弹层下半粘贴对方的邀请,接受后自动互认。没有口令的邀请会被拒绝,请对方重新生成。
158
+ - **邀请码格式**:一行 `coda-friend-v1:` 加紧凑 JSON 的 base64url(无填充)。键用短名:`c` control、`k` authKey、`n` peerNode、`t` bindingToken(一次性口令)、`a` 邀请人公钥(`ed25519:…`)、`e` 过期时刻(Unix 毫秒)。`scope` 等于从 `control` 推出的值时不写,不等时写 `s`;推法同客户端:`control` 去掉首尾空白和末尾斜杠,空的或 `https://login.tailscale.com` 写成 `https://controlplane.tailscale.com`,`scope` 为 `coda-tailnet/` 加它。编码与解析是 `lib/friends.mjs` 的 `encodeInvite`、`parseInvite`(页面和 Node 共用);旧的 JSON、`coda-friend://` 链接、多行 `key=value` 照旧都认。前缀后面不是合法的 base64url 或 JSON 时报中文错误。
159
+ - **生成**:在弹层的「邀请对方」点「生成邀请码」(需在 Coda 客户端里打开好友页)。页面拿客户端 `coda.inviteFriend` 的结果,加上本机作者和过期时刻编成邀请码,显示邀请人(几何纹头像与展示名)、二维码、单行截断的邀请码,和「复制邀请码」「换一个」;有效期 24 小时,只能用一次。邀请码是凭据,只显示这一次,不进页面状态、存储或日志,关掉弹层就清掉。
160
+ - **二维码**:由插件自带的 [qrcode-generator](THIRD-PARTY.md)(MIT,`view/vendor/qrcode.mjs`)生成,纠错级别 M,画成 SVG,白底黑码,四格安静区。
161
+ - **接受**:弹层的「接受邀请」里有一个输入框,粘贴邀请码即识别;也可点「粘贴」(点按时读剪贴板)或「扫码」(只在 `coda.scanCode` 存在时出现,扫码取消不报错)。识别后只显示邀请人(旧邀请没有公钥,写「对方」)与「邀请你成为好友 · 还有 N 小时过期」,不再展开入网地址、入网码等字段;点「接受」才发请求,过期的邀请码直接提示重新生成、不发请求。接受后自动互认,成功后卡片写「已成为好友」。没有口令的邀请会被拒绝,请对方重新生成。
162
+ - **带参数打开**:页面的 `coda.args` 里 `add` 为 `true` 时,第一次画完自动弹出添加弹层(几台电脑时是第一节那台),默认停在「邀请对方」,`tab` 为 `accept` 时停在「接受邀请」;页面开着时被别的 `args` 打开(`context` 事件)同样处理。
160
163
  - 邀请的字段、口令的校验与互认的细节见 Coda 仓库的 `docs/peers.md`,这里不再另列。
161
164
 
162
165
  ### 已知限制
@@ -209,7 +212,7 @@ coda self grants.restrict '{"grant":"<授权号>","restrict":{"dirs":[…]}}'
209
212
  - `friends/social@1` 的权限组:`read` 管 `friends`、`records`;`publish` 管 `publish`、`retract`、`outbox`。
210
213
  - `uses`:`coda/accord@1` 的 `read`(读好友表)、`publish`(网关代别的插件发布)、`manage`(接受邀请、互认、移除);`coda/machine@1` 的 `read`(别台的目标读不到时,看那台还在不在空间里;好友页据此标出离线的电脑);`friends/machine@1` 的 `read`(好友页读各台的身份与好友摘要)。`optionalUses`:`remote-exec/machine@1` 的 `use`(转给本机的远程执行,没装就没有这部分)。
211
214
  - 保留种类 `friends/rpc-grant`、`friends/rpc-call`、`friends/rpc-answer`:只有本插件的内部入口能签发与读取,通用网关的发布、撤回、`records`、`outbox` 都不给出。
212
- - 入网码(`authKey`)是凭据:只在提交时用一次,提交后立即清空输入框,不写入任何文件、日志或页面状态。
215
+ - 入网码(`authKey`)与邀请码是凭据:只在提交时用一次,提交后立即清空输入框,不写入任何文件、日志或页面状态。
213
216
  - 节点名等外来数据只当文本渲染(`textContent`),不当指令或 HTML。
214
217
  - 好友页读目录里的 `friends/machine@1`,Accord 的写(接受、互认、移除)在页面交互时发起;模块在 `activate` 时监听本机 Accord 记录(证书、好友表),用来刷新网关记录、写 `friends/machine@1`、证书恢复后冲洗待发队列。
215
218
  - 待发的 `body` 只在本机 `outbox.json`,不经别处。
package/THIRD-PARTY.md ADDED
@@ -0,0 +1,32 @@
1
+ # 第三方声明
2
+
3
+ ## qrcode-generator 1.4.4
4
+
5
+ - 位置:`view/vendor/qrcode.mjs`(邀请二维码的生成器)
6
+ - 来源:<https://github.com/kazuhikoarase/qrcode-generator>,npm 包 `qrcode-generator@1.4.4`
7
+ - 改动:只把文件末尾的 UMD 包装换成 `export default qrcode;`,其余逐字不动
8
+ - 许可证:MIT
9
+
10
+ ```
11
+ The MIT License (MIT)
12
+
13
+ Copyright (c) 2009 Kazuhiko Arase
14
+
15
+ Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ of this software and associated documentation files (the "Software"), to deal
17
+ in the Software without restriction, including without limitation the rights
18
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ copies of the Software, and to permit persons to whom the Software is
20
+ furnished to do so, subject to the following conditions:
21
+
22
+ The above copyright notice and this permission notice shall be included in all
23
+ copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ SOFTWARE.
32
+ ```
package/lib/friends.mjs CHANGED
@@ -47,14 +47,62 @@ function fromLines(text) {
47
47
  return found;
48
48
  }
49
49
 
50
+ // ---- 邀请码:coda-friend-v1:<base64url 的紧凑 JSON> ----
51
+
52
+ const CODE_PREFIX = 'coda-friend-v1:';
53
+ const OFFICIAL_CONTROL = 'https://controlplane.tailscale.com';
54
+
55
+ /** 与客户端 FriendInvitation 一致:control 去掉首尾空白和末尾斜杠,空的或 login.tailscale.com 写成官方控制面;scope 是 `coda-tailnet/` 加它。 */
56
+ export function scopeOf(control) {
57
+ let value = String(control ?? '').trim().replace(/\/+$/, '');
58
+ if (!value || value === 'https://login.tailscale.com') value = OFFICIAL_CONTROL;
59
+ return `coda-tailnet/${value}`;
60
+ }
61
+
62
+ const toBase64Url = text => btoa(String.fromCharCode(...new TextEncoder().encode(text))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
63
+ function fromBase64Url(body) {
64
+ if (!/^[A-Za-z0-9_-]+$/.test(body)) fail('邀请码不是合法的 base64url,请对方重新发一次完整的邀请码');
65
+ let json;
66
+ try {
67
+ const binary = atob(body.replace(/-/g, '+').replace(/_/g, '/'));
68
+ json = new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(binary, c => c.charCodeAt(0)));
69
+ } catch { fail('邀请码不是合法的 base64url,请对方重新发一次完整的邀请码'); }
70
+ let object;
71
+ try { object = JSON.parse(json); } catch { fail('邀请码里的内容不是合法的 JSON,请对方重新生成'); }
72
+ if (!object || typeof object !== 'object' || Array.isArray(object)) fail('邀请码里的内容须是对象,请对方重新生成');
73
+ return object;
74
+ }
75
+
76
+ /**
77
+ * 编成一行邀请码:`coda-friend-v1:` 加紧凑 JSON 的 base64url(无填充)。键:c control、k authKey、n peerNode、t bindingToken、
78
+ * a 邀请人公钥、e 过期时刻(Unix 毫秒);scope 等于从 control 推出的值时不写,不等时写 s。
79
+ */
80
+ export function encodeInvite({ control, authKey, peerNode, bindingToken, scope, author, expires }) {
81
+ const payload = { c: control, k: authKey, n: peerNode, t: bindingToken };
82
+ if (scope && scope !== scopeOf(control)) payload.s = scope;
83
+ if (author) payload.a = author;
84
+ if (expires !== undefined) payload.e = expires;
85
+ return CODE_PREFIX + toBase64Url(JSON.stringify(payload));
86
+ }
87
+
88
+ function fromCode(text) {
89
+ const { c, k, n, t, s, a, e } = fromBase64Url(text.slice(CODE_PREFIX.length));
90
+ for (const [key, value] of Object.entries({ c, k, n, t, s, a })) if (value !== undefined && typeof value !== 'string') fail(`邀请码里的 ${key} 须是文本,请对方重新生成`);
91
+ if (e !== undefined && !Number.isFinite(e)) fail('邀请码里的过期时刻不对,请对方重新生成');
92
+ const invite = checked({ control: c, authKey: k, peerNode: n, bindingToken: t, scope: s ?? scopeOf(c) });
93
+ return { ...invite, ...(a ? { inviter: a } : {}), ...(e !== undefined ? { expires: e } : {}) };
94
+ }
95
+
50
96
  /**
51
97
  * 把粘贴的邀请解析成 accept 的入参:`{ linkId, control, authKey, bindingToken, peerNode, scope?, hostname?, peerPort? }`。
52
- * 接受 JSON 对象、coda-friend:// 或带查询串的链接、多行 key=value;错误抛出清晰的中文提示。
98
+ * 接受 `coda-friend-v1:` 邀请码(另带 `inviter` 公钥与 `expires` 过期时刻,只给页面显示、不交给 accept)、JSON 对象、coda-friend:// 或带查询串的链接、多行 key=value;错误抛出清晰的中文提示。
53
99
  */
54
100
  export function parseInvite(raw) {
55
101
  if (typeof raw !== 'string' || !raw.trim()) fail('请先粘贴邀请内容');
56
102
  const text = raw.trim();
57
103
  if (text.includes('\0')) fail('邀请内容含有不合法的字符');
104
+ if (text.startsWith(CODE_PREFIX)) return fromCode(text);
105
+ if (/^coda-friend-v\d+:/i.test(text)) fail('不认识这个版本的邀请码,请对方重新生成或升级后再试');
58
106
  let found;
59
107
  if (/^[{[]/.test(text)) {
60
108
  let object;
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "displayName": "好友",
5
5
  "description": "管理 Accord 身份与熟人好友通道,并提供业务无关的好友网关",
6
6
  "icon": { "symbol": "person.2.fill", "color": "blue" },
7
- "version": "0.13.0",
7
+ "version": "0.14.0",
8
8
  "categories": [
9
9
  "Skills 与工具"
10
10
  ],
@@ -283,7 +283,8 @@
283
283
  "files": [
284
284
  "main.mjs",
285
285
  "lib",
286
- "view"
286
+ "view",
287
+ "THIRD-PARTY.md"
287
288
  ],
288
289
  "dependencies": {
289
290
  "@coda-console/protocol": "6.29.0"
package/view/app.mjs CHANGED
@@ -7,11 +7,12 @@
7
7
  // 移除好友后留在网络里的节点(status.networkRemovals)显示在分节里,用户点「重试」才读、才删,页面不会自己调用。
8
8
  // 昵称、头像都由 Accord 公钥推出(WebView 标准库 coda-view://lib/v1/accord.js、avatar.mjs),没有可编辑的名片;
9
9
  // 节点名等外来数据一律用 textContent / DOM API 渲染,从不拼 HTML 字符串。
10
- import { shortAuthor } from 'coda-view://lib/v1/accord.js';
10
+ import { identityTitles, isAuthor, shortAuthor } from 'coda-view://lib/v1/accord.js';
11
11
  import { accordStatusSummary, resolveAvatar } from '../lib/avatar.mjs';
12
- import { checked, parseInvite } from '../lib/friends.mjs';
12
+ import { encodeInvite, parseInvite } from '../lib/friends.mjs';
13
13
  import { applyEntry, applyOffline, friendSections, identities, listMembers, memberOf, memberTitles } from '../lib/view-members.mjs';
14
14
  import { fill, h, identiconSvg, svg } from './dom.mjs';
15
+ import qrcode from './vendor/qrcode.mjs';
15
16
 
16
17
  const ACCORD = 'coda/accord@1', LOCAL = { kind: ACCORD, id: 'local' };
17
18
  const MACHINE_RECORD = 'friends/machine@1', MACHINE = 'coda/machine@1';
@@ -183,133 +184,165 @@ async function copyKey(author) {
183
184
  }
184
185
 
185
186
  // ---- 添加好友 ----
186
- const invite = {
187
- paste: h('textarea', { placeholder: '粘贴邀请:JSON、coda-friend:// 链接,或多行 control=… / authKey=…', autocomplete: 'off', spellcheck: 'false', oninput: parsePaste }),
188
- control: h('input', { type: 'text', autocomplete: 'off', spellcheck: 'false', placeholder: 'https://…', oninput: dropHidden }),
189
- authKey: h('input', { type: 'password', autocomplete: 'off', spellcheck: 'false', placeholder: '入网码,提交后立即清空', oninput: dropHidden }),
190
- linkId: h('input', { type: 'text', autocomplete: 'off', placeholder: '留空自动生成' }),
191
- scope: h('input', { type: 'text', autocomplete: 'off', placeholder: '留空用本机空间' }),
192
- peerNode: h('input', { type: 'text', autocomplete: 'off', placeholder: '可选', oninput: dropHidden }),
193
- message: h('p', { class: 'hint' }),
194
- button: h('button', { class: 'btn', type: 'button', onclick: submitInvite }, '接受邀请'),
195
- hidden: {},
196
- };
197
- // 各字段只在识别出一份邀请之后展开给用户核对:口令只随粘贴的邀请来,空表单手填交不出去。
198
- const ASK_PASTE = '请粘贴对方给你的完整邀请';
199
- invite.fields = h('div', { class: 'fields' },
200
- h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'control(入网地址)'), invite.control),
201
- h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'authKey(入网码)'), invite.authKey),
202
- h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'linkId'), invite.linkId),
203
- h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'scope'), invite.scope),
204
- h('label', { class: 'field' }, h('span', { class: 'lbl' }, 'peerNode'), invite.peerNode));
205
- invite.fields.hidden = true;
206
- invite.dialog = makeDialog({ title: '添加好友', close: '关闭', onClose: resetGenerated });
187
+ // 弹层分「邀请对方」「接受邀请」两页,切换时各自的状态保留。邀请码是凭据:生成的只放在 generated.code 里显示,
188
+ // 识别出的放在 accept.parsed 里,都不进 setState、存储或日志;生成的和识别出的都随弹层关闭、换目标电脑清掉,识别出的在交给 accept 时也清掉。
189
+ const invite = { target: null, tab: 'invite', message: h('p', { class: 'hint' }) };
190
+ invite.dialog = makeDialog({ title: '添加好友', close: '关闭', onClose: resetInvite });
191
+ const TABS = [['invite', '邀请对方'], ['accept', '接受邀请']];
192
+ const tabButtons = TABS.map(([id, label]) => h('button', { type: 'button', role: 'tab', onclick: () => showTab(id) }, label));
193
+ const panes = { invite: h('section', { class: 'pane' }), accept: h('section', { class: 'pane' }) };
194
+ function showTab(id) {
195
+ invite.tab = id;
196
+ TABS.forEach(([name], i) => {
197
+ tabButtons[i].className = name === id ? 'on' : '';
198
+ tabButtons[i].setAttribute('aria-selected', String(name === id));
199
+ panes[name].hidden = name !== id;
200
+ });
201
+ }
207
202
  // 接受邀请和随后的互认都发给打开它的那一节的电脑。
208
203
  function openInvite(m) {
209
- if (invite.target !== m) say(invite.message, '');
204
+ if (invite.target !== m) { say(invite.message, ''); resetInvite(); }
210
205
  invite.target = m;
211
206
  invite.dialog.heading.textContent = multi ? `添加好友 · ${m.name}` : '添加好友';
212
207
  showDialog(invite.dialog);
213
208
  }
214
- // 上半「邀请对方」:说明、主按钮、结果区各有固定的位置,状态变化只换内容;下半「接受对方的邀请」不受它影响。
215
- // 生成的邀请是凭据:只放在 generated.text 里显示这一次,不进 setState、存储或日志,关掉弹层就清掉。
216
- const generated = { state: 'idle', text: '', error: '', copied: false, copyError: '', token: 0, timer: 0 };
217
- const generate = {
218
- button: h('button', { class: 'btn', type: 'button', onclick: generateInvite }, '生成邀请'),
219
- result: h('div', { class: 'result', role: 'status', 'aria-live': 'polite' }),
220
- };
209
+ const inviterTitle = author => memberTitles(members).get(author) ?? identityTitles([author]).get(author);
210
+ // 头像加名字(几何纹头像由公钥推出;没有公钥的旧邀请写「对方」)。
211
+ const personView = (author, name, ...more) => h('div', { class: 'person' }, avatar(resolveAvatar({ author, name }), 'lg'), h('div', { class: 'person-info' }, h('div', { class: 'nm' }, name), ...more));
212
+
213
+ // 「邀请对方」:生成 coda.inviteFriend 的邀请,编成一行邀请码,配二维码。
214
+ const generated = { state: 'idle', code: '', author: null, error: '', copied: false, copyError: '', token: 0, timer: 0 };
215
+ const generate = { button: h('button', { class: 'btn', type: 'button', onclick: generateInvite }, '生成邀请码'), view: h('div', { class: 'stack', role: 'status', 'aria-live': 'polite' }) };
221
216
  const canInvite = () => typeof coda.inviteFriend === 'function';
217
+ const VALID = '24 小时内有效,只能用一次';
218
+ function qrSvg(text) {
219
+ const qr = qrcode(0, 'M');
220
+ qr.addData(text);
221
+ qr.make();
222
+ const count = qr.getModuleCount(), edge = count + 8;
223
+ let path = '';
224
+ for (let r = 0; r < count; r++) for (let c = 0; c < count; c++) if (qr.isDark(r, c)) path += `M${c} ${r}h1v1h-1z`;
225
+ return svg('svg', { viewBox: `-4 -4 ${edge} ${edge}`, 'shape-rendering': 'crispEdges', role: 'img', 'aria-label': '邀请二维码' },
226
+ svg('rect', { x: -4, y: -4, width: edge, height: edge, fill: '#fff' }), svg('path', { d: path, fill: '#000' }));
227
+ }
222
228
  function drawGenerated() {
223
229
  const s = canInvite() ? generated.state : 'na';
224
230
  generate.button.disabled = s === 'busy' || s === 'na';
225
- generate.button.textContent = s === 'done' ? '再生成一个' : s === 'fail' ? '重试' : '生成邀请';
231
+ generate.button.textContent = s === 'fail' ? '重试' : '生成邀请码';
226
232
  if (s === 'done') {
227
- const copy = h('button', { class: 'btn quiet small', type: 'button', onclick: copyInvite }, generated.copied ? '已复制' : '复制');
228
- return fill(generate.result, h('pre', { class: 'res-box code', 'aria-label': '好友邀请' }, generated.text),
229
- h('div', { class: 'copyrow' }, copy, generated.copyError ? h('span', { class: 'error' }, generated.copyError) : h('span', { class: 'secondary' }, '24 小时内有效,只能用一次')));
233
+ const { code, author } = generated;
234
+ return fill(generate.view,
235
+ personView(author, author ? inviterTitle(author) : '我', h('div', { class: 'secondary' }, '邀请你成为好友')),
236
+ h('div', { class: 'qr', 'aria-hidden': 'false' }, qrSvg(code)),
237
+ h('div', { class: 'code-line mono selectable', 'aria-label': '好友邀请码' }, h('span', { class: 'truncate' }, code)),
238
+ h('div', { class: 'line' },
239
+ h('button', { class: 'btn', type: 'button', onclick: copyInvite }, generated.copied ? '已复制' : '复制邀请码'),
240
+ h('button', { class: 'btn quiet', type: 'button', onclick: generateInvite }, '换一个')),
241
+ generated.copyError ? h('p', { class: 'error' }, generated.copyError) : h('p', { class: 'hint center' }, VALID));
230
242
  }
231
- const text = { busy: '正在生成…', fail: generated.error, na: '请在 Coda 客户端里打开好友页来生成邀请' }[s];
232
- fill(generate.result, h('div', { class: s === 'fail' ? 'res-box err' : 'res-box' }, text));
243
+ const text = { idle: '生成一个邀请码,发给对方或让对方扫码', busy: '正在生成…', fail: generated.error, na: '请在 Coda 客户端里打开好友页来生成邀请' }[s];
244
+ fill(generate.view, h('p', { class: s === 'fail' ? 'error center' : 'hint center' }, text), generate.button, s === 'idle' ? h('p', { class: 'hint center' }, VALID) : null);
233
245
  }
234
246
  async function generateInvite() {
235
247
  if (generated.state === 'busy' || !canInvite()) return;
236
248
  const mine = ++generated.token, target = invite.target;
237
- Object.assign(generated, { state: 'busy', text: '', error: '', copied: false, copyError: '' });
249
+ Object.assign(generated, { state: 'busy', code: '', author: null, error: '', copied: false, copyError: '' });
238
250
  drawGenerated();
239
251
  let outcome;
240
- try { outcome = { state: 'done', text: (await coda.inviteFriend({ machine: target.id })).text }; }
252
+ try {
253
+ const { text, expires } = await coda.inviteFriend({ machine: target.id });
254
+ const { control, authKey, scope, peerNode, bindingToken } = JSON.parse(text);
255
+ outcome = { state: 'done', author: target.author, code: encodeInvite({ control, authKey, peerNode, bindingToken, scope, author: target.author ?? undefined, expires }) };
241
256
  // 在确认框里取消:回到空闲,不显示错误。
242
- catch (e) { outcome = e?.code === 'canceled' ? { state: 'idle' } : { state: 'fail', error: e?.message ?? String(e) }; }
257
+ } catch (e) { outcome = e?.code === 'canceled' ? { state: 'idle' } : { state: 'fail', error: e?.message ?? String(e) }; }
243
258
  if (mine !== generated.token) return;
244
259
  Object.assign(generated, outcome);
245
260
  drawGenerated();
246
261
  }
247
262
  async function copyInvite() {
248
263
  clearTimeout(generated.timer);
249
- try { await coda.copy(generated.text); Object.assign(generated, { copied: true, copyError: '' }); }
264
+ try { await coda.copy(generated.code); Object.assign(generated, { copied: true, copyError: '' }); }
250
265
  catch (e) { Object.assign(generated, { copied: false, copyError: `复制失败:${e.message}` }); }
251
266
  drawGenerated();
252
267
  generated.timer = setTimeout(() => { generated.copied = false; drawGenerated(); }, 1500);
253
268
  }
254
269
  function resetGenerated() {
255
270
  clearTimeout(generated.timer);
256
- Object.assign(generated, { state: 'idle', text: '', error: '', copied: false, copyError: '', token: generated.token + 1 });
271
+ Object.assign(generated, { state: 'idle', code: '', author: null, error: '', copied: false, copyError: '', token: generated.token + 1 });
257
272
  drawGenerated();
258
273
  }
259
- drawGenerated();
260
- invite.dialog.body.append(
261
- h('section', { class: 'blk' }, h('h4', { class: 'sec' }, '邀请对方'),
262
- h('p', { class: 'hint' }, '生成一段邀请发给对方,对方在他的好友页粘贴'),
263
- h('div', { class: 'line' }, generate.button), generate.result),
264
- h('section', { class: 'blk' }, h('h4', { class: 'sec' }, '接受对方的邀请'), h('div', { class: 'stack' },
265
- h('p', { class: 'hint' }, ASK_PASTE), invite.paste, invite.fields,
266
- h('div', { class: 'line' }, invite.button), invite.message)));
267
- // hostname、peerPort、bindingToken(一次性口令)只随识别出的那份邀请,不进输入框:手改入网地址或入网码就是另一份邀请了,
268
- // 连粘贴区的原文一起丢掉,免得再从原文里解析出旧邀请;口令只交给邀请指定的那台,改 peerNode 同理;改 linkId、scope 不算。
269
- function dropHidden() { invite.hidden = {}; invite.paste.value = ''; }
270
- // 粘贴区没有识别出邀请(清空了或识别不了):上次识别出的字段不再属于它,清掉并收起。
271
- function closeFields() {
272
- for (const name of ['control', 'authKey', 'linkId', 'scope', 'peerNode']) invite[name].value = '';
273
- invite.fields.hidden = true;
274
+
275
+ // 生成侧和接受侧一起清。接受进行中(凭据已交出)不动,等它自己走完。
276
+ function resetInvite() {
277
+ resetGenerated();
278
+ if (accept.state === 'busy') return;
279
+ accept.input.value = '';
280
+ Object.assign(accept, { state: 'empty', parsed: null, card: null });
281
+ drawAccept();
282
+ }
283
+
284
+ // 「接受邀请」:粘贴或扫码得到邀请码,识别后只给人看「谁邀请你、还有多久过期」,点「接受」才发请求。
285
+ // state:empty 等邀请码,found 已识别,busy 正在接受,done 接受完成(互认没成时 card.kind 是 error)。
286
+ const accept = { state: 'empty', parsed: null, card: null };
287
+ accept.input = h('textarea', { placeholder: '粘贴对方发来的邀请码', autocomplete: 'off', spellcheck: 'false', oninput: parsePaste });
288
+ const pickButtons = [h('button', { class: 'btn quiet', type: 'button', onclick: () => readCode(() => coda.paste()) }, '粘贴'),
289
+ typeof coda.scanCode === 'function' ? h('button', { class: 'btn quiet', type: 'button', onclick: () => readCode(() => coda.scanCode()) }, '扫码') : null].filter(Boolean);
290
+ accept.pick = h('div', { class: 'line' }, ...pickButtons);
291
+ accept.cardBox = h('div', { class: 'found' });
292
+ accept.button = h('button', { class: 'btn', type: 'button', onclick: submitInvite }, '接受');
293
+ accept.again = h('button', { class: 'link', type: 'button', onclick: resetAccept }, '换一个邀请码');
294
+ const left = ms => (ms <= 3_600_000 ? `${Math.max(1, Math.ceil(ms / 60_000))} 分钟` : `${Math.ceil(ms / 3_600_000)} 小时`);
295
+ const EXPIRED = '这个邀请码已经过期,请对方重新生成';
296
+ function drawAccept() {
297
+ const { state, card } = accept, empty = state === 'empty';
298
+ accept.input.hidden = accept.pick.hidden = !empty;
299
+ accept.button.hidden = !(state === 'found' || state === 'busy');
300
+ // 接受进行中(点「接受」到互认结束)输入框、粘贴、扫码、接受都不能动。
301
+ for (const control of [accept.input, accept.button, ...pickButtons]) control.disabled = state === 'busy';
302
+ accept.again.hidden = empty || state === 'busy';
303
+ accept.again.textContent = state === 'done' ? '再加一位' : '换一个邀请码';
304
+ accept.cardBox.hidden = !card;
305
+ if (!card) return;
306
+ const line = card.kind ? h('div', { class: card.kind }, card.text)
307
+ : h('div', { class: 'secondary' }, `邀请你成为好友${card.expires ? ` · 还有 ${left(card.expires - Date.now())}过期` : ''}`);
308
+ fill(accept.cardBox, personView(card.inviter, card.inviter ? inviterTitle(card.inviter) : '对方', line));
309
+ }
310
+ // 读到的文字放进输入框并识别;在扫码页取消不算错误;接受进行中或弹层已关时回来的结果直接丢掉。
311
+ async function readCode(read) {
312
+ const got = await Promise.resolve().then(read).then(text => ({ text }), error => ({ error }));
313
+ if (accept.state === 'busy' || openDialog !== invite.dialog) return;
314
+ if (got.error) { if (got.error?.code === 'canceled') return; return say(invite.message, `读取失败:${got.error?.message ?? got.error}`, 'error'); }
315
+ const { text } = got;
316
+ accept.input.value = typeof text === 'string' ? text : text?.text ?? '';
317
+ parsePaste();
274
318
  }
275
319
  function parsePaste() {
276
- invite.hidden = {};
277
- const text = invite.paste.value;
278
- if (!text.trim()) { closeFields(); return say(invite.message, '', 'hint'); }
279
- try {
280
- const found = parseInvite(text);
281
- for (const name of ['control', 'authKey', 'scope', 'peerNode']) if (found[name]) invite[name].value = found[name];
282
- if (found.linkId && !/^f-[0-9a-f]{8}$/.test(found.linkId)) invite.linkId.value = found.linkId;
283
- invite.hidden = { hostname: found.hostname ?? '', peerPort: found.peerPort, bindingToken: found.bindingToken };
284
- invite.fields.hidden = false;
285
- say(invite.message, '已识别邀请,核对后点「接受邀请」', 'ok');
286
- } catch (e) {
287
- // 提交时报的是这份的解析错误。
288
- closeFields();
289
- say(invite.message, e.message, 'error');
320
+ Object.assign(accept, { state: 'empty', parsed: null, card: null });
321
+ const text = accept.input.value;
322
+ say(invite.message, '');
323
+ if (text.trim()) {
324
+ try {
325
+ const { inviter, expires, ...input } = parseInvite(text);
326
+ if (expires <= Date.now()) throw new Error(EXPIRED);
327
+ Object.assign(accept, { state: 'found', parsed: input, card: { inviter: isAuthor(inviter) ? inviter : null, expires } });
328
+ } catch (e) { say(invite.message, e.message, 'error'); }
290
329
  }
330
+ drawAccept();
291
331
  }
292
- function clearInvite() {
293
- invite.paste.value = '';
294
- closeFields();
295
- invite.hidden = {};
332
+ function resetAccept() {
333
+ accept.input.value = '';
334
+ parsePaste();
296
335
  }
297
336
  async function submitInvite() {
298
- let input;
299
- try {
300
- input = checked({ control: invite.control.value, authKey: invite.authKey.value, linkId: invite.linkId.value, scope: invite.scope.value,
301
- peerNode: invite.peerNode.value, hostname: invite.hidden.hostname, peerPort: invite.hidden.peerPort, bindingToken: invite.hidden.bindingToken });
302
- } catch (e) {
303
- // 什么也没粘贴、字段也没展开:请对方的完整邀请。当前粘贴识别成功了(口令只在这时记着)、或没有粘贴,就以字段为准,校验不过只报错;
304
- // 粘贴了却还没识别成功,才按粘贴原文再解析一次,成不了就报它的错。
305
- if (invite.fields.hidden && !invite.paste.value.trim()) return say(invite.message, ASK_PASTE, 'error');
306
- if (invite.hidden.bindingToken || !invite.paste.value.trim()) return say(invite.message, e.message, 'error');
307
- try { input = parseInvite(invite.paste.value); } catch (pasted) { return say(invite.message, pasted.message, 'error'); }
308
- }
309
- // 入网码和一次性口令是凭据:取出后立刻清空所有输入框和记着的口令,不写进任何存储或日志。
310
- clearInvite();
337
+ let input = accept.parsed;
338
+ if (!input) return;
339
+ // 入网码和一次性口令是凭据:取出后立刻清空输入框和记着的邀请,不写进任何存储或日志。
340
+ accept.parsed = null;
341
+ accept.input.value = '';
342
+ if (accept.card.expires <= Date.now()) { resetAccept(); return say(invite.message, EXPIRED, 'error'); }
311
343
  const target = invite.target, opts = via(target), show = (text, kind) => { if (invite.target === target) say(invite.message, text, kind); };
312
- invite.button.disabled = true;
344
+ accept.state = 'busy';
345
+ drawAccept();
313
346
  show('正在接受邀请,加入对方的通道…', 'progress');
314
347
  const peerNode = input.peerNode;
315
348
  let node;
@@ -320,15 +353,49 @@ async function submitInvite() {
320
353
  ({ node } = await pending);
321
354
  } catch (e) {
322
355
  input = null;
323
- invite.button.disabled = false;
356
+ Object.assign(accept, { state: 'empty', card: null });
357
+ drawAccept();
324
358
  return show(`接受邀请失败:${e.message}。入网码和口令已清空,请重新粘贴邀请再试`, 'error');
325
359
  }
326
360
  show('已加入通道,正在与对方互认…', 'progress');
327
361
  try {
328
- await coda.call(LOCAL, 'handshake', { node, ...(peerNode ? { peerNode } : {}) }, opts);
329
- show('好友已添加并完成互认', 'ok');
330
- } catch (e) { show(`已加入通道,但互认暂未完成(${e.message})。可稍后在好友详情里点「重新互认」重试`, 'error'); }
331
- invite.button.disabled = false;
362
+ const { author } = await coda.call(LOCAL, 'handshake', { node, ...(peerNode ? { peerNode } : {}) }, opts) ?? {};
363
+ const { card } = accept, coded = card.inviter;
364
+ // 按互认出的真实身份显示;和邀请码里写的不是同一个人时写明,不说成码里那个人成了好友。
365
+ if (isAuthor(author)) card.inviter = author;
366
+ if (isAuthor(author) && coded && coded !== author) {
367
+ const titles = identityTitles([coded, author]);
368
+ Object.assign(card, { kind: 'error', text: `互认出的身份是 ${titles.get(author)},和邀请码里写的 ${titles.get(coded)} 不一样` });
369
+ } else Object.assign(card, { kind: 'ok', text: '已成为好友' });
370
+ show('', 'hint');
371
+ } catch (e) {
372
+ accept.card.kind = 'error';
373
+ accept.card.text = '已加入通道,但互认暂未完成';
374
+ show(`互认暂未完成(${e.message})。可稍后在好友详情里点「重新互认」重试`, 'error');
375
+ }
376
+ accept.state = 'done';
377
+ drawAccept();
378
+ }
379
+
380
+ drawGenerated();
381
+ drawAccept();
382
+ panes.invite.append(generate.view);
383
+ panes.accept.append(accept.input, accept.pick, accept.cardBox, accept.button, accept.again, invite.message);
384
+ showTab('invite');
385
+ invite.dialog.body.append(h('div', { class: 'segs', role: 'tablist' }, ...tabButtons), panes.invite, panes.accept);
386
+
387
+ // 带 { add: true } 打开好友页(或页面开着时又被这样打开):等页面第一次画完,自动弹出第一节那台电脑的添加弹层;tab 为 accept 停在「接受邀请」。
388
+ let pendingAdd = null;
389
+ function requestAdd(args) {
390
+ if (args?.add !== true) return;
391
+ pendingAdd = { tab: args.tab === 'accept' ? 'accept' : 'invite' };
392
+ flushAdd();
393
+ }
394
+ function flushAdd() {
395
+ if (!pendingAdd || !firstRead || !drawn.length) return;
396
+ showTab(pendingAdd.tab);
397
+ pendingAdd = null;
398
+ openInvite(drawn[0].member);
332
399
  }
333
400
 
334
401
  // ---- 好友详情:重新互认、移除都发给这一行所在的电脑 ----
@@ -1023,10 +1090,13 @@ function draw() {
1023
1090
  if (state.detail) { if (detailRow()) drawDetail(); else closeDialog(); }
1024
1091
  drawPicker();
1025
1092
  if (netView) drawNet();
1093
+ flushAdd();
1026
1094
  }
1027
1095
 
1028
1096
  picker.dialog.scrim.hidden = true;
1029
1097
  root.replaceChildren(page, detail.dialog.scrim, invite.dialog.scrim, picker.dialog.scrim, net.dialog.scrim);
1030
1098
 
1031
1099
  coda.header({ text: '好友' }).catch(() => {});
1100
+ requestAdd(coda.args);
1101
+ coda.on('context', ({ args }) => requestAdd(args));
1032
1102
  start();
package/view/style.css CHANGED
@@ -37,10 +37,6 @@ button:disabled { opacity: .5; cursor: default; }
37
37
  .stack { display: flex; flex-direction: column; gap: 12px; }
38
38
  .actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
39
39
  .actions.split { padding-top: 12px; border-top: 1px solid var(--line); }
40
- .field { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
41
- .lbl { display: block; color: var(--fg2); font-size: .88em; font-weight: 600; }
42
- .fields { display: flex; flex-wrap: wrap; gap: 10px; }
43
- .fields > .field { flex: 1 1 140px; }
44
40
  input, textarea { width: 100%; min-width: 0; padding: 8px 10px; border-radius: var(--coda-radius, 9px); border: 1px solid var(--line); background: var(--bg); outline: none; }
45
41
  input:focus, textarea:focus { border-color: var(--accent); }
46
42
  textarea { min-height: 84px; resize: vertical; }
@@ -145,15 +141,24 @@ details[open] > summary { margin-bottom: 10px; }
145
141
  .key-full { overflow-wrap: anywhere; word-break: break-all; }
146
142
  .warn-box { margin: 0 0 8px; padding: 9px 11px; border-radius: 11px; background: color-mix(in srgb, var(--red) 11%, transparent); color: var(--red); font-size: .92em; }
147
143
 
148
- /* 添加好友:「邀请对方」与「接受对方的邀请」各一块,结果区高度固定,状态变化只换里面的内容 */
149
- .blk { display: flex; flex-direction: column; gap: 10px; }
150
- .blk + .blk { margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--line); }
151
- .blk .sec { margin: 0; }
152
- .result { height: 208px; display: flex; flex-direction: column; gap: 8px; }
153
- .res-box { flex: 1 1 auto; min-height: 0; display: flex; align-items: center; justify-content: center; padding: 12px; text-align: center; border: 1px dashed var(--line); border-radius: 12px; color: var(--fg2); font-size: .92em; overflow: auto; }
154
- .res-box.code { display: block; text-align: left; border: 1px solid var(--line); background: var(--card); color: var(--fg); margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font-family: var(--mono); font-size: .86em; line-height: 1.5; -webkit-user-select: text; user-select: text; }
155
- .res-box.err { color: var(--red); border-color: color-mix(in srgb, var(--red) 40%, transparent); }
156
- .copyrow { flex: none; display: flex; align-items: center; gap: 10px; min-height: 28px; }
144
+ /* 添加好友:分段「邀请对方 / 接受邀请」,邀请页是头像、二维码、一行邀请码,接受页是输入框和识别出的邀请人 */
145
+ .segs { display: flex; padding: 2px; margin-bottom: 14px; border-radius: 10px; background: var(--fill); }
146
+ .segs button { flex: 1; padding: 5px 0; border: 0; border-radius: 8px; background: none; font-weight: 500; }
147
+ .segs button.on { background: var(--bg); box-shadow: 0 1px 3px rgba(0, 0, 0, .14); font-weight: 650; }
148
+ .pane { display: flex; flex-direction: column; gap: 14px; }
149
+ .person { display: flex; align-items: center; gap: 10px; min-width: 0; }
150
+ .person > .av { width: 40px; height: 40px; border-radius: 50%; }
151
+ .person-info { min-width: 0; }
152
+ .nm { font-weight: 650; overflow-wrap: anywhere; }
153
+ .qr { align-self: center; padding: 10px; border-radius: 16px; background: #fff; box-shadow: 0 0 0 1px var(--line); }
154
+ .qr svg { display: block; width: 216px; height: 216px; }
155
+ .code-line { display: flex; padding: 9px 12px; border-radius: 10px; background: var(--card); color: var(--fg2); }
156
+ .code-line > span { flex: 1; }
157
+ .center { text-align: center; }
158
+ .found { display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 16px; border-radius: 14px; background: var(--card); text-align: center; }
159
+ .found .person { flex-direction: column; }
160
+ .found .person > .av { width: 56px; height: 56px; }
161
+ .link { align-self: center; padding: 4px; border: 0; background: none; color: var(--accent); }
157
162
 
158
163
  /* 好友详情里的「共享」 */
159
164
  .share { padding-top: 12px; border-top: 1px solid var(--line); display: flex; flex-direction: column; gap: 16px; }