@dibssoftware/dibs 0.0.180 → 0.0.195
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/CHANGELOG.md +111 -1
- package/README.md +10 -8
- package/bin/dibs.mjs +379 -74
- package/docs/agents.md +303 -0
- package/docs/council.md +88 -0
- package/docs/files.md +3 -3
- package/docs/guard.md +86 -11
- package/docs/json.md +211 -0
- package/docs/later.md +5 -5
- package/docs/machines.md +6 -6
- package/docs/questions.md +104 -3
- package/docs/reference.md +124 -30
- package/docs/relay.md +135 -11
- package/docs/releasing.md +7 -1
- package/docs/scheduling.md +28 -6
- package/docs/secrets.md +53 -0
- package/docs/simulators.md +3 -3
- package/docs/windows.md +3 -3
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +79 -149
- package/src/about.mjs +341 -0
- package/src/acquire.mjs +113 -28
- package/src/after.mjs +127 -0
- package/src/agents.mjs +2 -1
- package/src/alerts.mjs +109 -48
- package/src/answers.mjs +2 -2
- package/src/board.mjs +21 -16
- package/src/broker.mjs +23 -7
- package/src/carry.mjs +287 -0
- package/src/codex.mjs +132 -0
- package/src/commands.mjs +254 -86
- package/src/config.mjs +85 -14
- package/src/connect.mjs +4 -2
- package/src/cool.mjs +28 -12
- package/src/council.mjs +482 -0
- package/src/cwd.mjs +9 -0
- package/src/decisions.mjs +250 -0
- package/src/declare.mjs +96 -0
- package/src/diskreport.mjs +306 -0
- package/src/diskuse.mjs +420 -0
- package/src/diskwarn.mjs +68 -13
- package/src/doctor.mjs +149 -0
- package/src/doors.mjs +547 -0
- package/src/durable.mjs +143 -0
- package/src/envs.mjs +372 -0
- package/src/events.mjs +7 -2
- package/src/files.mjs +121 -7
- package/src/guard.mjs +288 -105
- package/src/guardd.mjs +8 -1
- package/src/halt.mjs +63 -0
- package/src/handoffs.mjs +362 -0
- package/src/history.mjs +34 -4
- package/src/hogs.mjs +36 -8
- package/src/jobprogress.mjs +283 -0
- package/src/later.mjs +21 -10
- package/src/lock.mjs +51 -11
- package/src/measure.mjs +60 -14
- package/src/media.mjs +240 -0
- package/src/news.mjs +31 -0
- package/src/notes.mjs +49 -8
- package/src/notices.mjs +126 -43
- package/src/ondemand.mjs +25 -2
- package/src/outcome.mjs +163 -0
- package/src/overlap.mjs +2 -2
- package/src/override.mjs +149 -79
- package/src/owner.mjs +15 -2
- package/src/people.mjs +236 -0
- package/src/pickup.mjs +72 -0
- package/src/picture.mjs +321 -0
- package/src/plain.mjs +84 -18
- package/src/platform.mjs +29 -7
- package/src/preempt.mjs +123 -15
- package/src/primer.mjs +91 -20
- package/src/prints.mjs +99 -0
- package/src/proc.mjs +11 -1
- package/src/progress.mjs +49 -3
- package/src/proof.mjs +102 -0
- package/src/push.mjs +271 -0
- package/src/questions.mjs +328 -57
- package/src/quota.mjs +1 -1
- package/src/recap.mjs +205 -0
- package/src/relay.mjs +262 -26
- package/src/remote.mjs +23 -10
- package/src/reviewgate.mjs +268 -0
- package/src/reviews.mjs +377 -0
- package/src/route.mjs +263 -0
- package/src/rules.mjs +216 -0
- package/src/schedule.mjs +238 -44
- package/src/schema.mjs +62 -0
- package/src/scratch.mjs +2 -2
- package/src/serve.mjs +3 -2
- package/src/service.mjs +5 -1
- package/src/signed.mjs +97 -0
- package/src/simpool.mjs +46 -1
- package/src/spend.mjs +375 -0
- package/src/state.mjs +43 -17
- package/src/talk.mjs +1082 -134
- package/src/thin.sh +2 -0
- package/src/trail.mjs +290 -0
- package/src/trailnote.mjs +209 -0
- package/src/util.mjs +7 -0
- package/src/vault.mjs +435 -0
- package/src/vendors.mjs +327 -0
- package/src/version.mjs +1 -1
- package/src/web.mjs +354 -60
- package/src/work.mjs +487 -0
- package/src/worker.mjs +7 -1
package/src/recap.mjs
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// dibs recap: what happened while the person was away, in one place. Tasks agents closed, tasks
|
|
2
|
+
// they say are stuck, runs that failed and stayed failed, how many finished fine, what agents
|
|
3
|
+
// decided without asking, the reviews agents gave each other's changes, who left the person notes, what agents spent (src/spend.mjs), and agents
|
|
4
|
+
// that stopped mid-task (their session ended with work open, src/carry.mjs) and what came of that
|
|
5
|
+
// work. The page, the apps and the terminal all
|
|
6
|
+
// read this one summary (src/web.mjs serves it as /api/recap), so "while you were away" means the
|
|
7
|
+
// same thing everywhere.
|
|
8
|
+
//
|
|
9
|
+
// Agents read it too: `dibs recap --since 2h` is how a new session learns what the others did.
|
|
10
|
+
//
|
|
11
|
+
// Without --since, the person's recap starts where their last one ended (recap.json), and an
|
|
12
|
+
// agent's covers RECENT. Read without any lock: every source is appended to or read whole.
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { HOME, loadConfig } from './config.mjs';
|
|
16
|
+
import { readEvents } from './events.mjs';
|
|
17
|
+
import { read as readPosts, tasks } from './progress.mjs';
|
|
18
|
+
import { questionsJson } from './questions.mjs';
|
|
19
|
+
import { threadsJson } from './talk.mjs';
|
|
20
|
+
import { trailNow, summary } from './trail.mjs';
|
|
21
|
+
import { handoffsAll } from './handoffs.mjs';
|
|
22
|
+
import { answeredSince } from './reviews.mjs';
|
|
23
|
+
import { actor } from './owner.mjs';
|
|
24
|
+
import { load as loadItems } from './handoffs.mjs';
|
|
25
|
+
import { runProof, proofView } from './proof.mjs';
|
|
26
|
+
import { spentBetween, money, capName } from './spend.mjs';
|
|
27
|
+
import { now, dur, clock, die, deadline } from './util.mjs';
|
|
28
|
+
import { bold, dim, red } from './style.mjs';
|
|
29
|
+
import { described } from './declare.mjs';
|
|
30
|
+
|
|
31
|
+
const FILE = path.join(HOME, 'recap.json');
|
|
32
|
+
// With no last look on record: about a working day.
|
|
33
|
+
const RECENT = 12 * 36e5;
|
|
34
|
+
// A last look older than this is a fresh start; a week of recap is a log, not a catch-up.
|
|
35
|
+
const LONGEST = 3 * 864e5;
|
|
36
|
+
// How many of each list the terminal prints; --json has them all.
|
|
37
|
+
const SHOWN = 6;
|
|
38
|
+
|
|
39
|
+
// What happened between since and t. Pure over its inputs, so tests hand them in. items: the
|
|
40
|
+
// work items as stored (src/work.mjs); posts under an item's id (w3) count as that item's.
|
|
41
|
+
// me: with two or more people, the person reading. Every item then names its agent's owner, and
|
|
42
|
+
// the reader's own come first in each list; everyone's stay in it.
|
|
43
|
+
// handoffs: as handoffsAll() shows them, for work sessions left unfinished (src/carry.mjs).
|
|
44
|
+
// spend: what was spent meanwhile and the caps near or past ({ total, byProject, byAgent, near }), or none.
|
|
45
|
+
export function recapOf({ since, t = now(), posts, events, questions, threads, trail = [], items = [], me = null, spend = null, handoffs = [], reviews = [] }) {
|
|
46
|
+
const ks = tasks(posts.filter(p => p.at <= t), t).filter(k => !/^[wh]\d+$/i.test(k.task || ''));
|
|
47
|
+
const name = k => k.task || k.project || 'untitled';
|
|
48
|
+
const owners = new Map(threads.filter(th => th.owner).map(th => [th.to, th.owner]));
|
|
49
|
+
const own = (who, o) => { const x = o || owners.get(who); return x ? { owner: x } : {}; };
|
|
50
|
+
// Each done thing carries its proof (src/proof.mjs): what dibs checked, or "no proof".
|
|
51
|
+
const done = [
|
|
52
|
+
...ks.filter(k => k.state === 'done' && k.doneAt > since)
|
|
53
|
+
.map(k => ({ who: k.who, task: name(k), text: k.text, at: k.doneAt, proof: proofView(runProof({ who: k.who, since: k.started, t: k.doneAt, events })), ...own(k.who, k.owner) })),
|
|
54
|
+
...items.filter(x => x.state === 'done' && x.closedAt > since && x.closedAt <= t)
|
|
55
|
+
.map(x => ({ who: x.doneBy || x.taker?.name || 'the person', task: x.title, id: `w${x.id}`, text: x.note || '', at: x.closedAt, proof: proofView(x.proof) })),
|
|
56
|
+
];
|
|
57
|
+
const stuck = [
|
|
58
|
+
...ks.filter(k => k.state === 'blocked' && k.last > since).map(k => ({ who: k.who, task: name(k), text: k.text, at: k.last, ...own(k.who, k.owner) })),
|
|
59
|
+
...items.filter(x => (x.state === 'open' || x.state === 'taken') && x.blocked && x.blocked.at > since && x.blocked.at <= t)
|
|
60
|
+
.map(x => ({ who: x.taker?.name || x.blocked.by, task: x.title, id: `w${x.id}`, text: x.blocked.why, at: x.blocked.at })),
|
|
61
|
+
];
|
|
62
|
+
// A run that failed and then passed is fixed: only the ones still failing are news. One stopped
|
|
63
|
+
// by a signal (128 and up: someone's kill, a timeout) was stopped, not failed.
|
|
64
|
+
const ends = events.filter(e => e.kind === 'end' && e.type === 'run' && e.at > since && e.at <= t);
|
|
65
|
+
const lastOf = new Map();
|
|
66
|
+
for (const e of ends) lastOf.set(e.key || `${e.id}`, e);
|
|
67
|
+
const failing = [...lastOf.values()].filter(e => e.code != null && e.code !== 0 && e.code < 128);
|
|
68
|
+
// An agent fixes its own failed runs; one with a deadline (--by) was promised to the person.
|
|
69
|
+
const failed = failing.filter(e => e.due)
|
|
70
|
+
.map(e => ({ who: e.who, what: described(e), res: e.res || [], code: e.code, at: e.at, due: e.due, ...own(e.who) }));
|
|
71
|
+
const ran = ends.filter(e => e.code === 0).length;
|
|
72
|
+
const decided = questions.filter(q => q.state === 'decided' && (q.answeredAt || q.asked) > since && (q.answeredAt || q.asked) <= t)
|
|
73
|
+
.map(q => ({ who: q.agent || q.who, text: q.text, answer: q.answer, id: q.id, at: q.answeredAt || q.asked, ...(q.rule && { rule: q.rule }), ...own(q.agent || q.who, q.owner) }));
|
|
74
|
+
const notes = [];
|
|
75
|
+
for (const th of threads) {
|
|
76
|
+
const n = th.messages.filter(m => m.from === 'agent' && m.kind === 'note' && m.at > since && m.at <= t).length;
|
|
77
|
+
if (n) notes.push({ who: th.to, n, at: th.last, ...own(th.to, th.owner) });
|
|
78
|
+
}
|
|
79
|
+
// One agent's approval or changes on another's work: the check the person didn't have to make.
|
|
80
|
+
const reviewed = reviews.filter(x => x.answeredAt > since && x.answeredAt <= t && (x.state === 'approved' || x.state === 'changes'))
|
|
81
|
+
.map(x => ({ id: x.id, who: x.by, author: x.from, verdict: x.state, what: x.branch || `${x.base.slice(0, 7)}..${x.head.slice(0, 7)}`, project: x.project,
|
|
82
|
+
head: x.head, note: x.verdict, at: x.answeredAt }));
|
|
83
|
+
// Work a session left unfinished, made into a handoff since the last look, and where it is now.
|
|
84
|
+
const stopped = handoffs.filter(x => x.carry && x.carry.at > since && x.carry.at <= t)
|
|
85
|
+
.map(x => ({ who: x.carry.who, task: x.title, id: x.id, at: x.carry.at, state: x.state, taker: x.taker || null, to: x.to || null, offered: x.carry.offered || null }));
|
|
86
|
+
// What dibs saw them do (src/trail.mjs), whether or not they said so: the big things on their own,
|
|
87
|
+
// and per agent, one line of everything.
|
|
88
|
+
const seen = trail.filter(x => x.at > since && x.at <= t);
|
|
89
|
+
const shipped = seen.filter(x => x.ships);
|
|
90
|
+
const others = x => (me && x.owner !== me ? 1 : 0);
|
|
91
|
+
const newest = (a, b) => others(a) - others(b) || b.at - a.at;
|
|
92
|
+
// Caps near their limit come with what was spent meanwhile; on their own they are no news.
|
|
93
|
+
const spent = spend?.total ? spend : null;
|
|
94
|
+
return {
|
|
95
|
+
since, until: t, done: done.sort(newest), stuck: stuck.sort(newest), failed: failed.sort(newest), failing: failing.length, ran,
|
|
96
|
+
decided: decided.sort(newest), reviewed: reviewed.sort(newest), notes: notes.sort(newest), spent, stopped: stopped.sort(newest),
|
|
97
|
+
shipped: shipped.sort(newest), trail: summary(seen),
|
|
98
|
+
empty: !done.length && !stuck.length && !failing.length && !ran && !decided.length && !reviewed.length && !notes.length && !seen.length && !spent && !stopped.length,
|
|
99
|
+
...(me && { you: me }),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// The recap from what's on disk now.
|
|
104
|
+
export function recapNow(since, t = now(), me = null) {
|
|
105
|
+
// From a day earlier: a task done since may have passed its suite before.
|
|
106
|
+
const events = readEvents(t).filter(e => e.at > since - 864e5);
|
|
107
|
+
return recapOf({
|
|
108
|
+
since, t, me, events,
|
|
109
|
+
trail: trailNow({ since, t, events: events.filter(e => e.at > since) }),
|
|
110
|
+
posts: readPosts({ since: since - 864e5 }),
|
|
111
|
+
items: loadItems().handoffs,
|
|
112
|
+
questions: questionsJson(loadConfig(), t).questions,
|
|
113
|
+
threads: threadsJson(t).threads,
|
|
114
|
+
spend: spentBetween(since, t),
|
|
115
|
+
handoffs: handoffsAll(t),
|
|
116
|
+
reviews: answeredSince(since, t),
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Where a recap starts: the last look, unless there's none or it's too old to catch up from.
|
|
121
|
+
export const sinceOf = (seen, t = now()) => Number.isFinite(seen) && seen > 0 && seen < t && t - seen < LONGEST ? seen : t - RECENT;
|
|
122
|
+
|
|
123
|
+
// Each named person keeps their own last look (people), beside the one person's (seen).
|
|
124
|
+
const readLooks = () => { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch { return {}; } };
|
|
125
|
+
function lastLook(me) {
|
|
126
|
+
const j = readLooks();
|
|
127
|
+
const v = me ? j.people?.[me] : j.seen;
|
|
128
|
+
return typeof v === 'number' ? v : null;
|
|
129
|
+
}
|
|
130
|
+
function saveLook(t, me) {
|
|
131
|
+
const j = readLooks();
|
|
132
|
+
const next = me ? { ...j, people: { ...(j.people || {}), [me]: t } } : { ...j, seen: t };
|
|
133
|
+
const tmp = `${FILE}.${process.pid}`;
|
|
134
|
+
try { fs.writeFileSync(tmp, JSON.stringify(next)); fs.renameSync(tmp, FILE); } catch {}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
138
|
+
// What came of work an agent left unfinished, as of now.
|
|
139
|
+
export const fate = x => (x.state === 'taken' ? `${x.taker} took it` : x.state === 'done' ? `${x.taker || 'another agent'} finished it`
|
|
140
|
+
: x.state === 'cancelled' ? 'dropped' : x.state === 'expired' ? 'nobody took it' : x.to ? `given to ${x.to}, not taken yet`
|
|
141
|
+
: x.offered ? `offered to ${x.offered}, not taken yet` : `nobody has it: dibs handoff give ${x.id} <agent>`);
|
|
142
|
+
const cut = (s, n = 110) => { const x = String(s ?? '').replace(/\s+/g, ' ').trim(); return x.length > n ? `${x.slice(0, n - 3)}...` : x; };
|
|
143
|
+
|
|
144
|
+
export function lines(r, t = now()) {
|
|
145
|
+
const out = [bold(`Since ${clock(r.since)} (${dur(t - r.since)} ago):`)];
|
|
146
|
+
if (r.empty) return [...out, ' Nothing happened: no tasks closed, no runs, no decisions, no reviews, no notes.'];
|
|
147
|
+
const section = (title, list, line) => {
|
|
148
|
+
if (!list.length) return;
|
|
149
|
+
out.push('', ` ${title}`);
|
|
150
|
+
for (const x of list.slice(0, SHOWN)) out.push(` ${line(x)}`);
|
|
151
|
+
if (list.length > SHOWN) out.push(dim(` and ${list.length - SHOWN} more (dibs recap --json)`));
|
|
152
|
+
};
|
|
153
|
+
// Another person's agent says whose it is; the reader's own and everyone's with one person say nothing.
|
|
154
|
+
const by = x => (x.owner && x.owner !== r.you ? `${x.who} (${x.owner}'s)` : x.who);
|
|
155
|
+
section(red(`Stuck (${r.stuck.length})`), r.stuck, x => `${by(x)}, ${x.task}: ${cut(x.text)}`);
|
|
156
|
+
section(red(`Stopped mid-task (${r.stopped.length})`), r.stopped, x => `${by(x)}, ${cut(x.task, 70)}: ${fate(x)}`);
|
|
157
|
+
section(red(`Missed a deadline (${r.failed.length})`), r.failed, x => `${by(x)}: ${cut(x.what, 80)} (exit ${x.code}, ${clock(x.at)})`);
|
|
158
|
+
section(bold(`Done (${r.done.length})`), r.done, x => `${by(x)}, ${x.id ? `${x.id} ` : ''}${x.task}${x.text ? `: ${cut(x.text)}` : ''} (${x.proof.proved ? x.proof.line : red(x.proof.line)})`);
|
|
159
|
+
section(bold(`Shipped (${r.shipped.length})`), r.shipped, x => `${by(x)}: ${cut(x.text)}${x.repo ? ` in ${x.repo}` : ''}`);
|
|
160
|
+
section(`Seen by dibs, not in their words (${r.trail.length} ${r.trail.length === 1 ? 'agent' : 'agents'})`, r.trail, x => `${by(x)}: ${cut(x.text, 160)}`);
|
|
161
|
+
section(`Decided without you (${r.decided.length})`, r.decided, x => `#${x.id} ${by(x)}: ${cut(x.text, 70)} -> ${x.answer}${x.rule ? ` (your rule ${x.rule})` : ''}`);
|
|
162
|
+
section(`Reviewed (${r.reviewed.length})`, r.reviewed, x => `${x.id} ${x.who} ${x.verdict === 'approved' ? 'approved' : 'asked for changes to'} ${x.author}'s ${x.what} in ${x.project}${x.note ? `: ${cut(x.note, 70)}` : ''}`);
|
|
163
|
+
if (r.spent) {
|
|
164
|
+
const by = list => list.slice(0, 3).map(x => `${x.name ?? '(no project)'} ${money(x.amount)}`).join(', ');
|
|
165
|
+
out.push('', ` ${bold(`Spent ${money(r.spent.total)}`)}${r.spent.total ? `: ${by(r.spent.byProject)}; by ${by(r.spent.byAgent)}` : ''}`);
|
|
166
|
+
for (const c of r.spent.near) out.push(red(` ${capName(c)} ${c.per === 'day' ? 'today' : 'this month'}: ${money(c.used)} of its ${money(c.limit)} cap (${Math.round(c.pct * 100)}%)`));
|
|
167
|
+
}
|
|
168
|
+
if (r.ran || r.failing || r.notes.length) out.push('');
|
|
169
|
+
if (r.ran) out.push(` ${plural(r.ran, 'run')} finished fine.`);
|
|
170
|
+
if (r.failing) out.push(` ${plural(r.failing, 'run')} failed and ${r.failing === 1 ? "hasn't" : "haven't"} passed since.`);
|
|
171
|
+
if (r.notes.length) {
|
|
172
|
+
const n = r.notes.reduce((k, x) => k + x.n, 0);
|
|
173
|
+
out.push(` ${plural(n, 'note')} for you from ${r.notes.slice(0, 3).map(x => x.who).join(', ')}${r.notes.length > 3 ? ` and ${r.notes.length - 3} more` : ''}: dibs threads`);
|
|
174
|
+
}
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function recap(args) {
|
|
179
|
+
let since = null, json = false;
|
|
180
|
+
for (let i = 0; i < args.length; i++) {
|
|
181
|
+
const a = args[i];
|
|
182
|
+
if (a === '--json') json = true;
|
|
183
|
+
else if (a === '--since') {
|
|
184
|
+
const v = args[++i] ?? die('--since needs a value: how long ago (2h, 30m) or a clock time (09:00)');
|
|
185
|
+
const m = String(v).match(/^(\d+(?:\.\d+)?)([mhd])$/);
|
|
186
|
+
if (m) since = now() - parseFloat(m[1]) * { m: 6e4, h: 36e5, d: 864e5 }[m[2]];
|
|
187
|
+
else {
|
|
188
|
+
// A clock time means the last time it was that o'clock, not the next.
|
|
189
|
+
const at = deadline(v);
|
|
190
|
+
if (!at) die(`--since takes how long ago (2h, 30m) or a clock time (09:00), not ${v}`);
|
|
191
|
+
since = at > now() ? at - 864e5 : at;
|
|
192
|
+
}
|
|
193
|
+
} else die(`dibs recap takes --since and --json, not ${a}`);
|
|
194
|
+
}
|
|
195
|
+
const t = now();
|
|
196
|
+
const who = actor();
|
|
197
|
+
const person = !who.agent;
|
|
198
|
+
const me = person && who.person ? who.person : null;
|
|
199
|
+
if (since == null) since = sinceOf(person ? lastLook(me) : null, t);
|
|
200
|
+
const r = recapNow(since, t, me);
|
|
201
|
+
// The person's next recap starts here. An agent's look, or a --json reader's, moves nothing.
|
|
202
|
+
if (person && !json) saveLook(t, me);
|
|
203
|
+
if (json) return console.log(JSON.stringify(r));
|
|
204
|
+
console.log(lines(r, t).join('\n'));
|
|
205
|
+
}
|
package/src/relay.mjs
CHANGED
|
@@ -33,9 +33,13 @@ import { makeAlive, singleInstance } from './proc.mjs';
|
|
|
33
33
|
import { underLock, commit } from './lock.mjs';
|
|
34
34
|
import { qr, render } from './qr.mjs';
|
|
35
35
|
import { logChange } from './owner.mjs';
|
|
36
|
-
import { remoteAccess, LOCAL_ONLY_TEXT, lookOnlyText, remoteMcp, MCP_ORIGIN, mcpCodes } from './web.mjs';
|
|
36
|
+
import { remoteAccess, talkRoute, LOCAL_ONLY_TEXT, lookOnlyText, talkText, remoteMcp, MCP_ORIGIN, mcpCodes } from './web.mjs';
|
|
37
|
+
import { pusher } from './push.mjs';
|
|
38
|
+
import { giveDevice } from './people.mjs';
|
|
39
|
+
import { readJSON } from './durable.mjs';
|
|
40
|
+
import { PAGE, p256, bodyBytes, signatureOk, proofOf } from './signed.mjs';
|
|
37
41
|
|
|
38
|
-
export
|
|
42
|
+
export { PAGE, bodyBytes, talkDigest } from './signed.mjs';
|
|
39
43
|
export const RELAY = process.env.DIBS_RELAY_URL || 'wss://app.dibs.cc';
|
|
40
44
|
const KEYS = path.join(HOME, 'relay-keys.json');
|
|
41
45
|
const FILE = path.join(HOME, 'relay.json');
|
|
@@ -112,6 +116,52 @@ export const tokenHash = rt => b64u(sha(Buffer.concat([utf8('dibs-relay-token-v1
|
|
|
112
116
|
const MAX_HASHES = 56;
|
|
113
117
|
// Sign-in codes the relay's index takes from one machine at once (relay/src/index.js MAX_CODES).
|
|
114
118
|
const MAX_CODES = 10;
|
|
119
|
+
|
|
120
|
+
// The pairing code shown beside the QR code, for typing at app.dibs.cc instead of scanning:
|
|
121
|
+
// 12 Crockford base32 characters, 7KQM-2XRP-9DHT. The first 4 (R) name a drop at the relay; the
|
|
122
|
+
// other 8 (K, 40 bits) never leave this Mac and the person's eyes. The drop holds the link's
|
|
123
|
+
// fragment (mid, secret, fingerprint) sealed with AES-256-GCM under
|
|
124
|
+
// PBKDF2-SHA256(K, salt "dibs-code-v1" || R, 600,000 iterations). The page fetches the drop by R,
|
|
125
|
+
// derives the key from K and opens it, then pairs exactly as the link does, so the relay never
|
|
126
|
+
// learns the secret. Someone who gets the box (the relay itself, or a guesser who hit a live R)
|
|
127
|
+
// has 2^40 keys to try at 600,000 PBKDF2 rounds each: 3.3e17 HMAC-SHA256 calls on average. A
|
|
128
|
+
// top-end GPU does about 9e9 a second, so finding K inside the link's ten minutes takes some
|
|
129
|
+
// 60,000 of them, and the secret inside is worthless after those ten minutes or once the link is
|
|
130
|
+
// used. The relay hands out each box at most 3 times (relay/src/codebook.js), limits fetches per
|
|
131
|
+
// address, and drops the box when the link is used, revoked or expires.
|
|
132
|
+
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
|
133
|
+
export const CODE_ITERATIONS = 600000;
|
|
134
|
+
const CODE_SALT = 'dibs-code-v1';
|
|
135
|
+
// What people type: lower case, spaces and dashes are fine, and O, I and L read as 0, 1 and 1.
|
|
136
|
+
export const normCode = s => String(s || '').toUpperCase().replace(/[^0-9A-Z]/g, '').replace(/O/g, '0').replace(/[IL]/g, '1');
|
|
137
|
+
export const isCode = s => /^[0-9A-HJKMNP-TV-Z]{12}$/.test(s);
|
|
138
|
+
const randomCrockford = n => Array.from({ length: n }, () => CROCKFORD[crypto.randomInt(32)]).join('');
|
|
139
|
+
// DIBS_FAKE_CODES: codes to hand out first, comma-separated, so a test can make two Macs pick the
|
|
140
|
+
// same drop name. Read once per process.
|
|
141
|
+
const fakeCodes = (process.env.DIBS_FAKE_CODES || '').split(',').map(normCode).filter(isCode);
|
|
142
|
+
// A new code whose drop name none of this Mac's open links uses.
|
|
143
|
+
function freshCode() {
|
|
144
|
+
const mine = new Set(load().pairs.map(p => p.cr));
|
|
145
|
+
for (;;) {
|
|
146
|
+
const c = fakeCodes.shift() || randomCrockford(12);
|
|
147
|
+
if (!mine.has(c.slice(0, 4))) return c;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
// How long dibs pair --remote waits for the relay to take its code (the connector notices the new
|
|
151
|
+
// link within TOKEN_SYNC, then it's one round trip), and how many fresh codes it tries when
|
|
152
|
+
// another Mac already holds the drop name. One clash is a 1 in a million event; three in a row
|
|
153
|
+
// means something else is wrong.
|
|
154
|
+
const CODE_ACK_WAIT = 5000;
|
|
155
|
+
const CODE_TRIES = 3;
|
|
156
|
+
export const showCode = c => `${c.slice(0, 4)}-${c.slice(4, 8)}-${c.slice(8, 12)}`;
|
|
157
|
+
const codeKey = (k, r) => crypto.pbkdf2Sync(utf8(k), utf8(CODE_SALT + r), CODE_ITERATIONS, 32, 'sha256');
|
|
158
|
+
// iv (12) || ciphertext || tag (16), base64url, with the salt as associated data.
|
|
159
|
+
export function sealCode(frag, r, k) {
|
|
160
|
+
const iv = crypto.randomBytes(12);
|
|
161
|
+
const c = crypto.createCipheriv('aes-256-gcm', codeKey(k, r), iv);
|
|
162
|
+
c.setAAD(utf8(CODE_SALT + r));
|
|
163
|
+
return b64u(Buffer.concat([iv, c.update(utf8(frag)), c.final(), c.getAuthTag()]));
|
|
164
|
+
}
|
|
115
165
|
function openBox(key, box) {
|
|
116
166
|
if (box.length !== BOX_LEN) return null;
|
|
117
167
|
try {
|
|
@@ -123,6 +173,64 @@ function openBox(key, box) {
|
|
|
123
173
|
return { name: names.subarray(0, n < 0 ? NAME_PAD : n).toString('utf8'), rt: p.subarray(NAME_PAD) };
|
|
124
174
|
} catch { return null; }
|
|
125
175
|
}
|
|
176
|
+
// Talking from a phone (dibs pair --remote --allow-talk). Messages to agents and answers to their
|
|
177
|
+
// questions reach agents as the person's words, and agents act on them, shell commands included,
|
|
178
|
+
// so a phone that can talk is remote control of this Mac. Each such phone registers, sealed in its
|
|
179
|
+
// pairing message, a second key that signs only after Face ID (or the device passcode): a P-256 key
|
|
180
|
+
// in the Secure Enclave with biometry access control (kind raw), or a WebAuthn credential that
|
|
181
|
+
// requires user verification (kind webauthn). Every talk call then carries a fresh signature over
|
|
182
|
+
// the device, the call, its body and the time, checked here before api() runs it. docs/relay.md,
|
|
183
|
+
// "Talking from a phone", is the protocol.
|
|
184
|
+
const TALK_AAD = utf8('dibs-pair-talk-v1');
|
|
185
|
+
// The sealed key is a few hundred bytes; a WebAuthn credential id is at most 1023.
|
|
186
|
+
const TALK_BOX_MAX = 2048;
|
|
187
|
+
const CRED_MAX = 1023;
|
|
188
|
+
// How far a signature's time may be from this Mac's clock, either way. Phones set their clocks from
|
|
189
|
+
// the network, so two minutes covers drift and a slow relay; a replay inside it is caught by the
|
|
190
|
+
// time having to go up from the last one this device used.
|
|
191
|
+
export const UV_WINDOW = 120e3;
|
|
192
|
+
// { kind, pub, cred? } as kept on the device, or null for anything else.
|
|
193
|
+
export function talkKeyOf(j) {
|
|
194
|
+
if (!j || (j.kind !== 'raw' && j.kind !== 'webauthn')) return null;
|
|
195
|
+
const pub = unb64u(j.pub, 65);
|
|
196
|
+
if (!pub || pub[0] !== 4 || !p256(pub)) return null;
|
|
197
|
+
if (j.kind === 'raw') return { kind: 'raw', pub: j.pub };
|
|
198
|
+
const cred = unb64u(j.cred);
|
|
199
|
+
return cred && cred.length && cred.length <= CRED_MAX ? { kind: 'webauthn', pub: j.pub, cred: j.cred } : null;
|
|
200
|
+
}
|
|
201
|
+
function openTalkKey(key, box) {
|
|
202
|
+
if (box.length < 12 + 16) return null;
|
|
203
|
+
try {
|
|
204
|
+
const d = crypto.createDecipheriv('aes-256-gcm', key, box.subarray(0, 12));
|
|
205
|
+
d.setAAD(TALK_AAD);
|
|
206
|
+
d.setAuthTag(box.subarray(box.length - 16));
|
|
207
|
+
return talkKeyOf(JSON.parse(Buffer.concat([d.update(box.subarray(12, box.length - 16)), d.final()]).toString('utf8')));
|
|
208
|
+
} catch { return null; }
|
|
209
|
+
}
|
|
210
|
+
const UV_MISSING = 'Sending that from this phone needs Face ID each time, and this request came without it. Reload the page (or update the app) and try again.';
|
|
211
|
+
const UV_BAD = 'The Face ID signature on that didn\'t check out, so nothing was sent.';
|
|
212
|
+
const UV_STALE = 'That was signed more than 2 minutes ago, or this phone\'s clock is off, so nothing was sent. Try again.';
|
|
213
|
+
const UV_REPLAY = 'That signature was already used, so nothing was sent again.';
|
|
214
|
+
// One talk call from a talk device: { body, proof } (body without the signature) when it checks out, else { error }.
|
|
215
|
+
// The time must also beat the last one this device used, checked and recorded under one lock.
|
|
216
|
+
export function checkTalk(did, tk, m, clock = now) {
|
|
217
|
+
const body = m.body ?? {}, uv = body && typeof body === 'object' ? body.uv : null;
|
|
218
|
+
if (!uv || typeof uv !== 'object' || !Number.isSafeInteger(uv.t)) return { error: UV_MISSING };
|
|
219
|
+
if (Math.abs(clock() - uv.t) > UV_WINDOW) return { error: UV_STALE };
|
|
220
|
+
const bytes = bodyBytes(body);
|
|
221
|
+
if (!bytes || typeof m.path !== 'string' || !signatureOk(did, tk, m.method, m.path, bytes, uv)) return { error: UV_BAD };
|
|
222
|
+
const fresh = locked(w => {
|
|
223
|
+
const d = w.devices[did];
|
|
224
|
+
if (d?.tk?.pub !== tk.pub || (d.tlast || 0) >= uv.t) return false;
|
|
225
|
+
d.tlast = uv.t;
|
|
226
|
+
return true;
|
|
227
|
+
});
|
|
228
|
+
if (!fresh) return { error: UV_REPLAY };
|
|
229
|
+
const { uv: _, ...rest } = body;
|
|
230
|
+
// proof goes with what the call queues, so the agent it reaches can be shown it was signed (src/signed.mjs).
|
|
231
|
+
return { body: rest, proof: proofOf(did, m.method, m.path, bytes, uv) };
|
|
232
|
+
}
|
|
233
|
+
|
|
126
234
|
const hmac = (k, ...parts) => crypto.createHmac('sha256', k).update(Buffer.concat(parts)).digest();
|
|
127
235
|
const sameBytes = (a, b) => a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
128
236
|
const ZERO = Buffer.alloc(32);
|
|
@@ -149,9 +257,12 @@ function parseKeys(s) {
|
|
|
149
257
|
// relay.json: { devices: {id: {pub, name, created, seen, act}}, pairs: [{pid, key, nk, exp, fails, act}], mcp }
|
|
150
258
|
// mcp: the person turned on remote MCP (dibs relay mcp on). Off unless they did.
|
|
151
259
|
// act: the device may change things (any call but GET). Absent means look only.
|
|
260
|
+
// talk, tk, tlast: the device may also message agents and answer them, signing each call with its
|
|
261
|
+
// talking key tk ({ kind, pub, cred? }); tlast is the time of the last signature it used.
|
|
262
|
+
// push: the dibs app on that phone asked for notifications ({ tok, key, at }, registerPush).
|
|
152
263
|
export function load() {
|
|
153
264
|
try {
|
|
154
|
-
const j =
|
|
265
|
+
const j = readJSON(FILE);
|
|
155
266
|
const obj = k => (j[k] && typeof j[k] === 'object' && !Array.isArray(j[k]) ? j[k] : {});
|
|
156
267
|
return { devices: obj('devices'), pairs: Array.isArray(j.pairs) ? j.pairs : [], mcp: j.mcp === true, accounts: obj('accounts'), approvals: obj('approvals'), pins: obj('pins'), conn: typeof j.conn === 'string' ? j.conn : null };
|
|
157
268
|
} catch { return { devices: {}, pairs: [], mcp: false, accounts: {}, approvals: {}, pins: {}, conn: null }; }
|
|
@@ -173,19 +284,95 @@ function locked(fn) {
|
|
|
173
284
|
// A one-time pairing link. The secret is shown once and only its derived pieces are kept.
|
|
174
285
|
// act: the device it pairs may change things, not only look. account: it pairs a dibs account
|
|
175
286
|
// (the page at /account opens it), which may then give this Mac its account key (join, below).
|
|
176
|
-
|
|
287
|
+
// talk: it may also message agents and answer them, with Face ID each time (it implies act). The
|
|
288
|
+
// link ends in .t so the phone knows to make its talking key before it pairs.
|
|
289
|
+
// person: whose phone it is (dibs people), given the device as it pairs.
|
|
290
|
+
export function newPairing({ act = false, account = false, talk = false, person = null } = {}) {
|
|
177
291
|
const k = keys();
|
|
178
292
|
const secret = crypto.randomBytes(32);
|
|
293
|
+
if (talk) act = true;
|
|
294
|
+
const frag = `${k.mid}.${b64u(secret)}.${k.fp}${talk ? '.t' : ''}`;
|
|
295
|
+
// A browser link gets a code to type as well. The account link opens on /account, which has
|
|
296
|
+
// its own sign-in, so it has none.
|
|
297
|
+
const code = account ? null : freshCode();
|
|
298
|
+
const box = code && sealCode(frag, code.slice(0, 4), code.slice(4));
|
|
299
|
+
const pid = b64u(pairId(secret));
|
|
179
300
|
locked(w => {
|
|
180
|
-
w.pairs.push({ pid
|
|
301
|
+
w.pairs.push({ pid, key: b64u(pairKey(secret)), nk: b64u(nameKey(secret)), th: tokenHash(pairTicket(secret)), exp: now() + PAIR_LIFE, fails: 0, ...(act ? { act: true } : {}), ...(talk ? { talk: true } : {}), ...(account ? { acct: true } : {}), ...(code ? { cr: code.slice(0, 4), cb: box } : {}), ...(person ? { person } : {}) });
|
|
181
302
|
w.pairs = w.pairs.slice(-MAX_PAIRS);
|
|
182
303
|
});
|
|
183
|
-
|
|
184
|
-
|
|
304
|
+
return { link: account ? `${PAGE}account#join=${frag}` : `${PAGE}#p=${frag}`, ...(code ? { code: showCode(code) } : {}), pid, frag, mid: k.mid, fp: k.fp, life: PAIR_LIFE, exp: now() + PAIR_LIFE, act, talk };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// A new code for an open link whose drop name another Mac holds at the relay: the same link,
|
|
308
|
+
// sealed again under a fresh drop name and key. Null if the link is gone (used, revoked, expired).
|
|
309
|
+
export function recode(pid, frag) {
|
|
310
|
+
const code = freshCode();
|
|
311
|
+
const box = sealCode(frag, code.slice(0, 4), code.slice(4));
|
|
312
|
+
return locked(w => {
|
|
313
|
+
const p = w.pairs.find(x => x.pid === pid);
|
|
314
|
+
if (!p) return null;
|
|
315
|
+
Object.assign(p, { cr: code.slice(0, 4), cb: box });
|
|
316
|
+
delete p.ca;
|
|
317
|
+
return showCode(code);
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// The relay's answer to a drops message: which drop names it holds for this Mac (ok) and which
|
|
322
|
+
// another machine already holds (taken). Kept on each open link as ca, for pairRemote to wait on.
|
|
323
|
+
export function dropsAck(m) {
|
|
324
|
+
const ok = new Set(Array.isArray(m?.ok) ? m.ok : []), taken = new Set(Array.isArray(m?.taken) ? m.taken : []);
|
|
325
|
+
locked(w => {
|
|
326
|
+
for (const p of w.pairs) {
|
|
327
|
+
if (typeof p.cr !== 'string') continue;
|
|
328
|
+
if (taken.has(p.cr)) p.ca = 'taken';
|
|
329
|
+
else if (ok.has(p.cr)) p.ca = 'ok';
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// What the relay said about this link's code: 'ok', 'taken', 'gone' (the link was used or
|
|
335
|
+
// revoked meanwhile, so the code no longer matters), or null if it hasn't said within CODE_ACK_WAIT.
|
|
336
|
+
async function codeAck(pid, code) {
|
|
337
|
+
const r = normCode(code).slice(0, 4), until = now() + CODE_ACK_WAIT;
|
|
338
|
+
while (now() < until) {
|
|
339
|
+
const p = load().pairs.find(x => x.pid === pid);
|
|
340
|
+
if (!p) return 'gone';
|
|
341
|
+
if (p.cr === r && p.ca) return p.ca;
|
|
342
|
+
await sleep(100);
|
|
343
|
+
}
|
|
344
|
+
return null;
|
|
185
345
|
}
|
|
186
346
|
|
|
187
347
|
export const devices = () => Object.entries(load().devices).map(([id, d]) => ({ id, ...d }));
|
|
188
348
|
|
|
349
|
+
// Notifications (src/push.mjs). The dibs app gives its APNs token and a push key it made, over its
|
|
350
|
+
// own session, so only that phone can set either on its own device record: never another device's,
|
|
351
|
+
// and never from the Mac's own page. { off: true } turns them off.
|
|
352
|
+
const APNS_TOKEN = /^[0-9a-f]{64,200}$/;
|
|
353
|
+
export function registerPush(did, b, clock = now) {
|
|
354
|
+
const off = b?.off === true;
|
|
355
|
+
const key = unb64u(b?.key, 32);
|
|
356
|
+
if (!off && (typeof b?.token !== 'string' || !APNS_TOKEN.test(b.token) || !key))
|
|
357
|
+
return { status: 400, json: { error: 'a notification sign-up is {token: the APNs token in hex, key: 32 bytes in base64url}, or {off: true}' } };
|
|
358
|
+
const done = locked(w => {
|
|
359
|
+
const d = w.devices[did];
|
|
360
|
+
if (!d) return false;
|
|
361
|
+
if (off) delete d.push;
|
|
362
|
+
else d.push = { tok: b.token, key: b.key, at: clock() };
|
|
363
|
+
return true;
|
|
364
|
+
});
|
|
365
|
+
return done ? { status: 200, json: { ok: true, push: !off } } : { status: 403, json: { error: 'this device is not paired' } };
|
|
366
|
+
}
|
|
367
|
+
// Paired phones with notifications on, for the notifier.
|
|
368
|
+
export const pushPhones = () => Object.entries(load().devices).filter(([, d]) => typeof d.rth === 'string' && typeof d.push?.tok === 'string' && unb64u(d.push.key, 32))
|
|
369
|
+
.map(([did, d]) => ({ did, rth: d.rth, tok: d.push.tok, key: d.push.key }));
|
|
370
|
+
// Apple says that token is dead (the app was deleted, or notifications reset): the phone signs up
|
|
371
|
+
// again with a new one the next time it opens.
|
|
372
|
+
export function forgetPush(rth, tok) {
|
|
373
|
+
locked(w => { for (const d of Object.values(w.devices)) if (d.rth === rth && d.push?.tok === tok) delete d.push; });
|
|
374
|
+
}
|
|
375
|
+
|
|
189
376
|
// Removes every device whose id starts with `which` (or all). Live sessions end on their next frame.
|
|
190
377
|
export function revoke(which) {
|
|
191
378
|
return locked(w => {
|
|
@@ -411,8 +598,10 @@ export function macPeer({ k = keys(), send, kick, call, admit = () => {}, clock
|
|
|
411
598
|
|
|
412
599
|
function pair1(ch, m) {
|
|
413
600
|
const pid = unb64u(m.pid, 16), d = unb64u(m.d, 32), nb = unb64u(m.nb, 32), sig = unb64u(m.sig, 64), mac = unb64u(m.mac, 32), box = unb64u(m.name, BOX_LEN);
|
|
414
|
-
|
|
415
|
-
const
|
|
601
|
+
// tk: a phone's talking key, sealed. When it's there the transcript covers it too.
|
|
602
|
+
const tkBox = m.tk == null ? null : unb64u(m.tk);
|
|
603
|
+
if (!pid || !d || !nb || !sig || !mac || !box || (m.tk != null && (!tkBox || tkBox.length > TALK_BOX_MAX))) return refuse(ch, 'bad-pair');
|
|
604
|
+
const t1 = tkBox ? tx('dibs-pair1-v1', k.mid, pid, d, nb, box, tkBox) : tx('dibs-pair1-v1', k.mid, pid, d, nb, box);
|
|
416
605
|
let name, rth;
|
|
417
606
|
// Look up, check and spend under one lock, so a link can't pair twice.
|
|
418
607
|
const r = locked(w => {
|
|
@@ -427,14 +616,19 @@ export function macPeer({ k = keys(), send, kick, call, admit = () => {}, clock
|
|
|
427
616
|
if (!crypto.verify(null, t1, devKey, sig)) return { err: 'bad-pair' };
|
|
428
617
|
const opened = openBox(unb64u(p.nk, 32), box);
|
|
429
618
|
if (!opened) return { err: 'bad-pair' };
|
|
619
|
+
// Only a link made with --allow-talk lets its key talk; a key sent with any other is ignored.
|
|
620
|
+
// A talk link paired without a key pairs a device that can act but not talk.
|
|
621
|
+
const tk = p.talk === true && tkBox ? openTalkKey(unb64u(p.nk, 32), tkBox) : null;
|
|
622
|
+
if (p.talk === true && tkBox && !tk) return { err: 'bad-pair' };
|
|
430
623
|
name = cleanName(opened.name);
|
|
431
624
|
rth = tokenHash(opened.rt);
|
|
432
625
|
w.pairs = w.pairs.filter(x => x !== p);
|
|
433
626
|
const did = b64u(crypto.randomBytes(16));
|
|
434
|
-
w.devices[did] = { pub: b64u(d), name, rth, created: clock(), ...(p.act === true ? { act: true } : {}), ...(p.acct === true ? { acct: true } : {}) };
|
|
435
|
-
return { did, key: unb64u(p.key, 32) };
|
|
627
|
+
w.devices[did] = { pub: b64u(d), name, rth, created: clock(), ...(p.act === true ? { act: true } : {}), ...(tk ? { talk: true, tk } : {}), ...(p.acct === true ? { acct: true } : {}) };
|
|
628
|
+
return { did, key: unb64u(p.key, 32), person: typeof p.person === 'string' ? p.person : null };
|
|
436
629
|
});
|
|
437
630
|
if (r.err) return refuse(ch, r.err);
|
|
631
|
+
if (r.person) { try { giveDevice(r.person, r.did); } catch (e) { log(`relay: couldn't give ${r.did.slice(0, 8)} to ${r.person}: ${e.message}`); } }
|
|
438
632
|
const nm = crypto.randomBytes(32);
|
|
439
633
|
const t2 = tx('dibs-pair2-v1', k.mid, pid, d, nb, box, k.idPub, nm, utf8(r.did));
|
|
440
634
|
const s2 = crypto.sign(null, t2, k.identity);
|
|
@@ -498,17 +692,23 @@ export function macPeer({ k = keys(), send, kick, call, admit = () => {}, clock
|
|
|
498
692
|
// The route as api() will see it (src/web.mjs parses it the same way), so /api/x/../hook is /api/hook here too.
|
|
499
693
|
let route = null;
|
|
500
694
|
try { if (typeof m.path === 'string' && m.path.startsWith('/api/') && m.path.length <= 512) route = new URL(m.path, 'http://dibs').pathname; } catch {}
|
|
501
|
-
const
|
|
695
|
+
const talks = dev.talk === true && !!dev.tk;
|
|
696
|
+
// A talk call from a phone that may talk runs only with a fresh signature from its talking key.
|
|
697
|
+
const signed = route && talks && talkRoute(m.method, route) ? checkTalk(c.did, dev.tk, m, clock) : null;
|
|
698
|
+
const refused = route && remoteAccess(m.method, route, dev.act === true, !!signed?.body);
|
|
502
699
|
// An account paired through dibs connect --account gives this Mac its account key, so it can
|
|
503
700
|
// hand that key on to the account's new browsers (approve, below). Only such a device may.
|
|
504
701
|
if (route === '/api/account/join' && m.method === 'POST') res = joinAccount(dev, c.did, m.body);
|
|
505
702
|
else if (!METHODS.includes(m.method) || !route?.startsWith('/api/')) res = { status: 400, json: { error: 'not an API call' } };
|
|
506
|
-
else if (
|
|
703
|
+
else if (signed?.error) res = { status: 403, json: { error: signed.error, uv: true } };
|
|
704
|
+
else if (refused) res = { status: 403, json: { error: refused === 'look' ? lookOnlyText(c.did) : refused === 'talk' ? talkText(c.did) : LOCAL_ONLY_TEXT } };
|
|
705
|
+
// Only for the device this session belongs to, whatever the body says.
|
|
706
|
+
else if (route === '/api/push') res = registerPush(c.did, m.body, clock);
|
|
507
707
|
else {
|
|
508
708
|
let timer;
|
|
509
709
|
try {
|
|
510
710
|
res = await Promise.race([
|
|
511
|
-
call({ method: m.method, path: m.path, body: m.body ?? null, session: { kind: 'remote', device: c.did, name: dev.name, act: dev.act === true } }),
|
|
711
|
+
call({ method: m.method, path: m.path, body: signed ? signed.body : m.body ?? null, session: { kind: 'remote', device: c.did, name: dev.name, act: dev.act === true, talk: talks, ...(signed && { uv: true, proof: signed.proof }) } }),
|
|
512
712
|
new Promise(r => { timer = setTimeout(() => r({ status: 504, json: { error: 'dibs took too long to answer' } }), CALL_TIME); }),
|
|
513
713
|
]);
|
|
514
714
|
} catch (e) { res = { status: e.status || 500, json: { error: e.status ? e.message : 'dibs hit a bug answering that' } }; }
|
|
@@ -550,6 +750,12 @@ export function relayTokens(w = load(), t = now()) {
|
|
|
550
750
|
return { t: 'tokens', h, p: w.pairs.filter(p => p.exp > t && typeof p.th === 'string').map(p => p.th), c: w.mcp ? mcpCodes().slice(-MAX_CODES) : [] };
|
|
551
751
|
}
|
|
552
752
|
|
|
753
|
+
// The sealed boxes of open links' codes, by drop name, for the relay to hand to whoever types
|
|
754
|
+
// the code (see CROCKFORD above). Sent apart from the tokens, which have a size limit of their own.
|
|
755
|
+
export function relayDrops(w = load(), t = now()) {
|
|
756
|
+
return { t: 'drops', d: w.pairs.filter(p => p.exp > t && typeof p.cr === 'string' && typeof p.cb === 'string' && p.ca !== 'taken').map(p => ({ r: p.cr, b: p.cb, exp: p.exp })) };
|
|
757
|
+
}
|
|
758
|
+
|
|
553
759
|
function status(state, extra = {}) {
|
|
554
760
|
try {
|
|
555
761
|
const tmp = `${STATUS}.${process.pid}`;
|
|
@@ -657,19 +863,27 @@ export function connectOnce(base, k, call) {
|
|
|
657
863
|
let ws;
|
|
658
864
|
try { ws = new WebSocket(url); } catch (e) { return resolve(e.message); }
|
|
659
865
|
ws.binaryType = 'arraybuffer';
|
|
660
|
-
let authed = false, lastHeard = now(), done = false, sentTokens = '';
|
|
866
|
+
let authed = false, lastHeard = now(), done = false, sentTokens = '', sentDrops = '';
|
|
661
867
|
const finish = why => { if (done) return; done = true; clearInterval(beat); clearInterval(watch); clearInterval(approvals); peer.closeAll(); try { ws.close(); } catch {} resolve(why); };
|
|
662
868
|
// The relay's list of who may connect follows relay.json within a second: a new link opens
|
|
663
869
|
// the pairing pool, a pairing adds a hash, a revoke removes one (and its open sessions end).
|
|
664
870
|
const syncTokens = () => {
|
|
665
871
|
if (!authed || ws.readyState !== 1) return;
|
|
666
|
-
const
|
|
872
|
+
const w = load();
|
|
873
|
+
const t = JSON.stringify(relayTokens(w)), d = JSON.stringify(relayDrops(w));
|
|
874
|
+
if (d !== sentDrops) { sentDrops = d; ws.send(d); }
|
|
667
875
|
if (t === sentTokens) return;
|
|
668
876
|
sentTokens = t;
|
|
669
877
|
ws.send(t);
|
|
670
878
|
peer.sweep();
|
|
671
879
|
};
|
|
672
|
-
|
|
880
|
+
// What reaches the person goes to their phones as notifications (src/push.mjs).
|
|
881
|
+
const notifier = pusher({ mid: k.mid, phones: pushPhones, forget: forgetPush, send: text => (authed && ws.readyState === 1 ? (ws.send(text), true) : false) });
|
|
882
|
+
let pushFailed = false;
|
|
883
|
+
const notify = () => {
|
|
884
|
+
try { notifier.tick(); pushFailed = false; } catch (e) { if (!pushFailed) log(`relay: notifications: ${e.message}`); pushFailed = true; }
|
|
885
|
+
};
|
|
886
|
+
const watch = setInterval(() => { syncTokens(); notify(); }, TOKEN_SYNC);
|
|
673
887
|
// Browsers of this Mac's accounts waiting for its key: asked for every few seconds, only
|
|
674
888
|
// while this Mac belongs to an account.
|
|
675
889
|
// eph.conn names this connection in relay.json, so dibs connect --approve can tell when the
|
|
@@ -711,6 +925,8 @@ export function connectOnce(base, k, call) {
|
|
|
711
925
|
if (m.t === 'http' && typeof m.id === 'string') {
|
|
712
926
|
return mcpAnswer(m, k).catch(() => offJson(500)).then(r => { if (ws.readyState === 1) ws.send(httpRes(m.id, r)); });
|
|
713
927
|
}
|
|
928
|
+
if (m.t === 'push-res') { try { notifier.answer(m); } catch (e) { log(`relay: couldn't forget a dead notification token: ${e.message}`); } return; }
|
|
929
|
+
if (m.t === 'drops-res') { try { dropsAck(m); } catch (e) { log(`relay: couldn't note which codes the relay took: ${e.message}`); } return; }
|
|
714
930
|
if (m.t === 'open' && unb64u(m.ch, 16)) return peer.open(m.ch);
|
|
715
931
|
if (m.t === 'gone' && unb64u(m.ch, 16)) return peer.gone(m.ch);
|
|
716
932
|
return;
|
|
@@ -728,15 +944,34 @@ export function connectOnce(base, k, call) {
|
|
|
728
944
|
const ago = t => (t ? `${dur(now() - t)} ago` : 'never');
|
|
729
945
|
|
|
730
946
|
// The remote half of `dibs pair`: --remote [--allow-actions], and its rows in --list and --revoke.
|
|
731
|
-
export function pairRemote({ act = false } = {}) {
|
|
732
|
-
const p = newPairing({ act });
|
|
733
|
-
logChange('pair remote', { actions: act });
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
console.log(act ? 'It can act: boost, pause, resume and stop jobs, cap an agent, set the pace, cancel scheduled runs. Never message agents, answer their questions, or change the hook or your hours. Revoke it if the device is lost.'
|
|
738
|
-
: 'It can only look. To let a browser change things too: dibs pair --remote --allow-actions');
|
|
947
|
+
export async function pairRemote({ act = false, talk = false, person = null } = {}) {
|
|
948
|
+
const p = newPairing({ act, talk, person });
|
|
949
|
+
logChange('pair remote', { actions: p.act, ...(talk && { talk: true }), ...(person && { person }) });
|
|
950
|
+
// The code is shown only once the relay has taken it, so the one printed works. Another Mac
|
|
951
|
+
// holding the same drop name gets a fresh code for the same link; no answer from the relay
|
|
952
|
+
// (it's slow, or the connector isn't running) prints the code with a warning.
|
|
739
953
|
const s = statusLine();
|
|
954
|
+
const connected = !!s?.startsWith('connected');
|
|
955
|
+
let code = p.code, ack = connected ? await codeAck(p.pid, code) : null;
|
|
956
|
+
for (let i = 1; ack === 'taken' && i < CODE_TRIES; i++) {
|
|
957
|
+
code = recode(p.pid, p.frag);
|
|
958
|
+
ack = code ? await codeAck(p.pid, code) : 'gone';
|
|
959
|
+
}
|
|
960
|
+
const page = PAGE.replace(/^https?:\/\//, '').replace(/\/$/, '');
|
|
961
|
+
if (ack === 'taken') {
|
|
962
|
+
console.log(`${render(qr(p.link))}\n`);
|
|
963
|
+
console.log(`Scan the QR code with your phone. Its code clashed with another Mac's at the relay, so there's none to type this time: run dibs pair --remote again for one.`);
|
|
964
|
+
} else {
|
|
965
|
+
console.log(`${render(qr(p.link))}\nCode: ${code}\n`);
|
|
966
|
+
console.log(`Scan the QR code with your phone, or type the code at ${page}.`);
|
|
967
|
+
if (connected && !ack) console.log(`The relay hasn't confirmed the code yet, so it may not work. The QR code works either way.`);
|
|
968
|
+
}
|
|
969
|
+
console.log(`It works once, until ${clockOf(p.exp)} (${p.life / MIN} minutes). That browser checks it reached this Mac by its fingerprint ${p.fp.slice(0, 16)}...`);
|
|
970
|
+
console.log(`The QR code as a link:\n${p.link}\n`);
|
|
971
|
+
console.log(talk ? 'It can talk: message agents and answer their questions, asking for Face ID (or the passcode) on that phone every time. Agents read those as from you, via that phone. It can also act: boost, pause, resume and stop jobs, cap an agent, set the pace, cancel scheduled runs. Never change the hook or your hours. Revoke it at once if the phone is lost.'
|
|
972
|
+
: act ? 'It can act: boost, pause, resume and stop jobs, cap an agent, set the pace, cancel scheduled runs. Never message agents, answer their questions, or change the hook or your hours. Revoke it if the device is lost.'
|
|
973
|
+
: 'It can only look. To let a browser change things too: dibs pair --remote --allow-actions');
|
|
974
|
+
if (person) console.log(`\nIt's ${person}'s phone: it hears about ${person}'s agents and what's everyone's (dibs people).`);
|
|
740
975
|
if (!s || s.startsWith('not running')) console.log(`\nThis Mac isn't connected to the relay yet. Turn it on: dibs service install relay`);
|
|
741
976
|
}
|
|
742
977
|
// dibs connect --account: a link a browser signed in to a dibs account opens, to add this Mac to
|
|
@@ -755,10 +990,11 @@ export function pairAccount({ act = false } = {}) {
|
|
|
755
990
|
}
|
|
756
991
|
const clockOf = t => new Date(t).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
|
|
757
992
|
|
|
993
|
+
export const level = d => (d.talk === true && d.tk ? 'can talk (Face ID each time) and act' : d.act === true ? 'can act' : 'look only');
|
|
758
994
|
export function listRemote() {
|
|
759
995
|
const ds = devices();
|
|
760
996
|
if (load().mcp) console.log(`(${mcpLine()})`);
|
|
761
|
-
for (const d of ds) console.log(`${d.id.slice(0, 8)} ${d.acct ? 'account' : 'remote'}: ${d.name}, ${d
|
|
997
|
+
for (const d of ds) console.log(`${d.id.slice(0, 8)} ${d.acct ? 'account' : 'remote'}: ${d.name}, ${level(d)} paired ${new Date(d.created).toLocaleString()}, last connected ${ago(d.seen)}`);
|
|
762
998
|
const accts = Object.entries(load().accounts);
|
|
763
999
|
for (const [aid, a] of accts) console.log(`${aid.slice(0, 8)} dibs account${a.label && a.label !== 'a browser' ? ` ${a.label}` : ''}: this Mac holds its key and approves its new browsers (dibs connect --approve) joined ${new Date(a.joined).toLocaleString()}`);
|
|
764
1000
|
const wait = waitingApprovals();
|