---
title: JavaScript SDK
description: 'Public JavaScript SDK functions and types, generated from the SDK source.'
canonical_url: 'https://saaslayer.com/docs/reference/javascript/'
last_updated: '2026-11-21T21:44:41-08:00'
---
# 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.

```ts
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.

```ts
export declare function acceptInvitation(client: PermissionsClient, token: string): Promise<InvitationAcceptance>;
```

## AccessRequest

An access request record (requestId surfaced as id).

```ts
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.

```ts
export interface AccessRequestPage {
    items: AccessRequest[];
    nextCursor: string | null;
}
```

## AccessRequestQuery

Filters for listing access requests.

```ts
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.

```ts
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 }).

```ts
export declare function adaptEngineTokens(t: EngineTokens, nowMs?: number): TokenSet;
```

## addGroupMember

Add a principal to a group (POST /groups/:id/members).

```ts
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).

```ts
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, …).

```ts
export interface AdminUser {
    id: string;
    attributes: Record<string, unknown>;
}
```

## ApiError

```ts
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).

```ts
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.

```ts
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.

```ts
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.

```ts
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).

```ts
export declare function assignRole(client: PermissionsClient, userId: string, roleId: string, scope?: string | null, options?: AssignRoleOptions): Promise<AssignRoleResult>;
```

## AssignRoleOptions

Options for assignRole.

```ts
export interface AssignRoleOptions {
    expiresAt?: string;
}
```

## AssignRoleResult

What assignRole did: `alreadyAssigned` when the user already held exactly this grant (nothing was written).

```ts
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.

```ts
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).

```ts
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.

```ts
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).

```ts
export interface AuditPage {
    entries: AuditEntry[];
    nextCursor: string | null;
}
```

## AuditQuery

Optional filters + pagination for the audit scope feed.

```ts
export interface AuditQuery {
    cursor?: string;
    actor?: string;
    eventType?: string;
    from?: string;
    to?: string;
    limit?: number;
}
```

## AuthConnector

```ts
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.

```ts
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`.

```ts
export declare function authErrorMessage(err: unknown, fallback: string, overrides?: Record<string, string>): string;
```

## AuthState

```ts
export interface AuthState {
    status: AuthStatus;
    tokens: TokenSet | null;
    revoked?: true;
    ssoSessionExpired?: true;
    ssoEmail?: string;
    emailChange?: EmailChangeNotice;
    emailChangedTo?: string;
}
```

## AuthStatus

Sign-in / session lifecycle state.

```ts
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`.

```ts
export interface BatchPermissionResult extends PermissionResult {
    action: string;
    resource: string;
}
```

## Boundary

A permission boundary (a ceiling on what its attached entities may do).

```ts
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.

```ts
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.

```ts
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).

```ts
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).

```ts
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.

```ts
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.

```ts
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.

```ts
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`.

```ts
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.

```ts
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.

```ts
export declare function clearTileStart(): void;
```

## CognitoConnectorConfig

```ts
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

```ts
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.

```ts
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.

```ts
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.

```ts
export declare function completeSocialRedirect(url: string, options: CompleteSocialRedirectOptions): Promise<SocialRedirectResult | null>;
```

## CompleteSocialRedirectOptions

```ts
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.

```ts
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.

```ts
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).

```ts
export declare function connectorConfigFromDiscovery(doc: DeploymentDiscovery): CognitoConnectorConfig;
```

## createApiKey

Mint an api key (POST /api-keys) — the response carries the raw key once.

```ts
export declare function createApiKey(client: PermissionsClient, input: CreateApiKeyInput): Promise<ApiKey>;
```

## CreateApiKeyInput

Input to mint a key.

```ts
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.

```ts
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.

```ts
export declare function createGrant(client: PermissionsClient, input: GrantInput): Promise<Grant>;
```

## createGroup

Create a group (POST /groups).

```ts
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).

```ts
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.

```ts
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.

```ts
export type CreateMyApiKeyInput = Omit<CreateApiKeyInput, 'userId'>;
```

## createOrganization

Create an organization (POST /orgs).

```ts
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+.

