JavaScript SDK
Checked example
This example is included from source and typechecked against the SDK. Supply your own deployment configuration and session; this page does not run a live request.
import { createSignInFlow, type SignInFlowOptions, type SignInFlowState } from '@saaslayer/js'
export function connectSignInUI(options: SignInFlowOptions, render: (state: SignInFlowState) => void) {
const flow = createSignInFlow(options)
const renderState = () => render(flow.getState())
const unsubscribe = flow.subscribe(renderState)
renderState()
return {
flow,
dispose() {
unsubscribe()
flow.dispose()
},
}
}Reference for @saaslayer/js 0.0.15. Generated from this version's public exports and TypeScript declarations. Signatures describe the API; the integration guides explain behavior and setup.
acceptInvitation
Accept an invitation as the signed-in caller (POST /me/invitations/accept). Repeating it as the same user returns the
earlier outcome (recovered: true); a 409 with code membership_revoked means that membership was since removed.
export declare function acceptInvitation(client: PermissionsClient, token: string): Promise<InvitationAcceptance>;AccessRequest
An access request record (requestId surfaced as id).
export interface AccessRequest {
id: string;
requestId?: string;
status?: string;
requesterId?: string;
scope?: string;
type?: string;
reason?: string;
[key: string]: unknown;
}AccessRequestPage
A page of access requests.
export interface AccessRequestPage {
items: AccessRequest[];
nextCursor: string | null;
}AccessRequestQuery
Filters for listing access requests.
export interface AccessRequestQuery {
status?: string;
scope?: string;
requesterId?: string;
limit?: number;
cursor?: string;
}AccountConnector
The account self-service surface (M1.1): sign-up, email verification, password reset, and authenticated attribute/password changes. All Cognito-direct via the connector, so <SignUp>, <ForgotPassword>, and <UserProfile> need no user-service. A future proxy connector can implement the same interface. Kept separate from AuthConnector so a sign-in-only connector stays valid.
export interface AccountConnector {
signUp(params: SignUpParams): Promise<SignUpResult>;
confirmSignUp(params: {
username: string;
code: string;
clientMetadata?: Record<string, string>;
}): Promise<void>;
resendConfirmation(params: {
username: string;
}): Promise<void>;
forgotPassword(params: {
username: string;
loginMethod?: 'email' | 'phone';
}): Promise<void>;
confirmForgotPassword(params: {
username: string;
code: string;
newPassword: string;
loginMethod?: 'email' | 'phone';
}): Promise<void>;
changePassword(params: {
accessToken: string;
oldPassword: string;
newPassword: string;
}): Promise<void>;
updateAttributes(params: {
accessToken: string;
attributes: Record<string, string>;
}): Promise<void>;
}adaptEngineTokens
Convert engine tokens ({ expireAt: Date }) into our TokenSet ({ expiresAt: number }).
export declare function adaptEngineTokens(t: EngineTokens, nowMs?: number): TokenSet;addGroupMember
Add a principal to a group (POST /groups/:id/members).
export declare function addGroupMember(client: PermissionsClient, groupId: string, member: { type: string; id: string; }): Promise<void>;addRolePermission
Add a permission to a role (POST /roles/:id/permissions).
export declare function addRolePermission(client: PermissionsClient, roleId: string, perm: Permission): Promise<void>;AdminUser
A user as the admin routes answer it: suid + attributes (email, name, status, enabled, …).
export interface AdminUser {
id: string;
attributes: Record<string, unknown>;
}ApiError
export interface ApiError {
status: number;
type: string;
code?: string;
message: string;
details?: Record<string, unknown>;
}ApiKey
An api key (the raw apiKey string is present only once, on create).
export interface ApiKey {
id?: string;
keyId?: string;
name?: string;
status?: string;
userId?: string;
scope?: Scope | null;
permissions?: {
allows?: ApiKeyAllow[];
denies?: ApiKeyAllow[];
};
expiresAt?: string;
apiKey?: string;
[key: string]: unknown;
}ApiKeyAllow
A single allow/deny entry on an api key.
export interface ApiKeyAllow {
service?: string;
action: string;
resource?: string;
}applyScope
Apply the active scope to a permission check. An explicit check.scope always wins; otherwise the
active project scope is used. orgId is NOT sent — it is the token's mapped rbac tenant, asserted by
the server from the verified token, never the request body.
export declare function applyScope(check: PermissionCheck, scope?: Scope | null): PermissionCheck;approveAccessRequest
Approve an access request (POST /access-requests/:id/approve). The approver is the caller.
export declare function approveAccessRequest(client: PermissionsClient, id: string, input?: { comment?: string; }): Promise<AccessRequest>;assignRole
Assign a role to a user (POST /users/:id/roles). scope=null is global; else the project id. A user who already holds
the role at that scope with a different end date is refused with ApiError 409 role_already_assigned (its
meta.existing.expiresAt is the current end, null for none): change it with setRoleExpiry, or remove it first. An end
date the deployment could not schedule is 503 expiry_schedule_failed (nothing granted; retry).
export declare function assignRole(client: PermissionsClient, userId: string, roleId: string, scope?: string | null, options?: AssignRoleOptions): Promise<AssignRoleResult>;AssignRoleOptions
Options for assignRole.
export interface AssignRoleOptions {
expiresAt?: string;
}AssignRoleResult
What assignRole did: alreadyAssigned when the user already held exactly this grant (nothing was written).
export interface AssignRoleResult {
alreadyAssigned: boolean;
}assignServicePrincipalRole
Grant a role to a service principal. scope=null is deployment-wide (machine grants normally are); else an org scope.
export declare function assignServicePrincipalRole(client: PermissionsClient, servicePrincipalId: string, roleId: string, scope?: string | null): Promise<void>;AuditEntry
An audit-log entry (the fields the AuditLog widget renders).
export interface AuditEntry {
id: string;
actor?: string;
identities?: Record<string, AuditIdentity>;
identitiesTruncated?: boolean;
identitiesWithheld?: boolean;
eventType?: string;
operation?: string;
targetType?: string;
targetId?: string;
scope?: string;
timestamp?: string;
[key: string]: unknown;
}AuditIdentity
One person (or the system) an audit entry is about, as known when the entry was written.
export interface AuditIdentity {
kind: 'user' | 'operator' | 'service' | 'system';
name?: string;
email?: string;
source?: 'token' | 'membership' | 'backfill:membership' | 'backfill:principal' | 'legacy:actorName';
resolvedAt?: string;
supportLabel?: string;
erased?: boolean;
}AuditPage
A page of audit entries + the opaque cursor for the next page (null when exhausted).
export interface AuditPage {
entries: AuditEntry[];
nextCursor: string | null;
}AuditQuery
Optional filters + pagination for the audit scope feed.
export interface AuditQuery {
cursor?: string;
actor?: string;
eventType?: string;
from?: string;
to?: string;
limit?: number;
}AuthConnector
export interface AuthConnector {
readonly authPool?: SessionAuthPool;
signInWithPassword(params: PasswordSignInParams): Promise<TokenSet>;
refresh(refreshToken: string, clientMetadata?: Record<string, string>): Promise<TokenSet>;
signOut(tokens: TokenSet): Promise<void>;
forClient?(clientId: string): AuthConnector;
}authErrorCode
The code an error carries: a UserServiceError's, an SDK error's code field, or a deployment trigger's refusal code.
export declare function authErrorCode(err: unknown): string | undefined;authErrorMessage
The message to show for err: overrides for its code first, then the built-in copy for typed refusals, Cognito
exceptions and a closed passkey prompt, then a UserMessageError's own copy, else fallback.
export declare function authErrorMessage(err: unknown, fallback: string, overrides?: Record<string, string>): string;AuthState
export interface AuthState {
status: AuthStatus;
tokens: TokenSet | null;
revoked?: true;
ssoSessionExpired?: true;
ssoEmail?: string;
emailChange?: EmailChangeNotice;
emailChangedTo?: string;
}AuthStatus
Sign-in / session lifecycle state.
export type AuthStatus = 'signed-out' | 'signed-in' | 'refreshing';BatchPermissionResult
A caller-scoped batch result: one PermissionResult per input check, in the SAME order as checks.
export interface BatchPermissionResult extends PermissionResult {
action: string;
resource: string;
}Boundary
A permission boundary (a ceiling on what its attached entities may do).
export interface Boundary {
id: string;
name?: string;
statements?: unknown[];
[key: string]: unknown;
}BreakGlassError
Break-glass sign-in could not answer: 429 (too many requests from this client), 503 (unavailable; retry), 404 (SSO is
off on this deployment), 400 (no email or code), 0 (the network failed). retryable when trying again later can help.
export interface BreakGlassError {
readonly "status": number;
readonly "code": string | undefined;
readonly "retryable": boolean;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const BreakGlassError: {
new (status: number, code: string | undefined, retryable: boolean): BreakGlassError;
};BreakGlassVerification
Using a break-glass code: the grant's expiry (epoch milliseconds), or PROOF_INVALID for a wrong, expired or used code.
export type BreakGlassVerification = {
ok: true;
expiresAt: number;
} | {
ok: false;
code: 'PROOF_INVALID';
};buildAuthorizeUrl
Build the exact /oauth2/authorize URL that links straight to provider (skips the Cognito login page).
export declare function buildAuthorizeUrl(params: { authServerUrl: string; clientId: string; provider: string; redirectUri: string; scopes: string[]; codeChallenge: string; state: string; nonce: string; prompt?: "login"; }): string;Capability
One (product, service, type) of the discovery view (GET /registry/capabilities).
export interface Capability {
product: string;
service: string;
serviceDisplayName: string;
type: string;
builtIn: boolean;
displayName: string;
description: string;
labelKey: string;
actions: CapabilityAction[];
}CapabilityAction
One action of a discovery-view type. Built-in actions also carry their label, purpose, intended audiences and risk — intended-use annotations that never change an authorization decision.
export interface CapabilityAction {
name: string;
displayName: string;
description: string;
labelKey: string;
label?: string;
purpose?: string;
audiences?: Array<'customer-admin' | 'customer-integration' | 'app-user' | 'service-internal' | 'instance-operator' | 'platform-operator'>;
risk?: 'dangerous' | 'sensitive';
riskReason?: string;
}ChallengeSupersededError
Thrown by a pending challenge's respond (MFA, new password) or a password reset's confirm after the session moved
on: another login method was selected or signed in with, or the session ended. The code never reaches any pool;
start the sign-in or reset again.
export interface ChallengeSupersededError {
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const ChallengeSupersededError: {
new (): ChallengeSupersededError;
};checkMyPermission
Ask "can I (the caller) do this?" — the authoritative check (deny precedence, scope merge,
conditions, XRN), scoped to the caller by the server from the verified token, never the body.
The optional active scope narrows the check to the selected project (scope=project:<projectId>,
§5.0.7); an explicit check.scope wins. The org is the token's mapped tenant — never sent here.
export declare function checkMyPermission(client: PermissionsClient, check: PermissionCheck, scope?: Scope | null): Promise<PermissionResult>;checkMyPermissions
Ask "can I do ALL of these?" in ONE round-trip — the caller-scoped multi check (POST /me/permissions/check with a checks array).
The server loads the caller's permissions doc once and decides every check, so N on-screen gates cost one
request instead of N. Each check is decided in its own scope: its scope, else the active project scope
(project:<projectId>, §5.0.7). Results come from the server's ordered decisions array, one per check in input
order. Fail-closed: a missing decision (or missing allowed) is allowed:false.
export declare function checkMyPermissions(client: PermissionsClient, checks: PermissionCheck[], scope?: Scope | null): Promise<BatchPermissionResult[]>;cleanResetFragment
Remove only our fragment segments. Callers preserve pathname, search and history.state.
export declare function cleanResetFragment(hash: string): string;clearTileStart
Remove the tile parameter from the address bar (other params and the hash stay), so a reload or Back never starts again.
export declare function clearTileStart(): void;CognitoConnectorConfig
export interface CognitoConnectorConfig {
region: string;
userPoolId: string;
clientId: string;
loginMethod?: LoginMethod;
now?: () => number;
ops?: CognitoOps;
passwordless?: {
apiBaseUrl: string;
relyingPartyId?: string;
relyingPartyName?: string;
};
passwordlessOps?: PasswordlessOps;
userServiceApiBase?: string;
fetch?: typeof fetch;
recoveryMode?: 'native' | 'server';
}CognitoDirectConnector
export interface CognitoDirectConnector {
readonly "authPool"?: SessionAuthPool | undefined;
"startMagicLink": (username: string, opts?: PasswordlessSignInOptions) => Promise<void>;
"completeMagicLinkFromUrl": (url?: string, opts?: PasswordlessSignInOptions) => Promise<TokenSet>;
"authenticateWithPasskey": (username?: string, opts?: PasskeySignInOptions) => Promise<TokenSet>;
"registerPasskey": (params: { idToken: string; friendlyName?: string; }, _opts?: PasswordlessSignInOptions) => Promise<void>;
"listPasskeys": (params: { idToken: string; }) => Promise<PasskeyCredential[]>;
"deletePasskey": (params: { idToken: string; credentialId: string; }) => Promise<void>;
"signInWithPassword": (params: PasswordSignInParams) => Promise<TokenSet>;
"enrollTotp": ({ accessToken }: { accessToken: string; }) => Promise<{ secret: string; }>;
"verifyTotp": ({ accessToken, code, deviceName }: { accessToken: string; code: string; deviceName?: string; }) => Promise<void>;
"setTotpPreference": ({ accessToken, enabled, preferred }: { accessToken: string; enabled: boolean; preferred?: boolean; }) => Promise<void>;
"requestEmailVerification": ({ accessToken }: { accessToken: string; }) => Promise<void>;
"confirmEmailVerification": ({ accessToken, code }: { accessToken: string; code: string; }) => Promise<{ email: string | null; verified: boolean; }>;
"requestEmailChange": ({ accessToken, email }: { accessToken: string; email: string; }) => Promise<void>;
"refresh": (refreshToken: string, clientMetadata?: Record<string, string>) => Promise<TokenSet>;
"forClient": (clientId: string) => CognitoDirectConnector;
"signOut": (tokens: TokenSet) => Promise<void>;
"signUp": ({ username, password, attributes, clientMetadata }: SignUpParams) => Promise<SignUpResult>;
"confirmSignUp": ({ username, code, clientMetadata }: { username: string; code: string; clientMetadata?: Record<string, string>; }) => Promise<void>;
"resendConfirmation": ({ username }: { username: string; }) => Promise<void>;
"forgotPassword": ({ username, loginMethod }: { username: string; loginMethod?: "email" | "phone"; }) => Promise<void>;
"confirmForgotPassword": ({ username, code, newPassword, loginMethod }: { username: string; code: string; newPassword: string; loginMethod?: "email" | "phone"; }) => Promise<void>;
"changePassword": ({ accessToken, oldPassword, newPassword }: { accessToken: string; oldPassword: string; newPassword: string; }) => Promise<void>;
"updateAttributes": ({ accessToken, attributes }: { accessToken: string; attributes: Record<string, string>; }) => Promise<void>;
}
export declare const CognitoDirectConnector: {
new (config: CognitoConnectorConfig): CognitoDirectConnector;
};CognitoOps
The cogneato operations this connector needs — injectable for tests.
export interface CognitoOps {
srpLogin: typeof srpLogin;
getTokensFromRefreshToken: typeof getTokensFromRefreshToken;
revokeToken: typeof revokeToken;
signUp: typeof signUp;
confirmSignUp: typeof confirmSignUp;
resendConfirmationCode: typeof resendConfirmationCode;
forgotPassword: typeof forgotPassword;
confirmForgotPassword: typeof confirmForgotPassword;
changePassword: typeof changePassword;
updateUserAttributes: typeof updateUserAttributes;
associateSoftwareToken: typeof associateSoftwareToken;
verifySoftwareToken: typeof verifySoftwareToken;
setUserMfaPreference: typeof setUserMfaPreference;
getUserAttributeVerificationCode: typeof getUserAttributeVerificationCode;
verifyUserAttribute: typeof verifyUserAttribute;
getUser: typeof getUser;
}completeInvitationRegistration
Prove the mailbox and create the account with the chosen password. A link invitation proves it with the mailed
code; an emailed invitation's link is the proof itself, so it completes without one (a link invitation without a
code is refused with code_required). Returns the invited email and no tokens: sign in next (e.g. Session.signIn).
POST /api/invitations/register/complete.
export declare function completeInvitationRegistration(options: RegistrationClientOptions, input: { token: string; code?: string; password: string; }): Promise<RegistrationCompleted>;completeSocialRedirect
Complete a social redirect. Returns null, touching nothing, when the URL has no state or the state is not a pending
transaction of this page (another app's callback). A load with no code, state or error is where Cognito's /logout
hop of an SSO sign-in returns: a fresh pending start (startSsoSignIn) is consumed once and the browser goes on to the
provider; without one nothing happens (and it resolves null either way). Otherwise the transaction is completed once: callers with the same
state share one attempt and its result, and a finished result is answered from the page's cache. A login is exchanged
and adopted into the Session matching the transaction's deployment; a link is posted to that deployment's user-service
as the principal that started it. On a final result the transaction is deleted and only this flow's params are removed
from the address bar.
export declare function completeSocialRedirect(url: string, options: CompleteSocialRedirectOptions): Promise<SocialRedirectResult | null>;CompleteSocialRedirectOptions
export interface CompleteSocialRedirectOptions {
sessions: SocialRedirectSessions;
store?: OAuthTransactionStore;
fetch?: typeof fetch;
crypto?: Crypto;
now?: () => number;
sessionWaitMs?: number;
pendingStartStore?: PendingSsoStartStore;
loadedAt?: number;
redirect?: (url: string) => void;
}ConnectedIdentity
One linked sign-in method on the account: a social identity, or (opted in) a native email/phone credential.
export interface ConnectedIdentity {
provider: string;
id: string;
primary: boolean;
loginMethod?: LoginMethod;
maskedIdentifier?: string;
credentialStatus?: CredentialStatus;
}ConnectIdentityResult
The result of starting a connect. Social: a redirect URL to the provider. Native (email/phone): no URL; the proof code
was sent to delivery.maskedIdentifier, and state + that code complete it with completeIdentityLink.
export interface ConnectIdentityResult {
authorizeUrl?: string | null;
state?: string;
delivery?: {
maskedIdentifier: string;
};
}connectorConfigFromDiscovery
The Cognito connector config a deployment's discovery document describes (passwordless only when it is on).
export declare function connectorConfigFromDiscovery(doc: DeploymentDiscovery): CognitoConnectorConfig;createApiKey
Mint an api key (POST /api-keys) — the response carries the raw key once.
export declare function createApiKey(client: PermissionsClient, input: CreateApiKeyInput): Promise<ApiKey>;CreateApiKeyInput
Input to mint a key.
export interface CreateApiKeyInput {
userId: string;
name: string;
permissions: {
allows: ApiKeyAllow[];
denies: ApiKeyAllow[];
};
scope?: Scope | null;
expiresAt?: string;
}createBoundary
Create a boundary (POST /boundaries) — statements are lint-validated server-side.
export declare function createBoundary(client: PermissionsClient, input: { name?: string; statements?: unknown[]; id?: string; }): Promise<Boundary>;createGrant
Create a grant (POST /grants). The grantor is the caller; the server enforces the grant ceiling.
export declare function createGrant(client: PermissionsClient, input: GrantInput): Promise<Grant>;createGroup
Create a group (POST /groups).
export declare function createGroup(client: PermissionsClient, input: { workspaceId: string; name?: string; id?: string; }): Promise<Group>;createInvitation
Create an invitation (POST /orgs/:id/invitations) for 1–20 grants. delivery: 'link' (the default) returns the
one-time token + link; delivery: 'email' returns a deliveryTicket for sendInvitationEmail and no token.
inviterName (1–100 characters) is named in the invite email. A role listed twice at one scope is refused with
ApiError 400 duplicate_grant (meta names the roleId and scope).
export declare function createInvitation(client: PermissionsClient, orgId: string, input: { email: string; grants: InvitationGrant[]; expiresAt?: string; delivery?: "link" | "email"; inviterName?: string; }): Promise<Invitation>;createMyApiKey
Mint a key owned by the caller (POST /me/api-keys), capped at the caller's own permissions; the raw key comes back once.
export declare function createMyApiKey(client: PermissionsClient, input: CreateMyApiKeyInput): Promise<ApiKey>;CreateMyApiKeyInput
Input to mint a key owned by the caller: the owner is always the signed-in caller.
export type CreateMyApiKeyInput = Omit<CreateApiKeyInput, 'userId'>;createOrganization
Create an organization (POST /orgs).
export declare function createOrganization(client: PermissionsClient, input: { name: string; id?: string; }): Promise<OrgCreated>;createPermissionsClient
Create a headless Permissions client. No React, no DOM — safe in browsers, workers, and Node 18+.
export declare function createPermissionsClient(options: PermissionsClientOptions): PermissionsClient;createRole
Create a role in an org (POST /roles) and return it. Role ids are global across orgs, so pass undefined for id to
have the server mint a unique one (then name the role with updateRole). permissions optional.
export declare function createRole(client: PermissionsClient, id: string | undefined, orgId: string, permissions?: Permission[]): Promise<Role>;createSessionPermissionsClient
A Permissions client bound to a live Session: every request carries the session's current
Permissions bearer (getPermissionsBearer() — the ID token, or the active scoped session token),
refreshed as needed. Composes
export declare function createSessionPermissionsClient(session: Session, options: SessionPermissionsClientOptions): PermissionsClient;createSignInFlow
export declare function createSignInFlow(initial: SignInFlowOptions): SignInFlow;createSignUpFlow
export declare function createSignUpFlow(initial: SignUpFlowOptions): SignUpFlow;createSsoPasskey
Create a step-up passkey from the server's creation options (UserServiceClient.ssoPasskeyOptions) and answer the body registerSsoPasskey saves. Throws when the person cancels.
export declare function createSsoPasskey(params: { publicKey: Json; friendlyName: string; credentials?: CredentialsContainer; }): Promise<SsoPasskeyRegistration>;CreateUserInput
export interface CreateUserInput {
email: string;
name?: string;
soid?: string;
suid?: string;
password?: string;
delivery?: 'none' | 'invitation';
}CreateUserResult
201 created, 200 replayed (or the user already existed with this suid), 202 unfinished: follow the operation, or
retry with the same key and body to resume a failed component. user is null until its identity exists.
export interface CreateUserResult {
status: 200 | 201 | 202;
user: AdminUser | null;
operation: UserOperation;
}createUsersAdminClient
Create an admin users client for one deployment.
export declare function createUsersAdminClient(options: UsersAdminClientOptions): UsersAdminClient;credentialPendingMfa
The login method whose MFA enrollment the session's credential still has to complete (its server-stamped
custom:login_state is mfa_required, or enrollment from an enrollment-only client), else null. Email-only sessions
carry no binding and never need it.
export declare function credentialPendingMfa(tokens: TokenSet | null): LoginMethod | null;CredentialStatus
A native sign-in method's lifecycle state. enrollment_required = active but its MFA enrollment is not complete yet.
export type CredentialStatus = 'pending' | 'active' | 'enrollment_required' | 'disconnected';decodeDeploymentDiscovery
export declare function decodeDeploymentDiscovery(raw: unknown): DeploymentDiscovery;decodeDiscovery
Decode a raw /api/auth/config response into a validated, versioned DiscoveryConfig. Throws on malformed.
export declare function decodeDiscovery(raw: unknown): DiscoveryConfig;decodeDiscoveryBrand
The brand's renderable fields: non-empty names, an https logo and a #RRGGBB color; undefined when none is left.
export declare function decodeDiscoveryBrand(raw: unknown): DiscoveryBrand | undefined;decodeJwtPayload
Decode a JWT payload (base64url) without verifying — returns {} on any error.
export declare function decodeJwtPayload(token: string): Record<string, unknown>;decodeResetLogin
export declare function decodeResetLogin(value: string): string;DEFAULT_STORAGE_KEY
Default storage key, namespaced so it never collides with host app keys.
export declare const DEFAULT_STORAGE_KEY: "saaslayer.session";deleteBoundary
Delete a boundary (DELETE /boundaries/:id).
export declare function deleteBoundary(client: PermissionsClient, id: string): Promise<void>;deleteGroup
Delete a group (DELETE /groups/:id).
export declare function deleteGroup(client: PermissionsClient, id: string): Promise<void>;deleteInvitation
Revoke a pending invitation by its id (DELETE /orgs/:id/invitations/:invitationId).
export declare function deleteInvitation(client: PermissionsClient, orgId: string, invitationId: string): Promise<void>;deleteRole
Delete a role (DELETE /roles/:id). Preview with getRoleDeleteImpact first.
export declare function deleteRole(client: PermissionsClient, roleId: string): Promise<void>;denyAccessRequest
Deny an access request (POST /access-requests/:id/deny). The denier is the caller.
export declare function denyAccessRequest(client: PermissionsClient, id: string, input?: { reason?: string; }): Promise<AccessRequest>;DeploymentDiscovery
export interface DeploymentDiscovery {
contractVersion: number;
deploymentId: string;
revision: string | null;
region: string;
userPoolId: string;
clientId: string;
issuer: string;
audience: string[];
jwksUrl: string;
hostedLoginUrl: string;
usersApiBase: string;
permissionsApiBase: string;
passwordlessApiBase: string | null;
}DeploymentDiscoveryError
export interface DeploymentDiscoveryError {
"code": string;
"output"?: string | undefined;
"status"?: number | undefined;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const DeploymentDiscoveryError: {
new (code: string, message: string, extra?: { output?: string; status?: number; }): DeploymentDiscoveryError;
};deploymentDiscoveryUrl
export declare function deploymentDiscoveryUrl(target: DiscoveryTarget): string;discoverSignInRoute
Ask the deployment's user-service where email signs in (POST /api/auth/sso/discover). A domain decides where to sign
in, never membership. Throws SignInDiscoveryError when discovery cannot answer.
export declare function discoverSignInRoute(params: { userServiceApiBase: string; email: string; fetch?: typeof fetch; }): Promise<SignInRoute>;DISCOVERY_CONTRACT_VERSION
export declare const DISCOVERY_CONTRACT_VERSION: 2;DISCOVERY_SCHEMA_VERSION
Bumped when the client descriptor shape changes; carried at runtime for forward-compat checks.
export declare const DISCOVERY_SCHEMA_VERSION: 1;DiscoveryAuthPool
One ready login pool of an opted-in deployment: its login method, role and login client (never an enrollment client).
export interface DiscoveryAuthPool {
loginMethod: LoginMethod;
role: 'primary' | 'secondary';
userPoolId: string;
clientId: string;
region: string;
capabilities: DiscoveryAuthPoolCapabilities;
smsAllowedCountries?: string[];
smsStartNumber?: string;
transport?: DiscoveryPoolTransport;
challenge?: DiscoveryChallengeConfig;
}DiscoveryAuthPoolCapabilities
What one ready login pool offers (opted-in deployments): only the email primary has social, hosted UI and passwordless.
export interface DiscoveryAuthPoolCapabilities {
password: boolean;
social: boolean;
hosted: boolean;
passwordless: boolean;
identityPoolCredentials: boolean;
smsOtp?: boolean;
}DiscoveryBrand
The deployment's sign-in brand: only the fields that are set and safe to render (an https logo, a #RRGGBB color).
export interface DiscoveryBrand {
companyName?: string;
productName?: string;
logoUrl?: string;
primaryColor?: string;
}DiscoveryChallengeConfig
The public browser config of a gateway pool's invisible challenge (never its secret).
export interface DiscoveryChallengeConfig {
provider: 'turnstile';
siteKey: string;
actions: {
start: string;
resend: string;
};
}DiscoveryConfig
The public discovery descriptor (GET /api/auth/config), the source of the OAuth coordinates.
export interface DiscoveryConfig {
schemaVersion: number;
authServerUrl: string;
clientId: string;
region?: string;
userPoolId?: string;
callbackUrls?: string[];
providers: SocialProviderInfo[];
scopes?: string[];
passwordAuthAllowed: boolean;
passwordless: PasswordlessCapability;
mfa?: {
required: boolean;
methods: string[];
};
userServiceApiBase?: string;
recoveryMode?: 'native' | 'server';
primaryLoginMethod?: LoginMethod;
loginMethods?: LoginMethod[];
authPools?: {
schemaVersion: 1 | 2;
capabilityRevision: number;
pools: DiscoveryAuthPool[];
};
transport?: DiscoveryPoolTransport;
challenge?: DiscoveryChallengeConfig;
emailFirst?: boolean;
brand?: DiscoveryBrand;
}DiscoveryInstances
export interface DiscoveryInstances {
'user-service'?: string;
'permissions-service'?: string;
}DiscoveryPoolTransport
How a pool's sign-in reaches Cognito: cognito = the SDK calls Cognito directly; gateway = only the user-service gateway routes.
export type DiscoveryPoolTransport = 'cognito' | 'gateway';DiscoveryTarget
export type DiscoveryTarget = {
url: string;
refreshSeconds?: number;
} | {
apiBase: string;
deploymentId: string;
instances?: DiscoveryInstances;
};domainChallenge
The DNS TXT record that proves control of a domain for this connection (from its entry's own token).
export declare function domainChallenge(entry: { domain: string; token: string; }): { type: "TXT"; name: string; value: string; };EffectivePermissionEntry
One flattened effective permission entry.
export interface EffectivePermissionEntry {
action?: string;
resource?: string;
service?: string;
effect?: string;
scope?: string;
expandedFrom?: string;
[key: string]: unknown;
}EffectivePermissions
A principal's flattened effective permissions (GET /permissions/effective).
export interface EffectivePermissions {
id: string;
principalId: string;
principalType: string;
entries: EffectivePermissionEntry[];
summary: EffectivePermissionsSummary;
[key: string]: unknown;
}EffectivePermissionsQuery
Query for a principal's effective permissions.
export interface EffectivePermissionsQuery {
principalId: string;
principalType?: string;
scope?: string;
action?: string;
}EffectivePermissionsSummary
The rolled-up counts for a principal's effective state.
export interface EffectivePermissionsSummary {
totalAllows: number;
totalDenies: number;
grantCount: number;
[key: string]: unknown;
}EmailChangeNotice
See AuthState.emailChange.
export type EmailChangeNotice = 'changed' | 'finishing' | 'sign-in-to-finish' | 'link-refused';encodeResetLogin
export declare function encodeResetLogin(email: string): string;EngineTokens
Tokens as the passwordless engine returns them (note: expireAt is a Date, not epoch ms).
export interface EngineTokens {
idToken?: string;
accessToken?: string;
refreshToken?: string;
expireAt?: Date;
}explainMyPermission
"Why can (or can't) I do this?" — the caller-scoped decision WITH its explanation (reason, effect, contributing sources, condition results, near-miss). Powers the authorize-debugger widget (#179).
export declare function explainMyPermission(client: PermissionsClient, check: PermissionCheck, scope?: Scope | null): Promise<PermissionExplanation>;fetchDeploymentDiscovery
export declare function fetchDeploymentDiscovery(target: DiscoveryTarget, options?: { fetch?: typeof fetch; }): Promise<DeploymentDiscovery>;fetchDiscoveryConfig
Fetch the public discovery descriptor (no bearer). CORS must allow the widget origin (E1).
export declare function fetchDiscoveryConfig(userServiceApiBase: string, fetchImpl?: typeof fetch): Promise<DiscoveryConfig>;fragmentOf
Extract the URL fragment (after #) from a full URL, or undefined when there is none.
export declare function fragmentOf(url?: string): string | undefined;GatewayConnector
Signs in with SMS codes through the user-service gateway, which holds the Cognito client secret (this never does). Passwords, password reset, attribute changes and authenticator setup are refused with POLICY_DISABLED, as the server refuses them on such a deployment.
export interface GatewayConnector {
readonly "authPool": SessionAuthPool;
"startPhoneSignIn": (params: { phoneNumber: string; challengeToken?: string; }) => Promise<PhoneSignInChallenge>;
"verifyPhoneSignIn": (params: { challengeId: string; code: string; }) => Promise<{ tokens: TokenSet; created: boolean; }>;
"resendPhoneSignIn": (params: { challengeId: string; challengeToken?: string; }) => Promise<PhoneSignInChallenge>;
"signInWithPassword": (_params: PasswordSignInParams) => Promise<TokenSet>;
"signUp": () => Promise<SignUpResult>;
"confirmSignUp": () => Promise<void>;
"resendConfirmation": () => Promise<void>;
"forgotPassword": () => Promise<void>;
"confirmForgotPassword": () => Promise<void>;
"changePassword": () => Promise<void>;
"updateAttributes": () => Promise<void>;
"enrollTotp": () => Promise<{ secret: string; }>;
"verifyTotp": () => Promise<void>;
"setTotpPreference": () => Promise<void>;
"refresh": (refreshToken: string, clientMetadata?: Record<string, string>) => Promise<TokenSet>;
"signOut": (tokens: TokenSet) => Promise<void>;
}
export declare const GatewayConnector: {
new (config: GatewayConnectorConfig): GatewayConnector;
"fromDiscovery": (discovery: DiscoveryConfig | null | undefined, base?: Partial<Omit<GatewayConnectorConfig, "authPool">>) => GatewayConnector | null;
};GatewayConnectorConfig
export interface GatewayConnectorConfig {
userServiceApiBase: string;
authPool: SessionAuthPool;
fetch?: typeof fetch;
}getEffectivePermissions
A principal's flattened effective permissions — bound server-side to the target's owning scope.
export declare function getEffectivePermissions(client: PermissionsClient, q: EffectivePermissionsQuery): Promise<EffectivePermissions>;getIdentityPoolCredentials
Temporary AWS credentials for the signed-in user from a Cognito identity pool (GetId + GetCredentialsForIdentity).
export declare function getIdentityPoolCredentials(options: IdentityPoolCredentialsOptions): Promise<IdentityPoolCredentials>;getMyEffectivePermissions
The signed-in caller's own effective permissions in one org (GET /me/permissions/effective, self-service). With expand 'registry' the entries also list the registered permissions each held wildcard covers, marked expandedFrom.
export declare function getMyEffectivePermissions(client: PermissionsClient, q: { scope: string; action?: string; expand?: "registry"; }): Promise<EffectivePermissions>;getOrgMemberRemovalImpact
Preview the blast radius of removing an org member (GET .../removal-impact) — orphan warnings etc.
export declare function getOrgMemberRemovalImpact(client: PermissionsClient, orgId: string, memberId: string): Promise<Record<string, unknown>>;getRole
A single role (GET /roles/:id).
export declare function getRole(client: PermissionsClient, roleId: string): Promise<Role>;getRoleDeleteImpact
Preview the blast radius of deleting a role (GET /roles/:id/delete-impact).
export declare function getRoleDeleteImpact(client: PermissionsClient, roleId: string): Promise<Record<string, unknown>>;getSsoGroupMapping
The connection's group mapping set in its tenant org (Permissions API), or null while the deployment owner has set no ceiling for it. Needs sso-connection:read in that org.
export declare function getSsoGroupMapping(client: PermissionsClient, params: { connectionId: string; orgId: string; }): Promise<SsoGroupMapping | null>;getSsoPasskeyAssertion
Sign the server's step-up challenge (UserServiceClient.ssoStepUpOptions) with a step-up passkey and answer the assertion stepUpSso takes. Throws when the person cancels.
export declare function getSsoPasskeyAssertion(params: { publicKey: Json; credentials?: CredentialsContainer; }): Promise<SsoPasskeyAssertion>;Grant
A direct grant to a principal.
export interface Grant {
id?: string;
granteeType?: GranteeType;
granteeId?: string;
action?: string;
service?: string;
resourceType?: string;
resourceId?: string;
scope?: string;
grantedBy?: string;
expiresAt?: string;
[key: string]: unknown;
}GrantInput
Input to create a grant.
export interface GrantInput extends GrantKey {
expiresAt?: string;
}Group
A group (collection of principals) within a workspace.
export interface Group {
id: string;
workspaceId?: string;
name?: string;
[key: string]: unknown;
}IdentityDisconnection
The result of a disconnect. A native method also answers the account revocation the removal ran.
export interface IdentityDisconnection {
disconnected: true;
loginMethod?: LoginMethod;
securityRevocation?: SecurityRevocation;
}IdentityLinkResult
The result of completing a connect (link-callback).
export interface IdentityLinkResult {
linked: true;
alreadyLinked?: boolean;
loginMethod?: LoginMethod;
credentialStatus?: CredentialStatus;
}IdentityMfaCompletion
MFA enrollment completed: the next sign-in with this method is MFA-challenged and fully active.
export interface IdentityMfaCompletion {
loginMethod: LoginMethod;
credentialStatus: 'active';
}IdentityPoolCredentials
export interface IdentityPoolCredentials {
accessKeyId: string;
secretAccessKey: string;
sessionToken: string;
expiration: Date;
}IdentityPoolCredentialsOptions
export interface IdentityPoolCredentialsOptions {
region: string;
identityPoolId: string;
userPoolId: string;
idToken: string;
}IMPERSONATION_PERMISSION
The registered impersonation permission (product:service:type:action).
export declare const IMPERSONATION_PERMISSION: "saaslayer:users:account:impersonate";impersonationCheck
The check that gates starting a view-as in orgId: on one target (account/<suid>) or on login accounts in general.
export declare function impersonationCheck(orgId: string, targetSuid?: string): PermissionCheck;ImpersonationMode
How a session views as someone: view-only refuses every write; act-as allows writes (reserved operations stay refused).
export type ImpersonationMode = 'view-only' | 'act-as';ImpersonationTarget
The person a session views as, the org the impersonation is bounded to, and the mode asked for at the start.
export interface ImpersonationTarget {
targetSuid: string;
orgId: string;
mode?: ImpersonationMode;
}Invitation
An org invitation. A link invitation returns token and link only on create; an emailed one never returns them and
returns deliveryTicket on create instead (hand it to sendInvitationEmail).
export interface Invitation {
id: string;
orgId: string;
email: string;
grants: InvitationGrant[];
status: 'pending' | 'accepting' | 'accepted' | 'revoked' | 'expired';
expiresAt: string;
createdAt?: string;
createdBy?: string | null;
acceptedBy?: string | null;
delivery: 'link' | 'email';
deliveryExchanges?: number;
lastDeliveryAt?: string | null;
token?: string;
link?: string | null;
deliveryTicket?: string;
}InvitationAcceptance
The outcome of accepting an invitation: the org joined and the grants received.
export interface InvitationAcceptance {
orgId: string;
grants: InvitationGrant[];
userId: string;
acceptedAt?: string;
recovered?: boolean;
skipped?: Array<{
roleId: string;
scope: string;
reason: 'already_held';
}>;
}InvitationDeliveryError
A delivery refusal. The message is safe to display; cause is for local debugging and may contain secrets.
export interface InvitationDeliveryError {
readonly "code": InvitationDeliveryErrorCode;
readonly "status": number;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const InvitationDeliveryError: {
new (code: InvitationDeliveryErrorCode, status: number, options?: ErrorOptions): InvitationDeliveryError;
};InvitationDeliveryErrorCode
Stable refusal codes of an emailed invitation's delivery (plus client-side network / unknown).
export type InvitationDeliveryErrorCode = 'delivery_ticket_invalid' | 'invitation_not_pending' | 'delivery_limit_reached' | 'email_not_sent' | 'network' | 'unknown';InvitationGrant
One role an invitation grants, at a scope (the org, or a typed scope such as site:<orgId>:<id>).
export interface InvitationGrant {
roleId: string;
scope: string;
expiresAt?: string;
}InvitationPreview
What an invitation offers, from the public token-bound preview, and the invited email (only that one).
export interface InvitationPreview {
id: string;
orgId: string;
orgName: string | null;
email: string;
grants: Array<InvitationGrant & {
roleLabel: string;
}>;
expiresAt: string;
delivery: 'link' | 'email';
}isAccountScope
Whether scope is the account (org-wide) scope of orgId.
export declare function isAccountScope(scope: string | null | undefined, orgId: string): boolean;isMaintenanceError
A Permissions API admin maintenance answer (503 maintenance): retryable, never a deny or a permission error.
export declare function isMaintenanceError(err: unknown): err is ApiError;isPasswordResetRequired
Whether an error means "this user must reset their password": our typed error or Cognito's raw one.
export declare function isPasswordResetRequired(err: unknown): boolean;isRecentAuthRequired
Thrown/mapped when a passkey mutation needs recent authentication (server fresh-auth policy).
export declare function isRecentAuthRequired(err: unknown): boolean;isSsoSession
Whether a token is an SSO session: its identities claim names an SSO connection's provider, or it carries any SSO
claim (well formed or not, so a malformed one never reads as native).
export declare function isSsoSession(claims: Record<string, unknown> | null | undefined): boolean;issueInvitationDeliveryTicket
Issue a fresh delivery ticket for an emailed invitation, to send it again (POST /orgs/:id/invitations/:invitationId/
delivery-ticket). It supersedes any unspent ticket; the current link keeps working until the new ticket is sent.
A 409 invitation_not_pending or delivery_limit_reached is thrown as InvitationDeliveryError; other refusals
(403, 404, 400 for a link invitation) as the Permissions ApiError.
export declare function issueInvitationDeliveryTicket(client: PermissionsClient, orgId: string, invitationId: string): Promise<{ deliveryTicket: string; }>;listAccessRequests
List access requests (GET /access-requests).
export declare function listAccessRequests(client: PermissionsClient, q?: AccessRequestQuery): Promise<AccessRequestPage>;listApiKeys
The caller's own api keys (GET /api-keys?userId=).
export declare function listApiKeys(client: PermissionsClient, userId: string): Promise<ApiKey[]>;listAuditByScope
Org-scoped audit feed (GET /audit/scope/:scope) — scope-authorized server-side (S3).
export declare function listAuditByScope(client: PermissionsClient, scope: string, query?: AuditQuery): Promise<AuditPage>;listBoundaries
All boundaries (GET /boundaries).
export declare function listBoundaries(client: PermissionsClient): Promise<Boundary[]>;listGroupMembers
A group's members (GET /groups/:id/members).
export declare function listGroupMembers(client: PermissionsClient, groupId: string): Promise<Member[]>;listGroups
Groups in a workspace (GET /groups?workspaceId=).
export declare function listGroups(client: PermissionsClient, workspaceId: string): Promise<Group[]>;listInvitations
List an org's invitations (GET /orgs/:id/invitations) — no token material.
export declare function listInvitations(client: PermissionsClient, orgId: string): Promise<Invitation[]>;listMyApiKeys
The signed-in caller's own api keys (GET /me/api-keys, self-service: no keys:* permission needed).
export declare function listMyApiKeys(client: PermissionsClient): Promise<ApiKey[]>;listMyOrganizations
The authenticated caller's own orgs + projects, as two flat lists (v1 — no org→project nesting; the caller-scoped payload carries no parent-org link). The server scopes to the caller from the verified token, never a request body. This is the ONLY org source a widget may read.
export declare function listMyOrganizations(client: PermissionsClient): Promise<MyOrganizations>;listOrgMembers
Members of an organization (GET /orgs/:orgId/members); includeRoles adds each member's direct org roles.
export declare function listOrgMembers(client: PermissionsClient, orgId: string, options?: { includeRoles?: boolean; }): Promise<Member[]>;listPendingReviews
Requests the given user can review (GET /access-requests/pending-reviews).
export declare function listPendingReviews(client: PermissionsClient, userId: string): Promise<AccessRequest[]>;listProjectMembers
Members of a project, which is a Permissions workspace (GET /workspaces/:projectId/members).
export declare function listProjectMembers(client: PermissionsClient, projectId: string): Promise<Member[]>;listResourceRegistry
The service›resource›action registry — built-in (saaslayer) and customer types together, from the discovery view (GET /registry/capabilities) — flattened to one labelled entry per action: the matrix's column/row source.
export declare function listResourceRegistry(client: PermissionsClient): Promise<RegistryEntry[]>;listRolePermissions
The permissions attached to a role (GET /roles/:id/permissions).
export declare function listRolePermissions(client: PermissionsClient, roleId: string): Promise<unknown[]>;listRoles
Roles defined in an organization (GET /roles?orgId=:orgId).
export declare function listRoles(client: PermissionsClient, orgId: string): Promise<Role[]>;listServicePrincipalRoles
A service principal's role assignments (GET /principals/serviceAccount/:id/roles).
export declare function listServicePrincipalRoles(client: PermissionsClient, servicePrincipalId: string): Promise<RoleAssignment[]>;listUserGrants
A principal's direct grants (GET /grants/user/:granteeId — bound to the grantee's owning scope).
export declare function listUserGrants(client: PermissionsClient, granteeId: string, filter?: { action?: string; resourceType?: string; scope?: string; }): Promise<Grant[]>;listUserRoles
A user's role assignments (GET /users/:id/roles).
export declare function listUserRoles(client: PermissionsClient, userId: string): Promise<RoleAssignment[]>;localTokenStorage
Persist the session in localStorage — survives reloads + shared across tabs (the default). Without a key, a Session
whose primary connector names its authPool keeps it under saaslayer.session.<primaryUserPoolId>.
export declare function localTokenStorage(key?: string): TokenStorage;loginConnectorConfigs
The connector configs discovery (GET /api/auth/config) describes over the host's base config. A field base omits
(pool coordinates, user-service base, passwordless coordinates) comes from the descriptor; with no pool coordinates from
either, it throws. Without opted-in fields there is no secondary. Opted in: the primary names the permanent primary login
method (from the ready primary pool's coordinates when listed) and keeps passwordless only when that pool offers it; a
ready secondary pool gets its own connector with password sign-in and recovery only. A pending pool is never listed, so
it gets no connector. A schema 2 descriptor with a gateway pool (or no ready primary) throws instead.
export declare function loginConnectorConfigs(discovery: DiscoveryConfig | null | undefined, base?: Partial<CognitoConnectorConfig>): LoginConnectorConfigs;LoginConnectorConfigs
The connector configs for a Session: the primary's, and the ready secondary's (opted-in deployments).
export interface LoginConnectorConfigs {
primary: CognitoConnectorConfig;
secondary?: CognitoConnectorConfig;
}LoginMethod
A native sign-in method of the deployment's own pools (opted-in deployments).
export type LoginMethod = 'email' | 'phone';loginMethodsOf
The login methods session and discovery offer.
export declare function loginMethodsOf(session: Session, discovery: DiscoveryConfig | null | undefined): LoginMethodsView;LoginMethodsView
The login methods a sign-in, sign-up or recovery form offers.
export interface LoginMethodsView {
optedIn: boolean;
methods: LoginMethod[];
primary: LoginMethod;
preferred: LoginMethod;
}machinePrincipalId
The service principal id a declared IAM principal acts as (SERVICE_ACCOUNT#iam.<principalId>).
export declare function machinePrincipalId(iamPrincipalId: string): string;MaintenanceRetryOptions
Waiting out the Permissions API's admin maintenance gate (503, error code maintenance, Retry-After).
export interface MaintenanceRetryOptions {
baseDelayMs?: number;
maxWaitMs?: number;
sleep?: (ms: number) => Promise<void>;
}Member
A member of an org/project container; the container is named by orgId, workspaceId (a project) or groupId.
export interface Member {
id: string;
type?: string;
principalType?: string;
orgId?: string;
workspaceId?: string;
groupId?: string;
email?: string;
displayName?: string;
roles?: string[];
createdAt?: string;
[key: string]: unknown;
}memoryStorage
In-memory (closure) storage: highest security — the TokenSet never leaves JS memory, so nothing survives a reload or reaches another tab. Use when no persistence is wanted.
export declare function memoryStorage(): TokenStorage;memoryTransactionStore
An in-memory transaction store (tests / non-redirect flows).
export declare function memoryTransactionStore(): OAuthTransactionStore;MfaConnector
TOTP MFA self-service (M1.2) for a signed-in user. Enroll -> render the secret as a QR -> verify a code -> set as preferred. Cognito-direct via the connector; backs the <UserProfile> security page.
export interface MfaConnector {
enrollTotp(params: {
accessToken: string;
}): Promise<{
secret: string;
}>;
verifyTotp(params: {
accessToken: string;
code: string;
deviceName?: string;
}): Promise<void>;
setTotpPreference(params: {
accessToken: string;
enabled: boolean;
preferred?: boolean;
}): Promise<void>;
}MfaRequiredError
Thrown by signInWithPassword when the pool challenges for a TOTP/SMS code. Carries a bound
continuation: the caller prompts for the code and calls respond(code) to complete sign-in.
When thrown out of Session.signIn, respond also stores the resulting tokens in the session.
export interface MfaRequiredError {
readonly "isMfaRequired": true;
readonly "code": string;
readonly "respond": (mfaCode: string) => Promise<TokenSet>;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const MfaRequiredError: {
new (code: string, respond: (mfaCode: string) => Promise<TokenSet>): MfaRequiredError;
};MfaReset
What an MFA reset removed: passkeys deleted, whether Cognito TOTP/SMS MFA was on, and the sign-out everywhere.
export interface MfaReset {
passkeysRemoved: number;
cognitoMfaDisabled: boolean;
signedOut: boolean;
}MfaStatus
The MFA self-service view (GET /api/profile/mfa).
export interface MfaStatus {
enrolled: boolean;
required: boolean;
methods: string[];
recoveryCodesRemaining: number;
}MyOrganizations
The authenticated caller's own orgs + projects — the two-level switcher surface (M0.9).
export interface MyOrganizations {
organizations: OrgRef[];
projects: OrgRef[];
}NewPasswordRequiredError
Thrown by signInWithPassword when the pool requires the user to set a new password before the first
real sign-in (Cognito NEW_PASSWORD_REQUIRED — e.g. an admin-created / temporary-password user). Carries
a bound continuation: the caller prompts for a new password and calls respond(newPassword) to complete
sign-in. When thrown out of Session.signIn, respond also stores the resulting tokens in the session.
export interface NewPasswordRequiredError {
readonly "isNewPasswordRequired": true;
readonly "respond": (newPassword: string) => Promise<TokenSet>;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const NewPasswordRequiredError: {
new (respond: (newPassword: string) => Promise<TokenSet>): NewPasswordRequiredError;
};OAuthCallbackError
Thrown when the provider redirected back with ?error= — the session is left untouched.
export interface OAuthCallbackError {
readonly "isOAuthCallbackError": true;
readonly "error": string;
readonly "description"?: string | undefined;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const OAuthCallbackError: {
new (error: string, description?: string | undefined): OAuthCallbackError;
};OAuthNonceError
Thrown when the ID token's nonce does not match the transaction nonce (token-injection guard).
export interface OAuthNonceError {
readonly "isOAuthNonceError": true;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const OAuthNonceError: {
new (): OAuthNonceError;
};OAuthStateError
Rejected before token exchange when the callback state is missing, mismatched, expired, or replayed.
export interface OAuthStateError {
readonly "isOAuthStateError": true;
readonly "reason": "missing" | "expired" | "replayed";
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const OAuthStateError: {
new (reason: "missing" | "expired" | "replayed"): OAuthStateError;
};OAuthTransaction
One in-flight OAuth round trip: bound to a random state, held until the provider redirects back. A login carries its PKCE verifier and nonce; a link keeps both server-side and names the principal that started it.
export interface OAuthTransaction {
state: string;
codeVerifier?: string;
redirectUri: string;
provider: string;
nonce?: string;
createdAt: number;
expiresAt: number;
intent?: 'login' | 'link';
authServerUrl?: string;
clientId?: string;
appClientId?: string;
userServiceApiBase?: string;
serviceRef?: string;
principal?: string;
}OAuthTransactionStore
A short-lived, single-use store for the in-flight OAuth transaction. Persisted across the provider
redirect (default: sessionStorage). consume MUST remove the entry so a replayed state finds nothing.
export interface OAuthTransactionStore {
save(txn: OAuthTransaction): void;
load(state: string): OAuthTransaction | null;
consume(state: string): OAuthTransaction | null;
}openSetupLink
Open an IT admin's setup link: post its token (never in a URL) and receive a new management session for the link's connection. Every refusal (invalid, expired, revoked, replaced or completed link) answers alike.
export declare function openSetupLink(params: { apiBase: string; token: string; fetch?: typeof fetch; }): Promise<{ token: string; session: SsoManagementSession; }>;openSocialPopup
Open the popup a social sign-in will use. Call it synchronously in the click handler, before anything is awaited, or the browser blocks it. Null when it was blocked.
export declare function openSocialPopup(win?: PopupWindow | undefined): PopupWindow | null;OrgCreated
A created organization (POST /orgs).
export interface OrgCreated {
id: string;
name?: string;
[key: string]: unknown;
}OrgRef
A caller-scoped org/project reference (from GET /me/organizations).
export interface OrgRef {
id: string;
name?: string;
personal?: boolean;
createdAt?: string;
}parseResetLink
export declare function parseResetLink(hash: string): ResetLink;parseSiteScope
Parse a site scope; null for anything that isn't site:<orgId>:<siteId>.
export declare function parseSiteScope(scope: string | null | undefined): { orgId: string; siteId: string; } | null;parseTypedScope
Parse <kind>:<orgId>:<id>; null for bare org ids, legacy project:<id>, or malformed values.
export declare function parseTypedScope(scope: string | null | undefined): TypedScope | null;PasskeyCredential
A registered passkey (WebAuthn credential) as shown in management UI.
export interface PasskeyCredential {
credentialId: string;
friendlyName?: string;
createdAt?: string;
lastSignIn?: string;
[key: string]: unknown;
}PasskeySignInOptions
export interface PasskeySignInOptions extends PasswordlessSignInOptions {
mediation?: 'conditional';
onSigningIn?: () => void;
}PasswordlessBusyError
Thrown when a passwordless ceremony starts while another is already running (D9).
export interface PasswordlessBusyError {
readonly "isPasswordlessBusy": true;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const PasswordlessBusyError: {
new (): PasswordlessBusyError;
};PasswordlessCapability
Passwordless capability from discovery — a lane is offered only when its coordinates are present.
export interface PasswordlessCapability {
magicLink: boolean;
passkey: boolean;
apiBaseUrl?: string;
relyingPartyId?: string;
relyingPartyName?: string;
}PasswordlessConnector
A connector that also offers passwordless sign-in (magic-link + passkey). Kept separate from AuthConnector so a password-only connector stays valid; Session gains the passwordless paths only when its connector implements this (see supportsPasswordless).
export interface PasswordlessConnector extends AuthConnector {
startMagicLink(username: string, opts?: PasswordlessSignInOptions): Promise<void>;
completeMagicLinkFromUrl(url?: string, opts?: PasswordlessSignInOptions): Promise<TokenSet>;
authenticateWithPasskey(username?: string, opts?: PasskeySignInOptions): Promise<TokenSet>;
registerPasskey(params: {
idToken: string;
friendlyName?: string;
}, opts?: PasswordlessSignInOptions): Promise<void>;
listPasskeys(params: {
idToken: string;
}): Promise<import('./passwordless').PasskeyCredential[]>;
deletePasskey(params: {
idToken: string;
credentialId: string;
}): Promise<void>;
}PasswordlessOps
The passwordless engine ops the connector calls — injectable so the connector is testable.
export interface PasswordlessOps {
configure: (config: Record<string, unknown>) => unknown;
requestSignInLink: (args: {
username: string;
redirectUri?: string;
}) => {
signInLinkRequested: Promise<unknown>;
abort: () => void;
};
signInWithLink: (args: {
fragmentIdentifier?: string;
tokensCb?: (t: EngineTokens) => void;
}) => {
signedIn: Promise<EngineTokens | undefined>;
abort: () => void;
};
authenticateWithFido2: (args: {
username?: string;
mediation?: 'conditional';
statusCb?: (status: string) => void;
}) => {
signedIn: Promise<EngineTokens | undefined>;
abort: () => void;
};
fido2CreateCredential: (args: {
friendlyName?: string;
}) => Promise<unknown>;
fido2ListCredentials: () => Promise<{
authenticators?: PasskeyCredential[];
} | PasskeyCredential[]>;
fido2DeleteCredential: (args: {
credentialId: string;
}) => Promise<unknown>;
}PasswordlessSignInOptions
Options common to passwordless ceremonies (cancellation).
export interface PasswordlessSignInOptions {
signal?: AbortSignal;
}PasswordReset
A password reset started with Session.requestPasswordReset, bound to the login method it was sent through.
export interface PasswordReset {
readonly loginMethod: LoginMethod;
resend(): Promise<void>;
confirm(params: {
code: string;
newPassword: string;
}): Promise<void>;
}PasswordResetOptions
Greenfield reset-email protocol. Base64URL only obscures the identifier; the backend validates the proof.
export interface PasswordResetOptions {
emailDelivery?: 'code' | 'link';
handleRedirect?: boolean;
}PasswordResetRequiredError
Thrown by signInWithPassword when the pool requires a password reset before sign-in (Cognito PasswordResetRequiredException — e.g. a user imported without a password, or an admin reset). The caller sends a reset code (AccountConnector.forgotPassword) and completes it with confirmForgotPassword, then signs in with the new password.
export interface PasswordResetRequiredError {
readonly "isPasswordResetRequired": true;
readonly "username": string;
readonly "cause"?: unknown;
"name": string;
"message": string;
"stack"?: string | undefined;
}
export declare const PasswordResetRequiredError: {
new (username: string, cause?: unknown | undefined): PasswordResetRequiredError;
};PasswordSignInParams
Parameters for a password (SRP) sign-in.
export interface PasswordSignInParams {
username: string;
password: string;
loginMethod?: LoginMethod;
}pendingSocialRedirect
The provider return in url that this page is about to complete into entry's deployment, before the exchange: its
state names a stored, unexpired login of that deployment, it carries a code, and it has not finished. Null otherwise:
a return with error (it ends at once), a link, another deployment's or app's callback, or one already completed.
export declare function pendingSocialRedirect(url: string, entry: SocialRedirectSession, options?: { store?: OAuthTransactionStore; now?: () => number; }): SocialRedirectPending | null;PendingSsoStart
An SSO sign-in waiting for Cognito's /logout to return to the app's callback: what the authorize step needs, no secret.
export interface PendingSsoStart {
providerName: string;
clientId: string;
appClientId: string;
authServerUrl: string;
redirectUri: string;
userServiceApiBase?: string;
serviceRef?: string;
startedAt: number;
}PendingSsoStartStore
Where the one pending start of this tab is held. consume removes it before returning it, so it is used once.
export interface PendingSsoStartStore {
save(start: PendingSsoStart): boolean;
load(): PendingSsoStart | null;
consume(): PendingSsoStart | null;
}Permission
A permission on a role: effect + action + resource (+ optional service / condition).
export interface Permission {
effect: string;
action: string;
resource: string;
service?: string;
when?: unknown;
}PermissionCheck
A caller-scoped check. It carries only the locator — never an attestation or context: browsers can't vouch for
resource facts, so a rule that needs them is always denied here (reason: 'attestation_required'); backends return
per-item actions instead.
export interface PermissionCheck {
action: string;
resource: string;
scope?: string;
product: string;
service: string;
}PermissionExplanation
The full explanation for a caller-scoped decision (POST /me/permissions/check with explain).
export interface PermissionExplanation extends PermissionResult {
sources: unknown[];
conditionResults?: unknown;
nearMiss?: unknown;
}PermissionResult
export interface PermissionResult {
allowed: boolean;
effect: string | null;
reason: string | null;
unresolved?: string[];
}PermissionsClient
export interface PermissionsClient {
request(method: string, path: string, body?: unknown): Promise<ApiResponse>;
list(resource: string, params?: Record<string, string>): Promise<ApiResponse>;
get(resource: string, id: string): Promise<ApiResponse>;
listOrgs(params?: Record<string, string>): Promise<Org[]>;
listMyOrganizations(): Promise<MyOrganizations>;
listCatalogScopes(): Promise<CatalogScope[]>;
listApiKeys(userId: string): Promise<ApiKey[]>;
listWorkspaceApiKeys(workspaceId: string): Promise<ApiKey[]>;
createApiKey(input: CreateApiKeyInput): Promise<ApiKey>;
editApiKeyScopes(keyId: string, delta: ScopeDelta): Promise<ApiKey>;
rotateApiKey(keyId: string): Promise<ApiKey>;
revokeApiKey(keyId: string): Promise<void>;
}PermissionsClientOptions
export interface PermissionsClientOptions {
apiBase: string;
token: string;
authMode?: AuthMode;
fetch?: typeof fetch;
maintenanceRetry?: MaintenanceRetryOptions;
}PhoneCodeConnector
A connector that signs in with one SMS code through the user-service gateway (discovery transport gateway): start sends
the code, verify exchanges it for tokens, resend replaces the challenge. Kept separate from AuthConnector so the Session
gains the phone-code flow only when its connector implements it (see supportsPhoneCode).
export interface PhoneCodeConnector extends AuthConnector {
startPhoneSignIn(params: {
phoneNumber: string;
challengeToken?: string;
}): Promise<PhoneSignInChallenge>;
verifyPhoneSignIn(params: {
challengeId: string;
code: string;
}): Promise<{
tokens: TokenSet;
created: boolean;
}>;
resendPhoneSignIn(params: {
challengeId: string;
challengeToken?: string;
}): Promise<PhoneSignInChallenge>;
}PhoneNumberChanged
Number change, committed: the phone sign-in method now uses the new number and every older session is revoked.
export interface PhoneNumberChanged {
replaced: true;
loginMethod: 'phone';
maskedIdentifier: string;
securityRevocation: SecurityRevocation;
}PhoneNumberChangeStarted
Number change, started: a proof code went to the new number (the old one is not needed).
export interface PhoneNumberChangeStarted {
state: string;
delivery: {
maskedIdentifier: string;
};
}PhoneSignInChallenge
One phone-code sign-in challenge (the user-service gateway): the code went to the number, masked here.
export interface PhoneSignInChallenge {
challengeId: string;
maskedPhoneNumber: string;
codeLength: number;
expiresAt: string;
resendAfter: string;
}pkceChallenge
The S256 PKCE challenge for a verifier.
export declare function pkceChallenge(verifier: string, c: Crypto): Promise<string>;poolCapabilities
What method's ready pool offers, or null without opted-in discovery (then the legacy top-level lanes apply).
export declare function poolCapabilities(discovery: DiscoveryConfig | null | undefined, method: LoginMethod): DiscoveryAuthPoolCapabilities | null;PopupWindow
The parts of a browser window this flow touches (a real Window satisfies it; tests pass their own).
export interface PopupWindow {
location: {
href: string;
};
opener?: PopupWindow | null;
closed?: boolean;
document?: Document;
postMessage(message: unknown, targetOrigin: string): void;
addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
removeEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
close(): void;
open?(url: string, target: string, features: string): PopupWindow | null;
}presignWebSocketUrl
Presigns a wss:// API Gateway WebSocket URL with the given AWS credentials (SigV4, service execute-api).
export declare function presignWebSocketUrl(options: PresignWebSocketUrlOptions): Promise<string>;PresignWebSocketUrlOptions
export interface PresignWebSocketUrlOptions {
url: string;
region: string;
credentials: WebSocketSigningCredentials;
expiresInSeconds?: number;
}previewInvitation
Preview an invitation from its token, before signing in (POST /invitations/preview, public).
export declare function previewInvitation(client: PermissionsClient, token: string): Promise<InvitationPreview>;ProfileAttributes
The signed-in user's profile (GET /api/me): display fields, status and any further profile attributes.
export interface ProfileAttributes {
name?: string;
given_name?: string;
family_name?: string;
locale?: string;
zoneinfo?: string;
picture?: string;
email?: string;
status?: string;
orgId?: string;
createdAt?: number;
lastLoginAt?: number;
[attribute: string]: unknown;
}ProfileIdentities
The connected-account view (GET /api/profile/identities).
export interface ProfileIdentities {
identities: ConnectedIdentity[];
passwordSet: boolean;
primaryMethod: string | null;
}ProfileUpdate
The display fields a user may change on their own profile (PATCH /api/me).
export type ProfileUpdate = Partial<Pick<ProfileAttributes, 'name' | 'given_name' | 'family_name' | 'locale' | 'zoneinfo' | 'picture'>>;projectScope
Translate the active project into the canonical rbac grant-scope value (§5.0.7): a project is
scope = project:<projectId>. Returns undefined when no project is active (org-level scope).
export declare function projectScope(scope: Scope | null | undefined): string | undefined;randomUrlSafe
A URL-safe random string from byteLen random bytes (state / nonce / PKCE verifier).
export declare function randomUrlSafe(byteLen: number, c: Crypto): string;READABLE_SSO_CLAIMS
SSO claim contract versions this reader reads. A token without a version marker is contract 1.
export declare const READABLE_SSO_CLAIMS: readonly number[];readManagementSessionToken
The management session token in url's fragment (#session=<token>: a hosted settings page link the deployment owner
or the customer backend issued), or null. A query-string token is never read.
export declare function readManagementSessionToken(url: string): string | null;readSetupLinkToken
The setup link token in url's fragment (#setup=<token>), or null. A query-string token is never read.
export declare function readSetupLinkToken(url: string): string | null;readSsoClaims
Read the SSO claims of an already-verified token payload (this does not verify the token). A token with neither sso
nor any sso_* claim is not an SSO token. Anything else must be a complete, well-typed contract-1 encoding: a partial,
mistyped or unknown claim is sso_claims_malformed, and a higher version marker is sso_claims_newer_than_reader.
export declare function readSsoClaims(claims: Record<string, unknown> | null | undefined): SsoClaimsRead;readTileStart
The connection id of a dashboard-tile landing (?sso_tile=<connectionId>, added by the user-service tile bootstrap), or
null. Only identifies which connection's route to look up: the tile itself never signs anyone in.
export declare function readTileStart(url: string): string | null;RecoveryCodeVerification
The result of using one recovery code.
export interface RecoveryCodeVerification {
verified: boolean;
recoveryCodesRemaining: number;
}RefreshLock
A lock shared by the tabs that share token storage (the Web Locks API's navigator.locks fits).
export interface RefreshLock {
request<T>(name: string, run: () => Promise<T>): Promise<T>;
}RegistrationClientOptions
export interface RegistrationClientOptions {
apiBase: string;
fetch?: typeof fetch;
}RegistrationCompleted
export interface RegistrationCompleted {
status: 'complete';
email: string;
}RegistrationError
A registration refusal. The message is safe to display; cause is for local debugging and may contain secrets.
export interface RegistrationError {
readonly "code": RegistrationErrorCode;
readonly "status": number;
readonly "attemptsLeft"?: number | undefined;
readonly "retryAfter"?: number | undefined;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const RegistrationError: {
new (code: RegistrationErrorCode, status: number, meta?: { attemptsLeft?: number; retryAfter?: number; }, options?: ErrorOptions): RegistrationError;
};RegistrationErrorCode
Stable refusal codes the registration routes answer with (plus client-side network / unknown).
export type RegistrationErrorCode = 'invitation_not_found' | 'account_exists' | 'registration_complete' | 'registration_not_started' | 'registration_in_progress' | 'too_many_codes' | 'code_not_sent' | 'code_required' | 'code_expired' | 'invalid_code' | 'too_many_attempts' | 'password_required' | 'invalid_password' | 'maintenance' | 'registration_unavailable' | 'network' | 'unknown';RegistrationStarted
export interface RegistrationStarted {
state: string;
codeExpiresAt: number;
}RegistryEntry
An entry in the service›resource›action registry the permission matrix renders from, with its display labels.
export interface RegistryEntry {
id: string;
service: string;
resourceType: string;
action: string;
product?: string;
builtIn?: boolean;
serviceDisplayName?: string;
resourceDisplayName?: string;
displayName?: string;
labelKey?: string;
[key: string]: unknown;
}relaySocialCallback
On a callback page, before anything else reads the URL: when it carries a popup-mode state, offer the callback to the
window that opened this one (same origin only), again every half second until it acknowledges, then close. With no
opener, or no acknowledgment after the attempts, the page says to return to the original window; it never completes
the sign-in itself. Any other URL is left alone (relaying: false).
export declare function relaySocialCallback(options?: RelaySocialCallbackOptions): SocialCallbackRelay;removeGroupMember
Remove a principal from a group (DELETE /groups/:id/members/:memberId).
export declare function removeGroupMember(client: PermissionsClient, groupId: string, memberId: string, type?: string): Promise<void>;removeOrgMember
Remove a member from an org (DELETE /orgs/:id/members/:memberId). A member holding scoped roles or child
memberships needs cascade + the confirmationToken returned by getOrgMemberRemovalImpact.
export declare function removeOrgMember(client: PermissionsClient, orgId: string, memberId: string, opts?: RemoveOrgMemberOptions): Promise<void>;RemoveOrgMemberOptions
Options for removing a member who still holds scoped roles or child memberships.
export interface RemoveOrgMemberOptions {
cascade?: boolean;
confirmationToken?: string;
}removeProjectMember
Remove a member from a project, which is a Permissions workspace (DELETE /workspaces/:id/members/:memberId).
export declare function removeProjectMember(client: PermissionsClient, projectId: string, memberId: string): Promise<void>;removeRolePermission
Remove a permission from a role (DELETE /roles/:id/permissions?effect&action&resource[&service][&when]).
when is serialized as a JSON string so a CONDITIONAL permission is removed EXACTLY — without it the
server would match the unconditional permission (or nothing), leaving the conditional grant in place.
export declare function removeRolePermission(client: PermissionsClient, roleId: string, perm: Permission): Promise<void>;requestBreakGlassCode
Ask for an emergency sign-in code for email (POST /api/auth/sso/break-glass), for when the organization's SSO is
failing. The answer is the same for every address: only a person the organization allows emergency access is mailed one.
export declare function requestBreakGlassCode(params: { userServiceApiBase: string; email: string; fetch?: typeof fetch; }): Promise<void>;ResetLink
export type ResetLink = {
kind: 'unowned';
} | {
kind: 'invalid';
} | {
kind: 'valid';
email: string;
code: string;
};resolveTileRoute
Ask the deployment's user-service where a dashboard tile of connectionId signs in (GET /api/auth/sso/tiles/{id}/route):
the connection's route only while it allows tiles, the default route otherwise. Start it with startSsoSignIn, which makes
a fresh state, PKCE verifier and nonce. Throws SignInDiscoveryError when the lookup cannot answer.
export declare function resolveTileRoute(params: { userServiceApiBase: string; connectionId: string; fetch?: typeof fetch; }): Promise<SignInRoute>;revokeApiKey
Revoke an api key (DELETE /api-keys/:keyId).
export declare function revokeApiKey(client: PermissionsClient, keyId: string): Promise<void>;revokeGrant
Revoke a grant (DELETE /grants with the grant tuple in the body).
export declare function revokeGrant(client: PermissionsClient, input: GrantKey): Promise<void>;revokeMyApiKey
Revoke one of the caller's own keys (DELETE /me/api-keys/:keyId); another principal's key answers 404.
export declare function revokeMyApiKey(client: PermissionsClient, keyId: string): Promise<void>;Role
A role definition (id + its org + permissions).
export interface Role {
id: string;
orgId?: string;
permissions?: unknown[];
[key: string]: unknown;
}RoleAssignment
A role assigned to a user, at global (scope=null) or a project scope.
export interface RoleAssignment {
id: string;
roleId: string;
scope: string | null;
isDirect?: boolean;
inheritedFrom?: string | null;
expiresAt?: string | null;
}Scope
Active scope: the selected org (company) + project. Both nullable (default = token's primary org).
export interface Scope {
orgId: string | null;
projectId: string | null;
}SecurityRevocation
The account-wide session revocation a security change ran: this deployment's API denies every older session from
convergesAt (unix seconds); offline JWT verifiers and issued identity-pool credentials can still accept one for up to
the stated seconds after it.
export interface SecurityRevocation {
convergesAt: number;
offlineExposureSeconds: number;
stsExposureSeconds: number;
}sendInvitationEmail
Send an emailed invitation: user-service exchanges the delivery ticket (from createInvitation with delivery: 'email'
or issueInvitationDeliveryTicket) and emails the invite link to the invited address only. Each send rotates the link.
Resolves with sentAt, when SES accepted the email (not inbox delivery); refusals are InvitationDeliveryError.
POST /api/invitations/deliver.
export declare function sendInvitationEmail(options: RegistrationClientOptions, input: { ticket: string; }): Promise<{ sentAt: string; }>;Session
SaaSLayer session owner (Clerk-style): the SaaSLayer client owns the session, not
the host app. Token lanes are explicit — getPermissionsBearer() is the ID token by default
and the active scoped session token once an org-scoped session is set (D27/§5.4).
export interface Session {
"signIn": (params: PasswordSignInParams, options?: { signal?: AbortSignal; }) => Promise<void>;
"startPhoneSignIn": (params: { phoneNumber: string; challengeToken?: string; }) => Promise<PhoneSignInChallenge>;
"verifyPhoneSignIn": (params: { challengeId: string; code: string; }) => Promise<{ created: boolean; }>;
"resendPhoneSignIn": (params: { challengeId: string; challengeToken?: string; }) => Promise<PhoneSignInChallenge>;
readonly "loginMethods": LoginMethod[];
readonly "preferredLoginMethod": LoginMethod;
"selectLoginMethod": (method: LoginMethod) => void;
"requestPasswordReset": (params: { username: string; loginMethod?: LoginMethod; }, options?: { signal?: AbortSignal; accountConnector?: AccountConnector; }) => Promise<PasswordReset>;
"resumePasswordReset": (params: { username: string; loginMethod?: LoginMethod; }, options?: { signal?: AbortSignal; accountConnector?: AccountConnector; }) => PasswordReset;
"endRevokedSession": () => void;
"endExpiredSsoSession": () => void;
"adoptTokens": (tokens: TokenSet) => void;
"adoptSsoTokens": (tokens: TokenSet, binding: SessionSsoBinding) => void;
"requestMagicLink": (username: string, opts?: PasswordlessSignInOptions) => Promise<void>;
"completeMagicLinkFromUrl": (url?: string, opts?: PasswordlessSignInOptions) => Promise<void>;
"signInWithPasskey": (username?: string, opts?: PasskeySignInOptions) => Promise<void>;
"listPasskeys": () => Promise<PasskeyCredential[]>;
"registerPasskey": (friendlyName?: string) => Promise<void>;
"deletePasskey": (credentialId: string) => Promise<void>;
"requestEmailVerification": () => Promise<void>;
"confirmEmailVerification": ({ code }: { code: string; }) => Promise<void>;
"requestEmailChange": ({ email }: { email: string; }) => Promise<void>;
"confirmEmailChange": ({ code }: { code: string; }) => Promise<void>;
"finishEmailChangeFromLink": ({ code }: { code: string; }) => Promise<void>;
"markEmailChangeFinishing": () => void;
"reportEmailChangeFromOtherTab": ({ changedTo }: { changedTo: string | null; }) => void;
"signOut": (options?: SignOutOptions) => Promise<void>;
"impersonate": (target: ImpersonationTarget) => Promise<void>;
"stopImpersonating": () => Promise<void>;
readonly "isImpersonating": boolean;
readonly "impersonation": ImpersonationTarget | null;
"refresh": () => Promise<void>;
"getIdToken": () => Promise<string | null>;
"getAccessToken": () => Promise<string | null>;
"getRefreshToken": () => string | null;
"getPermissionsBearer": () => Promise<string | null>;
"setActiveSessionToken": (token: string | null) => void;
"ensureFresh": () => Promise<void>;
"getState": () => AuthState;
"onChange": (listener: (state: AuthState) => void) => () => void;
}
export declare const Session: {
new (options: SessionOptions): Session;
};SessionAuthPool
The pool, login client and login method that issued a session (opted-in deployments). Refresh and logout use this client only; a session without one is the primary's.
export interface SessionAuthPool {
loginMethod: LoginMethod;
userPoolId: string;
clientId: string;
}SessionOptions
export interface SessionOptions {
connector: AuthConnector;
secondaryConnector?: AuthConnector;
initialTokens?: TokenSet | null;
storage?: TokenStorage;
now?: () => number;
random?: () => number;
refreshLock?: RefreshLock | null;
redirect?: (url: string) => void;
}SessionPermissionsClientOptions
export interface SessionPermissionsClientOptions {
apiBase: string;
fetch?: typeof fetch;
maintenanceRetry?: MaintenanceRetryOptions;
}SessionSsoBinding
The SSO connection client and identity provider a session signed in through.
export interface SessionSsoBinding {
clientId: string;
providerName: string;
authServerUrl?: string;
logoutUri?: string;
}sessionTokenStorage
Persist the session in sessionStorage — survives reloads within the tab, cleared when it closes. Keyed as localTokenStorage.
export declare function sessionTokenStorage(key?: string): TokenStorage;setRoleExpiry
Change when a user's direct role grant ends (PATCH /users/:id/roles/:roleId[?scope=]); null makes it permanent. Only
an active direct grant changes (404 otherwise); 503 expiry_schedule_failed when the new end could not be scheduled.
export declare function setRoleExpiry(client: PermissionsClient, userId: string, roleId: string, scope: string | null, expiresAt: string | null): Promise<void>;setSsoGroupMappingRules
Set the connection's rules and default in its tenant org, against the revision read. Roles above the owner's ceiling are refused (403 GROUP_MAPPING_ROLE_ABOVE_CEILING). Needs sso-connection:manage in that org.
export declare function setSsoGroupMappingRules(client: PermissionsClient, params: { connectionId: string; orgId: string; rules: SsoGroupMappingRule[]; defaultGrant: SsoOrgGrant | null; expectedPolicyRevision: number; }): Promise<SsoGroupMapping>;SignedIn
How a sign-in completed: the login method of the credential and the way it was proven.
export interface SignedIn {
loginMethod: LoginMethod;
via: 'password' | 'social' | 'sso' | 'passkey' | 'magic-link' | 'sms-code';
created?: boolean;
}SignInDiscoveryError
Discovery could not answer (rate limit, outage, bad request); retryable when trying again later can help.
export interface SignInDiscoveryError {
readonly "status": number;
readonly "code": string | undefined;
readonly "retryable": boolean;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const SignInDiscoveryError: {
new (status: number, code: string | undefined, retryable: boolean): SignInDiscoveryError;
};SignInFlow
export type SignInFlow = Omit<UseSignIn, keyof SignInFlowState> & {
getState(): SignInFlowState;
subscribe(listener: () => void): () => void;
configure(options: Partial<Omit<SignInFlowOptions, 'session'>>): void;
dispose(): void;
startPasskeyAutofill(): void;
stopPasskeyAutofill(): Promise<void>;
};SignInFlowOptions
Dependencies and callbacks of one sign-in controller. Recreate the controller when its Session changes.
export interface SignInFlowOptions extends UseSignInOptions {
session: Session;
connector: AccountConnector;
loginConnectors?: Partial<Record<LoginMethod, AccountConnector>>;
discovery?: DiscoveryConfig | null;
discoveryLoading?: boolean;
discoveryError?: unknown;
onPasswordReset?: () => void;
lockedUsername?: string;
}SignInFlowState
export type SignInFlowState = Pick<UseSignIn, 'step' | 'error' | 'errorCode' | 'submitting' | 'passkeySigningIn' | 'loginMethod' | 'loginMethods' | 'mfaMethod' | 'resetUsername' | 'resetFromLink' | 'resetNeedsRecovery' | 'magicLinkEmail'> & {
resetVersion: number;
resetLinkPending: boolean;
};SignInRoute
Where an email signs in: an SSO connection's identity provider through its own app client, or the default form.
export type SignInRoute = {
method: 'default';
} | {
method: 'sso';
providerName: string;
clientId: string;
};SignInStep
The step of the sign-in flow (password + passwordless lanes).
export type SignInStep = 'password' | 'mfa' | 'newPassword' | 'resetPassword' | 'resetLinkSent' | 'resetSignIn' | 'magicLinkSent' | 'done';SignOutOptions
What signOut does beyond ending the session here.
export interface SignOutOptions {
endProviderSession?: boolean;
}SignUpFlow
export type SignUpFlow = Omit<UseSignUp, keyof SignUpFlowState> & {
getState(): SignUpFlowState;
subscribe(listener: () => void): () => void;
configure(options: Partial<Omit<SignUpFlowOptions, 'session'>>): void;
dispose(): void;
};SignUpFlowOptions
Dependencies and callbacks of one sign-up controller. No passwords appear in its public snapshot.
export interface SignUpFlowOptions extends UseSignUpOptions {
session: Session;
connector: AccountConnector;
loginConnectors?: Partial<Record<LoginMethod, AccountConnector>>;
discovery?: DiscoveryConfig | null;
}SignUpFlowState
export type SignUpFlowState = Pick<UseSignUp, 'step' | 'email' | 'error' | 'errorCode' | 'submitting' | 'loginMethod' | 'loginMethods' | 'delivery' | 'codeResent'>;SignUpInput
Credentials submitted to {@link UseSignUp.signUp}: the identifier of the form's login method, and its password.
export interface SignUpInput {
email?: string;
phoneNumber?: string;
password: string;
orgName?: string;
}SignUpParams
export interface SignUpParams {
username: string;
password: string;
attributes?: Record<string, string>;
clientMetadata?: Record<string, string>;
}SignUpResult
export interface SignUpResult {
userConfirmed: boolean;
userSub: string | null;
delivery?: {
maskedIdentifier: string;
};
}SignUpStep
The step of the sign-up flow.
export type SignUpStep = 'credentials' | 'verify' | 'done';siteScope
The scope for a single site in an org: site:<orgId>:<siteId>.
export declare function siteScope(orgId: string, siteId: string): string;SocialAckMessage
The acknowledgment, opener to popup: the relay was accepted (not: the sign-in completed).
export interface SocialAckMessage {
type: 'sl:oauth-ack';
v: 1;
state: string;
}SocialAuthClient
Drives social login over the Cognito hosted-UI OAuth redirect with PKCE (public client): builds the provider-direct authorize URL + a single-use CSRF transaction, then exchanges the returned code and verifies the OIDC nonce before adopting the tokens. Coexists with SRP/passwordless (a separate lane).
export interface SocialAuthClient {
"signInWithProvider": (provider: string) => Promise<string>;
"signInWithPopup": (provider: string, popup: PopupWindow, options?: Pick<AwaitPopupCallbackOptions, "window" | "timers" | "timeoutMs"> & { prompt?: "login"; }) => Promise<string>;
"handleRedirectCallback": (currentUrl: string) => Promise<TokenSet>;
}
export declare const SocialAuthClient: {
new (config: SocialAuthClientConfig): SocialAuthClient;
};SocialAuthClientConfig
export interface SocialAuthClientConfig {
authServerUrl: string;
clientId: string;
redirectUri: string;
userServiceApiBase?: string;
serviceRef?: string;
scopes?: string[];
store: OAuthTransactionStore;
sink?: TokenSink;
fetch?: typeof fetch;
crypto?: Crypto;
now?: () => number;
ttlMs?: number;
appClientId?: string;
redirect?: (url: string) => void;
}SocialCallbackMessage
The relay offer, popup to opener: the callback's own query values and nothing else (never a token or a verifier).
export interface SocialCallbackMessage {
type: 'sl:oauth-callback';
v: 1;
state: string;
code?: string;
error?: string;
errorDescription?: string;
}SocialCallbackRelay
What the callback page did about the URL it is showing.
export interface SocialCallbackRelay {
relaying: boolean;
acknowledged: Promise<boolean>;
}SocialPopupError
export interface SocialPopupError {
"code": SocialPopupErrorCode;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const SocialPopupError: {
new (code: SocialPopupErrorCode): SocialPopupError;
};SocialPopupErrorCode
Why a popup sign-in ended without a relayed callback.
export type SocialPopupErrorCode = 'popup_blocked' | 'popup_closed' | 'popup_timeout';SocialProviderInfo
A social provider as advertised by the discovery descriptor.
export interface SocialProviderInfo {
id: string;
label: string;
}SocialRedirectPending
A provider return about to be completed: the provider it came from, and whether it went through an SSO connection.
export interface SocialRedirectPending {
provider: string;
sso?: true;
}SocialRedirectReason
export type SocialRedirectReason = 'step_up_required' | 'sign_in_required' | 'provider_error' | 'invalid_callback' | 'expired' | 'redirect_mismatch' | 'session_unavailable' | 'wrong_principal' | 'nonce_mismatch' | 'exchange_failed' | 'link_failed';SocialRedirectResult
How one callback ended. code is a sanitized error code (a deployment trigger's refusal code, else the provider's
error value, or the user-service's error code), never the OAuth authorization code. The reasons step_up_required and sign_in_required are not final: the
pending link is kept and completeSocialRedirect can be called again once the same principal has reauthenticated.
export interface SocialRedirectResult {
kind: 'signed-in' | 'linked' | 'error';
provider: string;
intent: 'login' | 'link';
reason?: SocialRedirectReason;
code?: string;
detail?: string;
sso?: true;
}SocialRedirectSession
A Session and the deployment coordinates it signs in to; a callback is completed only into a matching one.
export interface SocialRedirectSession {
session: Session;
authServerUrl: string;
clientId: string;
userServiceApiBase?: string;
serviceRef?: string;
}SocialRedirectSessions
The Sessions a callback may complete into: a list, or a function read again while a deployment is still loading.
export type SocialRedirectSessions = SocialRedirectSession[] | (() => SocialRedirectSession[]);SsoAuditEvent
One audit event (redacted server-side).
export interface SsoAuditEvent {
eventId: string;
type: string;
at: string;
actor: string;
source: string;
outcome: string;
[key: string]: unknown;
}SsoClaims
One token's SSO claims. groups is null when the issuer marked them truncated: never read that as a complete (empty) set.
export interface SsoClaims {
readonly version: number;
readonly encoding: 'flat' | 'nested';
readonly connectionId: string;
readonly tenant: string;
readonly groups: readonly string[] | null;
readonly groupsComplete: boolean;
}SsoClaimsRead
A read: sso: null for a token without SSO claims (a native or social sign-in). Messages name claims, never values.
export type SsoClaimsRead = {
ok: true;
sso: SsoClaims | null;
} | {
ok: false;
reason: 'sso_claims_malformed';
message: string;
} | {
ok: false;
reason: 'sso_claims_newer_than_reader';
action: 'upgrade_reader';
version: number;
message: string;
};SsoConnection
A connection's settings and lifecycle as the API answers them: never a secret (a set one reads { set, updatedAt }).
export interface SsoConnection {
connectionId: string;
tenant: string;
status: 'draft' | 'active' | 'disabled' | 'deleting' | 'deleted' | (string & {});
version: number;
protocol: 'saml' | 'oidc';
orgIds?: string[];
issuer?: string;
providerTenant?: string | null;
subjectSource?: string;
idp?: {
metadataUrl?: string;
metadataXml?: string;
clientId?: string;
clientSecret?: {
set: true;
updatedAt: string;
};
scopes?: string[];
};
domains?: SsoDomainEntry[];
jit?: boolean;
createPersonalOrg?: boolean;
scim?: {
enabled: boolean;
};
deprovision?: string;
mfa?: 'delegated' | 'saaslayer';
delegatedTokens?: string;
sessionCapHours?: number;
tokenTtlMinutes?: number;
idpInitiated?: boolean;
enforcement?: {
enabled: boolean;
noticeDays?: number;
[key: string]: unknown;
};
managerGroup?: string | null;
breakGlass?: {
suids: string[];
grantMinutes: number;
};
deletePolicy?: string;
missingIdpFields?: string[];
[key: string]: unknown;
}SsoConnectionChange
One setting an edit changed.
export interface SsoConnectionChange {
field: string;
before?: unknown;
after?: unknown;
}SsoDeletionImpact
What deleting the connection would do.
export interface SsoDeletionImpact {
people: number;
ssoOnlyPeople: number;
deletePolicy: string;
enforcement: {
enabled: boolean;
inForce: boolean;
};
}SsoDomainEntry
A domain on a connection: pending until its DNS TXT proof (domainChallenge) is found, then verified.
export interface SsoDomainEntry {
domain: string;
status: 'pending' | 'verified' | (string & {});
method?: string;
token: string;
addedAt?: string;
[key: string]: unknown;
}SsoEnforcement
Where a connection's domain enforcement stands: the schedule, whether it refuses native sign-in now, who last turned it off and why, the sweep's progress on the current cutover, and how many people of each verified domain it affects (an upper bound: SSO-only people included).
export interface SsoEnforcement {
connectionId: string;
connectionStatus: string;
state: 'off' | 'scheduled' | 'enforced';
inEffect: boolean;
noticeDays: number | null;
scheduledAt: string | null;
cutoverAt: string | null;
disabledAt: string | null;
disabledBy: string | null;
disableReason: string | null;
progress: {
cutoverAt: string;
notice: string;
reminder: string;
cutover: string;
revoked: number;
failed: number;
} | null;
affected: {
upperBound: true;
total: number;
domains: Array<{
domain: string;
affected: number;
}>;
};
}SsoFactor
One factor of the SSO sign-in. id is totp or passkey.<credentialId>.
export interface SsoFactor {
id?: string;
kind: 'totp' | 'passkey';
friendlyName?: string;
createdAt: number;
lastUsedAt?: number;
}SsoFactors
The SSO sign-in's factors and whether passkeys can be added on this deployment.
export interface SsoFactors {
enrolled: boolean;
passkeyAvailable: boolean;
factors: SsoFactor[];
}SsoGroupMapping
A connection's group mapping set in its tenant: the owner-approved ceiling, the rules, the default, the revision.
export interface SsoGroupMapping {
source: string;
tenant: string;
policyRevision: number;
allowedOrgIds: string[];
approvedRoles: string[];
rules: SsoGroupMappingRule[];
defaultGrant: SsoOrgGrant | null;
}SsoGroupMappingRule
One mapping rule: a directory group (its immutable id or key) and an optional display label.
export interface SsoGroupMappingRule extends SsoOrgGrant {
group: string;
displayName?: string;
}SsoHealthReport
The connection's health report (sign-in, certificate, SCIM, domains, issues); never a name, email or token.
export interface SsoHealthReport {
connectionId: string;
overall: 'healthy' | 'degraded' | 'failing' | 'inactive';
checkedAt?: string;
signIn?: {
state: string;
lastSuccessAt: string | null;
failures: Array<{
category: string;
reason: string;
lastAt: string;
sinceLastSuccess: boolean;
}>;
};
certificate?: Record<string, unknown> | null;
provisioning?: {
scim: {
state: string;
reason?: string;
lastSuccessAt?: string | null;
};
groupDelivery: {
pending: number;
oldestPendingSeconds: number;
};
};
domains?: Array<{
domain: string;
status: string;
lastCheckAt: string | null;
lastResult: string | null;
failingSince: string | null;
demoteAt: string | null;
}>;
issues: Array<{
kind: string;
[key: string]: unknown;
}>;
[key: string]: unknown;
}SsoInitialSync
One step of the initial SCIM sync confirmation.
export interface SsoInitialSync {
connectionId: string;
generation: number;
people: number;
complete: boolean;
}SsoManagementClient
The management API as one person or session sees it. A connection outside the caller's reach answers 404; an owner-only field 403 SSO_MANAGEMENT_FIELD_FORBIDDEN. Nothing here holds or sends a server key.
export interface SsoManagementClient {
"listConnections": (params?: { tenant?: string; }) => Promise<SsoConnection[]>;
"getConnection": (connectionId: string) => Promise<SsoConnection>;
"updateConnection": (connectionId: string, attributes: Record<string, unknown>, expectedVersion: number) => Promise<{ connection: SsoConnection; changes: SsoConnectionChange[]; runtime?: Record<string, unknown>; }>;
"verifyDomain": (connectionId: string, domain: string) => Promise<{ connection: SsoConnection; check: { domain: string; result: string; verified: boolean; }; }>;
"getServiceProvider": (connectionId: string) => Promise<SsoServiceProvider>;
"getHealth": (connectionId: string) => Promise<SsoHealthReport>;
"activate": (connectionId: string) => Promise<SsoConnection>;
"disable": (connectionId: string) => Promise<SsoConnection>;
"rotate": (connectionId: string, idp: { metadataXml?: string; metadataUrl?: string; clientSecret?: string; }, expectedVersion: number) => Promise<SsoConnection>;
"getDeletionImpact": (connectionId: string) => Promise<SsoDeletionImpact>;
"deleteConnection": (connectionId: string, params: { confirm: string; reason: string; ssoOnlyPeople?: number; }) => Promise<SsoConnection>;
"confirmInitialScimSync": (connectionId: string, options?: { onProgress?: (step: SsoInitialSync) => void; maxCalls?: number; }) => Promise<SsoInitialSync>;
"listScimCredentials": (connectionId: string) => Promise<{ credentials: SsoScimCredential[]; scimUrl: string; }>;
"issueScimCredential": (connectionId: string, params?: { expiresInDays?: number; }) => Promise<{ token: string; credential: SsoScimCredential; scimUrl: string; }>;
"rotateScimCredential": (connectionId: string, credentialId: string, params?: { overlapSeconds?: number; expiresInDays?: number; }) => Promise<{ token: string; credential: SsoScimCredential; replaced: SsoScimCredential; scimUrl: string; }>;
"revokeScimCredential": (connectionId: string, credentialId: string) => Promise<SsoScimCredential>;
"getSetupLink": (connectionId: string) => Promise<SsoSetupLink | null>;
"issueSetupLink": (connectionId: string, params?: { validHours?: number; }) => Promise<{ token: string; link: SsoSetupLink; replaced: string | null; url: string | null; }>;
"revokeSetupLink": (connectionId: string) => Promise<SsoSetupLink>;
"getEnforcement": (connectionId: string) => Promise<SsoEnforcement>;
"disableEnforcement": (connectionId: string, params: { reason: string; expectedVersion: number; }) => Promise<{ connection: SsoConnection; changes: SsoConnectionChange[]; }>;
"listAudit": (connectionId: string, params?: { limit?: number; cursor?: string; type?: string; }) => Promise<{ events: SsoAuditEvent[]; nextCursor: string | null; }>;
}
export declare const SsoManagementClient: {
new (options: SsoManagementClientOptions): SsoManagementClient;
};SsoManagementClientOptions
export interface SsoManagementClientOptions {
apiBase: string;
session?: Session;
token?: string;
fetch?: typeof fetch;
}SsoManagementError
A refusal from SSO management. sessionEnded: the credential no longer works (a revoked, replaced or expired setup link or
management session, or a signed-out person): start again rather than retry.
export interface SsoManagementError {
readonly "status": number;
readonly "code": string;
readonly "meta"?: (UserServiceErrorMeta & Record<string, unknown>) | undefined;
readonly "sessionEnded": boolean;
readonly "retryable": boolean;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const SsoManagementError: {
new (status: number, code: string, message: string, meta?: Record<string, unknown>): SsoManagementError;
};SsoManagementSession
A scoped management session (setup-link or backend issued).
export interface SsoManagementSession {
sessionId: string;
tenant: string;
connectionId: string | null;
permissions: string[];
expiresAt: string;
idleMinutes: number;
[key: string]: unknown;
}SsoOrgGrant
Which org a group joins, with which roles.
export interface SsoOrgGrant {
orgId: string;
roleIds: string[];
}SsoPasskeyAssertion
A step-up passkey assertion, base64url.
export interface SsoPasskeyAssertion {
credentialIdB64: string;
authenticatorDataB64: string;
clientDataJSON_B64: string;
signatureB64: string;
userHandleB64?: string;
}SsoPasskeyRegistration
The body that saves a step-up passkey: the attestation, base64url.
export interface SsoPasskeyRegistration {
attestationObject: string;
clientDataJSON: string;
friendlyName: string;
rpId?: string;
transports?: string[];
}SsoScimCredential
A SCIM token's record; the token itself is only in an issue or rotate answer.
export interface SsoScimCredential {
credentialId: string;
status?: string;
[key: string]: unknown;
}SsoServiceProvider
What the IdP registers for this connection: the SAML entity id and ACS URL, or the OIDC redirect URI.
export interface SsoServiceProvider {
connectionId: string;
protocol: 'saml' | 'oidc';
loginHost: string;
entityId?: string;
acsUrl?: string;
redirectUri?: string;
}SsoSetupLink
A connection's setup link; the token is only in the issue answer.
export interface SsoSetupLink {
linkId: string;
connectionId: string;
status: 'active' | 'expired' | 'revoked' | 'completed';
issuedAt: string;
expiresAt: string;
openCount: number;
lastOpenedAt: string | null;
[key: string]: unknown;
}SsoStepUp
A recorded step-up of the session.
export interface SsoStepUp {
verified: boolean;
method: 'totp' | 'passkey';
}SsoTotpSetup
TOTP setup, answered once: the base32 secret and its otpauth URI.
export interface SsoTotpSetup {
secret: string;
uri: string;
}startInvitationRegistration
Begin (or resume) registering an invitee: the server mails a one-time code to the invited address only. POST /api/invitations/register/start — the token travels in the body.
export declare function startInvitationRegistration(options: RegistrationClientOptions, input: { token: string; }): Promise<RegistrationStarted>;startSsoSignIn
Send the browser to the SSO connection's identity provider through the connection's own client, the identity provider
deciding every time: first Cognito's /logout on the login host for that client (ending any hosted-UI session, which would
otherwise sign the browser in again for an hour without the provider), back to the exact redirectUri, where the callback
coordinator (completeSocialRedirect) consumes the single-use pending start written here and authorizes with PKCE, state
and nonce. The callback is completed by completeSocialRedirect into the app client's Session, bound to the connection's
client. Where the pending start cannot be stored, it authorizes directly. Returns the URL it navigated to.
export declare function startSsoSignIn(options: StartSsoSignInOptions): Promise<string>;StartSsoSignInOptions
export interface StartSsoSignInOptions {
route: {
providerName: string;
clientId: string;
};
authServerUrl: string;
appClientId: string;
redirectUri: string;
userServiceApiBase?: string;
serviceRef?: string;
store?: OAuthTransactionStore;
pendingStartStore?: PendingSsoStartStore;
fetch?: typeof fetch;
crypto?: Crypto;
now?: () => number;
redirect?: (url: string) => void;
}subscribeSocialRedirect
Hear the results of callbacks completed for entry's deployment. Final results already reached on this page are
delivered at once (a widget mounted after the callback finished); later ones as they happen. Returns an unsubscribe fn.
export declare function subscribeSocialRedirect(entry: SocialRedirectSession, listener: (result: SocialRedirectResult) => void): () => void;supportsPasswordless
True when a connector implements the passwordless surface (magic-link at minimum).
export declare function supportsPasswordless(c: AuthConnector): c is PasswordlessConnector;takeManagementSessionToken
Read the management session token from the page's fragment and remove it from the address bar, like takeSetupLinkToken.
export declare function takeManagementSessionToken(): string | null;takeSetupLinkToken
Read the setup link token from the page's fragment and remove it from the address bar (history.replaceState; other fragment params stay), so a reload, Back or shared screen never shows it. Null when the page carries none.
export declare function takeSetupLinkToken(): string | null;TokenSet
The tokens from one authenticated session.
export interface TokenSet {
idToken: string;
accessToken: string;
refreshToken: string;
expiresAt: number;
authPool?: SessionAuthPool;
sso?: SessionSsoBinding;
}TokenSink
The minimal session seam the callback uses to hand ownership of the issued tokens back.
export interface TokenSink {
adoptTokens(tokens: TokenSet): void;
}TokenStorage
Where the Session persists its TokenSet. Every method is best-effort and MUST NOT throw.
export interface TokenStorage {
load(): TokenSet | null;
save(tokens: TokenSet): void;
clear(): void;
loadImpersonation?(): ImpersonationTarget | null;
saveImpersonation?(target: ImpersonationTarget | null): void;
loadLoginMethod?(): LoginMethod | null;
saveLoginMethod?(method: LoginMethod): void;
}triggerRefusalCode
The code a deployment trigger put in a Cognito refusal ("PreAuthentication failed with error SSO_REQUIRED: ..."), e.g. SSO_REQUIRED for a native sign-in in a domain that must use SSO. Only the upper-case code is read; undefined otherwise.
export declare function triggerRefusalCode(err: unknown): string | undefined;typedScope
Build a typed scope <kind>:<orgId>:<id>. Throws on invalid segments.
export declare function typedScope(kind: string, orgId: string, id: string): string;TypedScope
A parsed typed scope.
export interface TypedScope {
kind: string;
orgId: string;
id: string;
}unassignRole
Unassign a role from a user (DELETE /users/:id/roles/:roleId[?scope=]).
export declare function unassignRole(client: PermissionsClient, userId: string, roleId: string, scope?: string | null): Promise<void>;unassignServicePrincipalRole
Revoke a role from a service principal (DELETE …/roles/:roleId[?scope=]).
export declare function unassignServicePrincipalRole(client: PermissionsClient, servicePrincipalId: string, roleId: string, scope?: string | null): Promise<void>;updateRole
Update a role's mutable fields — description, rename, permissions (PUT /roles/:id).
export declare function updateRole(client: PermissionsClient, roleId: string, updates: Partial<Role>): Promise<Role>;UserDeletion
export interface UserDeletion {
cognito: boolean;
projection: boolean;
pointers: number;
passwordless: Record<string, string> | null;
}UserList
export interface UserList {
users: AdminUser[];
nextCursor: string | null;
}UserMessageError
An error whose message is written for the user (a widget's own validation or next step), so it is shown as is.
export interface UserMessageError {
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const UserMessageError: {
new (message: string): UserMessageError;
};UserOperation
A durable user workflow operation (GET /api/users/operations/{id}).
export interface UserOperation {
id: string;
kind: string;
status: 'pending' | 'running' | 'succeeded' | 'failed' | 'partial';
components: UserOperationComponent[];
createdAt: string | null;
updatedAt: string | null;
requestKey: string | null;
}UserOperationComponent
One component of a user operation (identity, profile, permissions-principal, password | delivery).
export interface UserOperationComponent {
name: string;
status: string;
delivery?: 'external';
error?: {
code?: string | null;
message?: string | null;
};
nextAction?: string;
}UsersAdminClient
export interface UsersAdminClient {
create(input: CreateUserInput, options: {
idempotencyKey: string;
}): Promise<CreateUserResult>;
getOperation(id: string): Promise<UserOperation>;
get(suid: string, options?: {
org?: string;
}): Promise<AdminUser>;
list(query: {
email: string;
} | {
defaultOrg: string;
}, options?: {
limit?: number;
cursor?: string;
}): Promise<UserList>;
update(suid: string, attributes: Record<string, string>): Promise<AdminUser>;
disable(suid: string): Promise<AdminUser>;
enable(suid: string): Promise<AdminUser>;
delete(suid: string, options?: {
email?: string;
}): Promise<UserDeletion>;
resetPassword(suid: string): Promise<{
delivery: 'succeeded' | 'failed' | 'unknown';
}>;
setPassword(suid: string, password: string, options?: {
permanent?: boolean;
}): Promise<{
permanent: boolean;
}>;
adopt(suid: string): Promise<{
via: string;
adopted: boolean;
}>;
resetMfa(suid: string, options: {
reason: string;
}): Promise<MfaReset>;
}UsersAdminClientOptions
export interface UsersAdminClientOptions {
usersApiBase?: string;
discovery?: DiscoveryTarget;
getToken: () => string | Promise<string>;
fetch?: typeof fetch;
}UsersAdminError
A refusal from user-service: HTTP status, error code and message (and the operation, for a create).
export interface UsersAdminError {
"status": number;
"code": string;
"operation"?: UserOperation | undefined;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const UsersAdminError: {
new (status: number, code: string, message: string, operation?: UserOperation): UsersAdminError;
};UserServiceClient
A user-service client bound to a live Session: each request attaches the session's current ID token
(refreshed as needed) as the Authorization bearer and targets apiBase. Distinct from
CognitoDirectConnector.changePassword, which calls Cognito directly with the access token.
export interface UserServiceClient {
"getProfile": () => Promise<ProfileAttributes>;
"updateProfile": (attributes: ProfileUpdate) => Promise<ProfileAttributes>;
"setPassword": (params: { newPassword: string; }) => Promise<void>;
"setDefaultOrg": (orgId: string) => Promise<void>;
"listIdentities": () => Promise<ProfileIdentities>;
"connectIdentity": (params: { provider: string; identifier?: string; redirectUri?: string; }) => Promise<ConnectIdentityResult>;
"completeIdentityLink": (params: { provider: string; state: string; code: string; password?: string; }) => Promise<IdentityLinkResult>;
"disconnectIdentity": (params: { provider: string; }) => Promise<IdentityDisconnection>;
"changePhoneNumber": { (params: { identifier: string; }): Promise<PhoneNumberChangeStarted>; (params: { state: string; code: string; }): Promise<PhoneNumberChanged>; };
"completeIdentityMfa": (params: { provider: LoginMethod; }) => Promise<IdentityMfaCompletion>;
"getMfaStatus": () => Promise<MfaStatus>;
"generateRecoveryCodes": () => Promise<{ codes: string[]; }>;
"verifyRecoveryCode": (params: { code: string; }) => Promise<RecoveryCodeVerification>;
"listSsoFactors": () => Promise<SsoFactors>;
"startSsoTotp": () => Promise<SsoTotpSetup>;
"confirmSsoTotp": (params: { code: string; }) => Promise<SsoFactor>;
"ssoPasskeyOptions": () => Promise<Record<string, unknown>>;
"registerSsoPasskey": (registration: SsoPasskeyRegistration) => Promise<SsoFactor>;
"removeSsoFactor": (factorId: string) => Promise<void>;
"ssoStepUpOptions": () => Promise<Record<string, unknown>>;
"stepUpSso": (params: { code: string; } | { assertion: SsoPasskeyAssertion; }) => Promise<SsoStepUp>;
}
export declare const UserServiceClient: {
new (session: Session, options: UserServiceClientOptions): UserServiceClient;
};UserServiceClientOptions
export interface UserServiceClientOptions {
apiBase: string;
fetch?: typeof fetch;
}UserServiceError
A refusal from the user-service: HTTP status, API error code and meta. retryable marks a 503 UPSTREAM_UNAVAILABLE: the
change may already have landed with its clean-up or sign-out unfinished, and retrying (or signing in again) finishes it.
The message names the method, path and server answer only, never the request body (passwords, codes, numbers).
export interface UserServiceError {
readonly "status": number;
readonly "code": UserServiceErrorCode;
readonly "meta"?: UserServiceErrorMeta | undefined;
readonly "retryable": boolean;
"name": string;
"message": string;
"stack"?: string | undefined;
"cause"?: unknown;
}
export declare const UserServiceError: {
new (status: number, code: UserServiceErrorCode, message: string, meta?: UserServiceErrorMeta): UserServiceError;
};UserServiceErrorCode
API error codes the user-service answers on these routes (other codes pass through as strings).
export type UserServiceErrorCode = 'STEP_UP_REQUIRED' | 'SESSION_REVOKED' | 'SSO_SESSION_EXPIRED' | 'VALIDATION_FAILED' | 'NOT_FOUND' | 'CONFLICT' | 'LAST_METHOD' | 'INVALID_PROVIDER' | 'INVALID_STATE' | 'INVALID_GRANT' | 'INVALID_ID_TOKEN' | 'LINK_UNAVAILABLE' | 'INVALID_CODE' | 'INVALID_IDENTIFIER' | 'DELIVERY_NOT_ALLOWED' | 'ALREADY_CONNECTED' | 'TARGET_RESERVED' | 'TARGET_PENDING_REGISTRATION' | 'LINK_IN_PROGRESS' | 'PROOF_INVALID' | 'PROOF_ATTEMPTS_EXCEEDED' | 'PASSWORD_INVALID' | 'SURVIVOR_PROOF_REQUIRED' | 'SOCIAL_LOGIN_ATTACHED' | 'LOGIN_CAPABILITY_NOT_READY' | 'UPSTREAM_UNAVAILABLE' | 'MFA_ENROLLMENT_REQUIRED' | 'ACCOUNT_STEP_UP_REQUIRED' | 'SECURITY_CHANGE_IN_PROGRESS' | 'MFA_SIGN_IN_METHOD_REQUIRED' | 'SMS_OPTED_OUT' | 'CALLBACK_URL_NOT_ALLOWED' | 'ERROR' | (string & {});UserServiceErrorMeta
Error meta the user-service attaches to some refusals.
export interface UserServiceErrorMeta {
providers?: string[];
methods?: string[];
startNumber?: string;
stepUpMethods?: string[];
}verifyBreakGlassCode
Use an emailed break-glass code (POST /api/auth/sso/break-glass/verify). A right code opens a grant: until expiresAt
the person's usual sign-in (password, sign-in link, passkey) is exempt from SSO enforcement. The grant lives on the
server; nothing returned here admits anyone.
export declare function verifyBreakGlassCode(params: { userServiceApiBase: string; email: string; code: string; fetch?: typeof fetch; }): Promise<BreakGlassVerification>;WebSocketSigningCredentials
export interface WebSocketSigningCredentials {
accessKeyId: string;
secretAccessKey: string;
sessionToken?: string;
}webTransactionStore
A store over a Web Storage area (sessionStorage by default — cleared when the tab closes, survives the provider redirect). SSR-/private-mode-safe: any access failure degrades to a no-op / null.
export declare function webTransactionStore(area?: "localStorage" | "sessionStorage"): OAuthTransactionStore;withPasswordlessLock
Run a passwordless ceremony under the shared single-flight lock; reject a concurrent op rather than
let two configure() calls clobber each other. configure runs inside the lock so the engine is set
to THIS caller's coordinates for the whole ceremony.
export declare function withPasswordlessLock<T>(fn: () => Promise<T>): Promise<T>;