clavarium 0.2.81-next.1 → 0.2.82-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.
@@ -211,6 +211,18 @@ run() { if [ "$SAY" = "yes" ]; then printf '%s\n' "$*"; else exec "$@"; fi; }
211
211
  # with a letter; no trailing hyphen; 32 at most. The same rule as the server.
212
212
  is_name() { [[ "$1" =~ ^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$ ]]; }
213
213
  vm_of() { is_name "${1#clv-}" && [ "$1" != "${1#clv-}" ] || refuse "not one of our VMs: ${1:-<empty>}"; }
214
+ # The qemu process(es) of one of our machines -- a qemu-system whose disk is in
215
+ # that instance, the mapping "server room" also uses. Empty when none is left,
216
+ # which is what a suspend that freed the RAM leaves behind.
217
+ vm_qemu_pids() {
218
+ local want="$1" pid vm
219
+ for pid in $(pgrep qemu-system 2>/dev/null || true); do
220
+ vm="$(tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null | grep -oE '/instances/clv(shelf)?-[a-z0-9-]+/' | head -1 | cut -d/ -f3)" || vm=""
221
+ [ "$vm" = "$want" ] && printf '%s\n' "$pid"
222
+ done
223
+ }
224
+ # No qemu left for this machine after a short grace: its RAM has been freed.
225
+ vm_freed() { local v="$1" i; for i in $(seq 1 24); do [ -z "$(vm_qemu_pids "$v")" ] && return 0; sleep 0.5; done; return 1; }
214
226
  number() { [[ "$1" =~ ^[0-9]{1,6}$ ]] || refuse "not a number: ${1:-<empty>}"; }
215
227
  # A disk or partition named by its device: /dev/sdX, /dev/vdX, /dev/nvmeNnN(pN),
216
228
  # /dev/xvdX, /dev/mmcblkN(pN), with a digit or two at the end; a loop device only
@@ -770,9 +782,51 @@ case "$AREA $VERB" in
770
782
  "vm info")
771
783
  [ $# -eq 1 ] || usage; vm_of "$1"
772
784
  run "$MULTIPASS" info "$1" --format json ;;
773
- "vm start"|"vm stop"|"vm suspend")
785
+ "vm start"|"vm stop")
774
786
  [ $# -eq 1 ] || usage; vm_of "$1"
775
787
  run "$MULTIPASS" "$VERB" "$1" ;;
788
+ "vm suspend")
789
+ # Veille: suspend must save the machine's state AND free its RAM by ending
790
+ # its qemu process. Multipass saves the state reliably but at times leaves
791
+ # qemu alive (canonical/multipass #446, #2152, #5432), so the RAM stays
792
+ # taken though the machine shows "Suspended". The state being saved, we make
793
+ # the RAM come back, gentlest first: a second suspend from a clean running
794
+ # state usually ends qemu (and keeps the ~2s resume); failing that, a clean
795
+ # stop frees it for sure (it then wakes by a boot). Normally qemu is already
796
+ # gone after the first suspend and none of this runs.
797
+ [ $# -eq 1 ] || usage; vm_of "$1"
798
+ if [ "$SAY" = "yes" ]; then
799
+ printf '%s\n' "$MULTIPASS suspend $1" \
800
+ "if its qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
801
+ "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
802
+ exit 0
803
+ fi
804
+ "$MULTIPASS" suspend "$1" || refuse "suspend of $1 failed"
805
+ vm_freed "$1" && exit 0
806
+ "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
807
+ vm_freed "$1" && exit 0
808
+ "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
809
+ vm_freed "$1" && exit 0
810
+ refuse "suspended $1 but its memory was not freed (its qemu stayed); the VM manager likely needs a restart" ;;
811
+ "vm reclaim")
812
+ # Free a machine that is ASLEEP but whose qemu still holds the RAM -- a
813
+ # suspend (maybe from before this existed) that did not end the process.
814
+ # Idempotent and safe for an asleep machine (nobody is using it): if its
815
+ # qemu is already gone, nothing happens. Touches only this machine, and
816
+ # never restarts the VM manager.
817
+ [ $# -eq 1 ] || usage; vm_of "$1"
818
+ if [ "$SAY" = "yes" ]; then
819
+ printf '%s\n' "if $1's qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
820
+ "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
821
+ exit 0
822
+ fi
823
+ # Each step that frees the RAM says how, so the server can tell the owner.
824
+ vm_freed "$1" && { echo "freed-already"; exit 0; }
825
+ "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
826
+ vm_freed "$1" && { echo "freed-resleep"; exit 0; }
827
+ "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
828
+ vm_freed "$1" && { echo "freed-stop"; exit 0; }
829
+ refuse "could not free $1's memory (its qemu stayed); the VM manager likely needs a restart" ;;
776
830
  "vm kill")
777
831
  # A stop that does not wait for the system inside: asked only after a
778
832
  # clean stop hung or failed (a restart the owner asked for).
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.81-next.1",
3
+ "version": "0.2.82-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.81-next.1",
9
+ "version": "0.2.82-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
- "clavarium-binder": "0.1.8-next.1",
14
+ "clavarium-binder": "0.1.36-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
- "clavarium-parley": "0.17.11-next.1",
17
- "clavarium-tether": "0.1.0-next.13",
16
+ "clavarium-parley": "0.17.19-next.1",
17
+ "clavarium-tether": "0.1.0-next.30",
18
18
  "mermaid": "11.17.2",
