import { Buffer } from 'node:buffer'; import { createHmac, timingSafeEqual } from 'node:crypto'; import { readFile, stat } from 'node:fs/promises'; import { createServer } from 'node:http'; import process from 'node:process'; import { clearTimeout, setTimeout } from 'node:timers'; import { TextDecoder } from 'node:util'; import { URL } from 'node:url'; /** @typedef {{id: string, label: string, minutesPerKit: number}} PracticeRow */ /** @typedef {{teamId: string, channelId: string, appId: string, allowedUsers: Set, signingSecret: string}} CommandConfig */ const COMMAND = '/as-workshop-preview'; const PATH = '/slack/commands'; const MAX_BODY = 16384; const LOCAL_DEADLINE_MS = 1800; class RequestProblem extends Error { /** @param {number} status @param {string} code Fixed local diagnostics only. */ constructor(status, code) { super(code); this.status = status; } } /** Load configuration/data before listening. No HTTP call, token or background work. @returns {Promise} */ async function main() { if (process.version !== 'v24.21.0') throw new Error('EXPECTED_NODE_24_21_0'); const teamId = requiredId('SLACK_TEAM_ID', /^T[A-Z0-9]{5,31}$/); const channelId = requiredId('SLACK_CHANNEL_ID', /^[CG][A-Z0-9]{5,31}$/); const appId = requiredId('SLACK_APP_ID', /^A[A-Z0-9]{5,31}$/); const users = (process.env.SLACK_ALLOWED_USER_IDS || '').split(','); if (users.length < 1 || users.length > 5 || users.some((id) => !/^[UW][A-Z0-9]{5,31}$/.test(id)) || new Set(users).size !== users.length) throw new Error('EXPECTED_EXPLICIT_PRACTICE_USERS'); const secretPath = process.env.SLACK_SIGNING_SECRET_FILE; if (typeof secretPath !== 'string' || !secretPath.startsWith('/')) throw new Error('EXPECTED_ABSOLUTE_SECRET_FILE'); const signingSecret = (await smallFile(secretPath)).replace(/\r?\n$/, ''); if (!/^[A-Za-z0-9]{16,256}$/.test(signingSecret)) throw new Error('INVALID_SIGNING_SECRET_FILE'); /** @type {unknown} */ const fixture = JSON.parse(await smallFile(new URL('./practice-data.json', import.meta.url))); const rows = practiceRows(fixture); /** @type {CommandConfig} */ const config = {teamId, channelId, appId, allowedUsers: new Set(users), signingSecret}; // The public HTTPS reverse proxy runs on the SAME host; this port is never public. const server = createServer({maxHeaderSize: 8192, headersTimeout: 2000, requestTimeout: 2000, connectionsCheckingInterval: 250, keepAliveTimeout: 1000}, (req, res) => { const started = Date.now(); const timer = setTimeout(() => { res.destroy(); req.destroy(); }, LOCAL_DEADLINE_MS); res.once('close', () => clearTimeout(timer)); res.once('error', () => { clearTimeout(timer); req.destroy(); }); handleCommand(req, res, config, rows, started + LOCAL_DEADLINE_MS).catch((/** @type {unknown} */ error) => { if (!res.headersSent && !res.destroyed) { const status = error instanceof RequestProblem ? error.status : 500; res.writeHead(status, {'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', Connection: 'close'}); res.end('Command request rejected.'); } else { res.destroy(); } req.resume(); // No raw headers, body, signature, IDs, secret path, response_url or input text. console.error(JSON.stringify({stage: 'command_rejected', code: error instanceof RequestProblem ? error.message : 'internal_failure'})); }); }); server.maxConnections = 32; server.on('error', () => { console.error('Command server failed; inspect service/port configuration.'); process.exitCode = 1; }); server.listen(3000, '127.0.0.1', () => console.log('Command server listening on loopback; no Slack request verified yet.')); process.once('SIGTERM', () => { server.close(); const timer = setTimeout(() => server.closeAllConnections(), 2000); timer.unref(); }); } /** * Authenticate actual bytes before form decoding or business validation. * Only a pure local calculation and the synchronous HTTP response happen here. * @param {import('node:http').IncomingMessage} req * @param {import('node:http').ServerResponse} res * @param {CommandConfig} config * @param {PracticeRow[]} rows * @param {number} deadline * @returns {Promise} */ async function handleCommand(req, res, config, rows, deadline) { if (req.method !== 'POST' || req.url !== PATH) throw new RequestProblem(404, 'wrong_method_or_path'); const contentType = oneHeader(req, 'content-type'); if (!/^application\/x-www-form-urlencoded(?:\s*;\s*charset=utf-8)?$/i.test(contentType)) { throw new RequestProblem(415, 'expected_form_body'); } if (req.headers['content-encoding'] !== undefined) throw new RequestProblem(415, 'encoded_body_not_supported'); const timestamp = oneHeader(req, 'x-slack-request-timestamp'); const signature = oneHeader(req, 'x-slack-signature'); if (!/^[0-9]{10}$/.test(timestamp) || !/^v0=[0-9a-f]{64}$/.test(signature)) { throw new RequestProblem(401, 'invalid_signature_headers'); } const raw = await readBody(req); if (Date.now() >= deadline) throw new RequestProblem(503, 'local_deadline'); if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) throw new RequestProblem(401, 'stale_timestamp'); // Never decode/re-encode the form before signing. Key is Slack's literal UTF-8 secret. const digest = createHmac('sha256', Buffer.from(config.signingSecret, 'utf8')) .update('v0:' + timestamp + ':', 'utf8').update(raw).digest(); const supplied = Buffer.from(signature.slice(3), 'hex'); // Regex guarantees 32 supplied bytes; keep the length guard before timingSafeEqual. if (supplied.length !== digest.length || !timingSafeEqual(digest, supplied)) throw new RequestProblem(401, 'bad_signature'); const fields = decodeForm(raw); if (fields.get('team_id') !== config.teamId || fields.get('api_app_id') !== config.appId || fields.get('channel_id') !== config.channelId || fields.get('command') !== COMMAND || !config.allowedUsers.has(fields.get('user_id') || '')) throw new RequestProblem(403, 'practice_context_not_allowed'); const input = fields.get('text'); const preview = typeof input !== 'string' || input.length > 80 || /[\u0000-\u001f\u007f]/.test(input) ? 'Command input is not allowed. Use /as-workshop-preview help. No work is scheduled or posted.' : calculatePreview(input, rows); // Do not echo untrusted input. JSON encoding and plain_text blocks keep the result inert. const response = JSON.stringify({response_type: 'ephemeral', text: preview, mrkdwn: false, blocks: [{type: 'section', text: {type: 'plain_text', text: preview, emoji: false}}]}); if (Buffer.byteLength(response, 'utf8') > 2048) throw new RequestProblem(500, 'response_limit'); if (Date.now() >= deadline || res.destroyed) throw new RequestProblem(503, 'local_deadline'); res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Length': Buffer.byteLength(response, 'utf8'), Connection: 'close'}); res.end(response); // Calling end is not a receipt proving Slack received/displayed the response before 3 seconds. } /** @param {import('node:http').IncomingMessage} req @param {string} name @returns {string} */ function oneHeader(req, name) { /** @type {string[]} */ const matches = []; for (let i = 0; i < req.rawHeaders.length; i += 2) { if (req.rawHeaders[i].toLowerCase() === name) matches.push(req.rawHeaders[i + 1]); } if (matches.length !== 1) throw new RequestProblem(400, 'missing_or_duplicate_header'); return matches[0]; } /** @param {import('node:http').IncomingMessage} req @returns {Promise} */ function readBody(req) { const declared = req.headers['content-length']; if (declared !== undefined && (typeof declared !== 'string' || !/^[0-9]{1,5}$/.test(declared) || Number(declared) > MAX_BODY)) { return Promise.reject(new RequestProblem(413, 'body_limit')); } return new Promise((resolve, reject) => { /** @type {Buffer[]} */ const chunks = []; let size = 0; let failed = false; req.on('data', (/** @type {unknown} */ chunk) => { if (failed) return; if (!Buffer.isBuffer(chunk) || size + chunk.length > MAX_BODY) { failed = true; chunks.length = 0; reject(new RequestProblem(413, 'body_limit')); return; } size += chunk.length; chunks.push(chunk); }); req.once('end', () => { if (failed) return; if (!req.complete || size === 0) reject(new RequestProblem(400, 'incomplete_body')); else resolve(Buffer.concat(chunks, size)); }); req.once('error', () => reject(new RequestProblem(400, 'body_stream_failed'))); req.once('close', () => { if (!req.complete) reject(new RequestProblem(400, 'body_incomplete')); }); }); } /** Strict form decoding after authentication; no JSON payload wrapper for slash commands. @param {Buffer} raw @returns {Map} */ function decodeForm(raw) { try { const parts = new TextDecoder('utf-8', {fatal: true}).decode(raw).split('&'); if (parts.length > 32) throw new Error('field_count'); /** @type {Map} */ const fields = new Map(); for (const part of parts) { const index = part.indexOf('='); if (index < 1) throw new Error('missing_equals'); const name = decodeURIComponent(part.slice(0, index).replace(/\+/g, ' ')); const value = decodeURIComponent(part.slice(index + 1).replace(/\+/g, ' ')); if (!/^[a-z_]{1,64}$/.test(name) || value.length > 4096 || fields.has(name)) throw new Error('invalid_field'); fields.set(name, value); } return fields; } catch { throw new RequestProblem(400, 'malformed_form'); } } /** Pure fictional calculation. Unknown syntax gives help, never a queued job. @param {string} input @param {PracticeRow[]} rows @returns {string} */ function calculatePreview(input, rows) { const help = 'Fictional preview only. Use /as-workshop-preview preview REQ-001 2 (quantity 1 to 5), or /as-workshop-preview help. No work is scheduled or posted.'; if (input === 'help' || input === '') return help; const match = /^preview (REQ-[0-9]{3}) ([1-5])$/.exec(input); if (match === null) return 'Command not understood. ' + help; const row = rows.find((item) => item.id === match[1]); if (row === undefined) return 'Unknown fictional request. ' + help; const count = Number(match[2]); return 'Fictional preview: ' + row.id + ' - ' + row.label + '. ' + count + ' kits x ' + row.minutesPerKit + ' minutes = ' + count * row.minutesPerKit + ' minutes. No work is scheduled or posted.'; } /** @param {unknown} value @returns {PracticeRow[]} */ function practiceRows(value) { if (!Array.isArray(value) || value.length !== 3) throw new Error('EXPECTED_THREE_FICTIONAL_ROWS'); /** @type {PracticeRow[]} */ const rows = []; const candidates = /** @type {unknown[]} */ (value); for (const candidate of candidates) { if (candidate === null || typeof candidate !== 'object' || Array.isArray(candidate)) throw new Error('INVALID_ROW'); const row = /** @type {Record} */ (candidate); if (typeof row.id !== 'string' || !/^REQ-00[1-3]$/.test(row.id) || rows.some((item) => item.id === row.id) || typeof row.label !== 'string' || !/^[A-Za-z][A-Za-z &-]{1,59}$/.test(row.label) || typeof row.minutesPerKit !== 'number' || !Number.isSafeInteger(row.minutesPerKit) || row.minutesPerKit < 1 || row.minutesPerKit > 60) throw new Error('INVALID_FICTIONAL_ROW'); rows.push({id: row.id, label: row.label, minutesPerKit: row.minutesPerKit}); } return rows; } /** @param {string | URL} path @returns {Promise} */ async function smallFile(path) { const info = await stat(path); if (!info.isFile() || info.size < 1 || info.size > 4096) throw new Error('CONFIG_FILE_SIZE'); const bytes = await readFile(path); if (bytes.length > 4096) throw new Error('CONFIG_FILE_SIZE'); return new TextDecoder('utf-8', {fatal: true}).decode(bytes); } /** @param {string} name @param {RegExp} shape @returns {string} */ function requiredId(name, shape) { const value = process.env[name]; if (typeof value !== 'string' || !shape.test(value)) throw new Error('REQUIRED_ENVIRONMENT_ID'); return value; } main().catch(() => { console.error('Command startup failed. Inspect the approved Node version, configuration, credential and fixture without logging them.'); process.exitCode = 1; });