FastComments.com

Dodajanje živih komentarjev v aplikacije Val Town

Val Town izvaja TypeScript na Deno, zato je val pravi strežnik. To ga naredi primerno za FastComments: gradnik je oznaka script na strani, in vse, kar potrebuje skrivnost, kot je varna SSO ali preverjanje webhooka, lahko teče na strežniški strani v istem valu.

Ta vodnik pokriva dodajanje gradnika za komentarje v HTTP val, prikaz števila komentarjev na indeksni strani, prijavo uporabnikov s računom Val Town, ki ga že imajo, in prejemanje webhookov za komentarje.

Za preizkus ne potrebujete računa. Primeri uporabljajo tenantId: "demo", skupni sandbox, in korak 2 opisuje preklop na vašega.

Število komentarjev na indeksni strani Internal Link

On an index page, don't render one comment-count widget per row. That is one request per post. Use the bulk count, which takes a single request for the whole page.

Mark each row with the urlId its thread uses, then load the bulk widget once:

Masovni števci komentarjev na indeksni strani
Copy CopyRun External Link
1
2<ul>
3 {posts.map((post) => (
4 <li>
5 <a href={post.slug}>{post.title}</a>{" "}
6 <span class="fast-comments-count" data-fast-comments-url-id={post.slug}></span>
7 </li>
8 ))}
9</ul>
10
11<script
12 dangerouslySetInnerHTML={{
13 __html: `window.FastCommentsBulkCountConfig = ${
14 JSON.stringify({ tenantId: TENANT_ID })
15 };`,
16 }}
17/>
18<script src="https://cdn.fastcomments.com/js/embed-widget-comment-count-bulk.min.js"></script>
19

The script finds every .fast-comments-count element on the page and fills in its count.

data-fast-comments-url-id has to match the urlId that post's comment widget uses. If the widget uses the slug, the marker uses the slug. A mismatch shows zero on a thread that has comments.

The script polls for window.FastCommentsBulkCountConfig, so it does not matter whether you set the config before or after the script tag.

Zavaruj SSO z std/oauth Internal Link

If your val already knows who the visitor is, Secure SSO hands that identity to the widget so they never see a second login. There are no endpoints to build and nothing to call at runtime: you compute three values server-side and pass them in the widget config.

Val Town ships zero-config login with std/oauth, so the visitor can sign in with the Val Town account they already have. Swap that for whatever your app uses; the FastComments half does not change.

Build the payload on the server

The API secret signs the payload and must never reach browser code. Install the SDK from npm, which works on Val Town's Deno runtime as-is:

sso.ts
Copy CopyRun External Link
1
2import { SecureSSOPayloadBuilder } from "npm:fastcomments-sdk/server";
3
4export function buildSSOPayload(user) {
5 // id must be stable for the same person, or they get a new comment identity on every login.
6 const id = `vt-${user.id}`;
7
8 return new SecureSSOPayloadBuilder(Deno.env.get("FASTCOMMENTS_API_SECRET"), {
9 id,
10 // email is required and must be unique.
11 email: user.email ?? `${id}@users.noreply.val.town`,
12 // username is required and cannot be an email.
13 username: user.username ?? id,
14 displayName: user.username ?? undefined,
15 avatar: user.links.profileImageUrl ?? undefined,
16 }).getPayload();
17}
18

getPayload() returns { userDataJSONBase64, verificationHash, timestamp }. Those three values are all that reach the browser. The secret signs them and is then dropped, so nothing in the page lets a reader forge a different user.

Pass it to the widget

Konfiguracija gradnika z SSO
Copy CopyRun External Link
1
2import { getOAuthUserData, oauthMiddleware } from "https://esm.town/v/std/oauth/middleware.ts";
3
4app.get("/", async (c) => {
5 const session = await getOAuthUserData(c.req.raw);
6 const user = session?.user;
7
8 const config = {
9 tenantId: TENANT_ID,
10 urlId: "my-thread",
11 ...(user
12 ? { sso: { ...buildSSOPayload(user), logoutURL: "/logout" } }
13 : { sso: { loginURL: "/auth/login" } }),
14 };
15
16 // ...render the widget with this config
17});
18
19export default oauthMiddleware(app.fetch);
20

oauthMiddleware adds GET /auth/login, GET /auth/callback and POST /auth/logout for you. Note that logout is a POST, while the widget navigates to logoutURL with a GET, so point logoutURL at a small route of your own that submits the POST.

When the visitor is logged out, pass sso with only a loginURL. The widget then shows a login prompt instead of an anonymous comment box.

Things that go wrong

timestamp is epoch milliseconds, must not be in the future, and must not be more than two days old. Generate it on the server in the same request that computes the hash. Generating it in the browser is the classic failure: the value differs from the one that was hashed and every comment is rejected.

