@blogmcp/sdk 0.13.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 (61) 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/package.json +7 -3
  42. package/src/community/links.ts +8 -0
  43. package/src/community/outcome.ts +37 -0
  44. package/src/community/private/browser.ts +31 -0
  45. package/src/community/private/client.ts +304 -0
  46. package/src/community/private/dm.ts +1687 -0
  47. package/src/community/private/dpop.ts +110 -0
  48. package/src/community/private/encoding.ts +71 -0
  49. package/src/community/private/host-state.ts +37 -0
  50. package/src/community/private/index.ts +169 -0
  51. package/src/community/private/keystore.ts +179 -0
  52. package/src/community/private/marker.ts +28 -0
  53. package/src/community/private/private-routes.ts +80 -0
  54. package/src/community/private/promise.ts +125 -0
  55. package/src/community/private/realtime.ts +431 -0
  56. package/src/community/private/session.ts +848 -0
  57. package/src/community/private/transport.ts +125 -0
  58. package/src/community/server/grant-handoff.ts +179 -0
  59. package/src/community/server/grant.ts +292 -0
  60. package/src/community/server/index.ts +6 -0
  61. package/src/community/shapes.ts +46 -1
@@ -0,0 +1,441 @@
1
+ import { assertPrivateBrowser as we } from "./browser.js";
2
+ import { createDpopClock as me, signDpopProof as ye } from "./dpop.js";
3
+ import { randomBase64url as Ee } from "./encoding.js";
4
+ import { createPrivateKeystore as _e, privateRecordId as $, unboundRecordId as Re, isUnboundRecordId as ne } from "./keystore.js";
5
+ import { kbOriginOf as Ae, createPrivateTransport as be, PrivateTransportError as Te, PRIVATE_TIMEOUT_MS as Ne, privateBaseOf as Oe, PRIVATE_BASE_PATH as De } from "./transport.js";
6
+ we();
7
+ const l = (o, s = null) => ({ ok: !1, code: o, status: s }), Ie = 6e4, y = Object.freeze({
8
+ refreshPrefix: "blogmcp-private-refresh:",
9
+ current: "blogmcp-private-current",
10
+ handoff: "blogmcp-private-handoff"
11
+ }), re = /^kbpg_[A-Za-z0-9_-]{16,256}$/, K = /^kbpa_[A-Za-z0-9_-]{16,256}$/, ae = /^kbpr_[A-Za-z0-9_-]{16,256}$/, je = /^[A-Za-z0-9_-]{16,64}$/, Pe = /^[A-Za-z0-9_-]{32,128}$/, ue = /^[A-Z][A-Z0-9_]{0,63}$/, Se = /^\/(?![/\\])[^\s\\?#]*$/, N = (o) => `blogmcp-private-${o}`;
12
+ function Me() {
13
+ const o = /* @__PURE__ */ new Map();
14
+ return {
15
+ request(s, d) {
16
+ const i = (o.get(s) ?? Promise.resolve()).then(d, d);
17
+ return o.set(s, i.catch(() => {
18
+ })), i;
19
+ }
20
+ };
21
+ }
22
+ function Be() {
23
+ const s = globalThis.navigator?.locks;
24
+ return s && typeof s.request == "function" ? { request: (d, m) => s.request(d, m) } : Me();
25
+ }
26
+ async function Fe() {
27
+ try {
28
+ const o = globalThis.navigator?.serviceWorker;
29
+ if (!o) return null;
30
+ const s = await o.getRegistration();
31
+ return (s ? await s.pushManager.getSubscription() : null)?.endpoint ?? null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+ const oe = (o) => !!o && typeof o == "object" && !Array.isArray(o);
37
+ function se(o, s) {
38
+ return o === 200 && s?.ok === !0 ? null : s && typeof s.code == "string" && ue.test(s.code) ? s.code : o === 404 ? "UNKNOWN_PATH" : "BAD_ANSWER";
39
+ }
40
+ function ie(o) {
41
+ const { ok: s, serverTime: d, ...m } = o;
42
+ return m;
43
+ }
44
+ function Le(o) {
45
+ const s = Ae(o?.kbOrigin);
46
+ if (s === null) throw new TypeError("[blogmcp-sdk] createPrivateSession needs kbOrigin: kb-api’s https origin, e.g. https://tenant.blogmcp.ai");
47
+ const d = o.rendering === "provider_page" ? "provider_page" : "tenant";
48
+ if (d === "tenant") {
49
+ if (typeof o.grantPath != "string" || !Se.test(o.grantPath))
50
+ throw new TypeError("[blogmcp-sdk] createPrivateSession needs grantPath: the host’s grant route on its own origin, e.g. /komunita/grant");
51
+ if (typeof o.member != "function") throw new TypeError("[blogmcp-sdk] createPrivateSession needs member(): the host’s current member id");
52
+ }
53
+ const m = o.now ?? Date.now, i = _e({ kbOrigin: s, indexedDB: o.indexedDB, now: m }), le = be({ fetch: o.fetch, timeoutMs: o.timeoutMs }), ce = () => typeof o.fetch == "function" ? o.fetch() : globalThis.fetch, O = o.locks ?? Be(), Z = o.channel === null ? null : o.channel ?? (typeof BroadcastChannel == "function" ? (e) => new BroadcastChannel(e) : null), R = () => {
54
+ try {
55
+ return o.sessionStorage ? o.sessionStorage() : globalThis.sessionStorage ?? null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }, fe = o.askWaitMs ?? 40, _ = me(m), w = /* @__PURE__ */ new Map(), j = /* @__PURE__ */ new Map(), q = /* @__PURE__ */ new Set();
60
+ let A = null, D = null;
61
+ const b = (e, n) => !!e && e.jkt === n && e.exp - m() > Ie;
62
+ function F(e, n) {
63
+ const t = w.get(e);
64
+ (!t || t.jkt !== n.jkt || t.exp < n.exp) && w.set(e, n);
65
+ }
66
+ function x(e) {
67
+ if (!Z) return null;
68
+ let n = j.get(e);
69
+ if (n) return n;
70
+ try {
71
+ n = Z(N(e));
72
+ } catch {
73
+ return null;
74
+ }
75
+ return n.addEventListener("message", (t) => {
76
+ const r = t.data;
77
+ if (oe(r))
78
+ if (r.t === "token" && typeof r.jkt == "string" && typeof r.token == "string" && K.test(r.token) && typeof r.exp == "number")
79
+ F(e, { jkt: r.jkt, token: r.token, exp: r.exp });
80
+ else if (r.t === "ask" && typeof r.jkt == "string") {
81
+ const a = w.get(e);
82
+ b(a, r.jkt) && n.postMessage({ t: "token", jkt: a.jkt, token: a.token, exp: a.exp });
83
+ } else r.t === "gone" && w.delete(e);
84
+ }), j.set(e, n), n;
85
+ }
86
+ function z(e, n) {
87
+ x(e)?.postMessage({ t: "token", jkt: n.jkt, token: n.token, exp: n.exp });
88
+ }
89
+ function H(e) {
90
+ w.delete(e), x(e)?.postMessage({ t: "gone" });
91
+ }
92
+ async function de(e) {
93
+ const n = x(e.id);
94
+ !n || q.has(e.id) || (q.add(e.id), n.postMessage({ t: "ask", jkt: e.jkt }), await new Promise((t) => setTimeout(t, fe)));
95
+ }
96
+ function P(e) {
97
+ if (e.rendering === "tenant") return e.refreshToken;
98
+ const n = R()?.getItem(y.refreshPrefix + e.id) ?? null;
99
+ return n !== null && ae.test(n) ? n : null;
100
+ }
101
+ async function V(e, n, t) {
102
+ let r = { ...e, usedAt: m(), ...t !== void 0 ? { privateBase: t } : {} };
103
+ if (e.rendering === "tenant") r = { ...r, refreshToken: n };
104
+ else {
105
+ const a = R();
106
+ n === null ? a?.removeItem(y.refreshPrefix + e.id) : a?.setItem(y.refreshPrefix + e.id, n), r = { ...r, refreshToken: null };
107
+ }
108
+ return await i.put(r), r;
109
+ }
110
+ async function T(e, n, t, r, a) {
111
+ let c = !1, u = !1;
112
+ const p = `${n}/${t}`;
113
+ for (; ; ) {
114
+ const g = { DPoP: await ye({
115
+ privateKey: e.keyPair.privateKey,
116
+ jwk: e.publicJwk,
117
+ htm: "POST",
118
+ htu: p,
119
+ nonce: _.nonce(s, e.jkt),
120
+ accessToken: a,
121
+ iat: _.iat()
122
+ }) };
123
+ a && (g.Authorization = `DPoP ${a}`);
124
+ let f;
125
+ try {
126
+ f = await le(n, s, t, r, g);
127
+ } catch (h) {
128
+ return { status: null, body: null, code: h instanceof Te && h.reason === "refused_base" ? "BAD_ANSWER" : "NETWORK" };
129
+ }
130
+ _.setNonce(s, e.jkt, f.nonce);
131
+ const k = _.observe(f.body?.serverTime), E = se(f.status, f.body);
132
+ if (E === "DPOP_NONCE" && !c) {
133
+ c = !0;
134
+ continue;
135
+ }
136
+ if (E === "DPOP_INVALID" && k && !u) {
137
+ u = !0;
138
+ continue;
139
+ }
140
+ return { status: f.status, body: f.body, code: E };
141
+ }
142
+ }
143
+ async function S() {
144
+ if (d === "provider_page") {
145
+ const r = A, a = r ? await i.get(r) : null;
146
+ return a ? { ok: !0, value: { id: a.id, record: a } } : l("HANDOFF_REQUIRED");
147
+ }
148
+ let e;
149
+ try {
150
+ e = await o.member();
151
+ } catch {
152
+ return l("NETWORK");
153
+ }
154
+ if (typeof e != "string" || e === "") return l("NO_MEMBER");
155
+ const n = await $(s, e), t = await i.get(n);
156
+ return t && (D = t.id), { ok: !0, value: { id: n, record: t } };
157
+ }
158
+ async function pe() {
159
+ const e = await S();
160
+ if (!e.ok) return e;
161
+ if (e.value.record !== null) return { ok: !0, value: e.value.record };
162
+ const n = e.value.id, t = await O.request(N(n), async () => await i.get(n) ?? i.create(n, "tenant"));
163
+ return D = t.id, { ok: !0, value: t };
164
+ }
165
+ async function M(e) {
166
+ return await i.get(e.id) ?? await i.create(e.id, e.rendering);
167
+ }
168
+ async function B(e) {
169
+ return _.forgetKey(e.jkt), R()?.removeItem(y.refreshPrefix + e.id), H(e.id), i.create(e.id, e.rendering);
170
+ }
171
+ async function G(e) {
172
+ const n = AbortSignal.timeout(o.timeoutMs ?? Ne);
173
+ let t;
174
+ try {
175
+ t = await ce()(o.grantPath, {
176
+ method: "POST",
177
+ headers: { "Content-Type": "application/json" },
178
+ body: JSON.stringify({ jkt: e.jkt }),
179
+ mode: "same-origin",
180
+ credentials: "same-origin",
181
+ redirect: "error",
182
+ cache: "no-store",
183
+ signal: n
184
+ });
185
+ } catch {
186
+ return l("NETWORK");
187
+ }
188
+ let r = null;
189
+ try {
190
+ const u = await t.json();
191
+ r = oe(u) ? u : null;
192
+ } catch {
193
+ r = null;
194
+ }
195
+ const a = se(t.status, r);
196
+ if (a !== null) return l(a, t.status);
197
+ const c = Oe(r.privateBase, s);
198
+ return typeof r.grant != "string" || !re.test(r.grant) || c === null ? l("BAD_ANSWER", t.status) : { ok: !0, value: { grant: r.grant, privateBase: c, dpopNonce: r.dpopNonce, serverTime: r.serverTime } };
199
+ }
200
+ async function U(e, n, t = !1) {
201
+ _.observe(n.serverTime), _.setNonce(s, e.jkt, n.dpopNonce);
202
+ const r = await T(e, n.privateBase, "session", { grant: n.grant }, null);
203
+ if (r.code === "DEVICE_REMOVED" && d === "tenant" && !t) {
204
+ const v = await B(e), g = await G(v);
205
+ return g.ok ? U(v, g.value, !0) : g;
206
+ }
207
+ if (r.code !== null)
208
+ return r.code === "DEVICE_REMOVED" && await B(e), l(r.code, r.status);
209
+ const a = r.body;
210
+ if (typeof a.accessToken != "string" || !K.test(a.accessToken) || typeof a.refreshToken != "string" || !ae.test(a.refreshToken))
211
+ return l("BAD_ANSWER", r.status);
212
+ const c = await V(e, a.refreshToken, n.privateBase), u = { jkt: c.jkt, token: a.accessToken, exp: m() + J(a.expiresIn) };
213
+ F(c.id, u), z(c.id, u);
214
+ const p = ie(a);
215
+ return {
216
+ ok: !0,
217
+ value: {
218
+ opened: !0,
219
+ device: p.device,
220
+ address: p.address,
221
+ activation: p.activation
222
+ }
223
+ };
224
+ }
225
+ const J = (e) => typeof e == "number" && Number.isFinite(e) && e > 0 && e <= 3600 ? e * 1e3 : 6e5;
226
+ async function Q(e) {
227
+ const n = P(e);
228
+ if (n === null || e.privateBase === null) return null;
229
+ const t = await T(e, e.privateBase, "session/refresh", { refreshToken: n }, null);
230
+ if (t.code === "UNAUTHORIZED")
231
+ return await V(e, null), l("UNAUTHORIZED", t.status);
232
+ if (t.code === "DEVICE_REMOVED")
233
+ return await B(e), l("DEVICE_REMOVED", t.status);
234
+ if (t.code !== null) return l(t.code, t.status);
235
+ const r = t.body.accessToken;
236
+ if (typeof r != "string" || !K.test(r)) return l("BAD_ANSWER", t.status);
237
+ const a = { jkt: e.jkt, token: r, exp: m() + J(t.body.expiresIn) };
238
+ return F(e.id, a), z(e.id, a), { ok: !0, value: a };
239
+ }
240
+ async function ke(e, n) {
241
+ let t = await M(e);
242
+ const r = w.get(t.id);
243
+ if (b(r, t.jkt) && r.token !== n) return { ok: !0, value: { record: t, token: r, info: { opened: !1 } } };
244
+ if (!w.has(t.id)) {
245
+ await de(t);
246
+ const v = w.get(t.id);
247
+ if (b(v, t.jkt) && v.token !== n) return { ok: !0, value: { record: t, token: v, info: { opened: !1 } } };
248
+ }
249
+ const a = await Q(t);
250
+ if (a?.ok) return { ok: !0, value: { record: t, token: a.value, info: { opened: !1 } } };
251
+ if (a && a.code !== "UNAUTHORIZED" && a.code !== "DEVICE_REMOVED") return a;
252
+ if (d === "provider_page") return l("HANDOFF_REQUIRED");
253
+ t = await M(t);
254
+ const c = await G(t);
255
+ if (!c.ok) return c;
256
+ const u = await U(t, c.value);
257
+ if (!u.ok) return u;
258
+ t = await M(t);
259
+ const p = w.get(t.id);
260
+ return b(p, t.jkt) ? { ok: !0, value: { record: t, token: p, info: u.value } } : l("BAD_ANSWER");
261
+ }
262
+ async function W(e = null) {
263
+ const n = await pe();
264
+ if (!n.ok) return n;
265
+ const t = w.get(n.value.id);
266
+ return e === null && b(t, n.value.jkt) && n.value.privateBase !== null ? { ok: !0, value: { record: n.value, token: t, info: { opened: !1 } } } : O.request(N(n.value.id), () => ke(n.value, e));
267
+ }
268
+ async function X(e, n = {}) {
269
+ let t = await W();
270
+ if (!t.ok) return t;
271
+ let r = await T(t.value.record, t.value.record.privateBase, e, n, t.value.token.token);
272
+ if (r.code === "UNAUTHORIZED") {
273
+ if (w.delete(t.value.record.id), t = await W(t.value.token.token), !t.ok) return t;
274
+ r = await T(t.value.record, t.value.record.privateBase, e, n, t.value.token.token);
275
+ }
276
+ return r.code === "DEVICE_REMOVED" && await B(t.value.record), r.code !== null ? l(r.code, r.status) : { ok: !0, value: ie(r.body) };
277
+ }
278
+ async function C(e, n) {
279
+ const t = await M(e);
280
+ let r = !1;
281
+ try {
282
+ let a = w.get(t.id);
283
+ if (!b(a, t.jkt)) {
284
+ const c = await Q(t);
285
+ a = c?.ok ? c.value : void 0;
286
+ }
287
+ if (a && t.privateBase !== null) {
288
+ if (n) {
289
+ const u = await (o.pushEndpoint ?? Fe)();
290
+ typeof u == "string" && u !== "" && await T(t, t.privateBase, "push/unsubscribe", { endpoint: u }, a.token);
291
+ }
292
+ r = (await T(t, t.privateBase, "session/end", {}, a.token)).code === null;
293
+ }
294
+ } finally {
295
+ const a = await i.get(t.id) ?? t;
296
+ P(a) !== null && await V(a, null), H(t.id);
297
+ }
298
+ return r;
299
+ }
300
+ async function L(e, n) {
301
+ return O.request(N(e.id), () => C(e, n));
302
+ }
303
+ return {
304
+ kbOrigin: s,
305
+ rendering: d,
306
+ async ensureSession() {
307
+ const e = await W();
308
+ return e.ok ? { ok: !0, value: e.value.info } : e;
309
+ },
310
+ call: X,
311
+ async privateSignOut() {
312
+ const e = await S();
313
+ if (e.ok)
314
+ return e.value.record !== null && await L(e.value.record, !0), { ok: !0, value: null };
315
+ if (d === "provider_page") return e.code === "HANDOFF_REQUIRED" ? { ok: !0, value: null } : e;
316
+ const n = new Set(D !== null ? [D] : []);
317
+ if (e.code === "NO_MEMBER")
318
+ for (const t of await i.list()) t.rendering === "tenant" && t.refreshToken !== null && n.add(t.id);
319
+ if (n.size === 0) return e.code === "NO_MEMBER" ? { ok: !0, value: null } : e;
320
+ for (const t of n) {
321
+ const r = await i.get(t);
322
+ r && await L(r, !0);
323
+ }
324
+ return D = null, { ok: !0, value: null };
325
+ },
326
+ async forget() {
327
+ const e = await S();
328
+ if (!e.ok) return e;
329
+ const n = e.value.record;
330
+ if (n === null)
331
+ return R()?.removeItem(y.refreshPrefix + e.value.id), w.delete(e.value.id), { ok: !0, value: null };
332
+ const t = await X("devices/forget", {});
333
+ return _.forgetKey(n.jkt), R()?.removeItem(y.refreshPrefix + n.id), await i.delete(n.id), H(n.id), d === "provider_page" && (A = null), t.ok ? { ok: !0, value: null } : t;
334
+ },
335
+ async start() {
336
+ if (d !== "tenant") return { ok: !0, value: { ended: 0 } };
337
+ let e;
338
+ try {
339
+ e = await o.member();
340
+ } catch {
341
+ return l("NETWORK");
342
+ }
343
+ const n = typeof e == "string" && e !== "" ? await $(s, e) : null;
344
+ let t = 0;
345
+ for (const r of await i.list())
346
+ r.rendering !== "tenant" || r.id === n || r.refreshToken === null || await L(r, !0) && t++;
347
+ return { ok: !0, value: { ended: t } };
348
+ },
349
+ async activated() {
350
+ try {
351
+ return await (o.persist ?? (() => globalThis.navigator?.storage?.persist?.() ?? Promise.resolve(!1)))();
352
+ } catch {
353
+ return !1;
354
+ }
355
+ },
356
+ async beginHandoff(e) {
357
+ return Y(e, !1);
358
+ },
359
+ async completeHandoff(e, n) {
360
+ return ge(e, n);
361
+ },
362
+ async currentJkt() {
363
+ if (d === "provider_page") return A ? (await i.get(A))?.jkt ?? null : null;
364
+ const e = await S();
365
+ return e.ok ? e.value.record?.jkt ?? null : null;
366
+ },
367
+ close() {
368
+ for (const e of j.values()) e.close();
369
+ j.clear();
370
+ }
371
+ };
372
+ function ve(e) {
373
+ try {
374
+ const n = new URL(e);
375
+ return n.protocol !== "https:" && n.protocol !== "http:" || n.search || n.hash || n.username || n.password ? null : n.href;
376
+ } catch {
377
+ return null;
378
+ }
379
+ }
380
+ async function Y(e, n, t = null) {
381
+ if (d !== "provider_page") return l("HANDOFF_INVALID");
382
+ const r = ve(e), a = R();
383
+ if (r === null || a === null) return l("HANDOFF_INVALID");
384
+ const c = (await i.list()).filter((f) => f.rendering === "provider_page"), u = t ?? A ?? a.getItem(y.current);
385
+ let p = c.find((f) => f.id === u) ?? [...c].sort((f, k) => k.usedAt - f.usedAt)[0];
386
+ p ??= await i.create(Re(), "provider_page");
387
+ const v = Ee(32);
388
+ a.setItem(y.handoff, JSON.stringify({ state: v, recordId: p.id, jkt: p.jkt, repeat: n }));
389
+ const g = new URL(r);
390
+ return g.searchParams.set("jkt", p.jkt), g.searchParams.set("state", v), (o.navigate ?? ((f) => globalThis.location.assign(f)))(g.href), { ok: !0, value: null };
391
+ }
392
+ async function ge(e, n) {
393
+ if (d !== "provider_page") return l("HANDOFF_INVALID");
394
+ const t = R(), r = typeof e == "string" ? e.replace(/^#/, "") : "", a = new URLSearchParams(r);
395
+ try {
396
+ const I = globalThis.location;
397
+ I && r !== "" && globalThis.history?.replaceState(null, "", `${I.pathname}${I.search}`);
398
+ } catch {
399
+ }
400
+ const c = t?.getItem(y.handoff) ?? null;
401
+ t?.removeItem(y.handoff);
402
+ const u = xe(c), p = a.get("state"), v = a.get("grant"), g = a.get("memberRef"), f = a.get("error");
403
+ if (!u || typeof u.state != "string" || p === null || !Pe.test(p) || p !== u.state) return l("HANDOFF_INVALID");
404
+ if (v === null && f !== null && ue.test(f)) return l(f);
405
+ if (v === null || !re.test(v) || g === null || !je.test(g) || typeof u.recordId != "string")
406
+ return l("HANDOFF_INVALID");
407
+ const k = await i.get(u.recordId);
408
+ if (!k || k.jkt !== u.jkt) return l("HANDOFF_INVALID");
409
+ const E = await $(s, g);
410
+ let h;
411
+ if (k.id === E) h = k;
412
+ else if (ne(k.id) && !await i.get(E))
413
+ h = { ...k, id: E }, await i.put(h), await i.delete(k.id);
414
+ else {
415
+ if (u.repeat === !0) return l("HANDOFF_INVALID");
416
+ P(k) !== null && await O.request(N(k.id), () => C(k, !0));
417
+ const I = await i.get(E) ?? await i.create(E, "provider_page");
418
+ ne(k.id) && await i.delete(k.id);
419
+ const te = await Y(n, !0, I.id);
420
+ return te.ok ? l("HANDOFF_REPEATED") : te;
421
+ }
422
+ A = h.id, t?.setItem(y.current, h.id);
423
+ const he = `${s}${De}`, ee = Number(a.get("serverTime"));
424
+ return O.request(N(h.id), async () => P(h) !== null && (await C(h, !1), (await i.get(h.id))?.jkt !== h.jkt) ? l("DEVICE_REMOVED") : U(h, { grant: v, privateBase: he, dpopNonce: a.get("dpopNonce"), serverTime: Number.isFinite(ee) ? ee : null }));
425
+ }
426
+ }
427
+ function xe(o) {
428
+ if (o === null) return null;
429
+ try {
430
+ const s = JSON.parse(o);
431
+ return s && typeof s == "object" && !Array.isArray(s) ? s : null;
432
+ } catch {
433
+ return null;
434
+ }
435
+ }
436
+ export {
437
+ Ie as PRIVATE_REFRESH_MARGIN_MS,
438
+ y as PRIVATE_SESSION_STORAGE,
439
+ Le as createPrivateSession,
440
+ N as privateLockName
441
+ };
@@ -0,0 +1,47 @@
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
+ /** The path of the private surface under kb-api's public origin (the ingress strips `/api`, kb-api serves the rest). */
17
+ export declare const PRIVATE_BASE_PATH = "/api/community/v1/private";
18
+ export declare const PRIVATE_TIMEOUT_MS = 10000;
19
+ /**
20
+ * The kb-api origin a host configures (`https://<slug>.blogmcp.ai`): https, or http on a loopback host for local
21
+ * development; no path, query, fragment or credentials. Null otherwise.
22
+ */
23
+ export declare function kbOriginOf(value: unknown): string | null;
24
+ /**
25
+ * The private base a grant answer named, checked: an absolute URL (a relative one is refused) on exactly `kbOrigin`
26
+ * and exactly the private surface's path. Null for anything else.
27
+ */
28
+ export declare function privateBaseOf(value: unknown, kbOrigin: string): string | null;
29
+ /** What one private request answered. */
30
+ export interface PrivateTransportAnswer {
31
+ status: number;
32
+ body: Record<string, unknown> | null;
33
+ /** The `DPoP-Nonce` kb-api sent, or null. */
34
+ nonce: string | null;
35
+ }
36
+ /** The request could not be made or was not answered (network, timeout, a redirect, CORS). */
37
+ export declare class PrivateTransportError extends Error {
38
+ readonly reason: 'network' | 'timeout' | 'refused_base';
39
+ constructor(reason: 'network' | 'timeout' | 'refused_base');
40
+ }
41
+ export interface PrivateTransportOptions {
42
+ /** The fetch to use, resolved per call (a test stub; default the page's fetch). */
43
+ fetch?: () => typeof fetch;
44
+ timeoutMs?: number;
45
+ }
46
+ export type PrivateTransport = (base: string, kbOrigin: string, op: string, body: unknown, headers: Readonly<Record<string, string>>) => Promise<PrivateTransportAnswer>;
47
+ export declare function createPrivateTransport(options?: PrivateTransportOptions): PrivateTransport;
@@ -0,0 +1,65 @@
1
+ import { assertPrivateBrowser as m } from "./browser.js";
2
+ m();
3
+ const c = "/api/community/v1/private", d = 1e4, y = /^[a-z0-9_-]+(?:\/[a-z0-9_-]+)*$/, w = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
4
+ function T(t) {
5
+ if (typeof t != "string" || t.trim() === "") return null;
6
+ try {
7
+ const r = new URL(t.trim());
8
+ return !(r.protocol === "https:" || r.protocol === "http:" && w.has(r.hostname)) || r.username || r.password || r.search || r.hash || r.pathname !== "/" && r.pathname !== "" ? null : r.origin;
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+ function g(t, r) {
14
+ if (typeof t != "string" || !/^https?:\/\//i.test(t)) return null;
15
+ try {
16
+ const e = new URL(t);
17
+ return e.username || e.password || e.search || e.hash || e.origin !== r || T(e.origin) !== r || e.pathname.replace(/\/$/, "") !== c ? null : `${e.origin}${c}`;
18
+ } catch {
19
+ return null;
20
+ }
21
+ }
22
+ class u extends Error {
23
+ constructor(r) {
24
+ super(`[blogmcp-sdk] private request failed: ${r}`), this.reason = r, this.name = "PrivateTransportError";
25
+ }
26
+ }
27
+ function E(t = {}) {
28
+ const r = () => typeof t.fetch == "function" ? t.fetch() : globalThis.fetch, e = t.timeoutMs ?? d;
29
+ return async (l, h, a, p, f) => {
30
+ const i = g(l, h);
31
+ if (i === null || !y.test(a)) throw new u("refused_base");
32
+ let o;
33
+ try {
34
+ o = await r()(`${i}/${a}`, {
35
+ method: "POST",
36
+ headers: { ...f, "Content-Type": "application/json" },
37
+ body: JSON.stringify(p ?? {}),
38
+ mode: "cors",
39
+ credentials: "omit",
40
+ redirect: "error",
41
+ cache: "no-store",
42
+ referrerPolicy: "no-referrer",
43
+ signal: AbortSignal.timeout(e)
44
+ });
45
+ } catch (n) {
46
+ throw new u(n?.name === "TimeoutError" ? "timeout" : "network");
47
+ }
48
+ let s = null;
49
+ try {
50
+ const n = await o.json();
51
+ n && typeof n == "object" && !Array.isArray(n) && (s = n);
52
+ } catch {
53
+ s = null;
54
+ }
55
+ return { status: o.status, body: s, nonce: o.headers.get("dpop-nonce") };
56
+ };
57
+ }
58
+ export {
59
+ c as PRIVATE_BASE_PATH,
60
+ d as PRIVATE_TIMEOUT_MS,
61
+ u as PrivateTransportError,
62
+ E as createPrivateTransport,
63
+ T as kbOriginOf,
64
+ g as privateBaseOf
65
+ };
@@ -0,0 +1,53 @@
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
+ import { type CommunityHttp, type CommunityResponse } from './http.js';
32
+ /** The account host's page the hand-off lands on (§6.4, A.2). */
33
+ export declare const PRIVATE_HANDOFF_PAGE = "/zpravy";
34
+ /** The page's random state: 32–128 base64url characters (the SDK sends 43). */
35
+ export declare const PRIVATE_HANDOFF_STATE_RE: RegExp;
36
+ export interface PrivateGrantHandoffConfig {
37
+ /** kb-api's base URL (as the grant handler's). */
38
+ kbApiUrl: string;
39
+ /** The host's session → the member's bearer for kb-api, or null without a session. */
40
+ memberToken: (http: CommunityHttp) => Promise<string | null>;
41
+ /** The account host's origin (`https://<slug>--account.<base>`): the one target. */
42
+ accountOrigin: string;
43
+ clientIpHeader?: string;
44
+ fetch?: () => typeof fetch;
45
+ timeoutMs?: number;
46
+ }
47
+ export interface PrivateGrantHandoff {
48
+ /** One navigation: `search` is the request URL's query (`?jkt=…&state=…`). Never throws. */
49
+ handle(http: CommunityHttp, search: string): Promise<CommunityResponse>;
50
+ /** The same over a Web `Request`. */
51
+ handleRequest(request: Request): Promise<Response>;
52
+ }
53
+ export declare function createPrivateGrantHandoff(c: PrivateGrantHandoffConfig): PrivateGrantHandoff;