Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

environmentKeys.ts

154 lines5.8 KB

1import { importRelayPrivateKey, RelayJwtError, signRelayJwt } from "@t3tools/shared/relayJwt";
2import * as Context from "effect/Context";
3import * as Signature from "effect/crypto/Signature";
4import * as Effect from "effect/Effect";
5import * as Jwk from "effect/jose/Jwk";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Redacted from "effect/Redacted";
9import * as Schema from "effect/Schema";
10​
11import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
12​
13const CLOUD_LINK_KEY_PAIR = "cloud-link-ed25519-key-pair";
14const CLOUD_LINK_PRIVATE_KEY = "cloud-link-ed25519-private-key";
15const CLOUD_LINK_PUBLIC_KEY = "cloud-link-ed25519-public-key";
16​
17const EnvironmentKeyPair = Schema.Struct({
18 privateKey: Schema.String,
19 publicKey: Schema.String,
20});
21type EnvironmentKeyPair = typeof EnvironmentKeyPair.Type;
22​
23const EnvironmentKeyPairJson = Schema.fromJsonString(EnvironmentKeyPair);
24const decodeEnvironmentKeyPair = Schema.decodeUnknownEffect(EnvironmentKeyPairJson);
25const encodeEnvironmentKeyPair = Schema.encodeEffect(EnvironmentKeyPairJson);
26​
27function bytesToString(bytes: Uint8Array): string {
28 return new TextDecoder().decode(bytes);
30​
31function stringToBytes(value: string): Uint8Array {
32 return new TextEncoder().encode(value);
34​
35const KEY_PAIR_RESOURCE = "environment signing key pair";
36​
37const keyPairDecodeError = (cause: unknown): ServerSecretStore.SecretStoreDecodeError =>
38 new ServerSecretStore.SecretStoreDecodeError({ resource: KEY_PAIR_RESOURCE, cause });
39​
40const keyPairEncodeError = (cause: unknown): ServerSecretStore.SecretStoreEncodeError =>
41 new ServerSecretStore.SecretStoreEncodeError({ resource: KEY_PAIR_RESOURCE, cause });
42​
43const keyPairConcurrentReadError = (): ServerSecretStore.SecretStoreConcurrentReadError =>
44 new ServerSecretStore.SecretStoreConcurrentReadError({ resource: KEY_PAIR_RESOURCE });
45​
46const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (
47 secrets: ServerSecretStore.ServerSecretStore["Service"],
48) {
49 const encoded = yield* secrets.get(CLOUD_LINK_KEY_PAIR);
50 if (Option.isNone(encoded)) {
51 return Option.none<EnvironmentKeyPair>();
52 }
53 const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(
54 Effect.mapError(keyPairDecodeError),
55 );
56 return Option.some(decoded);
57});
58​
59const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(function* (
60 secrets: ServerSecretStore.ServerSecretStore["Service"],
61 keyPair: EnvironmentKeyPair,
62) {
63 const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(
64 Effect.mapError(keyPairEncodeError),
65 );
66 return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(
67 Effect.as(keyPair),
68 Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
69 ServerSecretStore.isSecretAlreadyExistsError(error)
70 ? readEnvironmentKeyPair(secrets).pipe(
71 Effect.flatMap(
72 Option.match({
73 onSome: Effect.succeed,
74 onNone: () => Effect.fail(keyPairConcurrentReadError()),
75 }),
76 ),
77 )
78 : Effect.fail(error),
79 ),
80 );
81});
82​
83export const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function* (
84 secrets: ServerSecretStore.ServerSecretStore["Service"],
85) {
86 const existing = yield* readEnvironmentKeyPair(secrets);
87 if (Option.isSome(existing)) {
88 return existing.value;
89 }
90​
91 const existingPrivate = yield* secrets.get(CLOUD_LINK_PRIVATE_KEY);
92 const existingPublic = yield* secrets.get(CLOUD_LINK_PUBLIC_KEY);
93 if (Option.isSome(existingPrivate) && Option.isSome(existingPublic)) {
94 return yield* persistEnvironmentKeyPair(secrets, {
95 privateKey: bytesToString(existingPrivate.value),
96 publicKey: bytesToString(existingPublic.value),
97 });
98 }
99​
100 const keyPair = yield* Jwk.generateKeyPair({ algorithm: "EdDSA" }).pipe(
101 Effect.flatMap((pair) =>
102 Effect.all({
103 privateKey: Jwk.importPrivate(pair.privateKey, "EdDSA").pipe(
104 Effect.flatMap((key) => Jwk.exportPkcs8(key, { format: "pem" })),
105 Effect.map(Redacted.value),
106 ),
107 publicKey: Jwk.importPublic(pair.publicKey, "EdDSA").pipe(
108 Effect.flatMap((key) => Jwk.exportSpki(key, { format: "pem" })),
109 ),
110 }),
111 ),
112 Effect.orDie,
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. */
118export 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​
130export 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);