@hot-updater/aws 1.2.0-rc.5 → 1.2.0-rc.50

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.
package/dist/index.mjs CHANGED
@@ -1,11 +1,10 @@
1
1
  import { CreateTableCommand, DescribeTableCommand, DescribeTimeToLiveCommand, DynamoDBClient, UpdateTimeToLiveCommand, waitUntilTableExists } from "@aws-sdk/client-dynamodb";
2
- import { BUNDLE_STORAGE_PREFIX, CONTENT_ADDRESSED_ASSET_PREFIX, createEngineDatabase, createKvAdapter, createStorageAdapter, createStorageKeyBuilder, createStorageUri, migrateCoreSchema, parseStorageUri } from "@hot-updater/plugin-core";
2
+ import { BUNDLE_STORAGE_PREFIX, CONTENT_ADDRESSED_ASSET_PREFIX, createEngineDatabase, createKvAdapter, migrateCoreSchema, resolveLazy } from "@hot-updater/plugin-core";
3
3
  import { CloudFrontClient, CreateInvalidationCommand, GetInvalidationCommand } from "@aws-sdk/client-cloudfront";
4
4
  import { BatchGetCommand, BatchWriteCommand, DynamoDBDocumentClient, QueryCommand, TransactWriteCommand } from "@aws-sdk/lib-dynamodb";
5
5
  import { SSM } from "@aws-sdk/client-ssm";
6
6
  import { getSignedUrl } from "@aws-sdk/cloudfront-signer";
7
- import { DeleteObjectCommand, DeleteObjectsCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, S3Client } from "@aws-sdk/client-s3";
8
- import { Upload } from "@aws-sdk/lib-storage";
7
+ import { createS3Storage } from "@hot-updater/storage-s3";
9
8
  import { randomUUID } from "node:crypto";
10
9
  //#region src/cloudFrontInvalidation.ts
11
10
  const DEFAULT_POLL_INTERVAL_MS = 2e3;
@@ -314,10 +313,30 @@ async apply() {
314
313
  };
315
314
  };
316
315
  //#endregion
316
+ //#region src/lazyCredentials.ts
317
+ /**
318
+ * `credentials` as the AWS SDK takes them: access keys with a lazy field
319
+ * become a provider, which the SDK calls once, on its first request.
320
+ */
321
+ const toSdkCredentials = (credentials) => {
322
+ if (credentials === void 0 || typeof credentials === "function") return credentials;
323
+ const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
324
+ if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
325
+ return async () => ({
326
+ ...rest,
327
+ accessKeyId: await resolveLazy(accessKeyId),
328
+ secretAccessKey: await resolveLazy(secretAccessKey),
329
+ ...sessionToken === void 0 ? {} : { sessionToken: await resolveLazy(sessionToken) }
330
+ });
331
+ };
332
+ //#endregion
317
333
  //#region src/dynamoDB.ts
318
334
  /** The DynamoDB client ignores the CloudFront and batching settings. */
