Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **Security: a panel image path can no longer leave `assets/`.** A value such
as `"../.env"` in `panel.logo.file` or `panel.banner.file` made the panel post
that file, the bot token included, to Discord as an attachment. Anyone with
`config.edit` in the dashboard could use it to read the `.env`, which is
otherwise owner only. Only a plain file name inside `assets/` (or
`assets/default/`) is accepted now. Affects every earlier version.
- The bot config editor showed no file: `GET /config/:file` answered 404 for
`config.jsonc`, `snippets.jsonc` and `.env` since the customer locale layer
went in. It reads the files directly again.
- The bot loads its locales through `require()` again, as before the customer
locale layer. Only the dashboard editor reads the raw files.

- The startup log printed `API key valid → business` in lower case, because
the label map had no entry for the Business tier. It prints `Business` now.

Expand Down
10 changes: 3 additions & 7 deletions src/dashboard/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -279,13 +279,9 @@ function registerRoutes(api, { config, supervisor, requirePermission, invalidate
return res.status(403).json({ error: 'Only the server owner can access the .env file.' });
}

let result;
try {
result = localeStore.readLocaleForEditor(LOCALES_DIR, path.basename(target));
} catch {
return res.status(404).json({ error: 'File not found.' });
}
res.json(result);
const content = await fs.readFile(target, 'utf-8').catch(() => null);
if (content === null) return res.status(404).json({ error: 'File not found.' });
res.json({ content });
}));

api.put('/config/:file', requirePermission('config.edit'), asyncRoute(async (req, res) => {
Expand Down
29 changes: 27 additions & 2 deletions src/utils/locales.js
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,36 @@ function loadLocale(code, { dir = LOCALES_DIR, warn } = {}) {
throw new Error(`Invalid locale code: ${code}`);
}
const fileName = `${code}.json`;
const shipped = JSON.parse(fs.readFileSync(path.join(dir, fileName), 'utf-8'));
const custom = readCustomFile(customPathFor(fileName, dir), warn);
const shipped = requireFresh(path.join(dir, fileName));
const custom = requireCustomFile(customPathFor(fileName, dir), warn);
return custom ? mergeLocale(shipped, custom) : shipped;
}

// The bot loads its locales through require(), as it did before the customer
// layer existed. The cache entry is dropped first, so an edit saved in the
// dashboard is picked up on the next load instead of after a restart. The
// dashboard editor below reads with fs, since it needs the raw text.
function requireFresh(file) {
const resolved = require.resolve(file);
delete require.cache[resolved];
return require(resolved);
}

function requireCustomFile(file, warn = (m) => logger.warn(m)) {
let parsed;
try {
parsed = requireFresh(file);
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') warn(`[Locale] Ignoring ${file}: ${err.message}. Using the shipped texts.`);
return null;
}
if (!isPlainObject(parsed)) {
warn(`[Locale] Ignoring ${file}: not a JSON object. Using the shipped texts.`);
return null;
}
return parsed;
}

// ── Dashboard editor helpers ─────────────────────────────────────────────────
// The dashboard resolves the file NAME against the real directory listing first
// (routes.js) and passes in the matched entry, so every path below is built from
Expand Down
9 changes: 8 additions & 1 deletion src/utils/panel.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,14 @@ const ASSETS_DIR = path.resolve(__dirname, '../../assets');
*/
function resolvePanelAsset(file, assetsDir = ASSETS_DIR) {
if (typeof file !== 'string' || file === '') return null;
for (const candidate of [path.resolve(assetsDir, file), path.resolve(assetsDir, 'default', file)]) {
// Only a plain file name inside assets/ is allowed. Without this, a config
// value like "../.env" made the panel post the bot's .env (token included)
// to Discord as an attachment.
if (file !== path.basename(file) || file === '.' || file === '..' || file.includes('\\') || file.includes('/')) return null;
const root = path.resolve(assetsDir);
for (const candidate of [path.resolve(root, file), path.resolve(root, 'default', file)]) {
const rel = path.relative(root, candidate);
if (rel.startsWith('..') || path.isAbsolute(rel)) continue;
if (fs.statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
}
return null;
Expand Down
41 changes: 41 additions & 0 deletions tests/config-route.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';

// The bot config editor reads config/*.jsonc and .env through GET /config/:file.
// PR #46 accidentally routed that read through the locale loader, so every file
// answered 404 and the editor stayed empty.

const test = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const express = require('express');
const { registerRoutes } = require('../src/dashboard/routes');

const SNIPPETS = path.resolve(__dirname, '../config/snippets.jsonc');

test('GET /config/snippets returns the file content', async (t) => {
// Use the local snippets file if there is one; otherwise create it ('wx' fails
// instead of overwriting if it appeared in between) and remove it afterwards.
let original = '// test snippets\n{}\n';
let created = false;
try {
fs.writeFileSync(SNIPPETS, original, { encoding: 'utf-8', flag: 'wx' });
created = true;
} catch (err) {
if (err.code !== 'EEXIST') throw err;
original = fs.readFileSync(SNIPPETS, 'utf-8');
}
t.after(() => { if (created) fs.rmSync(SNIPPETS, { force: true }); });

const app = express();
const api = express.Router();
app.use((req, _res, next) => { req.auth = { isOwner: true, userId: '1' }; next(); });
registerRoutes(api, { config: { guildId: '1' }, supervisor: {}, requirePermission: () => (_req, _res, next) => next(), invalidateMemberCache: () => {} });
app.use('/api', api);
const server = await new Promise(r => { const s = app.listen(0, '127.0.0.1', () => r(s)); });
t.after(() => server.close());

const res = await fetch(`http://127.0.0.1:${server.address().port}/api/config/snippets`);
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), { content: original });
});
12 changes: 12 additions & 0 deletions tests/panel-assets.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,15 @@ test('the repository ships the default logo for panel.logo.file "logo.png"', ()
assert.ok(fs.statSync(path.resolve(__dirname, '../assets/default/logo.png')).isFile());
assert.ok(resolvePanelAsset('logo.png'));
});

test('resolvePanelAsset: a path outside assets/ is never resolved', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tb-assets-'));
fs.mkdirSync(path.join(dir, 'assets'));
fs.writeFileSync(path.join(dir, '.env'), 'TOKEN=secret');
fs.writeFileSync(path.join(dir, 'assets', 'logo.png'), 'x');
const assets = path.join(dir, 'assets');
for (const bad of ['../.env', '..\.env', '/etc/passwd', path.join(dir, '.env'), '..', '.', 'default/../../.env']) {
assert.equal(resolvePanelAsset(bad, assets), null, bad);
}
assert.equal(resolvePanelAsset('logo.png', assets), path.join(assets, 'logo.png'));
});
Loading