Organization.ts overview

Organizations: members with role-checked "resource:action" permissions, invitations, teams, per-organization roles that replace the static ones, deactivatable memberships and DNS-verified domains. The active organization is a session attribute; authorize every request against the membership, never the attribute.


Exports Grouped by Category


errors

OrganizationConfigError (class)

OrganizationService’s layer was built with a OrganizationConfig.creatorRole other than the OrganizationOwnerRole in the context. The build dies with it, since deleting a user would otherwise guard a different role than organizations give their creators.

Signature

declare class OrganizationConfigError

Source

Since v0.9.0

references

OrganizationOwnerRole

The protected owner role of every organization: what OrganizationService gives a creator and guards in its last-owner checks, and what deleting a user reads to refuse removing an organization’s last owner. Provide it where both are built to change the role for both.

Signature

declare const OrganizationOwnerRole: Context.Reference<string>

Source

Since v0.9.0

utils

AcceptInvitationInput (interface)

Input for accepting an invitation.

Signature

export interface AcceptInvitationInput extends InvitationResponseInput {
  /**
   * The stored id (the token's digest, as `validateSession` answers it) of
   * the session the acceptance arrives over. When the
   * token is the first proof of the invited address (the account's matching
   * email identifier is unverified), every other session of the account is
   * revoked and this one kept; without it, all are revoked.
   */
  readonly currentSessionId?: string
}

Source

AcceptedInvitation (interface)

What accepting an invitation answers: the membership it created and the invitation as stored after the answer (status accepted). The invitation comes back here because the invitee cannot read it through listInvitations, which takes invitation:create.

Signature

export interface AcceptedInvitation {
  readonly member: Member
  readonly invitation: Invitation
}

Source

AddOrganizationDomainInput (interface)

Input for claiming an email domain for an organization

Signature

export interface AddOrganizationDomainInput {
  /**
   * Domain to claim; normalized (trimmed, lowercased) before storage. The
   * claim is always proved through DNS: an organization cannot choose
   * `manual` attestation, which is the operator's
   * ({@link OrganizationService.attestDomain}).
   */
  readonly domain: string
}

Source

AttestDomainOptions (interface)

Options for the operator’s OrganizationService.attestDomain.

Signature

export interface AttestDomainOptions {
  /**
   * Who is attesting, recorded on the claim as
   * {@link OrganizationDomain.attestedBy}: the platform admin's user id
   * over HTTP, or any identifier the operator's tooling uses for its
   * operators. Omitted, the claim records no attester.
   */
  readonly attestedBy?: string
}

Source

CreateOrganizationInput (interface)

Input for creating an organization

Signature

export interface CreateOrganizationInput {
  readonly name: string
  readonly slug: string
  readonly logo?: string
  readonly metadata?: Types.JsonObject
}

Source

CreateTeamInput (interface)

Input for creating a team

Signature

export interface CreateTeamInput {
  readonly name: string
}

Source

DomainVerificationState (type alias)

How far along a domain claim is.

pending - the claim exists but nothing has proved it yet; verified - the organization has proved control (and only then does the domain carry any authority, e.g. for JIT provisioning); failed - the last verification attempt did not find the proof. A failed claim can be retried.

Signature

type DomainVerificationState = "pending" | "verified" | "failed"

Source

DomainVerificationStrategy (type alias)

How a domain claim is proved.

dns - a TXT record carrying OrganizationDomain.verificationToken, checked by a DomainVerifier the app provides; the only proof an organization can offer for its own claim. manual - the application operator attested the claim out of band (OrganizationService.attestDomain); no organization member can make or verify a manual claim.

Signature

type DomainVerificationStrategy = "dns" | "manual"

Source

DomainVerifier (class)

Proof-of-control check for a claimed domain, kept as a contract so core adds no DNS dependency.

verify answers whether domain currently publishes token (conventionally as a TXT record). Implement it over whatever resolver your runtime has - Node dns/promises, Cloudflare’s DoH endpoint, a hosting provider’s API - and provide it with Layer.succeed(DomainVerifier)(impl). Without it in context no organization can verify a domain, and the operator’s OrganizationService.attestDomain is the only route to a verified one.

