@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.cjs +144 -188
- package/dist/index.d.cts +30 -12
- package/dist/index.d.mts +30 -12
- package/dist/index.mjs +145 -189
- package/dist/init/index.cjs +83 -31
- package/dist/init/index.d.cts +2 -2
- package/dist/init/index.d.mts +2 -2
- package/dist/init/index.mjs +85 -33
- package/dist/lambda/index.cjs +1789 -411
- package/package.json +8 -7
package/dist/index.cjs
CHANGED
|
@@ -5,8 +5,7 @@ let _aws_sdk_client_cloudfront = require("@aws-sdk/client-cloudfront");
|
|
|
5
5
|
let _aws_sdk_lib_dynamodb = require("@aws-sdk/lib-dynamodb");
|
|
6
6
|
let _aws_sdk_client_ssm = require("@aws-sdk/client-ssm");
|
|
7
7
|
let _aws_sdk_cloudfront_signer = require("@aws-sdk/cloudfront-signer");
|
|
8
|
-
let
|
|
9
|
-
let _aws_sdk_lib_storage = require("@aws-sdk/lib-storage");
|
|
8
|
+
let _hot_updater_storage_s3 = require("@hot-updater/storage-s3");
|
|
10
9
|
let node_crypto = require("node:crypto");
|
|
11
10
|
//#region src/cloudFrontInvalidation.ts
|
|
12
11
|
const DEFAULT_POLL_INTERVAL_MS = 2e3;
|
|
@@ -315,10 +314,30 @@ async apply() {
|
|
|
315
314
|
};
|
|
316
315
|
};
|
|
317
316
|
//#endregion
|
|
317
|
+
//#region src/lazyCredentials.ts
|
|
318
|
+
/**
|
|
319
|
+
* `credentials` as the AWS SDK takes them: access keys with a lazy field
|
|
320
|
+
* become a provider, which the SDK calls once, on its first request.
|
|
321
|
+
*/
|
|
322
|
+
const toSdkCredentials = (credentials) => {
|
|
323
|
+
if (credentials === void 0 || typeof credentials === "function") return credentials;
|
|
324
|
+
const { accessKeyId, secretAccessKey, sessionToken, ...rest } = credentials;
|
|
325
|
+
if (typeof accessKeyId !== "function" && typeof secretAccessKey !== "function" && typeof sessionToken !== "function") return credentials;
|
|
326
|
+
return async () => ({
|
|
327
|
+
...rest,
|
|
328
|
+
accessKeyId: await (0, _hot_updater_plugin_core.resolveLazy)(accessKeyId),
|
|
329
|
+
secretAccessKey: await (0, _hot_updater_plugin_core.resolveLazy)(secretAccessKey),
|
|
330
|
+
...sessionToken === void 0 ? {} : { sessionToken: await (0, _hot_updater_plugin_core.resolveLazy)(sessionToken) }
|
|
331
|
+
});
|
|
332
|
+
};
|
|
333
|
+
//#endregion
|
|
318
334
|
//#region src/dynamoDB.ts
|
|
319
335
|
/** The DynamoDB client ignores the CloudFront and batching settings. */
|
|
320
|
-
const adapterOf = ({ tableName, ...clientConfig }) => {
|
|
321
|
-
const client = new _aws_sdk_client_dynamodb.DynamoDBClient(
|
|
336
|
+
const adapterOf = ({ tableName, credentials, ...clientConfig }) => {
|
|
337
|
+
const client = new _aws_sdk_client_dynamodb.DynamoDBClient({
|
|
338
|
+
...clientConfig,
|
|
339
|
+
credentials: toSdkCredentials(credentials)
|
|
340
|
+
});
|
|
322
341
|
const store = createDynamoDBStore({
|
|
323
342
|
client,
|
|
324
343
|
tableName
|
|
@@ -353,7 +372,10 @@ const marked = (target) => ({ [DATABASE_TARGET]: target });
|
|
|
353
372
|
*/
|
|
354
373
|
const dynamoDB = (config) => {
|
|
355
374
|
const { client, adapter } = adapterOf(config);
|
|
356
|
-
const cloudFront = createUpdateRouteInvalidation(
|
|
375
|
+
const cloudFront = createUpdateRouteInvalidation({
|
|
376
|
+
...config,
|
|
377
|
+
credentials: toSdkCredentials(config.credentials)
|
|
378
|
+
});
|
|
357
379
|
return {
|
|
358
380
|
...(0, _hot_updater_plugin_core.createEngineDatabase)({
|
|
359
381
|
name: "dynamoDB",
|
|
@@ -496,153 +518,17 @@ const cloudFrontDownloadUrl = (config) => {
|
|
|
496
518
|
};
|
|
497
519
|
//#endregion
|
|
498
520
|
//#region src/s3Storage.ts
|
|
499
|
-
/** Devices download right after the update check that returns the URL. */
|
|
500
|
-
const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
|
|
501
|
-
const isObjectNotFoundError = (error) => error instanceof Error && (error.name === "NotFound" || error.name === "NoSuchKey");
|
|
502
521
|
function s3Storage(config) {
|
|
503
|
-
const { bucketName, basePath, getDownloadUrl, ...s3Config } = config;
|
|
504
|
-
|
|
505
|
-
const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
|
|
506
|
-
const getStorageKey = (0, _hot_updater_plugin_core.createStorageKeyBuilder)(normalizedBasePath);
|
|
507
|
-
const getListPrefix = (prefix = "") => {
|
|
508
|
-
const normalizedPrefix = prefix.replace(/^\/+|\/+$/g, "");
|
|
509
|
-
const value = [normalizedBasePath, normalizedPrefix].filter(Boolean).join("/");
|
|
510
|
-
return value ? `${value}/` : "";
|
|
511
|
-
};
|
|
512
|
-
/**
|
|
513
|
-
* The URI `put` returns for the key, or null for a key no `put` writes,
|
|
514
|
-
* such as a folder marker that ends in "/".
|
|
515
|
-
*/
|
|
516
|
-
const getListedStorageUri = (key) => {
|
|
517
|
-
try {
|
|
518
|
-
return (0, _hot_updater_plugin_core.createStorageUri)({
|
|
519
|
-
bucket: bucketName,
|
|
520
|
-
key,
|
|
521
|
-
protocol: "s3"
|
|
522
|
-
});
|
|
523
|
-
} catch {
|
|
524
|
-
return null;
|
|
525
|
-
}
|
|
526
|
-
};
|
|
527
|
-
const getRelativeKey = (key) => {
|
|
528
|
-
if (!normalizedBasePath) return key;
|
|
529
|
-
const basePrefix = `${normalizedBasePath}/`;
|
|
530
|
-
return key.startsWith(basePrefix) ? key.slice(basePrefix.length) : key;
|
|
531
|
-
};
|
|
532
|
-
const parseAndValidate = (storageUri) => {
|
|
533
|
-
const parsed = (0, _hot_updater_plugin_core.parseStorageUri)(storageUri, "s3");
|
|
534
|
-
if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
|
|
535
|
-
return parsed;
|
|
536
|
-
};
|
|
537
|
-
return (0, _hot_updater_plugin_core.createStorageAdapter)({
|
|
522
|
+
const { bucketName, basePath, getDownloadUrl, credentials, ...s3Config } = config;
|
|
523
|
+
return (0, _hot_updater_storage_s3.createS3Storage)({
|
|
538
524
|
name: "s3Storage",
|
|
539
|
-
protocol: "s3"
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
ContinuationToken: continuationToken,
|
|
547
|
-
Prefix: getListPrefix(prefix)
|
|
548
|
-
}));
|
|
549
|
-
for (const object of response.Contents ?? []) {
|
|
550
|
-
if (!object.Key) continue;
|
|
551
|
-
const storageUri = getListedStorageUri(object.Key);
|
|
552
|
-
if (storageUri === null) continue;
|
|
553
|
-
objects.push({
|
|
554
|
-
key: getRelativeKey(object.Key),
|
|
555
|
-
lastModifiedAt: object.LastModified,
|
|
556
|
-
size: object.Size ?? 0,
|
|
557
|
-
storageUri
|
|
558
|
-
});
|
|
559
|
-
}
|
|
560
|
-
continuationToken = response.NextContinuationToken;
|
|
561
|
-
} while (continuationToken);
|
|
562
|
-
return objects;
|
|
563
|
-
},
|
|
564
|
-
async deleteObjects(relativeKeys) {
|
|
565
|
-
const keys = relativeKeys.map((key) => getStorageKey(key));
|
|
566
|
-
for (let offset = 0; offset < keys.length; offset += 1e3) {
|
|
567
|
-
const batch = keys.slice(offset, offset + 1e3);
|
|
568
|
-
if (batch.length === 0) continue;
|
|
569
|
-
const response = await client.send(new _aws_sdk_client_s3.DeleteObjectsCommand({
|
|
570
|
-
Bucket: bucketName,
|
|
571
|
-
Delete: {
|
|
572
|
-
Objects: batch.map((Key) => ({ Key })),
|
|
573
|
-
Quiet: true
|
|
574
|
-
}
|
|
575
|
-
}));
|
|
576
|
-
if (response.Errors && response.Errors.length > 0) throw new Error(`Failed to delete ${response.Errors.length} S3 object(s).`);
|
|
577
|
-
}
|
|
578
|
-
},
|
|
579
|
-
async put({ key, body, contentLength, contentType }) {
|
|
580
|
-
const storageKey = getStorageKey(key);
|
|
581
|
-
const response = await new _aws_sdk_lib_storage.Upload({
|
|
582
|
-
client,
|
|
583
|
-
params: {
|
|
584
|
-
Body: body,
|
|
585
|
-
Bucket: bucketName,
|
|
586
|
-
CacheControl: "max-age=31536000",
|
|
587
|
-
...contentLength === void 0 ? {} : { ContentLength: contentLength },
|
|
588
|
-
ContentType: contentType,
|
|
589
|
-
Key: storageKey
|
|
590
|
-
}
|
|
591
|
-
}).done();
|
|
592
|
-
if (!response.Bucket || !response.Key) throw new Error("Upload failed");
|
|
593
|
-
return { storageUri: (0, _hot_updater_plugin_core.createStorageUri)({
|
|
594
|
-
bucket: bucketName,
|
|
595
|
-
key: storageKey,
|
|
596
|
-
protocol: "s3"
|
|
597
|
-
}) };
|
|
598
|
-
},
|
|
599
|
-
async get({ storageUri }) {
|
|
600
|
-
const { key } = parseAndValidate(storageUri);
|
|
601
|
-
try {
|
|
602
|
-
const response = await client.send(new _aws_sdk_client_s3.GetObjectCommand({
|
|
603
|
-
Bucket: bucketName,
|
|
604
|
-
Key: key
|
|
605
|
-
}));
|
|
606
|
-
if (!response.Body) return { response: null };
|
|
607
|
-
const headers = new Headers();
|
|
608
|
-
if (response.ContentType) headers.set("content-type", response.ContentType);
|
|
609
|
-
if (response.ContentLength !== void 0) headers.set("content-length", String(response.ContentLength));
|
|
610
|
-
return { response: new Response(response.Body.transformToWebStream(), { headers }) };
|
|
611
|
-
} catch (error) {
|
|
612
|
-
if (isObjectNotFoundError(error)) return { response: null };
|
|
613
|
-
throw error;
|
|
614
|
-
}
|
|
615
|
-
},
|
|
616
|
-
async getDownloadUrl({ storageUri }) {
|
|
617
|
-
const { key } = parseAndValidate(storageUri);
|
|
618
|
-
if (getDownloadUrl) return getDownloadUrl({ storageUri });
|
|
619
|
-
const { getSignedUrl } = await import("@aws-sdk/s3-request-presigner");
|
|
620
|
-
return { url: await getSignedUrl(client, new _aws_sdk_client_s3.GetObjectCommand({
|
|
621
|
-
Bucket: bucketName,
|
|
622
|
-
Key: key
|
|
623
|
-
}), { expiresIn: PRESIGNED_URL_EXPIRES_IN_SECONDS }) };
|
|
624
|
-
},
|
|
625
|
-
async exists({ storageUri }) {
|
|
626
|
-
const { key } = parseAndValidate(storageUri);
|
|
627
|
-
try {
|
|
628
|
-
await client.send(new _aws_sdk_client_s3.HeadObjectCommand({
|
|
629
|
-
Bucket: bucketName,
|
|
630
|
-
Key: key
|
|
631
|
-
}));
|
|
632
|
-
return { exists: true };
|
|
633
|
-
} catch (error) {
|
|
634
|
-
if (isObjectNotFoundError(error)) return { exists: false };
|
|
635
|
-
throw error;
|
|
636
|
-
}
|
|
637
|
-
},
|
|
638
|
-
async delete({ storageUri }) {
|
|
639
|
-
const { key } = parseAndValidate(storageUri);
|
|
640
|
-
await client.send(new _aws_sdk_client_s3.DeleteObjectCommand({
|
|
641
|
-
Bucket: bucketName,
|
|
642
|
-
Key: key
|
|
643
|
-
}));
|
|
644
|
-
return { deleted: true };
|
|
645
|
-
}
|
|
525
|
+
protocol: "s3"
|
|
526
|
+
}, {
|
|
527
|
+
...applyS3RuntimeAwsConfig(s3Config),
|
|
528
|
+
credentials,
|
|
529
|
+
bucketName,
|
|
530
|
+
basePath,
|
|
531
|
+
getDownloadUrl
|
|
646
532
|
});
|
|
647
533
|
}
|
|
648
534
|
//#endregion
|
|
@@ -655,6 +541,22 @@ const MAX_SECRET_ID_LENGTH = 512;
|
|
|
655
541
|
/** AWS's limit on a `SecretString`, in bytes. */
|
|
656
542
|
const MAX_SECRET_BYTES = 65536;
|
|
657
543
|
const REQUEST_TIMEOUT_MS = 3e4;
|
|
544
|
+
/**
|
|
545
|
+
* How long `set` waits, between reads, for a read to return the version it
|
|
546
|
+
* wrote: Secrets Manager's reads are eventually consistent. About 30 seconds.
|
|
547
|
+
*/
|
|
548
|
+
const VERSION_RETRY_DELAYS_MS = [
|
|
549
|
+
250,
|
|
550
|
+
500,
|
|
551
|
+
1e3,
|
|
552
|
+
2e3,
|
|
553
|
+
4e3,
|
|
554
|
+
8e3,
|
|
555
|
+
15e3
|
|
556
|
+
];
|
|
557
|
+
const delay = (ms) => new Promise((resolve) => {
|
|
558
|
+
setTimeout(resolve, ms);
|
|
559
|
+
});
|
|
658
560
|
/** Errors of credentials AWS no longer takes: signing in again fixes them. */
|
|
659
561
|
const EXPIRED_CREDENTIAL_ERRORS = /* @__PURE__ */ new Set([
|
|
660
562
|
"ExpiredToken",
|
|
@@ -667,9 +569,36 @@ const EXPIRED_CREDENTIAL_ERRORS = /* @__PURE__ */ new Set([
|
|
|
667
569
|
]);
|
|
668
570
|
/** Errors of the SDK finding no credentials, or an expired SSO session. */
|
|
669
571
|
const NO_CREDENTIAL_ERRORS = /* @__PURE__ */ new Set(["CredentialsProviderError", "TokenProviderError"]);
|
|
670
|
-
|
|
572
|
+
/** An error of one line each, for a terminal. */
|
|
573
|
+
const failure = (lines, cause) => new Error(lines.join("\n"), cause === void 0 ? void 0 : { cause });
|
|
671
574
|
const errorName = (error) => error instanceof Error ? error.name : "";
|
|
672
575
|
const errorMessage = (error) => (error instanceof Error ? error.message : String(error)).replace(/\.+$/u, "");
|
|
576
|
+
/** The access key variables set, which the SDK's chain tries first. */
|
|
577
|
+
const accessKeyVariables = () => {
|
|
578
|
+
if (!process.env["AWS_ACCESS_KEY_ID"] || !process.env["AWS_SECRET_ACCESS_KEY"]) return;
|
|
579
|
+
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";
|
|
580
|
+
};
|
|
581
|
+
/**
|
|
582
|
+
* The one step that can fix the credentials the SDK actually used. `AWS_PROFILE`
|
|
583
|
+
* wins over the access key variables in the SDK's chain, so it's looked at
|
|
584
|
+
* first; signing in fixes a profile only when it's an SSO one, as its error
|
|
585
|
+
* says, and fixes nothing when another source is in the way.
|
|
586
|
+
*/
|
|
587
|
+
const credentialHint = (error, configured) => {
|
|
588
|
+
if (configured !== void 0) return [`Check the credentials passed to ${NAME}().`];
|
|
589
|
+
const ci = Boolean(process.env["CI"]);
|
|
590
|
+
const profile = process.env["AWS_PROFILE"]?.trim();
|
|
591
|
+
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.`];
|
|
592
|
+
const variables = accessKeyVariables();
|
|
593
|
+
if (variables) return [`Fix or unset ${variables}.`];
|
|
594
|
+
return ci ? ["Set them with aws-actions/configure-aws-credentials."] : ["Sign in, then set AWS_PROFILE:", "aws sso login --profile <profile>"];
|
|
595
|
+
};
|
|
596
|
+
/**
|
|
597
|
+
* The caller's ARN in a refusal, `User: arn:aws:sts::…`, so the message names
|
|
598
|
+
* who to grant. Only that token is read: the rest of AWS's message, such as
|
|
599
|
+
* the resource it refused, stays out.
|
|
600
|
+
*/
|
|
601
|
+
const refusedCaller = (message) => /\bUser: (arn:aws[a-z-]*:(?:iam|sts)::\d*:[\w+=,.@/-]*[\w-])/u.exec(message)?.[1];
|
|
673
602
|
const resolveEndpoint = (endpoint) => {
|
|
674
603
|
let url;
|
|
675
604
|
try {
|
|
@@ -682,7 +611,11 @@ const resolveEndpoint = (endpoint) => {
|
|
|
682
611
|
"127.0.0.1",
|
|
683
612
|
"[::1]"
|
|
684
613
|
])).has(url.hostname);
|
|
685
|
-
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback) || url.username || url.password || url.search || url.hash) throw
|
|
614
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback) || url.username || url.password || url.search || url.hash) throw failure([
|
|
615
|
+
`${NAME} can't use its endpoint.`,
|
|
616
|
+
"Use HTTPS, or HTTP on a loopback address.",
|
|
617
|
+
"Leave out credentials, a query, and a fragment."
|
|
618
|
+
]);
|
|
686
619
|
return url.toString();
|
|
687
620
|
};
|
|
688
621
|
/** Masks a value in the CLI's output, which loads `@hot-updater/cli-tools`. */
|
|
@@ -699,30 +632,31 @@ const checkCredentials = async (credentials) => {
|
|
|
699
632
|
* Secrets from AWS Secrets Manager: each name is the secret
|
|
700
633
|
* `<prefix><name>`, its `SecretString`, or its `SecretBinary` as base64.
|
|
701
634
|
* `set` puts a new version of the secret, and creates the secret when it
|
|
702
|
-
* does not exist
|
|
703
|
-
*
|
|
704
|
-
*
|
|
705
|
-
* loads
|
|
635
|
+
* does not exist, then waits until a read returns that version, so a `get`
|
|
636
|
+
* after it reads the new value; AWS keeps the versions labeled
|
|
637
|
+
* `AWSCURRENT` and `AWSPREVIOUS`, and removes the older ones itself. The
|
|
638
|
+
* AWS SDK loads on the first read or write, so a config that only uses
|
|
639
|
+
* `s3Storage` never loads it.
|
|
706
640
|
*
|
|
707
641
|
* @example
|
|
708
642
|
* secrets: secretsManager({ region: "us-east-1" })
|
|
709
643
|
*/
|
|
710
644
|
const secretsManager = ({ credentials, endpoint, prefix = "hot-updater/", region }) => {
|
|
711
645
|
const checkSettings = () => {
|
|
712
|
-
if (typeof region !== "string" || !REGION_PATTERN.test(region)) throw
|
|
646
|
+
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\"."]);
|
|
713
647
|
if (prefix !== "" && !SECRET_ID_PATTERN.test(prefix)) throw new Error(`${NAME}'s prefix takes letters, digits, and /_+=.@- only.`);
|
|
714
648
|
};
|
|
715
649
|
const secretId = (name) => {
|
|
716
650
|
checkSettings();
|
|
717
651
|
const id = `${prefix}${name}`;
|
|
718
|
-
if (!SECRET_ID_PATTERN.test(name) || id.length > MAX_SECRET_ID_LENGTH) throw
|
|
652
|
+
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.`]);
|
|
719
653
|
return id;
|
|
720
654
|
};
|
|
721
655
|
const resolveCredentials = () => {
|
|
722
656
|
if (credentials !== void 0) return async () => checkCredentials(typeof credentials === "function" ? await credentials() : credentials);
|
|
723
657
|
const accessKeyId = process.env["AWS_ACCESS_KEY_ID"];
|
|
724
658
|
const secretAccessKey = process.env["AWS_SECRET_ACCESS_KEY"];
|
|
725
|
-
if (Boolean(accessKeyId) !== Boolean(secretAccessKey)) throw
|
|
659
|
+
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."]);
|
|
726
660
|
};
|
|
727
661
|
let opened;
|
|
728
662
|
const open = () => {
|
|
@@ -745,14 +679,17 @@ const secretsManager = ({ credentials, endpoint, prefix = "hot-updater/", region
|
|
|
745
679
|
const describeFailure = (verb, id, error, permissions) => {
|
|
746
680
|
const name = errorName(error);
|
|
747
681
|
const status = error?.$metadata?.httpStatusCode;
|
|
748
|
-
|
|
749
|
-
if (
|
|
750
|
-
if (
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
682
|
+
if (NO_CREDENTIAL_ERRORS.has(name)) return failure([`${NAME} found no AWS credentials.`, ...credentialHint(error, credentials)], error);
|
|
683
|
+
if (EXPIRED_CREDENTIAL_ERRORS.has(name)) return failure(["AWS rejected the credentials: expired or invalid.", ...credentialHint(error, credentials)], error);
|
|
684
|
+
if (name === "AccessDeniedException") {
|
|
685
|
+
const key = verb === "read" ? "kms:Decrypt" : "kms:GenerateDataKey";
|
|
686
|
+
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);
|
|
687
|
+
}
|
|
688
|
+
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);
|
|
689
|
+
return failure([`AWS Secrets Manager failed to ${verb} ${id}.`, `${name || "Error"}${status ? ` (${status})` : ""}: ${errorMessage(error)}.`], error);
|
|
754
690
|
};
|
|
755
|
-
|
|
691
|
+
/** The secret's `AWSCURRENT` version and value; undefined without one. */
|
|
692
|
+
const readCurrent = async ({ sdk, client }, id) => {
|
|
756
693
|
let output;
|
|
757
694
|
try {
|
|
758
695
|
output = await client.send(new sdk.GetSecretValueCommand({ SecretId: id }));
|
|
@@ -762,7 +699,22 @@ const secretsManager = ({ credentials, endpoint, prefix = "hot-updater/", region
|
|
|
762
699
|
}
|
|
763
700
|
const value = output.SecretString ?? (output.SecretBinary === void 0 ? void 0 : Buffer.from(output.SecretBinary).toString("base64"));
|
|
764
701
|
await mask([value]);
|
|
765
|
-
return
|
|
702
|
+
return {
|
|
703
|
+
version: output.VersionId,
|
|
704
|
+
value
|
|
705
|
+
};
|
|
706
|
+
};
|
|
707
|
+
/**
|
|
708
|
+
* Waits until a read of `id` returns `version`, the one `set` wrote, for
|
|
709
|
+
* about 30 seconds: until then, a read may return the previous version,
|
|
710
|
+
* or nothing for a secret just created.
|
|
711
|
+
*/
|
|
712
|
+
const waitForVersion = async (client, id, version) => {
|
|
713
|
+
for (const ms of [0, ...VERSION_RETRY_DELAYS_MS]) {
|
|
714
|
+
if (ms > 0) await delay(ms);
|
|
715
|
+
if ((await readCurrent(client, id))?.version === version) return;
|
|
716
|
+
}
|
|
717
|
+
throw failure([`AWS Secrets Manager doesn't return the new version of ${id} yet.`, "Run the same command again."]);
|
|
766
718
|
};
|
|
767
719
|
return {
|
|
768
720
|
name: NAME,
|
|
@@ -772,7 +724,7 @@ const secretsManager = ({ credentials, endpoint, prefix = "hot-updater/", region
|
|
|
772
724
|
const result = Object.create(null);
|
|
773
725
|
if (unique.length === 0) return result;
|
|
774
726
|
const client = await open();
|
|
775
|
-
const values = await Promise.all(ids.map((id) =>
|
|
727
|
+
const values = await Promise.all(ids.map(async (id) => (await readCurrent(client, id))?.value));
|
|
776
728
|
unique.forEach((name, index) => {
|
|
777
729
|
result[name] = values[index];
|
|
778
730
|
});
|
|
@@ -780,37 +732,41 @@ const secretsManager = ({ credentials, endpoint, prefix = "hot-updater/", region
|
|
|
780
732
|
},
|
|
781
733
|
set: async (name, value) => {
|
|
782
734
|
const id = secretId(name);
|
|
783
|
-
if (typeof value !== "string" || value === "") throw new Error(`${NAME}
|
|
784
|
-
if (Buffer.byteLength(value, "utf8") > MAX_SECRET_BYTES) throw
|
|
735
|
+
if (typeof value !== "string" || value === "") throw new Error(`${NAME} can't store an empty ${id}.`);
|
|
736
|
+
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.`]);
|
|
785
737
|
await mask([value]);
|
|
786
|
-
const
|
|
738
|
+
const opened = await open();
|
|
739
|
+
const { sdk, client } = opened;
|
|
787
740
|
const token = (0, node_crypto.randomUUID)();
|
|
788
741
|
const put = () => client.send(new sdk.PutSecretValueCommand({
|
|
789
742
|
ClientRequestToken: token,
|
|
790
743
|
SecretId: id,
|
|
791
744
|
SecretString: value
|
|
792
745
|
}));
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
await client.send(new sdk.CreateSecretCommand({
|
|
801
|
-
ClientRequestToken: token,
|
|
802
|
-
Description: "Stored by Hot Updater.",
|
|
803
|
-
Name: id,
|
|
804
|
-
SecretString: value
|
|
805
|
-
}));
|
|
806
|
-
} catch (error) {
|
|
807
|
-
if (!(error instanceof sdk.ResourceExistsException)) throw describeFailure("create", id, error, "secretsmanager:CreateSecret");
|
|
746
|
+
/** The version the write made. */
|
|
747
|
+
const write = async () => {
|
|
748
|
+
try {
|
|
749
|
+
return (await put()).VersionId;
|
|
750
|
+
} catch (error) {
|
|
751
|
+
if (!(error instanceof sdk.ResourceNotFoundException)) throw describeFailure("write", id, error, "secretsmanager:PutSecretValue");
|
|
752
|
+
}
|
|
808
753
|
try {
|
|
809
|
-
await
|
|
754
|
+
return (await client.send(new sdk.CreateSecretCommand({
|
|
755
|
+
ClientRequestToken: token,
|
|
756
|
+
Description: "Stored by Hot Updater.",
|
|
757
|
+
Name: id,
|
|
758
|
+
SecretString: value
|
|
759
|
+
}))).VersionId;
|
|
760
|
+
} catch (error) {
|
|
761
|
+
if (!(error instanceof sdk.ResourceExistsException)) throw describeFailure("create", id, error, "secretsmanager:CreateSecret");
|
|
762
|
+
}
|
|
763
|
+
try {
|
|
764
|
+
return (await put()).VersionId;
|
|
810
765
|
} catch (retryError) {
|
|
811
766
|
throw describeFailure("write", id, retryError, "secretsmanager:PutSecretValue");
|
|
812
767
|
}
|
|
813
|
-
}
|
|
768
|
+
};
|
|
769
|
+
await waitForVersion(opened, id, await write() ?? token);
|
|
814
770
|
},
|
|
815
771
|
describe: (name) => `the secret ${JSON.stringify(`${prefix}${name}`)} in AWS Secrets Manager (${region})`
|
|
816
772
|
};
|
package/dist/index.d.cts
CHANGED
|
@@ -1,17 +1,33 @@
|
|
|
1
1
|
import { DynamoDBClientConfig } from "@aws-sdk/client-dynamodb";
|
|
2
|
-
import { EngineDatabase, PluginTables, SecretsAdapter, StorageAdapter, StorageAdapterWith } from "@hot-updater/plugin-core";
|
|
2
|
+
import { EngineDatabase, Lazy, PluginTables, SecretsAdapter, StorageAdapter, StorageAdapterWith } from "@hot-updater/plugin-core";
|
|
3
3
|
import { S3ClientConfig } from "@aws-sdk/client-s3";
|
|
4
|
+
import { S3StorageOperations } from "@hot-updater/storage-s3";
|
|
5
|
+
//#region src/lazyCredentials.d.ts
|
|
6
|
+
type SdkCredentials = S3ClientConfig["credentials"];
|
|
7
|
+
/**
|
|
8
|
+
* Access keys whose fields may each be a function that returns them, such
|
|
9
|
+
* as `secret("<name>")` in `hot-updater.config.ts`, called on first use.
|
|
10
|
+
*/
|
|
11
|
+
interface LazyAwsCredentials {
|
|
12
|
+
readonly accessKeyId: Lazy<string>;
|
|
13
|
+
readonly secretAccessKey: Lazy<string>;
|
|
14
|
+
readonly sessionToken?: Lazy<string>;
|
|
15
|
+
}
|
|
16
|
+
/** The credentials the AWS SDK takes, or access keys with lazy fields. */
|
|
17
|
+
type AwsCredentialsOption = SdkCredentials | LazyAwsCredentials;
|
|
18
|
+
//#endregion
|
|
4
19
|
//#region src/dynamoDB.d.ts
|
|
5
|
-
interface DynamoDBConfig extends DynamoDBClientConfig {
|
|
20
|
+
interface DynamoDBConfig extends Omit<DynamoDBClientConfig, "credentials"> {
|
|
21
|
+
/** The SDK's credentials, or access keys whose fields are lazy. */
|
|
22
|
+
readonly credentials?: AwsCredentialsOption;
|
|
6
23
|
readonly apiBasePath?: string;
|
|
7
24
|
readonly cloudfrontDistributionId?: string;
|
|
8
25
|
readonly shouldWaitForInvalidation?: boolean;
|
|
9
26
|
readonly tableName: string;
|
|
10
27
|
/**
|
|
11
28
|
* DynamoDB bills each item a write touches, so Insights' aggregates are
|
|
12
|
-
* batched: through log rows a compaction merges (the default)
|
|
13
|
-
*
|
|
14
|
-
* each event.
|
|
29
|
+
* batched: through log rows a compaction merges (the default). `false` commits
|
|
30
|
+
* them with each event.
|
|
15
31
|
*/
|
|
16
32
|
readonly aggregateBatching?: EngineDatabase["aggregateBatching"] | false;
|
|
17
33
|
}
|
|
@@ -59,7 +75,9 @@ declare const cloudFrontDownloadUrl: (config: CloudFrontDownloadUrlOptions) => (
|
|
|
59
75
|
}>;
|
|
60
76
|
//#endregion
|
|
61
77
|
//#region src/s3Storage.d.ts
|
|
62
|
-
interface S3StorageConfig extends S3ClientConfig {
|
|
78
|
+
interface S3StorageConfig extends Omit<S3ClientConfig, "credentials"> {
|
|
79
|
+
/** The SDK's credentials, or access keys whose fields are lazy. */
|
|
80
|
+
credentials?: AwsCredentialsOption;
|
|
63
81
|
bucketName: string;
|
|
64
82
|
/** Base path where bundles will be stored in the bucket. */
|
|
65
83
|
basePath?: string;
|
|
@@ -70,7 +88,6 @@ interface S3StorageConfig extends S3ClientConfig {
|
|
|
70
88
|
*/
|
|
71
89
|
getDownloadUrl?: StorageAdapter["getDownloadUrl"];
|
|
72
90
|
}
|
|
73
|
-
type S3StorageOperations = "put" | "get" | "getDownloadUrl" | "exists" | "delete" | "listObjects" | "deleteObjects";
|
|
74
91
|
declare function s3Storage(config: S3StorageConfig): StorageAdapterWith<S3StorageOperations>;
|
|
75
92
|
//#endregion
|
|
76
93
|
//#region src/secretsManager.d.ts
|
|
@@ -85,7 +102,7 @@ interface SecretsManagerOptions {
|
|
|
85
102
|
/** The AWS region the secrets are in, such as `"us-east-1"`. */
|
|
86
103
|
readonly region: string;
|
|
87
104
|
/**
|
|
88
|
-
* Put before every name to make its secret's name, so `secret
|
|
105
|
+
* Put before every name to make its secret's name, so `secret("asc-api-key")`
|
|
89
106
|
* reads the secret `hot-updater/asc-api-key` and one IAM resource,
|
|
90
107
|
* `secret:hot-updater/*`, covers them all. Letters, digits, and
|
|
91
108
|
* `/_+=.@-`.
|
|
@@ -110,10 +127,11 @@ interface SecretsManagerOptions {
|
|
|
110
127
|
* Secrets from AWS Secrets Manager: each name is the secret
|
|
111
128
|
* `<prefix><name>`, its `SecretString`, or its `SecretBinary` as base64.
|
|
112
129
|
* `set` puts a new version of the secret, and creates the secret when it
|
|
113
|
-
* does not exist
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
* loads
|
|
130
|
+
* does not exist, then waits until a read returns that version, so a `get`
|
|
131
|
+
* after it reads the new value; AWS keeps the versions labeled
|
|
132
|
+
* `AWSCURRENT` and `AWSPREVIOUS`, and removes the older ones itself. The
|
|
133
|
+
* AWS SDK loads on the first read or write, so a config that only uses
|
|
134
|
+
* `s3Storage` never loads it.
|
|
117
135
|
*
|
|
118
136
|
* @example
|
|
119
137
|
* secrets: secretsManager({ region: "us-east-1" })
|
package/dist/index.d.mts
CHANGED
|
@@ -1,17 +1,33 @@
|
|
|
1
1
|
import { DynamoDBClientConfig } from "@aws-sdk/client-dynamodb";
|
|
2
|
-
import { EngineDatabase, PluginTables, SecretsAdapter, StorageAdapter, StorageAdapterWith } from "@hot-updater/plugin-core";
|
|
2
|
+
import { EngineDatabase, Lazy, PluginTables, SecretsAdapter, StorageAdapter, StorageAdapterWith } from "@hot-updater/plugin-core";
|
|
3
|
+
import { S3StorageOperations } from "@hot-updater/storage-s3";
|
|
3
4
|
import { S3ClientConfig } from "@aws-sdk/client-s3";
|
|
5
|
+
//#region src/lazyCredentials.d.ts
|
|
6
|
+
type SdkCredentials = S3ClientConfig["credentials"];
|
|
7
|
+
/**
|
|
8
|
+
* Access keys whose fields may each be a function that returns them, such
|
|
9
|
+
* as `secret("<name>")` in `hot-updater.config.ts`, called on first use.
|
|
10
|
+
*/
|
|
11
|
+
interface LazyAwsCredentials {
|
|
12
|
+
readonly accessKeyId: Lazy<string>;
|
|
13
|
+
readonly secretAccessKey: Lazy<string>;
|
|
14
|
+
readonly sessionToken?: Lazy<string>;
|
|
15
|
+
}
|
|
16
|
+
/** The credentials the AWS SDK takes, or access keys with lazy fields. */
|
|
17
|
+
type AwsCredentialsOption = SdkCredentials | LazyAwsCredentials;
|
|
18
|
+
//#endregion
|
|
4
19
|
//#region src/dynamoDB.d.ts
|
|
5
|
-
interface DynamoDBConfig extends DynamoDBClientConfig {
|
|
20
|
+
interface DynamoDBConfig extends Omit<DynamoDBClientConfig, "credentials"> {
|
|
21
|
+
/** The SDK's credentials, or access keys whose fields are lazy. */
|
|
22
|
+
readonly credentials?: AwsCredentialsOption;
|
|
6
23
|
readonly apiBasePath?: string;
|
|
7
24
|
readonly cloudfrontDistributionId?: string;
|
|
8
25
|
readonly shouldWaitForInvalidation?: boolean;
|
|
9
26
|
readonly tableName: string;
|
|
10
27
|
/**
|
|
11
28
|
* DynamoDB bills each item a write touches, so Insights' aggregates are
|
|
12
|
-
* batched: through log rows a compaction merges (the default)
|
|
13
|
-
*
|
|
14
|
-
* each event.
|
|
29
|
+
* batched: through log rows a compaction merges (the default). `false` commits
|
|
30
|
+
* them with each event.
|
|
15
31
|
*/
|
|
16
32
|
readonly aggregateBatching?: EngineDatabase["aggregateBatching"] | false;
|
|
17
33
|
}
|
|
@@ -59,7 +75,9 @@ declare const cloudFrontDownloadUrl: (config: CloudFrontDownloadUrlOptions) => (
|
|
|
59
75
|
}>;
|
|
60
76
|
//#endregion
|
|
61
77
|
//#region src/s3Storage.d.ts
|
|
62
|
-
interface S3StorageConfig extends S3ClientConfig {
|
|
78
|
+
interface S3StorageConfig extends Omit<S3ClientConfig, "credentials"> {
|
|
79
|
+
/** The SDK's credentials, or access keys whose fields are lazy. */
|
|
80
|
+
credentials?: AwsCredentialsOption;
|
|
63
81
|
bucketName: string;
|
|
64
82
|
/** Base path where bundles will be stored in the bucket. */
|
|
65
83
|
basePath?: string;
|
|
@@ -70,7 +88,6 @@ interface S3StorageConfig extends S3ClientConfig {
|
|
|
70
88
|
*/
|
|
71
89
|
getDownloadUrl?: StorageAdapter["getDownloadUrl"];
|
|
72
90
|
}
|
|
73
|
-
type S3StorageOperations = "put" | "get" | "getDownloadUrl" | "exists" | "delete" | "listObjects" | "deleteObjects";
|
|
74
91
|
declare function s3Storage(config: S3StorageConfig): StorageAdapterWith<S3StorageOperations>;
|
|
75
92
|
//#endregion
|
|
76
93
|
//#region src/secretsManager.d.ts
|
|
@@ -85,7 +102,7 @@ interface SecretsManagerOptions {
|
|
|
85
102
|
/** The AWS region the secrets are in, such as `"us-east-1"`. */
|
|
86
103
|
readonly region: string;
|
|
87
104
|
/**
|
|
88
|
-
* Put before every name to make its secret's name, so `secret
|
|
105
|
+
* Put before every name to make its secret's name, so `secret("asc-api-key")`
|
|
89
106
|
* reads the secret `hot-updater/asc-api-key` and one IAM resource,
|
|
90
107
|
* `secret:hot-updater/*`, covers them all. Letters, digits, and
|
|
91
108
|
* `/_+=.@-`.
|
|
@@ -110,10 +127,11 @@ interface SecretsManagerOptions {
|
|
|
110
127
|
* Secrets from AWS Secrets Manager: each name is the secret
|
|
111
128
|
* `<prefix><name>`, its `SecretString`, or its `SecretBinary` as base64.
|
|
112
129
|
* `set` puts a new version of the secret, and creates the secret when it
|
|
113
|
-
* does not exist
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
* loads
|
|
130
|
+
* does not exist, then waits until a read returns that version, so a `get`
|
|
131
|
+
* after it reads the new value; AWS keeps the versions labeled
|
|
132
|
+
* `AWSCURRENT` and `AWSPREVIOUS`, and removes the older ones itself. The
|
|
133
|
+
* AWS SDK loads on the first read or write, so a config that only uses
|
|
134
|
+
* `s3Storage` never loads it.
|
|
117
135
|
*
|
|
118
136
|
* @example
|
|
119
137
|
* secrets: secretsManager({ region: "us-east-1" })
|