clavarium 0.2.53-next.1 → 0.2.54-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,19 +1,20 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.53-next.1",
3
+ "version": "0.2.54-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.53-next.1",
9
+ "version": "0.2.54-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
13
13
  "@xterm/xterm": "^6.0.0",
14
14
  "clavarium-binder": "0.1.8-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
- "clavarium-parley": "0.17.4-next.1",
16
+ "clavarium-parley": "0.17.10-next.1",
17
+ "clavarium-tether": "0.1.0-next.11",
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",
@@ -714,9 +742,9 @@
714
742
  }
715
743
  },
716
744
  "node_modules/clavarium-parley": {
717
- "version": "0.17.4-next.1",
718
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.4-next.1.tgz",
719
- "integrity": "sha512-/rQy9WLP9/XndInawH6mIhS9RivA1IQmMpB5IhYMUflnLSWBvP096Z0TF3xB3u2X1e8uni4tar5Tua5hq/wjWg==",
745
+ "version": "0.17.10-next.1",
746
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.10-next.1.tgz",
747
+ "integrity": "sha512-a4mZ29EFeBV6P+cumehzJ3VmVWcswklv2L5XAC0Oo+kJQ6k09komHlz2uZZVRRQZFhgC0I6G+avFAYq5zsophA==",
720
748
  "license": "MIT",
721
749
  "bin": {
722
750
  "parley": "bin/parley.mjs",
@@ -726,6 +754,22 @@
726
754
  "node": ">=22"
727
755
  }
728
756
  },
