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

main
ts 356 lines 13.5 KB
Raw
1 import * as signer from "@distilled.cloud/aws/signer";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11
12 /**
13 * The signing certificate used to sign code. Required for platforms that
14 * sign with an ACM certificate (e.g. `AWSIoTDeviceManagement-SHA256-ECDSA`);
15 * the `AWSLambda-*` platforms use AWS-managed signing material and do not
16 * accept one.
17 */
18 export interface SigningMaterial {
19 /**
20 * The ARN of an AWS Certificate Manager (ACM) certificate used to sign
21 * code.
22 */
23 certificateArn: string;
24 }
25
26 /**
27 * How long a signature produced by this profile remains valid.
28 */
29 export interface SignatureValidityPeriod {
30 /**
31 * The numerical value of the validity period.
32 * @default 135
33 */
34 value?: number;
35
36 /**
37 * The unit of the validity period.
38 * @default "MONTHS"
39 */
40 type?: "DAYS" | "MONTHS" | "YEARS";
41 }
42
43 /**
44 * Overrides applied to the signing configuration of the chosen platform.
45 */
46 export interface SigningPlatformOverrides {
47 /**
48 * Overrides for the platform's default encryption/hash algorithms.
49 */
50 signingConfiguration?: {
51 /** The encryption algorithm used to sign code (`RSA` or `ECDSA`). */
52 encryptionAlgorithm?: "RSA" | "ECDSA";
53 /** The hash algorithm used to sign code (`SHA1` or `SHA256`). */
54 hashAlgorithm?: "SHA1" | "SHA256";
55 };
56
57 /**
58 * The signed image format for the platform, e.g. `JSONEmbedded`.
59 */
60 signingImageFormat?: string;
61 }
62
63 export interface SigningProfileProps {
64 /**
65 * Name of the signing profile. Must match `^[a-zA-Z0-9_]{2,64}$` (letters,
66 * digits, and underscores only — no hyphens). If omitted, a unique
67 * underscore-delimited name is generated. Changing it replaces the profile.
68 */
69 profileName?: string;
70
71 /**
72 * The ID of the signing platform, e.g. `AWSLambda-SHA384-ECDSA` for Lambda
73 * code signing. Changing it replaces the profile.
74 */
75 platformId: string;
76
77 /**
78 * The ACM certificate used to sign code. Only for platforms that sign with
79 * a customer-provided certificate; omit for the `AWSLambda-*` platforms.
80 * Changing it replaces the profile.
81 */
82 signingMaterial?: SigningMaterial;
83
84 /**
85 * How long signatures produced by this profile stay valid.
86 * Changing it replaces the profile.
87 * @default 135 MONTHS
88 */
89 signatureValidityPeriod?: SignatureValidityPeriod;
90
91 /**
92 * Overrides of the platform's default signing configuration.
93 * Changing them replaces the profile.
94 */
95 overrides?: SigningPlatformOverrides;
96
97 /**
98 * Map of key-value pairs for signing, attached as-is to every signing job
99 * started with this profile. Changing them replaces the profile. Rejected
100 * by the `AWSLambda-*` platforms ("Signing parameters should not be
101 * present when using AWSLambda-SHA384-ECDSA platform").
102 */
103 signingParameters?: Record<string, string>;
104
105 /**
106 * User tags to attach to the signing profile. Tags are the only mutable
107 * aspect of a signing profile.
108 */
109 tags?: Record<string, string>;
110 }
111
112 export interface SigningProfile extends Resource<
113 "AWS.Signer.SigningProfile",
114 SigningProfileProps,
115 {
116 /** The name of the signing profile. */
117 profileName: string;
118 /** The ARN of the signing profile (unversioned). */
119 arn: string;
120 /** The current version of the signing profile. */
121 profileVersion: string;
122 /** The ARN of the current signing profile version. */
123 profileVersionArn: string;
124 /** The ID of the signing platform. */
125 platformId: string;
126 /** The status of the signing profile (`Active`, `Canceled`, `Revoked`). */
127 status: string;
128 },
129 never,
130 Providers
131 > {}
132
133 /**
134 * An AWS Signer signing profile — a code-signing template (platform +
135 * signing material + signature validity) used to sign code, most commonly
136 * as the trust anchor for Lambda code signing configs.
137 *
138 * `PutSigningProfile` is create-only in practice (re-putting an existing
139 * name fails with "Profile with name X already exists"), so every property
140 * except tags is immutable — changing one replaces the profile under a new
141 * generated name. On destroy the profile is canceled — AWS retains canceled
142 * profiles (the name stays reserved) and deletes them per its data-retention
143 * policy, so prefer generated names over fixed `profileName`s.
144 *
145 * ### Creating a Signing Profile
146 * **Example:** Lambda Code-Signing Profile
147 * ```typescript
148 * const profile = yield* Signer.SigningProfile("release-profile", {
149 * platformId: "AWSLambda-SHA384-ECDSA",
150 * });
151 * ```
152 *
153 * **Example:** Profile with Signature Validity Period
154 * ```typescript
155 * const profile = yield* Signer.SigningProfile("release-profile", {
156 * platformId: "AWSLambda-SHA384-ECDSA",
157 * signatureValidityPeriod: { value: 12, type: "MONTHS" },
158 * tags: { team: "platform" },
159 * });
160 * ```
161 *
162 * @resource
163 */
164 export const SigningProfile = Resource<SigningProfile>("AWS.Signer.SigningProfile");
165
166 /**
167 * Signer profile names accept only `[a-zA-Z0-9_]` — coerce any other
168 * character (hyphens from stack/stage names, etc.) to an underscore.
169 */
170 const sanitizeProfileName = (name: string): string => name.replace(/[^a-zA-Z0-9_]/g, "_");
171
172 /** Coerce a distilled TagMap (values possibly undefined) to a plain record. */
173 const toTagRecord = (
174 tags: { [key: string]: string | undefined } | undefined,
175 ): Record<string, string> => {
176 const record: Record<string, string> = {};
177 for (const [key, value] of Object.entries(tags ?? {})) {
178 if (value !== undefined) record[key] = value;
179 }
180 return record;
181 };
182
183 export const SigningProfileProvider = () =>
184 Provider.effect(
185 SigningProfile,
186 Effect.gen(function* () {
187 const createName = Effect.fn(function* (
188 id: string,
189 props: Pick<SigningProfileProps, "profileName">,
190 ) {
191 return (
192 props.profileName ??
193 sanitizeProfileName(yield* createPhysicalName({ id, delimiter: "_", maxLength: 64 }))
194 );
195 });
196
197 const getProfile = (profileName: string) =>
198 signer
199 .getSigningProfile({ profileName })
200 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
201
202 const toAttributes = (profileName: string, live: signer.GetSigningProfileResponse) => ({
203 profileName,
204 arn: live.arn!,
205 profileVersion: live.profileVersion!,
206 profileVersionArn: live.profileVersionArn!,
207 platformId: live.platformId!,
208 status: (live.status ?? "Active") as string,
209 });
210
211 return SigningProfile.Provider.of({
212 // Updates only sync tags (all other props replace), so every
213 // identifying attribute — including the version — is update-stable.
214 stables: ["profileName", "arn", "profileVersion", "profileVersionArn", "platformId"],
215
216 list: () =>
217 signer.listSigningProfiles.pages({ includeCanceled: false }).pipe(
218 Stream.runCollect,
219 Effect.map((chunk) =>
220 Array.from(chunk).flatMap((page) =>
221 (page.profiles ?? [])
222 .filter(
223 (p) =>
224 p.profileName != null &&
225 p.arn != null &&
226 p.profileVersion != null &&
227 p.profileVersionArn != null &&
228 p.platformId != null,
229 )
230 .map((p) => ({
231 profileName: p.profileName!,
232 arn: p.arn!,
233 profileVersion: p.profileVersion!,
234 profileVersionArn: p.profileVersionArn!,
235 platformId: p.platformId!,
236 status: (p.status ?? "Active") as string,
237 })),
238 ),
239 ),
240 ),
241
242 read: Effect.fn(function* ({ id, olds, output }) {
243 const profileName = output?.profileName ?? (yield* createName(id, olds ?? {}));
244 const live = yield* getProfile(profileName);
245 // Canceled/revoked profiles cannot sign — treat them as deleted so
246 // a re-deploy publishes a fresh active version.
247 if (live === undefined || live.status !== "Active") return undefined;
248 const attrs = toAttributes(profileName, live);
249 const tags = toTagRecord(live.tags);
250 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
251 }),
252
253 diff: Effect.fn(function* ({ id, news, olds }) {
254 if (!isResolved(news)) return undefined;
255 const oldName = yield* createName(id, olds);
256 const newName = yield* createName(id, news);
257 if (oldName !== newName) return { action: "replace" } as const;
258 // PutSigningProfile is create-only (re-putting an existing name
259 // fails with "already exists"), so every property except tags is
260 // immutable — any change replaces the profile. Mirrors
261 // CloudFormation, where all AWS::Signer::SigningProfile properties
262 // trigger replacement.
263 if (
264 olds.platformId !== news.platformId ||
265 JSON.stringify(olds.signatureValidityPeriod ?? null) !==
266 JSON.stringify(news.signatureValidityPeriod ?? null) ||
267 JSON.stringify(olds.signingParameters ?? null) !==
268 JSON.stringify(news.signingParameters ?? null) ||
269 JSON.stringify(olds.signingMaterial ?? null) !==
270 JSON.stringify(news.signingMaterial ?? null) ||
271 JSON.stringify(olds.overrides ?? null) !== JSON.stringify(news.overrides ?? null)
272 ) {
273 return { action: "replace" } as const;
274 }
275 return undefined;
276 }),
277
278 reconcile: Effect.fn(function* ({ id, news, output, session }) {
279 const profileName = output?.profileName ?? (yield* createName(id, news));
280 const internalTags = yield* createInternalTags(id);
281 const desiredTags = { ...news.tags, ...internalTags };
282
283 // OBSERVE — cloud state is authoritative; output is only a cache
284 let live = yield* getProfile(profileName);
285
286 // ENSURE — PutSigningProfile is create-only in practice: re-putting
287 // an existing name (even Active with identical config) fails with
288 // "Profile with name X already exists". Every property except tags
289 // is therefore immutable and handled by diff → replace; here we
290 // only create when the profile is missing.
291 if (live === undefined) {
292 yield* signer
293 .putSigningProfile({
294 profileName,
295 platformId: news.platformId,
296 signingMaterial: news.signingMaterial,
297 signatureValidityPeriod: news.signatureValidityPeriod,
298 overrides: news.overrides,
299 signingParameters: news.signingParameters,
300 tags: desiredTags,
301 })
302 .pipe(
303 // Race with a concurrent create — fall through to re-observe.
304 Effect.catchTag("SigningProfileAlreadyExists", () => Effect.void),
305 );
306 live = yield* getProfile(profileName);
307 }
308 if (live === undefined) {
309 // Extremely unlikely read-after-write miss; surface loudly.
310 return yield* signer.ResourceNotFoundException.make({
311 message: `signing profile ${profileName} not visible after PutSigningProfile`,
312 });
313 }
314 if (live.status !== "Active") {
315 // The name is tombstoned by a canceled/revoked profile — Signer
316 // reserves canceled names, so the profile cannot be recreated
317 // under this name. Only reachable with a user-fixed profileName
318 // (generated names get a fresh random suffix per instance).
319 return yield* signer.SigningProfileAlreadyExists.make({
320 message: `signing profile ${profileName} exists with status ${live.status}; canceled profile names stay reserved — use a different profileName (or omit it to generate one)`,
321 });
322 }
323
324 // SYNC TAGS — diff against OBSERVED cloud tags (adoption may bring
325 // foreign tags; put only applies tags on first creation).
326 const observedTags = toTagRecord(live.tags);
327 const { upsert, removed } = diffTags(observedTags, desiredTags);
328 if (upsert.length > 0) {
329 yield* signer.tagResource({
330 resourceArn: live.arn!,
331 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
332 });
333 }
334 if (removed.length > 0) {
335 yield* signer.untagResource({
336 resourceArn: live.arn!,
337 tagKeys: removed,
338 });
339 }
340
341 yield* session.note(profileName);
342 return toAttributes(profileName, live);
343 }),
344
345 delete: Effect.fn(function* ({ output }) {
346 // Signing profiles cannot be deleted directly — cancel deactivates
347 // them and AWS deletes canceled profiles per its data-retention
348 // policy. Cancel is idempotent (re-canceling a canceled profile
349 // succeeds); a missing profile is not an error.
350 yield* signer
351 .cancelSigningProfile({ profileName: output.profileName })
352 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
353 }),
354 });
355 }),
356 );