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

@authticon/client

v0.0.0-beta46

Published

Official Authticon API client for Node.js

Downloads

4,639

Readme

@authticon/client

Oficjalny klient JavaScript/TypeScript dla Authticon — usługi uwierzytelniania. Biblioteka wspiera zarówno środowisko Node.js (SSR, API routes), jak i przeglądarkę (SPA, client-side).

Instalacja

npm install @authticon/client

Wymagania: Node.js >= 18

Dwa entry pointy

Biblioteka dostarcza dwa osobne moduły z odrębnymi implementacjami cookie i sesji:

| Import | Środowisko | Cookie adapter | | ------------------------------------------------ | ------------------ | -------------------------------------------------------------------------------------------------------------------------- | | @authticon/client lub @authticon/client/node | Node.js / SSR | Parsuje cookies z obiektu Request, zwraca CookieStorageAdapter z metodami applyToResponse(), stringifySetCookies() | | @authticon/client/browser | Przeglądarka / SPA | Używa document.cookie |

Szybki start

Node.js (np. Next.js, Express, Hono)

import { createAuthticon } from "@authticon/client/node";

const authticon = createAuthticon({
  projectId: "your-project-id",
});

// W handlerze HTTP:
async function handler(request: Request) {
  const { getUser, login, logout, cookies } = await authticon.session({
    request,
  });

  const user = getUser(); // SessionUser | null

  // cookies.applyToResponse(response) — ustawia Set-Cookie na odpowiedzi
}

Przeglądarka

import { createAuthticon } from "@authticon/client/browser";

const authticon = createAuthticon({
  projectId: "your-project-id",
});

const session = await authticon.session({});

const user = session.getUser();
await session.login({ email: "[email protected]", password: "secret" });

Konfiguracja

type AuthticonOptions = {
  projectId: string; // ID projektu w Authticon (wymagane)
  baseUrl?: string; // URL API (domyślnie: "https://authticon.com")
  jwksUrl?: string; // URL do JWKS (domyślnie: {baseUrl}/.well-known/jwks.json)
  jwksCacheTtlMs?: number; // TTL cache kluczy JWKS (domyślnie: 1h)
  cache?: CacheAdapter; // Zewnętrzny adapter cache (domyślnie: in-memory)
  logger?: Logger; // Instancja pino logger
};

Session (API stanowe)

session() to główny sposób interakcji z biblioteką. Tworzy stanowy obiekt sesji, który:

  1. Przy tworzeniu automatycznie odczytuje tokeny z cookies
  2. Weryfikuje access token za pomocą JWKS
  3. Jeśli token wygasł — automatycznie odświeża go za pomocą refresh tokena
  4. Cache'uje obiekt SessionUser w pamięci na czas życia sesji
  5. Operacje takie jak login(), logout(), createGuest() automatycznie aktualizują wewnętrzny stan sesji i zapisują nowe tokeny w cookies

Tworzenie sesji

Node.js — z obiektu Request

const session = await authticon.session({ request });
// session.cookies — CookieStorageAdapter z metodami applyToResponse(), stringifySetCookies()

Node.js — z własnym CookieAdapter

const session = await authticon.session({ cookies: myCookieAdapter });

Przeglądarka

const session = await authticon.session({});
// Automatycznie używa document.cookie

Opcjonalnie można przekazać tokenStorage do nadpisania nazw cookies i ich parametrów:

const session = await authticon.session({
  request,
  tokenStorage: {
    accessTokenName: "my_access_token",
    refreshTokenName: "my_refresh_token",
    secure: true,
    sameSite: "Strict",
    domain: ".example.com",
  },
});

Metody sesji

Autentykacja

| Metoda | Opis | | ---------------------------- | ------------------------------------------------------------------------- | | login(params) | Logowanie (email/password). Zwraca SessionUser. | | register(params) | Rejestracja. Zwraca dane rejestracji (tokeny nie są jeszcze zapisywane). | | loginByMagicLink(params) | Loguje użytkownika przez magic link (z deviceId). Zwraca SessionUser. | | forgotPassword(params) | Inicjuje reset hasła. | | verifyEmail(params) | Weryfikuje email. | | createGuest(params) | Tworzy użytkownika-gościa. Zwraca SessionUser. | | acceptInvitation(params) | Akceptuje zaproszenie. Zwraca SessionUser. | | resendConfirmation(params) | Ponownie wysyła email potwierdzający. | | logout() | Wylogowuje (server-side + czyści cookies). | | refresh() | Wymusza odświeżenie tokenów. |

