@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 433 lines 15.1 KB
Raw
1 import * as paymentcryptography from "@distilled.cloud/aws/payment-cryptography";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
7 import { toWireDays } from "alchemy/Util/Duration";
8 import type * as Duration from "effect/Duration";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 export interface KeyModesOfUse {
14 /**
15 * Whether the key can be used to encrypt data.
16 * @default false
17 */
18 encrypt?: boolean;
19 /**
20 * Whether the key can be used to decrypt data.
21 * @default false
22 */
23 decrypt?: boolean;
24 /**
25 * Whether the key can be used to wrap other keys.
26 * @default false
27 */
28 wrap?: boolean;
29 /**
30 * Whether the key can be used to unwrap other keys.
31 * @default false
32 */
33 unwrap?: boolean;
34 /**
35 * Whether the key can be used to generate cryptograms and MACs.
36 * @default false
37 */
38 generate?: boolean;
39 /**
40 * Whether the key can be used for signing.
41 * @default false
42 */
43 sign?: boolean;
44 /**
45 * Whether the key can be used to verify signatures, cryptograms and MACs.
46 * @default false
47 */
48 verify?: boolean;
49 /**
50 * Whether the key can be used to derive new keys.
51 * @default false
52 */
53 deriveKey?: boolean;
54 /**
55 * Whether the key usage is unrestricted.
56 * @default false
57 */
58 noRestrictions?: boolean;
59 }
60
61 export interface KeyAttributes {
62 /**
63 * The key algorithm to be used, e.g. `TDES_2KEY`, `AES_128`, `AES_256`,
64 * `RSA_2048`, `ECC_NIST_P256`. Immutable — changing it replaces the key.
65 */
66 keyAlgorithm: string;
67 /**
68 * The type of key, e.g. `SYMMETRIC_KEY`, `ASYMMETRIC_KEY_PAIR`,
69 * `PRIVATE_KEY`, `PUBLIC_KEY`. Immutable — changing it replaces the key.
70 */
71 keyClass: string;
72 /**
73 * The TR-31 cryptographic usage of the key, e.g.
74 * `TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY`, `TR31_M7_HMAC_KEY`,
75 * `TR31_P0_PIN_ENCRYPTION_KEY`. Immutable — changing it replaces the key.
76 */
77 keyUsage: string;
78 /**
79 * The cryptographic operations the key may perform. Immutable — changing
80 * any mode replaces the key.
81 */
82 keyModesOfUse: KeyModesOfUse;
83 }
84
85 export interface KeyProps {
86 /**
87 * The immutable cryptographic attributes of the key: algorithm, class,
88 * usage and modes of use. Changing any of these replaces the key.
89 */
90 keyAttributes: KeyAttributes;
91 /**
92 * Whether the key can be exported out of the service (e.g. via TR-31/TR-34
93 * key blocks). Immutable — changing it replaces the key.
94 * @default false
95 */
96 exportable?: boolean;
97 /**
98 * Whether the key is enabled for cryptographic operations. Toggling this
99 * calls StartKeyUsage/StopKeyUsage in place.
100 * @default true
101 */
102 enabled?: boolean;
103 /**
104 * The algorithm used to compute the key check value, `CMAC` or
105 * `ANSI_X9_24`. Immutable — changing it replaces the key.
106 * @default ANSI_X9_24 for TDES keys, CMAC otherwise
107 */
108 keyCheckValueAlgorithm?: string;
109 /**
110 * For ECC key pairs used in ECDH key agreement, the usage bound to the
111 * derived symmetric key. Immutable — changing it replaces the key.
112 */
113 deriveKeyUsage?: string;
114 /**
115 * The waiting period before a deleted key is permanently removed, e.g.
116 * `"7 days"` or `Duration.days(7)` (`3` - `180` days; sent to the API as
117 * whole days — a bare number is milliseconds). During the window the key
118 * is `DELETE_PENDING` and can be restored.
119 * @default "3 days"
120 */
121 deleteWindow?: Duration.Input;
122 /**
123 * Tags to apply to the key. Merged with internal Alchemy tags.
124 */
125 tags?: Record<string, string>;
126 }
127
128 export interface Key extends Resource<
129 "AWS.PaymentCryptography.Key",
130 KeyProps,
131 {
132 /**
133 * ARN of the key.
134 */
135 keyArn: string;
136 /**
137 * Key state (e.g. `CREATE_COMPLETE`, `DELETE_PENDING`).
138 */
139 keyState: string;
140 /**
141 * Key check value (KCV) used to verify the key material.
142 */
143 keyCheckValue: string;
144 /**
145 * Whether the key is enabled for cryptographic operations.
146 */
147 enabled: boolean;
148 /**
149 * Whether the key material can be exported.
150 */
151 exportable: boolean;
152 },
153 never,
154 Providers
155 > {}
156
157 /**
158 * An AWS Payment Cryptography key — a managed cryptographic key with TR-31
159 * attributes (algorithm, class, usage, modes of use) used for data
160 * encryption, MAC generation/verification, and other payment-domain
161 * cryptographic operations.
162 *
163 * The key ARN is auto-assigned by the service; attach an {@link Alias} for a
164 * stable human-readable identifier. Deletion schedules the key for removal
165 * after a waiting window (minimum 3 days) during which it can be restored.
166 * ### Creating Keys
167 * **Example:** Symmetric data-encryption key
168 * ```typescript
169 * import * as PaymentCryptography from "@alchemy.run/aws/PaymentCryptography";
170 *
171 * const key = yield* PaymentCryptography.Key("DataKey", {
172 * keyAttributes: {
173 * keyAlgorithm: "AES_128",
174 * keyClass: "SYMMETRIC_KEY",
175 * keyUsage: "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
176 * keyModesOfUse: { encrypt: true, decrypt: true, wrap: true, unwrap: true },
177 * },
178 * });
179 * ```
180 *
181 * **Example:** HMAC key for MAC generation and verification
182 * ```typescript
183 * const macKey = yield* PaymentCryptography.Key("MacKey", {
184 * keyAttributes: {
185 * keyAlgorithm: "HMAC_SHA256",
186 * keyClass: "SYMMETRIC_KEY",
187 * keyUsage: "TR31_M7_HMAC_KEY",
188 * keyModesOfUse: { generate: true, verify: true },
189 * },
190 * });
191 * ```
192 *
193 * ### Managing Key State
194 * **Example:** Disable a key without deleting it
195 * ```typescript
196 * const key = yield* PaymentCryptography.Key("DataKey", {
197 * keyAttributes: { ... },
198 * enabled: false,
199 * });
200 * ```
201 *
202 * ### Using Keys at Runtime
203 * **Example:** Encrypt data from a Lambda handler
204 * ```typescript
205 * // init
206 * const encrypt = yield* PaymentCryptography.EncryptData(key);
207 *
208 * return {
209 * fetch: Effect.gen(function* () {
210 * // runtime — PlainText is hex-encoded
211 * const result = yield* encrypt({
212 * PlainText: "31323334353637383930313233343536",
213 * EncryptionAttributes: { Symmetric: { Mode: "CBC" } },
214 * });
215 * return HttpServerResponse.json({ cipherText: result.CipherText });
216 * }),
217 * };
218 * ```
219 *
220 * @resource
221 */
222 export const Key = Resource<Key>("AWS.PaymentCryptography.Key");
223
224 const toWireKeyAttributes = (attributes: KeyAttributes): paymentcryptography.KeyAttributes => ({
225 KeyAlgorithm: attributes.keyAlgorithm,
226 KeyClass: attributes.keyClass,
227 KeyUsage: attributes.keyUsage,
228 KeyModesOfUse: {
229 Encrypt: attributes.keyModesOfUse.encrypt ?? false,
230 Decrypt: attributes.keyModesOfUse.decrypt ?? false,
231 Wrap: attributes.keyModesOfUse.wrap ?? false,
232 Unwrap: attributes.keyModesOfUse.unwrap ?? false,
233 Generate: attributes.keyModesOfUse.generate ?? false,
234 Sign: attributes.keyModesOfUse.sign ?? false,
235 Verify: attributes.keyModesOfUse.verify ?? false,
236 DeriveKey: attributes.keyModesOfUse.deriveKey ?? false,
237 NoRestrictions: attributes.keyModesOfUse.noRestrictions ?? false,
238 },
239 });
240
241 const toAttrs = (key: paymentcryptography.Key): Key["Attributes"] => ({
242 keyArn: key.KeyArn,
243 keyState: key.KeyState,
244 keyCheckValue: key.KeyCheckValue,
245 enabled: key.Enabled,
246 exportable: key.Exportable,
247 });
248
249 const tagsToRecord = (tags: readonly paymentcryptography.Tag[]): Record<string, string> =>
250 Object.fromEntries(tags.map((t) => [t.Key, t.Value ?? ""]));
251
252 const fetchKeyTags = (keyArn: string) =>
253 paymentcryptography.listTagsForResource.items({ ResourceArn: keyArn }).pipe(
254 Stream.runCollect,
255 Effect.map((chunk) => tagsToRecord(Array.from(chunk))),
256 Effect.orElseSucceed(() => ({}) as Record<string, string>),
257 );
258
259 export const KeyProvider = () =>
260 Provider.effect(
261 Key,
262 Effect.gen(function* () {
263 // Fetch a key by ARN; a missing or fully-deleted key observes as
264 // `undefined`. A key inside its deletion window (DELETE_PENDING) is
265 // still returned so reconcile can restore it.
266 const observeKey = Effect.fn(function* (keyArn: string) {
267 const found = yield* paymentcryptography.getKey({ KeyIdentifier: keyArn }).pipe(
268 Effect.map((r) => r.Key),
269 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
270 );
271 if (found === undefined || found.KeyState === "DELETE_COMPLETE") {
272 return undefined;
273 }
274 return found;
275 });
276
277 // Keys have service-assigned identity (no name), so locating one
278 // without a cached ARN falls back to scanning for the internal
279 // Alchemy tags.
280 const findKeyByTags = Effect.fn(function* (id: string) {
281 const summaries = yield* paymentcryptography.listKeys.items({}).pipe(
282 Stream.runCollect,
283 Effect.map((chunk) => Array.from(chunk).filter((k) => k.KeyState !== "DELETE_COMPLETE")),
284 );
285 for (const summary of summaries) {
286 const tags = yield* fetchKeyTags(summary.KeyArn);
287 if (yield* hasAlchemyTags(id, tags)) {
288 return summary.KeyArn;
289 }
290 }
291 return undefined;
292 });
293
294 return Key.Provider.of({
295 stables: ["keyArn", "keyCheckValue"],
296 list: () =>
297 paymentcryptography.listKeys.items({}).pipe(
298 Stream.runCollect,
299 Effect.map((chunk) =>
300 Array.from(chunk)
301 // Keys already inside their deletion window are as deleted
302 // as the API allows — a second DeleteKey is a no-op, so they
303 // are not orphans (mirrors KMS PendingDeletion filtering).
304 .filter((k) => k.KeyState !== "DELETE_PENDING" && k.KeyState !== "DELETE_COMPLETE")
305 .map((k): Key["Attributes"] => ({
306 keyArn: k.KeyArn,
307 keyState: k.KeyState,
308 keyCheckValue: k.KeyCheckValue,
309 enabled: k.Enabled,
310 exportable: k.Exportable,
311 })),
312 ),
313 ),
314 read: Effect.fn(function* ({ id, output }) {
315 const keyArn = output?.keyArn ?? (yield* findKeyByTags(id));
316 if (keyArn === undefined) return undefined;
317 const key = yield* observeKey(keyArn);
318 if (key === undefined) return undefined;
319 const attrs = toAttrs(key);
320 const tags = yield* fetchKeyTags(key.KeyArn);
321 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
322 }),
323 diff: Effect.fn(function* ({ news, olds }) {
324 if (!isResolved(news)) return undefined;
325 const wireOld = toWireKeyAttributes(olds.keyAttributes);
326 const wireNew = toWireKeyAttributes(news.keyAttributes);
327 if (
328 JSON.stringify(wireOld) !== JSON.stringify(wireNew) ||
329 (olds.exportable ?? false) !== (news.exportable ?? false) ||
330 olds.keyCheckValueAlgorithm !== news.keyCheckValueAlgorithm ||
331 olds.deriveKeyUsage !== news.deriveKeyUsage
332 ) {
333 return { action: "replace" } as const;
334 }
335 // fall through: undefined → default update (enabled / tags sync)
336 }),
337 reconcile: Effect.fn(function* ({ id, news, output, session }) {
338 const desiredEnabled = news.enabled ?? true;
339 const internalTags = yield* createInternalTags(id);
340
341 // 1. Observe — output.keyArn is only an identity cache; the cloud
342 // is authoritative. Fall back to a tag scan for adoption after
343 // state-persistence failures.
344 const cachedArn = output?.keyArn ?? (yield* findKeyByTags(id));
345 let key = cachedArn === undefined ? undefined : yield* observeKey(cachedArn);
346
347 // A key inside its deletion window is restored rather than
348 // recreated — the material (and dependent ciphertext) survives.
349 if (key !== undefined && key.KeyState === "DELETE_PENDING") {
350 key = yield* paymentcryptography
351 .restoreKey({ KeyIdentifier: key.KeyArn })
352 .pipe(Effect.map((r) => r.Key));
353 }
354
355 // 2. Ensure — create when missing.
356 if (key === undefined) {
357 key = yield* paymentcryptography
358 .createKey({
359 KeyAttributes: toWireKeyAttributes(news.keyAttributes),
360 Exportable: news.exportable ?? false,
361 Enabled: desiredEnabled,
362 KeyCheckValueAlgorithm: news.keyCheckValueAlgorithm,
363 DeriveKeyUsage: news.deriveKeyUsage,
364 Tags: Object.entries({
365 ...news.tags,
366 ...internalTags,
367 }).map(([Key, Value]) => ({ Key, Value })),
368 })
369 .pipe(Effect.map((r) => r.Key));
370 }
371
372 // 3a. Sync enabled state against OBSERVED cloud state.
373 if (key.Enabled !== desiredEnabled) {
374 key = desiredEnabled
375 ? yield* paymentcryptography
376 .startKeyUsage({ KeyIdentifier: key.KeyArn })
377 .pipe(Effect.map((r) => r.Key))
378 : yield* paymentcryptography
379 .stopKeyUsage({ KeyIdentifier: key.KeyArn })
380 .pipe(Effect.map((r) => r.Key));
381 }
382
383 // 3b. Sync tags — diff against observed cloud tags so adoption
384 // (foreign tags) converges.
385 const observedTags = yield* fetchKeyTags(key.KeyArn);
386 const desiredTags: Record<string, string> = {
387 ...news.tags,
388 ...internalTags,
389 };
390 const { upsert, removed } = diffTags(observedTags, desiredTags);
391 if (upsert.length > 0) {
392 yield* paymentcryptography.tagResource({
393 ResourceArn: key.KeyArn,
394 Tags: upsert,
395 });
396 }
397 if (removed.length > 0) {
398 yield* paymentcryptography.untagResource({
399 ResourceArn: key.KeyArn,
400 TagKeys: removed,
401 });
402 }
403
404 yield* session.note(key.KeyArn);
405 return toAttrs(key);
406 }),
407 delete: Effect.fn(function* ({ output, olds }) {
408 yield* paymentcryptography
409 .deleteKey({
410 KeyIdentifier: output.keyArn,
411 DeleteKeyInDays: toWireDays(olds.deleteWindow) ?? 3,
412 })
413 .pipe(
414 Effect.catchTags({
415 ResourceNotFoundException: () => Effect.void,
416 // A key already scheduled for deletion rejects a second
417 // DeleteKey with a conflict — that is the desired end state,
418 // so treat it as success. Any other conflict is re-raised.
419 ConflictException: (error) =>
420 paymentcryptography.getKey({ KeyIdentifier: output.keyArn }).pipe(
421 Effect.flatMap((r) =>
422 r.Key.KeyState === "DELETE_PENDING" || r.Key.KeyState === "DELETE_COMPLETE"
423 ? Effect.void
424 : Effect.fail(error),
425 ),
426 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
427 ),
428 }),
429 );
430 }),
431 });
432 }),
433 );