ksf-identity-bridge.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // Internal pipe transport for the in-process current-message registration tool.
  2. // Stdin is not authentication. Only the gateway handler validates provenance.
  3. // Same-UID arbitrary code execution is outside this integration's isolation scope.
  4. import fs from 'node:fs';
  5. import path from 'node:path';
  6. import crypto from 'node:crypto';
  7. import {fileURLToPath} from 'node:url';
  8. import {readAgentProfileByKey,registerChannelParticipant} from './ksf-identity.mjs';
  9. const fail=code=>{throw Object.assign(Error(code),{code});};
  10. export function registerBridgeIdentity(envelope,options={}){
  11. if(!envelope||typeof envelope!=='object'||Array.isArray(envelope)||
  12. Object.keys(envelope).sort().join(',')!=='agentProfileKey,identity,version'||
  13. envelope.version!=='ksf.current-employee-registration.v1')fail('INVALID_BRIDGE_REQUEST');
  14. const agentProfile=readAgentProfileByKey(envelope.agentProfileKey,options.profileDir);
  15. if(agentProfile.role!=='workshop')fail('AGENT_ROLE_MISMATCH');
  16. const result=registerChannelParticipant(envelope.identity,{...options,agentProfile});
  17. return{ok:true,version:envelope.version,invocationId:crypto.randomUUID(),
  18. changed:result.changed,profile:result.profile,agentProfileKey:agentProfile.key,
  19. needsNameBinding:result.needsNameBinding,displayNameAuthenticated:false,
  20. accountAuthenticated:false,networkRequests:0,databaseWrites:0};
  21. }
  22. if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
  23. try{
  24. if(process.argv.length!==2)fail('BRIDGE_NO_ARGUMENTS_REQUIRED');
  25. const buffer=Buffer.alloc(16385);let length=0;
  26. while(length<buffer.length){const n=fs.readSync(0,buffer,length,buffer.length-length,null);if(!n)break;length+=n;}
  27. if(length>16384)fail('BRIDGE_REQUEST_TOO_LARGE');
  28. console.log(JSON.stringify(registerBridgeIdentity(JSON.parse(buffer.subarray(0,length).toString('utf8')))));
  29. }catch(e){
  30. const code=/^[A-Z][A-Z0-9_]+$/.test(e.code||'')?e.code:'IDENTITY_REGISTRATION_FAILED';
  31. console.error(JSON.stringify({ok:false,error:code}));process.exitCode=1;
  32. }
  33. }