@simplr-ai/express 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +122 -0
- package/dist/fastify.cjs +241 -0
- package/dist/fastify.cjs.map +1 -0
- package/dist/fastify.d.cts +11 -0
- package/dist/fastify.d.ts +11 -0
- package/dist/fastify.js +214 -0
- package/dist/fastify.js.map +1 -0
- package/dist/hono.cjs +246 -0
- package/dist/hono.cjs.map +1 -0
- package/dist/hono.d.cts +25 -0
- package/dist/hono.d.ts +25 -0
- package/dist/hono.js +218 -0
- package/dist/hono.js.map +1 -0
- package/dist/index.cjs +244 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +96 -0
- package/dist/index.d.ts +96 -0
- package/dist/index.js +210 -0
- package/dist/index.js.map +1 -0
- package/dist/next.cjs +269 -0
- package/dist/next.cjs.map +1 -0
- package/dist/next.d.cts +41 -0
- package/dist/next.d.ts +41 -0
- package/dist/next.js +241 -0
- package/dist/next.js.map +1 -0
- package/dist/types-CmzpR5S4.d.cts +115 -0
- package/dist/types-CmzpR5S4.d.ts +115 -0
- package/package.json +108 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Simplr
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# @simplr-ai/express
|
|
2
|
+
|
|
3
|
+
Drop-in **server middleware** that auto-runs [Simplr](https://docs.simplr.so) fraud/identity checks (and optionally ships edge logs) on every request — for **Express, Fastify, Hono, and Next.js**.
|
|
4
|
+
|
|
5
|
+
It wraps the [`@simplr-ai/node`](https://www.npmjs.com/package/@simplr-ai/node) server SDK: same endpoints, same `X-API-Key` auth, same `{ success, message, content }` envelope, same 15s default timeout. Use your **secret key** (`sk_live_… / sk_test_…`) — this runs server-side only.
|
|
6
|
+
|
|
7
|
+
Docs: https://docs.simplr.so/docs/sdks/
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @simplr-ai/express @simplr-ai/node
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Frameworks are **optional peer dependencies** — install only the one you use. Requires Node 18+ (built-in `fetch`).
|
|
16
|
+
|
|
17
|
+
## Express
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import express from "express";
|
|
21
|
+
import { simplrExpress } from "@simplr-ai/express";
|
|
22
|
+
|
|
23
|
+
const app = express();
|
|
24
|
+
app.use(express.json()); // so the default extractor can read email/phone from the body
|
|
25
|
+
app.use(simplrExpress({ apiKey: process.env.SIMPLR_API_KEY! }));
|
|
26
|
+
|
|
27
|
+
app.post("/signup", (req, res) => {
|
|
28
|
+
// req.simplr is the CheckResult (or null if the check failed open)
|
|
29
|
+
res.json({ risk: req.simplr?.risk_level });
|
|
30
|
+
});
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Blocked requests (risk **high** or above by default) get a `403` with a JSON envelope before your handler runs.
|
|
34
|
+
|
|
35
|
+
## Fastify
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import Fastify from "fastify";
|
|
39
|
+
import { simplrFastify } from "@simplr-ai/express/fastify";
|
|
40
|
+
|
|
41
|
+
const app = Fastify();
|
|
42
|
+
await app.register(simplrFastify, { apiKey: process.env.SIMPLR_API_KEY! });
|
|
43
|
+
|
|
44
|
+
app.post("/signup", async (req) => ({ risk: req.simplr?.risk_level }));
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Registers a `preHandler` hook and decorates `request.simplr`.
|
|
48
|
+
|
|
49
|
+
## Hono
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { Hono } from "hono";
|
|
53
|
+
import { simplrHono, getSimplr } from "@simplr-ai/express/hono";
|
|
54
|
+
|
|
55
|
+
const app = new Hono();
|
|
56
|
+
app.use("*", simplrHono({ apiKey: process.env.SIMPLR_API_KEY! }));
|
|
57
|
+
|
|
58
|
+
app.post("/signup", (c) => c.json({ risk: getSimplr(c)?.risk_level }));
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The result is stored with `c.set('simplr', result)`; read it with `c.get('simplr')` or the `getSimplr(c)` helper. Hono bodies are read async, so the default extractor uses headers only — pass a custom `extract` to also score body `email`/`phone`.
|
|
62
|
+
|
|
63
|
+
## Next.js (app router)
|
|
64
|
+
|
|
65
|
+
**Edge/Node middleware** (`middleware.ts`):
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { simplrNextMiddleware } from "@simplr-ai/express/next";
|
|
69
|
+
|
|
70
|
+
export const middleware = simplrNextMiddleware({ apiKey: process.env.SIMPLR_API_KEY! });
|
|
71
|
+
export const config = { matcher: ["/api/:path*"] };
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Returns `NextResponse.next()` to allow, or a `403` `NextResponse.json(...)` to block.
|
|
75
|
+
|
|
76
|
+
**Route-handler wrapper** for app-router API routes (`app/api/signup/route.ts`):
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import { withSimplr } from "@simplr-ai/express/next";
|
|
80
|
+
|
|
81
|
+
export const POST = withSimplr(
|
|
82
|
+
async (req) => {
|
|
83
|
+
// req.simplr is the CheckResult
|
|
84
|
+
return Response.json({ ok: true });
|
|
85
|
+
},
|
|
86
|
+
{ apiKey: process.env.SIMPLR_API_KEY! },
|
|
87
|
+
);
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Options
|
|
91
|
+
|
|
92
|
+
| Option | Type | Default | Description |
|
|
93
|
+
| --- | --- | --- | --- |
|
|
94
|
+
| `apiKey` | `string` | — (required) | Secret key (`sk_…`). Server-side only. |
|
|
95
|
+
| `baseUrl` | `string` | `https://api.simplr.sh` | API base URL (trailing slashes stripped). |
|
|
96
|
+
| `timeoutMs` | `number` | `15000` | Per-request timeout. |
|
|
97
|
+
| `fetch` | `typeof fetch` | global `fetch` | Override the fetch implementation. |
|
|
98
|
+
| `extract` | `(req) => CheckInput` | IP + user-agent + body `email`/`phone` | Build the `CheckInput` for a request. |
|
|
99
|
+
| `onResult` | `(result, ctx) => void` | — | Observe every result (and `{ req, input, blocked }`). |
|
|
100
|
+
| `block` | `(result) => boolean` \| `{ whenRiskAtLeast: RiskLevel }` | `{ whenRiskAtLeast: "high" }` | Decide whether to block. |
|
|
101
|
+
| `ingestLogs` | `boolean` | `false` | Ship a `/v1/edge/logs` entry per request. |
|
|
102
|
+
| `deviceId` | `string` | `"simplr-edge-middleware"` | Device id for ingested logs. |
|
|
103
|
+
| `failOpen` | `boolean` | `true` | Let requests through if the Simplr check fails. |
|
|
104
|
+
|
|
105
|
+
### Threshold blocking
|
|
106
|
+
|
|
107
|
+
Risk levels are ordered `low < medium < high < critical`. The default `block` blocks when the result is **at or above `high`** (i.e. `high` and `critical`). Override with a threshold (`block: { whenRiskAtLeast: "medium" }`) or a custom predicate (`block: (r) => r.risk_score > 80`).
|
|
108
|
+
|
|
109
|
+
### Fail-open
|
|
110
|
+
|
|
111
|
+
By default (`failOpen: true`) a Simplr outage — network error, timeout, or 5xx — does **not** take down your app: the middleware logs nothing to the client, attaches `req.simplr = null`, and continues to your handler. Set `failOpen: false` to **fail closed** and surface the error (Express forwards it to `next(err)`; the other adapters re-throw).
|
|
112
|
+
|
|
113
|
+
## API by subpath
|
|
114
|
+
|
|
115
|
+
- `@simplr-ai/express` — `createGuard`, `simplrExpress`, helpers (`riskRank`, `riskAtLeast`, `blockEnvelope`, `defaultExtract`), `createClient`, and all types.
|
|
116
|
+
- `@simplr-ai/express/fastify` — `simplrFastify` plugin.
|
|
117
|
+
- `@simplr-ai/express/hono` — `simplrHono`, `getSimplr`.
|
|
118
|
+
- `@simplr-ai/express/next` — `simplrNextMiddleware`, `withSimplr`.
|
|
119
|
+
|
|
120
|
+
## License
|
|
121
|
+
|
|
122
|
+
MIT
|
package/dist/fastify.cjs
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/fastify.ts
|
|
21
|
+
var fastify_exports = {};
|
|
22
|
+
__export(fastify_exports, {
|
|
23
|
+
simplrFastify: () => simplrFastify
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(fastify_exports);
|
|
26
|
+
|
|
27
|
+
// src/client.ts
|
|
28
|
+
var DEFAULT_BASE_URL = "https://api.simplr.sh";
|
|
29
|
+
var SimplrError = class extends Error {
|
|
30
|
+
status;
|
|
31
|
+
body;
|
|
32
|
+
constructor(message, status, body) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.name = "SimplrError";
|
|
35
|
+
this.status = status;
|
|
36
|
+
this.body = body;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
function createClient(config) {
|
|
40
|
+
if (!config?.apiKey) throw new Error("Simplr: `apiKey` is required");
|
|
41
|
+
const baseUrl = (config.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
42
|
+
const timeoutMs = config.timeoutMs ?? 15e3;
|
|
43
|
+
const fetchImpl = config.fetch ?? globalThis.fetch;
|
|
44
|
+
if (typeof fetchImpl !== "function") {
|
|
45
|
+
throw new Error(
|
|
46
|
+
"Simplr: no global fetch available \u2014 use Node 18+ or pass `fetch` in options"
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
async function apiRequest(method, path, body) {
|
|
50
|
+
const controller = new AbortController();
|
|
51
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
52
|
+
try {
|
|
53
|
+
const res = await fetchImpl(`${baseUrl}${path}`, {
|
|
54
|
+
method,
|
|
55
|
+
headers: { "Content-Type": "application/json", "X-API-Key": config.apiKey },
|
|
56
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0,
|
|
57
|
+
signal: controller.signal
|
|
58
|
+
});
|
|
59
|
+
const text = await res.text();
|
|
60
|
+
let parsed;
|
|
61
|
+
try {
|
|
62
|
+
parsed = text ? JSON.parse(text) : void 0;
|
|
63
|
+
} catch {
|
|
64
|
+
parsed = text;
|
|
65
|
+
}
|
|
66
|
+
if (!res.ok) {
|
|
67
|
+
const message = parsed && (parsed.message || parsed.error) || `Simplr API error ${res.status}`;
|
|
68
|
+
throw new SimplrError(message, res.status, parsed);
|
|
69
|
+
}
|
|
70
|
+
return parsed && typeof parsed === "object" && "content" in parsed ? parsed.content : parsed;
|
|
71
|
+
} catch (err) {
|
|
72
|
+
if (err instanceof SimplrError) throw err;
|
|
73
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
74
|
+
throw new SimplrError(`Request to ${path} timed out after ${timeoutMs}ms`, 0, null);
|
|
75
|
+
}
|
|
76
|
+
throw new SimplrError(err instanceof Error ? err.message : "Network error", 0, null);
|
|
77
|
+
} finally {
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
check: (input) => apiRequest("POST", "/v1/check", input),
|
|
83
|
+
ingestLogs: (deviceId, logs) => apiRequest("POST", "/v1/edge/logs", { device_id: deviceId, logs })
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/core.ts
|
|
88
|
+
var RISK_ORDER = {
|
|
89
|
+
low: 0,
|
|
90
|
+
medium: 1,
|
|
91
|
+
high: 2,
|
|
92
|
+
critical: 3
|
|
93
|
+
};
|
|
94
|
+
var DEFAULT_DEVICE_ID = "simplr-edge-middleware";
|
|
95
|
+
var DEFAULT_THRESHOLD = "high";
|
|
96
|
+
function riskRank(level) {
|
|
97
|
+
return RISK_ORDER[level] ?? 0;
|
|
98
|
+
}
|
|
99
|
+
function riskAtLeast(level, min) {
|
|
100
|
+
return riskRank(level) >= riskRank(min);
|
|
101
|
+
}
|
|
102
|
+
function readHeader(headers, name) {
|
|
103
|
+
if (!headers) return void 0;
|
|
104
|
+
const h = headers;
|
|
105
|
+
if (typeof h.get === "function") {
|
|
106
|
+
const v = h.get(name);
|
|
107
|
+
return v == null ? void 0 : String(v);
|
|
108
|
+
}
|
|
109
|
+
const lower = name.toLowerCase();
|
|
110
|
+
if (lower in h && h[lower] != null) return String(h[lower]);
|
|
111
|
+
for (const key of Object.keys(h)) {
|
|
112
|
+
if (key.toLowerCase() === lower && h[key] != null) return String(h[key]);
|
|
113
|
+
}
|
|
114
|
+
return void 0;
|
|
115
|
+
}
|
|
116
|
+
function extractIp(req) {
|
|
117
|
+
const fwd = readHeader(req?.headers, "x-forwarded-for");
|
|
118
|
+
if (fwd) return fwd.split(",")[0].trim();
|
|
119
|
+
const real = readHeader(req?.headers, "x-real-ip");
|
|
120
|
+
if (real) return real;
|
|
121
|
+
return req?.ip || req?.socket?.remoteAddress || req?.connection?.remoteAddress || void 0;
|
|
122
|
+
}
|
|
123
|
+
function defaultExtract(req) {
|
|
124
|
+
const input = {};
|
|
125
|
+
const device = {};
|
|
126
|
+
const ip = extractIp(req);
|
|
127
|
+
if (ip) device.ip = ip;
|
|
128
|
+
const ua = readHeader(req?.headers, "user-agent");
|
|
129
|
+
if (ua) device.user_agent = ua;
|
|
130
|
+
if (Object.keys(device).length > 0) input.device = device;
|
|
131
|
+
const body = req?.body;
|
|
132
|
+
if (body && typeof body === "object") {
|
|
133
|
+
const b = body;
|
|
134
|
+
if (typeof b.email === "string") input.email = b.email;
|
|
135
|
+
if (typeof b.phone === "string") input.phone = b.phone;
|
|
136
|
+
}
|
|
137
|
+
return input;
|
|
138
|
+
}
|
|
139
|
+
function normalizeBlock(block) {
|
|
140
|
+
if (typeof block === "function") return block;
|
|
141
|
+
const threshold = block?.whenRiskAtLeast ?? DEFAULT_THRESHOLD;
|
|
142
|
+
return (result) => riskAtLeast(result.risk_level, threshold);
|
|
143
|
+
}
|
|
144
|
+
function createGuard(options) {
|
|
145
|
+
if (!options?.apiKey) throw new Error("createGuard: `apiKey` is required");
|
|
146
|
+
const client = createClient({
|
|
147
|
+
apiKey: options.apiKey,
|
|
148
|
+
baseUrl: options.baseUrl,
|
|
149
|
+
timeoutMs: options.timeoutMs,
|
|
150
|
+
fetch: options.fetch
|
|
151
|
+
});
|
|
152
|
+
const extract = options.extract ?? defaultExtract;
|
|
153
|
+
const shouldBlock = normalizeBlock(options.block);
|
|
154
|
+
const failOpen = options.failOpen ?? true;
|
|
155
|
+
const ingestLogs = options.ingestLogs ?? false;
|
|
156
|
+
const deviceId = options.deviceId ?? DEFAULT_DEVICE_ID;
|
|
157
|
+
async function run(req) {
|
|
158
|
+
const input = await extract(req);
|
|
159
|
+
let result;
|
|
160
|
+
try {
|
|
161
|
+
result = await client.check(input);
|
|
162
|
+
} catch (error) {
|
|
163
|
+
if (failOpen) {
|
|
164
|
+
return { result: null, blocked: false, input, error };
|
|
165
|
+
}
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
const blocked = shouldBlock(result);
|
|
169
|
+
const ctx = { req, input, blocked };
|
|
170
|
+
if (options.onResult) {
|
|
171
|
+
try {
|
|
172
|
+
await options.onResult(result, ctx);
|
|
173
|
+
} catch {
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if (ingestLogs) {
|
|
177
|
+
try {
|
|
178
|
+
await client.ingestLogs(deviceId, [
|
|
179
|
+
{
|
|
180
|
+
category: "security",
|
|
181
|
+
level: blocked ? "warn" : "info",
|
|
182
|
+
message: blocked ? "simplr guard blocked request" : "simplr guard checked request",
|
|
183
|
+
risk_level: result.risk_level,
|
|
184
|
+
risk_score: result.risk_score
|
|
185
|
+
}
|
|
186
|
+
]);
|
|
187
|
+
} catch {
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return { result, blocked, input };
|
|
191
|
+
}
|
|
192
|
+
return { client, run };
|
|
193
|
+
}
|
|
194
|
+
function blockEnvelope(result) {
|
|
195
|
+
return {
|
|
196
|
+
error: "request_blocked",
|
|
197
|
+
message: "This request was blocked by Simplr fraud protection.",
|
|
198
|
+
risk_level: result.risk_level,
|
|
199
|
+
risk_score: result.risk_score
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// src/fastify.ts
|
|
204
|
+
function simplrFastify(fastify, options, done) {
|
|
205
|
+
try {
|
|
206
|
+
const guard = createGuard(options);
|
|
207
|
+
const failOpen = options.failOpen ?? true;
|
|
208
|
+
if (typeof fastify.decorateRequest === "function") {
|
|
209
|
+
fastify.decorateRequest("simplr", null);
|
|
210
|
+
}
|
|
211
|
+
fastify.addHook(
|
|
212
|
+
"preHandler",
|
|
213
|
+
async (request, reply) => {
|
|
214
|
+
try {
|
|
215
|
+
const outcome = await guard.run(request);
|
|
216
|
+
request.simplr = outcome.result;
|
|
217
|
+
if (outcome.blocked && outcome.result) {
|
|
218
|
+
reply.code(403).send(blockEnvelope(outcome.result));
|
|
219
|
+
return reply;
|
|
220
|
+
}
|
|
221
|
+
} catch (err) {
|
|
222
|
+
if (failOpen) {
|
|
223
|
+
request.simplr = null;
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
throw err;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
);
|
|
230
|
+
done?.();
|
|
231
|
+
} catch (err) {
|
|
232
|
+
if (done) done(err);
|
|
233
|
+
else throw err;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
simplrFastify[/* @__PURE__ */ Symbol.for("skip-override")] = true;
|
|
237
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
238
|
+
0 && (module.exports = {
|
|
239
|
+
simplrFastify
|
|
240
|
+
});
|
|
241
|
+
//# sourceMappingURL=fastify.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/fastify.ts","../src/client.ts","../src/core.ts"],"sourcesContent":["/**\n * Fastify adapter. A plugin that registers a `preHandler` hook decorating\n * `request.simplr` and short-circuiting blocked requests with a 403.\n *\n * ```ts\n * import Fastify from \"fastify\";\n * import { simplrFastify } from \"@simplr-ai/express/fastify\";\n * const app = Fastify();\n * await app.register(simplrFastify, { apiKey: process.env.SIMPLR_API_KEY! });\n * ```\n */\nimport { blockEnvelope, createGuard } from \"./core.js\";\nimport type { CheckResult, GuardOptions } from \"./types.js\";\n\ntype FastifyInstance = any;\ntype FastifyRequest = any;\ntype FastifyReply = {\n code(statusCode: number): FastifyReply;\n send(payload: unknown): unknown;\n};\n\n/**\n * Fastify plugin. Register with `app.register(simplrFastify, options)`.\n * Accepts the standard `(fastify, options, done)` plugin signature.\n */\nexport function simplrFastify(\n fastify: FastifyInstance,\n options: GuardOptions,\n done?: (err?: Error) => void,\n): void {\n try {\n const guard = createGuard(options);\n const failOpen = options.failOpen ?? true;\n\n // Decorate so TypeScript/Fastify know about `request.simplr`.\n if (typeof fastify.decorateRequest === \"function\") {\n fastify.decorateRequest(\"simplr\", null);\n }\n\n fastify.addHook(\n \"preHandler\",\n async (request: FastifyRequest, reply: FastifyReply) => {\n try {\n const outcome = await guard.run(request);\n request.simplr = outcome.result;\n if (outcome.blocked && outcome.result) {\n reply.code(403).send(blockEnvelope(outcome.result));\n return reply;\n }\n } catch (err) {\n if (failOpen) {\n request.simplr = null;\n return;\n }\n throw err;\n }\n },\n );\n\n done?.();\n } catch (err) {\n if (done) done(err as Error);\n else throw err;\n }\n}\n\n// Mark as a Fastify plugin so `fastify-plugin`-style encapsulation skipping is\n// not required; Fastify reads this property when present.\n(simplrFastify as any)[Symbol.for(\"skip-override\")] = true;\n\n// Consumers can augment `FastifyRequest` with `simplr?: CheckResult | null`\n// themselves; we don't `declare module \"fastify\"` here so the package builds\n// without `fastify` (an optional peer) installed. `CheckResult` is re-exported\n// for that purpose.\nexport type { CheckResult };\n","/**\n * Thin internal client.\n *\n * This is a ~40-line port of the minimal call path from `@simplr-ai/node`\n * (`apiRequest` + `check` + `edge.ingestLogs`) so that this package builds and\n * tests without an unbuilt workspace dependency or any network access.\n *\n * In production this package pairs with `@simplr-ai/node`; the endpoints, auth\n * header (`X-API-Key`), `{ success, message, content }` envelope unwrapping, and\n * 15s default timeout here are byte-for-byte compatible with that SDK and the\n * Simplr API contract.\n */\nimport type { CheckInput, CheckResult, EdgeLogEntry } from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.simplr.sh\";\n\n/** Thrown when the Simplr API returns a non-2xx response or the request fails. */\nexport class SimplrError extends Error {\n readonly status: number;\n readonly body: unknown;\n constructor(message: string, status: number, body: unknown) {\n super(message);\n this.name = \"SimplrError\";\n this.status = status;\n this.body = body;\n }\n}\n\nexport interface ClientConfig {\n apiKey: string;\n baseUrl?: string;\n timeoutMs?: number;\n fetch?: typeof fetch;\n}\n\nexport interface SimplrClient {\n check(input: CheckInput): Promise<CheckResult>;\n ingestLogs(deviceId: string, logs: EdgeLogEntry[]): Promise<unknown>;\n}\n\nexport function createClient(config: ClientConfig): SimplrClient {\n if (!config?.apiKey) throw new Error(\"Simplr: `apiKey` is required\");\n const baseUrl = (config.baseUrl || DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const timeoutMs = config.timeoutMs ?? 15000;\n const fetchImpl = config.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new Error(\n \"Simplr: no global fetch available — use Node 18+ or pass `fetch` in options\",\n );\n }\n\n async function apiRequest<T>(method: string, path: string, body?: unknown): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n method,\n headers: { \"Content-Type\": \"application/json\", \"X-API-Key\": config.apiKey },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: controller.signal,\n });\n const text = await res.text();\n let parsed: any;\n try {\n parsed = text ? JSON.parse(text) : undefined;\n } catch {\n parsed = text;\n }\n if (!res.ok) {\n const message =\n (parsed && (parsed.message || parsed.error)) || `Simplr API error ${res.status}`;\n throw new SimplrError(message, res.status, parsed);\n }\n return (parsed && typeof parsed === \"object\" && \"content\" in parsed\n ? parsed.content\n : parsed) as T;\n } catch (err) {\n if (err instanceof SimplrError) throw err;\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new SimplrError(`Request to ${path} timed out after ${timeoutMs}ms`, 0, null);\n }\n throw new SimplrError(err instanceof Error ? err.message : \"Network error\", 0, null);\n } finally {\n clearTimeout(timer);\n }\n }\n\n return {\n check: (input) => apiRequest<CheckResult>(\"POST\", \"/v1/check\", input),\n ingestLogs: (deviceId, logs) =>\n apiRequest(\"POST\", \"/v1/edge/logs\", { device_id: deviceId, logs }),\n };\n}\n","/**\n * Framework-agnostic guard engine.\n *\n * `createGuard` returns an object that, given any request-like object, builds a\n * `CheckInput`, calls `/v1/check`, decides whether to block, optionally ships an\n * edge log, and fails open on error. Framework adapters (express/fastify/hono/\n * next) are thin wrappers over this engine.\n */\nimport { createClient, type SimplrClient } from \"./client.js\";\nimport type {\n BlockThreshold,\n CheckInput,\n CheckResult,\n GuardContext,\n GuardOptions,\n GuardOutcome,\n RiskLevel,\n} from \"./types.js\";\n\nconst RISK_ORDER: Record<RiskLevel, number> = {\n low: 0,\n medium: 1,\n high: 2,\n critical: 3,\n};\n\nconst DEFAULT_DEVICE_ID = \"simplr-edge-middleware\";\nconst DEFAULT_THRESHOLD: RiskLevel = \"high\";\n\n/** Numeric rank of a risk level. Unknown levels rank as the lowest (0). */\nexport function riskRank(level: RiskLevel | string | undefined): number {\n return RISK_ORDER[level as RiskLevel] ?? 0;\n}\n\n/** True when `level` is at least `min` in the low<medium<high<critical ordering. */\nexport function riskAtLeast(level: RiskLevel | string | undefined, min: RiskLevel): boolean {\n return riskRank(level) >= riskRank(min);\n}\n\n/** Read a header from either a plain bag (lowercase keys) or a Headers-like getter. */\nfunction readHeader(headers: unknown, name: string): string | undefined {\n if (!headers) return undefined;\n const h = headers as any;\n if (typeof h.get === \"function\") {\n const v = h.get(name);\n return v == null ? undefined : String(v);\n }\n // Plain object: try the lowercase key, then a case-insensitive scan.\n const lower = name.toLowerCase();\n if (lower in h && h[lower] != null) return String(h[lower]);\n for (const key of Object.keys(h)) {\n if (key.toLowerCase() === lower && h[key] != null) return String(h[key]);\n }\n return undefined;\n}\n\n/** Best-effort client IP from common header and socket locations. */\nfunction extractIp(req: any): string | undefined {\n const fwd = readHeader(req?.headers, \"x-forwarded-for\");\n if (fwd) return fwd.split(\",\")[0]!.trim();\n const real = readHeader(req?.headers, \"x-real-ip\");\n if (real) return real;\n return (\n req?.ip ||\n req?.socket?.remoteAddress ||\n req?.connection?.remoteAddress ||\n undefined\n );\n}\n\n/**\n * Default request → CheckInput extractor. Pulls the client IP and user-agent into\n * `device`, and lifts `email`/`phone` from a parsed JSON body when present.\n */\nexport function defaultExtract(req: any): CheckInput {\n const input: CheckInput = {};\n\n const device: Record<string, unknown> = {};\n const ip = extractIp(req);\n if (ip) device.ip = ip;\n const ua = readHeader(req?.headers, \"user-agent\");\n if (ua) device.user_agent = ua;\n if (Object.keys(device).length > 0) input.device = device;\n\n const body = req?.body;\n if (body && typeof body === \"object\") {\n const b = body as Record<string, unknown>;\n if (typeof b.email === \"string\") input.email = b.email;\n if (typeof b.phone === \"string\") input.phone = b.phone;\n }\n\n return input;\n}\n\nfunction normalizeBlock(\n block: GuardOptions[\"block\"],\n): (result: CheckResult) => boolean {\n if (typeof block === \"function\") return block;\n const threshold = (block as BlockThreshold | undefined)?.whenRiskAtLeast ?? DEFAULT_THRESHOLD;\n return (result) => riskAtLeast(result.risk_level, threshold);\n}\n\nexport interface Guard<Req = any> {\n /** The underlying thin Simplr client (check + edge log ingestion). */\n readonly client: SimplrClient;\n /** Run the full engine against a request; never throws when `failOpen`. */\n run(req: Req): Promise<GuardOutcome>;\n}\n\nexport function createGuard<Req = any>(options: GuardOptions<Req>): Guard<Req> {\n if (!options?.apiKey) throw new Error(\"createGuard: `apiKey` is required\");\n\n const client = createClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n timeoutMs: options.timeoutMs,\n fetch: options.fetch,\n });\n\n const extract = options.extract ?? defaultExtract;\n const shouldBlock = normalizeBlock(options.block);\n const failOpen = options.failOpen ?? true;\n const ingestLogs = options.ingestLogs ?? false;\n const deviceId = options.deviceId ?? DEFAULT_DEVICE_ID;\n\n async function run(req: Req): Promise<GuardOutcome> {\n const input = await extract(req);\n let result: CheckResult;\n try {\n result = await client.check(input);\n } catch (error) {\n if (failOpen) {\n return { result: null, blocked: false, input, error };\n }\n throw error;\n }\n\n const blocked = shouldBlock(result);\n const ctx: GuardContext<Req> = { req, input, blocked };\n\n if (options.onResult) {\n try {\n await options.onResult(result, ctx);\n } catch {\n // onResult is observational; never let it break the request.\n }\n }\n\n if (ingestLogs) {\n try {\n await client.ingestLogs(deviceId, [\n {\n category: \"security\",\n level: blocked ? \"warn\" : \"info\",\n message: blocked ? \"simplr guard blocked request\" : \"simplr guard checked request\",\n risk_level: result.risk_level,\n risk_score: result.risk_score,\n },\n ]);\n } catch {\n // Log shipping is best-effort and must never affect the request.\n }\n }\n\n return { result, blocked, input };\n }\n\n return { client, run };\n}\n\n/** Standard JSON envelope returned to the client on a blocked request. */\nexport function blockEnvelope(result: CheckResult) {\n return {\n error: \"request_blocked\",\n message: \"This request was blocked by Simplr fraud protection.\",\n risk_level: result.risk_level,\n risk_score: result.risk_score,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACcA,IAAM,mBAAmB;AAGlB,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EACA;AAAA,EACT,YAAY,SAAiB,QAAgB,MAAe;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AACF;AAcO,SAAS,aAAa,QAAoC;AAC/D,MAAI,CAAC,QAAQ,OAAQ,OAAM,IAAI,MAAM,8BAA8B;AACnE,QAAM,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AAA,UACF;AACA,gBAAM;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,KAAM,MAAK,GAAY;AAAA,QACtB,OAAM;AAAA,EACb;AACF;AAIC,cAAsB,uBAAO,IAAI,eAAe,CAAC,IAAI;","names":[]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { G as GuardOptions } from './types-CmzpR5S4.cjs';
|
|
2
|
+
export { C as CheckResult } from './types-CmzpR5S4.cjs';
|
|
3
|
+
|
|
4
|
+
type FastifyInstance = any;
|
|
5
|
+
/**
|
|
6
|
+
* Fastify plugin. Register with `app.register(simplrFastify, options)`.
|
|
7
|
+
* Accepts the standard `(fastify, options, done)` plugin signature.
|
|
8
|
+
*/
|
|
9
|
+
declare function simplrFastify(fastify: FastifyInstance, options: GuardOptions, done?: (err?: Error) => void): void;
|
|
10
|
+
|
|
11
|
+
export { simplrFastify };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { G as GuardOptions } from './types-CmzpR5S4.js';
|
|
2
|
+
export { C as CheckResult } from './types-CmzpR5S4.js';
|
|
3
|
+
|
|
4
|
+
type FastifyInstance = any;
|
|
5
|
+
/**
|
|
6
|
+
* Fastify plugin. Register with `app.register(simplrFastify, options)`.
|
|
7
|
+
* Accepts the standard `(fastify, options, done)` plugin signature.
|
|
8
|
+
*/
|
|
9
|
+
declare function simplrFastify(fastify: FastifyInstance, options: GuardOptions, done?: (err?: Error) => void): void;
|
|
10
|
+
|
|
11
|
+
export { simplrFastify };
|
package/dist/fastify.js
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
var DEFAULT_BASE_URL = "https://api.simplr.sh";
|
|
3
|
+
var SimplrError = class extends Error {
|
|
4
|
+
status;
|
|
5
|
+
body;
|
|
6
|
+
constructor(message, status, body) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "SimplrError";
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.body = body;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
function createClient(config) {
|
|
14
|
+
if (!config?.apiKey) throw new Error("Simplr: `apiKey` is required");
|
|
15
|
+
const baseUrl = (config.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
16
|
+
const timeoutMs = config.timeoutMs ?? 15e3;
|
|
17
|
+
const fetchImpl = config.fetch ?? globalThis.fetch;
|
|
18
|
+
if (typeof fetchImpl !== "function") {
|
|
19
|
+
throw new Error(
|
|
20
|
+
"Simplr: no global fetch available \u2014 use Node 18+ or pass `fetch` in options"
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
async function apiRequest(method, path, body) {
|
|
24
|
+
const controller = new AbortController();
|
|
25
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
26
|
+
try {
|
|
27
|
+
const res = await fetchImpl(`${baseUrl}${path}`, {
|
|
28
|
+
method,
|
|
29
|
+
headers: { "Content-Type": "application/json", "X-API-Key": config.apiKey },
|
|
30
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0,
|
|
31
|
+
signal: controller.signal
|
|
32
|
+
});
|
|
33
|
+
const text = await res.text();
|
|
34
|
+
let parsed;
|
|
35
|
+
try {
|
|
36
|
+
parsed = text ? JSON.parse(text) : void 0;
|
|
37
|
+
} catch {
|
|
38
|
+
parsed = text;
|
|
39
|
+
}
|
|
40
|
+
if (!res.ok) {
|
|
41
|
+
const message = parsed && (parsed.message || parsed.error) || `Simplr API error ${res.status}`;
|
|
42
|
+
throw new SimplrError(message, res.status, parsed);
|
|
43
|
+
}
|
|
44
|
+
return parsed && typeof parsed === "object" && "content" in parsed ? parsed.content : parsed;
|
|
45
|
+
} catch (err) {
|
|
46
|
+
if (err instanceof SimplrError) throw err;
|
|
47
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
48
|
+
throw new SimplrError(`Request to ${path} timed out after ${timeoutMs}ms`, 0, null);
|
|
49
|
+
}
|
|
50
|
+
throw new SimplrError(err instanceof Error ? err.message : "Network error", 0, null);
|
|
51
|
+
} finally {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
check: (input) => apiRequest("POST", "/v1/check", input),
|
|
57
|
+
ingestLogs: (deviceId, logs) => apiRequest("POST", "/v1/edge/logs", { device_id: deviceId, logs })
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// src/core.ts
|
|
62
|
+
var RISK_ORDER = {
|
|
63
|
+
low: 0,
|
|
64
|
+
medium: 1,
|
|
65
|
+
high: 2,
|
|
66
|
+
critical: 3
|
|
67
|
+
};
|
|
68
|
+
var DEFAULT_DEVICE_ID = "simplr-edge-middleware";
|
|
69
|
+
var DEFAULT_THRESHOLD = "high";
|
|
70
|
+
function riskRank(level) {
|
|
71
|
+
return RISK_ORDER[level] ?? 0;
|
|
72
|
+
}
|
|
73
|
+
function riskAtLeast(level, min) {
|
|
74
|
+
return riskRank(level) >= riskRank(min);
|
|
75
|
+
}
|
|
76
|
+
function readHeader(headers, name) {
|
|
77
|
+
if (!headers) return void 0;
|
|
78
|
+
const h = headers;
|
|
79
|
+
if (typeof h.get === "function") {
|
|
80
|
+
const v = h.get(name);
|
|
81
|
+
return v == null ? void 0 : String(v);
|
|
82
|
+
}
|
|
83
|
+
const lower = name.toLowerCase();
|
|
84
|
+
if (lower in h && h[lower] != null) return String(h[lower]);
|
|
85
|
+
for (const key of Object.keys(h)) {
|
|
86
|
+
if (key.toLowerCase() === lower && h[key] != null) return String(h[key]);
|
|
87
|
+
}
|
|
88
|
+
return void 0;
|
|
89
|
+
}
|
|
90
|
+
function extractIp(req) {
|
|
91
|
+
const fwd = readHeader(req?.headers, "x-forwarded-for");
|
|
92
|
+
if (fwd) return fwd.split(",")[0].trim();
|
|
93
|
+
const real = readHeader(req?.headers, "x-real-ip");
|
|
94
|
+
if (real) return real;
|
|
95
|
+
return req?.ip || req?.socket?.remoteAddress || req?.connection?.remoteAddress || void 0;
|
|
96
|
+
}
|
|
97
|
+
function defaultExtract(req) {
|
|
98
|
+
const input = {};
|
|
99
|
+
const device = {};
|
|
100
|
+
const ip = extractIp(req);
|
|
101
|
+
if (ip) device.ip = ip;
|
|
102
|
+
const ua = readHeader(req?.headers, "user-agent");
|
|
103
|
+
if (ua) device.user_agent = ua;
|
|
104
|
+
if (Object.keys(device).length > 0) input.device = device;
|
|
105
|
+
const body = req?.body;
|
|
106
|
+
if (body && typeof body === "object") {
|
|
107
|
+
const b = body;
|
|
108
|
+
if (typeof b.email === "string") input.email = b.email;
|
|
109
|
+
if (typeof b.phone === "string") input.phone = b.phone;
|
|
110
|
+
}
|
|
111
|
+
return input;
|
|
112
|
+
}
|
|
113
|
+
function normalizeBlock(block) {
|
|
114
|
+
if (typeof block === "function") return block;
|
|
115
|
+
const threshold = block?.whenRiskAtLeast ?? DEFAULT_THRESHOLD;
|
|
116
|
+
return (result) => riskAtLeast(result.risk_level, threshold);
|
|
117
|
+
}
|
|
118
|
+
function createGuard(options) {
|
|
119
|
+
if (!options?.apiKey) throw new Error("createGuard: `apiKey` is required");
|
|
120
|
+
const client = createClient({
|
|
121
|
+
apiKey: options.apiKey,
|
|
122
|
+
baseUrl: options.baseUrl,
|
|
123
|
+
timeoutMs: options.timeoutMs,
|
|
124
|
+
fetch: options.fetch
|
|
125
|
+
});
|
|
126
|
+
const extract = options.extract ?? defaultExtract;
|
|
127
|
+
const shouldBlock = normalizeBlock(options.block);
|
|
128
|
+
const failOpen = options.failOpen ?? true;
|
|
129
|
+
const ingestLogs = options.ingestLogs ?? false;
|
|
130
|
+
const deviceId = options.deviceId ?? DEFAULT_DEVICE_ID;
|
|
131
|
+
async function run(req) {
|
|
132
|
+
const input = await extract(req);
|
|
133
|
+
let result;
|
|
134
|
+
try {
|
|
135
|
+
result = await client.check(input);
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (failOpen) {
|
|
138
|
+
return { result: null, blocked: false, input, error };
|
|
139
|
+
}
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
const blocked = shouldBlock(result);
|
|
143
|
+
const ctx = { req, input, blocked };
|
|
144
|
+
if (options.onResult) {
|
|
145
|
+
try {
|
|
146
|
+
await options.onResult(result, ctx);
|
|
147
|
+
} catch {
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (ingestLogs) {
|
|
151
|
+
try {
|
|
152
|
+
await client.ingestLogs(deviceId, [
|
|
153
|
+
{
|
|
154
|
+
category: "security",
|
|
155
|
+
level: blocked ? "warn" : "info",
|
|
156
|
+
message: blocked ? "simplr guard blocked request" : "simplr guard checked request",
|
|
157
|
+
risk_level: result.risk_level,
|
|
158
|
+
risk_score: result.risk_score
|
|
159
|
+
}
|
|
160
|
+
]);
|
|
161
|
+
} catch {
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return { result, blocked, input };
|
|
165
|
+
}
|
|
166
|
+
return { client, run };
|
|
167
|
+
}
|
|
168
|
+
function blockEnvelope(result) {
|
|
169
|
+
return {
|
|
170
|
+
error: "request_blocked",
|
|
171
|
+
message: "This request was blocked by Simplr fraud protection.",
|
|
172
|
+
risk_level: result.risk_level,
|
|
173
|
+
risk_score: result.risk_score
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// src/fastify.ts
|
|
178
|
+
function simplrFastify(fastify, options, done) {
|
|
179
|
+
try {
|
|
180
|
+
const guard = createGuard(options);
|
|
181
|
+
const failOpen = options.failOpen ?? true;
|
|
182
|
+
if (typeof fastify.decorateRequest === "function") {
|
|
183
|
+
fastify.decorateRequest("simplr", null);
|
|
184
|
+
}
|
|
185
|
+
fastify.addHook(
|
|
186
|
+
"preHandler",
|
|
187
|
+
async (request, reply) => {
|
|
188
|
+
try {
|
|
189
|
+
const outcome = await guard.run(request);
|
|
190
|
+
request.simplr = outcome.result;
|
|
191
|
+
if (outcome.blocked && outcome.result) {
|
|
192
|
+
reply.code(403).send(blockEnvelope(outcome.result));
|
|
193
|
+
return reply;
|
|
194
|
+
}
|
|
195
|
+
} catch (err) {
|
|
196
|
+
if (failOpen) {
|
|
197
|
+
request.simplr = null;
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
throw err;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
);
|
|
204
|
+
done?.();
|
|
205
|
+
} catch (err) {
|
|
206
|
+
if (done) done(err);
|
|
207
|
+
else throw err;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
simplrFastify[/* @__PURE__ */ Symbol.for("skip-override")] = true;
|
|
211
|
+
export {
|
|
212
|
+
simplrFastify
|
|
213
|
+
};
|
|
214
|
+
//# sourceMappingURL=fastify.js.map
|