Stan użytkownika

| Metoda | Opis | | --------------------- | --------------------------------------------------------------------------------- | | getUser() | Zwraca SessionUser \| null. | | requireUser() | Zwraca SessionUser lub rzuca AuthticonError. | | isLoggedIn() | Zwraca boolean — czy istnieje access token. | | isLoggedInByAdmin() | Zwraca boolean — czy istnieje admin refresh token (logowanie jako użytkownik). | | getFirstChallenge() | Zwraca pierwszy challenge (np. "verifyTwoFa", "setPassword") lub undefined. |

Profil użytkownika

| Metoda | Opis | | ------------------ | -------------------------------------------- | | getMe() | Pobiera dane zalogowanego użytkownika z API. | | updateMe(params) | Aktualizuje dane zalogowanego użytkownika. |

Zarządzanie kontem

| Metoda | Opis | | ------------------------ | ---------------------------------- | | changeEmail(params) | Zmiana emaila. | | changePassword(params) | Zmiana hasła. | | setPassword(params) | Ustawienie hasła (np. po resecie). | | changePhone(params) | Zmiana numeru telefonu. | | verifyPhone(params) | Weryfikacja numeru telefonu. |

Dwuskładnikowe uwierzytelnianie (2FA)

| Metoda | Opis | | ---------------------------------- | ------------------------------------------------------------- | | getTwoFaSecret() | Pobiera sekret 2FA (do wyświetlenia QR code). | | enableTwoFa(params) | Włącza 2FA. | | disableTwoFa(params) | Wyłącza 2FA. | | sendTwoFaCode(params) | Wysyła kod 2FA. | | verifyTwoFaCode(code, remember?) | Weryfikuje kod 2FA i aktualizuje sesję. Zwraca SessionUser. |

Zaproszenia

| Metoda | Opis | | -------------------------- | ------------------- | | createInvitation(params) | Tworzy zaproszenie. | | deleteInvitation(params) | Usuwa zaproszenie. |

Tokeny

Obiekt session.tokens daje bezpośredni dostęp do tokenów:

session.tokens.getAccessToken(); // string | null
session.tokens.getRefreshToken(); // string | null
session.tokens.verify(); // weryfikuje aktualny access token
session.tokens.verify(customToken); // weryfikuje dowolny token
session.tokens.clear(); // czyści tokeny z cookies i resetuje stan sesji

SessionUser

type SessionUser<Payload> = {
  id: string; // ID użytkownika
  sessionId: string; // ID sesji
  projectId: string; // ID projektu
  role: "guest" | "user";
  isGuest: boolean;
  challenges: Challenge[]; // np. ["verifyTwoFa", "setPassword"]
  payload: Payload; // custom claims z tokena
  raw: AccessTokenPayload; // surowy payload JWT
};

Low-level API

Oprócz stanowej sesji, createAuthticon() udostępnia niskopoziomowe klienty API, które nie zarządzają stanem ani cookies.

authticon.auth() — klient publiczny (bez autoryzacji)

Bezstanowy klient do endpointów niewymagających tokenu:

const auth = authticon.auth();

await auth.login({ email: "[email protected]", password: "secret" });
await auth.register({ email: "[email protected]", password: "secret" });
await auth.forgotPassword({ email: "[email protected]" });
await auth.loginByMagicLink({ token: "..." });
await auth.verifyEmail({ token: "..." });
await auth.createGuestUser({ ... });
await auth.acceptInvitation({ token: "...", password: "..." });
await auth.resendConfirmation({ email: "..." });

Uwaga: Te metody zwracają surowe dane z API (np. tokeny). Zarządzanie cookies/stanem leży po stronie wywołującego.

authticon.admin(options) — klient administracyjny (tylko Node.js)

Wymaga klucza API. Służy do operacji administracyjnych:

const admin = authticon.admin({ apiKey: "your-api-key" });

