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: hold relay signing keys in EnvironmentSigningKey and CloudMintSigner (#30529)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 4, 2026 at 10:35 UTC
33ba7bf5ef098cd7c27d9cf44b79e2b06c020e6a
20 files changed
+384
-189
apps/server/src/cloud/CloudLink.lifecycle.test.ts
+7
-1
@@ -13,6 +13,7 @@ import { HttpClient, HttpClientResponse, HttpServer, type HttpClientRequest } fr
13
import * as NetAddress from "effect/net/NetAddress";
14
15
import { EnvironmentId } from "@t3tools/contracts";
16
+import * as EnvironmentKeys from "./environmentKeys.ts";
17
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
18
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
19
import * as ServerConfigModule from "../config.ts";
@@ -161,7 +162,12 @@ describe("releaseManagedTunnelOnShutdown", () => {
162
(harness: ReleaseHarness) =>
163
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
164
effect.pipe(
164
- Effect.provide(CloudLink.layer.pipe(Layer.provide(ManagedPolicy.layerTest()))),
165
+ Effect.provide(
166
+ CloudLink.layer.pipe(
167
+ Layer.provide(EnvironmentKeys.layer),
168
+ Layer.provide(ManagedPolicy.layerTest()),
169
+ ),
170
+ ),
171
Effect.provideService(
172
ConnectReachability.ConnectReachability,
173
ConnectReachability.ConnectReachability.of({
apps/server/src/cloud/CloudLink.test.ts
+17
-2
@@ -10,6 +10,7 @@ import * as NetAddress from "effect/net/NetAddress";
10
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
11
import * as NodeServices from "@effect/platform-node/NodeServices";
12
13
+import * as EnvironmentKeys from "./environmentKeys.ts";
14
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
15
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
16
import * as ServerConfig from "../config.ts";
@@ -119,7 +120,13 @@ const withService = <A, E>(
120
const link = yield* CloudLink.CloudLink;
121
return yield* body({ preferences: { update: link.updatePreferences }, stored, relayCalls });
122
}).pipe(
122
- Effect.provide(CloudLink.layer.pipe(Layer.provide(layerDependencies))),
123
+ Effect.provide(
124
+ CloudLink.layer.pipe(
125
+ // These tests never sign proofs; the mocked secret store cannot create a key pair.
126
+ Layer.provide(Layer.mock(EnvironmentKeys.EnvironmentSigningKey)({ publicKey: "" })),
127
+ Layer.provide(layerDependencies),
128
+ ),
129
+ ),
130
Effect.provideService(FetchHttpClient.Fetch, fetch),
131
);
132
});
@@ -301,6 +308,14 @@ it.effect("unlinks on startup and refuses to link when the policy turns Connect
308
const mintError = yield* link.mintCredential({} as never).pipe(Effect.flip);
309
assert.equal(applyError.message, "Example Corp's policy does not allow T3 Connect.");
310
assert.equal(mintError._tag, "ManagedPolicyRefusedError");
304
- }).pipe(Effect.provide(CloudLink.layer.pipe(Layer.provide(layerDependencies))));
311
+ }).pipe(
312
+ Effect.provide(
313
+ CloudLink.layer.pipe(
314
+ // These tests never sign proofs; the mocked secret store cannot create a key pair.
315
+ Layer.provide(Layer.mock(EnvironmentKeys.EnvironmentSigningKey)({ publicKey: "" })),
316
+ Layer.provide(layerDependencies),
317
+ ),
318
+ ),
319
+ );
320
}),
321
);
apps/server/src/cloud/CloudLink.ts
+52
-64
@@ -36,7 +36,6 @@ import {
36
RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
37
RELAY_MINT_REQUEST_TYP,
38
RELAY_MINT_RESPONSE_TYP,
39
- signRelayJwt,
39
verifyRelayJwt,
40
} from "@t3tools/shared/relayJwt";
41
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
@@ -95,7 +94,7 @@ import {
94
RELAY_ISSUER_SECRET,
95
RELAY_URL_SECRET,
96
} from "./config.ts";
98
-import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
97
+import { EnvironmentSigningKey } from "./environmentKeys.ts";
98
import * as ConnectReachability from "./ConnectReachability.ts";
99
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
100
import * as ManagedLimits from "../policy/managedLimits.ts";
@@ -525,6 +524,7 @@ const make = Effect.gen(function* () {
524
const awarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
525
const random = yield* SecureRandom.SecureRandom;
526
const signature = yield* Signature.Signature;
527
+ const signingKey = yield* EnvironmentSigningKey;
528
const config = yield* ServerConfig.ServerConfig;
529
const fileSystem = yield* FileSystem.FileSystem;
530
const path = yield* Path.Path;
@@ -581,9 +581,6 @@ const make = Effect.gen(function* () {
581
requestUrl: string,
582
allowNonLoopbackRequestHost = false,
583
) {
584
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
585
- Effect.provideService(Signature.Signature, signature),
586
- );
584
if (
585
!isSupportedLinkProviderKind(request) ||
586
!isAllowedEndpointOrigin({
@@ -608,24 +605,24 @@ const make = Effect.gen(function* () {
605
challenge: request.challenge,
606
descriptor,
607
environmentId: descriptor.environmentId,
611
- environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),
608
+ environmentPublicKey: normalizePemForSignedPayload(signingKey.publicKey),
609
endpoint: request.endpoint,
610
origin: request.origin,
611
scopes: linkProofScopes(request),
612
} satisfies RelayEnvironmentLinkProofPayload;
616
- return yield* signRelayJwt({
617
- privateKey: keyPair.privateKey,
618
- typ: RELAY_LINK_PROOF_TYP,
619
- payload,
620
- }).pipe(
621
- Effect.provideService(Signature.Signature, signature),
622
- Effect.mapError(
623
- (cause) =>
624
- new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
625
- cause,
626
- }),
627
- ),
628
- );
613
+ return yield* signingKey
614
+ .sign({
615
+ typ: RELAY_LINK_PROOF_TYP,
616
+ payload,
617
+ })
618
+ .pipe(
619
+ Effect.mapError(
620
+ (cause) =>
621
+ new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
622
+ cause,
623
+ }),
624
+ ),
625
+ );
626
});
627
628
const linkProof = Effect.fn("environment.cloud.linkProof")(
@@ -925,9 +922,6 @@ const make = Effect.gen(function* () {
922
const makeManagedTunnelRecoveryProof = Effect.fn(
923
"environment.cloud.makeManagedTunnelRecoveryProof",
924
)(function* (input: ManagedTunnelRecoveryProofInput) {
928
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
929
- Effect.provideService(Signature.Signature, signature),
930
- );
925
const configuredIssuer = yield* secrets.get(RELAY_ISSUER_SECRET);
926
const now = yield* DateTime.now;
927
const issuedAt = Math.floor(now.epochMilliseconds / 1_000);
@@ -953,16 +947,16 @@ const make = Effect.gen(function* () {
947
}
948
: { ...claims, action: "recover" as const, origin: input.origin };
949
956
- return yield* signRelayJwt({
957
- privateKey: keyPair.privateKey,
958
- typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
959
- payload,
960
- }).pipe(
961
- Effect.provideService(Signature.Signature, signature),
962
- Effect.mapError(
963
- (cause) => new CloudLinkInternalError({ operation: "sign-recovery-proof", cause }),
964
- ),
965
- );
950
+ return yield* signingKey
951
+ .sign({
952
+ typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
953
+ payload,
954
+ })
955
+ .pipe(
956
+ Effect.mapError(
957
+ (cause) => new CloudLinkInternalError({ operation: "sign-recovery-proof", cause }),
958
+ ),
959
+ );
960
});
961
962
/** Keep credentials: clock skew can cause 401s. A relink during the request returns false without marking; accepted registration clears the mark. */
@@ -1481,9 +1475,6 @@ const make = Effect.gen(function* () {
1475
return yield* new CloudLinkProofReplayedError({ request: "health" });
1476
}
1477
1484
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
1485
- Effect.provideService(Signature.Signature, signature),
1486
- );
1478
const descriptor = yield* environment.getDescriptor;
1479
const responseExpiresAt = DateTime.add(now, { minutes: 5 });
1480
const responsePayload = {
@@ -1499,19 +1490,19 @@ const make = Effect.gen(function* () {
1490
descriptor,
1491
checkedAt: DateTime.formatIso(now),
1492
} satisfies RelayEnvironmentHealthResponseProofPayload;
1502
- const responseProof = yield* signRelayJwt({
1503
- privateKey: keyPair.privateKey,
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({
1511
- cause,
1512
- }),
1513
- ),
1514
- );
1493
+ const responseProof = yield* signingKey
1494
+ .sign({
1495
+ typ: RELAY_HEALTH_RESPONSE_TYP,
1496
+ payload: responsePayload,
1497
+ })
1498
+ .pipe(
1499
+ Effect.mapError(
1500
+ (cause) =>
1501
+ new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({
1502
+ cause,
1503
+ }),
1504
+ ),
1505
+ );
1506
return {
1507
environmentId,
1508
status: "online",
@@ -1587,9 +1578,6 @@ const make = Effect.gen(function* () {
1578
return yield* new CloudLinkProofReplayedError({ request: "mint" });
1579
}
1580
1590
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
1591
- Effect.provideService(Signature.Signature, signature),
1592
- );
1581
const issued = yield* environmentAuth.createPairingLink({
1582
scopes: AuthStandardClientScopes,
1583
subject: "cloud-connect",
@@ -1609,19 +1597,19 @@ const make = Effect.gen(function* () {
1597
requestNonce: proof.nonce,
1598
credential: issued.credential,
1599
} satisfies RelayEnvironmentMintResponseProofPayload;
1612
- const responseProof = yield* signRelayJwt({
1613
- privateKey: keyPair.privateKey,
1614
- typ: RELAY_MINT_RESPONSE_TYP,
1615
- payload: responsePayload,
1616
- }).pipe(
1617
- Effect.provideService(Signature.Signature, signature),
1618
- Effect.mapError(
1619
- (cause) =>
1620
- new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
1621
- cause,
1622
- }),
1623
- ),
1624
- );
1600
+ const responseProof = yield* signingKey
1601
+ .sign({
1602
+ typ: RELAY_MINT_RESPONSE_TYP,
1603
+ payload: responsePayload,
1604
+ })
1605
+ .pipe(
1606
+ Effect.mapError(
1607
+ (cause) =>
1608
+ new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
1609
+ cause,
1610
+ }),
1611
+ ),
1612
+ );
1613
return {
1614
credential: issued.credential,
1615
expiresAt: DateTime.formatIso(issued.expiresAt),
apps/server/src/cloud/environmentKeys.test.ts
+11
-1
@@ -8,7 +8,11 @@ import * as PlatformError from "effect/PlatformError";
8
9
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
10
import * as ServerConfig from "../config.ts";
11
-import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
11
+import {
12
+ EnvironmentSigningKey,
13
+ getOrCreateEnvironmentKeyPairFromSecretStore,
14
+ layer,
15
+} from "./environmentKeys.ts";
16
17
const layerServerSecretStore = () =>
18
ServerSecretStore.layer.pipe(
@@ -48,6 +52,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
52
publicKey: "public",
53
});
54
assert.isTrue(Option.isSome(yield* secretStore.get("cloud-link-ed25519-key-pair")));
55
+
56
+ // Unparseable key material must fail signing, not the layer every server starts.
57
+ const signingKey = yield* EnvironmentSigningKey.pipe(Effect.provide(layer));
58
+ assert.strictEqual(signingKey.publicKey, "public");
59
+ const error = yield* Effect.flip(signingKey.sign({ typ: "test+jwt", payload: {} }));
60
+ assert.strictEqual(error._tag, "RelayJwtError");
61
}).pipe(Effect.provide(layerServerSecretStore())),
62
);
63
apps/server/src/cloud/environmentKeys.ts
+43
@@ -1,5 +1,9 @@
1
+import { importRelayPrivateKey, RelayJwtError, signRelayJwt } from "@t3tools/shared/relayJwt";
2
+import * as Context from "effect/Context";
3
+import * as Signature from "effect/crypto/Signature";
4
import * as Effect from "effect/Effect";
5
import * as Jwk from "effect/jose/Jwk";
6
+import * as Layer from "effect/Layer";
7
import * as Option from "effect/Option";
8
import * as Redacted from "effect/Redacted";
9
import * as Schema from "effect/Schema";
@@ -109,3 +113,42 @@ export const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function*
113
);
114
return yield* persistEnvironmentKeyPair(secrets, keyPair);
115
});
116
+
117
+/** The environment's Ed25519 relay signing key, loaded at startup and parsed on first use. */
118
+export class EnvironmentSigningKey extends Context.Service<
119
+ EnvironmentSigningKey,
120
+ {
121
+ /** SPKI PEM, as relays and linked clients receive it. */
122
+ readonly publicKey: string;
123
+ readonly sign: (input: {
124
+ readonly typ: string;
125
+ readonly payload: Readonly<Record<string, unknown>>;
126
+ }) => Effect.Effect<string, RelayJwtError>;
127
+ }
128
+>()("t3/cloud/environmentKeys/EnvironmentSigningKey") {}
129
+
130
+export const layer = Layer.effect(
131
+ EnvironmentSigningKey,
132
+ Effect.gen(function* () {
133
+ const secrets = yield* ServerSecretStore.ServerSecretStore;
134
+ const signature = yield* Signature.Signature;
135
+ const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
136
+ // Parsed lazily so corrupt key material fails Connect operations, not server startup.
137
+ let privateKey: Jwk.PrivateKey | undefined;
138
+ return EnvironmentSigningKey.of({
139
+ publicKey: keyPair.publicKey,
140
+ sign: Effect.fn("EnvironmentSigningKey.sign")(function* (input) {
141
+ if (privateKey === undefined) {
142
+ privateKey = yield* importRelayPrivateKey(keyPair.privateKey).pipe(
143
+ Effect.mapError(
144
+ (cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause }),
145
+ ),
146
+ );
147
+ }
148
+ return yield* signRelayJwt({ ...input, privateKey }).pipe(
149
+ Effect.provideService(Signature.Signature, signature),
150
+ );
151
+ }),
152
+ });
153
+ }),
154
+);
apps/server/src/cloud/http.test.ts
+2
@@ -25,6 +25,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
25
import * as NetAddress from "effect/net/NetAddress";
26
import { decodeRelayJwt, RELAY_LINK_PROOF_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";
27
28
+import * as EnvironmentKeys from "./environmentKeys.ts";
29
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
30
import * as AuthHttp from "../auth/http.ts";
31
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -78,6 +79,7 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(
79
Layer.provide([AuthHttp.layer, ConnectHttp.layer]),
80
Layer.provide(AuthHttp.layerAuthenticatedAuth),
81
Layer.provide(CloudLink.layer),
82
+ Layer.provide(EnvironmentKeys.layer),
83
Layer.provide(
84
Layer.mock(ConnectReachability.ConnectReachability)({ latest: Effect.succeedNone }),
85
),
apps/server/src/relay/AgentAwarenessRelay.test.ts
+2
@@ -28,6 +28,7 @@ import * as Stream from "effect/Stream";
28
import * as TestClock from "effect/testing/TestClock";
29
import * as FetchHttpClient from "effect/http/FetchHttpClient";
30
31
+import * as EnvironmentKeys from "../cloud/environmentKeys.ts";
32
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
33
import {
34
PUBLISH_AGENT_ACTIVITY_SECRET,
@@ -276,6 +277,7 @@ const makeTestRelay = Effect.fnUntraced(function* (
277
deletedAt: null,
278
};
279
const relay = yield* AgentAwarenessRelay.make.pipe(
280
+ Effect.provide(EnvironmentKeys.layer),
281
Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
282
Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
283
Effect.provideService(ServerEnvironment.ServerEnvironment, {
apps/server/src/relay/AgentAwarenessRelay.ts
+6
-17
@@ -16,15 +16,10 @@ import { projectThreadAwarenessV2 } from "@t3tools/shared/agentAwareness";
16
import { turnItemUpdateCanEndBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
17
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
18
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
19
-import {
20
- normalizeRelayIssuer,
21
- RELAY_ACTIVITY_PUBLISH_TYP,
22
- signRelayJwt,
23
-} from "@t3tools/shared/relayJwt";
19
+import { normalizeRelayIssuer, RELAY_ACTIVITY_PUBLISH_TYP } from "@t3tools/shared/relayJwt";
20
import * as Cause from "effect/Cause";
21
import * as Context from "effect/Context";
22
import * as SecureRandom from "effect/crypto/SecureRandom";
27
-import * as Signature from "effect/crypto/Signature";
23
import * as DateTime from "effect/DateTime";
24
import * as Effect from "effect/Effect";
25
import * as Fiber from "effect/Fiber";
@@ -47,7 +42,7 @@ import {
42
RELAY_ISSUER_SECRET,
43
RELAY_URL_SECRET,
44
} from "../cloud/config.ts";
50
-import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environmentKeys.ts";
45
+import { EnvironmentSigningKey } from "../cloud/environmentKeys.ts";
46
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
47
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
48
import * as ProjectService from "../project/ProjectService.ts";
@@ -249,7 +244,6 @@ function deliveryStats(
244
}
245
246
const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
252
- readonly privateKey: string;
247
readonly relayIssuer: string;
248
readonly environmentId: string;
249
readonly threadId: ThreadId;
@@ -269,11 +263,8 @@ const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
263
threadId: input.threadId,
264
state: input.state,
265
} satisfies RelayAgentActivityPublishProofPayload;
272
- return yield* signRelayJwt({
273
- privateKey: input.privateKey,
274
- typ: RELAY_ACTIVITY_PUBLISH_TYP,
275
- payload,
276
- });
266
+ const signingKey = yield* EnvironmentSigningKey;
267
+ return yield* signingKey.sign({ typ: RELAY_ACTIVITY_PUBLISH_TYP, payload });
268
});
269
270
function describeThreadShellForAwareness(
@@ -372,9 +363,8 @@ export const make = Effect.gen(function* () {
363
const threads = yield* ThreadManagement.ThreadManagementService;
364
const projects = yield* ProjectService.ProjectService;
365
const random = yield* SecureRandom.SecureRandom;
375
- const signature = yield* Signature.Signature;
366
+ const signingKey = yield* EnvironmentSigningKey;
367
const scope = yield* Effect.scope;
377
- const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
368
const startedAt = (yield* DateTime.now).epochMilliseconds;
369
const catchUpRequests = yield* Queue.dropping<void>(1);
370
const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
@@ -480,13 +470,12 @@ export const make = Effect.gen(function* () {
470
}
471
const relayClient = cachedRelayClient;
472
const proof = yield* makePublishProof({
483
- privateKey: cloudLinkKeyPair.privateKey,
473
relayIssuer: relayConfig.issuer,
474
environmentId,
475
threadId,
476
state: input.state,
477
jti: yield* random.uuidV4(),
489
- }).pipe(Effect.provideService(Signature.Signature, signature));
478
+ }).pipe(Effect.provideService(EnvironmentSigningKey, signingKey));
479
480
yield* Effect.logInfo("publishing agent activity for thread", {
481
environmentId,
apps/server/src/server.ts
+2
-1
@@ -1,6 +1,7 @@
1
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
2
import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
3
import * as Random from "effect/Random";
4
+import * as EnvironmentKeys from "./cloud/environmentKeys.ts";
5
import * as AssetSigner from "./assets/AssetSigner.ts";
6
import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
7
import * as StorageCleanup from "./storageCleanup.ts";
@@ -720,7 +721,7 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe(
721
Layer.provideMerge(CodexManagedTokenBroker.layer),
722
Layer.provideMerge(layerServerEnvironment),
723
Layer.provideMerge(layerAuth),
723
- Layer.provideMerge(AssetSigner.layer),
724
+ Layer.provideMerge(Layer.mergeAll(AssetSigner.layer, EnvironmentKeys.layer)),
725
Layer.provideMerge(ServerSecretStore.layer),
726
Layer.provideMerge(
727
Layer.mergeAll(
infra/relay/src/auth/CloudMintSigner.ts
new
+92
@@ -0,0 +1,92 @@
1
+import {
2
+ importRelayPrivateKey,
3
+ importRelayPublicKey,
4
+ RelayJwtError,
5
+ signRelayJwt,
6
+ verifyRelayJwt,
7
+} from "@t3tools/shared/relayJwt";
8
+import * as Context from "effect/Context";
9
+import * as Signature from "effect/crypto/Signature";
10
+import type * as Duration from "effect/Duration";
11
+import * as Effect from "effect/Effect";
12
+import * as Layer from "effect/Layer";
13
+import * as Redacted from "effect/Redacted";
14
+import type * as Schema from "effect/Schema";
15
+
16
+import * as RelayConfiguration from "../Config.ts";
17
+
18
+/** Signs and verifies relay-issued tokens with the cloud mint key pair. */
19
+export class CloudMintSigner extends Context.Service<
20
+ CloudMintSigner,
21
+ {
22
+ readonly sign: (input: {
23
+ readonly typ: string;
24
+ readonly payload: Readonly<Record<string, unknown>>;
25
+ }) => Effect.Effect<string, RelayJwtError>;
26
+ readonly verify: <A>(
27
+ schema: Schema.ConstraintDecoder<A>,
28
+ input: {
29
+ readonly token: string;
30
+ readonly typ: string;
31
+ readonly issuer: string;
32
+ readonly audience: string;
33
+ readonly maxTokenAge?: Duration.Input;
34
+ },
35
+ ) => Effect.Effect<A, RelayJwtError>;
36
+ }
37
+>()("t3code-relay/auth/CloudMintSigner") {}
38
+
39
+// Parsed on first use and kept; a failed parse is retried so a bad key fails requests, not boot.
40
+const cacheSuccess = <A, E>(load: Effect.Effect<A, E>) => {
41
+ let value: A | undefined;
42
+ return Effect.suspend(() =>
43
+ value !== undefined
44
+ ? Effect.succeed(value)
45
+ : Effect.tap(load, (loaded) =>
46
+ Effect.sync(() => {
47
+ value = loaded;
48
+ }),
49
+ ),
50
+ );
51
+};
52
+
53
+export const layer = Layer.effect(
54
+ CloudMintSigner,
55
+ Effect.gen(function* () {
56
+ const config = yield* RelayConfiguration.RelayConfiguration;
57
+ const signature = yield* Signature.Signature;
58
+ const privateKey = cacheSuccess(
59
+ importRelayPrivateKey(Redacted.value(config.cloudMintPrivateKey)),
60
+ );
61
+ const publicKey = cacheSuccess(importRelayPublicKey(config.cloudMintPublicKey));
62
+
63
+ return CloudMintSigner.of({
64
+ sign: Effect.fn("CloudMintSigner.sign")(function* (input) {
65
+ const key = yield* privateKey.pipe(
66
+ Effect.mapError(
67
+ (cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause }),
68
+ ),
69
+ );
70
+ return yield* signRelayJwt({ ...input, privateKey: key }).pipe(
71
+ Effect.provideService(Signature.Signature, signature),
72
+ );
73
+ }),
74
+ verify: Effect.fn("CloudMintSigner.verify")(function* (schema, input) {
75
+ return yield* publicKey.pipe(
76
+ Effect.mapError(
77
+ (cause) =>
78
+ new RelayJwtError({
79
+ operation: "verify",
80
+ typ: input.typ,
81
+ issuer: input.issuer,
82
+ audience: input.audience,
83
+ cause,
84
+ }),
85
+ ),
86
+ Effect.flatMap((key) => verifyRelayJwt(schema, { ...input, publicKey: key })),
87
+ Effect.provideService(Signature.Signature, signature),
88
+ );
89
+ }),
90
+ });
91
+ }),
92
+);
infra/relay/src/auth/RelayTokens.test.ts
+2
@@ -10,6 +10,7 @@ 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 CloudMintSigner from "./CloudMintSigner.ts";
14
import * as RelayConfiguration from "../Config.ts";
15
import * as RelayTokens from "./RelayTokens.ts";
16
@@ -38,6 +39,7 @@ const config = RelayConfiguration.RelayConfiguration.of({
39
});
40
41
const layer = RelayTokens.layer.pipe(
42
+ Layer.provide(CloudMintSigner.layer),
43
Layer.provide(RelayConfiguration.layer(config)),
44
Layer.provideMerge(Signature.layerWebCrypto),
45
Layer.provide(SecureRandom.layerWebCrypto),
infra/relay/src/auth/RelayTokens.ts
+50
-58
@@ -9,20 +9,14 @@ import {
9
type RelayEnvironmentLinkChallengeRequest,
10
} from "@t3tools/contracts/relay";
11
import { encodeOAuthScope, parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";
12
-import {
13
- normalizeRelayIssuer,
14
- RelayJwtError,
15
- signRelayJwt,
16
- verifyRelayJwt,
17
-} from "@t3tools/shared/relayJwt";
12
+import { normalizeRelayIssuer, RelayJwtError } from "@t3tools/shared/relayJwt";
13
import * as Context from "effect/Context";
19
-import * as Signature from "effect/crypto/Signature";
14
import * as Effect from "effect/Effect";
15
import * as Layer from "effect/Layer";
22
-import * as Redacted from "effect/Redacted";
16
import * as Schema from "effect/Schema";
17
18
import * as RelayConfiguration from "../Config.ts";
19
+import * as CloudMintSigner from "./CloudMintSigner.ts";
20
21
const LINK_CHALLENGE_TYP = "t3-link-challenge+jwt";
22
const ACCESS_TOKEN_TYP = "t3-relay-dpop-access+jwt";
@@ -114,13 +108,12 @@ export class RelayTokens extends Context.Service<
108
const make = Effect.gen(function* () {
109
const config = yield* RelayConfiguration.RelayConfiguration;
110
const issuer = normalizeRelayIssuer(config.relayIssuer);
117
- const signature = yield* Signature.Signature;
111
+ const mint = yield* CloudMintSigner.CloudMintSigner;
112
113
const issueLinkChallenge: RelayTokens["Service"]["issueLinkChallenge"] = Effect.fn(
114
"relay.tokens.issue_link_challenge",
115
)(function* (input) {
122
- return yield* signRelayJwt({
123
- privateKey: Redacted.value(config.cloudMintPrivateKey),
116
+ return yield* mint.sign({
117
typ: LINK_CHALLENGE_TYP,
118
payload: {
119
kind: LINK_CHALLENGE_KIND,
@@ -132,40 +125,39 @@ const make = Effect.gen(function* () {
125
exp: input.expiresAtEpochSeconds,
126
...input.request,
127
},
135
- }).pipe(Effect.provideService(Signature.Signature, signature));
128
+ });
129
});
130
131
const verifyLinkChallenge: RelayTokens["Service"]["verifyLinkChallenge"] = Effect.fn(
132
"relay.tokens.verify_link_challenge",
133
)((input) =>
141
- verifyRelayJwt(LinkChallengeClaims, {
142
- publicKey: config.cloudMintPublicKey,
143
- token: input.token,
144
- typ: LINK_CHALLENGE_TYP,
145
- issuer,
146
- audience: issuer,
147
- }).pipe(
148
- Effect.provideService(Signature.Signature, signature),
149
- Effect.map((claims) => {
150
- if (
151
- claims.sub !== input.userId ||
152
- (input.request.notificationsEnabled && claims.notificationsEnabled !== true) ||
153
- (input.request.liveActivitiesEnabled && claims.liveActivitiesEnabled !== true) ||
154
- (input.request.managedTunnelsEnabled && claims.managedTunnelsEnabled !== true)
155
- ) {
156
- return null;
157
- }
158
- return claims;
159
- }),
160
- Effect.orElseSucceed(() => null),
161
- ),
134
+ mint
135
+ .verify(LinkChallengeClaims, {
136
+ token: input.token,
137
+ typ: LINK_CHALLENGE_TYP,
138
+ issuer,
139
+ audience: issuer,
140
+ })
141
+ .pipe(
142
+ Effect.map((claims) => {
143
+ if (
144
+ claims.sub !== input.userId ||
145
+ (input.request.notificationsEnabled && claims.notificationsEnabled !== true) ||
146
+ (input.request.liveActivitiesEnabled && claims.liveActivitiesEnabled !== true) ||
147
+ (input.request.managedTunnelsEnabled && claims.managedTunnelsEnabled !== true)
148
+ ) {
149
+ return null;
150
+ }
151
+ return claims;
152
+ }),
153
+ Effect.orElseSucceed(() => null),
154
+ ),
155
);
156
157
const issueDpopAccessToken: RelayTokens["Service"]["issueDpopAccessToken"] = Effect.fn(
158
"relay.tokens.issue_dpop_access_token",
159
)(function* (input) {
167
- return yield* signRelayJwt({
168
- privateKey: Redacted.value(config.cloudMintPrivateKey),
160
+ return yield* mint.sign({
161
typ: ACCESS_TOKEN_TYP,
162
payload: {
163
iss: issuer,
@@ -178,36 +170,36 @@ const make = Effect.gen(function* () {
170
scope: encodeOAuthScope(input.scopes),
171
cnf: { jkt: input.proofKeyThumbprint },
172
},
181
- }).pipe(Effect.provideService(Signature.Signature, signature));
173
+ });
174
});
175
176
const verifyDpopAccessToken: RelayTokens["Service"]["verifyDpopAccessToken"] = Effect.fn(
177
"relay.tokens.verify_dpop_access_token",
178
)((input) =>
187
- verifyRelayJwt(RelayDpopAccessTokenClaims, {
188
- publicKey: config.cloudMintPublicKey,
189
- token: input.token,
190
- typ: ACCESS_TOKEN_TYP,
191
- issuer,
192
- audience: issuer,
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),
179
+ mint
180
+ .verify(RelayDpopAccessTokenClaims, {
181
+ token: input.token,
182
+ typ: ACCESS_TOKEN_TYP,
183
+ issuer,
184
+ audience: issuer,
185
+ maxTokenAge: RELAY_DPOP_ACCESS_TOKEN_TTL,
186
+ })
187
+ .pipe(
188
+ Effect.tapError((error) =>
189
+ Effect.annotateCurrentSpan(
190
+ "relay.tokens.verification_failure",
191
+ RelayJwtError.diagnosticCode(error),
192
+ ),
193
),
194
+ Effect.map((claims): RelayDpopAccessTokenClaims | null => {
195
+ const scopes = resolveDpopAccessTokenScopes({
196
+ clientId: claims.client_id,
197
+ scope: claims.scope,
198
+ });
199
+ return scopes === null ? null : { ...claims, scope: scopes };
200
+ }),
201
+ Effect.orElseSucceed(() => null),
202
),
202
- Effect.map((claims): RelayDpopAccessTokenClaims | null => {
203
- const scopes = resolveDpopAccessTokenScopes({
204
- clientId: claims.client_id,
205
- scope: claims.scope,
206
- });
207
- return scopes === null ? null : { ...claims, scope: scopes };
208
- }),
209
- Effect.orElseSucceed(() => null),
210
- ),
203
);
204
205
return RelayTokens.of({
infra/relay/src/environments/EnvironmentConnector.test.ts
+2
@@ -23,6 +23,7 @@ import * as Schema from "effect/Schema";
23
import * as Tracer from "effect/Tracer";
24
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
25
26
+import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
27
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
28
import * as RelayConfiguration from "../Config.ts";
29
import * as EnvironmentConnector from "./EnvironmentConnector.ts";
@@ -162,6 +163,7 @@ function layerConnectorTest(
163
},
164
) {
165
return EnvironmentConnector.layer.pipe(
166
+ Layer.provide(CloudMintSigner.layer),
167
Layer.provide(NodeCryptoLayer.layer),
168
Layer.provide(Layer.succeed(EnvironmentLinks.EnvironmentLinks, options?.links ?? makeLinks())),
169
Layer.provide(
infra/relay/src/environments/EnvironmentConnector.ts
+32
-32
@@ -25,7 +25,6 @@ import {
25
RELAY_HEALTH_RESPONSE_TYP,
26
RELAY_MINT_REQUEST_TYP,
27
RELAY_MINT_RESPONSE_TYP,
28
- signRelayJwt,
28
verifyRelayJwt,
29
} from "@t3tools/shared/relayJwt";
30
import { stableStringify } from "@t3tools/shared/relaySigning";
@@ -37,7 +36,6 @@ import * as Duration from "effect/Duration";
36
import * as Effect from "effect/Effect";
37
import * as Layer from "effect/Layer";
38
import * as Option from "effect/Option";
40
-import * as Redacted from "effect/Redacted";
39
import * as Result from "effect/Result";
40
import * as Schema from "effect/Schema";
41
import * as FetchHttpClient from "effect/http/FetchHttpClient";
@@ -48,6 +46,7 @@ import { diagnoseEndpointFailure } from "./endpointFailure.ts";
46
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
47
import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
48
import * as RelayConfiguration from "../Config.ts";
49
+import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
50
import { isManagedEndpointHostname } from "../deploymentConfig.ts";
51
52
function environmentConnectNotAuthorizedReasonMessage(
@@ -376,6 +375,7 @@ const make = Effect.gen(function* () {
375
const httpClient = yield* HttpClient.HttpClient;
376
const random = yield* SecureRandom.SecureRandom;
377
const signature = yield* Signature.Signature;
378
+ const mint = yield* CloudMintSigner.CloudMintSigner;
379
const relayIssuer = normalizeRelayIssuer(settings.relayIssuer);
380
const makeEnvironmentClient = (httpBaseUrl: string) =>
381
makeEnvironmentHttpApiClient(httpBaseUrl).pipe(
@@ -463,21 +463,21 @@ const make = Effect.gen(function* () {
463
nonce,
464
scope: ["environment:status"],
465
} satisfies RelayCloudEnvironmentHealthProofPayload;
466
- const proof = yield* signRelayJwt({
467
- privateKey: Redacted.value(settings.cloudMintPrivateKey),
468
- typ: RELAY_HEALTH_REQUEST_TYP,
469
- payload,
470
- }).pipe(
471
- Effect.provideService(Signature.Signature, signature),
472
- Effect.mapError(
473
- (cause) =>
474
- new EnvironmentMintRequestFailed({
475
- environmentId: input.environmentId,
476
- operation: "status",
477
- cause,
478
- }),
479
- ),
480
- );
466
+ const proof = yield* mint
467
+ .sign({
468
+ typ: RELAY_HEALTH_REQUEST_TYP,
469
+ payload,
470
+ })
471
+ .pipe(
472
+ Effect.mapError(
473
+ (cause) =>
474
+ new EnvironmentMintRequestFailed({
475
+ environmentId: input.environmentId,
476
+ operation: "status",
477
+ cause,
478
+ }),
479
+ ),
480
+ );
481
const checkedAt = DateTime.formatIso(now);
482
const traceId = yield* currentTraceId;
483
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
@@ -629,21 +629,21 @@ const make = Effect.gen(function* () {
629
nonce,
630
scope: ["environment:connect"],
631
} satisfies RelayCloudMintCredentialProofPayload;
632
- const proof = yield* signRelayJwt({
633
- privateKey: Redacted.value(settings.cloudMintPrivateKey),
634
- typ: RELAY_MINT_REQUEST_TYP,
635
- payload,
636
- }).pipe(
637
- Effect.provideService(Signature.Signature, signature),
638
- Effect.mapError(
639
- (cause) =>
640
- new EnvironmentMintRequestFailed({
641
- environmentId: input.environmentId,
642
- operation: "connect",
643
- cause,
644
- }),
645
- ),
646
- );
632
+ const proof = yield* mint
633
+ .sign({
634
+ typ: RELAY_MINT_REQUEST_TYP,
635
+ payload,
636
+ })
637
+ .pipe(
638
+ Effect.mapError(
639
+ (cause) =>
640
+ new EnvironmentMintRequestFailed({
641
+ environmentId: input.environmentId,
642
+ operation: "connect",
643
+ cause,
644
+ }),
645
+ ),
646
+ );
647
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
648
const decoded = yield* environmentClient.connect
649
.t3MintCredential({ payload: { proof } })
infra/relay/src/environments/EnvironmentLinker.test.ts
+2
-1
@@ -14,6 +14,7 @@ import * as Redacted from "effect/Redacted";
14
import * as Result from "effect/Result";
15
import * as Schema from "effect/Schema";
16
17
+import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
18
import * as DpopProofs from "../auth/DpopProofs.ts";
19
import * as RelayTokens from "../auth/RelayTokens.ts";
20
import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
@@ -114,7 +115,7 @@ function layerTest(input?: {
115
readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"];
116
}) {
117
return EnvironmentLinker.layer.pipe(
117
- Layer.provideMerge(RelayTokens.layer),
118
+ Layer.provideMerge(RelayTokens.layer.pipe(Layer.provide(CloudMintSigner.layer))),
119
Layer.provide(
120
Layer.mergeAll(
121
RelayConfiguration.layer(config),
infra/relay/src/hooks/HookForwarder.test.ts
+2
@@ -22,6 +22,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
22
import * as HttpServerRequest from "effect/http/HttpServerRequest";
23
import * as HttpServerResponse from "effect/http/HttpServerResponse";
24
25
+import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
26
import * as RelayConfiguration from "../Config.ts";
27
import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
28
import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts";
@@ -107,6 +108,7 @@ function makeHarness(options: Harness = {}) {
108
));
109
const layerForwarder = HookForwarder.layer.pipe(
110
Layer.provideMerge(HeldHooks.layer),
111
+ Layer.provide(CloudMintSigner.layer),
112
Layer.provide(
113
Layer.mergeAll(
114
Layer.succeed(RelayConfiguration.RelayConfiguration, settings),
infra/relay/src/hooks/HookForwarder.ts
+4
-7
@@ -1,12 +1,10 @@
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";
4
import * as DateTime from "effect/DateTime";
5
import * as Effect from "effect/Effect";
6
import * as Layer from "effect/Layer";
7
import * as Option from "effect/Option";
9
-import * as Redacted from "effect/Redacted";
8
import * as Result from "effect/Result";
9
import * as Schema from "effect/Schema";
10
import * as Stream from "effect/Stream";
@@ -20,10 +18,10 @@ import {
18
normalizeRelayIssuer,
19
RELAY_HOOK_DELIVERY_HEADER,
20
RELAY_HOOK_DELIVERY_TYP,
23
- signRelayJwt,
21
} from "@t3tools/shared/relayJwt";
22
23
import * as RelayConfiguration from "../Config.ts";
24
+import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
25
import { MANAGED_ENDPOINT_KEY_PATTERN } from "../deploymentConfig.ts";
26
import * as HeldHooks from "./HeldHooks.ts";
27
import * as HookInbox from "./HookInbox.ts";
@@ -221,7 +219,7 @@ const make = Effect.gen(function* () {
219
const rateLimiter = yield* HookRateLimiter;
220
const inbox = yield* HookInbox.HookInbox;
221
const random = yield* SecureRandom.SecureRandom;
224
- const signature = yield* Signature.Signature;
222
+ const mint = yield* CloudMintSigner.CloudMintSigner;
223
224
const signDeliveryProof = Effect.fn("HookForwarder.signDeliveryProof")(
225
function* (input: {
@@ -232,8 +230,7 @@ const make = Effect.gen(function* () {
230
readonly jti: string;
231
}) {
232
const now = Math.floor((yield* Clock.currentTimeMillis) / 1_000);
235
- return yield* signRelayJwt({
236
- privateKey: Redacted.value(settings.cloudMintPrivateKey),
233
+ return yield* mint.sign({
234
typ: RELAY_HOOK_DELIVERY_TYP,
235
payload: {
236
iss: normalizeRelayIssuer(settings.relayIssuer),
@@ -247,7 +244,7 @@ const make = Effect.gen(function* () {
244
receivedAt: input.receivedAt,
245
hookId: input.hookId,
246
} satisfies RelayHookDeliveryProofPayload,
250
- }).pipe(Effect.provideService(Signature.Signature, signature));
247
+ });
248
},
249
(effect, _input) => effect.pipe(Effect.orDie),
250
);
infra/relay/src/worker.ts
+2
-1
@@ -28,6 +28,7 @@ import {
28
traceRelayHttpRequestWith,
29
withoutCapturedParentSpan,
30
} from "./http/Api.ts";
31
+import * as CloudMintSigner from "./auth/CloudMintSigner.ts";
32
import * as RelayHttpApi from "./http/Api.ts";
33
import { ManagedEndpointZone, RelayApiZone, RelayDeploymentConfig } from "./zone.ts";
34
import { RelayObservability } from "./observability.ts";
@@ -340,7 +341,7 @@ export const layer = Api.make(
341
),
342
Layer.provideMerge(Layer.mergeAll(LiveActivities.layer, T3ChatAccounts.layer)),
343
Layer.provideMerge(DeliveryAttempts.layer),
343
- Layer.provideMerge(RelayTokens.layer),
344
+ Layer.provideMerge(RelayTokens.layer.pipe(Layer.provideMerge(CloudMintSigner.layer))),
345
Layer.provideMerge(
346
RelayDb.RelayTransactions.layer.pipe(
347
Layer.provideMerge(Layer.succeed(RelayDb.RelayDb, db)),
packages/shared/src/relayJwt.test.ts
+31
@@ -1,7 +1,9 @@
1
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2
import { describe, expect, it } from "@effect/vitest";
3
+import * as Clock from "effect/Clock";
4
import * as Effect from "effect/Effect";
5
import * as Jwk from "effect/jose/Jwk";
6
+import * as Jws from "effect/jose/Jws";
7
import * as Redacted from "effect/Redacted";
8
import * as Schema from "effect/Schema";
9
import * as TestClock from "effect/testing/TestClock";
@@ -46,6 +48,35 @@ describe("relayJwt", () => {
48
const error = yield* Effect.flip(verify);
49
expect(RelayJwtError.diagnosticCode(error)).toBe("ClaimValidationFailed.exp.expired");
50
expect(error.message).toBe('Failed to verify relay JWT of type "test+jwt".');
51
+
52
+ const es256 = yield* Jwk.generateKeyPair({ algorithm: "ES256" });
53
+ const es256Private = yield* Jwk.importPrivate(es256.privateKey, "ES256");
54
+ const signWrong = yield* Effect.flip(
55
+ signRelayJwt({ privateKey: es256Private, typ: "test+jwt", payload: { sub: "user" } }),
56
+ );
57
+ expect(RelayJwtError.diagnosticCode(signWrong)).toBe("AlgorithmNotAllowed");
58
+ const es256Token = yield* Jws.sign(
59
+ new TextEncoder().encode(
60
+ JSON.stringify({
61
+ sub: "user",
62
+ iss: "relay",
63
+ aud: "env",
64
+ iat: Math.floor((yield* Clock.currentTimeMillis) / 1_000),
65
+ }),
66
+ ),
67
+ es256Private,
68
+ { typ: "test+jwt" },
69
+ );
70
+ const verifyWrong = yield* Effect.flip(
71
+ verifyRelayJwt(Claims, {
72
+ publicKey: yield* Jwk.importPublic(es256.publicKey, "ES256"),
73
+ token: Redacted.value(es256Token),
74
+ typ: "test+jwt",
75
+ issuer: "relay",
76
+ audience: "env",
77
+ }),
78
+ );
79
+ expect(RelayJwtError.diagnosticCode(verifyWrong)).toBe("AlgorithmNotAllowed");
80
}).pipe(Effect.provide(NodeCrypto.layerSignature)),
81
);
82
});
packages/shared/src/relayJwt.ts
+23
-4
@@ -62,12 +62,28 @@ function normalizePem(value: string): string {
62
return value.replace(/\\n/gu, "\n").trim();
63
}
64
65
+/** Parses a PKCS#8 PEM relay signing key once, for callers that sign repeatedly. */
66
+export const importRelayPrivateKey = (pem: string) =>
67
+ Jwk.importPkcs8(Redacted.make(normalizePem(pem)), "EdDSA");
68
+
69
+/** Parses an SPKI PEM relay verification key once, for callers that verify repeatedly. */
70
+export const importRelayPublicKey = (pem: string) => Jwk.importSpki(normalizePem(pem), "EdDSA");
71
+
72
+// A parsed key carries its own algorithm; relay JWTs are EdDSA only.
73
+const requireEdDsa = <K extends Jwk.PrivateKey | Jwk.PublicKey>(key: K) =>
74
+ key.algorithm === "EdDSA"
75
+ ? Effect.succeed(key)
76
+ : Effect.fail(new JoseError.JoseError({ reason: new JoseError.AlgorithmNotAllowed() }));
77
+
78
export const signRelayJwt = Effect.fn("relayJwt.sign")(function* (input: {
66
- readonly privateKey: string;
79
+ readonly privateKey: string | Jwk.PrivateKey;
80
readonly typ: string;
81
readonly payload: Readonly<Record<string, unknown>>;
82
}): Effect.fn.Return<string, RelayJwtError, Signature.Signature> {
70
- const token = yield* Jwk.importPkcs8(Redacted.make(normalizePem(input.privateKey)), "EdDSA").pipe(
83
+ const privateKey = input.privateKey;
84
+ const token = yield* (
85
+ typeof privateKey === "string" ? importRelayPrivateKey(privateKey) : requireEdDsa(privateKey)
86
+ ).pipe(
87
Effect.flatMap((key) =>
88
Jws.sign(new TextEncoder().encode(JSON.stringify(input.payload)), key, { typ: input.typ }),
89
),
@@ -80,7 +96,7 @@ export const signRelayJwt = Effect.fn("relayJwt.sign")(function* (input: {
96
export const verifyRelayJwt = Effect.fn("relayJwt.verify")(function* <A>(
97
schema: Schema.ConstraintDecoder<A>,
98
input: {
83
- readonly publicKey: string;
99
+ readonly publicKey: string | Jwk.PublicKey;
100
readonly token: string;
101
readonly typ: string;
102
readonly issuer: string;
@@ -88,7 +104,10 @@ export const verifyRelayJwt = Effect.fn("relayJwt.verify")(function* <A>(
104
readonly maxTokenAge?: Duration.Input;
105
},
106
): Effect.fn.Return<A, RelayJwtError, Signature.Signature> {
91
- const verified = yield* Jwk.importSpki(normalizePem(input.publicKey), "EdDSA").pipe(
107
+ const publicKey = input.publicKey;
108
+ const verified = yield* (
109
+ typeof publicKey === "string" ? importRelayPublicKey(publicKey) : requireEdDsa(publicKey)
110
+ ).pipe(
111
Effect.flatMap((key) =>
112
Jwt.verify(schema, input.token, key, {
113
typ: input.typ,