Skip to content

SecretKey

Source: src/Cloudflare/Workers/SecretKey.ts

A Cloudflare Workers Secret Key binding — key material uploaded once and exposed to the Worker as a native, non-extractable CryptoKey. The Worker can sign, verify, encrypt, or decrypt with the key via crypto.subtle, but can never read the raw key material back out.

SecretKey is a single value that is at once the Binding.Service tag, the callable that produces a SecretKeyBinding, and the type. Declare it on a Worker’s env (it flows through InferEnv → the native CryptoKey) or yield* it inside an Effect-native Worker to attach the binding and obtain a deferred SecretKeyAccessor.

HMAC sign and verify

Cloudflare.Worker(
"SignerWorker",
{ main: import.meta.url },
Effect.gen(function* () {
// Attaches the binding to this Worker AND returns a deferred accessor.
const hmacKey = yield* Cloudflare.Workers.SecretKey("HMAC_KEY", {
format: "raw",
algorithm: { name: "HMAC", hash: "SHA-256" },
usages: ["sign", "verify"],
keyBase64: "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=",
});
return {
fetch: Effect.gen(function* () {
const key = yield* hmacKey;
const data = new TextEncoder().encode("hello");
const signature = yield* Effect.promise(() =>
crypto.subtle.sign("HMAC", key, data),
);
const valid = yield* Effect.promise(() =>
crypto.subtle.verify("HMAC", key, signature, data),
);
return HttpServerResponse.json({ valid });
}),
};
}).pipe(Effect.provide(Cloudflare.Workers.SecretKeyBinding)),
);

JSON Web Key format

const jwkKey = yield* Cloudflare.Workers.SecretKey("HMAC_KEY_JWK", {
format: "jwk",
algorithm: { name: "HMAC", hash: "SHA-256" },
usages: ["sign", "verify"],
keyJwk: {
kty: "oct",
k: "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",
alg: "HS256",
},
});
export const Worker = Cloudflare.Worker("Worker", {
main: "./src/worker.ts",
env: {
HMAC_KEY: Cloudflare.Workers.SecretKey("HMAC_KEY", {
format: "raw",
algorithm: { name: "HMAC", hash: "SHA-256" },
usages: ["sign", "verify"],
keyBase64: Redacted.make("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="),
}),
},
});
export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>;
// { HMAC_KEY: CryptoKey } — the native runtime binding
// worker.ts
export default {
fetch: async (req: Request, env: WorkerEnv) => {
const signature = await crypto.subtle.sign(
"HMAC",
env.HMAC_KEY,
new TextEncoder().encode("hello"),
);
return new Response(btoa(String.fromCharCode(...new Uint8Array(signature))));
},
};