clavarium 0.2.62-next.1 → 0.2.63-next.1

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.
@@ -33,6 +33,13 @@ if [ -f "$chat/server.mjs" ] && command -v docket-mcp >/dev/null 2>&1 && ! grep
33
33
  claude mcp add --scope user docket -- docket-mcp --dir "$docket" >/dev/null 2>&1 \
34
34
  || echo "launch: Docket was not given to Claude Code as tools: the command docket still works" >&2
35
35
  fi
36
+ # ITS TETHER AS ITS OWN TOOLS (MCP): the accesses it was given -- a mailbox, a calendar, an address
37
+ # book, an online folder, a machine over SSH. The server holds the keys; it acts within its rights.
38
+ tether="/work/.tether"
39
+ if command -v tether-mcp >/dev/null 2>&1 && ! grep -q "\"$tether\"" "$HOME/.claude.json" 2>/dev/null; then
40
+ claude mcp add --scope user tether -- tether-mcp --dir "$tether" >/dev/null 2>&1 \
41
+ || echo "launch: Tether was not given to Claude Code as tools: the command tether still works" >&2
42
+ fi
36
43
  # ITS PULSE: Claude Code's own hooks say to the chat that it acts, and when its turn ends, so that
37
44
  # the person sees "Working..." while it works without a word (parley pulse; nothing posted).
38
45
  if [ -f "$chat/server.mjs" ]; then
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.62-next.1",
3
+ "version": "0.2.63-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.62-next.1",
9
+ "version": "0.2.63-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -14,6 +14,7 @@
14
14
  "clavarium-binder": "0.1.8-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
16
  "clavarium-parley": "0.17.9-next.1",
17
+ "clavarium-tether": "0.1.0-next.5",
17
18
  "mermaid": "11.17.2",
18
19
  "node-pty": "^1.1.0",
19
20
  "pdfjs-dist": "6.4.299",
@@ -654,6 +655,15 @@
654
655
  "url": "https://github.com/chalk/ansi-styles?sponsor=1"
655
656
  }
656
657
  },
658
+ "node_modules/asn1": {
659
+ "version": "0.2.6",
660
+ "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
661
+ "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
662
+ "license": "MIT",
663
+ "dependencies": {
664
+ "safer-buffer": "~2.1.0"
665
+ }
666
+ },
657
667
  "node_modules/asn1.js": {
658
668
  "version": "5.4.1",
659
669
  "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz",
@@ -666,6 +676,15 @@
666
676
  "safer-buffer": "^2.1.0"
667
677
  }
668
678
  },
679
+ "node_modules/bcrypt-pbkdf": {
680
+ "version": "1.0.2",
681
+ "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
682
+ "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
683
+ "license": "BSD-3-Clause",
684
+ "dependencies": {
685
+ "tweetnacl": "^0.14.3"
686
+ }
687
+ },
669
688
  "node_modules/bn.js": {
670
689
  "version": "4.12.5",
671
690
  "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.5.tgz",
@@ -678,6 +697,15 @@
678
697
  "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
679
698
  "license": "BSD-3-Clause"
680
699
  },
700
+ "node_modules/buildcheck": {
701
+ "version": "0.0.7",
702
+ "resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz",
703
+ "integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==",
704
+ "optional": true,
705
+ "engines": {
706
+ "node": ">=10.0.0"
707
+ }
708
+ },
681
709
  "node_modules/camelcase": {
682
710
  "version": "5.3.1",
683
711
  "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
@@ -726,6 +754,22 @@
726
754
  "node": ">=22"
727
755
  }
728
756
  },
757
+ "node_modules/clavarium-tether": {
758
+ "version": "0.1.0-next.5",
759
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.5.tgz",
760
+ "integrity": "sha512-umwPP9HsoBGzFbQSoExWjOQnvodeGZGAzM6e2VpXIUJDx3GtTVR/UyVr40ojOziTkjJ5czH5ds/xb5dFuk/OBw==",
761
+ "license": "MIT",
762
+ "dependencies": {
763
+ "ssh2": "1.17.0"
764
+ },
765
+ "bin": {
766
+ "tether": "bin/cli.mjs",
767
+ "tether-mcp": "server/mcp.mjs"
768
+ },
769
+ "engines": {
770
+ "node": ">=22"
771
+ }
772
+ },
729
773
  "node_modules/cliui": {
730
774
  "version": "6.0.0",
731
775
  "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
@@ -773,6 +817,20 @@
773
817
  "layout-base": "^1.0.0"
774
818
  }
