Compare commits
242
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3291cf83e | ||
|
|
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 | ||
|
|
ff8d87ddee | ||
|
|
3289a25e57 | ||
|
|
df5bde7e11 | ||
|
|
b3bca04caf | ||
|
|
bf71e0bc5e | ||
|
|
a542a3b168 | ||
|
|
56d13faa1a | ||
|
|
2a435aef66 | ||
|
|
28afb14004 | ||
|
|
8f3515572d | ||
|
|
529315b4c8 | ||
|
|
0a503d0cde | ||
|
|
d4a7e1ac0b | ||
|
|
be1abc88fd | ||
|
|
384f35084e | ||
|
|
1371ce2cce | ||
|
|
d6408a2949 | ||
|
|
e823f8f14e | ||
|
|
2b08d86696 | ||
|
|
e11fb6e778 | ||
|
|
d415558915 | ||
|
|
843d6d8678 | ||
|
|
754cded24a | ||
|
|
2b6640af1e | ||
|
|
9e29c9d728 | ||
|
|
ef2569196f | ||
|
|
34cef6202b | ||
|
|
25c7003226 | ||
|
|
46e63b3612 | ||
|
|
d373389703 | ||
|
|
bc12421736 | ||
|
|
8f11ea44a7 | ||
|
|
56660b04e9 | ||
|
|
2a237c2001 | ||
|
|
77716b4ccb | ||
|
|
fb18b2de16 |
No files matched your search
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "T3 Code Dev",
|
||||||
|
"image": "debian:bookworm",
|
||||||
|
"features": {
|
||||||
|
"ghcr.io/devcontainers-extra/features/bun:1": {},
|
||||||
|
"ghcr.io/devcontainers/features/node:1": {
|
||||||
|
"version": "24",
|
||||||
|
"nodeGypDependencies": true
|
||||||
|
},
|
||||||
|
"ghcr.io/devcontainers/features/python:1": {
|
||||||
|
"version": "3.12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"postCreateCommand": {
|
||||||
|
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
||||||
|
},
|
||||||
|
"customizations": {
|
||||||
|
"vscode": {
|
||||||
|
"extensions": ["oxc.oxc-vscode"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
### 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
|
||||||
|
|
||||||
|
### 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
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
## 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.
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
|
||||||
|
## 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.
|
||||||
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||||
`bun run dev -- --state-dir ~/.t3/another-dev-state`
|
`bun run dev -- --base-dir ~/.t3-2`
|
||||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
|
||||||
|
* text=auto eol=lf
|
||||||
+2
-1
@@ -28,4 +28,5 @@ github:realAhmedRoach
|
|||||||
github:shiroyasha9
|
github:shiroyasha9
|
||||||
github:Yash-Singh1
|
github:Yash-Singh1
|
||||||
github:eggfriedrice24
|
github:eggfriedrice24
|
||||||
github:Ymit24
|
github:Ymit24
|
||||||
|
github:shivamhwp
|
||||||
@@ -10,6 +10,7 @@ jobs:
|
|||||||
quality:
|
quality:
|
||||||
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
||||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||||
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
@@ -71,11 +72,12 @@ jobs:
|
|||||||
- name: Verify preload bundle output
|
- name: Verify preload bundle output
|
||||||
run: |
|
run: |
|
||||||
test -f apps/desktop/dist-electron/preload.js
|
test -f apps/desktop/dist-electron/preload.js
|
||||||
grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||||
|
|
||||||
release_smoke:
|
release_smoke:
|
||||||
name: Release Smoke
|
name: Release Smoke
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
|
|||||||
+102
-12
@@ -24,32 +24,32 @@ jobs:
|
|||||||
{
|
{
|
||||||
name: "size:XS",
|
name: "size:XS",
|
||||||
color: "0e8a16",
|
color: "0e8a16",
|
||||||
description: "0-9 changed lines (additions + deletions).",
|
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:S",
|
name: "size:S",
|
||||||
color: "5ebd3e",
|
color: "5ebd3e",
|
||||||
description: "10-29 changed lines (additions + deletions).",
|
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:M",
|
name: "size:M",
|
||||||
color: "fbca04",
|
color: "fbca04",
|
||||||
description: "30-99 changed lines (additions + deletions).",
|
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:L",
|
name: "size:L",
|
||||||
color: "fe7d37",
|
color: "fe7d37",
|
||||||
description: "100-499 changed lines (additions + deletions).",
|
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:XL",
|
name: "size:XL",
|
||||||
color: "d93f0b",
|
color: "d93f0b",
|
||||||
description: "500-999 changed lines (additions + deletions).",
|
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "size:XXL",
|
name: "size:XXL",
|
||||||
color: "b60205",
|
color: "b60205",
|
||||||
description: "1,000+ changed lines (additions + deletions).",
|
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -124,19 +124,49 @@ jobs:
|
|||||||
group: pr-size-${{ github.event.pull_request.number }}
|
group: pr-size-${{ github.event.pull_request.number }}
|
||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
steps:
|
steps:
|
||||||
|
- name: Checkout base repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
- name: Sync PR size label
|
- name: Sync PR size label
|
||||||
uses: actions/github-script@v8
|
uses: actions/github-script@v8
|
||||||
env:
|
env:
|
||||||
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
|
||||||
with:
|
with:
|
||||||
script: |
|
script: |
|
||||||
const issueNumber = context.payload.pull_request.number;
|
const { execFileSync } = require("node:child_process");
|
||||||
const additions = context.payload.pull_request.additions ?? 0;
|
|
||||||
const deletions = context.payload.pull_request.deletions ?? 0;
|
|
||||||
const changedLines = additions + deletions;
|
|
||||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
|
||||||
|
|
||||||
|
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));
|
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||||
|
// Keep this aligned with the repo's test entrypoints and test-only support files.
|
||||||
|
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 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) => {
|
const resolveSizeLabel = (totalChangedLines) => {
|
||||||
if (totalChangedLines < 10) {
|
if (totalChangedLines < 10) {
|
||||||
@@ -162,6 +192,55 @@ jobs:
|
|||||||
return "size:XXL";
|
return "size:XXL";
|
||||||
};
|
};
|
||||||
|
|
||||||
|
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
|
||||||
|
stdio: "inherit",
|
||||||
|
});
|
||||||
|
|
||||||
|
execFileSync(
|
||||||
|
"git",
|
||||||
|
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
|
||||||
|
{
|
||||||
|
stdio: "inherit",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
|
||||||
|
encoding: "utf8",
|
||||||
|
}).trim();
|
||||||
|
|
||||||
|
if (resolvedHeadSha !== headSha) {
|
||||||
|
core.warning(
|
||||||
|
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
|
||||||
|
stdio: "inherit",
|
||||||
|
});
|
||||||
|
|
||||||
|
const diffArgs = [
|
||||||
|
"diff",
|
||||||
|
"--numstat",
|
||||||
|
"--ignore-all-space",
|
||||||
|
"--ignore-blank-lines",
|
||||||
|
`${baseSha}...${resolvedHeadSha}`,
|
||||||
|
];
|
||||||
|
|
||||||
|
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);
|
const nextLabelName = resolveSizeLabel(changedLines);
|
||||||
|
|
||||||
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
|
||||||
@@ -199,4 +278,15 @@ jobs:
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
core.info(`PR #${issueNumber}: ${changedLines} changed lines -> ${nextLabelName}`);
|
const classification =
|
||||||
|
nonTestChangedLines === 0
|
||||||
|
? testChangedLines > 0
|
||||||
|
? "test-only PR"
|
||||||
|
: "no line changes"
|
||||||
|
: testChangedLines > 0
|
||||||
|
? "test lines excluded"
|
||||||
|
: "all non-test changes";
|
||||||
|
|
||||||
|
core.info(
|
||||||
|
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
|
||||||
|
);
|
||||||
@@ -19,6 +19,7 @@ jobs:
|
|||||||
preflight:
|
preflight:
|
||||||
name: Preflight
|
name: Preflight
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 10
|
||||||
outputs:
|
outputs:
|
||||||
version: ${{ steps.release_meta.outputs.version }}
|
version: ${{ steps.release_meta.outputs.version }}
|
||||||
tag: ${{ steps.release_meta.outputs.tag }}
|
tag: ${{ steps.release_meta.outputs.tag }}
|
||||||
@@ -81,6 +82,7 @@ jobs:
|
|||||||
name: Build ${{ matrix.label }}
|
name: Build ${{ matrix.label }}
|
||||||
needs: preflight
|
needs: preflight
|
||||||
runs-on: ${{ matrix.runner }}
|
runs-on: ${{ matrix.runner }}
|
||||||
|
timeout-minutes: 30
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@@ -227,6 +229,7 @@ jobs:
|
|||||||
name: Publish CLI to npm
|
name: Publish CLI to npm
|
||||||
needs: [preflight, build]
|
needs: [preflight, build]
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
@@ -260,6 +263,7 @@ jobs:
|
|||||||
name: Publish GitHub Release
|
name: Publish GitHub Release
|
||||||
needs: [preflight, build, publish_cli]
|
needs: [preflight, build, publish_cli]
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v6
|
||||||
@@ -307,12 +311,13 @@ jobs:
|
|||||||
name: Finalize release
|
name: Finalize release
|
||||||
needs: [preflight, release]
|
needs: [preflight, release]
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 10
|
||||||
steps:
|
steps:
|
||||||
- id: app_token
|
- id: app_token
|
||||||
name: Mint release app token
|
name: Mint release app token
|
||||||
uses: actions/create-github-app-token@v2
|
uses: actions/create-github-app-token@v2
|
||||||
with:
|
with:
|
||||||
app-id: ${{ vars.RELEASE_APP_ID }}
|
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||||
owner: ${{ github.repository_owner }}
|
owner: ${{ github.repository_owner }}
|
||||||
|
|
||||||
|
|||||||
+5
-1
@@ -12,9 +12,13 @@ packages/*/dist
|
|||||||
build/
|
build/
|
||||||
.logs/
|
.logs/
|
||||||
release/
|
release/
|
||||||
|
release-mock/
|
||||||
.t3
|
.t3
|
||||||
.idea/
|
.idea/
|
||||||
apps/web/.playwright
|
apps/web/.playwright
|
||||||
apps/web/playwright-report
|
apps/web/playwright-report
|
||||||
apps/web/src/components/__screenshots__
|
apps/web/src/components/__screenshots__
|
||||||
.vitest-*
|
.vitest-*
|
||||||
|
__screenshots__/
|
||||||
|
.tanstack
|
||||||
|
squashfs-root/
|
||||||
+3
-1
@@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||||
"ignorePatterns": [
|
"ignorePatterns": [
|
||||||
|
".reference",
|
||||||
".plans",
|
".plans",
|
||||||
"dist",
|
"dist",
|
||||||
"dist-electron",
|
"dist-electron",
|
||||||
@@ -8,7 +9,8 @@
|
|||||||
"bun.lock",
|
"bun.lock",
|
||||||
"*.tsbuildinfo",
|
"*.tsbuildinfo",
|
||||||
"**/routeTree.gen.ts",
|
"**/routeTree.gen.ts",
|
||||||
"apps/web/public/mockServiceWorker.js"
|
"apps/web/public/mockServiceWorker.js",
|
||||||
|
"apps/web/src/lib/vendor/qrcodegen.ts"
|
||||||
],
|
],
|
||||||
"sortPackageJson": {}
|
"sortPackageJson": {}
|
||||||
}
|
}
|
||||||
@@ -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,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.
|
||||||
@@ -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+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||||
{ "key": "mod+w", "command": "terminal.close", "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+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "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.split`: split terminal (in focused terminal context by default)
|
||||||
- `terminal.new`: create new 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)
|
- `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.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`))
|
- `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
|
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||||
|
|||||||
@@ -2,18 +2,42 @@
|
|||||||
|
|
||||||
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 and Claude, more coming soon).
|
||||||
|
|
||||||
## How to use
|
## Installation
|
||||||
|
|
||||||
> [!WARNING]
|
> [!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 and Claude.
|
||||||
|
> Install and authenticate at least one provider before use:
|
||||||
|
>
|
||||||
|
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
||||||
|
> - Claude: install Claude Code and run `claude auth login`
|
||||||
|
|
||||||
|
### Run without installing
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npx t3
|
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
|
## Some notes
|
||||||
|
|
||||||
@@ -21,8 +45,18 @@ We are very very early in this project. Expect bugs.
|
|||||||
|
|
||||||
We are not accepting contributions yet.
|
We are not accepting contributions yet.
|
||||||
|
|
||||||
|
Observability guide: [docs/observability.md](./docs/observability.md)
|
||||||
|
|
||||||
## If you REALLY want to contribute still.... read this first
|
## 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.
|
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||||
|
|
||||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||||
@@ -1,65 +1,87 @@
|
|||||||
# 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 |
|
That gives you:
|
||||||
| ----------------------- | --------------------- | ---------------------------------- |
|
|
||||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
|
||||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
|
||||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
|
||||||
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State 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. |
|
|
||||||
|
|
||||||
> 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.
|
There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
|
||||||
- Treat the token like a password.
|
|
||||||
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
|
|
||||||
|
|
||||||
## 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 address the server is reachable at (e.g. `http://192.168.x.y:3773`).
|
||||||
|
4. Use **Create Link** to generate a pairing link you can share with another device.
|
||||||
|
|
||||||
|
### 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
|
```bash
|
||||||
bun run build
|
npx t3 serve --host "$(tailscale ip -4)"
|
||||||
TOKEN="$(openssl rand -hex 24)"
|
|
||||||
bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
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.
|
> Note
|
||||||
- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.
|
> The GUIs do not currently support adding projects on remote environments.
|
||||||
- Ensure your OS firewall allows inbound TCP on the selected port.
|
> For now, use `t3 project ...` on the server machine instead.
|
||||||
|
> Full GUI support for remote project management is coming soon.
|
||||||
|
|
||||||
## 2) Tailnet / Tailscale access
|
## How Pairing Works
|
||||||
|
|
||||||
If you use Tailscale, you can bind directly to your Tailnet address.
|
The remote device does not need a long-lived secret up front.
|
||||||
|
|
||||||
```bash
|
Instead:
|
||||||
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
|
|
||||||
```
|
|
||||||
|
|
||||||
Open from any device in your tailnet:
|
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.
|
||||||
|
|
||||||
`http://<tailnet-ip>:3773`
|
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
|
||||||
|
|
||||||
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
|
## 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.
|
||||||
|
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@t3tools/desktop",
|
"name": "@t3tools/desktop",
|
||||||
"version": "0.0.10",
|
"version": "0.0.17",
|
||||||
"private": true,
|
"private": true,
|
||||||
"main": "dist-electron/main.js",
|
"main": "dist-electron/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -24,8 +24,7 @@
|
|||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
"tsdown": "catalog:",
|
"tsdown": "catalog:",
|
||||||
"typescript": "catalog:",
|
"typescript": "catalog:",
|
||||||
"vitest": "catalog:",
|
"vitest": "catalog:"
|
||||||
"wait-on": "^8.0.2"
|
|
||||||
},
|
},
|
||||||
"productName": "T3 Code (Alpha)"
|
"productName": "T3 Code (Alpha)"
|
||||||
}
|
}
|
||||||
@@ -1,27 +1,39 @@
|
|||||||
import { spawn, spawnSync } from "node:child_process";
|
import { spawn, spawnSync } from "node:child_process";
|
||||||
import { watch } from "node:fs";
|
import { watch } from "node:fs";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import waitOn from "wait-on";
|
|
||||||
|
|
||||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
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 = [
|
const requiredFiles = [
|
||||||
"dist-electron/main.js",
|
"dist-electron/main.js",
|
||||||
"dist-electron/preload.js",
|
"dist-electron/preload.js",
|
||||||
"../server/dist/index.mjs",
|
"../server/dist/bin.mjs",
|
||||||
];
|
];
|
||||||
const watchedDirectories = [
|
const watchedDirectories = [
|
||||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||||
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
|
||||||
];
|
];
|
||||||
const forcedShutdownTimeoutMs = 1_500;
|
const forcedShutdownTimeoutMs = 1_500;
|
||||||
const restartDebounceMs = 120;
|
const restartDebounceMs = 120;
|
||||||
const childTreeGracePeriodMs = 1_200;
|
const childTreeGracePeriodMs = 1_200;
|
||||||
|
|
||||||
await waitOn({
|
await waitForResources({
|
||||||
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
baseDir: desktopDir,
|
||||||
|
files: requiredFiles,
|
||||||
|
tcpHost: devServer.hostname,
|
||||||
|
tcpPort: port,
|
||||||
});
|
});
|
||||||
|
|
||||||
const childEnv = { ...process.env };
|
const childEnv = { ...process.env };
|
||||||
@@ -60,10 +72,7 @@ function startApp() {
|
|||||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||||
{
|
{
|
||||||
cwd: desktopDir,
|
cwd: desktopDir,
|
||||||
env: {
|
env: childEnv,
|
||||||
...childEnv,
|
|
||||||
VITE_DEV_SERVER_URL: devServerUrl,
|
|
||||||
},
|
|
||||||
stdio: "inherit",
|
stdio: "inherit",
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import { fileURLToPath } from "node:url";
|
|||||||
|
|
||||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||||
const APP_BUNDLE_ID = "com.t3tools.t3code";
|
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||||
const LAUNCHER_VERSION = 1;
|
const LAUNCHER_VERSION = 1;
|
||||||
|
|
||||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||||
|
|||||||
@@ -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,109 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { resolveDesktopBackendPort } from "./backendPort";
|
||||||
|
|
||||||
|
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";
|
||||||
|
|
||||||
|
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,234 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
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 = {
|
||||||
|
confirmThreadArchive: true,
|
||||||
|
confirmThreadDelete: false,
|
||||||
|
diffWordWrap: true,
|
||||||
|
sidebarProjectSortOrder: "manual",
|
||||||
|
sidebarThreadSortOrder: "created_at",
|
||||||
|
timestampFormat: "24-hour",
|
||||||
|
};
|
||||||
|
|
||||||
|
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",
|
||||||
|
};
|
||||||
|
|
||||||
|
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,216 @@
|
|||||||
|
import * as FS from "node:fs";
|
||||||
|
import * as Path from "node:path";
|
||||||
|
|
||||||
|
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||||
|
import { Predicate } from "effect";
|
||||||
|
|
||||||
|
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.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 {
|
||||||
|
return {
|
||||||
|
environmentId: record.environmentId,
|
||||||
|
label: record.label,
|
||||||
|
httpBaseUrl: record.httpBaseUrl,
|
||||||
|
wsBaseUrl: record.wsBaseUrl,
|
||||||
|
createdAt: record.createdAt,
|
||||||
|
lastConnectedAt: record.lastConnectedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readClientSettings(settingsPath: string): ClientSettings | null {
|
||||||
|
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? 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,
|
||||||
|
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");
|
||||||
|
return {
|
||||||
|
environmentId: record.environmentId,
|
||||||
|
label: record.label,
|
||||||
|
httpBaseUrl: record.httpBaseUrl,
|
||||||
|
wsBaseUrl: record.wsBaseUrl,
|
||||||
|
createdAt: record.createdAt,
|
||||||
|
lastConnectedAt: record.lastConnectedAt,
|
||||||
|
encryptedBearerToken,
|
||||||
|
} satisfies PersistedSavedEnvironmentStorageRecord;
|
||||||
|
}),
|
||||||
|
} 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);
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
|
|||||||
const options = {
|
const options = {
|
||||||
type: "question" as const,
|
type: "question" as const,
|
||||||
buttons: ["No", "Yes"],
|
buttons: ["No", "Yes"],
|
||||||
defaultId: CONFIRM_BUTTON_INDEX,
|
defaultId: 0,
|
||||||
cancelId: 0,
|
cancelId: 0,
|
||||||
noLink: true,
|
noLink: true,
|
||||||
message: normalizedMessage,
|
message: normalizedMessage,
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
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,
|
||||||
|
setDesktopServerExposurePreference,
|
||||||
|
writeDesktopSettings,
|
||||||
|
} from "./desktopSettings";
|
||||||
|
|
||||||
|
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())).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("persists and reloads the configured server exposure mode", () => {
|
||||||
|
const settingsPath = makeSettingsPath();
|
||||||
|
|
||||||
|
writeDesktopSettings(settingsPath, {
|
||||||
|
serverExposureMode: "network-accessible",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(readDesktopSettings(settingsPath)).toEqual({
|
||||||
|
serverExposureMode: "network-accessible",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves the requested network-accessible preference across temporary fallback", () => {
|
||||||
|
expect(
|
||||||
|
setDesktopServerExposurePreference(
|
||||||
|
{
|
||||||
|
serverExposureMode: "local-only",
|
||||||
|
},
|
||||||
|
"network-accessible",
|
||||||
|
),
|
||||||
|
).toEqual({
|
||||||
|
serverExposureMode: "network-accessible",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to defaults when the settings file is malformed", () => {
|
||||||
|
const settingsPath = makeSettingsPath();
|
||||||
|
fs.writeFileSync(settingsPath, "{not-json", "utf8");
|
||||||
|
|
||||||
|
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import * as FS from "node:fs";
|
||||||
|
import * as Path from "node:path";
|
||||||
|
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
export interface DesktopSettings {
|
||||||
|
readonly serverExposureMode: DesktopServerExposureMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||||
|
serverExposureMode: "local-only",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function setDesktopServerExposurePreference(
|
||||||
|
settings: DesktopSettings,
|
||||||
|
requestedMode: DesktopServerExposureMode,
|
||||||
|
): DesktopSettings {
|
||||||
|
return settings.serverExposureMode === requestedMode
|
||||||
|
? settings
|
||||||
|
: {
|
||||||
|
...settings,
|
||||||
|
serverExposureMode: requestedMode,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readDesktopSettings(settingsPath: string): DesktopSettings {
|
||||||
|
try {
|
||||||
|
if (!FS.existsSync(settingsPath)) {
|
||||||
|
return DEFAULT_DESKTOP_SETTINGS;
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = FS.readFileSync(settingsPath, "utf8");
|
||||||
|
const parsed = JSON.parse(raw) as {
|
||||||
|
readonly serverExposureMode?: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
serverExposureMode:
|
||||||
|
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return DEFAULT_DESKTOP_SETTINGS;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
+765
-76
File diff suppressed because it is too large.
Load diff
@@ -9,12 +9,41 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
|||||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||||
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||||
|
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
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 GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||||
|
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||||
getWsUrl: () => wsUrl,
|
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),
|
||||||
|
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
|
||||||
|
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
|
||||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||||
@@ -32,6 +61,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||||
|
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
|
||||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||||
onUpdateState: (listener) => {
|
onUpdateState: (listener) => {
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
|
||||||
|
|
||||||
|
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("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,80 @@
|
|||||||
|
import type { NetworkInterfaceInfo } from "node:os";
|
||||||
|
import type { 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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.");
|
||||||
|
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { ServerListeningDetector } from "./serverListeningDetector";
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,11 +6,12 @@ describe("syncShellEnvironment", () => {
|
|||||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||||
const env: NodeJS.ProcessEnv = {
|
const env: NodeJS.ProcessEnv = {
|
||||||
SHELL: "/bin/zsh",
|
SHELL: "/bin/zsh",
|
||||||
PATH: "/usr/bin",
|
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||||
};
|
};
|
||||||
const readEnvironment = vi.fn(() => ({
|
const readEnvironment = vi.fn(() => ({
|
||||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||||
|
HOMEBREW_PREFIX: "/opt/homebrew",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
syncShellEnvironment(env, {
|
syncShellEnvironment(env, {
|
||||||
@@ -18,9 +19,18 @@ describe("syncShellEnvironment", () => {
|
|||||||
readEnvironment,
|
readEnvironment,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
"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.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||||
|
expect(env.HOMEBREW_PREFIX).toBe("/opt/homebrew");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("preserves an inherited SSH_AUTH_SOCK value", () => {
|
it("preserves an inherited SSH_AUTH_SOCK value", () => {
|
||||||
@@ -62,14 +72,13 @@ describe("syncShellEnvironment", () => {
|
|||||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
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 = {
|
const env: NodeJS.ProcessEnv = {
|
||||||
SHELL: "/bin/zsh",
|
SHELL: "/bin/zsh",
|
||||||
PATH: "/usr/bin",
|
PATH: "/usr/bin",
|
||||||
SSH_AUTH_SOCK: "/tmp/inherited.sock",
|
|
||||||
};
|
};
|
||||||
const readEnvironment = vi.fn(() => ({
|
const readEnvironment = vi.fn(() => ({
|
||||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -78,8 +87,85 @@ describe("syncShellEnvironment", () => {
|
|||||||
readEnvironment,
|
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 outside macOS and linux", () => {
|
||||||
|
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: "win32",
|
||||||
|
readEnvironment,
|
||||||
|
});
|
||||||
|
|
||||||
expect(readEnvironment).not.toHaveBeenCalled();
|
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");
|
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,29 +1,79 @@
|
|||||||
import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell";
|
import {
|
||||||
|
listLoginShellCandidates,
|
||||||
|
mergePathEntries,
|
||||||
|
readPathFromLaunchctl,
|
||||||
|
readEnvironmentFromLoginShell,
|
||||||
|
ShellEnvironmentReader,
|
||||||
|
} from "@t3tools/shared/shell";
|
||||||
|
|
||||||
|
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(
|
export function syncShellEnvironment(
|
||||||
env: NodeJS.ProcessEnv = process.env,
|
env: NodeJS.ProcessEnv = process.env,
|
||||||
options: {
|
options: {
|
||||||
platform?: NodeJS.Platform;
|
platform?: NodeJS.Platform;
|
||||||
readEnvironment?: ShellEnvironmentReader;
|
readEnvironment?: ShellEnvironmentReader;
|
||||||
|
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||||
|
userShell?: string;
|
||||||
|
logWarning?: (message: string, error?: unknown) => void;
|
||||||
} = {},
|
} = {},
|
||||||
): void {
|
): void {
|
||||||
if ((options.platform ?? process.platform) !== "darwin") return;
|
const platform = options.platform ?? process.platform;
|
||||||
|
if (platform !== "darwin" && platform !== "linux") return;
|
||||||
|
|
||||||
|
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
|
||||||
|
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
|
||||||
|
const shellEnvironment: Partial<Record<string, string>> = {};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const shell = env.SHELL ?? "/bin/zsh";
|
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
try {
|
||||||
"PATH",
|
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
|
||||||
"SSH_AUTH_SOCK",
|
if (shellEnvironment.PATH) {
|
||||||
]);
|
break;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logWarning(`Failed to read login shell environment from ${shell}.`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (shellEnvironment.PATH) {
|
const launchctlPath =
|
||||||
env.PATH = shellEnvironment.PATH;
|
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) {
|
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
|
||||||
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,40 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
resolveDesktopUpdateChannel,
|
||||||
|
shouldAcceptDesktopUpdateForCurrentVersion,
|
||||||
|
shouldAllowDesktopPrereleaseUpdates,
|
||||||
|
} from "./updateChannel";
|
||||||
|
|
||||||
|
describe("updateChannel", () => {
|
||||||
|
it("uses the stable latest channel for plain versions", () => {
|
||||||
|
expect(resolveDesktopUpdateChannel("0.0.17")).toBe("latest");
|
||||||
|
expect(shouldAllowDesktopPrereleaseUpdates("0.0.17")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("derives the prerelease channel from the installed version", () => {
|
||||||
|
expect(resolveDesktopUpdateChannel("0.0.18-nightly.20260415")).toBe("nightly");
|
||||||
|
expect(shouldAllowDesktopPrereleaseUpdates("0.0.18-nightly.20260415")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accepts updates that stay on the same prerelease track", () => {
|
||||||
|
expect(
|
||||||
|
shouldAcceptDesktopUpdateForCurrentVersion(
|
||||||
|
"0.0.18-nightly.20260415",
|
||||||
|
"0.0.18-nightly.20260416",
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects stable releases while running a nightly build", () => {
|
||||||
|
expect(shouldAcceptDesktopUpdateForCurrentVersion("0.0.18-nightly.20260415", "0.0.17")).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects updates from a different prerelease track", () => {
|
||||||
|
expect(
|
||||||
|
shouldAcceptDesktopUpdateForCurrentVersion("0.0.18-nightly.20260415", "0.0.18-beta.1"),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
const VERSION_PRERELEASE_CHANNEL_PATTERN =
|
||||||
|
/^\d+\.\d+\.\d+(?:-([0-9A-Za-z-]+)(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||||
|
|
||||||
|
function resolvePrereleaseChannel(version: string): string | null {
|
||||||
|
const normalizedVersion = version.trim();
|
||||||
|
const match = VERSION_PRERELEASE_CHANNEL_PATTERN.exec(normalizedVersion);
|
||||||
|
const channel = match?.[1]?.trim().toLowerCase();
|
||||||
|
return channel && channel.length > 0 ? channel : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveDesktopUpdateChannel(version: string): string {
|
||||||
|
return resolvePrereleaseChannel(version) ?? "latest";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shouldAllowDesktopPrereleaseUpdates(version: string): boolean {
|
||||||
|
return resolvePrereleaseChannel(version) !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shouldAcceptDesktopUpdateForCurrentVersion(
|
||||||
|
currentVersion: string,
|
||||||
|
candidateVersion: string,
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
resolveDesktopUpdateChannel(currentVersion) === resolveDesktopUpdateChannel(candidateVersion)
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -71,10 +71,37 @@ describe("getAutoUpdateDisabledReason", () => {
|
|||||||
platform: "darwin",
|
platform: "darwin",
|
||||||
appImage: undefined,
|
appImage: undefined,
|
||||||
disabledByEnv: false,
|
disabledByEnv: false,
|
||||||
|
hasUpdateFeedConfig: true,
|
||||||
}),
|
}),
|
||||||
).toContain("packaged production builds");
|
).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", () => {
|
it("reports env-disabled auto updates", () => {
|
||||||
expect(
|
expect(
|
||||||
getAutoUpdateDisabledReason({
|
getAutoUpdateDisabledReason({
|
||||||
@@ -83,6 +110,7 @@ describe("getAutoUpdateDisabledReason", () => {
|
|||||||
platform: "darwin",
|
platform: "darwin",
|
||||||
appImage: undefined,
|
appImage: undefined,
|
||||||
disabledByEnv: true,
|
disabledByEnv: true,
|
||||||
|
hasUpdateFeedConfig: true,
|
||||||
}),
|
}),
|
||||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||||
});
|
});
|
||||||
@@ -95,6 +123,7 @@ describe("getAutoUpdateDisabledReason", () => {
|
|||||||
platform: "linux",
|
platform: "linux",
|
||||||
appImage: undefined,
|
appImage: undefined,
|
||||||
disabledByEnv: false,
|
disabledByEnv: false,
|
||||||
|
hasUpdateFeedConfig: true,
|
||||||
}),
|
}),
|
||||||
).toContain("AppImage");
|
).toContain("AppImage");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -34,7 +34,11 @@ export function getAutoUpdateDisabledReason(args: {
|
|||||||
platform: NodeJS.Platform;
|
platform: NodeJS.Platform;
|
||||||
appImage?: string | undefined;
|
appImage?: string | undefined;
|
||||||
disabledByEnv: boolean;
|
disabledByEnv: boolean;
|
||||||
|
hasUpdateFeedConfig: boolean;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
|
if (!args.hasUpdateFeedConfig) {
|
||||||
|
return "Automatic updates are not available because no update feed is configured.";
|
||||||
|
}
|
||||||
if (args.isDevelopment || !args.isPackaged) {
|
if (args.isDevelopment || !args.isPackaged) {
|
||||||
return "Automatic updates are only available in packaged production builds.";
|
return "Automatic updates are only available in packaged production builds.";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
---
|
---
|
||||||
import Layout from "../layouts/Layout.astro";
|
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.">
|
<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>
|
<h2 class="platform-name">macOS</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="download-cards">
|
<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-arch">Apple Silicon (arm64)</span>
|
||||||
<span class="card-format">.dmg</span>
|
<span class="card-format">.dmg</span>
|
||||||
</a>
|
</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-arch">Intel (x64)</span>
|
||||||
<span class="card-format">.dmg</span>
|
<span class="card-format">.dmg</span>
|
||||||
</a>
|
</a>
|
||||||
@@ -35,7 +36,7 @@ import Layout from "../layouts/Layout.astro";
|
|||||||
<h2 class="platform-name">Windows</h2>
|
<h2 class="platform-name">Windows</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="download-cards">
|
<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-arch">Windows 10, 11</span>
|
||||||
<span class="card-format">.exe</span>
|
<span class="card-format">.exe</span>
|
||||||
</a>
|
</a>
|
||||||
@@ -49,7 +50,7 @@ import Layout from "../layouts/Layout.astro";
|
|||||||
<h2 class="platform-name">Linux</h2>
|
<h2 class="platform-name">Linux</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="download-cards">
|
<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-arch">x86_64</span>
|
||||||
<span class="card-format">AppImage</span>
|
<span class="card-format">AppImage</span>
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
import fs from "node:fs";
|
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
|
||||||
import { execFileSync } from "node:child_process";
|
import { execFileSync } from "node:child_process";
|
||||||
|
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
@@ -13,9 +10,11 @@ import {
|
|||||||
import {
|
import {
|
||||||
Effect,
|
Effect,
|
||||||
Exit,
|
Exit,
|
||||||
|
FileSystem,
|
||||||
Layer,
|
Layer,
|
||||||
ManagedRuntime,
|
ManagedRuntime,
|
||||||
Option,
|
Option,
|
||||||
|
Path,
|
||||||
Ref,
|
Ref,
|
||||||
Schedule,
|
Schedule,
|
||||||
Schema,
|
Schema,
|
||||||
@@ -25,7 +24,9 @@ import {
|
|||||||
|
|
||||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||||
import { CheckpointStore } from "../src/checkpointing/Services/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 { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||||
|
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
|
||||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||||
@@ -38,16 +39,18 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
|
|||||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||||
|
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||||
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||||
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.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 { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||||
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.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 { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
||||||
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
||||||
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
||||||
@@ -66,7 +69,9 @@ import {
|
|||||||
makeTestProviderAdapterHarness,
|
makeTestProviderAdapterHarness,
|
||||||
type TestProviderAdapterHarness,
|
type TestProviderAdapterHarness,
|
||||||
} from "./TestProviderAdapter.integration.ts";
|
} from "./TestProviderAdapter.integration.ts";
|
||||||
import { ServerConfig } from "../src/config.ts";
|
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||||
|
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||||
|
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
||||||
|
|
||||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||||
return execFileSync("git", args, {
|
return execFileSync("git", args, {
|
||||||
@@ -76,14 +81,16 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function initializeGitWorkspace(cwd: string) {
|
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
|
||||||
runGit(cwd, ["init", "--initial-branch=main"]);
|
runGit(cwd, ["init", "--initial-branch=main"]);
|
||||||
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||||
runGit(cwd, ["config", "user.name", "Test User"]);
|
runGit(cwd, ["config", "user.name", "Test User"]);
|
||||||
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const { join } = yield* Path.Path;
|
||||||
|
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
|
||||||
runGit(cwd, ["add", "."]);
|
runGit(cwd, ["add", "."]);
|
||||||
runGit(cwd, ["commit", "-m", "Initial"]);
|
runGit(cwd, ["commit", "-m", "Initial"]);
|
||||||
}
|
});
|
||||||
|
|
||||||
export function gitRefExists(cwd: string, ref: string): boolean {
|
export function gitRefExists(cwd: string, ref: string): boolean {
|
||||||
try {
|
try {
|
||||||
@@ -121,7 +128,7 @@ function waitFor<A, E>(
|
|||||||
read: Effect.Effect<A, E>,
|
read: Effect.Effect<A, E>,
|
||||||
predicate: (value: A) => boolean,
|
predicate: (value: A) => boolean,
|
||||||
description: string,
|
description: string,
|
||||||
timeoutMs = 10_000,
|
timeoutMs = 40_000,
|
||||||
): Effect.Effect<A, never> {
|
): Effect.Effect<A, never> {
|
||||||
const RETRY_SIGNAL = "wait_for_retry";
|
const RETRY_SIGNAL = "wait_for_retry";
|
||||||
const retryIntervalMs = 10;
|
const retryIntervalMs = 10;
|
||||||
@@ -214,7 +221,9 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
options?: MakeOrchestrationIntegrationHarnessOptions,
|
options?: MakeOrchestrationIntegrationHarnessOptions,
|
||||||
) =>
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const sleep = (ms: number) => Effect.sleep(ms);
|
const path = yield* Path.Path;
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
|
||||||
const provider = options?.provider ?? "codex";
|
const provider = options?.provider ?? "codex";
|
||||||
const useRealCodex = options?.realCodex === true;
|
const useRealCodex = options?.realCodex === true;
|
||||||
const adapterHarness = useRealCodex
|
const adapterHarness = useRealCodex
|
||||||
@@ -231,13 +240,16 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||||
} as typeof ProviderAdapterRegistry.Service)
|
} as typeof ProviderAdapterRegistry.Service)
|
||||||
: null;
|
: null;
|
||||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||||
|
prefix: "t3-orchestration-integration-",
|
||||||
|
});
|
||||||
const workspaceDir = path.join(rootDir, "workspace");
|
const workspaceDir = path.join(rootDir, "workspace");
|
||||||
const stateDir = path.join(rootDir, "state");
|
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
|
||||||
const dbPath = path.join(stateDir, "state.sqlite");
|
Effect.provideService(Path.Path, path),
|
||||||
fs.mkdirSync(workspaceDir, { recursive: true });
|
);
|
||||||
fs.mkdirSync(stateDir, { recursive: true });
|
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
|
||||||
initializeGitWorkspace(workspaceDir);
|
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
|
||||||
|
yield* initializeGitWorkspace(workspaceDir);
|
||||||
|
|
||||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||||
@@ -262,7 +274,7 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
}),
|
}),
|
||||||
).pipe(
|
).pipe(
|
||||||
Layer.provide(makeCodexAdapterLive()),
|
Layer.provide(makeCodexAdapterLive()),
|
||||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||||
);
|
);
|
||||||
@@ -278,41 +290,75 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
Layer.provide(AnalyticsService.layerTest),
|
Layer.provide(AnalyticsService.layerTest),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||||
|
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||||
const runtimeServicesLayer = Layer.mergeAll(
|
const runtimeServicesLayer = Layer.mergeAll(
|
||||||
orchestrationLayer,
|
projectionSnapshotQueryLayer,
|
||||||
OrchestrationProjectionSnapshotQueryLive,
|
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
|
||||||
ProjectionCheckpointRepositoryLive,
|
ProjectionCheckpointRepositoryLive,
|
||||||
ProjectionPendingApprovalRepositoryLive,
|
ProjectionPendingApprovalRepositoryLive,
|
||||||
CheckpointStoreLive,
|
checkpointStoreLayer,
|
||||||
providerLayer,
|
providerLayer,
|
||||||
RuntimeReceiptBusLive,
|
RuntimeReceiptBusTest,
|
||||||
);
|
);
|
||||||
|
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
|
Layer.provideMerge(serverSettingsLayer),
|
||||||
);
|
);
|
||||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||||
Effect.succeed({ branch: input.newBranch }),
|
Effect.succeed({ branch: input.newBranch }),
|
||||||
} as unknown as GitCoreShape);
|
} as unknown as GitCoreShape);
|
||||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
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);
|
} as unknown as TextGenerationShape);
|
||||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
Layer.provideMerge(gitCoreLayer),
|
Layer.provideMerge(gitCoreLayer),
|
||||||
Layer.provideMerge(textGenerationLayer),
|
Layer.provideMerge(textGenerationLayer),
|
||||||
|
Layer.provideMerge(serverSettingsLayer),
|
||||||
);
|
);
|
||||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeServicesLayer),
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
|
Layer.provideMerge(
|
||||||
|
Layer.succeed(GitStatusBroadcaster, {
|
||||||
|
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||||
|
refreshLocalStatus: () =>
|
||||||
|
Effect.succeed({
|
||||||
|
isRepo: true,
|
||||||
|
hasOriginRemote: false,
|
||||||
|
isDefaultBranch: true,
|
||||||
|
branch: "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(gitCoreLayer),
|
||||||
|
Layer.provide(NodeServices.layer),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(WorkspacePathsLive),
|
||||||
);
|
);
|
||||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||||
Layer.provideMerge(runtimeIngestionLayer),
|
Layer.provideMerge(runtimeIngestionLayer),
|
||||||
Layer.provideMerge(providerCommandReactorLayer),
|
Layer.provideMerge(providerCommandReactorLayer),
|
||||||
Layer.provideMerge(checkpointReactorLayer),
|
Layer.provideMerge(checkpointReactorLayer),
|
||||||
);
|
);
|
||||||
const layer = orchestrationReactorLayer.pipe(
|
const layer = Layer.empty.pipe(
|
||||||
|
Layer.provideMerge(runtimeServicesLayer),
|
||||||
|
Layer.provideMerge(orchestrationReactorLayer),
|
||||||
Layer.provide(persistenceLayer),
|
Layer.provide(persistenceLayer),
|
||||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||||
|
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -346,13 +392,13 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
|
|
||||||
const scope = yield* Scope.make("sequential");
|
const scope = yield* Scope.make("sequential");
|
||||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
|
||||||
).pipe(Effect.orDie);
|
).pipe(Effect.orDie);
|
||||||
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
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),
|
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||||
).pipe(Effect.forkIn(scope));
|
).pipe(Effect.forkIn(scope));
|
||||||
yield* sleep(10);
|
yield* Effect.sleep(10);
|
||||||
|
|
||||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||||
threadId,
|
threadId,
|
||||||
@@ -392,7 +438,7 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
) =>
|
) =>
|
||||||
waitFor(
|
waitFor(
|
||||||
pendingApprovalRepository
|
pendingApprovalRepository
|
||||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
|
||||||
.pipe(
|
.pipe(
|
||||||
Effect.map((row) =>
|
Effect.map((row) =>
|
||||||
Option.match(row, {
|
Option.match(row, {
|
||||||
@@ -469,13 +515,7 @@ export const makeOrchestrationIntegrationHarness = (
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
yield* shutdown.pipe(
|
yield* shutdown;
|
||||||
Effect.ensuring(
|
|
||||||
Effect.sync(() => {
|
|
||||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -289,7 +289,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
|||||||
|
|
||||||
state.turnCount += 1;
|
state.turnCount += 1;
|
||||||
const turnCount = state.turnCount;
|
const turnCount = state.turnCount;
|
||||||
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
|
const turnId = TurnId.make(`turn-${turnCount}`);
|
||||||
|
|
||||||
const response = state.queuedResponses.shift();
|
const response = state.queuedResponses.shift();
|
||||||
if (!response) {
|
if (!response) {
|
||||||
@@ -307,7 +307,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
|||||||
...(fixtureEvent as Record<string, unknown>),
|
...(fixtureEvent as Record<string, unknown>),
|
||||||
eventId: randomUUID(),
|
eventId: randomUUID(),
|
||||||
provider,
|
provider,
|
||||||
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
|
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
};
|
};
|
||||||
rawEvent.threadId = state.snapshot.threadId;
|
rawEvent.threadId = state.snapshot.threadId;
|
||||||
@@ -363,7 +363,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
|||||||
if (deferredTurnCompletedEvents.length === 0) {
|
if (deferredTurnCompletedEvents.length === 0) {
|
||||||
yield* emit({
|
yield* emit({
|
||||||
type: "turn.completed",
|
type: "turn.completed",
|
||||||
eventId: EventId.makeUnsafe(randomUUID()),
|
eventId: EventId.make(randomUUID()),
|
||||||
provider,
|
provider,
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
threadId: state.snapshot.threadId,
|
threadId: state.snapshot.threadId,
|
||||||
|
|||||||
@@ -5,14 +5,14 @@ const PROVIDER = "codex" as const;
|
|||||||
const SESSION_ID = "fixture-session";
|
const SESSION_ID = "fixture-session";
|
||||||
const THREAD_ID = "fixture-thread";
|
const THREAD_ID = "fixture-thread";
|
||||||
const TURN_ID = "fixture-turn";
|
const TURN_ID = "fixture-turn";
|
||||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
const REQUEST_ID = RuntimeRequestId.make("req-1");
|
||||||
|
|
||||||
function baseEvent(
|
function baseEvent(
|
||||||
eventId: string,
|
eventId: string,
|
||||||
createdAt: string,
|
createdAt: string,
|
||||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||||
return {
|
return {
|
||||||
eventId: EventId.makeUnsafe(eventId),
|
eventId: EventId.make(eventId),
|
||||||
provider: PROVIDER,
|
provider: PROVIDER,
|
||||||
sessionId: SESSION_ID,
|
sessionId: SESSION_ID,
|
||||||
createdAt,
|
createdAt,
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
ProjectId,
|
ProjectId,
|
||||||
ProviderKind,
|
ProviderKind,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
|
ModelSelection,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { assert, it } from "@effect/vitest";
|
import { assert, it } from "@effect/vitest";
|
||||||
import { Effect, Option, Schema } from "effect";
|
import { Effect, Option, Schema } from "effect";
|
||||||
@@ -27,15 +28,15 @@ import type {
|
|||||||
CheckpointDiffFinalizedReceipt,
|
CheckpointDiffFinalizedReceipt,
|
||||||
TurnProcessingQuiescedReceipt,
|
TurnProcessingQuiescedReceipt,
|
||||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
|
||||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
const asEventId = (value: string): EventId => EventId.make(value);
|
||||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||||
ApprovalRequestId.makeUnsafe(value);
|
|
||||||
|
|
||||||
const PROJECT_ID = asProjectId("project-1");
|
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 FIXTURE_TURN_ID = "fixture-turn";
|
||||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||||
type IntegrationProvider = ProviderKind;
|
type IntegrationProvider = ProviderKind;
|
||||||
@@ -51,13 +52,11 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
|
|||||||
},
|
},
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
const sleep = (ms: number) => Effect.sleep(ms);
|
|
||||||
|
|
||||||
function waitForSync<A>(
|
function waitForSync<A>(
|
||||||
read: () => A,
|
read: () => A,
|
||||||
predicate: (value: A) => boolean,
|
predicate: (value: A) => boolean,
|
||||||
description: string,
|
description: string,
|
||||||
timeoutMs = 3000,
|
timeoutMs = 10_000,
|
||||||
): Effect.Effect<A, never> {
|
): Effect.Effect<A, never> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const deadline = Date.now() + timeoutMs;
|
const deadline = Date.now() + timeoutMs;
|
||||||
@@ -70,7 +69,7 @@ function waitForSync<A>(
|
|||||||
if (Date.now() >= deadline) {
|
if (Date.now() >= deadline) {
|
||||||
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
|
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
|
||||||
}
|
}
|
||||||
yield* sleep(10);
|
yield* Effect.sleep(10);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -91,7 +90,7 @@ function withHarness<A, E>(
|
|||||||
makeOrchestrationIntegrationHarness({ provider }),
|
makeOrchestrationIntegrationHarness({ provider }),
|
||||||
use,
|
use,
|
||||||
(harness) => harness.dispose,
|
(harness) => harness.dispose,
|
||||||
);
|
).pipe(Effect.provide(NodeServices.layer));
|
||||||
}
|
}
|
||||||
|
|
||||||
function withRealCodexHarness<A, E>(
|
function withRealCodexHarness<A, E>(
|
||||||
@@ -101,7 +100,7 @@ function withRealCodexHarness<A, E>(
|
|||||||
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
||||||
use,
|
use,
|
||||||
(harness) => harness.dispose,
|
(harness) => harness.dispose,
|
||||||
);
|
).pipe(Effect.provide(NodeServices.layer));
|
||||||
}
|
}
|
||||||
|
|
||||||
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||||
@@ -112,21 +111,27 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
|||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "project.create",
|
type: "project.create",
|
||||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
commandId: CommandId.make("cmd-project-create"),
|
||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Project",
|
title: "Integration Project",
|
||||||
workspaceRoot: harness.workspaceDir,
|
workspaceRoot: harness.workspaceDir,
|
||||||
defaultModel,
|
defaultModelSelection: {
|
||||||
|
provider,
|
||||||
|
model: defaultModel,
|
||||||
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "thread.create",
|
type: "thread.create",
|
||||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
commandId: CommandId.make("cmd-thread-create"),
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Thread",
|
title: "Integration Thread",
|
||||||
model: defaultModel,
|
modelSelection: {
|
||||||
|
provider,
|
||||||
|
model: defaultModel,
|
||||||
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -140,11 +145,11 @@ const startTurn = (input: {
|
|||||||
readonly commandId: string;
|
readonly commandId: string;
|
||||||
readonly messageId: string;
|
readonly messageId: string;
|
||||||
readonly text: string;
|
readonly text: string;
|
||||||
readonly provider?: IntegrationProvider;
|
readonly modelSelection?: ModelSelection;
|
||||||
}) =>
|
}) =>
|
||||||
input.harness.engine.dispatch({
|
input.harness.engine.dispatch({
|
||||||
type: "thread.turn.start",
|
type: "thread.turn.start",
|
||||||
commandId: CommandId.makeUnsafe(input.commandId),
|
commandId: CommandId.make(input.commandId),
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
message: {
|
message: {
|
||||||
messageId: asMessageId(input.messageId),
|
messageId: asMessageId(input.messageId),
|
||||||
@@ -152,7 +157,11 @@ const startTurn = (input: {
|
|||||||
text: input.text,
|
text: input.text,
|
||||||
attachments: [],
|
attachments: [],
|
||||||
},
|
},
|
||||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
...(input.modelSelection !== undefined
|
||||||
|
? {
|
||||||
|
modelSelection: input.modelSelection,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
@@ -251,21 +260,27 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
|||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "project.create",
|
type: "project.create",
|
||||||
commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
|
commandId: CommandId.make("cmd-project-create-real-codex"),
|
||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Project",
|
title: "Integration Project",
|
||||||
workspaceRoot: harness.workspaceDir,
|
workspaceRoot: harness.workspaceDir,
|
||||||
defaultModel: "gpt-5.3-codex",
|
defaultModelSelection: {
|
||||||
|
provider: "codex",
|
||||||
|
model: "gpt-5.3-codex",
|
||||||
|
},
|
||||||
createdAt,
|
createdAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "thread.create",
|
type: "thread.create",
|
||||||
commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
|
commandId: CommandId.make("cmd-thread-create-real-codex"),
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
projectId: PROJECT_ID,
|
projectId: PROJECT_ID,
|
||||||
title: "Integration Thread",
|
title: "Integration Thread",
|
||||||
model: "gpt-5.3-codex",
|
modelSelection: {
|
||||||
|
provider: "codex",
|
||||||
|
model: "gpt-5.3-codex",
|
||||||
|
},
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -275,7 +290,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
|||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "thread.turn.start",
|
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,
|
threadId: THREAD_ID,
|
||||||
message: {
|
message: {
|
||||||
messageId: asMessageId("msg-real-codex-1"),
|
messageId: asMessageId("msg-real-codex-1"),
|
||||||
@@ -302,7 +317,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
|||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "thread.turn.start",
|
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,
|
threadId: THREAD_ID,
|
||||||
message: {
|
message: {
|
||||||
messageId: asMessageId("msg-real-codex-2"),
|
messageId: asMessageId("msg-real-codex-2"),
|
||||||
@@ -567,7 +582,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
|||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "thread.approval.respond",
|
type: "thread.approval.respond",
|
||||||
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
|
commandId: CommandId.make("cmd-approval-respond"),
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
requestId: APPROVAL_REQUEST_ID,
|
requestId: APPROVAL_REQUEST_ID,
|
||||||
decision: "accept",
|
decision: "accept",
|
||||||
@@ -799,7 +814,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
|||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "thread.checkpoint.revert",
|
type: "thread.checkpoint.revert",
|
||||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
|
commandId: CommandId.make("cmd-checkpoint-revert"),
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnCount: 1,
|
turnCount: 1,
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
@@ -859,7 +874,7 @@ it.live(
|
|||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "thread.checkpoint.revert",
|
type: "thread.checkpoint.revert",
|
||||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
|
commandId: CommandId.make("cmd-checkpoint-revert-no-session"),
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnCount: 0,
|
turnCount: 0,
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
@@ -923,7 +938,10 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
|||||||
commandId: "cmd-turn-start-claude-initial",
|
commandId: "cmd-turn-start-claude-initial",
|
||||||
messageId: "msg-user-claude-initial",
|
messageId: "msg-user-claude-initial",
|
||||||
text: "Use Claude",
|
text: "Use Claude",
|
||||||
provider: "claudeAgent",
|
modelSelection: {
|
||||||
|
provider: "claudeAgent",
|
||||||
|
model: "claude-sonnet-4-6",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const thread = yield* harness.waitForThread(
|
const thread = yield* harness.waitForThread(
|
||||||
@@ -977,7 +995,10 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
|||||||
commandId: "cmd-turn-start-claude-recover-1",
|
commandId: "cmd-turn-start-claude-recover-1",
|
||||||
messageId: "msg-user-claude-recover-1",
|
messageId: "msg-user-claude-recover-1",
|
||||||
text: "Before restart",
|
text: "Before restart",
|
||||||
provider: "claudeAgent",
|
modelSelection: {
|
||||||
|
provider: "claudeAgent",
|
||||||
|
model: "claude-sonnet-4-6",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
yield* harness.waitForThread(
|
yield* harness.waitForThread(
|
||||||
@@ -1084,7 +1105,10 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
|||||||
commandId: "cmd-turn-start-claude-approval",
|
commandId: "cmd-turn-start-claude-approval",
|
||||||
messageId: "msg-user-claude-approval",
|
messageId: "msg-user-claude-approval",
|
||||||
text: "Need approval",
|
text: "Need approval",
|
||||||
provider: "claudeAgent",
|
modelSelection: {
|
||||||
|
provider: "claudeAgent",
|
||||||
|
model: "claude-sonnet-4-6",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
||||||
@@ -1094,7 +1118,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
|||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "thread.approval.respond",
|
type: "thread.approval.respond",
|
||||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
commandId: CommandId.make("cmd-claude-approval-respond"),
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
requestId: APPROVAL_REQUEST_ID,
|
requestId: APPROVAL_REQUEST_ID,
|
||||||
decision: "accept",
|
decision: "accept",
|
||||||
@@ -1153,7 +1177,10 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
|||||||
commandId: "cmd-turn-start-claude-interrupt",
|
commandId: "cmd-turn-start-claude-interrupt",
|
||||||
messageId: "msg-user-claude-interrupt",
|
messageId: "msg-user-claude-interrupt",
|
||||||
text: "Start long turn",
|
text: "Start long turn",
|
||||||
provider: "claudeAgent",
|
modelSelection: {
|
||||||
|
provider: "claudeAgent",
|
||||||
|
model: "claude-sonnet-4-6",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const thread = yield* harness.waitForThread(
|
const thread = yield* harness.waitForThread(
|
||||||
@@ -1164,7 +1191,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
|||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "thread.turn.interrupt",
|
type: "thread.turn.interrupt",
|
||||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
commandId: CommandId.make("cmd-turn-interrupt-claude"),
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
});
|
});
|
||||||
@@ -1223,7 +1250,10 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
|||||||
commandId: "cmd-turn-start-claude-revert-1",
|
commandId: "cmd-turn-start-claude-revert-1",
|
||||||
messageId: "msg-user-claude-revert-1",
|
messageId: "msg-user-claude-revert-1",
|
||||||
text: "First Claude edit",
|
text: "First Claude edit",
|
||||||
provider: "claudeAgent",
|
modelSelection: {
|
||||||
|
provider: "claudeAgent",
|
||||||
|
model: "claude-sonnet-4-6",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
yield* harness.waitForThread(
|
yield* harness.waitForThread(
|
||||||
@@ -1278,7 +1308,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
|||||||
|
|
||||||
yield* harness.engine.dispatch({
|
yield* harness.engine.dispatch({
|
||||||
type: "thread.checkpoint.revert",
|
type: "thread.checkpoint.revert",
|
||||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
|
||||||
threadId: THREAD_ID,
|
threadId: THREAD_ID,
|
||||||
turnCount: 1,
|
turnCount: 1,
|
||||||
createdAt: nowIso(),
|
createdAt: nowIso(),
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||||
import { ThreadId } from "@t3tools/contracts";
|
import { ThreadId } from "@t3tools/contracts";
|
||||||
|
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
|
||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { it, assert } from "@effect/vitest";
|
import { it, assert } from "@effect/vitest";
|
||||||
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
||||||
@@ -12,6 +13,7 @@ import {
|
|||||||
ProviderService,
|
ProviderService,
|
||||||
type ProviderServiceShape,
|
type ProviderServiceShape,
|
||||||
} from "../src/provider/Services/ProviderService.ts";
|
} from "../src/provider/Services/ProviderService.ts";
|
||||||
|
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||||
@@ -60,6 +62,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
|||||||
const shared = Layer.mergeAll(
|
const shared = Layer.mergeAll(
|
||||||
directoryLayer,
|
directoryLayer,
|
||||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||||
|
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||||
AnalyticsService.layerTest,
|
AnalyticsService.layerTest,
|
||||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||||
|
|
||||||
@@ -83,6 +86,7 @@ const collectEventsDuring = <A, E, R>(
|
|||||||
Effect.forkScoped,
|
Effect.forkScoped,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
yield* Effect.sleep("50 millis");
|
||||||
yield* action;
|
yield* action;
|
||||||
|
|
||||||
return yield* Effect.forEach(
|
return yield* Effect.forEach(
|
||||||
@@ -101,7 +105,6 @@ const runTurn = (input: {
|
|||||||
}) =>
|
}) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||||
|
|
||||||
return yield* collectEventsDuring(
|
return yield* collectEventsDuring(
|
||||||
input.provider.streamEvents,
|
input.provider.streamEvents,
|
||||||
input.response.events.length,
|
input.response.events.length,
|
||||||
@@ -113,21 +116,18 @@ const runTurn = (input: {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it.effect("replays typed runtime fixture events", () =>
|
it.live("replays typed runtime fixture events", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fixture = yield* makeIntegrationFixture;
|
const fixture = yield* makeIntegrationFixture;
|
||||||
|
|
||||||
yield* Effect.gen(function* () {
|
yield* Effect.gen(function* () {
|
||||||
const provider = yield* ProviderService;
|
const provider = yield* ProviderService;
|
||||||
const session = yield* provider.startSession(
|
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||||
ThreadId.makeUnsafe("thread-integration-typed"),
|
threadId: ThreadId.make("thread-integration-typed"),
|
||||||
{
|
provider: "codex",
|
||||||
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
|
cwd: fixture.cwd,
|
||||||
provider: "codex",
|
runtimeMode: "full-access",
|
||||||
cwd: fixture.cwd,
|
});
|
||||||
runtimeMode: "full-access",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
assert.equal((session.threadId ?? "").length > 0, true);
|
assert.equal((session.threadId ?? "").length > 0, true);
|
||||||
|
|
||||||
const observedEvents = yield* runTurn({
|
const observedEvents = yield* runTurn({
|
||||||
@@ -146,7 +146,7 @@ it.effect("replays typed runtime fixture events", () =>
|
|||||||
}).pipe(Effect.provide(NodeServices.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* () {
|
Effect.gen(function* () {
|
||||||
const fixture = yield* makeIntegrationFixture;
|
const fixture = yield* makeIntegrationFixture;
|
||||||
const { join } = yield* Path.Path;
|
const { join } = yield* Path.Path;
|
||||||
@@ -154,15 +154,12 @@ it.effect("replays file-changing fixture turn events", () =>
|
|||||||
|
|
||||||
yield* Effect.gen(function* () {
|
yield* Effect.gen(function* () {
|
||||||
const provider = yield* ProviderService;
|
const provider = yield* ProviderService;
|
||||||
const session = yield* provider.startSession(
|
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||||
ThreadId.makeUnsafe("thread-integration-tools"),
|
threadId: ThreadId.make("thread-integration-tools"),
|
||||||
{
|
provider: "codex",
|
||||||
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
|
cwd: fixture.cwd,
|
||||||
provider: "codex",
|
runtimeMode: "full-access",
|
||||||
cwd: fixture.cwd,
|
});
|
||||||
runtimeMode: "full-access",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
assert.equal((session.threadId ?? "").length > 0, true);
|
assert.equal((session.threadId ?? "").length > 0, true);
|
||||||
|
|
||||||
const observedEvents = yield* runTurn({
|
const observedEvents = yield* runTurn({
|
||||||
@@ -185,7 +182,7 @@ it.effect("replays file-changing fixture turn events", () =>
|
|||||||
}).pipe(Effect.provide(NodeServices.layer)),
|
}).pipe(Effect.provide(NodeServices.layer)),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("runs multi-turn tool/approval flow", () =>
|
it.live("runs multi-turn tool/approval flow", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fixture = yield* makeIntegrationFixture;
|
const fixture = yield* makeIntegrationFixture;
|
||||||
const { join } = yield* Path.Path;
|
const { join } = yield* Path.Path;
|
||||||
@@ -193,15 +190,12 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
|||||||
|
|
||||||
yield* Effect.gen(function* () {
|
yield* Effect.gen(function* () {
|
||||||
const provider = yield* ProviderService;
|
const provider = yield* ProviderService;
|
||||||
const session = yield* provider.startSession(
|
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||||
ThreadId.makeUnsafe("thread-integration-multi"),
|
threadId: ThreadId.make("thread-integration-multi"),
|
||||||
{
|
provider: "codex",
|
||||||
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
|
cwd: fixture.cwd,
|
||||||
provider: "codex",
|
runtimeMode: "full-access",
|
||||||
cwd: fixture.cwd,
|
});
|
||||||
runtimeMode: "full-access",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
assert.equal((session.threadId ?? "").length > 0, true);
|
assert.equal((session.threadId ?? "").length > 0, true);
|
||||||
|
|
||||||
const firstTurnEvents = yield* runTurn({
|
const firstTurnEvents = yield* runTurn({
|
||||||
@@ -239,7 +233,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
|||||||
}).pipe(Effect.provide(NodeServices.layer)),
|
}).pipe(Effect.provide(NodeServices.layer)),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("rolls back provider conversation state only", () =>
|
it.live("rolls back provider conversation state only", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fixture = yield* makeIntegrationFixture;
|
const fixture = yield* makeIntegrationFixture;
|
||||||
const { join } = yield* Path.Path;
|
const { join } = yield* Path.Path;
|
||||||
@@ -247,15 +241,12 @@ it.effect("rolls back provider conversation state only", () =>
|
|||||||
|
|
||||||
yield* Effect.gen(function* () {
|
yield* Effect.gen(function* () {
|
||||||
const provider = yield* ProviderService;
|
const provider = yield* ProviderService;
|
||||||
const session = yield* provider.startSession(
|
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||||
ThreadId.makeUnsafe("thread-integration-rollback"),
|
threadId: ThreadId.make("thread-integration-rollback"),
|
||||||
{
|
provider: "codex",
|
||||||
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
|
cwd: fixture.cwd,
|
||||||
provider: "codex",
|
runtimeMode: "full-access",
|
||||||
cwd: fixture.cwd,
|
});
|
||||||
runtimeMode: "full-access",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
assert.equal((session.threadId ?? "").length > 0, true);
|
assert.equal((session.threadId ?? "").length > 0, true);
|
||||||
|
|
||||||
yield* runTurn({
|
yield* runTurn({
|
||||||
|
|||||||
@@ -1,35 +1,36 @@
|
|||||||
{
|
{
|
||||||
"name": "t3",
|
"name": "t3",
|
||||||
"version": "0.0.10",
|
"version": "0.0.17",
|
||||||
|
"license": "MIT",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://github.com/pingdotgg/t3code",
|
"url": "https://github.com/pingdotgg/t3code",
|
||||||
"directory": "apps/server"
|
"directory": "apps/server"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"t3": "./dist/index.mjs"
|
"t3": "./dist/bin.mjs"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist"
|
"dist"
|
||||||
],
|
],
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "bun run src/index.ts",
|
"dev": "bun run src/bin.ts",
|
||||||
"build": "node scripts/cli.ts build",
|
"build": "node scripts/cli.ts build",
|
||||||
"start": "node dist/index.mjs",
|
"start": "node dist/bin.mjs",
|
||||||
"prepare": "effect-language-service patch",
|
"prepare": "effect-language-service patch",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "vitest run"
|
"test": "vitest run"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||||
|
"@effect/platform-bun": "catalog:",
|
||||||
"@effect/platform-node": "catalog:",
|
"@effect/platform-node": "catalog:",
|
||||||
"@effect/sql-sqlite-bun": "catalog:",
|
"@effect/sql-sqlite-bun": "catalog:",
|
||||||
"@pierre/diffs": "^1.1.0-beta.16",
|
"@pierre/diffs": "^1.1.0-beta.16",
|
||||||
"effect": "catalog:",
|
"effect": "catalog:",
|
||||||
"node-pty": "^1.1.0",
|
"node-pty": "^1.1.0",
|
||||||
"open": "^10.1.0",
|
"open": "^10.1.0"
|
||||||
"ws": "^8.18.0"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@effect/language-service": "catalog:",
|
"@effect/language-service": "catalog:",
|
||||||
@@ -39,7 +40,6 @@
|
|||||||
"@t3tools/web": "workspace:*",
|
"@t3tools/web": "workspace:*",
|
||||||
"@types/bun": "catalog:",
|
"@types/bun": "catalog:",
|
||||||
"@types/node": "catalog:",
|
"@types/node": "catalog:",
|
||||||
"@types/ws": "^8.5.13",
|
|
||||||
"tsdown": "catalog:",
|
"tsdown": "catalog:",
|
||||||
"typescript": "catalog:",
|
"typescript": "catalog:",
|
||||||
"vitest": "catalog:"
|
"vitest": "catalog:"
|
||||||
|
|||||||
@@ -14,6 +14,22 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog
|
|||||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||||
import serverPackageJson 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")<{
|
class CliError extends Data.TaggedError("CliError")<{
|
||||||
readonly message: string;
|
readonly message: string;
|
||||||
readonly cause?: unknown;
|
readonly cause?: unknown;
|
||||||
@@ -177,7 +193,7 @@ const publishCmd = Command.make(
|
|||||||
const backupPath = `${packageJsonPath}.bak`;
|
const backupPath = `${packageJsonPath}.bak`;
|
||||||
|
|
||||||
// Assert build assets exist
|
// 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);
|
const abs = path.join(serverDir, relPath);
|
||||||
if (!(yield* fs.exists(abs))) {
|
if (!(yield* fs.exists(abs))) {
|
||||||
return yield* new CliError({
|
return yield* new CliError({
|
||||||
@@ -192,7 +208,7 @@ const publishCmd = Command.make(
|
|||||||
// Resolve catalog dependencies before any file mutations. If this throws,
|
// Resolve catalog dependencies before any file mutations. If this throws,
|
||||||
// acquire fails and no release hook runs, so filesystem must still be untouched.
|
// acquire fails and no release hook runs, so filesystem must still be untouched.
|
||||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||||
const pkg = {
|
const pkg: PackageJson = {
|
||||||
name: serverPackageJson.name,
|
name: serverPackageJson.name,
|
||||||
repository: serverPackageJson.repository,
|
repository: serverPackageJson.repository,
|
||||||
bin: serverPackageJson.bin,
|
bin: serverPackageJson.bin,
|
||||||
@@ -200,7 +216,8 @@ const publishCmd = Command.make(
|
|||||||
version,
|
version,
|
||||||
engines: serverPackageJson.engines,
|
engines: serverPackageJson.engines,
|
||||||
files: serverPackageJson.files,
|
files: serverPackageJson.files,
|
||||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
dependencies: serverPackageJson.dependencies,
|
||||||
|
overrides: rootPackageJson.overrides,
|
||||||
};
|
};
|
||||||
|
|
||||||
pkg.dependencies = resolveCatalogDependencies(
|
pkg.dependencies = resolveCatalogDependencies(
|
||||||
@@ -208,6 +225,11 @@ const publishCmd = Command.make(
|
|||||||
rootPackageJson.workspaces.catalog,
|
rootPackageJson.workspaces.catalog,
|
||||||
"apps/server dependencies",
|
"apps/server dependencies",
|
||||||
);
|
);
|
||||||
|
pkg.overrides = resolveCatalogDependencies(
|
||||||
|
pkg.overrides,
|
||||||
|
rootPackageJson.workspaces.catalog,
|
||||||
|
"root overrides",
|
||||||
|
);
|
||||||
|
|
||||||
const original = yield* fs.readFileString(packageJsonPath);
|
const original = yield* fs.readFileString(packageJsonPath);
|
||||||
yield* fs.writeFileString(backupPath, original);
|
yield* fs.writeFileString(backupPath, original);
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function resolveAttachmentRelativePath(input: {
|
export function resolveAttachmentRelativePath(input: {
|
||||||
readonly stateDir: string;
|
readonly attachmentsDir: string;
|
||||||
readonly relativePath: string;
|
readonly relativePath: string;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
||||||
@@ -19,7 +19,7 @@ export function resolveAttachmentRelativePath(input: {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
|
const attachmentsRoot = path.resolve(input.attachmentsDir);
|
||||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -44,34 +44,32 @@ describe("attachmentStore", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||||
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||||
try {
|
try {
|
||||||
const attachmentId = "thread-1-attachment";
|
const attachmentId = "thread-1-attachment";
|
||||||
const attachmentsDir = path.join(stateDir, "attachments");
|
|
||||||
fs.mkdirSync(attachmentsDir, { recursive: true });
|
|
||||||
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||||
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
||||||
|
|
||||||
const resolved = resolveAttachmentPathById({
|
const resolved = resolveAttachmentPathById({
|
||||||
stateDir,
|
attachmentsDir,
|
||||||
attachmentId,
|
attachmentId,
|
||||||
});
|
});
|
||||||
expect(resolved).toBe(pngPath);
|
expect(resolved).toBe(pngPath);
|
||||||
} finally {
|
} finally {
|
||||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns null when no attachment file exists for the id", () => {
|
it("returns null when no attachment file exists for the id", () => {
|
||||||
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||||
try {
|
try {
|
||||||
const resolved = resolveAttachmentPathById({
|
const resolved = resolveAttachmentPathById({
|
||||||
stateDir,
|
attachmentsDir,
|
||||||
attachmentId: "thread-1-missing",
|
attachmentId: "thread-1-missing",
|
||||||
});
|
});
|
||||||
expect(resolved).toBeNull();
|
expect(resolved).toBeNull();
|
||||||
} finally {
|
} finally {
|
||||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
fs.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -66,17 +66,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function resolveAttachmentPath(input: {
|
export function resolveAttachmentPath(input: {
|
||||||
readonly stateDir: string;
|
readonly attachmentsDir: string;
|
||||||
readonly attachment: ChatAttachment;
|
readonly attachment: ChatAttachment;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
return resolveAttachmentRelativePath({
|
return resolveAttachmentRelativePath({
|
||||||
stateDir: input.stateDir,
|
attachmentsDir: input.attachmentsDir,
|
||||||
relativePath: attachmentRelativePath(input.attachment),
|
relativePath: attachmentRelativePath(input.attachment),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveAttachmentPathById(input: {
|
export function resolveAttachmentPathById(input: {
|
||||||
readonly stateDir: string;
|
readonly attachmentsDir: string;
|
||||||
readonly attachmentId: string;
|
readonly attachmentId: string;
|
||||||
}): string | null {
|
}): string | null {
|
||||||
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
||||||
@@ -85,7 +85,7 @@ export function resolveAttachmentPathById(input: {
|
|||||||
}
|
}
|
||||||
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
||||||
const maybePath = resolveAttachmentRelativePath({
|
const maybePath = resolveAttachmentRelativePath({
|
||||||
stateDir: input.stateDir,
|
attachmentsDir: input.attachmentsDir,
|
||||||
relativePath: `${normalizedId}${extension}`,
|
relativePath: `${normalizedId}${extension}`,
|
||||||
});
|
});
|
||||||
if (maybePath && existsSync(maybePath)) {
|
if (maybePath && existsSync(maybePath)) {
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { expect, it } from "@effect/vitest";
|
||||||
|
import { Effect, Layer } from "effect";
|
||||||
|
|
||||||
|
import { 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,176 @@
|
|||||||
|
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,
|
||||||
|
AuthControlPlaneShape,
|
||||||
|
DEFAULT_SESSION_SUBJECT,
|
||||||
|
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 { SessionRole } from "./SessionCredentialService";
|
||||||
|
|
||||||
|
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";
|
||||||
|
|
||||||
|
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,17 @@
|
|||||||
|
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 { cli } from "./cli";
|
||||||
|
import { version } from "../package.json" with { type: "json" };
|
||||||
|
|
||||||
|
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||||
|
|
||||||
|
Command.run(cli, { version }).pipe(
|
||||||
|
Effect.scoped,
|
||||||
|
Effect.provide(CliRuntimeLayer),
|
||||||
|
NodeRuntime.runMain,
|
||||||
|
);
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import * as NFS from "node:fs";
|
||||||
|
import * as path from "node:path";
|
||||||
|
import { execFileSync, spawn } from "node:child_process";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { assert, it } from "@effect/vitest";
|
||||||
|
import { FileSystem, Schema } from "effect";
|
||||||
|
import * as Duration from "effect/Duration";
|
||||||
|
import * as Effect from "effect/Effect";
|
||||||
|
import * as Fiber from "effect/Fiber";
|
||||||
|
import { TestClock } from "effect/testing";
|
||||||
|
import { vi } from "vitest";
|
||||||
|
|
||||||
|
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
||||||
|
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||||
|
|
||||||
|
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
||||||
|
|
||||||
|
vi.mock("node:fs", async (importOriginal) => {
|
||||||
|
const actual = await importOriginal<typeof import("node:fs")>();
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
openSync: (...args: Parameters<typeof actual.openSync>) => {
|
||||||
|
const [filePath, flags] = args;
|
||||||
|
if (
|
||||||
|
typeof filePath === "string" &&
|
||||||
|
filePath === openSyncInterceptor.failPath &&
|
||||||
|
flags === "r"
|
||||||
|
) {
|
||||||
|
const error = new Error("no such device or address");
|
||||||
|
Object.assign(error, { code: "ENXIO" });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return (actual.openSync as (...a: typeof args) => number)(...args);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
|
||||||
|
|
||||||
|
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
|
||||||
|
it.effect("uses platform-specific fd paths", () =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
assert.equal(resolveFdPath(3, "linux"), "/proc/self/fd/3");
|
||||||
|
assert.equal(resolveFdPath(3, "darwin"), "/dev/fd/3");
|
||||||
|
assert.equal(resolveFdPath(3, "win32"), undefined);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("reads a bootstrap envelope from a provided fd", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||||
|
|
||||||
|
yield* fs.writeFileString(
|
||||||
|
filePath,
|
||||||
|
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||||
|
mode: "desktop",
|
||||||
|
})}\n`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const fd = yield* Effect.acquireRelease(
|
||||||
|
Effect.sync(() => NFS.openSync(filePath, "r")),
|
||||||
|
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||||
|
assertSome(payload, {
|
||||||
|
mode: "desktop",
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("falls back to reading the inherited fd when path duplication fails", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||||
|
|
||||||
|
yield* fs.writeFileString(
|
||||||
|
filePath,
|
||||||
|
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
|
||||||
|
mode: "desktop",
|
||||||
|
})}\n`,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
|
||||||
|
// so the stream owns the fd lifecycle and closes it asynchronously on end.
|
||||||
|
// Attempting to also close it synchronously in a finalizer races with the
|
||||||
|
// stream's async close and produces an uncaught EBADF.
|
||||||
|
const fd = NFS.openSync(filePath, "r");
|
||||||
|
|
||||||
|
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
|
||||||
|
try {
|
||||||
|
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||||
|
assertSome(payload, {
|
||||||
|
mode: "desktop",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
openSyncInterceptor.failPath = null;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("returns none when the fd is unavailable", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fd = NFS.openSync("/dev/null", "r");
|
||||||
|
NFS.closeSync(fd);
|
||||||
|
|
||||||
|
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
|
||||||
|
assertNone(payload);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("returns none when the bootstrap read times out before any value arrives", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" });
|
||||||
|
const fifoPath = path.join(tempDir, "bootstrap.pipe");
|
||||||
|
|
||||||
|
yield* Effect.sync(() => execFileSync("mkfifo", [fifoPath]));
|
||||||
|
|
||||||
|
const _writer = yield* Effect.acquireRelease(
|
||||||
|
Effect.sync(() =>
|
||||||
|
spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
|
||||||
|
stdio: ["ignore", "ignore", "ignore"],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(writer) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
writer.kill("SIGKILL");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const fd = yield* Effect.acquireRelease(
|
||||||
|
Effect.sync(() => NFS.openSync(fifoPath, "r")),
|
||||||
|
(fd) => Effect.sync(() => NFS.closeSync(fd)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
|
||||||
|
timeoutMs: 100,
|
||||||
|
}).pipe(Effect.forkScoped);
|
||||||
|
|
||||||
|
yield* Effect.yieldNow;
|
||||||
|
yield* TestClock.adjust(Duration.millis(100));
|
||||||
|
|
||||||
|
const payload = yield* Fiber.join(fiber);
|
||||||
|
assertNone(payload);
|
||||||
|
}).pipe(Effect.provide(TestClock.layer())),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
import * as NFS from "node:fs";
|
||||||
|
import * as Net from "node:net";
|
||||||
|
import * as readline from "node:readline";
|
||||||
|
import type { Readable } from "node:stream";
|
||||||
|
|
||||||
|
import { Data, Effect, Option, Predicate, Result, Schema } from "effect";
|
||||||
|
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||||
|
|
||||||
|
class BootstrapError extends Data.TaggedError("BootstrapError")<{
|
||||||
|
readonly message: string;
|
||||||
|
readonly cause?: unknown;
|
||||||
|
}> {}
|
||||||
|
|
||||||
|
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
|
||||||
|
schema: Schema.Codec<A, I>,
|
||||||
|
fd: number,
|
||||||
|
options?: {
|
||||||
|
timeoutMs?: number;
|
||||||
|
},
|
||||||
|
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
|
||||||
|
const fdReady = yield* isFdReady(fd);
|
||||||
|
if (!fdReady) return Option.none();
|
||||||
|
|
||||||
|
const stream = yield* makeBootstrapInputStream(fd);
|
||||||
|
|
||||||
|
const timeoutMs = options?.timeoutMs ?? 1000;
|
||||||
|
|
||||||
|
return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
|
||||||
|
const input = readline.createInterface({
|
||||||
|
input: stream,
|
||||||
|
crlfDelay: Infinity,
|
||||||
|
});
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
stream.removeListener("error", handleError);
|
||||||
|
input.removeListener("line", handleLine);
|
||||||
|
input.removeListener("close", handleClose);
|
||||||
|
input.close();
|
||||||
|
stream.destroy();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleError = (error: Error) => {
|
||||||
|
if (isUnavailableBootstrapFdError(error)) {
|
||||||
|
resume(Effect.succeedNone);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
resume(
|
||||||
|
Effect.fail(
|
||||||
|
new BootstrapError({
|
||||||
|
message: "Failed to read bootstrap envelope.",
|
||||||
|
cause: error,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLine = (line: string) => {
|
||||||
|
const parsed = decodeJsonResult(schema)(line);
|
||||||
|
if (Result.isSuccess(parsed)) {
|
||||||
|
resume(Effect.succeedSome(parsed.success));
|
||||||
|
} else {
|
||||||
|
resume(
|
||||||
|
Effect.fail(
|
||||||
|
new BootstrapError({
|
||||||
|
message: "Failed to decode bootstrap envelope.",
|
||||||
|
cause: parsed.failure,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
resume(Effect.succeedNone);
|
||||||
|
};
|
||||||
|
|
||||||
|
stream.once("error", handleError);
|
||||||
|
input.once("line", handleLine);
|
||||||
|
input.once("close", handleClose);
|
||||||
|
|
||||||
|
return Effect.sync(cleanup);
|
||||||
|
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
|
||||||
|
});
|
||||||
|
|
||||||
|
const isUnavailableBootstrapFdError = Predicate.compose(
|
||||||
|
Predicate.hasProperty("code"),
|
||||||
|
(_) => _.code === "EBADF" || _.code === "ENOENT",
|
||||||
|
);
|
||||||
|
|
||||||
|
const isFdReady = (fd: number) =>
|
||||||
|
Effect.try({
|
||||||
|
try: () => NFS.fstatSync(fd),
|
||||||
|
catch: (error) =>
|
||||||
|
new BootstrapError({
|
||||||
|
message: "Failed to stat bootstrap fd.",
|
||||||
|
cause: error,
|
||||||
|
}),
|
||||||
|
}).pipe(
|
||||||
|
Effect.as(true),
|
||||||
|
Effect.catchIf(
|
||||||
|
(error) => isUnavailableBootstrapFdError(error.cause),
|
||||||
|
() => Effect.succeed(false),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const makeBootstrapInputStream = (fd: number) =>
|
||||||
|
Effect.try<Readable, BootstrapError>({
|
||||||
|
try: () => {
|
||||||
|
const fdPath = resolveFdPath(fd);
|
||||||
|
if (fdPath === undefined) {
|
||||||
|
return makeDirectBootstrapStream(fd);
|
||||||
|
}
|
||||||
|
|
||||||
|
let streamFd: number | undefined;
|
||||||
|
try {
|
||||||
|
streamFd = NFS.openSync(fdPath, "r");
|
||||||
|
return NFS.createReadStream("", {
|
||||||
|
fd: streamFd,
|
||||||
|
encoding: "utf8",
|
||||||
|
autoClose: true,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (isBootstrapFdPathDuplicationError(error)) {
|
||||||
|
if (streamFd !== undefined) {
|
||||||
|
NFS.closeSync(streamFd);
|
||||||
|
}
|
||||||
|
return makeDirectBootstrapStream(fd);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
catch: (error) =>
|
||||||
|
new BootstrapError({
|
||||||
|
message: "Failed to duplicate bootstrap fd.",
|
||||||
|
cause: error,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const makeDirectBootstrapStream = (fd: number): Readable => {
|
||||||
|
try {
|
||||||
|
return NFS.createReadStream("", {
|
||||||
|
fd,
|
||||||
|
encoding: "utf8",
|
||||||
|
autoClose: true,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
const stream = new Net.Socket({
|
||||||
|
fd,
|
||||||
|
readable: true,
|
||||||
|
writable: false,
|
||||||
|
});
|
||||||
|
stream.setEncoding("utf8");
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isBootstrapFdPathDuplicationError = Predicate.compose(
|
||||||
|
Predicate.hasProperty("code"),
|
||||||
|
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
|
||||||
|
);
|
||||||
|
|
||||||
|
export function resolveFdPath(
|
||||||
|
fd: number,
|
||||||
|
platform: NodeJS.Platform = process.platform,
|
||||||
|
): string | undefined {
|
||||||
|
if (platform === "linux") {
|
||||||
|
return `/proc/self/fd/${fd}`;
|
||||||
|
}
|
||||||
|
if (platform === "win32") {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return `/dev/fd/${fd}`;
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Schema } from "effect";
|
import { Schema } from "effect";
|
||||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||||
import { GitCommandError } from "../git/Errors.ts";
|
import { GitCommandError } from "@t3tools/contracts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||||
|
|||||||
@@ -1,79 +1,38 @@
|
|||||||
import {
|
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||||
CheckpointRef,
|
import { Effect, Layer, Option } from "effect";
|
||||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
ProjectId,
|
|
||||||
ThreadId,
|
|
||||||
TurnId,
|
|
||||||
type OrchestrationReadModel,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { Effect, Layer } from "effect";
|
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
import {
|
||||||
|
ProjectionSnapshotQuery,
|
||||||
|
type ProjectionThreadCheckpointContext,
|
||||||
|
} from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||||
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
|
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
|
||||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||||
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
|
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
|
||||||
|
|
||||||
function makeSnapshot(input: {
|
function makeThreadCheckpointContext(input: {
|
||||||
readonly projectId: ProjectId;
|
readonly projectId: ProjectId;
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
readonly workspaceRoot: string;
|
readonly workspaceRoot: string;
|
||||||
readonly worktreePath: string | null;
|
readonly worktreePath: string | null;
|
||||||
readonly checkpointTurnCount: number;
|
readonly checkpointTurnCount: number;
|
||||||
readonly checkpointRef: CheckpointRef;
|
readonly checkpointRef: CheckpointRef;
|
||||||
}): OrchestrationReadModel {
|
}): ProjectionThreadCheckpointContext {
|
||||||
return {
|
return {
|
||||||
snapshotSequence: 0,
|
threadId: input.threadId,
|
||||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
projectId: input.projectId,
|
||||||
projects: [
|
workspaceRoot: input.workspaceRoot,
|
||||||
|
worktreePath: input.worktreePath,
|
||||||
|
checkpoints: [
|
||||||
{
|
{
|
||||||
id: input.projectId,
|
turnId: TurnId.make("turn-1"),
|
||||||
title: "Project",
|
checkpointTurnCount: input.checkpointTurnCount,
|
||||||
workspaceRoot: input.workspaceRoot,
|
checkpointRef: input.checkpointRef,
|
||||||
defaultModel: null,
|
status: "ready",
|
||||||
scripts: [],
|
files: [],
|
||||||
createdAt: "2026-01-01T00:00:00.000Z",
|
assistantMessageId: null,
|
||||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
completedAt: "2026-01-01T00:00:00.000Z",
|
||||||
deletedAt: null,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
threads: [
|
|
||||||
{
|
|
||||||
id: input.threadId,
|
|
||||||
projectId: input.projectId,
|
|
||||||
title: "Thread",
|
|
||||||
model: "gpt-5-codex",
|
|
||||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
branch: null,
|
|
||||||
worktreePath: input.worktreePath,
|
|
||||||
latestTurn: {
|
|
||||||
turnId: TurnId.makeUnsafe("turn-1"),
|
|
||||||
state: "completed",
|
|
||||||
requestedAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
startedAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
completedAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
assistantMessageId: null,
|
|
||||||
},
|
|
||||||
createdAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
deletedAt: null,
|
|
||||||
messages: [],
|
|
||||||
activities: [],
|
|
||||||
proposedPlans: [],
|
|
||||||
checkpoints: [
|
|
||||||
{
|
|
||||||
turnId: TurnId.makeUnsafe("turn-1"),
|
|
||||||
checkpointTurnCount: input.checkpointTurnCount,
|
|
||||||
checkpointRef: input.checkpointRef,
|
|
||||||
status: "ready",
|
|
||||||
files: [],
|
|
||||||
assistantMessageId: null,
|
|
||||||
completedAt: "2026-01-01T00:00:00.000Z",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
session: null,
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
@@ -81,8 +40,8 @@ function makeSnapshot(input: {
|
|||||||
|
|
||||||
describe("CheckpointDiffQueryLive", () => {
|
describe("CheckpointDiffQueryLive", () => {
|
||||||
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
|
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
|
||||||
const projectId = ProjectId.makeUnsafe("project-1");
|
const projectId = ProjectId.make("project-1");
|
||||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
const threadId = ThreadId.make("thread-1");
|
||||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||||
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
|
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
|
||||||
const diffCheckpointsCalls: Array<{
|
const diffCheckpointsCalls: Array<{
|
||||||
@@ -91,7 +50,7 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
}> = [];
|
}> = [];
|
||||||
|
|
||||||
const snapshot = makeSnapshot({
|
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||||
projectId,
|
projectId,
|
||||||
threadId,
|
threadId,
|
||||||
workspaceRoot: "/tmp/workspace",
|
workspaceRoot: "/tmp/workspace",
|
||||||
@@ -121,7 +80,17 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(ProjectionSnapshotQuery, {
|
Layer.succeed(ProjectionSnapshotQuery, {
|
||||||
getSnapshot: () => Effect.succeed(snapshot),
|
getSnapshot: () =>
|
||||||
|
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||||
|
getShellSnapshot: () =>
|
||||||
|
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||||
|
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||||
|
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||||
|
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||||
|
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||||
|
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||||
|
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||||
|
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -155,7 +124,7 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("fails when the thread is missing from the snapshot", async () => {
|
it("fails when the thread is missing from the snapshot", async () => {
|
||||||
const threadId = ThreadId.makeUnsafe("thread-missing");
|
const threadId = ThreadId.make("thread-missing");
|
||||||
|
|
||||||
const checkpointStore: CheckpointStoreShape = {
|
const checkpointStore: CheckpointStoreShape = {
|
||||||
isGitRepository: () => Effect.succeed(true),
|
isGitRepository: () => Effect.succeed(true),
|
||||||
@@ -171,12 +140,16 @@ describe("CheckpointDiffQueryLive", () => {
|
|||||||
Layer.provideMerge(
|
Layer.provideMerge(
|
||||||
Layer.succeed(ProjectionSnapshotQuery, {
|
Layer.succeed(ProjectionSnapshotQuery, {
|
||||||
getSnapshot: () =>
|
getSnapshot: () =>
|
||||||
Effect.succeed({
|
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||||
snapshotSequence: 0,
|
getShellSnapshot: () =>
|
||||||
projects: [],
|
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||||
threads: [],
|
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||||
} satisfies OrchestrationReadModel),
|
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||||
|
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||||
|
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||||
|
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||||
|
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,11 +4,11 @@ import {
|
|||||||
type OrchestrationGetFullThreadDiffResult,
|
type OrchestrationGetFullThreadDiffResult,
|
||||||
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
|
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect, Layer, Schema } from "effect";
|
import { Effect, Layer, Option, Schema } from "effect";
|
||||||
|
|
||||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||||
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
|
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
|
||||||
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
|
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||||
import {
|
import {
|
||||||
CheckpointDiffQuery,
|
CheckpointDiffQuery,
|
||||||
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
|
|||||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||||
const checkpointStore = yield* CheckpointStore;
|
const checkpointStore = yield* CheckpointStore;
|
||||||
|
|
||||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
|
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||||
Effect.gen(function* () {
|
function* (input) {
|
||||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||||
|
|
||||||
if (input.fromTurnCount === input.toTurnCount) {
|
if (input.fromTurnCount === input.toTurnCount) {
|
||||||
@@ -41,16 +41,17 @@ const make = Effect.gen(function* () {
|
|||||||
return emptyDiff;
|
return emptyDiff;
|
||||||
}
|
}
|
||||||
|
|
||||||
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
|
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
|
||||||
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
|
input.threadId,
|
||||||
if (!thread) {
|
);
|
||||||
|
if (Option.isNone(threadContext)) {
|
||||||
return yield* new CheckpointInvariantError({
|
return yield* new CheckpointInvariantError({
|
||||||
operation,
|
operation,
|
||||||
detail: `Thread '${input.threadId}' not found.`,
|
detail: `Thread '${input.threadId}' not found.`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const maxTurnCount = thread.checkpoints.reduce(
|
const maxTurnCount = threadContext.value.checkpoints.reduce(
|
||||||
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
|
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
|
||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
@@ -62,10 +63,7 @@ const make = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||||
thread,
|
|
||||||
projects: snapshot.projects,
|
|
||||||
});
|
|
||||||
if (!workspaceCwd) {
|
if (!workspaceCwd) {
|
||||||
return yield* new CheckpointInvariantError({
|
return yield* new CheckpointInvariantError({
|
||||||
operation,
|
operation,
|
||||||
@@ -76,7 +74,7 @@ const make = Effect.gen(function* () {
|
|||||||
const fromCheckpointRef =
|
const fromCheckpointRef =
|
||||||
input.fromTurnCount === 0
|
input.fromTurnCount === 0
|
||||||
? checkpointRefForThreadTurn(input.threadId, 0)
|
? checkpointRefForThreadTurn(input.threadId, 0)
|
||||||
: thread.checkpoints.find(
|
: threadContext.value.checkpoints.find(
|
||||||
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
||||||
)?.checkpointRef;
|
)?.checkpointRef;
|
||||||
if (!fromCheckpointRef) {
|
if (!fromCheckpointRef) {
|
||||||
@@ -87,7 +85,7 @@ const make = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const toCheckpointRef = thread.checkpoints.find(
|
const toCheckpointRef = threadContext.value.checkpoints.find(
|
||||||
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
||||||
)?.checkpointRef;
|
)?.checkpointRef;
|
||||||
if (!toCheckpointRef) {
|
if (!toCheckpointRef) {
|
||||||
@@ -149,7 +147,8 @@ const make = Effect.gen(function* () {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return turnDiff;
|
return turnDiff;
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
||||||
input: OrchestrationGetFullThreadDiffInput,
|
input: OrchestrationGetFullThreadDiffInput,
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { it } from "@effect/vitest";
|
||||||
|
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||||
|
import { describe, expect } from "vitest";
|
||||||
|
|
||||||
|
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||||
|
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
||||||
|
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||||
|
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||||
|
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||||
|
import { GitCommandError } from "@t3tools/contracts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { ThreadId } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||||
|
prefix: "t3-checkpoint-store-test-",
|
||||||
|
});
|
||||||
|
const GitCoreTestLayer = GitCoreLive.pipe(
|
||||||
|
Layer.provide(ServerConfigLayer),
|
||||||
|
Layer.provide(NodeServices.layer),
|
||||||
|
);
|
||||||
|
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
|
||||||
|
Layer.provide(GitCoreTestLayer),
|
||||||
|
Layer.provide(NodeServices.layer),
|
||||||
|
);
|
||||||
|
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
|
||||||
|
|
||||||
|
function makeTmpDir(
|
||||||
|
prefix = "checkpoint-store-test-",
|
||||||
|
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeTextFile(
|
||||||
|
filePath: string,
|
||||||
|
contents: string,
|
||||||
|
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
yield* fileSystem.writeFileString(filePath, contents);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function git(
|
||||||
|
cwd: string,
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
): Effect.Effect<string, GitCommandError, GitCore> {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const gitCore = yield* GitCore;
|
||||||
|
const result = yield* gitCore.execute({
|
||||||
|
operation: "CheckpointStore.test.git",
|
||||||
|
cwd,
|
||||||
|
args,
|
||||||
|
timeoutMs: 10_000,
|
||||||
|
});
|
||||||
|
return result.stdout.trim();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function initRepoWithCommit(
|
||||||
|
cwd: string,
|
||||||
|
): Effect.Effect<
|
||||||
|
void,
|
||||||
|
GitCommandError | PlatformError.PlatformError,
|
||||||
|
GitCore | FileSystem.FileSystem
|
||||||
|
> {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const core = yield* GitCore;
|
||||||
|
yield* core.initRepo({ cwd });
|
||||||
|
yield* git(cwd, ["config", "user.email", "[email protected]"]);
|
||||||
|
yield* git(cwd, ["config", "user.name", "Test"]);
|
||||||
|
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
|
||||||
|
yield* git(cwd, ["add", "."]);
|
||||||
|
yield* git(cwd, ["commit", "-m", "initial commit"]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildLargeText(lineCount = 5_000): string {
|
||||||
|
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
|
||||||
|
.join("\n")
|
||||||
|
.concat("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||||
|
describe("diffCheckpoints", () => {
|
||||||
|
it.effect("returns full oversized checkpoint diffs without truncation", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tmp = yield* makeTmpDir();
|
||||||
|
yield* initRepoWithCommit(tmp);
|
||||||
|
const checkpointStore = yield* CheckpointStore;
|
||||||
|
const threadId = ThreadId.make("thread-checkpoint-store");
|
||||||
|
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||||
|
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||||
|
|
||||||
|
yield* checkpointStore.captureCheckpoint({
|
||||||
|
cwd: tmp,
|
||||||
|
checkpointRef: fromCheckpointRef,
|
||||||
|
});
|
||||||
|
yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText());
|
||||||
|
yield* checkpointStore.captureCheckpoint({
|
||||||
|
cwd: tmp,
|
||||||
|
checkpointRef: toCheckpointRef,
|
||||||
|
});
|
||||||
|
|
||||||
|
const diff = yield* checkpointStore.diffCheckpoints({
|
||||||
|
cwd: tmp,
|
||||||
|
fromCheckpointRef,
|
||||||
|
toCheckpointRef,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(diff).toContain("diff --git");
|
||||||
|
expect(diff).not.toContain("[truncated]");
|
||||||
|
expect(diff).toContain("+line 04999");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -14,16 +14,15 @@ import { randomUUID } from "node:crypto";
|
|||||||
import { Effect, Layer, FileSystem, Path } from "effect";
|
import { Effect, Layer, FileSystem, Path } from "effect";
|
||||||
|
|
||||||
import { CheckpointInvariantError } from "../Errors.ts";
|
import { CheckpointInvariantError } from "../Errors.ts";
|
||||||
import { GitCommandError } from "../../git/Errors.ts";
|
import { GitCommandError } from "@t3tools/contracts";
|
||||||
import { GitServiceLive } from "../../git/Layers/GitService.ts";
|
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||||
import { GitService } from "../../git/Services/GitService.ts";
|
|
||||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||||
import { CheckpointRef } from "@t3tools/contracts";
|
import { CheckpointRef } from "@t3tools/contracts";
|
||||||
|
|
||||||
const makeCheckpointStore = Effect.gen(function* () {
|
const makeCheckpointStore = Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
const git = yield* GitService;
|
const git = yield* GitCore;
|
||||||
|
|
||||||
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||||
git
|
git
|
||||||
@@ -87,139 +86,140 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
Effect.catch(() => Effect.succeed(false)),
|
Effect.catch(() => Effect.succeed(false)),
|
||||||
);
|
);
|
||||||
|
|
||||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
|
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
|
||||||
Effect.gen(function* () {
|
"captureCheckpoint",
|
||||||
const operation = "CheckpointStore.captureCheckpoint";
|
)(function* (input) {
|
||||||
|
const operation = "CheckpointStore.captureCheckpoint";
|
||||||
|
|
||||||
yield* Effect.acquireUseRelease(
|
yield* Effect.acquireUseRelease(
|
||||||
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
||||||
(tempDir) =>
|
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
|
||||||
Effect.gen(function* () {
|
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
const commitEnv: NodeJS.ProcessEnv = {
|
||||||
const commitEnv: NodeJS.ProcessEnv = {
|
...process.env,
|
||||||
...process.env,
|
GIT_INDEX_FILE: tempIndexPath,
|
||||||
GIT_INDEX_FILE: tempIndexPath,
|
GIT_AUTHOR_NAME: "T3 Code",
|
||||||
GIT_AUTHOR_NAME: "T3 Code",
|
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
GIT_COMMITTER_NAME: "T3 Code",
|
||||||
GIT_COMMITTER_NAME: "T3 Code",
|
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
};
|
||||||
};
|
|
||||||
|
|
||||||
const headExists = yield* hasHeadCommit(input.cwd);
|
const headExists = yield* hasHeadCommit(input.cwd);
|
||||||
if (headExists) {
|
if (headExists) {
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["read-tree", "HEAD"],
|
args: ["read-tree", "HEAD"],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["add", "-A", "--", "."],
|
args: ["add", "-A", "--", "."],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
|
|
||||||
const writeTreeResult = yield* git.execute({
|
const writeTreeResult = yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["write-tree"],
|
args: ["write-tree"],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
const treeOid = writeTreeResult.stdout.trim();
|
const treeOid = writeTreeResult.stdout.trim();
|
||||||
if (treeOid.length === 0) {
|
if (treeOid.length === 0) {
|
||||||
return yield* new GitCommandError({
|
return yield* new GitCommandError({
|
||||||
operation,
|
operation,
|
||||||
command: "git write-tree",
|
command: "git write-tree",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
detail: "git write-tree returned an empty tree oid.",
|
detail: "git write-tree returned an empty tree oid.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||||
const commitTreeResult = yield* git.execute({
|
const commitTreeResult = yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["commit-tree", treeOid, "-m", message],
|
args: ["commit-tree", treeOid, "-m", message],
|
||||||
env: commitEnv,
|
env: commitEnv,
|
||||||
});
|
});
|
||||||
const commitOid = commitTreeResult.stdout.trim();
|
const commitOid = commitTreeResult.stdout.trim();
|
||||||
if (commitOid.length === 0) {
|
if (commitOid.length === 0) {
|
||||||
return yield* new GitCommandError({
|
return yield* new GitCommandError({
|
||||||
operation,
|
operation,
|
||||||
command: "git commit-tree",
|
command: "git commit-tree",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
detail: "git commit-tree returned an empty commit oid.",
|
detail: "git commit-tree returned an empty commit oid.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["update-ref", input.checkpointRef, commitOid],
|
args: ["update-ref", input.checkpointRef, commitOid],
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
||||||
).pipe(
|
).pipe(
|
||||||
Effect.catchTags({
|
Effect.catchTags({
|
||||||
PlatformError: (error) =>
|
PlatformError: (error) =>
|
||||||
Effect.fail(
|
Effect.fail(
|
||||||
new CheckpointInvariantError({
|
new CheckpointInvariantError({
|
||||||
operation: "CheckpointStore.captureCheckpoint",
|
operation: "CheckpointStore.captureCheckpoint",
|
||||||
detail: "Failed to capture checkpoint.",
|
detail: "Failed to capture checkpoint.",
|
||||||
cause: error,
|
cause: error,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
|
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
|
||||||
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
||||||
Effect.map((commit) => commit !== null),
|
Effect.map((commit) => commit !== null),
|
||||||
);
|
);
|
||||||
|
|
||||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
|
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
|
||||||
Effect.gen(function* () {
|
"restoreCheckpoint",
|
||||||
const operation = "CheckpointStore.restoreCheckpoint";
|
)(function* (input) {
|
||||||
|
const operation = "CheckpointStore.restoreCheckpoint";
|
||||||
|
|
||||||
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
||||||
|
|
||||||
if (!commitOid && input.fallbackToHead === true) {
|
if (!commitOid && input.fallbackToHead === true) {
|
||||||
commitOid = yield* resolveHeadCommit(input.cwd);
|
commitOid = yield* resolveHeadCommit(input.cwd);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!commitOid) {
|
if (!commitOid) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||||
});
|
});
|
||||||
yield* git.execute({
|
yield* git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["clean", "-fd", "--", "."],
|
args: ["clean", "-fd", "--", "."],
|
||||||
});
|
|
||||||
|
|
||||||
const headExists = yield* hasHeadCommit(input.cwd);
|
|
||||||
if (headExists) {
|
|
||||||
yield* git.execute({
|
|
||||||
operation,
|
|
||||||
cwd: input.cwd,
|
|
||||||
args: ["reset", "--quiet", "--", "."],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
|
const headExists = yield* hasHeadCommit(input.cwd);
|
||||||
Effect.gen(function* () {
|
if (headExists) {
|
||||||
|
yield* git.execute({
|
||||||
|
operation,
|
||||||
|
cwd: input.cwd,
|
||||||
|
args: ["reset", "--quiet", "--", "."],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
|
||||||
|
function* (input) {
|
||||||
const operation = "CheckpointStore.diffCheckpoints";
|
const operation = "CheckpointStore.diffCheckpoints";
|
||||||
|
|
||||||
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
||||||
@@ -248,24 +248,26 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return result.stdout;
|
return result.stdout;
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
|
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
|
||||||
Effect.gen(function* () {
|
"deleteCheckpointRefs",
|
||||||
const operation = "CheckpointStore.deleteCheckpointRefs";
|
)(function* (input) {
|
||||||
|
const operation = "CheckpointStore.deleteCheckpointRefs";
|
||||||
|
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
input.checkpointRefs,
|
input.checkpointRefs,
|
||||||
(checkpointRef) =>
|
(checkpointRef) =>
|
||||||
git.execute({
|
git.execute({
|
||||||
operation,
|
operation,
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
args: ["update-ref", "-d", checkpointRef],
|
args: ["update-ref", "-d", checkpointRef],
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
}),
|
}),
|
||||||
{ discard: true },
|
{ discard: true },
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
isGitRepository,
|
isGitRepository,
|
||||||
@@ -277,6 +279,4 @@ const makeCheckpointStore = Effect.gen(function* () {
|
|||||||
} satisfies CheckpointStoreShape;
|
} satisfies CheckpointStoreShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
|
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
|
||||||
Layer.provideMerge(GitServiceLive),
|
|
||||||
);
|
|
||||||
@@ -12,7 +12,7 @@ import type {
|
|||||||
OrchestrationGetTurnDiffInput,
|
OrchestrationGetTurnDiffInput,
|
||||||
OrchestrationGetTurnDiffResult,
|
OrchestrationGetTurnDiffResult,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { ServiceMap } from "effect";
|
import { Context } from "effect";
|
||||||
import type { Effect } from "effect";
|
import type { Effect } from "effect";
|
||||||
|
|
||||||
import type { CheckpointServiceError } from "../Errors.ts";
|
import type { CheckpointServiceError } from "../Errors.ts";
|
||||||
@@ -43,7 +43,7 @@ export interface CheckpointDiffQueryShape {
|
|||||||
/**
|
/**
|
||||||
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
|
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
|
||||||
*/
|
*/
|
||||||
export class CheckpointDiffQuery extends ServiceMap.Service<
|
export class CheckpointDiffQuery extends Context.Service<
|
||||||
CheckpointDiffQuery,
|
CheckpointDiffQuery,
|
||||||
CheckpointDiffQueryShape
|
CheckpointDiffQueryShape
|
||||||
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
|
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
|
||||||
@@ -5,12 +5,12 @@
|
|||||||
* workspace thread timeline. It does not store user-facing checkpoint metadata
|
* workspace thread timeline. It does not store user-facing checkpoint metadata
|
||||||
* and does not coordinate provider conversation rollback.
|
* and does not coordinate provider conversation rollback.
|
||||||
*
|
*
|
||||||
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
|
* Uses Effect `Context.Service` for dependency injection and exposes typed
|
||||||
* domain errors for checkpoint storage operations.
|
* domain errors for checkpoint storage operations.
|
||||||
*
|
*
|
||||||
* @module CheckpointStore
|
* @module CheckpointStore
|
||||||
*/
|
*/
|
||||||
import { ServiceMap } from "effect";
|
import { Context } from "effect";
|
||||||
import type { Effect } from "effect";
|
import type { Effect } from "effect";
|
||||||
|
|
||||||
import type { CheckpointStoreError } from "../Errors.ts";
|
import type { CheckpointStoreError } from "../Errors.ts";
|
||||||
@@ -95,6 +95,6 @@ export interface CheckpointStoreShape {
|
|||||||
/**
|
/**
|
||||||
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
|
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
|
||||||
*/
|
*/
|
||||||
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
|
export class CheckpointStore extends Context.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||||
"t3/checkpointing/Services/CheckpointStore",
|
"t3/checkpointing/Services/CheckpointStore",
|
||||||
) {}
|
) {}
|
||||||
@@ -4,7 +4,7 @@ import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
|
|||||||
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
||||||
|
|
||||||
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
|
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
|
||||||
return CheckpointRef.makeUnsafe(
|
return CheckpointRef.make(
|
||||||
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
|
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,528 @@
|
|||||||
|
import os from "node:os";
|
||||||
|
|
||||||
|
import { assert, expect, it } from "@effect/vitest";
|
||||||
|
import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect";
|
||||||
|
|
||||||
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { deriveServerPaths } from "./config";
|
||||||
|
import { resolveServerConfig } from "./cli";
|
||||||
|
|
||||||
|
it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||||
|
const defaultObservabilityConfig = {
|
||||||
|
traceMinLevel: "Info",
|
||||||
|
traceTimingEnabled: true,
|
||||||
|
traceBatchWindowMs: 200,
|
||||||
|
traceMaxBytes: 10 * 1024 * 1024,
|
||||||
|
traceMaxFiles: 10,
|
||||||
|
otlpTracesUrl: undefined,
|
||||||
|
otlpMetricsUrl: undefined,
|
||||||
|
otlpExportIntervalMs: 10_000,
|
||||||
|
otlpServiceName: "t3-server",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
|
||||||
|
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
|
||||||
|
const { fd } = yield* fs.open(filePath, { flag: "r" });
|
||||||
|
return fd;
|
||||||
|
});
|
||||||
|
|
||||||
|
it.effect("falls back to effect/config values when flags are omitted", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const { join } = yield* Path.Path;
|
||||||
|
const baseDir = join(os.tmpdir(), "t3-cli-config-env-base");
|
||||||
|
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
|
||||||
|
const resolved = yield* resolveServerConfig(
|
||||||
|
{
|
||||||
|
mode: Option.none(),
|
||||||
|
port: Option.none(),
|
||||||
|
host: Option.none(),
|
||||||
|
baseDir: Option.none(),
|
||||||
|
cwd: Option.none(),
|
||||||
|
devUrl: Option.none(),
|
||||||
|
noBrowser: Option.none(),
|
||||||
|
bootstrapFd: Option.none(),
|
||||||
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
|
logWebSocketEvents: Option.none(),
|
||||||
|
},
|
||||||
|
Option.none(),
|
||||||
|
).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
Layer.mergeAll(
|
||||||
|
ConfigProvider.layer(
|
||||||
|
ConfigProvider.fromEnv({
|
||||||
|
env: {
|
||||||
|
T3CODE_LOG_LEVEL: "Warn",
|
||||||
|
T3CODE_MODE: "desktop",
|
||||||
|
T3CODE_PORT: "4001",
|
||||||
|
T3CODE_HOST: "0.0.0.0",
|
||||||
|
T3CODE_HOME: baseDir,
|
||||||
|
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||||
|
T3CODE_NO_BROWSER: "true",
|
||||||
|
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||||
|
T3CODE_LOG_WS_EVENTS: "true",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
NetService.layer,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(resolved).toEqual({
|
||||||
|
logLevel: "Warn",
|
||||||
|
...defaultObservabilityConfig,
|
||||||
|
mode: "desktop",
|
||||||
|
port: 4001,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
baseDir,
|
||||||
|
...derivedPaths,
|
||||||
|
host: "0.0.0.0",
|
||||||
|
staticDir: undefined,
|
||||||
|
devUrl: new URL("http://127.0.0.1:5173"),
|
||||||
|
noBrowser: true,
|
||||||
|
startupPresentation: "browser",
|
||||||
|
desktopBootstrapToken: undefined,
|
||||||
|
autoBootstrapProjectFromCwd: false,
|
||||||
|
logWebSocketEvents: true,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("uses CLI flags when provided", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const { join } = yield* Path.Path;
|
||||||
|
const baseDir = join(os.tmpdir(), "t3-cli-config-flags-base");
|
||||||
|
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||||
|
const resolved = yield* resolveServerConfig(
|
||||||
|
{
|
||||||
|
mode: Option.some("web"),
|
||||||
|
port: Option.some(8788),
|
||||||
|
host: Option.some("127.0.0.1"),
|
||||||
|
baseDir: Option.some(baseDir),
|
||||||
|
cwd: Option.none(),
|
||||||
|
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||||
|
noBrowser: Option.some(true),
|
||||||
|
bootstrapFd: Option.none(),
|
||||||
|
autoBootstrapProjectFromCwd: Option.some(true),
|
||||||
|
logWebSocketEvents: Option.some(true),
|
||||||
|
},
|
||||||
|
Option.some("Debug"),
|
||||||
|
).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
Layer.mergeAll(
|
||||||
|
ConfigProvider.layer(
|
||||||
|
ConfigProvider.fromEnv({
|
||||||
|
env: {
|
||||||
|
T3CODE_LOG_LEVEL: "Warn",
|
||||||
|
T3CODE_MODE: "desktop",
|
||||||
|
T3CODE_PORT: "4001",
|
||||||
|
T3CODE_HOST: "0.0.0.0",
|
||||||
|
T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
|
||||||
|
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||||
|
T3CODE_NO_BROWSER: "false",
|
||||||
|
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||||
|
T3CODE_LOG_WS_EVENTS: "false",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
NetService.layer,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(resolved).toEqual({
|
||||||
|
logLevel: "Debug",
|
||||||
|
...defaultObservabilityConfig,
|
||||||
|
mode: "web",
|
||||||
|
port: 8788,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
baseDir,
|
||||||
|
...derivedPaths,
|
||||||
|
host: "127.0.0.1",
|
||||||
|
staticDir: undefined,
|
||||||
|
devUrl: new URL("http://127.0.0.1:4173"),
|
||||||
|
noBrowser: true,
|
||||||
|
startupPresentation: "browser",
|
||||||
|
desktopBootstrapToken: undefined,
|
||||||
|
autoBootstrapProjectFromCwd: true,
|
||||||
|
logWebSocketEvents: true,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const { join } = yield* Path.Path;
|
||||||
|
const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags");
|
||||||
|
const fd = yield* openBootstrapFd({
|
||||||
|
noBrowser: true,
|
||||||
|
autoBootstrapProjectFromCwd: true,
|
||||||
|
logWebSocketEvents: true,
|
||||||
|
});
|
||||||
|
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||||
|
|
||||||
|
const resolved = yield* resolveServerConfig(
|
||||||
|
{
|
||||||
|
mode: Option.some("web"),
|
||||||
|
port: Option.some(8788),
|
||||||
|
host: Option.some("127.0.0.1"),
|
||||||
|
baseDir: Option.some(baseDir),
|
||||||
|
cwd: Option.none(),
|
||||||
|
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||||
|
noBrowser: Option.some(false),
|
||||||
|
bootstrapFd: Option.none(),
|
||||||
|
autoBootstrapProjectFromCwd: Option.some(false),
|
||||||
|
logWebSocketEvents: Option.some(false),
|
||||||
|
},
|
||||||
|
Option.none(),
|
||||||
|
).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
Layer.mergeAll(
|
||||||
|
ConfigProvider.layer(
|
||||||
|
ConfigProvider.fromEnv({
|
||||||
|
env: {
|
||||||
|
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||||
|
T3CODE_NO_BROWSER: "true",
|
||||||
|
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||||
|
T3CODE_LOG_WS_EVENTS: "true",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
NetService.layer,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(resolved).toEqual({
|
||||||
|
logLevel: "Info",
|
||||||
|
...defaultObservabilityConfig,
|
||||||
|
mode: "web",
|
||||||
|
port: 8788,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
baseDir,
|
||||||
|
...derivedPaths,
|
||||||
|
host: "127.0.0.1",
|
||||||
|
staticDir: undefined,
|
||||||
|
devUrl: new URL("http://127.0.0.1:4173"),
|
||||||
|
noBrowser: false,
|
||||||
|
startupPresentation: "browser",
|
||||||
|
desktopBootstrapToken: undefined,
|
||||||
|
autoBootstrapProjectFromCwd: false,
|
||||||
|
logWebSocketEvents: false,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const { join } = yield* Path.Path;
|
||||||
|
const baseDir = "/tmp/t3-bootstrap-home";
|
||||||
|
const fd = yield* openBootstrapFd({
|
||||||
|
mode: "desktop",
|
||||||
|
port: 4888,
|
||||||
|
host: "127.0.0.2",
|
||||||
|
t3Home: baseDir,
|
||||||
|
devUrl: "http://127.0.0.1:5173",
|
||||||
|
noBrowser: true,
|
||||||
|
autoBootstrapProjectFromCwd: false,
|
||||||
|
logWebSocketEvents: true,
|
||||||
|
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||||
|
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||||
|
});
|
||||||
|
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
|
||||||
|
|
||||||
|
const resolved = yield* resolveServerConfig(
|
||||||
|
{
|
||||||
|
mode: Option.none(),
|
||||||
|
port: Option.none(),
|
||||||
|
host: Option.none(),
|
||||||
|
baseDir: Option.none(),
|
||||||
|
cwd: Option.none(),
|
||||||
|
devUrl: Option.none(),
|
||||||
|
noBrowser: Option.none(),
|
||||||
|
bootstrapFd: Option.none(),
|
||||||
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
|
logWebSocketEvents: Option.none(),
|
||||||
|
},
|
||||||
|
Option.none(),
|
||||||
|
).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
Layer.mergeAll(
|
||||||
|
ConfigProvider.layer(
|
||||||
|
ConfigProvider.fromEnv({
|
||||||
|
env: {
|
||||||
|
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
NetService.layer,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(resolved).toEqual({
|
||||||
|
logLevel: "Info",
|
||||||
|
...defaultObservabilityConfig,
|
||||||
|
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||||
|
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||||
|
mode: "desktop",
|
||||||
|
port: 4888,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
baseDir,
|
||||||
|
...derivedPaths,
|
||||||
|
host: "127.0.0.2",
|
||||||
|
staticDir: undefined,
|
||||||
|
devUrl: new URL("http://127.0.0.1:5173"),
|
||||||
|
noBrowser: true,
|
||||||
|
startupPresentation: "browser",
|
||||||
|
desktopBootstrapToken: undefined,
|
||||||
|
autoBootstrapProjectFromCwd: false,
|
||||||
|
logWebSocketEvents: true,
|
||||||
|
});
|
||||||
|
assert.equal(join(baseDir, "dev"), resolved.stateDir);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("creates derived runtime directories during config resolution", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
|
||||||
|
const customCwd = path.join(baseDir, "nested", "project");
|
||||||
|
|
||||||
|
const resolved = yield* resolveServerConfig(
|
||||||
|
{
|
||||||
|
mode: Option.some("desktop"),
|
||||||
|
port: Option.some(4888),
|
||||||
|
host: Option.none(),
|
||||||
|
baseDir: Option.some(baseDir),
|
||||||
|
cwd: Option.some(customCwd),
|
||||||
|
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
|
||||||
|
noBrowser: Option.none(),
|
||||||
|
bootstrapFd: Option.none(),
|
||||||
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
|
logWebSocketEvents: Option.none(),
|
||||||
|
},
|
||||||
|
Option.none(),
|
||||||
|
).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
Layer.mergeAll(
|
||||||
|
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
|
||||||
|
NetService.layer,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const directory of [
|
||||||
|
customCwd,
|
||||||
|
resolved.stateDir,
|
||||||
|
resolved.logsDir,
|
||||||
|
resolved.providerLogsDir,
|
||||||
|
resolved.terminalLogsDir,
|
||||||
|
resolved.attachmentsDir,
|
||||||
|
resolved.worktreesDir,
|
||||||
|
path.dirname(resolved.serverLogPath),
|
||||||
|
path.dirname(resolved.serverTracePath),
|
||||||
|
]) {
|
||||||
|
expect(yield* fs.exists(directory)).toBe(true);
|
||||||
|
}
|
||||||
|
expect(resolved.cwd).toBe(path.resolve(customCwd));
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("applies flag then env precedence over bootstrap envelope values", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const { join } = yield* Path.Path;
|
||||||
|
const baseDir = join(os.tmpdir(), "t3-cli-config-env-wins");
|
||||||
|
const fd = yield* openBootstrapFd({
|
||||||
|
mode: "desktop",
|
||||||
|
port: 4888,
|
||||||
|
host: "127.0.0.2",
|
||||||
|
t3Home: "/tmp/t3-bootstrap-home",
|
||||||
|
devUrl: "http://127.0.0.1:5173",
|
||||||
|
noBrowser: false,
|
||||||
|
autoBootstrapProjectFromCwd: false,
|
||||||
|
logWebSocketEvents: false,
|
||||||
|
});
|
||||||
|
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||||
|
|
||||||
|
const resolved = yield* resolveServerConfig(
|
||||||
|
{
|
||||||
|
mode: Option.none(),
|
||||||
|
port: Option.some(8788),
|
||||||
|
host: Option.some("127.0.0.1"),
|
||||||
|
baseDir: Option.none(),
|
||||||
|
cwd: Option.none(),
|
||||||
|
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||||
|
noBrowser: Option.none(),
|
||||||
|
bootstrapFd: Option.none(),
|
||||||
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
|
logWebSocketEvents: Option.none(),
|
||||||
|
},
|
||||||
|
Option.some("Debug"),
|
||||||
|
).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
Layer.mergeAll(
|
||||||
|
ConfigProvider.layer(
|
||||||
|
ConfigProvider.fromEnv({
|
||||||
|
env: {
|
||||||
|
T3CODE_MODE: "web",
|
||||||
|
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||||
|
T3CODE_HOME: baseDir,
|
||||||
|
T3CODE_NO_BROWSER: "true",
|
||||||
|
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||||
|
T3CODE_LOG_WS_EVENTS: "true",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
NetService.layer,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(resolved).toEqual({
|
||||||
|
logLevel: "Debug",
|
||||||
|
...defaultObservabilityConfig,
|
||||||
|
mode: "web",
|
||||||
|
port: 8788,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
baseDir,
|
||||||
|
...derivedPaths,
|
||||||
|
host: "127.0.0.1",
|
||||||
|
staticDir: undefined,
|
||||||
|
devUrl: new URL("http://127.0.0.1:4173"),
|
||||||
|
noBrowser: true,
|
||||||
|
startupPresentation: "browser",
|
||||||
|
desktopBootstrapToken: undefined,
|
||||||
|
autoBootstrapProjectFromCwd: true,
|
||||||
|
logWebSocketEvents: true,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("falls back to persisted observability settings when env vars are absent", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
|
||||||
|
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||||
|
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
|
||||||
|
yield* fs.writeFileString(
|
||||||
|
derivedPaths.settingsPath,
|
||||||
|
`${JSON.stringify({
|
||||||
|
observability: {
|
||||||
|
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||||
|
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||||
|
},
|
||||||
|
})}\n`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const resolved = yield* resolveServerConfig(
|
||||||
|
{
|
||||||
|
mode: Option.some("desktop"),
|
||||||
|
port: Option.some(4888),
|
||||||
|
host: Option.none(),
|
||||||
|
baseDir: Option.some(baseDir),
|
||||||
|
cwd: Option.none(),
|
||||||
|
devUrl: Option.none(),
|
||||||
|
noBrowser: Option.none(),
|
||||||
|
bootstrapFd: Option.none(),
|
||||||
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
|
logWebSocketEvents: Option.none(),
|
||||||
|
},
|
||||||
|
Option.none(),
|
||||||
|
).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
Layer.mergeAll(
|
||||||
|
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
|
||||||
|
NetService.layer,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
|
||||||
|
expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics");
|
||||||
|
expect(resolved).toEqual({
|
||||||
|
logLevel: "Info",
|
||||||
|
...defaultObservabilityConfig,
|
||||||
|
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||||
|
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||||
|
mode: "desktop",
|
||||||
|
port: 4888,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
baseDir,
|
||||||
|
...derivedPaths,
|
||||||
|
host: "127.0.0.1",
|
||||||
|
staticDir: resolved.staticDir,
|
||||||
|
devUrl: undefined,
|
||||||
|
noBrowser: true,
|
||||||
|
startupPresentation: "browser",
|
||||||
|
desktopBootstrapToken: undefined,
|
||||||
|
autoBootstrapProjectFromCwd: false,
|
||||||
|
logWebSocketEvents: false,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const { join } = yield* Path.Path;
|
||||||
|
const baseDir = join(os.tmpdir(), "t3-cli-config-headless-base");
|
||||||
|
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||||
|
|
||||||
|
const resolved = yield* resolveServerConfig(
|
||||||
|
{
|
||||||
|
mode: Option.some("web"),
|
||||||
|
port: Option.some(3773),
|
||||||
|
host: Option.none(),
|
||||||
|
baseDir: Option.some(baseDir),
|
||||||
|
cwd: Option.none(),
|
||||||
|
devUrl: Option.none(),
|
||||||
|
noBrowser: Option.none(),
|
||||||
|
bootstrapFd: Option.none(),
|
||||||
|
autoBootstrapProjectFromCwd: Option.none(),
|
||||||
|
logWebSocketEvents: Option.none(),
|
||||||
|
},
|
||||||
|
Option.none(),
|
||||||
|
{
|
||||||
|
startupPresentation: "headless",
|
||||||
|
},
|
||||||
|
).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
Layer.mergeAll(
|
||||||
|
ConfigProvider.layer(
|
||||||
|
ConfigProvider.fromEnv({
|
||||||
|
env: {
|
||||||
|
T3CODE_NO_BROWSER: "false",
|
||||||
|
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
NetService.layer,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(resolved).toEqual({
|
||||||
|
logLevel: "Info",
|
||||||
|
...defaultObservabilityConfig,
|
||||||
|
mode: "web",
|
||||||
|
port: 3773,
|
||||||
|
cwd: process.cwd(),
|
||||||
|
baseDir,
|
||||||
|
...derivedPaths,
|
||||||
|
host: undefined,
|
||||||
|
staticDir: resolved.staticDir,
|
||||||
|
devUrl: undefined,
|
||||||
|
noBrowser: true,
|
||||||
|
startupPresentation: "headless",
|
||||||
|
desktopBootstrapToken: undefined,
|
||||||
|
autoBootstrapProjectFromCwd: false,
|
||||||
|
logWebSocketEvents: false,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,356 @@
|
|||||||
|
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 "./cli.ts";
|
||||||
|
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
||||||
|
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.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,
|
||||||
|
} 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)("cli log-level 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 orchestrationEngine = yield* OrchestrationEngineService;
|
||||||
|
const readModel = yield* orchestrationEngine.getReadModel();
|
||||||
|
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");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,88 @@
|
|||||||
|
import { expect, it } from "@effect/vitest";
|
||||||
|
import { DateTime } from "effect";
|
||||||
|
|
||||||
|
import {
|
||||||
|
formatIssuedPairingCredential,
|
||||||
|
formatIssuedSession,
|
||||||
|
formatPairingCredentialList,
|
||||||
|
formatSessionList,
|
||||||
|
} from "./cliAuthFormat.ts";
|
||||||
|
|
||||||
|
it("formats issued pairing credentials with the secret and optional pair URL", () => {
|
||||||
|
const output = formatIssuedPairingCredential(
|
||||||
|
{
|
||||||
|
id: "pairing-1",
|
||||||
|
credential: "secret-pairing-token",
|
||||||
|
role: "client",
|
||||||
|
subject: "one-time-token",
|
||||||
|
createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
||||||
|
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||||
|
},
|
||||||
|
{ baseUrl: "https://example.com", json: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(output).toContain("secret-pairing-token");
|
||||||
|
expect(output).toContain("https://example.com/pair#token=secret-pairing-token");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("formats pairing listings without exposing the secret token", () => {
|
||||||
|
const output = formatPairingCredentialList(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
id: "pairing-1",
|
||||||
|
credential: "secret-pairing-token",
|
||||||
|
subject: "one-time-token",
|
||||||
|
label: "Phone",
|
||||||
|
role: "client",
|
||||||
|
createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
||||||
|
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ json: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(output).toContain("pairing-1");
|
||||||
|
expect(output).not.toContain("secret-pairing-token");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("formats issued sessions with the bearer token but omits tokens from listings", () => {
|
||||||
|
const issuedOutput = formatIssuedSession(
|
||||||
|
{
|
||||||
|
sessionId: "session-1" as never,
|
||||||
|
token: "secret-session-token",
|
||||||
|
method: "bearer-session-token",
|
||||||
|
role: "owner",
|
||||||
|
subject: "cli-issued-session",
|
||||||
|
client: {
|
||||||
|
label: "deploy-bot",
|
||||||
|
deviceType: "bot",
|
||||||
|
},
|
||||||
|
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||||
|
},
|
||||||
|
{ json: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
const listedOutput = formatSessionList(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
sessionId: "session-1" as never,
|
||||||
|
method: "bearer-session-token",
|
||||||
|
role: "owner",
|
||||||
|
subject: "cli-issued-session",
|
||||||
|
client: {
|
||||||
|
label: "deploy-bot",
|
||||||
|
deviceType: "bot",
|
||||||
|
},
|
||||||
|
connected: false,
|
||||||
|
current: false,
|
||||||
|
issuedAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
|
||||||
|
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
|
||||||
|
lastConnectedAt: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ json: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(issuedOutput).toContain("secret-session-token");
|
||||||
|
expect(listedOutput).not.toContain("secret-session-token");
|
||||||
|
});
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
|
||||||
|
import { DateTime } from "effect";
|
||||||
|
|
||||||
|
import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts";
|
||||||
|
|
||||||
|
const newline = "\n";
|
||||||
|
|
||||||
|
function serializeOptionalFields(values: ReadonlyArray<string | null | undefined>) {
|
||||||
|
return values.filter((value): value is string => typeof value === "string" && value.length > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatClientMetadata(metadata: AuthClientMetadata): string {
|
||||||
|
const details = serializeOptionalFields([
|
||||||
|
metadata.label,
|
||||||
|
metadata.deviceType !== "unknown" ? metadata.deviceType : undefined,
|
||||||
|
metadata.os,
|
||||||
|
metadata.browser,
|
||||||
|
metadata.ipAddress,
|
||||||
|
]);
|
||||||
|
return details.length > 0 ? details.join(" | ") : "unlabeled client";
|
||||||
|
}
|
||||||
|
|
||||||
|
function toIsoString(value: DateTime.DateTime | DateTime.Utc): string {
|
||||||
|
return DateTime.formatIso(DateTime.toUtc(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatIssuedPairingCredential(
|
||||||
|
credential: IssuedPairingLink,
|
||||||
|
options?: {
|
||||||
|
readonly json?: boolean;
|
||||||
|
readonly baseUrl?: string;
|
||||||
|
},
|
||||||
|
): string {
|
||||||
|
const pairUrl =
|
||||||
|
options?.baseUrl != null && options.baseUrl.length > 0
|
||||||
|
? (() => {
|
||||||
|
const url = new URL("/pair", options.baseUrl);
|
||||||
|
url.searchParams.delete("token");
|
||||||
|
url.hash = new URLSearchParams([["token", credential.credential]]).toString();
|
||||||
|
return url.toString();
|
||||||
|
})()
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
if (options?.json) {
|
||||||
|
return `${JSON.stringify(
|
||||||
|
{
|
||||||
|
id: credential.id,
|
||||||
|
credential: credential.credential,
|
||||||
|
...(credential.label ? { label: credential.label } : {}),
|
||||||
|
role: credential.role,
|
||||||
|
expiresAt: toIsoString(credential.expiresAt),
|
||||||
|
...(pairUrl ? { pairUrl } : {}),
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
)}${newline}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
[
|
||||||
|
`Issued client pairing token ${credential.id}.`,
|
||||||
|
`Token: ${credential.credential}`,
|
||||||
|
...(pairUrl ? [`Pair URL: ${pairUrl}`] : []),
|
||||||
|
`Expires at: ${credential.expiresAt}`,
|
||||||
|
].join(newline) + newline
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatPairingCredentialList(
|
||||||
|
credentials: ReadonlyArray<AuthPairingLink>,
|
||||||
|
options?: {
|
||||||
|
readonly json?: boolean;
|
||||||
|
},
|
||||||
|
): string {
|
||||||
|
if (options?.json) {
|
||||||
|
return `${JSON.stringify(
|
||||||
|
credentials.map((credential) => ({
|
||||||
|
id: credential.id,
|
||||||
|
...(credential.label ? { label: credential.label } : {}),
|
||||||
|
role: credential.role,
|
||||||
|
createdAt: toIsoString(credential.createdAt),
|
||||||
|
expiresAt: toIsoString(credential.expiresAt),
|
||||||
|
})),
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
)}${newline}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (credentials.length === 0) {
|
||||||
|
return `No active pairing credentials.${newline}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
credentials
|
||||||
|
.map((credential) =>
|
||||||
|
[
|
||||||
|
`${credential.id}${credential.label ? ` (${credential.label})` : ""}`,
|
||||||
|
` role: ${credential.role}`,
|
||||||
|
` created: ${toIsoString(credential.createdAt)}`,
|
||||||
|
` expires: ${toIsoString(credential.expiresAt)}`,
|
||||||
|
].join(newline),
|
||||||
|
)
|
||||||
|
.join(`${newline}${newline}`) + newline
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatIssuedSession(
|
||||||
|
session: IssuedBearerSession,
|
||||||
|
options?: {
|
||||||
|
readonly json?: boolean;
|
||||||
|
readonly tokenOnly?: boolean;
|
||||||
|
},
|
||||||
|
): string {
|
||||||
|
if (options?.tokenOnly) {
|
||||||
|
return `${session.token}${newline}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options?.json) {
|
||||||
|
return `${JSON.stringify(
|
||||||
|
{
|
||||||
|
sessionId: session.sessionId,
|
||||||
|
token: session.token,
|
||||||
|
method: session.method,
|
||||||
|
role: session.role,
|
||||||
|
subject: session.subject,
|
||||||
|
client: session.client,
|
||||||
|
expiresAt: toIsoString(session.expiresAt),
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
)}${newline}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
[
|
||||||
|
`Issued ${session.role} bearer session ${session.sessionId}.`,
|
||||||
|
`Token: ${session.token}`,
|
||||||
|
`Subject: ${session.subject}`,
|
||||||
|
`Client: ${formatClientMetadata(session.client)}`,
|
||||||
|
`Expires at: ${toIsoString(session.expiresAt)}`,
|
||||||
|
].join(newline) + newline
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatSessionList(
|
||||||
|
sessions: ReadonlyArray<AuthClientSession>,
|
||||||
|
options?: {
|
||||||
|
readonly json?: boolean;
|
||||||
|
},
|
||||||
|
): string {
|
||||||
|
if (options?.json) {
|
||||||
|
return `${JSON.stringify(
|
||||||
|
sessions.map((session) => ({
|
||||||
|
sessionId: session.sessionId,
|
||||||
|
method: session.method,
|
||||||
|
role: session.role,
|
||||||
|
subject: session.subject,
|
||||||
|
client: session.client,
|
||||||
|
connected: session.connected,
|
||||||
|
issuedAt: toIsoString(session.issuedAt),
|
||||||
|
expiresAt: toIsoString(session.expiresAt),
|
||||||
|
lastConnectedAt: session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : null,
|
||||||
|
})),
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
)}${newline}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sessions.length === 0) {
|
||||||
|
return `No active sessions.${newline}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
sessions
|
||||||
|
.map((session) =>
|
||||||
|
[
|
||||||
|
`${session.sessionId} [${session.role}]${session.connected ? " connected" : ""}`,
|
||||||
|
` method: ${session.method}`,
|
||||||
|
` subject: ${session.subject}`,
|
||||||
|
` client: ${formatClientMetadata(session.client)}`,
|
||||||
|
` issued: ${toIsoString(session.issuedAt)}`,
|
||||||
|
` last connected: ${
|
||||||
|
session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : "never"
|
||||||
|
}`,
|
||||||
|
` expires: ${toIsoString(session.expiresAt)}`,
|
||||||
|
].join(newline),
|
||||||
|
)
|
||||||
|
.join(`${newline}${newline}`) + newline
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
resolveCodexModelForAccount,
|
resolveCodexModelForAccount,
|
||||||
} from "./codexAppServerManager";
|
} from "./codexAppServerManager";
|
||||||
|
|
||||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||||
|
|
||||||
function createSendTurnHarness() {
|
function createSendTurnHarness() {
|
||||||
const manager = new CodexAppServerManager();
|
const manager = new CodexAppServerManager();
|
||||||
@@ -37,6 +37,7 @@ function createSendTurnHarness() {
|
|||||||
planType: null,
|
planType: null,
|
||||||
sparkEnabled: true,
|
sparkEnabled: true,
|
||||||
},
|
},
|
||||||
|
collabReceiverTurns: new Map(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const requireSession = vi
|
const requireSession = vi
|
||||||
@@ -75,6 +76,7 @@ function createThreadControlHarness() {
|
|||||||
createdAt: "2026-02-10T00:00:00.000Z",
|
createdAt: "2026-02-10T00:00:00.000Z",
|
||||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||||
},
|
},
|
||||||
|
collabReceiverTurns: new Map(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const requireSession = vi
|
const requireSession = vi
|
||||||
@@ -109,14 +111,15 @@ function createPendingUserInputHarness() {
|
|||||||
},
|
},
|
||||||
pendingUserInputs: new Map([
|
pendingUserInputs: new Map([
|
||||||
[
|
[
|
||||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
ApprovalRequestId.make("req-user-input-1"),
|
||||||
{
|
{
|
||||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
requestId: ApprovalRequestId.make("req-user-input-1"),
|
||||||
jsonRpcId: 42,
|
jsonRpcId: 42,
|
||||||
threadId: asThreadId("thread_1"),
|
threadId: asThreadId("thread_1"),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
]),
|
]),
|
||||||
|
collabReceiverTurns: new Map(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const requireSession = vi
|
const requireSession = vi
|
||||||
@@ -135,6 +138,43 @@ function createPendingUserInputHarness() {
|
|||||||
return { manager, context, requireSession, writeMessage, emitEvent };
|
return { manager, context, requireSession, writeMessage, emitEvent };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createCollabNotificationHarness() {
|
||||||
|
const manager = new CodexAppServerManager();
|
||||||
|
const context = {
|
||||||
|
session: {
|
||||||
|
provider: "codex",
|
||||||
|
status: "running",
|
||||||
|
threadId: asThreadId("thread_1"),
|
||||||
|
runtimeMode: "full-access",
|
||||||
|
model: "gpt-5.3-codex",
|
||||||
|
activeTurnId: "turn_parent",
|
||||||
|
resumeCursor: { threadId: "provider_parent" },
|
||||||
|
createdAt: "2026-02-10T00:00:00.000Z",
|
||||||
|
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||||
|
},
|
||||||
|
account: {
|
||||||
|
type: "unknown",
|
||||||
|
planType: null,
|
||||||
|
sparkEnabled: true,
|
||||||
|
},
|
||||||
|
pending: new Map(),
|
||||||
|
pendingApprovals: new Map(),
|
||||||
|
pendingUserInputs: new Map(),
|
||||||
|
collabReceiverTurns: new Map<string, string>(),
|
||||||
|
nextRequestId: 1,
|
||||||
|
stopping: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const emitEvent = vi
|
||||||
|
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
||||||
|
.mockImplementation(() => {});
|
||||||
|
const updateSession = vi
|
||||||
|
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
|
||||||
|
.mockImplementation(() => {});
|
||||||
|
|
||||||
|
return { manager, context, emitEvent, updateSession };
|
||||||
|
}
|
||||||
|
|
||||||
describe("classifyCodexStderrLine", () => {
|
describe("classifyCodexStderrLine", () => {
|
||||||
it("ignores empty lines", () => {
|
it("ignores empty lines", () => {
|
||||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||||
@@ -167,6 +207,42 @@ describe("classifyCodexStderrLine", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("process stderr events", () => {
|
||||||
|
it("emits classified stderr lines as notifications", () => {
|
||||||
|
const manager = new CodexAppServerManager();
|
||||||
|
const emitEvent = vi
|
||||||
|
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
||||||
|
.mockImplementation(() => {});
|
||||||
|
|
||||||
|
(
|
||||||
|
manager as unknown as {
|
||||||
|
emitNotificationEvent: (
|
||||||
|
context: { session: { threadId: ThreadId } },
|
||||||
|
method: string,
|
||||||
|
message: string,
|
||||||
|
) => void;
|
||||||
|
}
|
||||||
|
).emitNotificationEvent(
|
||||||
|
{
|
||||||
|
session: {
|
||||||
|
threadId: asThreadId("thread-1"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"process/stderr",
|
||||||
|
"fatal: permission denied",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(emitEvent).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
kind: "notification",
|
||||||
|
method: "process/stderr",
|
||||||
|
threadId: "thread-1",
|
||||||
|
message: "fatal: permission denied",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("normalizeCodexModelSlug", () => {
|
describe("normalizeCodexModelSlug", () => {
|
||||||
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
||||||
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
||||||
@@ -234,7 +310,7 @@ describe("readCodexAccountSnapshot", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps spark enabled for api key accounts", () => {
|
it("disables spark for api key accounts", () => {
|
||||||
expect(
|
expect(
|
||||||
readCodexAccountSnapshot({
|
readCodexAccountSnapshot({
|
||||||
type: "apiKey",
|
type: "apiKey",
|
||||||
@@ -242,7 +318,20 @@ describe("readCodexAccountSnapshot", () => {
|
|||||||
).toEqual({
|
).toEqual({
|
||||||
type: "apiKey",
|
type: "apiKey",
|
||||||
planType: null,
|
planType: null,
|
||||||
sparkEnabled: true,
|
sparkEnabled: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("disables spark for unknown chatgpt plans", () => {
|
||||||
|
expect(
|
||||||
|
readCodexAccountSnapshot({
|
||||||
|
type: "chatgpt",
|
||||||
|
email: "[email protected]",
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
type: "chatgpt",
|
||||||
|
planType: "unknown",
|
||||||
|
sparkEnabled: false,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -267,6 +356,16 @@ describe("resolveCodexModelForAccount", () => {
|
|||||||
}),
|
}),
|
||||||
).toBe("gpt-5.3-codex-spark");
|
).toBe("gpt-5.3-codex-spark");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("falls back from spark to default for api key auth", () => {
|
||||||
|
expect(
|
||||||
|
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
|
||||||
|
type: "apiKey",
|
||||||
|
planType: null,
|
||||||
|
sparkEnabled: false,
|
||||||
|
}),
|
||||||
|
).toBe("gpt-5.3-codex");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("startSession", () => {
|
describe("startSession", () => {
|
||||||
@@ -302,6 +401,7 @@ describe("startSession", () => {
|
|||||||
manager.startSession({
|
manager.startSession({
|
||||||
threadId: asThreadId("thread-1"),
|
threadId: asThreadId("thread-1"),
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
|
binaryPath: "codex",
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
}),
|
}),
|
||||||
).rejects.toThrow("cwd missing");
|
).rejects.toThrow("cwd missing");
|
||||||
@@ -350,6 +450,7 @@ describe("startSession", () => {
|
|||||||
manager.startSession({
|
manager.startSession({
|
||||||
threadId: asThreadId("thread-1"),
|
threadId: asThreadId("thread-1"),
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
|
binaryPath: "codex",
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
}),
|
}),
|
||||||
).rejects.toThrow(
|
).rejects.toThrow(
|
||||||
@@ -642,7 +743,7 @@ describe("respondToUserInput", () => {
|
|||||||
|
|
||||||
await manager.respondToUserInput(
|
await manager.respondToUserInput(
|
||||||
asThreadId("thread_1"),
|
asThreadId("thread_1"),
|
||||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
ApprovalRequestId.make("req-user-input-1"),
|
||||||
{
|
{
|
||||||
scope: "All request methods",
|
scope: "All request methods",
|
||||||
compat: "Keep current envelope",
|
compat: "Keep current envelope",
|
||||||
@@ -679,7 +780,7 @@ describe("respondToUserInput", () => {
|
|||||||
|
|
||||||
await manager.respondToUserInput(
|
await manager.respondToUserInput(
|
||||||
asThreadId("thread_1"),
|
asThreadId("thread_1"),
|
||||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
ApprovalRequestId.make("req-user-input-1"),
|
||||||
{
|
{
|
||||||
scope: [],
|
scope: [],
|
||||||
},
|
},
|
||||||
@@ -721,6 +822,7 @@ describe("respondToUserInput", () => {
|
|||||||
},
|
},
|
||||||
pendingApprovals: new Map(),
|
pendingApprovals: new Map(),
|
||||||
pendingUserInputs: new Map(),
|
pendingUserInputs: new Map(),
|
||||||
|
collabReceiverTurns: new Map(),
|
||||||
};
|
};
|
||||||
type ApprovalRequestContext = {
|
type ApprovalRequestContext = {
|
||||||
session: typeof context.session;
|
session: typeof context.session;
|
||||||
@@ -748,6 +850,152 @@ describe("respondToUserInput", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("collab child conversation routing", () => {
|
||||||
|
it("rewrites child notification turn ids onto the parent turn", () => {
|
||||||
|
const { manager, context, emitEvent } = createCollabNotificationHarness();
|
||||||
|
|
||||||
|
(
|
||||||
|
manager as unknown as {
|
||||||
|
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||||
|
}
|
||||||
|
).handleServerNotification(context, {
|
||||||
|
method: "item/completed",
|
||||||
|
params: {
|
||||||
|
item: {
|
||||||
|
type: "collabAgentToolCall",
|
||||||
|
id: "call_collab_1",
|
||||||
|
receiverThreadIds: ["child_provider_1"],
|
||||||
|
},
|
||||||
|
threadId: "provider_parent",
|
||||||
|
turnId: "turn_parent",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
(
|
||||||
|
manager as unknown as {
|
||||||
|
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||||
|
}
|
||||||
|
).handleServerNotification(context, {
|
||||||
|
method: "item/agentMessage/delta",
|
||||||
|
params: {
|
||||||
|
threadId: "child_provider_1",
|
||||||
|
turnId: "turn_child_1",
|
||||||
|
itemId: "msg_child_1",
|
||||||
|
delta: "working",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(emitEvent).toHaveBeenLastCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
method: "item/agentMessage/delta",
|
||||||
|
turnId: "turn_parent",
|
||||||
|
itemId: "msg_child_1",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
|
||||||
|
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
|
||||||
|
|
||||||
|
(
|
||||||
|
manager as unknown as {
|
||||||
|
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||||
|
}
|
||||||
|
).handleServerNotification(context, {
|
||||||
|
method: "item/completed",
|
||||||
|
params: {
|
||||||
|
item: {
|
||||||
|
type: "collabAgentToolCall",
|
||||||
|
id: "call_collab_1",
|
||||||
|
receiverThreadIds: ["child_provider_1"],
|
||||||
|
},
|
||||||
|
threadId: "provider_parent",
|
||||||
|
turnId: "turn_parent",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
emitEvent.mockClear();
|
||||||
|
updateSession.mockClear();
|
||||||
|
|
||||||
|
(
|
||||||
|
manager as unknown as {
|
||||||
|
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||||
|
}
|
||||||
|
).handleServerNotification(context, {
|
||||||
|
method: "turn/started",
|
||||||
|
params: {
|
||||||
|
threadId: "child_provider_1",
|
||||||
|
turn: { id: "turn_child_1" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
(
|
||||||
|
manager as unknown as {
|
||||||
|
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||||
|
}
|
||||||
|
).handleServerNotification(context, {
|
||||||
|
method: "turn/completed",
|
||||||
|
params: {
|
||||||
|
threadId: "child_provider_1",
|
||||||
|
turn: { id: "turn_child_1", status: "completed" },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(emitEvent).not.toHaveBeenCalled();
|
||||||
|
expect(updateSession).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rewrites child approval requests onto the parent turn", () => {
|
||||||
|
const { manager, context, emitEvent } = createCollabNotificationHarness();
|
||||||
|
|
||||||
|
(
|
||||||
|
manager as unknown as {
|
||||||
|
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||||
|
}
|
||||||
|
).handleServerNotification(context, {
|
||||||
|
method: "item/completed",
|
||||||
|
params: {
|
||||||
|
item: {
|
||||||
|
type: "collabAgentToolCall",
|
||||||
|
id: "call_collab_1",
|
||||||
|
receiverThreadIds: ["child_provider_1"],
|
||||||
|
},
|
||||||
|
threadId: "provider_parent",
|
||||||
|
turnId: "turn_parent",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
emitEvent.mockClear();
|
||||||
|
|
||||||
|
(
|
||||||
|
manager as unknown as {
|
||||||
|
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
|
||||||
|
}
|
||||||
|
).handleServerRequest(context, {
|
||||||
|
id: 42,
|
||||||
|
method: "item/commandExecution/requestApproval",
|
||||||
|
params: {
|
||||||
|
threadId: "child_provider_1",
|
||||||
|
turnId: "turn_child_1",
|
||||||
|
itemId: "call_child_1",
|
||||||
|
command: "bun install",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
turnId: "turn_parent",
|
||||||
|
itemId: "call_child_1",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(emitEvent).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
method: "item/commandExecution/requestApproval",
|
||||||
|
turnId: "turn_parent",
|
||||||
|
itemId: "call_child_1",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
|
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
|
||||||
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
|
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
|
||||||
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
|
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
|
||||||
@@ -761,12 +1009,8 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
|||||||
provider: "codex",
|
provider: "codex",
|
||||||
cwd: workspaceDir,
|
cwd: workspaceDir,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
providerOptions: {
|
binaryPath: process.env.CODEX_BINARY_PATH!,
|
||||||
codex: {
|
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||||
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
|
||||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const firstTurn = await manager.sendTurn({
|
const firstTurn = await manager.sendTurn({
|
||||||
@@ -796,12 +1040,8 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
|||||||
cwd: workspaceDir,
|
cwd: workspaceDir,
|
||||||
runtimeMode: "approval-required",
|
runtimeMode: "approval-required",
|
||||||
resumeCursor: firstSession.resumeCursor,
|
resumeCursor: firstSession.resumeCursor,
|
||||||
providerOptions: {
|
binaryPath: process.env.CODEX_BINARY_PATH!,
|
||||||
codex: {
|
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||||
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
|
||||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(resumedSession.threadId).toBe(originalThreadId);
|
expect(resumedSession.threadId).toBe(originalThreadId);
|
||||||
|
|||||||
@@ -14,19 +14,27 @@ import {
|
|||||||
type ProviderApprovalDecision,
|
type ProviderApprovalDecision,
|
||||||
type ProviderEvent,
|
type ProviderEvent,
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
type ProviderSessionStartInput,
|
|
||||||
type ProviderTurnStartResult,
|
type ProviderTurnStartResult,
|
||||||
RuntimeMode,
|
RuntimeMode,
|
||||||
ProviderInteractionMode,
|
ProviderInteractionMode,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||||
import { Effect, ServiceMap } from "effect";
|
import { Effect, Context } from "effect";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
formatCodexCliUpgradeMessage,
|
formatCodexCliUpgradeMessage,
|
||||||
isCodexCliVersionSupported,
|
isCodexCliVersionSupported,
|
||||||
parseCodexCliVersion,
|
parseCodexCliVersion,
|
||||||
} from "./provider/codexCliVersion";
|
} from "./provider/codexCliVersion";
|
||||||
|
import {
|
||||||
|
readCodexAccountSnapshot,
|
||||||
|
resolveCodexModelForAccount,
|
||||||
|
type CodexAccountSnapshot,
|
||||||
|
} from "./provider/codexAccount";
|
||||||
|
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
|
||||||
|
|
||||||
|
export { buildCodexInitializeParams } from "./provider/codexAppServer";
|
||||||
|
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
|
||||||
|
|
||||||
type PendingRequestKey = string;
|
type PendingRequestKey = string;
|
||||||
|
|
||||||
@@ -70,6 +78,7 @@ interface CodexSessionContext {
|
|||||||
pending: Map<PendingRequestKey, PendingRequest>;
|
pending: Map<PendingRequestKey, PendingRequest>;
|
||||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||||
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
|
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
|
||||||
|
collabReceiverTurns: Map<string, TurnId>;
|
||||||
nextRequestId: number;
|
nextRequestId: number;
|
||||||
stopping: boolean;
|
stopping: boolean;
|
||||||
}
|
}
|
||||||
@@ -96,23 +105,6 @@ interface JsonRpcNotification {
|
|||||||
params?: unknown;
|
params?: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
type CodexPlanType =
|
|
||||||
| "free"
|
|
||||||
| "go"
|
|
||||||
| "plus"
|
|
||||||
| "pro"
|
|
||||||
| "team"
|
|
||||||
| "business"
|
|
||||||
| "enterprise"
|
|
||||||
| "edu"
|
|
||||||
| "unknown";
|
|
||||||
|
|
||||||
interface CodexAccountSnapshot {
|
|
||||||
readonly type: "apiKey" | "chatgpt" | "unknown";
|
|
||||||
readonly planType: CodexPlanType | null;
|
|
||||||
readonly sparkEnabled: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CodexAppServerSendTurnInput {
|
export interface CodexAppServerSendTurnInput {
|
||||||
readonly threadId: ThreadId;
|
readonly threadId: ThreadId;
|
||||||
readonly input?: string;
|
readonly input?: string;
|
||||||
@@ -130,7 +122,8 @@ export interface CodexAppServerStartSessionInput {
|
|||||||
readonly model?: string;
|
readonly model?: string;
|
||||||
readonly serviceTier?: string;
|
readonly serviceTier?: string;
|
||||||
readonly resumeCursor?: unknown;
|
readonly resumeCursor?: unknown;
|
||||||
readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
|
readonly binaryPath: string;
|
||||||
|
readonly homePath?: string;
|
||||||
readonly runtimeMode: RuntimeMode;
|
readonly runtimeMode: RuntimeMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,50 +154,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
|||||||
"unknown thread",
|
"unknown thread",
|
||||||
"does not exist",
|
"does not exist",
|
||||||
];
|
];
|
||||||
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
|
|
||||||
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
|
|
||||||
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
|
|
||||||
|
|
||||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
||||||
if (!value || typeof value !== "object") {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return value as Record<string, unknown>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function asString(value: unknown): string | undefined {
|
|
||||||
return typeof value === "string" ? value : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
|
|
||||||
const record = asObject(response);
|
|
||||||
const account = asObject(record?.account) ?? record;
|
|
||||||
const accountType = asString(account?.type);
|
|
||||||
|
|
||||||
if (accountType === "apiKey") {
|
|
||||||
return {
|
|
||||||
type: "apiKey",
|
|
||||||
planType: null,
|
|
||||||
sparkEnabled: true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (accountType === "chatgpt") {
|
|
||||||
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
|
|
||||||
return {
|
|
||||||
type: "chatgpt",
|
|
||||||
planType,
|
|
||||||
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
type: "unknown",
|
|
||||||
planType: null,
|
|
||||||
sparkEnabled: true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
|
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
|
||||||
|
|
||||||
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
|
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
|
||||||
@@ -341,31 +290,26 @@ In Default mode, strongly prefer making reasonable assumptions and executing the
|
|||||||
</collaboration_mode>`;
|
</collaboration_mode>`;
|
||||||
|
|
||||||
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
||||||
readonly approvalPolicy: "on-request" | "never";
|
readonly approvalPolicy: "untrusted" | "on-request" | "never";
|
||||||
readonly sandbox: "workspace-write" | "danger-full-access";
|
readonly sandbox: "read-only" | "workspace-write" | "danger-full-access";
|
||||||
} {
|
} {
|
||||||
if (runtimeMode === "approval-required") {
|
switch (runtimeMode) {
|
||||||
return {
|
case "approval-required":
|
||||||
approvalPolicy: "on-request",
|
return {
|
||||||
sandbox: "workspace-write",
|
approvalPolicy: "untrusted",
|
||||||
};
|
sandbox: "read-only",
|
||||||
|
};
|
||||||
|
case "auto-accept-edits":
|
||||||
|
return {
|
||||||
|
approvalPolicy: "on-request",
|
||||||
|
sandbox: "workspace-write",
|
||||||
|
};
|
||||||
|
case "full-access":
|
||||||
|
return {
|
||||||
|
approvalPolicy: "never",
|
||||||
|
sandbox: "danger-full-access",
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
|
||||||
approvalPolicy: "never",
|
|
||||||
sandbox: "danger-full-access",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveCodexModelForAccount(
|
|
||||||
model: string | undefined,
|
|
||||||
account: CodexAccountSnapshot,
|
|
||||||
): string | undefined {
|
|
||||||
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
|
|
||||||
return model;
|
|
||||||
}
|
|
||||||
|
|
||||||
return CODEX_DEFAULT_MODEL;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -374,15 +318,7 @@ export function resolveCodexModelForAccount(
|
|||||||
* entire process tree instead.
|
* entire process tree instead.
|
||||||
*/
|
*/
|
||||||
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
||||||
if (process.platform === "win32" && child.pid !== undefined) {
|
killCodexChildProcess(child);
|
||||||
try {
|
|
||||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
|
||||||
return;
|
|
||||||
} catch {
|
|
||||||
// fallback to direct kill
|
|
||||||
}
|
|
||||||
}
|
|
||||||
child.kill();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalizeCodexModelSlug(
|
export function normalizeCodexModelSlug(
|
||||||
@@ -401,19 +337,6 @@ export function normalizeCodexModelSlug(
|
|||||||
return normalized;
|
return normalized;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildCodexInitializeParams() {
|
|
||||||
return {
|
|
||||||
clientInfo: {
|
|
||||||
name: "t3code_desktop",
|
|
||||||
title: "T3 Code Desktop",
|
|
||||||
version: "0.1.0",
|
|
||||||
},
|
|
||||||
capabilities: {
|
|
||||||
experimentalApi: true,
|
|
||||||
},
|
|
||||||
} as const;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildCodexCollaborationMode(input: {
|
function buildCodexCollaborationMode(input: {
|
||||||
readonly interactionMode?: "default" | "plan";
|
readonly interactionMode?: "default" | "plan";
|
||||||
readonly model?: string;
|
readonly model?: string;
|
||||||
@@ -516,7 +439,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
|
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
|
||||||
|
|
||||||
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
|
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
|
||||||
constructor(services?: ServiceMap.ServiceMap<never>) {
|
constructor(services?: Context.Context<never>) {
|
||||||
super();
|
super();
|
||||||
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
|
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
|
||||||
}
|
}
|
||||||
@@ -540,9 +463,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
};
|
};
|
||||||
|
|
||||||
const codexOptions = readCodexProviderOptions(input);
|
const codexBinaryPath = input.binaryPath;
|
||||||
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
|
const codexHomePath = input.homePath;
|
||||||
const codexHomePath = codexOptions.homePath;
|
|
||||||
this.assertSupportedCodexCliVersion({
|
this.assertSupportedCodexCliVersion({
|
||||||
binaryPath: codexBinaryPath,
|
binaryPath: codexBinaryPath,
|
||||||
cwd: resolvedCwd,
|
cwd: resolvedCwd,
|
||||||
@@ -571,6 +493,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
pending: new Map(),
|
pending: new Map(),
|
||||||
pendingApprovals: new Map(),
|
pendingApprovals: new Map(),
|
||||||
pendingUserInputs: new Map(),
|
pendingUserInputs: new Map(),
|
||||||
|
collabReceiverTurns: new Map(),
|
||||||
nextRequestId: 1,
|
nextRequestId: 1,
|
||||||
stopping: false,
|
stopping: false,
|
||||||
};
|
};
|
||||||
@@ -717,7 +640,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
this.stopSession(threadId);
|
this.stopSession(threadId);
|
||||||
} else {
|
} else {
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
id: EventId.makeUnsafe(randomUUID()),
|
id: EventId.make(randomUUID()),
|
||||||
kind: "error",
|
kind: "error",
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
threadId,
|
threadId,
|
||||||
@@ -732,6 +655,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
|
|
||||||
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||||
const context = this.requireSession(input.threadId);
|
const context = this.requireSession(input.threadId);
|
||||||
|
context.collabReceiverTurns.clear();
|
||||||
|
|
||||||
const turnInput: Array<
|
const turnInput: Array<
|
||||||
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
||||||
@@ -815,7 +739,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
if (!turnIdRaw) {
|
if (!turnIdRaw) {
|
||||||
throw new Error("turn/start response did not include a turn id.");
|
throw new Error("turn/start response did not include a turn id.");
|
||||||
}
|
}
|
||||||
const turnId = TurnId.makeUnsafe(turnIdRaw);
|
const turnId = TurnId.make(turnIdRaw);
|
||||||
|
|
||||||
this.updateSession(context, {
|
this.updateSession(context, {
|
||||||
status: "running",
|
status: "running",
|
||||||
@@ -916,7 +840,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
id: EventId.makeUnsafe(randomUUID()),
|
id: EventId.make(randomUUID()),
|
||||||
kind: "notification",
|
kind: "notification",
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
@@ -955,7 +879,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
id: EventId.makeUnsafe(randomUUID()),
|
id: EventId.make(randomUUID()),
|
||||||
kind: "notification",
|
kind: "notification",
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
@@ -1044,7 +968,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
this.emitNotificationEvent(context, "process/stderr", classified.message);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1121,21 +1045,32 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
context: CodexSessionContext,
|
context: CodexSessionContext,
|
||||||
notification: JsonRpcNotification,
|
notification: JsonRpcNotification,
|
||||||
): void {
|
): void {
|
||||||
const route = this.readRouteFields(notification.params);
|
const rawRoute = this.readRouteFields(notification.params);
|
||||||
|
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
|
||||||
|
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
|
||||||
|
const isChildConversation = childParentTurnId !== undefined;
|
||||||
|
if (
|
||||||
|
isChildConversation &&
|
||||||
|
this.shouldSuppressChildConversationNotification(notification.method)
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const textDelta =
|
const textDelta =
|
||||||
notification.method === "item/agentMessage/delta"
|
notification.method === "item/agentMessage/delta"
|
||||||
? this.readString(notification.params, "delta")
|
? this.readString(notification.params, "delta")
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
id: EventId.makeUnsafe(randomUUID()),
|
id: EventId.make(randomUUID()),
|
||||||
kind: "notification",
|
kind: "notification",
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
method: notification.method,
|
method: notification.method,
|
||||||
turnId: route.turnId,
|
...((childParentTurnId ?? rawRoute.turnId)
|
||||||
itemId: route.itemId,
|
? { turnId: childParentTurnId ?? rawRoute.turnId }
|
||||||
|
: {}),
|
||||||
|
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||||
textDelta,
|
textDelta,
|
||||||
payload: notification.params,
|
payload: notification.params,
|
||||||
});
|
});
|
||||||
@@ -1151,6 +1086,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (notification.method === "turn/started") {
|
if (notification.method === "turn/started") {
|
||||||
|
if (isChildConversation) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
|
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
|
||||||
this.updateSession(context, {
|
this.updateSession(context, {
|
||||||
status: "running",
|
status: "running",
|
||||||
@@ -1160,6 +1098,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (notification.method === "turn/completed") {
|
if (notification.method === "turn/completed") {
|
||||||
|
if (isChildConversation) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
context.collabReceiverTurns.clear();
|
||||||
const turn = this.readObject(notification.params, "turn");
|
const turn = this.readObject(notification.params, "turn");
|
||||||
const status = this.readString(turn, "status");
|
const status = this.readString(turn, "status");
|
||||||
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
|
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
|
||||||
@@ -1172,6 +1114,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (notification.method === "error") {
|
if (notification.method === "error") {
|
||||||
|
if (isChildConversation) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const message = this.readString(this.readObject(notification.params)?.error, "message");
|
const message = this.readString(this.readObject(notification.params)?.error, "message");
|
||||||
const willRetry = this.readBoolean(notification.params, "willRetry");
|
const willRetry = this.readBoolean(notification.params, "willRetry");
|
||||||
|
|
||||||
@@ -1183,11 +1128,13 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
|
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
|
||||||
const route = this.readRouteFields(request.params);
|
const rawRoute = this.readRouteFields(request.params);
|
||||||
|
const childParentTurnId = this.readChildParentTurnId(context, request.params);
|
||||||
|
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
|
||||||
const requestKind = this.requestKindForMethod(request.method);
|
const requestKind = this.requestKindForMethod(request.method);
|
||||||
let requestId: ApprovalRequestId | undefined;
|
let requestId: ApprovalRequestId | undefined;
|
||||||
if (requestKind) {
|
if (requestKind) {
|
||||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
requestId = ApprovalRequestId.make(randomUUID());
|
||||||
const pendingRequest: PendingApprovalRequest = {
|
const pendingRequest: PendingApprovalRequest = {
|
||||||
requestId,
|
requestId,
|
||||||
jsonRpcId: request.id,
|
jsonRpcId: request.id,
|
||||||
@@ -1199,32 +1146,32 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
: "item/fileChange/requestApproval",
|
: "item/fileChange/requestApproval",
|
||||||
requestKind,
|
requestKind,
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
...(route.turnId ? { turnId: route.turnId } : {}),
|
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
||||||
...(route.itemId ? { itemId: route.itemId } : {}),
|
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||||
};
|
};
|
||||||
context.pendingApprovals.set(requestId, pendingRequest);
|
context.pendingApprovals.set(requestId, pendingRequest);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (request.method === "item/tool/requestUserInput") {
|
if (request.method === "item/tool/requestUserInput") {
|
||||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
requestId = ApprovalRequestId.make(randomUUID());
|
||||||
context.pendingUserInputs.set(requestId, {
|
context.pendingUserInputs.set(requestId, {
|
||||||
requestId,
|
requestId,
|
||||||
jsonRpcId: request.id,
|
jsonRpcId: request.id,
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
...(route.turnId ? { turnId: route.turnId } : {}),
|
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
||||||
...(route.itemId ? { itemId: route.itemId } : {}),
|
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
id: EventId.makeUnsafe(randomUUID()),
|
id: EventId.make(randomUUID()),
|
||||||
kind: "request",
|
kind: "request",
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
method: request.method,
|
method: request.method,
|
||||||
turnId: route.turnId,
|
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
||||||
itemId: route.itemId,
|
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
|
||||||
requestId,
|
requestId,
|
||||||
requestKind,
|
requestKind,
|
||||||
payload: request.params,
|
payload: request.params,
|
||||||
@@ -1307,7 +1254,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
|
|
||||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
id: EventId.makeUnsafe(randomUUID()),
|
id: EventId.make(randomUUID()),
|
||||||
kind: "session",
|
kind: "session",
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
@@ -1319,7 +1266,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
|
|
||||||
private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
|
private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
id: EventId.makeUnsafe(randomUUID()),
|
id: EventId.make(randomUUID()),
|
||||||
kind: "error",
|
kind: "error",
|
||||||
provider: "codex",
|
provider: "codex",
|
||||||
threadId: context.session.threadId,
|
threadId: context.session.threadId,
|
||||||
@@ -1329,6 +1276,22 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private emitNotificationEvent(
|
||||||
|
context: CodexSessionContext,
|
||||||
|
method: string,
|
||||||
|
message: string,
|
||||||
|
): void {
|
||||||
|
this.emitEvent({
|
||||||
|
id: EventId.make(randomUUID()),
|
||||||
|
kind: "notification",
|
||||||
|
provider: "codex",
|
||||||
|
threadId: context.session.threadId,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
method,
|
||||||
|
message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private emitEvent(event: ProviderEvent): void {
|
private emitEvent(event: ProviderEvent): void {
|
||||||
this.emit("event", event);
|
this.emit("event", event);
|
||||||
}
|
}
|
||||||
@@ -1378,7 +1341,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
const turns = turnsRaw.map((turnValue, index) => {
|
const turns = turnsRaw.map((turnValue, index) => {
|
||||||
const turn = this.readObject(turnValue);
|
const turn = this.readObject(turnValue);
|
||||||
const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
|
const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
|
||||||
const turnId = TurnId.makeUnsafe(turnIdRaw);
|
const turnId = TurnId.make(turnIdRaw);
|
||||||
const items = this.readArray(turn, "items") ?? [];
|
const items = this.readArray(turn, "items") ?? [];
|
||||||
return {
|
return {
|
||||||
id: turnId,
|
id: turnId,
|
||||||
@@ -1451,6 +1414,64 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
return route;
|
return route;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private readProviderConversationId(params: unknown): string | undefined {
|
||||||
|
return (
|
||||||
|
this.readString(params, "threadId") ??
|
||||||
|
this.readString(this.readObject(params, "thread"), "id") ??
|
||||||
|
this.readString(params, "conversationId")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
|
||||||
|
const providerConversationId = this.readProviderConversationId(params);
|
||||||
|
if (!providerConversationId) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return context.collabReceiverTurns.get(providerConversationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private rememberCollabReceiverTurns(
|
||||||
|
context: CodexSessionContext,
|
||||||
|
params: unknown,
|
||||||
|
parentTurnId: TurnId | undefined,
|
||||||
|
): void {
|
||||||
|
if (!parentTurnId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const payload = this.readObject(params);
|
||||||
|
const item = this.readObject(payload, "item") ?? payload;
|
||||||
|
const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
|
||||||
|
if (itemType !== "collabAgentToolCall") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const receiverThreadIds =
|
||||||
|
this.readArray(item, "receiverThreadIds")
|
||||||
|
?.map((value) => (typeof value === "string" ? value : null))
|
||||||
|
.filter((value): value is string => value !== null) ?? [];
|
||||||
|
for (const receiverThreadId of receiverThreadIds) {
|
||||||
|
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private shouldSuppressChildConversationNotification(method: string): boolean {
|
||||||
|
return (
|
||||||
|
method === "thread/started" ||
|
||||||
|
method === "thread/status/changed" ||
|
||||||
|
method === "thread/archived" ||
|
||||||
|
method === "thread/unarchived" ||
|
||||||
|
method === "thread/closed" ||
|
||||||
|
method === "thread/compacted" ||
|
||||||
|
method === "thread/name/updated" ||
|
||||||
|
method === "thread/tokenUsage/updated" ||
|
||||||
|
method === "turn/started" ||
|
||||||
|
method === "turn/completed" ||
|
||||||
|
method === "turn/aborted" ||
|
||||||
|
method === "turn/plan/updated" ||
|
||||||
|
method === "item/plan/delta"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
|
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
|
||||||
const target =
|
const target =
|
||||||
key === undefined
|
key === undefined
|
||||||
@@ -1507,20 +1528,6 @@ function normalizeProviderThreadId(value: string | undefined): string | undefine
|
|||||||
return brandIfNonEmpty(value, (normalized) => normalized);
|
return brandIfNonEmpty(value, (normalized) => normalized);
|
||||||
}
|
}
|
||||||
|
|
||||||
function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
|
|
||||||
readonly binaryPath?: string;
|
|
||||||
readonly homePath?: string;
|
|
||||||
} {
|
|
||||||
const options = input.providerOptions?.codex;
|
|
||||||
if (!options) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
...(options.binaryPath ? { binaryPath: options.binaryPath } : {}),
|
|
||||||
...(options.homePath ? { homePath: options.homePath } : {}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function assertSupportedCodexCliVersion(input: {
|
function assertSupportedCodexCliVersion(input: {
|
||||||
readonly binaryPath: string;
|
readonly binaryPath: string;
|
||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
@@ -1574,14 +1581,18 @@ function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
|
|||||||
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
|
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function readResumeThreadId(input: CodexAppServerStartSessionInput): string | undefined {
|
function readResumeThreadId(input: {
|
||||||
|
readonly resumeCursor?: unknown;
|
||||||
|
readonly threadId?: ThreadId;
|
||||||
|
readonly runtimeMode?: RuntimeMode;
|
||||||
|
}): string | undefined {
|
||||||
return readResumeCursorThreadId(input.resumeCursor);
|
return readResumeCursorThreadId(input.resumeCursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||||
return brandIfNonEmpty(value, TurnId.makeUnsafe);
|
return brandIfNonEmpty(value, TurnId.make);
|
||||||
}
|
}
|
||||||
|
|
||||||
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
|
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
|
||||||
return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);
|
return brandIfNonEmpty(value, ProviderItemId.make);
|
||||||
}
|
}
|
||||||
+125
-14
@@ -6,55 +6,166 @@
|
|||||||
*
|
*
|
||||||
* @module ServerConfig
|
* @module ServerConfig
|
||||||
*/
|
*/
|
||||||
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
|
||||||
|
|
||||||
export const DEFAULT_PORT = 3773;
|
export const DEFAULT_PORT = 3773;
|
||||||
|
|
||||||
export type RuntimeMode = "web" | "desktop";
|
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
|
||||||
|
export type RuntimeMode = typeof RuntimeMode.Type;
|
||||||
|
|
||||||
|
export const StartupPresentation = Schema.Literals(["browser", "headless"]);
|
||||||
|
export type StartupPresentation = typeof StartupPresentation.Type;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ServerDerivedPaths - Derived paths from the base directory.
|
||||||
|
*/
|
||||||
|
export interface ServerDerivedPaths {
|
||||||
|
readonly stateDir: string;
|
||||||
|
readonly dbPath: string;
|
||||||
|
readonly keybindingsConfigPath: string;
|
||||||
|
readonly settingsPath: string;
|
||||||
|
readonly providerStatusCacheDir: string;
|
||||||
|
readonly worktreesDir: string;
|
||||||
|
readonly attachmentsDir: string;
|
||||||
|
readonly logsDir: string;
|
||||||
|
readonly serverLogPath: string;
|
||||||
|
readonly serverTracePath: string;
|
||||||
|
readonly providerLogsDir: string;
|
||||||
|
readonly providerEventLogPath: string;
|
||||||
|
readonly terminalLogsDir: string;
|
||||||
|
readonly anonymousIdPath: string;
|
||||||
|
readonly environmentIdPath: string;
|
||||||
|
readonly serverRuntimeStatePath: string;
|
||||||
|
readonly secretsDir: string;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ServerConfigShape - Process/runtime configuration required by the server.
|
* ServerConfigShape - Process/runtime configuration required by the server.
|
||||||
*/
|
*/
|
||||||
export interface ServerConfigShape {
|
export interface ServerConfigShape extends ServerDerivedPaths {
|
||||||
|
readonly logLevel: LogLevel.LogLevel;
|
||||||
|
readonly traceMinLevel: LogLevel.LogLevel;
|
||||||
|
readonly traceTimingEnabled: boolean;
|
||||||
|
readonly traceBatchWindowMs: number;
|
||||||
|
readonly traceMaxBytes: number;
|
||||||
|
readonly traceMaxFiles: number;
|
||||||
|
readonly otlpTracesUrl: string | undefined;
|
||||||
|
readonly otlpMetricsUrl: string | undefined;
|
||||||
|
readonly otlpExportIntervalMs: number;
|
||||||
|
readonly otlpServiceName: string;
|
||||||
readonly mode: RuntimeMode;
|
readonly mode: RuntimeMode;
|
||||||
readonly port: number;
|
readonly port: number;
|
||||||
readonly host: string | undefined;
|
readonly host: string | undefined;
|
||||||
readonly cwd: string;
|
readonly cwd: string;
|
||||||
readonly keybindingsConfigPath: string;
|
readonly baseDir: string;
|
||||||
readonly stateDir: string;
|
|
||||||
readonly staticDir: string | undefined;
|
readonly staticDir: string | undefined;
|
||||||
readonly devUrl: URL | undefined;
|
readonly devUrl: URL | undefined;
|
||||||
readonly noBrowser: boolean;
|
readonly noBrowser: boolean;
|
||||||
readonly authToken: string | undefined;
|
readonly startupPresentation: StartupPresentation;
|
||||||
|
readonly desktopBootstrapToken: string | undefined;
|
||||||
readonly autoBootstrapProjectFromCwd: boolean;
|
readonly autoBootstrapProjectFromCwd: boolean;
|
||||||
readonly logWebSocketEvents: boolean;
|
readonly logWebSocketEvents: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const deriveServerPaths = Effect.fn(function* (
|
||||||
|
baseDir: ServerConfigShape["baseDir"],
|
||||||
|
devUrl: ServerConfigShape["devUrl"],
|
||||||
|
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
|
||||||
|
const { join } = yield* Path.Path;
|
||||||
|
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
|
||||||
|
const dbPath = join(stateDir, "state.sqlite");
|
||||||
|
const attachmentsDir = join(stateDir, "attachments");
|
||||||
|
const logsDir = join(stateDir, "logs");
|
||||||
|
const providerLogsDir = join(logsDir, "provider");
|
||||||
|
const providerStatusCacheDir = join(baseDir, "caches");
|
||||||
|
return {
|
||||||
|
stateDir,
|
||||||
|
dbPath,
|
||||||
|
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
||||||
|
settingsPath: join(stateDir, "settings.json"),
|
||||||
|
providerStatusCacheDir,
|
||||||
|
worktreesDir: join(baseDir, "worktrees"),
|
||||||
|
attachmentsDir,
|
||||||
|
logsDir,
|
||||||
|
serverLogPath: join(logsDir, "server.log"),
|
||||||
|
serverTracePath: join(logsDir, "server.trace.ndjson"),
|
||||||
|
providerLogsDir,
|
||||||
|
providerEventLogPath: join(providerLogsDir, "events.log"),
|
||||||
|
terminalLogsDir: join(logsDir, "terminals"),
|
||||||
|
anonymousIdPath: join(stateDir, "anonymous-id"),
|
||||||
|
environmentIdPath: join(stateDir, "environment-id"),
|
||||||
|
serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
|
||||||
|
secretsDir: join(stateDir, "secrets"),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
|
||||||
|
yield* Effect.all(
|
||||||
|
[
|
||||||
|
fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
|
||||||
|
fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
|
||||||
|
fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
|
||||||
|
fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
|
||||||
|
fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
|
||||||
|
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
||||||
|
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
||||||
|
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
||||||
|
fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
|
||||||
|
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
|
||||||
|
fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
|
||||||
|
],
|
||||||
|
{ concurrency: "unbounded" },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ServerConfig - Service tag for server runtime configuration.
|
* ServerConfig - Service tag for server runtime configuration.
|
||||||
*/
|
*/
|
||||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShape>()(
|
||||||
"t3/config/ServerConfig",
|
"t3/config/ServerConfig",
|
||||||
) {
|
) {
|
||||||
static readonly layerTest = (cwd: string, statedir: string) =>
|
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
|
||||||
Layer.effect(
|
Layer.effect(
|
||||||
ServerConfig,
|
ServerConfig,
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const path = yield* Path.Path;
|
const devUrl = undefined;
|
||||||
|
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const baseDir =
|
||||||
|
typeof baseDirOrPrefix === "string"
|
||||||
|
? baseDirOrPrefix
|
||||||
|
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
|
||||||
|
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||||
|
yield* ensureServerDirectories(derivedPaths);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
logLevel: "Error",
|
||||||
|
traceMinLevel: "Info",
|
||||||
|
traceTimingEnabled: true,
|
||||||
|
traceBatchWindowMs: 200,
|
||||||
|
traceMaxBytes: 10 * 1024 * 1024,
|
||||||
|
traceMaxFiles: 10,
|
||||||
|
otlpTracesUrl: undefined,
|
||||||
|
otlpMetricsUrl: undefined,
|
||||||
|
otlpExportIntervalMs: 10_000,
|
||||||
|
otlpServiceName: "t3-server",
|
||||||
cwd,
|
cwd,
|
||||||
stateDir: statedir,
|
baseDir,
|
||||||
|
...derivedPaths,
|
||||||
mode: "web",
|
mode: "web",
|
||||||
autoBootstrapProjectFromCwd: false,
|
autoBootstrapProjectFromCwd: false,
|
||||||
logWebSocketEvents: false,
|
logWebSocketEvents: false,
|
||||||
port: 0,
|
port: 0,
|
||||||
host: undefined,
|
host: undefined,
|
||||||
authToken: undefined,
|
desktopBootstrapToken: undefined,
|
||||||
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
|
||||||
staticDir: undefined,
|
staticDir: undefined,
|
||||||
devUrl: undefined,
|
devUrl,
|
||||||
noBrowser: false,
|
noBrowser: false,
|
||||||
};
|
startupPresentation: "browser",
|
||||||
|
} satisfies ServerConfigShape;
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import * as nodePath from "node:path";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { expect, it } from "@effect/vitest";
|
||||||
|
import { Effect, Exit, FileSystem, Layer, PlatformError } from "effect";
|
||||||
|
|
||||||
|
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "../../config.ts";
|
||||||
|
import { ServerEnvironment } from "../Services/ServerEnvironment.ts";
|
||||||
|
import { ServerEnvironmentLive } from "./ServerEnvironment.ts";
|
||||||
|
|
||||||
|
const makeServerEnvironmentLayer = (baseDir: string) =>
|
||||||
|
ServerEnvironmentLive.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));
|
||||||
|
|
||||||
|
const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
||||||
|
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...derivedPaths,
|
||||||
|
logLevel: "Error",
|
||||||
|
traceMinLevel: "Info",
|
||||||
|
traceTimingEnabled: true,
|
||||||
|
traceBatchWindowMs: 200,
|
||||||
|
traceMaxBytes: 10 * 1024 * 1024,
|
||||||
|
traceMaxFiles: 10,
|
||||||
|
otlpTracesUrl: undefined,
|
||||||
|
otlpMetricsUrl: undefined,
|
||||||
|
otlpExportIntervalMs: 10_000,
|
||||||
|
otlpServiceName: "t3-server",
|
||||||
|
cwd: process.cwd(),
|
||||||
|
baseDir,
|
||||||
|
mode: "web",
|
||||||
|
autoBootstrapProjectFromCwd: false,
|
||||||
|
logWebSocketEvents: false,
|
||||||
|
port: 0,
|
||||||
|
host: undefined,
|
||||||
|
desktopBootstrapToken: undefined,
|
||||||
|
staticDir: undefined,
|
||||||
|
devUrl: undefined,
|
||||||
|
noBrowser: false,
|
||||||
|
startupPresentation: "browser",
|
||||||
|
} satisfies ServerConfigShape;
|
||||||
|
});
|
||||||
|
|
||||||
|
it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
|
||||||
|
it.effect("persists the environment id across service restarts", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||||
|
prefix: "t3-server-environment-test-",
|
||||||
|
});
|
||||||
|
|
||||||
|
const first = yield* Effect.gen(function* () {
|
||||||
|
const serverEnvironment = yield* ServerEnvironment;
|
||||||
|
return yield* serverEnvironment.getDescriptor;
|
||||||
|
}).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
|
||||||
|
const second = yield* Effect.gen(function* () {
|
||||||
|
const serverEnvironment = yield* ServerEnvironment;
|
||||||
|
return yield* serverEnvironment.getDescriptor;
|
||||||
|
}).pipe(Effect.provide(makeServerEnvironmentLayer(baseDir)));
|
||||||
|
|
||||||
|
expect(first.environmentId).toBe(second.environmentId);
|
||||||
|
expect(second.capabilities.repositoryIdentity).toBe(true);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("fails instead of overwriting a persisted id when reading the file errors", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||||
|
prefix: "t3-server-environment-read-error-test-",
|
||||||
|
});
|
||||||
|
const serverConfig = yield* makeServerConfig(baseDir);
|
||||||
|
const environmentIdPath = serverConfig.environmentIdPath;
|
||||||
|
yield* fileSystem.makeDirectory(nodePath.dirname(environmentIdPath), { recursive: true });
|
||||||
|
yield* fileSystem.writeFileString(environmentIdPath, "persisted-environment-id\n");
|
||||||
|
const writeAttempts: string[] = [];
|
||||||
|
const failingFileSystemLayer = FileSystem.layerNoop({
|
||||||
|
exists: (path) => Effect.succeed(path === environmentIdPath),
|
||||||
|
readFileString: (path) =>
|
||||||
|
path === environmentIdPath
|
||||||
|
? Effect.fail(
|
||||||
|
PlatformError.systemError({
|
||||||
|
_tag: "PermissionDenied",
|
||||||
|
module: "FileSystem",
|
||||||
|
method: "readFileString",
|
||||||
|
description: "permission denied",
|
||||||
|
pathOrDescriptor: path,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
: Effect.fail(
|
||||||
|
PlatformError.systemError({
|
||||||
|
_tag: "NotFound",
|
||||||
|
module: "FileSystem",
|
||||||
|
method: "readFileString",
|
||||||
|
description: "not found",
|
||||||
|
pathOrDescriptor: path,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
writeFileString: (path) => {
|
||||||
|
writeAttempts.push(path);
|
||||||
|
return Effect.void;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const exit = yield* Effect.gen(function* () {
|
||||||
|
const serverEnvironment = yield* ServerEnvironment;
|
||||||
|
return yield* serverEnvironment.getDescriptor;
|
||||||
|
}).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
ServerEnvironmentLive.pipe(
|
||||||
|
Layer.provide(
|
||||||
|
Layer.merge(Layer.succeed(ServerConfig, serverConfig), failingFileSystemLayer),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Effect.exit,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(Exit.isFailure(exit)).toBe(true);
|
||||||
|
expect(writeAttempts).toEqual([]);
|
||||||
|
expect(yield* fileSystem.readFileString(environmentIdPath)).toBe(
|
||||||
|
"persisted-environment-id\n",
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||||
|
import { Effect, FileSystem, Layer, Path, Random } from "effect";
|
||||||
|
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
|
||||||
|
import { version } from "../../../package.json" with { type: "json" };
|
||||||
|
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||||
|
|
||||||
|
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
|
||||||
|
switch (process.platform) {
|
||||||
|
case "darwin":
|
||||||
|
return "darwin";
|
||||||
|
case "linux":
|
||||||
|
return "linux";
|
||||||
|
case "win32":
|
||||||
|
return "windows";
|
||||||
|
default:
|
||||||
|
return "unknown";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function platformArch(): ExecutionEnvironmentDescriptor["platform"]["arch"] {
|
||||||
|
switch (process.arch) {
|
||||||
|
case "arm64":
|
||||||
|
return "arm64";
|
||||||
|
case "x64":
|
||||||
|
return "x64";
|
||||||
|
default:
|
||||||
|
return "other";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function* () {
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const serverConfig = yield* ServerConfig;
|
||||||
|
|
||||||
|
const readPersistedEnvironmentId = Effect.gen(function* () {
|
||||||
|
const exists = yield* fileSystem
|
||||||
|
.exists(serverConfig.environmentIdPath)
|
||||||
|
.pipe(Effect.orElseSucceed(() => false));
|
||||||
|
if (!exists) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = yield* fileSystem
|
||||||
|
.readFileString(serverConfig.environmentIdPath)
|
||||||
|
.pipe(Effect.map((value) => value.trim()));
|
||||||
|
|
||||||
|
return raw.length > 0 ? raw : null;
|
||||||
|
});
|
||||||
|
|
||||||
|
const persistEnvironmentId = (value: string) =>
|
||||||
|
fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\n`);
|
||||||
|
|
||||||
|
const environmentIdRaw = yield* Effect.gen(function* () {
|
||||||
|
const persisted = yield* readPersistedEnvironmentId;
|
||||||
|
if (persisted) {
|
||||||
|
return persisted;
|
||||||
|
}
|
||||||
|
|
||||||
|
const generated = yield* Random.nextUUIDv4;
|
||||||
|
yield* persistEnvironmentId(generated);
|
||||||
|
return generated;
|
||||||
|
});
|
||||||
|
|
||||||
|
const environmentId = EnvironmentId.make(environmentIdRaw);
|
||||||
|
const cwdBaseName = path.basename(serverConfig.cwd).trim();
|
||||||
|
const label = yield* resolveServerEnvironmentLabel({
|
||||||
|
cwdBaseName,
|
||||||
|
});
|
||||||
|
|
||||||
|
const descriptor: ExecutionEnvironmentDescriptor = {
|
||||||
|
environmentId,
|
||||||
|
label,
|
||||||
|
platform: {
|
||||||
|
os: platformOs(),
|
||||||
|
arch: platformArch(),
|
||||||
|
},
|
||||||
|
serverVersion: version,
|
||||||
|
capabilities: {
|
||||||
|
repositoryIdentity: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
getEnvironmentId: Effect.succeed(environmentId),
|
||||||
|
getDescriptor: Effect.succeed(descriptor),
|
||||||
|
} satisfies ServerEnvironmentShape;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||||
|
import { Effect, FileSystem } from "effect";
|
||||||
|
import { vi } from "vitest";
|
||||||
|
|
||||||
|
vi.mock("../../processRunner.ts", () => ({
|
||||||
|
runProcess: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { runProcess } from "../../processRunner.ts";
|
||||||
|
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||||
|
|
||||||
|
const mockedRunProcess = vi.mocked(runProcess);
|
||||||
|
const NoopFileSystemLayer = FileSystem.layerNoop({});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
mockedRunProcess.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resolveServerEnvironmentLabel", () => {
|
||||||
|
it.effect("uses hostname fallback regardless of launch mode", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const result = yield* resolveServerEnvironmentLabel({
|
||||||
|
cwdBaseName: "t3code",
|
||||||
|
platform: "win32",
|
||||||
|
hostname: "macbook-pro",
|
||||||
|
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||||
|
|
||||||
|
expect(result).toBe("macbook-pro");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("prefers the macOS ComputerName", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
mockedRunProcess.mockResolvedValueOnce({
|
||||||
|
stdout: " Julius's MacBook Pro \n",
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = yield* resolveServerEnvironmentLabel({
|
||||||
|
cwdBaseName: "t3code",
|
||||||
|
platform: "darwin",
|
||||||
|
hostname: "macbook-pro",
|
||||||
|
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||||
|
|
||||||
|
expect(result).toBe("Julius's MacBook Pro");
|
||||||
|
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||||
|
"scutil",
|
||||||
|
["--get", "ComputerName"],
|
||||||
|
expect.objectContaining({ allowNonZeroExit: true }),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("prefers Linux PRETTY_HOSTNAME from machine-info", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const result = yield* resolveServerEnvironmentLabel({
|
||||||
|
cwdBaseName: "t3code",
|
||||||
|
platform: "linux",
|
||||||
|
hostname: "buildbox",
|
||||||
|
}).pipe(
|
||||||
|
Effect.provide(
|
||||||
|
FileSystem.layerNoop({
|
||||||
|
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
|
||||||
|
readFileString: (path) =>
|
||||||
|
path === "/etc/machine-info"
|
||||||
|
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
|
||||||
|
: Effect.succeed(""),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toBe("Build Agent 01");
|
||||||
|
expect(mockedRunProcess).not.toHaveBeenCalled();
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
mockedRunProcess.mockResolvedValueOnce({
|
||||||
|
stdout: "CI Runner\n",
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = yield* resolveServerEnvironmentLabel({
|
||||||
|
cwdBaseName: "t3code",
|
||||||
|
platform: "linux",
|
||||||
|
hostname: "runner-01",
|
||||||
|
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||||
|
|
||||||
|
expect(result).toBe("CI Runner");
|
||||||
|
expect(mockedRunProcess).toHaveBeenCalledWith(
|
||||||
|
"hostnamectl",
|
||||||
|
["--pretty"],
|
||||||
|
expect.objectContaining({ allowNonZeroExit: true }),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("falls back to the hostname when friendly labels are unavailable", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const result = yield* resolveServerEnvironmentLabel({
|
||||||
|
cwdBaseName: "t3code",
|
||||||
|
platform: "win32",
|
||||||
|
hostname: "JULIUS-LAPTOP",
|
||||||
|
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||||
|
|
||||||
|
expect(result).toBe("JULIUS-LAPTOP");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
|
||||||
|
|
||||||
|
const result = yield* resolveServerEnvironmentLabel({
|
||||||
|
cwdBaseName: "t3code",
|
||||||
|
platform: "darwin",
|
||||||
|
hostname: "macbook-pro",
|
||||||
|
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||||
|
|
||||||
|
expect(result).toBe("macbook-pro");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("falls back to the cwd basename when the hostname is blank", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
mockedRunProcess.mockResolvedValueOnce({
|
||||||
|
stdout: " ",
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
signal: null,
|
||||||
|
timedOut: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = yield* resolveServerEnvironmentLabel({
|
||||||
|
cwdBaseName: "t3code",
|
||||||
|
platform: "linux",
|
||||||
|
hostname: " ",
|
||||||
|
}).pipe(Effect.provide(NoopFileSystemLayer));
|
||||||
|
|
||||||
|
expect(result).toBe("t3code");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import * as OS from "node:os";
|
||||||
|
|
||||||
|
import { Effect, FileSystem } from "effect";
|
||||||
|
|
||||||
|
import { runProcess } from "../../processRunner.ts";
|
||||||
|
|
||||||
|
interface ResolveServerEnvironmentLabelInput {
|
||||||
|
readonly cwdBaseName: string;
|
||||||
|
readonly platform?: NodeJS.Platform;
|
||||||
|
readonly hostname?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeLabel(value: string | null | undefined): string | null {
|
||||||
|
const trimmed = value?.trim();
|
||||||
|
return trimmed && trimmed.length > 0 ? trimmed : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseMachineInfoValue(raw: string, key: string): string | null {
|
||||||
|
for (const line of raw.split(/\r?\n/g)) {
|
||||||
|
const trimmed = line.trim();
|
||||||
|
if (trimmed.length === 0 || trimmed.startsWith("#") || !trimmed.startsWith(`${key}=`)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const value = trimmed.slice(key.length + 1).trim();
|
||||||
|
if (
|
||||||
|
(value.startsWith('"') && value.endsWith('"')) ||
|
||||||
|
(value.startsWith("'") && value.endsWith("'"))
|
||||||
|
) {
|
||||||
|
return normalizeLabel(value.slice(1, -1));
|
||||||
|
}
|
||||||
|
return normalizeLabel(value);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () {
|
||||||
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
|
const exists = yield* fileSystem
|
||||||
|
.exists("/etc/machine-info")
|
||||||
|
.pipe(Effect.orElseSucceed(() => false));
|
||||||
|
if (!exists) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return yield* fileSystem
|
||||||
|
.readFileString("/etc/machine-info")
|
||||||
|
.pipe(Effect.orElseSucceed(() => null));
|
||||||
|
});
|
||||||
|
|
||||||
|
const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
|
||||||
|
command: string,
|
||||||
|
args: readonly string[],
|
||||||
|
) {
|
||||||
|
const result = yield* Effect.tryPromise({
|
||||||
|
try: () =>
|
||||||
|
runProcess(command, args, {
|
||||||
|
allowNonZeroExit: true,
|
||||||
|
}),
|
||||||
|
catch: () => null,
|
||||||
|
}).pipe(Effect.orElseSucceed(() => null));
|
||||||
|
|
||||||
|
if (!result || result.code !== 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalizeLabel(result.stdout);
|
||||||
|
});
|
||||||
|
|
||||||
|
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
|
||||||
|
platform: NodeJS.Platform,
|
||||||
|
) {
|
||||||
|
if (platform === "darwin") {
|
||||||
|
return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (platform === "linux") {
|
||||||
|
const machineInfo = normalizeLabel(yield* readLinuxMachineInfo());
|
||||||
|
if (machineInfo) {
|
||||||
|
const prettyHostname = parseMachineInfoValue(machineInfo, "PRETTY_HOSTNAME");
|
||||||
|
if (prettyHostname) {
|
||||||
|
return prettyHostname;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* (
|
||||||
|
input: ResolveServerEnvironmentLabelInput,
|
||||||
|
) {
|
||||||
|
const platform = input.platform ?? process.platform;
|
||||||
|
const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform);
|
||||||
|
if (friendlyHostLabel) {
|
||||||
|
return friendlyHostLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hostname = normalizeLabel(input.hostname ?? OS.hostname());
|
||||||
|
if (hostname) {
|
||||||
|
return hostname;
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalizeLabel(input.cwdBaseName) ?? "T3 environment";
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||||
|
import { Context } from "effect";
|
||||||
|
import type { Effect } from "effect";
|
||||||
|
|
||||||
|
export interface ServerEnvironmentShape {
|
||||||
|
readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
|
||||||
|
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ServerEnvironment extends Context.Service<ServerEnvironment, ServerEnvironmentShape>()(
|
||||||
|
"t3/environment/Services/ServerEnvironment",
|
||||||
|
) {}
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
import { Schema } from "effect";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GitCommandError - Git command execution failed.
|
|
||||||
*/
|
|
||||||
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
|
|
||||||
operation: Schema.String,
|
|
||||||
command: Schema.String,
|
|
||||||
cwd: Schema.String,
|
|
||||||
detail: Schema.String,
|
|
||||||
cause: Schema.optional(Schema.Defect),
|
|
||||||
}) {
|
|
||||||
override get message(): string {
|
|
||||||
return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GitHubCliError - GitHub CLI execution or authentication failed.
|
|
||||||
*/
|
|
||||||
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
|
||||||
operation: Schema.String,
|
|
||||||
detail: Schema.String,
|
|
||||||
cause: Schema.optional(Schema.Defect),
|
|
||||||
}) {
|
|
||||||
override get message(): string {
|
|
||||||
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* TextGenerationError - Commit or PR text generation failed.
|
|
||||||
*/
|
|
||||||
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
|
|
||||||
"TextGenerationError",
|
|
||||||
{
|
|
||||||
operation: Schema.String,
|
|
||||||
detail: Schema.String,
|
|
||||||
cause: Schema.optional(Schema.Defect),
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
override get message(): string {
|
|
||||||
return `Text generation failed in ${this.operation}: ${this.detail}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GitManagerError - Stacked Git workflow orchestration failed.
|
|
||||||
*/
|
|
||||||
export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", {
|
|
||||||
operation: Schema.String,
|
|
||||||
detail: Schema.String,
|
|
||||||
cause: Schema.optional(Schema.Defect),
|
|
||||||
}) {
|
|
||||||
override get message(): string {
|
|
||||||
return `Git manager failed in ${this.operation}: ${this.detail}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
|
|
||||||
*/
|
|
||||||
export type GitManagerServiceError =
|
|
||||||
| GitManagerError
|
|
||||||
| GitCommandError
|
|
||||||
| GitHubCliError
|
|
||||||
| TextGenerationError;
|
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { it } from "@effect/vitest";
|
||||||
|
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||||
|
import { expect } from "vitest";
|
||||||
|
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
import { sanitizeThreadTitle } from "../Utils.ts";
|
||||||
|
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
|
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
|
||||||
|
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||||
|
Layer.provideMerge(
|
||||||
|
ServerConfig.layerTest(process.cwd(), {
|
||||||
|
prefix: "t3code-claude-text-generation-test-",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
);
|
||||||
|
|
||||||
|
function makeFakeClaudeBinary(dir: string) {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const binDir = path.join(dir, "bin");
|
||||||
|
const claudePath = path.join(binDir, "claude");
|
||||||
|
yield* fs.makeDirectory(binDir, { recursive: true });
|
||||||
|
|
||||||
|
yield* fs.writeFileString(
|
||||||
|
claudePath,
|
||||||
|
[
|
||||||
|
"#!/bin/sh",
|
||||||
|
'args="$*"',
|
||||||
|
'stdin_content="$(cat)"',
|
||||||
|
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
|
||||||
|
' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
|
||||||
|
' printf "%s\\n" "args missing expected content" >&2',
|
||||||
|
" exit 2",
|
||||||
|
" }",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
|
||||||
|
' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
|
||||||
|
' printf "%s\\n" "args contained forbidden content" >&2',
|
||||||
|
" exit 3",
|
||||||
|
" fi",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
|
||||||
|
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||||
|
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||||
|
" exit 4",
|
||||||
|
" }",
|
||||||
|
"fi",
|
||||||
|
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
|
||||||
|
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
|
||||||
|
"fi",
|
||||||
|
'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
|
||||||
|
'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
|
||||||
|
"",
|
||||||
|
].join("\n"),
|
||||||
|
);
|
||||||
|
yield* fs.chmod(claudePath, 0o755);
|
||||||
|
return binDir;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function withFakeClaudeEnv<A, E, R>(
|
||||||
|
input: {
|
||||||
|
output: string;
|
||||||
|
exitCode?: number;
|
||||||
|
stderr?: string;
|
||||||
|
argsMustContain?: string;
|
||||||
|
argsMustNotContain?: string;
|
||||||
|
stdinMustContain?: string;
|
||||||
|
},
|
||||||
|
effect: Effect.Effect<A, E, R>,
|
||||||
|
) {
|
||||||
|
return Effect.acquireUseRelease(
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
|
||||||
|
const binDir = yield* makeFakeClaudeBinary(tempDir);
|
||||||
|
const previousPath = process.env.PATH;
|
||||||
|
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
|
||||||
|
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
||||||
|
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
|
||||||
|
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
||||||
|
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
||||||
|
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
||||||
|
|
||||||
|
yield* Effect.sync(() => {
|
||||||
|
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||||
|
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
|
||||||
|
|
||||||
|
if (input.exitCode !== undefined) {
|
||||||
|
process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stderr !== undefined) {
|
||||||
|
process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_STDERR;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.argsMustContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.argsMustNotContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.stdinMustContain !== undefined) {
|
||||||
|
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
||||||
|
} else {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
previousPath,
|
||||||
|
previousOutput,
|
||||||
|
previousExitCode,
|
||||||
|
previousStderr,
|
||||||
|
previousArgsMustContain,
|
||||||
|
previousArgsMustNotContain,
|
||||||
|
previousStdinMustContain,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
() => effect,
|
||||||
|
(previous) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
process.env.PATH = previous.previousPath;
|
||||||
|
|
||||||
|
if (previous.previousOutput === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousExitCode === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStderr === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_STDERR;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousArgsMustContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousArgsMustNotContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous.previousStdinMustContain === undefined) {
|
||||||
|
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
||||||
|
} else {
|
||||||
|
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
|
||||||
|
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
|
||||||
|
withFakeClaudeEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
structured_output: {
|
||||||
|
subject: "Add important change",
|
||||||
|
body: "",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
|
||||||
|
argsMustNotContain: "--effort",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/claude-effect",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: {
|
||||||
|
provider: "claudeAgent",
|
||||||
|
model: "claude-haiku-4-5",
|
||||||
|
options: {
|
||||||
|
thinking: false,
|
||||||
|
effort: "high",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.subject).toBe("Add important change");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("forwards Claude fast mode and supported effort", () =>
|
||||||
|
withFakeClaudeEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
structured_output: {
|
||||||
|
title: "Improve orchestration flow",
|
||||||
|
body: "Body",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
argsMustContain: '--effort max --settings {"fastMode":true}',
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generatePrContent({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
baseBranch: "main",
|
||||||
|
headBranch: "feature/claude-effect",
|
||||||
|
commitSummary: "Improve orchestration",
|
||||||
|
diffSummary: "1 file changed",
|
||||||
|
diffPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: {
|
||||||
|
provider: "claudeAgent",
|
||||||
|
model: "claude-opus-4-6",
|
||||||
|
options: {
|
||||||
|
effort: "max",
|
||||||
|
fastMode: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.title).toBe("Improve orchestration flow");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("generates thread titles through the Claude provider", () =>
|
||||||
|
withFakeClaudeEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
structured_output: {
|
||||||
|
title:
|
||||||
|
' "Reconnect failures after restart because the session state does not recover" ',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
stdinMustContain: "You write concise thread titles for coding conversations.",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateThreadTitle({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Please investigate reconnect failures after restarting the session.",
|
||||||
|
modelSelection: {
|
||||||
|
provider: "claudeAgent",
|
||||||
|
model: "claude-sonnet-4-6",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.title).toBe(
|
||||||
|
sanitizeThreadTitle(
|
||||||
|
'"Reconnect failures after restart because the session state does not recover"',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
|
||||||
|
withFakeClaudeEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
structured_output: {
|
||||||
|
title: ' """ """ ',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateThreadTitle({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Name this thread.",
|
||||||
|
modelSelection: {
|
||||||
|
provider: "claudeAgent",
|
||||||
|
model: "claude-sonnet-4-6",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.title).toBe("New thread");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
/**
|
||||||
|
* ClaudeTextGeneration – Text generation layer using the Claude CLI.
|
||||||
|
*
|
||||||
|
* Implements the same TextGenerationShape contract as CodexTextGeneration but
|
||||||
|
* delegates to the `claude` CLI (`claude -p`) with structured JSON output
|
||||||
|
* instead of the `codex exec` CLI.
|
||||||
|
*
|
||||||
|
* @module ClaudeTextGeneration
|
||||||
|
*/
|
||||||
|
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||||
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
|
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||||
|
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||||
|
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||||
|
|
||||||
|
import { TextGenerationError } from "@t3tools/contracts";
|
||||||
|
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
import {
|
||||||
|
buildBranchNamePrompt,
|
||||||
|
buildCommitMessagePrompt,
|
||||||
|
buildPrContentPrompt,
|
||||||
|
buildThreadTitlePrompt,
|
||||||
|
} from "../Prompts.ts";
|
||||||
|
import {
|
||||||
|
normalizeCliError,
|
||||||
|
sanitizeCommitSubject,
|
||||||
|
sanitizePrTitle,
|
||||||
|
sanitizeThreadTitle,
|
||||||
|
toJsonSchemaObject,
|
||||||
|
} from "../Utils.ts";
|
||||||
|
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
|
||||||
|
|
||||||
|
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
|
||||||
|
* We only care about `structured_output`.
|
||||||
|
*/
|
||||||
|
const ClaudeOutputEnvelope = Schema.Struct({
|
||||||
|
structured_output: Schema.Unknown,
|
||||||
|
});
|
||||||
|
|
||||||
|
const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||||
|
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||||
|
|
||||||
|
const readStreamAsString = <E>(
|
||||||
|
operation: string,
|
||||||
|
stream: Stream.Stream<Uint8Array, E>,
|
||||||
|
): Effect.Effect<string, TextGenerationError> =>
|
||||||
|
stream.pipe(
|
||||||
|
Stream.decodeText(),
|
||||||
|
Stream.runFold(
|
||||||
|
() => "",
|
||||||
|
(acc, chunk) => acc + chunk,
|
||||||
|
),
|
||||||
|
Effect.mapError((cause) =>
|
||||||
|
normalizeCliError("claude", operation, cause, "Failed to collect process output"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Spawn the Claude CLI with structured JSON output and return the parsed,
|
||||||
|
* schema-validated result.
|
||||||
|
*/
|
||||||
|
const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
|
||||||
|
operation,
|
||||||
|
cwd,
|
||||||
|
prompt,
|
||||||
|
outputSchemaJson,
|
||||||
|
modelSelection,
|
||||||
|
}: {
|
||||||
|
operation:
|
||||||
|
| "generateCommitMessage"
|
||||||
|
| "generatePrContent"
|
||||||
|
| "generateBranchName"
|
||||||
|
| "generateThreadTitle";
|
||||||
|
cwd: string;
|
||||||
|
prompt: string;
|
||||||
|
outputSchemaJson: S;
|
||||||
|
modelSelection: ClaudeModelSelection;
|
||||||
|
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||||
|
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||||
|
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
|
||||||
|
getClaudeModelCapabilities(modelSelection.model),
|
||||||
|
modelSelection.options,
|
||||||
|
);
|
||||||
|
const settings = {
|
||||||
|
...(typeof normalizedOptions?.thinking === "boolean"
|
||||||
|
? { alwaysThinkingEnabled: normalizedOptions.thinking }
|
||||||
|
: {}),
|
||||||
|
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const claudeSettings = yield* Effect.map(
|
||||||
|
serverSettingsService.getSettings,
|
||||||
|
(settings) => settings.providers.claudeAgent,
|
||||||
|
).pipe(Effect.catch(() => Effect.undefined));
|
||||||
|
|
||||||
|
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
|
||||||
|
const command = ChildProcess.make(
|
||||||
|
claudeSettings?.binaryPath || "claude",
|
||||||
|
[
|
||||||
|
"-p",
|
||||||
|
"--output-format",
|
||||||
|
"json",
|
||||||
|
"--json-schema",
|
||||||
|
jsonSchemaStr,
|
||||||
|
"--model",
|
||||||
|
resolveApiModelId(modelSelection),
|
||||||
|
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||||
|
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||||
|
"--dangerously-skip-permissions",
|
||||||
|
],
|
||||||
|
{
|
||||||
|
cwd,
|
||||||
|
shell: process.platform === "win32",
|
||||||
|
stdin: {
|
||||||
|
stream: Stream.encodeText(Stream.make(prompt)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const child = yield* commandSpawner
|
||||||
|
.spawn(command)
|
||||||
|
.pipe(
|
||||||
|
Effect.mapError((cause) =>
|
||||||
|
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||||
|
[
|
||||||
|
readStreamAsString(operation, child.stdout),
|
||||||
|
readStreamAsString(operation, child.stderr),
|
||||||
|
child.exitCode.pipe(
|
||||||
|
Effect.mapError((cause) =>
|
||||||
|
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
{ concurrency: "unbounded" },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (exitCode !== 0) {
|
||||||
|
const stderrDetail = stderr.trim();
|
||||||
|
const stdoutDetail = stdout.trim();
|
||||||
|
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail:
|
||||||
|
detail.length > 0
|
||||||
|
? `Claude CLI command failed: ${detail}`
|
||||||
|
: `Claude CLI command failed with code ${exitCode}.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return stdout;
|
||||||
|
});
|
||||||
|
|
||||||
|
const rawStdout = yield* runClaudeCommand().pipe(
|
||||||
|
Effect.scoped,
|
||||||
|
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
|
||||||
|
Effect.flatMap(
|
||||||
|
Option.match({
|
||||||
|
onNone: () =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
|
||||||
|
),
|
||||||
|
onSome: (value) => Effect.succeed(value),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
|
||||||
|
rawStdout,
|
||||||
|
).pipe(
|
||||||
|
Effect.catchTag("SchemaError", (cause) =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: "Claude CLI returned unexpected output format.",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
|
||||||
|
Effect.catchTag("SchemaError", (cause) =>
|
||||||
|
Effect.fail(
|
||||||
|
new TextGenerationError({
|
||||||
|
operation,
|
||||||
|
detail: "Claude returned invalid structured output.",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// TextGenerationShape methods
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||||
|
"ClaudeTextGeneration.generateCommitMessage",
|
||||||
|
)(function* (input) {
|
||||||
|
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||||
|
branch: input.branch,
|
||||||
|
stagedSummary: input.stagedSummary,
|
||||||
|
stagedPatch: input.stagedPatch,
|
||||||
|
includeBranch: input.includeBranch === true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "claudeAgent") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateCommitMessage",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const generated = yield* runClaudeJson({
|
||||||
|
operation: "generateCommitMessage",
|
||||||
|
cwd: input.cwd,
|
||||||
|
prompt,
|
||||||
|
outputSchemaJson: outputSchema,
|
||||||
|
modelSelection: input.modelSelection,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
subject: sanitizeCommitSubject(generated.subject),
|
||||||
|
body: generated.body.trim(),
|
||||||
|
...("branch" in generated && typeof generated.branch === "string"
|
||||||
|
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
||||||
|
"ClaudeTextGeneration.generatePrContent",
|
||||||
|
)(function* (input) {
|
||||||
|
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||||
|
baseBranch: input.baseBranch,
|
||||||
|
headBranch: input.headBranch,
|
||||||
|
commitSummary: input.commitSummary,
|
||||||
|
diffSummary: input.diffSummary,
|
||||||
|
diffPatch: input.diffPatch,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "claudeAgent") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generatePrContent",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const generated = yield* runClaudeJson({
|
||||||
|
operation: "generatePrContent",
|
||||||
|
cwd: input.cwd,
|
||||||
|
prompt,
|
||||||
|
outputSchemaJson: outputSchema,
|
||||||
|
modelSelection: input.modelSelection,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
title: sanitizePrTitle(generated.title),
|
||||||
|
body: generated.body.trim(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
||||||
|
"ClaudeTextGeneration.generateBranchName",
|
||||||
|
)(function* (input) {
|
||||||
|
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||||
|
message: input.message,
|
||||||
|
attachments: input.attachments,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "claudeAgent") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const generated = yield* runClaudeJson({
|
||||||
|
operation: "generateBranchName",
|
||||||
|
cwd: input.cwd,
|
||||||
|
prompt,
|
||||||
|
outputSchemaJson: outputSchema,
|
||||||
|
modelSelection: input.modelSelection,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
branch: sanitizeBranchFragment(generated.branch),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||||
|
"ClaudeTextGeneration.generateThreadTitle",
|
||||||
|
)(function* (input) {
|
||||||
|
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||||
|
message: input.message,
|
||||||
|
attachments: input.attachments,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (input.modelSelection.provider !== "claudeAgent") {
|
||||||
|
return yield* new TextGenerationError({
|
||||||
|
operation: "generateThreadTitle",
|
||||||
|
detail: "Invalid model selection.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const generated = yield* runClaudeJson({
|
||||||
|
operation: "generateThreadTitle",
|
||||||
|
cwd: input.cwd,
|
||||||
|
prompt,
|
||||||
|
outputSchemaJson: outputSchema,
|
||||||
|
modelSelection: input.modelSelection,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
title: sanitizeThreadTitle(generated.title),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
generateCommitMessage,
|
||||||
|
generatePrContent,
|
||||||
|
generateBranchName,
|
||||||
|
generateThreadTitle,
|
||||||
|
} satisfies TextGenerationShape;
|
||||||
|
});
|
||||||
|
|
||||||
|
export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);
|
||||||
@@ -1,20 +1,43 @@
|
|||||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
import { it } from "@effect/vitest";
|
import { it } from "@effect/vitest";
|
||||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
import { Effect, FileSystem, Layer, Path, Result } from "effect";
|
||||||
import { expect } from "vitest";
|
import { expect } from "vitest";
|
||||||
|
|
||||||
import { ServerConfig } from "../../config.ts";
|
import { ServerConfig } from "../../config.ts";
|
||||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||||
import { TextGenerationError } from "../Errors.ts";
|
import { TextGenerationError } from "@t3tools/contracts";
|
||||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||||
|
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||||
|
|
||||||
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
|
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||||
CodexTextGenerationLive.pipe(
|
provider: "codex" as const,
|
||||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
model: "gpt-5.4-mini",
|
||||||
Layer.provideMerge(NodeServices.layer),
|
};
|
||||||
);
|
|
||||||
|
|
||||||
function makeFakeCodexBinary(dir: string) {
|
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||||
|
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||||
|
Layer.provideMerge(
|
||||||
|
ServerConfig.layerTest(process.cwd(), {
|
||||||
|
prefix: "t3code-codex-text-generation-test-",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
Layer.provideMerge(NodeServices.layer),
|
||||||
|
);
|
||||||
|
|
||||||
|
function makeFakeCodexBinary(
|
||||||
|
dir: string,
|
||||||
|
input: {
|
||||||
|
output: string;
|
||||||
|
exitCode?: number;
|
||||||
|
stderr?: string;
|
||||||
|
requireImage?: boolean;
|
||||||
|
requireFastServiceTier?: boolean;
|
||||||
|
requireReasoningEffort?: string;
|
||||||
|
forbidReasoningEffort?: boolean;
|
||||||
|
stdinMustContain?: string;
|
||||||
|
stdinMustNotContain?: string;
|
||||||
|
},
|
||||||
|
) {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
@@ -27,49 +50,102 @@ function makeFakeCodexBinary(dir: string) {
|
|||||||
[
|
[
|
||||||
"#!/bin/sh",
|
"#!/bin/sh",
|
||||||
'output_path=""',
|
'output_path=""',
|
||||||
|
'seen_image="0"',
|
||||||
|
'seen_fast_service_tier="0"',
|
||||||
|
'seen_reasoning_effort=""',
|
||||||
"while [ $# -gt 0 ]; do",
|
"while [ $# -gt 0 ]; do",
|
||||||
' if [ "$1" = "--image" ]; then',
|
' if [ "$1" = "--image" ]; then',
|
||||||
" shift",
|
" shift",
|
||||||
' if [ -n "$1" ]; then',
|
' if [ -n "$1" ]; then',
|
||||||
' seen_image="1"',
|
' seen_image="1"',
|
||||||
" fi",
|
" fi",
|
||||||
|
" shift",
|
||||||
|
" continue",
|
||||||
|
" fi",
|
||||||
|
' if [ "$1" = "--config" ]; then',
|
||||||
|
" shift",
|
||||||
|
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
|
||||||
|
' seen_fast_service_tier="1"',
|
||||||
|
" fi",
|
||||||
|
' case "$1" in',
|
||||||
|
" model_reasoning_effort=*)",
|
||||||
|
' seen_reasoning_effort="$1"',
|
||||||
|
" ;;",
|
||||||
|
" esac",
|
||||||
|
" shift",
|
||||||
" continue",
|
" continue",
|
||||||
" fi",
|
" fi",
|
||||||
' if [ "$1" = "--output-last-message" ]; then',
|
' if [ "$1" = "--output-last-message" ]; then',
|
||||||
" shift",
|
" shift",
|
||||||
' output_path="$1"',
|
' output_path="$1"',
|
||||||
|
" shift",
|
||||||
|
" continue",
|
||||||
" fi",
|
" fi",
|
||||||
" shift",
|
" shift",
|
||||||
"done",
|
"done",
|
||||||
'stdin_content="$(cat)"',
|
'stdin_content="$(cat)"',
|
||||||
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
|
...(input.requireImage
|
||||||
' printf "%s\\n" "missing --image input" >&2',
|
? [
|
||||||
" exit 2",
|
'if [ "$seen_image" != "1" ]; then',
|
||||||
"fi",
|
' printf "%s\\n" "missing --image input" >&2',
|
||||||
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
|
` exit 2`,
|
||||||
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
|
"fi",
|
||||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
]
|
||||||
" exit 3",
|
: []),
|
||||||
" }",
|
...(input.requireFastServiceTier
|
||||||
"fi",
|
? [
|
||||||
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
|
'if [ "$seen_fast_service_tier" != "1" ]; then',
|
||||||
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
|
' printf "%s\\n" "missing fast service tier config" >&2',
|
||||||
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
` exit 5`,
|
||||||
" exit 4",
|
"fi",
|
||||||
" fi",
|
]
|
||||||
"fi",
|
: []),
|
||||||
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
|
...(input.requireReasoningEffort !== undefined
|
||||||
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
? [
|
||||||
"fi",
|
`if [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"${input.requireReasoningEffort}\\"" ]; then`,
|
||||||
|
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
|
||||||
|
` exit 6`,
|
||||||
|
"fi",
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
...(input.forbidReasoningEffort
|
||||||
|
? [
|
||||||
|
'if [ -n "$seen_reasoning_effort" ]; then',
|
||||||
|
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
|
||||||
|
` exit 7`,
|
||||||
|
"fi",
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
...(input.stdinMustContain !== undefined
|
||||||
|
? [
|
||||||
|
`if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
|
||||||
|
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||||
|
` exit 3`,
|
||||||
|
"fi",
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
...(input.stdinMustNotContain !== undefined
|
||||||
|
? [
|
||||||
|
`if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`,
|
||||||
|
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
||||||
|
` exit 4`,
|
||||||
|
"fi",
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
...(input.stderr !== undefined
|
||||||
|
? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`]
|
||||||
|
: []),
|
||||||
'if [ -n "$output_path" ]; then',
|
'if [ -n "$output_path" ]; then',
|
||||||
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
|
" cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
|
||||||
|
input.output,
|
||||||
|
"__T3CODE_FAKE_CODEX_OUTPUT__",
|
||||||
"fi",
|
"fi",
|
||||||
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
|
`exit ${input.exitCode ?? 0}`,
|
||||||
"",
|
"",
|
||||||
].join("\n"),
|
].join("\n"),
|
||||||
);
|
);
|
||||||
yield* fs.chmod(codexPath, 0o755);
|
yield* fs.chmod(codexPath, 0o755);
|
||||||
return binDir;
|
return codexPath;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,6 +155,9 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
exitCode?: number;
|
exitCode?: number;
|
||||||
stderr?: string;
|
stderr?: string;
|
||||||
requireImage?: boolean;
|
requireImage?: boolean;
|
||||||
|
requireFastServiceTier?: boolean;
|
||||||
|
requireReasoningEffort?: string;
|
||||||
|
forbidReasoningEffort?: boolean;
|
||||||
stdinMustContain?: string;
|
stdinMustContain?: string;
|
||||||
stdinMustNotContain?: string;
|
stdinMustNotContain?: string;
|
||||||
},
|
},
|
||||||
@@ -88,106 +167,32 @@ function withFakeCodexEnv<A, E, R>(
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||||
const binDir = yield* makeFakeCodexBinary(tempDir);
|
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
||||||
const previousPath = process.env.PATH;
|
const serverSettings = yield* ServerSettingsService;
|
||||||
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
const previousSettings = yield* serverSettings.getSettings;
|
||||||
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
yield* serverSettings.updateSettings({
|
||||||
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
providers: {
|
||||||
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
codex: {
|
||||||
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
binaryPath: codexPath,
|
||||||
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
},
|
||||||
|
},
|
||||||
yield* Effect.sync(() => {
|
|
||||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
|
||||||
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
|
|
||||||
|
|
||||||
if (input.exitCode !== undefined) {
|
|
||||||
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.stderr !== undefined) {
|
|
||||||
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CODEX_STDERR;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.requireImage) {
|
|
||||||
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.stdinMustContain !== undefined) {
|
|
||||||
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (input.stdinMustNotContain !== undefined) {
|
|
||||||
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
|
|
||||||
} else {
|
|
||||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
|
||||||
return {
|
|
||||||
previousPath,
|
|
||||||
previousOutput,
|
|
||||||
previousExitCode,
|
|
||||||
previousStderr,
|
|
||||||
previousRequireImage,
|
|
||||||
previousStdinMustContain,
|
|
||||||
previousStdinMustNotContain,
|
|
||||||
};
|
|
||||||
}),
|
}),
|
||||||
() => effect,
|
() => effect,
|
||||||
(previous) =>
|
({ serverSettings, previousBinaryPath }) =>
|
||||||
Effect.sync(() => {
|
serverSettings
|
||||||
process.env.PATH = previous.previousPath;
|
.updateSettings({
|
||||||
|
providers: {
|
||||||
if (previous.previousOutput === undefined) {
|
codex: {
|
||||||
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
binaryPath: previousBinaryPath,
|
||||||
} else {
|
},
|
||||||
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
|
},
|
||||||
}
|
})
|
||||||
|
.pipe(Effect.asVoid),
|
||||||
if (previous.previousExitCode === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousStderr === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CODEX_STDERR;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousRequireImage === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousStdinMustContain === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (previous.previousStdinMustNotContain === undefined) {
|
|
||||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
|
||||||
} else {
|
|
||||||
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
|
||||||
|
|
||||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||||
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
@@ -207,6 +212,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
branch: "feature/codex-effect",
|
branch: "feature/codex-effect",
|
||||||
stagedSummary: "M README.md",
|
stagedSummary: "M README.md",
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||||
@@ -217,6 +223,63 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect(
|
||||||
|
"forwards codex fast mode and non-default reasoning effort into codex exec config",
|
||||||
|
() =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
subject: "Add important change",
|
||||||
|
body: "",
|
||||||
|
}),
|
||||||
|
requireFastServiceTier: true,
|
||||||
|
requireReasoningEffort: "xhigh",
|
||||||
|
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/codex-effect",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: {
|
||||||
|
provider: "codex",
|
||||||
|
model: "gpt-5.4",
|
||||||
|
options: {
|
||||||
|
reasoningEffort: "xhigh",
|
||||||
|
fastMode: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("defaults git text generation codex effort to low", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
subject: "Add important change",
|
||||||
|
body: "",
|
||||||
|
}),
|
||||||
|
requireReasoningEffort: "low",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/codex-effect",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
it.effect("generates commit message with branch when includeBranch is true", () =>
|
it.effect("generates commit message with branch when includeBranch is true", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
{
|
{
|
||||||
@@ -236,6 +299,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
stagedSummary: "M README.md",
|
stagedSummary: "M README.md",
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
includeBranch: true,
|
includeBranch: true,
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.subject).toBe("Add important change");
|
expect(generated.subject).toBe("Add important change");
|
||||||
@@ -262,6 +326,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
commitSummary: "feat: improve orchestration flow",
|
commitSummary: "feat: improve orchestration flow",
|
||||||
diffSummary: "2 files changed",
|
diffSummary: "2 files changed",
|
||||||
diffPatch: "diff --git a/a.ts b/a.ts",
|
diffPatch: "diff --git a/a.ts b/a.ts",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.title).toBe("Improve orchestration flow");
|
expect(generated.title).toBe("Improve orchestration flow");
|
||||||
@@ -285,6 +350,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
const generated = yield* textGeneration.generateBranchName({
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Please update session handling.",
|
message: "Please update session handling.",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.branch).toBe("feat/session");
|
expect(generated.branch).toBe("feat/session");
|
||||||
@@ -292,6 +358,70 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect("generates thread titles and trims them for sidebar use", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
title:
|
||||||
|
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateThreadTitle({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Please investigate websocket reconnect regressions after a worktree restore.",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("falls back when thread title normalization becomes whitespace-only", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
title: ' """ """ ',
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateThreadTitle({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Name this thread.",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.title).toBe("New thread");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("trims whitespace exposed after quote removal in thread titles", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
title: ` "' hello world '" `,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateThreadTitle({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
message: "Name this thread.",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.title).toBe("hello world");
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
{
|
{
|
||||||
@@ -306,6 +436,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
const generated = yield* textGeneration.generateBranchName({
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix timeout behavior.",
|
message: "Fix timeout behavior.",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(generated.branch).toBe("fix/session-timeout");
|
expect(generated.branch).toBe("fix/session-timeout");
|
||||||
@@ -325,27 +456,27 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
|
const { attachmentsDir } = yield* ServerConfig;
|
||||||
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||||
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||||
|
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = yield* textGeneration
|
const generated = yield* textGeneration.generateBranchName({
|
||||||
.generateBranchName({
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix layout bug from screenshot.",
|
message: "Fix layout bug from screenshot.",
|
||||||
attachments: [
|
attachments: [
|
||||||
{
|
{
|
||||||
type: "image",
|
type: "image",
|
||||||
id: attachmentId,
|
id: attachmentId,
|
||||||
name: "bug.png",
|
name: "bug.png",
|
||||||
mimeType: "image/png",
|
mimeType: "image/png",
|
||||||
sizeBytes: 5,
|
sizeBytes: 5,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
});
|
||||||
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
|
|
||||||
|
|
||||||
expect(generated.branch).toBe("fix/ui-regression");
|
expect(generated.branch).toBe("fix/ui-regression");
|
||||||
}),
|
}),
|
||||||
@@ -363,14 +494,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
|
const { attachmentsDir } = yield* ServerConfig;
|
||||||
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||||
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||||
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||||
|
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const generated = yield* textGeneration
|
const generated = yield* textGeneration
|
||||||
.generateBranchName({
|
.generateBranchName({
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix layout bug from screenshot.",
|
message: "Fix layout bug from screenshot.",
|
||||||
attachments: [
|
attachments: [
|
||||||
@@ -410,13 +543,15 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const fs = yield* FileSystem.FileSystem;
|
const fs = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
|
const { attachmentsDir } = yield* ServerConfig;
|
||||||
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||||
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
|
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
|
||||||
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||||
|
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
const result = yield* textGeneration
|
const result = yield* textGeneration
|
||||||
.generateBranchName({
|
.generateBranchName({
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix layout bug from screenshot.",
|
message: "Fix layout bug from screenshot.",
|
||||||
attachments: [
|
attachments: [
|
||||||
@@ -429,17 +564,12 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(Effect.result);
|
||||||
Effect.match({
|
|
||||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
|
||||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result._tag).toBe("Left");
|
expect(Result.isFailure(result)).toBe(true);
|
||||||
if (result._tag === "Left") {
|
if (Result.isFailure(result)) {
|
||||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||||
expect(result.left.message).toContain("missing --image input");
|
expect(result.failure.message).toContain("missing --image input");
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -461,18 +591,14 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
.generateBranchName({
|
.generateBranchName({
|
||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
message: "Fix websocket reconnect flake",
|
message: "Fix websocket reconnect flake",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(Effect.result);
|
||||||
Effect.match({
|
|
||||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
|
||||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result._tag).toBe("Left");
|
expect(Result.isFailure(result)).toBe(true);
|
||||||
if (result._tag === "Left") {
|
if (Result.isFailure(result)) {
|
||||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||||
expect(result.left.message).toContain("Codex returned invalid structured output");
|
expect(result.failure.message).toContain("Codex returned invalid structured output");
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
@@ -494,18 +620,16 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
branch: "feature/codex-error",
|
branch: "feature/codex-error",
|
||||||
stagedSummary: "M README.md",
|
stagedSummary: "M README.md",
|
||||||
stagedPatch: "diff --git a/README.md b/README.md",
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||||
})
|
})
|
||||||
.pipe(
|
.pipe(Effect.result);
|
||||||
Effect.match({
|
|
||||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
|
||||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result._tag).toBe("Left");
|
expect(Result.isFailure(result)).toBe(true);
|
||||||
if (result._tag === "Left") {
|
if (Result.isFailure(result)) {
|
||||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||||
expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
|
expect(result.failure.message).toContain(
|
||||||
|
"Codex CLI command failed: codex execution failed",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|||||||
Loaded 100 of 635 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user