19
19
  "node-pty": "^1.1.0",
20
20
  "pdfjs-dist": "6.4.299",
@@ -716,9 +716,9 @@
716
716
  }
717
717
  },
718
718
  "node_modules/clavarium-binder": {
719
- "version": "0.1.8-next.1",
720
- "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.8-next.1.tgz",
721
- "integrity": "sha512-0ZvTgn4z3IzLWjVyt5H82tnrE4g4Zdh0eb0kKrpVYjJ8vEfun6CmzHFclce9lb7vH+CC5ozKETuTAmSVYkk+lg==",
719
+ "version": "0.1.36-next.1",
720
+ "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.36-next.1.tgz",
721
+ "integrity": "sha512-4YvWkq3az1sP2N7Ot5fsYJONsoqN8Rwi8snS2rUoV1sTtcd9vvwRghfC01myZcoGHq3chFep3Jb6q4mibDvvRQ==",
722
722
  "license": "MIT",
723
723
  "bin": {
724
724
  "binder": "bin/binder.mjs",
@@ -742,9 +742,9 @@
742
742
  }
743
743
  },
744
744
  "node_modules/clavarium-parley": {
745
- "version": "0.17.11-next.1",
746
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.11-next.1.tgz",
747
- "integrity": "sha512-IHGgFbDzHjrNVRcSR/KudWPUfvKxCeu03bNXE8+84lLMGHL7LyaiIg+iuw/cXMq4etz5BVXddVA/DGDoTUFO3A==",
745
+ "version": "0.17.19-next.1",
746
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.19-next.1.tgz",
747
+ "integrity": "sha512-Qk+eNYW96S9xX45n2fMw4ZGpxALnPauJd4iQS2B/NaUhIb0SHr8zl/eGOAFxeZabBDsaB6bR15u2HAnoOlteQA==",
748
748
  "license": "MIT",
749
749
  "bin": {
750
750
  "parley": "bin/parley.mjs",
@@ -755,9 +755,9 @@
755
755
  }
756
756
  },
757
757
  "node_modules/clavarium-tether": {
758
- "version": "0.1.0-next.13",
759
- "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.13.tgz",
760
- "integrity": "sha512-2H4OcE43KcXnDo44Ptlzu3LM9upLYKEck4u5AWsYQcgvwrkSdG5D7aN4/jMuJALSf1/mJVrD6jvxgUCjb6n+GA==",
758
+ "version": "0.1.0-next.30",
759
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.30.tgz",
760
+ "integrity": "sha512-vnNcggToTPQUmVDu1DrbYjIf2NXtAL4rR0vq5FCXrLSTPifKDKc7a1685O91jb8Bv9/8OFH4mfzTt176mooifQ==",
761
761
  "license": "MIT",
762
762
  "bin": {
763
763
  "tether": "bin/cli.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.81-next.1",
3
+ "version": "0.2.82-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.",
@@ -44,10 +44,10 @@
44
44
  "dependencies": {
45
45
  "@xterm/addon-fit": "^0.11.0",
46
46
  "@xterm/xterm": "^6.0.0",
47
- "clavarium-binder": "0.1.8-next.1",
47
+ "clavarium-binder": "0.1.36-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
- "clavarium-parley": "0.17.11-next.1",
50
- "clavarium-tether": "0.1.0-next.13",
49
+ "clavarium-parley": "0.17.19-next.1",
50
+ "clavarium-tether": "0.1.0-next.30",
51
51
  "mermaid": "11.17.2",
52
52
  "node-pty": "^1.1.0",
53
53
  "pdfjs-dist": "6.4.299",
@@ -12,10 +12,9 @@
12
12
  *
13
13
  * ONE ACCOUNT, ONE TOKEN, SEVERAL TARGETS. A consent for mail+calendar+contacts
14
14
  * yields a single refresh token; this makes one host-only secret and a Tether
15
- * target per kind, each naming that secret. Both providers borrow an open-source
16
- * desktop client verified for all three: Google uses GNOME Online Accounts' over
17
- * IMAP + CalDAV/CardDAV, Microsoft uses its Graph client (mail, calendar and
18
- * contacts all over Microsoft Graph).
15
+ * target per kind, each naming that secret. Both providers borrow Thunderbird's
16
+ * own open-source desktop client, verified for all three: Google over IMAP +
17
+ * CalDAV/CardDAV, Microsoft over Microsoft Graph (mail, calendar and contacts).
19
18
  *
20
19
  * A CREATED TARGET IS GIVEN TO NO ONE. The person grants it per conversation, at
21
20
  * its own level, from the page (Assets > Access) -- like git: one mailbox, many
@@ -23,18 +22,16 @@
23
22
  */
24
23
  import { Refusal } from './conversations.mjs';
25
24
  import { createHash } from 'node:crypto';
26
- import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, pkcePair, newState, PROVIDERS } from './oauth.mjs';
25
+ import { consentUrl, exchangeCode, extractCode, thunderbird, scopeFor, kindsGranted, refreshAccess, pkcePair, newState, PROVIDERS } from './oauth.mjs';
27
26
 
28
27
  /* The loopback the provider sends the code back to; nothing listens there. The
29
28
  person's browser lands on a page that will not load, and they copy the whole
30
29
  address -- which carries the code -- back into Clavarium. The same address
31
- trades the code, so it only has to stay constant. Google's desktop client
32
- accepts any 127.0.0.1 port; Microsoft (Azure) rejects a 127.0.0.1 whose exact
33
- port is not registered but accepts http://localhost with ANY port for a public
34
- client, so Microsoft uses localhost. */
30
+ trades the code, so it must match what the borrowed client registered. Both
31
+ borrowed Thunderbird clients (one for Google, one for Microsoft) registered the
32
+ loopback on any 127.0.0.1 port, so one address serves both. */
35
33
  const REDIRECT = 'http://127.0.0.1:47813/';
36
- const REDIRECT_LOCALHOST = 'http://localhost:47813/';
37
- const redirectFor = (provider) => (provider === 'microsoft' ? REDIRECT_LOCALHOST : REDIRECT);
34
+ const redirectFor = () => REDIRECT;
38
35
  const PENDING_MS = 10 * 60_000;
39
36
  const PENDING_MAX = 20;
40
37
 
@@ -42,7 +39,7 @@ const PENDING_MAX = 20;
42
39
  Tether kind each becomes, and whether the target needs the email address. */
43
40
  const KIND = {
44
41
  mail: { connector: 'mail', kind: 'mail', title: 'Mail', needsUser: true },
45
- calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: false },
42
+ calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: true },
46
43
  contacts: { connector: 'contacts', kind: 'contacts', title: 'Contacts', needsUser: true },
47
44
  };