```ts
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.

```ts
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

```ts
export declare function createSessionPermissionsClient(session: Session, options: SessionPermissionsClientOptions): PermissionsClient;
```

## createSignInFlow

```ts
export declare function createSignInFlow(initial: SignInFlowOptions): SignInFlow;
```

## createSignUpFlow

```ts
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.

```ts
export declare function createSsoPasskey(params: { publicKey: Json; friendlyName: string; credentials?: CredentialsContainer; }): Promise<SsoPasskeyRegistration>;
```

## CreateUserInput

```ts
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.

```ts
export interface CreateUserResult {
    status: 200 | 201 | 202;
    user: AdminUser | null;
    operation: UserOperation;
}
```

## createUsersAdminClient

Create an admin users client for one deployment.

```ts
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.

```ts
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.

```ts
export type CredentialStatus = 'pending' | 'active' | 'enrollment_required' | 'disconnected';
```

## decodeDeploymentDiscovery

```ts
export declare function decodeDeploymentDiscovery(raw: unknown): DeploymentDiscovery;
```

## decodeDiscovery

Decode a raw /api/auth/config response into a validated, versioned DiscoveryConfig. Throws on malformed.

```ts
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.

```ts
export declare function decodeDiscoveryBrand(raw: unknown): DiscoveryBrand | undefined;
```

## decodeJwtPayload

Decode a JWT payload (base64url) without verifying — returns \{} on any error.

```ts
export declare function decodeJwtPayload(token: string): Record<string, unknown>;
```

## decodeResetLogin

```ts
export declare function decodeResetLogin(value: string): string;
```

## DEFAULT_STORAGE_KEY

Default storage key, namespaced so it never collides with host app keys.

```ts
export declare const DEFAULT_STORAGE_KEY: "saaslayer.session";
```

## deleteBoundary

Delete a boundary (DELETE /boundaries/:id).

```ts
export declare function deleteBoundary(client: PermissionsClient, id: string): Promise<void>;
```

## deleteGroup

Delete a group (DELETE /groups/:id).

```ts
export declare function deleteGroup(client: PermissionsClient, id: string): Promise<void>;
```

## deleteInvitation

Revoke a pending invitation by its id (DELETE /orgs/:id/invitations/:invitationId).

```ts
export declare function deleteInvitation(client: PermissionsClient, orgId: string, invitationId: string): Promise<void>;
```

## deleteRole

Delete a role (DELETE /roles/:id). Preview with getRoleDeleteImpact first.

```ts
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.

```ts
export declare function denyAccessRequest(client: PermissionsClient, id: string, input?: { reason?: string; }): Promise<AccessRequest>;
```

## DeploymentDiscovery

```ts
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

```ts
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

```ts
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.

```ts
export declare function discoverSignInRoute(params: { userServiceApiBase: string; email: string; fetch?: typeof fetch; }): Promise<SignInRoute>;
```

## DISCOVERY_CONTRACT_VERSION

```ts
export declare const DISCOVERY_CONTRACT_VERSION: 2;
```

## DISCOVERY_SCHEMA_VERSION

Bumped when the client descriptor shape changes; carried at runtime for forward-compat checks.

```ts
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).

```ts
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.

```ts
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).

```ts
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).

```ts
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.

```ts
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

```ts
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.

```ts
export type DiscoveryPoolTransport = 'cognito' | 'gateway';
```

## DiscoveryTarget

```ts
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).

```ts
export declare function domainChallenge(entry: { domain: string; token: string; }): { type: "TXT"; name: string; value: string; };
```

## EffectivePermissionEntry

One flattened effective permission entry.

```ts
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).

```ts
export interface EffectivePermissions {
    id: string;
    principalId: string;
    principalType: string;
    entries: EffectivePermissionEntry[];
    summary: EffectivePermissionsSummary;
    [key: string]: unknown;
}
```

## EffectivePermissionsQuery

Query for a principal's effective permissions.

```ts
export interface EffectivePermissionsQuery {
    principalId: string;
    principalType?: string;
    scope?: string;
    action?: string;
}
```

