@volter/teams 0.2.29 → 0.2.31

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.
package/board-owner.mjs CHANGED
@@ -46,6 +46,14 @@ export const BOARD_OPERATION_VERBS = new Set(['serve', 'daemon', 'dispatch', 'in
46
46
  export const CALLER_FACTS = ['SUPERCODE_AGENT_ID', 'SUPERCODE_AUTOMATION', 'SUPERCODE_CONTEXT', 'HERMES_PROFILE', 'USER', 'SUPERCODE_CALLER', 'SUPERCODE_RUN_LAUNCH'];
47
47
  export const callerFacts = (env = process.env) => Object.fromEntries(CALLER_FACTS.filter((key) => env[key]).map((key) => [key, env[key]]));
48
48
 
49
+ /**
50
+ * What a caller says of an answer marked `unanswered` (the owner took the request and the call ended with no answer):
51
+ * the outcome is unknown, and the card is read before the verb is run again. `what` names the verb or tool.
52
+ */
53
+ export function unansweredText(answer, what) {
54
+ return `${String(answer.stderr ?? '').trim() || 'the board owner gave no answer'}; whether ${what} ran is unknown: read the card with \`supercode workflow show <id>\` before running it again\n`;
55
+ }
56
+
49
57
  /**
50
58
  * Send one verb to the owner of the home at `root`: answers `{ code, stdout, stderr }`. A home whose owner is not
51
59
  * running answers that, with what starts it; nothing else runs the verb.
@@ -56,25 +64,29 @@ export function askBoardOwner(root, request) {
56
64
  return new Promise((done) => {
57
65
  let answer = '';
58
66
  let settled = false;
67
+ // once the request is written the owner may have run the verb: a failure after that is `unanswered` (whether it
68
+ // ran is unknown), never a plain failure a caller would take as "nothing happened" and run again
69
+ let sent = false;
59
70
  const finish = (value) => { if (!settled) { settled = true; done(value); } };
71
+ const lost = (stderr) => finish({ code: 1, stdout: '', stderr, ...(sent ? { unanswered: true } : {}) });
60
72
  const socket = connect(path);
61
73
  socket.setEncoding('utf8');
62
74
  // The request is one line, and the connection stays open both ways until the answer's line has come: an answer that
63
75
  // takes its time (a Teams lookup, a reread home) is never lost to a closed side.
64
- socket.on('connect', () => socket.write(`${JSON.stringify({ v: 1, ...request })}\n`));
76
+ socket.on('connect', () => { sent = true; socket.write(`${JSON.stringify({ v: 1, ...request })}\n`); });
65
77
  socket.on('data', (chunk) => {
66
78
  answer += chunk;
67
79
  const end = answer.indexOf('\n');
68
80
  if (end < 0) return;
69
81
  socket.end();
70
- try { finish(JSON.parse(answer.slice(0, end))); } catch { finish({ code: 1, stdout: '', stderr: `the board owner of ${root} answered nothing readable\n` }); }
82
+ try { finish(JSON.parse(answer.slice(0, end))); } catch { lost(`the board owner of ${root} answered nothing readable\n`); }
71
83
  });
72
- socket.on('close', () => finish({ code: 1, stdout: '', stderr: `the board owner of ${root} closed the call before answering\n` }));
84
+ socket.on('close', () => lost(`the board owner of ${root} closed the call before answering\n`));
73
85
  socket.on('error', (error) => {
74
- const down = ['ENOENT', 'ECONNREFUSED'].includes(error.code);
75
- finish({ code: 1, stdout: '', stderr: down
86
+ const down = !sent && ['ENOENT', 'ECONNREFUSED'].includes(error.code);
87
+ lost(down
76
88
  ? `the boards of ${root} have no running owner: \`supercode workflow serve --root ${root}\` is it (an install's keeper runs it)\n`
77
- : `the board owner of ${root} could not be reached: ${error.message}\n` });
89
+ : sent ? `the board owner of ${root} dropped the call after it was sent: ${error.message}\n` : `the board owner of ${root} could not be reached: ${error.message}\n`);
78
90
  });
79
91
  });
80
92
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@volter/teams",
3
- "version": "0.2.29",
3
+ "version": "0.2.31",
4
4
  "type": "module",
5
5
  "description": "Volter Teams, the neutral team plane: machine identity and daemon core, the local door and server link, admission from machine grants, product doors, and the Teams server's neutral routes (company RFC 0008).",
6
6
  "license": "MIT",
package/server/http.mjs CHANGED
@@ -10,7 +10,7 @@ import { permissionRoute } from './permissions.mjs';
10
10
  import { randomBytes } from 'node:crypto';
11
11
  import { bearer, hashToken, canManage, isAdmin, makeToken } from './auth.mjs';
12
12
  import { ContractError, canonicalJson, validationFailure, cursorHash, cursorToken, sha256 } from './wire.mjs';
13
- import { machineGrantRoute, machineGrantRows, closeMachineChannels, closeChannelsFor } from './machine-link.mjs';
13
+ import { machineGrantRoute, machineGrantRows, closeMachineChannels, closeChannelsFor, closeCredentialChannels } from './machine-link.mjs';
14
14
  import { publicationRoute, publisherRevocation } from './publications.mjs';
15
15
  import { exact, parseJson as parseRequestJson } from './request-json.mjs';
16
16
  import { identityOf } from './identity.mjs';
@@ -206,7 +206,7 @@ async function createCredential(api,req,res,auth,requestId){
206
206
  }
207
207
  async function revokeCredential(api,req,res,auth,id,requestId){
208
208
  if(!['user','service'].includes(auth.kind))fail(403,'forbidden','credential kind cannot use this operation');const credential=await api.store.one('SELECT * FROM credentials WHERE id=? AND revoked_at IS NULL',[id]);if(!credential)fail(404,'not_found','not found');const globalUser=credential.kind==='user'&&credential.team_id===null;if(globalUser?credential.principal_id!==auth.principal_id:credential.team_id!==auth.team_id||credential.principal_id!==auth.principal_id&&!isAdmin(auth))fail(404,'not_found','not found');
209
- const now=api.clock.nowMs(),guards=[...authGuards(auth,now),{sql:"SELECT 1 ok FROM credentials c WHERE c.id=? AND c.revoked_at IS NULL AND ((c.kind='user' AND c.team_id IS NULL AND c.principal_id=?) OR (c.team_id=? AND (c.principal_id=? OR ?=1))) AND (c.id!=? OR c.kind!='user' OR c.team_id IS NOT NULL OR NOT EXISTS (SELECT 1 FROM memberships m WHERE m.principal_id=c.principal_id AND m.role='owner' AND m.active=1) OR EXISTS (SELECT 1 FROM credentials other WHERE other.principal_id=c.principal_id AND other.kind='user' AND other.team_id IS NULL AND other.id!=c.id AND other.revoked_at IS NULL AND (other.expires_at IS NULL OR other.expires_at>?)))",params:[id,auth.principal_id,auth.team_id,auth.principal_id,isAdmin(auth)?1:0,auth.credential_id,now],code:'conflict',status:409,message:'credential changed or would lock out owner'}];await guardedMutation(api,res,auth,guards,[{sql:'UPDATE credentials SET revoked_at=? WHERE id=?',params:[now,id]}],{status:204,body:null,targetId:id});send(res,204,null,requestId);
209
+ const now=api.clock.nowMs(),guards=[...authGuards(auth,now),{sql:"SELECT 1 ok FROM credentials c WHERE c.id=? AND c.revoked_at IS NULL AND ((c.kind='user' AND c.team_id IS NULL AND c.principal_id=?) OR (c.team_id=? AND (c.principal_id=? OR ?=1))) AND (c.id!=? OR c.kind!='user' OR c.team_id IS NOT NULL OR NOT EXISTS (SELECT 1 FROM memberships m WHERE m.principal_id=c.principal_id AND m.role='owner' AND m.active=1) OR EXISTS (SELECT 1 FROM credentials other WHERE other.principal_id=c.principal_id AND other.kind='user' AND other.team_id IS NULL AND other.id!=c.id AND other.revoked_at IS NULL AND (other.expires_at IS NULL OR other.expires_at>?)))",params:[id,auth.principal_id,auth.team_id,auth.principal_id,isAdmin(auth)?1:0,auth.credential_id,now],code:'conflict',status:409,message:'credential changed or would lock out owner'}];await guardedMutation(api,res,auth,guards,[{sql:'UPDATE credentials SET revoked_at=? WHERE id=?',params:[now,id]}],{status:204,body:null,targetId:id});await closeCredentialChannels(api,id);send(res,204,null,requestId);
210
210
  }
211
211
  async function createInvitation(api,req,res,auth,requestId){if(!isAdmin(auth))fail(403,'forbidden','forbidden');await requireUnlinked(api,auth.team_id);const body=await parseJson(req);exact(body,['display_name','role','expires_in_ms']);if(!['admin','member','viewer'].includes(body.role)||!Number.isSafeInteger(body.expires_in_ms)||body.expires_in_ms<1||body.expires_in_ms>604800000)fail(400,'invalid_request','invalid invitation');const pid=api.ids.next('user'),iid=api.ids.next('invitation'),secret=`sci_${iid}.${randomBytes(32).toString('base64url')}`,now=api.clock.nowMs(),exp=now+body.expires_in_ms,response=result(api,auth,{id:iid,role:body.role,expires_at:exp,enrollment_code:secret});await guardedMutation(api,res,auth,authGuards(auth,now),[{sql:'INSERT INTO principals(id,kind,display_name) VALUES (?,?,?)',params:[pid,'user',body.display_name]},{sql:'INSERT INTO invitations(team_id,id,principal_id,secret_hash,role,expires_at) VALUES (?,?,?,?,?,?)',params:[auth.team_id,iid,pid,hashToken(secret),body.role,exp]}],{status:201,body:response,targetId:iid});send(res,201,response,requestId);}
212
212
  async function acceptInvite(api,res,body,requestId){exact(body,['enrollment_code','access_token']);
@@ -18,7 +18,7 @@ import { appAuthentication } from './apps.mjs';
18
18
  import { machineTransition } from './machine-events.mjs';
19
19
  import { randomUUID } from 'node:crypto';
20
20
  import { Channel } from '../channel.mjs';
21
- import { bearer } from './auth.mjs';
21
+ import { APP_LINEAGE, bearer } from './auth.mjs';
22
22
  import { delegatedAccessOf, delegatedPrincipal, delegatedSessionOf, looksDelegated, surfaceCaps } from './delegated.mjs';
23
23
  import { delegatedGrantIssuer, publicationFor } from './publications.mjs';
24
24
 
@@ -85,6 +85,23 @@ async function claimFor(api, auth, machineId) {
85
85
  return { principal: auth.principal_id, principal_name, groups: [...groups, teamSubject(auth.team_id)], grants: held.map((row) => row.id), revisions: Object.fromEntries(held.map((row) => [row.id, row.revision])) };
86
86
  }
87
87
 
88
+ /**
89
+ * Close every channel a revoked credential opened, or one derived from it (an app's or an agent's credential whose
90
+ * lineage holds it): a revoked, leaked token keeps no stream while its member stays.
91
+ */
92
+ export async function closeCredentialChannels(api, credentialId, reason = 'credential_revoked') {
93
+ let closed = 0;
94
+ for (const entry of [...channels(api)]) {
95
+ if (!entry.credentialId) continue;
96
+ const derived = entry.credentialId === credentialId
97
+ || Boolean(await api.store.one(`${APP_LINEAGE} SELECT 1 ok FROM lineage WHERE id=? LIMIT 1`, [entry.credentialId, credentialId]).catch(() => null));
98
+ if (!derived) continue;
99
+ entry.close(reason);
100
+ closed += 1;
101
+ }
102
+ return closed;
103
+ }
104
+
88
105
  /** Close every channel a member leaving the team, or a group losing a member or being deleted, leaves without its claimed authority. */
89
106
  export function closeChannelsFor(api, teamId, { principalId = null, groupId = null, reason = 'access_revoked' } = {}) {
90
107
  let closed = 0;
@@ -488,7 +505,7 @@ async function acceptChannel(api, auth, machineId, duplex, closeSocket) {
488
505
  } catch { closeSocket('refused'); return; }
489
506
  const open = new Set();
490
507
  const entry = {
491
- teamId: auth.team_id, machineId, installationId:auth.installation_id??null, principal: auth.principal_id, actors:[...(auth.act??[])], claim: null, grantIssuer: auth.grant_issuer ?? null,
508
+ teamId: auth.team_id, machineId, installationId:auth.installation_id??null, principal: auth.principal_id, credentialId: auth.credential_id ?? null, actors:[...(auth.act??[])], claim: null, grantIssuer: auth.grant_issuer ?? null,
492
509
  close: (reason) => closeSocket(reason),
493
510
  dropStreams: (reason) => { for (const pair of open) pair.close(reason); },
494
511
  };