@forumulate/reader
v0.2.0
Published
Sign your app's users in to your Forumulate docs, forum and blog: reader hand-off, sign-out cookies and error mapping.
Maintainers
Readme
@forumulate/reader
Sign the users of your app in to your Forumulate docs, forum and blog, using
the external_jwt reader sign-in method. No runtime dependencies (Node ≥ 18,
node:crypto only).
If your app already signs users in with an OpenID Connect provider — Atlas, Auth0, Clerk, Okta, Cognito, Keycloak, Entra, Firebase, Supabase, WorkOS — you may not need this package at all: configure that provider as a reader sign-in method and hand us its own token. See Reader sign-in with your app.
npm install @forumulate/readerHand-off
import { ReaderHandoff } from '@forumulate/reader';
const handoff = new ReaderHandoff({
orgId: process.env.FORUMULATE_ORG_ID!,
// spaceId is optional: omit it and the helper reads every space's addresses (org-wide)
// and `returnTo` picks the one it is served from. Name one to pin the helper to it.
spaceId: process.env.FORUMULATE_SPACE_ID,
sharedSecret: process.env.FORUMULATE_READER_SECRET!, // the external_jwt sharedSecret
audience: process.env.FORUMULATE_READER_CLIENT_ID, // only if the provider has a clientId
// Either copy `readerEndpoints` from GET /orgs/{org}/spaces/{space}/reader-auth …
// readerEndpoints: [...],
// … or let the helper read (and cache for 10 minutes) them with an admin token:
adminToken: process.env.FORUMULATE_ADMIN_TOKEN,
});Express
app.get('/docs-sign-in', requireLogin, async (req, res) => {
const url = await handoff.redeemUrl({
user: { sub: req.user.id, email: req.user.email, name: req.user.name },
returnTo: String(req.query.returnTo ?? 'https://example.com/docs'),
});
res.redirect(url);
});Next.js route handler
export async function GET(req: Request) {
const user = await currentUser();
const returnTo = new URL(req.url).searchParams.get('returnTo') ?? 'https://example.com/docs';
return Response.redirect(await handoff.redeemUrl({ user, returnTo }), 302);
}Rules the helper keeps for you:
- A fresh token per call.
iatis now,expis 120 s later (never more than 300 s: the server refuses aniatolder than that). Never cache one. - HS256, keyed with the UTF-8 bytes of the secret — not a base64 decode.
- The reader's own host. The cookies are host-only, so the token is
redeemed at the address the page is served from (
<mount>/_api/…on your domain), picked fromreaderEndpointsbyreturnTo. returnTois checked first: absolutehttps, no credentials, at most 2048 characters, and under one of the space's addresses. A bad value throwsReturnToErrorinstead of silently landing the reader on the space root.subis the key, not the email. A user who changes address comes back as the same reader.
redeemBody() answers {url, body} for a server-side POST instead of a link.
Sign-out, both ways
- From your app on the same host as the docs: send
signOutCookies()asSet-Cookieheaders. - From anywhere else:
POSTtoawait handoff.signOutUrl(returnTo); it revokes the session and clears the cookies on the reader's host. - From Forumulate to you: set
signOutUrlon the reader-auth registry and we send the reader there after ours.
Reader cookies (all host-only, Path=/; list them in your CMP as necessary):
| Cookie | What |
| --- | --- |
| forumulate_session | The reader's session (httpOnly) |
| fm_signed_in | A "signed in" hint for the page |
| cflx_vis_org_<orgId> | The org-wide reader pass |
| cflx_vis_<spaceId> | The per-space reader pass |
Errors
import { mapError } from '@forumulate/reader';
const res = await fetch(url, { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' } });
if (!res.ok) {
const { reason, hint, retry } = mapError(await res.json());
// retry → mint a fresh token and try once more
}| error.reason | Retry? | Meaning |
| --- | --- | --- |
| malformed | no | Not a JWT |
| bad_signature | no | Wrong secret (UTF-8 bytes) or wrong key |
| bad_algorithm | no | HS256 only with a shared secret; asymmetric only for IdP tokens |
| unknown_key | no | No JWKS key matches the kid |
| jwks_unavailable / jwks_unreachable | yes | We could not fetch the keys |
| discovery_failed | yes | The issuer's discovery document failed or names another issuer |
| bad_issuer / unknown_issuer | no | iss is not the configured issuer |
| bad_audience / wrong_audience | no | aud is not the configured audience |
| expired | yes | Mint a fresh token |
| iat_too_old | yes | Minted more than 300 s ago |
| not_yet_valid / iat_in_future | no | Your server clock is ahead |
| lifetime_too_long | no | exp is further out than the provider allows |
| wrong_token_use | no | Wrong kind of IdP token |
| missing_claim / invalid_claim | no | sub, exp, iat |
| missing_email | no | An email claim is needed |
| not_configured | no | The space offers no token sign-in |
Test vectors
test/vectors.json holds inputs and the exact header/payload a conforming
implementation produces (key order included). A port reproduces the header
segment, the payload JSON, and an HMAC-SHA256 signature that verifies with the
UTF-8 bytes of the secret.
Python and Go
Ports with the same API and behaviour, standard library only. Each carries a
copy of test/vectors.json and a test that it is still identical.
| Language | Install | Source |
| --- | --- | --- |
| Python 3.8+ | pip install git+https://github.com/forumulate/forumulate-reader-python (import forumulate_reader) | integrations/reader-python |
| Go 1.21+ | go get github.com/forumulate/forumulate-reader-go | integrations/reader-go |
from forumulate_reader import ReaderHandoff
handoff = ReaderHandoff(org_id, shared_secret, space_id=space_id, admin_token=admin_token)
url = handoff.redeem_url({"sub": user.id, "email": user.email}, "https://example.com/docs")handoff, _ := reader.New(reader.Options{OrgID: orgID, SpaceID: spaceID, SharedSecret: secret, AdminToken: token})
url, err := handoff.RedeemURL(ctx, reader.RedeemInput{
User: reader.User{Sub: u.ID, Email: u.Email},
ReturnTo: "https://example.com/docs",
})A change to this package's behaviour changes all three. Edit the vectors here,
copy them to integrations/reader-python/tests/ and
integrations/reader-go/testdata/, and make both ports pass.