Signature

declare class DomainVerifier

Source

FullOrganization (interface)

An organization together with its member list

Signature

export interface FullOrganization {
  readonly organization: Organization
  readonly members: ReadonlyArray<Member>
}

Source

Invitation (interface)

An email invitation to join an organization.

The invitation link carries a secret token: only the token’s SHA-256 digest is stored, and presenting the token is what proves the invitee holds the invited address. The id alone accepts nothing.

Signature

export interface Invitation {
  readonly id: string
  readonly organizationId: string
  /** Normalized (trimmed, lowercased) invitee email */
  readonly email: string
  /**
   * SHA-256 hex digest (`hashToken`) of the invitation's secret token. The
   * raw token reaches the invitee once, through
   * {@link OrganizationConfig.sendInvitationEmail}; a resend replaces it.
   */
  readonly tokenHash: string
  /** Role the invitee receives upon acceptance */
  readonly role: string
  readonly status: InvitationStatus
  /**
   * User id of the member who issued the invitation, or last resent it. At
   * acceptance they must still hold `invitation:create` and be able to grant
   * {@link role}.
   */
  readonly inviterId: string
  /** Epoch milliseconds */
  readonly expiresAt: number
  /** Epoch milliseconds */
  readonly createdAt: number
  /**
   * When the invitation's latest email was sent, in epoch milliseconds; the
   * resend cooldown runs from it. Absent on rows written before it existed,
   * which read as {@link createdAt}.
   */
  readonly sentAt?: number
}

Source

InvitationDelivery (interface)

What OrganizationConfig.sendInvitationEmail delivers: the stored invitation, its organization, and the raw secret token for the link.

Signature

export interface InvitationDelivery {
  readonly invitation: Invitation
  readonly organization: Organization
  /** The invitation's secret token (256 bits, base64url); put it in the link. */
  readonly token: string
}

Source

InvitationResponseInput (interface)

The invitee’s answer to an invitation: its id and, unless the user’s matching email identifier is verified, the secret token the invitation email carried.

Signature

export interface InvitationResponseInput {
  readonly invitationId: string
  /**
   * The invitation email's secret token. Omit it to answer from a verified
   * matching email identifier (an in-app "pending invitations" list); an
   * unverified one needs the token, which is then its first proof.
   */
  readonly token?: string
}

Source

InvitationStatus (type alias)

Lifecycle states of an invitation.

Signature

type InvitationStatus = "pending" | "accepted" | "rejected" | "canceled"

Source

InviteMemberInput (interface)

Input for inviting a member by email

Signature

export interface InviteMemberInput {
  readonly email: string
  readonly role: string
}

Source

Member (interface)

A user’s membership in an organization.

Signature

export interface Member {
  readonly id: string
  readonly organizationId: string
  readonly userId: string
  /** Role name, resolved against the configured role → permission map */
  readonly role: string
  /**
   * Membership lifecycle state. Absent means `"active"`, so rows written
   * before member deactivation existed keep working unchanged.
   */
  readonly status?: MemberStatus
  /**
   * The role the member held when they were deactivated, restored on
   * reactivation. Only set while `status` is `"inactive"`.
   */
  readonly previousRole?: string
  /** Epoch milliseconds */
  readonly createdAt: number
}

Source

MemberStatus (type alias)

Lifecycle states of a membership.

An inactive member keeps its row (history, team memberships and the restorable role survive) but is treated as a non-member by every authorization question - see isActiveMember.

Signature

type MemberStatus = "active" | "inactive"

Source

OrgRole (interface)

A role defined at runtime by one organization (dynamic access control).

An OrgRole replaces the static OrganizationConfig.roles entry of the same name, for that organization only: permission resolution never merges the two, so a tenant’s role grants exactly the permissions it lists. Permissions are "resource:action" strings and may use the "*" wildcard ("team:*", "*:*"), matched with permissionMatches.

The protected owner role (OrganizationOwnerRole, default owner) can never be redefined this way - see OrganizationService.upsertOrgRole.

