# Cyber Rakshak error monitoring: libraries for apps, servers and scripts

Version 1.1.0 · Copyright Laabam One Business Solutions (OPC) Private Limited · Released under the
[MIT licence](LICENSE): use, change and ship them in your own apps, free or paid, keeping the copyright line.

Your website's visitors already report errors through the script tag. These libraries do the same for your **mobile
apps, servers and scripts**: what went wrong lands on the same site's **Errors** page in the Cyber Rakshak console.
Each is **one file with no dependencies**: download it, add it to your project, start it with your site's app key
(`crk_…`: on the site's **Security scan** tab, under **Apps, servers and scripts**, press **Make an app key**).
`index.json` lists every file with its SHA-256, so you can check a download.

| For | File | What it catches by itself |
|---|---|---|
| Node.js 18+ | [`node/cyberrakshak-monitor.mjs`](node/cyberrakshak-monitor.mjs) (ES module) or [`.cjs`](node/cyberrakshak-monitor.cjs) (CommonJS, same code) | uncaught exceptions (then Node exits with code 1, as it would), unhandled promise rejections (Node's `--unhandled-rejections` behaviour kept); `expressErrorHandler()` for Express/Connect 5xx errors |
| React Native / Expo | [`react-native/cyberrakshak-monitor.ts`](react-native/cyberrakshak-monitor.ts) | every error reaching React Native's global handler (fatal ones as crashes, kept across the crash with AsyncStorage if you pass it); unhandled promise rejections in release builds on Hermes |
| PHP 8.1+ | [`php/CyberRakshakMonitor.php`](php/CyberRakshakMonitor.php.txt) (saved as `CyberRakshakMonitor.php`) | uncaught exceptions, fatal errors (out of memory too, where PHP still runs shutdown functions after it: Ubuntu's PHP 8.1.34 packages run none, so nothing can report it there); with `captureErrors`, warnings |
| Python 3.9+ | [`python/cyberrakshak_monitor.py`](python/cyberrakshak_monitor.py) | an exception that ends the program or a thread; ERROR log records with `LoggingHandler` |
| Shell (POSIX sh + curl) | [`shell/cr-report.sh`](shell/cr-report.sh) | a command run through it that fails: its name, exit code and last 20 lines of standard error |
| Android (Kotlin) | [`android/CyberRakshakMonitor.kt`](android/CyberRakshakMonitor.kt) | uncaught exceptions on any thread: written at once, sent at the next start (not native crashes or ANRs) |
| iOS (Swift) | [`ios/CyberRakshakMonitor.swift`](ios/CyberRakshakMonitor.swift) | uncaught Objective-C exceptions, sent at the next launch. **Not Swift runtime traps or signals** (a force-unwrapped nil, an index out of range, `fatalError`). Tested on macOS and an iOS Simulator, not yet on a real iPhone. |

The handlers your app already had still run, as they did: a library adds a report, it never changes what happens.

## Start

```js
// Node.js
import * as monitor from './cyberrakshak-monitor.mjs';
monitor.init({ key: process.env.CR_MONITOR_KEY, release: '2026.11.21', environment: 'production' });
app.use(monitor.expressErrorHandler());        // after your routes
monitor.captureException(err, { route: 'nightly-import', context: { batch: 42 } });
await monitor.flush(2000);                     // before you call process.exit() yourself
```

```ts
// Next.js (App Router, Node.js runtime): instrumentation.ts
import type { Instrumentation } from 'next';

export async function register() {
  if (process.env.NEXT_RUNTIME !== 'nodejs') return;
  const monitor = await import('./cyberrakshak-monitor.mjs');   // or '@cyberrakshak/monitor'
  monitor.init({ key: process.env.CR_MONITOR_KEY, release: process.env.VERCEL_GIT_COMMIT_SHA, environment: process.env.VERCEL_ENV });
}

export const onRequestError: Instrumentation.onRequestError = async (err, request, context) => {
  if (process.env.NEXT_RUNTIME !== 'nodejs') return;
  const monitor = await import('./cyberrakshak-monitor.mjs');
  await monitor.captureRequestError(err, request, context);     // route = method + routePath; sent before it returns
};
```

`captureRequestError` takes the route Next.js names (`POST /app/api/pay/route`), never `request.path` (it carries the
query string) and never the headers, and resolves once what is waiting is sent (at most 2 s), so a serverless function
is not frozen before it goes. With no `CR_MONITOR_KEY` (a preview, your own computer) nothing starts and nothing is sent.

```ts
// React Native / Expo
import * as monitor from './cyberrakshak-monitor';
monitor.init({ key: 'crk_…', release: '1.4.2+57', environment: 'production', storage: AsyncStorage });
monitor.setRoute('Checkout');                  // from your navigation's state change
// in an error boundary: monitor.captureException(error, { componentStack: info.componentStack });
```

```php
// PHP (Laravel: init in AppServiceProvider::boot() with 'handleExceptions' => false, and in bootstrap/app.php
// ->withExceptions(fn ($e) => $e->report(fn (Throwable $t) => \CyberRakshak\Monitor::captureException($t))))
require_once __DIR__.'/CyberRakshakMonitor.php';
\CyberRakshak\Monitor::init(['key' => getenv('CR_MONITOR_KEY'), 'environment' => 'production']);
\CyberRakshak\Monitor::captureException($e, ['route' => 'checkout']);
```

```python
# Python (Django and Flask notes are in the file's docstring)
import cyberrakshak_monitor as monitor
monitor.init(key=os.environ["CR_MONITOR_KEY"], release="2026.11.21", environment="production")
logging.getLogger().addHandler(monitor.LoggingHandler())
monitor.capture_exception(exc, route="nightly-import")
```

```sh
# Shell
export CR_MONITOR_KEY=crk_...
cr-report.sh run -- ./backup.sh --target s3://bucket   # output and exit code unchanged
cr-report.sh message --level error "Nightly import failed"
```

```kotlin
// Android: in Application.onCreate(); needs the INTERNET permission
CyberRakshakMonitor.init(this, CyberRakshakMonitor.Options(key = "crk_…", release = BuildConfig.VERSION_NAME))
CyberRakshakMonitor.captureException(e, route = "Checkout")
```

```swift
// iOS
CyberRakshakMonitor.start(.init(key: "crk_…", release: "1.4.2+57", environment: "production"))
CyberRakshakMonitor.captureError(error)
```

## Options (the same in every library, in its own spelling)

| Option | Meaning |
|---|---|
| `key` | Your site's app key, `crk_` and 32 letters or digits. Required; a library with no valid key does nothing. |
| `endpoint` | Where reports go. Default `https://app.cyberrakshak.ai/api/v1/app-reports`. |
| `release` | Your version or build (`A-Z a-z 0-9 . _ + -`, at most 60), so a problem shows the release it started in. |
| `environment` | `production`, `staging`… (`a-z 0-9 _ -`, at most 30). |
| `enabled` | `false` sends nothing (default `true`). |
| `sampleRate` | 0 to 1: the share of problems sent (default 1, all). |
| `beforeSend` | Gets each problem, already scrubbed; return it (changed if you like) or nothing to drop it. Shell: `CR_MONITOR_BEFORE_SEND`, a command that reads the problem's JSON and prints it. |
| `debug` | Says on the console / standard error what the library does and why something was not sent. The key is never printed. |
| `context` | Values sent with every problem: at most 20, strings (300 characters), numbers, true/false. |
| `scrubNames` | Names of your own whose values are removed, like `password=`: whole words, `A-Z a-z 0-9 _ . -`, at most 50 (`x-brand-key`, `face.key`). |
| `scrubPatterns` | Regular expressions of your own (the language's own syntax): what they match becomes `[removed]`. At most 20; one that does not compile, or matches an empty text, is left out. Not in the shell library. |

`scrubNames` and `scrubPatterns` only add to the built-in rules below: those always run first and cannot be switched
off. They apply to the message, the stack, the route and context values; a context entry whose name is a secret name
(built in, or one of yours) is sent as `[removed]`.

The shell library reads them from `CR_MONITOR_KEY`, `CR_MONITOR_ENDPOINT`, `CR_MONITOR_RELEASE`, `CR_MONITOR_ENVIRONMENT`,
`CR_MONITOR_ENABLED`, `CR_MONITOR_SAMPLE_RATE`, `CR_MONITOR_CONTEXT` (`k=v,k2=v2`), `CR_MONITOR_SCRUB_NAMES`
(`name1,name2`), `CR_MONITOR_DEBUG`.

## What is sent, and what never is

Sent, per problem: its kind (exception, crash, unhandled promise, log message, failed request, failed script), its
message, its stack trace (file, line and function; never argument values), the route, screen or command (never its query
string), the level, how many times it happened and when last; with each request: the library's name and version, the
platform and runtime (`node 22.4`, `android 14`, `ios 18.1`…), your release and environment.

Never sent: request or response bodies, headers, cookies, sessions, form fields, what a user types, environment
variables, local variables, device identifiers, location, contacts. The console keeps the address a report came from
only if your site keeps visitors' addresses.

**Scrubbed before anything leaves** (the same rules, in the same order, in every library, checked by one shared set of
test cases): query strings (`?name=…`); `Bearer`/`Basic` values; the value after `password`, `passwd`, `secret`,
`token`, `api_key`, `access_key`, `private_key`, `credential` or `session_id` and a `=` or `:` (quoted or not, any case);
JSON Web Tokens; keys that say what they are (`crk_`, `crw_`, `sk_live_`, `pk_live_`, `ghp_`, `xoxb-`, `AKIA`, `AIza`…);
email addresses; IBANs (that pass the ISO 13616 mod-97 check, written whole or in groups of four); card numbers (13 to
19 digits that pass the Luhn check); the value after `authorization`, `cookie` (and `set-cookie`), `signature`, `otp`,
`pin`, `cvv`, `cvc`, `iban`, `bban`, `pan`, `account_number` (`accountno`, `account-num`…), `sort_code`, `card_number`
or `bank_auth_id` and a `=` or `:`, as whole words only (not right after a letter or digit: `company:` and `spinning:`
stay); runs of 32 or more hex digits; runs of 40 or more letters and digits mixing upper case, lower case and digits.
They become `[removed]`, `[token]`, `[email]`, `[iban]` or `[card]`. The console scrubs everything again when it
arrives. Each library has a `scrub()` (shell: `cr-report.sh scrub`) that shows what a text would become, with your
`scrubNames` and `scrubPatterns` once it has started.

## How sending behaves

- At most **10 problems per request**, each request **under 64 KB** (long stacks are cut, then fewer problems go per
  request). Repeats of one problem (same kind, message and top frame) are **counted**, not resent; at most 50 different
  problems wait at once (the oldest go first).
- A request takes at most **5 s**; at exit, at most **2 s** are spent sending what is left. Sending happens off your
  main path (a background thread, a timer, the end of the request in PHP).
- **429** (slow down), **5xx** and no answer: kept and tried again later, never before `Retry-After`, with a growing wait
  otherwise. Mobile libraries keep them on the device, PHP and shell in a small file in the temp or cache folder, for the
  next launch, request or run.
- **401 / 403** (key not known, site not verified or monitoring off): dropped, and nothing is sent for an hour.
  **413 / 422** and other refusals: those problems are dropped, never retried.
- Nothing here throws into your code, and an error inside a library is never reported by itself.

## Tested

Against a stand-in console only (never a real Cyber Rakshak host): Node.js, React Native (logic under Node, types
checked against react-native's own), PHP (with and without curl and mbstring), Python, shell (sh + curl + awk), and
Kotlin (compiled against Android's `android.jar` alone, tested on a plain JVM), and Swift (Xcode 26.6, Apple Swift 6.3.3:
built for macOS and iOS devices, tested on macOS and on an iOS 26.5 Simulator; not yet on a real iPhone).
