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, 04:30 UTC
refactor: replace jose with effect/jose (#30474)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 4, 2026 at 10:35 UTC
14e8f393faeb7e74f576525d63b540d61e4331fc
33 files changed
+557
-439
apps/server/package.json
-1
@@ -63,7 +63,6 @@
63
"diff": "8.0.3",
64
"effect": "catalog:",
65
"ffi-rs": "1.3.2",
66
- "jose": "catalog:",
66
"node-pty": "^1.2.0-beta.15",
67
"playwright-core": "1.60.0",
68
"proper-lockfile": "4.1.2",
apps/server/src/cloud/CloudLink.ts
+10
-9
@@ -44,6 +44,7 @@ import {
44
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
45
import * as Context from "effect/Context";
46
import * as SecureRandom from "effect/crypto/SecureRandom";
47
+import * as Signature from "effect/crypto/Signature";
48
import * as DateTime from "effect/DateTime";
49
import * as Duration from "effect/Duration";
50
import * as Effect from "effect/Effect";
@@ -374,9 +375,6 @@ function normalizePemForSignedPayload(value: string): string {
375
return value.trim();
376
}
377
377
-const decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentHealthProofPayload);
378
-const decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload);
379
-
378
type ManagedTunnelRecoveryProofInput = {
379
readonly environmentId: RelayManagedEndpointRecoveryProofPayload["environmentId"];
380
readonly cloudUserId: string;
@@ -532,6 +530,7 @@ const make = Effect.gen(function* () {
530
const httpServer = yield* HttpServer.HttpServer;
531
const awarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
532
const random = yield* SecureRandom.SecureRandom;
533
+ const signature = yield* Signature.Signature;
534
const config = yield* ServerConfig.ServerConfig;
535
const fileSystem = yield* FileSystem.FileSystem;
536
const path = yield* Path.Path;
@@ -623,6 +622,7 @@ const make = Effect.gen(function* () {
622
typ: RELAY_LINK_PROOF_TYP,
623
payload,
624
}).pipe(
625
+ Effect.provideService(Signature.Signature, signature),
626
Effect.mapError(
627
(cause) =>
628
new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
@@ -960,6 +960,7 @@ const make = Effect.gen(function* () {
960
typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
961
payload,
962
}).pipe(
963
+ Effect.provideService(Signature.Signature, signature),
964
Effect.mapError(
965
(cause) => new CloudLinkInternalError({ operation: "sign-recovery-proof", cause }),
966
),
@@ -1453,14 +1454,13 @@ const make = Effect.gen(function* () {
1454
const linkedCloudUserId = yield* readInstalledCloudUserId;
1455
const now = yield* DateTime.now;
1456
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
1456
- const proofOption = yield* verifyRelayJwt({
1457
+ const proofOption = yield* verifyRelayJwt(RelayCloudEnvironmentHealthProofPayload, {
1458
publicKey: cloudMintPublicKey,
1459
token: request.proof,
1460
typ: RELAY_HEALTH_REQUEST_TYP,
1461
issuer: normalizeRelayIssuer(relayIssuer),
1462
audience: `t3-env:${environmentId}`,
1462
- nowEpochSeconds: nowSeconds,
1463
- }).pipe(Effect.flatMap(decodeCloudHealthProof), Effect.option);
1463
+ }).pipe(Effect.provideService(Signature.Signature, signature), Effect.option);
1464
if (
1465
Option.isNone(proofOption) ||
1466
proofOption.value.environmentId !== environmentId ||
@@ -1504,6 +1504,7 @@ const make = Effect.gen(function* () {
1504
typ: RELAY_HEALTH_RESPONSE_TYP,
1505
payload: responsePayload,
1506
}).pipe(
1507
+ Effect.provideService(Signature.Signature, signature),
1508
Effect.mapError(
1509
(cause) =>
1510
new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({
@@ -1556,14 +1557,13 @@ const make = Effect.gen(function* () {
1557
const linkedCloudUserId = yield* readInstalledCloudUserId;
1558
const now = yield* DateTime.now;
1559
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
1559
- const proofOption = yield* verifyRelayJwt({
1560
+ const proofOption = yield* verifyRelayJwt(RelayCloudMintCredentialProofPayload, {
1561
publicKey: cloudMintPublicKey,
1562
token: request.proof,
1563
typ: RELAY_MINT_REQUEST_TYP,
1564
issuer: normalizeRelayIssuer(relayIssuer),
1565
audience: `t3-env:${environmentId}`,
1565
- nowEpochSeconds: nowSeconds,
1566
- }).pipe(Effect.flatMap(decodeCloudMintProof), Effect.option);
1566
+ }).pipe(Effect.provideService(Signature.Signature, signature), Effect.option);
1567
if (
1568
Option.isNone(proofOption) ||
1569
proofOption.value.environmentId !== environmentId ||
@@ -1612,6 +1612,7 @@ const make = Effect.gen(function* () {
1612
typ: RELAY_MINT_RESPONSE_TYP,
1613
payload: responsePayload,
1614
}).pipe(
1615
+ Effect.provideService(Signature.Signature, signature),
1616
Effect.mapError(
1617
(cause) =>
1618
new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
apps/server/src/cloud/http.test.ts
+122
-111
@@ -13,6 +13,7 @@ import {
13
type RelayLinkProofRequest,
14
} from "@t3tools/contracts/relay";
15
import * as Effect from "effect/Effect";
16
+import * as TestClock from "effect/testing/TestClock";
17
import * as Layer from "effect/Layer";
18
import * as Schema from "effect/Schema";
19
import { HttpClient, HttpServer } from "effect/http";
@@ -22,8 +23,7 @@ import * as HttpRouter from "effect/http/HttpRouter";
23
import * as HttpApi from "effect/http-api/HttpApi";
24
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
25
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";
27
28
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
29
import * as AuthHttp from "../auth/http.ts";
@@ -52,7 +52,7 @@ const proofRequest: RelayLinkProofRequest = {
52
},
53
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
54
};
55
-const decodeLinkProofPayload = Schema.decodeUnknownSync(RelayEnvironmentLinkProofPayload);
55
+const decodeLinkProofPayload = Schema.decodeUnknownEffect(RelayEnvironmentLinkProofPayload);
56
57
class LinkProofTestApi extends HttpApi.make("environment").add(
58
EnvironmentHttpApi.groups.auth,
@@ -112,119 +112,123 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(
112
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
113
);
114
115
-const withLinkProofClient = async (
116
- body: (client: {
117
- post: (
118
- path: string,
119
- payload: unknown,
120
- headers?: Record<string, string>,
121
- origin?: string,
122
- ) => Promise<Response>;
123
- exchange: (credential: string, scope?: string) => Promise<string>;
124
- }) => Promise<void>,
125
-) => {
126
- const { handler, dispose } = HttpRouter.toWebHandler(layerLinkProofRoutes, {
127
- disableLogger: true,
128
- });
115
+const responseJson = (response: Response) => Effect.promise(() => response.json());
116
+
117
+// Scoped: the web handler and its layer are disposed when the test's scope closes.
118
+const linkProofClient = Effect.gen(function* () {
119
+ const { handler } = yield* Effect.acquireRelease(
120
+ Effect.sync(() => HttpRouter.toWebHandler(layerLinkProofRoutes, { disableLogger: true })),
121
+ (web) => Effect.promise(() => web.dispose()),
122
+ );
123
const post = (
124
path: string,
125
payload: unknown,
126
headers?: Record<string, string>,
127
origin = NON_LOOPBACK_ORIGIN,
128
) =>
135
- handler(
136
- new Request(`${origin}${path}`, {
137
- method: "POST",
138
- headers: { "content-type": "application/json", ...headers },
139
- body: JSON.stringify(payload),
140
- }),
129
+ Effect.promise(() =>
130
+ handler(
131
+ new Request(`${origin}${path}`, {
132
+ method: "POST",
133
+ headers: { "content-type": "application/json", ...headers },
134
+ body: JSON.stringify(payload),
135
+ }),
136
+ ),
137
);
142
- const exchange = async (credential: string, scope?: string) => {
143
- const response = await handler(
144
- new Request(`${NON_LOOPBACK_ORIGIN}/oauth/token`, {
145
- method: "POST",
146
- body: new URLSearchParams({
147
- grant_type: AuthTokenExchangeGrantType,
148
- subject_token: credential,
149
- subject_token_type: AuthEnvironmentBootstrapTokenType,
150
- requested_token_type: AuthAccessTokenType,
151
- ...(scope ? { scope } : {}),
138
+ const exchange = Effect.fnUntraced(function* (credential: string, scope?: string) {
139
+ const response = yield* Effect.promise(() =>
140
+ handler(
141
+ new Request(`${NON_LOOPBACK_ORIGIN}/oauth/token`, {
142
+ method: "POST",
143
+ body: new URLSearchParams({
144
+ grant_type: AuthTokenExchangeGrantType,
145
+ subject_token: credential,
146
+ subject_token_type: AuthEnvironmentBootstrapTokenType,
147
+ requested_token_type: AuthAccessTokenType,
148
+ ...(scope ? { scope } : {}),
149
+ }),
150
}),
153
- }),
151
+ ),
152
);
153
expect(response.status).toBe(200);
156
- const payload = (await response.json()) as { access_token: string };
154
+ const payload = (yield* responseJson(response)) as { access_token: string };
155
return payload.access_token;
158
- };
159
- try {
160
- await body({ post, exchange });
161
- } finally {
162
- await dispose();
163
- }
164
-};
156
+ });
157
+ return { post, exchange };
158
+});
159
160
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"],
161
+ it.effect(
162
+ "signs a loopback tunnel origin after desktop bootstrap token exchange over a non-loopback host",
163
+ () =>
164
+ Effect.gen(function* () {
165
+ const { post, exchange } = yield* linkProofClient;
166
+ const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
167
+ const response = yield* post("/api/connect/link-proof", proofRequest, {
168
+ authorization: `Bearer ${token}`,
169
+ });
170
+ expect(response.status).toBe(200);
171
+ expect(response.headers.get("cache-control")).toBe("no-store");
172
+ const proof = (yield* responseJson(response)) as string;
173
+ const unverified = yield* decodeRelayJwt(proof).pipe(
174
+ Effect.flatMap(decodeLinkProofPayload),
175
+ );
176
+ yield* TestClock.setTime(unverified.iat * 1_000);
177
+ const verified = yield* verifyRelayJwt(RelayEnvironmentLinkProofPayload, {
178
+ publicKey: unverified.environmentPublicKey,
179
+ token: proof,
180
typ: RELAY_LINK_PROOF_TYP,
181
issuer: "t3-env:wsl-environment",
182
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
- }));
183
+ });
184
+ expect(verified).toMatchObject({
185
+ origin: proofRequest.origin,
186
+ endpoint: proofRequest.endpoint,
187
+ challenge: proofRequest.challenge,
188
+ });
189
+ }).pipe(Effect.provide(NodeCrypto.layerSignature)),
190
+ );
191
194
- it("does not pass desktop trust to a paired client or accept client-supplied provenance", () =>
195
- withLinkProofClient(async ({ post, exchange }) => {
196
- const desktop = await exchange(DESKTOP_BOOTSTRAP_TOKEN);
197
- const paired = await post(
198
- "/api/auth/pairing-token",
199
- {
200
- scopes: ["relay:write"],
201
- label: "desktop-bootstrap",
192
+ it.effect(
193
+ "does not pass desktop trust to a paired client or accept client-supplied provenance",
194
+ () =>
195
+ Effect.gen(function* () {
196
+ const { post, exchange } = yield* linkProofClient;
197
+ const desktop = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
198
+ const paired = yield* post(
199
+ "/api/auth/pairing-token",
200
+ {
201
+ scopes: ["relay:write"],
202
+ label: "desktop-bootstrap",
203
+ subject: "desktop-bootstrap",
204
+ },
205
+ { authorization: `Bearer ${desktop}` },
206
+ );
207
+ expect(paired.status).toBe(200);
208
+ const { credential } = (yield* responseJson(paired)) as { credential: string };
209
+ const token = yield* exchange(credential);
210
+ const headers = { authorization: `Bearer ${token}`, "x-desktop-bootstrap": "true" };
211
+ const payload = {
212
+ ...proofRequest,
213
+ allowNonLoopbackRequestHost: true,
214
subject: "desktop-bootstrap",
203
- },
204
- { authorization: `Bearer ${desktop}` },
205
- );
206
- expect(paired.status).toBe(200);
207
- const { credential } = (await paired.json()) as { credential: string };
208
- const token = await exchange(credential);
209
- const headers = { authorization: `Bearer ${token}`, "x-desktop-bootstrap": "true" };
210
- const payload = {
211
- ...proofRequest,
212
- allowNonLoopbackRequestHost: true,
213
- subject: "desktop-bootstrap",
214
- };
215
- const rejected = await post("/api/connect/link-proof", payload, headers);
216
- expect(rejected.status).toBe(400);
217
- expect(await rejected.json()).toMatchObject({ message: "Invalid managed endpoint origin." });
218
- const loopback = await post(
219
- "/api/connect/link-proof",
220
- proofRequest,
221
- headers,
222
- LOOPBACK_ORIGIN,
223
- );
224
- expect(loopback.status).toBe(200);
225
- }));
215
+ };
216
+ const rejected = yield* post("/api/connect/link-proof", payload, headers);
217
+ expect(rejected.status).toBe(400);
218
+ expect(yield* responseJson(rejected)).toMatchObject({
219
+ message: "Invalid managed endpoint origin.",
220
+ });
221
+ const loopback = yield* post(
222
+ "/api/connect/link-proof",
223
+ proofRequest,
224
+ headers,
225
+ LOOPBACK_ORIGIN,
226
+ );
227
+ expect(loopback.status).toBe(200);
228
+ }),
229
+ );
230
227
- it.each([
231
+ it.effect.each([
232
{
233
name: "non-loopback tunnel origin",
234
origin: { localHttpHost: "172.24.162.233", localHttpPort: 3773 },
@@ -246,34 +250,41 @@ describe("link proof over a non-loopback desktop transport", () => {
250
headers: { "x-forwarded-proto": "http" },
251
},
252
])("rejects $name even for desktop bootstrap", ({ origin, headers }) =>
249
- withLinkProofClient(async ({ post, exchange }) => {
250
- const token = await exchange(DESKTOP_BOOTSTRAP_TOKEN);
251
- const response = await post(
253
+ Effect.gen(function* () {
254
+ const { post, exchange } = yield* linkProofClient;
255
+ const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN);
256
+ const response = yield* post(
257
"/api/connect/link-proof",
258
{ ...proofRequest, origin },
259
{ ...headers, authorization: `Bearer ${token}` },
260
);
261
expect(response.status).toBe(400);
257
- expect(await response.json()).toMatchObject({ message: "Invalid managed endpoint origin." });
262
+ expect(yield* responseJson(response)).toMatchObject({
263
+ message: "Invalid managed endpoint origin.",
264
+ });
265
}),
266
);
267
261
- it("requires relay-write scope even for desktop bootstrap", () =>
262
- withLinkProofClient(async ({ post, exchange }) => {
263
- const token = await exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:read");
264
- const response = await post("/api/connect/link-proof", proofRequest, {
268
+ it.effect("requires relay-write scope even for desktop bootstrap", () =>
269
+ Effect.gen(function* () {
270
+ const { post, exchange } = yield* linkProofClient;
271
+ const token = yield* exchange(DESKTOP_BOOTSTRAP_TOKEN, "relay:read");
272
+ const response = yield* post("/api/connect/link-proof", proofRequest, {
273
authorization: `Bearer ${token}`,
274
});
275
expect(response.status).toBe(403);
268
- expect(await response.json()).toMatchObject({
276
+ expect(yield* responseJson(response)).toMatchObject({
277
code: "insufficient_scope",
278
requiredScope: "relay:write",
279
});
272
- }));
280
+ }),
281
+ );
282
274
- it("rejects unauthenticated requests", () =>
275
- withLinkProofClient(async ({ post }) => {
276
- const response = await post("/api/connect/link-proof", proofRequest);
283
+ it.effect("rejects unauthenticated requests", () =>
284
+ Effect.gen(function* () {
285
+ const { post } = yield* linkProofClient;
286
+ const response = yield* post("/api/connect/link-proof", proofRequest);
287
expect(response.status).toBe(401);
278
- }));
288
+ }),
289
+ );
290
});
apps/server/src/provider/CodexChatGptAuth.test.ts
+49
-22
@@ -14,11 +14,11 @@ import * as Effect from "effect/Effect";
14
import * as Layer from "effect/Layer";
15
import * as Option from "effect/Option";
16
import * as Stream from "effect/Stream";
17
+import * as TestClock from "effect/testing/TestClock";
18
import * as Fiber from "effect/Fiber";
19
import * as Deferred from "effect/Deferred";
20
import { subscribeChatGptHandoff } from "./CodexChatGptHandoff.ts";
21
import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
21
-import { exportJWK, generateKeyPair, SignJWT } from "jose";
22
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
23
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
24
import * as ProviderCredentialStore from "./ProviderCredentialStore.ts";
@@ -44,9 +44,23 @@ const makeHarnessFor = Effect.fnUntraced(function* (
44
const environment = ServerEnvironment.ServerEnvironmentIdentity.of({
45
getEnvironmentId: Effect.succeed(environmentId),
46
});
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"));
47
+ const signingKeyFor = (kid: string) => {
48
+ const pair = NodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
49
+ return {
50
+ kid,
51
+ privateKey: pair.privateKey,
52
+ publicJwk: { ...pair.publicKey.export({ format: "jwk" }), kid, alg: "RS256", use: "sig" },
53
+ };
54
+ };
55
+ let signingKey = signingKeyFor("test");
56
+ let jwksRequests = 0;
57
+ const untrustedKeys = NodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
58
+ const signIdToken = (claims: Record<string, unknown>, privateKey: NodeCrypto.KeyObject) => {
59
+ const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
60
+ const signingInput = `${encode({ alg: "RS256", kid: signingKey.kid })}.${encode(claims)}`;
61
+ const signature = NodeCrypto.sign("sha256", Buffer.from(signingInput), privateKey);
62
+ return `${signingInput}.${signature.toString("base64url")}`;
63
+ };
64
const secrets = ServerSecretStore.ServerSecretStore.of({
65
get: (name) => Effect.sync(() => Option.fromUndefinedOr(bytes.get(name))),
66
set: (name, value) =>
@@ -99,9 +113,8 @@ const makeHarnessFor = Effect.fnUntraced(function* (
113
return;
114
}
115
if (request.url === "/jwks") {
102
- response.end(
103
- JSON.stringify({ keys: [{ ...jwk, kid: "test", alg: "RS256", use: "sig" }] }),
104
- );
116
+ jwksRequests += 1;
117
+ response.end(JSON.stringify({ keys: [signingKey.publicJwk] }));
118
return;
119
}
120
if (request.url === "/revoke") {
@@ -167,21 +180,20 @@ const makeHarnessFor = Effect.fnUntraced(function* (
180
.digest("base64url"),
181
authorize.searchParams.get("code_challenge"),
182
);
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);
183
+ const token = signIdToken(
184
+ {
185
+ nonce: invalidNonce ? "incorrect" : authorize.searchParams.get("nonce"),
186
+ email,
187
+ iss: identityFailure === "issuer" ? "https://untrusted-issuer.test" : origin,
188
+ aud:
189
+ identityFailure === "audience"
190
+ ? "oaiapp_untrusted_audience"
191
+ : body.get("client_id")!,
192
+ sub: subject,
193
+ exp: 4_102_444_800,
194
+ },
195
+ identityFailure === "signature" ? untrustedKeys.privateKey : signingKey.privateKey,
196
+ );
197
response.end(
198
JSON.stringify({
199
access_token: "initial-access",
@@ -283,6 +295,10 @@ const makeHarnessFor = Effect.fnUntraced(function* (
295
});
296
return {
297
auth,
298
+ jwksRequests: () => jwksRequests,
299
+ rotateSigningKey: () => {
300
+ signingKey = signingKeyFor("rotated");
301
+ },
302
analyticsEvents,
303
secrets,
304
environmentId,
@@ -649,6 +665,17 @@ it.effect(
665
h.exchanges[2]!.get("redirect_uri"),
666
reconnect.searchParams.get("redirect_uri"),
667
);
668
+ assert.strictEqual(h.jwksRequests(), 1);
669
+ h.rotateSigningKey();
670
+ yield* h.auth.controller.logout(Effect.void);
671
+ yield* h.signIn;
672
+ yield* h.phase("succeeded");
673
+ assert.strictEqual(h.jwksRequests(), 2);
674
+ yield* TestClock.adjust("10 minutes");
675
+ yield* h.auth.controller.logout(Effect.void);
676
+ yield* h.signIn;
677
+ yield* h.phase("succeeded");
678
+ assert.strictEqual(h.jwksRequests(), 3);
679
}),
680
),
681
);
apps/server/src/provider/CodexChatGptAuth.ts
+82
-31
@@ -1,7 +1,6 @@
1
// @effect-diagnostics nodeBuiltinImport:off - OAuth loopback listener and PKCE use Node APIs.
2
import * as NodeCrypto from "node:crypto";
3
import * as NodeHttp from "node:http";
4
-import { createRemoteJWKSet, jwtVerify } from "jose";
4
import {
5
ProviderSetupError,
6
type ChatGptReconnectProfile,
@@ -16,6 +15,10 @@ import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
15
import { openAiUserId } from "../telemetry/Identify.ts";
16
import * as Digest from "effect/crypto/Digest";
17
import * as SecureRandom from "effect/crypto/SecureRandom";
18
+import * as Signature from "effect/crypto/Signature";
19
+import * as JoseError from "effect/jose/JoseError";
20
+import * as Jwks from "effect/jose/Jwks";
21
+import * as Jwt from "effect/jose/Jwt";
22
import * as Hex from "effect/encoding/Hex";
23
import * as Exit from "effect/Exit";
24
import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts";
@@ -95,6 +98,13 @@ const Discovery = Schema.Struct({
98
revocation_endpoint: Schema.optionalKey(Schema.String),
99
});
100
const OAuthError = Schema.Struct({ error: Schema.String });
101
+const JWKS_CACHE_TTL_MS = 10 * 60 * 1000;
102
+const IdTokenClaims = Schema.Struct({
103
+ sub: Schema.String,
104
+ nonce: Schema.optionalKey(Schema.Unknown),
105
+ email: Schema.optionalKey(Schema.Unknown),
106
+});
107
+const decodeKeySet = Schema.decodeUnknownEffect(Jwks.KeySet);
108
const decodeSessions = Schema.decodeUnknownEffect(
109
Schema.fromJsonString(Schema.Union([Sessions, Record])),
110
);
@@ -165,6 +175,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
175
const secrets = yield* ServerSecretStore.ServerSecretStore;
176
const random = yield* SecureRandom.SecureRandom;
177
const digest = yield* Digest.Digest;
178
+ const signature = yield* Signature.Signature;
179
const environmentLocks = sessionLocks.get(secrets) ?? new Map<string, Semaphore.Semaphore>();
180
sessionLocks.set(secrets, environmentLocks);
181
const lock = environmentLocks.get(store.binding.key) ?? (yield* Semaphore.make(1));
@@ -177,7 +188,6 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
188
const failure = (operation: string, detail: string) =>
189
new ProviderSetupError({ instanceId: options.instanceId, operation, detail });
190
let metadata: typeof Discovery.Type | undefined;
180
- let jwks: ReturnType<typeof createRemoteJWKSet> | undefined;
191
const discover = Effect.gen(function* () {
192
if (metadata) return metadata;
193
const result = yield* http.get(options.discoveryUrl ?? DISCOVERY).pipe(
@@ -203,9 +213,58 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
213
)
214
return yield* failure("discover", "ChatGPT sign-in configuration could not be verified.");
215
metadata = result;
206
- jwks = createRemoteJWKSet(new URL(result.jwks_uri));
216
return result;
217
});
218
+ // Reused for 10 minutes like jose's remote set; an unknown kid refetches once for rotation.
219
+ let keySet: { readonly keys: Jwks.KeySet; readonly expiresAt: number } | undefined;
220
+ const fetchKeySet = Effect.fn("CodexChatGptAuth.fetchKeySet")(function* (jwksUri: string) {
221
+ return yield* http.get(jwksUri).pipe(
222
+ Effect.filterOrFail(
223
+ (response) => response.status === 200,
224
+ () => failure("verify", "Could not reach ChatGPT sign-in. Try again."),
225
+ ),
226
+ Effect.flatMap((response) => response.json),
227
+ Effect.flatMap(decodeKeySet),
228
+ // Bounds the body read too, as jose's remote set did; a stalled endpoint fails the sign-in.
229
+ Effect.timeoutOrElse({
230
+ duration: "5 seconds",
231
+ orElse: () => Effect.fail(failure("verify", "Could not reach ChatGPT sign-in. Try again.")),
232
+ }),
233
+ Effect.tap((fetched) =>
234
+ Effect.map(Clock.currentTimeMillis, (now) => {
235
+ keySet = { keys: fetched, expiresAt: now + JWKS_CACHE_TTL_MS };
236
+ }),
237
+ ),
238
+ );
239
+ });
240
+ const verifyIdToken = Effect.fn("CodexChatGptAuth.verifyIdToken")(
241
+ function* (token: string, audience: string) {
242
+ const endpoints = yield* discover;
243
+ const verifyWith = (keys: Jwks.KeySet) =>
244
+ Jwks.makeLocal(keys).pipe(
245
+ Effect.flatMap((jwks) =>
246
+ Jwt.verifyWithKeySet(IdTokenClaims, token, {
247
+ issuer: endpoints.issuer,
248
+ audience,
249
+ algorithms: ["RS256", "ES256"],
250
+ clockTolerance: "5 seconds",
251
+ requiredClaims: ["exp"],
252
+ }).pipe(Effect.provideService(Jwks.Jwks, jwks)),
253
+ ),
254
+ );
255
+ const fresh = fetchKeySet(endpoints.jwks_uri).pipe(Effect.flatMap(verifyWith));
256
+ const cached = keySet;
257
+ return yield* cached === undefined || cached.expiresAt <= (yield* Clock.currentTimeMillis)
258
+ ? fresh
259
+ : verifyWith(cached.keys).pipe(
260
+ Effect.catchIf(
261
+ (error) => JoseError.isJoseError(error) && error.reason._tag === "KeyNotFound",
262
+ () => fresh,
263
+ ),
264
+ );
265
+ },
266
+ Effect.provideService(Signature.Signature, signature),
267
+ );
268
const readSessions = store.get.pipe(
269
Effect.mapError(() => failure("read", "Could not read the saved ChatGPT connection.")),
270
Effect.flatMap((bytes) =>
@@ -622,22 +681,19 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
681
"verify",
682
"ChatGPT did not return a verified identity. Sign in again.",
683
);
625
- const identity = yield* Effect.tryPromise({
626
- try: async () => {
627
- const { payload } = await jwtVerify(tokens.id_token!, jwks!, {
628
- issuer: endpoints.issuer,
629
- audience: clientId,
630
- algorithms: ["RS256", "ES256"],
631
- clockTolerance: 5,
632
- });
633
- if (payload.nonce !== nonce || !payload.sub || !payload.exp) throw new Error("identity");
634
- return {
635
- subject: payload.sub,
636
- email: typeof payload.email === "string" ? payload.email : null,
637
- };
638
- },
639
- catch: () => failure("verify", "ChatGPT sign-in could not be verified. Start again."),
640
- });
684
+ const identity = yield* verifyIdToken(tokens.id_token, clientId).pipe(
685
+ Effect.flatMap(({ claims }) =>
686
+ claims.nonce === nonce
687
+ ? Effect.succeed({
688
+ subject: claims.sub,
689
+ email: typeof claims.email === "string" ? claims.email : null,
690
+ })
691
+ : Effect.fail(failure("verify", "identity")),
692
+ ),
693
+ Effect.mapError(() =>
694
+ failure("verify", "ChatGPT sign-in could not be verified. Start again."),
695
+ ),
696
+ );
697
const expectedSubject =
698
savedRegistration?.subject ??
699
(previous?.clientId === registeredClientId ? previous?.subject : undefined);
@@ -951,20 +1007,15 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
1007
"import",
1008
"The transferred ChatGPT connection is invalid or expired.",
1009
);
954
- const identity = yield* Effect.tryPromise({
955
- try: () =>
956
- jwtVerify(credentials.idToken, jwks!, {
957
- issuer: endpoints.issuer,
958
- audience: credentials.clientId,
959
- algorithms: ["RS256", "ES256"],
960
- clockTolerance: 5,
961
- }),
962
- catch: () => failure("import", "The transferred ChatGPT identity could not be verified."),
963
- });
1010
+ const identity = yield* verifyIdToken(credentials.idToken, credentials.clientId).pipe(
1011
+ Effect.mapError(() =>
1012
+ failure("import", "The transferred ChatGPT identity could not be verified."),
1013
+ ),
1014
+ );
1015
if (
965
- identity.payload.sub !== credentials.subject ||
1016
+ identity.claims.sub !== credentials.subject ||
1017
profile.registration.subject !== credentials.subject ||
967
- (identity.payload.email ?? null) !== credentials.email ||
1018
+ (identity.claims.email ?? null) !== credentials.email ||
1019
(profile.registration.email !== undefined &&
1020
profile.registration.email !== credentials.email)
1021
)
apps/server/src/provider/Drivers/CodexDriver.ts
+2
@@ -1,6 +1,7 @@
1
import { CodexSettings, ProviderDriverKind } from "@t3tools/contracts";
2
import * as Digest from "effect/crypto/Digest";
3
import * as SecureRandom from "effect/crypto/SecureRandom";
4
+import type * as Signature from "effect/crypto/Signature";
5
import * as Effect from "effect/Effect";
6
import * as FileSystem from "effect/FileSystem";
7
import * as Path from "effect/Path";
@@ -101,6 +102,7 @@ export type CodexDriverEnv =
102
| ResetCreditCoordinator.ResetCreditCoordinator
103
| Digest.Digest
104
| SecureRandom.SecureRandom
105
+ | Signature.Signature
106
| FileSystem.FileSystem
107
| HttpClient.HttpClient
108
| ProviderLatestVersions.ProviderLatestVersions
apps/server/src/relay/AgentAwarenessRelay.ts
+8
-13
@@ -24,6 +24,7 @@ import {
24
import * as Cause from "effect/Cause";
25
import * as Context from "effect/Context";
26
import * as SecureRandom from "effect/crypto/SecureRandom";
27
+import * as Signature from "effect/crypto/Signature";
28
import * as DateTime from "effect/DateTime";
29
import * as Effect from "effect/Effect";
30
import * as Fiber from "effect/Fiber";
@@ -247,17 +248,6 @@ function deliveryStats(
248
};
249
}
250
250
-function signRelayAgentActivityPublishProof(input: {
251
- readonly privateKey: string;
252
- readonly payload: RelayAgentActivityPublishProofPayload;
253
-}) {
254
- return signRelayJwt({
255
- privateKey: input.privateKey,
256
- typ: RELAY_ACTIVITY_PUBLISH_TYP,
257
- payload: input.payload,
258
- });
259
-}
260
-
251
const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
252
readonly privateKey: string;
253
readonly relayIssuer: string;
@@ -279,7 +269,11 @@ const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
269
threadId: input.threadId,
270
state: input.state,
271
} satisfies RelayAgentActivityPublishProofPayload;
282
- return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });
272
+ return yield* signRelayJwt({
273
+ privateKey: input.privateKey,
274
+ typ: RELAY_ACTIVITY_PUBLISH_TYP,
275
+ payload,
276
+ });
277
});
278
279
function describeThreadShellForAwareness(
@@ -378,6 +372,7 @@ export const make = Effect.gen(function* () {
372
const threads = yield* ThreadManagement.ThreadManagementService;
373
const projects = yield* ProjectService.ProjectService;
374
const random = yield* SecureRandom.SecureRandom;
375
+ const signature = yield* Signature.Signature;
376
const scope = yield* Effect.scope;
377
const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
378
const startedAt = (yield* DateTime.now).epochMilliseconds;
@@ -491,7 +486,7 @@ export const make = Effect.gen(function* () {
486
threadId,
487
state: input.state,
488
jti: yield* random.uuidV4(),
494
- });
489
+ }).pipe(Effect.provideService(Signature.Signature, signature));
490
491
yield* Effect.logInfo("publishing agent activity for thread", {
492
environmentId,
apps/server/src/scheduledTasks/RelayDeliveryProof.ts
+6
-8
@@ -6,21 +6,19 @@ import {
6
RELAY_HOOK_DELIVERY_TYP,
7
verifyRelayJwt,
8
} from "@t3tools/shared/relayJwt";
9
-import * as Clock from "effect/Clock";
9
import * as Context from "effect/Context";
10
+import * as Signature from "effect/crypto/Signature";
11
import * as Effect from "effect/Effect";
12
import * as Layer from "effect/Layer";
13
import * as Option from "effect/Option";
14
-import * as Schema from "effect/Schema";
14
15
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
16
import { CLOUD_MINT_PUBLIC_KEY, RELAY_ISSUER_SECRET, RELAY_URL_SECRET } from "../cloud/config.ts";
17
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
18
19
/** Covers the relay's 24-hour hold plus a margin. */
21
-const MAX_PROOF_AGE_SECONDS = 25 * 60 * 60;
20
+const MAX_PROOF_AGE = "25 hours";
21
23
-const decodePayload = Schema.decodeUnknownOption(RelayHookDeliveryProofPayload);
22
const text = (bytes: Option.Option<Uint8Array>) =>
23
Option.map(bytes, (value) => new TextDecoder().decode(value));
24
@@ -39,6 +37,7 @@ export class RelayDeliveryProof extends Context.Service<
37
const make = Effect.gen(function* () {
38
const secrets = yield* ServerSecretStore.ServerSecretStore;
39
const environment = yield* ServerEnvironment.ServerEnvironment;
40
+ const signature = yield* Signature.Signature;
41
const verify: RelayDeliveryProof["Service"]["verify"] = Effect.fn("webhook.verifyRelayDelivery")(
42
function* (input) {
43
const proof = input.headers[RELAY_HOOK_DELIVERY_HEADER];
@@ -55,15 +54,14 @@ const make = Effect.gen(function* () {
54
const relayIssuer = Option.isSome(issuer) ? issuer : relayUrl;
55
if (Option.isNone(publicKey) || Option.isNone(relayIssuer)) return Option.none();
56
const environmentId = yield* environment.getEnvironmentId;
58
- const payload = yield* verifyRelayJwt({
57
+ const payload = yield* verifyRelayJwt(RelayHookDeliveryProofPayload, {
58
publicKey: publicKey.value,
59
token: proof,
60
typ: RELAY_HOOK_DELIVERY_TYP,
61
issuer: normalizeRelayIssuer(relayIssuer.value),
62
audience: `t3-env:${environmentId}`,
64
- nowEpochSeconds: Math.floor((yield* Clock.currentTimeMillis) / 1_000),
65
- maxTokenAge: MAX_PROOF_AGE_SECONDS,
66
- }).pipe(Effect.map(decodePayload), Effect.orElseSucceed(Option.none));
63
+ maxTokenAge: MAX_PROOF_AGE,
64
+ }).pipe(Effect.provideService(Signature.Signature, signature), Effect.option);
65
// The proof must name exactly this delivery, so it cannot be lifted onto another one.
66
if (
67
Option.isNone(payload) ||
apps/server/src/scheduledTasks/webhookRoute.test.ts
+3
-2
@@ -1,3 +1,4 @@
1
+import * as PlatformNodeCrypto from "@effect/platform-node/NodeCrypto";
2
import { describe, expect, it } from "@effect/vitest";
3
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
4
import * as NodeCrypto from "node:crypto";
@@ -66,7 +67,7 @@ const relayProof = Effect.fn("relayProof")(function* (claims: {
67
receivedAt: claims.receivedAt,
68
hookId: claims.hookId,
69
},
69
- });
70
+ }).pipe(Effect.provide(PlatformNodeCrypto.layerSignature));
71
});
72
73
const handlerFor = (
@@ -101,7 +102,7 @@ const handlerFor = (
102
Layer.provideMerge(Etag.layerWeak),
103
),
104
),
104
- Layer.provide(NodeServices.layer),
105
+ Layer.provide([NodeServices.layer, PlatformNodeCrypto.layerSignature]),
106
),
107
{ disableLogger: true },
108
);
apps/web/package.json
-1
@@ -65,7 +65,6 @@
65
"hast-util-to-jsx-runtime": "^2.3.6",
66
"heic-to": "^1.5.2",
67
"html-url-attributes": "^3.0.1",
68
- "jose": "catalog:",
68
"jsonc-parser": "3.3.1",
69
"jszip": "3.10.1",
70
"katex": "^0.16.47",
apps/web/src/cloud/dpop.test.ts
+3
-4
@@ -1,7 +1,7 @@
1
import { verifyDpopProof } from "@t3tools/shared/dpop";
2
import { describe, expect, it } from "@effect/vitest";
3
import * as Effect from "effect/Effect";
4
-import { decodeJwt } from "jose";
4
+import * as TestClock from "effect/testing/TestClock";
5
import { vi } from "vite-plus/test";
6
7
import { createBrowserDpopProof, generateBrowserDpopKey } from "./dpop";
@@ -11,6 +11,7 @@ describe("browser DPoP proofs", () => {
11
it.effect("signs relay resource proofs with an access-token hash", () =>
12
Effect.gen(function* () {
13
vi.stubGlobal("indexedDB", undefined);
14
+ yield* TestClock.setTime(1_700_000_000_000);
15
const proofKey = yield* generateBrowserDpopKey;
16
const proof = yield* createBrowserDpopProof({
17
method: "POST",
@@ -18,8 +19,6 @@ describe("browser DPoP proofs", () => {
19
accessToken: "relay-access-token",
20
proofKey,
21
}).pipe(Effect.provide(Dpop.layer));
21
- const issuedAt = decodeJwt(proof.proof).iat;
22
- expect(issuedAt).toBeTypeOf("number");
22
23
expect(
24
verifyDpopProof({
@@ -28,7 +27,7 @@ describe("browser DPoP proofs", () => {
27
url: "https://relay.example.test/v1/environments/env-1/connect",
28
expectedThumbprint: proof.thumbprint,
29
expectedAccessToken: "relay-access-token",
31
- nowEpochSeconds: issuedAt!,
30
+ nowEpochSeconds: 1_700_000_000,
31
}),
32
).toMatchObject({ ok: true });
33
}),
apps/web/src/cloud/dpop.ts
+31
-21
@@ -5,11 +5,14 @@ import {
5
} from "@t3tools/shared/dpop";
6
import * as Digest from "effect/crypto/Digest";
7
import * as SecureRandom from "effect/crypto/SecureRandom";
8
+import * as Signature from "effect/crypto/Signature";
9
+import * as Clock from "effect/Clock";
10
import * as Data from "effect/Data";
11
import * as Effect from "effect/Effect";
12
+import * as Jwt from "effect/jose/Jwt";
13
import * as Layer from "effect/Layer";
14
+import * as Redacted from "effect/Redacted";
15
import * as Schema from "effect/Schema";
12
-import { importJWK, SignJWT, type JWK } from "jose";
16
17
export interface BrowserDpopKey {
18
readonly privateKey: CryptoKey;
@@ -28,7 +31,9 @@ const DPOP_KEY_STORE_NAME = "keys";
31
const DPOP_KEY_ID = "relay-dpop-proof-key";
32
const decodeDpopPublicJwk = Schema.decodeUnknownEffect(DpopPublicJwk);
33
31
-export const layer = Layer.mergeAll(SecureRandom.layerWebCrypto, Digest.layerWebCrypto);
34
+export const layer = Layer.mergeAll(Digest.layerWebCrypto, Signature.layerWebCrypto).pipe(
35
+ Layer.provideMerge(SecureRandom.layerWebCrypto),
36
+);
37
38
function dpopError(message: string, cause?: unknown) {
39
return new BrowserDpopError({ message, ...(cause === undefined ? {} : { cause }) });
@@ -122,7 +127,10 @@ export const generateBrowserDpopKey = Effect.gen(function* () {
127
),
128
);
129
const privateKey = yield* Effect.tryPromise({
125
- try: () => importJWK(privateJwk as JWK, "ES256", { extractable: false }) as Promise<CryptoKey>,
130
+ try: () =>
131
+ crypto.subtle.importKey("jwk", privateJwk, { name: "ECDSA", namedCurve: "P-256" }, false, [
132
+ "sign",
133
+ ]),
134
catch: (cause) => dpopError("Could not import DPoP private key.", cause),
135
});
136
return {
@@ -140,7 +148,7 @@ export const createBrowserDpopProof = Effect.fn("dpop.createBrowserDpopProof")(f
148
}): Effect.fn.Return<
149
{ readonly proof: string; readonly thumbprint: string },
150
BrowserDpopError,
143
- SecureRandom.SecureRandom
151
+ SecureRandom.SecureRandom | Signature.Signature
152
> {
153
const normalizedUrl = yield* Effect.try({
154
try: () => new URL(input.url),
@@ -149,22 +157,24 @@ export const createBrowserDpopProof = Effect.fn("dpop.createBrowserDpopProof")(f
157
normalizedUrl.search = "";
158
normalizedUrl.hash = "";
159
const jti = yield* SecureRandom.SecureRandom.pipe(Effect.flatMap((random) => random.uuidV4()));
152
- const proof = yield* Effect.tryPromise({
153
- try: () =>
154
- new SignJWT({
155
- htm: input.method.toUpperCase(),
156
- htu: normalizedUrl.toString(),
157
- jti,
158
- ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),
159
- })
160
- .setProtectedHeader({
161
- typ: "dpop+jwt",
162
- alg: "ES256",
163
- jwk: input.proofKey.publicJwk,
164
- })
165
- .setIssuedAt()
166
- .sign(input.proofKey.privateKey),
167
- catch: (cause) => dpopError("Could not sign DPoP proof.", cause),
168
- });
160
+ const key = yield* Signature.privateKeyFromCryptoKey(
161
+ Signature.ecdsaP256,
162
+ input.proofKey.privateKey,
163
+ ).pipe(Effect.mapError((cause) => dpopError("Could not load DPoP proof key.", cause)));
164
+ const proof = yield* Jwt.sign(
165
+ Schema.Json,
166
+ {
167
+ htm: input.method.toUpperCase(),
168
+ htu: normalizedUrl.toString(),
169
+ jti,
170
+ iat: Math.floor((yield* Clock.currentTimeMillis) / 1_000),
171
+ ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),
172
+ },
173
+ { _tag: "PrivateKey", algorithm: "ES256", kid: undefined, key },
174
+ { typ: "dpop+jwt", jwk: input.proofKey.publicJwk },
175
+ ).pipe(
176
+ Effect.map(Redacted.value),
177
+ Effect.mapError((cause) => dpopError("Could not sign DPoP proof.", cause)),
178
+ );
179
return { proof, thumbprint: input.proofKey.thumbprint };
180
});
apps/web/src/cloud/managedRelayLayer.ts
+3
@@ -1,6 +1,7 @@
1
import { ManagedRelay } from "@t3tools/client-runtime/relay";
2
import { RelayWebClientId } from "@t3tools/contracts/relay";
3
import * as SecureRandom from "effect/crypto/SecureRandom";
4
+import * as Signature from "effect/crypto/Signature";
5
import * as Effect from "effect/Effect";
6
import * as Layer from "effect/Layer";
7
import * as Semaphore from "effect/Semaphore";
@@ -17,6 +18,7 @@ const layerRelayDpopSigner = Layer.effect(
18
ManagedRelay.ManagedRelayDpopSigner,
19
Effect.gen(function* () {
20
const random = yield* SecureRandom.SecureRandom;
21
+ const signature = yield* Signature.Signature;
22
const keyLoadSemaphore = yield* Semaphore.make(1);
23
let loadedKey: BrowserDpopKey | null = null;
24
const loadOrCreateBrowserDpopKey = keyLoadSemaphore.withPermit(
@@ -61,6 +63,7 @@ const layerRelayDpopSigner = Layer.effect(
63
);
64
return yield* createBrowserDpopProof({ ...input, proofKey }).pipe(
65
Effect.provideService(SecureRandom.SecureRandom, random),
66
+ Effect.provideService(Signature.Signature, signature),
67
Effect.map((proof) => proof.proof),
68
Effect.mapError(
69
(error) =>
infra/relay/src/auth/RelayTokens.test.ts
+19
-14
@@ -3,9 +3,12 @@ import * as NodeCrypto from "node:crypto";
3
4
import { describe, expect, it } from "@effect/vitest";
5
import { signRelayJwt } from "@t3tools/shared/relayJwt";
6
+import * as SecureRandom from "effect/crypto/SecureRandom";
7
+import * as Signature from "effect/crypto/Signature";
8
import * as Effect from "effect/Effect";
9
import * as Layer from "effect/Layer";
10
import * as Redacted from "effect/Redacted";
11
+import * as TestClock from "effect/testing/TestClock";
12
13
import * as RelayConfiguration from "../Config.ts";
14
import * as RelayTokens from "./RelayTokens.ts";
@@ -34,7 +37,11 @@ const config = RelayConfiguration.RelayConfiguration.of({
37
managedEndpointNamespace: undefined,
38
});
39
37
-const layer = RelayTokens.layer.pipe(Layer.provide(RelayConfiguration.layer(config)));
40
+const layer = RelayTokens.layer.pipe(
41
+ Layer.provide(RelayConfiguration.layer(config)),
42
+ Layer.provideMerge(Signature.layerWebCrypto),
43
+ Layer.provide(SecureRandom.layerWebCrypto),
44
+);
45
46
describe("RelayTokens", () => {
47
it.effect("issues a user-bound environment link challenge", () =>
@@ -51,6 +58,7 @@ describe("RelayTokens", () => {
58
issuedAtEpochSeconds: 100,
59
expiresAtEpochSeconds: 200,
60
});
61
+ yield* TestClock.setTime(150_000);
62
63
expect(
64
yield* relayTokens.verifyLinkChallenge({
@@ -61,7 +69,6 @@ describe("RelayTokens", () => {
69
liveActivitiesEnabled: true,
70
managedTunnelsEnabled: true,
71
},
64
- nowEpochSeconds: 150,
72
}),
73
).toMatchObject({ sub: "user_123", jti: "challenge-1" });
74
expect(
@@ -73,7 +80,6 @@ describe("RelayTokens", () => {
80
liveActivitiesEnabled: true,
81
managedTunnelsEnabled: true,
82
},
76
- nowEpochSeconds: 150,
83
}),
84
).toBeNull();
85
}).pipe(Effect.provide(layer)),
@@ -92,17 +98,15 @@ describe("RelayTokens", () => {
98
scopes: ["environment:connect", "environment:status", "mobile:registration"],
99
});
100
95
- expect(
96
- yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 700 }),
97
- ).toMatchObject({
101
+ yield* TestClock.setTime(700_000);
102
+ expect(yield* relayTokens.verifyDpopAccessToken({ token })).toMatchObject({
103
sub: "user_123",
104
cnf: { jkt: "proof-key-thumbprint" },
105
client_id: "t3-mobile",
106
scope: ["environment:connect", "environment:status", "mobile:registration"],
107
});
103
- expect(
104
- yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 1_961 }),
105
- ).toBeNull();
108
+ yield* TestClock.setTime(1_961_000);
109
+ expect(yield* relayTokens.verifyDpopAccessToken({ token })).toBeNull();
110
}).pipe(Effect.provide(layer)),
111
);
112
@@ -119,9 +123,8 @@ describe("RelayTokens", () => {
123
scopes: ["environment:connect", "environment:status"],
124
});
125
122
- expect(
123
- yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 }),
124
- ).toMatchObject({
126
+ yield* TestClock.setTime(150_000);
127
+ expect(yield* relayTokens.verifyDpopAccessToken({ token })).toMatchObject({
128
client_id: "t3-web",
129
scope: ["environment:connect", "environment:status"],
130
cnf: { jkt: "web-proof-key-thumbprint" },
@@ -148,7 +151,8 @@ describe("RelayTokens", () => {
151
},
152
});
153
151
- expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 })).toBeNull();
154
+ yield* TestClock.setTime(150_000);
155
+ expect(yield* relayTokens.verifyDpopAccessToken({ token })).toBeNull();
156
}).pipe(Effect.provide(layer)),
157
);
158
@@ -171,7 +175,8 @@ describe("RelayTokens", () => {
175
},
176
});
177
174
- expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 })).toBeNull();
178
+ yield* TestClock.setTime(150_000);
179
+ expect(yield* relayTokens.verifyDpopAccessToken({ token })).toBeNull();
180
}).pipe(Effect.provide(layer)),
181
);
182
});
infra/relay/src/auth/RelayTokens.ts
+8
-13
@@ -16,6 +16,7 @@ import {
16
verifyRelayJwt,
17
} from "@t3tools/shared/relayJwt";
18
import * as Context from "effect/Context";
19
+import * as Signature from "effect/crypto/Signature";
20
import * as Effect from "effect/Effect";
21
import * as Layer from "effect/Layer";
22
import * as Redacted from "effect/Redacted";
@@ -57,9 +58,6 @@ export type RelayDpopAccessTokenClaims = Omit<typeof RelayDpopAccessTokenClaims.
58
readonly scope: ReadonlyArray<RelayDpopAccessTokenScope>;
59
};
60
60
-const decodeLinkChallengeClaims = Schema.decodeUnknownEffect(LinkChallengeClaims);
61
-const decodeDpopAccessTokenClaims = Schema.decodeUnknownEffect(RelayDpopAccessTokenClaims);
62
-
61
const allowedScopesByClientId: Record<
62
RelayPublicClientId,
63
ReadonlySet<RelayDpopAccessTokenScope>
@@ -97,7 +95,6 @@ export class RelayTokens extends Context.Service<
95
readonly token: string;
96
readonly userId: string;
97
readonly request: RelayEnvironmentLinkChallengeRequest;
100
- readonly nowEpochSeconds: number;
98
}) => Effect.Effect<LinkChallengeClaims | null>;
99
readonly issueDpopAccessToken: (input: {
100
readonly userId: string;
@@ -110,7 +107,6 @@ export class RelayTokens extends Context.Service<
107
}) => Effect.Effect<string, RelayJwtError>;
108
readonly verifyDpopAccessToken: (input: {
109
readonly token: string;
113
- readonly nowEpochSeconds: number;
110
}) => Effect.Effect<RelayDpopAccessTokenClaims | null>;
111
}
112
>()("t3code-relay/auth/RelayTokens") {}
@@ -118,6 +114,7 @@ export class RelayTokens extends Context.Service<
114
const make = Effect.gen(function* () {
115
const config = yield* RelayConfiguration.RelayConfiguration;
116
const issuer = normalizeRelayIssuer(config.relayIssuer);
117
+ const signature = yield* Signature.Signature;
118
119
const issueLinkChallenge: RelayTokens["Service"]["issueLinkChallenge"] = Effect.fn(
120
"relay.tokens.issue_link_challenge",
@@ -135,21 +132,20 @@ const make = Effect.gen(function* () {
132
exp: input.expiresAtEpochSeconds,
133
...input.request,
134
},
138
- });
135
+ }).pipe(Effect.provideService(Signature.Signature, signature));
136
});
137
138
const verifyLinkChallenge: RelayTokens["Service"]["verifyLinkChallenge"] = Effect.fn(
139
"relay.tokens.verify_link_challenge",
140
)((input) =>
144
- verifyRelayJwt({
141
+ verifyRelayJwt(LinkChallengeClaims, {
142
publicKey: config.cloudMintPublicKey,
143
token: input.token,
144
typ: LINK_CHALLENGE_TYP,
145
issuer,
146
audience: issuer,
150
- nowEpochSeconds: input.nowEpochSeconds,
147
}).pipe(
152
- Effect.flatMap(decodeLinkChallengeClaims),
148
+ Effect.provideService(Signature.Signature, signature),
149
Effect.map((claims) => {
150
if (
151
claims.sub !== input.userId ||
@@ -182,28 +178,27 @@ const make = Effect.gen(function* () {
178
scope: encodeOAuthScope(input.scopes),
179
cnf: { jkt: input.proofKeyThumbprint },
180
},
185
- });
181
+ }).pipe(Effect.provideService(Signature.Signature, signature));
182
});
183
184
const verifyDpopAccessToken: RelayTokens["Service"]["verifyDpopAccessToken"] = Effect.fn(
185
"relay.tokens.verify_dpop_access_token",
186
)((input) =>
191
- verifyRelayJwt({
187
+ verifyRelayJwt(RelayDpopAccessTokenClaims, {
188
publicKey: config.cloudMintPublicKey,
189
token: input.token,
190
typ: ACCESS_TOKEN_TYP,
191
issuer,
192
audience: issuer,
197
- nowEpochSeconds: input.nowEpochSeconds,
193
maxTokenAge: RELAY_DPOP_ACCESS_TOKEN_TTL,
194
}).pipe(
195
+ Effect.provideService(Signature.Signature, signature),
196
Effect.tapError((error) =>
197
Effect.annotateCurrentSpan(
198
"relay.tokens.verification_failure",
199
RelayJwtError.diagnosticCode(error),
200
),
201
),
206
- Effect.flatMap(decodeDpopAccessTokenClaims),
202
Effect.map((claims): RelayDpopAccessTokenClaims | null => {
203
const scopes = resolveDpopAccessTokenScopes({
204
clientId: claims.client_id,
infra/relay/src/environments/EnvironmentConnector.ts
+12
-22
@@ -31,6 +31,7 @@ import {
31
import { stableStringify } from "@t3tools/shared/relaySigning";
32
import * as Context from "effect/Context";
33
import * as SecureRandom from "effect/crypto/SecureRandom";
34
+import * as Signature from "effect/crypto/Signature";
35
import * as DateTime from "effect/DateTime";
36
import * as Duration from "effect/Duration";
37
import * as Effect from "effect/Effect";
@@ -151,12 +152,6 @@ export class EnvironmentConnector extends Context.Service<
152
}
153
>()("t3code-relay/environments/EnvironmentConnector") {}
154
154
-const decodeMintResponseProof = Schema.decodeUnknownEffect(
155
- RelayEnvironmentMintResponseProofPayload,
156
-);
157
-const decodeHealthResponseProof = Schema.decodeUnknownEffect(
158
- RelayEnvironmentHealthResponseProofPayload,
159
-);
155
const isEnvironmentHealthError = Schema.is(
156
Schema.Union([
157
EnvironmentHttpBadRequestError,
@@ -200,21 +195,17 @@ const currentTraceId = Effect.currentSpan.pipe(
195
export const withoutRedirects = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
196
effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
197
203
-const verifyWithEnvironmentKeys = Effect.fnUntraced(function* <A, E>(input: {
198
+const verifyWithEnvironmentKeys = Effect.fnUntraced(function* <A>(input: {
199
readonly token: string;
200
readonly typ: string;
201
readonly issuer: string;
202
readonly audience: string;
208
- readonly nowEpochSeconds: number;
203
readonly environmentPublicKeys: ReadonlyArray<string>;
210
- readonly decodePayload: (input: unknown) => Effect.Effect<A, E>;
204
+ readonly schema: Schema.ConstraintDecoder<A>;
205
}) {
212
- const { decodePayload, ...rest } = input;
206
+ const { schema, environmentPublicKeys: _keys, ...rest } = input;
207
for (const publicKey of input.environmentPublicKeys) {
214
- const proof = yield* verifyRelayJwt({ ...rest, publicKey }).pipe(
215
- Effect.flatMap(decodePayload),
216
- Effect.option,
217
- );
208
+ const proof = yield* verifyRelayJwt(schema, { ...rest, publicKey }).pipe(Effect.option);
209
if (Option.isSome(proof)) {
210
return proof.value;
211
}
@@ -230,16 +221,14 @@ function verifyEnvironmentResponse(input: {
221
readonly clientProofKeyThumbprint: string;
222
readonly environmentPublicKeys: ReadonlyArray<string>;
223
readonly relayIssuer: string;
233
- readonly nowEpochSeconds: number;
224
}) {
225
return verifyWithEnvironmentKeys({
226
token: input.response.proof,
227
typ: RELAY_MINT_RESPONSE_TYP,
228
issuer: `t3-env:${input.environmentId}`,
229
audience: normalizeRelayIssuer(input.relayIssuer),
240
- nowEpochSeconds: input.nowEpochSeconds,
230
environmentPublicKeys: input.environmentPublicKeys,
242
- decodePayload: decodeMintResponseProof,
231
+ schema: RelayEnvironmentMintResponseProofPayload,
232
}).pipe(
233
Effect.map(
234
(proof) =>
@@ -270,9 +259,8 @@ function verifyEnvironmentHealthResponse(input: {
259
typ: RELAY_HEALTH_RESPONSE_TYP,
260
issuer: `t3-env:${input.environmentId}`,
261
audience: normalizeRelayIssuer(input.relayIssuer),
273
- nowEpochSeconds: Math.floor(input.now.epochMilliseconds / 1_000),
262
environmentPublicKeys: input.environmentPublicKeys,
275
- decodePayload: decodeHealthResponseProof,
263
+ schema: RelayEnvironmentHealthResponseProofPayload,
264
}).pipe(
265
Effect.map((proof) => {
266
if (
@@ -387,6 +375,7 @@ const make = Effect.gen(function* () {
375
const settings = yield* RelayConfiguration.RelayConfiguration;
376
const httpClient = yield* HttpClient.HttpClient;
377
const random = yield* SecureRandom.SecureRandom;
378
+ const signature = yield* Signature.Signature;
379
const relayIssuer = normalizeRelayIssuer(settings.relayIssuer);
380
const makeEnvironmentClient = (httpBaseUrl: string) =>
381
makeEnvironmentHttpApiClient(httpBaseUrl).pipe(
@@ -479,6 +468,7 @@ const make = Effect.gen(function* () {
468
typ: RELAY_HEALTH_REQUEST_TYP,
469
payload,
470
}).pipe(
471
+ Effect.provideService(Signature.Signature, signature),
472
Effect.mapError(
473
(cause) =>
474
new EnvironmentMintRequestFailed({
@@ -556,7 +546,7 @@ const make = Effect.gen(function* () {
546
environmentPublicKeys: [link.environmentPublicKey],
547
relayIssuer,
548
now: yield* DateTime.now,
559
- });
549
+ }).pipe(Effect.provideService(Signature.Signature, signature));
550
if (!verified) {
551
return yield* new EnvironmentMintResponseInvalid({
552
environmentId: input.environmentId,
@@ -644,6 +634,7 @@ const make = Effect.gen(function* () {
634
typ: RELAY_MINT_REQUEST_TYP,
635
payload,
636
}).pipe(
637
+ Effect.provideService(Signature.Signature, signature),
638
Effect.mapError(
639
(cause) =>
640
new EnvironmentMintRequestFailed({
@@ -693,8 +684,7 @@ const make = Effect.gen(function* () {
684
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
685
environmentPublicKeys: [link.environmentPublicKey],
686
relayIssuer,
696
- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
697
- });
687
+ }).pipe(Effect.provideService(Signature.Signature, signature));
688
if (!verified) {
689
return yield* new EnvironmentMintResponseInvalid({
690
environmentId: input.environmentId,
infra/relay/src/environments/EnvironmentLinker.test.ts
+2
@@ -1,5 +1,6 @@
1
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.
2
import * as NodeCrypto from "node:crypto";
3
+import * as EffectNodeCrypto from "@effect/platform-node/NodeCrypto";
4
import type {
5
RelayEnvironmentLinkProofPayload,
6
RelayEnvironmentLinkRequest,
@@ -153,6 +154,7 @@ function layerTest(input?: {
154
}),
155
),
156
),
157
+ Layer.provideMerge(EffectNodeCrypto.layerSignature),
158
);
159
}
160
infra/relay/src/environments/EnvironmentLinker.ts
+16
-15
@@ -10,6 +10,7 @@ import {
10
verifyRelayJwt,
11
} from "@t3tools/shared/relayJwt";
12
import * as Context from "effect/Context";
13
+import * as Signature from "effect/crypto/Signature";
14
import * as DateTime from "effect/DateTime";
15
import * as Effect from "effect/Effect";
16
import * as Layer from "effect/Layer";
@@ -142,22 +143,24 @@ const make = Effect.gen(function* () {
143
const proofReplay = yield* DpopProofs.DpopProofReplay;
144
const relayTokens = yield* RelayTokens.RelayTokens;
145
const config = yield* RelayConfiguration.RelayConfiguration;
146
+ const signature = yield* Signature.Signature;
147
148
return EnvironmentLinker.of({
149
link: Effect.fn("relay.environment_linker.link")(function* (input) {
150
const now = yield* DateTime.now;
151
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
150
- const unverified = yield* Effect.try({
151
- try: () => decodeRelayJwt(input.request.proof),
152
- catch: (cause) =>
153
- new EnvironmentLinkProofInvalid({
154
- userId: input.userId,
155
- environmentId: "unknown",
156
- reason: "invalid_signature_or_scope",
157
- stage: "decode_token",
158
- cause,
159
- }),
160
- });
152
+ const unverified = yield* decodeRelayJwt(input.request.proof).pipe(
153
+ Effect.mapError(
154
+ (cause) =>
155
+ new EnvironmentLinkProofInvalid({
156
+ userId: input.userId,
157
+ environmentId: "unknown",
158
+ reason: "invalid_signature_or_scope",
159
+ stage: "decode_token",
160
+ cause,
161
+ }),
162
+ ),
163
+ );
164
const candidate = yield* decodeProof(unverified).pipe(
165
Effect.mapError(
166
(cause) =>
@@ -185,15 +188,14 @@ const make = Effect.gen(function* () {
188
}
189
const issuer = `t3-env:${candidate.environmentId}`;
190
const relayIssuer = normalizeRelayIssuer(config.relayIssuer);
188
- const verified = yield* verifyRelayJwt({
191
+ const verified = yield* verifyRelayJwt(RelayEnvironmentLinkProofPayload, {
192
publicKey: candidate.environmentPublicKey,
193
token: input.request.proof,
194
typ: RELAY_LINK_PROOF_TYP,
195
issuer,
196
audience: relayIssuer,
194
- nowEpochSeconds: nowSeconds,
197
}).pipe(
196
- Effect.flatMap(decodeProof),
198
+ Effect.provideService(Signature.Signature, signature),
199
Effect.mapError(
200
(cause) =>
201
new EnvironmentLinkProofInvalid({
@@ -232,7 +234,6 @@ const make = Effect.gen(function* () {
234
liveActivitiesEnabled: input.request.liveActivitiesEnabled,
235
managedTunnelsEnabled: input.request.managedTunnelsEnabled,
236
},
235
- nowEpochSeconds: nowSeconds,
237
});
238
if (challenge === null) {
239
return yield* new EnvironmentLinkProofInvalid({
infra/relay/src/environments/EnvironmentPublishSignatures.ts
+16
-16
@@ -12,6 +12,7 @@ import {
12
import { stableStringify } from "@t3tools/shared/relaySigning";
13
import * as Context from "effect/Context";
14
import * as Digest from "effect/crypto/Digest";
15
+import * as Signature from "effect/crypto/Signature";
16
import * as DateTime from "effect/DateTime";
17
import * as Effect from "effect/Effect";
18
import * as Base64Url from "effect/encoding/Base64Url";
@@ -73,8 +74,6 @@ export class EnvironmentPublishSignatures extends Context.Service<
74
}
75
>()("t3code-relay/environments/EnvironmentPublishSignatures") {}
76
76
-const decodeProof = Schema.decodeUnknownEffect(RelayAgentActivityPublishProofPayload);
77
-
77
function environmentPublishReplayThumbprintData(input: {
78
readonly environmentId: string;
79
readonly environmentPublicKey: string;
@@ -94,6 +93,7 @@ const make = Effect.gen(function* () {
93
const proofReplay = yield* DpopProofs.DpopProofReplay;
94
const config = yield* RelayConfiguration.RelayConfiguration;
95
const crypto = yield* Digest.Digest;
96
+ const signature = yield* Signature.Signature;
97
98
return EnvironmentPublishSignatures.of({
99
verify: Effect.fn("relay.environment_publish_signatures.verify")(function* (input) {
@@ -102,17 +102,18 @@ const make = Effect.gen(function* () {
102
"relay.thread_id": input.threadId,
103
});
104
const now = yield* DateTime.now;
105
- const decoded = yield* Effect.try({
106
- try: () => decodeRelayJwt(input.request.proof),
107
- catch: (cause) =>
108
- new EnvironmentPublishSignatureInvalid({
109
- environmentId: input.environmentId,
110
- threadId: input.threadId,
111
- reason: "invalid_signature_or_payload",
112
- stage: "decode_token",
113
- cause,
114
- }),
115
- });
105
+ const decoded = yield* decodeRelayJwt(input.request.proof).pipe(
106
+ Effect.mapError(
107
+ (cause) =>
108
+ new EnvironmentPublishSignatureInvalid({
109
+ environmentId: input.environmentId,
110
+ threadId: input.threadId,
111
+ reason: "invalid_signature_or_payload",
112
+ stage: "decode_token",
113
+ cause,
114
+ }),
115
+ ),
116
+ );
117
if (
118
typeof decoded.exp === "number" &&
119
decoded.exp <= Math.floor(now.epochMilliseconds / 1_000)
@@ -123,15 +124,14 @@ const make = Effect.gen(function* () {
124
expiresAt: DateTime.formatIso(DateTime.makeUnsafe(decoded.exp * 1_000)),
125
});
126
}
126
- const proof = yield* verifyRelayJwt({
127
+ const proof = yield* verifyRelayJwt(RelayAgentActivityPublishProofPayload, {
128
publicKey: input.environmentPublicKey,
129
token: input.request.proof,
130
typ: RELAY_ACTIVITY_PUBLISH_TYP,
131
issuer: `t3-env:${input.environmentId}`,
132
audience: normalizeRelayIssuer(config.relayIssuer),
132
- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
133
}).pipe(
134
- Effect.flatMap(decodeProof),
134
+ Effect.provideService(Signature.Signature, signature),
135
Effect.mapError(
136
(cause) =>
137
new EnvironmentPublishSignatureInvalid({
infra/relay/src/hooks/HookForwarder.test.ts
+3
-5
@@ -4,9 +4,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
4
import * as NodeCrypto from "node:crypto";
5
import * as EffectNodeCrypto from "@effect/platform-node/NodeCrypto";
6
import { describe, expect, it } from "@effect/vitest";
7
-import { RelayApi } from "@t3tools/contracts/relay";
7
+import { RelayApi, RelayHookDeliveryProofPayload } from "@t3tools/contracts/relay";
8
import * as Deferred from "effect/Deferred";
9
-import * as Clock from "effect/Clock";
9
import * as Effect from "effect/Effect";
10
import * as Layer from "effect/Layer";
11
import * as Redacted from "effect/Redacted";
@@ -256,14 +255,13 @@ describe("HookForwarder", () => {
255
}),
256
);
257
const sent = harness.sent[0]!;
259
- const payload = yield* verifyRelayJwt({
258
+ const payload = yield* verifyRelayJwt(RelayHookDeliveryProofPayload, {
259
publicKey: mintKeys.publicKey,
260
token: sent.headers["x-t3-relay-delivery"]!,
261
typ: RELAY_HOOK_DELIVERY_TYP,
262
issuer: settings.relayIssuer,
263
audience: `t3-env:${environmentId}`,
265
- nowEpochSeconds: Math.floor((yield* Clock.currentTimeMillis) / 1_000),
266
- });
264
+ }).pipe(Effect.provide(EffectNodeCrypto.layerSignature));
265
expect(payload).toMatchObject({
266
environmentId,
267
hookId: "hook-1",
infra/relay/src/hooks/HookForwarder.ts
+3
-1
@@ -1,6 +1,7 @@
1
import * as Clock from "effect/Clock";
2
import * as Context from "effect/Context";
3
import * as SecureRandom from "effect/crypto/SecureRandom";
4
+import * as Signature from "effect/crypto/Signature";
5
import * as DateTime from "effect/DateTime";
6
import * as Effect from "effect/Effect";
7
import * as Layer from "effect/Layer";
@@ -220,6 +221,7 @@ const make = Effect.gen(function* () {
221
const rateLimiter = yield* HookRateLimiter;
222
const inbox = yield* HookInbox.HookInbox;
223
const random = yield* SecureRandom.SecureRandom;
224
+ const signature = yield* Signature.Signature;
225
226
const signDeliveryProof = Effect.fn("HookForwarder.signDeliveryProof")(
227
function* (input: {
@@ -245,7 +247,7 @@ const make = Effect.gen(function* () {
247
receivedAt: input.receivedAt,
248
hookId: input.hookId,
249
} satisfies RelayHookDeliveryProofPayload,
248
- });
250
+ }).pipe(Effect.provideService(Signature.Signature, signature));
251
},
252
(effect, _input) => effect.pipe(Effect.orDie),
253
);
infra/relay/src/http/Api.test.ts
+9
-3
@@ -637,7 +637,10 @@ describe("relay managed tunnel recovery", () => {
637
}),
638
);
639
expect(wrongAction).toMatchObject({ _tag: "Unauthorized" });
640
- }).pipe(Effect.provideService(RelayConfiguration.RelayConfiguration, relaySettings)),
640
+ }).pipe(
641
+ Effect.provideService(RelayConfiguration.RelayConfiguration, relaySettings),
642
+ Effect.provide(NodeCryptoLayer.layerSignature),
643
+ ),
644
);
645
646
it.effect("rejects a signed registration proof for a different origin", () =>
@@ -679,7 +682,10 @@ describe("relay managed tunnel recovery", () => {
682
);
683
684
expect(error).toMatchObject({ _tag: "Unauthorized" });
682
- }).pipe(Effect.provideService(RelayConfiguration.RelayConfiguration, relaySettings)),
685
+ }).pipe(
686
+ Effect.provideService(RelayConfiguration.RelayConfiguration, relaySettings),
687
+ Effect.provide(NodeCryptoLayer.layerSignature),
688
+ ),
689
);
690
691
it.effect("registers recovery for an existing tunnel without provisioning it", () => {
@@ -1458,7 +1464,7 @@ describe("relay routing fallback", () => {
1464
})),
1465
);
1466
expect(verified.map((input) => input.threadId)).toEqual(threadIds);
1461
- }).pipe(Effect.scoped),
1467
+ }).pipe(Effect.scoped, Effect.provide(NodeCryptoLayer.layerSignature)),
1468
);
1469
});
1470
infra/relay/src/http/Api.ts
+3
-16
@@ -88,10 +88,6 @@ export const RELAY_HTTP_ROUTER_CONFIG = {
88
maxParamLength: 512,
89
} as const;
90
91
-const decodeManagedTunnelRecoveryProof = Schema.decodeUnknownEffect(
92
- RelayManagedEndpointRecoveryProofPayload,
93
-);
94
-
91
const appendRelayCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(
92
(_request, response) =>
93
Effect.succeed(
@@ -397,11 +393,7 @@ export const layerDpopClientAuth = Layer.effect(
393
return yield* relayAuthInvalidError("invalid_bearer");
394
}
395
const token = readHttpAuthorizationCredential(credential);
400
- const now = yield* DateTime.now;
401
- const verified = yield* relayTokens.verifyDpopAccessToken({
402
- token,
403
- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
404
- });
396
+ const verified = yield* relayTokens.verifyDpopAccessToken({ token });
397
if (!verified) {
398
return yield* relayAuthInvalidError("invalid_bearer");
399
}
@@ -588,18 +580,13 @@ export const verifyEnvironmentTunnelRecoveryProof = Effect.fn(
580
"relay.api.server.verifyEnvironmentTunnelRecoveryProof",
581
)(function* (input: EnvironmentTunnelRecoveryProofInput) {
582
const config = yield* RelayConfiguration.RelayConfiguration;
591
- const now = yield* DateTime.now;
592
- const verified = yield* verifyRelayJwt({
583
+ const verified = yield* verifyRelayJwt(RelayManagedEndpointRecoveryProofPayload, {
584
publicKey: input.environmentPublicKey,
585
token: input.proof,
586
typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
587
issuer: `t3-env:${input.environmentId}`,
588
audience: normalizeRelayIssuer(config.relayIssuer),
598
- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
599
- }).pipe(
600
- Effect.flatMap(decodeManagedTunnelRecoveryProof),
601
- Effect.mapError(() => new HttpApiError.Unauthorized({})),
602
- );
589
+ }).pipe(Effect.mapError(() => new HttpApiError.Unauthorized({})));
590
591
if (
592
verified.environmentId !== input.environmentId ||
infra/relay/src/worker.ts
+4
-1
@@ -7,6 +7,7 @@ import * as Cause from "effect/Cause";
7
import * as DateTime from "effect/DateTime";
8
import * as Digest from "effect/crypto/Digest";
9
import * as SecureRandom from "effect/crypto/SecureRandom";
10
+import * as Signature from "effect/crypto/Signature";
11
import * as Effect from "effect/Effect";
12
import * as Layer from "effect/Layer";
13
import * as Option from "effect/Option";
@@ -73,7 +74,9 @@ import * as HookInbox from "./hooks/HookInbox.ts";
74
import * as HookInboxObject from "./hooks/HookInboxObject.ts";
75
import * as MobileTelemetry from "./mobileTelemetry/MobileTelemetry.ts";
76
76
-const layerWebcrypto = Layer.mergeAll(SecureRandom.layerWebCrypto, Digest.layerWebCrypto);
77
+const layerWebcrypto = Layer.mergeAll(Digest.layerWebCrypto, Signature.layerWebCrypto).pipe(
78
+ Layer.provideMerge(SecureRandom.layerWebCrypto),
79
+);
80
81
const layerHttpPlatformNotSupported = Layer.succeed(HttpPlatform.HttpPlatform, {
82
platform: "web",
packages/client-runtime/src/relay/discovery.ts
+8
-10
@@ -105,15 +105,13 @@ function validateStatus(
105
return Effect.succeed(status);
106
}
107
108
-function relayAccountId(clerkToken: string): Option.Option<string> {
109
- try {
110
- return Option.fromNullishOr(decodeRelayJwt(clerkToken).sub).pipe(
111
- Option.filter((subject) => subject.length > 0),
112
- );
113
- } catch {
114
- return Option.none();
115
- }
116
-}
108
+const relayAccountId = Effect.fn("clientRuntime.discovery.relayAccountId")(function* (
109
+ clerkToken: string,
110
+) {
111
+ const claims = yield* decodeRelayJwt(clerkToken).pipe(Effect.option);
112
+ const sub = Option.isSome(claims) ? claims.value.sub : undefined;
113
+ return typeof sub === "string" && sub.length > 0 ? Option.some(sub) : Option.none<string>();
114
+});
115
116
/** @public */
117
export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
@@ -258,7 +256,7 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
256
if ((yield* Ref.get(accountGeneration)) !== generation) {
257
return;
258
}
261
- const accountId = relayAccountId(clerkToken);
259
+ const accountId = yield* relayAccountId(clerkToken);
260
const previousAccountId = yield* Ref.get(activeAccountId);
261
if (
262
Option.isSome(previousAccountId) &&
packages/client-runtime/src/relay/managedRelay.test.ts
+1
-1
@@ -36,7 +36,7 @@ function layerManagedRelayTest(
36
function clerkToken(subject: string, nonce: string): string {
37
const encode = (value: unknown) =>
38
btoa(JSON.stringify(value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
39
- return `${encode({ alg: "none" })}.${encode({ sub: subject, nonce })}.signature`;
39
+ return `${encode({ alg: "RS256" })}.${encode({ sub: subject, nonce })}.c2lnbmF0dXJl`;
40
}
41
42
describe("ManagedRelayClient", () => {
packages/client-runtime/src/relay/managedRelay.ts
+8
-10
@@ -408,15 +408,13 @@ function tokenMatches(
408
);
409
}
410
411
-function relayAccountId(clerkToken: string): Option.Option<string> {
412
- try {
413
- return Option.fromNullishOr(decodeRelayJwt(clerkToken).sub).pipe(
414
- Option.filter((subject) => subject.length > 0),
415
- );
416
- } catch {
417
- return Option.none();
418
- }
419
-}
411
+const relayAccountId = Effect.fn("clientRuntime.managedRelay.relayAccountId")(function* (
412
+ clerkToken: string,
413
+) {
414
+ const claims = yield* decodeRelayJwt(clerkToken).pipe(Effect.option);
415
+ const sub = Option.isSome(claims) ? claims.value.sub : undefined;
416
+ return typeof sub === "string" && sub.length > 0 ? Option.some(sub) : Option.none<string>();
417
+});
418
419
function bearerHeaders(clerkToken: string) {
420
return { authorization: `Bearer ${clerkToken}` };
@@ -564,7 +562,7 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* (
562
"relay.scopes": input.scopes.join(" "),
563
});
564
const nowMillis = yield* Clock.currentTimeMillis;
567
- const accountId = relayAccountId(input.clerkToken);
565
+ const accountId = yield* relayAccountId(input.clerkToken);
566
if (Option.isNone(accountId)) {
567
yield* Effect.annotateCurrentSpan({
568
"relay.token_cache.result": "bypass",
packages/client-runtime/src/relay/managedRelayState.test.ts
+1
-1
@@ -96,7 +96,7 @@ function setSession() {
96
function clerkToken(expiresAtSeconds: number): string {
97
const encode = (value: unknown) =>
98
btoa(JSON.stringify(value)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
99
- return `${encode({ alg: "none" })}.${encode({ exp: expiresAtSeconds })}.signature`;
99
+ return `${encode({ alg: "RS256" })}.${encode({ exp: expiresAtSeconds })}.c2lnbmF0dXJl`;
100
}
101
102
describe("createManagedRelayQueryManager", () => {
packages/client-runtime/src/relay/managedRelayState.ts
+10
-9
@@ -85,15 +85,16 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): Mana
85
cachedToken = null;
86
return null;
87
}
88
- try {
89
- const expiresAtSeconds = decodeRelayJwt(token).exp;
90
- cachedToken =
91
- typeof expiresAtSeconds === "number"
92
- ? { token, expiresAtMillis: expiresAtSeconds * 1_000 }
93
- : null;
94
- } catch {
95
- cachedToken = null;
96
- }
88
+ const expiresAtSeconds = Effect.runSync(
89
+ decodeRelayJwt(token).pipe(
90
+ Effect.map((claims) => claims.exp),
91
+ Effect.orElseSucceed(() => undefined),
92
+ ),
93
+ );
94
+ cachedToken =
95
+ typeof expiresAtSeconds === "number"
96
+ ? { token, expiresAtMillis: expiresAtSeconds * 1_000 }
97
+ : null;
98
return token;
99
});
100
pendingToken = operation;
packages/shared/package.json
-1
@@ -534,7 +534,6 @@
534
"@t3tools/contracts": "workspace:*",
535
"effect": "catalog:",
536
"ffi-rs": "1.3.2",
537
- "jose": "catalog:",
537
"mdast-util-directive": "catalog:",
538
"mdast-util-to-hast": "^13.2.1",
539
"micromark-extension-directive": "catalog:",
packages/shared/src/relayJwt.test.ts
+45
-10
@@ -1,16 +1,51 @@
1
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2
import { describe, expect, it } from "@effect/vitest";
3
+import * as Effect from "effect/Effect";
4
+import * as Jwk from "effect/jose/Jwk";
5
+import * as Redacted from "effect/Redacted";
6
+import * as Schema from "effect/Schema";
7
+import * as TestClock from "effect/testing/TestClock";
8
3
-import { RelayJwtError } from "./relayJwt.ts";
9
+import { decodeRelayJwt, RelayJwtError, signRelayJwt, verifyRelayJwt } from "./relayJwt.ts";
10
+
11
+const Claims = Schema.Struct({ sub: Schema.String });
12
+
13
+const keyPair = Effect.gen(function* () {
14
+ const pair = yield* Jwk.generateKeyPair({ algorithm: "EdDSA" });
15
+ const publicKey = yield* Jwk.importPublic(pair.publicKey, "EdDSA").pipe(
16
+ Effect.flatMap((key) => Jwk.exportSpki(key, { format: "pem" })),
17
+ );
18
+ const privateKey = yield* Jwk.importPrivate(pair.privateKey, "EdDSA").pipe(
19
+ Effect.flatMap((key) => Jwk.exportPkcs8(key, { format: "pem" })),
20
+ );
21
+ return { publicKey, privateKey: Redacted.value(privateKey) };
22
+});
23
24
describe("relayJwt", () => {
6
- it("extracts stable diagnostic codes without copying cause text into the error message", () => {
7
- const error = new RelayJwtError({
8
- operation: "verify",
9
- typ: "test+jwt",
10
- cause: { code: "ERR_JWT_EXPIRED", message: "sensitive library detail" },
11
- });
25
+ it.effect("verifies against the ambient clock and reports claim diagnostics", () =>
26
+ Effect.gen(function* () {
27
+ yield* TestClock.setTime(1_000_000);
28
+ const keys = yield* keyPair;
29
+ const token = yield* signRelayJwt({
30
+ privateKey: keys.privateKey,
31
+ typ: "test+jwt",
32
+ payload: { sub: "user", iss: "relay", aud: "env", iat: 1_000, exp: 1_100 },
33
+ });
34
+ const verify = verifyRelayJwt(Claims, {
35
+ publicKey: keys.publicKey,
36
+ token,
37
+ typ: "test+jwt",
38
+ issuer: "relay",
39
+ audience: "env",
40
+ });
41
+
42
+ expect(yield* verify).toEqual({ sub: "user" });
43
+ expect((yield* decodeRelayJwt(token)).sub).toBe("user");
44
13
- expect(RelayJwtError.diagnosticCode(error)).toBe("ERR_JWT_EXPIRED");
14
- expect(error.message).not.toContain("sensitive library detail");
15
- });
45
+ yield* TestClock.adjust("161 seconds");
46
+ const error = yield* Effect.flip(verify);
47
+ expect(RelayJwtError.diagnosticCode(error)).toBe("ClaimValidationFailed.exp.expired");
48
+ expect(error.message).toBe('Failed to verify relay JWT of type "test+jwt".');
49
+ }).pipe(Effect.provide(NodeCrypto.layerSignature)),
50
+ );
51
});
packages/shared/src/relayJwt.ts
+70
-59
@@ -1,7 +1,11 @@
1
-import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT, type JWTPayload } from "jose";
2
-import * as DateTime from "effect/DateTime";
1
+import type * as Signature from "effect/crypto/Signature";
2
+import type * as Duration from "effect/Duration";
3
import * as Effect from "effect/Effect";
4
-import * as Predicate from "effect/Predicate";
4
+import * as JoseError from "effect/jose/JoseError";
5
+import * as Jwk from "effect/jose/Jwk";
6
+import * as Jws from "effect/jose/Jws";
7
+import * as Jwt from "effect/jose/Jwt";
8
+import * as Redacted from "effect/Redacted";
9
import * as Schema from "effect/Schema";
10
11
export const RELAY_LINK_PROOF_TYP = "t3-env-link+jwt";
@@ -15,88 +19,95 @@ export const RELAY_HOOK_DELIVERY_TYP = "t3-relay-hook-delivery+jwt";
19
export const RELAY_HOOK_DELIVERY_HEADER = "x-t3-relay-delivery";
20
21
export class RelayJwtError extends Schema.TaggedError<RelayJwtError>()("RelayJwtError", {
18
- operation: Schema.Literals(["sign", "verify"]),
19
- typ: Schema.String,
22
+ operation: Schema.Literals(["sign", "verify", "decode"]),
23
+ typ: Schema.optional(Schema.String),
24
issuer: Schema.optional(Schema.String),
25
audience: Schema.optional(Schema.String),
26
cause: Schema.Defect(),
27
}) {
28
override get message(): string {
25
- return `Failed to ${this.operation} relay JWT of type "${this.typ}".`;
29
+ return this.typ === undefined
30
+ ? `Failed to ${this.operation} relay JWT.`
31
+ : `Failed to ${this.operation} relay JWT of type "${this.typ}".`;
32
}
33
34
static diagnosticCode(error: RelayJwtError): string {
29
- if (
30
- Predicate.isObject(error.cause) &&
31
- Predicate.hasProperty(error.cause, "code") &&
32
- Predicate.isString(error.cause.code) &&
33
- error.cause.code.length > 0
34
- ) {
35
- return error.cause.code;
35
+ if (JoseError.isJoseError(error.cause)) {
36
+ const reason = error.cause.reason;
37
+ return reason._tag === "ClaimValidationFailed"
38
+ ? `${reason._tag}.${reason.claim}.${reason.reason}`
39
+ : reason._tag;
40
}
37
-
38
- return error.cause instanceof Error && error.cause.name ? error.cause.name : "unknown";
41
+ return Schema.isSchemaError(error.cause) ? "SchemaError" : "unknown";
42
}
43
}
44
45
+export type RelayJwtClaims = Readonly<Record<string, Schema.Json>>;
46
+
47
export function normalizeRelayIssuer(value: string): string {
48
return value.trim().replace(/\/+$/gu, "");
49
}
50
46
-export function decodeRelayJwt(token: string): JWTPayload {
47
- return decodeJwt(token);
48
-}
51
+/** Reads claims without verifying them. Never authorize on the result. */
52
+export const decodeRelayJwt = Effect.fn("relayJwt.decode")(function* (
53
+ token: string,
54
+): Effect.fn.Return<RelayJwtClaims, RelayJwtError> {
55
+ const unverified = yield* Jwt.decodeUnverified(token).pipe(
56
+ Effect.mapError((cause) => new RelayJwtError({ operation: "decode", cause })),
57
+ );
58
+ return unverified.claims;
59
+});
60
61
function normalizePem(value: string): string {
62
return value.replace(/\\n/gu, "\n").trim();
63
}
64
54
-export function signRelayJwt(input: {
65
+export const signRelayJwt = Effect.fn("relayJwt.sign")(function* (input: {
66
readonly privateKey: string;
67
readonly typ: string;
57
- readonly payload: JWTPayload;
58
-}): Effect.Effect<string, RelayJwtError> {
59
- return Effect.tryPromise({
60
- try: async () => {
61
- const key = await importPKCS8(normalizePem(input.privateKey), "EdDSA");
62
- return new SignJWT(input.payload)
63
- .setProtectedHeader({ alg: "EdDSA", typ: input.typ })
64
- .sign(key);
65
- },
66
- catch: (cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause }),
67
- });
68
-}
68
+ readonly payload: Readonly<Record<string, unknown>>;
69
+}): Effect.fn.Return<string, RelayJwtError, Signature.Signature> {
70
+ const token = yield* Jwk.importPkcs8(Redacted.make(normalizePem(input.privateKey)), "EdDSA").pipe(
71
+ Effect.flatMap((key) =>
72
+ Jws.sign(new TextEncoder().encode(JSON.stringify(input.payload)), key, { typ: input.typ }),
73
+ ),
74
+ Effect.mapError((cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause })),
75
+ );
76
+ return Redacted.value(token);
77
+});
78
70
-export function verifyRelayJwt(input: {
71
- readonly publicKey: string;
72
- readonly token: string;
73
- readonly typ: string;
74
- readonly issuer: string;
75
- readonly audience: string;
76
- readonly nowEpochSeconds: number;
77
- readonly maxTokenAge?: string | number;
78
-}): Effect.Effect<JWTPayload, RelayJwtError> {
79
- return Effect.tryPromise({
80
- try: async () => {
81
- const key = await importSPKI(normalizePem(input.publicKey), "EdDSA");
82
- const verified = await jwtVerify(input.token, key, {
83
- algorithms: ["EdDSA"],
79
+/** Verifies an EdDSA relay JWT against the ambient `Clock` and decodes its claims. */
80
+export const verifyRelayJwt = Effect.fn("relayJwt.verify")(function* <A>(
81
+ schema: Schema.ConstraintDecoder<A>,
82
+ input: {
83
+ readonly publicKey: string;
84
+ readonly token: string;
85
+ readonly typ: string;
86
+ readonly issuer: string;
87
+ readonly audience: string;
88
+ readonly maxTokenAge?: Duration.Input;
89
+ },
90
+): Effect.fn.Return<A, RelayJwtError, Signature.Signature> {
91
+ const verified = yield* Jwk.importSpki(normalizePem(input.publicKey), "EdDSA").pipe(
92
+ Effect.flatMap((key) =>
93
+ Jwt.verify(schema, input.token, key, {
94
typ: input.typ,
95
issuer: input.issuer,
96
audience: input.audience,
97
maxTokenAge: input.maxTokenAge ?? "5 minutes",
88
- clockTolerance: 60,
89
- currentDate: DateTime.toDate(DateTime.makeUnsafe(input.nowEpochSeconds * 1_000)),
90
- });
91
- return verified.payload;
92
- },
93
- catch: (cause) =>
94
- new RelayJwtError({
95
- operation: "verify",
96
- typ: input.typ,
97
- issuer: input.issuer,
98
- audience: input.audience,
99
- cause,
98
+ clockTolerance: "60 seconds",
99
}),
101
- });
102
-}
100
+ ),
101
+ Effect.mapError(
102
+ (cause) =>
103
+ new RelayJwtError({
104
+ operation: "verify",
105
+ typ: input.typ,
106
+ issuer: input.issuer,
107
+ audience: input.audience,
108
+ cause,
109
+ }),
110
+ ),
111
+ );
112
+ return verified.claims;
113
+});
pnpm-lock.yaml
-9
@@ -909,9 +909,6 @@ importers:
909
ffi-rs:
910
specifier: 1.3.2
911
version: 1.3.2
912
- jose:
913
- specifier: 'catalog:'
914
- version: 6.2.2
912
node-pty:
913
specifier: 1.2.0-beta.15
914
version: 1.2.0-beta.15(patch_hash=f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651)
@@ -1165,9 +1162,6 @@ importers:
1162
html-url-attributes:
1163
specifier: ^3.0.1
1164
version: 3.0.1
1168
- jose:
1169
- specifier: 'catalog:'
1170
- version: 6.2.2
1165
jsonc-parser:
1166
specifier: 3.3.1
1167
version: 3.3.1
@@ -2048,9 +2042,6 @@ importers:
2042
ffi-rs:
2043
specifier: 1.3.2
2044
version: 1.3.2
2051
- jose:
2052
- specifier: 'catalog:'
2053
- version: 6.2.2
2045
mdast-util-directive:
2046
specifier: 'catalog:'
2047
version: 3.1.0(supports-color@8.1.1)