@mp-lb/forum-secrets 0.2.4 → 0.2.6

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.js CHANGED
@@ -1257,8 +1257,8 @@ function cleanEnum(obj) {
1257
1257
  return Number.isNaN(Number.parseInt(k, 10));
1258
1258
  }).map((el) => el[1]);
1259
1259
  }
1260
- function base64ToUint8Array(base643) {
1261
- const binaryString = atob(base643);
1260
+ function base64ToUint8Array(base644) {
1261
+ const binaryString = atob(base644);
1262
1262
  const bytes = new Uint8Array(binaryString.length);
1263
1263
  for (let i = 0; i < binaryString.length; i++) {
1264
1264
  bytes[i] = binaryString.charCodeAt(i);
@@ -1273,9 +1273,9 @@ function uint8ArrayToBase64(bytes) {
1273
1273
  return btoa(binaryString);
1274
1274
  }
1275
1275
  function base64urlToUint8Array(base64url3) {
1276
- const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1277
- const padding = "=".repeat((4 - base643.length % 4) % 4);
1278
- return base64ToUint8Array(base643 + padding);
1276
+ const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1277
+ const padding = "=".repeat((4 - base644.length % 4) % 4);
1278
+ return base64ToUint8Array(base644 + padding);
1279
1279
  }
1280
1280
  function uint8ArrayToBase64url(bytes) {
1281
1281
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
@@ -2641,8 +2641,8 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
2641
2641
  function isValidBase64URL(data) {
2642
2642
  if (!base64url.test(data))
2643
2643
  return false;
2644
- const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
2645
- const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
2644
+ const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
2645
+ const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "=");
2646
2646
  return isValidBase64(padded);
2647
2647
  }
2648
2648
  var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
@@ -14519,8 +14519,8 @@ function date4(params) {
14519
14519
  config(en_default());
14520
14520
 
14521
14521
  // ../encryption/src/bytes/base64ToBytes.ts
14522
- var base64ToBytes = (base643) => {
14523
- const binary = atob(base643);
14522
+ var base64ToBytes = (base644) => {
14523
+ const binary = atob(base644);
14524
14524
  const bytes = new Uint8Array(binary.length);
14525
14525
  for (let index = 0; index < binary.length; index += 1) {
14526
14526
  bytes[index] = binary.charCodeAt(index);
@@ -14534,8 +14534,197 @@ var toBufferSource = (bytes) => bytes.buffer.slice(
14534
14534
  bytes.byteOffset + bytes.byteLength
14535
14535
  );
14536
14536
 
14537
- // ../encryption/src/keyBinding/createUserEncryptionKeyBinding.ts
14537
+ // ../encryption/src/cipherNames.ts
14538
+ var encryptedFileCipher = "AES-GCM";
14539
+ var publicKeyCipher = "RSA-OAEP-SHA-256";
14540
+
14541
+ // ../encryption/src/envelope/EncryptedEnvelopeMismatchError.ts
14542
+ var messages = {
14543
+ different_object: "This encrypted content belongs to a different encrypted file than expected.",
14544
+ stale: "This encrypted content is an older revision than expected; it may have been replayed or restored.",
14545
+ unbound: "This encrypted content uses an older format without an authenticated identity, but an identity was expected."
14546
+ };
14547
+ var EncryptedEnvelopeMismatchError = class extends Error {
14548
+ continuity;
14549
+ constructor(continuity) {
14550
+ super(messages[continuity] ?? "Unexpected encrypted content.");
14551
+ this.name = "EncryptedEnvelopeMismatchError";
14552
+ this.continuity = continuity;
14553
+ }
14554
+ };
14555
+
14556
+ // ../encryption/src/envelope/readEncryptedEnvelopeIdentity.ts
14557
+ var readEncryptedEnvelopeIdentity = (envelope) => envelope.doctrineEncryptedFile === 4 ? { objectId: envelope.objectId, revision: envelope.revision } : null;
14558
+
14559
+ // ../encryption/src/envelope/assertEncryptedEnvelopeExpectation.ts
14560
+ var assertEncryptedEnvelopeExpectation = (envelope, { minRevision, objectId }) => {
14561
+ if (objectId === void 0 && minRevision === void 0) {
14562
+ return;
14563
+ }
14564
+ const identity = readEncryptedEnvelopeIdentity(envelope);
14565
+ if (!identity) {
14566
+ throw new EncryptedEnvelopeMismatchError("unbound");
14567
+ }
14568
+ if (objectId !== void 0 && identity.objectId !== objectId) {
14569
+ throw new EncryptedEnvelopeMismatchError("different_object");
14570
+ }
14571
+ if (minRevision !== void 0 && identity.revision < minRevision) {
14572
+ throw new EncryptedEnvelopeMismatchError("stale");
14573
+ }
14574
+ };
14575
+
14576
+ // ../encryption/src/envelope/encryptedEnvelopeLimits.ts
14577
+ var encryptedEnvelopeLimits = {
14578
+ maxEnvelopeChars: 16 * 1024 * 1024,
14579
+ maxLabelChars: 512,
14580
+ maxRecipientIdChars: 256,
14581
+ maxRecipients: 256,
14582
+ maxRevision: Number.MAX_SAFE_INTEGER,
14583
+ maxWrappedKeyChars: 2048
14584
+ };
14585
+
14586
+ // ../encryption/src/envelope/createEncryptedEnvelopeBinding.ts
14587
+ var encryptedEnvelopeBindingPurpose = "forum-encrypted-file-envelope";
14538
14588
  var textEncoder = new TextEncoder();
14589
+ var createEncryptedEnvelopeBinding = (header) => textEncoder.encode(
14590
+ JSON.stringify([
14591
+ encryptedEnvelopeBindingPurpose,
14592
+ header.doctrineEncryptedFile,
14593
+ header.cipher,
14594
+ header.objectId,
14595
+ header.revision,
14596
+ header.workspaceAccess,
14597
+ header.recipients.map((recipient) => [
14598
+ recipient.recipientId,
14599
+ recipient.label ?? null,
14600
+ recipient.wrappedDataKey.cipher,
14601
+ recipient.wrappedDataKey.data,
14602
+ recipient.wrappedDataKey.cipher === encryptedFileCipher ? recipient.wrappedDataKey.iv : null
14603
+ ])
14604
+ ])
14605
+ );
14606
+
14607
+ // ../encryption/src/envelope/EncryptedEnvelopeFormatError.ts
14608
+ var EncryptedEnvelopeFormatError = class extends Error {
14609
+ constructor(detail) {
14610
+ super(
14611
+ detail ? `Unsupported encrypted file format: ${detail}` : "Unsupported encrypted file format."
14612
+ );
14613
+ this.name = "EncryptedEnvelopeFormatError";
14614
+ }
14615
+ };
14616
+
14617
+ // ../encryption/src/envelope/encryptedEnvelopeVersions.ts
14618
+ var legacyEncryptedEnvelopeVersion = 2;
14619
+ var unboundEncryptedEnvelopeVersion = 3;
14620
+ var boundEncryptedEnvelopeVersion = 4;
14621
+
14622
+ // ../encryption/src/envelope/encryptedEnvelopeSchemas.ts
14623
+ var base64Pattern = /^[A-Za-z0-9+/]+={0,2}$/;
14624
+ var base643 = (maxChars) => external_exports.string().min(1).max(maxChars).regex(base64Pattern, "Expected base64.");
14625
+ var ivSchema = external_exports.string().length(16).regex(base64Pattern, "Expected base64.");
14626
+ var untrimmedText = (maxChars) => external_exports.string().min(1).max(maxChars).refine((value) => value.trim() === value, "Unexpected whitespace.");
14627
+ var boundAesWrappedKeySchema = external_exports.strictObject({
14628
+ cipher: external_exports.literal(encryptedFileCipher),
14629
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars),
14630
+ iv: ivSchema
14631
+ });
14632
+ var boundPublicKeyWrappedKeySchema = external_exports.strictObject({
14633
+ cipher: external_exports.literal(publicKeyCipher),
14634
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars)
14635
+ });
14636
+ var boundRecipientSchema = external_exports.strictObject({
14637
+ label: untrimmedText(encryptedEnvelopeLimits.maxLabelChars).optional(),
14638
+ recipientId: untrimmedText(encryptedEnvelopeLimits.maxRecipientIdChars),
14639
+ wrappedDataKey: external_exports.discriminatedUnion("cipher", [
14640
+ boundAesWrappedKeySchema,
14641
+ boundPublicKeyWrappedKeySchema
14642
+ ])
14643
+ });
14644
+ var hasUniqueRecipientIds = (recipients) => new Set(recipients.map((recipient) => recipient.recipientId)).size === recipients.length;
14645
+ var boundHeaderShape = {
14646
+ doctrineEncryptedFile: external_exports.literal(boundEncryptedEnvelopeVersion),
14647
+ cipher: external_exports.literal(encryptedFileCipher),
14648
+ objectId: external_exports.uuid(),
14649
+ revision: external_exports.number().int().min(0).max(encryptedEnvelopeLimits.maxRevision),
14650
+ workspaceAccess: external_exports.enum(["personal", "team"]),
14651
+ recipients: external_exports.array(boundRecipientSchema).min(1).max(encryptedEnvelopeLimits.maxRecipients).refine(hasUniqueRecipientIds, "Duplicate recipient id.")
14652
+ };
14653
+ var boundEncryptedEnvelopeHeaderSchema = external_exports.strictObject(boundHeaderShape);
14654
+ var boundEncryptedEnvelopeSchema = external_exports.strictObject({
14655
+ ...boundHeaderShape,
14656
+ data: base643(encryptedEnvelopeLimits.maxEnvelopeChars),
14657
+ iv: ivSchema
14658
+ });
14659
+ var unboundWrappedKeySchema = external_exports.discriminatedUnion("cipher", [
14660
+ external_exports.object({
14661
+ cipher: external_exports.literal(encryptedFileCipher),
14662
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars),
14663
+ iv: ivSchema
14664
+ }),
14665
+ external_exports.object({
14666
+ cipher: external_exports.literal(publicKeyCipher),
14667
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars)
14668
+ })
14669
+ ]);
14670
+ var unboundRecipientsSchema = external_exports.array(
14671
+ external_exports.object({
14672
+ label: external_exports.string().trim().min(1).max(encryptedEnvelopeLimits.maxLabelChars).optional(),
14673
+ recipientId: external_exports.string().trim().min(1).max(encryptedEnvelopeLimits.maxRecipientIdChars),
14674
+ wrappedDataKey: unboundWrappedKeySchema
14675
+ })
14676
+ ).min(1).max(encryptedEnvelopeLimits.maxRecipients);
14677
+ var unboundBodyShape = {
14678
+ cipher: external_exports.literal(encryptedFileCipher),
14679
+ data: base643(encryptedEnvelopeLimits.maxEnvelopeChars),
14680
+ iv: ivSchema,
14681
+ recipients: unboundRecipientsSchema
14682
+ };
14683
+ var legacyEncryptedEnvelopeSchema = external_exports.object({
14684
+ ...unboundBodyShape,
14685
+ doctrineEncryptedFile: external_exports.literal(legacyEncryptedEnvelopeVersion)
14686
+ });
14687
+ var unboundEncryptedEnvelopeSchema = external_exports.object({
14688
+ ...unboundBodyShape,
14689
+ doctrineEncryptedFile: external_exports.literal(unboundEncryptedEnvelopeVersion),
14690
+ workspaceAccess: external_exports.enum(["personal", "team"]).default("personal")
14691
+ });
14692
+
14693
+ // ../encryption/src/envelope/parseEncryptedEnvelope.ts
14694
+ var schemaByVersion = /* @__PURE__ */ new Map([
14695
+ [2, legacyEncryptedEnvelopeSchema],
14696
+ [3, unboundEncryptedEnvelopeSchema],
14697
+ [4, boundEncryptedEnvelopeSchema]
14698
+ ]);
14699
+ var readVersion = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value.doctrineEncryptedFile : void 0;
14700
+ var parseEncryptedEnvelope = (encryptedText) => {
14701
+ if (typeof encryptedText !== "string") {
14702
+ throw new EncryptedEnvelopeFormatError("expected text.");
14703
+ }
14704
+ if (encryptedText.length > encryptedEnvelopeLimits.maxEnvelopeChars) {
14705
+ throw new EncryptedEnvelopeFormatError("the file is too large.");
14706
+ }
14707
+ let parsed;
14708
+ try {
14709
+ parsed = JSON.parse(encryptedText);
14710
+ } catch {
14711
+ throw new EncryptedEnvelopeFormatError("not valid JSON.");
14712
+ }
14713
+ const schema = schemaByVersion.get(readVersion(parsed));
14714
+ if (!schema) {
14715
+ throw new EncryptedEnvelopeFormatError("unknown envelope version.");
14716
+ }
14717
+ const result = schema.safeParse(parsed);
14718
+ if (!result.success) {
14719
+ const issue2 = result.error.issues[0];
14720
+ const path = issue2?.path?.join(".") || "envelope";
14721
+ throw new EncryptedEnvelopeFormatError(`invalid ${path}.`);
14722
+ }
14723
+ return result.data;
14724
+ };
14725
+
14726
+ // ../encryption/src/keyBinding/createUserEncryptionKeyBinding.ts
14727
+ var textEncoder2 = new TextEncoder();
14539
14728
 
14540
14729
  // ../encryption/src/kdf/userEncryptionKdfNames.ts
14541
14730
  var pbkdf2Sha256KdfName = "PBKDF2-SHA-256";
@@ -14598,13 +14787,11 @@ var userEncryptionKdfSchema = external_exports.union([
14598
14787
  ]);
14599
14788
 
14600
14789
  // ../encryption/src/kdf/deriveUserEncryptionPasswordKey.ts
14601
- var textEncoder2 = new TextEncoder();
14790
+ var textEncoder3 = new TextEncoder();
14602
14791
 
14603
14792
  // ../encryption/src/fileEncryption.ts
14604
14793
  var legacyEncryptedFileVersion = 2;
14605
14794
  var currentEncryptedFileVersion = 3;
14606
- var encryptedFileCipher = "AES-GCM";
14607
- var publicKeyCipher = "RSA-OAEP-SHA-256";
14608
14795
  var externalRecipientSecretPrefix = "doctrine-recipient-v1_";
14609
14796
  var forumRecipientSecretPrefix = externalRecipientSecretPrefix;
14610
14797
  var storeEncryptedValueSchema = external_exports.object({
@@ -14697,7 +14884,7 @@ var userEncryptionMetadataSchema = external_exports.union([
14697
14884
  unboundUserEncryptionMetadataSchema,
14698
14885
  boundUserEncryptionMetadataSchema
14699
14886
  ]);
14700
- var textEncoder3 = new TextEncoder();
14887
+ var textEncoder4 = new TextEncoder();
14701
14888
  var textDecoder = new TextDecoder();
14702
14889
  var rsaKeyGenerationAlgorithm = {
14703
14890
  hash: "SHA-256",
@@ -14729,6 +14916,30 @@ var decryptBytes = async ({
14729
14916
  toBufferSource(base64ToBytes(data))
14730
14917
  )
14731
14918
  );
14919
+ var envelopeAdditionalData = (envelope) => envelope.doctrineEncryptedFile === boundEncryptedEnvelopeVersion ? createEncryptedEnvelopeBinding(envelope) : void 0;
14920
+ var decryptEnvelopeBytes = async ({
14921
+ envelope,
14922
+ expectation,
14923
+ fileKey
14924
+ }) => {
14925
+ let bytes;
14926
+ try {
14927
+ bytes = await decryptBytes({
14928
+ additionalData: envelopeAdditionalData(envelope),
14929
+ data: envelope.data,
14930
+ iv: envelope.iv,
14931
+ key: fileKey
14932
+ });
14933
+ } catch {
14934
+ throw new Error(
14935
+ "Could not decrypt the encrypted file: the key is wrong, or the encrypted file or its protected metadata was modified."
14936
+ );
14937
+ }
14938
+ if (expectation) {
14939
+ assertEncryptedEnvelopeExpectation(envelope, expectation);
14940
+ }
14941
+ return bytes;
14942
+ };
14732
14943
  var importForumRecipientSecretKey = async (secret) => {
14733
14944
  if (!secret.startsWith(forumRecipientSecretPrefix)) {
14734
14945
  throw new Error("Unsupported Forum recipient secret.");
@@ -14757,17 +14968,10 @@ var unwrapFileKeyBytesForRecipientSecret = async ({
14757
14968
  }
14758
14969
  throw new Error("No recipient matched the Forum recipient secret.");
14759
14970
  };
14760
- var parseForumEncryptedFilePayload = (encryptedText) => {
14761
- const parsed = JSON.parse(
14762
- encryptedText
14763
- );
14764
- if (parsed.doctrineEncryptedFile !== legacyEncryptedFileVersion && parsed.doctrineEncryptedFile !== currentEncryptedFileVersion || parsed.cipher !== encryptedFileCipher || typeof parsed.data !== "string" || typeof parsed.iv !== "string" || !Array.isArray(parsed.recipients)) {
14765
- throw new Error("Unsupported Forum encrypted file format.");
14766
- }
14767
- return parsed;
14768
- };
14971
+ var parseForumEncryptedFilePayload = (encryptedText) => parseEncryptedEnvelope(encryptedText);
14769
14972
  var decryptForumEncryptedFile = async ({
14770
14973
  encryptedText,
14974
+ expectation,
14771
14975
  recipientSecret
14772
14976
  }) => {
14773
14977
  const payload = parseForumEncryptedFilePayload(encryptedText);
@@ -14777,14 +14981,34 @@ var decryptForumEncryptedFile = async ({
14777
14981
  recipients: payload.recipients
14778
14982
  });
14779
14983
  const fileKey = await importAesKey(fileKeyBytes, false);
14780
- return decryptBytes({
14781
- data: payload.data,
14782
- iv: payload.iv,
14783
- key: fileKey
14784
- });
14984
+ return decryptEnvelopeBytes({ envelope: payload, expectation, fileKey });
14785
14985
  };
14786
14986
  var decryptForumEncryptedFileText = async (input) => textDecoder.decode(await decryptForumEncryptedFile(input));
14787
14987
 
14988
+ // ../encryption/src/envelope/parseEncryptedEnvelopeExpectation.ts
14989
+ var objectIdSchema = external_exports.uuid();
14990
+ var revisionPattern = /^\d{1,16}$/;
14991
+ var parseEncryptedEnvelopeExpectation = ({
14992
+ minRevision,
14993
+ objectId
14994
+ }) => {
14995
+ const expectation = {};
14996
+ if (objectId != null) {
14997
+ if (!objectIdSchema.safeParse(objectId).success) {
14998
+ throw new Error("--expect-object must be an encrypted object id (UUID).");
14999
+ }
15000
+ expectation.objectId = objectId.toLowerCase();
15001
+ }
15002
+ if (minRevision != null) {
15003
+ const revision = Number(minRevision);
15004
+ if (!revisionPattern.test(minRevision) || revision > encryptedEnvelopeLimits.maxRevision) {
15005
+ throw new Error("--min-revision must be a non-negative integer.");
15006
+ }
15007
+ expectation.minRevision = revision;
15008
+ }
15009
+ return expectation;
15010
+ };
15011
+
14788
15012
  // ../encryption/src/password/encryptionPassphraseRules.ts
14789
15013
  var encryptionPassphraseRules = {
14790
15014
  maxCharacters: 1024,
@@ -14793,6 +15017,41 @@ var encryptionPassphraseRules = {
14793
15017
  };
14794
15018
  var encryptionPassphraseGuidance = `Use at least ${encryptionPassphraseRules.minCharacters} characters. A memorable passphrase of several words is better than a short PIN.`;
14795
15019
 
15020
+ // ../encryption/src/backup/encryptionBackupFormat.ts
15021
+ var encryptionBackupFormat = {
15022
+ name: "forum-encryption-backup",
15023
+ version: 1
15024
+ };
15025
+
15026
+ // ../encryption/src/backup/encryptionBackupSchema.ts
15027
+ var sha256HexSchema = external_exports.string().regex(/^[0-9a-f]{64}$/);
15028
+ var encryptionBackupFileSchema = external_exports.strictObject({
15029
+ path: external_exports.string(),
15030
+ // The file's encrypted envelope exactly as Forum stores it.
15031
+ encryptedText: external_exports.string().min(1),
15032
+ sha256: sha256HexSchema
15033
+ });
15034
+ var encryptionBackupSchema = external_exports.strictObject({
15035
+ format: external_exports.literal(encryptionBackupFormat.name),
15036
+ version: external_exports.literal(encryptionBackupFormat.version),
15037
+ createdAt: external_exports.iso.datetime(),
15038
+ identity: currentUserEncryptionMetadataSchema,
15039
+ fingerprint: sha256HexSchema,
15040
+ files: external_exports.array(encryptionBackupFileSchema),
15041
+ digest: sha256HexSchema
15042
+ });
15043
+
15044
+ // ../encryption/src/machineKeys/machineKeyAlgorithms.ts
15045
+ var machineRsaAlgorithm = {
15046
+ hash: "SHA-256",
15047
+ name: "RSA-OAEP"
15048
+ };
15049
+ var machineRsaKeyGenerationAlgorithm = {
15050
+ ...machineRsaAlgorithm,
15051
+ modulusLength: 2048,
15052
+ publicExponent: Uint8Array.from([1, 0, 1])
15053
+ };
15054
+
14796
15055
  // src/readRecipientSecret.ts
14797
15056
  var readRecipientSecret = (secretArg) => {
14798
15057
  const recipientSecret = secretArg ?? process.env.DOCTRINE_RECIPIENT_SECRET;
@@ -14803,14 +15062,459 @@ var readRecipientSecret = (secretArg) => {
14803
15062
  }
14804
15063
  return recipientSecret;
14805
15064
  };
15065
+
15066
+ // src/credentials/credentialEnvironmentNames.ts
15067
+ var credentialEnvironmentNames = [
15068
+ "DOCTRINE_RECIPIENT_SECRET",
15069
+ "DOCTRINE_ENCRYPTION_PASSWORD",
15070
+ "DOCTRINE_NEW_ENCRYPTION_PASSWORD",
15071
+ "DOCTRINE_TOKEN"
15072
+ ];
15073
+
15074
+ // src/credentials/readCredentialFromFd.ts
15075
+ import { createReadStream } from "fs";
15076
+ var maxCredentialBytes = 64 * 1024;
15077
+ var readCredentialFromFd = async (fd, label) => {
15078
+ if (!Number.isInteger(fd) || fd < 0 || fd === 1 || fd === 2) {
15079
+ throw new Error(
15080
+ `${label} file descriptor must be 0 or 3 and above (got ${fd}).`
15081
+ );
15082
+ }
15083
+ const chunks = [];
15084
+ let size = 0;
15085
+ try {
15086
+ for await (const chunk of createReadStream("", { autoClose: true, fd })) {
15087
+ const buffer = chunk;
15088
+ size += buffer.length;
15089
+ if (size > maxCredentialBytes) {
15090
+ throw new Error(`${label} on fd ${fd} is too large.`);
15091
+ }
15092
+ chunks.push(buffer);
15093
+ }
15094
+ } catch (error51) {
15095
+ if (error51 instanceof Error && error51.message.endsWith("is too large.")) {
15096
+ throw error51;
15097
+ }
15098
+ throw new Error(
15099
+ `Could not read ${label} from fd ${fd}. Open it in the shell, e.g. ${fd}<file.`
15100
+ );
15101
+ }
15102
+ const value = Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
15103
+ if (!value) {
15104
+ throw new Error(`${label} on fd ${fd} is empty.`);
15105
+ }
15106
+ return value;
15107
+ };
15108
+
15109
+ // src/selection/isEnvironmentName.ts
15110
+ var environmentNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
15111
+ var isEnvironmentName = (name) => environmentNamePattern.test(name);
15112
+
15113
+ // src/source/parseDotenvValue.ts
15114
+ var doubleQuoteEscapes = {
15115
+ '"': '"',
15116
+ "\\": "\\",
15117
+ n: "\n",
15118
+ r: "\r",
15119
+ t: " "
15120
+ };
15121
+ var isCommentOrEnd = (rest) => {
15122
+ const trimmed = rest.trim();
15123
+ return trimmed === "" || trimmed.startsWith("#");
15124
+ };
15125
+ var parseDoubleQuoted = (raw) => {
15126
+ let value = "";
15127
+ for (let index = 1; index < raw.length; index += 1) {
15128
+ const char = raw[index];
15129
+ if (char === "\\") {
15130
+ const escaped = doubleQuoteEscapes[raw[index + 1] ?? ""];
15131
+ if (escaped === void 0) {
15132
+ return null;
15133
+ }
15134
+ value += escaped;
15135
+ index += 1;
15136
+ continue;
15137
+ }
15138
+ if (char === '"') {
15139
+ return isCommentOrEnd(raw.slice(index + 1)) ? value : null;
15140
+ }
15141
+ value += char;
15142
+ }
15143
+ return null;
15144
+ };
15145
+ var parseSingleQuoted = (raw) => {
15146
+ const end = raw.indexOf("'", 1);
15147
+ if (end === -1 || !isCommentOrEnd(raw.slice(end + 1))) {
15148
+ return null;
15149
+ }
15150
+ return raw.slice(1, end);
15151
+ };
15152
+ var parseUnquoted = (raw) => {
15153
+ const comment = raw.search(/\s#/);
15154
+ return (comment === -1 ? raw : raw.slice(0, comment)).trim();
15155
+ };
15156
+ var parseDotenvValue = (rawValue) => {
15157
+ const raw = rawValue.trimStart();
15158
+ if (raw.startsWith('"')) {
15159
+ return parseDoubleQuoted(raw);
15160
+ }
15161
+ if (raw.startsWith("'")) {
15162
+ return parseSingleQuoted(raw);
15163
+ }
15164
+ return parseUnquoted(raw);
15165
+ };
15166
+
15167
+ // src/source/parseDotenvSecretSource.ts
15168
+ var assignmentPattern = /^(?:export\s+)?([^=\s]+)\s*=(.*)$/;
15169
+ var parseDotenvSecretSource = (plaintext) => {
15170
+ const values = {};
15171
+ const lines = plaintext.split("\n");
15172
+ lines.forEach((rawLine, index) => {
15173
+ const lineNumber = index + 1;
15174
+ const line = rawLine.replace(/\r$/, "").trim();
15175
+ if (line === "" || line.startsWith("#")) {
15176
+ return;
15177
+ }
15178
+ const match = assignmentPattern.exec(line);
15179
+ if (!match || !isEnvironmentName(match[1])) {
15180
+ throw new Error(
15181
+ `Invalid env source line ${lineNumber}: expected KEY=value (contents omitted).`
15182
+ );
15183
+ }
15184
+ const [, key, rawValue] = match;
15185
+ const value = parseDotenvValue(rawValue);
15186
+ if (value === null) {
15187
+ throw new Error(
15188
+ `Invalid value for ${key} on env source line ${lineNumber} (value omitted).`
15189
+ );
15190
+ }
15191
+ if (Object.hasOwn(values, key)) {
15192
+ throw new Error(
15193
+ `Ambiguous env source: ${key} is defined more than once (line ${lineNumber}).`
15194
+ );
15195
+ }
15196
+ values[key] = value;
15197
+ });
15198
+ return values;
15199
+ };
15200
+
15201
+ // src/source/parseJsonSecretSource.ts
15202
+ var parseJsonSecretSource = (plaintext) => {
15203
+ let decoded;
15204
+ try {
15205
+ decoded = JSON.parse(plaintext);
15206
+ } catch {
15207
+ throw new Error("Secret source is not valid JSON (contents omitted).");
15208
+ }
15209
+ if (!decoded || Array.isArray(decoded) || typeof decoded !== "object") {
15210
+ throw new Error("Secret source JSON must be an object of named values.");
15211
+ }
15212
+ return decoded;
15213
+ };
15214
+
15215
+ // src/source/parseSecretSource.ts
15216
+ var parseSecretSource = (plaintext, format) => {
15217
+ const resolved = format ?? (plaintext.trimStart().startsWith("{") ? "json" : "env");
15218
+ return resolved === "json" ? parseJsonSecretSource(plaintext) : parseDotenvSecretSource(plaintext);
15219
+ };
15220
+
15221
+ // src/selection/parseSecretSelection.ts
15222
+ var parseSecretSelection = (spec) => {
15223
+ const separator = spec.indexOf("=");
15224
+ const output = separator === -1 ? spec : spec.slice(0, separator);
15225
+ const source = separator === -1 ? spec : spec.slice(separator + 1);
15226
+ if (!isEnvironmentName(output)) {
15227
+ throw new Error(
15228
+ `Invalid variable name "${output}". Use letters, digits and underscores, not starting with a digit.`
15229
+ );
15230
+ }
15231
+ if (!source) {
15232
+ throw new Error(`Missing source key in "${spec}". Use OUTPUT=SOURCE_KEY.`);
15233
+ }
15234
+ return { output, source };
15235
+ };
15236
+
15237
+ // src/selection/isUsableSecretValue.ts
15238
+ var isUsableSecretValue = (value) => typeof value === "string" && value.trim() !== "" && !value.includes("\0");
15239
+
15240
+ // src/selection/selectSecretVariables.ts
15241
+ var selectAll = (values) => Object.keys(values).map((key) => {
15242
+ if (!isEnvironmentName(key)) {
15243
+ throw new Error(
15244
+ `Source key "${key}" is not a valid variable name; select it with OUTPUT=${key}.`
15245
+ );
15246
+ }
15247
+ return { output: key, source: key };
15248
+ });
15249
+ var assertUniqueOutputs = (selections) => {
15250
+ const seen = /* @__PURE__ */ new Set();
15251
+ for (const { output } of selections) {
15252
+ if (seen.has(output)) {
15253
+ throw new Error(`Variable ${output} is requested more than once.`);
15254
+ }
15255
+ seen.add(output);
15256
+ }
15257
+ };
15258
+ var selectSecretVariables = (values, selections) => {
15259
+ const resolved = selections === "all" ? selectAll(values) : selections;
15260
+ assertUniqueOutputs(resolved);
15261
+ const missing = resolved.filter(({ source }) => !Object.hasOwn(values, source)).map(({ source }) => source);
15262
+ if (missing.length) {
15263
+ throw new Error(
15264
+ `Missing secret${missing.length > 1 ? "s" : ""} in source: ${missing.join(", ")}.`
15265
+ );
15266
+ }
15267
+ return Object.fromEntries(
15268
+ resolved.map(({ output, source }) => {
15269
+ const value = values[source];
15270
+ if (!isUsableSecretValue(value)) {
15271
+ throw new Error(
15272
+ `Invalid value for ${source}: expected a non-empty string without NUL bytes (value omitted).`
15273
+ );
15274
+ }
15275
+ return [output, value];
15276
+ })
15277
+ );
15278
+ };
15279
+
15280
+ // src/run/minimalEnvironmentNames.ts
15281
+ var minimalEnvironmentNames = [
15282
+ "PATH",
15283
+ "HOME",
15284
+ "USER",
15285
+ "LOGNAME",
15286
+ "SHELL",
15287
+ "LANG",
15288
+ "LC_ALL",
15289
+ "TERM",
15290
+ "TZ",
15291
+ "TMPDIR",
15292
+ "TMP",
15293
+ "TEMP",
15294
+ "SystemRoot",
15295
+ "ComSpec",
15296
+ "PATHEXT",
15297
+ "WINDIR",
15298
+ "USERPROFILE",
15299
+ "APPDATA",
15300
+ "LOCALAPPDATA"
15301
+ ];
15302
+
15303
+ // src/run/buildChildEnvironment.ts
15304
+ var pickNames = (environment, names) => Object.fromEntries(
15305
+ names.filter((name) => environment[name] !== void 0).map((name) => [name, environment[name]])
15306
+ );
15307
+ var buildChildEnvironment = ({
15308
+ cleanEnv,
15309
+ credentialValues,
15310
+ parentEnvironment,
15311
+ secrets
15312
+ }) => {
15313
+ const reserved = Object.keys(secrets).filter(
15314
+ (name) => credentialEnvironmentNames.includes(name)
15315
+ );
15316
+ if (reserved.length) {
15317
+ throw new Error(
15318
+ `${reserved.join(", ")} is reserved for Forum credentials and cannot be passed to the command.`
15319
+ );
15320
+ }
15321
+ const base = cleanEnv ? pickNames(parentEnvironment, minimalEnvironmentNames) : { ...parentEnvironment };
15322
+ const credentials = new Set(credentialValues.filter(Boolean));
15323
+ const removed = [];
15324
+ const environment = {};
15325
+ for (const [name, value] of Object.entries(base)) {
15326
+ if (value === void 0) {
15327
+ continue;
15328
+ }
15329
+ if (credentialEnvironmentNames.includes(name) || credentials.has(value)) {
15330
+ removed.push(name);
15331
+ continue;
15332
+ }
15333
+ environment[name] = value;
15334
+ }
15335
+ return { environment: { ...environment, ...secrets }, removed };
15336
+ };
15337
+
15338
+ // src/run/createSecretRedactor.ts
15339
+ var redactedMarker = "[redacted]";
15340
+ var minimumRedactedLength = 4;
15341
+ var escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15342
+ var createSecretRedactor = (values) => {
15343
+ const redacted = [...new Set(values)].filter((value) => value.length >= minimumRedactedLength).sort((left, right) => right.length - left.length);
15344
+ const pattern = redacted.length ? new RegExp(redacted.map(escapeRegExp).join("|"), "g") : null;
15345
+ const holdBack = redacted.length ? redacted[0].length - 1 : 0;
15346
+ let pending = "";
15347
+ const replace = (text) => pattern ? text.replace(pattern, redactedMarker) : text;
15348
+ return {
15349
+ flush: () => {
15350
+ const text = replace(pending);
15351
+ pending = "";
15352
+ return text;
15353
+ },
15354
+ push: (chunk) => {
15355
+ const text = replace(pending + chunk);
15356
+ const emitLength = Math.max(0, text.length - holdBack);
15357
+ pending = text.slice(emitLength);
15358
+ return text.slice(0, emitLength);
15359
+ }
15360
+ };
15361
+ };
15362
+
15363
+ // src/run/forwardSignals.ts
15364
+ var forwardedSignals = process.platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"];
15365
+ var forwardSignals = (child, source = process) => {
15366
+ const listeners = forwardedSignals.map((signal) => {
15367
+ const listener = () => {
15368
+ if (child.exitCode === null && child.signalCode === null) {
15369
+ child.kill(signal);
15370
+ }
15371
+ };
15372
+ source.on(signal, listener);
15373
+ return { listener, signal };
15374
+ });
15375
+ return () => {
15376
+ for (const { listener, signal } of listeners) {
15377
+ source.off(signal, listener);
15378
+ }
15379
+ };
15380
+ };
15381
+
15382
+ // src/run/runCommandWithSecrets.ts
15383
+ import { spawn } from "child_process";
15384
+
15385
+ // src/run/exitCodeForSignal.ts
15386
+ import { constants } from "os";
15387
+ var exitCodeForSignal = (signal) => 128 + (constants.signals[signal] ?? 0);
15388
+
15389
+ // src/run/pipeRedacted.ts
15390
+ import { StringDecoder } from "string_decoder";
15391
+ var idleFlushMs = 50;
15392
+ var pipeRedacted = (source, target, values) => new Promise((resolve) => {
15393
+ const decoder = new StringDecoder("utf8");
15394
+ const redactor = createSecretRedactor(values);
15395
+ let idleTimer = null;
15396
+ const write = (text) => {
15397
+ if (text) {
15398
+ target.write(text);
15399
+ }
15400
+ };
15401
+ const clearIdle = () => {
15402
+ if (idleTimer) {
15403
+ clearTimeout(idleTimer);
15404
+ idleTimer = null;
15405
+ }
15406
+ };
15407
+ source.on("data", (chunk) => {
15408
+ clearIdle();
15409
+ write(redactor.push(decoder.write(chunk)));
15410
+ idleTimer = setTimeout(() => write(redactor.flush()), idleFlushMs);
15411
+ });
15412
+ source.on("close", () => {
15413
+ clearIdle();
15414
+ write(redactor.push(decoder.end()));
15415
+ write(redactor.flush());
15416
+ resolve();
15417
+ });
15418
+ });
15419
+
15420
+ // src/run/runCommandWithSecrets.ts
15421
+ var launchFailureFor = (error51) => error51.code === "ENOENT" ? "not_found" : error51.code === "EACCES" ? "not_executable" : "spawn_failed";
15422
+ var exitCodeForLaunchFailure = {
15423
+ not_executable: 126,
15424
+ not_found: 127,
15425
+ spawn_failed: 1
15426
+ };
15427
+ var outputStdio = (output) => output === "inherit" ? "inherit" : output === "withhold" ? "ignore" : "pipe";
15428
+ var runCommandWithSecrets = ({
15429
+ command,
15430
+ cwd,
15431
+ environment,
15432
+ output,
15433
+ redactValues,
15434
+ signalSource,
15435
+ stderr = process.stderr,
15436
+ stdin,
15437
+ stdout = process.stdout
15438
+ }) => {
15439
+ const [file2, ...args] = command;
15440
+ if (!file2) {
15441
+ throw new Error("Supply a command to run after --.");
15442
+ }
15443
+ const stdio = [stdin, outputStdio(output), outputStdio(output)];
15444
+ return new Promise((resolve) => {
15445
+ const child = spawn(file2, args, {
15446
+ cwd,
15447
+ env: environment,
15448
+ shell: false,
15449
+ stdio,
15450
+ windowsHide: true
15451
+ });
15452
+ const stopForwarding = forwardSignals(child, signalSource);
15453
+ const pipes = output === "redact" && child.stdout && child.stderr ? [
15454
+ pipeRedacted(child.stdout, stdout, redactValues),
15455
+ pipeRedacted(child.stderr, stderr, redactValues)
15456
+ ] : [];
15457
+ let settled = false;
15458
+ const settle = async (result) => {
15459
+ if (settled) {
15460
+ return;
15461
+ }
15462
+ settled = true;
15463
+ stopForwarding();
15464
+ await Promise.all(pipes);
15465
+ resolve(result);
15466
+ };
15467
+ child.on("error", (error51) => {
15468
+ if (child.pid !== void 0) {
15469
+ return;
15470
+ }
15471
+ const launchFailure = launchFailureFor(error51);
15472
+ void settle({
15473
+ exitCode: exitCodeForLaunchFailure[launchFailure],
15474
+ launchFailure,
15475
+ signal: null
15476
+ });
15477
+ });
15478
+ child.once("close", (code, signal) => {
15479
+ void settle({
15480
+ exitCode: signal ? exitCodeForSignal(signal) : code ?? 1,
15481
+ launchFailure: null,
15482
+ signal
15483
+ });
15484
+ });
15485
+ });
15486
+ };
15487
+
15488
+ // src/run/SecretOutputMode.ts
15489
+ var secretOutputModes = [
15490
+ "redact",
15491
+ "inherit",
15492
+ "withhold"
15493
+ ];
14806
15494
  export {
15495
+ EncryptedEnvelopeMismatchError,
15496
+ buildChildEnvironment,
15497
+ createSecretRedactor,
15498
+ credentialEnvironmentNames,
14807
15499
  currentEncryptedFileVersion,
14808
15500
  decryptForumEncryptedFile,
14809
15501
  decryptForumEncryptedFileText,
14810
15502
  encryptedFileCipher,
14811
15503
  forumRecipientSecretPrefix,
15504
+ forwardSignals,
14812
15505
  legacyEncryptedFileVersion,
15506
+ minimumRedactedLength,
15507
+ parseDotenvSecretSource,
15508
+ parseEncryptedEnvelopeExpectation,
14813
15509
  parseForumEncryptedFilePayload,
14814
- readRecipientSecret
15510
+ parseJsonSecretSource,
15511
+ parseSecretSelection,
15512
+ parseSecretSource,
15513
+ readCredentialFromFd,
15514
+ readRecipientSecret,
15515
+ redactedMarker,
15516
+ runCommandWithSecrets,
15517
+ secretOutputModes,
15518
+ selectSecretVariables
14815
15519
  };
14816
15520
  //# sourceMappingURL=index.js.map