'use strict'; const fs = require('fs'); const path = require('path'); const os = require('os'); const { randomBytes } = require('crypto'); const ENV_PATH = path.join(os.homedir(), '.memory-bridge', '.env'); let token = null; function init() { // Prefer env var (loaded by dotenv on subsequent runs) if (process.env.MEMORY_BRIDGE_TOKEN) { token = process.env.MEMORY_BRIDGE_TOKEN; return; } // Try reading directly from file (handles edge cases) try { const raw = fs.readFileSync(ENV_PATH, 'utf8'); const m = raw.match(/^MEMORY_BRIDGE_TOKEN=(.+)$/m); if (m) { token = m[1].trim(); process.env.MEMORY_BRIDGE_TOKEN = token; return; } } catch { /* file doesn't exist yet */ } // First run: generate and persist token = randomBytes(32).toString('hex'); const dir = path.dirname(ENV_PATH); fs.mkdirSync(dir, { recursive: true }); if (fs.existsSync(ENV_PATH)) { fs.appendFileSync(ENV_PATH, `\nMEMORY_BRIDGE_TOKEN=${token}\n`); } else { fs.writeFileSync( ENV_PATH, `MEMORY_BRIDGE_TOKEN=${token}\nMEMORY_BRIDGE_PORT=3722\nOLLAMA_URL=http://localhost:11434\n` ); } process.env.MEMORY_BRIDGE_TOKEN = token; console.log('\n══════════════════════════════════════════════════'); console.log('First run — your auth token (save this):'); console.log(` ${token}`); console.log(`Persisted to: ${ENV_PATH}`); console.log('══════════════════════════════════════════════════\n'); } function middleware(req, res, next) { const hdr = req.headers['authorization'] || ''; if (!hdr.startsWith('Bearer ')) { return res.status(401).json({ error: 'Authorization: Bearer required' }); } if (hdr.slice(7).trim() !== token) { return res.status(401).json({ error: 'Invalid token' }); } next(); } module.exports = { init, middleware };