@north-light/cli 0.3.655 → 0.3.657
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/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/docs.d.ts +6 -3
- package/dist/clients/attach/session/document-links.d.ts +3 -2
- package/dist/clients/attach/session/document-links.js +1 -1
- package/dist/clients/attach/viewer.js +3 -3
- package/dist/core/graph/events.d.ts +1 -1
- package/dist/core/graph/events.js +8 -8
- package/dist/daemon/api/canvas-host.d.ts +9 -0
- package/dist/daemon/api/canvas-host.js +1 -0
- package/dist/daemon/api/document-listener.js +1 -11
- package/dist/daemon/api/document-page.d.ts +18 -0
- package/dist/daemon/api/document-page.js +11 -0
- package/dist/daemon/api/handlers/document-access.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/broker-signals/bus.d.ts +3 -2
- package/dist/daemon/broker-signals/bus.js +1 -1
- package/dist/doc-editor/editor.js +24 -24
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare function subscribeDocumentEvents(id: string, callback: (
|
|
1
|
+
export declare function subscribeDocumentEvents(id: string, callback: () => void): Promise<() => void>;
|
|
2
2
|
import { type ReposFn } from './reader.js';
|
|
3
3
|
import { type Subscription } from './watches.js';
|
|
4
4
|
import { CrtrError } from '../errors.js';
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var
|
|
2
|
-
AND name = ? AND id != ? LIMIT 1`).get(e.name,e.id)?`${e.type}:${e.name}`:e.name}
|
|
3
|
-
`)[0]:`${e.event} ${e.object.type} ${e.object.name}`),...l?.bodyRef===void 0?{}:{bodyRef:l.bodyRef},...l?.disposition===void 0?{}:{disposition:l.disposition},senderNodeId:e.actor?.type==="node"?e.actor.id:null,senderName:e.actor===null||e.actor===void 0?null:e.actor.home_machine?`${e.actor.name} on ${T(e.actor.home_machine)}`:e.actor.name,bodyJson:f}}
|
|
1
|
+
var x=Object.defineProperty;var c=(t,e)=>x(t,"name",{value:e,configurable:!0});import{brokerSignalBus as M}from"../../daemon/broker-signals/bus.js";const _=new Map;let k;async function le(t,e){k??=M.subscribe(n=>{for(const s of _.get(n)??[])s()},{kinds:["document"],onListenStart:c(()=>{for(const n of[..._.values()])for(const s of n)s()},"onListenStart")}),await k;const o=_.get(t)??new Set;_.set(t,o);const i=c(()=>e(),"listener");return o.add(i),()=>{o.delete(i),o.size===0&&_.get(t)===o&&_.delete(t)}}c(le,"subscribeDocumentEvents");import{evalCondition as $}from"../predicate.js";import{finalizeNodeMail as B,insertMessage as J}from"../feed/messages.js";import{check as I,resolveReader as U}from"../permissions/evaluator.js";import{getById as K}from"./objects.js";import{appScopesNow as G,publishLookups as q,readerForObject as z}from"./reader.js";import{configFromJson as C}from"./watches.js";import{CrtrError as L}from"../errors.js";import{ExitCode as v}from"../../types.js";import{eventSpec as V,kindOf as F}from"./kinds/registry.js";import{machineNameOf as T}from"../peer/names.js";import{settleObjectWaits as Y}from"../canvas/waits.js";import{RECEIVERS as D}from"./receivers.js";import{DEFAULT_LISTEN as W}from"./types.js";import{afterCommit as P}from"../canvas/db.js";function X(t,e){if(t.level===void 0||t.level===e.level||e.levels?.includes(t.level))return t.level??e.level;const o=[e.level,...e.levels??[]].filter((i,n,s)=>s.indexOf(i)===n).sort((i,n)=>i-n);throw new L("invalid_level",`${t.object.type} ${t.event} publishes at level ${o.join(", ")}, not ${t.level}`,v.USAGE,{kind:t.object.type,event:t.event,level:t.level,allowed:o})}c(X,"resolveLevel");function Q(t,e){const o=t.split("."),i=e.split(".");for(let n=0;n<o.length;n++){if(o[n]===">")return n===o.length-1&&i.length>n;if(n>=i.length||o[n]!=="*"&&o[n]!==i[n])return!1}return o.length===i.length}c(Q,"matchSubject");const H={"next-turn":1,"after-turn":2,steer:3,interrupt:4};function Z(t,e){let o=null;for(const i of t){let n=null;for(const s of i)s.threshold<=e&&(!n||s.threshold>n.threshold)&&(n=s);n&&(!o||H[n.delivery]>H[o])&&(o=n.delivery)}return o}c(Z,"resolveDelivery");async function Oe(t,e,o){if(e.config)return e.config;const i=await t.prepare("SELECT listen_json FROM objects WHERE id = ?").get(o.id);return i?.listen_json?C(i.listen_json):W}c(Oe,"listenConfigFor");function ee(t,e){return e.inboxKind??(t.level>=7?"urgent":"update")}c(ee,"inboxKind");async function te(t,e){return e.type==="node"?e.id:await t.prepare(`SELECT 1 FROM objects WHERE type IN ('person','app','repo','profile')
|
|
2
|
+
AND name = ? AND id != ? LIMIT 1`).get(e.name,e.id)?`${e.type}:${e.name}`:e.name}c(te,"ownerHandleOf");async function ne(t,e,o){const i=e.object.owner===null?null:await t.prepare("SELECT * FROM objects WHERE id = ?").get(e.object.owner),n=i?.id??null,s=i?await te(t,i):null,f=e.object.type==="node"?await t.prepare("SELECT i.external_id FROM nodes n JOIN identities i ON i.object = n.app AND i.scheme = 'app' WHERE n.node_id = ?").get(e.object.id):void 0;return{event:e.event,level:e.level,object:{id:e.object.id,type:e.object.type,kind:e.object.kind,owner:n,owner_handle:s,...f?{app:f.external_id}:{},name:e.object.name,...e.object.home_machine?{machine:T(e.object.home_machine),machine_id:e.object.home_machine}:{}},actor:e.actor?.id??null,...e.actor?.home_machine?{actor_machine:T(e.actor.home_machine),actor_machine_id:e.actor.home_machine}:{},attrs:o,...e.pointer===void 0?{}:{pointer:e.pointer}}}c(ne,"pushFields");async function oe(t,e,o,i){const n=await ne(t,e,i),s=e.messageBody!==void 0&&o.carriesBody===!0,f=s?typeof e.messageBody=="object"&&e.messageBody!==null&&!Array.isArray(e.messageBody)?{...e.messageBody,push:n}:{body:e.messageBody,push:n}:{push:n},d=s?e.messageBody:null,l=d?.bodyRef===void 0?null:d;return{kind:ee(e,o),label:l?.label??(typeof d?.label=="string"?d.label:e.object.type.includes(".")&&typeof e.messageBody?.summary=="string"?e.messageBody.summary.split(`
|
|
3
|
+
`)[0]:`${e.event} ${e.object.type} ${e.object.name}`),...l?.bodyRef===void 0?{}:{bodyRef:l.bodyRef},...l?.disposition===void 0?{}:{disposition:l.disposition},senderNodeId:e.actor?.type==="node"?e.actor.id:null,senderName:e.actor===null||e.actor===void 0?null:e.actor.home_machine?`${e.actor.name} on ${T(e.actor.home_machine)}`:e.actor.name,bodyJson:f}}c(oe,"messageInput");async function ie(t,e,o,i,n){if(!o.supersedes)return[{attrs:e.attrs,destinations:[...i]}];const s=t.prepare(`SELECT d.delivery_id, d.message_id, d.state, m.body_json FROM deliveries d
|
|
4
4
|
JOIN messages m ON m.message_id = d.message_id
|
|
5
5
|
WHERE d.destination_id = ? AND d.state IN ('pending', 'handed_off')
|
|
6
6
|
AND d.canceled_at IS NULL AND m.event = ? AND m.object_id = ?
|
|
7
|
-
ORDER BY m.seq`),f=t.prepare("DELETE FROM deliveries WHERE delivery_id = ?"),
|
|
7
|
+
ORDER BY m.seq`),f=t.prepare("DELETE FROM deliveries WHERE delivery_id = ?"),d=t.prepare("SELECT * FROM objects WHERE id = ?"),l=new Map,j=new Set;for(const m of i){const R=n(m),N=await d.get(R),O=N===void 0?void 0:await F(t,N.type),y=await s.all(R,e.event,e.object.id),b=new Set;for(const u of y)u.state==="handed_off"?await O?.supersedeClaimed?.(t,u.delivery_id)&&b.add(u.delivery_id):(await f.run(u.delivery_id),j.add(u.message_id));const r=y.filter(u=>u.state==="pending"||b.has(u.delivery_id)).at(-1),a=r?.message_id??null,p=l.get(a)??{prior:r?.body_json?JSON.parse(r.body_json).push?.attrs??null:null,destinations:[]};p.destinations.push(m),l.set(a,p)}const S=t.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)");for(const m of j)await S.run(m,m);return[...l.values()].map(m=>({attrs:o.merge?o.merge(m.prior,e):e.attrs,destinations:m.destinations}))}c(ie,"supersede");async function se(t,e,o,i,n){const s=await K(t,i);if(s===null||s.type!=="app")return!1;const f=await t.prepare("SELECT 1 FROM peer_stubs WHERE object = ?").get(e.id)!==void 0,d=f?null:await G(t,s,n);if(!f&&d===null||e.owner===null)return!1;const l=await U(t,{class:"app",app:s,scopes:d??[]});return(e.owner===s.id||await I(t,l,"edit",e.owner))&&(d===null||await I(t,l,"read",o.id,{verb:"link"}))}c(se,"linkDelivers");async function re(t,e){return((await t.prepare(`WITH RECURSIVE chain(id, depth) AS (
|
|
8
8
|
SELECT owner, 1 FROM objects WHERE id = ? AND owner IS NOT NULL
|
|
9
9
|
UNION ALL
|
|
10
10
|
SELECT o.owner, c.depth + 1 FROM objects o JOIN chain c ON o.id = c.id WHERE o.owner IS NOT NULL
|
|
11
|
-
) SELECT o.type FROM chain c JOIN objects o ON o.id = c.id ORDER BY c.depth DESC LIMIT 1`).get(e.id))?.type??e.type)==="repo"}
|
|
12
|
-
UNION ALL SELECT depth FROM message_causes WHERE message_id = ? LIMIT 1`).get(
|
|
13
|
-
COALESCE(s.config_json, o.listen_json) AS config_json, w.link_app`,
|
|
11
|
+
) SELECT o.type FROM chain c JOIN objects o ON o.id = c.id ORDER BY c.depth DESC LIMIT 1`).get(e.id))?.type??e.type)==="repo"}c(re,"inRepoSpace");const A=8;class ae extends L{static{c(this,"HopLimitError")}constructor(e){super("hop_limit",`event depth ${e} exceeds ${A}`,v.GENERAL,{depth:e,limit:A})}}async function Se(t,e,o=async()=>[]){const i=await V(t,e.object.type,e.event),n={...e,level:X(e,i)};n.object.type==="document"&&(n.event==="edited"||n.event==="deleted")&&(await t.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`document:${n.object.id}`),P(()=>M.markSignal("document",n.object.id)));const s=e.cause??null,f=s===null?null:await t.prepare(`SELECT depth FROM messages WHERE message_id = ?
|
|
12
|
+
UNION ALL SELECT depth FROM message_causes WHERE message_id = ? LIMIT 1`).get(s,s);if(s!==null&&f===void 0)throw new L("unknown_cause",`no message ${s}`,v.USAGE,{cause:s});const d=f===null?0:f.depth+1;if(d>A)throw new ae(d);(i.endsWait===!0||n.event==="deleted")&&await Y(t,n.object.id);const l=`w.watcher, o.id AS watcher_id, o.type AS watcher_type, o.reception, s.pattern, s.filter_json,
|
|
13
|
+
COALESCE(s.config_json, o.listen_json) AS config_json, w.link_app`,j=await t.prepareUncached(i.durable?`SELECT ${l} FROM watches w JOIN watch_subscriptions s ON s.watch = w.watch_id
|
|
14
14
|
JOIN objects o ON o.id = w.watcher WHERE w.object = ? AND w.watcher != ? AND o.reception >= 1`:`SELECT ${l} FROM objects o JOIN watches w ON w.watcher = o.id JOIN watch_subscriptions s ON s.watch = w.watch_id
|
|
15
|
-
WHERE o.reception = 2 AND w.object = ? AND w.watcher != ?`).all(n.object.id,n.actor?.id??"");if(
|
|
15
|
+
WHERE o.reception = 2 AND w.object = ? AND w.watcher != ?`).all(n.object.id,n.actor?.id??"");if(j.length===0)return{delivered:0,message_id:null,depth:d};const S={event:n.event,level:n.level,id:n.object.id,type:n.object.type,kind:n.object.kind,actor:n.actor?.id??null,...n.attrs},m=new Map;for(const r of j){if(n.onlyWatchers!==void 0&&!n.onlyWatchers.includes(r.watcher_id)||!Q(r.pattern,n.event)||r.filter_json!==null&&!$(JSON.parse(r.filter_json),S))continue;const a=m.get(r.watcher)??{id:r.watcher_id,type:r.watcher_type,reception:r.reception,configs:[],configured:!1,linkApp:r.link_app};a.configs.push(r.config_json?C(r.config_json):W),a.configured||=r.config_json!==null,m.set(r.watcher,a)}const R=await re(t,n.object),N=c(async()=>[],"noRepos"),O=q(t),y=[];for(const r of m.values()){const a=await t.prepare("SELECT * FROM objects WHERE id = ?").get(r.id),p=await F(t,a.type),u=p.receiverFor?await p.receiverFor(t,a):p.receiver;if(u===void 0)continue;const h=u==="peer"&&!r.configured?"next-turn":Z(r.configs,n.level);if(h===null)continue;const E=await z(t,a,R?o:N,O);if(E.scopes===null&&(E.class==="node"||E.owner.type!=="person"))continue;const w=await I(t,E,"read",n.object.id),g=r.linkApp!==null&&!w&&await se(t,n.object,a,r.linkApp,O);!g&&!w||y.push({id:r.id,reception:r.reception,delivery:h,receiver:u,...g?{linked:g}:{}})}if(y.length===0)return{delivered:0,message_id:null,depth:d};let b=null;for(const r of await ie(t,n,i,y,a=>a.id)){const a=new Map;for(const w of r.destinations)a.set(w.receiver,[...a.get(w.receiver)??[],w]);const p=await oe(t,n,i,r.attrs),u=[...a].map(([w,g])=>D[w].bodyOwner(g)).find(w=>w!==null)??null,h=B({...p,urgency:"normal"},u),E=await J(t,{operationId:h.operationId,createdAt:h.createdAt,senderNodeId:p.senderNodeId,senderName:p.senderName,kind:p.kind,label:p.label,bodyRef:h.bodyRef,bodyJson:h.bodyJson,disposition:p.disposition??null,event:{event:n.event,objectId:n.object.id,level:n.level,actorId:n.actor?.id??null},causeMessageId:s,depth:d});b??=E;for(const[w,g]of a)await D[w].enqueue(t,{messageId:E,event:n.event,level:n.level,senderNodeId:p.senderNodeId,elevatesTier:i.elevatesTier===!0,...n.idempotencyKey===void 0?{}:{idempotencyKey:n.idempotencyKey}},g)}return{delivered:y.length,message_id:b,depth:d}}c(Se,"publish");export{A as HOP_LIMIT,ae as HopLimitError,Oe as listenConfigFor,Q as matchSubject,Se as publish,Z as resolveDelivery,X as resolveLevel,le as subscribeDocumentEvents,ie as supersede};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
export declare const CANVAS_CALLBACK_PATH = "/auth/callback";
|
|
3
|
+
/** The configured canvas origin, from `CRTR_CANVAS_URL` alone, on a cloud role; undefined otherwise. Never reads the key, so a
|
|
4
|
+
* half-configured canvas cannot fail requests for any other host. */
|
|
5
|
+
export declare function canvasOrigin(): string | undefined;
|
|
6
|
+
/** Whether `req` is for the canvas host: a cloud role whose `CRTR_CANVAS_URL` host equals the request's Host. */
|
|
7
|
+
export declare function isCanvasRequest(req: IncomingMessage): boolean;
|
|
8
|
+
/** Serve one request on the canvas host. The caller checked `isCanvasRequest`. */
|
|
9
|
+
export declare function serveCanvas(req: IncomingMessage, res: ServerResponse): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var U=Object.defineProperty;var a=(e,n)=>U(e,"name",{value:n,configurable:!0});import{createHash as v,createHmac as C,createPrivateKey as x,hkdfSync as j,randomBytes as _,randomUUID as J,sign as D,timingSafeEqual as H}from"node:crypto";import{readFileSync as V}from"node:fs";import{JwksCache as W,verifyIdToken as B}from"@north-light/identity";import{isCloudRole as M,runAsPerson as z}from"../../core/canvas/person.js";import{directoryIssuer as F}from"../../core/directory/issuer.js";import{emitEvent as R}from"../../core/events/emit.js";import{ApiError as K}from"../../api/errors.js";import{boundDaemonControl as G}from"../control.js";import{loadPersonSettings as Y}from"../../core/scoped-state/person-rows.js";import{personHasSnapshot as Z}from"../../core/scoped-state/person-store.js";import{escapeHtml as T}from"./vendor-signin.js";import{cookieValue as A,documentNotFound as Q,documentShell as X,error as m,messagePage as p,resolveDocument as q,serveDocumentApi as ee,setPageHeaders as ne}from"./document-page.js";const w="/auth/callback",E=12*36e5,L=10*6e4,te=1e4;let g,$,y;function oe(){if(g!==void 0)return g;const e=process.env.CRTR_CANVAS_URL;if(!e)return g=null;const n=new URL(e),t=process.env.CRTR_CANVAS_CLIENT_ID,o=process.env.CRTR_CANVAS_JWK_FILE,r=F();if(!t||!o||r===null)throw new Error("CRTR_CANVAS_URL needs CRTR_CANVAS_CLIENT_ID, CRTR_CANVAS_JWK_FILE and CRTR_DIRECTORY_URL");const i=JSON.parse(V(o,"utf8"));if(i.kty!=="EC"||i.crv!=="P-256"||!i.d)throw new Error("CRTR_CANVAS_JWK_FILE must hold a private P-256 JWK");const s=Buffer.from(j("sha256",i.d,"crtr-canvas","canvas-session-cookies",32));return g={origin:n.origin,host:n.host,secure:n.protocol==="https:",clientId:t,jwk:i,issuer:r,key:s}}a(oe,"canvasConfig");function re(){const e=process.env.CRTR_CANVAS_URL;if(!(!M()||!e))try{return new URL(e).origin}catch{return}}a(re,"canvasOrigin");function ve(e){const n=re();return n!==void 0&&e.headers.host===new URL(n).host}a(ve,"isCanvasRequest");const f=a(e=>e.toString("base64url"),"b64");function I(e,n,t,o){const r=f(Buffer.from(JSON.stringify({...t,purpose:n,exp:Date.now()+o})));return`${r}.${f(C("sha256",e.key).update(r).digest())}`}a(I,"seal");function N(e,n,t){if(!t)return null;const[o,r,i]=t.split(".");if(!o||!r||i!==void 0)return null;const s=a(c=>v("sha256").update(c).digest(),"digest");if(!H(s(r),s(f(C("sha256",e.key).update(o).digest()))))return null;try{const c=JSON.parse(Buffer.from(o,"base64url").toString("utf8"));return c.purpose===n&&typeof c.exp=="number"&&c.exp>Date.now()?c:null}catch{return null}}a(N,"open");const S=a((e,n)=>e.secure?`__Host-${n}`:n,"cookieName");function k(e,n,t,o){return`${S(e,n)}=${t}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(o/1e3)}${e.secure?"; Secure":""}`}a(k,"cookie");async function O(e,n){const t=await fetch(e,{...n,signal:AbortSignal.timeout(te)}),o=await t.json().catch(()=>({}));if(!t.ok)throw new Error(`directory ${new URL(e).pathname} answered ${t.status}: ${String(o.error_description??o.error??"")}`);return o}a(O,"directoryJson");function P(e){return y??=O(`${e.issuer}/.well-known/openid-configuration`).then(n=>{if(typeof n.authorization_endpoint!="string"||typeof n.token_endpoint!="string")throw new Error("directory discovery has no authorization or token endpoint");return n},n=>{throw y=void 0,n}),y}a(P,"discover");function ie(e,n){const t=Math.floor(Date.now()/1e3),o=f(Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",...e.jwk.kid?{kid:e.jwk.kid}:{}}))),r=f(Buffer.from(JSON.stringify({iss:e.clientId,sub:e.clientId,aud:n,iat:t,exp:t+60,jti:J()}))),i=D("sha256",Buffer.from(`${o}.${r}`),{key:x({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${o}.${r}.${f(i)}`}a(ie,"clientAssertion");async function b(e,n,t){return await O(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({...t,client_id:e.clientId,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:ie(e,n)})})}a(b,"directoryPost");async function ae(e,n,t){const o=await P(e),r={state:f(_(16)),verifier:f(_(32)),nonce:f(_(32)),next:t},i=new URL(o.authorization_endpoint);i.search=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:`${e.origin}${w}`,scope:"openid",state:r.state,nonce:r.nonce,code_challenge:f(v("sha256").update(r.verifier).digest()),code_challenge_method:"S256"}).toString(),n.writeHead(303,{Location:i.href,"Set-Cookie":k(e,`crtr_canvas_login_${r.state}`,I(e,"login",r,L),L),"Cache-Control":"no-store"}),n.end()}a(ae,"startSignIn");async function se(e,n,t,o){const r=o.searchParams.get("state"),i=r!==null&&/^[A-Za-z0-9_-]{22}$/.test(r)?`crtr_canvas_login_${r}`:void 0,s=i===void 0?null:N(e,"login",A(n.headers.cookie,S(e,i))),c=o.searchParams.get("code");if(o.searchParams.get("error")!==null)return p(t,400,"Sign-in did not finish",`Northlight answered <code>${T(o.searchParams.get("error").slice(0,100))}</code>. Open the document link again to retry.`);if(s===null||c===null||r!==s.state)return p(t,400,"Sign-in did not finish","This sign-in started in another browser or expired. Open the document link again.");const d=await P(e),u=await b(e,d.token_endpoint,{grant_type:"authorization_code",code:c,redirect_uri:`${e.origin}${w}`,code_verifier:s.verifier});if(typeof u.refresh_token=="string"&&d.revocation_endpoint!==void 0&&await b(e,d.revocation_endpoint,{token:u.refresh_token,token_type_hint:"refresh_token"}).catch(h=>R({level:"warn",event:"api.canvas.revoke_failed",error:h instanceof Error?h:new Error(String(h))})),typeof u.id_token!="string")throw new Error("the directory token response has no id_token");$??=new W(e.issuer);const l=await B({token:u.id_token,jwks:$,issuer:e.issuer,audience:e.clientId});if(l.nonce!==s.nonce)return p(t,400,"Sign-in did not finish","The sign-in answer does not match this browser. Open the document link again.");t.writeHead(303,{Location:s.next,"Set-Cookie":[k(e,"crtr_canvas_session",I(e,"session",{sub:l.sub},E),E),k(e,i,"",0)],"Cache-Control":"no-store"}),t.end()}a(se,"finishSignIn");async function Ce(e,n){try{await ce(e,n)}catch(t){R({level:"error",event:"api.canvas.failed",error:t instanceof Error?t:new Error(String(t)),fields:{method:e.method,path:e.url?.split("?")[0]}}),n.headersSent?n.destroy():p(n,500,"Something went wrong","The document could not be opened. Try again in a moment.")}}a(Ce,"serveCanvas");async function ce(e,n){const t=oe();if(t===null)throw new Error("CRTR_CANVAS_URL is unset");if(ne(n),G()?.startupBlock()!=null)return p(n,503,"Starting up","The canvas is starting. Try again in a moment.");const o=new URL(e.url??"/",t.origin);if(e.method==="POST"){if(e.headers.origin!==t.origin)return m(n,403,"forbidden","invalid Origin");if(e.headers["content-type"]!=="application/json")return m(n,415,"unsupported_media_type","Content-Type must be application/json")}if(e.method==="GET"&&o.pathname===w)return await se(t,e,n,o);const r=e.method==="GET"&&(o.pathname.startsWith("/r/")||o.pathname.startsWith("/document/")),i=o.pathname.startsWith("/assets/")?null:N(t,"session",A(e.headers.cookie,S(t,"crtr_canvas_session")));if(i===null&&!o.pathname.startsWith("/assets/"))return r?await ae(t,n,`${o.pathname}${o.search}`):m(n,401,"unauthorized","your sign-in expired: reload the page to sign in again");const s=i?.sub,c=a(d=>s===void 0?d():z(s,async()=>(Z()||await Y(s),await d())),"asPerson");await c(async()=>{if(r){const d=o.pathname.startsWith("/r/")?"/r/":"/document/";let u;try{u=decodeURIComponent(o.pathname.slice(d.length))}catch{return m(n,400,"invalid_request","the address is not valid percent-encoding")}let l;try{l=u===""?null:await q(u)}catch(h){if(h instanceof K&&h.code==="ambiguous_name")return p(n,409,"More than one document has this name",T(h.message));throw h}if(l===null||d==="/document/"&&l.id!==u)return Q(n,u);if(d==="/r/"){n.writeHead(303,{Location:`/document/${encodeURIComponent(l.id)}`,"Cache-Control":"no-store"}),n.end();return}return X(n,l.id,l)}if(!await ee(e,n,o,c))return e.method==="GET"&&o.pathname==="/"?p(n,404,"Northlight canvas","Open a document from its link in the viewer."):m(n,404,"not_found","route not found")})}a(ce,"canvasRequest");export{w as CANVAS_CALLBACK_PATH,re as canvasOrigin,ve as isCanvasRequest,Ce as serveCanvas};
|
|
@@ -1,11 +1 @@
|
|
|
1
|
-
var
|
|
2
|
-
|
|
3
|
-
`);const s=h(async _=>{if(_==="deleted"){e.write(`event: deleted
|
|
4
|
-
data: {}
|
|
5
|
-
|
|
6
|
-
`),e.end();return}const f=await p(o),g=f&&await D(f);g&&e.write(`event: edited
|
|
7
|
-
data: ${JSON.stringify({revision:g.revision,heads_key:g.heads_key})}
|
|
8
|
-
|
|
9
|
-
`)},"notify"),d=await M(o,_=>{s(_).catch(f=>{V({level:"error",event:"daemon.document_events.notify_failed",error:f}),e.end()})}),w=setInterval(()=>e.write(`: keepalive
|
|
10
|
-
|
|
11
|
-
`),3e4);e.on("close",()=>{clearInterval(w),d()});return}if(i.method==="GET"&&c.pathname.startsWith(`/assets/${y}/`)){const o=c.pathname.slice(`/assets/${y}/`.length);if(!/^[a-zA-Z0-9_.-]+$/.test(o))return m(e,404,"not_found","asset not found");const s=o==="mermaid.js"?E(j,"clients/attach/assets/mermaid.min.js"):E(j,"doc-editor",o);try{const d=B(s);return e.writeHead(200,{"Content-Type":z(o)===".css"?"text/css; charset=utf-8":"text/javascript; charset=utf-8","Cache-Control":"public, max-age=31536000, immutable"}),e.end(d)}catch(d){if(d.code==="ENOENT")return m(e,404,"not_found","asset not found");throw d}}return m(e,404,"not_found","route not found")})().catch(u=>{e.headersSent?e.destroy():m(e,500,"server_failure",u instanceof Error?u.message:String(u))})});return{ready:new Promise((i,e)=>{r.once("error",u=>{v=`the document listener could not bind 127.0.0.1:${n}: ${u.message}`,e(u)}),r.listen(n,"127.0.0.1",()=>{r.removeAllListeners("error"),v=void 0,i()})}),close:h(()=>new Promise(i=>{v="the document listener is closed",r.closeAllConnections(),r.close(()=>i())}),"close")}}h(Ee,"createDocumentListener");export{Ee as createDocumentListener,Te as documentListenerUnavailable};
|
|
1
|
+
var f=Object.defineProperty;var c=(n,r)=>f(n,"name",{value:r,configurable:!0});import{createHash as p,timingSafeEqual as v}from"node:crypto";import{createServer as g}from"node:http";import{cookieValue as S,documentNotFound as $,documentShell as y,error as d,messagePage as w,resolveDocument as P,serveDocumentApi as k,setPageHeaders as _}from"./document-page.js";function m(n,r){const l=c(s=>p("sha256").update(s).digest(),"digest");return v(l(n),l(r))}c(m,"sameSecret");const b=c(n=>n(),"inProcess");let h="the document listener has not started";function T(){return h}c(T,"documentListenerUnavailable");function W(n,r){const l=`crtr_doc_${n}`,s=g((t,e)=>{(async()=>{_(e);const a=[`127.0.0.1:${n}`,`localhost:${n}`];if(typeof t.headers.host!="string"||!a.includes(t.headers.host))return d(e,403,"forbidden","invalid Host");if(t.method==="POST"){if(!a.some(i=>t.headers.origin===`http://${i}`))return d(e,403,"forbidden","invalid Origin");if(t.headers["content-type"]!=="application/json")return d(e,415,"unsupported_media_type","Content-Type must be application/json")}const o=new URL(t.url??"/",`http://127.0.0.1:${n}`);if(!o.pathname.startsWith("/assets/")){const i=t.method==="GET"&&o.pathname.startsWith("/r/")?o.searchParams.get("t"):null;if(i!==null&&m(i,r))return o.searchParams.delete("t"),e.writeHead(303,{Location:`${o.pathname}${o.search}`,"Set-Cookie":`${l}=${r}; HttpOnly; SameSite=Strict; Path=/`,"Cache-Control":"no-store"}),e.end();const u=S(t.headers.cookie,l);if(i!==null||u===void 0||!m(u,r))return o.pathname.startsWith("/r/")?w(e,401,"Not authorized","Open this document from its link in the attach viewer."):d(e,401,"unauthorized","open the document link from the attach viewer")}if(t.method==="GET"&&o.pathname.startsWith("/r/")){let i;try{i=decodeURIComponent(o.pathname.slice(3))}catch{return d(e,400,"invalid_request","ref is not valid percent-encoding")}const u=await P(i);return u?y(e,i,u):$(e,i)}if(!await k(t,e,o,b))return d(e,404,"not_found","route not found")})().catch(a=>{e.headersSent?e.destroy():d(e,500,"server_failure",a instanceof Error?a.message:String(a))})});return{ready:new Promise((t,e)=>{s.once("error",a=>{h=`the document listener could not bind 127.0.0.1:${n}: ${a.message}`,e(a)}),s.listen(n,"127.0.0.1",()=>{s.removeAllListeners("error"),h=void 0,t()})}),close:c(()=>new Promise(t=>{h="the document listener is closed",s.closeAllConnections(),s.close(()=>t())}),"close")}}c(W,"createDocumentListener");export{W as createDocumentListener,T as documentListenerUnavailable};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import type { ObjectRow } from '../../core/graph/types.js';
|
|
3
|
+
/** Runs a callback as the request's person. The canvas host wraps it in `runAsPerson`; a live-update notification fires outside the
|
|
4
|
+
* request's async context, so it re-enters the person through this. */
|
|
5
|
+
export type AsPerson = <T>(fn: () => Promise<T>) => Promise<T>;
|
|
6
|
+
export declare function setPageHeaders(res: ServerResponse): void;
|
|
7
|
+
export declare function error(res: ServerResponse, status: number, code: string, message: string): void;
|
|
8
|
+
export declare function cookieValue(header: string | undefined, name: string): string | undefined;
|
|
9
|
+
/** A small HTML page with a heading and one paragraph of already-escaped HTML. */
|
|
10
|
+
export declare function messagePage(res: ServerResponse, status: number, title: string, html: string): void;
|
|
11
|
+
export declare function documentNotFound(res: ServerResponse, ref: string): void;
|
|
12
|
+
/** The editor's HTML shell; the editor reads `ref` from `#app[data-ref]` and calls the `/api/*` routes with it. */
|
|
13
|
+
export declare function documentShell(res: ServerResponse, ref: string, doc: ObjectRow): void;
|
|
14
|
+
/** The live document `ref` names that the request's person can read, or null. */
|
|
15
|
+
export declare function resolveDocument(ref: string): Promise<ObjectRow | null>;
|
|
16
|
+
/** Serve `/api/doc`, `/api/save`, `/api/events` and `/assets/<version>/…`. Answers false for any other route. The caller has already
|
|
17
|
+
* checked its gate, and for a POST the Origin and Content-Type. */
|
|
18
|
+
export declare function serveDocumentApi(req: IncomingMessage, res: ServerResponse, url: URL, asPerson: AsPerson): Promise<boolean>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
var j=Object.defineProperty;var s=(n,e)=>j(n,"name",{value:e,configurable:!0});import{readFileSync as D}from"node:fs";import{join as x,extname as O}from"node:path";import{fileURLToPath as P}from"node:url";import{withCanvasWrite as p}from"../../core/canvas/db.js";import{ApiError as R}from"../../api/errors.js";import{get as v}from"../../core/graph/bodies.js";import{canChange as E,isShipped as A}from"../../core/graph/access.js";import{documentRecord as T,editDocument as B,heads as $,withCurrentNames as _}from"../../core/graph/documents.js";import{getById as g}from"../../core/graph/objects.js";import{subscribeDocumentEvents as F}from"../../core/graph/events.js";import{emitEvent as I}from"../../core/events/emit.js";import{checkoutsForCwd as J}from"../../core/graph/repo-sync/repos.js";import{canonicalName as L,repoChange as U,syncChanged as W}from"./handlers/docs.js";import{escapeHtml as h}from"./vendor-signin.js";import{readerFor as b,resolveRef as G,warmDocumentWatchers as z}from"./reader.js";import{mergeDocumentLines as M}from"./document-merge.js";import{crtrVersion as V}from"../../shared/crtr-version.js";const X="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",C={class:"person"},w=encodeURIComponent(V()),S=P(new URL("../../../dist/",import.meta.url));function we(n){n.setHeader("Content-Security-Policy",X),n.setHeader("X-Content-Type-Options","nosniff")}s(we,"setPageHeaders");function u(n,e,t,o){n.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),n.end(JSON.stringify({error:{code:t,message:o}}))}s(u,"error");function ve(n,e){for(const t of(n??"").split(";")){const o=t.indexOf("=");if(o!==-1&&t.slice(0,o).trim()===e)return t.slice(o+1).trim()}}s(ve,"cookieValue");function H(n,e,t){n.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),n.end(JSON.stringify(t))}s(H,"json");function Z(n,e,t,o){n.writeHead(e,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),n.end(`<!doctype html><html><head><meta charset="utf-8"><title>${h(t)}</title><link rel="icon" href="data:,"></head><body style="font-family:system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem"><h1>${h(t)}</h1><p>${o}</p></body></html>`)}s(Z,"messagePage");function _e(n,e){Z(n,404,"Document not found",`No document you can read is named <code>${h(e)}</code>.`)}s(_e,"documentNotFound");function ge(n,e,t){n.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),n.end(`<!doctype html><html><head><meta charset="utf-8"><title>${h(t.name)}</title><link rel="icon" href="data:,"><link rel="stylesheet" href="/assets/${w}/editor.css"></head><body><div id="app" data-ref="${h(e)}"></div><script type="module" src="/assets/${w}/editor.js"><\/script></body></html>`)}s(ge,"documentShell");async function N(n){return await p(async e=>{const t=await g(e,n.id);if(!t||t.deleted_at||t.type!=="document")return null;const o=await b(e,{principal:C}),a=await T(e,t),r=await $(e,t),i=await L(e,t),c=r.length===1&&await E(e,o,t);return{id:t.id,name:i,revision:a.revision,heads_key:a.heads_key,body:r.length===1?await _(e,t,await v(e,r[0].body_hash)):"",editable:c,...c?{}:{readonly_reason:r.length!==1?`has ${r.length} heads and needs a merge`:await A(e,t)?"shipped by a plugin":"you cannot change this document"}}})}s(N,"snapshot");async function k(n){return await p(async e=>{const t=await b(e,{principal:C});try{const o=await G(e,t,n);return"deleted"in o||"remote"in o||o.type!=="document"?null:o}catch(o){if(o instanceof R&&o.code==="not_found")return null;throw o}})}s(k,"resolveDocument");async function q(n){return await p(async e=>{const t=await g(e,n);return!t||t.type!=="document"||t.deleted_at!==null})}s(q,"isDeleted");async function K(n){const e=[];let t=0;for await(const o of n){if(t+=o.length,t>2e6)throw new Error("request body exceeds 2 MB");e.push(o)}return JSON.parse(Buffer.concat(e).toString("utf8"))}s(K,"requestBody");async function Q(n){await z(n.id);const e=await p(async t=>{const o=await b(t,{principal:C}),a=await g(t,n.id);if(!a||a.type!=="document"||a.deleted_at)return{status:404,value:{error:{code:"not_found",message:"document not found"}}};const r=await T(t,a),i=await $(t,a);if(i.length!==1||!await E(t,o,a))return{status:403,value:{error:{code:"forbidden",message:"document is read-only"}}};const c=await _(t,a,await v(t,i[0].body_hash)),f=await t.prepareUncached("SELECT body_hash FROM revisions WHERE document = ? AND rev_id = ?").get(a.id,n.base_heads_key);if(!f||await _(t,a,await v(t,f.body_hash))!==n.base_body)return{status:409,value:{saved:!1,conflict:{revision:r.revision,heads_key:r.heads_key,current_body:c,your_body:n.body}}};const y=n.base_heads_key!==r.heads_key,l=y?M(n.base_body,n.body,c):n.body;if(l===null)return{status:409,value:{saved:!1,conflict:{revision:r.revision,heads_key:r.heads_key,current_body:c,your_body:n.body}}};const d=await B(t,o,a,{body:l},n.rationale?.trim()||"edited by the person in the browser",r.heads_key,{},async m=>await J(t,m));return"stale"in d?{status:409,value:{saved:!1,conflict:{revision:d.stale.revision,heads_key:d.stale.heads_key,current_body:c,your_body:n.body}}}:{status:200,value:{saved:!0,revision:d.revision,heads_key:d.heads_key,body:l,merged:y},change:await U(t,o,[a])}});return e.change&&await W(e.change),e}s(Q,"save");async function be(n,e,t,o){if(n.method==="GET"&&t.pathname==="/api/doc"){const a=t.searchParams.get("ref"),r=a?await k(a):null,i=r&&await N(r);return i?H(e,200,{...i,ref:a}):u(e,404,"not_found","document not found"),!0}if(n.method==="POST"&&t.pathname==="/api/save"){const a=await K(n);if(!a||typeof a!="object"||Array.isArray(a))return u(e,400,"invalid_request","invalid save body"),!0;const r=a;if(typeof r.id!="string"||typeof r.base_heads_key!="string"||typeof r.base_body!="string"||typeof r.body!="string"||r.rationale!==void 0&&typeof r.rationale!="string")return u(e,400,"invalid_request","invalid save body"),!0;const i=await Q(r);return H(e,i.status,i.value),!0}if(n.method==="GET"&&t.pathname==="/api/events"){const a=t.searchParams.get("id");if(!a||!await k(a))return u(e,404,"not_found","document not found"),!0;e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),e.write(`: connected
|
|
2
|
+
|
|
3
|
+
`);const r=s(async()=>{const d=await k(a),m=d&&await N(d);if(!e.writableEnded){if(m){e.write(`event: edited
|
|
4
|
+
data: ${JSON.stringify({revision:m.revision,heads_key:m.heads_key})}
|
|
5
|
+
|
|
6
|
+
`);return}await q(a)&&e.write(`event: deleted
|
|
7
|
+
data: {}
|
|
8
|
+
|
|
9
|
+
`),e.end()}},"notify");let i=!1,c=!1;const f=s(()=>{if(i){c=!0;return}i=!0,o(r).catch(d=>{I({level:"error",event:"daemon.document_events.notify_failed",error:d}),e.end()}).finally(()=>{i=!1,c&&!e.writableEnded&&(c=!1,f())})},"wake"),y=await F(a,f),l=setInterval(()=>{e.writableEnded||e.write(`: keepalive
|
|
10
|
+
|
|
11
|
+
`)},3e4);return e.on("close",()=>{clearInterval(l),y()}),!0}if(n.method==="GET"&&t.pathname.startsWith(`/assets/${w}/`)){const a=t.pathname.slice(`/assets/${w}/`.length);if(!/^[a-zA-Z0-9_.-]+$/.test(a))return u(e,404,"not_found","asset not found"),!0;const r=a==="mermaid.js"?x(S,"clients/attach/assets/mermaid.min.js"):x(S,"doc-editor",a);try{const i=D(r);e.writeHead(200,{"Content-Type":O(a)===".css"?"text/css; charset=utf-8":"text/javascript; charset=utf-8","Cache-Control":"public, max-age=31536000, immutable"}),e.end(i)}catch(i){if(i.code==="ENOENT")u(e,404,"not_found","asset not found");else throw i}return!0}return!1}s(be,"serveDocumentApi");export{ve as cookieValue,_e as documentNotFound,ge as documentShell,u as error,Z as messagePage,k as resolveDocument,be as serveDocumentApi,we as setPageHeaders};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var n=Object.defineProperty;var o=(e,t)=>n(e,"name",{value:t,configurable:!0});import{ApiError as r}from"../../../api/errors.js";import{isCloudRole as s}from"../../../core/canvas/person.js";import{canvasOrigin as i}from"../canvas-host.js";import{documentListenerUnavailable as a}from"../document-listener.js";import{documentSecret as u}from"../document-secret.js";const v=[{method:"GET",pattern:"/v1/documents/browser-access",handler:o(()=>{if(s()){const t=i();if(t===void 0)throw new r(503,"document_listener_unavailable","this API serves no document page (CRTR_CANVAS_URL is unset)");return{status:200,body:{canvas_url:t}}}const e=a();if(e!==void 0)throw new r(503,"document_listener_unavailable",e);return{status:200,body:{secret:u()}}},"handler")}];export{v as documentAccessRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var ze=Object.defineProperty;var n=(e,r)=>ze(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as He,importPrincipalFor as Le}from"./import-auth.js";import{createServer as ie}from"node:http";import{createServer as Be}from"node:https";import{chmodSync as xe,existsSync as G,readFileSync as se,unlinkSync as ae}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as le,RUNTIME_VERSION_HEADER as Y,minimumRuntimeRefusal as De}from"../../api/runtime-version.js";import{CONTRACT_HEADER as K,CONTRACT_LEVEL as ce,REQUIRED_CONTRACT_HEADER as ue,contractRefusal as Me}from"../../api/contract.js";import{crtrVersion as X}from"../../shared/crtr-version.js";import{apiSocketPath as Fe}from"../../core/canvas/paths.js";import{resolveNodeToken as $e}from"../../core/canvas/node-tokens.js";import{isCloudRole as H,runAsPerson as J}from"../../core/canvas/person.js";import{personBearerVerifier as pe}from"./auth/person-bearer.js";import{personHasSnapshot as Z}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as Q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as Je}from"./principal.js";import{createAppRequestHandler as We}from"./app-listener.js";import{decodeJwt as je}from"jose";import{handleRuntimeSignIn as Ve,isRuntimeSignInPath as Ge}from"./key-signin.js";import{RunError as S}from"../../core/runs/operations.js";import{removeVendorAccount as Ye,vendorStatus as Ke}from"./handlers/vendor-status.js";import{toErrorBody as Xe}from"./map.js";import{CONTROL_BODY_MAX_BYTES as Ze}from"../../core/llm/body-limits.js";import{grantFor as Qe,hasSyncedGrants as qe}from"../../core/grants/mirror.js";import{readConfig as de}from"../../core/config.js";import{directoryIssuer as er}from"../../core/directory/issuer.js";import{peerUid as rr}from"../../native/linux.js";import{findScopedApiToken as tr,getApiToken as nr,listScopedApiTokens as or}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as ir,envCrtrdToken as sr}from"../../shared/env.js";import{Router as fe,actsAsPerson as me}from"./router.js";import{handleAttachUpgrade as ar,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as lr,machineLinkEnvironment as cr,setApiAddress as ur}from"../machine-link/holder.js";import{handleMachineViewUpgrade as pr,machineViewEnvironment as dr}from"../machine-link/forward.js";import{boundDaemonControl as fr}from"../control.js";import{attachRoutes as mr,mayAttachNode as ge}from"./handlers/attach.js";import{peerRoutes as gr}from"../peer/handlers.js";import{bashJobRoutes as hr}from"./handlers/bash-jobs.js";import{bashRoutes as Rr}from"./handlers/bash.js";import{hookExecRoutes as Ar}from"./handlers/hook-exec.js";import{brokerOperationRoutes as he}from"./handlers/broker-ops.js";import{brokerSignalRoutes as yr,brokerSignalStreams as _r}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Re,nodeFaultRoutes as vr}from"./handlers/broker-recovery.js";import{canvasRoutes as wr}from"./handlers/canvas.js";import{conversationRoutes as Er}from"./handlers/conversations.js";import{chatInventoryRoutes as Sr}from"./handlers/chat-inventory.js";import{daemonRoutes as br}from"./handlers/daemon.js";import{fileRoutes as Tr}from"./handlers/files.js";import{focusRoutes as Cr}from"./handlers/focus.js";import{analyticsRoutes as kr}from"./handlers/analytics.js";import{memoryReadsRoutes as Ur}from"./handlers/memory-reads.js";import{memoryRoutes as Or}from"./handlers/memory.js";import{healthRoutes as Pr}from"./handlers/health.js";import{humanRequestRoutes as Nr}from"./handlers/human-requests.js";import{inboxRoutes as Ir}from"./handlers/inbox.js";import{feedbackCommentRoutes as zr}from"./handlers/feedback-comments.js";import{objectRoutes as Hr}from"./handlers/objects.js";import{shareRoutes as Lr}from"./handlers/shares.js";import{customObjectRoutes as Br}from"./handlers/custom-objects.js";import{docRoutes as xr}from"./handlers/docs.js";import{deliveryRoutes as Ae}from"./handlers/delivery.js";import{deliveryRetryRoutes as Dr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Mr}from"./handlers/package-docs.js";import{documentAccessRoutes as Fr}from"./handlers/document-access.js";import{pluginAppRoutes as $r}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as ye,messageRoutes as Jr}from"./handlers/messages.js";import{modelAuthRoutes as Wr}from"./handlers/modelauth.js";import{llmRoutes as jr}from"./handlers/llm.js";import{providerRoutes as Vr}from"./handlers/providers.js";import{modelConfigRoutes as Gr}from"./handlers/model-config.js";import{settingsRoutes as Yr}from"./handlers/settings.js";import{nodeRoutes as Kr}from"./handlers/nodes.js";import{nodeRecordRoutes as Xr}from"./handlers/node-records.js";import{nodeOutcomeRoutes as Zr}from"./handlers/node-outcomes.js";import{nodeEventRoutes as Qr}from"./handlers/node-events.js";import{profileRoutes as qr}from"./handlers/profiles.js";import{prospectiveChatInventoryRoutes as et}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as rt}from"./handlers/reports.js";import{runRoutes as tt}from"./handlers/run-routes.js";import{reviewCommentRoutes as nt}from"./handlers/review-comments.js";import{reviewRoutes as ot}from"./handlers/reviews.js";import{subscriptionRoutes as it}from"./handlers/subscriptions.js";import{structuredRequestRoutes as st}from"./handlers/structured-requests.js";import{cronRoutes as at}from"./handlers/crons.js";import{setCronRequestHandler as _e}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as lt,cronPrincipalForRunToken as ct}from"../cron/run-token.js";import{worktreeRoutes as ut}from"./handlers/worktree.js";import{limitsRoutes as pt}from"./handlers/limits.js";import{chargeRoutes as dt,spendLimitRoutes as ft}from"./handlers/charges.js";import{executionStartRoutes as mt}from"./handlers/execution-start.js";import{machineCredentialRoutes as gt}from"./handlers/machine-credential.js";import{importRoutes as ht}from"./handlers/imports.js";import{gitCredentialRoutes as Rt}from"./handlers/git-credential.js";function At(e){return new fe().registerAll(Pr(e)).registerAll(br).registerAll(Lr).registerAll(Kr).registerAll(Xr).registerAll(Zr).registerAll(Dr).registerAll(Qr).registerAll(hr).registerAll(Rr).registerAll(Ar).registerAll(he).registerAll(yr).registerAll(Ae).registerAll(Re).registerAll(vr).registerAll(ut).registerAll(pt).registerAll(dt).registerAll(mt).registerAll(gt).registerAll(ht).registerAll(Rt).registerAll(ft).registerAll(ye).registerAll(Jr).registerAll(rt).registerAll(tt).registerAll(st).registerAll(mr).registerAll(wr).registerAll(Er).registerAll(kr).registerAll(Ur).registerAll(Or).registerAll(Tr).registerAll(Hr).registerAll(Br).registerAll(xr).registerAll(Mr).registerAll(Fr).registerAll($r).registerAll(Cr).registerAll(it).registerAll(at).registerAll(qr).registerAll(Wr).registerAll(jr).registerAll(Vr).registerAll(Gr).registerAll(Yr).registerAll(ot).registerAll(nt).registerAll(Ir).registerAll(Nr).registerAll(Sr).registerAll(et).registerAll(zr).registerAll(gr)}n(At,"buildRouter");function yt(e,r){if(e.toUpperCase()!=="GET")return null;const o=r.split("/").filter(u=>u.length>0);if(o.length!==4||o[0]!=="v1"||o[1]!=="nodes"||o[3]!=="attach")return null;const a=o[2];return a===void 0||a===""?null:decodeURIComponent(a)}n(yt,"attachNodeId");function _t(e){const r=e.trim();if(r==="")return null;const o=r.lastIndexOf(":");if(o<0)return null;const a=r.slice(0,o),u=r.slice(o+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}n(_t,"parseTcp");function vt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}n(vt,"formatTcpAddress");const P={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},M={code:"person_bearer_not_supported",message:"this listener accepts a person bearer only on a cloud role with CRTR_DIRECTORY_URL and CRTR_PUBLIC_API_URL set; call with a node, app or public token"},q={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function F(e){return B.get(e)}n(F,"socketPrincipal");async function ve(e,r){const o=process.platform==="linux"?rr(e.socket):null,a=e.headers.authorization;if(a===void 0)return o===null||r.has(o)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return q;if(a.slice(7).startsWith(ee)){const u=be(a.slice(7));return u!==void 0&&(o===null||r.has(o))?u.principal:"unauthorized"}return we(a.slice(7),o)}n(ve,"resolveSocketPrincipal");async function we(e,r){const o=await $e(e);if(!o||r!==null&&r!==o.uid)return"unauthorized";const a=er();if(a&&!H()&&!await qe(a))return"runtime_starting";const u=o.grant??(await Qe("app:terminal",o.sub))?.id??null;return{class:"broker",...o,grant:u}}n(we,"brokerPrincipal");function Ee(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}n(Ee,"requestPerson");function Se(e,r){r.class==="broker"&&A({event:"api.request.principal",level:r.app==="app:terminal"?"debug":"info",node_id:r.node,fields:{principal:`${r.app} node:${r.node}`,method:e.method,path:e.url}})}n(Se,"noteBrokerRequest");const ee="crtr_app_";function be(e){const r=e.startsWith(ee)?tr(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}n(be,"appBearer");function wt(e){const r=new Map;for(const o of or("user"))r.set(o.token,{principal:{class:"app",app:o.grantee,scopes:o.scopes},ceiling:o.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}n(wt,"resolveBearers");function Et(e){try{return je(e).act!==void 0}catch{return!1}}n(Et,"carriesAct");const St=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function k(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}n(k,"deny");async function Te(e,r,o){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:q,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return k(o,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:q,ceiling:null};if(u.startsWith(ee))return be(u)??k(o,"app_token_unknown");if(u.startsWith(lt)){const w=await ct(u);return w===null?k(o,"run_token_invalid_or_settled"):{principal:w,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const R=Le(u);if(R!==null)return{principal:R,ceiling:null};if(u.startsWith(He))return k(o,"import_token_invalid");if(St.test(u)){if(H()&&Et(u)){const x=j();if(x===null)return"person_bearer";try{const v=await x.verifyCall(a);return v.chain[0]?.sub.startsWith("app:")?{call:v}:k(o,"call_token_presenter_not_an_app")}catch(v){return v instanceof S&&v.status===503?"runtime_starting":k(o,`call_token_${v instanceof S?v.code:"invalid"}`)}}const w=H()?pe():null;if(w===null)return"person_bearer";const U=await w.verify(u);return U===null?k(o,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await we(u,null);return m==="unauthorized"?k(o,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}n(Te,"authorizeTcp");let W;function j(){if(W!==void 0)return W;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return W=e===void 0||r===void 0?null:new Je(e,r,async()=>{}),W}n(j,"cloudCallResolver");let Ce;function bt(){const e=j();if(e===null)throw new S(503,"runtime_starting","app calls are not configured on this listener");return Ce??=We(e,async()=>!0,async()=>{}),Ce}n(bt,"cloudAppCalls");async function Tt(e,r){N(r),I(r);const o=j();try{if(o===null)throw new S(503,"runtime_starting","sign-in is not configured on this listener");await Ve(e,r,new URL(e.url??"/","http://runtime.local"),o)}catch(a){if(!(a instanceof S))throw a;if(r.headersSent){r.destroy();return}r.writeHead(a.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:a.code,message:a.message,...a.param?{param:a.param}:{},origin:"runtime"}}))}}n(Tt,"serveRuntimeSignIn");function Ct(){const e=process.env.CRTRD_TLS_CERT||void 0,r=process.env.CRTRD_TLS_KEY||void 0;if(e===void 0&&r===void 0)return null;if(e===void 0||r===void 0)throw new Error("CRTRD_TLS_CERT and CRTRD_TLS_KEY must be set together");return{cert:se(e),key:se(r)}}n(Ct,"tcpTls");function N(e){e.setHeader(Y,X()),e.setHeader(K,ce)}n(N,"advertiseRuntime");function I(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Y}, ${K}`)}n(I,"exposeRuntimeHeaders");function kt(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(N(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Y}, ${K}`,"Access-Control-Allow-Headers":`authorization, content-type, ${le.toLowerCase()}, ${ue.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}n(kt,"answerPreflight");function V(e,r=!1){N(e),r&&I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...P,origin:"runtime"}}))}n(V,"writeUnauthorized");function Ut(e){N(e),I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}n(Ut,"writePersonBearerRefused");const Ot={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function Pt(e,r){if(!H())return!1;const o=new URL(e.url??"/","http://runtime.local").pathname,a=Ot[o];if(a===void 0||e.method!==a.method)return!1;const u=n((d,R)=>{N(r),I(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=pe();if(d===null)throw new S(401,M.code,M.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),a.purpose):null;if(m===null)throw new S(401,"unauthorized","invalid directory token");const w=a.purpose==="vendor_status"?void 0:await Nt(e);u(200,await J(m,async()=>a.purpose==="vendor_status"?Ke():await Ye(w)))}catch(d){const{status:R,body:m}=Xe(d);u(R,m)}return!0}n(Pt,"serveCloudVendorRoute");async function Nt(e){const r=[];let o=0;for await(const a of e){if(o+=a.length,o>Ze)throw new S(400,"invalid_request","request body too large");r.push(a)}if(o!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new S(400,"invalid_request","invalid JSON body")}}n(Nt,"readVendorBody");function ke(e){N(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}n(ke,"writeRuntimeStarting");function It(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}n(It,"writeStartupBlocked");function Ue(e,r,o){return new Promise(a=>{for(const m of r)m.destroy();if(o===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const m of u)clearTimeout(m);a()});const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),o);u.push(d,R),e.closeIdleConnections()})}n(Ue,"closeServer");function vo(e={}){let r=null;const o=At(()=>r),a=new fe().registerAll(he).registerAll(Ae).registerAll(Re).registerAll(ye),u=n((t,i)=>{const c=fr()?.startupBlock()??null;return c===null||t==="GET"&&(i==="/healthz"||i==="/v1/status"||i==="/v1/ready")||t==="POST"&&(i==="/v1/daemon/migrate"||i==="/v1/daemon/admit")||c.phase==="recovering"&&a.match(t,i)!==null?null:c},"startupBlockFor"),d=e.socketPath??Fe(),R=new Set([process.getuid?.()??0,...de("user").runtime?.person_uids??[]]),m=n((t,i,c)=>{N(i);const p=n(s=>Array.isArray(s)?s[0]:s,"first"),O=p(t.headers[le.toLowerCase()]),h=De(O,X())??Me(p(t.headers[ue.toLowerCase()]),ce,{legacyMinimum:O,runtimeVersion:X()});if(h!==null){i.writeHead(h.status,{"content-type":"application/json; charset=utf-8"}),i.end(JSON.stringify({error:{code:h.code,message:h.message,type:"invalid_request_error",origin:"runtime",retryable:!1,..."param"in h?{param:h.param}:{details:h.details}}}));return}const E=n(s=>{const l=F(t);A({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:s instanceof Error?s:new Error(String(s))});try{i.headersSent||i.writeHead(500,{"content-type":"application/json; charset=utf-8"}),i.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let T;try{T=new URL(t.url??"/","http://127.0.0.1")}catch{try{i.writeHead(400,{"content-type":"application/json; charset=utf-8"}),i.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const s=u((t.method??"GET").toUpperCase(),T.pathname);if(s!==null){It(i,s.message);return}const l=F(t)??{class:"person"},f=Ee(l),g=n(()=>o.handle(t,i,c,l),"handled");(f===void 0?g():J(f,n(async()=>{Z()||await Q(f),await g()},"handledAsPerson"))).catch(E)}catch(s){E(s)}},"onRequest"),w=n(async(t,i,c)=>{const p=F(t);return p===void 0||me(p)||await ge(p,"either",c)?!0:(y(i,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),U=new Set,x=n(t=>{U.add(t),t.once("close",()=>U.delete(t)),t.on("error",()=>{})},"trackUpgrade"),v=n((t,i,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),O=u((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){y(i,503,"Service Unavailable","startup_blocked",O.message);return}const h=yt(t.method??"GET",p.pathname);if(h===null){i.destroy();return}const E=(()=>{const s=F(t);return s===void 0?void 0:Ee(s)})(),T=n(()=>w(t,i,h).then(s=>s?ar(t,i,c,h,async l=>{const f=F(t);return f===void 0||me(f)||await ge(f,l,h)}):void 0),"attach");(E===void 0?T():J(E,async()=>{Z()||await Q(E),await T()})).catch(()=>{try{i.destroy()}catch{}})}catch{try{i.destroy()}catch{}}},"onUpgrade"),Oe=n(t=>{t.on("error",i=>{A({event:"api.server.failed",level:"error",error:i})})},"bindErrorHandler"),Pe=n(async(t,i)=>{try{const c=await ve(t,R);if(c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),V(i);return}if(c==="runtime_starting"){ke(i);return}B.set(t,c),Se(t,c),m(t,i,c.class==="app"?c.scopes:null)}catch(c){A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),V(i)}},"onSocketRequest"),D=ie((t,i)=>{Pe(t,i).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Ne=n(async(t,i,c)=>{try{const p=await ve(t,R);if(p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(i,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(i,403,"Forbidden",L.code,L.message);return}B.set(t,p),v(t,i,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(i,401,"Unauthorized",P.code,P.message)}},"onSocketUpgrade");D.on("upgrade",(t,i,c)=>{x(i),Ne(t,i,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),_e((t,i,c)=>{B.set(t,c),m(t,i,null)});let re=!1,te,ne;const Ie=new Promise((t,i)=>{te=t,ne=i});D.once("listening",()=>{re=!0,te()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),re||ne(t)});try{G(d)&&ae(d)}catch{}D.listen(d,()=>{try{xe(d,process.platform==="linux"&&G("/run/crtr/launcher.sock")?438:384)}catch(t){A({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let b;const $=e.tcp??ir()??de("user").api.tcp;if($!==void 0&&$!==""){const t=_t($);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${$}`)});else{H()&&j();const i=e.token??sr()??nr("user"),c=wt(i),p=n(async(s,l)=>{if(kt(s,l))return;if(H()&&Ge(new URL(s.url??"/","http://runtime.local").pathname)){await Tt(s,l);return}if(await Pt(s,l))return;const f={},g=await Te(s,c,f);if(g==="runtime_starting"){I(l),ke(l);return}if(g==="person_bearer"){Ut(l);return}if(g==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:s.method,listener:"tcp",path:new URL(s.url??"/","http://runtime.local").pathname,reason:f.reason??"unknown"}}),V(l,!0);return}if("call"in g){I(l);const z=g.call.sub;await J(z,async()=>{Z()||await Q(z),await bt()(s,l,g.call)});return}B.set(s,g.principal),Se(s,g.principal),I(l),m(s,l,g.ceiling)},"tcpOnRequest"),O=n(async(s,l,f)=>{const g=cr(s);if(g!==null){const _=await lr(s,l,f,g);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const z=dr(s);if(z!==null){const _=pr(s,l,f,z);_!==null&&y(l,_.status,_.text,_.code,_.message);return}const C=await Te(s,c);if(C==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(C==="person_bearer"){y(l,401,"Unauthorized",M.code,M.message);return}if(C==="unauthorized"){y(l,401,"Unauthorized",P.code,P.message);return}if("call"in C){y(l,403,"Forbidden",L.code,L.message);return}if(C.ceiling!==null||C.principal.class==="anonymous"||C.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(s,C.principal),v(s,l,f)},"tcpOnUpgrade"),h=n(s=>{A({event:"api.principal.failed",level:"error",error:s instanceof Error?s:new Error(String(s))})},"failed"),E=n((s,l)=>{p(s,l).catch(f=>{h(f),l.headersSent?l.destroy():V(l,!0)})},"listener"),T=Ct();b=T===null?ie(E):Be(T,E),b.on("upgrade",(s,l,f)=>{x(l),O(s,l,f).catch(g=>{h(g),y(l,401,"Unauthorized",P.code,P.message)})}),Oe(b),b.once("listening",()=>{const s=b?.address();if(s!==null&&typeof s=="object"){const{address:l,port:f}=s;r=vt(l,f),l!=="0.0.0.0"&&l!=="::"&&ur(r)}}),b.listen(t.port,t.host)}}let oe=!1;return{ready:Ie,tcpAddress:n(()=>r,"tcpAddress"),close:n(async(t={})=>{if(!oe){oe=!0,_e(null),_r.close(),await Promise.all([Ue(D,U,t.graceMs),b!==void 0?Ue(b,U,t.graceMs):Promise.resolve()]);try{G(d)&&ae(d)}catch{}}},"close")}}n(vo,"createApiServer");export{At as buildRouter,Ue as closeServer,vo as createApiServer,F as socketPrincipal};
|
|
1
|
+
var ze=Object.defineProperty;var o=(e,r)=>ze(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as He,importPrincipalFor as Le}from"./import-auth.js";import{createServer as ie}from"node:http";import{createServer as Be}from"node:https";import{chmodSync as xe,existsSync as G,readFileSync as se,unlinkSync as ae}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as le,RUNTIME_VERSION_HEADER as Y,minimumRuntimeRefusal as De}from"../../api/runtime-version.js";import{CONTRACT_HEADER as K,CONTRACT_LEVEL as ce,REQUIRED_CONTRACT_HEADER as ue,contractRefusal as Me}from"../../api/contract.js";import{crtrVersion as X}from"../../shared/crtr-version.js";import{apiSocketPath as Fe}from"../../core/canvas/paths.js";import{resolveNodeToken as $e}from"../../core/canvas/node-tokens.js";import{isCloudRole as H,runAsPerson as J}from"../../core/canvas/person.js";import{isCanvasRequest as Je,serveCanvas as We}from"./canvas-host.js";import{personBearerVerifier as pe}from"./auth/person-bearer.js";import{personHasSnapshot as Z}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as Q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as je}from"./principal.js";import{createAppRequestHandler as Ve}from"./app-listener.js";import{decodeJwt as Ge}from"jose";import{handleRuntimeSignIn as Ye,isRuntimeSignInPath as Ke}from"./key-signin.js";import{RunError as S}from"../../core/runs/operations.js";import{removeVendorAccount as Xe,vendorStatus as Ze}from"./handlers/vendor-status.js";import{toErrorBody as Qe}from"./map.js";import{CONTROL_BODY_MAX_BYTES as qe}from"../../core/llm/body-limits.js";import{grantFor as er,hasSyncedGrants as rr}from"../../core/grants/mirror.js";import{readConfig as de}from"../../core/config.js";import{directoryIssuer as tr}from"../../core/directory/issuer.js";import{peerUid as nr}from"../../native/linux.js";import{findScopedApiToken as or,getApiToken as ir,listScopedApiTokens as sr}from"../../core/secrets.js";import{emitEvent as A}from"../../core/events/emit.js";import{envCrtrdTcp as ar,envCrtrdToken as lr}from"../../shared/env.js";import{Router as fe,actsAsPerson as me}from"./router.js";import{handleAttachUpgrade as cr,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as ur,machineLinkEnvironment as pr,setApiAddress as dr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as fr,machineViewEnvironment as mr}from"../machine-link/forward.js";import{boundDaemonControl as gr}from"../control.js";import{attachRoutes as hr,mayAttachNode as ge}from"./handlers/attach.js";import{peerRoutes as Rr}from"../peer/handlers.js";import{bashJobRoutes as Ar}from"./handlers/bash-jobs.js";import{bashRoutes as yr}from"./handlers/bash.js";import{hookExecRoutes as vr}from"./handlers/hook-exec.js";import{brokerOperationRoutes as he}from"./handlers/broker-ops.js";import{brokerSignalRoutes as _r,brokerSignalStreams as wr}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Re,nodeFaultRoutes as Er}from"./handlers/broker-recovery.js";import{canvasRoutes as Sr}from"./handlers/canvas.js";import{conversationRoutes as br}from"./handlers/conversations.js";import{chatInventoryRoutes as Tr}from"./handlers/chat-inventory.js";import{daemonRoutes as Cr}from"./handlers/daemon.js";import{fileRoutes as kr}from"./handlers/files.js";import{focusRoutes as Ur}from"./handlers/focus.js";import{analyticsRoutes as Or}from"./handlers/analytics.js";import{memoryReadsRoutes as Pr}from"./handlers/memory-reads.js";import{memoryRoutes as Nr}from"./handlers/memory.js";import{healthRoutes as Ir}from"./handlers/health.js";import{humanRequestRoutes as zr}from"./handlers/human-requests.js";import{inboxRoutes as Hr}from"./handlers/inbox.js";import{feedbackCommentRoutes as Lr}from"./handlers/feedback-comments.js";import{objectRoutes as Br}from"./handlers/objects.js";import{shareRoutes as xr}from"./handlers/shares.js";import{customObjectRoutes as Dr}from"./handlers/custom-objects.js";import{docRoutes as Mr}from"./handlers/docs.js";import{deliveryRoutes as Ae}from"./handlers/delivery.js";import{deliveryRetryRoutes as Fr}from"./handlers/delivery-retry.js";import{packageDocRoutes as $r}from"./handlers/package-docs.js";import{documentAccessRoutes as Jr}from"./handlers/document-access.js";import{pluginAppRoutes as Wr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as ye,messageRoutes as jr}from"./handlers/messages.js";import{modelAuthRoutes as Vr}from"./handlers/modelauth.js";import{llmRoutes as Gr}from"./handlers/llm.js";import{providerRoutes as Yr}from"./handlers/providers.js";import{modelConfigRoutes as Kr}from"./handlers/model-config.js";import{settingsRoutes as Xr}from"./handlers/settings.js";import{nodeRoutes as Zr}from"./handlers/nodes.js";import{nodeRecordRoutes as Qr}from"./handlers/node-records.js";import{nodeOutcomeRoutes as qr}from"./handlers/node-outcomes.js";import{nodeEventRoutes as et}from"./handlers/node-events.js";import{profileRoutes as rt}from"./handlers/profiles.js";import{prospectiveChatInventoryRoutes as tt}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as nt}from"./handlers/reports.js";import{runRoutes as ot}from"./handlers/run-routes.js";import{reviewCommentRoutes as it}from"./handlers/review-comments.js";import{reviewRoutes as st}from"./handlers/reviews.js";import{subscriptionRoutes as at}from"./handlers/subscriptions.js";import{structuredRequestRoutes as lt}from"./handlers/structured-requests.js";import{cronRoutes as ct}from"./handlers/crons.js";import{setCronRequestHandler as ve}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as ut,cronPrincipalForRunToken as pt}from"../cron/run-token.js";import{worktreeRoutes as dt}from"./handlers/worktree.js";import{limitsRoutes as ft}from"./handlers/limits.js";import{chargeRoutes as mt,spendLimitRoutes as gt}from"./handlers/charges.js";import{executionStartRoutes as ht}from"./handlers/execution-start.js";import{machineCredentialRoutes as Rt}from"./handlers/machine-credential.js";import{importRoutes as At}from"./handlers/imports.js";import{gitCredentialRoutes as yt}from"./handlers/git-credential.js";function vt(e){return new fe().registerAll(Ir(e)).registerAll(Cr).registerAll(xr).registerAll(Zr).registerAll(Qr).registerAll(qr).registerAll(Fr).registerAll(et).registerAll(Ar).registerAll(yr).registerAll(vr).registerAll(he).registerAll(_r).registerAll(Ae).registerAll(Re).registerAll(Er).registerAll(dt).registerAll(ft).registerAll(mt).registerAll(ht).registerAll(Rt).registerAll(At).registerAll(yt).registerAll(gt).registerAll(ye).registerAll(jr).registerAll(nt).registerAll(ot).registerAll(lt).registerAll(hr).registerAll(Sr).registerAll(br).registerAll(Or).registerAll(Pr).registerAll(Nr).registerAll(kr).registerAll(Br).registerAll(Dr).registerAll(Mr).registerAll($r).registerAll(Jr).registerAll(Wr).registerAll(Ur).registerAll(at).registerAll(ct).registerAll(rt).registerAll(Vr).registerAll(Gr).registerAll(Yr).registerAll(Kr).registerAll(Xr).registerAll(st).registerAll(it).registerAll(Hr).registerAll(zr).registerAll(Tr).registerAll(tt).registerAll(Lr).registerAll(Rr)}o(vt,"buildRouter");function _t(e,r){if(e.toUpperCase()!=="GET")return null;const i=r.split("/").filter(u=>u.length>0);if(i.length!==4||i[0]!=="v1"||i[1]!=="nodes"||i[3]!=="attach")return null;const a=i[2];return a===void 0||a===""?null:decodeURIComponent(a)}o(_t,"attachNodeId");function wt(e){const r=e.trim();if(r==="")return null;const i=r.lastIndexOf(":");if(i<0)return null;const a=r.slice(0,i),u=r.slice(i+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:a===""?"0.0.0.0":a,port:d}}o(wt,"parseTcp");function Et(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}o(Et,"formatTcpAddress");const P={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},M={code:"person_bearer_not_supported",message:"this listener accepts a person bearer only on a cloud role with CRTR_DIRECTORY_URL and CRTR_PUBLIC_API_URL set; call with a node, app or public token"},q={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function F(e){return B.get(e)}o(F,"socketPrincipal");async function _e(e,r){const i=process.platform==="linux"?nr(e.socket):null,a=e.headers.authorization;if(a===void 0)return i===null||r.has(i)?{class:"person"}:"unauthorized";if(typeof a!="string"||!a.startsWith("Bearer "))return"unauthorized";if(a.slice(7).startsWith("crtr_pub_"))return q;if(a.slice(7).startsWith(ee)){const u=be(a.slice(7));return u!==void 0&&(i===null||r.has(i))?u.principal:"unauthorized"}return we(a.slice(7),i)}o(_e,"resolveSocketPrincipal");async function we(e,r){const i=await $e(e);if(!i||r!==null&&r!==i.uid)return"unauthorized";const a=tr();if(a&&!H()&&!await rr(a))return"runtime_starting";const u=i.grant??(await er("app:terminal",i.sub))?.id??null;return{class:"broker",...i,grant:u}}o(we,"brokerPrincipal");function Ee(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}o(Ee,"requestPerson");function Se(e,r){r.class==="broker"&&A({event:"api.request.principal",level:r.app==="app:terminal"?"debug":"info",node_id:r.node,fields:{principal:`${r.app} node:${r.node}`,method:e.method,path:e.url}})}o(Se,"noteBrokerRequest");const ee="crtr_app_";function be(e){const r=e.startsWith(ee)?or(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}o(be,"appBearer");function St(e){const r=new Map;for(const i of sr("user"))r.set(i.token,{principal:{class:"app",app:i.grantee,scopes:i.scopes},ceiling:i.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}o(St,"resolveBearers");function bt(e){try{return Ge(e).act!==void 0}catch{return!1}}o(bt,"carriesAct");const Tt=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function k(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}o(k,"deny");async function Te(e,r,i){const a=e.headers.authorization;if(a===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:q,ceiling:null};if(typeof a!="string"||!a.startsWith("Bearer "))return k(i,a===void 0?"no_authorization_header":"not_a_bearer");const u=a.slice(7);if(u.startsWith("crtr_pub_"))return{principal:q,ceiling:null};if(u.startsWith(ee))return be(u)??k(i,"app_token_unknown");if(u.startsWith(ut)){const w=await pt(u);return w===null?k(i,"run_token_invalid_or_settled"):{principal:w,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const R=Le(u);if(R!==null)return{principal:R,ceiling:null};if(u.startsWith(He))return k(i,"import_token_invalid");if(Tt.test(u)){if(H()&&bt(u)){const x=j();if(x===null)return"person_bearer";try{const _=await x.verifyCall(a);return _.chain[0]?.sub.startsWith("app:")?{call:_}:k(i,"call_token_presenter_not_an_app")}catch(_){return _ instanceof S&&_.status===503?"runtime_starting":k(i,`call_token_${_ instanceof S?_.code:"invalid"}`)}}const w=H()?pe():null;if(w===null)return"person_bearer";const U=await w.verify(u);return U===null?k(i,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await we(u,null);return m==="unauthorized"?k(i,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}o(Te,"authorizeTcp");let W;function j(){if(W!==void 0)return W;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return W=e===void 0||r===void 0?null:new je(e,r,async()=>{}),W}o(j,"cloudCallResolver");let Ce;function Ct(){const e=j();if(e===null)throw new S(503,"runtime_starting","app calls are not configured on this listener");return Ce??=Ve(e,async()=>!0,async()=>{}),Ce}o(Ct,"cloudAppCalls");async function kt(e,r){N(r),I(r);const i=j();try{if(i===null)throw new S(503,"runtime_starting","sign-in is not configured on this listener");await Ye(e,r,new URL(e.url??"/","http://runtime.local"),i)}catch(a){if(!(a instanceof S))throw a;if(r.headersSent){r.destroy();return}r.writeHead(a.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:a.code,message:a.message,...a.param?{param:a.param}:{},origin:"runtime"}}))}}o(kt,"serveRuntimeSignIn");function Ut(){const e=process.env.CRTRD_TLS_CERT||void 0,r=process.env.CRTRD_TLS_KEY||void 0;if(e===void 0&&r===void 0)return null;if(e===void 0||r===void 0)throw new Error("CRTRD_TLS_CERT and CRTRD_TLS_KEY must be set together");return{cert:se(e),key:se(r)}}o(Ut,"tcpTls");function N(e){e.setHeader(Y,X()),e.setHeader(K,ce)}o(N,"advertiseRuntime");function I(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Y}, ${K}`)}o(I,"exposeRuntimeHeaders");function Ot(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(N(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Y}, ${K}`,"Access-Control-Allow-Headers":`authorization, content-type, ${le.toLowerCase()}, ${ue.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}o(Ot,"answerPreflight");function V(e,r=!1){N(e),r&&I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...P,origin:"runtime"}}))}o(V,"writeUnauthorized");function Pt(e){N(e),I(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}o(Pt,"writePersonBearerRefused");const Nt={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function It(e,r){if(!H())return!1;const i=new URL(e.url??"/","http://runtime.local").pathname,a=Nt[i];if(a===void 0||e.method!==a.method)return!1;const u=o((d,R)=>{N(r),I(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=pe();if(d===null)throw new S(401,M.code,M.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),a.purpose):null;if(m===null)throw new S(401,"unauthorized","invalid directory token");const w=a.purpose==="vendor_status"?void 0:await zt(e);u(200,await J(m,async()=>a.purpose==="vendor_status"?Ze():await Xe(w)))}catch(d){const{status:R,body:m}=Qe(d);u(R,m)}return!0}o(It,"serveCloudVendorRoute");async function zt(e){const r=[];let i=0;for await(const a of e){if(i+=a.length,i>qe)throw new S(400,"invalid_request","request body too large");r.push(a)}if(i!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new S(400,"invalid_request","invalid JSON body")}}o(zt,"readVendorBody");function ke(e){N(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}o(ke,"writeRuntimeStarting");function Ht(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}o(Ht,"writeStartupBlocked");function Ue(e,r,i){return new Promise(a=>{for(const m of r)m.destroy();if(i===void 0){try{e.closeAllConnections()}catch{}e.close(()=>a());return}const u=[];e.close(()=>{for(const m of u)clearTimeout(m);a()});const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),i);u.push(d,R),e.closeIdleConnections()})}o(Ue,"closeServer");function So(e={}){let r=null;const i=vt(()=>r),a=new fe().registerAll(he).registerAll(Ae).registerAll(Re).registerAll(ye),u=o((t,s)=>{const c=gr()?.startupBlock()??null;return c===null||t==="GET"&&(s==="/healthz"||s==="/v1/status"||s==="/v1/ready")||t==="POST"&&(s==="/v1/daemon/migrate"||s==="/v1/daemon/admit")||c.phase==="recovering"&&a.match(t,s)!==null?null:c},"startupBlockFor"),d=e.socketPath??Fe(),R=new Set([process.getuid?.()??0,...de("user").runtime?.person_uids??[]]),m=o((t,s,c)=>{N(s);const p=o(n=>Array.isArray(n)?n[0]:n,"first"),O=p(t.headers[le.toLowerCase()]),h=De(O,X())??Me(p(t.headers[ue.toLowerCase()]),ce,{legacyMinimum:O,runtimeVersion:X()});if(h!==null){s.writeHead(h.status,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:h.code,message:h.message,type:"invalid_request_error",origin:"runtime",retryable:!1,..."param"in h?{param:h.param}:{details:h.details}}}));return}const E=o(n=>{const l=F(t);A({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:n instanceof Error?n:new Error(String(n))});try{s.headersSent||s.writeHead(500,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let T;try{T=new URL(t.url??"/","http://127.0.0.1")}catch{try{s.writeHead(400,{"content-type":"application/json; charset=utf-8"}),s.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const n=u((t.method??"GET").toUpperCase(),T.pathname);if(n!==null){Ht(s,n.message);return}const l=F(t)??{class:"person"},f=Ee(l),g=o(()=>i.handle(t,s,c,l),"handled");(f===void 0?g():J(f,o(async()=>{Z()||await Q(f),await g()},"handledAsPerson"))).catch(E)}catch(n){E(n)}},"onRequest"),w=o(async(t,s,c)=>{const p=F(t);return p===void 0||me(p)||await ge(p,"either",c)?!0:(y(s,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),U=new Set,x=o(t=>{U.add(t),t.once("close",()=>U.delete(t)),t.on("error",()=>{})},"trackUpgrade"),_=o((t,s,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),O=u((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){y(s,503,"Service Unavailable","startup_blocked",O.message);return}const h=_t(t.method??"GET",p.pathname);if(h===null){s.destroy();return}const E=(()=>{const n=F(t);return n===void 0?void 0:Ee(n)})(),T=o(()=>w(t,s,h).then(n=>n?cr(t,s,c,h,async l=>{const f=F(t);return f===void 0||me(f)||await ge(f,l,h)}):void 0),"attach");(E===void 0?T():J(E,async()=>{Z()||await Q(E),await T()})).catch(()=>{try{s.destroy()}catch{}})}catch{try{s.destroy()}catch{}}},"onUpgrade"),Oe=o(t=>{t.on("error",s=>{A({event:"api.server.failed",level:"error",error:s})})},"bindErrorHandler"),Pe=o(async(t,s)=>{try{const c=await _e(t,R);if(c==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),V(s);return}if(c==="runtime_starting"){ke(s);return}B.set(t,c),Se(t,c),m(t,s,c.class==="app"?c.scopes:null)}catch(c){A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),V(s)}},"onSocketRequest"),D=ie((t,s)=>{Pe(t,s).catch(c=>A({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Ne=o(async(t,s,c)=>{try{const p=await _e(t,R);if(p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&A({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(s,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(s,403,"Forbidden",L.code,L.message);return}B.set(t,p),_(t,s,c)}catch(p){A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(s,401,"Unauthorized",P.code,P.message)}},"onSocketUpgrade");D.on("upgrade",(t,s,c)=>{x(s),Ne(t,s,c).catch(p=>A({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),ve((t,s,c)=>{B.set(t,c),m(t,s,null)});let re=!1,te,ne;const Ie=new Promise((t,s)=>{te=t,ne=s});D.once("listening",()=>{re=!0,te()}),D.on("error",t=>{A({event:"api.server.failed",level:"error",error:t}),re||ne(t)});try{G(d)&&ae(d)}catch{}D.listen(d,()=>{try{xe(d,process.platform==="linux"&&G("/run/crtr/launcher.sock")?438:384)}catch(t){A({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let b;const $=e.tcp??ar()??de("user").api.tcp;if($!==void 0&&$!==""){const t=wt($);if(t===null)A({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${$}`)});else{H()&&j();const s=e.token??lr()??ir("user"),c=St(s),p=o(async(n,l)=>{if(Je(n)){await We(n,l);return}if(Ot(n,l))return;if(H()&&Ke(new URL(n.url??"/","http://runtime.local").pathname)){await kt(n,l);return}if(await It(n,l))return;const f={},g=await Te(n,c,f);if(g==="runtime_starting"){I(l),ke(l);return}if(g==="person_bearer"){Pt(l);return}if(g==="unauthorized"){A({event:"api.principal.denied",level:"warn",fields:{method:n.method,listener:"tcp",path:new URL(n.url??"/","http://runtime.local").pathname,reason:f.reason??"unknown"}}),V(l,!0);return}if("call"in g){I(l);const z=g.call.sub;await J(z,async()=>{Z()||await Q(z),await Ct()(n,l,g.call)});return}B.set(n,g.principal),Se(n,g.principal),I(l),m(n,l,g.ceiling)},"tcpOnRequest"),O=o(async(n,l,f)=>{const g=pr(n);if(g!==null){const v=await ur(n,l,f,g);v!==null&&y(l,v.status,v.text,v.code,v.message);return}const z=mr(n);if(z!==null){const v=fr(n,l,f,z);v!==null&&y(l,v.status,v.text,v.code,v.message);return}const C=await Te(n,c);if(C==="runtime_starting"){y(l,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(C==="person_bearer"){y(l,401,"Unauthorized",M.code,M.message);return}if(C==="unauthorized"){y(l,401,"Unauthorized",P.code,P.message);return}if("call"in C){y(l,403,"Forbidden",L.code,L.message);return}if(C.ceiling!==null||C.principal.class==="anonymous"||C.principal.class==="import"){y(l,403,"Forbidden",L.code,L.message);return}B.set(n,C.principal),_(n,l,f)},"tcpOnUpgrade"),h=o(n=>{A({event:"api.principal.failed",level:"error",error:n instanceof Error?n:new Error(String(n))})},"failed"),E=o((n,l)=>{p(n,l).catch(f=>{h(f),l.headersSent?l.destroy():V(l,!0)})},"listener"),T=Ut();b=T===null?ie(E):Be(T,E),b.on("upgrade",(n,l,f)=>{x(l),O(n,l,f).catch(g=>{h(g),y(l,401,"Unauthorized",P.code,P.message)})}),Oe(b),b.once("listening",()=>{const n=b?.address();if(n!==null&&typeof n=="object"){const{address:l,port:f}=n;r=Et(l,f),l!=="0.0.0.0"&&l!=="::"&&dr(r)}}),b.listen(t.port,t.host)}}let oe=!1;return{ready:Ie,tcpAddress:o(()=>r,"tcpAddress"),close:o(async(t={})=>{if(!oe){oe=!0,ve(null),wr.close(),await Promise.all([Ue(D,U,t.graceMs),b!==void 0?Ue(b,U,t.graceMs):Promise.resolve()]);try{G(d)&&ae(d)}catch{}}},"close")}}o(So,"createApiServer");export{vt as buildRouter,Ue as closeServer,So as createApiServer,F as socketPrincipal};
|
|
@@ -11,9 +11,10 @@ export declare function cachedBrokerNodeFields(node: BrokerExtensionNodeDTO): Br
|
|
|
11
11
|
* (D39): a grant id, run or node id, structured request, queue, limit, or environment object. `fault_retry` carries a node id: the
|
|
12
12
|
* fault-retry backstop publishes it in the commit that claims the nudge, and the API process holding that node's stream turns it
|
|
13
13
|
* into a `fault-retry` line. `machine` carries a machine environment object id (a call is pending for the API process holding its link);
|
|
14
|
-
* `machine_call` carries a call id (the caller waiting on it re-reads the row).
|
|
14
|
+
* `machine_call` carries a call id (the caller waiting on it re-reads the row). `document` carries a document object id: it was edited or
|
|
15
|
+
* deleted, and a browser document stream re-reads it. The writers fire them (the
|
|
15
16
|
* schema's triggers, or the unit that owns the writer); the bus only delivers. */
|
|
16
|
-
export declare const BROKER_SIGNAL_KINDS: readonly ["mail", "node", "grant", "run_event", "report", "structured_request", "queue", "spend_limits", "environment_image", "fault_retry", "settings", "machine", "machine_call"];
|
|
17
|
+
export declare const BROKER_SIGNAL_KINDS: readonly ["mail", "node", "grant", "run_event", "report", "structured_request", "queue", "spend_limits", "environment_image", "fault_retry", "settings", "machine", "machine_call", "document"];
|
|
17
18
|
export type BrokerSignalKind = (typeof BROKER_SIGNAL_KINDS)[number];
|
|
18
19
|
export type BrokerSignalSubscriber = (id: string, kind: BrokerSignalKind) => void;
|
|
19
20
|
export interface BrokerSignalSubscription {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var h=Object.defineProperty;var r=(i,e)=>h(i,"name",{value:e,configurable:!0});import d from"pg";const a=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent","situational_card"],l=r(i=>i==="review_binding_json"?"review_binding":i==="persona_ack_json"?"persona_ack":i,"nodeField");function p(i){const e={};for(const n of a){if(n==="situational_card")continue;const t=l(n);e[t]=i[t]}return e}r(p,"cachedBrokerNodeFields");const u=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call"],f=new Set(u);class k{static{r(this,"BrokerSignalBus")}dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){const t={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(t),this.listener!==void 0&&t.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(t)&&this.callListenStart(t)}),()=>{this.subscribers.delete(t)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){const t=`${e}:${n}`;this.dirty.has(t)||this.dirty.set(t,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;const e=[...this.dirty.values()];this.dirty.clear();for(const{id:n,kind:t}of e)for(const s of this.subscribers)if(s.kinds.has(t))try{s.listener(n,t)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){const e=new d.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",t=>{const s=t.payload??"",c=s.indexOf(":");if(c<0)return;const o=s.slice(0,c);f.has(o)&&this.mark(o,s.slice(c+1))});const n=r(()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())},"lost");e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(t){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),t}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(const t of[...this.subscribers])this.callListenStart(t)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let t;const s=new Promise((c,o)=>{t=setTimeout(()=>o(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),s]).catch(()=>n()).finally(()=>clearTimeout(t))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();const e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}}const b=new k;export{u as BROKER_SIGNAL_KINDS,a as BROKER_SIGNAL_NODE_COLUMNS,k as BrokerSignalBus,b as brokerSignalBus,p as cachedBrokerNodeFields};
|
|
1
|
+
var h=Object.defineProperty;var r=(i,e)=>h(i,"name",{value:e,configurable:!0});import d from"pg";const a=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent","situational_card"],l=r(i=>i==="review_binding_json"?"review_binding":i==="persona_ack_json"?"persona_ack":i,"nodeField");function p(i){const e={};for(const n of a){if(n==="situational_card")continue;const t=l(n);e[t]=i[t]}return e}r(p,"cachedBrokerNodeFields");const u=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document"],f=new Set(u);class k{static{r(this,"BrokerSignalBus")}dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){const t={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(t),this.listener!==void 0&&t.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(t)&&this.callListenStart(t)}),()=>{this.subscribers.delete(t)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){const t=`${e}:${n}`;this.dirty.has(t)||this.dirty.set(t,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;const e=[...this.dirty.values()];this.dirty.clear();for(const{id:n,kind:t}of e)for(const s of this.subscribers)if(s.kinds.has(t))try{s.listener(n,t)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){const e=new d.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",t=>{const s=t.payload??"",c=s.indexOf(":");if(c<0)return;const o=s.slice(0,c);f.has(o)&&this.mark(o,s.slice(c+1))});const n=r(()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())},"lost");e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(t){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),t}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(const t of[...this.subscribers])this.callListenStart(t)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let t;const s=new Promise((c,o)=>{t=setTimeout(()=>o(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),s]).catch(()=>n()).finally(()=>clearTimeout(t))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();const e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}}const b=new k;export{u as BROKER_SIGNAL_KINDS,a as BROKER_SIGNAL_NODE_COLUMNS,k as BrokerSignalBus,b as brokerSignalBus,p as cachedBrokerNodeFields};
|