## EffectivePermissionsSummary

The rolled-up counts for a principal's effective state.

```ts
export interface EffectivePermissionsSummary {
    totalAllows: number;
    totalDenies: number;
    grantCount: number;
    [key: string]: unknown;
}
```

## EmailChangeNotice

See AuthState.emailChange.

```ts
export type EmailChangeNotice = 'changed' | 'finishing' | 'sign-in-to-finish' | 'link-refused';
```

## encodeResetLogin

```ts
export declare function encodeResetLogin(email: string): string;
```

## EngineTokens

Tokens as the passwordless engine returns them (note: `expireAt` is a Date, not epoch ms).

```ts
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).

```ts
export declare function explainMyPermission(client: PermissionsClient, check: PermissionCheck, scope?: Scope | null): Promise<PermissionExplanation>;
```

## fetchDeploymentDiscovery

```ts
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).

```ts
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.

```ts
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.

```ts
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

```ts
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.

```ts
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).

```ts
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.

```ts
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.

```ts
export declare function getOrgMemberRemovalImpact(client: PermissionsClient, orgId: string, memberId: string): Promise<Record<string, unknown>>;
```

## getRole

A single role (GET /roles/:id).

```ts
export declare function getRole(client: PermissionsClient, roleId: string): Promise<Role>;
```

## getRoleDeleteImpact

Preview the blast radius of deleting a role (GET /roles/:id/delete-impact).

```ts
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.

```ts
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.

```ts
export declare function getSsoPasskeyAssertion(params: { publicKey: Json; credentials?: CredentialsContainer; }): Promise<SsoPasskeyAssertion>;
```

## Grant

A direct grant to a principal.

```ts
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.

```ts
export interface GrantInput extends GrantKey {
    expiresAt?: string;
}
```

## Group

A group (collection of principals) within a workspace.

```ts
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.

```ts
export interface IdentityDisconnection {
    disconnected: true;
    loginMethod?: LoginMethod;
    securityRevocation?: SecurityRevocation;
}
```

## IdentityLinkResult

The result of completing a connect (link-callback).

```ts
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.

```ts
export interface IdentityMfaCompletion {
    loginMethod: LoginMethod;
    credentialStatus: 'active';
}
```

## IdentityPoolCredentials

```ts
export interface IdentityPoolCredentials {
    accessKeyId: string;
    secretAccessKey: string;
    sessionToken: string;
    expiration: Date;
}
```

## IdentityPoolCredentialsOptions

```ts
export interface IdentityPoolCredentialsOptions {
    region: string;
    identityPoolId: string;
    userPoolId: string;
    idToken: string;
}
```

## IMPERSONATION_PERMISSION

The registered impersonation permission (`product:service:type:action`).

```ts
export declare const IMPERSONATION_PERMISSION: "saaslayer:users:account:impersonate";
```

## impersonationCheck

The check that gates starting a view-as in `orgId`: on one target (`account/&#60;suid&#62;`) or on login accounts in general.

```ts
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).

```ts
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.

```ts
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).

```ts
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.

```ts
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.

```ts
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`).

```ts
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:&#60;orgId&#62;:&#60;id&#62;`).

```ts
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).

```ts
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`.

```ts
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.

```ts
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.

```ts
export declare function isPasswordResetRequired(err: unknown): boolean;
```

## isRecentAuthRequired

Thrown/mapped when a passkey mutation needs recent authentication (server fresh-auth policy).

```ts
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).

