@blogmcp/sdk 0.6.1 → 0.7.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.
Files changed (136) hide show
  1. package/dist/consultations/channel-text.d.ts +118 -0
  2. package/dist/consultations/channel-text.js +40 -0
  3. package/dist/consultations/index.d.ts +28 -0
  4. package/dist/consultations/index.js +60 -0
  5. package/dist/consultations/messages.cs.d.ts +149 -0
  6. package/dist/consultations/messages.cs.js +143 -0
  7. package/dist/consultations/messages.d.ts +34 -0
  8. package/dist/consultations/messages.en.d.ts +143 -0
  9. package/dist/consultations/messages.en.js +141 -0
  10. package/dist/consultations/messages.js +48 -0
  11. package/dist/consultations/outcome.d.ts +121 -0
  12. package/dist/consultations/outcome.js +161 -0
  13. package/dist/consultations/public-config.d.ts +71 -0
  14. package/dist/consultations/public-config.js +104 -0
  15. package/dist/consultations/reader.d.ts +83 -0
  16. package/dist/consultations/reader.js +128 -0
  17. package/dist/consultations/routes.d.ts +214 -0
  18. package/dist/consultations/routes.js +149 -0
  19. package/dist/consultations/server/client-ip.d.ts +50 -0
  20. package/dist/consultations/server/client-ip.js +44 -0
  21. package/dist/consultations/server/contact.d.ts +23 -0
  22. package/dist/consultations/server/contact.js +138 -0
  23. package/dist/consultations/server/context.d.ts +246 -0
  24. package/dist/consultations/server/context.js +152 -0
  25. package/dist/consultations/server/cookie.d.ts +60 -0
  26. package/dist/consultations/server/cookie.js +57 -0
  27. package/dist/consultations/server/env.d.ts +20 -0
  28. package/dist/consultations/server/env.js +35 -0
  29. package/dist/consultations/server/http.d.ts +59 -0
  30. package/dist/consultations/server/http.js +64 -0
  31. package/dist/consultations/server/index.d.ts +37 -0
  32. package/dist/consultations/server/index.js +19 -0
  33. package/dist/consultations/server/origin.d.ts +39 -0
  34. package/dist/consultations/server/origin.js +31 -0
  35. package/dist/consultations/server/server.d.ts +106 -0
  36. package/dist/consultations/server/server.js +122 -0
  37. package/dist/consultations/server/session.d.ts +38 -0
  38. package/dist/consultations/server/session.js +210 -0
  39. package/dist/consultations/server/transport.d.ts +69 -0
  40. package/dist/consultations/server/transport.js +117 -0
  41. package/dist/consultations/server/turnstile.d.ts +44 -0
  42. package/dist/consultations/server/turnstile.js +31 -0
  43. package/dist/consultations/site.d.ts +100 -0
  44. package/dist/consultations/site.js +60 -0
  45. package/dist/consultations/submit-new.d.ts +103 -0
  46. package/dist/consultations/submit-new.js +72 -0
  47. package/dist/core/auth.d.ts +2 -2
  48. package/dist/core/client.d.ts +25 -4
  49. package/dist/core/client.js +35 -30
  50. package/dist/core/consultation-adapter.d.ts +2 -2
  51. package/dist/core/consultations.d.ts +1 -1
  52. package/dist/core/errors.d.ts +1 -1
  53. package/dist/core/errors.js +16 -15
  54. package/dist/core/index.d.ts +31 -31
  55. package/dist/core/index.js +35 -34
  56. package/dist/core/markdown.d.ts +1 -1
  57. package/dist/core/queries.d.ts +4 -1
  58. package/dist/core/queries.js +131 -86
  59. package/dist/core/review/format.d.ts +1 -1
  60. package/dist/core/review/index.d.ts +2 -2
  61. package/dist/core/seo.d.ts +1 -1
  62. package/dist/core/translations/cs.json.js +1 -1
  63. package/dist/core/translations/en.json.js +1 -1
  64. package/dist/core/types.d.ts +50 -1
  65. package/dist/core/view-model.d.ts +12 -2
  66. package/dist/core/view-model.js +40 -34
  67. package/dist/{packages/tripmap-core/node_modules → node_modules}/pmtiles/dist/esm/index.js +1 -1
  68. package/dist/nuxt/composables/useAsyncKb.d.ts +4 -4
  69. package/dist/nuxt/index.d.ts +1 -1
  70. package/dist/packages/tripmap-core/dist/engine.js +3 -3
  71. package/dist/packages/tripmap-core/dist/generated/maplibre-worker.bundle.js +1 -1
  72. package/dist/react/KbMdxContent.d.ts +1 -1
  73. package/dist/react/context.d.ts +4 -4
  74. package/dist/react/hooks/useImageRenderer.d.ts +1 -1
  75. package/dist/react/hooks/useKbClient.d.ts +1 -1
  76. package/dist/react/hooks/useKbContext.d.ts +1 -1
  77. package/dist/react/hooks/useKbI18n.d.ts +1 -1
  78. package/dist/react/hooks/useKbLanguage.d.ts +1 -1
  79. package/dist/react/hooks/useKbSearch.d.ts +1 -1
  80. package/dist/react/hooks/useMdxContent.d.ts +1 -1
  81. package/dist/react/index.d.ts +15 -15
  82. package/dist/react/provider.d.ts +2 -2
  83. package/dist/react/server/index.d.ts +2 -2
  84. package/dist/vue/components/KbAccessGate.vue.d.ts +4 -1
  85. package/dist/vue/components/KbAccessGate.vue.js +42 -32
  86. package/dist/vue/components/KbArticleCard.vue.d.ts +3 -1
  87. package/dist/vue/components/KbArticleCard.vue.js +67 -39
  88. package/dist/vue/composables/useArticles.d.ts +1 -1
  89. package/dist/vue/composables/useImageRenderer.d.ts +1 -1
  90. package/dist/vue/composables/useKbAuth.d.ts +1 -1
  91. package/dist/vue/composables/useKbClient.d.ts +1 -1
  92. package/dist/vue/composables/useKbComments.d.ts +1 -1
  93. package/dist/vue/composables/useKbI18n.d.ts +1 -1
  94. package/dist/vue/composables/useKbLanguage.d.ts +1 -1
  95. package/dist/vue/composables/useNavigation.d.ts +1 -1
  96. package/dist/vue/composables/useSearch.d.ts +1 -1
  97. package/dist/vue/composables/useTags.d.ts +1 -1
  98. package/dist/vue/index.d.ts +19 -19
  99. package/dist/vue/plugin.d.ts +4 -4
  100. package/package.json +15 -5
  101. package/src/consultations/channel-text.ts +168 -0
  102. package/src/consultations/index.ts +87 -0
  103. package/src/consultations/messages.cs.ts +175 -0
  104. package/src/consultations/messages.en.ts +171 -0
  105. package/src/consultations/messages.ts +91 -0
  106. package/src/consultations/outcome.ts +278 -0
  107. package/src/consultations/public-config.ts +246 -0
  108. package/src/consultations/reader.ts +281 -0
  109. package/src/consultations/routes.ts +341 -0
  110. package/src/consultations/server/client-ip.ts +106 -0
  111. package/src/consultations/server/contact.ts +267 -0
  112. package/src/consultations/server/context.ts +403 -0
  113. package/src/consultations/server/cookie.ts +129 -0
  114. package/src/consultations/server/env.ts +66 -0
  115. package/src/consultations/server/http.ts +148 -0
  116. package/src/consultations/server/index.ts +55 -0
  117. package/src/consultations/server/origin.ts +71 -0
  118. package/src/consultations/server/server.ts +322 -0
  119. package/src/consultations/server/session.ts +414 -0
  120. package/src/consultations/server/transport.ts +196 -0
  121. package/src/consultations/server/turnstile.ts +98 -0
  122. package/src/consultations/site.ts +183 -0
  123. package/src/consultations/submit-new.ts +266 -0
  124. package/src/core/auth.ts +1 -1
  125. package/src/core/client.ts +32 -1
  126. package/src/core/errors.ts +5 -2
  127. package/src/core/index.ts +3 -0
  128. package/src/core/queries.ts +56 -0
  129. package/src/core/translations/cs.json +2 -1
  130. package/src/core/translations/en.json +2 -1
  131. package/src/core/types.ts +51 -0
  132. package/src/core/view-model.ts +18 -0
  133. package/src/vue/components/KbAccessGate.vue +14 -1
  134. package/src/vue/components/KbArticleCard.vue +25 -0
  135. /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl-shared.js +0 -0
  136. /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl.js +0 -0