Signature

export interface OrgRole {
  /**
   * The definition's own id, kept when the role is redefined; the HTTP tier
   * addresses it as `/organization-roles/:id`.
   */
  readonly id: string
  readonly organizationId: string
  /** Role name, as it appears on a {@link Member} */
  readonly role: string
  /** `"resource:action"` permission strings, `"*"` wildcards allowed */
  readonly permissions: ReadonlyArray<string>
  /** Epoch milliseconds */
  readonly createdAt: number
  /** Epoch milliseconds */
  readonly updatedAt: number
}

Source

Organization (interface)

An organization (team / tenant).

Signature

export interface Organization {
  readonly id: string
  readonly name: string
  /** URL-friendly unique identifier */
  readonly slug: string
  readonly logo?: string
  /** Arbitrary app-specific metadata */
  readonly metadata: Types.JsonObject
  /**
   * Role given to members added without an explicit one (direct
   * {@link OrganizationService.addMember}, JIT provisioning, SCIM). Absent
   * means `"member"`. Only owners may change it - see
   * {@link OrganizationService.setDefaultRole}.
   */
  readonly defaultRole?: string
  /**
   * Whether a user signing in through SSO whose verified email domain matches
   * one of this organization's *verified* domains is added as a member
   * automatically. Absent means `false`: silent domain absorption is opt-in.
   */
  readonly jitProvisioning?: boolean
  /** Epoch milliseconds */
  readonly createdAt: number
}

Source

OrganizationConfig (interface)

Organization service configuration

Signature

export interface OrganizationConfig {
  /** Whether users may create organizations at all (default: true) */
  readonly allowUserToCreateOrganization?: boolean
  /**
   * Maximum number of organizations a user may hold before creating another
   * (default: 5). Only memberships the user chose count: organizations they
   * own (hold the creator role in) or joined by accepting an invitation. A
   * membership someone else made for them (a managed user's direct add, JIT
   * provisioning, SCIM) does not, so nobody can fill another user's quota.
   */
  readonly organizationLimit?: number
  /** Maximum number of members per organization (default: 100) */
  readonly membershipLimit?: number
  /**
   * Maximum number of pending, unexpired invitations per organization
   * (default: 100). `inviteMember`, and a resend that revives an expired
   * invitation, refuse past it.
   */
  readonly pendingInvitationLimit?: number
  /**
   * Minimum time in milliseconds between two invitation emails from one
   * organization to one address (default: 60 seconds; `0` turns it off).
   * It covers `resendInvitation` and a fresh `inviteMember` after a
   * cancellation alike; a send inside it fails with `ResendTooSoonError`.
   */
  readonly invitationResendCooldown?: number
  /** Invitation lifetime in milliseconds (default: 48 hours) */
  readonly invitationExpiresIn?: number
  /**
   * Role assigned to the creator of an organization, and the protected owner
   * role of the last-owner safeguards.
   *
   * @deprecated Provide {@link OrganizationOwnerRole} instead, which user
   * deletion reads too. A value other than the reference's makes the layer
   * build die with {@link OrganizationConfigError}.
   */
  readonly creatorRole?: string
  /**
   * Static role → permission map (default: {@link defaultOrganizationRoles}).
   * A per-organization {@link OrgRole} of the same name replaces the entry
   * here for that organization.
   *
   * A member grants a role (adds, invites or promotes someone to it) only
   * when their own role carries every permission that role carries.
   * The default owner role is `"*:*"`; a map that narrows it leaves owners
   * unable to hand out roles carrying what it omits.
   */
  readonly roles?: Record<string, ReadonlyArray<string>>
  /**
   * Invitation email delivery. The email's link carries `delivery.token`,
   * the invitation's secret, which the invitee presents to accept or reject
   * it; the token is never stored and is handed to nothing else.
   * Without this callback no token can reach an invitee, so
   * `inviteMember` and `resendInvitation` refuse.
   */
  readonly sendInvitationEmail?: (delivery: InvitationDelivery) => Effect.Effect<void, OrganizationError>
  /**
   * Called after a member is deactivated, with the updated (inactive)
   * membership.
   *
   * **Deliberate deviation from WorkOS:** deactivating a member there ends
   * that user's sessions. Here it does not, because a session is *app*-scoped
   * while a membership is *organization*-scoped: one user may belong to
   * several organizations, and revoking their sessions because one tenant
   * deactivated them would sign them out of the others too. Everything
   * organization-scoped is already denied the moment the row flips (every
   * permission check treats an inactive member as a non-member), so what
   * remains is an app-level policy question - single-tenant apps usually do
   * want the sign-out, multi-tenant ones usually do not. This hook is where
   * that policy goes: call
   * `sessionManager.invalidateUserSessions(member.userId)` from it if your app
   * wants WorkOS's behavior.
   *
   * Failures propagate to the caller of `deactivateMember` (the membership is
   * already stored by then), matching `sendInvitationEmail`.
   */
  readonly onMemberDeactivated?: (member: Member, organization: Organization) => Effect.Effect<void, OrganizationError>
}

