On this page
  1. Install
  2. Compose sessions and credentials
  3. Session configuration
  4. Session security and maintenance
  5. Dual-inbox email approval
  6. Transaction-bound active identity checks
  7. Credential configuration
  8. Prepared credential mutations
  9. Browser-bound OAuth login
  10. Primary bridge contracts
  11. Website sign-in with IndieAuth
  12. Bounded binary HTTPS and authoritative DNS
  13. Snapshot TXT bytes without decoding
  14. Realtime composition
  15. Web and persistence adapters
  16. Compose only supported operations
  17. Migrate an established application
  18. Staff verification on a caller transaction
  19. Boundary
  20. Explicit identity and replay policies
  21. Optional session lifetime and admission policies
  22. API entry points and requirements
  23. Peer dependencies

This guide describes upcoming source contracts, not a publication receipt. Check release availability and keep your complete Playstack graph on one verified version.

@playstack/auth

Framework-independent identity and opaque session primitives for Node and Workers.

Reference: @playstack/auth@0.1.0-beta.5 · TypeScript · MIT licence

Free. MIT licensed. Check preview availability before installing. See package access.

@playstack/auth owns framework-independent identities, credentials, and opaque session behavior for Node and Workers. It deliberately does not own accounts, authorization, device identity, or MFA.

Install

sh
npm install @playstack/auth @playstack/core @playstack/crypto @playstack/events

Install the optional argon2 peer only in the Node process that hashes passwords.

Compose sessions and credentials

ts
import { createAuthAttemptLimiter, createCredentialService, databaseSessions } from '@playstack/auth'
import { argon2id } from '@playstack/auth/node'

const sessions = databaseSessions({
  persistence,
  crypto: applicationCrypto,
  events,
  clock,
  ids,
  deviceValidator: devices,
  requireDevice: true,
  reusePolicy: 'all-user-sessions',
})

const credentials = createCredentialService({
  persistence,
  crypto: applicationCrypto,
  passwordHasher: argon2id(),
  breachChecker,
  limiter: createAuthAttemptLimiter(rateLimiter),
  delivery,
  stepUp: mfa,
  events,
  clock,
  ids,
  dummyPasswordHash: process.env.AUTH_DUMMY_PASSWORD_HASH!,
})

The same persistence instance may implement both the session and credential contracts. Transactional event handlers must use the same transactionKind so state and Tier 1 events commit atomically.

Session configuration

DatabaseSessionOptions propertyRequiredPurpose
persistenceYesTransactional session and refresh-token state.
cryptoYesRandom tokens, SHA-256 digests, and replacement-token encryption.
eventsYesTyped auth event emitter.
clock, idsYesApplication-owned time and ID generation.
deviceValidatorNoRejects inactive device-backed sessions.
requireDeviceNoRequires a device ID on issue; defaults to false.
accessTtlMsNoAccess lifetime; defaults to 15 minutes.
refreshTtlMsNoRefresh lifetime; defaults to 30 days.
refreshGraceMsNoParallel-refresh replacement grace; defaults to 30 seconds.
reusePolicyNoReuse response: session-family by default or all-user-sessions.

Refresh tokens rotate under a persistence lock. Reuse after the grace window revokes the token family and session.

jwtAccessSessions() signs and verifies the final token response before its issuance/rotation transaction commits. Recovery returns that exact response and refuses a consumed successor. The optional @playstack/auth/jwt/node codec uses local rotating HS256, RS256 or ES256 keys with explicit issuer, audience and clock. Install its optional jose peer only for that entry point; use a supported Node version listed in the package README. Server revalidation remains enabled by default. An application disabling it accepts expiry-bounded revocation.

Session security and maintenance

ts
const active = await sessions.listSessionsForUser(userId)
await sessions.revokeSessionForUser(userId, active[0].id)

const maintenance = createAuthMaintenance({
  persistence,
  clock,
  kinds: ['sessions', 'refreshTokens', 'authTokens'],
  consumedRetentionMs: 7 * 24 * 60 * 60_000,
})

await maintenance.purgeExpired({ limit: 250 })

