@hot-updater/azure 1.2.0-rc.2 → 1.2.0-rc.21

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,3 +1,4 @@
1
+ import { Readable } from "node:stream";
1
2
  import { isTokenCredential } from "@azure/core-auth";
2
3
  import { BlobSASPermissions, BlobServiceClient, RestError, StorageSharedKeyCredential, generateBlobSASQueryParameters } from "@azure/storage-blob";
3
4
  import { SETTINGS_TABLE, createEngineDatabase, createKvAdapter, createStorageAdapter, createStorageKeyBuilder, createStorageUri, encodeKvKey, migrateCoreSchema, parseStorageUri, toolingTargetOf } from "@hot-updater/plugin-core";
@@ -10,7 +11,11 @@ const SAS_EXPIRES_IN_MS = 36e5;
10
11
  /** A user delegation key signs SAS URLs for up to seven days; it is renewed well before. */
11
12
  const DELEGATION_KEY_LIFETIME_MS = 864e5;
12
13
  const isNotFound = (error) => error instanceof RestError && error.statusCode === 404;
13
- const serviceOf = (config) => "connectionString" in config ? BlobServiceClient.fromConnectionString(config.connectionString) : new BlobServiceClient(config.accountUrl, config.credential);
14
+ const serviceOf = async (config) => {
15
+ if (!("connectionString" in config)) return new BlobServiceClient(config.accountUrl, config.credential);
16
+ const { connectionString } = config;
17
+ return BlobServiceClient.fromConnectionString(typeof connectionString === "function" ? await connectionString() : connectionString);
18
+ };
14
19
  /**
15
20
  * Bundles in an Azure Blob Storage container. Without `getDownloadUrl`,
16
21
  * devices download through SAS URLs: signed with the account key when the
@@ -20,8 +25,11 @@ const serviceOf = (config) => "connectionString" in config ? BlobServiceClient.f
20
25
  function azureBlobStorage(config) {
21
26
  const { containerName, basePath, getDownloadUrl } = config;
22
27
  let client;
23
- const service = () => client ??= serviceOf(config);
24
- const container = () => service().getContainerClient(containerName);
28
+ const service = () => client ??= serviceOf(config).catch((error) => {
29
+ client = void 0;
30
+ throw error;
31
+ });
32
+ const container = async () => (await service()).getContainerClient(containerName);
25
33
  const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
26
34
  const getStorageKey = createStorageKeyBuilder(normalizedBasePath);
27
35
  const getListPrefix = (prefix = "") => {
@@ -53,7 +61,7 @@ function azureBlobStorage(config) {
53
61
  const delegationKey = () => {
54
62
  const now = Date.now();
55
63
  if (delegation === void 0 || delegation.renewAt <= now) {
56
- const key = service().getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS));
64
+ const key = service().then((blobService) => blobService.getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS)));
57
65
  key.catch(() => {
58
66
  delegation = void 0;
59
67
  });
@@ -65,7 +73,7 @@ function azureBlobStorage(config) {
65
73
  return delegation.key;
66
74
  };
67
75
  const signedUrl = async (key) => {
68
- const blob = container().getBlobClient(key);
76
+ const blob = (await container()).getBlobClient(key);
69
77
  const expiresOn = new Date(Date.now() + SAS_EXPIRES_IN_MS);
70
78
  const permissions = BlobSASPermissions.parse("r");
71
79
  if (blob.credential instanceof StorageSharedKeyCredential) return blob.generateSasUrl({
@@ -86,7 +94,8 @@ function azureBlobStorage(config) {
86
94
  protocol: PROTOCOL,
87
95
  async listObjects(prefix) {
88
96
  const objects = [];
89
- for await (const blob of container().listBlobsFlat({ prefix: getListPrefix(prefix) })) {
97
+ const blobs = await container();
98
+ for await (const blob of blobs.listBlobsFlat({ prefix: getListPrefix(prefix) })) {
90
99
  const storageUri = getListedStorageUri(blob.name);
91
100
  if (storageUri === null) continue;
92
101
  objects.push({
@@ -103,7 +112,8 @@ function azureBlobStorage(config) {
103
112
  for (let offset = 0; offset < keys.length; offset += 256) {
104
113
  const batch = keys.slice(offset, offset + 256);
105
114
  if (batch.length === 0) continue;
106
- const failed = (await container().getBlobBatchClient().deleteBlobs(batch.map((key) => container().getBlobClient(key)))).subResponses.filter(({ status }) => status >= 300 && status !== 404);
115
+ const blobs = await container();
116
+ const failed = (await blobs.getBlobBatchClient().deleteBlobs(batch.map((key) => blobs.getBlobClient(key)))).subResponses.filter(({ status }) => status >= 300 && status !== 404);
107
117
  if (failed.length > 0) throw new Error(`Failed to delete ${failed.length} Azure blob(s).`);
108
118
  }
109
119
  },
@@ -113,7 +123,7 @@ function azureBlobStorage(config) {
113
123
  blobContentType: contentType,
114
124
  blobCacheControl: "max-age=31536000"
115
125
  } };
116
- const blob = container().getBlockBlobClient(storageKey);
126
+ const blob = (await container()).getBlockBlobClient(storageKey);
117
127
  if (contentLength === void 0) await blob.uploadData(new Uint8Array(await new Response(body).arrayBuffer()), options);
118
128
  else {
119
129
  const { Readable } = await import("node:stream");
@@ -142,13 +152,12 @@ function azureBlobStorage(config) {
142
152
  async get({ storageUri }) {
143
153
  const { key } = parseAndValidate(storageUri);
144
154
  try {
145
- const download = await container().getBlobClient(key).download();
155
+ const download = await (await container()).getBlobClient(key).download();
146
156
  const body = download.readableStreamBody;
147
157
  if (body === void 0) return { response: null };
148
158
  const headers = new Headers();
149
159
  if (download.contentType) headers.set("content-type", download.contentType);
150
160
  if (download.contentLength !== void 0) headers.set("content-length", String(download.contentLength));
151
- const { Readable } = await import("node:stream");
152
161
  return { response: new Response(Readable.toWeb(body), { headers }) };
153
162
  } catch (error) {
154
163
  if (isNotFound(error)) return { response: null };
@@ -162,11 +171,11 @@ function azureBlobStorage(config) {
162
171
  },
163
172
  async exists({ storageUri }) {
164
173
  const { key } = parseAndValidate(storageUri);
165
- return { exists: await container().getBlobClient(key).exists() };
174
+ return { exists: await (await container()).getBlobClient(key).exists() };
166
175
  },
167
176
  async delete({ storageUri }) {
168
177
  const { key } = parseAndValidate(storageUri);
169
- await container().getBlobClient(key).deleteIfExists();
178
+ await (await container()).getBlobClient(key).deleteIfExists();
170
179
  return { deleted: true };
171
180
  }
172
181
  });
@@ -283,7 +292,7 @@ const TRANSIENT = /* @__PURE__ */ new Set([
283
292
  503
284
293
  ]);