Source

OrganizationDomain (interface)

An email domain claimed by an organization.

An organization holds at most one claim per domain, and at most one claim per domain is verified across all organizations. Several organizations may hold unverified claims on the same domain, each with its own token: whether another tenant claims a domain is never revealed to a tenant, and a pending claim cannot squat a domain its real owner later proves. Only the verified claim carries authority.

Signature

export interface OrganizationDomain {
  readonly id: string
  readonly organizationId: string
  /** Normalized (trimmed, lowercased) domain, e.g. `"acme.test"` */
  readonly domain: string
  readonly verificationState: DomainVerificationState
  readonly verificationStrategy: DomainVerificationStrategy
  /**
   * Random token the DNS TXT record must contain, generated server-side when
   * an organization adds the claim. Absent for `manual` claims.
   */
  readonly verificationToken?: string
  /** Epoch milliseconds */
  readonly createdAt: number
  /**
   * Epoch milliseconds; set when the claim reached `verified`. For a `manual`
   * claim this is when the operator attested it.
   */
  readonly verifiedAt?: number
  /**
   * Who attested a `manual` claim: the id of the platform admin whose
   * `POST /admin/organization-domains` attested it, or whatever the operator's
   * own tooling passed as {@link AttestDomainOptions.attestedBy}. Absent for
   * `dns` claims and for an attestation made without one.
   */
  readonly attestedBy?: string
}

Source

OrganizationDomainStore (class)

Storage for OrganizationDomain claims.

A separate contract from OrganizationStore so apps that never use domains implement nothing: OrganizationService resolves it from ambient context and answers “Organization domains are not enabled” when it is absent, exactly as the SAML pieces do in Sso.ts.

Conventions: lookups answer None when the record does not exist, deletes of unknown ids are no-ops, and failures are reported as AuthError. Put a unique index on (organizationId, domain) and, where the database has partial indexes, a unique index on domain over the verified rows: the service checks both rules before writing, but the indexes are what make them hold under concurrency. Never a unique index on domain alone, which would let one tenant’s pending claim block every other organization. OrganizationService.deleteOrganization releases an organization’s claims before deleting it, so this store needs no cascade of its own - but a direct OrganizationStore.deleteOrganization call bypasses that, so delete the domain rows alongside it if you go around the service.

Signature

declare class OrganizationDomainStore

Source

OrganizationError (class)

Organization error

Signature

declare class OrganizationError

Source

OrganizationService (class)

Organization service

Signature

declare class OrganizationService

Source

OrganizationStore (class)

Storage interface for organizations, members, invitations, teams, and custom organization roles. Implement with your preferred backend (SQL, Redis, …).

Note: deleteOrganization should cascade - implementations are expected to remove the organization’s members, invitations, teams, team memberships, and custom roles (OrgRole) as well. deleteTeam cascades too: it must remove the team’s team-member rows along with the team.

Conventions: lookups answer None when the record does not exist, deletes of unknown ids are no-ops, and failures are reported as AuthError.

Signature

declare class OrganizationStore