Session activity exposes IDs, creation and last-use timestamps, expiry, account/client/device references, and bounded IP and user-agent metadata. It never exposes access or refresh credentials. Maintenance is bounded and scheduler-neutral; one call removes at most 1,000 expired or retained consumed records across sessions, refresh records, one-time tokens, authorization codes, email changes, and staff sessions.

Choose trusted kinds for the installed capabilities. Omission selects all six kinds and therefore requires their tables; unselected kinds are not queried. Selecting sessions also requires refreshTokens. A selected missing table is an error that rolls back the purge, not a reason to silently skip maintenance. Signup proofs use their separate native cleanup operation. Schedule both where needed and configure database timeouts: a row-deletion budget is not a scan or elapsed-time bound.

Consumed refresh tokens remain replay evidence through the family's original absolute expiry, even after revocation or a shorter consumed-record retention. Cleanup preserves refreshable sessions after access expiry and removes only eligible childless parents within the shared row budget. Do not equate expired access credentials with safely reclaimable session families.

Use listRenewableSessionsForUser() when a security page must include sessions whose access expired but whose renewal authority remains valid. It returns bounded, scope-bound cursor pages. Individual and all-user revocation can join the caller's physical transaction and revoke retained refresh descendants too. clearExpiredRefreshReplacements({ limit }) separately reclaims expired recovery ciphertext without deleting replay evidence. Current custom adapters must implement these ports and update-only session/refresh saves; a stale write must not recreate a purged credential.

Dual-inbox email approval

Set emailChangePolicy: 'dual-inbox' on CredentialService to require approval from both the current and proposed inbox. The default 'new-inbox' policy preserves new-address confirmation and the old-address reversal window. Pending requests retain their own immutable policy across service reconstruction.

Dual mode requires a TransactionalAuthDelivery. Request admission creates two independent proofs and enqueues both encrypted delivery intents on the same transaction. Deliveries identify purpose: 'emailChangeApproval' and an inbox of 'old' or 'new'; immutable outbox keys must distinguish the two sides. Failure of either enqueue rolls the request back. Delivery providers run only through the application's claimed worker after commit.

approveEmailChange(inbox, token, context?, transaction?) returns a discriminated pending or completed result. The first approval leaves the email unchanged. The second commits the contact change, proof consumption, session/refresh revocation, completion notice and required evidence together. Replays, expired or superseded requests, changed current contacts and deleted identities refuse. Standard confirmation/reversal cannot bypass a dual-policy request, and dual completion issues no unilateral reversal proof.

Both policies' notifyEmailChanged notices include native changeId, matching the original delivery's source.id. This also applies to ordinary after-commit notifications. Use that identity for exact encrypted outbox binding rather than reconstructing it from approval events or contact pairs. It is metadata, not a proof or permission; worker source/current-user checks and uncertain-outcome handling remain required. Public user responses and the changed-event payload are unchanged.

The optional authorizeEmailChange callback runs on the identity transaction with safe change metadata, including the approval side and completion stage. Use it for application-owned dispute and freeze checks. Native requested and approved events contain IDs/inbox only; the existing changed event represents the final mutation. Return results to clients after the caller transaction commits. A passing fixture does not qualify product policy, mail or browser flows.

Native persistence adds the policy, old-inbox proof hash and approval timestamps. Update custom adapters and schema together. The Playstack host migration refuses existing pending rows rather than inventing policy/approval evidence; retained application requests need an explicit reviewed transition. No automatic backfill is included. The current Playstack API does not enable dual-approval routes and explicitly refuses that unadopted mail purpose.

Transaction-bound active identity checks

For a trusted authenticated principal, call assertActiveUser(persistence, userId, transaction) before protected writes on that same physical transaction. Native Prisma's findUserActivityForUpdate locks the identity row through commit/rollback, rather than performing an unlocked findUserById lookup. The helper rejects root/autocommitting clients; a user ID is not authentication. Account membership, roles and token scopes still need current authorization.

Cooperating operations must serialize deactivation/restoration/deletion on that same row. Acquire identity locks before dependent account/membership/credential locks, sorting IDs when locking multiple identities. Reconcile existing adapter lock ordering before adoption; putting an unlocked read inside a transaction is not equivalent. Do not perform provider I/O while holding these locks or reuse the result outside the transaction.

Credential configuration

