New:Socket for Asana Is Now Available.Learn more
Get Started

infinityauth

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package was removed
Sorry, it seems this package was removed from the registry

infinityauth

A comprehensive, secure, and developer-friendly authentication package

latest
npmnpm
Version
1.1.1
Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

InfinityAuth

A comprehensive, secure, and developer-friendly authentication package that rivals Auth0, Okta, and Clerk. Built with modern security practices and designed for seamless integration across all platforms.

System Architecture

InfinityAuth System Architecture

Note: This diagram shows the complete system architecture including client SDKs, backend services, and data flows.

Installation

npm install infinityauth

After install, you'll see a notice: "package author: ashutosh0x".

Quick Start

import { createAuthClient } from 'infinityauth';

const auth = createAuthClient({
  baseURL: 'http://localhost:4000',
  clientId: 'your-client-id',
});

// Signup
await auth.signup('user@example.com', 'StrongP@ssw0rd!');

// Login
const { accessToken, refreshToken } = await auth.login('user@example.com', 'StrongP@ssw0rd!');

// Current user
const me = await auth.getUser();

// Refresh
const newTokens = await auth.refreshToken();

// Logout
await auth.logout();

Role helper

const isAdmin = auth.hasRole?.('admin');

Offline-first profile

// If offline, getUser will return last cached profile
const me = await auth.getUser();

API

createAuthClient(config) returns an AuthClient

  • config.baseURL: string (required) – Base URL of InfinityAuth API
  • config.clientId: string (required)
  • config.clientSecret: string (optional)
  • config.storage: 'memory' | 'localStorage' (optional)

AuthClient methods

  • signup(email, password){ accessToken, refreshToken, expiresIn }
  • login(email, password){ accessToken, refreshToken, expiresIn }
  • getUser(){ id, email, role } | null
  • refreshToken(){ accessToken, refreshToken, expiresIn }
  • logout()void

Configuration

createAuthClient({
  baseURL: 'http://localhost:4000',
  clientId: 'web',
  clientSecret?: 'optional',
  storage?: 'memory' | 'localStorage' | 'indexeddb',
  debug?: true,
  fetchAdapter?: (input, init) => fetch(input, init),
});
  • debug: logs requests and token refresh attempts
  • fetchAdapter: plug Axios/fetch polyfills
  • storage: memory or browser storage (localStorage is encrypted best-effort)

Events / Hooks

auth.on('login', ({ email }) => {/* ... */});
auth.on('tokenRefresh', () => {/* ... */});
auth.on('logout', () => {/* ... */});

Auto Refresh & Silent Login

Client retries once on 401 by calling /refresh-token silently.

getUser() caches profile; when offline it returns the last cached value.

MFA & Passwordless (optional)

Server endpoints (present in dev server):

  • POST /mfa/totp/enroll/start{ otpauthUrl, secret }
  • POST /mfa/totp/verify { code }{ ok }
  • POST /mfa/otp/send { channel: 'email'|'sms', to? }{ ok }
  • POST /mfa/otp/verify { code }{ ok, accessToken?, refreshToken? }
  • POST /passwordless/start { email }{ ok }
  • POST /passwordless/verify { token } → tokens

Client helpers (stubs): totpEnrollStart, totpVerify, otpSend, otpVerify, passwordlessStart, passwordlessVerify.

PKCE (OAuth2/OIDC)

import { createAuthClient } from 'infinityauth';
const auth = createAuthClient({ baseURL, clientId });
const { verifier, challenge } = await auth.pkceStart?.();

// redirect user to your /authorize with code_challenge & method=S256
// after redirect back with ?code=...
await auth.authorizeWithCode?.({ 
  code, 
  redirectUri: window.location.origin + '/callback', 
  codeVerifier: verifier 
});

Social Logins (OIDC providers)

// After redirect back, exchange provider code at your server
await fetch('/social/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ 
    tokenEndpoint: 'https://accounts.google.com/o/oauth2/token', 
    code, 
    clientId, 
    clientSecret, 
    redirectUri 
  })
});

Device Code Flow

// Start device code
const start = await fetch('/oauth/device/code', { 
  method: 'POST', 
  headers: { 'Content-Type': 'application/json' }, 
  body: JSON.stringify({ client_id: 'myapp' }) 
}).then(r => r.json());

// Show start.user_code to user, poll tokens:
const poll = await fetch('/oauth/token/device', { 
  method: 'POST', 
  headers: { 'Content-Type': 'application/json' }, 
  body: JSON.stringify({ 
    device_code: start.device_code, 
    client_id: 'myapp' 
  }) 
});

WebAuthn (Passkeys) – Dev Stub

await auth.webauthnRegister('user@example.com');
const result = await auth.webauthnLogin('user@example.com');

