Compare commits
337
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb538d76c5 | ||
|
|
357211864c | ||
|
|
4e4f44f286 | ||
|
|
90c0d7d95a | ||
|
|
2b7dcd0295 | ||
|
|
169e16803d | ||
|
|
0dc0cc76be | ||
|
|
499f1463d5 | ||
|
|
a2ff50dbba | ||
|
|
166bce0389 | ||
|
|
1498335e39 | ||
|
|
25c9d267ac | ||
|
|
536dcad19e | ||
|
|
0e38870647 | ||
|
|
9b604bcae1 | ||
|
|
35721d9a08 | ||
|
|
f4c9418d40 | ||
|
|
02dd47ea31 | ||
|
|
aca0fa4e5b | ||
|
|
0576820755 | ||
|
|
cb3211c8f3 | ||
|
|
826965978b | ||
|
|
623e471a02 | ||
|
|
91a03e0747 | ||
|
|
d501ebe877 | ||
|
|
3772fa127c | ||
|
|
92e340d80c | ||
|
|
d7969264de | ||
|
|
f7748a0d65 | ||
|
|
0ce7e56e43 | ||
|
|
350d76ee14 | ||
|
|
6d7fe2eeb7 | ||
|
|
460d9c3eb9 | ||
|
|
cb8015a34d | ||
|
|
8f50ca8e2c | ||
|
|
4ceabac764 | ||
|
|
7a3f21e7ca | ||
|
|
17b43960e8 | ||
|
|
e5c7ac5a8c | ||
|
|
a480f07241 | ||
|
|
1eb6fcea84 | ||
|
|
4ef361da73 | ||
|
|
c07ac592d8 | ||
|
|
d649ccf715 | ||
|
|
f54f4385e5 | ||
|
|
e25ce07cc2 | ||
|
|
532a1d891d | ||
|
|
9e2f7129e3 | ||
|
|
a4298f1ceb | ||
|
|
86c94b4852 | ||
|
|
69d9a659a3 | ||
|
|
9acf46a76d | ||
|
|
44b39fe2ec | ||
|
|
02903f2db8 | ||
|
|
22b7d8c524 | ||
|
|
fe2fde5172 | ||
|
|
7da6522fb8 | ||
|
|
08e6d4cfbf | ||
|
|
35822884d1 | ||
|
|
dbebc387dd | ||
|
|
5cf83ffe8f | ||
|
|
ada410bccf | ||
|
|
00b5c3e1b3 | ||
|
|
188df6da07 | ||
|
|
0d55a42840 | ||
|
|
0ee302e24d | ||
|
|
d5b7690f95 | ||
|
|
8d1d699f88 | ||
|
|
b0b7b38da1 | ||
|
|
fd3b96b487 | ||
|
|
aa2d385a62 | ||
|
|
e25db3a572 | ||
|
|
b8305afa29 | ||
|
|
b7c89cf496 | ||
|
|
3a1daa87ac | ||
|
|
055897f0ea | ||
|
|
40b3a80034 | ||
|
|
f6978db605 | ||
|
|
de05b0c94e | ||
|
|
6d1505c9fb | ||
|
|
306ec4bb84 | ||
|
|
3b98fe3548 | ||
|
|
66c326b8c4 | ||
|
|
8dbcf92a0d | ||
|
|
37965da01d | ||
|
|
57b59b5bf2 | ||
|
|
20f346d8ef | ||
|
|
c83bc5d48a | ||
|
|
9df3c64021 | ||
|
|
8ac57f7944 | ||
|
|
29cb917ac4 | ||
|
|
9c64f12ea0 | ||
|
|
0f184c28b0 | ||
|
|
a3b1df5224 | ||
|
|
4e0c003e78 | ||
|
|
60387f67e9 | ||
|
|
ce94feeea1 | ||
|
|
39ca3ee858 | ||
|
|
52a6067802 | ||
|
|
721b6b4c6f | ||
|
|
40009735ee | ||
|
|
df9d34004f | ||
|
|
f297e30e4c | ||
|
|
a7a44d0662 | ||
|
|
d8d329691a | ||
|
|
54179c86b8 | ||
|
|
8dba2d6484 | ||
|
|
ed6b7fbf27 | ||
|
|
b991b9b9e6 | ||
|
|
505db9f696 | ||
|
|
2d87574e62 | ||
|
|
b2cca674df | ||
|
|
549043863a | ||
|
|
b7df3dfca0 | ||
|
|
6891c77d3e | ||
|
|
d90e15d1d7 | ||
|
|
e0117b271a | ||
|
|
188a40c315 | ||
|
|
7a08fcf2e8 | ||
|
|
19d47408a5 | ||
|
|
3e07f5a6a4 | ||
|
|
d22c6f5280 | ||
|
|
5e13f53571 | ||
|
|
f9580ff088 | ||
|
|
5e1dd56d2c | ||
|
|
68061af042 | ||
|
|
28cb9db20b | ||
|
|
7968f278ee | ||
|
|
44afe784a3 | ||
|
|
9ff31f8c35 | ||
|
|
409ff90a14 | ||
|
|
0d280262f6 | ||
|
|
c9b07d665d | ||
|
|
2e42f3fdf6 | ||
|
|
008ac5c3e5 | ||
|
|
9dcea68bce | ||
|
|
5f7ec73a22 | ||
|
|
569fea87a9 | ||
|
|
33dadb5aec | ||
|
|
d18e43b674 | ||
|
|
6f699346e4 | ||
|
|
f5ecca4480 | ||
|
|
cadd708646 | ||
|
|
5f7becf386 | ||
|
|
9b29be916b | ||
|
|
047a0a697c | ||
|
|
77fcad3586 | ||
|
|
801b83e937 | ||
|
|
f2205bdc42 | ||
|
|
1bf048eb8b | ||
|
|
f7fa62aaf9 | ||
|
|
57d7746a5d | ||
|
|
850c912556 | ||
|
|
dff8784aef | ||
|
|
96c9306dbd | ||
|
|
94d13a2b75 | ||
|
|
7a008461fc | ||
|
|
f59ee36bf1 | ||
|
|
2fce84a1d4 | ||
|
|
f9019cd63f | ||
|
|
f9372a4c3d | ||
|
|
934037cb66 | ||
|
|
5467d11980 | ||
|
|
1f4a3f65bf | ||
|
|
26cc1fffb3 | ||
|
|
97880e8870 | ||
|
|
b80e8476b8 | ||
|
|
e0e01b4a54 | ||
|
|
58e5f714b0 | ||
|
|
4ae9de311b | ||
|
|
5fa09fa2d9 | ||
|
|
12c3af7821 | ||
|
|
e2316814da | ||
|
|
678f827f0b | ||
|
|
a3dadf311e | ||
|
|
e3004ae806 | ||
|
|
9385314d26 | ||
|
|
a3f292770e | ||
|
|
2028d57e88 | ||
|
|
3405a64dd8 | ||
|
|
1cba2f64d3 | ||
|
|
1a05d8ca1a | ||
|
|
cf9f236c80 | ||
|
|
e82b987386 | ||
|
|
ea9e61b266 | ||
|
|
e32077cee7 | ||
|
|
5d9eb18312 | ||
|
|
abb84c09e3 | ||
|
|
65d797c13e | ||
|
|
7c0849fe2e | ||
|
|
592c234fd5 | ||
|
|
66d76b5d02 | ||
|
|
528bb2a1fa | ||
|
|
869789b4ed | ||
|
|
9bedd7140c | ||
|
|
70f5dfcef7 | ||
|
|
9847e9b621 | ||
|
|
b547fee77e | ||
|
|
7b3cdc6a8c | ||
|
|
386eb18a58 | ||
|
|
7372184d06 | ||
|
|
d9ded65dfe | ||
|
|
2aa73985ea | ||
|
|
5b3b31b6e6 | ||
|
|
b7559c4678 | ||
|
|
b96308fc5a | ||
|
|
72b7f90c50 | ||
|
|
1ec346c22e | ||
|
|
28e481eb24 | ||
|
|
b1934b925a | ||
|
|
8244fb80e6 | ||
|
|
afc3924393 | ||
|
|
11d456f6c8 | ||
|
|
a221542921 | ||
|
|
226ed997e1 | ||
|
|
c6f57a1064 | ||
|
|
340dbbb36e | ||
|
|
53a552e80d | ||
|
|
cf2c628bc0 | ||
|
|
e0874b651d | ||
|
|
12347082ef | ||
|
|
740d7a3216 | ||
|
|
cd7980b457 | ||
|
|
f2cd53f232 | ||
|
|
04a1ae77e6 | ||
|
|
6de4b47ecb | ||
|
|
27c2b145f8 | ||
|
|
8515f02770 | ||
|
|
e9ed849b53 | ||
|
|
e8f5b4ad5b | ||
|
|
752f96e9ae | ||
|
|
1b272fd709 | ||
|
|
9013c07f6d | ||
|
|
085340588a | ||
|
|
48481aa923 | ||
|
|
da107f315c | ||
|
|
d2822a8883 | ||
|
|
ae3ea3980d | ||
|
|
915a0548c0 | ||
|
|
5ce5472bc3 | ||
|
|
9ea443d73a | ||
|
|
60f7ae86bb | ||
|
|
867cf4cf09 | ||
|
|
ae6f9715c6 | ||
|
|
b92c78f552 | ||
|
|
801dfe5b41 | ||
|
|
823d69f621 | ||
|
|
4963fccb05 | ||
|
|
dd89d5ce1a | ||
|
|
9132c37c86 | ||
|
|
b9c7ea0581 | ||
|
|
556a195c9d | ||
|
|
80b282ece7 | ||
|
|
d15075b32d | ||
|
|
9f6686a13d | ||
|
|
c6ff7c0d5b | ||
|
|
a9e5a84c03 | ||
|
|
67ca528fea | ||
|
|
6d9b21c5d0 | ||
|
|
ddffdfc095 | ||
|
|
a58290ed79 | ||
|
|
3488ca3570 | ||
|
|
c542ce3369 | ||
|
|
15f0be848d | ||
|
|
1c3fa67374 | ||
|
|
0ac59d569d | ||
|
|
d8aa2f85df | ||
|
|
64d6938cf4 | ||
|
|
0a88719a3a | ||
|
|
0bc94bc24e | ||
|
|
19eb9e7227 | ||
|
|
aa5521dcfb | ||
|
|
2d03847ccd | ||
|
|
d303ac39cb | ||
|
|
48fc85e7fe | ||
|
|
0ea639196a | ||
|
|
6f51725732 | ||
|
|
8622b952ca | ||
|
|
f47c1f1046 | ||
|
|
145ddfc408 | ||
|
|
0bb787b90d | ||
|
|
59f23d7bfd | ||
|
|
4a4795e5f0 | ||
|
|
5b58f74e9a | ||
|
|
32dca3b76b | ||
|
|
6358444900 | ||
|
|
792ad4b5c1 | ||
|
|
d41781987c | ||
|
|
fc6507066e | ||
|
|
bf9c828aef | ||
|
|
7b676b76de | ||
|
|
d5f2333173 | ||
|
|
40e7dbdae9 | ||
|
|
a60daa1c76 | ||
|
|
bc1024caf0 | ||
|
|
a1c428b6e2 | ||
|
|
00f3efb95b | ||
|
|
7f3387a86c | ||
|
|
5462d50177 | ||
|
|
f82bae1668 | ||
|
|
9e60597174 | ||
|
|
afc807ac3f | ||
|
|
58ba4f1263 | ||
|
|
5513845fd5 | ||
|
|
33773ff17e | ||
|
|
64d21bd6d2 | ||
|
|
5210a833a5 | ||
|
|
5b1d5c1220 | ||
|
|
f4617e7b19 | ||
|
|
c426452239 | ||
|
|
73b2f255a9 | ||
|
|
ce463a5360 | ||
|
|
52fa6a7333 | ||
|
|
04298962be | ||
|
|
61f983098b | ||
|
|
32c1f98a02 | ||
|
|
5851b8aca4 | ||
|
|
3e2df5a782 | ||
|
|
f0cdaf94c2 | ||
|
|
48196e67a7 | ||
|
|
80a176fe1f | ||
|
|
42ea7cfae1 | ||
|
|
d2e6c82709 | ||
|
|
23b3f0c3d0 | ||
|
|
e08cea3a23 | ||
|
|
83eb396c40 | ||
|
|
59a383e1ea | ||
|
|
fb7260792f | ||
|
|
d8a485ea7e | ||
|
|
02989fe600 | ||
|
|
648f0676bd | ||
|
|
add5f34619 | ||
|
|
9403429a7a | ||
|
|
37cf0c1144 | ||
|
|
bf1f3e1c4f | ||
|
|
2aa11ae076 | ||
|
|
8888f6a0c9 |
No files matched your search
@@ -0,0 +1 @@
|
||||
plans/
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "T3 Code Dev",
|
||||
"image": "debian:bookworm",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/git:1": {},
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {
|
||||
"version": "1.3.11"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "24.13.1"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/python:1": {
|
||||
"version": "3.10",
|
||||
"installTools": false
|
||||
}
|
||||
},
|
||||
"overrideFeatureInstallOrder": [
|
||||
"ghcr.io/devcontainers/features/git",
|
||||
"ghcr.io/devcontainers-extra/features/bun"
|
||||
],
|
||||
"postCreateCommand": {
|
||||
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
||||
},
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": ["oxc.oxc-vscode"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
# Remote Architecture
|
||||
|
||||
This document describes the target architecture for first-class remote environments in T3 Code.
|
||||
|
||||
It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite.
|
||||
|
||||
## Goals
|
||||
|
||||
- Treat remote environments as first-class product primitives, not special cases.
|
||||
- Support multiple ways to reach the same environment.
|
||||
- Keep the T3 server as the execution boundary.
|
||||
- Let desktop, mobile, and web all share the same conceptual model.
|
||||
- Avoid introducing a local control plane unless product pressure proves it is necessary.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Replacing the existing WebSocket server boundary with a custom transport protocol.
|
||||
- Making SSH the only remote story.
|
||||
- Syncing provider auth across machines.
|
||||
- Shipping every access method in the first iteration.
|
||||
|
||||
## High-level architecture
|
||||
|
||||
T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations.
|
||||
|
||||
Remote support should preserve that boundary.
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Client (desktop / mobile / web) │
|
||||
│ │
|
||||
│ - known environments │
|
||||
│ - connection manager │
|
||||
│ - environment-aware routing │
|
||||
└───────────────┬──────────────────────────────┘
|
||||
│
|
||||
│ resolves one access endpoint
|
||||
│
|
||||
┌───────────────▼──────────────────────────────┐
|
||||
│ Access method │
|
||||
│ │
|
||||
│ - direct ws / wss │
|
||||
│ - tunneled ws / wss │
|
||||
│ - desktop-managed ssh bootstrap + forward │
|
||||
└───────────────┬──────────────────────────────┘
|
||||
│
|
||||
│ connects to one T3 server
|
||||
│
|
||||
┌───────────────▼──────────────────────────────┐
|
||||
│ Execution environment = one T3 server │
|
||||
│ │
|
||||
│ - environment identity │
|
||||
│ - provider state │
|
||||
│ - projects / threads / terminals │
|
||||
│ - git / filesystem / process runtime │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself.
|
||||
|
||||
## Domain model
|
||||
|
||||
### ExecutionEnvironment
|
||||
|
||||
An `ExecutionEnvironment` is one running T3 server instance.
|
||||
|
||||
It is the unit that owns:
|
||||
|
||||
- provider availability and auth state
|
||||
- model availability
|
||||
- projects and threads
|
||||
- terminal processes
|
||||
- filesystem access
|
||||
- git operations
|
||||
- server settings
|
||||
|
||||
It is identified by a stable `environmentId`.
|
||||
|
||||
This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here.
|
||||
|
||||
### KnownEnvironment
|
||||
|
||||
A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach.
|
||||
|
||||
It is not server-authored. It is local to a device or client profile.
|
||||
|
||||
Examples:
|
||||
|
||||
- a saved LAN URL
|
||||
- a saved public `wss://` endpoint
|
||||
- a desktop-managed SSH host entry
|
||||
- a saved tunneled environment
|
||||
|
||||
A known environment may or may not know the target `environmentId` before first successful connect.
|
||||
|
||||
In the hosted web app, known environments are browser-local. A hosted pairing URL can create the saved entry, but it does not give the hosted app a server-side control plane or a copy of the session state.
|
||||
|
||||
### AccessEndpoint
|
||||
|
||||
An `AccessEndpoint` is one concrete way to reach a known environment.
|
||||
|
||||
This is the key abstraction that keeps SSH from taking over the model.
|
||||
|
||||
A single environment may have many endpoints:
|
||||
|
||||
- `wss://t3.example.com`
|
||||
- `ws://10.0.0.25:3773`
|
||||
- a tunneled relay URL
|
||||
- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL
|
||||
|
||||
The environment stays the same. Only the access path changes.
|
||||
|
||||
### AdvertisedEndpoint
|
||||
|
||||
An `AdvertisedEndpoint` is a server or desktop-authored candidate endpoint for an environment. It is how the backend tells the client which URLs may be useful for pairing and reconnecting.
|
||||
|
||||
`AdvertisedEndpoint` is deliberately narrower than the full access model:
|
||||
|
||||
- it describes a concrete HTTP and WebSocket base URL pair
|
||||
- it can mark the endpoint as default, available, or unavailable
|
||||
- it includes reachability hints such as loopback, LAN, private, public, or tunnel
|
||||
- it includes compatibility hints such as whether the endpoint can be used from the hosted HTTPS app
|
||||
|
||||
Clients should treat advertised endpoints as hints, not as proof that a route works from the current device. The final connection attempt still decides whether the endpoint is reachable.
|
||||
|
||||
The UI presents one default advertised endpoint in the network-access summary and keeps the rest behind an expandable advanced list. The default controls pairing QR codes and primary copy actions. Users can override it, but that override is a UI preference, not backend configuration.
|
||||
|
||||
Persist the override by stable endpoint kind rather than raw URL whenever possible. For example, a LAN endpoint should be stored as the desktop LAN endpoint preference, not as `192.168.x.y`, because the address can change when the user switches networks. Provider endpoints should use provider-specific stable keys such as Tailscale IP or Tailscale MagicDNS HTTPS. Custom endpoints may fall back to their concrete identity.
|
||||
|
||||
When no user default is saved, endpoint selection should prefer:
|
||||
|
||||
1. endpoints compatible with the hosted HTTPS app
|
||||
2. explicitly default endpoints
|
||||
3. non-loopback endpoints
|
||||
4. loopback endpoints only for same-machine clients
|
||||
|
||||
This keeps endpoint discovery centralized without making any one provider, such as Tailscale or a future tunnel service, part of the core environment model.
|
||||
|
||||
### Endpoint providers
|
||||
|
||||
Endpoint providers are add-ons that contribute advertised endpoints for the current environment.
|
||||
|
||||
The provider boundary is intentionally outside the core environment model:
|
||||
|
||||
- core owns `ExecutionEnvironment`, saved environments, pairing, and connection lifecycle
|
||||
- providers discover or synthesize endpoints
|
||||
- providers return normalized `AdvertisedEndpoint` records
|
||||
- the UI and pairing logic select from those records without knowing provider-specific commands
|
||||
|
||||
The first provider is Tailscale. It can discover Tailnet IP and MagicDNS addresses from the local machine and publish them as additional endpoint candidates. Future providers, such as a hosted tunnel service, should plug into the same shape rather than adding a separate remote environment path.
|
||||
|
||||
Provider-specific confidence should remain a hint. A Tailscale endpoint still needs a successful browser or desktop connection before the client treats it as connected.
|
||||
|
||||
### Hosted pairing request
|
||||
|
||||
A hosted pairing request is a bootstrap URL for the static web app, not a transport.
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
|
||||
```
|
||||
|
||||
The hosted app reads the `host` parameter and pairing token, exchanges the token directly with that backend, then saves the resulting environment record in browser local storage.
|
||||
|
||||
Important constraints:
|
||||
|
||||
- the hosted app does not proxy HTTP or WebSocket traffic
|
||||
- the backend must still be reachable directly from the browser
|
||||
- HTTPS pages can only connect to HTTPS/WSS backends
|
||||
- HTTP LAN endpoints should keep using direct desktop or CLI pairing URLs
|
||||
- the token belongs in the URL hash so it is not sent to the hosted app origin
|
||||
|
||||
### RepositoryIdentity
|
||||
|
||||
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
|
||||
|
||||
It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository.
|
||||
|
||||
### Workspace / Project
|
||||
|
||||
The current `Project` model remains environment-local.
|
||||
|
||||
That means:
|
||||
|
||||
- a local clone and a remote clone are different projects
|
||||
- they may share a `RepositoryIdentity`
|
||||
- threads still bind to one project in one environment
|
||||
|
||||
## Access methods
|
||||
|
||||
Access methods answer one question:
|
||||
|
||||
How does the client speak WebSocket to a T3 server?
|
||||
|
||||
They do not answer:
|
||||
|
||||
- how the server got started
|
||||
- who manages the server process
|
||||
- whether the environment is local or remote
|
||||
|
||||
### 1. Direct WebSocket access
|
||||
|
||||
Examples:
|
||||
|
||||
- `ws://10.0.0.15:3773`
|
||||
- `wss://t3.example.com`
|
||||
|
||||
This is the base model and should be the first-class default.
|
||||
|
||||
Benefits:
|
||||
|
||||
- works for desktop, mobile, and web
|
||||
- no client-specific process management required
|
||||
- best fit for hosted or self-managed remote T3 deployments
|
||||
|
||||
Browser security rules are part of this access method. A hosted HTTPS web client can connect to `wss://` backends, but it cannot connect to plain `ws://` or `http://` LAN backends because that would be mixed content.
|
||||
|
||||
### 2. Tunneled WebSocket access
|
||||
|
||||
Examples:
|
||||
|
||||
- public relay URLs
|
||||
- private network relay URLs
|
||||
- local tunnel products such as pipenet
|
||||
|
||||
This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay.
|
||||
|
||||
For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment.
|
||||
|
||||
This is especially useful when:
|
||||
|
||||
- the host is behind NAT
|
||||
- inbound ports are unavailable
|
||||
- mobile must reach a desktop-hosted environment
|
||||
- a machine should be reachable without exposing raw LAN or public ports
|
||||
|
||||
Tailscale-backed access sits here architecturally even though the current implementation is endpoint discovery rather than a T3-managed tunnel. It contributes private-network endpoints and lets the existing HTTP/WebSocket client path do the actual connection.
|
||||
|
||||
### 3. Desktop-managed SSH access
|
||||
|
||||
SSH is an access and launch helper, not a separate environment type.
|
||||
|
||||
The desktop main process can use SSH to:
|
||||
|
||||
- reach a machine
|
||||
- probe it
|
||||
- launch or reuse a remote T3 server
|
||||
- establish a local port forward
|
||||
|
||||
After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port.
|
||||
|
||||
This keeps the renderer transport model consistent with every other access method.
|
||||
|
||||
The desktop main process owns the SSH bridge because it can spawn local SSH processes, manage askpass prompts, write temporary launch scripts, and clean up forwards. The renderer receives a saved environment record and connects through the forwarded URL; it should not need SSH-specific RPC paths for normal environment traffic.
|
||||
|
||||
## Launch methods
|
||||
|
||||
Launch methods answer a different question:
|
||||
|
||||
How does a T3 server come to exist on the target machine?
|
||||
|
||||
Launch and access should stay separate in the design.
|
||||
|
||||
### 1. Pre-existing server
|
||||
|
||||
The simplest launch method is no launch at all.
|
||||
|
||||
The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint.
|
||||
|
||||
This should be the first remote mode shipped because it validates the environment model with minimal extra machinery.
|
||||
|
||||
### 2. Desktop-managed remote launch over SSH
|
||||
|
||||
This is the main place where Zed is a useful reference.
|
||||
|
||||
Useful ideas to borrow from Zed:
|
||||
|
||||
- remote probing
|
||||
- platform detection
|
||||
- session directories with pid/log metadata
|
||||
- reconnect-friendly launcher behavior
|
||||
- desktop-owned connection UX
|
||||
|
||||
What should be different in T3:
|
||||
|
||||
- no custom stdio/socket proxy protocol between renderer and remote runtime
|
||||
- no attempt to make the remote runtime look like an editor transport
|
||||
- keep the final client-to-server connection as WebSocket
|
||||
|
||||
The recommended T3 flow is:
|
||||
|
||||
1. Desktop connects over SSH.
|
||||
2. Desktop probes the remote machine and verifies T3 availability.
|
||||
3. Desktop launches or reuses a remote T3 server.
|
||||
4. Desktop establishes local port forwarding.
|
||||
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
|
||||
|
||||
The saved environment should remember that it was created by desktop SSH launch only for reconnect and lifecycle UX. That metadata should not change the server protocol or the environment identity model.
|
||||
|
||||
Failure handling should be explicit:
|
||||
|
||||
- SSH authentication failure should surface before any environment is saved
|
||||
- remote launch failure should include remote logs or the launcher command output when available
|
||||
- forwarded-port failure should leave the saved environment disconnected rather than falling back to an unrelated endpoint
|
||||
- reconnect should attempt to restore the SSH bridge before reconnecting the normal WebSocket client
|
||||
|
||||
### 3. Client-managed local publish
|
||||
|
||||
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
|
||||
|
||||
This is useful for:
|
||||
|
||||
- exposing a desktop-hosted environment to mobile
|
||||
- temporary remote access without changing router or firewall settings
|
||||
|
||||
This is still a launch concern, not a new environment kind.
|
||||
|
||||
## Why access and launch must stay separate
|
||||
|
||||
These concerns are easy to conflate, but separating them prevents architectural drift.
|
||||
|
||||
Examples:
|
||||
|
||||
- A manually hosted T3 server might be reached through direct `wss`.
|
||||
- The same server might also be reachable through a tunnel.
|
||||
- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket.
|
||||
- A local desktop server might be published through a tunnel for mobile.
|
||||
|
||||
In all of those cases, the `ExecutionEnvironment` is the same kind of thing.
|
||||
|
||||
Only the launch and access paths differ.
|
||||
|
||||
## Security model
|
||||
|
||||
Remote support must assume that some environments will be reachable over untrusted networks.
|
||||
|
||||
That means:
|
||||
|
||||
- remote-capable environments should require explicit authentication
|
||||
- tunnel exposure should not rely on obscurity
|
||||
- client-saved endpoints should carry enough auth metadata to reconnect safely
|
||||
|
||||
T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention.
|
||||
|
||||
For publicly reachable environments, authenticated access should be treated as required.
|
||||
|
||||
Hosted pairing should be treated as a client-side convenience only. The hosted app must not receive pairing tokens through query parameters, must not store pairing state server-side, and must not imply that an HTTP backend is safe or reachable from an HTTPS browser context.
|
||||
|
||||
## Relationship to Zed
|
||||
|
||||
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
|
||||
|
||||
The relevant lessons are:
|
||||
|
||||
- remote bootstrap should be explicit
|
||||
- reconnect should be first-class
|
||||
- connection UX belongs in the client shell
|
||||
- runtime ownership should stay clearly on the remote host
|
||||
|
||||
The important mismatch is transport shape.
|
||||
|
||||
Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime.
|
||||
|
||||
T3 should not copy that part.
|
||||
|
||||
T3 already has the right runtime boundary:
|
||||
|
||||
- one T3 server per environment
|
||||
- ordinary HTTP/WebSocket between client and environment
|
||||
|
||||
So T3 should borrow Zed's launch discipline, not its transport protocol.
|
||||
|
||||
## Recommended rollout
|
||||
|
||||
1. First-class known environments and access endpoints.
|
||||
2. Direct `ws` / `wss` remote environments.
|
||||
3. Authenticated tunnel-backed environments.
|
||||
4. Desktop-managed SSH launch and forwarding.
|
||||
5. Multi-environment UI improvements after the base runtime path is proven.
|
||||
|
||||
This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows.
|
||||
@@ -0,0 +1,2 @@
|
||||
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
||||
* text=auto eol=lf
|
||||
+5
-1
@@ -28,4 +28,8 @@ github:realAhmedRoach
|
||||
github:shiroyasha9
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
github:Ymit24
|
||||
github:shivamhwp
|
||||
github:jappyjan
|
||||
github:justsomelegs
|
||||
github:UtkarshUsername
|
||||
@@ -9,7 +9,8 @@ on:
|
||||
jobs:
|
||||
quality:
|
||||
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -70,12 +71,13 @@ jobs:
|
||||
|
||||
- name: Verify preload bundle output
|
||||
run: |
|
||||
test -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
test -f apps/desktop/dist-electron/preload.cjs
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
|
||||
|
||||
release_smoke:
|
||||
name: Release Smoke
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -90,5 +92,8 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Exercise release-only workflow steps
|
||||
run: node scripts/release-smoke.ts
|
||||
@@ -124,25 +124,49 @@ jobs:
|
||||
group: pr-size-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
- name: Checkout base repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Sync PR size label
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||
with:
|
||||
script: |
|
||||
const { execFileSync } = require("node:child_process");
|
||||
|
||||
const issueNumber = context.payload.pull_request.number;
|
||||
const baseSha = context.payload.pull_request.base.sha;
|
||||
const headSha = context.payload.pull_request.head.sha;
|
||||
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
|
||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||
// Keep this aligned with the repo's test entrypoints and test-only support files.
|
||||
const testFilePatterns = [
|
||||
/(^|\/)__tests__(\/|$)/,
|
||||
/(^|\/)tests?(\/|$)/,
|
||||
/^apps\/server\/integration\//,
|
||||
/\.(test|spec|browser|integration)\.[^.\/]+$/,
|
||||
const testExcludePathspecs = [
|
||||
":(glob,exclude)**/__tests__/**",
|
||||
":(glob,exclude)**/test/**",
|
||||
":(glob,exclude)**/tests/**",
|
||||
":(glob,exclude)apps/server/integration/**",
|
||||
":(glob,exclude)**/*.test.*",
|
||||
":(glob,exclude)**/*.spec.*",
|
||||
":(glob,exclude)**/*.browser.*",
|
||||
":(glob,exclude)**/*.integration.*",
|
||||
];
|
||||
|
||||
const isTestFile = (filename) =>
|
||||
testFilePatterns.some((pattern) => pattern.test(filename));
|
||||
const sumNumstat = (text) =>
|
||||
text
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.reduce((total, line) => {
|
||||
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
|
||||
const additions =
|
||||
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
|
||||
const deletions =
|
||||
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
|
||||
|
||||
return total + additions + deletions;
|
||||
}, 0);
|
||||
|
||||
const resolveSizeLabel = (totalChangedLines) => {
|
||||
if (totalChangedLines < 10) {
|
||||
@@ -168,40 +192,53 @@ jobs:
|
||||
return "size:XXL";
|
||||
};
|
||||
|
||||
const files = await github.paginate(
|
||||
github.rest.pulls.listFiles,
|
||||
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
execFileSync(
|
||||
"git",
|
||||
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
|
||||
{
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: issueNumber,
|
||||
per_page: 100,
|
||||
stdio: "inherit",
|
||||
},
|
||||
(response) => response.data,
|
||||
);
|
||||
|
||||
if (files.length >= 3000) {
|
||||
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
|
||||
if (resolvedHeadSha !== headSha) {
|
||||
core.warning(
|
||||
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
|
||||
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
|
||||
);
|
||||
}
|
||||
|
||||
let testChangedLines = 0;
|
||||
let nonTestChangedLines = 0;
|
||||
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
for (const file of files) {
|
||||
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--numstat",
|
||||
"--ignore-all-space",
|
||||
"--ignore-blank-lines",
|
||||
`${baseSha}...${resolvedHeadSha}`,
|
||||
];
|
||||
|
||||
if (changedLinesForFile === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isTestFile(file.filename)) {
|
||||
testChangedLines += changedLinesForFile;
|
||||
continue;
|
||||
}
|
||||
|
||||
nonTestChangedLines += changedLinesForFile;
|
||||
}
|
||||
const totalChangedLines = sumNumstat(
|
||||
execFileSync(
|
||||
"git",
|
||||
diffArgs,
|
||||
{ encoding: "utf8" },
|
||||
),
|
||||
);
|
||||
const nonTestChangedLines = sumNumstat(
|
||||
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
|
||||
encoding: "utf8",
|
||||
}),
|
||||
);
|
||||
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
|
||||
|
||||
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
|
||||
const nextLabelName = resolveSizeLabel(changedLines);
|
||||
|
||||
+320
-50
@@ -1,14 +1,25 @@
|
||||
name: Release Desktop
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
- "!v*-nightly.*"
|
||||
schedule:
|
||||
- cron: "0 */3 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
description: "Release channel"
|
||||
required: false
|
||||
default: stable
|
||||
type: choice
|
||||
options:
|
||||
- stable
|
||||
- nightly
|
||||
version:
|
||||
description: "Release version (for example 1.2.3 or v1.2.3)"
|
||||
required: true
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
@@ -16,44 +27,63 @@ permissions:
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
check_changes:
|
||||
name: Check for changes since last nightly
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
outputs:
|
||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: check
|
||||
name: Compare HEAD to last nightly tag
|
||||
run: |
|
||||
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
|
||||
if [[ -z "$last_nightly_tag" ]]; then
|
||||
echo "No previous nightly tag found. Proceeding with release."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
|
||||
head_sha=$(git rev-parse HEAD)
|
||||
|
||||
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
|
||||
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
|
||||
echo "has_changes=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: ubuntu-24.04
|
||||
needs: [check_changes]
|
||||
if: |
|
||||
!failure() && !cancelled() &&
|
||||
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
release_channel: ${{ steps.release_meta.outputs.release_channel }}
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
release_name: ${{ steps.release_meta.outputs.name }}
|
||||
short_sha: ${{ steps.release_meta.outputs.short_sha }}
|
||||
previous_tag: ${{ steps.previous_tag.outputs.previous_tag }}
|
||||
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
|
||||
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
|
||||
make_latest: ${{ steps.release_meta.outputs.make_latest }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
raw="${{ github.event.inputs.version }}"
|
||||
else
|
||||
raw="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
|
||||
version="${raw#v}"
|
||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "Invalid release version: $raw" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -68,6 +98,60 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
shell: bash
|
||||
env:
|
||||
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
|
||||
DISPATCH_VERSION: ${{ github.event.inputs.version }}
|
||||
NIGHTLY_DATE: ${{ github.run_started_at }}
|
||||
NIGHTLY_SHA: ${{ github.sha }}
|
||||
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
|
||||
nightly_date="$(date -u -d "$NIGHTLY_DATE" +%Y%m%d)"
|
||||
|
||||
node scripts/resolve-nightly-release.ts \
|
||||
--date "$nightly_date" \
|
||||
--run-number "$NIGHTLY_RUN_NUMBER" \
|
||||
--sha "$NIGHTLY_SHA" \
|
||||
--github-output
|
||||
|
||||
echo "release_channel=nightly" >> "$GITHUB_OUTPUT"
|
||||
echo "cli_dist_tag=nightly" >> "$GITHUB_OUTPUT"
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
raw="${DISPATCH_VERSION}"
|
||||
if [[ -z "$raw" ]]; then
|
||||
echo "workflow_dispatch stable releases require the version input." >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
raw="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
|
||||
version="${raw#v}"
|
||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "Invalid release version: $raw" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "release_channel=stable" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
echo "name=T3 Code v$version" >> "$GITHUB_OUTPUT"
|
||||
echo "cli_dist_tag=latest" >> "$GITHUB_OUTPUT"
|
||||
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
@@ -77,34 +161,49 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- id: previous_tag
|
||||
name: Resolve previous release tag
|
||||
run: |
|
||||
node scripts/resolve-previous-release-tag.ts \
|
||||
--channel "${{ steps.release_meta.outputs.release_channel }}" \
|
||||
--current-tag "${{ steps.release_meta.outputs.tag }}" \
|
||||
--github-output
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- label: macOS arm64
|
||||
runner: macos-14
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
- label: macOS x64
|
||||
runner: macos-15-intel
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
- label: Linux x64
|
||||
runner: ubuntu-24.04
|
||||
runner: blacksmith-32vcpu-ubuntu-2404
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
- label: Windows x64
|
||||
runner: windows-2022
|
||||
runner: blacksmith-32vcpu-windows-2025
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
# - label: Windows arm64
|
||||
# runner: windows-11-arm
|
||||
# platform: win
|
||||
# target: nsis
|
||||
# arch: arm64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -128,6 +227,23 @@ jobs:
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Install Spectre-mitigated MSVC libs
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
$installPath = & $vswhere -products * -latest -property installationPath
|
||||
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
|
||||
$proc = Start-Process -FilePath $setupExe `
|
||||
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
|
||||
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
|
||||
-Wait -PassThru -NoNewWindow
|
||||
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
|
||||
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
|
||||
Write-Error "Visual Studio Installer failed with exit code $code"
|
||||
exit $code
|
||||
}
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
@@ -204,18 +320,31 @@ jobs:
|
||||
"release/*.AppImage" \
|
||||
"release/*.exe" \
|
||||
"release/*.blockmap" \
|
||||
"release/latest*.yml"; do
|
||||
"release/*.yml"; do
|
||||
for file in $pattern; do
|
||||
cp "$file" release-publish/
|
||||
done
|
||||
done
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
|
||||
if [[ -f release-publish/latest-mac.yml ]]; then
|
||||
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
|
||||
fi
|
||||
shopt -s nullglob
|
||||
for manifest in release-publish/*-mac.yml; do
|
||||
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
|
||||
done
|
||||
fi
|
||||
|
||||
# Enable if Windows arm64 builds are enabled.
|
||||
# Windows updater metadata is channel-specific (for example
|
||||
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
|
||||
# release job can merge matching arm64/x64 manifests back into one
|
||||
# canonical manifest per channel.
|
||||
# if [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
# shopt -s nullglob
|
||||
# for manifest in release-publish/*.yml; do
|
||||
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
|
||||
# done
|
||||
# fi
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -226,7 +355,9 @@ jobs:
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -245,32 +376,53 @@ jobs:
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build web package
|
||||
run: bun --filter=@t3tools/web run build
|
||||
|
||||
- name: Build CLI package
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
run: bun --filter=t3 run build
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -280,17 +432,72 @@ jobs:
|
||||
|
||||
- name: Merge macOS updater manifests
|
||||
run: |
|
||||
node scripts/merge-mac-update-manifests.ts \
|
||||
release-assets/latest-mac.yml \
|
||||
release-assets/latest-mac-x64.yml
|
||||
rm -f release-assets/latest-mac-x64.yml
|
||||
shopt -s nullglob
|
||||
for x64_manifest in release-assets/*-mac-x64.yml; do
|
||||
arm64_manifest="${x64_manifest%-x64.yml}.yml"
|
||||
if [[ -f "$arm64_manifest" ]]; then
|
||||
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
|
||||
rm -f "$x64_manifest"
|
||||
fi
|
||||
done
|
||||
|
||||
# - name: Merge Windows updater manifests
|
||||
# run: |
|
||||
# shopt -s nullglob
|
||||
# found_windows_manifest=false
|
||||
# for x64_manifest in release-assets/*-win-x64.yml; do
|
||||
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
|
||||
# continue
|
||||
# fi
|
||||
|
||||
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
|
||||
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
|
||||
# if [[ ! -f "$arm64_manifest" ]]; then
|
||||
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
|
||||
# exit 1
|
||||
# fi
|
||||
|
||||
# found_windows_manifest=true
|
||||
# node scripts/merge-update-manifests.ts --platform win \
|
||||
# "$arm64_manifest" \
|
||||
# "$x64_manifest" \
|
||||
# "$output_manifest"
|
||||
# rm -f "$arm64_manifest" "$x64_manifest"
|
||||
# done
|
||||
|
||||
# if [[ "$found_windows_manifest" != true ]]; then
|
||||
# echo "No Windows updater manifests found to merge." >&2
|
||||
# exit 1
|
||||
# fi
|
||||
|
||||
- name: Publish release
|
||||
if: needs.preflight.outputs.previous_tag != ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
name: ${{ needs.preflight.outputs.release_name }}
|
||||
generate_release_notes: true
|
||||
previous_tag: ${{ needs.preflight.outputs.previous_tag }}
|
||||
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
|
||||
make_latest: ${{ needs.preflight.outputs.make_latest }}
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
- name: Publish first release
|
||||
if: needs.preflight.outputs.previous_tag == ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: ${{ needs.preflight.outputs.release_name }}
|
||||
generate_release_notes: true
|
||||
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
|
||||
make_latest: ${{ needs.preflight.outputs.make_latest }}
|
||||
@@ -300,13 +507,16 @@ jobs:
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/latest*.yml
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
@@ -344,6 +554,9 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
@@ -352,7 +565,7 @@ jobs:
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
run: bunx oxfmt@0.40.0 apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
@@ -375,3 +588,60 @@ jobs:
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
git push origin HEAD:main
|
||||
|
||||
announce_discord:
|
||||
name: Announce release on Discord
|
||||
if: |
|
||||
always() && !cancelled() &&
|
||||
needs.preflight.result == 'success' &&
|
||||
needs.release.result == 'success' &&
|
||||
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
|
||||
needs: [preflight, release, finalize]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
|
||||
- name: Announce prerelease on Discord
|
||||
if: needs.preflight.outputs.is_prerelease == 'true'
|
||||
continue-on-error: true
|
||||
env:
|
||||
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_NIGHTLY_ROLE_ID }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
|
||||
run: |
|
||||
node scripts/notify-discord-release.ts prerelease \
|
||||
--role-id "$DISCORD_MENTION_ROLE_ID" \
|
||||
--release-name "${{ needs.preflight.outputs.release_name }}" \
|
||||
--release-version "${{ needs.preflight.outputs.version }}" \
|
||||
--tag "${{ needs.preflight.outputs.tag }}" \
|
||||
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
|
||||
|
||||
- name: Announce latest release on Discord
|
||||
if: needs.preflight.outputs.make_latest == 'true'
|
||||
continue-on-error: true
|
||||
env:
|
||||
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_LATEST_ROLE_ID }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
|
||||
run: |
|
||||
node scripts/notify-discord-release.ts latest \
|
||||
--role-id "$DISCORD_MENTION_ROLE_ID" \
|
||||
--release-name "${{ needs.preflight.outputs.release_name }}" \
|
||||
--release-version "${{ needs.preflight.outputs.version }}" \
|
||||
--tag "${{ needs.preflight.outputs.tag }}" \
|
||||
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
|
||||
@@ -12,6 +12,7 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
release-mock/
|
||||
.t3
|
||||
.idea/
|
||||
apps/web/.playwright
|
||||
@@ -20,3 +21,5 @@ apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
squashfs-root/
|
||||
.vercel
|
||||
+13
-2
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
".reference",
|
||||
".plans",
|
||||
"dist",
|
||||
"dist-electron",
|
||||
@@ -8,7 +9,17 @@
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js"
|
||||
"apps/web/public/mockServiceWorker.js",
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts",
|
||||
"*.icon/**"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
"sortPackageJson": {},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [".devcontainer/devcontainer.json"],
|
||||
"options": {
|
||||
"trailingComma": "none"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,823 @@
|
||||
# Server Auth Model Plan
|
||||
|
||||
## Purpose
|
||||
|
||||
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
|
||||
|
||||
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
|
||||
|
||||
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
|
||||
|
||||
## Primary goals
|
||||
|
||||
- Make auth server-wide, not WebSocket-only.
|
||||
- Make insecure exposure hard to do accidentally.
|
||||
- Preserve zero-login local desktop UX for desktop-managed environments.
|
||||
- Support browser-native pairing and session auth.
|
||||
- Leave room for native/mobile credentials later without rewriting the server boundary.
|
||||
- Keep auth separate from transport and launch method.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Full multi-user authorization and RBAC.
|
||||
- OAuth / SSO / enterprise identity.
|
||||
- Passkeys or biometric UX in v1.
|
||||
- Syncing auth state across environments.
|
||||
- Designing the full remote environment product in this document.
|
||||
|
||||
## Core decisions
|
||||
|
||||
### 1. Auth is a server concern
|
||||
|
||||
Every privileged surface of the T3 server must go through the same auth policy engine:
|
||||
|
||||
- HTTP routes
|
||||
- WebSocket upgrades
|
||||
- RPC methods reached through WebSocket
|
||||
|
||||
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
|
||||
|
||||
### 2. Pairing and session are different things
|
||||
|
||||
The system should distinguish:
|
||||
|
||||
- bootstrap credentials
|
||||
- session credentials
|
||||
|
||||
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
|
||||
|
||||
Session credentials are the durable credentials used after pairing.
|
||||
|
||||
Bootstrap should never become the long-lived request credential.
|
||||
|
||||
### 3. Auth and transport are separate
|
||||
|
||||
Auth must not be defined by how the client reached the server.
|
||||
|
||||
Examples:
|
||||
|
||||
- local desktop-managed server
|
||||
- LAN `ws://`
|
||||
- public `wss://`
|
||||
- tunneled `wss://`
|
||||
- SSH-forwarded `ws://127.0.0.1:<port>`
|
||||
|
||||
All of these should feed into the same auth model.
|
||||
|
||||
### 4. Exposure level changes defaults
|
||||
|
||||
The more exposed an environment is, the narrower the safe default should be.
|
||||
|
||||
Safe default expectations:
|
||||
|
||||
- local desktop-managed: auto-pair allowed
|
||||
- loopback browser access: explicit bootstrap allowed
|
||||
- non-loopback bind: auth required
|
||||
- tunnel/public endpoint: auth required, explicit enablement required
|
||||
|
||||
### 5. Browser and native clients may use different session credentials
|
||||
|
||||
The auth model should support more than one session credential type even if only one ships first.
|
||||
|
||||
Examples:
|
||||
|
||||
- browser session cookie
|
||||
- native bearer/device token
|
||||
|
||||
This should be represented in the model now, even if browser cookies are the first implementation.
|
||||
|
||||
## Target auth domain
|
||||
|
||||
### Route classes
|
||||
|
||||
Every route or transport entrypoint should be classified as one of:
|
||||
|
||||
1. `public`
|
||||
2. `bootstrap`
|
||||
3. `authenticated`
|
||||
|
||||
#### `public`
|
||||
|
||||
Unauthenticated by definition.
|
||||
|
||||
Should be extremely small. Examples:
|
||||
|
||||
- static shell needed to render the pairing/login UI
|
||||
- favicon/assets required for the pairing screen
|
||||
- a minimal server health/version endpoint if needed
|
||||
|
||||
#### `bootstrap`
|
||||
|
||||
Used only to exchange a bootstrap credential for a session.
|
||||
|
||||
Examples:
|
||||
|
||||
- Initial bootstrap envelope over file descriptor at startup
|
||||
- `POST /api/auth/bootstrap`
|
||||
- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX
|
||||
|
||||
#### `authenticated`
|
||||
|
||||
Everything that reveals machine state or mutates it.
|
||||
|
||||
Examples:
|
||||
|
||||
- WebSocket upgrade
|
||||
- orchestration snapshot and events
|
||||
- terminal open/write/close
|
||||
- project search and file writes
|
||||
- git routes
|
||||
- attachments
|
||||
- project favicon lookup
|
||||
- server settings
|
||||
|
||||
The default stance should be: if it touches the machine, it is authenticated.
|
||||
|
||||
## Credential model
|
||||
|
||||
### Bootstrap credentials
|
||||
|
||||
Initial credential types to model:
|
||||
|
||||
- `desktop-bootstrap`
|
||||
- `one-time-token`
|
||||
|
||||
Possible future credential types:
|
||||
|
||||
- `device-code`
|
||||
- `passkey-assertion`
|
||||
- `external-identity`
|
||||
|
||||
#### `desktop-bootstrap`
|
||||
|
||||
Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments.
|
||||
|
||||
Properties:
|
||||
|
||||
- launcher-provided
|
||||
- short-lived
|
||||
- one-time or bounded-use
|
||||
- never shown to the user as a reusable password
|
||||
|
||||
#### `one-time-token`
|
||||
|
||||
Used for explicit browser/mobile pairing flows.
|
||||
|
||||
Properties:
|
||||
|
||||
- short TTL
|
||||
- one-time use
|
||||
- safe to embed in a pairing URL fragment
|
||||
- exchanged for a session credential
|
||||
|
||||
### Session credentials
|
||||
|
||||
Initial credential types to model:
|
||||
|
||||
- `browser-session-cookie`
|
||||
- `bearer-session-token`
|
||||
|
||||
#### `browser-session-cookie`
|
||||
|
||||
Primary browser credential.
|
||||
|
||||
Properties:
|
||||
|
||||
- signed
|
||||
- `HttpOnly`
|
||||
- bounded lifetime
|
||||
- revocable by server key rotation or session invalidation
|
||||
|
||||
#### `bearer-session-token`
|
||||
|
||||
Reserved for native/mobile or non-browser clients.
|
||||
|
||||
Properties:
|
||||
|
||||
- opaque token, not a bootstrap secret
|
||||
- long enough lifetime to survive reconnects
|
||||
- stored in secure client storage when available
|
||||
|
||||
## Auth policy model
|
||||
|
||||
Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics.
|
||||
|
||||
### Policy examples
|
||||
|
||||
#### `DesktopManagedLocalPolicy`
|
||||
|
||||
Default for desktop-managed local server.
|
||||
|
||||
Allowed bootstrap methods:
|
||||
|
||||
- `desktop-bootstrap`
|
||||
|
||||
Allowed session methods:
|
||||
|
||||
- `browser-session-cookie`
|
||||
|
||||
Disabled by default:
|
||||
|
||||
- `one-time-token`
|
||||
- `bearer-session-token`
|
||||
- password login
|
||||
- public pairing
|
||||
|
||||
#### `LoopbackBrowserPolicy`
|
||||
|
||||
Used for browser access on localhost without desktop-managed bootstrap.
|
||||
|
||||
Allowed bootstrap methods:
|
||||
|
||||
- `one-time-token`
|
||||
|
||||
Allowed session methods:
|
||||
|
||||
- `browser-session-cookie`
|
||||
|
||||
#### `RemoteReachablePolicy`
|
||||
|
||||
Used when binding non-loopback or using an explicit remote/tunnel workflow.
|
||||
|
||||
Allowed bootstrap methods:
|
||||
|
||||
- `one-time-token`
|
||||
- possibly `desktop-bootstrap` when a desktop shell is brokering access
|
||||
|
||||
Allowed session methods:
|
||||
|
||||
- `browser-session-cookie`
|
||||
- `bearer-session-token`
|
||||
|
||||
#### `UnsafeNoAuthPolicy`
|
||||
|
||||
Should exist only as an explicit escape hatch.
|
||||
|
||||
Requirements:
|
||||
|
||||
- explicit opt-in flag
|
||||
- loud startup warnings
|
||||
- never defaulted automatically
|
||||
|
||||
## Effect-native service model
|
||||
|
||||
### `ServerAuth`
|
||||
|
||||
The main auth facade used by HTTP routes and WebSocket upgrade handling.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- classify requests
|
||||
- authenticate requests
|
||||
- authorize bootstrap attempts
|
||||
- create sessions from bootstrap credentials
|
||||
- enforce policy by environment mode
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
export interface ServerAuthShape {
|
||||
readonly getCapabilities: Effect.Effect<AuthCapabilities>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
routeClass: RouteAuthClass,
|
||||
) => Effect.Effect<AuthContext, AuthError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, AuthError>;
|
||||
readonly exchangeBootstrapCredential: (
|
||||
input: BootstrapExchangeInput,
|
||||
) => Effect.Effect<SessionGrant, AuthError>;
|
||||
}
|
||||
|
||||
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
|
||||
"t3/ServerAuth",
|
||||
) {}
|
||||
```
|
||||
|
||||
### `BootstrapCredentialService`
|
||||
|
||||
Owns issuance, storage, validation, and consumption of bootstrap credentials.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- issue desktop bootstrap grants
|
||||
- issue one-time pairing tokens
|
||||
- validate TTL and single-use semantics
|
||||
- consume bootstrap grants atomically
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
export interface BootstrapCredentialServiceShape {
|
||||
readonly issueDesktopBootstrap: (
|
||||
input: IssueDesktopBootstrapInput,
|
||||
) => Effect.Effect<BootstrapCredential>;
|
||||
readonly issueOneTimeToken: (
|
||||
input: IssueOneTimeTokenInput,
|
||||
) => Effect.Effect<BootstrapCredential>;
|
||||
readonly consume: (
|
||||
presented: PresentedBootstrapCredential,
|
||||
) => Effect.Effect<ConsumedBootstrapCredential, BootstrapCredentialError>;
|
||||
}
|
||||
```
|
||||
|
||||
### `SessionCredentialService`
|
||||
|
||||
Owns creation and validation of authenticated sessions.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- mint cookie sessions
|
||||
- mint bearer sessions
|
||||
- validate active session credentials
|
||||
- revoke sessions if needed later
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
export interface SessionCredentialServiceShape {
|
||||
readonly createBrowserSession: (
|
||||
input: CreateSessionFromBootstrapInput,
|
||||
) => Effect.Effect<BrowserSessionGrant, SessionCredentialError>;
|
||||
readonly createBearerSession: (
|
||||
input: CreateSessionFromBootstrapInput,
|
||||
) => Effect.Effect<BearerSessionGrant, SessionCredentialError>;
|
||||
readonly authenticateCookie: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, SessionCredentialError>;
|
||||
readonly authenticateBearer: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthContext, SessionCredentialError>;
|
||||
}
|
||||
```
|
||||
|
||||
### `ServerAuthPolicy`
|
||||
|
||||
Pure policy/config service that decides which credential types are allowed.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- map runtime mode and bind/exposure settings to allowed auth methods
|
||||
- answer whether a route can be public
|
||||
- answer whether remote exposure requires auth
|
||||
|
||||
This should stay mostly pure and cheap to test.
|
||||
|
||||
### `ServerSecretStore`
|
||||
|
||||
Owns long-lived server signing keys and secrets.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- get or create signing key
|
||||
- rotate signing key
|
||||
- abstract secure OS-backed storage vs filesystem fallback
|
||||
|
||||
Important:
|
||||
|
||||
- prefer platform secure storage when available
|
||||
- support hardened filesystem fallback for headless/server-only environments
|
||||
|
||||
### `BrowserSessionCookieCodec`
|
||||
|
||||
Focused utility service for cookie encode/decode/signing behavior.
|
||||
|
||||
This should not own policy. It should only own the cookie format.
|
||||
|
||||
### `AuthRouteGuards`
|
||||
|
||||
Thin helper layer used by routes to enforce auth consistently.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- require auth for HTTP route handlers
|
||||
- classify route auth mode
|
||||
- convert auth failures into `401` / `403`
|
||||
|
||||
This prevents every route from re-implementing the same pattern.
|
||||
|
||||
Integrates with `HttpRouter.middleware` to enforce auth consistently.
|
||||
|
||||
## Suggested layer graph
|
||||
|
||||
```text
|
||||
ServerSecretStore
|
||||
├─> BootstrapCredentialService
|
||||
├─> BrowserSessionCookieCodec
|
||||
└─> SessionCredentialService
|
||||
|
||||
ServerAuthPolicy
|
||||
├─> BootstrapCredentialService
|
||||
├─> SessionCredentialService
|
||||
└─> ServerAuth
|
||||
|
||||
ServerAuth
|
||||
└─> AuthRouteGuards
|
||||
```
|
||||
|
||||
Layer naming should follow existing repo style:
|
||||
|
||||
- `ServerSecretStoreLive`
|
||||
- `BootstrapCredentialServiceLive`
|
||||
- `SessionCredentialServiceLive`
|
||||
- `ServerAuthPolicyLive`
|
||||
- `ServerAuthLive`
|
||||
- `AuthRouteGuardsLive`
|
||||
|
||||
## High-level implementation examples
|
||||
|
||||
### Example: WebSocket upgrade auth
|
||||
|
||||
Current state:
|
||||
|
||||
- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts)
|
||||
|
||||
Target shape:
|
||||
|
||||
```ts
|
||||
const websocketUpgradeAuth = HttpMiddleware.make((httpApp) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
yield* serverAuth.authenticateWebSocketUpgrade(request);
|
||||
return yield* httpApp;
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Then the `/ws` route becomes:
|
||||
|
||||
```ts
|
||||
export const websocketRpcRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/ws",
|
||||
rpcWebSocketHttpEffect.pipe(
|
||||
websocketUpgradeAuth,
|
||||
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
|
||||
),
|
||||
);
|
||||
```
|
||||
|
||||
This keeps the route itself declarative and makes auth compose like normal HTTP middleware.
|
||||
|
||||
### Example: authenticated HTTP route
|
||||
|
||||
For routes like attachments or project favicon:
|
||||
|
||||
```ts
|
||||
const authenticatedRoute = (routeClass: RouteAuthClass) =>
|
||||
HttpMiddleware.make((httpApp) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
yield* serverAuth.authenticateHttpRequest(request, routeClass);
|
||||
return yield* httpApp;
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
```ts
|
||||
export const attachmentsRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
|
||||
serveAttachment.pipe(
|
||||
authenticatedRoute(RouteAuthClass.Authenticated),
|
||||
Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)),
|
||||
),
|
||||
);
|
||||
```
|
||||
|
||||
### Example: desktop bootstrap exchange
|
||||
|
||||
The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel.
|
||||
|
||||
That grant is then exchanged for a browser cookie session when the renderer loads.
|
||||
|
||||
Sketch:
|
||||
|
||||
```ts
|
||||
const pairDesktopRenderer = Effect.gen(function* () {
|
||||
const bootstrapService = yield* BootstrapCredentialService;
|
||||
const credential = yield* bootstrapService.issueDesktopBootstrap({
|
||||
audience: "desktop-renderer",
|
||||
ttlMs: 30_000,
|
||||
});
|
||||
return credential;
|
||||
});
|
||||
```
|
||||
|
||||
The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid.
|
||||
|
||||
### Example: one-time pairing URL
|
||||
|
||||
For browser-driven pairing:
|
||||
|
||||
```ts
|
||||
const createPairingToken = Effect.gen(function* () {
|
||||
const bootstrapService = yield* BootstrapCredentialService;
|
||||
return yield* bootstrapService.issueOneTimeToken({
|
||||
ttlMs: 5 * 60_000,
|
||||
audience: "browser",
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
|
||||
|
||||
## Sequence diagrams
|
||||
|
||||
These flows are meant to anchor the auth model in concrete user journeys.
|
||||
|
||||
The important invariant across all of them is:
|
||||
|
||||
- access method is not the auth method
|
||||
- launch method is not the auth method
|
||||
- bootstrap credential is not the session credential
|
||||
|
||||
### Normal desktop user
|
||||
|
||||
This is the default desktop-managed local flow.
|
||||
|
||||
The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopMain = Electron main
|
||||
SecretStore = secure local secret backend
|
||||
T3Server = local backend child process
|
||||
Frontend = desktop renderer
|
||||
|
||||
DesktopMain -> SecretStore : getOrCreate("server-signing-key")
|
||||
SecretStore --> DesktopMain : signing key available
|
||||
|
||||
DesktopMain -> T3Server : spawn server (--bootstrap-fd ...)
|
||||
DesktopMain -> T3Server : send desktop bootstrap envelope
|
||||
note over T3Server : policy = DesktopManagedLocalPolicy
|
||||
note over T3Server : allowed pairing = desktop-bootstrap only
|
||||
|
||||
Frontend -> DesktopMain : request local bootstrap grant
|
||||
DesktopMain --> Frontend : short-lived desktop bootstrap grant
|
||||
|
||||
Frontend -> T3Server : POST /api/auth/bootstrap
|
||||
T3Server -> T3Server : validate desktop bootstrap grant
|
||||
T3Server -> T3Server : create browser session
|
||||
T3Server --> Frontend : Set-Cookie: session=...
|
||||
|
||||
Frontend -> T3Server : GET /ws + authenticated cookie
|
||||
T3Server -> T3Server : validate cookie session
|
||||
T3Server --> Frontend : websocket accepted
|
||||
```
|
||||
|
||||
### `npx t3` user
|
||||
|
||||
This is the standalone local server flow.
|
||||
|
||||
There is no trusted desktop shell here, so pairing should be explicit.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
UserShell = npx t3 launcher
|
||||
T3Server = standalone local server
|
||||
Browser = browser tab
|
||||
|
||||
UserShell -> T3Server : start server
|
||||
T3Server -> T3Server : getOrCreate("server-signing-key")
|
||||
note over T3Server : policy = LoopbackBrowserPolicy
|
||||
|
||||
UserShell -> T3Server : issue one-time pairing token
|
||||
T3Server --> UserShell : pairing URL or pairing token
|
||||
|
||||
UserShell --> Browser : open /pair?token=...
|
||||
|
||||
Browser -> T3Server : GET /pair?token=...
|
||||
T3Server -> T3Server : validate one-time token
|
||||
T3Server -> T3Server : create browser session
|
||||
T3Server --> Browser : Set-Cookie: session=...
|
||||
T3Server --> Browser : redirect to app
|
||||
|
||||
Browser -> T3Server : GET /ws + authenticated cookie
|
||||
T3Server --> Browser : websocket accepted
|
||||
```
|
||||
|
||||
### Phone user with tunneled host
|
||||
|
||||
This is the explicit remote access flow for a browser on another device.
|
||||
|
||||
The tunnel only provides reachability. It must not imply trust.
|
||||
|
||||
Recommended UX:
|
||||
|
||||
- desktop shows a QR code
|
||||
- desktop also shows a copyable pairing URL
|
||||
- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopUser = user at the host machine
|
||||
DesktopMain = desktop app
|
||||
Tunnel = tunnel provider
|
||||
T3Server = T3 server
|
||||
PhoneBrowser = mobile browser
|
||||
|
||||
DesktopUser -> DesktopMain : enable remote access via tunnel
|
||||
DesktopMain -> T3Server : switch policy to RemoteReachablePolicy
|
||||
DesktopMain -> Tunnel : publish local T3 endpoint
|
||||
Tunnel --> DesktopMain : public https/wss URL
|
||||
|
||||
DesktopMain -> T3Server : issue one-time pairing token
|
||||
T3Server --> DesktopMain : pairing token
|
||||
DesktopMain -> DesktopUser : show QR code / shareable URL
|
||||
|
||||
DesktopUser -> PhoneBrowser : scan QR / open URL
|
||||
PhoneBrowser -> Tunnel : GET https://public-host/pair?token=...
|
||||
Tunnel -> T3Server : forward request
|
||||
T3Server -> T3Server : validate one-time token
|
||||
T3Server -> T3Server : create mobile browser session
|
||||
T3Server --> PhoneBrowser : Set-Cookie: session=...
|
||||
T3Server --> PhoneBrowser : redirect to app
|
||||
|
||||
PhoneBrowser -> Tunnel : GET /ws + authenticated cookie
|
||||
Tunnel -> T3Server : forward websocket upgrade
|
||||
T3Server --> PhoneBrowser : websocket accepted
|
||||
```
|
||||
|
||||
### Phone user with private network
|
||||
|
||||
This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale.
|
||||
|
||||
The auth flow should stay the same.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopUser = user at the host machine
|
||||
T3Server = T3 server
|
||||
PrivateNet = tailscale / private LAN
|
||||
PhoneBrowser = mobile browser
|
||||
|
||||
DesktopUser -> T3Server : enable private-network access
|
||||
T3Server -> T3Server : switch policy to RemoteReachablePolicy
|
||||
DesktopUser -> T3Server : issue one-time pairing token
|
||||
T3Server --> DesktopUser : pairing URL / QR
|
||||
|
||||
DesktopUser -> PhoneBrowser : open private-network URL
|
||||
PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=...
|
||||
PrivateNet -> T3Server : route request
|
||||
T3Server -> T3Server : validate one-time token
|
||||
T3Server -> T3Server : create mobile browser session
|
||||
T3Server --> PhoneBrowser : Set-Cookie: session=...
|
||||
T3Server --> PhoneBrowser : redirect to app
|
||||
|
||||
PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
|
||||
PrivateNet -> T3Server : websocket upgrade
|
||||
T3Server --> PhoneBrowser : websocket accepted
|
||||
```
|
||||
|
||||
### Desktop user adding new SSH hosts
|
||||
|
||||
SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
|
||||
|
||||
The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
|
||||
|
||||
```text
|
||||
Participants:
|
||||
DesktopUser = local desktop user
|
||||
DesktopMain = desktop app
|
||||
SSH = ssh transport/session
|
||||
RemoteHost = remote machine
|
||||
RemoteT3 = remote T3 server
|
||||
Frontend = desktop renderer
|
||||
|
||||
DesktopUser -> DesktopMain : add SSH host
|
||||
DesktopMain -> SSH : connect to remote host
|
||||
SSH -> RemoteHost : probe environment / verify t3 availability
|
||||
DesktopMain -> SSH : run remote launch command
|
||||
SSH -> RemoteHost : t3 remote launch --json
|
||||
RemoteHost -> RemoteT3 : start or reuse server
|
||||
RemoteT3 --> RemoteHost : port + environment metadata
|
||||
RemoteHost --> SSH : launch result JSON
|
||||
SSH --> DesktopMain : remote server details
|
||||
|
||||
DesktopMain -> SSH : establish local port forward
|
||||
SSH --> DesktopMain : localhost:FORWARDED_PORT ready
|
||||
|
||||
note over RemoteT3 : policy = RemoteReachablePolicy
|
||||
note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
|
||||
|
||||
Frontend -> DesktopMain : request bootstrap for selected environment
|
||||
DesktopMain --> Frontend : short-lived bootstrap grant
|
||||
|
||||
Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
|
||||
RemoteT3 -> RemoteT3 : validate bootstrap grant
|
||||
RemoteT3 -> RemoteT3 : create browser session
|
||||
RemoteT3 --> Frontend : Set-Cookie: session=...
|
||||
|
||||
Frontend -> RemoteT3 : GET /ws + authenticated cookie
|
||||
RemoteT3 --> Frontend : websocket accepted
|
||||
```
|
||||
|
||||
## Storage decisions
|
||||
|
||||
### Server secrets
|
||||
|
||||
Use a `ServerSecretStore` abstraction.
|
||||
|
||||
Preferred order (use a layer for each, resolve on startup):
|
||||
|
||||
1. OS secure storage if available
|
||||
2. hardened filesystem fallback if not
|
||||
|
||||
The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
|
||||
|
||||
### Client credentials
|
||||
|
||||
Client-side credential persistence should prefer secure storage when available:
|
||||
|
||||
- desktop: OS keychain / secure store
|
||||
- mobile: platform secure storage
|
||||
- browser: cookie session for browser auth
|
||||
|
||||
This concern should stay in the client shell/runtime layer, not the server auth layer.
|
||||
|
||||
## What to build now
|
||||
|
||||
These are the parts worth building before remote environments ship:
|
||||
|
||||
1. `ServerAuth` service boundary.
|
||||
2. route classification and route guards.
|
||||
3. `ServerSecretStore` abstraction.
|
||||
4. bootstrap vs session credential split.
|
||||
5. browser session cookie codec as one session method.
|
||||
6. explicit auth capabilities/config surfaced in contracts.
|
||||
|
||||
Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
|
||||
|
||||
## What to add as part of first remote-capable auth
|
||||
|
||||
1. Browser pairing flow using one-time bootstrap token and cookie session.
|
||||
2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
|
||||
3. Auth-required defaults for any non-loopback or explicitly published server.
|
||||
4. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks.
|
||||
|
||||
## What to defer
|
||||
|
||||
- passkeys / WebAuthn
|
||||
- iCloud Keychain / Face ID-specific UX
|
||||
- multi-user permissions
|
||||
- collaboration roles
|
||||
- OAuth / SSO
|
||||
- polished session management UI
|
||||
- complex device approval flows
|
||||
|
||||
These can all sit on top of the same bootstrap/session/service split.
|
||||
|
||||
## Relationship to future remote environments
|
||||
|
||||
Remote access is one reason this auth model matters, but the auth model should not be remote-shaped.
|
||||
|
||||
Keep the design focused on:
|
||||
|
||||
- one T3 server
|
||||
- one auth policy
|
||||
- multiple credential types
|
||||
- multiple future access methods
|
||||
|
||||
That keeps the server auth model stable even as access methods expand later.
|
||||
|
||||
## Recommended implementation order
|
||||
|
||||
### Phase 1
|
||||
|
||||
- Introduce route auth classes.
|
||||
- Add `ServerAuth` and `AuthRouteGuards`.
|
||||
- Move existing `authToken` check behind `ServerAuth`.
|
||||
- Require auth for all privileged HTTP routes as well as WebSocket.
|
||||
|
||||
### Phase 2
|
||||
|
||||
- Add `ServerSecretStore` service with platform-specific layer implementations.
|
||||
- `layerOSXKeychain`, `layer
|
||||
- Add bootstrap/session split.
|
||||
- Add browser session cookie support.
|
||||
- Add one-time bootstrap exchange endpoint.
|
||||
|
||||
### Phase 3
|
||||
|
||||
- Add desktop bootstrap flow on top of the same services.
|
||||
- Make desktop-managed local environments default to bootstrap-only pairing.
|
||||
- Surface auth capabilities in shared contracts and renderer bootstrap.
|
||||
|
||||
### Phase 4
|
||||
|
||||
- Add non-browser bearer session support if mobile/native needs it.
|
||||
- Add richer policy modes for remote-reachable environments.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- No privileged HTTP or WebSocket path bypasses auth policy.
|
||||
- Local desktop-managed flows still avoid a visible login screen.
|
||||
- Non-loopback or published environments require explicit authenticated pairing by default.
|
||||
- Bootstrap and session credentials are distinct in code and in behavior.
|
||||
- Auth logic is centralized in Effect services/layers rather than route-local branching.
|
||||
@@ -0,0 +1,350 @@
|
||||
# Remote Endpoints and Hosted Static App Plan
|
||||
|
||||
## Purpose
|
||||
|
||||
Make remote access feel first-class while keeping the free DIY path open.
|
||||
|
||||
The immediate product goal is:
|
||||
|
||||
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
|
||||
- users can generate a hosted pairing link for `app.t3.codes`
|
||||
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
|
||||
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
|
||||
|
||||
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
|
||||
|
||||
## Current State
|
||||
|
||||
Already present or in progress:
|
||||
|
||||
- Server auth distinguishes bootstrap credentials from session credentials.
|
||||
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
|
||||
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
|
||||
- Remote environment WebSocket connections use a short-lived WebSocket token.
|
||||
- Pairing URLs can carry tokens in the URL fragment.
|
||||
- Hosted `/pair?host=...#token=...` can add a saved environment.
|
||||
- Hosted static startup can avoid assuming the page origin is the backend.
|
||||
|
||||
Main gaps:
|
||||
|
||||
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
|
||||
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
|
||||
- Tailscale/MagicDNS endpoints are not detected or surfaced.
|
||||
- Hosted-static empty/offline states are still thin.
|
||||
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
|
||||
|
||||
## Core Decision: Add `AdvertisedEndpoint`
|
||||
|
||||
Add a new first-class contract instead of extending the environment descriptor.
|
||||
|
||||
### Why not extend `ExecutionEnvironmentDescriptor`
|
||||
|
||||
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
|
||||
|
||||
Examples:
|
||||
|
||||
- environment id
|
||||
- label
|
||||
- platform
|
||||
- server version
|
||||
- capabilities
|
||||
|
||||
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
|
||||
|
||||
Examples:
|
||||
|
||||
- loopback URL
|
||||
- LAN URL
|
||||
- Tailscale IP URL
|
||||
- MagicDNS/Serve URL
|
||||
- manual URL
|
||||
- future T3 Tunnel URL
|
||||
- browser compatibility and exposure level
|
||||
|
||||
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
|
||||
|
||||
### Target Contract
|
||||
|
||||
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
|
||||
|
||||
```ts
|
||||
type AdvertisedEndpointProvider =
|
||||
| "loopback"
|
||||
| "lan"
|
||||
| "tailscale-ip"
|
||||
| "tailscale-magicdns"
|
||||
| "manual"
|
||||
| "t3-tunnel";
|
||||
|
||||
type AdvertisedEndpointVisibility = "local" | "private-network" | "tailnet" | "public";
|
||||
|
||||
type AdvertisedEndpointCompatibility = {
|
||||
hostedHttpsApp: "compatible" | "mixed-content-blocked" | "untrusted-certificate" | "unknown";
|
||||
desktopApp: "compatible" | "unknown";
|
||||
};
|
||||
|
||||
type AdvertisedEndpoint = {
|
||||
id: string;
|
||||
provider: AdvertisedEndpointProvider;
|
||||
label: string;
|
||||
httpBaseUrl: string;
|
||||
wsBaseUrl: string;
|
||||
visibility: AdvertisedEndpointVisibility;
|
||||
compatibility: AdvertisedEndpointCompatibility;
|
||||
source: "server" | "desktop" | "user";
|
||||
status: "available" | "unavailable" | "unknown";
|
||||
isDefault?: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
Keep the contract schema-only. All classification logic belongs in `packages/shared`, `apps/server`, `apps/desktop`, or `apps/web`.
|
||||
|
||||
## HTTP/WS and HTTPS/WSS Readiness
|
||||
|
||||
The codebase is partially ready, but the UX and compatibility model are not explicit enough.
|
||||
|
||||
What is ready:
|
||||
|
||||
- Remote target parsing already derives `ws://` from `http://` and `wss://` from `https://`.
|
||||
- Saved environments store both HTTP and WebSocket base URLs.
|
||||
- Remote auth uses bearer tokens instead of cookies, so cross-origin hosted clients are viable.
|
||||
- WebSocket connections can use a dynamically issued `wsToken`.
|
||||
- Server CORS support exists for browser remote auth endpoints.
|
||||
|
||||
What is not solved by code alone:
|
||||
|
||||
- `https://app.t3.codes` cannot reliably call `http://...` or `ws://...` endpoints because browsers block mixed content.
|
||||
- `wss://100.x.y.z:3773` needs a certificate the browser trusts. A raw Tailscale IP does not solve certificate trust.
|
||||
- LAN `http://192.168.x.y:3773` is usable from another desktop/native context but not from the hosted HTTPS app.
|
||||
- The UI needs to explain why an endpoint is copyable for desktop pairing but not hosted-app compatible.
|
||||
|
||||
Policy:
|
||||
|
||||
- Support both HTTP/WS and HTTPS/WSS at the runtime layer.
|
||||
- Mark endpoint compatibility at the product layer.
|
||||
- Generate `app.t3.codes` links only from endpoints that are likely hosted-browser compatible, or show a warning with an explicit fallback.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Endpoint Sources
|
||||
|
||||
Endpoint records can come from several providers:
|
||||
|
||||
1. **Server runtime**
|
||||
- headless bind host and port
|
||||
- server-known explicit advertised host config
|
||||
|
||||
2. **Desktop shell**
|
||||
- loopback backend URL
|
||||
- LAN exposure state
|
||||
- network interface discovery
|
||||
- Tailscale CLI/status discovery
|
||||
|
||||
3. **User configuration**
|
||||
- manually added hostnames
|
||||
- preferred endpoint labels
|
||||
- hidden/disabled endpoints
|
||||
|
||||
4. **Future cloud provider**
|
||||
- T3 Tunnel endpoint
|
||||
- billing/account status
|
||||
- tunnel lifecycle state
|
||||
|
||||
### Endpoint Registry
|
||||
|
||||
Create a central runtime registry:
|
||||
|
||||
- `packages/contracts/src/remoteAccess.ts`
|
||||
- `packages/shared/src/remoteAccess.ts` for URL normalization and compatibility classification
|
||||
- `apps/server/src/remoteAccess/*` for server/headless endpoints
|
||||
- `apps/desktop/src/remoteAccess/*` for desktop-discovered endpoints
|
||||
- `apps/web/src/environments/endpoints/*` for client-side display and pairing selection
|
||||
|
||||
The web app should consume endpoint records and not care whether they came from LAN, Tailscale, or a future tunnel.
|
||||
|
||||
### Pairing Link Generation
|
||||
|
||||
Move hosted pairing link generation to endpoint-driven input:
|
||||
|
||||
```ts
|
||||
buildHostedPairingUrl({
|
||||
endpoint: AdvertisedEndpoint,
|
||||
token,
|
||||
});
|
||||
```
|
||||
|
||||
Generated URL:
|
||||
|
||||
```text
|
||||
https://app.t3.codes/pair?host=<encoded endpoint httpBaseUrl>#token=<one-time token>
|
||||
```
|
||||
|
||||
Use fragment tokens by default. Continue accepting `?token=` for compatibility.
|
||||
|
||||
## Phase 1: Endpoint Abstraction
|
||||
|
||||
### Goals
|
||||
|
||||
- Centralize URL normalization, protocol derivation, and compatibility checks.
|
||||
- Replace ad hoc desktop `endpointUrl` pairing logic with endpoint selection.
|
||||
- Preserve all current remote behavior.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Add `AdvertisedEndpoint` schemas to `packages/contracts`.
|
||||
2. Add shared helpers:
|
||||
- normalize HTTP base URL
|
||||
- derive WebSocket base URL
|
||||
- classify loopback/private/LAN/Tailscale/public host
|
||||
- classify hosted HTTPS compatibility
|
||||
3. Add server endpoint discovery:
|
||||
- loopback endpoint
|
||||
- configured non-loopback endpoint
|
||||
- explicit advertised host override
|
||||
4. Add desktop endpoint discovery:
|
||||
- local loopback
|
||||
- LAN exposure endpoint
|
||||
- endpoint status labels
|
||||
5. Add WebSocket/API method or existing config field for endpoint snapshots.
|
||||
6. Refactor settings connections UI:
|
||||
- render endpoint rows
|
||||
- endpoint picker for pairing link copy
|
||||
- show compatibility warnings
|
||||
7. Refactor hosted link builder to accept endpoint records.
|
||||
8. Add tests for URL normalization and compatibility classification.
|
||||
|
||||
### Acceptance Criteria
|
||||
|
||||
- Existing LAN/network access UI still works.
|
||||
- Pairing links are generated from endpoint records.
|
||||
- Loopback endpoints never produce hosted pairing links silently.
|
||||
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
|
||||
- No remote environment runtime changes are required for existing saved environments.
|
||||
|
||||
## Phase 2: BYO Tailscale/MagicDNS
|
||||
|
||||
### Goals
|
||||
|
||||
- Detect free DIY Tailscale reachability.
|
||||
- Surface Tailscale endpoints as normal advertised endpoints.
|
||||
- Keep users in control of their own tailnet.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Detect Tailscale IPs from network interfaces:
|
||||
- IPv4 `100.64.0.0/10`
|
||||
- mark as `provider: "tailscale-ip"`
|
||||
2. Add optional desktop-side `tailscale status --json` discovery:
|
||||
- MagicDNS hostname
|
||||
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
|
||||
- graceful failure if CLI is missing
|
||||
3. Add manual Tailscale endpoint override:
|
||||
- hostname
|
||||
- label
|
||||
- preferred/default flag
|
||||
4. Show Tailscale endpoint rows in settings:
|
||||
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
|
||||
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
|
||||
5. Generate pairing links using selected Tailscale endpoint.
|
||||
6. Document DIY setup:
|
||||
- local desktop-to-desktop over Tailscale
|
||||
- hosted app requirements
|
||||
- why HTTPS matters
|
||||
|
||||
### Acceptance Criteria
|
||||
|
||||
- A machine on Tailscale shows a Tailscale endpoint without paid features.
|
||||
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
|
||||
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
|
||||
- Tailscale is optional and never required for regular LAN/loopback use.
|
||||
|
||||
## Phase 3: Hosted Static App Completion
|
||||
|
||||
### Goals
|
||||
|
||||
- `app.t3.codes` works as a real client shell.
|
||||
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Finish hosted-static root behavior:
|
||||
- no primary backend required
|
||||
- saved environment hydration before initial routing decisions
|
||||
- first saved environment selected as active
|
||||
2. Add hosted empty state:
|
||||
- no saved environments
|
||||
- paste pairing URL
|
||||
- add host + token
|
||||
3. Add offline saved environment UI:
|
||||
- last connected
|
||||
- reconnect
|
||||
- remove
|
||||
- copy/add alternate endpoint
|
||||
4. Audit primary-backend assumptions:
|
||||
- command palette
|
||||
- settings pages
|
||||
- server config atom defaults
|
||||
- keybindings
|
||||
- provider/model lists
|
||||
- update/desktop-only affordances
|
||||
5. Add route tests for:
|
||||
- hosted `/pair?host=...#token=...`
|
||||
- hosted root with no saved environments
|
||||
- hosted root with saved environment
|
||||
- primary backend unavailable but saved environment present
|
||||
6. Add deployment hardening:
|
||||
- SPA fallback
|
||||
- strict CSP
|
||||
- no third-party scripts
|
||||
- no query token logging
|
||||
- disable or hide source maps in production if needed
|
||||
7. Add browser error messages:
|
||||
- mixed content
|
||||
- unreachable backend
|
||||
- CORS failure
|
||||
- certificate failure
|
||||
|
||||
### Acceptance Criteria
|
||||
|
||||
- `app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
|
||||
- A saved environment can be used without any backend at `app.t3.codes`.
|
||||
- Offline machines show a useful state instead of a generic boot error.
|
||||
- HTTP endpoints are still supported in desktop/native/local contexts.
|
||||
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
|
||||
|
||||
## Phase 4: Future T3 Tunnel Provider
|
||||
|
||||
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
|
||||
|
||||
Future tunnel provider responsibilities:
|
||||
|
||||
- create endpoint with `provider: "t3-tunnel"`
|
||||
- surface tunnel status
|
||||
- provide stable HTTPS URL
|
||||
- use existing backend pairing/session auth
|
||||
- never bypass server auth
|
||||
|
||||
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
|
||||
|
||||
## Security Checklist
|
||||
|
||||
- Pairing tokens are short-lived and one-time.
|
||||
- Generated hosted pairing links put tokens in the fragment.
|
||||
- The backend remains the authorization boundary.
|
||||
- Endpoint discovery never disables backend auth.
|
||||
- Hosted app does not silently downgrade to HTTP.
|
||||
- Tunnel/public endpoints require explicit user action.
|
||||
- Client sessions remain revocable.
|
||||
- Endpoint URLs and request logs must avoid recording pairing tokens.
|
||||
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
|
||||
|
||||
## Verification
|
||||
|
||||
Each implementation PR should run:
|
||||
|
||||
- `bun fmt`
|
||||
- `bun lint`
|
||||
- `bun typecheck`
|
||||
- focused tests for changed backend/web behavior
|
||||
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
# Version Control Phase 1: VCS Driver Foundation
|
||||
|
||||
## Goal
|
||||
|
||||
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
|
||||
|
||||
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
|
||||
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
|
||||
- Add server services under `apps/server/src/vcs`:
|
||||
- `Services/VcsDriver.ts`
|
||||
- `Services/VcsRepositoryResolver.ts`
|
||||
- `Services/VcsProcess.ts`
|
||||
- `Layers/GitVcsDriver.ts`
|
||||
- `errors.ts`
|
||||
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
|
||||
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
|
||||
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
|
||||
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
|
||||
- No T3 Review implementation yet.
|
||||
- No broad UI redesign.
|
||||
|
||||
## Driver Model
|
||||
|
||||
Use provider-neutral nouns in new APIs:
|
||||
|
||||
- `VcsDriver`: local repository mechanics.
|
||||
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
|
||||
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
|
||||
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
|
||||
- `RefName`: branch, bookmark, tag, or provider-specific ref.
|
||||
|
||||
The initial driver capabilities should be explicit:
|
||||
|
||||
```ts
|
||||
export interface VcsDriverCapabilities {
|
||||
readonly kind: "git" | "jj" | "sapling" | "unknown";
|
||||
readonly supportsWorktrees: boolean;
|
||||
readonly supportsBookmarks: boolean;
|
||||
readonly supportsAtomicSnapshot: boolean;
|
||||
readonly supportsPushDefaultRemote: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
|
||||
|
||||
- `detectRepository(cwd)`
|
||||
- `status(cwd, options)`
|
||||
- `listRefs(cwd, query/pagination)`
|
||||
- `checkoutRef(cwd, ref)`
|
||||
- `createRef(cwd, ref, from?)`
|
||||
- `createWorkspace(cwd, ref, path?)`
|
||||
- `removeWorkspace(path)`
|
||||
- `prepareChangeContext(cwd, filePaths?)`
|
||||
- `createChange(cwd, message, options)`
|
||||
- `push(cwd, target?)`
|
||||
- `rangeContext(cwd, base, head)`
|
||||
- `listWorkspaceFiles(cwd, options)`
|
||||
|
||||
## Effect Process Layer
|
||||
|
||||
Create a small reusable `VcsProcess` service instead of using `runProcess`.
|
||||
|
||||
Requirements:
|
||||
|
||||
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
|
||||
- Support scoped acquisition/release for long-running commands and interruption.
|
||||
- Support bounded stdout/stderr collection with truncation markers.
|
||||
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
|
||||
- Support stdin.
|
||||
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
|
||||
- Stream output lines to progress callbacks as Effects.
|
||||
- Return a typed `ProcessOutput` value for successful execution.
|
||||
- Fail with typed errors, not generic thrown exceptions.
|
||||
|
||||
Errors should be schema-backed tagged classes, for example:
|
||||
|
||||
- `VcsProcessSpawnError`
|
||||
- `VcsProcessExitError`
|
||||
- `VcsProcessTimeoutError`
|
||||
- `VcsOutputDecodeError`
|
||||
- `VcsRepositoryDetectionError`
|
||||
- `VcsUnsupportedOperationError`
|
||||
|
||||
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
|
||||
|
||||
## Git Driver Rewrite
|
||||
|
||||
Rewrite Git support against `VcsProcess`.
|
||||
|
||||
Carry forward current behavior from:
|
||||
|
||||
- `apps/server/src/git/Layers/GitCore.ts`
|
||||
- `apps/server/src/git/Layers/GitCore.test.ts`
|
||||
- current Git status/branch/worktree contracts
|
||||
|
||||
But split the implementation into smaller modules:
|
||||
|
||||
- command execution and hardening config
|
||||
- repository detection
|
||||
- status parsing
|
||||
- branch/ref parsing
|
||||
- worktree operations
|
||||
- commit/range context generation
|
||||
- push/pull operations
|
||||
|
||||
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
|
||||
|
||||
## Freshness and Local Caching
|
||||
|
||||
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
|
||||
|
||||
Treat these as live/local:
|
||||
|
||||
- repository detection for the active cwd
|
||||
- working copy dirty state
|
||||
- staged/unstaged/untracked file summaries
|
||||
- current branch/bookmark/change name
|
||||
- local branch/bookmark lists
|
||||
- local worktree/workspace lists
|
||||
|
||||
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
|
||||
|
||||
Treat these as cached or explicit-refresh only:
|
||||
|
||||
- remote tracking branch refreshes
|
||||
- ahead/behind counts that require network fetches
|
||||
- default branch discovery from a remote provider
|
||||
- remote branch lists beyond locally known refs
|
||||
|
||||
The VCS driver should expose freshness metadata with status results:
|
||||
|
||||
```ts
|
||||
export interface VcsFreshness {
|
||||
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
|
||||
readonly observedAt: string;
|
||||
readonly expiresAt?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
|
||||
|
||||
Use Effect `Cache` for repository identity and expensive local metadata:
|
||||
|
||||
- key by resolved repository root plus VCS kind
|
||||
- invalidate on cwd/root changes and workspace mutation operations
|
||||
- use short TTLs for local status caches when filesystem events are unavailable
|
||||
- never hide command failures behind stale values unless the caller explicitly accepts stale data
|
||||
|
||||
## Cutover Policy
|
||||
|
||||
Prefer direct migration and deletion over compatibility wrappers.
|
||||
|
||||
Rules:
|
||||
|
||||
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
|
||||
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
|
||||
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
|
||||
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
|
||||
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
|
||||
- No new feature work may depend on transitional modules.
|
||||
|
||||
Expected transitional candidates:
|
||||
|
||||
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
|
||||
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
|
||||
|
||||
## Tests
|
||||
|
||||
Add integration-style tests with real temporary Git repositories for the new Git driver:
|
||||
|
||||
- non-repository detection
|
||||
- status for clean/dirty/untracked/staged states
|
||||
- branch/ref list with pagination
|
||||
- checkout/create branch
|
||||
- worktree create/remove
|
||||
- commit context generation with file filters
|
||||
- commit creation with hook progress events
|
||||
- push behavior against a local bare remote
|
||||
- status polling does not perform remote network refresh by default
|
||||
- concurrent duplicate status requests are coalesced
|
||||
- bounded output/truncation
|
||||
- timeout/interruption
|
||||
- typed error shape for command failure and missing executable
|
||||
|
||||
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. Add `vcs` contracts and tagged errors.
|
||||
2. Add `VcsProcess` and unit tests around process execution semantics.
|
||||
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
|
||||
4. Implement `GitVcsDriver` with real Git command integration tests.
|
||||
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
|
||||
6. Move commit/range/push callers to the VCS service directly.
|
||||
7. Delete migrated `GitCore` internals and tests as each caller group moves.
|
||||
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
|
||||
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Current Git branch/status/worktree/commit behavior remains intact.
|
||||
- New Git implementation does not depend on `processRunner.ts`.
|
||||
- New errors are typed and inspectable by tests.
|
||||
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
|
||||
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
||||
- Background status refresh is local-only by default and cannot hit provider rate limits.
|
||||
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
|
||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
||||
@@ -0,0 +1,268 @@
|
||||
# Version Control Phase 2: Source Control Provider Foundation
|
||||
|
||||
## Goal
|
||||
|
||||
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
|
||||
|
||||
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
|
||||
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
|
||||
- Add server services under `apps/server/src/sourceControl`:
|
||||
- `Services/SourceControlProvider.ts`
|
||||
- `Services/SourceControlProviderRegistry.ts`
|
||||
- `Services/SourceControlProcess.ts`
|
||||
- `Layers/GitHubSourceControlProvider.ts`
|
||||
- `errors.ts`
|
||||
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
|
||||
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
|
||||
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
|
||||
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
|
||||
- No in-app review UI yet.
|
||||
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
|
||||
|
||||
## Provider Model
|
||||
|
||||
Use provider-neutral names:
|
||||
|
||||
- `SourceControlProvider`: hosted repository and change-request mechanics.
|
||||
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
|
||||
- `ChangeRequestThread`: review or discussion thread.
|
||||
- `ChangeRequestComment`: top-level or inline comment.
|
||||
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
|
||||
|
||||
Core provider operations:
|
||||
|
||||
- `detectRemote(remoteUrl)`
|
||||
- `checkAuth(cwd)`
|
||||
- `getRepository(cwd | remoteUrl)`
|
||||
- `getDefaultTargetRef(repository)`
|
||||
- `listChangeRequests(repository, filters)`
|
||||
- `getChangeRequest(repository, reference)`
|
||||
- `createChangeRequest(repository, input)`
|
||||
- `checkoutChangeRequest(cwd, changeRequest, options)`
|
||||
- `getCloneUrls(repository)`
|
||||
|
||||
Review-facing operations should be designed now, even if unimplemented:
|
||||
|
||||
- `listReviewThreads(changeRequest)`
|
||||
- `createReviewComment(changeRequest, input)`
|
||||
- `replyToReviewThread(thread, input)`
|
||||
- `resolveReviewThread(thread)`
|
||||
- `submitReview(changeRequest, input)`
|
||||
|
||||
Each operation should be guarded by capabilities:
|
||||
|
||||
```ts
|
||||
export interface SourceControlProviderCapabilities {
|
||||
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
|
||||
readonly supportsCreateChangeRequest: boolean;
|
||||
readonly supportsCheckoutChangeRequest: boolean;
|
||||
readonly supportsReviewThreads: boolean;
|
||||
readonly supportsInlineComments: boolean;
|
||||
readonly supportsDraftChangeRequests: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
## Provider Registry
|
||||
|
||||
Add a registry that resolves a provider from repository remotes and explicit user input.
|
||||
|
||||
Rules:
|
||||
|
||||
- Detection should be pure where possible and testable without spawning CLIs.
|
||||
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
|
||||
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
|
||||
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
|
||||
|
||||
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
|
||||
|
||||
## Rate Limits and Provider Caching
|
||||
|
||||
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
|
||||
|
||||
Default behavior:
|
||||
|
||||
- Pure URL/remote parsing is always live because it is local.
|
||||
- Provider detection from local remotes is live-local.
|
||||
- Authentication checks are cached.
|
||||
- Repository metadata is cached.
|
||||
- Default branch metadata is cached.
|
||||
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
|
||||
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
|
||||
- Create/update operations invalidate affected cache keys immediately after success.
|
||||
|
||||
The provider API should make freshness explicit:
|
||||
|
||||
```ts
|
||||
export interface SourceControlFreshness {
|
||||
readonly source: "live-local" | "cached-provider" | "live-provider";
|
||||
readonly observedAt: string;
|
||||
readonly expiresAt?: string;
|
||||
readonly stale?: boolean;
|
||||
}
|
||||
|
||||
export type ProviderRefreshPolicy =
|
||||
| "cache-first"
|
||||
| "stale-while-revalidate"
|
||||
| "force-refresh"
|
||||
| "local-only";
|
||||
```
|
||||
|
||||
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
|
||||
|
||||
Use Effect `Cache` for provider data:
|
||||
|
||||
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
|
||||
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
|
||||
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
|
||||
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
|
||||
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
|
||||
|
||||
Provider drivers should surface rate-limit signals when available:
|
||||
|
||||
- remaining quota
|
||||
- reset time
|
||||
- retry-after duration
|
||||
- whether the limit is primary, secondary/abuse, or unknown
|
||||
|
||||
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
|
||||
|
||||
Avoid rate-limit footguns:
|
||||
|
||||
- no provider calls from render loops or fast status polling
|
||||
- no listing all PRs/MRs across all repos to infer one branch state
|
||||
- no silent GitHub fallback for unknown providers
|
||||
- no unbounded cache cardinality for branch names or free-form search queries
|
||||
- no per-thread duplicate provider refresh when multiple views observe the same repository
|
||||
|
||||
## GitHub Provider Rewrite
|
||||
|
||||
Rewrite GitHub support as `GitHubSourceControlProvider`.
|
||||
|
||||
Carry forward behavior from:
|
||||
|
||||
- `apps/server/src/git/Layers/GitHubCli.ts`
|
||||
- `apps/server/src/git/Layers/GitHubCli.test.ts`
|
||||
- `apps/server/src/git/githubPullRequests.ts`
|
||||
- GitHub-specific `GitManager` PR paths
|
||||
|
||||
Implementation requirements:
|
||||
|
||||
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
|
||||
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
|
||||
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
|
||||
- Keep stdout/stderr bounded.
|
||||
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
|
||||
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
|
||||
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
|
||||
|
||||
## GitManager Cutover
|
||||
|
||||
Refactor `GitManager` so it coordinates three independent services:
|
||||
|
||||
- `VcsDriver` for local repository mechanics.
|
||||
- `SourceControlProviderRegistry` for hosted provider selection.
|
||||
- `TextGeneration` for message/body generation.
|
||||
|
||||
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
|
||||
|
||||
The Commit + PR flow should become:
|
||||
|
||||
1. Resolve VCS repository and local status.
|
||||
2. Resolve source-control provider from remotes.
|
||||
3. Generate commit content through the existing text generation service.
|
||||
4. Create local change through `VcsDriver`.
|
||||
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
|
||||
6. Generate change-request title/body.
|
||||
7. Create the change request through `SourceControlProvider`.
|
||||
|
||||
## Cutover Policy
|
||||
|
||||
This phase should aggressively remove old GitHub-specific internals.
|
||||
|
||||
Rules:
|
||||
|
||||
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
|
||||
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
|
||||
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
|
||||
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
|
||||
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
|
||||
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
|
||||
|
||||
## GitLab and Azure Readiness
|
||||
|
||||
Use the triaged references as implementation inputs, not merge targets:
|
||||
|
||||
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
|
||||
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
|
||||
|
||||
The abstraction should let Phase 3 add:
|
||||
|
||||
- `GitLabSourceControlProvider` using `glab`.
|
||||
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
|
||||
|
||||
No provider should need to edit GitHub code to join the registry.
|
||||
|
||||
## T3 Review Design Constraint
|
||||
|
||||
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
|
||||
|
||||
That means contracts should include stable IDs and enough metadata for:
|
||||
|
||||
- file-level diffs
|
||||
- inline review threads
|
||||
- resolved/unresolved state
|
||||
- top-level discussion comments
|
||||
- pending review submission
|
||||
- provider URL back-links
|
||||
|
||||
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
|
||||
|
||||
## Tests
|
||||
|
||||
Add tests at three levels:
|
||||
|
||||
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
|
||||
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
|
||||
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
|
||||
|
||||
Required cases:
|
||||
|
||||
- GitHub PR URL, number, and branch-ish references.
|
||||
- GitLab MR URL/reference parsing.
|
||||
- Azure DevOps PR URL parsing for same-repo URLs.
|
||||
- unknown provider returns unsupported-operation errors.
|
||||
- missing CLI and auth failures produce distinct typed errors.
|
||||
- invalid CLI JSON fails at decode boundary with useful context.
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. Add `sourceControl` contracts and provider-neutral schemas.
|
||||
2. Add shared remote/reference parser helpers and tests.
|
||||
3. Add `SourceControlProcess` and provider errors.
|
||||
4. Add provider registry with GitHub-only registration.
|
||||
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
|
||||
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
|
||||
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
|
||||
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
|
||||
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Existing GitHub Commit + PR and PR checkout flows still work.
|
||||
- `GitManager` no longer imports or depends on `GitHubCli`.
|
||||
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
||||
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
|
||||
- Unknown/unsupported providers fail explicitly and visibly.
|
||||
- GitHub command execution does not depend on `processRunner.ts`.
|
||||
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
|
||||
- Rate-limit responses become typed errors with retry/reset metadata where available.
|
||||
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
|
||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
||||
@@ -10,3 +10,5 @@
|
||||
8. `08-precommit-format-and-lint.md`
|
||||
9. `09-event-state-test-expansion.md`
|
||||
10. `10-unify-process-session-abstraction.md`
|
||||
19. `19-version-control-phase-1-vcs-driver-foundation.md`
|
||||
20. `20-version-control-phase-2-source-control-provider-foundation.md`
|
||||
@@ -0,0 +1,89 @@
|
||||
# Replace React Query With AtomRpc + Atom State
|
||||
|
||||
## Summary
|
||||
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
|
||||
- Keep Zustand for orchestration read model and UI state.
|
||||
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
|
||||
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
|
||||
|
||||
## Target Architecture
|
||||
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
|
||||
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
|
||||
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
|
||||
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
|
||||
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
|
||||
|
||||
## Phase 1: Infrastructure First
|
||||
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
|
||||
2. Build the AtomRpc client on top of that layer.
|
||||
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
|
||||
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
|
||||
5. Land this as a no-behavior-change PR.
|
||||
|
||||
## Phase 2: Replace `wsNativeApi`-Owned Push State
|
||||
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
|
||||
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
|
||||
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
|
||||
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
||||
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
|
||||
|
||||
## Phase 3: Replace React Query Domain By Domain
|
||||
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
|
||||
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
|
||||
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
|
||||
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
|
||||
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
|
||||
6. Defer the desktop updater until the last phase.
|
||||
|
||||
## Phase 4: Move Root Invalidation Off `queryClient`
|
||||
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
|
||||
2. Keep Zustand orchestration/event application unchanged.
|
||||
3. Map current effects exactly:
|
||||
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
|
||||
- file creation/deletion/restoration touches `project:${cwd}`
|
||||
- config-affecting server events touch `server-config`
|
||||
|
||||
## Phase 5: Remove Imperative `NativeApi` Usage
|
||||
1. Create narrow modules instead of a replacement mega-facade:
|
||||
- `rpc/orchestrationActions.ts`
|
||||
- `rpc/terminalActions.ts`
|
||||
- `rpc/gitActions.ts`
|
||||
- `rpc/projectActions.ts`
|
||||
- `platform/desktopBridge.ts`
|
||||
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
|
||||
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
|
||||
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
|
||||
|
||||
## Phase 6: Remove React Query Completely
|
||||
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
|
||||
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
|
||||
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
|
||||
4. Delete the old query-option tests.
|
||||
|
||||
## Public Interfaces And Types
|
||||
- Preserve the current server-state hook names during the transition.
|
||||
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
|
||||
- Do not expose raw AtomRpc clients to components.
|
||||
- Do not add Suspense as part of this migration.
|
||||
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
|
||||
|
||||
## Test Plan
|
||||
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
|
||||
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
|
||||
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
|
||||
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
|
||||
- Acceptance scenarios:
|
||||
- welcome still bootstraps snapshot and navigation
|
||||
- keybindings toast still responds to config stream updates
|
||||
- git status/branches refresh after checkout/pull/worktree actions
|
||||
- PR resolve dialog keeps cached result while typing
|
||||
- `@` path search refreshes after file mutations and orchestration events
|
||||
- diff panel refreshes when checkpoints arrive
|
||||
- desktop updater still reflects push events and button actions
|
||||
|
||||
## Assumptions And Defaults
|
||||
- Zustand stays in scope; only `react-query` is being removed.
|
||||
- `desktopBridge` remains the only non-RPC boundary.
|
||||
- The migration lands as 5-6 small PRs, each green independently.
|
||||
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
|
||||
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
|
||||
Vendored
+1
-1
@@ -5,5 +5,5 @@
|
||||
"source.fixAll.oxc": "always"
|
||||
},
|
||||
"oxc.unusedDisableDirectives": "warn",
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib"
|
||||
}
|
||||
@@ -23,6 +23,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
||||
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
|
||||
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
|
||||
@@ -50,6 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `commandPalette.toggle`: open or close the global command palette
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
|
||||
@@ -1,19 +1,44 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
|
||||
|
||||
## How to use
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||
> T3 Code currently supports Codex, Claude, and OpenCode.
|
||||
> Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
|
||||
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
|
||||
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
|
||||
|
||||
### Run without installing
|
||||
|
||||
```bash
|
||||
npx t3
|
||||
```
|
||||
|
||||
You can also just install the desktop app. It's cooler.
|
||||
### Desktop app
|
||||
|
||||
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
||||
|
||||
#### Windows (`winget`)
|
||||
|
||||
```bash
|
||||
winget install T3Tools.T3Code
|
||||
```
|
||||
|
||||
#### macOS (Homebrew)
|
||||
|
||||
```bash
|
||||
brew install --cask t3-code
|
||||
```
|
||||
|
||||
#### Arch Linux (AUR)
|
||||
|
||||
```bash
|
||||
yay -S t3code-bin
|
||||
```
|
||||
|
||||
## Some notes
|
||||
|
||||
@@ -21,8 +46,18 @@ We are very very early in this project. Expect bugs.
|
||||
|
||||
We are not accepting contributions yet.
|
||||
|
||||
Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Before local development, prepare the environment and install dependencies:
|
||||
|
||||
```bash
|
||||
# Optional: only needed if you use mise for dev tool management.
|
||||
mise install
|
||||
bun install .
|
||||
```
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -1,68 +1,162 @@
|
||||
# Remote Access Setup
|
||||
# Remote Access
|
||||
|
||||
Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
|
||||
Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
|
||||
|
||||
## CLI ↔ Env option map
|
||||
## Recommended Setup
|
||||
|
||||
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
||||
Use a trusted private network that meshes your devices together, such as a tailnet.
|
||||
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
|
||||
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
||||
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
||||
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. |
|
||||
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
|
||||
That gives you:
|
||||
|
||||
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
||||
- a stable address to connect to
|
||||
- transport security at the network layer
|
||||
- less exposure than opening the server to the public internet
|
||||
|
||||
## Security First
|
||||
## Enabling Network Access
|
||||
|
||||
- Always set `--auth-token` before exposing the server outside localhost.
|
||||
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
|
||||
With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
|
||||
- Treat the token like a password.
|
||||
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
|
||||
There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
|
||||
|
||||
## 1) Build + run server for remote access
|
||||
### Option 1: Desktop App
|
||||
|
||||
Remote access should use the built web app (not local Vite redirect mode).
|
||||
If you are already running the desktop app and want to make it reachable from other devices:
|
||||
|
||||
1. Open **Settings** → **Connections**.
|
||||
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
|
||||
3. The settings panel will show the default reachable endpoint, with a `+N` control when more endpoints are available. Expand it to inspect alternatives such as loopback, LAN, private-network, or HTTPS endpoints.
|
||||
4. Use **Create Link** to generate a pairing link you can share with another device.
|
||||
|
||||
The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks.
|
||||
|
||||
When no user default is saved, the app uses the built-in LAN endpoint for pairing links when
|
||||
available. You can set another endpoint as the default from the expanded endpoint list.
|
||||
|
||||
- HTTPS/WSS-compatible endpoints work from `https://app.t3.codes`, but are not made the default
|
||||
automatically.
|
||||
- Non-loopback HTTP endpoints are useful for direct LAN pairing.
|
||||
- Loopback-only endpoints are not useful for another device unless that device is the same machine.
|
||||
|
||||
If the copied link points directly at `http://192.168.x.y:3773`, open it from a client that can reach that LAN address. If it points at `https://app.t3.codes/pair?...`, the hosted web app will save the environment and connect directly to the backend URL in the link.
|
||||
|
||||
### Tailscale Endpoints
|
||||
|
||||
When the desktop app can detect Tailscale, it adds Tailnet endpoints to the reachable endpoint list.
|
||||
|
||||
Depending on your Tailscale setup, this may include:
|
||||
|
||||
- the machine's `100.x.y.z` Tailnet IP
|
||||
- a MagicDNS name
|
||||
- an HTTPS MagicDNS endpoint when Tailscale Serve is configured for this backend
|
||||
|
||||
The Tailscale HTTPS endpoint uses the clean MagicDNS URL, such as
|
||||
`https://machine.tailnet.ts.net/`, and is disabled until the app verifies that the URL reaches this
|
||||
backend. Use **Setup** on the Tailscale HTTPS row to opt in. The desktop app restarts the backend
|
||||
with the same server-side behavior as `t3 serve --tailscale-serve`, then the server asks Tailscale
|
||||
Serve to proxy HTTPS traffic to the local backend.
|
||||
|
||||
The Tailscale support is an endpoint provider add-on. The core remote model still works without Tailscale: LAN HTTP endpoints, custom HTTPS endpoints, future tunnels, and SSH-launched environments all use the same saved environment and pairing flow.
|
||||
|
||||
For `https://app.t3.codes`, prefer an HTTPS Tailnet or other HTTPS endpoint. A plain `http://100.x.y.z:3773` endpoint can still work from a desktop client or another browser page served over HTTP, but it will not work from the hosted HTTPS app because of browser mixed-content rules.
|
||||
|
||||
### Option 2: Headless Server (CLI)
|
||||
|
||||
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
|
||||
|
||||
Run the server with `t3 serve`.
|
||||
|
||||
```bash
|
||||
bun run build
|
||||
TOKEN="$(openssl rand -hex 24)"
|
||||
bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
|
||||
npx t3 serve --host "$(tailscale ip -4)"
|
||||
```
|
||||
|
||||
Then open on your phone:
|
||||
`t3 serve` starts the server without opening a browser and prints:
|
||||
|
||||
`http://<your-machine-ip>:3773`
|
||||
- a connection string
|
||||
- a pairing token
|
||||
- a pairing URL
|
||||
- a QR code for the pairing URL
|
||||
|
||||
Example:
|
||||
From there, connect from another device in either of these ways:
|
||||
|
||||
`http://192.168.1.42:3773`
|
||||
- scan the QR code on your phone
|
||||
- in the desktop app, enter the full pairing URL
|
||||
- in the desktop app, enter the host and token separately
|
||||
- in the hosted web app, open a hosted pairing URL when the backend is reachable over HTTPS
|
||||
|
||||
Notes:
|
||||
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
|
||||
|
||||
- `--host 0.0.0.0` listens on all IPv4 interfaces.
|
||||
- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.
|
||||
- Ensure your OS firewall allows inbound TCP on the selected port.
|
||||
|
||||
## 2) Tailnet / Tailscale access
|
||||
|
||||
If you use Tailscale, you can bind directly to your Tailnet address.
|
||||
For hosted web pairing over Tailscale HTTPS, opt in to Tailscale Serve:
|
||||
|
||||
```bash
|
||||
TAILNET_IP="$(tailscale ip -4)"
|
||||
TOKEN="$(openssl rand -hex 24)"
|
||||
bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser
|
||||
npx t3 serve --tailscale-serve
|
||||
```
|
||||
|
||||
Open from any device in your tailnet:
|
||||
By default this configures Tailscale Serve on HTTPS port 443 and advertises
|
||||
`https://machine.tailnet.ts.net/`. Advanced users can choose a different HTTPS port:
|
||||
|
||||
`http://<tailnet-ip>:3773`
|
||||
```bash
|
||||
npx t3 serve --tailscale-serve --tailscale-serve-port 8443
|
||||
```
|
||||
|
||||
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
|
||||
> Note
|
||||
> The GUIs do not currently support adding projects on remote environments.
|
||||
> For now, use `t3 project ...` on the server machine instead.
|
||||
> Full GUI support for remote project management is coming soon.
|
||||
|
||||
### Option 3: Desktop-Managed SSH Launch
|
||||
|
||||
Use this when you want the desktop app to start or reuse T3 Code on another machine over SSH.
|
||||
|
||||
1. Open **Settings** → **Connections**.
|
||||
2. Under **Remote Environments**, choose **Add environment**.
|
||||
3. Select the SSH launch flow.
|
||||
4. Enter the SSH target, such as `[email protected]`.
|
||||
5. Confirm the launch. The desktop app probes the host, starts or reuses a remote T3 server, opens a local port forward, and saves the environment.
|
||||
|
||||
After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint. The remote host still owns the actual T3 server, projects, files, git state, terminals, and provider sessions.
|
||||
|
||||
SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.
|
||||
|
||||
## How Pairing Works
|
||||
|
||||
The remote device does not need a long-lived secret up front.
|
||||
|
||||
Instead:
|
||||
|
||||
1. `t3 serve` issues a one-time owner pairing token.
|
||||
2. The remote device exchanges that token with the server.
|
||||
3. The server creates an authenticated session for that device.
|
||||
|
||||
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
|
||||
|
||||
## Hosted Web App Pairing
|
||||
|
||||
The hosted web app at `https://app.t3.codes` can save a remote backend in browser local storage from a URL like:
|
||||
|
||||
```text
|
||||
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
|
||||
```
|
||||
|
||||
Use hosted pairing when the backend is reachable from the browser over HTTPS/WSS. This includes a backend behind a trusted HTTPS tunnel or another HTTPS endpoint you operate.
|
||||
|
||||
Do not use hosted pairing for plain HTTP LAN URLs such as `http://192.168.x.y:3773`. Browsers block an HTTPS page from connecting to an insecure HTTP or WS backend. For those endpoints, use the direct pairing URL shown by the desktop app or CLI from a client that can open that HTTP URL directly.
|
||||
|
||||
Hosted pairing does not proxy traffic through T3 Code. The browser still connects directly to the backend URL in the pairing link.
|
||||
|
||||
## Managing Access Later
|
||||
|
||||
Use `t3 auth` to manage access after the initial pairing flow.
|
||||
|
||||
Typical uses:
|
||||
|
||||
- issue additional pairing credentials
|
||||
- inspect active sessions
|
||||
- revoke old pairing links or sessions
|
||||
|
||||
Use `t3 auth --help` and the nested subcommand help pages for the full reference.
|
||||
|
||||
## Security Notes
|
||||
|
||||
- Treat pairing URLs and pairing tokens like passwords.
|
||||
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
|
||||
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
|
||||
- Hosted pairing links keep the credential in the URL hash so it is not sent to the hosted app server, but it can still be exposed through browser history, screenshots, logs, or copy/paste.
|
||||
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
|
||||
@@ -1,31 +1,37 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.14",
|
||||
"version": "0.0.22",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"dev:electron": "node scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "bun run scripts/start-electron.mjs",
|
||||
"start": "node scripts/start-electron.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
"electron": "40.9.3",
|
||||
"electron-updater": "^6.6.2",
|
||||
"jsonc-parser": "^3.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/ssh": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"wait-on": "^8.0.2"
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
}
|
||||
@@ -1,27 +1,39 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
import { waitForResources } from "./wait-for-resources.mjs";
|
||||
|
||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
|
||||
if (!devServerUrl) {
|
||||
throw new Error("VITE_DEV_SERVER_URL is required for desktop development.");
|
||||
}
|
||||
|
||||
const devServer = new URL(devServerUrl);
|
||||
const port = Number.parseInt(devServer.port, 10);
|
||||
if (!Number.isInteger(port) || port <= 0) {
|
||||
throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`);
|
||||
}
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
const requiredFiles = [
|
||||
"dist-electron/main.js",
|
||||
"dist-electron/preload.js",
|
||||
"../server/dist/index.mjs",
|
||||
"dist-electron/main.cjs",
|
||||
"dist-electron/preload.cjs",
|
||||
"../server/dist/bin.mjs",
|
||||
];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
||||
{ directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
|
||||
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
|
||||
await waitOn({
|
||||
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||
await waitForResources({
|
||||
baseDir: desktopDir,
|
||||
files: requiredFiles,
|
||||
tcpHost: devServer.hostname,
|
||||
tcpPort: port,
|
||||
});
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
@@ -57,13 +69,10 @@ function startApp() {
|
||||
|
||||
const app = spawn(
|
||||
resolveElectronPath(),
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
env: childEnv,
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
@@ -6,8 +6,8 @@ import {
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
@@ -18,11 +18,14 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 1;
|
||||
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 2;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
const repoRoot = resolve(desktopDir, "..", "..");
|
||||
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
|
||||
@@ -43,6 +46,68 @@ function setPlistString(plistPath, key, value) {
|
||||
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
|
||||
}
|
||||
|
||||
function runChecked(command, args) {
|
||||
const result = spawnSync(command, args, { encoding: "utf8" });
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
|
||||
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
|
||||
}
|
||||
|
||||
function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
if (!existsSync(developmentMacIconPngPath)) {
|
||||
return defaultIconPath;
|
||||
}
|
||||
|
||||
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
|
||||
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
|
||||
return generatedIconPath;
|
||||
}
|
||||
|
||||
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
|
||||
const iconsetDir = join(iconsetRoot, "icon.iconset");
|
||||
mkdirSync(iconsetDir, { recursive: true });
|
||||
|
||||
try {
|
||||
for (const size of [16, 32, 128, 256, 512]) {
|
||||
runChecked("sips", [
|
||||
"-z",
|
||||
String(size),
|
||||
String(size),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
]);
|
||||
|
||||
const retinaSize = size * 2;
|
||||
runChecked("sips", [
|
||||
"-z",
|
||||
String(retinaSize),
|
||||
String(retinaSize),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
]);
|
||||
}
|
||||
|
||||
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
|
||||
return generatedIconPath;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
|
||||
error,
|
||||
);
|
||||
return defaultIconPath;
|
||||
} finally {
|
||||
rmSync(iconsetRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
@@ -55,40 +120,6 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
|
||||
if (!existsSync(frameworksDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
|
||||
continue;
|
||||
}
|
||||
if (!entry.name.startsWith("Electron Helper")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
|
||||
if (!existsSync(helperPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
|
||||
const helperName = suffix
|
||||
? `${APP_DISPLAY_NAME} Helper ${suffix}`
|
||||
: `${APP_DISPLAY_NAME} Helper`;
|
||||
const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");
|
||||
const helperBundleId = helperIdSuffix
|
||||
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
|
||||
: `${APP_BUNDLE_ID}.helper`;
|
||||
|
||||
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
@@ -102,7 +133,7 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
const runtimeDir = join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const iconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
@@ -126,7 +157,6 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
|
||||
return targetBinaryPath;
|
||||
@@ -140,5 +170,11 @@ export function resolveElectronPath() {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
// Dev launches do not need a renamed app bundle badly enough to risk breaking
|
||||
// Electron helper resource lookup on macOS.
|
||||
if (isDevelopment) {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.js");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import * as FileSystem from "node:fs/promises";
|
||||
import * as Net from "node:net";
|
||||
import * as Path from "node:path";
|
||||
import * as Timers from "node:timers/promises";
|
||||
|
||||
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
|
||||
|
||||
async function fileExists(filePath) {
|
||||
try {
|
||||
await FileSystem.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
|
||||
return new Promise((resolveReady) => {
|
||||
const socket = Net.createConnection({ host, port });
|
||||
let settled = false;
|
||||
|
||||
const finish = (ready) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
socket.removeAllListeners();
|
||||
socket.destroy();
|
||||
resolveReady(ready);
|
||||
};
|
||||
|
||||
socket.once("connect", () => {
|
||||
finish(true);
|
||||
});
|
||||
socket.once("timeout", () => {
|
||||
finish(false);
|
||||
});
|
||||
socket.once("error", () => {
|
||||
finish(false);
|
||||
});
|
||||
socket.setTimeout(connectTimeoutMs);
|
||||
});
|
||||
}
|
||||
|
||||
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
|
||||
const pendingFiles = [];
|
||||
|
||||
for (const relativeFilePath of files) {
|
||||
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
|
||||
if (!ready) {
|
||||
pendingFiles.push(relativeFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
let tcpReady = false;
|
||||
for (const host of tcpHosts) {
|
||||
tcpReady = await tcpPortIsReady({
|
||||
host,
|
||||
port: tcpPort,
|
||||
connectTimeoutMs,
|
||||
});
|
||||
if (tcpReady) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
pendingFiles,
|
||||
tcpReady,
|
||||
};
|
||||
}
|
||||
|
||||
export async function waitForResources({
|
||||
baseDir,
|
||||
files = [],
|
||||
intervalMs = 100,
|
||||
timeoutMs = 120_000,
|
||||
tcpHost,
|
||||
tcpPort,
|
||||
connectTimeoutMs = 500,
|
||||
}) {
|
||||
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
|
||||
throw new TypeError("waitForResources requires a positive integer tcpPort");
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
|
||||
|
||||
while (true) {
|
||||
const { pendingFiles, tcpReady } = await resolvePendingResources({
|
||||
baseDir,
|
||||
files,
|
||||
tcpPort,
|
||||
tcpHosts,
|
||||
connectTimeoutMs,
|
||||
});
|
||||
|
||||
if (pendingFiles.length === 0 && tcpReady) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
const pendingResources = [];
|
||||
if (!tcpReady) {
|
||||
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
|
||||
}
|
||||
for (const filePath of pendingFiles) {
|
||||
pendingResources.push(`file:${filePath}`);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
await Timers.setTimeout(intervalMs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding.ts";
|
||||
|
||||
describe("resolveDesktopAppStageLabel", () => {
|
||||
it("uses Dev in desktop development", () => {
|
||||
expect(
|
||||
resolveDesktopAppStageLabel({
|
||||
isDevelopment: true,
|
||||
appVersion: "0.0.17-nightly.20260414.1",
|
||||
}),
|
||||
).toBe("Dev");
|
||||
});
|
||||
|
||||
it("uses Nightly for packaged nightly builds", () => {
|
||||
expect(
|
||||
resolveDesktopAppStageLabel({
|
||||
isDevelopment: false,
|
||||
appVersion: "0.0.17-nightly.20260414.1",
|
||||
}),
|
||||
).toBe("Nightly");
|
||||
});
|
||||
|
||||
it("uses Alpha for packaged stable builds", () => {
|
||||
expect(
|
||||
resolveDesktopAppStageLabel({
|
||||
isDevelopment: false,
|
||||
appVersion: "0.0.17",
|
||||
}),
|
||||
).toBe("Alpha");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDesktopAppBranding", () => {
|
||||
it("returns a complete desktop branding payload", () => {
|
||||
expect(
|
||||
resolveDesktopAppBranding({
|
||||
isDevelopment: false,
|
||||
appVersion: "0.0.17-nightly.20260414.1",
|
||||
}),
|
||||
).toEqual({
|
||||
baseName: "T3 Code",
|
||||
stageLabel: "Nightly",
|
||||
displayName: "T3 Code (Nightly)",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { DesktopAppBranding, DesktopAppStageLabel } from "@t3tools/contracts";
|
||||
|
||||
import { isNightlyDesktopVersion } from "./updateChannels.ts";
|
||||
|
||||
const APP_BASE_NAME = "T3 Code";
|
||||
|
||||
export function resolveDesktopAppStageLabel(input: {
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
}): DesktopAppStageLabel {
|
||||
if (input.isDevelopment) {
|
||||
return "Dev";
|
||||
}
|
||||
|
||||
return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Alpha";
|
||||
}
|
||||
|
||||
export function resolveDesktopAppBranding(input: {
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
}): DesktopAppBranding {
|
||||
const stageLabel = resolveDesktopAppStageLabel(input);
|
||||
return {
|
||||
baseName: APP_BASE_NAME,
|
||||
stageLabel,
|
||||
displayName: `${APP_BASE_NAME} (${stageLabel})`,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { resolveDesktopBackendPort } from "./backendPort.ts";
|
||||
|
||||
describe("resolveDesktopBackendPort", () => {
|
||||
it("returns the starting port when it is available", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number) => port === 3773);
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3773);
|
||||
|
||||
expect(canListenOnHost).toHaveBeenCalledTimes(1);
|
||||
expect(canListenOnHost).toHaveBeenCalledWith(3773, "127.0.0.1");
|
||||
});
|
||||
|
||||
it("increments sequentially until it finds an available port", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number) => port === 3775);
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3775);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3774, "127.0.0.1"],
|
||||
[3775, "127.0.0.1"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number, host: string) => {
|
||||
if (port === 3773 && host === "127.0.0.1") return true;
|
||||
if (port === 3773 && host === "0.0.0.0") return false;
|
||||
return port === 3774;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0"],
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3774);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3774, "127.0.0.1"],
|
||||
[3774, "0.0.0.0"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("checks overlapping hosts sequentially to avoid self-interference", async () => {
|
||||
let inFlightCount = 0;
|
||||
const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
|
||||
inFlightCount += 1;
|
||||
const overlapped = inFlightCount > 1;
|
||||
await Promise.resolve();
|
||||
inFlightCount -= 1;
|
||||
return !overlapped;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0", "::"],
|
||||
startPort: 3773,
|
||||
maxPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3773);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3773, "::"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails when the scan range is exhausted", async () => {
|
||||
const canListenOnHost = vi.fn(async () => false);
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
startPort: 65534,
|
||||
maxPort: 65535,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
|
||||
);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[65534, "127.0.0.1"],
|
||||
[65535, "127.0.0.1"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
export const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
|
||||
const MAX_TCP_PORT = 65_535;
|
||||
|
||||
export interface ResolveDesktopBackendPortOptions {
|
||||
readonly host: string;
|
||||
readonly startPort?: number;
|
||||
readonly maxPort?: number;
|
||||
readonly requiredHosts?: ReadonlyArray<string>;
|
||||
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
const defaultCanListenOnHost = async (port: number, host: string): Promise<boolean> =>
|
||||
Effect.service(NetService).pipe(
|
||||
Effect.flatMap((net) => net.canListenOnHost(port, host)),
|
||||
Effect.provide(NetService.layer),
|
||||
Effect.runPromise,
|
||||
);
|
||||
|
||||
const isValidPort = (port: number): boolean =>
|
||||
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
|
||||
|
||||
const normalizeHosts = (
|
||||
host: string,
|
||||
requiredHosts: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> =>
|
||||
Array.from(
|
||||
new Set(
|
||||
[host, ...requiredHosts]
|
||||
.map((candidate) => candidate.trim())
|
||||
.filter((candidate) => candidate.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
async function canListenOnAllHosts(
|
||||
port: number,
|
||||
hosts: ReadonlyArray<string>,
|
||||
canListenOnHost: (port: number, host: string) => Promise<boolean>,
|
||||
): Promise<boolean> {
|
||||
for (const candidateHost of hosts) {
|
||||
if (!(await canListenOnHost(port, candidateHost))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function resolveDesktopBackendPort({
|
||||
host,
|
||||
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
maxPort = MAX_TCP_PORT,
|
||||
requiredHosts = [],
|
||||
canListenOnHost = defaultCanListenOnHost,
|
||||
}: ResolveDesktopBackendPortOptions): Promise<number> {
|
||||
if (!isValidPort(startPort)) {
|
||||
throw new Error(`Invalid desktop backend start port: ${startPort}`);
|
||||
}
|
||||
|
||||
if (!isValidPort(maxPort)) {
|
||||
throw new Error(`Invalid desktop backend max port: ${maxPort}`);
|
||||
}
|
||||
|
||||
if (maxPort < startPort) {
|
||||
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
|
||||
}
|
||||
|
||||
const hostsToCheck = normalizeHosts(host, requiredHosts);
|
||||
|
||||
// Keep desktop startup predictable across app restarts by probing upward from
|
||||
// the same preferred port instead of picking a fresh ephemeral port.
|
||||
for (let port = startPort; port <= maxPort; port += 1) {
|
||||
if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
BackendReadinessAbortedError,
|
||||
isBackendReadinessAborted,
|
||||
waitForHttpReady,
|
||||
} from "./backendReadiness.ts";
|
||||
|
||||
describe("waitForHttpReady", () => {
|
||||
it("returns once the backend serves the requested readiness path", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }));
|
||||
|
||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 0,
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("retries after a readiness request stalls past the per-request timeout", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockImplementationOnce(
|
||||
(_input, init) =>
|
||||
new Promise((_resolve, reject) => {
|
||||
init?.signal?.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
reject(new Error("request timed out"));
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
}) as ReturnType<typeof fetch>,
|
||||
)
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }));
|
||||
|
||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 100,
|
||||
intervalMs: 0,
|
||||
requestTimeoutMs: 1,
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("aborts an in-flight readiness wait", async () => {
|
||||
const controller = new AbortController();
|
||||
const fetchImpl = vi.fn<typeof fetch>().mockImplementation(
|
||||
() =>
|
||||
new Promise((_resolve, reject) => {
|
||||
controller.signal.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
reject(new BackendReadinessAbortedError());
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
}) as ReturnType<typeof fetch>,
|
||||
);
|
||||
|
||||
const waitPromise = waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 0,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
controller.abort();
|
||||
|
||||
await expect(waitPromise).rejects.toBeInstanceOf(BackendReadinessAbortedError);
|
||||
});
|
||||
|
||||
it("recognizes aborted readiness errors", () => {
|
||||
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
|
||||
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
|
||||
});
|
||||
|
||||
it("supports custom readiness predicates", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }));
|
||||
|
||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 0,
|
||||
path: "/api/healthz",
|
||||
isReady: (response) => response.status === 204,
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
export interface WaitForHttpReadyOptions {
|
||||
readonly timeoutMs?: number;
|
||||
readonly intervalMs?: number;
|
||||
readonly requestTimeoutMs?: number;
|
||||
readonly fetchImpl?: typeof fetch;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly path?: string;
|
||||
readonly isReady?: (response: Response) => boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_INTERVAL_MS = 100;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
|
||||
|
||||
export class BackendReadinessAbortedError extends Error {
|
||||
constructor() {
|
||||
super("Backend readiness wait was aborted.");
|
||||
this.name = "BackendReadinessAbortedError";
|
||||
}
|
||||
}
|
||||
|
||||
function delay(ms: number, signal: AbortSignal | undefined): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
resolve();
|
||||
}, ms);
|
||||
|
||||
const onAbort = () => {
|
||||
cleanup();
|
||||
reject(new BackendReadinessAbortedError());
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
};
|
||||
|
||||
if (signal?.aborted) {
|
||||
cleanup();
|
||||
reject(new BackendReadinessAbortedError());
|
||||
return;
|
||||
}
|
||||
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
export function isBackendReadinessAborted(error: unknown): error is BackendReadinessAbortedError {
|
||||
return error instanceof BackendReadinessAbortedError;
|
||||
}
|
||||
|
||||
export async function waitForHttpReady(
|
||||
baseUrl: string,
|
||||
options?: WaitForHttpReadyOptions,
|
||||
): Promise<void> {
|
||||
const fetchImpl = options?.fetchImpl ?? fetch;
|
||||
const signal = options?.signal;
|
||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
|
||||
const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||
const readinessPath = options?.path ?? "/";
|
||||
const isReady = options?.isReady ?? ((response: Response) => response.ok);
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
for (;;) {
|
||||
if (signal?.aborted) {
|
||||
throw new BackendReadinessAbortedError();
|
||||
}
|
||||
|
||||
const requestController = new AbortController();
|
||||
const requestTimeout = setTimeout(() => {
|
||||
requestController.abort();
|
||||
}, requestTimeoutMs);
|
||||
const abortRequest = () => {
|
||||
requestController.abort();
|
||||
};
|
||||
signal?.addEventListener("abort", abortRequest, { once: true });
|
||||
|
||||
try {
|
||||
const response = await fetchImpl(new URL(readinessPath, baseUrl).toString(), {
|
||||
redirect: "manual",
|
||||
signal: requestController.signal,
|
||||
});
|
||||
if (isReady(response)) {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
throw error;
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
throw new BackendReadinessAbortedError();
|
||||
}
|
||||
// Retry until the backend becomes reachable or the deadline expires.
|
||||
} finally {
|
||||
clearTimeout(requestTimeout);
|
||||
signal?.removeEventListener("abort", abortRequest);
|
||||
}
|
||||
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error(`Timed out waiting for backend readiness at ${baseUrl}.`);
|
||||
}
|
||||
|
||||
await delay(intervalMs, signal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { BackendReadinessAbortedError } from "./backendReadiness.ts";
|
||||
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
||||
|
||||
describe("waitForBackendStartupReady", () => {
|
||||
it("falls back to the HTTP probe when no listening signal exists", async () => {
|
||||
const waitForHttpReady = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
|
||||
const cancelHttpWait = vi.fn();
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
waitForHttpReady,
|
||||
cancelHttpWait,
|
||||
}),
|
||||
).resolves.toBe("http");
|
||||
|
||||
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
|
||||
expect(cancelHttpWait).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the listening signal and cancels the HTTP probe", async () => {
|
||||
let rejectHttpWait: ((error: unknown) => void) | null = null;
|
||||
const waitForHttpReady = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((_resolve, reject) => {
|
||||
rejectHttpWait = reject;
|
||||
}),
|
||||
);
|
||||
const cancelHttpWait = vi.fn(() => {
|
||||
rejectHttpWait?.(new BackendReadinessAbortedError());
|
||||
});
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
listeningPromise: Promise.resolve(),
|
||||
waitForHttpReady,
|
||||
cancelHttpWait,
|
||||
}),
|
||||
).resolves.toBe("listening");
|
||||
|
||||
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
|
||||
expect(cancelHttpWait).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects when the listening signal fails before HTTP readiness", async () => {
|
||||
const error = new Error("backend exited");
|
||||
const waitForHttpReady = vi.fn(() => new Promise<void>(() => {}));
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
listeningPromise: Promise.reject(error),
|
||||
waitForHttpReady,
|
||||
cancelHttpWait: vi.fn(),
|
||||
}),
|
||||
).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { isBackendReadinessAborted } from "./backendReadiness.ts";
|
||||
|
||||
export interface WaitForBackendStartupReadyOptions {
|
||||
readonly listeningPromise?: Promise<void> | null;
|
||||
readonly waitForHttpReady: () => Promise<void>;
|
||||
readonly cancelHttpWait: () => void;
|
||||
}
|
||||
|
||||
export async function waitForBackendStartupReady(
|
||||
options: WaitForBackendStartupReadyOptions,
|
||||
): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = options.waitForHttpReady();
|
||||
const listeningPromise = options.listeningPromise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
options.cancelHttpWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ClientSettings,
|
||||
type PersistedSavedEnvironmentRecord,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
readClientSettings,
|
||||
readSavedEnvironmentRegistry,
|
||||
readSavedEnvironmentSecret,
|
||||
removeSavedEnvironmentSecret,
|
||||
writeClientSettings,
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
type DesktopSecretStorage,
|
||||
} from "./clientPersistence.ts";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of tempDirectories.splice(0)) {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function makeTempPath(fileName: string): string {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-client-persistence-test-"));
|
||||
tempDirectories.push(directory);
|
||||
return path.join(directory, fileName);
|
||||
}
|
||||
|
||||
function makeSecretStorage(available: boolean): DesktopSecretStorage {
|
||||
return {
|
||||
isEncryptionAvailable: () => available,
|
||||
encryptString: (value) => Buffer.from(`enc:${value}`, "utf8"),
|
||||
decryptString: (value) => {
|
||||
const decoded = value.toString("utf8");
|
||||
if (!decoded.startsWith("enc:")) {
|
||||
throw new Error("invalid secret");
|
||||
}
|
||||
return decoded.slice("enc:".length);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
},
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
timestampFormat: "24-hour",
|
||||
themePreference: { mode: "system" },
|
||||
};
|
||||
|
||||
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
createdAt: "2026-04-09T00:00:00.000Z",
|
||||
lastConnectedAt: "2026-04-09T01:00:00.000Z",
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
};
|
||||
|
||||
describe("clientPersistence", () => {
|
||||
it("persists and reloads client settings", () => {
|
||||
const settingsPath = makeTempPath("client-settings.json");
|
||||
|
||||
writeClientSettings(settingsPath, clientSettings);
|
||||
|
||||
expect(readClientSettings(settingsPath)).toEqual(clientSettings);
|
||||
});
|
||||
|
||||
it("persists and reloads saved environment metadata", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
|
||||
});
|
||||
|
||||
it("persists encrypted saved environment secrets when encryption is available", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage,
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage,
|
||||
}),
|
||||
).toBe("bearer-token");
|
||||
|
||||
expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({
|
||||
records: [
|
||||
{
|
||||
...savedRegistryRecord,
|
||||
encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves existing secrets when encryption is unavailable", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const availableSecretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage: availableSecretStorage,
|
||||
});
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "next-token",
|
||||
secretStorage: makeSecretStorage(false),
|
||||
}),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage: availableSecretStorage,
|
||||
}),
|
||||
).toBe("bearer-token");
|
||||
});
|
||||
|
||||
it("removes saved environment secrets", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage,
|
||||
});
|
||||
|
||||
removeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
});
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("treats malformed secrets documents as empty", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
fs.writeFileSync(registryPath, "{}\n", "utf8");
|
||||
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage: makeSecretStorage(true),
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
expect(() =>
|
||||
removeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("returns false when writing a secret without metadata", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
|
||||
expect(
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage: makeSecretStorage(true),
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves encrypted secrets when metadata is rewritten", () => {
|
||||
const registryPath = makeTempPath("saved-environments.json");
|
||||
const secretStorage = makeSecretStorage(true);
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
writeSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secret: "bearer-token",
|
||||
secretStorage,
|
||||
});
|
||||
|
||||
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
|
||||
|
||||
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
|
||||
expect(
|
||||
readSavedEnvironmentSecret({
|
||||
registryPath,
|
||||
environmentId: savedRegistryRecord.environmentId,
|
||||
secretStorage,
|
||||
}),
|
||||
).toBe("bearer-token");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
|
||||
import {
|
||||
ClientSettingsSchema,
|
||||
type ClientSettings,
|
||||
type PersistedSavedEnvironmentRecord,
|
||||
} from "@t3tools/contracts";
|
||||
import { Predicate } from "effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
interface ClientSettingsDocument {
|
||||
readonly settings: ClientSettings;
|
||||
}
|
||||
|
||||
interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
|
||||
readonly encryptedBearerToken?: string;
|
||||
}
|
||||
|
||||
interface SavedEnvironmentRegistryDocument {
|
||||
readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
|
||||
}
|
||||
|
||||
export interface DesktopSecretStorage {
|
||||
readonly isEncryptionAvailable: () => boolean;
|
||||
readonly encryptString: (value: string) => Buffer;
|
||||
readonly decryptString: (value: Buffer) => string;
|
||||
}
|
||||
|
||||
function readJsonFile<T>(filePath: string): T | null {
|
||||
try {
|
||||
if (!FS.existsSync(filePath)) {
|
||||
return null;
|
||||
}
|
||||
return JSON.parse(FS.readFileSync(filePath, "utf8")) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeJsonFile(filePath: string, value: unknown): void {
|
||||
const directory = Path.dirname(filePath);
|
||||
const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
|
||||
FS.mkdirSync(directory, { recursive: true });
|
||||
FS.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
||||
FS.renameSync(tempPath, filePath);
|
||||
}
|
||||
|
||||
function isPersistedSavedEnvironmentStorageRecord(
|
||||
value: unknown,
|
||||
): value is PersistedSavedEnvironmentStorageRecord {
|
||||
return (
|
||||
Predicate.isObject(value) &&
|
||||
typeof value.environmentId === "string" &&
|
||||
typeof value.label === "string" &&
|
||||
typeof value.httpBaseUrl === "string" &&
|
||||
typeof value.wsBaseUrl === "string" &&
|
||||
typeof value.createdAt === "string" &&
|
||||
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
|
||||
(value.desktopSsh === undefined ||
|
||||
(Predicate.isObject(value.desktopSsh) &&
|
||||
typeof value.desktopSsh.alias === "string" &&
|
||||
typeof value.desktopSsh.hostname === "string" &&
|
||||
(value.desktopSsh.username === null || typeof value.desktopSsh.username === "string") &&
|
||||
(value.desktopSsh.port === null || typeof value.desktopSsh.port === "number"))) &&
|
||||
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
|
||||
);
|
||||
}
|
||||
|
||||
function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument {
|
||||
const parsed = readJsonFile<SavedEnvironmentRegistryDocument>(filePath);
|
||||
if (!Predicate.isObject(parsed)) {
|
||||
return { records: [] };
|
||||
}
|
||||
|
||||
return {
|
||||
records: Array.isArray(parsed.records)
|
||||
? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
record: PersistedSavedEnvironmentStorageRecord,
|
||||
): PersistedSavedEnvironmentRecord {
|
||||
const nextRecord = {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
};
|
||||
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
|
||||
}
|
||||
|
||||
export function readClientSettings(settingsPath: string): ClientSettings | null {
|
||||
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
|
||||
writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument);
|
||||
}
|
||||
|
||||
export function readSavedEnvironmentRegistry(
|
||||
registryPath: string,
|
||||
): readonly PersistedSavedEnvironmentRecord[] {
|
||||
return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) =>
|
||||
toPersistedSavedEnvironmentRecord(record),
|
||||
);
|
||||
}
|
||||
|
||||
export function writeSavedEnvironmentRegistry(
|
||||
registryPath: string,
|
||||
records: readonly PersistedSavedEnvironmentRecord[],
|
||||
): void {
|
||||
const currentDocument = readSavedEnvironmentRegistryDocument(registryPath);
|
||||
const encryptedBearerTokenById = new Map(
|
||||
currentDocument.records.flatMap((record) =>
|
||||
record.encryptedBearerToken
|
||||
? [[record.environmentId, record.encryptedBearerToken] as const]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
writeJsonFile(registryPath, {
|
||||
records: records.map((record) => {
|
||||
const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
|
||||
return encryptedBearerToken
|
||||
? {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
|
||||
encryptedBearerToken,
|
||||
}
|
||||
: record;
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
}
|
||||
|
||||
export function readSavedEnvironmentSecret(input: {
|
||||
readonly registryPath: string;
|
||||
readonly environmentId: string;
|
||||
readonly secretStorage: DesktopSecretStorage;
|
||||
}): string | null {
|
||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
||||
const encoded = document.records.find(
|
||||
(record) => record.environmentId === input.environmentId,
|
||||
)?.encryptedBearerToken;
|
||||
if (!encoded) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!input.secretStorage.isEncryptionAvailable()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return input.secretStorage.decryptString(Buffer.from(encoded, "base64"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeSavedEnvironmentSecret(input: {
|
||||
readonly registryPath: string;
|
||||
readonly environmentId: string;
|
||||
readonly secret: string;
|
||||
readonly secretStorage: DesktopSecretStorage;
|
||||
}): boolean {
|
||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
||||
|
||||
if (!input.secretStorage.isEncryptionAvailable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let found = false;
|
||||
|
||||
writeJsonFile(input.registryPath, {
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== input.environmentId) {
|
||||
return record;
|
||||
}
|
||||
|
||||
found = true;
|
||||
const encryptedBearerToken = input.secretStorage
|
||||
.encryptString(input.secret)
|
||||
.toString("base64");
|
||||
const nextRecord = {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
encryptedBearerToken,
|
||||
};
|
||||
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
return found;
|
||||
}
|
||||
|
||||
export function removeSavedEnvironmentSecret(input: {
|
||||
readonly registryPath: string;
|
||||
readonly environmentId: string;
|
||||
}): void {
|
||||
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
|
||||
if (
|
||||
!document.records.some(
|
||||
(record) =>
|
||||
record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
writeJsonFile(input.registryPath, {
|
||||
records: document.records.map((record) => {
|
||||
if (record.environmentId !== input.environmentId) {
|
||||
return record;
|
||||
}
|
||||
|
||||
return toPersistedSavedEnvironmentRecord(record);
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||
|
||||
describe("showDesktopConfirmDialog", () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
|
||||
const options = {
|
||||
type: "question" as const,
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: CONFIRM_BUTTON_INDEX,
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
resolveDefaultDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopTailscaleServePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings.ts";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of tempDirectories.splice(0)) {
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function makeSettingsPath() {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-desktop-settings-test-"));
|
||||
tempDirectories.push(directory);
|
||||
return path.join(directory, "desktop-settings.json");
|
||||
}
|
||||
|
||||
describe("desktopSettings", () => {
|
||||
it("returns defaults when no settings file exists", () => {
|
||||
expect(readDesktopSettings(makeSettingsPath(), "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
|
||||
it("defaults packaged nightly builds to the nightly update channel", () => {
|
||||
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("persists and reloads the configured server exposure mode", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
|
||||
writeDesktopSettings(settingsPath, {
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the requested network-accessible preference across temporary fallback", () => {
|
||||
expect(
|
||||
setDesktopServerExposurePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
"network-accessible",
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("persists the requested Tailscale Serve preference", () => {
|
||||
expect(
|
||||
setDesktopTailscaleServePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
{ enabled: true, port: 8443 },
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the configured Tailscale Serve port when no new port is requested", () => {
|
||||
expect(
|
||||
setDesktopTailscaleServePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
{ enabled: true },
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("persists the requested nightly update channel", () => {
|
||||
expect(
|
||||
setDesktopUpdateChannelPreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
"nightly",
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to defaults when the settings file is malformed", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(settingsPath, "{not-json", "utf8");
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
|
||||
it("falls back to the nightly channel for legacy nightly settings without an update track", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(settingsPath, JSON.stringify({ serverExposureMode: "local-only" }), "utf8");
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("migrates legacy implicit stable settings to nightly when running a nightly build", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(
|
||||
settingsPath,
|
||||
JSON.stringify({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves an explicit stable choice on nightly builds", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(
|
||||
settingsPath,
|
||||
JSON.stringify({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the default Tailscale Serve port when the persisted port is invalid", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(
|
||||
settingsPath,
|
||||
JSON.stringify({
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 0,
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
|
||||
|
||||
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
readonly tailscaleServeEnabled: boolean;
|
||||
readonly tailscaleServePort: number;
|
||||
readonly updateChannel: DesktopUpdateChannel;
|
||||
readonly updateChannelConfiguredByUser: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
};
|
||||
|
||||
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
|
||||
return {
|
||||
...DEFAULT_DESKTOP_SETTINGS,
|
||||
updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
|
||||
};
|
||||
}
|
||||
|
||||
export function setDesktopServerExposurePreference(
|
||||
settings: DesktopSettings,
|
||||
requestedMode: DesktopServerExposureMode,
|
||||
): DesktopSettings {
|
||||
return settings.serverExposureMode === requestedMode
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
serverExposureMode: requestedMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function setDesktopTailscaleServePreference(
|
||||
settings: DesktopSettings,
|
||||
input: { readonly enabled: boolean; readonly port?: number },
|
||||
): DesktopSettings {
|
||||
const port =
|
||||
input.port === undefined
|
||||
? settings.tailscaleServePort
|
||||
: normalizeTailscaleServePort(input.port);
|
||||
return settings.tailscaleServeEnabled === input.enabled && settings.tailscaleServePort === port
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
tailscaleServeEnabled: input.enabled,
|
||||
tailscaleServePort: port,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeTailscaleServePort(value: unknown): number {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65_535
|
||||
? value
|
||||
: DEFAULT_TAILSCALE_SERVE_PORT;
|
||||
}
|
||||
|
||||
export function setDesktopUpdateChannelPreference(
|
||||
settings: DesktopSettings,
|
||||
requestedChannel: DesktopUpdateChannel,
|
||||
): DesktopSettings {
|
||||
return {
|
||||
...settings,
|
||||
updateChannel: requestedChannel,
|
||||
updateChannelConfiguredByUser: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function readDesktopSettings(settingsPath: string, appVersion: string): DesktopSettings {
|
||||
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
|
||||
|
||||
try {
|
||||
if (!FS.existsSync(settingsPath)) {
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
const raw = FS.readFileSync(settingsPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
readonly serverExposureMode?: unknown;
|
||||
readonly tailscaleServeEnabled?: unknown;
|
||||
readonly tailscaleServePort?: unknown;
|
||||
readonly updateChannel?: unknown;
|
||||
readonly updateChannelConfiguredByUser?: unknown;
|
||||
};
|
||||
const parsedUpdateChannel =
|
||||
parsed.updateChannel === "nightly" || parsed.updateChannel === "latest"
|
||||
? parsed.updateChannel
|
||||
: null;
|
||||
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
|
||||
const updateChannelConfiguredByUser =
|
||||
parsed.updateChannelConfiguredByUser === true ||
|
||||
(isLegacySettings && parsedUpdateChannel === "nightly");
|
||||
|
||||
return {
|
||||
serverExposureMode:
|
||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
|
||||
tailscaleServePort: normalizeTailscaleServePort(parsed.tailscaleServePort),
|
||||
updateChannel:
|
||||
updateChannelConfiguredByUser && parsedUpdateChannel !== null
|
||||
? parsedUpdateChannel
|
||||
: defaultSettings.updateChannel,
|
||||
updateChannelConfiguredByUser,
|
||||
};
|
||||
} catch {
|
||||
return defaultSettings;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeDesktopSettings(settingsPath: string, settings: DesktopSettings): void {
|
||||
const directory = Path.dirname(settingsPath);
|
||||
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
FS.mkdirSync(directory, { recursive: true });
|
||||
FS.writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
|
||||
FS.renameSync(tempPath, settingsPath);
|
||||
}
|
||||
+1041
-110
File diff suppressed because it is too large.
Load diff
+109
-5
@@ -4,23 +4,125 @@ import type { DesktopBridge } from "@t3tools/contracts";
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const DISCOVER_COLOR_THEMES_CHANNEL = "desktop:discover-color-themes";
|
||||
const LOAD_COLOR_THEME_CHANNEL = "desktop:load-color-theme";
|
||||
const GET_EDITOR_THEME_PREFERENCES_CHANNEL = "desktop:get-editor-theme-preferences";
|
||||
const SET_WINDOW_THEME_COLORS_CHANNEL = "desktop:set-window-theme-colors";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
|
||||
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
|
||||
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
|
||||
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
||||
const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
||||
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
|
||||
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
|
||||
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
|
||||
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
|
||||
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
|
||||
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
|
||||
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
||||
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
||||
const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
|
||||
function unwrapEnsureSshEnvironmentResult(result: unknown) {
|
||||
if (
|
||||
typeof result === "object" &&
|
||||
result !== null &&
|
||||
"type" in result &&
|
||||
result.type === SSH_PASSWORD_PROMPT_CANCELLED_RESULT
|
||||
) {
|
||||
const message =
|
||||
"message" in result && typeof result.message === "string"
|
||||
? result.message
|
||||
: "SSH authentication cancelled.";
|
||||
throw new Error(message);
|
||||
}
|
||||
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => {
|
||||
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
|
||||
return typeof result === "string" ? result : null;
|
||||
getAppBranding: () => {
|
||||
const result = ipcRenderer.sendSync(GET_APP_BRANDING_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
return null;
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getAppBranding"]>;
|
||||
},
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
getLocalEnvironmentBootstrap: () => {
|
||||
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
return null;
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
|
||||
},
|
||||
getClientSettings: () => ipcRenderer.invoke(GET_CLIENT_SETTINGS_CHANNEL),
|
||||
setClientSettings: (settings) => ipcRenderer.invoke(SET_CLIENT_SETTINGS_CHANNEL, settings),
|
||||
getSavedEnvironmentRegistry: () => ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
|
||||
setSavedEnvironmentRegistry: (records) =>
|
||||
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
|
||||
getSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
setSavedEnvironmentSecret: (environmentId, secret) =>
|
||||
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
|
||||
removeSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
discoverSshHosts: () => ipcRenderer.invoke(DISCOVER_SSH_HOSTS_CHANNEL),
|
||||
ensureSshEnvironment: async (target, options) =>
|
||||
unwrapEnsureSshEnvironmentResult(
|
||||
await ipcRenderer.invoke(ENSURE_SSH_ENVIRONMENT_CHANNEL, target, options),
|
||||
),
|
||||
disconnectSshEnvironment: (target) =>
|
||||
ipcRenderer.invoke(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, target),
|
||||
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
|
||||
ipcRenderer.invoke(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, httpBaseUrl),
|
||||
bootstrapSshBearerSession: (httpBaseUrl, credential) =>
|
||||
ipcRenderer.invoke(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL, httpBaseUrl, credential),
|
||||
fetchSshSessionState: (httpBaseUrl, bearerToken) =>
|
||||
ipcRenderer.invoke(FETCH_SSH_SESSION_STATE_CHANNEL, httpBaseUrl, bearerToken),
|
||||
issueSshWebSocketToken: (httpBaseUrl, bearerToken) =>
|
||||
ipcRenderer.invoke(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL, httpBaseUrl, bearerToken),
|
||||
onSshPasswordPrompt: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {
|
||||
if (typeof request !== "object" || request === null) return;
|
||||
listener(request as Parameters<typeof listener>[0]);
|
||||
};
|
||||
|
||||
ipcRenderer.on(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
resolveSshPasswordPrompt: (requestId, password) =>
|
||||
ipcRenderer.invoke(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL, requestId, password),
|
||||
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
|
||||
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
|
||||
setTailscaleServeEnabled: (input) =>
|
||||
ipcRenderer.invoke(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
|
||||
getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL),
|
||||
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
discoverColorThemes: () => ipcRenderer.invoke(DISCOVER_COLOR_THEMES_CHANNEL),
|
||||
loadColorTheme: (themeId) => ipcRenderer.invoke(LOAD_COLOR_THEME_CHANNEL, themeId),
|
||||
getEditorThemePreferences: () => ipcRenderer.invoke(GET_EDITOR_THEME_PREFERENCES_CHANNEL),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
setWindowThemeColors: (input) => ipcRenderer.invoke(SET_WINDOW_THEME_COLORS_CHANNEL, input),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
@@ -35,6 +137,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||
setUpdateChannel: (channel) => ipcRenderer.invoke(UPDATE_SET_CHANNEL_CHANNEL, channel),
|
||||
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
|
||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||
onUpdateState: (listener) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
||||
|
||||
describe("resolveDesktopRuntimeInfo", () => {
|
||||
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveDesktopCoreAdvertisedEndpoints,
|
||||
resolveDesktopServerExposure,
|
||||
resolveLanAdvertisedHost,
|
||||
} from "./serverExposure.ts";
|
||||
|
||||
describe("resolveLanAdvertisedHost", () => {
|
||||
it("prefers an explicit host override", () => {
|
||||
expect(
|
||||
resolveLanAdvertisedHost(
|
||||
{
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
"10.0.0.9",
|
||||
),
|
||||
).toBe("10.0.0.9");
|
||||
});
|
||||
|
||||
it("returns the first usable non-internal IPv4 address", () => {
|
||||
expect(
|
||||
resolveLanAdvertisedHost(
|
||||
{
|
||||
lo0: [
|
||||
{
|
||||
address: "127.0.0.1",
|
||||
family: "IPv4",
|
||||
internal: true,
|
||||
netmask: "255.0.0.0",
|
||||
cidr: "127.0.0.1/8",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
undefined,
|
||||
),
|
||||
).toBe("192.168.1.44");
|
||||
});
|
||||
|
||||
it("returns null when no usable network address is available", () => {
|
||||
expect(
|
||||
resolveLanAdvertisedHost(
|
||||
{
|
||||
lo0: [
|
||||
{
|
||||
address: "127.0.0.1",
|
||||
family: "IPv4",
|
||||
internal: true,
|
||||
netmask: "255.0.0.0",
|
||||
cidr: "127.0.0.1/8",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
undefined,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDesktopCoreAdvertisedEndpoints", () => {
|
||||
it("advertises loopback and LAN endpoints without provider-specific assumptions", () => {
|
||||
const exposure = resolveDesktopServerExposure({
|
||||
mode: "network-accessible",
|
||||
port: 3773,
|
||||
networkInterfaces: {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveDesktopCoreAdvertisedEndpoints({
|
||||
port: 3773,
|
||||
exposure,
|
||||
customHttpsEndpointUrls: [
|
||||
"https://desktop.example.ts.net",
|
||||
"http://desktop.example.test:3773",
|
||||
"not-a-url",
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
id: "desktop-loopback:3773",
|
||||
label: "This machine",
|
||||
provider: {
|
||||
id: "desktop-core",
|
||||
label: "Desktop",
|
||||
kind: "core",
|
||||
isAddon: false,
|
||||
},
|
||||
httpBaseUrl: "http://127.0.0.1:3773/",
|
||||
wsBaseUrl: "ws://127.0.0.1:3773/",
|
||||
reachability: "loopback",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "mixed-content-blocked",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "desktop-core",
|
||||
status: "available",
|
||||
description: "Loopback endpoint for this desktop app.",
|
||||
},
|
||||
{
|
||||
id: "desktop-lan:http://192.168.1.44:3773",
|
||||
label: "Local network",
|
||||
provider: {
|
||||
id: "desktop-core",
|
||||
label: "Desktop",
|
||||
kind: "core",
|
||||
isAddon: false,
|
||||
},
|
||||
httpBaseUrl: "http://192.168.1.44:3773/",
|
||||
wsBaseUrl: "ws://192.168.1.44:3773/",
|
||||
reachability: "lan",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "mixed-content-blocked",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "desktop-core",
|
||||
status: "available",
|
||||
isDefault: true,
|
||||
description: "Reachable from devices on the same network.",
|
||||
},
|
||||
{
|
||||
id: "manual:https://desktop.example.ts.net",
|
||||
label: "Custom HTTPS",
|
||||
provider: {
|
||||
id: "manual",
|
||||
label: "Manual",
|
||||
kind: "manual",
|
||||
isAddon: false,
|
||||
},
|
||||
httpBaseUrl: "https://desktop.example.ts.net/",
|
||||
wsBaseUrl: "wss://desktop.example.ts.net/",
|
||||
reachability: "public",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "compatible",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "user",
|
||||
status: "unknown",
|
||||
description: "User-configured HTTPS endpoint for this desktop backend.",
|
||||
},
|
||||
{
|
||||
id: "manual:http://desktop.example.test:3773",
|
||||
label: "Custom endpoint",
|
||||
provider: {
|
||||
id: "manual",
|
||||
label: "Manual",
|
||||
kind: "manual",
|
||||
isAddon: false,
|
||||
},
|
||||
httpBaseUrl: "http://desktop.example.test:3773/",
|
||||
wsBaseUrl: "ws://desktop.example.test:3773/",
|
||||
reachability: "public",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "mixed-content-blocked",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "user",
|
||||
status: "unknown",
|
||||
description: "User-configured endpoint for this desktop backend.",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDesktopServerExposure", () => {
|
||||
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
|
||||
expect(
|
||||
resolveDesktopServerExposure({
|
||||
mode: "local-only",
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
}),
|
||||
).toEqual({
|
||||
mode: "local-only",
|
||||
bindHost: "127.0.0.1",
|
||||
localHttpUrl: "http://127.0.0.1:3773",
|
||||
localWsUrl: "ws://127.0.0.1:3773",
|
||||
endpointUrl: null,
|
||||
advertisedHost: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("binds to all interfaces in network-accessible mode", () => {
|
||||
expect(
|
||||
resolveDesktopServerExposure({
|
||||
mode: "network-accessible",
|
||||
port: 3773,
|
||||
networkInterfaces: {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
mode: "network-accessible",
|
||||
bindHost: "0.0.0.0",
|
||||
localHttpUrl: "http://127.0.0.1:3773",
|
||||
localWsUrl: "ws://127.0.0.1:3773",
|
||||
endpointUrl: "http://192.168.1.44:3773",
|
||||
advertisedHost: "192.168.1.44",
|
||||
});
|
||||
});
|
||||
|
||||
it("stays network-accessible even when no LAN address is currently detectable", () => {
|
||||
expect(
|
||||
resolveDesktopServerExposure({
|
||||
mode: "network-accessible",
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
}),
|
||||
).toEqual({
|
||||
mode: "network-accessible",
|
||||
bindHost: "0.0.0.0",
|
||||
localHttpUrl: "http://127.0.0.1:3773",
|
||||
localWsUrl: "ws://127.0.0.1:3773",
|
||||
endpointUrl: null,
|
||||
advertisedHost: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type {
|
||||
AdvertisedEndpoint,
|
||||
AdvertisedEndpointProvider,
|
||||
DesktopServerExposureMode,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||
|
||||
export interface DesktopServerExposure {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly bindHost: string;
|
||||
readonly localHttpUrl: string;
|
||||
readonly localWsUrl: string;
|
||||
readonly endpointUrl: string | null;
|
||||
readonly advertisedHost: string | null;
|
||||
}
|
||||
|
||||
export interface DesktopAdvertisedEndpointInput {
|
||||
readonly port: number;
|
||||
readonly exposure: DesktopServerExposure;
|
||||
readonly customHttpsEndpointUrls?: readonly string[];
|
||||
}
|
||||
|
||||
const DESKTOP_CORE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
||||
id: "desktop-core",
|
||||
label: "Desktop",
|
||||
kind: "core",
|
||||
isAddon: false,
|
||||
};
|
||||
|
||||
const DESKTOP_MANUAL_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
||||
id: "manual",
|
||||
label: "Manual",
|
||||
kind: "manual",
|
||||
isAddon: false,
|
||||
};
|
||||
|
||||
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
|
||||
const normalized = value?.trim();
|
||||
return normalized && normalized.length > 0 ? normalized : undefined;
|
||||
};
|
||||
|
||||
const isUsableLanIpv4Address = (address: string): boolean =>
|
||||
!address.startsWith("127.") && !address.startsWith("169.254.");
|
||||
|
||||
function isHttpsEndpointUrl(value: string): boolean {
|
||||
try {
|
||||
return new URL(value).protocol === "https:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveLanAdvertisedHost(
|
||||
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
|
||||
explicitHost: string | undefined,
|
||||
): string | null {
|
||||
const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
|
||||
if (normalizedExplicitHost) {
|
||||
return normalizedExplicitHost;
|
||||
}
|
||||
|
||||
for (const interfaceAddresses of Object.values(networkInterfaces)) {
|
||||
if (!interfaceAddresses) continue;
|
||||
|
||||
for (const address of interfaceAddresses) {
|
||||
if (address.internal) continue;
|
||||
if (address.family !== "IPv4") continue;
|
||||
if (!isUsableLanIpv4Address(address.address)) continue;
|
||||
return address.address;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveDesktopServerExposure(input: {
|
||||
readonly mode: DesktopServerExposureMode;
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
|
||||
readonly advertisedHostOverride?: string;
|
||||
}): DesktopServerExposure {
|
||||
const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
|
||||
const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
|
||||
|
||||
if (input.mode === "local-only") {
|
||||
return {
|
||||
mode: input.mode,
|
||||
bindHost: DESKTOP_LOOPBACK_HOST,
|
||||
localHttpUrl,
|
||||
localWsUrl,
|
||||
endpointUrl: null,
|
||||
advertisedHost: null,
|
||||
};
|
||||
}
|
||||
|
||||
const advertisedHost = resolveLanAdvertisedHost(
|
||||
input.networkInterfaces,
|
||||
input.advertisedHostOverride,
|
||||
);
|
||||
|
||||
return {
|
||||
mode: input.mode,
|
||||
bindHost: DESKTOP_LAN_BIND_HOST,
|
||||
localHttpUrl,
|
||||
localWsUrl,
|
||||
endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null,
|
||||
advertisedHost,
|
||||
};
|
||||
}
|
||||
|
||||
function createDesktopEndpoint(
|
||||
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
|
||||
): AdvertisedEndpoint {
|
||||
return createAdvertisedEndpoint({
|
||||
...input,
|
||||
provider: DESKTOP_CORE_ENDPOINT_PROVIDER,
|
||||
source: "desktop-core",
|
||||
});
|
||||
}
|
||||
|
||||
function createManualEndpoint(
|
||||
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
|
||||
): AdvertisedEndpoint {
|
||||
return createAdvertisedEndpoint({
|
||||
...input,
|
||||
provider: DESKTOP_MANUAL_ENDPOINT_PROVIDER,
|
||||
source: "user",
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveDesktopCoreAdvertisedEndpoints(
|
||||
input: DesktopAdvertisedEndpointInput,
|
||||
): readonly AdvertisedEndpoint[] {
|
||||
const endpoints: AdvertisedEndpoint[] = [
|
||||
createDesktopEndpoint({
|
||||
id: `desktop-loopback:${input.port}`,
|
||||
label: "This machine",
|
||||
httpBaseUrl: input.exposure.localHttpUrl,
|
||||
reachability: "loopback",
|
||||
status: "available",
|
||||
description: "Loopback endpoint for this desktop app.",
|
||||
}),
|
||||
];
|
||||
|
||||
if (input.exposure.endpointUrl) {
|
||||
endpoints.push(
|
||||
createDesktopEndpoint({
|
||||
id: `desktop-lan:${input.exposure.endpointUrl}`,
|
||||
label: "Local network",
|
||||
httpBaseUrl: input.exposure.endpointUrl,
|
||||
reachability: "lan",
|
||||
status: "available",
|
||||
isDefault: true,
|
||||
description: "Reachable from devices on the same network.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) {
|
||||
try {
|
||||
const isHttpsEndpoint = isHttpsEndpointUrl(customEndpointUrl);
|
||||
endpoints.push(
|
||||
createManualEndpoint({
|
||||
id: `manual:${customEndpointUrl}`,
|
||||
label: isHttpsEndpoint ? "Custom HTTPS" : "Custom endpoint",
|
||||
httpBaseUrl: customEndpointUrl,
|
||||
reachability: "public",
|
||||
...(isHttpsEndpoint ? ({ hostedHttpsCompatibility: "compatible" } as const) : {}),
|
||||
status: "unknown",
|
||||
description: isHttpsEndpoint
|
||||
? "User-configured HTTPS endpoint for this desktop backend."
|
||||
: "User-configured endpoint for this desktop backend.",
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// Ignore malformed user-configured endpoints without dropping valid endpoints.
|
||||
}
|
||||
}
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ServerListeningDetector } from "./serverListeningDetector.ts";
|
||||
|
||||
describe("ServerListeningDetector", () => {
|
||||
it("resolves when the server logs the listening line", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listening on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves when the listening line arrives across multiple chunks", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listen");
|
||||
detector.push("ing on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects when the server exits before logging readiness", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
const error = new Error("server exited");
|
||||
|
||||
detector.fail(error);
|
||||
|
||||
await expect(detector.promise).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
const LISTENING_LOG_FRAGMENT = "Listening on http://";
|
||||
const MAX_BUFFER_CHARS = 8_192;
|
||||
|
||||
export class ServerListeningDetector {
|
||||
private buffer = "";
|
||||
private settled = false;
|
||||
private readonly resolvePromise: () => void;
|
||||
private readonly rejectPromise: (error: unknown) => void;
|
||||
readonly promise: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
let resolvePromise: (() => void) | null = null;
|
||||
let rejectPromise: ((error: unknown) => void) | null = null;
|
||||
|
||||
this.promise = new Promise<void>((resolve, reject) => {
|
||||
resolvePromise = resolve;
|
||||
rejectPromise = reject;
|
||||
});
|
||||
|
||||
this.resolvePromise = () => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
resolvePromise?.();
|
||||
};
|
||||
this.rejectPromise = (error) => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
rejectPromise?.(error);
|
||||
};
|
||||
}
|
||||
|
||||
push(chunk: unknown): void {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
|
||||
this.buffer = `${this.buffer}${text.replace(/\r/g, "")}`;
|
||||
if (this.buffer.includes(LISTENING_LOG_FRAGMENT)) {
|
||||
this.resolvePromise();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.buffer.length > MAX_BUFFER_CHARS) {
|
||||
this.buffer = this.buffer.slice(-MAX_BUFFER_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
fail(error: unknown): void {
|
||||
this.rejectPromise(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
|
||||
|
||||
import { discoverDesktopSshHosts, isSshPasswordPromptCancellation } from "./sshEnvironment.ts";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of tempDirectories.splice(0)) {
|
||||
FS.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function makeTempHomeDir(): string {
|
||||
const directory = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-ssh-env-test-"));
|
||||
tempDirectories.push(directory);
|
||||
return directory;
|
||||
}
|
||||
|
||||
describe("sshEnvironment", () => {
|
||||
it("treats password prompt timeouts as cancellable authentication prompts", () => {
|
||||
expect(
|
||||
isSshPasswordPromptCancellation(
|
||||
new SshPasswordPromptError({
|
||||
message: "SSH authentication timed out for devbox.",
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("wires desktop host discovery through the ssh package runtime", async () => {
|
||||
const homeDir = makeTempHomeDir();
|
||||
const sshDir = Path.join(homeDir, ".ssh");
|
||||
FS.mkdirSync(Path.join(sshDir, "config.d"), { recursive: true });
|
||||
FS.writeFileSync(
|
||||
Path.join(sshDir, "config"),
|
||||
["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
FS.writeFileSync(
|
||||
Path.join(sshDir, "config.d", "team.conf"),
|
||||
[
|
||||
"Host staging",
|
||||
" HostName staging.example.com",
|
||||
"Host *",
|
||||
" ServerAliveInterval 30",
|
||||
"",
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
FS.writeFileSync(
|
||||
Path.join(sshDir, "known_hosts"),
|
||||
[
|
||||
"known.example.com ssh-ed25519 AAAA",
|
||||
"|1|hashed|entry ssh-ed25519 AAAA",
|
||||
"[bastion.example.com]:2222 ssh-ed25519 AAAA",
|
||||
"",
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
await expect(discoverDesktopSshHosts({ homeDir })).resolves.toEqual([
|
||||
{
|
||||
alias: "bastion.example.com",
|
||||
hostname: "bastion.example.com",
|
||||
username: null,
|
||||
port: null,
|
||||
source: "known-hosts",
|
||||
},
|
||||
{
|
||||
alias: "devbox",
|
||||
hostname: "devbox",
|
||||
username: null,
|
||||
port: null,
|
||||
source: "ssh-config",
|
||||
},
|
||||
{
|
||||
alias: "known.example.com",
|
||||
hostname: "known.example.com",
|
||||
username: null,
|
||||
port: null,
|
||||
source: "known-hosts",
|
||||
},
|
||||
{
|
||||
alias: "staging",
|
||||
hostname: "staging",
|
||||
username: null,
|
||||
port: null,
|
||||
source: "ssh-config",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,420 @@
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import type {
|
||||
AuthBearerBootstrapResult,
|
||||
AuthSessionState,
|
||||
AuthWebSocketTokenResult,
|
||||
DesktopDiscoveredSshHost,
|
||||
DesktopSshEnvironmentTarget,
|
||||
DesktopSshPasswordPromptRequest,
|
||||
ExecutionEnvironmentDescriptor,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
SshPasswordPrompt,
|
||||
type SshPasswordPromptShape,
|
||||
type SshPasswordRequest,
|
||||
} from "@t3tools/ssh/auth";
|
||||
import { discoverSshHosts } from "@t3tools/ssh/config";
|
||||
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
|
||||
import {
|
||||
fetchLoopbackSshJson,
|
||||
SshEnvironmentManager,
|
||||
type RemoteT3RunnerOptions,
|
||||
} from "@t3tools/ssh/tunnel";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
|
||||
|
||||
export { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
|
||||
|
||||
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
|
||||
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
||||
const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
||||
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
|
||||
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
|
||||
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
|
||||
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
|
||||
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
|
||||
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
|
||||
const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
|
||||
const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
|
||||
interface DesktopSshEnvironmentManagerOptions {
|
||||
readonly passwordProvider?: (request: SshPasswordRequest) => Promise<string | null>;
|
||||
readonly resolveCliPackageSpec?: () => string;
|
||||
readonly resolveCliRunner?: () => RemoteT3RunnerOptions;
|
||||
}
|
||||
|
||||
const sshRuntime = ManagedRuntime.make(
|
||||
Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, NetService.layer),
|
||||
);
|
||||
|
||||
function createDesktopSshRuntime(
|
||||
passwordPrompt: SshPasswordPromptShape,
|
||||
scope: Scope.Scope,
|
||||
options: DesktopSshEnvironmentManagerOptions,
|
||||
) {
|
||||
return ManagedRuntime.make(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
NodeHttpClient.layerUndici,
|
||||
NetService.layer,
|
||||
Layer.succeed(Scope.Scope, scope),
|
||||
Layer.succeed(SshPasswordPrompt, SshPasswordPrompt.of(passwordPrompt)),
|
||||
SshEnvironmentManager.layer({
|
||||
...(options.resolveCliPackageSpec === undefined
|
||||
? {}
|
||||
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
|
||||
...(options.resolveCliRunner === undefined
|
||||
? {}
|
||||
: { resolveCliRunner: options.resolveCliRunner }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function discoverDesktopSshHosts(input?: {
|
||||
readonly homeDir?: string;
|
||||
}): Promise<readonly DesktopDiscoveredSshHost[]> {
|
||||
return await sshRuntime.runPromise(discoverSshHosts(input ?? {}));
|
||||
}
|
||||
|
||||
export class DesktopSshEnvironmentManager {
|
||||
private readonly runtime: ReturnType<typeof createDesktopSshRuntime>;
|
||||
private readonly scope: Scope.Scope;
|
||||
|
||||
constructor(options: DesktopSshEnvironmentManagerOptions = {}) {
|
||||
const passwordPrompt: SshPasswordPromptShape = {
|
||||
isAvailable: options.passwordProvider !== undefined,
|
||||
request: (request) => {
|
||||
const passwordProvider = options.passwordProvider;
|
||||
if (!passwordProvider) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
|
||||
return Effect.tryPromise({
|
||||
try: () => passwordProvider(request),
|
||||
catch: (cause) =>
|
||||
new SshPasswordPromptError({
|
||||
message: cause instanceof Error ? cause.message : "SSH password prompt failed.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
},
|
||||
};
|
||||
this.scope = Effect.runSync(Scope.make());
|
||||
this.runtime = createDesktopSshRuntime(passwordPrompt, this.scope, options);
|
||||
}
|
||||
|
||||
async discoverHosts(): Promise<readonly DesktopDiscoveredSshHost[]> {
|
||||
return await discoverDesktopSshHosts();
|
||||
}
|
||||
|
||||
async ensureEnvironment(
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
options?: { readonly issuePairingToken?: boolean },
|
||||
) {
|
||||
return await this.runtime.runPromise(
|
||||
Effect.service(SshEnvironmentManager).pipe(
|
||||
Effect.flatMap((manager) => manager.ensureEnvironment(target, options)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async disconnectEnvironment(target: DesktopSshEnvironmentTarget): Promise<void> {
|
||||
await this.runtime.runPromise(
|
||||
Effect.service(SshEnvironmentManager).pipe(
|
||||
Effect.flatMap((manager) => manager.disconnectEnvironment(target)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
await this.runtime.runPromise(Scope.close(this.scope, Exit.void));
|
||||
await this.runtime.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
function getSafeDesktopSshTarget(rawTarget: unknown): DesktopSshEnvironmentTarget | null {
|
||||
if (typeof rawTarget !== "object" || rawTarget === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const target = rawTarget as Partial<DesktopSshEnvironmentTarget>;
|
||||
if (typeof target.alias !== "string" || typeof target.hostname !== "string") {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
target.username !== null &&
|
||||
target.username !== undefined &&
|
||||
typeof target.username !== "string"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (target.port !== null && target.port !== undefined && !Number.isInteger(target.port)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const alias = target.alias.trim();
|
||||
const hostname = target.hostname.trim();
|
||||
if (alias.length === 0 || hostname.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
alias,
|
||||
hostname,
|
||||
username: target.username?.trim() || null,
|
||||
port: target.port ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Minimal subset of Electron's BrowserWindow used by the SSH bridge. */
|
||||
export interface DesktopSshBridgeWindow {
|
||||
isDestroyed(): boolean;
|
||||
isMinimized(): boolean;
|
||||
restore(): void;
|
||||
focus(): void;
|
||||
readonly webContents: {
|
||||
send(channel: string, ...args: readonly unknown[]): void;
|
||||
};
|
||||
}
|
||||
|
||||
/** Minimal subset of Electron's ipcMain used by the SSH bridge. */
|
||||
export interface DesktopSshBridgeIpcMain {
|
||||
removeHandler(channel: string): void;
|
||||
handle(
|
||||
channel: string,
|
||||
listener: (event: unknown, ...args: readonly unknown[]) => unknown | Promise<unknown>,
|
||||
): void;
|
||||
}
|
||||
|
||||
export interface DesktopSshEnvironmentBridgeOptions {
|
||||
readonly getMainWindow: () => DesktopSshBridgeWindow | null;
|
||||
readonly resolveCliPackageSpec?: () => string;
|
||||
readonly resolveCliRunner?: () => RemoteT3RunnerOptions;
|
||||
readonly passwordPromptTimeoutMs?: number;
|
||||
}
|
||||
|
||||
interface PendingSshPasswordPrompt {
|
||||
readonly resolve: (password: string | null) => void;
|
||||
readonly reject: (error: Error) => void;
|
||||
readonly timeout: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
export function isSshPasswordPromptCancellation(error: unknown): error is SshPasswordPromptError {
|
||||
const message = error instanceof SshPasswordPromptError ? error.message.toLowerCase() : "";
|
||||
return (
|
||||
error instanceof SshPasswordPromptError &&
|
||||
(message.includes("cancelled") || message.includes("timed out"))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wires the SSH environment manager to Electron IPC, owning the renderer-facing
|
||||
* password prompt state so `main.ts` only needs to register, cancel, and dispose.
|
||||
*/
|
||||
export class DesktopSshEnvironmentBridge {
|
||||
private readonly options: DesktopSshEnvironmentBridgeOptions;
|
||||
private readonly manager: DesktopSshEnvironmentManager;
|
||||
private readonly pendingPrompts = new Map<string, PendingSshPasswordPrompt>();
|
||||
private readonly passwordPromptTimeoutMs: number;
|
||||
|
||||
constructor(options: DesktopSshEnvironmentBridgeOptions) {
|
||||
this.options = options;
|
||||
this.passwordPromptTimeoutMs =
|
||||
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
|
||||
this.manager = new DesktopSshEnvironmentManager({
|
||||
passwordProvider: (request) => this.requestPasswordFromRenderer(request),
|
||||
...(options.resolveCliPackageSpec === undefined
|
||||
? {}
|
||||
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
|
||||
...(options.resolveCliRunner === undefined
|
||||
? {}
|
||||
: { resolveCliRunner: options.resolveCliRunner }),
|
||||
});
|
||||
}
|
||||
|
||||
registerIpcHandlers(ipcMain: DesktopSshBridgeIpcMain): void {
|
||||
ipcMain.removeHandler(DISCOVER_SSH_HOSTS_CHANNEL);
|
||||
ipcMain.handle(DISCOVER_SSH_HOSTS_CHANNEL, async () => this.manager.discoverHosts());
|
||||
|
||||
ipcMain.removeHandler(ENSURE_SSH_ENVIRONMENT_CHANNEL);
|
||||
ipcMain.handle(ENSURE_SSH_ENVIRONMENT_CHANNEL, async (_event, rawTarget, rawOptions) => {
|
||||
const target = getSafeDesktopSshTarget(rawTarget);
|
||||
if (!target) {
|
||||
throw new Error("Invalid desktop SSH target.");
|
||||
}
|
||||
|
||||
const issuePairingToken =
|
||||
typeof rawOptions === "object" &&
|
||||
rawOptions !== null &&
|
||||
"issuePairingToken" in rawOptions &&
|
||||
(rawOptions as { issuePairingToken?: unknown }).issuePairingToken === true;
|
||||
|
||||
try {
|
||||
return await this.manager.ensureEnvironment(target, {
|
||||
issuePairingToken,
|
||||
});
|
||||
} catch (error) {
|
||||
if (isSshPasswordPromptCancellation(error)) {
|
||||
return {
|
||||
type: SSH_PASSWORD_PROMPT_CANCELLED_RESULT,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(DISCONNECT_SSH_ENVIRONMENT_CHANNEL);
|
||||
ipcMain.handle(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, async (_event, rawTarget) => {
|
||||
const target = getSafeDesktopSshTarget(rawTarget);
|
||||
if (!target) {
|
||||
throw new Error("Invalid desktop SSH target.");
|
||||
}
|
||||
|
||||
await this.manager.disconnectEnvironment(target);
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL);
|
||||
ipcMain.handle(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, async (_event, rawHttpBaseUrl) =>
|
||||
sshRuntime.runPromise(
|
||||
fetchLoopbackSshJson<ExecutionEnvironmentDescriptor>({
|
||||
httpBaseUrl: rawHttpBaseUrl,
|
||||
pathname: "/.well-known/t3/environment",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL);
|
||||
ipcMain.handle(
|
||||
BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
|
||||
async (_event, rawHttpBaseUrl, rawCredential) =>
|
||||
sshRuntime.runPromise(
|
||||
fetchLoopbackSshJson<AuthBearerBootstrapResult>({
|
||||
httpBaseUrl: rawHttpBaseUrl,
|
||||
pathname: "/api/auth/bootstrap/bearer",
|
||||
method: "POST",
|
||||
body: { credential: rawCredential },
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(FETCH_SSH_SESSION_STATE_CHANNEL);
|
||||
ipcMain.handle(
|
||||
FETCH_SSH_SESSION_STATE_CHANNEL,
|
||||
async (_event, rawHttpBaseUrl, rawBearerToken) =>
|
||||
sshRuntime.runPromise(
|
||||
fetchLoopbackSshJson<AuthSessionState>({
|
||||
httpBaseUrl: rawHttpBaseUrl,
|
||||
pathname: "/api/auth/session",
|
||||
bearerToken: rawBearerToken,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL);
|
||||
ipcMain.handle(
|
||||
ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
|
||||
async (_event, rawHttpBaseUrl, rawBearerToken) =>
|
||||
sshRuntime.runPromise(
|
||||
fetchLoopbackSshJson<AuthWebSocketTokenResult>({
|
||||
httpBaseUrl: rawHttpBaseUrl,
|
||||
pathname: "/api/auth/ws-token",
|
||||
method: "POST",
|
||||
bearerToken: rawBearerToken,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL);
|
||||
ipcMain.handle(
|
||||
RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
|
||||
async (_event, rawRequestId, rawPassword) => {
|
||||
if (typeof rawRequestId !== "string" || rawRequestId.trim().length === 0) {
|
||||
throw new Error("Invalid SSH password prompt id.");
|
||||
}
|
||||
if (rawPassword !== null && typeof rawPassword !== "string") {
|
||||
throw new Error("Invalid SSH password prompt response.");
|
||||
}
|
||||
|
||||
const pending = this.pendingPrompts.get(rawRequestId);
|
||||
if (!pending) {
|
||||
throw new Error("SSH password prompt expired. Try connecting again.");
|
||||
}
|
||||
|
||||
clearTimeout(pending.timeout);
|
||||
this.pendingPrompts.delete(rawRequestId);
|
||||
pending.resolve(rawPassword);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cancelPendingPasswordPrompts(reason: string): void {
|
||||
for (const [requestId, pending] of this.pendingPrompts) {
|
||||
clearTimeout(pending.timeout);
|
||||
this.pendingPrompts.delete(requestId);
|
||||
pending.reject(new Error(reason));
|
||||
}
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
this.cancelPendingPasswordPrompts("SSH environment bridge disposed.");
|
||||
await this.manager.dispose();
|
||||
}
|
||||
|
||||
private async requestPasswordFromRenderer(input: SshPasswordRequest): Promise<string | null> {
|
||||
const window = this.options.getMainWindow();
|
||||
if (!window || window.isDestroyed()) {
|
||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
||||
}
|
||||
|
||||
const request: DesktopSshPasswordPromptRequest = {
|
||||
requestId: Crypto.randomUUID(),
|
||||
destination: input.destination,
|
||||
username: input.username,
|
||||
prompt: input.prompt,
|
||||
expiresAt: new Date(Date.now() + this.passwordPromptTimeoutMs).toISOString(),
|
||||
};
|
||||
|
||||
return await new Promise<string | null>((resolve, reject) => {
|
||||
const rejectPrompt = (error: Error) => {
|
||||
clearTimeout(timeout);
|
||||
this.pendingPrompts.delete(request.requestId);
|
||||
reject(error);
|
||||
};
|
||||
const timeout = setTimeout(() => {
|
||||
this.pendingPrompts.delete(request.requestId);
|
||||
reject(new Error(`SSH authentication timed out for ${input.destination}.`));
|
||||
}, this.passwordPromptTimeoutMs);
|
||||
timeout.unref();
|
||||
|
||||
this.pendingPrompts.set(request.requestId, { resolve, reject, timeout });
|
||||
|
||||
try {
|
||||
if (window.isDestroyed()) {
|
||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
||||
}
|
||||
window.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, request);
|
||||
if (window.isDestroyed()) {
|
||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
||||
}
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
if (window.isDestroyed()) {
|
||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
||||
}
|
||||
window.focus();
|
||||
} catch (error) {
|
||||
rejectPrompt(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("T3 Code window is not available for SSH authentication."),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
||||
|
||||
describe("syncShellEnvironment", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
HOMEBREW_PREFIX: "/opt/homebrew",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
@@ -18,9 +19,18 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
expect(env.HOMEBREW_PREFIX).toBe("/opt/homebrew");
|
||||
});
|
||||
|
||||
it("preserves an inherited SSH_AUTH_SOCK value", () => {
|
||||
@@ -62,14 +72,13 @@ describe("syncShellEnvironment", () => {
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("does nothing outside macOS", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
@@ -78,8 +87,203 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("falls back to launchctl PATH on macOS when shell probing does not return one", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/opt/homebrew/bin/nu",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error("unknown flag");
|
||||
})
|
||||
.mockImplementationOnce(() => ({}));
|
||||
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
const logWarning = vi.fn();
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "darwin",
|
||||
readEnvironment,
|
||||
readLaunchctlPath,
|
||||
userShell: "/bin/zsh",
|
||||
logWarning,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(2, "/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
|
||||
expect(logWarning).toHaveBeenCalledWith(
|
||||
"Failed to read login shell environment from /opt/homebrew/bin/nu.",
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing on unsupported platforms", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
PATH: "C:\\Windows\\System32",
|
||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/usr/local/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "freebsd",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).not.toHaveBeenCalled();
|
||||
expect(env.PATH).toBe("/usr/bin");
|
||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("hydrates PATH on Windows by merging PowerShell PATH with inherited PATH", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(() => ({
|
||||
PATH: "C:\\Custom\\Bin;C:\\Windows\\System32",
|
||||
}));
|
||||
const isWindowsCommandAvailable = vi.fn(() => true);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(readWindowsEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
"C:\\Windows\\System32",
|
||||
].join(";"),
|
||||
);
|
||||
expect(isWindowsCommandAvailable).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("loads the PowerShell profile on Windows when node is not available", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(
|
||||
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
|
||||
options?.loadProfile
|
||||
? {
|
||||
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
|
||||
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
|
||||
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
|
||||
}
|
||||
: { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" },
|
||||
);
|
||||
const isWindowsCommandAvailable = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Profile\\Node",
|
||||
"C:\\Windows\\System32",
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
].join(";"),
|
||||
);
|
||||
expect(env.FNM_DIR).toBe("C:\\Users\\testuser\\AppData\\Roaming\\fnm");
|
||||
expect(env.FNM_MULTISHELL_PATH).toBe(
|
||||
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
|
||||
);
|
||||
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
|
||||
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
|
||||
{ loadProfile: true },
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves baseline Windows env when the profile probe fails", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(
|
||||
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => {
|
||||
if (options?.loadProfile) {
|
||||
throw new Error("profile load failed");
|
||||
}
|
||||
return { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" };
|
||||
},
|
||||
);
|
||||
const isWindowsCommandAvailable = vi.fn(() => false);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
"C:\\Windows\\System32",
|
||||
].join(";"),
|
||||
);
|
||||
expect(env.SSH_AUTH_SOCK).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,29 +1,109 @@
|
||||
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
|
||||
import {
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveWindowsEnvironment,
|
||||
} from "@t3tools/shared/shell";
|
||||
import type {
|
||||
CommandAvailabilityOptions,
|
||||
ShellEnvironmentReader,
|
||||
WindowsShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
type WindowsCommandAvailabilityChecker = (
|
||||
command: string,
|
||||
options?: CommandAvailabilityOptions,
|
||||
) => boolean;
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const;
|
||||
|
||||
function logShellEnvironmentWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[desktop] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
options: {
|
||||
platform?: NodeJS.Platform;
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
readWindowsEnvironment?: WindowsShellEnvironmentReader;
|
||||
isWindowsCommandAvailable?: WindowsCommandAvailabilityChecker;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
if ((options.platform ?? process.platform) !== "darwin") return;
|
||||
const platform = options.platform ?? process.platform;
|
||||
|
||||
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
|
||||
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
|
||||
const shellEnvironment: Partial<Record<string, string>> = {};
|
||||
|
||||
try {
|
||||
const shell = env.SHELL ?? "/bin/zsh";
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
]);
|
||||
if (platform === "win32") {
|
||||
const repairedEnvironment = resolveWindowsEnvironment(env, {
|
||||
...(options.readWindowsEnvironment
|
||||
? { readEnvironment: options.readWindowsEnvironment }
|
||||
: {}),
|
||||
...(options.isWindowsCommandAvailable
|
||||
? { commandAvailable: options.isWindowsCommandAvailable }
|
||||
: {}),
|
||||
});
|
||||
for (const [key, value] of Object.entries(repairedEnvironment)) {
|
||||
if (value !== undefined) {
|
||||
env[key] = value;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (shellEnvironment.PATH) {
|
||||
env.PATH = shellEnvironment.PATH;
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
|
||||
if (shellEnvironment.PATH) {
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read login shell environment from ${shell}.`, error);
|
||||
}
|
||||
}
|
||||
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellEnvironment.PATH
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellEnvironment.PATH ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
}
|
||||
|
||||
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
|
||||
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
} catch {
|
||||
// Keep inherited environment if shell lookup fails.
|
||||
|
||||
for (const name of [
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const) {
|
||||
if (!env[name] && shellEnvironment[name]) {
|
||||
env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to synchronize the desktop shell environment.", error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import {
|
||||
isTailscaleIpv4Address,
|
||||
parseTailscaleMagicDnsName,
|
||||
resolveTailscaleAdvertisedEndpoints,
|
||||
} from "./tailscaleEndpointProvider.ts";
|
||||
|
||||
describe("tailscale endpoint provider", () => {
|
||||
it("detects Tailnet IPv4 addresses", () => {
|
||||
expect(isTailscaleIpv4Address("100.64.0.1")).toBe(true);
|
||||
expect(isTailscaleIpv4Address("100.127.255.254")).toBe(true);
|
||||
expect(isTailscaleIpv4Address("100.128.0.1")).toBe(false);
|
||||
expect(isTailscaleIpv4Address("192.168.1.44")).toBe(false);
|
||||
});
|
||||
|
||||
it("parses MagicDNS names from tailscale status", async () => {
|
||||
expect(
|
||||
Effect.runSync(
|
||||
parseTailscaleMagicDnsName(JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } })),
|
||||
),
|
||||
).toBe("desktop.tail.ts.net");
|
||||
expect(Effect.runSync(parseTailscaleMagicDnsName("{}"))).toBeNull();
|
||||
await expect(Effect.runPromise(parseTailscaleMagicDnsName("not-json"))).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
it("resolves Tailscale endpoints as add-on advertised endpoints", async () => {
|
||||
await expect(
|
||||
resolveTailscaleAdvertisedEndpoints({
|
||||
port: 3773,
|
||||
networkInterfaces: {
|
||||
tailscale0: [
|
||||
{
|
||||
address: "100.100.100.100",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.192.0.0",
|
||||
cidr: "100.100.100.100/10",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
|
||||
}),
|
||||
).resolves.toEqual([
|
||||
{
|
||||
id: "tailscale-ip:http://100.100.100.100:3773",
|
||||
label: "Tailscale IP",
|
||||
provider: {
|
||||
id: "tailscale",
|
||||
label: "Tailscale",
|
||||
kind: "private-network",
|
||||
isAddon: true,
|
||||
},
|
||||
httpBaseUrl: "http://100.100.100.100:3773/",
|
||||
wsBaseUrl: "ws://100.100.100.100:3773/",
|
||||
reachability: "private-network",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "mixed-content-blocked",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "desktop-addon",
|
||||
status: "available",
|
||||
description: "Reachable from devices on the same Tailnet.",
|
||||
},
|
||||
{
|
||||
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
|
||||
label: "Tailscale HTTPS",
|
||||
provider: {
|
||||
id: "tailscale",
|
||||
label: "Tailscale",
|
||||
kind: "private-network",
|
||||
isAddon: true,
|
||||
},
|
||||
httpBaseUrl: "https://desktop.tail.ts.net/",
|
||||
wsBaseUrl: "wss://desktop.tail.ts.net/",
|
||||
reachability: "private-network",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "requires-configuration",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "desktop-addon",
|
||||
status: "unavailable",
|
||||
description: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable", async () => {
|
||||
await expect(
|
||||
resolveTailscaleAdvertisedEndpoints({
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
|
||||
serveEnabled: true,
|
||||
probe: async () => true,
|
||||
}),
|
||||
).resolves.toEqual([
|
||||
{
|
||||
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
|
||||
label: "Tailscale HTTPS",
|
||||
provider: {
|
||||
id: "tailscale",
|
||||
label: "Tailscale",
|
||||
kind: "private-network",
|
||||
isAddon: true,
|
||||
},
|
||||
httpBaseUrl: "https://desktop.tail.ts.net/",
|
||||
wsBaseUrl: "wss://desktop.tail.ts.net/",
|
||||
reachability: "private-network",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "compatible",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "desktop-addon",
|
||||
status: "available",
|
||||
description: "HTTPS endpoint served by Tailscale Serve.",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
|
||||
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
|
||||
import {
|
||||
buildTailscaleHttpsBaseUrl,
|
||||
isTailscaleIpv4Address,
|
||||
parseTailscaleMagicDnsName,
|
||||
probeTailscaleHttpsEndpoint,
|
||||
readTailscaleStatus,
|
||||
} from "@t3tools/tailscale";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
|
||||
|
||||
const TailscaleDesktopLayer = Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici);
|
||||
|
||||
const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
||||
id: "tailscale",
|
||||
label: "Tailscale",
|
||||
kind: "private-network",
|
||||
isAddon: true,
|
||||
};
|
||||
|
||||
function createTailscaleEndpoint(
|
||||
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
|
||||
): AdvertisedEndpoint {
|
||||
return createAdvertisedEndpoint({
|
||||
...input,
|
||||
provider: TAILSCALE_ENDPOINT_PROVIDER,
|
||||
source: "desktop-addon",
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveTailscaleIpAdvertisedEndpoints(input: {
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
|
||||
}): readonly AdvertisedEndpoint[] {
|
||||
const seen = new Set<string>();
|
||||
const endpoints: AdvertisedEndpoint[] = [];
|
||||
|
||||
for (const interfaceAddresses of Object.values(input.networkInterfaces)) {
|
||||
if (!interfaceAddresses) continue;
|
||||
|
||||
for (const address of interfaceAddresses) {
|
||||
if (address.internal) continue;
|
||||
if (address.family !== "IPv4") continue;
|
||||
if (!isTailscaleIpv4Address(address.address)) continue;
|
||||
if (seen.has(address.address)) continue;
|
||||
seen.add(address.address);
|
||||
|
||||
endpoints.push(
|
||||
createTailscaleEndpoint({
|
||||
id: `tailscale-ip:http://${address.address}:${input.port}`,
|
||||
label: "Tailscale IP",
|
||||
httpBaseUrl: `http://${address.address}:${input.port}`,
|
||||
reachability: "private-network",
|
||||
status: "available",
|
||||
description: "Reachable from devices on the same Tailnet.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
export async function resolveTailscaleMagicDnsAdvertisedEndpoint(input: {
|
||||
readonly dnsName: string | null;
|
||||
readonly serveEnabled: boolean;
|
||||
readonly servePort?: number;
|
||||
readonly probe?: (baseUrl: string) => Promise<boolean>;
|
||||
}): Promise<AdvertisedEndpoint | null> {
|
||||
if (!input.dnsName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const httpBaseUrl = buildTailscaleHttpsBaseUrl({
|
||||
magicDnsName: input.dnsName,
|
||||
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
|
||||
});
|
||||
const isReachable = input.serveEnabled
|
||||
? await (input.probe?.(httpBaseUrl) ??
|
||||
Effect.runPromise(
|
||||
probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl }).pipe(
|
||||
Effect.provide(TailscaleDesktopLayer),
|
||||
),
|
||||
))
|
||||
: false;
|
||||
|
||||
return createTailscaleEndpoint({
|
||||
id: `tailscale-magicdns:${httpBaseUrl}`,
|
||||
label: "Tailscale HTTPS",
|
||||
httpBaseUrl,
|
||||
reachability: "private-network",
|
||||
hostedHttpsCompatibility: isReachable ? "compatible" : "requires-configuration",
|
||||
status: isReachable ? "available" : "unavailable",
|
||||
description: isReachable
|
||||
? "HTTPS endpoint served by Tailscale Serve."
|
||||
: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
|
||||
});
|
||||
}
|
||||
|
||||
export async function resolveTailscaleAdvertisedEndpoints(input: {
|
||||
readonly port: number;
|
||||
readonly serveEnabled?: boolean;
|
||||
readonly servePort?: number;
|
||||
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
|
||||
readonly statusJson?: string | null;
|
||||
readonly probe?: (baseUrl: string) => Promise<boolean>;
|
||||
}): Promise<readonly AdvertisedEndpoint[]> {
|
||||
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
? await Effect.runPromise(
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.provide(TailscaleDesktopLayer),
|
||||
),
|
||||
)
|
||||
: input.statusJson
|
||||
? await Effect.runPromise(
|
||||
parseTailscaleMagicDnsName(input.statusJson).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const magicDnsEndpoint = await resolveTailscaleMagicDnsAdvertisedEndpoint({
|
||||
dnsName,
|
||||
serveEnabled: input.serveEnabled === true,
|
||||
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
|
||||
...(input.probe === undefined ? {} : { probe: input.probe }),
|
||||
});
|
||||
|
||||
return magicDnsEndpoint ? [...ipEndpoints, magicDnsEndpoint] : ipEndpoints;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
doesVersionMatchDesktopUpdateChannel,
|
||||
isNightlyDesktopVersion,
|
||||
resolveDefaultDesktopUpdateChannel,
|
||||
} from "./updateChannels.ts";
|
||||
|
||||
describe("isNightlyDesktopVersion", () => {
|
||||
it("detects packaged nightly versions", () => {
|
||||
expect(isNightlyDesktopVersion("0.0.17-nightly.20260415.1")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not flag stable versions as nightly", () => {
|
||||
expect(isNightlyDesktopVersion("0.0.17")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDefaultDesktopUpdateChannel", () => {
|
||||
it("defaults stable builds to latest", () => {
|
||||
expect(resolveDefaultDesktopUpdateChannel("0.0.17")).toBe("latest");
|
||||
});
|
||||
|
||||
it("defaults nightly builds to nightly", () => {
|
||||
expect(resolveDefaultDesktopUpdateChannel("0.0.17-nightly.20260415.1")).toBe("nightly");
|
||||
});
|
||||
});
|
||||
|
||||
describe("doesVersionMatchDesktopUpdateChannel", () => {
|
||||
it("accepts nightly releases on the nightly channel", () => {
|
||||
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "nightly")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects stable releases on the nightly channel", () => {
|
||||
expect(doesVersionMatchDesktopUpdateChannel("0.0.17", "nightly")).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects nightly releases on the stable channel", () => {
|
||||
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "latest")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { DesktopUpdateChannel } from "@t3tools/contracts";
|
||||
|
||||
const NIGHTLY_VERSION_PATTERN = /-nightly\.\d{8}\.\d+$/;
|
||||
|
||||
export function isNightlyDesktopVersion(version: string): boolean {
|
||||
return NIGHTLY_VERSION_PATTERN.test(version);
|
||||
}
|
||||
|
||||
export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
|
||||
return isNightlyDesktopVersion(appVersion) ? "nightly" : "latest";
|
||||
}
|
||||
|
||||
export function doesVersionMatchDesktopUpdateChannel(
|
||||
version: string,
|
||||
channel: DesktopUpdateChannel,
|
||||
): boolean {
|
||||
return resolveDefaultDesktopUpdateChannel(version) === channel;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
} from "./updateMachine.ts";
|
||||
|
||||
const runtimeInfo = {
|
||||
hostArch: "x64",
|
||||
@@ -23,7 +23,7 @@ describe("updateMachine", () => {
|
||||
it("clears transient errors when a check starts", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
message: "network",
|
||||
@@ -42,7 +42,7 @@ describe("updateMachine", () => {
|
||||
it("records a check failure without exposing an action", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
@@ -58,7 +58,7 @@ describe("updateMachine", () => {
|
||||
it("preserves available version on download failure for retry", () => {
|
||||
const state = reduceDesktopUpdateStateOnDownloadFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
@@ -76,7 +76,7 @@ describe("updateMachine", () => {
|
||||
it("transitions to downloaded and then preserves install retry state", () => {
|
||||
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
@@ -98,7 +98,7 @@ describe("updateMachine", () => {
|
||||
it("clears stale download state when no update is available", () => {
|
||||
const state = reduceDesktopUpdateStateOnNoUpdate(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
availableVersion: "1.1.0",
|
||||
@@ -120,7 +120,7 @@ describe("updateMachine", () => {
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
@@ -131,6 +131,7 @@ describe("updateMachine", () => {
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(available.channel).toBe("latest");
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
|
||||
import type {
|
||||
DesktopRuntimeInfo,
|
||||
DesktopUpdateChannel,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState.ts";
|
||||
|
||||
export function createInitialDesktopUpdateState(
|
||||
currentVersion: string,
|
||||
runtimeInfo: DesktopRuntimeInfo,
|
||||
channel: DesktopUpdateChannel,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
enabled: false,
|
||||
status: "disabled",
|
||||
channel,
|
||||
currentVersion,
|
||||
hostArch: runtimeInfo.hostArch,
|
||||
appArch: runtimeInfo.appArch,
|
||||
|
||||
@@ -6,11 +6,12 @@ import {
|
||||
getAutoUpdateDisabledReason,
|
||||
nextStatusAfterDownloadFailure,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState";
|
||||
} from "./updateState.ts";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
channel: "latest",
|
||||
currentVersion: "1.0.0",
|
||||
hostArch: "x64",
|
||||
appArch: "x64",
|
||||
@@ -71,10 +72,37 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("packaged production builds");
|
||||
});
|
||||
|
||||
it("reports packaged local builds without an update feed as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: false,
|
||||
}),
|
||||
).toContain("no update feed");
|
||||
});
|
||||
|
||||
it("allows packaged builds with an update feed", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("reports env-disabled auto updates", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
@@ -83,6 +111,7 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: true,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||
});
|
||||
@@ -95,6 +124,7 @@ describe("getAutoUpdateDisabledReason", () => {
|
||||
platform: "linux",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
hasUpdateFeedConfig: true,
|
||||
}),
|
||||
).toContain("AppImage");
|
||||
});
|
||||
|
||||
@@ -34,7 +34,11 @@ export function getAutoUpdateDisabledReason(args: {
|
||||
platform: NodeJS.Platform;
|
||||
appImage?: string | undefined;
|
||||
disabledByEnv: boolean;
|
||||
hasUpdateFeedConfig: boolean;
|
||||
}): string | null {
|
||||
if (!args.hasUpdateFeedConfig) {
|
||||
return "Automatic updates are not available because no update feed is configured.";
|
||||
}
|
||||
if (args.isDevelopment || !args.isPackaged) {
|
||||
return "Automatic updates are only available in packaged production builds.";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
discoverEditorColorThemes,
|
||||
getEditorThemePreferences,
|
||||
loadEditorColorTheme,
|
||||
resolveEditorRoots,
|
||||
} from "./vscodeThemeDiscovery.ts";
|
||||
|
||||
let tempDir = "";
|
||||
|
||||
function writeJson(filePath: string, value: unknown) {
|
||||
FS.mkdirSync(Path.dirname(filePath), { recursive: true });
|
||||
FS.writeFileSync(filePath, JSON.stringify(value, null, 2));
|
||||
}
|
||||
|
||||
describe("vscodeThemeDiscovery", () => {
|
||||
beforeEach(() => {
|
||||
tempDir = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-vscode-themes-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
FS.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("discovers contributed themes and ignores unsafe paths", () => {
|
||||
const roots = resolveEditorRoots({ platform: "darwin", homedir: tempDir });
|
||||
const vscodeRoot = roots.find((root) => root.source === "vscode");
|
||||
expect(vscodeRoot).toBeDefined();
|
||||
if (!vscodeRoot) return;
|
||||
|
||||
const extensionDir = Path.join(vscodeRoot.extensionsPath, "github.github-vscode-theme");
|
||||
writeJson(Path.join(extensionDir, "package.json"), {
|
||||
publisher: "GitHub",
|
||||
displayName: "GitHub Theme",
|
||||
contributes: {
|
||||
themes: [
|
||||
{ label: "GitHub Dark Default", uiTheme: "vs-dark", path: "./themes/dark.json" },
|
||||
{ label: "Escaped", uiTheme: "vs", path: "../escaped.json" },
|
||||
],
|
||||
},
|
||||
});
|
||||
writeJson(Path.join(extensionDir, "themes", "dark.json"), {
|
||||
colors: { "editor.background": "#0d1117" },
|
||||
});
|
||||
|
||||
expect(discoverEditorColorThemes(roots)).toMatchObject([
|
||||
{
|
||||
source: "vscode",
|
||||
label: "GitHub Dark Default",
|
||||
kind: "dark",
|
||||
publisher: "GitHub",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("loads JSONC settings overrides into the resolved app theme", () => {
|
||||
const roots = resolveEditorRoots({ platform: "darwin", homedir: tempDir });
|
||||
const vscodeRoot = roots.find((root) => root.source === "vscode");
|
||||
expect(vscodeRoot).toBeDefined();
|
||||
if (!vscodeRoot) return;
|
||||
|
||||
const extensionDir = Path.join(vscodeRoot.extensionsPath, "github.github-vscode-theme");
|
||||
writeJson(Path.join(extensionDir, "package.json"), {
|
||||
contributes: {
|
||||
themes: [{ label: "GitHub Dark Default", uiTheme: "vs-dark", path: "./themes/dark.json" }],
|
||||
},
|
||||
});
|
||||
writeJson(Path.join(extensionDir, "themes", "dark.json"), {
|
||||
semanticHighlighting: true,
|
||||
colors: {
|
||||
"editor.background": "#0d1117",
|
||||
"editor.foreground": "#e6edf3",
|
||||
},
|
||||
tokenColors: [],
|
||||
});
|
||||
FS.mkdirSync(Path.dirname(vscodeRoot.settingsPath), { recursive: true });
|
||||
FS.writeFileSync(
|
||||
vscodeRoot.settingsPath,
|
||||
`{
|
||||
"workbench.colorTheme": "GitHub Dark Default",
|
||||
"workbench.colorCustomizations": {
|
||||
"button.background": "#238636",
|
||||
"[GitHub Dark Default]": {
|
||||
"sideBar.background": "#010409"
|
||||
}
|
||||
}
|
||||
}`,
|
||||
);
|
||||
|
||||
const preferences = getEditorThemePreferences(roots);
|
||||
expect(preferences[0]?.colorTheme).toBe("GitHub Dark Default");
|
||||
|
||||
const themeId = discoverEditorColorThemes(roots)[0]?.id;
|
||||
expect(themeId).toBeTruthy();
|
||||
const resolved = themeId ? loadEditorColorTheme(themeId, roots) : null;
|
||||
|
||||
expect(resolved?.colors["button.background"]).toBe("#238636");
|
||||
expect(resolved?.colors["sideBar.background"]).toBe("#010409");
|
||||
expect(resolved?.appVariables["--primary"]).toBe("#238636");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,284 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { parse as parseJsonc } from "jsonc-parser";
|
||||
import type {
|
||||
DiscoveredColorTheme,
|
||||
EditorThemePreference,
|
||||
EditorThemeSource,
|
||||
ResolvedColorTheme,
|
||||
ThemeKind,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
mapVscodeColorsToAppVariables,
|
||||
normalizeCssColor,
|
||||
normalizeThemeColors,
|
||||
} from "@t3tools/shared/themeMapping";
|
||||
|
||||
interface EditorRoot {
|
||||
readonly source: EditorThemeSource;
|
||||
readonly extensionsPath: string;
|
||||
readonly settingsPath: string;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function kindFromUiTheme(uiTheme: unknown): ThemeKind {
|
||||
if (uiTheme === "hc-light") return "high-contrast-light";
|
||||
if (uiTheme === "hc-black") return "high-contrast-dark";
|
||||
if (uiTheme === "vs") return "light";
|
||||
return "dark";
|
||||
}
|
||||
|
||||
function readJsonOrJsoncFile(filePath: string): unknown | null {
|
||||
try {
|
||||
return parseJsonc(FS.readFileSync(filePath, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function safeResolveChild(root: string, relativePath: string): string | null {
|
||||
const resolved = Path.resolve(root, relativePath);
|
||||
const normalizedRoot = Path.resolve(root);
|
||||
if (resolved === normalizedRoot || resolved.startsWith(`${normalizedRoot}${Path.sep}`)) {
|
||||
return resolved;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveEditorRoots(input: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly homedir: string;
|
||||
readonly appData?: string;
|
||||
}): readonly EditorRoot[] {
|
||||
const home = input.homedir;
|
||||
if (input.platform === "win32") {
|
||||
const appData = input.appData ?? Path.join(home, "AppData", "Roaming");
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(appData, "Code", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(appData, "Code - Insiders", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(appData, "Cursor", "User", "settings.json"),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (input.platform === "darwin") {
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Code",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Code - Insiders",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Cursor",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Code", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Code - Insiders", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Cursor", "User", "settings.json"),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function resolveDefaultEditorRoots() {
|
||||
const input: { platform: NodeJS.Platform; homedir: string; appData?: string } = {
|
||||
platform: process.platform,
|
||||
homedir: OS.homedir(),
|
||||
};
|
||||
if (process.env.APPDATA) input.appData = process.env.APPDATA;
|
||||
return resolveEditorRoots(input);
|
||||
}
|
||||
|
||||
function readEditorSettings(settingsPath: string): Record<string, unknown> {
|
||||
const parsed = readJsonOrJsoncFile(settingsPath);
|
||||
return isObject(parsed) ? parsed : {};
|
||||
}
|
||||
|
||||
export function getEditorThemePreferences(
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): readonly EditorThemePreference[] {
|
||||
return roots.map((root) => {
|
||||
const settings = readEditorSettings(root.settingsPath);
|
||||
const customizations = settings["workbench.colorCustomizations"];
|
||||
return {
|
||||
source: root.source,
|
||||
colorTheme:
|
||||
typeof settings["workbench.colorTheme"] === "string"
|
||||
? settings["workbench.colorTheme"]
|
||||
: null,
|
||||
preferredLightColorTheme:
|
||||
typeof settings["workbench.preferredLightColorTheme"] === "string"
|
||||
? settings["workbench.preferredLightColorTheme"]
|
||||
: null,
|
||||
preferredDarkColorTheme:
|
||||
typeof settings["workbench.preferredDarkColorTheme"] === "string"
|
||||
? settings["workbench.preferredDarkColorTheme"]
|
||||
: null,
|
||||
autoDetectColorScheme: settings["window.autoDetectColorScheme"] === true,
|
||||
workbenchColorCustomizations: isObject(customizations) ? customizations : {},
|
||||
editorTokenColorCustomizations: settings["editor.tokenColorCustomizations"],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function discoverEditorColorThemes(
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): readonly DiscoveredColorTheme[] {
|
||||
const themes: DiscoveredColorTheme[] = [];
|
||||
|
||||
for (const root of roots) {
|
||||
if (!FS.existsSync(root.extensionsPath)) continue;
|
||||
|
||||
for (const entry of FS.readdirSync(root.extensionsPath, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
|
||||
const extensionDir = Path.join(root.extensionsPath, entry.name);
|
||||
const packagePath = Path.join(extensionDir, "package.json");
|
||||
const packageJson = readJsonOrJsoncFile(packagePath);
|
||||
if (!isObject(packageJson)) continue;
|
||||
|
||||
const contributes = packageJson.contributes;
|
||||
const contributedThemes = isObject(contributes) ? contributes.themes : null;
|
||||
if (!Array.isArray(contributedThemes)) continue;
|
||||
|
||||
for (const theme of contributedThemes) {
|
||||
if (!isObject(theme) || typeof theme.label !== "string" || typeof theme.path !== "string") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const themePath = safeResolveChild(extensionDir, theme.path);
|
||||
if (!themePath || !FS.existsSync(themePath)) continue;
|
||||
|
||||
themes.push({
|
||||
id: `${root.source}:${entry.name}:${theme.label}`,
|
||||
source: root.source,
|
||||
extensionId: entry.name,
|
||||
extensionDisplayName:
|
||||
typeof packageJson.displayName === "string" ? packageJson.displayName : undefined,
|
||||
label: theme.label,
|
||||
kind: kindFromUiTheme(theme.uiTheme),
|
||||
themePath,
|
||||
packagePath,
|
||||
publisher: typeof packageJson.publisher === "string" ? packageJson.publisher : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return themes.toSorted((a, b) => a.label.localeCompare(b.label));
|
||||
}
|
||||
|
||||
function mergeWorkbenchOverrides(input: {
|
||||
readonly themeLabel: string;
|
||||
readonly themeColors: Record<string, string>;
|
||||
readonly customizations: Record<string, unknown>;
|
||||
}) {
|
||||
const next = { ...input.themeColors };
|
||||
|
||||
for (const [key, rawValue] of Object.entries(input.customizations)) {
|
||||
if (key.startsWith("[") && key.endsWith("]")) continue;
|
||||
const color = normalizeCssColor(rawValue);
|
||||
if (color) next[key] = color;
|
||||
}
|
||||
|
||||
const scoped = input.customizations[`[${input.themeLabel}]`];
|
||||
if (isObject(scoped)) {
|
||||
for (const [key, rawValue] of Object.entries(scoped)) {
|
||||
const color = normalizeCssColor(rawValue);
|
||||
if (color) next[key] = color;
|
||||
}
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function loadEditorColorTheme(
|
||||
themeId: string,
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): ResolvedColorTheme | null {
|
||||
const themes = discoverEditorColorThemes(roots);
|
||||
const theme = themes.find((entry) => entry.id === themeId);
|
||||
if (!theme) return null;
|
||||
|
||||
const rawTheme = readJsonOrJsoncFile(theme.themePath);
|
||||
if (!isObject(rawTheme)) return null;
|
||||
|
||||
const preferences = getEditorThemePreferences(roots);
|
||||
const preference = preferences.find((entry) => entry.source === theme.source);
|
||||
const colors = mergeWorkbenchOverrides({
|
||||
themeLabel: theme.label,
|
||||
themeColors: normalizeThemeColors(rawTheme.colors),
|
||||
customizations: preference?.workbenchColorCustomizations ?? {},
|
||||
});
|
||||
|
||||
return {
|
||||
id: theme.id,
|
||||
label: theme.label,
|
||||
source: theme.source,
|
||||
kind: theme.kind,
|
||||
colors,
|
||||
tokenColors: rawTheme.tokenColors ?? [],
|
||||
semanticHighlighting:
|
||||
typeof rawTheme.semanticHighlighting === "boolean"
|
||||
? rawTheme.semanticHighlighting
|
||||
: undefined,
|
||||
semanticTokenColors: rawTheme.semanticTokenColors,
|
||||
appVariables: mapVscodeColorsToAppVariables({ kind: theme.kind, colors }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { bindFirstRevealTrigger } from "./windowReveal.ts";
|
||||
|
||||
describe("bindFirstRevealTrigger", () => {
|
||||
it("reveals when the first trigger fires", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reveals when only the fallback trigger fires (Wayland deadlock case)", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
webContents.emit("did-finish-load");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("only reveals once when multiple triggers fire", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
webContents.emit("did-finish-load");
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("subscribers using `once` ignore re-emitted events after reveal", () => {
|
||||
const window = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger([(fire) => window.once("ready-to-show", fire)], reveal);
|
||||
|
||||
window.emit("ready-to-show");
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
export type RevealSubscription = (listener: () => void) => void;
|
||||
|
||||
/**
|
||||
* Wire a reveal callback to fire exactly once, on whichever of the provided
|
||||
* event subscribers fires first. Each subscriber is responsible for binding
|
||||
* its own event source.
|
||||
*
|
||||
* Used by the desktop main window's first-paint reveal logic. The standard
|
||||
* Electron pattern is to wait for `ready-to-show` before calling `show()`,
|
||||
* but on Linux/Wayland with `show: false`, `ready-to-show` only fires after
|
||||
* `show()` is called, deadlocking that pattern. Subscribing to both
|
||||
* `ready-to-show` and `did-finish-load` (or any other "renderer is alive"
|
||||
* signal) lets the window surface reliably across platforms.
|
||||
*/
|
||||
export function bindFirstRevealTrigger(
|
||||
subscribers: readonly RevealSubscription[],
|
||||
reveal: () => void,
|
||||
): void {
|
||||
let revealed = false;
|
||||
const fire = () => {
|
||||
if (revealed) return;
|
||||
revealed = true;
|
||||
reveal();
|
||||
};
|
||||
for (const subscribe of subscribers) {
|
||||
subscribe(fire);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"types": ["node", "electron"],
|
||||
"lib": ["ES2023", "DOM", "esnext.disposable"]
|
||||
"lib": ["ESNext", "DOM", "esnext.disposable"]
|
||||
},
|
||||
"include": ["src", "tsdown.config.ts"]
|
||||
}
|
||||
@@ -4,7 +4,7 @@ const shared = {
|
||||
format: "cjs" as const,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".js" }),
|
||||
outExtensions: () => ({ js: ".cjs" }),
|
||||
};
|
||||
|
||||
export default defineConfig([
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
---
|
||||
import Layout from "../layouts/Layout.astro";
|
||||
import { RELEASES_URL } from "../lib/releases";
|
||||
---
|
||||
|
||||
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
|
||||
@@ -17,11 +18,11 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">macOS</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="arm64.dmg" href="#">
|
||||
<a class="download-card" data-asset="arm64.dmg" href={RELEASES_URL}>
|
||||
<span class="card-arch">Apple Silicon (arm64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
<a class="download-card" data-asset="x64.dmg" href="#">
|
||||
<a class="download-card" data-asset="x64.dmg" href={RELEASES_URL}>
|
||||
<span class="card-arch">Intel (x64)</span>
|
||||
<span class="card-format">.dmg</span>
|
||||
</a>
|
||||
@@ -35,7 +36,7 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">Windows</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x64.exe" href="#">
|
||||
<a class="download-card" data-asset="x64.exe" href={RELEASES_URL}>
|
||||
<span class="card-arch">Windows 10, 11</span>
|
||||
<span class="card-format">.exe</span>
|
||||
</a>
|
||||
@@ -49,7 +50,7 @@ import Layout from "../layouts/Layout.astro";
|
||||
<h2 class="platform-name">Linux</h2>
|
||||
</div>
|
||||
<div class="download-cards">
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href="#">
|
||||
<a class="download-card" data-asset="x86_64.AppImage" href={RELEASES_URL}>
|
||||
<span class="card-arch">x86_64</span>
|
||||
<span class="card-format">AppImage</span>
|
||||
</a>
|
||||
|
||||
@@ -3,7 +3,8 @@ import { execFileSync } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
ProviderKind,
|
||||
CodexSettings,
|
||||
ProviderDriverKind,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -24,9 +25,7 @@ import {
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
||||
@@ -35,19 +34,24 @@ import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/
|
||||
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
|
||||
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
|
||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import {
|
||||
NoOpProviderEventLoggers,
|
||||
ProviderEventLoggers,
|
||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../src/project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
||||
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
||||
@@ -55,6 +59,7 @@ import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../src/orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
|
||||
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -67,6 +72,13 @@ import {
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
||||
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
|
||||
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
|
||||
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -123,7 +135,7 @@ function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 10_000,
|
||||
timeoutMs = 40_000,
|
||||
): Effect.Effect<A, never> {
|
||||
const RETRY_SIGNAL = "wait_for_retry";
|
||||
const retryIntervalMs = 10;
|
||||
@@ -208,7 +220,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly provider?: ProviderDriverKind;
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
@@ -219,7 +231,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const provider = options?.provider ?? "codex";
|
||||
const provider = options?.provider ?? ProviderDriverKind.make("codex");
|
||||
const useRealCodex = options?.realCodex === true;
|
||||
const adapterHarness = useRealCodex
|
||||
? null
|
||||
@@ -227,13 +239,10 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
provider,
|
||||
});
|
||||
const fakeRegistry = adapterHarness
|
||||
? Layer.succeed(ProviderAdapterRegistry, {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === adapterHarness.provider
|
||||
? Effect.succeed(adapterHarness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service)
|
||||
? Layer.succeed(
|
||||
ProviderAdapterRegistry,
|
||||
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
|
||||
)
|
||||
: null;
|
||||
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-orchestration-integration-",
|
||||
@@ -258,68 +267,107 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
const realCodexRegistry = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexAdapter = yield* CodexAdapter;
|
||||
return {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === "codex"
|
||||
? Effect.succeed(codexAdapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed(["codex"] as const),
|
||||
} as typeof ProviderAdapterRegistry.Service;
|
||||
const codexSettings = Schema.decodeSync(CodexSettings)({});
|
||||
const codexAdapter = yield* makeCodexAdapter(codexSettings);
|
||||
return makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: codexAdapter,
|
||||
});
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(makeCodexAdapterLive()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
|
||||
const providerLayer = useRealCodex
|
||||
? makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(realCodexRegistry),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(providerEventLoggersLayer),
|
||||
)
|
||||
: makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(fakeRegistry!),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(providerEventLoggersLayer),
|
||||
);
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
|
||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
projectionSnapshotQueryLayer,
|
||||
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusLive,
|
||||
RuntimeReceiptBusTest,
|
||||
);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
|
||||
Effect.succeed({ branch: input.newBranch }),
|
||||
} as unknown as GitCoreShape);
|
||||
});
|
||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||
generateBranchName: () => Effect.succeed({ branch: null }),
|
||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(gitWorkflowLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
|
||||
streamStatus: () => Stream.empty,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsDriverRegistry.layer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadDeletionReactor, {
|
||||
start: () => Effect.void,
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
const layer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(orchestrationReactorLayer),
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
@@ -354,10 +402,10 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
||||
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
|
||||
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
|
||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* Effect.sleep(10);
|
||||
@@ -400,7 +448,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
ProviderTurnStartResult,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderKind,
|
||||
ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
@@ -36,7 +36,7 @@ export interface TestTurnResponse {
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: ProviderKind;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly provider?: ProviderDriverKind;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
@@ -206,7 +206,7 @@ function nowIso(): string {
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: ProviderKind,
|
||||
provider: ProviderDriverKind,
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
@@ -216,7 +216,7 @@ function sessionNotFound(
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: ProviderKind,
|
||||
provider: ProviderDriverKind,
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
@@ -224,7 +224,7 @@ function missingSessionEffect(
|
||||
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = options?.provider ?? "codex";
|
||||
const provider = options?.provider ?? ProviderDriverKind.make("codex");
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
const sessions = new Map<ThreadId, SessionState>();
|
||||
@@ -257,6 +257,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
...(input.providerInstanceId !== undefined
|
||||
? { providerInstanceId: input.providerInstanceId }
|
||||
: {}),
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId,
|
||||
@@ -289,7 +292,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
const turnId = TurnId.make(`turn-${turnCount}`);
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
@@ -307,7 +310,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
|
||||
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
@@ -363,7 +366,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
eventId: EventId.make(randomUUID()),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const PROVIDER = ProviderDriverKind.make("codex");
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
||||
const REQUEST_ID = RuntimeRequestId.make("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.makeUnsafe(eventId),
|
||||
eventId: EventId.make(eventId),
|
||||
provider: PROVIDER,
|
||||
sessionId: SESSION_ID,
|
||||
createdAt,
|
||||
|
||||
@@ -4,14 +4,17 @@ import path from "node:path";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
defaultInstanceIdForDriver,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderKind,
|
||||
ProviderDriverKind,
|
||||
ThreadId,
|
||||
ModelSelection,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Option, Schema } from "effect";
|
||||
@@ -30,17 +33,18 @@ import type {
|
||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||
|
||||
const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = ProviderKind;
|
||||
type IntegrationProvider = ProviderDriverKind;
|
||||
const CODEX_PROVIDER = ProviderDriverKind.make("codex");
|
||||
const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
@@ -57,7 +61,7 @@ function waitForSync<A>(
|
||||
read: () => A,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 3000,
|
||||
timeoutMs = 10_000,
|
||||
): Effect.Effect<A, never> {
|
||||
return Effect.gen(function* () {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
@@ -75,7 +79,11 @@ function waitForSync<A>(
|
||||
});
|
||||
}
|
||||
|
||||
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
|
||||
function runtimeBase(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
provider: IntegrationProvider = CODEX_PROVIDER,
|
||||
) {
|
||||
return {
|
||||
eventId: asEventId(eventId),
|
||||
provider,
|
||||
@@ -85,7 +93,7 @@ function runtimeBase(eventId: string, createdAt: string, provider: IntegrationPr
|
||||
|
||||
function withHarness<A, E>(
|
||||
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
||||
provider: IntegrationProvider = "codex",
|
||||
provider: IntegrationProvider = CODEX_PROVIDER,
|
||||
) {
|
||||
return Effect.acquireUseRelease(
|
||||
makeOrchestrationIntegrationHarness({ provider }),
|
||||
@@ -98,7 +106,7 @@ function withRealCodexHarness<A, E>(
|
||||
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
||||
) {
|
||||
return Effect.acquireUseRelease(
|
||||
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
||||
makeOrchestrationIntegrationHarness({ provider: CODEX_PROVIDER, realCodex: true }),
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
).pipe(Effect.provide(NodeServices.layer));
|
||||
@@ -107,17 +115,18 @@ function withRealCodexHarness<A, E>(
|
||||
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = nowIso();
|
||||
const provider = harness.adapterHarness?.provider ?? "codex";
|
||||
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
const provider = harness.adapterHarness?.provider ?? CODEX_PROVIDER;
|
||||
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
|
||||
const instanceId = defaultInstanceIdForDriver(provider);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModelSelection: {
|
||||
provider,
|
||||
instanceId,
|
||||
model: defaultModel,
|
||||
},
|
||||
createdAt,
|
||||
@@ -125,12 +134,12 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
modelSelection: {
|
||||
provider,
|
||||
instanceId,
|
||||
model: defaultModel,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -150,7 +159,7 @@ const startTurn = (input: {
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe(input.commandId),
|
||||
commandId: CommandId.make(input.commandId),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId(input.messageId),
|
||||
@@ -261,12 +270,12 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
|
||||
commandId: CommandId.make("cmd-project-create-real-codex"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
createdAt,
|
||||
@@ -274,12 +283,12 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
|
||||
commandId: CommandId.make("cmd-thread-create-real-codex"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -291,7 +300,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),
|
||||
commandId: CommandId.make("cmd-turn-start-real-codex-1"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-1"),
|
||||
@@ -318,7 +327,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),
|
||||
commandId: CommandId.make("cmd-turn-start-real-codex-2"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-2"),
|
||||
@@ -497,6 +506,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
assert.equal(incrementalDiff.includes("README.md"), true);
|
||||
|
||||
@@ -505,6 +515,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
assert.equal(fullDiff.includes("README.md"), true);
|
||||
|
||||
@@ -583,7 +594,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
|
||||
commandId: CommandId.make("cmd-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
@@ -815,7 +826,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
@@ -875,7 +886,7 @@ it.live(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert-no-session"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 0,
|
||||
createdAt: nowIso(),
|
||||
@@ -913,20 +924,32 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-start-1",
|
||||
"2026-02-24T10:10:00.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-start-2",
|
||||
"2026-02-24T10:10:00.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Claude first turn.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-start-3",
|
||||
"2026-02-24T10:10:00.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -940,7 +963,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
||||
messageId: "msg-user-claude-initial",
|
||||
text: "Use Claude",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
@@ -956,7 +979,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
||||
);
|
||||
assert.equal(thread.session?.providerName, "claudeAgent");
|
||||
}),
|
||||
"claudeAgent",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -970,20 +993,32 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-1",
|
||||
"2026-02-24T10:11:00.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-2",
|
||||
"2026-02-24T10:11:00.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn before restart.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-3",
|
||||
"2026-02-24T10:11:00.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -997,7 +1032,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
||||
messageId: "msg-user-claude-recover-1",
|
||||
text: "Before restart",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
@@ -1019,20 +1054,32 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-4",
|
||||
"2026-02-24T10:11:01.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-5",
|
||||
"2026-02-24T10:11:01.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn after restart.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-6",
|
||||
"2026-02-24T10:11:01.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1064,7 +1111,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
||||
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
|
||||
assert.equal(recoveredThread.session?.threadId, "thread-1");
|
||||
}),
|
||||
"claudeAgent",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1078,13 +1125,21 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-approval-1",
|
||||
"2026-02-24T10:12:00.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-approval-2",
|
||||
"2026-02-24T10:12:00.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
@@ -1093,7 +1148,11 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-approval-3",
|
||||
"2026-02-24T10:12:00.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1107,7 +1166,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
messageId: "msg-user-claude-approval",
|
||||
text: "Need approval",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
@@ -1119,7 +1178,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
||||
commandId: CommandId.make("cmd-claude-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
@@ -1138,7 +1197,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
);
|
||||
assert.equal(approvalResponses[0]?.decision, "accept");
|
||||
}),
|
||||
"claudeAgent",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1152,20 +1211,32 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-interrupt-1",
|
||||
"2026-02-24T10:13:00.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-interrupt-2",
|
||||
"2026-02-24T10:13:00.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Long running output.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-interrupt-3",
|
||||
"2026-02-24T10:13:00.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1179,7 +1250,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
messageId: "msg-user-claude-interrupt",
|
||||
text: "Start long turn",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
@@ -1192,7 +1263,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
||||
commandId: CommandId.make("cmd-turn-interrupt-claude"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
@@ -1207,7 +1278,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
);
|
||||
assert.equal(interruptCalls.length, 1);
|
||||
}),
|
||||
"claudeAgent",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1221,20 +1292,32 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-1",
|
||||
"2026-02-24T10:14:00.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-2",
|
||||
"2026-02-24T10:14:00.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v2\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-3",
|
||||
"2026-02-24T10:14:00.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1252,7 +1335,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
messageId: "msg-user-claude-revert-1",
|
||||
text: "First Claude edit",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
@@ -1267,20 +1350,32 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-4",
|
||||
"2026-02-24T10:14:01.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-5",
|
||||
"2026-02-24T10:14:01.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v3\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-6",
|
||||
"2026-02-24T10:14:01.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1309,7 +1404,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
||||
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
@@ -1331,6 +1426,6 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
||||
}),
|
||||
"claudeAgent",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
);
|
||||
@@ -1,17 +1,23 @@
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
||||
|
||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
NoOpProviderEventLoggers,
|
||||
ProviderEventLoggers,
|
||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../src/provider/Services/ProviderService.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||
@@ -27,6 +33,8 @@ import {
|
||||
codexTurnTextFixture,
|
||||
} from "./fixtures/providerRuntime.ts";
|
||||
|
||||
const codexInstanceId = ProviderInstanceId.make("codex");
|
||||
|
||||
const makeWorkspaceDirectory = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
@@ -45,13 +53,9 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const cwd = yield* makeWorkspaceDirectory;
|
||||
const harness = yield* makeTestProviderAdapterHarness();
|
||||
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(harness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
const registry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: harness.adapter,
|
||||
});
|
||||
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
@@ -60,7 +64,9 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
AnalyticsService.layerTest,
|
||||
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
@@ -83,6 +89,7 @@ const collectEventsDuring = <A, E, R>(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* action;
|
||||
|
||||
return yield* Effect.forEach(
|
||||
@@ -101,7 +108,6 @@ const runTurn = (input: {
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||
|
||||
return yield* collectEventsDuring(
|
||||
input.provider.streamEvents,
|
||||
input.response.events.length,
|
||||
@@ -113,21 +119,19 @@ const runTurn = (input: {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("replays typed runtime fixture events", () =>
|
||||
it.live("replays typed runtime fixture events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||
threadId: ThreadId.make("thread-integration-typed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
@@ -142,11 +146,15 @@ it.effect("replays typed runtime fixture events", () =>
|
||||
observedEvents.map((event) => event.type),
|
||||
codexTurnTextFixture.map((event) => event.type),
|
||||
);
|
||||
assert.deepEqual(
|
||||
observedEvents.map((event) => event.providerInstanceId),
|
||||
codexTurnTextFixture.map(() => codexInstanceId),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("replays file-changing fixture turn events", () =>
|
||||
it.live("replays file-changing fixture turn events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -154,15 +162,13 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||
threadId: ThreadId.make("thread-integration-tools"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
@@ -185,7 +191,7 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("runs multi-turn tool/approval flow", () =>
|
||||
it.live("runs multi-turn tool/approval flow", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -193,15 +199,13 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||
threadId: ThreadId.make("thread-integration-multi"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
@@ -239,7 +243,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("rolls back provider conversation state only", () =>
|
||||
it.live("rolls back provider conversation state only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
@@ -247,15 +251,13 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||
threadId: ThreadId.make("thread-integration-rollback"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
yield* runTurn({
|
||||
|
||||
+15
-11
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.14",
|
||||
"version": "0.0.22",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -8,39 +8,43 @@
|
||||
"directory": "apps/server"
|
||||
},
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
"t3": "./dist/bin.mjs"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun run src/index.ts",
|
||||
"dev": "node --watch src/bin.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"start": "node dist/index.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"build:bundle": "tsdown",
|
||||
"start": "node dist/bin.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
"open": "^10.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/ws": "^8.5.13",
|
||||
"effect-acp": "workspace:*",
|
||||
"effect-codex-app-server": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
#!/usr/bin/env bun
|
||||
import { appendFileSync } from "node:fs";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
|
||||
import * as EffectAcpAgent from "effect-acp/agent";
|
||||
import * as AcpError from "effect-acp/errors";
|
||||
import type * as AcpSchema from "effect-acp/schema";
|
||||
|
||||
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
|
||||
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
|
||||
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
|
||||
const emitInterleavedAssistantToolCalls =
|
||||
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
let currentModeId = "ask";
|
||||
let currentModelId = "default";
|
||||
let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function logExit(reason: string): void {
|
||||
if (!exitLogPath) {
|
||||
return;
|
||||
}
|
||||
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
logExit("SIGINT");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("exit", (code) => {
|
||||
logExit(`exit:${code}`);
|
||||
});
|
||||
|
||||
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
if (parameterizedModelPicker) {
|
||||
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: currentModeId,
|
||||
options: availableModes.map((mode) => ({
|
||||
value: mode.id,
|
||||
name: mode.name,
|
||||
...(mode.description ? { description: mode.description } : {}),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ value: "claude-opus-4-6", name: "Opus 4.6" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
switch (currentModelId) {
|
||||
case "gpt-5.4":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "none", name: "None" },
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
{ value: "extra-high", name: "Extra High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "context",
|
||||
name: "Context",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: currentContext,
|
||||
options: [
|
||||
{ value: "272k", name: "272K" },
|
||||
{ value: "1m", name: "1M" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "composer-2":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "claude-opus-4-6":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
category: "model_config",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
},
|
||||
];
|
||||
default:
|
||||
return baseOptions;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select" as const,
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "composer-2[fast=true]", name: "Composer 2 Fast" },
|
||||
{ value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
|
||||
{
|
||||
id: "ask",
|
||||
name: "Ask",
|
||||
description: "Request permission before making any changes",
|
||||
},
|
||||
{
|
||||
id: "architect",
|
||||
name: "Architect",
|
||||
description: "Design and plan software systems without implementation",
|
||||
},
|
||||
{
|
||||
id: "code",
|
||||
name: "Code",
|
||||
description: "Write and modify code with full tool access",
|
||||
},
|
||||
];
|
||||
|
||||
function modeState(): AcpSchema.SessionModeState {
|
||||
return {
|
||||
currentModeId,
|
||||
availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const agent = yield* EffectAcpAgent.AcpAgent;
|
||||
|
||||
yield* agent.handleInitialize((request) =>
|
||||
Effect.sync(() => {
|
||||
parameterizedModelPicker =
|
||||
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
|
||||
return {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleAuthenticate(() => Effect.succeed({}));
|
||||
|
||||
yield* agent.handleCreateSession(() =>
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleLoadSession((request) =>
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionConfigOption((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (exitOnSetConfigOption) {
|
||||
return yield* Effect.sync(() => {
|
||||
process.exit(7);
|
||||
});
|
||||
}
|
||||
if (failSetConfigOption) {
|
||||
return yield* AcpError.AcpRequestError.invalidParams(
|
||||
"Mock invalid params for session/set_config_option",
|
||||
{
|
||||
method: "session/set_config_option",
|
||||
params: request,
|
||||
},
|
||||
);
|
||||
}
|
||||
if (request.configId === "mode" && typeof request.value === "string") {
|
||||
currentModeId = request.value;
|
||||
}
|
||||
if (request.configId === "model" && typeof request.value === "string") {
|
||||
currentModelId = request.value;
|
||||
}
|
||||
if (request.configId === "reasoning" && typeof request.value === "string") {
|
||||
currentReasoning = request.value;
|
||||
}
|
||||
if (request.configId === "context" && typeof request.value === "string") {
|
||||
currentContext = request.value;
|
||||
}
|
||||
if (request.configId === "fast") {
|
||||
currentFast = request.value === true || request.value === "true";
|
||||
}
|
||||
return {
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "before tool" },
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["echo", "hello"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: "hello",
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "after tool" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["cat", "server/package.json"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
const permission = yield* agent.client.requestPermission({
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId,
|
||||
title: "`cat server/package.json`",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Not in allowlist: cat server/package.json",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
|
||||
const cancelled =
|
||||
cancelledSessions.delete(requestedSessionId) ||
|
||||
permission.outcome.outcome === "cancelled";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: cancelled ? "cancelled" : "end_turn" };
|
||||
}
|
||||
|
||||
if (emitGenericToolPlaceholders) {
|
||||
const toolCallId = "tool-call-generic-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Read File",
|
||||
kind: "read",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
content: "package.json\n",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitAskQuestion) {
|
||||
yield* agent.client.extRequest("cursor/ask_question", {
|
||||
toolCallId: "ask-question-tool-call-1",
|
||||
title: "Question",
|
||||
questions: [
|
||||
{
|
||||
id: "scope",
|
||||
prompt: "Which scope?",
|
||||
options: [
|
||||
{ id: "workspace", label: "Workspace" },
|
||||
{ id: "session", label: "Session" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect mock ACP state",
|
||||
priority: "high",
|
||||
status: "completed",
|
||||
},
|
||||
{
|
||||
content: "Implement the requested change",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: promptResponseText ?? "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleUnknownExtRequest((method, params) => {
|
||||
if (method !== "session/mode/set") {
|
||||
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
}
|
||||
|
||||
const nextModeId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"modeId" in params &&
|
||||
typeof params.modeId === "string"
|
||||
? params.modeId
|
||||
: typeof params === "object" &&
|
||||
params !== null &&
|
||||
"mode" in params &&
|
||||
typeof params.mode === "string"
|
||||
? params.mode
|
||||
: undefined;
|
||||
const requestedSessionId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"sessionId" in params &&
|
||||
typeof params.sessionId === "string"
|
||||
? params.sessionId
|
||||
: sessionId;
|
||||
|
||||
if (typeof nextModeId === "string" && nextModeId.trim()) {
|
||||
currentModeId = nextModeId.trim();
|
||||
return agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
},
|
||||
})
|
||||
.pipe(Effect.as({}));
|
||||
}
|
||||
|
||||
return Effect.succeed({});
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EffectAcpAgent.layerStdio(
|
||||
requestLogPath
|
||||
? {
|
||||
logIncoming: true,
|
||||
logger: (event) => {
|
||||
if (event.direction !== "incoming" || event.stage !== "raw") {
|
||||
return Effect.void;
|
||||
}
|
||||
if (typeof event.payload !== "string") {
|
||||
return Effect.void;
|
||||
}
|
||||
const payload = event.payload;
|
||||
return Effect.sync(() => {
|
||||
appendFileSync(
|
||||
requestLogPath,
|
||||
payload.endsWith("\n") ? payload : `${payload}\n`,
|
||||
"utf8",
|
||||
);
|
||||
});
|
||||
},
|
||||
}
|
||||
: {},
|
||||
),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
NodeRuntime.runMain(program);
|
||||
+33
-16
@@ -14,6 +14,22 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
interface PackageJson {
|
||||
name: string;
|
||||
repository: {
|
||||
type: string;
|
||||
url: string;
|
||||
directory: string;
|
||||
};
|
||||
bin: Record<string, string>;
|
||||
type: string;
|
||||
version: string;
|
||||
engines: Record<string, string>;
|
||||
files: string[];
|
||||
dependencies: Record<string, string>;
|
||||
overrides: Record<string, string>;
|
||||
}
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
@@ -131,13 +147,13 @@ const buildCmd = Command.make(
|
||||
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
|
||||
// Windows needs shell mode to resolve `.cmd` shims on PATH.
|
||||
shell: process.platform === "win32",
|
||||
})`bun tsdown`,
|
||||
}),
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
@@ -177,7 +193,7 @@ const publishCmd = Command.make(
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new CliError({
|
||||
@@ -187,12 +203,10 @@ const publishCmd = Command.make(
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
// Resolve catalog dependencies before any file mutations. If this throws,
|
||||
// acquire fails and no release hook runs, so filesystem must still be untouched.
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg = {
|
||||
const pkg: PackageJson = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
@@ -200,19 +214,22 @@ const publishCmd = Command.make(
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||
dependencies: resolveCatalogDependencies(
|
||||
serverPackageJson.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server",
|
||||
),
|
||||
overrides: resolveCatalogDependencies(
|
||||
rootPackageJson.overrides,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server",
|
||||
),
|
||||
};
|
||||
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
yield* Effect.log("[cli] Resolved package.json for publish");
|
||||
yield* Effect.log("[cli] Prepared package.json for publish");
|
||||
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import process from "node:process";
|
||||
import readline from "node:readline";
|
||||
|
||||
type JsonPrimitive = null | boolean | number | string;
|
||||
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
|
||||
|
||||
type JsonRpcId = number | string;
|
||||
|
||||
type JsonRpcMessage = {
|
||||
jsonrpc?: string;
|
||||
id?: JsonRpcId;
|
||||
method?: string;
|
||||
params?: JsonValue;
|
||||
result?: JsonValue;
|
||||
error?: JsonValue;
|
||||
headers?: JsonValue;
|
||||
};
|
||||
|
||||
type SelectLeafOption = {
|
||||
value: string;
|
||||
label?: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
type SelectGroupOption = {
|
||||
label?: string;
|
||||
name?: string;
|
||||
options: SelectLeafOption[];
|
||||
};
|
||||
|
||||
type SessionConfigOption = {
|
||||
id: string;
|
||||
name?: string;
|
||||
category?: string;
|
||||
type?: string;
|
||||
options?: Array<SelectLeafOption | SelectGroupOption>;
|
||||
};
|
||||
|
||||
type SessionNewResult = {
|
||||
sessionId: string;
|
||||
configOptions?: SessionConfigOption[];
|
||||
};
|
||||
|
||||
type SetConfigResult = {
|
||||
configOptions?: SessionConfigOption[];
|
||||
};
|
||||
|
||||
type PendingRequest = {
|
||||
method: string;
|
||||
resolve: (value: JsonValue | undefined) => void;
|
||||
reject: (error: Error) => void;
|
||||
};
|
||||
|
||||
const targetCwd = process.argv[2] ?? process.cwd();
|
||||
const targetModel = process.argv[3] ?? "gpt-5.4";
|
||||
const promptText = process.argv[4] ?? "helo";
|
||||
const targetReasoning = process.env.CURSOR_REASONING ?? "";
|
||||
const targetContext = process.env.CURSOR_CONTEXT ?? "";
|
||||
const targetFast = process.env.CURSOR_FAST ?? "";
|
||||
const agentBin = process.env.CURSOR_AGENT_BIN ?? "agent";
|
||||
const promptWaitMs = Number(process.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
|
||||
const requestTimeoutMs = Number(process.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
|
||||
|
||||
function logSection(title: string, value: unknown) {
|
||||
process.stdout.write(`\n=== ${title} ===\n`);
|
||||
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
||||
}
|
||||
|
||||
function fail(message: string): never {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
function asString(value: JsonValue | undefined): string | null {
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function flattenSelectValues(option: SessionConfigOption | undefined): string[] {
|
||||
if (!option || option.type !== "select" || !Array.isArray(option.options)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const values: string[] = [];
|
||||
for (const entry of option.options) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
continue;
|
||||
}
|
||||
if ("value" in entry && typeof entry.value === "string") {
|
||||
values.push(entry.value);
|
||||
continue;
|
||||
}
|
||||
if ("options" in entry && Array.isArray(entry.options)) {
|
||||
for (const nested of entry.options) {
|
||||
if (nested && typeof nested === "object" && typeof nested.value === "string") {
|
||||
values.push(nested.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function findConfigOption(
|
||||
configOptions: SessionConfigOption[],
|
||||
predicate: (option: SessionConfigOption) => boolean,
|
||||
): SessionConfigOption | undefined {
|
||||
return configOptions.find(predicate);
|
||||
}
|
||||
|
||||
function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
|
||||
const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();
|
||||
return haystack.includes(keyword.toLowerCase());
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
class JsonRpcChild {
|
||||
readonly child: ChildProcessWithoutNullStreams;
|
||||
readonly pending = new Map<JsonRpcId, PendingRequest>();
|
||||
nextId = 1;
|
||||
closed = false;
|
||||
|
||||
constructor(bin: string, args: string[], cwd: string) {
|
||||
this.child = spawn(bin, args, {
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
this.child.on("exit", (code, signal) => {
|
||||
this.closed = true;
|
||||
const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.reject(new Error(`${detail} while waiting for ${pending.method}`));
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
|
||||
this.child.on("error", (error) => {
|
||||
this.closed = true;
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.reject(error);
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
|
||||
const stdout = readline.createInterface({ input: this.child.stdout });
|
||||
stdout.on("line", (line) => {
|
||||
void this.handleStdoutLine(line);
|
||||
});
|
||||
|
||||
const stderr = readline.createInterface({ input: this.child.stderr });
|
||||
stderr.on("line", (line) => {
|
||||
process.stdout.write(`[stderr] ${line}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
write(message: JsonRpcMessage) {
|
||||
if (this.closed) {
|
||||
fail("ACP process is already closed.");
|
||||
}
|
||||
const payload = JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
headers: [],
|
||||
...message,
|
||||
});
|
||||
process.stdout.write(`>>> ${payload}\n`);
|
||||
this.child.stdin.write(`${payload}\n`);
|
||||
}
|
||||
|
||||
async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {
|
||||
const id = this.nextId++;
|
||||
|
||||
const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
|
||||
}, timeoutMs);
|
||||
|
||||
this.pending.set(id, {
|
||||
method,
|
||||
resolve: (value) => {
|
||||
clearTimeout(timeout);
|
||||
resolve(value);
|
||||
},
|
||||
reject: (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
this.write({
|
||||
id,
|
||||
method,
|
||||
params,
|
||||
});
|
||||
|
||||
return responsePromise;
|
||||
}
|
||||
|
||||
notify(method: string, params: JsonValue) {
|
||||
this.write({
|
||||
method,
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
respond(id: JsonRpcId, result: JsonValue) {
|
||||
this.write({
|
||||
id,
|
||||
result,
|
||||
});
|
||||
}
|
||||
|
||||
respondError(id: JsonRpcId, code: number, message: string) {
|
||||
this.write({
|
||||
id,
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async handleStdoutLine(line: string) {
|
||||
if (line.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.stdout.write(`<<< ${line}\n`);
|
||||
|
||||
let message: JsonRpcMessage;
|
||||
try {
|
||||
message = JSON.parse(line) as JsonRpcMessage;
|
||||
} catch (error) {
|
||||
process.stdout.write(`[parse-error] ${(error as Error).message}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.id !== "undefined" && !message.method) {
|
||||
const pending = this.pending.get(message.id);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
this.pending.delete(message.id);
|
||||
if (typeof message.error !== "undefined") {
|
||||
pending.reject(
|
||||
new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.resolve(message.result);
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.method === "session/request_permission" && typeof message.id !== "undefined") {
|
||||
this.respond(message.id, {
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "allow",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.id !== "undefined" && message.id !== "") {
|
||||
this.respondError(
|
||||
message.id,
|
||||
-32601,
|
||||
`Unhandled server request: ${message.method ?? "unknown"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
this.child.kill("SIGTERM");
|
||||
await sleep(250);
|
||||
if (!this.closed) {
|
||||
this.child.kill("SIGKILL");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function setSelectOptionIfAdvertised(
|
||||
rpc: JsonRpcChild,
|
||||
sessionId: string,
|
||||
configOptions: SessionConfigOption[],
|
||||
predicate: (option: SessionConfigOption) => boolean,
|
||||
value: string,
|
||||
label: string,
|
||||
) {
|
||||
if (value.length === 0) {
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
const option = findConfigOption(configOptions, predicate);
|
||||
const values = flattenSelectValues(option);
|
||||
if (!option || !values.includes(value)) {
|
||||
logSection(`SKIP_${label}`, {
|
||||
requestedValue: value,
|
||||
availableValues: values,
|
||||
});
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
const response = (await rpc.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: option.id,
|
||||
value,
|
||||
})) as SetConfigResult | null | undefined;
|
||||
|
||||
logSection(`SET_${label}_RESPONSE`, response);
|
||||
return response?.configOptions ?? configOptions;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);
|
||||
|
||||
try {
|
||||
const initializeResponse = await rpc.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
},
|
||||
clientInfo: {
|
||||
name: "cursor-acp-model-mismatch-probe",
|
||||
version: "0.0.0",
|
||||
},
|
||||
});
|
||||
logSection("INITIALIZE_RESPONSE", initializeResponse);
|
||||
|
||||
const authenticateResponse = await rpc.request("authenticate", {
|
||||
methodId: "cursor_login",
|
||||
});
|
||||
logSection("AUTHENTICATE_RESPONSE", authenticateResponse);
|
||||
|
||||
const sessionResponse = (await rpc.request("session/new", {
|
||||
cwd: targetCwd,
|
||||
mcpServers: [],
|
||||
})) as SessionNewResult;
|
||||
logSection("SESSION_NEW_RESPONSE", sessionResponse);
|
||||
|
||||
const sessionId = asString(sessionResponse.sessionId);
|
||||
if (!sessionId) {
|
||||
fail("session/new did not return a sessionId.");
|
||||
}
|
||||
|
||||
let configOptions = sessionResponse.configOptions ?? [];
|
||||
const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");
|
||||
const advertisedModels = flattenSelectValues(modelConfig);
|
||||
logSection("ADVERTISED_MODEL_VALUES", advertisedModels);
|
||||
|
||||
if (!modelConfig || modelConfig.type !== "select") {
|
||||
fail("Cursor ACP did not expose a select-type model config option.");
|
||||
}
|
||||
|
||||
if (!advertisedModels.includes(targetModel)) {
|
||||
fail(
|
||||
`Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
const setModelResponse = (await rpc.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: modelConfig.id,
|
||||
value: targetModel,
|
||||
})) as SetConfigResult | null | undefined;
|
||||
logSection("SET_MODEL_RESPONSE", setModelResponse);
|
||||
|
||||
configOptions = setModelResponse?.configOptions ?? configOptions;
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "thought_level",
|
||||
targetReasoning,
|
||||
"REASONING",
|
||||
);
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "model_config" && matchesKeyword(option, "context"),
|
||||
targetContext,
|
||||
"CONTEXT",
|
||||
);
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "model_config" && matchesKeyword(option, "fast"),
|
||||
targetFast,
|
||||
"FAST",
|
||||
);
|
||||
|
||||
const promptResponse = await rpc.request("session/prompt", {
|
||||
sessionId,
|
||||
prompt: [
|
||||
{
|
||||
type: "text",
|
||||
text: promptText,
|
||||
},
|
||||
],
|
||||
});
|
||||
logSection("PROMPT_RESPONSE", promptResponse);
|
||||
|
||||
await sleep(promptWaitMs);
|
||||
rpc.notify("session/cancel", { sessionId });
|
||||
} finally {
|
||||
await rpc.close();
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
process.stderr.write(
|
||||
`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Effect, FileSystem, Path } from "effect";
|
||||
import * as Random from "effect/Random";
|
||||
|
||||
export const writeFileStringAtomically = (input: {
|
||||
readonly filePath: string;
|
||||
readonly contents: string;
|
||||
}) =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempFileId = yield* Random.nextUUIDv4;
|
||||
const targetDirectory = path.dirname(input.filePath);
|
||||
|
||||
yield* fs.makeDirectory(targetDirectory, { recursive: true });
|
||||
const tempDirectory = yield* fs.makeTempDirectoryScoped({
|
||||
directory: targetDirectory,
|
||||
prefix: `${path.basename(input.filePath)}.`,
|
||||
});
|
||||
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
|
||||
|
||||
yield* fs.writeFileString(tempPath, input.contents);
|
||||
yield* fs.rename(tempPath, input.filePath);
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,111 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
|
||||
import { makeAuthControlPlane } from "./AuthControlPlane.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
|
||||
const makeServerConfigLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })),
|
||||
);
|
||||
|
||||
const makeAuthControlPlaneLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
Layer.effect(AuthControlPlane, makeAuthControlPlane).pipe(
|
||||
Layer.provideMerge(BootstrapCredentialServiceLive),
|
||||
Layer.provideMerge(SessionCredentialServiceLive),
|
||||
Layer.provideMerge(ServerSecretStoreLive),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
Layer.provide(makeServerConfigLayer(overrides)),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("AuthControlPlane", (it) => {
|
||||
it.effect("creates, lists, and revokes client pairing links", () =>
|
||||
Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
|
||||
const created = yield* authControlPlane.createPairingLink({
|
||||
role: "client",
|
||||
subject: "one-time-token",
|
||||
label: "CI phone",
|
||||
});
|
||||
const listedBeforeRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
|
||||
const revoked = yield* authControlPlane.revokePairingLink(created.id);
|
||||
const listedAfterRevoke = yield* authControlPlane.listPairingLinks({ role: "client" });
|
||||
|
||||
expect(created.role).toBe("client");
|
||||
expect(created.credential.length).toBeGreaterThan(0);
|
||||
expect(listedBeforeRevoke).toHaveLength(1);
|
||||
expect(listedBeforeRevoke[0]?.id).toBe(created.id);
|
||||
expect(listedBeforeRevoke[0]?.label).toBe("CI phone");
|
||||
expect(listedBeforeRevoke[0]?.credential).toBe(created.credential);
|
||||
expect(revoked).toBe(true);
|
||||
expect(listedAfterRevoke).toHaveLength(0);
|
||||
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
|
||||
);
|
||||
|
||||
it.effect("issues bearer sessions and lists them without exposing raw tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
const sessionCredentials = yield* SessionCredentialService;
|
||||
|
||||
const issued = yield* authControlPlane.issueSession({
|
||||
label: "deploy-bot",
|
||||
});
|
||||
const verified = yield* sessionCredentials.verify(issued.token);
|
||||
const listedBeforeRevoke = yield* authControlPlane.listSessions();
|
||||
const revoked = yield* authControlPlane.revokeSession(issued.sessionId);
|
||||
const listedAfterRevoke = yield* authControlPlane.listSessions();
|
||||
|
||||
expect(issued.method).toBe("bearer-session-token");
|
||||
expect(issued.role).toBe("owner");
|
||||
expect(issued.client.deviceType).toBe("bot");
|
||||
expect(issued.client.label).toBe("deploy-bot");
|
||||
expect(verified.sessionId).toBe(issued.sessionId);
|
||||
expect(verified.role).toBe("owner");
|
||||
expect(verified.method).toBe("bearer-session-token");
|
||||
expect(listedBeforeRevoke).toHaveLength(1);
|
||||
expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);
|
||||
expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false);
|
||||
expect(revoked).toBe(true);
|
||||
expect(listedAfterRevoke).toHaveLength(0);
|
||||
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
|
||||
);
|
||||
|
||||
it.effect("surfaces lastConnectedAt through the listed session view", () =>
|
||||
Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
const sessionCredentials = yield* SessionCredentialService;
|
||||
|
||||
const issued = yield* authControlPlane.issueSession({
|
||||
label: "remote-ipad",
|
||||
});
|
||||
const beforeConnect = yield* authControlPlane.listSessions();
|
||||
yield* sessionCredentials.markConnected(issued.sessionId);
|
||||
const afterConnect = yield* authControlPlane.listSessions();
|
||||
|
||||
expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
|
||||
expect(afterConnect[0]?.lastConnectedAt).not.toBeNull();
|
||||
}).pipe(Effect.provide(makeAuthControlPlaneLayer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Layer } from "effect";
|
||||
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts";
|
||||
import {
|
||||
AuthControlPlane,
|
||||
AuthControlPlaneError,
|
||||
DEFAULT_SESSION_SUBJECT,
|
||||
} from "../Services/AuthControlPlane.ts";
|
||||
import type {
|
||||
AuthControlPlaneShape,
|
||||
IssuedBearerSession,
|
||||
IssuedPairingLink,
|
||||
} from "../Services/AuthControlPlane.ts";
|
||||
|
||||
const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
|
||||
if (left.role !== right.role) {
|
||||
return left.role === "owner" ? -1 : 1;
|
||||
}
|
||||
if (left.connected !== right.connected) {
|
||||
return left.connected ? -1 : 1;
|
||||
}
|
||||
return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
|
||||
};
|
||||
|
||||
const toAuthControlPlaneError =
|
||||
(message: string) =>
|
||||
(cause: unknown): AuthControlPlaneError =>
|
||||
new AuthControlPlaneError({
|
||||
message,
|
||||
cause,
|
||||
});
|
||||
|
||||
export const makeAuthControlPlane = Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
|
||||
const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = yield* DateTime.now;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
});
|
||||
return {
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
createdAt: DateTime.toUtc(createdAt),
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedPairingLink;
|
||||
}).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link.")));
|
||||
|
||||
const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
|
||||
bootstrapCredentials.listActive().pipe(
|
||||
Effect.map((pairingLinks) =>
|
||||
pairingLinks
|
||||
.filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
|
||||
.filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
|
||||
.map((pairingLink) =>
|
||||
pairingLink.label
|
||||
? ({
|
||||
id: pairingLink.id,
|
||||
credential: pairingLink.credential,
|
||||
role: pairingLink.role,
|
||||
subject: pairingLink.subject,
|
||||
label: pairingLink.label,
|
||||
createdAt: pairingLink.createdAt,
|
||||
expiresAt: pairingLink.expiresAt,
|
||||
} satisfies AuthPairingLink)
|
||||
: ({
|
||||
id: pairingLink.id,
|
||||
credential: pairingLink.credential,
|
||||
role: pairingLink.role,
|
||||
subject: pairingLink.subject,
|
||||
createdAt: pairingLink.createdAt,
|
||||
expiresAt: pairingLink.expiresAt,
|
||||
} satisfies AuthPairingLink),
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
|
||||
),
|
||||
),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
|
||||
);
|
||||
|
||||
const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) =>
|
||||
bootstrapCredentials
|
||||
.revoke(id)
|
||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link.")));
|
||||
|
||||
const issueSession: AuthControlPlaneShape["issueSession"] = (input) =>
|
||||
sessions
|
||||
.issue({
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
method: "bearer-session-token",
|
||||
role: input?.role ?? "owner",
|
||||
client: {
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
deviceType: "bot",
|
||||
},
|
||||
...(input?.ttl ? { ttl: input.ttl } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((issued) => {
|
||||
if (issued.method !== "bearer-session-token") {
|
||||
return Effect.fail(
|
||||
new AuthControlPlaneError({
|
||||
message: "CLI session issuance produced an unexpected session method.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed({
|
||||
sessionId: issued.sessionId,
|
||||
token: issued.token,
|
||||
method: "bearer-session-token" as const,
|
||||
role: issued.role,
|
||||
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
|
||||
client: issued.client,
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
} satisfies IssuedBearerSession);
|
||||
}),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")),
|
||||
);
|
||||
|
||||
const listSessions: AuthControlPlaneShape["listSessions"] = () =>
|
||||
sessions.listActive().pipe(
|
||||
Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")),
|
||||
);
|
||||
|
||||
const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) =>
|
||||
sessions
|
||||
.revoke(sessionId)
|
||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session.")));
|
||||
|
||||
const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = (
|
||||
sessionId,
|
||||
) =>
|
||||
sessions
|
||||
.revokeAllExcept(sessionId)
|
||||
.pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions.")));
|
||||
|
||||
return {
|
||||
createPairingLink,
|
||||
listPairingLinks,
|
||||
revokePairingLink,
|
||||
issueSession,
|
||||
listSessions,
|
||||
revokeSession,
|
||||
revokeOtherSessionsExcept,
|
||||
} satisfies AuthControlPlaneShape;
|
||||
});
|
||||
|
||||
export const AuthCoreLive = Layer.mergeAll(
|
||||
BootstrapCredentialServiceLive,
|
||||
SessionCredentialServiceLive,
|
||||
);
|
||||
|
||||
export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive);
|
||||
|
||||
export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive));
|
||||
|
||||
export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane);
|
||||
|
||||
export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe(
|
||||
Layer.provideMerge(AuthRuntimeLive),
|
||||
);
|
||||
@@ -0,0 +1,151 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Duration, Effect, Layer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
|
||||
const makeServerConfigLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })),
|
||||
);
|
||||
|
||||
const makeBootstrapCredentialLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
BootstrapCredentialServiceLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(makeServerConfigLayer(overrides)),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => {
|
||||
it.effect("issues pairing tokens in a short manual-entry format", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken();
|
||||
|
||||
expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/);
|
||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
||||
);
|
||||
|
||||
it.effect("issues one-time bootstrap tokens that can only be consumed once", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" });
|
||||
const first = yield* bootstrapCredentials.consume(issued.credential);
|
||||
const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential));
|
||||
|
||||
expect(first.method).toBe("one-time-token");
|
||||
expect(first.role).toBe("client");
|
||||
expect(first.subject).toBe("one-time-token");
|
||||
expect(first.label).toBe("Julius iPhone");
|
||||
expect(issued.label).toBe("Julius iPhone");
|
||||
expect(second._tag).toBe("BootstrapCredentialError");
|
||||
expect(second.message).toContain("Unknown bootstrap credential");
|
||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
||||
);
|
||||
|
||||
it.effect("atomically consumes a one-time token when multiple requests race", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const token = yield* bootstrapCredentials.issueOneTimeToken();
|
||||
const results = yield* Effect.all(
|
||||
Array.from({ length: 8 }, () =>
|
||||
Effect.result(bootstrapCredentials.consume(token.credential)),
|
||||
),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
|
||||
const successes = results.filter((result) => result._tag === "Success");
|
||||
const failures = results.filter((result) => result._tag === "Failure");
|
||||
|
||||
expect(successes).toHaveLength(1);
|
||||
expect(failures).toHaveLength(7);
|
||||
for (const failure of failures) {
|
||||
expect(failure.failure._tag).toBe("BootstrapCredentialError");
|
||||
expect(failure.failure.message).toContain("Unknown bootstrap credential");
|
||||
}
|
||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
||||
);
|
||||
|
||||
it.effect("seeds the desktop bootstrap credential as a one-time grant", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
|
||||
const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
|
||||
|
||||
expect(first.method).toBe("desktop-bootstrap");
|
||||
expect(first.role).toBe("owner");
|
||||
expect(first.subject).toBe("desktop-bootstrap");
|
||||
expect(second._tag).toBe("BootstrapCredentialError");
|
||||
expect(second.status).toBe(401);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeBootstrapCredentialLayer({
|
||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
|
||||
yield* TestClock.adjust(Duration.minutes(6));
|
||||
const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token"));
|
||||
|
||||
expect(expired._tag).toBe("BootstrapCredentialError");
|
||||
expect(expired.status).toBe(401);
|
||||
expect(expired.message).toContain("Bootstrap credential expired");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.merge(
|
||||
makeBootstrapCredentialLayer({
|
||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
TestClock.layer(),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("lists and revokes active pairing links", () =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const first = yield* bootstrapCredentials.issueOneTimeToken();
|
||||
const second = yield* bootstrapCredentials.issueOneTimeToken({ role: "owner" });
|
||||
|
||||
const activeBeforeRevoke = yield* bootstrapCredentials.listActive();
|
||||
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id);
|
||||
expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id);
|
||||
|
||||
const revoked = yield* bootstrapCredentials.revoke(first.id);
|
||||
const activeAfterRevoke = yield* bootstrapCredentials.listActive();
|
||||
const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential));
|
||||
|
||||
expect(revoked).toBe(true);
|
||||
expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id);
|
||||
expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id);
|
||||
expect(revokedConsume.message).toContain("no longer available");
|
||||
expect(revokedConsume.status).toBe(401);
|
||||
}).pipe(Effect.provide(makeBootstrapCredentialLayer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,296 @@
|
||||
import type { AuthPairingLink } from "@t3tools/contracts";
|
||||
import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
|
||||
import { Option } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
|
||||
import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";
|
||||
import {
|
||||
BootstrapCredentialError,
|
||||
BootstrapCredentialService,
|
||||
type BootstrapCredentialChange,
|
||||
type BootstrapCredentialServiceShape,
|
||||
type BootstrapGrant,
|
||||
type IssuedBootstrapCredential,
|
||||
} from "../Services/BootstrapCredentialService.ts";
|
||||
|
||||
interface StoredBootstrapGrant extends BootstrapGrant {
|
||||
readonly remainingUses: number | "unbounded";
|
||||
}
|
||||
|
||||
type ConsumeResult =
|
||||
| {
|
||||
readonly _tag: "error";
|
||||
readonly reason: "not-found" | "expired";
|
||||
readonly error: BootstrapCredentialError;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "success";
|
||||
readonly grant: BootstrapGrant;
|
||||
};
|
||||
|
||||
const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
|
||||
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
|
||||
const PAIRING_TOKEN_LENGTH = 12;
|
||||
|
||||
const generatePairingToken = (): string => {
|
||||
const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH));
|
||||
|
||||
return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join("");
|
||||
};
|
||||
|
||||
export const makeBootstrapCredentialService = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const pairingLinks = yield* AuthPairingLinkRepository;
|
||||
const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
|
||||
const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
|
||||
|
||||
const invalidBootstrapCredentialError = (message: string) =>
|
||||
new BootstrapCredentialError({
|
||||
message,
|
||||
status: 401,
|
||||
});
|
||||
|
||||
const internalBootstrapCredentialError = (message: string, cause: unknown) =>
|
||||
new BootstrapCredentialError({
|
||||
message,
|
||||
status: 500,
|
||||
cause,
|
||||
});
|
||||
|
||||
const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
|
||||
Ref.update(seededGrantsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
next.set(credential, grant);
|
||||
return next;
|
||||
});
|
||||
|
||||
const emitUpsert = (pairingLink: AuthPairingLink) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "pairingLinkUpserted",
|
||||
pairingLink,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const emitRemoved = (id: string) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "pairingLinkRemoved",
|
||||
id,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
if (config.desktopBootstrapToken) {
|
||||
const now = yield* DateTime.now;
|
||||
yield* seedGrant(config.desktopBootstrapToken, {
|
||||
method: "desktop-bootstrap",
|
||||
role: "owner",
|
||||
subject: "desktop-bootstrap",
|
||||
expiresAt: DateTime.add(now, {
|
||||
milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
|
||||
}),
|
||||
remainingUses: 1,
|
||||
});
|
||||
}
|
||||
|
||||
const toBootstrapCredentialError = (message: string) => (cause: unknown) =>
|
||||
internalBootstrapCredentialError(message, cause);
|
||||
|
||||
const listActive: BootstrapCredentialServiceShape["listActive"] = () =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const rows = yield* pairingLinks.listActive({ now });
|
||||
|
||||
return rows.map((row) =>
|
||||
row.label
|
||||
? ({
|
||||
id: row.id,
|
||||
credential: row.credential,
|
||||
role: row.role,
|
||||
subject: row.subject,
|
||||
label: row.label,
|
||||
createdAt: row.createdAt,
|
||||
expiresAt: row.expiresAt,
|
||||
} satisfies AuthPairingLink)
|
||||
: ({
|
||||
id: row.id,
|
||||
credential: row.credential,
|
||||
role: row.role,
|
||||
subject: row.subject,
|
||||
createdAt: row.createdAt,
|
||||
expiresAt: row.expiresAt,
|
||||
} satisfies AuthPairingLink),
|
||||
);
|
||||
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")));
|
||||
|
||||
const revoke: BootstrapCredentialServiceShape["revoke"] = (id) =>
|
||||
Effect.gen(function* () {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* pairingLinks.revoke({
|
||||
id,
|
||||
revokedAt,
|
||||
});
|
||||
if (revoked) {
|
||||
yield* emitRemoved(id);
|
||||
}
|
||||
return revoked;
|
||||
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")));
|
||||
|
||||
const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const id = crypto.randomUUID();
|
||||
const credential = generatePairingToken();
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
|
||||
const issued: IssuedBootstrapCredential = {
|
||||
id,
|
||||
credential,
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
expiresAt,
|
||||
};
|
||||
yield* pairingLinks.create({
|
||||
id,
|
||||
credential,
|
||||
method: "one-time-token",
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
label: input?.label ?? null,
|
||||
createdAt: now,
|
||||
expiresAt: expiresAt,
|
||||
});
|
||||
yield* emitUpsert({
|
||||
id,
|
||||
credential,
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.subject ?? "one-time-token",
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
createdAt: now,
|
||||
expiresAt,
|
||||
});
|
||||
return issued;
|
||||
}).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")));
|
||||
|
||||
const consume: BootstrapCredentialServiceShape["consume"] = (credential) =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const seededResult: ConsumeResult = yield* Ref.modify(
|
||||
seededGrantsRef,
|
||||
(current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
|
||||
const grant = current.get(credential);
|
||||
if (!grant) {
|
||||
return [
|
||||
{
|
||||
_tag: "error",
|
||||
reason: "not-found",
|
||||
error: invalidBootstrapCredentialError("Unknown bootstrap credential."),
|
||||
},
|
||||
current,
|
||||
];
|
||||
}
|
||||
|
||||
const next = new Map(current);
|
||||
if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
|
||||
next.delete(credential);
|
||||
return [
|
||||
{
|
||||
_tag: "error",
|
||||
reason: "expired",
|
||||
error: invalidBootstrapCredentialError("Bootstrap credential expired."),
|
||||
},
|
||||
next,
|
||||
];
|
||||
}
|
||||
|
||||
const remainingUses = grant.remainingUses;
|
||||
if (typeof remainingUses === "number") {
|
||||
if (remainingUses <= 1) {
|
||||
next.delete(credential);
|
||||
} else {
|
||||
next.set(credential, {
|
||||
...grant,
|
||||
remainingUses: remainingUses - 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
_tag: "success",
|
||||
grant: {
|
||||
method: grant.method,
|
||||
role: grant.role,
|
||||
subject: grant.subject,
|
||||
...(grant.label ? { label: grant.label } : {}),
|
||||
expiresAt: grant.expiresAt,
|
||||
} satisfies BootstrapGrant,
|
||||
},
|
||||
next,
|
||||
];
|
||||
},
|
||||
);
|
||||
|
||||
if (seededResult._tag === "success") {
|
||||
return seededResult.grant;
|
||||
}
|
||||
if (seededResult.reason !== "not-found") {
|
||||
return yield* seededResult.error;
|
||||
}
|
||||
|
||||
const consumed = yield* pairingLinks.consumeAvailable({
|
||||
credential,
|
||||
consumedAt: now,
|
||||
now,
|
||||
});
|
||||
|
||||
if (Option.isSome(consumed)) {
|
||||
yield* emitRemoved(consumed.value.id);
|
||||
return {
|
||||
method: consumed.value.method,
|
||||
role: consumed.value.role,
|
||||
subject: consumed.value.subject,
|
||||
...(consumed.value.label ? { label: consumed.value.label } : {}),
|
||||
expiresAt: consumed.value.expiresAt,
|
||||
} satisfies BootstrapGrant;
|
||||
}
|
||||
|
||||
const matching = yield* pairingLinks.getByCredential({ credential });
|
||||
if (Option.isNone(matching)) {
|
||||
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
|
||||
}
|
||||
|
||||
if (matching.value.revokedAt !== null) {
|
||||
return yield* invalidBootstrapCredentialError(
|
||||
"Bootstrap credential is no longer available.",
|
||||
);
|
||||
}
|
||||
|
||||
if (matching.value.consumedAt !== null) {
|
||||
return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
|
||||
}
|
||||
|
||||
if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
|
||||
return yield* invalidBootstrapCredentialError("Bootstrap credential expired.");
|
||||
}
|
||||
|
||||
return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available.");
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof BootstrapCredentialError
|
||||
? cause
|
||||
: internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
issueOneTimeToken,
|
||||
listActive,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
revoke,
|
||||
consume,
|
||||
} satisfies BootstrapCredentialServiceShape;
|
||||
});
|
||||
|
||||
export const BootstrapCredentialServiceLive = Layer.effect(
|
||||
BootstrapCredentialService,
|
||||
makeBootstrapCredentialService,
|
||||
).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive));
|
||||
@@ -0,0 +1,182 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
|
||||
import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts";
|
||||
import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
|
||||
const makeServerConfigLayer = (overrides?: Partial<ServerConfigShape>) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" })));
|
||||
|
||||
const makeServerAuthLayer = (overrides?: Partial<ServerConfigShape>) =>
|
||||
ServerAuthLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(ServerSecretStoreLive),
|
||||
Layer.provide(makeServerConfigLayer(overrides)),
|
||||
);
|
||||
|
||||
const makeCookieRequest = (
|
||||
sessionToken: string,
|
||||
): Parameters<ServerAuthShape["authenticateHttpRequest"]>[0] =>
|
||||
({
|
||||
cookies: {
|
||||
t3_session: sessionToken,
|
||||
},
|
||||
headers: {},
|
||||
}) as unknown as Parameters<ServerAuthShape["authenticateHttpRequest"]>[0];
|
||||
|
||||
const requestMetadata = {
|
||||
deviceType: "desktop" as const,
|
||||
os: "macOS",
|
||||
browser: "Chrome",
|
||||
ipAddress: "192.168.1.23",
|
||||
};
|
||||
|
||||
it.layer(NodeServices.layer)("ServerAuthLive", (it) => {
|
||||
it.effect("maps invalid bootstrap credential failures to 401", () =>
|
||||
Effect.sync(() => {
|
||||
const error = toBootstrapExchangeAuthError(
|
||||
new BootstrapCredentialError({
|
||||
message: "Unknown bootstrap credential.",
|
||||
status: 401,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error.status).toBe(401);
|
||||
expect(error.message).toBe("Invalid bootstrap credential.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps unexpected bootstrap failures to 500", () =>
|
||||
Effect.sync(() => {
|
||||
const error = toBootstrapExchangeAuthError(
|
||||
new BootstrapCredentialError({
|
||||
message: "Failed to consume bootstrap credential.",
|
||||
status: 500,
|
||||
cause: new Error("sqlite is unavailable"),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error.status).toBe(500);
|
||||
expect(error.message).toBe("Failed to validate bootstrap credential.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("issues client pairing credentials by default", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* ServerAuth;
|
||||
|
||||
const pairingCredential = yield* serverAuth.issuePairingCredential();
|
||||
const exchanged = yield* serverAuth.exchangeBootstrapCredential(
|
||||
pairingCredential.credential,
|
||||
requestMetadata,
|
||||
);
|
||||
const verified = yield* serverAuth.authenticateHttpRequest(
|
||||
makeCookieRequest(exchanged.sessionToken),
|
||||
);
|
||||
|
||||
expect(verified.sessionId.length).toBeGreaterThan(0);
|
||||
expect(verified.role).toBe("client");
|
||||
expect(verified.subject).toBe("one-time-token");
|
||||
}).pipe(Effect.provide(makeServerAuthLayer())),
|
||||
);
|
||||
|
||||
it.effect("issues startup pairing URLs that bootstrap owner sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* ServerAuth;
|
||||
|
||||
const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773");
|
||||
const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token");
|
||||
const listedPairingLinks = yield* serverAuth.listPairingLinks();
|
||||
expect(token).toBeTruthy();
|
||||
expect(
|
||||
listedPairingLinks.some((pairingLink) => pairingLink.subject === "owner-bootstrap"),
|
||||
).toBe(false);
|
||||
|
||||
const exchanged = yield* serverAuth.exchangeBootstrapCredential(token ?? "", requestMetadata);
|
||||
const verified = yield* serverAuth.authenticateHttpRequest(
|
||||
makeCookieRequest(exchanged.sessionToken),
|
||||
);
|
||||
|
||||
expect(verified.role).toBe("owner");
|
||||
expect(verified.subject).toBe("owner-bootstrap");
|
||||
}).pipe(Effect.provide(makeServerAuthLayer())),
|
||||
);
|
||||
|
||||
it.effect("lists pairing links and revokes other client sessions while keeping the owner", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* ServerAuth;
|
||||
|
||||
const ownerExchange = yield* serverAuth.exchangeBootstrapCredential(
|
||||
"desktop-bootstrap-token",
|
||||
requestMetadata,
|
||||
);
|
||||
const ownerSession = yield* serverAuth.authenticateHttpRequest(
|
||||
makeCookieRequest(ownerExchange.sessionToken),
|
||||
);
|
||||
const pairingCredential = yield* serverAuth.issuePairingCredential({
|
||||
label: "Julius iPhone",
|
||||
});
|
||||
const listedPairingLinks = yield* serverAuth.listPairingLinks();
|
||||
const clientExchange = yield* serverAuth.exchangeBootstrapCredential(
|
||||
pairingCredential.credential,
|
||||
{
|
||||
...requestMetadata,
|
||||
deviceType: "mobile",
|
||||
os: "iOS",
|
||||
browser: "Safari",
|
||||
ipAddress: "192.168.1.88",
|
||||
},
|
||||
);
|
||||
const clientSession = yield* serverAuth.authenticateHttpRequest(
|
||||
makeCookieRequest(clientExchange.sessionToken),
|
||||
);
|
||||
const clientsBeforeRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
|
||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(ownerSession.sessionId);
|
||||
const clientsAfterRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId);
|
||||
|
||||
expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id);
|
||||
expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe(
|
||||
"Julius iPhone",
|
||||
);
|
||||
expect(clientsBeforeRevoke).toHaveLength(2);
|
||||
expect(
|
||||
clientsBeforeRevoke.find((entry) => entry.sessionId === ownerSession.sessionId)?.current,
|
||||
).toBe(true);
|
||||
expect(
|
||||
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.current,
|
||||
).toBe(false);
|
||||
expect(
|
||||
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
|
||||
.label,
|
||||
).toBe("Julius iPhone");
|
||||
expect(
|
||||
clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client
|
||||
.deviceType,
|
||||
).toBe("mobile");
|
||||
expect(revokedCount).toBe(1);
|
||||
expect(clientsAfterRevoke).toHaveLength(1);
|
||||
expect(clientsAfterRevoke[0]?.sessionId).toBe(ownerSession.sessionId);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthLayer({
|
||||
desktopBootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,395 @@
|
||||
import {
|
||||
type AuthBearerBootstrapResult,
|
||||
type AuthClientSession,
|
||||
type AuthBootstrapResult,
|
||||
type AuthPairingCredentialResult,
|
||||
type AuthSessionState,
|
||||
type AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Layer, Option } from "effect";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
|
||||
import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
|
||||
import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
|
||||
import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
|
||||
import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
|
||||
import {
|
||||
ServerAuth,
|
||||
type AuthenticatedSession,
|
||||
AuthError,
|
||||
type ServerAuthShape,
|
||||
} from "../Services/ServerAuth.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
|
||||
|
||||
type BootstrapExchangeResult = {
|
||||
readonly response: AuthBootstrapResult;
|
||||
readonly sessionToken: string;
|
||||
};
|
||||
|
||||
const AUTHORIZATION_PREFIX = "Bearer ";
|
||||
const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken";
|
||||
|
||||
export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError {
|
||||
if (cause.status === 500) {
|
||||
return new AuthError({
|
||||
message: "Failed to validate bootstrap credential.",
|
||||
status: 500,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
return new AuthError({
|
||||
message: "Invalid bootstrap credential.",
|
||||
status: 401,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
|
||||
const header = request.headers["authorization"];
|
||||
if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
|
||||
return token.length > 0 ? token : null;
|
||||
}
|
||||
|
||||
export const makeServerAuth = Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const bootstrapCredentials = yield* BootstrapCredentialService;
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause: SessionCredentialError) =>
|
||||
Effect.logWarning("Rejected authenticated session credential.").pipe(
|
||||
Effect.annotateLogs({
|
||||
reason: cause.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
subject: session.subject,
|
||||
method: session.method,
|
||||
role: session.role,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Unauthorized request.",
|
||||
status: 401,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {
|
||||
const cookieToken = request.cookies[sessions.cookieName];
|
||||
const bearerToken = parseBearerToken(request);
|
||||
const credential = cookieToken ?? bearerToken;
|
||||
if (!credential) {
|
||||
return Effect.fail(
|
||||
new AuthError({
|
||||
message: "Authentication required.",
|
||||
status: 401,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return authenticateToken(credential);
|
||||
};
|
||||
|
||||
const getSessionState: ServerAuthShape["getSessionState"] = (request) =>
|
||||
authenticateRequest(request).pipe(
|
||||
Effect.map(
|
||||
(session) =>
|
||||
({
|
||||
authenticated: true,
|
||||
auth: descriptor,
|
||||
role: session.role,
|
||||
sessionMethod: session.method,
|
||||
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
|
||||
}) satisfies AuthSessionState,
|
||||
),
|
||||
Effect.catchTag("AuthError", () =>
|
||||
Effect.succeed({
|
||||
authenticated: false,
|
||||
auth: descriptor,
|
||||
} satisfies AuthSessionState),
|
||||
),
|
||||
);
|
||||
|
||||
const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = (
|
||||
credential,
|
||||
requestMetadata,
|
||||
) =>
|
||||
bootstrapCredentials.consume(credential).pipe(
|
||||
Effect.mapError(toBootstrapExchangeAuthError),
|
||||
Effect.flatMap((grant) =>
|
||||
sessions
|
||||
.issue({
|
||||
method: "browser-session-cookie",
|
||||
subject: grant.subject,
|
||||
role: grant.role,
|
||||
client: {
|
||||
...requestMetadata,
|
||||
...(grant.label ? { label: grant.label } : {}),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue authenticated session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
(session) =>
|
||||
({
|
||||
response: {
|
||||
authenticated: true,
|
||||
role: session.role,
|
||||
sessionMethod: session.method,
|
||||
expiresAt: DateTime.toUtc(session.expiresAt),
|
||||
} satisfies AuthBootstrapResult,
|
||||
sessionToken: session.token,
|
||||
}) satisfies BootstrapExchangeResult,
|
||||
),
|
||||
);
|
||||
|
||||
const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] =
|
||||
(credential, requestMetadata) =>
|
||||
bootstrapCredentials.consume(credential).pipe(
|
||||
Effect.mapError(toBootstrapExchangeAuthError),
|
||||
Effect.flatMap((grant) =>
|
||||
sessions
|
||||
.issue({
|
||||
method: "bearer-session-token",
|
||||
subject: grant.subject,
|
||||
role: grant.role,
|
||||
client: {
|
||||
...requestMetadata,
|
||||
...(grant.label ? { label: grant.label } : {}),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue authenticated session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
(session) =>
|
||||
({
|
||||
authenticated: true,
|
||||
role: session.role,
|
||||
sessionMethod: "bearer-session-token",
|
||||
expiresAt: DateTime.toUtc(session.expiresAt),
|
||||
sessionToken: session.token,
|
||||
}) satisfies AuthBearerBootstrapResult,
|
||||
),
|
||||
);
|
||||
|
||||
const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) =>
|
||||
authControlPlane
|
||||
.createPairingLink({
|
||||
role: input?.role ?? "client",
|
||||
subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token",
|
||||
...(input?.label ? { label: input.label } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue pairing credential.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
({
|
||||
id: issued.id,
|
||||
credential: issued.credential,
|
||||
...(issued.label ? { label: issued.label } : {}),
|
||||
expiresAt: issued.expiresAt,
|
||||
}) satisfies AuthPairingCredentialResult,
|
||||
),
|
||||
);
|
||||
|
||||
const listPairingLinks: ServerAuthShape["listPairingLinks"] = () =>
|
||||
authControlPlane
|
||||
.listPairingLinks({
|
||||
role: "client",
|
||||
excludeSubjects: ["owner-bootstrap"],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to load pairing links.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) =>
|
||||
authControlPlane.revokePairingLink(id).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to revoke pairing link.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) =>
|
||||
authControlPlane.listSessions().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to load paired clients.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map((clientSessions) =>
|
||||
clientSessions.map(
|
||||
(clientSession): AuthClientSession => ({
|
||||
...clientSession,
|
||||
current: clientSession.sessionId === currentSessionId,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const revokeClientSession: ServerAuthShape["revokeClientSession"] = (
|
||||
currentSessionId,
|
||||
targetSessionId,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (currentSessionId === targetSessionId) {
|
||||
return yield* new AuthError({
|
||||
message: "Use revoke other clients to keep the current owner session active.",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
return yield* authControlPlane.revokeSession(targetSessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to revoke client session.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = (
|
||||
currentSessionId,
|
||||
) =>
|
||||
authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to revoke other client sessions.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) =>
|
||||
issuePairingCredential({ role: "owner" }).pipe(
|
||||
Effect.map((issued) => {
|
||||
const url = new URL(baseUrl);
|
||||
url.pathname = "/pair";
|
||||
url.searchParams.delete("token");
|
||||
url.hash = new URLSearchParams([["token", issued.credential]]).toString();
|
||||
return url.toString();
|
||||
}),
|
||||
);
|
||||
|
||||
const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) =>
|
||||
sessions.issueWebSocketToken(session.sessionId).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Failed to issue websocket token.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.map(
|
||||
(issued) =>
|
||||
({
|
||||
token: issued.token,
|
||||
expiresAt: DateTime.toUtc(issued.expiresAt),
|
||||
}) satisfies AuthWebSocketTokenResult,
|
||||
),
|
||||
);
|
||||
|
||||
const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestUrl = HttpServerRequest.toURL(request);
|
||||
if (Option.isSome(requestUrl)) {
|
||||
const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM);
|
||||
if (websocketToken && websocketToken.trim().length > 0) {
|
||||
return yield* sessions.verifyWebSocketToken(websocketToken).pipe(
|
||||
Effect.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
subject: session.subject,
|
||||
method: session.method,
|
||||
role: session.role,
|
||||
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
|
||||
})),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Unauthorized request.",
|
||||
status: 401,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return yield* authenticateRequest(request);
|
||||
});
|
||||
|
||||
return {
|
||||
getDescriptor: () => Effect.succeed(descriptor),
|
||||
getSessionState,
|
||||
exchangeBootstrapCredential,
|
||||
exchangeBootstrapCredentialForBearerSession,
|
||||
issuePairingCredential,
|
||||
listPairingLinks,
|
||||
revokePairingLink,
|
||||
listClientSessions,
|
||||
revokeClientSession,
|
||||
revokeOtherClientSessions,
|
||||
authenticateHttpRequest: authenticateRequest,
|
||||
authenticateWebSocketUpgrade,
|
||||
issueWebSocketToken,
|
||||
issueStartupPairingUrl,
|
||||
} satisfies ServerAuthShape;
|
||||
});
|
||||
|
||||
export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe(
|
||||
Layer.provideMerge(AuthControlPlaneLive),
|
||||
Layer.provideMerge(AuthCoreLive),
|
||||
Layer.provideMerge(ServerAuthPolicyLive),
|
||||
);
|
||||
@@ -0,0 +1,114 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
|
||||
import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
|
||||
|
||||
const makeServerAuthPolicyLayer = (overrides?: Partial<ServerConfigShape>) =>
|
||||
ServerAuthPolicyLive.pipe(
|
||||
Layer.provide(
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-policy-test-" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
||||
it.effect("uses desktop-managed-local policy for desktop mode", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
port: 3773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("remote-reachable");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap", "one-time-token"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
host: "0.0.0.0",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses loopback-browser policy for loopback web hosts", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("loopback-browser");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "127.0.0.1",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for wildcard web hosts", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("remote-reachable");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "0.0.0.0",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses remote-reachable policy for non-loopback web hosts", () =>
|
||||
Effect.gen(function* () {
|
||||
const policy = yield* ServerAuthPolicy;
|
||||
const descriptor = yield* policy.getDescriptor();
|
||||
|
||||
expect(descriptor.policy).toBe("remote-reachable");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "web",
|
||||
host: "192.168.1.50",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
|
||||
import { resolveSessionCookieName } from "../utils.ts";
|
||||
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
|
||||
|
||||
export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host);
|
||||
|
||||
const policy =
|
||||
config.mode === "desktop"
|
||||
? isRemoteReachable
|
||||
? "remote-reachable"
|
||||
: "desktop-managed-local"
|
||||
: isRemoteReachable
|
||||
? "remote-reachable"
|
||||
: "loopback-browser";
|
||||
|
||||
const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] =
|
||||
policy === "desktop-managed-local"
|
||||
? ["desktop-bootstrap"]
|
||||
: config.mode === "desktop" && policy === "remote-reachable"
|
||||
? ["desktop-bootstrap", "one-time-token"]
|
||||
: ["one-time-token"];
|
||||
|
||||
const descriptor: ServerAuthDescriptor = {
|
||||
policy,
|
||||
bootstrapMethods,
|
||||
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
}),
|
||||
};
|
||||
|
||||
return {
|
||||
getDescriptor: () => Effect.succeed(descriptor),
|
||||
} satisfies ServerAuthPolicyShape;
|
||||
});
|
||||
|
||||
export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy);
|
||||
@@ -0,0 +1,263 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
|
||||
const makeServerConfigLayer = () =>
|
||||
ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" });
|
||||
|
||||
const makeServerSecretStoreLayer = () =>
|
||||
Layer.provide(ServerSecretStoreLive, makeServerConfigLayer());
|
||||
|
||||
const PermissionDeniedFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
readFile: (path) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: path,
|
||||
description: "Permission denied while reading secret file.",
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makePermissionDeniedSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(PermissionDeniedFileSystemLayer),
|
||||
);
|
||||
|
||||
const RenameFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
rename: (from, to) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "rename",
|
||||
pathOrDescriptor: `${String(from)} -> ${String(to)}`,
|
||||
description: "Permission denied while persisting secret file.",
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeRenameFailureSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(RenameFailureFileSystemLayer),
|
||||
);
|
||||
|
||||
const RemoveFailureFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
remove: (path, options) =>
|
||||
Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "remove",
|
||||
pathOrDescriptor: String(path),
|
||||
description: `Permission denied while removing secret file.${options ? " options-set" : ""}`,
|
||||
}),
|
||||
),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeRemoveFailureSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(RemoveFailureFileSystemLayer),
|
||||
);
|
||||
|
||||
const ConcurrentReadMissFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const readCountRef = yield* Ref.make(0);
|
||||
const readBarrier = yield* Deferred.make<void>();
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
readFile: (path) =>
|
||||
String(path).endsWith("/session-signing-key.bin")
|
||||
? Ref.updateAndGet(readCountRef, (count) => count + 1).pipe(
|
||||
Effect.flatMap((count) => {
|
||||
if (count > 2) {
|
||||
return fileSystem.readFile(path);
|
||||
}
|
||||
return Effect.gen(function* () {
|
||||
if (count === 2) {
|
||||
yield* Deferred.succeed(readBarrier, void 0);
|
||||
}
|
||||
yield* Deferred.await(readBarrier);
|
||||
return yield* Effect.failCause(
|
||||
Cause.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "readFile",
|
||||
pathOrDescriptor: String(path),
|
||||
description: "Secret file does not exist yet.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
}),
|
||||
)
|
||||
: fileSystem.readFile(path),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const makeConcurrentCreateSecretStoreLayer = () =>
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(ConcurrentReadMissFileSystemLayer),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => {
|
||||
it.effect("returns null when a secret file does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const secret = yield* secretStore.get("missing-secret");
|
||||
|
||||
expect(secret).toBeNull();
|
||||
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("reuses an existing secret instead of regenerating it", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
|
||||
const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32);
|
||||
|
||||
expect(Array.from(second)).toEqual(Array.from(first));
|
||||
}).pipe(Effect.provide(makeServerSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("returns the persisted secret when concurrent creators race", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const [first, second] = yield* Effect.all(
|
||||
[
|
||||
secretStore.getOrCreateRandom("session-signing-key", 32),
|
||||
secretStore.getOrCreateRandom("session-signing-key", 32),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const persisted = yield* secretStore.get("session-signing-key");
|
||||
|
||||
expect(persisted).not.toBeNull();
|
||||
expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array()));
|
||||
expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array()));
|
||||
}).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("uses restrictive permissions for the secret directory and files", () =>
|
||||
Effect.gen(function* () {
|
||||
const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = [];
|
||||
const recordingFileSystemLayer = Layer.effect(
|
||||
FileSystem.FileSystem,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
return {
|
||||
...fileSystem,
|
||||
makeDirectory: () => Effect.void,
|
||||
writeFile: () => Effect.void,
|
||||
rename: () => Effect.void,
|
||||
chmod: (path, mode) =>
|
||||
Effect.sync(() => {
|
||||
chmodCalls.push({ path: String(path), mode });
|
||||
}),
|
||||
} satisfies FileSystem.FileSystem;
|
||||
}),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const secretStore = yield* Effect.service(ServerSecretStore).pipe(
|
||||
Effect.provide(
|
||||
ServerSecretStoreLive.pipe(
|
||||
Layer.provide(makeServerConfigLayer()),
|
||||
Layer.provideMerge(recordingFileSystemLayer),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3]));
|
||||
|
||||
expect(chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(chmodCalls.filter((call) => call.mode === 0o600).length).toBeGreaterThanOrEqual(2);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("propagates read failures other than missing-file errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32));
|
||||
|
||||
expect(error).toBeInstanceOf(SecretStoreError);
|
||||
expect(error.message).toContain("Failed to read secret session-signing-key.");
|
||||
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
|
||||
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
|
||||
}).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("propagates write failures instead of treating them as success", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])),
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(SecretStoreError);
|
||||
expect(error.message).toContain("Failed to persist secret session-signing-key.");
|
||||
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
|
||||
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())),
|
||||
);
|
||||
|
||||
it.effect("propagates remove failures other than missing-file errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
|
||||
const error = yield* Effect.flip(secretStore.remove("session-signing-key"));
|
||||
|
||||
expect(error).toBeInstanceOf(SecretStoreError);
|
||||
expect(error.message).toContain("Failed to remove secret session-signing-key.");
|
||||
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
|
||||
expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied");
|
||||
}).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
SecretStoreError,
|
||||
ServerSecretStore,
|
||||
type ServerSecretStoreShape,
|
||||
} from "../Services/ServerSecretStore.ts";
|
||||
|
||||
export const makeServerSecretStore = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
|
||||
yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });
|
||||
yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreError({
|
||||
message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
|
||||
|
||||
const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
|
||||
Predicate.isTagged(u, "PlatformError");
|
||||
|
||||
const get: ServerSecretStoreShape["get"] = (name) =>
|
||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
||||
Effect.map((bytes) => Uint8Array.from(bytes)),
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.succeed(null)
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to read secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const set: ServerSecretStoreShape["set"] = (name, value) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`;
|
||||
return Effect.gen(function* () {
|
||||
yield* fileSystem.writeFile(tempPath, value);
|
||||
yield* fileSystem.chmod(tempPath, 0o600);
|
||||
yield* fileSystem.rename(tempPath, secretPath);
|
||||
yield* fileSystem.chmod(secretPath, 0o600);
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
fileSystem.remove(tempPath).pipe(
|
||||
Effect.ignore,
|
||||
Effect.flatMap(() =>
|
||||
Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to persist secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const create: ServerSecretStoreShape["set"] = (name, value) => {
|
||||
const secretPath = resolveSecretPath(name);
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const file = yield* fileSystem.open(secretPath, {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
yield* file.writeAll(value);
|
||||
yield* file.sync;
|
||||
yield* fileSystem.chmod(secretPath, 0o600);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SecretStoreError({
|
||||
message: `Failed to persist secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) =>
|
||||
get(name).pipe(
|
||||
Effect.flatMap((existing) => {
|
||||
if (existing) {
|
||||
return Effect.succeed(existing);
|
||||
}
|
||||
|
||||
const generated = Crypto.randomBytes(bytes);
|
||||
return create(name, generated).pipe(
|
||||
Effect.as(Uint8Array.from(generated)),
|
||||
Effect.catchTag("SecretStoreError", (error) =>
|
||||
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
|
||||
? get(name).pipe(
|
||||
Effect.flatMap((created) =>
|
||||
created !== null
|
||||
? Effect.succeed(created)
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to read secret ${name} after concurrent creation.`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
: Effect.fail(error),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const remove: ServerSecretStoreShape["remove"] = (name) =>
|
||||
fileSystem.remove(resolveSecretPath(name)).pipe(
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
message: `Failed to remove secret ${name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
get,
|
||||
set,
|
||||
getOrCreateRandom,
|
||||
remove,
|
||||
} satisfies ServerSecretStoreShape;
|
||||
});
|
||||
|
||||
export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore);
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Duration, Effect, Layer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
import { SessionCredentialServiceLive } from "./SessionCredentialService.ts";
|
||||
|
||||
const makeServerConfigLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
return {
|
||||
...config,
|
||||
...overrides,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-session-test-" })));
|
||||
|
||||
const makeSessionCredentialLayer = (
|
||||
overrides?: Partial<Pick<ServerConfigShape, "desktopBootstrapToken">>,
|
||||
) =>
|
||||
SessionCredentialServiceLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(ServerSecretStoreLive),
|
||||
Layer.provide(makeServerConfigLayer(overrides)),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => {
|
||||
it.effect("issues and verifies signed browser session tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const issued = yield* sessions.issue({
|
||||
subject: "desktop-bootstrap",
|
||||
role: "owner",
|
||||
client: {
|
||||
label: "Desktop app",
|
||||
deviceType: "desktop",
|
||||
os: "macOS",
|
||||
browser: "Electron",
|
||||
ipAddress: "127.0.0.1",
|
||||
},
|
||||
});
|
||||
const verified = yield* sessions.verify(issued.token);
|
||||
|
||||
expect(verified.method).toBe("browser-session-cookie");
|
||||
expect(verified.subject).toBe("desktop-bootstrap");
|
||||
expect(verified.role).toBe("owner");
|
||||
expect(verified.client.label).toBe("Desktop app");
|
||||
expect(verified.client.browser).toBe("Electron");
|
||||
expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString());
|
||||
}).pipe(Effect.provide(makeSessionCredentialLayer())),
|
||||
);
|
||||
it.effect("rejects malformed session tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const error = yield* Effect.flip(sessions.verify("not-a-session-token"));
|
||||
|
||||
expect(error._tag).toBe("SessionCredentialError");
|
||||
expect(error.message).toContain("Malformed session token");
|
||||
}).pipe(Effect.provide(makeSessionCredentialLayer())),
|
||||
);
|
||||
it.effect("verifies session tokens against the Effect clock", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const issued = yield* sessions.issue({
|
||||
method: "bearer-session-token",
|
||||
subject: "test-clock",
|
||||
});
|
||||
const verified = yield* sessions.verify(issued.token);
|
||||
|
||||
expect(verified.method).toBe("bearer-session-token");
|
||||
expect(verified.subject).toBe("test-clock");
|
||||
expect(verified.role).toBe("client");
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("rejects websocket tokens once the parent session has expired", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const issued = yield* sessions.issue({
|
||||
method: "bearer-session-token",
|
||||
subject: "short-lived",
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
expect(error.message).toContain("expired");
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const owner = yield* sessions.issue({
|
||||
subject: "desktop-bootstrap",
|
||||
role: "owner",
|
||||
client: {
|
||||
label: "Desktop app",
|
||||
deviceType: "desktop",
|
||||
os: "macOS",
|
||||
browser: "Electron",
|
||||
},
|
||||
});
|
||||
const client = yield* sessions.issue({
|
||||
subject: "one-time-token",
|
||||
role: "client",
|
||||
client: {
|
||||
label: "Julius iPhone",
|
||||
deviceType: "mobile",
|
||||
os: "iOS",
|
||||
browser: "Safari",
|
||||
ipAddress: "192.168.1.88",
|
||||
},
|
||||
});
|
||||
|
||||
yield* sessions.markConnected(client.sessionId);
|
||||
const beforeRevoke = yield* sessions.listActive();
|
||||
const revokedCount = yield* sessions.revokeAllExcept(owner.sessionId);
|
||||
const afterRevoke = yield* sessions.listActive();
|
||||
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
|
||||
|
||||
expect(beforeRevoke).toHaveLength(2);
|
||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
|
||||
true,
|
||||
);
|
||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.client.label).toBe(
|
||||
"Julius iPhone",
|
||||
);
|
||||
expect(
|
||||
beforeRevoke.find((entry) => entry.sessionId === owner.sessionId)?.client.deviceType,
|
||||
).toBe("desktop");
|
||||
expect(revokedCount).toBe(1);
|
||||
expect(afterRevoke).toHaveLength(1);
|
||||
expect(afterRevoke[0]?.sessionId).toBe(owner.sessionId);
|
||||
expect(revokedClient.message).toContain("revoked");
|
||||
}).pipe(Effect.provide(makeSessionCredentialLayer())),
|
||||
);
|
||||
|
||||
it.effect("persists lastConnectedAt on first connect and updates it after reconnect", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const issued = yield* sessions.issue({
|
||||
subject: "reconnect-test",
|
||||
method: "bearer-session-token",
|
||||
});
|
||||
|
||||
const beforeConnect = yield* sessions.listActive();
|
||||
expect(beforeConnect[0]?.lastConnectedAt).toBeNull();
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* sessions.markConnected(issued.sessionId);
|
||||
const firstConnect = yield* sessions.listActive();
|
||||
const firstConnectedAt = firstConnect[0]?.lastConnectedAt;
|
||||
|
||||
expect(firstConnect[0]?.connected).toBe(true);
|
||||
expect(firstConnectedAt).not.toBeNull();
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* sessions.markConnected(issued.sessionId);
|
||||
const stillConnected = yield* sessions.listActive();
|
||||
|
||||
expect(stillConnected[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
|
||||
|
||||
yield* sessions.markDisconnected(issued.sessionId);
|
||||
yield* sessions.markDisconnected(issued.sessionId);
|
||||
const afterDisconnect = yield* sessions.listActive();
|
||||
|
||||
expect(afterDisconnect[0]?.connected).toBe(false);
|
||||
expect(afterDisconnect[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString());
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* sessions.markConnected(issued.sessionId);
|
||||
const afterReconnect = yield* sessions.listActive();
|
||||
|
||||
expect(afterReconnect[0]?.connected).toBe(true);
|
||||
expect(afterReconnect[0]?.lastConnectedAt).not.toBeNull();
|
||||
expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString());
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,500 @@
|
||||
import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
|
||||
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
|
||||
import { Option } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
|
||||
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
|
||||
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
type IssuedSession,
|
||||
type SessionCredentialChange,
|
||||
type SessionCredentialServiceShape,
|
||||
type VerifiedSession,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
base64UrlEncode,
|
||||
resolveSessionCookieName,
|
||||
signPayload,
|
||||
timingSafeEqualBase64Url,
|
||||
} from "../utils.ts";
|
||||
|
||||
const SIGNING_SECRET_NAME = "server-signing-key";
|
||||
const DEFAULT_SESSION_TTL = Duration.days(30);
|
||||
const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);
|
||||
|
||||
const SessionClaims = Schema.Struct({
|
||||
v: Schema.Literal(1),
|
||||
kind: Schema.Literal("session"),
|
||||
sid: AuthSessionId,
|
||||
sub: Schema.String,
|
||||
role: Schema.Literals(["owner", "client"]),
|
||||
method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]),
|
||||
iat: Schema.Number,
|
||||
exp: Schema.Number,
|
||||
});
|
||||
type SessionClaims = typeof SessionClaims.Type;
|
||||
|
||||
const WebSocketClaims = Schema.Struct({
|
||||
v: Schema.Literal(1),
|
||||
kind: Schema.Literal("websocket"),
|
||||
sid: AuthSessionId,
|
||||
iat: Schema.Number,
|
||||
exp: Schema.Number,
|
||||
});
|
||||
type WebSocketClaims = typeof WebSocketClaims.Type;
|
||||
|
||||
const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
|
||||
const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
|
||||
|
||||
function createDefaultClientMetadata(): AuthClientMetadata {
|
||||
return {
|
||||
deviceType: "unknown",
|
||||
};
|
||||
}
|
||||
|
||||
function toClientMetadata(record: {
|
||||
readonly label: string | null;
|
||||
readonly ipAddress: string | null;
|
||||
readonly userAgent: string | null;
|
||||
readonly deviceType: AuthClientMetadata["deviceType"];
|
||||
readonly os: string | null;
|
||||
readonly browser: string | null;
|
||||
}): AuthClientMetadata {
|
||||
return {
|
||||
...(record.label ? { label: record.label } : {}),
|
||||
...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
|
||||
...(record.userAgent ? { userAgent: record.userAgent } : {}),
|
||||
deviceType: record.deviceType,
|
||||
...(record.os ? { os: record.os } : {}),
|
||||
...(record.browser ? { browser: record.browser } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthClientSession {
|
||||
return {
|
||||
...input,
|
||||
current: false,
|
||||
};
|
||||
}
|
||||
|
||||
export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const authSessions = yield* AuthSessionRepository;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
});
|
||||
|
||||
const toSessionCredentialError = (message: string) => (cause: unknown) =>
|
||||
new SessionCredentialError({
|
||||
message,
|
||||
cause,
|
||||
});
|
||||
|
||||
const emitUpsert = (clientSession: AuthClientSession) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "clientUpserted",
|
||||
clientSession,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const emitRemoved = (sessionId: AuthSessionId) =>
|
||||
PubSub.publish(changesPubSub, {
|
||||
type: "clientRemoved",
|
||||
sessionId,
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const loadActiveSession = (sessionId: AuthSessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const row = yield* authSessions.getById({ sessionId });
|
||||
if (Option.isNone(row) || row.value.revokedAt !== null) {
|
||||
return Option.none<AuthClientSession>();
|
||||
}
|
||||
|
||||
const connectedSessions = yield* Ref.get(connectedSessionsRef);
|
||||
return Option.some(
|
||||
toAuthClientSession({
|
||||
sessionId: row.value.sessionId,
|
||||
subject: row.value.subject,
|
||||
role: row.value.role,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
issuedAt: row.value.issuedAt,
|
||||
expiresAt: row.value.expiresAt,
|
||||
lastConnectedAt: row.value.lastConnectedAt,
|
||||
connected: connectedSessions.has(row.value.sessionId),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) =>
|
||||
Ref.modify(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
const wasDisconnected = !next.has(sessionId);
|
||||
next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
|
||||
return [wasDisconnected, next] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap((wasDisconnected) =>
|
||||
wasDisconnected
|
||||
? DateTime.now.pipe(
|
||||
Effect.flatMap((lastConnectedAt) =>
|
||||
authSessions.setLastConnectedAt({
|
||||
sessionId,
|
||||
lastConnectedAt,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.flatMap(() => loadActiveSession(sessionId)),
|
||||
Effect.flatMap((session) =>
|
||||
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logError("Failed to publish connected-session auth update.").pipe(
|
||||
Effect.annotateLogs({
|
||||
sessionId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) =>
|
||||
Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
const remaining = (next.get(sessionId) ?? 0) - 1;
|
||||
if (remaining > 0) {
|
||||
next.set(sessionId, remaining);
|
||||
} else {
|
||||
next.delete(sessionId);
|
||||
}
|
||||
return next;
|
||||
}).pipe(
|
||||
Effect.flatMap(() => loadActiveSession(sessionId)),
|
||||
Effect.flatMap((session) =>
|
||||
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logError("Failed to publish disconnected-session auth update.").pipe(
|
||||
Effect.annotateLogs({
|
||||
sessionId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const issue: SessionCredentialServiceShape["issue"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const sessionId = AuthSessionId.make(crypto.randomUUID());
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
});
|
||||
const claims: SessionClaims = {
|
||||
v: 1,
|
||||
kind: "session",
|
||||
sid: sessionId,
|
||||
sub: input?.subject ?? "browser",
|
||||
role: input?.role ?? "client",
|
||||
method: input?.method ?? "browser-session-cookie",
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
const client = input?.client ?? createDefaultClientMetadata();
|
||||
yield* authSessions.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
role: claims.role,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
});
|
||||
yield* emitUpsert(
|
||||
toAuthClientSession({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
role: claims.role,
|
||||
method: claims.method,
|
||||
client,
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
lastConnectedAt: null,
|
||||
connected: false,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
method: claims.method,
|
||||
client,
|
||||
expiresAt: expiresAt,
|
||||
role: claims.role,
|
||||
} satisfies IssuedSession;
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential.")));
|
||||
|
||||
const verify: SessionCredentialServiceShape["verify"] = (token) =>
|
||||
Effect.gen(function* () {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Malformed session token.",
|
||||
});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Invalid session token signature.",
|
||||
});
|
||||
}
|
||||
|
||||
const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionCredentialError({
|
||||
message: "Invalid session token payload.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Session token expired.",
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Unknown session token.",
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Session token revoked.",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: claims.sid,
|
||||
token,
|
||||
method: claims.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: DateTime.makeUnsafe(claims.exp),
|
||||
subject: claims.sub,
|
||||
role: claims.role,
|
||||
} satisfies VerifiedSession;
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof SessionCredentialError
|
||||
? cause
|
||||
: new SessionCredentialError({
|
||||
message: "Failed to verify session credential.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
|
||||
sessionId,
|
||||
input,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token.")));
|
||||
|
||||
const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) =>
|
||||
Effect.gen(function* () {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Malformed websocket token.",
|
||||
});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Invalid websocket token signature.",
|
||||
});
|
||||
}
|
||||
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionCredentialError({
|
||||
message: "Invalid websocket token payload.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Websocket token expired.",
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Unknown websocket session.",
|
||||
});
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= now) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Websocket session expired.",
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionCredentialError({
|
||||
message: "Websocket session revoked.",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
role: row.value.role,
|
||||
} satisfies VerifiedSession;
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof SessionCredentialError
|
||||
? cause
|
||||
: new SessionCredentialError({
|
||||
message: "Failed to verify websocket token.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listActive: SessionCredentialServiceShape["listActive"] = () =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const connectedSessions = yield* Ref.get(connectedSessionsRef);
|
||||
const rows = yield* authSessions.listActive({ now });
|
||||
|
||||
return rows.map((row) =>
|
||||
toAuthClientSession({
|
||||
sessionId: row.sessionId,
|
||||
subject: row.subject,
|
||||
role: row.role,
|
||||
method: row.method,
|
||||
client: toClientMetadata(row.client),
|
||||
issuedAt: row.issuedAt,
|
||||
expiresAt: row.expiresAt,
|
||||
lastConnectedAt: row.lastConnectedAt,
|
||||
connected: connectedSessions.has(row.sessionId),
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions.")));
|
||||
|
||||
const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* authSessions.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
if (revoked) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(sessionId);
|
||||
return next;
|
||||
});
|
||||
yield* emitRemoved(sessionId);
|
||||
}
|
||||
return revoked;
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session.")));
|
||||
|
||||
const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions.revokeAllExcept({
|
||||
currentSessionId: sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
|
||||
|
||||
return {
|
||||
cookieName,
|
||||
issue,
|
||||
verify,
|
||||
issueWebSocketToken,
|
||||
verifyWebSocketToken,
|
||||
listActive,
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
revoke,
|
||||
revokeAllExcept,
|
||||
markConnected,
|
||||
markDisconnected,
|
||||
} satisfies SessionCredentialServiceShape;
|
||||
});
|
||||
|
||||
export const SessionCredentialServiceLive = Layer.effect(
|
||||
SessionCredentialService,
|
||||
makeSessionCredentialService,
|
||||
).pipe(Layer.provideMerge(AuthSessionRepositoryLive));
|
||||
@@ -0,0 +1,69 @@
|
||||
import type {
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthPairingLink,
|
||||
AuthSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Effect, Context } from "effect";
|
||||
import type { SessionRole } from "./SessionCredentialService.ts";
|
||||
|
||||
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
|
||||
|
||||
export interface IssuedPairingLink {
|
||||
readonly id: string;
|
||||
readonly credential: string;
|
||||
readonly role: SessionRole;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly createdAt: DateTime.Utc;
|
||||
readonly expiresAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
export interface IssuedBearerSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly token: string;
|
||||
readonly method: "bearer-session-token";
|
||||
readonly role: SessionRole;
|
||||
readonly subject: string;
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly expiresAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface AuthControlPlaneShape {
|
||||
readonly createPairingLink: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly label?: string;
|
||||
readonly role?: SessionRole;
|
||||
readonly subject?: string;
|
||||
}) => Effect.Effect<IssuedPairingLink, AuthControlPlaneError>;
|
||||
readonly listPairingLinks: (input?: {
|
||||
readonly role?: SessionRole;
|
||||
readonly excludeSubjects?: ReadonlyArray<string>;
|
||||
}) => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthControlPlaneError>;
|
||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthControlPlaneError>;
|
||||
readonly issueSession: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly subject?: string;
|
||||
readonly role?: SessionRole;
|
||||
readonly label?: string;
|
||||
}) => Effect.Effect<IssuedBearerSession, AuthControlPlaneError>;
|
||||
readonly listSessions: () => Effect.Effect<
|
||||
ReadonlyArray<AuthClientSession>,
|
||||
AuthControlPlaneError
|
||||
>;
|
||||
readonly revokeSession: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, AuthControlPlaneError>;
|
||||
readonly revokeOtherSessionsExcept: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, AuthControlPlaneError>;
|
||||
}
|
||||
|
||||
export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
|
||||
"t3/AuthControlPlane",
|
||||
) {}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export type BootstrapCredentialRole = "owner" | "client";
|
||||
|
||||
export interface BootstrapGrant {
|
||||
readonly method: ServerAuthBootstrapMethod;
|
||||
readonly role: BootstrapCredentialRole;
|
||||
readonly subject: string;
|
||||
readonly label?: string;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
}
|
||||
|
||||
export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{
|
||||
readonly message: string;
|
||||
readonly status?: 401 | 500;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface IssuedBootstrapCredential {
|
||||
readonly id: string;
|
||||
readonly credential: string;
|
||||
readonly label?: string;
|
||||
readonly expiresAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
export type BootstrapCredentialChange =
|
||||
| {
|
||||
readonly type: "pairingLinkUpserted";
|
||||
readonly pairingLink: AuthPairingLink;
|
||||
}
|
||||
| {
|
||||
readonly type: "pairingLinkRemoved";
|
||||
readonly id: string;
|
||||
};
|
||||
|
||||
export interface BootstrapCredentialServiceShape {
|
||||
readonly issueOneTimeToken: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly role?: BootstrapCredentialRole;
|
||||
readonly subject?: string;
|
||||
readonly label?: string;
|
||||
}) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthPairingLink>,
|
||||
BootstrapCredentialError
|
||||
>;
|
||||
readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
|
||||
readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialError>;
|
||||
readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
|
||||
}
|
||||
|
||||
export class BootstrapCredentialService extends Context.Service<
|
||||
BootstrapCredentialService,
|
||||
BootstrapCredentialServiceShape
|
||||
>()("t3/auth/Services/BootstrapCredentialService") {}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type {
|
||||
AuthBearerBootstrapResult,
|
||||
AuthBootstrapResult,
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthCreatePairingCredentialInput,
|
||||
AuthPairingLink,
|
||||
AuthPairingCredentialResult,
|
||||
AuthSessionId,
|
||||
AuthSessionState,
|
||||
ServerAuthDescriptor,
|
||||
ServerAuthSessionMethod,
|
||||
AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import type { SessionRole } from "./SessionCredentialService.ts";
|
||||
|
||||
export interface AuthenticatedSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly subject: string;
|
||||
readonly method: ServerAuthSessionMethod;
|
||||
readonly role: SessionRole;
|
||||
readonly expiresAt?: DateTime.DateTime;
|
||||
}
|
||||
|
||||
export class AuthError extends Data.TaggedError("AuthError")<{
|
||||
readonly message: string;
|
||||
readonly status?: 400 | 401 | 403 | 500;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface ServerAuthShape {
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
readonly getSessionState: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthSessionState, never>;
|
||||
readonly exchangeBootstrapCredential: (
|
||||
credential: string,
|
||||
requestMetadata: AuthClientMetadata,
|
||||
) => Effect.Effect<
|
||||
{
|
||||
readonly response: AuthBootstrapResult;
|
||||
readonly sessionToken: string;
|
||||
},
|
||||
AuthError
|
||||
>;
|
||||
readonly exchangeBootstrapCredentialForBearerSession: (
|
||||
credential: string,
|
||||
requestMetadata: AuthClientMetadata,
|
||||
) => Effect.Effect<AuthBearerBootstrapResult, AuthError>;
|
||||
readonly issuePairingCredential: (
|
||||
input?: AuthCreatePairingCredentialInput & {
|
||||
readonly role?: SessionRole;
|
||||
},
|
||||
) => Effect.Effect<AuthPairingCredentialResult, AuthError>;
|
||||
readonly listPairingLinks: () => Effect.Effect<ReadonlyArray<AuthPairingLink>, AuthError>;
|
||||
readonly revokePairingLink: (id: string) => Effect.Effect<boolean, AuthError>;
|
||||
readonly listClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<ReadonlyArray<AuthClientSession>, AuthError>;
|
||||
readonly revokeClientSession: (
|
||||
currentSessionId: AuthSessionId,
|
||||
targetSessionId: AuthSessionId,
|
||||
) => Effect.Effect<boolean, AuthError>;
|
||||
readonly revokeOtherClientSessions: (
|
||||
currentSessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, AuthError>;
|
||||
readonly authenticateHttpRequest: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, AuthError>;
|
||||
readonly authenticateWebSocketUpgrade: (
|
||||
request: HttpServerRequest.HttpServerRequest,
|
||||
) => Effect.Effect<AuthenticatedSession, AuthError>;
|
||||
readonly issueWebSocketToken: (
|
||||
session: AuthenticatedSession,
|
||||
) => Effect.Effect<AuthWebSocketTokenResult, AuthError>;
|
||||
readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
|
||||
}
|
||||
|
||||
export class ServerAuth extends Context.Service<ServerAuth, ServerAuthShape>()(
|
||||
"t3/auth/Services/ServerAuth",
|
||||
) {}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerAuthPolicyShape {
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerAuthPolicy extends Context.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
|
||||
"t3/auth/Services/ServerAuthPolicy",
|
||||
) {}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Data, Context } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface ServerSecretStoreShape {
|
||||
readonly get: (name: string) => Effect.Effect<Uint8Array | null, SecretStoreError>;
|
||||
readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;
|
||||
readonly getOrCreateRandom: (
|
||||
name: string,
|
||||
bytes: number,
|
||||
) => Effect.Effect<Uint8Array, SecretStoreError>;
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
|
||||
}
|
||||
|
||||
export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(
|
||||
"t3/auth/Services/ServerSecretStore",
|
||||
) {}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type {
|
||||
AuthClientMetadata,
|
||||
AuthClientSession,
|
||||
AuthSessionId,
|
||||
ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Context } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export type SessionRole = "owner" | "client";
|
||||
|
||||
export interface IssuedSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly token: string;
|
||||
readonly method: ServerAuthSessionMethod;
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
readonly role: SessionRole;
|
||||
}
|
||||
|
||||
export interface VerifiedSession {
|
||||
readonly sessionId: AuthSessionId;
|
||||
readonly token: string;
|
||||
readonly method: ServerAuthSessionMethod;
|
||||
readonly client: AuthClientMetadata;
|
||||
readonly expiresAt?: DateTime.DateTime;
|
||||
readonly subject: string;
|
||||
readonly role: SessionRole;
|
||||
}
|
||||
|
||||
export type SessionCredentialChange =
|
||||
| {
|
||||
readonly type: "clientUpserted";
|
||||
readonly clientSession: AuthClientSession;
|
||||
}
|
||||
| {
|
||||
readonly type: "clientRemoved";
|
||||
readonly sessionId: AuthSessionId;
|
||||
};
|
||||
|
||||
export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export interface SessionCredentialServiceShape {
|
||||
readonly cookieName: string;
|
||||
readonly issue: (input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
readonly subject?: string;
|
||||
readonly method?: ServerAuthSessionMethod;
|
||||
readonly role?: SessionRole;
|
||||
readonly client?: AuthClientMetadata;
|
||||
}) => Effect.Effect<IssuedSession, SessionCredentialError>;
|
||||
readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;
|
||||
readonly issueWebSocketToken: (
|
||||
sessionId: AuthSessionId,
|
||||
input?: {
|
||||
readonly ttl?: Duration.Duration;
|
||||
},
|
||||
) => Effect.Effect<
|
||||
{
|
||||
readonly token: string;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
},
|
||||
SessionCredentialError
|
||||
>;
|
||||
readonly verifyWebSocketToken: (
|
||||
token: string,
|
||||
) => Effect.Effect<VerifiedSession, SessionCredentialError>;
|
||||
readonly listActive: () => Effect.Effect<
|
||||
ReadonlyArray<AuthClientSession>,
|
||||
SessionCredentialError
|
||||
>;
|
||||
readonly streamChanges: Stream.Stream<SessionCredentialChange>;
|
||||
readonly revoke: (sessionId: AuthSessionId) => Effect.Effect<boolean, SessionCredentialError>;
|
||||
readonly revokeAllExcept: (
|
||||
sessionId: AuthSessionId,
|
||||
) => Effect.Effect<number, SessionCredentialError>;
|
||||
readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
|
||||
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export class SessionCredentialService extends Context.Service<
|
||||
SessionCredentialService,
|
||||
SessionCredentialServiceShape
|
||||
>()("t3/auth/Services/SessionCredentialService") {}
|
||||
@@ -0,0 +1,254 @@
|
||||
import {
|
||||
type AuthBearerBootstrapResult,
|
||||
AuthBootstrapInput,
|
||||
AuthCreatePairingCredentialInput,
|
||||
AuthRevokeClientSessionInput,
|
||||
AuthRevokePairingLinkInput,
|
||||
type AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Schema } from "effect";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
|
||||
import { SessionCredentialService } from "./Services/SessionCredentialService.ts";
|
||||
import { deriveAuthClientMetadata } from "./utils.ts";
|
||||
|
||||
export const respondToAuthError = (error: AuthError) =>
|
||||
Effect.gen(function* () {
|
||||
if ((error.status ?? 500) >= 500) {
|
||||
yield* Effect.logError("auth route failed", {
|
||||
message: error.message,
|
||||
cause: error.cause,
|
||||
});
|
||||
}
|
||||
return HttpServerResponse.jsonUnsafe(
|
||||
{
|
||||
error: error.message,
|
||||
},
|
||||
{ status: error.status ?? 500 },
|
||||
);
|
||||
});
|
||||
|
||||
export const authSessionRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/auth/session",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const session = yield* serverAuth.getSessionState(request);
|
||||
return HttpServerResponse.jsonUnsafe(session, { status: 200 });
|
||||
}),
|
||||
);
|
||||
|
||||
const PairingCredentialRequestHeaders = Schema.Struct({
|
||||
"content-length": Schema.optionalKey(Schema.String),
|
||||
"content-type": Schema.optionalKey(Schema.String),
|
||||
"transfer-encoding": Schema.optionalKey(Schema.String),
|
||||
});
|
||||
|
||||
function hasRequestBody(headers: typeof PairingCredentialRequestHeaders.Type) {
|
||||
const contentLengthHeader = headers["content-length"];
|
||||
if (typeof contentLengthHeader === "string") {
|
||||
const contentLength = Number.parseInt(contentLengthHeader, 10);
|
||||
if (Number.isFinite(contentLength)) {
|
||||
return contentLength > 0;
|
||||
}
|
||||
}
|
||||
return typeof headers["transfer-encoding"] === "string";
|
||||
}
|
||||
|
||||
export const authBootstrapRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/bootstrap",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid bootstrap payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const result = yield* serverAuth.exchangeBootstrapCredential(
|
||||
payload.credential,
|
||||
deriveAuthClientMetadata({ request }),
|
||||
);
|
||||
|
||||
return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe(
|
||||
HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {
|
||||
expires: DateTime.toDate(result.response.expiresAt),
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
sameSite: "lax",
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authBearerBootstrapRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/bootstrap/bearer",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid bootstrap payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const result = yield* serverAuth.exchangeBootstrapCredentialForBearerSession(
|
||||
payload.credential,
|
||||
deriveAuthClientMetadata({ request }),
|
||||
);
|
||||
return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {
|
||||
status: 200,
|
||||
});
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authWebSocketTokenRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/ws-token",
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
||||
const result = yield* serverAuth.issueWebSocketToken(session);
|
||||
return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, {
|
||||
status: 200,
|
||||
});
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authPairingCredentialRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/pairing-token",
|
||||
Effect.gen(function* () {
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
||||
if (session.role !== "owner") {
|
||||
return yield* new AuthError({
|
||||
message: "Only owner sessions can create pairing credentials.",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
const headers = yield* HttpServerRequest.schemaHeaders(PairingCredentialRequestHeaders).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid pairing credential request headers.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const payload = hasRequestBody(headers)
|
||||
? yield* HttpServerRequest.schemaBodyJson(AuthCreatePairingCredentialInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid pairing credential payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
)
|
||||
: {};
|
||||
const result = yield* serverAuth.issuePairingCredential(payload);
|
||||
return HttpServerResponse.jsonUnsafe(result, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
const authenticateOwnerSession = Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const serverAuth = yield* ServerAuth;
|
||||
const session = yield* serverAuth.authenticateHttpRequest(request);
|
||||
if (session.role !== "owner") {
|
||||
return yield* new AuthError({
|
||||
message: "Only owner sessions can manage network access.",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
return { serverAuth, session } as const;
|
||||
});
|
||||
|
||||
export const authPairingLinksRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/auth/pairing-links",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth } = yield* authenticateOwnerSession;
|
||||
const pairingLinks = yield* serverAuth.listPairingLinks();
|
||||
return HttpServerResponse.jsonUnsafe(pairingLinks, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authPairingLinksRevokeRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/pairing-links/revoke",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth } = yield* authenticateOwnerSession;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokePairingLinkInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid revoke pairing link payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const revoked = yield* serverAuth.revokePairingLink(payload.id);
|
||||
return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authClientsRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"/api/auth/clients",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
||||
const clients = yield* serverAuth.listClientSessions(session.sessionId);
|
||||
return HttpServerResponse.jsonUnsafe(clients, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authClientsRevokeRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/clients/revoke",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
||||
const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokeClientSessionInput).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AuthError({
|
||||
message: "Invalid revoke client payload.",
|
||||
status: 400,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const revoked = yield* serverAuth.revokeClientSession(session.sessionId, payload.sessionId);
|
||||
return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
|
||||
export const authClientsRevokeOthersRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
"/api/auth/clients/revoke-others",
|
||||
Effect.gen(function* () {
|
||||
const { serverAuth, session } = yield* authenticateOwnerSession;
|
||||
const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);
|
||||
return HttpServerResponse.jsonUnsafe({ revokedCount }, { status: 200 });
|
||||
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
|
||||
);
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { deriveAuthClientMetadata } from "./utils.ts";
|
||||
|
||||
describe("deriveAuthClientMetadata", () => {
|
||||
it("labels Electron user agents as Electron instead of Chrome", () => {
|
||||
const metadata = deriveAuthClientMetadata({
|
||||
request: {
|
||||
headers: {
|
||||
"user-agent":
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) t3code/0.0.15 Chrome/136.0.7103.93 Electron/36.3.2 Safari/537.36",
|
||||
},
|
||||
source: {
|
||||
remoteAddress: "::ffff:127.0.0.1",
|
||||
},
|
||||
} as never,
|
||||
});
|
||||
|
||||
expect(metadata).toMatchObject({
|
||||
browser: "Electron",
|
||||
deviceType: "desktop",
|
||||
ipAddress: "127.0.0.1",
|
||||
os: "macOS",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
|
||||
return buffer.toString("base64url");
|
||||
}
|
||||
|
||||
export function base64UrlDecodeUtf8(input: string): string {
|
||||
return Buffer.from(input, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
export function signPayload(payload: string, secret: Uint8Array): string {
|
||||
return Crypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url");
|
||||
}
|
||||
|
||||
export function timingSafeEqualBase64Url(left: string, right: string): boolean {
|
||||
const leftBuffer = Buffer.from(left, "base64url");
|
||||
const rightBuffer = Buffer.from(right, "base64url");
|
||||
if (leftBuffer.length !== rightBuffer.length) {
|
||||
return false;
|
||||
}
|
||||
return Crypto.timingSafeEqual(leftBuffer, rightBuffer);
|
||||
}
|
||||
|
||||
function normalizeNonEmptyString(value: string | null | undefined): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizeIpAddress(value: string | null | undefined): string | undefined {
|
||||
const normalized = normalizeNonEmptyString(value);
|
||||
if (!normalized) {
|
||||
return undefined;
|
||||
}
|
||||
return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized;
|
||||
}
|
||||
|
||||
function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {
|
||||
if (!userAgent) {
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const normalized = userAgent.toLowerCase();
|
||||
if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
|
||||
return "bot";
|
||||
}
|
||||
if (/ipad|tablet/.test(normalized)) {
|
||||
return "tablet";
|
||||
}
|
||||
if (/iphone|android.+mobile|mobile/.test(normalized)) {
|
||||
return "mobile";
|
||||
}
|
||||
return "desktop";
|
||||
}
|
||||
|
||||
function inferBrowser(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = userAgent.toLowerCase();
|
||||
if (/edg\//.test(normalized)) return "Edge";
|
||||
if (/opr\//.test(normalized)) return "Opera";
|
||||
if (/firefox\//.test(normalized)) return "Firefox";
|
||||
if (/electron\//.test(normalized)) return "Electron";
|
||||
if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome";
|
||||
if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function inferOs(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = userAgent.toLowerCase();
|
||||
if (/iphone|ipad|ipod/.test(normalized)) return "iOS";
|
||||
if (/android/.test(normalized)) return "Android";
|
||||
if (/mac os x|macintosh/.test(normalized)) return "macOS";
|
||||
if (/windows nt/.test(normalized)) return "Windows";
|
||||
if (/linux/.test(normalized)) return "Linux";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readRemoteAddressFromSource(source: unknown): string | undefined {
|
||||
if (!source || typeof source !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const candidate = source as {
|
||||
readonly remoteAddress?: string | null;
|
||||
readonly socket?: {
|
||||
readonly remoteAddress?: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);
|
||||
}
|
||||
|
||||
export function deriveAuthClientMetadata(input: {
|
||||
readonly request: HttpServerRequest.HttpServerRequest;
|
||||
readonly label?: string;
|
||||
}): AuthClientMetadata {
|
||||
const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]);
|
||||
const ipAddress = readRemoteAddressFromSource(input.request.source);
|
||||
const os = inferOs(userAgent);
|
||||
const browser = inferBrowser(userAgent);
|
||||
return {
|
||||
...(input.label ? { label: input.label } : {}),
|
||||
...(ipAddress ? { ipAddress } : {}),
|
||||
...(userAgent ? { userAgent } : {}),
|
||||
deviceType: inferDeviceType(userAgent),
|
||||
...(os ? { os } : {}),
|
||||
...(browser ? { browser } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
import * as NodeHttp from "node:http";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServer from "effect/unstable/http/HttpServer";
|
||||
import * as CliError from "effect/unstable/cli/CliError";
|
||||
import * as TestConsole from "effect/testing/TestConsole";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "./bin.ts";
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import {
|
||||
orchestrationDispatchRouteLayer,
|
||||
orchestrationSnapshotRouteLayer,
|
||||
} from "./orchestration/http.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
|
||||
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
|
||||
import {
|
||||
makePersistedServerRuntimeState,
|
||||
persistServerRuntimeState,
|
||||
} from "./serverRuntimeState.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
|
||||
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
const runCli = (args: ReadonlyArray<string>) => Command.runWith(cli, { version: "0.0.0" })(args);
|
||||
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
|
||||
runCli(args).pipe(Effect.provide(CliRuntimeLayer));
|
||||
|
||||
const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* effect;
|
||||
const output =
|
||||
(yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
|
||||
"";
|
||||
return { result, output };
|
||||
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
|
||||
|
||||
const makeCliTestServerConfig = (baseDir: string) =>
|
||||
Effect.gen(function* () {
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||
return {
|
||||
logLevel: "Info",
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: "127.0.0.1",
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: true,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
} satisfies ServerConfigShape;
|
||||
});
|
||||
|
||||
const makeProjectPersistenceLayer = (config: ServerConfigShape) =>
|
||||
Layer.mergeAll(
|
||||
OrchestrationLayerLive.pipe(
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
),
|
||||
WorkspacePathsLive,
|
||||
).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
);
|
||||
|
||||
const readPersistedSnapshot = (baseDir: string) =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* makeCliTestServerConfig(baseDir);
|
||||
return yield* Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
return yield* projectionSnapshotQuery.getSnapshot();
|
||||
}).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
|
||||
});
|
||||
|
||||
const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* makeCliTestServerConfig(baseDir);
|
||||
const routesLayer = Layer.mergeAll(
|
||||
orchestrationSnapshotRouteLayer,
|
||||
orchestrationDispatchRouteLayer,
|
||||
);
|
||||
const appLayer = HttpRouter.serve(routesLayer, {
|
||||
disableListenLog: true,
|
||||
disableLogger: true,
|
||||
}).pipe(
|
||||
Layer.provideMerge(
|
||||
ServerAuthLive.pipe(
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provide(ServerSecretStoreLive),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(makeProjectPersistenceLayer(config)),
|
||||
Layer.provideMerge(
|
||||
NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: "127.0.0.1",
|
||||
port: 0,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
);
|
||||
|
||||
return yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* HttpServer.HttpServer;
|
||||
const address = server.address;
|
||||
if (typeof address === "string" || !("port" in address)) {
|
||||
assert.fail(`Expected TCP address, got ${address}`);
|
||||
}
|
||||
yield* persistServerRuntimeState({
|
||||
path: config.serverRuntimeStatePath,
|
||||
state: makePersistedServerRuntimeState({
|
||||
config,
|
||||
port: address.port,
|
||||
}),
|
||||
});
|
||||
return yield* run();
|
||||
}).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
it.effect("accepts the built-in lowercase log-level flag values", () =>
|
||||
runCliWithRuntime(["--log-level", "debug", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("accepts canonical --no-<flag> boolean negation", () =>
|
||||
runCliWithRuntime(["--no-log-websocket-events", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
}
|
||||
if (error._tag !== "InvalidValue") {
|
||||
assert.fail(`Expected InvalidValue, got ${error._tag}`);
|
||||
}
|
||||
assert.equal(error.option, "log-level");
|
||||
assert.equal(error.value, "Debug");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-"));
|
||||
|
||||
const createdOutput = yield* captureStdout(
|
||||
runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
const created = JSON.parse(createdOutput.output) as {
|
||||
readonly id: string;
|
||||
readonly credential: string;
|
||||
};
|
||||
const listedOutput = yield* captureStdout(
|
||||
runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
|
||||
readonly id: string;
|
||||
readonly credential?: string;
|
||||
}>;
|
||||
|
||||
assert.equal(typeof created.id, "string");
|
||||
assert.equal(typeof created.credential, "string");
|
||||
assert.equal(created.credential.length > 0, true);
|
||||
assert.equal(listed.length, 1);
|
||||
assert.equal(listed[0]?.id, created.id);
|
||||
assert.equal("credential" in (listed[0] ?? {}), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("executes auth session subcommands and redacts secrets from list output", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-"));
|
||||
|
||||
const issuedOutput = yield* captureStdout(
|
||||
runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
const issued = JSON.parse(issuedOutput.output) as {
|
||||
readonly sessionId: string;
|
||||
readonly token: string;
|
||||
readonly role: string;
|
||||
};
|
||||
const listedOutput = yield* captureStdout(
|
||||
runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
|
||||
);
|
||||
const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
|
||||
readonly sessionId: string;
|
||||
readonly token?: string;
|
||||
readonly role: string;
|
||||
}>;
|
||||
|
||||
assert.equal(typeof issued.sessionId, "string");
|
||||
assert.equal(typeof issued.token, "string");
|
||||
assert.equal(issued.role, "owner");
|
||||
assert.equal(listed.length, 1);
|
||||
assert.equal(listed[0]?.sessionId, issued.sessionId);
|
||||
assert.equal(listed[0]?.role, "owner");
|
||||
assert.equal("token" in (listed[0] ?? {}), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid ttl values before running auth commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
}
|
||||
if (error._tag !== "ShowHelp") {
|
||||
assert.fail(`Expected ShowHelp, got ${error._tag}`);
|
||||
}
|
||||
assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
|
||||
const ttlError = error.errors[0] as CliError.CliError | undefined;
|
||||
if (!ttlError || ttlError._tag !== "InvalidValue") {
|
||||
assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
|
||||
}
|
||||
assert.equal(ttlError.option, "ttl");
|
||||
assert.equal(ttlError.value, "soon");
|
||||
assert.isTrue(ttlError.message.includes("Invalid duration"));
|
||||
assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-offline-test-"));
|
||||
const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-workspace-"));
|
||||
|
||||
yield* runCliWithRuntime([
|
||||
"project",
|
||||
"add",
|
||||
workspaceRoot,
|
||||
"--title",
|
||||
"Alpha",
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const afterAdd = yield* readPersistedSnapshot(baseDir);
|
||||
const addedProject = afterAdd.projects.find(
|
||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
||||
);
|
||||
assert.isTrue(addedProject !== undefined);
|
||||
assert.equal(addedProject?.title, "Alpha");
|
||||
|
||||
yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
|
||||
const afterRename = yield* readPersistedSnapshot(baseDir);
|
||||
const renamedProject = afterRename.projects.find(
|
||||
(project) => project.id === addedProject?.id,
|
||||
);
|
||||
assert.equal(renamedProject?.title, "Beta");
|
||||
assert.equal(renamedProject?.deletedAt, null);
|
||||
|
||||
yield* runCliWithRuntime([
|
||||
"project",
|
||||
"remove",
|
||||
addedProject?.id ?? "",
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const afterRemove = yield* readPersistedSnapshot(baseDir);
|
||||
const removedProject = afterRemove.projects.find(
|
||||
(project) => project.id === addedProject?.id,
|
||||
);
|
||||
assert.isTrue((removedProject?.deletedAt ?? null) !== null);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes project commands through a running server when runtime state is present", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-test-"));
|
||||
const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-workspace-"));
|
||||
|
||||
yield* withLiveProjectCliServer(baseDir, () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCliWithRuntime([
|
||||
"project",
|
||||
"add",
|
||||
workspaceRoot,
|
||||
"--title",
|
||||
"Live Project",
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const readModel = yield* projectionSnapshotQuery.getSnapshot();
|
||||
const addedProject = readModel.projects.find(
|
||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
||||
);
|
||||
assert.isTrue(addedProject !== undefined);
|
||||
assert.equal(addedProject?.title, "Live Project");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects dev-url on project commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceRoot = mkdtempSync(
|
||||
join(tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
|
||||
);
|
||||
const error = yield* runCliWithRuntime([
|
||||
"project",
|
||||
"add",
|
||||
workspaceRoot,
|
||||
"--dev-url",
|
||||
"http://127.0.0.1:5173",
|
||||
]).pipe(Effect.flip);
|
||||
|
||||
if (!CliError.isCliError(error)) {
|
||||
assert.fail(`Expected CliError, got ${String(error)}`);
|
||||
}
|
||||
if (error._tag !== "ShowHelp") {
|
||||
assert.fail(`Expected ShowHelp, got ${error._tag}`);
|
||||
}
|
||||
assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
|
||||
const optionError = error.errors[0] as CliError.CliError | undefined;
|
||||
if (!optionError || optionError._tag !== "UnrecognizedOption") {
|
||||
assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
|
||||
}
|
||||
assert.equal(optionError.option, "--dev-url");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { authCommand } from "./cli/auth.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
export const cli = Command.make("t3", { ...sharedServerCommandFlags }).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((flags) => runServerCommand(flags)),
|
||||
Command.withSubcommands([startCommand, serveCommand, authCommand, projectCommand]),
|
||||
);
|
||||
|
||||
if (import.meta.main) {
|
||||
Command.run(cli, { version: packageJson.version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
}
|
||||
Loaded 100 of 991 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user