@originals/auth
v4.0.0
Published
Turnkey-based authentication for the Originals Protocol
Downloads
1,020
Maintainers
Readme
@originals/auth
Turnkey-based authentication for the Originals Protocol — server middleware and client helpers for email-OTP auth flows backed by Turnkey key management.
Installation
npm install @originals/auth
# or
bun add @originals/authRequires Node.js >=20.10.0 (or Bun). Published as ESM. express is an optional peer dependency for the server middleware.
Usage
The supported flow is server-driven email OTP: your server holds the Turnkey API keys and exposes send/verify endpoints; the client calls those endpoints.
Server-side — create the Turnkey client and handle the OTP endpoints:
import {
createTurnkeyClient,
initiateEmailAuth,
verifyEmailAuth,
createAuthMiddleware,
} from '@originals/auth/server';
// In your send-OTP endpoint: initiateEmailAuth(...)
// In your verify-OTP endpoint: verifyEmailAuth(...)
// Protect routes with createAuthMiddleware(...)Client-side (pure functions, no React) — call your server's OTP endpoints:
import { sendOtp, verifyOtp } from '@originals/auth/client';
const { sessionId } = await sendOtp('[email protected]');
// ...user enters the code from their inbox...
const { verified } = await verifyOtp(sessionId, '123456');Types:
import type { AuthUser, TokenPayload, TurnkeyWallet } from '@originals/auth/types';Import client utilities from @originals/auth/client (not the package root) to avoid pulling server code into browser bundles. Turnkey API keys are server-only: initialize Turnkey with createTurnkeyClient from @originals/auth/server — there is no client-side Turnkey initializer.
Authentication middleware
Both createAuthMiddleware and createOptionalAuthMiddleware accept issuer
and audience options. Set them to the same values used by signToken:
import { signToken, createAuthMiddleware, createOptionalAuthMiddleware } from '@originals/auth/server';
const claims = { issuer: 'my-app', audience: 'my-app-api' };
const token = signToken(user.turnkeySubOrgId, user.email, undefined, {
secret: process.env.JWT_SECRET,
...claims,
});
const options = {
jwtSecret: process.env.JWT_SECRET,
...claims,
getUserByTurnkeyId: async (id: string) => db.users.findByTurnkeyId(id),
};
const requireUser = createAuthMiddleware(options);
const optionalUser = createOptionalAuthMiddleware(options);Omitted options preserve the defaults: issuer originals-auth, audience
originals-api, and cookie name auth_token. Configure cookie parsing before
these middleware functions. Issuer/audience mismatches, invalid tokens, and
expired tokens produce a 401 with required authentication and continue without
populating req.user with optional authentication. Optional authentication also
continues anonymously when the cookie or matching user is absent.
JWT configuration errors and user lookup failures reach Express error handling
through next(error); optional authentication does not hide backend failures as
anonymous traffic. Successful authentication populates req.user and calls
next() once. Errors thrown by the consumer's next callback propagate without
calling it again.
Security notes
Rate-limit the send-OTP endpoint. initiateEmailAuth sends an email on every call. The endpoint exposing it MUST enforce rate limits (per IP and per target email) — Turnkey's per-user throttle does not protect arbitrary recipient addresses from an attacker who varies the email. Turnkey sub-organizations and wallets are only provisioned after the OTP is verified, so unverified requests create no billable resources, but unthrottled requests still spam arbitrary inboxes.
Keep the verification-token key in the browser. The Turnkey verification token returned by verifyEmailAuth is bound to a P-256 key. Generate that keypair in the browser (generateP256KeyPair from @turnkey/crypto) and pass its public key through your verify endpoint into verifyEmailAuth's options.publicKey, so the private key never transits an HTTP response:
// Browser
import { generateP256KeyPair } from '@turnkey/crypto';
import { verifyOtp } from '@originals/auth/client';
const keyPair = generateP256KeyPair(); // private key stays here
const result = await verifyOtp(sessionId, code, undefined, {
publicKey: keyPair.publicKey,
});
// Server verify endpoint
const result = await verifyEmailAuth(sessionId, code, turnkeyClient, storage, {
publicKey: req.body.publicKey, // bind the token to the client's key
});If no publicKey is supplied, verifyEmailAuth falls back to generating the keypair server-side and returns the private key in its result — acceptable for pure server-to-server flows only.
OTP attempt limiting. A verification session is destroyed after 5 failed attempts; the user must request a new code.
The session cookie defaults to Secure. getAuthCookieConfig/getClearAuthCookieConfig set secure: true unless you pass { secure: false } explicitly — this does not depend on NODE_ENV, since not every deployment platform sets it to exactly "production". Only opt out for local plain-HTTP development:
// Local HTTP development only — never in a deployed environment
const cookie = getAuthCookieConfig(token, { secure: false });
// The logout/clear config must opt out the same way, or the clear cookie
// stays Secure and a plain-HTTP browser will ignore it, leaving the
// session looking active.
const clearCookie = getClearAuthCookieConfig(undefined, { secure: false });Documentation
- Originals SDK repository — source, issues, and protocol documentation
- @originals/sdk on npm — the core SDK this package builds on
License
MIT © Aviary Tech
