@blogmcp/sdk 0.13.0 → 0.14.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 (67) hide show
  1. package/dist/community/index.d.ts +4 -1
  2. package/dist/community/index.js +39 -36
  3. package/dist/community/legal-text.d.ts +65 -0
  4. package/dist/community/legal-text.js +247 -0
  5. package/dist/community/links.d.ts +6 -0
  6. package/dist/community/links.js +9 -1
  7. package/dist/community/outcome.d.ts +1 -1
  8. package/dist/community/outcome.js +60 -23
  9. package/dist/community/private/browser.d.ts +18 -0
  10. package/dist/community/private/browser.js +17 -0
  11. package/dist/community/private/client.d.ts +259 -0
  12. package/dist/community/private/client.js +98 -0
  13. package/dist/community/private/dm.d.ts +547 -0
  14. package/dist/community/private/dm.js +852 -0
  15. package/dist/community/private/dpop.d.ts +59 -0
  16. package/dist/community/private/dpop.js +46 -0
  17. package/dist/community/private/encoding.d.ts +17 -0
  18. package/dist/community/private/encoding.js +50 -0
  19. package/dist/community/private/host-state.d.ts +20 -0
  20. package/dist/community/private/host-state.js +15 -0
  21. package/dist/community/private/index.d.ts +51 -0
  22. package/dist/community/private/index.js +71 -0
  23. package/dist/community/private/keystore.d.ts +73 -0
  24. package/dist/community/private/keystore.js +91 -0
  25. package/dist/community/private/marker.d.ts +17 -0
  26. package/dist/community/private/marker.js +11 -0
  27. package/dist/community/private/private-routes.d.ts +6 -0
  28. package/dist/community/private/private-routes.js +72 -0
  29. package/dist/community/private/promise.d.ts +65 -0
  30. package/dist/community/private/promise.js +39 -0
  31. package/dist/community/private/realtime.d.ts +127 -0
  32. package/dist/community/private/realtime.js +199 -0
  33. package/dist/community/private/session.d.ts +175 -0
  34. package/dist/community/private/session.js +441 -0
  35. package/dist/community/private/transport.d.ts +47 -0
  36. package/dist/community/private/transport.js +65 -0
  37. package/dist/community/server/grant-handoff.d.ts +53 -0
  38. package/dist/community/server/grant-handoff.js +96 -0
  39. package/dist/community/server/grant.d.ts +100 -0
  40. package/dist/community/server/grant.js +165 -0
  41. package/dist/community/server/index.d.ts +4 -0
  42. package/dist/community/server/index.js +20 -16
  43. package/dist/community/shapes.d.ts +27 -1
  44. package/dist/community/shapes.js +27 -17
  45. package/package.json +7 -3
  46. package/src/community/index.ts +6 -1
  47. package/src/community/legal-text.ts +438 -0
  48. package/src/community/links.ts +8 -0
  49. package/src/community/outcome.ts +37 -0
  50. package/src/community/private/browser.ts +31 -0
  51. package/src/community/private/client.ts +304 -0
  52. package/src/community/private/dm.ts +1687 -0
  53. package/src/community/private/dpop.ts +110 -0
  54. package/src/community/private/encoding.ts +71 -0
  55. package/src/community/private/host-state.ts +37 -0
  56. package/src/community/private/index.ts +169 -0
  57. package/src/community/private/keystore.ts +179 -0
  58. package/src/community/private/marker.ts +28 -0
  59. package/src/community/private/private-routes.ts +80 -0
  60. package/src/community/private/promise.ts +125 -0
  61. package/src/community/private/realtime.ts +431 -0
  62. package/src/community/private/session.ts +848 -0
  63. package/src/community/private/transport.ts +125 -0
  64. package/src/community/server/grant-handoff.ts +179 -0
  65. package/src/community/server/grant.ts +292 -0
  66. package/src/community/server/index.ts +6 -0
  67. package/src/community/shapes.ts +46 -1
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The promise of the private surfaces as data (docs/internal/m4-contracts.md §6.1, invariant 12; community.md §9.4):
3
+ * the capability matrix — who receives what — by space × identity × `private_rendering`, and the wording keys the
4
+ * elements render from it, with the Czech sentences of §9.4. The elements (PU2) render the promise from this function
5
+ * only, and their "rendering the promise against the matrix" test checks that no sentence promises more than the row
6
+ * says; kb-api's analytics wording reads the same data (DM5).
7
+ *
8
+ * The rules the data encodes:
9
+ * - the participants receive the content; nobody else does in the normal course;
10
+ * - a reported message reaches whoever handles reports for blogmcp (T&S on the illegal line and appeals; an
11
+ * authorised person — possibly the website's moderator — on the rules line) with at most 10 preceding messages;
12
+ * - the tenant's team and server receive outcome codes and counts only;
13
+ * - under tenant rendering the website's page code receives the content to display it (U22: the promise says so);
14
+ * under `provider_page` it receives nothing — the screens are on blogmcp's account host — and that sentence goes;
15
+ * - a delegated sign-in (the delegated identity, or a native member whose session came through the tenant's host)
16
+ * adds the addendum under both renderings: the website can sign in as the member as a new device;
17
+ * - with the same legal person behind the website and blogmcp (U10, `same_entity`), under tenant rendering the
18
+ * sentence says plainly that this person writes the code that displays the messages.
19
+ */
20
+ /** A private space. M4 builds DMs; groups come later and their row is here so the matrix is settled once. */
21
+ export type PrivateSpace = 'dm' | 'group';
22
+ export type PrivateIdentity = 'native' | 'sso' | 'delegated';
23
+ export type PrivatePromiseRendering = 'tenant' | 'provider_page';
24
+ /** What one party receives. */
25
+ export type PrivateReceives = 'content'
26
+ /** Reported messages only, with at most 10 preceding messages. */
27
+ | 'reported_content'
28
+ /** Outcome codes and aggregate counts, never content or case metadata. */
29
+ | 'outcome_codes_and_counts'
30
+ /** The content, to put it on the member's screen (tenant rendering). */
31
+ | 'content_for_display'
32
+ /** A group's content, only while visibly a member with a badge. */
33
+ | 'content_when_visible_member' | 'nothing';
34
+ export interface PrivatePromiseInput {
35
+ space: PrivateSpace;
36
+ identity: PrivateIdentity;
37
+ rendering: PrivatePromiseRendering;
38
+ /** The website and blogmcp are run by the same legal person (the admission's `same_entity`). */
39
+ sameEntity?: boolean;
40
+ /** The session came through the tenant's host (`host_tenant`): a native member there counts as delegated (§5.11). */
41
+ hostKind?: 'blogmcp' | 'tenant';
42
+ }
43
+ export interface PrivatePromise {
44
+ readonly receivers: Readonly<{
45
+ participants: PrivateReceives;
46
+ authorisedPersons: PrivateReceives;
47
+ trustAndSafety: PrivateReceives;
48
+ tenantTeam: PrivateReceives;
49
+ tenantServer: PrivateReceives;
50
+ websiteCode: PrivateReceives;
51
+ }>;
52
+ /** The wording keys, in the order the sentences are shown. */
53
+ readonly keys: readonly PrivatePromiseKey[];
54
+ /** Whether the delegated addendum applies. */
55
+ readonly delegated: boolean;
56
+ }
57
+ export declare const PRIVATE_PROMISE_KEYS: readonly ["private.promise.dm.core", "private.promise.group.core", "private.promise.display.tenant", "private.promise.same_entity", "private.promise.reports", "private.promise.orders", "private.promise.not_e2e", "private.promise.delegated"];
58
+ export type PrivatePromiseKey = (typeof PRIVATE_PROMISE_KEYS)[number];
59
+ /**
60
+ * The sentences of community.md §9.4, split where a rendering or an identity drops or adds one. Placeholders:
61
+ * `{site}` the website's name, `{entity}` and `{ico}` the operator's name and IČO.
62
+ */
63
+ export declare const PRIVATE_PROMISE_MESSAGES_CS: Readonly<Record<PrivatePromiseKey, string>>;
64
+ /** The promise for one space, identity and rendering (see the module doc). */
65
+ export declare function privatePromise(input: PrivatePromiseInput): PrivatePromise;
@@ -0,0 +1,39 @@
1
+ const a = Object.freeze([
2
+ "private.promise.dm.core",
3
+ "private.promise.group.core",
4
+ "private.promise.display.tenant",
5
+ "private.promise.same_entity",
6
+ "private.promise.reports",
7
+ "private.promise.orders",
8
+ "private.promise.not_e2e",
9
+ "private.promise.delegated"
10
+ ]), s = Object.freeze({
11
+ "private.promise.dm.core": "Soukromé zprávy jsou jen pro vás a druhého účastníka. Provozuje je blogmcp.",
12
+ "private.promise.group.core": "Skupiny jsou jen pro členy; člen týmu je vidí jen tehdy, když je ve skupině viditelně s odznakem.",
13
+ "private.promise.display.tenant": "Na obrazovku je dává web {site} a smlouva mu zakazuje je číst, ukládat nebo měřit.",
14
+ "private.promise.same_entity": "Soukromé zprávy provozuje blogmcp. Web i blogmcp dnes provozuje stejná osoba ({entity}, IČO {ico}) a píše i kód webu, který vám zprávy zobrazuje. Technicky by je tak mohla číst, zakazuje jí to zákon. Jinak se obsah mimo vaši obrazovku otevře jen u nahlášené zprávy nebo na příkaz úřadu a každé takové otevření se samo zapíše.",
15
+ "private.promise.reports": "Tým webu k nim nemá žádný nástroj, kromě vyřizování nahlášených zpráv. Když kdokoli z vás zprávu nahlásí, uvidí ji i s nejvýš 10 předchozími zprávami ten, kdo hlášení vyřizuje za provozovatele soukromých zpráv. Může to být i pověřený moderátor webu {site}. Kdo hlásí, vidí jeho jméno před odesláním.",
16
+ "private.promise.orders": "Výjimkou jsou i údaje, které musí provozovatel vydat na příkaz soudu nebo policie.",
17
+ "private.promise.not_e2e": "Nejsou šifrované koncově.",
18
+ "private.promise.delegated": "Web, přes který se přihlašujete, se za vás technicky umí přihlásit jako nové zařízení. Starší zprávy by tam bez vašeho schválení neviděl, nové ano, a mohl by i psát vaším jménem. Každé nové přihlášení vám proto ohlásíme e-mailem od blogmcp."
19
+ });
20
+ function p(e) {
21
+ const r = e.rendering !== "provider_page", t = e.identity === "delegated" || e.identity === "native" && e.hostKind === "tenant", i = e.sameEntity === !0 && r, o = [];
22
+ return e.space === "group" && o.push("private.promise.group.core"), i ? o.push("private.promise.same_entity") : (e.space === "dm" && o.push("private.promise.dm.core"), r && o.push("private.promise.display.tenant")), o.push("private.promise.reports", "private.promise.orders", "private.promise.not_e2e"), t && o.push("private.promise.delegated"), Object.freeze({
23
+ receivers: Object.freeze({
24
+ participants: "content",
25
+ authorisedPersons: "reported_content",
26
+ trustAndSafety: "reported_content",
27
+ tenantTeam: e.space === "group" ? "content_when_visible_member" : "outcome_codes_and_counts",
28
+ tenantServer: "outcome_codes_and_counts",
29
+ websiteCode: r ? "content_for_display" : "nothing"
30
+ }),
31
+ keys: Object.freeze(o),
32
+ delegated: t
33
+ });
34
+ }
35
+ export {
36
+ a as PRIVATE_PROMISE_KEYS,
37
+ s as PRIVATE_PROMISE_MESSAGES_CS,
38
+ p as privatePromise
39
+ };
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The private realtime client (docs/internal/m4-contracts.md §6.3 "Realtime", C.8, C.9): the member's inbox on this
3
+ * device, as content-free events `{ k, c?, s?, r? }` — the elements' `realtime` property (`{ subscribe(listener) }`).
4
+ *
5
+ * const realtime = createPrivateRealtime({ client }) // client: createPrivateClient(…)
6
+ * const off = realtime.subscribe((event) => …) // event.k: 'device_new', 'resync', …
7
+ * // later: off(), or realtime.close()
8
+ *
9
+ * **Its own connection.** `private/realtime/token` answers a connection token whose `channels` claim names the
10
+ * member's inbox, `user:inbox#<memberId>` — a server-side subscription: Centrifugo subscribes the connection to it, and
11
+ * the client never asks for the channel (the chart's `user` namespace refuses a client's subscribe). So this client
12
+ * opens a Centrifuge connection of its own, beside the public client's (both `sub = memberId`, so a revocation's user
13
+ * disconnect closes both), reads the inbox's name from the token it was given and hands on only that channel's
14
+ * publications. The URL comes only from kb-api's answer; nothing here builds one from configuration.
15
+ *
16
+ * **Renewal.** The token lives 120 s (`expiresInS`) and is DPoP-bound through the private session that asks for it:
17
+ * `realtime.token()` runs with this device's session, its refresh and its proof retries. A fresh token is fetched
18
+ * `PRIVATE_RT_RENEW_MARGIN_MS` before the current one expires, so when Centrifuge asks for one (`getToken`, at the
19
+ * token's ttl) it is already there, and the socket never waits on a private round trip with an expired token; the
20
+ * renewal after that is scheduled from the token Centrifuge took, so a connection refreshes once per token (every
21
+ * 120 s less the margin). A
22
+ * device that is signed out, denied or whose mint key was retired gets its renewal refused (UNAUTHORIZED,
23
+ * DEVICE_REMOVED, …): the client then closes at once instead of waiting for Centrifugo to close it at the token's
24
+ * expiry plus its grace (≤ 145 s, which stays the server's guarantee). A transient failure (the network, a 5xx, a
25
+ * quota) leaves the socket to Centrifugo's own retries.
26
+ *
27
+ * **Closing.** `close()` (an unmounted view, a sign-out), the last listener leaving, a refused renewal, a server
28
+ * disconnect that is final (the revocation of every session, 4501; any code in Centrifugo's terminal ranges) and a
29
+ * token that does not name exactly one inbox end the connection for good; `onEnd` says why, once. A closed client
30
+ * stays closed: the host makes a new one for a new session.
31
+ *
32
+ * `centrifuge` (≥ 5.7, MIT) is the package's optional peer dependency, loaded only when a listener subscribes; a host
33
+ * passes the module or a loader of it as `centrifuge` (a test passes a fake). Nothing here logs or reports.
34
+ */
35
+ import type { PrivateOutcome } from './session.js';
36
+ /** A Centrifuge client, as far as this client uses it (server-side subscriptions report on the client). */
37
+ export interface PrivateCentrifugeLike {
38
+ on(event: 'connected' | 'connecting' | 'disconnected' | 'subscribed' | 'unsubscribed' | 'publication' | 'error', listener: (ctx: any) => void): unknown;
39
+ connect(): void;
40
+ disconnect(): void;
41
+ }
42
+ /** `centrifuge`'s module, as far as this client uses it. */
43
+ export interface PrivateCentrifugeModuleLike {
44
+ Centrifuge: new (endpoints: Array<{
45
+ transport: 'websocket' | 'http_stream';
46
+ endpoint: string;
47
+ }>, options: {
48
+ token: string;
49
+ getToken: () => Promise<string>;
50
+ emulationEndpoint: string;
51
+ name?: string;
52
+ }) => PrivateCentrifugeLike;
53
+ /** Thrown from getToken, it tells Centrifuge to stop (no retry). */
54
+ UnauthorizedError?: new (message?: string) => Error;
55
+ }
56
+ /** `private/realtime/token`'s answer (C.8). */
57
+ export interface PrivateRealtimeTokenAnswer {
58
+ readonly token: string;
59
+ readonly url: string;
60
+ readonly expiresInS: number;
61
+ }
62
+ /**
63
+ * One inbox event (§6.3, invariant 6): a code and, at most, a conversation id, a sequence number and the device an
64
+ * account event is about. Nothing else of a publication is handed on.
65
+ */
66
+ export interface PrivateRealtimeEvent {
67
+ readonly k: string;
68
+ readonly c?: string;
69
+ readonly s?: number;
70
+ readonly r?: string;
71
+ }
72
+ export type PrivateRealtimeListener = (event: PrivateRealtimeEvent) => void;
73
+ /** `idle` until a listener subscribes; `connecting` (again after a drop); `live` once the inbox is subscribed; `closed`. */
74
+ export type PrivateRealtimeMode = 'idle' | 'connecting' | 'live' | 'closed';
75
+ /**
76
+ * Why the connection ended: `closed` (by the host, or its last listener left), `refused` (kb-api refused a token:
77
+ * `code` says which), `revoked` (Centrifugo cut the user for good: a revocation of every session), `off` (kb-api has
78
+ * no realtime for this tenant, or the private surface answers nothing), `unavailable` (no usable answer, no
79
+ * `centrifuge` module, or the first token could not be had).
80
+ */
81
+ export type PrivateRealtimeEndReason = 'closed' | 'refused' | 'revoked' | 'off' | 'unavailable';
82
+ export interface PrivateRealtimeEnd {
83
+ readonly reason: PrivateRealtimeEndReason;
84
+ /** kb-api's or the SDK's code for `refused`, `off` and `unavailable`; Centrifugo's disconnect code for `revoked`. */
85
+ readonly code: string | null;
86
+ }
87
+ export interface PrivateRealtimeOptions {
88
+ /** The private client (createPrivateClient), as far as this one uses it: its device's session asks for the tokens. */
89
+ client: {
90
+ realtime: {
91
+ token(): Promise<PrivateOutcome<PrivateRealtimeTokenAnswer>>;
92
+ };
93
+ };
94
+ /** The `centrifuge` module, or a loader of it; default `import('centrifuge')` (the optional peer dependency). */
95
+ centrifuge?: PrivateCentrifugeModuleLike | (() => Promise<PrivateCentrifugeModuleLike>);
96
+ /** Called on every change of mode. */
97
+ onMode?: (mode: PrivateRealtimeMode) => void;
98
+ /** Called once, when the connection ends for good. */
99
+ onEnd?: (end: PrivateRealtimeEnd) => void;
100
+ /** How long before a token's expiry the next one is fetched (default PRIVATE_RT_RENEW_MARGIN_MS). */
101
+ renewMarginMs?: number;
102
+ now?: () => number;
103
+ }
104
+ export interface PrivateRealtime {
105
+ readonly mode: PrivateRealtimeMode;
106
+ /** The inbox channel the current token names, or null before the first token. */
107
+ readonly channel: string | null;
108
+ /** Adds a listener (the first one connects); returns the function that removes it (the last one closes). */
109
+ subscribe(listener: PrivateRealtimeListener): () => void;
110
+ /** Ends the connection for good (idempotent). */
111
+ close(): void;
112
+ }
113
+ /** The next token is fetched this long before the current one expires (a 120 s token: at 90 s). */
114
+ export declare const PRIVATE_RT_RENEW_MARGIN_MS = 30000;
115
+ /**
116
+ * The one inbox channel a connection token names in its `channels` claim, or null. The token is kb-api's and Centrifugo
117
+ * verifies it; this only reads which channel the server will subscribe, so that nothing else is handed on.
118
+ */
119
+ export declare function inboxChannelOfToken(token: unknown): string | null;
120
+ /** kb-api's connection URL without a trailing slash: an absolute http(s) URL with no credentials, query or fragment. */
121
+ export declare function privateRealtimeUrlOf(url: unknown): string | null;
122
+ /**
123
+ * A publication's data as an inbox event, or null: `k` a code, `c` and `r` ids, `s` a non-negative integer; any other
124
+ * key, or a value of another kind, is not passed on (the inbox carries no content, invariant 6).
125
+ */
126
+ export declare function privateRealtimeEventOf(data: unknown): PrivateRealtimeEvent | null;
127
+ export declare function createPrivateRealtime(options: PrivateRealtimeOptions): PrivateRealtime;
@@ -0,0 +1,199 @@
1
+ import { assertPrivateBrowser as B } from "./browser.js";
2
+ import { fromBase64url as C } from "./encoding.js";
3
+ B();
4
+ const x = 3e4, O = 5e3, F = 3, W = 1e3, P = 4501, $ = (e) => typeof e == "number" && (e >= 3500 && e < 4e3 || e >= 4500 && e < 5e3), b = /* @__PURE__ */ new Set([
5
+ "NETWORK",
6
+ "BAD_ANSWER",
7
+ "UNAVAILABLE",
8
+ "INTERNAL",
9
+ "BUSY",
10
+ "TOO_FAST",
11
+ "QUOTA_DAILY",
12
+ "QUOTA_IP_HOURLY",
13
+ "LEDGER_UNAVAILABLE"
14
+ ]), z = /* @__PURE__ */ new Set(["REALTIME_OFF", "UNKNOWN_PATH", "MODULE_DARK"]), K = /^user:inbox#[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, M = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, V = /^[a-z][a-z0-9_]{0,63}$/, m = (e) => typeof e == "object" && e !== null && !Array.isArray(e);
15
+ function N(e) {
16
+ if (typeof e != "string" || e.length > 4096) return null;
17
+ const r = e.split(".");
18
+ if (r.length !== 3) return null;
19
+ const E = C(r[1]);
20
+ if (!E) return null;
21
+ let f;
22
+ try {
23
+ f = JSON.parse(new TextDecoder().decode(E));
24
+ } catch {
25
+ return null;
26
+ }
27
+ if (!m(f) || !Array.isArray(f.channels) || f.channels.length !== 1) return null;
28
+ const s = f.channels[0];
29
+ return typeof s == "string" && K.test(s) ? s : null;
30
+ }
31
+ function Y(e) {
32
+ if (typeof e != "string" || e.length > 2048) return null;
33
+ let r;
34
+ try {
35
+ r = new URL(e);
36
+ } catch {
37
+ return null;
38
+ }
39
+ return r.protocol !== "https:" && r.protocol !== "http:" || r.username || r.password || r.search || r.hash ? null : r.href.replace(/\/+$/, "");
40
+ }
41
+ function j(e) {
42
+ if (!m(e) || typeof e.k != "string" || !V.test(e.k)) return null;
43
+ const r = { k: e.k };
44
+ return typeof e.c == "string" && M.test(e.c) && (r.c = e.c.toLowerCase()), typeof e.s == "number" && Number.isSafeInteger(e.s) && e.s >= 0 && (r.s = e.s), typeof e.r == "string" && M.test(e.r) && (r.r = e.r.toLowerCase()), Object.freeze(r);
45
+ }
46
+ async function q(e) {
47
+ try {
48
+ const r = typeof e == "function" ? await e() : e || await import("centrifuge");
49
+ return r && typeof r.Centrifuge == "function" ? r : null;
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ function Q(e) {
55
+ const { client: r } = e, E = e.now ?? Date.now, f = typeof e.renewMarginMs == "number" && e.renewMarginMs >= 0 ? e.renewMarginMs : x, s = /* @__PURE__ */ new Set();
56
+ let d = "idle", h = null, a = null, y = null, p = null, w = null;
57
+ const u = () => d === "closed", R = (n) => {
58
+ if (!(d === n || u())) {
59
+ d = n;
60
+ try {
61
+ e.onMode?.(n);
62
+ } catch {
63
+ }
64
+ }
65
+ };
66
+ function l(n, c) {
67
+ if (u()) return;
68
+ p && clearTimeout(p), p = null, y = null;
69
+ const A = a;
70
+ a = null;
71
+ try {
72
+ A?.disconnect();
73
+ } catch {
74
+ }
75
+ d = "closed";
76
+ try {
77
+ e.onMode?.("closed");
78
+ } catch {
79
+ }
80
+ try {
81
+ e.onEnd?.({ reason: n, code: c });
82
+ } catch {
83
+ }
84
+ }
85
+ function g(n) {
86
+ l(z.has(n) ? "off" : "refused", n);
87
+ }
88
+ const T = (n) => {
89
+ const c = typeof n.expiresInS == "number" && Number.isFinite(n.expiresInS) && n.expiresInS > 0 ? n.expiresInS : 120;
90
+ return E() + c * 1e3;
91
+ };
92
+ function v(n) {
93
+ p && clearTimeout(p);
94
+ const c = Math.max(O, n - E() - f);
95
+ p = setTimeout(() => {
96
+ p = null, I();
97
+ }, c);
98
+ }
99
+ function I() {
100
+ return w || (w = (async () => {
101
+ try {
102
+ if (u()) return;
103
+ const n = await r.realtime.token();
104
+ if (u()) return;
105
+ if (!n.ok) {
106
+ b.has(n.code) || g(n.code);
107
+ return;
108
+ }
109
+ if (N(n.value.token) !== h) return l("unavailable", "BAD_ANSWER");
110
+ y = { token: n.value.token, exp: T(n.value) };
111
+ } finally {
112
+ w = null;
113
+ }
114
+ })(), w);
115
+ }
116
+ async function D() {
117
+ R("connecting");
118
+ let n = null;
119
+ for (let t = 0; t < F; t++) {
120
+ if (t > 0 && await new Promise((o) => setTimeout(o, W * 2 ** (t - 1))), u() || (n = await r.realtime.token(), u())) return;
121
+ if (n.ok || !b.has(n.code)) break;
122
+ }
123
+ if (!n) return l("unavailable", null);
124
+ if (!n.ok) return b.has(n.code) ? l("unavailable", n.code) : g(n.code);
125
+ const c = Y(n.value.url), A = N(n.value.token);
126
+ if (!c || !A) return l("unavailable", "BAD_ANSWER");
127
+ h = A;
128
+ const _ = await q(e.centrifuge);
129
+ if (u()) return;
130
+ if (!_) return l("unavailable", null);
131
+ const S = (t) => _.UnauthorizedError ? new _.UnauthorizedError(t) : new Error(t), L = async () => {
132
+ const t = y;
133
+ if (y = null, t && t.exp - E() > O)
134
+ return v(t.exp), t.token;
135
+ const o = await r.realtime.token();
136
+ if (u()) throw S("closed");
137
+ if (o.ok) {
138
+ if (N(o.value.token) !== h)
139
+ throw queueMicrotask(() => l("unavailable", "BAD_ANSWER")), S("BAD_ANSWER");
140
+ return v(T(o.value)), o.value.token;
141
+ }
142
+ throw b.has(o.code) ? new Error(o.code) : (queueMicrotask(() => g(o.code)), S(o.code));
143
+ }, k = c, i = new _.Centrifuge(
144
+ [
145
+ { transport: "websocket", endpoint: `${k.replace(/^http/, "ws")}/connection/websocket` },
146
+ { transport: "http_stream", endpoint: `${k}/connection/http_stream` }
147
+ ],
148
+ { token: n.value.token, getToken: L, emulationEndpoint: `${k}/emulation`, name: "blogmcp-private" }
149
+ );
150
+ a = i, i.on("connecting", () => {
151
+ i === a && d === "live" && R("connecting");
152
+ }), i.on("subscribed", (t) => {
153
+ i === a && m(t) && t.channel === h && R("live");
154
+ }), i.on("unsubscribed", (t) => {
155
+ i === a && m(t) && t.channel === h && l("refused", null);
156
+ }), i.on("publication", (t) => {
157
+ if (i !== a || !m(t) || t.channel !== h) return;
158
+ const o = j(t.data);
159
+ if (o)
160
+ for (const U of [...s])
161
+ try {
162
+ U(o);
163
+ } catch {
164
+ }
165
+ }), i.on("disconnected", (t) => {
166
+ if (i !== a) return;
167
+ const o = m(t) ? t.code : void 0;
168
+ if (o === 1) return l("refused", null);
169
+ if (o === P || $(o)) return l("revoked", String(o));
170
+ }), v(T(n.value)), i.connect();
171
+ }
172
+ return {
173
+ get mode() {
174
+ return d;
175
+ },
176
+ get channel() {
177
+ return h;
178
+ },
179
+ subscribe(n) {
180
+ if (u() || typeof n != "function") return () => {
181
+ };
182
+ s.add(n), d === "idle" && D().catch(() => l("unavailable", null));
183
+ let c = !0;
184
+ return () => {
185
+ c && (c = !1, s.delete(n), s.size === 0 && l("closed", null));
186
+ };
187
+ },
188
+ close() {
189
+ l("closed", null);
190
+ }
191
+ };
192
+ }
193
+ export {
194
+ x as PRIVATE_RT_RENEW_MARGIN_MS,
195
+ Q as createPrivateRealtime,
196
+ N as inboxChannelOfToken,
197
+ j as privateRealtimeEventOf,
198
+ Y as privateRealtimeUrlOf
199
+ };
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The private session in the browser (docs/internal/m4-contracts.md §6.1, §5.9).
3
+ *
4
+ * **Getting a session.** `ensureSession()`: the device key (keystore.ts) → a refresh with a proof when the record
5
+ * holds a refresh token, or else a grant from the host's `grantPath` (the host's server turns its own member session
6
+ * into a one-minute grant for this key: `createPrivateGrantHandler`) redeemed at `private/session`. The access token
7
+ * lives in this tab's memory only (one per tab; a refresh adds a token on kb-api and invalidates none, §5.9).
8
+ *
9
+ * **Many tabs.** Every refresh and every grant runs inside `navigator.locks.request('blogmcp-private-<memberHash>')`
10
+ * and re-reads the record from IndexedDB after taking the lock, so a burst of tabs never refreshes past kb-api's cap of
11
+ * eight access tokens per session. Before it refreshes, a tab takes the newest access token another tab of the same
12
+ * member already holds, through a `BroadcastChannel` of the same name: every tab announces the token it obtained, and
13
+ * a tab with none asks once. So nine tabs open over fifteen minutes cause one refresh per token lifetime between them,
14
+ * and no new session.
15
+ *
16
+ * **The recovery rule.** `UNAUTHORIZED` on a call triggers one refresh under the lock; only `UNAUTHORIZED` on the
17
+ * refresh triggers one grant. A grant opens a new `sessions` row on kb-api, so a grant per failed call would orphan
18
+ * sessions. `DEVICE_REMOVED` deletes the record and makes a new key: a new, pending device at the next grant.
19
+ *
20
+ * **The proof's two retries** (dpop.ts): one on `DPOP_NONCE` with the nonce the refusal carried, one on `DPOP_INVALID`
21
+ * when the refusal's `serverTime` shows the clock was more than 60 s off.
22
+ *
23
+ * **The host's session decides** (§5.9). `start()` asks the host for its current member (the `me/get` it reads anyway):
24
+ * for every stored record of another member — a shared browser where B now signs in after A — and for every record
25
+ * when the host has no member at all, it unsubscribes that device's private push (so the shared push endpoint stops
26
+ * pinging for the previous member), ends the private session and deletes the refresh token, keeping the key (that
27
+ * member's device). `privateSignOut()` unsubscribes the device's private push, ends the session and deletes the
28
+ * refresh token; the hosts call it in their sign-out flows, before or after ending their own session (when the host's
29
+ * member is already gone it ends the record this tab used and every stored tenant session, as `start()` would on the
30
+ * next load). `forget()` removes the device on kb-api (`devices/forget`) and deletes the record.
31
+ *
32
+ * **Under `provider_page`** (the account host's `/zpravy`, §6.4) there is no `me/get` and no grant path: every load
33
+ * starts with the hand-off (handoff.ts), the record is keyed by the hand-off's `memberRef`, and the refresh token is
34
+ * kept in this tab's `sessionStorage` only, never in IndexedDB. A sign-out on the site therefore ends the private view
35
+ * at the next load, and the next person on a shared browser never reaches the previous member's session. A load that
36
+ * finds this tab's previous refresh token ends that session before it opens the new one, so reloading the page does not
37
+ * leave one live session per load behind.
38
+ *
39
+ * Nothing here logs, tracks or reports: the private entry imports no error tracker, analytics or RUM (§9.3).
40
+ */
41
+ import type { CommunityApiCode } from '../outcome.js';
42
+ import { type PrivateRendering } from './keystore.js';
43
+ /** The SDK's own codes besides kb-api's (`CommunityApiCode`, `UNKNOWN_PATH`). */
44
+ export type PrivateClientCode =
45
+ /** The host has no member session (tenant rendering): sign in on the site first. */
46
+ 'NO_MEMBER'
47
+ /** `provider_page`: no session in this tab — the page starts the hand-off. */
48
+ | 'HANDOFF_REQUIRED'
49
+ /** `provider_page`: the hand-off's fragment is not the one this tab started (a foreign `state`, a stale link). */
50
+ | 'HANDOFF_INVALID'
51
+ /** `provider_page`: the hand-off named another member; the page navigated to repeat it with that member's key. */
52
+ | 'HANDOFF_REPEATED'
53
+ /** No answer: the network, a timeout, a refused redirect, CORS. */
54
+ | 'NETWORK'
55
+ /** An answer that is not kb-api's or the host's (a gateway's page, a malformed grant). */
56
+ | 'BAD_ANSWER';
57
+ export type PrivateCode = CommunityApiCode | 'UNKNOWN_PATH' | PrivateClientCode;
58
+ export interface PrivateFailure {
59
+ ok: false;
60
+ code: PrivateCode;
61
+ /** The HTTP status, or null when there was none. */
62
+ status: number | null;
63
+ }
64
+ /** What every private call resolves to; nothing here throws on a refusal. */
65
+ export type PrivateOutcome<T> = {
66
+ ok: true;
67
+ value: T;
68
+ } | PrivateFailure;
69
+ /** What `private/session` says of the device, the address and the activation (§5.9). */
70
+ export interface PrivateSessionOpened {
71
+ readonly device: {
72
+ readonly state: 'first' | 'pending' | 'approved';
73
+ readonly label: string | null;
74
+ };
75
+ readonly address: {
76
+ readonly state: 'none' | 'pending' | 'verified';
77
+ };
78
+ /**
79
+ * kb-api's activation vocabulary (`ActivationStateValue` of PS4's activation service), the same values as the
80
+ * client's `PrivateActivation['state']`: one field, one set of values, whichever route answers it.
81
+ */
82
+ readonly activation: {
83
+ readonly state: 'active' | 'needed' | 'refused';
84
+ };
85
+ }
86
+ /** `ensureSession()`'s value: whether this call opened a new session (then with its answer) or reused one. */
87
+ export type PrivateSessionInfo = {
88
+ readonly opened: false;
89
+ } | ({
90
+ readonly opened: true;
91
+ } & PrivateSessionOpened);
92
+ /** The part of the Web Locks API the session uses. */
93
+ export interface PrivateLocks {
94
+ request<T>(name: string, callback: () => Promise<T>): Promise<T>;
95
+ }
96
+ /** The part of BroadcastChannel the session uses. */
97
+ export interface PrivateChannel {
98
+ postMessage(message: unknown): void;
99
+ addEventListener(type: 'message', listener: (event: {
100
+ data: unknown;
101
+ }) => void): void;
102
+ close(): void;
103
+ }
104
+ export interface PrivateSessionConfig {
105
+ /** kb-api's public origin (`https://<slug>.blogmcp.ai`): the key's scope and the only origin a private base may have. */
106
+ kbOrigin: string;
107
+ /** `tenant` (default) or `provider_page` (the account host's `/zpravy`). */
108
+ rendering?: PrivateRendering;
109
+ /** Tenant rendering: the host's grant route on its own origin (`/komunita/grant`, `/blog/community/grant`). */
110
+ grantPath?: string;
111
+ /**
112
+ * Tenant rendering: the host's current member id (`me/get`'s `member.memberId`), or null without a member session.
113
+ * Read on every `ensureSession()` and by `start()`.
114
+ */
115
+ member?: () => Promise<string | null>;
116
+ /** The fetch for kb-api and the host's grant route (a test stub; default the page's fetch). */
117
+ fetch?: () => typeof fetch;
118
+ /** Default `navigator.locks`; without it an in-tab mutex (Safari before 15.4). */
119
+ locks?: PrivateLocks;
120
+ /** Default `new BroadcastChannel(name)`; null turns the sharing between tabs off. */
121
+ channel?: ((name: string) => PrivateChannel) | null;
122
+ indexedDB?: () => IDBFactory;
123
+ sessionStorage?: () => Storage;
124
+ /** Default `navigator.storage.persist()`. */
125
+ persist?: () => Promise<boolean>;
126
+ /** This browser's push endpoint, for `push/unsubscribe` of another member's device (default the service worker's). */
127
+ pushEndpoint?: () => Promise<string | null>;
128
+ now?: () => number;
129
+ timeoutMs?: number;
130
+ /** How long a tab without a token waits for another tab's answer before it refreshes (default 40 ms). */
131
+ askWaitMs?: number;
132
+ /** `provider_page`: navigate the tab (default `location.assign`). */
133
+ navigate?: (url: string) => void;
134
+ }
135
+ /** Refresh when less than this is left of an access token (it lives 600 s). */
136
+ export declare const PRIVATE_REFRESH_MARGIN_MS = 60000;
137
+ /** The `sessionStorage` keys under `provider_page`. */
138
+ export declare const PRIVATE_SESSION_STORAGE: Readonly<{
139
+ refreshPrefix: "blogmcp-private-refresh:";
140
+ current: "blogmcp-private-current";
141
+ handoff: "blogmcp-private-handoff";
142
+ }>;
143
+ /** The lock and channel name of one member's key (the record id is already a hash). */
144
+ export declare const privateLockName: (recordId: string) => string;
145
+ export interface PrivateSession {
146
+ readonly kbOrigin: string;
147
+ readonly rendering: PrivateRendering;
148
+ /** A usable access token for this tab (refreshed or granted when needed). */
149
+ ensureSession(): Promise<PrivateOutcome<PrivateSessionInfo>>;
150
+ /** One private operation with this session: the recovery rule and the proof's retries applied. */
151
+ call<T = Record<string, unknown>>(op: string, body?: Record<string, unknown>): Promise<PrivateOutcome<T>>;
152
+ /**
153
+ * `push/unsubscribe` and `session/end`, then the refresh token deleted; the key stays (it is this member's device).
154
+ * Safe before or after the host ends its own session: without a host member it ends the record this tab used and
155
+ * every stored tenant session.
156
+ */
157
+ privateSignOut(): Promise<PrivateOutcome<null>>;
158
+ /** `devices/forget`, then the record deleted (key and refresh token). */
159
+ forget(): Promise<PrivateOutcome<null>>;
160
+ /** The host-session check (tenant rendering): ends every stored session that is not the host's current member's. */
161
+ start(): Promise<PrivateOutcome<{
162
+ ended: number;
163
+ }>>;
164
+ /** After an activation: ask the browser to keep this origin's storage (fewer lapses into a new pending device). */
165
+ activated(): Promise<boolean>;
166
+ /** `provider_page`: navigate to the site's hand-off route with this tab's key (see handoff.ts). */
167
+ beginHandoff(handoffUrl: string): Promise<PrivateOutcome<null>>;
168
+ /** `provider_page`: read the hand-off's fragment and open the session (see handoff.ts). */
169
+ completeHandoff(hash: string, handoffUrl: string): Promise<PrivateOutcome<PrivateSessionInfo>>;
170
+ /** For tests and the elements: the current record's thumbprint, or null. */
171
+ currentJkt(): Promise<string | null>;
172
+ /** Stop listening on the channels (an unmounted view). */
173
+ close(): void;
174
+ }
175
+ export declare function createPrivateSession(config: PrivateSessionConfig): PrivateSession;