@2digits/tlo-mcp 2.0.6 → 2.0.8
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/README.md +43 -36
- package/dist/bin.mjs +9 -9
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -5,39 +5,13 @@ Only Orbit tools are exposed. No local Executor, cookie adapter, Amp plugin, Ver
|
|
|
5
5
|
|
|
6
6
|
## Run
|
|
7
7
|
|
|
8
|
-
Requires Node.js 24+.
|
|
9
|
-
With `mise activate` enabled in your shell, entering the repository installs the pinned Pitchfork version and
|
|
10
|
-
starts the gateway automatically. It keeps running after you leave the repository or close the terminal.
|
|
11
|
-
The Mac must stay awake. Pitchfork retries failed processes up to three times and waits for the public tunnel
|
|
12
|
-
to be ready, not just the local HTTP port. Each start builds the CLI; source edits need a restart.
|
|
13
|
-
|
|
14
|
-
From the repository root:
|
|
8
|
+
Requires Node.js 24+. Start the gateway with:
|
|
15
9
|
|
|
16
10
|
```bash
|
|
17
|
-
|
|
18
|
-
mise exec -- pitchfork logs tlo-mcp --tail
|
|
19
|
-
mise exec -- pitchfork restart tlo-mcp
|
|
20
|
-
mise exec -- pitchfork stop tlo-mcp
|
|
11
|
+
npx @2digits/tlo-mcp
|
|
21
12
|
```
|
|
22
13
|
|
|
23
|
-
|
|
24
|
-
Stopping the log viewer does not stop the gateway. Stop any manually started gateway before enabling Pitchfork,
|
|
25
|
-
since both use port `4790`. First-time Orbit login still requires completing the browser flow.
|
|
26
|
-
To keep the gateway stopped across repository visits, use `mise exec -- pitchfork disable tlo-mcp`;
|
|
27
|
-
resume with `mise exec -- pitchfork enable tlo-mcp` followed by `mise exec -- pitchfork start tlo-mcp`.
|
|
28
|
-
This setup starts on repository entry, not automatically at macOS login.
|
|
29
|
-
|
|
30
|
-
To run in the foreground instead, first stop/disable the Pitchfork daemon. From this package:
|
|
31
|
-
|
|
32
|
-
```bash
|
|
33
|
-
vp run run
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
Or, after installation/build:
|
|
37
|
-
|
|
38
|
-
```bash
|
|
39
|
-
vp exec tlo-mcp
|
|
40
|
-
```
|
|
14
|
+
Or install it globally (`npm i -g @2digits/tlo-mcp`) and run `tlo-mcp`.
|
|
41
15
|
|
|
42
16
|
The command:
|
|
43
17
|
|
|
@@ -52,6 +26,34 @@ Keep this process running and the computer awake. Ctrl-C closes the HTTP server
|
|
|
52
26
|
so subsequent starts reuse the URL. Use `--port 4791` if the default port is occupied.
|
|
53
27
|
The first tunnel certificate can take several minutes. Failed startup closes acquired resources.
|
|
54
28
|
|
|
29
|
+
## Run in the background
|
|
30
|
+
|
|
31
|
+
Any process supervisor works (launchd, systemd, pm2, Pitchfork, …). Keep these in mind:
|
|
32
|
+
|
|
33
|
+
- Run one instance per machine; it binds `127.0.0.1:4790` (or `--port`).
|
|
34
|
+
- Treat it as ready once `TLO gateway ready:` is logged, not when the port opens; the tunnel comes up later.
|
|
35
|
+
- The process exits when the tunnel drops for good, so restart it on failure.
|
|
36
|
+
- Send `SIGINT` to stop it cleanly.
|
|
37
|
+
- The first start needs the interactive Orbit login. Run it once in a terminal (or run `tlo-mcp login`) before handing it to a supervisor.
|
|
38
|
+
- The logs contain the public endpoint and the Executor prompt; the gateway key is never printed.
|
|
39
|
+
|
|
40
|
+
Example with [Pitchfork](https://pitchfork.jdx.dev), in `~/.config/pitchfork/config.toml`:
|
|
41
|
+
|
|
42
|
+
```toml
|
|
43
|
+
[daemons.tlo]
|
|
44
|
+
run = "npx -y @2digits/tlo-mcp --port 4790"
|
|
45
|
+
dir = "~/"
|
|
46
|
+
boot_start = true
|
|
47
|
+
retry = true
|
|
48
|
+
ready_output = { pattern = "TLO gateway ready:", timeout = "5m" }
|
|
49
|
+
health_port = { port = 4790, interval = "30s", retries = 3 }
|
|
50
|
+
stop_signal = { signal = "SIGINT", timeout = "10s" }
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Run `pitchfork boot enable` so the supervisor starts at login. Boot-started supervisors get a minimal `PATH`, so use
|
|
54
|
+
absolute paths for `npx`/`node` if they are not found. Manage it with `pitchfork status global/tlo`,
|
|
55
|
+
`pitchfork logs global/tlo`, and `pitchfork restart global/tlo`.
|
|
56
|
+
|
|
55
57
|
## Connect Executor Cloud
|
|
56
58
|
|
|
57
59
|
Paste the printed prompt into an agent with Executor tools. It registers a Streamable HTTP MCP integration with
|
|
@@ -85,12 +87,12 @@ handoff for the API key and verify one read-only tool after connecting.
|
|
|
85
87
|
## Re-login and logout
|
|
86
88
|
|
|
87
89
|
```bash
|
|
88
|
-
|
|
89
|
-
|
|
90
|
+
npx @2digits/tlo-mcp login
|
|
91
|
+
npx @2digits/tlo-mcp logout
|
|
90
92
|
```
|
|
91
93
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
+
Stop the running gateway (and disable its supervisor) before either command. After login, start it again.
|
|
95
|
+
Leave it stopped after logout, or the next start opens the Orbit login again.
|
|
94
96
|
Logout removes local OAuth credentials, not the upstream grant,
|
|
95
97
|
gateway key or tunnel identity. An expired/rejected existing grant fails visibly; re-login explicitly rather than
|
|
96
98
|
silently registering replacement clients. OAuth credential locks fail closed; never remove a live process's lock.
|
|
@@ -104,8 +106,13 @@ The SDK/protocol are bundled into the CLI so published output does not depend on
|
|
|
104
106
|
Re-test these patches when upgrading OpenTunnel. The standalone SDK's original Bun requirement does not apply
|
|
105
107
|
to this patched Node CLI.
|
|
106
108
|
|
|
109
|
+
## Development
|
|
110
|
+
|
|
111
|
+
From this package in the repository:
|
|
112
|
+
|
|
107
113
|
```bash
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
114
|
+
vpr run # build and start the gateway from source
|
|
115
|
+
vpr test
|
|
116
|
+
vpr types
|
|
117
|
+
vpr build
|
|
111
118
|
```
|
package/dist/bin.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as e from"@effect/platform-node/NodeRuntime";import*as t from"@effect/platform-node/NodeServices";import*as n from"effect/Effect";import*as r from"effect/Schema";import*as i from"effect/cli/Command";import*as a from"effect/cli/Flag";import*as o from"@yielded/oauth/OAuth";import*as s from"@yielded/oauth/Pkce";import*as c from"effect/Clock";import*as l from"effect/Context";import*as u from"effect/Crypto";import*as d from"effect/Equal";import*as f from"effect/Exit";import*as p from"effect/Layer";import*as m from"effect/Match";import*as h from"effect/Redacted";import*as ee from"effect/Semaphore";import*as g from"effect/http/FetchHttpClient";import*as _ from"effect/http/HttpClient";import*as v from"effect/http/HttpClientRequest";import*as te from"effect/process/ChildProcess";import*as y from"effect/process/ChildProcessSpawner";import{timingSafeEqual as ne}from"node:crypto";import{createServer as re}from"node:http";import*as ie from"@effect/platform-node/NodeHttpServer";import*as b from"effect/Deferred";import*as ae from"effect/Predicate";import*as x from"effect/http/HttpRouter";import*as oe from"effect/http/HttpServer";import*as se from"effect/http/HttpServerRequest";import*as S from"effect/http/HttpServerResponse";import*as ce from"node:os";import{homedir as le}from"node:os";import*as ue from"effect/FileSystem";import*as de from"effect/Path";import*as C from"effect/Stream";import{Context as fe,Effect as w,Layer as T,Option as pe,Queue as E,Schema as D,Stream as me}from"effect";import{FetchHttpClient as he,HttpClient as ge,HttpClientError as _e,HttpClientRequest as ve}from"effect/http";import{HttpApi as ye,HttpApiClient as be,HttpApiEndpoint as O,HttpApiGroup as xe,HttpApiMiddleware as Se,HttpApiSchema as Ce,HttpApiSecurity as we,OpenApi as Te}from"effect/http-api";import*as k from"node:fs/promises";import*as A from"node:path";import*as Ee from"node:net";import{Duplex as De}from"node:stream";import*as Oe from"node:tls";import*as ke from"effect/ByteSize";import*as j from"effect/ai/McpProtocol";import*as Ae from"effect/ai/McpServer";import*as je from"effect/encoding/Hex";import*as Me from"effect/http/HttpIncomingMessage";import*as Ne from"effect/Option";import*as Pe from"effect/Struct";import*as M from"effect/ai/McpSchema";import*as Fe from"effect/encoding/Sse";import*as Ie from"effect/http/HttpClientResponse";const Le=`https://api.orbit.teamleader.eu`,N=`${Le}/mcp`,Re=r.String.check(r.isMinLength(1)).pipe(r.RedactedFromValue),ze=r.Struct({clientId:r.String.check(r.isMinLength(1)),clientSecret:Re.pipe(r.optionalKey),accessToken:Re,refreshToken:Re.pipe(r.optionalKey),expiresAt:r.Finite.pipe(r.optionalKey)});var P=class extends r.TaggedError()(`OrbitAuthError`,{message:r.String}){};function Be(e,t,n){let r=t.refreshToken??e.refreshToken;return{clientId:e.clientId,...e.clientSecret===void 0?{}:{clientSecret:e.clientSecret},accessToken:t.accessToken,...r===void 0?{}:{refreshToken:r},...t.expiresIn===void 0?{}:{expiresAt:n+t.expiresIn*1e3}}}function Ve(e,t){return e.expiresAt===void 0||e.expiresAt<=t+6e4}function He(e){return e.clientSecret===void 0?{method:`none`,publicClient:!0}:{method:`client_secret_post`,secret:e.clientSecret.pipe(h.value,h.make)}}const Ue={"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,"referrer-policy":`no-referrer`,"content-security-policy":`default-src 'none'`},F=S.text(`Invalid callback.`,{status:400,headers:Ue}),We=S.text(`Authorization received. Return to your terminal to complete login.`,{headers:Ue}),Ge=S.text(`Authorization denied. Return to your terminal.`,{status:400,headers:Ue});function Ke(e,t){let n=e.searchParams.getAll(t);return n.length===1?n[0]:void 0}function qe(e,t){let n=Ke(e,`state`);if(n===void 0||e.pathname!==`/callback`)return;let r=Buffer.from(t),i=Buffer.from(n);if(r.length!==i.length||!ne(r,i))return;if(e.searchParams.has(`error`))throw Error(`Orbit authorization was denied.`);let a=Ke(e,`code`);return a===``?void 0:a}const Je=n.fn(`OrbitAuth.listenForLogin`)(function*(e){let t=yield*b.make(),r=yield*n.sync(re),i=yield*ie.make(()=>r,{port:0,host:`127.0.0.1`}).pipe(n.mapError(()=>P.make({message:`Could not bind OAuth callback.`})));if(!ae.isTagged(i.address,`InetAddressV4`))return yield*P.make({message:`Could not bind OAuth callback.`});let a=`127.0.0.1:${i.address.port}`,o=`http://${a}/callback`,s=n.fn(`OrbitAuth.handleCallback`)(function*(){let r=yield*se.HttpServerRequest;return r.method!==`GET`||r.headers.host!==a||(yield*b.isDone(t))?F:yield*n.try({try:()=>qe(new URL(r.url,o),e),catch:()=>P.make({message:`Orbit authorization was denied.`})}).pipe(n.matchEffect({onFailure:e=>b.fail(t,e).pipe(n.map(e=>e?Ge:F)),onSuccess:e=>e===void 0?n.succeed(F):b.succeed(t,e).pipe(n.map(e=>e?We:F))}))}),c=yield*x.toHttpEffect(x.add(`*`,`*`,s()));return yield*oe.serveEffect(c).pipe(n.provideService(oe.HttpServer,i)),yield*n.addFinalizer(()=>n.sync(()=>r.closeAllConnections())),{redirectUri:o,code:b.await(t).pipe(n.timeout(`3 minutes`),n.mapError(()=>P.make({message:`Login denied or timed out. Run tlo-mcp login again.`})))}}),Ye=ze.pipe(r.fromJsonString),Xe=r.decodeEffect(Ye),Ze=r.encodeEffect(Ye),Qe=`@2digits/tlo-mcp/orbit`,$e=[`-a`,`orbit`,`-s`,Qe];var I=class extends l.Service()(`@2digits/tlo-mcp/oauth/store/SessionStore`){};function et(e){return`"${e.replaceAll(/["\\]/g,String.raw`\$&`)}"`}function tt(e={}){return p.effect(I,n.gen(function*(){let t=yield*ue.FileSystem,r=yield*de.Path,i=yield*y.ChildProcessSpawner,a=e.platform??process.platform,o=e.directory??r.join(le(),`.config`,`2digits`,`tlo-mcp`),s=r.join(o,`session.json`),c=r.join(o,`session.lock`),l=t.makeDirectory(o,{recursive:!0,mode:448}).pipe(n.andThen(t.chmod(o,448))),u=n.fn(`SessionStore.security`)(function*(e,t){let r=yield*i.spawn(te.make(`/usr/bin/security`,e,{stdin:t===void 0?`ignore`:C.succeed(new TextEncoder().encode(t)),stderr:`ignore`}));return yield*n.all({output:r.stdout.pipe(C.decodeText(),C.mkString),exitCode:r.exitCode},{concurrency:`unbounded`})},n.scoped),d=n.fn(`SessionStore.load`)(function*(){if(a===`darwin`){let e=yield*u([`find-generic-password`,...$e,`-w`]);return e.exitCode===44?void 0:e.exitCode===0?yield*Xe(e.output.trim()):yield*P.make({message:`Could not read macOS Keychain.`})}let e=yield*t.readFileString(s).pipe(n.catchReason(`PlatformError`,`NotFound`,()=>n.undefined));return e===void 0?void 0:yield*Xe(e)},n.mapError(()=>P.make({message:`Could not read credentials. Run tlo-mcp login again.`}))),f=n.fn(`SessionStore.save`)(function*(e){let n=yield*Ze(e);if(a===`darwin`){if((yield*u([`-q`,`-i`],`add-generic-password -U -a orbit -s ${et(Qe)} -w ${et(n)}\n`)).exitCode!==0)return yield*P.make({message:`Could not save macOS Keychain credentials.`})}else{yield*l;let e=yield*t.makeTempDirectoryScoped({directory:o,prefix:`session-`}),i=r.join(e,`session.json`);yield*t.writeFileString(i,n,{mode:384}),yield*t.rename(i,s)}},n.scoped,n.mapError(()=>P.make({message:`Could not persist OAuth credentials. Run tlo-mcp login again.`}))),p=n.fn(`SessionStore.clear`)(function*(){if(a===`darwin`){let e=yield*u([`delete-generic-password`,...$e]);if(e.exitCode!==0&&e.exitCode!==44)return yield*P.make({message:`Could not remove Keychain credentials.`})}else yield*t.remove(s,{force:!0})},n.mapError(()=>P.make({message:`Could not remove OAuth credentials.`}))),m=n.fn(`SessionStore.lock`)(function*(){yield*l,yield*n.acquireRelease(t.writeFileString(c,String(process.pid),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>P.make({message:`OAuth credentials locked. Close other login/refresh processes. After a crash only, remove ${c}.`}))),()=>t.remove(c).pipe(n.orDie))},n.catchTag(`PlatformError`,()=>P.make({message:`Could not acquire OAuth credential lock. Check directory permissions.`})));return I.of({load:d(),save:f,clear:p(),lock:m()})}))}const nt=tt(),rt=r.Struct({client_id:r.String.check(r.isMinLength(1)),client_secret:r.String.check(r.isMinLength(1)).pipe(r.RedactedFromValue,r.optionalKey)}),it=r.is(P),at=te.make({stdout:`ignore`,stderr:`ignore`,forceKillAfter:`1 second`});var L=class extends l.Service()(`@2digits/tlo-mcp/oauth/OrbitAuth`){};const ot=p.effect(L,n.gen(function*(){let e=yield*I,t=yield*u.Crypto,i=yield*_.HttpClient,a=yield*y.ChildProcessSpawner,l=yield*ee.make(1),p=yield*n.fn(`OrbitAuth.discover`)(function*(){let e=yield*_.withScope(i).get(`${Le}/.well-known/oauth-authorization-server`);if(e.status!==200)return yield*P.make({message:`Could not discover Orbit OAuth endpoints.`});let t=yield*e.json.pipe(n.flatMap(r.decodeUnknownEffect(o.Metadata)));return t.issuer!==`https://api.orbit.teamleader.eu`||t.authorization_endpoint!==`https://api.orbit.teamleader.eu/oauth2/Authorize`||t.token_endpoint!==`https://api.orbit.teamleader.eu/oauth2/access_token`?yield*P.make({message:`Unexpected Orbit endpoints; refusing to send credentials.`}):t},n.scoped,n.timeout(`15 seconds`),n.mapError(()=>P.make({message:`Invalid or unavailable Orbit OAuth metadata.`})))().pipe(n.cachedWithTTL(e=>f.isSuccess(e)?1/0:0)),te=n.fn(`OrbitAuth.accessToken`)(function*(){let t=yield*e.load;if(t===void 0)return yield*P.make({message:`Not authenticated. Run tlo-mcp login first.`});if(!Ve(t,yield*c.currentTimeMillis))return t.accessToken;if(t.refreshToken===void 0)return t.expiresAt===void 0?t.accessToken:yield*P.make({message:`Orbit session expired without a refresh token. Run tlo-mcp login.`});let r=yield*p,i=Be(t,yield*(yield*o.make({metadata:r,clientId:t.clientId,authentication:He(t),timeoutMs:15e3})).refreshGrant({refreshToken:t.refreshToken,resources:[N]}).pipe(n.flatMap(o.tokens)),yield*c.currentTimeMillis);return yield*e.save(i),i.accessToken}),ne=n.fn(`OrbitAuth.register`)(function*(e){let t=yield*v.post(`${Le}/oauth2/register`).pipe(v.bodyJson({client_name:`@2digits/tlo-mcp`,redirect_uris:[e],response_types:[`code`],grant_types:[`authorization_code`,`refresh_token`],token_endpoint_auth_method:`none`}),n.flatMap(_.withScope(i).execute));return t.status!==200&&t.status!==201?yield*P.make({message:`Orbit client registration failed (HTTP ${t.status}).`}):yield*t.json.pipe(n.flatMap(r.decodeUnknownEffect(rt)))},n.scoped,n.timeout(`15 seconds`)),re=n.fn(`OrbitAuth.openBrowser`)(function*(e){return yield*(yield*m.value(process.platform).pipe(m.when(`darwin`,()=>at`open ${h.value(e)}`),m.when(`win32`,()=>at`rundll32 url.dll,FileProtocolHandler ${h.value(e)}`),m.orElse(()=>at`xdg-open ${h.value(e)}`))).exitCode},n.scoped,n.timeout(`5 seconds`),n.filterOrFail(d.equals(y.ExitCode(0)),()=>P.make({message:`Could not open browser.`})),(e,t)=>e.pipe(n.catch(()=>n.sync(()=>{process.stderr.write(`Open this URL in your browser:\n${h.value(t)}\n`)})))),ie=n.fn(`OrbitAuth.login`)(function*(){let t=yield*p,r=yield*s.random(),i=yield*s.make(),a=yield*r.pipe(h.value,Je),l=yield*ne(a.redirectUri),u={clientId:l.client_id,...l.client_secret===void 0?{}:{clientSecret:l.client_secret}},d=yield*o.make({metadata:t,...u,authentication:He(u),timeoutMs:15e3}),f=yield*d.authorizationUrl({redirectUri:a.redirectUri,scopes:[],state:r,codeChallenge:i.challenge,resources:[N]});yield*re(f);let m=yield*a.code,ee=yield*d.codeGrant({code:h.make(m),redirectUri:a.redirectUri,pkceVerifier:i.verifier,resources:[N]}).pipe(n.flatMap(o.tokens));yield*e.save(Be(u,ee,yield*c.currentTimeMillis)),yield*n.sync(()=>{process.stderr.write(`Orbit login complete.
|
|
3
|
-
`)})}),b=n.fn(`OrbitAuth.locked`)(function*(t){return yield*e.lock,yield*t},n.scoped,l.withPermit,n.provideService(_.HttpClient,i),n.provideService(u.Crypto,t),n.provideService(y.ChildProcessSpawner,a),n.provideService(g.RequestInit,{redirect:`error`}),n.mapError(e=>
|
|
4
|
-
`)}-----END CERTIFICATE REQUEST-----`}var
|
|
5
|
-
`);let[t,n]=e.family===4?[`TCP4`,`0.0.0.0`]:[`TCP6`,`::`];return kn.encode(`PROXY ${t} ${On(e)} ${n} ${e.port} 443\r\n`)},Mn=(e,t)=>{let n=kn.encode(t),r=n.length>0&&n.length<=255?3+n.length:0,i=(e===void 0?0:e.family===4?12:36)+r,a=new Uint8Array(16+i),o=new DataView(a.buffer);a.set(bn,0),a[12]=e?33:32,a[13]=e===void 0?0:e.family===4?17:33,o.setUint16(14,i);let s=16;if(e){let t=e.bytes.length;a.set(e.bytes,s),s+=t*2,o.setUint16(s,e.port),o.setUint16(s+2,443),s+=4}return r>0&&(a[s]=2,o.setUint16(s+1,n.length),a.set(n,s+3)),a},Nn=WebSocket;var Pn=class extends Error{code;constructor(e){super(`Bridge attach failed: ${e}`),this.code=e}};const Fn=/* @__PURE__ */ new Set([q.BAD_TOKEN,q.CERT_NOT_READY]),In=/* @__PURE__ */ new Set([`target`,`proxyProtocol`]),Ln=(e,t)=>{if(!gn(e))throw Error(`Invalid route name '${e}'`);let n=t,r;if(typeof t==`object`&&t&&!Array.isArray(t)){for(let n of Object.keys(t))if(!In.has(n))throw Error(`Unknown option '${n}' for route '${e}': expected target or proxyProtocol`);let i=t;if(i.target===void 0)throw Error(`Route '${e}' has no target`);if(n=i.target,i.proxyProtocol!==void 0){if(!yn(i.proxyProtocol))throw Error(`Invalid proxyProtocol '${String(i.proxyProtocol)}' for route '${e}': use "v1" or "v2"`);r=i.proxyProtocol}}let i=typeof n==`string`?vn(n):void 0;if(!i)throw Error(`Invalid target '${String(n)}' for route '${e}': use host:port`);return r===void 0?{target:i}:{target:i,proxyProtocol:r}},Rn=e=>{for(let[t,n]of Object.entries(e))Ln(t,n)},zn=e=>new Map(Object.entries(e).map(([e,t])=>[e,Ln(e,t)])),Bn=e=>Oe.createSecureContext({key:e.privateKey,cert:`${e.certificate}\n${e.chain}`}),Vn=(e,t)=>{let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((e,t)=>e===r[t])},Hn=e=>{let t=Math.min(fn.RECONNECT_BACKOFF_MIN_MS*2**Math.min(e,16),fn.RECONNECT_BACKOFF_MAX_MS);return Math.round(t/2+t/2*Math.random())};var Un=class{options;routes;resolved;identity;secureContext;refreshTimer;session;shutdown=!1;wake;status;ready;closed;constructor(e){this.options=e,this.resolved=zn(e.routes),this.routes={...e.routes},this.identity=e.identity,this.secureContext=Bn(e.identity),this.status={state:`connecting`,hostname:e.identity.hostname,routes:this.routes,connections:0};let t,n;this.ready=new Promise((e,r)=>{t=e,n=r}),this.closed=this.run(t).then(()=>t(),e=>{throw n(e),e}),this.ready.catch(()=>void 0),this.refreshCertificate()}async refreshCertificate(){if(this.shutdown)return;try{let e=new URL(`/api/tunnel/${encodeURIComponent(this.identity.id)}/certificate`,this.options.api),t=await fetch(e,{headers:{authorization:`Bearer ${this.identity.token}`}}),n=(t.ok?await t.json():void 0)?.state;if(n?.type===`ready`&&n.certificate&&n.expiry&&n.certificate!==this.identity.certificate){let e={...this.identity,certificate:n.certificate,chain:n.chain??``,certificateExpiry:new Date(n.expiry)};this.secureContext=Bn(e),this.identity=e,this.options.onRenewed?.(e),this.emit({type:`certificate-renewed`,expiry:n.expiry})}}catch{}if(this.shutdown)return;let e=this.identity.certificateExpiry.getTime()-Date.now()<2592e6;this.refreshTimer=setTimeout(()=>void this.refreshCertificate(),e?6e4:432e5),this.refreshTimer.unref?.()}getStatus(){return{...this.status,routes:{...this.status.routes}}}setRoutes(e){let t=zn(e),n=this.routes;this.resolved=t,this.routes={...e},this.status.routes=this.routes,Vn(n,this.routes)||this.session?.end({type:`routes-changed`}),this.wake?.()}close(){return this.shutdown=!0,clearTimeout(this.refreshTimer),this.session?.end({type:`shutdown`}),this.wake?.(),this.closed.catch(()=>void 0)}emit(e){this.options.onEvent(e)}sleep(e){return new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),t()}this.wake=r}).finally(()=>{this.wake=void 0})}async run(e){let t=0;try{for(;!this.shutdown;){if(Object.keys(this.routes).length===0){this.status.state=`waiting-routes`,await this.sleep(2**31-1);continue}this.status.state=`connecting`,this.emit({type:`connecting`,attempt:t});let n=new Wn(this.options,this.routes,()=>this.secureContext,{emit:e=>this.emit(e),route:e=>this.resolved.get(e),attached:t=>{this.status.state=`connected`,this.status.session=t,this.status.lastError=void 0,this.status.connectedAt=Date.now(),e()},connections:e=>{this.status.connections=e}});this.session=n;let r=await n.run();if(this.session=void 0,this.status.session=void 0,this.status.connections=0,r.type===`shutdown`)break;if(r.type===`fatal`)throw r.error;if(r.type===`routes-changed`){this.emit({type:`disconnected`,reason:`routes changed`}),t=0;continue}r.attached&&(t=0),this.emit({type:`disconnected`,reason:r.error});let i=Hn(t);t++,this.status.state=`reconnecting`,this.status.lastError=r.error,this.emit({type:`reconnecting`,attempt:t,delayMs:i}),await this.sleep(i)}this.status.state=`stopped`,this.emit({type:`stopped`})}catch(e){throw this.status.state=`stopped`,this.status.lastError=e instanceof Error?e.message:String(e),this.emit({type:`stopped`,error:this.status.lastError}),e}}},Wn=class{options;routes;secureContext;hooks;socket;finish;channels=/* @__PURE__ */ new Map;drainWaiters=[];drainTimer;heartbeat;attachTimeout;lastReceived=Date.now();attached=!1;constructor(e,t,n,r){this.options=e,this.routes=t,this.secureContext=n,this.hooks=r}run(){return new Promise(e=>{this.finish=e;let t=new URL(`/api/tunnel/${encodeURIComponent(this.options.identity.id)}/connect`,this.options.api);t.protocol=t.protocol===`https:`?`wss:`:`ws:`;let n=new Nn(t,{protocols:[`opentunnel`],headers:{"user-agent":It}});n.binaryType=`arraybuffer`,this.socket=n,this.attachTimeout=setTimeout(()=>this.end({type:`retry`,error:`bridge attach timed out`,attached:!1}),fn.CONNECT_TIMEOUT_MS),n.addEventListener(`open`,()=>{this.sendControl({type:`attach`,token:this.options.identity.token,transport:`ws`,routes:Object.keys(this.routes).sort(),client:{version:`0.1.0`,max_conns:256}})}),n.addEventListener(`message`,e=>{this.lastReceived=Date.now(),typeof e.data==`string`?this.onControl(e.data):this.onData(new Uint8Array(e.data))}),n.addEventListener(`close`,e=>{let t=`${e.code} ${e.reason}`.trim();this.end({type:`retry`,error:`bridge closed: ${t}`,attached:this.attached})})})}end(e){let t=this.finish;if(t){this.finish=void 0,clearTimeout(this.attachTimeout),clearInterval(this.heartbeat),clearInterval(this.drainTimer);for(let e of this.drainWaiters.splice(0))e();for(let e of[...this.channels.values()])e.destroy(`bridge disconnected`);this.socket&&this.socket.readyState<=WebSocket.OPEN&&this.socket.close(1e3),t(e)}}onControl(e){let t=dn(e);if(pe.isNone(t))return;let n=t.value;if(this.attached)switch(n.type){case`open`:return this.open(n.conn,n.sni,n.peer);case`end`:return this.channels.get(n.conn)?.endInbound();case`reset`:return this.channels.get(n.conn)?.destroy(n.code,!1);case`ping`:return this.sendControl({type:`pong`,time_sent:n.time_sent});case`drain`:return this.end({type:`retry`,error:`server draining: ${n.reason}`,attached:!0})}else if(n.type===`attached`){this.attached=!0,clearTimeout(this.attachTimeout);let e=Math.max(n.heartbeat_ms,1e3),t=Math.max(n.idle_timeout_ms,5e3);this.heartbeat=setInterval(()=>{Date.now()-this.lastReceived>t?this.end({type:`retry`,error:`bridge idle timeout`,attached:!0}):this.sendControl({type:`ping`,time_sent:Date.now()})},e),this.hooks.attached(n.session),this.hooks.emit({type:`connected`,session:n.session,routes:[...n.routes]})}else n.type===`attach_error`&&this.end(Fn.has(n.code)?{type:`fatal`,error:new Pn(n.code)}:{type:`retry`,error:`attach failed: ${n.code}`,attached:!1})}onData(e){let t=pn(e);t&&this.channels.get(t.conn)?.push(t.payload)}open(e,t,n){let r=_n(t,this.options.identity.hostname),i=r===void 0?void 0:this.hooks.route(r);if(r===void 0||!i){this.sendControl({type:`reset`,conn:e,code:q.UNKNOWN_ROUTE});return}if(this.channels.size>=256){this.sendControl({type:`reset`,conn:e,code:q.TOO_MANY_CONNECTIONS});return}let a=i.proxyProtocol===void 0?void 0:An(i.proxyProtocol,n,t),o=new Gn(e,r,i.target,a,this.secureContext(),this);this.channels.set(e,o),this.hooks.connections(this.channels.size),this.hooks.emit({type:`connection-opened`,conn:e,route:r,peer:n})}closed(e,t){this.channels.get(e.conn)===e&&(this.channels.delete(e.conn),this.hooks.connections(this.channels.size),this.hooks.emit({type:`connection-closed`,conn:e.conn,route:e.route,...t===void 0?{}:{error:t}}))}sendControl(e){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}sendData(e,t,n){let r=this.socket;if(!this.finish||r?.readyState!==WebSocket.OPEN)n(/* @__PURE__ */ Error(`bridge closed`));else{for(let n=0;n<t.byteLength;n+=J.MAX_PAYLOAD_SIZE){let i=t.subarray(n,n+J.MAX_PAYLOAD_SIZE);r.send(mn(e,i))}r.bufferedAmount<1048576?n():(this.drainWaiters.push(()=>n()),this.drainTimer??=setInterval(()=>{if(!(this.socket&&this.socket.bufferedAmount>262144&&this.finish)){clearInterval(this.drainTimer),this.drainTimer=void 0;for(let e of this.drainWaiters.splice(0))e()}},5))}}},Gn=class{conn;route;session;raw;tls;upstream;done=!1;constructor(e,t,n,r,i,a){this.conn=e,this.route=t,this.session=a,this.raw=new De({allowHalfOpen:!0,read(){},write:(t,n,r)=>a.sendData(e,t,r),final:t=>{a.sendControl({type:`end`,conn:e}),t()}}),this.tls=new Oe.TLSSocket(this.raw,{isServer:!0,secureContext:i}),this.tls.on(`secure`,()=>{let e=Ee.connect({host:n.host,port:n.port,allowHalfOpen:!0});this.upstream=e,e.setNoDelay(!0),r&&e.write(r),e.on(`error`,t=>this.destroy(e.connecting?q.UPSTREAM_CONNECT_FAILED:q.UPSTREAM_IO_ERROR,!0,t.message)),this.tls.pipe(e),e.pipe(this.tls)}),this.tls.on(`error`,e=>this.destroy(q.UPSTREAM_IO_ERROR,!0,e.message)),this.tls.on(`close`,()=>this.finish(void 0))}push(e){this.done||(this.raw.readableLength>8388608?this.destroy(q.UPSTREAM_IO_ERROR,!0,`local connection stalled`):this.raw.push(e))}endInbound(){this.done||this.raw.push(null)}destroy(e,t=!0,n=e){this.done||(t&&this.session.sendControl({type:`reset`,conn:this.conn,code:e}),this.finish(n))}finish(e){this.done||(this.done=!0,this.upstream?.destroy(),this.tls.destroy(),this.raw.destroy(),this.session.closed(this,e))}};const Y=e=>e?.profile??`default`,Kn=e=>{if(_e.isHttpClientError(e)){let t=e.response;if(!t)return e.message;let n=ft(t.status,``);return n.startsWith(`HTTP `)?n:`${n} (HTTP ${t.status})`}if(typeof e==`object`&&e){let{_tag:t,message:n}=e;if(typeof t==`string`&&typeof n==`string`)return`${t}: ${n}`}return e instanceof Error?e.message:void 0},X=(e,t)=>{let n=Kn(t);return new Yt({message:n?`${e}: ${n}`:e,cause:t})},qn=e=>_e.isHttpClientError(e)&&(e.reason._tag===`TransportError`||e.response!==void 0&&ct(e.response.status,`idempotent`)),Jn=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);let r=btoa(n);return`-----BEGIN PRIVATE KEY-----\n${r.match(/.{1,64}/g)?.join(`
|
|
6
|
-
`)??r}\n-----END PRIVATE KEY-----\n`};var Yn=class e extends fe.Service()(`@opentunnel/client/OpenTunnelClient`){static layer(t={}){let n=t.storage??Xt();return T.effect(e,w.gen(function*(){let e=yield*Ht,r=new URL(t.api??`https://opentunnel.xyz`),i=w.fn(`OpenTunnelClient.tunnel.get`)(function*(e){return yield*n.load(Y(e))}),a=w.fn(`OpenTunnelClient.tunnel.completePending`)(function*(t){let r=yield*e.authorized(z.make(t.pending.token));yield*w.sync(()=>t.onProgress?.(`requesting-certificate`)),yield*r.tunnel[`tunnel.bindCertificate`]({params:{id:R.make(t.pending.id)},payload:{csr:t.pending.csr}}).pipe(w.catchTag(`CertificateInProgressError`,()=>w.void),w.mapError(e=>X(`Failed to start certificate issuance`,e)));let i=yield*w.gen(function*(){for(;;){yield*w.sync(()=>t.onProgress?.(`waiting-certificate`));let e=yield*r.tunnel[`tunnel.getCertificate`]({params:{id:R.make(t.pending.id)}}).pipe(w.mapError(e=>X(`Failed to read certificate`,e)));if(e.state.type===`ready`)return e.state;if(e.state.type===`failed`)return yield*new Yt({message:`Certificate issuance failed: ${e.state.reason}`});yield*w.sleep(`2 seconds`)}}),a={id:t.pending.id,hostname:t.pending.hostname,token:t.pending.token,privateKey:t.pending.privateKey,certificate:i.certificate,chain:i.chain,certificateExpiry:new Date(i.expiry)};return yield*w.sync(()=>t.onProgress?.(`saving-identity`)),yield*n.save(t.profile,a),yield*w.sync(()=>t.onProgress?.(`ready`)),a}),o=w.fn(`OpenTunnelClient.tunnel.provision`)(function*(e){yield*w.sync(()=>e.onProgress?.(`generating-key`));let t=yield*w.tryPromise({try:()=>crypto.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!0,[`sign`,`verify`]),catch:e=>X(`Failed to generate certificate key`,e)});yield*w.sync(()=>e.onProgress?.(`generating-csr`));let r=yield*w.tryPromise({try:()=>Jt(e.hostname,t),catch:e=>X(`Failed to generate certificate request`,e)}),i=yield*w.tryPromise({try:()=>crypto.subtle.exportKey(`pkcs8`,t.privateKey),catch:e=>X(`Failed to export certificate key`,e)}),o={id:String(e.id),hostname:e.hostname,token:e.token,privateKey:Jn(i),csr:r};return yield*n.savePending(e.profile,o),yield*a({profile:e.profile,pending:o,onProgress:e.onProgress})}),s=w.fn(`OpenTunnelClient.tunnel.create`)(function*(t){let r=Y(t);if(yield*n.load(r))return yield*new Yt({message:`Profile '${r}' already has a tunnel`});let i=yield*n.loadPending(r);if(i)return yield*w.sync(()=>t?.onProgress?.(`resuming-certificate`)),yield*a({profile:r,pending:i,onProgress:t?.onProgress});yield*w.sync(()=>t?.onProgress?.(`creating-tunnel`));let s=yield*e.client.tunnel[`tunnel.create`]({payload:{}}).pipe(w.mapError(e=>X(`Failed to create tunnel`,e)));return yield*o({profile:r,id:s.tunnel.id,hostname:String(s.tunnel.hostname),token:s.token,onProgress:t?.onProgress})}),c=w.fn(`OpenTunnelClient.tunnel.ensure`)(function*(t){let r=yield*i(t);if(!r)return yield*s(t);let a=yield*(yield*e.authorized(z.make(r.token))).tunnel[`tunnel.getCertificate`]({params:{id:R.make(r.id)}}).pipe(w.catchIf(e=>qn(e)&&r.certificateExpiry.getTime()>Date.now(),()=>w.succeed(void 0)),w.mapError(e=>X(`Failed to read certificate`,e)));if(!a)return r;let c=a.state;if(c.type===`ready`&&c.certificate!==r.certificate){let e={...r,certificate:c.certificate,chain:c.chain,certificateExpiry:new Date(c.expiry)};return yield*n.save(Y(t),e),e}return c.type===`failed`?yield*o({profile:Y(t),id:R.make(r.id),hostname:r.hostname,token:z.make(r.token)}):r}),l=w.fn(`OpenTunnelClient.tunnel.pending`)(function*(e){let t=yield*n.loadPending(Y(e));return t?{id:t.id,hostname:t.hostname}:void 0}),u=w.fn(`OpenTunnelClient.tunnel.resume`)(function*(e){let t=Y(e),r=yield*n.loadPending(t);if(r)return yield*w.sync(()=>e?.onProgress?.(`resuming-certificate`)),yield*a({profile:t,pending:r,onProgress:e?.onProgress})});return{profile:{list:n.profiles},tunnel:{list:n.list,get:i,pending:l,resume:u,create:s,ensure:c,remove:w.fn(`OpenTunnelClient.tunnel.remove`)(function*(t){let r=Y(t),i=yield*n.load(r);i&&(yield*(yield*e.authorized(z.make(i.token))).tunnel[`tunnel.remove`]({params:{id:R.make(i.id)}}).pipe(w.mapError(e=>X(`Failed to remove tunnel`,e))),yield*n.remove(r))}),connect:w.fn(`OpenTunnelClient.tunnel.connect`)(function*(e){yield*w.try({try:()=>Rn(e.routes),catch:e=>X(e instanceof Error?e.message:`Invalid routes`,e)});let t=yield*c(e),i=yield*E.unbounded(),a=yield*w.acquireRelease(w.sync(()=>new Un({api:r,identity:t,routes:e.routes,onEvent:e=>{E.offerUnsafe(i,e),e.type===`stopped`&&E.endUnsafe(i)},onRenewed:t=>{w.runFork(n.save(Y(e),t).pipe(w.ignore))}})),e=>w.promise(()=>e.close()).pipe(w.andThen(E.end(i))));return yield*w.tryPromise({try:()=>a.ready,catch:e=>X(`Failed to connect tunnel`,e)}),{tunnel:t,events:me.fromQueue(i),status:w.sync(()=>a.getStatus()),setRoutes:e=>w.try({try:()=>a.setRoutes(e),catch:e=>X(e instanceof Error?e.message:`Invalid routes`,e)}),closed:w.tryPromise({try:()=>a.closed,catch:e=>X(`Tunnel stopped`,e)}),close:w.promise(()=>a.close())}})}}})).pipe(T.provide(Ht.layer({api:t.api??`https://opentunnel.xyz`})))}};const Xn=r.Union([r.Struct({jsonrpc:r.Literal(`2.0`),id:M.RequestId,result:r.Unknown}),r.Struct({jsonrpc:r.Literal(`2.0`),id:M.RequestId.pipe(r.NullOr),error:M.McpErrorBase}),r.Struct({jsonrpc:r.Literal(`2.0`),method:r.String,params:r.Unknown.pipe(r.optionalKey)})]),Zn=Xn.pipe(r.fromJsonString),Qn=r.decodeEffect(Zn),$n=j.v2025_06_18.protocolVersion;var Z=class extends r.TaggedError()(`OrbitMcpError`,{message:r.String}){};const er=r.is(Z);function tr(e){return Z.make({message:`Orbit HTTP ${e.status}: authorization rejected. Run tlo-mcp login; a 403 can also mean insufficient rights.`})}var Q=class extends l.Service()(`@2digits/tlo-mcp/mcp/OrbitClient`){};const nr=p.effect(Q,n.gen(function*(){let e=yield*L,t=(yield*_.HttpClient).pipe(_.withScope,_.transformResponse(n.flatMap(Ie.matchStatus({"2xx":e=>n.succeed(e),401:tr,403:tr,429:e=>Z.make({message:`Orbit rate limited. Retry after ${e.headers[`retry-after`]??`the server cooldown`}; request not replayed.`}),orElse:e=>Z.make({message:`Orbit HTTP ${e.status}. Request not replayed.`})})))),i=0,a,o=n.fn(`OrbitClient.send`)(function*(r,o,s=!1){let c=++i,l=yield*e.accessToken,u=yield*v.post(N).pipe(v.bearerToken(l),v.setHeader(`accept`,`application/json, text/event-stream`),v.setHeader(`mcp-protocol-version`,$n),e=>a===void 0?e:v.setHeader(e,`mcp-session-id`,a),v.bodyJson({jsonrpc:`2.0`,...s?{}:{id:c},method:r,params:o})),d=yield*t.execute(u),f=d.headers[`mcp-session-id`];if(r===`initialize`&&(a=f),s)return;let p=d.headers[`content-type`]?.startsWith(`text/event-stream`)?yield*d.stream.pipe(C.decodeText(),C.pipeThroughChannel(Fe.decode({maxEventSize:10485760})),C.filter(e=>e.event===`message`||e.event===``),C.map(Pe.get(`data`)),C.mapEffect(e=>Qn(e)),C.filter(e=>`id`in e&&e.id===c),C.runHead,n.flatMap(Ne.match({onNone:()=>Z.make({message:`Orbit stream ended before replying.`}),onSome:n.succeed}))):yield*Ie.schemaBodyJson(Xn)(d);return!(`id`in p)||p.id!==c?yield*Z.make({message:`Unexpected Orbit response ID.`}):`error`in p?yield*Z.make({message:p.error.message}):p.result},n.timeout(`120 seconds`),n.scoped,n.provideService(g.RequestInit,{redirect:`error`}),n.mapError(e=>er(e)?e:Z.make({message:`Orbit connection or response failed. Request not replayed.`}))),s=yield*o(`initialize`,{protocolVersion:$n,capabilities:{},clientInfo:{name:`@2digits/tlo-mcp`,version:`0.1.38`}}).pipe(n.flatMap(r.decodeUnknownEffect(M.InitializeResult)));if(s.protocolVersion!==$n)return yield*Z.make({message:`Unsupported upstream MCP protocol: ${s.protocolVersion}.`});yield*o(`notifications/initialized`,{},!0);let c=/* @__PURE__ */ new Set,l=yield*C.paginate(void 0,n.fn(`OrbitClient.listToolsPage`)(function*(e){let t=yield*o(`tools/list`,e===void 0?{}:{cursor:e}).pipe(n.flatMap(r.decodeUnknownEffect(M.ListToolsResult)));if(t.nextCursor!==void 0){if(c.has(t.nextCursor))return yield*Z.make({message:`Orbit returned a repeated tools cursor.`});c.add(t.nextCursor)}return[t.tools,Ne.fromUndefinedOr(t.nextCursor)]})).pipe(C.runCollect);return Q.of({tools:l,instructions:s.instructions,callTool:n.fn(`OrbitClient.callTool`)(function*(e,t){return yield*o(`tools/call`,{name:e,arguments:t})},n.flatMap(r.decodeUnknownEffect(M.CallToolResult)),n.catchTag(`SchemaError`,()=>Z.make({message:`Invalid Orbit tool result. Request not replayed.`})))})})).pipe(p.provide(g.layer)),rr=r.decodeUnknownEffect(r.JsonObject),ir=p.effectDiscard(n.gen(function*(){let e=yield*Q,t=yield*Ae.McpServer;yield*n.forEach(e.tools,n.fn(`OrbitProxyLive.tool`)(function*(r){yield*t.addTool({tool:r,annotations:l.empty(),handle:n.fn(`handle`)(function*(e){return yield*rr(e)},n.mapError(e=>M.InvalidParams.make({message:`Tool arguments must be a JSON object.`,data:e})),n.flatMap(t=>e.callTool(r.name,t).pipe(n.mapError(e=>M.InternalError.make({message:e.message})))))})}),{discard:!0})})),ar=`${le()}/.config/2digits/tlo-mcp/gateway.key`,or=ke.mebibytes(1),sr=S.empty({status:401,headers:{"www-authenticate":`Bearer`,"cache-control":`no-store`}}),cr=S.empty({status:403,headers:{"cache-control":`no-store`}}),lr=new TextEncoder,ur=r.String.check(r.isPattern(/^[a-f0-9]{64}$/)).pipe(r.RedactedFromValue);var $=class extends r.TaggedError()(`GatewayError`,{message:r.String}){};const dr=n.fn(`Gateway.loadKey`)(function*(e){let t=yield*ue.FileSystem,i=yield*u.Crypto,a=(yield*de.Path).dirname(e);yield*t.makeDirectory(a,{recursive:!0,mode:448}),yield*t.chmod(a,448);let o=yield*i.randomBytes(32);yield*t.writeFileString(e,je.encode(o),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>n.void));let s=yield*t.stat(e);return s.type!==`File`||s.mode&63?yield*$.make({message:`Gateway key must be a private file (chmod 600).`}):yield*t.readFileString(e).pipe(n.flatMap(r.decodeEffect(ur)))},n.mapError(()=>$.make({message:`Cannot load private gateway key. Check its permissions and format.`})));function fr(e,t){return e.digest(`SHA-256`,lr.encode(t)).pipe(n.orDie)}function pr(e){return p.unwrap(n.gen(function*(){let t=yield*u.Crypto,r=yield*fr(t,`Bearer ${h.value(e)}`);return x.middleware(e=>n.gen(function*(){let i=yield*se.HttpServerRequest,a=yield*fr(t,i.headers.authorization??``);return ne(r,a)?i.headers.origin===void 0?yield*e.pipe(n.provideService(Me.MaxBodySize,or),n.map(e=>S.setHeader(e,`cache-control`,`no-store`))):cr:sr}),{global:!0})}))}function mr(e){let t=p.unwrap(n.gen(function*(){let e=yield*Q;return ir.pipe(p.provide(Ae.layerHttp({name:`tlo-mcp`,version:`1.0.0`,instructions:e.instructions,path:`/mcp`,protocols:[j.v2025_11_25,j.v2025_06_18,j.v2025_03_26]})))}));return p.merge(t,pr(e))}const hr=r.String.check(r.isPattern(/^[a-z0-9]+\.opentunnel\.xyz$/)),gr=r.decodeEffect(hr),_r=n.fn(`Gateway.openTunnel`)(function*(e){let t=yield*(yield*Yn).tunnel.connect({profile:`tlo-mcp`,routes:{tlo:`127.0.0.1:${e}`}}),r=yield*gr(t.tunnel.hostname);return yield*t.events.pipe(C.filter(e=>e.type===`reconnecting`),C.runForEach(()=>n.sync(()=>process.stderr.write(`OpenTunnel reconnecting...
|
|
7
|
-
`))),n.forkScoped),{endpoint:`https://tlo.${r}/mcp`,closed:t.closed.pipe(n.mapError(()=>$.make({message:`OpenTunnel stopped unexpectedly. Restart tlo-mcp.`})))}},n.timeout(`180 seconds`),n.mapError(()=>$.make({message:`Could not connect OpenTunnel. Check network access and retry; existing tunnel identity is preserved.`})));function
|
|
2
|
+
import*as e from"@effect/platform-node/NodeRuntime";import*as t from"@effect/platform-node/NodeServices";import*as n from"effect/Effect";import*as r from"effect/Schema";import*as i from"effect/cli/Command";import*as a from"effect/cli/Flag";import*as o from"@yielded/oauth/OAuth";import*as s from"@yielded/oauth/Pkce";import*as c from"effect/Clock";import*as l from"effect/Context";import*as u from"effect/Crypto";import*as d from"effect/Equal";import*as f from"effect/Exit";import*as p from"effect/Layer";import*as m from"effect/Match";import*as h from"effect/Redacted";import*as ee from"effect/Semaphore";import*as g from"effect/http/FetchHttpClient";import*as _ from"effect/http/HttpClient";import*as v from"effect/http/HttpClientRequest";import*as te from"effect/process/ChildProcess";import*as y from"effect/process/ChildProcessSpawner";import{timingSafeEqual as ne}from"node:crypto";import{createServer as re}from"node:http";import*as ie from"@effect/platform-node/NodeHttpServer";import*as b from"effect/Deferred";import*as ae from"effect/Predicate";import*as x from"effect/http/HttpRouter";import*as oe from"effect/http/HttpServer";import*as se from"effect/http/HttpServerRequest";import*as S from"effect/http/HttpServerResponse";import*as ce from"node:os";import{homedir as le}from"node:os";import*as ue from"effect/FileSystem";import*as de from"effect/Path";import*as C from"effect/Stream";import*as w from"effect/String";import{Context as fe,Effect as T,Layer as pe,Option as me,Queue as he,Schema as E,Stream as ge}from"effect";import{FetchHttpClient as _e,HttpClient as D,HttpClientError as ve,HttpClientRequest as ye}from"effect/http";import{HttpApi as be,HttpApiClient as xe,HttpApiEndpoint as O,HttpApiGroup as Se,HttpApiMiddleware as Ce,HttpApiSchema as we,HttpApiSecurity as Te,OpenApi as Ee}from"effect/http-api";import*as k from"node:fs/promises";import*as A from"node:path";import*as De from"node:net";import{Duplex as Oe}from"node:stream";import*as ke from"node:tls";import*as Ae from"effect/ByteSize";import*as j from"effect/ai/McpProtocol";import*as je from"effect/ai/McpServer";import*as Me from"effect/encoding/Hex";import*as Ne from"effect/http/HttpIncomingMessage";import*as Pe from"effect/Option";import*as Fe from"effect/Struct";import*as M from"effect/ai/McpSchema";import*as Ie from"effect/encoding/Sse";import*as Le from"effect/http/HttpClientResponse";const Re=`https://api.orbit.teamleader.eu`,N=`${Re}/mcp`,ze=r.String.check(r.isMinLength(1)).pipe(r.RedactedFromValue);var P=class extends r.Class(`Session`)({clientId:r.String.check(r.isMinLength(1)),clientSecret:ze.pipe(r.optionalKey),accessToken:ze,refreshToken:ze.pipe(r.optionalKey),expiresAt:r.Finite.pipe(r.optionalKey)}){static update(e,t,n){let r=t.refreshToken??e.refreshToken;return this.make({clientId:e.clientId,...e.clientSecret===void 0?{}:{clientSecret:e.clientSecret},accessToken:t.accessToken,...r===void 0?{}:{refreshToken:r},...t.expiresIn===void 0?{}:{expiresAt:n+t.expiresIn*1e3}})}static needsRefresh(e,t){return e.expiresAt===void 0||e.expiresAt<=t+6e4}},F=class extends r.TaggedError()(`OrbitAuthError`,{message:r.String}){};function Be(e){return e.clientSecret===void 0?{method:`none`,publicClient:!0}:{method:`client_secret_post`,secret:e.clientSecret.pipe(h.value,h.make)}}const Ve={"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,"referrer-policy":`no-referrer`,"content-security-policy":`default-src 'none'`},I=S.text(`Invalid callback.`,{status:400,headers:Ve}),He=S.text(`Authorization received. Return to your terminal to complete login.`,{headers:Ve}),Ue=S.text(`Authorization denied. Return to your terminal.`,{status:400,headers:Ve});function We(e,t){let n=e.searchParams.getAll(t);return n.length===1?n[0]:void 0}function Ge(e,t){let n=We(e,`state`);if(n===void 0||e.pathname!==`/callback`)return;let r=Buffer.from(t),i=Buffer.from(n);if(r.length!==i.length||!ne(r,i))return;if(e.searchParams.has(`error`))throw Error(`Orbit authorization was denied.`);let a=We(e,`code`);return a===``?void 0:a}const Ke=n.fn(`OrbitAuth.listenForLogin`)(function*(e){let t=yield*b.make(),r=yield*n.sync(re),i=yield*ie.make(()=>r,{port:0,host:`127.0.0.1`}).pipe(n.mapError(()=>F.make({message:`Could not bind OAuth callback.`})));if(!ae.isTagged(i.address,`InetAddressV4`))return yield*F.make({message:`Could not bind OAuth callback.`});let a=`127.0.0.1:${i.address.port}`,o=`http://${a}/callback`,s=n.fn(`OrbitAuth.handleCallback`)(function*(){let r=yield*se.HttpServerRequest;return r.method!==`GET`||r.headers.host!==a||(yield*b.isDone(t))?I:yield*n.try({try:()=>Ge(new URL(r.url,o),e),catch:()=>F.make({message:`Orbit authorization was denied.`})}).pipe(n.matchEffect({onFailure:e=>b.fail(t,e).pipe(n.map(e=>e?Ue:I)),onSuccess:e=>e===void 0?n.succeed(I):b.succeed(t,e).pipe(n.map(e=>e?He:I))}))}),c=yield*x.toHttpEffect(x.add(`*`,`*`,s()));return yield*oe.serveEffect(c).pipe(n.provideService(oe.HttpServer,i)),yield*n.addFinalizer(()=>n.sync(()=>r.closeAllConnections())),{redirectUri:o,code:b.await(t).pipe(n.timeout(`3 minutes`),n.mapError(()=>F.make({message:`Login denied or timed out. Run tlo-mcp login again.`})))}}),qe=P.pipe(r.fromJsonString),Je=r.decodeEffect(qe),Ye=r.encodeEffect(qe),Xe=`@2digits/tlo-mcp/orbit`,Ze=[`-a`,`orbit`,`-s`,Xe];var L=class extends l.Service()(`@2digits/tlo-mcp/oauth/store/SessionStore`){};function Qe(e){return`"${w.replaceAll(/["\\]/g,w.String.raw`\$&`)(e)}"`}function $e(e={}){return p.effect(L,n.gen(function*(){let t=yield*ue.FileSystem,r=yield*de.Path,i=yield*y.ChildProcessSpawner,a=e.platform??process.platform,o=e.directory??r.join(le(),`.config`,`2digits`,`tlo-mcp`),s=r.join(o,`session.json`),c=r.join(o,`session.lock`),l=t.makeDirectory(o,{recursive:!0,mode:448}).pipe(n.andThen(t.chmod(o,448))),u=n.fn(`SessionStore.security`)(function*(e,t){let r=yield*i.spawn(te.make(`/usr/bin/security`,e,{stdin:t===void 0?`ignore`:C.succeed(new TextEncoder().encode(t)),stderr:`ignore`}));return yield*n.all({output:r.stdout.pipe(C.decodeText(),C.mkString),exitCode:r.exitCode},{concurrency:`unbounded`})},n.scoped),d=n.fn(`SessionStore.load`)(function*(){if(a===`darwin`){let e=yield*u([`find-generic-password`,...Ze,`-w`]);return e.exitCode===44?void 0:e.exitCode===0?yield*Je(w.trim(e.output)):yield*F.make({message:`Could not read macOS Keychain.`})}let e=yield*t.readFileString(s).pipe(n.catchReason(`PlatformError`,`NotFound`,()=>n.undefined));return e===void 0?void 0:yield*Je(e)},n.mapError(()=>F.make({message:`Could not read credentials. Run tlo-mcp login again.`}))),f=n.fn(`SessionStore.save`)(function*(e){let n=yield*Ye(e);if(a===`darwin`){if((yield*u([`-q`,`-i`],`add-generic-password -U -a orbit -s ${Qe(Xe)} -w ${Qe(n)}\n`)).exitCode!==0)return yield*F.make({message:`Could not save macOS Keychain credentials.`})}else{yield*l;let e=yield*t.makeTempDirectoryScoped({directory:o,prefix:`session-`}),i=r.join(e,`session.json`);yield*t.writeFileString(i,n,{mode:384}),yield*t.rename(i,s)}},n.scoped,n.mapError(()=>F.make({message:`Could not persist OAuth credentials. Run tlo-mcp login again.`}))),p=n.fn(`SessionStore.clear`)(function*(){if(a===`darwin`){let e=yield*u([`delete-generic-password`,...Ze]);if(e.exitCode!==0&&e.exitCode!==44)return yield*F.make({message:`Could not remove Keychain credentials.`})}else yield*t.remove(s,{force:!0})},n.mapError(()=>F.make({message:`Could not remove OAuth credentials.`}))),m=n.fn(`SessionStore.lock`)(function*(){yield*l,yield*n.acquireRelease(t.writeFileString(c,process.pid.toString(),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>F.make({message:`OAuth credentials locked. Close other login/refresh processes. After a crash only, remove ${c}.`}))),()=>t.remove(c).pipe(n.orDie))},n.catchTag(`PlatformError`,()=>F.make({message:`Could not acquire OAuth credential lock. Check directory permissions.`})));return L.of({load:d(),save:f,clear:p(),lock:m()})}))}const et=$e(),tt=r.Struct({client_id:r.String.check(r.isMinLength(1)),client_secret:r.String.check(r.isMinLength(1)).pipe(r.RedactedFromValue,r.optionalKey)}),nt=r.is(F),rt=te.make({stdout:`ignore`,stderr:`ignore`,forceKillAfter:`1 second`});var R=class extends l.Service()(`@2digits/tlo-mcp/oauth/OrbitAuth`){};const it=p.effect(R,n.gen(function*(){let e=yield*L,t=yield*u.Crypto,i=yield*_.HttpClient,a=yield*y.ChildProcessSpawner,l=yield*ee.make(1),p=yield*n.fn(`OrbitAuth.discover`)(function*(){let e=yield*_.withScope(i).get(`${Re}/.well-known/oauth-authorization-server`);if(e.status!==200)return yield*F.make({message:`Could not discover Orbit OAuth endpoints.`});let t=yield*e.json.pipe(n.flatMap(r.decodeUnknownEffect(o.Metadata)));return t.issuer!==`https://api.orbit.teamleader.eu`||t.authorization_endpoint!==`https://api.orbit.teamleader.eu/oauth2/Authorize`||t.token_endpoint!==`https://api.orbit.teamleader.eu/oauth2/access_token`?yield*F.make({message:`Unexpected Orbit endpoints; refusing to send credentials.`}):t},n.scoped,n.timeout(`15 seconds`),n.mapError(()=>F.make({message:`Invalid or unavailable Orbit OAuth metadata.`})))().pipe(n.cachedWithTTL(e=>f.isSuccess(e)?1/0:0)),te=n.fn(`OrbitAuth.accessToken`)(function*(){let t=yield*e.load;if(t===void 0)return yield*F.make({message:`Not authenticated. Run tlo-mcp login first.`});let r=yield*c.currentTimeMillis;if(!P.needsRefresh(t,r))return t.accessToken;if(t.refreshToken===void 0)return t.expiresAt===void 0?t.accessToken:yield*F.make({message:`Orbit session expired without a refresh token. Run tlo-mcp login.`});let i=yield*p,a=yield*(yield*o.make({metadata:i,clientId:t.clientId,authentication:Be(t),timeoutMs:15e3})).refreshGrant({refreshToken:t.refreshToken,resources:[N]}).pipe(n.flatMap(o.tokens)),s=P.update(t,a,yield*c.currentTimeMillis);return yield*e.save(s),s.accessToken}),ne=n.fn(`OrbitAuth.register`)(function*(e){let t=yield*v.post(`${Re}/oauth2/register`).pipe(v.bodyJson({client_name:`@2digits/tlo-mcp`,redirect_uris:[e],response_types:[`code`],grant_types:[`authorization_code`,`refresh_token`],token_endpoint_auth_method:`none`}),n.flatMap(_.withScope(i).execute));return t.status!==200&&t.status!==201?yield*F.make({message:`Orbit client registration failed (HTTP ${t.status}).`}):yield*t.json.pipe(n.flatMap(r.decodeUnknownEffect(tt)))},n.scoped,n.timeout(`15 seconds`)),re=n.fn(`OrbitAuth.openBrowser`)(function*(e){return yield*(yield*m.value(process.platform).pipe(m.when(`darwin`,()=>rt`open ${h.value(e)}`),m.when(`win32`,()=>rt`rundll32 url.dll,FileProtocolHandler ${h.value(e)}`),m.orElse(()=>rt`xdg-open ${h.value(e)}`))).exitCode},n.scoped,n.timeout(`5 seconds`),n.filterOrFail(d.equals(y.ExitCode(0)),()=>F.make({message:`Could not open browser.`})),(e,t)=>e.pipe(n.catch(()=>n.sync(()=>{process.stderr.write(`Open this URL in your browser:\n${h.value(t)}\n`)})))),ie=n.fn(`OrbitAuth.login`)(function*(){let t=yield*p,r=yield*s.random(),i=yield*s.make(),a=yield*r.pipe(h.value,Ke),l=yield*ne(a.redirectUri),u={clientId:l.client_id,...l.client_secret===void 0?{}:{clientSecret:l.client_secret}},d=yield*o.make({metadata:t,...u,authentication:Be(u),timeoutMs:15e3}),f=yield*d.authorizationUrl({redirectUri:a.redirectUri,scopes:[],state:r,codeChallenge:i.challenge,resources:[N]});yield*re(f);let m=yield*a.code,ee=yield*d.codeGrant({code:h.make(m),redirectUri:a.redirectUri,pkceVerifier:i.verifier,resources:[N]}).pipe(n.flatMap(o.tokens));yield*e.save(P.update(u,ee,yield*c.currentTimeMillis)),yield*n.sync(()=>{process.stderr.write(`Orbit login complete.
|
|
3
|
+
`)})}),b=n.fn(`OrbitAuth.locked`)(function*(t){return yield*e.lock,yield*t},n.scoped,l.withPermit,n.provideService(_.HttpClient,i),n.provideService(u.Crypto,t),n.provideService(y.ChildProcessSpawner,a),n.provideService(g.RequestInit,{redirect:`error`}),n.mapError(e=>nt(e)?e:F.make({message:`Orbit authentication unavailable. Check connectivity or run tlo-mcp login again.`})));return R.of({accessToken:b(te()),login:b(ie()),logout:b(e.clear)})})).pipe(p.provide(et),p.provide(g.layer)),at=8e3,ot=(e,t)=>t===`idempotent`?e===429||e>=500&&e<=599:[429,503,521,522,523,525].includes(e),st=(e,t)=>{let n=t?.trim();if(n&&/^\d+$/.test(n)){let e=Math.min(Number(n)*1e3,at);return[e,e]}let r=Math.min(250*2**Math.min(e,16),at);return[r/2,r]},ct={520:`the server returned an unknown error`,521:`the server refused the connection`,522:`the connection to the server timed out`,523:`the server is unreachable`,524:`the server did not answer in time`,525:`the SSL handshake with the server failed`,526:`the server's certificate is invalid`,527:`the connection to the server failed`},lt=e=>ct[e],ut=(e,t)=>{let n=lt(e);if(n)return`Cloudflare ${e}: ${n}`;let r=t.trim();return r?Array.from(r).slice(0,200).join(``):`HTTP ${e}`},dt=E.String.pipe(E.brand(`CSR.Raw`)),ft=E.String.pipe(E.brand(`Hostname`));function pt(){return(e,t)=>{class n{static makeUnsafe(e){return e}}return Object.setPrototypeOf(n,t),n}}var mt=class extends pt()(`CertificateID`,E.String){};E.String.pipe(E.brand(`ChallengeToken`));var ht=class extends E.Class(`Certificate/StateChallenge`)({type:E.Literal(`challenge`),token:E.String,key:E.String}){},gt=class extends E.Class(`Certificate/StateIssuing`)({type:E.Literal(`issuing`)}){},_t=class extends E.Class(`Certificate/StateReady`)({type:E.Literal(`ready`),certificate:E.String,chain:E.String,expiry:E.String}){},vt=class extends E.Class(`Certificate/StateFailed`)({type:E.Literal(`failed`),reason:E.String}){};const yt=E.Union([ht,gt,_t,vt]);var bt=class extends E.Class(`Certificate`)({id:mt,state:yt}){},z=class extends pt()(`TunnelID`,E.String){};const B=E.String.pipe(E.brand(`TunnelToken`));E.TaggedError()(`NotFound`,{tunnelID:z}),E.TaggedError()(`NoCertificate`,{tunnelID:z}),E.TaggedError()(`CertificateNotReady`,{tunnelID:z,currentState:E.String}),E.TaggedError()(`InvalidHostname`,{provided:ft,expected:ft});const xt=E.Literals([`offline`,`online`]);var St=class extends E.Class(`Tunnel/Info`)({id:z,hostname:ft,state:xt,certificateID:mt.pipe(E.optional)}){},Ct=`0.5.5`,wt=class extends E.TaggedError()(`InvalidRequestError`,{message:E.String},{httpApiStatus:400}){},Tt=class extends E.TaggedError()(`UnauthorizedError`,{message:E.String},{httpApiStatus:401}){},V=class extends E.TaggedError()(`TunnelNotFoundError`,{tunnelID:E.String,message:E.String},{httpApiStatus:404}){},Et=class extends E.TaggedError()(`CertificateNotFoundError`,{tunnelID:E.String,message:E.String},{httpApiStatus:404}){},Dt=class extends E.TaggedError()(`InvalidHostnameError`,{provided:E.String,expected:E.String,message:E.String},{httpApiStatus:400}){},Ot=class extends E.TaggedError()(`HostnameUnavailableError`,{name:E.String,message:E.String},{httpApiStatus:409}){},kt=class extends E.TaggedError()(`CertificateInProgressError`,{tunnelID:E.String,message:E.String},{httpApiStatus:409}){},H=class extends E.TaggedError()(`ServiceUnavailableError`,{message:E.String},{httpApiStatus:503}){};fe.Service()(`@opentunnel/protocol/OpenTunnelAuthorizationToken`);var U=class extends Ce.Service()(`@opentunnel/protocol/OpenTunnelAuthorization`,{security:{bearer:Te.bearer},error:Tt}){};const At=E.Struct({name:E.String.pipe(E.optional)}),jt=E.Struct({tunnel:St,token:B}).pipe(we.status(201)),Mt=Se.make(`tunnel`).add(O.post(`tunnel.create`,`/api/tunnel`,{payload:At,success:jt,error:[wt,Ot,H]})).add(O.get(`tunnel.get`,`/api/tunnel/:id`,{params:E.Struct({id:z}),success:St,error:[V,H]}).middleware(U)).add(O.post(`tunnel.bindCertificate`,`/api/tunnel/:id/certificate`,{params:E.Struct({id:z}),payload:E.Struct({csr:dt}),success:bt.pipe(we.status(202)),error:[wt,Dt,V,kt,H]}).middleware(U)).add(O.get(`tunnel.getCertificate`,`/api/tunnel/:id/certificate`,{params:E.Struct({id:z}),success:bt,error:[V,Et,H]}).middleware(U)).add(O.delete(`tunnel.remove`,`/api/tunnel/:id`,{params:E.Struct({id:z}),success:we.NoContent,error:[V,H]}).middleware(U)).add(O.get(`tunnel.connect`,`/api/tunnel/:id/connect`,{params:E.Struct({id:z}),success:E.Boolean,error:[V]}).annotateMerge(Ee.annotations({summary:`Connect a bridge WebSocket`,description:`This endpoint upgrades to the opentunnel WebSocket protocol.`}))).annotateMerge(Ee.annotations({title:`tunnel`})),Nt=be.make(`opentunnel`).add(Mt).annotateMerge(Ee.annotations({title:`OpenTunnel API`,version:`0.1.0`,description:`Create and manage blind TLS tunnels.`})),Pt=`opentunnel-sdk/${Ct}`,Ft=/* @__PURE__ */ new Set([`ConnectionRefused`,`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`FailedToOpenSocket`,`UND_ERR_CONNECT_TIMEOUT`]),It=e=>{if(typeof e!=`object`||!e)return;let{code:t,cause:n}=e;return typeof t==`string`?t:It(n)},Lt=e=>e.method===`GET`||e.method===`POST`&&e.url.endsWith(`/certificate`)?`idempotent`:`once`,Rt=(e,t)=>ve.isHttpClientError(e)&&e.reason._tag===`TransportError`&&(t===`idempotent`||Ft.has(It(e.reason.cause)??``)),zt=e=>D.transform(e,(e,t)=>{let n=Lt(t),r=(e,t)=>{let[n,r]=st(e,t);return T.sleep(n+Math.random()*(r-n))},i=t=>T.matchEffect(e,{onFailure:e=>t<6&&Rt(e,n)?T.andThen(r(t),()=>i(t+1)):T.fail(e),onSuccess:e=>t<6&&ot(e.status,n)?T.andThen(r(t,e.headers[`retry-after`]),()=>i(t+1)):T.succeed(e)});return i(0)});var Bt=class e extends fe.Service()(`@opentunnel/client/OpenTunnelApiClient`){static layer(t){return pe.effect(e,T.gen(function*(){let e=(yield*D.HttpClient).pipe(D.mapRequest(ye.setHeader(`user-agent`,Pt)),zt);return{client:yield*xe.makeWith(Nt,{baseUrl:t.api,httpClient:e}),authorized:n=>xe.makeWith(Nt,{baseUrl:t.api,httpClient:e.pipe(D.mapRequest(ye.bearerToken(n)))})}})).pipe(pe.provide(_e.layer))}};const W=(e,...t)=>{let n=Vt(t),r=n.length<128?[n.length]:(()=>{let e=[];for(let t=n.length;t>0;t>>=8)e.unshift(t&255);return[128|e.length,...e]})();return Vt([new Uint8Array([e,...r]),n])},Vt=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},G=(...e)=>W(48,...e),Ht=(...e)=>W(49,...e),Ut=e=>W(12,new TextEncoder().encode(e)),Wt=e=>W(130,new TextEncoder().encode(e)),K=e=>{let[t,n,...r]=e.split(`.`).map(Number),i=[t*40+n];for(let e of r){let t=[e&127];for(let n=e>>7;n>0;n>>=7)t.unshift(n&127|128);i.push(...t)}return W(6,new Uint8Array(i))},Gt=e=>{let t=0;for(;t<e.length-1&&e[t]===0;)t++;let n=e.subarray(t);return W(2,n[0]&128?Vt([new Uint8Array([0]),n]):n)};async function Kt(e,t){let n=new Uint8Array(await crypto.subtle.exportKey(`spki`,t.publicKey)),r=G(W(2,new Uint8Array([0])),G(Ht(G(K(`2.5.4.3`),Ut(e)))),n,W(160,G(K(`1.2.840.113549.1.9.14`),Ht(G(G(K(`2.5.29.17`),W(4,G(Wt(e),Wt(`*.${e}`))))))))),i=new Uint8Array(await crypto.subtle.sign({name:`ECDSA`,hash:`SHA-256`},t.privateKey,r)),a=G(Gt(i.subarray(0,32)),Gt(i.subarray(32))),o=G(r,G(K(`1.2.840.10045.4.3.2`)),W(3,new Uint8Array([0]),a));return`-----BEGIN CERTIFICATE REQUEST-----\n${Buffer.from(o).toString(`base64`).replace(/.{1,64}/g,`$&
|
|
4
|
+
`)}-----END CERTIFICATE REQUEST-----`}var qt=class extends E.TaggedError()(`OpenTunnelClientError`,{message:E.String,cause:E.optional(E.Defect())}){},q=class extends E.TaggedError()(`OpenTunnelStorageError`,{message:E.String,cause:E.optional(E.Defect())}){};function Jt(e={}){let t=e.env??process.env,n=e.home??ce.homedir(),r=t.XDG_DATA_HOME??A.join(n,`.local`,`share`),i=A.join(r,`opentunnel`),a=e=>A.join(i,e),o=e=>T.tryPromise({try:()=>k.readFile(e,`utf8`),catch:e=>e}).pipe(T.catch(t=>T.gen(function*(){if(!(typeof t==`object`&&t&&`code`in t&&t.code===`ENOENT`))return yield*new q({message:`Failed to read ${e}`,cause:t})}))),s=T.fn(`OpenTunnelStorage.profiles`)(function*(){return(yield*T.tryPromise({try:()=>k.readdir(i,{withFileTypes:!0}),catch:e=>e}).pipe(T.catch(e=>T.gen(function*(){return typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`?[]:yield*new q({message:`Failed to list ${i}`,cause:e})})))).filter(e=>e.isDirectory()).map(e=>e.name).sort()}),c=T.fn(`OpenTunnelStorage.load`)(function*(e){let t=a(e),n=yield*o(A.join(t,`tunnel.json`));if(!n)return;let[r,i,s,c]=yield*T.all([o(A.join(t,`token`)),o(A.join(t,`private-key.pem`)),o(A.join(t,`certificate.pem`)),o(A.join(t,`chain.pem`))]);if(!r||!i||!s||c===void 0)return yield*new q({message:`Incomplete tunnel identity for ${e}`});let l=JSON.parse(n);return{id:l.id,hostname:l.hostname,token:r.trim(),privateKey:i,certificate:s,chain:c,certificateExpiry:new Date(l.certificateExpiry)}}),l=T.fn(`OpenTunnelStorage.loadPending`)(function*(e){let t=a(e),n=yield*o(A.join(t,`pending.json`));if(!n)return;let[r,i]=yield*T.all([o(A.join(t,`token`)),o(A.join(t,`private-key.pem`))]);if(!r||!i)return yield*new q({message:`Incomplete pending tunnel identity for ${e}`});let s=JSON.parse(n);return{id:s.id,hostname:s.hostname,token:r.trim(),privateKey:i,csr:s.csr}});return{profiles:()=>s(),load:e=>c(e),loadPending:e=>l(e),savePending:(e,t)=>T.tryPromise({try:async()=>{let n=a(e);await k.mkdir(n,{recursive:!0,mode:448}),await Promise.all([k.writeFile(A.join(n,`pending.json`),JSON.stringify({id:t.id,hostname:t.hostname,csr:t.csr},null,2),{mode:384}),k.writeFile(A.join(n,`token`),`${t.token}\n`,{mode:384}),k.writeFile(A.join(n,`private-key.pem`),t.privateKey,{mode:384})])},catch:t=>new q({message:`Failed to save pending tunnel identity for ${e}`,cause:t})}),save:(e,t)=>T.tryPromise({try:async()=>{let n=a(e);await k.mkdir(n,{recursive:!0,mode:448}),await Promise.all([k.writeFile(A.join(n,`tunnel.json`),JSON.stringify({id:t.id,hostname:t.hostname,certificateExpiry:t.certificateExpiry.toISOString()},null,2),{mode:384}),k.writeFile(A.join(n,`token`),`${t.token}\n`,{mode:384}),k.writeFile(A.join(n,`private-key.pem`),t.privateKey,{mode:384}),k.writeFile(A.join(n,`certificate.pem`),t.certificate,{mode:384}),k.writeFile(A.join(n,`chain.pem`),t.chain,{mode:384})]),await k.rm(A.join(n,`pending.json`),{force:!0})},catch:t=>new q({message:`Failed to save tunnel identity for ${e}`,cause:t})}),remove:e=>T.tryPromise({try:()=>k.rm(a(e),{recursive:!0,force:!0}),catch:t=>new q({message:`Failed to remove tunnel identity for ${e}`,cause:t})}),list:()=>s().pipe(T.flatMap(e=>T.forEach(e,e=>c(e).pipe(T.map(t=>t?{profile:e,tunnel:t}:void 0)))),T.map(e=>e.filter(e=>e!==void 0)))}}const Yt=E.Int.check(E.isBetween({minimum:0,maximum:4294967295}));var Xt=class extends E.Class(`BridgeProtocol/ClientInfo`)({version:E.String,max_conns:E.Number}){},Zt=class extends E.Class(`BridgeProtocol/AttachMessage`)({type:E.Literal(`attach`),token:E.String,transport:E.Literal(`ws`),client:Xt,routes:E.Array(E.String).pipe(E.optional)}){},Qt=class extends E.Class(`BridgeProtocol/AttachedMessage`)({type:E.Literal(`attached`),session:E.String,routes:E.Array(E.String),heartbeat_ms:E.Number,idle_timeout_ms:E.Number}){},$t=class extends E.Class(`BridgeProtocol/AttachErrorMessage`)({type:E.Literal(`attach_error`),code:E.String}){},en=class extends E.Class(`BridgeProtocol/PingMessage`)({type:E.Literal(`ping`),time_sent:E.Number}){},tn=class extends E.Class(`BridgeProtocol/PongMessage`)({type:E.Literal(`pong`),time_sent:E.Number}){},nn=class extends E.Class(`BridgeProtocol/DrainMessage`)({type:E.Literal(`drain`),reason:E.String}){},rn=class extends E.Class(`BridgeProtocol/OpenMessage`)({type:E.Literal(`open`),conn:Yt,peer:E.String,sni:E.String,alpn:E.String}){},an=class extends E.Class(`BridgeProtocol/EndMessage`)({type:E.Literal(`end`),conn:Yt}){},on=class extends E.Class(`BridgeProtocol/ResetMessage`)({type:E.Literal(`reset`),conn:Yt,code:E.String}){};E.Union([Zt,en,tn,nn,an,on]);const sn=E.Union([Qt,$t,en,tn,nn,rn,an,on]),cn=E.decodeUnknownOption(sn);function ln(e){try{return cn(JSON.parse(e))}catch{return me.none()}}E.Union([Zt,Qt,$t,en,tn,nn,rn,an,on]);const J={BAD_ATTACH:`bad_attach`,BAD_TOKEN:`bad_token`,TUNNEL_NOT_BOUND:`tunnel_not_bound`,CERT_NOT_READY:`cert_not_ready`,REPLACED:`replaced`,UPSTREAM_CONNECT_FAILED:`upstream_connect_failed`,UPSTREAM_IO_ERROR:`upstream_io_error`,CLIENT_IO_ERROR:`client_io_error`,IDLE_TIMEOUT:`idle_timeout`,ROUTE_CONFLICT:`route_conflict`,INVALID_ROUTE:`invalid_route`,UNKNOWN_ROUTE:`unknown_route`,TOO_MANY_CONNECTIONS:`too_many_connections`},un={HEARTBEAT_MS:15e3,IDLE_TIMEOUT_MS:45e3,CONNECT_TIMEOUT_MS:1e4,RECONNECT_BACKOFF_MIN_MS:250,RECONNECT_BACKOFF_MAX_MS:3e4},Y={CONN_ID_SIZE:4,MAX_PAYLOAD_SIZE:32768};function dn(e){return e.length<Y.CONN_ID_SIZE?null:{conn:new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!1),payload:e.slice(Y.CONN_ID_SIZE)}}function fn(e,t){let n=new Uint8Array(Y.CONN_ID_SIZE+t.length);return new DataView(n.buffer).setUint32(0,e,!1),n.set(t,Y.CONN_ID_SIZE),n}const pn=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,mn=e=>e===`@`||pn.test(e),hn=(e,t)=>{let n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return`@`;let i=`.${r}`;if(!n.endsWith(i))return;let a=n.slice(0,-i.length);return pn.test(a)?a:void 0},gn=e=>{let t=e.lastIndexOf(`:`);if(t===-1)return;let n=e.slice(t+1);if(!/^\d{1,5}$/.test(n))return;let r=Number(n);if(r<1||r>65535)return;let i=e.slice(0,t);if(i.startsWith(`[`)){if(!i.endsWith(`]`))return;i=i.slice(1,-1)}if(i&&/^[A-Za-z0-9.\-:_]+$/.test(i))return{host:i,port:r}},_n=e=>e===`v1`||e===`v2`,vn=Uint8Array.of(13,10,13,10,0,13,10,81,85,73,84,10),yn=e=>{let t=e.split(`.`);if(t.length!==4)return;let n=/* @__PURE__ */ new Uint8Array(4);for(let[e,r]of t.entries()){if(!/^(?:0|[1-9][0-9]{0,2})$/.test(r))return;let t=Number(r);if(t>255)return;n[e]=t}return n},bn=(e,t)=>{if(e===``)return[];let n=[],r=e.split(`:`);for(let[e,i]of r.entries())if(t&&e===r.length-1&&i.includes(`.`)){let e=yn(i);if(!e)return;n.push(e[0]<<8|e[1],e[2]<<8|e[3])}else{if(!/^[0-9A-Fa-f]{1,4}$/.test(i))return;n.push(Number.parseInt(i,16))}return n},xn=e=>{let t=e.indexOf(`::`),n;if(t===-1){if(n=bn(e,!0),n?.length!==8)return}else{if(e.indexOf(`::`,t+1)!==-1)return;let r=bn(e.slice(0,t),!1),i=bn(e.slice(t+2),!0);if(!r||!i||r.length+i.length>7)return;n=[...r,...Array(8-r.length-i.length).fill(0),...i]}let r=/* @__PURE__ */ new Uint8Array(16);for(let[e,t]of n.entries())r[e*2]=t>>8,r[e*2+1]=t&255;return r},Sn=e=>{if(!/^[0-9]{1,5}$/.test(e))return;let t=Number(e);return t<=65535?t:void 0},Cn=e=>e.subarray(0,10).every(e=>e===0)&&e[10]===255&&e[11]===255,wn=(e,t)=>e.length===16&&Cn(e)?{family:4,bytes:e.slice(12),port:t}:e.length===4?{family:4,bytes:e,port:t}:{family:6,bytes:e,port:t},Tn=e=>{let t=yn(e)??xn(e);if(t)return wn(t,0);if(e.startsWith(`[`)){let t=e.indexOf(`]:`);if(t===-1)return;let n=xn(e.slice(1,t)),r=Sn(e.slice(t+2));return n&&r!==void 0?wn(n,r):void 0}let n=e.lastIndexOf(`:`);if(n===-1)return;let r=yn(e.slice(0,n)),i=Sn(e.slice(n+1));return r&&i!==void 0?wn(r,i):void 0},En=e=>{if(e.family===4)return[...e.bytes].join(`.`);let t=Array.from({length:8},(t,n)=>e.bytes[n*2]<<8|e.bytes[n*2+1]),n=-1,r=1;for(let e=0;e<8;){if(t[e]!==0){e++;continue}let i=e;for(;i<8&&t[i]===0;)i++;i-e>r&&(n=e,r=i-e),e=i}let i=e=>e.map(e=>e.toString(16)).join(`:`);return n===-1?i(t):`${i(t.slice(0,n))}::${i(t.slice(n+r))}`},Dn=new TextEncoder,On=(e,t,n)=>{let r=Tn(t);return e===`v1`?kn(r):An(r,n)},kn=e=>{if(!e)return Dn.encode(`PROXY UNKNOWN\r
|
|
5
|
+
`);let[t,n]=e.family===4?[`TCP4`,`0.0.0.0`]:[`TCP6`,`::`];return Dn.encode(`PROXY ${t} ${En(e)} ${n} ${e.port} 443\r\n`)},An=(e,t)=>{let n=Dn.encode(t),r=n.length>0&&n.length<=255?3+n.length:0,i=(e===void 0?0:e.family===4?12:36)+r,a=new Uint8Array(16+i),o=new DataView(a.buffer);a.set(vn,0),a[12]=e?33:32,a[13]=e===void 0?0:e.family===4?17:33,o.setUint16(14,i);let s=16;if(e){let t=e.bytes.length;a.set(e.bytes,s),s+=t*2,o.setUint16(s,e.port),o.setUint16(s+2,443),s+=4}return r>0&&(a[s]=2,o.setUint16(s+1,n.length),a.set(n,s+3)),a},jn=WebSocket;var Mn=class extends Error{code;constructor(e){super(`Bridge attach failed: ${e}`),this.code=e}};const Nn=/* @__PURE__ */ new Set([J.BAD_TOKEN,J.CERT_NOT_READY]),Pn=/* @__PURE__ */ new Set([`target`,`proxyProtocol`]),Fn=(e,t)=>{if(!mn(e))throw Error(`Invalid route name '${e}'`);let n=t,r;if(typeof t==`object`&&t&&!Array.isArray(t)){for(let n of Object.keys(t))if(!Pn.has(n))throw Error(`Unknown option '${n}' for route '${e}': expected target or proxyProtocol`);let i=t;if(i.target===void 0)throw Error(`Route '${e}' has no target`);if(n=i.target,i.proxyProtocol!==void 0){if(!_n(i.proxyProtocol))throw Error(`Invalid proxyProtocol '${String(i.proxyProtocol)}' for route '${e}': use "v1" or "v2"`);r=i.proxyProtocol}}let i=typeof n==`string`?gn(n):void 0;if(!i)throw Error(`Invalid target '${String(n)}' for route '${e}': use host:port`);return r===void 0?{target:i}:{target:i,proxyProtocol:r}},In=e=>{for(let[t,n]of Object.entries(e))Fn(t,n)},Ln=e=>new Map(Object.entries(e).map(([e,t])=>[e,Fn(e,t)])),Rn=e=>ke.createSecureContext({key:e.privateKey,cert:`${e.certificate}\n${e.chain}`}),zn=(e,t)=>{let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((e,t)=>e===r[t])},Bn=e=>{let t=Math.min(un.RECONNECT_BACKOFF_MIN_MS*2**Math.min(e,16),un.RECONNECT_BACKOFF_MAX_MS);return Math.round(t/2+t/2*Math.random())};var Vn=class{options;routes;resolved;identity;secureContext;refreshTimer;session;shutdown=!1;wake;status;ready;closed;constructor(e){this.options=e,this.resolved=Ln(e.routes),this.routes={...e.routes},this.identity=e.identity,this.secureContext=Rn(e.identity),this.status={state:`connecting`,hostname:e.identity.hostname,routes:this.routes,connections:0};let t,n;this.ready=new Promise((e,r)=>{t=e,n=r}),this.closed=this.run(t).then(()=>t(),e=>{throw n(e),e}),this.ready.catch(()=>void 0),this.refreshCertificate()}async refreshCertificate(){if(this.shutdown)return;try{let e=new URL(`/api/tunnel/${encodeURIComponent(this.identity.id)}/certificate`,this.options.api),t=await fetch(e,{headers:{authorization:`Bearer ${this.identity.token}`}}),n=(t.ok?await t.json():void 0)?.state;if(n?.type===`ready`&&n.certificate&&n.expiry&&n.certificate!==this.identity.certificate){let e={...this.identity,certificate:n.certificate,chain:n.chain??``,certificateExpiry:new Date(n.expiry)};this.secureContext=Rn(e),this.identity=e,this.options.onRenewed?.(e),this.emit({type:`certificate-renewed`,expiry:n.expiry})}}catch{}if(this.shutdown)return;let e=this.identity.certificateExpiry.getTime()-Date.now()<2592e6;this.refreshTimer=setTimeout(()=>void this.refreshCertificate(),e?6e4:432e5),this.refreshTimer.unref?.()}getStatus(){return{...this.status,routes:{...this.status.routes}}}setRoutes(e){let t=Ln(e),n=this.routes;this.resolved=t,this.routes={...e},this.status.routes=this.routes,zn(n,this.routes)||this.session?.end({type:`routes-changed`}),this.wake?.()}close(){return this.shutdown=!0,clearTimeout(this.refreshTimer),this.session?.end({type:`shutdown`}),this.wake?.(),this.closed.catch(()=>void 0)}emit(e){this.options.onEvent(e)}sleep(e){return new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),t()}this.wake=r}).finally(()=>{this.wake=void 0})}async run(e){let t=0;try{for(;!this.shutdown;){if(Object.keys(this.routes).length===0){this.status.state=`waiting-routes`,await this.sleep(2**31-1);continue}this.status.state=`connecting`,this.emit({type:`connecting`,attempt:t});let n=new Hn(this.options,this.routes,()=>this.secureContext,{emit:e=>this.emit(e),route:e=>this.resolved.get(e),attached:t=>{this.status.state=`connected`,this.status.session=t,this.status.lastError=void 0,this.status.connectedAt=Date.now(),e()},connections:e=>{this.status.connections=e}});this.session=n;let r=await n.run();if(this.session=void 0,this.status.session=void 0,this.status.connections=0,r.type===`shutdown`)break;if(r.type===`fatal`)throw r.error;if(r.type===`routes-changed`){this.emit({type:`disconnected`,reason:`routes changed`}),t=0;continue}r.attached&&(t=0),this.emit({type:`disconnected`,reason:r.error});let i=Bn(t);t++,this.status.state=`reconnecting`,this.status.lastError=r.error,this.emit({type:`reconnecting`,attempt:t,delayMs:i}),await this.sleep(i)}this.status.state=`stopped`,this.emit({type:`stopped`})}catch(e){throw this.status.state=`stopped`,this.status.lastError=e instanceof Error?e.message:String(e),this.emit({type:`stopped`,error:this.status.lastError}),e}}},Hn=class{options;routes;secureContext;hooks;socket;finish;channels=/* @__PURE__ */ new Map;drainWaiters=[];drainTimer;heartbeat;attachTimeout;lastReceived=Date.now();attached=!1;constructor(e,t,n,r){this.options=e,this.routes=t,this.secureContext=n,this.hooks=r}run(){return new Promise(e=>{this.finish=e;let t=new URL(`/api/tunnel/${encodeURIComponent(this.options.identity.id)}/connect`,this.options.api);t.protocol=t.protocol===`https:`?`wss:`:`ws:`;let n=new jn(t,{protocols:[`opentunnel`],headers:{"user-agent":Pt}});n.binaryType=`arraybuffer`,this.socket=n,this.attachTimeout=setTimeout(()=>this.end({type:`retry`,error:`bridge attach timed out`,attached:!1}),un.CONNECT_TIMEOUT_MS),n.addEventListener(`open`,()=>{this.sendControl({type:`attach`,token:this.options.identity.token,transport:`ws`,routes:Object.keys(this.routes).sort(),client:{version:`0.1.0`,max_conns:256}})}),n.addEventListener(`message`,e=>{this.lastReceived=Date.now(),typeof e.data==`string`?this.onControl(e.data):this.onData(new Uint8Array(e.data))}),n.addEventListener(`close`,e=>{let t=`${e.code} ${e.reason}`.trim();this.end({type:`retry`,error:`bridge closed: ${t}`,attached:this.attached})})})}end(e){let t=this.finish;if(t){this.finish=void 0,clearTimeout(this.attachTimeout),clearInterval(this.heartbeat),clearInterval(this.drainTimer);for(let e of this.drainWaiters.splice(0))e();for(let e of[...this.channels.values()])e.destroy(`bridge disconnected`);this.socket&&this.socket.readyState<=WebSocket.OPEN&&this.socket.close(1e3),t(e)}}onControl(e){let t=ln(e);if(me.isNone(t))return;let n=t.value;if(this.attached)switch(n.type){case`open`:return this.open(n.conn,n.sni,n.peer);case`end`:return this.channels.get(n.conn)?.endInbound();case`reset`:return this.channels.get(n.conn)?.destroy(n.code,!1);case`ping`:return this.sendControl({type:`pong`,time_sent:n.time_sent});case`drain`:return this.end({type:`retry`,error:`server draining: ${n.reason}`,attached:!0})}else if(n.type===`attached`){this.attached=!0,clearTimeout(this.attachTimeout);let e=Math.max(n.heartbeat_ms,1e3),t=Math.max(n.idle_timeout_ms,5e3);this.heartbeat=setInterval(()=>{Date.now()-this.lastReceived>t?this.end({type:`retry`,error:`bridge idle timeout`,attached:!0}):this.sendControl({type:`ping`,time_sent:Date.now()})},e),this.hooks.attached(n.session),this.hooks.emit({type:`connected`,session:n.session,routes:[...n.routes]})}else n.type===`attach_error`&&this.end(Nn.has(n.code)?{type:`fatal`,error:new Mn(n.code)}:{type:`retry`,error:`attach failed: ${n.code}`,attached:!1})}onData(e){let t=dn(e);t&&this.channels.get(t.conn)?.push(t.payload)}open(e,t,n){let r=hn(t,this.options.identity.hostname),i=r===void 0?void 0:this.hooks.route(r);if(r===void 0||!i){this.sendControl({type:`reset`,conn:e,code:J.UNKNOWN_ROUTE});return}if(this.channels.size>=256){this.sendControl({type:`reset`,conn:e,code:J.TOO_MANY_CONNECTIONS});return}let a=i.proxyProtocol===void 0?void 0:On(i.proxyProtocol,n,t),o=new Un(e,r,i.target,a,this.secureContext(),this);this.channels.set(e,o),this.hooks.connections(this.channels.size),this.hooks.emit({type:`connection-opened`,conn:e,route:r,peer:n})}closed(e,t){this.channels.get(e.conn)===e&&(this.channels.delete(e.conn),this.hooks.connections(this.channels.size),this.hooks.emit({type:`connection-closed`,conn:e.conn,route:e.route,...t===void 0?{}:{error:t}}))}sendControl(e){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}sendData(e,t,n){let r=this.socket;if(!this.finish||r?.readyState!==WebSocket.OPEN)n(/* @__PURE__ */ Error(`bridge closed`));else{for(let n=0;n<t.byteLength;n+=Y.MAX_PAYLOAD_SIZE){let i=t.subarray(n,n+Y.MAX_PAYLOAD_SIZE);r.send(fn(e,i))}r.bufferedAmount<1048576?n():(this.drainWaiters.push(()=>n()),this.drainTimer??=setInterval(()=>{if(!(this.socket&&this.socket.bufferedAmount>262144&&this.finish)){clearInterval(this.drainTimer),this.drainTimer=void 0;for(let e of this.drainWaiters.splice(0))e()}},5))}}},Un=class{conn;route;session;raw;tls;upstream;done=!1;constructor(e,t,n,r,i,a){this.conn=e,this.route=t,this.session=a,this.raw=new Oe({allowHalfOpen:!0,read(){},write:(t,n,r)=>a.sendData(e,t,r),final:t=>{a.sendControl({type:`end`,conn:e}),t()}}),this.tls=new ke.TLSSocket(this.raw,{isServer:!0,secureContext:i}),this.tls.on(`secure`,()=>{let e=De.connect({host:n.host,port:n.port,allowHalfOpen:!0});this.upstream=e,e.setNoDelay(!0),r&&e.write(r),e.on(`error`,t=>this.destroy(e.connecting?J.UPSTREAM_CONNECT_FAILED:J.UPSTREAM_IO_ERROR,!0,t.message)),this.tls.pipe(e),e.pipe(this.tls)}),this.tls.on(`error`,e=>this.destroy(J.UPSTREAM_IO_ERROR,!0,e.message)),this.tls.on(`close`,()=>this.finish(void 0))}push(e){this.done||(this.raw.readableLength>8388608?this.destroy(J.UPSTREAM_IO_ERROR,!0,`local connection stalled`):this.raw.push(e))}endInbound(){this.done||this.raw.push(null)}destroy(e,t=!0,n=e){this.done||(t&&this.session.sendControl({type:`reset`,conn:this.conn,code:e}),this.finish(n))}finish(e){this.done||(this.done=!0,this.upstream?.destroy(),this.tls.destroy(),this.raw.destroy(),this.session.closed(this,e))}};const X=e=>e?.profile??`default`,Wn=e=>{if(ve.isHttpClientError(e)){let t=e.response;if(!t)return e.message;let n=ut(t.status,``);return n.startsWith(`HTTP `)?n:`${n} (HTTP ${t.status})`}if(typeof e==`object`&&e){let{_tag:t,message:n}=e;if(typeof t==`string`&&typeof n==`string`)return`${t}: ${n}`}return e instanceof Error?e.message:void 0},Z=(e,t)=>{let n=Wn(t);return new qt({message:n?`${e}: ${n}`:e,cause:t})},Gn=e=>ve.isHttpClientError(e)&&(e.reason._tag===`TransportError`||e.response!==void 0&&ot(e.response.status,`idempotent`)),Kn=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);let r=btoa(n);return`-----BEGIN PRIVATE KEY-----\n${r.match(/.{1,64}/g)?.join(`
|
|
6
|
+
`)??r}\n-----END PRIVATE KEY-----\n`};var qn=class e extends fe.Service()(`@opentunnel/client/OpenTunnelClient`){static layer(t={}){let n=t.storage??Jt();return pe.effect(e,T.gen(function*(){let e=yield*Bt,r=new URL(t.api??`https://opentunnel.xyz`),i=T.fn(`OpenTunnelClient.tunnel.get`)(function*(e){return yield*n.load(X(e))}),a=T.fn(`OpenTunnelClient.tunnel.completePending`)(function*(t){let r=yield*e.authorized(B.make(t.pending.token));yield*T.sync(()=>t.onProgress?.(`requesting-certificate`)),yield*r.tunnel[`tunnel.bindCertificate`]({params:{id:z.make(t.pending.id)},payload:{csr:t.pending.csr}}).pipe(T.catchTag(`CertificateInProgressError`,()=>T.void),T.mapError(e=>Z(`Failed to start certificate issuance`,e)));let i=yield*T.gen(function*(){for(;;){yield*T.sync(()=>t.onProgress?.(`waiting-certificate`));let e=yield*r.tunnel[`tunnel.getCertificate`]({params:{id:z.make(t.pending.id)}}).pipe(T.mapError(e=>Z(`Failed to read certificate`,e)));if(e.state.type===`ready`)return e.state;if(e.state.type===`failed`)return yield*new qt({message:`Certificate issuance failed: ${e.state.reason}`});yield*T.sleep(`2 seconds`)}}),a={id:t.pending.id,hostname:t.pending.hostname,token:t.pending.token,privateKey:t.pending.privateKey,certificate:i.certificate,chain:i.chain,certificateExpiry:new Date(i.expiry)};return yield*T.sync(()=>t.onProgress?.(`saving-identity`)),yield*n.save(t.profile,a),yield*T.sync(()=>t.onProgress?.(`ready`)),a}),o=T.fn(`OpenTunnelClient.tunnel.provision`)(function*(e){yield*T.sync(()=>e.onProgress?.(`generating-key`));let t=yield*T.tryPromise({try:()=>crypto.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!0,[`sign`,`verify`]),catch:e=>Z(`Failed to generate certificate key`,e)});yield*T.sync(()=>e.onProgress?.(`generating-csr`));let r=yield*T.tryPromise({try:()=>Kt(e.hostname,t),catch:e=>Z(`Failed to generate certificate request`,e)}),i=yield*T.tryPromise({try:()=>crypto.subtle.exportKey(`pkcs8`,t.privateKey),catch:e=>Z(`Failed to export certificate key`,e)}),o={id:String(e.id),hostname:e.hostname,token:e.token,privateKey:Kn(i),csr:r};return yield*n.savePending(e.profile,o),yield*a({profile:e.profile,pending:o,onProgress:e.onProgress})}),s=T.fn(`OpenTunnelClient.tunnel.create`)(function*(t){let r=X(t);if(yield*n.load(r))return yield*new qt({message:`Profile '${r}' already has a tunnel`});let i=yield*n.loadPending(r);if(i)return yield*T.sync(()=>t?.onProgress?.(`resuming-certificate`)),yield*a({profile:r,pending:i,onProgress:t?.onProgress});yield*T.sync(()=>t?.onProgress?.(`creating-tunnel`));let s=yield*e.client.tunnel[`tunnel.create`]({payload:{}}).pipe(T.mapError(e=>Z(`Failed to create tunnel`,e)));return yield*o({profile:r,id:s.tunnel.id,hostname:String(s.tunnel.hostname),token:s.token,onProgress:t?.onProgress})}),c=T.fn(`OpenTunnelClient.tunnel.ensure`)(function*(t){let r=yield*i(t);if(!r)return yield*s(t);let a=yield*(yield*e.authorized(B.make(r.token))).tunnel[`tunnel.getCertificate`]({params:{id:z.make(r.id)}}).pipe(T.catchIf(e=>Gn(e)&&r.certificateExpiry.getTime()>Date.now(),()=>T.succeed(void 0)),T.mapError(e=>Z(`Failed to read certificate`,e)));if(!a)return r;let c=a.state;if(c.type===`ready`&&c.certificate!==r.certificate){let e={...r,certificate:c.certificate,chain:c.chain,certificateExpiry:new Date(c.expiry)};return yield*n.save(X(t),e),e}return c.type===`failed`?yield*o({profile:X(t),id:z.make(r.id),hostname:r.hostname,token:B.make(r.token)}):r}),l=T.fn(`OpenTunnelClient.tunnel.pending`)(function*(e){let t=yield*n.loadPending(X(e));return t?{id:t.id,hostname:t.hostname}:void 0}),u=T.fn(`OpenTunnelClient.tunnel.resume`)(function*(e){let t=X(e),r=yield*n.loadPending(t);if(r)return yield*T.sync(()=>e?.onProgress?.(`resuming-certificate`)),yield*a({profile:t,pending:r,onProgress:e?.onProgress})});return{profile:{list:n.profiles},tunnel:{list:n.list,get:i,pending:l,resume:u,create:s,ensure:c,remove:T.fn(`OpenTunnelClient.tunnel.remove`)(function*(t){let r=X(t),i=yield*n.load(r);i&&(yield*(yield*e.authorized(B.make(i.token))).tunnel[`tunnel.remove`]({params:{id:z.make(i.id)}}).pipe(T.mapError(e=>Z(`Failed to remove tunnel`,e))),yield*n.remove(r))}),connect:T.fn(`OpenTunnelClient.tunnel.connect`)(function*(e){yield*T.try({try:()=>In(e.routes),catch:e=>Z(e instanceof Error?e.message:`Invalid routes`,e)});let t=yield*c(e),i=yield*he.unbounded(),a=yield*T.acquireRelease(T.sync(()=>new Vn({api:r,identity:t,routes:e.routes,onEvent:e=>{he.offerUnsafe(i,e),e.type===`stopped`&&he.endUnsafe(i)},onRenewed:t=>{T.runFork(n.save(X(e),t).pipe(T.ignore))}})),e=>T.promise(()=>e.close()).pipe(T.andThen(he.end(i))));return yield*T.tryPromise({try:()=>a.ready,catch:e=>Z(`Failed to connect tunnel`,e)}),{tunnel:t,events:ge.fromQueue(i),status:T.sync(()=>a.getStatus()),setRoutes:e=>T.try({try:()=>a.setRoutes(e),catch:e=>Z(e instanceof Error?e.message:`Invalid routes`,e)}),closed:T.tryPromise({try:()=>a.closed,catch:e=>Z(`Tunnel stopped`,e)}),close:T.promise(()=>a.close())}})}}})).pipe(pe.provide(Bt.layer({api:t.api??`https://opentunnel.xyz`})))}};const Jn=r.Union([r.Struct({jsonrpc:r.Literal(`2.0`),id:M.RequestId,result:r.Unknown}),r.Struct({jsonrpc:r.Literal(`2.0`),id:M.RequestId.pipe(r.NullOr),error:M.McpErrorBase}),r.Struct({jsonrpc:r.Literal(`2.0`),method:r.String,params:r.Unknown.pipe(r.optionalKey)})]),Yn=Jn.pipe(r.fromJsonString),Xn=r.decodeEffect(Yn),Zn=j.v2025_06_18.protocolVersion;var Q=class extends r.TaggedError()(`OrbitMcpError`,{message:r.String}){};const Qn=r.is(Q);function $n(e){return Q.make({message:`Orbit HTTP ${e.status}: authorization rejected. Run tlo-mcp login; a 403 can also mean insufficient rights.`})}var er=class extends l.Service()(`@2digits/tlo-mcp/mcp/OrbitClient`){};const tr=p.effect(er,n.gen(function*(){let e=yield*R,t=(yield*_.HttpClient).pipe(_.withScope,_.transformResponse(n.flatMap(Le.matchStatus({"2xx":e=>n.succeed(e),401:$n,403:$n,429:e=>Q.make({message:`Orbit rate limited. Retry after ${e.headers[`retry-after`]??`the server cooldown`}; request not replayed.`}),orElse:e=>Q.make({message:`Orbit HTTP ${e.status}. Request not replayed.`})})))),i=0,a,o=n.fn(`OrbitClient.send`)(function*(r,o,s=!1){let c=++i,l=yield*e.accessToken,u=yield*v.post(N).pipe(v.bearerToken(l),v.setHeader(`accept`,`application/json, text/event-stream`),v.setHeader(`mcp-protocol-version`,Zn),e=>a===void 0?e:v.setHeader(e,`mcp-session-id`,a),v.bodyJson({jsonrpc:`2.0`,...s?{}:{id:c},method:r,params:o})),d=yield*t.execute(u),f=d.headers[`mcp-session-id`];if(r===`initialize`&&(a=f),s)return;let p=w.startsWith(`text/event-stream`)(d.headers[`content-type`]??``)?yield*d.stream.pipe(C.decodeText(),C.pipeThroughChannel(Ie.decode({maxEventSize:10485760})),C.filter(e=>e.event===`message`||e.event===``),C.map(Fe.get(`data`)),C.mapEffect(e=>Xn(e)),C.filter(e=>`id`in e&&e.id===c),C.runHead,n.flatMap(Pe.match({onNone:()=>Q.make({message:`Orbit stream ended before replying.`}),onSome:n.succeed}))):yield*Le.schemaBodyJson(Jn)(d);return!(`id`in p)||p.id!==c?yield*Q.make({message:`Unexpected Orbit response ID.`}):`error`in p?yield*Q.make({message:p.error.message}):p.result},n.timeout(`120 seconds`),n.scoped,n.provideService(g.RequestInit,{redirect:`error`}),n.mapError(e=>Qn(e)?e:Q.make({message:`Orbit connection or response failed. Request not replayed.`}))),s=yield*o(`initialize`,{protocolVersion:Zn,capabilities:{},clientInfo:{name:`@2digits/tlo-mcp`,version:`0.1.38`}}).pipe(n.flatMap(r.decodeUnknownEffect(M.InitializeResult)));if(s.protocolVersion!==Zn)return yield*Q.make({message:`Unsupported upstream MCP protocol: ${s.protocolVersion}.`});yield*o(`notifications/initialized`,{},!0);let c=/* @__PURE__ */ new Set,l=yield*C.paginate(void 0,n.fn(`OrbitClient.listToolsPage`)(function*(e){let t=yield*o(`tools/list`,e===void 0?{}:{cursor:e}).pipe(n.flatMap(r.decodeUnknownEffect(M.ListToolsResult)));if(t.nextCursor!==void 0){if(c.has(t.nextCursor))return yield*Q.make({message:`Orbit returned a repeated tools cursor.`});c.add(t.nextCursor)}return[t.tools,Pe.fromUndefinedOr(t.nextCursor)]})).pipe(C.runCollect);return er.of({tools:l,instructions:s.instructions,callTool:n.fn(`OrbitClient.callTool`)(function*(e,t){return yield*o(`tools/call`,{name:e,arguments:t})},n.flatMap(r.decodeUnknownEffect(M.CallToolResult)),n.catchTag(`SchemaError`,()=>Q.make({message:`Invalid Orbit tool result. Request not replayed.`})))})})).pipe(p.provide(g.layer)),nr=r.decodeUnknownEffect(r.JsonObject),rr=p.effectDiscard(n.gen(function*(){let e=yield*er,t=yield*je.McpServer;yield*n.forEach(e.tools,n.fn(`OrbitProxyLive.tool`)(function*(r){yield*t.addTool({tool:r,annotations:l.empty(),handle:n.fn(`handle`)(function*(e){return yield*nr(e)},n.mapError(e=>M.InvalidParams.make({message:`Tool arguments must be a JSON object.`,data:e})),n.flatMap(t=>e.callTool(r.name,t).pipe(n.mapError(e=>M.InternalError.make({message:e.message})))))})}),{discard:!0})})),ir=`${le()}/.config/2digits/tlo-mcp/gateway.key`,ar=Ae.mebibytes(1),or=S.empty({status:401,headers:{"www-authenticate":`Bearer`,"cache-control":`no-store`}}),sr=S.empty({status:403,headers:{"cache-control":`no-store`}}),cr=new TextEncoder,lr=r.String.check(r.isPattern(/^[a-f0-9]{64}$/)).pipe(r.RedactedFromValue);var $=class extends r.TaggedError()(`GatewayError`,{message:r.String}){};const ur=n.fn(`Gateway.loadKey`)(function*(e){let t=yield*ue.FileSystem,i=yield*u.Crypto,a=(yield*de.Path).dirname(e);yield*t.makeDirectory(a,{recursive:!0,mode:448}),yield*t.chmod(a,448);let o=yield*i.randomBytes(32);yield*t.writeFileString(e,Me.encode(o),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>n.void));let s=yield*t.stat(e);return s.type!==`File`||s.mode&63?yield*$.make({message:`Gateway key must be a private file (chmod 600).`}):yield*t.readFileString(e).pipe(n.flatMap(r.decodeEffect(lr)))},n.mapError(()=>$.make({message:`Cannot load private gateway key. Check its permissions and format.`})));function dr(e,t){return e.digest(`SHA-256`,cr.encode(t)).pipe(n.orDie)}function fr(e){return p.unwrap(n.gen(function*(){let t=yield*u.Crypto,r=yield*dr(t,`Bearer ${h.value(e)}`);return x.middleware(e=>n.gen(function*(){let i=yield*se.HttpServerRequest,a=yield*dr(t,i.headers.authorization??``);return ne(r,a)?i.headers.origin===void 0?yield*e.pipe(n.provideService(Ne.MaxBodySize,ar),n.map(e=>S.setHeader(e,`cache-control`,`no-store`))):sr:or}),{global:!0})}))}function pr(e){let t=p.unwrap(n.gen(function*(){let e=yield*er;return rr.pipe(p.provide(je.layerHttp({name:`tlo-mcp`,version:`1.0.0`,instructions:e.instructions,path:`/mcp`,protocols:[j.v2025_11_25,j.v2025_06_18,j.v2025_03_26]})))}));return p.merge(t,fr(e))}const mr=r.String.check(r.isPattern(/^[a-z0-9]+\.opentunnel\.xyz$/)),hr=r.decodeEffect(mr),gr=n.fn(`Gateway.openTunnel`)(function*(e){let t=yield*(yield*qn).tunnel.connect({profile:`tlo-mcp`,routes:{tlo:`127.0.0.1:${e}`}}),r=yield*hr(t.tunnel.hostname);return yield*t.events.pipe(C.filter(e=>e.type===`reconnecting`),C.runForEach(()=>n.sync(()=>process.stderr.write(`OpenTunnel reconnecting...
|
|
7
|
+
`))),n.forkScoped),{endpoint:`https://tlo.${r}/mcp`,closed:t.closed.pipe(n.mapError(()=>$.make({message:`OpenTunnel stopped unexpectedly. Restart tlo-mcp.`})))}},n.timeout(`180 seconds`),n.mapError(()=>$.make({message:`Could not connect OpenTunnel. Check network access and retry; existing tunnel identity is preserved.`})));function _r(e){return`Connect my personal Teamleader Orbit MCP to Executor Cloud.
|
|
8
8
|
Endpoint: ${e}
|
|
9
9
|
Transport: Streamable HTTP. Authentication: API key in Authorization: Bearer <key>.
|
|
10
10
|
Register an MCP integration named Teamleader Orbit (slug tlo_mcp) with a bearer-header API-key template, not OAuth.
|
|
@@ -12,9 +12,9 @@ Use a secure credential handoff so I enter the gateway key directly in Executor;
|
|
|
12
12
|
Create a personal connection, discover tools, and verify with one read-only tool. Do not change business data.
|
|
13
13
|
If this endpoint already exists, reuse its integration/connection instead of creating duplicates.
|
|
14
14
|
Orbit login and refresh are handled on my Mac; do not register another Orbit OAuth client.
|
|
15
|
-
`}const
|
|
16
|
-
`));let{endpoint:a,closed:o}=yield*
|
|
15
|
+
`}const vr=n.fn(`TloMcp.connect`)(function*(e){let t=yield*ur(ir),r=yield*L,i=yield*R;(yield*r.load)===void 0&&(yield*i.login),yield*p.build(x.serve(pr(t),{disableLogger:!0,disableListenLog:!0}).pipe(p.provide(tr),p.provide(ie.layer(()=>re({maxHeaderSize:8192,requestTimeout:13e4}),{host:`127.0.0.1`,port:e})))),yield*n.sync(()=>process.stderr.write(`Connecting OpenTunnel (first certificate may take a few minutes)...
|
|
16
|
+
`));let{endpoint:a,closed:o}=yield*gr(e);return yield*n.sync(()=>{process.stderr.write(`TLO gateway ready: ${a}\nGateway key: ${ir} (private; not printed)\n`),process.platform===`darwin`&&process.stderr.write(`Copy the key for Executor's secure credential form: pbcopy < "${ir}"\n`),process.stderr.write(`Keep this process running and your Mac awake. Ctrl-C closes the gateway and tunnel.
|
|
17
17
|
|
|
18
18
|
Copy this prompt to your agent:
|
|
19
19
|
|
|
20
|
-
`),process.stdout.write(
|
|
20
|
+
`),process.stdout.write(_r(a))}),yield*o,yield*$.make({message:`The OpenTunnel connection stopped. Restart tlo-mcp.`})},n.scoped,n.provide(p.mergeAll(it,et,qn.layer())));function yr(e){return i.make(e,{},n.fn(`TloMcp.${e}`)(function*(){yield*(yield*R)[e]},n.provide(it),n.scoped))}const br=i.make(`tlo-mcp`,{port:a.Int(`port`).pipe(a.withSchema(r.Int.check(r.isBetween({minimum:1024,maximum:65535}))),a.withDefault(4790))},({port:e})=>vr(e)).pipe(i.withSubcommands([yr(`login`),yr(`logout`)]));n.fn(`TloMcp.run`)(function*(e){return yield*i.runWith(br,{version:`1.0.0`})(e)})(process.argv.slice(2)).pipe(n.provide(t.layer),e.runMain);export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@2digits/tlo-mcp",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.8",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/2digits-agency/configs.git",
|
|
@@ -19,16 +19,16 @@
|
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
21
|
"@effect/platform-node": "4.0.5",
|
|
22
|
-
"@opentunnel/client": "0.5.
|
|
22
|
+
"@opentunnel/client": "0.5.5",
|
|
23
23
|
"@yielded/oauth": "0.1.0-beta.43",
|
|
24
24
|
"effect": "4.0.5"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
|
-
"@2digits/tsconfig": "1.0.
|
|
27
|
+
"@2digits/tsconfig": "1.0.4",
|
|
28
28
|
"@arethetypeswrong/core": "0.18.5",
|
|
29
29
|
"@effect/vitest": "4.0.5",
|
|
30
30
|
"publint": "0.3.25",
|
|
31
|
-
"typescript": "7.0
|
|
31
|
+
"typescript": "7.1.0-beta",
|
|
32
32
|
"vite-plus": "1.3.0",
|
|
33
33
|
"vitest": "5.0.5"
|
|
34
34
|
},
|