@hallohuman/hightea 0.1.30 → 0.1.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +5 -0
- package/dist/bin.js +24 -362
- package/dist/chunk-19pwmgzg.js +5 -0
- package/dist/chunk-5s85pw9m.js +13 -0
- package/dist/chunk-5zb06f9b.js +2 -0
- package/dist/chunk-69dva4cx.js +58 -0
- package/dist/chunk-8rbp82rh.js +139 -0
- package/dist/chunk-8x5daqht.js +1 -0
- package/dist/chunk-9pv1nvfv.js +5 -0
- package/dist/chunk-db8mr7mp.js +1 -0
- package/dist/chunk-dkzzzkex.js +13 -0
- package/dist/chunk-f04t1q6v.js +2 -0
- package/dist/chunk-gcqhggbh.js +1 -0
- package/dist/chunk-jdzvh3gk.js +1 -0
- package/dist/chunk-p616vcdm.js +4 -0
- package/dist/chunk-r9yjtfhp.js +5 -0
- package/dist/chunk-xj3c5jgm.js +5 -0
- package/dist/chunk-xy8j3npr.js +1 -0
- package/dist/plugin/plugin.json +1 -1
- package/dist/plugin/plugin.mjs +51 -15364
- package/package.json +2 -1
- package/dist/chunk-0ab6h39c.js +0 -402
- package/dist/chunk-0r70ekxd.js +0 -8
- package/dist/chunk-13tpn1g6.js +0 -465
- package/dist/chunk-3rgfnt23.js +0 -16
- package/dist/chunk-5mezgvms.js +0 -139
- package/dist/chunk-9e325ntw.js +0 -89
- package/dist/chunk-cx3yvvkz.js +0 -7295
- package/dist/chunk-d5h204vj.js +0 -14
- package/dist/chunk-dvnzt54t.js +0 -7168
- package/dist/chunk-dvt4hb8z.js +0 -1491
- package/dist/chunk-gk8tyqac.js +0 -184
- package/dist/chunk-h8pdqn31.js +0 -157
- package/dist/chunk-ph04jess.js +0 -17
- package/dist/chunk-sbqmqp8e.js +0 -123
- package/dist/chunk-w0ebwtch.js +0 -161
- package/dist/chunk-y5r2yxx1.js +0 -347
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import"./chunk-r9yjtfhp.js";import{t,e}from"./chunk-xj3c5jgm.js";var k=`hightea service list (--host HOST --origin URL --workspace SLUG | --local [--host HOST]) [--json]
|
|
2
|
+
`+`hightea service add|change NAME [--command CMD] [--cwd DIR] [--patch JSON] (--host … | --local)
|
|
3
|
+
`+`hightea service remove|start|stop|restart NAME (--host … | --local)
|
|
4
|
+
`+`hightea service logs NAME [--limit N] [--end N] (--host … | --local)
|
|
5
|
+
`+`hightea service acknowledge (--host … | --local)
|
|
6
|
+
`+`hightea service backup --host HOST --origin URL --workspace SLUG [--json]
|
|
7
|
+
hightea service restore [NAME...] --from OLD_HOST (--host NEW_HOST | --local) --origin URL --workspace SLUG [--yes] [--json]
|
|
8
|
+
hightea service enable|disable [--host HOST] (run on the machine)`,O=(n)=>typeof n==="object"&&n!==null&&!Array.isArray(n)&&typeof n.ok==="boolean"?n:void 0;function A(n,o){let r=encodeURIComponent((n.host??"").trim()),m=async(s,i,a,f)=>{let l=await e(n,o,{method:s,path:`/hosts/${r}/services${i}`,what:a,label:"SERVICE",...f===void 0?{}:{body:f}});if("error"in l){let u=O(l.body?.answer);return u===void 0?l:{answer:u}}let g=O(l.answer.answer);return g===void 0?{exit:1,error:`SERVICE_ANSWER_INVALID: ${a} answered without the host's answer: ${JSON.stringify(l.answer).slice(0,300)}`}:{answer:g}},c=(s)=>`/${encodeURIComponent(s)}`;return{machine:(n.host??"").trim(),list:()=>m("GET","","list"),put:(s)=>m("PUT",c(String(s.service.name)),"put",s),remove:(s)=>m("DELETE",c(s.name),"remove",{ifVersion:s.ifVersion}),control:(s,i)=>m("POST",`${c(s)}/${i}`,i),logs:(s)=>{let i=new URLSearchParams;if(s.end!==void 0)i.set("end",String(s.end));if(s.limit!==void 0)i.set("limit",String(s.limit));let a=i.size===0?"":`?${i}`;return m("GET",`${c(s.name)}/logs${a}`,"logs")},acknowledge:(s)=>m("POST","/acknowledge","acknowledge",s)}}async function T(n){let{localHost:o}=await import("./chunk-xy8j3npr.js"),r=await o(n.host);if("error"in r)return r;let{localServices:m,LOG_LINES_MAX:c}=await import("@hallohuman/hightea-services"),s=m(r.configDir);if(typeof s==="string")return{error:`SERVICE_NOT_CONFIGURED: ${s}`};let i=(a)=>({answer:a});return{machine:s.machine.name,list:async()=>i(s.list()),put:async(a)=>i(await s.put(a)),remove:async(a)=>i(await s.remove(a)),control:async(a,f)=>i(await s.control(a,f)),logs:async(a)=>i(await s.logs({name:a.name,endOffset:a.end??0,limit:Math.min(a.limit??100,c)})),acknowledge:async(a)=>i(await s.acknowledge(a))}}async function L(n,o,r=t(),m={}){let c=!n.local;if(c&&((n.host??"").trim()===""||n.workspace.trim()===""))return r.err(`SERVICE_INPUT: name the host with --host and --workspace, or act on this machine with --local.
|
|
9
|
+
${k}`),1;let s=o.command!=="list"&&o.command!=="acknowledge",i=o.name?.trim()??"";if(s&&i==="")return r.err(`SERVICE_INPUT: ${o.command} names one service.
|
|
10
|
+
${k}`),1;let a=c?A(n,r):await(m.local??T)(n);if("error"in a)return r.err(a.error),1;let f=(l,g)=>{if("error"in l)return r.err(l.error),l.exit;let u=l.answer;if(!u.ok){if(r.err(`${String(u.code??"SERVICE_REFUSED")}: ${String(u.message??"the machine refused")}`),typeof u.diff==="string"&&u.diff!=="")r.err(u.diff);if(n.json)r.out(JSON.stringify(u));return 1}if(n.json)r.out(JSON.stringify(u));else g(u);return 0};switch(o.command){case"list":return f(await a.list(),(l)=>r.out(C(l,a.machine)));case"start":case"stop":case"restart":return f(await a.control(i,o.command),()=>r.out(`${o.command}: ${i} on ${a.machine}`));case"logs":{let l=N(o.end,0),g=N(o.limit,1);if(l===null||g===null)return r.err("SERVICE_INPUT: --end and --limit are whole numbers of lines; --limit is at least 1"),1;let u=await a.logs({name:i,...l===void 0?{}:{end:l},...g===void 0?{}:{limit:g}});return f(u,(y)=>{r.out(`raw output from ${i} on ${a.machine}:`);for(let w of Array.isArray(y.lines)?y.lines:[])r.out(String(w))})}case"acknowledge":case"add":case"change":case"remove":{let l=await a.list();if("error"in l)return r.err(l.error),l.exit;if(!l.answer.ok)return f(l,()=>{});let g=String(l.answer.ifVersion??""),y=(Array.isArray(l.answer.services)?l.answer.services:[]).some((h)=>h.name===i);if(o.command==="acknowledge"){let h=l.answer.hashes??{};return f(await a.acknowledge({hashes:h}),()=>r.out(`acknowledged ${Object.keys(h).join(", ")||"no files"} on ${a.machine} as they are now`))}if(o.command==="remove")return f(await a.remove({name:i,ifVersion:g}),()=>r.out(`removed ${i} on ${a.machine}`));if(o.command==="add"&&y)return r.err(`SERVICE_EXISTS: ${i} is already a service on ${a.machine}; use \`hightea service change\``),1;if(o.command==="change"&&!y)return r.err(`SERVICE_NOT_FOUND: ${i} is not a service on ${a.machine}; use \`hightea service add\``),1;let w=x(i,o.fields??{});if(typeof w==="string")return r.err(`SERVICE_INPUT: ${w}`),1;if(o.command==="add"&&w.command===void 0)return r.err("SERVICE_INPUT: a new service needs --command"),1;return f(await a.put({service:w,ifVersion:g}),(h)=>r.out(h.changed===!1?`${i} on ${a.machine} already reads so; nothing was written`:`${o.command==="add"?"added":"changed"} ${i} on ${a.machine}`))}}}function x(n,o){let r={};if(o.patch!==void 0){try{r=JSON.parse(o.patch)}catch{return"--patch is a JSON object of service fields"}if(typeof r!=="object"||r===null||Array.isArray(r))return"--patch is a JSON object of service fields";if(r.name!==void 0&&r.name!==n)return"--patch names another service"}return{...r,name:n,...o.command===void 0?{}:{command:o.command},...o.cwd===void 0?{}:{cwd:o.cwd}}}function N(n,o){if(n===void 0)return;return/^\d{1,7}$/u.test(n.trim())&&Number(n)>=o?Number(n):null}function C(n,o){let r=Array.isArray(n.services)?n.services:[],m=Array.isArray(n.readOnly)?n.readOnly:[],c=r.map((s)=>{let i=Array.isArray(s.plainEnv)&&s.plainEnv.length>0?` (plain env: ${s.plainEnv.join("; ")})`:"";return`${String(s.name)} ${String(s.command??"")}${i}`});for(let s of m)c.push(`${String(s.name)} read-only: ${String(s.reason)}`);if(c.length===0)return`no services on ${o} (${String(n.file??"its file")})`;return c.join(`
|
|
11
|
+
`)}var p=(n)=>typeof n==="object"&&n!==null&&!Array.isArray(n);async function V(n,o,r){let m=await e(n,o,{method:"GET",path:`/hosts/${encodeURIComponent(r)}/services/backup`,what:"backup",label:"SERVICE"});if("error"in m)return m;let c=m.answer.backup;if(!p(c)||typeof c.label!=="string"||!p(c.listing)||!Array.isArray(c.lines))return{exit:1,error:`SERVICE_ANSWER_INVALID: backup answered without a backup: ${JSON.stringify(m.answer).slice(0,300)}`};return{backup:c}}function U(n){if(n.unreadable===!0)return`unreadable line at ${String(n.offset)} (${String(n.bytes)} bytes)`;if(n.boundary===!0)return`--- ${String(n.message)} ---`;let o=p(n.refused)?` refused ${String(n.refused.code)}`:"",r=typeof n.name==="string"&&n.name!==""?` ${n.name}`:"";return`${String(n.at??"")} ${String(n.principal??"")} ${String(n.op??"")}${r}${o}`}async function G(n,o=t()){let r=(n.host??"").trim();if(r===""||n.workspace.trim()===""||n.local)return o.err(`SERVICE_INPUT: name the host with --host and --workspace; a backup is read from Hightea, never --local.
|
|
12
|
+
${k}`),1;let m=await V(n,o,r);if("error"in m)return o.err(m.error),m.exit;let{backup:c}=m;if(n.json)return o.out(JSON.stringify(c)),0;let s=c.hostStatus==="revoked"?`revoked ${c.revokedAt??""}`.trim():c.connected?"connected":"offline";if(o.out(`${r} (${s}): ${c.label}`),typeof c.reason==="string")o.out(`last pull: ${c.reason}`);o.out(C({ok:!0,...c.listing},r)),o.out(c.lines.length===0?"no changes backed up":`changes, oldest first (${c.lines.length}):`);for(let{line:i}of c.lines)o.out(` ${U(i)}`);return 0}function j(){return{...t(),confirm:async(n)=>{let{createInterface:o}=await import("node:readline/promises"),r=o({input:process.stdin,output:process.stderr});try{return/^y(es)?$/iu.test((await r.question(n)).trim())}finally{r.close()}}}}async function J(n,o,r=j(),m={}){let c=o.from.trim(),s=(n.host??"").trim();if(c===""||n.workspace.trim()===""||!n.local&&s==="")return r.err(`SERVICE_INPUT: restore names the old host with --from, the workspace with --workspace, and the new host with --host or --local.
|
|
13
|
+
${k}`),1;let i=await V(n,r,c);if("error"in i)return r.err(i.error),i.exit;let{backup:a}=i,f=Array.isArray(a.listing.services)?a.listing.services.filter(p):[],l=o.names.filter((d)=>!f.some((S)=>S.name===d));if(l.length>0)return r.err(`SERVICE_NOT_IN_BACKUP: ${l.join(", ")} ${l.length===1?"is":"are"} not in ${c}'s backup (${a.label}); it holds ${f.map((d)=>String(d.name)).join(", ")||"no services"}`),1;let g=o.names.length===0?f:f.filter((d)=>o.names.includes(String(d.name)));if(g.length===0)return r.err(`SERVICE_NOTHING_TO_RESTORE: ${c}'s backup (${a.label}) holds no services`),1;let u=n.local?await(m.local??T)(n):A(n,r);if("error"in u)return r.err(u.error),1;let y=(d)=>p(d.env)?Object.entries(d.env).map(([S,v])=>`${S} (${String(p(v)?v.$secret:v)})`):[],w=(d)=>Array.isArray(d.plainEnv)?d.plainEnv.map(String):[];r.err(`restore from ${c} (${a.label}) to ${u.machine}, create only:`);for(let d of g){r.err(` ${String(d.name)} ${String(d.command??"")}`);let S=y(d);if(S.length>0)r.err(` secrets to enter again on ${u.machine}: ${S.join(", ")}`)}if(!o.yes&&!await r.confirm(`create ${g.length} service${g.length===1?"":"s"} on ${u.machine}? [y/N] `))return r.err("SERVICE_RESTORE_DECLINED: nothing was sent"),1;let h=[];for(let d of g){let{plainEnv:S,...v}=d,R=String(d.name),b=y(d),I=w(d),E=await u.put({service:v,ifVersion:"absent"});if("error"in E){let[_="SERVICE_FAILED",...P]=E.error.split(": ");h.push({name:R,outcome:"failed",code:_,message:P.join(": "),secrets:b,plainEnv:I})}else if(!E.answer.ok)h.push({name:R,outcome:"refused",code:String(E.answer.code??"SERVICE_REFUSED"),message:String(E.answer.message??""),secrets:b,plainEnv:I});else h.push({name:R,outcome:"created",secrets:b,plainEnv:I})}if(n.json)r.out(JSON.stringify({from:c,to:u.machine,label:a.label,results:h}));else for(let d of h){if(r.out(d.outcome==="created"?`created ${d.name}`:`${d.outcome} ${d.name}: ${d.code}: ${d.message}`),d.outcome==="created"&&d.secrets.length>0)r.out(` secrets to enter again: ${d.secrets.join(", ")}`);if(d.outcome==="created"&&d.plainEnv.length>0)r.out(` plain values never backed up: ${d.plainEnv.join("; ")}`)}return h.every((d)=>d.outcome==="created")?0:1}export{G as serviceBackupCommand,L as serviceCommand,J as serviceRestore};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var f=(e,r)=>({kind:e,id:r}),R=(e,r)=>e!==void 0&&r!==void 0&&e.kind===r.kind&&e.id===r.id,O=(e)=>`${e.kind}:${e.id}`;function j(e,r){if(e.kind==="agent")throw Error(`${r}: a person must grant this; agent ${e.id} cannot`)}var C="source",k="x-hh/source",L=["command","cwd","env","schedule","restart","depends_on","health"],_=(e)=>({command:e.command,cwd:e.cwd,env:e.env,schedule:e.schedule,restart:e.restart,depends_on:e.depends_on,health:e.health}),h=(e)=>{if(e===void 0)return"undefined";if(Array.isArray(e))return`[${e.map(h).join(",")}]`;if(e!==null&&typeof e==="object")return`{${Object.keys(e).sort().map((n)=>`${JSON.stringify(n)}:${h(e[n])}`).join(",")}}`;return JSON.stringify(e)},F=(e,r)=>{let n=_(e),o=_(r);return L.filter((s)=>h(n[s])!==h(o[s]))},H="x-hh-services://",A=(e,r,n)=>e.call("x-ahpd/invokeOperation",{channel:H,operationId:r,...n}),U=async(e)=>{let r=await e.call("subscribe",{channel:H});await e.call("unsubscribe",{channel:H});let n=r?.snapshot?.state;if(typeof n?.error==="string")throw Error(`the machine's services could not be read: ${n.error}`);if(n===void 0||!Array.isArray(n.rows))throw Error("the services channel answered no rows");let o=n.rows;return{services:o.flatMap((s)=>s.record===void 0?[]:[W(s.record,s.state)]),readOnly:o.flatMap((s)=>s.readOnly===void 0?[]:[{name:s.name,reason:s.readOnly}]),capabilities:n.capabilities,ifVersion:n.ifVersion,...typeof n.file==="string"?{file:n.file}:{}}},W=(e,r)=>{if(!p(r)||typeof r.status!=="string")return e;return{...e,state:{status:r.status,...typeof r.why==="string"?{why:r.why}:{}}}},P="x-hh-deploys://";async function w(e,r){if(typeof r?.service!=="string"||r.service.trim()==="")throw Error("deployService: service is a non-empty name");if(typeof r?.version!=="string"||r.version.trim()==="")throw Error("deployService: version is a branch, a tag or a commit sha");let n=await e.call("x-ahpd/invokeOperation",{channel:P,operationId:"deploy",target:{id:r.service},input:{service:r.service,version:r.version}});if(!p(n))throw Error(`the deploys channel answered no record: ${JSON.stringify(n)}`);if(n.ok===!0){let{service:a,sha:y,deployId:l}=n;if(typeof a!=="string"||typeof y!=="string"||typeof l!=="string"||n.state!=="started")throw Error(`the deploys channel answered a start without service, sha, deployId and state: ${JSON.stringify(n)}`);return{ok:!0,service:a,sha:y,deployId:l,state:"started"}}let{code:o,message:s}=n;if(n.ok===!1&&typeof o==="string"&&o!==""&&typeof s==="string")return{ok:!1,code:o,message:s};throw Error(`the deploys channel answered neither a start nor a named refusal: ${JSON.stringify(n)}`)}var G=(e)=>{if(!p(e))return;let{service:r,deployId:n,state:o}=e;if(typeof r!=="string"||typeof n!=="string"||typeof o!=="string")return;let{step:s,from:a,to:y,at:l,last:c}=e,t=p(c)&&typeof c.reason==="string"?c.reason:void 0,d=p(c)&&(c.exit===null||typeof c.exit==="number")?c.exit:void 0;return{service:r,deployId:n,state:o,...typeof s==="string"?{step:s}:{},...a===null||typeof a==="string"?{from:a}:{},...typeof y==="string"?{to:y}:{},...typeof l==="string"?{at:l}:{},...t===void 0?{}:{reason:t},...d===void 0?{}:{exit:d}}};async function S(e){let r=await e.call("subscribe",{channel:P});await e.call("unsubscribe",{channel:P});let n=r?.snapshot?.state;if(n===void 0)throw Error("the deploys channel answered no state");let o=Array.isArray(n.runs)?n.runs.flatMap((y)=>{let l=G(y);return l===void 0?[]:[l]}):[],s=typeof n.machine==="string"?n.machine:"",a=typeof n.error==="string"?n.error:void 0;return{machine:s,runs:o,...a===void 0?{}:{error:a}}}async function E(e,r,n){let o=z(e);return{...(e.services===void 0?void 0:await Y(e.services,r,n))??{create:[],change:[],unchanged:[],readOnly:[],remove:[],keep:[],unmanaged:[]},...e.agents===void 0?{}:{agents:await ne(e.agents,r,n)},...o.length===0?{}:{hosts:await q(o,n)}}}async function Y(e,r,n){let o=await U(r),s=o.capabilities?.fields??[];if(!s.includes(C))throw Error(`this machine's services driver records no "${C}" (its fields are ${s.join(", ")}); it cannot say which client wrote an entry, so nothing is written`);let a=new Map(o.services.map((u)=>[u.name,u])),y=new Map(o.readOnly.map((u)=>[u.name,u.reason])),l=[],c=[],t=[],d=new Set;for(let u of e){d.add(u.name);let v=a.get(u.name);if(y.has(u.name))throw Error(`${u.name} is read-only on this machine: ${y.get(u.name)??""}`);if(v===void 0)l.push(u);else{let N=F(v,u);if(N.length===0)t.push(u.name);else c.push({name:u.name,before:v,after:u,changed:N})}}let g=n.prune===!0?o.services.filter((u)=>R(u.source,n.source)&&!d.has(u.name)):[];if(g.length>0&&n.removal===void 0){let u=g.map((v)=>`${v.name} (${v.state?.status??"state unknown"})`).join(", ");throw Error(`prune would remove ${u}: pass stop (stop each program, then remove the entry) or keep (leave it running here and clear its source)`)}let m=n.removal==="stop"?g:[],x=n.removal==="keep"?g:[],V=n.prune===!0?o.services.filter((u)=>!R(u.source,n.source)&&!d.has(u.name)):[];return{ifVersion:o.ifVersion,create:l,change:c,unchanged:t,readOnly:o.readOnly,remove:m,keep:x,unmanaged:V}}function z(e){let r=e.hosts;if(r===void 0)return[];if(!Array.isArray(r))throw Error("the plan's hosts is not a list: a host entry is {name, agents}");let n=new Set;return r.map((o,s)=>{if(!p(o))throw Error(`host entry ${s+1} is not an object: a host entry is {name, agents}`);let a=o.name;if(typeof a!=="string"||a.trim().length===0)throw Error(`host entry ${s+1} names no machine: every host entry needs a non-empty "name"`);let y=Object.keys(o).filter((c)=>c!=="name"&&c!=="agents");if(y.length>0)throw Error(`host entry ${a}: unknown ${y.length===1?"field":"fields"} ${y.join(", ")} (a host entry is {name, agents})`);if(n.has(a))throw Error(`${a} is named twice in one plan`);n.add(a);let l=o.agents;if(l!==void 0&&(!Array.isArray(l)||!l.every((c)=>typeof c==="string"&&c.length>0&&c.length<=256)))throw Error(`host entry ${a}: agents must be a list of agent member ids`);return l===void 0?{name:a}:{name:a,agents:l}})}function K(e,r){let n=r.hostJoin;if(n!==void 0)return n;let o=e.map((s)=>`host:${s.name}`).join(", ");throw Error(`host entries need a workspace to mint their join links and this apply has none: ${o}. Nothing is sent and no host is created from a plan: run it with the workspace's origin and slug, signed in as a person, or take the hosts out of the plan.`)}async function q(e,r){j(r.source.kind==="agent"?{kind:"agent",id:r.source.id}:{kind:"person",id:r.source.id},"host-join"),K(e,r);let n=e.map((o)=>({name:o.name,agents:[...o.agents??[]]}));if(r.prune!==!0)return{pending:n};return{pending:n,pruneNote:"host links are not pruned; each unconsumed link expires on its own, and its expiry is printed when it is minted"}}var M="x-ahpd-agents://",B=["engine","owner","name","description","tags","model"],p=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),Q=(e,r)=>{let n=r[k];if(n===void 0)return;if(!p(n))throw Error(`${e}: config.${k} is not a source ({kind, id})`);let{kind:o,id:s}=n;if(o!=="file"&&o!=="program"&&o!=="agent"&&o!=="ci")throw Error(`${e}: config.${k}.kind is not one of file, program, agent, ci`);if(typeof s!=="string"||s==="")throw Error(`${e}: config.${k}.id is empty`);return{kind:o,id:s}},X=(e)=>{if(!p(e))throw Error("the agents channel answered an entry that is not an object");let r=p(e.record)?e.record:e,n=e.id;if(typeof n!=="string"||n==="")throw Error("the agents channel answered a record that names no id");let o=typeof r.revision==="number"&&Number.isInteger(r.revision)&&r.revision>=0?r.revision:void 0,s=p(r.config)?r.config:{},a=Q(n,s);return{id:n,...o===void 0?{}:{revision:o},record:r,...a===void 0?{}:{source:a}}};async function Z(e){let r=await e.call("subscribe",{channel:M});await e.call("unsubscribe",{channel:M});let n=r?.snapshot?.state,o=p(n)?n.records:void 0;if(!Array.isArray(o))throw Error("the agents channel answered no records");return o.map(X)}var J=(e)=>({engine:e.engine,owner:e.owner,name:e.name,...e.description===void 0?{}:{description:e.description},...e.tags===void 0?{}:{tags:e.tags},...e.model===void 0?{}:{model:e.model}}),D=(e)=>Object.fromEntries(Object.entries(e).filter(([r])=>r!==k)),ee=(e,r)=>{let n=J(r),o=B.filter((a)=>h(e.record[a])!==h(n[a])),s=p(e.record.config)?e.record.config:{};if(h(D(s))!==h(D(r.config??{})))o.push("config");return o};async function ne(e,r,n){let o=await Z(r),s=new Map(o.map((d)=>[d.id,d])),a=[],y=[],l=[],c=new Set;for(let d of e){if(c.has(d.id))throw Error(`${d.id} is named twice in one plan`);c.add(d.id);let g=s.get(d.id);if(g===void 0)a.push(d);else{let m=ee(g,d);if(m.length===0)l.push(d.id);else if(g.revision===void 0)throw Error(`${d.id} has no revision on this machine; it cannot be edited from here`);else y.push({id:d.id,before:g,after:d,changed:m})}}let t=n.prune===!0?o.filter((d)=>R(d.source,n.source)&&!c.has(d.id)):[];for(let d of t)if(d.revision===void 0)throw Error(`${d.id} has no revision on this machine; it cannot be removed from here`);return{create:a,change:y,unchanged:l,remove:t}}async function T(e,r,n){let o=e.ifVersion??"",s=[],a=[];for(let t of e.hosts?.pending??[]){if(n===void 0)throw Error(`host ${t.name}: host links need a workspace to mint them and this apply has none; nothing was minted`);let d;try{d=await n.mintHostJoin(t.agents)}catch(g){throw Error(`host ${t.name} was not minted: ${g.message}`)}a.push({name:t.name,link:d})}for(let t of e.create)o=(await A(r,"put",{input:{service:t,ifVersion:"absent"}})).ifVersion??o,s.push(t.name);for(let t of e.change)o=(await A(r,"put",{input:{service:t.after,ifVersion:o}})).ifVersion??o,s.push(t.name);let y=[];for(let t of e.keep??[])o=(await A(r,"put",{input:{service:{name:t.name,source:null},ifVersion:o}})).ifVersion??o,y.push(t.name);let l=[];for(let t of e.remove??[]){if(t.state?.status.toLowerCase()==="running")await A(r,"stop",{target:{id:t.name},input:{}});o=(await A(r,"remove",{target:{id:t.name},input:{ifVersion:o}})).ifVersion??o,l.push(t.name)}if(e.agents!==void 0){for(let t of e.agents.create)await I(r,t,0),s.push(`agent:${t.id}`);for(let t of e.agents.change){if(t.before.revision===void 0)throw Error(`${t.id} has no revision on this machine; it cannot be edited from here`);await I(r,t.after,t.before.revision),s.push(`agent:${t.id}`)}for(let t of e.agents.remove){if(t.revision===void 0)throw Error(`${t.id} has no revision on this machine; it cannot be removed from here`);await re(r,t.id,t.revision),l.push(`agent:${t.id}`)}}let c=e.hosts?.pruneNote===void 0?void 0:a.length===0?"host links are not pruned; this apply minted none, so nothing of its own is outstanding":`host links are not pruned; unconsumed ones expire at ${a.map((t)=>t.link.expiresAt).sort()[0]}`;return{preview:e,written:s,removed:l,kept:y,...e.hosts===void 0?{}:{hostLinks:a},...c===void 0?{}:{hostNote:c}}}var I=(e,r,n)=>e.call("x-ahpd/agents/put",{id:r.id,...J(r),config:{...r.config,[k]:r.source},ifRevision:n}),re=(e,r,n)=>e.call("x-ahpd/agents/remove",{id:r,ifRevision:n});function b(e){let r=[];for(let n of e.create)r.push(`+ ${n.name}`);for(let n of e.change)r.push(`~ ${n.name} (${n.changed.join(", ")})`);for(let n of e.remove??[]){let o=n.state?.status.toLowerCase()==="running";r.push(`- ${n.name} (${o?"stop, then remove":"remove"}; source ${O(n.source)})`)}for(let n of e.keep??[])r.push(`= ${n.name} (kept: left running here, source cleared)`);for(let n of e.unmanaged??[]){let o=n.source===void 0?"no source":`source ${O(n.source)}`;r.push(`? ${n.name} (not managed by this apply: ${o})`)}for(let n of e.unchanged)r.push(`= ${n}`);for(let n of e.readOnly)r.push(`! ${n.name} read-only: ${n.reason}`);if(e.hosts!==void 0){for(let n of e.hosts.pending){let o=n.agents.length===0?"no agents":`agents ${n.agents.join(",")}`;r.push(`+ host:${n.name} (pending link: the machine must join; ${o})`)}if(e.hosts.pruneNote!==void 0)r.push(`note: ${e.hosts.pruneNote}`)}if(e.agents!==void 0){for(let n of e.agents.create)r.push(`+ agent:${n.id}`);for(let n of e.agents.change)r.push(`~ agent:${n.id} (${n.changed.join(", ")})`);for(let n of e.agents.remove)r.push(`- agent:${n.id} (source ${n.source===void 0?"unknown":O(n.source)})`);for(let n of e.agents.unchanged)r.push(`= agent:${n}`)}return r}import oe from"ws";async function i(e,r){let n=r.token===void 0?e:`${e}${e.includes("?")?"&":"?"}tkn=${encodeURIComponent(r.token)}`,o=new oe(n),s=new Map,a,y=0;o.on("message",(c)=>{let t=JSON.parse(String(c));if(t.id!==void 0&&t.method===void 0)s.get(t.id)?.(t)}),o.on("close",(c,t)=>{a=`${String(c)} ${t.toString()}`;for(let d of s.values())d({error:{code:0,message:`closed: ${a}`}})}),await new Promise((c,t)=>{o.once("open",()=>c()),o.once("error",(d)=>t(d))});let l=(c,t)=>new Promise((d,g)=>{if(a!==void 0)return g(Error(`the machine's connection closed: ${a}`));let m=++y;s.set(m,(x)=>{if(x.error!==void 0)g(Error(x.error.message));else d(x.result)}),o.send(JSON.stringify({jsonrpc:"2.0",id:m,method:c,params:t}))});return await l("initialize",{channel:"ahp-root://",protocolVersions:["1.1.0"],clientId:r.clientId}),{call:l,close:()=>o.close()}}
|
|
2
|
+
export{f,w,S,E,T,b,i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./chunk-69dva4cx.js";import{r,n}from"./chunk-9pv1nvfv.js";import{p}from"./chunk-5zb06f9b.js";var k='That code is not waiting here. It may have expired, or already have been used. On the browser, press "Approve this browser" again for a new code.';async function E(e){let{createInterface:t}=await import("node:readline/promises"),o=t({input:process.stdin,output:process.stderr});try{return/^y(es)?$/iu.test((await o.question(e)).trim())}finally{o.close()}}function c(e){return typeof e==="string"?e:""}async function v(e){try{let t=await e.json();return typeof t==="object"&&t!==null?t:null}catch{return null}}function P(e,t){let o=e?.error;if(typeof o==="object"&&o!==null){let s=o,g=c(s.code),l=c(s.message);if(g!==""&&l!=="")return`${g}: ${l}`;if(l!=="")return l}return`the deployment answered ${String(t)}`}async function D(e,t={localHost:(o)=>n(o),trust:(o)=>p(o),confirm:E,fetch:(o,s)=>fetch(o,s)}){let o=await t.localHost(e.host);if("error"in o)return console.error(o.error.replace(/^SERVICE_/u,"APPROVE_")),1;let s=(e.origin??o.gateway??"").trim().replace(/\/+$/u,"");if(s==="")return console.error(`APPROVE_ORIGIN_UNKNOWN: this machine's claim for host ${o.hostId} records no deployment address; name it with --origin <url> and the workspace with --workspace <slug>; nothing was approved`),1;let g=(e.workspace??o.workspaceId).trim();if(g==="")return console.error("APPROVE_WORKSPACE_UNKNOWN: no workspace slug to ask about; name it with --workspace <slug>; nothing was approved"),1;let l=e.code.trim();if(l==="")return console.error("APPROVE_CODE_MISSING: give the code the browser shows, e.g. `hightea approve 7QK4-2M8X`; nothing was approved"),1;let b=`${s}/api/ws/${encodeURIComponent(g)}/browser-approval/${encodeURIComponent(l)}`,u;try{u=await t.fetch(b,{headers:{accept:"application/json"},redirect:"error"})}catch(d){return console.error(`APPROVE_UNREACHABLE: could not reach ${s} (${d.message}); nothing was approved`),1}if(u.status===404)return console.error(k),1;let a=await v(u);if(a===null)return console.error(`APPROVE_ANSWER_INVALID: ${s} answered ${String(u.status)} without a JSON body; nothing was approved`),1;if(u.status!==200)return console.error(`APPROVE_REFUSED: ${P(a,u.status)}; nothing was approved`),1;let f=c(a.state);if(f==="approved")return console.error(k),1;if(f!=="pending")return console.error(`APPROVE_ANSWER_INVALID: ${s} answered a state this command does not know (${JSON.stringify(f)}); nothing was approved`),1;let i=c(a.browser).trim(),A=c(a.check).trim(),R=c(a.publicKey),h=c(a.personName).trim(),N=c(a.expiresAt),y=r(R);if(i===""||A===""||"error"in y)return console.error("APPROVE_ANSWER_INVALID: the deployment's answer names no browser and check characters, or carries no usable public key; nothing was approved"),1;let w=e.json===!0?(d)=>console.error(d):(d)=>console.log(d);if(w("Approve this browser?"),w(""),w(` ${i}`),w(` Check that your browser shows ${A}.`),w(h===""?" For: the person who asked on that browser":` For: ${h}, to ask this computer's agents`),w(""),!await t.confirm("Type y to approve, anything else to cancel: "))return console.error("Nothing was approved. The code is still waiting until it expires."),1;if(await t.trust({action:"add",name:i,publicKey:R,quiet:!0,...h===""?{}:{personName:h},...e.host===void 0?{}:{host:e.host},...e.configDir===void 0?{}:{configDir:e.configDir}})!==0)return console.error("Nothing was approved on the browser side; the code is still waiting."),1;let I=`${b}/approved`,m;try{m=await t.fetch(I,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({keyFingerprint:y.keyId}),redirect:"error"})}catch(d){return console.error(`APPROVE_NOT_MARKED: this computer now trusts ${i}, but ${s} could not be told (${d.message}). The browser keeps waiting; press "Approve this browser" again for a new code.`),1}if(m.status!==204)return console.error(`APPROVE_NOT_MARKED: this computer now trusts ${i}, but the deployment did not mark the code spent (${P(await v(m),m.status)}). The browser keeps waiting; press "Approve this browser" again for a new code.`),1;if(e.json===!0)return console.log(JSON.stringify({approved:!0,browser:i,keyId:y.keyId,personName:h===""?null:h,expiresAt:N})),0;return console.log(`Approved. ${i} can ask this computer's agents from now on.`),console.log(`Remove it later: hightea browsers remove "${i}"`),0}export{D as hostApprove};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s,_,C,L,P}from"./chunk-r9yjtfhp.js";export{C as authLogin,P as authLogout,L as authStatus,s as checkedOrigin,_ as ensureCredential};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{w,S,i}from"./chunk-f04t1q6v.js";import"./chunk-69dva4cx.js";import{o}from"./chunk-9pv1nvfv.js";import{readFile as D}from"node:fs/promises";import{join as E}from"node:path";var h=`hightea deploy <service> --pin <sha> [--host <id>] [--json]
|
|
2
|
+
hightea deploy status <service> [--host <id>] [--json]`,O=/^[0-9a-fA-F]{40}$/u,y=()=>({out:(e)=>console.log(e),err:(e)=>console.error(e)}),P=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),u=(e)=>e.hostIds.length>0?`${e.hostIds.join(",")} (pid ${String(e.pid)})`:`pid ${String(e.pid)}`;async function _(e,n){if(e.port!==void 0)return e.port;try{let a=JSON.parse(await n(e.config));if(P(a)&&typeof a.port==="number"&&Number.isInteger(a.port))return a.port}catch{return}return}async function N(e,n){let a=e.connectionTokenFile??E(e.configDir,"connection.token");try{return(await n(a)).trim()||void 0}catch{return}}async function f(e,n={}){let a=n.readFile??((t)=>D(t,"utf8")),d;try{d=await(n.runningAhpds??o)()}catch(t){return{error:`DEPLOY_NO_AHPD: the process table could not be read: ${t.message}`}}let l=e?.trim(),r;if(l!==void 0&&l!==""){let t=d.filter((p)=>p.hostIds.includes(l));if(t.length===0)return{error:`DEPLOY_NO_AHPD: no running ahpd on this machine serves host ${l} (running: ${d.map(u).join("; ")||"none"})`};if(t.length>1)return{error:`DEPLOY_NO_AHPD: ${String(t.length)} running ahpds serve host ${l} (${t.map(u).join("; ")}); the process table cannot tell them apart`};r=t[0]}else{if(d.length===0)return{error:"DEPLOY_NO_AHPD: no running ahpd on this machine; start one with `hightea host join` first"};if(d.length>1)return{error:`DEPLOY_NO_AHPD: this machine runs ${String(d.length)} ahpds (${d.map(u).join("; ")}); name one with --host <id>`};r=d[0]}if(r===void 0)return{error:"DEPLOY_NO_AHPD: no running ahpd on this machine"};let c=await _(r,a);if(c===void 0)return{error:`DEPLOY_NO_AHPD: ${r.config} names no port and its command line has no --port; cannot reach this ahpd`};let s=await N(r,a);return{url:`ws://${r.host??"127.0.0.1"}:${String(c)}`,...s===void 0?{}:{token:s},label:r.hostIds[0]??`pid ${String(r.pid)}`}}async function g(e,n){try{return await(n.connect??i)(e.url,{token:e.token,clientId:"hightea-deploy"})}catch(a){return{error:`DEPLOY_NO_AHPD: ${e.url} did not answer: ${a.message}`}}}var R=(e,n)=>{if(e==="RUNNING")return`DEPLOY_RUNNING: ${n}`;if(e==="UNKNOWN_SERVICE")return`DEPLOY_UNKNOWN_SERVICE: ${n}`;return`DEPLOY_REFUSED ${e}: ${n}`},m=(e)=>/No channel at x-hh-deploys:\/\//u.test(e.message)?"DEPLOY_NO_DRIVER: this ahpd has no deploy driver loaded (x-hh-deploys://); its deploy plugin is not in its configuration":`DEPLOY_DRIVER_UNREADABLE: ${e.message}`;async function x(e,n=y(),a={}){let d=e.service.trim();if(d==="")return n.err(`DEPLOY_SERVICE_REQUIRED: name the service to deploy
|
|
3
|
+
${h}`),1;let l=e.pin.trim();if(!O.test(l))return n.err(`DEPLOY_PIN_NOT_SHA: --pin must be a full 40-character commit sha; '${l}' is not`),1;let r=await f(e.host,a);if("error"in r)return n.err(r.error),1;let c=await g(r,a);if("error"in c)return n.err(c.error),1;try{let s=await w(c,{service:d,version:l.toLowerCase()});if(!s.ok)return n.err(R(s.code,s.message)),1;if(e.json)n.out(JSON.stringify({machine:r.label,service:s.service,pin:s.sha,deployId:s.deployId,state:s.state}));else n.out(`started ${s.service} at ${s.sha}: deploy ${s.deployId} on ${r.label}`);return 0}catch(s){return n.err(m(s)),1}finally{c.close()}}var I=(e,n)=>({machine:n,service:e.service,state:e.state,pin:e.to??null,from:e.from??null,...e.step===void 0?{}:{step:e.step},...e.reason===void 0?{}:{reason:e.reason},...e.exit===void 0?{}:{exit:e.exit},deployId:e.deployId,...e.at===void 0?{}:{at:e.at}});async function j(e,n=y(),a={}){let d=e.service.trim();if(d==="")return n.err(`DEPLOY_SERVICE_REQUIRED: name the service to read
|
|
4
|
+
${h}`),1;let l=await f(e.host,a);if("error"in l)return n.err(l.error),1;let r=await g(l,a);if("error"in r)return n.err(r.error),1;try{let c=await S(r),s=c.runs.filter((p)=>p.service===d);if(s.length===0){let p=c.error===void 0?"":` (${c.error})`;return n.err(`DEPLOY_UNKNOWN_SERVICE: ${d} has no deploy on ${c.machine||l.label}${p}`),1}let t=I(s[0],c.machine||l.label);if(e.json)n.out(JSON.stringify(t));else n.out(`${t.state} ${t.service} pin ${t.pin??"?"} ${t.step===void 0?"":`${t.step} `}deploy ${t.deployId}${t.reason===void 0?"":` last error: ${t.reason}`}`);return 0}catch(c){return n.err(m(c)),1}finally{r.close()}}export{x as deployPlace,j as deployStatus};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{chmod as j,mkdir as J,readFile as M,rename as V,rm as B,stat as G,writeFile as W}from"node:fs/promises";import{spawn as X}from"node:child_process";import{randomUUID as z}from"node:crypto";import{homedir as Z}from"node:os";import{join as k}from"node:path";function U(r){return r.replace(/\brt_[A-Za-z0-9_-]+/g,"[redacted-refresh-token]").replace(/\bht_session=[^;\s]+/g,"ht_session=[redacted]").replace(/\b[A-Za-z0-9_-]{40,}\b/g,"[redacted-token]")}function N(){return{readFile:(r)=>M(r,"utf8"),stat:(r)=>G(r),writeFile:(r,e,n)=>W(r,e,n),mkdir:async(r,e)=>{await J(r,e)},chmod:(r,e)=>j(r,e),rename:(r,e)=>V(r,e),rm:(r,e)=>B(r,e),env:process.env,home:Z(),nowMs:()=>Date.now(),fetch:(r,e)=>globalThis.fetch(r,e),out:(r)=>{process.stdout.write(`${r}
|
|
2
|
+
`)},err:(r)=>{process.stderr.write(`${r}
|
|
3
|
+
`)},sleep:(r)=>new Promise((e)=>setTimeout(e,r)),openBrowser:async(r)=>{let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",r]:[r];try{X(e,n,{stdio:"ignore",detached:!0}).unref()}catch{}}}}function s(r,e){let n;try{n=new URL(r)}catch{return{error:`${e}_ORIGIN_INVALID: --origin must be the https deployment origin, e.g. https://hightea.dev (got ${JSON.stringify(r)}).`}}let t=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]"||n.hostname==="::1";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t)||n.pathname!=="/"||n.search!==""||n.hash!=="")return{error:`${e}_ORIGIN_INVALID: --origin must be the https deployment origin (http is allowed only on localhost), e.g. https://hightea.dev (got ${JSON.stringify(r)}).`};return{origin:n.origin}}function R(r){return r.env.XDG_CONFIG_HOME?.trim()||k(r.home,".config")}function p(r,e){return k(R(e),"hightea","credentials.json")}function l(r){return`run \`hightea auth login --origin ${r}\``}function q(r){return`0${(r&511).toString(8).padStart(3,"0")}`}async function v(r,e,n){let t=`${r}.${process.pid}.${z()}.tmp`;try{await n.writeFile(t,`${JSON.stringify(e,null,2)}
|
|
4
|
+
`,{mode:384,flag:"wx"}),await n.chmod(t,384),await n.rename(t,r)}catch(o){try{await n.rm?.(t,{force:!0})}catch{}throw o}}async function Y(r,e){let n,t;try{n=await e.readFile(r),t=(await e.stat(r)).mode}catch(o){if(o.code==="ENOENT")return{error:"AUTH_NOT_SIGNED_IN"};return{error:`AUTH_CREDENTIALS_UNREADABLE: ${r} (${o.message})`}}if((t&63)!==0)return{error:`AUTH_CREDENTIALS_EXPOSED: ${r} is mode ${q(t)}; run chmod 600 ${r}.`};try{let o=JSON.parse(n);if(typeof o!=="object"||o===null||Array.isArray(o))throw SyntaxError("not an object");let i=o;if(i.version!==1||typeof i.origins!=="object"||i.origins===null||Array.isArray(i.origins))throw SyntaxError("not a version 1 credential file");return{file:i}}catch(o){return{error:`AUTH_CREDENTIALS_INVALID: ${r} (${o.message})`}}}function K(r){let e=r;return e!==null&&typeof e==="object"&&typeof e.sessionToken==="string"&&e.sessionToken.length>0&&typeof e.sessionExpiresAt==="string"&&Number.isFinite(Date.parse(e.sessionExpiresAt))&&(e.refreshToken===void 0||typeof e.refreshToken==="string")&&(e.account===void 0||typeof e.account==="object"&&e.account!==null)}async function y(r,e){let n=p(r,e),t=await Y(n,e);if("error"in t){if(t.error==="AUTH_NOT_SIGNED_IN")return{error:`${t.error}: no sign-in for ${r}; ${l(r)}.`};if(t.error.startsWith("AUTH_CREDENTIALS_INVALID"))return{error:`${t.error}; ${l(r)}.`};return{error:t.error}}let o=t.file.origins[r];if(!K(o))return{error:`AUTH_NOT_SIGNED_IN: no sign-in for ${r}; ${l(r)}.`};return{credential:o}}async function D(r,e,n){if(n.writeFile===void 0||n.mkdir===void 0||n.chmod===void 0||n.rename===void 0)return{error:"AUTH_FILESYSTEM_UNAVAILABLE: this command had no filesystem to store the credential."};let t=p(r,n),o=k(R(n),"hightea"),i={};try{let a=JSON.parse(await n.readFile(t));if(typeof a.origins==="object"&&a.origins!==null&&!Array.isArray(a.origins))i=a.origins}catch{}try{await n.mkdir(o,{recursive:!0,mode:448});let a={version:1,origins:{...i,[r]:e}};return await v(t,a,n),{ok:!0}}catch(a){return{error:`AUTH_CREDENTIALS_UNWRITABLE: ${t} (${a.message})`}}}async function Q(r,e){if(e.writeFile===void 0||e.chmod===void 0||e.rename===void 0||e.rm===void 0)return{error:"AUTH_FILESYSTEM_UNAVAILABLE: this command had no filesystem to forget the credential."};let n=p(r,e),t;try{t=JSON.parse(await e.readFile(n))}catch(i){if(i.code==="ENOENT")return{ok:!0};return{error:`AUTH_CREDENTIALS_INVALID: ${n} (${i.message}).`}}let o={...t.origins};delete o[r];try{if(Object.keys(o).length===0)await e.rm(n,{force:!0});else await v(n,{version:1,origins:o},e);return{ok:!0}}catch(i){return{error:`AUTH_CREDENTIALS_UNWRITABLE: ${n} (${i.message})`}}}async function E(r,e,n,t){let o;try{o=await r.fetch(e,{method:"POST",headers:{origin:n,"content-type":"application/json",accept:"application/json","cache-control":"no-store"},body:JSON.stringify(t)})}catch(d){return{error:`AUTH_UNREACHABLE: ${e} did not answer: ${d.message}`}}let i=await o.text(),a={};if(i.length>0)try{let d=JSON.parse(i);if(typeof d!=="object"||d===null||Array.isArray(d))throw SyntaxError("not an object");a=d}catch{return{error:`AUTH_ANSWER_INVALID: ${e} answered HTTP ${o.status} with non-JSON: ${U(i.slice(0,200))}`}}return{status:o.status,answer:a}}function I(r){let e=r.error;return{code:typeof e?.code==="string"?e.code:"HTTP_ERROR",message:U(typeof e?.message==="string"?e.message:"the deployment refused the request")}}function b(r){let{sessionToken:e,sessionExpiresAt:n,refreshToken:t,account:o}=r;if(typeof e!=="string"||e.length===0||typeof n!=="string"||!Number.isFinite(Date.parse(n))||typeof t!=="string"||t.length===0)return null;return{sessionToken:e,sessionExpiresAt:n,refreshToken:t,...o===void 0?{}:{account:o}}}async function O(r,e,n,t=!1){if(e.refreshToken===void 0||e.refreshToken.length===0)return{error:`AUTH_SESSION_EXPIRED: no refresh token for ${r}; ${l(r)}.`};let o=await E(n,`${r}/auth/cli/refresh`,r,{refreshToken:e.refreshToken,sessionToken:e.sessionToken});if("error"in o)return{error:o.error};if(o.status!==200){let d=I(o.answer);if(!t&&(o.status===401||d.code==="REFRESH_INVALID")){let c=await y(r,n);if("credential"in c&&c.credential.refreshToken!==e.refreshToken){if(Date.parse(c.credential.sessionExpiresAt)-(n.nowMs?.()??Date.now())>60000)return c;return await O(r,c.credential,n,!0)}}return{error:`AUTH_${d.code}: ${d.message} ${l(r)}`}}let i=b(o.answer);if(i===null)return{error:"AUTH_ANSWER_INVALID: the refresh answer lacked a session or refresh token."};let a=await D(r,{...i,...e.account===void 0?{}:{account:e.account}},n);if("error"in a)return a;return{credential:i}}async function _(r,e){let n=await y(r,e);if("error"in n)return n;if(Date.parse(n.credential.sessionExpiresAt)-(e.nowMs?.()??Date.now())>60000)return n;return await O(r,n.credential,e)}async function C(r,e=N()){let n=s(r.origin,"AUTH");if("error"in n)return e.err(n.error),1;let t=n.origin,o=await E(e,`${t}/auth/cli/device`,t,{});if("error"in o)return e.err(o.error),1;if(o.status!==200){let u=I(o.answer);return e.err(`AUTH_${u.code}: ${u.message}`),1}let i=o.answer.deviceCode,a=o.answer.userCode,d=o.answer.verificationUri,c=o.answer.verificationUriComplete,m=o.answer.expiresIn,w=o.answer.interval;if(typeof i!=="string"||typeof a!=="string"||typeof d!=="string"||typeof c!=="string"||typeof m!=="number"||typeof w!=="number")return e.err("AUTH_ANSWER_INVALID: the device authorization answer was malformed."),1;let A=r.json?e.err:e.out;if(A(`To sign in to ${t}, open ${d}`),A(`and confirm the code ${a}.`),r.noBrowser!==!0)A(`Opening ${c}`),await e.openBrowser(c);let x=w*1000,H=(e.nowMs?.()??Date.now())+m*1000,F=Math.max(1,Math.ceil(m/w)+1);for(let u=0;u<F;u+=1){if((e.nowMs?.()??Date.now())>=H)break;await e.sleep(x);let f=await E(e,`${t}/auth/cli/token`,t,{deviceCode:i});if("error"in f)return e.err(f.error),1;if(f.status===200){let g=b(f.answer);if(g===null)return e.err("AUTH_ANSWER_INVALID: the sign-in answer lacked a session or refresh token."),1;let S=await D(t,g,e);if("error"in S)return e.err(S.error),1;if(r.json)return e.out(JSON.stringify({origin:t,sessionExpiresAt:g.sessionExpiresAt,account:g.account??null})),0;let T=g.account?.email;return e.out(`Signed in to ${t}${typeof T==="string"&&T.length>0?` as ${T}`:""}.`),e.out(`Credential stored at ${p(t,e)} (mode 0600).`),0}let h=I(f.answer);if(h.code==="AUTHORIZATION_PENDING")continue;if(h.code==="SLOW_DOWN"){x+=5000;continue}return e.err(`AUTH_${h.code}: ${h.message}`),1}return e.err(`AUTH_EXPIRED_TOKEN: the sign-in code expired; ${l(t)}.`),1}async function L(r,e=N()){let n=s(r.origin,"AUTH");if("error"in n)return e.err(n.error),1;let t=await y(n.origin,e);if("error"in t)return e.err(t.error),1;let o=t.credential,i=Date.parse(o.sessionExpiresAt)<=(e.nowMs?.()??Date.now()),a=o.account;if(r.json)return e.out(JSON.stringify({origin:n.origin,account:a??null,sessionExpiresAt:o.sessionExpiresAt,expired:i})),0;let d=a?.email;return e.out(`Signed in to ${n.origin}${typeof d==="string"&&d.length>0?` as ${d}`:""}.`),e.out(`Session ${i?"expired":"expires"} ${o.sessionExpiresAt}${i?`; ${l(n.origin)}.`:"."}`),0}async function P(r,e=N()){let n=s(r.origin,"AUTH");if("error"in n)return e.err(n.error),1;let t=n.origin,o=await y(t,e);if("error"in o){if(o.error.startsWith("AUTH_NOT_SIGNED_IN"))return e.out(`Not signed in to ${t}; nothing to do.`),0;return e.err(o.error),1}let i=!0;try{let d=await e.fetch(`${t}/auth/logout`,{method:"POST",headers:{origin:t,cookie:`ht_session=${o.credential.sessionToken}`,accept:"application/json","cache-control":"no-store"}});i=d.ok||d.status===302}catch{i=!1}if(!i)return e.err(`AUTH_LOGOUT_FAILED: ${t} could not be told to revoke the session; the local credential was kept. Try again.`),1;let a=await Q(t,e);if("error"in a)return e.err(a.error),1;if(r.json)e.out(JSON.stringify({origin:t,signedOut:!0,revoked:i}));else e.out(`Signed out of ${t}.`);return 0}
|
|
5
|
+
export{s,_,C,L,P};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{s,_}from"./chunk-r9yjtfhp.js";import{chmod as p,mkdir as u,readFile as f,rm as I,stat as O,writeFile as N}from"node:fs/promises";import{homedir as x}from"node:os";import{join as S}from"node:path";var T=new Set(["FORBIDDEN","NOT_A_MEMBER","UNAUTHENTICATED"]);function t(){return{fetch:(r,o)=>globalThis.fetch(r,o),readFile:(r)=>f(r,"utf8"),stat:(r)=>O(r),writeFile:(r,o,n)=>N(r,o,n),mkdir:async(r,o)=>{await u(r,o)},chmod:(r,o)=>p(r,o),rm:(r,o)=>I(r,o),env:process.env,home:x(),nowMs:()=>Date.now(),out:(r)=>{process.stdout.write(`${r}
|
|
2
|
+
`)},err:(r)=>{process.stderr.write(`${r}
|
|
3
|
+
`)}}}async function k(r,o,n,c){let d=r.sessionFile?.trim()||o.env.HIGHTEA_SESSION_FILE?.trim();if(d===void 0||d===""){let i=await _(c,o);if("credential"in i)return{cookie:i.credential.sessionToken};if(i.error.startsWith("AUTH_NOT_SIGNED_IN")){let a=S(o.env.XDG_CONFIG_HOME?.trim()||S(o.home,".config"),"hightea","session"),m=await h(a,o,n);if(!("error"in m))return m;return{error:`${n}_SESSION_MISSING: ${i.error}`}}if(i.error.startsWith("AUTH_CREDENTIALS_EXPOSED"))return{error:`${n}_SESSION_EXPOSED: ${i.error}`};if(i.error.startsWith("AUTH_SESSION_EXPIRED")||i.error.startsWith("AUTH_REFRESH"))return{error:`${n}_SESSION_EXPIRED: ${i.error}`};return{error:`${n}_SESSION_INVALID: ${i.error}`}}return await h(d,o,n)}async function h(r,o,n){let c,d;try{c=await o.readFile(r),d=(await o.stat(r)).mode}catch(a){return{error:`${n}_SESSION_MISSING: no session in ${r} (${a.message}). Sign in to the deployment in a browser and write its ht_session cookie to that file, or pass --session-file.`}}if((d&63)!==0)return{error:`${n}_SESSION_EXPOSED: ${r} is mode 0${(d&511).toString(8).padStart(3,"0")}; run chmod 600 ${r}.`};let i=c.split(`
|
|
4
|
+
`).map((a)=>a.trim()).filter((a)=>a.length>0);if(i.length!==1)return{error:`${n}_SESSION_INVALID: ${r} must hold exactly one non-empty line (the ht_session cookie value); it holds ${i.length}.`};return{cookie:i[0]}}async function e(r,o,n){let c=s(r.origin,n.label);if("error"in c)return{exit:1,error:c.error};let d=await k(r,o,n.label,c.origin);if("error"in d)return{exit:1,error:d.error};let i=`${c.origin}/api/ws/${encodeURIComponent(r.workspace)}${n.path}`,a;try{a=await o.fetch(i,{method:n.method,headers:{cookie:`ht_session=${d.cookie}`,origin:c.origin,accept:"application/json","cache-control":"no-store",...n.body===void 0?{}:{"content-type":"application/json"}},...n.body===void 0?{}:{body:JSON.stringify(n.body)}})}catch(l){return{exit:1,error:`${n.label}_UNREACHABLE: ${n.what} ${n.method} ${i} did not answer: ${l.message}`}}let m=await a.text(),w={};if(m.length>0)try{let l=JSON.parse(m);if(typeof l!=="object"||l===null||Array.isArray(l))throw SyntaxError("not a JSON object");w=l}catch(l){if(!(l instanceof SyntaxError))throw l;return{exit:1,error:`${n.label}_ANSWER_INVALID: ${n.what} ${n.method} ${i} answered HTTP ${a.status} with non-JSON: ${m.slice(0,300)}`}}if(a.ok)return{answer:w};let y=w.error,g=typeof y?.code==="string"?y.code:`HTTP_${a.status}`,E=typeof y?.message==="string"?y.message:m.slice(0,300);return{exit:T.has(g)?3:n.extraExits?.[g]??1,error:`${g}: ${E}`,body:w}}
|
|
5
|
+
export{t,e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v,A,n,o,I,O}from"./chunk-9pv1nvfv.js";import"./chunk-69dva4cx.js";export{v as hostJoin,I as hostServicesGrants,A as hostStatus,O as hostUpdate,n as localHost,o as runningAhpds};
|