48
45
  /* What each provider's built-in (Thunderbird) client grants a refresh token for. */
@@ -106,19 +103,32 @@ export class Accounts {
106
103
  let code;
107
104
  try { code = extractCode(redirected, { state }); } catch (e) { throw new Refusal(400, e.message); }
108
105
  const { clientId, clientSecret } = thunderbird(p.provider);
109
- let refreshToken;
110
- try { ({ refreshToken } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: redirectFor(p.provider), code, codeVerifier: p.verifier, fetch: this.#fetch })); }
106
+ let refreshToken, grantedScope;
107
+ try { ({ refreshToken, scope: grantedScope } = await exchangeCode(p.provider, { clientId, clientSecret, redirectUri: redirectFor(p.provider), code, codeVerifier: p.verifier, fetch: this.#fetch })); }
111
108
  catch (e) { throw new Refusal(502, `The connection could not be completed: ${e.message}`); }
112
109
  if (!refreshToken) throw new Refusal(502, 'The account returned no lasting token; allow offline access and try again.');
110
+ /* What was actually allowed. A provider may grant fewer kinds than asked
111
+ (the person unticks one); the token's scope says so, so we make a target
112
+ only for a kind that was really granted, and tell the caller which were
113
+ denied -- no guessing. If the scope is unreadable (matched nothing) we
114
+ trust what was asked, as before. */
115
+ const matched = kindsGranted(p.provider, grantedScope);
116
+ const useScope = matched.length > 0;
117
+ const authorized = useScope ? p.kinds.filter((k) => matched.includes(k)) : p.kinds;
118
+ const denied = useScope ? p.kinds.filter((k) => !matched.includes(k)) : [];
113
119
  /* The token is kept host-only: it can never be attached to a conversation,
114
120
  so it is never delivered to a machine -- the keeper reveals it by name. */
115
121
  const name = secretName(p.provider, p.user);
116
122
  this.#secrets.set({ name, value: refreshToken, hostOnly: true });
117
123
  const label = PROVIDERS[p.provider].label;
118
124
  const made = [];
119
- for (const k of p.kinds) {
125
+ for (const k of authorized) {
120
126
  const spec = KIND[k];
121
- const config = { provider: p.provider };
127
+ /* Pin the client that minted the token onto the target, so the keeper
128
+ refreshes with the same one -- a refresh token is bound to its client,
129
+ and this keeps a target working even if the built-in default later
130
+ moves (the connector prefers config.clientId over its own default). */
131
+ const config = { provider: p.provider, clientId, authorizedKinds: authorized };
122
132
  if (spec.needsUser) config.user = p.user;
123
133
  const target = this.#targets.put({
124
134
  id: targetId(k, p.provider, p.user),
@@ -127,7 +137,33 @@ export class Accounts {
127
137
  });
128
138
  made.push({ id: target?.id ?? targetId(k, p.provider, p.user), title: target?.title, kind: spec.kind });
129
139
  }
130
- return { provider: p.provider, user: p.user, targets: made };
140
+ return { provider: p.provider, user: p.user, targets: made, authorized, denied };
141
+ }
142
+
143
+ /* Check, live, what a connected account is really authorized for right now --
144
+ not only at connection. A refresh host-side (the token never leaves the
145
+ server) reads the token's current scopes, so the page can say "mail yes,
146
+ calendar no" at any time and reflect a permission removed since. Records the
147
+ result on every target of the account, so it shows without another check. */
148
+ async verify({ id } = {}) {
149
+ const all = this.#targets.all?.() ?? [];
150
+ const target = all.find((t) => t.id === id);
151
+ if (!target) throw new Refusal(404, 'No such connexion.');
152
+ const provider = target.config?.provider;
153
+ if (!PROVIDERS[provider]) throw new Refusal(400, 'This connexion is not an account.');
154
+ const secretRef = target.secrets?.refresh;
155
+ const refreshToken = secretRef && this.#secrets.reveal(secretRef);
156
+ if (!refreshToken) throw new Refusal(404, 'The account token is gone; connect it again.');
157
+ const def = thunderbird(provider);
158
+ const clientId = target.config?.clientId || def.clientId;
159
+ let scope, fresh;
160
+ try { ({ scope, refreshToken: fresh } = await refreshAccess(provider, { clientId, clientSecret: def.clientSecret, refreshToken, fetch: this.#fetch })); }
161
+ catch (e) { throw new Refusal(502, `The account could not be checked: ${e.message}`); }
162
+ /* Keep the token current if the provider rotated it on the refresh. */
163
+ if (fresh && fresh !== refreshToken) this.#secrets.set({ name: secretRef, value: fresh, hostOnly: true });
164
+ const authorized = kindsGranted(provider, scope);
165
+ for (const t of all.filter((x) => x.secrets?.refresh === secretRef)) this.#targets.put({ ...t, config: { ...t.config, authorizedKinds: authorized } });
166
+ return { id, provider, all: SUPPORTED[provider], authorized };
131
167
  }
132
168
 
133
169
  #sweep() { const now = Date.now(); for (const [k, v] of this.#pending) if (now - v.at > PENDING_MS) this.#pending.delete(k); }
package/server/api.mjs CHANGED
@@ -19,6 +19,7 @@
19
19
  * POST /api/conversations/<name>/talk {text, answers?, files?, via?}: written in its chat; files from .../talk/file; via 'voice': dictated
20
20
  * POST /api/conversations/<name>/talk/react {to, reaction}: the owner's reaction to a message of the tool (null: taken back)
21
21
  * POST /api/conversations/<name>/chat-name {name}: the name the chat gives its tool ('' : the neutral word of the dictionary)
22
+ * POST /api/conversations/<name>/tasks-binder {binder}: the binder shown beside its chat ('' automatic, '-' none, else an id)
22
23
  * POST /api/conversations/<name>/voice-mark {on}: what is dictated into its terminal starts with a microphone sign (AI tools only)
23
24
  * POST /api/conversations/<name>/talk/file?name=<file name> the body IS a file the person attaches -> {path, name, size}
24
25
  * GET /api/conversations/<name>/talk?last=|days=|before=|from=|since= a part of its chat: the newest messages, those of the
@@ -151,6 +152,9 @@ function readBody(request, max = BODY_MAX) {
151
152
  }
152
153
 
153
154
  /* Returns true when the request was an API request (answered here). */
155
+ /* This run of the server: a page's count of binder changes is of one run, and starts again with the next. */
156
+ const BOOT = Math.random().toString(36).slice(2, 10);
157
+
154
158
  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) {
155
159
  const { pathname } = new URL(request.url ?? '/', 'http://local');
156
160
  if (!pathname.startsWith('/api/')) return false;
@@ -299,7 +303,7 @@ export async function handleApi(request, response, conversations, headers, resou
299
303
  if (pathname === '/api/wifi/scan' && wifi) return send(200, await wifi.scan()), true;
300
304
  if (pathname === '/api/meshcentral' && meshcentral) return send(200, await meshcentral.status()), true;
301
305
  if (pathname === '/api/operators') return send(200, team ? { operators: team.list(), me: identity } : { local: true }), true;
302
- if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: binders.changes() }), true;
306
+ if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: `${BOOT}:${binders.changes()}` }), true;
303
307
  if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
304
308
  /* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
305
309
  if (pathname === '/api/server' && capacity) return send(200, await capacity.about()), true;
@@ -430,6 +434,7 @@ export async function handleApi(request, response, conversations, headers, resou
430
434
  kept host-only, a Tether target made): see accounts.mjs. */
431
435
  if (pathname === '/api/accounts/consent' && accounts) return send(200, accounts.consent(body)), true;
432
436
  if (pathname === '/api/accounts/connect' && accounts) { const made = await accounts.connect(body); return send(201, made), true; }
437
+ if (pathname === '/api/accounts/verify' && accounts) { const r = await accounts.verify(body); return send(200, r), true; }
433
438
  /* Assets > Access: the owner sets a conversation's level and rules on a
434
439
  target, decides a call that waited, or removes a target. Each is an op the
435
440
  keeper runs as the owner (person), never as an agent. */
@@ -637,6 +642,8 @@ export async function handleApi(request, response, conversations, headers, resou
637
642
  if (asking) return send(200, conversations.setAskFirst(decodeURIComponent(asking[1]), body.on)), true;
638
643
  const naming = /^\/api\/conversations\/([^/]+)\/chat-name$/.exec(pathname);
639
644
  if (naming) return send(200, conversations.setChatName(decodeURIComponent(naming[1]), body.name)), true;
645
+ const beside = /^\/api\/conversations\/([^/]+)\/tasks-binder$/.exec(pathname);
646
+ if (beside) return send(200, conversations.setTasksBinder(decodeURIComponent(beside[1]), body.binder)), true;
640
647
  /* The list: folders and order, the same on every device (conversations.mjs). */
641
648
  if (pathname === '/api/instance' && instance) return send(200, instance.setName(body.name)), true;
642
649
  if (pathname === '/api/dictation' && voice) return send(200, voice.set(body)), true;
@@ -45,7 +45,7 @@ export class Binders {
45
45
  the owner's devices (optional), told of a card a person owns that came due. */
46
46
  constructor({ dataDir, resources, conversations, dockets = null, team = null, alert = null, now = () => Date.now() }) {
47
47
  this.#resources = resources; this.#conversations = conversations; this.#dockets = dockets; this.#team = team; this.#alert = alert;
48
- this.#keeper = keeper(`${dataDir}/binder`, { sides: () => this.#sides(), now });
48
+ this.#keeper = keeper(`${dataDir}/binder`, { sides: () => this.#sides(), now, people: () => this.people() });
49
49
  this.#keeper.store.onChange((line) => { this.#changes++; this.#heard(line); });
50
50
  }
51
51
 
@@ -110,9 +110,12 @@ export class Binders {
110
110
  }
111
111
  /* Who may own a record, or be given a list. */
112
112
  people(identity = '') {
113
+ /* Who signed in, as the store names their ownership ('me' resolves to this). The matrix
114
+ colours a card "à moi" by matching this, so the page is told which entry is the viewer. */
115
+ const meId = `person:${identity || 'owner'}`;
113
116
  const persons = (this.#team?.list?.() ?? []).map((o) => ({ id: `person:${String(o.email ?? o.id ?? '').toLowerCase()}`, kind: 'person', name: String(o.email ?? o.id ?? '') })).filter((p) => p.name);
114
- if (!persons.length) persons.push({ id: `person:${identity || 'owner'}`, kind: 'person', name: identity || 'Owner' });
115
- return [...persons, ...this.#conversations().map((name) => ({ id: `${AGENT}${name}`, kind: 'agent', name }))];
117
+ if (!persons.length) persons.push({ id: meId, kind: 'person', name: identity || 'Owner' });
118
+ return [...persons.map((p) => (p.id === meId ? { ...p, me: true } : p)), ...this.#conversations().map((name) => ({ id: `${AGENT}${name}`, kind: 'agent', name }))];
116
119
  }
117
120
  /* What each conversation was given: { name: { lists, waiting } }, waiting being the
118
121
  records of those lists that wait for a person's tick (a list with a gate, not approved). */
@@ -49,6 +49,13 @@ export const RESERVE_DISK_MAX_MB = 1024 * 1024;
49
49
  export const RESERVE_MEMORY_MAX_MB = 256 * 1024;
50
50
  export const ROOM_MS = 10_000;
51
51
  export const USAGE_MS = 5 * 60_000;
52
+ /* A sleeping machine whose qemu still holds at least this much host memory is a
53
+ suspend that did not free it (see the host program's `vm suspend`); the watch
54
+ reclaims it. */
55
+ export const RECLAIM_MIN_MB = 128;
56
+ /* The same machine is not reclaimed again within this, so a stubborn one (rare,
57
+ needs a VM-manager restart) is reported once, not looped on. */
58
+ export const RECLAIM_EVERY_MS = 30 * 60_000;
52
59
  /* The page shows its small gauge when disk or memory is fuller than this, or
53
60
  when what is free is under this many times the reserve. */
54
61
  export const HIGH_PERCENT = 85;
@@ -92,7 +99,7 @@ const percent = (part, all) => (all > 0 ? Math.round((part / all) * 100) : 0);
92
99
  export class Capacity {
93
100
  /* What the machines take on their disk, as last measured (MB), or undefined. */
94
101
  machinesUsedMb() { const u = this.#usage; if (!u) return undefined; return Object.values(u.machines ?? {}).reduce((a, b) => a + b, 0) + (u.shelf ?? 0) + (u.images ?? 0); }
95
- #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
102
+ #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #reclaim; #reclaimEveryMs; #sweeping = false; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
96
103
 
97
104
  /* `run(argv)`: the host program. `store`: where the reserve is kept.
98
105
  `conversations`: what each machine was given. `shelf`: how large a
@@ -100,8 +107,8 @@ export class Capacity {
100
107
  /* `roomMs`: how long what is free is taken as known (ROOM_MS). */
101
108
  /* `sleep(name)`, `alert(payload)`, `say(name, text)`: what watch() does
102
109
  when what is free falls under the reserve. */
103
- constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null }) {
104
- this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say;
110
+ constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null, reclaim = null, reclaimEveryMs = RECLAIM_EVERY_MS }) {
111
+ this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say; this.#reclaim = reclaim; this.#reclaimEveryMs = reclaimEveryMs;
105
112
  this.#run = run; this.#store = store; this.#conversations = conversations; this.#shelf = shelf; this.#now = now;
106
113
  }
107
114
 
@@ -288,9 +295,53 @@ export class Capacity {
288
295
  return done;
289
296
  }
290
297
 
298
+ /* WATCHED too, and on its own: machines that are ASLEEP (not awake) yet whose
299
+ qemu still holds the host RAM -- a suspend that did not end the process,
300
+ including ones left stuck before this ran. Each is freed through the host
301
+ program (`vm reclaim`: wake+resleep, then a clean stop if needed), the owner
302
+ told, and not tried again within reclaimEveryMs, so a stubborn one (rare,
303
+ the VM manager would need a restart) is reported once, not looped on. Only
304
+ asleep machines are touched; the others are never disturbed, and the VM
305
+ manager is never restarted. Resolves with what was reclaimed. */
306
+ async reclaimSleepers() {
307
+ if (!this.#reclaim || this.#sweeping) return [];
308
+ this.#sweeping = true;
309
+ try {
310
+ const f = this.#figures(await this.room({ fresh: true }).catch(() => null));
311
+ if (!f) return [];
312
+ const awake = new Set(this.#conversations.awake?.() ?? []);
313
+ const holding = f.machines.filter((m) => m.name && !m.shelf && !awake.has(m.name) && m.rssMb >= RECLAIM_MIN_MB);
314
+ if (!holding.length) return [];
315
+ const now = this.#now();
316
+ const at = this.#store.get('reclaim')?.at ?? {};
317
+ const done = [];
318
+ for (const m of holding) {
319
+ if (at[m.name] && now - at[m.name] < this.#reclaimEveryMs) continue;
320
+ at[m.name] = now;
321
+ this.#store.put({ name: 'reclaim', at });
322
+ const held = m.rssMb;
323
+ const how = await Promise.resolve(this.#reclaim(m.name)).then((x) => String(x || ''), () => '');
324
+ const by = how.includes('resleep') ? ' by waking it and putting it back to sleep'
325
+ : how.includes('stop') ? ' with a clean stop (it will boot when you open it)'
326
+ : '';
327
+ const after = this.#figures(await this.room({ fresh: true }).catch(() => null));
328
+ const freed = !after?.machines.some((x) => x.name === m.name && !awake.has(x.name) && x.rssMb >= RECLAIM_MIN_MB);
329
+ this.#alert?.(freed
330
+ ? { title: "Reclaimed a sleeping machine's memory", body: `${m.name} was asleep but still held ${gb(held)} (its sleep had not freed it); its memory was reclaimed${by}.`, url: '/?open=settings&at=resources' }
331
+ : { title: 'A sleeping machine still holds memory', body: `${m.name} was asleep but still held ${gb(held)} and could not be freed; the VM manager may need a restart.`, url: '/?open=settings&at=resources' });
332
+ this.#say?.(m.name, freed
333
+ ? `This machine was asleep but still held ${gb(held)} of memory (its sleep had not freed it). Its memory was reclaimed${by}; it still wakes when you open it.`
334
+ : `This machine was asleep but still held ${gb(held)} of memory, and it could not be freed automatically — the VM manager may need a restart.`);
335
+ done.push({ name: m.name, heldMb: held, freed });
336
+ }
337
+ return done;
338
+ } finally { this.#sweeping = false; }
339
+ }
340
+
291
341
  /* Watches every `everyMs`; returns what stops it. */
292
342
  start(everyMs = WATCH_MS) {
293
- const timer = setInterval(() => { void this.watch().catch(() => {}); }, everyMs);
343
+ const tick = () => { void this.watch().catch(() => {}).finally(() => { void this.reclaimSleepers().catch(() => {}); }); };
344
+ const timer = setInterval(tick, everyMs);
294
345
  timer.unref?.();
295
346
  return () => clearInterval(timer);
296
347
  }
@@ -608,6 +608,18 @@ export class Conversations {
608
608
  return this.#store.get(name);
609
609
  }
610
610
 
611
+ /* WHICH BINDER ITS CHAT SHOWS BESIDE IT (the side panel), the same on every device:
612
+ '' for the automatic choice (the first binder of batches it was given), '-' for none,
613
+ else a binder's id. Which binders it was given is Binder's: one it no longer has
614
+ falls back to the automatic choice on the page. */
615
+ setTasksBinder(name, given) {
616
+ const c = this.#store.get(name);
617
+ if (!c) throw new Refusal(404, 'No such conversation.');
618
+ if (typeof given !== 'string' || given.length > 100 || !/^(|-|[a-z0-9][a-z0-9._-]*)$/.test(given)) throw new Refusal(400, 'Give a binder\'s id, "-" for none, or nothing for the automatic choice.');
619
+ this.#store.patch(name, { tasksBinder: given || undefined });
620
+ return this.#store.get(name);
621
+ }
622
+
611
623
  /* THE NAME A PERSON READS, changed at any time; its identifier stays.
612
624
  Kept only when it differs from the identifier: a conversation made
613
625
  before free names is read by its identifier, and nothing is rewritten. */
@@ -696,7 +696,11 @@ export class GitKeeper {
696
696
  /* Its machine did not run them: tried again later, when it may. */
697
697
  if (checks.status !== 'unavailable') held.done.set(b, tip.id);
698
698
  const why = checks.status === 'failed' ? `the checks failed in the machine of ${conversation}` : checks.status === 'none' ? 'automatic sending needs passing checks, and none is set (no pre-push hook, no check command)' : `the checks could not run: the machine of ${conversation} does not run`;
699
- return once(`checks-${checks.status}`, { what: `Not sent: ${why}.`, tell: true, ...(checks.status === 'failed' ? { ai: `the checks failed for ${plain(b)}, it was not sent` } : {}) }), false;
699
+ /* On a failure the agent is given the END OF THE CHECK OUTPUT, not only
700
+ that it failed: it is the one that can fix it, and guessing without the
701
+ output wastes its time. */
702
+ const tail = String(checks.output ?? '').trim();
703
+ return once(`checks-${checks.status}`, { what: `Not sent: ${why}.`, tell: true, ...(checks.status === 'failed' ? { ai: `the checks failed for ${plain(b)}, it was not sent${tail ? `. The end of the output:\n\n${tail}` : ''}` } : {}) }), false;
700
704
  }
701
705
  }
702
706
  const checked = s.checks ? 'checks passed' : 'no checks asked for';
package/server/main.mjs CHANGED
@@ -411,7 +411,19 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
411
411
  /* Connecting a mailbox, calendar or address book by token: the consent happens
412
412
  in the owner's browser, the refresh token is kept host-only (never in a
413
413
  machine) and a Tether target is made for it: see accounts.mjs. */
414
- const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec) } });
414
+ const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec), all: () => tethers.store().targets() } });
415
+ /* A calendar target made before it needed the account address (Google CalDAV
416
+ puts it in the URL) carries none. The same account's mailbox or address book
417
+ has it -- they share the one refresh token -- so fill it in from a sibling,
418
+ once, with no reconnection asked of anyone. */
419
+ (() => {
420
+ const store = tethers.store();
421
+ for (const t of store.targets()) {
422
+ if (t.kind !== 'calendar' || t.config?.user || !t.secrets?.refresh) continue;
423
+ const sib = store.targets().find((o) => o.secrets?.refresh === t.secrets.refresh && o.config?.user);
424
+ if (sib) store.putTarget({ ...t, config: { ...t.config, user: sib.config.user } });
425
+ }
426
+ })();
415
427
  /* A repository's origin kept up to date, checks run in the machine, and
416
428
  automatic sending to the branches the owner listed: see gitkeeper.mjs. */
417
429
  /* What could not be read is told to the agents that write in the repository, where they can act. */
@@ -458,6 +470,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
458
470
  alert: (payload) => { void alerts.tell(payload); } });
459
471
  /* Its machine restarted or built again: said in its chat, and the tool told to read it again. */
460
472
  all.renewed = (name, text, running) => talk.renewed(name, text, running);
473
+ /* A Tether call waiting for the owner is said in its conversation's thread, with Accept / Refuse. */
474
+ tethers.announce = (name, event) => { try { return talk.event(name, event); } catch { return null; } };
461
475
  /* A device given a conversation that talks through the app talks there too. */
462
476
  door.talk = talk;
463
477
  /* AFTER AN UPDATE, the machines that run get the new tools at once (parley, docket: they serve from
@@ -512,6 +526,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
512
526
  const capacity = new Capacity({ run: asHost, store: new Store(`${dataDir}/server.json`), conversations: all, shelf, ...(serverRoomMs === undefined ? {} : { roomMs: serverRoomMs }),
513
527
  /* Under the reserve: the machine that takes the most put to sleep, the owner told, and its chat. */
514
528
  sleep: (name) => { events.add({ kind: 'machine', text: `Machine of ${name} put to sleep: this server was short of room`, conversation: name }); return all.sleep(name); }, alert: (payload) => { events.add({ kind: 'server', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload); },
529
+ /* A machine asleep but still holding its RAM (a suspend that did not free it): its memory reclaimed, only that machine touched. */
530
+ reclaim: (name) => { events.add({ kind: 'machine', text: `Machine of ${name}: memory reclaimed (it was asleep but still held RAM)`, conversation: name }); return vms.reclaim(name).then((r) => (r.stdout || '').trim()); },
515
531
  say: (name, text) => { try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine' }); } catch { /* its chat may be off */ } } });
516
532
  all.room = (ask) => capacity.check(ask);
517
533
  const stopWatch = capacity.start();
package/server/oauth.mjs CHANGED
@@ -37,14 +37,14 @@ const b64url = (buf) => Buffer.from(buf).toString('base64url');
37
37
 
38
38
  /* Per-provider endpoints, the scopes we may ask for by kind, and a built-in,
39
39
  already-verified open-source desktop client as the default (the `thunderbird`
40
- field, kept by that name for its callers). WHICH client matters: a client is
41
- only granted the scopes its app was verified for. For GOOGLE we borrow GNOME
42
- Online Accounts' client, verified for mail AND calendar AND contacts, so one
43
- consent gives all three. For MICROSOFT we use Thunderbird's client, verified
44
- for mail (IMAP) only; Microsoft calendar/contacts go over Graph and need a
45
- Graph-verified client -- see card #110. `consentExtra` is what a provider
46
- needs on the consent URL to return a refresh token; `offlineScope` is the same
47
- thing when it is a scope rather than a parameter (Microsoft). */
40
+ field). We borrow THUNDERBIRD's own client for BOTH providers: each registered
41
+ the loopback 127.0.0.1 redirect on any port, so the person always lands on the
42
+ same copy-pastable http://127.0.0.1 address, and each is cleared for the three
43
+ kinds -- Google's client carries the mail + CalDAV + CardDAV scopes; Microsoft's
44
+ takes mail, calendar and contacts over Graph (a multitenant public client, by
45
+ dynamic consent). `consentExtra` is what a provider needs on the consent URL to
46
+ return a refresh token; `offlineScope` is the same thing when it is a scope
47
+ rather than a parameter (Microsoft). */
48
48
  export const PROVIDERS = {
49
49
  google: {
50
50
  label: 'Google',
@@ -58,12 +58,16 @@ export const PROVIDERS = {
58
58
  calendar: 'https://www.googleapis.com/auth/calendar',
59
59
  contacts: 'https://www.googleapis.com/auth/carddav',
60
60
  },
61
- /* GNOME Online Accounts' built-in client (open source, embedded secret
62
- sanctioned by Google for an installed app). Verified for mail,
63
- calendar and contacts -- unlike Thunderbird's, which carries mail only. */
61
+ /* Thunderbird's own built-in Google client (open source, embedded secret
62
+ sanctioned by Google for an installed app; comm-central
63
+ OAuth2Providers.sys.mjs). Its GOOGLE_SCOPES carry mail AND CalDAV AND
64
+ CardDAV, so one consent gives all three -- the same loopback 127.0.0.1
65
+ redirect as before. Using Thunderbird for Google too means one borrowed
66
+ identity for both providers. (GNOME Online Accounts' client
67
+ 44438659992-... worked as well; we unified on Thunderbird.) */
64
68
  thunderbird: {
65
- clientId: '44438659992-7kgjeitenc16ssihbtdjbgguch7ju55s.apps.googleusercontent.com',
66
- clientSecret: '-gMLuQyDiI0XrQS_vx_mhuYF',
69
+ clientId: '406964657835-aq8lmia8j95dhl1a2bvharmfk3t1hgqj.apps.googleusercontent.com',
70
+ clientSecret: 'kSmqreRr0qwBWJgbf5Y-PjSU',
67
71
  },
68
72
  },
69
73
  microsoft: {
@@ -73,17 +77,23 @@ export const PROVIDERS = {
73
77
  pkce: true,
74
78
  consentExtra: {},
75
79
  offlineScope: 'offline_access',
76
- /* Microsoft over Graph: GNOME Online Accounts' client is a Graph client,
77
- so mail, calendar and contacts all go through graph.microsoft.com (the
78
- mail connector uses its Graph path for Microsoft). mail.send is needed
79
- to send. GOA's client is verified for all of these. */
80
+ /* Microsoft over Graph: mail, calendar and contacts all go through
81
+ graph.microsoft.com (the mail connector uses its Graph path for
82
+ Microsoft). mail.send is needed to send. Thunderbird's public client
83
+ takes these delegated scopes by dynamic consent. */
80
84
  scopes: {
81
85
  mail: 'mail.readwrite mail.send',
82
86
  calendar: 'calendars.readwrite',
83
87
  contacts: 'contacts.readwrite',
84
88
  },
89
+ /* Thunderbird's built-in Microsoft client (open source, public, no secret;
90
+ comm-central OAuth2Providers.sys.mjs). It registered the loopback
91
+ 127.0.0.1 redirect on ANY port, so we reuse the same http://127.0.0.1
92
+ address as Google -- the person copies it from the bar. (GNOME Online
93
+ Accounts' Graph client, b155a604-..., registered only a custom-scheme
94
+ goa-oauth2:// redirect a browser cannot surface, so we left it.) */
85
95
  thunderbird: {
86
- clientId: 'b155a604-3c31-4079-93b0-6bb6aa9d5464',
96
+ clientId: '9e5f94bc-e8a4-4e73-b8be-63364c29d753',
87
97
  clientSecret: null,
88
98
  },
89
99
  },
@@ -128,6 +138,22 @@ export function scopeFor(name, kinds = ['mail']) {
128
138
  return [...new Set(parts)].join(' ');
129
139
  }
130
140
 
141
+ /* Which kinds a granted scope string actually covers. A provider may grant fewer
142
+ scopes than asked (the person unticks one on the consent screen); the token's
143
+ `scope` field says what was allowed, so we never have to guess. A kind counts as
144
+ granted when the first (primary) scope token of its request appears in the
145
+ granted string, matched case-insensitively -- providers echo scopes back in
146
+ their own casing and URL form (Microsoft returns
147
+ `https://graph.microsoft.com/Calendars.ReadWrite` for a requested
148
+ `calendars.readwrite`). Returns [] when the scope is unknown, so a caller can
149
+ fall back to trusting what it asked for. */
150
+ export function kindsGranted(name, granted = '') {
151
+ const p = provider(name);
152
+ const g = String(granted).toLowerCase();
153
+ if (!g) return [];
154
+ return Object.keys(p.scopes).filter((k) => g.includes(p.scopes[k].split(/\s+/)[0].toLowerCase()));
155
+ }
156
+
131
157
  /* The URL the person's browser opens to sign in and allow. `redirectUri` is the
132
158
  loopback the provider sends the code back to (http://127.0.0.1:PORT). */
133
159
  export function consentUrl(name, { clientId, redirectUri, scope, state, codeChallenge, loginHint } = {}) {