@farm.js/bot 0.0.0-stage → 0.1.0-beta.1

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.
Files changed (66) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +240 -2
  3. package/dist/build-mode.d.ts +3 -0
  4. package/dist/build-mode.d.ts.map +1 -0
  5. package/dist/build-mode.js +4 -0
  6. package/dist/captcha/index.d.ts +4 -0
  7. package/dist/captcha/index.d.ts.map +1 -0
  8. package/dist/captcha/index.js +2 -0
  9. package/dist/captcha/providers.d.ts +11 -0
  10. package/dist/captcha/providers.d.ts.map +1 -0
  11. package/dist/captcha/providers.js +90 -0
  12. package/dist/captcha/siteverify.d.ts +37 -0
  13. package/dist/captcha/siteverify.d.ts.map +1 -0
  14. package/dist/captcha/siteverify.js +88 -0
  15. package/dist/captcha/widget.d.ts +19 -0
  16. package/dist/captcha/widget.d.ts.map +1 -0
  17. package/dist/captcha/widget.js +52 -0
  18. package/dist/client.d.ts +69 -0
  19. package/dist/client.d.ts.map +1 -0
  20. package/dist/client.js +235 -0
  21. package/dist/csp.d.ts +15 -0
  22. package/dist/csp.d.ts.map +1 -0
  23. package/dist/csp.js +99 -0
  24. package/dist/errors.d.ts +10 -0
  25. package/dist/errors.d.ts.map +1 -0
  26. package/dist/errors.js +9 -0
  27. package/dist/index.d.ts +28 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +128 -0
  30. package/dist/keys.d.ts +44 -0
  31. package/dist/keys.d.ts.map +1 -0
  32. package/dist/keys.js +67 -0
  33. package/dist/preact.d.ts +10 -0
  34. package/dist/preact.d.ts.map +1 -0
  35. package/dist/preact.js +31 -0
  36. package/dist/provider-widget.d.ts +3 -0
  37. package/dist/provider-widget.d.ts.map +1 -0
  38. package/dist/provider-widget.js +5 -0
  39. package/dist/provider.d.ts +70 -0
  40. package/dist/provider.d.ts.map +1 -0
  41. package/dist/provider.js +83 -0
  42. package/dist/react.d.ts +8 -0
  43. package/dist/react.d.ts.map +1 -0
  44. package/dist/react.js +31 -0
  45. package/dist/runtime.d.ts +5 -0
  46. package/dist/runtime.d.ts.map +1 -0
  47. package/dist/runtime.js +8 -0
  48. package/dist/server.d.ts +9 -0
  49. package/dist/server.d.ts.map +1 -0
  50. package/dist/server.js +14 -0
  51. package/dist/solid.d.ts +9 -0
  52. package/dist/solid.d.ts.map +1 -0
  53. package/dist/solid.js +34 -0
  54. package/dist/svelte.d.ts +12 -0
  55. package/dist/svelte.d.ts.map +1 -0
  56. package/dist/svelte.js +22 -0
  57. package/dist/testing.d.ts +22 -0
  58. package/dist/testing.d.ts.map +1 -0
  59. package/dist/testing.js +102 -0
  60. package/dist/verify.d.ts +39 -0
  61. package/dist/verify.d.ts.map +1 -0
  62. package/dist/verify.js +113 -0
  63. package/dist/vue.d.ts +20 -0
  64. package/dist/vue.d.ts.map +1 -0
  65. package/dist/vue.js +32 -0
  66. package/package.json +122 -3
