@boldare/askdare 0.3.0 → 0.5.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/CHANGELOG.md +63 -0
- package/README.md +14 -4
- package/dist/cli.js +111 -26
- package/dist/define-tool.js +1006 -8
- package/dist/embed.d.ts +19 -0
- package/dist/embed.js +250 -0
- package/dist/{store.d.ts → events.d.ts} +163 -54
- package/dist/index.d.ts +28 -2
- package/dist/index.js +74 -158
- package/dist/next.d.ts +70 -9
- package/dist/next.js +767 -169
- package/dist/react-marked.js +648 -624
- package/dist/react.d.ts +63 -77
- package/dist/react.js +148 -1854
- package/dist/root.js +2254 -0
- package/dist/tool-results.d.ts +140 -0
- package/dist/ui/askdare.css +21 -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 +6 -4
- package/dist/ui/panel.tsx +17 -6
- package/dist/ui/welcome.tsx +1 -1
- package/docs/accessibility.md +83 -0
- package/docs/cli.md +5 -3
- package/docs/compliance.md +160 -0
- package/docs/configuration.md +58 -2
- package/docs/costs.md +8 -1
- package/docs/custom-store.md +2 -0
- package/docs/embedding.md +104 -0
- package/docs/events.md +1 -1
- 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 +27 -3
- package/docs/protocol.md +15 -1
- package/docs/react.md +57 -3
- package/docs/styling.md +4 -3
- package/docs/support.md +3 -3
- package/docs/texts.md +127 -98
- package/docs/tools.md +20 -0
- package/docs/troubleshooting.md +30 -3
- package/llms.txt +14 -11
- package/package.json +10 -6
- package/skills/askdare/SKILL.md +12 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,68 @@
|
|
|
1
1
|
# @boldare/askdare
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 2be0e0a: Optional bot protection, both off by default; a bot that turns neither on works as in 0.4.
|
|
8
|
+
|
|
9
|
+
- **Human check with Cloudflare Turnstile:** `security: { humanVerifier: turnstile({ siteKey }) }` in `defineBot`, with the secret key in `TURNSTILE_SECRET_KEY`. The chat shows the Turnstile widget when it needs a new session, and `/session` checks the token with Cloudflare; renewing a live session needs no new check for 24 hours after the visitor passed one. For that bot only, the iframe's Content Security Policy allows `https://challenges.cloudflare.com` in `script-src` and `frame-src`. A chat inside your page must allow the same origin in your page's policy, and a headless chat renders the new `HumanCheck` primitive. To check tokens another way, implement the `HumanVerifier` type.
|
|
10
|
+
- **`limits.requireSharedStore`** in `createChatHandler`: with `true`, the route refuses to load unless `limits.store` is shared, instead of only warning in production.
|
|
11
|
+
|
|
12
|
+
New texts `humanCheck.label` and `error.humanCheck`, a `human-check` part, and `state.humanCheck` in the React hooks.
|
|
13
|
+
- 1b5c112: New `Disclosure` primitive in `@boldare/askdare/react`: the AI notice (EU AI Act, art. 50) for your own markup and for your own page in the widget's iframe. It shows `disclosure.text` with the `widget.disclosure.privacyUrl` link, takes children to replace the text, and renders nothing with `disclosure: false`. The default look now uses it, with the same markup as before.
|
|
14
|
+
|
|
15
|
+
In development, `Root` and `EmbedRoot` note once in the console when the chat rendered without a `Disclosure` while the bot keeps the notice on; `widget.disclosure: false` silences it. `askdare doctor` lists bots with `disclosure: false` as information, not a failure. Nothing changes for existing bots.
|
|
16
|
+
- 1f19a17: Guardrails, all opt-in and set in `defineBot` (ADR-0019). A bot that sets none of them behaves exactly as before.
|
|
17
|
+
|
|
18
|
+
- `moderation: { model, check?, categories?, message? }` runs OpenAI moderation on visitors' messages (`check: 'input'`, the default), on answers (`'output'`) or both. You choose the moderation model, which categories block (default: any flagged one) and the text visitors see. Each checked message adds one call to OpenAI's moderation endpoint.
|
|
19
|
+
- `onInput(text, context)` and `onOutput(text, context)` return `{ action: 'allow' }` (or `undefined`), `{ action: 'block', message? }` or `{ action: 'redact', text }`. A hook that throws lets the text through and logs one line naming the hook.
|
|
20
|
+
- While answers are checked (`onOutput`, or moderation of output), they are held back on the server until complete, then sent whole, replaced or blocked; reasoning and tool status still stream. A blocked answer never reaches the browser, and a replaced one comes without its tool cards and reply options. For these bots the history shows an answer only once its check passed, and a conversation takes one turn at a time (a second message meanwhile gets `rate_limited`).
|
|
21
|
+
- Blocked turns end with the existing `content_blocked` error, with your text or the translated default. Nothing blocked or redacted is logged as content. Attached files are not checked.
|
|
22
|
+
- `toolResults: 'untrusted'` hands tool results to the model wrapped as third-party data that it must not follow as instructions. Recommended for tools that return text from outside your control.
|
|
23
|
+
|
|
24
|
+
New exported types: `GuardrailOptions`, `ModerationConfig`, `GuardHook`, `GuardVerdict` and `GuardContext`. See `docs/guardrails.md`.
|
|
25
|
+
- 1b94b92: Built-in texts in Czech, German, Spanish, French and Italian, next to English and Polish. `widget.locale` set to one of these languages, or `'auto'` on a page or browser in one of them, now shows the chat and the launcher in that language with no `widget.texts` of your own. Your overrides still win. Other languages keep showing English.
|
|
26
|
+
- 5aecb96: Public API clean-up before 1.0 (ADR-0020, ADR-0021).
|
|
27
|
+
|
|
28
|
+
- **`defineBot` now returns a `BotHandle`**, which exposes only `id` and `embedPath`. Pass it to `createChatHandler`, `getChatConfig` and `getEmbedConfig` as before. The resolved `Bot` type, with its filled-in defaults, is no longer exported. If you annotated a variable as `Bot`, use `BotHandle` (or `BotDefinition` for the input). Passing an object that didn't come from `defineBot` now throws a clear `TypeError`.
|
|
29
|
+
- **`ERROR_CODES` and `ErrorCode` are exported** from `@boldare/askdare`, so you can switch on the `code` that `onError` and the chat report.
|
|
30
|
+
- Node.js 26 joins the support matrix.
|
|
31
|
+
- `zod` stays a required peer: `defineBot` validates every definition with it.
|
|
32
|
+
|
|
33
|
+
Type-only removals can't warn at runtime a minor ahead, so this changeset names the replacements instead.
|
|
34
|
+
|
|
35
|
+
### Patch Changes
|
|
36
|
+
|
|
37
|
+
- 7f962ab: Screen readers now hear a finished answer once, as its rendered text. The conversation (`Messages`) is still a `log` but no longer a live region, since text growing inside a message was read in fragments or not at all; a visually hidden `status` next to it (`data-ask-part="announcement"`) announces each answer when it ends. Answers restored after a reload aren't read out. New guide, `docs/accessibility.md`: the dated WCAG 2.2 AA conformance statement, with its scope, method, manual review and known limitations.
|
|
38
|
+
- 8744972: New guide, `docs/compliance.md`: what the AI Act, the GDPR and the European Accessibility Act ask of a website chatbot, what askdare does about each, and the decisions left to you. It covers the AI disclosure, OpenAI's DPA, retention and deletion, `safety_identifier`, OpenAI's data residency (which doesn't cover the Conversations API askdare uses), the resume token in a chat inside your page, and hosts other than Vercel and Heroku (Docker, `next start`, OpenNext; no Edge runtime). It isn't legal advice.
|
|
39
|
+
- b5f3c44: A conversation that outgrows the model's context window now ends with "This conversation is too long. Please start a new one." (`invalid_input`, key `error.conversationTooLong`) instead of a generic "temporarily unavailable" error, should OpenAI ever refuse it. askdare keeps sending the deprecated `truncation: 'auto'` until OpenAI announces a shutdown date, so long conversations keep working as before.
|
|
40
|
+
- 6aacbb8: `askdare doctor` warns when OpenAI has announced a shutdown date for a bot's model or its transcription model, with the date from the OpenAI API and a link to OpenAI's deprecations page for the replacement.
|
|
41
|
+
- 5d745bf: A chat that fills the screen (on a phone, or a desktop page zoomed to 400%) keeps keyboard focus until it is closed, instead of letting it move to the page hidden behind it (WCAG 2.4.11).
|
|
42
|
+
- 08a1b01: A bot's `widget.css` can no longer reach the host page when the chat is inside a page. A stray `}` used to close the `@scope` block early, so a typo like `a { color: red } } body { display: none }` applied `body { display: none }` to the whole page. Stray closing braces are now dropped, and unclosed blocks or strings are closed, so every rule stays scoped to the chat.
|
|
43
|
+
- 0c0ccda: Server logs no longer risk carrying what a visitor wrote. When OpenAI rejects a request with a message that quotes the value it refused, or any other failure reaches the default error log (no `onError` set), quoted values longer than 32 characters are replaced, API keys are cut to their prefix and the message is capped at 300 characters. Status, error code, request ID and stack frames stay, so the logs remain useful for debugging.
|
|
44
|
+
- fe8f7d8: Docs: releases are now tested on an iPhone viewport in WebKit (Safari's engine) automatically, and no longer wait on manual checks in Safari on iOS or with screen readers. The accessibility statement says so: screen readers are not tested by hand, and what they rely on is checked by the automated tests.
|
|
45
|
+
- c8ed689: Docs for 0.5: `privacy.md` covers the moderation calls to OpenAI and Cloudflare as a processor for the human check, `troubleshooting.md` covers guardrail blocks, the one-turn-at-a-time hold and a failing human check, `cli.md` lists doctor's note about the AI notice, `styling.md` lists the `announcement` part, and the package READMEs list what is new in 0.5 and `limits.requireSharedStore`.
|
|
46
|
+
- a190bcd: Streamed answers stay smooth however long they get: `Markdown` now re-lexes and re-renders only the last blocks of a message on each delta, instead of the whole answer. Sanitizing is unchanged.
|
|
47
|
+
- 8fba8ee: Bots with `replies: 'suggest'` no longer write their answer twice. Current models mark an answer written before the `suggest_replies` call as commentary, and askdare took that as an unfinished turn and asked the model again, which repeated the answer. Text followed only by reply options now ends the turn as the answer, and the history shows it once.
|
|
48
|
+
|
|
49
|
+
## 0.4.0
|
|
50
|
+
|
|
51
|
+
### Minor Changes
|
|
52
|
+
|
|
53
|
+
- de9caf4: New route `GET <basePath>/config/<bot>?lang=<tag>`: the bot's public configuration in one language, built like the chat document's, so it never carries the model, instructions, tools or vector stores. It prepares switching the chat's language in place (ADR-0014, step 2). A bot with a fixed locale ignores `lang`, and an invalid tag answers `400` with `invalid_input`. Additive within protocol version 1.
|
|
54
|
+
- 82af455: A bot can show a page of your app in the widget's iframe instead of askdare's own (ADR-0018). Set `defineBot({ embedPath: '/askdare/support' })`, and the chat route redirects the iframe there with the visitor's language and the mode; the loader on the embedding sites doesn't change. `@boldare/askdare/next` adds `getEmbedConfig({ bots, bot, searchParams })`, the configuration for that page, and `embedPageHeaders({ bots, bot })`, the `frame-ancestors`, `Permissions-Policy` and `Referrer-Policy` headers it must send, to send from `proxy.ts`. `askdare doctor` follows the redirect and checks the page: no redirect in front of it, `EmbedRoot` on it, who may frame it and the microphone rule. The page renders the chat with `EmbedRoot` from `@boldare/askdare/embed`.
|
|
55
|
+
- 1e30933: Your own page in the widget's iframe (ADR-0018). A new entry, `@boldare/askdare/embed`, exports `EmbedRoot`: render it on the page a bot's `embedPath` points to, with `getEmbedConfig`, and put `DefaultChat`, an ejected copy or your own markup inside. It connects to the loader on the embedding site exactly as askdare's own page does (identity, `configure`, events, closing, language switches), so the widget on every site uses your components and draws your `toolRenderers`. Inside `EmbedRoot`, `DefaultChat` and an ejected copy of it own the document: an `h1` and a close button. A new hook, `useFrame()`, gives your own markup the same close action. The loader answers a new `askdare:hello` from its own iframe, so a page that hydrates after its load event still connects. Send the page's headers from `proxy.ts` with `embedPageHeaders`; the guide is in Embedding.
|
|
56
|
+
- e1fadd3: The chat switches its language in place (ADR-0014, step 2). When the page calls `askdare('configure', { locale })` or follows `<html lang>` with `data-follow-lang`, the chat no longer reloads: it fetches its texts for the new language from `GET <basePath>/config/<bot>` and keeps the conversation, the unsent message and an answer still streaming, which now finishes instead of being reported as `stopped`. New answers follow the new language. If the texts can't be loaded, the chat reloads as before. In React, a `Root` whose config changes only its `locale` switches the same chat instead of starting another one. `GET /config/<bot>` also answers `Content-Language`, the language its texts are written in.
|
|
57
|
+
- c994c50: A bot can give its texts per language: `widget.texts` also takes `{ en: {...}, pl: {...} }`, one set of overrides per language, so a chat with `locale: 'auto'` shows your own texts in each language (ADR-0014, step 2). A visitor gets the set for their language tag, else one for the same language; a language without a built-in dictionary gets the `en` set. The launcher on the page follows the same sets. A set's key wins over the `title`, `greeting`, `placeholder` and `launcherLabel` shortcuts for its language. The flat form is unchanged and still applies in every language. The chat document's `lang` follows a set written for the visitor's language.
|
|
58
|
+
- 3c7a2ca: Tool cards in the chat inside your page (ADR-0017). Give `Root` your components with `toolRenderers={{ find_slots: SlotList }}`, and the chat draws each tool's `ui` payload with its component under the answer, live and after a reload. A component gets `{ data, name, callId }`, typed from the tool with `ToolRendererProps<typeof findSlots>` and `import type`; `satisfies ToolRenderers<[typeof findSlots]>` checks the whole map. New primitives: `ToolResults` (parts `tool-results` and `tool-result`, with `data-ask-tool`), which `DefaultChat` places under the answer's text, and `Link`, which allows only `https`, `http` and `mailto` URLs from a payload. A tool without a component shows nothing, and a component that throws leaves out only its card. In the script-tag widget, a bot draws them when its iframe shows your own page (`embedPath` and `EmbedRoot`); askdare's own iframe page has no components to draw them with.
|
|
59
|
+
- 4ff33c4: Tools can pick what the visitor sees of their result (ADR-0017). `defineTool({ ui: (result) => data })` returns plain JSON of at most 8 KB for a card, list or table; only that reaches the browser, never the result itself. The server sends it as a new `tool.ui` event after the call (additive within protocol version 1), and `POST /history` brings every answer's payloads back as `ui` after a reload. At most 4 per answer, in call order; a failed call, a throwing `ui` or a payload over the limits shows nothing. `Tool` now carries the tool's name and payload type (`Tool<Name, Ui>`), so the React components that draw the payloads (`toolRenderers`) are typed from the tool. The browser keeps them on `ChatMessage.ui`.
|
|
60
|
+
|
|
61
|
+
### Patch Changes
|
|
62
|
+
|
|
63
|
+
- ca03828: Dependencies: `openai` ^7.56.0 (was ^7.52.0) and `jose` ^6.2.17 (was ^6.2.15). Nothing changes in askdare's API.
|
|
64
|
+
- 95fb6e2: The README's "What you get" picture now shows what 0.4 adds: tool cards, drawn by your own React components, your own page inside the widget, and texts per language.
|
|
65
|
+
|
|
3
66
|
## 0.3.0
|
|
4
67
|
|
|
5
68
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -38,9 +38,19 @@ export const bots = [
|
|
|
38
38
|
|
|
39
39
|
## What you get
|
|
40
40
|
|
|
41
|
-
[](https://askdare.vercel.app/#features)
|
|
42
|
+
|
|
43
|
+
[Knowledge base](https://askdare.vercel.app/docs/knowledge-base) · [Tools](https://askdare.vercel.app/docs/tools) · [Tool cards](https://askdare.vercel.app/docs/react#tool-cards) · [Reply options](https://askdare.vercel.app/docs/reply-options) · [Attachments](https://askdare.vercel.app/docs/attachments) · [Voice input](https://askdare.vercel.app/docs/voice-input) · [The chat inside your page (React)](https://askdare.vercel.app/docs/react) · [Your own page in the widget](https://askdare.vercel.app/docs/embedding#your-own-page-in-the-iframe) · [Answer ratings](https://askdare.vercel.app/docs/feedback) · [Guardrails](https://askdare.vercel.app/docs/guardrails) · [Accessibility](https://askdare.vercel.app/docs/accessibility) · [Security](https://github.com/boldare/askdare/blob/main/THREAT_MODEL.md)
|
|
44
|
+
|
|
45
|
+
**New in 0.5:**
|
|
46
|
+
|
|
47
|
+
- **Guardrails**, all opt-in: OpenAI moderation of messages and answers, your own `onInput` and `onOutput` rules to block or redact, and tool results marked as untrusted. See [Guardrails](https://askdare.vercel.app/docs/guardrails).
|
|
48
|
+
- **Bot protection**: an optional human check with Cloudflare Turnstile (`security.humanVerifier`), and `limits.requireSharedStore` to refuse a deployment without shared limits. See [Configuration](https://askdare.vercel.app/docs/configuration#human-check).
|
|
49
|
+
- **Seven languages built in**: Czech, German, Spanish, French and Italian join English and Polish. See [Texts](https://askdare.vercel.app/docs/texts).
|
|
50
|
+
- **WCAG 2.2 AA**: finished answers are read out once, a full-screen chat keeps the focus, and a dated [accessibility statement](https://askdare.vercel.app/docs/accessibility).
|
|
51
|
+
- **Compliance**: the `Disclosure` primitive for the AI notice in your own markup, and a [guide](https://askdare.vercel.app/docs/compliance) to what the AI Act, the GDPR and the European Accessibility Act ask of a website chatbot.
|
|
52
|
+
- **Also**: `doctor` warns about model shutdown dates, smoother streaming of long answers, error logs without visitor text, and a clear error when a conversation outgrows the model's context. `defineBot` returns a `BotHandle`, `ERROR_CODES` is exported, and Node.js 26 is supported. See the [changelog](https://github.com/boldare/askdare/blob/main/packages/askdare/CHANGELOG.md).
|
|
42
53
|
|
|
43
|
-
[Knowledge base](https://askdare.vercel.app/docs/knowledge-base) · [Tools](https://askdare.vercel.app/docs/tools) · [Attachments](https://askdare.vercel.app/docs/attachments) · [Voice input](https://askdare.vercel.app/docs/voice-input) · [The chat inside your page (React)](https://askdare.vercel.app/docs/react) · [Answer ratings](https://askdare.vercel.app/docs/feedback) · [Security](https://github.com/boldare/askdare/blob/main/THREAT_MODEL.md)
|
|
44
54
|
|
|
45
55
|
## Themes
|
|
46
56
|
|
|
@@ -54,7 +64,7 @@ The guides are on [askdare.vercel.app/docs](https://askdare.vercel.app/docs), wi
|
|
|
54
64
|
|
|
55
65
|
- **Start:** [Getting started](https://askdare.vercel.app/docs/getting-started) · [Embedding the chat](https://askdare.vercel.app/docs/embedding) · [Command line](https://askdare.vercel.app/docs/cli)
|
|
56
66
|
- **Look and language:** [Themes](https://askdare.vercel.app/docs/themes) · [Styling](https://askdare.vercel.app/docs/styling) · [Texts](https://askdare.vercel.app/docs/texts) · [The chat inside your page (React)](https://askdare.vercel.app/docs/react)
|
|
57
|
-
- **Going live:** [Deployment](https://askdare.vercel.app/docs/deployment) · [Going-public checklist](https://askdare.vercel.app/docs/going-public) · [Costs](https://askdare.vercel.app/docs/costs) · [Observability](https://askdare.vercel.app/docs/observability) · [Chat events](https://askdare.vercel.app/docs/events) · [Answer ratings](https://askdare.vercel.app/docs/feedback) · [Privacy](https://askdare.vercel.app/docs/privacy)
|
|
67
|
+
- **Going live:** [Deployment](https://askdare.vercel.app/docs/deployment) · [Going-public checklist](https://askdare.vercel.app/docs/going-public) · [Guardrails](https://askdare.vercel.app/docs/guardrails) · [Costs](https://askdare.vercel.app/docs/costs) · [Observability](https://askdare.vercel.app/docs/observability) · [Chat events](https://askdare.vercel.app/docs/events) · [Answer ratings](https://askdare.vercel.app/docs/feedback) · [Privacy](https://askdare.vercel.app/docs/privacy) · [Compliance](https://askdare.vercel.app/docs/compliance) · [Accessibility](https://askdare.vercel.app/docs/accessibility)
|
|
58
68
|
- **Reference:** [Configuration](https://askdare.vercel.app/docs/configuration) · [Troubleshooting](https://askdare.vercel.app/docs/troubleshooting) · [Support matrix](https://askdare.vercel.app/docs/support)
|
|
59
69
|
- **AI coding agents:** `llms.txt` and the `askdare` skill ship in the package ([how to use them](https://askdare.vercel.app/docs/getting-started#working-with-an-ai-coding-agent))
|
|
60
70
|
|
|
@@ -67,7 +77,7 @@ The guides are on [askdare.vercel.app/docs](https://askdare.vercel.app/docs), wi
|
|
|
67
77
|
|
|
68
78
|
## Requirements
|
|
69
79
|
|
|
70
|
-
Node.js 22 or
|
|
80
|
+
Node.js 22, 24 or 26, Next.js 16 with the App Router on the Node.js runtime, React 19 and zod 4.1 or later.
|
|
71
81
|
|
|
72
82
|
## License
|
|
73
83
|
|
package/dist/cli.js
CHANGED
|
@@ -19,6 +19,14 @@ import OpenAI, { NotFoundError, toFile } from "openai";
|
|
|
19
19
|
function isBasePath(value) {
|
|
20
20
|
return /^(\/[a-zA-Z0-9._~-]+)+$/.test(value);
|
|
21
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* Whether a bot's `embedPath` is a page of the same app, like `/askdare/support` (ADR-0018): a
|
|
24
|
+
* path as `isBasePath` accepts it, without `.` or `..` segments, so a redirect to it can't leave
|
|
25
|
+
* the app or climb out of where it points.
|
|
26
|
+
*/
|
|
27
|
+
function isEmbedPath(value) {
|
|
28
|
+
return isBasePath(value) && !value.split("/").some((segment) => /^\.{1,2}$/.test(segment));
|
|
29
|
+
}
|
|
22
30
|
// src/cli/project.ts
|
|
23
31
|
const LOCKFILES = [
|
|
24
32
|
["pnpm-lock.yaml", "pnpm"],
|
|
@@ -248,7 +256,13 @@ const doctorReportSchema = z.object({
|
|
|
248
256
|
bots: z.array(z.object({
|
|
249
257
|
id: z.string().max(48),
|
|
250
258
|
checks: z.array(check).max(20),
|
|
251
|
-
turnTimeoutMs: z.number().int().positive().optional()
|
|
259
|
+
turnTimeoutMs: z.number().int().positive().optional(),
|
|
260
|
+
disclosure: z.boolean().optional(),
|
|
261
|
+
embed: z.object({
|
|
262
|
+
path: z.string().refine(isEmbedPath),
|
|
263
|
+
allowedOrigins: z.array(z.string().max(300)).max(50),
|
|
264
|
+
voice: z.boolean()
|
|
265
|
+
}).optional()
|
|
252
266
|
})).max(50)
|
|
253
267
|
});
|
|
254
268
|
// src/security/identity.ts
|
|
@@ -520,10 +534,13 @@ async function createTokenService(options) {
|
|
|
520
534
|
});
|
|
521
535
|
}
|
|
522
536
|
return {
|
|
523
|
-
issueAccess: (botId, visitorId, identity) => issue(ACCESS_TYP, botId, visitorId, identity ? Math.max(1, Math.min(accessTtl, identity.expiresAt - now())) : accessTtl,
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
537
|
+
issueAccess: (botId, visitorId, identity, humanCheckedAt) => issue(ACCESS_TYP, botId, visitorId, identity ? Math.max(1, Math.min(accessTtl, identity.expiresAt - now())) : accessTtl, {
|
|
538
|
+
...identity ? {
|
|
539
|
+
idn: { ...identity.identity },
|
|
540
|
+
ixp: identity.expiresAt
|
|
541
|
+
} : {},
|
|
542
|
+
...humanCheckedAt === void 0 ? {} : { hv: humanCheckedAt }
|
|
543
|
+
}),
|
|
527
544
|
async verifyAccess(token, botId) {
|
|
528
545
|
try {
|
|
529
546
|
const { payload } = await verify(token, ACCESS_TYP, botId);
|
|
@@ -541,9 +558,11 @@ async function createTokenService(options) {
|
|
|
541
558
|
try {
|
|
542
559
|
const { payload } = await verify(token, ACCESS_TYP, botId, RENEWAL_GRACE_SECONDS);
|
|
543
560
|
if (typeof payload.sub !== "string" || !VISITOR_ID.test(payload.sub)) throw new AskdareError("unauthorized");
|
|
561
|
+
const { hv } = payload;
|
|
544
562
|
return {
|
|
545
563
|
visitorId: payload.sub,
|
|
546
|
-
identity: identityOf(payload, now())
|
|
564
|
+
identity: identityOf(payload, now()),
|
|
565
|
+
...typeof hv === "number" && Number.isFinite(hv) ? { humanCheckedAt: hv } : {}
|
|
547
566
|
};
|
|
548
567
|
} catch (error) {
|
|
549
568
|
throw new AskdareError("unauthorized", { cause: error });
|
|
@@ -642,6 +661,11 @@ const fail = (title, fix) => ({
|
|
|
642
661
|
title,
|
|
643
662
|
fix
|
|
644
663
|
});
|
|
664
|
+
const info = (title, fix) => ({
|
|
665
|
+
status: "info",
|
|
666
|
+
title,
|
|
667
|
+
fix
|
|
668
|
+
});
|
|
645
669
|
const PROXY_FIX = "Exclude askdare's routes in proxy.ts, e.g. matcher: ['/((?!api/chat|_next/static|_next/image).*)'].";
|
|
646
670
|
function versions(project) {
|
|
647
671
|
const checks = [];
|
|
@@ -751,36 +775,95 @@ async function request(fetcher, url, init = {}) {
|
|
|
751
775
|
function redirectOrMissing(response, url) {
|
|
752
776
|
if (response.status >= 300 && response.status < 400) return fail(`${url} redirects to ${response.headers.get("location") ?? "another page"}.`, PROXY_FIX);
|
|
753
777
|
}
|
|
778
|
+
/** The sources of the response's `frame-ancestors`, one list per policy that sets it. */
|
|
779
|
+
function frameAncestorsOf(response) {
|
|
780
|
+
return [...(response.headers.get("content-security-policy") ?? "").matchAll(/frame-ancestors\s+([^;,]*)/g)].map((match) => (match[1] ?? "").trim().split(/\s+/).filter(Boolean));
|
|
781
|
+
}
|
|
782
|
+
/** Whether `origin` may frame a page whose `frame-ancestors` sources are these. */
|
|
783
|
+
const mayFrame = (sources, origin, appOrigin) => sources.includes(origin) || origin === appOrigin && sources.includes("'self'");
|
|
784
|
+
const EMBED_HEADERS_FIX = (path, botId) => `Send embedPageHeaders({ bots, bot: '${botId}' }) from @boldare/askdare/next for ${path} in the headers() of next.config.`;
|
|
785
|
+
/**
|
|
786
|
+
* A bot's own page in the widget's iframe (ADR-0018): reachable without a login or a redirect,
|
|
787
|
+
* rendered with EmbedRoot, framed only by the app and the bot's allowed origins, and with the
|
|
788
|
+
* microphone off unless the bot has voice input.
|
|
789
|
+
*/
|
|
790
|
+
async function embedPage(fetcher, base, botId, embed, origin) {
|
|
791
|
+
const appOrigin = new URL(base).origin;
|
|
792
|
+
const url = `${appOrigin}${embed.path}`;
|
|
793
|
+
const page = await request(fetcher, url);
|
|
794
|
+
if (!(page instanceof Response)) return [page];
|
|
795
|
+
const pageFix = `Leave ${embed.path} out of proxy.ts (its matcher) and of anything that signs visitors in or rewrites the path.`;
|
|
796
|
+
const missing = redirectOrMissing(page, url);
|
|
797
|
+
if (missing) {
|
|
798
|
+
await page.body?.cancel();
|
|
799
|
+
return [{
|
|
800
|
+
...missing,
|
|
801
|
+
fix: pageFix
|
|
802
|
+
}];
|
|
803
|
+
}
|
|
804
|
+
if (!page.ok) {
|
|
805
|
+
await page.body?.cancel();
|
|
806
|
+
return [fail(`${url} answered HTTP ${page.status}.`, pageFix)];
|
|
807
|
+
}
|
|
808
|
+
const checks = [];
|
|
809
|
+
const html = await page.text();
|
|
810
|
+
checks.push(html.includes("data-askdare-embed") ? ok(`${embed.path} renders the chat.`) : fail(`${embed.path} doesn't render EmbedRoot.`, "Render <EmbedRoot config={getEmbedConfig(…)}> from @boldare/askdare/embed on that page."));
|
|
811
|
+
const fix = EMBED_HEADERS_FIX(embed.path, botId);
|
|
812
|
+
const ancestors = frameAncestorsOf(page);
|
|
813
|
+
const sources = ancestors[0] ?? [];
|
|
814
|
+
const allowed = /* @__PURE__ */ new Set([
|
|
815
|
+
"'self'",
|
|
816
|
+
appOrigin,
|
|
817
|
+
...embed.allowedOrigins
|
|
818
|
+
]);
|
|
819
|
+
const wider = sources.filter((source) => !allowed.has(source));
|
|
820
|
+
const absent = [...mayFrame(sources, appOrigin, appOrigin) ? [] : [appOrigin], ...embed.allowedOrigins.filter((item) => !sources.includes(item))];
|
|
821
|
+
if (page.headers.has("x-frame-options")) checks.push(fail(`X-Frame-Options on ${embed.path} stops sites from embedding it.`, fix));
|
|
822
|
+
else if (ancestors.length !== 1) checks.push(fail(ancestors.length === 0 ? `Any site can frame ${embed.path}: it has no frame-ancestors policy.` : `A second Content-Security-Policy on ${embed.path} overrides who may frame it.`, fix));
|
|
823
|
+
else if (wider.length > 0) checks.push(fail(`${embed.path} may be framed by more than the bot allows: ${wider.join(" ")}`, fix));
|
|
824
|
+
else if (absent.length > 0) checks.push(fail(`${absent.join(", ")} may not frame ${embed.path}, so the widget can't open there.`, fix));
|
|
825
|
+
else checks.push(ok(`Sites that may frame ${embed.path}: ${sources.join(" ")}`));
|
|
826
|
+
if (origin !== void 0 && ancestors.length === 1) checks.push(mayFrame(sources, origin, appOrigin) ? ok(`${origin} may embed the chat.`) : fail(`${origin} may not embed the chat: it isn't in the bot's security.allowedOrigins.`, `Add '${origin}' to security.allowedOrigins of bot "${botId}" and deploy.`));
|
|
827
|
+
const microphone = /(?:^|,)\s*microphone=([^,]*)/.exec(page.headers.get("permissions-policy") ?? "")?.[1]?.trim();
|
|
828
|
+
if (!embed.voice && microphone !== "()") checks.push(fail(`${embed.path} doesn't keep the microphone off for a bot without voice input.`, fix));
|
|
829
|
+
else if (embed.voice && !/\bself\b|\*/.test(microphone ?? "")) checks.push(warn(`${embed.path} doesn't allow the microphone, so dictation won't start.`, fix));
|
|
830
|
+
if (page.headers.has("set-cookie")) checks.push(warn(`Something sets cookies on ${embed.path}.`, "askdare uses no cookies; scripts on the page could read them with the chat."));
|
|
831
|
+
return checks;
|
|
832
|
+
}
|
|
754
833
|
/** What the browser needs from widget.js and the chat page; things in front of askdare can break it. */
|
|
755
|
-
async function headers(fetcher, base, botId, origin) {
|
|
834
|
+
async function headers(fetcher, base, botId, origin, embed) {
|
|
756
835
|
const checks = [];
|
|
757
836
|
const loaderUrl = `${base}/widget.js?bot=${botId}`;
|
|
758
837
|
const loader = await request(fetcher, loaderUrl);
|
|
759
838
|
if (!(loader instanceof Response)) return [loader];
|
|
760
839
|
const embedUrl = `${base}/embed/${botId}`;
|
|
761
|
-
const
|
|
762
|
-
if (!(
|
|
840
|
+
const embedResponse = await request(fetcher, embedUrl);
|
|
841
|
+
if (!(embedResponse instanceof Response)) return [embedResponse];
|
|
763
842
|
const loaderProblem = redirectOrMissing(loader, loaderUrl);
|
|
764
843
|
if (loaderProblem) checks.push(loaderProblem);
|
|
765
844
|
else if (!loader.ok || !(loader.headers.get("content-type") ?? "").includes("javascript")) checks.push(fail(`${loaderUrl} answered HTTP ${loader.status} instead of the script.`, PROXY_FIX));
|
|
766
845
|
else checks.push(ok("widget.js loads."));
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
846
|
+
if (embed) {
|
|
847
|
+
const location = embedResponse.headers.get("location") ?? "";
|
|
848
|
+
if (embedResponse.status === 302 && (location === embed.path || location.startsWith(`${embed.path}?`))) {
|
|
849
|
+
checks.push(ok(`The widget opens ${embed.path}.`));
|
|
850
|
+
checks.push(...await embedPage(fetcher, base, botId, embed, origin));
|
|
851
|
+
} else checks.push(fail(`${embedUrl} doesn't send the widget to ${embed.path}.`, PROXY_FIX));
|
|
852
|
+
} else {
|
|
853
|
+
const embedProblem = redirectOrMissing(embedResponse, embedUrl);
|
|
854
|
+
if (embedProblem) checks.push(embedProblem);
|
|
855
|
+
else if (!embedResponse.ok) checks.push(fail(`${embedUrl} answered HTTP ${embedResponse.status}.`, PROXY_FIX));
|
|
856
|
+
else {
|
|
857
|
+
const ancestors = frameAncestorsOf(embedResponse);
|
|
858
|
+
const fix = "Leave /api/chat out of the headers() in next.config and of proxy.ts.";
|
|
859
|
+
if (origin !== void 0 && ancestors.length === 1) checks.push(mayFrame(ancestors[0] ?? [], origin, new URL(base).origin) ? ok(`${origin} may embed the chat.`) : fail(`${origin} may not embed the chat: it isn't in the bot's security.allowedOrigins.`, `Add '${origin}' to security.allowedOrigins of bot "${botId}" and deploy.`));
|
|
860
|
+
if (embedResponse.headers.has("x-frame-options")) checks.push(fail("X-Frame-Options on the chat page stops sites from embedding it.", fix));
|
|
861
|
+
else if (ancestors.length !== 1) checks.push(fail(ancestors.length === 0 ? "The chat page lost its frame-ancestors policy." : "A second Content-Security-Policy on the chat page overrides who may embed it.", fix));
|
|
862
|
+
else checks.push(ok(`Sites that may embed the chat: ${(ancestors[0] ?? []).join(" ")}`));
|
|
777
863
|
}
|
|
778
|
-
if (embed.headers.has("x-frame-options")) checks.push(fail("X-Frame-Options on the chat page stops sites from embedding it.", fix));
|
|
779
|
-
else if (ancestors.length !== 1) checks.push(fail(ancestors.length === 0 ? "The chat page lost its frame-ancestors policy." : "A second Content-Security-Policy on the chat page overrides who may embed it.", fix));
|
|
780
|
-
else checks.push(ok(`Sites that may embed the chat: ${ancestors[0]}`));
|
|
781
864
|
}
|
|
782
|
-
if (loader.headers.has("set-cookie") ||
|
|
783
|
-
await Promise.all([loader.body?.cancel(),
|
|
865
|
+
if (loader.headers.has("set-cookie") || embedResponse.headers.has("set-cookie")) checks.push(warn("Something sets cookies on askdare's responses.", "askdare uses no cookies; leave /api/chat out of the code that sets them."));
|
|
866
|
+
await Promise.all([loader.body?.cancel(), embedResponse.body?.cancel()]);
|
|
784
867
|
return checks;
|
|
785
868
|
}
|
|
786
869
|
/** The literal `maxDuration` of the askdare route, in seconds, if the file has one. */
|
|
@@ -855,14 +938,16 @@ async function live(options, project, env) {
|
|
|
855
938
|
title: `Bot "${bot.id}"`,
|
|
856
939
|
checks: [
|
|
857
940
|
...bot.checks,
|
|
858
|
-
...await headers(fetcher, base, bot.id, options.origin),
|
|
859
|
-
...timeout(bot, routeSeconds)
|
|
941
|
+
...await headers(fetcher, base, bot.id, options.origin, bot.embed),
|
|
942
|
+
...timeout(bot, routeSeconds),
|
|
943
|
+
...bot.disclosure === false ? [info("The AI notice is off (widget.disclosure: false).", "Fine when your page already tells visitors they are talking to an AI (EU AI Act, art. 50).")] : []
|
|
860
944
|
]
|
|
861
945
|
});
|
|
862
946
|
return sections;
|
|
863
947
|
}
|
|
864
948
|
const MARK = {
|
|
865
949
|
ok: "✓",
|
|
950
|
+
info: "i",
|
|
866
951
|
warn: "!",
|
|
867
952
|
fail: "✗"
|
|
868
953
|
};
|