The best way to control Claude Code, Codex and more from any computer or phone

main
ts 247 lines 8.43 KB
Raw
1 import type { RuntimeContext } from "alchemy/RuntimeContext";
2 import type * as Effect from "effect/Effect";
3 import * as Redacted from "effect/Redacted";
4 import * as Binding from "./Binding.ts";
5 import type { SecretKeyBinding } from "./SecretKeyBinding.ts";
6
7 const TypeId = "Cloudflare.Workers.SecretKey" as const;
8 type TypeId = typeof TypeId;
9
10 /**
11 * Data format of the key material, mirroring
12 * [`SubtleCrypto.importKey`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#format).
13 */
14 export type SecretKeyFormat = "raw" | "pkcs8" | "spki" | "jwk";
15
16 /**
17 * Operations the imported key may be used for, mirroring
18 * [`SubtleCrypto.importKey`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#keyUsages).
19 */
20 export type SecretKeyUsage =
21 | "encrypt"
22 | "decrypt"
23 | "sign"
24 | "verify"
25 | "deriveKey"
26 | "deriveBits"
27 | "wrapKey"
28 | "unwrapKey";
29
30 /**
31 * Algorithm-specific import parameters, mirroring
32 * [`SubtleCrypto.importKey`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#algorithm)
33 * (e.g. `{ name: "HMAC", hash: "SHA-256" }`, `{ name: "AES-GCM" }`).
34 */
35 export interface SecretKeyAlgorithm {
36 /** WebCrypto algorithm name, e.g. `"HMAC"`, `"AES-GCM"`, `"RSA-PSS"`. */
37 readonly name: string;
38 /** Algorithm-specific parameters (`hash`, `length`, `namedCurve`, …). */
39 readonly [param: string]: unknown;
40 }
41
42 /**
43 * Key material in [JSON Web Key](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey#json_web_key)
44 * format, e.g. `{ kty: "oct", k: "<base64url>", alg: "HS256" }`.
45 */
46 export interface SecretKeyJwk {
47 /** JWK key type, e.g. `"oct"`, `"RSA"`, `"EC"`. */
48 readonly kty: string;
49 /** Remaining JWK members (`k`, `n`, `e`, `crv`, `alg`, …). */
50 readonly [member: string]: unknown;
51 }
52
53 export type SecretKeyProps = {
54 /**
55 * Algorithm-specific key parameters passed to WebCrypto's `importKey`,
56 * e.g. `{ name: "HMAC", hash: "SHA-256" }`.
57 */
58 algorithm: SecretKeyAlgorithm;
59 /**
60 * Allowed operations with the key (`"sign"`, `"verify"`, `"encrypt"`, …).
61 */
62 usages: ReadonlyArray<SecretKeyUsage>;
63 } & (
64 | {
65 /**
66 * Data format of the key material. `raw` / `pkcs8` / `spki` formats
67 * carry the key as base64 in `keyBase64`.
68 */
69 format: "raw" | "pkcs8" | "spki";
70 /**
71 * Base64-encoded key data (raw bytes, or DER for `pkcs8`/`spki`).
72 * Accepts a `Redacted` value — it is unwrapped when the binding is
73 * registered, since the Cloudflare API accepts only the plain value.
74 */
75 keyBase64: string | Redacted.Redacted<string>;
76 keyJwk?: never;
77 }
78 | {
79 /** Data format of the key material — a JSON Web Key in `keyJwk`. */
80 format: "jwk";
81 /**
82 * Key data in JSON Web Key format. Accepts a `Redacted` value — it is
83 * unwrapped when the binding is registered, since the Cloudflare API
84 * accepts only the plain value.
85 */
86 keyJwk: SecretKeyJwk | Redacted.Redacted<SecretKeyJwk>;
87 keyBase64?: never;
88 }
89 );
90
91 /**
92 * Deferred accessor for the bound key. The env binding only exists at the
93 * *exec* phase on the deployed Worker, so reading it is behind an Effect
94 * requiring {@link RuntimeContext}. Yield it inside a handler to obtain the
95 * native `CryptoKey`, then use `crypto.subtle` directly.
96 */
97 export type SecretKeyAccessor = Effect.Effect<
98 // The ambient global type, matching InferEnv's SecretKeyBinding mapping:
99 // resolves to @cloudflare/workers-types' CryptoKey inside a Worker program
100 // and to the platform CryptoKey elsewhere.
101 CryptoKey,
102 never,
103 RuntimeContext
104 >;
105
106 /** The resolved (plain, non-Redacted) binding payload carried on a {@link SecretKeyBinding}. */
107 export interface SecretKeyPayload {
108 format: SecretKeyFormat;
109 algorithm: SecretKeyAlgorithm;
110 usages: SecretKeyUsage[];
111 keyBase64?: string;
112 keyJwk?: SecretKeyJwk;
113 }
114
115 const unwrap = <A>(value: A | Redacted.Redacted<A> | undefined): A | undefined =>
116 value === undefined ? undefined : Redacted.isRedacted(value) ? Redacted.value(value) : value;
117
118 /**
119 * A Cloudflare Workers Secret Key binding — key material uploaded once and
120 * exposed to the Worker as a native, non-extractable
121 * [`CryptoKey`](https://developers.cloudflare.com/workers/runtime-apis/bindings/secret-key/).
122 * The Worker can sign, verify, encrypt, or decrypt with the key via
123 * `crypto.subtle`, but can never read the raw key material back out.
124 *
125 * `SecretKey` is a single value that is at once the `Binding.Service` tag, the
126 * callable that produces a {@link SecretKeyBinding}, and the type. Declare it
127 * on a Worker's `env` (it flows through `InferEnv` → the native `CryptoKey`)
128 * or `yield*` it inside an Effect-native Worker to attach the binding and
129 * obtain a deferred {@link SecretKeyAccessor}.
130 *
131 * ### Binding inside an Effect-native Worker
132 * **Example:** HMAC sign and verify
133 * ```typescript
134 * Cloudflare.Worker(
135 * "SignerWorker",
136 * { main: import.meta.url },
137 * Effect.gen(function* () {
138 * // Attaches the binding to this Worker AND returns a deferred accessor.
139 * const hmacKey = yield* Cloudflare.Workers.SecretKey("HMAC_KEY", {
140 * format: "raw",
141 * algorithm: { name: "HMAC", hash: "SHA-256" },
142 * usages: ["sign", "verify"],
143 * keyBase64: "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=",
144 * });
145 *
146 * return {
147 * fetch: Effect.gen(function* () {
148 * const key = yield* hmacKey;
149 * const data = new TextEncoder().encode("hello");
150 * const signature = yield* Effect.promise(() =>
151 * crypto.subtle.sign("HMAC", key, data),
152 * );
153 * const valid = yield* Effect.promise(() =>
154 * crypto.subtle.verify("HMAC", key, signature, data),
155 * );
156 * return HttpServerResponse.json({ valid });
157 * }),
158 * };
159 * }).pipe(Effect.provide(Cloudflare.Workers.SecretKeyBinding)),
160 * );
161 * ```
162 *
163 * **Example:** JSON Web Key format
164 * ```typescript
165 * const jwkKey = yield* Cloudflare.Workers.SecretKey("HMAC_KEY_JWK", {
166 * format: "jwk",
167 * algorithm: { name: "HMAC", hash: "SHA-256" },
168 * usages: ["sign", "verify"],
169 * keyJwk: {
170 * kty: "oct",
171 * k: "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",
172 * alg: "HS256",
173 * },
174 * });
175 * ```
176 *
177 * ### Declaring on a Worker's env
178 * **Example:** Async (non-Effect) Worker
179 * ```typescript
180 * export const Worker = Cloudflare.Worker("Worker", {
181 * main: "./src/worker.ts",
182 * env: {
183 * HMAC_KEY: Cloudflare.Workers.SecretKey("HMAC_KEY", {
184 * format: "raw",
185 * algorithm: { name: "HMAC", hash: "SHA-256" },
186 * usages: ["sign", "verify"],
187 * keyBase64: Redacted.make("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="),
188 * }),
189 * },
190 * });
191 *
192 * export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>;
193 * // { HMAC_KEY: CryptoKey } — the native runtime binding
194 *
195 * // worker.ts
196 * export default {
197 * fetch: async (req: Request, env: WorkerEnv) => {
198 * const signature = await crypto.subtle.sign(
199 * "HMAC",
200 * env.HMAC_KEY,
201 * new TextEncoder().encode("hello"),
202 * );
203 * return new Response(btoa(String.fromCharCode(...new Uint8Array(signature))));
204 * },
205 * };
206 * ```
207 *
208 * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/secret-key/
209 *
210 * @binding
211 * @product Workers
212 * @category Workers & Compute
213 */
214 export interface SecretKey extends Binding.Service<SecretKey, TypeId, SecretKeyAccessor> {
215 /**
216 * @param name Binding name (logical id) — the `env` key it resolves to.
217 * @param props Key format, algorithm, usages, and the key material.
218 */
219 (name: string, props: SecretKeyProps): SecretKeyBinding;
220 }
221
222 export const SecretKey = Binding.Service<SecretKey, SecretKeyPayload>({
223 id: TypeId,
224 defaultName: "SECRET_KEY",
225 parse: (name: string, props: SecretKeyProps) => ({
226 name,
227 format: props.format,
228 algorithm: props.algorithm,
229 usages: [...props.usages],
230 // The wire shape is plain — Redacted key material is unwrapped at bind
231 // time (same convention as Redacted env values → `secret_text`).
232 keyBase64: unwrap(props.keyBase64),
233 keyJwk: unwrap(props.keyJwk),
234 }),
235 toWorkerBinding: (binding) => ({
236 type: "secret_key",
237 name: binding.name,
238 format: binding.format,
239 algorithm: binding.algorithm,
240 usages: binding.usages,
241 keyBase64: binding.keyBase64,
242 keyJwk: binding.keyJwk,
243 }),
244 });
245
246 export const isSecretKey = (value: unknown): value is SecretKeyBinding =>
247 Binding.isBinding(value) && value.kind === TypeId;