ovr 6.2.4 → 7.0.0-next.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/README.md +3 -1
- package/dist/app/index.d.ts +51 -7
- package/dist/app/index.d.ts.map +1 -1
- package/dist/app/index.js +163 -28
- package/dist/auth/auth-data.d.ts +26 -0
- package/dist/auth/auth-data.d.ts.map +1 -0
- package/dist/auth/auth-data.js +42 -0
- package/dist/auth/cbor.d.ts +50 -0
- package/dist/auth/cbor.d.ts.map +1 -0
- package/dist/auth/cbor.js +200 -0
- package/dist/auth/client-source.d.ts +3 -0
- package/dist/auth/client-source.d.ts.map +1 -0
- package/dist/auth/client-source.js +3 -0
- package/dist/auth/client.d.ts +3 -0
- package/dist/auth/client.d.ts.map +1 -0
- package/dist/auth/client.js +186 -0
- package/dist/auth/configure.d.ts +28 -0
- package/dist/auth/configure.d.ts.map +1 -0
- package/dist/auth/configure.js +228 -0
- package/dist/auth/der.d.ts +6 -0
- package/dist/auth/der.d.ts.map +1 -0
- package/dist/auth/der.js +36 -0
- package/dist/auth/index.d.ts +242 -0
- package/dist/auth/index.d.ts.map +1 -0
- package/dist/auth/index.js +152 -0
- package/dist/auth/issue.d.ts +36 -0
- package/dist/auth/issue.d.ts.map +1 -0
- package/dist/auth/issue.js +47 -0
- package/dist/auth/metadata.d.ts +22 -0
- package/dist/auth/metadata.d.ts.map +1 -0
- package/dist/auth/metadata.js +134 -0
- package/dist/auth/oauth.d.ts +29 -0
- package/dist/auth/oauth.d.ts.map +1 -0
- package/dist/auth/oauth.js +724 -0
- package/dist/auth/passkey.d.ts +101 -0
- package/dist/auth/passkey.d.ts.map +1 -0
- package/dist/auth/passkey.js +393 -0
- package/dist/auth/state.d.ts +49 -0
- package/dist/auth/state.d.ts.map +1 -0
- package/dist/auth/state.js +184 -0
- package/dist/auth/storage.d.ts +193 -0
- package/dist/auth/storage.d.ts.map +1 -0
- package/dist/auth/storage.js +410 -0
- package/dist/auth/token.d.ts +12 -0
- package/dist/auth/token.d.ts.map +1 -0
- package/dist/auth/token.js +39 -0
- package/dist/context/index.d.ts +86 -16
- package/dist/context/index.d.ts.map +1 -1
- package/dist/context/index.js +166 -42
- package/dist/cookie/index.d.ts +3 -0
- package/dist/cookie/index.d.ts.map +1 -1
- package/dist/cookie/index.js +1 -0
- package/dist/database/index.d.ts +262 -0
- package/dist/database/index.d.ts.map +1 -0
- package/dist/database/index.js +807 -0
- package/dist/form/index.d.ts +699 -0
- package/dist/form/index.d.ts.map +1 -0
- package/dist/form/index.js +901 -0
- package/dist/index.d.ts +10 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -3
- package/dist/jsx/elements.d.ts +28 -2
- package/dist/jsx/elements.d.ts.map +1 -1
- package/dist/jsx/index.d.ts +20 -4
- package/dist/jsx/index.d.ts.map +1 -1
- package/dist/jsx/index.js +6 -65
- package/dist/limiter/index.d.ts +65 -0
- package/dist/limiter/index.d.ts.map +1 -0
- package/dist/limiter/index.js +157 -0
- package/dist/markdown/index.d.ts +61 -0
- package/dist/markdown/index.d.ts.map +1 -0
- package/dist/markdown/index.js +1160 -0
- package/dist/markup/index.d.ts +188 -0
- package/dist/markup/index.d.ts.map +1 -0
- package/dist/markup/index.js +718 -0
- package/dist/mcp/index.d.ts +73 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +988 -0
- package/dist/middleware/index.d.ts +3 -4
- package/dist/middleware/index.d.ts.map +1 -1
- package/dist/multipart/index.d.ts +53 -7
- package/dist/multipart/index.d.ts.map +1 -1
- package/dist/multipart/index.js +332 -124
- package/dist/route/index.d.ts +226 -80
- package/dist/route/index.d.ts.map +1 -1
- package/dist/route/index.js +239 -99
- package/dist/schema/index.d.ts +307 -734
- package/dist/schema/index.d.ts.map +1 -1
- package/dist/schema/index.js +783 -1050
- package/dist/table/index.d.ts +132 -0
- package/dist/table/index.d.ts.map +1 -0
- package/dist/table/index.js +188 -0
- package/dist/trie/index.js +4 -4
- package/dist/util/index.d.ts +37 -5
- package/dist/util/index.d.ts.map +1 -1
- package/dist/util/index.js +156 -41
- package/package.json +11 -4
- package/src/app/index.ts +230 -42
- package/src/auth/auth-data.ts +56 -0
- package/src/auth/cbor.ts +231 -0
- package/src/auth/client-source.ts +3 -0
- package/src/auth/client.ts +205 -0
- package/src/auth/configure.ts +279 -0
- package/src/auth/der.ts +35 -0
- package/src/auth/index.ts +387 -0
- package/src/auth/issue.ts +52 -0
- package/src/auth/metadata.ts +149 -0
- package/src/auth/oauth.ts +882 -0
- package/src/auth/passkey.ts +556 -0
- package/src/auth/state.ts +213 -0
- package/src/auth/storage.ts +572 -0
- package/src/auth/token.ts +67 -0
- package/src/context/index.ts +240 -65
- package/src/cookie/index.ts +3 -0
- package/src/database/index.ts +1193 -0
- package/src/form/index.ts +1720 -0
- package/src/index.ts +10 -3
- package/src/jsx/elements.ts +45 -25
- package/src/jsx/index.ts +24 -69
- package/src/limiter/index.ts +221 -0
- package/src/markdown/index.ts +1322 -0
- package/src/markup/index.ts +853 -0
- package/src/mcp/conformance.2025-11-25.yml +39 -0
- package/src/mcp/conformance.2026-07-28.yml +56 -0
- package/src/mcp/index.ts +1262 -0
- package/src/middleware/index.ts +5 -6
- package/src/multipart/index.ts +410 -158
- package/src/route/index.ts +559 -278
- package/src/schema/index.ts +1542 -2256
- package/src/table/index.ts +387 -0
- package/src/trie/index.ts +4 -4
- package/src/util/index.ts +163 -49
- package/dist/render/index.d.ts +0 -79
- package/dist/render/index.d.ts.map +0 -1
- package/dist/render/index.js +0 -257
- package/src/render/index.ts +0 -314
package/src/index.ts
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
export { App } from "./app/index.js";
|
|
2
|
-
export {
|
|
2
|
+
export { Auth } from "./auth/index.js";
|
|
3
|
+
export { Database } from "./database/index.js";
|
|
4
|
+
export { Limiter } from "./limiter/index.js";
|
|
5
|
+
export { Mcp } from "./mcp/index.js";
|
|
6
|
+
export type { JSX } from "./jsx/index.js";
|
|
3
7
|
export type { Middleware } from "./middleware/index.js";
|
|
4
8
|
export { Multipart } from "./multipart/index.js";
|
|
5
|
-
export {
|
|
9
|
+
export { Markup } from "./markup/index.js";
|
|
10
|
+
export { Markdown } from "./markdown/index.js";
|
|
6
11
|
export { Route } from "./route/index.js";
|
|
7
|
-
export {
|
|
12
|
+
export { Table } from "./table/index.js";
|
|
13
|
+
export { Field } from "./form/index.js";
|
|
14
|
+
export { Schema } from "./schema/index.js";
|
package/src/jsx/elements.ts
CHANGED
|
@@ -328,6 +328,8 @@ type FieldsetAttributes = Attributes<{
|
|
|
328
328
|
disabled: boolean;
|
|
329
329
|
form: string;
|
|
330
330
|
name: string;
|
|
331
|
+
/** WebMCP description of a radio group for browser agents */
|
|
332
|
+
toolparamdescription: string;
|
|
331
333
|
}>;
|
|
332
334
|
|
|
333
335
|
type FormAttributes = Attributes<{
|
|
@@ -350,6 +352,12 @@ type FormAttributes = Attributes<{
|
|
|
350
352
|
method: SharedAttributes["method"];
|
|
351
353
|
novalidate: boolean;
|
|
352
354
|
target: SharedAttributes["target"];
|
|
355
|
+
/** [WebMCP](https://developer.chrome.com/docs/ai/webmcp/declarative-api) tool name for browser agents */
|
|
356
|
+
toolname: string;
|
|
357
|
+
/** WebMCP tool description, required with `toolname` */
|
|
358
|
+
tooldescription: string;
|
|
359
|
+
/** Lets a browser agent submit the form without the user clicking */
|
|
360
|
+
toolautosubmit: boolean;
|
|
353
361
|
}>;
|
|
354
362
|
|
|
355
363
|
type HtmlAttributes = Attributes<{ xmlns: string }>;
|
|
@@ -445,6 +453,8 @@ type InputAttributes = Attributes<
|
|
|
445
453
|
value: string | number;
|
|
446
454
|
webkitdirectory: boolean;
|
|
447
455
|
width: string;
|
|
456
|
+
/** WebMCP parameter description for browser agents */
|
|
457
|
+
toolparamdescription: string;
|
|
448
458
|
},
|
|
449
459
|
never
|
|
450
460
|
>;
|
|
@@ -607,6 +617,8 @@ type SelectAttributes = Attributes<{
|
|
|
607
617
|
name: string;
|
|
608
618
|
required: boolean;
|
|
609
619
|
size: string | number;
|
|
620
|
+
/** WebMCP parameter description for browser agents */
|
|
621
|
+
toolparamdescription: string;
|
|
610
622
|
}>;
|
|
611
623
|
|
|
612
624
|
type SlotAttributes = Attributes<{ name: string }>;
|
|
@@ -656,6 +668,8 @@ type TextareaAttributes = Attributes<{
|
|
|
656
668
|
required: boolean;
|
|
657
669
|
rows: string | number;
|
|
658
670
|
wrap: "hard" | "soft" | "off";
|
|
671
|
+
/** WebMCP parameter description for browser agents */
|
|
672
|
+
toolparamdescription: string;
|
|
659
673
|
}>;
|
|
660
674
|
|
|
661
675
|
type ThAttributes = Attributes<{
|
|
@@ -697,6 +711,12 @@ type VideoAttributes = Attributes<{
|
|
|
697
711
|
}>;
|
|
698
712
|
|
|
699
713
|
// XML
|
|
714
|
+
/**
|
|
715
|
+
* Attributes of an XML element.
|
|
716
|
+
*
|
|
717
|
+
* @template P Element attributes
|
|
718
|
+
* @template Children Children the element accepts
|
|
719
|
+
*/
|
|
700
720
|
type XMLAttributes<
|
|
701
721
|
P extends JSX.Props = JSX.Props,
|
|
702
722
|
Children = JSX.Element,
|
|
@@ -730,6 +750,12 @@ type AtomLinkAttributes = {
|
|
|
730
750
|
|
|
731
751
|
// SVG
|
|
732
752
|
// SVG
|
|
753
|
+
/**
|
|
754
|
+
* Attributes of an SVG element.
|
|
755
|
+
*
|
|
756
|
+
* @template P Element attributes
|
|
757
|
+
* @template Children Children the element accepts
|
|
758
|
+
*/
|
|
733
759
|
type SvgAttributes<
|
|
734
760
|
P extends JSX.Props = JSX.Props,
|
|
735
761
|
Children = JSX.Element,
|
|
@@ -867,32 +893,26 @@ type SvgImageAttributes = SvgAttributes<{
|
|
|
867
893
|
preserveAspectRatio: SvgRootAttributes["preserveAspectRatio"];
|
|
868
894
|
}>;
|
|
869
895
|
|
|
870
|
-
type SvgLinearGradientAttributes = SvgAttributes<
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
},
|
|
880
|
-
undefined
|
|
881
|
-
>;
|
|
896
|
+
type SvgLinearGradientAttributes = SvgAttributes<{
|
|
897
|
+
x1: string | number;
|
|
898
|
+
y1: string | number;
|
|
899
|
+
x2: string | number;
|
|
900
|
+
y2: string | number;
|
|
901
|
+
gradientUnits: "userSpaceOnUse" | "objectBoundingBox";
|
|
902
|
+
gradientTransform: string;
|
|
903
|
+
spreadMethod: "pad" | "reflect" | "repeat";
|
|
904
|
+
}>;
|
|
882
905
|
|
|
883
|
-
type SvgRadialGradientAttributes = SvgAttributes<
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
},
|
|
894
|
-
undefined
|
|
895
|
-
>;
|
|
906
|
+
type SvgRadialGradientAttributes = SvgAttributes<{
|
|
907
|
+
cx: string | number;
|
|
908
|
+
cy: string | number;
|
|
909
|
+
r: string | number;
|
|
910
|
+
fx: string | number;
|
|
911
|
+
fy: string | number;
|
|
912
|
+
gradientUnits: "userSpaceOnUse" | "objectBoundingBox";
|
|
913
|
+
gradientTransform: string;
|
|
914
|
+
spreadMethod: "pad" | "reflect" | "repeat";
|
|
915
|
+
}>;
|
|
896
916
|
|
|
897
917
|
type SvgStopAttributes = SvgAttributes<
|
|
898
918
|
{
|
package/src/jsx/index.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Element, type Markup } from "../markup/index.js";
|
|
2
2
|
import type { IntrinsicElements as IE } from "./elements.js";
|
|
3
3
|
|
|
4
4
|
export namespace JSX {
|
|
5
|
+
/**
|
|
6
|
+
* `T`, or a promise of it.
|
|
7
|
+
*
|
|
8
|
+
* @template T Value
|
|
9
|
+
*/
|
|
5
10
|
type MaybePromise<T> = T | Promise<T>;
|
|
11
|
+
/**
|
|
12
|
+
* `T`, or a function returning it.
|
|
13
|
+
*
|
|
14
|
+
* @template T Value
|
|
15
|
+
*/
|
|
6
16
|
type MaybeFunction<T> = T | (() => T);
|
|
7
17
|
|
|
8
18
|
/** Standard HTML elements */
|
|
@@ -26,90 +36,35 @@ export namespace JSX {
|
|
|
26
36
|
|
|
27
37
|
/** Unknown component props */
|
|
28
38
|
export type Props = Record<string, JSX.Element>;
|
|
29
|
-
}
|
|
30
39
|
|
|
31
|
-
/** ovr JSX */
|
|
32
|
-
export class JSX {
|
|
33
40
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
41
|
+
* What a tag can be: an element's name, or a component, which is a
|
|
42
|
+
* function. A class is not one, so `<Form />` with the `Form` class is a
|
|
43
|
+
* type error instead of failing as it renders.
|
|
37
44
|
*/
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
"base",
|
|
41
|
-
"br",
|
|
42
|
-
"col",
|
|
43
|
-
"embed",
|
|
44
|
-
"hr",
|
|
45
|
-
"img",
|
|
46
|
-
"input",
|
|
47
|
-
"link",
|
|
48
|
-
"meta",
|
|
49
|
-
"source",
|
|
50
|
-
"track",
|
|
51
|
-
"wbr",
|
|
52
|
-
"xml",
|
|
53
|
-
]);
|
|
45
|
+
export type ElementType = string | ((props: any) => unknown);
|
|
46
|
+
}
|
|
54
47
|
|
|
48
|
+
/** ovr JSX */
|
|
49
|
+
export class JSX {
|
|
55
50
|
/**
|
|
56
51
|
* The main function of the JSX transform cycle, each time JSX is encountered
|
|
57
52
|
* it is passed into `jsx` to be resolved.
|
|
58
53
|
*
|
|
54
|
+
* @template P Props of the element or component
|
|
59
55
|
* @param tag tag name or function component
|
|
60
56
|
* @param props object containing all the properties and attributes passed to the element or component
|
|
61
|
-
* @
|
|
57
|
+
* @returns Generator of the element's `Chunk`s of HTML
|
|
62
58
|
*/
|
|
63
|
-
static
|
|
59
|
+
static jsx<P extends JSX.Props = JSX.Props>(
|
|
64
60
|
tag: ((props: P) => JSX.Element) | string,
|
|
65
61
|
props: P,
|
|
66
|
-
): AsyncGenerator<
|
|
62
|
+
): AsyncGenerator<Markup.Chunk, void, unknown> {
|
|
67
63
|
// this function doesn't need to be called recursively
|
|
68
64
|
// JSX will be transformed into `jsx()` function calls automatically
|
|
69
65
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
yield* new Render(tag(props));
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// intrinsic element
|
|
77
|
-
// faster to concatenate attributes than to yield them as separate chunks
|
|
78
|
-
let opening = tag;
|
|
79
|
-
|
|
80
|
-
for (const key in props) {
|
|
81
|
-
// more memory efficient to skip children instead of destructuring and using ...rest
|
|
82
|
-
if (key === "children") continue;
|
|
83
|
-
|
|
84
|
-
const value = props[key];
|
|
85
|
-
|
|
86
|
-
if (value === true) {
|
|
87
|
-
// just put the key without the value
|
|
88
|
-
opening += ` ${key}`;
|
|
89
|
-
} else if (typeof value === "string") {
|
|
90
|
-
opening += ` ${key}="${Render.escape(value, true)}"`;
|
|
91
|
-
} else if (typeof value === "number" || typeof value === "bigint") {
|
|
92
|
-
opening += ` ${key}="${value}"`;
|
|
93
|
-
}
|
|
94
|
-
// otherwise, don't include the attribute
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
if (tag === "html") {
|
|
98
|
-
yield Render.html(`<!doctype html><${opening}>`);
|
|
99
|
-
} else if (tag === "xml") {
|
|
100
|
-
yield Render.html(`<?${opening}?>`);
|
|
101
|
-
} else {
|
|
102
|
-
yield Render.html(`<${opening}>`);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
// if children and a void element, render it like normal
|
|
106
|
-
// to account for cases like XML <link>content</link>
|
|
107
|
-
// assumes the user knows what they are doing
|
|
108
|
-
if (props.children == null && JSX.#void.has(tag)) return;
|
|
109
|
-
|
|
110
|
-
yield* new Render(props.children);
|
|
111
|
-
|
|
112
|
-
yield Render.html(`</${tag}>`);
|
|
66
|
+
// a component is called, and an element's markup built, when it is rendered
|
|
67
|
+
return new Element(tag, props);
|
|
113
68
|
}
|
|
114
69
|
|
|
115
70
|
/**
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import type { Context as ContextType } from "../context/index.js";
|
|
2
|
+
import { type Database, owned } from "../database/index.js";
|
|
3
|
+
import type { Middleware } from "../middleware/index.js";
|
|
4
|
+
import { Schema } from "../schema/index.js";
|
|
5
|
+
import { Table } from "../table/index.js";
|
|
6
|
+
import { Codec, Time, noStore } from "../util/index.js";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Internal to ovr, which counts each client this way.
|
|
10
|
+
*
|
|
11
|
+
* @param value Client IP
|
|
12
|
+
* @returns The IPv4 address, or the IPv6 /64 network, one home or office
|
|
13
|
+
*/
|
|
14
|
+
export function network(value: string | undefined) {
|
|
15
|
+
if (!value || value.length > 64 || !/^[\da-f:.]+$/i.test(value)) return;
|
|
16
|
+
if (!value.includes(":")) {
|
|
17
|
+
const octets = value.split(".");
|
|
18
|
+
|
|
19
|
+
return octets.length === 4 &&
|
|
20
|
+
octets.every((v) => /^(0|[1-9]\d{0,2})$/.test(v) && Number(v) <= 255)
|
|
21
|
+
? value
|
|
22
|
+
: undefined;
|
|
23
|
+
}
|
|
24
|
+
let host: string;
|
|
25
|
+
try {
|
|
26
|
+
host = new URL(`http://[${value}]`).hostname;
|
|
27
|
+
} catch {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const [head = "", tail = ""] = host.slice(1, -1).split("::");
|
|
31
|
+
const first = head ? head.split(":") : [];
|
|
32
|
+
const last = tail ? tail.split(":") : [];
|
|
33
|
+
const groups: string[] = [
|
|
34
|
+
...first,
|
|
35
|
+
...Array<string>(8 - first.length - last.length).fill("0"),
|
|
36
|
+
...last,
|
|
37
|
+
];
|
|
38
|
+
// IPv4-mapped IPv6 addresses share their IPv4 budget, rather than one giant ::ffff /64 bucket.
|
|
39
|
+
if (groups.slice(0, 5).every((v) => v === "0") && groups[5] === "ffff") {
|
|
40
|
+
const high = parseInt(groups[6]!, 16);
|
|
41
|
+
const low = parseInt(groups[7]!, 16);
|
|
42
|
+
return [high >> 8, high & 255, low >> 8, low & 255].join(".");
|
|
43
|
+
}
|
|
44
|
+
return (
|
|
45
|
+
groups
|
|
46
|
+
.map((v, i) => (i < 4 ? parseInt(v, 16).toString(16) : "0"))
|
|
47
|
+
.join(":") + "/64"
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export namespace Limiter {
|
|
52
|
+
/**
|
|
53
|
+
* Request capabilities available before parsing a body, including the
|
|
54
|
+
* session, so a `key` can count each signed-in user.
|
|
55
|
+
*/
|
|
56
|
+
export type Context = Pick<
|
|
57
|
+
ContextType,
|
|
58
|
+
"req" | "url" | "ip" | "cookie" | "res" | "session"
|
|
59
|
+
>;
|
|
60
|
+
/** A token bucket allows an initial burst, then replenishes continuously. */
|
|
61
|
+
export interface Policy {
|
|
62
|
+
readonly limit: number;
|
|
63
|
+
readonly interval: number;
|
|
64
|
+
}
|
|
65
|
+
/** Shared Postgres storage, with a default policy of 60 requests per minute. */
|
|
66
|
+
export interface Options extends Partial<Policy> {
|
|
67
|
+
/** Database containing `Limiter.table`, shared by every instance. */
|
|
68
|
+
readonly database: Database & {
|
|
69
|
+
readonly [Name in (typeof Limiter.table)["name"]]: typeof Limiter.table;
|
|
70
|
+
};
|
|
71
|
+
/** Override trusted-IP keying, for example with an authenticated user ID. Missing keys fail closed. */
|
|
72
|
+
readonly key?: (
|
|
73
|
+
c: Context,
|
|
74
|
+
) => string | undefined | Promise<string | undefined>;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Internal failure to apply a rate limit; callers must not admit the request. */
|
|
79
|
+
export class LimitIssue extends Error {}
|
|
80
|
+
|
|
81
|
+
/** Token buckets stored in Postgres, usable by authentication and ordinary route middleware. */
|
|
82
|
+
export class Limiter {
|
|
83
|
+
/**
|
|
84
|
+
* Token buckets shared by every limiter, include it in the database's
|
|
85
|
+
* tables. `database.migrate` then creates it, `Auth.tables` already includes it.
|
|
86
|
+
*/
|
|
87
|
+
static readonly table = new Table("rate_limits", {
|
|
88
|
+
key: Schema.string(),
|
|
89
|
+
tokens: Schema.number(),
|
|
90
|
+
time: Schema.number().int(),
|
|
91
|
+
expiration: Schema.number().int(),
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
static {
|
|
95
|
+
// a version never changes, later changes ship as new versions
|
|
96
|
+
owned.set(Limiter.table, [
|
|
97
|
+
{
|
|
98
|
+
id: "rate_limits:1",
|
|
99
|
+
sql: `CREATE TABLE rate_limits (
|
|
100
|
+
key text PRIMARY KEY,
|
|
101
|
+
tokens double precision NOT NULL,
|
|
102
|
+
time bigint NOT NULL,
|
|
103
|
+
expiration bigint NOT NULL
|
|
104
|
+
);
|
|
105
|
+
CREATE INDEX rate_limits_expiration ON rate_limits (expiration);`,
|
|
106
|
+
},
|
|
107
|
+
]);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
readonly #name;
|
|
111
|
+
readonly #options;
|
|
112
|
+
#pruned = 0;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Create a policy backed by the application's database.
|
|
116
|
+
*
|
|
117
|
+
* @param name Stable name of the policy's buckets. Limiters with the same name and policy share them, across every server using the database.
|
|
118
|
+
*/
|
|
119
|
+
constructor(name: string, options: Limiter.Options) {
|
|
120
|
+
this.#options = { limit: 60, interval: Time.minute, ...options };
|
|
121
|
+
this.#name = name;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Admit a request or return its retry deadline. Scopes have independent budgets. */
|
|
125
|
+
async check(c: Limiter.Context, scope = ""): Promise<true | Date> {
|
|
126
|
+
const identity = this.#options.key
|
|
127
|
+
? await this.#options.key(c)
|
|
128
|
+
: network(c.ip);
|
|
129
|
+
if (typeof identity !== "string" || !identity || identity.length > 1024)
|
|
130
|
+
throw new LimitIssue(
|
|
131
|
+
"Rate limiting requires a trusted client IP in App.fetch(request, { ip }), or an explicit authenticated key",
|
|
132
|
+
);
|
|
133
|
+
const { limit, interval } = this.#options;
|
|
134
|
+
// Different policies cannot interpret the same stored token balance
|
|
135
|
+
// differently. Hashed, so a long name, scope, or identity always fits
|
|
136
|
+
// in the primary key's index.
|
|
137
|
+
const retry = await this.#consume(
|
|
138
|
+
Codec.Base64Url.encode(
|
|
139
|
+
new Uint8Array(
|
|
140
|
+
await crypto.subtle.digest(
|
|
141
|
+
"SHA-256",
|
|
142
|
+
Codec.encode(
|
|
143
|
+
JSON.stringify([this.#name, limit, interval, scope, identity]),
|
|
144
|
+
),
|
|
145
|
+
),
|
|
146
|
+
),
|
|
147
|
+
),
|
|
148
|
+
);
|
|
149
|
+
if (retry === true) return true;
|
|
150
|
+
const now = Date.now();
|
|
151
|
+
return new Date(
|
|
152
|
+
Math.min(now + 3600000, Math.max(now + 1000, Math.ceil(retry))),
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Mount globally with app.use(), or on selected routes. A missing identity
|
|
158
|
+
* or storage failure throws, so the app's error handling sees it and the
|
|
159
|
+
* request is not admitted.
|
|
160
|
+
*/
|
|
161
|
+
readonly middleware: Middleware = async (c, next) => {
|
|
162
|
+
const result = await this.check(c);
|
|
163
|
+
if (result === true) return next();
|
|
164
|
+
noStore(c.res.headers);
|
|
165
|
+
c.res.headers.set(
|
|
166
|
+
"retry-after",
|
|
167
|
+
String(Math.max(1, Math.ceil((result.getTime() - Date.now()) / 1000))),
|
|
168
|
+
);
|
|
169
|
+
c.text("Too many requests. Try again later.", 429);
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Atomically refill and consume a token, in one statement when admitted.
|
|
174
|
+
*
|
|
175
|
+
* @param key Bucket key
|
|
176
|
+
* @returns `true` when admitted, otherwise the retry time in milliseconds
|
|
177
|
+
*/
|
|
178
|
+
async #consume(key: string) {
|
|
179
|
+
const { database: db, limit, interval } = this.#options;
|
|
180
|
+
const table = Limiter.table;
|
|
181
|
+
const now = Date.now();
|
|
182
|
+
|
|
183
|
+
// either direction, so a clock moving back cannot stop pruning
|
|
184
|
+
if (Math.abs(now - this.#pruned) >= Time.minute) {
|
|
185
|
+
this.#pruned = now;
|
|
186
|
+
await db.sql`DELETE FROM ${table} WHERE expiration <= ${now}`;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// expired buckets start full, others refill continuously since their last use
|
|
190
|
+
const tokens = db.sql`CASE WHEN l.expiration > ${now}::bigint
|
|
191
|
+
THEN LEAST(${limit}::float8, l.tokens + GREATEST(0, ${now}::bigint - l.time) * ${limit}::float8 / ${interval}::float8)
|
|
192
|
+
ELSE ${limit}::float8 END`;
|
|
193
|
+
const admitted = await db.sql`
|
|
194
|
+
INSERT INTO ${table} AS l (key, tokens, time, expiration)
|
|
195
|
+
VALUES (${key}, ${limit - 1}, ${now}, ${now + interval})
|
|
196
|
+
ON CONFLICT (key) DO UPDATE SET
|
|
197
|
+
tokens = ${tokens} - 1,
|
|
198
|
+
time = GREATEST(${now}::bigint, l.time),
|
|
199
|
+
expiration = ${now + interval}
|
|
200
|
+
WHERE ${tokens} >= 1
|
|
201
|
+
RETURNING 1
|
|
202
|
+
`;
|
|
203
|
+
|
|
204
|
+
if (admitted.length) return true;
|
|
205
|
+
|
|
206
|
+
const [bucket] = await db.sql`
|
|
207
|
+
SELECT * FROM ${table} WHERE key = ${key}
|
|
208
|
+
`.parse(Limiter.table);
|
|
209
|
+
const available =
|
|
210
|
+
!bucket || bucket.expiration <= now
|
|
211
|
+
? limit
|
|
212
|
+
: Math.min(
|
|
213
|
+
limit,
|
|
214
|
+
bucket.tokens + (Math.max(0, now - bucket.time) * limit) / interval,
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
return (
|
|
218
|
+
now + Math.max(1000, Math.ceil(((1 - available) * interval) / limit))
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
}
|