@tdacorp/hyle-sdk 0.9.0 → 0.12.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/README.md +111 -2
- package/bin/hyle-sdk-engage-keygen.mjs +3 -0
- package/dist/check-routes-bin.js +5 -1
- package/dist/{chunk-54JF4E53.js → chunk-N7ZQUAGM.js} +45 -2
- package/dist/chunk-R5EMI4HQ.js +61 -0
- package/dist/{chunk-XKR74Y5G.js → chunk-S7PCCEHP.js} +1 -1
- package/dist/{chunk-6LW33475.js → chunk-ZQFYH4FX.js} +538 -50
- package/dist/comments.cjs +1048 -0
- package/dist/comments.d.cts +152 -0
- package/dist/comments.d.ts +152 -0
- package/dist/comments.js +1025 -0
- package/dist/{types-BPPZrYOZ.d.cts → embed-DL5QIZRJ.d.ts} +44 -3
- package/dist/{types-C1eCQ2As.d.ts → embed-jCaSI31t.d.cts} +44 -3
- package/dist/engage-keygen-bin.js +67 -0
- package/dist/index.cjs +26 -1
- package/dist/index.d.cts +11 -3
- package/dist/index.d.ts +11 -3
- package/dist/index.js +5 -1
- package/dist/mermaid-diagram.js +9 -54
- package/dist/next.cjs +1010 -78
- package/dist/next.d.cts +163 -6
- package/dist/next.d.ts +163 -6
- package/dist/next.js +442 -14
- package/dist/react.cjs +340 -49
- package/dist/react.d.cts +112 -7
- package/dist/react.d.ts +112 -7
- package/dist/react.js +7 -1
- package/dist/{resolve-Dpb6Orsj.d.ts → resolve-DvmuBlpO.d.ts} +1 -1
- package/dist/{resolve-D2rnnho9.d.cts → resolve-f6IJ6SL9.d.cts} +1 -1
- package/dist/styles.css +117 -0
- package/dist/{types-CHxH5E0S.d.cts → types-5D6ZD0Wi.d.cts} +59 -1
- package/dist/{types-CHxH5E0S.d.ts → types-5D6ZD0Wi.d.ts} +59 -1
- package/dist/use-cache.cjs +5 -1
- package/dist/use-cache.d.cts +2 -2
- package/dist/use-cache.d.ts +2 -2
- package/dist/use-cache.js +2 -2
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -52,13 +52,32 @@ export const { GET, HEAD } = createAssetRoute({ baseUrl: process.env.HYLE_TARGET
|
|
|
52
52
|
|
|
53
53
|
Register the revalidate URL as the workspace's webhook endpoint in hyle. Set `metadataBase` in your root layout so canonical and hreflang URLs are absolute.
|
|
54
54
|
|
|
55
|
+
## RSS feed
|
|
56
|
+
|
|
57
|
+
`hyleFeed` answers an RSS 2.0 feed of the newest articles of the mount's default section. Mount it as a route handler and give it the same options as `hylePage`, plus the site's public origin (feeds need absolute URLs).
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
// app/feed.xml/route.ts
|
|
61
|
+
import { hyleFeed } from "@tdacorp/hyle-sdk/next";
|
|
62
|
+
import { options } from "../hyle-options";
|
|
63
|
+
|
|
64
|
+
export const revalidate = 300;
|
|
65
|
+
export const GET = () => hyleFeed({ ...options, siteOrigin: "https://tdacorp.in", limit: 50 });
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
- `siteOrigin` must be a bare https origin (the same rule as the JSON-LD). Without a valid one the route logs once and answers 404.
|
|
69
|
+
- `limit` defaults to 50 (the server maximum is 100). `feedPath` (default `/feed.xml`) is where you mounted the route; it only fills `<atom:link rel="self">`.
|
|
70
|
+
- The channel title and description come from `list.title` and `list.description`, else hyle's section title. Each item carries the title, the link on the mount (through `localePrefix`), a permalink `guid` equal to the link, `pubDate` from `published_at` and the description when there is one. Every value is XML-escaped, and an item whose `canonical_path` does not start with `/` is dropped.
|
|
71
|
+
- The list is read through the same resolver as `hylePage`, so it shares its fetch cache and publish tags. `export const revalidate` is Next's own route-handler setting and decides how long Next keeps the generated XML; the SDK adds no `cache-control`.
|
|
72
|
+
- A hyle failure answers 503 with an empty body instead of throwing; Next control flow still propagates.
|
|
73
|
+
|
|
55
74
|
## Entry points
|
|
56
75
|
|
|
57
76
|
| Import | Contents | Needs |
|
|
58
77
|
|---|---|---|
|
|
59
78
|
| `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve`, `mounts` and `asset`), `listPublicationPaths`, `checkRoutes` and the other route-check functions, `Cp1ClientError`, `verifyHyleSignature`, `parseSignatureHeader`, `isValidCacheTag`, `DeliveryDedupe`, `createRevalidationCallbackRoute`, the result types | nothing (no framework) |
|
|
60
|
-
| `@tdacorp/hyle-sdk/react` | `ArticlePage`, `ListPage`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
|
|
61
|
-
| `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createRevalidateRoute`, `createAssetRoute`, `fetchResolver`, `workspaceTags` | next >= 16 |
|
|
79
|
+
| `@tdacorp/hyle-sdk/react` | `ArticlePage`, `Comments`, `ListPage`, `HyleListView`, `HyleArticleView`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
|
|
80
|
+
| `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleFeed`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createRevalidateRoute`, `createAssetRoute`, `createEngagementRoute`, `HyleList`, `HyleArticle`, `HyleComments`, `HyleCommentsFallback`, `fetchResolver`, `workspaceTags` | next >= 16 |
|
|
62
81
|
| `@tdacorp/hyle-sdk/next/use-cache` | `cachedResolver` | next >= 16 with `cacheComponents: true` |
|
|
63
82
|
| `@tdacorp/hyle-sdk/styles.css` | the stylesheet | |
|
|
64
83
|
|
|
@@ -216,6 +235,13 @@ What is sent: `PUT /cp1/control/workspace/host-reserved-paths` with `{ paths, ho
|
|
|
216
235
|
|
|
217
236
|
## Host requirements
|
|
218
237
|
|
|
238
|
+
Checklist for a site that mounts hyle at the root (details in the sections named):
|
|
239
|
+
|
|
240
|
+
- A REQUIRED catch-all `app/(site)/[...hyle]/page.tsx` (not `[[...hyle]]`), see "Root catch-all". A single mount that you name (`hylePage` at `/learn`) needs only its own route.
|
|
241
|
+
- `app/api/hyle/assets/[file]/route.ts` exporting `GET` and `HEAD` from `createAssetRoute`, if content has images, video or audio, see "Media".
|
|
242
|
+
- hyle's reserved paths must cover `/api/hyle/*` and your other routes: run `hyle-sdk-check-routes --sync` after `next build` (needs `HYLE_CONTROL_TOKEN`), see "Syncing reserved paths".
|
|
243
|
+
- No parent layout or page above the mount may export `dynamicParams = false` (below).
|
|
244
|
+
|
|
219
245
|
Bundler only: `@tdacorp/hyle-sdk/next` and `/next/use-cache` import `next/navigation` and `next/cache` the way a Next app does, so plain Node ESM cannot import them. Real `next build` runs of the packed package passed with Next 16.2.7, 16.3.4 and 16.4.2 (Turbopack, the default).
|
|
220
246
|
|
|
221
247
|
No layout or page above the mount may export `dynamicParams = false`. hyle content (an article published after your last build) is by definition not known at build time, and Next inherits a parent's `false` for every child route: the route is compiled with `"fallback": false`, so each path not generated at build time is a hard 404 that falls through to any `[locale]/[...rest]` catch-all (observed: `x-matched-path: /[locale]/[...rest]`, content looks missing). Setting `dynamicParams = true` on the page does not override a parent's `false`.
|
|
@@ -234,6 +260,76 @@ Safety: the only input is the `file` segment and it must match `<lowercase uuid>
|
|
|
234
260
|
|
|
235
261
|
The route sits under `/api/hyle/*`, which hyle's Reserved paths must cover (`hyle-sdk-check-routes --print-reserved` always lists `/api/hyle/*`, and so does `--sync`), and the checker prints a note when the build has no `/api/hyle/assets/...` route. If your proxy or middleware matcher intercepts `/api`, exclude `/api/hyle/assets`. Nothing renders `/assets/...` for you outside the SDK's components: a custom renderer of the `hast` tree should map `src` the same way (`/assets/<id>.<ext>` to `/api/hyle/assets/<id>.<ext>`).
|
|
236
262
|
|
|
263
|
+
## Comments and likes
|
|
264
|
+
|
|
265
|
+
Readers can comment and like under an article (hyle ADR 0017, `docs/cp1-spec.md` section 3.11). It is off unless you turn it on in three places, and nothing on a cached page changes when someone likes: the section is fetched in the browser, uncached, after the article has rendered.
|
|
266
|
+
|
|
267
|
+
1. **hyle**: switch engagement on for the workspace and register the site's public key (below).
|
|
268
|
+
2. **A key pair.** `npx hyle-sdk-engage-keygen --out .env.engage` makes an Ed25519 pair: the private key goes to a new file (mode 0600, never overwritten) as `HYLE_ENGAGE_SIGNING_KEY=...`, and the PUBLIC key is printed only after that write succeeded, with a warning if git does not ignore the file. `--stdout` is the only mode that prints the private key; with no arguments the tool prints usage and nothing else. Register the public key in hyle. hyle never sees the private key. To rotate, register the new public key; the old one stays valid for 24 hours.
|
|
269
|
+
3. **The route file** `app/api/hyle/engage/[...path]/route.ts`:
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
import { createEngagementRoute } from "@tdacorp/hyle-sdk/next";
|
|
273
|
+
|
|
274
|
+
export const { GET, POST, PATCH, PUT, DELETE } = createEngagementRoute({
|
|
275
|
+
baseUrl: process.env.HYLE_TARGET_BASE_URL,
|
|
276
|
+
token: process.env.HYLE_TARGET_TOKEN,
|
|
277
|
+
workspaceId: process.env.HYLE_WORKSPACE_ID, // the target credential's workspace; hyle checks the assertion's claim against it
|
|
278
|
+
signingKey: process.env.HYLE_ENGAGE_SIGNING_KEY,
|
|
279
|
+
// Your own session check. Return { sub, name } for a signed-in reader, null for none. `sub` is any stable id you own (up to 255
|
|
280
|
+
// characters), `name` is what other readers see (up to 200). The visitor's cookies are read by YOU here and never forwarded to hyle.
|
|
281
|
+
getReader: async (req) => {
|
|
282
|
+
const user = await currentUser(req); // your auth
|
|
283
|
+
return user ? { sub: user.id, name: user.displayName } : null;
|
|
284
|
+
},
|
|
285
|
+
});
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
**Rate-limit this route yourself.** hyle limits per reader and per site, but every anonymous read of `/api/hyle/engage/comments` and every `session` check reaches your server first. The route shares ANONYMOUS listings between visitors for 3 seconds (`cacheTtlMs`, 0 turns it off); a signed-in reader's listing is shared only with that same reader (never across readers), a fallback answer is never kept, bodies over 256 KB are never kept, and the whole share is capped at 8 MB (least recently used out first); a write on that server makes everything stale at once, other servers catch up within the window, and `onRequest(req, { action })` runs before any work so you can answer with your own 429 (`action` is `session`, `comments.list`, `comments.create`, `comments.edit`, `comments.delete`, `reactions.add` or `reactions.remove`); put a limit on `/api/hyle/engage` in your middleware or CDN as well. `getReader` runs once per request and its answer is never kept for the next one, so keep it cheap. The name you return is cleaned as hyle cleans it (control, bidi and invisible characters stripped, spaces collapsed, 80 characters) and a reader whose assertion would pass hyle's 2 KiB cap is treated as signed out.
|
|
289
|
+
|
|
290
|
+
Then pass `engagement` to the page: `hylePage({ ..., engagement: { signInHref: "/sign-in" } })`, or `<ArticlePage engagement={{ signInHref: "/sign-in" }} />`. `engagement.endpoint` defaults to `/api/hyle/engage`. `layout: "docs"` has no comments.
|
|
291
|
+
|
|
292
|
+
What the route does, per request: it matches (method, path) against a fixed allowlist (`session`, `comments`, `comments/<uuid>`, `reactions`), rebuilds the body with only the known keys (a comment is 1 to 4000 characters, a path is a canonical site path), and calls hyle with the target credential. An anonymous read carries the bearer only. A signed-in reader's read also carries a separate Ed25519 read assertion (`scope: "read"`, 30 s, not single use) so hyle can add that reader's own state; a write carries a fresh single-use assertion (30 s) of the reader `getReader` returned; a missing or invalid reader is a bare 401 before hyle is called. The browser's cookies and `Authorization` are never forwarded. Writes must be same-origin (`Sec-Fetch-Site: same-origin` when sent, and an `Origin` equal to the request's host, with the scheme compared too when the proxy sends `X-Forwarded-Proto`), carry the header `x-hyle-engage: 1` and `application/json` (at most 20 KiB), otherwise 403/415/413. The host is taken from `X-Forwarded-Host`, else `Host`: behind a proxy that rewrites `Host` or terminates TLS without forwarding these headers, pass `allowedOrigins: ["https://www.example.com"]`, which replaces the derivation with an exact list (scheme, host and port). Every response is `Cache-Control: no-store`. Failures are mapped to a fixed set of codes with no text from hyle: hyle 404 stays 404 (a disabled workspace, a banned reader and a hidden comment look the same), 429 keeps a clamped `Retry-After`, a 409 is an edit after the 10 minute window, and everything else, including a 401 from hyle (a wrong key or credential, which a visitor must not learn), is a 502. The kill switch is `HYLE_ENGAGE_ENABLED` (and `HYLE_CONTENT_ENABLED`): unset, empty, `1` or `true` leave the route on, and ANY other non-empty value (`0`, `false`, `off`, `no`, a typo) answers 404 everywhere; a missing or malformed configuration also answers 404 and never throws at build time. Your proxy or middleware matcher must let `/api/hyle/engage` through, and the route sits under `/api/hyle/*`, which hyle's Reserved paths already cover (see "Collision checker": `--print-reserved` and `--sync` always list it).
|
|
293
|
+
|
|
294
|
+
The component (`Comments`, a client component with no dependency) renders the states of the design kit: signed out, composer, threads to depth 4 (no Reply at depth 4), likes with a pressed state and an optimistic count, a reader's own pending comment ("Awaiting approval", visible only to them), edited marks, tombstones for removed and deleted comments, empty, loading, load error with Try again, post error that keeps the text, rate limited (the box is disabled, the button is `aria-disabled` and stays focusable), banned, and Load more (20 threads at a time). A write that answers 404 is not taken for a ban: the listing and the session are reloaded and a plain error shows; only a second 404 for a still valid session shows the banned message. Comment bodies are the sanitized hast hyle renders; the client sanitizes again with a narrower allowlist (links, emphasis, code, quotes, lists) and builds React elements, never HTML strings. Ctrl or Cmd+Enter posts, Escape closes a reply and returns focus to its button. Styling uses the existing `--hyle-*` variables plus six optional ones: `--hyle-comments-indent`, `--hyle-comments-gap`, `--hyle-comments-avatar-size`, `--hyle-comments-rule`, `--hyle-comments-held` and `--hyle-comments-like-on`. Strings are in en, fr and es (fr and es are unreviewed drafts).
|
|
295
|
+
|
|
296
|
+
The listing is viewer-aware (hyle cp1 spec section 3.11): for a signed-in reader the route sends a separate read assertion (`scope: "read"`, 30 s, not single use) with the `GET`, and hyle adds the reader's own state, so a reload restores their pending comment (`mine_held`), their pressed likes (`liked_by_me`) and Edit (only while `can_edit_until` is in the future; Delete stays available on the reader's own comments, as hyle allows it at any time). Edit after a reload starts from Markdown rebuilt from the rendered comment (hyle lists rendered comments, not their source), which can differ from the original in whitespace and escaping. Viewer reads are never shared between readers; a 401 on the read assertion is re-signed once and retried. If the viewer read cannot be served for the reader's own sake (a 401 after one re-sign, which means a wrong or rotated key; a 404, which means no key is registered at hyle yet; or a 429 that hyle marks `Hyle-Throttle: viewer`, the reader's own view bucket) the route answers with the public listing, so a signed-in reader never loses the section. Any other 429, the site-wide read bucket, is passed on with its `Retry-After` and not retried. A reader hyle has never seen, a banned reader and an anonymous visitor all get the public listing (no viewer members). Tombstones say whether a moderator removed the comment or its author deleted it. Known limits: there is no cursor, so a page holds at most 500 comments (and at most 100 000 characters of comment source are rendered per response); an edit can put a visible comment back in the moderation queue, in which case it moves to the reader's pending list.
|
|
297
|
+
|
|
298
|
+
## Embeds
|
|
299
|
+
|
|
300
|
+
Show hyle content inside a page you own, such as a "latest notes" strip on a home page or one article on a product page, without mounting the whole site. They are async server components and take the same `options` object as `hylePage` (`baseUrl`, `token`, `workspaceId`, `basePath`, `localePrefix`, `components`, `slots`, `onError`, or a `cachedResolver`).
|
|
301
|
+
|
|
302
|
+
```tsx
|
|
303
|
+
import { Suspense } from "react";
|
|
304
|
+
import { HyleArticle, HyleComments, HyleCommentsFallback, HyleList } from "@tdacorp/hyle-sdk/next";
|
|
305
|
+
|
|
306
|
+
// The 3 newest articles as cards, linking to the mount.
|
|
307
|
+
<HyleList options={options} limit={3} layout="grid" title="Latest notes" headingLevel={2} moreHref="/learn" />
|
|
308
|
+
|
|
309
|
+
// One article in place (path = the article's canonical_path, with the workspace prefix and no locale prefix).
|
|
310
|
+
<HyleArticle options={options} path="/learn/computing-reading-time" headingLevel={2} />
|
|
311
|
+
|
|
312
|
+
// Crawlable comments, streamed. The component awaits its fetch, so Suspense is how a page keeps streaming.
|
|
313
|
+
<Suspense fallback={<HyleCommentsFallback />}>
|
|
314
|
+
<HyleComments options={{ baseUrl: process.env.HYLE_TARGET_BASE_URL!, token: process.env.HYLE_TARGET_TOKEN! }} path="/learn/computing-reading-time" />
|
|
315
|
+
</Suspense>
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
- `HyleList`: `section` (a slug other than the default `posts`, resolved under `basePath`), `limit` (default 5, at most 100), `layout` (`"list"` or `"grid"`, default list), `title`, `headingLevel` (2, 3 or 4, default 2), `moreHref` (a "View all" link to a URL you choose, usually the mount) and `locale` (needed when `options.locale` is a function of route params, which a component cannot evaluate). It is a flat list, newest first, with no month groups and no pagination. The slots `list.item` and `list.empty` of `options.slots` apply.
|
|
319
|
+
- `HyleArticle`: `path`, `headingLevel` (default 2), `locale`. Title, date, description, the body, and a visible "Read at source" link. No table of contents, pager, languages bar, comments or JSON-LD. A path that is not an article (a redirect included) renders nothing.
|
|
320
|
+
- `HyleComments`: `options: { baseUrl, token, locale? }`, `path` (the article's canonical path), `revalidate` (seconds, default 60) and `interactive`. The listing is public and cached for `revalidate` seconds, not purged by a webhook. It renders the thread as server HTML (`ol > li > article`, names, dates, sanitized bodies, links `rel="nofollow ugc"`, removed comments as tombstones) and nothing at all when there are no comments or hyle answers 404 (engagement off, unknown article) or fails. With `interactive` (`true`, or `{ endpoint?, signInHref? }`) the `Comments` island is rendered INSTEAD, seeded from the same listing: the thread is still in the server HTML, there is no skeleton flash, readers can comment and like (it needs `createEngagementRoute`, as in "Comments and likes"), and it refetches silently on mount. The listing is serialized once into the page for the island (up to 500 comments), so leave `interactive` off where you only need to show comments.
|
|
321
|
+
|
|
322
|
+
SEO rules the embeds follow, and one you must:
|
|
323
|
+
|
|
324
|
+
- Links back: every item and the "Read at source" link is a plain `<a href>` to the canonical page on the mount, through your `localePrefix`. `HyleList` shows links and snippets only.
|
|
325
|
+
- Nothing in the document head: no `<title>`, `<link>`, `<meta>` or JSON-LD. Your page keeps its own metadata.
|
|
326
|
+
- **Canonical:** a page that embeds a full article with `HyleArticle` must set its own canonical URL to the article's URL on the mount (for example `alternates.canonical` in `generateMetadata`), or the two pages compete as duplicates. A list or a comments embed needs nothing. The embeds build no absolute URLs; those belong to the mount (see its documentation).
|
|
327
|
+
- Headings: the default level is 2, and the article body's headings are h2 and below (a body `h1` is demoted), so under your page's `h1` and a section heading of your own, set `headingLevel` to 3.
|
|
328
|
+
- Failure: an embed never calls `notFound()`, never redirects and never throws on a hyle outage. A missing page, a request hyle rejects and an empty section render nothing (or the `list.empty` slot). Any other failure is logged by name and renders `onError(error)` if you gave one, else nothing. A missing `workspaceId`, a bad `baseUrl` or an empty `token` is a configuration error and throws.
|
|
329
|
+
- The token is used only in the server-side request. `HyleComments` sends the target credential and nothing else (no reader assertion, no cookie, no header of the visitor), so every visitor shares one cached listing. The `Comments` island receives the listing, the path, your own `/api/hyle/engage` route and the chrome strings: never the token or hyle's URL.
|
|
330
|
+
|
|
331
|
+
Styling: import `@tdacorp/hyle-sdk/styles.css`. An embed is a `.hyle.hyle-embed` block with no page padding or maximum width, so the host's layout sets its width; `data-layout="grid"` lays the items out as cards (260px minimum columns). The pure markup is also exported as `HyleListView` and `HyleArticleView` from `@tdacorp/hyle-sdk/react` for hosts that fetch for themselves.
|
|
332
|
+
|
|
237
333
|
## Mermaid diagrams
|
|
238
334
|
|
|
239
335
|
Zero setup. A Mermaid fence arrives from hyle as a sandboxed `<iframe srcdoc>` that loads a script from cdnjs, and a `srcdoc` frame inherits the host page's CSP, so a host with `script-src 'self'` would show a blank box. The SDK therefore reads the diagram text out of that document (only after it matched hyle's exact template) and renders it in your page with the Mermaid library it bundles as a dependency (`mermaid` `~11.9.0`, MIT). No cdnjs, no extra package, no config.
|
|
@@ -302,12 +398,25 @@ Chrome strings exist for en, fr and es (fr and es are unreviewed drafts). The pa
|
|
|
302
398
|
- The `hast` tree is rendered through an allowlist (`sanitizeHast`) even though hyle sanitizes server-side: only known tags and properties with accepted value shapes survive; no `on*` attributes, `style` only inside KaTeX output and only for the properties KaTeX emits with small values (no `position:absolute`, `z-index`, `left` or large sizes), ids and in-page fragments scoped with the server's `user-content-` prefix (so heading ids, footnote links and TOC links still resolve), `href` and `src` limited to site-relative paths and `http(s)` (and `mailto` for links), unknown tags are unwrapped, `script` and `style` are dropped, and an `iframe` is kept only with `sandbox="allow-scripts"` and a `srcdoc` that is exactly the document hyle's renderer builds for a Mermaid fence (pinned script URL, at most 64 KiB); the SDK adds `referrerpolicy="no-referrer"` and a `csp` that allows only that script (checked in headless Chromium: the diagram still renders). A tree over 20,000 nodes or 512 KiB of text fails closed with `HastLimitError` and a safe notice. `dangerouslySetInnerHTML` is used in exactly three places: the Mermaid SVG sink (below), the same SVG with rewritten ids in the diagram viewer's stage (below), and `TrustedServerHtml`, the escape hatch for `content.format === "html"`: it renders HTML as is, so pass it only HTML that came straight from hyle's resolve endpoint, never user input.
|
|
303
399
|
- Mermaid renders into your page, so: the source comes only from hyle content, passes the exact-template check and a 20,000 character cap, and is rendered with `securityLevel: "strict"` (Mermaid's own DOMPurify pass, no raw HTML labels) and `maxTextSize` set to the cap. The SDK strips every `%%{ ... }%%` directive (multi-line, unterminated and `init`, `initialize`, `config`, `wrap` forms) and a leading YAML frontmatter block from the source before rendering, and keeps plain `%% comment` lines. Reason: Mermaid's `themeCSS` (set by a directive or by frontmatter `config:`) is injected into the page as CSS and its sanitizer only checks brace balance, so a diagram could make the page fetch a URL or overlay the host UI; verified against Mermaid 11.9.0 with a loopback canary server, which received requests when the stripping was disabled and none with it. Consequence: authors cannot configure a diagram per diagram; a diagram that carries an init directive renders with the SDK's defaults. As a second guard `.hyle-mermaid-svg` uses `contain: paint` and the SVG is `position: static !important`, so diagram CSS cannot place anything over the host page. Flowchart `style` and `classDef` lines cannot carry `url(...)` (they fail to parse). What remains: Mermaid keeps an `<img>` inside a label (event handlers are stripped), so an author can make the page request an image, and your CSP `img-src` governs that exactly as for Markdown images (the e2e proves a strict `img-src 'self' data:` stops it); a `click A "https://..."` line makes a clickable link, a phishing-link capability inside author-controlled content, so treat hyle authors as trusted to link. Nothing is executed: the SDK ignores Mermaid's `bindFunctions`, and the hostile `click ... call`, `<img onerror>` and `securityLevel: "loose"` payloads did nothing in the browser check. The host CSP needs `style-src 'unsafe-inline'`.
|
|
304
400
|
- The diagram viewer adds no network request, no `eval`, no storage and no new way to write HTML: its stage receives the very string the inline diagram holds (Mermaid's strict-mode DOMPurify output) after one rewrite of the SDK-generated render id (`hyle-mermaid-N`) to another SDK-generated token (`hyle-viewer-N`), applied only inside tags and `<style>` bodies and only for `[\w-]+` tokens, so it cannot add a quote, a tag or a script; the node and edge decoration only sets classes, `tabindex`, `role` and `aria-*` on elements that already exist. Export builds `blob:` and `data:` URLs from that same string on click, and the clipboard is only touched inside the click that asked for it. A unit test pins these properties by reading the viewer's source (no `fetch`, `eval`, `innerHTML =`, storage or `document.write`, exactly one `dangerouslySetInnerHTML`).
|
|
401
|
+
- The comments client talks only to the host's own `createEngagementRoute` (same origin; no credential, no hyle URL, no storage, no cookie access in the browser bundle, which a test pins). The route is an allowlist, not a proxy, and writes need same-origin plus a custom header (see "Comments and likes"). The private signing key stays on the server and is never logged; a malformed key is refused with a message that does not contain it.
|
|
305
402
|
- Webhooks are verified with HMAC-SHA256 over the raw body (read with a running 64 KiB cap), a 300 s timestamp tolerance and constant-time comparison, with dual-secret rotation (empty secrets are never candidates), a payload shape check (400, not 500), tag validation, and delivery-id dedupe that records an id only after every purge succeeded, so a failed delivery can be retried.
|
|
306
403
|
|
|
307
404
|
## Not included
|
|
308
405
|
|
|
309
406
|
Docs versions, reading time, "closest matches" on the 404 page and a copy-code button: hyle does not provide that data or the page would need client JavaScript. Image URLs in content such as `/assets/<id>` are no longer passed through unchanged: see "Media".
|
|
310
407
|
|
|
408
|
+
Social card images (`og:image`): the resolve contract carries no image data, so `hyleMetadata` emits none. Add your own by wrapping the returned function:
|
|
409
|
+
|
|
410
|
+
```ts
|
|
411
|
+
import { hyleMetadata, type PageProps } from "@tdacorp/hyle-sdk/next";
|
|
412
|
+
|
|
413
|
+
const base = hyleMetadata(options);
|
|
414
|
+
export async function generateMetadata(props: PageProps) {
|
|
415
|
+
const meta = await base(props);
|
|
416
|
+
return { ...meta, openGraph: { ...meta.openGraph, images: ["/og.png"] } };
|
|
417
|
+
}
|
|
418
|
+
```
|
|
419
|
+
|
|
311
420
|
## Contract
|
|
312
421
|
|
|
313
422
|
Types in `src/types.ts` mirror `packages/cp1-read/src/resolve.ts`. `src/__tests__/contract.test.ts` pins them against fixture JSON for every result kind, so a server-side shape change fails a test here.
|
package/dist/check-routes-bin.js
CHANGED
|
@@ -101,7 +101,11 @@ function createHyleClient(options) {
|
|
|
101
101
|
if (opts.limit !== void 0) query.set("limit", String(opts.limit));
|
|
102
102
|
const reply = await get("/cp1/read/resolve", query, opts.init);
|
|
103
103
|
const data = reply.parsed?.data;
|
|
104
|
-
if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind))
|
|
104
|
+
if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind)) {
|
|
105
|
+
const resolved = data;
|
|
106
|
+
if (resolved.kind === "article" && resolved.content.format === "html" && opts.format !== "html") throw failure(reply);
|
|
107
|
+
return resolved;
|
|
108
|
+
}
|
|
105
109
|
throw failure(reply);
|
|
106
110
|
}
|
|
107
111
|
async function mounts(opts = {}) {
|
|
@@ -95,7 +95,11 @@ function createHyleClient(options) {
|
|
|
95
95
|
if (opts.limit !== void 0) query.set("limit", String(opts.limit));
|
|
96
96
|
const reply = await get("/cp1/read/resolve", query, opts.init);
|
|
97
97
|
const data = reply.parsed?.data;
|
|
98
|
-
if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind))
|
|
98
|
+
if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind)) {
|
|
99
|
+
const resolved = data;
|
|
100
|
+
if (resolved.kind === "article" && resolved.content.format === "html" && opts.format !== "html") throw failure(reply);
|
|
101
|
+
return resolved;
|
|
102
|
+
}
|
|
99
103
|
throw failure(reply);
|
|
100
104
|
}
|
|
101
105
|
async function mounts(opts = {}) {
|
|
@@ -516,8 +520,42 @@ var printable = (text) => {
|
|
|
516
520
|
return clean.length > MAX_PRINTED ? `${clean.slice(0, MAX_PRINTED)}...` : clean;
|
|
517
521
|
};
|
|
518
522
|
|
|
523
|
+
// src/engage-keys.ts
|
|
524
|
+
import { createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID, sign } from "crypto";
|
|
525
|
+
var KEY_B64URL = /^[A-Za-z0-9_-]{43}$/;
|
|
526
|
+
var PKCS8_ED25519 = Buffer.from("302e020100300506032b657004220420", "hex");
|
|
527
|
+
function generateEngagementKeyPair() {
|
|
528
|
+
const jwk = generateKeyPairSync("ed25519").privateKey.export({ format: "jwk" });
|
|
529
|
+
return { publicKey: String(jwk.x), privateKey: String(jwk.d) };
|
|
530
|
+
}
|
|
531
|
+
function engagementSigningKey(seed) {
|
|
532
|
+
const bytes = KEY_B64URL.test(seed) ? Buffer.from(seed, "base64url") : void 0;
|
|
533
|
+
if (bytes?.length !== 32) throw new TypeError("the engagement signing key must be a 32-byte Ed25519 seed, base64url (43 characters)");
|
|
534
|
+
return createPrivateKey({ key: Buffer.concat([PKCS8_ED25519, bytes]), format: "der", type: "pkcs8" });
|
|
535
|
+
}
|
|
536
|
+
function engagementPublicKey(seed) {
|
|
537
|
+
return String(createPublicKey(engagementSigningKey(seed)).export({ format: "jwk" }).x);
|
|
538
|
+
}
|
|
539
|
+
var ASSERTION_MAX_BYTES = 2048;
|
|
540
|
+
var ASSERTION_TTL_SECONDS = 30;
|
|
541
|
+
var b64 = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
542
|
+
function signReaderAssertion(key, claims, nowSeconds = Math.floor(Date.now() / 1e3), scope) {
|
|
543
|
+
const input = `${b64({ alg: "EdDSA", typ: "JWT" })}.${b64({ ...claims, ...scope ? { scope } : {}, aud: "hyle", iat: nowSeconds, exp: nowSeconds + ASSERTION_TTL_SECONDS, jti: randomUUID() })}`;
|
|
544
|
+
const token = `${input}.${sign(null, Buffer.from(input), key).toString("base64url")}`;
|
|
545
|
+
if (Buffer.byteLength(token) > ASSERTION_MAX_BYTES) throw new RangeError("the reader assertion would exceed 2 KiB");
|
|
546
|
+
return token;
|
|
547
|
+
}
|
|
548
|
+
var INVISIBLE = /[\u0000-\u001f\u007f-\u009f\p{Cf}\u115f\u1160\u17b4\u17b5\u3164\uffa0]/gu;
|
|
549
|
+
var DISPLAY_NAME_MAX = 80;
|
|
550
|
+
function cleanDisplayName(raw) {
|
|
551
|
+
const cleaned = [...raw.replace(/[\t\n\r\f\v]/gu, " ").replace(INVISIBLE, "").replace(/\s+/gu, " ").trim()].slice(0, DISPLAY_NAME_MAX).join("").trim();
|
|
552
|
+
return cleaned.length > 0 ? cleaned : void 0;
|
|
553
|
+
}
|
|
554
|
+
|
|
519
555
|
export {
|
|
520
556
|
Cp1ClientError,
|
|
557
|
+
readCapped,
|
|
558
|
+
checkBaseUrl,
|
|
521
559
|
createHyleClient,
|
|
522
560
|
syncHostReserved,
|
|
523
561
|
DeliveryDedupe,
|
|
@@ -533,5 +571,10 @@ export {
|
|
|
533
571
|
checkRoutes,
|
|
534
572
|
SDK_OWN_RESERVED,
|
|
535
573
|
reservedFor,
|
|
536
|
-
formatReport
|
|
574
|
+
formatReport,
|
|
575
|
+
generateEngagementKeyPair,
|
|
576
|
+
engagementSigningKey,
|
|
577
|
+
engagementPublicKey,
|
|
578
|
+
signReaderAssertion,
|
|
579
|
+
cleanDisplayName
|
|
537
580
|
};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// src/react/mermaid-config.ts
|
|
2
|
+
var MAX_MERMAID_SOURCE = 2e4;
|
|
3
|
+
function luminance(css) {
|
|
4
|
+
const m = /^(rgba?)\(([^)]*)\)$|^color\(srgb ([^)]*)\)$/.exec(css.trim());
|
|
5
|
+
if (!m) return void 0;
|
|
6
|
+
const parts = (m[2] ?? m[3] ?? "").split(/[\s,/]+/).filter(Boolean).map(Number);
|
|
7
|
+
const [r, g, b] = parts.map((v) => m[3] ? v : v / 255);
|
|
8
|
+
const alpha = parts[3] ?? 1;
|
|
9
|
+
if (r === void 0 || g === void 0 || b === void 0 || [r, g, b, alpha].some(Number.isNaN) || alpha < 0.5) return void 0;
|
|
10
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
|
11
|
+
}
|
|
12
|
+
function pickMermaidTheme(background, prefersDark) {
|
|
13
|
+
const l = luminance(background);
|
|
14
|
+
return (l === void 0 ? prefersDark : l < 0.5) ? "dark" : "default";
|
|
15
|
+
}
|
|
16
|
+
var RENDER_TIMEOUT_MS = 1e4;
|
|
17
|
+
var NEAR_VIEWPORT_MARGIN = "200px";
|
|
18
|
+
var FRONTMATTER = /^\s*-{3}[^\S\n]*\n[\s\S]*?\n-{3}[^\S\n]*(?:\n|$)/;
|
|
19
|
+
var DIRECTIVE = /%%\{(?:(?!\}%%)[\s\S])*(?:\}%%)?/g;
|
|
20
|
+
function stripMermaidConfig(source) {
|
|
21
|
+
let text = source.replace(/\r\n?/g, "\n");
|
|
22
|
+
for (let previous = ""; previous !== text; ) {
|
|
23
|
+
previous = text;
|
|
24
|
+
text = text.replace(FRONTMATTER, "").replace(DIRECTIVE, "");
|
|
25
|
+
}
|
|
26
|
+
return text;
|
|
27
|
+
}
|
|
28
|
+
var counter = 0;
|
|
29
|
+
var nextMermaidId = () => `hyle-mermaid-${++counter}`;
|
|
30
|
+
function withTimeout(promise, ms) {
|
|
31
|
+
let timer;
|
|
32
|
+
const timeout = new Promise((_, reject) => {
|
|
33
|
+
timer = setTimeout(() => reject(new Error("timeout")), ms);
|
|
34
|
+
});
|
|
35
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
|
36
|
+
}
|
|
37
|
+
function whenNearViewport(el, onNear, Observer = globalThis.IntersectionObserver) {
|
|
38
|
+
if (!Observer) {
|
|
39
|
+
onNear();
|
|
40
|
+
return () => {
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const observer = new Observer((entries) => {
|
|
44
|
+
if (entries.some((e) => e.isIntersecting)) {
|
|
45
|
+
observer.disconnect();
|
|
46
|
+
onNear();
|
|
47
|
+
}
|
|
48
|
+
}, { rootMargin: NEAR_VIEWPORT_MARGIN });
|
|
49
|
+
observer.observe(el);
|
|
50
|
+
return () => observer.disconnect();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export {
|
|
54
|
+
MAX_MERMAID_SOURCE,
|
|
55
|
+
pickMermaidTheme,
|
|
56
|
+
RENDER_TIMEOUT_MS,
|
|
57
|
+
stripMermaidConfig,
|
|
58
|
+
nextMermaidId,
|
|
59
|
+
withTimeout,
|
|
60
|
+
whenNearViewport
|
|
61
|
+
};
|