tmux-weblink 1.0.1 → 1.0.2

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/index.js CHANGED
@@ -3,7 +3,7 @@ import{chmodSync as $e,existsSync as K,mkdirSync as Be,readdirSync as pe,readFil
3
3
  <rect x="2.5" y="5.5" width="27" height="21" rx="4" fill="#0d1117" stroke="#7dd3fc" stroke-width="2"/>
4
4
  <path d="M8 13l4.2 3.1L8 19.2" fill="none" stroke="#7dd3fc" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>
5
5
  <line x1="15.5" y1="19.6" x2="22.5" y2="19.6" stroke="#7dd3fc" stroke-width="2.2" stroke-linecap="round"/>
6
- </svg>`,Le=e=>e.body(Ar,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"});s.get("/favicon.svg",Le),s.get("/favicon.ico",Le),s.get("/login",e=>{const r=e.req.query("setup")==="1"?!0:!l.passwordHash,n=e.req.query("error");return e.html(rt({setupMode:r,error:n?decodeURIComponent(n):void 0,theme:y}))}),s.get("/",I(),e=>{const t=p?C(v(),A()):[],r=je();return e.html(mt({theme:y,commandbarEnabled:p,commandbarSessions:t,agentsEnabled:_,fsRoots:r,terminalCfg:B,renderer:Z,scrollback:B.initialLines+2*B.historyChunk}))}),s.get("/s/:session",I(),async e=>{const t=decodeURIComponent(e.req.param("session"));await jt(t),oe(t);const r=v(),n=A(),a=p?C(r,n):[];return e.html(tt(t,de,{commandbarEnabled:p,commandbarSessions:a,quickCommands:p?se():[],agentsEnabled:_,terminal:B,theme:y,renderer:Z}))}),s.get("/notes",I(),e=>{const t=p?C(v(),A()):[];return e.html(nt(j.data.notes,y,p,t,_))}),s.get("/notes/:session",I(),e=>{const t=decodeURIComponent(e.req.param("session")),r=p?C(v(),A()):[];return e.html(ot(t,y,p,r))}),s.get("/schedule",I(),e=>{const t=p?C(v(),A()):[];return e.html(it(M.list(),M.listTriggered(),y,Oe,p,t,_))}),s.get("/agents",I(),e=>{if(!_)return e.redirect("/settings",303);const t=p?C(v(),A()):[];return e.html(dt(y,p,t))}),s.get("/history",I(),e=>{const t=v(),r=p?C(t,A()):[],n=new Set(t.map(a=>a.name));return e.html(ut(kt(),y,p,r,_,n))}),s.get("/quick-commands",I(),e=>{const t=p?C(v(),A()):[];return e.html(ct(se(),y,p,t,_))}),s.get("/files",I(),e=>{const t=p?C(v(),A()):[],r=je();return e.html(lt(y,p,t,_,r))}),s.post("/api/history/clear",i(),async e=>(await vt(),e.json({ok:!0}))),s.get("/api/quick-commands",i(),e=>e.json(se())),s.post("/api/quick-commands",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=await Qt(t);return"error"in r?e.json({error:r.error},400):e.json(r,201)}),s.patch("/api/quick-commands/:id",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=await Yt(e.req.param("id"),t);return"error"in r?e.json({error:r.error},r.status):e.json(r)}),s.delete("/api/quick-commands/:id",i(),async e=>await Xt(e.req.param("id"))?e.json({ok:!0}):e.json({error:"not found"},404)),s.get("/api/agents",i(),async e=>{if(!_)return e.json({error:"agents page disabled"},403);const t=Me?yr():await fr();return e.json(t)}),s.post("/api/auth/password",async e=>{const t=J(e),r=E.check(t);if(!r.allowed)return c("rate_limited",{ip:t,retryAfterMs:r.retryAfterMs,permanentLock:r.permanentLock}),r.permanentLock?e.json({error:"Server locked after too many failed attempts",permanentLock:!0},403):e.json({error:"Too many attempts",retryAfterMs:r.retryAfterMs},429);let n;try{n=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const a=typeof n.password=="string"?n.password:"";if(!l.passwordHash){if(!l.security.allowRemoteSetup&&!Ae(t))return c("setup_rejected_remote",{ip:t}),e.json({error:"First-run setup must be performed from localhost"},403);if(W)return e.json({error:"Password setup in progress"},409);const f=ge(a);if(f)return e.json({error:f},400);W=!0;try{l.passwordHash=await ye(a),he(l),c("password_set",{ip:t})}finally{W=!1}const{plaintext:T}=h.createAccessToken("setup",l.security.tokenTtlDays);return _e(e,T),e.json({ok:!0,token:T,setupMode:!0})}if(!await we(a,l.passwordHash)){const f=E.recordFailure(t);return c("auth_failed",{ip:t,method:"password",failures:f.failures,permanentLock:f.permanentLock}),f.permanentLock?(h.revokeAll(),c("permanent_lock",{ip:t,failures:f.failures}),e.json({error:"Server locked after too many failed attempts",permanentLock:!0},403)):f.allowed?e.json({error:"Incorrect password"},401):e.json({error:"Too many attempts",retryAfterMs:f.retryAfterMs},429)}E.recordSuccess(t);const d=`browser-${t}`,{plaintext:S}=h.createAccessToken(d,l.security.tokenTtlDays);return _e(e,S),c("auth_success",{ip:t,method:"password",tokenName:d}),e.json({ok:!0,token:S})}),s.post("/api/auth/token",i(),async e=>{const t=J(e);let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const n=typeof r.name=="string"?r.name:`api-${t}`,a=typeof r.ttlDays=="number"?r.ttlDays:l.security.tokenTtlDays,{stored:o,plaintext:d}=h.createAccessToken(n,a);return c("token_created",{ip:t,name:o.name,tokenId:o.id}),e.json({id:o.id,name:o.name,token:d,expiresAt:o.expiresAt})}),s.get("/api/auth/tokens",i(),e=>e.json(h.list().map(t=>({id:t.id,name:t.name,createdAt:t.createdAt,lastUsedAt:t.lastUsedAt,expiresAt:t.expiresAt})))),s.delete("/api/auth/tokens/:id",i(),e=>h.revoke(e.req.param("id"))?(c("token_revoked",{ip:J(e),tokenId:e.req.param("id")}),e.json({ok:!0})):e.json({error:"not found"},404)),s.post("/api/auth/logout",i(),e=>(kr(e),e.json({ok:!0}))),s.get("/settings",I(),async e=>{const t=await ne(),r=t.terminalRenderer??"xterm";return e.html(st({settings:t,renderer:Z,rendererOverridden:Z!==r,theme:y,plugins:t.plugins??[],saved:e.req.query("saved")==="1",error:e.req.query("error")?decodeURIComponent(e.req.query("error")):void 0}))}),s.post("/settings",i(),async e=>{let t;try{t=await e.req.parseBody()}catch{return e.redirect("/settings?error="+encodeURIComponent("invalid form body"),303)}const r=await ne(),n=t.terminalRenderer==="ghostty"?"ghostty":"xterm",a=t.defaultView==="recent"?"recent":"default",o=Ce(typeof t.scheduleHistoryDays=="string"?Number(t.scheduleHistoryDays):void 0);return await Lt({...r,commandbar:t.commandbar!==void 0,agents:t.agents!==void 0,agentsBackgroundWatch:t.agentsBackgroundWatch!==void 0,terminalRenderer:n,defaultView:a,scheduleHistoryDays:o}),e.redirect("/settings?saved=1",303)}),s.post("/settings/plugins",i(),async e=>{let t;try{t=await e.req.parseBody()}catch{return e.redirect("/settings?error="+encodeURIComponent("invalid form body"),303)}const r=t.action,n=typeof t.pkg=="string"?t.pkg.trim():"";if(!n)return e.redirect("/settings?error="+encodeURIComponent("missing package name"),303);const a=r==="remove"?await Ht(n):r==="add"?await Wt(n):{ok:!1,output:"unknown action"};return a.ok?e.redirect("/settings?saved=1",303):e.redirect("/settings?error="+encodeURIComponent(a.output.slice(0,800)),303)}),s.get("/settings/theme",I(),e=>e.html(at({theme:y,saved:e.req.query("saved")==="1"}))),s.post("/settings/theme",i(),async e=>{let t;try{t=await e.req.parseBody()}catch{return e.redirect("/settings/theme?error=1",303)}const r=t.template;return typeof r!="string"||!Te(r)?e.redirect("/settings/theme",303):(y=await Se(r),e.redirect("/settings/theme?saved=1",303))});const Ir={vscode:"VS Code",ghostty:"Ghostty","warm-clay":"Warm Clay","dark-cove":"Dark Cove"};s.get("/api/theme",i(),e=>e.json({active:y.template,templates:Dt.map(t=>({id:t,name:Ir[t]}))})),s.post("/api/theme",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=t.template;return typeof r!="string"||!Te(r)?e.json({error:"invalid theme template"},400):(y=await Se(r),e.json({ok:!0,active:y.template}))}),s.get("/api/sessions",i(),e=>p?e.json(C(v(),A())):e.json({error:"commandbar disabled"},404)),s.post("/api/sessions/new",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=typeof t.name=="string"?t.name.trim():"";if(!r)return e.json({error:"name is required"},400);if(!/^[a-zA-Z0-9_\-. ]+$/.test(r))return e.json({error:"name contains invalid characters"},400);const n=typeof t.dir=="string"&&t.dir.trim()?t.dir.trim():void 0;if(v().some(o=>o.name===r))return e.json({error:"session already exists"},409);try{return ur(r,n),e.json({ok:!0})}catch(o){const d=o instanceof X?o.message:"failed to create session";return e.json({error:d},500)}}),s.post("/api/sessions/rename",i(),async e=>{try{const{oldName:t,newName:r}=await e.req.json();return!t||!r?e.json({error:"oldName and newName required"},400):/^[a-zA-Z0-9_\-. ]+$/.test(r)?(cr(t,r),e.json({ok:!0})):e.json({error:"invalid characters in name"},400)}catch{return e.json({error:"rename failed"},500)}}),s.post("/api/sessions/kill",i(),async e=>{try{const{name:t}=await e.req.json();return t?(lr(t),e.json({ok:!0})):e.json({error:"name required"},400)}catch{return e.json({error:"kill failed"},500)}}),s.get("/api/fs/session-path",i(),e=>{const t=e.req.query("session");if(!t)return e.json({error:"session is required"},400);try{const r=gt(t),a=r.find(o=>o.active)?.path??r[0]?.path??process.env.HOME??"/";return e.json({path:a})}catch{return e.json({path:process.env.HOME??"/"})}}),s.get("/api/fs/list",i(),e=>{const t=process.env.HOME??"/";let r=e.req.query("path")??t;r.startsWith("~")&&(r=t+r.slice(1)),r.startsWith("/")||(r=g.join(t,r));const n=e.req.query("recursive")==="true";let a=r,o="",d=r.endsWith("/");if(!d)try{d=D(r).isDirectory()}catch{}d||(a=g.dirname(r),o=g.basename(r).toLowerCase());try{const S=pe(a),f=[],T=[];for(const O of S)if(!O.startsWith(".")&&!(o&&!O.toLowerCase().startsWith(o))){try{const b=g.join(a,O);D(b).isDirectory()?(f.push(b),n&&wt(b,f,T,0)):T.push(b)}catch{}if(f.length+T.length>=5e3)break}return e.json({dirs:f,files:T})}catch{return e.json({dirs:[],files:[]})}}),s.get("/api/file",i(),e=>{try{const t=e.req.query("path");if(!t)return e.json({error:"path is required"},400);const r=Q(t);if(!D(r).isFile())return e.json({error:"not a file"},400);const n=D(r).size;if(n>ke)return e.json({error:"file too large",size:n,maxBytes:ke},413);const a=Ve(r,"utf-8");return e.json({path:r,content:a,size:n})}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):t.code==="ENOENT"?e.json({error:"not found"},404):e.json({error:"internal error"},500)}}),s.put("/api/file",i(),async e=>{try{const t=await e.req.json();if(!t.path||typeof t.content!="string")return e.json({error:"path and content are required"},400);const r=Q(t.path);return yt(r,t.content),e.json({ok:!0})}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):e.json({error:"write failed"},500)}}),s.post("/api/file/delete",i(),async e=>{try{const t=await e.req.json();if(!t.path)return e.json({error:"path is required"},400);const r=Q(t.path);return D(r).isFile()?(Ge(r),e.json({ok:!0})):e.json({error:"not a file"},400)}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):t.code==="ENOENT"?e.json({error:"not found"},404):e.json({error:"delete failed"},500)}}),s.post("/api/file/touch",i(),async e=>{try{const t=await e.req.json();if(!t.path)return e.json({error:"path is required"},400);const r=Q(t.path);return K(r)?e.json({error:"file already exists"},409):(Be(g.dirname(r),{recursive:!0}),ze(r,"","utf-8"),e.json({ok:!0,path:r}))}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):e.json({error:"touch failed"},500)}});function ue(e){return{...Kt(v(),A(),$t()),currentSession:e??null}}function Ne(e){const t=typeof e.sessionName=="string"?e.sessionName.trim():"";if(!t)return{error:"sessionName is required"};if(e.windowIndex===void 0)return{sessionName:t};const r=e.windowIndex;return typeof r!="number"||!Number.isInteger(r)||r<0?{error:"windowIndex must be a non-negative integer"}:{sessionName:t,windowIndex:r}}s.get("/api/sidebar/sessions",i(),e=>{const t=e.req.query("currentSession");return e.json(ue(typeof t=="string"&&t?t:void 0))}),s.get("/api/sidebar/session-windows/:session",i(),e=>{const t=decodeURIComponent(e.req.param("session"));return e.json(be(t))}),s.post("/api/pinned-views",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=Ne(t);return"error"in r?e.json({error:r.error},400):(await Ut(r.sessionName,r.windowIndex),e.json(ue()))}),s.delete("/api/pinned-views",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=Ne(t);return"error"in r?e.json({error:r.error},400):(await Ft(r.sessionName,r.windowIndex),e.json(ue()))}),s.get("/api/notes",i(),e=>{const t=[...j.data.notes].sort((r,n)=>(n.updatedAt??0)-(r.updatedAt??0));return e.json(t)}),s.get("/api/notes/:scope",i(),e=>{const t=decodeURIComponent(e.req.param("scope")),r=j.data.notes.find(n=>n.scope===t);return r?e.json(r):e.json(null,404)}),s.put("/api/notes/:scope",i(),async e=>{const t=decodeURIComponent(e.req.param("scope"));let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}if(typeof r.content!="string")return e.json({error:"content must be string"},400);const n={scope:t,content:r.content,updatedAt:Date.now()},a=j.data.notes.findIndex(o=>o.scope===t);return a>=0?j.data.notes[a]=n:j.data.notes.push(n),await j.write(),e.json({ok:!0})}),s.post("/api/session/:session/upload",i(),async e=>{const t=decodeURIComponent(e.req.param("session"));if(!v().some(o=>o.name===t))return e.json({error:"session not found"},404);let n;try{n=await e.req.parseBody()}catch{return e.json({error:"invalid multipart body"},400)}const a=n.file;if(!(a instanceof File))return e.json({error:"missing file field"},400);try{const o=await a.arrayBuffer(),d=Buffer.from(o),{path:S}=await or(d,a.type||void 0,a.name||void 0);return e.json({path:S})}catch(o){return o instanceof nr?e.json({error:o.message},o.status):(console.error("[upload]",o),e.json({error:"upload failed"},500))}}),s.get("/api/session/:session/windows",i(),e=>{const t=decodeURIComponent(e.req.param("session")),r=new Map(Bt(t).map(o=>[o.windowIndex,o.label])),n=new Map(be(t).map(o=>[o.index,o])),a=sr(t).map(o=>({...o,label:r.get(o.index)??null,worktree:n.get(o.index)?.worktree??!1}));return e.json(a)}),s.post("/api/session/:session/window-label",i(),async e=>{const t=decodeURIComponent(e.req.param("session"));let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const{windowIndex:n}=r;if(typeof n!="number"||!Number.isInteger(n)||n<0)return e.json({error:"windowIndex must be a non-negative integer"},400);const a=typeof r.label=="string"?r.label:"",o=await Vt(t,n,a);return e.json(o)}),s.post("/api/session/:session/select-window",i(),async e=>{const t=decodeURIComponent(e.req.param("session"));let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const{windowIndex:n}=r;if(typeof n!="number"||!Number.isInteger(n)||n<0)return e.json({error:"windowIndex must be a non-negative integer"},400);try{return ar(t,n),ee(t),e.json({ok:!0})}catch(a){return a instanceof X?e.json({error:a.message},a.status):(console.error("[select-window]",a),e.json({error:"select-window failed"},500))}}),s.post("/api/session/:session/rename-window",i(),async e=>{const t=decodeURIComponent(e.req.param("session"));let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const{windowIndex:n}=r;if(typeof n!="number"||!Number.isInteger(n)||n<0)return e.json({error:"windowIndex must be a non-negative integer"},400);if(typeof r.name!="string"||!r.name.trim())return e.json({error:"name is required"},400);try{return dr(t,n,r.name),oe(t),e.json({ok:!0})}catch(a){return a instanceof X?e.json({error:a.message},a.status):(console.error("[rename-window]",a),e.json({error:"rename-window failed"},500))}}),s.post("/api/session/:session/new-window",i(),e=>{const t=decodeURIComponent(e.req.param("session"));try{return ir(t),ee(t),oe(t),e.json({ok:!0})}catch(r){return r instanceof X?e.json({error:r.message},r.status):(console.error("[new-window]",r),e.json({error:"new-window failed"},500))}}),s.get("/api/schedule",i(),e=>e.json(M.list(e.req.query("session")))),s.post("/api/schedule",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=ve(t);if(r)return e.json({error:r},400);if(!qt(t))return e.json({error:"invalid body"},400);const n=await M.create(t);return e.json({id:n.id,fireAt:n.fireAt})}),s.delete("/api/schedule/:id",i(),async e=>await M.delete(e.req.param("id"))?e.json({ok:!0}):e.json({error:"not found"},404)),s.patch("/api/schedule/:id",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=ve(t);if(r)return e.json({error:r},400);if(!At(t))return e.json({error:"invalid body"},400);const n=await M.reschedule(e.req.param("id"),t.delayMs);return n?e.json({id:n.id,fireAt:n.fireAt}):e.json({error:"not found"},404)});const _r=parseInt(process.env.PORT||"21000",10),Cr=Je({fetch:s.fetch,port:_r},e=>{console.log(`tmux-web running at http://localhost:${e.port}`)});Me&&hr();const ce=new Ze({noServer:!0});function De(e,t,r){e.write(`HTTP/1.1 ${t} ${r}\r
6
+ </svg>`,Le=e=>e.body(Ar,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"});s.get("/favicon.svg",Le),s.get("/favicon.ico",Le),s.get("/login",e=>{const r=e.req.query("setup")==="1"?!0:!l.passwordHash,n=e.req.query("error");return e.html(rt({setupMode:r,error:n?decodeURIComponent(n):void 0,theme:y}))}),s.get("/",I(),e=>{const t=p?C(v(),A()):[],r=je();return e.html(mt({theme:y,commandbarEnabled:p,commandbarSessions:t,agentsEnabled:_,fsRoots:r,terminalCfg:B,renderer:Z,scrollback:B.initialLines+2*B.historyChunk}))}),s.get("/s/:session",I(),async e=>{const t=decodeURIComponent(e.req.param("session"));await jt(t),oe(t);const r=v(),n=A(),a=p?C(r,n):[];return e.html(tt(t,de,{commandbarEnabled:p,commandbarSessions:a,quickCommands:p?se():[],agentsEnabled:_,terminal:B,theme:y,renderer:Z}))}),s.get("/notes",I(),e=>{const t=p?C(v(),A()):[];return e.html(nt(j.data.notes,y,p,t,_))}),s.get("/notes/:session",I(),e=>{const t=decodeURIComponent(e.req.param("session")),r=p?C(v(),A()):[];return e.html(ot(t,y,p,r))}),s.get("/schedule",I(),e=>{const t=p?C(v(),A()):[];return e.html(it(M.list(),M.listTriggered(),y,Oe,p,t,_))}),s.get("/agents",I(),e=>{if(!_)return e.redirect("/settings",303);const t=p?C(v(),A()):[];return e.html(dt(y,p,t))}),s.get("/history",I(),e=>{const t=v(),r=p?C(t,A()):[],n=new Set(t.map(a=>a.name));return e.html(ut(kt(),y,p,r,_,n))}),s.get("/quick-commands",I(),e=>{const t=p?C(v(),A()):[];return e.html(ct(se(),y,p,t,_))}),s.get("/files",I(),e=>{const t=p?C(v(),A()):[],r=je();return e.html(lt(y,p,t,_,r))}),s.post("/api/history/clear",i(),async e=>(await vt(),e.json({ok:!0}))),s.get("/api/quick-commands",i(),e=>e.json(se())),s.post("/api/quick-commands",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=await Qt(t);return"error"in r?e.json({error:r.error},400):e.json(r,201)}),s.patch("/api/quick-commands/:id",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=await Yt(e.req.param("id"),t);return"error"in r?e.json({error:r.error},r.status):e.json(r)}),s.delete("/api/quick-commands/:id",i(),async e=>await Xt(e.req.param("id"))?e.json({ok:!0}):e.json({error:"not found"},404)),s.get("/api/agents",i(),async e=>{if(!_)return e.json({error:"agents page disabled"},403);const t=Me?yr():await fr();return e.json(t)}),s.post("/api/auth/password",async e=>{const t=J(e),r=E.check(t);if(!r.allowed)return c("rate_limited",{ip:t,retryAfterMs:r.retryAfterMs,permanentLock:r.permanentLock}),r.permanentLock?e.json({error:"Server locked after too many failed attempts",permanentLock:!0},403):e.json({error:"Too many attempts",retryAfterMs:r.retryAfterMs},429);let n;try{n=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const a=typeof n.password=="string"?n.password:"";if(!l.passwordHash){if(!l.security.allowRemoteSetup&&!Ae(t))return c("setup_rejected_remote",{ip:t}),e.json({error:"First-run setup must be performed from localhost"},403);if(W)return e.json({error:"Password setup in progress"},409);const f=ge(a);if(f)return e.json({error:f},400);W=!0;try{l.passwordHash=await ye(a),he(l),c("password_set",{ip:t})}finally{W=!1}const{plaintext:T}=h.createAccessToken("setup",l.security.tokenTtlDays);return _e(e,T),e.json({ok:!0,token:T,setupMode:!0})}if(!await we(a,l.passwordHash)){const f=E.recordFailure(t);return c("auth_failed",{ip:t,method:"password",failures:f.failures,permanentLock:f.permanentLock}),f.permanentLock?(h.revokeAll(),c("permanent_lock",{ip:t,failures:f.failures}),e.json({error:"Server locked after too many failed attempts",permanentLock:!0},403)):f.allowed?e.json({error:"Incorrect password"},401):e.json({error:"Too many attempts",retryAfterMs:f.retryAfterMs},429)}E.recordSuccess(t);const d=`browser-${t}`,{plaintext:S}=h.createAccessToken(d,l.security.tokenTtlDays);return _e(e,S),c("auth_success",{ip:t,method:"password",tokenName:d}),e.json({ok:!0,token:S})}),s.post("/api/auth/token",i(),async e=>{const t=J(e);let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const n=typeof r.name=="string"?r.name:`api-${t}`,a=typeof r.ttlDays=="number"?r.ttlDays:l.security.tokenTtlDays,{stored:o,plaintext:d}=h.createAccessToken(n,a);return c("token_created",{ip:t,name:o.name,tokenId:o.id}),e.json({id:o.id,name:o.name,token:d,expiresAt:o.expiresAt})}),s.get("/api/auth/tokens",i(),e=>e.json(h.list().map(t=>({id:t.id,name:t.name,createdAt:t.createdAt,lastUsedAt:t.lastUsedAt,expiresAt:t.expiresAt})))),s.delete("/api/auth/tokens/:id",i(),e=>h.revoke(e.req.param("id"))?(c("token_revoked",{ip:J(e),tokenId:e.req.param("id")}),e.json({ok:!0})):e.json({error:"not found"},404)),s.post("/api/auth/logout",i(),e=>(kr(e),e.json({ok:!0}))),s.get("/settings",I(),async e=>{const t=await ne(),r=t.terminalRenderer??"xterm";return e.html(st({settings:t,renderer:Z,rendererOverridden:Z!==r,theme:y,plugins:t.plugins??[],saved:e.req.query("saved")==="1",error:e.req.query("error")?decodeURIComponent(e.req.query("error")):void 0}))}),s.post("/settings",i(),async e=>{let t;try{t=await e.req.parseBody()}catch{return e.redirect("/settings?error="+encodeURIComponent("invalid form body"),303)}const r=await ne(),n=t.terminalRenderer==="ghostty"?"ghostty":"xterm",a=t.defaultView==="recent"?"recent":"default",o=Ce(typeof t.scheduleHistoryDays=="string"?Number(t.scheduleHistoryDays):void 0);return await Lt({...r,commandbar:t.commandbar!==void 0,agents:t.agents!==void 0,agentsBackgroundWatch:t.agentsBackgroundWatch!==void 0,terminalRenderer:n,defaultView:a,scheduleHistoryDays:o}),e.redirect("/settings?saved=1",303)}),s.post("/settings/plugins",i(),async e=>{let t;try{t=await e.req.parseBody()}catch{return e.redirect("/settings?error="+encodeURIComponent("invalid form body"),303)}const r=t.action,n=typeof t.pkg=="string"?t.pkg.trim():"";if(!n)return e.redirect("/settings?error="+encodeURIComponent("missing package name"),303);const a=r==="remove"?await Ht(n):r==="add"?await Wt(n):{ok:!1,output:"unknown action"};return a.ok?e.redirect("/settings?saved=1",303):e.redirect("/settings?error="+encodeURIComponent(a.output.slice(0,800)),303)}),s.get("/settings/theme",I(),e=>e.html(at({theme:y,saved:e.req.query("saved")==="1"}))),s.post("/settings/theme",i(),async e=>{let t;try{t=await e.req.parseBody()}catch{return e.redirect("/settings/theme?error=1",303)}const r=t.template;return typeof r!="string"||!Te(r)?e.redirect("/settings/theme",303):(y=await Se(r),e.redirect("/settings/theme?saved=1",303))});const Ir={vscode:"VS Code",ghostty:"Ghostty","warm-clay":"Warm Clay","dark-cove":"Dark Cove"};s.get("/api/theme",i(),e=>e.json({active:y.template,templates:Dt.map(t=>({id:t,name:Ir[t]}))})),s.post("/api/theme",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=t.template;return typeof r!="string"||!Te(r)?e.json({error:"invalid theme template"},400):(y=await Se(r),e.json({ok:!0,active:y.template}))}),s.get("/api/sessions",i(),e=>p?e.json(C(v(),A())):e.json({error:"commandbar disabled"},404)),s.post("/api/sessions/new",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=typeof t.name=="string"?t.name.trim():"";if(!r)return e.json({error:"name is required"},400);if(!/^[a-zA-Z0-9_\-. ]+$/.test(r))return e.json({error:"name contains invalid characters"},400);const n=typeof t.dir=="string"&&t.dir.trim()?t.dir.trim():void 0;if(v().some(o=>o.name===r))return e.json({error:"session already exists"},409);try{return ur(r,n),e.json({ok:!0})}catch(o){const d=o instanceof X?o.message:"failed to create session";return e.json({error:d},500)}}),s.post("/api/sessions/rename",i(),async e=>{try{const{oldName:t,newName:r}=await e.req.json();return!t||!r?e.json({error:"oldName and newName required"},400):/^[a-zA-Z0-9_\-. ]+$/.test(r)?(cr(t,r),e.json({ok:!0})):e.json({error:"invalid characters in name"},400)}catch{return e.json({error:"rename failed"},500)}}),s.post("/api/sessions/kill",i(),async e=>{try{const{name:t}=await e.req.json();return t?(lr(t),e.json({ok:!0})):e.json({error:"name required"},400)}catch{return e.json({error:"kill failed"},500)}}),s.get("/api/fs/session-path",i(),e=>{const t=e.req.query("session");if(!t)return e.json({error:"session is required"},400);try{const r=gt(t),a=r.find(o=>o.active)?.path??r[0]?.path??process.env.HOME??"/";return e.json({path:a})}catch{return e.json({path:process.env.HOME??"/"})}}),s.get("/api/fs/list",i(),e=>{const t=process.env.HOME??"/";let r=e.req.query("path")??t;r.startsWith("~")&&(r=t+r.slice(1)),r.startsWith("/")||(r=g.join(t,r));const n=e.req.query("recursive")==="true";let a=r,o="",d=r.endsWith("/");if(!d)try{d=D(r).isDirectory()}catch{}d||(a=g.dirname(r),o=g.basename(r).toLowerCase());try{const S=pe(a),f=[],T=[];for(const O of S)if(!O.startsWith(".")&&!(o&&!O.toLowerCase().startsWith(o))){try{const b=g.join(a,O);D(b).isDirectory()?(f.push(b),n&&wt(b,f,T,0)):T.push(b)}catch{}if(f.length+T.length>=5e3)break}return e.json({dirs:f,files:T})}catch{return e.json({dirs:[],files:[]})}}),s.get("/api/file",i(),e=>{try{const t=e.req.query("path");if(!t)return e.json({error:"path is required"},400);const r=Q(t);if(!D(r).isFile())return e.json({error:"not a file"},400);const n=D(r).size;if(n>ke)return e.json({error:"file too large",size:n,maxBytes:ke},413);const a=Ve(r,"utf-8");return e.json({path:r,content:a,size:n})}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):t.code==="ENOENT"?e.json({error:"not found"},404):e.json({error:"internal error"},500)}}),s.put("/api/file",i(),async e=>{try{const t=await e.req.json();if(!t.path||typeof t.content!="string")return e.json({error:"path and content are required"},400);const r=Q(t.path);return yt(r,t.content),e.json({ok:!0})}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):e.json({error:"write failed"},500)}}),s.post("/api/file/delete",i(),async e=>{try{const t=await e.req.json();if(!t.path)return e.json({error:"path is required"},400);const r=Q(t.path);return D(r).isFile()?(Ge(r),e.json({ok:!0})):e.json({error:"not a file"},400)}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):t.code==="ENOENT"?e.json({error:"not found"},404):e.json({error:"delete failed"},500)}}),s.post("/api/file/touch",i(),async e=>{try{const t=await e.req.json();if(!t.path)return e.json({error:"path is required"},400);const r=Q(t.path);return K(r)?e.json({error:"file already exists"},409):(Be(g.dirname(r),{recursive:!0}),ze(r,"","utf-8"),e.json({ok:!0,path:r}))}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):e.json({error:"touch failed"},500)}});function ue(e){return{...Kt(v(),A(),$t()),currentSession:e??null}}function Ne(e){const t=typeof e.sessionName=="string"?e.sessionName.trim():"";if(!t)return{error:"sessionName is required"};if(e.windowIndex===void 0)return{sessionName:t};const r=e.windowIndex;return typeof r!="number"||!Number.isInteger(r)||r<0?{error:"windowIndex must be a non-negative integer"}:{sessionName:t,windowIndex:r}}s.get("/api/sidebar/sessions",i(),e=>{const t=e.req.query("currentSession");return e.json(ue(typeof t=="string"&&t?t:void 0))}),s.get("/api/sidebar/session-windows/:session",i(),e=>{const t=decodeURIComponent(e.req.param("session"));return e.json(be(t))}),s.post("/api/pinned-views",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=Ne(t);return"error"in r?e.json({error:r.error},400):(await Ut(r.sessionName,r.windowIndex),e.json(ue()))}),s.delete("/api/pinned-views",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=Ne(t);return"error"in r?e.json({error:r.error},400):(await Ft(r.sessionName,r.windowIndex),e.json(ue()))}),s.get("/api/notes",i(),e=>{const t=[...j.data.notes].sort((r,n)=>(n.updatedAt??0)-(r.updatedAt??0));return e.json(t)}),s.get("/api/notes/:scope",i(),e=>{const t=decodeURIComponent(e.req.param("scope")),r=j.data.notes.find(n=>n.scope===t);return r?e.json(r):e.json(null,404)}),s.put("/api/notes/:scope",i(),async e=>{const t=decodeURIComponent(e.req.param("scope"));let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}if(typeof r.content!="string")return e.json({error:"content must be string"},400);const n={scope:t,content:r.content,updatedAt:Date.now()},a=j.data.notes.findIndex(o=>o.scope===t);return a>=0?j.data.notes[a]=n:j.data.notes.push(n),await j.write(),e.json({ok:!0})}),s.post("/api/session/:session/upload",i(),async e=>{const t=decodeURIComponent(e.req.param("session"));if(!v().some(o=>o.name===t))return e.json({error:"session not found"},404);let n;try{n=await e.req.parseBody()}catch{return e.json({error:"invalid multipart body"},400)}const a=n.file;if(!(a instanceof File))return e.json({error:"missing file field"},400);try{const o=await a.arrayBuffer(),d=Buffer.from(o),{path:S}=await or(d,a.type||void 0,a.name||void 0);return e.json({path:S})}catch(o){return o instanceof nr?e.json({error:o.message},o.status):(console.error("[upload]",o),e.json({error:"upload failed"},500))}}),s.get("/api/session/:session/windows",i(),e=>{const t=decodeURIComponent(e.req.param("session")),r=new Map(Bt(t).map(o=>[o.windowIndex,o.label])),n=new Map(be(t).map(o=>[o.index,o])),a=sr(t).map(o=>({...o,label:r.get(o.index)??null,worktree:n.get(o.index)?.worktree??!1}));return e.json(a)}),s.post("/api/session/:session/window-label",i(),async e=>{const t=decodeURIComponent(e.req.param("session"));let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const{windowIndex:n}=r;if(typeof n!="number"||!Number.isInteger(n)||n<0)return e.json({error:"windowIndex must be a non-negative integer"},400);const a=typeof r.label=="string"?r.label:"",o=await Vt(t,n,a);return e.json(o)}),s.post("/api/session/:session/select-window",i(),async e=>{const t=decodeURIComponent(e.req.param("session"));let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const{windowIndex:n}=r;if(typeof n!="number"||!Number.isInteger(n)||n<0)return e.json({error:"windowIndex must be a non-negative integer"},400);try{return ar(t,n),ee(t),e.json({ok:!0})}catch(a){return a instanceof X?e.json({error:a.message},a.status):(console.error("[select-window]",a),e.json({error:"select-window failed"},500))}}),s.post("/api/session/:session/rename-window",i(),async e=>{const t=decodeURIComponent(e.req.param("session"));let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const{windowIndex:n}=r;if(typeof n!="number"||!Number.isInteger(n)||n<0)return e.json({error:"windowIndex must be a non-negative integer"},400);if(typeof r.name!="string"||!r.name.trim())return e.json({error:"name is required"},400);try{return dr(t,n,r.name),oe(t),e.json({ok:!0})}catch(a){return a instanceof X?e.json({error:a.message},a.status):(console.error("[rename-window]",a),e.json({error:"rename-window failed"},500))}}),s.post("/api/session/:session/new-window",i(),e=>{const t=decodeURIComponent(e.req.param("session"));try{return ir(t),ee(t),oe(t),e.json({ok:!0})}catch(r){return r instanceof X?e.json({error:r.message},r.status):(console.error("[new-window]",r),e.json({error:"new-window failed"},500))}}),s.get("/api/schedule",i(),e=>e.json(M.list(e.req.query("session")))),s.post("/api/schedule",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=ve(t);if(r)return e.json({error:r},400);if(!qt(t))return e.json({error:"invalid body"},400);const n=await M.create(t);return e.json({id:n.id,fireAt:n.fireAt})}),s.delete("/api/schedule/:id",i(),async e=>await M.delete(e.req.param("id"))?e.json({ok:!0}):e.json({error:"not found"},404)),s.patch("/api/schedule/:id",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=ve(t);if(r)return e.json({error:r},400);if(!At(t))return e.json({error:"invalid body"},400);const n=await M.reschedule(e.req.param("id"),t.delayMs);return n?e.json({id:n.id,fireAt:n.fireAt}):e.json({error:"not found"},404)});const _r=parseInt(process.env.PORT||"21000",10),Cr=Je({fetch:s.fetch,port:_r,hostname:"0.0.0.0"},e=>{console.log(`tmux-web running at http://${e.port}`)});Me&&hr();const ce=new Ze({noServer:!0});function De(e,t,r){e.write(`HTTP/1.1 ${t} ${r}\r
7
7
  \r
8
8
  `),e.destroy()}Cr.on("upgrade",(e,t,r)=>{const n=new URL(e.url||"/",`http://${e.headers.host}`),a=n.pathname.match(/^\/ws\/(.+)$/);if(!a){t.destroy();return}const o=jr(e),d=e.headers.origin,S=l.security.allowedOrigins;if(d&&!(d===`http://${e.headers.host}`||d===`https://${e.headers.host}`)&&(S.length===0||!S.includes(d))){c("ws_rejected_origin",{ip:o,origin:d}),De(t,403,"Origin not allowed");return}const f=xr(o);if(f>=l.security.maxConnectionsPerIp){c("ws_rejected_per_ip_cap",{ip:o,liveFromIp:f}),De(t,429,"Too many connections");return}const T=Ie(e)||n.searchParams.get("token")||"",O=T?h.validateToken(T):null;ce.handleUpgrade(e,t,r,b=>{ce.emit("connection",b,e,decodeURIComponent(a[1]),o,O)})}),ce.on("connection",(e,t,r,n,a)=>{const o={ws:e,ip:n,authenticated:!1,authTimeout:null};H.set(e,o),c("ws_connected",{ip:n});let d=null;const{initialLines:S,historyChunk:f,syncIdleMs:T,syncMaxMs:O}=B;let b=!0,N=null,G=null,F=r,P=null;const z=()=>{N&&(clearTimeout(N),N=null),G&&(clearTimeout(G),G=null)},le=()=>{if(b){z(),b=!1;try{F=Jt(r)}catch{F=r}if(ee(r),!tr(F))try{const w=Zt(F,S);x(e,{type:"snapshot",data:qe(w),lines:S})}catch{}}},He=()=>{b&&(N&&clearTimeout(N),N=setTimeout(le,T))};function me(){try{d=et.spawn("tmux",["attach-session","-t",r],{name:"xterm-256color",cols:80,rows:24,cwd:process.env.HOME||"/",env:process.env})}catch(u){x(e,{type:"data",data:`\r
9
9
  \x1B[31mFailed to attach to tmux session "${r}": ${u.message}\x1B[0m\r
@@ -1,4 +1,4 @@
1
- import{cssVarsStyle as g}from"../theme.js";import{commandbarCSS as x,commandbarHTML as m,commandbarScript as f}from"../commandbar.js";import{newSessionModalCSS as h,newSessionModalHTML as u,newSessionModalScript as v,reducedMotion as y}from"../shared-layout.js";import{icon as o}from"../icons.js";function C(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function a(n="var(--panel-accent)"){return`box-shadow: 0 0 0 2px ${n}; outline: none;`}function _(n){const{theme:e,commandbarEnabled:t,commandbarSessions:s,agentsEnabled:r,fsRoots:d,terminalCfg:l,renderer:i,scrollback:p}=n,c=`
1
+ import{cssVarsStyle as g}from"../theme.js";import{commandbarCSS as x,commandbarHTML as m,commandbarScript as f}from"../commandbar.js";import{newSessionModalCSS as v,newSessionModalHTML as h,newSessionModalScript as u,reducedMotion as y}from"../shared-layout.js";import{icon as o}from"../icons.js";function C(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function a(n="var(--panel-accent)"){return`box-shadow: 0 0 0 2px ${n}; outline: none;`}function _(n){const{theme:e,commandbarEnabled:t,commandbarSessions:s,agentsEnabled:r,fsRoots:d,terminalCfg:l,renderer:i,scrollback:p}=n,c=`
2
2
  *, *::before, *::after { box-sizing: border-box; }
3
3
  html, body {
4
4
  background: var(--page-bg); color: var(--page-fg);
@@ -28,6 +28,7 @@ import{cssVarsStyle as g}from"../theme.js";import{commandbarCSS as x,commandbarH
28
28
  display: flex;
29
29
  height: 100vh;
30
30
  padding-top: 48px;
31
+ transition: height 0.05s;
31
32
  }
32
33
 
33
34
  /* \u2500\u2500 Sidebar \u2500\u2500 */
@@ -302,7 +303,7 @@ import{cssVarsStyle as g}from"../theme.js";import{commandbarCSS as x,commandbarH
302
303
  /* \u2500\u2500 Commandbar \u2500\u2500 */
303
304
  ${t?x():""}
304
305
  ${y()}
305
- ${h()}
306
+ ${v()}
306
307
  @media (max-width: 640px) {
307
308
  .app-layout { flex-direction: column; }
308
309
  .sidebar { flex: 0 0 auto; border-right: none; border-bottom: 1px solid var(--panel-border); transition: max-height 0.2s; }
@@ -443,7 +444,7 @@ import{cssVarsStyle as g}from"../theme.js";import{commandbarCSS as x,commandbarH
443
444
  })();
444
445
  </script>
445
446
 
446
- ${u()}
447
+ ${h()}
447
448
  ${t?m():""}
448
449
 
449
450
  <script>
@@ -457,7 +458,18 @@ window.__onSessionCreated = async function(name) {
457
458
  await window.__refreshSidebar();
458
459
  window.__openSession(name);
459
460
  };
460
- ${v("__onSessionCreated")}
461
+ ${u("__onSessionCreated")}
462
+ </script>
463
+ <script>
464
+ // Sync app-layout height to visual viewport so mobile keyboard doesn't overlap
465
+ (function(){
466
+ var el = document.querySelector('.app-layout');
467
+ var vv = window.visualViewport;
468
+ if (!vv || !el) return;
469
+ function sync(){ el.style.height = vv.height + 'px'; }
470
+ vv.addEventListener('resize', sync);
471
+ sync();
472
+ })();
461
473
  </script>
462
474
  </body>
463
475
  </html>`}export{_ as renderShell};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tmux-weblink",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Access your tmux sessions from the browser. A continuation of tmux-web and persalink.",
5
5
  "type": "module",
6
6
  "bin": {