draco-insomnis 0.1.27 → 0.1.29
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/README.md +80 -3
- package/dist/core/crowdsec.d.ts +34 -0
- package/dist/core/crowdsec.js +143 -0
- package/dist/core/gatekeeper.d.ts +49 -8
- package/dist/core/gatekeeper.js +82 -11
- package/dist/core/request.d.ts +2 -0
- package/dist/core/review.d.ts +36 -0
- package/dist/core/review.js +87 -0
- package/dist/core/store.d.ts +9 -2
- package/dist/core/store.js +31 -0
- package/dist/geo.d.ts +34 -0
- package/dist/geo.js +174 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +4 -2
- package/dist/node.d.ts +2 -0
- package/dist/node.js +12 -14
- package/dist/worker.js +19 -17
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -20,9 +20,10 @@ Draco checks requests in this order:
|
|
|
20
20
|
|
|
21
21
|
1. **Blocked addresses** can still read the site. They cannot post anything or open sensitive pages
|
|
22
22
|
(login, sign-up and admin).
|
|
23
|
-
2. **Countries**.
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
2. **Countries**. Behind Cloudflare the country comes from Cloudflare (`request.cf.country` in
|
|
24
|
+
Workers, `CF-IPCountry` when the request really comes from Cloudflare). In Node.js without
|
|
25
|
+
Cloudflare, give it the country list (see [Countries without Cloudflare](#countries-without-cloudflare)).
|
|
26
|
+
By default it applies to sensitive requests only.
|
|
26
27
|
3. **Firewall signatures** look for SQL injection, path traversal, code injection, XSS in the URL,
|
|
27
28
|
known scanners and probes for files like `.env` or `.git`. They read the path, the query and the
|
|
28
29
|
parsed body, including nested JSON, and also check values that were URL-encoded twice.
|
|
@@ -119,6 +120,82 @@ In Workers the visitor's address is the one Cloudflare sets, and the country com
|
|
|
119
120
|
atomic increment, and each isolate counts on its own. Without a store, everything stays in memory.
|
|
120
121
|
Form and JSON bodies up to 64 KB are read from a copy of the request.
|
|
121
122
|
|
|
123
|
+
## Countries without Cloudflare
|
|
124
|
+
|
|
125
|
+
In Node.js, `GeoFile` reads the same country list as the PHP editions: DB-IP "IP to Country Lite"
|
|
126
|
+
(CC BY 4.0), built monthly by this project. The lookup is local and sends nothing anywhere.
|
|
127
|
+
|
|
128
|
+
```js
|
|
129
|
+
import { GeoFile } from 'draco-insomnis/geo';
|
|
130
|
+
|
|
131
|
+
const lookup = new GeoFile('/var/lib/myapp/draco-geo.bin');
|
|
132
|
+
app.use(draco({ waf: 'block', geo: { mode: 'block', countries: ['XX'], action: 'log', lookup } }));
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
- **Download:** the file (about 9 MB) is fetched on start when it is missing or older than 35 days,
|
|
136
|
+
then checked once a day. It only replaces the old file when the published SHA-256 matches. Pass
|
|
137
|
+
`{ update: false }` to manage the file yourself.
|
|
138
|
+
- **Lookup:** a binary search over the file, about 20 small reads per address.
|
|
139
|
+
- **No country:** private, reserved and unknown addresses have none, so they are never filtered.
|
|
140
|
+
|
|
141
|
+
## "This is a mistake": review requests
|
|
142
|
+
|
|
143
|
+
With a secret of your own, the 403 page carries a short form: the person who was stopped leaves an
|
|
144
|
+
e-mail and what they were doing, and the request reaches you.
|
|
145
|
+
|
|
146
|
+
```js
|
|
147
|
+
draco({
|
|
148
|
+
waf: 'block',
|
|
149
|
+
review: {
|
|
150
|
+
secret: process.env.DRACO_SECRET, // 16+ characters, the same on every server
|
|
151
|
+
onRequest: (r) => mailMe(`Review: ${r.email} (${r.ip}, rule ${r.rule}): ${r.message}`),
|
|
152
|
+
},
|
|
153
|
+
});
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
It works like the PHP editions, and both languages check the same cases (`tests/vectors/review.json`):
|
|
157
|
+
|
|
158
|
+
- The form is signed for the address and the moment it was shown, and is valid for a day.
|
|
159
|
+
- The rule that stopped the request travels sealed, so the page never says what matched.
|
|
160
|
+
- A hidden trap field catches bots; one address may send 3 requests a day, the site 50.
|
|
161
|
+
- The visitor always gets the same "Request sent" page, whether the request was kept or not.
|
|
162
|
+
- Draco never writes to the person who asks: that would let anyone make your site send mail. Let
|
|
163
|
+
someone through with `gate.blocks.remove(ip)` or by adding the address to `adminIps`.
|
|
164
|
+
|
|
165
|
+
The body must be parsed: `express.urlencoded()` in Express, a body parser before Draco in Koa
|
|
166
|
+
(Strapi: after `strapi::body`). Workers read it themselves. The texts of the pages are in `texts`
|
|
167
|
+
(`reviewEmail`, `reviewMessage`, `reviewButton`, `reviewSentTitle`, `reviewSentText`,
|
|
168
|
+
`textWithReview`).
|
|
169
|
+
|
|
170
|
+
## CrowdSec
|
|
171
|
+
|
|
172
|
+
If you run CrowdSec, Draco can enforce its bans and feed it evidence.
|
|
173
|
+
|
|
174
|
+
**Enforcing its bans.** Create a key with `cscli bouncers add draco` and give Draco your Local API:
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
draco({ waf: 'block', crowdsec: { url: 'http://127.0.0.1:8080', apiKey: process.env.CROWDSEC_KEY } });
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
- Bans on an address or a range join Draco's block list, which works as usual: the address may read
|
|
181
|
+
the site but not post or log in.
|
|
182
|
+
- The decisions are copied in the background, at most once a minute, so no request waits for
|
|
183
|
+
CrowdSec. When a decision is deleted or expires in CrowdSec, the block goes too; blocks you set
|
|
184
|
+
yourself are never touched.
|
|
185
|
+
- Ranges wider than /16 (IPv4) or /32 (IPv6) and the addresses in `adminIps` are never imported.
|
|
186
|
+
- In Workers, background work ends with the request, so call `gate.crowdsec.sync()` from a scheduled
|
|
187
|
+
handler instead.
|
|
188
|
+
|
|
189
|
+
**Feeding it evidence.** `crowdsecLine(event)` writes one line in the format read by the parser and
|
|
190
|
+
scenario in [`server/crowdsec`](../server/crowdsec):
|
|
191
|
+
|
|
192
|
+
```js
|
|
193
|
+
import { appendFileSync } from 'node:fs';
|
|
194
|
+
import { crowdsecLine } from 'draco-insomnis';
|
|
195
|
+
|
|
196
|
+
draco({ onEvent: (e) => appendFileSync('/var/log/draco/events.log', crowdsecLine(e, 'shop.example') + '\n') });
|
|
197
|
+
```
|
|
198
|
+
|
|
122
199
|
## Several servers
|
|
123
200
|
|
|
124
201
|
The default `MemoryStore` serves a single process. For several processes or servers, give every one
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type DracoEvent, type Store } from './store.ts';
|
|
2
|
+
export declare const REASON = "CrowdSec";
|
|
3
|
+
export interface CrowdSecOptions {
|
|
4
|
+
/** The Local API, e.g. http://127.0.0.1:8080 */
|
|
5
|
+
url: string;
|
|
6
|
+
apiKey: string;
|
|
7
|
+
/** Seconds to wait for an answer (default 2). */
|
|
8
|
+
timeout?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface SyncResult {
|
|
11
|
+
added: number;
|
|
12
|
+
removed: number;
|
|
13
|
+
error: string;
|
|
14
|
+
}
|
|
15
|
+
/** Go durations as CrowdSec sends them: "3h59m40.5s", "45m", "1.5s"… */
|
|
16
|
+
export declare function seconds(duration: string): number;
|
|
17
|
+
export declare class CrowdSec {
|
|
18
|
+
private readonly options;
|
|
19
|
+
private readonly store;
|
|
20
|
+
private readonly blocks;
|
|
21
|
+
private readonly admins;
|
|
22
|
+
private readonly now;
|
|
23
|
+
private running;
|
|
24
|
+
constructor(options: CrowdSecOptions, store: Store, admins?: () => readonly string[], now?: () => number);
|
|
25
|
+
/** From the gatekeeper: one sync a minute at most (across processes sharing the store), never awaited. */
|
|
26
|
+
maybeSync(): Promise<void>;
|
|
27
|
+
sync(): Promise<SyncResult>;
|
|
28
|
+
private pull;
|
|
29
|
+
private imported;
|
|
30
|
+
/** Only blocks that came from CrowdSec are lifted: a block the owner set stays. */
|
|
31
|
+
private removeIfOurs;
|
|
32
|
+
}
|
|
33
|
+
/** One line for the CrowdSec agent (server/crowdsec: parser draco-insomnis-logs, scenario draco-insomnis/attacks). */
|
|
34
|
+
export declare function crowdsecLine(event: DracoEvent, host?: string): string;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CrowdSec, both ways — like server/src/CrowdSec.php.
|
|
3
|
+
*
|
|
4
|
+
* In: Draco is a bouncer of your own CrowdSec Local API (url + the key from
|
|
5
|
+
* "cscli bouncers add draco"). The decisions stream is copied into Draco's block list at most once a
|
|
6
|
+
* minute, in the background: no request ever waits for CrowdSec. Bans on an address or a range (no
|
|
7
|
+
* wider than /16 or /32) become Draco blocks — the address may read but not post or log in. The
|
|
8
|
+
* owner's addresses (adminIps) are never imported.
|
|
9
|
+
*
|
|
10
|
+
* Out: crowdsecLine(event) is one JSON line in the format the parser and scenario in server/crowdsec
|
|
11
|
+
* read (acquisition type draco-insomnis): append it to a file the CrowdSec agent watches, from onEvent.
|
|
12
|
+
*/
|
|
13
|
+
import { isIP } from "./net.js";
|
|
14
|
+
import { Blocks, validNet } from "./store.js";
|
|
15
|
+
export const REASON = 'CrowdSec';
|
|
16
|
+
const EVERY = 60;
|
|
17
|
+
const IMPORTED = 'draco:crowdsec:imported';
|
|
18
|
+
/** Go durations as CrowdSec sends them: "3h59m40.5s", "45m", "1.5s"… */
|
|
19
|
+
export function seconds(duration) {
|
|
20
|
+
if (duration.trim().startsWith('-'))
|
|
21
|
+
return 0;
|
|
22
|
+
let total = 0;
|
|
23
|
+
let any = false;
|
|
24
|
+
for (const m of duration.matchAll(/(\d+(?:\.\d+)?)(h|ms|m|s)/g)) {
|
|
25
|
+
any = true;
|
|
26
|
+
total += Number(m[1]) * { h: 3600, m: 60, s: 1, ms: 0.001 }[m[2]];
|
|
27
|
+
}
|
|
28
|
+
return any ? Math.ceil(total) : 0;
|
|
29
|
+
}
|
|
30
|
+
export class CrowdSec {
|
|
31
|
+
options;
|
|
32
|
+
store;
|
|
33
|
+
blocks;
|
|
34
|
+
admins;
|
|
35
|
+
now;
|
|
36
|
+
running = null;
|
|
37
|
+
constructor(options, store, admins = () => [], now = () => Date.now() / 1000) {
|
|
38
|
+
this.options = options;
|
|
39
|
+
this.store = store;
|
|
40
|
+
this.blocks = new Blocks(store);
|
|
41
|
+
this.admins = admins;
|
|
42
|
+
this.now = now;
|
|
43
|
+
}
|
|
44
|
+
/** From the gatekeeper: one sync a minute at most (across processes sharing the store), never awaited. */
|
|
45
|
+
async maybeSync() {
|
|
46
|
+
if (this.running !== null || (await this.store.bump('draco:crowdsec:sync', EVERY)) !== 1)
|
|
47
|
+
return;
|
|
48
|
+
await this.sync();
|
|
49
|
+
}
|
|
50
|
+
sync() {
|
|
51
|
+
this.running ??= this.pull().finally(() => { this.running = null; });
|
|
52
|
+
return this.running;
|
|
53
|
+
}
|
|
54
|
+
async pull() {
|
|
55
|
+
const out = { added: 0, removed: 0, error: '' };
|
|
56
|
+
// The first call asks for everything in force; later ones only for changes.
|
|
57
|
+
const startup = (await this.store.get('draco:crowdsec:started')) === null;
|
|
58
|
+
const url = `${this.options.url.replace(/\/+$/, '')}/v1/decisions/stream?startup=${startup}&scopes=ip,range`;
|
|
59
|
+
let data = null;
|
|
60
|
+
try {
|
|
61
|
+
const res = await fetch(url, {
|
|
62
|
+
headers: { 'X-Api-Key': this.options.apiKey, 'User-Agent': 'Draco-Insomnis' },
|
|
63
|
+
signal: AbortSignal.timeout((this.options.timeout ?? 2) * 1000),
|
|
64
|
+
});
|
|
65
|
+
if (res.status !== 200)
|
|
66
|
+
out.error = `HTTP ${res.status}`;
|
|
67
|
+
else
|
|
68
|
+
data = (await res.json());
|
|
69
|
+
}
|
|
70
|
+
catch (e) {
|
|
71
|
+
out.error = e instanceof SyntaxError ? 'not JSON' : 'no answer';
|
|
72
|
+
}
|
|
73
|
+
if (out.error !== '' || data === null || typeof data !== 'object') {
|
|
74
|
+
out.error ||= 'not JSON';
|
|
75
|
+
await this.store.set('draco:crowdsec:last', `${Math.floor(this.now())}|${out.error}`, 86400 * 30);
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
let imported = await this.imported();
|
|
79
|
+
if (startup) {
|
|
80
|
+
for (const value of imported)
|
|
81
|
+
if (await this.removeIfOurs(value))
|
|
82
|
+
out.removed++;
|
|
83
|
+
imported = [];
|
|
84
|
+
}
|
|
85
|
+
for (const d of Array.isArray(data.deleted) ? data.deleted : []) {
|
|
86
|
+
const value = String(d.value ?? '').toLowerCase();
|
|
87
|
+
if (value !== '' && imported.includes(value) && (await this.removeIfOurs(value))) {
|
|
88
|
+
out.removed++;
|
|
89
|
+
imported = imported.filter((v) => v !== value);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const admins = this.admins();
|
|
93
|
+
for (const d of Array.isArray(data.new) ? data.new : []) {
|
|
94
|
+
const decision = d;
|
|
95
|
+
if (String(decision.type ?? '').toLowerCase() !== 'ban')
|
|
96
|
+
continue;
|
|
97
|
+
const value = String(decision.value ?? '').trim().toLowerCase();
|
|
98
|
+
const ttl = seconds(String(decision.duration ?? ''));
|
|
99
|
+
const allowed = value.includes('/') ? validNet(value) : isIP(value);
|
|
100
|
+
if (ttl <= 0 || !allowed || admins.includes(value))
|
|
101
|
+
continue;
|
|
102
|
+
const reason = `${REASON}: ${String(decision.scenario ?? decision.origin ?? '').slice(0, 150)}`;
|
|
103
|
+
if (await this.blocks.addUntil(value, Math.floor(this.now()) + ttl, reason, true, this.now())) {
|
|
104
|
+
out.added++;
|
|
105
|
+
if (!imported.includes(value))
|
|
106
|
+
imported.push(value);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
await this.store.set(IMPORTED, JSON.stringify(imported.slice(-20_000)), 0);
|
|
110
|
+
await this.store.set('draco:crowdsec:started', '1', 86400 * 365);
|
|
111
|
+
await this.store.set('draco:crowdsec:last', `${Math.floor(this.now())}|ok +${out.added} -${out.removed}`, 86400 * 30);
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
async imported() {
|
|
115
|
+
try {
|
|
116
|
+
const list = JSON.parse((await this.store.get(IMPORTED)) ?? '[]');
|
|
117
|
+
return Array.isArray(list) ? list.filter((v) => typeof v === 'string') : [];
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return [];
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/** Only blocks that came from CrowdSec are lifted: a block the owner set stays. */
|
|
124
|
+
async removeIfOurs(value) {
|
|
125
|
+
const entry = await this.blocks.entry(value, this.now());
|
|
126
|
+
if (entry === null || !entry.reason.startsWith(REASON))
|
|
127
|
+
return false;
|
|
128
|
+
await this.blocks.remove(value);
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** One line for the CrowdSec agent (server/crowdsec: parser draco-insomnis-logs, scenario draco-insomnis/attacks). */
|
|
133
|
+
export function crowdsecLine(event, host = '') {
|
|
134
|
+
return JSON.stringify({
|
|
135
|
+
time: new Date(event.time * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z'),
|
|
136
|
+
ip: event.ip,
|
|
137
|
+
host,
|
|
138
|
+
endpoint: event.endpoint,
|
|
139
|
+
verdict: event.verdict,
|
|
140
|
+
reasons: event.reasons.join(','),
|
|
141
|
+
user_agent: event.userAgent,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
import { type Resolver } from './crawler.ts';
|
|
9
9
|
import { type DracoRequest, type ProxyMode } from './request.ts';
|
|
10
10
|
import { Blocks, type DracoEvent, type Store } from './store.ts';
|
|
11
|
+
import { type ReviewRequest } from './review.ts';
|
|
12
|
+
import { CrowdSec, type CrowdSecOptions } from './crowdsec.ts';
|
|
11
13
|
export type Mode = 'off' | 'log' | 'block';
|
|
12
14
|
export interface DracoOptions {
|
|
13
15
|
/** Firewall: "log" (default) writes evidence only, "block" answers 403. */
|
|
@@ -35,6 +37,13 @@ export interface DracoOptions {
|
|
|
35
37
|
action?: 'log' | 'block';
|
|
36
38
|
/** "sensitive" (default) or the whole "site". */
|
|
37
39
|
scope?: 'sensitive' | 'site';
|
|
40
|
+
/**
|
|
41
|
+
* Where the country comes from when the platform does not say it (Cloudflare does): in Node.js,
|
|
42
|
+
* new GeoFile(path) from 'draco-insomnis/geo'.
|
|
43
|
+
*/
|
|
44
|
+
lookup?: {
|
|
45
|
+
country(ip: string): string | null | Promise<string | null>;
|
|
46
|
+
};
|
|
38
47
|
};
|
|
39
48
|
/** Security headers (nosniff, SAMEORIGIN, referrer and permissions policy) and HSTS on HTTPS. */
|
|
40
49
|
headers?: boolean;
|
|
@@ -43,24 +52,41 @@ export interface DracoOptions {
|
|
|
43
52
|
resolver?: Resolver;
|
|
44
53
|
/** Every line of evidence, as it is written (send it to your logs, a SIEM or CrowdSec). */
|
|
45
54
|
onEvent?: (event: DracoEvent) => void | Promise<void>;
|
|
46
|
-
/**
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
55
|
+
/**
|
|
56
|
+
* "This is a mistake" on the 403 page: the visitor leaves an e-mail and a line, and the request
|
|
57
|
+
* reaches onRequest (store it, mail it to yourself). Needs a secret of your own (32+ characters,
|
|
58
|
+
* the same on every server); the form is signed with it. The body must be parsed for it to work
|
|
59
|
+
* (express.urlencoded(), a Koa body parser; Workers read it themselves).
|
|
60
|
+
*/
|
|
61
|
+
review?: {
|
|
62
|
+
secret: string;
|
|
63
|
+
onRequest?: (request: ReviewRequest) => void | Promise<void>;
|
|
51
64
|
};
|
|
65
|
+
/**
|
|
66
|
+
* Your own CrowdSec Local API (url + the key from "cscli bouncers add draco"): its bans join
|
|
67
|
+
* Draco's block list, synced in the background at most once a minute. In Workers, call
|
|
68
|
+
* gate.crowdsec.sync() from a scheduled handler instead (background work ends with the request).
|
|
69
|
+
*/
|
|
70
|
+
crowdsec?: CrowdSecOptions;
|
|
71
|
+
/** The texts of the 403, 429 and review pages. */
|
|
72
|
+
texts?: Partial<typeof TEXTS>;
|
|
52
73
|
}
|
|
53
74
|
export declare const SENSITIVE: string[];
|
|
54
75
|
export interface Answer {
|
|
55
|
-
|
|
56
|
-
|
|
76
|
+
/** 200 only answers a review request (the thanks page). */
|
|
77
|
+
status: 200 | 403 | 429;
|
|
78
|
+
/** The rule, "blocked", "geo", "pace" or "review": for the evidence, never shown to the visitor. */
|
|
57
79
|
why: string;
|
|
58
80
|
retry: number;
|
|
81
|
+
/** The review form for the 403 page, when reviews are on. */
|
|
82
|
+
form?: string;
|
|
59
83
|
}
|
|
60
84
|
export declare class Gatekeeper {
|
|
61
85
|
readonly options: DracoOptions;
|
|
62
86
|
readonly store: Store;
|
|
63
87
|
readonly blocks: Blocks;
|
|
88
|
+
/** Set when options.crowdsec is. */
|
|
89
|
+
readonly crowdsec: CrowdSec | null;
|
|
64
90
|
private readonly recent;
|
|
65
91
|
private readonly now;
|
|
66
92
|
constructor(options?: DracoOptions, now?: () => number);
|
|
@@ -68,6 +94,8 @@ export declare class Gatekeeper {
|
|
|
68
94
|
/** The last 200 lines of evidence of this process (newest last). */
|
|
69
95
|
events(): readonly DracoEvent[];
|
|
70
96
|
decide(r: DracoRequest): Promise<Answer | null>;
|
|
97
|
+
private reviewing;
|
|
98
|
+
private rules;
|
|
71
99
|
/** Security headers to add, unless the application already set them. */
|
|
72
100
|
headers(https: boolean): Record<string, string>;
|
|
73
101
|
private excepted;
|
|
@@ -80,9 +108,22 @@ export declare class Gatekeeper {
|
|
|
80
108
|
/** Trusted proxies, admin addresses and lists may be given as text too ("a, b # comment"). */
|
|
81
109
|
export declare const list: (value: string | string[] | undefined) => string[];
|
|
82
110
|
/** The 403 page: says nothing about which rule matched; the reference ties it to the evidence. */
|
|
83
|
-
export declare function page(title: string, text: string): string;
|
|
111
|
+
export declare function page(title: string, text: string, extraHtml?: string): string;
|
|
84
112
|
export declare const TEXTS: {
|
|
85
113
|
title: string;
|
|
86
114
|
text: string;
|
|
87
115
|
tooMany: string;
|
|
116
|
+
/** Above the review form, instead of "text". */
|
|
117
|
+
textWithReview: string;
|
|
118
|
+
reviewEmail: string;
|
|
119
|
+
reviewMessage: string;
|
|
120
|
+
reviewButton: string;
|
|
121
|
+
reviewSentTitle: string;
|
|
122
|
+
reviewSentText: string;
|
|
123
|
+
};
|
|
124
|
+
/** Status, headers and body of an answer, for any framework. */
|
|
125
|
+
export declare function render(gate: Gatekeeper, answer: Answer): {
|
|
126
|
+
status: number;
|
|
127
|
+
headers: Record<string, string>;
|
|
128
|
+
body: string;
|
|
88
129
|
};
|
package/dist/core/gatekeeper.js
CHANGED
|
@@ -9,6 +9,8 @@ import { claimed, resolvesBack } from "./crawler.js";
|
|
|
9
9
|
import { network, parse } from "./net.js";
|
|
10
10
|
import { clientIp, remote, wantsPage } from "./request.js";
|
|
11
11
|
import { Blocks, MemoryStore } from "./store.js";
|
|
12
|
+
import { accept, form, isRequest } from "./review.js";
|
|
13
|
+
import { CrowdSec } from "./crowdsec.js";
|
|
12
14
|
import { inspect } from "./waf.js";
|
|
13
15
|
export const SENSITIVE = [
|
|
14
16
|
'/wp-login.php', '/login', '/register', '/signup', '/user/login', '/user/register', '/admin',
|
|
@@ -23,12 +25,17 @@ export class Gatekeeper {
|
|
|
23
25
|
options;
|
|
24
26
|
store;
|
|
25
27
|
blocks;
|
|
28
|
+
/** Set when options.crowdsec is. */
|
|
29
|
+
crowdsec;
|
|
26
30
|
recent = [];
|
|
27
31
|
now;
|
|
28
32
|
constructor(options = {}, now = () => Date.now() / 1000) {
|
|
29
33
|
this.options = options;
|
|
30
34
|
this.store = options.store ?? new MemoryStore(now);
|
|
31
35
|
this.blocks = new Blocks(this.store);
|
|
36
|
+
this.crowdsec = options.crowdsec?.url && options.crowdsec.apiKey
|
|
37
|
+
? new CrowdSec(options.crowdsec, this.store, () => options.adminIps ?? [], now)
|
|
38
|
+
: null;
|
|
32
39
|
this.now = now;
|
|
33
40
|
}
|
|
34
41
|
ip(r) {
|
|
@@ -39,9 +46,41 @@ export class Gatekeeper {
|
|
|
39
46
|
return this.recent;
|
|
40
47
|
}
|
|
41
48
|
async decide(r) {
|
|
49
|
+
const answer = await this.rules(r);
|
|
50
|
+
if (answer?.status === 403 && this.reviewing()) {
|
|
51
|
+
const texts = { ...TEXTS, ...this.options.texts };
|
|
52
|
+
answer.form = await form(this.options.review.secret, this.ip(r), answer.why, this.now(), {
|
|
53
|
+
email: texts.reviewEmail, message: texts.reviewMessage, button: texts.reviewButton,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
return answer;
|
|
57
|
+
}
|
|
58
|
+
reviewing() {
|
|
59
|
+
return (this.options.review?.secret ?? '').length >= 16;
|
|
60
|
+
}
|
|
61
|
+
async rules(r) {
|
|
42
62
|
const o = this.options;
|
|
63
|
+
// Never awaited: no request waits for CrowdSec.
|
|
64
|
+
if (this.crowdsec !== null)
|
|
65
|
+
this.crowdsec.maybeSync().catch(() => undefined);
|
|
43
66
|
const ip = this.ip(r);
|
|
44
|
-
if (
|
|
67
|
+
if (this.excepted(r.path))
|
|
68
|
+
return null;
|
|
69
|
+
if (this.reviewing() && isRequest(r.method, r.form)) {
|
|
70
|
+
const request = await accept(this.store, o.review.secret, ip, r.userAgent, r.form ?? {}, this.now());
|
|
71
|
+
if (request !== null) {
|
|
72
|
+
await this.log(r, ip, 'review', 'pending', [`review_${request.rule !== '' ? request.rule : 'blocked'}`], request.message, request.email);
|
|
73
|
+
try {
|
|
74
|
+
await o.review.onRequest?.(request);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
// The visitor gets the thanks page whatever the owner's code does.
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
// The same answer either way, so a script learns nothing.
|
|
81
|
+
return { status: 200, why: 'review', retry: 0 };
|
|
82
|
+
}
|
|
83
|
+
if ((o.adminIps ?? []).includes(ip))
|
|
45
84
|
return null;
|
|
46
85
|
const waf = o.waf ?? 'log';
|
|
47
86
|
if (waf !== 'off') {
|
|
@@ -51,7 +90,7 @@ export class Gatekeeper {
|
|
|
51
90
|
const country = await this.refusedCountry(r, ip);
|
|
52
91
|
if (country !== '') {
|
|
53
92
|
const blocking = o.geo?.action === 'block';
|
|
54
|
-
await this.log(r, ip, 'waf:geo', blocking, ['waf_geo'], `${country} ${r.path}`);
|
|
93
|
+
await this.log(r, ip, 'waf:geo', blocking ? 'bot' : 'doubtful', ['waf_geo'], `${country} ${r.path}`);
|
|
55
94
|
if (blocking)
|
|
56
95
|
return { status: 403, why: 'geo', retry: 0 };
|
|
57
96
|
}
|
|
@@ -75,7 +114,7 @@ export class Gatekeeper {
|
|
|
75
114
|
const block = pace === 'block';
|
|
76
115
|
// One line per address and minute is enough evidence; the rest only counts.
|
|
77
116
|
if (ipHits === ipLimit + 1 || netHits === netLimit + 1) {
|
|
78
|
-
await this.log(r, ip, `anticopy:${over}`,
|
|
117
|
+
await this.log(r, ip, `anticopy:${over}`, 'doubtful', [`anticopy_${over}_${block ? 'block' : 'log'}`], r.path);
|
|
79
118
|
}
|
|
80
119
|
if (block)
|
|
81
120
|
return { status: 429, why: 'pace', retry: Math.max(1, WINDOW - (Math.floor(now) % WINDOW)) };
|
|
@@ -115,7 +154,15 @@ export class Gatekeeper {
|
|
|
115
154
|
return '';
|
|
116
155
|
if (geo?.scope !== 'site' && !this.sensitive(r))
|
|
117
156
|
return '';
|
|
118
|
-
|
|
157
|
+
let country = (r.country ?? '').toUpperCase();
|
|
158
|
+
if (!/^[A-Z]{2}$/.test(country) && geo?.lookup !== undefined) {
|
|
159
|
+
try {
|
|
160
|
+
country = ((await geo.lookup.country(ip)) ?? '').toUpperCase();
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
country = '';
|
|
164
|
+
}
|
|
165
|
+
}
|
|
119
166
|
// Unknown, Tor ("T1") or anonymous ("XX"): not refused for its country.
|
|
120
167
|
if (!/^[A-Z]{2}$/.test(country) || country === 'XX' || country === 'T1')
|
|
121
168
|
return '';
|
|
@@ -128,7 +175,7 @@ export class Gatekeeper {
|
|
|
128
175
|
return country;
|
|
129
176
|
}
|
|
130
177
|
async record(r, ip, rule, blocking) {
|
|
131
|
-
await this.log(r, ip, `waf:${rule}`, blocking, [`waf_${rule}`], r.path + (r.query !== '' ? `?${r.query}` : ''));
|
|
178
|
+
await this.log(r, ip, `waf:${rule}`, blocking ? 'bot' : 'doubtful', [`waf_${rule}`], r.path + (r.query !== '' ? `?${r.query}` : ''));
|
|
132
179
|
if (!blocking)
|
|
133
180
|
return;
|
|
134
181
|
const hits = await this.store.bump(`draco:waf:${ip}`, HIT_WINDOW);
|
|
@@ -151,17 +198,19 @@ export class Gatekeeper {
|
|
|
151
198
|
await this.store.set(key, ok ? 'y' : 'n', VERIFIED_FOR);
|
|
152
199
|
return ok;
|
|
153
200
|
}
|
|
154
|
-
async log(r, ip, endpoint,
|
|
201
|
+
async log(r, ip, endpoint, verdict, reasons, detail, email) {
|
|
155
202
|
const event = {
|
|
156
203
|
time: Math.floor(this.now()),
|
|
157
204
|
ip,
|
|
158
205
|
remote: remote(r),
|
|
159
206
|
endpoint,
|
|
160
|
-
verdict
|
|
207
|
+
verdict,
|
|
161
208
|
reasons,
|
|
162
209
|
userAgent: r.userAgent.slice(0, 255),
|
|
163
|
-
detail: detail.slice(0, 200),
|
|
210
|
+
detail: detail.slice(0, endpoint === 'review' ? 500 : 200),
|
|
164
211
|
};
|
|
212
|
+
if (email !== undefined)
|
|
213
|
+
event.email = email;
|
|
165
214
|
this.recent.push(event);
|
|
166
215
|
if (this.recent.length > 200)
|
|
167
216
|
this.recent.shift();
|
|
@@ -177,16 +226,38 @@ const limit = (value, fallback) => (value !== undefined && value >= 10 ? Math.fl
|
|
|
177
226
|
/** Trusted proxies, admin addresses and lists may be given as text too ("a, b # comment"). */
|
|
178
227
|
export const list = (value) => (value === undefined ? [] : parse(value));
|
|
179
228
|
/** The 403 page: says nothing about which rule matched; the reference ties it to the evidence. */
|
|
180
|
-
export function page(title, text) {
|
|
229
|
+
export function page(title, text, extraHtml = '') {
|
|
181
230
|
const h = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
182
231
|
const ref = Array.from(crypto.getRandomValues(new Uint8Array(5)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
183
232
|
return '<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="robots" content="noindex,nofollow"><meta name="viewport" content="width=device-width,initial-scale=1"><title>403</title>'
|
|
184
|
-
+ '<style>body{font:16px/1.5 system-ui,sans-serif;background:#f4f5f7;color:#1d2327;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;padding:20px;box-sizing:border-box}main{background:#fff;border-radius:12px;padding:32px;max-width:440px;width:100%;box-shadow:0 2px 12px rgba(0,0,0,.08);text-align:center}</style></head><body><main>'
|
|
185
|
-
+ `<h1 style="font-size:20px">${h(title)}</h1><p>${h(text)}</p
|
|
233
|
+
+ '<style>body{font:16px/1.5 system-ui,sans-serif;background:#f4f5f7;color:#1d2327;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;padding:20px;box-sizing:border-box}main{background:#fff;border-radius:12px;padding:32px;max-width:440px;width:100%;box-shadow:0 2px 12px rgba(0,0,0,.08);text-align:center}form{text-align:left;margin-top:20px}label{display:block;font-size:14px;margin:10px 0 4px}input,textarea{width:100%;box-sizing:border-box;padding:8px;border:1px solid #c3c4c7;border-radius:6px;font:inherit}button{margin-top:12px;padding:9px 16px;border:0;border-radius:6px;background:#2271b1;color:#fff;font:inherit;cursor:pointer}.hp{position:absolute;left:-9999px}</style></head><body><main>'
|
|
234
|
+
+ `<h1 style="font-size:20px">${h(title)}</h1><p>${h(text)}</p>${extraHtml}`
|
|
186
235
|
+ `<p style="color:#64748b;font-size:13px">Ref. ${ref}</p></main></body></html>`;
|
|
187
236
|
}
|
|
188
237
|
export const TEXTS = {
|
|
189
238
|
title: 'Request blocked',
|
|
190
239
|
text: 'This request was blocked by the site\'s security. If you think this is a mistake, contact the site owner.',
|
|
191
240
|
tooMany: 'Too many pages in a short time. Please wait a moment and try again.',
|
|
241
|
+
/** Above the review form, instead of "text". */
|
|
242
|
+
textWithReview: 'This request was blocked by the site\'s security. If you think this is a mistake, tell the site owner what you were doing:',
|
|
243
|
+
reviewEmail: 'Your e-mail',
|
|
244
|
+
reviewMessage: 'What were you doing?',
|
|
245
|
+
reviewButton: 'Ask for a review',
|
|
246
|
+
reviewSentTitle: 'Request sent',
|
|
247
|
+
reviewSentText: 'Thank you. The owner of the site will look at it and, if it was a mistake, let you through.',
|
|
192
248
|
};
|
|
249
|
+
/** Status, headers and body of an answer, for any framework. */
|
|
250
|
+
export function render(gate, answer) {
|
|
251
|
+
const texts = { ...TEXTS, ...gate.options.texts };
|
|
252
|
+
if (answer.status === 429) {
|
|
253
|
+
return {
|
|
254
|
+
status: 429,
|
|
255
|
+
headers: { 'Retry-After': String(answer.retry), 'Content-Type': 'text/plain; charset=UTF-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' },
|
|
256
|
+
body: texts.tooMany,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
const html = { 'Content-Type': 'text/html; charset=UTF-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' };
|
|
260
|
+
if (answer.status === 200)
|
|
261
|
+
return { status: 200, headers: html, body: page(texts.reviewSentTitle, texts.reviewSentText) };
|
|
262
|
+
return { status: 403, headers: html, body: answer.form !== undefined ? page(texts.title, texts.textWithReview, answer.form) : page(texts.title, texts.text) };
|
|
263
|
+
}
|
package/dist/core/request.d.ts
CHANGED
|
@@ -17,6 +17,8 @@ export interface DracoRequest {
|
|
|
17
17
|
accept?: string;
|
|
18
18
|
/** Sent with "X-Requested-With: XMLHttpRequest". */
|
|
19
19
|
ajax?: boolean;
|
|
20
|
+
/** The text fields of a posted form (urlencoded or JSON), for the review form. */
|
|
21
|
+
form?: Record<string, string>;
|
|
20
22
|
}
|
|
21
23
|
export type ProxyMode = '' | 'cf' | 'xff';
|
|
22
24
|
/** Decodes like PHP's urldecode: "+" is a space and malformed "%" sequences are left as they are. */
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "This is a mistake": a person the firewall stopped asks the owner to look again, from the 403
|
|
3
|
+
* page — the same form, signatures and limits as src/Core/Review.php (tests/vectors/review.json).
|
|
4
|
+
*
|
|
5
|
+
* The form is signed for the address and the moment it was shown, carries the rule sealed (the page
|
|
6
|
+
* never says what matched), has a trap field and is limited per address (3 a day) and per site (50 a
|
|
7
|
+
* day). Draco never writes to the person who asks: that would let anyone make the site send mail.
|
|
8
|
+
*/
|
|
9
|
+
import type { Store } from './store.ts';
|
|
10
|
+
export declare const FIELD = "draco_review";
|
|
11
|
+
export declare const ENDPOINT = "review";
|
|
12
|
+
export interface ReviewLabels {
|
|
13
|
+
email: string;
|
|
14
|
+
message: string;
|
|
15
|
+
button: string;
|
|
16
|
+
}
|
|
17
|
+
/** One accepted request, for the owner's queue (see DracoOptions.review.onRequest). */
|
|
18
|
+
export interface ReviewRequest {
|
|
19
|
+
time: number;
|
|
20
|
+
ip: string;
|
|
21
|
+
/** The rule that stopped the visitor ("sqli", "blocked", "geo"…); '' when it could not be read. */
|
|
22
|
+
rule: string;
|
|
23
|
+
email: string;
|
|
24
|
+
message: string;
|
|
25
|
+
userAgent: string;
|
|
26
|
+
}
|
|
27
|
+
/** The rule hidden from the visitor: XOR with a key from the secret, the address and the moment. */
|
|
28
|
+
export declare function seal(secret: string, ip: string, ts: string, rule: string): Promise<string>;
|
|
29
|
+
/** The rule from seal(), or '' when the value is not one. */
|
|
30
|
+
export declare function open(secret: string, ip: string, ts: string, sealed: string): Promise<string>;
|
|
31
|
+
export declare function sign(secret: string, ip: string, rule: string, ts: string): Promise<string>;
|
|
32
|
+
/** The form under the 403 text, already escaped. */
|
|
33
|
+
export declare function form(secret: string, ip: string, why: string, now: number, labels: ReviewLabels): Promise<string>;
|
|
34
|
+
export declare function isRequest(method: string, form: Record<string, string> | undefined): boolean;
|
|
35
|
+
/** Checks a request and returns it when it passes; the visitor gets the same thanks either way. */
|
|
36
|
+
export declare function accept(store: Store, secret: string, ip: string, userAgent: string, post: Record<string, string>, now: number): Promise<ReviewRequest | null>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
export const FIELD = 'draco_review';
|
|
2
|
+
export const ENDPOINT = 'review';
|
|
3
|
+
const MAX_PER_IP_DAY = 3;
|
|
4
|
+
const MAX_PER_DAY = 50;
|
|
5
|
+
const VALID_FOR = 86400;
|
|
6
|
+
const enc = new TextEncoder();
|
|
7
|
+
async function hmac(secret, data) {
|
|
8
|
+
const key = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
9
|
+
return new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(data)));
|
|
10
|
+
}
|
|
11
|
+
const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
12
|
+
const cleanRule = (rule) => rule.toLowerCase().replace(/[^a-z0-9_]/g, '');
|
|
13
|
+
/** The rule hidden from the visitor: XOR with a key from the secret, the address and the moment. */
|
|
14
|
+
export async function seal(secret, ip, ts, rule) {
|
|
15
|
+
const plain = new Uint8Array(32);
|
|
16
|
+
plain.set(enc.encode(cleanRule(rule).slice(0, 32)));
|
|
17
|
+
const key = await hmac(secret, `review-rule|${ip}|${ts}`);
|
|
18
|
+
return hex(plain.map((b, i) => b ^ key[i]));
|
|
19
|
+
}
|
|
20
|
+
/** The rule from seal(), or '' when the value is not one. */
|
|
21
|
+
export async function open(secret, ip, ts, sealed) {
|
|
22
|
+
if (!/^[0-9a-f]{64}$/i.test(sealed))
|
|
23
|
+
return '';
|
|
24
|
+
const key = await hmac(secret, `review-rule|${ip}|${ts}`);
|
|
25
|
+
const bytes = Uint8Array.from(sealed.match(/../g), (h, i) => parseInt(h, 16) ^ key[i]);
|
|
26
|
+
let end = bytes.length;
|
|
27
|
+
while (end > 0 && bytes[end - 1] === 0)
|
|
28
|
+
end--;
|
|
29
|
+
const rule = new TextDecoder().decode(bytes.subarray(0, end));
|
|
30
|
+
return /^[a-z0-9_]*$/.test(rule) ? rule : '';
|
|
31
|
+
}
|
|
32
|
+
export async function sign(secret, ip, rule, ts) {
|
|
33
|
+
return hex(await hmac(secret, `review|${ip}|${rule}|${ts}`));
|
|
34
|
+
}
|
|
35
|
+
/** Equal strings, compared in constant time. */
|
|
36
|
+
function same(a, b) {
|
|
37
|
+
if (a.length !== b.length)
|
|
38
|
+
return false;
|
|
39
|
+
let d = 0;
|
|
40
|
+
for (let i = 0; i < a.length; i++)
|
|
41
|
+
d |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
42
|
+
return d === 0;
|
|
43
|
+
}
|
|
44
|
+
const h = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
45
|
+
/** The form under the 403 text, already escaped. */
|
|
46
|
+
export async function form(secret, ip, why, now, labels) {
|
|
47
|
+
const ts = String(Math.floor(now));
|
|
48
|
+
const rule = cleanRule(why);
|
|
49
|
+
return '<form method="post" action="">'
|
|
50
|
+
+ `<input type="hidden" name="${FIELD}" value="1">`
|
|
51
|
+
+ `<input type="hidden" name="draco_rule" value="${h(await seal(secret, ip, ts, rule))}">`
|
|
52
|
+
+ `<input type="hidden" name="draco_ts" value="${h(ts)}">`
|
|
53
|
+
+ `<input type="hidden" name="draco_sig" value="${h(await sign(secret, ip, rule, ts))}">`
|
|
54
|
+
+ '<p class="hp"><label>Website <input type="text" name="draco_website" tabindex="-1" autocomplete="off"></label></p>'
|
|
55
|
+
+ `<label for="draco-r-email">${h(labels.email)}</label>`
|
|
56
|
+
+ '<input id="draco-r-email" type="email" name="draco_email" required maxlength="190">'
|
|
57
|
+
+ `<label for="draco-r-msg">${h(labels.message)}</label>`
|
|
58
|
+
+ '<textarea id="draco-r-msg" name="draco_message" rows="3" maxlength="500" required></textarea>'
|
|
59
|
+
+ `<button type="submit">${h(labels.button)}</button>`
|
|
60
|
+
+ '</form>';
|
|
61
|
+
}
|
|
62
|
+
export function isRequest(method, form) {
|
|
63
|
+
return method === 'POST' && (form?.[FIELD] ?? '') === '1';
|
|
64
|
+
}
|
|
65
|
+
// The same checks as PHP's FILTER_VALIDATE_EMAIL for what people really type; no quoted local parts.
|
|
66
|
+
const EMAIL = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/i;
|
|
67
|
+
/** Checks a request and returns it when it passes; the visitor gets the same thanks either way. */
|
|
68
|
+
export async function accept(store, secret, ip, userAgent, post, now) {
|
|
69
|
+
const ts = post.draco_ts ?? '';
|
|
70
|
+
const rule = await open(secret, ip, ts, post.draco_rule ?? '');
|
|
71
|
+
const email = (post.draco_email ?? '').trim().toLowerCase();
|
|
72
|
+
const message = Array.from((post.draco_message ?? '')
|
|
73
|
+
.replace(/<(script|style)[^>]*?>[\s\S]*?<\/\1>|<[^>]*>/gi, '')
|
|
74
|
+
.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '')
|
|
75
|
+
.trim()).slice(0, 500).join('');
|
|
76
|
+
const fresh = /^\d+$/.test(ts) && Number(ts) <= now && now - Number(ts) < VALID_FOR;
|
|
77
|
+
const ok = fresh && same(await sign(secret, ip, rule, ts), post.draco_sig ?? '') && (post.draco_website ?? '') === ''
|
|
78
|
+
&& EMAIL.test(email) && email.length <= 190 && message !== '';
|
|
79
|
+
if (!ok)
|
|
80
|
+
return null;
|
|
81
|
+
const day = new Date(now * 1000).toISOString().slice(0, 10).replace(/-/g, '');
|
|
82
|
+
if ((await store.bump(`draco:review:ip:${ip}`, VALID_FOR)) > MAX_PER_IP_DAY)
|
|
83
|
+
return null;
|
|
84
|
+
if ((await store.bump(`draco:review:day:${day}`, VALID_FOR)) > MAX_PER_DAY)
|
|
85
|
+
return null;
|
|
86
|
+
return { time: Math.floor(now), ip, rule, email, message, userAgent: userAgent.slice(0, 255) };
|
|
87
|
+
}
|
package/dist/core/store.d.ts
CHANGED
|
@@ -25,11 +25,14 @@ export interface DracoEvent {
|
|
|
25
25
|
remote: string;
|
|
26
26
|
/** "waf:sqli", "waf:geo", "anticopy:ip"… */
|
|
27
27
|
endpoint: string;
|
|
28
|
-
|
|
28
|
+
/** "pending": a review request waiting for the owner. */
|
|
29
|
+
verdict: 'bot' | 'doubtful' | 'pending';
|
|
29
30
|
reasons: string[];
|
|
30
31
|
userAgent: string;
|
|
31
|
-
/** Path and query,
|
|
32
|
+
/** Path and query, country and path, or the review request's message. */
|
|
32
33
|
detail: string;
|
|
34
|
+
/** Review requests: the e-mail the visitor left. */
|
|
35
|
+
email?: string;
|
|
33
36
|
}
|
|
34
37
|
export interface BlockEntry {
|
|
35
38
|
value: string;
|
|
@@ -45,6 +48,10 @@ export declare class Blocks {
|
|
|
45
48
|
private readonly store;
|
|
46
49
|
constructor(store: Store);
|
|
47
50
|
add(value: string, days: number, reason: string, automatic: boolean, now?: number): Promise<boolean>;
|
|
51
|
+
/** A block until a given moment (seconds), for lists that come with their own duration (CrowdSec). */
|
|
52
|
+
addUntil(value: string, until: number, reason: string, automatic: boolean, now?: number): Promise<boolean>;
|
|
53
|
+
/** The block in force on exactly this address or network, if any. */
|
|
54
|
+
entry(value: string, now?: number): Promise<BlockEntry | null>;
|
|
48
55
|
remove(value: string): Promise<void>;
|
|
49
56
|
nets(now?: number): Promise<BlockEntry[]>;
|
|
50
57
|
isBlocked(ip: string, now?: number): Promise<boolean>;
|
package/dist/core/store.js
CHANGED
|
@@ -77,6 +77,37 @@ export class Blocks {
|
|
|
77
77
|
await this.store.set(`draco:block:${value}`, JSON.stringify(entry), days === 0 ? 0 : days * 86400);
|
|
78
78
|
return true;
|
|
79
79
|
}
|
|
80
|
+
/** A block until a given moment (seconds), for lists that come with their own duration (CrowdSec). */
|
|
81
|
+
async addUntil(value, until, reason, automatic, now = Date.now() / 1000) {
|
|
82
|
+
const ttl = Math.floor(until - now);
|
|
83
|
+
if (ttl <= 0)
|
|
84
|
+
return false;
|
|
85
|
+
const entry = { value, until: Math.floor(until), reason, automatic };
|
|
86
|
+
if (value.includes('/')) {
|
|
87
|
+
if (!validNet(value))
|
|
88
|
+
return false;
|
|
89
|
+
const nets = (await this.nets(now)).filter((n) => n.value !== value);
|
|
90
|
+
nets.push(entry);
|
|
91
|
+
await this.store.set('draco:nets', JSON.stringify(nets), 0);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
await this.store.set(`draco:block:${value}`, JSON.stringify(entry), ttl);
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
/** The block in force on exactly this address or network, if any. */
|
|
98
|
+
async entry(value, now = Date.now() / 1000) {
|
|
99
|
+
if (value.includes('/'))
|
|
100
|
+
return (await this.nets(now)).find((n) => n.value === value) ?? null;
|
|
101
|
+
const raw = await this.store.get(`draco:block:${value}`);
|
|
102
|
+
if (raw === null)
|
|
103
|
+
return null;
|
|
104
|
+
try {
|
|
105
|
+
return JSON.parse(raw);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
80
111
|
async remove(value) {
|
|
81
112
|
if (value.includes('/')) {
|
|
82
113
|
const nets = (await this.nets()).filter((n) => n.value !== value);
|
package/dist/geo.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export declare const SOURCE = "https://github.com/fermatacordis-create/draco-insomnis/releases/download/geo/draco-geo.bin";
|
|
2
|
+
export declare const MAX_AGE_DAYS = 35;
|
|
3
|
+
export interface GeoFileOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Download the list when it is missing or older than 35 days, now and then once a day (the timer
|
|
6
|
+
* does not keep the process alive). Default true; false if you refresh the file yourself.
|
|
7
|
+
*/
|
|
8
|
+
update?: boolean;
|
|
9
|
+
/** Where to download from (tests, mirrors). The SHA-256 is read from the same address + ".sha256". */
|
|
10
|
+
source?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare class GeoFile {
|
|
13
|
+
readonly path: string;
|
|
14
|
+
private readonly source;
|
|
15
|
+
private db;
|
|
16
|
+
private triedAt;
|
|
17
|
+
/** Why the last download failed ('' when it did not, or none was needed). */
|
|
18
|
+
lastError: string;
|
|
19
|
+
constructor(path: string, options?: GeoFileOptions);
|
|
20
|
+
/** Two-letter country of the address, or null (no file yet, private or unknown address). */
|
|
21
|
+
country(ip: string): string | null;
|
|
22
|
+
/** The date the file was built (YYYYMMDD), or '' when it is missing or not a Draco file. */
|
|
23
|
+
built(): string;
|
|
24
|
+
stale(now?: number): boolean;
|
|
25
|
+
/** Downloads the list when it is missing or stale. '' when done or not needed, otherwise why not. */
|
|
26
|
+
refresh(): Promise<string>;
|
|
27
|
+
/**
|
|
28
|
+
* Downloads the list, checks the SHA-256 published next to it and only then replaces the old file.
|
|
29
|
+
* '' when done; otherwise "checksum", "download", "format" or "folder".
|
|
30
|
+
*/
|
|
31
|
+
update(): Promise<string>;
|
|
32
|
+
close(): void;
|
|
33
|
+
private open;
|
|
34
|
+
}
|
package/dist/geo.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The visitor's country without Cloudflare, for Node.js: the same file and lookup as
|
|
3
|
+
* src/Core/Geo.php (DB-IP "IP to Country Lite", CC BY 4.0, built monthly by this project). A binary
|
|
4
|
+
* search over fixed-size records, about 20 small reads, nothing sent anywhere. Private, reserved and
|
|
5
|
+
* unknown addresses have no country, so they are never filtered by country.
|
|
6
|
+
*
|
|
7
|
+
* import { GeoFile } from 'draco-insomnis/geo';
|
|
8
|
+
* const geo = new GeoFile('/var/lib/myapp/draco-geo.bin'); // downloaded now and kept fresh
|
|
9
|
+
* app.use(draco({ waf: 'block', geo: { mode: 'block', countries: ['XX'], lookup: geo } }));
|
|
10
|
+
*
|
|
11
|
+
* Behind Cloudflare the country header is used and this file is not needed.
|
|
12
|
+
*/
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
15
|
+
import { dirname } from 'node:path';
|
|
16
|
+
import { toBytes, unmap } from "./core/net.js";
|
|
17
|
+
export const SOURCE = 'https://github.com/fermatacordis-create/draco-insomnis/releases/download/geo/draco-geo.bin';
|
|
18
|
+
export const MAX_AGE_DAYS = 35;
|
|
19
|
+
const HEADER = 22;
|
|
20
|
+
const DAY = 86_400_000;
|
|
21
|
+
export class GeoFile {
|
|
22
|
+
path;
|
|
23
|
+
source;
|
|
24
|
+
db = null;
|
|
25
|
+
triedAt = 0;
|
|
26
|
+
/** Why the last download failed ('' when it did not, or none was needed). */
|
|
27
|
+
lastError = '';
|
|
28
|
+
constructor(path, options = {}) {
|
|
29
|
+
this.path = path;
|
|
30
|
+
this.source = options.source ?? SOURCE;
|
|
31
|
+
if (options.update ?? true) {
|
|
32
|
+
void this.refresh();
|
|
33
|
+
setInterval(() => void this.refresh(), DAY).unref();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Two-letter country of the address, or null (no file yet, private or unknown address). */
|
|
37
|
+
country(ip) {
|
|
38
|
+
const addr = toBytes(unmap(ip.trim()));
|
|
39
|
+
const db = addr === null ? null : this.open();
|
|
40
|
+
if (addr === null || db === null)
|
|
41
|
+
return null;
|
|
42
|
+
const v4 = addr.length === 4;
|
|
43
|
+
const count = v4 ? db.v4 : db.v6;
|
|
44
|
+
const size = v4 ? 6 : 18;
|
|
45
|
+
const width = size - 2;
|
|
46
|
+
const base = HEADER + (v4 ? 0 : db.v4 * 6);
|
|
47
|
+
const buf = new Uint8Array(size);
|
|
48
|
+
let lo = 0;
|
|
49
|
+
let hi = count - 1;
|
|
50
|
+
let found = -1;
|
|
51
|
+
while (lo <= hi) {
|
|
52
|
+
const mid = (lo + hi) >>> 1;
|
|
53
|
+
readSync(db.fd, buf, 0, width, base + mid * size);
|
|
54
|
+
if (compare(buf.subarray(0, width), addr) <= 0) {
|
|
55
|
+
found = mid;
|
|
56
|
+
lo = mid + 1;
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
hi = mid - 1;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (found < 0)
|
|
63
|
+
return null;
|
|
64
|
+
readSync(db.fd, buf, 0, 2, base + found * size + width);
|
|
65
|
+
const cc = String.fromCharCode(buf[0], buf[1]);
|
|
66
|
+
return /^[A-Z]{2}$/.test(cc) ? cc : null;
|
|
67
|
+
}
|
|
68
|
+
/** The date the file was built (YYYYMMDD), or '' when it is missing or not a Draco file. */
|
|
69
|
+
built() {
|
|
70
|
+
return this.open()?.built ?? '';
|
|
71
|
+
}
|
|
72
|
+
stale(now = Date.now()) {
|
|
73
|
+
const b = this.built();
|
|
74
|
+
if (b === '')
|
|
75
|
+
return true;
|
|
76
|
+
const built = Date.UTC(Number(b.slice(0, 4)), Number(b.slice(4, 6)) - 1, Number(b.slice(6, 8)));
|
|
77
|
+
return now - built > MAX_AGE_DAYS * DAY;
|
|
78
|
+
}
|
|
79
|
+
/** Downloads the list when it is missing or stale. '' when done or not needed, otherwise why not. */
|
|
80
|
+
async refresh() {
|
|
81
|
+
if (!this.stale())
|
|
82
|
+
return (this.lastError = '');
|
|
83
|
+
return (this.lastError = await this.update());
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Downloads the list, checks the SHA-256 published next to it and only then replaces the old file.
|
|
87
|
+
* '' when done; otherwise "checksum", "download", "format" or "folder".
|
|
88
|
+
*/
|
|
89
|
+
async update() {
|
|
90
|
+
const get = async (url) => {
|
|
91
|
+
try {
|
|
92
|
+
const res = await fetch(url, { headers: { 'User-Agent': 'Draco-Insomnis' }, signal: AbortSignal.timeout(120_000) });
|
|
93
|
+
return res.ok ? new Uint8Array(await res.arrayBuffer()) : null;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
const sum = await get(`${this.source}.sha256`);
|
|
100
|
+
const want = sum === null ? '' : new TextDecoder().decode(sum).trim().slice(0, 64).toLowerCase();
|
|
101
|
+
if (!/^[a-f0-9]{64}$/.test(want))
|
|
102
|
+
return 'checksum';
|
|
103
|
+
const body = await get(this.source);
|
|
104
|
+
if (body === null || createHash('sha256').update(body).digest('hex') !== want)
|
|
105
|
+
return 'download';
|
|
106
|
+
if (readHead(body, body.length) === null)
|
|
107
|
+
return 'format';
|
|
108
|
+
const part = `${this.path}.part`;
|
|
109
|
+
try {
|
|
110
|
+
mkdirSync(dirname(this.path), { recursive: true });
|
|
111
|
+
writeFileSync(part, body);
|
|
112
|
+
renameSync(part, this.path);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
try {
|
|
116
|
+
unlinkSync(part);
|
|
117
|
+
}
|
|
118
|
+
catch { /* nothing to remove */ }
|
|
119
|
+
return 'folder';
|
|
120
|
+
}
|
|
121
|
+
this.close();
|
|
122
|
+
return '';
|
|
123
|
+
}
|
|
124
|
+
close() {
|
|
125
|
+
if (this.db !== null)
|
|
126
|
+
closeSync(this.db.fd);
|
|
127
|
+
this.db = null;
|
|
128
|
+
this.triedAt = 0;
|
|
129
|
+
}
|
|
130
|
+
open() {
|
|
131
|
+
if (this.db !== null)
|
|
132
|
+
return this.db;
|
|
133
|
+
// A missing file is looked for again at most once a minute.
|
|
134
|
+
if (Date.now() - this.triedAt < 60_000)
|
|
135
|
+
return null;
|
|
136
|
+
this.triedAt = Date.now();
|
|
137
|
+
if (!existsSync(this.path))
|
|
138
|
+
return null;
|
|
139
|
+
let fd = -1;
|
|
140
|
+
try {
|
|
141
|
+
fd = openSync(this.path, 'r');
|
|
142
|
+
const head = new Uint8Array(HEADER);
|
|
143
|
+
readSync(fd, head, 0, HEADER, 0);
|
|
144
|
+
const info = readHead(head, fstatSync(fd).size);
|
|
145
|
+
if (info === null) {
|
|
146
|
+
closeSync(fd);
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
return (this.db = { fd, ...info });
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
if (fd >= 0)
|
|
153
|
+
closeSync(fd);
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** The header of a Draco country file, when the size matches it. */
|
|
159
|
+
function readHead(bytes, size) {
|
|
160
|
+
if (bytes.length < HEADER || new TextDecoder().decode(bytes.subarray(0, 6)) !== 'DRGEO1')
|
|
161
|
+
return null;
|
|
162
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, HEADER);
|
|
163
|
+
const v4 = view.getUint32(14);
|
|
164
|
+
const v6 = view.getUint32(18);
|
|
165
|
+
if (size !== HEADER + v4 * 6 + v6 * 18)
|
|
166
|
+
return null;
|
|
167
|
+
return { v4, v6, built: new TextDecoder().decode(bytes.subarray(6, 14)) };
|
|
168
|
+
}
|
|
169
|
+
function compare(a, b) {
|
|
170
|
+
for (let i = 0; i < a.length; i++)
|
|
171
|
+
if (a[i] !== b[i])
|
|
172
|
+
return a[i] - b[i];
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
/** Draco Insomnis for JavaScript: the engine, with no framework. Adapters: ./express, ./koa, ./worker. */
|
|
2
|
-
export { Gatekeeper, SENSITIVE, TEXTS, list, page, type Answer, type DracoOptions, type Mode } from './core/gatekeeper.ts';
|
|
2
|
+
export { Gatekeeper, SENSITIVE, TEXTS, list, page, render, type Answer, type DracoOptions, type Mode } from './core/gatekeeper.ts';
|
|
3
|
+
export { open, seal, sign, type ReviewRequest } from './core/review.ts';
|
|
4
|
+
export { CrowdSec, crowdsecLine, seconds as crowdsecSeconds, type CrowdSecOptions, type SyncResult } from './core/crowdsec.ts';
|
|
3
5
|
export { CLOUDFLARE, LOCAL_PROXIES, contains, inNet, isIP, network, parse } from './core/net.ts';
|
|
4
6
|
export { clientIp, urlDecode, type DracoRequest, type ProxyMode } from './core/request.ts';
|
|
5
7
|
export { Blocks, MemoryStore, validNet, type BlockEntry, type DracoEvent, type Store } from './core/store.ts';
|
|
6
8
|
export { flatten, inspect, type WafInput, type WafRule } from './core/waf.ts';
|
|
7
9
|
export type { Resolver } from './core/crawler.ts';
|
|
8
|
-
export declare const VERSION = "0.1.
|
|
10
|
+
export declare const VERSION = "0.1.29";
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/** Draco Insomnis for JavaScript: the engine, with no framework. Adapters: ./express, ./koa, ./worker. */
|
|
2
|
-
export { Gatekeeper, SENSITIVE, TEXTS, list, page } from "./core/gatekeeper.js";
|
|
2
|
+
export { Gatekeeper, SENSITIVE, TEXTS, list, page, render } from "./core/gatekeeper.js";
|
|
3
|
+
export { open, seal, sign } from "./core/review.js";
|
|
4
|
+
export { CrowdSec, crowdsecLine, seconds as crowdsecSeconds } from "./core/crowdsec.js";
|
|
3
5
|
export { CLOUDFLARE, LOCAL_PROXIES, contains, inNet, isIP, network, parse } from "./core/net.js";
|
|
4
6
|
export { clientIp, urlDecode } from "./core/request.js";
|
|
5
7
|
export { Blocks, MemoryStore, validNet } from "./core/store.js";
|
|
6
8
|
export { flatten, inspect } from "./core/waf.js";
|
|
7
|
-
export const VERSION = '0.1.
|
|
9
|
+
export const VERSION = '0.1.29';
|
package/dist/node.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export declare const nodeResolver: {
|
|
|
11
11
|
*/
|
|
12
12
|
export declare function fromNode(req: IncomingMessage, url: string, query?: unknown, body?: unknown): DracoRequest;
|
|
13
13
|
export declare const https: (req: IncomingMessage) => boolean;
|
|
14
|
+
/** The string fields of a parsed body (the review form only needs those). */
|
|
15
|
+
export declare function textFields(body: object): Record<string, string>;
|
|
14
16
|
/** The answer as status, headers and body, for any framework. */
|
|
15
17
|
export declare function reply(gate: Gatekeeper, answer: Answer): {
|
|
16
18
|
status: number;
|
package/dist/node.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* node:http and the DNS used to prove search engines.
|
|
4
4
|
*/
|
|
5
5
|
import { promises as dns } from 'node:dns';
|
|
6
|
-
import {
|
|
6
|
+
import { render } from "./core/gatekeeper.js";
|
|
7
7
|
import { CLOUDFLARE, contains } from "./core/net.js";
|
|
8
8
|
import { remote, urlDecode } from "./core/request.js";
|
|
9
9
|
import { flatten } from "./core/waf.js";
|
|
@@ -44,27 +44,25 @@ export function fromNode(req, url, query, body) {
|
|
|
44
44
|
accept: header(req, 'accept'),
|
|
45
45
|
ajax: header(req, 'x-requested-with').toLowerCase() === 'xmlhttprequest',
|
|
46
46
|
};
|
|
47
|
+
if (body !== undefined && body !== null && typeof body === 'object' && !(body instanceof Uint8Array))
|
|
48
|
+
r.form = textFields(body);
|
|
47
49
|
// Cloudflare's country header, only when the connection really comes from Cloudflare.
|
|
48
50
|
if (contains(CLOUDFLARE, remote(r)))
|
|
49
51
|
r.country = header(req, 'cf-ipcountry');
|
|
50
52
|
return r;
|
|
51
53
|
}
|
|
52
54
|
export const https = (req) => req.socket?.encrypted === true;
|
|
55
|
+
/** The string fields of a parsed body (the review form only needs those). */
|
|
56
|
+
export function textFields(body) {
|
|
57
|
+
const out = {};
|
|
58
|
+
for (const [k, v] of Object.entries(body))
|
|
59
|
+
if (typeof v === 'string')
|
|
60
|
+
out[k] = v.slice(0, 4000);
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
53
63
|
/** The answer as status, headers and body, for any framework. */
|
|
54
64
|
export function reply(gate, answer) {
|
|
55
|
-
|
|
56
|
-
if (answer.status === 429) {
|
|
57
|
-
return {
|
|
58
|
-
status: 429,
|
|
59
|
-
headers: { 'Retry-After': String(answer.retry), 'Content-Type': 'text/plain; charset=UTF-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' },
|
|
60
|
-
body: texts.tooMany,
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
return {
|
|
64
|
-
status: 403,
|
|
65
|
-
headers: { 'Content-Type': 'text/html; charset=UTF-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' },
|
|
66
|
-
body: page(texts.title, texts.text),
|
|
67
|
-
};
|
|
65
|
+
return render(gate, answer);
|
|
68
66
|
}
|
|
69
67
|
/** Sends the answer on a plain node:http response. */
|
|
70
68
|
export function send(res, out) {
|
package/dist/worker.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* In Workers the connecting address IS the visitor (CF-Connecting-IP is set by Cloudflare itself)
|
|
11
11
|
* and request.cf.country gives the country without any database.
|
|
12
12
|
*/
|
|
13
|
-
import { Gatekeeper,
|
|
13
|
+
import { Gatekeeper, render } from "./core/gatekeeper.js";
|
|
14
14
|
import { urlDecode } from "./core/request.js";
|
|
15
15
|
import { flatten } from "./core/waf.js";
|
|
16
16
|
export class KVStore {
|
|
@@ -46,22 +46,30 @@ export async function fromFetch(request) {
|
|
|
46
46
|
const url = new URL(request.url);
|
|
47
47
|
const rawQuery = url.search.replace(/^\?/, '');
|
|
48
48
|
const params = flatten(Object.fromEntries(url.searchParams));
|
|
49
|
+
let form;
|
|
49
50
|
const type = (request.headers.get('content-type') ?? '').toLowerCase();
|
|
50
51
|
const length = Number(request.headers.get('content-length') ?? '0');
|
|
51
52
|
if (request.body !== null && length <= 65536 && (type.includes('json') || type.includes('x-www-form-urlencoded'))) {
|
|
52
53
|
try {
|
|
53
54
|
const text = await request.clone().text();
|
|
54
|
-
if (type.includes('json'))
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
if (type.includes('json')) {
|
|
56
|
+
const body = JSON.parse(text);
|
|
57
|
+
params.push(...flatten(body));
|
|
58
|
+
if (body !== null && typeof body === 'object' && !Array.isArray(body)) {
|
|
59
|
+
form = Object.fromEntries(Object.entries(body).filter((e) => typeof e[1] === 'string'));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
form = Object.fromEntries(new URLSearchParams(text));
|
|
64
|
+
params.push(...flatten(form));
|
|
65
|
+
}
|
|
58
66
|
}
|
|
59
67
|
catch {
|
|
60
68
|
// Unreadable body: the URL is still inspected.
|
|
61
69
|
}
|
|
62
70
|
}
|
|
63
71
|
const cf = request.cf;
|
|
64
|
-
|
|
72
|
+
const out = {
|
|
65
73
|
method: request.method.toUpperCase(),
|
|
66
74
|
path: urlDecode(url.pathname),
|
|
67
75
|
query: urlDecode(rawQuery, true),
|
|
@@ -72,19 +80,13 @@ export async function fromFetch(request) {
|
|
|
72
80
|
accept: request.headers.get('accept') ?? '',
|
|
73
81
|
ajax: (request.headers.get('x-requested-with') ?? '').toLowerCase() === 'xmlhttprequest',
|
|
74
82
|
};
|
|
83
|
+
if (form !== undefined)
|
|
84
|
+
out.form = form;
|
|
85
|
+
return out;
|
|
75
86
|
}
|
|
76
87
|
export function response(gate, answer) {
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
return new Response(texts.tooMany, {
|
|
80
|
-
status: 429,
|
|
81
|
-
headers: { 'Retry-After': String(answer.retry), 'Content-Type': 'text/plain; charset=UTF-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' },
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
return new Response(page(texts.title, texts.text), {
|
|
85
|
-
status: 403,
|
|
86
|
-
headers: { 'Content-Type': 'text/html; charset=UTF-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex, nofollow' },
|
|
87
|
-
});
|
|
88
|
+
const out = render(gate, answer);
|
|
89
|
+
return new Response(out.body, { status: out.status, headers: out.headers });
|
|
88
90
|
}
|
|
89
91
|
/** Wraps a Worker: Draco answers first, the Worker only sees what Draco lets through. */
|
|
90
92
|
export function withDraco(handler, options = {}) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "draco-insomnis",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.29",
|
|
4
4
|
"description": "Firewall, anti-copy pace and country rules for Node.js (Express, Koa, Strapi, Directus) and Cloudflare Workers. No dependencies.",
|
|
5
5
|
"license": "GPL-2.0-or-later",
|
|
6
6
|
"type": "module",
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
|
|
14
14
|
"./express": { "types": "./dist/express.d.ts", "default": "./dist/express.js" },
|
|
15
15
|
"./koa": { "types": "./dist/koa.d.ts", "default": "./dist/koa.js" },
|
|
16
|
-
"./worker": { "types": "./dist/worker.d.ts", "default": "./dist/worker.js" }
|
|
16
|
+
"./worker": { "types": "./dist/worker.d.ts", "default": "./dist/worker.js" },
|
|
17
|
+
"./geo": { "types": "./dist/geo.d.ts", "default": "./dist/geo.js" }
|
|
17
18
|
},
|
|
18
19
|
"files": ["dist", "README.md"],
|
|
19
20
|
"scripts": {
|