await admin.listUsers({ page: 1 });
await admin.createUser({ email: "[email protected]", password: "..." });
await admin.getUser("user-id");
await admin.updateUser("user-id", { ... });
await admin.deleteUser("user-id");
await admin.loginAs({ userId: "user-id" });
await admin.sendMagicLink({ email: "[email protected]", url: "https://example.com/login" });


// Role
await admin.createUserRole("user-id", { ... });
await admin.listUserRoles("user-id");
await admin.updateUserRole("user-id", "role-id", { ... });
await admin.deleteUserRole("user-id", "role-id");

// Magic link
await admin.sendMagicLink({ email: "[email protected]" });

// SMS
await admin.sendSmsCode("user-id");
await admin.verifySms("user-id", { code: "123456" });

// Dostępność
await admin.isEmailAvailable("[email protected]");  // boolean
await admin.isPhoneAvailable("+48123456789");       // boolean

// Test email
await admin.testEmail({ ... });

authticon.tokens (tylko Node.js)

Bezpośredni dostęp do weryfikatora tokenów na poziomie instancji:

const payload = await authticon.tokens.verify(accessToken);
authticon.tokens.clearKeyCache(); // czyści cache kluczy JWKS

Cookie adaptery

Node.js — createNodeCookieStorageAdapter

Parsuje cookies z Request, buforuje zmiany i pozwala je aplikować do Response:

import { createNodeCookieStorageAdapter } from "@authticon/client/node";

const cookies = createNodeCookieStorageAdapter(request);

// Po operacjach sesji:
cookies.applyToResponse(response);
// lub:
const setCookieHeaders = cookies.stringifySetCookies(); // string[]

Przeglądarka — createBrowserCookieAdapter

Operuje bezpośrednio na document.cookie:

import { createBrowserCookieAdapter } from "@authticon/client/browser";

const cookies = createBrowserCookieAdapter();

Własny adapter

Możesz zaimplementować interfejs CookieAdapter:

interface CookieAdapter {
  get(name: string): string | null;
  set(name: string, value: string, options: CookieSetOptions): void;
  remove(name: string, options: CookieRemoveOptions): void;
}

Token storage — konfiguracja cookies

type TokenStorageOptions = {
  accessTokenName?: string; // domyślnie: "access_token"
  refreshTokenName?: string; // domyślnie: "refresh_token"
  deviceIdName?: string; // domyślnie: "device_id"
  adminRefreshTokenName?: string; // domyślnie: "admin_refresh_token"
  path?: string; // domyślnie: "/"
  domain?: string;
  secure?: boolean; // domyślnie: true
  sameSite?: "Strict" | "Lax" | "None"; // domyślnie: "Lax"
  accessTokenMaxAge?: number; // domyślnie: 900 (15 min)
  refreshTokenMaxAge?: number; // domyślnie: 2592000 (30 dni)
};

Obsługa błędów

Biblioteka definiuje dedykowaną hierarchię błędów:

import {
  AuthticonError,
  AuthticonApiError,
  AuthticonTokenError,
  isAuthticonError,
  isAuthticonApiError,
  isAuthticonTokenError,
} from "@authticon/client";

| Klasa | Opis | | --------------------- | -------------------------------------------------------------- | | AuthticonError | Bazowy błąd (np. brak tokenu, użytkownik niezalogowany) | | AuthticonApiError | Błąd odpowiedzi API (zawiera statusCode i response) | | AuthticonTokenError | Błąd weryfikacji JWT (zawiera code i oryginalny joseError) |

try {
  const user = session.requireUser();
} catch (error) {
  if (isAuthticonApiError(error)) {
    console.log(error.statusCode); // np. 401
  }
  if (isAuthticonTokenError(error, "ERR_JWT_EXPIRED")) {
    // Token wygasł
  }
}

Typowanie custom payloadu

Biblioteka wspiera generyczne typowanie payloadu JWT:

type MyPayload = {
  organizationId: string;
  permissions: string[];
};

const authticon = createAuthticon<MyPayload>({
  projectId: "...",
});

const session = await authticon.session({ request });
const user = session.getUser();

user?.payload.organizationId; // string
user?.payload.permissions; // string[]

Licencja

MIT