775
819
  },
820
+ "node_modules/cpu-features": {
821
+ "version": "0.0.10",
822
+ "resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
823
+ "integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",
824
+ "hasInstallScript": true,
825
+ "optional": true,
826
+ "dependencies": {
827
+ "buildcheck": "~0.0.6",
828
+ "nan": "^2.19.0"
829
+ },
830
+ "engines": {
831
+ "node": ">=10.0.0"
832
+ }
833
+ },
776
834
  "node_modules/cytoscape": {
777
835
  "version": "3.34.4",
778
836
  "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.34.4.tgz",
@@ -1598,6 +1656,13 @@
1598
1656
  "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
1599
1657
  "license": "MIT"
1600
1658
  },
1659
+ "node_modules/nan": {
1660
+ "version": "2.30.0",
1661
+ "resolved": "https://registry.npmjs.org/nan/-/nan-2.30.0.tgz",
1662
+ "integrity": "sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==",
1663
+ "license": "MIT",
1664
+ "optional": true
1665
+ },
1601
1666
  "node_modules/node-addon-api": {
1602
1667
  "version": "7.1.1",
1603
1668
  "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",
@@ -1805,6 +1870,23 @@
1805
1870
  "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
1806
1871
  "license": "ISC"
1807
1872
  },
1873
+ "node_modules/ssh2": {
1874
+ "version": "1.17.0",
1875
+ "resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
1876
+ "integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
1877
+ "hasInstallScript": true,
1878
+ "dependencies": {
1879
+ "asn1": "^0.2.6",
1880
+ "bcrypt-pbkdf": "^1.0.2"
1881
+ },
1882
+ "engines": {
1883
+ "node": ">=10.16.0"
1884
+ },
1885
+ "optionalDependencies": {
1886
+ "cpu-features": "~0.0.10",
1887
+ "nan": "^2.23.0"
1888
+ }
1889
+ },
1808
1890
  "node_modules/strictdom": {
1809
1891
  "version": "1.0.1",
1810
1892
  "resolved": "https://registry.npmjs.org/strictdom/-/strictdom-1.0.1.tgz",
@@ -1861,6 +1943,12 @@
1861
1943
  "node": ">=6.10"
1862
1944
  }
1863
1945
  },
