Harden Cards administrator access and the database path
Ignore the development login in production unless a test server asks for it in code, apply the administrator list to existing accounts at startup, and move the example database to a folder the deployment script does not reset to root. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
115e62d5b2
commit
b2e46b1d2a
5 changed files with 64 additions and 5 deletions
|
|
@ -2,12 +2,13 @@ PORT=5173
|
|||
|
||||
# Sokko TCG reste désactivé en production tant que ces valeurs ne sont pas configurées.
|
||||
CARDS_ENABLED=false
|
||||
CARDS_DB_PATH=/var/lib/sokko-g/nebula-cards.sqlite
|
||||
# Un sous-dossier possédé par le compte du service : le script de livraison remet /var/lib/sokko-g à root.
|
||||
CARDS_DB_PATH=/var/lib/sokko-g/cards/nebula-cards.sqlite
|
||||
# La recharge des ouvertures, l'ouverture des paquets et les taux de tirage se règlent depuis l'administration.
|
||||
CARDS_PUBLIC_ORIGIN=https://sokkog.example.com
|
||||
DISCORD_CLIENT_ID=
|
||||
DISCORD_CLIENT_SECRET=
|
||||
DISCORD_REDIRECT_URI=https://sokkog.example.com/api/cards/auth/callback
|
||||
CARDS_ADMIN_DISCORD_IDS=
|
||||
# Ne jamais activer cette connexion factice en production : elle accorde les droits administrateur.
|
||||
# Connexion factice qui accorde les droits administrateur : réservée au développement, ignorée en production.
|
||||
CARDS_DEV_AUTH=false
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ const { startServer } = await import("../server.mjs");
|
|||
const draws = [0.999, 0, 0.999, 0.999, 0.999, 0];
|
||||
let drawIndex = 0;
|
||||
// Tous les parcours et leurs deux comptes partagent la même adresse IP : la limite par minute les ferait échouer au hasard.
|
||||
const server = startServer({ cardsApiOptions: { apiRateLimit: 100_000, random: (max) => Math.min(max - 1, Math.floor(draws[drawIndex++ % draws.length] * max)) } });
|
||||
const server = startServer({ cardsApiOptions: { allowProductionDevAuth: true, apiRateLimit: 100_000, random: (max) => Math.min(max - 1, Math.floor(draws[drawIndex++ % draws.length] * max)) } });
|
||||
let stopping = false;
|
||||
|
||||
function stop() {
|
||||
|
|
|
|||
|
|
@ -117,7 +117,9 @@ export function createCardsApiHandler({
|
|||
projectRoot = resolve("."),
|
||||
env = process.env,
|
||||
enabled = bool(env.CARDS_ENABLED, env.NODE_ENV !== "production"),
|
||||
devAuth = bool(env.CARDS_DEV_AUTH, env.NODE_ENV !== "production"),
|
||||
devAuth: requestedDevAuth = bool(env.CARDS_DEV_AUTH, env.NODE_ENV !== "production"),
|
||||
// Réservé au serveur E2E : cette option n'est pas lisible depuis l'environnement, une erreur de configuration ne peut donc pas l'activer.
|
||||
allowProductionDevAuth = false,
|
||||
databasePath = env.CARDS_DB_PATH || join(projectRoot, ".local", "nebula-cards.sqlite"),
|
||||
catalogPath = join(projectRoot, "website", "public", "data", "cards", "catalog.json"),
|
||||
now = Date.now,
|
||||
|
|
@ -126,6 +128,9 @@ export function createCardsApiHandler({
|
|||
devPerks = false,
|
||||
apiRateLimit = 60
|
||||
} = {}) {
|
||||
// Cette connexion accorde les droits administrateur à n'importe quel visiteur.
|
||||
const devAuth = requestedDevAuth && (env.NODE_ENV !== "production" || allowProductionDevAuth);
|
||||
if (requestedDevAuth && !devAuth) console.error("CARDS_DEV_AUTH is ignored in production.");
|
||||
let database = null;
|
||||
let service = null;
|
||||
if (enabled) {
|
||||
|
|
@ -138,6 +143,7 @@ export function createCardsApiHandler({
|
|||
}
|
||||
const secureCookies = env.NODE_ENV === "production";
|
||||
const adminIds = new Set(String(env.CARDS_ADMIN_DISCORD_IDS || "").split(",").map((item) => item.trim()).filter(Boolean));
|
||||
service?.syncAdmins(adminIds, { keepDevAdmin: devAuth });
|
||||
const rateLimit = createRateLimiter(now);
|
||||
const publicOrigin = (req) => env.CARDS_PUBLIC_ORIGIN || requestOrigin(req);
|
||||
const discordCallbackUrl = (req) => env.DISCORD_REDIRECT_URI || `${publicOrigin(req)}/api/cards/auth/callback`;
|
||||
|
|
|
|||
|
|
@ -280,6 +280,12 @@ export class CardsService {
|
|||
return publicPlayer(row);
|
||||
}
|
||||
|
||||
// La liste des administrateurs vient de l'environnement et ne change qu'au redémarrage : elle s'applique alors aux sessions déjà ouvertes.
|
||||
syncAdmins(adminDiscordIds, { keepDevAdmin = false } = {}) {
|
||||
const ids = JSON.stringify([...adminDiscordIds, ...(keepDevAdmin ? [DEV_DISCORD_ID] : [])]);
|
||||
this.db.prepare("UPDATE players SET is_admin = (discord_id IN (SELECT value FROM json_each(?1)))").run(ids);
|
||||
}
|
||||
|
||||
createSession(playerId) {
|
||||
const rawToken = token(32);
|
||||
const csrfToken = token(24);
|
||||
|
|
|
|||
|
|
@ -2,8 +2,11 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { Readable } from "node:stream";
|
||||
import { test } from "node:test";
|
||||
import { resolve } from "node:path";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { createCardsApiHandler } from "../services/cards/api.js";
|
||||
import { DEV_DISCORD_ID } from "../services/cards/service.js";
|
||||
|
||||
function mockRequest({ method = "GET", path, body, headers = {} }) {
|
||||
const req = Readable.from(body == null ? [] : [Buffer.from(JSON.stringify(body))]);
|
||||
|
|
@ -227,3 +230,46 @@ test("gift pack codes are claimed and opened through the API", async (t) => {
|
|||
const extended = await call(handler, { method: "PUT", path: `/api/cards/admin/campaigns/${created.json.campaign.id}/expiry`, headers, body: { expiresAt: Date.now() + 120_000 } });
|
||||
assert.equal(extended.status, 200);
|
||||
});
|
||||
|
||||
test("development login cannot be enabled in production by configuration alone", async (t) => {
|
||||
const originalError = console.error;
|
||||
const logged = [];
|
||||
console.error = (...values) => logged.push(values.join(" "));
|
||||
t.after(() => { console.error = originalError; });
|
||||
const env = { NODE_ENV: "production", CARDS_ENABLED: "true", CARDS_DEV_AUTH: "true", CARDS_DB_PATH: ":memory:", CARDS_PUBLIC_ORIGIN: "https://cards.invalid", CARDS_PRIVACY_CONTACT: "privacy@example.invalid" };
|
||||
const refused = createCardsApiHandler({ projectRoot: resolve("."), env });
|
||||
t.after(() => refused.close());
|
||||
assert.equal((await call(refused, { path: "/api/cards/config" })).json.devAuth, false);
|
||||
assert.equal((await call(refused, { method: "POST", path: "/api/cards/auth/dev" })).status, 404);
|
||||
assert.match(logged.join("\n"), /CARDS_DEV_AUTH/);
|
||||
|
||||
const explicit = createCardsApiHandler({ projectRoot: resolve("."), env, allowProductionDevAuth: true });
|
||||
t.after(() => explicit.close());
|
||||
assert.equal((await call(explicit, { path: "/api/cards/config" })).json.devAuth, true);
|
||||
});
|
||||
|
||||
test("the administrator list is applied to existing accounts at startup", async (t) => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "sokko-cards-admins-"));
|
||||
t.after(() => rm(directory, { recursive: true, force: true }));
|
||||
const databasePath = join(directory, "cards.sqlite");
|
||||
const start = (adminIds, devAuth = false) => createCardsApiHandler({ projectRoot: resolve("."), enabled: true, devAuth, databasePath, env: { NODE_ENV: "test", CARDS_ADMIN_DISCORD_IDS: adminIds } });
|
||||
const isAdmin = (handler, discordId) => Boolean(handler.service.db.prepare("SELECT is_admin FROM players WHERE discord_id = ?").get(discordId).is_admin);
|
||||
|
||||
const first = start("removed,kept");
|
||||
for (const discordId of ["removed", "kept"]) first.service.upsertPlayer({ discordId, displayName: discordId, isAdmin: true });
|
||||
first.service.upsertPlayer({ discordId: "promoted", displayName: "promoted" });
|
||||
first.service.upsertPlayer({ discordId: DEV_DISCORD_ID, displayName: "dev", isAdmin: true });
|
||||
const removedPlayer = first.service.upsertPlayer({ discordId: "removed", displayName: "removed", isAdmin: true });
|
||||
const openSession = first.service.createSession(removedPlayer.id);
|
||||
first.close();
|
||||
|
||||
const second = start("kept,promoted", true);
|
||||
assert.deepEqual(["removed", "kept", "promoted", DEV_DISCORD_ID].map((id) => isAdmin(second, id)), [false, true, true, true]);
|
||||
const forbidden = await call(second, { path: "/api/cards/admin/dashboard", headers: { cookie: `sokkog_cards_session=${openSession.token}` } });
|
||||
assert.equal(forbidden.status, 403);
|
||||
second.close();
|
||||
|
||||
const third = start("kept");
|
||||
assert.equal(isAdmin(third, DEV_DISCORD_ID), false);
|
||||
third.close();
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue