@boldare/askdare 0.4.0 → 0.5.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.
- package/CHANGELOG.md +54 -0
- package/README.md +14 -4
- package/dist/cli.js +19 -6
- package/dist/define-tool.js +677 -7
- package/dist/embed.d.ts +1 -1
- package/dist/embed.js +2 -1
- package/dist/{store.d.ts → events.d.ts} +127 -52
- package/dist/index.d.ts +28 -2
- package/dist/index.js +82 -1
- package/dist/next.d.ts +22 -11
- package/dist/next.js +537 -139
- package/dist/react-marked.js +883 -810
- package/dist/react.d.ts +24 -4
- package/dist/react.js +126 -18
- package/dist/root.js +170 -38
- package/dist/tool-results.d.ts +11 -1
- package/dist/ui/askdare.css +9 -1
- package/dist/ui/avatar.tsx +1 -1
- package/dist/ui/chat.tsx +1 -1
- package/dist/ui/confirm.tsx +1 -1
- package/dist/ui/context.ts +1 -1
- package/dist/ui/feedback.tsx +1 -1
- package/dist/ui/footer.tsx +3 -15
- package/dist/ui/header.tsx +1 -1
- package/dist/ui/icons.tsx +1 -1
- package/dist/ui/index.ts +1 -1
- package/dist/ui/message.tsx +1 -1
- package/dist/ui/panel.tsx +3 -1
- package/dist/ui/welcome.tsx +1 -1
- package/docs/accessibility.md +83 -0
- package/docs/cli.md +4 -3
- package/docs/compliance.md +160 -0
- package/docs/configuration.md +47 -2
- package/docs/costs.md +8 -1
- package/docs/custom-store.md +2 -0
- package/docs/embedding.md +2 -0
- package/docs/feedback.md +1 -1
- package/docs/going-public.md +15 -3
- package/docs/guardrails.md +128 -0
- package/docs/migrating-from-openai-assistant.md +1 -1
- package/docs/privacy.md +26 -2
- package/docs/react.md +7 -1
- package/docs/styling.md +2 -2
- package/docs/support.md +3 -3
- package/docs/texts.md +100 -96
- package/docs/troubleshooting.md +30 -3
- package/llms.txt +12 -9
- package/package.json +4 -4
- package/skills/askdare/SKILL.md +9 -2
package/dist/embed.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
2
|
+
import { f as EmbedChatConfig, i as ToolRenderers } from "./tool-results.js";
|
|
3
3
|
import { ReactElement, ReactNode } from "react";
|
|
4
4
|
interface EmbedRootProps {
|
|
5
5
|
/** From `getEmbedConfig()` in the page's Server Component. */
|
package/dist/embed.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
import {
|
|
2
|
+
import { _ as ChatProvider, c as pageLocale, d as noteMissingDisclosure, i as ToolRenderersProvider, l as pageOptions, n as checkConfig, o as createChatStore, s as identityToken, v as FrameContext } from "./root.js";
|
|
3
3
|
import { useEffect, useMemo, useState } from "react";
|
|
4
4
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
5
5
|
// src/chat/bind-bridge.ts
|
|
@@ -215,6 +215,7 @@ function EmbedRoot({ config, toolRenderers, children }) {
|
|
|
215
215
|
const connection = bridge;
|
|
216
216
|
const unbind = bindBridge(store, connection);
|
|
217
217
|
const stopLocale = followLocale(store, connection, unbind);
|
|
218
|
+
if (process.env.NODE_ENV !== "production") noteMissingDisclosure(store);
|
|
218
219
|
if (connection.embedded && !inline) {
|
|
219
220
|
setClose(() => () => {
|
|
220
221
|
store.hide();
|
|
@@ -53,6 +53,8 @@ declare const EN: {
|
|
|
53
53
|
readonly "launcher.open": "Open chat";
|
|
54
54
|
readonly "launcher.close": "Close chat";
|
|
55
55
|
readonly "launcher.unavailable": "The chat couldn’t load. Please try again later.";
|
|
56
|
+
readonly "humanCheck.label": "Checking that you’re human";
|
|
57
|
+
readonly "error.humanCheck": "We couldn’t confirm you’re human. Please try again.";
|
|
56
58
|
readonly "error.connection": "Connection problem. Please try again.";
|
|
57
59
|
readonly "error.history": "Could not load the previous conversation.";
|
|
58
60
|
readonly "error.updated": "The assistant was updated. Please reload the page.";
|
|
@@ -91,6 +93,38 @@ declare const EN: {
|
|
|
91
93
|
declare const PLURAL_BASES: readonly ["message.attachments"];
|
|
92
94
|
declare const PLURAL_FORMS: readonly ["zero", "one", "two", "few", "many", "other"];
|
|
93
95
|
type TextKey = keyof typeof EN | `${(typeof PLURAL_BASES)[number]}.${(typeof PLURAL_FORMS)[number]}`;
|
|
96
|
+
/**
|
|
97
|
+
* The challenge the chat shows before a new session starts. Public: it is sent to browsers, so it
|
|
98
|
+
* holds the site key and never the secret.
|
|
99
|
+
*/
|
|
100
|
+
interface HumanChallenge {
|
|
101
|
+
/** Which widget the chat renders. Cloudflare Turnstile is the only one in 0.5. */
|
|
102
|
+
readonly provider: "turnstile";
|
|
103
|
+
/** The widget's public site key. */
|
|
104
|
+
readonly siteKey: string;
|
|
105
|
+
}
|
|
106
|
+
/** What a verifier gets with each token. */
|
|
107
|
+
interface HumanCheckContext {
|
|
108
|
+
/** The bot the session is for. */
|
|
109
|
+
readonly botId: string;
|
|
110
|
+
/** Aborts when the check takes too long or the visitor goes away; pass it to `fetch`. */
|
|
111
|
+
readonly signal: AbortSignal;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Checks that a new session comes from a person (ADR-0004, ADR-0019). The chat renders
|
|
115
|
+
* `challenge`, and `/session` passes the token it got to `verify`. Renewals of a live session
|
|
116
|
+
* aren't checked again. Build one with `turnstile()`, or implement it to check the token some
|
|
117
|
+
* other way.
|
|
118
|
+
*/
|
|
119
|
+
interface HumanVerifier {
|
|
120
|
+
readonly challenge: HumanChallenge;
|
|
121
|
+
/**
|
|
122
|
+
* Resolves true when the token proves a person, false when it doesn't (invalid, expired or
|
|
123
|
+
* already used): the visitor is asked to try again. Throw when the check itself can't run, such
|
|
124
|
+
* as a missing secret or an outage: the session is refused and `onError` hears about it.
|
|
125
|
+
*/
|
|
126
|
+
verify(token: string, context: HumanCheckContext): Promise<boolean>;
|
|
127
|
+
}
|
|
94
128
|
/** A signed-in user, as the site's backend vouched for it (ADR-0009). */
|
|
95
129
|
interface VisitorIdentity {
|
|
96
130
|
/** The site's own user ID: the JWT's `sub`. */
|
|
@@ -159,13 +193,6 @@ interface ThemeDefinition {
|
|
|
159
193
|
readonly dark?: Partial<ThemeTokens>;
|
|
160
194
|
readonly variants?: Partial<ThemeVariants>;
|
|
161
195
|
}
|
|
162
|
-
interface ResolvedTheme {
|
|
163
|
-
readonly preset: PresetName;
|
|
164
|
-
readonly colorScheme: ColorScheme;
|
|
165
|
-
readonly light: ThemeTokens;
|
|
166
|
-
readonly dark: ThemeTokens;
|
|
167
|
-
readonly variants: ThemeVariants;
|
|
168
|
-
}
|
|
169
196
|
/** Validates a theme once, so several bots can share it. Throws on invalid values. */
|
|
170
197
|
declare function defineTheme(definition: ThemeDefinition): ThemeDefinition;
|
|
171
198
|
/** What a tool may know about the request. Identity here is verified, never chosen by the model. */
|
|
@@ -240,6 +267,77 @@ interface Tool<Name extends string = string, Ui = unknown> {
|
|
|
240
267
|
* before `execute` runs; failures are reported to the model, never to the visitor.
|
|
241
268
|
*/
|
|
242
269
|
declare function defineTool<Input extends z.ZodObject, Output = unknown, Ui = never, const Name extends string = string>(definition: ToolDefinition<Input, Output, Ui, Name>): Tool<Name, Ui>;
|
|
270
|
+
/**
|
|
271
|
+
* OpenAI moderation for a bot's messages (ADR-0019). Each checked message costs one call to the
|
|
272
|
+
* moderation endpoint before the turn goes on (docs/costs.md).
|
|
273
|
+
*/
|
|
274
|
+
interface ModerationConfig {
|
|
275
|
+
/**
|
|
276
|
+
* OpenAI moderation model, for example `omni-moderation-latest`. Required: the library never
|
|
277
|
+
* assumes a model.
|
|
278
|
+
*/
|
|
279
|
+
readonly model: string;
|
|
280
|
+
/**
|
|
281
|
+
* What is checked: the visitor's message before it reaches the model, the finished answer
|
|
282
|
+
* before the visitor sees it, or both. Checking output holds each answer back until it is
|
|
283
|
+
* complete (docs/guardrails.md). Default `input`.
|
|
284
|
+
*/
|
|
285
|
+
readonly check?: "input" | "output" | "both";
|
|
286
|
+
/**
|
|
287
|
+
* Moderation categories that block, such as `harassment` or `self-harm/intent`. Default: any
|
|
288
|
+
* category the model flags.
|
|
289
|
+
*/
|
|
290
|
+
readonly categories?: readonly string[];
|
|
291
|
+
/** What the visitor sees when moderation blocks a message. Default: the `error.content_blocked` text. */
|
|
292
|
+
readonly message?: string;
|
|
293
|
+
}
|
|
294
|
+
/** Who and what a guardrail hook is checking, besides the text itself. */
|
|
295
|
+
interface GuardContext {
|
|
296
|
+
/** The bot's `id`. */
|
|
297
|
+
readonly bot: string;
|
|
298
|
+
/** Validated BCP 47 tag chosen by the widget. */
|
|
299
|
+
readonly locale: string;
|
|
300
|
+
/** The signed-in user, verified with IDENTITY_SECRET (ADR-0009); undefined when anonymous. */
|
|
301
|
+
readonly identity?: VisitorIdentity | undefined;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* What an `onInput` or `onOutput` hook decides: let the text through, block the turn (with an
|
|
305
|
+
* optional text for the visitor, at most 300 characters), or replace the text. Returning
|
|
306
|
+
* `undefined` lets it through.
|
|
307
|
+
*/
|
|
308
|
+
type GuardVerdict = {
|
|
309
|
+
readonly action: "allow";
|
|
310
|
+
} | {
|
|
311
|
+
readonly action: "block";
|
|
312
|
+
readonly message?: string;
|
|
313
|
+
} | {
|
|
314
|
+
readonly action: "redact";
|
|
315
|
+
readonly text: string;
|
|
316
|
+
};
|
|
317
|
+
/** An `onInput` or `onOutput` hook. Runs on the server; whatever it throws lets the text through. */
|
|
318
|
+
type GuardHook = (text: string, context: GuardContext) => GuardVerdict | undefined | Promise<GuardVerdict | undefined>;
|
|
319
|
+
/** The guardrail options of `defineBot` (ADR-0019). Every one is off when absent. */
|
|
320
|
+
interface GuardrailOptions {
|
|
321
|
+
/** OpenAI moderation on input, output or both. Off when absent. */
|
|
322
|
+
readonly moderation?: ModerationConfig | undefined;
|
|
323
|
+
/**
|
|
324
|
+
* Your own rule for each visitor message, before it reaches the model (and before moderation):
|
|
325
|
+
* allow it, block the turn, or replace the text the model gets. Files and the page's
|
|
326
|
+
* description are not passed to it.
|
|
327
|
+
*/
|
|
328
|
+
readonly onInput?: GuardHook | undefined;
|
|
329
|
+
/**
|
|
330
|
+
* Your own rule for each finished answer, before the visitor sees it (and before moderation).
|
|
331
|
+
* Setting it holds every answer back until it is complete (docs/guardrails.md).
|
|
332
|
+
*/
|
|
333
|
+
readonly onOutput?: GuardHook | undefined;
|
|
334
|
+
/**
|
|
335
|
+
* `untrusted` hands your tools' results to the model wrapped as third-party data that it must
|
|
336
|
+
* not follow as instructions (prompt-injection hardening, ADR-0004). Recommended for tools that
|
|
337
|
+
* return text from outside your control. Default `trusted`: results go to the model as they are.
|
|
338
|
+
*/
|
|
339
|
+
readonly toolResults?: "trusted" | "untrusted" | undefined;
|
|
340
|
+
}
|
|
243
341
|
/** Per-request context available when building instructions. */
|
|
244
342
|
interface BotContext {
|
|
245
343
|
/** Validated BCP 47 tag chosen by the widget. */
|
|
@@ -289,6 +387,12 @@ interface BotSecurity {
|
|
|
289
387
|
* always allowed. Enforced by the browser through `frame-ancestors` (ADR-0004, ADR-0005).
|
|
290
388
|
*/
|
|
291
389
|
readonly allowedOrigins?: readonly string[];
|
|
390
|
+
/**
|
|
391
|
+
* Asks for a human check before a new session starts, such as `turnstile({ siteKey })`
|
|
392
|
+
* (ADR-0019). The chat shows the challenge, and the iframe's CSP allows its provider. Renewals
|
|
393
|
+
* of a live session aren't checked again. Off when absent.
|
|
394
|
+
*/
|
|
395
|
+
readonly humanVerifier?: HumanVerifier | undefined;
|
|
292
396
|
}
|
|
293
397
|
interface KnowledgeConfig {
|
|
294
398
|
/** Vector store filled by `askdare kb sync`, usually `process.env.KB_VECTOR_STORE_ID`. */
|
|
@@ -377,36 +481,8 @@ interface WidgetConfig {
|
|
|
377
481
|
/** Default `auto`: follows the visitor's system setting. */
|
|
378
482
|
readonly colorScheme?: ColorScheme;
|
|
379
483
|
}
|
|
380
|
-
/**
|
|
381
|
-
interface
|
|
382
|
-
/** In the configured locale (English for `auto`); the visitor may see another language. */
|
|
383
|
-
readonly title: string;
|
|
384
|
-
readonly subtitle: string;
|
|
385
|
-
readonly greeting: string;
|
|
386
|
-
readonly placeholder: string;
|
|
387
|
-
/** The configured BCP 47 tag, or `auto`. */
|
|
388
|
-
readonly locale: string;
|
|
389
|
-
readonly starters: readonly string[];
|
|
390
|
-
/** Whether this bot lets visitors rate answers, when the handler has `onFeedback`. */
|
|
391
|
-
readonly feedback: boolean;
|
|
392
|
-
/** Whether the model suggests reply options. Only the server reads it. */
|
|
393
|
-
readonly replies: "suggest" | "off";
|
|
394
|
-
readonly avatar: string | undefined;
|
|
395
|
-
readonly launcherLabel: string;
|
|
396
|
-
/**
|
|
397
|
-
* Text overrides for every language, including the title, greeting, placeholder and launcher
|
|
398
|
-
* label shortcuts.
|
|
399
|
-
*/
|
|
400
|
-
readonly texts: WidgetTexts;
|
|
401
|
-
/** Text overrides per language, by canonical BCP 47 tag; they win over `texts`. */
|
|
402
|
-
readonly textsByLocale: Readonly<Record<string, WidgetTexts>>;
|
|
403
|
-
readonly disclosure: false | {
|
|
404
|
-
readonly privacyUrl: string | undefined;
|
|
405
|
-
};
|
|
406
|
-
readonly css: string;
|
|
407
|
-
readonly theme: ResolvedTheme;
|
|
408
|
-
}
|
|
409
|
-
interface BotDefinition {
|
|
484
|
+
/** A bot's settings; the guardrail options (`moderation`, `onInput`, …) are in `GuardrailOptions`. */
|
|
485
|
+
interface BotDefinition extends GuardrailOptions {
|
|
410
486
|
/** URL-safe identifier used in the script tag (`widget.js?bot=<id>`) and routes. */
|
|
411
487
|
readonly id: string;
|
|
412
488
|
/** OpenAI model ID. Required on purpose: the library never assumes a model (ADR-0002). */
|
|
@@ -443,27 +519,21 @@ interface BotDefinition {
|
|
|
443
519
|
*/
|
|
444
520
|
readonly embedPath?: string | undefined;
|
|
445
521
|
}
|
|
446
|
-
|
|
522
|
+
/**
|
|
523
|
+
* What `defineBot` returns. Pass it to `createChatHandler`, `getChatConfig` and `getEmbedConfig`;
|
|
524
|
+
* the settings it resolved are internal (ADR-0020).
|
|
525
|
+
*/
|
|
526
|
+
interface BotHandle {
|
|
527
|
+
/** The bot's `id` from its definition. */
|
|
447
528
|
readonly id: string;
|
|
448
|
-
|
|
449
|
-
readonly instructions: (context: BotContext) => string;
|
|
450
|
-
readonly limits: Required<BotLimits>;
|
|
451
|
-
readonly tools: readonly Tool[];
|
|
452
|
-
readonly pageContext: boolean;
|
|
453
|
-
readonly knowledge: Required<KnowledgeConfig> | undefined;
|
|
454
|
-
readonly attachments: Required<AttachmentConfig> | undefined;
|
|
455
|
-
readonly voice: Required<VoiceConfig> | undefined;
|
|
456
|
-
readonly security: {
|
|
457
|
-
readonly allowedOrigins: readonly string[];
|
|
458
|
-
};
|
|
459
|
-
readonly widget: BotWidget;
|
|
529
|
+
/** The bot's `embedPath` from its definition, for matching its page in `proxy.ts` (ADR-0018). */
|
|
460
530
|
readonly embedPath: string | undefined;
|
|
461
531
|
}
|
|
462
532
|
/**
|
|
463
533
|
* Declares a chatbot. Validates eagerly so misconfiguration fails at startup, not on the first
|
|
464
534
|
* visitor's message.
|
|
465
535
|
*/
|
|
466
|
-
declare function defineBot(definition: BotDefinition):
|
|
536
|
+
declare function defineBot(definition: BotDefinition): BotHandle;
|
|
467
537
|
/** Result of incrementing a fixed-window counter. */
|
|
468
538
|
interface CounterHit {
|
|
469
539
|
/** Counter value after the increment. */
|
|
@@ -485,4 +555,9 @@ interface RateLimitStore {
|
|
|
485
555
|
/** True for stores that are shared across server instances. */
|
|
486
556
|
readonly shared: boolean;
|
|
487
557
|
}
|
|
488
|
-
|
|
558
|
+
/** Stable error codes sent to clients. The accompanying message never contains internals. */
|
|
559
|
+
declare const ERROR_CODES: readonly ["invalid_input", "unauthorized", "session_expired", "not_found", "rate_limited", "budget_exceeded", "bot_unavailable", "content_blocked", "timeout", "upstream_error", "internal_error"];
|
|
560
|
+
type ErrorCode = (typeof ERROR_CODES)[number];
|
|
561
|
+
declare const MESSAGE_END_REASONS: readonly ["completed", "max_steps", "max_output_tokens", "timeout", "content_filter", "aborted"];
|
|
562
|
+
type MessageEndReason = (typeof MESSAGE_END_REASONS)[number];
|
|
563
|
+
export { ThemeVariants as A, ToolDefinition as C, defineTheme as D, ThemeDefinition as E, HumanChallenge as M, HumanCheckContext as N, PresetName as O, HumanVerifier as P, ToolContext as S, ColorScheme as T, GuardHook as _, RateLimitStore as a, ModerationConfig as b, BotDefinition as c, BotSecurity as d, KnowledgeConfig as f, GuardContext as g, defineBot as h, CounterHit as i, VisitorIdentity as j, ThemeTokens as k, BotHandle as l, WidgetConfig as m, ErrorCode as n, AttachmentConfig as o, VoiceConfig as p, MessageEndReason as r, BotContext as s, ERROR_CODES as t, BotLimits as u, GuardVerdict as v, defineTool as w, Tool as x, GuardrailOptions as y };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,33 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { A as ThemeVariants, C as ToolDefinition, D as defineTheme, E as ThemeDefinition, M as HumanChallenge, N as HumanCheckContext, O as PresetName, P as HumanVerifier, S as ToolContext, T as ColorScheme, _ as GuardHook, a as RateLimitStore, b as ModerationConfig, c as BotDefinition, d as BotSecurity, f as KnowledgeConfig, g as GuardContext, h as defineBot, i as CounterHit, j as VisitorIdentity, k as ThemeTokens, l as BotHandle, m as WidgetConfig, n as ErrorCode, o as AttachmentConfig, p as VoiceConfig, s as BotContext, t as ERROR_CODES, u as BotLimits, v as GuardVerdict, w as defineTool, x as Tool, y as GuardrailOptions } from "./events.js";
|
|
2
2
|
/**
|
|
3
3
|
* Version of the SSE wire protocol between the askdare server and its clients.
|
|
4
4
|
* Bumped on any breaking change to event names or payloads (ADR-0006).
|
|
5
5
|
*/
|
|
6
6
|
export declare const PROTOCOL_VERSION: 1;
|
|
7
|
-
|
|
7
|
+
interface TurnstileOptions {
|
|
8
|
+
/** The widget's site key from the Cloudflare dashboard. Public: browsers receive it. */
|
|
9
|
+
readonly siteKey: string;
|
|
10
|
+
/**
|
|
11
|
+
* The widget's secret key. Default `process.env.TURNSTILE_SECRET_KEY`, read at the first check,
|
|
12
|
+
* so building the app never needs it.
|
|
13
|
+
*/
|
|
14
|
+
readonly secretKey?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Host names the challenge may have been solved on, compared with siteverify's `hostname`, such
|
|
17
|
+
* as `['www.example.com']`: the host of your chat route's app. Off by default, because the
|
|
18
|
+
* dashboard's hostname list already limits where the widget runs, and a proxy that serves the
|
|
19
|
+
* app under another name would be refused. Skipped with Cloudflare's test secret keys.
|
|
20
|
+
*/
|
|
21
|
+
readonly hostnames?: readonly string[];
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A `HumanVerifier` backed by Cloudflare Turnstile: the chat shows the Turnstile widget before a
|
|
25
|
+
* new session starts, and the server checks its token with Cloudflare's siteverify endpoint.
|
|
26
|
+
*
|
|
27
|
+
* ```ts
|
|
28
|
+
* // The site key is public; the secret key comes from TURNSTILE_SECRET_KEY.
|
|
29
|
+
* security: { humanVerifier: turnstile({ siteKey: '0x4AAAAAAA…' }) }
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare function turnstile(options: TurnstileOptions): HumanVerifier;
|
|
33
|
+
export { type AttachmentConfig, type BotContext, type BotDefinition, type BotHandle, type BotLimits, type BotSecurity, type ColorScheme, type CounterHit, ERROR_CODES, type ErrorCode, type GuardContext, type GuardHook, type GuardVerdict, type GuardrailOptions, type HumanChallenge, type HumanCheckContext, type HumanVerifier, type KnowledgeConfig, type ModerationConfig, type PresetName, type RateLimitStore, type ThemeDefinition, type ThemeTokens, type ThemeVariants, type Tool, type ToolContext, type ToolDefinition, type TurnstileOptions, type VisitorIdentity, type VoiceConfig, type WidgetConfig, defineBot, defineTheme, defineTool };
|
package/dist/index.js
CHANGED
|
@@ -1 +1,82 @@
|
|
|
1
|
-
|
|
1
|
+
import { P as defineTheme, S as defineBot, d as AskdareError, l as TURNSTILE_ORIGIN, n as defineTool, u as turnstileAction, v as PROTOCOL_VERSION, y as ERROR_CODES } from "./define-tool.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
// src/security/turnstile.ts
|
|
4
|
+
const SITEVERIFY = `${TURNSTILE_ORIGIN}/turnstile/v0/siteverify`;
|
|
5
|
+
const SITE_KEY = /^[A-Za-z0-9_-]{1,100}$/;
|
|
6
|
+
/** The fields of Cloudflare's siteverify response that the decision needs. */
|
|
7
|
+
const siteverifyResponse = z.object({
|
|
8
|
+
success: z.boolean(),
|
|
9
|
+
"error-codes": z.array(z.string()).optional(),
|
|
10
|
+
hostname: z.string().optional(),
|
|
11
|
+
action: z.string().optional()
|
|
12
|
+
});
|
|
13
|
+
/**
|
|
14
|
+
* Cloudflare's published test secret keys: they answer for a dummy token, always with the
|
|
15
|
+
* hostname example.com and without an action, so those two checks can't apply.
|
|
16
|
+
*/
|
|
17
|
+
const TEST_SECRETS = /* @__PURE__ */ new Set([
|
|
18
|
+
"1x0000000000000000000000000000000AA",
|
|
19
|
+
"2x0000000000000000000000000000000AA",
|
|
20
|
+
"3x0000000000000000000000000000000AA"
|
|
21
|
+
]);
|
|
22
|
+
/** Codes that mean the operator's setup is wrong, not the visitor's token. */
|
|
23
|
+
const SETUP_ERRORS = /* @__PURE__ */ new Set(["missing-input-secret", "invalid-input-secret"]);
|
|
24
|
+
const processEnv = (name) => globalThis.process?.env?.[name];
|
|
25
|
+
/**
|
|
26
|
+
* A `HumanVerifier` backed by Cloudflare Turnstile: the chat shows the Turnstile widget before a
|
|
27
|
+
* new session starts, and the server checks its token with Cloudflare's siteverify endpoint.
|
|
28
|
+
*
|
|
29
|
+
* ```ts
|
|
30
|
+
* // The site key is public; the secret key comes from TURNSTILE_SECRET_KEY.
|
|
31
|
+
* security: { humanVerifier: turnstile({ siteKey: '0x4AAAAAAA…' }) }
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
function turnstile(options) {
|
|
35
|
+
const siteKey = typeof options.siteKey === "string" ? options.siteKey.trim() : "";
|
|
36
|
+
if (!SITE_KEY.test(siteKey)) throw new TypeError("[askdare] turnstile() needs the siteKey of a Turnstile widget (letters, digits, - and _).");
|
|
37
|
+
const hostnames = options.hostnames?.map((host) => host.trim().toLowerCase());
|
|
38
|
+
return Object.freeze({
|
|
39
|
+
challenge: Object.freeze({
|
|
40
|
+
provider: "turnstile",
|
|
41
|
+
siteKey
|
|
42
|
+
}),
|
|
43
|
+
verify: async (token, context) => {
|
|
44
|
+
const secret = options.secretKey ?? processEnv("TURNSTILE_SECRET_KEY");
|
|
45
|
+
if (!secret) throw new AskdareError("bot_unavailable", { cause: "TURNSTILE_SECRET_KEY is not configured." });
|
|
46
|
+
if (token.length === 0 || token.length > 2048) return false;
|
|
47
|
+
let response;
|
|
48
|
+
try {
|
|
49
|
+
response = await fetch(SITEVERIFY, {
|
|
50
|
+
method: "POST",
|
|
51
|
+
headers: { "content-type": "application/json" },
|
|
52
|
+
body: JSON.stringify({
|
|
53
|
+
secret,
|
|
54
|
+
response: token
|
|
55
|
+
}),
|
|
56
|
+
signal: context.signal
|
|
57
|
+
});
|
|
58
|
+
} catch (error) {
|
|
59
|
+
throw new AskdareError(context.signal.aborted ? "timeout" : "upstream_error", { cause: new Error("Cloudflare Turnstile siteverify could not be reached.", { cause: error }) });
|
|
60
|
+
}
|
|
61
|
+
let body;
|
|
62
|
+
try {
|
|
63
|
+
body = await response.json();
|
|
64
|
+
} catch {
|
|
65
|
+
body = void 0;
|
|
66
|
+
}
|
|
67
|
+
const parsed = siteverifyResponse.safeParse(body);
|
|
68
|
+
if (!parsed.success) throw new AskdareError("upstream_error", { cause: `Cloudflare Turnstile siteverify answered ${response.status} without a result.` });
|
|
69
|
+
if (parsed.data.success) {
|
|
70
|
+
if (TEST_SECRETS.has(secret)) return true;
|
|
71
|
+
if (parsed.data.action !== turnstileAction(context.botId)) return false;
|
|
72
|
+
const hostname = parsed.data.hostname?.toLowerCase();
|
|
73
|
+
return hostnames === void 0 || hostname !== void 0 && hostnames.includes(hostname);
|
|
74
|
+
}
|
|
75
|
+
const codes = parsed.data["error-codes"] ?? [];
|
|
76
|
+
if (codes.some((code) => SETUP_ERRORS.has(code))) throw new AskdareError("bot_unavailable", { cause: `Cloudflare rejected the Turnstile secret key (${codes.join(", ")}). Check TURNSTILE_SECRET_KEY.` });
|
|
77
|
+
if (codes.includes("internal-error")) throw new AskdareError("upstream_error", { cause: "Cloudflare Turnstile siteverify reported an internal error." });
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
export { ERROR_CODES, PROTOCOL_VERSION, defineBot, defineTheme, defineTool, turnstile };
|
package/dist/next.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as ThemeVariants, O as PresetName, a as RateLimitStore, j as VisitorIdentity, l as BotHandle, n as ErrorCode, r as MessageEndReason } from "./events.js";
|
|
2
2
|
/** What a visitor may attach, as the bot allows it. */
|
|
3
3
|
interface ChatAttachments {
|
|
4
4
|
readonly images: boolean;
|
|
@@ -56,6 +56,16 @@ interface ChatConfig {
|
|
|
56
56
|
};
|
|
57
57
|
/** From `getChatConfig`, for a chat inside a page. The iframe links its own stylesheets. */
|
|
58
58
|
readonly styles?: ChatStyles;
|
|
59
|
+
/**
|
|
60
|
+
* Absent unless the bot has `security.humanVerifier`: the challenge the chat shows before a new
|
|
61
|
+
* session starts, rendered by `HumanCheck`.
|
|
62
|
+
*/
|
|
63
|
+
readonly humanCheck?: ChatHumanCheck;
|
|
64
|
+
}
|
|
65
|
+
/** A human check the chat must pass before it connects; public, the site key only. */
|
|
66
|
+
interface ChatHumanCheck {
|
|
67
|
+
readonly provider: "turnstile";
|
|
68
|
+
readonly siteKey: string;
|
|
59
69
|
}
|
|
60
70
|
/** What `EmbedRoot` from `@boldare/askdare/embed` needs; `getEmbedConfig` builds it (ADR-0018). */
|
|
61
71
|
interface EmbedChatConfig extends ChatConfig {
|
|
@@ -94,11 +104,6 @@ interface ChatFeedbackReport {
|
|
|
94
104
|
/** The OpenAI ID of the rated answer within the conversation. */
|
|
95
105
|
readonly itemId: string;
|
|
96
106
|
}
|
|
97
|
-
/** Stable error codes sent to clients. The accompanying message never contains internals. */
|
|
98
|
-
declare const ERROR_CODES: readonly ["invalid_input", "unauthorized", "session_expired", "not_found", "rate_limited", "budget_exceeded", "bot_unavailable", "content_blocked", "timeout", "upstream_error", "internal_error"];
|
|
99
|
-
type ErrorCode = (typeof ERROR_CODES)[number];
|
|
100
|
-
declare const MESSAGE_END_REASONS: readonly ["completed", "max_steps", "max_output_tokens", "timeout", "content_filter", "aborted"];
|
|
101
|
-
type MessageEndReason = (typeof MESSAGE_END_REASONS)[number];
|
|
102
107
|
/** Tokens one turn used, summed over its model calls, as OpenAI reports them. */
|
|
103
108
|
interface ChatTokenUsage {
|
|
104
109
|
readonly inputTokens: number;
|
|
@@ -149,7 +154,7 @@ interface ChatUsageReport {
|
|
|
149
154
|
readonly tools: readonly ChatToolCallReport[];
|
|
150
155
|
}
|
|
151
156
|
interface ChatHandlerOptions {
|
|
152
|
-
readonly bots: readonly
|
|
157
|
+
readonly bots: readonly BotHandle[];
|
|
153
158
|
/** Path of the catch-all route. Default `/api/chat` (route file `app/api/chat/[...path]/route.ts`). */
|
|
154
159
|
readonly basePath?: string;
|
|
155
160
|
/** Default `process.env.OPENAI_API_KEY`. */
|
|
@@ -211,6 +216,12 @@ interface ChatHandlerLimitsOptions {
|
|
|
211
216
|
readonly trustProxy?: TrustProxy;
|
|
212
217
|
/** Input plus output tokens per UTC day across all bots. Unlimited by default. */
|
|
213
218
|
readonly globalDailyTokens?: number;
|
|
219
|
+
/**
|
|
220
|
+
* Refuse to start without a shared `store`, instead of warning in production that limits are
|
|
221
|
+
* per instance (ADR-0019). For example `process.env.NODE_ENV === 'production'`, so development
|
|
222
|
+
* keeps the in-memory store. Default `false`.
|
|
223
|
+
*/
|
|
224
|
+
readonly requireSharedStore?: boolean;
|
|
214
225
|
}
|
|
215
226
|
type RouteHandler = (request: Request) => Promise<Response>;
|
|
216
227
|
interface ChatHandlers {
|
|
@@ -233,7 +244,7 @@ interface ChatHandlers {
|
|
|
233
244
|
export declare function createChatHandler(options: ChatHandlerOptions): ChatHandlers;
|
|
234
245
|
interface ChatConfigOptions {
|
|
235
246
|
/** The same bots as in `createChatHandler`. */
|
|
236
|
-
readonly bots: readonly
|
|
247
|
+
readonly bots: readonly BotHandle[];
|
|
237
248
|
/** The id of the bot to show. */
|
|
238
249
|
readonly bot: string;
|
|
239
250
|
/** Path of the chat route, the same as in `createChatHandler`. Default `/api/chat`. */
|
|
@@ -259,7 +270,7 @@ export declare function getChatConfig(options: ChatConfigOptions): ChatConfig;
|
|
|
259
270
|
type EmbedSearchParams = URLSearchParams | Readonly<Record<string, string | readonly string[] | undefined>>;
|
|
260
271
|
interface EmbedConfigOptions {
|
|
261
272
|
/** The same bots as in `createChatHandler`. */
|
|
262
|
-
readonly bots: readonly
|
|
273
|
+
readonly bots: readonly BotHandle[];
|
|
263
274
|
/** The id of the bot whose `embedPath` this page is. */
|
|
264
275
|
readonly bot: string;
|
|
265
276
|
/** Path of the chat route, the same as in `createChatHandler`. Default `/api/chat`. */
|
|
@@ -295,7 +306,7 @@ interface EmbedPageHeader {
|
|
|
295
306
|
* ```
|
|
296
307
|
*/
|
|
297
308
|
export declare function embedPageHeaders(options: {
|
|
298
|
-
readonly bots: readonly
|
|
309
|
+
readonly bots: readonly BotHandle[];
|
|
299
310
|
readonly bot: string;
|
|
300
311
|
}): EmbedPageHeader[];
|
|
301
|
-
export type { ChatAttachments, ChatConfig, ChatConfigOptions, ChatErrorReport, ChatFeedbackReport, ChatHandlerLimitsOptions, ChatHandlerOptions, ChatHandlers, ChatStyles, ChatTokenUsage, ChatToolCallReport, ChatUsageReport, ChatWidget, EmbedChatConfig, EmbedConfigOptions, EmbedPageHeader, EmbedSearchParams, RouteHandler, TrustProxy };
|
|
312
|
+
export type { ChatAttachments, ChatConfig, ChatConfigOptions, ChatErrorReport, ChatFeedbackReport, ChatHandlerLimitsOptions, ChatHandlerOptions, ChatHandlers, ChatHumanCheck, ChatStyles, ChatTokenUsage, ChatToolCallReport, ChatUsageReport, ChatWidget, EmbedChatConfig, EmbedConfigOptions, EmbedPageHeader, EmbedSearchParams, RouteHandler, TrustProxy };
|