@tktchurch/convoy
v0.5.0
Published
Type-safe, runtime-neutral SDK for the TKTChurch Convoy registration API
Maintainers
Readme
@tktchurch/convoy
Runtime-neutral TypeScript client for Convoy campaigns and registration flows.
It uses web-standard fetch, Headers, AbortController, and URL APIs and
has no runtime dependencies, so the same package works in browsers and Deno.
Install
npm install @tktchurch/convoyDeno can import the npm package directly:
import { createConvoyClient } from "npm:@tktchurch/[email protected]";Create a client
import { createConvoyClient } from "@tktchurch/convoy";
const convoy = createConvoyClient({
baseUrl: "https://convoy.tktchurch.com",
timeout: 30_000,
defaultHeaders: {
// Add Authorization here only in a trusted request-scoped client.
authorization: `Bearer ${accessToken}`,
},
});fetch may be injected for testing or runtimes that do not expose
globalThis.fetch. Request headers override defaultHeaders.
Authentication tiers
Each resource belongs to exactly one auth tier — send the matching credential:
| Tier | Credential | SDK resources |
| --- | --- | --- |
| Public | None | campaigns.*, invites.resolve, leaderboard reads |
| Owner capability | x-registration-owner header | registration.getSession, submitStep, resendOtp, syncVerifiedEmail |
| Bearer | authorization via a request-scoped client's defaultHeaders | registrations.*, referrals.mine, invites.myInvites, avatar writes |
| Staff | — | Not in this SDK. Staff APIs live behind Convoy's staff auth (app/convoy/*); use the MCP tools above instead. |
x-registration-owner
In-flight registration calls send the session's ownerSecret in the
x-registration-owner request header (passed as the last SDK argument). The
secret is a capability: whoever holds it can resume the session without a
Bearer token. Keep it in memory or an HttpOnly server session — never in URLs,
query strings, or telemetry.
baseUrl and CORS
- Point
baseUrlat the public Convoy API origin (https://convoy.tktchurch.com) or a first-party proxy of it. It must be an absolute HTTP(S) URL; a path prefix onbaseUrlis preserved when requests are built. - Convoy's browser CORS policy is an origin allowlist (never
*). Register each campaign's origin before calling the API from a browser; unregistered origins are rejected before any endpoint logic runs. - Deno/Node callers are not affected by CORS but should keep the same origin so rate limits behave like production.
Campaigns
const campaign = await convoy.campaigns.get("faith-gathering");
const status = await convoy.campaigns.status("faith-gathering");Campaign status includes currently relevant announcements. The pure selector
applies the shared display order: global before campaign, newest startsAt,
then announcement ID.
import {
announcementDismissalKey,
selectActiveAnnouncement,
} from "@tktchurch/convoy";
const announcement = selectActiveAnnouncement(
status.announcements,
campaign.campaign.campaignId,
);
if (announcement) {
const key = announcementDismissalKey(
announcement,
announcement.presentation,
);
// Persist `key` after the user dismisses this presentation.
}Modal and banner keys are intentionally separate and include
announcementId:revision; publishing a revision shows it again without making
a modal dismissal suppress the banner. selectAnnouncement is also available
when a consumer needs to pre-filter one presentation and a set of dismissal
keys.
Registration flow
const touch = captureAttributionTouch({
url: window.location.href,
referrer: document.referrer,
});
const attribution = mergeAttribution(
previouslyStoredAttribution,
touch,
`acq_${crypto.randomUUID().replaceAll("-", "")}`,
);
let session = await convoy.registration.startSession({
campaignId: "faith-gathering",
attribution: attributionToRecord(attribution),
});
// Keep ownerSecret in memory or an HttpOnly server session. It is a capability.
const ownerSecret = session.ownerSecret;
session = await convoy.registration.submitStep(
session.sessionId,
session.currentStep!.id,
{ accepted: "true" },
ownerSecret,
);
// Calling the OTP step without a code asks Convoy to send another code.
session = await convoy.registration.resendOtp(
session.sessionId,
session.currentStep!.id,
{ phoneCountryCode: "+91", phone: "9000025521" },
ownerSecret,
);Resume an in-flight registration with
registration.getSession(sessionId, ownerSecret). expiresAt and
ownerSecret are typed for the owner-secret API rollout while remaining
optional against the current API response.
registration.redeemRecovery(campaignId, token) calls
POST /convoy/register/recovery/redeem. The opaque token is sent in the JSON
body with its campaign binding, never in the URL.
Recovery-route contract
Convoy-generated links use
/registration/recover#campaignId=<encoded>&token=<encoded>. Both Fresh
microsites must implement this as a client-only route: read the fragment,
immediately call history.replaceState(null, "", "/registration/recover"),
then pass both values to registration.redeemRecovery. Store the returned
ownerSecret as the registration-only capability and resume with getSession.
The route must not server-render, persist, log, or copy the fragment into a query string. Fragments are not sent in HTTP requests or Referer headers; clearing it before further navigation keeps the bearer out of browser history.
Current registration
The current API requires eventId; the SDK keeps it optional so the planned
server-side default remains source-compatible.
const mine = await convoy.registrations.me({ eventId: "evt_123" });
await convoy.registrations.updateFormFields({
eventId: "evt_123",
fields: { ATTENDS_TKT_CHURCH: "yes" },
});These endpoints require an OAuth Bearer token, normally supplied through a
request-scoped client's defaultHeaders.
Invites and referrals
Two separate systems that share one microsite landing path:
| | Invite | Referral |
| --- | --- | --- |
| Unit | One code = one invitee registration | One code, unlimited uses |
| Resource | convoy.invites | convoy.referrals |
| Landing | {origin}/invite/{code} → ?invite= | {origin}/invite/{code} → ?ref= |
// Landing page (anonymous): validate before redirecting to registration.
const invite = await convoy.invites.resolve(code, eventId);
// → redirect to `${origin}/register?invite=${code}`
// invite.inviterFirstName is present only when the event enables it.
// Registered user: quota + links. Grants are minted lazily up to the
// configured quota on first read, so existing registrations qualify.
const { quota, remaining, invites } = await convoy.invites.myInvites(eventId);
// Share URLs
convoy.invites.shareUrl(origin, code); // site/invite/CODE (OG preview)
convoy.invites.registerUrl(origin, code); // site/register?invite=CODE (direct)
// Referrals
const { ownReferralCode } = await convoy.referrals.mine({ eventId });
convoy.referrals.shareUrl(origin, code); // same landing; forwards with ?ref=
convoy.referrals.registerUrl(origin, code); // site/register?ref=CODE (direct)Notes:
invites.resolveis read-only — resolving never consumes a code. It rejects withConvoyErrorcodesINVITE_NOT_FOUND(404; also sent when invites are disabled for the event) andINVITE_USED/INVITE_EXPIRED/INVITE_REVOKED(410). A landing shared with legacy referral links can treat the 404 as "not an invite" and fall back to?ref=.- The campaign's
inviteConfig(enabled,quotaPerRegistration,codeLength,expiresAfterDays,showInviterName) is present oncampaigns.getonly when the event has invites enabled. - Both link builders emit the same canonical
/invite/{code}path; the landing page decides?invite=vs?ref=by resolving the code. UseregisterUrlto skip the landing (no OG/WhatsApp preview). - Staff endpoints (listing or revoking any invite) are intentionally not part of this SDK.
Convoy MCP (staff tools)
The REST client above targets convoy.tktchurch.com. Convoy MCP staff tools
live at https://convoy.tktchurch.net/mcp and use a separate import:
npm install @tktchurch/convoy @tktchurch/authimport { createAuthClient } from "@tktchurch/auth";
import { createConvoyMcpClient } from "@tktchurch/convoy/mcp";
const auth = createAuthClient({
clientId: process.env.TKT_CLIENT_ID!,
baseUrl: "https://prod-auth.tktchurch.com",
});
const ctx = await auth.mcp.discover("https://convoy.tktchurch.net/mcp");
const request = await auth.mcp.createAuthorizationRequest(ctx, {
redirectUri: "https://my-host.example/callback",
scope: "openid convoy:read",
});
const tokens = await auth.mcp.handleCallback(ctx, {
callback: callbackUrl,
expectedState: saved.state,
codeVerifier: saved.codeVerifier,
redirectUri: request.redirectUri,
});
const mcp = createConvoyMcpClient({ accessToken: tokens.accessToken });
await mcp.discover();
const campaigns = await mcp.tools.listCampaigns();OAuth belongs in @tktchurch/auth; this package only transports Bearer tokens
to the Convoy MCP resource server.
Typed errors
All failures derive from ConvoyError:
SessionExpiredErrorOtpSessionExpiredErrorRateLimitedError(retryAfter) — any HTTP 429OtpRateLimitedErrorextends it (OTP endpoints, explicitOTP_RATE_LIMITED)
InviteRequiredError(invite-only campaigns, HTTP 403)InviteInvalidError(bad invite at registration start, HTTP 403)MaintenanceError(mode,endsAt)OwnershipRequiredErrorMcpUnauthorizedError,McpInsufficientScopeError,McpRpcError,McpHeaderMismatchError(MCP subpath only)
Invite lifecycle codes from invites.resolve (INVITE_NOT_FOUND,
INVITE_USED, INVITE_EXPIRED, INVITE_REVOKED) surface as plain
ConvoyError with code set — check error.code for those.
import { MaintenanceError, SessionExpiredError } from "@tktchurch/convoy";
try {
await convoy.registration.getSession(sessionId, ownerSecret);
} catch (error) {
if (error instanceof SessionExpiredError) {
// Offer recovery or begin a new session.
} else if (error instanceof MaintenanceError) {
// Keep local form state and retry after maintenance.
}
}The SDK parses structured code, message, error, error_description, and
reason fields. It never logs requests, owner secrets, recovery tokens, or
Bearer tokens. Callers must apply the same rule to their own telemetry.
Caching
Session, status, recovery, mutation, and self-service requests use
cache: "no-store". Campaign metadata may use the runtime's default caching
policy.