319
- const adapterOf = ({ tableName, ...clientConfig }) => {
320
- const client = new DynamoDBClient(clientConfig);
335
+ const adapterOf = ({ tableName, credentials, ...clientConfig }) => {
336
+ const client = new DynamoDBClient({
337
+ ...clientConfig,
338
+ credentials: toSdkCredentials(credentials)
339
+ });
321
340
  const store = createDynamoDBStore({
322
341
  client,
323
342
  tableName
@@ -352,7 +371,10 @@ const marked = (target) => ({ [DATABASE_TARGET]: target });
352
371
  */
353
372
  const dynamoDB = (config) => {
354
373
  const { client, adapter } = adapterOf(config);
355
- const cloudFront = createUpdateRouteInvalidation(config);
374
+ const cloudFront = createUpdateRouteInvalidation({
375
+ ...config,
376
+ credentials: toSdkCredentials(config.credentials)
377
+ });
356
378
  return {
357
379
  ...createEngineDatabase({
358
380
  name: "dynamoDB",
@@ -495,153 +517,17 @@ const cloudFrontDownloadUrl = (config) => {
495
517
  };
496
518
  //#endregion
497
519
  //#region src/s3Storage.ts
498
- /** Devices download right after the update check that returns the URL. */
499
- const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
500
- const isObjectNotFoundError = (error) => error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey");
501
520
  function s3Storage(config) {
502
- const { bucketName, basePath, getDownloadUrl, ...s3Config } = config;
503
- const client = new S3Client(applyS3RuntimeAwsConfig(s3Config));
504
- const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
505
- const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
506
- const getListPrefix = (prefix = "") => {
507
- const normalizedPrefix = prefix.replace(/^\/+|\/+$/g, "");
508
- const value = [normalizedBasePath, normalizedPrefix].filter(Boolean).join("/");
509
- return value ? `${value}/` : "";
510
- };
511
- /**
512
- * The URI `put` returns for the key, or null for a key no `put` writes,
513
- * such as a folder marker that ends in "/".
514
- */
515
- const getListedStorageUri = (key) => {
516
- try {
517
- return createStorageUri({
518
- bucket: bucketName,
519
- key,
520
- protocol: "s3"
521
- });
522
- } catch {
523
- return null;
524
- }
525
- };
526
- const getRelativeKey = (key) => {
527
- if (!normalizedBasePath) return key;
528
- const basePrefix = `${normalizedBasePath}/`;
529
- return key.startsWith(basePrefix) ? key.slice(basePrefix.length) : key;
530
- };
531
- const parseAndValidate = (storageUri) => {
532
- const parsed = parseStorageUri(storageUri, "s3");
533
- if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
534
- return parsed;
535
- };
536
- return createStorageAdapter({
521
+ const { bucketName, basePath, getDownloadUrl, credentials, ...s3Config } = config;
522
+ return createS3Storage({
537
523
  name: "s3Storage",
538
- protocol: "s3",
539
- async listObjects(prefix) {
540
- const objects = [];
541
- let continuationToken;
542
- do {
543
- const response = await client.send(new ListObjectsV2Command({
544
- Bucket: bucketName,
545
- ContinuationToken: continuationToken,
546
- Prefix: getListPrefix(prefix)
547
- }));
548
- for (const object of response.Contents ?? []) {
549
- if (!object.Key) continue;
550
- const storageUri = getListedStorageUri(object.Key);
551
- if (storageUri === null) continue;
552
- objects.push({
553
- key: getRelativeKey(object.Key),
554
- lastModifiedAt: object.LastModified,
555
- size: object.Size ?? 0,
556
- storageUri
557
- });
558
- }
559
- continuationToken = response.NextContinuationToken;
560
- } while (continuationToken);
561
- return objects;
562
- },
563
- async deleteObjects(relativeKeys) {
564
- const keys = relativeKeys.map((key) => getStorageKey(key));
565
- for (let offset = 0; offset < keys.length; offset += 1e3) {
566
- const batch = keys.slice(offset, offset + 1e3);
567
- if (batch.length === 0) continue;
568
- const response = await client.send(new DeleteObjectsCommand({
569
- Bucket: bucketName,
570
- Delete: {
571
- Objects: batch.map((Key) => ({ Key })),
572
- Quiet: true
573
- }
574
- }));
575
- if (response.Errors && response.Errors.length > 0) throw new Error(`Failed to delete ${response.Errors.length} S3 object(s).`);
576
- }
577
- },
578
- async put({ key, body, contentLength, contentType }) {
579
- const storageKey = getStorageKey(key);
580
- const response = await new Upload({
581
- client,
582
- params: {
583
- Body: body,
584
- Bucket: bucketName,
585
- CacheControl: "max-age=31536000",
586
- ...contentLength === void 0 ? {} : { ContentLength: contentLength },
587
- ContentType: contentType,
588
- Key: storageKey
589
- }
590
- }).done();
591
- if (!response.Bucket || !response.Key) throw new Error("Upload failed");
592
- return { storageUri: createStorageUri({
593
- bucket: bucketName,
594
- key: storageKey,
595
- protocol: "s3"
596
- }) };
597
- },
598
- async get({ storageUri }) {
599
- const { key } = parseAndValidate(storageUri);
600
- try {
601
- const response = await client.send(new GetObjectCommand({
602
- Bucket: bucketName,
603
- Key: key
604
- }));
605
- if (!response.Body) return { response: null };
606
- const headers = new Headers();
607
- if (response.ContentType) headers.set("content-type", response.ContentType);
608
- if (response.ContentLength !== void 0) headers.set("content-length", String(response.ContentLength));
609
- return { response: new Response(response.Body.transformToWebStream(), { headers }) };
610
- } catch (error) {
611
- if (isObjectNotFoundError(error)) return { response: null };
612
- throw error;
613
- }
614
- },
615
- async getDownloadUrl({ storageUri }) {
616
- const { key } = parseAndValidate(storageUri);
617
- if (getDownloadUrl) return getDownloadUrl({ storageUri });
618
- const { getSignedUrl } = await import("@aws-sdk/s3-request-presigner");
619
- return { url: await getSignedUrl(client, new GetObjectCommand({
620
- Bucket: bucketName,
621
- Key: key
622
- }), { expiresIn: PRESIGNED_URL_EXPIRES_IN_SECONDS }) };
623
- },
624
- async exists({ storageUri }) {
625
- const { key } = parseAndValidate(storageUri);
626
- try {
627
- await client.send(new HeadObjectCommand({
628
- Bucket: bucketName,
629
- Key: key
630
- }));
631
- return { exists: true };
632
- } catch (error) {
633
- if (isObjectNotFoundError(error)) return { exists: false };
634
- throw error;
635
- }
636
- },
637
- async delete({ storageUri }) {
638
- const { key } = parseAndValidate(storageUri);
639
- await client.send(new DeleteObjectCommand({
640
- Bucket: bucketName,
641
- Key: key
642
- }));
643
- return { deleted: true };
644
- }
524
+ protocol: "s3"
525
+ }, {
526
+ ...applyS3RuntimeAwsConfig(s3Config),
527
+ credentials,
528
+ bucketName,
529
+ basePath,
530
+ getDownloadUrl
645
531
  });
646
532
  }
647
533
  //#endregion
@@ -654,6 +540,22 @@ const MAX_SECRET_ID_LENGTH = 512;
654
540
  /** AWS's limit on a `SecretString`, in bytes. */
655
541
  const MAX_SECRET_BYTES = 65536;
656
542
  const REQUEST_TIMEOUT_MS = 3e4;
543
+ /**
544
+ * How long `set` waits, between reads, for a read to return the version it
545
+ * wrote: Secrets Manager's reads are eventually consistent. About 30 seconds.
546
+ */
547
+ const VERSION_RETRY_DELAYS_MS = [
548
+ 250,
549
+ 500,
550
+ 1e3,
551
+ 2e3,
552
+ 4e3,
553
+ 8e3,
554
+ 15e3
555
+ ];
556
+ const delay = (ms) => new Promise((resolve) => {
557
+ setTimeout(resolve, ms);
558
+ });
657
559
  /** Errors of credentials AWS no longer takes: signing in again fixes them. */
658
560
  const EXPIRED_CREDENTIAL_ERRORS = /* @__PURE__ */ new Set([
659
561
  "ExpiredToken",
@@ -666,9 +568,36 @@ const EXPIRED_CREDENTIAL_ERRORS = /* @__PURE__ */ new Set([
666
568
  ]);
667
569
  /** Errors of the SDK finding no credentials, or an expired SSO session. */
668
570
  const NO_CREDENTIAL_ERRORS = /* @__PURE__ */ new Set(["CredentialsProviderError", "TokenProviderError"]);
669
- const SIGN_IN_HINT = "In CI, set them with aws-actions/configure-aws-credentials; on your machine, run aws sso login --profile <profile> and set AWS_PROFILE=<profile>";
571
+ /** An error of one line each, for a terminal. */
572
+ const failure = (lines, cause) => new Error(lines.join("\n"), cause === void 0 ? void 0 : { cause });
670
573
  const errorName = (error) => error instanceof Error ? error.name : "";
671
574
  const errorMessage = (error) => (error instanceof Error ? error.message : String(error)).replace(/\.+$/u, "");
575
+ /** The access key variables set, which the SDK's chain tries first. */
576
+ const accessKeyVariables = () => {
577
+ if (!process.env["AWS_ACCESS_KEY_ID"] || !process.env["AWS_SECRET_ACCESS_KEY"]) return;
578
+ return process.env["AWS_SESSION_TOKEN"] ? "AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN" : "AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY";
579
+ };
580
+ /**
581
+ * The one step that can fix the credentials the SDK actually used. `AWS_PROFILE`
582
+ * wins over the access key variables in the SDK's chain, so it's looked at
583
+ * first; signing in fixes a profile only when it's an SSO one, as its error
584
+ * says, and fixes nothing when another source is in the way.
585
+ */
586
+ const credentialHint = (error, configured) => {
587
+ if (configured !== void 0) return [`Check the credentials passed to ${NAME}().`];
588
+ const ci = Boolean(process.env["CI"]);
589
+ const profile = process.env["AWS_PROFILE"]?.trim();
590
+ if (profile) return !ci && /\bsso\b/iu.test(errorMessage(error)) ? ["Sign in again:", `aws sso login --profile ${profile}`] : [`Check the AWS profile ${profile}, which AWS_PROFILE selects.`];
591
+ const variables = accessKeyVariables();
592
+ if (variables) return [`Fix or unset ${variables}.`];
593
+ return ci ? ["Set them with aws-actions/configure-aws-credentials."] : ["Sign in, then set AWS_PROFILE:", "aws sso login --profile <profile>"];
594
+ };
595
+ /**
596
+ * The caller's ARN in a refusal, `User: arn:aws:sts::…`, so the message names
597
+ * who to grant. Only that token is read: the rest of AWS's message, such as
598
+ * the resource it refused, stays out.
599
+ */
600
+ const refusedCaller = (message) => /\bUser: (arn:aws[a-z-]*:(?:iam|sts)::\d*:[\w+=,.@/-]*[\w-])/u.exec(message)?.[1];
672
601
  const resolveEndpoint = (endpoint) => {
673
602
  let url;
674
603
  try {
@@ -681,7 +610,11 @@ const resolveEndpoint = (endpoint) => {
681
610
  "127.0.0.1",
682
611
  "[::1]"
683
612
  ])).has(url.hostname);
684
- if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback) || url.username || url.password || url.search || url.hash) throw new Error(`${NAME} endpoint must use HTTPS, or HTTP on a loopback address, without credentials, a query, or a fragment.`);
613
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback) || url.username || url.password || url.search || url.hash) throw failure([
614
+ `${NAME} can't use its endpoint.`,
615
+ "Use HTTPS, or HTTP on a loopback address.",
616
+ "Leave out credentials, a query, and a fragment."
617
+ ]);
685
618
  return url.toString();
686
619
  };
687
620
  /** Masks a value in the CLI's output, which loads `@hot-updater/cli-tools`. */
@@ -698,30 +631,31 @@ const checkCredentials = async (credentials) => {
698
631
  * Secrets from AWS Secrets Manager: each name is the secret
699
632
  * `<prefix><name>`, its `SecretString`, or its `SecretBinary` as base64.
700
633
  * `set` puts a new version of the secret, and creates the secret when it
701
- * does not exist; AWS keeps the versions labeled `AWSCURRENT` and
702
- * `AWSPREVIOUS`, and removes the older ones itself. The AWS SDK loads on
703
- * the first read or write, so a config that only uses `s3Storage` never
704
- * loads it.
634
+ * does not exist, then waits until a read returns that version, so a `get`
635
+ * after it reads the new value; AWS keeps the versions labeled
636
+ * `AWSCURRENT` and `AWSPREVIOUS`, and removes the older ones itself. The
637
+ * AWS SDK loads on the first read or write, so a config that only uses
638
+ * `s3Storage` never loads it.
705
639
  *
706
640
  * @example
707
641
  * secrets: secretsManager({ region: "us-east-1" })
708
642
  */
709
643
  const secretsManager = ({ credentials, endpoint, prefix = "hot-updater/", region }) => {
710
644
  const checkSettings = () => {
711
- if (typeof region !== "string" || !REGION_PATTERN.test(region)) throw new Error(`${NAME} needs an AWS region, such as "us-east-1", and ${JSON.stringify(region)} is not one.`);
645
+ if (typeof region !== "string" || !REGION_PATTERN.test(region)) throw failure([`${NAME} can't use the region ${JSON.stringify(region)}.`, "Set an AWS region, such as \"us-east-1\"."]);
712
646
  if (prefix !== "" && !SECRET_ID_PATTERN.test(prefix)) throw new Error(`${NAME}'s prefix takes letters, digits, and /_+=.@- only.`);
713
647
  };
714
648
  const secretId = (name) => {
715
649
  checkSettings();
716
650
  const id = `${prefix}${name}`;
717
- if (!SECRET_ID_PATTERN.test(name) || id.length > MAX_SECRET_ID_LENGTH) throw new Error(`${NAME} cannot name a secret ${JSON.stringify(id)}: AWS takes up to ${MAX_SECRET_ID_LENGTH} letters, digits, and /_+=.@- characters.`);
651
+ if (!SECRET_ID_PATTERN.test(name) || id.length > MAX_SECRET_ID_LENGTH) throw failure([`${NAME} can't name a secret ${JSON.stringify(id)}.`, `AWS takes up to ${MAX_SECRET_ID_LENGTH} letters, digits, and /_+=.@- characters.`]);
718
652
  return id;
719
653
  };
720
654
  const resolveCredentials = () => {
721
655
  if (credentials !== void 0) return async () => checkCredentials(typeof credentials === "function" ? await credentials() : credentials);
722
656
  const accessKeyId = process.env["AWS_ACCESS_KEY_ID"];
723
657
  const secretAccessKey = process.env["AWS_SECRET_ACCESS_KEY"];
724
- if (Boolean(accessKeyId) !== Boolean(secretAccessKey)) throw new Error(`${NAME} found ${accessKeyId ? "AWS_ACCESS_KEY_ID" : "AWS_SECRET_ACCESS_KEY"} without ${accessKeyId ? "AWS_SECRET_ACCESS_KEY" : "AWS_ACCESS_KEY_ID"} in the environment: set both, or neither to use a profile.`);
658
+ if (Boolean(accessKeyId) !== Boolean(secretAccessKey)) throw failure([`${NAME} found ${accessKeyId ? "AWS_ACCESS_KEY_ID" : "AWS_SECRET_ACCESS_KEY"} without ${accessKeyId ? "AWS_SECRET_ACCESS_KEY" : "AWS_ACCESS_KEY_ID"}.`, "Set both, or neither to use a profile."]);
725
659
  };
726
660
  let opened;
727
661
  const open = () => {
@@ -744,14 +678,17 @@ const secretsManager = ({ credentials, endpoint, prefix = "hot-updater/", region
744
678
  const describeFailure = (verb, id, error, permissions) => {
745
679
  const name = errorName(error);
746
680
  const status = error?.$metadata?.httpStatusCode;
747
- const detail = `${name || "Error"}${status ? ` (${status})` : ""}: ${errorMessage(error)}`;
748
- if (NO_CREDENTIAL_ERRORS.has(name)) return new Error(`${NAME} found no usable AWS credentials to ${verb} ${JSON.stringify(id)} (${errorMessage(error)}). ${SIGN_IN_HINT}.`, { cause: error });
749
- if (EXPIRED_CREDENTIAL_ERRORS.has(name)) return new Error(`AWS Secrets Manager refused the credentials to ${verb} ${JSON.stringify(id)}, ${detail}. They are expired or invalid: sign in again. ${SIGN_IN_HINT}.`, { cause: error });
750
- if (name === "AccessDeniedException") return new Error(`AWS Secrets Manager refused to ${verb} ${JSON.stringify(id)}, ${detail}. The AWS identity needs ${permissions} on it, and on a secret encrypted with a customer managed KMS key, kms:Decrypt to read and kms:GenerateDataKey to store.`, { cause: error });
751
- if (/marked for deletion|scheduled for deletion/iu.test(errorMessage(error))) return new Error(`AWS Secrets Manager cannot ${verb} ${JSON.stringify(id)}: it is scheduled for deletion. Restore it with aws secretsmanager restore-secret --secret-id ${id}, or wait until it is deleted.`, { cause: error });
752
- return new Error(`AWS Secrets Manager failed to ${verb} ${JSON.stringify(id)}, ${detail}.`, { cause: error });
681
+ if (NO_CREDENTIAL_ERRORS.has(name)) return failure([`${NAME} found no AWS credentials.`, ...credentialHint(error, credentials)], error);
682
+ if (EXPIRED_CREDENTIAL_ERRORS.has(name)) return failure(["AWS rejected the credentials: expired or invalid.", ...credentialHint(error, credentials)], error);
683
+ if (name === "AccessDeniedException") {
684
+ const key = verb === "read" ? "kms:Decrypt" : "kms:GenerateDataKey";
685
+ return failure([`AWS Secrets Manager refused to ${verb} ${id}.`, `${refusedCaller(errorMessage(error)) ?? "The identity"} needs ${/\bkms\b/iu.test(errorMessage(error)) ? key : permissions} on it.`], error);
686
+ }
687
+ if (/marked for deletion|scheduled for deletion/iu.test(errorMessage(error))) return failure([`${id} is scheduled for deletion. Restore it, or wait until it is gone:`, `aws secretsmanager restore-secret --secret-id ${id}`], error);
688
+ return failure([`AWS Secrets Manager failed to ${verb} ${id}.`, `${name || "Error"}${status ? ` (${status})` : ""}: ${errorMessage(error)}.`], error);
753
689
  };
754
- const read = async ({ sdk, client }, id) => {
690
+ /** The secret's `AWSCURRENT` version and value; undefined without one. */
691
+ const readCurrent = async ({ sdk, client }, id) => {
755
692
  let output;
756
693
  try {
757
694
  output = await client.send(new sdk.GetSecretValueCommand({ SecretId: id }));
@@ -761,7 +698,22 @@ const secretsManager = ({ credentials, endpoint, prefix = "hot-updater/", region
761
698
  }
762
699
  const value = output.SecretString ?? (output.SecretBinary === void 0 ? void 0 : Buffer.from(output.SecretBinary).toString("base64"));
763
700
  await mask([value]);
764
- return value;
701
+ return {
702
+ version: output.VersionId,
703
+ value
704
+ };
705
+ };
706
+ /**
707
+ * Waits until a read of `id` returns `version`, the one `set` wrote, for
708
+ * about 30 seconds: until then, a read may return the previous version,
709
+ * or nothing for a secret just created.
710
+ */
711
+ const waitForVersion = async (client, id, version) => {
712
+ for (const ms of [0, ...VERSION_RETRY_DELAYS_MS]) {
713
+ if (ms > 0) await delay(ms);
714
+ if ((await readCurrent(client, id))?.version === version) return;
715
+ }
716
+ throw failure([`AWS Secrets Manager doesn't return the new version of ${id} yet.`, "Run the same command again."]);
765
717
  };
766
718
  return {
767
719
  name: NAME,
@@ -771,7 +723,7 @@ const secretsManager = ({ credentials, endpoint, prefix = "hot-updater/", region
771
723
  const result = Object.create(null);
772
724
  if (unique.length === 0) return result;
773
725
  const client = await open();
774
- const values = await Promise.all(ids.map((id) => read(client, id)));
726
+ const values = await Promise.all(ids.map(async (id) => (await readCurrent(client, id))?.value));
775
727
  unique.forEach((name, index) => {
776
728
  result[name] = values[index];
777
729
  });
@@ -779,37 +731,41 @@ const secretsManager = ({ credentials, endpoint, prefix = "hot-updater/", region
779
731
  },
780
732
  set: async (name, value) => {
781
733
  const id = secretId(name);
782
- if (typeof value !== "string" || value === "") throw new Error(`${NAME} cannot store an empty ${id}.`);
783
- if (Buffer.byteLength(value, "utf8") > MAX_SECRET_BYTES) throw new Error(`${NAME} cannot store ${id}: AWS takes up to ${MAX_SECRET_BYTES} bytes per secret.`);
734
+ if (typeof value !== "string" || value === "") throw new Error(`${NAME} can't store an empty ${id}.`);
735
+ if (Buffer.byteLength(value, "utf8") > MAX_SECRET_BYTES) throw failure([`${NAME} can't store ${id}.`, `AWS takes up to ${MAX_SECRET_BYTES} bytes per secret.`]);
784
736
  await mask([value]);
785
- const { sdk, client } = await open();
737
+ const opened = await open();
738
+ const { sdk, client } = opened;
786
739
  const token = randomUUID();
787
740
  const put = () => client.send(new sdk.PutSecretValueCommand({
788
741
  ClientRequestToken: token,
789
742
  SecretId: id,
790
743
  SecretString: value
791
744
  }));
792
- try {
793
- await put();
794
- return;
795
- } catch (error) {
796
- if (!(error instanceof sdk.ResourceNotFoundException)) throw describeFailure("write", id, error, "secretsmanager:PutSecretValue");
797
- }
798
- try {
799
- await client.send(new sdk.CreateSecretCommand({
800
- ClientRequestToken: token,
801
- Description: "Stored by Hot Updater.",
802
- Name: id,
803
- SecretString: value
804
- }));
805
- } catch (error) {
806
- if (!(error instanceof sdk.ResourceExistsException)) throw describeFailure("create", id, error, "secretsmanager:CreateSecret");
745
+ /** The version the write made. */
746
+ const write = async () => {
747
+ try {
748
+ return (await put()).VersionId;
749
+ } catch (error) {
750
+ if (!(error instanceof sdk.ResourceNotFoundException)) throw describeFailure("write", id, error, "secretsmanager:PutSecretValue");
751
+ }
807
752
  try {
808
- await put();
753
+ return (await client.send(new sdk.CreateSecretCommand({
754
+ ClientRequestToken: token,
755
+ Description: "Stored by Hot Updater.",
756
+ Name: id,
757
+ SecretString: value
758
+ }))).VersionId;
759
+ } catch (error) {
760
+ if (!(error instanceof sdk.ResourceExistsException)) throw describeFailure("create", id, error, "secretsmanager:CreateSecret");
761
+ }
762
+ try {
763
+ return (await put()).VersionId;
809
764
  } catch (retryError) {
810
765
  throw describeFailure("write", id, retryError, "secretsmanager:PutSecretValue");
811
766
  }
812
- }
767
+ };
768
+ await waitForVersion(opened, id, await write() ?? token);
813
769
  },
814
770
  describe: (name) => `the secret ${JSON.stringify(`${prefix}${name}`)} in AWS Secrets Manager (${region})`
815
771
  };
@@ -6579,10 +6579,30 @@ async apply() {
6579
6579
  };
6580
6580
  };
6581
6581
  //#endregion
6582
+ //#region src/lazyCredentials.ts
6583
+ /**
6584
+ * `credentials` as the AWS SDK takes them: access keys with a lazy field
6585
+ * become a provider, which the SDK calls once, on its first request.
6586
+ */
6587
+ const toSdkCredentials = (credentials) => {
6588
+ if (credentials === void 0 || typeof credentials === "function") return credentials;
6589
+ const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
6590
+ if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
6591
+ return async () => ({
6592
+ ...rest,
6593
+ accessKeyId: await (0, _hot_updater_plugin_core.resolveLazy)(accessKeyId),
6594
+ secretAccessKey: await (0, _hot_updater_plugin_core.resolveLazy)(secretAccessKey),
6595
+ ...sessionToken === void 0 ? {} : { sessionToken: await (0, _hot_updater_plugin_core.resolveLazy)(sessionToken) }
6596
+ });
6597
+ };
6598
+ //#endregion
6582
6599
  //#region src/dynamoDB.ts
6583
6600
  /** The DynamoDB client ignores the CloudFront and batching settings. */
6584
- const adapterOf = ({ tableName, ...clientConfig }) => {
6585
- const client = new _aws_sdk_client_dynamodb.DynamoDBClient(clientConfig);
6601
+ const adapterOf = ({ tableName, credentials, ...clientConfig }) => {
6602
+ const client = new _aws_sdk_client_dynamodb.DynamoDBClient({
6603
+ ...clientConfig,
6604
+ credentials: toSdkCredentials(credentials)
6605
+ });
6586
6606
  const store = createDynamoDBStore({
6587
6607
  client,
6588
6608
  tableName
@@ -6617,7 +6637,10 @@ const marked = (target) => ({ [DATABASE_TARGET]: target });
6617
6637
  */
6618
6638
  const dynamoDB = (config) => {
6619
6639
  const { client, adapter } = adapterOf(config);
6620
- const cloudFront = createUpdateRouteInvalidation(config);
6640
+ const cloudFront = createUpdateRouteInvalidation({
6641
+ ...config,
6642
+ credentials: toSdkCredentials(config.credentials)
6643
+ });
6621
6644
  return {
6622
6645
  ...(0, _hot_updater_plugin_core.createEngineDatabase)({
6623
6646
  name: "dynamoDB",
@@ -7255,6 +7278,33 @@ const buildOriginRequestPolicyConfig = (clientHeaders) => ({
7255
7278
  CookiesConfig: { CookieBehavior: "none" },
7256
7279
  QueryStringsConfig: { QueryStringBehavior: "all" }
7257
7280
  });
7281
+ /**
7282
+ * Server errors CloudFront never caches: by default it keeps a 5xx for ten
7283
+ * seconds, so one 503 of a retryable read would reach every device behind
7284
+ * that edge. No response page replaces the server's own answer.
7285
+ */
7286
+ const HOT_UPDATER_UNCACHED_ERROR_CODES = [
7287
+ 500,
7288
+ 502,
7289
+ 503,
7290
+ 504
7291
+ ];
7292
+ /**
7293
+ * The API reference lists `ResponsePagePath` and `ResponseCode` as optional,
7294
+ * but CloudFront rejects an error response without both elements
7295
+ * (IllegalUpdate: "The specified list of custom error responses does not
7296
+ * exist or is not valid"). Empty elements mean no page replaces the origin's
7297
+ * answer.
7298
+ */
7299
+ const withResponseElements = (response) => ({
7300
+ ...response,
7301
+ ResponsePagePath: response.ResponsePagePath ?? "",
7302
+ ResponseCode: response.ResponseCode ?? ""
7303
+ });
7304
+ const uncachedErrorResponses = () => HOT_UPDATER_UNCACHED_ERROR_CODES.map((ErrorCode) => withResponseElements({
7305
+ ErrorCode,
7306
+ ErrorCachingMinTTL: 0
7307
+ }));
7258
7308
  const READ_ONLY_METHODS = {
7259
7309
  Quantity: 2,
7260
7310
  Items: ["HEAD", "GET"],
@@ -7314,7 +7364,11 @@ const sanitizeDistributionConfig = (distributionConfig) => ({
7314
7364
  CacheBehaviors: distributionConfig.CacheBehaviors ? {
7315
7365
  Quantity: distributionConfig.CacheBehaviors.Quantity,
7316
7366
  Items: (distributionConfig.CacheBehaviors.Items ?? []).map((behavior) => sanitizeCacheBehavior(behavior))
7317
- } : distributionConfig.CacheBehaviors
7367
+ } : distributionConfig.CacheBehaviors,
7368
+ CustomErrorResponses: distributionConfig.CustomErrorResponses ? {
7369
+ Quantity: distributionConfig.CustomErrorResponses.Quantity,
7370
+ Items: distributionConfig.CustomErrorResponses.Items?.map(withResponseElements)
7371
+ } : distributionConfig.CustomErrorResponses
7318
7372
  });
7319
7373
  const buildOriginRequestLambdaAssociations = (functionArn) => ({
7320
7374
  Quantity: 1,
@@ -7431,6 +7485,10 @@ const buildDistributionConfigOverrides = (options) => ({
7431
7485
  sharedCachePolicyId: options.sharedCachePolicyId
7432
7486
  }))
7433
7487
  ]
7488
+ },
7489
+ CustomErrorResponses: {
7490
+ Quantity: HOT_UPDATER_UNCACHED_ERROR_CODES.length,
7491
+ Items: uncachedErrorResponses()
7434
7492
  }
7435
7493
  });
7436
7494
  const applyDistributionConfigOverrides = (distributionConfig, overrides) => {
@@ -7446,6 +7504,8 @@ const applyDistributionConfigOverrides = (distributionConfig, overrides) => {
7446
7504
  } : behavior);
7447
7505
  const origins = mergeOrigins(distributionConfig.Origins?.Items ?? [], overrides.Origins.Items ?? []);
7448
7506
  const cacheBehaviors = mergeCacheBehaviors(distributionConfig.CacheBehaviors?.Items ?? [], cacheBehaviorOverrides);
7507
+ const managedCodes = new Set((overrides.CustomErrorResponses.Items ?? []).map(({ ErrorCode }) => ErrorCode));
7508
+ const errorResponses = [...(distributionConfig.CustomErrorResponses?.Items ?? []).filter(({ ErrorCode }) => !managedCodes.has(ErrorCode)), ...overrides.CustomErrorResponses.Items ?? []];
7449
7509
  return sanitizeDistributionConfig({
7450
7510
  ...distributionConfig,
7451
7511
  Origins: {
@@ -7456,6 +7516,10 @@ const applyDistributionConfigOverrides = (distributionConfig, overrides) => {
7456
7516
  CacheBehaviors: {
7457
7517
  Quantity: cacheBehaviors.length,
7458
7518
  Items: cacheBehaviors
7519
+ },
7520
+ CustomErrorResponses: {
7521
+ Quantity: errorResponses.length,
7522
+ Items: errorResponses
7459
7523
  }
7460
7524
  });
7461
7525
  };
@@ -8419,10 +8483,11 @@ var SSMKeyPairManager = class {
8419
8483
  //#region iac/templates.ts
8420
8484
  /**
8421
8485
  * The config init writes. With the `resources` init set up, it names them,
8422
- * and an account's access keys are read with `secretEnv`, from the
8486
+ * and an account's access keys are read with `secret()`, from the
8423
8487
  * environment and `.env.hotupdater`, then the config's `secrets` adapter.
8424
- * Without them, as the agent scaffold writes it, it reads every value from
8425
- * the environment. A profile or SSO sign-in is each person's own.
8488
+ * Without them, as the agent scaffold writes it before the agent creates the
8489
+ * resources, it reads their names from the environment, where the agent
8490
+ * records them. A profile or SSO sign-in is each person's own.
8426
8491
  */
8427
8492
  const getConfigScaffold = (build, authMode, resources) => {
8428
8493
  const value = (envKey, resolved) => resolved === void 0 ? `process.env.${envKey}!` : JSON.stringify(resolved);
@@ -8478,31 +8543,19 @@ const awsOptions = {
8478
8543
  };`.trim()
8479
8544
  }];
8480
8545
  break;
8481
- case "account":
8482
- helperStatements = [{
8483
- name: "awsOptions",
8484
- strategy: "merge-object",
8485
- replaceIncompatibleProperties: ["credentials"],
8486
- code: resources === void 0 ? `
8546
+ case "account": helperStatements = [{
8547
+ name: "awsOptions",
8548
+ strategy: "merge-object",
8549
+ replaceIncompatibleProperties: ["credentials"],
8550
+ code: `
8487
8551
  const awsOptions = {
8488
8552
  region: ${region},
8489
8553
  credentials: {
8490
- accessKeyId: process.env.HOT_UPDATER_S3_ACCESS_KEY_ID!,
8491
- secretAccessKey: process.env.HOT_UPDATER_S3_SECRET_ACCESS_KEY!,
8492
- },
8493
- };`.trim() : `
8494
- const awsOptions = {
8495
- region: ${region},
8496
- credentials: async () => {
8497
- const env = await deploySecrets();
8498
- return {
8499
- accessKeyId: env.HOT_UPDATER_S3_ACCESS_KEY_ID,
8500
- secretAccessKey: env.HOT_UPDATER_S3_SECRET_ACCESS_KEY,
8501
- };
8554
+ accessKeyId: secret("HOT_UPDATER_S3_ACCESS_KEY_ID"),
8555
+ secretAccessKey: secret("HOT_UPDATER_S3_SECRET_ACCESS_KEY"),
8502
8556
  },
8503
8557
  };`.trim()
8504
- }];
8505
- if (resources !== void 0) helperStatements.unshift((0, _hot_updater_cli_tools.secretEnvHelper)("deploySecrets", ["HOT_UPDATER_S3_ACCESS_KEY_ID", "HOT_UPDATER_S3_SECRET_ACCESS_KEY"]));
8558
+ }];
8506
8559
  }
8507
8560
  const builder = new _hot_updater_cli_tools.ConfigBuilder().setBuildType(build).setStorage(storageConfig).setDatabase(databaseConfig).setPlugins({
8508
8561
  imports: [{
@@ -8528,9 +8581,9 @@ const awsOptions = {
8528
8581
  named: [authMode.profile ? "fromIni" : "fromNodeProviderChain"]
8529
8582
  });
8530
8583
  break;
8531
- case "account": if (resources !== void 0) builder.addImport({
8584
+ case "account": builder.addImport({
8532
8585
  pkg: "hot-updater",
8533
- named: ["secretEnv"]
8586
+ named: ["secret"]
8534
8587
  });
8535
8588
  }
8536
8589
  return (0, _hot_updater_cli_tools.createHotUpdaterConfigScaffoldFromBuilder)(builder, { helperStatements });
@@ -8781,8 +8834,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
8781
8834
  ...credential === void 0 ? {} : { credential },
8782
8835
  clientPlugins: server.clientPlugins
8783
8836
  });
8784
- _hot_updater_cli_tools.p.log.message(`Next step: ${(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/aws#step-3-add-hotupdater-to-your-project")}`);
8785
- _hot_updater_cli_tools.p.log.success("Done! 🎉");
8837
+ return { nextSteps: [(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/aws#step-3-add-hotupdater-to-your-project")] };
8786
8838
  };
8787
8839
  //#endregion
8788
8840
  exports.LAMBDA_EDGE_TRUST_POLICY = LAMBDA_EDGE_TRUST_POLICY;
@@ -1,4 +1,4 @@
1
- import { RunInitOptions } from "@hot-updater/cli-tools";
1
+ import { RunInitOptions, RunInitResult } from "@hot-updater/cli-tools";
2
2
  //#region iac/dynamodb.d.ts
3
3
  declare const buildDynamoDBCreateTableInput: (tableName: string) => {
4
4
  AttributeDefinitions: {
@@ -219,6 +219,6 @@ declare const prepareDynamoDBDeployment: (input: {
219
219
  readonly region: string;
220
220
  readonly tableName: string;
221
221
  }) => Promise<void>;
222
- declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<void>;
222
+ declare const runInit: ({ build, envFile, secretsEnv }: RunInitOptions) => Promise<RunInitResult>;
223
223
  //#endregion
224
224
  export { LAMBDA_EDGE_TRUST_POLICY, buildDynamoDBBackupInput, buildDynamoDBCreateTableInput, buildDynamoDBPolicy, buildDynamoDBSchemaSettingsInput, buildDynamoDBTimeToLiveInput, buildS3Policy, buildSsmPolicy, initProvider, prepareDynamoDBDeployment, runInit };