@mp-lb/forum-secrets 0.2.3 → 0.2.5

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/README.md CHANGED
@@ -1,28 +1,101 @@
1
1
  # Doctrine Secrets
2
2
 
3
- Decrypt Doctrine encrypted text files from CI or other Node.js runtimes.
3
+ Decrypt Doctrine encrypted text files from CI or other Node.js runtimes, and
4
+ run commands with selected decrypted values.
4
5
 
5
6
  ## CLI
6
7
 
7
- Store the external recipient secret in your CI secret manager:
8
+ Store the external recipient secret in your CI secret manager and expose it to
9
+ the step as `DOCTRINE_RECIPIENT_SECRET`, for example in GitHub Actions:
8
10
 
9
- ```sh
10
- doctrine-secrets decrypt secrets.enc.json > secrets.json
11
+ ```yaml
12
+ - run: npx @mp-lb/forum-secrets decrypt secrets.enc.json > secrets.json
13
+ env:
14
+ DOCTRINE_RECIPIENT_SECRET: ${{ secrets.DOCTRINE_RECIPIENT_SECRET }}
11
15
  ```
12
16
 
13
- The CLI reads the recipient secret from `DOCTRINE_RECIPIENT_SECRET` by default.
17
+ Do not write the secret on the command line (`--secret <value>` or
18
+ `DOCTRINE_RECIPIENT_SECRET='…' doctrine-secrets …`): it ends up in shell history
19
+ and process listings.
20
+
21
+ `decrypt` is an explicit export: it prints plaintext. To use secrets as
22
+ environment variables without writing plaintext, prefer `fm decrypt-run` from
23
+ `@mp-lb/forum-cli`, or the library runner below.
24
+
25
+ ## Pinning the encrypted object
26
+
27
+ Current Forum encrypted files carry an authenticated object id and revision.
28
+ A decryption succeeding proves the file was written by someone holding the
29
+ file key (any recipient, including other CI secrets), not that it is the
30
+ file or the version you meant. Pin both in CI to refuse another encrypted file
31
+ copied over this one, or an old version replayed in its place:
14
32
 
15
33
  ```sh
16
- DOCTRINE_RECIPIENT_SECRET='doctrine-recipient-v1_...' doctrine-secrets decrypt secrets.enc.json
34
+ doctrine-secrets decrypt secrets.enc.json \
35
+ --expect-object 0b8f7a2e-4c55-4a8e-9a8e-6c1e2f3a4b5c \
36
+ --min-revision 12
17
37
  ```
18
38
 
39
+ The object id and revision are the `objectId` and `revision` fields of the
40
+ encrypted file. Any pin rejects older files without an authenticated identity;
41
+ re-save them from Forum first. Raise `--min-revision` when you rotate secrets.
42
+
19
43
  ## Library
20
44
 
21
45
  ```ts
22
- import { decryptDoctrineEncryptedFileText } from "@mp-lb/forum-secrets";
46
+ import { decryptForumEncryptedFileText } from "@mp-lb/forum-secrets";
23
47
 
