openadminjs 0.1.23 → 0.2.0
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 +97 -16
- package/dist/adapt-package-manager.d.ts +3 -0
- package/dist/adapt-package-manager.js +115 -0
- package/dist/adapt-package-manager.test.d.ts +1 -0
- package/dist/adapt-package-manager.test.js +76 -0
- package/dist/cli.e2e.test.d.ts +1 -0
- package/dist/cli.e2e.test.js +87 -0
- package/dist/create-project.d.ts +31 -2
- package/dist/create-project.js +296 -102
- package/dist/create-project.test.js +180 -4
- package/dist/database-providers.integration.test.d.ts +1 -0
- package/dist/database-providers.integration.test.js +64 -0
- package/dist/db-commands.d.ts +20 -0
- package/dist/db-commands.js +75 -0
- package/dist/db-commands.test.d.ts +1 -0
- package/dist/db-commands.test.js +27 -0
- package/dist/detect-package-manager.d.ts +8 -0
- package/dist/detect-package-manager.js +37 -0
- package/dist/doctor.d.ts +13 -0
- package/dist/doctor.js +203 -0
- package/dist/doctor.test.d.ts +1 -0
- package/dist/doctor.test.js +102 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +233 -141
- package/dist/index.test.js +7 -3
- package/dist/render-schema.d.ts +20 -0
- package/dist/render-schema.js +37 -0
- package/dist/render-schema.test.d.ts +1 -0
- package/dist/render-schema.test.js +57 -0
- package/dist/secrets.d.ts +24 -0
- package/dist/secrets.js +93 -0
- package/dist/secrets.test.d.ts +1 -0
- package/dist/secrets.test.js +36 -0
- package/dist/security.d.ts +13 -0
- package/dist/security.js +168 -0
- package/dist/security.test.d.ts +1 -0
- package/dist/security.test.js +54 -0
- package/dist/validate-name.d.ts +33 -0
- package/dist/validate-name.js +206 -0
- package/dist/validate-name.test.d.ts +1 -0
- package/dist/validate-name.test.js +63 -0
- package/package.json +26 -1
- package/template/README.md +22 -3
- package/template/apps/admin/app/layout.tsx +2 -9
- package/template/apps/api/package.json +22 -20
- package/template/apps/api/src/app.module.test.ts +12 -0
- package/template/apps/api/src/app.module.ts +17 -11
- package/template/apps/api/src/common/json-field-codec.test.ts +76 -0
- package/template/apps/api/src/common/json-field-codec.ts +139 -0
- package/template/apps/api/src/common/openadmin-throttler.guard.ts +39 -0
- package/template/apps/api/src/common/prisma.service.test.ts +19 -0
- package/template/apps/api/src/common/prisma.service.ts +13 -0
- package/template/apps/api/src/common/request-logging.interceptor.test.ts +39 -0
- package/template/apps/api/src/common/request-logging.interceptor.ts +5 -3
- package/template/apps/api/src/graphql/admin-resources.args.ts +15 -0
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +20 -1
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.ts +15 -0
- package/template/apps/api/src/graphql/graphql-apollo-config.test.ts +26 -0
- package/template/apps/api/src/graphql/graphql-schema.test.ts +8 -0
- package/template/apps/api/src/graphql/graphql.module.ts +13 -1
- package/template/apps/api/src/queue/queue.module.ts +1 -8
- package/template/apps/api/src/queue/queue.processor.ts +26 -6
- package/template/apps/api/src/queue/queue.service.test.ts +33 -0
- package/template/apps/api/src/queue/queue.service.ts +30 -12
- package/template/package.json +19 -0
- package/template/prisma/migrations/20260713120000_add_user_oidc_key_and_category_order/migration.sql +11 -0
- package/template/prisma/seed.ts +30 -1
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
/**
|
|
3
|
+
* Generates a cryptographically secure secret suitable for JWT signing keys.
|
|
4
|
+
* Returns a URL-safe base64 string. 48 bytes → 64 base64url chars (~384 bits).
|
|
5
|
+
*/
|
|
6
|
+
export function generateSecret(bytes = 48) {
|
|
7
|
+
return randomBytes(bytes).toString("base64url");
|
|
8
|
+
}
|
|
9
|
+
const WEAK_SECRET_VALUES = new Set([
|
|
10
|
+
"secret",
|
|
11
|
+
"changeme",
|
|
12
|
+
"change-me",
|
|
13
|
+
"change-me-to-a-long-random-secret",
|
|
14
|
+
"change-me-too",
|
|
15
|
+
"password",
|
|
16
|
+
"jwt",
|
|
17
|
+
"jwt-secret",
|
|
18
|
+
"test",
|
|
19
|
+
"test-jwt-secret",
|
|
20
|
+
"test-jwt-refresh-secret",
|
|
21
|
+
"dev",
|
|
22
|
+
"development"
|
|
23
|
+
]);
|
|
24
|
+
/** Minimum acceptable secret length (characters). */
|
|
25
|
+
export const MIN_SECRET_LENGTH = 32;
|
|
26
|
+
/**
|
|
27
|
+
* Estimates Shannon entropy (bits) of a string. Used to flag low-entropy
|
|
28
|
+
* secrets such as `aaaaaaaa...` that pass a naive length check.
|
|
29
|
+
*/
|
|
30
|
+
export function shannonEntropyBits(value) {
|
|
31
|
+
if (!value)
|
|
32
|
+
return 0;
|
|
33
|
+
const counts = new Map();
|
|
34
|
+
for (const ch of value)
|
|
35
|
+
counts.set(ch, (counts.get(ch) ?? 0) + 1);
|
|
36
|
+
let bitsPerChar = 0;
|
|
37
|
+
for (const count of counts.values()) {
|
|
38
|
+
const p = count / value.length;
|
|
39
|
+
bitsPerChar -= p * Math.log2(p);
|
|
40
|
+
}
|
|
41
|
+
return bitsPerChar * value.length;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Returns whether a secret is weak/predictable and why. A secret is weak when
|
|
45
|
+
* it is empty, a known placeholder, too short, or has insufficient entropy.
|
|
46
|
+
*/
|
|
47
|
+
export function inspectSecret(value, label = "secret") {
|
|
48
|
+
const v = (value ?? "").trim();
|
|
49
|
+
if (!v)
|
|
50
|
+
return { weak: true, reason: `${label} is empty` };
|
|
51
|
+
if (WEAK_SECRET_VALUES.has(v.toLowerCase())) {
|
|
52
|
+
return { weak: true, reason: `${label} is a well-known default/placeholder value` };
|
|
53
|
+
}
|
|
54
|
+
if (v.length < MIN_SECRET_LENGTH) {
|
|
55
|
+
return { weak: true, reason: `${label} is shorter than ${MIN_SECRET_LENGTH} characters` };
|
|
56
|
+
}
|
|
57
|
+
if (shannonEntropyBits(v) < 64) {
|
|
58
|
+
return { weak: true, reason: `${label} has insufficient entropy` };
|
|
59
|
+
}
|
|
60
|
+
return { weak: false };
|
|
61
|
+
}
|
|
62
|
+
export function isWeakSecret(value) {
|
|
63
|
+
return inspectSecret(value).weak;
|
|
64
|
+
}
|
|
65
|
+
const COMMON_WEAK_PASSWORDS = new Set([
|
|
66
|
+
"admin",
|
|
67
|
+
"administrator",
|
|
68
|
+
"password",
|
|
69
|
+
"passw0rd",
|
|
70
|
+
"123456",
|
|
71
|
+
"12345678",
|
|
72
|
+
"changeme",
|
|
73
|
+
"change-me",
|
|
74
|
+
"letmein",
|
|
75
|
+
"welcome",
|
|
76
|
+
"qwerty",
|
|
77
|
+
"root",
|
|
78
|
+
"test",
|
|
79
|
+
"secret"
|
|
80
|
+
]);
|
|
81
|
+
export const MIN_PASSWORD_LENGTH = 8;
|
|
82
|
+
export function inspectPassword(value) {
|
|
83
|
+
const v = value ?? "";
|
|
84
|
+
if (!v)
|
|
85
|
+
return { weak: true, reason: "password is empty" };
|
|
86
|
+
if (COMMON_WEAK_PASSWORDS.has(v.toLowerCase())) {
|
|
87
|
+
return { weak: true, reason: "password is a common/guessable value" };
|
|
88
|
+
}
|
|
89
|
+
if (v.length < MIN_PASSWORD_LENGTH) {
|
|
90
|
+
return { weak: true, reason: `password is shorter than ${MIN_PASSWORD_LENGTH} characters` };
|
|
91
|
+
}
|
|
92
|
+
return { weak: false };
|
|
93
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { generateSecret, inspectPassword, inspectSecret, isWeakSecret, MIN_SECRET_LENGTH, shannonEntropyBits } from "./secrets.js";
|
|
3
|
+
describe("generateSecret", () => {
|
|
4
|
+
it("produces high-entropy, sufficiently long, unique secrets", () => {
|
|
5
|
+
const a = generateSecret();
|
|
6
|
+
const b = generateSecret();
|
|
7
|
+
expect(a).not.toBe(b);
|
|
8
|
+
expect(a.length).toBeGreaterThanOrEqual(MIN_SECRET_LENGTH);
|
|
9
|
+
expect(isWeakSecret(a)).toBe(false);
|
|
10
|
+
expect(shannonEntropyBits(a)).toBeGreaterThan(64);
|
|
11
|
+
});
|
|
12
|
+
it("is URL-safe base64 (no +, /, =)", () => {
|
|
13
|
+
expect(generateSecret()).toMatch(/^[A-Za-z0-9_-]+$/);
|
|
14
|
+
});
|
|
15
|
+
});
|
|
16
|
+
describe("inspectSecret", () => {
|
|
17
|
+
it("flags empty, placeholder, short and low-entropy secrets", () => {
|
|
18
|
+
expect(inspectSecret("").weak).toBe(true);
|
|
19
|
+
expect(inspectSecret("change-me-to-a-long-random-secret").weak).toBe(true);
|
|
20
|
+
expect(inspectSecret("secret").weak).toBe(true);
|
|
21
|
+
expect(inspectSecret("short").weak).toBe(true);
|
|
22
|
+
expect(inspectSecret("a".repeat(40)).weak).toBe(true);
|
|
23
|
+
});
|
|
24
|
+
it("accepts a real generated secret", () => {
|
|
25
|
+
expect(inspectSecret(generateSecret()).weak).toBe(false);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
describe("inspectPassword", () => {
|
|
29
|
+
it("rejects common passwords and short values", () => {
|
|
30
|
+
for (const p of ["admin", "password", "123456", "changeme"]) {
|
|
31
|
+
expect(inspectPassword(p).weak).toBe(true);
|
|
32
|
+
}
|
|
33
|
+
expect(inspectPassword("short").weak).toBe(true);
|
|
34
|
+
expect(inspectPassword("a-good-enough-passphrase").weak).toBe(false);
|
|
35
|
+
});
|
|
36
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export type Severity = "info" | "warning" | "critical";
|
|
2
|
+
export type Finding = {
|
|
3
|
+
id: string;
|
|
4
|
+
severity: Severity;
|
|
5
|
+
message: string;
|
|
6
|
+
};
|
|
7
|
+
export type SecurityReport = {
|
|
8
|
+
findings: Finding[];
|
|
9
|
+
ok: boolean;
|
|
10
|
+
};
|
|
11
|
+
export declare function runSecurityChecks(cwd: string, opts?: {
|
|
12
|
+
skipNetwork?: boolean;
|
|
13
|
+
}): SecurityReport;
|
package/dist/security.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { inspectPassword, inspectSecret } from "./secrets.js";
|
|
5
|
+
function readFileSafe(path) {
|
|
6
|
+
try {
|
|
7
|
+
return readFileSync(path, "utf8");
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function parseEnv(content) {
|
|
14
|
+
const env = {};
|
|
15
|
+
for (const line of content.split(/\r?\n/)) {
|
|
16
|
+
const trimmed = line.trim();
|
|
17
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
18
|
+
continue;
|
|
19
|
+
const eq = trimmed.indexOf("=");
|
|
20
|
+
if (eq < 0)
|
|
21
|
+
continue;
|
|
22
|
+
const key = trimmed.slice(0, eq).trim();
|
|
23
|
+
let value = trimmed.slice(eq + 1).trim();
|
|
24
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
|
25
|
+
value = value.slice(1, -1);
|
|
26
|
+
}
|
|
27
|
+
env[key] = value;
|
|
28
|
+
}
|
|
29
|
+
return env;
|
|
30
|
+
}
|
|
31
|
+
function gitignoreIgnoresEnv(cwd) {
|
|
32
|
+
const gi = readFileSafe(join(cwd, ".gitignore"));
|
|
33
|
+
if (!gi)
|
|
34
|
+
return false;
|
|
35
|
+
const lines = gi.split(/\r?\n/).map((l) => l.trim());
|
|
36
|
+
return lines.includes(".env") || lines.includes(".env.*") || lines.includes("*.env");
|
|
37
|
+
}
|
|
38
|
+
function scanForHardcodedSecrets(cwd) {
|
|
39
|
+
const hits = [];
|
|
40
|
+
const roots = [join(cwd, "apps"), join(cwd, "packages")].filter((d) => existsSync(d));
|
|
41
|
+
const patterns = [
|
|
42
|
+
[/(?:jwt[_-]?secret|refresh[_-]?secret)\s*[:=]\s*["'][^"']{6,}["']/i, "hardcoded JWT secret"],
|
|
43
|
+
[/(?:password|passwd)\s*[:=]\s*["'][^"']{4,}["']/i, "hardcoded password"],
|
|
44
|
+
[/(?:api[_-]?key|secret[_-]?key|access[_-]?token)\s*[:=]\s*["'][^"']{8,}["']/i, "hardcoded API key/token"]
|
|
45
|
+
];
|
|
46
|
+
const stack = [...roots];
|
|
47
|
+
let scanned = 0;
|
|
48
|
+
while (stack.length && scanned < 4000) {
|
|
49
|
+
const current = stack.pop();
|
|
50
|
+
let entries;
|
|
51
|
+
try {
|
|
52
|
+
entries = readdirSync(current, { withFileTypes: true });
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
for (const entry of entries) {
|
|
58
|
+
const path = join(current, entry.name);
|
|
59
|
+
if (entry.isDirectory()) {
|
|
60
|
+
if (["node_modules", ".next", "dist", ".turbo", ".git", "storybook-static", "coverage", "build", "out"].includes(entry.name)) {
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
stack.push(path);
|
|
64
|
+
}
|
|
65
|
+
else if (/\.(ts|tsx|js|jsx|mts|cts)$/.test(entry.name) &&
|
|
66
|
+
!/\.(test|spec)\./.test(entry.name) &&
|
|
67
|
+
!/\.min\.js$/.test(entry.name)) {
|
|
68
|
+
scanned++;
|
|
69
|
+
const content = readFileSafe(path);
|
|
70
|
+
if (!content)
|
|
71
|
+
continue;
|
|
72
|
+
for (const [re, label] of patterns) {
|
|
73
|
+
if (re.test(content) && !/process\.env/.test(content.match(re)?.[0] ?? "")) {
|
|
74
|
+
hits.push(`${label} in ${path.replace(cwd + "/", "")}`);
|
|
75
|
+
break;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return hits;
|
|
82
|
+
}
|
|
83
|
+
export function runSecurityChecks(cwd, opts = {}) {
|
|
84
|
+
const findings = [];
|
|
85
|
+
const add = (id, severity, message) => findings.push({ id, severity, message });
|
|
86
|
+
const envRaw = readFileSafe(join(cwd, "apps", "api", ".env"));
|
|
87
|
+
const env = envRaw ? parseEnv(envRaw) : undefined;
|
|
88
|
+
if (!env) {
|
|
89
|
+
add("env-missing", "warning", "apps/api/.env not found — cannot assess runtime secrets.");
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
const jwt = inspectSecret(env.JWT_SECRET, "JWT_SECRET");
|
|
93
|
+
if (jwt.weak)
|
|
94
|
+
add("jwt-secret", "critical", jwt.reason);
|
|
95
|
+
const jwtR = inspectSecret(env.JWT_REFRESH_SECRET, "JWT_REFRESH_SECRET");
|
|
96
|
+
if (jwtR.weak)
|
|
97
|
+
add("jwt-refresh-secret", "critical", jwtR.reason);
|
|
98
|
+
if (env.JWT_SECRET && env.JWT_SECRET === env.JWT_REFRESH_SECRET) {
|
|
99
|
+
add("jwt-identical", "critical", "JWT_SECRET and JWT_REFRESH_SECRET must not be identical.");
|
|
100
|
+
}
|
|
101
|
+
if (env.SUPERADMIN_PASSWORD) {
|
|
102
|
+
const pw = inspectPassword(env.SUPERADMIN_PASSWORD);
|
|
103
|
+
if (pw.weak)
|
|
104
|
+
add("admin-password", "critical", pw.reason);
|
|
105
|
+
}
|
|
106
|
+
if (!jwt.weak && !jwtR.weak)
|
|
107
|
+
add("jwt-ok", "info", "JWT secrets have sufficient length and entropy.");
|
|
108
|
+
}
|
|
109
|
+
// .env handling
|
|
110
|
+
if (!gitignoreIgnoresEnv(cwd)) {
|
|
111
|
+
add("gitignore-env", "critical", ".env is not excluded by .gitignore.");
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
add("gitignore-env-ok", "info", ".env is excluded by .gitignore.");
|
|
115
|
+
}
|
|
116
|
+
if (existsSync(join(cwd, ".git"))) {
|
|
117
|
+
const tracked = spawnSync("git", ["ls-files", "--error-unmatch", "apps/api/.env"], { cwd, stdio: "ignore" });
|
|
118
|
+
if (tracked.status === 0)
|
|
119
|
+
add("env-tracked", "critical", "apps/api/.env is tracked by Git. Untrack it and rotate all secrets.");
|
|
120
|
+
}
|
|
121
|
+
// npm tarball exposure — only relevant if the package is publishable
|
|
122
|
+
const rootPkgRaw = readFileSafe(join(cwd, "package.json"));
|
|
123
|
+
if (rootPkgRaw) {
|
|
124
|
+
try {
|
|
125
|
+
const pkg = JSON.parse(rootPkgRaw);
|
|
126
|
+
if (pkg.private !== true && pkg.files && pkg.files.some((f) => f.includes(".env"))) {
|
|
127
|
+
add("npm-env", "critical", "package.json `files` would publish a .env file.");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
/* ignore */
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
// production config scans
|
|
135
|
+
const mainCandidates = [join(cwd, "apps", "api", "src", "main.ts")];
|
|
136
|
+
for (const file of mainCandidates) {
|
|
137
|
+
const content = readFileSafe(file);
|
|
138
|
+
if (!content)
|
|
139
|
+
continue;
|
|
140
|
+
if (/origin\s*:\s*["']\*["']/.test(content) && /credentials\s*:\s*true/.test(content)) {
|
|
141
|
+
add("cors-credentials", "critical", "CORS is configured with origin '*' together with credentials.");
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const hardcoded = scanForHardcodedSecrets(cwd);
|
|
145
|
+
for (const hit of hardcoded)
|
|
146
|
+
add("hardcoded-secret", "warning", hit);
|
|
147
|
+
// dependency audit (best-effort, network-dependent)
|
|
148
|
+
if (!opts.skipNetwork && existsSync(join(cwd, "node_modules"))) {
|
|
149
|
+
const audit = spawnSync("npm", ["audit", "--production", "--audit-level=high", "--json"], { cwd, encoding: "utf8" });
|
|
150
|
+
if (audit.stdout) {
|
|
151
|
+
try {
|
|
152
|
+
const parsed = JSON.parse(audit.stdout);
|
|
153
|
+
const vulns = parsed.metadata?.vulnerabilities ?? {};
|
|
154
|
+
const high = (vulns.high ?? 0) + (vulns.critical ?? 0);
|
|
155
|
+
if (high > 0)
|
|
156
|
+
add("dependency-audit", "warning", `${high} high/critical dependency vulnerabilities reported by npm audit.`);
|
|
157
|
+
else
|
|
158
|
+
add("dependency-audit", "info", "No high/critical dependency vulnerabilities reported.");
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
/* ignore audit parse errors */
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
add("https-guidance", "info", "In production, terminate TLS at a reverse proxy and set secure cookie flags + trust proxy.");
|
|
166
|
+
const ok = !findings.some((f) => f.severity === "critical");
|
|
167
|
+
return { findings, ok };
|
|
168
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
5
|
+
import { runSecurityChecks } from "./security.js";
|
|
6
|
+
import { generateSecret } from "./secrets.js";
|
|
7
|
+
let dir;
|
|
8
|
+
function sev(findings, id) {
|
|
9
|
+
return findings.find((f) => f.id === id)?.severity;
|
|
10
|
+
}
|
|
11
|
+
function writeEnv(root, content) {
|
|
12
|
+
mkdirSync(join(root, "apps", "api"), { recursive: true });
|
|
13
|
+
writeFileSync(join(root, "apps", "api", ".env"), content);
|
|
14
|
+
}
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
dir = mkdtempSync(join(tmpdir(), "oaj-sec-"));
|
|
17
|
+
});
|
|
18
|
+
afterEach(() => {
|
|
19
|
+
rmSync(dir, { recursive: true, force: true });
|
|
20
|
+
});
|
|
21
|
+
describe("runSecurityChecks", () => {
|
|
22
|
+
it("flags weak/identical JWT secrets and weak admin password as critical", () => {
|
|
23
|
+
writeEnv(dir, "JWT_SECRET=secret\nJWT_REFRESH_SECRET=secret\nSUPERADMIN_PASSWORD=admin\n");
|
|
24
|
+
writeFileSync(join(dir, ".gitignore"), ".env\n");
|
|
25
|
+
const { findings, ok } = runSecurityChecks(dir, { skipNetwork: true });
|
|
26
|
+
expect(sev(findings, "jwt-secret")).toBe("critical");
|
|
27
|
+
expect(sev(findings, "jwt-identical")).toBe("critical");
|
|
28
|
+
expect(sev(findings, "admin-password")).toBe("critical");
|
|
29
|
+
expect(ok).toBe(false);
|
|
30
|
+
});
|
|
31
|
+
it("flags missing .env exclusion in .gitignore as critical", () => {
|
|
32
|
+
writeEnv(dir, `JWT_SECRET=${generateSecret()}\nJWT_REFRESH_SECRET=${generateSecret()}\n`);
|
|
33
|
+
writeFileSync(join(dir, ".gitignore"), "node_modules\n");
|
|
34
|
+
const { findings, ok } = runSecurityChecks(dir, { skipNetwork: true });
|
|
35
|
+
expect(sev(findings, "gitignore-env")).toBe("critical");
|
|
36
|
+
expect(ok).toBe(false);
|
|
37
|
+
});
|
|
38
|
+
it("passes for a hardened project", () => {
|
|
39
|
+
writeEnv(dir, `JWT_SECRET=${generateSecret()}\nJWT_REFRESH_SECRET=${generateSecret()}\nSUPERADMIN_PASSWORD=a-strong-passphrase\n`);
|
|
40
|
+
writeFileSync(join(dir, ".gitignore"), ".env\n.env.*\n!.env.example\n");
|
|
41
|
+
const { findings, ok } = runSecurityChecks(dir, { skipNetwork: true });
|
|
42
|
+
expect(ok).toBe(true);
|
|
43
|
+
expect(sev(findings, "jwt-ok")).toBe("info");
|
|
44
|
+
});
|
|
45
|
+
it("detects CORS '*' with credentials", () => {
|
|
46
|
+
writeEnv(dir, `JWT_SECRET=${generateSecret()}\nJWT_REFRESH_SECRET=${generateSecret()}\n`);
|
|
47
|
+
writeFileSync(join(dir, ".gitignore"), ".env\n");
|
|
48
|
+
mkdirSync(join(dir, "apps", "api", "src"), { recursive: true });
|
|
49
|
+
writeFileSync(join(dir, "apps", "api", "src", "main.ts"), "app.enableCors({ origin: '*', credentials: true });\n");
|
|
50
|
+
const { findings, ok } = runSecurityChecks(dir, { skipNetwork: true });
|
|
51
|
+
expect(sev(findings, "cors-credentials")).toBe("critical");
|
|
52
|
+
expect(ok).toBe(false);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export declare class InvalidNameError extends Error {
|
|
2
|
+
constructor(message: string);
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* Documented valid input format:
|
|
6
|
+
* - must start with a letter
|
|
7
|
+
* - may contain letters, numbers, spaces, hyphens and underscores
|
|
8
|
+
* - separators are collapsed when converting to Pascal/camel/kebab case
|
|
9
|
+
*/
|
|
10
|
+
export declare const VALID_NAME_DESCRIPTION = "Names must start with a letter and contain only letters, numbers, spaces, hyphens or underscores.";
|
|
11
|
+
export declare function toPascalCase(input: string): string;
|
|
12
|
+
export declare function toCamelCase(input: string): string;
|
|
13
|
+
export declare function toKebabCase(input: string): string;
|
|
14
|
+
/**
|
|
15
|
+
* Validates a user-supplied resource/plugin/field name. Throws InvalidNameError
|
|
16
|
+
* on any unsafe or invalid input. Returns the trimmed raw value on success.
|
|
17
|
+
*
|
|
18
|
+
* Rejects: empty, `.`/`..`, path separators, absolute paths, null bytes,
|
|
19
|
+
* control characters, shell metacharacters, reserved OS names, reserved
|
|
20
|
+
* identifiers, and names that normalize to an empty string.
|
|
21
|
+
*/
|
|
22
|
+
export declare function validateName(raw: string | undefined, kind?: string): string;
|
|
23
|
+
/**
|
|
24
|
+
* Validates a plugin id. Plugin ids follow reverse-DNS style and may contain
|
|
25
|
+
* dots (e.g. `com.example.my-plugin`), but must not enable path traversal or
|
|
26
|
+
* shell injection. Returns the trimmed value on success.
|
|
27
|
+
*/
|
|
28
|
+
export declare function validatePluginId(raw: string | undefined): string;
|
|
29
|
+
/**
|
|
30
|
+
* Resolves `child` against `baseDir` and guarantees the result stays inside
|
|
31
|
+
* `baseDir`. Throws on any traversal attempt. Returns the resolved path.
|
|
32
|
+
*/
|
|
33
|
+
export declare function assertInsideDir(baseDir: string, child: string): string;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { relative, resolve, isAbsolute } from "node:path";
|
|
2
|
+
/**
|
|
3
|
+
* Reserved Windows device names that must never be used as file/dir names.
|
|
4
|
+
* Rejected case-insensitively, with or without an extension.
|
|
5
|
+
*/
|
|
6
|
+
const RESERVED_NAMES = new Set([
|
|
7
|
+
"con",
|
|
8
|
+
"prn",
|
|
9
|
+
"aux",
|
|
10
|
+
"nul",
|
|
11
|
+
"com1",
|
|
12
|
+
"com2",
|
|
13
|
+
"com3",
|
|
14
|
+
"com4",
|
|
15
|
+
"com5",
|
|
16
|
+
"com6",
|
|
17
|
+
"com7",
|
|
18
|
+
"com8",
|
|
19
|
+
"com9",
|
|
20
|
+
"lpt1",
|
|
21
|
+
"lpt2",
|
|
22
|
+
"lpt3",
|
|
23
|
+
"lpt4",
|
|
24
|
+
"lpt5",
|
|
25
|
+
"lpt6",
|
|
26
|
+
"lpt7",
|
|
27
|
+
"lpt8",
|
|
28
|
+
"lpt9"
|
|
29
|
+
]);
|
|
30
|
+
/**
|
|
31
|
+
* TypeScript reserved words / keywords that would break generated identifiers
|
|
32
|
+
* if used verbatim as class or variable names.
|
|
33
|
+
*/
|
|
34
|
+
const RESERVED_IDENTIFIERS = new Set([
|
|
35
|
+
"class",
|
|
36
|
+
"function",
|
|
37
|
+
"const",
|
|
38
|
+
"let",
|
|
39
|
+
"var",
|
|
40
|
+
"return",
|
|
41
|
+
"if",
|
|
42
|
+
"else",
|
|
43
|
+
"for",
|
|
44
|
+
"while",
|
|
45
|
+
"do",
|
|
46
|
+
"switch",
|
|
47
|
+
"case",
|
|
48
|
+
"default",
|
|
49
|
+
"break",
|
|
50
|
+
"continue",
|
|
51
|
+
"new",
|
|
52
|
+
"delete",
|
|
53
|
+
"typeof",
|
|
54
|
+
"instanceof",
|
|
55
|
+
"void",
|
|
56
|
+
"this",
|
|
57
|
+
"super",
|
|
58
|
+
"extends",
|
|
59
|
+
"implements",
|
|
60
|
+
"interface",
|
|
61
|
+
"enum",
|
|
62
|
+
"export",
|
|
63
|
+
"import",
|
|
64
|
+
"package",
|
|
65
|
+
"private",
|
|
66
|
+
"protected",
|
|
67
|
+
"public",
|
|
68
|
+
"static",
|
|
69
|
+
"yield",
|
|
70
|
+
"await",
|
|
71
|
+
"async",
|
|
72
|
+
"null",
|
|
73
|
+
"true",
|
|
74
|
+
"false",
|
|
75
|
+
"undefined"
|
|
76
|
+
]);
|
|
77
|
+
export class InvalidNameError extends Error {
|
|
78
|
+
constructor(message) {
|
|
79
|
+
super(message);
|
|
80
|
+
this.name = "InvalidNameError";
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Documented valid input format:
|
|
85
|
+
* - must start with a letter
|
|
86
|
+
* - may contain letters, numbers, spaces, hyphens and underscores
|
|
87
|
+
* - separators are collapsed when converting to Pascal/camel/kebab case
|
|
88
|
+
*/
|
|
89
|
+
export const VALID_NAME_DESCRIPTION = "Names must start with a letter and contain only letters, numbers, spaces, hyphens or underscores.";
|
|
90
|
+
function splitWords(input) {
|
|
91
|
+
return input
|
|
92
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
93
|
+
.replace(/[^a-zA-Z0-9]+/g, " ")
|
|
94
|
+
.trim()
|
|
95
|
+
.split(/\s+/)
|
|
96
|
+
.filter(Boolean);
|
|
97
|
+
}
|
|
98
|
+
export function toPascalCase(input) {
|
|
99
|
+
return splitWords(input)
|
|
100
|
+
.map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
|
|
101
|
+
.join("");
|
|
102
|
+
}
|
|
103
|
+
export function toCamelCase(input) {
|
|
104
|
+
const pascal = toPascalCase(input);
|
|
105
|
+
return pascal ? pascal.charAt(0).toLowerCase() + pascal.slice(1) : "";
|
|
106
|
+
}
|
|
107
|
+
export function toKebabCase(input) {
|
|
108
|
+
return splitWords(input)
|
|
109
|
+
.map((w) => w.toLowerCase())
|
|
110
|
+
.join("-");
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Validates a user-supplied resource/plugin/field name. Throws InvalidNameError
|
|
114
|
+
* on any unsafe or invalid input. Returns the trimmed raw value on success.
|
|
115
|
+
*
|
|
116
|
+
* Rejects: empty, `.`/`..`, path separators, absolute paths, null bytes,
|
|
117
|
+
* control characters, shell metacharacters, reserved OS names, reserved
|
|
118
|
+
* identifiers, and names that normalize to an empty string.
|
|
119
|
+
*/
|
|
120
|
+
export function validateName(raw, kind = "name") {
|
|
121
|
+
if (raw == null)
|
|
122
|
+
throw new InvalidNameError(`A ${kind} is required.`);
|
|
123
|
+
const value = String(raw).trim();
|
|
124
|
+
if (!value)
|
|
125
|
+
throw new InvalidNameError(`A ${kind} is required.`);
|
|
126
|
+
if (value === "." || value === "..") {
|
|
127
|
+
throw new InvalidNameError(`"${value}" is not a valid ${kind}.`);
|
|
128
|
+
}
|
|
129
|
+
if (value.includes("\0")) {
|
|
130
|
+
throw new InvalidNameError(`${kind} must not contain null bytes.`);
|
|
131
|
+
}
|
|
132
|
+
// eslint-disable-next-line no-control-regex
|
|
133
|
+
if (/[\u0000-\u001f\u007f]/.test(value)) {
|
|
134
|
+
throw new InvalidNameError(`${kind} must not contain control characters.`);
|
|
135
|
+
}
|
|
136
|
+
if (/[/\\]/.test(value)) {
|
|
137
|
+
throw new InvalidNameError(`${kind} must not contain path separators ("/" or "\\").`);
|
|
138
|
+
}
|
|
139
|
+
if (isAbsolute(value)) {
|
|
140
|
+
throw new InvalidNameError(`${kind} must not be an absolute path.`);
|
|
141
|
+
}
|
|
142
|
+
if (/[;&|`$(){}<>*?!"'\[\]#~]/.test(value)) {
|
|
143
|
+
throw new InvalidNameError(`${kind} must not contain shell metacharacters.`);
|
|
144
|
+
}
|
|
145
|
+
if (!/^[A-Za-z]/.test(value)) {
|
|
146
|
+
throw new InvalidNameError(`${kind} must start with a letter. ${VALID_NAME_DESCRIPTION}`);
|
|
147
|
+
}
|
|
148
|
+
if (!/^[A-Za-z0-9 _-]+$/.test(value)) {
|
|
149
|
+
throw new InvalidNameError(`${kind} contains invalid characters. ${VALID_NAME_DESCRIPTION}`);
|
|
150
|
+
}
|
|
151
|
+
const base = value.toLowerCase().split(".")[0] ?? "";
|
|
152
|
+
if (RESERVED_NAMES.has(base)) {
|
|
153
|
+
throw new InvalidNameError(`"${value}" is a reserved operating-system name.`);
|
|
154
|
+
}
|
|
155
|
+
if (RESERVED_IDENTIFIERS.has(value.toLowerCase())) {
|
|
156
|
+
throw new InvalidNameError(`"${value}" is a reserved keyword and cannot be used as a ${kind}.`);
|
|
157
|
+
}
|
|
158
|
+
if (!toPascalCase(value)) {
|
|
159
|
+
throw new InvalidNameError(`"${value}" cannot be converted into a valid identifier.`);
|
|
160
|
+
}
|
|
161
|
+
return value;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Validates a plugin id. Plugin ids follow reverse-DNS style and may contain
|
|
165
|
+
* dots (e.g. `com.example.my-plugin`), but must not enable path traversal or
|
|
166
|
+
* shell injection. Returns the trimmed value on success.
|
|
167
|
+
*/
|
|
168
|
+
export function validatePluginId(raw) {
|
|
169
|
+
if (raw == null)
|
|
170
|
+
throw new InvalidNameError("A plugin id is required.");
|
|
171
|
+
const value = String(raw).trim();
|
|
172
|
+
if (!value)
|
|
173
|
+
throw new InvalidNameError("A plugin id is required.");
|
|
174
|
+
if (value.includes("\0"))
|
|
175
|
+
throw new InvalidNameError("plugin id must not contain null bytes.");
|
|
176
|
+
// eslint-disable-next-line no-control-regex
|
|
177
|
+
if (/[\u0000-\u001f\u007f]/.test(value))
|
|
178
|
+
throw new InvalidNameError("plugin id must not contain control characters.");
|
|
179
|
+
if (/[/\\]/.test(value))
|
|
180
|
+
throw new InvalidNameError('plugin id must not contain path separators ("/" or "\\").');
|
|
181
|
+
if (isAbsolute(value))
|
|
182
|
+
throw new InvalidNameError("plugin id must not be an absolute path.");
|
|
183
|
+
if (value.includes(".."))
|
|
184
|
+
throw new InvalidNameError("plugin id must not contain consecutive dots.");
|
|
185
|
+
if (/[;&|`$(){}<>*?!"'\[\]#~]/.test(value))
|
|
186
|
+
throw new InvalidNameError("plugin id must not contain shell metacharacters.");
|
|
187
|
+
if (!/^[A-Za-z][A-Za-z0-9]*(?:[.-][A-Za-z0-9]+)*$/.test(value)) {
|
|
188
|
+
throw new InvalidNameError("plugin id must start with a letter and use only letters, numbers, dots and hyphens (e.g. com.example.my-plugin).");
|
|
189
|
+
}
|
|
190
|
+
return value;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Resolves `child` against `baseDir` and guarantees the result stays inside
|
|
194
|
+
* `baseDir`. Throws on any traversal attempt. Returns the resolved path.
|
|
195
|
+
*/
|
|
196
|
+
export function assertInsideDir(baseDir, child) {
|
|
197
|
+
const base = resolve(baseDir);
|
|
198
|
+
const target = resolve(base, child);
|
|
199
|
+
const rel = relative(base, target);
|
|
200
|
+
if (rel === "" || rel === ".")
|
|
201
|
+
return target;
|
|
202
|
+
if (rel.startsWith("..") || isAbsolute(rel)) {
|
|
203
|
+
throw new InvalidNameError(`Refusing to write outside the project directory: ${target}`);
|
|
204
|
+
}
|
|
205
|
+
return target;
|
|
206
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { assertInsideDir, InvalidNameError, toCamelCase, toKebabCase, toPascalCase, validateName, validatePluginId } from "./validate-name.js";
|
|
3
|
+
describe("case conversion", () => {
|
|
4
|
+
it("converts to PascalCase / camelCase / kebab-case", () => {
|
|
5
|
+
expect(toPascalCase("order item")).toBe("OrderItem");
|
|
6
|
+
expect(toPascalCase("order-item")).toBe("OrderItem");
|
|
7
|
+
expect(toPascalCase("OrderItem")).toBe("OrderItem");
|
|
8
|
+
expect(toCamelCase("order-item")).toBe("orderItem");
|
|
9
|
+
expect(toKebabCase("OrderItem")).toBe("order-item");
|
|
10
|
+
expect(toKebabCase("Order Item")).toBe("order-item");
|
|
11
|
+
});
|
|
12
|
+
});
|
|
13
|
+
describe("validateName - rejects unsafe input", () => {
|
|
14
|
+
const bad = [
|
|
15
|
+
"../admin",
|
|
16
|
+
"../../outside",
|
|
17
|
+
"foo/bar",
|
|
18
|
+
"foo\\bar",
|
|
19
|
+
'"; process.exit()',
|
|
20
|
+
"class",
|
|
21
|
+
"CON",
|
|
22
|
+
".",
|
|
23
|
+
"..",
|
|
24
|
+
"",
|
|
25
|
+
" ",
|
|
26
|
+
"/etc/passwd",
|
|
27
|
+
"foo\0bar",
|
|
28
|
+
"1name",
|
|
29
|
+
"-name"
|
|
30
|
+
];
|
|
31
|
+
for (const input of bad) {
|
|
32
|
+
it(`rejects ${JSON.stringify(input)}`, () => {
|
|
33
|
+
expect(() => validateName(input, "resource")).toThrow(InvalidNameError);
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
describe("validateName - accepts valid input", () => {
|
|
38
|
+
for (const input of ["Post", "order-item", "order_item", "BlogPost", "user2"]) {
|
|
39
|
+
it(`accepts ${JSON.stringify(input)}`, () => {
|
|
40
|
+
expect(validateName(input, "resource")).toBe(input.trim());
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
describe("validatePluginId", () => {
|
|
45
|
+
it("accepts reverse-DNS style ids", () => {
|
|
46
|
+
expect(validatePluginId("com.example.my-plugin")).toBe("com.example.my-plugin");
|
|
47
|
+
expect(validatePluginId("seo")).toBe("seo");
|
|
48
|
+
});
|
|
49
|
+
it("rejects traversal and injection attempts", () => {
|
|
50
|
+
for (const bad of ["../evil", "a/../b", "foo/bar", "a..b", "$(x)", "a;b", ".hidden", "1abc"]) {
|
|
51
|
+
expect(() => validatePluginId(bad), bad).toThrow(InvalidNameError);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
describe("assertInsideDir", () => {
|
|
56
|
+
it("allows paths inside the base directory", () => {
|
|
57
|
+
expect(() => assertInsideDir("/tmp/proj", "apps/api/x.ts")).not.toThrow();
|
|
58
|
+
});
|
|
59
|
+
it("rejects traversal outside the base directory", () => {
|
|
60
|
+
expect(() => assertInsideDir("/tmp/proj", "../../etc/passwd")).toThrow(InvalidNameError);
|
|
61
|
+
expect(() => assertInsideDir("/tmp/proj", "/etc/passwd")).toThrow(InvalidNameError);
|
|
62
|
+
});
|
|
63
|
+
});
|