```ts
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.

```ts
export declare function issueInvitationDeliveryTicket(client: PermissionsClient, orgId: string, invitationId: string): Promise<{ deliveryTicket: string; }>;
```

## listAccessRequests

List access requests (GET /access-requests).

```ts
export declare function listAccessRequests(client: PermissionsClient, q?: AccessRequestQuery): Promise<AccessRequestPage>;
```

## listApiKeys

The caller's own api keys (GET /api-keys?userId=).

```ts
export declare function listApiKeys(client: PermissionsClient, userId: string): Promise<ApiKey[]>;
```

## listAuditByScope

Org-scoped audit feed (GET /audit/scope/:scope) — scope-authorized server-side (S3).

```ts
export declare function listAuditByScope(client: PermissionsClient, scope: string, query?: AuditQuery): Promise<AuditPage>;
```

## listBoundaries

All boundaries (GET /boundaries).

```ts
export declare function listBoundaries(client: PermissionsClient): Promise<Boundary[]>;
```

## listGroupMembers

A group's members (GET /groups/:id/members).

```ts
export declare function listGroupMembers(client: PermissionsClient, groupId: string): Promise<Member[]>;
```

## listGroups

Groups in a workspace (GET /groups?workspaceId=).

```ts
export declare function listGroups(client: PermissionsClient, workspaceId: string): Promise<Group[]>;
```

## listInvitations

List an org's invitations (GET /orgs/:id/invitations) — no token material.

```ts
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).

```ts
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.

```ts
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.

```ts
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).

```ts
export declare function listPendingReviews(client: PermissionsClient, userId: string): Promise<AccessRequest[]>;
```

## listProjectMembers

Members of a project, which is a Permissions workspace (GET /workspaces/:projectId/members).

```ts
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.

```ts
export declare function listResourceRegistry(client: PermissionsClient): Promise<RegistryEntry[]>;
```

## listRolePermissions

The permissions attached to a role (GET /roles/:id/permissions).

```ts
export declare function listRolePermissions(client: PermissionsClient, roleId: string): Promise<unknown[]>;
```

## listRoles

Roles defined in an organization (GET /roles?orgId=:orgId).

```ts
export declare function listRoles(client: PermissionsClient, orgId: string): Promise<Role[]>;
```

## listServicePrincipalRoles

A service principal's role assignments (GET /principals/serviceAccount/:id/roles).

```ts
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).

```ts
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).

```ts
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.&#60;primaryUserPoolId&#62;`.

```ts
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.

```ts
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).

```ts
export interface LoginConnectorConfigs {
    primary: CognitoConnectorConfig;
    secondary?: CognitoConnectorConfig;
}
```

## LoginMethod

A native sign-in method of the deployment's own pools (opted-in deployments).

```ts
export type LoginMethod = 'email' | 'phone';
```

## loginMethodsOf

The login methods `session` and `discovery` offer.

```ts
export declare function loginMethodsOf(session: Session, discovery: DiscoveryConfig | null | undefined): LoginMethodsView;
```

## LoginMethodsView

The login methods a sign-in, sign-up or recovery form offers.

```ts
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>).

```ts
export declare function machinePrincipalId(iamPrincipalId: string): string;
```

## MaintenanceRetryOptions

Waiting out the Permissions API's admin maintenance gate (503, error code `maintenance`, Retry-After).

```ts
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.

```ts
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.

```ts
export declare function memoryStorage(): TokenStorage;
```

## memoryTransactionStore

An in-memory transaction store (tests / non-redirect flows).

```ts
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.

```ts
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.

```ts
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.

```ts
export interface MfaReset {
    passkeysRemoved: number;
    cognitoMfaDisabled: boolean;
    signedOut: boolean;
}
```

## MfaStatus

The MFA self-service view (GET /api/profile/mfa).

```ts
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).

```ts
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.

```ts
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.

```ts
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).

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
export declare function openSocialPopup(win?: PopupWindow | undefined): PopupWindow | null;
```

## OrgCreated

A created organization (POST /orgs).

```ts
export interface OrgCreated {
    id: string;
    name?: string;
    [key: string]: unknown;
}
```

## OrgRef

A caller-scoped org/project reference (from GET /me/organizations).

```ts
export interface OrgRef {
    id: string;
    name?: string;
    personal?: boolean;
    createdAt?: string;
}
```

## parseResetLink

```ts
export declare function parseResetLink(hash: string): ResetLink;
```

## parseSiteScope

Parse a site scope; null for anything that isn't `site:&#60;orgId&#62;:&#60;siteId&#62;`.

