badmfck-api-server 6.0.3 → 6.0.4

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
@@ -307,6 +307,17 @@ monitorAuthDir: "/var/lib/my-service", // where 2FA enrollments are kept
307
307
  change is ignored and the previous access stays in force. The reason is logged.
308
308
  - **Location and permissions.** Keep the file outside the deploy folders and `chmod 600` it. A warning
309
309
  is logged if other users can read it.
310
+ - **Restrict by address.** `monitorAllowedIps` in `access` (inline or in `access.json`) limits every
311
+ `sm/*` request to the given IPs and CIDR subnets, the page and sign-in included. A session token
312
+ taken elsewhere is therefore useless outside those addresses too:
313
+
314
+ ```jsonc
315
+ { "monitor": [ … ], "monitorAllowedIps": ["10.8.0.0/24", "203.0.113.7"] }
316
+ ```
317
+
318
+ Other addresses get `403`. Changes in `access.json` apply without a restart, and an invalid entry
319
+ rejects the change. Behind nginx, pass `X-Real-IP` (see [`trustedProxies`](#options-reference)),
320
+ otherwise every request appears to come from `127.0.0.1`.
310
321
  - **Keep `monitorAuthDir` outside the deploy folders.** Otherwise a deploy wipes the enrollments and
311
322
  everyone has to enroll again.
312
323
 
@@ -911,7 +922,7 @@ so no restart is needed.
911
922
  | `isProductionEnvironment` | `false` | production mode |
912
923
  | `interceptor` | — | authentication for your endpoints |
913
924
  | `preproducer` / `postproducer` | — | hooks before the handler / before the response is sent |
914
- | `access` | `{}` | `{ monitor, documentation }` users, or a path to a JSON file reloaded on change |
925
+ | `access` | `{}` | `{ monitor, documentation, monitorAllowedIps }`, or a path to a JSON file reloaded on change |
915
926
  | `monitorAuthDir` / `monitorAuthFile` | in memory | where 2FA enrollments are stored |
916
927
  | `metricsDir` | in memory | persist metrics; 10 weeks are kept |
917
928
  | `logFiles` | pm2 auto-detected | log files the monitor may tail (for example nginx) |
@@ -86,6 +86,7 @@ export declare const REQ_WS_SERVER: Req<void, WebSocketServer | null>;
86
86
  export declare const REQ_INTERNAL_CALL: Req<HTTPRequestVO, IError | any>;
87
87
  export declare const REQ_MONITOR_USERS: Req<void, IMonitorUser[]>;
88
88
  export declare const REQ_DOC_USERS: Req<void, IDocumentationUser[]>;
89
+ export declare const REQ_MONITOR_ALLOWED_IPS: Req<void, string[]>;
89
90
  export declare const S_APP_STARTED: Signal<void>;
90
91
  export declare function Initializer(services: IBaseService[]): Promise<void>;
91
92
  export declare class APIService<TInterceptorResult = any, TInternalCallParams = any> extends BaseService {
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.APIService = exports.S_APP_STARTED = exports.REQ_DOC_USERS = exports.REQ_MONITOR_USERS = exports.REQ_INTERNAL_CALL = exports.REQ_WS_SERVER = exports.REQ_HTTP_SERVER = exports.REQ_HTTP_REQUESTS_COUNT = exports.REQ_HTTP_LOG = exports.getDefaultOptions = void 0;
39
+ exports.APIService = exports.S_APP_STARTED = exports.REQ_MONITOR_ALLOWED_IPS = exports.REQ_DOC_USERS = exports.REQ_MONITOR_USERS = exports.REQ_INTERNAL_CALL = exports.REQ_WS_SERVER = exports.REQ_HTTP_SERVER = exports.REQ_HTTP_REQUESTS_COUNT = exports.REQ_HTTP_LOG = exports.getDefaultOptions = void 0;
40
40
  exports.Initializer = Initializer;
41
41
  const express_1 = __importDefault(require("express"));
42
42
  const BaseService_1 = require("./BaseService");
@@ -106,6 +106,7 @@ exports.REQ_WS_SERVER = new badmfck_signal_1.Req(undefined, "REQ_WS_SERVER");
106
106
  exports.REQ_INTERNAL_CALL = new badmfck_signal_1.Req(undefined, "REQ_INTERNAL_CALL");
107
107
  exports.REQ_MONITOR_USERS = new badmfck_signal_1.Req(undefined, "REQ_MONITOR_USERS");
108
108
  exports.REQ_DOC_USERS = new badmfck_signal_1.Req(undefined, "REQ_DOC_USERS");
109
+ exports.REQ_MONITOR_ALLOWED_IPS = new badmfck_signal_1.Req(undefined, "REQ_MONITOR_ALLOWED_IPS");
109
110
  exports.S_APP_STARTED = new badmfck_signal_1.default("S_APP_STARTED");
110
111
  const activeServices = [];
111
112
  const PACKAGE_VERSION = (() => {
@@ -186,6 +187,7 @@ class APIService extends BaseService_1.BaseService {
186
187
  });
187
188
  exports.REQ_MONITOR_USERS.listener = async () => access.monitor;
188
189
  exports.REQ_DOC_USERS.listener = async () => access.documentation;
190
+ exports.REQ_MONITOR_ALLOWED_IPS.listener = async () => access.monitorAllowedIps;
189
191
  this.options.endpoints.push(new Monitor_1.Monitor(this.options));
190
192
  this.options.endpoints.push(new Documentation_1.Documentation(this.options));
191
193
  this.options.endpoints.push(new ExternalServiceEndpoint_1.ExternalServiceEndpoint());
@@ -5,7 +5,6 @@ import { UploadedFile } from "express-fileupload";
5
5
  import { ValidationModel } from "../..";
6
6
  import { IDeploymentNotifier } from "./Notifier";
7
7
  import { IError } from "../structures/Interfaces";
8
- import net from "net";
9
8
  import { IPendingReview, ReviewStore } from "./ReviewStore";
10
9
  declare const _TSetup: {
11
10
  readonly users: readonly [{
@@ -280,7 +279,7 @@ export declare class DeployerService extends BaseService {
280
279
  private _projectByToken;
281
280
  tokensMatch(a: string | undefined, b: string | undefined): boolean;
282
281
  static buildAllowList(entries: readonly string[] | undefined | null): {
283
- list: net.BlockList | null;
282
+ list: import("node:net").BlockList | null;
284
283
  error?: string;
285
284
  };
286
285
  isIpAllowed(ip: string | undefined): boolean;
@@ -16,7 +16,6 @@ const util_1 = require("util");
16
16
  const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
17
17
  const fs_1 = __importDefault(require("fs"));
18
18
  const crypto_1 = __importDefault(require("crypto"));
19
- const net_1 = __importDefault(require("net"));
20
19
  const Watchdog_1 = require("./Watchdog");
21
20
  const NginxHelper_1 = require("./NginxHelper");
22
21
  const BlueGreenState_1 = require("./BlueGreenState");
@@ -24,6 +23,7 @@ const BackupManager_1 = require("./BackupManager");
24
23
  const PasswordHash_1 = require("../helper/PasswordHash");
25
24
  const ReviewStore_1 = require("./ReviewStore");
26
25
  const SecretsInjector_1 = require("./SecretsInjector");
26
+ const IpAllowList_1 = require("../helper/IpAllowList");
27
27
  const _TSetup = {
28
28
  users: [{
29
29
  login: "",
@@ -980,38 +980,13 @@ class DeployerService extends BaseService_1.BaseService {
980
980
  return crypto_1.default.timingSafeEqual(ha, hb);
981
981
  }
982
982
  static buildAllowList(entries) {
983
- const items = (entries ?? []).map(e => String(e).trim()).filter(e => e.length > 0);
984
- if (items.length === 0)
985
- return { list: null };
986
- const list = new net_1.default.BlockList();
987
- for (const item of items) {
988
- const [addr, prefix, extra] = item.split("/");
989
- const family = net_1.default.isIP(addr);
990
- if (!family || extra !== undefined)
991
- return { list: null, error: `"${item}" is not an IP address or subnet` };
992
- const type = family === 6 ? "ipv6" : "ipv4";
993
- if (prefix === undefined) {
994
- list.addAddress(addr, type);
995
- continue;
996
- }
997
- const bits = Number(prefix), max = family === 6 ? 128 : 32;
998
- if (!/^\d+$/.test(prefix) || bits > max)
999
- return { list: null, error: `"${item}" has an invalid prefix (0–${max})` };
1000
- list.addSubnet(addr, bits, type);
1001
- }
1002
- return { list };
983
+ return IpAllowList_1.IpAllowList.build(entries);
1003
984
  }
1004
985
  isIpAllowed(ip) {
1005
986
  return this._ipAllowed(ip);
1006
987
  }
1007
988
  _ipAllowed(ip) {
1008
- const { list } = DeployerService.buildAllowList(this.setup?.allowed_ips);
1009
- if (!list)
1010
- return true;
1011
- const family = net_1.default.isIP(String(ip ?? ""));
1012
- if (!family)
1013
- return false;
1014
- return list.check(String(ip), family === 6 ? "ipv6" : "ipv4");
989
+ return IpAllowList_1.IpAllowList.allows(IpAllowList_1.IpAllowList.build(this.setup?.allowed_ips).list, ip);
1015
990
  }
1016
991
  _warnPlaintextUsers() {
1017
992
  if (!DeployerService.buildAllowList(this.setup?.allowed_ips).list)
@@ -0,0 +1,8 @@
1
+ import net from "net";
2
+ export declare class IpAllowList {
3
+ static build(entries: readonly string[] | undefined | null): {
4
+ list: net.BlockList | null;
5
+ error?: string;
6
+ };
7
+ static allows(list: net.BlockList | null, ip: string | undefined | null): boolean;
8
+ }
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.IpAllowList = void 0;
7
+ const net_1 = __importDefault(require("net"));
8
+ class IpAllowList {
9
+ static build(entries) {
10
+ const items = (entries ?? []).map(e => String(e).trim()).filter(e => e.length > 0);
11
+ if (items.length === 0)
12
+ return { list: null };
13
+ const list = new net_1.default.BlockList();
14
+ for (const item of items) {
15
+ const [addr, prefix, extra] = item.split("/");
16
+ const family = net_1.default.isIP(addr);
17
+ if (!family || extra !== undefined)
18
+ return { list: null, error: `"${item}" is not an IP address or subnet` };
19
+ const type = family === 6 ? "ipv6" : "ipv4";
20
+ if (prefix === undefined) {
21
+ list.addAddress(addr, type);
22
+ continue;
23
+ }
24
+ const bits = Number(prefix), max = family === 6 ? 128 : 32;
25
+ if (!/^\d+$/.test(prefix) || bits > max)
26
+ return { list: null, error: `"${item}" has an invalid prefix (0–${max})` };
27
+ list.addSubnet(addr, bits, type);
28
+ }
29
+ return { list };
30
+ }
31
+ static allows(list, ip) {
32
+ if (!list)
33
+ return true;
34
+ const family = net_1.default.isIP(String(ip ?? ""));
35
+ if (!family)
36
+ return false;
37
+ return list.check(String(ip), family === 6 ? "ipv6" : "ipv4");
38
+ }
39
+ }
40
+ exports.IpAllowList = IpAllowList;
@@ -2,6 +2,7 @@ import type { IMonitorUser, IDocumentationUser } from "../APIService";
2
2
  export interface IAccess {
3
3
  monitor?: IMonitorUser[];
4
4
  documentation?: IDocumentationUser[];
5
+ monitorAllowedIps?: string[];
5
6
  }
6
7
  export declare class AccessStore {
7
8
  private onChange?;
@@ -13,6 +14,7 @@ export declare class AccessStore {
13
14
  constructor(source: IAccess | string | undefined | null, onChange?: ((prev: IAccess, next: IAccess) => void) | undefined);
14
15
  get monitor(): IMonitorUser[];
15
16
  get documentation(): IDocumentationUser[];
17
+ get monitorAllowedIps(): string[];
16
18
  static validate(value: any): string | null;
17
19
  private loadSync;
18
20
  private reload;
@@ -8,6 +8,7 @@ const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const crypto_1 = __importDefault(require("crypto"));
10
10
  const LogService_1 = require("../LogService");
11
+ const IpAllowList_1 = require("../helper/IpAllowList");
11
12
  const ROLES = ["admin", "it", "analytic"];
12
13
  class AccessStore {
13
14
  onChange;
@@ -28,9 +29,17 @@ class AccessStore {
28
29
  }
29
30
  get monitor() { return this.current.monitor ?? []; }
30
31
  get documentation() { return this.current.documentation ?? []; }
32
+ get monitorAllowedIps() { return this.current.monitorAllowedIps ?? []; }
31
33
  static validate(value) {
32
34
  if (!value || typeof value !== "object" || Array.isArray(value))
33
35
  return "root must be an object";
36
+ if (value.monitorAllowedIps !== undefined) {
37
+ if (!Array.isArray(value.monitorAllowedIps) || value.monitorAllowedIps.some((e) => typeof e !== "string"))
38
+ return "monitorAllowedIps must be an array of strings";
39
+ const ips = IpAllowList_1.IpAllowList.build(value.monitorAllowedIps);
40
+ if (ips.error)
41
+ return "monitorAllowedIps: " + ips.error;
42
+ }
34
43
  for (const list of ["monitor", "documentation"]) {
35
44
  const users = value[list];
36
45
  if (users === undefined)
@@ -99,8 +108,9 @@ class AccessStore {
99
108
  this.hash = hash;
100
109
  this.refusedHash = "";
101
110
  this.warnPermissions();
102
- this.apply({ monitor: parsed.monitor, documentation: parsed.documentation });
103
- (0, LogService_1.logInfo)(`Access ${initial ? "loaded" : "reloaded"} from ${this.file}: ${this.monitor.length} monitor, ${this.documentation.length} documentation user(s)`);
111
+ this.apply({ monitor: parsed.monitor, documentation: parsed.documentation, monitorAllowedIps: parsed.monitorAllowedIps });
112
+ (0, LogService_1.logInfo)(`Access ${initial ? "loaded" : "reloaded"} from ${this.file}: ${this.monitor.length} monitor, ${this.documentation.length} documentation user(s)`
113
+ + (this.monitorAllowedIps.length ? `, monitor limited to ${this.monitorAllowedIps.join(", ")}` : ""));
104
114
  }
105
115
  refuse(reason, initial) {
106
116
  if (initial)
@@ -21,6 +21,7 @@ export declare class Monitor extends BaseEndpoint {
21
21
  fileParsed: boolean;
22
22
  lastTimeCacheChecked: number;
23
23
  constructor(options: APIServiceOptions);
24
+ __precheck(req: HTTPRequestVO): Promise<TransferPacketVO<any> | null>;
24
25
  loadHTMLFile(): Promise<string>;
25
26
  html(req: HTTPRequestVO): Promise<TransferPacketVO>;
26
27
  controllers(req: HTTPRequestVO): Promise<TransferPacketVO>;
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Monitor = exports.S_MONITOR_RESTART_REQUESTED = exports.S_MONITOR_REGISTRATE_ACTION = void 0;
7
7
  const badmfck_signal_1 = require("badmfck-signal");
8
8
  const APIService_1 = require("../APIService");
9
+ const IpAllowList_1 = require("../helper/IpAllowList");
9
10
  const BaseEndpoint_1 = require("../BaseEndpoint");
10
11
  const BaseService_1 = require("../BaseService");
11
12
  const LogService_1 = require("../LogService");
@@ -103,6 +104,21 @@ class Monitor extends BaseEndpoint_1.BaseEndpoint {
103
104
  } }
104
105
  ]);
105
106
  }
107
+ async __precheck(req) {
108
+ const entries = await APIService_1.REQ_MONITOR_ALLOWED_IPS.request();
109
+ if (!entries || entries.length === 0)
110
+ return null;
111
+ const { list, error } = IpAllowList_1.IpAllowList.build(entries);
112
+ if (error) {
113
+ (0, LogService_1.logError)(`Monitor: monitorAllowedIps is invalid (${error}) — the monitor refuses every request until it is fixed`);
114
+ return { error: { ...DefaultErrors_1.default.FORBIDDEN, details: "The monitor is closed: its address allow-list is invalid." } };
115
+ }
116
+ if (!IpAllowList_1.IpAllowList.allows(list, req.ip)) {
117
+ (0, LogService_1.logWarn)(`Monitor: request refused from ${req.ip ?? "unknown"} — not in monitorAllowedIps`);
118
+ return { error: { ...DefaultErrors_1.default.FORBIDDEN, details: "The monitor is not available from this address." } };
119
+ }
120
+ return null;
121
+ }
106
122
  async loadHTMLFile() {
107
123
  if (!this.indexHtmlFile)
108
124
  this.indexHtmlFile = fs_1.default.readFileSync(path_1.default.resolve(__dirname, "index.html")).toString("utf-8");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "badmfck-api-server",
3
- "version": "6.0.3",
3
+ "version": "6.0.4",
4
4
  "description": "Simple API http server based on express",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",