Never set isAdmin or isModerator from the identity provider. Signing in with a Val Town account says nothing about who should moderate your site.

See the SSO guide for the full field list, group-gated threads, and badges.

Prejemanje webhookov Internal Link

A val je naravni prejemnik webhookov: ima stabilen URL, lahko preveri podpis in ima vgrajeno SQLite ter shranjevanje blobov.

FastComments podpiše ${timestamp}.${body} z API skrivnostjo vašega računa in pošlje dva glavi:

Glave webhooka
Copy CopyRun External Link
1
2X-FastComments-Timestamp: 1789004710 unix seconds, not milliseconds
3X-FastComments-Signature: sha256=<hex>
4

Metoda prenaša dogodek: PUT za ustvarjen ali posodobljen komentar, DELETE za izbrisan komentar.

Preverjanje dostave
Copy CopyRun External Link
1
2import { createHmac, timingSafeEqual } from "node:crypto";
3
4async function receive(c) {
5 // Natančni bajti, ki so prispeli. NE uporabljajte c.req.json() in ponovno serijalizirajte.
6 const rawBody = await c.req.raw.text();
7 const timestamp = c.req.raw.headers.get("X-FastComments-Timestamp");
8 const signature = c.req.raw.headers.get("X-FastComments-Signature");
9
10 if (!timestamp || !signature) return new Response("Missing headers", { status: 400 });
11
12 // Zavrnite zastarele dostave, da zajetega zahtevka ne morete kasneje ponovno predvajati.
13 if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300) {
14 return new Response("Timestamp outside window", { status: 400 });
15 }
16
17 const expected = "sha256=" + createHmac("sha256", Deno.env.get("FASTCOMMENTS_API_SECRET"))
18 .update(`${timestamp}.${rawBody}`)
19 .digest("hex");
20
21 const a = new TextEncoder().encode(signature);
22 const b = new TextEncoder().encode(expected);
23 if (a.length !== b.length || !timingSafeEqual(a, b)) {
24 return new Response("Signature mismatch", { status: 401 });
25 }
26
27 // ...obdelajte JSON.parse(rawBody)
28 return Response.json({ received: true });
29}
30
31app.put("/", receive);
32app.delete("/", receive);
33

Dve stvari, ki povzročata težave

Preverite surove bajte. Parsiranje JSON-a in ponovno serijaliziranje spremeni vrstni red ključev in presledke, zato se hash razlikuje in vsaka dostava spodleti brez očitnega vzroka. To je običajen razlog, da prejemnik webhooka "preprosto ne deluje".

Primerjajte v konstantnem času. Preprosto === na podpisu razkrije, koliko bajtov se ujema, kar je dovolj za podvajanje enega bajta naenkrat.

Obdelava dogodkov

Odgovorite hitro. FastComments ponavlja poizvedbe pri ne-2xx odgovoru, in končna točka, ki stalno odpoveduje, je na koncu samodejno onemogočena, zato opravite dejansko delo po odgovoru, namesto v isti zahtevi.

Poskrbite, da bo delo idempotentno glede na ID komentarja. Ponovna poizvedba je ponovno podpisana s svežim časovnim žigom, in isti ID komentarja ponovno prispe pri urejanju in brisanju, zato ni nič stabilnega, na čemer bi se lahko deduplikiralo.

Primer Vals Internal Link

Štiri javne vals, ki jih lahko remiksate, vsaka pokriva en del tega vodnika.

Blog s komentarji (živo) je Markdown blog z nitjo pod vsakim objavom in skupnimi števci komentarjev na indeksu. Deluje takoj, ko ga remiksate, in ena spremenljivka okolja ga usmeri na vaš račun.

SSO demo (živo) prijavi obiskovalca s svojim računom Val Town in to identiteto predaja gradniku, tako da ni drugega prijavljanja.

Prejemnik Webhook (živo) preveri HMAC podpis pri vsaki dostavi in shranjuje dogodke v SQLite. Ima gumb, ki podpiše testni paket podatkov in ga pošlje samemu sebi, tako da lahko opazujete uspešno preverjanje, preden konfigurirate pravi webhook.

Spretnosti agenta (živo) je knjižnica spretnosti agenta FastComments, ki pokrivajo gradnik, SSO, REST API, moderacijo in migracijo iz Disqus. Remiksajte jo in agent Val Town, Townie, samodejno prebere spretnosti iz skills/, tako da vaš agent ve, kako nastaviti komentarje, ne da bi morali lepljivo vstavljati dokumentacijo v klepet.

Enake spretnosti lahko namestite kjerkoli drugje z npx skills add fastcomments/skills.