@blogmcp/sdk 0.6.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) 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/auth.js +21 -21
  49. package/dist/core/client.d.ts +25 -4
  50. package/dist/core/client.js +35 -30
  51. package/dist/core/consultation-adapter.d.ts +2 -2
  52. package/dist/core/consultations.d.ts +1 -1
  53. package/dist/core/errors.d.ts +1 -1
  54. package/dist/core/errors.js +16 -15
  55. package/dist/core/index.d.ts +31 -31
  56. package/dist/core/index.js +35 -34
  57. package/dist/core/markdown.d.ts +1 -1
  58. package/dist/core/queries.d.ts +4 -1
  59. package/dist/core/queries.js +131 -86
  60. package/dist/core/review/format.d.ts +1 -1
  61. package/dist/core/review/index.d.ts +2 -2
  62. package/dist/core/seo.d.ts +1 -1
  63. package/dist/core/translations/cs.json.js +1 -1
  64. package/dist/core/translations/en.json.js +1 -1
  65. package/dist/core/types.d.ts +50 -1
  66. package/dist/core/view-model.d.ts +12 -2
  67. package/dist/core/view-model.js +40 -34
  68. package/dist/{packages/tripmap-core/node_modules → node_modules}/pmtiles/dist/esm/index.js +1 -1
  69. package/dist/nuxt/composables/useAsyncKb.d.ts +4 -4
  70. package/dist/nuxt/index.d.ts +1 -1
  71. package/dist/packages/tripmap-core/dist/engine.js +3 -3
  72. package/dist/packages/tripmap-core/dist/generated/maplibre-worker.bundle.js +1 -1
  73. package/dist/react/KbMdxContent.d.ts +1 -1
  74. package/dist/react/context.d.ts +4 -4
  75. package/dist/react/hooks/useImageRenderer.d.ts +1 -1
  76. package/dist/react/hooks/useKbClient.d.ts +1 -1
  77. package/dist/react/hooks/useKbContext.d.ts +1 -1
  78. package/dist/react/hooks/useKbI18n.d.ts +1 -1
  79. package/dist/react/hooks/useKbLanguage.d.ts +1 -1
  80. package/dist/react/hooks/useKbSearch.d.ts +1 -1
  81. package/dist/react/hooks/useMdxContent.d.ts +1 -1
  82. package/dist/react/index.d.ts +15 -15
  83. package/dist/react/provider.d.ts +2 -2
  84. package/dist/react/server/index.d.ts +2 -2
  85. package/dist/vue/components/KbAccessGate.vue.d.ts +4 -1
  86. package/dist/vue/components/KbAccessGate.vue.js +42 -32
  87. package/dist/vue/components/KbArticleCard.vue.d.ts +3 -1
  88. package/dist/vue/components/KbArticleCard.vue.js +67 -39
  89. package/dist/vue/composables/useArticles.d.ts +1 -1
  90. package/dist/vue/composables/useImageRenderer.d.ts +1 -1
  91. package/dist/vue/composables/useKbAuth.d.ts +1 -1
  92. package/dist/vue/composables/useKbClient.d.ts +1 -1
  93. package/dist/vue/composables/useKbComments.d.ts +1 -1
  94. package/dist/vue/composables/useKbI18n.d.ts +1 -1
  95. package/dist/vue/composables/useKbLanguage.d.ts +1 -1
  96. package/dist/vue/composables/useNavigation.d.ts +1 -1
  97. package/dist/vue/composables/useSearch.d.ts +1 -1
  98. package/dist/vue/composables/useTags.d.ts +1 -1
  99. package/dist/vue/index.d.ts +19 -19
  100. package/dist/vue/plugin.d.ts +4 -4
  101. package/package.json +15 -5
  102. package/src/consultations/channel-text.ts +168 -0
  103. package/src/consultations/index.ts +87 -0
  104. package/src/consultations/messages.cs.ts +175 -0
  105. package/src/consultations/messages.en.ts +171 -0
  106. package/src/consultations/messages.ts +91 -0
  107. package/src/consultations/outcome.ts +278 -0
  108. package/src/consultations/public-config.ts +246 -0
  109. package/src/consultations/reader.ts +281 -0
  110. package/src/consultations/routes.ts +341 -0
  111. package/src/consultations/server/client-ip.ts +106 -0
  112. package/src/consultations/server/contact.ts +267 -0
  113. package/src/consultations/server/context.ts +403 -0
  114. package/src/consultations/server/cookie.ts +129 -0
  115. package/src/consultations/server/env.ts +66 -0
  116. package/src/consultations/server/http.ts +148 -0
  117. package/src/consultations/server/index.ts +55 -0
  118. package/src/consultations/server/origin.ts +71 -0
  119. package/src/consultations/server/server.ts +322 -0
  120. package/src/consultations/server/session.ts +414 -0
  121. package/src/consultations/server/transport.ts +196 -0
  122. package/src/consultations/server/turnstile.ts +98 -0
  123. package/src/consultations/site.ts +183 -0
  124. package/src/consultations/submit-new.ts +266 -0
  125. package/src/core/auth.ts +5 -1
  126. package/src/core/client.ts +32 -1
  127. package/src/core/errors.ts +5 -2
  128. package/src/core/index.ts +3 -0
  129. package/src/core/queries.ts +56 -0
  130. package/src/core/translations/cs.json +2 -1
  131. package/src/core/translations/en.json +2 -1
  132. package/src/core/types.ts +51 -0
  133. package/src/core/view-model.ts +18 -0
  134. package/src/vue/components/KbAccessGate.vue +14 -1
  135. package/src/vue/components/KbArticleCard.vue +25 -0
  136. /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl-shared.js +0 -0
  137. /package/dist/{packages/tripmap-core/node_modules → node_modules}/maplibre-gl/dist/maplibre-gl.js +0 -0