```ts
export declare function parseSiteScope(scope: string | null | undefined): { orgId: string; siteId: string; } | null;
```

## parseTypedScope

Parse `&#60;kind&#62;:&#60;orgId&#62;:&#60;id&#62;`; null for bare org ids, legacy `project:&#60;id&#62;`, or malformed values.

```ts
export declare function parseTypedScope(scope: string | null | undefined): TypedScope | null;
```

## PasskeyCredential

A registered passkey (WebAuthn credential) as shown in management UI.

```ts
export interface PasskeyCredential {
    credentialId: string;
    friendlyName?: string;
    createdAt?: string;
    lastSignIn?: string;
    [key: string]: unknown;
}
```

## PasskeySignInOptions

```ts
export interface PasskeySignInOptions extends PasswordlessSignInOptions {
    mediation?: 'conditional';
    onSigningIn?: () => void;
}
```

## PasswordlessBusyError

Thrown when a passwordless ceremony starts while another is already running (D9).

```ts
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.

```ts
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).

```ts
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.

```ts
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).

```ts
export interface PasswordlessSignInOptions {
    signal?: AbortSignal;
}
```

## PasswordReset

A password reset started with Session.requestPasswordReset, bound to the login method it was sent through.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
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).

```ts
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.

```ts
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).

```ts
export interface PermissionExplanation extends PermissionResult {
    sources: unknown[];
    conditionResults?: unknown;
    nearMiss?: unknown;
}
```

## PermissionResult

```ts
export interface PermissionResult {
    allowed: boolean;
    effect: string | null;
    reason: string | null;
    unresolved?: string[];
}
```

## PermissionsClient

```ts
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

```ts
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).

```ts
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.

```ts
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).

```ts
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.

```ts
export interface PhoneSignInChallenge {
    challengeId: string;
    maskedPhoneNumber: string;
    codeLength: number;
    expiresAt: string;
    resendAfter: string;
}
```

## pkceChallenge

The S256 PKCE challenge for a verifier.

```ts
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).

```ts
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).

```ts
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).

```ts
export declare function presignWebSocketUrl(options: PresignWebSocketUrlOptions): Promise<string>;
```

## PresignWebSocketUrlOptions

```ts
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).

```ts
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.

```ts
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).

```ts
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).

```ts
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:&#60;projectId&#62;`. Returns undefined when no project is active (org-level scope).

```ts
export declare function projectScope(scope: Scope | null | undefined): string | undefined;
```

## randomUrlSafe

A URL-safe random string from `byteLen` random bytes (state / nonce / PKCE verifier).

```ts
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.

```ts
export declare const READABLE_SSO_CLAIMS: readonly number[];
```

## readManagementSessionToken

The management session token in `url`'s fragment (`#session=&#60;token&#62;`: a hosted settings page link the deployment owner
or the customer backend issued), or null. A query-string token is never read.

```ts
export declare function readManagementSessionToken(url: string): string | null;
```

## readSetupLinkToken

The setup link token in `url`'s fragment (`#setup=&#60;token&#62;`), or null. A query-string token is never read.

```ts
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`.

```ts
export declare function readSsoClaims(claims: Record<string, unknown> | null | undefined): SsoClaimsRead;
```

## readTileStart

The connection id of a dashboard-tile landing (`?sso_tile=&#60;connectionId&#62;`, 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.

```ts
export declare function readTileStart(url: string): string | null;
```

## RecoveryCodeVerification

The result of using one recovery code.

```ts
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).

```ts
export interface RefreshLock {
    request<T>(name: string, run: () => Promise<T>): Promise<T>;
}
```

## RegistrationClientOptions

```ts
export interface RegistrationClientOptions {
    apiBase: string;
    fetch?: typeof fetch;
}
```

## RegistrationCompleted

```ts
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.

```ts
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`).

```ts
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

```ts
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.

```ts
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`).

```ts
export declare function relaySocialCallback(options?: RelaySocialCallbackOptions): SocialCallbackRelay;
```

## removeGroupMember

Remove a principal from a group (DELETE /groups/:id/members/:memberId).

