@playstack/connections
Durable, refreshable, encrypted credentials for acting against third-party APIs.
Reference: @playstack/connections@0.1.0-beta.5 · TypeScript · MIT licence
Free. MIT licensed. Check preview availability before installing. See package access.
@playstack/connections manages encrypted, refreshable credentials for acting against third-party APIs on behalf of a user, account member, or account.
Explicit managed GitHub refresh
The Node GitHub.com profile provides an explicit durable rotating workflow:
createNodeGitHubConnectionProvider from
@playstack/connections/managed-refresh/node,
createManagedConnectionRefresh from the root and
PrismaConnectionsManagedRefreshPersistence from
@playstack/connections/managed-refresh/prisma. Use one shared Clock, explicit
managed enrollment, the exact native Connections store, qualified transaction
fencing and required authorization/evidence callbacks. The Prisma subpath needs
the optional @playstack/prisma-runtime peer.
The returned Node provider exposes close(): Promise<void>. It stops native
network admission immediately, cancels outstanding requests and waits for their
physical request/response/socket closure. Prepared requests cannot dispatch after
closing; complete response observations remain available for durable storage.
Stop application ingress, close the provider, then await your refresh/recovery
and onboarding operations before disconnecting their database or crypto resources.
The transport drain does not wait for those application operations or release
uncertain durable attempts. Repeated close calls share the same drain.
Admission permanently claims the predecessor and blocks its canonical target. Only a fresh local one-use request after committed admission confirmation can submit. Complete responses are retained as restricted encrypted receipts before parsing/current-actor checks; recovery never repeats refresh. Installation joins current source/authority checks, required evidence and native credential replacement with target release. Expiry stays anchored to original preparation.
Adopt the updated optional authority fragment with narrow journal-column grants and explicit retention of source IDs/commitments. Uncertain or incomplete attempts have no TTL/reset/replay path. Unresolved targets and spent credentials block secret use and admission; local denial remains possible. This does not enable automatic rotating refresh or qualify custom Fetch/endpoints/providers/journals. Application migrations, production grants and live provider qualification remain required. See the package README for the full composition and grant contract.
Retained refresh secret redaction
createManagedConnectionRefreshRedaction composes a native journal, clock,
dedicated trusted authorization and required evidence without provider access or
encryption keys. redact(input, transaction?) accepts the exact operation key,
Connection/scope, current inspected revision, reason and explicit requester
context. terminal covers installed or genuinely superseded operations. Native
storage verifies the complete retained supersession witnesses, including after
required evidence and on repeats; a marker alone cannot authorize cleanup.
Authorized owner-erasure also
covers unresolved operations after owner deletion. Worker attribution is separate
from the original refresh actor. Authorization runs before/after locks and after
evidence, with atomic caller-transaction rollback.
Permanent source bindings retain a commitment instead of source credential
ciphertexts. Redaction removes the response ciphertext and sets irreversible
secretsRedactedAt, preserving claims, status, supersession evidence, installed
successor and target. Superseded received operations keep their factual status.
Recovery and late sealing/installation cannot restore it. Installed redacted
history remains terminal; unresolved redacted history still blocks replay.
Use the current revision for harmless repeats. Stale revisions refuse.
Drain in-flight operations before owner erasure. This does not recall decrypted memory, remove live Connection credentials or erase provider grants/backups. Adopt the updated optional schema/hash and grants; existing journal/receipt data needs a reviewed cutover/conversion, with no automatic fallback or barrier reset.
Safe reconnect after uncertainty
admitOAuthGrant can explicitly accept supersedeManagedRefresh with a matching
native journal, exact old operation key/revision and required trusted
authorize/recordAction hooks. The replacement must be a verified prepared grant
with a supplied, different, never-known refresh credential. Normal grant
authorization still applies. The dedicated hook must verify fresh exchange
provenance, old-work quiescence and both scopes; local preparation time and
different bytes do not attest provider issuance.
Commit per-target preparation retirement below before obtaining and preparing a
fresh exchange. It fences earlier stamped grants, callback state and captured
native storage admissions across service instances. Provider close() alone
does not revoke admission capabilities. Credential generations fence admitted
credentials; preparation retirement fences earlier durable issuance, rather than
arbitrary re-preparation of unseen old token bytes. Fresh-exchange provenance and
reviewed handling of already submitted work remain required.
Native admission atomically
installs the grant, consumes its preparation, retires the old attempt and advances
a target-wide generation. Every older link remains blocked, including unclaimed,
manual/access-only and other-owner credentials. Known old tokens cannot be
re-admitted into the new generation. Current fresh grants and successors work;
local denial remains possible. Required evidence/final authorization roll back
with caller transactions.
Old factual/redaction state and claims remain. Recovery, confirmation, sealing and installation cannot reactivate the superseded operation; late HTTP facts do not change that. A cleared pointer alone is insufficient retirement evidence. Adopt the updated optional generation/marker schema, identity/link constraint, hash and grants together. Lost commit acknowledgments require authorized state inspection, not replay or a new key to bypass uncertainty. Live-provider and application lifecycle qualification remain required.
Per-target preparation retirement
Native managed GitHub.com preparations and begin() commit an issuance stamp
before provider work. Use inspectOAuthPreparations with provider, expected
credential binding/subject, explicit actor/scope context and trusted authorization
to read the target revision. retireOAuthPreparations additionally requires that
exact expectedRevision and transactional recordAction. Authorization must
return true before locks, after waits and after evidence. The safe view contains
revision and decimal-string retiredThrough, not internal target/client hashes.
The durable floor and credential admissions share the canonical target lock through physical commit or rollback, including an open caller transaction after the service call returns. Earlier grants and callback state refuse storage; later issuance works and unrelated subjects keep their preparations. Retirement orders durable issuance, not local invocation time or external token issuance. Old state whose subject is unknown can still perform provider I/O, but cannot admit credentials for the retired target. Joined results remain provisional; refusal must escape the caller transaction. Inspect after an unknown commit acknowledgment instead of blindly replaying a retirement.
Adopt ConnectionOAuthPreparationClient and ConnectionOAuthPreparationRetirement
with the current optional refresh-authority schema/hash and reviewed narrow
grants. Their counters/floors are permanent, with no deletion, reset or cascade.
Unstamped old managed callback state refuses; use a coherent schema/adapter/service
cutover. Ordinary nonmanaged providers retain their existing composition.
Retirement does not cancel remote work, resolve uncertainty, erase secrets or
remove consumed-token barriers. Drain full operations before disposing shared
resources. Live provider and application reconnect qualification remain separate.
Install
npm install @playstack/connections @playstack/core @playstack/crypto @playstack/eventsCompose providers and storage
Adopt the selected base schema and activate ordinary credential policy with separate maintenance credentials before starting this runtime composition.
import { createConnections } from '@playstack/connections'
import { githubConnectionProvider } from '@playstack/connections/providers/github'
const github = githubConnectionProvider({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
})
export const connections = createConnections({
persistence,
crypto: applicationCrypto,
events,
clock,
ids,
providers: [github],
scope: 'account',
redirectUri: 'https://app.example/api/connections/callback',
returnUrlOrigins: ['https://app.example'],
})
const { authorizationUrl } = await connections.begin({
provider: 'github',
scope: { type: 'account', id: accountId },
connectedByUserId: userId,
returnUrl: 'https://app.example/settings/connections',
scopes: ['repo:read'],
})OAuth uses PKCE plus a purpose-bound, short-lived, single-use state token. Access and refresh tokens are encrypted before persistence.
Service configuration
ConnectionsOptions property | Required | Purpose |
|---|---|---|
persistence | Yes | Transactional encrypted connection state and refresh locking. |
crypto | Yes | Random tokens, digests, encryption, and signed single-use state. |
events, clock, ids | Yes | Typed lifecycle events and deterministic primitives. |
providers | Yes | Unique provider bridges keyed by provider ID. |
scope | Yes | Exactly one of user, accountMember, or account. |
redirectUri | Yes | Exact OAuth callback URI. |
returnUrlOrigins | Yes | Allowlist for post-authorization return URLs. |
stateTtl | No | Signed OAuth state lifetime; defaults to 5m. |
refreshAheadMs | No | Refresh before expiry window; defaults to five minutes. |
grantPreparationTtlMs | No | Exchanged-grant admission lifetime; defaults to 60,000 ms, range 1–300,000. |
The configured scope must match the selected Prisma artifact variant and persistence adapter option.
Provider bridge
interface ConnectionProvider {
id: string
credentialBinding(): Promise<string>
capabilities: {
incrementalScopes: boolean
refresh: boolean
revoke: boolean
rotatingRefreshTokens?: boolean
}
authorizationUrl(context: OAuthAuthorizationContext): string
exchangeCode(code: string, context: OAuthExchangeContext): Promise<TokenSet>
identify(tokens: TokenSet): Promise<ProviderIdentity>
refresh?(refreshToken: string): Promise<TokenSet>
revoke?(tokens: TokenSet): Promise<void>
validateManual?(credential: string): Promise<ProviderIdentity>
}Capabilities must describe real provider behavior. The service handles connection state, encryption, scope comparison, refresh concurrency, and lifecycle events; provider drivers own protocol-specific URLs and token exchange.
Bind credentials to provider configuration
Providers must implement credentialBinding(): Promise<string> and every
ConnectionRecord must carry the resulting immutable lowercase SHA-256 hex
commitment. Native drivers bind the actual client ID, server endpoints,
authentication mode, resource and request parameters using owned configuration.
Provider aliases are independent of this identity; rotating the dedicated
clientSecret leaves it unchanged. OAuth state and prepared grants carry the
binding too. A changed configuration refuses stored-credential use with
provider_binding_mismatch before decryption or credential-bearing I/O;
callbacks also refuse before exchanging a code under a different configuration.
Already-exchanged admission requires expectedCredentialBinding from the trusted
exchange implementation, alongside the expected provider account. It must describe
the configuration that actually obtained the tokens, not untrusted input or a
new label copied from the current configuration. Generic OAuth2 also requires an
HTTPS resource declaring where the trusted identify callback uses credentials.
This declaration does not attest callback or injected-transport behavior.
All three schemas require credentialBinding without a default. Native readers
and native/memory write ports reject missing or malformed values; even a current
revision cannot rebind a stored row. Review historical configuration evidence and
adopt the schema, custom providers and persistence together. No automatic backfill,
old-format fallback or rebind path is supplied.
This guard does not establish cross-ID physical-target ownership or pin a durable target-key hasher. Committed dispatch and retained outcome/uncertainty journals remain separate work. Rotating and unclassified automatic refresh stay refused.
Inspect native refresh requests
Native GitHub and generic OAuth2 drivers expose optional
refreshRequestIdentity(), returning frozen readonly clientId and
tokenEndpoint facts from their actual request configuration. LinkedIn,
Mastodon and X inherit the same capability. It makes no provider request and
contains no credentials. Custom providers may omit it.
These facts do not establish a canonical OAuth issuer, endpoint-alias mapping,
verified subject or refresh barrier. Scopes, resource, static parameters,
authentication mode, dedicated secret and logical alias are separate from this
request identity. Use trusted server wiring and reviewed authority mappings;
never expose it through Auth/browser projections or infer dispatch permission.
The broader credentialBinding must not be used as a target partition: changing
its request settings need not change the underlying refresh lineage. Rotating
refresh remains refused. Request-facts inspection itself adds no schema or
retained target registry; the mandatory ordinary-policy table is separate.
Activate GitHub.com target-key configuration
Optional connections.refresh-authority.prisma adds retained opaque authority/key
configuration; default database sync excludes it. GitHubRefreshAuthorityRegistry
uses a native createConnectionRefreshAuthorityKey with exactly 32 private bytes.
Explicit maintenance activate(provider) pins the actual key and configured
client. Runtime targetKey(provider, verifiedNumericUserId, tx?) requires that
activation, joins an optional caller transaction, and derives a stable keyed
GitHub.com/client/subject target. Secret rotation and logical aliases do not change
it; changed actual key material refuses rather than opening a new target space.
This profile requires the actual native GitHub driver with standard token/API endpoints. Generic objects and custom endpoints do not qualify by exposing similar facts. Injected Fetch and the verified numeric subject remain trusted host responsibilities. A hash is not identity proof or dispatch permission.
Activation also retains the exact credential configuration's mapping to its
request/client authority, using private native constructor state rather than
public method overrides. assertCredentialBinding(provider, binding, tx?) checks
that configuration and activated key on an owned or joined transaction. It returns
no capability, reads no stored Connection and does not verify identity, refresh
freshness or permission to dispatch. Missing/conflicting mappings refuse; read
checks never activate them. Target hashes keep their existing framing.
Adopt the updated optional fragment and custom authority-adapter contract together;
the activation binding now requires credentialBinding. There is no automatic
backfill or missing-schema fallback. This configuration mapping does not enforce
credential-writer admission or advance per-link refresh epochs.
Runtime roles need SELECT only on the retained tables; explicit maintenance also needs INSERT. Neither should own or update/delete/truncate the tables. Retain configuration outside Connection/owner cleanup and review stable key custody. Custom persistence has an explicit adapter scaffold; database sync never generates its source. There is no automatic activation, migration, backfill or key reset.
This optional authority registry does not own targets or replace the mandatory ordinary credential policy below. It adds no provider submission or recovery journal. Rotating refresh remains refused until those remaining contracts are implemented.
Native GitHub client selection
The selected base scope schema also includes ConnectionNativeClientPolicy and a
nullable nativeClientKey on each exact credential policy. Native GitHub and
OAuth2 constructors privately recognize the exact standard GitHub token endpoint.
They derive a key-independent SHA-256 commitment to the fixed GitHub realm and
actual client ID; API/resource settings, alias, secret and credential binding do
not partition it. This key is distinct from the optional keyed authority/client/
target identities. There is no public client-fingerprint method.
The first explicit maintenance activation selects ordinary or
github-com-managed-v1 for that native client. Mode comes from the actual policy
profile. It is immutable across manual/OAuth classes and exact configurations.
An ordinary client cannot later become managed, and an enrolled client cannot
ordinary-activate a custom-API GitHub or generic OAuth2 configuration using the
same standard token endpoint/client. Different clients remain independent.
activateManaged selects both managed policies before activating optional
HMAC mappings, on the same original transaction. Authority-only activate does
not select a credential mode.
Activation uses one native maintenance transaction mutex, validates existing exact/client rows before any insert, then inserts only missing compatible rows. Runtime compares the expected and retained key including its presence, and native reads/writes independently validate the stored client mode. Omission is not an exemption. Missing tables, malformed rows, missing selections and mismatched modes refuse. Ordinary recognized clients still require no HMAC key or optional refresh-authority tables. Runtime needs SELECT on both required policy tables; maintenance adds INSERT only. Retain rows without UPDATE, DELETE, TRUNCATE, TTL, owner cascades or reset privileges.
Native subclasses/prototype changes retain this negative client classification
while losing positive managed qualification. Public request-identity/binding
methods cannot replace private facts. At the recognized endpoint, generic Basic
auth requires URI-unreserved client IDs and rejects a conflicting static body
client_id, keeping its wire identity unambiguous. Body/none authentication and
other providers retain their existing contracts. Structural/custom providers,
operation/transport overrides, injected Fetch and unqualified endpoint aliases
remain trusted host wiring, not native lineage
attestation. Do not claim this fences arbitrary transports or all OAuth issuers.
Adopt the updated base schema, adapter and scaffold together. Existing native policies need reviewed application-owned configuration/data adoption; no missing- key fallback, inferred history, automatic backfill or ordinary-to-managed promotion is supplied. Client selection is configuration admission, not token consumption, a refresh lease, provider dispatch or recovery. Rotating refresh remains disabled.
Managed native GitHub credential identity
For reviewed native GitHub.com integrations, explicitly enroll each configured
provider with authority.activateManaged(github, maintenanceConnections).
maintenanceConnections supplies the credential-policy port on the same physical
database transaction as the authority registry. Activation commits the actual key,
request/client/exact-binding mappings and github-com-managed-v1 policies for
both manual and OAuth grants together. Exact repetition converges; conflicting
ordinary policies or keys refuse. There is no automatic promotion, backfill,
profile rewrite or reset.
Runtime selects enrollment per alias using the original native driver object:
const connections = createConnections({
persistence, crypto, events, clock, ids,
providers: [github],
managedGitHub: [{ provider: github.id, authority: runtimeAuthority }],
scope: 'account',
redirectUri: 'https://app.example/api/connections/callback',
returnUrlOrigins: ['https://app.example'],
});runtimeAuthority uses the same retained key and database domain, with read-only
activation access. Unknown/duplicate aliases, missing or structural registry
objects, copied/proxied/subclassed providers and custom GitHub origins refuse.
Native operations and exact configuration are captured privately; changing public
methods or capability declarations cannot relabel the enrolled profile. An
injected Fetch remains trusted host wiring, not provider/transport attestation.
Ordinary profiles remain available without a target key. An ordinary service for
an enrolled binding refuses before credential-bearing provider/crypto work.
Managed preparation and native callback completion verify provider identity, then derive a private, purpose-bound refresh credential identity from the canonical client and exact refresh-token bytes. The existing four public HMAC methods and their domains are unchanged; there is no public fingerprint method. Well-formed Unicode preserves case, whitespace and composition exactly; unpaired UTF-16 surrogates refuse. The managed limit is 65,536 code units and 196,608 UTF-8 bytes. Ordinary credential input limits and external provider support remain unchanged.
The optional authority fragment supplies these retained identity tables, in addition to authority mappings and managed attempt/target tables:
ConnectionRefreshCredentialIdentitybinds one opaque credential key to one canonical client/verified-subject target. The same client/token across aliases, owners and re-encryption converges; distinct tokens stay distinct. Rebinding the same identity to another verified subject refuses through the retained relation.ConnectionManagedRefreshLinkretains a Connection/binding/target anchor and its current credential pointer. A new refresh-bearing grant installs its identity; access-only OAuth reauthorization preserves only the exact locked prior OAuth ciphertext/key. Manual replacement clears the active pointer while preserving the anchor and immutable identity history. Ordinary saves preserve that evidence.
These facts stay in private preparation and validated opaque write admission,
not public prepared descriptors, ConnectionRecord or browser responses. Custom
adapters inspect readonly managed facts and atomically move identity/link state
with the successful credential mutation and any preparation receipt. Failed CAS,
caller rollback and required-handler refusal must leave no provisional admission.
The required assertManagedCredential(record, targetKey, transaction) validates the
current enrolled row/link, authority and identity on the original physical
transaction before stored-secret use; target strings are comparison data, not
permission. Missing/malformed/stale links or schema refuse without adoption.
Adopt the updated optional authority schema and adapter/scaffold together before
enrollment. Retain all identity/link anchors independently of Connection/owner
FKs, cascade, TTL and cleanup. Runtime needs SELECT/INSERT on identity rows and
SELECT/INSERT plus UPDATE of only currentCredentialKey on links. Withhold
anchor UPDATE, DELETE, TRUNCATE and ownership. Maintenance activation still uses
SELECT/INSERT on authority mappings and policies; no key/identity reset is implied.
The native mutation joins exact identity/target and link constraints atomically;
custom adapters must qualify equivalent rollback, concurrency and confinement.
Managed identity and target locking cover explicitly enrolled native bindings. The required client-selection policy also excludes ordinary native configurations sharing that recognized GitHub refresh client. It does not attest arbitrary custom transports or unqualified endpoint aliases. The cooperative lock alone grants no dispatch permission. The explicit managed profile adds permanent claims, encrypted recovery and guarded installation. Automatic due rotating refresh still requires reauthorization; unresolved managed attempts also block existing secret use.
Managed target lock ordering
Managed scoped lookups receive a service-issued opaque ConnectionLookupAdmission
before any provider or live-row lock, including when no Connection exists. Custom
adapters use inspectConnectionLookupAdmission(scope, provider, subject, proof, tx)
to validate the exact lookup and original physical transaction. Copies, changed
inputs and other transactions refuse; there is no public proof issuer. A lookup
proof authorizes neither a write nor a provider request.
Native managed operations acquire owner FOR UPDATE, canonical target advisory
transaction lock, scoped provider mutex, then ID reservation/live row. By-ID reads
and direct saves discover retained link facts without locking the Connection,
then revalidate them after the ordered waits. Existing managed rows cannot omit
the target by using an unconfigured native peer. Creation/replacement derives its
target from the existing exact credential-write admission. The target lock spans
all owners and aliases using that canonical client/verified subject, while
different targets remain independent of each other unless another lock conflicts.
Native adapters share lock-phase tracking on the actual physical transaction handle. Once a provider/row prefix begins, acquiring a previously unheld managed target refuses rather than locking it late. The same target may be reused. Enter managed work before unrelated provider lookups. A caller transaction spanning multiple owners must establish all required strong owner/ancestor locks before its first target lock; ordering owners only between later service calls is not sufficient. Raw host SQL locks and arbitrary cross-domain lock orders remain the host's responsibility. Results are provisional until outer commit; refusal must escape to roll back the unit. Memory validates lookup admissions but does not simulate PostgreSQL contention.
This adds no schema or new grants: advisory transaction locks release on commit or rollback. They serialize current managed credential work, not durable refresh submission. Consumed-token evidence, uncertain outcomes and acknowledged-result installation belong to the explicit managed profile, not the lock alone.
Production role grants, provider qualification, schema adoption and publication remain separate owner actions.
Qualified credential writes
The service supplies opaque admission for native credential creation and
replacement. Persistence create(record, transaction, admission) requires it;
replaceCredentials(record, transaction, admission) replaces an existing bundle
with expected-revision CAS. A missing/copied admission, changed payload or another
transaction refuses across native adapter instances. Custom adapters can validate
with assertConnectionCredentialAdmission or inspect readonly binding, grant type,
profile and intent using inspectConnectionCredentialAdmission. Its
prepared-oauth-grant variant also carries the private preparation ID for the
trusted adapter's atomic admission receipt. Inspection validates the exact local
admission; it does not mint authority, write that receipt or replace durable-policy,
physical-transaction and CAS checks. Repeat validation after awaited guards/locks;
a late refusal must roll back all provisional writes.
Ordinary save preserves ciphertexts, refresh presence, scopes/order, expiry,
grant type and credential attribution; it also refuses nonactive-to-active changes.
It prevents revoked/insufficient credentials from becoming expired, which can
still return valid or nonexpiring tokens. Status, display/metadata and verification
updates keep their existing path. Reauthorization and supported nonrotating refresh
use qualified replacement; access-only reauthorization preserves the latest locked
refresh credential. Admissions remain local exact-invocation facts, not durable
receipts, product authorization or proof of commit.
Activate ordinary credential policy
The base schema now requires ConnectionCredentialPolicy, keyed by credential
binding and grant type. The following activates ordinary profiles; reviewed managed
GitHub enrollment uses the distinct profile described above. Activate every used
ordinary pair with maintenance credentials
before starting runtime writers:
import { ConnectionCredentialPolicyRegistry } from '@playstack/connections';
const registry = new ConnectionCredentialPolicyRegistry({
persistence: maintenancePersistence,
});
await registry.activate(provider, 'oauth');Activation owns its transaction and derives the profile from captured provider
configuration. Exact repeats succeed; a conflicting existing profile refuses.
Activate 'manual' separately if the same binding supports manual credentials.
Activation does not enable unsupported provider operations.
| Grant type | Derived profile | Supported ordinary path |
|---|---|---|
manual | manual | Manual credential admission and use. |
oauth | oauth-refresh-blocked | Fresh OAuth admission and access-token use; no automatic refresh. |
oauth | oauth-nonrotating | Fresh OAuth admission and supported nonrotating refresh. |
Nonrotating classification requires explicit refresh capability and
rotatingRefreshTokens: false. Rotating, unclassified and nonrefreshable OAuth
remain blocked. Native GitHub, including Enterprise, uses private blocked
capabilities and binding despite public overrides. Native OAuth2 captures its
constructor configuration; native subclasses conservatively remain blocked.
Custom provider declarations/callbacks remain trusted host configuration, not
provider or transport attestation.
Runtime persistence requires SELECT-only assertCredentialPolicy(policy, transaction).
Native instances check the shared durable policy before stored-secret use and
credential writes; ordinary saves validate the actual stored pair. Unknown or
mismatched policies and absent schema refuse. There is no automatic activation,
reset, rewrite, cleanup or backfill, including on owner/Connection deletion.
Grant runtime SELECT on this table and separate maintenance SELECT/INSERT; withhold
UPDATE, DELETE and TRUNCATE. Custom adapters implement the runtime check plus the
separate ConnectionCredentialPolicyPersistence maintenance port.
assertConnectionsPersistenceContract(persistence, maintenance) requires both ports.
Update custom adapters and scaffold implementations together.
Review and adopt the updated base scope schema before activation. Existing bindings need reviewed configuration evidence rather than inferred profiles. This ordinary policy requires no target key or optional refresh-authority tables. It supplies no target ownership, epoch or provider-dispatch guarantee. Linked credential identities, uncertainty barriers and rotating recovery remain separate work.
Native mutation ordering
Native by-ID locking reads, provider lookups, direct save and create now acquire
the selected owner with FOR UPDATE before provider-key and Connection locks.
Enrolled managed paths insert the canonical target lock before the provider key.
Unlocked discovery only locates those locks; by-ID reads return the latest
same-identity row after waits, while save retains its expected revision CAS.
Creation still reserves IDs before inserting live rows. Transaction-bound memory
operations also reject handles that settle during a guard wait.
This removes an owner/row inversion and prevents weak-owner/audit-upgrade cycles. The tradeoff is selected-owner-wide serialization, including fresh access-token locking reads and owner locks held during supported nonrotating provider I/O. By-ID readers/direct savers need owner-table SELECT and row-lock UPDATE grants; authority-registry SELECT-only privileges are a separate contract. Host callbacks must preserve their broader ancestor lock order; raw host row-first SQL is not covered. The updated adapter scaffold documents the same cooperative contract. Owner-first locking itself introduces no schema, target barrier or rotating dispatch; the mandatory ordinary-policy table is separate.
Automatic refresh safety
Outside refreshAheadMs, accessToken() can return the existing access credential.
When refresh is due and otherwise available, automatic submission requires
capabilities.rotatingRefreshTokens === false. A rotating or unclassified
provider instead receives fixed, nonretryable
playstack/connections/refresh_requires_reauthorization before refresh-secret
decryption, provider I/O, status changes or events. Repeated calls and new service
instances leave the stored row unchanged and never submit that refresh.
GitHub and X declare rotation; generic OAuth2 and LinkedIn currently omit the
classification. Do not relabel these providers as nonrotating. Use fresh reviewed
authorization/admission, or retain the application's qualified durable integration.
Direct provider refresh() methods remain protocol escape hatches, with their
durability and provider qualification owned by the caller.
Explicit nonrotating refresh keeps its existing serialized behavior. This guard adds no schema or journal and does not claim durable rotating recovery, uncertain quarantine or provider-submission no-replay receipts. A database rollback cannot undo a provider's consumption of a rotating credential; that requires the explicit managed profile.
Provider options
The included driver accepts required clientId and clientSecret, plus optional GitHub Enterprise webBaseUrl and apiBaseUrl, REST apiVersion, userAgent, allowSignup, prompt, injected fetch, and test clock. It supports OAuth App authorization with PKCE and personal access tokens as manual credentials.
@playstack/connections/providers/oauth2 supplies a standards-based authorization-code, PKCE, refresh, client-authentication, and optional RFC 7009 revocation factory. Named drivers configure GitHub, LinkedIn, Mastodon, and X while preserving the native provider instance and injected Fetch boundary.
AT Protocol is intentionally separate. @playstack/atproto retains official discovery, PAR, DPoP, nonce, refresh, and session-store behavior instead of copying its credentials into a conventional OAuth token record.
Crypto and persistence bridges
ConnectionCrypto is structurally compatible with @playstack/crypto. Its sign and verify methods must preserve purpose and single-use semantics. ConnectionsPersistence provides transactional lookup/save and must lock a connection during refresh.
Every Connection record now requires a positive integer revision. create
only admits revision 1; save(record, transaction) compares its current version
and immutable owner/provider/credential-binding/creation bindings, updates an existing row only,
and returns the authoritative version plus one. It never UPSERTs a missing row.
Stale/mismatched/missing or exhausted versions return fixed, retryable
connection_conflict; reread and reprepare after known rollback rather than
replaying the stale record. Consume the returned version for later joined writes.
Verification results retain their original pre-provider version. A later grant or status write prevents an old success, provider denial or identity mismatch from changing its credentials, profile or evidence—even when timestamps match. Direct current-state status commands remain separate from delayed verification. Custom adapters, all three schema variants, the scaffold/hash and conformance must move together. Existing data needs reviewed revision-column adoption before cutover; no automatic backfill or old-format reader is provided.
The selected fragment also includes ConnectionIdReservation(id) with no FK,
cascade or expiry. Native create reserves the opaque ID and inserts the row on
one transaction; a committed ID cannot be reused after Connection/owner deletion.
Known rollback permits a retry. save requires that witness as well as the row
version; an unregistered row cannot be silently adopted. Native direct creation
keeps owner/provider-key locks before the reservation. Custom adapters must
qualify equivalent retained identity, physical deletion and rollback behavior.
Review/apply the schema before activating writers. Historical protection needs reliable reviewed ID evidence; previously deleted IDs cannot be invented from current rows. No automatic backfill is provided. Retain reservations through cleanup, grant application roles SELECT/INSERT only, and exclude UPDATE/DELETE/ TRUNCATE and owner cascades. Direct SQL/owner bypass is outside this contract. Nondispatch reads do not attest schema adoption. This stores opaque IDs, not credentials or provider-account data; retention remains host policy.
This closes same-ID resurrection, not cross-ID/provider-target uncertainty. A fresh ID is a separate incarnation. Durable dispatch, encrypted outcome recovery and current-authority installation require the explicit managed profile; the automatic refusal stays in place.
import { prismaConnectionsPersistence } from '@playstack/connections/prisma'
const persistence = prismaConnectionsPersistence(prisma, { scope: 'account' })Select the matching managed schema variant in playstack.json; it is security-critical and non-ejectable. The CLI composes the matching reverse model extension into a managed owner artifact. When an established schema differs physically, use an application-owned persistence adapter and contract tests rather than importing parallel User or Account models.
Custom persistence must implement the required assertTransaction and create-only
create contracts with the published scaffold/conformance checks. Native owned
and joined mutations require ReadCommitted and refuse root, wrong-kind, settled
or retained-snapshot handles. The owner foreign-key row locks before the
provider-account mutex, avoiding an inversion with caller-owned identity creation.
That existence lock grants no activity authority; restricted roles must qualify
SELECT and row-lock UPDATE privileges on the chosen owner table. The admission
seam now also requires the permanent preparation receipt below; revision,
binding, reservation and ordinary credential-policy contracts require reviewed
schema adoption before activation.
Reuse an already-exchanged OAuth grant
Call prepareOAuthGrant({ provider, expectedProviderAccountId, expectedCredentialBinding, tokens }) before
opening the database transaction. It snapshots the tokens/scopes, verifies the
provider identity against the mandatory expected account, and encrypts the
credentials without exchanging the code again. Expiry is an absolute millisecond
timestamp. Provider metadata is detached and bounded.
Then call admitOAuthGrant({ grant, scope, connectedByUserId, authorize }, context?, transaction?)
inside the first-login/returning-user transaction, or omit the handle to let the
service own it. The required trusted authorize callback binds verified provider
facts to the current owner, before Connection locks and after required evidence.
Acquire identity/owner authority first, with the same lock order on every path.
IDs and tracing context are not permission. Explicit ConnectionsError('not_authorized')
refuses admission; unknown callback/storage failures remain sanitized retryable
persistence failures. Propagate failure to roll back caller/native writes together.
Expose acceptance only after commit; later arbitrary caller waits are outside
admission's final freshness boundary.
For returning-user admission, set omittedRefreshToken: 'clear' when the product
requires an absent new refresh token to remove the old one. Omission or explicit
'preserve' keeps the latest locked token; a new token actually supplied by the
verified grant always replaces it. The effective policy is captured before
waits and included in both authorization calls. Invalid policies refuse before
admission writes, and caller rollback restores the prior token and evidence.
Managed clearing also nulls the active credential pointer while retaining its client/subject anchor, credential identities and consumed-token history. It does not erase retained refresh receipts or release an unresolved target. This option is not reconnect/supersession or secret-redaction authority. Native adapters support it through the service-issued prepared-grant admission; custom managed adapters must honor the inspected policy rather than bypassing qualified writes.
The server-only descriptor is secret-free, service-instance-bound and expires within the configured preparation lifetime or original token expiry, whichever comes first. Retry storage only after known rollback, with fresh owner resolution and authorization, without repeating provider identification.
Each preparation gets one private ID from crypto.randomToken(32), omitted from
the public descriptor. Successful admission atomically inserts that ID into
mandatory ConnectionOAuthGrantAdmission(id) alongside the credential write.
The same committed preparation cannot admit again, even into another owner/row
or after Connection/owner deletion. A duplicate refuses without returning the
old record. The native plain INSERT aborts the physical transaction; propagate
late failure so all provisional caller/native writes roll back. A failed row/CAS
write must not consume the preparation. Known rollback removes both writes and
permits retry of that same preparation.
The receipt has no owner/live-row FK, cascade, TTL or cleanup. Adopt it from the
selected base scope fragment before enabling writers. Runtime needs INSERT and
SELECT on the ID for native returning inserts, with no UPDATE, DELETE, TRUNCATE
or ownership. Custom adapters inspect prepared-oauth-grant facts and atomically
claim the private ID with successful create/replacement. Update scaffold and
conformance implementations together; there is no standalone claim API or
automatic historical backfill.
This permanent local once-admission guard is not a durable recovery or disclosure API. An absent receipt is not proof of rollback; the host must resolve unknown transaction outcomes. Do not replay after success/unknown commit, serialize the preparation for another process, or treat it as identity-linking authority. Independently preparing the same plaintext creates a separate admission and remains allowed; this is not a refresh-token fingerprint, credential epoch or consumed-token barrier. Ordinary callback completion, manual admission and supported nonrotating refresh keep their existing paths, without a preparation receipt or target-key requirement.
Admission creates a missing row or updates the same locked provider-account row.
An omitted refresh token preserves only the latest credential for that same
OAuth grant; manual/OAuth changes never inherit it. An already-active row does
not emit a new creation/status event. Additional login audit requirements remain
host-owned. Keep returned ciphertext-bearing ConnectionRecord values server-only
and retain the service's normal constructor ports. This does not qualify lost
refresh responses or uncertain rotating-token submissions; those need a separate
durable recovery policy.
Boundary
Connections returns a valid access token; feature code uses the provider’s native SDK directly. The package does not implement login, provider API clients, posting, syndication, or provider-specific UI. Secret sources and provider configuration remain application-owned.
The base persistence conformance runner covers ordinary workflows. Qualify managed custom adapters separately for enrollment, identity/link consistency, rollback and actual provider/role grants; generated scaffold typechecking is structural only. Managed async APIs return allowlisted codes with fixed messages and no raw provider, crypto or SQL diagnostic causes.
API entry points and requirements
Reference snapshot: @playstack/connections@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 point | Declaration file |
|---|---|
@playstack/connections | ./dist/index.d.ts |
@playstack/connections/errors | ./dist/errors.d.ts |
@playstack/connections/prisma | ./dist/prisma.d.ts |
@playstack/connections/providers/github | ./dist/providers/github.d.ts |
@playstack/connections/providers/oauth2 | ./dist/providers/oauth2.d.ts |
@playstack/connections/providers/transport | ./dist/providers/transport.d.ts |
@playstack/connections/providers/linkedin | ./dist/providers/linkedin.d.ts |
@playstack/connections/providers/mastodon | ./dist/providers/mastodon.d.ts |
@playstack/connections/providers/x | ./dist/providers/x.d.ts |
@playstack/connections/testing | ./dist/testing.d.ts |
@playstack/connections/playstack.artifacts.json | No TypeScript declaration (asset or metadata export). |
@playstack/connections/playstack.integration.json | No TypeScript declaration (asset or metadata export). |
@playstack/connections/package.json | No TypeScript declaration (asset or metadata export). |
@playstack/connections/managed-refresh/node | ./dist/managed-refresh-node.d.ts |
@playstack/connections/managed-refresh/prisma | ./dist/managed-refresh-prisma.d.ts |
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.
| Peer | Compatible range | When needed |
|---|---|---|
@playstack/crypto | 0.1.0-beta.5 | Required by the package. |
@playstack/prisma-runtime | 0.1.0-beta.5 | Optional; 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.