Notes

  • Client stores tokens in memory by default. For browser persistence, pass storage: 'localStorage'.
  • Ensure your server is configured for CORS and uses RS256 JWTs with a JWKS endpoint.
  • Never commit private keys; use environment variables in production.

Server Security Model (InfinityAuth dev server)

  • JWT: RS256 with /.well-known/jwks.json exposure
  • Refresh tokens: hashed (SHA-256), expiresAt enforced, rotation on refresh, reuse detection (revokes all tokens on reuse)
  • Rate limiting: express-rate-limit; optional Redis store via REDIS_URL
  • Argon2id password hashing

Environment (server):

  • JWT_PRIVATE_KEY, JWT_PUBLIC_KEY, JWT_KID (optional; otherwise dev keys)
  • REDIS_URL (optional for distributed rate limits)
  • CORS_ORIGINS

License

MIT © ashutosh0x

Provider/OIDC Compatibility

InfinityAuth client speaks simple REST by default. For OIDC providers (Auth0, Okta, Keycloak), point baseURL to your compat layer or expose matching endpoints:

  • POST /signup { email, password }
  • POST /login { email, password }
  • GET /me (bearer auth)
  • POST /refresh-token { refreshToken }
  • POST /logout (bearer auth)

Optional Advanced:

  • POST /mfa/totp/enroll/start
  • POST /mfa/totp/verify { code }
  • POST /mfa/otp/send { channel: 'email'|'sms', to? }
  • POST /mfa/otp/verify { code }
  • POST /passwordless/start { email }
  • POST /passwordless/verify { token }

Events & Debugging

auth.on('login', ({ email }) => console.log('logged in', email));
auth.on('tokenRefresh', () => console.log('token refreshed'));
auth.on('logout', () => console.log('logged out'));

const auth = createAuthClient({
  baseURL,
  clientId,
  debug: true,
});

Framework Examples

React

import { useEffect, useState } from 'react';
import { createAuthClient } from 'infinityauth';

const auth = createAuthClient({ baseURL: 'http://localhost:4000', clientId: 'web' });

export function App() {
  const [me, setMe] = useState(null);
  useEffect(() => { auth.getUser().then(setMe); }, []);
  
  return (
    <div>
      {me ? (
        <pre>{JSON.stringify(me, null, 2)}</pre>
      ) : (
        <button onClick={async () => {
          await auth.login('u@example.com', 'P@ssw0rd1');
          setMe(await auth.getUser());
        }}>
          Login
        </button>
      )}
    </div>
  );
}

Node/Express

const { createAuthClient } = require('infinityauth');
const auth = createAuthClient({ baseURL: 'http://localhost:4000', clientId: 'server' });

async function demo() {
  await auth.signup('u@example.com', 'P@ssw0rd1');
  const me = await auth.getUser();
  console.log(me);
}
demo();

Troubleshooting

  • CORS errors: ensure CORS_ORIGINS includes your app origin and that credentials: true is set when needed.
  • 401 after some time: access tokens expire by design; the client auto-refreshes once on 401. Verify /refresh-token responds and your refresh token is valid (not revoked/expired).
  • JWT invalid: confirm server is using RS256 and your consumer verifies with the JWKS /.well-known/jwks.json. Issuer must be infinity-auth, audience infinity-auth-users.
  • Clock skew: if tokens appear "expired" immediately, ensure server and client clocks are in sync.

Cookbook

SSR (Next.js) – validate on API route

// pages/api/me.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const hdr = req.headers.authorization || '';
  if (!hdr.startsWith('Bearer ')) return res.status(401).end();
  
  // Forward to InfinityAuth server
  const r = await fetch(process.env.AUTH_URL + '/me', { 
    headers: { Authorization: hdr } 
  });
  if (!r.ok) return res.status(401).end();
  return res.status(200).json(await r.json());
}

GraphQL – pass auth header

const at = await auth.getUser()
  .then(() => auth.refreshToken())
  .then(t => t.accessToken);
await fetch('/graphql', { 
  method: 'POST', 
  headers: { 'Authorization': `Bearer ${at}` } 
});

WebSockets – attach token

const at = await auth.refreshToken().then(t => t.accessToken);
const ws = new WebSocket(`wss://example/ws?token=${at}`);

Architecture (High-Level)

  • Signup/Login → issue RS256 JWT (15m) and hashed refresh token (30d)
  • Client stores tokens (encrypted localStorage best-effort) and caches profile
  • API calls use bearer; on 401, client silently refreshes once
  • Refresh rotation + reuse detection; if reuse detected, revoke all tokens for user
  • PKCE flow supported via /authorize and /oauth/token

Roadmap

  • Full OAuth2/OIDC surface (PKCE, Device Code)
  • WebAuthn MFA/passwordless
  • IndexedDB storage option
  • API Playground and examples repo

Keywords

auth, oauth, oidc, jwt, infinityauth, authentication

Keywords

auth

FAQs

Package last updated on 14 Aug 2025

Related posts