An invoice goes unpaid for a quarter, or a customer’s contract ends and they ask for their data to be erased. Either way the account has to stop, for everybody in it, without reaching the people in it who also work somewhere else. Your support desk does it through the control plane, and every step leaves a reason in the trail.
An organization can be suspended or deleted. The kit holds the state, enforces it at every door a member uses, records every transition, and tells the owners. An operator acts through the six routes below; an owner deletes their own through DELETE {base}/current, the same hard deletion with the owner as its actor. It has the shape a person’s account lifecycle has, and one rule of its own about members.
| Route | Scope | What it does |
|---|---|---|
POST {base}/admin/organizations/:organizationId/suspend | organization:accounts:suspend | Suspend it, until until or a reinstatement. A second call restates the reason and the end, keeping the start |
POST …/suspend/preview | organization:accounts:suspend | Who the suspension’s cascade would reach, with nothing applied. The suspension’s body and refusals |
POST …/reinstate | organization:accounts:suspend | Lift the suspension. No suspension in force is a 200 that changed nothing |
DELETE {base}/admin/organizations/:organizationId | organization:accounts:delete | Delete it. Soft by default; mode: "hard" purges now |
POST …/delete/preview | organization:accounts:delete | Who the deletion’s cascade would reach, soft or hard, with nothing applied. The deletion’s body and refusals |
POST …/restore | organization:accounts:delete | Restore it inside its window, with every membership it had |
Each is reached only by a registered connection holding the scope it names. The two scopes are separate from each other and from every read and write scope, so a client holding neither is refused 403 on all six. An unknown :organizationId is a 404 on every one, never a 403.
Two states
| State | Columns | What it means | Ends |
|---|---|---|---|
| Suspended | suspended_at, suspended_until | Nobody can act in it. It is gone from every member’s list | At suspended_until, by itself, or when an operator reinstates it |
| Deleted | deleted_at, purge_after | The same, and its data is due for erasure once the purge window closes. Restorable, memberships and all, until then | When it is restored inside the window, or when the purge erases it |
Both live on pithy_organization_organizations, so the read that already joins a membership to its organization carries them. A deletion outranks a suspension the organization was already under. A suspension past its suspended_until is not a suspension, and nothing has to run to end it.
What a suspension means for a member
Nobody can act in a suspended organization. A member whose session acts in it is refused 403 organization/organization_suspended on the next request, and their selection of it is cleared in the same request. A route that names the organization refuses its members the same way, and so does choosing it. params.suspendedUntil says when it ends, when it does. A stranger still gets organization/not_found: the 403 only ever answers somebody already proved to be a member, so it tells nobody about an account they could not already see.
It leaves every member’s list. GET {base} lists what a person may act in, and a suspended or deleted organization is not that. Beside the list it answers suspended: how many of the caller’s own organizations are suspended. A member whose only organization is suspended has nothing to choose, and the count is what tells a chooser they are not somebody who belongs nowhere. A deleted organization is not counted.
A member of several organizations carries on in the others, unchanged. Suspending one organization writes nothing to anybody’s account. Their memberships elsewhere, their selection of another organization, their sessions and their account all stand. The suspended one simply stops being theirs until it is reinstated.
pithy ui add react ships an organization suspended screen, and pithy ui add react-native ships the same screen for a React Native app. The scaffolded chooser sends a member there when their list is empty and suspended is not zero, and when the organization they pick was suspended after the list was drawn. Your own screens do the same with organizationRefusal(code) === "suspended", from @pithy-sh/organization/src/index.
A deleted organization is refused as one that is not there: organization/not_found, to a member and a stranger alike, and every session’s selection of it is cleared when it is deleted.
A repeated founding answers the same way. A POST {base} that repeats an idempotencyKey whose organization is now deleted answers organization/not_found, and one whose organization is suspended answers organization/organization_suspended, with its suspendedUntil. The founding record stays until the purge erases the organization, so the key keeps answering that 404 until then. A restore makes the repeat answer as the restored organization now stands: 200 with it, or the 403 while a suspension is still in force. An owner’s DELETE {base}/current and an operator’s hard deletion start the purge at once, and the key is freed when it erases the founding record with the organization. From then on it founds a new one. Using Organization has the key itself.
It takes nobody in. An invitation to a suspended or deleted organization reads as organization/invitation_invalid, on the accept screen’s read and on the accept itself, so no membership is written into a shut account. The offer stays pending: once the organization is reinstated or restored, the link works again until it expires.
The member cascade
A suspension or a deletion reaches the people in the organization only on purpose: members: "sole" in the body. The default, and what leaving it out means, is members: "none", which touches nobody.
sole reaches only a member whose one and only organization this is. A member of any other organization is never modified, whatever state that other organization is in. “Suspend the account and its users” written naively locks a person out of every other tenant they work in; this cannot.
It runs through the user lifecycle, not around it. A reached account is suspended, or deleted the way the organization is, soft or hard, by auth’s own transitions, with the organization’s reason: the same columns, history row, auth/admin_user_* audit event, mail and hook an operator acting on that one person would produce. A hard cascade starts each reached account’s purge, or leaves it to auth’s daily pass. An account already suspended keeps its own suspension, its reason and its end. One already deleted is left as it is.
The response says who was reached, who was not, and why. members.reached lists each account suspended or deleted. members.skipped lists each member left alone, with a reason: member_elsewhere, actor for the owner who deleted it through DELETE {base}/current, already_suspended, account_deleted, no_account, or failed when the user transition refused, which the log explains. The audit event carries the counts, never the people.
Preview it before it runs. POST {base}/admin/organizations/:organizationId/suspend/preview and …/delete/preview take the write’s own body, under the write’s own scope, and answer { organizationId, members }: the same reached and skipped, computed by the function the write calls, with nothing applied. members absent or none answers an empty cascade. A body the write would refuse — no reason, an end in the past, a deleted organization’s suspension, a sole cascade on a Worker with no auth composed — is refused with the same error, so a client cannot preview an act it could not then take. A preview writes nothing: no column, no history row, no mail, no hook, no audit event; the write that follows is the one on the trail. Who belongs to no other organization is a disclosure, which is why it sits behind the write’s scope. It is a snapshot: a membership added or removed between the preview and the write changes what the write does, and the write’s own response is the record of what happened. A preview never says failed, which only a write that ran can report.
Nothing undoes a cascade silently. Reinstating the organization lifts nobody’s own suspension, and restoring it restores nobody’s account. Both responses list membersStillShut: every member whose own account is still suspended or deleted. Reinstate or restore each through auth’s own routes.
Every one takes a reason
reason is required in the JSON body of all six, a DELETE included: at most 500 characters, with no email address. Each write records an organization/admin_organization_* event with the operator, the connection, the reason and the tenant; the two previews record none. A deleted organization cannot be suspended or reinstated: the refusal is 409 core/conflict, naming the restore route, and a suspension it was under is still there to lift once it is restored.
Delete, and restore
Soft, the default: shut now, gone from every list, every selection of it cleared, its memberships kept. purge_after is now plus the purge window: retention.purgeWindows.organization from the Worker’s retention block in pithy.config.ts when it names one, otherwise organization’s own retention.purgeAfterDays, 30 unless you set it. The response says purge: "scheduled".
Hard, mode: "hard": the window closes now, nothing can restore it, and the purge starts in the same call. purge is started, or pending when this Worker binds no purge Workflow, and the daily pass starts it then. A hard deletion of one already deleted softly brings its purge forward; outcome says deleted, brought_forward or unchanged.
Restore clears both columns inside the window and fires onOrganizationRestored. Its memberships were never removed, so every member sees it again. A suspension it was under is still in force, and the response says state: "suspended". Once purge_after has passed, a restore is 409 core/conflict naming the date. After the purge there is no organization: a 404, whose action says the data is gone.
GET {base}/admin/organizations says where each tenant stands: state, suspendedUntil and purgeAfter. It narrows on it with ?state=active, suspended or deleted, judged as every door judges it, and pages on nextCursor.
The owner’s deletion
DELETE {base}/current, under organization:delete in the organization the session acts in, is a hard deletion through this lifecycle. The organization is shut at once: refused to every member, gone from every list, every selection of it cleared. A deleted row records actor type owner, the owner’s user id, the reason and mode hard, onOrganizationDeleted fires, and the purge starts. Nothing is erased inside the request. There is no window and no restore, and no mail is sent, as for any hard deletion.
The body is optional. reason follows an operator’s rules: at most 500 characters, no email address. With none, or no body at all, Deleted by its owner. is recorded. The response is { organizationId, deletedAt, purge }: purge is started, or pending when this Worker binds no ORGANIZATION_PURGE Workflow or the start failed, and the daily pass starts it then. The audit event is organization/deleted, with the purge state, the cascade’s counts, and the reason when the owner gave one.
ownerDelete.members decides whose accounts go with it. none, the default, deletes nobody’s. sole runs the member cascade, hard: the members whose only organization this is are deleted through auth’s own lifecycle, recorded as user with the owner as the acting user. The owner’s own account is never touched, and is listed as skipped with the reason actor. With sole the response carries members; with none it does not.
Your own route can run the same deletion. deleteOrganizationAsOwner(c, { reason }), from @pithy-sh/organization/src/lifecycle/ownerDelete, is the code DELETE {base}/current runs, for a route that checks something first, such as a typed name. It refuses a role without organization:delete itself, and checks no origin: a cookie session can carry the deletion, so mount requireSameOrigin() first, then requireAuth() and requireOrganization(), as the kit’s own route does.
import type { D1Database } from "@cloudflare/workers-types";
import { requireAuth } from "@pithy-sh/auth/src/http/middleware";
import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
import { validate } from "@pithy-sh/core/src/http/validation";
import { organizationDatabase } from "@pithy-sh/organization/src/data/tables";
import { type OrganizationHonoEnv, requireOrganization } from "@pithy-sh/organization/src/http/guard";
import { deleteOrganizationAsOwner } from "@pithy-sh/organization/src/lifecycle/ownerDelete";
import { Hono } from "hono";
import { z } from "zod";
import { roles } from "./organization/roles";
const deps = {
catalog: roles,
database: (env: Record<string, unknown>) => organizationDatabase(env.DB as D1Database),
};
const CloseBody = z
.object({ name: z.string().describe("The organization's name, typed to confirm the deletion.") })
.describe("Close the organization the session acts in.");
const app = new Hono<OrganizationHonoEnv>();
app.post(
"/settings/close",
requireSameOrigin(),
requireAuth(),
requireOrganization(deps),
validate("json", CloseBody),
async (c) => {
if (c.req.valid("json").name !== c.var.acting.name) throw new ValidationError({ message: "Type the name." });
const deleted = await deleteOrganizationAsOwner(c, { reason: "Closed from settings." });
return c.json({ purge: deleted.purge });
},
);The record
pithy_organization_lifecycle holds every transition: the action, the actor, the reason, the time. The columns say what is true now; the table says what happened and who did it, and the two are written in one transaction. It has no foreign key to the organization, because the purge erases that row and this record has to outlive it. The actor is control-plane, owner or system. A transition that finds the organization already where it was asked to put it writes no row and fires no hook.
The purge
A purge erases one deleted organization from every composed capability that declares what erasing it means. It runs as a Workflow, one step per composed purge contribution for the organization subject, named for its capability, so a capability that fails retries alone and the steps that finished are not run again. A contribution that retains its rows is a step too: it records purge_retained, with the basis it gave and its basisKey, and erases nothing. Each contribution’s erase is handed deletion: { actor, reason, mode, at } beside the subject, read from the newest deleted row, so it can tell members or record the act without reading this capability’s tables. An owner’s deletion and an operator’s both fill it; a deletion recorded before the history kept a mode leaves it absent. Organization’s own step runs last, because the others may still read a membership: it deletes the organization, its memberships, invitations, ownership offer, founding records and selections, and your onDelete rows in the same batch. Once the founding record is gone, the key that founded it founds a new organization. Then the purged record, organization/purged, and onOrganizationPurged, once.
Every organization purge can be proved, the way a person’s is. Every step also records organization/purge_step in the organization’s own audit chain, with the step’s name and whether it erased or retained, and a purge that runs out of retries records a purge_failed row and organization/purge_failed, naming the step, before the run fails. The deleted row keeps the deletion’s mode and when its purge comes due. The erasure attestation reads them: GET /control-plane/erasure/organization/:organizationId, under erasure:read, and the period read counts organization purges beside people’s.
A legal hold stops it. The daily pass starts no purge for an organization a hold stands on. A purge already running asks before each step whether one stands, and a hold found ends the run as held with nothing more erased; once the hold is released, the next daily pass starts it again and its finished steps find nothing left to erase. Holds are placed over the control plane: retention and legal holds.
Three kit capabilities declare one. Media deletes every record whose organizationId is the organization’s, with its bytes in R2, Cloudflare Images or Stream, and its dedup hashes. Storage deletes every file whose organizationId is the organization’s, with its bytes in R2 and every share link to it. Each deletes the bytes before the row, so a step that fails keeps the rows that say where the rest is, and retries. Payments declares none: an organization’s purchases and entitlements are billing records, and the purge leaves them.
A person’s purge is a different subject. Organization declares a user contribution too: it erases the person’s memberships, the organization each of their sessions acted for, every ownership offer made to or by them, every founding record of theirs, with the idempotency key their client chose, and every invitation addressed to them, and exports them first, never an invitation’s token digest. An invitation they sent and the organization’s lifecycle history keep their id, which names nobody once the account is gone. An organization they were the last owner of is left without one, and an operator gives it an owner again. What each capability does with a person’s rows has the rest of the kit.
A capability that declares no contribution is not touched by the purge, whatever rows it holds. Declare one for your own tenanted tables on your app capability, beside its user contribution:
purge: [
{
subject: "organization",
summary: "Deletes the organization's uploads.",
erase: async ({ subject, env, deletion }) => {
// deletion?.actor.type is "owner", "control-plane" or "system"; deletion?.reason is why.
},
},
],A daily cron at 02:00 UTC, the one auth’s purge uses, starts the purge for every organization past its purge_after. The instance is named for the deletion and the UTC day, so a hard deletion and the daily pass start one purge, not two.
The Workflows are yours to export, for the reason auth’s are: only the Worker that composes the capabilities has their contributions.
// apps/api/src/index.ts
import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
import { NonRetryableError } from "cloudflare:workflows";
import { runOrganizationPurge, runOrganizationPurgeDue } from "@pithy-sh/organization/src/purge/workflow";
export class OrganizationPurgeWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
return runOrganizationPurge(this.env, event, step, NonRetryableError);
}
}
export class OrganizationPurgeDueWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
return runOrganizationPurgeDue(this.env, event, step, NonRetryableError);
}
}// apps/api/wrangler.jsonc, in each environment's stanza
"workflows": [
{ "binding": "ORGANIZATION_PURGE", "name": "acme-prod-organization-purge", "class_name": "OrganizationPurgeWorkflow" },
{ "binding": "ORGANIZATION_PURGE_DUE", "name": "acme-prod-organization-purge-due", "class_name": "OrganizationPurgeDueWorkflow" }
],
"triggers": { "crons": ["0 2 * * *"] }Until they are bound, a deletion still shuts the organization, a hard deletion reports its purge as pending, and nothing is erased.
Who is told
The owners: the members holding the role your ownership pair confers or, with no pair, the members whose role holds organization:delete. Three templates in email, all transactional, in each owner’s own language:
organizationSuspended, with the reason and any end. Unlike an operator’s membership notices, this one carries the reason, because the suspended screen tells every member the owners were told why. An owner asolecascade reached is sent their own account’s suspension notice instead, because this one says their account is unaffected.organizationReinstated.organizationDeletionScheduled, with the date the data is erased.
A hard deletion sends none. With no email composed nothing is sent and nothing is refused, and the audit event records mailed: null.
Config and hooks
organization({
roles,
// How long a deleted organization waits before the purge erases it. 30 when nothing says otherwise.
retention: { purgeAfterDays: 30 },
// Whose accounts an owner's DELETE {base}/current takes with it: "none", or "sole".
ownerDelete: { members: "none" },
// All three send by default. Turn one off by setting it to false.
lifecycleEmails: { organizationSuspended: true, organizationReinstated: true, organizationDeletionScheduled: true },
onOrganizationSuspended: async (event, d1, runtime) => {},
onOrganizationReinstated: async (event, d1, runtime) => {},
onOrganizationDeleted: async (event, d1, runtime) => {},
onOrganizationRestored: async (event, d1, runtime) => {},
onOrganizationPurged: async (event, d1, runtime) => {},
}),Each hook fires once per transition that happened, after it is written. A hook that throws is logged and swallowed, and the transition stands.
onOrganizationRestored is the undo for onOrganizationDeleted. It fires when a deleted organization is restored inside its window, with the operator, the reason and at. Restoring one that is not deleted fires nothing, and neither does a restore refused because the window closed.
organization({
roles,
onOrganizationDeleted: async ({ organizationId, at }, d1) => {
await d1.prepare("update workspaces set archived_at = ? where org_id = ?").bind(at.getTime(), organizationId).run();
},
onOrganizationRestored: async ({ organizationId }, d1) => {
await d1.prepare("update workspaces set archived_at = null where org_id = ?").bind(organizationId).run();
},
}),Each hook is handed the event, the D1 binding, and runtime: { env, waitUntil? }. env is the Worker’s environment, so a hook can read a secret, start a Workflow, send to a queue, or call out. Call organization.withEnv<Env>()({ … }) with your own Env and runtime.env is typed as it, with no cast. The catalog’s roles are still inferred from roles, so an ownership pair naming a role it does not declare is still a compile error. organization<Env>() would not do this: TypeScript infers all of a call’s type arguments or none.
waitUntil is the request’s ExecutionContext.waitUntil. It is there when the hook fires inside a request, and absent when it fires from the purge Workflow, which has no ExecutionContext. onOrganizationPurged always fires from the Workflow. Check for it before you call it.
Outside work belongs in a Workflow. The hook only starts it: it cannot fail the transition, and the Workflow retries the call.
interface Env {
REVOKE_GRANTS: Workflow<{ organizationId: string }>;
}
organization.withEnv<Env>()({
roles,
onOrganizationDeleted: async ({ organizationId }, _d1, { env }) => {
await env.REVOKE_GRANTS.create({ params: { organizationId } });
},
}),A hook written as (event, d1) still compiles and runs unchanged.
Two membership hooks are passed the same way, handed the same runtime, and fire on a member rather than on the organization: after a role change or the end of a membership is written and recorded, once per member it changed, through every route that makes one — a member’s own, an ownership transfer accepted or forced, and an operator’s.
organization({
roles,
// A role changed. `powersLost` is what the old role held and the new one does not, from the catalog's nesting; empty for a promotion.
onMemberRoleChanged: async ({ organizationId, membershipId, userId, previousRole, role, powersLost, actor, at }, d1, runtime) => {},
// A membership ended: removed, left (`left: true`), removed by an operator, or removed by a forced transfer.
onMemberRemoved: async ({ organizationId, membershipId, userId, role, left, actor, at }, d1, runtime) => {},
}),actor is { type: "member", userId } or { type: "control-plane", connectionId }. A hook that throws is logged and swallowed, and the change stands. A hook cannot undo the write it heard about. A row that must begin with a membership belongs in onJoin, which joins the batch that writes it: your own rows, in the same write. The hooks exist so a management client can re-check what a demoted member’s agents were granted, and revoke what a departed one authorized.
What it does not do
Delete from inside the account softly. DELETE {base}/current is always a hard deletion: shut at once and purged, with no window to restore it in. The window and the restore are an operator’s.