CredentialServiceOptions propertyRequiredBridge responsibility
persistenceYesUsers, identities, one-time credentials, pending email changes, and sessions.
cryptoYesOpaque token generation, hashing, and encryption.
passwordHasherYesPassword-grade hash and verify operations.
breachCheckerYesChecks candidate passwords against the application’s breach source.
limiterYesFails closed for identifier-plus-IP auth attempts.
deliveryYesSends verification, reset, magic-link, and email-change notifications.
stepUpYesVerifies a recent-auth or MFA proof for sensitive changes.
events, clock, idsYesTyped events and deterministic primitives.
dummyPasswordHashYesValid hash verified for unknown users to reduce timing disclosure.
tokenTtlMsNoOne-time token lifetime, 15–60 minutes; defaults to 30 minutes.
proofTtlMsNoPer-purpose proof lifetimes, one minute to seven days.
preparationTtlMsNoOne-shot preparation lifetime; defaults to 60 seconds, bounded to 1–300 seconds.
authorizeCredentialOperationNoRead-only product policy checked under current identity locks.
passwordChangeStepUpFor password changePurpose/user-bound grant preparation and transaction-local reauthorization/consumption.

Prepared credential mutations

preparePasswordRegistration, preparePasswordAuthentication, preparePasswordReset and preparePasswordChange move expensive password work before write locks. Each returns a one-shot in-process commit(transaction) capability. Commit checks current identity, password/contact/proof binding, original expiry and policy before joining native writes and required audit. Prepared reset/change require durable transaction-bound mail admission. Roll back the enclosing transaction on any error and expose results only after commit; retry after rollback requires fresh preparation.

Password change verifies the current password and requires a step-up grant whose original purpose/user binding and expiry remain authoritative. Its authorizeInTransaction must recheck or consume the original proof in the same physical transaction. A boolean verifier alone does not supply this contract. Keep onboarding, suspension, Account policy, templates and transport in the host.

Browser-bound OAuth login

@playstack/auth/oauth-login provides immutable, expiring browser-bound state and S256 PKCE with atomic single-use consumption before provider I/O. For shared workers, @playstack/auth/oauth-login-prisma and the optional auth.oauth-login.prisma artifact supply encrypted scoped persistence and bounded cleanup. Use a distinct purpose-bound encryption adapter. An uncertain consume or exchange requires a new attempt.

Configure the provider's exact HTTPS issuer identifier. Slashless root, slashed root and path-based issuers are preserved unchanged through state commitments and encrypted persistence; they never become aliases. A mismatched callback iss refuses before consuming the valid attempt. Issuer validation rejects credentials, query/fragment delimiters, whitespace/controls, backslashes and malformed input. Endpoint/redirect canonical URL rules remain unchanged. The provider adapter still owns ID-token verification and exact metadata/claim matching.

@playstack/auth/github supplies GitHub user login through the optional Connections peer. It returns a scrubbed profile and trusts only a verified primary email; provider tokens are not returned. Pass that server-only result to authenticateProfile() with an explicit identity-linking policy. Hosts own secure binding cookies, trusted callback extraction, initiation CSRF/rates, redirect destinations and MFA. GitHub App installation tokens are a separate capability.

Primary bridge contracts

ContractKey members
AuthPersistenceTransaction, session lookup/save/revoke, refresh-family locking and rotation.
CredentialPersistenceExtends auth persistence with user, identity, one-time token, and email-change records.
AuthCryptorandomToken, digestSha256, encrypt, decryptText; structurally compatible with @playstack/crypto.
PasswordHasherhash(password) and verify(hash, password).
PasswordBreachCheckerisBreached(password).
AuthAttemptLimiterconsume(operation, { identifier, ip }); returns allowed and optional retryAt.
AuthDeliveryToken delivery plus password- and email-change notifications.
StepUpVerifierverify(userId, proof); MfaService implements it structurally.
DeviceSessionValidatorassertActive(userId, deviceId).

CredentialService.authenticateProfile(profile, context?) is the entry point for a provider profile already normalized by Auth.js or another framework. authenticateProvider(provider, code, context?) performs the provider exchange and delegates to the same method, so linking and verified-email policy cannot drift between paths.

The transactional auth.user.registered event lets @playstack/accounts provision an initial account and owner membership in the same database unit of work. Delivery and initial session issuance remain post-commit application orchestration.