1946
+ "node_modules/tweetnacl": {
1947
+ "version": "0.14.5",
1948
+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
1949
+ "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
1950
+ "license": "Unlicense"
1951
+ },
1864
1952
  "node_modules/uuid": {
1865
1953
  "version": "14.0.3",
1866
1954
  "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.3.tgz",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.62-next.1",
3
+ "version": "0.2.63-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
@@ -47,6 +47,7 @@
47
47
  "clavarium-binder": "0.1.8-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
49
  "clavarium-parley": "0.17.9-next.1",
50
+ "clavarium-tether": "0.1.0-next.5",
50
51
  "mermaid": "11.17.2",
51
52
  "node-pty": "^1.1.0",
52
53
  "pdfjs-dist": "6.4.299",
@@ -0,0 +1,130 @@
1
+ /* CONNECTING AN ACCOUNT BY TOKEN: a mailbox, a calendar, an address book of a
2
+ * Google or Microsoft account, reached live through Tether -- not copied into a
3
+ * folder (that is the older mailbox.mjs, kept until this replaces it).
4
+ *
5
+ * THE TOKEN NEVER ENTERS A MACHINE. The person allows the account in their own
6
+ * browser; the code comes back here; this server trades it for a long-lived
7
+ * refresh token and keeps it as a HOST-ONLY secret (secrets.mjs): a secret that
8
+ * cannot be attached to a conversation, so it is never delivered to a VM. The
9
+ * agent is root in its machine, so a token in the machine would be a token lost;
10
+ * instead the keeper reveals it to the connector alone, host-side, and acts on
11
+ * the agent's behalf within the level and rules the person set.
12
+ *
13
+ * ONE ACCOUNT, ONE TOKEN, SEVERAL TARGETS. A Google consent for mail+calendar+
14
+ * contacts yields a single refresh token; this makes one host-only secret and a
15
+ * Tether target per kind, each naming that secret. Microsoft's Thunderbird client
16
+ * carries only the mail scope here, so a Microsoft consent makes the mail target
17
+ * alone (calendar and files over Graph need a deployment's own OAuth app, added
18
+ * later as config.clientId + an own client secret).
19
+ *
20
+ * A CREATED TARGET IS GIVEN TO NO ONE. The person grants it per conversation, at
21
+ * its own level, from the page (Assets > Access) -- like git: one mailbox, many
22
+ * conversations, each its own rights.
23
+ */
24
+ import { Refusal } from './conversations.mjs';
25
+ import { createHash } from 'node:crypto';
26
+ import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, pkcePair, newState, PROVIDERS } from './oauth.mjs';
27
+
28
+ /* The loopback the provider sends the code back to; nothing listens there. The
29
+ person's browser lands on a page that will not load, and they copy the whole
30
+ address -- which carries the code -- back into Clavarium. Desktop OAuth clients
31
+ accept any 127.0.0.1 port, and the same address trades the code, so it only has
32
+ to stay constant. (Shared, on purpose, with the older file-copy mailbox.) */
33
+ const REDIRECT = 'http://127.0.0.1:47813/';
34
+ const PENDING_MS = 10 * 60_000;
35
+ const PENDING_MAX = 20;
36
+
37
+ /* The kinds a provider can be connected for here, with the connector and the
38
+ Tether kind each becomes, and whether the target needs the email address. */
39
+ const KIND = {
40
+ mail: { connector: 'mail', kind: 'mail', title: 'Mail', needsUser: true },
41
+ calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: false },
42
+ contacts: { connector: 'contacts', kind: 'contacts', title: 'Contacts', needsUser: true },
43
+ };
44
+ /* What each provider's built-in (Thunderbird) client grants a refresh token for. */
45
+ const SUPPORTED = { google: ['mail', 'calendar', 'contacts'], microsoft: ['mail'] };
46
+
47
+ const emailOk = (s) => /^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{2,}$/.test(s);
48
+ /* A deterministic, valid secret name for an account's token: a short slug of the
49
+ address plus a hash of it, so reconnecting the same account reuses the name
50
+ (its value is replaced) and two different accounts never collide. */
51
+ function secretName(provider, user) {
52
+ const slug = user.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 8).replace(/_+$/, '') || 'X';
53
+ const hex = createHash('sha256').update(`${provider}:${user}`).digest('hex').slice(0, 6).toUpperCase();
54
+ return `OAUTH_${provider.toUpperCase()}_${slug}_${hex}`;
55
+ }
56
+ /* A stable target id per account and kind. */
57
+ const targetId = (kind, provider, user) => `${kind}-${provider}-${user.toLowerCase().normalize('NFD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`.slice(0, 60);
58
+
59
+ export class Accounts {
60
+ #secrets; #targets; #fetch; #pending = new Map();
61
+
62
+ /* `secrets`: the vault (set host-only, by name). `targets`: { put(spec) } onto
63
+ the Tether store. `fetch`: injected for tests. */
64
+ constructor({ secrets, targets, fetch = globalThis.fetch }) {
65
+ if (!secrets?.set) throw new Error('accounts needs the secret store');
66
+ if (!targets?.put) throw new Error('accounts needs the Tether target store');
67
+ this.#secrets = secrets; this.#targets = targets; this.#fetch = fetch;
68
+ }
69
+
70
+ /* Which kinds may be connected, per provider, for the page to offer. */
71
+ supported() { return { ...SUPPORTED }; }
72
+
73
+ /* Start a connection: build the provider's consent page for the kinds asked,
74
+ and keep the state and PKCE verifier until the person pastes the address. */
75
+ consent({ provider, user, kinds } = {}) {
76
+ const prov = String(provider ?? '');
77
+ if (!PROVIDERS[prov] || !SUPPORTED[prov]) throw new Refusal(400, 'Choose Google or Microsoft.');
78
+ const address = String(user ?? '').trim();
79
+ if (!emailOk(address)) throw new Refusal(400, 'The account needs its email address.');
80
+ const wanted = (Array.isArray(kinds) && kinds.length ? kinds : ['mail']).map(String);
81
+ const chosen = SUPPORTED[prov].filter((k) => wanted.includes(k));
82
+ if (!chosen.length) throw new Refusal(400, `${PROVIDERS[prov].label} can be connected here for: ${SUPPORTED[prov].join(', ')}.`);
83
+ this.#sweep();
84
+ if (this.#pending.size >= PENDING_MAX) throw new Refusal(429, 'Too many connections in progress; try again shortly.');
85
+ const { clientId } = thunderbird(prov);
86
+ const state = newState();
87
+ const { verifier, challenge } = pkcePair();
88
+ const url = consentUrl(prov, { clientId, redirectUri: REDIRECT, scope: scopeFor(prov, chosen), state, codeChallenge: challenge, loginHint: address });
89
+ this.#pending.set(state, { provider: prov, user: address, kinds: chosen, verifier, at: Date.now() });
90
+ return { url };
91
+ }
92
+
93
+ /* Finish it: from the pasted address read the code, trade it for a refresh
94
+ token, keep the token host-side, and make a Tether target per kind. */
95
+ async connect({ redirected } = {}) {
96
+ this.#sweep();
97
+ let state;
98
+ try { state = new URL(String(redirected ?? '').trim()).searchParams.get('state'); } catch { throw new Refusal(400, 'Paste the whole address from the bar, after you allow.'); }
99
+ const p = state && this.#pending.get(state);
100
+ if (!p) throw new Refusal(400, 'This connection has expired or was already used; start it again.');
101
+ this.#pending.delete(state);
102
+ let code;
103
+ try { code = extractCode(redirected, { state }); } catch (e) { throw new Refusal(400, e.message); }
104
+ const { clientId, clientSecret } = thunderbird(p.provider);
105
+ let refreshToken;
106
+ try { ({ refreshToken } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: REDIRECT, code, codeVerifier: p.verifier, fetch: this.#fetch })); }
107
+ catch (e) { throw new Refusal(502, `The connection could not be completed: ${e.message}`); }
108
+ if (!refreshToken) throw new Refusal(502, 'The account returned no lasting token; allow offline access and try again.');
109
+ /* The token is kept host-only: it can never be attached to a conversation,
110
+ so it is never delivered to a machine -- the keeper reveals it by name. */
111
+ const name = secretName(p.provider, p.user);
112
+ this.#secrets.set({ name, value: refreshToken, hostOnly: true });
113
+ const label = PROVIDERS[p.provider].label;
114
+ const made = [];
115
+ for (const k of p.kinds) {
116
+ const spec = KIND[k];
117
+ const config = { provider: p.provider };
118
+ if (spec.needsUser) config.user = p.user;
119
+ const target = this.#targets.put({
120
+ id: targetId(k, p.provider, p.user),
121
+ title: `${spec.title} — ${p.user} (${label})`,
122
+ kind: spec.kind, connector: spec.connector, config, secrets: { refresh: name },
123
+ });
124
+ made.push({ id: target?.id ?? targetId(k, p.provider, p.user), title: target?.title, kind: spec.kind });
125
+ }
126
+ return { provider: p.provider, user: p.user, targets: made };
127
+ }
128
+
129
+ #sweep() { const now = Date.now(); for (const [k, v] of this.#pending) if (now - v.at > PENDING_MS) this.#pending.delete(k); }
130
+ }
package/server/api.mjs CHANGED
@@ -146,7 +146,7 @@ function readBody(request, max = BODY_MAX) {
146
146
  }
147
147
 
148
148
  /* Returns true when the request was an API request (answered here). */
149
- export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral) {
149
+ export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts) {
150
150
  const { pathname } = new URL(request.url ?? '/', 'http://local');
151
151
  if (!pathname.startsWith('/api/')) return false;
152
152
  let send = (status, body) => {
@@ -241,6 +241,11 @@ export async function handleApi(request, response, conversations, headers, resou
241
241
  if (pathname === '/api/shortcuts' && shortcuts) return send(200, shortcuts.list()), true;
242
242
  if (pathname === '/api/secrets' && secrets) return send(200, secrets.list()), true;
243
243
  if (pathname === '/api/mailboxes' && mailboxes) return send(200, mailboxes.list()), true;
244
+ /* Which providers and kinds an account can be connected for here. */
245
+ if (pathname === '/api/accounts' && accounts) return send(200, { supported: accounts.supported() }), true;
246
+ /* Assets > Access: the targets, who was given each at which level, the
247
+ calls waiting, and the recent journal -- all the page needs to read. */
248
+ if (pathname === '/api/tether' && tethers) { const r = await tethers.act('state', { agent: query.get('agent') ?? undefined }, ''); return send(200, { given: tethers.given(), changes: tethers.changes(), ...(r.data ?? {}) }), true; }
244
249
  /* Every device, each with all it was given. */
245
250
  if (pathname === '/api/devices' && sharing) return send(200, sharing.devices.all()), true;
246
251
  if (pathname === '/api/git-keys' && gitAccess) return send(200, gitAccess.keys()), true;
@@ -408,8 +413,19 @@ export async function handleApi(request, response, conversations, headers, resou
408
413
  return send(200, { ok: true }), true;
409
414
  }
410
415
  if (pathname === '/api/mailboxes' && mailboxes) { const made = await mailboxes.add(body); void setup?.assetAdded(made.name).catch(() => {}); return send(201, made), true; }
416
+ if (pathname === '/api/mailboxes/consent' && mailboxes) return send(200, mailboxes.consent(body)), true;
417
+ if (pathname === '/api/mailboxes/connect' && mailboxes) { const made = await mailboxes.connect(body); void setup?.assetAdded(made.name).catch(() => {}); return send(201, made), true; }
411
418
  const fetched = /^\/api\/mailboxes\/([a-z0-9-]{1,32})\/sync$/.exec(pathname);
412
419
  if (fetched && mailboxes) return send(200, await mailboxes.sync(fetched[1])), true;
420
+ /* Connecting an account by token (consent in the owner's browser, the token
421
+ kept host-only, a Tether target made): see accounts.mjs. */
422
+ if (pathname === '/api/accounts/consent' && accounts) return send(200, accounts.consent(body)), true;
423
+ if (pathname === '/api/accounts/connect' && accounts) { const made = await accounts.connect(body); return send(201, made), true; }
424
+ /* Assets > Access: the owner sets a conversation's level and rules on a
425
+ target, decides a call that waited, or removes a target. Each is an op the
426
+ keeper runs as the owner (person), never as an agent. */
427
+ const tetherOp = /^\/api\/tether\/(level|allow|unallow|decide|remove-target|stop|resume)$/.exec(pathname);
428
+ if (tetherOp && tethers) { const r = await tethers.act(tetherOp[1], body, ''); if (!r.ok) throw new Refusal(400, r.text); return send(200, r.data ?? { ok: true }), true; }
413
429
  if (pathname === '/api/shortcuts' && shortcuts) return send(201, shortcuts.add(body)), true;
414
430
  if (pathname === '/api/secrets' && secrets) { const made = secrets.set(body); setup?.secretAdded(made.name); return send(201, made), true; }
415
431
  const reactSet = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
package/server/imap.mjs CHANGED
@@ -72,4 +72,20 @@ export class Exchange {
72
72
  if (!new RegExp(`^${tag} OK`, 'i').test(lines.at(-1) ?? '')) throw new Refusal(502, failure);
73
73
  return lines;
74
74
  }
75
+ /* AUTHENTICATE XOAUTH2 with the base64 SASL response given inline (initial
76
+ response, which Gmail and Outlook accept). On success the server answers the
77
+ tag with OK. On failure it first sends a `+ <base64 error>` challenge and
78
+ waits for an empty line before the tagged NO, so we finish that exchange and
79
+ then surface the refusal, rather than hang. */
80
+ async authenticateXoauth2(initial, failure) {
81
+ const tag = `c${++this.#n}`;
82
+ this.#socket.write(`${tag} AUTHENTICATE XOAUTH2 ${initial}\r\n`);
83
+ let lines = await this.#until((l) => l.startsWith(`${tag} `) || l.startsWith('+ '));
84
+ if ((lines.at(-1) ?? '').startsWith('+ ')) {
85
+ this.#socket.write('\r\n');
86
+ lines = await this.#until((l) => l.startsWith(`${tag} `));
87
+ }
88
+ if (!new RegExp(`^${tag} OK`, 'i').test(lines.at(-1) ?? '')) throw new Refusal(502, failure);
89
+ return lines;
90
+ }
75
91
  }
@@ -21,8 +21,18 @@ import { connect as tlsConnect } from 'node:tls';
21
21
  import { mkdirSync, readdirSync, writeFileSync, renameSync, rmSync, existsSync } from 'node:fs';
22
22
  import { Refusal } from './conversations.mjs';
23
23
  import { Exchange, quoted } from './imap.mjs';
24
- import { readSettings, TIMEOUT_MS } from './signin.mjs';
24
+ import { readSettings, oauthSettings, imapAuthenticate, PROVIDER_IMAP, TIMEOUT_MS } from './signin.mjs';
25
25
  import { isConversationName } from './names.mjs';
26
+ import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, pkcePair, newState } from './oauth.mjs';
27
+
28
+ /* The loopback address the provider sends the code back to. Nothing listens on it:
29
+ the person's browser lands there (a page that will not load), and they copy the
30
+ address -- which carries the code -- back into Clavarium. Desktop OAuth clients
31
+ (Thunderbird's) accept any 127.0.0.1 port, and the same address is used again to
32
+ trade the code, so it only has to be constant. */
33
+ const REDIRECT = 'http://127.0.0.1:47813/';
34
+ const PENDING_MS = 10 * 60_000;
35
+ const PENDING_MAX = 20;
26
36
 
27
37
  export const MESSAGES = 50;
28
38
  /* A message is kept up to this size; a longer one is cut (its text comes first). */
@@ -33,13 +43,13 @@ const SYNC_TIMEOUT_MS = TIMEOUT_MS * 6;
33
43
  /* ---------- reading ---------- */
34
44
 
35
45
  /* The most recent messages, oldest first: [{ uid, receivedAt, raw }]. */
36
- export async function recentMessages(settings, { connect = tlsConnect, ca, limit = MESSAGES } = {}) {
46
+ export async function recentMessages(settings, { connect = tlsConnect, ca, limit = MESSAGES, fetch: fetchImpl = globalThis.fetch } = {}) {
37
47
  const socket = connect({ host: settings.host, port: settings.port, servername: settings.host, ...(ca ? { ca } : {}) });
38
48
  const timer = setTimeout(() => socket.destroy(new Error('timeout')), SYNC_TIMEOUT_MS);
39
49
  try {
40
50
  const imap = new Exchange(socket, limit * (MESSAGE_BYTES + 4096) + 2_000_000);
41
51
  await imap.greeting();
42
- await imap.command(`LOGIN ${quoted(settings.user)} ${quoted(settings.password)}`, 'The mailbox refused the user or the password.');
52
+ await imapAuthenticate(imap, settings, { fetch: fetchImpl });
43
53
  await imap.command('EXAMINE INBOX', 'The inbox could not be opened.');
44
54
  const found = await imap.command('UID SEARCH ALL', 'The mailbox could not be searched.');
45
55
  const uids = (found.find((l) => /^\* SEARCH/i.test(l)) ?? '').split(' ').slice(2).map(Number).filter((n) => Number.isInteger(n) && n > 0).slice(-limit);
@@ -115,13 +125,13 @@ export function writeFolder(folder, user, messages) {
115
125
  /* ---------- the mailboxes kept ---------- */
116
126
 
117
127
  export class Mailboxes {
118
- #store; #vault; #resources; #reader; #busy = new Set();
128
+ #store; #vault; #resources; #reader; #fetch; #pending = new Map(); #busy = new Set();
119
129
 
120
- constructor({ store, vault, resources, reader = recentMessages }) { this.#store = store; this.#vault = vault; this.#resources = resources; this.#reader = reader; }
130
+ constructor({ store, vault, resources, reader = recentMessages, fetch = globalThis.fetch }) { this.#store = store; this.#vault = vault; this.#resources = resources; this.#reader = reader; this.#fetch = fetch; }
121
131
 
122
132
  /* What the page may know. Never the password. */
123
133
  list() {
124
- return this.#store.all().map((m) => ({ name: m.name, host: m.host, port: m.port ?? 993, user: m.user, messages: m.messages ?? 0, syncedAt: m.syncedAt ?? null, failure: m.failure ?? null }));
134
+ return this.#store.all().map((m) => ({ name: m.name, host: m.host, port: m.port ?? 993, user: m.user, provider: m.provider ?? null, messages: m.messages ?? 0, syncedAt: m.syncedAt ?? null, failure: m.failure ?? null }));
125
135
  }
126
136
 
127
137
  /* Adds a mailbox after proving it can be read, as a folder of that name. */
@@ -129,14 +139,53 @@ export class Mailboxes {
129
139
  const name = String(body?.name ?? '');
130
140
  if (!isConversationName(name)) throw new Refusal(400, 'A name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter and does not end with a hyphen.');
131
141
  if (this.#resources.list().some((r) => r.name === name)) throw new Refusal(409, 'A folder already has this name.');
132
- const settings = readSettings(body);
142
+ const settings = body?.provider ? oauthSettings(body) : readSettings(body);
133
143
  const messages = await this.#reader(settings);
134
144
  await this.#resources.create({ name, type: 'mailbox' });
135
- this.#store.put({ name, host: settings.host, port: settings.port, user: settings.user, sealed: this.#vault.seal(settings.password) });
145
+ this.#store.put({ name, host: settings.host, port: settings.port, user: settings.user, provider: settings.provider, sealed: this.#vault.seal(settings.password) });
136
146
  this.#write(name, settings.user, messages);
137
147
  return this.list().find((m) => m.name === name);
138
148
  }
139
149
 
150
+ /* Start connecting a mailbox by token: build the provider's consent page and
151
+ keep the state and PKCE verifier until the person pastes the address back. */
152
+ consent({ name, provider, user }) {
153
+ const nm = String(name ?? '');
154
+ if (!isConversationName(nm)) throw new Refusal(400, 'A name is 1 to 32 lower-case letters, digits or hyphens; it starts with a letter and does not end with a hyphen.');
155
+ if (this.#resources.list().some((r) => r.name === nm)) throw new Refusal(409, 'A folder already has this name.');
156
+ if (!PROVIDER_IMAP[String(provider ?? '')]) throw new Refusal(400, 'Choose Gmail or Microsoft.');
157
+ const address = String(user ?? '').trim();
158
+ if (address === '' || address.length > 200) throw new Refusal(400, 'The mailbox needs its email address.');
159
+ this.#sweepPending();
160
+ if (this.#pending.size >= PENDING_MAX) throw new Refusal(429, 'Too many connections in progress; try again shortly.');
161
+ const { clientId } = thunderbird(provider);
162
+ const state = newState();
163
+ const { verifier, challenge } = pkcePair();
164
+ const url = consentUrl(provider, { clientId, redirectUri: REDIRECT, scope: scopeFor(provider, ['mail']), state, codeChallenge: challenge, loginHint: address });
165
+ this.#pending.set(state, { name: nm, provider: String(provider), user: address, verifier, at: Date.now() });
166
+ return { url };
167
+ }
168
+
169
+ /* Finish it: from the pasted address, read the code, trade it for a refresh
170
+ token, and add the mailbox (which proves it can be read). */
171
+ async connect({ redirected }) {
172
+ this.#sweepPending();
173
+ let state;
174
+ try { state = new URL(String(redirected ?? '').trim()).searchParams.get('state'); } catch { throw new Refusal(400, 'Paste the whole address from the bar, after you allow.'); }
175
+ const p = state && this.#pending.get(state);
176
+ if (!p) throw new Refusal(400, 'This connection has expired or was already used; start it again.');
177
+ this.#pending.delete(state);
178
+ let code;
179
+ try { code = extractCode(redirected, { state }); } catch (e) { throw new Refusal(400, e.message); }
180
+ const { clientId, clientSecret } = thunderbird(p.provider);
181
+ let refreshToken;
182
+ try { ({ refreshToken } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: REDIRECT, code, codeVerifier: p.verifier, fetch: this.#fetch })); }
183
+ catch (e) { throw new Refusal(502, `The connection could not be completed: ${e.message}`); }
184
+ return this.add({ name: p.name, provider: p.provider, user: p.user, refresh: refreshToken });
185
+ }
186
+
187
+ #sweepPending() { const now = Date.now(); for (const [k, v] of this.#pending) if (now - v.at > PENDING_MS) this.#pending.delete(k); }
188
+
140
189
  #write(name, user, messages) {
141
190
  writeFolder(this.#resources.folder(name), user, messages);
142
191
  this.#store.patch(name, { messages: messages.length, syncedAt: new Date().toISOString(), failure: undefined });
@@ -150,7 +199,7 @@ export class Mailboxes {
150
199
  if (this.#busy.has(name)) return this.list().find((x) => x.name === name);
151
200
  this.#busy.add(name);
152
201
  try {
153
- const messages = await this.#reader({ host: m.host, port: m.port, user: m.user, password: this.#vault.open(m.sealed) });
202
+ const messages = await this.#reader({ host: m.host, port: m.port, user: m.user, provider: m.provider, password: this.#vault.open(m.sealed) });
154
203
  this.#write(name, m.user, messages);
155
204
  } catch (error) {
156
205
  this.#store.patch(name, { failure: error instanceof Refusal ? error.message : 'The mailbox could not be read.' });
package/server/main.mjs CHANGED
@@ -67,6 +67,8 @@ import { MachinesMove } from './machinesmove.mjs';
67
67
  import { Wifi } from './wifi.mjs';
68
68
  import { MeshCentral } from './meshcentral.mjs';
69
69
  import { Binders } from './binders.mjs';
70
+ import { Tethers } from './tethers.mjs';
71
+ import { Accounts } from './accounts.mjs';
70
72
  import { ServerLogs } from './serverlogs.mjs';
71
73
  import { History, STEP_MS as HISTORY_STEP_MS } from './history.mjs';
72
74
  import { Events } from './events.mjs';
@@ -155,7 +157,7 @@ const withoutTmux = (env) => Object.fromEntries(Object.entries(env).filter(([key
155
157
 
156
158
  const REFUSED = 'This Clavarium belongs to someone else: your account is not one of its operators.\n';
157
159
 
158
- function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral } = {}) {
160
+ function serve(port, conversations, resources, { gate = () => 'local', originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, repair, capacity, updates, instance = new Instance(), certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts } = {}) {
159
161
  /* Its manifest carries the name of this Clavarium, or the one a device chose (instance.mjs). */
160
162
  const sendManifest = (response, url) => response.writeHead(200, { ...HEADERS, 'content-type': 'application/manifest+json' }).end(instance.manifest(new URL(url ?? '/', 'http://local').searchParams.get('name') ?? undefined));
161
163
  const sendFile = async (response, file) => {
@@ -198,7 +200,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
198
200
  response.writeHead(403, { ...HEADERS, 'content-type': 'text/plain; charset=utf-8' }).end(REFUSED);
199
201
  return;
200
202
  }
201
- if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral)) return;
203
+ if (conversations && await handleApi(request, response, conversations, HEADERS, resources, originOk, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts)) return;
202
204
  if (pathname === '/manifest.webmanifest' && request.method === 'GET') { sendManifest(response, request.url); return; }
203
205
  const file = FILES[pathname];
204
206
  if (!file || (request.method !== 'GET' && request.method !== 'HEAD')) {
@@ -398,6 +400,15 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
398
400
  const binders = new Binders({ dataDir, resources: folders, conversations: () => all.list().map((c) => c.name), dockets, team,
399
401
  alert: (message) => alerts.tell({ ...message, title: `${instance.name()}: ${message.title}` }) });
400
402
  const stopBinders = binders.start();
403
+ /* The accesses an agent was given -- a machine over SSH, an online folder, a
404
+ mailbox, a calendar, an address book -- held here with their secrets read from
405
+ the vault by name, never in a machine: see tethers.mjs. */
406
+ const tethers = new Tethers({ dataDir, resources: folders, conversations: () => all.list().map((c) => c.name), secrets });
407
+ const stopTethers = tethers.start();
408
+ /* Connecting a mailbox, calendar or address book by token: the consent happens
409
+ in the owner's browser, the refresh token is kept host-only (never in a
410
+ machine) and a Tether target is made for it: see accounts.mjs. */
411
+ const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec) } });
401
412
  /* A repository's origin kept up to date, checks run in the machine, and
402
413
  automatic sending to the branches the owner listed: see gitkeeper.mjs. */
403
414
  /* What could not be read is told to the agents that write in the repository, where they can act. */
@@ -520,8 +531,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
520
531
  void team.refresh().catch((error) => console.error(`operators: ${error.message}`));
521
532
  const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
522
533
  }
523
- const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
524
- server.on('close', () => { closing = true; stopBinders(); clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
534
+ const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
535
+ server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
525
536
  let closing = false;
526
537
  bridge = attachBridge(server, {
527
538
  onRejoin: (name) => all.rejoin(name),