hazo_invite
v1.3.0
Published
Invite-code and waitlist management for hazo_* workspace apps
Readme
hazo_invite
Invite-code and waitlist management for hazo_* workspace apps. Bearer and email-bound invite codes, single-use or multi-use, with expiry tracking and a waitlist fallback.
Status: v1.0.0 — ships shared types, the config loader,
deriveCodeStatus,generateInviteToken, cookie helpers for the dual-path redemption flow, the DDL for all 3 tables, the full code lifecycle + redemption + waitlist HTTP API (createInviteServer()), theInviteAdminPageadmin UI, theInviteCodePageturnkey landing page (4 states: valid/expired/exhausted/ not-found), and a full i18n layer (createPackageT('hazo_invite', ...)+InviteI18nProvider) covering every string in the admin UI and landing page. See "HTTP API" and "Client Entry" below for the full route/export list.
⚠️ Wiring requirement: both template-sending paths need a HazoConnectInstance, not a raw adapter
generateCode (email-bound codes), updateCodeLifecycle (reactivation
notify), and signupToWaitlist each render and send a transactional email —
hazo-invite-code, hazo-invite-reactivated, hazo-invite-waitlist-confirmation
respectively — via hazo_notify/template_manager's send_template_email(),
by template_name. (An earlier version of this package called
hazo_notify/dispatcher's dispatch() with recipient_emails instead —
that path never actually looks up or renders a template at all; it passes
{template_name, variables} straight through to the channel adapter with
rendered_bodies: {}, so the email that went out had no subject and no
body. Fixed by switching all 3 send sites to send_template_email().) That
send is fire-and-forget and swallows failures (logged via
logger?.warn, never thrown) — by design, so a flaky mail provider or a
missing template row can never fail code generation/redemption/signup itself.
The consequence: if the consumer's app never successfully seeds these 3
template rows into hazo_notify_templates (via hazo_notify/template_manager's
sync_system_templates(hazo_connect, hazo_invite_template_manifest), typically
called once at boot — see Kinstripe's own
src/lib/notify/sync-system-templates.ts convention, and this package's own
test-app/app/api/invite/[...path]/route.ts's ensureTemplatesSynced()
below), every one of these 3 emails will silently fail to send, with no
error surfaced anywhere the end user or the admin UI can see.
createInviteServer() logs a one-time boot warning when it can detect this
misconfiguration in advance (email sending enabled in config but no
notifyOptions passed, or notifyOptions passed with no logger configured
— falls back to console.warn in that case) — see src/server/factory.ts —
but it can't detect the specific mistake below, since that happens entirely
in the consumer's own wiring code.
The actual pitfall — and it's a wiring mistake, not an upstream bug: both
sync_system_templates() AND send_template_email() take a
HazoConnectInstance — a higher-level CRUD facade (query() / list() /
findById() / findBy() / insert() / updateById() / deleteById())
that hazo_notify/template_manager defines and expects the consumer to
implement over their own adapter. Most hazo_connect consumers instead have
a raw HazoConnectAdapter lying around (e.g. whatever
get_hazo_connect_instance() from hazo_auth/server-lib returns) — a
completely different, lower-level shape (query(builder, method?, body?),
rawQuery(), getConfig(), claimRows()). hazo_notify/template_manager/
types.ts's own JSDoc says explicitly that the two "cannot be substituted"
for each other. Passing the raw adapter straight into either call throws
immediately (.from is not a function or similar) — not because of a
hazo_connect/hazo_notify version mismatch, but because it's simply the
wrong shape for that call. This is why InviteNotifyOptions.getHazoConnect
(passed as notifyOptions.getHazoConnect) is a SEPARATE, required field from
the top-level InviteServerOptions.getHazoConnect — the top-level one
returns whatever raw adapter the CRUD code/waitlist services need, while
notifyOptions.getHazoConnect must resolve to a HazoConnectInstance. This
package deliberately does not try to wrap a raw adapter into a
HazoConnectInstance itself — that's the consumer's wiring responsibility,
same as sync_system_templates()'s identical requirement below.
Fix: wrap your raw adapter in a small HazoConnectInstance shim and pass
it for BOTH sync_system_templates() and notifyOptions.getHazoConnect.
Kinstripe already has a working, copy-pasteable example of exactly this at
src/lib/db/notify-adapter.ts (createNotifyAdapter()), written for its
PostgREST adapter. This package's own test-app/lib/notify_adapter.ts is a
second worked example — adapted from Kinstripe's version, but implemented
against the real hazo_connect QueryBuilder/createCrudService() instead
of hand-built PostgREST endpoint strings. It's verified working against this
test-app's SQLite adapter; see that file's serializeJsonFields doc comment
for a caveat that hasn't been verified against a real Postgres/PostgREST
adapter (JSON-stringifying a value before an insert/updateById may or may
not round-trip correctly into a JSONB column there — unconfirmed either way).
The bridging strategy itself (driving hazo_connect's own QueryBuilder /
createCrudService()) is also what hazo_notify uses internally for its own
inbox delivery-time template rendering (asTemplateManagerInstance in
hazo_notify/dist/lib/inbox/worker/render.js) — good independent
confirmation it's the shape hazo_notify itself expects a consumer adapter to
support. See test-app/app/api/invite/[...path]/route.ts's
ensureTemplatesSynced() (and its surrounding doc comments, including
test-app/instrumentation.ts's, for why the sync call lives there and not in
instrumentation.ts) for how it's wired in and called at boot.
Installation
npm install hazo_invitePeer Dependencies
Ensure your app has these installed (hazo_invite declares them as peers):
| Package | Version | Notes |
|---------|---------|-------|
| react | ^18.0.0 \|\| ^19.0.0 | |
| react-dom | ^18.0.0 \|\| ^19.0.0 | |
| next | ^14.0.0 \|\| ^16.0.0 | |
| hazo_core | ^2.5.0 | Error classes, correlation ID, logger factory |
| hazo_connect | ^4.3.3 | Database access |
| hazo_auth | ^10.24.0 | User auth |
| hazo_ui | ^6.16.0 | UI primitives (admin UI, landing page) |
| hazo_notify | ^6.7.0 | Invite / waitlist confirmation emails (required, not optional) |
| hazo_config | ^2.6.0 | INI config loader |
| lucide-react | ^0.553.0 | Icons (admin UI) |
| hazo_i18n | ^0.15.2 | Optional — translated strings; see "i18n" below |
Database setup
Run ddl/db_setup_postgres.sql (or ddl/db_setup_sqlite.sql for a local
SQLite dev DB) against your database. Both scripts are idempotent and are the
single source of truth for the v1.0.0 schema — no migrations/ directory.
Tables: hazo_invite_codes, hazo_invite_redemptions, hazo_invite_waitlist.
Config
Copy config/hazo_invite_config.ini.sample to config/hazo_invite_config.ini
(gitignored) and adjust. Override the file path with HAZO_INVITE_CONFIG_PATH.
Sections: [app], [gate], [rate_limit], [waitlist], [notify].
Usage so far
import {
getInviteConfig,
deriveCodeStatus,
generateInviteToken,
setInviteCodeCookie,
readInviteCodeCookie,
clearInviteCodeCookie,
} from 'hazo_invite';
const code = generateInviteToken(); // default length from config.codeLength
const status = deriveCodeStatus(
{ max_uses: 1, expires_at: null },
0, // redemptions so far
); // 'valid'deriveCodeStatus is pure (no DB call) — callers fetch the redemption count
themselves. generateInviteToken returns a URL-safe (base64url) token.
Cookie helpers use Next.js's cookies() (Route Handlers / Server Actions).
HTTP API
Mount createInviteServer() from a Next.js App Router catch-all route
(app/api/invite/[...path]/route.ts):
⚠️ Mount-path constraint:
server/router.ts'sextract_invite_pathmatches the literal substring'invite/'in the request URL's pathname — it is not a configurable prefix. Your catch-all route's path AND everyapiBaseprop you pass to this package's client components (InviteCodeRedeemer,InviteAdminPage,InviteCodePage, …) must both end in/invite— e.g. mount atapp/api/invite/[...path]/route.tsand passapiBase="/api/invite"(matching Kinstripe's planned mount point andtest-app's own route below). A mount point that doesn't end in/invite(e.g./api/beta-invite) never matches, and every route 404s.
import { createInviteServer, hazo_invite_template_manifest } from 'hazo_invite';
const server = createInviteServer({
getHazoConnect: () => getMyHazoConnectAdapter(),
appId: 'kinstripe',
adminScope: 'kinstripe:super_admin',
notifyOptions: {
from: '[email protected]',
fromName: 'Kinstripe',
// MUST resolve to a HazoConnectInstance, not the raw adapter above —
// see "Wiring requirement" above.
getHazoConnect: () => createNotifyAdapter(getMyHazoConnectAdapter()),
},
});
export const { GET, POST, PATCH, DELETE } = server.handlers;Sync hazo_invite_template_manifest at boot (alongside your other
SystemTemplateManifest[]s) so hazo-invite-code / hazo-invite-reactivated
exist for hazo_notify to render.
Routes (Task 2 — 5 of the 11 total planned for this package):
| Method | Path | Auth | Notes |
|---|---|---|---|
| POST | /codes | admin (adminScope) | { email?, max_uses?, expires_at?, metadata? }. Bearer when email omitted. Sends hazo-invite-code when email-bound. Rate-limited per [rate_limit]. |
| GET | /codes | admin | Query: status, search, limit, offset. |
| GET | /codes/:code/lookup | public | Returns a minimal view (code, status, maxUses, expiresAt) — never email/metadata/id. |
| PATCH | /codes/:id | admin | { action: 'expire' \| 'reactivate', notify? }. Reactivate is always a fixed 30 days (not default_expiry_days). |
| POST | /codes/:code/expired-click | public | Rate-limited per [rate_limit]. |
Redemption (/codes/:code/redeem, /codes/:id/redemptions) and the waitlist
routes (/waitlist, /waitlist/export, /waitlist/batch-invite) are also
live on the same router — see Tasks 3/4's handlers under
src/server/handlers/ for their request/response shapes.
Client Entry
// Landing page (mount at your invite-link route, e.g. app/invite/[code]/page.tsx)
export { InviteCodePage } from 'hazo_invite/client';
// Standalone states, for a custom landing page built around your own lookup call
export { InviteValidState, InviteExpiredState, InviteExhaustedState, InviteNotFoundState } from 'hazo_invite/client';
export { lookupInviteCode } from 'hazo_invite/client';
// type InviteCodePageProps, InviteValidStateProps, InviteExpiredStateProps,
// InviteExhaustedStateProps, InviteNotFoundStateProps, InviteCodeLookupResult
// Dual-path redemption flow
export { InviteCodeRedeemer, writeInviteCodeCookie, DEFAULT_INVITE_COOKIE_NAME } from 'hazo_invite/client';
// type InviteCodeRedeemerProps
// Admin UI
export { InviteAdminPage } from 'hazo_invite/client';
// type InviteAdminPageProps
// i18n bridge
export { InviteI18nProvider, useInviteT } from 'hazo_invite/client';
// type InviteTFunction
// Pure utilities + client-safe types
export { deriveCodeStatus } from 'hazo_invite/client';
// type InviteCode, InviteRedemption, WaitlistEntry, InviteCodeStatus,
// InviteCodeStatusInput, InviteConfig and sub-shapes, InviteCodeWithStatus,
// RedemptionWithUser, WaitlistEntryWithStatusInviteCodePage — turnkey invite-link landing page
// app/invite/[code]/page.tsx
import { InviteCodePage } from 'hazo_invite/client';
export default function Page({ params }: { params: { code: string } }) {
return (
<InviteCodePage
code={params.code}
apiBase="/api/invite"
getStartedHref="/signup"
waitlistHref="/waitlist"
/>
);
}Renders one of 4 states, decided client-side via lookupInviteCode(apiBase,
code) against the public GET /codes/:code/lookup route:
| State | When | Behavior |
|---|---|---|
| InviteValidState | status: 'valid' | Writes the pending-invite cookie client-side (document.cookie, via writeInviteCodeCookie() — not setInviteCodeCookie(), since this is a client component and can't call a server-only function; see below) so InviteCodeRedeemer's auto-redeem flow can pick it up later; renders a "Get Started" CTA to getStartedHref. |
| InviteExpiredState | status: 'expired' | Fires the POST /codes/:code/expired-click analytics call (best-effort); renders an optional "Join the waitlist" CTA when waitlistHref is passed. |
| InviteExhaustedState | status: 'exhausted' | Static "fully used" message. |
| InviteNotFoundState | lookup returns null (404, or a failed/erroring request — this package has no separate network-error state) | Static "not found" message. |
Each state is also exported standalone for a custom landing page that already has its own lookup result.
Why InviteCodePage is a Client Component, not a Server Component: it
follows this package's established apiBase: string convention (every
fetch goes through the same public HTTP route every other consumer hits,
rather than this package exposing a second "call the server logic
directly" surface). It's also the only option that actually works end to
end for the cookie: Next.js can only write cookies from a Route Handler
or a Server Action, never during a Server Component's render (see
setInviteCodeCookie's doc comment) — so even a Server Component version
of this page would still need a Server Action to set a cookie, same
constraint either way. setInviteCodeCookie() (Task 1, server-only, uses
next/headers) is therefore not re-exported from hazo_invite/client
— it can't be (next/headers isn't available in a client bundle) — and
InviteCodePage doesn't call it. Instead, writeInviteCodeCookie() writes
the same (non-httpOnly) cookie name via plain document.cookie, which is
also what InviteCodeRedeemer's existing cookie-match leg reads back. If
you build your own Server-Action-based invite flow, setInviteCodeCookie()
is still exported from the server barrel (hazo_invite, not
hazo_invite/client) — and, along with readInviteCodeCookie() /
clearInviteCodeCookie(), is the normal, supported server-side cookie API
for this flow: Next.js's cookies() sees every cookie the browser sends
regardless of which path wrote it, and can clear any cookie by name, so all
three work interchangeably with cookies written either server-side or via
writeInviteCodeCookie(). The cookie is deliberately not httpOnly — its
value is just the bearer invite code, already visible in the URL the
visitor opened, so there's nothing sensitive to hide from client JS, and
keeping it readable is what makes the dual-path flow work.
Test app
test-app/ is a real Next.js 16 App Router consumer of this package
(installed via "hazo_invite": "file:..", since this package isn't
published) backed by a local SQLite file — no Postgres/ops involvement.
Mirrors hazo_feedback's own test-app/ conventions.
cd test-app
npm install
npm run build # or: npm run dev (port 3106)Against a running server:
curl -X POST http://localhost:3106/api/migrate # idempotent schema bootstrap
curl -X POST http://localhost:3106/api/bootstrap # seeds + logs in a test admin
curl http://localhost:3106/api/auto_test/invite_lifecycle
curl http://localhost:3106/api/auto_test/edge_casesPages: / (index), /admin (InviteAdminPage), /invite/:code
(InviteCodePage), /translations (every bundled i18n string).
Both /api/auto_test/* routes are dev-only (404 under NODE_ENV=production,
i.e. under next start) and self-contained — unique per-run data, full
cleanup in finally. Since this test-app is a genuine external consumer,
not code living inside this package, they drive the real HTTP API via
same-origin fetch for every admin/self-service action rather than calling
server/logic/*.ts directly (that layer isn't part of the public exports
map — only createCodeService/createRedemptionService/
createWaitlistService/hasValidInviteCode/etc. are; hasValidInviteCode
is called in-process for exactly that reason).
test-app/config/hazo_auth_config.ini pins
[hazo_connect] sqlite_driver = better-sqlite3 — hazo_connect's SQLite
adapter defaults to the sql.js driver (WASM, loads the file into memory
once and never re-reads it), and under Next dev/Turbopack each route
compiles to its own module graph with its own in-memory copy, so a row
written by one route is invisible to another's lookup. better-sqlite3 is
a real file-backed driver with no such divergence.
i18n
Every string in the admin UI and InviteCodePage goes through
createPackageT('hazo_invite', en) (src/strings.ts, bundled English
catalog at src/locales/en.json). Without any extra wiring, every
component renders that bundled English — createPackageT is locale-blind
by itself.
To translate these strings for a multi-locale app, wire up hazo_i18n
(optional peer dependency) the same way hazo_feedback does (see that
package's SETUP_CHECKLIST.md §15 for the fuller walkthrough — the shape
below is identical, just renamed):
Catalog —
hazo_invite's strings register themselves intohazo_i18n's cross-package registry automatically (a fire-and-forget side effect of callingcreatePackageT, the first time any hazo_invite module is imported) ifhazo_i18nis installed. Translate and publish them via the hazo_i18n Language Editor so a per-locale artifact exists.Provider — in your app's
layout.tsx, load the published artifact for the request locale and pass it to hazo_i18n'sHazoI18nProvider.Bridge — mount
InviteI18nProviderinsideHazoI18nProvider, aroundInviteAdminPageand/orInviteCodePage, with a namespacedtfromuseTranslations('hazo_invite'):'use client'; import { useTranslations } from 'hazo_i18n/client'; import { InviteI18nProvider, InviteAdminPage } from 'hazo_invite/client'; const t = useTranslations('hazo_invite'); <InviteI18nProvider t={t}> <InviteAdminPage apiBase="/api/invite" /> </InviteI18nProvider>
With no InviteI18nProvider mounted, every component falls back to the
bundled English catalog via useInviteT()'s own default context value — no
code change required for that fallback to work; it's always on. A missing
key in the active locale's catalog (hazo_i18n throws in dev mode for this)
falls back to the bundled English string for that key specifically, rather
than crashing the page (InviteI18nProvider's wrapTranslatorWithFallback).
The translate prop on InviteCodePage and each standalone landing-page
state (InviteValidState, etc.) still overrides the bridge when supplied,
for a one-off override without a provider.
License
Private — internal hazo_* workspace package.
