badmfck-api-server 6.0.2 → 6.0.3

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
@@ -28,8 +28,9 @@ Node.js 21+ is required.
28
28
  11. [Deployer and CLI](#deployer-and-cli)
29
29
  12. [Blue-green deployments](#blue-green-deployments)
30
30
  13. [Backups and restore](#backups-and-restore)
31
- 14. [Options reference](#options-reference)
32
- 15. [Security](#security)
31
+ 14. [Deploy review](#deploy-review)
32
+ 15. [Options reference](#options-reference)
33
+ 16. [Security](#security)
33
34
 
34
35
  ---
35
36
 
@@ -321,6 +322,7 @@ The library protects four things, each in its own way:
321
322
  | Monitor (`sm/*`) | your operations team | password + mandatory TOTP 2FA, then a session token |
322
323
  | Documentation (`doc/*`) | developers and partners | login and password (a static token) |
323
324
  | Deployer (`pckg/*`) | CI and developers | deployer user + project token |
325
+ | Deploy review (`review/*`) | reviewers | personal emailed link + login, password and TOTP 2FA |
324
326
 
325
327
  The library doesn't manage the users of your application. That's the job of your interceptor and
326
328
  database. The rest of this section is about the built-in consoles.
@@ -575,6 +577,43 @@ A project config (`projects_path/<name>.json`):
575
577
  }
576
578
  ```
577
579
 
580
+ #### Keeping secrets out of the deployed code
581
+
582
+ By default, `config` values are written into the shipped files in place of `_{{KEY}}_`. That puts
583
+ passwords into the code, into both blue-green slots and into every backup. Add `secrets` to the project
584
+ config to avoid this:
585
+
586
+ ```jsonc
587
+ "secrets": {} // uses "secrets_dir" from setup.json
588
+ "secrets": { "dir": "/etc/node-secrets" } // → /etc/node-secrets/<project>[-<slot>].json
589
+ "secrets": { "file": "/etc/node-secrets/my.json" }
590
+ ```
591
+
592
+ The deployer writes the values (merged for the slot) into that file, with permissions `600` and
593
+ outside the deploy folder, and rewrites each quoted placeholder in `.js` files as a read of the file:
594
+
595
+ ```js
596
+ DB_PASSWORD: "_{{db_password}}_" // in the archive
597
+ DB_PASSWORD: (function(k){ … reads /etc/node-secrets/my-blue.json … })("db_password") // on the server
598
+ ```
599
+
600
+ - **No code changes.** The application gets exactly the strings it got before, so `parseInt("_{{port}}_")`
601
+ still works. The file is read once per process.
602
+ - **Restarts.** pm2 restarts, `migrate` and cluster workers keep working, because the file stays in place.
603
+ - **Backups and restore.** Backups and archives contain only the file path. A restored version reads
604
+ the current values instead of the ones from its deploy.
605
+ - **Missing key.** If a key is missing from the file, the start fails with a clear error instead of
606
+ running with a placeholder.
607
+ - **Same user.** The secrets file belongs to the deployer's user and is readable only by it. pm2,
608
+ started by the deployer, runs the app as that same user. A project whose pm2 attributes switch the
609
+ user (`--uid`, `--gid`) is refused before anything changes, since the app couldn't read the file.
610
+ The file is also read back before the app is started.
611
+ - **Start with a blue-green project.** If the new version fails to start, the inactive slot fails and
612
+ traffic stays on the old one until you `activate`.
613
+ - **Fallback to plain substitution.** Values are still written into the file for `.json`, `.env`,
614
+ unquoted placeholders, templates with `${…}`, ES-module projects, and any file that wouldn't compile
615
+ after the rewrite. Each deploy logs which files still hold values.
616
+
578
617
  **In your project**, create `deploy.json` or a `deploy/` folder with one or more configs. Keep it out of
579
618
  git: it holds credentials.
580
619
 
@@ -623,6 +662,8 @@ To pass a config path through npm, use `--`: `npm run deploy -- deploy/prod.json
623
662
  - Every deploy, switch and restore needs a deployer user and the project token. Both are stored on
624
663
  the server only as hashes.
625
664
  - `allowed_ips` limits which addresses can reach the deployer at all.
665
+ - With [deploy review](#deploy-review), uploads wait for approval by reviewers who sign in with a
666
+ password and 2FA.
626
667
 
627
668
  ---
628
669
 
@@ -763,7 +804,98 @@ How a restore works:
763
804
  Restoring a standby slot changes nothing until you `activate` it.
764
805
 
765
806
  Configuration values are baked in at deploy time. A restored version comes back with the secrets it was
766
- deployed with.
807
+ deployed with, unless the project uses a [secrets file](#keeping-secrets-out-of-the-deployed-code).
808
+
809
+ ---
810
+
811
+ ## Deploy review
812
+
813
+ A project can require approval before anything reaches the server. The upload is held, each reviewer
814
+ gets a personal link by email, and the deploy runs only after approval. That way stolen deploy
815
+ credentials alone can't change production.
816
+
817
+ ### Setup
818
+
819
+ Reviewers are defined in the deployer's `setup.json`. Their passwords are hashes made with
820
+ `npx badmfck hash-password`, and they set up 2FA at the first sign-in. `review_url` is the address of
821
+ the review page, as reviewers reach it:
822
+
823
+ ```jsonc
824
+ {
825
+ "reviewers": [
826
+ { "login": "lead", "password": "scrypt$16384$8$1$…", "email": "lead@example.com" },
827
+ { "login": "cto", "password": "scrypt$16384$8$1$…", "email": "cto@example.com" }
828
+ ],
829
+ "review_url": "https://deployer.example.com/api/review/html",
830
+ "notifier": { "URL": "…", "KEY": "…" }, // sends the emails
831
+ "allowed_ips": ["10.8.0.0/24"] // the review page is behind it too, e.g. the VPN range
832
+ }
833
+ ```
834
+
835
+ A project opts in from its config:
836
+
837
+ ```jsonc
838
+ "review": { "reviewers": ["lead", "cto"], "mode": "all", "ttlHours": 24 }
839
+ ```
840
+
841
+ - **`mode`.** With `"any"`, one accept is enough; with `"all"`, every reviewer must accept. Either
842
+ way, a single decline rejects the upload.
843
+ - **`ttlHours`.** How long the links stay valid: 1 to 168 hours, 24 by default.
844
+
845
+ If a project's review can't work (an unknown reviewer, no `review_url`, no notifier), the deployer says
846
+ so at startup and refuses that project's uploads until it is fixed.
847
+
848
+ ### How it works
849
+
850
+ 1. **`badmfck deploy`** uploads as usual. The archive goes through all the usual checks and is then
851
+ held. The CLI prints `WAITING FOR REVIEW`, and production is untouched.
852
+ 2. **Each reviewer gets an email** with a personal link. The link alone is not enough: it opens a
853
+ sign-in with login, password and a 2FA code.
854
+ 3. **The page shows the changes** compared with the last deployed version: version before and
855
+ after, dependency changes in `package.json`, and added, removed and changed files with a
856
+ line-by-line diff.
857
+ 4. **Accept** runs the normal deploy (backup, migrations, pm2, nginx) from the stored archive, after
858
+ checking that its SHA-256 still matches what the reviewers saw. For blue-green, the new version
859
+ lands in the inactive slot, and `badmfck activate` still switches traffic. **Decline** deletes the
860
+ archive.
861
+ 5. **A new upload** replaces the pending one. Every old link and every open review session stop
862
+ working, and reviewers get new links.
863
+
864
+ Undecided uploads expire after `ttlHours`, and their archive is removed.
865
+
866
+ ### What the diff shows and hides
867
+
868
+ The comparison uses the **raw archives**: the stored archive of the last successful deploy and the
869
+ new one. Deployed folders are never read, because config values (passwords) are substituted there.
870
+ Files such as `.env*`, `*.pem` and `*.key` are listed, but their content is never shown. Binary and
871
+ very large files are listed with their sizes. The first reviewed deploy of a project has nothing to
872
+ compare with, so every file is shown as added.
873
+
874
+ ### Security notes
875
+
876
+ - **Personal links.** A link works only for the reviewer it was sent to. The token is in the URL
877
+ fragment (`#…`), which never reaches the server logs, and the page removes it from the address bar.
878
+ - **Sessions.** A session lasts 15 minutes without activity and 1 hour at most. It is bound to one
879
+ upload: a new upload ends it.
880
+ - **Lockout.** 10 failed sign-ins lock the reviewer for 30 minutes.
881
+ - **Mail scanners.** Opening the link changes nothing. Accept and decline need a signed-in click, so
882
+ a mail scanner that "visits" links can't approve anything.
883
+ - **Separation of duties.** Give the review to someone other than the person who deploys. That's
884
+ what change control (for example PCI DSS 6.5) expects.
885
+
886
+ ### Audit trail and maintenance
887
+
888
+ All review data lives in `<projects_path>/.review/`, with permissions `600`:
889
+
890
+ | File | Content |
891
+ |---|---|
892
+ | `<project>.history.jsonl` | every upload, decision and result, with IP addresses and the archive SHA-256 |
893
+ | `<project>.pending.*` | the archive waiting for review and its state |
894
+ | `<project>.last.tgz` | the raw archive of the last successful deploy, the "before" of the next diff |
895
+ | `reviewers-2fa.json` | reviewers' 2FA enrollments |
896
+
897
+ To reset a reviewer's 2FA, delete their entry from `reviewers-2fa.json`. It is read at every sign-in,
898
+ so no restart is needed.
767
899
 
768
900
  ---
769
901
 
@@ -66,6 +66,7 @@ const AccessStore_1 = require("./monitor/AccessStore");
66
66
  const MonitorAuth_1 = require("./monitor/MonitorAuth");
67
67
  const ClientIp_1 = require("./helper/ClientIp");
68
68
  const Deployer_1 = require("./deployment/Deployer");
69
+ const Review_1 = require("./review/Review");
69
70
  const ws_1 = require("ws");
70
71
  const WebSocketServer_1 = require("./WebSocketServer");
71
72
  let nextLogID = 0;
@@ -198,6 +199,7 @@ class APIService extends BaseService_1.BaseService {
198
199
  this.deployer.init();
199
200
  this.options.endpoints = [
200
201
  new Deployer_1.Deployer(),
202
+ new Review_1.Review(this.deployer, this.options),
201
203
  new Documentation_1.Documentation(this.options),
202
204
  new Monitor_1.Monitor(this.options),
203
205
  ];
@@ -60,6 +60,21 @@ declare const _TConfig: {
60
60
  readonly $__upstream_name_optional: true;
61
61
  };
62
62
  readonly $__nginx_optional: true;
63
+ readonly review: {
64
+ readonly reviewers: readonly [""];
65
+ readonly mode: "";
66
+ readonly $__mode_values: readonly ["any", "all"];
67
+ readonly ttlHours: 24;
68
+ readonly $__ttlHours_optional: true;
69
+ };
70
+ readonly $__review_optional: true;
71
+ readonly secrets: {
72
+ readonly dir: "";
73
+ readonly $__dir_optional: true;
74
+ readonly file: "";
75
+ readonly $__file_optional: true;
76
+ };
77
+ readonly $__secrets_optional: true;
63
78
  };
64
79
  export type IConfig = ValidationModel<typeof _TConfig>;
65
80
  export declare const REQ_DEPLOYMENT_CONFIG: Req<void, Map<string, {
@@ -92,6 +107,15 @@ export declare const REQ_DEPLOYMENT_CONFIG: Req<void, Map<string, {
92
107
  domain?: string | undefined;
93
108
  upstream_name?: string | undefined;
94
109
  } | undefined;
110
+ review?: {
111
+ reviewers: string[];
112
+ mode: "all" | "any";
113
+ ttlHours?: number | undefined;
114
+ } | undefined;
115
+ secrets?: {
116
+ dir?: string | undefined;
117
+ file?: string | undefined;
118
+ } | undefined;
95
119
  }>>;
96
120
  export declare const S_CONFIG_UPDATED: Signal<void>;
97
121
  export declare class ConfigService extends BaseService {
@@ -102,6 +102,21 @@ const _TConfig = {
102
102
  $__upstream_name_optional: true,
103
103
  },
104
104
  $__nginx_optional: true,
105
+ review: {
106
+ reviewers: [""],
107
+ mode: "",
108
+ $__mode_values: ["any", "all"],
109
+ ttlHours: 24,
110
+ $__ttlHours_optional: true,
111
+ },
112
+ $__review_optional: true,
113
+ secrets: {
114
+ dir: "",
115
+ $__dir_optional: true,
116
+ file: "",
117
+ $__file_optional: true,
118
+ },
119
+ $__secrets_optional: true,
105
120
  };
106
121
  exports.REQ_DEPLOYMENT_CONFIG = new badmfck_signal_1.Req();
107
122
  exports.S_CONFIG_UPDATED = new badmfck_signal_1.default();
@@ -274,6 +274,24 @@ async function Deploy(opt) {
274
274
  }
275
275
  const emptyResponse = body === null || body === undefined
276
276
  || (typeof body === "object" && Object.keys(body).length === 0);
277
+ const pending = body?.data?.data;
278
+ if (pending && typeof pending === "object" && pending.pendingReview === true) {
279
+ console.log(yellow(bold("⏳ UPLOADED — WAITING FOR REVIEW (not deployed yet)")));
280
+ console.log(line);
281
+ console.log(` ${dim("project: ")} ${opt.name}`);
282
+ console.log(` ${dim("version: ")} ${oldVersion} ${dim("→")} ${bold(newVersion)}`);
283
+ console.log(` ${dim("reviewers:")} ${(pending.reviewers ?? []).join(", ")} ${dim(pending.mode === "all" ? "(all must accept)" : "(any one can accept)")}`);
284
+ if (Array.isArray(pending.notNotified) && pending.notNotified.length)
285
+ console.log(` ${yellow("⚠ email not delivered to:")} ${pending.notNotified.join(", ")}`);
286
+ if (pending.expiresAt)
287
+ console.log(` ${dim("link valid until:")} ${new Date(pending.expiresAt).toISOString()}`);
288
+ if (pending.replacedPrevious)
289
+ console.log(` ${dim("replaced the previous pending upload — its links no longer work")}`);
290
+ console.log(` ${dim("elapsed: ")} ${elapsedMs}ms`);
291
+ console.log(line);
292
+ console.log("");
293
+ return archiveName;
294
+ }
277
295
  if (emptyResponse) {
278
296
  console.log(yellow(bold("⚠ DEPLOY LIKELY OK (server returned empty response)")));
279
297
  }
@@ -6,6 +6,7 @@ import { ValidationModel } from "../..";
6
6
  import { IDeploymentNotifier } from "./Notifier";
7
7
  import { IError } from "../structures/Interfaces";
8
8
  import net from "net";
9
+ import { IPendingReview, ReviewStore } from "./ReviewStore";
9
10
  declare const _TSetup: {
10
11
  readonly users: readonly [{
11
12
  readonly login: "";
@@ -22,6 +23,16 @@ declare const _TSetup: {
22
23
  readonly $__status_url_optional: true;
23
24
  readonly allowed_ips: readonly [""];
24
25
  readonly $__allowed_ips_optional: true;
26
+ readonly reviewers: readonly [{
27
+ readonly login: "";
28
+ readonly password: "";
29
+ readonly email: "";
30
+ }];
31
+ readonly $__reviewers_optional: true;
32
+ readonly review_url: "";
33
+ readonly $__review_url_optional: true;
34
+ readonly secrets_dir: "";
35
+ readonly $__secrets_dir_optional: true;
25
36
  };
26
37
  export type TDeployerSetup = ValidationModel<typeof _TSetup>;
27
38
  export interface IDeployerServiceOptions {
@@ -80,10 +91,12 @@ export declare class DeployerService extends BaseService {
80
91
  setup: TDeployerSetup | null;
81
92
  notifier: IDeploymentNotifier | null;
82
93
  busy: Map<string, boolean>;
94
+ reviews: ReviewStore;
83
95
  private _setupWatchDebounceTimer;
84
96
  private _lastSetupHash;
85
97
  constructor(options: IDeployerServiceOptions);
86
98
  init(): Promise<void>;
99
+ private _checkReviewSetup;
87
100
  private _loadSetup;
88
101
  private _reloadSetup;
89
102
  private _watchSetup;
@@ -104,7 +117,6 @@ export declare class DeployerService extends BaseService {
104
117
  };
105
118
  data?: undefined;
106
119
  } | {
107
- error?: undefined;
108
120
  data: {
109
121
  ok: boolean;
110
122
  project: string;
@@ -113,7 +125,29 @@ export declare class DeployerService extends BaseService {
113
125
  active: "blue" | "green" | null;
114
126
  activeThisDeploy: boolean;
115
127
  };
128
+ error?: undefined;
129
+ } | {
130
+ error?: undefined;
131
+ data: {
132
+ ok: boolean;
133
+ project: string;
134
+ pendingReview: boolean;
135
+ mode: "all" | "any";
136
+ reviewers: string[];
137
+ notNotified: string[];
138
+ expiresAt: number;
139
+ replacedPrevious: boolean;
140
+ };
116
141
  }>;
142
+ private _deploy;
143
+ private _reviewSetup;
144
+ private _queueForReview;
145
+ reviewDecide(project: string, sha256: string, reviewer: string, decision: "accept" | "decline", ip: string | null): Promise<{
146
+ pending?: IPendingReview;
147
+ error?: string;
148
+ }>;
149
+ private _deployApproved;
150
+ private _copyArchive;
117
151
  switchSlot(data: {
118
152
  auth?: string;
119
153
  authLogin?: string;
@@ -192,10 +226,10 @@ export declare class DeployerService extends BaseService {
192
226
  }): Promise<{
193
227
  data?: undefined;
194
228
  error: {
229
+ details?: undefined;
195
230
  code: number;
196
231
  message: string;
197
232
  httpStatus: number;
198
- details?: undefined;
199
233
  };
200
234
  } | {
201
235
  data?: undefined;
@@ -249,18 +283,26 @@ export declare class DeployerService extends BaseService {
249
283
  list: net.BlockList | null;
250
284
  error?: string;
251
285
  };
286
+ isIpAllowed(ip: string | undefined): boolean;
252
287
  private _ipAllowed;
253
288
  private _warnPlaintextUsers;
254
289
  static PLAINTEXT_ERROR: string;
255
290
  private _checkUserAuth;
256
291
  private static _extractPort;
257
292
  private _renderNginx;
293
+ private static _pm2AttributesFor;
258
294
  runPM2(found: IConfig, projectState?: IProjectState | null): Promise<IError | null>;
259
295
  private _verifyAutorestart;
260
296
  private static readonly SKIP_DIRS;
261
297
  private static readonly TEMPLATE_EXTENSIONS;
262
- applyConfig(dir: string, config: Record<string, string>): Promise<void>;
263
- processFile(filePath: string, config: Record<string, string>): Promise<void>;
298
+ applyConfig(dir: string, config: Record<string, string>, ctx?: {
299
+ secretsFile: string | null;
300
+ onDisk: string[];
301
+ }): Promise<void>;
302
+ processFile(filePath: string, config: Record<string, string>, ctx?: {
303
+ secretsFile: string | null;
304
+ onDisk: string[];
305
+ }): Promise<void>;
264
306
  private _destinationProblem;
265
307
  private static _unsafeArchiveEntry;
266
308
  private static _escapingSymlink;