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 +135 -3
- package/dist/apiServer/APIService.js +2 -0
- package/dist/apiServer/deployment/ConfigService.d.ts +24 -0
- package/dist/apiServer/deployment/ConfigService.js +15 -0
- package/dist/apiServer/deployment/Deploy.js +18 -0
- package/dist/apiServer/deployment/DeployerService.d.ts +46 -4
- package/dist/apiServer/deployment/DeployerService.js +327 -11
- package/dist/apiServer/deployment/Notifier.d.ts +14 -0
- package/dist/apiServer/deployment/Notifier.js +22 -0
- package/dist/apiServer/deployment/ReviewStore.d.ts +62 -0
- package/dist/apiServer/deployment/ReviewStore.js +186 -0
- package/dist/apiServer/deployment/SecretsInjector.d.ts +21 -0
- package/dist/apiServer/deployment/SecretsInjector.js +188 -0
- package/dist/apiServer/review/Review.d.ts +23 -0
- package/dist/apiServer/review/Review.js +149 -0
- package/dist/apiServer/review/ReviewAuth.d.ts +56 -0
- package/dist/apiServer/review/ReviewAuth.js +147 -0
- package/dist/apiServer/review/ReviewDiff.d.ts +43 -0
- package/dist/apiServer/review/ReviewDiff.js +175 -0
- package/dist/apiServer/review/index.html +501 -0
- package/package.json +2 -2
|
@@ -0,0 +1,186 @@
|
|
|
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.ReviewStore = void 0;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
10
|
+
const NAME_RE = /^[A-Za-z0-9._-]+$/;
|
|
11
|
+
class ReviewStore {
|
|
12
|
+
dir;
|
|
13
|
+
constructor(projectsPath) {
|
|
14
|
+
this.dir = path_1.default.resolve(projectsPath, ".review");
|
|
15
|
+
}
|
|
16
|
+
static hashToken(token) {
|
|
17
|
+
return crypto_1.default.createHash("sha256").update(String(token)).digest("hex");
|
|
18
|
+
}
|
|
19
|
+
file(project, kind) {
|
|
20
|
+
if (!NAME_RE.test(project))
|
|
21
|
+
throw new Error("invalid project name");
|
|
22
|
+
return path_1.default.join(this.dir, `${project}.${kind}`);
|
|
23
|
+
}
|
|
24
|
+
archivePath(project) { return this.file(project, "pending.tgz"); }
|
|
25
|
+
lastArchivePath(project) { return this.file(project, "last.tgz"); }
|
|
26
|
+
ensureDir() {
|
|
27
|
+
fs_1.default.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
28
|
+
}
|
|
29
|
+
static sha256File(file) {
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
const h = crypto_1.default.createHash("sha256");
|
|
32
|
+
fs_1.default.createReadStream(file).on("data", d => h.update(d)).on("error", reject).on("end", () => resolve(h.digest("hex")));
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
writeJson(file, value) {
|
|
36
|
+
const tmp = file + ".tmp";
|
|
37
|
+
fs_1.default.writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: "utf-8", mode: 0o600 });
|
|
38
|
+
fs_1.default.renameSync(tmp, file);
|
|
39
|
+
}
|
|
40
|
+
async create(project, file, meta) {
|
|
41
|
+
this.ensureDir();
|
|
42
|
+
const replaced = this.get(project) !== null;
|
|
43
|
+
this.remove(project);
|
|
44
|
+
const archive = this.archivePath(project);
|
|
45
|
+
await new Promise((resolve, reject) => file.mv(archive, (err) => err ? reject(err) : resolve()));
|
|
46
|
+
fs_1.default.chmodSync(archive, 0o600);
|
|
47
|
+
const tokens = {};
|
|
48
|
+
const reviewers = {};
|
|
49
|
+
for (const login of meta.reviewers) {
|
|
50
|
+
const token = crypto_1.default.randomBytes(32).toString("base64url");
|
|
51
|
+
tokens[login] = token;
|
|
52
|
+
reviewers[login] = { tokenHash: ReviewStore.hashToken(token), decision: null, at: null, ip: null };
|
|
53
|
+
}
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
const pending = {
|
|
56
|
+
project,
|
|
57
|
+
state: "pending",
|
|
58
|
+
sha256: await ReviewStore.sha256File(archive),
|
|
59
|
+
size: fs_1.default.statSync(archive).size,
|
|
60
|
+
uploadedBy: meta.uploadedBy,
|
|
61
|
+
uploadedFrom: meta.uploadedFrom,
|
|
62
|
+
uploadedAt: now,
|
|
63
|
+
expiresAt: now + meta.ttlMs,
|
|
64
|
+
mode: meta.mode,
|
|
65
|
+
reviewers,
|
|
66
|
+
};
|
|
67
|
+
this.writeJson(this.file(project, "pending.json"), pending);
|
|
68
|
+
return { pending, tokens, replaced };
|
|
69
|
+
}
|
|
70
|
+
get(project) {
|
|
71
|
+
try {
|
|
72
|
+
const p = JSON.parse(fs_1.default.readFileSync(this.file(project, "pending.json"), "utf-8"));
|
|
73
|
+
return p && typeof p === "object" && p.project === project ? p : null;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
save(pending) {
|
|
80
|
+
this.writeJson(this.file(pending.project, "pending.json"), pending);
|
|
81
|
+
}
|
|
82
|
+
findByToken(token) {
|
|
83
|
+
if (typeof token !== "string" || token.length < 20 || token.length > 200)
|
|
84
|
+
return null;
|
|
85
|
+
const hash = Buffer.from(ReviewStore.hashToken(token), "hex");
|
|
86
|
+
let entries;
|
|
87
|
+
try {
|
|
88
|
+
entries = fs_1.default.readdirSync(this.dir);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
for (const f of entries) {
|
|
94
|
+
if (!f.endsWith(".pending.json"))
|
|
95
|
+
continue;
|
|
96
|
+
const pending = this.get(f.slice(0, -".pending.json".length));
|
|
97
|
+
if (!pending || pending.expiresAt < Date.now())
|
|
98
|
+
continue;
|
|
99
|
+
for (const [login, r] of Object.entries(pending.reviewers)) {
|
|
100
|
+
const stored = Buffer.from(String(r.tokenHash), "hex");
|
|
101
|
+
if (stored.length === hash.length && crypto_1.default.timingSafeEqual(stored, hash))
|
|
102
|
+
return { pending, reviewer: login };
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
async archiveIntact(pending) {
|
|
108
|
+
try {
|
|
109
|
+
return (await ReviewStore.sha256File(this.archivePath(pending.project))) === pending.sha256;
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
journal(project, event, details) {
|
|
116
|
+
try {
|
|
117
|
+
this.ensureDir();
|
|
118
|
+
const file = path_1.default.join(this.dir, `${project}.history.jsonl`);
|
|
119
|
+
if (!NAME_RE.test(project))
|
|
120
|
+
return;
|
|
121
|
+
try {
|
|
122
|
+
if (fs_1.default.statSync(file).size > 1024 * 1024)
|
|
123
|
+
fs_1.default.renameSync(file, file + ".1");
|
|
124
|
+
}
|
|
125
|
+
catch { }
|
|
126
|
+
fs_1.default.appendFileSync(file, JSON.stringify({ at: new Date().toISOString(), event, ...details }) + "\n", { encoding: "utf-8", mode: 0o600 });
|
|
127
|
+
}
|
|
128
|
+
catch { }
|
|
129
|
+
}
|
|
130
|
+
dropArchive(project) {
|
|
131
|
+
try {
|
|
132
|
+
fs_1.default.rmSync(this.archivePath(project), { force: true });
|
|
133
|
+
}
|
|
134
|
+
catch { }
|
|
135
|
+
}
|
|
136
|
+
sweep() {
|
|
137
|
+
const expired = [];
|
|
138
|
+
let entries;
|
|
139
|
+
try {
|
|
140
|
+
entries = fs_1.default.readdirSync(this.dir);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
return expired;
|
|
144
|
+
}
|
|
145
|
+
for (const f of entries) {
|
|
146
|
+
if (!f.endsWith(".pending.json"))
|
|
147
|
+
continue;
|
|
148
|
+
const pending = this.get(f.slice(0, -".pending.json".length));
|
|
149
|
+
if (!pending || pending.state !== "pending" || pending.expiresAt >= Date.now())
|
|
150
|
+
continue;
|
|
151
|
+
pending.state = "expired";
|
|
152
|
+
pending.result = { at: Date.now(), message: "Nobody decided in time — upload again to restart the review." };
|
|
153
|
+
this.save(pending);
|
|
154
|
+
this.dropArchive(pending.project);
|
|
155
|
+
this.journal(pending.project, "expired", { sha256: pending.sha256 });
|
|
156
|
+
expired.push(pending.project);
|
|
157
|
+
}
|
|
158
|
+
return expired;
|
|
159
|
+
}
|
|
160
|
+
remove(project) {
|
|
161
|
+
for (const kind of ["pending.json", "pending.tgz"])
|
|
162
|
+
try {
|
|
163
|
+
fs_1.default.rmSync(this.file(project, kind), { force: true });
|
|
164
|
+
}
|
|
165
|
+
catch { }
|
|
166
|
+
}
|
|
167
|
+
stageBaseline(project, archive) {
|
|
168
|
+
this.ensureDir();
|
|
169
|
+
const incoming = this.file(project, "incoming.tgz");
|
|
170
|
+
fs_1.default.copyFileSync(archive, incoming);
|
|
171
|
+
fs_1.default.chmodSync(incoming, 0o600);
|
|
172
|
+
}
|
|
173
|
+
commitBaseline(project) {
|
|
174
|
+
try {
|
|
175
|
+
fs_1.default.renameSync(this.file(project, "incoming.tgz"), this.lastArchivePath(project));
|
|
176
|
+
}
|
|
177
|
+
catch { }
|
|
178
|
+
}
|
|
179
|
+
dropStagedBaseline(project) {
|
|
180
|
+
try {
|
|
181
|
+
fs_1.default.rmSync(this.file(project, "incoming.tgz"), { force: true });
|
|
182
|
+
}
|
|
183
|
+
catch { }
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
exports.ReviewStore = ReviewStore;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface ISecretsSettings {
|
|
2
|
+
dir?: string;
|
|
3
|
+
file?: string;
|
|
4
|
+
}
|
|
5
|
+
export declare class SecretsInjector {
|
|
6
|
+
static resolvePath(project: string, slot: string | null, settings: ISecretsSettings | undefined, defaultDir: string | undefined, destinationRoot: string): {
|
|
7
|
+
path?: string;
|
|
8
|
+
error?: string;
|
|
9
|
+
};
|
|
10
|
+
static write(file: string, values: Record<string, unknown>): void;
|
|
11
|
+
static verify(file: string, values: Record<string, unknown>): string | null;
|
|
12
|
+
static expression(file: string, key: string): string;
|
|
13
|
+
static transform(source: string, keys: Set<string>, file: string): {
|
|
14
|
+
content: string;
|
|
15
|
+
rewritten: number;
|
|
16
|
+
leftover: boolean;
|
|
17
|
+
};
|
|
18
|
+
private static endsInBlockComment;
|
|
19
|
+
private static rewriteLiteral;
|
|
20
|
+
static parses(source: string): boolean;
|
|
21
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
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.SecretsInjector = void 0;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const vm_1 = __importDefault(require("vm"));
|
|
10
|
+
const PLACEHOLDER = /_\{\{([A-Za-z0-9_]+)\}\}_/g;
|
|
11
|
+
class SecretsInjector {
|
|
12
|
+
static resolvePath(project, slot, settings, defaultDir, destinationRoot) {
|
|
13
|
+
const file = settings?.file?.trim(), dir = (settings?.dir?.trim() || defaultDir?.trim() || "");
|
|
14
|
+
let target;
|
|
15
|
+
if (file) {
|
|
16
|
+
if (!path_1.default.isAbsolute(file))
|
|
17
|
+
return { error: `secrets.file must be an absolute path ("${file}")` };
|
|
18
|
+
const ext = path_1.default.extname(file) || ".json";
|
|
19
|
+
target = slot ? path_1.default.join(path_1.default.dirname(file), `${path_1.default.basename(file, path_1.default.extname(file))}-${slot}${ext}`) : file;
|
|
20
|
+
}
|
|
21
|
+
else if (dir) {
|
|
22
|
+
if (!path_1.default.isAbsolute(dir))
|
|
23
|
+
return { error: `the secrets directory must be an absolute path ("${dir}")` };
|
|
24
|
+
target = path_1.default.join(dir, `${project}${slot ? "-" + slot : ""}.json`);
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
return { error: "secrets is enabled, but neither secrets.dir / secrets.file nor secrets_dir in setup.json is set" };
|
|
28
|
+
}
|
|
29
|
+
target = path_1.default.resolve(target);
|
|
30
|
+
const root = path_1.default.resolve(destinationRoot);
|
|
31
|
+
if (target === root || target.startsWith(root + path_1.default.sep))
|
|
32
|
+
return { error: `the secrets file must live outside the deploy folder ("${target}" is inside "${root}")` };
|
|
33
|
+
return { path: target };
|
|
34
|
+
}
|
|
35
|
+
static write(file, values) {
|
|
36
|
+
fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true, mode: 0o700 });
|
|
37
|
+
const tmp = file + ".tmp";
|
|
38
|
+
fs_1.default.writeFileSync(tmp, JSON.stringify(values, null, 2), { encoding: "utf-8", mode: 0o600 });
|
|
39
|
+
fs_1.default.chmodSync(tmp, 0o600);
|
|
40
|
+
fs_1.default.renameSync(tmp, file);
|
|
41
|
+
}
|
|
42
|
+
static verify(file, values) {
|
|
43
|
+
try {
|
|
44
|
+
fs_1.default.accessSync(file, fs_1.default.constants.R_OK);
|
|
45
|
+
const back = JSON.parse(fs_1.default.readFileSync(file, "utf-8"));
|
|
46
|
+
const missing = Object.keys(values).filter(k => !Object.prototype.hasOwnProperty.call(back, k));
|
|
47
|
+
return missing.length ? `${file} lacks ${missing.join(", ")}` : null;
|
|
48
|
+
}
|
|
49
|
+
catch (e) {
|
|
50
|
+
return `${file} is not readable: ${e?.message ?? e}`;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
static expression(file, key) {
|
|
54
|
+
const p = JSON.stringify(file);
|
|
55
|
+
return `(function(k){var s=globalThis.__badmfckSecrets||(globalThis.__badmfckSecrets=JSON.parse(require("fs").readFileSync(${p},"utf8")));`
|
|
56
|
+
+ `if(!Object.prototype.hasOwnProperty.call(s,k))throw new Error("secret \\""+k+"\\" is missing in "+${p});return String(s[k]);})(${JSON.stringify(key)})`;
|
|
57
|
+
}
|
|
58
|
+
static transform(source, keys, file) {
|
|
59
|
+
let rewritten = 0, inBlockComment = false;
|
|
60
|
+
const lines = source.split("\n");
|
|
61
|
+
for (let n = 0; n < lines.length; n++) {
|
|
62
|
+
const line = lines[n];
|
|
63
|
+
if (!inBlockComment && line.indexOf("_{{") === -1) {
|
|
64
|
+
inBlockComment = SecretsInjector.endsInBlockComment(line, false);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const defuse = (text) => text.replace(/_\{\{/g, "_{ {");
|
|
68
|
+
let out = "", i = 0;
|
|
69
|
+
while (i < line.length) {
|
|
70
|
+
if (inBlockComment) {
|
|
71
|
+
const end = line.indexOf("*/", i);
|
|
72
|
+
if (end === -1) {
|
|
73
|
+
out += defuse(line.slice(i));
|
|
74
|
+
i = line.length;
|
|
75
|
+
break;
|
|
76
|
+
}
|
|
77
|
+
out += defuse(line.slice(i, end + 2));
|
|
78
|
+
i = end + 2;
|
|
79
|
+
inBlockComment = false;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const c = line[i];
|
|
83
|
+
if (c === "/" && line[i + 1] === "/") {
|
|
84
|
+
out += defuse(line.slice(i));
|
|
85
|
+
i = line.length;
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
if (c === "/" && line[i + 1] === "*") {
|
|
89
|
+
inBlockComment = true;
|
|
90
|
+
out += "/*";
|
|
91
|
+
i += 2;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
95
|
+
let j = i + 1;
|
|
96
|
+
while (j < line.length && line[j] !== c)
|
|
97
|
+
j += line[j] === "\\" ? 2 : 1;
|
|
98
|
+
if (j >= line.length) {
|
|
99
|
+
out += line.slice(i);
|
|
100
|
+
i = line.length;
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
const literal = line.slice(i, j + 1);
|
|
104
|
+
const rep = SecretsInjector.rewriteLiteral(literal, c, keys, file);
|
|
105
|
+
if (rep !== literal)
|
|
106
|
+
rewritten++;
|
|
107
|
+
out += rep;
|
|
108
|
+
i = j + 1;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
out += c;
|
|
112
|
+
i++;
|
|
113
|
+
}
|
|
114
|
+
lines[n] = out;
|
|
115
|
+
}
|
|
116
|
+
const content = lines.join("\n");
|
|
117
|
+
let leftover = false;
|
|
118
|
+
for (const m of content.matchAll(PLACEHOLDER))
|
|
119
|
+
if (keys.has(m[1])) {
|
|
120
|
+
leftover = true;
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
return { content, rewritten, leftover };
|
|
124
|
+
}
|
|
125
|
+
static endsInBlockComment(line, open) {
|
|
126
|
+
let i = 0;
|
|
127
|
+
while (i < line.length) {
|
|
128
|
+
if (open) {
|
|
129
|
+
const e = line.indexOf("*/", i);
|
|
130
|
+
if (e === -1)
|
|
131
|
+
return true;
|
|
132
|
+
open = false;
|
|
133
|
+
i = e + 2;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
const c = line[i];
|
|
137
|
+
if (c === "/" && line[i + 1] === "/")
|
|
138
|
+
return false;
|
|
139
|
+
if (c === "/" && line[i + 1] === "*") {
|
|
140
|
+
open = true;
|
|
141
|
+
i += 2;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
145
|
+
let j = i + 1;
|
|
146
|
+
while (j < line.length && line[j] !== c)
|
|
147
|
+
j += line[j] === "\\" ? 2 : 1;
|
|
148
|
+
i = j + 1;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
i++;
|
|
152
|
+
}
|
|
153
|
+
return open;
|
|
154
|
+
}
|
|
155
|
+
static rewriteLiteral(literal, quote, keys, file) {
|
|
156
|
+
const body = literal.slice(1, -1);
|
|
157
|
+
if (quote === "`" && body.includes("${"))
|
|
158
|
+
return literal;
|
|
159
|
+
const parts = [];
|
|
160
|
+
let last = 0, found = false;
|
|
161
|
+
for (const m of body.matchAll(PLACEHOLDER)) {
|
|
162
|
+
if (!keys.has(m[1]))
|
|
163
|
+
continue;
|
|
164
|
+
found = true;
|
|
165
|
+
const before = body.slice(last, m.index);
|
|
166
|
+
if (before)
|
|
167
|
+
parts.push(quote + before + quote);
|
|
168
|
+
parts.push(SecretsInjector.expression(file, m[1]));
|
|
169
|
+
last = m.index + m[0].length;
|
|
170
|
+
}
|
|
171
|
+
if (!found)
|
|
172
|
+
return literal;
|
|
173
|
+
const after = body.slice(last);
|
|
174
|
+
if (after)
|
|
175
|
+
parts.push(quote + after + quote);
|
|
176
|
+
return "(" + (parts.length === 1 ? parts[0] : `""+` + parts.join("+")) + ")";
|
|
177
|
+
}
|
|
178
|
+
static parses(source) {
|
|
179
|
+
try {
|
|
180
|
+
new vm_1.default.Script(`(function (exports, require, module, __filename, __dirname) {${source}\n})`);
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
exports.SecretsInjector = SecretsInjector;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { APIServiceOptions } from "../APIService";
|
|
2
|
+
import { BaseEndpoint } from "../BaseEndpoint";
|
|
3
|
+
import { HTTPRequestVO, TransferPacketVO } from "../structures/Interfaces";
|
|
4
|
+
import { DeployerService } from "../deployment/DeployerService";
|
|
5
|
+
export declare class Review extends BaseEndpoint {
|
|
6
|
+
private deployer;
|
|
7
|
+
private apiServiceOptions;
|
|
8
|
+
ignoreInDocumentation: boolean;
|
|
9
|
+
private indexHtmlFile;
|
|
10
|
+
private auth;
|
|
11
|
+
constructor(deployer: DeployerService, apiServiceOptions: APIServiceOptions);
|
|
12
|
+
private gate;
|
|
13
|
+
private session;
|
|
14
|
+
private static view;
|
|
15
|
+
html(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
16
|
+
info(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
17
|
+
login(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
18
|
+
enroll2fa(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
19
|
+
details(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
20
|
+
diff(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
21
|
+
decide(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
22
|
+
logout(req: HTTPRequestVO): Promise<TransferPacketVO>;
|
|
23
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
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.Review = void 0;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const BaseEndpoint_1 = require("../BaseEndpoint");
|
|
10
|
+
const LogService_1 = require("../LogService");
|
|
11
|
+
const DefaultErrors_1 = __importDefault(require("../structures/DefaultErrors"));
|
|
12
|
+
const ReviewAuth_1 = require("./ReviewAuth");
|
|
13
|
+
const ReviewDiff_1 = require("./ReviewDiff");
|
|
14
|
+
class Review extends BaseEndpoint_1.BaseEndpoint {
|
|
15
|
+
deployer;
|
|
16
|
+
apiServiceOptions;
|
|
17
|
+
ignoreInDocumentation = true;
|
|
18
|
+
indexHtmlFile = null;
|
|
19
|
+
auth;
|
|
20
|
+
constructor(deployer, apiServiceOptions) {
|
|
21
|
+
super("review");
|
|
22
|
+
this.deployer = deployer;
|
|
23
|
+
this.apiServiceOptions = apiServiceOptions;
|
|
24
|
+
this.auth = new ReviewAuth_1.ReviewAuth(deployer.reviews, () => (deployer.setup?.reviewers ?? []), `${apiServiceOptions.projectName || "Deployer"} review`);
|
|
25
|
+
this.registerEndpoints([
|
|
26
|
+
{ ignoreInterceptor: true, ignoreHttpLogging: true, endpoint: "html", handler: this.html },
|
|
27
|
+
{ ignoreInterceptor: true, ignoreHttpLogging: true, endpoint: "info", handler: this.info, validationModel: { token: "" } },
|
|
28
|
+
{ ignoreInterceptor: true, ignoreHttpLogging: true, endpoint: "login", handler: this.login,
|
|
29
|
+
validationModel: { token: "", login: "", password: "", totp: "", $__totp_optional: true } },
|
|
30
|
+
{ ignoreInterceptor: true, ignoreHttpLogging: true, endpoint: "enroll2fa", handler: this.enroll2fa,
|
|
31
|
+
validationModel: { enrollmentToken: "", totp: "" } },
|
|
32
|
+
{ ignoreInterceptor: true, ignoreHttpLogging: true, endpoint: "details", handler: this.details },
|
|
33
|
+
{ ignoreInterceptor: true, ignoreHttpLogging: true, endpoint: "diff", handler: this.diff },
|
|
34
|
+
{ ignoreInterceptor: true, ignoreHttpLogging: true, endpoint: "decide", handler: this.decide,
|
|
35
|
+
validationModel: { decision: "", $__decision_values: ["accept", "decline"] } },
|
|
36
|
+
{ ignoreInterceptor: true, ignoreHttpLogging: true, endpoint: "logout", handler: this.logout },
|
|
37
|
+
]);
|
|
38
|
+
}
|
|
39
|
+
gate(req) {
|
|
40
|
+
if (!this.deployer.isIpAllowed(req.ip)) {
|
|
41
|
+
(0, LogService_1.logWarn)(`Review: request refused from ${req.ip ?? "unknown"} — not in allowed_ips`);
|
|
42
|
+
throw { ...DefaultErrors_1.default.FORBIDDEN, details: "The review page is not available from this address — connect to the VPN." };
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
session(req) {
|
|
46
|
+
const token = String(req.headers["authorization"] ?? "").split(" ").pop() ?? "";
|
|
47
|
+
const { session, pending, error } = this.auth.touch(token);
|
|
48
|
+
if (!session || !pending)
|
|
49
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: error ?? "Sign in again." };
|
|
50
|
+
return { session, pending };
|
|
51
|
+
}
|
|
52
|
+
static view(p, me) {
|
|
53
|
+
return {
|
|
54
|
+
project: p.project, state: p.state, result: p.result ?? null,
|
|
55
|
+
uploadedBy: p.uploadedBy, uploadedAt: p.uploadedAt, expiresAt: p.expiresAt,
|
|
56
|
+
mode: p.mode, sha256: p.sha256, size: p.size,
|
|
57
|
+
reviewers: Object.entries(p.reviewers).map(([login, r]) => ({ login, decision: r.decision, at: r.at })),
|
|
58
|
+
you: me ?? null,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
async html(req) {
|
|
62
|
+
this.gate(req);
|
|
63
|
+
if (!this.indexHtmlFile) {
|
|
64
|
+
let base = this.apiServiceOptions.baseEndPoint;
|
|
65
|
+
if (!base.endsWith("/"))
|
|
66
|
+
base += "/";
|
|
67
|
+
const title = `${this.apiServiceOptions.projectName || "Deployer"} — deploy review`;
|
|
68
|
+
const esc = (v) => v.replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
|
69
|
+
this.indexHtmlFile = fs_1.default.readFileSync(path_1.default.resolve(__dirname, "index.html"), "utf-8")
|
|
70
|
+
.replace(/{{host}}/g, esc(base + "review/"))
|
|
71
|
+
.replace(/{{title}}/g, esc(title));
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
rawResponse: true,
|
|
75
|
+
data: this.indexHtmlFile,
|
|
76
|
+
headers: {
|
|
77
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
78
|
+
"Content-Length": Buffer.byteLength(this.indexHtmlFile).toString(),
|
|
79
|
+
"Referrer-Policy": "no-referrer",
|
|
80
|
+
"Cache-Control": "no-store",
|
|
81
|
+
"X-Frame-Options": "DENY",
|
|
82
|
+
"X-Content-Type-Options": "nosniff",
|
|
83
|
+
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
async info(req) {
|
|
88
|
+
this.gate(req);
|
|
89
|
+
const link = this.deployer.reviews.findByToken(String(req.data.token ?? ""));
|
|
90
|
+
if (!link)
|
|
91
|
+
throw { ...DefaultErrors_1.default.NOT_FOUND, details: "This link is invalid, expired or was replaced by a newer upload." };
|
|
92
|
+
const v = Review.view(link.pending, link.reviewer);
|
|
93
|
+
return { data: { project: v.project, state: v.state, result: v.result, uploadedBy: v.uploadedBy, uploadedAt: v.uploadedAt, expiresAt: v.expiresAt, mode: v.mode, reviewer: link.reviewer } };
|
|
94
|
+
}
|
|
95
|
+
async login(req) {
|
|
96
|
+
this.gate(req);
|
|
97
|
+
const r = await this.auth.login(req.data.token, req.data.login, req.data.password, req.data.totp);
|
|
98
|
+
if (r.error) {
|
|
99
|
+
(0, LogService_1.logWarn)(`Review sign-in failed for "${String(req.data.login).slice(0, 64)}" from ${req.ip ?? "unknown"}: ${r.error}`);
|
|
100
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: r.error };
|
|
101
|
+
}
|
|
102
|
+
if (r.enrollment)
|
|
103
|
+
return { data: { enrollmentRequired: true, ...r.enrollment } };
|
|
104
|
+
(0, LogService_1.logInfo)(`Review sign-in: "${r.session.login}" for "${r.session.project}" from ${req.ip ?? "unknown"}`);
|
|
105
|
+
return { data: { token: r.session.token, idleTimeoutMs: ReviewAuth_1.ReviewAuth.SESSION_IDLE_MS } };
|
|
106
|
+
}
|
|
107
|
+
async enroll2fa(req) {
|
|
108
|
+
this.gate(req);
|
|
109
|
+
const r = this.auth.enroll(req.data.enrollmentToken, req.data.totp);
|
|
110
|
+
if (r.error)
|
|
111
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: r.error };
|
|
112
|
+
(0, LogService_1.logInfo)(`Review 2FA enrolled for "${r.session.login}" from ${req.ip ?? "unknown"}`);
|
|
113
|
+
return { data: { token: r.session.token, idleTimeoutMs: ReviewAuth_1.ReviewAuth.SESSION_IDLE_MS } };
|
|
114
|
+
}
|
|
115
|
+
async details(req) {
|
|
116
|
+
this.gate(req);
|
|
117
|
+
const { session, pending } = this.session(req);
|
|
118
|
+
return { data: Review.view(pending, session.login) };
|
|
119
|
+
}
|
|
120
|
+
async diff(req) {
|
|
121
|
+
this.gate(req);
|
|
122
|
+
const { pending } = this.session(req);
|
|
123
|
+
const store = this.deployer.reviews;
|
|
124
|
+
const archive = store.archivePath(pending.project);
|
|
125
|
+
if (pending.state !== "pending" || !fs_1.default.existsSync(archive))
|
|
126
|
+
return { data: { unavailable: "The upload is no longer waiting for review — its archive was removed." } };
|
|
127
|
+
const baseline = fs_1.default.existsSync(store.lastArchivePath(pending.project)) ? store.lastArchivePath(pending.project) : null;
|
|
128
|
+
try {
|
|
129
|
+
return { data: await ReviewDiff_1.ReviewDiff.compute(baseline, archive) };
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
(0, LogService_1.logWarn)(`Review diff for "${pending.project}" failed: ${e?.message ?? e}`);
|
|
133
|
+
return { data: { unavailable: "Can't compare the archives: " + String(e?.message ?? e).slice(0, 300) } };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async decide(req) {
|
|
137
|
+
this.gate(req);
|
|
138
|
+
const { session } = this.session(req);
|
|
139
|
+
const r = await this.deployer.reviewDecide(session.project, session.sha256, session.login, req.data.decision, req.ip ?? null);
|
|
140
|
+
if (r.error || !r.pending)
|
|
141
|
+
throw { ...DefaultErrors_1.default.BAD_REQUEST, details: r.error ?? "Can't record the decision." };
|
|
142
|
+
return { data: Review.view(r.pending, session.login) };
|
|
143
|
+
}
|
|
144
|
+
async logout(req) {
|
|
145
|
+
this.auth.logout(String(req.headers["authorization"] ?? "").split(" ").pop() ?? "");
|
|
146
|
+
return { data: true };
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
exports.Review = Review;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { IPendingReview, ReviewStore } from "../deployment/ReviewStore";
|
|
2
|
+
export interface IReviewer {
|
|
3
|
+
login: string;
|
|
4
|
+
password: string;
|
|
5
|
+
email: string;
|
|
6
|
+
}
|
|
7
|
+
export interface IReviewSession {
|
|
8
|
+
token: string;
|
|
9
|
+
login: string;
|
|
10
|
+
project: string;
|
|
11
|
+
sha256: string;
|
|
12
|
+
linkHash: string;
|
|
13
|
+
createdAt: number;
|
|
14
|
+
lastSeenAt: number;
|
|
15
|
+
}
|
|
16
|
+
export declare class ReviewAuth {
|
|
17
|
+
private store;
|
|
18
|
+
private reviewers;
|
|
19
|
+
private issuer;
|
|
20
|
+
static SESSION_IDLE_MS: number;
|
|
21
|
+
static SESSION_MAX_MS: number;
|
|
22
|
+
static ENROLLMENT_TTL_MS: number;
|
|
23
|
+
static MAX_FAILED_ATTEMPTS: number;
|
|
24
|
+
static LOCKOUT_MS: number;
|
|
25
|
+
private sessions;
|
|
26
|
+
private enrollments;
|
|
27
|
+
private failures;
|
|
28
|
+
private readonly totpFile;
|
|
29
|
+
constructor(store: ReviewStore, reviewers: () => IReviewer[], issuer?: string);
|
|
30
|
+
private readSecrets;
|
|
31
|
+
private secretFor;
|
|
32
|
+
private saveSecret;
|
|
33
|
+
private lockedFor;
|
|
34
|
+
private fail;
|
|
35
|
+
login(linkToken: string, login: string, password: string, totp?: string): Promise<{
|
|
36
|
+
session?: IReviewSession;
|
|
37
|
+
enrollment?: {
|
|
38
|
+
enrollmentToken: string;
|
|
39
|
+
secret: string;
|
|
40
|
+
otpauthUri: string;
|
|
41
|
+
expiresInMs: number;
|
|
42
|
+
};
|
|
43
|
+
error?: string;
|
|
44
|
+
}>;
|
|
45
|
+
enroll(enrollmentToken: string, totp: string): {
|
|
46
|
+
session?: IReviewSession;
|
|
47
|
+
error?: string;
|
|
48
|
+
};
|
|
49
|
+
private createSession;
|
|
50
|
+
touch(token: string): {
|
|
51
|
+
session?: IReviewSession;
|
|
52
|
+
pending?: IPendingReview;
|
|
53
|
+
error?: string;
|
|
54
|
+
};
|
|
55
|
+
logout(token: string): void;
|
|
56
|
+
}
|