Skip to content

Commit 4df339b

Browse files
committed
host: serve GET /api/health ahead of the sign-in wall (#2128)
An instance answers nothing without a session, so asking which build is running means counting startup banners. GET /api/health is an exact WebServer route, matched before the /api prefix that carries the wall, and answers exactly ok, version, commit and startedAt. It keeps the wall's Host/Origin half by reading the connection service's own decision, skips only the session half, and answers GET only.
1 parent be10ea2 commit 4df339b

8 files changed

Lines changed: 900 additions & 3 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The instance now answers `GET /api/health` without a session: a JSON object holding exactly `ok`, `version`, `commit` and `startedAt`, so a person or a monitor can ask which build is running instead of counting startup banners. It is served ahead of the sign-in wall as an exact route, keeps the wall's Host/Origin fence (loopback or a trusted authority only), answers `GET` only, and reports `commit: null` when the install has no git checkout of its own ([#2128](https://github.com/ThinkFlowLab/FlyBot/issues/2128)).

‎core/index.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import * as hooks from './src/host/hooks.js'
5151
import * as remoteChat from './src/host/remote-chat.js'
5252
import * as workflowStore from './src/host/workflow-store.js'
5353
import * as channel from './src/host/channel.js'
54+
import * as health from './src/host/health.js'
5455

5556
export { COLORS } from './src/host/constants.js'
5657

@@ -61,7 +62,7 @@ export const inject = ['llm', 'tools', 'systemPrompt', 'sessionController', 'ses
6162
// the functions other modules call; they call them through `rt` at run time, never during
6263
// install. Listeners run and tools are listed in registration order, so this order holds:
6364
// usage meters model requests after every listener that rewrites them.
64-
const MODULES = [diagnostics, store, harness, memberAuth, authz, models, permissions, turns, busyAck, steeringInterrupt, delivery, roster, folders, agents, prompt, timeContext, tools, decisions, projectState, meetings, chatIndex, groups, roomMembership, reach, tasks, projectBoard, taskDrive, approvals, resume, memory, parts, images, secrets, connectors, connectorAccess, capabilities, schedules, projectAssistant, projectChief, projectTeam, automationDefault, browser, usage, update, dshUpdate, hooks, remoteChat, workflowStore, channel]
65+
const MODULES = [diagnostics, store, harness, memberAuth, authz, models, permissions, turns, busyAck, steeringInterrupt, delivery, roster, folders, agents, prompt, timeContext, tools, decisions, projectState, meetings, chatIndex, groups, roomMembership, reach, tasks, projectBoard, taskDrive, approvals, resume, memory, parts, images, secrets, connectors, connectorAccess, capabilities, schedules, projectAssistant, projectChief, projectTeam, automationDefault, browser, usage, update, dshUpdate, hooks, remoteChat, workflowStore, health, channel]
6566

6667
export function apply(ctx, config = {}) {
6768
const rt = createRuntime(ctx, config)

‎core/src/host/health.js‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
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

Comments
 (0)