clavarium 0.2.85-next.1 → 0.2.87-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.85-next.1",
3
+ "version": "0.2.87-next.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.85-next.1",
9
+ "version": "0.2.87-next.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.85-next.1",
3
+ "version": "0.2.87-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
@@ -22,7 +22,7 @@
22
22
  */
23
23
  import { Refusal } from './conversations.mjs';
24
24
  import { createHash } from 'node:crypto';
25
- 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';
26
26
 
27
27
  /* The loopback the provider sends the code back to; nothing listens there. The
28
28
  person's browser lands on a page that will not load, and they copy the whole
@@ -103,23 +103,32 @@ export class Accounts {
103
103
  let code;
104
104
  try { code = extractCode(redirected, { state }); } catch (e) { throw new Refusal(400, e.message); }
105
105
  const { clientId, clientSecret } = thunderbird(p.provider);
106
- let refreshToken;
107
- 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 })); }
108
108
  catch (e) { throw new Refusal(502, `The connection could not be completed: ${e.message}`); }
109
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)) : [];
110
119
  /* The token is kept host-only: it can never be attached to a conversation,
111
120
  so it is never delivered to a machine -- the keeper reveals it by name. */
112
121
  const name = secretName(p.provider, p.user);
113
122
  this.#secrets.set({ name, value: refreshToken, hostOnly: true });
114
123
  const label = PROVIDERS[p.provider].label;
115
124
  const made = [];
116
- for (const k of p.kinds) {
125
+ for (const k of authorized) {
117
126
  const spec = KIND[k];
118
127
  /* Pin the client that minted the token onto the target, so the keeper
119
128
  refreshes with the same one -- a refresh token is bound to its client,
120
129
  and this keeps a target working even if the built-in default later
121
130
  moves (the connector prefers config.clientId over its own default). */
122
- const config = { provider: p.provider, clientId };
131
+ const config = { provider: p.provider, clientId, authorizedKinds: authorized };
123
132
  if (spec.needsUser) config.user = p.user;
124
133
  const target = this.#targets.put({
125
134
  id: targetId(k, p.provider, p.user),
@@ -128,7 +137,33 @@ export class Accounts {
128
137
  });
129
138
  made.push({ id: target?.id ?? targetId(k, p.provider, p.user), title: target?.title, kind: spec.kind });
130
139
  }
131
- 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 };
132
167
  }
133
168
 
134
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
@@ -430,6 +430,7 @@ export async function handleApi(request, response, conversations, headers, resou
430
430
  kept host-only, a Tether target made): see accounts.mjs. */
431
431
  if (pathname === '/api/accounts/consent' && accounts) return send(200, accounts.consent(body)), true;
432
432
  if (pathname === '/api/accounts/connect' && accounts) { const made = await accounts.connect(body); return send(201, made), true; }
433
+ if (pathname === '/api/accounts/verify' && accounts) { const r = await accounts.verify(body); return send(200, r), true; }
433
434
  /* Assets > Access: the owner sets a conversation's level and rules on a
434
435
  target, decides a call that waited, or removes a target. Each is an op the
435
436
  keeper runs as the owner (person), never as an agent. */
package/server/main.mjs CHANGED
@@ -411,7 +411,7 @@ 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
415
  /* A repository's origin kept up to date, checks run in the machine, and
416
416
  automatic sending to the branches the owner listed: see gitkeeper.mjs. */
417
417
  /* What could not be read is told to the agents that write in the repository, where they can act. */
package/server/oauth.mjs CHANGED
@@ -138,6 +138,22 @@ export function scopeFor(name, kinds = ['mail']) {
138
138
  return [...new Set(parts)].join(' ');
139
139
  }
140
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
+
141
157
  /* The URL the person's browser opens to sign in and allow. `redirectUri` is the
142
158
  loopback the provider sends the code back to (http://127.0.0.1:PORT). */
