clavarium 0.2.46-beta.1 → 0.2.47-beta.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.46-beta.1",
3
+ "version": "0.2.47-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.46-beta.1",
9
+ "version": "0.2.47-beta.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.46-beta.1",
3
+ "version": "0.2.47-beta.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;
@@ -412,6 +417,15 @@ export async function handleApi(request, response, conversations, headers, resou
412
417
  if (pathname === '/api/mailboxes/connect' && mailboxes) { const made = await mailboxes.connect(body); void setup?.assetAdded(made.name).catch(() => {}); return send(201, made), true; }
413
418
  const fetched = /^\/api\/mailboxes\/([a-z0-9-]{1,32})\/sync$/.exec(pathname);
414
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; }
415
429
  if (pathname === '/api/shortcuts' && shortcuts) return send(201, shortcuts.add(body)), true;
416
430
  if (pathname === '/api/secrets' && secrets) { const made = secrets.set(body); setup?.secretAdded(made.name); return send(201, made), true; }
417
431
  const reactSet = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
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),
package/server/parley.mjs CHANGED
@@ -22,6 +22,7 @@ export const APP = fileURLToPath(new URL('..', import.meta.url));
22
22
  export const PARLEY = 'clavarium-parley';
23
23
  export const DOCKET = 'clavarium-docket';
24
24
  export const BINDER = 'clavarium-binder';
25
+ export const TETHER = 'clavarium-tether';
25
26
  /* THE TOOLS EVERY MACHINE IS GIVEN, each an npm dependency at an exact version, as Parley is:
26
27
  installed by this server in every machine (toolbox.mjs), from its archive here. `usage`
27
28
  is what /tools/index.json says of it. Adding one is adding a line here and its dependency. */
@@ -29,6 +30,7 @@ export const MACHINE_TOOLS = Object.freeze([
29
30
  { name: 'parley', pkg: PARLEY, usage: 'Installed in every machine: parley --help. Talk with the person you work for, on their screen, when their chat is on.' },
30
31
  { name: 'docket', pkg: DOCKET, usage: 'Installed in every machine: docket --help. What woke you, waiting until you say done or failed; and reminders you set yourself.' },
31
32
  { name: 'binder', pkg: BINDER, usage: 'Installed in every machine: binder --help. The lists you were given (batches, tasks, customers...): read them, add to them, note and attach; a person approves.' },
33
+ { name: 'tether', pkg: TETHER, usage: 'Installed in every machine: tether --help. The accesses you were given -- a mailbox, a calendar, an address book, an online folder, a machine over SSH, a browser -- used within your rights; a person holds the keys and decides what passes.' },
32
34
  ]);
33
35
 
34
36
  /* Where an installed package is, by the lookup Node itself makes from here
@@ -108,7 +108,7 @@ export class Secrets {
108
108
  days left (null without an expiry); `expired`: no longer delivered. */