@@ -0,0 +1,69 @@
1
+ import type { BotClientState } from "./provider.js";
2
+ export type { BotClientState } from "./provider.js";
3
+ export type BotTheme = "auto" | "light" | "dark";
4
+ /** What an app passes when it shows the check. */
5
+ export interface BotWidgetOptions {
6
+ /** Defaults to `"auto"`, which follows the visitor's color scheme. */
7
+ theme?: BotTheme;
8
+ /** Passed straight to the provider's widget, for example `{ size: "compact" }`. */
9
+ settings?: Readonly<Record<string, unknown>>;
10
+ /** Called with the token once the visitor passes. A check that draws nothing passes `""`. */
11
+ onVerify?: (token: string) => void;
12
+ /** Called when the widget or its script fails. */
13
+ onError?: (error: unknown) => void;
14
+ /** Called when a token expires before the form is sent. */
15
+ onExpire?: () => void;
16
+ }
17
+ export interface BotWidget {
18
+ /** Clear the token and run the check again, for example after a failed submit. */
19
+ reset(): void;
20
+ /** Remove the widget. Safe to call before it has finished loading. */
21
+ remove(): void;
22
+ }
23
+ /** The handle a component exposes through its ref. */
24
+ export type BotCheckHandle = Pick<BotWidget, "reset">;
25
+ /** What a provider's browser half receives for each widget. */
26
+ export interface BotWidgetMount {
27
+ theme: BotTheme;
28
+ settings: Readonly<Record<string, unknown>>;
29
+ /** Aborted when the app removes the widget before `mount` has finished. */
30
+ signal: AbortSignal;
31
+ /** Report the token. Farm adds it to the form under the provider's `tokenField`. */
32
+ onVerify(token: string): void;
33
+ onError(error: unknown): void;
34
+ /** Report that the token can no longer be used. Farm takes it out of the form. */
35
+ onExpire(): void;
36
+ }
37
+ /** The browser half of a bot checker. */
38
+ export interface BotWidgetDriver {
39
+ /** Draw the check inside `element`. `remove` must take away everything `mount` added. */
40
+ mount(element: HTMLElement, mount: BotWidgetMount): BotWidget | Promise<BotWidget>;
41
+ }
42
+ /** Builds the browser half from the provider's `public` data. Return nothing to draw nothing. */
43
+ export type BotWidgetFactory<TConfig = undefined> = (config: TConfig) => BotWidgetDriver | void | Promise<BotWidgetDriver | void>;
44
+ /** Declare a provider's browser half. Make it the default export of the module `client()` names. */
45
+ export declare function defineBotWidget<TConfig = undefined>(create: BotWidgetFactory<TConfig>): BotWidgetFactory<TConfig>;
46
+ /** What the plugin compiles into the browser bundle. */
47
+ export interface BotWidgetStart {
48
+ widget: string;
49
+ tokenField?: string;
50
+ config?: unknown;
51
+ }
52
+ export interface BotScriptOptions {
53
+ /** The browser global the script defines. */
54
+ global: string;
55
+ /** The script signals readiness through an `onload` callback instead of its load event. */
56
+ readyCallback?: boolean;
57
+ }
58
+ /** Start a provider's browser half. Farm calls this when the page loads. */
59
+ export declare function startBotWidget(create: unknown, start: BotWidgetStart): Promise<BotClientState>;
60
+ /** Make a widget available to the page. Widgets mounted earlier wait for this. */
61
+ export declare function provideBotWidget(driver: BotWidgetDriver, runtimeWindow?: Window): BotClientState;
62
+ /**
63
+ * Show the bot check inside an element in a form. Pass a function to have callbacks read fresh
64
+ * on every event, which is what the renderer components do.
65
+ */
66
+ export declare function mountBotCheck(element: HTMLElement, options?: BotWidgetOptions | (() => BotWidgetOptions)): BotWidget;
67
+ /** Load a provider's script once per page, carrying the page's CSP nonce. */
68
+ export declare function loadBotScript<TApi = unknown>(src: string, options: BotScriptOptions, runtimeWindow?: Window): Promise<TApi>;
69
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,YAAY,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AAEjD,kDAAkD;AAClD,MAAM,WAAW,gBAAgB;IAC/B,sEAAsE;IACtE,KAAK,CAAC,EAAE,QAAQ,CAAC;IACjB,mFAAmF;IACnF,QAAQ,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAC7C,6FAA6F;IAC7F,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,kDAAkD;IAClD,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACnC,2DAA2D;IAC3D,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;CACvB;AAED,MAAM,WAAW,SAAS;IACxB,kFAAkF;IAClF,KAAK,IAAI,IAAI,CAAC;IACd,sEAAsE;IACtE,MAAM,IAAI,IAAI,CAAC;CAChB;AAED,sDAAsD;AACtD,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;AAEtD,+DAA+D;AAC/D,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,QAAQ,CAAC;IAChB,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAC5C,2EAA2E;IAC3E,MAAM,EAAE,WAAW,CAAC;IACpB,oFAAoF;IACpF,QAAQ,CAAC,K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gB,CAAM,GACxD,SAAS,CAyDX;AAED,6EAA6E;AAC7E,wBAAgB,aAAa,CAAC,IAAI,GAAG,OAAO,EAC1C,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,gBAAgB,EACzB,aAAa,GAAE,MAAe,GAC7B,OAAO,CAAC,IAAI,CAAC,CA2Df"}
package/dist/client.js ADDED
@@ -0,0 +1,235 @@
1
+ import { BotError } from "./errors.js";
2
+ /** Declare a provider's browser half. Make it the default export of the module `client()` names. */
3
+ export function defineBotWidget(create) {
4
+ return create;
5
+ }
6
+ // Shared through the window: the plugin and the components may load separate module copies.
7
+ const REGISTRY = Symbol.for("farm.bot");
8
+ const MISSING_PROVIDER_WARNING_MS = 3000;
9
+ // Pages can gate a form on `onVerify`, so a check with nothing to show has to report in too.
10
+ const INVISIBLE_DRIVER = {
11
+ mount(_element, mount) {
12
+ const report = () => mount.onVerify("");
13
+ report();
14
+ return { reset: report, remove() { } };
15
+ },
16
+ };
17
+ function registryFor(runtimeWindow) {
18
+ const host = runtimeWindow;
19
+ return (host[REGISTRY] ??= {
20
+ driver: undefined,
21
+ waiters: [],
22
+ scripts: new Map(),
23
+ callbacks: 0,
24
+ });
25
+ }
26
+ /** Keep the widget's latest token in the form, so the form sends it like any other input. */
27
+ function withTokenField(driver, name) {
28
+ if (name === undefined)
29
+ return driver;
30
+ return {
31
+ async mount(element, mount) {
32
+ let field;
33
+ const clear = () => {
34
+ field?.remove();
35
+ field = undefined;
36
+ };
37
+ const widget = await driver.mount(element, {
38
+ ...mount,
39
+ onVerify(token) {
40
+ if (mount.signal.aborted)
41
+ return;
42
+ // Vendor scripts add their own field, and a widget may redraw its element.
43
+ const hasOwnField = [...element.querySelectorAll("[name]")].some((node) => node !== field && node.getAttribute("name") === name);
44
+ if (!hasOwnField) {
45
+ if (!field?.isConnected) {
46
+ field = element.ownerDocument.createElement("input");
47
+ field.type = "hidden";
48
+ field.name = name;
49
+ element.append(field);
50
+ }
51
+ field.value = token;
52
+ }
53
+ mount.onVerify(token);
54
+ },
55
+ onExpire() {
56
+ clear();
57
+ mount.onExpire();
58
+ },
59
+ });
60
+ return {
61
+ reset() {
62
+ clear();
63
+ widget.reset();
64
+ },
65
+ remove() {
66
+ clear();
67
+ widget.remove();
68
+ },
69
+ };
70
+ },
71
+ };
72
+ }
73
+ /** Start a provider's browser half. Farm calls this when the page loads. */
74
+ export async function startBotWidget(create, start) {
75
+ // The placeholder `@farm.js/bot/provider-widget` exports, in place of the provider's widget.
76
+ if (create === Symbol.for("@farm.js/bot/no-widget")) {
77
+ throw new BotError("missing_plugin", `This build has no widget for "${start.widget}". The bot plugin's \`configure\` hook adds it, and \`experimental.serverComponents\` in \`rsc\` mode doesn't run that hook yet. Use \`islands\` mode.`);
78
+ }
79
+ if (typeof create !== "function") {
80
+ throw new TypeError(`"${start.widget}" must have \`defineBotWidget(...)\` as its default export.`);
81
+ }
82
+ const driver = ((await create(start.config)) ?? INVISIBLE_DRIVER);
83
+ if (typeof driver.mount !== "function") {
84
+ throw new TypeError(`The widget in "${start.widget}" must return an object with \`mount\`, or nothing if it draws nothing.`);
85
+ }
86
+ return provideBotWidget(withTokenField(driver, start.tokenField));
87
+ }
88
+ /** Make a widget available to the page. Widgets mounted earlier wait for this. */
89
+ export function provideBotWidget(driver, runtimeWindow = window) {
90
+ const registry = registryFor(runtimeWindow);
91
+ registry.driver = driver;
92
+ for (const resolve of registry.waiters.splice(0))
93
+ resolve(driver);
94
+ return {
95
+ close() {
96
+ if (registry.driver === driver)
97
+ registry.driver = undefined;
98
+ },
99
+ };
100
+ }
101
+ function waitForDriver(registry) {
102
+ if (registry.driver)
103
+ return Promise.resolve(registry.driver);
104
+ return new Promise((resolve) => registry.waiters.push(resolve));
105
+ }
106
+ /** In development, say why a check never appears. The server still refuses the form. */
107
+ function warnIfNoProvider(registry, runtimeWindow) {
108
+ const env = import.meta.env;
109
+ if (env?.DEV !== true || registry.driver)
110
+ return () => { };
111
+ const timer = runtimeWindow.setTimeout(() => {
112
+ console.warn("[farm:bot] No bot provider has started on this page. Add `bot({ provider })` to `plugins` in farm.config.ts. A provider with no browser half doesn't need a widget.");
113
+ }, MISSING_PROVIDER_WARNING_MS);
114
+ return () => runtimeWindow.clearTimeout(timer);
115
+ }
116
+ /**
117
+ * Show the bot check inside an element in a form. Pass a function to have callbacks read fresh
118
+ * on every event, which is what the renderer components do.
119
+ */
120
+ export function mountBotCheck(element, options = {}) {
121
+ const runtimeWindow = element.ownerDocument.defaultView;
122
+ if (!runtimeWindow) {
123
+ throw new Error("mountBotCheck() needs an element in a document with a window.");
124
+ }
125
+ const latest = typeof options === "function" ? options : () => options;
126
+ const { theme = "auto", settings = {} } = latest();
127
+ const aborter = new AbortController();
128
+ let widget;
129
+ const reportError = (error) => {
130
+ if (aborter.signal.aborted)
131
+ return;
132
+ const { onError } = latest();
133
+ if (onError)
134
+ onError(error);
135
+ else
136
+ console.error("[farm:bot]", error);
137
+ };
138
+ const registry = registryFor(runtimeWindow);
139
+ const stopWarning = warnIfNoProvider(registry, runtimeWindow);
140
+ waitForDriver(registry)
141
+ .then((driver) => {
142
+ stopWarning();
143
+ if (aborter.signal.aborted)
144
+ return undefined;
145
+ return driver.mount(element, {
146
+ theme,
147
+ settings,
148
+ signal: aborter.signal,
149
+ // A provider with no `remove` can still call back after the app removed the widget.
150
+ onVerify: (token) => {
151
+ if (!aborter.signal.aborted)
152
+ latest().onVerify?.(token);
153
+ },
154
+ onError: reportError,
155
+ onExpire: () => {
156
+ if (!aborter.signal.aborted)
157
+ latest().onExpire?.();
158
+ },
159
+ });
160
+ })
161
+ .then((mounted) => {
162
+ if (!mounted)
163
+ return;
164
+ if (aborter.signal.aborted)
165
+ mounted.remove();
166
+ else
167
+ widget = mounted;
168
+ })
169
+ .catch(reportError);
170
+ return {
171
+ reset() {
172
+ widget?.reset();
173
+ },
174
+ remove() {
175
+ aborter.abort();
176
+ stopWarning();
177
+ widget?.remove();
178
+ widget = undefined;
179
+ },
180
+ };
181
+ }
182
+ /** Load a provider's script once per page, carrying the page's CSP nonce. */
183
+ export function loadBotScript(src, options, runtimeWindow = window) {
184
+ const registry = registryFor(runtimeWindow);
185
+ const existing = registry.scripts.get(src);
186
+ if (existing)
187
+ return existing;
188
+ const host = runtimeWindow;
189
+ const { global, readyCallback } = options;
190
+ const loading = new Promise((resolve, reject) => {
191
+ const current = host[global];
192
+ if (current && (!readyCallback || typeof current.render === "function")) {
193
+ return resolve(current);
194
+ }
195
+ const finish = () => {
196
+ const api = host[global];
197
+ if (api)
198
+ resolve(api);
199
+ else
200
+ reject(new Error(`${src} loaded without defining window.${global}.`));
201
+ };
202
+ const { document } = runtimeWindow;
203
+ const script = document.createElement("script");
204
+ script.async = true;
205
+ script.dataset.farmBotScript = "";
206
+ // Carry the page's CSP nonce so a nonce-only policy still runs the provider script.
207
+ const nonce = document.querySelector("script[nonce]")?.nonce;
208
+ if (nonce)
209
+ script.nonce = nonce;
210
+ if (readyCallback) {
211
+ const callback = `__farmBotReady${registry.callbacks++}`;
212
+ host[callback] = () => {
213
+ delete host[callback];
214
+ finish();
215
+ };
216
+ script.src = `${src}${src.includes("?") ? "&" : "?"}onload=${callback}`;
217
+ }
218
+ else {
219
+ script.src = src;
220
+ script.addEventListener("load", finish, { once: true });
221
+ }
222
+ script.addEventListener("error", () => {
223
+ script.remove();
224
+ reject(new Error(`Couldn't load ${src}. Check the network, and that the page's CSP allows it.`));
225
+ }, { once: true });
226
+ document.head.append(script);
227
+ });
228
+ registry.scripts.set(src, loading);
229
+ // Let the next widget retry after a failed load.
230
+ loading.catch(() => {
231
+ if (registry.scripts.get(src) === loading)
232
+ registry.scripts.delete(src);
233
+ });
234
+ return loading;
235
+ }
package/dist/csp.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ type CspDirectiveValue = string | readonly string[] | boolean | null | undefined;
2
+ /** The shapes `security.csp` accepts, plus the resolved `{ value }` form. */
3
+ export type BotCspInput = string | false | undefined | {
4
+ policy?: string;
5
+ directives?: Readonly<Record<string, CspDirectiveValue>>;
6
+ value?: string;
7
+ [option: string]: unknown;
8
+ };
9
+ /**
10
+ * Add the widget's sources to an app's CSP, so turning on `security.csp` doesn't silently
11
+ * block the widget. Directives the policy leaves unrestricted stay unrestricted.
12
+ */
13
+ export declare function withBotCsp(csp: BotCspInput, sources: Readonly<Record<string, readonly string[]>>): BotCspInput;
14
+ export {};
15
+ //# sourceMappingURL=csp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"csp.d.ts","sourceRoot":"","sources":["../src/csp.ts"],"names":[],"mappings":"AAAA,KAAK,iBAAiB,GAAG,MAAM,GAAG,SAAS,MAAM,EAAE,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;AAEjF,6EAA6E;AAC7E,MAAM,MAAM,WAAW,GACnB,MAAM,GACN,KAAK,GACL,SAAS,GACT;IACE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;CAC3B,CAAC;AAqBN;;;GAGG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,WAAW,EAChB,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC,GACnD,WAAW,CASb"}
package/dist/csp.js ADDED
@@ -0,0 +1,99 @@
1
+ // A directive the policy leaves out falls back to these, in order (CSP Level 3).
2
+ const FALLBACKS = {
3
+ "frame-src": ["child-src", "default-src"],
4
+ "worker-src": ["child-src", "script-src", "default-src"],
5
+ "script-src-elem": ["script-src", "default-src"],
6
+ "script-src-attr": ["script-src", "default-src"],
7
+ "style-src-elem": ["style-src", "default-src"],
8
+ "style-src-attr": ["style-src", "default-src"],
9
+ };
10
+ function fallbacksFor(directive) {
11
+ return FALLBACKS[directive] ?? (directive.endsWith("-src") ? ["default-src"] : []);
12
+ }
13
+ /**
14
+ * Add the widget's sources to an app's CSP, so turning on `security.csp` doesn't silently
15
+ * block the widget. Directives the policy leaves unrestricted stay unrestricted.
16
+ */
17
+ export function withBotCsp(csp, sources) {
18
+ if (csp === undefined || csp === false)
19
+ return csp;
20
+ if (typeof csp === "string")
21
+ return mergePolicy(csp, sources);
22
+ if (typeof csp.policy === "string")
23
+ return { ...csp, policy: mergePolicy(csp.policy, sources) };
24
+ if (typeof csp.value === "string")
25
+ return { ...csp, value: mergePolicy(csp.value, sources) };
26
+ if (csp.directives && typeof csp.directives === "object") {
27
+ return { ...csp, directives: mergeDirectives(csp.directives, sources) };
28
+ }
29
+ return csp;
30
+ }
31
+ function addSources(access, sources) {
32
+ for (const [directive, needed] of Object.entries(sources)) {
33
+ const targets = [directive];
34
+ // `script-src-elem` and `style-src-elem` override the base directive for elements.
35
+ if (access.get(`${directive}-elem`) !== undefined)
36
+ targets.push(`${directive}-elem`);
37
+ for (const target of targets) {
38
+ let current = access.get(target);
39
+ if (current === undefined) {
40
+ for (const fallback of fallbacksFor(target)) {
41
+ current = access.get(fallback);
42
+ if (current !== undefined)
43
+ break;
44
+ }
45
+ // Nothing restricts this directive, so adding sources would only narrow it.
46
+ if (current === undefined)
47
+ continue;
48
+ }
49
+ if (current.includes("*"))
50
+ continue;
51
+ const next = current.filter((source) => source !== "'none'");
52
+ for (const source of needed) {
53
+ if (!next.includes(source))
54
+ next.push(source);
55
+ }
56
+ access.set(target, next);
57
+ }
58
+ }
59
+ }
60
+ function mergePolicy(policy, sources) {
61
+ const directives = new Map();
62
+ for (const part of policy.split(";")) {
63
+ const [name, ...values] = part.trim().split(/\s+/);
64
+ if (!name)
65
+ continue;
66
+ const key = name.toLowerCase();
67
+ // Browsers ignore a repeated directive, so the first one wins.
68
+ if (!directives.has(key))
69
+ directives.set(key, values);
70
+ }
71
+ addSources({
72
+ get: (name) => {
73
+ const value = directives.get(name);
74
+ return value ? [...value] : undefined;
75
+ },
76
+ set: (name, value) => directives.set(name, value),
77
+ }, sources);
78
+ return [...directives].map(([name, values]) => [name, ...values].join(" ")).join("; ");
79
+ }
80
+ function mergeDirectives(directives, sources) {
81
+ const next = { ...directives };
82
+ const normalize = (key) => key.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
83
+ const keyFor = (name) => Object.keys(next).find((key) => normalize(key) === name);
84
+ addSources({
85
+ get: (name) => {
86
+ const key = keyFor(name);
87
+ const value = key === undefined ? undefined : next[key];
88
+ if (typeof value === "string")
89
+ return value.split(/\s+/).filter(Boolean);
90
+ if (Array.isArray(value))
91
+ return [...value];
92
+ return undefined;
93
+ },
94
+ set: (name, value) => {
95
+ next[keyFor(name) ?? name] = value;
96
+ },
97
+ }, sources);
98
+ return next;
99
+ }
@@ -0,0 +1,10 @@
1
+ export type BotErrorCode = "invalid_provider" | "missing_site_key" | "missing_secret_key" | "test_key_in_production" | "invalid_secret_key" | "missing_request" | "missing_hostnames" | "missing_plugin";
2
+ /** A configuration problem the app owner has to fix. Visitor failures are returned, not thrown. */
3
+ export declare class BotError extends Error {
4
+ readonly name = "BotError";
5
+ readonly code: BotErrorCode;
6
+ constructor(code: BotErrorCode, message: string, options?: {
7
+ cause?: unknown;
8
+ });
9
+ }
10
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,YAAY,GACpB,kBAAkB,GAClB,kBAAkB,GAClB,oBAAoB,GACpB,wBAAwB,GACxB,oBAAoB,GACpB,iBAAiB,GACjB,mBAAmB,GACnB,gBAAgB,CAAC;AAErB,mGAAmG;AACnG,qBAAa,QAAS,SAAQ,KAAK;IACjC,SAAkB,IAAI,cAAc;IACpC,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;gBAEhB,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE;CAI/E"}
package/dist/errors.js ADDED
@@ -0,0 +1,9 @@
1
+ /** A configuration problem the app owner has to fix. Visitor failures are returned, not thrown. */
2
+ export class BotError extends Error {
3
+ name = "BotError";
4
+ code;
5
+ constructor(code, message, options) {
6
+ super(message, options);
7
+ this.code = code;
8
+ }
9
+ }
@@ -0,0 +1,28 @@
1
+ import type { FarmPlugin } from "@farm.js/core/plugin";
2
+ import { type BotClientState, type BotProvider } from "./provider.js";
3
+ import { type BotVerifier } from "./runtime.js";
4
+ export { BotError, type BotErrorCode } from "./errors.js";
5
+ export { createBotKeys, type BotKeys, type BotKeysConfig, type BotProviderKeys } from "./keys.js";
6
+ export { BOT_FAILURE_CODES, defineBotProvider, type BotClientState, type BotCspSources, type BotFailureCode, type BotProvider, type BotProviderClient, type BotVerdict, type BotVerdictFail, type BotVerdictPass, type BotVerifyInput, } from "./provider.js";
7
+ export type { BotCheckFailure, BotCheckResult, BotCheckSuccess, BotCheckVerifyOptions, } from "./verify.js";
8
+ export interface BotOptions<TData = unknown> {
9
+ /** The checker to use: one from `@farm.js/bot/captcha`, another package, or your own. */
10
+ provider: BotProvider<TData>;
11
+ /**
12
+ * Hostnames a check may come from. Required outside development, so `farm build` fails
13
+ * without it. In development it defaults to the hostname of the request being verified.
14
+ */
15
+ hostnames?: readonly string[];
16
+ /** How long to wait for the provider. Defaults to 5000. */
17
+ timeoutMs?: number;
18
+ }
19
+ export type BotPlugin<TData = unknown> = FarmPlugin<unknown, Record<string, unknown>, BotClientState | void, unknown> & {
20
+ /**
21
+ * Check a submission with this plugin. `verifyBot()` from `@farm.js/bot/server` does the same
22
+ * without needing the plugin in hand. Call this one for a typed `check.data`.
23
+ */
24
+ verify: BotVerifier<TData>;
25
+ };
26
+ /** Protect forms with a bot checker. Add it to `plugins` in farm.config.ts. */
27
+ export declare function bot<TData = unknown>(options: BotOptions<TData>): BotPlugin<TData>;
28
+ //# sourceM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C;AAEF,+EAA+E;AAC/E,wBAAgB,GAAG,CAAC,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,UAAU,CAAC,KAAK,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,CAyGjF"}
package/dist/index.js ADDED
@@ -0,0 +1,128 @@
1
+ import { withBotCsp } from "./csp.js";
2
+ import { BotError } from "./errors.js";
3
+ import { assertBotProvider, botClientIssues, } from "./provider.js";
4
+ import { setBotVerifier } from "./runtime.js";
5
+ import { missingHostnamesError, verifyBotCheck } from "./verify.js";
6
+ export { BotError } from "./errors.js";
7
+ export { createBotKeys } from "./keys.js";
8
+ export { BOT_FAILURE_CODES, defineBotProvider, } from "./provider.js";
9
+ const PLUGIN_NAME = "farm:bot";
10
+ const MAX_TIMEOUT_MS = 2_147_483_647;
11
+ const WIDGET_MODULE = "@farm.js/bot/provider-widget";
12
+ /** Point the plugin's fixed browser hook at the module this provider names. */
13
+ function widgetResolver(providerName, widget) {
14
+ return {
15
+ name: "farm:bot-widget",
16
+ enforce: "pre",
17
+ async resolveId(id, _importer, options) {
18
+ // Server bundles keep the package's empty module, so browser code never lands in them.
19
+ if (id !== WIDGET_MODULE || options.ssr)
20
+ return undefined;
21
+ const resolved = await this.resolve(widget, undefined, { ...options, skipSelf: true });
22
+ if (resolved)
23
+ return resolved;
24
+ throw new BotError("invalid_provider", `Bot provider "${providerName}" names the widget "${widget}", which can't be found. Use a package path the app can import, or a path from the app root such as "/src/acme.widget.ts".`);
25
+ },
26
+ };
27
+ }
28
+ function withVitePlugin(vite, plugin) {
29
+ const add = (config) => ({
30
+ ...config,
31
+ plugins: [plugin, ...(config?.plugins ?? [])],
32
+ });
33
+ return typeof vite === "function" ? (config) => add(vite(config)) : add(vite);
34
+ }
35
+ /** Protect forms with a bot checker. Add it to `plugins` in farm.config.ts. */
36
+ export function bot(options) {
37
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
38
+ throw new TypeError("bot() needs an options object with a `provider`. Use one from `@farm.js/bot/captcha`, or write your own with `defineBotProvider`.");
39
+ }
40
+ const { provider, hostnames, timeoutMs = 5000 } = options;
41
+ assertBotProvider(provider);
42
+ const issues = [];
43
+ if (hostnames !== undefined &&
44
+ (!Array.isArray(hostnames) ||
45
+ hostnames.length === 0 ||
46
+ hostnames.some((hostname) => typeof hostname !== "string" || !hostname.trim()))) {
47
+ issues.push("`hostnames` must be a non-empty array of hostnames.");
48
+ }
49
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMEOUT_MS) {
50
+ issues.push(`\`timeoutMs\` must be a whole number of milliseconds from 1 to ${MAX_TIMEOUT_MS}.`);
51
+ }
52
+ if (issues.length > 0) {
53
+ throw new TypeError(`bot() options are invalid. ${issues.join(" ")}`);
54
+ }
55
+ const verify = (input, verifyOptions) => verifyBotCheck({ provider, hostnames, timeoutMs }, input, verifyOptions);
56
+ // How `verifyBot()` reaches these options from a route, which can't import farm.config.ts.
57
+ setBotVerifier(verify);
58
+ // `farm start` loads the config too, without the build-only site key. Saving the error for
59
+ // `configure` lets the server start, while `farm dev` and `farm build` still report it.
60
+ let client;
61
+ let clientError;
62
+ try {
63
+ client = provider.client?.();
64
+ const clientProblems = provider.client ? botClientIssues(client) : [];
65
+ if (clientProblems.length > 0) {
66
+ client = undefined;
67
+ throw new BotError("invalid_provider", `Bot provider "${provider.name}" is invalid. ${clientProblems.join(" ")}`);
68
+ }
69
+ }
70
+ catch (error) {
71
+ clientError = error;
72
+ }
73
+ const start = client && {
74
+ widget: client.widget,
75
+ ...(provider.tokenField === undefined ? {} : { tokenField: provider.tokenField }),
76
+ ...(client.public === undefined ? {} : { config: client.public }),
77
+ };
78
+ // A plain object: `definePlugin` would pull Farm's build tooling into the server bundle, and it
79
+ // adds nothing for a plugin with no options schema.
80
+ return {
81
+ name: PLUGIN_NAME,
82
+ verify,
83
+ // Empty on purpose. Having it makes the server load farm.config.ts, so `bot()` runs there.
84
+ // `setup`, `close`, or a request hook would send every prerendered page through the server.
85
+ runtime: {},
86
+ configure(appConfig, context) {
87
+ if (clientError)
88
+ throw clientError;
89
+ if (hostnames === undefined && context?.isProd)
90
+ throw missingHostnamesError();
91
+ const instances = (appConfig.plugins ?? []).filter((candidate) => candidate?.name === PLUGIN_NAME);
92
+ if (instances.length > 1) {
93
+ throw new Error(`[${PLUGIN_NAME}] Add the bot plugin once.`);
94
+ }
95
+ const csp = appConfig.security?.csp;
96
+ const addsCsp = csp !== undefined && csp !== false && provider.csp !== undefined;
97
+ if (!client && !addsCsp)
98
+ return;
99
+ return {
100
+ ...appConfig,
101
+ ...(client
102
+ ? { vite: withVitePlugin(appConfig.vite, widgetResolver(provider.name, client.widget)) }
103
+ : {}),
104
+ ...(addsCsp
105
+ ? { security: { ...appConfig.security, csp: withBotCsp(csp, provider.csp) } }
106
+ : {}),
107
+ };
108
+ },
109
+ ...(start
110
+ ? {
111
+ client: {
112
+ public: start,
113
+ // Farm compiles this from its source text, so it uses only its argument.
114
+ async setup({ public: settings }) {
115
+ const [runtime, widget] = await Promise.all([
116
+ import("@farm.js/bot/client"),
117
+ import("@farm.js/bot/provider-widget"),
118
+ ]);
119
+ return runtime.startBotWidget(widget.default, settings);
120
+ },
121
+ close({ state }) {
122
+ state?.close();
123
+ },
124
+ },
125
+ }
126
+ : {}),
127
+ };
128
+ }
package/dist/keys.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ /** What an app can pass to a provider. Every provider built on `createBotKeys` takes these. */
2
+ export interface BotProviderKeys {
3
+ /** The public site key. Read from the environment at build time when omitted. */
4
+ siteKey?: string;
5
+ /** The server-only secret. Read from the environment on every check when omitted. */
6
+ secretKey?: string;
7
+ /**
8
+ * Fall back to the provider's always-passing test keys when a key is missing, and accept
9
+ * checks made with them. Defaults to `true` when `NODE_ENV` is `development` or `test`. A
10
+ * server in any other environment refuses test keys, so a missing key fails instead.
11
+ */
12
+ testKeys?: boolean;
13
+ }
14
+ export interface BotKeysConfig {
15
+ /** The provider's name, as the app calls it: `acme` for `acme()`. Used in error messages. */
16
+ name: string;
17
+ /** The environment variable holding the site key. */
18
+ siteKeyEnv?: string;
19
+ /** The environment variable holding the secret key. */
20
+ secretKeyEnv?: string;
21
+ /** Always-passing keys the provider publishes. Without them, development needs real keys. */
22
+ testKeys?: {
23
+ siteKey: string;
24
+ secretKey: string;
25
+ /** Defaults to an exact match on `secretKey`. */
26
+ isTestSecret?: (secret: string) => boolean;
27
+ };
28
+ }
29
+ export interface BotKeys {
30
+ /** The key for the browser. Call it from `client()`. Throws a `BotError` when it's missing. */
31
+ siteKey(): string;
32
+ /** The secret. Call it from `verify`, so it's read on the server that runs the check. */
33
+ secretKey(): {
34
+ value: string;
35
+ isTest: boolean;
36
+ };
37
+ }
38
+ export declare function isDevelopment(): boolean;
39
+ /**
40
+ * Read a provider's keys the way the built-in providers do: from the app's options or the
41
+ * environment, including Cloudflare bindings, and never accepting a test key in production.
42
+ */
43
+ export declare function createBotKeys(config: BotKeysConfig, keys?: BotProviderKeys): BotKeys;
44
+ //# sourceMappingURL=keys.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../src/keys.ts"],"names":[],"mappings":"AAGA,+FAA+F;AAC/F,MAAM,WAAW,eAAe;IAC9B,iFAAiF;IACjF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qFAAqF;IACrF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,aAAa;IAC5B,6FAA6F;IAC7F,IAAI,EAAE,MAAM,CAAC;IACb,qDAAqD;IACrD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,uDAAuD;IACvD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,6FAA6F;IAC7F,QAAQ,CAAC,EAAE;QACT,OAAO,EAAE,MAAM,CAAC;QAChB,SAAS,EAAE,MAAM,CAAC;QAClB,iDAAiD;QACjD,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC;KAC5C,CAAC;CACH;AAED,MAAM,WAAW,OAAO;IACtB,+FAA+F;IAC/F,OAAO,IAAI,MAAM,CAAC;IAClB,yFAAyF;IACzF,SAAS,IAAI;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC;CACjD;AAaD,wBAAgB,aAAa,IAAI,OAAO,CAIvC;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,eAAoB,GAAG,OAAO,CAsDxF"}