@tktchurch/auth
@tktchurch/auth
Framework-agnostic auth SDK for TKTChurch OAuth/AuthFlow services.
- Default production endpoint:
https://prod-auth.tktchurch.com - Works in browser and Node runtimes (requires
fetch) - Pluggable token storage (
memoryby default) - First-class support for AuthFlow endpoints
Install
npm install @tktchurch/auth
Quick Start
import { createAuthClient } from "@tktchurch/auth";
const auth = createAuthClient({
clientId: "your_client_id",
// Optional:
// clientSecret: "your_client_secret",
// baseUrl: "https://prod-auth.tktchurch.com",
});
// Authorization code + PKCE (see the redirect-flow section below).
const request = await auth.authorize.createRequest({
redirectUri: "https://app.example.com/callback",
});
// Persist request.state / request.codeVerifier / request.nonce server-side,
// then redirect the browser to request.url.
auth.token.password()(ROPC) is deprecated. OAuth 2.1 removes it. It logs a one-time warning and will be removed in v2.0.0. See Migrating offtoken.password().
Primary email verification compatibility
SDK 0.9.9's user.emailVerification.start() / verify() contract requires a
backend exposing POST /api/v1/users/me/email/verify with the
identity:write scope and recent-authentication enforcement. Deploy and
validate that backend before releasing or adopting SDK 0.9.9. A successful
verification revokes the caller's existing sessions and tokens, so clients
must sign in again; the stable user identity remains the OIDC sub, not email.
Authorization Code + PKCE (redirect flow)
The recommended browser/SSR login flow. The SDK generates PKCE, state, and
nonce for you and hands back everything you must persist across the redirect —
no more hand-rolling crypto per app.
1. Start the flow (server route that begins login):
import { createAuthClient } from "@tktchurch/auth";
const auth = createAuthClient({ clientId: process.env.TKT_CLIENT_ID! });
const request = await auth.authorize.createRequest({
redirectUri: "https://app.example.com/callback",
// scope defaults to "openid profile email offline_access"
});
// Persist these in an HttpOnly cookie / server session, keyed by `state`:
// request.state, request.nonce, request.codeVerifier, request.redirectUri
// Then redirect the user agent:
// 302 -> request.url
2. Handle the callback — one call validates state (constant-time),
surfaces server errors, and exchanges the code for tokens:
const tokens = await auth.authorize.handleCallback({
callback: requestUrl, // full callback URL or its query string
expectedState: saved.state, // the state you persisted in step 1
expectedNonce: saved.nonce, // binds the ID token to this login (OIDC)
codeVerifier: saved.codeVerifier,
redirectUri: saved.redirectUri,
});
// tokens.accessToken / tokens.refreshToken — persist refresh in HttpOnly cookie;
// keep access token in server memory per request (see examples/).
Security: the PKCE
codeVerifieris a secret — keep it server-side (HttpOnly cookie or session store), never inlocalStorage.stateis verified with a constant-time comparison to defeat CSRF and timing oracles.Mix-up defence (RFC 9207):
handleCallbackalso checks the callbackissagainst the issuer from OIDC discovery (cached), or againstexpectedIssuerif you pass one.issis required when the AS advertisesauthorization_response_iss_parameter_supported, and a wrongissalways rejects the callback before the code is exchanged.ID token (OIDC Core §3.1.3.7): when the token response has an
id_token,handleCallbackverifies its signature against the issuer JWKS and checksiss,aud/azp,exp/iat,nonce(viaexpectedNonce) andat_hashbefore anything is stored. Failures throwIdTokenValidationErrorwith a typedreason. Validated claims are returned astokens.idTokenClaims.
Open-redirect protection
Always sanitize any next/returnTo value before redirecting after login:
import { sanitizePostAuthRedirect } from "@tktchurch/auth";
return Response.redirect(sanitizePostAuthRedirect(next, "/dashboard"));
// "//evil.com", "https://evil.com", "javascript:…", CRLF → fallback
Low-level PKCE helpers
If you need the primitives directly:
import {
deriveCodeChallenge,
generateNonce,
generatePkce,
generateState,
} from "@tktchurch/auth";
const { codeVerifier, codeChallenge, codeChallengeMethod } =
await generatePkce();
OIDC discovery
const meta = await auth.oidc.discover(); // /.well-known/openid-configuration
console.log(meta.authorizationEndpoint, meta.tokenEndpoint, meta.jwksUri);
Framework-Agnostic Usage
Server route (recommended)
Use in-memory storage (the default) and persist refresh tokens in HttpOnly
cookies. See examples/ for full PKCE redirect flows.
import { createAuthClient } from "@tktchurch/auth";
const auth = createAuthClient({
clientId: process.env.TKT_CLIENT_ID!,
clientSecret: process.env.TKT_CLIENT_SECRET!,
});
export async function GET() {
const me = await auth.user.me();
return Response.json(me);
}
Do not store OAuth tokens in
localStorageorsessionStorage. The SDK does not ship a browser persistence adapter — use server-side cookies or a platform secure store (Keychain, Keystore). SeeSECURITY.md.
Framework Examples (Best Practices)
Production-oriented examples are available in:
They follow server-first patterns:
- Authorization code + PKCE redirect flow (primary).
clientSecretremains server-only.- Tokens live in a sealed HttpOnly session cookie (
@tktchurch/auth/server). - PKCE
codeVerifieris stored inside that sealed session during the redirect. - Refresh token rotation is performed on every refresh call.
- Logout uses OIDC RP-Initiated Logout (
/oauth/end_session) when available, plus refresh revoke and sealed-cookie clear. Mount front-/back-channel logout handlers for multi-RP SSO teardown. - Next.js apps use
@tktchurch/auth/next(see below).
OIDC Logout (RP-Initiated)
const url = auth.oidc.buildEndSessionUrl({
idTokenHint: session.idToken,
clientId: process.env.TKT_CLIENT_ID!,
postLogoutRedirectUri: "https://app.example.com/",
state: "csrf-logout-state",
});
// Redirect the browser to `url` after clearing local session cookies.
Register post_logout_redirect_uris (and optionally front-/back-channel logout
URIs) on the OAuth client in the developers console.
Next.js Adapter (@tktchurch/auth/next)
First-class App Router support for Next.js 15/16 (proxy, async cookies(),
RSC, Route Handlers, Server Actions).
import { createNextAuth } from "@tktchurch/auth/next";
import { createAuthClient } from "@tktchurch/auth";
export const nextAuth = createNextAuth({
auth: () =>
createAuthClient({
clientId: process.env.TKT_CLIENT_ID!,
clientSecret: process.env.TKT_CLIENT_SECRET,
}),
session: {
secret: process.env.TKT_SESSION_SECRET!,
cookieName: "tkt_next_session",
},
routes: {
redirectUri: "https://app.example.com/api/auth/callback",
afterLoginPath: "/dashboard",
loginPath: "/api/auth/login",
},
});
// app/api/auth/login/route.ts
export const GET = nextAuth.handlers.login.GET;
// proxy.ts (Next.js 16 — not middleware.ts)
const { proxy, config } = nextAuth.createProxy({
matcher: ["/dashboard/:path*"],
requireAccountType: "user",
});
export { proxy, config };
// Server Component
const session = await nextAuth.auth();
Rules: keep token refresh in Node Route Handlers; proxy only unseals the
cookie and redirects. See examples/next-app-router.
Server sessions (@tktchurch/auth/server)
Shared cookie / SSO helpers for Accounts, Developers, Convoy, and Deno microsites.
Do not set product JWT sessions with Domain=.tktchurch.com — that causes
HTTP 431 on other subdomains (e.g. campaign sites on Deno Deploy).
import {
createSessionCookies,
cookieOptions,
expireLegacyParentDomainCookies,
mintSealedSsoCookieValue,
startSilentAuthorize,
hasSsoCookieHint,
} from "@tktchurch/auth/server";
// Host-only app session (Nuxt h3 or Deno Set-Cookie)
const sessions = createSessionCookies({
secret: process.env.COOKIE_SECRET!,
cookieName: "dev_auth_session",
legacyParentDomainNames: ["dev_auth_session"],
});
const setCookie = await sessions.serializeSessionSetCookie(payload, {
hostname: "developers.tktchurch.com",
});
// Tiny parent-domain SSO hint (Accounts IdP only — no JWTs)
const { cookieValue } = await mintSealedSsoCookieValue(ssoSecret, {
userId: user.id,
expiresAt: Date.now() + 30 * 24 * 3600 * 1000,
});
// Resume SSO without password when tkt_sid is present
if (hasSsoCookieHint(req.headers.get("cookie"))) {
const authRequest = await startSilentAuthorize(client, {
redirectUri: "https://app.example/callback",
});
}
Nuxt Module (@tktchurch/auth/nuxt)
Register the module in nuxt.config.ts:
export default defineNuxtConfig({
modules: ["@tktchurch/auth/nuxt"],
tktAuth: {
baseUrl: process.env.TKT_AUTH_BASE_URL ?? "https://prod-auth.tktchurch.com",
clientId: process.env.TKT_CLIENT_ID,
clientSecret: process.env.TKT_CLIENT_SECRET,
autoRefresh: false,
refreshCookieName: "tkt_refresh_token",
},
});
Then use provided imports:
const auth = createTktServerAuthClient();
const appAuth = useTktAuth();
const refreshCookieName = useTktRefreshCookieName();
AuthFlow Example
const init = await auth.flow.initAuthentication({
username: "user@example.com",
});
let status = await auth.flow.executeStep({
sessionId: init.sessionId,
stepId: init.currentStep.stepId,
continuationToken: init.continuationToken,
credential: {
username: "user@example.com",
password: "secret",
},
});
while (status.status === "in_progress") {
// Render UI for status.nextStep and collect credentials for that step.
status = await auth.flow.executeStep({
sessionId: status.sessionId,
stepId: status.nextStep.stepId,
continuationToken: init.continuationToken,
credential: {},
});
}
// status.status === "complete"
console.log(status.accessToken);
Token Storage
Memory (default)
import { createAuthClient, createMemoryTokenStorage } from "@tktchurch/auth";
const auth = createAuthClient({
clientId: "client_id",
storage: createMemoryTokenStorage(),
});
Custom TokenStorage
For platform-specific secure backends (Keychain, Keystore, encrypted server
session), implement TokenStorage using the exported validators
(assertValidAuthTokens, parseStoredAuthTokens, serializeAuthTokens). See
SECURITY.md.
Error Handling
import { AuthError, MFARequiredAuthError } from "@tktchurch/auth";
try {
await auth.token.password({
username: "user@example.com",
password: "secret",
});
} catch (error) {
if (error instanceof MFARequiredAuthError) {
console.log("MFA required:", error.mfaMethods);
} else if (error instanceof AuthError) {
console.log(error.code, error.message, error.status);
} else {
throw error;
}
}
Authenticated Fetch
fetchWithAuth adds the bearer token automatically and retries once on 401
using refresh token when possible.
Note:
fetchWithAuthandrequest()are available only in the full SDK (GitHub Packages / localfile:build). The public npmjs consumer build omits generic passthrough helpers.
const response = await auth.fetchWithAuth("/api/v1/users/me");
if (!response.ok) {
// handle response
}
API reference (public consumer build)
The public npmjs package ships OAuth/OIDC client namespaces only. Admin console
modules (clients, roles, auditLogs, …) and generic passthrough helpers are
available in the full SDK from GitHub Packages — see
CONTEXT.md.
| Namespace | Methods | Auth |
|---|---|---|
token |
password, refresh, clientCredentials, authorizationCode, anonymous, tokenExchange, revoke, introspect |
client credentials / stored tokens |
authorize |
createRequest, parseCallback, handleCallback, consent, consentWithCredentials |
public + server session |
oidc |
userInfo, discover, jwks |
bearer / public |
oauth |
publicClient, discoverAuthorizationServer |
public |
flow |
initAuthentication, executeStep, initRegistration, executeRegistrationStep, initRecovery, executeRecoveryStep, getStatus |
public / step session |
user |
me, updateMe, changePassword, uploadAvatar, avatarAssets.*, deleteAvatar, verifyPhone, securityOverview, recoveryContacts.*, identities.*, deleteMe |
bearer |
sessions |
list, current, get, update, revoke, revokeAll, revokeAllDevices |
bearer |
webauthn |
registerBegin/Finish, authenticateBegin/Finish, credentials, removeCredential, renameCredential, setPrimaryCredential |
bearer / public begin |
passwordReset |
request, validate, complete |
public |
mfa |
setup, verify, devices, removeDevice, regenerateBackupCodes, disable |
bearer |
maintenance |
status |
public |
token.clientCredentials() is for confidential clients only and throws
invalid_request when clientSecret is not configured. Public clients must use
authorization code + PKCE (authorize.createRequest).
Integrators must pass an explicit baseUrl in
createAuthClient({ baseUrl, clientId, … }). The public consumer build does not
export DEFAULT_BASE_URL.
user.avatarAssets.list() returns private history metadata only. Select a
retained version with user.avatarAssets.select(assetId) and explicitly delete
one with user.avatarAssets.delete(assetId). The compatibility
user.deleteAvatar() method only deselects the current version; it does not
delete history. Since asset source URLs and object keys are intentionally
private, render the active image from user.me().picture.
Internal admin SDK (GitHub Packages only)
The full build adds consents, admin maintenance.*, clients … comms,
privacy, user.admin.*, plus request() / fetchWithAuth(). Admin methods
require a bearer access token with matching backend permissions (client:read,
user:write, *:*, etc.). The SDK does not enforce permissions — the OAuth
server does.
Migrating off token.password() and responseType
OAuth 2.1 removes the resource owner password grant and the implicit grant.
tktchurch/oauth sunsets both for legacy20 clients: warnings from 2026-11-14,
blocked 2027-01-13, code deleted 2027-02-12. The SDK follows the same timeline:
| API | v1.x (now) | v2.0.0 |
|---|---|---|
token.password() |
works, @deprecated, one-time console.warn |
removed |
AuthorizationUrlOptions.responseType other than code |
still sent, one-time console.warn |
option removed; always code |
Migration:
- Replace
token.password({ username, password })with the redirect flow:authorize.createRequest()→ redirect →authorize.handleCallback()(or the Next/Nuxt adapters, which do this for you). - To keep your own sign-in UI, use hosted sign-in (
buildHostedLoginUrl/hostedLoginadapter option). The accounts app collects credentials and the app still receives an authorization code. - Drop any
responseTypeoption. The SDK always sendsresponse_type=codewith PKCE S256.
Migrating from hand-rolled oauth.ts
Replace direct fetch calls with namespaced SDK methods:
// Before
await fetch(`${baseUrl}/oauth/token`, { method: "POST", body });
// After
const tokens = await auth.token.authorizationCode({
code,
redirectUri,
codeVerifier,
});
For admin console CRUD (/api/v1/clients, etc.), use the full SDK from
GitHub Packages — see CONTEXT.md.
MCP OAuth (RFC 8707 / 9728 / 8628)
Use @tktchurch/auth as the generic MCP OAuth client for prod-auth. Works for
Convoy MCP, Calendar MCP, and future resource servers.
import { createAuthClient } from "@tktchurch/auth";
import { createConvoyMcpClient } from "@tktchurch/convoy/mcp";
const MCP_URL = "https://convoy.tktchurch.net/mcp";
const auth = createAuthClient({
clientId: process.env.TKT_CLIENT_ID!,
baseUrl: "https://prod-auth.tktchurch.com",
});
// 1. Discover PRM + authorization server metadata
const ctx = await auth.mcp.discover(MCP_URL);
// 2. Authorize with RFC 8707 resource binding
const request = await auth.mcp.createAuthorizationRequest(ctx, {
redirectUri: "https://my-host.example/callback",
scope: "openid convoy:read",
});
// Persist request.state, codeVerifier, redirectUri → redirect to request.url
const tokens = await auth.mcp.handleCallback(ctx, {
callback: callbackUrl,
expectedState: saved.state,
codeVerifier: saved.codeVerifier,
redirectUri: request.redirectUri,
});
auth.mcp.assertTokenAudience(tokens.accessToken, ctx.resource);
// 3. Call Convoy MCP tools (product SDK)
const convoy = createConvoyMcpClient({ accessToken: tokens.accessToken });
await convoy.discover();
const campaigns = await convoy.tools.listCampaigns();
CLI / IDE hosts (device flow):
const started = await auth.device.start({
scope: "openid convoy:read",
resource: ctx.resource,
});
// Show started.userCode + started.verificationUri to the user
const tokens = await auth.device.pollUntilAuthorized({
deviceCode: started.deviceCode,
resource: ctx.resource,
});
Official MCP SDK adapter: import @tktchurch/auth/mcp-provider and pass
createTktAuthOAuthProvider() as the authProvider on
@modelcontextprotocol/client transports.
Inject internal URL rewriting via createAuthClient({ fetch }) — same pattern
as accounts / developers oauth-fetch.ts.
Release and Publish
- Changelog:
CHANGELOG.md - Publishing guide:
PUBLISHING.md
GitHub Packages (private, tktchurch scope) is configured via:
- Script:
bun run publish:github - Workflow:
.github/workflows/publish-github-packages.yml - Auth token:
NODE_AUTH_TOKEN(GITHUB_TOKENin workflow)
npmjs (public) publishing ships the consumer build only:
- Script:
bun run publish:npmjs(runsrelease:check:consumer) - Workflow:
.github/workflows/publish-npmjs.yml - Auth: npm trusted publishing (OIDC, no
NPM_TOKENsecret) or localNODE_AUTH_TOKEN
GitHub Packages ships the full internal SDK. See
PUBLISHING.md for the dual-build matrix.
CI
CI runs on the org self-hosted runner [self-hosted, macOS, ARM64] (GitHub-hosted runners are not available for this org). If Actions is unavailable, run the same checks locally:
scripts/ci-local.sh
This runs bun install --frozen-lockfile, typecheck, test, and both the full and consumer builds.
Related Packages
AuthAction server-side SDK — session-based auth for Next.js, Nuxt, Remix, and Sv...
Nuxt integrator for Qelos: server middleware/module that identifies the user and...
Vue 3 composables and components for Proteles authentication, plus Nuxt/h3 serve...
Version History
| Version | Released | Vue | License |
|---|---|---|---|
| 1.1.1 | ^3.0 | MIT | |
| 1.1.0 | ^3.0 | MIT | |
| 1.0.0 | ^3.0 | MIT | |
| 0.14.0 | ^3.0 | MIT | |
| 0.13.1 | ^3.0 | MIT | |
| 0.13.0 | ^3.0 | MIT | |
| 0.12.0 | ^3.0 | MIT | |
| 0.11.0 | ^3.0 | MIT | |
| 0.10.0 | ^3.0 | MIT | |
| 0.9.9 | ^3.0 | MIT | |
| 0.9.8 | ^3.0 | MIT | |
| 0.9.7 | ^3.0 | MIT | |
| 0.9.6 | ^3.0 | MIT | |
| 0.9.5 | ^3.0 | MIT | |
| 0.9.1 | ^3.0 | MIT |