Skip to content
TypeScript

refactor: hold relay signing keys in EnvironmentSigningKey and CloudMintSigner (#30529)

Julius Marminge33ba7bf5ef09
diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.ts
index 39971c81d85..8213288dee9 100644
--- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts
+++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts
@@ -13,6 +13,7 @@ import { HttpClient, HttpClientResponse, HttpServer, type HttpClientRequest } fr
import * as NetAddress from "effect/net/NetAddress";
import { EnvironmentId } from "@t3tools/contracts";
+import * as EnvironmentKeys from "./environmentKeys.ts";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfigModule from "../config.ts";
@@ -161,7 +162,12 @@ describe("releaseManagedTunnelOnShutdown", () => {
(harness: ReleaseHarness) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
- Effect.provide(CloudLink.layer.pipe(Layer.provide(ManagedPolicy.layerTest()))),
+ Effect.provide(
+ CloudLink.layer.pipe(
+ Layer.provide(EnvironmentKeys.layer),
+ Layer.provide(ManagedPolicy.layerTest()),
+ ),
+ ),
Effect.provideService(
ConnectReachability.ConnectReachability,
ConnectReachability.ConnectReachability.of({
diff --git a/apps/server/src/cloud/CloudLink.test.ts b/apps/server/src/cloud/CloudLink.test.ts
index 2a4cc53b050..8de291e3fda 100644
--- a/apps/server/src/cloud/CloudLink.test.ts
+++ b/apps/server/src/cloud/CloudLink.test.ts
@@ -10,6 +10,7 @@ import * as NetAddress from "effect/net/NetAddress";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
+import * as EnvironmentKeys from "./environmentKeys.ts";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
@@ -119,7 +120,13 @@ const withService = <A, E>(
const link = yield* CloudLink.CloudLink;
return yield* body({ preferences: { update: link.updatePreferences }, stored, relayCalls });
}).pipe(
- Effect.provide(CloudLink.layer.pipe(Layer.provide(layerDependencies))),
+ Effect.provide(
+ CloudLink.layer.pipe(
+ // These tests never sign proofs; the mocked secret store cannot create a key pair.
+ Layer.provide(Layer.mock(EnvironmentKeys.EnvironmentSigningKey)({ publicKey: "" })),
+ Layer.provide(layerDependencies),
+ ),
+ ),
Effect.provideService(FetchHttpClient.Fetch, fetch),
);
});
@@ -301,6 +308,14 @@ it.effect("unlinks on startup and refuses to link when the policy turns Connect
const mintError = yield* link.mintCredential({} as never).pipe(Effect.flip);
assert.equal(applyError.message, "Example Corp's policy does not allow T3 Connect.");
assert.equal(mintError._tag, "ManagedPolicyRefusedError");
- }).pipe(Effect.provide(CloudLink.layer.pipe(Layer.provide(layerDependencies))));
+ }).pipe(
+ Effect.provide(
+ CloudLink.layer.pipe(
+ // These tests never sign proofs; the mocked secret store cannot create a key pair.
+ Layer.provide(Layer.mock(EnvironmentKeys.EnvironmentSigningKey)({ publicKey: "" })),
+ Layer.provide(layerDependencies),
+ ),
+ ),
+ );
}),
);
diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.ts
index 1dd2f23bdbd..37ac9d9b743 100644
--- a/apps/server/src/cloud/CloudLink.ts
+++ b/apps/server/src/cloud/CloudLink.ts
@@ -36,7 +36,6 @@ import {
RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
RELAY_MINT_REQUEST_TYP,
RELAY_MINT_RESPONSE_TYP,
- signRelayJwt,
verifyRelayJwt,
} from "@t3tools/shared/relayJwt";
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
@@ -95,7 +94,7 @@ import {
RELAY_ISSUER_SECRET,
RELAY_URL_SECRET,
} from "./config.ts";
-import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
+import { EnvironmentSigningKey } from "./environmentKeys.ts";
import * as ConnectReachability from "./ConnectReachability.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import * as ManagedLimits from "../policy/managedLimits.ts";
@@ -525,6 +524,7 @@ const make = Effect.gen(function* () {
const awarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
const random = yield* SecureRandom.SecureRandom;
const signature = yield* Signature.Signature;
+ const signingKey = yield* EnvironmentSigningKey;
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -581,9 +581,6 @@ const make = Effect.gen(function* () {
requestUrl: string,
allowNonLoopbackRequestHost = false,
) {
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
- Effect.provideService(Signature.Signature, signature),
- );
if (
!isSupportedLinkProviderKind(request) ||
!isAllowedEndpointOrigin({
@@ -608,24 +605,24 @@ const make = Effect.gen(function* () {
challenge: request.challenge,
descriptor,
environmentId: descriptor.environmentId,
- environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),
+ environmentPublicKey: normalizePemForSignedPayload(signingKey.publicKey),
endpoint: request.endpoint,
origin: request.origin,
scopes: linkProofScopes(request),
} satisfies RelayEnvironmentLinkProofPayload;
- return yield* signRelayJwt({
- privateKey: keyPair.privateKey,
- typ: RELAY_LINK_PROOF_TYP,
- payload,
- }).pipe(
- Effect.provideService(Signature.Signature, signature),
- Effect.mapError(
- (cause) =>
- new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
- cause,
- }),
- ),
- );
+ return yield* signingKey
+ .sign({
+ typ: RELAY_LINK_PROOF_TYP,
+ payload,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
+ cause,
+ }),
+ ),
+ );
});
const linkProof = Effect.fn("environment.cloud.linkProof")(
@@ -925,9 +922,6 @@ const make = Effect.gen(function* () {
const makeManagedTunnelRecoveryProof = Effect.fn(
"environment.cloud.makeManagedTunnelRecoveryProof",
)(function* (input: ManagedTunnelRecoveryProofInput) {
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
- Effect.provideService(Signature.Signature, signature),
- );
const configuredIssuer = yield* secrets.get(RELAY_ISSUER_SECRET);
const now = yield* DateTime.now;
const issuedAt = Math.floor(now.epochMilliseconds / 1_000);
@@ -953,16 +947,16 @@ const make = Effect.gen(function* () {
}
: { ...claims, action: "recover" as const, origin: input.origin };
- return yield* signRelayJwt({
- privateKey: keyPair.privateKey,
- typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
- payload,
- }).pipe(
- Effect.provideService(Signature.Signature, signature),
- Effect.mapError(
- (cause) => new CloudLinkInternalError({ operation: "sign-recovery-proof", cause }),
- ),
- );
+ return yield* signingKey
+ .sign({
+ typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
+ payload,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) => new CloudLinkInternalError({ operation: "sign-recovery-proof", cause }),
+ ),
+ );
});
/** 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* () {
return yield* new CloudLinkProofReplayedError({ request: "health" });
}
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
- Effect.provideService(Signature.Signature, signature),
- );
const descriptor = yield* environment.getDescriptor;
const responseExpiresAt = DateTime.add(now, { minutes: 5 });
const responsePayload = {
@@ -1499,19 +1490,19 @@ const make = Effect.gen(function* () {
descriptor,
checkedAt: DateTime.formatIso(now),
} satisfies RelayEnvironmentHealthResponseProofPayload;
- const responseProof = yield* signRelayJwt({
- privateKey: keyPair.privateKey,
- typ: RELAY_HEALTH_RESPONSE_TYP,
- payload: responsePayload,
- }).pipe(
- Effect.provideService(Signature.Signature, signature),
- Effect.mapError(
- (cause) =>
- new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({
- cause,
- }),
- ),
- );
+ const responseProof = yield* signingKey
+ .sign({
+ typ: RELAY_HEALTH_RESPONSE_TYP,
+ payload: responsePayload,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({
+ cause,
+ }),
+ ),
+ );
return {
environmentId,
status: "online",
@@ -1587,9 +1578,6 @@ const make = Effect.gen(function* () {
return yield* new CloudLinkProofReplayedError({ request: "mint" });
}
- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets).pipe(
- Effect.provideService(Signature.Signature, signature),
- );
const issued = yield* environmentAuth.createPairingLink({
scopes: AuthStandardClientScopes,
subject: "cloud-connect",
@@ -1609,19 +1597,19 @@ const make = Effect.gen(function* () {
requestNonce: proof.nonce,
credential: issued.credential,
} satisfies RelayEnvironmentMintResponseProofPayload;
- const responseProof = yield* signRelayJwt({
- privateKey: keyPair.privateKey,
- typ: RELAY_MINT_RESPONSE_TYP,
- payload: responsePayload,
- }).pipe(
- Effect.provideService(Signature.Signature, signature),
- Effect.mapError(
- (cause) =>
- new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
- cause,
- }),
- ),
- );
+ const responseProof = yield* signingKey
+ .sign({
+ typ: RELAY_MINT_RESPONSE_TYP,
+ payload: responsePayload,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
+ cause,
+ }),
+ ),
+ );
return {
credential: issued.credential,
expiresAt: DateTime.formatIso(issued.expiresAt),
diff --git a/apps/server/src/cloud/environmentKeys.test.ts b/apps/server/src/cloud/environmentKeys.test.ts
index 4c45f4d65fc..a10ec9aeaa9 100644
--- a/apps/server/src/cloud/environmentKeys.test.ts
+++ b/apps/server/src/cloud/environmentKeys.test.ts
@@ -8,7 +8,11 @@ import * as PlatformError from "effect/PlatformError";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
-import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
+import {
+ EnvironmentSigningKey,
+ getOrCreateEnvironmentKeyPairFromSecretStore,
+ layer,
+} from "./environmentKeys.ts";
const layerServerSecretStore = () =>
ServerSecretStore.layer.pipe(
@@ -48,6 +52,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
publicKey: "public",
});
assert.isTrue(Option.isSome(yield* secretStore.get("cloud-link-ed25519-key-pair")));
+
+ // Unparseable key material must fail signing, not the layer every server starts.
+ const signingKey = yield* EnvironmentSigningKey.pipe(Effect.provide(layer));
+ assert.strictEqual(signingKey.publicKey, "public");
+ const error = yield* Effect.flip(signingKey.sign({ typ: "test+jwt", payload: {} }));
+ assert.strictEqual(error._tag, "RelayJwtError");
}).pipe(Effect.provide(layerServerSecretStore())),
);
diff --git a/apps/server/src/cloud/environmentKeys.ts b/apps/server/src/cloud/environmentKeys.ts
index 79715885956..9b7053908e3 100644
--- a/apps/server/src/cloud/environmentKeys.ts
+++ b/apps/server/src/cloud/environmentKeys.ts
@@ -1,5 +1,9 @@
+import { importRelayPrivateKey, RelayJwtError, signRelayJwt } from "@t3tools/shared/relayJwt";
+import * as Context from "effect/Context";
+import * as Signature from "effect/crypto/Signature";
import * as Effect from "effect/Effect";
import * as Jwk from "effect/jose/Jwk";
+import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
@@ -109,3 +113,42 @@ export const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function*
);
return yield* persistEnvironmentKeyPair(secrets, keyPair);
});
+
+/** The environment's Ed25519 relay signing key, loaded at startup and parsed on first use. */
+export class EnvironmentSigningKey extends Context.Service<
+ EnvironmentSigningKey,
+ {
+ /** SPKI PEM, as relays and linked clients receive it. */
+ readonly publicKey: string;
+ readonly sign: (input: {
+ readonly typ: string;
+ readonly payload: Readonly<Record<string, unknown>>;
+ }) => Effect.Effect<string, RelayJwtError>;
+ }
+>()("t3/cloud/environmentKeys/EnvironmentSigningKey") {}
+
+export const layer = Layer.effect(
+ EnvironmentSigningKey,
+ Effect.gen(function* () {
+ const secrets = yield* ServerSecretStore.ServerSecretStore;
+ const signature = yield* Signature.Signature;
+ const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
+ // Parsed lazily so corrupt key material fails Connect operations, not server startup.
+ let privateKey: Jwk.PrivateKey | undefined;
+ return EnvironmentSigningKey.of({
+ publicKey: keyPair.publicKey,
+ sign: Effect.fn("EnvironmentSigningKey.sign")(function* (input) {
+ if (privateKey === undefined) {
+ privateKey = yield* importRelayPrivateKey(keyPair.privateKey).pipe(
+ Effect.mapError(
+ (cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause }),
+ ),
+ );
+ }
+ return yield* signRelayJwt({ ...input, privateKey }).pipe(
+ Effect.provideService(Signature.Signature, signature),
+ );
+ }),
+ });
+ }),
+);
diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts
index ddbf46fdfb3..2d3dee882dc 100644
--- a/apps/server/src/cloud/http.test.ts
+++ b/apps/server/src/cloud/http.test.ts
@@ -25,6 +25,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
import * as NetAddress from "effect/net/NetAddress";
import { decodeRelayJwt, RELAY_LINK_PROOF_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";
+import * as EnvironmentKeys from "./environmentKeys.ts";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as AuthHttp from "../auth/http.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -78,6 +79,7 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(
Layer.provide([AuthHttp.layer, ConnectHttp.layer]),
Layer.provide(AuthHttp.layerAuthenticatedAuth),
Layer.provide(CloudLink.layer),
+ Layer.provide(EnvironmentKeys.layer),
Layer.provide(
Layer.mock(ConnectReachability.ConnectReachability)({ latest: Effect.succeedNone }),
),
diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts
index 8747ad7e3d8..f7edcc869f2 100644
--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts
+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts
@@ -28,6 +28,7 @@ import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
+import * as EnvironmentKeys from "../cloud/environmentKeys.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import {
PUBLISH_AGENT_ACTIVITY_SECRET,
@@ -276,6 +277,7 @@ const makeTestRelay = Effect.fnUntraced(function* (
deletedAt: null,
};
const relay = yield* AgentAwarenessRelay.make.pipe(
+ Effect.provide(EnvironmentKeys.layer),
Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
Effect.provideService(ServerEnvironment.ServerEnvironment, {
diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts
index 286c95cf7f1..2523fea9f2c 100644
--- a/apps/server/src/relay/AgentAwarenessRelay.ts
+++ b/apps/server/src/relay/AgentAwarenessRelay.ts
@@ -16,15 +16,10 @@ import { projectThreadAwarenessV2 } from "@t3tools/shared/agentAwareness";
import { turnItemUpdateCanEndBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
-import {
- normalizeRelayIssuer,
- RELAY_ACTIVITY_PUBLISH_TYP,
- signRelayJwt,
-} from "@t3tools/shared/relayJwt";
+import { normalizeRelayIssuer, RELAY_ACTIVITY_PUBLISH_TYP } from "@t3tools/shared/relayJwt";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
-import * as Signature from "effect/crypto/Signature";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -47,7 +42,7 @@ import {
RELAY_ISSUER_SECRET,
RELAY_URL_SECRET,
} from "../cloud/config.ts";
-import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environmentKeys.ts";
+import { EnvironmentSigningKey } from "../cloud/environmentKeys.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
import * as ProjectService from "../project/ProjectService.ts";
@@ -249,7 +244,6 @@ function deliveryStats(
}
const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
- readonly privateKey: string;
readonly relayIssuer: string;
readonly environmentId: string;
readonly threadId: ThreadId;
@@ -269,11 +263,8 @@ const makePublishProof = Effect.fn("makePublishProof")(function* (input: {
threadId: input.threadId,
state: input.state,
} satisfies RelayAgentActivityPublishProofPayload;
- return yield* signRelayJwt({
- privateKey: input.privateKey,
- typ: RELAY_ACTIVITY_PUBLISH_TYP,
- payload,
- });
+ const signingKey = yield* EnvironmentSigningKey;
+ return yield* signingKey.sign({ typ: RELAY_ACTIVITY_PUBLISH_TYP, payload });
});
function describeThreadShellForAwareness(
@@ -372,9 +363,8 @@ export const make = Effect.gen(function* () {
const threads = yield* ThreadManagement.ThreadManagementService;
const projects = yield* ProjectService.ProjectService;
const random = yield* SecureRandom.SecureRandom;
- const signature = yield* Signature.Signature;
+ const signingKey = yield* EnvironmentSigningKey;
const scope = yield* Effect.scope;
- const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
const startedAt = (yield* DateTime.now).epochMilliseconds;
const catchUpRequests = yield* Queue.dropping<void>(1);
const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());
@@ -480,13 +470,12 @@ export const make = Effect.gen(function* () {
}
const relayClient = cachedRelayClient;
const proof = yield* makePublishProof({
- privateKey: cloudLinkKeyPair.privateKey,
relayIssuer: relayConfig.issuer,
environmentId,
threadId,
state: input.state,
jti: yield* random.uuidV4(),
- }).pipe(Effect.provideService(Signature.Signature, signature));
+ }).pipe(Effect.provideService(EnvironmentSigningKey, signingKey));
yield* Effect.logInfo("publishing agent activity for thread", {
environmentId,
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 9a5cf6c391b..53f53db72cc 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1,6 +1,7 @@
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
import * as Random from "effect/Random";
+import * as EnvironmentKeys from "./cloud/environmentKeys.ts";
import * as AssetSigner from "./assets/AssetSigner.ts";
import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
import * as StorageCleanup from "./storageCleanup.ts";
@@ -720,7 +721,7 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe(
Layer.provideMerge(CodexManagedTokenBroker.layer),
Layer.provideMerge(layerServerEnvironment),
Layer.provideMerge(layerAuth),
- Layer.provideMerge(AssetSigner.layer),
+ Layer.provideMerge(Layer.mergeAll(AssetSigner.layer, EnvironmentKeys.layer)),
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(
Layer.mergeAll(
diff --git a/infra/relay/src/auth/CloudMintSigner.ts b/infra/relay/src/auth/CloudMintSigner.ts
new file mode 100644
index 00000000000..a5addbca921
--- /dev/null
+++ b/infra/relay/src/auth/CloudMintSigner.ts
@@ -0,0 +1,92 @@
+import {
+ importRelayPrivateKey,
+ importRelayPublicKey,
+ RelayJwtError,
+ signRelayJwt,
+ verifyRelayJwt,
+} from "@t3tools/shared/relayJwt";
+import * as Context from "effect/Context";
+import * as Signature from "effect/crypto/Signature";
+import type * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Redacted from "effect/Redacted";
+import type * as Schema from "effect/Schema";
+
+import * as RelayConfiguration from "../Config.ts";
+
+/** Signs and verifies relay-issued tokens with the cloud mint key pair. */
+export class CloudMintSigner extends Context.Service<
+ CloudMintSigner,
+ {
+ readonly sign: (input: {
+ readonly typ: string;
+ readonly payload: Readonly<Record<string, unknown>>;
+ }) => Effect.Effect<string, RelayJwtError>;
+ readonly verify: <A>(
+ schema: Schema.ConstraintDecoder<A>,
+ input: {
+ readonly token: string;
+ readonly typ: string;
+ readonly issuer: string;
+ readonly audience: string;
+ readonly maxTokenAge?: Duration.Input;
+ },
+ ) => Effect.Effect<A, RelayJwtError>;
+ }
+>()("t3code-relay/auth/CloudMintSigner") {}
+
+// Parsed on first use and kept; a failed parse is retried so a bad key fails requests, not boot.
+const cacheSuccess = <A, E>(load: Effect.Effect<A, E>) => {
+ let value: A | undefined;
+ return Effect.suspend(() =>
+ value !== undefined
+ ? Effect.succeed(value)
+ : Effect.tap(load, (loaded) =>
+ Effect.sync(() => {
+ value = loaded;
+ }),
+ ),
+ );
+};
+
+export const layer = Layer.effect(
+ CloudMintSigner,
+ Effect.gen(function* () {
+ const config = yield* RelayConfiguration.RelayConfiguration;
+ const signature = yield* Signature.Signature;
+ const privateKey = cacheSuccess(
+ importRelayPrivateKey(Redacted.value(config.cloudMintPrivateKey)),
+ );
+ const publicKey = cacheSuccess(importRelayPublicKey(config.cloudMintPublicKey));
+
+ return CloudMintSigner.of({
+ sign: Effect.fn("CloudMintSigner.sign")(function* (input) {
+ const key = yield* privateKey.pipe(
+ Effect.mapError(
+ (cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause }),
+ ),
+ );
+ return yield* signRelayJwt({ ...input, privateKey: key }).pipe(
+ Effect.provideService(Signature.Signature, signature),
+ );
+ }),
+ verify: Effect.fn("CloudMintSigner.verify")(function* (schema, input) {
+ return yield* publicKey.pipe(
+ Effect.mapError(
+ (cause) =>
+ new RelayJwtError({
+ operation: "verify",
+ typ: input.typ,
+ issuer: input.issuer,
+ audience: input.audience,
+ cause,
+ }),
+ ),
+ Effect.flatMap((key) => verifyRelayJwt(schema, { ...input, publicKey: key })),
+ Effect.provideService(Signature.Signature, signature),
+ );
+ }),
+ });
+ }),
+);
diff --git a/infra/relay/src/auth/RelayTokens.test.ts b/infra/relay/src/auth/RelayTokens.test.ts
index fc6e35fec03..fa4ab7b9e09 100644
--- a/infra/relay/src/auth/RelayTokens.test.ts
+++ b/infra/relay/src/auth/RelayTokens.test.ts
@@ -10,6 +10,7 @@ import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as TestClock from "effect/testing/TestClock";
+import * as CloudMintSigner from "./CloudMintSigner.ts";
import * as RelayConfiguration from "../Config.ts";
import * as RelayTokens from "./RelayTokens.ts";
@@ -38,6 +39,7 @@ const config = RelayConfiguration.RelayConfiguration.of({
});
const layer = RelayTokens.layer.pipe(
+ Layer.provide(CloudMintSigner.layer),
Layer.provide(RelayConfiguration.layer(config)),
Layer.provideMerge(Signature.layerWebCrypto),
Layer.provide(SecureRandom.layerWebCrypto),
diff --git a/infra/relay/src/auth/RelayTokens.ts b/infra/relay/src/auth/RelayTokens.ts
index 9d6014b8d72..80834884c6a 100644
--- a/infra/relay/src/auth/RelayTokens.ts
+++ b/infra/relay/src/auth/RelayTokens.ts
@@ -9,20 +9,14 @@ import {
type RelayEnvironmentLinkChallengeRequest,
} from "@t3tools/contracts/relay";
import { encodeOAuthScope, parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";
-import {
- normalizeRelayIssuer,
- RelayJwtError,
- signRelayJwt,
- verifyRelayJwt,
-} from "@t3tools/shared/relayJwt";
+import { normalizeRelayIssuer, RelayJwtError } from "@t3tools/shared/relayJwt";
import * as Context from "effect/Context";
-import * as Signature from "effect/crypto/Signature";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
-import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as RelayConfiguration from "../Config.ts";
+import * as CloudMintSigner from "./CloudMintSigner.ts";
const LINK_CHALLENGE_TYP = "t3-link-challenge+jwt";
const ACCESS_TOKEN_TYP = "t3-relay-dpop-access+jwt";
@@ -114,13 +108,12 @@ export class RelayTokens extends Context.Service<
const make = Effect.gen(function* () {
const config = yield* RelayConfiguration.RelayConfiguration;
const issuer = normalizeRelayIssuer(config.relayIssuer);
- const signature = yield* Signature.Signature;
+ const mint = yield* CloudMintSigner.CloudMintSigner;
const issueLinkChallenge: RelayTokens["Service"]["issueLinkChallenge"] = Effect.fn(
"relay.tokens.issue_link_challenge",
)(function* (input) {
- return yield* signRelayJwt({
- privateKey: Redacted.value(config.cloudMintPrivateKey),
+ return yield* mint.sign({
typ: LINK_CHALLENGE_TYP,
payload: {
kind: LINK_CHALLENGE_KIND,
@@ -132,40 +125,39 @@ const make = Effect.gen(function* () {
exp: input.expiresAtEpochSeconds,
...input.request,
},
- }).pipe(Effect.provideService(Signature.Signature, signature));
+ });
});
const verifyLinkChallenge: RelayTokens["Service"]["verifyLinkChallenge"] = Effect.fn(
"relay.tokens.verify_link_challenge",
)((input) =>
- verifyRelayJwt(LinkChallengeClaims, {
- publicKey: config.cloudMintPublicKey,
- token: input.token,
- typ: LINK_CHALLENGE_TYP,
- issuer,
- audience: issuer,
- }).pipe(
- Effect.provideService(Signature.Signature, signature),
- Effect.map((claims) => {
- if (
- claims.sub !== input.userId ||
- (input.request.notificationsEnabled && claims.notificationsEnabled !== true) ||
- (input.request.liveActivitiesEnabled && claims.liveActivitiesEnabled !== true) ||
- (input.request.managedTunnelsEnabled && claims.managedTunnelsEnabled !== true)
- ) {
- return null;
- }
- return claims;
- }),
- Effect.orElseSucceed(() => null),
- ),
+ mint
+ .verify(LinkChallengeClaims, {
+ token: input.token,
+ typ: LINK_CHALLENGE_TYP,
+ issuer,
+ audience: issuer,
+ })
+ .pipe(
+ Effect.map((claims) => {
+ if (
+ claims.sub !== input.userId ||
+ (input.request.notificationsEnabled && claims.notificationsEnabled !== true) ||
+ (input.request.liveActivitiesEnabled && claims.liveActivitiesEnabled !== true) ||
+ (input.request.managedTunnelsEnabled && claims.managedTunnelsEnabled !== true)
+ ) {
+ return null;
+ }
+ return claims;
+ }),
+ Effect.orElseSucceed(() => null),
+ ),
);
const issueDpopAccessToken: RelayTokens["Service"]["issueDpopAccessToken"] = Effect.fn(
"relay.tokens.issue_dpop_access_token",
)(function* (input) {
- return yield* signRelayJwt({
- privateKey: Redacted.value(config.cloudMintPrivateKey),
+ return yield* mint.sign({
typ: ACCESS_TOKEN_TYP,
payload: {
iss: issuer,
@@ -178,36 +170,36 @@ const make = Effect.gen(function* () {
scope: encodeOAuthScope(input.scopes),
cnf: { jkt: input.proofKeyThumbprint },
},
- }).pipe(Effect.provideService(Signature.Signature, signature));
+ });
});
const verifyDpopAccessToken: RelayTokens["Service"]["verifyDpopAccessToken"] = Effect.fn(
"relay.tokens.verify_dpop_access_token",
)((input) =>
- verifyRelayJwt(RelayDpopAccessTokenClaims, {
- publicKey: config.cloudMintPublicKey,
- token: input.token,
- typ: ACCESS_TOKEN_TYP,
- issuer,
- audience: issuer,
- maxTokenAge: RELAY_DPOP_ACCESS_TOKEN_TTL,
- }).pipe(
- Effect.provideService(Signature.Signature, signature),
- Effect.tapError((error) =>
- Effect.annotateCurrentSpan(
- "relay.tokens.verification_failure",
- RelayJwtError.diagnosticCode(error),
+ mint
+ .verify(RelayDpopAccessTokenClaims, {
+ token: input.token,
+ typ: ACCESS_TOKEN_TYP,
+ issuer,
+ audience: issuer,
+ maxTokenAge: RELAY_DPOP_ACCESS_TOKEN_TTL,
+ })
+ .pipe(
+ Effect.tapError((error) =>
+ Effect.annotateCurrentSpan(
+ "relay.tokens.verification_failure",
+ RelayJwtError.diagnosticCode(error),
+ ),
),
+ Effect.map((claims): RelayDpopAccessTokenClaims | null => {
+ const scopes = resolveDpopAccessTokenScopes({
+ clientId: claims.client_id,
+ scope: claims.scope,
+ });
+ return scopes === null ? null : { ...claims, scope: scopes };
+ }),
+ Effect.orElseSucceed(() => null),
),
- Effect.map((claims): RelayDpopAccessTokenClaims | null => {
- const scopes = resolveDpopAccessTokenScopes({
- clientId: claims.client_id,
- scope: claims.scope,
- });
- return scopes === null ? null : { ...claims, scope: scopes };
- }),
- Effect.orElseSucceed(() => null),
- ),
);
return RelayTokens.of({
diff --git a/infra/relay/src/environments/EnvironmentConnector.test.ts b/infra/relay/src/environments/EnvironmentConnector.test.ts
index 5eba9de86cc..b08a8b5e951 100644
--- a/infra/relay/src/environments/EnvironmentConnector.test.ts
+++ b/infra/relay/src/environments/EnvironmentConnector.test.ts
@@ -23,6 +23,7 @@ import * as Schema from "effect/Schema";
import * as Tracer from "effect/Tracer";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
+import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as RelayConfiguration from "../Config.ts";
import * as EnvironmentConnector from "./EnvironmentConnector.ts";
@@ -162,6 +163,7 @@ function layerConnectorTest(
},
) {
return EnvironmentConnector.layer.pipe(
+ Layer.provide(CloudMintSigner.layer),
Layer.provide(NodeCryptoLayer.layer),
Layer.provide(Layer.succeed(EnvironmentLinks.EnvironmentLinks, options?.links ?? makeLinks())),
Layer.provide(
diff --git a/infra/relay/src/environments/EnvironmentConnector.ts b/infra/relay/src/environments/EnvironmentConnector.ts
index 00841b8731f..e9862fa1976 100644
--- a/infra/relay/src/environments/EnvironmentConnector.ts
+++ b/infra/relay/src/environments/EnvironmentConnector.ts
@@ -25,7 +25,6 @@ import {
RELAY_HEALTH_RESPONSE_TYP,
RELAY_MINT_REQUEST_TYP,
RELAY_MINT_RESPONSE_TYP,
- signRelayJwt,
verifyRelayJwt,
} from "@t3tools/shared/relayJwt";
import { stableStringify } from "@t3tools/shared/relaySigning";
@@ -37,7 +36,6 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
-import * as Redacted from "effect/Redacted";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
@@ -48,6 +46,7 @@ import { diagnoseEndpointFailure } from "./endpointFailure.ts";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
import * as RelayConfiguration from "../Config.ts";
+import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
import { isManagedEndpointHostname } from "../deploymentConfig.ts";
function environmentConnectNotAuthorizedReasonMessage(
@@ -376,6 +375,7 @@ const make = Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
const random = yield* SecureRandom.SecureRandom;
const signature = yield* Signature.Signature;
+ const mint = yield* CloudMintSigner.CloudMintSigner;
const relayIssuer = normalizeRelayIssuer(settings.relayIssuer);
const makeEnvironmentClient = (httpBaseUrl: string) =>
makeEnvironmentHttpApiClient(httpBaseUrl).pipe(
@@ -463,21 +463,21 @@ const make = Effect.gen(function* () {
nonce,
scope: ["environment:status"],
} satisfies RelayCloudEnvironmentHealthProofPayload;
- const proof = yield* signRelayJwt({
- privateKey: Redacted.value(settings.cloudMintPrivateKey),
- typ: RELAY_HEALTH_REQUEST_TYP,
- payload,
- }).pipe(
- Effect.provideService(Signature.Signature, signature),
- Effect.mapError(
- (cause) =>
- new EnvironmentMintRequestFailed({
- environmentId: input.environmentId,
- operation: "status",
- cause,
- }),
- ),
- );
+ const proof = yield* mint
+ .sign({
+ typ: RELAY_HEALTH_REQUEST_TYP,
+ payload,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new EnvironmentMintRequestFailed({
+ environmentId: input.environmentId,
+ operation: "status",
+ cause,
+ }),
+ ),
+ );
const checkedAt = DateTime.formatIso(now);
const traceId = yield* currentTraceId;
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
@@ -629,21 +629,21 @@ const make = Effect.gen(function* () {
nonce,
scope: ["environment:connect"],
} satisfies RelayCloudMintCredentialProofPayload;
- const proof = yield* signRelayJwt({
- privateKey: Redacted.value(settings.cloudMintPrivateKey),
- typ: RELAY_MINT_REQUEST_TYP,
- payload,
- }).pipe(
- Effect.provideService(Signature.Signature, signature),
- Effect.mapError(
- (cause) =>
- new EnvironmentMintRequestFailed({
- environmentId: input.environmentId,
- operation: "connect",
- cause,
- }),
- ),
- );
+ const proof = yield* mint
+ .sign({
+ typ: RELAY_MINT_REQUEST_TYP,
+ payload,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new EnvironmentMintRequestFailed({
+ environmentId: input.environmentId,
+ operation: "connect",
+ cause,
+ }),
+ ),
+ );
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
const decoded = yield* environmentClient.connect
.t3MintCredential({ payload: { proof } })
diff --git a/infra/relay/src/environments/EnvironmentLinker.test.ts b/infra/relay/src/environments/EnvironmentLinker.test.ts
index bab85ffb722..b770b52d22f 100644
--- a/infra/relay/src/environments/EnvironmentLinker.test.ts
+++ b/infra/relay/src/environments/EnvironmentLinker.test.ts
@@ -14,6 +14,7 @@ import * as Redacted from "effect/Redacted";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
+import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
import * as DpopProofs from "../auth/DpopProofs.ts";
import * as RelayTokens from "../auth/RelayTokens.ts";
import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
@@ -114,7 +115,7 @@ function layerTest(input?: {
readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"];
}) {
return EnvironmentLinker.layer.pipe(
- Layer.provideMerge(RelayTokens.layer),
+ Layer.provideMerge(RelayTokens.layer.pipe(Layer.provide(CloudMintSigner.layer))),
Layer.provide(
Layer.mergeAll(
RelayConfiguration.layer(config),
diff --git a/infra/relay/src/hooks/HookForwarder.test.ts b/infra/relay/src/hooks/HookForwarder.test.ts
index 0ecdee43617..15090d3bd8c 100644
--- a/infra/relay/src/hooks/HookForwarder.test.ts
+++ b/infra/relay/src/hooks/HookForwarder.test.ts
@@ -22,6 +22,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
import * as HttpServerRequest from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
+import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
import * as RelayConfiguration from "../Config.ts";
import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts";
@@ -107,6 +108,7 @@ function makeHarness(options: Harness = {}) {
));
const layerForwarder = HookForwarder.layer.pipe(
Layer.provideMerge(HeldHooks.layer),
+ Layer.provide(CloudMintSigner.layer),
Layer.provide(
Layer.mergeAll(
Layer.succeed(RelayConfiguration.RelayConfiguration, settings),
diff --git a/infra/relay/src/hooks/HookForwarder.ts b/infra/relay/src/hooks/HookForwarder.ts
index 037a851409c..9f6b80a5e86 100644
--- a/infra/relay/src/hooks/HookForwarder.ts
+++ b/infra/relay/src/hooks/HookForwarder.ts
@@ -1,12 +1,10 @@
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as SecureRandom from "effect/crypto/SecureRandom";
-import * as Signature from "effect/crypto/Signature";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
-import * as Redacted from "effect/Redacted";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
@@ -20,10 +18,10 @@ import {
normalizeRelayIssuer,
RELAY_HOOK_DELIVERY_HEADER,
RELAY_HOOK_DELIVERY_TYP,
- signRelayJwt,
} from "@t3tools/shared/relayJwt";
import * as RelayConfiguration from "../Config.ts";
+import * as CloudMintSigner from "../auth/CloudMintSigner.ts";
import { MANAGED_ENDPOINT_KEY_PATTERN } from "../deploymentConfig.ts";
import * as HeldHooks from "./HeldHooks.ts";
import * as HookInbox from "./HookInbox.ts";
@@ -221,7 +219,7 @@ const make = Effect.gen(function* () {
const rateLimiter = yield* HookRateLimiter;
const inbox = yield* HookInbox.HookInbox;
const random = yield* SecureRandom.SecureRandom;
- const signature = yield* Signature.Signature;
+ const mint = yield* CloudMintSigner.CloudMintSigner;
const signDeliveryProof = Effect.fn("HookForwarder.signDeliveryProof")(
function* (input: {
@@ -232,8 +230,7 @@ const make = Effect.gen(function* () {
readonly jti: string;
}) {
const now = Math.floor((yield* Clock.currentTimeMillis) / 1_000);
- return yield* signRelayJwt({
- privateKey: Redacted.value(settings.cloudMintPrivateKey),
+ return yield* mint.sign({
typ: RELAY_HOOK_DELIVERY_TYP,
payload: {
iss: normalizeRelayIssuer(settings.relayIssuer),
@@ -247,7 +244,7 @@ const make = Effect.gen(function* () {
receivedAt: input.receivedAt,
hookId: input.hookId,
} satisfies RelayHookDeliveryProofPayload,
- }).pipe(Effect.provideService(Signature.Signature, signature));
+ });
},
(effect, _input) => effect.pipe(Effect.orDie),
);
diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts
index dbece02354c..e9da9a21672 100644
--- a/infra/relay/src/worker.ts
+++ b/infra/relay/src/worker.ts
@@ -28,6 +28,7 @@ import {
traceRelayHttpRequestWith,
withoutCapturedParentSpan,
} from "./http/Api.ts";
+import * as CloudMintSigner from "./auth/CloudMintSigner.ts";
import * as RelayHttpApi from "./http/Api.ts";
import { ManagedEndpointZone, RelayApiZone, RelayDeploymentConfig } from "./zone.ts";
import { RelayObservability } from "./observability.ts";
@@ -340,7 +341,7 @@ export const layer = Api.make(
),
Layer.provideMerge(Layer.mergeAll(LiveActivities.layer, T3ChatAccounts.layer)),
Layer.provideMerge(DeliveryAttempts.layer),
- Layer.provideMerge(RelayTokens.layer),
+ Layer.provideMerge(RelayTokens.layer.pipe(Layer.provideMerge(CloudMintSigner.layer))),
Layer.provideMerge(
RelayDb.RelayTransactions.layer.pipe(
Layer.provideMerge(Layer.succeed(RelayDb.RelayDb, db)),
diff --git a/packages/shared/src/relayJwt.test.ts b/packages/shared/src/relayJwt.test.ts
index 0e41fb3a717..fd552e732ae 100644
--- a/packages/shared/src/relayJwt.test.ts
+++ b/packages/shared/src/relayJwt.test.ts
@@ -1,7 +1,9 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { describe, expect, it } from "@effect/vitest";
+import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Jwk from "effect/jose/Jwk";
+import * as Jws from "effect/jose/Jws";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
@@ -46,6 +48,35 @@ describe("relayJwt", () => {
const error = yield* Effect.flip(verify);
expect(RelayJwtError.diagnosticCode(error)).toBe("ClaimValidationFailed.exp.expired");
expect(error.message).toBe('Failed to verify relay JWT of type "test+jwt".');
+
+ const es256 = yield* Jwk.generateKeyPair({ algorithm: "ES256" });
+ const es256Private = yield* Jwk.importPrivate(es256.privateKey, "ES256");
+ const signWrong = yield* Effect.flip(
+ signRelayJwt({ privateKey: es256Private, typ: "test+jwt", payload: { sub: "user" } }),
+ );
+ expect(RelayJwtError.diagnosticCode(signWrong)).toBe("AlgorithmNotAllowed");
+ const es256Token = yield* Jws.sign(
+ new TextEncoder().encode(
+ JSON.stringify({
+ sub: "user",
+ iss: "relay",
+ aud: "env",
+ iat: Math.floor((yield* Clock.currentTimeMillis) / 1_000),
+ }),
+ ),
+ es256Private,
+ { typ: "test+jwt" },
+ );
+ const verifyWrong = yield* Effect.flip(
+ verifyRelayJwt(Claims, {
+ publicKey: yield* Jwk.importPublic(es256.publicKey, "ES256"),
+ token: Redacted.value(es256Token),
+ typ: "test+jwt",
+ issuer: "relay",
+ audience: "env",
+ }),
+ );
+ expect(RelayJwtError.diagnosticCode(verifyWrong)).toBe("AlgorithmNotAllowed");
}).pipe(Effect.provide(NodeCrypto.layerSignature)),
);
});
diff --git a/packages/shared/src/relayJwt.ts b/packages/shared/src/relayJwt.ts
index f21a532bd0b..c85356421ad 100644
--- a/packages/shared/src/relayJwt.ts
+++ b/packages/shared/src/relayJwt.ts
@@ -62,12 +62,28 @@ function normalizePem(value: string): string {
return value.replace(/\\n/gu, "\n").trim();
}
+/** Parses a PKCS#8 PEM relay signing key once, for callers that sign repeatedly. */
+export const importRelayPrivateKey = (pem: string) =>
+ Jwk.importPkcs8(Redacted.make(normalizePem(pem)), "EdDSA");
+
+/** Parses an SPKI PEM relay verification key once, for callers that verify repeatedly. */
+export const importRelayPublicKey = (pem: string) => Jwk.importSpki(normalizePem(pem), "EdDSA");
+
+// A parsed key carries its own algorithm; relay JWTs are EdDSA only.
+const requireEdDsa = <K extends Jwk.PrivateKey | Jwk.PublicKey>(key: K) =>
+ key.algorithm === "EdDSA"
+ ? Effect.succeed(key)
+ : Effect.fail(new JoseError.JoseError({ reason: new JoseError.AlgorithmNotAllowed() }));
+
export const signRelayJwt = Effect.fn("relayJwt.sign")(function* (input: {
- readonly privateKey: string;
+ readonly privateKey: string | Jwk.PrivateKey;
readonly typ: string;
readonly payload: Readonly<Record<string, unknown>>;
}): Effect.fn.Return<string, RelayJwtError, Signature.Signature> {
- const token = yield* Jwk.importPkcs8(Redacted.make(normalizePem(input.privateKey)), "EdDSA").pipe(
+ const privateKey = input.privateKey;
+ const token = yield* (
+ typeof privateKey === "string" ? importRelayPrivateKey(privateKey) : requireEdDsa(privateKey)
+ ).pipe(
Effect.flatMap((key) =>
Jws.sign(new TextEncoder().encode(JSON.stringify(input.payload)), key, { typ: input.typ }),
),
@@ -80,7 +96,7 @@ export const signRelayJwt = Effect.fn("relayJwt.sign")(function* (input: {
export const verifyRelayJwt = Effect.fn("relayJwt.verify")(function* <A>(
schema: Schema.ConstraintDecoder<A>,
input: {
- readonly publicKey: string;
+ readonly publicKey: string | Jwk.PublicKey;
readonly token: string;
readonly typ: string;
readonly issuer: string;
@@ -88,7 +104,10 @@ export const verifyRelayJwt = Effect.fn("relayJwt.verify")(function* <A>(
readonly maxTokenAge?: Duration.Input;
},
): Effect.fn.Return<A, RelayJwtError, Signature.Signature> {
- const verified = yield* Jwk.importSpki(normalizePem(input.publicKey), "EdDSA").pipe(
+ const publicKey = input.publicKey;
+ const verified = yield* (
+ typeof publicKey === "string" ? importRelayPublicKey(publicKey) : requireEdDsa(publicKey)
+ ).pipe(
Effect.flatMap((key) =>
Jwt.verify(schema, input.token, key, {
typ: input.typ,