```ts
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.

```ts
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.

```ts
export interface RemoveOrgMemberOptions {
    cascade?: boolean;
    confirmationToken?: string;
}
```

## removeProjectMember

Remove a member from a project, which is a Permissions workspace (DELETE /workspaces/:id/members/:memberId).

```ts
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.

```ts
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.

```ts
export declare function requestBreakGlassCode(params: { userServiceApiBase: string; email: string; fetch?: typeof fetch; }): Promise<void>;
```

## ResetLink

```ts
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.

```ts
export declare function resolveTileRoute(params: { userServiceApiBase: string; connectionId: string; fetch?: typeof fetch; }): Promise<SignInRoute>;
```

## revokeApiKey

Revoke an api key (DELETE /api-keys/:keyId).

```ts
export declare function revokeApiKey(client: PermissionsClient, keyId: string): Promise<void>;
```

## revokeGrant

Revoke a grant (DELETE /grants with the grant tuple in the body).

```ts
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.

```ts
export declare function revokeMyApiKey(client: PermissionsClient, keyId: string): Promise<void>;
```

## Role

A role definition (id + its org + permissions).

```ts
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.

```ts
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).

```ts
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.

```ts
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.

```ts
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).

```ts
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.

```ts
export interface SessionAuthPool {
    loginMethod: LoginMethod;
    userPoolId: string;
    clientId: string;
}
```

## SessionOptions

```ts
export interface SessionOptions {
    connector: AuthConnector;
    secondaryConnector?: AuthConnector;
    initialTokens?: TokenSet | null;
    storage?: TokenStorage;
    now?: () => number;
    random?: () => number;
    refreshLock?: RefreshLock | null;
    redirect?: (url: string) => void;
}
```

## SessionPermissionsClientOptions

```ts
export interface SessionPermissionsClientOptions {
    apiBase: string;
    fetch?: typeof fetch;
    maintenanceRetry?: MaintenanceRetryOptions;
}
```

## SessionSsoBinding

The SSO connection client and identity provider a session signed in through.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
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

```ts
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.

```ts
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

```ts
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.

```ts
export type SignInRoute = {
    method: 'default';
} | {
    method: 'sso';
    providerName: string;
    clientId: string;
};
```

## SignInStep

The step of the sign-in flow (password + passwordless lanes).

```ts
export type SignInStep = 'password' | 'mfa' | 'newPassword' | 'resetPassword' | 'resetLinkSent' | 'resetSignIn' | 'magicLinkSent' | 'done';
```

## SignOutOptions

What signOut does beyond ending the session here.

```ts
export interface SignOutOptions {
    endProviderSession?: boolean;
}
```

## SignUpFlow

```ts
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.

```ts
export interface SignUpFlowOptions extends UseSignUpOptions {
    session: Session;
    connector: AccountConnector;
    loginConnectors?: Partial<Record<LoginMethod, AccountConnector>>;
    discovery?: DiscoveryConfig | null;
}
```

## SignUpFlowState

```ts
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.

```ts
export interface SignUpInput {
    email?: string;
    phoneNumber?: string;
    password: string;
    orgName?: string;
}
```

## SignUpParams

```ts
export interface SignUpParams {
    username: string;
    password: string;
    attributes?: Record<string, string>;
    clientMetadata?: Record<string, string>;
}
```

## SignUpResult

```ts
export interface SignUpResult {
    userConfirmed: boolean;
    userSub: string | null;
    delivery?: {
        maskedIdentifier: string;
    };
}
```

## SignUpStep

The step of the sign-up flow.

```ts
export type SignUpStep = 'credentials' | 'verify' | 'done';
```

## siteScope

The scope for a single site in an org: `site:&#60;orgId&#62;:&#60;siteId&#62;`.

```ts
export declare function siteScope(orgId: string, siteId: string): string;
```

## SocialAckMessage

The acknowledgment, opener to popup: the relay was accepted (not: the sign-in completed).

```ts
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).

```ts
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

```ts
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).

```ts
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.

