@atzentis/auth-sdk
v0.1.1
Published
Atzentis Auth SDK — TypeScript client for auth.atzentis.com
Maintainers
Readme
@atzentis/auth-sdk
Core TypeScript client for auth.atzentis.com. Framework-agnostic with no runtime dependencies — runs in Node.js, Deno, Bun, edge functions, and any TypeScript environment.
Features
- HTTP client with request/response interceptors, automatic retry with exponential backoff, and configurable rate limiting
- Multi-method authentication — email/password, username/password, phone OTP, OAuth providers, magic link, and passkey/WebAuthn
- Session management with background token refresh and multi-session support
- Device tracking and trust management — list devices, trust/untrust, remove, and collect browser device signals
- Login activity monitoring — paginated event history, mark recognized, report suspicious with risk scoring
- Organization management with full RBAC — create, update, delete, invite members, manage roles, handle invitations
- API key management — create, rotate, revoke, validate, and track usage with pagination
- User profile management — update profile, change password, manage connected OAuth providers, phone numbers, and two-factor auth
- Passkey/WebAuthn support — register, authenticate, list, rename, and remove passkeys
- 341 localization keys shared across React and Expo packages
- 15 Zod validation schemas for all request/response shapes
- TanStack Query key factory (
authKeys) for consistent cache key management
Installation
npm install @atzentis/auth-sdk
# or
pnpm add @atzentis/auth-sdk
# or
bun add @atzentis/auth-sdkQuick Start
import { AuthClient } from "@atzentis/auth-sdk";
const auth = new AuthClient({
baseUrl: "https://auth.atzentis.com",
});
// Sign in
const session = await auth.auth.signInWithEmail({
email: "[email protected]",
password: "password123",
});
// Get current user
const user = await auth.users.getCurrentUser();
// Get the active session
const current = await auth.sessions.getSession();
// Sign out
await auth.auth.signOut();Services
AuthClient exposes the following services as properties:
| Property | Service | Key Methods |
| --- | --- | --- |
| auth.auth | AuthService | signInWithEmail, signInWithUsername, signInWithPhone, signInWithOAuth, signInWithMagicLink, signUp, signOut, requestPasswordReset, resetPassword, sendVerificationEmail, verifyEmail |
| auth.sessions | SessionService | getSession, refreshSession, listSessions, revokeSession, revokeAllSessions, setActiveSession |
| auth.devices | DeviceService | list, getCurrent, trust, untrust, remove, removeAllOthers |
| auth.loginActivity | LoginActivityService | list, markRecognized, reportSuspicious |
| auth.organizations | OrganizationService | create, get, list, update, delete, inviteMember, removeMember, updateMemberRole, listMembers, listInvitations, resendInvitation, revokeInvitation, acceptInvitation, declineInvitation, leave |
| auth.apiKeys | ApiKeyService | create, get, list, update, rotate, revoke, validate, getUsage |
| auth.users | UserService | getCurrentUser, update, setupTwoFactor, verifyTwoFactorSetup, disableTwoFactor, changePassword, deleteAccount, listConnectedProviders, connectOAuthProvider, disconnectOAuthProvider, addPhoneNumber, verifyPhoneNumber, removePhoneNumber |
| auth.passkeys | PasskeyService | register, authenticate, list, remove, rename, getChallenge |
| auth.phone | PhoneService | sendOTP, verify, signIn |
AuthService
Handles all authentication flows:
// Email sign-in
const session = await auth.auth.signInWithEmail({
email: "[email protected]",
password: "password123",
});
// OAuth — get redirect URL
const { url } = await auth.auth.signInWithOAuth({
provider: "google",
redirectUrl: "https://myapp.com/auth/callback",
});
window.location.href = url;
// Magic link
await auth.auth.signInWithMagicLink({
email: "[email protected]",
redirectUrl: "https://myapp.com/auth/magic",
});
// Sign up
const result = await auth.auth.signUp({
email: "[email protected]",
password: "password123",
name: "Jane Doe",
});
// Password reset
await auth.auth.requestPasswordReset({ email: "[email protected]" });
await auth.auth.resetPassword({ token: "reset-token", password: "newpass" });SessionService
Manages sessions across devices:
// Get current session
const session = await auth.sessions.getSession();
// List all sessions (paginated)
const { sessions } = await auth.sessions.listSessions({ page: 1, limit: 20 });
// Revoke a specific session
await auth.sessions.revokeSession({ sessionId: "sess_abc123" });
// Revoke all other sessions
await auth.sessions.revokeAllSessions({ exceptCurrent: true });OrganizationService
Full organization management with RBAC:
// Create an organization
const org = await auth.organizations.create({
name: "Acme Corp",
slug: "acme",
});
// Invite a member
await auth.organizations.inviteMember({
organizationId: org.id,
email: "[email protected]",
role: "member",
});
// Update member role
await auth.organizations.updateMemberRole({
organizationId: org.id,
memberId: "member_123",
role: "admin",
});
// Leave an organization
await auth.organizations.leave({ organizationId: org.id });ApiKeyService
// Create an API key
const { key, apiKey } = await auth.apiKeys.create({
name: "Production key",
scopes: ["read", "write"],
expiresAt: "2025-12-31T00:00:00Z",
});
// Rotate an existing key
const { key: newKey } = await auth.apiKeys.rotate({ apiKeyId: apiKey.id });
// Get usage statistics
const usage = await auth.apiKeys.getUsage({ apiKeyId: apiKey.id });Error Handling
All service methods throw typed error classes on failure:
import {
AuthenticationError,
ConflictError,
ForbiddenError,
NetworkError,
NotFoundError,
RateLimitError,
ValidationError,
} from "@atzentis/auth-sdk";
try {
await auth.auth.signInWithEmail({ email, password });
} catch (error) {
if (error instanceof AuthenticationError) {
// 401 — invalid credentials
console.error("Invalid email or password");
} else if (error instanceof RateLimitError) {
// 429 — too many attempts, error.retryAfter has the wait time
console.error("Too many login attempts, try again later");
} else if (error instanceof NetworkError) {
// Network or timeout failure
console.error("Could not reach auth server");
} else if (error instanceof ValidationError) {
// 422 — request failed validation
console.error("Invalid request", error.details);
}
}Every error class extends AuthError and carries a typed code property from AuthErrorCode. Use error.code to map errors to localized user-facing messages.
HTTP Client Configuration
The underlying HttpClient supports interceptors, retry, and rate limiting:
import { AuthClient, createAuthInterceptor } from "@atzentis/auth-sdk";
const auth = new AuthClient({
baseUrl: "https://auth.atzentis.com",
timeout: 10_000,
retry: {
maxAttempts: 3,
baseDelay: 300,
maxDelay: 5_000,
},
rateLimit: {
maxRequests: 100,
windowMs: 60_000,
},
});Storage Adapters
Three built-in storage adapters for token persistence:
import {
CookieStorage,
LocalStorageAdapter,
MemoryStorage,
} from "@atzentis/auth-sdk";
// Browser (default for web)
const storage = new LocalStorageAdapter();
// Cookie-based (SSR-friendly)
const storage = new CookieStorage({ secure: true, sameSite: "lax" });
// In-memory (tests, server-side)
const storage = new MemoryStorage();Validation Schemas
The core package exports 15 Zod schemas used by all three packages:
import {
loginSchema,
signupSchema,
forgotPasswordSchema,
resetPasswordSchema,
changePasswordSchema,
changeEmailSchema,
updateNameSchema,
updateUsernameSchema,
inviteMemberSchema,
createOrganizationSchema,
} from "@atzentis/auth-sdk";TanStack Query Key Factory
import { authKeys } from "@atzentis/auth-sdk";
// Use in your TanStack Query hooks
const sessionKey = authKeys.session();
const userKey = authKeys.user();
const devicesKey = authKeys.devices();
const orgsKey = authKeys.organizations();TypeScript
The package is written in strict TypeScript and ships with full type definitions. No @types/* packages are needed. All request and response shapes are exported as named types:
import type {
User,
Session,
Organization,
Member,
ApiKey,
Device,
LoginEvent,
Passkey,
OAuthProvider,
OrganizationRole,
RiskLevel,
} from "@atzentis/auth-sdk";Framework Bindings
@atzentis/auth-react— React hooks, components, and auth flows@atzentis/auth-expo— React Native/Expo screens, biometrics, and secure storage
License
MIT — see LICENSE for details.