@@ -0,0 +1,152 @@
1
+ import { LOCALE_RE as d, newClientRequestId as p, CLIENT_REQUEST_ID_RE as y } from "../routes.js";
2
+ import { CONSULTATION_RESPONSE_HEADERS as O, consultationFailureOf as E, CONSULTATION_UI_HTTP_STATUS as m, ConsultationTransportError as _ } from "../outcome.js";
3
+ import { readerSiteStatus as c } from "../site.js";
4
+ import { isKbGraphQLError as T } from "../../core/errors.js";
5
+ import { clientIpFrom as g } from "./client-ip.js";
6
+ const l = "en", f = 30, P = "contact_form", b = Object.freeze({ enabled: !1 });
7
+ function C(t) {
8
+ return t === "unavailable" || t === "submit";
9
+ }
10
+ function A(t) {
11
+ return t instanceof _ || t instanceof Error && t.name === "ConsultationTransportError" && "retryAfterS" in t;
12
+ }
13
+ const k = /^[A-Z][A-Z0-9_]{0,63}$/, K = (t) => {
14
+ console.warn(
15
+ `[consultations] op=${t.op} outcome=${t.outcome} kb_code=${t.kbCode ?? "none"} status=${t.status ?? "none"}`
16
+ );
17
+ };
18
+ function F(t) {
19
+ return (e) => {
20
+ if (!C(e.outcome)) return;
21
+ const o = typeof e.kbCode == "string" ? k.test(e.kbCode) ? e.kbCode : "other" : null, n = typeof e.status == "number" && Number.isInteger(e.status) ? e.status : null;
22
+ try {
23
+ t({ op: String(e.op).replace(/[^A-Za-z0-9_.-]/g, "").slice(0, 40), outcome: e.outcome, kbCode: o, status: n });
24
+ } catch {
25
+ }
26
+ };
27
+ }
28
+ const h = Object.freeze({ ok: !1, code: "unavailable" });
29
+ async function S(t, e, o = {}) {
30
+ const n = typeof e == "string" && d.test(e), s = n ? e : l, u = { siteUrls: t.siteUrls, readerProxyKey: t.proxyKey !== null, adapterKey: t.adapterKey !== null, locale: s };
31
+ if (t.proxyKey === null)
32
+ return t.warnOnce(
33
+ "proxy_key",
34
+ "[consultations] no reader-proxy key (CONSULTATIONS_READER_PROXY_KEY) — the reader consultation pages stay dark (404)."
35
+ ), c(h, u);
36
+ let r;
37
+ if (o.peek) {
38
+ const i = t.publicConfig.peek(s);
39
+ if (t.publicConfig.get(s).catch(() => {
40
+ t.warnOnce("peek_load", "[consultations] a background public-config load failed unexpectedly.");
41
+ }), !i) return null;
42
+ r = i;
43
+ } else
44
+ r = await t.publicConfig.get(s);
45
+ const a = c(r, u);
46
+ return a.state === "live" && t.adapterKey === null && r.ok && r.value.emailNotices && t.warnOnce(
47
+ "adapter_key",
48
+ "[consultations] no adapter key (CONSULTATIONS_ADAPTER_KEY) — the contact form stays off (404)."
49
+ ), !n && a.features.contactForm ? Object.freeze({
50
+ ...a,
51
+ features: Object.freeze({ ...a.features, contactForm: !1 }),
52
+ contactText: b
53
+ }) : a;
54
+ }
55
+ async function U(t, e, o = l) {
56
+ const n = await S(t, o);
57
+ return n.state === "unknown" ? { ok: !1, code: "unavailable", retryAfterS: f } : n.state !== "live" || n.features[e] !== !0 ? { ok: !1, code: "disabled" } : { ok: !0, status: n };
58
+ }
59
+ function N(t, e = {}) {
60
+ const o = { ...O };
61
+ return (t === 503 || t === 429 && e.retryAfterS !== void 0) && (o["Retry-After"] = String(Math.max(1, e.retryAfterS ?? f))), e.allow && (o.Allow = e.allow), o;
62
+ }
63
+ function G(t, e, o = {}) {
64
+ return { status: t, headers: N(t, o), body: e };
65
+ }
66
+ function D(t) {
67
+ return m[t] ?? 502;
68
+ }
69
+ function H(t, e) {
70
+ return e === void 0 ? t : { ...t, retryAfterS: e };
71
+ }
72
+ const Y = "POST", j = "GET, HEAD";
73
+ function z(t) {
74
+ return typeof t.method == "string" && t.method.toUpperCase() === "POST";
75
+ }
76
+ function $(t) {
77
+ const e = typeof t.method == "string" ? t.method.toUpperCase() : "";
78
+ return e === "GET" || e === "HEAD";
79
+ }
80
+ async function q(t) {
81
+ try {
82
+ const e = await t.form();
83
+ return e && typeof e == "object" ? e : null;
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+ function X(t, e) {
89
+ if (!Object.prototype.hasOwnProperty.call(t, e)) return;
90
+ const o = t[e];
91
+ return typeof o == "string" ? o : void 0;
92
+ }
93
+ function Z(t, e) {
94
+ const o = g(e, { header: t.clientIpHeader });
95
+ return o === null && t.warnOnce(
96
+ "client_ip",
97
+ "[consultations] a reader request without a client IP (no valid edge header or X-Forwarded-For) — the KB's per-IP quotas count the blog server's own IP instead. Check CONSULTATIONS_CLIENT_IP_HEADER and the reverse-proxy configuration."
98
+ ), o;
99
+ }
100
+ function B(t) {
101
+ let e;
102
+ try {
103
+ e = t.randomId();
104
+ } catch {
105
+ e = null;
106
+ }
107
+ return typeof e == "string" && y.test(e) ? e : p();
108
+ }
109
+ function M(t, e) {
110
+ return t.transport ? t.transport.graphql(e) : null;
111
+ }
112
+ function Q(t) {
113
+ return {
114
+ ...E(t),
115
+ kbCode: T(t) ? t.code : null,
116
+ status: A(t) ? t.status : null
117
+ };
118
+ }
119
+ function J(t) {
120
+ return t.code === "auth" ? { ...t, code: "unavailable" } : t;
121
+ }
122
+ function V(t, e, o) {
123
+ t.logger({ op: e, outcome: o.code, kbCode: o.kbCode, status: o.status });
124
+ }
125
+ export {
126
+ P as CONTACT_FORM_CHANNEL,
127
+ l as GATE_LOCALE,
128
+ f as GATE_RETRY_AFTER_S,
129
+ j as GET_ONLY,
130
+ b as NO_TEXT,
131
+ Y as POST_ONLY,
132
+ J as blogKeyFailure,
133
+ K as defaultConsultationLogger,
134
+ X as fieldOf,
135
+ B as freshKey,
136
+ U as gate,
137
+ F as hygienicLogger,
138
+ $ as isGet,
139
+ C as isLoggedOutcome,
140
+ z as isPost,
141
+ A as isTransportError,
142
+ M as kbClient,
143
+ Q as kbFailureOf,
144
+ V as logFailure,
145
+ q as readForm,
146
+ Z as readerIp,
147
+ G as respond,
148
+ N as responseHeaders,
149
+ S as siteStatusOf,
150
+ D as statusOf,
151
+ H as withRetry
152
+ };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The session cookie of a reader who opened a magic link.
3
+ *
4
+ * `__Host-` is enforced by the browser: only with `Secure`, only `Path=/`, no
5
+ * `Domain` — so no sister host can read, overwrite or plant it. `HttpOnly`: the
6
+ * session is a bearer capability (whoever holds it reads the question) and must
7
+ * never reach page JavaScript. `SameSite=Lax`: it comes along with a click from
8
+ * the mail client, never with a cross-site POST.
9
+ *
10
+ * Clearing a cookie is a full `Set-Cookie` with `Max-Age=0` and EVERY attribute.
11
+ * A clear without `Secure` and `Path=/` (Next's `cookies().delete()`) is a
12
+ * different cookie as far as the browser is concerned — it is ignored and the
13
+ * session stays.
14
+ */
15
+ import type { ConsultationHttp } from './http.js';
16
+ /** The default name of the session cookie. */
17
+ export declare const CONSULTATION_SESSION_COOKIE = "__Host-kb_consult";
18
+ /** A configurable cookie name must keep the `__Host-` prefix. */
19
+ export declare const CONSULTATION_COOKIE_NAME_RE: RegExp;
20
+ /** Upper bound on the cookie's life: 12 h, even when the KB keeps the session longer. */
21
+ export declare const CONSULTATION_SESSION_COOKIE_MAX_S: number;
22
+ /** Lower bound: clock skew between the KB and the blog must not make a cookie that is gone at once. */
23
+ export declare const CONSULTATION_SESSION_COOKIE_MIN_S = 60;
24
+ /** A cookie exactly as the consultation pages set it; the attributes are fixed by the type. */
25
+ export interface ConsultationCookie {
26
+ name: string;
27
+ value: string;
28
+ /** Seconds; 0 clears the cookie. */
29
+ maxAge: number;
30
+ path: '/';
31
+ httpOnly: true;
32
+ secure: true;
33
+ sameSite: 'lax';
34
+ }
35
+ /** The session cookie; `Max-Age` = clamp(expiresAt − now, 60 s, 12 h). The KB decides validity; the cookie only carries it. */
36
+ export declare function sessionCookie(name: string, session: string, expiresAt: string | null | undefined, now: number): ConsultationCookie;
37
+ /** The cookie that removes the session from the browser. */
38
+ export declare function clearedCookie(name: string): ConsultationCookie;
39
+ /**
40
+ * `Set-Cookie` value for a consultation cookie. The attributes are always
41
+ * written from the fixed set, whatever the object says. Throws on a name
42
+ * without `__Host-`, a value that is not cookie-safe or a bad `Max-Age` — a
43
+ * programming error; the message never quotes the value (it is a session).
44
+ */
45
+ export declare function serializeConsultationCookie(c: ConsultationCookie): string;
46
+ /**
47
+ * The `Cookie` request header without the consultation cookie — for a blog's
48
+ * `/api` proxy, so the session never travels on to the KB (or into its logs).
49
+ * The name is matched case-insensitively (browsers apply the `__Host-` prefix
50
+ * rules case-insensitively), every other cookie is kept in order.
51
+ */
52
+ export declare function stripConsultationCookie(cookieHeader: string, name?: string): string;
53
+ /** The value of cookie `name` in a `Cookie` header (the first one), or null. */
54
+ export declare function cookieFromHeader(cookieHeader: string | null | undefined, name: string): string | null;
55
+ /**
56
+ * The session from the request's cookie, or null. A value of any other shape
57
+ * than the KB's 43-char base64url secret is not a session at all and never
58
+ * goes to the KB.
59
+ */
60
+ export declare function readSessionCookie(http: Pick<ConsultationHttp, 'cookie'>, name: string): string | null;
@@ -0,0 +1,57 @@
1
+ import { CONSULTATION_SECRET_RE as u } from "../routes.js";
2
+ const l = "__Host-kb_consult", m = /^__Host-[A-Za-z0-9_]+$/, s = 720 * 60, c = 60, f = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;
3
+ function _(t, o, e, n) {
4
+ const r = typeof e == "string" ? Date.parse(e) : Number.NaN, i = Number.isNaN(r) ? s : Math.floor((r - n) / 1e3), a = Math.max(c, Math.min(i, s));
5
+ return { name: t, value: o, maxAge: a, path: "/", httpOnly: !0, secure: !0, sameSite: "lax" };
6
+ }
7
+ function S(t) {
8
+ return { name: t, value: "", maxAge: 0, path: "/", httpOnly: !0, secure: !0, sameSite: "lax" };
9
+ }
10
+ function x(t) {
11
+ if (typeof t?.name != "string" || !m.test(t.name))
12
+ throw new TypeError("[blogmcp-sdk] consultation cookie name must match ^__Host-[A-Za-z0-9_]+$");
13
+ if (typeof t.value != "string" || !f.test(t.value))
14
+ throw new TypeError("[blogmcp-sdk] consultation cookie value is not a valid cookie value");
15
+ if (!Number.isInteger(t.maxAge) || t.maxAge < 0)
16
+ throw new TypeError("[blogmcp-sdk] consultation cookie maxAge must be a non-negative integer");
17
+ return `${t.name}=${t.value}; Max-Age=${t.maxAge}; Path=/; HttpOnly; Secure; SameSite=Lax`;
18
+ }
19
+ function N(t, o = l) {
20
+ if (typeof t != "string" || t === "") return "";
21
+ const e = o.toLowerCase();
22
+ return t.split(";").map((n) => n.trim()).filter((n) => {
23
+ if (n === "") return !1;
24
+ const r = n.indexOf("=");
25
+ return (r < 0 ? n : n.slice(0, r)).trim().toLowerCase() !== e;
26
+ }).join("; ");
27
+ }
28
+ function g(t, o) {
29
+ if (typeof t != "string" || t === "") return null;
30
+ for (const e of t.split(";")) {
31
+ const n = e.indexOf("=");
32
+ if (!(n < 0) && e.slice(0, n).trim() === o)
33
+ return e.slice(n + 1).trim();
34
+ }
35
+ return null;
36
+ }
37
+ function p(t, o) {
38
+ let e;
39
+ try {
40
+ e = t.cookie(o);
41
+ } catch {
42
+ return null;
43
+ }
44
+ return typeof e == "string" && u.test(e) ? e : null;
45
+ }
46
+ export {
47
+ m as CONSULTATION_COOKIE_NAME_RE,
48
+ l as CONSULTATION_SESSION_COOKIE,
49
+ s as CONSULTATION_SESSION_COOKIE_MAX_S,
50
+ c as CONSULTATION_SESSION_COOKIE_MIN_S,
51
+ S as clearedCookie,
52
+ g as cookieFromHeader,
53
+ p as readSessionCookie,
54
+ x as serializeConsultationCookie,
55
+ _ as sessionCookie,
56
+ N as stripConsultationCookie
57
+ };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The consultation server's configuration from the environment — the same
3
+ * names for the managed blog (chart) and a headless kit:
4
+ *
5
+ * {prefix}CONSULTATIONS_READER_PROXY_KEY the PUBLIC reader-proxy service key
6
+ * {prefix}CONSULTATIONS_ADAPTER_KEY the contact form's adapter key
7
+ * {prefix}CONSULTATIONS_CLIENT_IP_HEADER the edge IP header (unset: cf-connecting-ip; empty: none)
8
+ * {prefix}CONSULTATIONS_TURNSTILE_SITE_KEY \ Turnstile on the contact form
9
+ * {prefix}CONSULTATIONS_TURNSTILE_SECRET_KEY / (both, or neither)
10
+ * KB_MANAGED_BLOG_URLS, SITE_URL, NUXT_PUBLIC_SITE_URL the blog's own URLs (their union)
11
+ *
12
+ * `prefix` is `''` for Next and `'NUXT_'` for Nuxt (whose runtime config reads
13
+ * `NUXT_*`). The keys are never PUBLIC: a `NEXT_PUBLIC_CONSULTATIONS_*` or
14
+ * `NUXT_PUBLIC_CONSULTATIONS_*` variable would be bundled into page
15
+ * JavaScript, so its mere presence throws — before anything reads it.
16
+ */
17
+ import type { ConsultationServerConfig } from './server.js';
18
+ export declare function consultationServerEnv(env: Record<string, string | undefined>, o?: {
19
+ prefix?: '' | 'NUXT_';
20
+ }): Omit<ConsultationServerConfig, 'kbApiUrl'>;
@@ -0,0 +1,35 @@
1
+ import { parseSiteUrls as I } from "../site.js";
2
+ const U = ["NEXT_PUBLIC_CONSULTATIONS_", "NUXT_PUBLIC_CONSULTATIONS_"];
3
+ function r(t, o) {
4
+ const e = t[o];
5
+ return typeof e == "string" ? e : void 0;
6
+ }
7
+ function n(t, o) {
8
+ const e = r(t, o)?.trim();
9
+ return e || null;
10
+ }
11
+ function a(t, o = {}) {
12
+ for (const T of Object.keys(t ?? {})) {
13
+ const S = t[T];
14
+ if (typeof S == "string" && S !== "" && U.some((E) => T.startsWith(E)))
15
+ throw new Error(
16
+ `[blogmcp-sdk] ${T} is set — consultation keys are never PUBLIC (a *_PUBLIC_* variable ends up in page JavaScript). Rename it without PUBLIC_ and rotate the key.`
17
+ );
18
+ }
19
+ const e = o.prefix === "NUXT_" ? "NUXT_" : "", _ = n(t, `${e}CONSULTATIONS_TURNSTILE_SITE_KEY`), s = n(t, `${e}CONSULTATIONS_TURNSTILE_SECRET_KEY`);
20
+ _ === null != (s === null) && console.warn(
21
+ `[consultations] only one of ${e}CONSULTATIONS_TURNSTILE_SITE_KEY / _SECRET_KEY is set — the contact form runs without Turnstile.`
22
+ );
23
+ const i = r(t, `${e}CONSULTATIONS_CLIENT_IP_HEADER`);
24
+ return {
25
+ siteUrls: I(r(t, "KB_MANAGED_BLOG_URLS"), r(t, "SITE_URL"), r(t, "NUXT_PUBLIC_SITE_URL")),
26
+ readerProxyKey: n(t, `${e}CONSULTATIONS_READER_PROXY_KEY`),
27
+ adapterKey: n(t, `${e}CONSULTATIONS_ADAPTER_KEY`),
28
+ // Unset: the default edge header. Set but empty: none (a deployment not fronted by Cloudflare).
29
+ ...i !== void 0 ? { clientIpHeader: i.trim() } : {},
30
+ turnstile: _ && s ? { siteKey: _, secretKey: s } : null
31
+ };
32
+ }
33
+ export {
34
+ a as consultationServerEnv
35
+ };
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The one request/response seam between the consultation handlers and a
3
+ * framework. A Nitro (h3) event, a Next server action or route handler, or a
4
+ * plain Web `Request` each become a `ConsultationHttp` in a few lines; the
5
+ * handlers answer with a `ConsultationResponse` the framework writes out.
6
+ *
7
+ * `fromWebRequest` is the ready-made adapter for anything that speaks Web
8
+ * `Request`/`Response` (Next route handlers, Nitro's `toWebRequest`, workers).
9
+ */
10
+ import { type ConsultationCookie } from './cookie.js';
11
+ export interface ConsultationHttp {
12
+ /** The request method, upper case. A server action is always `'POST'`. */
13
+ method: string;
14
+ /** A request header, case-insensitive; null when absent. */
15
+ header(name: string): string | null;
16
+ /** A request cookie; null when absent. */
17
+ cookie(name: string): string | null;
18
+ /**
19
+ * Queue a `Set-Cookie`. May be a no-op where cookies cannot be set (a Next
20
+ * Server Component) — the handlers only ever clear a cookie there, best effort.
21
+ */
22
+ setCookie(c: ConsultationCookie): void;
23
+ /**
24
+ * The posted form: urlencoded or multipart, string fields only; null when the
25
+ * body is not a form (or is too large, or malformed). Called at most once.
26
+ *
27
+ * An adapter MUST enforce what `fromWebRequest` enforces: only
28
+ * `application/x-www-form-urlencoded` and `multipart/form-data`, at most
29
+ * 64 KB (stop reading past it and answer null), files dropped. Extra fields
30
+ * (Next's `$ACTION_*`, a blog's own) may stay: the handlers read only their
31
+ * own field names.
32
+ */
33
+ form(): Promise<Record<string, string> | null>;
34
+ /** Optional: the framework's own idea of the client IP. Still validated as exactly one IP. */
35
+ clientIp?(): string | null;
36
+ }
37
+ /** What a handler answers; `Set-Cookie` travels separately, through `ConsultationHttp.setCookie`. */
38
+ export interface ConsultationResponse<B> {
39
+ status: number;
40
+ headers: Record<string, string>;
41
+ /** JSON; `null` means no body at all (a 204, or a 200 with nothing to say). */
42
+ body: B;
43
+ }
44
+ export interface FromWebRequestOptions {
45
+ /** Largest accepted form body in bytes (default 65 536); a larger one reads as "no form". */
46
+ maxBodyBytes?: number;
47
+ }
48
+ /** Fields of a posted form, string values only (files are dropped); a repeated field keeps its last value. */
49
+ export declare function stringFields(entries: Iterable<[string, unknown]>): Record<string, string>;
50
+ /**
51
+ * A `ConsultationHttp` over a Web `Request`, and `respond` to turn a handler's
52
+ * answer into a `Response` (JSON body, the handler's headers, every queued
53
+ * `Set-Cookie`). Only urlencoded or multipart bodies up to `maxBodyBytes` are
54
+ * read as forms.
55
+ */
56
+ export declare function fromWebRequest(req: Request, o?: FromWebRequestOptions): {
57
+ http: ConsultationHttp;
58
+ respond<B>(r: ConsultationResponse<B>): Response;
59
+ };
@@ -0,0 +1,64 @@
1
+ import { cookieFromHeader as d, serializeConsultationCookie as l } from "./cookie.js";
2
+ const f = 65536, p = /* @__PURE__ */ new Set([101, 103, 204, 205, 304]);
3
+ function u(e) {
4
+ const n = /* @__PURE__ */ Object.create(null);
5
+ for (const [r, o] of e)
6
+ typeof o == "string" && (n[r] = o);
7
+ return n;
8
+ }
9
+ function m(e) {
10
+ return (e ?? "").split(";")[0].trim().toLowerCase();
11
+ }
12
+ function y(e, n) {
13
+ const r = Number(e.headers.get("content-length"));
14
+ if (Number.isFinite(r) && r > n) return null;
15
+ if (!e.body) return "";
16
+ let o = 0;
17
+ return e.body.pipeThrough(
18
+ new TransformStream({
19
+ transform(s, a) {
20
+ o += s.byteLength, o > n ? a.error(new Error("form body too large")) : a.enqueue(s);
21
+ }
22
+ })
23
+ );
24
+ }
25
+ async function h(e, n) {
26
+ const r = e.headers.get("content-type"), o = m(r);
27
+ if (o !== "application/x-www-form-urlencoded" && o !== "multipart/form-data") return null;
28
+ try {
29
+ const s = y(e, n);
30
+ if (s === null) return null;
31
+ const a = new Response(s, { headers: { "content-type": r } });
32
+ if (o === "application/x-www-form-urlencoded")
33
+ return u(new URLSearchParams(await a.text()));
34
+ const t = await a.formData();
35
+ return u(t);
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+ function b(e, n = {}) {
41
+ const r = Math.max(0, n.maxBodyBytes ?? f), o = [];
42
+ let s = null;
43
+ return {
44
+ http: {
45
+ method: e.method.toUpperCase(),
46
+ header: (t) => e.headers.get(t),
47
+ cookie: (t) => d(e.headers.get("cookie"), t),
48
+ setCookie: (t) => {
49
+ o.push(l(t));
50
+ },
51
+ // Memoised: the body stream can be read only once.
52
+ form: () => s ??= h(e, r)
53
+ },
54
+ respond(t) {
55
+ const i = new Headers(t.headers);
56
+ for (const c of o) i.append("Set-Cookie", c);
57
+ return t.body === null || t.body === void 0 || p.has(t.status) ? new Response(null, { status: t.status, headers: i }) : (i.set("Content-Type", "application/json; charset=utf-8"), new Response(JSON.stringify(t.body), { status: t.status, headers: i }));
58
+ }
59
+ };
60
+ }
61
+ export {
62
+ b as fromWebRequest,
63
+ u as stringFields
64
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * `@blogmcp/sdk/consultations/server` — everything of the reader consultation
3
+ * pages that touches a key, a session, a cookie, a reader's IP or Turnstile
4
+ * (docs/internal/reader-consultations.md; the F5 plan §3).
5
+ *
6
+ * SERVER-ONLY: `createConsultationServer` throws when a global `window`
7
+ * exists. Runtime-neutral otherwise — Web `fetch`, `URL`, `crypto`,
8
+ * `AbortSignal.timeout`, no `node:*` — so it runs in Nitro on Bun or Node and
9
+ * in Next on Node.
10
+ *
11
+ * The browser-safe half (routes, codes, messages, the new-question flow) is
12
+ * `@blogmcp/sdk/consultations`.
13
+ *
14
+ * ```ts
15
+ * // Next (App Router): lib/consultations.server.ts
16
+ * import 'server-only'
17
+ * export const consultations = createConsultationServer({
18
+ * kbApiUrl: process.env.KB_API_URL!, ...consultationServerEnv(process.env) })
19
+ * // app/api/consultations/access/route.ts
20
+ * export async function POST(req: Request) {
21
+ * const { http, respond } = fromWebRequest(req)
22
+ * return respond(await consultations.handleAccess(http))
23
+ * }
24
+ * ```
25
+ */
26
+ export { createConsultationServer } from './server.js';
27
+ export type { ConsultationServer, ConsultationServerConfig } from './server.js';
28
+ export type { ConsultationFeature, ConsultationPageGate, SessionPageState, AccessResult, SessionActionResult, ForgetResult, AttachResult, RequestLinkResult, ContactPageState, ContactResult, } from './context.js';
29
+ export { consultationServerEnv } from './env.js';
30
+ export { fromWebRequest } from './http.js';
31
+ export type { ConsultationHttp, ConsultationResponse, FromWebRequestOptions } from './http.js';
32
+ export { CONSULTATION_SESSION_COOKIE, serializeConsultationCookie, stripConsultationCookie } from './cookie.js';
33
+ export type { ConsultationCookie } from './cookie.js';
34
+ export { clientIpFrom } from './client-ip.js';
35
+ export { isAllowedOrigin } from './origin.js';
36
+ export { verifyTurnstile, TURNSTILE_VERIFY_URL } from './turnstile.js';
37
+ export type { TurnstileVerdict, VerifyTurnstileOptions } from './turnstile.js';
@@ -0,0 +1,19 @@
1
+ import { createConsultationServer as e } from "./server.js";
2
+ import { consultationServerEnv as i } from "./env.js";
3
+ import { fromWebRequest as f } from "./http.js";
4
+ import { CONSULTATION_SESSION_COOKIE as m, serializeConsultationCookie as p, stripConsultationCookie as s } from "./cookie.js";
5
+ import { clientIpFrom as C } from "./client-ip.js";
6
+ import { isAllowedOrigin as a } from "./origin.js";
7
+ import { TURNSTILE_VERIFY_URL as I, verifyTurnstile as O } from "./turnstile.js";
8
+ export {
9
+ m as CONSULTATION_SESSION_COOKIE,
10
+ I as TURNSTILE_VERIFY_URL,
11
+ C as clientIpFrom,
12
+ i as consultationServerEnv,
13
+ e as createConsultationServer,
14
+ f as fromWebRequest,
15
+ a as isAllowedOrigin,
16
+ p as serializeConsultationCookie,
17
+ s as stripConsultationCookie,
18
+ O as verifyTurnstile
19
+ };
@@ -0,0 +1,39 @@
1
+ /**
2
+ * CSRF check for every consultation POST: did the request come from one of
3
+ * this blog's own pages? Exported so a blog's `/api` proxy applies the very
4
+ * same rule (`isAllowedOrigin(http, consultations.allowedOrigins())`) instead
5
+ * of a copy.
6
+ *
7
+ * The session cookie is `SameSite=Lax`, which stops a cross-SITE POST by
8
+ * itself. But "site" is the registrable domain: every tenant of a shared
9
+ * domain (`evil.blogmcp.ai` next to `tenant.blogmcp.ai`) is same-site and its
10
+ * pages send the cookie along. `Origin` compares the whole origin, and
11
+ * `Sec-Fetch-Site` (when the browser sends it) must say `same-origin` — so a
12
+ * sister host is stopped here, not by the cookie. `__Host-` stops the other
13
+ * half of that attack: a sister host cannot plant (toss) a cookie with
14
+ * `Domain=.blogmcp.ai` under our name.
15
+ *
16
+ * The allowlist is the origins of the blog's own site URLs plus explicit
17
+ * extras. Nothing is derived from the request: not `Host`, not
18
+ * `X-Forwarded-Host`, not `X-Forwarded-Proto` (behind a TLS-terminating proxy
19
+ * the request URL says `http://`, and trusting it once let a page served on
20
+ * plain `http://` by a network attacker pass the check).
21
+ *
22
+ * A missing `Origin` and the opaque `Origin: null` are refused. Browsers send
23
+ * `Origin` on every POST; the blog's pages answer with `Referrer-Policy:
24
+ * same-origin` (never `no-referrer`, which makes a plain form POST send
25
+ * `Origin: null` even to its own site).
26
+ */
27
+ import type { ConsultationHttp } from './http.js';
28
+ /** The origin of an absolute http(s) URL, or null. */
29
+ export declare function originOf(value: unknown): string | null;
30
+ /** The allowed origins: every site URL's origin plus the explicit extras, deduplicated (junk entries are skipped). */
31
+ export declare function siteOrigins(siteUrls: readonly string[], extra?: readonly string[]): readonly string[];
32
+ /**
33
+ * True when the request carries an `Origin` that is exactly one of `allowed`
34
+ * (not `null`) and, if present, `Sec-Fetch-Site: same-origin`. Browsers
35
+ * serialise `Origin` canonically (lower-case host, no default port, punycode),
36
+ * so the comparison is exact; `allowed` holds origins as `URL.origin` writes
37
+ * them (`ConsultationServer.allowedOrigins()`).
38
+ */
39
+ export declare function isAllowedOrigin(http: Pick<ConsultationHttp, 'header'>, allowed: readonly string[]): boolean;
@@ -0,0 +1,31 @@
1
+ function o(t) {
2
+ if (typeof t != "string" || t.trim() === "") return null;
3
+ try {
4
+ const i = new URL(t.trim());
5
+ return i.protocol === "https:" || i.protocol === "http:" ? i.origin : null;
6
+ } catch {
7
+ return null;
8
+ }
9
+ }
10
+ function s(t, i = []) {
11
+ const r = [];
12
+ for (const e of [...t, ...i]) {
13
+ const n = o(e);
14
+ n && !r.includes(n) && r.push(n);
15
+ }
16
+ return Object.freeze(r);
17
+ }
18
+ function u(t, i) {
19
+ let r, e;
20
+ try {
21
+ r = t.header("origin"), e = t.header("sec-fetch-site");
22
+ } catch {
23
+ return !1;
24
+ }
25
+ return !(typeof r != "string" || r === "" || r === "null" || !Array.isArray(i) || !i.includes(r) || e != null && e.trim().toLowerCase() !== "same-origin");
26
+ }
27
+ export {
28
+ u as isAllowedOrigin,
29
+ o as originOf,
30
+ s as siteOrigins
31
+ };