auth README

The project's README from github.com/yielded-dev/auth. As one markdown file: README.md.

Yielded Auth

npm CI MIT license

Documentation · Getting started · yielded.dev

Composable authentication, sessions, and identity workflows for Effect.

Define your contract with Schema, supply infrastructure with Layers, and call auth alongside your other Effects. The same contract connects your server to an Effect HttpClient service and Effect Atom queries and mutations.

Your application owns its accounts, identifiers, and authorization policy. Use managed auth tables, map an existing SQL schema, or implement storage services against another backend. The auth API stays the same when you change storage. Core has only Effect as a runtime peer; companion packages supply database, cryptography, and protocol adapters.

Start with Auth in an Effect application or compare database and backend choices. The four account apps show managed Drizzle, custom Drizzle, Effect SQL, and non-SQL persistence.

Install the beta release with Effect:

bun add @yielded/auth@beta effect

Prefer named namespace imports from @yielded/auth. Direct module paths such as @yielded/auth/AuthContract remain available; see the import guide.

One API, server and client

Define the shared contract in packages/domain/auth-contract.ts:

import { Schema } from "effect";
import { AuthContract } from "@yielded/auth";

export const AuthApi = AuthContract.make("app/Auth", {
  claims: Schema.Struct({ displayName: Schema.String }),
  actions: (sessions) => ({ signIn: AuthContract.passwordSignIn(sessions) }),
});

Bind the server implementation and mount its HTTP routes:

import { Auth, Http, Password, Sessions } from "@yielded/auth";

import { AuthApi } from "@app/domain/auth-contract";

export const AppAuth = Auth.make(AuthApi, {
  sessions: Sessions.stateful(),
  strategies: { password: Password.make() },
  defaultStrategy: "password",
});

export const AuthRoutes = Http.layer(AppAuth, { origin: "https://app.example.com" });

Supply your persistence and account Layers to AuthRoutes, then merge it with your router. For application routes that call auth, use the middleware shown in the router composition. Inside an existing Effect handler, call the service directly:

const auth = yield* AppAuth;
const result = yield* auth.signIn({ email, password });

The request context supplies credentials and cookie delivery. auth.getSession(), auth.requireSession(), and auth.signOut() use the same boundary. An Authenticated sign-in result contains a session with typed claims.displayName.

Create the client and its atoms from the same contract:

import { Atom as AuthAtom, Client } from "@yielded/auth";

import { AuthApi } from "@app/domain/auth-contract";

export const AppClient = Client.make(AuthApi, { baseUrl: "https://app.example.com" });
export const auth = AuthAtom.make(AppClient);

Use auth.session, auth.signIn, and auth.signOut with ordinary @effect/atom-react hooks. Auth mutations refresh auth queries automatically; React renders and dispatches. Compose your own queries through the same client:

import { Effect } from "effect";

import { AppClient, auth } from "./auth-client";

export const memberName = auth.runtime.atom(
  Effect.gen(function* () {
    const client = yield* AppClient;
    const session = yield* client.auth.getSession();

    return session?.claims.displayName ?? null;
  }),
);

Fetch is configured by default. To customize transport, compose AppClient.layer with your HttpClient Layer and pass { layer: ClientLive } to AuthAtom.make. See the client guide for React, shared invalidation, and standalone Effect calls.

Add passwords, passkeys, email or phone codes, two-factor authentication, and OAuth through strategies and their required Layers. OAuth can also retain encrypted provider grants for calling APIs after sign-in.

Start with the documentation and consumer examples. The public library lives in packages/auth; examples are leaf workspaces.

Development

Install Bun and Vite+, then run:

vp install
vp run patch:tsgo
vp run ready

The toolchain guide covers release setup and contributor rules. Shared versions live in the root catalog. Formatting, linting, strict TypeScript, package exports, dependency purity, tests, and builds use Vite+.

License

MIT

auth (yielded-dev/auth)

Searching Database…

239 ·GitHub
Что это?Библиотека компонуемых сценариев аутентификации, сессий и работы с личностью, созданная специально для экосистемы Effect. Вы описываете свой auth-контракт через Schema, а инфраструктуру подключаете через Effect Layers.
Это самостоятельный фреймворк или библиотека, которую я подключаю к существующему приложению Effect?Это библиотека, а не фреймворк: публичный пакет лежит в packages/auth, его сервис вы вызываете рядом с остальными вашими эффектами Effect, а примеры приложений вынесены в отдельные конечные рабочие пространства (leaf workspaces).
Как добавить это в мой проект Effect?Установите бета-версию вместе с Effect, используйте именованные namespace-импорты из @yielded/auth, определите общий контракт (например, packages/domain/auth-contract.ts), привяжите серверную реализацию и смонтируйте её HTTP-маршруты, затем создайте клиент и его атомы из того же контракта.
Что нужно кроме самого Effect?У ядра единственная peer-зависимость времени выполнения — Effect; отдельные сопутствующие пакеты предоставляют адаптеры баз данных, криптографии и протоколов в зависимости от того, какое хранилище и какие стратегии аутентификации вы выберете. Для контрибуции и разработки нужны Bun и Vite+.
Готово ли это к использованию в продакшене?Сейчас проект распространяется как бета-релиз, так что будьте готовы, что поверхность API ещё будет меняться до выхода стабильной версии.
Эта библиотека привязывает меня к конкретной базе данных?Нет. Можно использовать управляемые auth-таблицы, отобразить её на существующую SQL-схему или реализовать сервисы хранения под совершенно другой бэкенд — auth-API в любом случае останется тем же.
Какие стратегии аутентификации поддерживаются из коробки?Пароли, пасскеи, коды по электронной почте или телефону, двухфакторная аутентификация и OAuth — каждый вариант добавляется через стратегии и требуемые ими Layers. OAuth также может сохранять зашифрованные гранты провайдера для вызова API после входа.
Можно использовать это с React?Да. Клиент предоставляет атомы, которые вы используете с обычными хуками @effect/atom-react (auth.session, auth.signIn, auth.signOut), а мутации аутентификации автоматически обновляют связанные запросы.
Для чего нужны примеры приложений?Четыре входящие в комплект приложения аккаунтов демонстрируют варианты хранения: управляемый Drizzle, собственный Drizzle, Effect SQL и хранилище без SQL.
Как работает HTTP-транспорт?По умолчанию настроен Fetch; чтобы настроить его по-своему, соберите собственный слой HttpClient с помощью AppClient.layer и передайте его как клиентский Layer при создании auth-клиента.
Size
5.9 MB
Stars
239
Updated
CommitOct 19
Age
1mo
Commits · 90 Days