registerPassword() also accepts an explicit transaction context. Use createUnitOfWork() from @playstack/events when auth, accounts, profiles, and audit records must share one application-owned database transaction. Persistence adapters must declare the same transaction kind and physical handle; mismatches fail closed.

Website sign-in with IndieAuth

Use the optional server-side IndieAuth client when visitors should sign in with their own website URL. It verifies the website's authorization server and hands the confirmed URL to the existing credential/session system; it does not host an IndieAuth authorization server or request Micropub access tokens.

ts
import {
  createIndieAuthClient,
  createIndieAuthBrowserBinding,
  createMemoryIndieAuthAttemptStore,
} from '@playstack/auth/indieauth'
import { createNodeIndieAuthTransport } from '@playstack/auth/indieauth/node'

const indieauth = createIndieAuthClient({
  clientId: 'https://your-site.example/indieauth-client',
  redirectUri: 'https://your-site.example/auth/indieauth/callback',
  attempts: createMemoryIndieAuthAttemptStore(), // single process only
  transport: createNodeIndieAuthTransport(),
})

// After rate limiting and CSRF validation on your sign-in POST:
const browserBinding = createIndieAuthBrowserBinding()
const { authorizationUrl } = await indieauth.begin({ me: websiteUrl, browserBinding })
// Set a Secure/HttpOnly/SameSite=Lax/Path=/ host-only binding cookie;
// then redirect the browser to authorizationUrl.

// In the configured callback, read browserBinding from that cookie:
const profile = await indieauth.complete({ callbackUrl, browserBinding })
const user = await credentials.authenticateProfile(profile)
// Continue required MFA/account checks and your existing session flow.

Serve indieauth.clientMetadata as JSON at clientId. Configure the credential service with providerIdentityPolicy: { linking: 'explicit', email: 'optional' }. Only the confirmed website URL identifies the visitor. Provider email, profile attributes and tokens are discarded; first-contact email enrollment and identity linking require separate verified flows. An existing account is never selected merely because a provider claims its email address.

Attempts use S256 PKCE, browser binding, expiry and atomic single-use consumption. Multi-process/serverless deployments must supply a shared IndieAuthAttemptStore with atomic binding/expiry checks and consumption; a replayable cookie alone or get-then-delete storage is insufficient. Missing/duplicate binding cookies must fail. Keep login/callback responses private and uncached, suppress referrers, and redact callback query strings and credentials from logs. Uncertain exchanges require fresh sign-in, never an automatic code retry.

The supported profile uses public HTTPS websites and current server-metadata discovery with S256 and iss. HTTP/private/local endpoints and endpoint-only discovery are not supported. The Node transport pins public DNS answers and bounds redirects, headers, bodies and deadlines. Workers require an explicit equivalent safe transport; ordinary global fetch does not establish SSRF safety.

The installed package's README includes the full setup, storage contract, limits and error policy. Qualify your provider, browser cookies, proxy configuration, shared storage and session/MFA flow before launch. The adapter itself adds no managed schema or application routes.

Bounded binary HTTPS and authoritative DNS

createNodeBinaryHttpsTransport from @playstack/auth/https/node returns bounded binary bytes without UTF-8 decoding, while preserving all-address public DNS admission, connection pinning, TLS verification and redirect refusal. Configure trusted origins/paths and byte/time limits. Redirect hops are caller-managed and must repeat validation; image signatures, raster processing and local asset publication remain application policy.

createNodeAuthoritativeDnsTransport from @playstack/auth/dns/node supplies explicit public-address-safe UDP/TCP observations. Install its optional exact @dnspect/dns-ts@0.4.0 peer and retain the packaged parser worker asset. The root Auth entry remains Worker-safe and does not load Node sockets or that parser. Configure trusted numeric public bootstrap resolvers and required bounds for time, bytes, records, authority candidates, datagrams and concurrency. Request inputs cannot choose ports, bootstrap resolvers or source interfaces.

