Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PeerLinks.testkit.ts

190 lines7.6 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import {
4 EnvironmentHttpApi,
5 EnvironmentId,
6 type AuthMcpClientAccess,
7 type ExecutionEnvironmentDescriptor,
8} from "@t3tools/contracts";
9import * as Context from "effect/Context";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Ref from "effect/Ref";
13import * as FetchHttpClient from "effect/http/FetchHttpClient";
14import * as HttpRouter from "effect/http/HttpRouter";
15import * as HttpServer from "effect/http/HttpServer";
16import * as HttpServerRequest from "effect/http/HttpServerRequest";
17import * as HttpApi from "effect/http-api/HttpApi";
18import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
19​
20import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
21import * as AuthHttp from "../auth/http.ts";
22import * as McpOAuth from "../auth/McpOAuth.ts";
23import * as McpOAuthHttp from "../auth/mcpOAuthHttp.ts";
24import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
25import * as ServerConfig from "../config.ts";
26import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
27import * as ServerHttp from "../http.ts";
28import * as McpHttpServer from "../mcp/McpHttpServer.ts";
29import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
30import * as Sqlite from "../persistence/Sqlite.ts";
31import * as PeerLinks from "./PeerLinks.ts";
32import * as ServerSettings from "../serverSettings.ts";
33import * as PeerMcpClient from "./PeerMcpClient.ts";
34import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
35​
36class PeerTestApi extends HttpApi.make("environment")
37 .add(EnvironmentHttpApi.groups.metadata)
38 .add(EnvironmentHttpApi.groups.mcpOAuth) {}
39​
40export const descriptorOf = (
41 environmentId: string,
42 label: string,
43 capabilities: Partial<ExecutionEnvironmentDescriptor["capabilities"]> = {},
44): ExecutionEnvironmentDescriptor => ({
45 environmentId: EnvironmentId.make(environmentId),
46 label,
47 platform: { os: "linux", arch: "x64" },
48 serverVersion: "0.0.0-test",
49 capabilities: {
50 repositoryIdentity: true,
51 mcpModeLimitHeader: true,
52 linkFence: true,
53 ...capabilities,
54 },
55});
56​
57/**
58 * The environment a link points at, as it runs: its descriptor, MCP OAuth,
59 * and `/mcp` with `tools` behind the real client authenticator, on a real
60 * socket. The descriptor can be swapped, as when its address comes to answer
61 * as another environment, and every bearer it receives is recorded.
62 */
63export const servePeer = <E, R>(
64 initial: ExecutionEnvironmentDescriptor,
65 tools: Layer.Layer<never, E, R>,
66) =>
67 Effect.gen(function* () {
68 const descriptor = yield* Ref.make(initial);
69 const bearers = yield* Ref.make<ReadonlyArray<string>>([]);
70 const probes = yield* Ref.make(0);
71 const layerEnvironment = Layer.succeed(ServerEnvironment.ServerEnvironment, {
72 getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)),
73 getDescriptor: Ref.get(descriptor),
74 });
75 const authContext = yield* EnvironmentAuth.layer.pipe(
76 Layer.provide(ManagedPolicy.layerTest()),
77 Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
78 Layer.provide(Sqlite.layerMemory),
79 Layer.provideMerge(ServerSecretStore.layer),
80 Layer.provideMerge(ServerEnvironment.layerIdentity),
81 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-peer-" })),
82 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
83 Layer.fresh,
84 Layer.build,
85 );
86 const layerRecordBearers = HttpRouter.middleware(
87 (httpEffect) =>
88 Effect.gen(function* () {
89 const request = yield* HttpServerRequest.HttpServerRequest;
90 if (request.url.startsWith("/.well-known/t3/environment")) {
91 yield* Ref.update(probes, (count) => count + 1);
92 }
93 const authorization = request.headers.authorization;
94 if (authorization !== undefined) {
95 yield* Ref.update(bearers, (seen) => [...seen, authorization]);
96 }
97 return yield* httpEffect;
98 }),
99 { global: true },
100 );
101 const layerRoutes = Layer.mergeAll(
102 HttpApiBuilder.layer(PeerTestApi).pipe(
103 Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
104 Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
105 Layer.provide(AuthHttp.layerAuthenticatedAuth),
106 ),
107 McpHttpServer.layerMcpTransport(tools).pipe(
108 Layer.provide(
109 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
110 // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
111 resolve: () => Effect.succeed(undefined),
112 }),
113 ),
114 Layer.provide(McpOAuth.layerMcpClientAuthenticator),
115 ),
116 ).pipe(
117 Layer.provide(layerRecordBearers),
118 Layer.provide(layerEnvironment),
119 Layer.provide(Layer.succeedContext(authContext)),
120 );
121 // Fresh, so the peer never shares a toolkit or MCP server with the
122 // environment that links to it in the same test.
123 yield* HttpRouter.serve(layerRoutes, { disableListenLog: true, disableLogger: true }).pipe(
124 Layer.fresh,
125 Layer.build,
126 );
127 const address = (yield* HttpServer.HttpServer).address;
128 if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
129 const url = `http://127.0.0.1:${address.port}`;
130 const auth = Context.get(authContext, EnvironmentAuth.EnvironmentAuth);
131 return {
132 url,
133 auth,
134 /** Its settings, as for turning its Linked environments beta off. */
135 settings: Context.get(authContext, ServerSettings.ServerSettingsService),
136 descriptor,
137 bearers,
138 /** How often its descriptor was asked for, as a probe of whether it answers. */
139 probes,
140 /** The sessions linking created there, which its Connections lists. */
141 linkedSessions: auth
142 .listSessions()
143 .pipe(
144 Effect.map((sessions) =>
145 sessions.filter((session) => session.client.label?.startsWith("T3 Code · ")),
146 ),
147 ),
148 };
149 });
150​
151export type ServedPeer = Effect.Success<ReturnType<typeof servePeer>>;
152​
153/**
154 * The environment that links: its own database and secret store, reaching
155 * peers over plain HTTP. Provide it to anything built on its links.
156 */
157export const layerLinkingEnvironment = (
158 descriptor: ExecutionEnvironmentDescriptor,
159 secrets: typeof ServerSecretStore.layer = ServerSecretStore.layer,
160) =>
161 PeerMcpClient.layer.pipe(
162 Layer.provideMerge(PeerLinks.layer),
163 Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
164 Layer.provideMerge(Sqlite.layerMemory),
165 Layer.provide(Layer.mergeAll(secrets, FetchHttpClient.layer)),
166 // Services that act for this environment, such as delegation, name it too.
167 Layer.provideMerge(
168 Layer.succeed(ServerEnvironment.ServerEnvironment, {
169 getEnvironmentId: Effect.succeed(descriptor.environmentId),
170 getDescriptor: Effect.succeed(descriptor),
171 }),
172 ),
173 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-here-" })),
174 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
175 Layer.fresh,
176 );
177​
178/** Links `links` to `peer` with a fresh pairing code from it. */
179export const linkTo = (
180 links: PeerLinks.PeerLinks["Service"],
181 peer: ServedPeer,
182 access: AuthMcpClientAccess = "auto",
183) =>
184 peer.auth
185 .issuePairingCredential()
186 .pipe(
187 Effect.flatMap((pairing) =>
188 links.link({ url: peer.url, pairingCode: pairing.credential, access }),
189 ),
190 );