Skip to content

@venturekit/auth

Terminal window
npm install @venturekit/auth
import { createCognitoConfig, buildUserPoolConfig, DEFAULT_COGNITO_CONFIG } from '@venturekit/auth';
const config = createCognitoConfig({ mfa: { mode: 'optional', methods: ['totp'] }, passwordPolicy: { minLength: 12 } });
const userPoolConfig = buildUserPoolConfig(config);

In a VentureKit project you rarely call these directly — the pool is declared as an auth intent and provisioned by vk deploy.

Server-side flows (@venturekit/auth/server)

Section titled “Server-side flows (@venturekit/auth/server)”

Everything a Lambda needs to run authentication against the pool, without exposing Cognito’s API surface to route handlers:

import {
signInWithPasswordOrChallenge, respondToSoftwareTokenMfa, // password sign-in + TOTP challenge
beginTotpSetup, confirmTotpSetup, setTotpPreference, // authenticator-app enrolment
refreshSession, revokeRefreshToken, globalSignOut, // session lifecycle
buildSessionCookies, buildClearSessionCookies, cookieAuthMiddleware, // HttpOnly session cookies
signUpUser, forgotPassword, confirmForgotPassword, changePassword,
adminInviteUser, adminUpdateUserAttributes, adminDisableUser,
ensureUserForVerifiedEmail, mintSessionForVerifiedEmail, // passwordless / magic-link
createFederatedAuthRoutes, createSessionHandoffRoutes, // ready-made route sets
requestVerificationCode, verifyVerificationCode, // OTP toolkit
beginPasskeyRegistration, completePasskeySignIn, // passkeys / WebAuthn (auth[].passkeys)
createApiKey, apiKeyAuth, // customer API keys for your own API
createInvitation, acceptInvitation, // "join as <role>" links
issueImpersonationGrant, impersonationMiddleware, // support "view as user", no token minting
AuthError,
} from '@venturekit/auth/server';

Each helper takes an optional AuthServerConfig and defaults to loadAuthServerConfig(), which reads the COGNITO_* variables the first auth intent injects ({ intent: 'staff' } selects another pool’s AUTH_STAFF_* set). Errors surface as AuthError with a stable code and HTTP status. The Authentication guide walks through each flow.

API keys, invitations and verification codes keep their state in tables this package’s migrations create (vk_api_keys, vk_invitations, vk_verification_codes, vk_role_scopes); every such helper takes a querier — @venturekit/data’s query or a transaction’s tx.query — so @venturekit/data stays an optional peer.

import { hasScope, hasAnyScope, hasAllScopes, getScopesForRoles, validateRolesConfig } from '@venturekit/auth';
getScopesForRoles(['member'], rolesConfig); // → ['users.read', 'users.write']
hasScope(['admin'], 'admin.users', config); // → true

For a role → scopes matrix you can change at runtime, use the DB-backed helpers over the vk_role_scopes table (shipped by this package’s migrations, auto-applied by vk migrate):

import { createRoleScopesResolver, setRoleScopes, grantScopeToRole } from '@venturekit/auth';
import { query } from '@venturekit/data';
await setRoleScopes(query, 'editor', ['posts.read', 'posts.write']);
await grantScopeToRole(query, 'editor', 'media.upload');
const resolver = createRoleScopesResolver({ querier: query, ttlMs: 30_000 });
const scopes = await resolver.lookup('editor'); // cached per process; pass as scopesByRole to tenancy middleware
import {
decodeTokenUnsafe,
verifyAndDecode,
extractUserFromToken,
isTokenExpired,
getTokenExpiry,
} from '@venturekit/auth';
// Unsafe decoder — use only when the token has already been verified
// upstream (e.g. API Gateway Cognito Authorizer). The `Unsafe` suffix is
// deliberate so reviewers can spot authentication bypasses.
const claims = decodeTokenUnsafe(jwt);
const user = extractUserFromToken(jwt);
const expired = isTokenExpired(jwt);
// Signature-verifying decoder for paths that haven't been gated upstream
// (cookie-based sessions, background jobs, internal HTTP callers, etc.).
const verified = await verifyAndDecode(jwt, {
userPoolId: 'eu-west-1_xxxxx',
clientId: process.env.COGNITO_APP_CLIENT_ID,
tokenUse: 'access',
});

decodeToken is exported as a deprecated alias of decodeTokenUnsafe for backward compatibility — prefer the explicit name in new code.

  • User, Session, Role, Permission — auth domain types
  • RolesConfig — role definitions; Querier, RoleScopesResolver — DB-backed role → scopes
  • UserPoolOutputs, UserPoolInfraConfig — Cognito infrastructure types
  • SignInResult, SignInChallenge, TotpSetup, SessionTokens, CookieOptions, HandoffStore, VerificationCodeStore — server-side types (from @venturekit/auth/server)
SubpathDescription
@venturekit/authClient-safe: scope checks, JWT utilities, role → scopes helpers, Cognito config builders (no AWS SDK)
@venturekit/auth/serverCognito flows, TOTP MFA, cookies and middleware, federated / handoff route factories, OTP toolkit
@venturekit/auth/server/store/postgrescreatePostgresVerificationCodeStore() over vk_verification_codes (opt-in so @venturekit/data stays optional)
  • @venturekit/core — required
  • @aws-sdk/client-cognito-identity-provider — used by @venturekit/auth/server
  • @venturekit/data — optional (Postgres verification-code store, role → scopes Querier)