import * as signer from "@distilled.cloud/aws/signer";
import { Unowned } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import { createPhysicalName } from "alchemy/PhysicalName";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import type { Providers } from "../Providers.ts";
/**
* The signing certificate used to sign code. Required for platforms that
* sign with an ACM certificate (e.g. `AWSIoTDeviceManagement-SHA256-ECDSA`);
* the `AWSLambda-*` platforms use AWS-managed signing material and do not
* accept one.
*/
export interface SigningMaterial {
/**
* The ARN of an AWS Certificate Manager (ACM) certificate used to sign
* code.
*/
certificateArn: string;
}
/**
* How long a signature produced by this profile remains valid.
*/
export interface SignatureValidityPeriod {
/**
* The numerical value of the validity period.
* @default 135
*/
value?: number;
/**
* The unit of the validity period.
* @default "MONTHS"
*/
type?: "DAYS" | "MONTHS" | "YEARS";
}
/**
* Overrides applied to the signing configuration of the chosen platform.
*/
export interface SigningPlatformOverrides {
/**
* Overrides for the platform's default encryption/hash algorithms.
*/
signingConfiguration?: {
/** The encryption algorithm used to sign code (`RSA` or `ECDSA`). */
encryptionAlgorithm?: "RSA" | "ECDSA";
/** The hash algorithm used to sign code (`SHA1` or `SHA256`). */
hashAlgorithm?: "SHA1" | "SHA256";
};
/**
* The signed image format for the platform, e.g. `JSONEmbedded`.
*/
signingImageFormat?: string;
}
export interface SigningProfileProps {
/**
* Name of the signing profile. Must match `^[a-zA-Z0-9_]{2,64}
.repos/alchemy-effect/packages/aws/src/Signer/SigningProfile.ts at main · sailfork/t3code-github · Sailfork
(letters,
* digits, and underscores only — no hyphens). If omitted, a unique
* underscore-delimited name is generated. Changing it replaces the profile.
*/
profileName?: string;
/**
* The ID of the signing platform, e.g. `AWSLambda-SHA384-ECDSA` for Lambda
* code signing. Changing it replaces the profile.
*/
platformId: string;
/**
* The ACM certificate used to sign code. Only for platforms that sign with
* a customer-provided certificate; omit for the `AWSLambda-*` platforms.
* Changing it replaces the profile.
*/
signingMaterial?: SigningMaterial;
/**
* How long signatures produced by this profile stay valid.
* Changing it replaces the profile.
* @default 135 MONTHS
*/
signatureValidityPeriod?: SignatureValidityPeriod;
/**
* Overrides of the platform's default signing configuration.
* Changing them replaces the profile.
*/
overrides?: SigningPlatformOverrides;
/**
* Map of key-value pairs for signing, attached as-is to every signing job
* started with this profile. Changing them replaces the profile. Rejected
* by the `AWSLambda-*` platforms ("Signing parameters should not be
* present when using AWSLambda-SHA384-ECDSA platform").
*/
signingParameters?: Record<string, string>;
/**
* User tags to attach to the signing profile. Tags are the only mutable
* aspect of a signing profile.
*/
tags?: Record<string, string>;
}
export interface SigningProfile extends Resource<
"AWS.Signer.SigningProfile",
SigningProfileProps,
{
/** The name of the signing profile. */
profileName: string;
/** The ARN of the signing profile (unversioned). */
arn: string;
/** The current version of the signing profile. */
profileVersion: string;
/** The ARN of the current signing profile version. */
profileVersionArn: string;
/** The ID of the signing platform. */
platformId: string;
/** The status of the signing profile (`Active`, `Canceled`, `Revoked`). */
status: string;
},
never,
Providers
> {}
/**
* An AWS Signer signing profile — a code-signing template (platform +
* signing material + signature validity) used to sign code, most commonly
* as the trust anchor for Lambda code signing configs.
*
* `PutSigningProfile` is create-only in practice (re-putting an existing
* name fails with "Profile with name X already exists"), so every property
* except tags is immutable — changing one replaces the profile under a new
* generated name. On destroy the profile is canceled — AWS retains canceled
* profiles (the name stays reserved) and deletes them per its data-retention
* policy, so prefer generated names over fixed `profileName`s.
*
* ### Creating a Signing Profile
* **Example:** Lambda Code-Signing Profile
* ```typescript
* const profile = yield* Signer.SigningProfile("release-profile", {
* platformId: "AWSLambda-SHA384-ECDSA",
* });
* ```
*
* **Example:** Profile with Signature Validity Period
* ```typescript
* const profile = yield* Signer.SigningProfile("release-profile", {
* platformId: "AWSLambda-SHA384-ECDSA",
* signatureValidityPeriod: { value: 12, type: "MONTHS" },
* tags: { team: "platform" },
* });
* ```
*
* @resource
*/
export const SigningProfile = Resource<SigningProfile>("AWS.Signer.SigningProfile");
/**
* Signer profile names accept only `[a-zA-Z0-9_]` — coerce any other
* character (hyphens from stack/stage names, etc.) to an underscore.
*/
const sanitizeProfileName = (name: string): string => name.replace(/[^a-zA-Z0-9_]/g, "_");
/** Coerce a distilled TagMap (values possibly undefined) to a plain record. */
const toTagRecord = (
tags: { [key: string]: string | undefined } | undefined,
): Record<string, string> => {
const record: Record<string, string> = {};
for (const [key, value] of Object.entries(tags ?? {})) {
if (value !== undefined) record[key] = value;
}
return record;
};
export const SigningProfileProvider = () =>
Provider.effect(
SigningProfile,
Effect.gen(function* () {
const createName = Effect.fn(function* (
id: string,
props: Pick<SigningProfileProps, "profileName">,
) {
return (
props.profileName ??
sanitizeProfileName(yield* createPhysicalName({ id, delimiter: "_", maxLength: 64 }))
);
});
const getProfile = (profileName: string) =>
signer
.getSigningProfile({ profileName })
.pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
const toAttributes = (profileName: string, live: signer.GetSigningProfileResponse) => ({
profileName,
arn: live.arn!,
profileVersion: live.profileVersion!,
profileVersionArn: live.profileVersionArn!,
platformId: live.platformId!,
status: (live.status ?? "Active") as string,
});
return SigningProfile.Provider.of({
// Updates only sync tags (all other props replace), so every
// identifying attribute — including the version — is update-stable.
stables: ["profileName", "arn", "profileVersion", "profileVersionArn", "platformId"],
list: () =>
signer.listSigningProfiles.pages({ includeCanceled: false }).pipe(
Stream.runCollect,
Effect.map((chunk) =>
Array.from(chunk).flatMap((page) =>
(page.profiles ?? [])
.filter(
(p) =>
p.profileName != null &&
p.arn != null &&
p.profileVersion != null &&
p.profileVersionArn != null &&
p.platformId != null,
)
.map((p) => ({
profileName: p.profileName!,
arn: p.arn!,
profileVersion: p.profileVersion!,
profileVersionArn: p.profileVersionArn!,
platformId: p.platformId!,
status: (p.status ?? "Active") as string,
})),
),
),
),
read: Effect.fn(function* ({ id, olds, output }) {
const profileName = output?.profileName ?? (yield* createName(id, olds ?? {}));
const live = yield* getProfile(profileName);
// Canceled/revoked profiles cannot sign — treat them as deleted so
// a re-deploy publishes a fresh active version.
if (live === undefined || live.status !== "Active") return undefined;
const attrs = toAttributes(profileName, live);
const tags = toTagRecord(live.tags);
return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
}),
diff: Effect.fn(function* ({ id, news, olds }) {
if (!isResolved(news)) return undefined;
const oldName = yield* createName(id, olds);
const newName = yield* createName(id, news);
if (oldName !== newName) return { action: "replace" } as const;
// PutSigningProfile is create-only (re-putting an existing name
// fails with "already exists"), so every property except tags is
// immutable — any change replaces the profile. Mirrors
// CloudFormation, where all AWS::Signer::SigningProfile properties
// trigger replacement.
if (
olds.platformId !== news.platformId ||
JSON.stringify(olds.signatureValidityPeriod ?? null) !==
JSON.stringify(news.signatureValidityPeriod ?? null) ||
JSON.stringify(olds.signingParameters ?? null) !==
JSON.stringify(news.signingParameters ?? null) ||
JSON.stringify(olds.signingMaterial ?? null) !==
JSON.stringify(news.signingMaterial ?? null) ||
JSON.stringify(olds.overrides ?? null) !== JSON.stringify(news.overrides ?? null)
) {
return { action: "replace" } as const;
}
return undefined;
}),
reconcile: Effect.fn(function* ({ id, news, output, session }) {
const profileName = output?.profileName ?? (yield* createName(id, news));
const internalTags = yield* createInternalTags(id);
const desiredTags = { ...news.tags, ...internalTags };
// OBSERVE — cloud state is authoritative; output is only a cache
let live = yield* getProfile(profileName);
// ENSURE — PutSigningProfile is create-only in practice: re-putting
// an existing name (even Active with identical config) fails with
// "Profile with name X already exists". Every property except tags
// is therefore immutable and handled by diff → replace; here we
// only create when the profile is missing.
if (live === undefined) {
yield* signer
.putSigningProfile({
profileName,
platformId: news.platformId,
signingMaterial: news.signingMaterial,
signatureValidityPeriod: news.signatureValidityPeriod,
overrides: news.overrides,
signingParameters: news.signingParameters,
tags: desiredTags,
})
.pipe(
// Race with a concurrent create — fall through to re-observe.
Effect.catchTag("SigningProfileAlreadyExists", () => Effect.void),
);
live = yield* getProfile(profileName);
}
if (live === undefined) {
// Extremely unlikely read-after-write miss; surface loudly.
return yield* signer.ResourceNotFoundException.make({
message: `signing profile ${profileName} not visible after PutSigningProfile`,
});
}
if (live.status !== "Active") {
// The name is tombstoned by a canceled/revoked profile — Signer
// reserves canceled names, so the profile cannot be recreated
// under this name. Only reachable with a user-fixed profileName
// (generated names get a fresh random suffix per instance).
return yield* signer.SigningProfileAlreadyExists.make({
message: `signing profile ${profileName} exists with status ${live.status}; canceled profile names stay reserved — use a different profileName (or omit it to generate one)`,
});
}
// SYNC TAGS — diff against OBSERVED cloud tags (adoption may bring
// foreign tags; put only applies tags on first creation).
const observedTags = toTagRecord(live.tags);
const { upsert, removed } = diffTags(observedTags, desiredTags);
if (upsert.length > 0) {
yield* signer.tagResource({
resourceArn: live.arn!,
tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
});
}
if (removed.length > 0) {
yield* signer.untagResource({
resourceArn: live.arn!,
tagKeys: removed,
});
}
yield* session.note(profileName);
return toAttributes(profileName, live);
}),
delete: Effect.fn(function* ({ output }) {
// Signing profiles cannot be deleted directly — cancel deactivates
// them and AWS deletes canceled profiles per its data-retention
// policy. Cancel is idempotent (re-canceling a canceled profile
// succeeds); a missing profile is not an error.
yield* signer
.cancelSigningProfile({ profileName: output.profileName })
.pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
}),
});
}),
);
.repos/alchemy-effect/packages/aws/src/Signer/SigningProfile.ts at main · sailfork/t3code-github · Sailfork
(letters,\n * digits, and underscores only — no hyphens). If omitted, a unique\n * underscore-delimited name is generated. Changing it replaces the profile.\n */\n profileName?: string;\n\n /**\n * The ID of the signing platform, e.g. `AWSLambda-SHA384-ECDSA` for Lambda\n * code signing. Changing it replaces the profile.\n */\n platformId: string;\n\n /**\n * The ACM certificate used to sign code. Only for platforms that sign with\n * a customer-provided certificate; omit for the `AWSLambda-*` platforms.\n * Changing it replaces the profile.\n */\n signingMaterial?: SigningMaterial;\n\n /**\n * How long signatures produced by this profile stay valid.\n * Changing it replaces the profile.\n * @default 135 MONTHS\n */\n signatureValidityPeriod?: SignatureValidityPeriod;\n\n /**\n * Overrides of the platform's default signing configuration.\n * Changing them replaces the profile.\n */\n overrides?: SigningPlatformOverrides;\n\n /**\n * Map of key-value pairs for signing, attached as-is to every signing job\n * started with this profile. Changing them replaces the profile. Rejected\n * by the `AWSLambda-*` platforms (\"Signing parameters should not be\n * present when using AWSLambda-SHA384-ECDSA platform\").\n */\n signingParameters?: Record\u003cstring, string>;\n\n /**\n * User tags to attach to the signing profile. Tags are the only mutable\n * aspect of a signing profile.\n */\n tags?: Record\u003cstring, string>;\n}\n\nexport interface SigningProfile extends Resource\u003c\n \"AWS.Signer.SigningProfile\",\n SigningProfileProps,\n {\n /** The name of the signing profile. */\n profileName: string;\n /** The ARN of the signing profile (unversioned). */\n arn: string;\n /** The current version of the signing profile. */\n profileVersion: string;\n /** The ARN of the current signing profile version. */\n profileVersionArn: string;\n /** The ID of the signing platform. */\n platformId: string;\n /** The status of the signing profile (`Active`, `Canceled`, `Revoked`). */\n status: string;\n },\n never,\n Providers\n> {}\n\n/**\n * An AWS Signer signing profile — a code-signing template (platform +\n * signing material + signature validity) used to sign code, most commonly\n * as the trust anchor for Lambda code signing configs.\n *\n * `PutSigningProfile` is create-only in practice (re-putting an existing\n * name fails with \"Profile with name X already exists\"), so every property\n * except tags is immutable — changing one replaces the profile under a new\n * generated name. On destroy the profile is canceled — AWS retains canceled\n * profiles (the name stays reserved) and deletes them per its data-retention\n * policy, so prefer generated names over fixed `profileName`s.\n *\n * ### Creating a Signing Profile\n * **Example:** Lambda Code-Signing Profile\n * ```typescript\n * const profile = yield* Signer.SigningProfile(\"release-profile\", {\n * platformId: \"AWSLambda-SHA384-ECDSA\",\n * });\n * ```\n *\n * **Example:** Profile with Signature Validity Period\n * ```typescript\n * const profile = yield* Signer.SigningProfile(\"release-profile\", {\n * platformId: \"AWSLambda-SHA384-ECDSA\",\n * signatureValidityPeriod: { value: 12, type: \"MONTHS\" },\n * tags: { team: \"platform\" },\n * });\n * ```\n *\n * @resource\n */\nexport const SigningProfile = Resource\u003cSigningProfile>(\"AWS.Signer.SigningProfile\");\n\n/**\n * Signer profile names accept only `[a-zA-Z0-9_]` — coerce any other\n * character (hyphens from stack/stage names, etc.) to an underscore.\n */\nconst sanitizeProfileName = (name: string): string => name.replace(/[^a-zA-Z0-9_]/g, \"_\");\n\n/** Coerce a distilled TagMap (values possibly undefined) to a plain record. */\nconst toTagRecord = (\n tags: { [key: string]: string | undefined } | undefined,\n): Record\u003cstring, string> => {\n const record: Record\u003cstring, string> = {};\n for (const [key, value] of Object.entries(tags ?? {})) {\n if (value !== undefined) record[key] = value;\n }\n return record;\n};\n\nexport const SigningProfileProvider = () =>\n Provider.effect(\n SigningProfile,\n Effect.gen(function* () {\n const createName = Effect.fn(function* (\n id: string,\n props: Pick\u003cSigningProfileProps, \"profileName\">,\n ) {\n return (\n props.profileName ??\n sanitizeProfileName(yield* createPhysicalName({ id, delimiter: \"_\", maxLength: 64 }))\n );\n });\n\n const getProfile = (profileName: string) =>\n signer\n .getSigningProfile({ profileName })\n .pipe(Effect.catchTag(\"ResourceNotFoundException\", () => Effect.undefined));\n\n const toAttributes = (profileName: string, live: signer.GetSigningProfileResponse) => ({\n profileName,\n arn: live.arn!,\n profileVersion: live.profileVersion!,\n profileVersionArn: live.profileVersionArn!,\n platformId: live.platformId!,\n status: (live.status ?? \"Active\") as string,\n });\n\n return SigningProfile.Provider.of({\n // Updates only sync tags (all other props replace), so every\n // identifying attribute — including the version — is update-stable.\n stables: [\"profileName\", \"arn\", \"profileVersion\", \"profileVersionArn\", \"platformId\"],\n\n list: () =>\n signer.listSigningProfiles.pages({ includeCanceled: false }).pipe(\n Stream.runCollect,\n Effect.map((chunk) =>\n Array.from(chunk).flatMap((page) =>\n (page.profiles ?? [])\n .filter(\n (p) =>\n p.profileName != null &&\n p.arn != null &&\n p.profileVersion != null &&\n p.profileVersionArn != null &&\n p.platformId != null,\n )\n .map((p) => ({\n profileName: p.profileName!,\n arn: p.arn!,\n profileVersion: p.profileVersion!,\n profileVersionArn: p.profileVersionArn!,\n platformId: p.platformId!,\n status: (p.status ?? \"Active\") as string,\n })),\n ),\n ),\n ),\n\n read: Effect.fn(function* ({ id, olds, output }) {\n const profileName = output?.profileName ?? (yield* createName(id, olds ?? {}));\n const live = yield* getProfile(profileName);\n // Canceled/revoked profiles cannot sign — treat them as deleted so\n // a re-deploy publishes a fresh active version.\n if (live === undefined || live.status !== \"Active\") return undefined;\n const attrs = toAttributes(profileName, live);\n const tags = toTagRecord(live.tags);\n return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);\n }),\n\n diff: Effect.fn(function* ({ id, news, olds }) {\n if (!isResolved(news)) return undefined;\n const oldName = yield* createName(id, olds);\n const newName = yield* createName(id, news);\n if (oldName !== newName) return { action: \"replace\" } as const;\n // PutSigningProfile is create-only (re-putting an existing name\n // fails with \"already exists\"), so every property except tags is\n // immutable — any change replaces the profile. Mirrors\n // CloudFormation, where all AWS::Signer::SigningProfile properties\n // trigger replacement.\n if (\n olds.platformId !== news.platformId ||\n JSON.stringify(olds.signatureValidityPeriod ?? null) !==\n JSON.stringify(news.signatureValidityPeriod ?? null) ||\n JSON.stringify(olds.signingParameters ?? null) !==\n JSON.stringify(news.signingParameters ?? null) ||\n JSON.stringify(olds.signingMaterial ?? null) !==\n JSON.stringify(news.signingMaterial ?? null) ||\n JSON.stringify(olds.overrides ?? null) !== JSON.stringify(news.overrides ?? null)\n ) {\n return { action: \"replace\" } as const;\n }\n return undefined;\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output, session }) {\n const profileName = output?.profileName ?? (yield* createName(id, news));\n const internalTags = yield* createInternalTags(id);\n const desiredTags = { ...news.tags, ...internalTags };\n\n // OBSERVE — cloud state is authoritative; output is only a cache\n let live = yield* getProfile(profileName);\n\n // ENSURE — PutSigningProfile is create-only in practice: re-putting\n // an existing name (even Active with identical config) fails with\n // \"Profile with name X already exists\". Every property except tags\n // is therefore immutable and handled by diff → replace; here we\n // only create when the profile is missing.\n if (live === undefined) {\n yield* signer\n .putSigningProfile({\n profileName,\n platformId: news.platformId,\n signingMaterial: news.signingMaterial,\n signatureValidityPeriod: news.signatureValidityPeriod,\n overrides: news.overrides,\n signingParameters: news.signingParameters,\n tags: desiredTags,\n })\n .pipe(\n // Race with a concurrent create — fall through to re-observe.\n Effect.catchTag(\"SigningProfileAlreadyExists\", () => Effect.void),\n );\n live = yield* getProfile(profileName);\n }\n if (live === undefined) {\n // Extremely unlikely read-after-write miss; surface loudly.\n return yield* signer.ResourceNotFoundException.make({\n message: `signing profile ${profileName} not visible after PutSigningProfile`,\n });\n }\n if (live.status !== \"Active\") {\n // The name is tombstoned by a canceled/revoked profile — Signer\n // reserves canceled names, so the profile cannot be recreated\n // under this name. Only reachable with a user-fixed profileName\n // (generated names get a fresh random suffix per instance).\n return yield* signer.SigningProfileAlreadyExists.make({\n message: `signing profile ${profileName} exists with status ${live.status}; canceled profile names stay reserved — use a different profileName (or omit it to generate one)`,\n });\n }\n\n // SYNC TAGS — diff against OBSERVED cloud tags (adoption may bring\n // foreign tags; put only applies tags on first creation).\n const observedTags = toTagRecord(live.tags);\n const { upsert, removed } = diffTags(observedTags, desiredTags);\n if (upsert.length > 0) {\n yield* signer.tagResource({\n resourceArn: live.arn!,\n tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),\n });\n }\n if (removed.length > 0) {\n yield* signer.untagResource({\n resourceArn: live.arn!,\n tagKeys: removed,\n });\n }\n\n yield* session.note(profileName);\n return toAttributes(profileName, live);\n }),\n\n delete: Effect.fn(function* ({ output }) {\n // Signing profiles cannot be deleted directly — cancel deactivates\n // them and AWS deletes canceled profiles per its data-retention\n // policy. Cancel is idempotent (re-canceling a canceled profile\n // succeeds); a missing profile is not an error.\n yield* signer\n .cancelSigningProfile({ profileName: output.profileName })\n .pipe(Effect.catchTag(\"ResourceNotFoundException\", () => Effect.void));\n }),\n });\n }),\n );\n","preview":null,"history":null,"version":"f4c18cac99b4ec4779a9955a1d20ecd4990cd05a"},"/_session?shell=1":null}