Skip to content
refs
History
101 lines · 3.7 KBRaw
1const IV_BYTES = 12;
2const KEY_BYTES = 32;
3
4/** Where a secret belongs. It is bound into the ciphertext, so a sealed value copied to another row does not open. */
5export interface SecretScope {
6 /** `repo:<id>` for a repository secret, `namespace:<id>` for an organization secret. */
7 readonly owner: string;
8 readonly environment: string | null;
9 readonly name: string;
10}
11
12export interface SealedSecret {
13 readonly ciphertext: string;
14 readonly wrappedKey: string;
15}
16
17export class InvalidMasterKey extends Error {
18 constructor() {
19 super(`CI_SECRETS_KEY must be ${KEY_BYTES} random bytes in base64.`);
20 }
21}
22
23export class SecretUnreadable extends Error {
24 readonly scope: SecretScope;
25
26 constructor(scope: SecretScope) {
27 super(`The secret ${scope.name} could not be opened. The master key or the stored value changed.`);
28 this.scope = scope;
29 }
30}
31
32/**
33 * Envelope encryption with AES-256-GCM. Each secret has its own data key, and the master key only wraps data keys,
34 * so a new master key re-wraps keys without touching values. The scope is the additional data of both layers.
35 */
36export class SecretBox {
37 readonly #master: CryptoKey;
38
39 private constructor(master: CryptoKey) {
40 this.#master = master;
41 }
42
43 static async fromBase64(encoded: string): Promise<SecretBox> {
44 let raw: Uint8Array<ArrayBuffer>;
45 try {
46 raw = fromBase64(encoded);
47 } catch {
48 throw new InvalidMasterKey();
49 }
50 if (raw.length !== KEY_BYTES) throw new InvalidMasterKey();
51 return new SecretBox(await crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt", "decrypt"]));
52 }
53
54 async seal(value: string, scope: SecretScope): Promise<SealedSecret> {
55 const aad = scopeBytes(scope);
56 const dataKey = crypto.getRandomValues(new Uint8Array(KEY_BYTES));
57 const key = await crypto.subtle.importKey("raw", dataKey, "AES-GCM", false, ["encrypt"]);
58 const ciphertext = await encrypt(key, new TextEncoder().encode(value), aad);
59 const wrappedKey = await encrypt(this.#master, dataKey, aad);
60 return { ciphertext: toBase64(ciphertext), wrappedKey: toBase64(wrappedKey) };
61 }
62
63 async open(sealed: SealedSecret, scope: SecretScope): Promise<string> {
64 const aad = scopeBytes(scope);
65 try {
66 const dataKey = await decrypt(this.#master, fromBase64(sealed.wrappedKey), aad);
67 const key = await crypto.subtle.importKey("raw", dataKey, "AES-GCM", false, ["decrypt"]);
68 return new TextDecoder().decode(await decrypt(key, fromBase64(sealed.ciphertext), aad));
69 } catch {
70 throw new SecretUnreadable(scope);
71 }
72 }
73}
74
75async function encrypt(key: CryptoKey, plaintext: Uint8Array<ArrayBuffer>, aad: Uint8Array<ArrayBuffer>): Promise<Uint8Array<ArrayBuffer>> {
76 const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
77 const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad }, key, plaintext));
78 const out = new Uint8Array(IV_BYTES + body.length);
79 out.set(iv);
80 out.set(body, IV_BYTES);
81 return out;
82}
83
84async function decrypt(key: CryptoKey, sealed: Uint8Array<ArrayBuffer>, aad: Uint8Array<ArrayBuffer>): Promise<Uint8Array<ArrayBuffer>> {
85 const iv = sealed.subarray(0, IV_BYTES);
86 return new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv, additionalData: aad }, key, sealed.subarray(IV_BYTES)));
87}
88
89function scopeBytes(scope: SecretScope): Uint8Array<ArrayBuffer> {
90 return new TextEncoder().encode(JSON.stringify(["refs-ci-secret/2", scope.owner, scope.environment, scope.name]));
91}
92
93function toBase64(bytes: Uint8Array): string {
94 let binary = "";
95 for (const byte of bytes) binary += String.fromCharCode(byte);
96 return btoa(binary);
97}
98
99function fromBase64(encoded: string): Uint8Array<ArrayBuffer> {
100 return Uint8Array.from(atob(encoded), (char) => char.charCodeAt(0));
101}