|
| 1 | +// GET /api/health (#2128, P-392): the one answer the instance gives without a session, so |
| 2 | +// "does this process run the build I just published?" is asked of the service instead of |
| 3 | +// counted from startup banners. It is an exact WebServer route — the web server matches an |
| 4 | +// exact path before the /api prefix whose admission is the sign-in wall — and the four fields |
| 5 | +// are the whole contract: no environment, path, host name or dependency version. |
| 6 | +import { execFileSync } from 'node:child_process' |
| 7 | +import { existsSync, readFileSync } from 'node:fs' |
| 8 | +import { dirname, join } from 'node:path' |
| 9 | +import { fileURLToPath } from 'node:url' |
| 10 | + |
| 11 | +export const HEALTH_PATH = '/api/health' |
| 12 | + |
| 13 | +const PKG = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) |
| 14 | +// The package root (`core/` in the repository, the installed directory otherwise), and the |
| 15 | +// directory a clone puts it in. |
| 16 | +const PKG_ROOT = dirname(fileURLToPath(new URL('../../package.json', import.meta.url))) |
| 17 | + |
| 18 | +/** |
| 19 | + * HEAD of the clone this package sits in, or null for a package/path install. |
| 20 | + * Only the one directory that holds the package is asked: a path install lives at |
| 21 | + * `<project>/node_modules/ds-bot`, and climbing to `<project>` would report the user's own |
| 22 | + * checkout as this package's commit, against the `commit: null` promise in core-host.md. |
| 23 | + */ |
| 24 | +export function readCommit(start = dirname(PKG_ROOT)) { |
| 25 | + if (!existsSync(join(start, '.git'))) return null |
| 26 | + try { |
| 27 | + const sha = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: start, encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] }).trim() |
| 28 | + return /^[0-9a-f]{40}$/.test(sha) ? sha : null |
| 29 | + } catch { |
| 30 | + // `git` may not exist on this machine, and a .git that is not a repository is no checkout. |
| 31 | + return null |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +/** The moment this process started, from its own uptime: stable while it runs, new after a restart. */ |
| 36 | +export function startedAtOf(now = Date.now(), uptimeMs = process.uptime() * 1000) { |
| 37 | + return new Date(now - uptimeMs).toISOString() |
| 38 | +} |
| 39 | + |
| 40 | +/** Exactly the four fields, whatever the caller passes in. */ |
| 41 | +export function healthPayload({ version = PKG.version, commit = readCommit(), startedAt = startedAtOf() } = {}) { |
| 42 | + // JSON.stringify drops an undefined value silently, and a missing `version` key breaks the |
| 43 | + // four-key contract the tests and the issue hold to, so a bad input answers a readable value. |
| 44 | + const name = typeof version === 'string' ? version.trim() : '' |
| 45 | + return { ok: true, version: name || 'unknown', commit, startedAt } |
| 46 | +} |
| 47 | + |
| 48 | +export function install(rt) { |
| 49 | + const { ctx } = rt |
| 50 | + // The connection service owns the Host/Origin fence. Reading the decision from it keeps one |
| 51 | + // implementation: the same loopback/bind/trusted-Host and Origin rules every /api path gets. |
| 52 | + const connection = ctx.get?.('connection') |
| 53 | + const attach = sub => { |
| 54 | + if (sub?.webServer === undefined || connection === undefined) return |
| 55 | + // Built here, not in install(): a composition with no web server registers no route and must |
| 56 | + // not pay for a `git` call on behalf of one. |
| 57 | + const payload = healthPayload() |
| 58 | + const route = { |
| 59 | + kind: 'exact', |
| 60 | + path: HEALTH_PATH, |
| 61 | + handler: (req, res) => { |
| 62 | + // An exact route is matched before the /api prefix, so the wall's own admission never |
| 63 | + // runs for it. Keep its first half: a request whose Host is not loopback, the bind |
| 64 | + // address or a trusted authority (or whose Origin is foreign) is refused, exactly as |
| 65 | + // the wall refuses it. Only the session half is skipped. |
| 66 | + if (connection.requestRejection?.(req) === 403) { |
| 67 | + res.writeHead(403) |
| 68 | + res.end('forbidden') |
| 69 | + return |
| 70 | + } |
| 71 | + if (req.method !== 'GET') { |
| 72 | + res.writeHead(405, { allow: 'GET' }) |
| 73 | + res.end() |
| 74 | + return |
| 75 | + } |
| 76 | + const body = JSON.stringify(payload) |
| 77 | + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }) |
| 78 | + res.end(body) |
| 79 | + }, |
| 80 | + } |
| 81 | + sub.effect(() => sub.webServer.register(route), 'ds-bot: /api/health route') |
| 82 | + } |
| 83 | + // No `webServer` outside the Web composition (Electron serves files over IPC): then the |
| 84 | + // endpoint simply does not exist, and nothing else changes. |
| 85 | + if (typeof ctx.inject === 'function') ctx.inject(['webServer'], attach) |
| 86 | + else if (ctx.get?.('webServer') !== undefined) attach({ webServer: ctx.get('webServer'), effect: (execute, label) => ctx.effect(execute, label) }) |
| 87 | +} |
0 commit comments