757
+ "node_modules/clavarium-tether": {
758
+ "version": "0.1.0-next.11",
759
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.11.tgz",
760
+ "integrity": "sha512-GiLaCXmANy8OsiTacZIe5n+UUK+Lw33QzonZkU+vTVSx8X5g4fF4hzUkfRmpXWMDVWMuvTvptL/qIrJNbXJ9+Q==",
761
+ "license": "MIT",
762
+ "bin": {
763
+ "tether": "bin/cli.mjs",
764
+ "tether-mcp": "server/mcp.mjs"
765
+ },
766
+ "engines": {
767
+ "node": ">=22"
768
+ },
769
+ "optionalDependencies": {
770
+ "ssh2": "1.17.0"
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.53-next.1",
3
+ "version": "0.2.54-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.",
@@ -46,7 +46,8 @@
46
46
  "@xterm/xterm": "^6.0.0",
47
47
  "clavarium-binder": "0.1.8-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
- "clavarium-parley": "0.17.4-next.1",
49
+ "clavarium-parley": "0.17.10-next.1",
50
+ "clavarium-tether": "0.1.0-next.11",
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
@@ -78,6 +78,11 @@
78
78
  * POST /api/secrets/<NAME>/replace {value?, expires?}: in place, its name and grants kept; '' removes the expiry
79
79
  * POST /api/secrets/<NAME>/remove
80
80
  * POST /api/secrets/<NAME>/rename {name}: its value and where it is handed go with it
81
+ * GET /api/asset-groups the owner's asset groups: [{id, label, members}]
82
+ * POST /api/asset-groups {label}: a new, empty group
83
+ * POST /api/asset-groups/place {asset, group}: put an asset in a group (group null to take it out)
84
+ * POST /api/asset-groups/<id>/rename {label}
85
+ * POST /api/asset-groups/<id>/remove
81
86
  * GET /api/conversations/<name>/health-react POST the same {on?, message?, command?}: what it does when its machine is short
82
87
  * GET /api/machines/places GET /api/machines/moving POST /api/machines/move {to}: all the machines to another disk
83
88
  * POST /api/machines/forget-old: the copy a move left behind, removed
@@ -146,7 +151,7 @@ function readBody(request, max = BODY_MAX) {
146
151
  }
147
152
 
148
153
  /* 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) {
154
+ 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, groups) {
150
155
  const { pathname } = new URL(request.url ?? '/', 'http://local');
151
156
  if (!pathname.startsWith('/api/')) return false;
152
157
  let send = (status, body) => {
@@ -235,12 +240,21 @@ export async function handleApi(request, response, conversations, headers, resou
235
240
  if (pathname === '/api/tools') return send(200, conversations.tools()), true;
236
241
  if (pathname === '/api/conversations') {
237
242
  const lists = binders?.given() ?? {};
238
- return send(200, conversations.list().map((c) => ({ ...c, lists: lists[c.name] ?? null, resources: resources?.of(c.name) ?? [], secrets: secrets?.of(c.name) ?? [], answerer: answerer?.of(c.name) ?? null, wakeups: wakeups?.of(c.name) ?? null, health: health?.of(c.name) ?? null, talk: talk?.brief(c.name) ?? null }))), true;
243
+ return send(200, conversations.list().map((c) => ({ ...c, lists: lists[c.name] ?? null, resources: resources?.of(c.name) ?? [], secrets: secrets?.of(c.name) ?? [], ephemeralSecrets: secrets?.liveFor(c.name) ?? [], answerer: answerer?.of(c.name) ?? null, wakeups: wakeups?.of(c.name) ?? null, health: health?.of(c.name) ?? null, talk: talk?.brief(c.name) ?? null }))), true;
239
244
  }
240
245
  if (pathname === '/api/resources' && resources) return send(200, resources.list()), true;
241
246
  if (pathname === '/api/shortcuts' && shortcuts) return send(200, shortcuts.list()), true;
242
247
  if (pathname === '/api/secrets' && secrets) return send(200, secrets.list()), true;
248
+ /* The owner's asset groups (groups.mjs): a label and the asset ids each
249
+ holds. Distinct from /api/groups/* above, which are the conversation
250
+ list's folders. */
251
+ if (pathname === '/api/asset-groups' && groups) return send(200, groups.list()), true;
243
252
  if (pathname === '/api/mailboxes' && mailboxes) return send(200, mailboxes.list()), true;
253
+ /* Which providers and kinds an account can be connected for here. */
254
+ if (pathname === '/api/accounts' && accounts) return send(200, { supported: accounts.supported() }), true;
255
+ /* Assets > Access: the targets, who was given each at which level, the
256
+ calls waiting, and the recent journal -- all the page needs to read. */
257
+ 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
258
  /* Every device, each with all it was given. */
245
259
  if (pathname === '/api/devices' && sharing) return send(200, sharing.devices.all()), true;
246
260
  if (pathname === '/api/git-keys' && gitAccess) return send(200, gitAccess.keys()), true;
@@ -408,10 +422,29 @@ export async function handleApi(request, response, conversations, headers, resou
408
422
  return send(200, { ok: true }), true;
409
423
  }
410
424
  if (pathname === '/api/mailboxes' && mailboxes) { const made = await mailboxes.add(body); void setup?.assetAdded(made.name).catch(() => {}); return send(201, made), true; }
425
+ if (pathname === '/api/mailboxes/consent' && mailboxes) return send(200, mailboxes.consent(body)), true;
426
+ if (pathname === '/api/mailboxes/connect' && mailboxes) { const made = await mailboxes.connect(body); void setup?.assetAdded(made.name).catch(() => {}); return send(201, made), true; }
411
427
  const fetched = /^\/api\/mailboxes\/([a-z0-9-]{1,32})\/sync$/.exec(pathname);
412
428
  if (fetched && mailboxes) return send(200, await mailboxes.sync(fetched[1])), true;
429
+ /* Connecting an account by token (consent in the owner's browser, the token
430
+ kept host-only, a Tether target made): see accounts.mjs. */
431
+ if (pathname === '/api/accounts/consent' && accounts) return send(200, accounts.consent(body)), true;
432
+ if (pathname === '/api/accounts/connect' && accounts) { const made = await accounts.connect(body); return send(201, made), true; }
433
+ /* Assets > Access: the owner sets a conversation's level and rules on a
434
+ target, decides a call that waited, or removes a target. Each is an op the
435
+ keeper runs as the owner (person), never as an agent. */
436
+ const tetherOp = /^\/api\/tether\/(level|allow|unallow|decide|remove-target|stop|resume)$/.exec(pathname);
437
+ 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
438
  if (pathname === '/api/shortcuts' && shortcuts) return send(201, shortcuts.add(body)), true;
414
439
  if (pathname === '/api/secrets' && secrets) { const made = secrets.set(body); setup?.secretAdded(made.name); return send(201, made), true; }
440
+ /* Asset groups (groups.mjs): a folder-style tidy-up, not a right. */
441
+ if (pathname === '/api/asset-groups' && groups) return send(201, groups.create(body.label)), true;
442
+ if (pathname === '/api/asset-groups/place' && groups) return send(200, groups.place(body.asset, body.group ?? null)), true;
443
+ const groupOp = /^\/api\/asset-groups\/([0-9a-f]{12})\/(rename|remove)$/.exec(pathname);
444
+ if (groupOp && groups) {
445
+ if (groupOp[2] === 'rename') return send(200, groups.rename(groupOp[1], body.label)), true;
446
+ return groups.remove(groupOp[1]), send(200, { ok: true }), true;
447
+ }
415
448
  const reactSet = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
416
449
  if (reactSet && reacting) { const n = decodeURIComponent(reactSet[1]); if (!conversations.list().some((c) => c.name === n)) throw new Refusal(404, 'No such conversation.'); return send(200, reacting.set(n, body)), true; }
417
450
  if (pathname === '/api/machines/move' && machinesMove) return send(202, await machinesMove.move(String(body.to ?? ''))), true;
@@ -505,6 +538,14 @@ export async function handleApi(request, response, conversations, headers, resou
505
538
  retell(conversation);
506
539
  return send(200, { ok: true, secrets: secrets.of(conversation) }), true;
507
540
  }
541
+ /* Forget an ephemeral secret now (its stars in the chat have a button): gone from the vault and the machine. */
542
+ const forgetSecret = /^\/api\/conversations\/([^/]+)\/secrets\/([^/]+)\/forget$/.exec(pathname);
543
+ if (forgetSecret && secrets) {
544
+ const conversation = decodeURIComponent(forgetSecret[1]);
545
+ if (!conversations.list().some((c) => c.name === conversation)) throw new Refusal(404, 'No such conversation.');
546
+ await secrets.drop(conversation, decodeURIComponent(forgetSecret[2]));
547
+ return send(200, { ok: true }), true;
548
+ }
508
549
  const share = /^\/api\/conversations\/([^/]+)\/share$/.exec(pathname);
509
550
  if (share && sharing) {
510
551
  const conversation = decodeURIComponent(share[1]);
@@ -0,0 +1,120 @@
1
+ /* GROUPS OF ASSETS: a folder-style tidy-up, for the owner's convenience.
2
+ *
3
+ * The owner may have many assets -- folders, git repositories, mailboxes,
4
+ * secrets, connexions. A GROUP is a named box they drop some of them into,
5
+ * to calm the three places assets are shown (the Assets list, a
6
+ * conversation's panel, the access map) and to hand a whole box to a
7
+ * conversation at once.
8
+ *
9
+ * WHAT A GROUP IS NOT: a right. The table of rights (grants.mjs, and the
10
+ * Tether levels) stays the ONE truth of who may do what. A group is only a
11
+ * label an asset carries. "Give the group" is a shortcut that gives each of
12
+ * its assets, one by one, each at a sensible default for its own type -- it
13
+ * is never a line of its own in the rights table, and there is no
14
+ * inheritance. So a group may hold assets of mixed types, and taking a right
15
+ * back is still done on the one asset.
16
+ *
17
+ * THE MODEL IS A FOLDER: an asset sits in AT MOST ONE group; placing it in a
18
+ * group takes it out of any other. Assets with no group ("loose") and
19
+ * grouped assets live side by side. A group emptied of its assets is still a
20
+ * group until it is removed.
21
+ *
22
+ * A MEMBER is an asset id, the same string the rest of the server uses:
23
+ * "folder:reports", "git:site", "mailbox:news", "secret:MODEL_KEY",
24
+ * "connexion:<id>". This store does not police what an id points at (assets
25
+ * come and go, and a Tether connexion is not in grants.mjs), so it keeps ids
26
+ * as given; a view resolves them against the assets that exist and ignores
27
+ * the rest. `forget(asset)` drops a member whose asset is gone.
28
+ */
29
+ import { randomBytes } from 'node:crypto';
30
+ import { Refusal } from './conversations.mjs';
31
+ import { titleProblem } from './names.mjs';
32
+
33
+ export const LABEL_MAX = 40;
34
+ /* An id a browser cannot forge into something else: short, random, lower. */
35
+ const ID = /^[0-9a-f]{12}$/;
36
+ /* A member is "<type>:<name>" -- a type of a few lower letters, then a name
37
+ with no space or control character. Kept loose on purpose (see above). */
38
+ const MEMBER = /^[a-z]{2,16}:[^\s\u0000-\u001f]{1,64}$/;
39
+
40
+ export function labelProblem(value) {
41
+ const problem = titleProblem(value);
42
+ if (problem) return problem.replace('A name', 'A group name').replace('Give a name.', 'Give the group a name.');
43
+ if ([...value].length > LABEL_MAX) return `A group name is ${LABEL_MAX} characters at most.`;
44
+ return '';
45
+ }
46
+
47
+ export const isMember = (asset) => typeof asset === 'string' && MEMBER.test(asset);
48
+
49
+ export class Groups {
50
+ #store;
51
+
52
+ constructor({ store }) { this.#store = store; }
53
+
54
+ /* [{ id, label, members: [asset...] }], in the order they were made. */
55
+ list() {
56
+ return this.#store.all().map((g) => ({ id: g.name, label: g.label, members: [...(g.members ?? [])] }));
57
+ }
58
+
59
+ /* The group an asset is in, or null. */
60
+ groupOf(asset) {
61
+ const g = this.#store.all().find((x) => (x.members ?? []).includes(asset));
62
+ return g ? g.name : null;
63
+ }
64
+
65
+ /* A new, empty group. */
66
+ create(label) {
67
+ const problem = labelProblem(label);
68
+ if (problem) throw new Refusal(400, problem);
69
+ let id; do { id = randomBytes(6).toString('hex'); } while (this.#store.get(id));
70
+ this.#store.put({ name: id, label, members: [] });
71
+ return { id, label, members: [] };
72
+ }
73
+
74
+ rename(id, label) {
75
+ const group = this.#require(id);
76
+ const problem = labelProblem(label);
77
+ if (problem) throw new Refusal(400, problem);
78
+ this.#store.put({ ...group, label });
79
+ return { id, label, members: [...(group.members ?? [])] };
80
+ }
81
+
82
+ remove(id) {
83
+ this.#require(id);
84
+ this.#store.remove(id);
85
+ }
86
+
87
+ /* Put an asset in a group, or take it out (group null). A folder move:
88
+ the asset leaves whatever other group it was in. */
89
+ place(asset, group) {
90
+ if (!isMember(asset)) throw new Refusal(400, 'Not an asset: a type and a name, such as "folder:reports".');
91
+ if (group !== null && group !== undefined) this.#require(group);
92
+ for (const g of this.#store.all()) {
93
+ const has = (g.members ?? []).includes(asset);
94
+ if (g.name === group) { if (!has) this.#store.put({ ...g, members: [...(g.members ?? []), asset] }); }
95
+ else if (has) this.#store.put({ ...g, members: (g.members ?? []).filter((a) => a !== asset) });
96
+ }
97
+ return { asset, group: group ?? null };
98
+ }
99
+
100
+ /* Drop a member everywhere its asset appears (the asset was removed). */
101
+ forget(asset) {
102
+ for (const g of this.#store.all()) {
103
+ if ((g.members ?? []).includes(asset)) this.#store.put({ ...g, members: (g.members ?? []).filter((a) => a !== asset) });
104
+ }
105
+ }
106
+
107
+ /* An asset renamed keeps its place under its new id. */
108
+ renamed(from, to) {
109
+ for (const g of this.#store.all()) {
110
+ if ((g.members ?? []).includes(from)) this.#store.put({ ...g, members: (g.members ?? []).map((a) => (a === from ? to : a)).filter((a, i, all) => all.indexOf(a) === i) });
111
+ }
112
+ }
113
+
114
+ #require(id) {
115
+ if (typeof id !== 'string' || !ID.test(id)) throw new Refusal(400, 'Not a group.');
116
+ const group = this.#store.get(id);
117
+ if (!group) throw new Refusal(404, 'No such group.');
118
+ return group;
119
+ }
120
+ }
package/server/guide.mjs CHANGED
@@ -130,7 +130,7 @@ export function ownText({ name, tool, workKept, resources = [], chat, online, se
130
130
  out.push(online === false ? '- Internet: off.' : '- Internet: on.');
131
131
  if (secrets.length) out.push(`- Secrets given, by name only: ${list(secrets.map((s) => plain(s, 40)))}.`);
132
132
  /* A secret pasted in the chat is lifted out (talk.mjs, secret-scan.mjs): the message shows a marker, the value waits in /run/secrets. */
133
- if (chat) out.push('- A secret the person pastes in the chat is kept OUT of it: the message shows ⟨secret:NAME⟩ and the value waits at /run/secrets/NAME for a few minutes. Use it only from there, inside a command (clv-run, or $(cat /run/secrets/NAME)); never write its value back into the chat. It clears itself when its time runs out.');
133
+ if (chat) out.push('- A secret the person pastes in the chat is kept OUT of it: the message shows ⟨secret:NAME⟩ and the value waits at /run/secrets/NAME for a few minutes. Use it only from there, inside a command (clv-run, or $(cat /run/secrets/NAME)); never write its value back into the chat. It clears itself when its time runs out, or at once with `parley forget NAME` when you are done.');
134
134
  const own = lines.map((l) => plain(l)).filter(Boolean).slice(0, LINES_MAX);
135
135
  if (own.length) out.push('', '## From the owner', '', ...own.map((l) => `- ${l}`));
136
136
  out.push('');
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
  }