@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.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_stream = require("node:stream");
2
3
  let _azure_core_auth = require("@azure/core-auth");
3
4
  let _azure_storage_blob = require("@azure/storage-blob");
4
5
  let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
@@ -11,7 +12,11 @@ const SAS_EXPIRES_IN_MS = 36e5;
11
12
  /** A user delegation key signs SAS URLs for up to seven days; it is renewed well before. */
12
13
  const DELEGATION_KEY_LIFETIME_MS = 864e5;
13
14
  const isNotFound = (error) => error instanceof _azure_storage_blob.RestError && error.statusCode === 404;
14
- const serviceOf = (config) => "connectionString" in config ? _azure_storage_blob.BlobServiceClient.fromConnectionString(config.connectionString) : new _azure_storage_blob.BlobServiceClient(config.accountUrl, config.credential);
15
+ const serviceOf = async (config) => {
16
+ if (!("connectionString" in config)) return new _azure_storage_blob.BlobServiceClient(config.accountUrl, config.credential);
17
+ const { connectionString } = config;
18
+ return _azure_storage_blob.BlobServiceClient.fromConnectionString(typeof connectionString === "function" ? await connectionString() : connectionString);
19
+ };
15
20
  /**
16
21
  * Bundles in an Azure Blob Storage container. Without `getDownloadUrl`,
17
22
  * devices download through SAS URLs: signed with the account key when the
@@ -21,8 +26,11 @@ const serviceOf = (config) => "connectionString" in config ? _azure_storage_blob
21
26
  function azureBlobStorage(config) {
22
27
  const { containerName, basePath, getDownloadUrl } = config;
23
28
  let client;
24
- const service = () => client ??= serviceOf(config);
25
- const container = () => service().getContainerClient(containerName);
29
+ const service = () => client ??= serviceOf(config).catch((error) => {
30
+ client = void 0;
31
+ throw error;
32
+ });
33
+ const container = async () => (await service()).getContainerClient(containerName);
26
34
  const normalizedBasePath = basePath?.replace(/^\/+|\/+$/g, "") ?? "";
27
35
  const getStorageKey = (0, _hot_updater_plugin_core.createStorageKeyBuilder)(normalizedBasePath);
28
36
  const getListPrefix = (prefix = "") => {
@@ -54,7 +62,7 @@ function azureBlobStorage(config) {
54
62
  const delegationKey = () => {
55
63
  const now = Date.now();
56
64
  if (delegation === void 0 || delegation.renewAt <= now) {
57
- const key = service().getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS));
65
+ const key = service().then((blobService) => blobService.getUserDelegationKey(/* @__PURE__ */ new Date(now - 3e5), new Date(now + DELEGATION_KEY_LIFETIME_MS)));
58
66
  key.catch(() => {
59
67
  delegation = void 0;
60
68
  });
@@ -66,7 +74,7 @@ function azureBlobStorage(config) {
66
74
  return delegation.key;
67
75
  };