143
159
  export function consentUrl(name, { clientId, redirectUri, scope, state, codeChallenge, loginHint } = {}) {
package/web/app.js CHANGED
@@ -4162,6 +4162,32 @@
4162
4162
  if (chosen.target) {
4163
4163
  const t = chosen.target;
4164
4164
  detail.append(el('p', 'hint', ['live', connexionSub(t.kind), t.config?.user].filter(Boolean).join(' · ')));
4165
+ /* The account's real permissions, read from the token (server-side) --
4166
+ shown here so they can be checked at any time, not only at connection.
4167
+ "Re-check" reads them live, to catch a permission removed since. */
4168
+ if (['google', 'microsoft'].includes(t.config?.provider)) {
4169
+ const KINDS3 = ['mail', 'calendar', 'contacts'];
4170
+ const perms = el('div', 'as-perms');
4171
+ detail.append(perms);
4172
+ const draw = (authorized) => {
4173
+ perms.replaceChildren();
4174
+ if (Array.isArray(authorized)) {
4175
+ const line = el('p', 'hint');
4176
+ line.append(el('b', '', 'Permissions: '));
4177
+ line.append(document.createTextNode(KINDS3.map((k) => `${k} ${authorized.includes(k) ? '✓' : '✗'}`).join(' ')));
4178
+ perms.append(line);
4179
+ } else { perms.append(el('p', 'hint', 'Permissions not checked yet.')); }
4180
+ const btn = el('button', '', Array.isArray(authorized) ? 'Re-check' : 'Check permissions');
4181
+ btn.type = 'button';
4182
+ btn.addEventListener('click', async () => {
4183
+ btn.disabled = true; btn.textContent = 'Checking…';
4184
+ try { const r = await post(`${API}/accounts/verify`, { id: t.id }); draw(r.authorized); }
4185
+ catch (e) { perms.append(el('p', 'error', e.message)); btn.disabled = false; btn.textContent = 'Re-check'; }
4186
+ });
4187
+ perms.append(btn);
4188
+ };
4189
+ draw(Array.isArray(t.config?.authorizedKinds) ? t.config.authorizedKinds : null);
4190
+ }
4165
4191
  if (chosen.siblings?.length) {
4166
4192
  const a = el('p', 'as-assoc hint');
4167
4193
  a.append(el('b', '', 'Linked'), document.createTextNode(` to the same account: ${chosen.siblings.join(', ')}. They share the account's token (kept on the server); rights are given separately.`));
@@ -6217,9 +6243,21 @@
6217
6243
  const btn = $('connexion-connect'); const was = btn.textContent; btn.disabled = true; btn.textContent = 'Connecting...';
6218
6244
  try {
6219
6245
  const made = await post(`${API}/accounts/connect`, { redirected: $('connexion-code').value.trim() });
6220
- if (made?.targets?.[0]) assetOpen = `connexion:${made.targets[0].id}`;
6221
- assetsAdding = '';
6222
- $('connexion-new').reset(); setConnexionProvider('google');
6246
+ const denied = Array.isArray(made?.denied) ? made.denied : [];
6247
+ if (denied.length) {
6248
+ /* A partial grant: say plainly what was allowed and what was not,
6249
+ from the token itself, and keep the form so they can allow the rest. */
6250
+ const word = (k) => ({ mail: 'mail', calendar: 'calendar', contacts: 'contacts' }[k] || k);
6251
+ const ok = (made.authorized || []).map(word);
6252
+ const no = denied.map(word);
6253
+ $('connexion-error').textContent = `${ok.length ? `Connected for ${ok.join(', ')}. ` : ''}Not allowed: ${no.join(', ')} — connect again and allow ${no.length > 1 ? 'them' : 'it'} on the provider's screen.`;
6254
+ $('connexion-error').hidden = false;
6255
+ $('connexion-code').value = ''; $('connexion-paste').hidden = true;
6256
+ } else {
6257
+ if (made?.targets?.[0]) assetOpen = `connexion:${made.targets[0].id}`;
6258
+ assetsAdding = '';
6259
+ $('connexion-new').reset(); setConnexionProvider('google');
6260
+ }
6223
6261
  } catch (error) { $('connexion-error').textContent = error.message; $('connexion-error').hidden = false; }
6224
6262
  btn.disabled = false; btn.textContent = was;
6225
6263
  await paintAssets();
package/web/style.css CHANGED
@@ -59,6 +59,8 @@ button:focus-visible, input:focus-visible { outline: 2px solid var(--brass); out
59
59
  .row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
60
60
  .hint { color: var(--ink2); font-size: .75rem; margin: 0; }
61
61
  .error { color: var(--danger); font-size: .8125rem; margin: 0; }
62
+ .as-perms { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; margin: 8px 0; }
63
+ .as-perms button { font-size: .75rem; padding: 4px 10px; }
62
64
  #room { grid-column: 2; grid-row: 1 / span 2; min-width: 0; min-height: 0; display: flex; flex-direction: column; }
63
65
  /* The bar wraps onto a second line rather than squeeze the name away or break a button's label in two. */
64
66
  header { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 8px; padding: 6px 10px; background: var(--bar); border-bottom: 1px solid var(--line); min-height: 44px; }