@blogmcp/sdk 0.12.0 → 0.14.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 (75) hide show
  1. package/dist/community/links.d.ts +6 -0
  2. package/dist/community/links.js +9 -1
  3. package/dist/community/outcome.d.ts +1 -1
  4. package/dist/community/outcome.js +60 -23
  5. package/dist/community/private/browser.d.ts +18 -0
  6. package/dist/community/private/browser.js +17 -0
  7. package/dist/community/private/client.d.ts +259 -0
  8. package/dist/community/private/client.js +98 -0
  9. package/dist/community/private/dm.d.ts +547 -0
  10. package/dist/community/private/dm.js +852 -0
  11. package/dist/community/private/dpop.d.ts +59 -0
  12. package/dist/community/private/dpop.js +46 -0
  13. package/dist/community/private/encoding.d.ts +17 -0
  14. package/dist/community/private/encoding.js +50 -0
  15. package/dist/community/private/host-state.d.ts +20 -0
  16. package/dist/community/private/host-state.js +15 -0
  17. package/dist/community/private/index.d.ts +51 -0
  18. package/dist/community/private/index.js +71 -0
  19. package/dist/community/private/keystore.d.ts +73 -0
  20. package/dist/community/private/keystore.js +91 -0
  21. package/dist/community/private/marker.d.ts +17 -0
  22. package/dist/community/private/marker.js +11 -0
  23. package/dist/community/private/private-routes.d.ts +6 -0
  24. package/dist/community/private/private-routes.js +72 -0
  25. package/dist/community/private/promise.d.ts +65 -0
  26. package/dist/community/private/promise.js +39 -0
  27. package/dist/community/private/realtime.d.ts +127 -0
  28. package/dist/community/private/realtime.js +199 -0
  29. package/dist/community/private/session.d.ts +175 -0
  30. package/dist/community/private/session.js +441 -0
  31. package/dist/community/private/transport.d.ts +47 -0
  32. package/dist/community/private/transport.js +65 -0
  33. package/dist/community/server/grant-handoff.d.ts +53 -0
  34. package/dist/community/server/grant-handoff.js +96 -0
  35. package/dist/community/server/grant.d.ts +100 -0
  36. package/dist/community/server/grant.js +165 -0
  37. package/dist/community/server/index.d.ts +4 -0
  38. package/dist/community/server/index.js +20 -16
  39. package/dist/community/shapes.d.ts +27 -1
  40. package/dist/community/shapes.js +27 -17
  41. package/dist/core/client.d.ts +9 -0
  42. package/dist/core/client.js +54 -50
  43. package/dist/core/index.d.ts +2 -0
  44. package/dist/core/index.js +113 -103
  45. package/dist/core/queries.d.ts +1 -0
  46. package/dist/core/queries.js +76 -71
  47. package/dist/core/review/types.d.ts +7 -0
  48. package/dist/core/style-layers.d.ts +88 -0
  49. package/dist/core/style-layers.js +69 -0
  50. package/package.json +7 -3
  51. package/src/community/links.ts +8 -0
  52. package/src/community/outcome.ts +37 -0
  53. package/src/community/private/browser.ts +31 -0
  54. package/src/community/private/client.ts +304 -0
  55. package/src/community/private/dm.ts +1687 -0
  56. package/src/community/private/dpop.ts +110 -0
  57. package/src/community/private/encoding.ts +71 -0
  58. package/src/community/private/host-state.ts +37 -0
  59. package/src/community/private/index.ts +169 -0
  60. package/src/community/private/keystore.ts +179 -0
  61. package/src/community/private/marker.ts +28 -0
  62. package/src/community/private/private-routes.ts +80 -0
  63. package/src/community/private/promise.ts +125 -0
  64. package/src/community/private/realtime.ts +431 -0
  65. package/src/community/private/session.ts +848 -0
  66. package/src/community/private/transport.ts +125 -0
  67. package/src/community/server/grant-handoff.ts +179 -0
  68. package/src/community/server/grant.ts +292 -0
  69. package/src/community/server/index.ts +6 -0
  70. package/src/community/shapes.ts +46 -1
  71. package/src/core/client.ts +12 -0
  72. package/src/core/index.ts +14 -0
  73. package/src/core/queries.ts +8 -0
  74. package/src/core/review/types.ts +8 -0
  75. package/src/core/style-layers.ts +169 -0
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The private transport (docs/internal/m4-contracts.md §6.1, §5.8): its own, never the public client's. The public
3
+ * client posts to the host's relative base with the host's cookies; the private one posts to kb-api's own origin,
4
+ * cross-origin, with no credentials at all — the DPoP access token and its proof are the whole authentication, and
5
+ * kb-api's CORS never allows credentials.
6
+ *
7
+ * - The base is the absolute `privateBase` a grant answer named (`https://<slug>.blogmcp.ai/api/community/v1/private`)
8
+ * and nothing built from configuration: a relative base is refused, and so is any base whose origin is not the
9
+ * one the grant answer named and the host configured as its kb-api origin (`privateBaseOf`).
10
+ * - Every request: POST, JSON, `mode: 'cors'`, `credentials: 'omit'`, `redirect: 'error'` (a redirect would carry
11
+ * the token elsewhere), `cache: 'no-store'`, `referrerPolicy: 'no-referrer'` (the private view's URL is nobody's
12
+ * business), a 10 s timeout.
13
+ * - What it answers: the status, the parsed JSON body (null when there is none), and the `DPoP-Nonce` header, which
14
+ * kb-api's CORS exposes. `WWW-Authenticate` is exposed too but the codes in the body say the same.
15
+ */
16
+
17
+ import { assertPrivateBrowser } from './browser'
18
+
19
+ assertPrivateBrowser()
20
+
21
+ /** The path of the private surface under kb-api's public origin (the ingress strips `/api`, kb-api serves the rest). */
22
+ export const PRIVATE_BASE_PATH = '/api/community/v1/private'
23
+
24
+ export const PRIVATE_TIMEOUT_MS = 10_000
25
+
26
+ /** An operation of the private surface: literal lower-case segments, no ids in the path (§5.8). */
27
+ const OP_RE = /^[a-z0-9_-]+(?:\/[a-z0-9_-]+)*$/
28
+
29
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
30
+
31
+ /**
32
+ * The kb-api origin a host configures (`https://<slug>.blogmcp.ai`): https, or http on a loopback host for local
33
+ * development; no path, query, fragment or credentials. Null otherwise.
34
+ */
35
+ export function kbOriginOf(value: unknown): string | null {
36
+ if (typeof value !== 'string' || value.trim() === '') return null
37
+ try {
38
+ const url = new URL(value.trim())
39
+ const secure = url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))
40
+ if (!secure || url.username || url.password || url.search || url.hash || (url.pathname !== '/' && url.pathname !== '')) return null
41
+ return url.origin
42
+ } catch {
43
+ return null
44
+ }
45
+ }
46
+
47
+ /**
48
+ * The private base a grant answer named, checked: an absolute URL (a relative one is refused) on exactly `kbOrigin`
49
+ * and exactly the private surface's path. Null for anything else.
50
+ */
51
+ export function privateBaseOf(value: unknown, kbOrigin: string): string | null {
52
+ if (typeof value !== 'string' || !/^https?:\/\//i.test(value)) return null
53
+ try {
54
+ const url = new URL(value)
55
+ if (url.username || url.password || url.search || url.hash) return null
56
+ if (url.origin !== kbOrigin || kbOriginOf(url.origin) !== kbOrigin) return null
57
+ if (url.pathname.replace(/\/$/, '') !== PRIVATE_BASE_PATH) return null
58
+ return `${url.origin}${PRIVATE_BASE_PATH}`
59
+ } catch {
60
+ return null
61
+ }
62
+ }
63
+
64
+ /** What one private request answered. */
65
+ export interface PrivateTransportAnswer {
66
+ status: number
67
+ body: Record<string, unknown> | null
68
+ /** The `DPoP-Nonce` kb-api sent, or null. */
69
+ nonce: string | null
70
+ }
71
+
72
+ /** The request could not be made or was not answered (network, timeout, a redirect, CORS). */
73
+ export class PrivateTransportError extends Error {
74
+ constructor(readonly reason: 'network' | 'timeout' | 'refused_base') {
75
+ super(`[blogmcp-sdk] private request failed: ${reason}`)
76
+ this.name = 'PrivateTransportError'
77
+ }
78
+ }
79
+
80
+ export interface PrivateTransportOptions {
81
+ /** The fetch to use, resolved per call (a test stub; default the page's fetch). */
82
+ fetch?: () => typeof fetch
83
+ timeoutMs?: number
84
+ }
85
+
86
+ export type PrivateTransport = (
87
+ base: string,
88
+ kbOrigin: string,
89
+ op: string,
90
+ body: unknown,
91
+ headers: Readonly<Record<string, string>>,
92
+ ) => Promise<PrivateTransportAnswer>
93
+
94
+ export function createPrivateTransport(options: PrivateTransportOptions = {}): PrivateTransport {
95
+ const fetchFn = (): typeof fetch => (typeof options.fetch === 'function' ? options.fetch() : globalThis.fetch)
96
+ const timeoutMs = options.timeoutMs ?? PRIVATE_TIMEOUT_MS
97
+ return async (base, kbOrigin, op, body, headers) => {
98
+ const checked = privateBaseOf(base, kbOrigin)
99
+ if (checked === null || !OP_RE.test(op)) throw new PrivateTransportError('refused_base')
100
+ let res: Response
101
+ try {
102
+ res = await fetchFn()(`${checked}/${op}`, {
103
+ method: 'POST',
104
+ headers: { ...headers, 'Content-Type': 'application/json' },
105
+ body: JSON.stringify(body ?? {}),
106
+ mode: 'cors',
107
+ credentials: 'omit',
108
+ redirect: 'error',
109
+ cache: 'no-store',
110
+ referrerPolicy: 'no-referrer',
111
+ signal: AbortSignal.timeout(timeoutMs),
112
+ })
113
+ } catch (err) {
114
+ throw new PrivateTransportError((err as { name?: string })?.name === 'TimeoutError' ? 'timeout' : 'network')
115
+ }
116
+ let parsed: Record<string, unknown> | null = null
117
+ try {
118
+ const value: unknown = await res.json()
119
+ if (value && typeof value === 'object' && !Array.isArray(value)) parsed = value as Record<string, unknown>
120
+ } catch {
121
+ parsed = null
122
+ }
123
+ return { status: res.status, body: parsed, nonce: res.headers.get('dpop-nonce') }
124
+ }
125
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * `createPrivateGrantHandoff` — the host's hand-off route for `provider_page` (docs/internal/m4-contracts.md §6.1,
3
+ * §6.4, `[OWNER]` B-24): the storefront's `/komunita/grant/handoff`, a managed blog's `/blog/community/grant/handoff`.
4
+ *
5
+ * Under `provider_page` the private view runs on blogmcp's account host (`https://<slug>--account.<base>/zpravy`),
6
+ * whose device key lives in that origin's IndexedDB. It gets its grant by a top-level round trip: the page navigates
7
+ * here with `?jkt=<thumbprint>&state=<random>`; this route asks kb-api for a `purpose: 'handoff'` grant with the
8
+ * host's own member session and answers `303` to the FIXED
9
+ * `<accountOrigin>/zpravy#grant=…&state=…&dpopNonce=…&serverTime=…&memberRef=…` — the first nonce and the clock, so
10
+ * the first `private/session` proof needs no `use_dpop_nonce` round trip, and the opaque per-tenant `memberRef` the
11
+ * page keys its record by. GET, because a cross-site top-level POST carries no `SameSite=Lax` session cookie. The
12
+ * query's two values are public (a thumbprint and a random state); the grant travels only in the fragment, which no
13
+ * server, log or `Referer` sees, and is useless without the key.
14
+ *
15
+ * What it refuses: any method but GET (and HEAD's twin), any parameter beside `jkt` and `state` or either of them twice
16
+ * or malformed (the uniform unknown-path answer: the route serves nothing else); a request a page started with `fetch`
17
+ * (`Sec-Fetch-Mode` present and not `navigate`), because only a navigation lands on the account page. The target comes
18
+ * from configuration, never from the request: a cross-site page that navigates a member here with its own `jkt` gets
19
+ * nothing, the grant goes to the fixed blogmcp URL, whose page discards a `state` it did not create.
20
+ *
21
+ * When kb-api refuses (no member session, `PRIVATE_IDENTITY`, `ACTIVATION_REQUIRED`, …) the route still answers 303 to
22
+ * the same fixed page with `#state=…&error=<code>`, so the account page can say what to do; nothing of the request is
23
+ * echoed but the state the page itself created. kb-api's unknown-path answer is the one exception: it becomes this
24
+ * route's own unknown-path answer, so to a signed-in member a flag-false instance looks as though the route did not
25
+ * exist. Without a host session the route answers `#state=…&error=UNAUTHORIZED` before kb-api is asked, whatever the
26
+ * flag: nothing private is reached, but the 303 shows that the route is mounted, so whether to mount it on a dark
27
+ * instance is the host's decision (the PH slices), not this route's.
28
+ *
29
+ * Server-only (it holds members' tokens): the factory throws where a global `window` exists.
30
+ */
31
+
32
+ import { assertServerOnly } from '../../core/server-only'
33
+ import { clientIpFrom } from '../../consultations/server/client-ip'
34
+ import {
35
+ PRIVATE_JKT_RE,
36
+ clientIpHeaderOf,
37
+ grantUpstreamBase,
38
+ issueUpstreamGrant,
39
+ memberTokenOf,
40
+ timeoutOf,
41
+ } from './grant'
42
+ import { fromWebRequest, type CommunityHttp, type CommunityResponse } from './http'
43
+ import { communityUnknownPath } from './unknown-path'
44
+
45
+ /** The account host's page the hand-off lands on (§6.4, A.2). */
46
+ export const PRIVATE_HANDOFF_PAGE = '/zpravy'
47
+
48
+ /** The page's random state: 32–128 base64url characters (the SDK sends 43). */
49
+ export const PRIVATE_HANDOFF_STATE_RE = /^[A-Za-z0-9_-]{32,128}$/
50
+
51
+ export interface PrivateGrantHandoffConfig {
52
+ /** kb-api's base URL (as the grant handler's). */
53
+ kbApiUrl: string
54
+ /** The host's session → the member's bearer for kb-api, or null without a session. */
55
+ memberToken: (http: CommunityHttp) => Promise<string | null>
56
+ /** The account host's origin (`https://<slug>--account.<base>`): the one target. */
57
+ accountOrigin: string
58
+ clientIpHeader?: string
59
+ fetch?: () => typeof fetch
60
+ timeoutMs?: number
61
+ }
62
+
63
+ export interface PrivateGrantHandoff {
64
+ /** One navigation: `search` is the request URL's query (`?jkt=…&state=…`). Never throws. */
65
+ handle(http: CommunityHttp, search: string): Promise<CommunityResponse>
66
+ /** The same over a Web `Request`. */
67
+ handleRequest(request: Request): Promise<Response>
68
+ }
69
+
70
+ const REDIRECT_HEADERS: Readonly<Record<string, string>> = Object.freeze({
71
+ 'Cache-Control': 'no-store',
72
+ 'Referrer-Policy': 'no-referrer',
73
+ 'X-Robots-Tag': 'noindex',
74
+ 'X-Content-Type-Options': 'nosniff',
75
+ })
76
+
77
+ /** The account origin, checked: https (http only on a loopback host), no path. */
78
+ function accountOriginOf(value: unknown): string | null {
79
+ if (typeof value !== 'string') return null
80
+ try {
81
+ const url = new URL(value.trim())
82
+ const loopback = url.hostname === 'localhost' || url.hostname === '127.0.0.1'
83
+ if (!(url.protocol === 'https:' || (url.protocol === 'http:' && loopback))) return null
84
+ if (url.username || url.password || url.search || url.hash || (url.pathname !== '/' && url.pathname !== '')) return null
85
+ return url.origin
86
+ } catch {
87
+ return null
88
+ }
89
+ }
90
+
91
+ /** `jkt` and `state` from the query: exactly those two, once each, well-formed; else null. */
92
+ function queryOf(search: string): { jkt: string; state: string } | null {
93
+ if (typeof search !== 'string') return null
94
+ const raw = search.startsWith('?') ? search.slice(1) : search
95
+ if (raw === '' || raw.includes('#')) return null
96
+ const params = new URLSearchParams(raw)
97
+ const names = [...params.keys()]
98
+ if (names.length !== 2 || new Set(names).size !== 2 || !names.includes('jkt') || !names.includes('state')) return null
99
+ const jkt = params.get('jkt')!
100
+ const state = params.get('state')!
101
+ return PRIVATE_JKT_RE.test(jkt) && PRIVATE_HANDOFF_STATE_RE.test(state) ? { jkt, state } : null
102
+ }
103
+
104
+ export function createPrivateGrantHandoff(c: PrivateGrantHandoffConfig): PrivateGrantHandoff {
105
+ assertServerOnly('createPrivateGrantHandoff', "it holds the site's members' tokens, which must never reach the browser.")
106
+ const config = c ?? ({} as PrivateGrantHandoffConfig)
107
+ if (typeof config.memberToken !== 'function') {
108
+ throw new TypeError('[blogmcp-sdk] createPrivateGrantHandoff needs memberToken: (http) => Promise<string | null>')
109
+ }
110
+ const upstream = grantUpstreamBase(config.kbApiUrl)
111
+ if (upstream === null) throw new TypeError('[blogmcp-sdk] createPrivateGrantHandoff needs kbApiUrl: an absolute http(s) URL')
112
+ const accountOrigin = accountOriginOf(config.accountOrigin)
113
+ if (accountOrigin === null) throw new TypeError('[blogmcp-sdk] createPrivateGrantHandoff needs accountOrigin: https://<slug>--account.<base>')
114
+ const base: string = upstream
115
+ const target = `${accountOrigin}${PRIVATE_HANDOFF_PAGE}`
116
+ const ipHeader = clientIpHeaderOf(config.clientIpHeader)
117
+ const fetchFn = (): typeof fetch => (typeof config.fetch === 'function' ? config.fetch() : globalThis.fetch)
118
+ const timeoutMs = timeoutOf(config.timeoutMs)
119
+
120
+ const unknown = (): CommunityResponse => {
121
+ const answer = communityUnknownPath()
122
+ return { status: answer.status, headers: answer.headers, body: answer.body }
123
+ }
124
+ const redirect = (fragment: Record<string, string>): CommunityResponse => ({
125
+ status: 303,
126
+ headers: { ...REDIRECT_HEADERS, Location: `${target}#${new URLSearchParams(fragment).toString()}` },
127
+ body: '',
128
+ })
129
+
130
+ async function handle(http: CommunityHttp, search: string): Promise<CommunityResponse> {
131
+ try {
132
+ if (String(http.method).toUpperCase() !== 'GET') return unknown()
133
+ const query = queryOf(search)
134
+ if (query === null) return unknown()
135
+ const mode = http.header('sec-fetch-mode')
136
+ if (typeof mode === 'string' && mode.trim().toLowerCase() !== 'navigate') return unknown()
137
+ const token = await memberTokenOf(config.memberToken, http)
138
+ if (token === 'invalid') return redirect({ state: query.state, error: 'UNAVAILABLE' })
139
+ if (token === null) return redirect({ state: query.state, error: 'UNAUTHORIZED' })
140
+ const out = await issueUpstreamGrant({
141
+ base,
142
+ token,
143
+ body: { jkt: query.jkt, purpose: 'handoff' },
144
+ clientIp: ipHeader === '' ? null : clientIpFrom(http, { header: ipHeader }),
145
+ fetch: fetchFn,
146
+ timeoutMs,
147
+ })
148
+ // kb-api's uniform unknown-path answer (a dark instance, a member the test gate hides) stays the uniform answer
149
+ // here too, as the grant handler passes it through: a redirect naming UNKNOWN_PATH would tell a visitor that the
150
+ // surface exists.
151
+ if (!out.ok) return out.unknownPath ? unknown() : redirect({ state: query.state, error: out.code })
152
+ const g = out.grant
153
+ if (g.memberRef === undefined) return redirect({ state: query.state, error: 'UNAVAILABLE' })
154
+ return redirect({
155
+ grant: g.grant,
156
+ state: query.state,
157
+ dpopNonce: g.dpopNonce,
158
+ serverTime: String(g.serverTime),
159
+ memberRef: g.memberRef,
160
+ })
161
+ } catch {
162
+ return unknown()
163
+ }
164
+ }
165
+
166
+ return {
167
+ handle,
168
+ async handleRequest(request) {
169
+ const { http, respond } = fromWebRequest(request)
170
+ let search = ''
171
+ try {
172
+ search = new URL(request.url).search
173
+ } catch {
174
+ search = ''
175
+ }
176
+ return respond(await handle(http, search))
177
+ },
178
+ }
179
+ }
@@ -0,0 +1,292 @@
1
+ /**
2
+ * `createPrivateGrantHandler` — the host's grant route (docs/internal/m4-contracts.md §6.1, §5.9): the storefront's
3
+ * `/komunita/grant`, a managed blog's `/blog/community/grant`. The page's private SDK posts the thumbprint of its
4
+ * device key here; the handler turns the host's own member session into a one-minute, single-use private grant for
5
+ * that key and hands kb-api's answer back. The grant is useless without the key (kb-api compares the proof's key with
6
+ * the grant's at `private/session`), so a page that sees it learns nothing it could use elsewhere.
7
+ *
8
+ * Every request, in this order; a step that refuses answers alone:
9
+ * 1. POST only: anything else gets kb-api's uniform unknown-path answer (the route serves nothing else);
10
+ * 2. `Origin` exactly one of the site URLs' origins and, when sent, `Sec-Fetch-Site: same-origin` — the BFF's check
11
+ * (`isAllowedOrigin`): another site's page, or a sister host of a shared domain, cannot drive it (403 ORIGIN);
12
+ * 3. a strict body `{ jkt }` of at most 1 KB: the RFC 7638 thumbprint and nothing else (400 VALIDATION, 413
13
+ * TOO_LARGE, 400 INVALID_JSON) — never a member id, never a purpose (the hand-off has its own route);
14
+ * 4. the host's session: `memberToken(http)` → the member's bearer, or 401 UNAUTHORIZED without one;
15
+ * 5. one upstream `POST <kbApiUrl>/community/v1/grant/issue { jkt }` with `Authorization: Bearer <member token>`,
16
+ * `Content-Type` and — when `clientIpHeader` names an edge header — the visitor's IP in `X-Blogmcp-Client-Ip`
17
+ * (the grant's own ingress router keeps it, §5.8, so every member is not counted in the site server's one
18
+ * per-IP bucket); nothing else: no cookie, no Origin, `redirect: 'error'`, `cache: 'no-store'`, a timeout;
19
+ * 6. the answer: kb-api's success passed through as exactly `{ ok: true, grant, expiresIn, privateBase, dpopNonce,
20
+ * serverTime }` — the first nonce and the clock the first proof needs (§5.7) — and a refusal as `{ ok: false,
21
+ * code, message }` with kb-api's status (its unknown-path answer byte for byte); `Cache-Control: no-store`.
22
+ * Anything else from upstream is 503 UNAVAILABLE. Nothing is stored and nothing logged but codes.
23
+ *
24
+ * A flag-false instance: kb-api answers a signed-in member's grant request with its unknown-path answer, passed
25
+ * through unchanged, so to that member the route looks absent. Steps 1–4 answer before kb-api is asked, whatever the
26
+ * flag (a visitor without a host session gets 401 UNAUTHORIZED): nothing private is reached, but those answers show
27
+ * that the route is mounted, so whether to mount it on a dark instance is the host's decision (the PH slices).
28
+ *
29
+ * Server-only (it holds members' tokens): the factory throws where a global `window` exists. Runtime-neutral (Web
30
+ * fetch, no `node:*`).
31
+ */
32
+
33
+ import { assertServerOnly } from '../../core/server-only'
34
+ import { KB_CLIENT_IP_HEADER, clientIpFrom, isHeaderName } from '../../consultations/server/client-ip'
35
+ import { isAllowedOrigin, originOf, siteOrigins } from '../../consultations/server/origin'
36
+ import { isJsonContentType, type CommunityHttp, type CommunityResponse } from './http'
37
+ import { COMMUNITY_UNKNOWN_PATH_BODY, communityUnknownPath } from './unknown-path'
38
+
39
+ /** The largest grant request body: `{ "jkt": "<43 characters>" }` with room to spare. */
40
+ export const PRIVATE_GRANT_BODY_MAX_BYTES = 1024
41
+
42
+ /** kb-api's grant operation under its base (the base carries `/api` when it is the public address). */
43
+ export const PRIVATE_GRANT_UPSTREAM_PATH = '/community/v1/grant/issue'
44
+
45
+ /** An RFC 7638 SHA-256 thumbprint: 43 base64url characters (kb-api's JKT_RE). */
46
+ export const PRIVATE_JKT_RE = /^[A-Za-z0-9_-]{43}$/
47
+
48
+ const GRANT_RE = /^kbpg_[A-Za-z0-9_-]{16,256}$/
49
+ const NONCE_RE = /^[A-Za-z0-9_-]{8,128}$/
50
+ const CODE_RE = /^[A-Z][A-Z0-9_]{0,63}$/
51
+ const HEADER_TOKEN_RE = /^[\x21-\x7E]{1,8192}$/
52
+ const DEFAULT_TIMEOUT_MS = 10_000
53
+
54
+ export type PrivateGrantRefusal = 'ORIGIN' | 'VALIDATION' | 'TOO_LARGE' | 'INVALID_JSON' | 'UNAUTHORIZED' | 'UNAVAILABLE'
55
+
56
+ const REFUSALS: Readonly<Record<PrivateGrantRefusal, { status: number; message: string }>> = Object.freeze({
57
+ ORIGIN: { status: 403, message: 'This request did not come from the site' },
58
+ VALIDATION: { status: 400, message: 'The request body is not valid' },
59
+ TOO_LARGE: { status: 413, message: 'The request body is too large' },
60
+ INVALID_JSON: { status: 400, message: 'The request body must be a JSON object' },
61
+ UNAUTHORIZED: { status: 401, message: 'Sign in first' },
62
+ UNAVAILABLE: { status: 503, message: 'Temporarily unavailable' },
63
+ })
64
+
65
+ const RESPONSE_HEADERS: Readonly<Record<string, string>> = Object.freeze({
66
+ 'Content-Type': 'application/json; charset=utf-8',
67
+ 'Cache-Control': 'no-store',
68
+ 'Referrer-Policy': 'no-referrer',
69
+ 'X-Robots-Tag': 'noindex',
70
+ 'X-Content-Type-Options': 'nosniff',
71
+ })
72
+
73
+ export interface PrivateGrantHandlerConfig {
74
+ /** kb-api's base URL: its in-cluster origin, or the instance's public address WITH `/api` (as the BFF's). */
75
+ kbApiUrl: string
76
+ /** The site's own URLs: their origins are the only `Origin`s admitted. */
77
+ siteUrls: string[]
78
+ /** The host's session → the member's bearer for kb-api (the bare token), or null without a session. */
79
+ memberToken: (http: CommunityHttp) => Promise<string | null>
80
+ /** The edge header with the visitor's IP (e.g. `cf-connecting-ip`), forwarded as `X-Blogmcp-Client-Ip`; none by default. */
81
+ clientIpHeader?: string
82
+ fetch?: () => typeof fetch
83
+ timeoutMs?: number
84
+ }
85
+
86
+ export interface PrivateGrantHandler {
87
+ /** One request of the page's private SDK: its answer, never a throw. */
88
+ handle(http: CommunityHttp): Promise<CommunityResponse>
89
+ }
90
+
91
+ // ───────────────────────── shared with the hand-off ─────────────────────────
92
+
93
+ /** kb-api's base without a trailing slash, or null when it is not an absolute http(s) URL without a query. */
94
+ export function grantUpstreamBase(value: unknown): string | null {
95
+ if (typeof value !== 'string' || value.trim() === '') return null
96
+ try {
97
+ const url = new URL(value.trim())
98
+ if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.search || url.hash || url.username || url.password) return null
99
+ return url.origin + url.pathname.replace(/\/+$/, '')
100
+ } catch {
101
+ return null
102
+ }
103
+ }
104
+
105
+ /** kb-api's grant answer, checked: exactly the fields the page needs, or null. */
106
+ export interface IssuedGrant {
107
+ grant: string
108
+ expiresIn: number
109
+ privateBase: string
110
+ dpopNonce: string
111
+ serverTime: number
112
+ memberRef?: string
113
+ }
114
+
115
+ export type UpstreamGrant =
116
+ | { ok: true; grant: IssuedGrant }
117
+ | { ok: false; status: number; code: string; message: string; unknownPath: boolean }
118
+ | { ok: false; status: 503; code: 'UNAVAILABLE'; message: string; unknownPath: false }
119
+
120
+ /** One upstream `grant/issue` call with the member's bearer; never throws. */
121
+ export async function issueUpstreamGrant(options: {
122
+ base: string
123
+ token: string
124
+ body: { jkt: string; purpose?: 'handoff' }
125
+ clientIp: string | null
126
+ fetch: () => typeof fetch
127
+ timeoutMs: number
128
+ }): Promise<UpstreamGrant> {
129
+ const unavailable = { ok: false as const, status: 503 as const, code: 'UNAVAILABLE' as const, message: REFUSALS.UNAVAILABLE.message, unknownPath: false as const }
130
+ const headers: Record<string, string> = { 'Content-Type': 'application/json', Authorization: `Bearer ${options.token}` }
131
+ if (options.clientIp) headers[KB_CLIENT_IP_HEADER] = options.clientIp
132
+ let res: Response
133
+ let text: string
134
+ try {
135
+ res = await options.fetch()(`${options.base}${PRIVATE_GRANT_UPSTREAM_PATH}`, {
136
+ method: 'POST',
137
+ headers,
138
+ body: JSON.stringify(options.body),
139
+ redirect: 'error',
140
+ cache: 'no-store',
141
+ signal: AbortSignal.timeout(options.timeoutMs),
142
+ })
143
+ text = await res.text()
144
+ } catch {
145
+ // The cause is dropped on purpose: a fetch header error quotes the header's value (the token).
146
+ return unavailable
147
+ }
148
+ if (res.status === 404 && text === COMMUNITY_UNKNOWN_PATH_BODY) {
149
+ return { ok: false, status: 404, code: 'UNKNOWN_PATH', message: 'Not found', unknownPath: true }
150
+ }
151
+ if (!isJsonContentType(res.headers.get('content-type')) || text.includes(options.token)) return unavailable
152
+ let body: Record<string, unknown>
153
+ try {
154
+ const value: unknown = JSON.parse(text)
155
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return unavailable
156
+ body = value as Record<string, unknown>
157
+ } catch {
158
+ return unavailable
159
+ }
160
+ if (res.status === 200 && body.ok === true) {
161
+ const { grant, expiresIn, privateBase, dpopNonce, serverTime, memberRef } = body
162
+ const base = typeof privateBase === 'string' ? grantUpstreamBase(privateBase) : null
163
+ if (
164
+ typeof grant !== 'string' ||
165
+ !GRANT_RE.test(grant) ||
166
+ typeof expiresIn !== 'number' ||
167
+ !Number.isInteger(expiresIn) ||
168
+ expiresIn <= 0 ||
169
+ base === null ||
170
+ !/^https?:\/\//.test(privateBase as string) ||
171
+ typeof dpopNonce !== 'string' ||
172
+ !NONCE_RE.test(dpopNonce) ||
173
+ typeof serverTime !== 'number' ||
174
+ !Number.isFinite(serverTime)
175
+ ) {
176
+ return unavailable
177
+ }
178
+ const issued: IssuedGrant = { grant, expiresIn, privateBase: privateBase as string, dpopNonce, serverTime }
179
+ if (typeof memberRef === 'string' && /^[A-Za-z0-9_-]{16,64}$/.test(memberRef)) issued.memberRef = memberRef
180
+ return { ok: true, grant: issued }
181
+ }
182
+ if (res.status >= 400 && res.status < 500 && typeof body.code === 'string' && CODE_RE.test(body.code)) {
183
+ const message = typeof body.message === 'string' ? body.message.slice(0, 200) : ''
184
+ return { ok: false, status: res.status, code: body.code, message, unknownPath: false }
185
+ }
186
+ return unavailable
187
+ }
188
+
189
+ /** A member token from the host, checked: the bare token, visible ASCII. */
190
+ export async function memberTokenOf(memberToken: (http: CommunityHttp) => Promise<string | null>, http: CommunityHttp): Promise<string | null | 'invalid'> {
191
+ let token: unknown
192
+ try {
193
+ token = await memberToken(http)
194
+ } catch {
195
+ return 'invalid'
196
+ }
197
+ if (token === null || token === undefined || token === '') return null
198
+ return typeof token === 'string' && HEADER_TOKEN_RE.test(token) ? token : 'invalid'
199
+ }
200
+
201
+ /** The edge header to read the visitor's IP from, or '' for none (a name that is no header name counts as none). */
202
+ export function clientIpHeaderOf(value: unknown): string {
203
+ const name = typeof value === 'string' ? value.trim() : ''
204
+ return name !== '' && isHeaderName(name) ? name : ''
205
+ }
206
+
207
+ export function timeoutOf(value: unknown): number {
208
+ const ms = typeof value === 'number' ? Math.floor(value) : Number.NaN
209
+ return ms >= 1 && ms <= 60_000 ? ms : DEFAULT_TIMEOUT_MS
210
+ }
211
+
212
+ // ───────────────────────── the handler ─────────────────────────
213
+
214
+ function respond(status: number, body: Record<string, unknown>): CommunityResponse {
215
+ return { status, headers: { ...RESPONSE_HEADERS }, body: JSON.stringify(body) }
216
+ }
217
+
218
+ function refusal(code: PrivateGrantRefusal): CommunityResponse {
219
+ const { status, message } = REFUSALS[code]
220
+ return respond(status, { ok: false, code, message })
221
+ }
222
+
223
+ /** The body: a JSON object of exactly `{ jkt }`, at most 1 KB. */
224
+ async function jktOf(http: CommunityHttp): Promise<string | PrivateGrantRefusal> {
225
+ if (!isJsonContentType(http.header('content-type'))) return 'INVALID_JSON'
226
+ const declared = Number(http.header('content-length'))
227
+ if (Number.isFinite(declared) && declared > PRIVATE_GRANT_BODY_MAX_BYTES) return 'TOO_LARGE'
228
+ let body
229
+ try {
230
+ body = await http.json()
231
+ } catch {
232
+ return 'INVALID_JSON'
233
+ }
234
+ if (!body.ok) return body.code
235
+ if (body.bytes.byteLength > PRIVATE_GRANT_BODY_MAX_BYTES) return 'TOO_LARGE'
236
+ const keys = Object.keys(body.value)
237
+ if (keys.length !== 1 || keys[0] !== 'jkt' || typeof body.value.jkt !== 'string' || !PRIVATE_JKT_RE.test(body.value.jkt)) return 'VALIDATION'
238
+ return body.value.jkt
239
+ }
240
+
241
+ export function createPrivateGrantHandler(c: PrivateGrantHandlerConfig): PrivateGrantHandler {
242
+ assertServerOnly('createPrivateGrantHandler', "it holds the site's members' tokens, which must never reach the browser.")
243
+ const config = c ?? ({} as PrivateGrantHandlerConfig)
244
+ if (typeof config.memberToken !== 'function') {
245
+ throw new TypeError('[blogmcp-sdk] createPrivateGrantHandler needs memberToken: (http) => Promise<string | null>')
246
+ }
247
+ const base = grantUpstreamBase(config.kbApiUrl)
248
+ if (base === null) throw new TypeError('[blogmcp-sdk] createPrivateGrantHandler needs kbApiUrl: an absolute http(s) URL')
249
+ const origins = siteOrigins(Array.isArray(config.siteUrls) ? config.siteUrls : [])
250
+ if (origins.length === 0 || config.siteUrls.some((u) => originOf(u) === null)) {
251
+ throw new TypeError('[blogmcp-sdk] createPrivateGrantHandler needs siteUrls: the site’s own http(s) URLs')
252
+ }
253
+ const ipHeader = clientIpHeaderOf(config.clientIpHeader)
254
+ const fetchFn = (): typeof fetch => (typeof config.fetch === 'function' ? config.fetch() : globalThis.fetch)
255
+ const timeoutMs = timeoutOf(config.timeoutMs)
256
+
257
+ return {
258
+ async handle(http) {
259
+ try {
260
+ if (String(http.method).toUpperCase() !== 'POST') {
261
+ const answer = communityUnknownPath()
262
+ return { status: answer.status, headers: answer.headers, body: answer.body }
263
+ }
264
+ if (!isAllowedOrigin(http, origins)) return refusal('ORIGIN')
265
+ const jkt = await jktOf(http)
266
+ if (!PRIVATE_JKT_RE.test(jkt)) return refusal(jkt as PrivateGrantRefusal)
267
+ const token = await memberTokenOf(config.memberToken, http)
268
+ if (token === 'invalid') return refusal('UNAVAILABLE')
269
+ if (token === null) return refusal('UNAUTHORIZED')
270
+ const out = await issueUpstreamGrant({
271
+ base,
272
+ token,
273
+ body: { jkt },
274
+ clientIp: ipHeader === '' ? null : clientIpFrom(http, { header: ipHeader }),
275
+ fetch: fetchFn,
276
+ timeoutMs,
277
+ })
278
+ if (out.ok) {
279
+ const g = out.grant
280
+ return respond(200, { ok: true, grant: g.grant, expiresIn: g.expiresIn, privateBase: g.privateBase, dpopNonce: g.dpopNonce, serverTime: g.serverTime })
281
+ }
282
+ if (out.unknownPath) {
283
+ const answer = communityUnknownPath()
284
+ return { status: answer.status, headers: answer.headers, body: answer.body }
285
+ }
286
+ return respond(out.status, { ok: false, code: out.code, message: out.message })
287
+ } catch {
288
+ return refusal('UNAVAILABLE')
289
+ }
290
+ },
291
+ }
292
+ }
@@ -58,3 +58,9 @@ export type { CommunityServerEnv } from './env'
58
58
 
59
59
  export { COMMUNITY_BODY_MAX_BYTES, fromWebRequest, parseCommunityJson } from './http'
60
60
  export type { CommunityHttp, CommunityJsonBody, CommunityJsonRefusal, CommunityResponse } from './http'
61
+
62
+ // M4 PU1 (m4-contracts.md §6.1): the host's grant route for the page's private SDK, and the provider_page hand-off.
63
+ export { createPrivateGrantHandler } from './grant'
64
+ export type { PrivateGrantHandler, PrivateGrantHandlerConfig, PrivateGrantRefusal } from './grant'
65
+ export { createPrivateGrantHandoff } from './grant-handoff'
66
+ export type { PrivateGrantHandoff, PrivateGrantHandoffConfig } from './grant-handoff'
@@ -123,9 +123,39 @@ export const isKnownAdverseEventOutcome = (outcome: unknown): outcome is KnownAd
123
123
  export const AGE_BANDS = Object.freeze(['16_17', '18_plus'] as const)
124
124
  export type AgeBand = (typeof AGE_BANDS)[number]
125
125
 
126
- export const LEGAL_TEXT_KINDS = Object.freeze(['rules', 'terms', 'privacy', 'art9_consent'] as const)
126
+ /**
127
+ * kb-api's LEGAL_TEXT_KINDS (services/legal-texts/legal-texts.service.ts), in its order; kb-api's
128
+ * src/__tests__/legal-kinds-drift.spec.ts reads both copies. M4 PX0 (m4-contracts.md Appendix A.8) adds the private
129
+ * surfaces' member-facing texts, which only the platform publishes (PLATFORM_ONLY_LEGAL_TEXT_KINDS): a host's
130
+ * `legal/current` never has one of them, because the tenant never publishes them and the account host renders them.
131
+ */
132
+ export const LEGAL_TEXT_KINDS = Object.freeze([
133
+ 'rules',
134
+ 'terms',
135
+ 'privacy',
136
+ 'art9_consent',
137
+ 'private_terms',
138
+ 'private_privacy',
139
+ 'private_notice_63e',
140
+ 'private_contact',
141
+ 'private_activation',
142
+ ] as const)
127
143
  export type LegalTextKind = (typeof LEGAL_TEXT_KINDS)[number]
128
144
 
145
+ /**
146
+ * The kinds only blogmcp publishes (kb-api's PLATFORM_ONLY_LEGAL_TEXT_KINDS): no host page renders one. It stays
147
+ * off the community barrel, because no host needs it yet; it is here so that the drift spec holds the SDK's copy
148
+ * of the split, and a later slice exports it the day a host must tell the two groups apart.
149
+ */
150
+ export const PLATFORM_ONLY_LEGAL_TEXT_KINDS = Object.freeze([
151
+ 'private_terms',
152
+ 'private_privacy',
153
+ 'private_notice_63e',
154
+ 'private_contact',
155
+ 'private_activation',
156
+ ] as const satisfies readonly LegalTextKind[])
157
+ export type PlatformOnlyLegalTextKind = (typeof PLATFORM_ONLY_LEGAL_TEXT_KINDS)[number]
158
+
129
159
  export type AcceptanceState = 'accepted' | 'reconsent_required' | 'never'
130
160
 
131
161
  // ───────────────────────── a discussion (§7.3) ─────────────────────────
@@ -364,6 +394,21 @@ export interface ModuleInfo {
364
394
  * (`state.away`). Absent from a kb-api older than M3 — read it through communityAwayOf.
365
395
  */
366
396
  readonly away?: CommunityAway | null
397
+ /**
398
+ * M4 (m4-contracts.md §5.11 "What the hosts read", C.3): the private surfaces' state and who renders the private view.
399
+ * Absent from a kb-api before M4 and on an instance that never had a private admission — read it through the private
400
+ * entry's `privateBlockOf`, which reads an absent or unknown block as `dark` (nothing private is mounted).
401
+ */
402
+ readonly private?: PrivateModuleBlock
403
+ }
404
+
405
+ /** The states of the private surfaces (§5.13): `braked` stops writes, not reads; `dark` serves nothing private. */
406
+ export type PrivateSurfaceState = 'dark' | 'live' | 'read_only' | 'braked'
407
+
408
+ /** MyState's `module.private` (M4 §5.11): the type only — the public entry holds no private code. */
409
+ export interface PrivateModuleBlock {
410
+ readonly state: PrivateSurfaceState
411
+ readonly rendering: 'tenant' | 'provider_page'
367
412
  }
368
413
 
369
414
  /**