CI / quality (push) Failing after 45s
Recruitment needs `write:admin` and `write:organization`, which the everyday token must not carry. A second token keeps the repository and issue scopes least privileged, falls back to `GITEA_TOKEN` so existing installs keep working, and a 403 now names the missing scope instead of pretending Gitea did not answer.
264 lines
9.3 KiB
JavaScript
264 lines
9.3 KiB
JavaScript
import { randomBytes } from 'node:crypto';
|
||
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||
import { env } from '../../config/env.js';
|
||
import { createLogger } from '../../core/logger.js';
|
||
import { badRequest, notFound } from '../http.js';
|
||
import {
|
||
diffValues,
|
||
maskValues,
|
||
mergeValues,
|
||
readEnvFile,
|
||
renderEnvFile,
|
||
secretStatus,
|
||
writeEnvFile,
|
||
} from '../services/env-file.js';
|
||
import { SECTIONS, VARIABLES, crossCheck, requiredKeys, validateAll } from '../services/env-schema.js';
|
||
|
||
/**
|
||
* Step by step `.env` wizard (M16-T09).
|
||
*
|
||
* Reachable by a bootstrap session, because its whole purpose is to run before
|
||
* the bot has a working configuration.
|
||
*/
|
||
|
||
const log = createLogger('web:configuration');
|
||
const WIZARD = { access: ACCESS_LEVELS.OWNER, setup: true };
|
||
|
||
/** Values currently loaded in the process, used to prefill a first run. */
|
||
const runningValues = () => ({
|
||
NODE_ENV: env.nodeEnv,
|
||
LOG_LEVEL: env.logLevel,
|
||
LOG_DIR: env.logDir,
|
||
LOG_RETENTION_DAYS: String(env.logRetentionDays),
|
||
DISCORD_CLIENT_ID: env.discord.clientId,
|
||
DISCORD_GUILD_ID: env.discord.guildId,
|
||
GITEA_URL: env.gitea.url,
|
||
GITEA_OWNER: env.gitea.owner,
|
||
GITEA_REPO: env.gitea.repo,
|
||
DATABASE_PATH: env.database.path,
|
||
});
|
||
|
||
function currentValues() {
|
||
const file = readEnvFile();
|
||
const defaults = Object.fromEntries(
|
||
VARIABLES.filter((variable) => variable.default !== undefined).map((v) => [v.key, v.default]),
|
||
);
|
||
return { file, values: { ...defaults, ...runningValues(), ...file.values } };
|
||
}
|
||
|
||
function report(values) {
|
||
const errors = validateAll(values);
|
||
const missing = requiredKeys().filter((key) => !String(values[key] ?? '').trim());
|
||
return {
|
||
errors,
|
||
warnings: crossCheck(values),
|
||
missingRequired: missing,
|
||
valid: Object.keys(errors).length === 0,
|
||
};
|
||
}
|
||
|
||
export function registerConfigurationRoutes(router) {
|
||
router.get(
|
||
'/api/configuration',
|
||
() => {
|
||
const { file, values } = currentValues();
|
||
return {
|
||
sections: SECTIONS,
|
||
variables: VARIABLES,
|
||
exists: file.exists,
|
||
unknownKeys: Object.keys(file.unknown),
|
||
values: maskValues(values),
|
||
secrets: secretStatus(values),
|
||
...report(values),
|
||
};
|
||
},
|
||
WIZARD,
|
||
);
|
||
|
||
/** Live feedback while the form is being filled, nothing is written. */
|
||
router.post(
|
||
'/api/configuration/validate',
|
||
({ body }) => {
|
||
const { values } = currentValues();
|
||
const next = mergeValues(values, body.values ?? {});
|
||
return { ...report(next), diff: diffValues(values, next) };
|
||
},
|
||
WIZARD,
|
||
);
|
||
|
||
router.post(
|
||
'/api/configuration/preview',
|
||
({ body }) => {
|
||
const { file, values } = currentValues();
|
||
const next = mergeValues(values, body.values ?? {});
|
||
// Secrets are blanked out: the preview may be copied or screenshotted.
|
||
const safe = { ...next };
|
||
for (const variable of VARIABLES) {
|
||
if (variable.type === 'secret' && safe[variable.key]) safe[variable.key] = '••••••••';
|
||
}
|
||
return { content: renderEnvFile(safe, file.unknown) };
|
||
},
|
||
WIZARD,
|
||
);
|
||
|
||
router.post(
|
||
'/api/configuration/save',
|
||
({ body, actor }) => {
|
||
const { file, values } = currentValues();
|
||
const next = mergeValues(values, body.values ?? {});
|
||
const status = report(next);
|
||
|
||
// A partial save is allowed while the wizard is still being walked through,
|
||
// but a malformed value never reaches the file.
|
||
if (!status.valid && body.force !== true) {
|
||
throw badRequest('Certaines valeurs sont invalides.', status.errors);
|
||
}
|
||
|
||
const diff = diffValues(values, next);
|
||
if (diff.length === 0) return { ...status, diff, written: false };
|
||
|
||
const { backup } = writeEnvFile(next, { unknown: file.unknown });
|
||
log.info('Configuration saved from the wizard', {
|
||
actor: actor.userId ?? 'setup',
|
||
changed: diff.map((entry) => entry.key),
|
||
});
|
||
|
||
return {
|
||
...status,
|
||
diff,
|
||
written: true,
|
||
backup,
|
||
restartRequired: diff.some((entry) => entry.restartRequired),
|
||
};
|
||
},
|
||
WIZARD,
|
||
);
|
||
|
||
router.post(
|
||
'/api/configuration/generate',
|
||
({ body }) => {
|
||
const kind = String(body.kind ?? 'hex32');
|
||
const sizes = { hex16: 16, hex32: 32 };
|
||
if (!(kind in sizes)) throw badRequest('Type de secret inconnu.');
|
||
return { value: randomBytes(sizes[kind]).toString('hex') };
|
||
},
|
||
WIZARD,
|
||
);
|
||
|
||
/**
|
||
* Tries the credentials the user just typed, before they are written to disk.
|
||
* Nothing is stored and the value never appears in the response.
|
||
*/
|
||
router.post(
|
||
'/api/configuration/test/:service',
|
||
async ({ params, body }) => {
|
||
const values = mergeValues(currentValues().values, body.values ?? {});
|
||
|
||
if (params.service === 'discord') {
|
||
const token = String(values.DISCORD_TOKEN ?? '');
|
||
if (!token) return { ok: false, detail: 'Aucun token à tester.' };
|
||
|
||
try {
|
||
const response = await fetch('https://discord.com/api/v10/users/@me', {
|
||
headers: { Authorization: `Bot ${token}` },
|
||
signal: AbortSignal.timeout(10_000),
|
||
});
|
||
if (!response.ok) {
|
||
return {
|
||
ok: false,
|
||
detail:
|
||
response.status === 401
|
||
? 'Token refusé par Discord. Vérifie que tu as bien copié le token du bot (et non le client secret).'
|
||
: `Discord a répondu ${response.status}.`,
|
||
};
|
||
}
|
||
const user = await response.json();
|
||
return {
|
||
ok: true,
|
||
detail: `Token valide : ${user.username} (${user.id}).`,
|
||
applicationId: user.id,
|
||
};
|
||
} catch (error) {
|
||
return { ok: false, detail: `Discord injoignable : ${error.message}` };
|
||
}
|
||
}
|
||
|
||
if (params.service === 'gitea') {
|
||
const url = String(values.GITEA_URL ?? '').replace(/\/+$/, '');
|
||
const token = String(values.GITEA_TOKEN ?? '');
|
||
if (!url || !token) return { ok: false, detail: 'URL ou jeton manquant.' };
|
||
|
||
try {
|
||
const response = await fetch(`${url}/api/v1/user`, {
|
||
headers: { Authorization: `token ${token}`, Accept: 'application/json' },
|
||
signal: AbortSignal.timeout(10_000),
|
||
});
|
||
if (!response.ok) return { ok: false, detail: `Gitea a répondu ${response.status}.` };
|
||
|
||
const user = await response.json();
|
||
const owner = String(values.GITEA_OWNER ?? '');
|
||
let detail = `Jeton valide pour « ${user.login} ».`;
|
||
let organizationReachable = true;
|
||
|
||
if (owner) {
|
||
const orgResponse = await fetch(`${url}/api/v1/orgs/${encodeURIComponent(owner)}`, {
|
||
headers: { Authorization: `token ${token}`, Accept: 'application/json' },
|
||
signal: AbortSignal.timeout(10_000),
|
||
});
|
||
organizationReachable = orgResponse.ok;
|
||
detail += orgResponse.ok
|
||
? ` Organisation « ${owner} » accessible.`
|
||
: ` En revanche l’organisation « ${owner} » est inaccessible (${orgResponse.status}).`;
|
||
}
|
||
// The token itself works: an unreachable organization is a warning, not a failure.
|
||
return { ok: true, warning: !organizationReachable, detail };
|
||
} catch (error) {
|
||
return { ok: false, detail: `Gitea injoignable : ${error.message}` };
|
||
}
|
||
}
|
||
|
||
if (params.service === 'gitea-recruitment') {
|
||
const url = String(values.GITEA_URL ?? '').replace(/\/+$/, '');
|
||
const token =
|
||
String(values.GITEA_RECRUITMENT_TOKEN ?? '').trim() || String(values.GITEA_TOKEN ?? '').trim();
|
||
if (!url || !token) return { ok: false, detail: 'URL ou jeton de recrutement manquant.' };
|
||
|
||
try {
|
||
const identity = await fetch(`${url}/api/v1/user`, {
|
||
headers: { Authorization: `token ${token}`, Accept: 'application/json' },
|
||
signal: AbortSignal.timeout(10_000),
|
||
});
|
||
if (!identity.ok) {
|
||
return { ok: false, detail: `Gitea a répondu ${identity.status} au jeton de recrutement.` };
|
||
}
|
||
const user = await identity.json();
|
||
// `/admin/users` is the route recruitment really calls: it proves both the
|
||
// account's admin rights and the token's `write:admin` scope.
|
||
const admin = await fetch(`${url}/api/v1/admin/users?limit=1`, {
|
||
headers: { Authorization: `token ${token}`, Accept: 'application/json' },
|
||
signal: AbortSignal.timeout(10_000),
|
||
});
|
||
if (!admin.ok) {
|
||
return {
|
||
ok: false,
|
||
detail:
|
||
user.is_admin === true
|
||
? `« ${user.login} » est administrateur, mais le jeton n’a pas la portée \`write:admin\` (Gitea a répondu ${admin.status}).`
|
||
: `« ${user.login} » n’est pas administrateur de l’instance : seuls les admins peuvent créer des comptes Gitea.`,
|
||
};
|
||
}
|
||
return {
|
||
ok: true,
|
||
detail: `Jeton de recrutement valide : « ${user.login} » peut créer des comptes et gérer les équipes.`,
|
||
};
|
||
} catch (error) {
|
||
return { ok: false, detail: `Gitea injoignable : ${error.message}` };
|
||
}
|
||
}
|
||
|
||
throw notFound('Service inconnu.');
|
||
},
|
||
WIZARD,
|
||
);
|
||
}
|