@samebase/alchemy-kit 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,145 @@
1
+ // Seals each secret of a state record with AES-256-GCM, with Web Crypto only.
2
+ //
3
+ // Alchemy writes a secret as `{"__redacted__": X}` in plain text. On write, X becomes
4
+ // `{"__sealed__": "v1.<iv>.<ciphertext>"}`: the IV is 12 random bytes, the ciphertext is the
5
+ // AES-GCM output of `JSON.stringify(X)` with its tag, both base64url. The additional authenticated
6
+ // data is the object key of the record, so a sealed value opens only in its own record. Every
7
+ // other field stays readable JSON.
8
+ import type { webcrypto } from "node:crypto";
9
+ import { REDACTED_MARKER, StateStoreError } from "alchemy/State";
10
+ import * as Effect from "effect/Effect";
11
+
12
+ type CryptoKey = webcrypto.CryptoKey;
13
+
14
+ export const KEY_VARIABLE = "ALCHEMY_GITHUB_STATE_KEY";
15
+
16
+ const SEALED_MARKER = "__sealed__";
17
+ const VERSION = "v1";
18
+
19
+ /** A key of 32 bytes in base64 is 43 characters and one `=`. */
20
+ const KEY_TEXT = /^[A-Za-z0-9+/]{43}=$/;
21
+
22
+ const encoder = new TextEncoder();
23
+ const decoder = new TextDecoder();
24
+
25
+ const fromBase64 = (text: string) => new Uint8Array(Buffer.from(text, "base64url"));
26
+ const toBase64Url = (bytes: Uint8Array) => Buffer.from(bytes).toString("base64url");
27
+
28
+ /**
29
+ * The AES-256-GCM key in `text`, base64 of exactly 32 bytes. It fails when the text is missing or
30
+ * malformed. An error never quotes the text.
31
+ */
32
+ export const parseKey = (text: string | undefined) =>
33
+ Effect.gen(function* () {
34
+ const make = `Make one with \`openssl rand -base64 32\` and keep it as a secret.`;
35
+ const trimmed = text?.trim();
36
+ if (!trimmed) {
37
+ return yield* new StateStoreError({
38
+ message: `GitHub state store: ${KEY_VARIABLE} is not set. ${make}`,
39
+ });
40
+ }
41
+ if (!KEY_TEXT.test(trimmed)) {
42
+ return yield* new StateStoreError({
43
+ message: `GitHub state store: ${KEY_VARIABLE} is not base64 of 32 bytes. ${make}`,
44
+ });
45
+ }
46
+ return yield* Effect.promise(() =>
47
+ crypto.subtle.importKey(
48
+ "raw",
49
+ new Uint8Array(Buffer.from(trimmed, "base64")),
50
+ "AES-GCM",
51
+ false,
52
+ ["encrypt", "decrypt"],
53
+ ),
54
+ );
55
+ });
56
+
57
+ /**
58
+ * `value` with `f` applied to each `__redacted__` field in it. Alchemy reads every object with
59
+ * that field as a secret, also when the object has other fields, so every such field is one here.
60
+ */
61
+ const mapSecrets = (
62
+ value: unknown,
63
+ f: (inner: unknown) => Effect.Effect<unknown, StateStoreError>,
64
+ ): Effect.Effect<unknown, StateStoreError> => {
65
+ if (Array.isArray(value)) return Effect.forEach(value, (item) => mapSecrets(item, f));
66
+ if (typeof value !== "object" || value === null) return Effect.succeed(value);
67
+ return Effect.forEach(Object.entries(value), ([name, item]) =>
68
+ (name === REDACTED_MARKER ? f(item) : mapSecrets(item, f)).pipe(
69
+ Effect.map((mapped) => [name, mapped] as const),
70
+ ),
71
+ ).pipe(Effect.map(Object.fromEntries));
72
+ };
73
+
74
+ /**
75
+ * Rewrites the record `text` with `f` applied to each secret. A record without a secret comes back
76
+ * as the same text.
77
+ */
78
+ const rewrite = (
79
+ objectKey: string,
80
+ text: string,
81
+ f: (inner: unknown) => Effect.Effect<unknown, StateStoreError>,
82
+ ) =>
83
+ Effect.gen(function* () {
84
+ const value: unknown = yield* Effect.try({
85
+ try: (): unknown => JSON.parse(text),
86
+ catch: () => new StateStoreError({ message: `GitHub state store: ${objectKey} is not JSON` }),
87
+ });
88
+ let secrets = 0;
89
+ const mapped = yield* mapSecrets(value, (inner) => {
90
+ secrets++;
91
+ return f(inner);
92
+ });
93
+ return secrets === 0 ? text : JSON.stringify(mapped, null, 2);
94
+ });
95
+
96
+ /** The record `text` with each secret sealed for the record at `objectKey`. */
97
+ export const sealRecord = (key: CryptoKey, objectKey: string, text: string) =>
98
+ rewrite(objectKey, text, (inner) =>
99
+ Effect.promise(async () => {
100
+ const iv = crypto.getRandomValues(new Uint8Array(12));
101
+ const ciphertext = await crypto.subtle.encrypt(
102
+ { name: "AES-GCM", iv, additionalData: encoder.encode(objectKey) },
103
+ key,
104
+ encoder.encode(JSON.stringify(inner)),
105
+ );
106
+ const sealed = `${VERSION}.${toBase64Url(iv)}.${toBase64Url(new Uint8Array(ciphertext))}`;
107
+ return { [SEALED_MARKER]: sealed };
108
+ }),
109
+ );
110
+
111
+ /**
112
+ * The record `text` with each sealed secret opened, as Alchemy wrote it. It fails when a secret is
113
+ * not sealed, or does not open with `key` at `objectKey`.
114
+ */
115
+ export const openRecord = (key: CryptoKey, objectKey: string, text: string) =>
116
+ rewrite(objectKey, text, (inner) =>
117
+ Effect.gen(function* () {
118
+ const sealed =
119
+ typeof inner === "object" && inner !== null && SEALED_MARKER in inner
120
+ ? inner[SEALED_MARKER]
121
+ : undefined;
122
+ const [version, iv, ciphertext, ...rest] =
123
+ typeof sealed === "string" ? sealed.split(".") : [];
124
+ if (version !== VERSION || iv === undefined || ciphertext === undefined || rest.length > 0) {
125
+ return yield* new StateStoreError({
126
+ message: `GitHub state store: ${objectKey} holds a secret that is not sealed by this store`,
127
+ });
128
+ }
129
+ const plaintext = yield* Effect.tryPromise({
130
+ try: () =>
131
+ crypto.subtle.decrypt(
132
+ { name: "AES-GCM", iv: fromBase64(iv), additionalData: encoder.encode(objectKey) },
133
+ key,
134
+ fromBase64(ciphertext),
135
+ ),
136
+ catch: () =>
137
+ new StateStoreError({
138
+ message: `GitHub state store: a secret in ${objectKey} does not open. ${KEY_VARIABLE} is not the key that sealed it, or the record was moved from another place.`,
139
+ }),
140
+ });
141
+ // AES-GCM opened it, so it is the JSON text that `sealRecord` sealed.
142
+ const value: unknown = JSON.parse(decoder.decode(plaintext));
143
+ return value;
144
+ }),
145
+ );