Supported queries include A, AAAA, NS, CNAME, SOA, TXT, DS, MX, SRV and CAA. MX exposes preference and lossless exchange labels (including null MX). SRV exposes distinct priority, weight, port and target, preserves underscore owners/root targets and rejects target compression. CAA exposes flags, a case-preserved tag and the complete Uint8Array value, including empty and non-UTF-8 values. Decode/validate issuer syntax in application policy, not by assuming every value is text. Every record retains owner/class/type/TTL and its containing answer, authority or additional section. Negative response flags and empty answers remain observations, not positive readiness. Earlier beta.3 local snapshots do not include these types; verify the exact adopted artifacts and immutable release before replacing an adapter.

Literal wildcard questions such as *.example.com preserve the complete leftmost * label through encoding, reply correlation and observations, without expansion. Partial/interior wildcards and wildcard authority hostnames remain invalid. TXT observations expose ordered readonly Uint8Array[] chunks, preserving empty chunks, arbitrary binary bytes and UTF-8 sequences split across chunks. There is no forced decoding, concatenation or replacement. Interpret bytes in host policy; migrate the earlier ASCII-string projection deliberately. The raw byte profile uses the same exact parser peer and bounded worker assets, not a second generic DNS implementation. Verify the new immutable release; existing beta.3 artifacts cannot acquire these changes without a distinct publication.

The transport pins admitted addresses, correlates replies, bounds parsing in a worker and handles cancellation/cleanup. It does not automatically follow referrals/CNAMEs or perform retries. Results keep answers, authority and additional sections separate: flags, glue and DS bytes are observations, not ownership or DNSSEC proofs. Delegation/bailiwick policy, network egress and real API/worker runtime qualification remain host responsibilities.

Snapshot TXT bytes without decoding

For an application-owned JSON snapshot, convert each byte chunk separately to a numeric array. This preserves order, empty chunks and arbitrary bytes, including UTF-8 sequences split across chunks, without choosing a text interpretation:

ts
import type { DnsRecord } from '@playstack/auth/dns/node'

export function txtChunkSnapshot(
  record: DnsRecord,
): readonly (readonly number[])[] | undefined {
  if (record.kind !== 'TXT') return undefined
  return record.chunks.map((chunk) => Array.from(chunk))
}

For example, [[226], [130, 172], [], [255, 0, 128]] remains four chunks, not a replacement-character string. This is a local projection, not a send grant, authenticated DNS result or new persistence contract. If product policy permits text, choose its encoding and validation explicitly and account for sequences spanning chunks; keep the original byte chunks. Consult the upgrade checklist before replacing older string-based projections.

Realtime composition

Issue a purpose-bound ticket from authenticated HTTP, then redeem it in the WebSocket hello frame:

ts
import { createRealtimeTicketService } from '@playstack/auth'

const tickets = createRealtimeTicketService({ sessions, crypto: applicationCrypto })
const ticket = await tickets.issue(accessToken)
const session = await tickets.redeem(ticket)

Tickets default to 30 seconds and may be configured from 1–60 seconds. Single-use safety depends on the atomic replay store configured in @playstack/crypto. Redemption re-resolves the session, so a newly revoked session cannot open a connection.

Web and persistence adapters

  • sessionCookie, clearSessionCookie, and assertCsrf enforce the v1 cookie/CSRF transport invariants without choosing a framework.
  • @playstack/auth-contracts publishes the JSON-safe session contract independently so a React or Next client can migrate before the server implementation.
  • parseAuthSessionView validates the narrow JSON-safe client projection and rejects unknown or credential-shaped fields.
  • @playstack/auth/prisma provides prismaAuthPersistence(prisma) and the managed, non-ejectable Prisma fragment.
  • @playstack/auth/testing provides in-memory persistence and crypto fakes.

Applications can register a validated extensions envelope with createAuthSessionViewParser() and createAuthSessionProjector(). The same parser must be used by server projection, React transport, account client, and Next helpers so product-specific account summaries or capabilities remain typed end to end. Tokens and provider credentials never belong in this envelope.

Compose only supported operations

Keep the complete Auth strategy private when adopting only session issuance or another bounded operation. Expose a literal facade containing bound supported methods. A partial persistence adapter must implement uninstalled ports as explicit failures, never fabricated null, empty arrays or successful no-ops. Do not advertise optional cap/idle/device capabilities without their real locking and activity semantics. Prefer the focused Accounts factories for their supported directory, administration, invitation, ownership and closure operations.

