badmfck-api-server 6.0.2 → 6.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +147 -4
- package/dist/apiServer/APIService.d.ts +1 -0
- package/dist/apiServer/APIService.js +5 -1
- 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 +47 -6
- package/dist/apiServer/deployment/DeployerService.js +330 -39
- 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/helper/IpAllowList.d.ts +8 -0
- package/dist/apiServer/helper/IpAllowList.js +40 -0
- package/dist/apiServer/monitor/AccessStore.d.ts +2 -0
- package/dist/apiServer/monitor/AccessStore.js +12 -2
- package/dist/apiServer/monitor/Monitor.d.ts +1 -0
- package/dist/apiServer/monitor/Monitor.js +16 -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,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
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
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.ReviewAuth = 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 MonitorAuth_1 = require("../monitor/MonitorAuth");
|
|
11
|
+
const PasswordHash_1 = require("../helper/PasswordHash");
|
|
12
|
+
class ReviewAuth {
|
|
13
|
+
store;
|
|
14
|
+
reviewers;
|
|
15
|
+
issuer;
|
|
16
|
+
static SESSION_IDLE_MS = 15 * 60 * 1000;
|
|
17
|
+
static SESSION_MAX_MS = 60 * 60 * 1000;
|
|
18
|
+
static ENROLLMENT_TTL_MS = 10 * 60 * 1000;
|
|
19
|
+
static MAX_FAILED_ATTEMPTS = 10;
|
|
20
|
+
static LOCKOUT_MS = 30 * 60 * 1000;
|
|
21
|
+
sessions = new Map();
|
|
22
|
+
enrollments = new Map();
|
|
23
|
+
failures = new Map();
|
|
24
|
+
totpFile;
|
|
25
|
+
constructor(store, reviewers, issuer = "Deploy review") {
|
|
26
|
+
this.store = store;
|
|
27
|
+
this.reviewers = reviewers;
|
|
28
|
+
this.issuer = issuer;
|
|
29
|
+
this.totpFile = path_1.default.join(store.dir, "reviewers-2fa.json");
|
|
30
|
+
}
|
|
31
|
+
readSecrets() {
|
|
32
|
+
try {
|
|
33
|
+
const doc = JSON.parse(fs_1.default.readFileSync(this.totpFile, "utf-8"));
|
|
34
|
+
return doc && typeof doc.users === "object" && doc.users ? doc.users : {};
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return {};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
secretFor(login) {
|
|
41
|
+
const r = this.readSecrets()[login];
|
|
42
|
+
return r && typeof r.secret === "string" && r.secret.length > 0 ? r.secret : null;
|
|
43
|
+
}
|
|
44
|
+
saveSecret(login, secret) {
|
|
45
|
+
fs_1.default.mkdirSync(path_1.default.dirname(this.totpFile), { recursive: true, mode: 0o700 });
|
|
46
|
+
const users = this.readSecrets();
|
|
47
|
+
users[login] = { secret, enrolledAt: Date.now() };
|
|
48
|
+
const tmp = this.totpFile + ".tmp";
|
|
49
|
+
fs_1.default.writeFileSync(tmp, JSON.stringify({ version: 1, users }, null, 2), { encoding: "utf-8", mode: 0o600 });
|
|
50
|
+
fs_1.default.renameSync(tmp, this.totpFile);
|
|
51
|
+
}
|
|
52
|
+
lockedFor(login) {
|
|
53
|
+
const f = this.failures.get(login);
|
|
54
|
+
return f && f.lockedUntil > Date.now() ? f.lockedUntil - Date.now() : 0;
|
|
55
|
+
}
|
|
56
|
+
fail(login) {
|
|
57
|
+
const f = this.failures.get(login) ?? { count: 0, lockedUntil: 0 };
|
|
58
|
+
f.count++;
|
|
59
|
+
if (f.count >= ReviewAuth.MAX_FAILED_ATTEMPTS) {
|
|
60
|
+
f.lockedUntil = Date.now() + ReviewAuth.LOCKOUT_MS;
|
|
61
|
+
f.count = 0;
|
|
62
|
+
}
|
|
63
|
+
this.failures.set(login, f);
|
|
64
|
+
}
|
|
65
|
+
async login(linkToken, login, password, totp) {
|
|
66
|
+
const link = this.store.findByToken(linkToken);
|
|
67
|
+
if (!link)
|
|
68
|
+
return { error: "This link is invalid, expired or was replaced by a newer upload." };
|
|
69
|
+
login = String(login ?? "").trim();
|
|
70
|
+
const locked = this.lockedFor(login);
|
|
71
|
+
if (locked > 0)
|
|
72
|
+
return { error: `Account locked, try again in ${Math.ceil(locked / 60000)} min.` };
|
|
73
|
+
const reviewer = this.reviewers().find(r => r.login === login);
|
|
74
|
+
const passwordOk = reviewer && link.reviewer === login && PasswordHash_1.PasswordHash.isHash(reviewer.password)
|
|
75
|
+
&& await PasswordHash_1.PasswordHash.verify(String(password ?? ""), reviewer.password);
|
|
76
|
+
if (!passwordOk) {
|
|
77
|
+
this.fail(login);
|
|
78
|
+
return { error: "Invalid login or password." };
|
|
79
|
+
}
|
|
80
|
+
const bound = { project: link.pending.project, sha256: link.pending.sha256, linkHash: link.pending.reviewers[login].tokenHash };
|
|
81
|
+
const secret = this.secretFor(login);
|
|
82
|
+
if (!secret) {
|
|
83
|
+
const now = Date.now();
|
|
84
|
+
for (const [t, e] of this.enrollments)
|
|
85
|
+
if (now - e.createdAt > ReviewAuth.ENROLLMENT_TTL_MS)
|
|
86
|
+
this.enrollments.delete(t);
|
|
87
|
+
const { secret: fresh, uri } = MonitorAuth_1.MonitorAuth.generateTotpSecret(login, this.issuer);
|
|
88
|
+
const enrollmentToken = crypto_1.default.randomBytes(32).toString("hex");
|
|
89
|
+
this.enrollments.set(enrollmentToken, { login, secret: fresh, link: bound, createdAt: now });
|
|
90
|
+
return { enrollment: { enrollmentToken, secret: fresh, otpauthUri: uri, expiresInMs: ReviewAuth.ENROLLMENT_TTL_MS } };
|
|
91
|
+
}
|
|
92
|
+
const totpError = MonitorAuth_1.MonitorAuth.verifyTotp("review:" + login, secret, String(totp ?? ""));
|
|
93
|
+
if (totpError) {
|
|
94
|
+
this.fail(login);
|
|
95
|
+
return { error: totpError };
|
|
96
|
+
}
|
|
97
|
+
this.failures.delete(login);
|
|
98
|
+
return { session: this.createSession(login, bound) };
|
|
99
|
+
}
|
|
100
|
+
enroll(enrollmentToken, totp) {
|
|
101
|
+
const e = this.enrollments.get(String(enrollmentToken ?? ""));
|
|
102
|
+
if (!e || Date.now() - e.createdAt > ReviewAuth.ENROLLMENT_TTL_MS) {
|
|
103
|
+
this.enrollments.delete(String(enrollmentToken ?? ""));
|
|
104
|
+
return { error: "Enrollment expired — sign in again." };
|
|
105
|
+
}
|
|
106
|
+
if (this.secretFor(e.login)) {
|
|
107
|
+
this.enrollments.delete(enrollmentToken);
|
|
108
|
+
return { error: "2FA is already set up for this reviewer — sign in with your code." };
|
|
109
|
+
}
|
|
110
|
+
const err = MonitorAuth_1.MonitorAuth.verifyTotp("review:" + e.login, e.secret, String(totp ?? ""));
|
|
111
|
+
if (err)
|
|
112
|
+
return { error: err };
|
|
113
|
+
this.saveSecret(e.login, e.secret);
|
|
114
|
+
this.enrollments.delete(enrollmentToken);
|
|
115
|
+
this.failures.delete(e.login);
|
|
116
|
+
return { session: this.createSession(e.login, e.link) };
|
|
117
|
+
}
|
|
118
|
+
createSession(login, link) {
|
|
119
|
+
const now = Date.now();
|
|
120
|
+
for (const [t, s] of this.sessions)
|
|
121
|
+
if (now - s.lastSeenAt > ReviewAuth.SESSION_IDLE_MS || now - s.createdAt > ReviewAuth.SESSION_MAX_MS)
|
|
122
|
+
this.sessions.delete(t);
|
|
123
|
+
const session = { token: crypto_1.default.randomBytes(32).toString("hex"), login, ...link, createdAt: now, lastSeenAt: now };
|
|
124
|
+
this.sessions.set(session.token, session);
|
|
125
|
+
return session;
|
|
126
|
+
}
|
|
127
|
+
touch(token) {
|
|
128
|
+
const s = this.sessions.get(String(token ?? ""));
|
|
129
|
+
const now = Date.now();
|
|
130
|
+
if (!s || now - s.lastSeenAt > ReviewAuth.SESSION_IDLE_MS || now - s.createdAt > ReviewAuth.SESSION_MAX_MS) {
|
|
131
|
+
if (s)
|
|
132
|
+
this.sessions.delete(s.token);
|
|
133
|
+
return { error: "Session expired — sign in again." };
|
|
134
|
+
}
|
|
135
|
+
const pending = this.store.get(s.project);
|
|
136
|
+
if (!pending || pending.sha256 !== s.sha256 || pending.reviewers[s.login]?.tokenHash !== s.linkHash) {
|
|
137
|
+
this.sessions.delete(s.token);
|
|
138
|
+
return { error: "This upload was replaced or removed — open the newest link from your email." };
|
|
139
|
+
}
|
|
140
|
+
s.lastSeenAt = now;
|
|
141
|
+
return { session: s, pending };
|
|
142
|
+
}
|
|
143
|
+
logout(token) {
|
|
144
|
+
this.sessions.delete(String(token ?? ""));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
exports.ReviewAuth = ReviewAuth;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export interface IFileChange {
|
|
2
|
+
path: string;
|
|
3
|
+
status: "added" | "removed" | "modified";
|
|
4
|
+
kind: "text" | "binary" | "symlink" | "sensitive" | "large";
|
|
5
|
+
sizeBefore: number | null;
|
|
6
|
+
sizeAfter: number | null;
|
|
7
|
+
diff?: string;
|
|
8
|
+
truncated?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface IDependencyChange {
|
|
11
|
+
name: string;
|
|
12
|
+
section: string;
|
|
13
|
+
before: string | null;
|
|
14
|
+
after: string | null;
|
|
15
|
+
}
|
|
16
|
+
export interface IReviewDiff {
|
|
17
|
+
baseline: {
|
|
18
|
+
at: number;
|
|
19
|
+
version: string | null;
|
|
20
|
+
} | null;
|
|
21
|
+
versionBefore: string | null;
|
|
22
|
+
versionAfter: string | null;
|
|
23
|
+
dependencies: IDependencyChange[];
|
|
24
|
+
files: IFileChange[];
|
|
25
|
+
unchanged: number;
|
|
26
|
+
limited: string | null;
|
|
27
|
+
}
|
|
28
|
+
export declare class ReviewDiff {
|
|
29
|
+
static MAX_ARCHIVE_BYTES: number;
|
|
30
|
+
static MAX_FILES: number;
|
|
31
|
+
static MAX_TEXT_FILE: number;
|
|
32
|
+
static MAX_FILE_DIFF: number;
|
|
33
|
+
static MAX_TOTAL_DIFF: number;
|
|
34
|
+
static SENSITIVE: RegExp[];
|
|
35
|
+
private static cache;
|
|
36
|
+
static compute(baseline: string | null, pending: string): Promise<IReviewDiff>;
|
|
37
|
+
private static sha;
|
|
38
|
+
private static walk;
|
|
39
|
+
private static isText;
|
|
40
|
+
private static compare;
|
|
41
|
+
private static readJson;
|
|
42
|
+
private static unified;
|
|
43
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
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.ReviewDiff = void 0;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const os_1 = __importDefault(require("os"));
|
|
9
|
+
const path_1 = __importDefault(require("path"));
|
|
10
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
11
|
+
const child_process_1 = require("child_process");
|
|
12
|
+
const util_1 = require("util");
|
|
13
|
+
const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
|
|
14
|
+
class ReviewDiff {
|
|
15
|
+
static MAX_ARCHIVE_BYTES = 200 * 1024 * 1024;
|
|
16
|
+
static MAX_FILES = 5000;
|
|
17
|
+
static MAX_TEXT_FILE = 512 * 1024;
|
|
18
|
+
static MAX_FILE_DIFF = 200 * 1024;
|
|
19
|
+
static MAX_TOTAL_DIFF = 2 * 1024 * 1024;
|
|
20
|
+
static SENSITIVE = [/(^|\/)\.env(\..*)?$/i, /\.(pem|key|p12|pfx|jks|keystore)$/i, /(^|\/)id_(rsa|dsa|ecdsa|ed25519)$/i,
|
|
21
|
+
/(^|\/)\.npmrc$/i, /(^|\/)\.netrc$/i, /(^|\/)(credentials|secrets?)(\.[a-z]+)?$/i];
|
|
22
|
+
static cache = new Map();
|
|
23
|
+
static async compute(baseline, pending) {
|
|
24
|
+
const key = `${baseline ? await ReviewDiff.sha(baseline) : "-"}:${await ReviewDiff.sha(pending)}`;
|
|
25
|
+
const hit = ReviewDiff.cache.get(key);
|
|
26
|
+
if (hit)
|
|
27
|
+
return hit;
|
|
28
|
+
const tmp = await fs_1.default.promises.mkdtemp(path_1.default.join(os_1.default.tmpdir(), "review-diff-"));
|
|
29
|
+
try {
|
|
30
|
+
await fs_1.default.promises.chmod(tmp, 0o700);
|
|
31
|
+
for (const f of [baseline, pending])
|
|
32
|
+
if (f && (await fs_1.default.promises.stat(f)).size > ReviewDiff.MAX_ARCHIVE_BYTES)
|
|
33
|
+
throw new Error(`archive is larger than ${ReviewDiff.MAX_ARCHIVE_BYTES / 1048576} MB — too large to compare`);
|
|
34
|
+
const before = path_1.default.join(tmp, "a"), after = path_1.default.join(tmp, "b");
|
|
35
|
+
await fs_1.default.promises.mkdir(before);
|
|
36
|
+
await fs_1.default.promises.mkdir(after);
|
|
37
|
+
if (baseline)
|
|
38
|
+
await execFileAsync("tar", ["-xzf", baseline, "-C", before]);
|
|
39
|
+
await execFileAsync("tar", ["-xzf", pending, "-C", after]);
|
|
40
|
+
const a = baseline ? await ReviewDiff.walk(before) : new Map();
|
|
41
|
+
const b = await ReviewDiff.walk(after);
|
|
42
|
+
const result = await ReviewDiff.compare(before, after, a, b);
|
|
43
|
+
result.baseline = baseline ? { at: (await fs_1.default.promises.stat(baseline)).mtimeMs, version: result.versionBefore } : null;
|
|
44
|
+
ReviewDiff.cache.set(key, result);
|
|
45
|
+
if (ReviewDiff.cache.size > 10)
|
|
46
|
+
ReviewDiff.cache.delete(ReviewDiff.cache.keys().next().value);
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
await fs_1.default.promises.rm(tmp, { recursive: true, force: true }).catch(() => { });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
static sha(file) {
|
|
54
|
+
return new Promise((resolve, reject) => {
|
|
55
|
+
const h = crypto_1.default.createHash("sha256");
|
|
56
|
+
fs_1.default.createReadStream(file).on("data", d => h.update(d)).on("error", reject).on("end", () => resolve(h.digest("hex")));
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
static async walk(root) {
|
|
60
|
+
const out = new Map();
|
|
61
|
+
const visit = async (dir) => {
|
|
62
|
+
for (const d of await fs_1.default.promises.readdir(dir, { withFileTypes: true })) {
|
|
63
|
+
if (out.size >= ReviewDiff.MAX_FILES)
|
|
64
|
+
return;
|
|
65
|
+
const abs = path_1.default.join(dir, d.name);
|
|
66
|
+
const rel = path_1.default.relative(root, abs).split(path_1.default.sep).join("/");
|
|
67
|
+
if (d.isSymbolicLink()) {
|
|
68
|
+
const target = await fs_1.default.promises.readlink(abs);
|
|
69
|
+
out.set(rel, { kind: "symlink", size: 0, hash: "link:" + target, target });
|
|
70
|
+
}
|
|
71
|
+
else if (d.isDirectory()) {
|
|
72
|
+
await visit(abs);
|
|
73
|
+
}
|
|
74
|
+
else if (d.isFile()) {
|
|
75
|
+
const buf = await fs_1.default.promises.readFile(abs);
|
|
76
|
+
out.set(rel, { kind: "file", size: buf.length, hash: crypto_1.default.createHash("sha256").update(buf).digest("hex") });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
await visit(root);
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
static isText(buf) {
|
|
84
|
+
return !buf.subarray(0, 8192).includes(0);
|
|
85
|
+
}
|
|
86
|
+
static async compare(beforeRoot, afterRoot, a, b) {
|
|
87
|
+
const files = [];
|
|
88
|
+
let unchanged = 0, budget = ReviewDiff.MAX_TOTAL_DIFF, limited = null;
|
|
89
|
+
if (a.size >= ReviewDiff.MAX_FILES || b.size >= ReviewDiff.MAX_FILES)
|
|
90
|
+
limited = `more than ${ReviewDiff.MAX_FILES} files — the list is incomplete`;
|
|
91
|
+
const paths = Array.from(new Set([...a.keys(), ...b.keys()])).sort();
|
|
92
|
+
for (const p of paths) {
|
|
93
|
+
const x = a.get(p), y = b.get(p);
|
|
94
|
+
if (x && y && x.hash === y.hash) {
|
|
95
|
+
unchanged++;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const change = {
|
|
99
|
+
path: p,
|
|
100
|
+
status: !x ? "added" : !y ? "removed" : "modified",
|
|
101
|
+
kind: "text",
|
|
102
|
+
sizeBefore: x ? x.size : null,
|
|
103
|
+
sizeAfter: y ? y.size : null,
|
|
104
|
+
};
|
|
105
|
+
if (x?.kind === "symlink" || y?.kind === "symlink") {
|
|
106
|
+
change.kind = "symlink";
|
|
107
|
+
change.diff = `${x?.target ? "- → " + x.target + "\n" : ""}${y?.target ? "+ → " + y.target + "\n" : ""}`;
|
|
108
|
+
}
|
|
109
|
+
else if (ReviewDiff.SENSITIVE.some(re => re.test(p))) {
|
|
110
|
+
change.kind = "sensitive";
|
|
111
|
+
}
|
|
112
|
+
else if ((x?.size ?? 0) > ReviewDiff.MAX_TEXT_FILE || (y?.size ?? 0) > ReviewDiff.MAX_TEXT_FILE) {
|
|
113
|
+
change.kind = "large";
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
const fa = x ? path_1.default.join(beforeRoot, p) : null, fb = y ? path_1.default.join(afterRoot, p) : null;
|
|
117
|
+
const ba = fa ? await fs_1.default.promises.readFile(fa) : Buffer.alloc(0), bb = fb ? await fs_1.default.promises.readFile(fb) : Buffer.alloc(0);
|
|
118
|
+
if (!ReviewDiff.isText(ba) || !ReviewDiff.isText(bb))
|
|
119
|
+
change.kind = "binary";
|
|
120
|
+
else if (budget <= 0) {
|
|
121
|
+
limited = limited ?? "the diff is too large — some files show no content";
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
let d = await ReviewDiff.unified(fa, fb, p);
|
|
125
|
+
if (d.length > Math.min(ReviewDiff.MAX_FILE_DIFF, budget)) {
|
|
126
|
+
d = d.slice(0, Math.min(ReviewDiff.MAX_FILE_DIFF, budget));
|
|
127
|
+
d = d.slice(0, d.lastIndexOf("\n") + 1);
|
|
128
|
+
change.truncated = true;
|
|
129
|
+
}
|
|
130
|
+
budget -= d.length;
|
|
131
|
+
change.diff = d;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
files.push(change);
|
|
135
|
+
}
|
|
136
|
+
const pkgA = ReviewDiff.readJson(path_1.default.join(beforeRoot, "package.json"));
|
|
137
|
+
const pkgB = ReviewDiff.readJson(path_1.default.join(afterRoot, "package.json"));
|
|
138
|
+
const dependencies = [];
|
|
139
|
+
for (const section of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
|
|
140
|
+
const da = pkgA?.[section] ?? {}, db = pkgB?.[section] ?? {};
|
|
141
|
+
for (const name of Array.from(new Set([...Object.keys(da), ...Object.keys(db)])).sort()) {
|
|
142
|
+
const before = typeof da[name] === "string" ? da[name] : null, after = typeof db[name] === "string" ? db[name] : null;
|
|
143
|
+
if (before !== after)
|
|
144
|
+
dependencies.push({ name, section, before, after });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
baseline: null,
|
|
149
|
+
versionBefore: typeof pkgA?.version === "string" ? pkgA.version : null,
|
|
150
|
+
versionAfter: typeof pkgB?.version === "string" ? pkgB.version : null,
|
|
151
|
+
dependencies, files, unchanged, limited,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
static readJson(file) {
|
|
155
|
+
try {
|
|
156
|
+
return JSON.parse(fs_1.default.readFileSync(file, "utf-8"));
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
static async unified(a, b, rel) {
|
|
163
|
+
const args = ["-u", "--label", a ? "a/" + rel : "/dev/null", "--label", b ? "b/" + rel : "/dev/null", a ?? "/dev/null", b ?? "/dev/null"];
|
|
164
|
+
try {
|
|
165
|
+
const { stdout } = await execFileAsync("diff", args, { maxBuffer: 16 * 1024 * 1024 });
|
|
166
|
+
return stdout;
|
|
167
|
+
}
|
|
168
|
+
catch (e) {
|
|
169
|
+
if (e?.code === 1 && typeof e.stdout === "string")
|
|
170
|
+
return e.stdout;
|
|
171
|
+
throw e;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
exports.ReviewDiff = ReviewDiff;
|