68
76
  const signedUrl = async (key) => {
69
- const blob = container().getBlobClient(key);
77
+ const blob = (await container()).getBlobClient(key);
70
78
  const expiresOn = new Date(Date.now() + SAS_EXPIRES_IN_MS);
71
79
  const permissions = _azure_storage_blob.BlobSASPermissions.parse("r");
72
80
  if (blob.credential instanceof _azure_storage_blob.StorageSharedKeyCredential) return blob.generateSasUrl({
@@ -87,7 +95,8 @@ function azureBlobStorage(config) {
87
95
  protocol: PROTOCOL,
88
96
  async listObjects(prefix) {
89
97
  const objects = [];
90
- for await (const blob of container().listBlobsFlat({ prefix: getListPrefix(prefix) })) {
98
+ const blobs = await container();
99
+ for await (const blob of blobs.listBlobsFlat({ prefix: getListPrefix(prefix) })) {
91
100
  const storageUri = getListedStorageUri(blob.name);
92
101
  if (storageUri === null) continue;
93
102
  objects.push({
@@ -104,7 +113,8 @@ function azureBlobStorage(config) {
104
113
  for (let offset = 0; offset < keys.length; offset += 256) {
105
114
  const batch = keys.slice(offset, offset + 256);
106
115
  if (batch.length === 0) continue;
107
- const failed = (await container().getBlobBatchClient().deleteBlobs(batch.map((key) => container().getBlobClient(key)))).subResponses.filter(({ status }) => status >= 300 && status !== 404);
116
+ const blobs = await container();
117
+ const failed = (await blobs.getBlobBatchClient().deleteBlobs(batch.map((key) => blobs.getBlobClient(key)))).subResponses.filter(({ status }) => status >= 300 && status !== 404);
108
118
  if (failed.length > 0) throw new Error(`Failed to delete ${failed.length} Azure blob(s).`);
109
119
  }
110
120
  },
@@ -114,7 +124,7 @@ function azureBlobStorage(config) {
114
124
  blobContentType: contentType,
115
125
  blobCacheControl: "max-age=31536000"
116
126
  } };
117
- const blob = container().getBlockBlobClient(storageKey);
127
+ const blob = (await container()).getBlockBlobClient(storageKey);
118
128
  if (contentLength === void 0) await blob.uploadData(new Uint8Array(await new Response(body).arrayBuffer()), options);
119
129
  else {
120
130
  const { Readable } = await import("node:stream");
@@ -143,14 +153,13 @@ function azureBlobStorage(config) {
143
153
  async get({ storageUri }) {
144
154
  const { key } = parseAndValidate(storageUri);
145
155
  try {
146
- const download = await container().getBlobClient(key).download();
156
+ const download = await (await container()).getBlobClient(key).download();
147
157
  const body = download.readableStreamBody;
148
158
  if (body === void 0) return { response: null };
149
159
  const headers = new Headers();
150
160
  if (download.contentType) headers.set("content-type", download.contentType);
151
161
  if (download.contentLength !== void 0) headers.set("content-length", String(download.contentLength));
152
- const { Readable } = await import("node:stream");
153
- return { response: new Response(Readable.toWeb(body), { headers }) };
162
+ return { response: new Response(node_stream.Readable.toWeb(body), { headers }) };
154
163
  } catch (error) {
155
164
  if (isNotFound(error)) return { response: null };
156
165
  throw error;
@@ -163,11 +172,11 @@ function azureBlobStorage(config) {
163
172
  },
164
173
  async exists({ storageUri }) {
165
174
  const { key } = parseAndValidate(storageUri);
166
- return { exists: await container().getBlobClient(key).exists() };
175
+ return { exists: await (await container()).getBlobClient(key).exists() };
167
176
  },
168
177
  async delete({ storageUri }) {
169
178
  const { key } = parseAndValidate(storageUri);
170
- await container().getBlobClient(key).deleteIfExists();
179
+ await (await container()).getBlobClient(key).deleteIfExists();
171
180
  return { deleted: true };
172
181
  }
173
182
  });
@@ -284,7 +293,7 @@ const TRANSIENT = /* @__PURE__ */ new Set([
284
293
  503
285
294
  ]);
286
295
  /** An error's HTTP status, or its cause's: the SDK wraps some answers, such as a failed batch's. */
287
- const statusOf = (error) => {
296
+ const statusOf$1 = (error) => {
288
297
  for (let at = error; at !== null && typeof at === "object"; at = at.cause) {
289
298
  const { statusCode, code } = at;
290
299
  const status = statusCode ?? code;
@@ -293,7 +302,7 @@ const statusOf = (error) => {
293
302
  };
294
303
  /** A missing database or container reads as a missing schema, like SQL's 42P01. */
295
304
  const missingContainer = (error) => {
296
- throw statusOf(error) === 404 ? Object.assign(new Error(error.message, { cause: error }), { code: "42P01" }) : error;
305
+ throw statusOf$1(error) === 404 ? Object.assign(new Error(error.message, { cause: error }), { code: "42P01" }) : error;
297
306
  };
298
307
  /** The header of a container read that reports its index transformation, in percent. */
299
308
  const INDEX_TRANSFORMATION_PROGRESS = "x-ms-documentdb-collection-index-transformation-progress";
@@ -371,7 +380,7 @@ const isWideAdd = (op) => op.type === "add" && Object.keys(op.by).length + (op.e
371
380
  * another one with these errors, having written nothing. Cosmos DB itself
372
381
  * runs the batches of a partition one at a time and never reports them.
373
382
  */
374
- const emulatorAborted = (error) => statusOf(error) === 500 && /PostgresError\(SqlState\(E(25P02|40001|40P01)\)/.test(String(error instanceof Error ? error.message : error));
383
+ const emulatorAborted = (error) => statusOf$1(error) === 500 && /PostgresError\(SqlState\(E(25P02|40001|40P01)\)/.test(String(error instanceof Error ? error.message : error));
375
384
  /**
376
385
  * The key-value store over one Cosmos DB container of `{ pk, sk, row }`
377
386
  * items in one logical partition, read through the composite index on
@@ -385,14 +394,17 @@ const emulatorAborted = (error) => statusOf(error) === 500 && /PostgresError\(Sq
385
394
  */
386
395
  const createCosmosStore = ({ client, databaseId, containerId, engine, nativePageSize }) => {
387
396
  let opened;
388
- const open = () => opened ??= (() => {
389
- const account = typeof client === "function" ? client() : client;
397
+ const open = () => opened ??= (async () => {
398
+ const account = typeof client === "function" ? await client() : client;
390
399
  return {
391
400
  client: account,
392
401
  container: account.database(databaseId).container(containerId)
393
402
  };
394
- })();
395
- const container = () => open().container;
403
+ })().catch((error) => {
404
+ opened = void 0;
405
+ throw error;
406
+ });
407
+ const container = async () => (await open()).container;
396
408
  /**
397
409
  * The state of the items `ids` names, by id, with the rows of `rowIds`;
398
410
  * a missing item has none.
@@ -400,7 +412,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
400
412
  const readStates = async (ids, rowIds) => {
401
413
  const states = /* @__PURE__ */ new Map();
402
414
  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) {
403
- 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);
415
+ 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);
404
416
  for (const { id, etag, v, expireAt, row } of resources) states.set(id, {
405
417
  etag,
406
418
  v,
@@ -538,7 +550,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
538
550
  const found = /* @__PURE__ */ new Map();
539
551
  const ids = [...new Set(keys.map(cosmosItemId))];
540
552
  for (let at = 0; at < ids.length; at += GET_BATCH) {
541
- 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);
553
+ 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);
542
554
  for (const resource of resources) found.set(resource.id, toRow(resource.row));
543
555
  }
544
556
  return keys.map((key) => found.get(cosmosItemId(key)) ?? null);
@@ -574,7 +586,7 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
574
586
  value: after
575
587
  });
576
588
  }
577
- const { resources } = await container().items.query({
589
+ const { resources } = await (await container()).items.query({
578
590
  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"}`,
579
591
  parameters
580
592
  }, {
@@ -624,12 +636,12 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
624
636
  if (planned.length > BATCH_OPERATIONS) throw new Error(`A Cosmos DB batch takes ${BATCH_OPERATIONS} operations; this write needs ${planned.length}.`);
625
637
  let results;
626
638
  try {
627
- const response = await container().items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
639
+ const response = await (await container()).items.batch(planned.map(({ operation }) => operation), COSMOS_PARTITION);
628
640
  if (response.result === void 0) throw Object.assign(/* @__PURE__ */ new Error(`Cosmos DB refused the batch with status ${response.code}`), { code: response.code });
629
641
  results = response.result;
630
642
  } catch (error) {
631
643
  if (emulatorAborted(error)) continue;
632
- if (TRANSIENT.has(statusOf(error))) return {
644
+ if (TRANSIENT.has(statusOf$1(error))) return {
633
645
  ok: false,
634
646
  retry: true
635
647
  };
@@ -658,12 +670,12 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
658
670
  async deleteConsumed(keys) {
659
671
  let remaining = [...new Set(keys.map(cosmosItemId))];
660
672
  for (let attempt = 0; remaining.length > 0; attempt += 1) {
661
- const failed = (await container().items.executeBulkOperations(remaining.map((id) => ({
673
+ const failed = (await (await container()).items.executeBulkOperations(remaining.map((id) => ({
662
674
  operationType: "Delete",
663
675
  id,
664
676
  partitionKey: COSMOS_PARTITION
665
677
  }))).catch(missingContainer)).flatMap((result, at) => {
666
- const status = result.response?.statusCode ?? statusOf(result.error);
678
+ const status = result.response?.statusCode ?? statusOf$1(result.error);
667
679
  return typeof status === "number" && status < 400 || status === 404 ? [] : [{
668
680
  id: remaining[at],
669
681
  error: result.error,
@@ -679,8 +691,8 @@ const createCosmosStore = ({ client, databaseId, containerId, engine, nativePage
679
691
  migrations: {
680
692
  /** Creates the database and the container when they are missing. */
681
693
  async apply() {
682
- if (engine !== void 0) await assertCosmosContainerReusable(container(), engine);
683
- const { database } = await open().client.databases.createIfNotExists({ id: databaseId });
694
+ if (engine !== void 0) await assertCosmosContainerReusable(await container(), engine);
695
+ const { database } = await (await open()).client.databases.createIfNotExists({ id: databaseId });
684
696
  const { resource } = await database.containers.createIfNotExists({
685
697
  id: containerId,
686
698
  partitionKey: { paths: [COSMOS_PARTITION_KEY_PATH] },
@@ -717,8 +729,12 @@ const adapterOf = (config) => {
717
729
  const { databaseId = AZURE_COSMOS_V1_DATABASE, containerId = AZURE_COSMOS_V1_CONTAINER, aggregateBatching: _, ...connection } = config;
718
730
  if (connection.consistencyLevel !== void 0 && connection.consistencyLevel !== "Strong") throw new Error(`cosmosDatabase reads with strong consistency; consistencyLevel "${String(connection.consistencyLevel)}" is weaker.`);
719
731
  let client;
732
+ const { connectionString } = connection;
720
733
  const store = createCosmosStore({
721
- client: () => client ??= new _azure_cosmos.CosmosClient(connection),
734
+ client: async () => client ??= new _azure_cosmos.CosmosClient({
735
+ ...connection,
736
+ connectionString: typeof connectionString === "function" ? await connectionString() : connectionString
737
+ }),
722
738
  databaseId,
723
739
  containerId,
724
740
  engine: currentCosmosEngine()
@@ -747,7 +763,7 @@ const migrateCosmosDatabase = (config, plugins = []) => {
747
763
  const DATABASE_TARGET = Symbol.for("@hot-updater/database-target");
748
764
  /** The account host a client reaches: its endpoint, or the connection string's. */
749
765
  const accountHostOf = ({ endpoint, connectionString }) => {
750
- const url = endpoint ?? connectionString?.match(/AccountEndpoint=([^;]+)/iu)?.[1];
766
+ const url = endpoint ?? (typeof connectionString === "string" ? connectionString.match(/AccountEndpoint=([^;]+)/iu)?.[1] : void 0);
751
767
  try {
752
768
  return url === void 0 ? void 0 : new URL(url).hostname;
753
769
  } catch {
@@ -777,6 +793,219 @@ const cosmosDatabase = (config) => {
777
793
  };
778
794
  };
779
795
  //#endregion
796
+ //#region src/keyVault.ts
797
+ const NAME = "keyVault";
798
+ const VAULT_NAME_PATTERN = /^[A-Za-z](?!.*--)[A-Za-z0-9-]{1,22}[A-Za-z0-9]$/u;
799
+ /** The characters Key Vault takes in a secret's name. */
800
+ const PREFIX_PATTERN = /^[A-Za-z0-9-]*$/u;
801
+ /** Names Key Vault keeps as they are: lower case, digits, single hyphens. */
802
+ const PLAIN_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
803
+ const MAX_SECRET_NAME_LENGTH = 127;
804
+ /** Key Vault's limit on a value, in characters: it refuses one more. */
805
+ const MAX_SECRET_LENGTH = 25600;
806
+ /** The tag that keeps the name a secret holds, which a mapped name hides. */
807
+ const NAME_TAG = "hot-updater-name";
808
+ /** Errors of `@azure/identity` finding no identity, or failing to sign in. */
809
+ const NO_CREDENTIAL_ERRORS = /* @__PURE__ */ new Set([
810
+ "AggregateAuthenticationError",
811
+ "AuthenticationRequiredError",
812
+ "CredentialUnavailableError"
813
+ ]);
814
+ /** The variables `DefaultAzureCredential` signs in with first, if complete. */
815
+ const environmentCredentialVariables = () => {
816
+ const { env } = process;
817
+ if (!env["AZURE_TENANT_ID"] || !env["AZURE_CLIENT_ID"]) return void 0;
818
+ if (env["AZURE_CLIENT_SECRET"]) return "AZURE_CLIENT_SECRET";
819
+ if (env["AZURE_CLIENT_CERTIFICATE_PATH"]) return "AZURE_CLIENT_CERTIFICATE_PATH";
820
+ if (env["AZURE_USERNAME"] && env["AZURE_PASSWORD"]) return "AZURE_PASSWORD";
821
+ };
822
+ /**
823
+ * The one step that can fix the identity in use: `az login` changes nothing
824
+ * while the environment's identity comes first.
825
+ */
826
+ const signInHint = (credential) => {
827
+ if (credential !== void 0) return [`Check the credential passed to ${NAME}().`];
828
+ const variable = environmentCredentialVariables();
829
+ if (variable) return [`Fix or unset ${variable}, AZURE_TENANT_ID, and AZURE_CLIENT_ID.`];
830
+ return process.env["CI"] ? ["Sign in with azure/login."] : ["Sign in:", "az login"];
831
+ };
832
+ /** An error of one line each, for a terminal. */
833
+ const failure = (lines, cause) => new Error(lines.join("\n"), cause === void 0 ? void 0 : { cause });
834
+ const READ_ROLE = "Key Vault Secrets User";
835
+ const WRITE_ROLE = "Key Vault Secrets Officer";
836
+ const errorName = (error) => error instanceof Error ? error.name : "";
837
+ /** The message's first line: Key Vault's next lines name the caller's IDs. */
838
+ const errorMessage = (error) => ((error instanceof Error ? error.message : String(error)).split(/\r?\n/u, 1)[0] ?? "").replace(/\.+$/u, "");
839
+ const innerCode = (error) => {
840
+ const inner = error?.details?.error;
841
+ return inner?.innerError?.code ?? inner?.innererror?.code;
842
+ };
843
+ const statusOf = (error) => error?.statusCode;
844
+ const isLoopback = (hostname) => (/* @__PURE__ */ new Set([
845
+ "localhost",
846
+ "127.0.0.1",
847
+ "[::1]"
848
+ ])).has(hostname);
849
+ const resolveVaultUrl = (vaultName, vaultUrl) => {
850
+ if (vaultName === void 0 === (vaultUrl === void 0)) throw new Error(`${NAME} needs a vaultName or a vaultUrl, and not both.`);
851
+ if (vaultName !== void 0) {
852
+ 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."]);
853
+ return new URL(`https://${vaultName.toLowerCase()}.vault.azure.net`);
854
+ }
855
+ let url;
856
+ try {
857
+ url = new URL(String(vaultUrl).trim());
858
+ } catch {
859
+ throw new Error(`${NAME} vaultUrl must be a valid URL.`);
860
+ }
861
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.pathname !== "/" && url.pathname !== "") throw failure([
862
+ `${NAME} can't use its vaultUrl.`,
863
+ "Use an HTTPS origin, such as https://my-vault.vault.azure.net.",
864
+ "Leave out credentials, a path, a query, and a fragment."
865
+ ]);
866
+ return url;
867
+ };
868
+ /** Masks a value in the CLI's output, which loads `@hot-updater/cli-tools`. */
869
+ const mask = async (values) => {
870
+ const { registerSecretValue } = await import("@hot-updater/cli-tools");
871
+ for (const value of values) if (value) registerSecretValue(value);
872
+ };
873
+ /** `credential`, with each access token it returns masked. */
874
+ const maskTokens = (credential) => ({ getToken: async (scopes, options) => {
875
+ const token = await credential.getToken(scopes, options);
876
+ await mask([token?.token]);
877
+ return token;
878
+ } });
879
+ /**
880
+ * The Key Vault secret name of `name`, after `prefix`. Key Vault takes
881
+ * only letters, digits, and `-` in a name, and matches names without
882
+ * regard to case, so:
883
+ *
884
+ * - a name of lower-case letters and digits in words joined by single
885
+ * hyphens, such as `asc-api-key`, is kept as it is;
886
+ * - any other name, such as `CLOUDFLARE_API_TOKEN` or `upload.keystore`,
887
+ * becomes its lower-cased words joined by `-`, then `--` and the first 10
888
+ * hex digits of the SHA-256 of the exact name:
889
+ * `cloudflare-api-token--<hash>`.
890
+ *
891
+ * A kept name never holds `--` and a mapped one always does, so no two
892
+ * names share a secret, and `CLOUDFLARE_API_TOKEN` and
893
+ * `cloudflare-api-token` stay apart. Each secret `set` stores is tagged
894
+ * `hot-updater-name` with the name it holds.
895
+ */
896
+ const keyVaultSecretName = (name, prefix = "hot-updater-") => {
897
+ if (PLAIN_NAME_PATTERN.test(name)) return `${prefix}${name}`;
898
+ return `${prefix}${name.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "")}--${(0, node_crypto.createHash)("sha256").update(name).digest("hex").slice(0, 10)}`;
899
+ };
900
+ /**
901
+ * Secrets from Azure Key Vault: each name is the secret `<prefix><name>`
902
+ * of the vault, `hot-updater-asc-api-key` for `asc-api-key`, with any
903
+ * other name mapped as `keyVaultSecretName` says, read at its current
904
+ * version. `set` adds a new version of
905
+ * the secret, which creates it when it does not exist; Key Vault keeps the
906
+ * older versions. A name whose secret was deleted and is still recoverable
907
+ * reads as missing, and `set` on it fails with the `az` commands that
908
+ * recover or purge it. `@azure/keyvault-secrets`, and `@azure/identity`
909
+ * without a `credential`, load on the first read or write, so a config
910
+ * that only uses `azureBlobStorage` never loads them.
911
+ *
912
+ * @example
913
+ * secrets: keyVault({ vaultName: "my-vault" })
914
+ */
915
+ const keyVault = ({ credential, prefix = "hot-updater-", vaultName, vaultUrl }) => {
916
+ const vault = () => {
917
+ const url = resolveVaultUrl(vaultName, vaultUrl);
918
+ if (typeof prefix !== "string" || !PREFIX_PATTERN.test(prefix)) throw new Error(`${NAME}'s prefix takes letters, digits, and - only.`);
919
+ return url;
920
+ };
921
+ const secretName = (name) => {
922
+ vault();
923
+ const id = keyVaultSecretName(name, prefix);
924
+ 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.`]);
925
+ return id;
926
+ };
927
+ /** The vault's name, for the az commands messages suggest. */
928
+ const vaultLabel = () => vault().hostname.split(".")[0];
929
+ let opened;
930
+ const open = () => {
931
+ const url = vault();
932
+ if (credential !== void 0 && !(0, _azure_core_auth.isTokenCredential)(credential)) throw new Error(`${NAME} credential must be a TokenCredential, such as one from @azure/identity.`);
933
+ 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) => {
934
+ opened = void 0;
935
+ throw error;
936
+ });
937
+ return opened;
938
+ };
939
+ const describeFailure = (verb, id, error, role) => {
940
+ const name = errorName(error);
941
+ const status = statusOf(error);
942
+ const code = innerCode(error) ?? error?.code;
943
+ if (NO_CREDENTIAL_ERRORS.has(name)) return failure([`${NAME} found no Azure identity.`, ...signInHint(credential)], error);
944
+ if (status === 401 || name === "AuthenticationError") return failure(["Azure rejected the sign-in.", ...signInHint(credential)], error);
945
+ 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);
946
+ if (code === "SecretDisabled") return failure([`${id}'s current version is disabled. Enable it, or store a new value.`], error);
947
+ 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);
948
+ if (code === "ObjectIsBeingDeleted" || /being deleted/iu.test(errorMessage(error))) return failure([`${id} is being deleted. Try again in a minute.`], error);
949
+ if (status === 409 || code === "ObjectIsDeletedButRecoverable") {
950
+ const vaultName = vaultLabel();
951
+ return failure([
952
+ `${id} was deleted. Recover it, or purge it:`,
953
+ `az keyvault secret recover --vault-name ${vaultName} --name ${id}`,
954
+ `az keyvault secret purge --vault-name ${vaultName} --name ${id}`
955
+ ], error);
956
+ }
957
+ return failure([`Azure Key Vault failed to ${verb} ${id}.`, `${code || name || "Error"}${status ? ` (${status})` : ""}: ${errorMessage(error)}.`], error);
958
+ };
959
+ const read = async (client, id) => {
960
+ let value;
961
+ try {
962
+ ({value} = await client.getSecret(id));
963
+ } catch (error) {
964
+ if (statusOf(error) === 404 && /NotFound/u.test(error.code ?? "") && !/disabled/iu.test(errorMessage(error))) return;
965
+ throw describeFailure("read", id, error, READ_ROLE);
966
+ }
967
+ await mask([value]);
968
+ return value;
969
+ };
970
+ return {
971
+ name: NAME,
972
+ get: async (names) => {
973
+ const unique = [...new Set(names)];
974
+ const ids = unique.map(secretName);
975
+ const result = Object.create(null);
976
+ if (unique.length === 0) return result;
977
+ const client = await open();
978
+ const values = await Promise.all(ids.map((id) => read(client, id)));
979
+ unique.forEach((name, index) => {
980
+ result[name] = values[index];
981
+ });
982
+ return result;
983
+ },
984
+ set: async (name, value) => {
985
+ const id = secretName(name);
986
+ if (typeof value !== "string" || value === "") throw new Error(`${NAME} can't store an empty ${id}.`);
987
+ 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.`]);
988
+ await mask([value]);
989
+ const client = await open();
990
+ try {
991
+ await client.setSecret(id, value, { tags: { [NAME_TAG]: name } });
992
+ } catch (error) {
993
+ throw describeFailure("write", id, error, WRITE_ROLE);
994
+ }
995
+ },
996
+ describe: (name) => {
997
+ let url;
998
+ try {
999
+ url = vault().origin;
1000
+ } catch {
1001
+ url = String(vaultUrl ?? vaultName);
1002
+ }
1003
+ return `the secret ${JSON.stringify(keyVaultSecretName(name, prefix))} in Azure Key Vault (${url})`;
1004
+ }
1005
+ };
1006
+ };
1007
+ //#endregion
780
1008
  exports.azureBlobStorage = azureBlobStorage;
781
1009
  exports.cosmosDatabase = cosmosDatabase;
1010
+ exports.keyVault = keyVault;
782
1011
  exports.migrateCosmosDatabase = migrateCosmosDatabase;
package/dist/index.d.cts CHANGED
@@ -1,11 +1,16 @@
1
1
  import { TokenCredential } from "@azure/core-auth";
2
2
  import { StorageSharedKeyCredential } from "@azure/storage-blob";
3
- import { EngineDatabase, PluginTables, StorageAdapter, StorageAdapterWith } from "@hot-updater/plugin-core";
3
+ import { EngineDatabase, Lazy, PluginTables, SecretsAdapter, StorageAdapter, StorageAdapterWith } from "@hot-updater/plugin-core";
4
4
  import { CosmosClientOptions } from "@azure/cosmos";
5
5
  //#region src/azureBlobStorage.d.ts
6
6
  /** The account to connect to: its connection string, or its Blob endpoint and a credential. */
7
7
  type AzureBlobConnection = {
8
- readonly connectionString: string;
8
+ /**
9
+ * The account's connection string, or a function that returns it,
10
+ * such as `secret("<name>")` in `hot-updater.config.ts`: called on
11
+ * first use, so a config loads without it.
12
+ */
13
+ readonly connectionString: Lazy<string>;
9
14
  } | {
10
15
  /** The Blob service endpoint, such as `https://<account>.blob.core.windows.net`. */
11
16
  readonly accountUrl: string;
@@ -38,7 +43,14 @@ declare function azureBlobStorage(config: AzureBlobStorageConfig): StorageAdapte
38
43
  * `endpoint` with a `key` or Microsoft Entra `aadCredentials`. Reads must
39
44
  * be strongly consistent, so `consistencyLevel` takes only `"Strong"`.
40
45
  */
41
- type CosmosDatabaseConfig = Omit<CosmosClientOptions, "consistencyLevel"> & {
46
+ type CosmosDatabaseConfig = Omit<CosmosClientOptions, "consistencyLevel" | "connectionString"> & {
47
+ /**
48
+ * The account's connection string, or a function that returns it, such as
49
+ * `secret("<name>")` in `hot-updater.config.ts`: called on the first
50
+ * request, so a config loads without it. `endpoint` beside a function
51
+ * names the account to `hot-updater doctor`.
52
+ */
53
+ readonly connectionString?: Lazy<string>;
42
54
  readonly consistencyLevel?: "Strong";
43
55
  /** The database the container lives in. @default "hot-updater" */
44
56
  readonly databaseId?: string;
@@ -46,9 +58,8 @@ type CosmosDatabaseConfig = Omit<CosmosClientOptions, "consistencyLevel"> & {
46
58
  readonly containerId?: string;
47
59
  /**
48
60
  * Cosmos DB bills each item a write touches, so Insights' aggregates are
49
- * batched: through log rows a compaction merges (the default), or
50
- * `{ mode: "memory" }` on a long-lived server. `false` commits them with
51
- * each event.
61
+ * batched: through log rows a compaction merges (the default). `false` commits
62
+ * them with each event.
52
63
  */
53
64
  readonly aggregateBatching?: EngineDatabase["aggregateBatching"] | false;
54
65
  };
@@ -68,4 +79,51 @@ declare const migrateCosmosDatabase: (config: CosmosDatabaseConfig, plugins?: re
68
79
  */
69
80
  declare const cosmosDatabase: (config: CosmosDatabaseConfig) => EngineDatabase;
70
81
  //#endregion
71
- export { AzureBlobConnection, AzureBlobStorageConfig, CosmosDatabaseConfig, azureBlobStorage, cosmosDatabase, migrateCosmosDatabase };
82
+ //#region src/keyVault.d.ts
83
+ interface KeyVaultOptions {
84
+ /**
85
+ * The vault's name, which reads `https://<vaultName>.vault.azure.net`.
86
+ * Set it or `vaultUrl`.
87
+ */
88
+ readonly vaultName?: string;
89
+ /**
90
+ * The vault's URL, such as `https://my-vault.vault.azure.net`, for a
91
+ * vault outside Azure's public cloud. An HTTPS URL on a loopback address,
92
+ * such as a local emulator's, skips the check that the sign-in challenge
93
+ * names the vault's domain.
94
+ */
95
+ readonly vaultUrl?: string;
96
+ /**
97
+ * Put before each name to make its secret's name, so `secret("asc-api-key")`
98
+ * reads the secret `hot-updater-asc-api-key`. Letters, digits, and `-`.
99
+ *
100
+ * @default "hot-updater-"
101
+ */
102
+ readonly prefix?: string;
103
+ /**
104
+ * The Microsoft Entra identity to sign in with, such as a
105
+ * `ClientSecretCredential` from `@azure/identity`. Without it,
106
+ * `DefaultAzureCredential`: `AZURE_CLIENT_ID` and its siblings, or the
107
+ * federated token `azure/login` leaves in CI, then `az login` on your
108
+ * machine, or a managed identity.
109
+ */
110
+ readonly credential?: TokenCredential;
111
+ }
112
+ /**
113
+ * Secrets from Azure Key Vault: each name is the secret `<prefix><name>`
114
+ * of the vault, `hot-updater-asc-api-key` for `asc-api-key`, with any
115
+ * other name mapped as `keyVaultSecretName` says, read at its current
116
+ * version. `set` adds a new version of
117
+ * the secret, which creates it when it does not exist; Key Vault keeps the
118
+ * older versions. A name whose secret was deleted and is still recoverable
119
+ * reads as missing, and `set` on it fails with the `az` commands that
120
+ * recover or purge it. `@azure/keyvault-secrets`, and `@azure/identity`
121
+ * without a `credential`, load on the first read or write, so a config
122
+ * that only uses `azureBlobStorage` never loads them.
123
+ *
124
+ * @example
125
+ * secrets: keyVault({ vaultName: "my-vault" })
126
+ */
127
+ declare const keyVault: ({ credential, prefix, vaultName, vaultUrl }: KeyVaultOptions) => SecretsAdapter;
128
+ //#endregion
129
+ export { AzureBlobConnection, AzureBlobStorageConfig, CosmosDatabaseConfig, KeyVaultOptions, azureBlobStorage, cosmosDatabase, keyVault, migrateCosmosDatabase };
package/dist/index.d.mts CHANGED
@@ -1,11 +1,16 @@
1
1
  import { TokenCredential } from "@azure/core-auth";
2
2
  import { StorageSharedKeyCredential } from "@azure/storage-blob";
3
- import { EngineDatabase, PluginTables, StorageAdapter, StorageAdapterWith } from "@hot-updater/plugin-core";
3
+ import { EngineDatabase, Lazy, PluginTables, SecretsAdapter, StorageAdapter, StorageAdapterWith } from "@hot-updater/plugin-core";
4
4
  import { CosmosClientOptions } from "@azure/cosmos";
5
5
  //#region src/azureBlobStorage.d.ts
6
6
  /** The account to connect to: its connection string, or its Blob endpoint and a credential. */
7
7
  type AzureBlobConnection = {
8
- readonly connectionString: string;
8
+ /**
9
+ * The account's connection string, or a function that returns it,
10
+ * such as `secret("<name>")` in `hot-updater.config.ts`: called on
11
+ * first use, so a config loads without it.
12
+ */
13
+ readonly connectionString: Lazy<string>;
9
14
  } | {
10
15
  /** The Blob service endpoint, such as `https://<account>.blob.core.windows.net`. */
11
16
  readonly accountUrl: string;
@@ -38,7 +43,14 @@ declare function azureBlobStorage(config: AzureBlobStorageConfig): StorageAdapte
38
43
  * `endpoint` with a `key` or Microsoft Entra `aadCredentials`. Reads must
39
44
  * be strongly consistent, so `consistencyLevel` takes only `"Strong"`.
40
45
  */
41
- type CosmosDatabaseConfig = Omit<CosmosClientOptions, "consistencyLevel"> & {
46
+ type CosmosDatabaseConfig = Omit<CosmosClientOptions, "consistencyLevel" | "connectionString"> & {
47
+ /**
48
+ * The account's connection string, or a function that returns it, such as
49
+ * `secret("<name>")` in `hot-updater.config.ts`: called on the first
50
+ * request, so a config loads without it. `endpoint` beside a function
51
+ * names the account to `hot-updater doctor`.
52
+ */
53
+ readonly connectionString?: Lazy<string>;
42
54
  readonly consistencyLevel?: "Strong";
43
55
  /** The database the container lives in. @default "hot-updater" */
44
56
  readonly databaseId?: string;
@@ -46,9 +58,8 @@ type CosmosDatabaseConfig = Omit<CosmosClientOptions, "consistencyLevel"> & {
46
58
  readonly containerId?: string;
47
59
  /**
48
60
  * Cosmos DB bills each item a write touches, so Insights' aggregates are
49
- * batched: through log rows a compaction merges (the default), or
50
- * `{ mode: "memory" }` on a long-lived server. `false` commits them with
51
- * each event.
61
+ * batched: through log rows a compaction merges (the default). `false` commits
62
+ * them with each event.
52
63
  */
53
64
  readonly aggregateBatching?: EngineDatabase["aggregateBatching"] | false;
54
65
  };
@@ -68,4 +79,51 @@ declare const migrateCosmosDatabase: (config: CosmosDatabaseConfig, plugins?: re
68
79
  */
69
80
  declare const cosmosDatabase: (config: CosmosDatabaseConfig) => EngineDatabase;
70
81
  //#endregion
71
- export { AzureBlobConnection, AzureBlobStorageConfig, CosmosDatabaseConfig, azureBlobStorage, cosmosDatabase, migrateCosmosDatabase };
82
+ //#region src/keyVault.d.ts
83
+ interface KeyVaultOptions {
84
+ /**
85
+ * The vault's name, which reads `https://<vaultName>.vault.azure.net`.
86
+ * Set it or `vaultUrl`.
87
+ */
88
+ readonly vaultName?: string;
89
+ /**
90
+ * The vault's URL, such as `https://my-vault.vault.azure.net`, for a
91
+ * vault outside Azure's public cloud. An HTTPS URL on a loopback address,
92
+ * such as a local emulator's, skips the check that the sign-in challenge
93
+ * names the vault's domain.
94
+ */
95
+ readonly vaultUrl?: string;
96
+ /**
97
+ * Put before each name to make its secret's name, so `secret("asc-api-key")`
98
+ * reads the secret `hot-updater-asc-api-key`. Letters, digits, and `-`.
99
+ *
100
+ * @default "hot-updater-"
101
+ */
102
+ readonly prefix?: string;
103
+ /**
104
+ * The Microsoft Entra identity to sign in with, such as a
105
+ * `ClientSecretCredential` from `@azure/identity`. Without it,
106
+ * `DefaultAzureCredential`: `AZURE_CLIENT_ID` and its siblings, or the
107
+ * federated token `azure/login` leaves in CI, then `az login` on your
108
+ * machine, or a managed identity.
109
+ */
110
+ readonly credential?: TokenCredential;
111
+ }
112
+ /**
113
+ * Secrets from Azure Key Vault: each name is the secret `<prefix><name>`
114
+ * of the vault, `hot-updater-asc-api-key` for `asc-api-key`, with any
115
+ * other name mapped as `keyVaultSecretName` says, read at its current
116
+ * version. `set` adds a new version of
117
+ * the secret, which creates it when it does not exist; Key Vault keeps the
118
+ * older versions. A name whose secret was deleted and is still recoverable
119
+ * reads as missing, and `set` on it fails with the `az` commands that
120
+ * recover or purge it. `@azure/keyvault-secrets`, and `@azure/identity`
121
+ * without a `credential`, load on the first read or write, so a config
122
+ * that only uses `azureBlobStorage` never loads them.
123
+ *
124
+ * @example
125
+ * secrets: keyVault({ vaultName: "my-vault" })
126
+ */
127
+ declare const keyVault: ({ credential, prefix, vaultName, vaultUrl }: KeyVaultOptions) => SecretsAdapter;
128
+ //#endregion
129
+ export { AzureBlobConnection, AzureBlobStorageConfig, CosmosDatabaseConfig, KeyVaultOptions, azureBlobStorage, cosmosDatabase, keyVault, migrateCosmosDatabase };