Issuance does not authenticate a supplied user ID. Revalidate the principal, account membership, device and scopes in the physical issuance transaction. Required registration/account provisioning, Audit and outbox consumers must do real same-transaction work and pass readiness checks; placeholder handlers do not establish required evidence. Disclose credentials only after acknowledged commit. An uncertain commit does not authorize repeating issuance.

Mandatory email verification and MFA are issuance gates, not consequences of installing factors. Compose current account policy, pending-login consumption and session issuance explicitly; qualify the complete database and browser flow. Keep application relations, deletion cleanup, transport origins and provider reconciliation application-owned. The qualification guide separates package tests from those deployment gates.

Migrate an established application

createMigratingPasswordHasher() verifies an explicitly configured legacy hash such as bcrypt, then rehashes with the current Argon2id policy under a compare-and-swap write. createLegacySessionExchange() provides an absolute, bounded window for exchanging an existing JWT or refresh session into ordinary Playstack opaque credentials.

Existing schemas may satisfy managed artifacts through exact model and field mappings. When physical storage differs, omit the artifact and implement application-owned AuthPersistence or CredentialPersistence; that adapter owns identifier conversion, dual reads, shadow writes, and record migration. The CLI can scaffold typed method stubs and contract-test entry points without declaring a semantically similar schema compatible.

Register sessions.deviceRevocationHandler() for devices.device.revoked and sessions.mfaChangeHandler() for MFA enrollment and disable events when those packages share the same transaction kind.

Staff verification on a caller transaction

createStaffSessionVerifier is a narrow existing-session capability requiring verification persistence, a digest provider, clock, a nonempty exact-IP allowlist and explicit staffUserPolicy: 'active' | 'verified-email'. It needs no dummy MFA or issuer. verifySession(token, transaction, ip?, { expectedUserId? }) starts no transaction: it locks User, StaffPrincipal and StaffSession in that order, refuses changed identity/hash bindings and checks current user policy, revocation, disablement, IP and expiry after waits. Expected-actor mismatch refuses before locking the other identity.

Returned claims contain only IDs/expiry and remain provisional until caller commit. They do not grant action permission. Required authorization, Audit and host writes join that same physical transaction; infrastructure errors must abort it. Reverify after subsequent waits if the operation requires final current authority. Multiple-identity callers prelock their complete identity set in stable order before dependent rows.

Native/custom adapters must provide the locking ports and physical handle assertion. The host retains trusted canonical schema/OID/DDL/RLS checks, grants, IP normalization and proxy policy before native reads. This does not add transaction-bound Staff issuance/revocation/impersonation, one-use MFA/action grants or a complete deployed operator workflow.

Boundary

Auth does not load secrets, choose HTTP routes, own account membership or authorization, identify devices, or decide MFA policy. Add React, Next.js, NestJS, accounts, devices, and MFA packages only at application edges that need them.

Explicit identity and replay policies

providerIdentityPolicy: { linking: 'explicit', email: 'optional' } supports email-less provider users without silently linking a matching email. Trusted server normalization and step-up-backed identity linking remain required. The compatible default is verified-email linking with required email. Safe user/session projections and registration-event email may be null; first-contact email enrollment remains an application-owned verified workflow.

New provider users emit the same transactional registration event as password signup. Required account/audit provisioning must join the actual transaction, not a post-login callback.

refreshReplayPolicy: 'strict' rejects every consumed-token replay without returning replacement material. The default bounded-grace policy retains encrypted replacement credentials for a bounded interval. reusePolicy: 'all-user-sessions' separately widens revocation scope. Strict mode rejects refreshGraceMs and requires shared client refresh coordination.

Authorization-code consumption and session issuance can commit together through required transaction-aware issuance/authorization seams with account context. A committed code cannot be replayed to recover lost credentials. Optional device authorization follows the same one-time boundary. See Client authentication.

Optional session lifetime and admission policies

databaseSessions() now accepts idleTtlMs, absoluteTtlMs and maxActiveSessions; omitted options preserve existing defaults.

  • Idle expiry is inclusive and measured from successful verify, resolve or refresh. Background requests count as activity and verification adds locked activity writes; this is not automatically human-idle detection.
  • Absolute lifetime starts at original issuance, survives refresh/account switching and clips token expiry. It cannot exceed refreshTtlMs.
  • Per-user caps reject new issuance with playstack/auth/session_limit_exceeded, never silently evict devices. Refreshable sessions count even after access expiry; caps require an explicit absolute lifetime.

