@tktchurch/auth

Framework-agnostic auth SDK for TKTChurch OAuth/AuthFlow services
2,767
Install
npm install @tktchurch/auth
Latest Version:1.1.1
Vue:3
License:MIT
Last Updated:Oct 17, 2026
Links: npm
Maintainer: vamsii777

@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 (memory by 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 off token.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 codeVerifier is a secret — keep it server-side (HttpOnly cookie or session store), never in localStorage. state is verified with a constant-time comparison to defeat CSRF and timing oracles.

Mix-up defence (RFC 9207): handleCallback also checks the callback iss against the issuer from OIDC discovery (cached), or against expectedIssuer if you pass one. iss is required when the AS advertises authorization_response_iss_parameter_supported, and a wrong iss always rejects the callback before the code is exchanged.

ID token (OIDC Core §3.1.3.7): when the token response has an id_token, handleCallback verifies its signature against the issuer JWKS and checks iss, aud/azp, exp/iat, nonce (via expectedNonce) and at_hash before anything is stored. Failures throw IdTokenValidationError with a typed reason. Validated claims are returned as tokens.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 localStorage or sessionStorage. The SDK does not ship a browser persistence adapter — use server-side cookies or a platform secure store (Keychain, Keystore). See SECURITY.md.

Framework Examples (Best Practices)

Production-oriented examples are available in:

They follow server-first patterns:

  1. Authorization code + PKCE redirect flow (primary).
  2. clientSecret remains server-only.
  3. Tokens live in a sealed HttpOnly session cookie (@tktchurch/auth/server).
  4. PKCE codeVerifier is stored inside that sealed session during the redirect.
  5. Refresh token rotation is performed on every refresh call.
  6. 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.
  7. 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: fetchWithAuth and request() are available only in the full SDK (GitHub Packages / local file: 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:

  1. Replace token.password({ username, password }) with the redirect flow: authorize.createRequest() → redirect → authorize.handleCallback() (or the Next/Nuxt adapters, which do this for you).
  2. To keep your own sign-in UI, use hosted sign-in (buildHostedLoginUrl / hostedLogin adapter option). The accounts app collects credentials and the app still receives an authorization code.
  3. Drop any responseType option. The SDK always sends response_type=code with 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

GitHub Packages (private, tktchurch scope) is configured via:

npmjs (public) publishing ships the consumer build only:

  • Script: bun run publish:npmjs (runs release:check:consumer)
  • Workflow: .github/workflows/publish-npmjs.yml
  • Auth: npm trusted publishing (OIDC, no NPM_TOKEN secret) or local NODE_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

nuxt-openid-connect

An nuxt 3 module with OpenID-Connect(OIDC) integration.

6,539 42
@authaction/server-sdk

AuthAction server-side SDK — session-based auth for Next.js, Nuxt, Remix, and Sv...

734
@qelos/integrator-nuxt

Nuxt integrator for Qelos: server middleware/module that identifies the user and...

2,274
@proteles/vue

Vue 3 composables and components for Proteles authentication, plus Nuxt/h3 serve...

465 0
nuxt-openid

OpenID-Connect (OIDC) integration module for Nuxt

4,795 0

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