285
294
  /** An error's HTTP status, or its cause's: the SDK wraps some answers, such as a failed batch's. */
286
- const statusOf = (error) => {
295
+ const statusOf$1 = (error) => {
287
296
  for (let at = error; at !== null && typeof at === "object"; at = at.cause) {
288
297
  const { statusCode, code } = at;
289
298
  const status = statusCode ?? code;
@@ -292,7 +301,7 @@ const statusOf = (error) => {
292
301
  };
293
302
  /** A missing database or container reads as a missing schema, like SQL's 42P01. */
294
303
  const missingContainer = (error) => {
295
- throw statusOf(error) === 404 ? Object.assign(new Error(error.message, { cause: error }), { code: "42P01" }) : error;
304
+ throw statusOf$1(error) === 404 ? Object.assign(new Error(error.message, { cause: error }), { code: "42P01" }) : error;
296
305
  };
297
306
  /** The header of a container read that reports its index transformation, in percent. */
298
307
  const INDEX_TRANSFORMATION_PROGRESS = "x-ms-documentdb-collection-index-transformation-progress";
@@ -370,7 +379,7 @@ const isWideAdd = (op) => op.type === "add" && Object.keys(op.by).length + (op.e
370
379
  * another one with these errors, having written nothing. Cosmos DB itself
371
380
  * runs the batches of a partition one at a time and never reports them.
372
381
  */
373
- const emulatorAborted = (error) => statusOf(error) === 500 && /PostgresError\(SqlState\(E(25P02|40001|40P01)\)/.test(String(error instanceof Error ? error.message : error));
382
+ const emulatorAborted = (error) => statusOf$1(error) === 500 && /PostgresError\(SqlState\(E(25P02|40001|40P01)\)/.test(String(error instanceof Error ? error.message : error));
374
383
  /**
375
384
  * The key-value store over one Cosmos DB container of `{ pk, sk, row }`
376
385
  * items in one logical partition, read through the composite index on
@@ -384,14 +393,17 @@ const emulatorAborted = (error) => statusOf(error) === 500 && /PostgresError\(Sq
384
393
  */
385
394
  const createCosmosStore = ({ client, databaseId, containerId, engine, nativePageSize }) => {
386
395
  let opened;
387
- const open = () => opened ??= (() => {
388
- const account = typeof client === "function" ? client() : client;
396
+ const open = () => opened ??= (async () => {
397
+ const account = typeof client === "function" ? await client() : client;
389
398
  return {
390
399
  client: account,
391
400
  container: account.database(databaseId).container(containerId)
392
401
  };
393
- })();
394
- const container = () => open().container;
402
+ })().catch((error) => {
403
+ opened = void 0;
404
+ throw error;
405
+ });
406
+ const container = async () => (await open()).container;
395
407
  /**
396
408
  * The state of the items `ids` names, by id, with the rows of `rowIds`;
397
409
  * a missing item has none.
@@ -399,7 +411,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
399
411
  const readStates = async (ids, rowIds) => {
400
412
  const states = /* @__PURE__ */ new Map();
401
413
  for (const [group, projection] of [[ids.filter((id) => !rowIds.has(id)), ""], [ids.filter((id) => rowIds.has(id)), ", c.row"]]) for (let at = 0; at < group.length; at += GET_BATCH) {
402
- const { resources } = await container().items.query(`SELECT c.id, c._etag AS etag, c.row._v AS v, c.expireAt${projection} FROM c WHERE c.id IN (${idList(group.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
414
+ const { resources } = await (await container()).items.query(`SELECT c.id, c._etag AS etag, c.row._v AS v, c.expireAt${projection} FROM c WHERE c.id IN (${idList(group.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
403
415
  for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
404
416
  etag,
405
417
  v,
@@ -537,7 +549,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
537
549
  const found = /* @__PURE__ */ new Map();
538
550
  const ids = [...new Set(keys.map(cosmosItemId))];
539
551
  for (let at = 0; at < ids.length; at += GET_BATCH) {
540
- const { resources } = await container().items.query(`SELECT c.id, c.row FROM c WHERE c.id IN (${idList(ids.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
552
+ const { resources } = await (await container()).items.query(`SELECT c.id, c.row FROM c WHERE c.id IN (${idList(ids.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
541
553
  for (const resource of resources) found.set(resource.id, toRow(resource.row));
542
554
  }
543
555
  return keys.map((key) => found.get(cosmosItemId(key)) ?? null);
@@ -573,7 +585,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
573
585
  value: after
574
586
  });
575
587
  }
576
- const { resources } = await container().items.query({
588
+ const { resources } = await (await container()).items.query({
577
589
  query: `SELECT TOP @size c.sk, c.row FROM c WHERE ${filters.join(" AND ")} ORDER BY c.pk ${order === "asc" ? "ASC" : "DESC"}, c.sk ${order === "asc" ? "ASC" : "DESC"}`,
578
590
  parameters
579
591
  }, {
@@ -623,12 +635,12 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
623
635
  if (planned.length > BATCH_OPERATIONS) throw new Error(`A Cosmos DB batch takes ${BATCH_OPERATIONS} operations; this write needs ${planned.length}.`);
624
636
  let results;
625
637
  try {
626
- const response = await container().items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
638
+ const response = await (await container()).items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
627
639
  if (response.result === void 0) throw Object.assign(/* @__PURE__ */ new Error(`Cosmos DB refused the batch with status ${response.code}`), { code: response.code });
628
640
  results = response.result;
629
641
  } catch (error) {
630
642
  if (emulatorAborted(error)) continue;
631
- if (TRANSIENT.has(statusOf(error))) return {
643
+ if (TRANSIENT.has(statusOf$1(error))) return {
632
644
  ok: false,
633
645
  retry: true
634
646
  };
@@ -657,12 +669,12 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
657
669
  async deleteConsumed(keys) {
658
670
  let remaining = [...new Set(keys.map(cosmosItemId))];
659
671
  for (let attempt = 0; remaining.length > 0; attempt += 1) {
660
- const failed = (await container().items.executeBulkOperations(remaining.map((id) => ({
672
+ const failed = (await (await container()).items.executeBulkOperations(remaining.map((id) => ({
661
673
  operationType: "Delete",
662
674
  id,
663
675
  partitionKey: COSMOS_PARTITION
664
676
  }))).catch(missingContainer)).flatMap((result, at) => {
665
- const status = result.response?.statusCode ?? statusOf(result.error);
677
+ const status = result.response?.statusCode ?? statusOf$1(result.error);
666
678
  return typeof status === "number" && status < 400 || status === 404 ? [] : [{
667
679
  id: remaining[at],
668
680
  error: result.error,
@@ -678,8 +690,8 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
678
690
  migrations: {
679
691
  /** Creates the database and the container when they are missing. */
680
692
  async apply() {
681
- if (engine !== void 0) await assertCosmosContainerReusable(container(), engine);
682
- const { database } = await open().client.databases.createIfNotExists({ id: databaseId });
693
+ if (engine !== void 0) await assertCosmosContainerReusable(await container(), engine);
694
+ const { database } = await (await open()).client.databases.createIfNotExists({ id: databaseId });
683
695
  const { resource } = await database.containers.createIfNotExists({
684
696
  id: containerId,
685
697
  partitionKey: { paths: [COSMOS_PARTITION_KEY_PATH] },
@@ -716,8 +728,12 @@ const adapterOf = (config) => {
716
728
  const { databaseId = AZURE_COSMOS_V1_DATABASE, containerId = AZURE_COSMOS_V1_CONTAINER, aggregateBatching: _, ...connection } = config;
717
729
  if (connection.consistencyLevel !== void 0 && connection.consistencyLevel !== "Strong") throw new Error(`cosmosDatabase reads with strong consistency; consistencyLevel "${String(connection.consistencyLevel)}" is weaker.`);
718
730
  let client;
731
+ const { connectionString } = connection;
719
732
  const store = createCosmosStore({
720
- client: () => client ??= new CosmosClient(connection),
733
+ client: async () => client ??= new CosmosClient({
734
+ ...connection,
735
+ connectionString: typeof connectionString === "function" ? await connectionString() : connectionString
736
+ }),
721
737
  databaseId,
722
738
  containerId,
723
739
  engine: currentCosmosEngine()
@@ -746,7 +762,7 @@ const migrateCosmosDatabase = (config, plugins = []) => {
746
762
  const DATABASE_TARGET = Symbol.for("@hot-updater/database-target");
747
763
  /** The account host a client reaches: its endpoint, or the connection string's. */
748
764
  const accountHostOf = ({ endpoint, connectionString }) => {
749
- const url = endpoint ?? connectionString?.match(/AccountEndpoint=([^;]+)/iu)?.[1];
765
+ const url = endpoint ?? (typeof connectionString === "string" ? connectionString.match(/AccountEndpoint=([^;]+)/iu)?.[1] : void 0);
750
766
  try {
751
767
  return url === void 0 ? void 0 : new URL(url).hostname;
752
768
  } catch {
@@ -776,4 +792,216 @@ const cosmosDatabase = (config) => {
776
792
  };
777
793
  };
778
794
  //#endregion
779
- export { azureBlobStorage, cosmosDatabase, migrateCosmosDatabase };
795
+ //#region src/keyVault.ts
796
+ const NAME = "keyVault";
797
+ const VAULT_NAME_PATTERN = /^[A-Za-z](?!.*--)[A-Za-z0-9-]{1,22}[A-Za-z0-9]$/u;
798
+ /** The characters Key Vault takes in a secret's name. */
799
+ const PREFIX_PATTERN = /^[A-Za-z0-9-]*$/u;
800
+ /** Names Key Vault keeps as they are: lower case, digits, single hyphens. */
801
+ const PLAIN_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
802
+ const MAX_SECRET_NAME_LENGTH = 127;
803
+ /** Key Vault's limit on a value, in characters: it refuses one more. */
804
+ const MAX_SECRET_LENGTH = 25600;
805
+ /** The tag that keeps the name a secret holds, which a mapped name hides. */
806
+ const NAME_TAG = "hot-updater-name";
807
+ /** Errors of `@azure/identity` finding no identity, or failing to sign in. */
808
+ const NO_CREDENTIAL_ERRORS = /* @__PURE__ */ new Set([
809
+ "AggregateAuthenticationError",
810
+ "AuthenticationRequiredError",
811
+ "CredentialUnavailableError"
812
+ ]);
813
+ /** The variables `DefaultAzureCredential` signs in with first, if complete. */
814
+ const environmentCredentialVariables = () => {
815
+ const { env } = process;
816
+ if (!env["AZURE_TENANT_ID"] || !env["AZURE_CLIENT_ID"]) return void 0;
817
+ if (env["AZURE_CLIENT_SECRET"]) return "AZURE_CLIENT_SECRET";
818
+ if (env["AZURE_CLIENT_CERTIFICATE_PATH"]) return "AZURE_CLIENT_CERTIFICATE_PATH";
819
+ if (env["AZURE_USERNAME"] && env["AZURE_PASSWORD"]) return "AZURE_PASSWORD";
820
+ };
821
+ /**
822
+ * The one step that can fix the identity in use: `az login` changes nothing
823
+ * while the environment's identity comes first.
824
+ */
825
+ const signInHint = (credential) => {
826
+ if (credential !== void 0) return [`Check the credential passed to ${NAME}().`];
827
+ const variable = environmentCredentialVariables();
828
+ if (variable) return [`Fix or unset ${variable}, AZURE_TENANT_ID, and AZURE_CLIENT_ID.`];
829
+ return process.env["CI"] ? ["Sign in with azure/login."] : ["Sign in:", "az login"];
830
+ };
831
+ /** An error of one line each, for a terminal. */
832
+ const failure = (lines, cause) => new Error(lines.join("\n"), cause === void 0 ? void 0 : { cause });
833
+ const READ_ROLE = "Key Vault Secrets User";
834
+ const WRITE_ROLE = "Key Vault Secrets Officer";
835
+ const errorName = (error) => error instanceof Error ? error.name : "";
836
+ /** The message's first line: Key Vault's next lines name the caller's IDs. */
837
+ const errorMessage = (error) => ((error instanceof Error ? error.message : String(error)).split(/\r?\n/u, 1)[0] ?? "").replace(/\.+$/u, "");
838
+ const innerCode = (error) => {
839
+ const inner = error?.details?.error;
840
+ return inner?.innerError?.code ?? inner?.innererror?.code;
841
+ };
842
+ const statusOf = (error) => error?.statusCode;
843
+ const isLoopback = (hostname) => (/* @__PURE__ */ new Set([
844
+ "localhost",
845
+ "127.0.0.1",
846
+ "[::1]"
847
+ ])).has(hostname);
848
+ const resolveVaultUrl = (vaultName, vaultUrl) => {
849
+ if (vaultName === void 0 === (vaultUrl === void 0)) throw new Error(`${NAME} needs a vaultName or a vaultUrl, and not both.`);
850
+ if (vaultName !== void 0) {
851
+ if (typeof vaultName !== "string" || !VAULT_NAME_PATTERN.test(vaultName)) throw failure([`${NAME} can't use the vault name ${JSON.stringify(vaultName)}.`, "Use 3 to 24 letters, digits, and single hyphens; start with a letter."]);
852
+ return new URL(`https://${vaultName.toLowerCase()}.vault.azure.net`);
853
+ }
854
+ let url;
855
+ try {
856
+ url = new URL(String(vaultUrl).trim());
857
+ } catch {
858
+ throw new Error(`${NAME} vaultUrl must be a valid URL.`);
859
+ }
860
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.pathname !== "/" && url.pathname !== "") throw failure([
861
+ `${NAME} can't use its vaultUrl.`,
862
+ "Use an HTTPS origin, such as https://my-vault.vault.azure.net.",
863
+ "Leave out credentials, a path, a query, and a fragment."
864
+ ]);
865
+ return url;
866
+ };
867
+ /** Masks a value in the CLI's output, which loads `@hot-updater/cli-tools`. */
868
+ const mask = async (values) => {
869
+ const { registerSecretValue } = await import("@hot-updater/cli-tools");
870
+ for (const value of values) if (value) registerSecretValue(value);
871
+ };
872
+ /** `credential`, with each access token it returns masked. */
873
+ const maskTokens = (credential) => ({ getToken: async (scopes, options) => {
874
+ const token = await credential.getToken(scopes, options);
875
+ await mask([token?.token]);
876
+ return token;
877
+ } });
878
+ /**
879
+ * The Key Vault secret name of `name`, after `prefix`. Key Vault takes
880
+ * only letters, digits, and `-` in a name, and matches names without
881
+ * regard to case, so:
882
+ *
883
+ * - a name of lower-case letters and digits in words joined by single
884
+ * hyphens, such as `asc-api-key`, is kept as it is;
885
+ * - any other name, such as `CLOUDFLARE_API_TOKEN` or `upload.keystore`,
886
+ * becomes its lower-cased words joined by `-`, then `--` and the first 10
887
+ * hex digits of the SHA-256 of the exact name:
888
+ * `cloudflare-api-token--<hash>`.
889
+ *
890
+ * A kept name never holds `--` and a mapped one always does, so no two
891
+ * names share a secret, and `CLOUDFLARE_API_TOKEN` and
892
+ * `cloudflare-api-token` stay apart. Each secret `set` stores is tagged
893
+ * `hot-updater-name` with the name it holds.
894
+ */
895
+ const keyVaultSecretName = (name, prefix = "hot-updater-") => {
896
+ if (PLAIN_NAME_PATTERN.test(name)) return `${prefix}${name}`;
897
+ return `${prefix}${name.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "")}--${createHash("sha256").update(name).digest("hex").slice(0, 10)}`;
898
+ };
899
+ /**
900
+ * Secrets from Azure Key Vault: each name is the secret `<prefix><name>`
901
+ * of the vault, `hot-updater-asc-api-key` for `asc-api-key`, with any
902
+ * other name mapped as `keyVaultSecretName` says, read at its current
903
+ * version. `set` adds a new version of
904
+ * the secret, which creates it when it does not exist; Key Vault keeps the
905
+ * older versions. A name whose secret was deleted and is still recoverable
906
+ * reads as missing, and `set` on it fails with the `az` commands that
907
+ * recover or purge it. `@azure/keyvault-secrets`, and `@azure/identity`
908
+ * without a `credential`, load on the first read or write, so a config
909
+ * that only uses `azureBlobStorage` never loads them.
910
+ *
911
+ * @example
912
+ * secrets: keyVault({ vaultName: "my-vault" })
913
+ */
914
+ const keyVault = ({ credential, prefix = "hot-updater-", vaultName, vaultUrl }) => {
915
+ const vault = () => {
916
+ const url = resolveVaultUrl(vaultName, vaultUrl);
917
+ if (typeof prefix !== "string" || !PREFIX_PATTERN.test(prefix)) throw new Error(`${NAME}'s prefix takes letters, digits, and - only.`);
918
+ return url;
919
+ };
920
+ const secretName = (name) => {
921
+ vault();
922
+ const id = keyVaultSecretName(name, prefix);
923
+ if (id.length > MAX_SECRET_NAME_LENGTH) throw failure([`${NAME} can't name a secret ${JSON.stringify(id)} for ${JSON.stringify(name)}.`, `Key Vault takes up to ${MAX_SECRET_NAME_LENGTH} characters.`]);
924
+ return id;
925
+ };
926
+ /** The vault's name, for the az commands messages suggest. */
927
+ const vaultLabel = () => vault().hostname.split(".")[0];
928
+ let opened;
929
+ const open = () => {
930
+ const url = vault();
931
+ if (credential !== void 0 && !isTokenCredential(credential)) throw new Error(`${NAME} credential must be a TokenCredential, such as one from @azure/identity.`);
932
+ opened ??= Promise.all([import("@azure/keyvault-secrets"), credential ?? import("@azure/identity").then(({ DefaultAzureCredential }) => new DefaultAzureCredential())]).then(([sdk, signWith]) => new sdk.SecretClient(url.origin, maskTokens(signWith), { disableChallengeResourceVerification: isLoopback(url.hostname) })).catch((error) => {
933
+ opened = void 0;
934
+ throw error;
935
+ });
936
+ return opened;
937
+ };
938
+ const describeFailure = (verb, id, error, role) => {
939
+ const name = errorName(error);
940
+ const status = statusOf(error);
941
+ const code = innerCode(error) ?? error?.code;
942
+ if (NO_CREDENTIAL_ERRORS.has(name)) return failure([`${NAME} found no Azure identity.`, ...signInHint(credential)], error);
943
+ if (status === 401 || name === "AuthenticationError") return failure(["Azure rejected the sign-in.", ...signInHint(credential)], error);
944
+ if (/\bENOTFOUND\b/u.test(`${code} ${errorMessage(error)}`) && errorMessage(error).includes(vault().hostname)) return failure([`${NAME} can't find ${vault().hostname}.`, `Check ${vaultUrl === void 0 ? "vaultName" : "vaultUrl"}.`], error);
945
+ if (code === "SecretDisabled") return failure([`${id}'s current version is disabled. Enable it, or store a new value.`], error);
946
+ if (status === 403) return failure([`Azure Key Vault refused to ${verb} ${id}.`, code === "ForbiddenByFirewall" ? "Its firewall refuses this network." : code === "ForbiddenByPolicy" ? `The identity needs the secret permissions ${role === READ_ROLE ? "get" : "get and set"}.` : `The identity needs the ${role} role on the vault.`], error);
947
+ if (code === "ObjectIsBeingDeleted" || /being deleted/iu.test(errorMessage(error))) return failure([`${id} is being deleted. Try again in a minute.`], error);
948
+ if (status === 409 || code === "ObjectIsDeletedButRecoverable") {
949
+ const vaultName = vaultLabel();
950
+ return failure([
951
+ `${id} was deleted. Recover it, or purge it:`,
952
+ `az keyvault secret recover --vault-name ${vaultName} --name ${id}`,
953
+ `az keyvault secret purge --vault-name ${vaultName} --name ${id}`
954
+ ], error);
955
+ }
956
+ return failure([`Azure Key Vault failed to ${verb} ${id}.`, `${code || name || "Error"}${status ? ` (${status})` : ""}: ${errorMessage(error)}.`], error);
957
+ };
958
+ const read = async (client, id) => {
959
+ let value;
960
+ try {
961
+ ({value} = await client.getSecret(id));
962
+ } catch (error) {
963
+ if (statusOf(error) === 404 && /NotFound/u.test(error.code ?? "") && !/disabled/iu.test(errorMessage(error))) return;
964
+ throw describeFailure("read", id, error, READ_ROLE);
965
+ }
966
+ await mask([value]);
967
+ return value;
968
+ };
969
+ return {
970
+ name: NAME,
971
+ get: async (names) => {
972
+ const unique = [...new Set(names)];
973
+ const ids = unique.map(secretName);
974
+ const result = Object.create(null);
975
+ if (unique.length === 0) return result;
976
+ const client = await open();
977
+ const values = await Promise.all(ids.map((id) => read(client, id)));
978
+ unique.forEach((name, index) => {
979
+ result[name] = values[index];
980
+ });
981
+ return result;
982
+ },
983
+ set: async (name, value) => {
984
+ const id = secretName(name);
985
+ if (typeof value !== "string" || value === "") throw new Error(`${NAME} can't store an empty ${id}.`);
986
+ if (value.length > MAX_SECRET_LENGTH) throw failure([`${NAME} can't store ${id}: it has ${value.length} characters.`, `Key Vault takes up to ${MAX_SECRET_LENGTH} characters per secret.`]);
987
+ await mask([value]);
988
+ const client = await open();
989
+ try {
990
+ await client.setSecret(id, value, { tags: { [NAME_TAG]: name } });
991
+ } catch (error) {
992
+ throw describeFailure("write", id, error, WRITE_ROLE);
993
+ }
994
+ },
995
+ describe: (name) => {
996
+ let url;
997
+ try {
998
+ url = vault().origin;
999
+ } catch {
1000
+ url = String(vaultUrl ?? vaultName);
1001
+ }
1002
+ return `the secret ${JSON.stringify(keyVaultSecretName(name, prefix))} in Azure Key Vault (${url})`;
1003
+ }
1004
+ };
1005
+ };
1006
+ //#endregion
1007
+ export { azureBlobStorage, cosmosDatabase, keyVault, migrateCosmosDatabase };
@@ -267,14 +267,17 @@ const emulatorAborted = (error) => statusOf(error) === 500 && /PostgresError\(Sq
267
267
  */
268
268
  const createCosmosStore = ({ client, databaseId, containerId, engine, nativePageSize }) => {
269
269
  let opened;
270
- const open = () => opened ??= (() => {
271
- const account = typeof client === "function" ? client() : client;
270
+ const open = () => opened ??= (async () => {
271
+ const account = typeof client === "function" ? await client() : client;
272
272
  return {
273
273
  client: account,
274
274
  container: account.database(databaseId).container(containerId)
275
275
  };
276
- })();
277
- const container = () => open().container;
276
+ })().catch((error) => {
277
+ opened = void 0;
278
+ throw error;
279
+ });
280
+ const container = async () => (await open()).container;
278
281
  /**
279
282
  * The state of the items `ids` names, by id, with the rows of `rowIds`;
280
283
  * a missing item has none.
@@ -282,7 +285,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
282
285
  const readStates = async (ids, rowIds) => {
283
286
  const states = /* @__PURE__ */ new Map();
284
287
  for (const [group, projection] of [[ids.filter((id) => !rowIds.has(id)), ""], [ids.filter((id) => rowIds.has(id)), ", c.row"]]) for (let at = 0; at < group.length; at += GET_BATCH) {
285
- const { resources } = await container().items.query(`SELECT c.id, c._etag AS etag, c.row._v AS v, c.expireAt${projection} FROM c WHERE c.id IN (${idList(group.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
288
+ const { resources } = await (await container()).items.query(`SELECT c.id, c._etag AS etag, c.row._v AS v, c.expireAt${projection} FROM c WHERE c.id IN (${idList(group.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
286
289
  for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
287
290
  etag,
288
291
  v,
@@ -420,7 +423,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
420
423
  const found = /* @__PURE__ */ new Map();
421
424
  const ids = [...new Set(keys.map(cosmosItemId))];
422
425
  for (let at = 0; at < ids.length; at += GET_BATCH) {
423
- const { resources } = await container().items.query(`SELECT c.id, c.row FROM c WHERE c.id IN (${idList(ids.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
426
+ const { resources } = await (await container()).items.query(`SELECT c.id, c.row FROM c WHERE c.id IN (${idList(ids.slice(at, at + GET_BATCH))})`, { partitionKey: COSMOS_PARTITION }).fetchAll().catch(missingContainer);
424
427
  for (const resource of resources) found.set(resource.id, toRow(resource.row));
425
428
  }
426
429
  return keys.map((key) => found.get(cosmosItemId(key)) ?? null);
@@ -456,7 +459,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
456
459
  value: after
457
460
  });
458
461
  }
459
- const { resources } = await container().items.query({
462
+ const { resources } = await (await container()).items.query({
460
463
  query: `SELECT TOP @size c.sk, c.row FROM c WHERE ${filters.join(" AND ")} ORDER BY c.pk ${order === "asc" ? "ASC" : "DESC"}, c.sk ${order === "asc" ? "ASC" : "DESC"}`,
461
464
  parameters
462
465
  }, {
@@ -506,7 +509,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
506
509
  if (planned.length > BATCH_OPERATIONS) throw new Error(`A Cosmos DB batch takes ${BATCH_OPERATIONS} operations; this write needs ${planned.length}.`);
507
510
  let results;
508
511
  try {
509
- const response = await container().items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
512
+ const response = await (await container()).items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
510
513
  if (response.result === void 0) throw Object.assign(/* @__PURE__ */ new Error(`Cosmos DB refused the batch with status ${response.code}`), { code: response.code });
511
514
  results = response.result;
512
515
  } catch (error) {
@@ -540,7 +543,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
540
543
  async deleteConsumed(keys) {
541
544
  let remaining = [...new Set(keys.map(cosmosItemId))];
542
545
  for (let attempt = 0; remaining.length > 0; attempt += 1) {
543
- const failed = (await container().items.executeBulkOperations(remaining.map((id) => ({
546
+ const failed = (await (await container()).items.executeBulkOperations(remaining.map((id) => ({
544
547
  operationType: "Delete",
545
548
  id,
546
549
  partitionKey: COSMOS_PARTITION
@@ -561,8 +564,8 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
561
564
  migrations: {
562
565
  /** Creates the database and the container when they are missing. */
563
566
  async apply() {
564
- if (engine !== void 0) await assertCosmosContainerReusable(container(), engine);
565
- const { database } = await open().client.databases.createIfNotExists({ id: databaseId });
567
+ if (engine !== void 0) await assertCosmosContainerReusable(await container(), engine);
568
+ const { database } = await (await open()).client.databases.createIfNotExists({ id: databaseId });
566
569
  const { resource } = await database.containers.createIfNotExists({
567
570
  id: containerId,
568
571
  partitionKey: { paths: [COSMOS_PARTITION_KEY_PATH] },
@@ -599,8 +602,12 @@ const adapterOf = (config) => {
599
602
  const { databaseId = AZURE_COSMOS_V1_DATABASE, containerId = AZURE_COSMOS_V1_CONTAINER, aggregateBatching: _, ...connection } = config;
600
603
  if (connection.consistencyLevel !== void 0 && connection.consistencyLevel !== "Strong") throw new Error(`cosmosDatabase reads with strong consistency; consistencyLevel "${String(connection.consistencyLevel)}" is weaker.`);
601
604
  let client;
605
+ const { connectionString } = connection;
602
606
  const store = createCosmosStore({
603
- client: () => client ??= new _azure_cosmos.CosmosClient(connection),
607
+ client: async () => client ??= new _azure_cosmos.CosmosClient({
608
+ ...connection,
609
+ connectionString: typeof connectionString === "function" ? await connectionString() : connectionString
610
+ }),
604
611
  databaseId,
605
612
  containerId,
606
613
  engine: currentCosmosEngine()
@@ -629,7 +636,7 @@ const migrateCosmosDatabase = (config, plugins = []) => {
629
636
  const DATABASE_TARGET = Symbol.for("@hot-updater/database-target");
630
637
  /** The account host a client reaches: its endpoint, or the connection string's. */
631
638
  const accountHostOf = ({ endpoint, connectionString }) => {
632
- const url = endpoint ?? connectionString?.match(/AccountEndpoint=([^;]+)/iu)?.[1];
639
+ const url = endpoint ?? (typeof connectionString === "string" ? connectionString.match(/AccountEndpoint=([^;]+)/iu)?.[1] : void 0);
633
640
  try {
634
641
  return url === void 0 ? void 0 : new URL(url).hostname;
635
642
  } catch {
@@ -7451,26 +7458,34 @@ const verifyFunction = async (baseURL, { attempts = 60, delayMs = 5e3 } = {}) =>
7451
7458
  * import without its extension, so it names the container itself.
7452
7459
  */
7453
7460
  const BLOB_CONTAINER = "hot-updater";
7454
- const getConfigScaffold = (build) => {
7461
+ /**
7462
+ * The config init writes. With the `resources` init set up, it names the
7463
+ * Cosmos DB account. Either way it reads both connection strings with
7464
+ * `secret()`, from the environment and `.env.hotupdater`, then the config's
7465
+ * `secrets` adapter.
7466
+ */
7467
+ const getConfigScaffold = (build, resources) => {
7455
7468
  const storageConfig = {
7456
7469
  imports: [{
7457
7470
  pkg: "@hot-updater/azure",
7458
7471
  named: ["azureBlobStorage"]
7459
7472
  }],
7460
7473
  configString: `azureBlobStorage({
7461
- connectionString: process.env.HOT_UPDATER_AZURE_STORAGE_CONNECTION_STRING!,
7474
+ connectionString: secret("HOT_UPDATER_AZURE_STORAGE_CONNECTION_STRING"),
7462
7475
  containerName: "${BLOB_CONTAINER}",
7463
7476
  })`
7464
7477
  };
7465
- return (0, _hot_updater_cli_tools.createHotUpdaterConfigScaffoldFromBuilder)(new _hot_updater_cli_tools.ConfigBuilder().setBuildType(build).setStorage(storageConfig).setDatabase({
7478
+ const databaseConfig = {
7466
7479
  imports: [{
7467
7480
  pkg: "@hot-updater/azure",
7468
7481
  named: ["cosmosDatabase"]
7469
7482
  }],
7470
- configString: `cosmosDatabase({
7471
- connectionString: process.env.HOT_UPDATER_AZURE_COSMOS_CONNECTION_STRING!,
7483
+ configString: `cosmosDatabase({${resources?.cosmosEndpoint === void 0 ? "" : `
7484
+ endpoint: ${JSON.stringify(resources.cosmosEndpoint)},`}
7485
+ connectionString: secret("HOT_UPDATER_AZURE_COSMOS_CONNECTION_STRING"),
7472
7486
  })`
7473
- }).setPlugins({
7487
+ };
7488
+ const builder = new _hot_updater_cli_tools.ConfigBuilder().setBuildType(build).setStorage(storageConfig).setDatabase(databaseConfig).setPlugins({
7474
7489
  imports: [{
7475
7490
  pkg: "hot-updater/plugins",
7476
7491
  named: [
@@ -7480,7 +7495,11 @@ const getConfigScaffold = (build) => {
7480
7495
  ]
7481
7496
  }],
7482
7497
  configString: "[apiKeys(), insights(), remoteConfig()]"
7483
- }));
7498
+ }).addImport({
7499
+ pkg: "hot-updater",
7500
+ named: ["secret"]
7501
+ });
7502
+ return (0, _hot_updater_cli_tools.createHotUpdaterConfigScaffoldFromBuilder)(builder);
7484
7503
  };
7485
7504
  //#endregion
7486
7505
  //#region iac/init/index.ts
@@ -7565,7 +7584,8 @@ const initProvider = {
7565
7584
  optional: true,
7566
7585
  preflight: false
7567
7586
  }
7568
- }
7587
+ },
7588
+ secrets: ["HOT_UPDATER_AZURE_STORAGE_CONNECTION_STRING", "HOT_UPDATER_AZURE_COSMOS_CONNECTION_STRING"]
7569
7589
  };
7570
7590
  //#endregion
7571
7591
  //#region iac/index.ts
@@ -7625,10 +7645,10 @@ const resolveName = async ({ input, saved, fallback, nonInteractive, validate, h
7625
7645
  validate: (value) => validate(value) ? void 0 : hint
7626
7646
  }));
7627
7647
  };
7628
- const runInit = async ({ build, envFile }) => {
7648
+ const runInit = async ({ build, envFile, secretsEnv }) => {
7629
7649
  const cwd = (0, _hot_updater_cli_tools.getCwd)();
7630
7650
  const nonInteractive = envFile !== void 0;
7631
- const initEnvSources = await (0, _hot_updater_cli_tools.readHotUpdaterInitEnv)(cwd, envFile);
7651
+ const initEnvSources = await (0, _hot_updater_cli_tools.readHotUpdaterInitEnv)(cwd, envFile, secretsEnv);
7632
7652
  const initInputEnv = (0, _hot_updater_cli_tools.getHotUpdaterInitInputEnv)(initEnvSources, nonInteractive);
7633
7653
  const saved = Object.fromEntries(Object.entries(inputs).map(([name, input]) => [name, initInputEnv[input.envKey]?.trim() || void 0]));
7634
7654
  const cliVersion = await azureCliVersion();
@@ -7835,7 +7855,8 @@ const runInit = async ({ build, envFile }) => {
7835
7855
  await database.dispose?.();
7836
7856
  }
7837
7857
  _hot_updater_cli_tools.p.log.success("Generated '.env.hotupdater' file with Azure settings.");
7838
- await (0, _hot_updater_cli_tools.writeHotUpdaterFiles)(getConfigScaffold(build), {
7858
+ const cosmosEndpoint = /AccountEndpoint=([^;]+)/iu.exec(cosmosConnectionString)?.[1];
7859
+ await (0, _hot_updater_cli_tools.writeHotUpdaterFiles)(getConfigScaffold(build, cosmosEndpoint === void 0 ? {} : { cosmosEndpoint }), {
7839
7860
  cwd,
7840
7861
  settings: "Azure"
7841
7862
  });
@@ -7844,8 +7865,7 @@ const runInit = async ({ build, envFile }) => {
7844
7865
  ...credential === void 0 ? {} : { credential },
7845
7866
  clientPlugins: server.clientPlugins
7846
7867
  });
7847
- _hot_updater_cli_tools.p.log.message(`Next step: ${(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/azure#step-3-add-hotupdater-to-your-project")}`);
7848
- _hot_updater_cli_tools.p.log.success("Done! 🎉");
7868
+ return { nextSteps: [(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/azure#step-3-add-hotupdater-to-your-project")] };
7849
7869
  };
7850
7870
  //#endregion
7851
7871
  exports.AZURE_FUNCTION_PACKAGE = AZURE_FUNCTION_PACKAGE;