Files
vHost/deploy/panel-account-security-verify.mjs
T

409 lines
28 KiB
JavaScript

import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
const panelURL = process.env.SEA_PANEL_URL?.trim();
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL) {
console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_CONSOLE_URL are required.');
process.exit(2);
}
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
const panelClient = panelBase.protocol === 'https:' ? https : http;
const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
const suffix = crypto.randomBytes(6).toString('hex');
const email = `security-${suffix}@seavhost.test`;
const tenantEmail = `tenant-security-${suffix}@seavhost.test`;
const initialPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}9a`;
const changedPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}8B`;
const tenantPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}7c`;
const marker = `Sea-vHost-account-security-${suffix}`;
const planName = `File verification ${suffix}`;
const planStatePath = `/var/lib/sea-vhost/account-verify-${suffix}.state`;
const domainRunDirectory = `domain-${suffix}`;
function authFields() {
const requestTime = Math.floor(Date.now() / 1000).toString();
return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) };
}
function panelForm(pathname, values) {
const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString());
return new Promise((resolve, reject) => {
const request = panelClient.request(new URL(pathname, panelBase), {
method: 'POST', agent: panelAgent, timeout: 30_000,
headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length },
}, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => { data += chunk; });
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`));
try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); }
});
});
request.on('timeout', () => request.destroy(new Error('panel request timed out')));
request.on('error', reject);
request.end(body);
});
}
async function runShell(name, shell, successMarker) {
const task = await panelForm('/crontab', {
action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0',
sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost account verification', save: '0', backupTo: 'localhost',
});
if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary verification task');
const taskID = Number(task.id);
if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned invalid task id');
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
let log = '';
for (let attempt = 0; attempt < 90; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) });
log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log;
if (log.includes(successMarker) || log.includes('★[')) break;
}
if (!log.includes(successMarker)) throw new Error(`temporary verification task failed:\n${log.trim()}`);
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const q = (value) => `'${value.replaceAll("'", "'\\''")}'`;
const seedMarker = `${marker}-seeded`;
const seedShell = [
'set -Eeuo pipefail',
'stage=initial; trap \'printf "account_seed_failed_stage=%s\\n" "$stage" >&2\' ERR',
`email=${q(email)}`,
`tenant_email=${q(tenantEmail)}`,
`password=${q(initialPassword)}`,
`tenant_password=${q(tenantPassword)}`,
`plan_name=${q(planName)}`,
`state_path=${q(planStatePath)}`,
'stage=php; php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; test -x "$php_bin"',
'password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"; test "${#password_hash}" -gt 50',
'tenant_password_hash="$(TEST_PASSWORD="$tenant_password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"; test "${#tenant_password_hash}" -gt 50',
'stage=config',
'mapfile -t db_parts < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')',
'test "${#db_parts[@]}" -eq 5; db_user="${db_parts[0]}"; db_password="${db_parts[1]}"; db_host="${db_parts[2]}"; db_port="${db_parts[3]}"; db_name="${db_parts[4]}"',
'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; test -x "$mysql_bin"',
'stage=database',
'sql="DELETE FROM users WHERE email IN (\'$email\',\'$tenant_email\'); INSERT INTO users(email,login_name,display_name,password_hash,role,status) VALUES (\'$email\',\'$email\',\'Security verification\',\'$password_hash\',\'admin\',\'active\'); INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$tenant_email\',\'$tenant_email\',\'Tenant security verification\',\'$tenant_password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
'MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="$sql"',
'read -r tenant_id original_plan_id project_root < <(MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --batch --skip-column-names --execute="SELECT p.tenant_id,t.plan_id,p.root_path FROM projects p JOIN tenants t ON t.id=p.tenant_id ORDER BY p.id LIMIT 1")',
'case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) ;; *) exit 1 ;; esac; if [[ -d "$project_root/.sea-trash" ]] && find "$project_root/.sea-trash" -mindepth 1 -print -quit | grep -q .; then printf "test project trash is not empty\\n" >&2; exit 1; fi',
'MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="INSERT INTO plans(name,storage_bytes,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit) SELECT \'$plan_name\',67108864,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit FROM plans WHERE id=$original_plan_id; SET @test_plan_id=LAST_INSERT_ID(); UPDATE tenants SET plan_id=@test_plan_id WHERE id=$tenant_id;"',
'temp_plan_id="$(MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --batch --skip-column-names --execute="SELECT id FROM plans WHERE name=\'$plan_name\'")"; test -n "$temp_plan_id"; printf "%s %s %s\\n" "$tenant_id" "$original_plan_id" "$temp_plan_id" | install -o root -g root -m 0600 /dev/stdin "$state_path"',
`printf '%s\\n' ${q(seedMarker)}`,
].join('\n');
const cleanupMarker = `${marker}-cleaned`;
const cleanupShell = [
'set -euo pipefail',
`email=${q(email)}`,
`tenant_email=${q(tenantEmail)}`,
`state_path=${q(planStatePath)}`,
`file_prefix=${q(`verify-${suffix}-`)}`,
`test_run_directory=${q(domainRunDirectory)}`,
'mapfile -t db_parts < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')',
'test "${#db_parts[@]}" -eq 5; db_user="${db_parts[0]}"; db_password="${db_parts[1]}"; db_host="${db_parts[2]}"; db_port="${db_parts[3]}"; db_name="${db_parts[4]}"',
'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; test -x "$mysql_bin"',
'if [[ -f "$state_path" ]]; then read -r tenant_id original_plan_id temp_plan_id <"$state_path"; project_root="$(MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --batch --skip-column-names --execute="SELECT root_path FROM projects WHERE tenant_id=$tenant_id ORDER BY id LIMIT 1")"; case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) find "$project_root" -xdev -maxdepth 1 -type f -name "$file_prefix*" -delete; if [[ -d "$project_root/.sea-trash" ]]; then find "$project_root/.sea-trash" -xdev -maxdepth 1 -type f -name "*$file_prefix*" -delete; fi; rmdir -- "$project_root/$test_run_directory" 2>/dev/null || true ;; *) exit 1 ;; esac; MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="UPDATE tenants SET plan_id=$original_plan_id WHERE id=$tenant_id AND plan_id=$temp_plan_id; DELETE FROM plans WHERE id=$temp_plan_id;"; rm -f -- "$state_path"; fi',
'MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="DELETE FROM users WHERE email IN (\'$email\',\'$tenant_email\');"',
`printf '%s\\n' ${q(cleanupMarker)}`,
].join('\n');
async function api(pathname, { method = 'GET', body, cookie, expected = [200] } = {}) {
const started = performance.now();
const response = await fetch(new URL(pathname, consoleBase), {
method, redirect: 'manual', signal: AbortSignal.timeout(15_000),
headers: {
Accept: 'application/json',
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
...(cookie ? { Cookie: cookie } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
});
const elapsedMs = performance.now() - started;
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}`);
return { response, payload, elapsedMs };
}
async function upload(projectID, cookie, name, bytes, overwrite, expected) {
const form = new FormData();
form.set('path', '');
form.set('overwrite', overwrite ? 'true' : 'false');
form.set('file', new Blob([bytes]), name);
const response = await fetch(new URL(`/api/v1/projects/${projectID}/files`, consoleBase), {
method: 'POST', headers: { Cookie: cookie }, body: form, redirect: 'manual', signal: AbortSignal.timeout(60_000),
});
const text = await response.text();
if (!expected.includes(response.status)) throw new Error(`file upload ${name} returned HTTP ${response.status}: ${text.slice(0, 160)}`);
return response;
}
function cookieFrom(response) {
const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
const cookie = header?.split(';', 1)[0];
if (!cookie?.startsWith('sea_session=')) throw new Error('login did not return a session cookie');
return cookie;
}
async function login(password, totpCode, expected = [200]) {
return loginIdentifier(email, password, totpCode, expected);
}
async function loginIdentifier(identifier, password, totpCode, expected = [200]) {
return api('/api/v1/auth/login', { method: 'POST', expected, body: { identifier, password, ...(totpCode ? { totpCode } : {}) } });
}
function decodeBase32(value) {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
let bits = '';
for (const character of value.replaceAll('=', '').toUpperCase()) {
const index = alphabet.indexOf(character);
if (index < 0) throw new Error('invalid TOTP secret');
bits += index.toString(2).padStart(5, '0');
}
const bytes = [];
for (let offset = 0; offset + 8 <= bits.length; offset += 8) bytes.push(Number.parseInt(bits.slice(offset, offset + 8), 2));
return Buffer.from(bytes);
}
function totp(secret) {
const counter = BigInt(Math.floor(Date.now() / 30_000));
const buffer = Buffer.alloc(8);
buffer.writeBigUInt64BE(counter);
const digest = crypto.createHmac('sha1', decodeBase32(secret)).update(buffer).digest();
const offset = digest[digest.length - 1] & 0x0f;
const value = (digest.readUInt32BE(offset) & 0x7fffffff) % 1_000_000;
return value.toString().padStart(6, '0');
}
let seeded = false;
let adminCookieForCleanup;
let tenantCookieForCleanup;
let projectIDForCleanup;
let siteIDForCleanup;
let originalDomainApproval;
try {
await runShell(`Sea vHost account seed ${suffix}`, seedShell, seedMarker);
seeded = true;
const knownTimings = [];
const missingTimings = [];
for (let index = 0; index < 5; index += 1) {
knownTimings.push((await login('definitely-wrong-password', undefined, [401])).elapsedMs);
missingTimings.push((await api('/api/v1/auth/login', { method: 'POST', expected: [401], body: { identifier: `missing-${suffix}@seavhost.test`, password: 'definitely-wrong-password' } })).elapsedMs);
}
const knownAverage = knownTimings.reduce((sum, value) => sum + value, 0) / knownTimings.length;
const missingAverage = missingTimings.reduce((sum, value) => sum + value, 0) / missingTimings.length;
if (knownAverage < 300 || missingAverage < 300 || Math.abs(knownAverage - missingAverage) > 150) throw new Error('login timing equalization is outside the accepted envelope');
let rateLimited;
for (let attempt = 1; attempt <= 21; attempt += 1) {
rateLimited = await api('/api/v1/auth/login', {
method: 'POST', expected: attempt === 21 ? [429] : [401],
body: { identifier: `limited-${suffix}@seavhost.test`, password: 'definitely-wrong-password' },
});
}
if (!rateLimited.response.headers.get('retry-after')) throw new Error('rate limit response omitted Retry-After');
const first = await login(initialPassword);
const second = await login(initialPassword);
const firstCookie = cookieFrom(first.response);
const secondCookie = cookieFrom(second.response);
await api('/api/v1/account/password', {
method: 'PUT', cookie: firstCookie, expected: [204],
body: { currentPassword: initialPassword, newPassword: changedPassword },
});
await api('/api/v1/me', { cookie: firstCookie });
await api('/api/v1/me', { cookie: secondCookie, expected: [401] });
await login(initialPassword, undefined, [401]);
const changedLogin = await login(changedPassword);
const changedCookie = cookieFrom(changedLogin.response);
const setup = await api('/api/v1/account/mfa/setup', {
method: 'POST', cookie: changedCookie, body: { currentPassword: changedPassword },
});
const secret = setup.payload?.secret;
if (typeof secret !== 'string' || secret.length < 16 || !setup.payload?.otpauthURI?.startsWith('otpauth://')) throw new Error('MFA setup returned invalid data');
const enabled = await api('/api/v1/account/mfa/enable', {
method: 'POST', cookie: changedCookie, body: { code: totp(secret) },
});
const recoveryCodes = enabled.payload?.recoveryCodes;
if (!Array.isArray(recoveryCodes) || recoveryCodes.length !== 10) throw new Error('MFA did not return ten recovery codes');
await login(changedPassword, undefined, [401]);
await login(changedPassword, '000000', [401]);
const mfaLogin = await login(changedPassword, totp(secret));
const mfaCookie = cookieFrom(mfaLogin.response);
await login(changedPassword, recoveryCodes[0]);
await login(changedPassword, recoveryCodes[0], [401]);
await api('/api/v1/account/mfa/disable', {
method: 'POST', cookie: mfaCookie, expected: [204],
body: { currentPassword: changedPassword, code: recoveryCodes[1] },
});
await api('/api/v1/me', { cookie: mfaCookie, expected: [401] });
const finalAdminLogin = await login(changedPassword);
const adminCookie = cookieFrom(finalAdminLogin.response);
adminCookieForCleanup = adminCookie;
const tenantLogin = await loginIdentifier(tenantEmail, tenantPassword);
const tenantCookie = cookieFrom(tenantLogin.response);
tenantCookieForCleanup = tenantCookie;
const projects = await api('/api/v1/projects', { cookie: tenantCookie });
const project = projects.payload?.projects?.[0];
if (!project?.id || !/^sv[0-9a-f]{10}$/.test(project.hostName)) throw new Error('temporary tenant could not read its managed host');
projectIDForCleanup = project.id;
const firstReset = await api(`/api/v1/projects/${project.id}/host-password/reset`, { method: 'POST', cookie: tenantCookie, body: {} });
const firstHostPassword = firstReset.payload?.password;
if (typeof firstHostPassword !== 'string' || firstHostPassword.length < 16) throw new Error('host password reset returned invalid data');
const hostLoginA = await loginIdentifier(project.hostName, firstHostPassword);
const hostLoginB = await loginIdentifier(project.hostName, firstHostPassword);
const hostCookieA = cookieFrom(hostLoginA.response);
const hostCookieB = cookieFrom(hostLoginB.response);
const hostDashboard = await api('/api/v1/dashboard', { cookie: hostCookieA });
if (hostDashboard.payload?.hostScoped !== true || hostDashboard.payload?.projects?.length !== 1 || hostDashboard.payload.projects[0].id !== project.id) {
throw new Error('host session was not scoped to exactly one project');
}
await api('/api/v1/admin/plans', { cookie: hostCookieA, expected: [403] });
await api(`/api/v1/projects/${project.id}/credentials`, { cookie: hostCookieA });
await api('/api/v1/projects/9223372036854775807/files', { cookie: hostCookieA, expected: [404] });
const secondReset = await api(`/api/v1/projects/${project.id}/host-password/reset`, { method: 'POST', cookie: tenantCookie, body: {} });
const secondHostPassword = secondReset.payload?.password;
await api('/api/v1/me', { cookie: hostCookieA, expected: [401] });
await api('/api/v1/me', { cookie: hostCookieB, expected: [401] });
await loginIdentifier(project.hostName, firstHostPassword, undefined, [401]);
await loginIdentifier(project.hostName, secondHostPassword);
const textName = `verify-${suffix}-text.txt`;
const uploadName = `verify-${suffix}-upload.bin`;
const limitName = `verify-${suffix}-20m.bin`;
const overLimitName = `verify-${suffix}-over.bin`;
const textPath = `/api/v1/projects/${project.id}/files`;
await api(textPath, { method: 'PUT', cookie: tenantCookie, expected: [204], body: { path: textName, content: 'first-value', overwrite: false } });
await api(textPath, { method: 'PUT', cookie: tenantCookie, expected: [409], body: { path: textName, content: 'duplicate', overwrite: false } });
await api(textPath, { method: 'PUT', cookie: tenantCookie, expected: [204], body: { path: textName, content: 'second-value', overwrite: true } });
const downloaded = await fetch(new URL(`${textPath}?path=${encodeURIComponent(textName)}&download=1`, consoleBase), { headers: { Cookie: tenantCookie }, signal: AbortSignal.timeout(15_000) });
if (downloaded.status !== 200 || await downloaded.text() !== 'second-value') throw new Error('downloaded text file did not match overwritten content');
await upload(project.id, tenantCookie, uploadName, Buffer.from('small-upload'), false, [201]);
await upload(project.id, tenantCookie, uploadName, Buffer.from('duplicate'), false, [409]);
await upload(project.id, tenantCookie, uploadName, Buffer.from('overwritten-upload'), true, [201]);
await upload(project.id, tenantCookie, limitName, Buffer.alloc(20 * 1024 * 1024, 0x61), false, [201]);
await upload(project.id, tenantCookie, overLimitName, Buffer.alloc(20 * 1024 * 1024 + 1, 0x62), false, [413]);
const listing = await api(textPath, { cookie: tenantCookie });
const listedNames = new Set((listing.payload?.entries ?? []).map((entry) => entry.name));
for (const required of [textName, uploadName, limitName]) if (!listedNames.has(required)) throw new Error(`file listing omitted ${required}`);
for (const name of [textName, uploadName, limitName]) {
await api(`${textPath}?path=${encodeURIComponent(name)}`, { method: 'DELETE', cookie: tenantCookie, expected: [204] });
await api(`${textPath}?path=${encodeURIComponent(name)}&download=1`, { cookie: tenantCookie, expected: [404] });
}
await api(`${textPath}?emptyTrash=1`, { method: 'DELETE', cookie: tenantCookie, expected: [204] });
const approvalSetting = await api('/api/v1/admin/settings/domain-approval', { cookie: adminCookie });
originalDomainApproval = approvalSetting.payload?.enabled === true;
await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: true } });
const siteCreate = await api(`/api/v1/projects/${project.id}/sites`, {
method: 'POST', cookie: tenantCookie, expected: [201],
body: { name: `domain-${suffix}`, runtime: 'PHP', version: project.version, runPath: `/${domainRunDirectory}`, customDomain: '', autoSSL: false },
});
const domainSite = siteCreate.payload?.site;
if (!domainSite?.id || domainSite.status !== 'running') throw new Error('domain verification site was not created');
siteIDForCleanup = domainSite.id;
const bindPath = `/api/v1/projects/${project.id}/sites/${domainSite.id}/domains`;
const dashboardForDomain = await api('/api/v1/dashboard', { cookie: tenantCookie });
const rootDomain = dashboardForDomain.payload?.rootDomain;
if (typeof rootDomain !== 'string' || !rootDomain.includes('.')) throw new Error('dashboard omitted root domain');
await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [422], body: { domain: rootDomain } });
await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [422], body: { domain: `blocked.${rootDomain}` } });
const pendingName = `pending-${suffix}.example.invalid`;
const pending = await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202], body: { domain: pendingName } });
if (pending.payload?.domain?.status !== 'pending') throw new Error('domain approval did not keep the domain pending');
const pendingList = await api('/api/v1/admin/domains/pending', { cookie: adminCookie });
const pendingItem = pendingList.payload?.domains?.find((item) => item.domain === pendingName && item.siteId === domainSite.id);
if (!pendingItem?.id) throw new Error('pending domain was not visible to the administrator');
const approved = await api(`/api/v1/admin/domains/${pendingItem.id}/review`, { method: 'POST', cookie: adminCookie, body: { approved: true } });
if (approved.payload?.domain?.status !== 'approved') throw new Error('administrator approval did not approve the domain');
const rejectedName = `rejected-${suffix}.example.invalid`;
await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202], body: { domain: rejectedName } });
const rejectList = await api('/api/v1/admin/domains/pending', { cookie: adminCookie });
const rejectItem = rejectList.payload?.domains?.find((item) => item.domain === rejectedName && item.siteId === domainSite.id);
if (!rejectItem?.id) throw new Error('second pending domain was not visible to the administrator');
const rejected = await api(`/api/v1/admin/domains/${rejectItem.id}/review`, { method: 'POST', cookie: adminCookie, body: { approved: false } });
if (rejected.payload?.domain?.status !== 'rejected') throw new Error('administrator rejection did not reject the domain');
await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: false } });
const directName = `direct-${suffix}.example.invalid`;
const direct = await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202], body: { domain: directName } });
if (direct.payload?.domain?.status !== 'approved') throw new Error('approval-disabled domain was not bound immediately');
const duplicateName = `duplicate-${suffix}.example.invalid`;
const duplicateResults = await Promise.all([
api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202, 422], body: { domain: duplicateName } }),
api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202, 422], body: { domain: duplicateName } }),
]);
const duplicateStatuses = duplicateResults.map((result) => result.response.status).sort();
if (duplicateStatuses[0] !== 202 || duplicateStatuses[1] !== 422) throw new Error(`concurrent duplicate binding returned ${duplicateStatuses.join(',')}`);
await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: true } });
const beforeLimit = await api('/api/v1/resources', { cookie: tenantCookie });
const currentDomainCount = (beforeLimit.payload?.domains ?? []).filter((item) => item.siteId === domainSite.id).length;
const expectedAccepted = 100 - currentDomainCount;
if (expectedAccepted < 1 || expectedAccepted > 100) throw new Error(`unexpected initial domain count ${currentDomainCount}`);
const limitResults = await Promise.all(Array.from({ length: expectedAccepted + 10 }, (_, index) => api(bindPath, {
method: 'POST', cookie: tenantCookie, expected: [202, 422], body: { domain: `limit-${index}-${suffix}.example.invalid` },
})));
const acceptedAtLimit = limitResults.filter((result) => result.response.status === 202).length;
if (acceptedAtLimit !== expectedAccepted) throw new Error(`domain limit accepted ${acceptedAtLimit}, want ${expectedAccepted}`);
const afterLimit = await api('/api/v1/resources', { cookie: tenantCookie });
const finalDomainCount = (afterLimit.payload?.domains ?? []).filter((item) => item.siteId === domainSite.id).length;
if (finalDomainCount !== 100) throw new Error(`site domain count is ${finalDomainCount}, want 100`);
await api(`/api/v1/projects/${project.id}/sites/${domainSite.id}`, { method: 'DELETE', cookie: tenantCookie, expected: [204] });
siteIDForCleanup = undefined;
await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: originalDomainApproval } });
originalDomainApproval = undefined;
console.log(JSON.stringify({
status: 'passed',
loginTiming: { knownAverageMs: Math.round(knownAverage), missingAverageMs: Math.round(missingAverage), differenceMs: Math.round(Math.abs(knownAverage - missingAverage)) },
checks: {
rateLimitAndRetryAfter: true, concurrentSessions: true, passwordChangeKeepsCurrentSession: true,
passwordChangeRevokesOtherSessions: true, oldPasswordRejected: true, totpLogin: true,
recoveryCodeSingleUse: true, disableMFARevokesSessions: true, loginWithoutMFAAfterDisable: true,
hostScopedDashboard: true, hostCannotUseAdminAPI: true, hostProjectIDORDenied: true,
hostPasswordResetRevokesAllSessions: true, oldHostPasswordRejected: true,
textCreateConflictOverwriteDownload: true, multipartCreateConflictOverwrite: true,
uploadExactly20MiBAccepted: true, uploadOver20MiBRejected: true,
fileListingTrashAndEmptyTrash: true,
domainReservedZoneRejected: true, domainApprovalAndRejection: true,
approvalDisabledImmediateBinding: true, concurrentDuplicateBinding: true,
concurrentDomainLimitExactly100: true, additionalSiteCleanup: true,
},
}, null, 2));
} finally {
if (tenantCookieForCleanup && projectIDForCleanup && siteIDForCleanup) {
try { await api(`/api/v1/projects/${projectIDForCleanup}/sites/${siteIDForCleanup}`, { method: 'DELETE', cookie: tenantCookieForCleanup, expected: [204, 404, 422] }); } catch { /* remote cleanup below handles the retained directory */ }
}
if (adminCookieForCleanup && typeof originalDomainApproval === 'boolean') {
try { await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookieForCleanup, expected: [204], body: { enabled: originalDomainApproval } }); } catch { /* best effort */ }
}
if (seeded) {
try { await runShell(`Sea vHost account cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch (error) {
console.error(`temporary account cleanup failed: ${error instanceof Error ? error.message : 'unknown error'}`);
process.exitCode = 1;
}
}
}