Prisma supplies transaction-scoped creation locks and locked reads. Application persistence must implement lockSessionCreationForUser for caps and findSessionByIdForUpdate for idle expiry, with real cross-instance correctness. Missing seams fail configuration; no-op locks are not sufficient. All issuers must use the same policy/lock contract.

Native caps take the User foreign-key lock before the creation mutex to compose with locked account switching. This is not active-user authorization. Restricted session-only PostgreSQL roles need the User locking-read grants (SELECT and UPDATE); qualify those grants before enabling this native cap profile.

Use verifyInTransaction(token, transaction) to admit an existing opaque or JWT access credential alongside protected host writes. It reads the exact credential hash and locked current session on the caller's handle, preserving device and access/idle/absolute policies. JWT admission always checks backing state, even with ordinary revalidate: false, and preserves signed expiry and bindings without resigning. resolveInTransaction(id, transaction) is a locked state lookup; a session ID is not credential proof.

Propagate late admission failures so activity and host writes roll back together. The method rechecks its own awaited work; hosts own later authorization waits, lock ordering and outer commit before exposing results. Custom persistence needs assertTransaction, joined access-hash reads and serialized session reads; the published scaffold and conformance checks describe those ports. No schema change is required.

Map authenticated cap failures to a deliberate host response while retaining enumeration-safe unauthenticated errors. Strict/bounded-grace refresh replay remains independent; cookie transport, SSO, native coordination and deployment policy changes require application acceptance tests.

API entry points and requirements

Reference snapshot: @playstack/auth@0.1.0-beta.5. Import only the entry point your runtime needs. Paths below are relative to the installed package; use Go to Definition in your editor to inspect exact parameters, return types and overloads. Do not import the declaration-file paths directly.

Public entry pointDeclaration file
@playstack/auth./dist/index.d.ts
@playstack/auth/errors./dist/errors.d.ts
@playstack/auth/indieauth./dist/indieauth.d.ts
@playstack/auth/indieauth/node./dist/indieauth-node.d.ts
@playstack/auth/https/node./dist/https-node.d.ts
@playstack/auth/dns/node./dist/dns-node.d.ts
@playstack/auth/authorization./dist/authorization.d.ts
@playstack/auth/device./dist/device-authorization.d.ts
@playstack/auth/device-prisma./dist/device-prisma.d.ts
@playstack/auth/device-testing./dist/device-testing.d.ts
@playstack/auth/passwords./dist/passwords.d.ts
@playstack/auth/jwt/node./dist/jwt-node.d.ts
@playstack/auth/oauth-login./dist/oauth-login.d.ts
@playstack/auth/oauth-login-prisma./dist/oauth-login-prisma.d.ts
@playstack/auth/github./dist/github.d.ts
@playstack/auth/node./dist/node.d.ts
@playstack/auth/prisma./dist/prisma.d.ts
@playstack/auth/testing./dist/testing.d.ts
@playstack/auth/playstack.artifacts.jsonNo TypeScript declaration (asset or metadata export).
@playstack/auth/package.jsonNo TypeScript declaration (asset or metadata export).

Node.js engine requirement: >=20. This is not a claim that every entry point works in browsers or Workers.

Peer dependencies

Keep existing framework versions that satisfy these ranges. Install optional peers only when using the corresponding adapter. The package manager resolves ordinary dependencies separately.

PeerCompatible rangeWhen needed
@playstack/connections0.1.0-beta.5Optional; only for the entry points that use it.
@dnspect/dns-ts0.4.0Optional; only for the entry points that use it.
argon2>=0.44.0 <1Optional; only for the entry points that use it.
jose>=6.2.13 <7Optional; only for the entry points that use it.

For a complete first program, start with Getting started. For API lookup and partial-example conventions, see Reading the reference. Provider failures, lifecycle requirements and application responsibilities remain described in the guide above; types alone do not establish production safety.

Go

Playstack Pro tag
OriginsPricingBlogChangelogStatus

© 2026 Playstack. All rights reserved.

With OSS

By

Commune Software