@venturekit/auth
Installation
Section titled “Installation”npm install @venturekit/authWhat It Provides
Section titled “What It Provides”Cognito Configuration
Section titled “Cognito Configuration”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.
Role-Based Access Control
Section titled “Role-Based Access Control”import { hasScope, hasAnyScope, hasAllScopes, getScopesForRoles, validateRolesConfig } from '@venturekit/auth';
getScopesForRoles(['member'], rolesConfig); // → ['users.read', 'users.write']hasScope(['admin'], 'admin.users', config); // → trueFor 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 middlewareJWT / Session Utilities
Section titled “JWT / Session Utilities”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 typesRolesConfig— role definitions;Querier,RoleScopesResolver— DB-backed role → scopesUserPoolOutputs,UserPoolInfraConfig— Cognito infrastructure typesSignInResult,SignInChallenge,TotpSetup,SessionTokens,CookieOptions,HandoffStore,VerificationCodeStore— server-side types (from@venturekit/auth/server)
Subpath Exports
Section titled “Subpath Exports”| Subpath | Description |
|---|---|
@venturekit/auth | Client-safe: scope checks, JWT utilities, role → scopes helpers, Cognito config builders (no AWS SDK) |
@venturekit/auth/server | Cognito flows, TOTP MFA, cookies and middleware, federated / handoff route factories, OTP toolkit |
@venturekit/auth/server/store/postgres | createPostgresVerificationCodeStore() over vk_verification_codes (opt-in so @venturekit/data stays optional) |
Dependencies
Section titled “Dependencies”@venturekit/core— required@aws-sdk/client-cognito-identity-provider— used by@venturekit/auth/server@venturekit/data— optional (Postgres verification-code store, role → scopesQuerier)
Related
Section titled “Related”- Authentication Guide — setup walkthrough
- Handlers — scope-based auth in handlers
- API Reference — full type documentation