Skip to content

Commit 442ccfe

Browse files
refactor: replace jose with effect/jose
Effect 4.1 ships JOSE support, so relay JWTs, Codex OIDC verification and web DPoP proofs now use effect/jose. relayJwt verifies against the ambient Clock, decodes claims with a schema, and requires Signature from the environment. jose stays only for the vendored task-cache worker. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 9d7f771 commit 442ccfe

33 files changed

Lines changed: 422 additions & 358 deletions

‎apps/server/package.json‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@
6363
"diff": "8.0.3",
6464
"effect": "catalog:",
6565
"ffi-rs": "1.3.2",
66-
"jose": "catalog:",
6766
"node-pty": "^1.2.0-beta.15",
6867
"playwright-core": "1.60.0",
6968
"proper-lockfile": "4.1.2",

‎apps/server/src/cloud/CloudLink.ts‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import {
4444
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
4545
import * as Context from "effect/Context";
4646
import * as SecureRandom from "effect/crypto/SecureRandom";
47+
import * as Signature from "effect/crypto/Signature";
4748
import * as DateTime from "effect/DateTime";
4849
import * as Duration from "effect/Duration";
4950
import * as Effect from "effect/Effect";
@@ -374,9 +375,6 @@ function normalizePemForSignedPayload(value: string): string {
374375
return value.trim();
375376
}
376377

377-
const decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentHealthProofPayload);
378-
const decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload);
379-
380378
type ManagedTunnelRecoveryProofInput = {
381379
readonly environmentId: RelayManagedEndpointRecoveryProofPayload["environmentId"];
382380
readonly cloudUserId: string;
@@ -532,6 +530,7 @@ const make = Effect.gen(function* () {
532530
const httpServer = yield* HttpServer.HttpServer;
533531
const awarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
534532
const random = yield* SecureRandom.SecureRandom;
533+
const signature = yield* Signature.Signature;
535534
const config = yield* ServerConfig.ServerConfig;
536535
const fileSystem = yield* FileSystem.FileSystem;
537536
const path = yield* Path.Path;
@@ -623,6 +622,7 @@ const make = Effect.gen(function* () {
623622
typ: RELAY_LINK_PROOF_TYP,
624623
payload,
625624
}).pipe(
625+
Effect.provideService(Signature.Signature, signature),
626626
Effect.mapError(
627627
(cause) =>
628628
new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
@@ -960,6 +960,7 @@ const make = Effect.gen(function* () {
960960
typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
961961
payload,
962962
}).pipe(
963+
Effect.provideService(Signature.Signature, signature),
963964
Effect.mapError(
964965
(cause) => new CloudLinkInternalError({ operation: "sign-recovery-proof", cause }),
965966
),
@@ -1453,14 +1454,13 @@ const make = Effect.gen(function* () {
14531454
const linkedCloudUserId = yield* readInstalledCloudUserId;
14541455
const now = yield* DateTime.now;
14551456
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
1456-
const proofOption = yield* verifyRelayJwt({
1457+
const proofOption = yield* verifyRelayJwt(RelayCloudEnvironmentHealthProofPayload, {
14571458
publicKey: cloudMintPublicKey,
14581459
token: request.proof,
14591460
typ: RELAY_HEALTH_REQUEST_TYP,
14601461
issuer: normalizeRelayIssuer(relayIssuer),
14611462
audience: `t3-env:${environmentId}`,
1462-
nowEpochSeconds: nowSeconds,
1463-
}).pipe(Effect.flatMap(decodeCloudHealthProof), Effect.option);
1463+
}).pipe(Effect.provideService(Signature.Signature, signature), Effect.option);
14641464
if (
14651465
Option.isNone(proofOption) ||
14661466
proofOption.value.environmentId !== environmentId ||
@@ -1504,6 +1504,7 @@ const make = Effect.gen(function* () {
15041504
typ: RELAY_HEALTH_RESPONSE_TYP,
15051505
payload: responsePayload,
15061506
}).pipe(
1507+
Effect.provideService(Signature.Signature, signature),
15071508
Effect.mapError(
15081509
(cause) =>
15091510
new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({
@@ -1556,14 +1557,13 @@ const make = Effect.gen(function* () {
15561557
const linkedCloudUserId = yield* readInstalledCloudUserId;
15571558
const now = yield* DateTime.now;
15581559
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
1559-
const proofOption = yield* verifyRelayJwt({
1560+
const proofOption = yield* verifyRelayJwt(RelayCloudMintCredentialProofPayload, {
15601561
publicKey: cloudMintPublicKey,
15611562
token: request.proof,
15621563
typ: RELAY_MINT_REQUEST_TYP,
15631564
issuer: normalizeRelayIssuer(relayIssuer),
15641565
audience: `t3-env:${environmentId}`,
1565-
nowEpochSeconds: nowSeconds,
1566-
}).pipe(Effect.flatMap(decodeCloudMintProof), Effect.option);
1566+
}).pipe(Effect.provideService(Signature.Signature, signature), Effect.option);
15671567
if (
15681568
Option.isNone(proofOption) ||
15691569
proofOption.value.environmentId !== environmentId ||
@@ -1612,6 +1612,7 @@ const make = Effect.gen(function* () {
16121612
typ: RELAY_MINT_RESPONSE_TYP,
16131613
payload: responsePayload,
16141614
}).pipe(
1615+
Effect.provideService(Signature.Signature, signature),
16151616
Effect.mapError(
16161617
(cause) =>
16171618
new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({

‎apps/server/src/cloud/http.test.ts‎

Lines changed: 41 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
type RelayLinkProofRequest,
1414
} from "@t3tools/contracts/relay";
1515
import * as Effect from "effect/Effect";
16+
import * as TestClock from "effect/testing/TestClock";
1617
import * as Layer from "effect/Layer";
1718
import * as Schema from "effect/Schema";
1819
import { HttpClient, HttpServer } from "effect/http";
@@ -22,8 +23,7 @@ import * as HttpRouter from "effect/http/HttpRouter";
2223
import * as HttpApi from "effect/http-api/HttpApi";
2324
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
2425
import * as NetAddress from "effect/net/NetAddress";
25-
import { decodeJwt, importSPKI, jwtVerify } from "jose";
26-
import { RELAY_LINK_PROOF_TYP } from "@t3tools/shared/relayJwt";
26+
import { decodeRelayJwt, RELAY_LINK_PROOF_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";
2727

2828
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
2929
import * as AuthHttp from "../auth/http.ts";
@@ -52,7 +52,7 @@ const proofRequest: RelayLinkProofRequest = {
5252
},
5353
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
5454
};
55-
const decodeLinkProofPayload = Schema.decodeUnknownSync(RelayEnvironmentLinkProofPayload);
55+
const decodeLinkProofPayload = Schema.decodeUnknownEffect(RelayEnvironmentLinkProofPayload);
5656

5757
class LinkProofTestApi extends HttpApi.make("environment").add(
5858
EnvironmentHttpApi.groups.auth,
@@ -112,7 +112,7 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(
112112
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
113113
);
114114

115-
const withLinkProofClient = async (
115+
const withLinkProofClient = async <A = void>(
116116
body: (client: {
117117
post: (
118118
path: string,
@@ -121,8 +121,8 @@ const withLinkProofClient = async (
121121
origin?: string,
122122
) => Promise<Response>;
123123
exchange: (credential: string, scope?: string) => Promise<string>;
124-
}) => Promise<void>,
125-
) => {
124+
}) => Promise<A>,
125+
): Promise<A> => {
126126
const { handler, dispose } = HttpRouter.toWebHandler(layerLinkProofRoutes, {
127127
disableLogger: true,
128128
});
@@ -157,39 +157,50 @@ const withLinkProofClient = async (
157157
return payload.access_token;
158158
};
159159
try {
160-
await body({ post, exchange });
160+
return await body({ post, exchange });
161161
} finally {
162162
await dispose();
163163
}
164164
};
165165

166166
describe("link proof over a non-loopback desktop transport", () => {
167-
it("signs a loopback tunnel origin after desktop bootstrap token exchange over a non-loopback host", () =>
168-
withLinkProofClient(async ({ post, exchange }) => {
169-
const token = await exchange(DESKTOP_BOOTSTRAP_TOKEN);
170-
const response = await post("/api/connect/link-proof", proofRequest, {
171-
authorization: `Bearer ${token}`,
172-
});
173-
expect(response.status).toBe(200);
174-
const proof = (await response.json()) as string;
175-
const payload = decodeLinkProofPayload(decodeJwt(proof));
176-
const verified = await jwtVerify(
177-
proof,
178-
await importSPKI(payload.environmentPublicKey, "EdDSA"),
179-
{
180-
algorithms: ["EdDSA"],
167+
it.effect(
168+
"signs a loopback tunnel origin after desktop bootstrap token exchange over a non-loopback host",
169+
() =>
170+
Effect.gen(function* () {
171+
const response = yield* Effect.promise(() =>
172+
withLinkProofClient(async ({ post, exchange }) => {
173+
const token = await exchange(DESKTOP_BOOTSTRAP_TOKEN);
174+
const response = await post("/api/connect/link-proof", proofRequest, {
175+
authorization: `Bearer ${token}`,
176+
});
177+
return {
178+
status: response.status,
179+
cacheControl: response.headers.get("cache-control"),
180+
proof: (await response.json()) as string,
181+
};
182+
}),
183+
);
184+
expect(response.status).toBe(200);
185+
expect(response.cacheControl).toBe("no-store");
186+
const unverified = yield* decodeRelayJwt(response.proof).pipe(
187+
Effect.flatMap(decodeLinkProofPayload),
188+
);
189+
yield* TestClock.setTime(unverified.iat * 1_000);
190+
const verified = yield* verifyRelayJwt(RelayEnvironmentLinkProofPayload, {
191+
publicKey: unverified.environmentPublicKey,
192+
token: response.proof,
181193
typ: RELAY_LINK_PROOF_TYP,
182194
issuer: "t3-env:wsl-environment",
183195
audience: proofRequest.relayIssuer,
184-
},
185-
);
186-
expect(verified.payload).toMatchObject({
187-
origin: proofRequest.origin,
188-
endpoint: proofRequest.endpoint,
189-
challenge: proofRequest.challenge,
190-
});
191-
expect(response.headers.get("cache-control")).toBe("no-store");
192-
}));
196+
});
197+
expect(verified).toMatchObject({
198+
origin: proofRequest.origin,
199+
endpoint: proofRequest.endpoint,
200+
challenge: proofRequest.challenge,
201+
});
202+
}).pipe(Effect.provide(NodeCrypto.layerSignature)),
203+
);
193204

194205
it("does not pass desktop trust to a paired client or accept client-supplied provenance", () =>
195206
withLinkProofClient(async ({ post, exchange }) => {

‎apps/server/src/provider/CodexChatGptAuth.test.ts‎

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import * as Fiber from "effect/Fiber";
1818
import * as Deferred from "effect/Deferred";
1919
import { subscribeChatGptHandoff } from "./CodexChatGptHandoff.ts";
2020
import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
21-
import { exportJWK, generateKeyPair, SignJWT } from "jose";
2221
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
2322
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
2423
import * as ProviderCredentialStore from "./ProviderCredentialStore.ts";
@@ -44,9 +43,20 @@ const makeHarnessFor = Effect.fnUntraced(function* (
4443
const environment = ServerEnvironment.ServerEnvironmentIdentity.of({
4544
getEnvironmentId: Effect.succeed(environmentId),
4645
});
47-
const keys = yield* Effect.promise(() => generateKeyPair("RS256"));
48-
const jwk = yield* Effect.promise(() => exportJWK(keys.publicKey));
49-
const untrustedKeys = yield* Effect.promise(() => generateKeyPair("RS256"));
46+
const keys = NodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
47+
const untrustedKeys = NodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
48+
const publicJwk = {
49+
...keys.publicKey.export({ format: "jwk" }),
50+
kid: "test",
51+
alg: "RS256",
52+
use: "sig",
53+
};
54+
const signIdToken = (claims: Record<string, unknown>, privateKey: NodeCrypto.KeyObject) => {
55+
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
56+
const signingInput = `${encode({ alg: "RS256", kid: "test" })}.${encode(claims)}`;
57+
const signature = NodeCrypto.sign("sha256", Buffer.from(signingInput), privateKey);
58+
return `${signingInput}.${signature.toString("base64url")}`;
59+
};
5060
const secrets = ServerSecretStore.ServerSecretStore.of({
5161
get: (name) => Effect.sync(() => Option.fromUndefinedOr(bytes.get(name))),
5262
set: (name, value) =>
@@ -99,9 +109,7 @@ const makeHarnessFor = Effect.fnUntraced(function* (
99109
return;
100110
}
101111
if (request.url === "/jwks") {
102-
response.end(
103-
JSON.stringify({ keys: [{ ...jwk, kid: "test", alg: "RS256", use: "sig" }] }),
104-
);
112+
response.end(JSON.stringify({ keys: [publicJwk] }));
105113
return;
106114
}
107115
if (request.url === "/revoke") {
@@ -167,21 +175,20 @@ const makeHarnessFor = Effect.fnUntraced(function* (
167175
.digest("base64url"),
168176
authorize.searchParams.get("code_challenge"),
169177
);
170-
const token = await new SignJWT({
171-
nonce: invalidNonce ? "incorrect" : authorize.searchParams.get("nonce"),
172-
email,
173-
})
174-
.setProtectedHeader({ alg: "RS256", kid: "test" })
175-
.setIssuer(identityFailure === "issuer" ? "https://untrusted-issuer.test" : origin)
176-
.setAudience(
177-
identityFailure === "audience"
178-
? "oaiapp_untrusted_audience"
179-
: body.get("client_id")!,
180-
)
181-
.setSubject(subject)
182-
.setIssuedAt()
183-
.setExpirationTime("1h")
184-
.sign(identityFailure === "signature" ? untrustedKeys.privateKey : keys.privateKey);
178+
const token = signIdToken(
179+
{
180+
nonce: invalidNonce ? "incorrect" : authorize.searchParams.get("nonce"),
181+
email,
182+
iss: identityFailure === "issuer" ? "https://untrusted-issuer.test" : origin,
183+
aud:
184+
identityFailure === "audience"
185+
? "oaiapp_untrusted_audience"
186+
: body.get("client_id")!,
187+
sub: subject,
188+
exp: 4_102_444_800,
189+
},
190+
identityFailure === "signature" ? untrustedKeys.privateKey : keys.privateKey,
191+
);
185192
response.end(
186193
JSON.stringify({
187194
access_token: "initial-access",

0 commit comments

Comments
 (0)