# @strutvane/health: Know Your App Is Sick Before Your Users Do

Here's a story you may know.

The app is "up". The uptime monitor is green. And yet nothing works, because the disk filled up last night, or a migration never ran after the deploy, or someone left debug mode on in production. You find out from a customer email at 9:14 a.m. 😬

"Is the server answering?" is the wrong question. The right question is: **"Is everything the app depends on actually healthy?"**

That's what `@strutvane/health` answers.

---

## What it is

`@strutvane/health` adds **application health checks** to apps built on Strutvane, an open-source (MIT) TypeScript framework for business (B2B) apps.

It checks the things that really break apps (the database, pending migrations, the cache, disk space, writable folders, the app key, debug mode and missing environment settings), keeps a **history** of the results, sends **rate-limited alerts** when something goes wrong, and exposes the results two ways:

- **`node strut health:check`**, a command with proper exit codes for CI pipelines and cron jobs;
- **`GET /health.json`**, an endpoint for monitoring tools, protected by a token or your own policy.

## Why it exists

Two reasons.

**A plain "ping" isn't enough.** A simple liveness probe (Strutvane apps have `/up` for that) tells you the process is alive. It doesn't tell you the database answers in 900 ms instead of 3, or that the disk is 92% full. Health checks look *inside*.

**Health endpoints leak if you're not careful.** A typical health page cheerfully reports database hostnames, error messages and connection strings to anyone who asks. This package is **closed by default**, and it scrubs secrets out of every result before anything is stored, served, printed or sent.

## What you get

**Built-in checks**

| Check | What it does | Warns / fails when |
|---|---|---|
| `database` | Runs `SELECT 1` on the app's connection | slow (over your thresholds), or unreachable |
| `migrations` | Compares your migration files with what has run | a ran migration's file is missing / any migration is pending |
| `cache` | Writes, reads back and deletes a random probe key | slow round trip / mismatch or error |
| `disk-space` | Measures how full the `storage` disk is | at 70% / at 90% by default |
| `storage` | Writes, reads and removes a probe file in each folder | any folder or disk isn't writable |
| `app-key` | Checks `APP_KEY` with the framework's own key rules | missing or weak (the value is never shown) |
| `debug-mode` | Checks `APP_DEBUG` per environment | on in staging / on in production |
| `environment` | Every key in `.env.example` is defined (names only, never values) | a key is missing, or empty when marked required |
| heartbeats | How long since a scheduler or queue worker last checked in | over 120 s / over 600 s |

**Your own checks**, with `defineCheck({ name, run })`. The runner handles the failure cases for you: a thrown error becomes `failed` (with its message, never its stack trace), a check that hangs fails at its deadline, and a malformed result is reported as `failed`.

**Thresholds**: every check reports **ok**, **warning** or **failed**, and you tune the limits in `config/health.ts`.

**History**: results are stored in a database table (kept for 7 days by default), created by a normal migration.

**Alerts** to Slack, signed webhooks, or mail:

- **Throttled:** each check and status alerts at most once per period (60 minutes by default). Even with several servers, only one sends, because the throttle is claimed atomically in the cache.
- **Escalation:** a check going from warning to failed alerts at once.
- **Recovery:** a check that alerted sends one "all good again" message.
- **Isolated:** one broken channel never blocks the others.
- **Signed webhooks:** with a secret, every body carries an HMAC signature you can verify.

## The command: made for CI and cron

```bash
node strut health:check                         # table, alerts, history
node strut health:check --only database         # one check (repeatable)
node strut health:check --fail-on warning       # warnings fail too
node strut health:check --json                  # machine-readable
node strut health:list                          # what is registered
```

| Exit code | Meaning |
|---|---|
| 0 | Healthy (warnings allowed unless you pass `--fail-on warning`) |
| 1 | At least one check failed, or the app didn't boot |
| 2 | Usage error, such as an unknown check name |

Schedule it every few minutes with cron, a systemd timer or your platform's scheduler. It stores history and sends alerts; the JSON endpoint only reads.

## The endpoint: closed by default

```bash
curl -H "Authorization: Bearer $HEALTH_CHECK_TOKEN" https://app.example.com/health.json
```