24
- const plaintext = await decryptDoctrineEncryptedFileText({
48
+ const plaintext = await decryptForumEncryptedFileText({
25
49
  encryptedText,
50
+ expectation: { objectId, minRevision }, // optional
26
51
  recipientSecret: process.env.DOCTRINE_RECIPIENT_SECRET!,
27
52
  });
28
53
  ```
54
+
55
+ ### Running a command with selected secrets
56
+
57
+ ```ts
58
+ import {
59
+ buildChildEnvironment,
60
+ parseSecretSelection,
61
+ parseSecretSource,
62
+ runCommandWithSecrets,
63
+ selectSecretVariables,
64
+ } from "@mp-lb/forum-secrets";
65
+
66
+ const secrets = selectSecretVariables(parseSecretSource(plaintext), [
67
+ parseSecretSelection("API_KEY"),
68
+ parseSecretSelection("DATABASE_URL=DB_URL"),
69
+ ]);
70
+
71
+ const { environment } = buildChildEnvironment({
72
+ cleanEnv: false,
73
+ credentialValues: [recipientSecret],
74
+ parentEnvironment: process.env,
75
+ secrets,
76
+ });
77
+
78
+ const { exitCode } = await runCommandWithSecrets({
79
+ command: ["npm", "start"],
80
+ environment,
81
+ output: "redact",
82
+ redactValues: Object.values(secrets),
83
+ stdin: "inherit",
84
+ });
85
+ ```
86
+
87
+ - `parseSecretSource` reads a JSON object or dotenv text. Dotenv sources with a
88
+ repeated key or a malformed line are rejected.
89
+ - `selectSecretVariables` follows ArcNet's `selectSecrets` rules: each
90
+ requested value must exist and be a non-blank string without NUL bytes.
91
+ Errors name keys, never values.
92
+ - `buildChildEnvironment` removes Forum credentials
93
+ (`credentialEnvironmentNames`), and any variable holding one of
94
+ `credentialValues`, before adding the selected secrets.
95
+ - `runCommandWithSecrets` spawns an argv array (no shell), forwards termination
96
+ signals and returns the child's status (128 + n when killed by signal n,
97
+ 127/126 when it cannot start). `output` is `redact` (best-effort exact-match
98
+ redaction), `inherit` (raw passthrough) or `withhold`. A child can always
99
+ disclose the values it receives.
100
+ - `readCredentialFromFd` reads a recipient secret or password from an open
101
+ file descriptor, so it never appears in argv.
package/dist/cli.js CHANGED
@@ -1258,8 +1258,8 @@ function cleanEnum(obj) {
1258
1258
  return Number.isNaN(Number.parseInt(k, 10));
1259
1259
  }).map((el) => el[1]);
1260
1260
  }
1261
- function base64ToUint8Array(base643) {
1262
- const binaryString = atob(base643);
1261
+ function base64ToUint8Array(base644) {
1262
+ const binaryString = atob(base644);
1263
1263
  const bytes = new Uint8Array(binaryString.length);
1264
1264
  for (let i = 0; i < binaryString.length; i++) {
1265
1265
  bytes[i] = binaryString.charCodeAt(i);
@@ -1274,9 +1274,9 @@ function uint8ArrayToBase64(bytes) {
1274
1274
  return btoa(binaryString);
1275
1275
  }
1276
1276
  function base64urlToUint8Array(base64url3) {
1277
- const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1278
- const padding = "=".repeat((4 - base643.length % 4) % 4);
1279
- return base64ToUint8Array(base643 + padding);
1277
+ const base644 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
1278
+ const padding = "=".repeat((4 - base644.length % 4) % 4);
1279
+ return base64ToUint8Array(base644 + padding);
1280
1280
  }
1281
1281
  function uint8ArrayToBase64url(bytes) {
1282
1282
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
@@ -2642,8 +2642,8 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
2642
2642
  function isValidBase64URL(data) {
2643
2643
  if (!base64url.test(data))
2644
2644
  return false;
2645
- const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
2646
- const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
2645
+ const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
2646
+ const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "=");
2647
2647
  return isValidBase64(padded);
2648
2648
  }
2649
2649
  var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
@@ -14520,8 +14520,8 @@ function date4(params) {
14520
14520
  config(en_default());
14521
14521
 
14522
14522
  // ../encryption/src/bytes/base64ToBytes.ts
14523
- var base64ToBytes = (base643) => {
14524
- const binary = atob(base643);
14523
+ var base64ToBytes = (base644) => {
14524
+ const binary = atob(base644);
14525
14525
  const bytes = new Uint8Array(binary.length);
14526
14526
  for (let index = 0; index < binary.length; index += 1) {
14527
14527
  bytes[index] = binary.charCodeAt(index);
@@ -14535,15 +14535,264 @@ var toBufferSource = (bytes) => bytes.buffer.slice(
14535
14535
  bytes.byteOffset + bytes.byteLength
14536
14536
  );
14537
14537
 
14538
- // ../encryption/src/keyBinding/createUserEncryptionKeyBinding.ts
14538
+ // ../encryption/src/cipherNames.ts
14539
+ var encryptedFileCipher = "AES-GCM";
14540
+ var publicKeyCipher = "RSA-OAEP-SHA-256";
14541
+
14542
+ // ../encryption/src/envelope/EncryptedEnvelopeMismatchError.ts
14543
+ var messages = {
14544
+ different_object: "This encrypted content belongs to a different encrypted file than expected.",
14545
+ stale: "This encrypted content is an older revision than expected; it may have been replayed or restored.",
14546
+ unbound: "This encrypted content uses an older format without an authenticated identity, but an identity was expected."
14547
+ };
14548
+ var EncryptedEnvelopeMismatchError = class extends Error {
14549
+ continuity;
14550
+ constructor(continuity) {
14551
+ super(messages[continuity] ?? "Unexpected encrypted content.");
14552
+ this.name = "EncryptedEnvelopeMismatchError";
14553
+ this.continuity = continuity;
14554
+ }
14555
+ };
14556
+
14557
+ // ../encryption/src/envelope/readEncryptedEnvelopeIdentity.ts
14558
+ var readEncryptedEnvelopeIdentity = (envelope) => envelope.doctrineEncryptedFile === 4 ? { objectId: envelope.objectId, revision: envelope.revision } : null;
14559
+
14560
+ // ../encryption/src/envelope/assertEncryptedEnvelopeExpectation.ts
14561
+ var assertEncryptedEnvelopeExpectation = (envelope, { minRevision, objectId }) => {
14562
+ if (objectId === void 0 && minRevision === void 0) {
14563
+ return;
14564
+ }
14565
+ const identity = readEncryptedEnvelopeIdentity(envelope);
14566
+ if (!identity) {
14567
+ throw new EncryptedEnvelopeMismatchError("unbound");
14568
+ }
14569
+ if (objectId !== void 0 && identity.objectId !== objectId) {
14570
+ throw new EncryptedEnvelopeMismatchError("different_object");
14571
+ }
14572
+ if (minRevision !== void 0 && identity.revision < minRevision) {
14573
+ throw new EncryptedEnvelopeMismatchError("stale");
14574
+ }
14575
+ };
14576
+
14577
+ // ../encryption/src/envelope/encryptedEnvelopeLimits.ts
14578
+ var encryptedEnvelopeLimits = {
14579
+ maxEnvelopeChars: 16 * 1024 * 1024,
14580
+ maxLabelChars: 512,
14581
+ maxRecipientIdChars: 256,
14582
+ maxRecipients: 256,
14583
+ maxRevision: Number.MAX_SAFE_INTEGER,
14584
+ maxWrappedKeyChars: 2048
14585
+ };
14586
+
14587
+ // ../encryption/src/envelope/createEncryptedEnvelopeBinding.ts
14588
+ var encryptedEnvelopeBindingPurpose = "forum-encrypted-file-envelope";
14539
14589
  var textEncoder = new TextEncoder();
14590
+ var createEncryptedEnvelopeBinding = (header) => textEncoder.encode(
14591
+ JSON.stringify([
14592
+ encryptedEnvelopeBindingPurpose,
14593
+ header.doctrineEncryptedFile,
14594
+ header.cipher,
14595
+ header.objectId,
14596
+ header.revision,
14597
+ header.workspaceAccess,
14598
+ header.recipients.map((recipient) => [
14599
+ recipient.recipientId,
14600
+ recipient.label ?? null,
14601
+ recipient.wrappedDataKey.cipher,
14602
+ recipient.wrappedDataKey.data,
14603
+ recipient.wrappedDataKey.cipher === encryptedFileCipher ? recipient.wrappedDataKey.iv : null
14604
+ ])
14605
+ ])
14606
+ );
14607
+
14608
+ // ../encryption/src/envelope/EncryptedEnvelopeFormatError.ts
14609
+ var EncryptedEnvelopeFormatError = class extends Error {
14610
+ constructor(detail) {
14611
+ super(
14612
+ detail ? `Unsupported encrypted file format: ${detail}` : "Unsupported encrypted file format."
14613
+ );
14614
+ this.name = "EncryptedEnvelopeFormatError";
14615
+ }
14616
+ };
14617
+
14618
+ // ../encryption/src/envelope/encryptedEnvelopeVersions.ts
14619
+ var legacyEncryptedEnvelopeVersion = 2;
14620
+ var unboundEncryptedEnvelopeVersion = 3;
14621
+ var boundEncryptedEnvelopeVersion = 4;
14622
+
14623
+ // ../encryption/src/envelope/encryptedEnvelopeSchemas.ts
14624
+ var base64Pattern = /^[A-Za-z0-9+/]+={0,2}$/;
14625
+ var base643 = (maxChars) => external_exports.string().min(1).max(maxChars).regex(base64Pattern, "Expected base64.");
14626
+ var ivSchema = external_exports.string().length(16).regex(base64Pattern, "Expected base64.");
14627
+ var untrimmedText = (maxChars) => external_exports.string().min(1).max(maxChars).refine((value) => value.trim() === value, "Unexpected whitespace.");
14628
+ var boundAesWrappedKeySchema = external_exports.strictObject({
14629
+ cipher: external_exports.literal(encryptedFileCipher),
14630
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars),
14631
+ iv: ivSchema
14632
+ });
14633
+ var boundPublicKeyWrappedKeySchema = external_exports.strictObject({
14634
+ cipher: external_exports.literal(publicKeyCipher),
14635
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars)
14636
+ });
14637
+ var boundRecipientSchema = external_exports.strictObject({
14638
+ label: untrimmedText(encryptedEnvelopeLimits.maxLabelChars).optional(),
14639
+ recipientId: untrimmedText(encryptedEnvelopeLimits.maxRecipientIdChars),
14640
+ wrappedDataKey: external_exports.discriminatedUnion("cipher", [
14641
+ boundAesWrappedKeySchema,
14642
+ boundPublicKeyWrappedKeySchema
14643
+ ])
14644
+ });
14645
+ var hasUniqueRecipientIds = (recipients) => new Set(recipients.map((recipient) => recipient.recipientId)).size === recipients.length;
14646
+ var boundHeaderShape = {
14647
+ doctrineEncryptedFile: external_exports.literal(boundEncryptedEnvelopeVersion),
14648
+ cipher: external_exports.literal(encryptedFileCipher),
14649
+ objectId: external_exports.uuid(),
14650
+ revision: external_exports.number().int().min(0).max(encryptedEnvelopeLimits.maxRevision),
14651
+ workspaceAccess: external_exports.enum(["personal", "team"]),
14652
+ recipients: external_exports.array(boundRecipientSchema).min(1).max(encryptedEnvelopeLimits.maxRecipients).refine(hasUniqueRecipientIds, "Duplicate recipient id.")
14653
+ };
14654
+ var boundEncryptedEnvelopeHeaderSchema = external_exports.strictObject(boundHeaderShape);
14655
+ var boundEncryptedEnvelopeSchema = external_exports.strictObject({
14656
+ ...boundHeaderShape,
14657
+ data: base643(encryptedEnvelopeLimits.maxEnvelopeChars),
14658
+ iv: ivSchema
14659
+ });
14660
+ var unboundWrappedKeySchema = external_exports.discriminatedUnion("cipher", [
14661
+ external_exports.object({
14662
+ cipher: external_exports.literal(encryptedFileCipher),
14663
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars),
14664
+ iv: ivSchema
14665
+ }),
14666
+ external_exports.object({
14667
+ cipher: external_exports.literal(publicKeyCipher),
14668
+ data: base643(encryptedEnvelopeLimits.maxWrappedKeyChars)
14669
+ })
14670
+ ]);
14671
+ var unboundRecipientsSchema = external_exports.array(
14672
+ external_exports.object({
14673
+ label: external_exports.string().trim().min(1).max(encryptedEnvelopeLimits.maxLabelChars).optional(),
14674
+ recipientId: external_exports.string().trim().min(1).max(encryptedEnvelopeLimits.maxRecipientIdChars),
14675
+ wrappedDataKey: unboundWrappedKeySchema
14676
+ })
14677
+ ).min(1).max(encryptedEnvelopeLimits.maxRecipients);
14678
+ var unboundBodyShape = {
14679
+ cipher: external_exports.literal(encryptedFileCipher),
14680
+ data: base643(encryptedEnvelopeLimits.maxEnvelopeChars),
14681
+ iv: ivSchema,
14682
+ recipients: unboundRecipientsSchema
14683
+ };
14684
+ var legacyEncryptedEnvelopeSchema = external_exports.object({
14685
+ ...unboundBodyShape,
14686
+ doctrineEncryptedFile: external_exports.literal(legacyEncryptedEnvelopeVersion)
14687
+ });
14688
+ var unboundEncryptedEnvelopeSchema = external_exports.object({
14689
+ ...unboundBodyShape,
14690
+ doctrineEncryptedFile: external_exports.literal(unboundEncryptedEnvelopeVersion),
14691
+ workspaceAccess: external_exports.enum(["personal", "team"]).default("personal")
14692
+ });
14693
+
14694
+ // ../encryption/src/envelope/parseEncryptedEnvelope.ts
14695
+ var schemaByVersion = /* @__PURE__ */ new Map([
14696
+ [2, legacyEncryptedEnvelopeSchema],
14697
+ [3, unboundEncryptedEnvelopeSchema],
14698
+ [4, boundEncryptedEnvelopeSchema]
14699
+ ]);
14700
+ var readVersion = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value.doctrineEncryptedFile : void 0;
14701
+ var parseEncryptedEnvelope = (encryptedText) => {
14702
+ if (typeof encryptedText !== "string") {
14703
+ throw new EncryptedEnvelopeFormatError("expected text.");
14704
+ }
14705
+ if (encryptedText.length > encryptedEnvelopeLimits.maxEnvelopeChars) {
14706
+ throw new EncryptedEnvelopeFormatError("the file is too large.");
14707
+ }
14708
+ let parsed;
14709
+ try {
14710
+ parsed = JSON.parse(encryptedText);
14711
+ } catch {
14712
+ throw new EncryptedEnvelopeFormatError("not valid JSON.");
14713
+ }
14714
+ const schema = schemaByVersion.get(readVersion(parsed));
14715
+ if (!schema) {
14716
+ throw new EncryptedEnvelopeFormatError("unknown envelope version.");
14717
+ }
14718
+ const result = schema.safeParse(parsed);
14719
+ if (!result.success) {
14720
+ const issue2 = result.error.issues[0];
14721
+ const path = issue2?.path?.join(".") || "envelope";
14722
+ throw new EncryptedEnvelopeFormatError(`invalid ${path}.`);
14723
+ }
14724
+ return result.data;
14725
+ };
14726
+
14727
+ // ../encryption/src/keyBinding/createUserEncryptionKeyBinding.ts
14728
+ var textEncoder2 = new TextEncoder();
14729
+
14730
+ // ../encryption/src/kdf/userEncryptionKdfNames.ts
14731
+ var pbkdf2Sha256KdfName = "PBKDF2-SHA-256";
14732
+ var argon2idKdfName = "Argon2id";
14733
+ var argon2Version = 19;
14734
+
14735
+ // ../encryption/src/kdf/userEncryptionKdfLimits.ts
14736
+ var userEncryptionKdfLimits = {
14737
+ argon2id: {
14738
+ maxCost: 1048576,
14739
+ maxIterations: 10,
14740
+ maxMemoryKiB: 262144,
14741
+ maxParallelism: 4,
14742
+ minIterations: 1,
14743
+ minMemoryKiB: 19456,
14744
+ minParallelism: 1
14745
+ },
14746
+ pbkdf2: {
14747
+ maxIterations: 2e6,
14748
+ minIterations: 1e5
14749
+ },
14750
+ salt: {
14751
+ maxBytes: 64,
14752
+ minBytes: 16
14753
+ }
14754
+ };
14755
+
14756
+ // ../encryption/src/kdf/userEncryptionKdfSchema.ts
14757
+ var { argon2id, pbkdf2, salt } = userEncryptionKdfLimits;
14758
+ var decodedBase64Length = (value) => {
14759
+ try {
14760
+ return atob(value).length;
14761
+ } catch {
14762
+ return null;
14763
+ }
14764
+ };
14765
+ var userEncryptionKdfSaltSchema = external_exports.string().regex(/^[A-Za-z0-9+/]+={0,2}$/, "Expected a base64 KDF salt.").refine((value) => {
14766
+ const length = decodedBase64Length(value);
14767
+ return length !== null && length >= salt.minBytes && length <= salt.maxBytes;
14768
+ }, `KDF salt must be ${salt.minBytes}-${salt.maxBytes} bytes.`);
14769
+ var pbkdf2UserEncryptionKdfSchema = external_exports.object({
14770
+ iterations: external_exports.number().int().min(pbkdf2.minIterations).max(pbkdf2.maxIterations),
14771
+ name: external_exports.literal(pbkdf2Sha256KdfName),
14772
+ salt: userEncryptionKdfSaltSchema
14773
+ }).strict();
14774
+ var argon2idUserEncryptionKdfSchema = external_exports.object({
14775
+ iterations: external_exports.number().int().min(argon2id.minIterations).max(argon2id.maxIterations),
14776
+ memoryKiB: external_exports.number().int().min(argon2id.minMemoryKiB).max(argon2id.maxMemoryKiB),
14777
+ name: external_exports.literal(argon2idKdfName),
14778
+ parallelism: external_exports.number().int().min(argon2id.minParallelism).max(argon2id.maxParallelism),
14779
+ salt: userEncryptionKdfSaltSchema,
14780
+ version: external_exports.literal(argon2Version)
14781
+ }).strict().refine(
14782
+ (kdf) => kdf.memoryKiB * kdf.iterations <= argon2id.maxCost,
14783
+ "Argon2id memory x iterations exceeds the supported cost."
14784
+ );
14785
+ var userEncryptionKdfSchema = external_exports.union([
14786
+ pbkdf2UserEncryptionKdfSchema,
14787
+ argon2idUserEncryptionKdfSchema
14788
+ ]);
14789
+
14790
+ // ../encryption/src/kdf/deriveUserEncryptionPasswordKey.ts
14791
+ var textEncoder3 = new TextEncoder();
14540
14792
 
14541
14793
  // ../encryption/src/fileEncryption.ts
14542
14794
  var legacyEncryptedFileVersion = 2;
14543
14795
  var currentEncryptedFileVersion = 3;
14544
- var encryptedFileKdf = "PBKDF2-SHA-256";
14545
- var encryptedFileCipher = "AES-GCM";
14546
- var publicKeyCipher = "RSA-OAEP-SHA-256";
14547
14796
  var externalRecipientSecretPrefix = "doctrine-recipient-v1_";
14548
14797
  var forumRecipientSecretPrefix = externalRecipientSecretPrefix;
14549
14798
  var storeEncryptedValueSchema = external_exports.object({
@@ -14596,19 +14845,10 @@ var publicKeyValueSchema = external_exports.object({
14596
14845
  var legacyUserEncryptionMetadataSchema = external_exports.object({
14597
14846
  version: external_exports.literal(1),
14598
14847
  keyId: external_exports.string().trim().min(1),
14599
- kdf: external_exports.object({
14600
- name: external_exports.literal(encryptedFileKdf),
14601
- iterations: external_exports.number().int().positive(),
14602
- salt: external_exports.string().trim().min(1)
14603
- }),
14848
+ kdf: pbkdf2UserEncryptionKdfSchema,
14604
14849
  wrappedUserKey: encryptedValueSchema,
14605
14850
  verification: encryptedValueSchema
14606
14851
  });
14607
- var userEncryptionKdfSchema = external_exports.object({
14608
- name: external_exports.literal(encryptedFileKdf),
14609
- iterations: external_exports.number().int().positive(),
14610
- salt: external_exports.string().trim().min(1)
14611
- });
14612
14852
  var encryptionFingerprintSchema = external_exports.string().regex(/^[0-9a-f]{64}$/, "Expected a lowercase hex SHA-256 fingerprint.");
14613
14853
  var unboundUserEncryptionMetadataSchema = external_exports.object({
14614
14854
  version: external_exports.literal(2),
@@ -14645,7 +14885,7 @@ var userEncryptionMetadataSchema = external_exports.union([
14645
14885
  unboundUserEncryptionMetadataSchema,
14646
14886
  boundUserEncryptionMetadataSchema
14647
14887
  ]);
14648
- var textEncoder2 = new TextEncoder();
14888
+ var textEncoder4 = new TextEncoder();
14649
14889
  var textDecoder = new TextDecoder();
14650
14890
  var rsaKeyGenerationAlgorithm = {
14651
14891
  hash: "SHA-256",
@@ -14677,6 +14917,30 @@ var decryptBytes = async ({
14677
14917
  toBufferSource(base64ToBytes(data))
14678
14918
  )
14679
14919
  );
14920
+ var envelopeAdditionalData = (envelope) => envelope.doctrineEncryptedFile === boundEncryptedEnvelopeVersion ? createEncryptedEnvelopeBinding(envelope) : void 0;
14921
+ var decryptEnvelopeBytes = async ({
14922
+ envelope,
14923
+ expectation,
14924
+ fileKey
14925
+ }) => {
14926
+ let bytes;
14927
+ try {
14928
+ bytes = await decryptBytes({
14929
+ additionalData: envelopeAdditionalData(envelope),
14930
+ data: envelope.data,
14931
+ iv: envelope.iv,
14932
+ key: fileKey
14933
+ });
14934
+ } catch {
14935
+ throw new Error(
14936
+ "Could not decrypt the encrypted file: the key is wrong, or the encrypted file or its protected metadata was modified."
14937
+ );
14938
+ }
14939
+ if (expectation) {
14940
+ assertEncryptedEnvelopeExpectation(envelope, expectation);
14941
+ }
14942
+ return bytes;
14943
+ };
14680
14944
  var importForumRecipientSecretKey = async (secret) => {
14681
14945
  if (!secret.startsWith(forumRecipientSecretPrefix)) {
14682
14946
  throw new Error("Unsupported Forum recipient secret.");
@@ -14705,17 +14969,10 @@ var unwrapFileKeyBytesForRecipientSecret = async ({
14705
14969
  }
14706
14970
  throw new Error("No recipient matched the Forum recipient secret.");
14707
14971
  };
14708
- var parseForumEncryptedFilePayload = (encryptedText) => {
14709
- const parsed = JSON.parse(
14710
- encryptedText
14711
- );
14712
- if (parsed.doctrineEncryptedFile !== legacyEncryptedFileVersion && parsed.doctrineEncryptedFile !== currentEncryptedFileVersion || parsed.cipher !== encryptedFileCipher || typeof parsed.data !== "string" || typeof parsed.iv !== "string" || !Array.isArray(parsed.recipients)) {
14713
- throw new Error("Unsupported Forum encrypted file format.");
14714
- }
14715
- return parsed;
14716
- };
14972
+ var parseForumEncryptedFilePayload = (encryptedText) => parseEncryptedEnvelope(encryptedText);
14717
14973
  var decryptForumEncryptedFile = async ({
14718
14974
  encryptedText,
14975
+ expectation,
14719
14976
  recipientSecret
14720
14977
  }) => {
14721
14978
  const payload = parseForumEncryptedFilePayload(encryptedText);
@@ -14725,20 +14982,102 @@ var decryptForumEncryptedFile = async ({
14725
14982
  recipients: payload.recipients
14726
14983
  });
14727
14984
  const fileKey = await importAesKey(fileKeyBytes, false);
14728
- return decryptBytes({
14729
- data: payload.data,
14730
- iv: payload.iv,
14731
- key: fileKey
14732
- });
14985
+ return decryptEnvelopeBytes({ envelope: payload, expectation, fileKey });
14733
14986
  };
14734
14987
  var decryptForumEncryptedFileText = async (input) => textDecoder.decode(await decryptForumEncryptedFile(input));
14735
14988
 
14989
+ // ../encryption/src/envelope/parseEncryptedEnvelopeExpectation.ts
14990
+ var objectIdSchema = external_exports.uuid();
14991
+ var revisionPattern = /^\d{1,16}$/;
14992
+ var parseEncryptedEnvelopeExpectation = ({
14993
+ minRevision,
14994
+ objectId
14995
+ }) => {
14996
+ const expectation = {};
14997
+ if (objectId != null) {
14998
+ if (!objectIdSchema.safeParse(objectId).success) {
14999
+ throw new Error("--expect-object must be an encrypted object id (UUID).");
15000
+ }
15001
+ expectation.objectId = objectId.toLowerCase();
15002
+ }
15003
+ if (minRevision != null) {
15004
+ const revision = Number(minRevision);
15005
+ if (!revisionPattern.test(minRevision) || revision > encryptedEnvelopeLimits.maxRevision) {
15006
+ throw new Error("--min-revision must be a non-negative integer.");
15007
+ }
15008
+ expectation.minRevision = revision;
15009
+ }
15010
+ return expectation;
15011
+ };
15012
+
15013
+ // ../encryption/src/password/encryptionPassphraseRules.ts
15014
+ var encryptionPassphraseRules = {
15015
+ maxCharacters: 1024,
15016
+ minCharacters: 12,
15017
+ minDistinctCharacters: 5
15018
+ };
15019
+ var encryptionPassphraseGuidance = `Use at least ${encryptionPassphraseRules.minCharacters} characters. A memorable passphrase of several words is better than a short PIN.`;
15020
+
15021
+ // ../encryption/src/backup/encryptionBackupFormat.ts
15022
+ var encryptionBackupFormat = {
15023
+ name: "forum-encryption-backup",
15024
+ version: 1
15025
+ };
15026
+
15027
+ // ../encryption/src/backup/encryptionBackupSchema.ts
15028
+ var sha256HexSchema = external_exports.string().regex(/^[0-9a-f]{64}$/);
15029
+ var encryptionBackupFileSchema = external_exports.strictObject({
15030
+ path: external_exports.string(),
15031
+ // The file's encrypted envelope exactly as Forum stores it.
15032
+ encryptedText: external_exports.string().min(1),
15033
+ sha256: sha256HexSchema
15034
+ });
15035
+ var encryptionBackupSchema = external_exports.strictObject({
15036
+ format: external_exports.literal(encryptionBackupFormat.name),
15037
+ version: external_exports.literal(encryptionBackupFormat.version),
15038
+ createdAt: external_exports.iso.datetime(),
15039
+ identity: currentUserEncryptionMetadataSchema,
15040
+ fingerprint: sha256HexSchema,
15041
+ files: external_exports.array(encryptionBackupFileSchema),
15042
+ digest: sha256HexSchema
15043
+ });
15044
+
15045
+ // ../encryption/src/machineKeys/machineKeyAlgorithms.ts
15046
+ var machineRsaAlgorithm = {
15047
+ hash: "SHA-256",
15048
+ name: "RSA-OAEP"
15049
+ };
15050
+ var machineRsaKeyGenerationAlgorithm = {
15051
+ ...machineRsaAlgorithm,
15052
+ modulusLength: 2048,
15053
+ publicExponent: Uint8Array.from([1, 0, 1])
15054
+ };
15055
+
14736
15056
  // src/parseCliArgs.ts
15057
+ var valueFlags = {
15058
+ "--expect-object": "expectObjectId",
15059
+ "--min-revision": "minRevision",
15060
+ "--secret": "secret"
15061
+ };
15062
+ var readValueFlag = (args, index) => {
15063
+ const arg = args[index];
15064
+ for (const [flag, field] of Object.entries(valueFlags)) {
15065
+ if (arg === flag) {
15066
+ return { consumed: 2, field, value: args[index + 1] ?? null };
15067
+ }
15068
+ if (arg.startsWith(`${flag}=`)) {
15069
+ return { consumed: 1, field, value: arg.slice(flag.length + 1) };
15070
+ }
15071
+ }
15072
+ return null;
15073
+ };
14737
15074
  var parseCliArgs = (args) => {
14738
15075
  const parsed = {
14739
15076
  command: null,
15077
+ expectObjectId: null,
14740
15078
  filePath: null,
14741
15079
  help: false,
15080
+ minRevision: null,
14742
15081
  secret: null
14743
15082
  };
14744
15083
  for (let index = 0; index < args.length; index += 1) {
@@ -14747,13 +15086,10 @@ var parseCliArgs = (args) => {
14747
15086
  parsed.help = true;
14748
15087
  continue;
14749
15088
  }
14750
- if (arg === "--secret") {
14751
- parsed.secret = args[index + 1] ?? null;
14752
- index += 1;
14753
- continue;
14754
- }
14755
- if (arg.startsWith("--secret=")) {
14756
- parsed.secret = arg.slice("--secret=".length);
15089
+ const flag = readValueFlag(args, index);
15090
+ if (flag) {
15091
+ parsed[flag.field] = flag.value;
15092
+ index += flag.consumed - 1;
14757
15093
  continue;
14758
15094
  }
14759
15095
  if (!parsed.command) {
@@ -14788,10 +15124,20 @@ var readRecipientSecret = (secretArg) => {
14788
15124
  var usage = `Doctrine Secrets
14789
15125
 
14790
15126
  Usage:
14791
- doctrine-secrets decrypt <secrets.enc.json> [--secret <recipient-secret>]
15127
+ doctrine-secrets decrypt <secrets.enc.json>
15128
+ [--expect-object <object-id>] [--min-revision <n>]
15129
+
15130
+ Pinning:
15131
+ --expect-object Refuse content from any other encrypted object (for example
15132
+ another file copied over this one).
15133
+ --min-revision Refuse revisions older than this (replayed old versions).
14792
15134
 
14793
15135
  Environment:
14794
- DOCTRINE_RECIPIENT_SECRET External recipient secret fallback
15136
+ DOCTRINE_RECIPIENT_SECRET External recipient secret; set it from your secret
15137
+ manager or CI env block.
15138
+
15139
+ --secret <recipient-secret> is still accepted but discouraged: arguments are
15140
+ visible in process listings and shell history.
14795
15141
  `;
14796
15142
 
14797
15143
  // src/runCli.ts
@@ -14804,8 +15150,13 @@ var runCli = async (args) => {
14804
15150
  if (parsed.command !== "decrypt" || !parsed.filePath) {
14805
15151
  throw new Error(usage);
14806
15152
  }
15153
+ const expectation = parseEncryptedEnvelopeExpectation({
15154
+ minRevision: parsed.minRevision,
15155
+ objectId: parsed.expectObjectId
15156
+ });
14807
15157
  const plaintext = await decryptForumEncryptedFileText({
14808
15158
  encryptedText: await readEncryptedFile(parsed.filePath),
15159
+ expectation,
14809
15160
  recipientSecret: readRecipientSecret(parsed.secret)
14810
15161
  });
14811
15162
  process.stdout.write(plaintext);