Source

Team (interface)

A team: a named sub-group of an organization.

Teams are managed with the organization-scoped team:* permissions; the membership rows (TeamMember) deliberately carry no role of their own.

Signature

export interface Team {
  readonly id: string
  readonly organizationId: string
  readonly name: string
  /** Epoch milliseconds */
  readonly createdAt: number
  /** Epoch milliseconds */
  readonly updatedAt: number
}

Source

TeamMember (interface)

A user’s membership in a team.

Team membership is orthogonal to the organization role: it grants no permissions by itself. The user is always also a Member of the team’s organization.

Signature

export interface TeamMember {
  /** The membership's own id; the HTTP tier addresses it as `/team-members/:id`. */
  readonly id: string
  readonly teamId: string
  readonly userId: string
  /** Epoch milliseconds */
  readonly createdAt: number
}

Source

UpdateOrganizationInput (interface)

Partial update of an organization’s fields

Signature

export interface UpdateOrganizationInput {
  readonly name?: string
  readonly slug?: string
  readonly logo?: string
  readonly metadata?: Types.JsonObject
  /**
   * Turn JIT provisioning on or off. Gated on `organization:update` like the
   * rest of this input - the same tier that adds the verified domains JIT
   * acts on. The *role* JIT hands out stays owner-only
   * ({@link OrganizationService.setDefaultRole}).
   */
  readonly jitProvisioning?: boolean
}

Source

UpdateTeamInput (interface)

Partial update of a team’s fields

Signature

export interface UpdateTeamInput {
  readonly name?: string
}

Source

UpsertOrgRoleInput (interface)

Input for defining (or redefining) a custom organization role

Signature

export interface UpsertOrgRoleInput {
  /** Role name; the protected owner role is rejected */
  readonly role: string
  /** `"resource:action"` permission strings, `"*"` wildcards allowed */
  readonly permissions: ReadonlyArray<string>
}

Source

defaultOrganizationRoles

Default role → permission map, mirroring better-auth’s built-in organization roles. Permissions are "resource:action" strings.

  • owner - "*:*", every permission: organization update/delete, member, invitation, domain and team management, role:manage for custom organization roles and the default role, and any application permission, so an owner can grant every custom role under the grant rule
  • admin - member, invitation, domain and team management plus organization updates, but cannot delete the organization or manage custom roles
  • member - read-only participant (no management permissions; may still read the organization’s teams and domains)

Override via OrganizationConfig.roles. A map that omits domain:manage simply leaves domain management to nobody - resolution fails closed, as it does for every other permission.

Signature

declare const defaultOrganizationRoles: Record<string, ReadonlyArray<string>>

Source

isActiveMember

Whether a membership counts for authorization: status absent (the historical shape) or "active".

Signature

declare const isActiveMember: (member: Member) => boolean

Source

make

Create an organization service

Signature

declare const make: (
  config?: OrganizationConfig
) => Effect.Effect<
  typeof OrganizationService.Service,
  never,
  | OrganizationStore
  | IdentifierStore
  | EmailPasswordStore
  | SessionService
  | UserStore
  | SecureRandom.SecureRandom
  | Digest.Digest
>

Source

memoryOrganizationDomainStore

In-memory OrganizationDomainStore, keyed by claim id. Single-process only - good for tests and single-instance deployments.

Pass your own MutableHashMap to inspect or pre-seed state in tests.

Signature

declare const memoryOrganizationDomainStore: (
  records?: MutableHashMap.MutableHashMap<string, OrganizationDomain>
) => typeof OrganizationDomainStore.Service

Source

missingPermission

The refusal of an operation that needs permission in an organization. A stranger, a deactivated member, a member without the permission and an id that names no record get this same error, so the refusal never confirms that an organization or a record exists.

Signature

declare const missingPermission: (permission: string) => OrganizationError

Source

notAMember

The refusal of a member-only read. A stranger, a deactivated member and an id that names no record get this same error.

Signature

declare const notAMember: () => OrganizationError

Source


This site uses Just the Docs, a documentation theme for Jekyll.