@devries-cameron20 / t3code Mirror · read-only / commits / 478fdfc0ea
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 19:30 UTC

fix(server): keep managed Codex token renewal in the server (#21786)

Julius Marminge committed Oct 22, 2026 at 16:41 UTC 478fdfc0eadebcc1bb80fd6ff55f1b2c1fd577de
4 files changed +534 -1
apps/server/src/provider/CodexChatGptAuth.test.ts
+218 -1
@@ -1,4 +1,9 @@
1 // @effect-diagnostics nodeBuiltinImport:off globalFetchInEffect:off - Local mock OAuth server validates the browser callback boundary.
2 +import * as NodeNet from "node:net";
3 +import * as Context from "effect/Context";
4 +import * as Scope from "effect/Scope";
5 +import * as ServerConfig from "../config.ts";
6 +import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
7 import * as NodeHttp from "node:http";
8 import * as NodeCrypto from "node:crypto";
9 import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -11,7 +16,7 @@ import * as Stream from "effect/Stream";
16 import * as Fiber from "effect/Fiber";
17 import * as Deferred from "effect/Deferred";
18 import { subscribeChatGptHandoff } from "./CodexChatGptHandoff.ts";
14 -import { FetchHttpClient } from "effect/http";
19 +import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
20 import { exportJWK, generateKeyPair, SignJWT } from "jose";
21 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
22 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
@@ -320,6 +325,16 @@ const makeHarnessFor = Effect.fnUntraced(function* (
325 );
326 return { auth: destination, bytes: destinationBytes };
327 }),
328 + bindProfile: (expectedProfileKey: string) =>
329 + makeCodexChatGptAuth({
330 + instanceId,
331 + expectedProfileKey,
332 + discoveryUrl: `${origin}/discovery`,
333 + resource: `${origin}/v1`,
334 + }).pipe(
335 + Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
336 + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment),
337 + ),
338 recreateAuth: makeCodexChatGptAuth({
339 instanceId,
340 discoveryUrl: `${origin}/discovery`,
@@ -1604,3 +1619,205 @@ it.effect("telemetry failures do not fail a verified ChatGPT sign-in", () =>
1619 }),
1620 ),
1621 );
1622 +it.effect("a running session renews its bound profile but refuses a replacement sign-in", () =>
1623 + provision(
1624 + Effect.gen(function* () {
1625 + const h = yield* makeHarness;
1626 + yield* h.signIn;
1627 + yield* h.phase("succeeded");
1628 + const profileKey = yield* h.auth.profileKey(Option.getOrThrow(yield* h.auth.read));
1629 + const first = yield* h.bindProfile(profileKey);
1630 + const second = yield* h.bindProfile(profileKey);
1631 + yield* h.seedExpired;
1632 + const renewed = yield* Effect.all([first.access, second.access], {
1633 + concurrency: "unbounded",
1634 + });
1635 + assert.equal(h.refreshes(), 1);
1636 + assert.equal(renewed[0].accessToken, "access-1");
1637 + assert.deepEqual(renewed[0], renewed[1]);
1638 + assert.equal(yield* h.auth.profileKey(renewed[0]), profileKey);
1639 +
1640 + // Reconnecting the same account replaces its sign-in identity, too.
1641 + yield* h.reconnectProfile("oaiapp_test");
1642 + yield* h.phase("succeeded");
1643 + const replacement = Option.getOrThrow(yield* h.auth.read);
1644 + assert.equal(replacement.clientId, renewed[0].clientId);
1645 + assert.equal(replacement.subject, renewed[0].subject);
1646 + yield* h.seedExpired;
1647 + assert.equal((yield* first.access.pipe(Effect.flip)).operation, "access");
1648 + assert.equal(h.refreshes(), 1);
1649 + yield* h.auth.revoke;
1650 + assert.equal((yield* second.access.pipe(Effect.flip)).operation, "access");
1651 + assert.isTrue(Option.isNone(yield* h.auth.read));
1652 + }),
1653 + ),
1654 +);
1655 +
1656 +const makeRenewalBroker = Effect.gen(function* () {
1657 + const oauthEntered = yield* Deferred.make<void>();
1658 + const oauthRelease = yield* Deferred.make<void>();
1659 + let pauseOAuth = false;
1660 + const refreshTokens: string[] = [];
1661 + const credentials = {
1662 + clientId: "oaiapp_broker",
1663 + subject: "broker-user",
1664 + idToken: "broker-sign-in",
1665 + email: null,
1666 + accessToken: "expired-access",
1667 + refreshToken: "single-use-refresh",
1668 + expiresAt: 0,
1669 + earliestRefreshAt: null,
1670 + scopes: ["chatgpt.tokens.use.direct"],
1671 + };
1672 + const environmentId = EnvironmentId.make("00000000-0000-4000-8000-000000000001");
1673 + const http = HttpClient.make((request) =>
1674 + Effect.gen(function* () {
1675 + if (request.url.endsWith("openid-configuration")) {
1676 + return HttpClientResponse.fromWeb(
1677 + request,
1678 + Response.json({
1679 + issuer: "https://auth.openai.com",
1680 + authorization_endpoint: "https://auth.openai.com/authorize",
1681 + token_endpoint: "https://auth.openai.com/token",
1682 + jwks_uri: "https://auth.openai.com/jwks",
1683 + }),
1684 + );
1685 + }
1686 + assert.equal(request.url, "https://auth.openai.com/token");
1687 + assert.equal(request.body._tag, "Uint8Array");
1688 + if (request.body._tag !== "Uint8Array") return yield* Effect.die("Missing refresh body");
1689 + const body = new URLSearchParams(new TextDecoder().decode(request.body.body));
1690 + refreshTokens.push(body.get("refresh_token")!);
1691 + yield* Deferred.succeed(oauthEntered, undefined);
1692 + if (pauseOAuth) yield* Deferred.await(oauthRelease);
1693 + return HttpClientResponse.fromWeb(
1694 + request,
1695 + Response.json({
1696 + access_token: "renewed-access",
1697 + refresh_token: "rotated-refresh",
1698 + expires_in: 3600,
1699 + token_type: "Bearer",
1700 + scope: "chatgpt.tokens.use.direct",
1701 + }),
1702 + );
1703 + }),
1704 + );
1705 + return yield* Effect.gen(function* () {
1706 + const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId);
1707 + yield* store.set(new TextEncoder().encode(JSON.stringify(credentials)));
1708 + const auth = yield* makeCodexChatGptAuth({ instanceId });
1709 + const profileKey = yield* auth.profileKey(credentials);
1710 + const scope = yield* Scope.make();
1711 + yield* Effect.addFinalizer((exit) => Scope.close(scope, exit));
1712 + const context = yield* Layer.buildWithScope(CodexManagedTokenBroker.layer, scope);
1713 + const broker = Context.get(context, CodexManagedTokenBroker.CodexManagedTokenBroker);
1714 + const endpoint = yield* broker.endpoint;
1715 + yield* Effect.addFinalizer(() => Deferred.succeed(oauthRelease, undefined));
1716 + return {
1717 + auth,
1718 + store,
1719 + broker,
1720 + endpoint,
1721 + refreshTokens,
1722 + request: { version: 1, instanceId, environmentId, profileKey },
1723 + oauthEntered,
1724 + oauthRelease,
1725 + pause: () => {
1726 + pauseOAuth = true;
1727 + },
1728 + };
1729 + }).pipe(
1730 + Effect.provide(ServerSecretStore.layer),
1731 + Effect.provideService(HttpClient.HttpClient, http),
1732 + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, {
1733 + getEnvironmentId: Effect.succeed(environmentId),
1734 + }),
1735 + );
1736 +});
1737 +
1738 +const brokerClient = (endpoint: string, request: unknown) =>
1739 + Effect.acquireRelease(
1740 + Effect.callback<{ socket: NodeNet.Socket; response: Promise<string> }, Error>((resume) => {
1741 + const socket = NodeNet.createConnection(endpoint);
1742 + let text = "";
1743 + socket.setEncoding("utf8");
1744 + socket.on("data", (chunk) => {
1745 + text += chunk;
1746 + });
1747 + const response = new Promise<string>((resolve) => socket.once("close", () => resolve(text)));
1748 + socket.on("error", () => {});
1749 + socket.once("error", (error) => resume(Effect.fail(error)));
1750 + socket.once("connect", () => {
1751 + socket.write(JSON.stringify(request) + "\n");
1752 + resume(Effect.succeed({ socket, response }));
1753 + });
1754 + return Effect.sync(() => {
1755 + if (socket.connecting) socket.destroy();
1756 + });
1757 + }),
1758 + ({ socket }) => Effect.sync(() => socket.destroy()),
1759 + );
1760 +const provideBroker = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
1761 + effect.pipe(
1762 + Effect.scoped,
1763 + Effect.provide(
1764 + ServerConfig.layerTest(process.cwd(), { prefix: "t3-renewal-test-" }).pipe(
1765 + Layer.provideMerge(NodeServices.layer),
1766 + ),
1767 + ),
1768 + );
1769 +
1770 +// regression: #16132 a renewal must outlive the Codex helper that asked for it, because the
1771 +// refresh token it spends is single-use.
1772 +it.effect("server-owned renewal persists rotated credentials after the helper disconnects", () =>
1773 + provideBroker(
1774 + Effect.gen(function* () {
1775 + const h = yield* makeRenewalBroker;
1776 + h.pause();
1777 + const client = yield* brokerClient(h.endpoint, h.request);
1778 + yield* Deferred.await(h.oauthEntered);
1779 + client.socket.destroy();
1780 + yield* Effect.promise(() => client.response);
1781 + assert.equal(Option.getOrThrow(yield* h.auth.read).refreshToken, "single-use-refresh");
1782 + yield* Deferred.succeed(h.oauthRelease, undefined);
1783 + yield* h.broker.awaitIdle;
1784 + const persisted = Option.getOrThrow(yield* h.auth.read);
1785 + assert.equal(persisted.refreshToken, "rotated-refresh");
1786 + assert.equal((yield* h.auth.access).accessToken, "renewed-access");
1787 + assert.deepEqual(h.refreshTokens, ["single-use-refresh"]);
1788 + }),
1789 + ),
1790 +);
1791 +
1792 +it.live("the private broker refuses another environment, instance, or sign-in profile", () =>
1793 + provideBroker(
1794 + Effect.gen(function* () {
1795 + const h = yield* makeRenewalBroker;
1796 + yield* Effect.forEach(
1797 + [
1798 + {
1799 + ...h.request,
1800 + environmentId: EnvironmentId.make("00000000-0000-4000-8000-000000000002"),
1801 + },
1802 + { ...h.request, instanceId: ProviderInstanceId.make("another-instance") },
1803 + { ...h.request, profileKey: "0".repeat(64) },
1804 + ],
1805 + (request) =>
1806 + Effect.scoped(
1807 + Effect.gen(function* () {
1808 + const client = yield* brokerClient(h.endpoint, request);
1809 + assert.equal(yield* Effect.promise(() => client.response), "");
1810 + }),
1811 + ),
1812 + );
1813 + yield* h.broker.awaitIdle;
1814 + assert.deepEqual(h.refreshTokens, []);
1815 + const client = yield* brokerClient(h.endpoint, h.request);
1816 + assert.deepEqual(JSON.parse(yield* Effect.promise(() => client.response)), {
1817 + token: "renewed-access",
1818 + });
1819 + yield* h.broker.awaitIdle;
1820 + assert.deepEqual(h.refreshTokens, ["single-use-refresh"]);
1821 + }),
1822 + ),
1823 +);
apps/server/src/provider/CodexChatGptAuth.ts
+19
@@ -15,6 +15,7 @@ import * as Cause from "effect/Cause";
15 import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
16 import { openAiUserId } from "../telemetry/Identify.ts";
17 import * as Crypto from "effect/Crypto";
18 +import * as Hex from "effect/encoding/Hex";
19 import * as Exit from "effect/Exit";
20 import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts";
21 import * as Effect from "effect/Effect";
@@ -108,6 +109,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
109 readonly defaultReturnUrl?: string;
110 readonly reconnectProfile?: ChatGptReconnectProfile | null;
111 readonly telemetryFlow?: "direct" | "primary_handoff";
112 + readonly expectedProfileKey?: string;
113 }) {
114 const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
115 const settings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
@@ -726,6 +728,17 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
728 ),
729 );
730 });
731 + // ID tokens survive renewal but change on sign-in. Bind active children to the
732 + // launch profile without putting an identity token or subject in their argv.
733 + const profileKey = (record: CodexChatGptCredentials) =>
734 + crypto
735 + .digest(
736 + "SHA-256",
737 + new TextEncoder().encode(
738 + JSON.stringify([record.clientId, record.subject, record.idToken ?? null]),
739 + ),
740 + )
741 + .pipe(Effect.map(Hex.encode), Effect.orDie);
742 const access = lock.withPermit(
743 withSessionLock(
744 Effect.uninterruptible(
@@ -734,6 +747,11 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
747 if (Option.isNone(saved))
748 return yield* failure("access", "Sign in with ChatGPT to use managed Codex.");
749 let record = saved.value;
750 + if (
751 + options.expectedProfileKey !== undefined &&
752 + (yield* profileKey(record)) !== options.expectedProfileKey
753 + )
754 + return yield* failure("access", "The ChatGPT connection changed. Start a new session.");
755 if (!record.scopes.includes(REQUIRED_SCOPE))
756 return yield* failure(
757 "sharing",
@@ -991,6 +1009,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
1009 controller: { ...controller, reconnectProfile, importProfile },
1010 read,
1011 access,
1012 + profileKey,
1013 exportProfile,
1014 revoke: lock.withPermit(withSessionLock(remove)),
1015 };
apps/server/src/provider/CodexManagedTokenBroker.ts new
+225
@@ -0,0 +1,225 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - Server-owned private pipe/Unix socket, never a public listener.
2 +import * as NodeFSP from "node:fs/promises";
3 +import * as NodeNet from "node:net";
4 +import * as NodeOS from "node:os";
5 +import * as NodePath from "node:path";
6 +import * as NodeCrypto from "node:crypto";
7 +import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
8 +import * as HostProcess from "@t3tools/shared/HostProcess";
9 +import * as Context from "effect/Context";
10 +import * as Effect from "effect/Effect";
11 +import * as FiberSet from "effect/FiberSet";
12 +import * as Layer from "effect/Layer";
13 +import * as Exit from "effect/Exit";
14 +import * as Scope from "effect/Scope";
15 +import * as Schema from "effect/Schema";
16 +import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
17 +import { makeCodexChatGptAuth } from "./CodexChatGptAuth.ts";
18 +import * as Protocol from "./CodexManagedTokenProtocol.ts";
19 +
20 +const MAX_CONNECTIONS = 32;
21 +const MAX_JOBS = 16;
22 +// Stay below macOS's 104-byte and Linux's 108-byte sockaddr_un limits, including NUL.
23 +const UNIX_SOCKET_PATH_BYTES = 100;
24 +const encodeResponse = Schema.encodeSync(Schema.fromJsonString(Protocol.Response));
25 +class BrokerStartError extends Schema.TaggedError<BrokerStartError>()(
26 + "ManagedTokenBrokerStartError",
27 + {
28 + cause: Schema.Defect(),
29 + },
30 +) {
31 + override get message() {
32 + return "Could not start the private managed token listener.";
33 + }
34 +}
35 +export class CodexManagedTokenBroker extends Context.Service<
36 + CodexManagedTokenBroker,
37 + {
38 + readonly endpoint: Effect.Effect<string, BrokerStartError>;
39 + readonly awaitIdle: Effect.Effect<void>;
40 + }
41 +>()("t3/provider/CodexManagedTokenBroker") {}
42 +
43 +const io = <A>(f: () => Promise<A>) =>
44 + Effect.tryPromise({ try: f, catch: (cause) => new BrokerStartError({ cause }) });
45 +const acquireListener = Effect.gen(function* () {
46 + const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
47 + const environmentId = yield* identity.getEnvironmentId;
48 + const platform = yield* HostProcess.Platform;
49 + const uid = yield* HostProcess.UserId;
50 + const owned = yield* Effect.acquireRelease(
51 + io(async () => {
52 + if (platform === "win32")
53 + return { endpoint: `\\\\.\\pipe\\t3-token-${NodeCrypto.randomUUID()}` };
54 + if (uid === undefined) throw new Error("Missing IPC owner");
55 + const acquireDirectory = async (candidate: string) => {
56 + const parent = await NodeFSP.realpath(candidate);
57 + const stat = await NodeFSP.lstat(parent);
58 + if (
59 + !stat.isDirectory() ||
60 + stat.isSymbolicLink() ||
61 + !(
62 + (stat.uid === uid && (stat.mode & 0o022) === 0) ||
63 + (stat.uid === 0 && ((stat.mode & 0o022) === 0 || (stat.mode & 0o1000) !== 0))
64 + )
65 + )
66 + throw new Error("Untrusted IPC parent");
67 + const directory = await NodeFSP.mkdtemp(NodePath.join(parent, "t3-token-"));
68 + try {
69 + await NodeFSP.chmod(directory, 0o700);
70 + const created = await NodeFSP.lstat(directory);
71 + if (
72 + !created.isDirectory() ||
73 + created.isSymbolicLink() ||
74 + created.uid !== uid ||
75 + (created.mode & 0o777) !== 0o700
76 + )
77 + throw new Error("Unprotected IPC directory");
78 + const endpoint = NodePath.join(directory, "s");
79 + if (Buffer.byteLength(endpoint) > UNIX_SOCKET_PATH_BYTES)
80 + throw new Error("IPC path too long");
81 + return { endpoint, directory, created };
82 + } catch (error) {
83 + await NodeFSP.rmdir(directory);
84 + throw error;
85 + }
86 + };
87 + return acquireDirectory(NodeOS.tmpdir()).catch(() => acquireDirectory("/tmp"));
88 + }),
89 + (owned) =>
90 + Effect.promise(async () => {
91 + if (!("directory" in owned)) return;
92 + // Never recursively remove a replaced directory or another process's files.
93 + const current = await NodeFSP.lstat(owned.directory).catch(() => undefined);
94 + if (
95 + current &&
96 + current.dev === owned.created.dev &&
97 + current.ino === owned.created.ino &&
98 + !current.isSymbolicLink()
99 + )
100 + await NodeFSP.rmdir(owned.directory).catch(() => undefined);
101 + }),
102 + );
103 + const jobs = yield* FiberSet.make<void>();
104 + const runJob =
105 + yield* FiberSet.runtime(jobs)<
106 + Exclude<
107 + Effect.Services<ReturnType<typeof makeCodexChatGptAuth>>,
108 + import("effect/Scope").Scope
109 + >
110 + >();
111 + const connections = yield* FiberSet.make<void>();
112 + const runConnection = yield* FiberSet.runtime(connections)();
113 + const sockets = new Set<NodeNet.Socket>();
114 + let closing = false;
115 + let admitted = 0;
116 + // Keep branded validation here so the helper need not load the contracts graph.
117 + const decode = Schema.decodeUnknownEffect(
118 + Schema.fromJsonString(
119 + Schema.Struct({
120 + ...Protocol.Request.fields,
121 + instanceId: ProviderInstanceId,
122 + environmentId: EnvironmentId,
123 + }),
124 + ),
125 + {
126 + onExcessProperty: "error",
127 + },
128 + );
129 + const server = NodeNet.createServer((socket) => {
130 + socket.on("error", () => {});
131 + if (closing || sockets.size >= MAX_CONNECTIONS) {
132 + socket.destroy();
133 + return;
134 + }
135 + sockets.add(socket);
136 + socket.once("close", () => sockets.delete(socket));
137 + let transferred = false;
138 + runConnection(
139 + Effect.gen(function* () {
140 + // Windows pipes permit read-only peers by default; send no bytes until a complete request.
141 + const request = yield* Protocol.readFrame(
142 + socket,
143 + Protocol.REQUEST_BYTES,
144 + Protocol.SOCKET_IDLE_MS,
145 + ).pipe(Effect.flatMap(decode));
146 + if (closing || admitted >= MAX_JOBS || request.environmentId !== environmentId) return;
147 + admitted++;
148 + transferred = true;
149 + runJob(
150 + Effect.scoped(
151 + Effect.gen(function* () {
152 + const auth = yield* makeCodexChatGptAuth({
153 + instanceId: request.instanceId,
154 + expectedProfileKey: request.profileKey,
155 + });
156 + // Retire abandoned permit waits; access saves a started rotation before honoring interruption.
157 + const credentials = yield* auth.access.pipe(
158 + Effect.timeout(Protocol.COMMAND_TIMEOUT_MS),
159 + );
160 + yield* Protocol.writeFrame(
161 + socket,
162 + encodeResponse({ token: credentials.accessToken }),
163 + Protocol.RESPONSE_BYTES,
164 + );
165 + }),
166 + ).pipe(
167 + Effect.ignoreCause,
168 + Effect.ensuring(
169 + Effect.sync(() => {
170 + admitted--;
171 + socket.destroy();
172 + }),
173 + ),
174 + ),
175 + );
176 + }).pipe(
177 + Effect.ignoreCause,
178 + Effect.ensuring(
179 + Effect.sync(() => {
180 + if (!transferred) socket.destroy();
181 + }),
182 + ),
183 + ),
184 + );
185 + });
186 + server.on("error", () => {});
187 + // Drain accepted rotations before the FiberSet finalizers interrupt their fibers.
188 + yield* Effect.addFinalizer(() =>
189 + Effect.gen(function* () {
190 + closing = true;
191 + for (const socket of sockets) socket.destroy();
192 + yield* Effect.promise(() => new Promise<void>((resolve) => server.close(() => resolve())));
193 + yield* FiberSet.awaitEmpty(connections);
194 + yield* FiberSet.awaitEmpty(jobs);
195 + }),
196 + );
197 + yield* Effect.callback<void, BrokerStartError>((resume) => {
198 + const onError = (cause: Error) => resume(Effect.fail(new BrokerStartError({ cause })));
199 + server.once("error", onError);
200 + try {
201 + server.listen(owned.endpoint, () => resume(Effect.void));
202 + } catch (cause) {
203 + resume(Effect.fail(new BrokerStartError({ cause })));
204 + }
205 + return Effect.sync(() => server.off("error", onError));
206 + });
207 + if (platform !== "win32") yield* io(() => NodeFSP.chmod(owned.endpoint, 0o600));
208 + return { endpoint: owned.endpoint, awaitIdle: FiberSet.awaitEmpty(jobs) };
209 +});
210 +const make = Effect.gen(function* () {
211 + const scope = yield* Scope.fork(yield* Effect.scope);
212 + const acquired = yield* acquireListener.pipe(Scope.provide(scope), Effect.result);
213 + if (acquired._tag === "Failure") {
214 + yield* Scope.close(scope, Exit.fail(acquired.failure));
215 + return CodexManagedTokenBroker.of({
216 + endpoint: Effect.fail(acquired.failure),
217 + awaitIdle: Effect.void,
218 + });
219 + }
220 + return CodexManagedTokenBroker.of({
221 + endpoint: Effect.succeed(acquired.success.endpoint),
222 + awaitIdle: acquired.success.awaitIdle,
223 + });
224 +});
225 +export const layer = Layer.effect(CodexManagedTokenBroker, make);
apps/server/src/provider/CodexManagedTokenProtocol.ts new
+72
@@ -0,0 +1,72 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - Private local IPC framing, shared by server and lean CLI.
2 +import type * as NodeNet from "node:net";
3 +import * as Effect from "effect/Effect";
4 +import * as Schema from "effect/Schema";
5 +
6 +export const Request = Schema.Struct({
7 + version: Schema.Literal(1),
8 + instanceId: Schema.NonEmptyString,
9 + environmentId: Schema.NonEmptyString,
10 + profileKey: Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/u)),
11 +});
12 +export const Response = Schema.Struct({ token: Schema.NonEmptyString });
13 +// Selectors are small; tokens can be larger JWTs. Never truncate either frame
14 +// into something that could be accepted.
15 +export const REQUEST_BYTES = 1024;
16 +export const RESPONSE_BYTES = 64 * 1024;
17 +// Idle/incomplete peers and blocked response consumers must not retain sockets.
18 +export const SOCKET_IDLE_MS = 5_000;
19 +// Existing lock retry (40s), OAuth (20s), plus startup/store headroom (20s).
20 +export const COMMAND_TIMEOUT_MS = 80_000;
21 +class ProtocolError extends Schema.TaggedError<ProtocolError>()("ManagedTokenProtocolError", {}) {
22 + override get message(): string {
23 + return "The managed token frame was invalid or incomplete.";
24 + }
25 +}
26 +
27 +export const readFrame = (socket: NodeNet.Socket, maxBytes: number, timeoutMs: number) =>
28 + Effect.callback<string, ProtocolError>((resume) => {
29 + let bytes = Buffer.alloc(0);
30 + const fail = () => resume(Effect.fail(new ProtocolError()));
31 + const onData = (chunk: Buffer) => {
32 + if (bytes.length + chunk.length > maxBytes) return fail();
33 + bytes = Buffer.concat([bytes, chunk]);
34 + const end = bytes.indexOf(10);
35 + if (end < 0) return;
36 + if (end !== bytes.length - 1) return fail();
37 + resume(Effect.succeed(bytes.subarray(0, end).toString("utf8")));
38 + };
39 + socket.on("data", onData);
40 + socket.once("error", fail);
41 + socket.once("close", fail);
42 + socket.once("end", fail);
43 + return Effect.sync(() => {
44 + socket.off("data", onData);
45 + socket.off("error", fail);
46 + socket.off("close", fail);
47 + socket.off("end", fail);
48 + });
49 + }).pipe(
50 + Effect.timeoutOrElse({ duration: timeoutMs, orElse: () => Effect.fail(new ProtocolError()) }),
51 + );
52 +
53 +export const writeFrame = (socket: NodeNet.Socket, frame: string, maxBytes: number) =>
54 + Effect.callback<void, ProtocolError>((resume) => {
55 + if (socket.destroyed || Buffer.byteLength(frame) + 1 > maxBytes) {
56 + resume(Effect.fail(new ProtocolError()));
57 + return;
58 + }
59 + const fail = () => resume(Effect.fail(new ProtocolError()));
60 + socket.once("error", fail);
61 + socket.once("close", fail);
62 + socket.end(`${frame}\n`, () => resume(Effect.void));
63 + return Effect.sync(() => {
64 + socket.off("error", fail);
65 + socket.off("close", fail);
66 + });
67 + }).pipe(
68 + Effect.timeoutOrElse({
69 + duration: SOCKET_IDLE_MS,
70 + orElse: () => Effect.fail(new ProtocolError()),
71 + }),
72 + );