109
109
  list() {
110
110
  return this.#store.all().map((s) => ({ name: s.name, conversations: this.#users(s.name), createdAt: s.createdAt,
111
- expires: s.expires ?? null, days: s.expires ? daysTo(s.expires, this.#now()) : null, expired: this.#expired(s),
111
+ expires: s.expires ?? null, days: s.expires ? daysTo(s.expires, this.#now()) : null, expired: this.#expired(s), ...(s.hostOnly ? { hostOnly: true } : {}),
112
112
  ...(s.ephemeral ? { ephemeral: true, expiresAt: s.expiresAt, expiresInMs: Math.max(0, Date.parse(s.expiresAt) - this.#now().getTime()) } : {}) }));
113
113
  }
114
114
  /* Past its expiry day: kept, not used (nor by dictation, voice.mjs). */
@@ -127,12 +127,15 @@ export class Secrets {
127
127
 
128
128
  /* Creates, or replaces the value of, a secret. `expires`: a day, '' for
129
129
  none, left out to keep the one it had. */
130
- set({ name, value, expires }) {
130
+ set({ name, value, expires, hostOnly }) {
131
131
  if (!isSecretName(name)) throw new Refusal(400, 'A secret is named like a variable: capitals, digits and underscores, starting with a letter.');
132
132
  const sealed = this.#seal(value);
133
133
  const day = expires === undefined ? undefined : expiryOf(expires);
134
134
  const before = this.#store.get(name);
135
- this.#write({ ...before, name, sealed, createdAt: before?.createdAt ?? new Date().toISOString() }, day);
135
+ /* hostOnly: a secret the server uses on the agent's behalf (an account token the
136
+ keeper reveals by name). It is never attached to a conversation, so never
137
+ delivered to a machine; attach() refuses it, so this cannot be undone by hand. */
138
+ this.#write({ ...before, name, sealed, createdAt: before?.createdAt ?? new Date().toISOString(), ...(hostOnly ? { hostOnly: true } : {}) }, day);
136
139
  return { name };
137
140
  }
138
141
 
@@ -200,6 +203,7 @@ export class Secrets {
200
203
  attach(conversation, name, attached) {
201
204
  const secret = this.#store.get(name);
202
205
  if (!secret) throw new Refusal(404, 'No such secret.');
206
+ if (attached && secret.hostOnly) throw new Refusal(403, 'This secret is held by the server (an account token) and is never put in a machine.');
203
207
  if (!isConversationName(conversation)) throw new Refusal(400, 'Not a conversation.');
204
208
  if (attached) this.#grants.give(conversationSubject(conversation), `secret:${name}`, 'x'); else this.#grants.take(conversationSubject(conversation), `secret:${name}`);
205
209
  }
@@ -0,0 +1,91 @@
1
+ /* TETHER, AS CLAVARIUM USES IT (clavarium-tether, a project of its own, installed in every machine
2
+ * as Parley, Docket and Binder are: toolbox.mjs). An agent reaches the accesses it was given -- a
3
+ * machine over SSH (its terminal and files), an online folder (WebDAV, Microsoft Graph), later a
4
+ * remote screen and a browser -- each created and given by a person.
5
+ *
6
+ * THE KEEPER IS KEPT HERE, in this server's data (tether/), never in a machine: what a tool could
7
+ * write, it could rewrite, and the keeper holds the targets AND THEIR SECRETS. It checks the rights,
8
+ * asks a person when it must, runs the connector, answers, and journals. A tool asks through its work
9
+ * folder's .tether (beside .parley, .docket, .binder); who asks is said by the folder --
10
+ * conversation:<name> -- never by the ask. The owner creates and gives the targets from the page
11
+ * (Assets > Access).
12
+ *
13
+ * SECRETS COME FROM THIS SERVER by name (the vault's reveal), never written to the store, never given
14
+ * to the agent or the journal: a target's config holds a secret's NAME, and the keeper reveals it for
15
+ * the connector alone. The person sets each target's level (watch / propose / frame / free); a call
16
+ * that must be decided waits, and the person decides it.
17
+ *
18
+ * The SSH and online-folder connectors are wired by the keeper itself (each a client that holds
19
+ * nothing until a target asks it to connect). The screen and browser connectors, which need an engine
20
+ * or a paired socket, are wired in a later step.
21
+ */
22
+ import { mkdirSync, lstatSync } from 'node:fs';
23
+ import { keeper } from 'clavarium-tether/host';
24
+
25
+ export const FOLDER = '.tether';
26
+ /* The keeper takes what the agents asked, this often. */
27
+ export const PUMP_MS = 1000;
28
+ const AGENT = 'conversation:';
29
+
30
+ export class Tethers {
31
+ #keeper; #resources; #conversations; #secrets; #timers = []; #changes = 0;
32
+
33
+ /* `resources`: Resources (workFolder). `conversations()`: the names of the conversations.
34
+ `secrets`: the vault, read by name for a connector only (reveal). */
35
+ constructor({ dataDir, resources, conversations, secrets, connectors, now = () => Date.now() }) {
36
+ this.#resources = resources; this.#conversations = conversations; this.#secrets = secrets;
37
+ this.#keeper = keeper(`${dataDir}/tether`, { sides: () => this.#sides(), secrets: (name) => this.#reveal(name), now, ...(connectors ? { connectors } : {}) });
38
+ this.#keeper.store.onChange(() => { this.#changes++; });
39
+ }
40
+
41
+ /* A secret's value for a connector, by name, from this server's vault; never seen by the agent.
42
+ An unknown or expired secret is a plain refusal the connector turns into "Refused". */
43
+ async #reveal(name) {
44
+ const value = this.#secrets?.reveal?.(name);
45
+ if (value === undefined || value === null) throw new Error(`no secret named "${name}" on this server`);
46
+ return value;
47
+ }
48
+
49
+ /* Each conversation's folder, made when missing; one that is anything but a folder of its own is left out. */
50
+ #sides() {
51
+ const out = [];
52
+ for (const name of this.#conversations()) {
53
+ let dir;
54
+ try { dir = `${this.#resources.workFolder(name)}/${FOLDER}`; } catch { continue; }
55
+ const info = lstatSync(dir, { throwIfNoEntry: false });
56
+ if (info === undefined) { try { mkdirSync(dir); } catch { continue; } }
57
+ else if (!info.isDirectory() || info.isSymbolicLink()) continue;
58
+ out.push({ dir, who: { id: `${AGENT}${name}`, kind: 'agent', name } });
59
+ }
60
+ return out;
61
+ }
62
+
63
+ start() {
64
+ this.#timers.push(setInterval(() => { try { this.#keeper.pump(); } catch { /* the next turn */ } }, PUMP_MS));
65
+ for (const t of this.#timers) t.unref?.();
66
+ return () => { for (const t of this.#timers) clearInterval(t); this.#timers = []; };
67
+ }
68
+ pump() { return this.#keeper.pump(); }
69
+
70
+ /* The owner, from the page (Assets > Access): create and give targets, read the queue, decide a
71
+ call that waited. `identity` is who signed in ('' on a server without sign-in). */
72
+ act(op, args, identity = '') {
73
+ const who = { id: `person:${identity || 'owner'}`, kind: 'person', name: identity || 'Owner' };
74
+ return this.#keeper.act(String(op ?? ''), args && typeof args === 'object' ? args : {}, who);
75
+ }
76
+
77
+ /* The store behind it, for the Assets page to create/give/remove targets. */
78
+ store() { return this.#keeper.store; }
79
+
80
+ /* What each conversation was given: { name: count } -- the targets it may use. */
81
+ given() {
82
+ const out = {};
83
+ for (const t of this.#keeper.store.targets()) {
84
+ for (const id of Object.keys(t.grants ?? {})) if (id.startsWith(AGENT)) out[id.slice(AGENT.length)] = (out[id.slice(AGENT.length)] ?? 0) + 1;
85
+ }
86
+ return out;
87
+ }
88
+
89
+ /* A number that moves with every change: the page reads again when it moved. */
90
+ changes() { return this.#changes; }
91
+ }
package/web/app.js CHANGED
@@ -3166,7 +3166,7 @@
3166
3166
  /* BINDER'S LISTS, AS THIS PAGE NAMES THEM: the one place for the word (Assets, a conversation's tab). */
3167
3167
  const LISTS_WORD = { many: 'Binders', one: 'Binder', a: 'a binder', its: 'Its binders' };
3168
3168
  $('view-lists-word').textContent = LISTS_WORD.many; $('listnew-head').textContent = `New ${LISTS_WORD.one.toLowerCase()}`;
3169
- const ASSET_KINDS = [['git', 'Git repositories', 'git-branch'], ['folder', 'Folders', 'folder'], ['mailbox', 'Mailboxes', 'mail'], ['secret', 'Secrets', 'key-round'], ['list', LISTS_WORD.many, '']];
3169
+ const ASSET_KINDS = [['git', 'Git repositories', 'git-branch'], ['folder', 'Folders', 'folder'], ['mailbox', 'Mailboxes', 'mail'], ['connexion', 'Connexions', 'link-2'], ['secret', 'Secrets', 'key-round'], ['list', LISTS_WORD.many, '']];
3170
3170
  const getJson = (path, fallback) => fetch(`${API}${path}`).then((r) => (r.ok ? r.json() : fallback)).catch(() => fallback);
3171
3171
  const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; };
3172
3172
  /* A commit: its line, and the rest of its message under it, opened by a click. */
@@ -3195,7 +3195,7 @@
3195
3195
  if (mine.length === 0 && !add) continue;
3196
3196
  const section = el('section', 'as-kind'); section.dataset.kind = kind;
3197
3197
  const head = el('div', 'as-kind-head'); head.append(el('h3', '', title));
3198
- if (add) head.append(roundPlus(`Add ${{ git: 'a repository', folder: 'a folder', mailbox: 'a mailbox', secret: 'a secret', list: LISTS_WORD.a }[kind]}`, () => add(kind)));
3198
+ if (add) head.append(roundPlus(`Add ${{ git: 'a repository', folder: 'a folder', mailbox: 'a mailbox', connexion: 'a connexion', secret: 'a secret', list: LISTS_WORD.a }[kind]}`, () => add(kind)));
3199
3199
  section.append(head);
3200
3200
  if (mine.length === 0) section.append(el('p', 'hint as-none', 'None yet'));
3201
3201
  for (const item of mine) {
@@ -3818,6 +3818,23 @@
3818
3818
  if (!done.ok) { $('assets-error').textContent = done.text; $('assets-error').hidden = false; }
3819
3819
  await refresh();
3820
3820
  }
3821
+ /* The plain word for a Tether target's kind, in a Connexion's sub-line. */
3822
+ const CONNEXION_SUB = { mail: 'mailbox', calendar: 'calendar', contacts: 'address book', files: 'online folder', ssh: 'machine', computer: 'computer', browser: 'browser', screen: 'screen' };
3823
+ const connexionSub = (kind) => CONNEXION_SUB[kind] ?? kind;
3824
+ /* Give a Tether target to a conversation at a level, or take it back (none). */
3825
+ async function grantTarget(id, name, level) {
3826
+ $('assets-error').hidden = true;
3827
+ try { await post(`${API}/tether/level`, { target: id, agent: `conversation:${name}`, level }); }
3828
+ catch (error) { $('assets-error').textContent = error.message; $('assets-error').hidden = false; }
3829
+ await refresh();
3830
+ }
3831
+ /* Accept or refuse a Tether call that is waiting for a person. */
3832
+ async function decideTether(id, decision) {
3833
+ $('assets-error').hidden = true;
3834
+ try { await post(`${API}/tether/decide`, { id, decision }); }
3835
+ catch (error) { $('assets-error').textContent = error.message; $('assets-error').hidden = false; }
3836
+ await paintAssets();
3837
+ }
3821
3838
  /* A new list: Binder's templates, read once. */
3822
3839
  async function fillTemplates() {
3823
3840
  const pick = $('listnew-template');
@@ -3828,7 +3845,7 @@
3828
3845
  }
3829
3846
  async function paintAssets() {
3830
3847
  if (place !== 'assets' || DEVICE) return;
3831
- const [all, boxes, secrets, keys, lists] = await Promise.all([getJson('/resources', []), getJson('/mailboxes', []), getJson('/secrets', []), getJson('/git-keys', []), binderCall('lists', {}), readDevices()]);
3848
+ const [all, boxes, secrets, keys, lists, tether] = await Promise.all([getJson('/resources', []), getJson('/mailboxes', []), getJson('/secrets', []), getJson('/git-keys', []), binderCall('lists', {}), getJson('/tether', {}), readDevices()]);
3832
3849
  if (place !== 'assets') return;
3833
3850
  paintKeys(keys);
3834
3851
  markSecrets(secrets);
@@ -3840,6 +3857,12 @@
3840
3857
  sub: kind === 'git' ? `${gitSub(r)}${viaText(r.via)}` : kind === 'mailbox' ? boxSub(box) : 'folder', tone: box?.failure ? 'bad' : '' });
3841
3858
  }
3842
3859
  for (const s2 of secrets) items.push({ key: `secret:${s2.name}`, kind: 'secret', name: s2.name, secret: s2, badge: String(s2.conversations.length), badgeTitle: `Used by ${s2.conversations.length} conversation${s2.conversations.length === 1 ? '' : 's'}`, badgeTone: 'count', ...secretItem(s2, 'name only') });
3860
+ /* Tether targets ("Connexions"): a mailbox, calendar or address book connected
3861
+ by token, given to a conversation at a level. The token lives on the server. */
3862
+ for (const tgt of Array.isArray(tether.targets) ? tether.targets : []) {
3863
+ const users = Object.keys(tgt.grants ?? {}).filter((id) => id.startsWith('conversation:')).length;
3864
+ items.push({ key: `connexion:${tgt.id}`, kind: 'connexion', name: tgt.title, target: tgt, badge: String(users), badgeTitle: `Used by ${users} conversation${users === 1 ? '' : 's'}`, badgeTone: 'count', sub: connexionSub(tgt.kind) });
3865
+ }
3843
3866
  /* Binder's lists: given to a conversation (read, write) in Binder itself. */
3844
3867
  const shownLists = lists.ok && Array.isArray(lists.data) ? lists.data.filter((l) => !l.archived) : [];
3845
3868
  listsSig = binderSig(lists.data);
@@ -3863,7 +3886,7 @@
3863
3886
  if (assetsAdding === 'choose') {
3864
3887
  detail.append(el('h3', '', 'New asset'));
3865
3888
  const kinds = el('div', 'as-kinds');
3866
- for (const [kind, word] of [['git', 'Git repository'], ['folder', 'Folder'], ['mailbox', 'Mailbox'], ['secret', 'Secret'], ['list', LISTS_WORD.one]]) {
3889
+ for (const [kind, word] of [['git', 'Git repository'], ['folder', 'Folder'], ['mailbox', 'Mailbox'], ['connexion', 'Connexion'], ['secret', 'Secret'], ['list', LISTS_WORD.one]]) {
3867
3890
  const b = el('button', '', word); b.type = 'button'; b.dataset.kind = kind;
3868
3891
  b.addEventListener('click', () => { assetsAdding = kind; void paintAssets(); });
3869
3892
  b.prepend(kindIcon(kind)); kinds.append(b);
@@ -3914,8 +3937,11 @@
3914
3937
  detail.append(box, ...replace.card);
3915
3938
  }
3916
3939
  /* Used by: each conversation that has it, what it may do; "+" offers the others. */
3917
- const options = chosen.kind === 'secret' ? [['off', 'Off'], ['use', 'Use']] : chosen.kind === 'mailbox' ? [['none', 'Off'], ['read', 'Read']] : [['none', 'Off'], ['read', 'Read'], ['write', 'Write']];
3918
- const has = (c) => (chosen.kind === 'secret' ? (chosen.secret.conversations.includes(c.name) ? 'use' : 'off') : chosen.kind === 'list' ? chosen.list.grants?.[`conversation:${c.name}`] ?? 'none' : r.attachments?.[c.name] ?? 'none');
3940
+ const options = chosen.kind === 'secret' ? [['off', 'Off'], ['use', 'Use']] : chosen.kind === 'mailbox' ? [['none', 'Off'], ['read', 'Read']]
3941
+ : chosen.kind === 'connexion' ? [['none', 'Off'], ['watch', 'Watch'], ['propose', 'Propose'], ['frame', 'Frame'], ['free', 'Free']]
3942
+ : [['none', 'Off'], ['read', 'Read'], ['write', 'Write']];
3943
+ const has = (c) => (chosen.kind === 'secret' ? (chosen.secret.conversations.includes(c.name) ? 'use' : 'off') : chosen.kind === 'list' ? chosen.list.grants?.[`conversation:${c.name}`] ?? 'none'
3944
+ : chosen.kind === 'connexion' ? chosen.target.grants?.[`conversation:${c.name}`]?.level ?? 'none' : r.attachments?.[c.name] ?? 'none');
3919
3945
  const using = ready.filter((c) => !['none', 'off'].includes(has(c)));
3920
3946
  const others = ready.filter((c) => ['none', 'off'].includes(has(c)));
3921
3947
  const users = el('div', 'as-users');
@@ -3925,6 +3951,7 @@
3925
3951
  line.append(el('span', '', shownName(c)), modes(options, has(c), async (value) => {
3926
3952
  if (chosen.kind === 'secret') await handTo(c.name, chosen.name, value === 'use', 'assets-error');
3927
3953
  else if (chosen.kind === 'list') await grantList(chosen.list.id, c.name, value);
3954
+ else if (chosen.kind === 'connexion') await grantTarget(chosen.target.id, c.name, value);
3928
3955
  else await attachTo(c.name, chosen.name, value, 'assets-error');
3929
3956
  await paintAssets();
3930
3957
  }, `What ${c.name} may do with ${chosen.name}`));
@@ -3970,11 +3997,31 @@
3970
3997
  edit.addEventListener('click', () => { remoteEditing = !remoteEditing; box.hidden = !remoteEditing; if (remoteEditing) focusField($('gitview-url')); });
3971
3998
  void gitDetail(holder, chosen.name, { place: true });
3972
3999
  }
4000
+ if (chosen.kind === 'connexion') {
4001
+ const t = chosen.target;
4002
+ detail.append(el('p', 'hint', [connexionSub(t.kind), t.config?.user].filter(Boolean).join(' · ')));
4003
+ detail.append(el('p', 'hint', 'A level is: watch (read only), propose (asks before each action), frame (acts within its rules, asks for the rest), free (acts, kept in the journal).'));
4004
+ /* Calls waiting for a person (propose/frame). Accept or refuse each. */
4005
+ const waiting = (Array.isArray(tether.approvals) ? tether.approvals : []).filter((q) => (q.target?.id ?? q.target) === t.id);
4006
+ if (waiting.length) {
4007
+ const box = el('div', 'as-users');
4008
+ for (const q of waiting) {
4009
+ const line = el('div', 'given-row');
4010
+ const what = el('span', ''); what.append(el('b', '', q.verb ?? 'action'), document.createTextNode(` ${q.detail ?? ''}`.trimEnd()));
4011
+ if (q.why) what.append(el('small', 'hint', ` — ${q.why}`));
4012
+ const yes = el('button', 'primary', 'Accept'); yes.type = 'button'; yes.addEventListener('click', () => { yes.disabled = true; void decideTether(q.id, 'yes'); });
4013
+ const no = el('button', 'danger', 'Refuse'); no.type = 'button'; no.addEventListener('click', () => { no.disabled = true; void decideTether(q.id, 'no'); });
4014
+ const acts = el('div', 'levels'); acts.append(yes, no);
4015
+ line.append(what, acts); box.append(line);
4016
+ }
4017
+ detail.append(chapter('Waiting for you'), box);
4018
+ }
4019
+ }
3973
4020
  /* Delete, out of the way; refused while it is used, and why. */
3974
4021
  const remove = el('button', 'as-link danger-link', 'Delete...'); remove.type = 'button';
3975
4022
  const why = el('small', 'hint');
3976
4023
  const inUse = chosen.kind !== 'secret' && using.length > 0;
3977
- const lost = { secret: 'Its value is lost for good.', list: 'Its cards are lost for good.' }[chosen.kind] ?? 'Its files are kept aside on the server.';
4024
+ const lost = { secret: 'Its value is lost for good.', list: 'Its cards are lost for good.', connexion: 'The connection is removed; the account token stays on the server.' }[chosen.kind] ?? 'Its files are kept aside on the server.';
3978
4025
  if (inUse) { remove.disabled = true; why.textContent = ` used by ${using.length} conversation${using.length > 1 ? 's' : ''}: set ${using.length > 1 ? 'them' : 'it'} to Off first`; }
3979
4026
  remove.addEventListener('click', () => {
3980
4027
  const sure = el('button', 'danger', chosen.kind === 'secret' || chosen.kind === 'list' ? `Yes, delete ${chosen.name}` : `Yes, remove ${chosen.name}`); sure.type = 'button';
@@ -3985,6 +4032,7 @@
3985
4032
  sure.addEventListener('click', async () => {
3986
4033
  try {
3987
4034
  if (chosen.kind === 'list') { const done = await binderCall('delete-list', { list: chosen.list.id }); if (!done.ok) throw new Error(done.text); }
4035
+ else if (chosen.kind === 'connexion') await post(`${API}/tether/remove-target`, { target: chosen.target.id });
3988
4036
  else await post(chosen.kind === 'secret' ? `${API}/secrets/${chosen.name}/remove` : `${API}/resources/${chosen.name}/remove`);
3989
4037
  assetOpen = '';
3990
4038
  }
@@ -3997,7 +4045,7 @@
3997
4045
  /* Given to a device: from here too (the map shows who has it). */
3998
4046
  const share = el('button', 'as-link', 'Share with a device...'); share.type = 'button';
3999
4047
  share.addEventListener('click', () => { void openCompose([[chosen.key, 'r']]); });
4000
- const foot = el('div', 'as-foot'); foot.append(...(chosen.kind === 'secret' || chosen.kind === 'list' ? [] : [share, el('br')]), remove, why);
4048
+ const foot = el('div', 'as-foot'); foot.append(...(['secret', 'list', 'connexion'].includes(chosen.kind) ? [] : [share, el('br')]), remove, why);
4001
4049
  detail.append(foot);
4002
4050
  }
4003
4051
  /* From the map's "+" of Assets: the Assets page over the map, on "which kind"; Back, the map. */
@@ -5915,6 +5963,53 @@
5915
5963
  btn.disabled = false; btn.textContent = was;
5916
5964
  await paintAssets();
5917
5965
  });
5966
+ /* CONNECT AN ACCOUNT (Connexions): a live link through Tether. The person signs
5967
+ in in their own browser; the token is kept on the server, never in a machine.
5968
+ Google covers mail+calendar+contacts in one go; Microsoft, mail only here. */
5969
+ const setConnexionProvider = (provider) => {
5970
+ const form = $('connexion-new');
5971
+ form.dataset.provider = provider;
5972
+ for (const b of $('connexion-provider').querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.provider === provider));
5973
+ const google = provider === 'google';
5974
+ for (const id of ['connexion-calendar', 'connexion-contacts']) { const c = $(id); if (!google) c.checked = false; c.disabled = !google; }
5975
+ $('connexion-calendar-label').classList.toggle('off', !google);
5976
+ $('connexion-contacts-label').classList.toggle('off', !google);
5977
+ $('connexion-paste').hidden = true;
5978
+ $('connexion-error').hidden = true;
5979
+ const who = MAILBOX_PROVIDER[provider];
5980
+ $('connexion-notice').textContent = google
5981
+ ? 'Clavarium signs in as Thunderbird — that is what Google sees. Mail, calendar and contacts can be connected together.'
5982
+ : 'Clavarium signs in as Thunderbird — that is what Microsoft sees. Mail here; calendar and files need a Microsoft app, added later.';
5983
+ $('connexion-open').textContent = `Open the ${who} sign-in page`;
5984
+ };
5985
+ for (const b of $('connexion-provider').querySelectorAll('button')) b.addEventListener('click', () => setConnexionProvider(b.dataset.provider));
5986
+ const connexionKinds = () => [['connexion-mail', 'mail'], ['connexion-calendar', 'calendar'], ['connexion-contacts', 'contacts']].filter(([id]) => $(id).checked && !$(id).disabled).map(([, k]) => k);
5987
+ $('connexion-open').addEventListener('click', async () => {
5988
+ $('connexion-error').hidden = true;
5989
+ const kinds = connexionKinds();
5990
+ if (!kinds.length) { $('connexion-error').textContent = 'Choose at least mail, calendar or contacts.'; $('connexion-error').hidden = false; return; }
5991
+ const btn = $('connexion-open'); btn.disabled = true;
5992
+ try {
5993
+ const { url } = await post(`${API}/accounts/consent`, { provider: $('connexion-new').dataset.provider, user: $('connexion-email').value.trim(), kinds });
5994
+ window.open(url, '_blank', 'noopener');
5995
+ $('connexion-paste').hidden = false;
5996
+ $('connexion-code').focus();
5997
+ } catch (error) { $('connexion-error').textContent = error.message; $('connexion-error').hidden = false; }
5998
+ btn.disabled = false;
5999
+ });
6000
+ $('connexion-connect').addEventListener('click', async () => {
6001
+ $('connexion-error').hidden = true;
6002
+ const btn = $('connexion-connect'); const was = btn.textContent; btn.disabled = true; btn.textContent = 'Connecting...';
6003
+ try {
6004
+ const made = await post(`${API}/accounts/connect`, { redirected: $('connexion-code').value.trim() });
6005
+ if (made?.targets?.[0]) assetOpen = `connexion:${made.targets[0].id}`;
6006
+ assetsAdding = '';
6007
+ $('connexion-new').reset(); setConnexionProvider('google');
6008
+ } catch (error) { $('connexion-error').textContent = error.message; $('connexion-error').hidden = false; }
6009
+ btn.disabled = false; btn.textContent = was;
6010
+ await paintAssets();
6011
+ });
6012
+ setConnexionProvider('google');
5918
6013
  $('list-new').addEventListener('submit', async (event) => {
5919
6014
  event.preventDefault();
5920
6015
  $('assets-error').hidden = true;
@@ -7392,7 +7487,7 @@
7392
7487
  what). Nothing is ever chosen for the owner but the thing they came
7393
7488
  from; writing is never chosen for them. */
7394
7489
  const KINDS = [['', 'All'], ['conversation', 'Conversations'], ['folder', 'Folders'], ['git', 'Repositories'], ['mailbox', 'Mailboxes']];
7395
- const KIND_WORD = { conversation: 'conversation', folder: 'folder', git: 'repository', mailbox: 'mailbox' };
7490
+ const KIND_WORD = { conversation: 'conversation', folder: 'folder', git: 'repository', mailbox: 'mailbox', connexion: 'connexion' };
7396
7491
  const ago = (date) => {
7397
7492
  if (!date) return 'never opened';
7398
7493
  const minutes = Math.max(0, Math.round((Date.now() - Date.parse(date)) / 60000));
package/web/index.html CHANGED
@@ -546,6 +546,29 @@
546
546
  <p id="mailbox-error" class="error" role="alert" hidden></p>
547
547
  </form>
548
548
  </div>
549
+ <div id="connexion-box" class="as-form" data-kind="connexion"><h3>Connect an account</h3>
550
+ <div class="hint">A live link to a mailbox, calendar or address book. The agent uses it through Tether, within the rights you give; the account's token stays on the server and never enters a machine. <details class="more"><summary>How the sign-in works</summary><span>Clavarium signs in as Thunderbird — that is what the provider sees. You sign in in your own browser; Clavarium never sees your password, and keeps only a token it uses on your behalf.</span></details></div>
551
+ <form id="connexion-new" autocomplete="off" data-provider="google">
552
+ <div id="connexion-provider" class="choices" role="group" aria-label="Kind of account">
553
+ <button type="button" data-provider="google" aria-pressed="true">Google</button>
554
+ <button type="button" data-provider="microsoft">Microsoft</button>
555
+ </div>
556
+ <label for="connexion-email">Email address</label>
557
+ <input id="connexion-email" type="email" spellcheck="false" autocapitalize="off" autocomplete="off" placeholder="your email address">
558
+ <div id="connexion-kinds" class="choices" role="group" aria-label="What to connect">
559
+ <label class="check"><input type="checkbox" id="connexion-mail" checked> Mail</label>
560
+ <label class="check" id="connexion-calendar-label"><input type="checkbox" id="connexion-calendar"> Calendar</label>
561
+ <label class="check" id="connexion-contacts-label"><input type="checkbox" id="connexion-contacts"> Contacts</label>
562
+ </div>
563
+ <p class="hint" id="connexion-notice"></p>
564
+ <div class="row"><button type="button" id="connexion-open" class="primary">Open the sign-in page</button></div>
565
+ <div id="connexion-paste" hidden>
566
+ <label for="connexion-code">After you allow, the page will not load — copy its full address and paste it here</label>
567
+ <div class="row"><input id="connexion-code" spellcheck="false" autocapitalize="off" placeholder="http://127.0.0.1..."><button type="button" id="connexion-connect" class="primary">Connect</button></div>
568
+ </div>
569
+ <p id="connexion-error" class="error" role="alert" hidden></p>
570
+ </form>
571
+ </div>
549
572
  <div id="list-box" class="as-form" data-kind="list"><h3 id="listnew-head">New binder</h3>
550
573
  <form id="list-new" autocomplete="off">
551
574
  <label for="listnew-template">Template</label>
package/web/style.css CHANGED
@@ -165,6 +165,8 @@ code { font-family: ui-monospace, Menlo, Consolas, monospace; }
165
165
  #shortcut-new { display: flex; flex-direction: column; gap: 6px; padding: 4px 0 8px; max-width: 520px; }
166
166
  #shortcut-new input:not([type]) , #shortcut-new input[maxlength] { font: .875rem var(--sans); color: var(--ink); background: var(--bg); border: 1px solid var(--line); border-radius: 7px; padding: 7px 9px; min-width: 0; }
167
167
  .check { font-size: .8125rem; color: var(--ink2); display: flex; align-items: center; gap: 6px; }
168
+ .check.off { opacity: .5; }
169
+ #connexion-kinds { gap: 16px; }
168
170
  footer#keys { border-top: 0; }
169
171
  #voice-line { margin: 0; padding: 5px 12px; font-size: .8125rem; color: var(--ink2); background: var(--bar); border-top: 1px solid var(--line); overflow-wrap: anywhere; }
170
172
  #voice-line::before { content: ""; display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 8px; background: var(--ok); }