badmfck-api-server 6.0.10 → 6.0.12
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 +45 -10
- package/dist/apiServer/deployment/Activate.js +2 -6
- package/dist/apiServer/deployment/Backups.js +3 -2
- package/dist/apiServer/deployment/Deploy.js +5 -3
- package/dist/apiServer/deployment/DeployKeyWizard.d.ts +1 -0
- package/dist/apiServer/deployment/DeployKeyWizard.js +68 -0
- package/dist/apiServer/deployment/Deployer.d.ts +1 -0
- package/dist/apiServer/deployment/Deployer.js +7 -5
- package/dist/apiServer/deployment/DeployerService.d.ts +23 -1
- package/dist/apiServer/deployment/DeployerService.js +43 -13
- package/dist/apiServer/deployment/Restore.js +4 -3
- package/dist/apiServer/deployment/SetupConfigWizard.js +38 -2
- package/dist/apiServer/deployment/Status.js +4 -7
- package/dist/apiServer/deployment/Wizards.d.ts +1 -0
- package/dist/apiServer/deployment/Wizards.js +78 -0
- package/dist/apiServer/deployment/cli.js +20 -0
- package/dist/apiServer/deployment/cliCommon.d.ts +1 -1
- package/dist/apiServer/deployment/cliCommon.js +6 -2
- package/dist/apiServer/deployment/resolveConfig.d.ts +2 -1
- package/dist/apiServer/deployment/resolveConfig.js +13 -2
- package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +39 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -176,8 +176,25 @@ getDefaultOptions({ interceptor: new SessionInterceptor(), … });
|
|
|
176
176
|
// handlers then read req.interceptorResult.userId
|
|
177
177
|
```
|
|
178
178
|
|
|
179
|
-
|
|
180
|
-
|
|
179
|
+
Two ready-made interceptors handle signed server-to-server requests. Both use a timestamp window and
|
|
180
|
+
nonce replay protection:
|
|
181
|
+
|
|
182
|
+
- **`InterceptorPayAuth`** uses an HMAC-SHA256 signature with a shared key.
|
|
183
|
+
- **`InterceptorSignedAuth`** uses Ed25519 key pairs. The caller keeps the private key, and the
|
|
184
|
+
server stores only public keys, so nothing on the server can be stolen and reused. The signature
|
|
185
|
+
covers the method, path, timestamp, nonce, every field and the sha256 of every uploaded file.
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { InterceptorSignedAuth } from "badmfck-api-server";
|
|
189
|
+
|
|
190
|
+
// server: public keys by key id
|
|
191
|
+
const interceptor = new InterceptorSignedAuth(kid => partners[kid]?.publicKey);
|
|
192
|
+
// handlers then read req.interceptorResult.kid
|
|
193
|
+
|
|
194
|
+
// client
|
|
195
|
+
const { publicKey, privateKey } = InterceptorSignedAuth.generateKeyPair();
|
|
196
|
+
const authorization = InterceptorSignedAuth.sign({ privateKey, kid: "partner-1", method: "POST", url, data: body });
|
|
197
|
+
```
|
|
181
198
|
|
|
182
199
|
---
|
|
183
200
|
|
|
@@ -521,10 +538,11 @@ documentation users their own passwords, never ones they use elsewhere.
|
|
|
521
538
|
|
|
522
539
|
- **Server.** The deployer server keeps `setup.json` users as hashes (`hash-password --deployer`).
|
|
523
540
|
- **Addresses.** `allowed_ips` in `setup.json` limits which addresses can use the deployer at all.
|
|
524
|
-
- **Client.** The deploying machine keeps the login and
|
|
525
|
-
|
|
526
|
-
- **What goes over the wire.**
|
|
527
|
-
|
|
541
|
+
- **Client.** The deploying machine keeps the login and either a private key (recommended) or the
|
|
542
|
+
password in `deploy.json`. Either way, the file can deploy on its own: never share it or commit it.
|
|
543
|
+
- **What goes over the wire.** With a key, `Authorization: Signature kid=…, ts=…, nonce=…, sig=…`. The
|
|
544
|
+
signature is good for one request and five minutes, and covers the project, the fields and the
|
|
545
|
+
archive. With a password, `Authorization: Bearer sha256(login:password)` and `X-Deployer-Login`.
|
|
528
546
|
- **Project token.** Deploying, switching and restoring also require the project's own `token`. The
|
|
529
547
|
project config on the server holds only its hash. Run `npx badmfck project-token`: it prints a new
|
|
530
548
|
random token for `deploy.json` and its hash for the project config. To keep an existing token, run
|
|
@@ -604,7 +622,14 @@ getDefaultOptions({
|
|
|
604
622
|
});
|
|
605
623
|
```
|
|
606
624
|
|
|
607
|
-
`setup.json` lists who may deploy.
|
|
625
|
+
`setup.json` lists who may deploy. The recommended way is a **signing key** per user. Run
|
|
626
|
+
`npx badmfck deploy-key` in the project: it writes an Ed25519 private key into `deploy.json` and prints the
|
|
627
|
+
public key to add to the user in `setup.json` (`setup-config` → "set a deployer user's public key").
|
|
628
|
+
Every request is then signed. A captured request can't be replayed or changed, the signature covers the
|
|
629
|
+
archive's sha256, and the deployer stores no secret at all. `"require_signature": true` in `setup.json`
|
|
630
|
+
turns passwords off for everyone once all users have keys. The project token is still required on top,
|
|
631
|
+
so a deploy always proves which project it is meant for. Users without a key sign in with a password,
|
|
632
|
+
which is stored as a hash. The easiest way to manage users, reviewers and
|
|
608
633
|
allowed addresses is `npx badmfck setup-config <folder>`, a menu that hashes passwords for you; for a
|
|
609
634
|
single hash use `npx badmfck hash-password --deployer`. When sign-in fails, the deployer logs why
|
|
610
635
|
(unknown login, wrong password, an old CLI without `X-Deployer-Login`), while the client only gets
|
|
@@ -612,7 +637,11 @@ single hash use `npx badmfck hash-password --deployer`. When sign-in fails, the
|
|
|
612
637
|
|
|
613
638
|
```jsonc
|
|
614
639
|
{
|
|
615
|
-
"users": [
|
|
640
|
+
"users": [
|
|
641
|
+
{ "login": "ci", "publicKey": "MCowBQYDK2VwAyEA…" }, // signs its requests
|
|
642
|
+
{ "login": "igor", "password": "scrypt$16384$8$1$…" } // password, until moved to a key
|
|
643
|
+
],
|
|
644
|
+
"require_signature": false,
|
|
616
645
|
"allowed_ips": ["203.0.113.7", "10.8.0.0/24"] // who may deploy; IPs and CIDR subnets, IPv4/IPv6
|
|
617
646
|
}
|
|
618
647
|
```
|
|
@@ -689,7 +718,7 @@ git: it holds credentials.
|
|
|
689
718
|
"host": "https://deployer.example.com/api/pckg/add",
|
|
690
719
|
"token": "<project token, printed by npx badmfck project-token>",
|
|
691
720
|
"username": "ci",
|
|
692
|
-
"password": "<your password>"
|
|
721
|
+
"privateKey": "<from npx badmfck deploy-key>", // or "password": "<your password>"
|
|
693
722
|
"includes": ["certs", { "src": "assets/logo.png", "dest": "bin/logo.png" }],
|
|
694
723
|
"excludes": ["*.map"]
|
|
695
724
|
}
|
|
@@ -707,6 +736,7 @@ git: it holds credentials.
|
|
|
707
736
|
|
|
708
737
|
| Command | What it does |
|
|
709
738
|
|---|---|
|
|
739
|
+
| `badmfck wizards` | list every interactive wizard below with what it does, and run one |
|
|
710
740
|
| `badmfck deploy [config]` | build and upload the project |
|
|
711
741
|
| `badmfck activate [config] [blue\|green]` | switch traffic to a slot (blue-green) |
|
|
712
742
|
| `badmfck status [config]` | active and last deployed slot, recent history |
|
|
@@ -718,6 +748,7 @@ git: it holds credentials.
|
|
|
718
748
|
| `badmfck access-config [file]` | create or edit `access.json`: monitor and documentation users, roles, passwords, allowed addresses |
|
|
719
749
|
| `badmfck migrate-configs [folder] [--yes]` | hash the secrets of old `setup.json`, project configs and `access.json` files in place |
|
|
720
750
|
| `badmfck setup-config [file\|folder]` | edit the deployer's `setup.json`: add, rename or remove users, change passwords, reviewers, allowed IPs |
|
|
751
|
+
| `badmfck deploy-key [deploy.json]` | generate a signing key: private key into `deploy.json`, public key for `setup.json` |
|
|
721
752
|
|
|
722
753
|
To pass a config path through npm, use `--`: `npm run deploy -- deploy/prod.json`.
|
|
723
754
|
|
|
@@ -1012,7 +1043,8 @@ so no restart is needed.
|
|
|
1012
1043
|
- **Client IP.** Proxy headers are trusted only from `trustedProxies`, so clients can't spoof their
|
|
1013
1044
|
address.
|
|
1014
1045
|
- **Deploys.** Archives are checked for path traversal and escaping symlinks, package install scripts
|
|
1015
|
-
are disabled, and every deploy needs a user and the project token
|
|
1046
|
+
are disabled, and every deploy needs a user and the project token. Requests are signed with Ed25519
|
|
1047
|
+
(the deployer keeps only public keys), so they can't be replayed or altered.
|
|
1016
1048
|
- **Blue-green.** Applications get a read-only status token; deploy credentials never reach them.
|
|
1017
1049
|
- **WebSocket.** Origin checks, authorization within a time limit, and limits on message size, message
|
|
1018
1050
|
rate and connections. A malformed frame can't crash the process.
|
|
@@ -1064,6 +1096,9 @@ or the same as the login). It copies the originals into a `.pre-hash-backup-*` f
|
|
|
1064
1096
|
`700`) and verifies every new hash. Delete that folder once deploys and sign-ins work, because it holds
|
|
1065
1097
|
the plain secrets.
|
|
1066
1098
|
|
|
1099
|
+
Then move deploys to signing keys, one user at a time: `npx badmfck deploy-key` in the project, and the
|
|
1100
|
+
public key into `setup.json`. When every user has a key, set `"require_signature": true`.
|
|
1101
|
+
|
|
1067
1102
|
Also removed in 6.x: the old `MysqlService` (use `DBService`).
|
|
1068
1103
|
|
|
1069
1104
|
---
|
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
3
|
exports.Activate = Activate;
|
|
7
|
-
const crypto_1 = __importDefault(require("crypto"));
|
|
8
4
|
const __1 = require("../..");
|
|
9
5
|
const resolveConfig_1 = require("./resolveConfig");
|
|
6
|
+
const cliCommon_1 = require("./cliCommon");
|
|
10
7
|
async function Activate(opt, scheme) {
|
|
11
8
|
opt = await (0, resolveConfig_1.resolveConfig)(opt);
|
|
12
9
|
if (scheme && scheme !== "blue" && scheme !== "green") {
|
|
@@ -23,14 +20,13 @@ async function Activate(opt, scheme) {
|
|
|
23
20
|
throw new Error(`Cannot derive switch URL from host "${opt.host}". ` +
|
|
24
21
|
`Either add "switch_host" to config, or make sure "host" ends with /add.`);
|
|
25
22
|
}
|
|
26
|
-
const authToken = crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
|
|
27
23
|
const requestBody = { name: opt.name, token: opt.token };
|
|
28
24
|
if (scheme)
|
|
29
25
|
requestBody.scheme = scheme;
|
|
30
26
|
console.log(`Activating${scheme ? ` slot=${scheme}` : " (auto: lastDeployed)"} for ${opt.name} at ${switchUrl}`);
|
|
31
27
|
const startedAt = Date.now();
|
|
32
28
|
const response = await __1.Http.post(switchUrl, requestBody, {
|
|
33
|
-
headers:
|
|
29
|
+
headers: (0, cliCommon_1.deployerHeaders)(opt, switchUrl, requestBody),
|
|
34
30
|
timeoutMs: 60 * 1000,
|
|
35
31
|
retry: { enabled: false },
|
|
36
32
|
});
|
|
@@ -7,8 +7,9 @@ const cliCommon_1 = require("./cliCommon");
|
|
|
7
7
|
async function Backups(opt) {
|
|
8
8
|
opt = await (0, resolveConfig_1.resolveConfig)(opt);
|
|
9
9
|
const { red, yellow, blue, green, dim, bold } = (0, cliCommon_1.palette)();
|
|
10
|
-
const
|
|
11
|
-
|
|
10
|
+
const url = (0, cliCommon_1.deployerUrl)(opt, "backups"), body = { name: opt.name };
|
|
11
|
+
const r = await __1.Http.post(url, body, {
|
|
12
|
+
headers: (0, cliCommon_1.deployerHeaders)(opt, url, body), timeoutMs: 30000, retry: { enabled: false },
|
|
12
13
|
});
|
|
13
14
|
const err = (0, cliCommon_1.responseError)(r);
|
|
14
15
|
if (err) {
|
|
@@ -8,10 +8,11 @@ const child_process_1 = require("child_process");
|
|
|
8
8
|
const path_1 = __importDefault(require("path"));
|
|
9
9
|
const fs_1 = __importDefault(require("fs"));
|
|
10
10
|
const __1 = require("../..");
|
|
11
|
-
const crypto_1 = __importDefault(require("crypto"));
|
|
12
11
|
const os_1 = __importDefault(require("os"));
|
|
13
12
|
const undici_1 = require("undici");
|
|
14
13
|
const resolveConfig_1 = require("./resolveConfig");
|
|
14
|
+
const cliCommon_1 = require("./cliCommon");
|
|
15
|
+
const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
|
|
15
16
|
async function Deploy(opt) {
|
|
16
17
|
opt = await (0, resolveConfig_1.resolveConfig)(opt);
|
|
17
18
|
const archiveName = __1.UID.sha256(opt.name.replaceAll(".", "_")) + ".tar.gz";
|
|
@@ -192,8 +193,9 @@ async function Deploy(opt) {
|
|
|
192
193
|
console.error("ARCHIVE NOT CREATED!");
|
|
193
194
|
return "";
|
|
194
195
|
}
|
|
195
|
-
const authToken = crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
|
|
196
196
|
const archivePath = path_1.default.resolve(archiveName);
|
|
197
|
+
const signedFields = { token: opt.token, name: opt.name };
|
|
198
|
+
const uploadHeaders = (0, cliCommon_1.deployerHeaders)(opt, opt.host, signedFields, opt.privateKey ? { file: await InterceptorSignedAuth_1.InterceptorSignedAuth.sha256File(archivePath) } : undefined);
|
|
197
199
|
const fileBlob = await fs_1.default.openAsBlob(archivePath);
|
|
198
200
|
const formData = new FormData();
|
|
199
201
|
formData.set("token", opt.token);
|
|
@@ -206,7 +208,7 @@ async function Deploy(opt) {
|
|
|
206
208
|
bodyTimeout: 5 * 60 * 1000,
|
|
207
209
|
});
|
|
208
210
|
const uploadResponse = await __1.Http.post(opt.host, formData, {
|
|
209
|
-
headers:
|
|
211
|
+
headers: uploadHeaders,
|
|
210
212
|
dispatcher: uploadAgent,
|
|
211
213
|
timeoutMs: 5 * 60 * 1000,
|
|
212
214
|
retry: { enabled: false },
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function DeployKeyWizard(target?: string): Promise<void>;
|
|
@@ -0,0 +1,68 @@
|
|
|
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.DeployKeyWizard = DeployKeyWizard;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const process_1 = require("process");
|
|
10
|
+
const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
|
|
11
|
+
const cliCommon_1 = require("./cliCommon");
|
|
12
|
+
const cliPrompt_1 = require("./cliPrompt");
|
|
13
|
+
async function DeployKeyWizard(target) {
|
|
14
|
+
const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
|
|
15
|
+
if (!process_1.stdin.isTTY) {
|
|
16
|
+
console.error(red("✗ deploy-key needs an interactive terminal — its output is a secret."));
|
|
17
|
+
process.exit(1);
|
|
18
|
+
}
|
|
19
|
+
console.log(bold("\nSigning key for deploys") + dim(" (Ed25519: the deployer keeps only the public key)"));
|
|
20
|
+
const candidates = target ? [target] : [
|
|
21
|
+
...(fs_1.default.existsSync("deploy.json") ? ["deploy.json"] : []),
|
|
22
|
+
...(fs_1.default.existsSync("deploy") && fs_1.default.statSync("deploy").isDirectory()
|
|
23
|
+
? fs_1.default.readdirSync("deploy").filter(f => f.endsWith(".json")).map(f => path_1.default.join("deploy", f)) : []),
|
|
24
|
+
];
|
|
25
|
+
let file = "";
|
|
26
|
+
if (candidates.length === 1)
|
|
27
|
+
file = await (0, cliPrompt_1.ask)("deploy.json to put the private key into (empty = only print it)", candidates[0]);
|
|
28
|
+
else if (candidates.length > 1) {
|
|
29
|
+
candidates.forEach((c, i) => console.log(` ${i + 1}) ${c}`));
|
|
30
|
+
const pick = await (0, cliPrompt_1.askValid)("deploy.json (number, path, or empty = only print)", "1", v => !v || !/^\d+$/.test(v) || candidates[+v - 1] ? null : "no such number");
|
|
31
|
+
file = /^\d+$/.test(pick) ? candidates[+pick - 1] : pick;
|
|
32
|
+
}
|
|
33
|
+
else
|
|
34
|
+
file = await (0, cliPrompt_1.ask)("deploy.json to put the private key into (empty = only print it)", "");
|
|
35
|
+
let cfg = null;
|
|
36
|
+
if (file) {
|
|
37
|
+
try {
|
|
38
|
+
cfg = JSON.parse(fs_1.default.readFileSync(file, "utf-8"));
|
|
39
|
+
}
|
|
40
|
+
catch (e) {
|
|
41
|
+
console.error(red(`✗ ${file}: ${e?.code === "ENOENT" ? "not found" : "not valid JSON"}`));
|
|
42
|
+
process.exit(1);
|
|
43
|
+
}
|
|
44
|
+
if (cfg.privateKey && !(await (0, cliPrompt_1.yes)(`${file} already has a privateKey — replace it?`, false)))
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const login = await (0, cliPrompt_1.askValid)("Deployer user login", cfg?.username ?? "", v => /^[A-Za-z0-9._@-]+$/.test(v) ? null : "letters, digits, '.', '_', '-', '@' only");
|
|
48
|
+
const { publicKey, privateKey } = InterceptorSignedAuth_1.InterceptorSignedAuth.generateKeyPair();
|
|
49
|
+
if (cfg) {
|
|
50
|
+
cfg.username = login;
|
|
51
|
+
cfg.privateKey = privateKey;
|
|
52
|
+
const hadPassword = "password" in cfg;
|
|
53
|
+
delete cfg.password;
|
|
54
|
+
const tmp = file + ".tmp";
|
|
55
|
+
fs_1.default.writeFileSync(tmp, JSON.stringify(cfg, null, 4) + "\n", { encoding: "utf-8", mode: 0o600 });
|
|
56
|
+
fs_1.default.chmodSync(tmp, 0o600);
|
|
57
|
+
fs_1.default.renameSync(tmp, file);
|
|
58
|
+
console.log(green(`\n✓ ${path_1.default.resolve(file)}`) + dim(` — privateKey written${hadPassword ? ", password removed" : ""} (0600)`));
|
|
59
|
+
console.log(yellow(" This file can deploy on its own: never commit or share it. In CI keep it in a secret."));
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
console.log(`\nPrivate key — put it into deploy.json as "privateKey" (and keep that file out of git):\n\n ${bold(privateKey)}\n`);
|
|
63
|
+
}
|
|
64
|
+
console.log(`\nPublic key of ${bold(login)} — for the deployer's setup.json:\n\n ${bold(publicKey)}\n`);
|
|
65
|
+
console.log(dim(" On the deployer: npx badmfck setup-config → \"set a deployer user's public key\""));
|
|
66
|
+
console.log(dim(` or by hand: { "login": "${login}", "publicKey": "${publicKey}" }`));
|
|
67
|
+
console.log(dim(" Until the deployer has this public key, this deploy.json can't deploy."));
|
|
68
|
+
}
|
|
@@ -2,6 +2,7 @@ import { BaseEndpoint } from "../BaseEndpoint";
|
|
|
2
2
|
import { HTTPRequestVO, TransferPacketVO } from "../structures/Interfaces";
|
|
3
3
|
export declare class Deployer extends BaseEndpoint {
|
|
4
4
|
ignoreInDocumentation: boolean;
|
|
5
|
+
private signed;
|
|
5
6
|
constructor();
|
|
6
7
|
file(req: HTTPRequestVO): Promise<TransferPacketVO<any>>;
|
|
7
8
|
switchSlot(req: HTTPRequestVO): Promise<TransferPacketVO<any>>;
|
|
@@ -7,8 +7,10 @@ exports.Deployer = void 0;
|
|
|
7
7
|
const BaseEndpoint_1 = require("../BaseEndpoint");
|
|
8
8
|
const DefaultErrors_1 = __importDefault(require("../structures/DefaultErrors"));
|
|
9
9
|
const DeployerService_1 = require("./DeployerService");
|
|
10
|
+
const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
|
|
10
11
|
class Deployer extends BaseEndpoint_1.BaseEndpoint {
|
|
11
12
|
ignoreInDocumentation = true;
|
|
13
|
+
signed = new InterceptorSignedAuth_1.InterceptorSignedAuth(login => DeployerService_1.REQ_DEPLOYER_PUBLIC_KEY.request(login));
|
|
12
14
|
constructor() {
|
|
13
15
|
super("pckg");
|
|
14
16
|
this.registerEndpoints([
|
|
@@ -72,20 +74,20 @@ class Deployer extends BaseEndpoint_1.BaseEndpoint {
|
|
|
72
74
|
async file(req) {
|
|
73
75
|
if (!req.files)
|
|
74
76
|
throw { ...DefaultErrors_1.default.FILE_NOT_EXISTS, details: "No files were uploaded" };
|
|
75
|
-
const result = await DeployerService_1.REQ_DEPLOYMENT_PROCEED.request({ ...req.data, files: req.files, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip });
|
|
77
|
+
const result = await DeployerService_1.REQ_DEPLOYMENT_PROCEED.request({ ...req.data, files: req.files, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip, sig: await this.signed.verify(req) });
|
|
76
78
|
return { data: result };
|
|
77
79
|
}
|
|
78
80
|
async switchSlot(req) {
|
|
79
|
-
return await DeployerService_1.REQ_DEPLOYMENT_SWITCH.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip });
|
|
81
|
+
return await DeployerService_1.REQ_DEPLOYMENT_SWITCH.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip, sig: await this.signed.verify(req) });
|
|
80
82
|
}
|
|
81
83
|
async status(req) {
|
|
82
|
-
return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip });
|
|
84
|
+
return await DeployerService_1.REQ_DEPLOYMENT_STATUS.request({ ...req.data, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip, sig: await this.signed.verify(req) });
|
|
83
85
|
}
|
|
84
86
|
async backups(req) {
|
|
85
|
-
return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip });
|
|
87
|
+
return await DeployerService_1.REQ_DEPLOYMENT_BACKUPS.request({ name: req.data.name, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip, sig: await this.signed.verify(req) });
|
|
86
88
|
}
|
|
87
89
|
async restore(req) {
|
|
88
|
-
return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip });
|
|
90
|
+
return await DeployerService_1.REQ_DEPLOYMENT_RESTORE.request({ name: req.data.name, token: req.data.token, backup: req.data.backup, auth: req.headers.authorization, authLogin: req.headers["x-deployer-login"], ip: req.ip, sig: await this.signed.verify(req) });
|
|
89
91
|
}
|
|
90
92
|
async slot(req) {
|
|
91
93
|
return await DeployerService_1.REQ_DEPLOYMENT_SLOT.request({ name: req.data.name, token: req.data.token, slot: req.data.slot });
|
|
@@ -6,11 +6,17 @@ import { ValidationModel } from "../..";
|
|
|
6
6
|
import { IDeploymentNotifier } from "./Notifier";
|
|
7
7
|
import { IError } from "../structures/Interfaces";
|
|
8
8
|
import { IPendingReview, ReviewStore } from "./ReviewStore";
|
|
9
|
+
import { ISignedAuthVerdict } from "../interceptors/InterceptorSignedAuth";
|
|
9
10
|
declare const _TSetup: {
|
|
10
11
|
readonly users: readonly [{
|
|
11
12
|
readonly login: "";
|
|
12
13
|
readonly password: "";
|
|
14
|
+
readonly $__password_optional: true;
|
|
15
|
+
readonly publicKey: "";
|
|
16
|
+
readonly $__publicKey_optional: true;
|
|
13
17
|
}];
|
|
18
|
+
readonly require_signature: false;
|
|
19
|
+
readonly $__require_signature_optional: true;
|
|
14
20
|
readonly watchdog: true;
|
|
15
21
|
readonly $__watchdog_optional: true;
|
|
16
22
|
readonly notifier: {
|
|
@@ -38,7 +44,12 @@ export declare const SETUP_MODEL: {
|
|
|
38
44
|
readonly users: readonly [{
|
|
39
45
|
readonly login: "";
|
|
40
46
|
readonly password: "";
|
|
47
|
+
readonly $__password_optional: true;
|
|
48
|
+
readonly publicKey: "";
|
|
49
|
+
readonly $__publicKey_optional: true;
|
|
41
50
|
}];
|
|
51
|
+
readonly require_signature: false;
|
|
52
|
+
readonly $__require_signature_optional: true;
|
|
42
53
|
readonly watchdog: true;
|
|
43
54
|
readonly $__watchdog_optional: true;
|
|
44
55
|
readonly notifier: {
|
|
@@ -71,6 +82,7 @@ export declare const REQ_DEPLOYMENT_PROCEED: Req<{
|
|
|
71
82
|
auth: string;
|
|
72
83
|
authLogin?: string;
|
|
73
84
|
ip?: string;
|
|
85
|
+
sig?: ISignedAuthVerdict;
|
|
74
86
|
name: string;
|
|
75
87
|
token: string;
|
|
76
88
|
files: {
|
|
@@ -81,6 +93,7 @@ export declare const REQ_DEPLOYMENT_SWITCH: Req<{
|
|
|
81
93
|
auth?: string;
|
|
82
94
|
authLogin?: string;
|
|
83
95
|
ip?: string;
|
|
96
|
+
sig?: ISignedAuthVerdict;
|
|
84
97
|
name: string;
|
|
85
98
|
token: string;
|
|
86
99
|
scheme?: "blue" | "green";
|
|
@@ -89,6 +102,7 @@ export declare const REQ_DEPLOYMENT_STATUS: Req<{
|
|
|
89
102
|
auth?: string;
|
|
90
103
|
authLogin?: string;
|
|
91
104
|
ip?: string;
|
|
105
|
+
sig?: ISignedAuthVerdict;
|
|
92
106
|
name?: string;
|
|
93
107
|
}, any>;
|
|
94
108
|
export declare const REQ_DEPLOYMENT_SLOT: Req<{
|
|
@@ -100,12 +114,15 @@ export declare const REQ_DEPLOYMENT_BACKUPS: Req<{
|
|
|
100
114
|
auth?: string;
|
|
101
115
|
authLogin?: string;
|
|
102
116
|
ip?: string;
|
|
117
|
+
sig?: ISignedAuthVerdict;
|
|
103
118
|
name: string;
|
|
104
119
|
}, any>;
|
|
120
|
+
export declare const REQ_DEPLOYER_PUBLIC_KEY: Req<string, string | null>;
|
|
105
121
|
export declare const REQ_DEPLOYMENT_RESTORE: Req<{
|
|
106
122
|
auth?: string;
|
|
107
123
|
authLogin?: string;
|
|
108
124
|
ip?: string;
|
|
125
|
+
sig?: ISignedAuthVerdict;
|
|
109
126
|
name: string;
|
|
110
127
|
token: string;
|
|
111
128
|
backup: string;
|
|
@@ -130,6 +147,7 @@ export declare class DeployerService extends BaseService {
|
|
|
130
147
|
auth?: string;
|
|
131
148
|
authLogin?: string;
|
|
132
149
|
ip?: string;
|
|
150
|
+
sig?: ISignedAuthVerdict;
|
|
133
151
|
name: string;
|
|
134
152
|
token: string;
|
|
135
153
|
files: {
|
|
@@ -143,6 +161,7 @@ export declare class DeployerService extends BaseService {
|
|
|
143
161
|
};
|
|
144
162
|
data?: undefined;
|
|
145
163
|
} | {
|
|
164
|
+
error?: undefined;
|
|
146
165
|
data: {
|
|
147
166
|
ok: boolean;
|
|
148
167
|
project: string;
|
|
@@ -151,7 +170,6 @@ export declare class DeployerService extends BaseService {
|
|
|
151
170
|
active: "blue" | "green" | null;
|
|
152
171
|
activeThisDeploy: boolean;
|
|
153
172
|
};
|
|
154
|
-
error?: undefined;
|
|
155
173
|
} | {
|
|
156
174
|
error?: undefined;
|
|
157
175
|
data: {
|
|
@@ -178,6 +196,7 @@ export declare class DeployerService extends BaseService {
|
|
|
178
196
|
auth?: string;
|
|
179
197
|
authLogin?: string;
|
|
180
198
|
ip?: string;
|
|
199
|
+
sig?: ISignedAuthVerdict;
|
|
181
200
|
name: string;
|
|
182
201
|
token: string;
|
|
183
202
|
scheme?: "blue" | "green";
|
|
@@ -201,6 +220,7 @@ export declare class DeployerService extends BaseService {
|
|
|
201
220
|
auth?: string;
|
|
202
221
|
authLogin?: string;
|
|
203
222
|
ip?: string;
|
|
223
|
+
sig?: ISignedAuthVerdict;
|
|
204
224
|
name?: string;
|
|
205
225
|
}): Promise<{
|
|
206
226
|
data?: undefined;
|
|
@@ -223,6 +243,7 @@ export declare class DeployerService extends BaseService {
|
|
|
223
243
|
auth?: string;
|
|
224
244
|
authLogin?: string;
|
|
225
245
|
ip?: string;
|
|
246
|
+
sig?: ISignedAuthVerdict;
|
|
226
247
|
name: string;
|
|
227
248
|
}): Promise<{
|
|
228
249
|
data?: undefined;
|
|
@@ -246,6 +267,7 @@ export declare class DeployerService extends BaseService {
|
|
|
246
267
|
auth?: string;
|
|
247
268
|
authLogin?: string;
|
|
248
269
|
ip?: string;
|
|
270
|
+
sig?: ISignedAuthVerdict;
|
|
249
271
|
name: string;
|
|
250
272
|
token: string;
|
|
251
273
|
backup: string;
|
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.DeployerService = exports.REQ_DEPLOYMENT_RESTORE = exports.REQ_DEPLOYMENT_BACKUPS = exports.REQ_DEPLOYMENT_SLOT = exports.REQ_DEPLOYMENT_STATUS = exports.REQ_DEPLOYMENT_SWITCH = exports.REQ_DEPLOYMENT_PROCEED = exports.SETUP_MODEL = void 0;
|
|
6
|
+
exports.DeployerService = exports.REQ_DEPLOYMENT_RESTORE = exports.REQ_DEPLOYER_PUBLIC_KEY = exports.REQ_DEPLOYMENT_BACKUPS = exports.REQ_DEPLOYMENT_SLOT = exports.REQ_DEPLOYMENT_STATUS = exports.REQ_DEPLOYMENT_SWITCH = exports.REQ_DEPLOYMENT_PROCEED = exports.SETUP_MODEL = void 0;
|
|
7
7
|
const badmfck_signal_1 = require("badmfck-signal");
|
|
8
8
|
const BaseService_1 = require("../BaseService");
|
|
9
9
|
const ConfigService_1 = require("./ConfigService");
|
|
@@ -27,8 +27,13 @@ const IpAllowList_1 = require("../helper/IpAllowList");
|
|
|
27
27
|
const _TSetup = {
|
|
28
28
|
users: [{
|
|
29
29
|
login: "",
|
|
30
|
-
password: ""
|
|
30
|
+
password: "",
|
|
31
|
+
$__password_optional: true,
|
|
32
|
+
publicKey: "",
|
|
33
|
+
$__publicKey_optional: true,
|
|
31
34
|
}],
|
|
35
|
+
require_signature: false,
|
|
36
|
+
$__require_signature_optional: true,
|
|
32
37
|
watchdog: true,
|
|
33
38
|
$__watchdog_optional: true,
|
|
34
39
|
notifier: {
|
|
@@ -57,6 +62,7 @@ exports.REQ_DEPLOYMENT_SWITCH = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYE
|
|
|
57
62
|
exports.REQ_DEPLOYMENT_STATUS = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_STATUS");
|
|
58
63
|
exports.REQ_DEPLOYMENT_SLOT = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_SLOT");
|
|
59
64
|
exports.REQ_DEPLOYMENT_BACKUPS = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_BACKUPS");
|
|
65
|
+
exports.REQ_DEPLOYER_PUBLIC_KEY = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_PUBLIC_KEY");
|
|
60
66
|
exports.REQ_DEPLOYMENT_RESTORE = new badmfck_signal_1.Req(undefined, "REQ_DEPLOYER_RESTORE");
|
|
61
67
|
class DeployerService extends BaseService_1.BaseService {
|
|
62
68
|
static MAX_HISTORY = 200;
|
|
@@ -107,6 +113,7 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
107
113
|
exports.REQ_DEPLOYMENT_SLOT.listener = async (data) => this.slotState(data);
|
|
108
114
|
exports.REQ_DEPLOYMENT_BACKUPS.listener = async (data) => this.listBackups(data);
|
|
109
115
|
exports.REQ_DEPLOYMENT_RESTORE.listener = async (data) => this.restoreBackup(data);
|
|
116
|
+
exports.REQ_DEPLOYER_PUBLIC_KEY.listener = async (login) => (this.setup?.users ?? []).find(u => u.login === login)?.publicKey || null;
|
|
110
117
|
await this._checkReviewSetup();
|
|
111
118
|
ConfigService_1.S_CONFIG_UPDATED.subscribe(() => { this._checkReviewSetup(); });
|
|
112
119
|
}
|
|
@@ -196,7 +203,7 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
196
203
|
setInterval(() => { this._reloadSetup(); }, 60_000).unref();
|
|
197
204
|
}
|
|
198
205
|
async proceed(data) {
|
|
199
|
-
const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
|
|
206
|
+
const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
|
|
200
207
|
const user = auth.user;
|
|
201
208
|
if (!user) {
|
|
202
209
|
(0, LogService_1.logError)("Deploy rejected: user auth failed");
|
|
@@ -665,7 +672,7 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
665
672
|
}
|
|
666
673
|
}
|
|
667
674
|
async switchSlot(data) {
|
|
668
|
-
const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
|
|
675
|
+
const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
|
|
669
676
|
const user = auth.user;
|
|
670
677
|
if (!user) {
|
|
671
678
|
(0, LogService_1.logError)("Switch rejected: user auth failed");
|
|
@@ -751,7 +758,7 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
751
758
|
}
|
|
752
759
|
}
|
|
753
760
|
async status(data) {
|
|
754
|
-
const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
|
|
761
|
+
const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
|
|
755
762
|
const user = auth.user;
|
|
756
763
|
if (!user) {
|
|
757
764
|
return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
|
|
@@ -785,7 +792,7 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
785
792
|
return DeployerService._isBlueGreen(found) ? dest : path_1.default.dirname(dest);
|
|
786
793
|
}
|
|
787
794
|
async listBackups(data) {
|
|
788
|
-
const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
|
|
795
|
+
const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
|
|
789
796
|
const user = auth.user;
|
|
790
797
|
if (!user) {
|
|
791
798
|
return { error: { code: 50, message: auth.error ?? "Unauthorized.", httpStatus: auth.status ?? 401 } };
|
|
@@ -816,7 +823,7 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
816
823
|
} };
|
|
817
824
|
}
|
|
818
825
|
async restoreBackup(data) {
|
|
819
|
-
const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip);
|
|
826
|
+
const auth = await this._checkUserAuth(data.auth, data.authLogin, data.ip, data.sig);
|
|
820
827
|
const user = auth.user;
|
|
821
828
|
if (!user) {
|
|
822
829
|
(0, LogService_1.logError)("Restore rejected: user auth failed");
|
|
@@ -989,11 +996,20 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
989
996
|
_warnPlaintextUsers() {
|
|
990
997
|
if (!DeployerService.buildAllowList(this.setup?.allowed_ips).list)
|
|
991
998
|
(0, LogService_1.logWarn)("Deployer: allowed_ips is not set in setup.json — deploys are accepted from any address");
|
|
992
|
-
const
|
|
999
|
+
const users = this.setup?.users ?? [];
|
|
1000
|
+
const plain = users.filter(u => u?.login && !u.publicKey && u.password && !PasswordHash_1.PasswordHash.isHash(u.password)).map(u => u.login);
|
|
1001
|
+
const keyless = users.filter(u => u?.login && !u.publicKey && !u.password).map(u => u.login);
|
|
1002
|
+
if (keyless.length)
|
|
1003
|
+
(0, LogService_1.logError)(`Deployer: ${keyless.map(l => '"' + l + '"').join(", ")} in setup.json have neither a password nor a publicKey — they can't sign in`);
|
|
1004
|
+
const passwordUsers = users.filter(u => u?.login && !u.publicKey && u.password).map(u => u.login);
|
|
1005
|
+
if (this.setup?.require_signature && passwordUsers.length)
|
|
1006
|
+
(0, LogService_1.logWarn)(`Deployer: require_signature is on — password users ${passwordUsers.map(l => '"' + l + '"').join(", ")} can't sign in until they get a publicKey`);
|
|
1007
|
+
else if (!this.setup?.require_signature && passwordUsers.length && users.some(u => u.publicKey))
|
|
1008
|
+
(0, LogService_1.logInfo)(`Deployer: ${passwordUsers.length} user(s) still sign in with a password — once all have a publicKey, set "require_signature": true`);
|
|
993
1009
|
if (plain.length)
|
|
994
1010
|
(0, LogService_1.logError)(`Deployer: password stored as plain text in setup.json for ${plain.map(l => '"' + l + '"').join(", ")} — these users are refused; store a hash instead: npx badmfck hash-password --deployer`);
|
|
995
1011
|
}
|
|
996
|
-
async _checkUserAuth(authHeader, loginHeader, ip) {
|
|
1012
|
+
async _checkUserAuth(authHeader, loginHeader, ip, sig) {
|
|
997
1013
|
if (!this._ipAllowed(ip)) {
|
|
998
1014
|
(0, LogService_1.logWarn)(`Deployer: request refused from ${ip ?? "unknown"} — not in allowed_ips`);
|
|
999
1015
|
return { error: "Forbidden.", status: 403 };
|
|
@@ -1001,10 +1017,20 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
1001
1017
|
const from = ip ?? "unknown";
|
|
1002
1018
|
const shown = (v) => JSON.stringify(v.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 64));
|
|
1003
1019
|
const refuse = (reason) => { (0, LogService_1.logWarn)(`Deployer auth failed from ${from}: ${reason}`); return {}; };
|
|
1004
|
-
if (!authHeader)
|
|
1005
|
-
return refuse("no Authorization header");
|
|
1006
1020
|
if (!this.setup)
|
|
1007
1021
|
return refuse("setup.json is not loaded");
|
|
1022
|
+
if (sig?.present) {
|
|
1023
|
+
if (sig.error || !sig.kid)
|
|
1024
|
+
return refuse(`signature refused — ${sig.error ?? "no key id"}`);
|
|
1025
|
+
const user = (this.setup.users ?? []).find(u => u.login === sig.kid);
|
|
1026
|
+
if (!user?.publicKey)
|
|
1027
|
+
return refuse(`signature by ${shown(sig.kid)}, who has no publicKey in setup.json`);
|
|
1028
|
+
return { user: user };
|
|
1029
|
+
}
|
|
1030
|
+
if (this.setup.require_signature)
|
|
1031
|
+
return refuse("unsigned request — require_signature is on in setup.json; the client needs a privateKey in deploy.json (npx badmfck deploy-key)");
|
|
1032
|
+
if (!authHeader)
|
|
1033
|
+
return refuse("no Authorization header");
|
|
1008
1034
|
const token = authHeader.split(" ").pop() ?? "";
|
|
1009
1035
|
if (!token)
|
|
1010
1036
|
return refuse("empty Authorization header");
|
|
@@ -1016,12 +1042,16 @@ class DeployerService extends BaseService_1.BaseService {
|
|
|
1016
1042
|
const user = users.find(u => u.login === login);
|
|
1017
1043
|
if (!user)
|
|
1018
1044
|
return refuse(`unknown login ${shown(login)}`);
|
|
1045
|
+
if (user.publicKey)
|
|
1046
|
+
return refuse(`${shown(login)} has a publicKey — only signed requests are accepted for them; the client needs its privateKey in deploy.json`);
|
|
1047
|
+
if (!user.password)
|
|
1048
|
+
return refuse(`${shown(login)} has neither a password nor a publicKey in setup.json`);
|
|
1019
1049
|
if (PasswordHash_1.PasswordHash.isHash(user.password))
|
|
1020
|
-
return (await PasswordHash_1.PasswordHash.verify(token, user.password)) ? { user } : refuse(`wrong password for ${shown(login)} (or the client's login/password differ from setup.json)`);
|
|
1050
|
+
return (await PasswordHash_1.PasswordHash.verify(token, user.password)) ? { user: user } : refuse(`wrong password for ${shown(login)} (or the client's login/password differ from setup.json)`);
|
|
1021
1051
|
}
|
|
1022
1052
|
let plainMatch = null;
|
|
1023
1053
|
for (const user of users) {
|
|
1024
|
-
if (
|
|
1054
|
+
if (user.publicKey || !user.password || PasswordHash_1.PasswordHash.isHash(user.password))
|
|
1025
1055
|
continue;
|
|
1026
1056
|
const expected = crypto_1.default.createHash("sha256").update(user.login + ":" + user.password).digest("hex");
|
|
1027
1057
|
if (this.tokensMatch(token, expected))
|
|
@@ -9,9 +9,9 @@ const cliCommon_1 = require("./cliCommon");
|
|
|
9
9
|
async function Restore(opt, backupName, assumeYes = false) {
|
|
10
10
|
opt = await (0, resolveConfig_1.resolveConfig)(opt);
|
|
11
11
|
const { red, yellow, green, dim, bold } = (0, cliCommon_1.palette)();
|
|
12
|
-
const headers = (0, cliCommon_1.deployerHeaders)(opt);
|
|
13
12
|
const fail = (msg) => { console.error(red(bold("✗ ")) + msg); process.exit(1); };
|
|
14
|
-
const
|
|
13
|
+
const listUrl = (0, cliCommon_1.deployerUrl)(opt, "backups"), listBody = { name: opt.name };
|
|
14
|
+
const lr = await __1.Http.post(listUrl, listBody, { headers: (0, cliCommon_1.deployerHeaders)(opt, listUrl, listBody), timeoutMs: 30000, retry: { enabled: false } });
|
|
15
15
|
const lerr = (0, cliCommon_1.responseError)(lr);
|
|
16
16
|
if (lerr)
|
|
17
17
|
fail("Cannot list backups: " + lerr);
|
|
@@ -64,7 +64,8 @@ async function Restore(opt, backupName, assumeYes = false) {
|
|
|
64
64
|
rl?.close();
|
|
65
65
|
}
|
|
66
66
|
console.log(dim("\nRestoring…"));
|
|
67
|
-
const
|
|
67
|
+
const restoreUrl = (0, cliCommon_1.deployerUrl)(opt, "restore"), restoreBody = { name: opt.name, token: opt.token, backup: chosen.name };
|
|
68
|
+
const rr = await __1.Http.post(restoreUrl, restoreBody, { headers: (0, cliCommon_1.deployerHeaders)(opt, restoreUrl, restoreBody), timeoutMs: 10 * 60 * 1000, retry: { enabled: false } });
|
|
68
69
|
const rerr = (0, cliCommon_1.responseError)(rr);
|
|
69
70
|
if (rerr)
|
|
70
71
|
fail("Restore failed: " + rerr);
|
|
@@ -54,8 +54,15 @@ async function SetupConfigWizard(target) {
|
|
|
54
54
|
console.log("\n" + bold("Deployer users") + dim(" (in deploy.json: username + password)"));
|
|
55
55
|
if (!doc.users.length)
|
|
56
56
|
console.log(red(" none — nobody can deploy"));
|
|
57
|
-
for (const u of doc.users)
|
|
58
|
-
|
|
57
|
+
for (const u of doc.users) {
|
|
58
|
+
const state = u.publicKey ? green("signing key")
|
|
59
|
+
: !u.password ? red("no password or key — can't sign in")
|
|
60
|
+
: doc.require_signature ? yellow("password — refused, require_signature is on")
|
|
61
|
+
: PasswordHash_1.PasswordHash.isHash(u.password) ? dim("hashed password")
|
|
62
|
+
: red("PLAIN-TEXT password — refused, set a new one or run migrate-configs");
|
|
63
|
+
console.log(` ${String(u.login).padEnd(20)} ${state}`);
|
|
64
|
+
}
|
|
65
|
+
console.log(bold("Signed requests only") + " " + (doc.require_signature ? green("yes") : dim("no — password users still accepted")));
|
|
59
66
|
console.log(bold("Reviewers"));
|
|
60
67
|
if (!doc.reviewers?.length)
|
|
61
68
|
console.log(dim(" none"));
|
|
@@ -120,6 +127,35 @@ async function SetupConfigWizard(target) {
|
|
|
120
127
|
console.log(green(` ✓ ${login} removed`));
|
|
121
128
|
changed = true;
|
|
122
129
|
} },
|
|
130
|
+
"k": { title: "set a deployer user's public key (signed deploys)", run: async () => {
|
|
131
|
+
const u = user(await (0, cliPrompt_1.askValid)(" login", "", v => user(v) ? null : "no such user — add the user first"));
|
|
132
|
+
const key = await (0, cliPrompt_1.askValid)(" public key from `npx badmfck deploy-key` (base64)", "", v => {
|
|
133
|
+
try {
|
|
134
|
+
crypto_1.default.createPublicKey({ key: Buffer.from(v, "base64"), format: "der", type: "spki" });
|
|
135
|
+
return /^MCowBQYDK2VwAyEA/.test(v) ? null : "not an Ed25519 public key";
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return "not a public key (base64 SPKI)";
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
u.publicKey = key;
|
|
142
|
+
if (u.password) {
|
|
143
|
+
delete u.password;
|
|
144
|
+
console.log(dim(" password removed — the user signs in with the key only"));
|
|
145
|
+
}
|
|
146
|
+
clientsToUpdate.delete(u.login);
|
|
147
|
+
console.log(green(` ✓ ${u.login} signs requests with their key`));
|
|
148
|
+
changed = true;
|
|
149
|
+
} },
|
|
150
|
+
"r": { title: "require signed requests from everyone (on/off)", run: async () => {
|
|
151
|
+
const passwordUsers = doc.users.filter((x) => !x.publicKey).map((x) => x.login);
|
|
152
|
+
if (!doc.require_signature && passwordUsers.length)
|
|
153
|
+
console.log(yellow(` ⚠ ${passwordUsers.join(", ")} have no key yet — they can't deploy once this is on.`));
|
|
154
|
+
doc.require_signature = await (0, cliPrompt_1.yes)(" only signed requests?", !doc.require_signature);
|
|
155
|
+
if (!doc.require_signature)
|
|
156
|
+
delete doc.require_signature;
|
|
157
|
+
changed = true;
|
|
158
|
+
} },
|
|
123
159
|
"5": { title: "add a reviewer", run: async () => {
|
|
124
160
|
const login = await (0, cliPrompt_1.askValid)(" login", "", v => !v ? "required" : reviewer(v) ? "already exists" : validLogin(v));
|
|
125
161
|
const email = await (0, cliPrompt_1.askValid)(" email (gets the review links)", "", v => /^[^\s@]+@[^\s@]+$/.test(v) ? null : "an email address");
|
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
3
|
exports.Status = Status;
|
|
7
|
-
const crypto_1 = __importDefault(require("crypto"));
|
|
8
4
|
const __1 = require("../..");
|
|
9
5
|
const resolveConfig_1 = require("./resolveConfig");
|
|
6
|
+
const cliCommon_1 = require("./cliCommon");
|
|
10
7
|
async function Status(opt) {
|
|
11
8
|
opt = await (0, resolveConfig_1.resolveConfig)(opt);
|
|
12
9
|
let statusUrl;
|
|
@@ -16,9 +13,9 @@ async function Status(opt) {
|
|
|
16
13
|
statusUrl = opt.switch_host.replace(/\/switch\/?$/, "/status");
|
|
17
14
|
else
|
|
18
15
|
throw new Error(`Cannot derive status URL from host "${opt.host}" — make sure "host" ends with /add.`);
|
|
19
|
-
const
|
|
20
|
-
const response = await __1.Http.post(statusUrl,
|
|
21
|
-
headers:
|
|
16
|
+
const requestBody = { name: opt.name };
|
|
17
|
+
const response = await __1.Http.post(statusUrl, requestBody, {
|
|
18
|
+
headers: (0, cliCommon_1.deployerHeaders)(opt, statusUrl, requestBody),
|
|
22
19
|
timeoutMs: 15 * 1000,
|
|
23
20
|
retry: { enabled: false },
|
|
24
21
|
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function Wizards(): Promise<void>;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Wizards = Wizards;
|
|
4
|
+
const process_1 = require("process");
|
|
5
|
+
const cliCommon_1 = require("./cliCommon");
|
|
6
|
+
const cliPrompt_1 = require("./cliPrompt");
|
|
7
|
+
const HashPassword_1 = require("./HashPassword");
|
|
8
|
+
const ProjectConfigWizard_1 = require("./ProjectConfigWizard");
|
|
9
|
+
const AccessConfigWizard_1 = require("./AccessConfigWizard");
|
|
10
|
+
const SetupConfigWizard_1 = require("./SetupConfigWizard");
|
|
11
|
+
const MigrateConfigsWizard_1 = require("./MigrateConfigsWizard");
|
|
12
|
+
const DeployKeyWizard_1 = require("./DeployKeyWizard");
|
|
13
|
+
const WIZARDS = [
|
|
14
|
+
{ command: "badmfck project-config", title: "New project config for the deployer",
|
|
15
|
+
what: "Asks for everything a project needs (folder, token, deploy steps, config values, blue-green, nginx, secrets file, review) and writes the deployer's project config plus a matching deploy.json.",
|
|
16
|
+
where: "anywhere; copy the config to the deployer's projects folder",
|
|
17
|
+
run: () => (0, ProjectConfigWizard_1.ProjectConfigWizard)() },
|
|
18
|
+
{ command: "badmfck setup-config [file|folder]", title: "Deployer users, reviewers and allowed IPs",
|
|
19
|
+
what: "Edits the deployer's setup.json from a menu: add, rename or remove deployer users, change passwords or set their public signing keys, require signed requests, manage reviewers, allowed addresses and the review page URL.",
|
|
20
|
+
where: "on the deployer server",
|
|
21
|
+
run: () => (0, SetupConfigWizard_1.SetupConfigWizard)() },
|
|
22
|
+
{ command: "badmfck deploy-key [deploy.json]", title: "Signing key for deploys",
|
|
23
|
+
what: "Generates an Ed25519 key pair: writes the private key into deploy.json (instead of the password) and prints the public key for the deployer's setup.json. Signed requests can't be replayed or altered.",
|
|
24
|
+
where: "in the project folder you deploy from",
|
|
25
|
+
run: () => (0, DeployKeyWizard_1.DeployKeyWizard)() },
|
|
26
|
+
{ command: "badmfck access-config [file]", title: "Monitor and documentation access",
|
|
27
|
+
what: "Creates or edits an app's access.json: monitor users with roles and passwords, documentation users, the monitor's allowed addresses. Finds the file named in the project's code.",
|
|
28
|
+
where: "on the app server, or in the project folder",
|
|
29
|
+
run: () => (0, AccessConfigWizard_1.AccessConfigWizard)() },
|
|
30
|
+
{ command: "badmfck migrate-configs [folder] [--yes]", title: "Upgrade old configs to hashed secrets",
|
|
31
|
+
what: "Hashes the plain passwords and tokens in old setup.json, project configs and access.json files, computing each hash from the value already there; clients keep their deploy.json.",
|
|
32
|
+
where: "on the servers, right after upgrading to 6.x",
|
|
33
|
+
run: () => (0, MigrateConfigsWizard_1.MigrateConfigsWizard)() },
|
|
34
|
+
{ command: "badmfck project-token", title: "New project token",
|
|
35
|
+
what: "Generates a random project token: the token itself for deploy.json and its hash for the project config.",
|
|
36
|
+
where: "anywhere",
|
|
37
|
+
run: () => (0, HashPassword_1.ProjectToken)("generate") },
|
|
38
|
+
{ command: "badmfck project-token --hash", title: "Hash an existing project token",
|
|
39
|
+
what: "Asks for a token you already use and prints its hash for the project config.",
|
|
40
|
+
where: "anywhere",
|
|
41
|
+
run: () => (0, HashPassword_1.ProjectToken)("hash") },
|
|
42
|
+
{ command: "badmfck hash-password", title: "Hash a monitor password",
|
|
43
|
+
what: "Prints a monitor user entry with a hashed password, to paste into access.json or the access option.",
|
|
44
|
+
where: "anywhere",
|
|
45
|
+
run: () => (0, HashPassword_1.HashPassword)("monitor") },
|
|
46
|
+
{ command: "badmfck hash-password --deployer", title: "Hash a deployer password",
|
|
47
|
+
what: "Prints a deployer user entry with a hashed password, to paste into setup.json.",
|
|
48
|
+
where: "anywhere",
|
|
49
|
+
run: () => (0, HashPassword_1.HashPassword)("deployer") },
|
|
50
|
+
];
|
|
51
|
+
async function Wizards() {
|
|
52
|
+
const { red, dim, bold, green } = (0, cliCommon_1.palette)();
|
|
53
|
+
if (!process_1.stdin.isTTY) {
|
|
54
|
+
console.error(red("✗ wizards is interactive — run it in a terminal. To script, call a command directly (see `badmfck` for the list)."));
|
|
55
|
+
process.exit(1);
|
|
56
|
+
}
|
|
57
|
+
for (;;) {
|
|
58
|
+
console.log(bold("\nbadmfck wizards\n"));
|
|
59
|
+
WIZARDS.forEach((w, i) => {
|
|
60
|
+
console.log(` ${bold(String(i + 1).padStart(2) + ")")} ${bold(w.title)}`);
|
|
61
|
+
console.log(` ${w.what}`);
|
|
62
|
+
console.log(dim(` where: ${w.where} · directly: npx ${w.command}`));
|
|
63
|
+
});
|
|
64
|
+
console.log(`\n ${bold("q)")} quit`);
|
|
65
|
+
const choice = (await (0, cliPrompt_1.ask)("\nChoose", "")).toLowerCase();
|
|
66
|
+
if (choice === "q" || choice === "")
|
|
67
|
+
return;
|
|
68
|
+
const w = WIZARDS[Number(choice) - 1];
|
|
69
|
+
if (!/^\d+$/.test(choice) || !w) {
|
|
70
|
+
console.log(red(" ✗ choose a number or q"));
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
console.log(green(`\n→ ${w.title}`) + dim(` (next time: npx ${w.command})`));
|
|
74
|
+
await w.run();
|
|
75
|
+
if (!(await (0, cliPrompt_1.yes)("\nBack to the list of wizards?", false)))
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -12,8 +12,11 @@ const ProjectConfigWizard_1 = require("./ProjectConfigWizard");
|
|
|
12
12
|
const AccessConfigWizard_1 = require("./AccessConfigWizard");
|
|
13
13
|
const MigrateConfigsWizard_1 = require("./MigrateConfigsWizard");
|
|
14
14
|
const SetupConfigWizard_1 = require("./SetupConfigWizard");
|
|
15
|
+
const Wizards_1 = require("./Wizards");
|
|
16
|
+
const DeployKeyWizard_1 = require("./DeployKeyWizard");
|
|
15
17
|
function usage() {
|
|
16
18
|
console.error("Usage:");
|
|
19
|
+
console.error(" badmfck wizards — list every interactive wizard and run one");
|
|
17
20
|
console.error(" badmfck deploy [config.json] — build + upload the current project");
|
|
18
21
|
console.error(" badmfck activate [config.json] [blue|green] — switch blue-green slot (omit slot for lastDeployed)");
|
|
19
22
|
console.error(" badmfck status [config.json] — show active / last deployed slot");
|
|
@@ -25,6 +28,7 @@ function usage() {
|
|
|
25
28
|
console.error(" badmfck access-config [file] — create or edit access.json (found in the project's code if omitted)");
|
|
26
29
|
console.error(" badmfck migrate-configs [folder] [--yes] — hash the secrets of old setup.json, project configs and access.json files");
|
|
27
30
|
console.error(" badmfck setup-config [file|folder] — edit the deployer's setup.json: users, reviewers, allowed IPs");
|
|
31
|
+
console.error(" badmfck deploy-key [deploy.json] — a signing key pair: private key into deploy.json, public key for setup.json");
|
|
28
32
|
console.error("");
|
|
29
33
|
console.error("Config path is optional (auto-discovers deploy/ folder → deploy.json when omitted).");
|
|
30
34
|
console.error("Via npm, prefix args with -- e.g. npm run deploy -- deploy/custom.json");
|
|
@@ -111,6 +115,22 @@ async function main() {
|
|
|
111
115
|
await (0, HashPassword_1.HashPassword)(rest.includes("--deployer") ? "deployer" : "monitor");
|
|
112
116
|
break;
|
|
113
117
|
}
|
|
118
|
+
case "wizards": {
|
|
119
|
+
if (rest.length) {
|
|
120
|
+
console.error("wizards takes no arguments.");
|
|
121
|
+
process.exit(1);
|
|
122
|
+
}
|
|
123
|
+
await (0, Wizards_1.Wizards)();
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
case "deploy-key": {
|
|
127
|
+
if (rest.length > 1) {
|
|
128
|
+
console.error("Usage: badmfck deploy-key [deploy.json]");
|
|
129
|
+
process.exit(1);
|
|
130
|
+
}
|
|
131
|
+
await (0, DeployKeyWizard_1.DeployKeyWizard)(rest[0]);
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
114
134
|
case "setup-config": {
|
|
115
135
|
if (rest.length > 1) {
|
|
116
136
|
console.error("Usage: badmfck setup-config [file|folder]");
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { IDeployerConfig } from "./resolveConfig";
|
|
2
2
|
export declare function deployerUrl(opt: IDeployerConfig, endpoint: string): string;
|
|
3
3
|
export declare function authHeader(opt: IDeployerConfig): string;
|
|
4
|
-
export declare function deployerHeaders(opt: IDeployerConfig): Record<string, string>;
|
|
4
|
+
export declare function deployerHeaders(opt: IDeployerConfig, url: string, data: unknown, files?: Record<string, string>): Record<string, string>;
|
|
5
5
|
export declare function responseError(r: any): string | null;
|
|
6
6
|
export declare function palette(): {
|
|
7
7
|
red: (t: string) => string;
|
|
@@ -12,6 +12,7 @@ exports.fmtDate = fmtDate;
|
|
|
12
12
|
exports.fmtSize = fmtSize;
|
|
13
13
|
const crypto_1 = __importDefault(require("crypto"));
|
|
14
14
|
const __1 = require("../..");
|
|
15
|
+
const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
|
|
15
16
|
function deployerUrl(opt, endpoint) {
|
|
16
17
|
if (/\/add\/?$/.test(opt.host))
|
|
17
18
|
return opt.host.replace(/\/add\/?$/, "/" + endpoint);
|
|
@@ -22,8 +23,11 @@ function deployerUrl(opt, endpoint) {
|
|
|
22
23
|
function authHeader(opt) {
|
|
23
24
|
return "Bearer " + crypto_1.default.createHash("sha256").update(opt.username + ":" + opt.password).digest("hex");
|
|
24
25
|
}
|
|
25
|
-
function deployerHeaders(opt) {
|
|
26
|
-
|
|
26
|
+
function deployerHeaders(opt, url, data, files) {
|
|
27
|
+
const authorization = opt.privateKey
|
|
28
|
+
? InterceptorSignedAuth_1.InterceptorSignedAuth.sign({ privateKey: opt.privateKey, kid: String(opt.username), method: "POST", url, data, files })
|
|
29
|
+
: authHeader(opt);
|
|
30
|
+
return { authorization, "x-deployer-login": String(opt.username) };
|
|
27
31
|
}
|
|
28
32
|
function responseError(r) {
|
|
29
33
|
const body = r?.ok ? r?.data : r?.error;
|
|
@@ -9,11 +9,22 @@ const fs_1 = __importDefault(require("fs"));
|
|
|
9
9
|
const path_1 = __importDefault(require("path"));
|
|
10
10
|
const promises_1 = require("readline/promises");
|
|
11
11
|
const process_1 = require("process");
|
|
12
|
+
const InterceptorSignedAuth_1 = require("../interceptors/InterceptorSignedAuth");
|
|
12
13
|
function validateConfig(cfg) {
|
|
13
14
|
if (!cfg || typeof cfg !== "object")
|
|
14
15
|
return "not an object";
|
|
15
|
-
if (!cfg.name || !cfg.token || !cfg.host || !cfg.username
|
|
16
|
-
return "missing one of: name, token, host, username
|
|
16
|
+
if (!cfg.name || !cfg.token || !cfg.host || !cfg.username)
|
|
17
|
+
return "missing one of: name, token, host, username";
|
|
18
|
+
if (!cfg.password && !cfg.privateKey)
|
|
19
|
+
return "missing credentials: privateKey (signed requests) or password";
|
|
20
|
+
if (cfg.privateKey) {
|
|
21
|
+
try {
|
|
22
|
+
InterceptorSignedAuth_1.InterceptorSignedAuth.publicKeyOf(cfg.privateKey);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return "privateKey is not a valid Ed25519 key (base64 PKCS#8)";
|
|
26
|
+
}
|
|
27
|
+
}
|
|
17
28
|
if (cfg.includes) {
|
|
18
29
|
if (!Array.isArray(cfg.includes))
|
|
19
30
|
return "includes must be an array";
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { IInterceptor } from "../APIService";
|
|
2
|
+
import { HTTPRequestVO } from "../structures/Interfaces";
|
|
3
|
+
export interface ISignedAuthResult {
|
|
4
|
+
kid: string;
|
|
5
|
+
}
|
|
6
|
+
export interface ISignedAuthVerdict {
|
|
7
|
+
present: boolean;
|
|
8
|
+
kid?: string;
|
|
9
|
+
error?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare class InterceptorSignedAuth implements IInterceptor<ISignedAuthResult> {
|
|
12
|
+
private resolveKey;
|
|
13
|
+
static TS_PAST_SEC: number;
|
|
14
|
+
static TS_FUTURE_SEC: number;
|
|
15
|
+
private static readonly NONCE_MAX;
|
|
16
|
+
private nonceSeen;
|
|
17
|
+
constructor(resolveKey: (kid: string) => Promise<string | null | undefined> | string | null | undefined);
|
|
18
|
+
intercept(req: HTTPRequestVO): Promise<ISignedAuthResult>;
|
|
19
|
+
verify(req: HTTPRequestVO): Promise<ISignedAuthVerdict>;
|
|
20
|
+
private purge;
|
|
21
|
+
private static parseHeader;
|
|
22
|
+
private static hashUpload;
|
|
23
|
+
static pathOf(url: string): string;
|
|
24
|
+
static message(method: string, path: string, ts: string, nonce: string, data: unknown, files: Record<string, string>): string;
|
|
25
|
+
static sha256File(file: string): Promise<string>;
|
|
26
|
+
static generateKeyPair(): {
|
|
27
|
+
publicKey: string;
|
|
28
|
+
privateKey: string;
|
|
29
|
+
};
|
|
30
|
+
static publicKeyOf(privateKey: string): string;
|
|
31
|
+
static sign(o: {
|
|
32
|
+
privateKey: string;
|
|
33
|
+
kid: string;
|
|
34
|
+
method: string;
|
|
35
|
+
url: string;
|
|
36
|
+
data?: unknown;
|
|
37
|
+
files?: Record<string, string>;
|
|
38
|
+
}): string;
|
|
39
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
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.InterceptorSignedAuth = void 0;
|
|
7
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
8
|
+
const fs_1 = __importDefault(require("fs"));
|
|
9
|
+
const JSONStableStringify_1 = require("../helper/JSONStableStringify");
|
|
10
|
+
const DefaultErrors_1 = __importDefault(require("../structures/DefaultErrors"));
|
|
11
|
+
const SCHEME = "signature ";
|
|
12
|
+
const VERSION = "badmfck-sig-v1";
|
|
13
|
+
class InterceptorSignedAuth {
|
|
14
|
+
resolveKey;
|
|
15
|
+
static TS_PAST_SEC = 300;
|
|
16
|
+
static TS_FUTURE_SEC = 60;
|
|
17
|
+
static NONCE_MAX = 100_000;
|
|
18
|
+
nonceSeen = new Map();
|
|
19
|
+
constructor(resolveKey) {
|
|
20
|
+
this.resolveKey = resolveKey;
|
|
21
|
+
}
|
|
22
|
+
async intercept(req) {
|
|
23
|
+
const v = await this.verify(req);
|
|
24
|
+
if (!v.kid)
|
|
25
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: v.present ? "Invalid signature" : "Signature required" };
|
|
26
|
+
return { kid: v.kid };
|
|
27
|
+
}
|
|
28
|
+
async verify(req) {
|
|
29
|
+
const header = String(req.headers?.["authorization"] ?? "");
|
|
30
|
+
if (!header.toLowerCase().startsWith(SCHEME))
|
|
31
|
+
return { present: false };
|
|
32
|
+
const p = InterceptorSignedAuth.parseHeader(header.slice(SCHEME.length));
|
|
33
|
+
if (!p.kid || !p.ts || !p.nonce || !p.sig)
|
|
34
|
+
return { present: true, error: "malformed Signature header" };
|
|
35
|
+
if (!/^[A-Za-z0-9._@-]{1,128}$/.test(p.kid))
|
|
36
|
+
return { present: true, error: "malformed key id" };
|
|
37
|
+
if (!/^[A-Za-z0-9_-]{16,128}$/.test(p.nonce))
|
|
38
|
+
return { present: true, error: "malformed nonce" };
|
|
39
|
+
if (!/^\d{13}$/.test(p.ts))
|
|
40
|
+
return { present: true, error: "ts must be epoch milliseconds (13 digits)" };
|
|
41
|
+
const now = Date.now();
|
|
42
|
+
const delta = Math.round((Number(p.ts) - now) / 1000);
|
|
43
|
+
if (delta < -InterceptorSignedAuth.TS_PAST_SEC || delta > InterceptorSignedAuth.TS_FUTURE_SEC)
|
|
44
|
+
return { present: true, error: `ts out of window: off by ${delta}s — check the client's clock` };
|
|
45
|
+
this.purge(now);
|
|
46
|
+
const nonceKey = p.kid + ":" + p.nonce;
|
|
47
|
+
if (this.nonceSeen.has(nonceKey))
|
|
48
|
+
return { present: true, error: "nonce already used (replayed request)" };
|
|
49
|
+
const publicKey = await this.resolveKey(p.kid);
|
|
50
|
+
if (!publicKey)
|
|
51
|
+
return { present: true, error: `unknown key id "${p.kid}"` };
|
|
52
|
+
let key;
|
|
53
|
+
try {
|
|
54
|
+
key = crypto_1.default.createPublicKey({ key: Buffer.from(publicKey, "base64"), format: "der", type: "spki" });
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return { present: true, error: `the public key of "${p.kid}" is not a valid Ed25519 key` };
|
|
58
|
+
}
|
|
59
|
+
const raw = req.raw ?? {};
|
|
60
|
+
const path = InterceptorSignedAuth.pathOf(raw.originalUrl ?? raw.url ?? req.endpoint ?? "");
|
|
61
|
+
const files = {};
|
|
62
|
+
for (const [field, f] of Object.entries((raw.files ?? {}))) {
|
|
63
|
+
const one = Array.isArray(f) ? f[0] : f;
|
|
64
|
+
files[field] = await InterceptorSignedAuth.hashUpload(one);
|
|
65
|
+
}
|
|
66
|
+
const data = { ...(raw.body ?? {}), ...(raw.query ?? {}) };
|
|
67
|
+
const message = InterceptorSignedAuth.message(String(req.method ?? raw.method ?? "").toUpperCase(), path, p.ts, p.nonce, data, files);
|
|
68
|
+
let ok = false;
|
|
69
|
+
try {
|
|
70
|
+
ok = crypto_1.default.verify(null, Buffer.from(message), key, Buffer.from(p.sig, "base64"));
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
ok = false;
|
|
74
|
+
}
|
|
75
|
+
if (!ok)
|
|
76
|
+
return { present: true, error: "signature does not match (wrong key, or the request was changed)" };
|
|
77
|
+
this.nonceSeen.set(nonceKey, now + (InterceptorSignedAuth.TS_PAST_SEC + InterceptorSignedAuth.TS_FUTURE_SEC) * 1000);
|
|
78
|
+
return { present: true, kid: p.kid };
|
|
79
|
+
}
|
|
80
|
+
purge(now) {
|
|
81
|
+
for (const [k, exp] of this.nonceSeen) {
|
|
82
|
+
if (exp > now)
|
|
83
|
+
break;
|
|
84
|
+
this.nonceSeen.delete(k);
|
|
85
|
+
}
|
|
86
|
+
while (this.nonceSeen.size > InterceptorSignedAuth.NONCE_MAX) {
|
|
87
|
+
const oldest = this.nonceSeen.keys().next().value;
|
|
88
|
+
if (oldest === undefined)
|
|
89
|
+
break;
|
|
90
|
+
this.nonceSeen.delete(oldest);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
static parseHeader(s) {
|
|
94
|
+
const out = {};
|
|
95
|
+
for (const part of s.split(",")) {
|
|
96
|
+
const eq = part.indexOf("=");
|
|
97
|
+
if (eq < 1)
|
|
98
|
+
continue;
|
|
99
|
+
let v = part.slice(eq + 1).trim();
|
|
100
|
+
if (v.length > 1 && ((v[0] === '"' && v.endsWith('"')) || (v[0] === "'" && v.endsWith("'"))))
|
|
101
|
+
v = v.slice(1, -1);
|
|
102
|
+
out[part.slice(0, eq).trim().toLowerCase()] = v;
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
static async hashUpload(f) {
|
|
107
|
+
if (f?.tempFilePath)
|
|
108
|
+
return InterceptorSignedAuth.sha256File(f.tempFilePath);
|
|
109
|
+
return crypto_1.default.createHash("sha256").update(f?.data ?? Buffer.alloc(0)).digest("hex");
|
|
110
|
+
}
|
|
111
|
+
static pathOf(url) {
|
|
112
|
+
try {
|
|
113
|
+
return new URL(url, "http://localhost").pathname;
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return url;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
static message(method, path, ts, nonce, data, files) {
|
|
120
|
+
const payload = (0, JSONStableStringify_1.JSONStableStringify)(JSON.parse(JSON.stringify({ data: data ?? {}, files })));
|
|
121
|
+
const digest = crypto_1.default.createHash("sha256").update(payload).digest("hex");
|
|
122
|
+
return [VERSION, method, path, ts, nonce, digest].join("\n");
|
|
123
|
+
}
|
|
124
|
+
static sha256File(file) {
|
|
125
|
+
return new Promise((resolve, reject) => {
|
|
126
|
+
const h = crypto_1.default.createHash("sha256");
|
|
127
|
+
fs_1.default.createReadStream(file).on("data", d => h.update(d)).on("error", reject).on("end", () => resolve(h.digest("hex")));
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
static generateKeyPair() {
|
|
131
|
+
const { publicKey, privateKey } = crypto_1.default.generateKeyPairSync("ed25519");
|
|
132
|
+
return {
|
|
133
|
+
publicKey: publicKey.export({ format: "der", type: "spki" }).toString("base64"),
|
|
134
|
+
privateKey: privateKey.export({ format: "der", type: "pkcs8" }).toString("base64"),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
static publicKeyOf(privateKey) {
|
|
138
|
+
const key = crypto_1.default.createPrivateKey({ key: Buffer.from(privateKey, "base64"), format: "der", type: "pkcs8" });
|
|
139
|
+
return crypto_1.default.createPublicKey(key).export({ format: "der", type: "spki" }).toString("base64");
|
|
140
|
+
}
|
|
141
|
+
static sign(o) {
|
|
142
|
+
const key = crypto_1.default.createPrivateKey({ key: Buffer.from(o.privateKey, "base64"), format: "der", type: "pkcs8" });
|
|
143
|
+
const ts = String(Date.now());
|
|
144
|
+
const nonce = crypto_1.default.randomBytes(18).toString("base64url");
|
|
145
|
+
const message = InterceptorSignedAuth.message(o.method.toUpperCase(), InterceptorSignedAuth.pathOf(o.url), ts, nonce, o.data ?? {}, o.files ?? {});
|
|
146
|
+
const sig = crypto_1.default.sign(null, Buffer.from(message), key).toString("base64");
|
|
147
|
+
return `Signature kid="${o.kid}", ts="${ts}", nonce="${nonce}", sig="${sig}"`;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
exports.InterceptorSignedAuth = InterceptorSignedAuth;
|
package/dist/index.d.ts
CHANGED
|
@@ -33,3 +33,5 @@ export { default as DefaultErrors } from "./apiServer/structures/DefaultErrors";
|
|
|
33
33
|
export type { HTTPRequestVO, TransferPacketVO, IError } from "./apiServer/structures/Interfaces";
|
|
34
34
|
export { logInfo, logWarn, logError, logCrit } from "./apiServer/LogService";
|
|
35
35
|
export type { IAccess } from "./apiServer/monitor/AccessStore";
|
|
36
|
+
export { InterceptorSignedAuth } from "./apiServer/interceptors/InterceptorSignedAuth";
|
|
37
|
+
export type { ISignedAuthResult, ISignedAuthVerdict } from "./apiServer/interceptors/InterceptorSignedAuth";
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.logCrit = exports.logError = exports.logWarn = exports.logInfo = exports.DefaultErrors = exports.BaseEndpoint = exports.getDefaultOptions = exports.WS_CLOSE_INTERNAL = exports.WS_CLOSE_RATE_LIMIT = exports.WS_CLOSE_AUTH_TIMEOUT = exports.WS_CLOSE_UNAUTHORIZED = exports.S_WS_ON_CLOSE = exports.S_WS_ON_MESSAGE = exports.S_WS_ON_CONNECTED = exports.WebSocketConnection = exports.WebSocketServer = exports.REQ_WS_SERVER = exports.S_BLUEGREEN_STATE_CHANGED = exports.ProcessMonitor = exports.S_MONITOR_RESTART_REQUESTED = exports.S_MONITOR_REGISTRATE_ACTION = exports.InterceptorPayAuth = exports.Activate = exports.Deploy = exports.DBService = exports.ExternalService = exports.ErrorUtils = exports.DataProvider = exports.LogService = exports.Validator = exports.TimeframeService = exports.LocalRequest = exports.Initializer = exports.APIService = exports.JSONStableStringify = exports.YYYYMMDDHH = exports.UID = exports.ZipUtils = exports.Http = exports.MicroserviceClient = exports.MicroserviceHost = void 0;
|
|
6
|
+
exports.InterceptorSignedAuth = exports.logCrit = exports.logError = exports.logWarn = exports.logInfo = exports.DefaultErrors = exports.BaseEndpoint = exports.getDefaultOptions = exports.WS_CLOSE_INTERNAL = exports.WS_CLOSE_RATE_LIMIT = exports.WS_CLOSE_AUTH_TIMEOUT = exports.WS_CLOSE_UNAUTHORIZED = exports.S_WS_ON_CLOSE = exports.S_WS_ON_MESSAGE = exports.S_WS_ON_CONNECTED = exports.WebSocketConnection = exports.WebSocketServer = exports.REQ_WS_SERVER = exports.S_BLUEGREEN_STATE_CHANGED = exports.ProcessMonitor = exports.S_MONITOR_RESTART_REQUESTED = exports.S_MONITOR_REGISTRATE_ACTION = exports.InterceptorPayAuth = exports.Activate = exports.Deploy = exports.DBService = exports.ExternalService = exports.ErrorUtils = exports.DataProvider = exports.LogService = exports.Validator = exports.TimeframeService = exports.LocalRequest = exports.Initializer = exports.APIService = exports.JSONStableStringify = exports.YYYYMMDDHH = exports.UID = exports.ZipUtils = exports.Http = exports.MicroserviceClient = exports.MicroserviceHost = void 0;
|
|
7
7
|
const APIService_1 = require("./apiServer/APIService");
|
|
8
8
|
Object.defineProperty(exports, "APIService", { enumerable: true, get: function () { return APIService_1.APIService; } });
|
|
9
9
|
Object.defineProperty(exports, "Initializer", { enumerable: true, get: function () { return APIService_1.Initializer; } });
|
|
@@ -73,3 +73,5 @@ Object.defineProperty(exports, "logInfo", { enumerable: true, get: function () {
|
|
|
73
73
|
Object.defineProperty(exports, "logWarn", { enumerable: true, get: function () { return LogService_2.logWarn; } });
|
|
74
74
|
Object.defineProperty(exports, "logError", { enumerable: true, get: function () { return LogService_2.logError; } });
|
|
75
75
|
Object.defineProperty(exports, "logCrit", { enumerable: true, get: function () { return LogService_2.logCrit; } });
|
|
76
|
+
var InterceptorSignedAuth_1 = require("./apiServer/interceptors/InterceptorSignedAuth");
|
|
77
|
+
Object.defineProperty(exports, "InterceptorSignedAuth", { enumerable: true, get: function () { return InterceptorSignedAuth_1.InterceptorSignedAuth; } });
|