import { WorkOSApiError, type Collection, type CursorPaginatedResult, type Entity, type Store } from '../core/index.js'; import { type WorkOSEventName } from './constants.js'; import type { WorkOSStore } from './store.js'; import type { EventBus } from './event-bus.js'; import type { WorkOSAgentBlueprint, WorkOSAgentInstance, WorkOSAgentInstanceSession, WorkOSOrganization, WorkOSOrganizationDomain, WorkOSItContact, WorkOSOrganizationMembership, WorkOSGroup, WorkOSUser, WorkOSSession, WorkOSAuthkitOauthResource, WorkOSEmailVerification, WorkOSPasswordReset, WorkOSMagicAuth, WorkOSAuthenticationFactor, WorkOSIdentity, WorkOSConnection, WorkOSConnectionType, WorkOSSSOProfile, WorkOSPipeConnection, WorkOSInvitation, WorkOSRedirectUri, WorkOSCorsOrigin, WorkOSAuthorizedApplication, WorkOSConnectedAccount, ConnectedAccountState, OneTimeCodeState, WorkOSAuthenticationChallenge, WorkOSDeviceAuthorization, WorkOSRole, WorkOSPermission, WorkOSAuthorizationResource, WorkOSRoleAssignment, WorkOSGroupRoleAssignment, WorkOSDirectory, WorkOSDirectoryUser, WorkOSDirectoryGroup, WorkOSAuditLogAction, WorkOSAuditLogExport, WorkOSFeatureFlag, WorkOSConnectApplication, WorkOSClientSecret, WorkOSRadarAttempt, WorkOSApiKey, WorkOSApiKeyOwner, WorkOSEvent, WorkOSWebhookEndpoint } from './entities.js'; export declare function formatEntity(entity: T, opts?: { exclude?: Set; }): Record; export declare function formatListResponse(result: CursorPaginatedResult, formatter: (item: T) => Record): { object: 'list'; data: Record[]; list_metadata: { before: string | null; after: string | null; }; }; export declare function formatOrganization(org: WorkOSOrganization, ws: WorkOSStore, opts?: { domains?: WorkOSOrganizationDomain[]; }): Record; /** * Both production serializers (the standalone domain and the organization's embedded list) render * `verification_token`, `verification_prefix` and `verification_strategy` whenever the domain has * them, so the fields appear once DNS verification has started and are absent before. */ export declare function formatDomain(domain: WorkOSOrganizationDomain): Record; export declare function formatItContact(contact: WorkOSItContact): Record; export declare function formatMembership(m: WorkOSOrganizationMembership, ws: WorkOSStore): Record; export declare function formatMembershipEvent(m: WorkOSOrganizationMembership, ws: WorkOSStore): Record; /** * The slimmer membership shape `GET .../groups/{groupId}/organization-memberships` returns — * the spec's `UserlandUserOrganizationMembershipBase`: the identifying fields without the * embedded `user` or `roles` the full membership serializer adds. The group-members list * endpoint is the only caller; the full `formatMembership` is wrong there because the base * schema has no `user` or `roles` property. */ export declare function formatMembershipBase(m: WorkOSOrganizationMembership): Record; /** An AuthKit group (`group` object). `formatEntity` yields exactly the spec's `Group` shape. */ export declare function formatGroup(g: WorkOSGroup): Record; export declare function formatUser(user: WorkOSUser): Record; export declare function formatSession(s: WorkOSSession): Record; /** Maps the emulator's PascalCase authentication_method values to the spec's snake_case event `type`. */ export declare const AUTH_METHOD_EVENT_TYPES: Record; /** * Maps authentication_method values to the session `auth_method` enum (note: magic_code, not magic_auth). * * The spec's session auth_method enum (cross_app_auth, external_auth, impersonation, magic_code, * migrated_session, oauth, passkey, password, sso, unknown) has no value for MFA or email * verification. An MFA completion normally records its *primary* factor instead (e.g. 'password'), * resolved from the pending-auth token via sessionAuthMethod in the authenticate handler. The MFA * and EmailVerification entries here are fallbacks: when no primary method is known they resolve to * 'unknown' — a valid enum member, so consumers that validate the field still pass. */ export declare const AUTH_METHOD_SESSION_VALUES: Record; /** * Resolve a spec-valid AuthenticateResponse.authentication_method from the emulator's internal * method category, or `undefined` to omit the field when no truthful value is available. * * The response enum is PascalCase and provider-specific: it has no bare 'OAuth', no 'MFA', no * 'EmailVerification', and — unlike the session's auth_method — no 'unknown'. So when the * emulator does not actually know the concrete method, it omits the field (which is nullable in * the SDKs) rather than inventing a provider: * - 'OAuth' resolves to the user's explicitly configured oauth_provider, else omitted. The * hosted authorize flow carries no provider information, so there is nothing truthful to * default to — a fixed provider would just be a fabricated guess. * - 'MFA' and 'EmailVerification' are verification gates, not methods. The real method is * whatever initiated the flow; callers pass it via the primary method when known (an MFA * challenge records the primary factor on the pending-auth token). When it isn't known, the * field is omitted rather than guessed. * Everything already spec-valid (Password, MagicAuth, SSO, Passkey, GoogleOAuth, …) passes through. */ export declare function resolveResponseAuthMethod(method: string, opts?: { oauthProvider?: string | null; }): string | undefined; /** * Resolve the response authentication_method for a refresh_token grant, which reuses an existing * session rather than authenticating fresh. Real WorkOS echoes the session's *original* method, so * we recover it from the reused session's stored `auth_method` (snake_case) instead of the grant's * hard-coded 'OAuth' category — a password login that refreshes truthfully reports 'Password'. * * Generic 'oauth' has no provider recorded on the session, so it falls back to the user's * oauth_provider (else omitted); 'unknown' and any unmapped value are omitted rather than guessed. */ export declare function resolveSessionResponseAuthMethod(sessionAuthMethod: string, opts?: { oauthProvider?: string | null; }): string | undefined; /** authentication.* event names per method, resolved from the spec-generated catalog. */ export declare const AUTH_EVENTS: Record; export declare function buildAuthenticationEventData(opts: { status: 'succeeded' | 'failed'; method: string; userId?: string | null; email?: string | null; ipAddress?: string | null; userAgent?: string | null; error?: { code: string; message: string; }; sso?: { organization_id: string | null; connection_id: string | null; session_id: string | null; }; }): Record; /** * Emit an authentication event (succeeded or failed) for a given method. * This unified helper handles both regular auth events and SSO-specific events. */ export declare function emitAuthenticationEvent(opts: { eventBus: EventBus | undefined; method: string; status: 'succeeded' | 'failed'; userId?: string | null; email?: string | null; ipAddress?: string | null; userAgent?: string | null; error?: { code: string; message: string; }; sso?: { organization_id: string | null; connection_id: string | null; session_id: string | null; }; }): void; export declare function formatEmailVerification(ev: WorkOSEmailVerification): Record; export declare function formatPasswordReset(pr: WorkOSPasswordReset): Record; export declare function formatMagicAuth(ma: WorkOSMagicAuth): Record; /** Production validates a caller-supplied `totp_secret` against exactly this. */ export declare const BASE32_SECRET: RegExp; /** * The TOTP details an enrollment stores. Without a caller-supplied secret it mints 32 Base32 * characters — the 160 bits RFC 4226 recommends — so authenticator apps and TOTP libraries * accept the secret verbatim; `uri` is the otpauth form those apps import. */ export declare function newTotp(issuer: string, user: string, secret?: string): WorkOSAuthenticationFactor['totp']; /** The spec's AuthenticationFactor: what GET and LIST return, secrets stripped. */ export declare function formatAuthFactor(f: WorkOSAuthenticationFactor): Record; /** The spec's AuthenticationFactorEnrolled: the one response that shows the secrets. */ export declare function formatAuthFactorEnrolled(f: WorkOSAuthenticationFactor): Record; /** * The factors production counts as enrolled: those whose enrollment challenge has verified. * `GET /user_management/users/{id}/auth_factors` lists these and nothing else * (`verifiedOnly: true`), and the password grant challenges a second factor only when one * exists — so a factor enrolled and never verified is invisible to both, as it is live. */ export declare function verifiedAuthFactors(ws: WorkOSStore, userId: string): WorkOSAuthenticationFactor[]; /** Production's `touchLastVerifiedAt`: the factor is verified from the moment one of its challenges is. */ export declare function touchFactorVerified(ws: WorkOSStore, factorId: string): void; /** * The spec's identity is the three federated fields and nothing else — no `object`, no `id`, no * timestamps — and its endpoint returns a bare array rather than a list envelope, which is what * the SDKs deserialize (`getUserIdentities` maps the response body directly). */ export declare function formatIdentity(i: WorkOSIdentity): Record; /** * Record that `user` signs in through `provider`, idempotently: an identity is a link, and a * second login through the same provider is the same link, not another one. Callers pass the * provider as a spec-valid AuthenticateResponse value ('GoogleOAuth', 'MicrosoftOAuth', …), * which is also what the identity `provider` enum holds. */ export declare function linkOAuthIdentity(ws: WorkOSStore, userId: string, provider: string, idpId: string): void; export declare function generateVerificationToken(): string; export declare function generateCode(): string; /** * Whether a string is shaped enough like an email to be worth storing. Deliberately loose — * the emulator is not an address validator, it just refuses input that could only be a typo. */ export declare function isEmailShaped(value: string): boolean; /** Why a supplied `email` cannot be used, kept apart so a caller can report which one happened. */ export type EmailProblem = 'missing' | 'not_a_string' | 'malformed'; export type NormalizedEmail = { ok: true; email: string; } | { ok: false; problem: EmailProblem; }; /** * Normalize a request's `email` to a trimmed string, or say why it can't be. Not every value * handed to this is normalizable, so the problem comes back as a value rather than an exception: * the routes disagree about how to report it — `validationError`'s 422 on the user-management * CRUD routes, a 400 `invalid_request` on the grants — and only about that. * * Callers used to type-assert instead, which was survivable while a lookup by email could only * miss — `findOneBy` returns undefined for a number as readily as for an unknown address. * Resolving case-insensitively means calling `toLowerCase` on it, so the same assertion throws and * a malformed request comes back a 500 that tells the caller nothing. * * `null` is `missing`, not `not_a_string`: in a JSON body it is how a caller spells absence, and * the guard exists to name what the caller must fix, not what `typeof` says. * * `requireShape` is for the routes that create something from the address rather than look one up. * A read that misses is a 404 the caller can act on; a write that stores a typo is an account or * an invitation nothing can ever reach. Read paths leave it off, so an address that does not * resolve still 404s rather than changing error shape. */ export declare function normalizeEmail(value: unknown, opts?: { requireShape?: boolean; }): NormalizedEmail; /** * The trimmed `email` from a request body, as a route that reports 400 `invalid_request` wants it. * * Absence comes back as `''` rather than throwing, because the grants name it alongside whatever * else they also require ("code and email are required") — a message that is more use than one * field at a time. */ export declare function requireEmailString(value: unknown, opts?: { requireShape?: boolean; }): string; /** * The trimmed `email` from a request body, as the user-management CRUD routes want it: a 422 with * the per-field code, which is the validation shape those routes already answer in. */ export declare function requireEmailField(value: unknown, opts?: { requireShape?: boolean; }): string; /** * Whether two addresses name the same account. Case-insensitive, like every lookup by email, and * trimmed for the same reason storage is: a padded copy of an address names the same person, and a * filter that skipped the trim would not return what creation had just written. */ export declare function emailsMatch(a: string, b: string): boolean; /** * Look a user up by email, ignoring case. `findOneBy` is an exact-match index lookup, which is * fine for a read but forks the account in two anywhere a miss creates a user instead. */ export declare function findUserByEmail(ws: WorkOSStore, email: string): WorkOSUser | undefined; /** * The one membership a user holds in an organization that is not `inactive`. `POST * /user_management/organization_memberships` never adds a second live membership (it answers * with the existing active one, or a 400 for a pending one) and validateSeedConfig rejects one, * so the first match is the only match — and a stale deactivated record is never taken for the * live one. */ export declare function liveMembershipFor(ws: WorkOSStore, organizationId: string, userId: string): WorkOSOrganizationMembership | undefined; /** * Hash password using SHA256. * NOTE: This is intentionally weak for emulator/testing only. * Production systems should use bcrypt, scrypt, or Argon2 with proper salt and iterations. */ export declare function hashPassword(password: string): string; export declare function verifyPassword(password: string, hash: string): boolean; export declare function expiresIn(minutes: number): string; export declare function isExpired(expiresAt: string): boolean; /** * End every session the user holds, the way `POST /user_management/sessions/revoke` ends one: * the record is stamped revoked so the `session.revoked` payload its deletion emits says so. * Production does this when a password is reset (`revokeByUser`), since the reset is how a user * takes an account back from whoever else was signed in to it. */ export declare function revokeSessionsForUser(ws: WorkOSStore, userId: string): void; export declare function revokeSession(ws: WorkOSStore, sessionId: string): void; /** Production's `MAX_AUTHENTICAITON_ATTEMPTS` (sic): comparisons a one-time code allows before it locks. */ export declare const MAX_ONE_TIME_CODE_ATTEMPTS = 3; export type OneTimeCodeOutcome = 'valid' | 'invalid' | 'expired' | 'previously_used' | 'too_many_attempts'; type OneTimeCode = Entity & OneTimeCodeState & { code: string; expires_at: string; }; /** * The newest of a user's codes: the only one production will compare against. It resolves the * code to verify by the user — the latest challenge on their email factor — rather than by the * code sent, so requesting a second code retires the first even while the first is unexpired. * Issuing through `issueEmailVerificationCode` / `issueMagicAuthCode` leaves one record per * user, but a record inserted directly (a seed, a test) can sit beside it, and insertion order * would not settle which is newer, since an update re-indexes a record to the end. */ export declare function latestOneTimeCode(records: T[]): T | undefined; /** * What production's AuthenticationChallengeVerifier answers for `code` against `record`, in its * order: a code already redeemed is refused before anything else, then one that has used up its * attempts, then one past its expiry — and only then is the code compared. A miss is counted * here, so the third miss is the last comparison the code gets: the fourth request, right code * or wrong, is `too_many_attempts`. A hit is not spent here; the caller runs `redeemOneTimeCode` * once whatever else its request has to check has passed, so a request that fails after the * code matched leaves the code redeemable. */ export declare function verifyOneTimeCode(collection: Collection, record: T, code: string): OneTimeCodeOutcome; /** * Issue the user a fresh email verification code, retiring any earlier one. Production compares * a code against the user's latest challenge only, so once this record exists an earlier code * can never be redeemed again — presenting it is a miss against the new code, not * `previously_used` — and nothing is lost by dropping its record. One record per user is also * what keeps a long-running emulator from holding one per login. The insert is what delivers * the code, on the email_verification.created webhook, the way every emailed code leaves the * emulator. */ export declare function issueEmailVerificationCode(ws: WorkOSStore, user: { id: string; email: string; }): WorkOSEmailVerification; /** The Magic Auth counterpart of `issueEmailVerificationCode`, delivered on magic_auth.created. */ export declare function issueMagicAuthCode(ws: WorkOSStore, user: { id: string; email: string; }): WorkOSMagicAuth; /** Spend a code `verifyOneTimeCode` found valid: the hit counts as an attempt, and the code answers `previously_used` from now on. */ export declare function redeemOneTimeCode(collection: Collection, record: T): void; /** * The authenticate grants' one-time-code failures, as production words them. `identifier` is * what the message names: the email for Magic Auth and email verification, the challenge id for * MFA — production's own distinction, since the first two being challenges underneath is not * something it exposes. */ export declare function oneTimeCodeError(outcome: Exclude, identifier: string): WorkOSApiError; export declare function formatConnection(conn: WorkOSConnection): Record; export declare function countsTowardConnectionLimit(type: WorkOSConnectionType): boolean; /** * The organization's SSO connections — the ones production counts toward its limit of one per * organization. Deleted connections are gone from the store, which is production's exclusion of * the `Deleting` state. */ export declare function organizationSsoConnections(ws: WorkOSStore, organizationId: string): WorkOSConnection[]; /** * The organization hosted AuthKit sends this sign-in to for SSO, or null when it stays on the * hosted flow. Production's order, once the email is known: * * 1. An organization whose domain policy covers the email's domain decides, whatever organization * the request selected and whether or not the person is a member. * 2. Otherwise a selected organization decides for its members, and for nobody else: production * branches on the selection before it looks the email up, so a selection the person is not a * member of ends the search rather than falling through to rule 3. * 3. With no organization selected, the one organization that verified the domain and holds the * person as an active member decides. * * "Decides" means its `require_sso` setting applies: an organization that allows other methods * keeps the hosted flow, and so does one with no SSO connection to send anyone to. */ export declare function ssoRequiredOrganization(ws: WorkOSStore, email: string, selectedOrganizationId: string | null): string | null; export declare function isListedConnectionType(type: WorkOSConnectionType): boolean; /** * The spec's Profile carries `name` (the user's full name, nullable) beside `first_name` and * `last_name`, and the SDKs read it as a required key — workos-python's `Profile.from_dict` fails * without it (#129). It is emitted as stored, never composed from the two parts: production's * reconciler (`api/src/profiles/profile-reconciler.ts`) sets `name` only when the connection's * attribute map has a `name` key, and its serializer returns that stored value or null. A * derived "Ada Lovelace" would pass against the emulator and come back null from WorkOS. */ export declare function formatSSOProfile(p: WorkOSSSOProfile): Record; export declare function formatPipeConnection(pc: WorkOSPipeConnection): Record; /** * How long an invitation stays open when the request names no `expires_in_days`: production's * `invitation_expiry` environment setting, 7 days as created. The request may say 1 to 30. */ export declare const INVITATION_DEFAULT_EXPIRY_DAYS = 7; export declare const INVITATION_MIN_EXPIRY_DAYS = 1; export declare const INVITATION_MAX_EXPIRY_DAYS = 30; export declare function invitationExpiresIn(days: number): string; export type InvitationState = 'pending' | 'accepted' | 'expired' | 'revoked'; /** * An invitation's state, derived when it is read the way production derives it * (`userland-user-invites/utils/get-invite-state.ts`): revoked wins, then accepted, then expiry * by the clock, else pending. Deriving it is what lets an invitation expire on its own — a stored * state could only ever be written by a request, and no request arrives at the moment one lapses. */ export declare function invitationState(inv: WorkOSInvitation): InvitationState; export declare function formatInvitation(inv: WorkOSInvitation): Record; /** * What WorkOS creates the moment an invitation to an organization is sent: the recipient's user, * when the address has no account yet, and their membership, `pending` with the invitation's role. * acceptInvitation activates that same membership; revoking the invitation leaves it behind, as in * production. A membership that already exists takes the invitation's role, and an inactive one * goes back to `pending` so acceptance activates it again; the REST route refuses to invite an * active member before this runs. Shared by the invitations REST route and seeded invitations so * the two cannot drift. */ export declare function provisionInvitee(inv: WorkOSInvitation, ws: WorkOSStore): void; /** * Mark an invitation accepted and join its recipient to the organization it names, returning that * organization's id (null if the invitation names none). Shared by the invitations REST route and * the authenticate grants that accept an `invitation_token` so the two cannot drift; validating * the invitation stays with each caller, which report a bad one under different spec error codes. * * An existing membership is reused rather than duplicated, and a deactivated one is reactivated — * a fresh invitation is how a removed member rejoins. */ export declare function acceptInvitation(inv: WorkOSInvitation, user: WorkOSUser | undefined, ws: WorkOSStore, eventBus: EventBus | undefined): string | null; export declare function formatRedirectUri(r: WorkOSRedirectUri): Record; /** * The organizations a session could be scoped to. 'pending' is an unaccepted invitation and * 'inactive' a deactivated member; neither is one production would scope a session to. */ export declare function activeOrganizationsFor(ws: WorkOSStore, userId: string): Array<{ id: string; name: string; }>; /** * Record a fresh sign-in: stamp the user's last sign-in and create the session it starts. Shared by * `/user_management/authenticate` and `/oauth2/token`, so a login through either leaves the same * trace. The caller emits the authentication event, which it knows the method of. * * `verifyEmail` marks the mailbox proven (a redeemed magic-auth code does), folded into the sign-in * write so it is one write and one `user.updated`. */ export declare function startLoginSession(ws: WorkOSStore, input: { user: WorkOSUser; organizationId: string | null; ipAddress: string | null; userAgent: string | null; /** The method the session records; see AUTH_METHOD_SESSION_VALUES. */ authMethod: string; verifyEmail?: boolean; }): WorkOSSession; export declare function formatAuthkitOauthResource(r: WorkOSAuthkitOauthResource): Record; export declare function formatCorsOrigin(o: WorkOSCorsOrigin): Record; export declare function formatAuthorizedApplication(a: WorkOSAuthorizedApplication): Record; export declare function formatConnectedAccount(a: WorkOSConnectedAccount): Record; /** * `pipes.connected_account.*` event payloads carry two fields the REST shape does not — the * provider slug and the data integration id. `state` is overridable because `disconnected` * exists only in the event a deletion emits; a stored row never holds it. */ export declare function formatConnectedAccountEvent(a: WorkOSConnectedAccount, state?: ConnectedAccountState | 'disconnected'): Record; /** * One data integration per provider slug: an account is an installation of the environment's * integration for that provider, so every account of one slug shares the id. Reused from any * live account before minting, keeping the id stable for as long as any account of the slug * exists rather than inventing a fresh integration per install. */ export declare function dataIntegrationIdFor(ws: WorkOSStore, slug: string): string; /** * The connected account a (user, provider) lookup addresses. `organization_id` narrows the * match rather than keying it: omitted, a lone account resolves whatever its scope, and * several — one provider installed in two organizations — answer the spec's 409 ("several * connected accounts match this user for the provider; one must be named"). */ export declare function findConnectedAccount(ws: WorkOSStore, userId: string, slug: string, organizationId: string | null): WorkOSConnectedAccount | undefined; /** * The account keyed by exactly (user, provider, organization scope), with `organization_id` * matched rather than filtered: the key import answers 409 on and authorize connects. */ export declare function findExactConnectedAccount(ws: WorkOSStore, userId: string, slug: string, organizationId: string | null): WorkOSConnectedAccount | undefined; /** * Inserts an OAuth connected account, the one auth method the import DTO, the seed and the * authorize flow describe. Fires the `pipes.connected_account.*` event for its state. */ export declare function insertConnectedAccount(ws: WorkOSStore, account: Pick & Partial>): WorkOSConnectedAccount; /** * The account an organization owns for a provider. Organization-owned accounts have no * `user_id`, which keeps them out of every per-user lookup above. */ export declare function findOrganizationConnectedAccount(ws: WorkOSStore, organizationId: string, slug: string): WorkOSConnectedAccount | undefined; /** * Acting for an organization's connected account requires an active membership, which the * spec answers with a bare 403 `{ message }` otherwise. */ export declare function assertActiveMember(ws: WorkOSStore, organizationId: string, userId: string): void; /** * The account with a usable access token, or `undefined` when it needs reauthorization. Shared * by `/token` and `/credentials`, which vend the same token in different envelopes. */ export declare function vendAccessToken(ws: WorkOSStore, account: WorkOSConnectedAccount): WorkOSConnectedAccount | undefined; /** Redirect URI hosts the emulator's authorize endpoints accept with no configuration. */ export declare const DEFAULT_ALLOWED_REDIRECT_HOSTS: string[]; /** * Normalize a configured redirect host into the form `URL.hostname` produces: lowercase, * punycode, no scheme, no port, IPv6 in brackets. Accepts a bare hostname * (`app.example.test`), a subdomain wildcard (`*.example.test`), `*`, or a whole origin * (`https://app.example.test:8443`), since an origin is what people usually have on hand. * Throws on input that would silently never match. */ export declare function normalizeRedirectHost(value: string): string; /** Normalize a list of configured redirect hosts, dropping blank entries. */ export declare function normalizeRedirectHosts(values: readonly string[]): string[]; /** * Validate that a redirect_uri points to a host the emulator is willing to redirect to. * Prevents the emulator from being used as an open redirect. Localhost is always allowed; * `allowedRedirectHosts` (`--redirect-hosts`) adds to that for test environments that use * production-like hostnames. */ export declare function assertAllowedRedirectUri(uri: string, store: Store): void; export declare function formatAuthChallenge(c: WorkOSAuthenticationChallenge): Record; export declare function formatRole(role: WorkOSRole, ws: WorkOSStore): Record; export declare function formatPermission(p: WorkOSPermission): Record; export declare function formatAuthorizationResource(r: WorkOSAuthorizationResource): Record; export declare function formatRoleAssignment(ra: WorkOSRoleAssignment): Record; export declare function formatGroupRoleAssignment(gra: WorkOSGroupRoleAssignment): Record; export declare function formatDeviceAuthorization(d: WorkOSDeviceAuthorization, baseUrl: string): Record; export declare function formatDirectory(d: WorkOSDirectory): Record; /** * The `data` of a `dsync.activated` event. Production documents it as the Directory object * with the singular `domain` replaced by a `domains` array of Organization Domains * (`object`, `id`, `domain`), and requires a string `external_key`. Strict SDK * deserializers (e.g. workos-python's `DsyncActivatedData.from_dict`) raise on a missing * `domains`, which fails the whole `GET /events` page it appears on. */ export declare function formatDirectoryActivatedEvent(d: WorkOSDirectory, ws: WorkOSStore): Record; /** * The `data` of a `dsync.deleted` event: the Directory object without `domain`, `domains` * or `external_key`, in the `deleting` state the directory is in when the event fires. */ export declare function formatDirectoryDeletedEvent(d: WorkOSDirectory): Record; export declare function formatDirectoryUser(u: WorkOSDirectoryUser): Record; export declare function formatDirectoryGroup(g: WorkOSDirectoryGroup): Record; export declare function formatAuditLogAction(a: WorkOSAuditLogAction): Record; export declare function formatAuditLogExport(ex: WorkOSAuditLogExport): Record; /** * The spec's `Flag` object, spelled out rather than derived from the entity: every key it * lists is `required`, so a strict SDK deserializer faults on an omission, and the emulator * must not add keys production does not send either. */ export declare function formatFeatureFlag(f: WorkOSFeatureFlag): Record; /** * Flag webhook payloads are the REST `Flag` plus `environment_id`, which the REST object * itself does not carry. */ export declare function formatFeatureFlagEvent(f: WorkOSFeatureFlag, environmentId: string): Record; /** * The actor an API-key request acts as — flag event `context.actor`, Vault `updated_by`. The * key's record when the caller's key has one (an array-form `apiKeys` seed entry, or a key * created over the API), otherwise the emulator's standing placeholder: a map-form `apiKeys` * entry authenticates but has no `api_key` resource behind it, so there is nothing to name. */ export declare function apiKeyActor(ws: WorkOSStore, apiKey?: string): { id: string; name: string; }; /** Generate a Connect Application client_id, e.g. `client_01HXYZ...`. */ export declare function generateClientId(): string; export declare function formatConnectApplication(a: WorkOSConnectApplication): Record; export declare function formatClientSecret(s: WorkOSClientSecret): Record; export declare function formatRadarAttempt(a: WorkOSRadarAttempt): Record; /** Mask an API key value the way the spec shows it, e.g. `sk_...3456`. */ export declare function obfuscateApiKey(key: string): string; /** * Drop every API key whose owner matches, from both the record store and the auth * allow-list. Deleting only the record leaves the secret in the map the middleware holds, * where it keeps authenticating for a principal that no longer exists — so the two stores * have to fall together, the same pairing `DELETE /api_keys/:id` makes. */ export declare function revokeApiKeysForOwner(store: Store, ws: WorkOSStore, matches: (owner: WorkOSApiKeyOwner) => boolean): void; /** The organization a key is scoped to: the owner org, or the org a user-owned key was issued in. */ export declare function apiKeyOrganizationId(k: WorkOSApiKey): string; export interface IssueApiKeyInput { name: string; owner: WorkOSApiKeyOwner; permissions: string[]; /** ISO-8601 expiry, or null for a key that never expires. */ expiresAt: string | null; /** Auth environment; decides the `sk_live_`/`sk_test_` prefix and travels into the allow-list. */ environment: string; } /** * Mint an API key: create the `api_key` record and register the secret in the auth allow-list * (the same object the middleware holds by reference) so the new key authenticates real * requests. Both the public routes and the widgets surface issue keys through here, so the two * stores cannot drift apart. Returns the plaintext secret alongside the record — it is shown to * the caller exactly once and never serialized again. */ export declare function issueApiKey(store: Store, ws: WorkOSStore, input: IssueApiKeyInput): { record: WorkOSApiKey; value: string; }; /** * Delete one API key from both the record store and the auth allow-list, so the key stops * authenticating and not merely stops resolving — see `revokeApiKeysForOwner`. */ export declare function deleteApiKey(store: Store, ws: WorkOSStore, record: WorkOSApiKey): void; export declare function isApiKeyExpired(record: WorkOSApiKey): boolean; /** * Set an API key's expiry: `null` clears it so the key never expires, a future timestamp * schedules it, and anything else — a past timestamp or none at all — expires the key now. * The allow-list entry moves in step, so the middleware enforces the new expiry on the next * request. A key that has already expired cannot be re-scheduled, as in production. */ export declare function expireApiKey(store: Store, ws: WorkOSStore, record: WorkOSApiKey, expiresAt: string | null | undefined): WorkOSApiKey; export declare function formatApiKeyRecord(k: WorkOSApiKey): Record; export declare function formatEvent(e: WorkOSEvent): Record; /** * The `WebhookEndpointJson` shape. Production serializes the signing secret on every read — * create, get, list and update alike (`webhook-endpoints.serializer.ts`) — so there is no * masked variant. */ export declare function formatWebhookEndpoint(ep: WorkOSWebhookEndpoint): Record; /** * A webhook signing secret shaped like production's: 25 base62 characters * (`WebhookEndpointsService.create`, `generateToken('base62', 25)`), no prefix. */ export declare function generateWebhookSecret(): string; export declare function formatAgentBlueprint(b: WorkOSAgentBlueprint): Record; export declare function formatAgentInstance(i: WorkOSAgentInstance): Record; /** Status is derived at read time, as in production: no clock ever flips a stored row to `expired`. */ export declare function agentSessionStatus(s: WorkOSAgentInstanceSession, now?: number): 'active' | 'revoked' | 'expired'; export declare function formatAgentInstanceSession(s: WorkOSAgentInstanceSession): Record; /** * Session webhook payloads differ from the REST object: they carry the owning instance's * `organization_id` and no `status`, and the created event adds the granted * `permission_slugs`. The refresh token never leaves the store either way. */ export declare function formatAgentInstanceSessionEvent(s: WorkOSAgentInstanceSession, organizationId: string, opts?: { permissionSlugs: string[]; }): Record; export {};