@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.
- package/dist/community/links.d.ts +6 -0
- package/dist/community/links.js +9 -1
- package/dist/community/outcome.d.ts +1 -1
- package/dist/community/outcome.js +60 -23
- package/dist/community/private/browser.d.ts +18 -0
- package/dist/community/private/browser.js +17 -0
- package/dist/community/private/client.d.ts +259 -0
- package/dist/community/private/client.js +98 -0
- package/dist/community/private/dm.d.ts +547 -0
- package/dist/community/private/dm.js +852 -0
- package/dist/community/private/dpop.d.ts +59 -0
- package/dist/community/private/dpop.js +46 -0
- package/dist/community/private/encoding.d.ts +17 -0
- package/dist/community/private/encoding.js +50 -0
- package/dist/community/private/host-state.d.ts +20 -0
- package/dist/community/private/host-state.js +15 -0
- package/dist/community/private/index.d.ts +51 -0
- package/dist/community/private/index.js +71 -0
- package/dist/community/private/keystore.d.ts +73 -0
- package/dist/community/private/keystore.js +91 -0
- package/dist/community/private/marker.d.ts +17 -0
- package/dist/community/private/marker.js +11 -0
- package/dist/community/private/private-routes.d.ts +6 -0
- package/dist/community/private/private-routes.js +72 -0
- package/dist/community/private/promise.d.ts +65 -0
- package/dist/community/private/promise.js +39 -0
- package/dist/community/private/realtime.d.ts +127 -0
- package/dist/community/private/realtime.js +199 -0
- package/dist/community/private/session.d.ts +175 -0
- package/dist/community/private/session.js +441 -0
- package/dist/community/private/transport.d.ts +47 -0
- package/dist/community/private/transport.js +65 -0
- package/dist/community/server/grant-handoff.d.ts +53 -0
- package/dist/community/server/grant-handoff.js +96 -0
- package/dist/community/server/grant.d.ts +100 -0
- package/dist/community/server/grant.js +165 -0
- package/dist/community/server/index.d.ts +4 -0
- package/dist/community/server/index.js +20 -16
- package/dist/community/shapes.d.ts +27 -1
- package/dist/community/shapes.js +27 -17
- package/dist/core/client.d.ts +9 -0
- package/dist/core/client.js +54 -50
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +113 -103
- package/dist/core/queries.d.ts +1 -0
- package/dist/core/queries.js +76 -71
- package/dist/core/review/types.d.ts +7 -0
- package/dist/core/style-layers.d.ts +88 -0
- package/dist/core/style-layers.js +69 -0
- package/package.json +7 -3
- package/src/community/links.ts +8 -0
- package/src/community/outcome.ts +37 -0
- package/src/community/private/browser.ts +31 -0
- package/src/community/private/client.ts +304 -0
- package/src/community/private/dm.ts +1687 -0
- package/src/community/private/dpop.ts +110 -0
- package/src/community/private/encoding.ts +71 -0
- package/src/community/private/host-state.ts +37 -0
- package/src/community/private/index.ts +169 -0
- package/src/community/private/keystore.ts +179 -0
- package/src/community/private/marker.ts +28 -0
- package/src/community/private/private-routes.ts +80 -0
- package/src/community/private/promise.ts +125 -0
- package/src/community/private/realtime.ts +431 -0
- package/src/community/private/session.ts +848 -0
- package/src/community/private/transport.ts +125 -0
- package/src/community/server/grant-handoff.ts +179 -0
- package/src/community/server/grant.ts +292 -0
- package/src/community/server/index.ts +6 -0
- package/src/community/shapes.ts +46 -1
- package/src/core/client.ts +12 -0
- package/src/core/index.ts +14 -0
- package/src/core/queries.ts +8 -0
- package/src/core/review/types.ts +8 -0
- package/src/core/style-layers.ts +169 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DPoP proofs (RFC 9449) as kb-api's verifier checks them (docs/internal/m4-contracts.md §5.7, `KB/auth/dpop.ts`):
|
|
3
|
+
* header `{ typ: 'dpop+jwt', alg: 'ES256', jwk }`, claims `{ jti, htm, htu, iat, nonce, ath? }`, signed with the
|
|
4
|
+
* device key through WebCrypto — whose ECDSA signature is already the IEEE P1363 `r ‖ s` that JWS ES256 wants
|
|
5
|
+
* (RFC 7518 §3.4), so no DER conversion.
|
|
6
|
+
*
|
|
7
|
+
* - `jti`: 16 random bytes, base64url (22 characters; kb-api takes 16–64 of `[A-Za-z0-9_-]` and spends each once).
|
|
8
|
+
* - `nonce`: kb-api's server nonce for this key, from the grant answer's `dpopNonce` first and then from the
|
|
9
|
+
* `DPoP-Nonce` header of every private answer (CORS exposes it). The cache is per kb-api origin; a refusal
|
|
10
|
+
* `DPOP_NONCE` (`use_dpop_nonce`) carries a fresh one and the caller retries once.
|
|
11
|
+
* - `iat`: the local clock corrected by the offset to kb-api's clock. The offset is kept from the `serverTime`
|
|
12
|
+
* (epoch ms) of the grant answer and of every private JSON answer, refusals included — never from `Date`, which is
|
|
13
|
+
* not a CORS-safelisted response header and reads as null cross-origin. On `DPOP_INVALID` whose `serverTime` is more
|
|
14
|
+
* than 60 s from the corrected clock the caller corrects the offset and retries once.
|
|
15
|
+
* - `ath`: `base64url(sha256(access token))` whenever a token is presented.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { assertPrivateBrowser, subtle } from './browser'
|
|
19
|
+
import { base64url, randomBase64url, sha256, utf8 } from './encoding'
|
|
20
|
+
import type { DevicePublicJwk } from './keystore'
|
|
21
|
+
|
|
22
|
+
assertPrivateBrowser()
|
|
23
|
+
|
|
24
|
+
/** How far the clock may be off before a `DPOP_INVALID` is read as the clock's fault (§5.7). */
|
|
25
|
+
export const DPOP_CLOCK_RETRY_MS = 60_000
|
|
26
|
+
|
|
27
|
+
export interface DpopProofInput {
|
|
28
|
+
privateKey: CryptoKey
|
|
29
|
+
jwk: DevicePublicJwk
|
|
30
|
+
htm: 'POST'
|
|
31
|
+
htu: string
|
|
32
|
+
/** The server nonce for this key, or null when none is known yet (kb-api then answers `use_dpop_nonce`). */
|
|
33
|
+
nonce: string | null
|
|
34
|
+
/** The access token the request presents, for `ath`. */
|
|
35
|
+
accessToken?: string | null
|
|
36
|
+
/** `iat` in epoch seconds (the corrected clock). */
|
|
37
|
+
iat: number
|
|
38
|
+
/** For the shared fixture only: a fixed `jti`. */
|
|
39
|
+
jti?: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `base64url(sha256(token))`, the `ath` claim. */
|
|
43
|
+
export async function dpopAth(accessToken: string): Promise<string> {
|
|
44
|
+
return base64url(await sha256(accessToken))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A compact JWS: the proof for one request. */
|
|
48
|
+
export async function signDpopProof(input: DpopProofInput): Promise<string> {
|
|
49
|
+
const header = { typ: 'dpop+jwt', alg: 'ES256', jwk: { kty: input.jwk.kty, crv: input.jwk.crv, x: input.jwk.x, y: input.jwk.y } }
|
|
50
|
+
const claims: Record<string, unknown> = {
|
|
51
|
+
jti: input.jti ?? randomBase64url(16),
|
|
52
|
+
htm: input.htm,
|
|
53
|
+
htu: input.htu,
|
|
54
|
+
iat: input.iat,
|
|
55
|
+
}
|
|
56
|
+
if (input.nonce !== null) claims.nonce = input.nonce
|
|
57
|
+
if (input.accessToken) claims.ath = await dpopAth(input.accessToken)
|
|
58
|
+
const signingInput = `${base64url(utf8(JSON.stringify(header)))}.${base64url(utf8(JSON.stringify(claims)))}`
|
|
59
|
+
const signature = await subtle().sign({ name: 'ECDSA', hash: 'SHA-256' }, input.privateKey, utf8(signingInput))
|
|
60
|
+
return `${signingInput}.${base64url(new Uint8Array(signature))}`
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A server nonce as kb-api mints them (base64url); anything else from a header is ignored. */
|
|
64
|
+
const NONCE_RE = /^[A-Za-z0-9_-]{8,128}$/
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The per-origin nonce cache and the clock offset of one session (one per tab: neither holds a secret, and another
|
|
68
|
+
* tab's values arrive with its own answers).
|
|
69
|
+
*/
|
|
70
|
+
export interface DpopClock {
|
|
71
|
+
/** The nonce for this origin and key, or null. */
|
|
72
|
+
nonce(origin: string, jkt: string): string | null
|
|
73
|
+
/** Remember a nonce kb-api handed out (a grant answer's `dpopNonce`, an answer's `DPoP-Nonce`). */
|
|
74
|
+
setNonce(origin: string, jkt: string, nonce: unknown): void
|
|
75
|
+
/** Forget every nonce of a key (it was replaced). */
|
|
76
|
+
forgetKey(jkt: string): void
|
|
77
|
+
/** `iat` in epoch seconds, corrected by the offset. */
|
|
78
|
+
iat(): number
|
|
79
|
+
/** The offset in ms (kb-api's clock minus ours). */
|
|
80
|
+
offsetMs(): number
|
|
81
|
+
/**
|
|
82
|
+
* Take a `serverTime` from an answer: the offset follows it. Answers whether the clock was off by more than
|
|
83
|
+
* DPOP_CLOCK_RETRY_MS before this answer (the condition of the one corrected retry).
|
|
84
|
+
*/
|
|
85
|
+
observe(serverTime: unknown): boolean
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function createDpopClock(now: () => number = Date.now): DpopClock {
|
|
89
|
+
const nonces = new Map<string, string>()
|
|
90
|
+
let offset = 0
|
|
91
|
+
const keyOf = (origin: string, jkt: string) => `${origin}|${jkt}`
|
|
92
|
+
return {
|
|
93
|
+
nonce: (origin, jkt) => nonces.get(keyOf(origin, jkt)) ?? null,
|
|
94
|
+
setNonce(origin, jkt, nonce) {
|
|
95
|
+
if (typeof nonce === 'string' && NONCE_RE.test(nonce)) nonces.set(keyOf(origin, jkt), nonce)
|
|
96
|
+
},
|
|
97
|
+
forgetKey(jkt) {
|
|
98
|
+
for (const key of [...nonces.keys()]) if (key.endsWith(`|${jkt}`)) nonces.delete(key)
|
|
99
|
+
},
|
|
100
|
+
iat: () => Math.floor((now() + offset) / 1000),
|
|
101
|
+
offsetMs: () => offset,
|
|
102
|
+
observe(serverTime) {
|
|
103
|
+
if (typeof serverTime !== 'number' || !Number.isFinite(serverTime) || serverTime <= 0) return false
|
|
104
|
+
const fresh = serverTime - now()
|
|
105
|
+
const off = Math.abs(fresh - offset) > DPOP_CLOCK_RETRY_MS
|
|
106
|
+
offset = fresh
|
|
107
|
+
return off
|
|
108
|
+
},
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The byte helpers the private entry needs: base64url (RFC 4648 §5, no padding — what JOSE and kb-api's tokens use),
|
|
3
|
+
* SHA-256 over WebCrypto, and random values from `crypto.getRandomValues`. No dependency, so the entry stays one of
|
|
4
|
+
* plain WebCrypto.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { subtle } from './browser'
|
|
8
|
+
|
|
9
|
+
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
|
|
10
|
+
|
|
11
|
+
/** base64url without padding. */
|
|
12
|
+
export function base64url(bytes: Uint8Array): string {
|
|
13
|
+
let out = ''
|
|
14
|
+
let i = 0
|
|
15
|
+
for (; i + 2 < bytes.length; i += 3) {
|
|
16
|
+
const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!
|
|
17
|
+
out += ALPHABET[(n >> 18) & 63]! + ALPHABET[(n >> 12) & 63]! + ALPHABET[(n >> 6) & 63]! + ALPHABET[n & 63]!
|
|
18
|
+
}
|
|
19
|
+
const rest = bytes.length - i
|
|
20
|
+
if (rest === 1) {
|
|
21
|
+
const n = bytes[i]! << 16
|
|
22
|
+
out += ALPHABET[(n >> 18) & 63]! + ALPHABET[(n >> 12) & 63]!
|
|
23
|
+
} else if (rest === 2) {
|
|
24
|
+
const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8)
|
|
25
|
+
out += ALPHABET[(n >> 18) & 63]! + ALPHABET[(n >> 12) & 63]! + ALPHABET[(n >> 6) & 63]!
|
|
26
|
+
}
|
|
27
|
+
return out
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The bytes of a base64url string, or null for anything that is not one (padding, `+`, `/`, a stray character). */
|
|
31
|
+
export function fromBase64url(text: string): Uint8Array | null {
|
|
32
|
+
if (typeof text !== 'string' || !/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return null
|
|
33
|
+
const out = new Uint8Array(Math.floor((text.length * 3) / 4))
|
|
34
|
+
let bits = 0
|
|
35
|
+
let value = 0
|
|
36
|
+
let o = 0
|
|
37
|
+
for (const ch of text) {
|
|
38
|
+
value = (value << 6) | ALPHABET.indexOf(ch)
|
|
39
|
+
bits += 6
|
|
40
|
+
if (bits >= 8) {
|
|
41
|
+
bits -= 8
|
|
42
|
+
out[o++] = (value >> bits) & 0xff
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** UTF-8 bytes of a string. */
|
|
49
|
+
export function utf8(text: string): Uint8Array<ArrayBuffer> {
|
|
50
|
+
return new TextEncoder().encode(text)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** SHA-256 of bytes or of a string's UTF-8. */
|
|
54
|
+
export async function sha256(input: Uint8Array | string): Promise<Uint8Array> {
|
|
55
|
+
const bytes = typeof input === 'string' ? utf8(input) : new Uint8Array(input)
|
|
56
|
+
return new Uint8Array(await subtle().digest('SHA-256', bytes))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Lower-case hex of bytes. */
|
|
60
|
+
export function hex(bytes: Uint8Array): string {
|
|
61
|
+
let out = ''
|
|
62
|
+
for (const b of bytes) out += b.toString(16).padStart(2, '0')
|
|
63
|
+
return out
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** `n` random bytes as base64url (a JWT `jti`, a hand-off `state`). */
|
|
67
|
+
export function randomBase64url(n: number): string {
|
|
68
|
+
const bytes = new Uint8Array(n)
|
|
69
|
+
globalThis.crypto.getRandomValues(bytes)
|
|
70
|
+
return base64url(bytes)
|
|
71
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a host reads from its own `me/get` before it mounts anything private (docs/internal/m4-contracts.md §5.11):
|
|
3
|
+
* the module block gains `private: { state, rendering }` — additive, absent from a kb-api before PS4. The dock and the
|
|
4
|
+
* blogs mount the private view only on `live` (or `read_only`, for the safety minimum), and under `provider_page` they
|
|
5
|
+
* render only the link to the account host.
|
|
6
|
+
*
|
|
7
|
+
* The block's type is the public shapes' (`ModuleInfo.private`, `PrivateModuleBlock` in shapes.ts), which the shapes'
|
|
8
|
+
* drift spec compares with kb-api's `ModuleBlock` member for member; this module only reads it.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { PrivateModuleBlock, PrivateSurfaceState } from '../shapes'
|
|
12
|
+
|
|
13
|
+
export type { PrivateModuleBlock }
|
|
14
|
+
|
|
15
|
+
export const PRIVATE_STATES: readonly PrivateSurfaceState[] = Object.freeze(['dark', 'live', 'read_only', 'braked'] as const)
|
|
16
|
+
export type PrivateState = PrivateSurfaceState
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The private block of a `me/get` answer (`MyState`), or null when kb-api sends none or one this SDK does not know —
|
|
20
|
+
* read as `dark`: nothing private is mounted.
|
|
21
|
+
*/
|
|
22
|
+
export function privateBlockOf(me: unknown): PrivateModuleBlock | null {
|
|
23
|
+
const module = (me as { module?: { private?: unknown } } | null)?.module
|
|
24
|
+
const block = module?.private as { state?: unknown; rendering?: unknown } | undefined
|
|
25
|
+
if (!block || typeof block !== 'object') return null
|
|
26
|
+
if (!(PRIVATE_STATES as readonly unknown[]).includes(block.state)) return null
|
|
27
|
+
const rendering = block.rendering === 'provider_page' ? 'provider_page' : block.rendering === 'tenant' ? 'tenant' : null
|
|
28
|
+
if (rendering === null) return null
|
|
29
|
+
return Object.freeze({ state: block.state as PrivateState, rendering })
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** What the host mounts for a private block: the private view, only the account host's link, or nothing. */
|
|
33
|
+
export function privateMountOf(block: PrivateModuleBlock | null): 'view' | 'link' | 'none' {
|
|
34
|
+
// §5.11: only on `live`, or `read_only` for the safety minimum (export, leave, report, appeal).
|
|
35
|
+
if (block === null || (block.state !== 'live' && block.state !== 'read_only')) return 'none'
|
|
36
|
+
return block.rendering === 'provider_page' ? 'link' : 'view'
|
|
37
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@blogmcp/sdk/community/private` — the member's private session in the browser (docs/internal/m4-contracts.md §6.1):
|
|
3
|
+
* the device key in IndexedDB, DPoP proofs, kb-api's private surface reached directly with no credentials, the
|
|
4
|
+
* session's lifecycle across tabs, the private view's marker and the promise as data. The private elements
|
|
5
|
+
* (`@blogmcp/community/private`) are built on it; a host mounts those, not this entry, unless it renders its own UI.
|
|
6
|
+
*
|
|
7
|
+
* BROWSER-ONLY by contract: importing it where `window`, `indexedDB` or `crypto.subtle` is missing throws (the device
|
|
8
|
+
* key must never exist on a server). Its server half — the grant route a host serves — is
|
|
9
|
+
* `createPrivateGrantHandler` / `createPrivateGrantHandoff` in `@blogmcp/sdk/community/server`, and this entry never
|
|
10
|
+
* imports it. It imports no error tracker, analytics or RUM, and a host that adds one excludes the private view
|
|
11
|
+
* (`PRIVATE_ROOT_ATTR`, `PRIVATE_VIEW_EVENT`).
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* // Client-only code of a host (a lazy chunk mounted when me/get's module.private.state is live):
|
|
15
|
+
* const client = createPrivateClient({
|
|
16
|
+
* kbOrigin: 'https://tenant.blogmcp.ai',
|
|
17
|
+
* grantPath: '/komunita/grant',
|
|
18
|
+
* member: async () => (await community.me.get()).value?.member?.memberId ?? null,
|
|
19
|
+
* })
|
|
20
|
+
* await client.session.start() // ends another member's stored session on a shared browser
|
|
21
|
+
* const s = await ensureSession(client)
|
|
22
|
+
* // …and in the host's sign-out flow:
|
|
23
|
+
* await privateSignOut(client)
|
|
24
|
+
* // The member's inbox, live (the elements' `realtime` property takes `createPrivateRealtime` itself):
|
|
25
|
+
* const realtime = createPrivateRealtime({ client })
|
|
26
|
+
* const off = realtime.subscribe((event) => console.log(event.k))
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { assertPrivateBrowser } from './browser'
|
|
31
|
+
|
|
32
|
+
assertPrivateBrowser()
|
|
33
|
+
|
|
34
|
+
export { PRIVATE_SERVER_IMPORT_MESSAGE, isPrivateBrowser } from './browser'
|
|
35
|
+
|
|
36
|
+
export { createPrivateClient, ensureSession, privateSignOut, forgetDevice, PRIVATE_CLIENT_OPS, PRIVATE_OPS_AHEAD } from './client'
|
|
37
|
+
export type {
|
|
38
|
+
PrivateClient,
|
|
39
|
+
PrivateClientConfig,
|
|
40
|
+
PrivateClientOp,
|
|
41
|
+
PrivateStateAnswer,
|
|
42
|
+
PrivateDeviceState,
|
|
43
|
+
PrivateDevice,
|
|
44
|
+
PrivateReadHour,
|
|
45
|
+
PrivateApprovalRequest,
|
|
46
|
+
PrivateApprovalStart,
|
|
47
|
+
PrivateLegalText,
|
|
48
|
+
PrivateActivation,
|
|
49
|
+
PrivateActivationState,
|
|
50
|
+
PrivateActivationAccept,
|
|
51
|
+
PrivateTextProof,
|
|
52
|
+
PrivatePushSubscription,
|
|
53
|
+
PrivateNotification,
|
|
54
|
+
PrivateNotificationsQuery,
|
|
55
|
+
PrivateNotificationsMarkRead,
|
|
56
|
+
} from './client'
|
|
57
|
+
|
|
58
|
+
export {
|
|
59
|
+
createPrivateRealtime,
|
|
60
|
+
inboxChannelOfToken,
|
|
61
|
+
privateRealtimeEventOf,
|
|
62
|
+
privateRealtimeUrlOf,
|
|
63
|
+
PRIVATE_RT_RENEW_MARGIN_MS,
|
|
64
|
+
} from './realtime'
|
|
65
|
+
export type {
|
|
66
|
+
PrivateRealtime,
|
|
67
|
+
PrivateRealtimeOptions,
|
|
68
|
+
PrivateRealtimeEvent,
|
|
69
|
+
PrivateRealtimeListener,
|
|
70
|
+
PrivateRealtimeMode,
|
|
71
|
+
PrivateRealtimeEnd,
|
|
72
|
+
PrivateRealtimeEndReason,
|
|
73
|
+
PrivateRealtimeTokenAnswer,
|
|
74
|
+
PrivateCentrifugeLike,
|
|
75
|
+
PrivateCentrifugeModuleLike,
|
|
76
|
+
} from './realtime'
|
|
77
|
+
|
|
78
|
+
export { createPrivateSession, PRIVATE_REFRESH_MARGIN_MS, PRIVATE_SESSION_STORAGE, privateLockName } from './session'
|
|
79
|
+
export type {
|
|
80
|
+
PrivateSession,
|
|
81
|
+
PrivateSessionConfig,
|
|
82
|
+
PrivateSessionInfo,
|
|
83
|
+
PrivateSessionOpened,
|
|
84
|
+
PrivateOutcome,
|
|
85
|
+
PrivateFailure,
|
|
86
|
+
PrivateCode,
|
|
87
|
+
PrivateClientCode,
|
|
88
|
+
PrivateLocks,
|
|
89
|
+
PrivateChannel,
|
|
90
|
+
} from './session'
|
|
91
|
+
|
|
92
|
+
export { PRIVATE_DB_NAME, PRIVATE_DB_STORE, jwkThumbprint, privateRecordId } from './keystore'
|
|
93
|
+
export type { DevicePublicJwk, PrivateKeyRecord, PrivateRendering } from './keystore'
|
|
94
|
+
|
|
95
|
+
export { DPOP_CLOCK_RETRY_MS, signDpopProof, dpopAth, createDpopClock } from './dpop'
|
|
96
|
+
export type { DpopProofInput, DpopClock } from './dpop'
|
|
97
|
+
|
|
98
|
+
export { PRIVATE_BASE_PATH, PRIVATE_TIMEOUT_MS, kbOriginOf, privateBaseOf } from './transport'
|
|
99
|
+
|
|
100
|
+
export { PRIVATE_ROUTES } from './private-routes'
|
|
101
|
+
export type { PrivateRoute } from './private-routes'
|
|
102
|
+
|
|
103
|
+
export { PRIVATE_ROOT_ATTR, PRIVATE_VIEW_EVENT, markPrivateRoot } from './marker'
|
|
104
|
+
export type { PrivateViewEventDetail } from './marker'
|
|
105
|
+
|
|
106
|
+
export { privatePromise, PRIVATE_PROMISE_KEYS, PRIVATE_PROMISE_MESSAGES_CS } from './promise'
|
|
107
|
+
export type { PrivatePromise, PrivatePromiseInput, PrivatePromiseKey, PrivateReceives, PrivateSpace, PrivateIdentity, PrivatePromiseRendering } from './promise'
|
|
108
|
+
|
|
109
|
+
export { PRIVATE_STATES, privateBlockOf, privateMountOf } from './host-state'
|
|
110
|
+
export type { PrivateModuleBlock, PrivateState } from './host-state'
|
|
111
|
+
export type { PrivateSurfaceState } from '../shapes'
|
|
112
|
+
|
|
113
|
+
export {
|
|
114
|
+
createPrivateDmClient,
|
|
115
|
+
dmEventEffect,
|
|
116
|
+
isBoundedDmFailure,
|
|
117
|
+
isRetryableDmFailure,
|
|
118
|
+
privateDmMessageOf,
|
|
119
|
+
PRIVATE_DM_EVENT_KINDS,
|
|
120
|
+
PRIVATE_DM_MESSAGE_STATES,
|
|
121
|
+
PRIVATE_DM_OPS,
|
|
122
|
+
PRIVATE_DM_OPS_AHEAD,
|
|
123
|
+
PRIVATE_DM_PAGE_MAX,
|
|
124
|
+
PRIVATE_DM_REREAD_PAGES,
|
|
125
|
+
PRIVATE_DM_RETRY,
|
|
126
|
+
PRIVATE_DM_RETRY_BOUNDED,
|
|
127
|
+
PRIVATE_DM_RETRYABLE,
|
|
128
|
+
PRIVATE_DM_TYPING_INTERVAL_MS,
|
|
129
|
+
PRIVATE_DM_TYPING_SHOW_MS,
|
|
130
|
+
} from './dm'
|
|
131
|
+
export type {
|
|
132
|
+
PrivateDmAudience,
|
|
133
|
+
PrivateDmBlock,
|
|
134
|
+
PrivateDmBlockReportInput,
|
|
135
|
+
PrivateDmCase,
|
|
136
|
+
PrivateDmClient,
|
|
137
|
+
PrivateDmClientCode,
|
|
138
|
+
PrivateDmClientOptions,
|
|
139
|
+
PrivateDmClientSource,
|
|
140
|
+
PrivateDmConversation,
|
|
141
|
+
PrivateDmCounterpart,
|
|
142
|
+
PrivateDmDrafts,
|
|
143
|
+
PrivateDmEditInput,
|
|
144
|
+
PrivateDmEventEffect,
|
|
145
|
+
PrivateDmExport,
|
|
146
|
+
PrivateDmFailure,
|
|
147
|
+
PrivateDmMessage,
|
|
148
|
+
PrivateDmMessagesQuery,
|
|
149
|
+
PrivateDmMessageState,
|
|
150
|
+
PrivateDmOp,
|
|
151
|
+
PrivateDmOpened,
|
|
152
|
+
PrivateDmPage,
|
|
153
|
+
PrivateDmReadResult,
|
|
154
|
+
PrivateDmPendingSend,
|
|
155
|
+
PrivateDmReportInput,
|
|
156
|
+
PrivateDmReportLine,
|
|
157
|
+
PrivateDmReportPreview,
|
|
158
|
+
PrivateDmReportRecipients,
|
|
159
|
+
PrivateDmReportTarget,
|
|
160
|
+
PrivateDmRequest,
|
|
161
|
+
PrivateDmSending,
|
|
162
|
+
PrivateDmSendInput,
|
|
163
|
+
PrivateDmSendOutcome,
|
|
164
|
+
PrivateDmSlice,
|
|
165
|
+
PrivateDmStatement,
|
|
166
|
+
PrivateDmThread,
|
|
167
|
+
PrivateDmThreadListener,
|
|
168
|
+
PrivateDmThreadState,
|
|
169
|
+
} from './dm'
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The device key (docs/internal/m4-contracts.md §6.1, §4.5, §5.9). One ECDSA P-256 key pair per member per browser,
|
|
3
|
+
* made by `crypto.subtle.generateKey(…, false, ['sign'])`: the private half is not extractable, and it is stored as
|
|
4
|
+
* the `CryptoKey` itself (a structured-clone value) in IndexedDB — database `blogmcp-private`, store `keys` — never
|
|
5
|
+
* exported, never serialised. The public half is exported as a JWK for the proof header and its RFC 7638 thumbprint
|
|
6
|
+
* (`jkt`), which is the device's identity on kb-api.
|
|
7
|
+
*
|
|
8
|
+
* A record's key is `sha256(<kb origin> ‖ "|" ‖ <member>)` in hex: two members on one browser have two keys, so each
|
|
9
|
+
* is one device of its own member, and the record names no member in clear. `<member>` is the member id the host's
|
|
10
|
+
* `me/get` gives under tenant rendering, and the hand-off's `memberRef` under `provider_page` (the account page never
|
|
11
|
+
* learns a member id).
|
|
12
|
+
*
|
|
13
|
+
* The record also holds, under tenant rendering, the session's refresh token (B-33: a refresh token bound to a
|
|
14
|
+
* non-extractable key is useless without that key — RFC 9449 §5 — and keeping it spares a grant on every page load)
|
|
15
|
+
* and the private base the grant named. Under `provider_page` the refresh token lives in this tab's `sessionStorage`
|
|
16
|
+
* only (session.ts), so every new load proves the site's current host session through the hand-off. The access token
|
|
17
|
+
* is never stored anywhere (session.ts keeps it in memory).
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { assertPrivateBrowser, subtle } from './browser'
|
|
21
|
+
import { base64url, hex, randomBase64url, sha256, utf8 } from './encoding'
|
|
22
|
+
|
|
23
|
+
assertPrivateBrowser()
|
|
24
|
+
|
|
25
|
+
export const PRIVATE_DB_NAME = 'blogmcp-private'
|
|
26
|
+
export const PRIVATE_DB_STORE = 'keys'
|
|
27
|
+
const PRIVATE_DB_VERSION = 1
|
|
28
|
+
|
|
29
|
+
/** How the private view is rendered: on the tenant's site, or on blogmcp's account host (`/zpravy`). */
|
|
30
|
+
export type PrivateRendering = 'tenant' | 'provider_page'
|
|
31
|
+
|
|
32
|
+
/** The public JWK of a device key: exactly the members RFC 7638 hashes, so the proof header carries nothing else. */
|
|
33
|
+
export interface DevicePublicJwk {
|
|
34
|
+
readonly kty: 'EC'
|
|
35
|
+
readonly crv: 'P-256'
|
|
36
|
+
readonly x: string
|
|
37
|
+
readonly y: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** One device key and what belongs to it (see the module doc). */
|
|
41
|
+
export interface PrivateKeyRecord {
|
|
42
|
+
/** `sha256(kbOrigin ‖ "|" ‖ member)` in hex, or `unbound:<random>` for a `provider_page` key before its first hand-off. */
|
|
43
|
+
readonly id: string
|
|
44
|
+
readonly kbOrigin: string
|
|
45
|
+
readonly rendering: PrivateRendering
|
|
46
|
+
readonly keyPair: CryptoKeyPair
|
|
47
|
+
readonly publicJwk: DevicePublicJwk
|
|
48
|
+
readonly jkt: string
|
|
49
|
+
/** Tenant rendering only; `provider_page` keeps it in sessionStorage. Null without a session. */
|
|
50
|
+
readonly refreshToken: string | null
|
|
51
|
+
/** The absolute private base the last grant answer named (transport.ts checks it again on every use). */
|
|
52
|
+
readonly privateBase: string | null
|
|
53
|
+
readonly createdAt: number
|
|
54
|
+
readonly usedAt: number
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The record id of a member's key on one kb-api origin. */
|
|
58
|
+
export async function privateRecordId(kbOrigin: string, member: string): Promise<string> {
|
|
59
|
+
return hex(await sha256(`${kbOrigin}|${member}`))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** An id for a key made before the member is known (the first hand-off under `provider_page`). */
|
|
63
|
+
export function unboundRecordId(): string {
|
|
64
|
+
return `unbound:${randomBase64url(16)}`
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const isUnboundRecordId = (id: string): boolean => id.startsWith('unbound:')
|
|
68
|
+
|
|
69
|
+
/** RFC 7638: the SHA-256 of the required members in lexicographic order, no whitespace, base64url. */
|
|
70
|
+
export async function jwkThumbprint(jwk: DevicePublicJwk): Promise<string> {
|
|
71
|
+
const canonical = `{"crv":"${jwk.crv}","kty":"${jwk.kty}","x":"${jwk.x}","y":"${jwk.y}"}`
|
|
72
|
+
return base64url(await sha256(utf8(canonical)))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A new non-extractable P-256 signing key, its public JWK and its thumbprint. */
|
|
76
|
+
export async function generateDeviceKey(): Promise<{ keyPair: CryptoKeyPair; publicJwk: DevicePublicJwk; jkt: string }> {
|
|
77
|
+
const keyPair = (await subtle().generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign'])) as CryptoKeyPair
|
|
78
|
+
// The public half of an asymmetric pair is always exportable, whatever `extractable` says of the private half.
|
|
79
|
+
const jwk = await subtle().exportKey('jwk', keyPair.publicKey)
|
|
80
|
+
if (jwk.kty !== 'EC' || jwk.crv !== 'P-256' || typeof jwk.x !== 'string' || typeof jwk.y !== 'string') {
|
|
81
|
+
throw new Error('[blogmcp-sdk] the browser made a key that is not a P-256 key')
|
|
82
|
+
}
|
|
83
|
+
const publicJwk: DevicePublicJwk = Object.freeze({ kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y })
|
|
84
|
+
return { keyPair, publicJwk, jkt: await jwkThumbprint(publicJwk) }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ───────────────────────── IndexedDB ─────────────────────────
|
|
88
|
+
|
|
89
|
+
function promiseOf<T>(request: IDBRequest<T>): Promise<T> {
|
|
90
|
+
return new Promise((resolve, reject) => {
|
|
91
|
+
request.onsuccess = () => resolve(request.result)
|
|
92
|
+
request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed'))
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function openDb(factory: IDBFactory): Promise<IDBDatabase> {
|
|
97
|
+
return new Promise((resolve, reject) => {
|
|
98
|
+
const request = factory.open(PRIVATE_DB_NAME, PRIVATE_DB_VERSION)
|
|
99
|
+
request.onupgradeneeded = () => {
|
|
100
|
+
const db = request.result
|
|
101
|
+
if (!db.objectStoreNames.contains(PRIVATE_DB_STORE)) db.createObjectStore(PRIVATE_DB_STORE, { keyPath: 'id' })
|
|
102
|
+
}
|
|
103
|
+
request.onsuccess = () => resolve(request.result)
|
|
104
|
+
request.onerror = () => reject(request.error ?? new Error('IndexedDB open failed'))
|
|
105
|
+
request.onblocked = () => reject(new Error('IndexedDB open blocked'))
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The store of device keys. Every call opens its own short transaction and re-reads (another tab may have written). */
|
|
110
|
+
export interface PrivateKeystore {
|
|
111
|
+
get(id: string): Promise<PrivateKeyRecord | null>
|
|
112
|
+
put(record: PrivateKeyRecord): Promise<void>
|
|
113
|
+
delete(id: string): Promise<void>
|
|
114
|
+
/** Every record of this kb origin. */
|
|
115
|
+
list(): Promise<PrivateKeyRecord[]>
|
|
116
|
+
/** A new key under `id` (replacing whatever was there: the old key is gone for good). */
|
|
117
|
+
create(id: string, rendering: PrivateRendering): Promise<PrivateKeyRecord>
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function createPrivateKeystore(options: { kbOrigin: string; indexedDB?: () => IDBFactory; now?: () => number }): PrivateKeystore {
|
|
121
|
+
const factory = options.indexedDB ?? (() => globalThis.indexedDB)
|
|
122
|
+
const now = options.now ?? Date.now
|
|
123
|
+
const kbOrigin = options.kbOrigin
|
|
124
|
+
|
|
125
|
+
async function withStore<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
|
|
126
|
+
const db = await openDb(factory())
|
|
127
|
+
try {
|
|
128
|
+
const tx = db.transaction(PRIVATE_DB_STORE, mode)
|
|
129
|
+
const done = new Promise<void>((resolve, reject) => {
|
|
130
|
+
tx.oncomplete = () => resolve()
|
|
131
|
+
tx.onerror = () => reject(tx.error ?? new Error('IndexedDB transaction failed'))
|
|
132
|
+
tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted'))
|
|
133
|
+
})
|
|
134
|
+
const result = await promiseOf(fn(tx.objectStore(PRIVATE_DB_STORE)))
|
|
135
|
+
await done
|
|
136
|
+
return result
|
|
137
|
+
} finally {
|
|
138
|
+
db.close()
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const isRecord = (value: unknown): value is PrivateKeyRecord =>
|
|
143
|
+
!!value && typeof value === 'object' && typeof (value as PrivateKeyRecord).id === 'string' && (value as PrivateKeyRecord).kbOrigin === kbOrigin
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
async get(id) {
|
|
147
|
+
const value = await withStore('readonly', (s) => s.get(id))
|
|
148
|
+
return isRecord(value) ? value : null
|
|
149
|
+
},
|
|
150
|
+
async put(record) {
|
|
151
|
+
await withStore('readwrite', (s) => s.put(record))
|
|
152
|
+
},
|
|
153
|
+
async delete(id) {
|
|
154
|
+
await withStore('readwrite', (s) => s.delete(id))
|
|
155
|
+
},
|
|
156
|
+
async list() {
|
|
157
|
+
const all = await withStore('readonly', (s) => s.getAll())
|
|
158
|
+
return (all as unknown[]).filter(isRecord)
|
|
159
|
+
},
|
|
160
|
+
async create(id, rendering) {
|
|
161
|
+
const key = await generateDeviceKey()
|
|
162
|
+
const at = now()
|
|
163
|
+
const record: PrivateKeyRecord = {
|
|
164
|
+
id,
|
|
165
|
+
kbOrigin,
|
|
166
|
+
rendering,
|
|
167
|
+
keyPair: key.keyPair,
|
|
168
|
+
publicJwk: key.publicJwk,
|
|
169
|
+
jkt: key.jkt,
|
|
170
|
+
refreshToken: null,
|
|
171
|
+
privateBase: null,
|
|
172
|
+
createdAt: at,
|
|
173
|
+
usedAt: at,
|
|
174
|
+
}
|
|
175
|
+
await withStore('readwrite', (s) => s.put(record))
|
|
176
|
+
return record
|
|
177
|
+
},
|
|
178
|
+
}
|
|
179
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The private view's marker (docs/internal/m4-contracts.md §6.1, §7.1). A host pauses its analytics and any RUM while
|
|
3
|
+
* private content is on screen: the private view's root carries `data-blogmcp-private`, and `document` receives
|
|
4
|
+
* `blogmcp:private-view` with `{ open: true }` when it mounts and `{ open: false }` when it goes. The storefront's Umami
|
|
5
|
+
* filter drops every event whose target is inside `[data-blogmcp-private]` (PH3).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export const PRIVATE_ROOT_ATTR = 'data-blogmcp-private'
|
|
9
|
+
export const PRIVATE_VIEW_EVENT = 'blogmcp:private-view'
|
|
10
|
+
|
|
11
|
+
/** The event's detail. */
|
|
12
|
+
export interface PrivateViewEventDetail {
|
|
13
|
+
open: boolean
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Marks `el` as the private view's root (or unmarks it with `open: false`) and tells the page. Returns a function that
|
|
18
|
+
* undoes the mark, for a view's unmount.
|
|
19
|
+
*/
|
|
20
|
+
export function markPrivateRoot(el: Element, open = true): () => void {
|
|
21
|
+
if (open) el.setAttribute(PRIVATE_ROOT_ATTR, '')
|
|
22
|
+
else el.removeAttribute(PRIVATE_ROOT_ATTR)
|
|
23
|
+
const doc = el.ownerDocument ?? (globalThis as { document?: Document }).document
|
|
24
|
+
doc?.dispatchEvent(new CustomEvent<PrivateViewEventDetail>(PRIVATE_VIEW_EVENT, { detail: { open } }))
|
|
25
|
+
return () => {
|
|
26
|
+
if (open) markPrivateRoot(el, false)
|
|
27
|
+
}
|
|
28
|
+
}
|