npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@intelicity/gates-auth

v0.1.11

Published

Framework-agnostic AWS Cognito authentication library with multi-tenant support

Readme

@intelicity/gates-auth

Biblioteca de autenticação AWS Cognito — framework-agnostic, multi-tenant, com PKCE nativo e suporte a popup e redirect.

Instalação

npm install @intelicity/gates-auth
# ou
pnpm add @intelicity/gates-auth

React adapter incluído no mesmo pacote via @intelicity/gates-auth/react. Requer React >= 18 como peer dependency.


Uso básico

import { CognitoAuth } from '@intelicity/gates-auth';

const auth = new CognitoAuth({
  domain:      'auth.empresa.com',
  clientId:    'seu-client-id',
  redirectUri: 'https://app.com/callback',
});

await auth.signIn();

Adapter React

// src/auth.ts
import { CognitoAuth } from '@intelicity/gates-auth';

export const auth = new CognitoAuth({
  domain:      'auth.empresa.com',
  clientId:    'seu-client-id',
  redirectUri: 'https://app.com',
});
// src/main.tsx
import { AuthProvider } from '@intelicity/gates-auth/react';
import { auth } from './auth';

createRoot(document.getElementById('root')!).render(
  <AuthProvider auth={auth} handleCallback>
    <App />
  </AuthProvider>
);
// src/components/Navbar.tsx
import { useAuth } from '@intelicity/gates-auth/react';

function Navbar() {
  const { isAuthenticated, isLoading, signIn, signOut } = useAuth();

  if (isLoading) return <Spinner />;

  return isAuthenticated
    ? <button onClick={() => signOut()}>Sair</button>
    : <button onClick={() => signIn()}>Entrar</button>;
}

Configuração

| Parâmetro | Tipo | Obrigatório | Padrão | Descrição | |-----------|------|:-----------:|--------|-----------| | domain | string | ✅ | — | Domínio do Cognito Hosted UI (sem https://) | | clientId | string | ✅ | — | App Client ID no User Pool | | redirectUri | string | ✅ | — | URL de callback registrada no Cognito | | strategy | 'redirect' \| 'popup' | — | 'redirect' | Estratégia de autenticação | | loginMethod | 'directLogin' \| 'federation' | — | 'directLogin' | Endpoint de login | | storage | 'localStorage' \| 'sessionStorage' \| 'memory' | — | 'localStorage' | Onde persistir a sessão | | autoRefresh | boolean | — | true | Renova tokens automaticamente antes de expirar | | refreshThresholdSeconds | number | — | 300 | Segundos antes do vencimento para renovar |


Fluxo redirect

// Iniciar login
await auth.signIn(); // navega para o Cognito

// Na página de callback
if (new URLSearchParams(location.search).has('code')) {
  await auth.handleCallback();
  window.history.replaceState({}, '', location.pathname);
}

Fluxo popup

const auth = new CognitoAuth({ ..., strategy: 'popup' });

try {
  await auth.signIn(); // aguarda o login na janela popup
} catch (err) {
  if (err.code === 'popup_closed') { /* usuário fechou */ }
}

Lendo o estado

// Snapshot pontual
const { status, user, tokens, error } = auth.getState();

// Reativo
const unsubscribe = auth.on('stateChange', ({ state }) => {
  console.log(state.status); // 'idle' | 'pending' | 'authenticated' | 'error' | 'unauthenticated'
});
unsubscribe(); // cancelar

Chamadas autenticadas

// Retorna token válido, renovando automaticamente se necessário
const token = await auth.getValidAccessToken();

await fetch('https://api.empresa.com/dados', {
  headers: { Authorization: `Bearer ${token}` },
});

Sign out

await auth.signOut();                          // logout simples
await auth.signOut({ global: true });          // revoga refresh token
await auth.signOut({ strategy: 'popup' });     // sem navegar a página principal

Expiração de sessão

Quando o refresh token expira ou é revogado no servidor, qualquer tentativa de renovação (refreshSession(), getValidAccessToken() ou o auto-refresh em background) limpa automaticamente a sessão local e emite o evento signOut:

auth.on('signOut', () => {
  // Disparado também quando o refresh token é inválido — redirecione para o login
  auth.signIn();
});

O erro lançado tem code: 'token_refresh_failed'. Em chamadas explícitas a getValidAccessToken() o erro propaga normalmente para o chamador; no auto-refresh ele é capturado internamente.


Eventos

auth.on('signIn',         ({ user, tokens }) => { });
auth.on('signOut',        ()                => { });
auth.on('tokenRefreshed', ({ tokens })      => { });
auth.on('error',          ({ error })       => { });
auth.on('stateChange',    ({ state })       => { });
auth.on('any',            (payload)         => { }); // todos os eventos

Tipos exportados

import type {
  CognitoAuthConfig,
  AuthState,
  AuthStatus,
  AuthUser,
  AuthTokens,
  AuthError,
  AuthEventType,
  AuthEventPayloads,
  AuthEventListener,
  SignInOptions,
  SignOutOptions,
  Strategy,
  StorageType,
  LoginMethod,
} from '@intelicity/gates-auth';

Múltiplas instâncias

Cada instância tem sua própria store isolada — ideal para microfrontends com múltiplos App Clients no mesmo User Pool.

const authAppA = new CognitoAuth({ clientId: 'client-app-a', ... });
const authAppB = new CognitoAuth({ clientId: 'client-app-b', ... });

Uso via CDN (projetos legados)

Para projetos sem bundler, a biblioteca está disponível como bundle IIFE via jsDelivr:

<!-- Sempre a versão mais recente -->
<script src="https://unpkg.com/@intelicity/gates-auth/dist/cdn/gates-auth.global.js"></script>

<!-- Versão fixada (recomendado em produção) -->
<script src="https://unpkg.com/@intelicity/[email protected]/dist/cdn/gates-auth.global.js"></script>

Após carregar o script, GatesAuth fica disponível globalmente:

<script>
  var auth = new GatesAuth.CognitoAuth({
    domain:      'auth.empresa.com',
    clientId:    'seu-client-id',
    redirectUri: window.location.origin,
  });

  // Iniciar login
  document.getElementById('btn-login').addEventListener('click', function () {
    auth.signIn();
  });

  // Processar callback (fluxo redirect)
  if (new URLSearchParams(window.location.search).has('code')) {
    auth.handleCallback().then(function () {
      window.history.replaceState({}, '', window.location.pathname);
    });
  }

  // Reagir a mudanças de estado
  auth.on('stateChange', function (payload) {
    var state = payload.state;
    if (state.status === 'authenticated') {
      console.log('Usuário:', state.user.name);
    }
  });
</script>

O adapter React não está disponível via CDN — é exclusivo para projetos com bundler.


Requisitos

  • Ambiente com suporte a Web Crypto API (crypto.subtle) — todos os browsers modernos e Node.js >= 15
  • PKCE sempre ativo — gerado internamente, invisível para o consumidor
  • React adapter requer React >= 18