@@ -0,0 +1,106 @@
1
+ /**
2
+ * `createConsultationServer` — one object per blog process that serves every
3
+ * reader consultation page and endpoint (docs/internal/reader-consultations.md;
4
+ * the F5 plan §3).
5
+ *
6
+ * The blog's keys live only in this closure: the reader-proxy key (a PUBLIC
7
+ * service key — session calls, the public config, link requests) and the
8
+ * adapter key (`consultations:ingest:contact_form` — the contact form only).
9
+ * Each goes only into the `Authorization` header of its own kind of call; no
10
+ * handler ever puts a key, a session, a link token or a JWT into a response
11
+ * body or a log line.
12
+ *
13
+ * A missing key never throws: the pages are dark (404) instead, and one
14
+ * console warning says why. The one thing that throws is running it in a
15
+ * browser.
16
+ */
17
+ import { type ConsultationLogger, type ConsultationSiteStatus, type PublicConfigCache } from '../index.js';
18
+ import { type AccessResult, type AttachResult, type ConsultationFeature, type ForgetResult, type ConsultationPageGate, type ContactPageState, type ContactResult, type RequestLinkResult, type SessionActionResult, type SessionPageState } from './context.js';
19
+ import type { ConsultationHttp, ConsultationResponse } from './http.js';
20
+ export interface ConsultationServerConfig {
21
+ /** The server-side kb-api base URL: GraphQL at `${kbApiUrl}/graphql`, the adapter at `${kbApiUrl}/consultations/adapter`. */
22
+ kbApiUrl: string;
23
+ /**
24
+ * The blog's own URLs (`parseSiteUrls(KB_MANAGED_BLOG_URLS, SITE_URL)`): the
25
+ * pages are live only when the KB's reader site is one of them, and their
26
+ * origins are the Origin allowlist.
27
+ */
28
+ siteUrls: string[];
29
+ /** The PUBLIC reader-proxy service key: session calls, the public config, link requests. Missing → dark. */
30
+ readerProxyKey?: string | null;
31
+ /** The adapter key (scope `consultations:ingest:contact_form`, no ref prefix): the contact form only. Missing → no form. */
32
+ adapterKey?: string | null;
33
+ /** The edge header holding the reader's IP. Default `cf-connecting-ip`; `''` = none (not behind Cloudflare). */
34
+ clientIpHeader?: string;
35
+ /** Origins allowed to POST besides the site URLs' own. */
36
+ allowedOrigins?: string[];
37
+ /** The session cookie's name; must match `^__Host-[A-Za-z0-9_]+$`. Default `__Host-kb_consult`. */
38
+ cookieName?: string;
39
+ /**
40
+ * Cloudflare Turnstile on the contact form. `action` defaults to
41
+ * `consultation_contact`; `failOpen` (default true) lets a question through
42
+ * when Cloudflare cannot be reached — `false` refuses it (`unavailable`).
43
+ */
44
+ turnstile?: {
45
+ siteKey: string;
46
+ secretKey: string;
47
+ action?: string;
48
+ failOpen?: boolean;
49
+ } | null;
50
+ /** The signed-in reader's JWT for `handleAttach`. Default: `Authorization: Bearer <JWT>`. */
51
+ readerToken?: (http: ConsultationHttp) => string | null;
52
+ /** `contactMessage`: the contact form's longest message (default 2000, at most 5000). */
53
+ limits?: {
54
+ contactMessage?: number;
55
+ };
56
+ /** Per KB request (default 10 000 ms). */
57
+ timeoutMs?: number;
58
+ /** Custom fetch for every outbound call (KB and Turnstile); default the global `fetch`, resolved per call. */
59
+ fetch?: typeof fetch;
60
+ /** The clock (tests). */
61
+ now?: () => number;
62
+ /** Idempotency keys the pages are rendered with (tests); default a UUID. */
63
+ randomId?: () => string;
64
+ /** Gets outages and the unexpected only; default one `console.warn` line. */
65
+ logger?: ConsultationLogger;
66
+ }
67
+ export interface ConsultationServer {
68
+ /** Whether this blog serves the reader pages in `locale`, and which (for logs, smoke tests, menus). */
69
+ siteStatus(locale: string): Promise<ConsultationSiteStatus>;
70
+ /**
71
+ * Non-blocking (menus, footers): the status from the memo as it is, or null
72
+ * when nothing is known for `locale` yet; a load starts in the background.
73
+ */
74
+ siteStatus(locale: string, o: {
75
+ peek: true;
76
+ }): Promise<ConsultationSiteStatus | null>;
77
+ siteStatus(locale: string, o?: {
78
+ peek?: boolean;
79
+ }): Promise<ConsultationSiteStatus | null>;
80
+ /** The Origin allowlist the handlers use — for a blog's `/api` proxy: `isAllowedOrigin(http, allowedOrigins())`. */
81
+ allowedOrigins(): readonly string[];
82
+ /** A loader's answer when it needs only the gate: 200, 404 (dark or the feature off) or 503 (`Retry-After: 30`). */
83
+ pageGate(feature: ConsultationFeature, locale: string): Promise<ConsultationPageGate>;
84
+ /** GET `/consultation`: the thread the session cookie opens. */
85
+ loadSession(http: ConsultationHttp): Promise<ConsultationResponse<SessionPageState>>;
86
+ /** POST `/api/consultations/access` (`intent=exchange&token=…`): the link token → the session cookie. */
87
+ handleAccess(http: ConsultationHttp): Promise<ConsultationResponse<AccessResult>>;
88
+ /** POST `/consultation` (`intent` = `reply` | `erase` | `logout`). Works without JavaScript. */
89
+ handleSessionAction(http: ConsultationHttp): Promise<ConsultationResponse<SessionActionResult>>;
90
+ /**
91
+ * POST `/api/consultations/forget`: clear a session cookie the KB no longer
92
+ * accepts (204 no session, 410 cleared, 200 still valid — left alone).
93
+ */
94
+ handleForget(http: ConsultationHttp): Promise<ConsultationResponse<ForgetResult>>;
95
+ /** POST `/api/consultations/attach`: move the session's thread to the signed-in reader's account (their JWT). */
96
+ handleAttach(http: ConsultationHttp): Promise<ConsultationResponse<AttachResult>>;
97
+ /** POST `/consultation/new-link`: e-mail fresh links; the same answer whatever the address. */
98
+ handleRequestLink(http: ConsultationHttp): Promise<ConsultationResponse<RequestLinkResult>>;
99
+ /** GET `/contact`: the form's legal text, its idempotency key and the Turnstile site key. */
100
+ loadContact(http: ConsultationHttp, locale: string): Promise<ConsultationResponse<ContactPageState>>;
101
+ /** POST `/contact`: the question becomes a KB thread (adapter key). */
102
+ handleContact(http: ConsultationHttp, locale: string): Promise<ConsultationResponse<ContactResult>>;
103
+ /** The server's memo of the KB's public config (identity-free: the proxy key, no reader IP, no JWT). */
104
+ publicConfig: PublicConfigCache;
105
+ }
106
+ export declare function createConsultationServer(c: ConsultationServerConfig): ConsultationServer;
@@ -0,0 +1,122 @@
1
+ import { assertServerOnly as v } from "../../core/server-only.js";
2
+ import { newClientRequestId as k, CONSULTATION_TURNSTILE_ACTION as L, CONTACT_MESSAGE_MAX as M, READER_BODY_MAX as R } from "../routes.js";
3
+ import { ConsultationTransportError as S } from "../outcome.js";
4
+ import { createPublicConfigCache as K } from "../public-config.js";
5
+ import { parseSiteUrls as H } from "../site.js";
6
+ import { DEFAULT_CLIENT_IP_HEADER as x, isHeaderName as D } from "./client-ip.js";
7
+ import { handleContact as F, loadContact as q } from "./contact.js";
8
+ import { hygienicLogger as P, defaultConsultationLogger as $, siteStatusOf as w, gate as G, responseHeaders as f, GATE_RETRY_AFTER_S as E } from "./context.js";
9
+ import { CONSULTATION_SESSION_COOKIE as B, CONSULTATION_COOKIE_NAME_RE as X } from "./cookie.js";
10
+ import { originOf as Y, siteOrigins as z } from "./origin.js";
11
+ import { bearerToken as Z, handleRequestLink as j, handleAttach as J, handleForget as Q, handleSessionAction as V, handleAccess as W, loadSession as ee } from "./session.js";
12
+ import { kbApiBase as te, createKbTransport as re, HEADER_TOKEN_RE as ne } from "./transport.js";
13
+ const oe = 1e4;
14
+ function C(r, t, i) {
15
+ if (typeof r != "string") return null;
16
+ const n = r.trim();
17
+ return n === "" ? null : ne.test(n) ? n : (i(`${t}_invalid`, `[consultations] the ${t} contains characters not allowed in an HTTP header — ignored.`), null);
18
+ }
19
+ function se(r, t) {
20
+ if (!r) return null;
21
+ const i = typeof r.siteKey == "string" ? r.siteKey.trim() : "", n = typeof r.secretKey == "string" ? r.secretKey.trim() : "";
22
+ if (!i || !n)
23
+ return t("turnstile_half", "[consultations] Turnstile needs both a site key and a secret key — the contact form runs without it."), null;
24
+ const l = typeof r.action == "string" && r.action.trim() !== "" ? r.action.trim() : L;
25
+ return { siteKey: i, secretKey: n, action: l, failOpen: r.failOpen !== !1 };
26
+ }
27
+ function Ae(r) {
28
+ v(
29
+ "createConsultationServer",
30
+ "it holds the blog's consultation keys and readers' sessions, which must never reach the browser."
31
+ );
32
+ const t = r ?? {}, i = /* @__PURE__ */ new Set(), n = (e, s) => {
33
+ i.has(e) || (i.add(e), console.warn(s));
34
+ }, l = te(t.kbApiUrl);
35
+ l === null && n("kb_api_url", "[consultations] kbApiUrl is not an absolute http(s) URL — every consultation page answers 503.");
36
+ let u = typeof t.clientIpHeader == "string" ? t.clientIpHeader.trim() : x;
37
+ u !== "" && !D(u) && (n("client_ip_header", "[consultations] clientIpHeader is not an HTTP header name — no edge header is read."), u = "");
38
+ const y = t.cookieName ?? B;
39
+ if (!X.test(y))
40
+ throw new TypeError("[blogmcp-sdk] consultations cookieName must match ^__Host-[A-Za-z0-9_]+$");
41
+ const A = H(Array.isArray(t.siteUrls) ? t.siteUrls : []), b = Array.isArray(t.allowedOrigins) ? t.allowedOrigins : [];
42
+ b.some((e) => Y(e) === null) && n("allowed_origins", "[consultations] an allowedOrigins entry is not an http(s) URL — ignored.");
43
+ const d = t.limits?.contactMessage, I = typeof d == "number" && Number.isInteger(d) && d >= 1 ? Math.min(d, R) : M, T = typeof t.timeoutMs == "number" && Number.isFinite(t.timeoutMs) && t.timeoutMs > 0 ? t.timeoutMs : oe, m = t.now ?? Date.now, _ = () => t.fetch ?? globalThis.fetch, p = P(t.logger ?? $), h = l === null ? null : re({ base: l, fetch: _, timeoutMs: T, now: m }), g = C(t.readerProxyKey, "reader-proxy key", n), N = C(t.adapterKey, "adapter key", n), O = K(
44
+ async (e) => {
45
+ if (!h) throw new S("kbApiUrl is not configured");
46
+ if (!g) throw new S("no reader-proxy key is configured");
47
+ return h.graphql({ token: g, clientIp: null }).consultations.publicConfig(e);
48
+ },
49
+ { now: m, logger: p }
50
+ ), o = {
51
+ transport: h,
52
+ siteUrls: A,
53
+ origins: z(A, b),
54
+ proxyKey: g,
55
+ adapterKey: N,
56
+ clientIpHeader: u,
57
+ cookieName: y,
58
+ turnstile: se(t.turnstile, n),
59
+ readerToken: typeof t.readerToken == "function" ? t.readerToken : Z,
60
+ contactMessageMax: I,
61
+ timeoutMs: T,
62
+ fetch: _,
63
+ now: m,
64
+ randomId: typeof t.randomId == "function" ? t.randomId : k,
65
+ publicConfig: O,
66
+ logger: p,
67
+ warnOnce: n
68
+ }, a = (e, s, c) => async (...U) => {
69
+ try {
70
+ return await s(...U);
71
+ } catch {
72
+ return p({ op: e, outcome: "unavailable", kbCode: null, status: null }), { status: 503, headers: f(503), body: c() };
73
+ }
74
+ };
75
+ return {
76
+ siteStatus: ((e, s) => s?.peek ? w(o, e, { peek: !0 }) : w(o, e)),
77
+ allowedOrigins: () => o.origins,
78
+ async pageGate(e, s) {
79
+ const c = await G(o, e, s);
80
+ return c.ok ? { status: 200, headers: f(200) } : c.code === "unavailable" ? { status: 503, headers: f(503, { retryAfterS: c.retryAfterS }) } : { status: 404, headers: f(404) };
81
+ },
82
+ loadSession: a("loadSession", (e) => ee(o, e), () => ({
83
+ state: "error",
84
+ error: "unavailable",
85
+ retryAfterS: E
86
+ })),
87
+ handleAccess: a("access", (e) => W(o, e), () => ({
88
+ success: !1,
89
+ error: "unavailable"
90
+ })),
91
+ handleSessionAction: a("sessionAction", (e) => V(o, e), () => ({
92
+ success: !1,
93
+ error: "unavailable"
94
+ })),
95
+ handleForget: a("forget", (e) => Q(o, e), () => ({
96
+ success: !1,
97
+ error: "unavailable"
98
+ })),
99
+ handleAttach: a("attach", (e) => J(o, e), () => ({
100
+ success: !1,
101
+ error: "unavailable"
102
+ })),
103
+ handleRequestLink: a("requestLink", (e) => j(o, e), () => ({
104
+ done: !1,
105
+ error: "unavailable"
106
+ })),
107
+ loadContact: a(
108
+ "loadContact",
109
+ (e, s) => q(o, e, s),
110
+ () => ({ state: "error", error: "unavailable", retryAfterS: E })
111
+ ),
112
+ handleContact: a(
113
+ "contact",
114
+ (e, s) => F(o, e, s),
115
+ () => ({ done: !1, error: "unavailable", messageId: `blog-contact:${k()}` })
116
+ ),
117
+ publicConfig: O
118
+ };
119
+ }
120
+ export {
121
+ Ae as createConsultationServer
122
+ };
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The anonymous reader's pages: the magic link (`/consultation/open` →
3
+ * `POST /api/consultations/access`), the thread its session opens
4
+ * (`/consultation`), dropping a session the KB no longer accepts
5
+ * (`POST /api/consultations/forget`), attaching that thread to an account, and
6
+ * asking for a fresh link (`/consultation/new-link`). A port of the drhoubicka
7
+ * storefront's `/dotaz*` routes, generalised.
8
+ *
9
+ * Every handler runs in the same order: 1. method, 2. the gate (`dark` → 404
10
+ * `disabled`, `unknown` → 503 `unavailable` with `Retry-After: 30`), 3. the
11
+ * Origin check, 4. the form, 5. the KB call. Nothing here throws.
12
+ *
13
+ * Credentials: the session calls go out with the blog's reader-proxy key and
14
+ * the reader's IP (the key is what makes kb-api believe the IP). Attaching
15
+ * goes out with the reader's own JWT — never the proxy key. The link token
16
+ * and the session only ever travel in a request body to the KB, and the
17
+ * session back to the browser only in `Set-Cookie`.
18
+ */
19
+ import { type AccessResult, type AttachResult, type ForgetResult, type RequestLinkResult, type ServerContext, type SessionActionResult, type SessionPageState } from './context.js';
20
+ import type { ConsultationHttp, ConsultationResponse } from './http.js';
21
+ /** `Authorization: Bearer <token>` → the token, or null. */
22
+ export declare function bearerToken(http: Pick<ConsultationHttp, 'header'>): string | null;
23
+ /** True for a plausible reader address (what the KB would take) — the shared entry's `isReaderEmail`. */
24
+ export declare const isEmailAddress: (value: string) => boolean;
25
+ export declare function loadSession(ctx: ServerContext, http: ConsultationHttp): Promise<ConsultationResponse<SessionPageState>>;
26
+ export declare function handleAccess(ctx: ServerContext, http: ConsultationHttp): Promise<ConsultationResponse<AccessResult>>;
27
+ /**
28
+ * Drop a session cookie the KB no longer accepts. The session page's loader
29
+ * clears such a cookie itself where the framework lets it; a Next Server
30
+ * Component cannot, so its page calls this endpoint instead. It asks the KB
31
+ * exactly what `loadSession` asks and clears the cookie ONLY on an expired or
32
+ * invalid session: a session that is still valid stays, so this can never
33
+ * close a fresh session the reader opened in another tab. Never thread data.
34
+ */
35
+ export declare function handleForget(ctx: ServerContext, http: ConsultationHttp): Promise<ConsultationResponse<ForgetResult>>;
36
+ export declare function handleSessionAction(ctx: ServerContext, http: ConsultationHttp): Promise<ConsultationResponse<SessionActionResult>>;
37
+ export declare function handleAttach(ctx: ServerContext, http: ConsultationHttp): Promise<ConsultationResponse<AttachResult>>;
38
+ export declare function handleRequestLink(ctx: ServerContext, http: ConsultationHttp): Promise<ConsultationResponse<RequestLinkResult>>;
@@ -0,0 +1,210 @@
1
+ import { isReaderEmail as $, NEW_LINK_FIELDS as K, SESSION_FIELDS as b, normalizeBody as W, READER_BODY_MAX as Y, CLIENT_REQUEST_ID_RE as z, CONSULTATION_SECRET_RE as j } from "../routes.js";
2
+ import { consultationOutcomeOf as Q } from "../outcome.js";
3
+ import { isPost as C, respond as c, gate as v, readForm as B, fieldOf as k, readerIp as w, kbClient as G, logFailure as y, kbFailureOf as J, blogKeyFailure as _, freshKey as D, isGet as H, withRetry as A, statusOf as E, GET_ONLY as V, POST_ONLY as N } from "./context.js";
4
+ import { readSessionCookie as q, sessionCookie as Z, clearedCookie as x } from "./cookie.js";
5
+ import { isAllowedOrigin as O } from "./origin.js";
6
+ const ee = /^[\w-]+\.[\w-]+\.[\w-]+$/, re = 4096, ne = /* @__PURE__ */ new Set(["reply", "erase", "logout"]);
7
+ function le(e) {
8
+ let r;
9
+ try {
10
+ r = e.header("authorization");
11
+ } catch {
12
+ return null;
13
+ }
14
+ const n = typeof r == "string" ? /^Bearer\s+(\S+)\s*$/i.exec(r) : null;
15
+ return n ? n[1] : null;
16
+ }
17
+ const oe = $;
18
+ function S(e, r) {
19
+ try {
20
+ r.setCookie(x(e.cookieName));
21
+ } catch {
22
+ }
23
+ }
24
+ function T(e) {
25
+ const r = e;
26
+ if (r && typeof r == "object" && r.success === !0) return null;
27
+ if (!r || typeof r != "object" || typeof r.success != "boolean")
28
+ return { code: "unavailable", kbCode: null, status: null };
29
+ const n = typeof r.code == "string" ? r.code : null;
30
+ return { code: Q(n), kbCode: n, status: null };
31
+ }
32
+ async function m(e, r, n, t) {
33
+ const s = G(e, { token: e.proxyKey, clientIp: n });
34
+ if (!s) {
35
+ const o = { code: "unavailable", kbCode: null, status: null };
36
+ return y(e, r, o), { ok: !1, failure: o };
37
+ }
38
+ try {
39
+ return { ok: !0, value: await t(s) };
40
+ } catch (o) {
41
+ const i = _(J(o));
42
+ return y(e, r, i), { ok: !1, failure: i };
43
+ }
44
+ }
45
+ function M(e) {
46
+ const r = e;
47
+ return !!r && typeof r == "object" && typeof r.id == "string" && Array.isArray(r.messages);
48
+ }
49
+ async function ce(e, r) {
50
+ const n = (i, a, u) => c(E(i), A({ state: "error", error: i }, a), {
51
+ retryAfterS: a,
52
+ allow: u
53
+ });
54
+ if (!H(r)) return n("method", void 0, V);
55
+ const t = await v(e, "magicLink");
56
+ if (!t.ok) return n(t.code, t.retryAfterS);
57
+ const s = q(r, e.cookieName);
58
+ if (!s) return c(200, { state: "none" });
59
+ const o = await m(e, "bySession", w(e, r), (i) => i.consultationSession.get(s));
60
+ return o.ok ? M(o.value) ? c(200, { state: "open", consultation: o.value, clientRequestId: D(e) }) : (y(e, "bySession", { code: "unavailable", kbCode: null, status: null }), n("unavailable")) : o.failure.code === "expired" ? (S(e, r), c(200, { state: "expired" })) : n(o.failure.code, o.failure.retryAfterS);
61
+ }
62
+ async function fe(e, r) {
63
+ const n = (l, f, p) => c(E(l), A({ success: !1, error: l }, f), {
64
+ retryAfterS: f,
65
+ allow: p
66
+ });
67
+ if (!C(r)) return n("method", void 0, N);
68
+ const t = await v(e, "magicLink");
69
+ if (!t.ok) return n(t.code, t.retryAfterS);
70
+ if (!O(r, e.origins)) return n("origin");
71
+ const s = await B(r);
72
+ if (!s || k(s, b.intent) !== "exchange") return n("invalid");
73
+ const o = k(s, b.token);
74
+ if (typeof o != "string" || !j.test(o)) return n("invalid");
75
+ const i = await m(e, "exchange", w(e, r), (l) => l.consultationSession.exchange(o));
76
+ if (!i.ok) return n(i.failure.code, i.failure.retryAfterS);
77
+ const a = T(i.value);
78
+ if (a) {
79
+ const l = _(a);
80
+ return y(e, "exchange", l), n(l.code);
81
+ }
82
+ const u = i.value.session;
83
+ if (typeof u != "string" || !j.test(u))
84
+ return y(e, "exchange", { code: "unavailable", kbCode: null, status: null }), n("unavailable");
85
+ try {
86
+ r.setCookie(Z(e.cookieName, u, i.value.expiresAt, e.now()));
87
+ } catch {
88
+ return y(e, "exchange", { code: "unavailable", kbCode: null, status: null }), n("unavailable");
89
+ }
90
+ return c(200, { success: !0 });
91
+ }
92
+ async function de(e, r) {
93
+ const n = (i, a, u) => c(E(i), A({ success: !1, error: i }, a), {
94
+ retryAfterS: a,
95
+ allow: u
96
+ });
97
+ if (!C(r)) return n("method", void 0, N);
98
+ const t = await v(e, "magicLink");
99
+ if (!t.ok) return n(t.code, t.retryAfterS);
100
+ if (!O(r, e.origins)) return n("origin");
101
+ const s = q(r, e.cookieName);
102
+ if (!s) return c(204, null);
103
+ const o = await m(e, "forget", w(e, r), (i) => i.consultationSession.get(s));
104
+ return o.ok ? M(o.value) ? c(200, null) : (y(e, "forget", { code: "unavailable", kbCode: null, status: null }), n("unavailable")) : o.failure.code === "expired" ? (S(e, r), n("expired")) : n(o.failure.code, o.failure.retryAfterS);
105
+ }
106
+ async function ye(e, r) {
107
+ const n = (d, g = {}) => c(
108
+ E(d),
109
+ A({ success: !1, error: d, ...g.echo ?? {} }, g.retryAfterS),
110
+ { retryAfterS: g.retryAfterS, allow: g.allow }
111
+ ), t = () => (S(e, r), c(200, { success: !0, done: "loggedOut" }));
112
+ if (!C(r)) return n("method", { allow: N });
113
+ const s = await v(e, "magicLink");
114
+ if (!s.ok && s.code === "disabled") return n("disabled");
115
+ const o = O(r, e.origins);
116
+ if (s.ok && !o) return n("origin");
117
+ const i = o ? await B(r) : null, a = i ? k(i, b.intent) : void 0;
118
+ if (!s.ok)
119
+ return i && a === "logout" ? t() : n(s.code, { retryAfterS: s.retryAfterS, echo: i && a === "reply" ? P(e, i) : void 0 });
120
+ if (!i || typeof a != "string" || !ne.has(a)) return n("invalid");
121
+ const u = w(e, r), l = q(r, e.cookieName);
122
+ if (a === "logout")
123
+ return l && await m(e, "closeSession", u, (d) => d.consultationSession.close(l)), t();
124
+ if (a === "reply") {
125
+ const d = P(e, i), g = W(k(i, b.body), Y);
126
+ if (!g.ok) return n(g.code, { echo: d });
127
+ const R = k(i, b.clientRequestId);
128
+ if (typeof R != "string" || !z.test(R)) return n("invalid", { echo: d });
129
+ if (!l) return n("expired", { echo: d });
130
+ const I = await m(
131
+ e,
132
+ "postBySession",
133
+ u,
134
+ (X) => X.consultationSession.post(l, { body: g.body, clientRequestId: R })
135
+ ), F = I.ok ? T(I.value) : I.failure;
136
+ if (!F) return c(200, { success: !0, done: "posted" });
137
+ const h = I.ok ? _(F) : F;
138
+ I.ok && y(e, "postBySession", h), h.code === "expired" && S(e, r);
139
+ const U = h.code === "conflict" ? D(e) : R;
140
+ return n(h.code, { retryAfterS: h.retryAfterS, echo: { body: d.body, clientRequestId: U } });
141
+ }
142
+ if (!l) return n("expired");
143
+ const f = await m(e, "erasureBySession", u, (d) => d.consultationSession.requestErasure(l)), p = f.ok ? T(f.value) : f.failure;
144
+ if (!p)
145
+ return S(e, r), c(200, { success: !0, done: "erased" });
146
+ const L = f.ok ? _(p) : p;
147
+ return f.ok && y(e, "erasureBySession", L), L.code === "expired" && S(e, r), n(L.code, { retryAfterS: L.retryAfterS });
148
+ }
149
+ function P(e, r) {
150
+ const n = W(k(r, b.body), Y), t = k(r, b.clientRequestId);
151
+ return {
152
+ body: n.body,
153
+ clientRequestId: typeof t == "string" && z.test(t) ? t : D(e)
154
+ };
155
+ }
156
+ async function ke(e, r) {
157
+ const n = (u, l, f) => c(E(u), A({ success: !1, error: u }, l), {
158
+ retryAfterS: l,
159
+ allow: f
160
+ });
161
+ if (!C(r)) return n("method", void 0, N);
162
+ const t = await v(e, "magicLink");
163
+ if (!t.ok) return n(t.code, t.retryAfterS);
164
+ if (!O(r, e.origins)) return n("origin");
165
+ const s = q(r, e.cookieName);
166
+ if (!s) return n("expired");
167
+ let o;
168
+ try {
169
+ o = e.readerToken(r);
170
+ } catch {
171
+ o = null;
172
+ }
173
+ if (typeof o != "string" || o.length > re || !ee.test(o)) return n("auth");
174
+ const i = G(e, { token: o, clientIp: w(e, r) });
175
+ if (!i)
176
+ return y(e, "attach", { code: "unavailable", kbCode: null, status: null }), n("unavailable");
177
+ let a;
178
+ try {
179
+ a = T(await i.consultationSession.attach(s));
180
+ } catch (u) {
181
+ a = J(u);
182
+ }
183
+ return a ? (y(e, "attach", a), a.code === "expired" && S(e, r), n(a.code, a.retryAfterS)) : (S(e, r), c(200, { success: !0, done: "attached" }));
184
+ }
185
+ async function ge(e, r) {
186
+ const n = (u, l, f) => c(E(u), A({ done: !1, error: u }, l), {
187
+ retryAfterS: l,
188
+ allow: f
189
+ }), t = () => c(200, { done: !0 });
190
+ if (!C(r)) return n("method", void 0, N);
191
+ const s = await v(e, "newLink");
192
+ if (!s.ok) return n(s.code, s.retryAfterS);
193
+ if (!O(r, e.origins)) return n("origin");
194
+ const o = await B(r);
195
+ if (!o) return n("invalid");
196
+ const i = k(o, K.honeypot);
197
+ if (typeof i == "string" && i !== "") return t();
198
+ const a = (k(o, K.email) ?? "").trim();
199
+ return oe(a) ? (await m(e, "requestLink", w(e, r), (u) => u.consultationSession.requestLink(a)), t()) : n("invalid");
200
+ }
201
+ export {
202
+ le as bearerToken,
203
+ fe as handleAccess,
204
+ ke as handleAttach,
205
+ de as handleForget,
206
+ ge as handleRequestLink,
207
+ ye as handleSessionAction,
208
+ oe as isEmailAddress,
209
+ ce as loadSession
210
+ };
@@ -0,0 +1,69 @@
1
+ /**
2
+ * How the consultation server talks to kb-api: a status-checking GraphQL
3
+ * transport and the per-request clients built on it.
4
+ *
5
+ * Why not the SDK's default fetcher: it never looks at the HTTP status. kb-api's
6
+ * rate limiter answers 429 with a JSON body that has no `errors`, so the default
7
+ * transport hands back `undefined` and a reader page shows "not found" where the
8
+ * truth is "the KB is busy, retry in N seconds". Here every way the KB can fail
9
+ * to answer — network, timeout, HTTP 5xx or 429 without a code, a body that is
10
+ * not JSON — is a `ConsultationTransportError` with the status and the
11
+ * `Retry-After`, which the handlers turn into `unavailable` (503). A GraphQL
12
+ * `errors` answer is left to the SDK client, which throws `KbGraphQLError` with
13
+ * the code.
14
+ *
15
+ * Every request: `redirect: 'error'` (following a redirect would re-send the key
16
+ * to wherever it points), `cache: 'no-store'` (a reader's thread must never sit
17
+ * in a fetch cache — Next's data cache included) and a timeout.
18
+ *
19
+ * Clients are built per request: the credential and the reader's IP differ per
20
+ * call, so a module-level client would carry one reader's identity into
21
+ * another's request.
22
+ */
23
+ import { type KbClient } from '../../core/client.js';
24
+ import type { Fetcher } from '../../core/client-types.js';
25
+ import { type ConsultationAdapterClient } from '../../core/consultation-adapter.js';
26
+ /** A key or token that is safe as an HTTP header value (visible ASCII, no whitespace). */
27
+ export declare const HEADER_TOKEN_RE: RegExp;
28
+ /**
29
+ * The kb-api base URL (`http://kb-api:5070`, `https://tenant.example/api`)
30
+ * without a trailing slash, or null when it is not an absolute http(s) URL
31
+ * without a query or fragment.
32
+ */
33
+ export declare function kbApiBase(value: unknown): string | null;
34
+ /**
35
+ * Seconds until a retry can succeed: `Retry-After` (seconds or an HTTP date),
36
+ * else the `reset` of the draft-7 `RateLimit` header kb-api's limiter sends
37
+ * (`limit=200, remaining=0, reset=37`). Null when neither says.
38
+ */
39
+ export declare function retryAfterSeconds(headers: Pick<Headers, 'get'>, now?: number): number | null;
40
+ export interface KbTransportOptions {
41
+ /** The kb-api base URL, already normalised (`kbApiBase`). */
42
+ base: string;
43
+ /** Resolved per call, so a test spy or a framework-patched global fetch is honoured. */
44
+ fetch: () => typeof fetch;
45
+ timeoutMs: number;
46
+ now: () => number;
47
+ }
48
+ /** The status-checking GraphQL transport (see the module doc). */
49
+ export declare function createKbFetcher(o: KbTransportOptions): Fetcher;
50
+ export interface KbTransport {
51
+ /**
52
+ * A GraphQL client for one call: `token` goes into `Authorization` (the
53
+ * reader-proxy key, or a reader's JWT), `clientIp` into
54
+ * `X-Blogmcp-Client-Ip` (omitted when null).
55
+ */
56
+ graphql(o: {
57
+ token: string | null;
58
+ clientIp: string | null;
59
+ }): KbClient;
60
+ /**
61
+ * The adapter client for one ingest, and the `Retry-After` of its last
62
+ * response (the adapter client does not keep it).
63
+ */
64
+ adapter(apiKey: string): {
65
+ client: ConsultationAdapterClient;
66
+ retryAfterS(): number | null;
67
+ };
68
+ }
69
+ export declare function createKbTransport(o: KbTransportOptions): KbTransport;
@@ -0,0 +1,117 @@
1
+ import { createKbClient as f } from "../../core/client.js";
2
+ import { createConsultationAdapterClient as d } from "../../core/consultation-adapter.js";
3
+ import { ConsultationTransportError as a } from "../outcome.js";
4
+ import { KB_CLIENT_IP_HEADER as m } from "./client-ip.js";
5
+ const k = /^[\x21-\x7E]+$/, p = 600;
6
+ function K(t) {
7
+ if (typeof t != "string" || t.trim() === "") return null;
8
+ try {
9
+ const r = new URL(t.trim());
10
+ return r.protocol !== "http:" && r.protocol !== "https:" || r.search || r.hash ? null : r.origin + r.pathname.replace(/\/+$/, "");
11
+ } catch {
12
+ return null;
13
+ }
14
+ }
15
+ function u(t, r = Date.now()) {
16
+ let n = null;
17
+ const e = t.get("retry-after")?.trim();
18
+ if (e)
19
+ if (/^\d+$/.test(e)) n = Number(e);
20
+ else {
21
+ const o = Date.parse(e);
22
+ Number.isNaN(o) || (n = Math.max(0, Math.ceil((o - r) / 1e3)));
23
+ }
24
+ if (n === null) {
25
+ const o = /(?:^|[\s,;])reset=(\d+)/.exec(t.get("ratelimit") ?? "");
26
+ o && (n = Number(o[1]));
27
+ }
28
+ return n === null ? null : Math.min(n, p);
29
+ }
30
+ function i(t) {
31
+ return typeof t == "object" && t !== null && !Array.isArray(t);
32
+ }
33
+ function w(t, r) {
34
+ return !i(t) || !Array.isArray(t.errors) || t.errors.length === 0 ? !1 : r >= 400 && r < 500 && r !== 429 ? !0 : t.errors.some(
35
+ (n) => i(n) && i(n.extensions) && n.extensions.code === "QUOTA_EXCEEDED"
36
+ );
37
+ }
38
+ function y(t) {
39
+ return async (r, n) => {
40
+ let e;
41
+ try {
42
+ e = await t.fetch()(r, {
43
+ method: n.method,
44
+ headers: n.headers,
45
+ body: n.body,
46
+ redirect: "error",
47
+ cache: "no-store",
48
+ signal: AbortSignal.timeout(t.timeoutMs)
49
+ });
50
+ } catch {
51
+ throw new a("KB request failed (network error or timeout)");
52
+ }
53
+ let o;
54
+ try {
55
+ o = await e.text();
56
+ } catch {
57
+ throw new a(`KB answered HTTP ${e.status} with an unreadable body`, {
58
+ status: e.status
59
+ });
60
+ }
61
+ let s;
62
+ try {
63
+ s = JSON.parse(o);
64
+ } catch {
65
+ s = void 0;
66
+ }
67
+ if (!e.ok) {
68
+ if (w(s, e.status)) return s;
69
+ throw new a(`KB answered HTTP ${e.status}`, {
70
+ status: e.status,
71
+ retryAfterS: u(e.headers, t.now())
72
+ });
73
+ }
74
+ if (!i(s))
75
+ throw new a("KB answered with a body that is not a GraphQL response", {
76
+ status: e.status
77
+ });
78
+ return s;
79
+ };
80
+ }
81
+ function A(t) {
82
+ return { getToken: () => t, setToken: () => {
83
+ }, removeToken: () => {
84
+ } };
85
+ }
86
+ function S(t) {
87
+ const r = y(t), n = `${t.base}/graphql`;
88
+ return {
89
+ graphql: ({ token: e, clientIp: o }) => f({
90
+ endpoint: n,
91
+ isServer: !0,
92
+ fetcher: r,
93
+ tokenStorage: A(e),
94
+ headers: o ? { [m]: o } : void 0
95
+ }),
96
+ adapter: (e) => {
97
+ let o = null;
98
+ const s = async (l, h) => {
99
+ const c = await t.fetch()(l, { ...h, cache: "no-store" });
100
+ return o = c.ok ? null : u(c.headers, t.now()), c;
101
+ };
102
+ return { client: d({
103
+ baseUrl: t.base,
104
+ apiKey: e,
105
+ fetch: s,
106
+ timeoutMs: t.timeoutMs
107
+ }), retryAfterS: () => o };
108
+ }
109
+ };
110
+ }
111
+ export {
112
+ k as HEADER_TOKEN_RE,
113
+ y as createKbFetcher,
114
+ S as createKbTransport,
115
+ K as kbApiBase,
116
+ u as retryAfterSeconds
117
+ };