- It answers **200** for ok and warning, and **503** for failed, so even a plain uptime monitor works without parsing any JSON.
- Access needs a bearer token (or your own policy, for example "admins only"). **With neither, it answers 404**, as if it didn't exist.
- A token in the query string is **ignored**, because URLs end up in logs. The token comparison runs in constant time.
- Wrong tokens are counted per client. After 10 failures in a minute, further wrong tokens get **429** (too many requests).
- Results are reused for 10 seconds and concurrent requests share one run, so nobody can use the endpoint to hammer your database.
- Responses are never cached by browsers or proxies, never include extra metadata, and include messages only if you opt in.

## How it fits into Strutvane

`@strutvane/health` is an **add-on**. It depends only on the published `@strutvane/framework` (as a peer dependency) and plugs in through its extension points: a service provider, CLI commands, an installer and the framework's own services.

It reuses the framework wherever it can: the app's database connection for the database check, the framework's key rules for the app-key check, the cache for alert throttling, and the framework's **SSRF-safe HTTP client** for alerts (SSRF is when an attacker tricks your server into calling internal addresses; this client refuses private, loopback and cloud-metadata addresses, even after DNS resolution or a redirect).

## A quick look

```bash
npm install @strutvane/health
node strut add health
node strut migrate           # creates the health_check_results table
```

The installer writes `config/health.ts` (never overwriting yours), the migration, a random 32-byte `HEALTH_CHECK_TOKEN` in `.env` (empty in `.env.example`), and registers the provider. Running it twice changes nothing. `node strut remove health` removes the provider, config entry and env key, but **keeps your history table**, because history is data.

A custom check for an external API:

```ts
import { defineCheck, Result } from '@strutvane/health'
import { HttpClientToken } from '@strutvane/framework'

export const paymentsApi = defineCheck({
  name: 'payments-api',
  label: 'Payments API',
  timeoutMs: 3000,
  async run({ make }) {
    const response = await make(HttpClientToken).timeout(2000).get('https://api.example.com/status')
    return response.ok ? Result.ok(`HTTP ${response.status}`) : Result.failed(`HTTP ${response.status}`)
  },
})
```

Register it in your app provider's `boot()` with `app.make(HealthToken).register(paymentsApi)`.

> ⚠️ This is a **0.2 preview**. The APIs may still change before 1.0, planned for January 2027.

## Built to be trusted

- **Secrets never leave the runner.** Before any result is stored, served, printed or sent: values of sensitive env variables (`*_PASSWORD`, `*_KEY`, `*_TOKEN`, `*_SECRET`…) are masked, credentials in URLs are masked, bearer tokens and password patterns are masked, and lengths are bounded.
- **Config can't escape the app.** `..` and absolute paths are refused. Probe files are random, created exclusively, and always removed.
- **Bad config stops the boot** with a list of every problem, for example a token shorter than 32 characters.
- **190 automated tests**, run on real engines: SQLite through the framework's driver, the shipped migration through the framework's own runner, and a real booted application for the endpoint.
- **CI on Linux, Windows and macOS**, on Node 24 and Node 26.
- **Security-reviewed** and secure by default.
- **Every release is staged by CI and approved by a human with two-factor authentication**, and published with **npm provenance**.

## What's next

- The framework's scheduler and queue workers will report **heartbeats** automatically once they ship. Until then, you can call `recordHeartbeat()` yourself.
- The framework's mailer isn't released yet, so **mail alerts** need a small transport you bind yourself for now.

---

## Try it, and tell me what you think

- ⭐ **GitHub:** [github.com/vishwajit-vm/strutvane-health](https://github.com/vishwajit-vm/strutvane-health)
- 📦 **npm:** [npmjs.com/package/@strutvane/health](https://www.npmjs.com/package/@strutvane/health)
- 💬 **Feedback welcome.** What's the outage that a health check would have caught for you? I'd love to turn it into a built-in check.

Next in the series: `@strutvane/social-login`, for "Sign in with Google" done safely. Follow along! 🩺

*— Vishwajit VM*

---

*Part of the Strutvane series. Strutvane™ is open source under the MIT licence.*
