// Node.js 20+, standard library only. Run behind an HTTPS reverse proxy: // node receiver.mjs (listens on 127.0.0.1:8000, or PORT). // Configure PUSH2HOOK_DEVICE_ID, PUSH2HOOK_SECRET (32+ UTF-8 bytes), // PUSH2HOOK_INBOX: an existing private directory outside the web root. import { createServer } from 'node:http'; import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto'; import * as fs from 'node:fs/promises'; import { isAbsolute, join } from 'node:path'; import { TextDecoder } from 'node:util'; const MAX_BODY = 1048576; const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value); const server = createServer(async (request, response) => { const reply = (status, message = '') => { request.resume(); const body = message ? JSON.stringify({ error: message }) : ''; response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Content-Length': Buffer.byteLength(body), ...(status === 405 ? { Allow: 'POST' } : {}), }); response.end(body); }; const header = name => typeof request.headers[name] === 'string' ? request.headers[name] : ''; let temporary; try { if (request.method !== 'POST') return reply(405, 'POST required'); if (header('content-type').split(';', 1)[0].trim().toLowerCase() !== 'application/json') { return reply(415, 'application/json required'); } const device = process.env.PUSH2HOOK_DEVICE_ID || ''; const secret = Buffer.from(process.env.PUSH2HOOK_SECRET || '', 'utf8'); const inbox = process.env.PUSH2HOOK_INBOX || ''; if (!device || secret.length < 32 || !isAbsolute(inbox) || !(await fs.stat(inbox)).isDirectory()) { return reply(503, 'Receiver not configured'); } const timestamp = header('x-timestamp'); const signature = header('x-signature'); if (header('x-device-id') !== device || !/^[0-9]{1,12}$/.test(timestamp) || Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300 || !/^[A-Za-z0-9+/]{43}=$/.test(signature)) { return reply(401, 'Authentication failed'); } const length = header('content-length'); if (!/^[0-9]{1,10}$/.test(length)) return reply(411, 'Content-Length required'); if (Number(length) > MAX_BODY) return reply(413, 'Body too large'); const chunks = []; let size = 0; for await (const chunk of request) { size += chunk.length; if (size > MAX_BODY) return reply(413, 'Body too large'); chunks.push(chunk); } const raw = Buffer.concat(chunks); if (raw.length !== Number(length)) return reply(400, 'Incomplete body'); // HMAC uses ORIGINAL bytes. Never parse/re-serialize JSON before verification. const expected = createHmac('sha256', secret).update(timestamp + '.', 'utf8').update(raw).digest(); const supplied = Buffer.from(signature, 'base64'); if (supplied.length !== 32 || !timingSafeEqual(expected, supplied)) { return reply(401, 'Authentication failed'); } let data; try { data = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw)); } catch { return reply(400, 'Invalid JSON'); } if (!isObject(data) || data.schemaVersion !== 1 || data.deviceId !== device || data.demo !== false || typeof data.eventId !== 'string' || data.eventId.length < 1 || data.eventId.length > 200 || /[^A-Za-z0-9._:-]/.test(data.eventId) || !isObject(data.source) || typeof data.source.packageName !== 'string' || !data.source.packageName || Buffer.byteLength(data.source.packageName, 'utf8') > 255 || !isObject(data.notification) || Object.keys(data.notification).length === 0) { return reply(400, 'Invalid notification or device mismatch'); } // Publish a complete private inbox file atomically, without overwriting an // existing device + eventId. Process these files asynchronously. const key = createHash('sha256').update(device + '\0' + data.eventId, 'utf8').digest('hex'); const target = join(inbox, key + '.json'); temporary = join(inbox, '.pending-' + randomUUID()); const output = await fs.open(temporary, 'wx', 0o600); try { await output.writeFile(raw); await output.sync(); } finally { await output.close(); } let duplicate = false; try { await fs.link(temporary, target); } catch (error) { if (error.code !== 'EEXIST' || !(await fs.stat(target)).isFile()) throw error; duplicate = true; } reply(duplicate ? 204 : 202); } catch { // A failed write must return 5xx so push2hook can retry. if (!response.headersSent) reply(503, 'Storage unavailable'); } finally { if (temporary) await fs.unlink(temporary).catch(() => {}); } }); server.requestTimeout = 15000; server.headersTimeout = 10000; server.listen(Number(process.env.PORT || 8000), '127.0.0.1');