```ts
export interface SocialCallbackRelay {
    relaying: boolean;
    acknowledged: Promise<boolean>;
}
```

## SocialPopupError

```ts
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.

```ts
export type SocialPopupErrorCode = 'popup_blocked' | 'popup_closed' | 'popup_timeout';
```

## SocialProviderInfo

A social provider as advertised by the discovery descriptor.

```ts
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.

```ts
export interface SocialRedirectPending {
    provider: string;
    sso?: true;
}
```

## SocialRedirectReason

```ts
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.

```ts
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.

```ts
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.

```ts
export type SocialRedirectSessions = SocialRedirectSession[] | (() => SocialRedirectSession[]);
```

## SsoAuditEvent

One audit event (redacted server-side).

```ts
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.

```ts
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.

```ts
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 `&#123; set, updatedAt &#125;`).

```ts
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.

```ts
export interface SsoConnectionChange {
    field: string;
    before?: unknown;
    after?: unknown;
}
```

## SsoDeletionImpact

What deleting the connection would do.

```ts
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.

```ts
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).

```ts
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.&#60;credentialId&#62;`.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
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

```ts
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.

```ts
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).

```ts
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.

```ts
export interface SsoOrgGrant {
    orgId: string;
    roleIds: string[];
}
```

## SsoPasskeyAssertion

A step-up passkey assertion, base64url.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
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.

```ts
export interface SsoStepUp {
    verified: boolean;
    method: 'totp' | 'passkey';
}
```

## SsoTotpSetup

TOTP setup, answered once: the base32 secret and its otpauth URI.

```ts
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.

```ts
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.

```ts
export declare function startSsoSignIn(options: StartSsoSignInOptions): Promise<string>;
```

## StartSsoSignInOptions

```ts
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.

```ts
export declare function subscribeSocialRedirect(entry: SocialRedirectSession, listener: (result: SocialRedirectResult) => void): () => void;
```

## supportsPasswordless

True when a connector implements the passwordless surface (magic-link at minimum).

```ts
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.

```ts
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.

```ts
export declare function takeSetupLinkToken(): string | null;
```

## TokenSet

The tokens from one authenticated session.

```ts
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.

```ts
export interface TokenSink {
    adoptTokens(tokens: TokenSet): void;
}
```

## TokenStorage

Where the Session persists its TokenSet. Every method is best-effort and MUST NOT throw.

```ts
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.

```ts
export declare function triggerRefusalCode(err: unknown): string | undefined;
```

## typedScope

Build a typed scope `&#60;kind&#62;:&#60;orgId&#62;:&#60;id&#62;`. Throws on invalid segments.

```ts
export declare function typedScope(kind: string, orgId: string, id: string): string;
```

## TypedScope

A parsed typed scope.

```ts
export interface TypedScope {
    kind: string;
    orgId: string;
    id: string;
}
```

## unassignRole

Unassign a role from a user (DELETE /users/:id/roles/:roleId[?scope=]).

```ts
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=]).

```ts
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).

```ts
export declare function updateRole(client: PermissionsClient, roleId: string, updates: Partial<Role>): Promise<Role>;
```

## UserDeletion

```ts
export interface UserDeletion {
    cognito: boolean;
    projection: boolean;
    pointers: number;
    passwordless: Record<string, string> | null;
}
```

## UserList

```ts
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.

```ts
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}).

```ts
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).

```ts
export interface UserOperationComponent {
    name: string;
    status: string;
    delivery?: 'external';
    error?: {
        code?: string | null;
        message?: string | null;
    };
    nextAction?: string;
}
```

## UsersAdminClient

```ts
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

```ts
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).

```ts
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.

```ts
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

```ts
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).

```ts
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).

```ts
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.

```ts
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.

```ts
export declare function verifyBreakGlassCode(params: { userServiceApiBase: string; email: string; code: string; fetch?: typeof fetch; }): Promise<BreakGlassVerification>;
```

## WebSocketSigningCredentials

```ts
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.

```ts
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.

```ts
export declare function withPasswordlessLock<T>(fn: () => Promise<T>): Promise<T>;
```
