diff --git a/AGENTS.md b/AGENTS.md index f3c4f9f7e..a166fed77 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,6 +27,7 @@ import { Activity } from "react"; ; ``` +- Always use skeletons for loading feedback. Use `` only if its necessary. - Add a breadcrumb with the route's `staticData.breadcrumb`; a crumb that renders strings needs its own `RouteMessages`. - Route files are topology only - `validateSearch`, `loaderDeps`, `loader`, `head`, `staticData`. The query, the permissions, the namespaces and the screen live in `@vitnode/core/tanstack/*`. - Write `head` **after** `loader` in the same object literal: `loaderData` is inferred from `loader`, and TypeScript reads members in order. diff --git a/apps/api/migrations/20261120192831_gdpr_account_deletion/migration.sql b/apps/api/migrations/20261120192831_gdpr_account_deletion/migration.sql new file mode 100644 index 000000000..7adeddd63 --- /dev/null +++ b/apps/api/migrations/20261120192831_gdpr_account_deletion/migration.sql @@ -0,0 +1,26 @@ +CREATE TABLE "core_users_deletions" ( + "id" serial PRIMARY KEY, + "userId" integer, + "erasedUserId" integer NOT NULL, + "source" varchar(16) NOT NULL, + "requestedById" integer, + "status" varchar(16) DEFAULT 'pending' NOT NULL, + "scheduledAt" timestamp NOT NULL, + "attempts" integer DEFAULT 0 NOT NULL, + "lastError" text, + "filesDeleted" integer DEFAULT 0 NOT NULL, + "filesKept" integer DEFAULT 0 NOT NULL, + "createdAt" timestamp DEFAULT now() NOT NULL, + "cancelledAt" timestamp, + "completedAt" timestamp +); +--> statement-breakpoint +ALTER TABLE "core_users_deletions" ENABLE ROW LEVEL SECURITY;--> statement-breakpoint +ALTER TABLE "core_roles" ADD COLUMN "allowDeleteAccount" boolean DEFAULT true NOT NULL;--> statement-breakpoint +ALTER TABLE "core_users" ALTER COLUMN "ipAddress" DROP NOT NULL;--> statement-breakpoint +CREATE UNIQUE INDEX "core_users_deletions_pending_user_unique" ON "core_users_deletions" ("userId") WHERE "status" = 'pending';--> statement-breakpoint +CREATE INDEX "core_users_deletions_status_scheduled_idx" ON "core_users_deletions" ("status","scheduledAt");--> statement-breakpoint +CREATE INDEX "core_users_deletions_erased_user_idx" ON "core_users_deletions" ("erasedUserId");--> statement-breakpoint +CREATE INDEX "core_users_deletions_created_at_id_idx" ON "core_users_deletions" ("createdAt","id");--> statement-breakpoint +ALTER TABLE "core_users_deletions" ADD CONSTRAINT "core_users_deletions_userId_core_users_id_fkey" FOREIGN KEY ("userId") REFERENCES "core_users"("id") ON DELETE SET NULL;--> statement-breakpoint +ALTER TABLE "core_users_deletions" ADD CONSTRAINT "core_users_deletions_requestedById_core_users_id_fkey" FOREIGN KEY ("requestedById") REFERENCES "core_users"("id") ON DELETE SET NULL; \ No newline at end of file diff --git a/apps/api/migrations/20261120192831_gdpr_account_deletion/snapshot.json b/apps/api/migrations/20261120192831_gdpr_account_deletion/snapshot.json new file mode 100644 index 000000000..b9c88216e --- /dev/null +++ b/apps/api/migrations/20261120192831_gdpr_account_deletion/snapshot.json @@ -0,0 +1,615 @@ +{ + "type": "diff", + "version": "9", + "dialect": "postgres", + "id": "d68f291f-7e91-4b91-b606-bca1ba71055c", + "prevIds": [ + "87dc294c-d906-4784-83d9-3d9c814ef7a4" + ], + "footprints": [ + { + "statementType": "create_table", + "statementTarget": [ + "table", + "public", + "core_users_deletions" + ], + "writes": [ + "s|tbl|public.core_users_deletions", + "n|tbl|public.core_users_deletions", + "e|tbl|public.core_users_deletions", + "n|rel|public.core_users_deletions", + "n|type|public.core_users_deletions", + "n|rel|public.core_users_deletions_pkey" + ], + "reads": [ + "n|sch|public" + ] + }, + { + "statementType": "add_column", + "statementTarget": [ + "column", + "public", + "core_roles", + "allowDeleteAccount" + ], + "writes": [ + "s|col|public.core_roles.allowDeleteAccount", + "n|col|public.core_roles.allowDeleteAccount", + "e|col|public.core_roles.allowDeleteAccount" + ], + "reads": [ + "n|tbl|public.core_roles", + "n|sch|public" + ] + }, + { + "statementType": "alter_column", + "statementTarget": [ + "column", + "public", + "core_users", + "ipAddress" + ], + "writes": [ + "s|colprop|public.core_users.ipAddress.notNull" + ], + "reads": [ + "n|tbl|public.core_users", + "n|sch|public", + "n|col|public.core_users.ipAddress" + ], + "sqlHash": "0676d6f8140f127a" + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "core_users_deletions", + "core_users_deletions_pending_user_unique" + ], + "writes": [ + "s|idx|public.core_users_deletions_pending_user_unique", + "n|idx|public.core_users_deletions_pending_user_unique", + "e|idx|public.core_users_deletions_pending_user_unique", + "n|rel|public.core_users_deletions_pending_user_unique" + ], + "reads": [ + "n|tbl|public.core_users_deletions", + "n|sch|public", + "n|col|public.core_users_deletions.userId" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "core_users_deletions", + "core_users_deletions_status_scheduled_idx" + ], + "writes": [ + "s|idx|public.core_users_deletions_status_scheduled_idx", + "n|idx|public.core_users_deletions_status_scheduled_idx", + "e|idx|public.core_users_deletions_status_scheduled_idx", + "n|rel|public.core_users_deletions_status_scheduled_idx" + ], + "reads": [ + "n|tbl|public.core_users_deletions", + "n|sch|public", + "n|col|public.core_users_deletions.status", + "n|col|public.core_users_deletions.scheduledAt" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "core_users_deletions", + "core_users_deletions_erased_user_idx" + ], + "writes": [ + "s|idx|public.core_users_deletions_erased_user_idx", + "n|idx|public.core_users_deletions_erased_user_idx", + "e|idx|public.core_users_deletions_erased_user_idx", + "n|rel|public.core_users_deletions_erased_user_idx" + ], + "reads": [ + "n|tbl|public.core_users_deletions", + "n|sch|public", + "n|col|public.core_users_deletions.erasedUserId" + ] + }, + { + "statementType": "create_index", + "statementTarget": [ + "index", + "public", + "core_users_deletions", + "core_users_deletions_created_at_id_idx" + ], + "writes": [ + "s|idx|public.core_users_deletions_created_at_id_idx", + "n|idx|public.core_users_deletions_created_at_id_idx", + "e|idx|public.core_users_deletions_created_at_id_idx", + "n|rel|public.core_users_deletions_created_at_id_idx" + ], + "reads": [ + "n|tbl|public.core_users_deletions", + "n|sch|public", + "n|col|public.core_users_deletions.createdAt", + "n|col|public.core_users_deletions.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "core_users_deletions" + ], + "writes": [ + "s|fk|public.core_users_deletions.core_users_deletions_userId_core_users_id_fkey", + "n|fk|public.core_users_deletions.core_users_deletions_userId_core_users_id_fkey", + "e|fk|public.core_users_deletions.core_users_deletions_userId_core_users_id_fkey", + "n|con|public.core_users_deletions.core_users_deletions_userId_core_users_id_fkey" + ], + "reads": [ + "n|tbl|public.core_users_deletions", + "n|sch|public", + "n|tbl|public.core_users", + "n|sch|public", + "n|col|public.core_users_deletions.userId", + "n|col|public.core_users.id", + "e|uniqueness|public.core_users.id" + ] + }, + { + "statementType": "create_fk", + "statementTarget": [ + "table", + "public", + "core_users_deletions" + ], + "writes": [ + "s|fk|public.core_users_deletions.core_users_deletions_requestedById_core_users_id_fkey", + "n|fk|public.core_users_deletions.core_users_deletions_requestedById_core_users_id_fkey", + "e|fk|public.core_users_deletions.core_users_deletions_requestedById_core_users_id_fkey", + "n|con|public.core_users_deletions.core_users_deletions_requestedById_core_users_id_fkey" + ], + "reads": [ + "n|tbl|public.core_users_deletions", + "n|sch|public", + "n|tbl|public.core_users", + "n|sch|public", + "n|col|public.core_users_deletions.requestedById", + "n|col|public.core_users.id", + "e|uniqueness|public.core_users.id" + ] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "public", + "name": "core_users_deletions", + "isRlsEnabled": true, + "entityType": "tables" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "id", + "type": "serial", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "userId", + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "erasedUserId", + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "source", + "type": "varchar(16)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "requestedById", + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "status", + "type": "varchar(16)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'pending'", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "scheduledAt", + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "attempts", + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "0", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "lastError", + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "filesDeleted", + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "0", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "filesKept", + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "0", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "createdAt", + "type": "timestamp", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "now()", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "cancelledAt", + "type": "timestamp", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "completedAt", + "type": "timestamp", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_roles", + "name": "allowDeleteAccount", + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "entityType": "columns" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "core_users_deletions_pending_user_unique", + "nameExplicit": true, + "columns": [ + { + "value": "userId", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": "\"status\" = 'pending'", + "with": "", + "method": "btree", + "concurrently": false, + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "core_users_deletions_status_scheduled_idx", + "nameExplicit": true, + "columns": [ + { + "value": "status", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "scheduledAt", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "core_users_deletions_erased_user_idx", + "nameExplicit": true, + "columns": [ + { + "value": "erasedUserId", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "core_users_deletions_created_at_id_idx", + "nameExplicit": true, + "columns": [ + { + "value": "createdAt", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "entityType": "indexes" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "core_users_deletions_userId_core_users_id_fkey", + "nameExplicit": false, + "columns": [ + "userId" + ], + "schemaTo": "public", + "tableTo": "core_users", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "core_users_deletions_requestedById_core_users_id_fkey", + "nameExplicit": false, + "columns": [ + "requestedById" + ], + "schemaTo": "public", + "tableTo": "core_users", + "columnsTo": [ + "id" + ], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "entityType": "fks" + } + }, + { + "op": "create", + "row": { + "schema": "public", + "table": "core_users_deletions", + "name": "core_users_deletions_pkey", + "columns": [ + "id" + ], + "nameExplicit": false, + "entityType": "pks" + } + }, + { + "op": "alter", + "key": "columns\u0000[\"public\",\"core_users\",\"ipAddress\"]", + "set": { + "notNull": false + } + } + ] +} \ No newline at end of file diff --git a/apps/web/content/docs/dev/events/built-in-events.mdx b/apps/web/content/docs/dev/events/built-in-events.mdx index d201b8a95..99e5cbaf5 100644 --- a/apps/web/content/docs/dev/events/built-in-events.mdx +++ b/apps/web/content/docs/dev/events/built-in-events.mdx @@ -108,23 +108,26 @@ while the envelope's `pluginId` names the content type's owner (see ## Core events (`@vitnode/core`) -Nineteen names. The `user.*` definitions are exported from +Twenty-one names. The `user.*` definitions are exported from `@vitnode/api/events/users` (`userCreatedEvent`, `userUpdatedEvent`, -`userDeletedEvent`, `userEmailVerifiedEvent`, `userPasswordUpdatedEvent`, +`userDeletedEvent`, `userDeletionRequestedEvent`, +`userDeletionCancelledEvent`, `userEmailVerifiedEvent`, `userPasswordUpdatedEvent`, `userSessionsRevokedEvent`, `userSsoLinkedEvent`, `userSsoUnlinkedEvent`, `userSsoPreferencesUpdatedEvent`, `userSsoProfileSyncedEvent`, `userPasskeyCreatedEvent`, `userPasskeyUpdatedEvent`, `userPasskeyDeletedEvent`, `userAvatarUpdatedEvent`, `userCoverUpdatedEvent`), `file.editor.uploaded` from `@vitnode/api/events/files` (`fileEditorUploadedEvent`) and `role.*` from `@vitnode/api/events/roles` (`roleCreatedEvent`, `roleUpdatedEvent`, -`roleDeletedEvent`). Every one except `user.deleted`, which core never emits, -fires **after** the write it describes has committed. +`roleDeletedEvent`). Every one fires **after** the write it describes has +committed. | Event | Payload | Fires when | | ------------------------------ | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `user.created` | `{ userId, email, name, emailVerified }` | A user row is inserted - public sign-up, AdminCP creation, or SSO sign-up | | `user.updated` | `{ userId, email, name }` | A user is edited in the AdminCP, or a member saves their own profile, time zone or **Browse anonymously** in **Settings → Overview** | -| `user.deleted` | `{ userId, email }` | Never - the name is declared for plugins, core has no deletion flow | +| `user.deletion.requested` | `{ userId, scheduledAt, source }` | An [account deletion](/docs/dev/working-with-users/account-deletion) is scheduled by the member in **Settings → Privacy & data** or by staff | +| `user.deletion.cancelled` | `{ userId }` | The member or staff cancel a pending deletion | +| `user.deleted` | `{ userId, email }` | An account was erased, after every plugin's `personalData.erase` ran and the account row was deleted | | `user.email.verified` | `{ userId, email }` | An address is [confirmed](/docs/dev/working-with-users/email-verification) - by its link, a completed reset, or by staff | | `user.password.updated` | `{ userId }` | A password is set - by a member completing a reset, or by staff on the AdminCP user page | | `user.sessions.revoked` | `{ userId, deviceId, sessions }` | A user is signed out remotely - one device or all of them, by the member or by staff, or after a password change | @@ -478,17 +481,19 @@ even when nothing changed. from. - + -Its definition, `userDeletedEvent`, exists so listeners type-check, but -**core never emits it**: there is no user-deletion flow yet. It is the -agreed-upon name for plugins that implement account deletion themselves, and -core will emit it once deletion lands. +Emitted once an account is erased: every plugin's `personalData.erase` ran and +the `core_users` row is gone, in one committed transaction. The account no +longer exists, so look nothing up by `userId`. Use it to clean systems outside +the database (a newsletter provider, an external search index). `email` is the +address the account had; never store it. See +[Export and Erase Plugin Data](/docs/dev/working-with-users/personal-data). + + + +`user.deletion.requested` fires when a deletion is scheduled: the member asked +in **Settings → Privacy & data**, or staff scheduled it in the AdminCP. The +account is already signed out everywhere and is erased at `scheduledAt`. +`user.deletion.cancelled` fires when the member or staff keep the account. + + + +**A listener would** pause a member's subscriptions or hide their listings +during the grace period, and restore them on cancel. + @@ -1684,8 +1719,7 @@ High-frequency or consumer-less events are added only when a listener needs them, so the catalog stays meaningful. There is currently no `user.signedIn`, `user.passwordResetRequested`, or `file.uploaded`. If you need one, open an issue or PR - adding an event is a `defineEvent` in `packages/vitnode/src/api/events/` -plus an `emit`. (`user.deleted` is the special case: its definition already -exists, and waits on core growing a user-deletion flow.) +plus an `emit`. Live editing is quiet on the bus too. Taking or giving back a field lock, autosaving the shared draft and every keystroke in a co-edited rich text field diff --git a/apps/web/content/docs/dev/working-with-users/account-deletion-admin-dialog.webp b/apps/web/content/docs/dev/working-with-users/account-deletion-admin-dialog.webp new file mode 100644 index 000000000..0363f0269 Binary files /dev/null and b/apps/web/content/docs/dev/working-with-users/account-deletion-admin-dialog.webp differ diff --git a/apps/web/content/docs/dev/working-with-users/account-deletion-admincp.webp b/apps/web/content/docs/dev/working-with-users/account-deletion-admincp.webp new file mode 100644 index 000000000..1651eedfb Binary files /dev/null and b/apps/web/content/docs/dev/working-with-users/account-deletion-admincp.webp differ diff --git a/apps/web/content/docs/dev/working-with-users/account-deletion-debug.webp b/apps/web/content/docs/dev/working-with-users/account-deletion-debug.webp new file mode 100644 index 000000000..8ad7df8f9 Binary files /dev/null and b/apps/web/content/docs/dev/working-with-users/account-deletion-debug.webp differ diff --git a/apps/web/content/docs/dev/working-with-users/account-deletion-overview.webp b/apps/web/content/docs/dev/working-with-users/account-deletion-overview.webp new file mode 100644 index 000000000..cc854350d Binary files /dev/null and b/apps/web/content/docs/dev/working-with-users/account-deletion-overview.webp differ diff --git a/apps/web/content/docs/dev/working-with-users/account-deletion-settings.webp b/apps/web/content/docs/dev/working-with-users/account-deletion-settings.webp new file mode 100644 index 000000000..c36423e49 Binary files /dev/null and b/apps/web/content/docs/dev/working-with-users/account-deletion-settings.webp differ diff --git a/apps/web/content/docs/dev/working-with-users/account-deletion.mdx b/apps/web/content/docs/dev/working-with-users/account-deletion.mdx new file mode 100644 index 000000000..4fa281764 --- /dev/null +++ b/apps/web/content/docs/dev/working-with-users/account-deletion.mdx @@ -0,0 +1,161 @@ +--- +title: Account Deletion and Data Export +description: How VitNode lets members download their data and delete their account under GDPR, how staff delete accounts from the AdminCP, and how to configure the grace period and IP retention. +icon: UserX +--- + +import { ImgDocs } from "@/components/fumadocs/img"; +import settingsImg from "./account-deletion-settings.webp"; +import admincpImg from "./account-deletion-admincp.webp"; +import adminDialogImg from "./account-deletion-admin-dialog.webp"; +import debugImg from "./account-deletion-debug.webp"; +import overviewImg from "./account-deletion-overview.webp"; + +VitNode handles GDPR data requests out of the box. Members download a copy of their data (Art. 15 and 20) and delete their account (Art. 17) from **Settings → Privacy & data**, staff delete accounts from the AdminCP, and the Debug Panel warns you before a request misses GDPR's one-month deadline. + +Core exports and erases its own tables. A plugin that stores data about members adds its own handlers, see [Export and Erase Plugin Data](/docs/dev/working-with-users/personal-data). + +## Let members delete their account + + + +- **Download my data** saves a JSON file with one key per plugin under `plugins`. The `@vitnode/core` key holds the profile, devices, passkeys, connected accounts, files, payments, warnings and reports filed. +- **Delete my account** asks for the current password, or a sign-in from the last 15 minutes when the account has no password. The member is then signed out everywhere, their public profile disappears, and an email explains how to cancel. +- During the grace period the account can't sign in quietly. Password, passkey and social sign-ins all stop at a **Keep your account?** dialog that counts down the days left, and only **Keep my account and sign in** starts a session and keeps the account. **Stay signed out** leaves them signed out. After the grace period, an hourly job erases the account and sends a goodbye email. +- The AdminCP sign-in refuses an account scheduled for deletion outright. Cancel the deletion first. +- AdminCP staff cannot delete their own account this way. Another administrator removes their AdminCP access first. + +### Turn self-deletion off for a role + +Open **AdminCP → Users → Roles**, edit a role and switch off **Allow deleting own account** on the **Profile** tab. The setting is on by default, and a member needs it on every role they hold. + +Without it, **Privacy & data** tells the member to contact staff, and the API answers `403` with `not_allowed`. GDPR still gives that member the right to erasure, so staff delete the account from the AdminCP when asked. + +### Sign in during the grace period + +A sign-in with the right credentials doesn't start a session for an account scheduled for deletion. The API answers `403` with the date and a short-lived token instead: + +```json +{ + "error": "account_deletion_pending", + "scheduledAt": "2026-12-05T10:00:00.000Z", + "token": "eyJhdWQiOiJhY2NvdW50LWRlbGV0aW9uLWhvbGQi..." +} +``` + +Password sign-in, passkeys, SSO callbacks, emailed SSO confirmations and SSO account linking all answer this way. The built-in login and SSO pages show the confirmation dialog for you. A custom front end confirms with the token, which cancels the deletion and starts the session: + +```ts +import { fetcher } from "@vitnode/core/tanstack/fetcher"; + +const res = await fetcher({ + plugin: "@vitnode/core", + method: "post", + module: "users", + path: "/sign_in/cancel-deletion", + args: { body: { token } }, +}); +``` + +The token lasts 10 minutes and works once. An expired or reused token answers `400` with `invalid_hold`, so ask the member to sign in again. No confirmation means no session, so leaving the screen keeps the deletion scheduled. + +## Delete an account from the AdminCP + +In **AdminCP → Users**, an account with an open request shows a **Deletion scheduled** or **Deletion failed** badge, and the **Deletion** filter lists only those accounts. + + + +Open a user and scroll to the red **Danger zone** at the end of their page: + +- **Delete account** opens a dialog with a **Delete immediately** switch. Switched on, the account is erased right away. Switched off, the deletion is scheduled with the grace period, and the member is signed out and emailed how to cancel. +- **Cancel deletion** keeps an account whose deletion is scheduled. +- **Retry erasure** appears when an erasure failed, next to the reason it failed. + +These actions need the **Delete user accounts** staff permission (`users:can_delete`), which depends on **Edit users**. + + + +## Monitor deletions in the Debug Panel + +**AdminCP → Debug Panel → Overview** treats account deletion like any other system. A failed erasure is a critical issue and a request past its grace period is a warning. The **Privacy requests** card shows how many of GDPR's 30 days the oldest open request has used, how many requests failed or are scheduled, and when the hourly job last ran. + + + +**Diagnostics → Account deletions** has the detail: + +- **Checks**: failed erasures, requests past their grace period, the oldest open request against 30 days, and the last run of the `account-deletion` job. +- **Needs you**: each failed or overdue request with its reason, and **Retry**, **Erase now** or **Cancel deletion**. +- **All requests**: every request, searchable by name, email, `#id` or `DR-0042` and filterable by status. The details button opens the request's timeline. + + + +A request outlives its account. It keeps only the erased user's id, the dates and the outcome. That is your proof the request was handled, and it holds nothing about the person. + +## Configure the grace period and IP retention + +Both options live under `users` in `buildApiConfig`: + +```ts title="apps/api/src/vitnode.api.config.ts" +export const vitNodeApiConfig = buildApiConfig({ + // ... + users: { + accountDeletion: { graceDays: 14 }, + ipRetentionDays: 90, + }, +}); +``` + +| Name | Type | Required | Default | Description | +| :-------------------------- | :------- | :------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `accountDeletion.graceDays` | `number` | No | `14` | Whole days between the request and the erasure. `0` erases on the next hourly run. Capped at `30`, so every request is handled within the month GDPR allows. | +| `ipRetentionDays` | `number` | No | `180` | Days IP addresses are kept. A daily job deletes older debug logs and clears the IP on older Activity Logs entries and sign-up records. `0` keeps them. | + +The `account-deletion` job runs every hour at minute 25 and `ip-retention` daily at 03:50. Both are ordinary [cron jobs](/docs/dev/cron), so they need a cron adapter or an external trigger like every other job. + +## How an account erasure runs + +1. Every session of the account is revoked. +2. Each file the member uploaded is deleted from storage. A file that live content still shows is kept and counted as **files kept** on the request. +3. In one database transaction, each plugin's `personalData.erase` runs, core removes the member's name and IP from Activity Logs and deletes their debug logs, and the `core_users` row is deleted. Tables with `onDelete: "cascade"` (sessions, passkeys, notifications, warnings) go with it, and `set null` columns (authors, reporters, payments) lose the link. +4. The request is marked **Erased**, the [`user.deleted`](/docs/dev/events/built-in-events#core-events-vitnodecore) event is emitted and a goodbye email is sent. + +A failure rolls the transaction back, leaves the account in place and stores the error on the request. The hourly job retries it up to five times, then marks it **Failed** and waits for staff. Staff can press **Retry erasure** at any time. + +## Check the result + +1. Sign in as a test member and open **Settings → Privacy & data**. Press **Download my data** and check that the file's `plugins` object has a `@vitnode/core` key. +2. Press **Delete my account**, enter the password, type your name and press **Delete account**. A dialog shows the deletion date. Press **Go to the home page** and you are signed out. +3. Sign in again as that member. Instead of signing you in, a dialog asks **Keep your account?**. Press **Stay signed out**. +4. Sign in as an admin and open **AdminCP → Users**. The member has a **Deletion scheduled** badge. +5. Open the member, press **Delete account** in the danger zone, switch on **Delete immediately** and confirm. You land back on the user list. +6. In **Debug Panel → Diagnostics → Account deletions**, the request is **Erased**, and the member's profile URL returns 404. + +## Related + +- [Export and Erase Plugin Data](/docs/dev/working-with-users/personal-data) +- [Built-in events](/docs/dev/events/built-in-events) +- [Staff permissions](/docs/dev/working-with-users/staff-permissions) diff --git a/apps/web/content/docs/dev/working-with-users/meta.json b/apps/web/content/docs/dev/working-with-users/meta.json index e230718c4..df794a321 100644 --- a/apps/web/content/docs/dev/working-with-users/meta.json +++ b/apps/web/content/docs/dev/working-with-users/meta.json @@ -13,6 +13,8 @@ "staff-permission-refs", "presence", "presence-in-plugins", + "account-deletion", + "personal-data", "..." ] } diff --git a/apps/web/content/docs/dev/working-with-users/personal-data.mdx b/apps/web/content/docs/dev/working-with-users/personal-data.mdx new file mode 100644 index 000000000..264447d19 --- /dev/null +++ b/apps/web/content/docs/dev/working-with-users/personal-data.mdx @@ -0,0 +1,119 @@ +--- +title: Export and Erase Plugin Data +description: Make a VitNode plugin include its rows in a member's GDPR data download and erase them when the account is deleted, with definePersonalData. +icon: DatabaseZap +--- + +When a member downloads their data or deletes their account, VitNode asks every plugin for its part. Declare `personalData` with `definePersonalData` in any plugin that stores something about members, so its rows land in the download and are deleted or anonymized with the account. + +The member and staff side of this is covered in [Account Deletion and Data Export](/docs/dev/working-with-users/account-deletion). + +## Add personal data handlers to a plugin + +This page uses a polls plugin that stores one row per vote, with the voter and their IP: + +```ts title="plugins/polls/src/database/votes.ts" +import { core_users } from "@vitnode/api/database/users"; +import { camelCase } from "drizzle-orm/pg-core"; + +export const polls_votes = camelCase.table.withRLS("polls_votes", (t) => ({ + id: t.serial().primaryKey(), + pollId: t.integer().notNull(), + optionId: t.integer().notNull(), + userId: t.integer().references(() => core_users.id, { onDelete: "set null" }), + ipAddress: t.varchar({ length: 45 }), + createdAt: t.timestamp().notNull().defaultNow(), +})); +``` + + + + +### Declare the handlers + +Create `personal-data.ts` in your plugin's API folder: + +```ts title="plugins/polls/src/api/personal-data.ts" +import { definePersonalData } from "@vitnode/api/lib/personal-data"; +import { eq } from "drizzle-orm"; + +import { polls_votes } from "@/database/votes"; + +export const pollsPersonalData = definePersonalData({ + export: async ({ c, userId }) => ({ + votes: await c + .get("db") + .select({ + pollId: polls_votes.pollId, + optionId: polls_votes.optionId, + createdAt: polls_votes.createdAt, + }) + .from(polls_votes) + .where(eq(polls_votes.userId, userId)), + }), + erase: async ({ tx, userId }) => { + await tx + .update(polls_votes) + .set({ ipAddress: null, userId: null }) + .where(eq(polls_votes.userId, userId)); + }, +}); +``` + +`export` returns plain JSON for the member's download. `Date` values become ISO strings, and password hashes, tokens and keys never belong here. + +`erase` keeps the votes, so poll results stay correct, but removes who cast them and from where. It runs inside the erasure transaction, before core deletes the account. Write through `tx`, never `c.get("db")`, so a failure rolls the whole erasure back. + + + + +### Register the handlers + +Pass them as `personalData` to `buildApiPlugin` in your plugin's API config: + +```ts title="plugins/polls/src/config.api.ts" +import { buildApiPlugin } from "@vitnode/api/lib/plugin"; + +import { pollsPersonalData } from "@/api/personal-data"; +import { votesModule } from "@/api/modules/votes/votes.module"; +import { manifest } from "@/manifest.gen"; + +export const pollsApiPlugin = () => + buildApiPlugin({ + manifest, + modules: [votesModule], + personalData: pollsPersonalData, + }); +``` + +Both handlers are optional. Plugins run in the order they are registered, and core always runs last, so the account row still exists while your `erase` runs. + + + + +## Decide what to delete and what to keep + +- **Delete** what only describes the member: preferences, drafts, private messages, tokens. +- **Anonymize** content other members depend on, like a vote or a post with replies. Clear the user, IP and email, and keep the rest. +- **Keep** records a law requires, such as invoices, but unlinked from the member. Core does this for payments. +- **Leave alone** rows whose foreign key to `core_users` uses `onDelete: "cascade"`. They are deleted with the account, so `erase` only needs the columns the database keeps. +- **Clean outside the database** (a newsletter provider, an external search index) in a [`user.deleted`](/docs/dev/events/built-in-events#core-events-vitnodecore) listener. It fires after the commit with the `userId` and the address the account had. + + + A column that references `core_users` with `onDelete: "restrict"`, such as a + required Content Engine `user` field, makes the account delete fail. The + hourly job retries it, then marks the request **Failed** with the constraint + name on the user's AdminCP page. Delete or reassign those rows in your + `erase`. + + +## Check the result + +1. Sign in as a test member who has rows in your plugin, open **Settings → Privacy & data** and press **Download my data**. The file's `plugins` object has a key named after your plugin id, for example `@vitnode/polls`, holding what `export` returned. +2. As an admin, open the member in **AdminCP → Users**, press **Delete account** with **Delete immediately** switched on, and confirm. +3. Query your table. The member's rows are deleted or anonymized the way `erase` describes. If the erasure failed, the error is on the request in **Debug Panel → Diagnostics → Account deletions**. + +## Related + +- [Account Deletion and Data Export](/docs/dev/working-with-users/account-deletion) +- [Built-in events](/docs/dev/events/built-in-events) diff --git a/apps/web/src/locales/@vitnode/core/pl.json b/apps/web/src/locales/@vitnode/core/pl.json index 23b3ba2b7..e4456d126 100644 --- a/apps/web/src/locales/@vitnode/core/pl.json +++ b/apps/web/src/locales/@vitnode/core/pl.json @@ -310,7 +310,8 @@ "services": "Usługi", "logs": "Przeglądarka logów", "queue": "Kolejka", - "ai": "Logi AI" + "ai": "Logi AI", + "deletions": "Usunięcia kont" }, "tone": { "critical": "Krytyczne", @@ -331,7 +332,8 @@ "diagnostics": { "logs": "Każde ostrzeżenie i błąd zapisane przez API, od najnowszych.", "queue": "Zadania w tle i to, co się z nimi stało.", - "ai": "Każde zapytanie do AI z modelem, statusem i kosztem." + "ai": "Każde zapytanie do AI z modelem, statusem i kosztem.", + "deletions": "Każde żądanie usunięcia konta i jego wynik, jako dowód, że każde zostało obsłużone." }, "security": { "alert": { @@ -426,6 +428,14 @@ "ai": "Modele AI", "captcha": "Captcha", "websocket": "WebSocket" + }, + "deletions": { + "subtitle": "{pending} zaplanowanych · {failed} nieudanych · najstarsze {oldest}/{deadline} dni", + "failed": "{count, plural, one {# usuwanie nie powiodło się} few {# usuwania nie powiodły się} many {# usuwań nie powiodło się} other {# usuwania nie powiodło się}} i nie jest ponawiane", + "overdue": "{count, plural, one {# żądanie przekroczyło} few {# żądania przekroczyły} many {# żądań przekroczyło} other {# żądania przekroczyło}} okres karencji", + "oldest": "Najstarsze otwarte żądanie: {days} z {deadline} dni", + "oldest_late": "Żądanie ma {days} dni i przekroczyło limit RODO wynoszący {deadline} dni", + "none": "Brak otwartych żądań" } }, "actions": { @@ -471,6 +481,24 @@ "error": "Błąd", "warn": "Ostrzeżenie" } + }, + "privacy": { + "title": "Żądania prywatności", + "desc": "Usunięcia kont i to, jak blisko każde jest miesięcznego limitu RODO.", + "open": "Otwórz usunięcia kont", + "oldest": "Najstarsze otwarte żądanie", + "oldest_note": "RODO daje miesiąc na działanie", + "oldest_none": "Brak otwartych żądań", + "failed": "Nieudane", + "failed_note": "Ponawianie zatrzymane", + "none": "Brak", + "scheduled": "Zaplanowane", + "overdue_note": "{count} po okresie karencji", + "next_note": "Następne {when}", + "erased": "Usunięte, ostatnie 30 dni", + "job_ran": "Zadanie uruchomiło się {when}", + "job_never": "Zadanie jeszcze się nie uruchomiło", + "of_deadline": "z {deadline} dni" } }, "global": { @@ -643,6 +671,10 @@ "allow_desc": "Członkowie tej roli mogą w ustawieniach konta ukryć przed innymi członkami swój status online i ostatnią aktywność.", "force": "Zawsze przeglądaj anonimowo", "force_desc": "Ukrywa status online i ostatnią aktywność każdego członka tej roli, niezależnie od jego wyboru. Ma pierwszeństwo przed ustawieniem powyżej i przed każdą inną rolą." + }, + "delete_account": { + "allow": "Zezwalaj na usuwanie własnego konta", + "allow_desc": "Użytkownicy z tą rolą mogą usunąć konto w Ustawienia → Prywatność i dane. Administracja zawsze może usunąć konto w AdminCP." } }, "list": { @@ -1555,7 +1587,12 @@ }, "roles": "Role", "searchPlaceholder": "Szukaj użytkowników po adresie e-mail lub nazwie...", - "user": "Użytkownik" + "user": "Użytkownik", + "deletionScheduled": "Usunięcie zaplanowane", + "deletionScheduledDesc": "To konto zostanie usunięte {date}.", + "deletionFailed": "Usunięcie nieudane", + "deletionFailedDesc": "Usuwanie tego konta nie powiodło się. Otwórz użytkownika, aby zobaczyć powód i ponowić.", + "deletionFilter": "Usunięcie" }, "show": { "addSecondaryRole": "Dodaj rolę", @@ -1716,8 +1753,21 @@ "signedOutAll": "Wylogowano wszędzie", "signedOutAllDesc": "{name} musi zalogować się ponownie na każdym urządzeniu.", "admincp": "AdminCP", - "showAll": "Pokaż wszystkie ({count})", - "showFewer": "Pokaż mniej", + "manageAll": "Zarządzaj wszystkimi sesjami ({count})", + "sheetDesc": "{count, plural, one {# sesja} few {# sesje} many {# sesji} other {# sesji}}, w których {name} jest zalogowany.", + "search": "Szukaj sesji", + "filter": "Filtruj", + "filterLabel": "{count, plural, =0 {Filtruj sesje} other {Filtruj sesje, aktywne: #}}", + "sessionType": "Typ sesji", + "public": "Publiczna", + "clearFilters": "Wyczyść filtry", + "showing": "Wyświetlono {shown} z {total}", + "showMore": "Pokaż {count} więcej", + "noMatch": { + "title": "Brak pasujących sesji", + "desc": "Spróbuj innej przeglądarki, systemu lub adresu IP albo wyczyść filtry." + }, + "signOutAllHint": "Kończy wszystkie sesje naraz.", "loadError": { "title": "Nie udało się wczytać urządzeń", "desc": "Coś poszło nie tak podczas pobierania urządzeń tego użytkownika. Spróbuj ponownie." @@ -1789,6 +1839,50 @@ "visible": "Widoczna dla członków", "hiddenFromPublic": "Ukryta przed członkami", "unknown": "Ukryta - potrzebujesz uprawnienia, aby ją zobaczyć" + }, + "delete": { + "title": "Usuń konto", + "desc": "Usuń tego użytkownika i jego dane osobowe (RODO). Zaplanuj usunięcie, aby dać czas na anulowanie, albo usuń od razu.", + "pending_title": "Zaplanowano usunięcie", + "scheduled_by_member": "Użytkownik poprosił o usunięcie konta. Zostanie usunięte", + "scheduled_by_admin": "Administracja zaplanowała usunięcie konta. Zostanie usunięte", + "failed": "Nie udało się usunąć konta", + "failed_desc": "Konto zostało zachowane. Powód znajdziesz w komunikacie na górze strony.", + "self_desc": "Nie możesz tutaj usunąć własnego konta.", + "schedule": { + "success": "Usunięcie zaplanowane", + "success_desc": "{name} dostał e-mail z instrukcją anulowania." + }, + "now": { + "success": "Konto usunięte", + "success_desc": "Konto {name} i jego dane osobowe zostały usunięte.", + "success_desc_kept": "Konto {name} zostało usunięte. {count, plural, one {# plik zachowano} few {# pliki zachowano} many {# plików zachowano} other {# pliku zachowano}}, bo pokazuje je treść." + }, + "cancel": { + "action": "Anuluj usunięcie", + "title": "Anulować to usunięcie?", + "desc": "Konto {name} zostaje i można się na nie normalnie logować.", + "confirm": "Zachowaj konto", + "success": "Usunięcie anulowane", + "success_desc": "Konto {name} zostaje bez zmian." + }, + "danger_zone": "Strefa zagrożenia", + "action": "Usuń konto", + "dialog_title": "Usunąć konto {name}?", + "dialog_desc": "Konto, metody logowania, urządzenia i przesłane pliki zostaną usunięte. Treści, na które odpowiedzieli inni, zostaną, ale bez powiązania z użytkownikiem.", + "immediately": "Usuń natychmiast", + "immediately_desc": "Usuń konto od razu. Pozostaw wyłączone, aby zaplanować usunięcie po okresie karencji. Użytkownik zostanie wtedy wylogowany i dostanie e-mail z instrukcją anulowania.", + "understand": "Rozumiem, że konto {name} i jego dane osobowe zostaną usunięte na zawsze", + "understand_required": "Zaznacz to pole, aby kontynuować.", + "submit": "Usuń konto", + "failed_title": "Usuwanie konta nie powiodło się po {attempts, plural, one {# próbie} other {# próbach}}.", + "failed_hint": "Usuń przyczynę i ponów. Anuluj usunięcie, aby zachować konto.", + "retry": { + "action": "Ponów usuwanie", + "title": "Ponowić usuwanie tego konta?", + "desc": "Konto {name} i jego dane osobowe zostaną usunięte od razu, jeśli przyczyna została usunięta. Tego nie da się cofnąć.", + "confirm": "Ponów usuwanie" + } } }, "verify_email": { @@ -1827,6 +1921,80 @@ "desc": "Obowiązuje od następnej operacji AI użytkownika." } } + }, + "deletions": { + "status": { + "pending": "Oczekuje", + "failed": "Nieudane", + "completed": "Usunięte", + "cancelled": "Anulowane" + }, + "source": { + "user": "Na prośbę użytkownika", + "admin": "Przez administrację" + }, + "erased_member": "Usunięty użytkownik #{id}", + "files": "{deleted, plural, one {usunięto # plik} few {usunięto # pliki} many {usunięto # plików} other {usunięto # pliku}}, {kept, plural, =0 {nic nie zachowano} one {# zachowany, bo pokazuje go treść} few {# zachowane, bo pokazuje je treść} many {# zachowanych, bo pokazuje je treść} other {# zachowanego, bo pokazuje je treść}}", + "empty": { + "title": "Brak żądań usunięcia", + "desc": "Gdy użytkownik usunie konto albo zrobi to administracja, żądanie pojawi się tutaj." + }, + "retry": { + "action": "Ponów", + "now": "Usuń teraz", + "title": "Usunąć to konto teraz?", + "desc": "Konto i jego dane osobowe zostaną usunięte od razu. Tego nie da się cofnąć.", + "confirm": "Usuń teraz", + "success": "Konto usunięte", + "success_desc": "Żądanie oznaczono jako usunięte.", + "failed": "Usuwanie znowu się nie powiodło", + "failed_desc": "Powód jest widoczny przy żądaniu. Napraw go i spróbuj ponownie." + }, + "cancel": { + "action": "Anuluj usunięcie", + "title": "Anulować to usunięcie?", + "desc": "Konto zostaje, a użytkownik może się normalnie logować.", + "confirm": "Zachowaj konto", + "success": "Usunięcie anulowane", + "success_desc": "Konto zostaje bez zmian." + }, + "all": "Wszystkie żądania", + "search": "Szukaj po nazwie, e-mailu, #id lub DR-0042", + "attention": { + "title": "Wymaga Ciebie", + "attempts": "{count, plural, one {# próba} few {# próby} many {# prób} other {# próby}}", + "due": "termin" + }, + "columns": { + "request": "Żądanie", + "member": "Użytkownik", + "status": "Status", + "requested_by": "Zgłoszone przez", + "requested": "Zgłoszono", + "due": "Termin / zamknięto" + }, + "details": { + "requested_by": "Zgłoszone przez", + "member": "Użytkownik", + "attempts": "Próby", + "files": "Pliki", + "member_id": "ID użytkownika", + "open": "Szczegóły", + "open_label": "Otwórz szczegóły {ref}" + }, + "timeline": { + "label": "Przebieg żądania", + "requested": "Zgłoszono, wylogowano i wysłano e-mail", + "cancelled": "Anulowano", + "erased": "Usunięto", + "failed": "Usuwanie nie powiodło się po {count, plural, one {# próbie} other {# próbach}}", + "failed_desc": "Ponawianie zatrzymane. Usuń przyczynę i ponów.", + "grace": "Koniec okresu karencji", + "erase": "Usunięcie", + "erase_waiting": "Czeka na najbliższe cogodzinne uruchomienie", + "erase_after": "Cogodzinne zadanie usunie konto po okresie karencji", + "files": "{deleted, plural, one {usunięto # plik} few {usunięto # pliki} many {usunięto # plików} other {usunięto # pliku}}, {kept, plural, =0 {nic nie zachowano} one {# zachowany, bo pokazuje go treść} few {# zachowane, bo pokazuje je treść} many {# zachowanych, bo pokazuje je treść} other {# zachowanego, bo pokazuje je treść}}" + } } }, "ai": { @@ -2200,7 +2368,8 @@ "sso": "Połączone konta", "notifications": "Powiadomienia", "ai": "Użycie AI", - "standing": "Status konta" + "standing": "Status konta", + "privacy": "Prywatność i dane" }, "overview": { "accountTitle": "Konto", @@ -2617,6 +2786,56 @@ "title": "Punkty AI", "details": "Zobacz swoje funkcje AI" } + }, + "privacy": { + "title": "Prywatność i dane", + "desc": "Pobierz kopię swoich danych albo usuń konto.", + "export": { + "title": "Pobierz swoje dane", + "desc": "Plik JSON ze wszystkim, co ta strona o Tobie przechowuje: profil, urządzenia, metody logowania, pliki, płatności i dane wtyczek.", + "action": "Pobierz moje dane", + "success": "Pobieranie danych", + "success_desc": "Przechowuj plik w bezpiecznym miejscu. Zawiera Twoje dane osobowe.", + "error_desc": "Nie udało się przygotować pliku. Spróbuj ponownie za minutę." + }, + "delete": { + "title": "Usuń konto", + "desc": "{days, plural, =0 {Konto zostanie usunięte w ciągu godziny.} one {Konto zostanie usunięte # dzień po zgłoszeniu. Do tego czasu możesz się zalogować i zmienić zdanie.} other {Konto zostanie usunięte # dni po zgłoszeniu. Do tego czasu możesz się zalogować i zmienić zdanie.}}", + "what": "Usuwamy: profil, metody logowania, urządzenia, powiadomienia i przesłane pliki. Posty, na które odpowiedzieli inni, zostaną, ale bez powiązania z Tobą. Faktury przechowujemy tak długo, jak wymaga prawo.", + "action": "Usuń moje konto", + "staff_title": "Kont administracji nie można tu usunąć", + "staff_desc": "Twoje konto ma dostęp do AdminCP. Poproś innego administratora o jego odebranie, a potem wróć tutaj.", + "dialog_title": "Usunąć Twoje konto?", + "dialog_desc": "Zostaniesz wylogowany na wszystkich urządzeniach, a my wyślemy Ci e-mail z linkiem do anulowania.", + "grace_days": "{count, plural, one {dzień na zmianę zdania} few {dni na zmianę zdania} many {dni na zmianę zdania} other {dnia na zmianę zdania}}", + "deleted_on": "Usunięcie ", + "password": "Obecne hasło", + "password_required": "Wpisz obecne hasło.", + "password_invalid": "To hasło jest nieprawidłowe.", + "confirm_name": "Wpisz {name}, aby potwierdzić", + "confirm_name_invalid": "To nie pasuje do Twojej nazwy. Wpisz ją dokładnie tak, jak jest pokazana.", + "confirm": "Usuń konto", + "reauth_title": "Zaloguj się ponownie", + "reauth_desc": "Twoje konto nie ma hasła, więc usunięcie wymaga świeżego logowania. Wyloguj się, zaloguj ponownie i wróć tutaj w ciągu 15 minut.", + "success": "Usunięcie konta zaplanowane", + "done_desc": "Jesteś wylogowany na wszystkich urządzeniach, a link do anulowania czeka w Twojej skrzynce.", + "done_hint": "Zaloguj się przed tą datą, aby zachować konto.", + "done_action": "Przejdź na stronę główną", + "pending_title": "Twoje konto zostanie usunięte", + "pending_desc": "Zostanie usunięte {date}. Zmieniłeś zdanie? Zachowaj konto poniżej.", + "pending_by_admin": "To usunięcie zaplanowała administracja.", + "cancel": "Zachowaj moje konto", + "cancel_success": "Twoje konto zostaje", + "cancel_success_desc": "Usunięcie anulowane. Wszystko jest tak, jak było.", + "danger_zone": "Strefa zagrożenia", + "not_allowed_title": "Usuwanie konta jest wyłączone dla Twojej roli", + "not_allowed_desc": "Skontaktuj się z administracją, a usunie Twoje konto i dane za Ciebie." + }, + "load_error": { + "title": "Nie udało się wczytać ustawień prywatności", + "desc": "Sprawdź połączenie i spróbuj ponownie." + }, + "retry": "Spróbuj ponownie" } }, "sign_in": { @@ -2685,7 +2904,24 @@ "desc": "Na tej stronie nie jest teraz włączony żaden sposób logowania. Zajrzyj później.", "title": "Logowanie jest niedostępne" }, - "last_used": "Ostatnio używane" + "last_used": "Ostatnio używane", + "deletion_hold": { + "title": "Zachować konto?", + "desc": "Zalogowanie się anuluje usunięcie. Nic jeszcze nie zostało usunięte.", + "days_left": "{count, plural, one {dzień do usunięcia} few {dni do usunięcia} many {dni do usunięcia} other {dnia do usunięcia}}", + "deleted_on": "Usunięcie ", + "confirm": "Zachowaj konto i zaloguj się", + "keep": "Pozostań wylogowany", + "back": "Wróć do logowania", + "expired": { + "title": "Potwierdzenie wygasło", + "desc": "Na potwierdzenie było 10 minut. Zaloguj się ponownie, aby dostać nowe." + }, + "success": { + "title": "Witaj z powrotem", + "desc": "Twoje konto nie jest już zaplanowane do usunięcia." + } + } }, "sign_up": { "already_have_account": "Masz już konto? Zaloguj się.", @@ -2866,6 +3102,26 @@ "help": "Jeśli masz problem z powyższym przyciskiem, skopiuj i wklej poniższy adres URL do tej samej przeglądarki:", "expire_time": "Ten link wygaśnie {date}" } + }, + "account_deletion": { + "email": { + "scheduled": { + "subject": "Twoje konto zostanie usunięte", + "greeting": "Cześć {name}!", + "intro": "Otrzymaliśmy prośbę o usunięcie Twojego konta. Zostanie ono trwale usunięte {date}.", + "button": "Zachowaj moje konto", + "instructions": "Zmieniłeś zdanie? Zaloguj się przed tą datą i potwierdź, że chcesz zachować konto. Do tego czasu jesteś wylogowany na wszystkich urządzeniach, a każde logowanie najpierw poprosi o anulowanie usunięcia.", + "no_action": "Jeśli to nie Ty, zaloguj się i od razu anuluj usunięcie, a potem zmień hasło.", + "admin_note": "To usunięcie zaplanowała administracja." + }, + "deleted": { + "subject": "Twoje konto zostało usunięte", + "greeting": "Do widzenia, {name}", + "intro": "Twoje konto i powiązane z nim dane osobowe zostały usunięte, zgodnie z prośbą.", + "details": "Posty, na które odpowiedzieli inni, mogą zostać na stronie, ale bez powiązania z Tobą. Dokumenty, które musimy przechowywać z mocy prawa, np. faktury, trzymamy tylko tak długo, jak to wymagane.", + "outro": "Dziękujemy, że byłeś częścią społeczności. Zawsze możesz wrócić z nowym kontem." + } + } } }, "editor": { @@ -5511,7 +5767,10 @@ "password_reset": "Zresetowano hasło", "email_verified": "Zweryfikowano adres e-mail", "device_revoked": "Wylogowano urządzenie", - "devices_revoked": "Wylogowano wszystkie urządzenia" + "devices_revoked": "Wylogowano wszystkie urządzenia", + "deleted": "Usunięto konto", + "deletion_scheduled": "Zaplanowano usunięcie konta", + "deletion_cancelled": "Anulowano usunięcie konta" }, "settings": { "updated": "Zaktualizowano ustawienia" @@ -5797,6 +6056,7 @@ }, "@vitnode/core:plugins:can_check_updates": "Sprawdzanie aktualizacji wtyczek i rdzenia na żądanie", "@vitnode/core:users:can_view_hidden_presence": "Wyświetlanie statusu online i ostatniej aktywności użytkowników przeglądających anonimowo", + "@vitnode/core:users:can_delete": "Usuwanie kont użytkowników", "@vitnode/core:activity_logs": "Dziennik aktywności", "@vitnode/core:activity_logs:can_view": "Wyświetlanie dziennika aktywności", "@vitnode/core:activity_logs:can_view_sensitive": "Wyświetlanie adresów IP i szczegółów technicznych", diff --git a/apps/web/src/page-cache.gen.ts b/apps/web/src/page-cache.gen.ts index c22914c43..0e7fda628 100644 --- a/apps/web/src/page-cache.gen.ts +++ b/apps/web/src/page-cache.gen.ts @@ -30,6 +30,7 @@ export const pageCacheRoutes: PageCacheRouteTable = [ { path: '/admin/core/debug/ai' }, { path: '/admin/core/debug/cache' }, { path: '/admin/core/debug/cron' }, + { path: '/admin/core/debug/deletions' }, { path: '/admin/core/debug/logs' }, { path: '/admin/core/debug/plugins' }, { path: '/admin/core/debug/queue' }, @@ -82,6 +83,7 @@ export const pageCacheRoutes: PageCacheRouteTable = [ { path: '/settings/ai' }, { path: '/settings/devices' }, { path: '/settings/notifications' }, + { path: '/settings/privacy' }, { path: '/settings/security' }, { path: '/settings/sso' }, { path: '/settings/standing' }, diff --git a/packages/api/src/database/account-deletions.ts b/packages/api/src/database/account-deletions.ts new file mode 100644 index 000000000..8f3e7e289 --- /dev/null +++ b/packages/api/src/database/account-deletions.ts @@ -0,0 +1,63 @@ +import { sql } from "drizzle-orm"; +import { camelCase, index, uniqueIndex } from "drizzle-orm/pg-core"; + +import { core_users } from "./users"; + +export const ACCOUNT_DELETION_STATUSES = [ + "pending", + "completed", + "cancelled", + "failed", +] as const; + +export type AccountDeletionStatus = (typeof ACCOUNT_DELETION_STATUSES)[number]; + +export const ACCOUNT_DELETION_SOURCES = ["user", "admin"] as const; + +export type AccountDeletionSource = (typeof ACCOUNT_DELETION_SOURCES)[number]; + +/** + * One request to erase an account (GDPR Art. 17). The row outlives the + * account on purpose: it is the proof that the request was handled, and it + * holds no personal data - only the erased id, which no longer resolves to + * anyone, so restoring an old backup can replay the erasure. + */ +export const core_users_deletions = camelCase.table.withRLS( + "core_users_deletions", + t => ({ + id: t.serial().primaryKey(), + /** Set while the account exists; `null` once it is erased. */ + userId: t.integer().references(() => core_users.id, { + onDelete: "set null", + }), + /** The account's id, kept after erasure as a tombstone. Not a foreign key. */ + erasedUserId: t.integer().notNull(), + source: t.varchar({ enum: ACCOUNT_DELETION_SOURCES, length: 16 }).notNull(), + requestedById: t.integer().references(() => core_users.id, { + onDelete: "set null", + }), + status: t + .varchar({ enum: ACCOUNT_DELETION_STATUSES, length: 16 }) + .notNull() + .default("pending"), + scheduledAt: t.timestamp().notNull(), + attempts: t.integer().notNull().default(0), + lastError: t.text(), + filesDeleted: t.integer().notNull().default(0), + filesKept: t.integer().notNull().default(0), + createdAt: t.timestamp().notNull().defaultNow(), + cancelledAt: t.timestamp(), + completedAt: t.timestamp(), + }), + t => [ + uniqueIndex("core_users_deletions_pending_user_unique") + .on(t.userId) + .where(sql`${t.status} = 'pending'`), + index("core_users_deletions_status_scheduled_idx").on( + t.status, + t.scheduledAt, + ), + index("core_users_deletions_erased_user_idx").on(t.erasedUserId), + index("core_users_deletions_created_at_id_idx").on(t.createdAt, t.id), + ], +); diff --git a/packages/api/src/database/roles.ts b/packages/api/src/database/roles.ts index 7eb77226a..abeba62de 100644 --- a/packages/api/src/database/roles.ts +++ b/packages/api/src/database/roles.ts @@ -23,6 +23,8 @@ export const core_roles = camelCase.table.withRLS( allowUploadCover: t.boolean().notNull().default(true), maxCoverSize: t.integer().notNull().default(5120), allowEditPersonalInfo: t.boolean().notNull().default(true), + /** Members of this role may delete their own account from their settings. */ + allowDeleteAccount: t.boolean().notNull().default(true), allowBrowseAnonymously: t.boolean().notNull().default(true), forceBrowseAnonymously: t.boolean().notNull().default(false), allowEditOwnContent: t.boolean().notNull().default(true), diff --git a/packages/api/src/database/users.ts b/packages/api/src/database/users.ts index 9ac6a2e6b..2e642e6ad 100644 --- a/packages/api/src/database/users.ts +++ b/packages/api/src/database/users.ts @@ -54,7 +54,8 @@ export const core_users = camelCase.table.withRLS( .notNull(), birthday: t.timestamp(), timeZone: t.varchar({ length: 64 }), - ipAddress: t.varchar({ length: 40 }).notNull(), + /** The sign-up IP; cleared after `users.ipRetentionDays`. */ + ipAddress: t.varchar({ length: 40 }), language: t .varchar({ length: 32 }) .notNull() diff --git a/packages/api/src/emails/account-deleted.tsx b/packages/api/src/emails/account-deleted.tsx new file mode 100644 index 000000000..5a091a799 --- /dev/null +++ b/packages/api/src/emails/account-deleted.tsx @@ -0,0 +1,80 @@ +import { Text } from "react-email"; +import { createTranslator } from "use-intl"; + +import DefaultTemplateEmail, { + type DefaultTemplateEmailProps, +} from "./default-template"; +import { + EmailCard, + EmailCardContent, + EmailCardDescription, + EmailCardHeader, + EmailCardTitle, +} from "./ui/card"; + +interface AccountDeletedEmailTemplateProps extends DefaultTemplateEmailProps { + /** The member's display name, read before the account row was deleted. */ + name: string; +} + +AccountDeletedEmailTemplate.PreviewProps = { + ...DefaultTemplateEmail.PreviewProps, + name: "John Doe", + i18n: { + ...DefaultTemplateEmail.PreviewProps.i18n, + messages: { + core: { + auth: { + account_deletion: { + email: { + deleted: { + subject: "Your account has been deleted", + greeting: "Goodbye, {name}", + intro: + "Your account and the personal data tied to it have been deleted, as you asked.", + details: + "Posts other members replied to may stay on the site, no longer linked to you. Records the law makes us keep, such as invoices, are kept only for as long as required.", + outro: + "Thanks for being part of the community. You're always welcome back with a new account.", + }, + }, + }, + }, + }, + }, + }, +} satisfies AccountDeletedEmailTemplateProps; + +/** Sent to the address an account had, once the account has been erased. */ +export default function AccountDeletedEmailTemplate({ + i18n, + name, + ...props +}: AccountDeletedEmailTemplateProps) { + const t = createTranslator({ + ...i18n, + namespace: "core.auth.account_deletion.email.deleted", + }); + + return ( + + + + {t("greeting", { name })} + {t("intro")} + + + + {t("details")} + + + {t("outro")} + + + + + ); +} diff --git a/packages/api/src/emails/account-deletion-scheduled.tsx b/packages/api/src/emails/account-deletion-scheduled.tsx new file mode 100644 index 000000000..b35c8aecd --- /dev/null +++ b/packages/api/src/emails/account-deletion-scheduled.tsx @@ -0,0 +1,123 @@ +import { Hr, Section, Text } from "react-email"; +import { createTranslator } from "use-intl"; + +import DefaultTemplateEmail, { + type DefaultTemplateEmailProps, +} from "./default-template"; +import { EmailButton } from "./ui/button"; +import { + EmailCard, + EmailCardContent, + EmailCardDescription, + EmailCardFooter, + EmailCardHeader, + EmailCardTitle, +} from "./ui/card"; + +interface AccountDeletionScheduledEmailTemplateProps extends DefaultTemplateEmailProps { + /** `true` when staff scheduled the deletion rather than the member. */ + byAdmin?: boolean; + /** Where the member cancels: the privacy settings page. */ + cancelUrl: string; + /** The member's display name, for the greeting. */ + name: string; + /** When the account will be erased. */ + scheduledAt: Date; +} + +AccountDeletionScheduledEmailTemplate.PreviewProps = { + ...DefaultTemplateEmail.PreviewProps, + cancelUrl: "https://example.com/settings/privacy", + name: "John Doe", + scheduledAt: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000), + user: { + id: 1, + name: "John Doe", + email: "john@example.com", + language: "en", + nameCode: "john-doe", + }, + i18n: { + ...DefaultTemplateEmail.PreviewProps.i18n, + messages: { + core: { + auth: { + account_deletion: { + email: { + scheduled: { + subject: "Your account is scheduled for deletion", + greeting: "Hello {name}!", + intro: + "We received a request to delete your account. It will be deleted for good on {date}.", + button: "Keep my account", + instructions: + "Changed your mind? Sign in before that date and confirm that you want to keep your account. Until then you're signed out everywhere, and signing in always asks you to cancel the deletion first.", + no_action: + "If you didn't ask for this, sign in and cancel the deletion right away, then change your password.", + admin_note: "An administrator scheduled this deletion.", + }, + }, + }, + }, + }, + }, + }, +} satisfies AccountDeletionScheduledEmailTemplateProps; + +/** Confirms a deletion request and tells the member how to cancel it. */ +export default function AccountDeletionScheduledEmailTemplate({ + byAdmin, + cancelUrl, + i18n, + name, + scheduledAt, + user, + ...props +}: AccountDeletionScheduledEmailTemplateProps) { + const t = createTranslator({ + ...i18n, + namespace: "core.auth.account_deletion.email.scheduled", + }); + const date = scheduledAt.toLocaleString(i18n.locale, { + year: "numeric", + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + timeZoneName: "short", + }); + + return ( + + + + {t("greeting", { name })} + {t("intro", { date })} + + + +
+ + {t("button")} + +
+ + + {t("instructions")} + +
+ + +
+ + {byAdmin ? t("admin_note") : t("no_action")} + +
+
+
+ ); +} diff --git a/packages/api/src/events/users.ts b/packages/api/src/events/users.ts index 5c4ec4991..feed5d286 100644 --- a/packages/api/src/events/users.ts +++ b/packages/api/src/events/users.ts @@ -19,8 +19,9 @@ export const userCreatedEvent = defineEvent({ }); /** - * Declared for plugins implementing account deletion - core has no user - * deletion flow yet and never emits this itself. + * An account was erased, after its row and every plugin's `personalData.erase` + * committed. `email` is the address it had, for cleaning up systems outside + * the database (a newsletter provider, a search index) - never store it. */ export const userDeletedEvent = defineEvent({ pluginId, @@ -28,6 +29,24 @@ export const userDeletedEvent = defineEvent({ payload: z.object({ email: z.string(), userId: z.number().int() }), }); +/** A deletion request was opened; the account is erased at `scheduledAt`. */ +export const userDeletionRequestedEvent = defineEvent({ + pluginId, + name: "user.deletion.requested", + payload: z.object({ + scheduledAt: z.string(), + source: z.enum(["user", "admin"]), + userId: z.number().int(), + }), +}); + +/** A pending deletion request was cancelled; the account stays. */ +export const userDeletionCancelledEvent = defineEvent({ + pluginId, + name: "user.deletion.cancelled", + payload: z.object({ userId: z.number().int() }), +}); + export const userUpdatedEvent = defineEvent({ pluginId, name: "user.updated", @@ -147,6 +166,8 @@ export const userSsoProfileSyncedEvent = defineEvent({ export const userEventDefinitions = [ userCreatedEvent, userDeletedEvent, + userDeletionRequestedEvent, + userDeletionCancelledEvent, userUpdatedEvent, userEmailVerifiedEvent, userPasswordUpdatedEvent, diff --git a/packages/api/src/lib/account-deletion/core-personal-data.ts b/packages/api/src/lib/account-deletion/core-personal-data.ts new file mode 100644 index 000000000..e96634720 --- /dev/null +++ b/packages/api/src/lib/account-deletion/core-personal-data.ts @@ -0,0 +1,252 @@ +import { and, eq } from "drizzle-orm"; + +import { core_users_deletions } from "@/database/account-deletions"; +import { core_audit_logs } from "@/database/audit"; +import { core_files } from "@/database/files"; +import { core_logs } from "@/database/logs"; +import { core_moderation_reports } from "@/database/moderation"; +import { core_users_passkeys } from "@/database/passkeys"; +import { core_payments } from "@/database/payments"; +import { + core_sessions, + core_sessions_known_devices, +} from "@/database/sessions"; +import { + core_users, + core_users_secondary_roles, + core_users_sso, +} from "@/database/users"; +import { + core_moderation_sanctions, + core_moderation_warnings, +} from "@/database/warnings"; +import { manifest } from "@/manifest"; + +import { definePersonalData } from "../personal-data"; + +const iso = (date: Date | null) => date?.toISOString() ?? null; + +/** + * Core's own tables. Rows that cascade with `core_users` need nothing here; + * these are the ones that outlive the account and still say who it was. + */ +export const corePersonalData = definePersonalData({ + export: async ({ c, userId }) => { + const db = c.get("db"); + + const [ + [profile], + secondaryRoles, + devices, + passkeys, + sso, + files, + payments, + warnings, + sanctions, + reports, + deletions, + ] = await Promise.all([ + db + .select({ + id: core_users.id, + name: core_users.name, + nameCode: core_users.nameCode, + email: core_users.email, + emailVerified: core_users.emailVerified, + firstName: core_users.firstName, + lastName: core_users.lastName, + phone: core_users.phone, + headline: core_users.headline, + birthday: core_users.birthday, + showRealName: core_users.showRealName, + language: core_users.language, + timeZone: core_users.timeZone, + newsletter: core_users.newsletter, + hideOnlineStatus: core_users.hideOnlineStatus, + ipAddress: core_users.ipAddress, + createdAt: core_users.createdAt, + lastSeenAt: core_users.lastSeenAt, + roleId: core_users.roleId, + }) + .from(core_users) + .where(eq(core_users.id, userId)) + .limit(1), + db + .select({ + roleId: core_users_secondary_roles.roleId, + since: core_users_secondary_roles.createdAt, + }) + .from(core_users_secondary_roles) + .where(eq(core_users_secondary_roles.userId, userId)), + db + .selectDistinct({ + ipAddress: core_sessions_known_devices.ipAddress, + userAgent: core_sessions_known_devices.userAgent, + lastSeen: core_sessions_known_devices.lastSeen, + }) + .from(core_sessions) + .innerJoin( + core_sessions_known_devices, + eq(core_sessions_known_devices.id, core_sessions.deviceId), + ) + .where(eq(core_sessions.userId, userId)), + db + .select({ + name: core_users_passkeys.name, + deviceType: core_users_passkeys.deviceType, + createdAt: core_users_passkeys.createdAt, + lastUsedAt: core_users_passkeys.lastUsedAt, + }) + .from(core_users_passkeys) + .where(eq(core_users_passkeys.userId, userId)), + db + .select({ + providerId: core_users_sso.providerId, + providerEmail: core_users_sso.providerEmail, + providerUsername: core_users_sso.providerUsername, + createdAt: core_users_sso.createdAt, + }) + .from(core_users_sso) + .where(eq(core_users_sso.userId, userId)), + db + .select({ + id: core_files.id, + name: core_files.name, + mimeType: core_files.mimeType, + size: core_files.size, + visibility: core_files.visibility, + createdAt: core_files.createdAt, + }) + .from(core_files) + .where(eq(core_files.userId, userId)), + db + .select({ + id: core_payments.id, + pluginId: core_payments.pluginId, + description: core_payments.description, + amount: core_payments.amount, + currency: core_payments.currency, + status: core_payments.status, + createdAt: core_payments.createdAt, + completedAt: core_payments.completedAt, + }) + .from(core_payments) + .where(eq(core_payments.userId, userId)), + db + .select({ + points: core_moderation_warnings.points, + message: core_moderation_warnings.message, + issuedAt: core_moderation_warnings.issuedAt, + expiresAt: core_moderation_warnings.expiresAt, + revokedAt: core_moderation_warnings.revokedAt, + }) + .from(core_moderation_warnings) + .where(eq(core_moderation_warnings.userId, userId)), + db + .select({ + type: core_moderation_sanctions.type, + startsAt: core_moderation_sanctions.startsAt, + endsAt: core_moderation_sanctions.endsAt, + }) + .from(core_moderation_sanctions) + .where(eq(core_moderation_sanctions.userId, userId)), + db + .select({ + reason: core_moderation_reports.reason, + description: core_moderation_reports.description, + targetTitle: core_moderation_reports.targetTitle, + status: core_moderation_reports.status, + createdAt: core_moderation_reports.createdAt, + }) + .from(core_moderation_reports) + .where(eq(core_moderation_reports.reporterId, userId)), + db + .select({ + status: core_users_deletions.status, + scheduledAt: core_users_deletions.scheduledAt, + createdAt: core_users_deletions.createdAt, + cancelledAt: core_users_deletions.cancelledAt, + }) + .from(core_users_deletions) + .where(eq(core_users_deletions.userId, userId)), + ]); + + return { + profile: profile + ? { + ...profile, + birthday: iso(profile.birthday), + createdAt: iso(profile.createdAt), + lastSeenAt: iso(profile.lastSeenAt), + } + : null, + secondaryRoles: secondaryRoles.map(row => ({ + ...row, + since: iso(row.since), + })), + devices: devices.map(row => ({ ...row, lastSeen: iso(row.lastSeen) })), + passkeys: passkeys.map(row => ({ + ...row, + createdAt: iso(row.createdAt), + lastUsedAt: iso(row.lastUsedAt), + })), + ssoConnections: sso.map(row => ({ + ...row, + createdAt: iso(row.createdAt), + })), + files: files.map(row => ({ ...row, createdAt: iso(row.createdAt) })), + payments: payments.map(row => ({ + ...row, + createdAt: iso(row.createdAt), + completedAt: iso(row.completedAt), + })), + warnings: warnings.map(row => ({ + points: row.points, + message: row.message, + issuedAt: iso(row.issuedAt), + expiresAt: iso(row.expiresAt), + revokedAt: iso(row.revokedAt), + })), + sanctions: sanctions.map(row => ({ + ...row, + startsAt: iso(row.startsAt), + endsAt: iso(row.endsAt), + })), + reportsFiled: reports.map(row => ({ + ...row, + createdAt: iso(row.createdAt), + })), + accountDeletionRequests: deletions.map(row => ({ + ...row, + scheduledAt: iso(row.scheduledAt), + createdAt: iso(row.createdAt), + cancelledAt: iso(row.cancelledAt), + })), + }; + }, + + erase: async ({ tx, userId }) => { + await tx.delete(core_logs).where(eq(core_logs.userId, userId)); + + await tx + .update(core_audit_logs) + .set({ actorName: null, ipAddress: null }) + .where(eq(core_audit_logs.actorId, userId)); + await tx + .update(core_audit_logs) + .set({ targetLabel: null }) + .where( + and( + eq(core_audit_logs.pluginId, manifest.id), + eq(core_audit_logs.targetType, "user"), + eq(core_audit_logs.targetId, String(userId)), + ), + ); + + await tx + .update(core_payments) + .set({ checkoutUrl: null }) + .where(eq(core_payments.userId, userId)); + }, +}); diff --git a/packages/api/src/lib/account-deletion/erase.ts b/packages/api/src/lib/account-deletion/erase.ts new file mode 100644 index 000000000..0e1bc3d61 --- /dev/null +++ b/packages/api/src/lib/account-deletion/erase.ts @@ -0,0 +1,273 @@ +import type { Context } from "hono"; + +import { and, asc, eq, lte, sql } from "drizzle-orm"; +import { HTTPException } from "hono/http-exception"; +import { createTranslator } from "use-intl"; + +import type { EnvVitNode } from "@/middlewares/global.middleware"; + +import { core_users_deletions } from "@/database/account-deletions"; +import { core_files } from "@/database/files"; +import { core_sessions_known_devices } from "@/database/sessions"; +import { core_users } from "@/database/users"; +import AccountDeletedEmailTemplate from "@/emails/account-deleted"; +import { userDeletedEvent } from "@/events/users"; +import { isPgReferenceViolation, pgConstraintName } from "@/lib/api/pg-error"; +import { writeAuditLog } from "@/lib/audit/write"; +import { revokeSessions } from "@/models/session-revoke"; +import { isOrphanedDevice } from "@/modules/cron/cron/clean.cron"; + +/** Failed erasures are retried by the hourly job this many times, then left for an admin. */ +export const ACCOUNT_DELETION_MAX_ATTEMPTS = 5; + +/** Erasures one cron run handles, so a backlog spreads over several runs. */ +const ACCOUNT_DELETION_BATCH_SIZE = 20; + +export type EraseAccountResult = + | { + /** Also stored on the request as `lastError`. */ + error: string; + filesDeleted: number; + filesKept: number; + status: "failed"; + } + | { + filesDeleted: number; + filesKept: number; + status: "completed" | "not_found"; + }; + +const describeError = (error: unknown): string => { + const message = error instanceof Error ? error.message : String(error); + if (!isPgReferenceViolation(error)) return message; + + const constraint = pgConstraintName(error); + + return `Another table still requires this account${constraint ? ` (${constraint})` : ""}. The plugin that owns it must delete or reassign those rows in its \`personalData.erase\`.`; +}; + +/** + * Deletes every stored file the member uploaded. A file live content still + * shows is kept - the content stays, attributed to nobody - and counted. + */ +const deleteUserFiles = async ( + c: Context, + userId: number, +): Promise<{ deleted: number; kept: number }> => { + const files = await c + .get("db") + .select({ id: core_files.id }) + .from(core_files) + .where(eq(core_files.userId, userId)); + + let deleted = 0; + let kept = 0; + for (const file of files) { + try { + await c + .get("storage") + .deleteFile(file.id, { force: true, ownerId: userId }); + deleted++; + } catch (error) { + if (error instanceof HTTPException && error.status === 409) { + kept++; + continue; + } + if (error instanceof HTTPException && error.status === 404) continue; + throw error; + } + } + + return { deleted, kept }; +}; + +const sendAccountDeletedEmail = async ( + c: Context, + { email, language, name }: { email: string; language: string; name: string }, +) => { + if (!c.get("core").email?.adapter) return; + + try { + await c.get("email").send({ + to: email, + locale: language, + content: props => AccountDeletedEmailTemplate({ ...props, name }), + subject: ({ i18n }) => + createTranslator(i18n)( + "core.auth.account_deletion.email.deleted.subject", + ), + }); + } catch (error) { + await c + .get("log") + .warn( + `Account deletion: the confirmation email could not be queued. ${describeError(error)}`, + ); + } +}; + +/** + * Erases one account now: signs it out everywhere, deletes its files, runs + * every plugin's `personalData.erase` and deletes the `core_users` row in one + * transaction, then emits `user.deleted` and emails a confirmation. + * + * Idempotent: an account that no longer exists is `not_found`. A failure + * leaves the account in place, records the error on the open request and + * returns `failed` - the hourly job retries it. + * + * Server-only. + */ +export const eraseAccount = async ( + c: Context, + { deletionId, userId }: { deletionId: number; userId: number }, +): Promise => { + const db = c.get("db"); + + const [user] = await db + .select({ + email: core_users.email, + language: core_users.language, + name: core_users.name, + }) + .from(core_users) + .where(eq(core_users.id, userId)) + .limit(1); + + if (!user) { + await db + .update(core_users_deletions) + .set({ completedAt: new Date(), status: "completed" }) + .where(eq(core_users_deletions.id, deletionId)); + + return { filesDeleted: 0, filesKept: 0, status: "not_found" }; + } + + let files = { deleted: 0, kept: 0 }; + try { + await revokeSessions(c, { userId }); + files = await deleteUserFiles(c, userId); + + await db.transaction(async tx => { + for (const entry of c.get("core").personalData) { + await entry.erase?.({ c, tx, userId }); + } + + await tx + .update(core_users_deletions) + .set({ + completedAt: new Date(), + filesDeleted: sql`${core_users_deletions.filesDeleted} + ${files.deleted}`, + filesKept: sql`${core_users_deletions.filesKept} + ${files.kept}`, + lastError: null, + status: "completed", + }) + .where(eq(core_users_deletions.id, deletionId)); + + await tx.delete(core_users).where(eq(core_users.id, userId)); + + await writeAuditLog( + c, + { + action: "user.deleted", + metadata: { deletionId, filesKept: files.kept }, + target: { id: userId, label: `#${userId}`, type: "user" }, + }, + tx, + ); + }); + } catch (error) { + const reason = describeError(error); + const [row] = await db + .update(core_users_deletions) + .set({ + attempts: sql`${core_users_deletions.attempts} + 1`, + filesDeleted: sql`${core_users_deletions.filesDeleted} + ${files.deleted}`, + filesKept: sql`${core_users_deletions.filesKept} + ${files.kept}`, + lastError: reason.slice(0, 2000), + }) + .where(eq(core_users_deletions.id, deletionId)) + .returning({ attempts: core_users_deletions.attempts }); + + if (row && row.attempts >= ACCOUNT_DELETION_MAX_ATTEMPTS) { + await db + .update(core_users_deletions) + .set({ status: "failed" }) + .where(eq(core_users_deletions.id, deletionId)); + } + + await c + .get("log") + .error(`Account deletion #${deletionId} failed: ${reason}`); + + return { + error: reason, + filesDeleted: files.deleted, + filesKept: files.kept, + status: "failed", + }; + } + + await db + .delete(core_sessions_known_devices) + .where(isOrphanedDevice(db)) + .catch(async (error: unknown) => { + await c + .get("log") + .warn( + `Account deletion #${deletionId}: orphaned devices were not removed. ${describeError(error)}`, + ); + }); + await c.get("events").emit(userDeletedEvent, { email: user.email, userId }); + await sendAccountDeletedEmail(c, user); + + return { + filesDeleted: files.deleted, + filesKept: files.kept, + status: "completed", + }; +}; + +/** + * Erases every account whose grace period is over, oldest first. Called by + * the hourly `account-deletion` cron job. + */ +export const processDueAccountDeletions = async ( + c: Context, + now = new Date(), +): Promise => { + const due = await c + .get("db") + .select({ + id: core_users_deletions.id, + userId: core_users_deletions.userId, + }) + .from(core_users_deletions) + .where( + and( + eq(core_users_deletions.status, "pending"), + lte(core_users_deletions.scheduledAt, now), + ), + ) + .orderBy(asc(core_users_deletions.scheduledAt)) + .limit(ACCOUNT_DELETION_BATCH_SIZE); + + let erased = 0; + for (const deletion of due) { + if (deletion.userId === null) { + await c + .get("db") + .update(core_users_deletions) + .set({ completedAt: now, status: "completed" }) + .where(eq(core_users_deletions.id, deletion.id)); + continue; + } + + const result = await eraseAccount(c, { + deletionId: deletion.id, + userId: deletion.userId, + }); + if (result.status === "completed") erased++; + } + + return erased; +}; diff --git a/packages/api/src/lib/account-deletion/ip-retention.ts b/packages/api/src/lib/account-deletion/ip-retention.ts new file mode 100644 index 000000000..bfa6cbe07 --- /dev/null +++ b/packages/api/src/lib/account-deletion/ip-retention.ts @@ -0,0 +1,105 @@ +import { and, inArray, isNotNull, lt } from "drizzle-orm"; + +import type { AuditDatabase } from "@/lib/audit/write"; + +import { core_audit_logs } from "@/database/audit"; +import { core_logs } from "@/database/logs"; +import { core_users } from "@/database/users"; + +const BATCH_SIZE = 1000; +const MAX_BATCHES = 100; + +/** Runs `step` until it touches fewer rows than a batch, at most {@link MAX_BATCHES} times. */ +const inBatches = async (step: () => Promise): Promise => { + let total = 0; + for (let batch = 0; batch < MAX_BATCHES; batch++) { + const count = await step(); + total += count; + if (count < BATCH_SIZE) break; + } + + return total; +}; + +/** + * Forgets IP addresses older than `retentionDays`: deletes debug logs (an IP + * is most of what they hold) and clears the IP on Activity Logs entries and + * on accounts' sign-up record. `0` keeps everything. Batched, so no table is + * locked for long. Only the `ip-retention` cron calls this. + */ +export const pruneIpAddresses = async ( + db: AuditDatabase, + { now = new Date(), retentionDays }: { now?: Date; retentionDays: number }, +): Promise<{ accounts: number; activityLogs: number; logs: number }> => { + if (retentionDays <= 0) return { accounts: 0, activityLogs: 0, logs: 0 }; + + const cutoff = new Date(now.getTime() - retentionDays * 86_400_000); + + const logs = await inBatches(async () => { + const rows = await db + .delete(core_logs) + .where( + inArray( + core_logs.id, + db + .select({ id: core_logs.id }) + .from(core_logs) + .where(lt(core_logs.createdAt, cutoff)) + .limit(BATCH_SIZE), + ), + ) + .returning({ id: core_logs.id }); + + return rows.length; + }); + + const activityLogs = await inBatches(async () => { + const rows = await db + .update(core_audit_logs) + .set({ ipAddress: null }) + .where( + inArray( + core_audit_logs.id, + db + .select({ id: core_audit_logs.id }) + .from(core_audit_logs) + .where( + and( + isNotNull(core_audit_logs.ipAddress), + lt(core_audit_logs.createdAt, cutoff), + ), + ) + .limit(BATCH_SIZE), + ), + ) + .returning({ id: core_audit_logs.id }); + + return rows.length; + }); + + const accounts = await inBatches(async () => { + const rows = await db + .update(core_users) + .set({ ipAddress: null }) + .where( + inArray( + core_users.id, + db + .select({ id: core_users.id }) + .from(core_users) + .where( + and( + isNotNull(core_users.ipAddress), + lt(core_users.createdAt, cutoff), + ), + ) + .limit(BATCH_SIZE), + ), + ) + .returning({ id: core_users.id }); + + return rows.length; + }); + + return { accounts, activityLogs, logs }; +}; diff --git a/packages/api/src/lib/account-deletion/requests.ts b/packages/api/src/lib/account-deletion/requests.ts new file mode 100644 index 000000000..d910f7150 --- /dev/null +++ b/packages/api/src/lib/account-deletion/requests.ts @@ -0,0 +1,240 @@ +import type { Context } from "hono"; + +import { and, desc, eq, inArray } from "drizzle-orm"; +import { createTranslator } from "use-intl"; + +import type { AccountDeletionSource } from "@/database/account-deletions"; +import type { EnvVitNode } from "@/middlewares/global.middleware"; + +import { core_users_deletions } from "@/database/account-deletions"; +import { core_roles } from "@/database/roles"; +import { core_users } from "@/database/users"; +import AccountDeletionScheduledEmailTemplate from "@/emails/account-deletion-scheduled"; +import { + userDeletionCancelledEvent, + userDeletionRequestedEvent, +} from "@/events/users"; +import { PG_ERROR_CODES, pgErrorCode } from "@/lib/api/pg-error"; +import { getUserRoleIds } from "@/lib/check-staff-permission"; +import { CONFIG } from "@/lib/config"; +import { revokeSessions } from "@/models/session-revoke"; + +const DAY_MS = 86_400_000; + +/** The settings page a member cancels a pending deletion from. */ +export const PRIVACY_SETTINGS_PATH = "settings/privacy"; + +/** Requests that still hold an account: waiting for erasure, or erasure failed. */ +export const OPEN_ACCOUNT_DELETION_STATUSES = ["pending", "failed"] as const; + +export interface OpenAccountDeletion { + attempts: number; + createdAt: Date; + id: number; + lastError: null | string; + scheduledAt: Date; + source: AccountDeletionSource; + status: (typeof OPEN_ACCOUNT_DELETION_STATUSES)[number]; +} + +/** + * The member's open deletion request, if any: pending, or failed and waiting + * for staff to retry it. Either way the account is on its way out. + */ +export const findOpenAccountDeletion = async ( + c: Context, + userId: number, +): Promise => { + const [row] = await c + .get("db") + .select({ + attempts: core_users_deletions.attempts, + createdAt: core_users_deletions.createdAt, + id: core_users_deletions.id, + lastError: core_users_deletions.lastError, + scheduledAt: core_users_deletions.scheduledAt, + source: core_users_deletions.source, + status: core_users_deletions.status, + }) + .from(core_users_deletions) + .where( + and( + eq(core_users_deletions.userId, userId), + inArray(core_users_deletions.status, OPEN_ACCOUNT_DELETION_STATUSES), + ), + ) + .orderBy(desc(core_users_deletions.createdAt)) + .limit(1); + + if (!row || (row.status !== "pending" && row.status !== "failed")) { + return null; + } + + return { ...row, status: row.status }; +}; + +/** + * Opens a deletion request for `userId`, due after the grace period (or now, + * with `immediately`). Returns the request already pending, unchanged, when + * there is one. + */ +export const openAccountDeletion = async ( + c: Context, + { + immediately = false, + requestedById, + source, + userId, + }: { + immediately?: boolean; + requestedById: null | number; + source: AccountDeletionSource; + userId: number; + }, +): Promise<{ created: boolean; deletion: OpenAccountDeletion }> => { + const existing = await findOpenAccountDeletion(c, userId); + if (existing) return { created: false, deletion: existing }; + + const graceDays = immediately ? 0 : c.get("core").privacy.deletionGraceDays; + const scheduledAt = new Date(Date.now() + graceDays * DAY_MS); + + try { + const [deletion] = await c + .get("db") + .insert(core_users_deletions) + .values({ + erasedUserId: userId, + requestedById, + scheduledAt, + source, + userId, + }) + .returning({ + attempts: core_users_deletions.attempts, + createdAt: core_users_deletions.createdAt, + id: core_users_deletions.id, + lastError: core_users_deletions.lastError, + scheduledAt: core_users_deletions.scheduledAt, + source: core_users_deletions.source, + }); + + return { created: true, deletion: { ...deletion, status: "pending" } }; + } catch (error) { + if (pgErrorCode(error) !== PG_ERROR_CODES.uniqueViolation) throw error; + const raced = await findOpenAccountDeletion(c, userId); + if (!raced) throw error; + + return { created: false, deletion: raced }; + } +}; + +/** + * Schedules a member's own (or an admin's) deletion request with a grace + * period: signs the account out everywhere, emails how to cancel and emits + * `user.deletion.requested`. + */ +export const scheduleAccountDeletion = async ( + c: Context, + args: { + requestedById: null | number; + source: AccountDeletionSource; + userId: number; + }, +): Promise => { + const { created, deletion } = await openAccountDeletion(c, args); + if (!created) return deletion; + + await revokeSessions(c, { userId: args.userId }); + + const [user] = await c + .get("db") + .select({ + email: core_users.email, + language: core_users.language, + name: core_users.name, + nameCode: core_users.nameCode, + }) + .from(core_users) + .where(eq(core_users.id, args.userId)) + .limit(1); + + if (user && c.get("core").email?.adapter) { + try { + await c.get("email").send({ + user: { ...user, id: args.userId }, + content: props => + AccountDeletionScheduledEmailTemplate({ + ...props, + byAdmin: args.source === "admin", + cancelUrl: new URL(PRIVACY_SETTINGS_PATH, CONFIG.web.href).href, + name: user.name, + scheduledAt: deletion.scheduledAt, + }), + subject: ({ i18n }) => + createTranslator(i18n)( + "core.auth.account_deletion.email.scheduled.subject", + ), + }); + } catch (error) { + await c + .get("log") + .warn( + `Account deletion: the confirmation email could not be queued. ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + await c.get("events").emit(userDeletionRequestedEvent, { + scheduledAt: deletion.scheduledAt.toISOString(), + source: args.source, + userId: args.userId, + }); + + return deletion; +}; + +/** + * Cancels the member's open deletion request, pending or failed. Returns + * `false` when there was none to cancel. + */ +export const cancelAccountDeletion = async ( + c: Context, + userId: number, +): Promise => { + const rows = await c + .get("db") + .update(core_users_deletions) + .set({ cancelledAt: new Date(), status: "cancelled" }) + .where( + and( + eq(core_users_deletions.userId, userId), + inArray(core_users_deletions.status, OPEN_ACCOUNT_DELETION_STATUSES), + ), + ) + .returning({ id: core_users_deletions.id }); + + if (rows.length === 0) return false; + + await c.get("events").emit(userDeletionCancelledEvent, { userId }); + + return true; +}; + +/** + * Whether the member's roles let them delete their own account: every role + * they hold (primary and secondary) must have `allowDeleteAccount`. Staff can + * still delete the account from the AdminCP. + */ +export const canDeleteOwnAccount = async ( + c: Context, + user: { id: number; roleId: number }, +): Promise => { + const roleIds = await getUserRoleIds(c, user); + const roles = await c + .get("db") + .select({ allowDeleteAccount: core_roles.allowDeleteAccount }) + .from(core_roles) + .where(inArray(core_roles.id, roleIds)); + + return roles.length > 0 && roles.every(role => role.allowDeleteAccount); +}; diff --git a/packages/api/src/lib/account-deletion/settings.ts b/packages/api/src/lib/account-deletion/settings.ts new file mode 100644 index 000000000..a5a52c098 --- /dev/null +++ b/packages/api/src/lib/account-deletion/settings.ts @@ -0,0 +1,31 @@ +import type { VitNodeApiConfig } from "@/vitnode.config"; + +export const ACCOUNT_DELETION_DEFAULT_GRACE_DAYS = 14; +/** GDPR Art. 12(3) gives a month to act on a request; the grace period must fit in it. */ +export const ACCOUNT_DELETION_MAX_GRACE_DAYS = 30; +export const IP_RETENTION_DEFAULT_DAYS = 180; + +const wholeDays = (value: unknown): null | number => + typeof value === "number" && Number.isSafeInteger(value) && value >= 0 + ? value + : null; + +export interface PrivacySettings { + /** Days between a member asking to delete their account and the erasure. */ + deletionGraceDays: number; + /** Days IP addresses are kept in logs and on accounts; `0` keeps them. */ + ipRetentionDays: number; +} + +/** `users.accountDeletion` and `users.ipRetentionDays`, with defaults and bounds applied. */ +export const resolvePrivacySettings = ( + users: VitNodeApiConfig["users"], +): PrivacySettings => ({ + deletionGraceDays: Math.min( + wholeDays(users?.accountDeletion?.graceDays) ?? + ACCOUNT_DELETION_DEFAULT_GRACE_DAYS, + ACCOUNT_DELETION_MAX_GRACE_DAYS, + ), + ipRetentionDays: + wholeDays(users?.ipRetentionDays) ?? IP_RETENTION_DEFAULT_DAYS, +}); diff --git a/packages/api/src/lib/account-deletion/sign-in-hold.ts b/packages/api/src/lib/account-deletion/sign-in-hold.ts new file mode 100644 index 000000000..c0d072c0b --- /dev/null +++ b/packages/api/src/lib/account-deletion/sign-in-hold.ts @@ -0,0 +1,84 @@ +import type { Context } from "hono"; + +import { HTTPException } from "hono/http-exception"; +import { z } from "zod"; + +import type { EnvVitNode } from "@/middlewares/global.middleware"; + +import { signPayload, verifySignedPayload } from "@/lib/api/signed-token"; +import { ensureServerSecret } from "@/lib/server-secret"; + +import { cancelAccountDeletion, findOpenAccountDeletion } from "./requests"; + +export const ACCOUNT_DELETION_PENDING = "account_deletion_pending"; + +export const ACCOUNT_DELETION_HOLD_SECRET_NAME = "account_deletion_hold"; + +export const ACCOUNT_DELETION_HOLD_TTL_MS = 10 * 60_000; + +export const zodAccountDeletionHold = z.object({ + error: z.literal(ACCOUNT_DELETION_PENDING), + scheduledAt: z.date(), + token: z.string(), +}); + +export type AccountDeletionHold = z.infer; + +const zodHoldTokenPayload = z.object({ + aud: z.literal("account-deletion-hold"), + d: z.number().int().positive(), + exp: z.number().int().positive(), + u: z.number().int().positive(), +}); + +const holdSecret = async (c: Context): Promise => + await ensureServerSecret(c.get("db"), ACCOUNT_DELETION_HOLD_SECRET_NAME); + +export const holdSignInForAccountDeletion = async ( + c: Context, + userId: number, +): Promise => { + const deletion = await findOpenAccountDeletion(c, userId); + if (!deletion) return null; + + const expiresAt = Date.now() + ACCOUNT_DELETION_HOLD_TTL_MS; + + return { + error: ACCOUNT_DELETION_PENDING, + scheduledAt: deletion.scheduledAt, + token: signPayload(await holdSecret(c), { + aud: "account-deletion-hold", + d: deletion.id, + exp: Math.floor(expiresAt / 1000), + u: userId, + }), + }; +}; + +export const assertNoAccountDeletion = async ( + c: Context, + userId: number, +): Promise => { + if (await findOpenAccountDeletion(c, userId)) { + throw new HTTPException(403); + } +}; + +export const releaseAccountDeletionHold = async ( + c: Context, + token: string, +): Promise => { + const payload = verifySignedPayload( + await holdSecret(c), + token, + zodHoldTokenPayload, + ); + if (!payload || payload.exp * 1000 <= Date.now()) return null; + + const deletion = await findOpenAccountDeletion(c, payload.u); + if (deletion?.id !== payload.d) return null; + + if (!(await cancelAccountDeletion(c, payload.u))) return null; + + return payload.u; +}; diff --git a/packages/api/src/lib/audit/actions.ts b/packages/api/src/lib/audit/actions.ts index 2f52dc8b8..e36d274c2 100644 --- a/packages/api/src/lib/audit/actions.ts +++ b/packages/api/src/lib/audit/actions.ts @@ -112,6 +112,9 @@ export const CORE_AUDIT_ACTIONS = defineAuditActions([ { action: "user.email_verified", targetType: "user" }, { action: "user.device_revoked", targetType: "user" }, { action: "user.devices_revoked", targetType: "user" }, + { action: "user.deleted", targetType: "user" }, + { action: "user.deletion_scheduled", targetType: "user" }, + { action: "user.deletion_cancelled", targetType: "user" }, { action: "settings.updated", targetType: "settings" }, { action: "ai_access.role_updated", targetType: "role" }, { action: "ai_access.user_override_saved", targetType: "user" }, diff --git a/packages/api/src/lib/core-staff-permissions.ts b/packages/api/src/lib/core-staff-permissions.ts index a1d05de05..13be7426a 100644 --- a/packages/api/src/lib/core-staff-permissions.ts +++ b/packages/api/src/lib/core-staff-permissions.ts @@ -36,6 +36,7 @@ export const coreStaffPermissions = defineStaffPermissions(manifest, { { permission: "can_edit", dependsOn: ["can_view"] }, { permission: "can_edit_admin", dependsOn: ["can_view"] }, { permission: "can_view_hidden_presence", dependsOn: ["can_view"] }, + { permission: "can_delete", dependsOn: ["can_edit"] }, ], roles: [ "can_view", diff --git a/packages/api/src/lib/personal-data.ts b/packages/api/src/lib/personal-data.ts new file mode 100644 index 000000000..b79ddd361 --- /dev/null +++ b/packages/api/src/lib/personal-data.ts @@ -0,0 +1,107 @@ +import type { Context } from "hono"; + +import type { EnvVitNode } from "@/middlewares/global.middleware"; + +type Db = EnvVitNode["Variables"]["db"]; + +/** The transaction an account erasure runs in. */ +export type PersonalDataTx = Parameters[0]>[0]; + +/** + * What a plugin hands back for one member's data export: JSON-serializable + * values (`Date`s become ISO strings). + */ +export type PersonalDataExport = Record; + +/** + * How a plugin takes part in GDPR requests: what it hands a member who asks + * for a copy of their data (Art. 15 and 20), and how it forgets them when the + * account is erased (Art. 17). Declare it with {@link definePersonalData} and + * pass it as `personalData` to `buildApiPlugin`. + */ +export interface PersonalDataHandlers { + /** + * Removes or anonymizes everything the plugin stores about `userId`. Runs + * server-side inside the erasure transaction, before core deletes the + * account row - so foreign keys to `core_users` still resolve, and a throw + * rolls the whole erasure back (it is retried on the next cron run). + * + * Write through `tx`, never `c.get("db")`. Content the member published may + * stay when deleting it would break other members' threads; strip the + * personal parts (author, IP, email) instead. Data a law obliges you to keep + * (invoices) may stay as long as it is no longer linked to the member. + * + * Leave side effects outside the database (storage, search, third-party + * APIs) to a `user.deleted` event listener, which runs after the commit. + */ + erase?: (args: { + c: Context; + tx: PersonalDataTx; + userId: number; + }) => Promise; + /** + * Returns the plugin's data about `userId` for the member's own download. + * Plain JSON only, and never secrets (password hashes, tokens, keys). Omit + * it when the plugin stores nothing about members. Server-side. + */ + export?: (args: { + c: Context; + userId: number; + }) => Promise; +} + +/** {@link PersonalDataHandlers} tagged with the plugin that declared them. */ +export interface RegisteredPersonalData extends PersonalDataHandlers { + pluginId: string; +} + +/** + * Declares how a plugin exports and erases a member's data. Returns the + * handlers unchanged; pass them as `personalData` to `buildApiPlugin`. + * Server-only. + * + * @example + * ```ts + * import { definePersonalData } from "@vitnode/api/lib/personal-data"; + * import { eq } from "drizzle-orm"; + * + * import { polls_votes } from "@/database/votes"; + * + * export const pollsPersonalData = definePersonalData({ + * export: async ({ c, userId }) => ({ + * votes: await c + * .get("db") + * .select({ pollId: polls_votes.pollId, optionId: polls_votes.optionId }) + * .from(polls_votes) + * .where(eq(polls_votes.userId, userId)), + * }), + * erase: async ({ tx, userId }) => { + * await tx + * .update(polls_votes) + * .set({ ipAddress: null, userId: null }) + * .where(eq(polls_votes.userId, userId)); + * }, + * }); + * ``` + */ +export const definePersonalData = ( + handlers: PersonalDataHandlers, +): PersonalDataHandlers => handlers; + +/** + * Every plugin's handlers, core last: plugins erase their rows while the + * account still exists, then core removes the account itself. + */ +export const collectPersonalData = ( + plugins: readonly { personalData?: PersonalDataHandlers; pluginId: string }[], + corePluginId: string, +): RegisteredPersonalData[] => { + const registered = plugins + .filter(plugin => plugin.personalData) + .map(plugin => ({ ...plugin.personalData, pluginId: plugin.pluginId })); + + return [ + ...registered.filter(entry => entry.pluginId !== corePluginId), + ...registered.filter(entry => entry.pluginId === corePluginId), + ]; +}; diff --git a/packages/api/src/lib/plugin.ts b/packages/api/src/lib/plugin.ts index 5475170dd..a11ae8991 100644 --- a/packages/api/src/lib/plugin.ts +++ b/packages/api/src/lib/plugin.ts @@ -47,6 +47,7 @@ import type { ModerationReportTargetDefinition } from "./moderation/targets"; import type { BaseBuildModuleReturn, BuildModuleReturn } from "./module"; import type { AnyNotificationTypeDefinition } from "./notifications/registry"; import type { PermissionStaffConfig } from "./permission-staff"; +import type { PersonalDataHandlers } from "./personal-data"; import type { QueueTaskConfig } from "./queue"; import type { ReactionsPluginConfig, @@ -114,6 +115,8 @@ export interface BuildPluginApiReturn< openApiTags?: string[]; /** The declared permissions, plus the ones content types, containers and report targets add. */ permissionStaff?: PermissionStaffConfig; + /** How the plugin exports and erases a member's data. */ + personalData?: PersonalDataHandlers; /** The plugin's npm package name, taken from `manifest.id`. */ pluginId: P; /** Content types the plugin serves public URLs for. */ @@ -188,6 +191,7 @@ export function buildApiPlugin< modules = [] as unknown as Modules, notificationTypes, permissionStaff, + personalData, reactions, searchIndexers, }: { @@ -241,6 +245,12 @@ export function buildApiPlugin< * object. Must be declared for this plugin's manifest. */ permissionStaff?: Pick, "config" | "pluginId">; + /** + * How the plugin exports a member's data and erases it when the account is + * deleted, from `definePersonalData`. Declare it whenever the plugin stores + * anything about members - core's own tables are handled by core. + */ + personalData?: PersonalDataHandlers; /** Reaction targets beyond those content models add (`reactions: true`). */ reactions?: ReactionsPluginConfig; /** Search indexers in addition to those modules declare. */ @@ -424,6 +434,7 @@ export function buildApiPlugin< events, queueTasks: collectPluginQueueTasks(pluginId, queueTasks), notificationTypes: pluginNotificationTypes, + personalData, searchIndexers: indexers, webSockets, // Every content type contributes can_view/can_create/can_edit/can_delete diff --git a/packages/api/src/locales/en.json b/packages/api/src/locales/en.json index 3d92bdbf1..18bc61993 100644 --- a/packages/api/src/locales/en.json +++ b/packages/api/src/locales/en.json @@ -39,6 +39,26 @@ "help": "If you're having trouble with the button above, copy and paste the URL below into the same browser:", "expire_time": "This link will expire on {date}" } + }, + "account_deletion": { + "email": { + "scheduled": { + "subject": "Your account is scheduled for deletion", + "greeting": "Hello {name}!", + "intro": "We received a request to delete your account. It will be deleted for good on {date}.", + "button": "Keep my account", + "instructions": "Changed your mind? Sign in before that date and confirm that you want to keep your account. Until then you're signed out everywhere, and signing in always asks you to cancel the deletion first.", + "no_action": "If you didn't ask for this, sign in and cancel the deletion right away, then change your password.", + "admin_note": "An administrator scheduled this deletion." + }, + "deleted": { + "subject": "Your account has been deleted", + "greeting": "Goodbye, {name}", + "intro": "Your account and the personal data tied to it have been deleted, as you asked.", + "details": "Posts other members replied to may stay on the site, no longer linked to you. Records the law makes us keep, such as invoices, are kept only for as long as required.", + "outro": "Thanks for being part of the community. You're always welcome back with a new account." + } + } } }, "notifications": { diff --git a/packages/api/src/middlewares/global.middleware.ts b/packages/api/src/middlewares/global.middleware.ts index 2e8d91e1d..78766ef91 100644 --- a/packages/api/src/middlewares/global.middleware.ts +++ b/packages/api/src/middlewares/global.middleware.ts @@ -5,9 +5,11 @@ import { HTTPException } from "hono/http-exception"; import type { RegisteredContentType } from "@/content/registry"; import type { RegisteredContentModel } from "@/content/server/model"; import type { ContentNotificationRegistry } from "@/content/server/notifications/registry"; +import type { PrivacySettings } from "@/lib/account-deletion/settings"; import type { CacheClient, DomainCache } from "@/lib/cache"; import type { LocaleRouting } from "@/lib/i18n/locale-routing"; import type { LocaleConfig, MessagesSource } from "@/lib/i18n/types"; +import type { RegisteredPersonalData } from "@/lib/personal-data"; import type { UpdateChannel } from "@/lib/updates/manifest"; import type { PersonalInformationFields } from "@/lib/user-personal-information"; import type { VitNodeApiConfig } from "@/vitnode.config"; @@ -25,6 +27,7 @@ import { ensureContentLocalizationLanguages } from "@/content/server/language-re import { createContentNotificationRegistry } from "@/content/server/notifications/registry"; import { warnAboutContentPreviewConfig } from "@/content/server/preview-config"; import { ensureContentPreviewSecret } from "@/content/server/preview-secret"; +import { resolvePrivacySettings } from "@/lib/account-deletion/settings"; import { runAfterResponse } from "@/lib/after-response"; import { DEFAULT_SESSION_COOKIE_NAME } from "@/lib/auth-cookie"; import { CacheModel, domainCacheOf } from "@/lib/cache"; @@ -35,6 +38,7 @@ import { collectLocaleCodes } from "@/lib/i18n/load-messages"; import { localeRoutingFromConfig } from "@/lib/i18n/locale-routing"; import { buildApiMessagesSources } from "@/lib/i18n/sources"; import { findActiveSuspension } from "@/lib/moderation/warnings/suspension"; +import { collectPersonalData } from "@/lib/personal-data"; import { resolvePersonalInformationFields } from "@/lib/user-personal-information"; import { manifest as coreManifest } from "@/manifest"; import { AIModel } from "@/models/ai"; @@ -262,9 +266,13 @@ export interface EnvVariablesVitNode { providers: PaymentProviderApiPlugin[]; }; permissionStaff: PermissionStaffCatalogEntry[]; + /** Each plugin's export and erasure handlers, core last. */ + personalData: RegisteredPersonalData[]; /** Which personal-information fields this install offers. */ personalInformationFields: PersonalInformationFields; plugins: { id: string }[]; + /** Account deletion grace period and IP retention (`users` in the API config). */ + privacy: PrivacySettings; queue: QueueTaskConfig[]; /** Every reaction target: custom ones and one per content type with `reactions`. */ reactions: ReactionsRegistry; @@ -707,9 +715,11 @@ export const globalMiddleware = ({ password: { enabled: authorization?.password ?? true }, }, captcha, + personalData: collectPersonalData(plugins, coreManifest.id), personalInformationFields: resolvePersonalInformationFields( users?.personalInformation, ), + privacy: resolvePrivacySettings(users), hasCronAdapter: !!cron, plugins: pluginsMetadata, installedPlugins, diff --git a/packages/api/src/middlewares/rate-limiter.middleware.ts b/packages/api/src/middlewares/rate-limiter.middleware.ts index 829f09c59..c29313003 100644 --- a/packages/api/src/middlewares/rate-limiter.middleware.ts +++ b/packages/api/src/middlewares/rate-limiter.middleware.ts @@ -76,6 +76,7 @@ export const rateLimitKey = (ipAddress: string): string => { const AUTH_RATE_LIMITED_PATHS = [ "/@vitnode/core/users/sign_in", + "/@vitnode/core/users/sign_in/cancel-deletion", "/@vitnode/core/users/sign_up", "/@vitnode/core/users/reset-password", "/@vitnode/core/users/verify-email", @@ -83,6 +84,7 @@ const AUTH_RATE_LIMITED_PATHS = [ "/@vitnode/core/users/change-password", "/@vitnode/core/users/passkeys/sign-in", "/@vitnode/core/users/passkeys/admin-sign-in", + "/@vitnode/core/users/me/account-deletion", ] as const; const AUTH_RATE_LIMITED_PATTERNS = [ diff --git a/packages/api/src/modules/admin/roles/routes/create.route.ts b/packages/api/src/modules/admin/roles/routes/create.route.ts index b2048bf9a..22156a22f 100644 --- a/packages/api/src/modules/admin/roles/routes/create.route.ts +++ b/packages/api/src/modules/admin/roles/routes/create.route.ts @@ -27,6 +27,7 @@ export const zodCreateRoleAdminSchema = z.object({ maxStorageForSubmit: zodRoleStorageSchema.optional(), allowUploadAvatar: z.boolean().optional(), allowEditPersonalInfo: z.boolean().optional(), + allowDeleteAccount: z.boolean().optional(), allowBrowseAnonymously: z.boolean().optional(), forceBrowseAnonymously: z.boolean().optional(), allowEditOwnContent: z.boolean().optional(), @@ -78,6 +79,7 @@ export const createRoleAdminRoute = buildRoute({ maxStorageForSubmit, allowUploadAvatar, allowEditPersonalInfo, + allowDeleteAccount, allowBrowseAnonymously, forceBrowseAnonymously, allowEditOwnContent, @@ -102,6 +104,7 @@ export const createRoleAdminRoute = buildRoute({ ...(allowEditPersonalInfo === undefined ? {} : { allowEditPersonalInfo }), + ...(allowDeleteAccount === undefined ? {} : { allowDeleteAccount }), ...(allowBrowseAnonymously === undefined ? {} : { allowBrowseAnonymously }), diff --git a/packages/api/src/modules/admin/roles/routes/list.route.ts b/packages/api/src/modules/admin/roles/routes/list.route.ts index c66a0f9b3..c84e89f0b 100644 --- a/packages/api/src/modules/admin/roles/routes/list.route.ts +++ b/packages/api/src/modules/admin/roles/routes/list.route.ts @@ -40,6 +40,7 @@ const rolesAdminListSchema = z.object({ maxStorageForSubmit: z.number().nullable(), allowUploadAvatar: z.boolean(), allowEditPersonalInfo: z.boolean(), + allowDeleteAccount: z.boolean(), allowBrowseAnonymously: z.boolean(), forceBrowseAnonymously: z.boolean(), allowEditOwnContent: z.boolean(), @@ -134,6 +135,7 @@ export const listRolesAdminRoute = buildRoute({ maxStorageForSubmit: core_roles.maxStorageForSubmit, allowUploadAvatar: core_roles.allowUploadAvatar, allowEditPersonalInfo: core_roles.allowEditPersonalInfo, + allowDeleteAccount: core_roles.allowDeleteAccount, allowBrowseAnonymously: core_roles.allowBrowseAnonymously, forceBrowseAnonymously: core_roles.forceBrowseAnonymously, allowEditOwnContent: core_roles.allowEditOwnContent, diff --git a/packages/api/src/modules/admin/roles/routes/show.route.ts b/packages/api/src/modules/admin/roles/routes/show.route.ts index cd4d65137..6f0613f89 100644 --- a/packages/api/src/modules/admin/roles/routes/show.route.ts +++ b/packages/api/src/modules/admin/roles/routes/show.route.ts @@ -27,6 +27,7 @@ const roleAdminSchema = z.object({ maxStorageForSubmit: z.number().nullable(), allowUploadAvatar: z.boolean(), allowEditPersonalInfo: z.boolean(), + allowDeleteAccount: z.boolean(), allowBrowseAnonymously: z.boolean(), forceBrowseAnonymously: z.boolean(), allowEditOwnContent: z.boolean(), @@ -97,6 +98,7 @@ export const showRoleAdminRoute = buildRoute({ maxStorageForSubmit: core_roles.maxStorageForSubmit, allowUploadAvatar: core_roles.allowUploadAvatar, allowEditPersonalInfo: core_roles.allowEditPersonalInfo, + allowDeleteAccount: core_roles.allowDeleteAccount, allowBrowseAnonymously: core_roles.allowBrowseAnonymously, forceBrowseAnonymously: core_roles.forceBrowseAnonymously, allowEditOwnContent: core_roles.allowEditOwnContent, diff --git a/packages/api/src/modules/admin/roles/routes/update.route.ts b/packages/api/src/modules/admin/roles/routes/update.route.ts index faeb70203..bffadbef1 100644 --- a/packages/api/src/modules/admin/roles/routes/update.route.ts +++ b/packages/api/src/modules/admin/roles/routes/update.route.ts @@ -31,6 +31,7 @@ export const zodUpdateRoleAdminSchema = z maxStorageForSubmit: zodRoleStorageSchema, allowUploadAvatar: z.boolean(), allowEditPersonalInfo: z.boolean(), + allowDeleteAccount: z.boolean(), allowBrowseAnonymously: z.boolean(), forceBrowseAnonymously: z.boolean(), allowEditOwnContent: z.boolean(), @@ -132,6 +133,9 @@ export const updateRoleAdminRoute = buildRoute({ if (body.allowEditPersonalInfo !== undefined) { values.allowEditPersonalInfo = body.allowEditPersonalInfo; } + if (body.allowDeleteAccount !== undefined) { + values.allowDeleteAccount = body.allowDeleteAccount; + } if (body.allowBrowseAnonymously !== undefined) { values.allowBrowseAnonymously = body.allowBrowseAnonymously; } diff --git a/packages/api/src/modules/admin/users/routes/delete.route.ts b/packages/api/src/modules/admin/users/routes/delete.route.ts new file mode 100644 index 000000000..03758d3a3 --- /dev/null +++ b/packages/api/src/modules/admin/users/routes/delete.route.ts @@ -0,0 +1,134 @@ +import { z } from "@hono/zod-openapi"; + +import { buildRoute } from "@/builders"; +import { eraseAccount } from "@/lib/account-deletion/erase"; +import { + openAccountDeletion, + scheduleAccountDeletion, +} from "@/lib/account-deletion/requests"; +import { writeAuditLogBestEffort } from "@/lib/audit/write"; +import { coreStaffPermissions } from "@/lib/core-staff-permissions"; + +import { assertCanEditAdminTarget } from "../lib/assert-edit-user-permission"; +import { + findTargetUserId, + USER_NOT_FOUND, + userNotFoundResponse, + zodTargetUserIdParam, +} from "../lib/target-user"; + +export const deleteUserAdminRoute = buildRoute({ + adminStaffPermission: coreStaffPermissions.admin.users.canDelete, + route: { + method: "delete", + description: + "Delete a user's account (GDPR Art. 17). `immediately` erases it now; otherwise it is scheduled with the member's grace period and the member is emailed how to cancel. Never your own account (Admin only).", + path: "/{id}", + request: { + params: z.object({ id: zodTargetUserIdParam }), + body: { + required: true, + content: { + "application/json": { + schema: z.object({ + immediately: z.boolean().openapi({ example: true }), + }), + }, + }, + }, + }, + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + filesKept: z.number().int(), + scheduledAt: z.date().nullable(), + status: z.enum(["completed", "scheduled"]), + }), + }, + }, + description: "Account erased or scheduled for deletion", + }, + 400: { + content: { + "application/json": { schema: z.object({ error: z.string() }) }, + }, + description: "Admins cannot delete their own account here", + }, + 403: { description: "Access Denied" }, + 404: userNotFoundResponse, + 409: { + content: { + "application/json": { + schema: z.object({ error: z.string(), lastError: z.string() }), + }, + }, + description: + "Erasure failed; the account was kept and the request is retried hourly", + }, + }, + }, + handler: async c => { + const { id } = c.req.valid("param"); + const { immediately } = c.req.valid("json"); + const userId = await findTargetUserId(c, id); + if (userId === null) return c.json(USER_NOT_FOUND, 404); + + const adminId = c.get("admin")?.user.id ?? null; + if (adminId === userId) { + return c.json({ error: "You cannot delete your own account" }, 400); + } + + await assertCanEditAdminTarget(c, userId); + + if (!immediately) { + const deletion = await scheduleAccountDeletion(c, { + requestedById: adminId, + source: "admin", + userId, + }); + await writeAuditLogBestEffort(c, { + action: "user.deletion_scheduled", + metadata: { scheduledAt: deletion.scheduledAt.toISOString() }, + target: { id: userId, type: "user" }, + }); + + return c.json( + { + filesKept: 0, + scheduledAt: deletion.scheduledAt, + status: "scheduled" as const, + }, + 200, + ); + } + + const { deletion } = await openAccountDeletion(c, { + immediately: true, + requestedById: adminId, + source: "admin", + userId, + }); + const result = await eraseAccount(c, { deletionId: deletion.id, userId }); + + if (result.status === "failed") { + return c.json( + { + error: "Account erasure failed", + lastError: result.error, + }, + 409, + ); + } + + return c.json( + { + filesKept: result.filesKept, + scheduledAt: null, + status: "completed" as const, + }, + 200, + ); + }, +}); diff --git a/packages/api/src/modules/admin/users/routes/deletions-summary.route.ts b/packages/api/src/modules/admin/users/routes/deletions-summary.route.ts new file mode 100644 index 000000000..5e96f42f0 --- /dev/null +++ b/packages/api/src/modules/admin/users/routes/deletions-summary.route.ts @@ -0,0 +1,176 @@ +import { z } from "@hono/zod-openapi"; +import { and, asc, count, eq, gte, inArray, lt, min } from "drizzle-orm"; + +import { buildRoute } from "@/builders"; +import { core_users_deletions } from "@/database/account-deletions"; +import { core_cron } from "@/database/cron"; +import { core_users } from "@/database/users"; +import { getNextCronRunDate } from "@/lib/api/get-next-cron-run-date"; +import { coreStaffPermissions } from "@/lib/core-staff-permissions"; +import { manifest } from "@/manifest"; +import { accountDeletionCron } from "@/modules/cron/cron/account-deletion.cron"; + +/** GDPR Art. 12(3): a request is answered within a month. */ +export const ACCOUNT_DELETION_DEADLINE_DAYS = 30; + +const DAY_MS = 86_400_000; +const ATTENTION_LIMIT = 20; + +export const accountDeletionsSummaryAdminRoute = buildRoute({ + adminStaffPermission: coreStaffPermissions.admin.users.canView, + route: { + method: "get", + description: + "How account deletion is doing, for the Debug Panel: counts, the oldest open request against the one-month GDPR deadline, the requests that need staff (failed, or past their grace period) and the hourly job (Admin only)", + path: "/account-deletions/summary", + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + attention: z.array( + z.object({ + attempts: z.number(), + id: z.number(), + lastError: z.string().nullable(), + scheduledAt: z.date(), + status: z.enum(["pending", "failed"]), + user: z + .object({ id: z.number(), name: z.string() }) + .nullable(), + }), + ), + deadlineDays: z.number(), + erasedLast30Days: z.number(), + failed: z.number(), + job: z.object({ + lastRun: z.date().nullable(), + nextRun: z.date().nullable(), + }), + nextScheduledAt: z.date().nullable(), + oldestOpenAt: z.date().nullable(), + overdue: z.number(), + pending: z.number(), + }), + }, + }, + description: "Account deletion health", + }, + }, + }, + handler: async c => { + const db = c.get("db"); + const now = new Date(); + const open = inArray(core_users_deletions.status, ["pending", "failed"]); + const overdue = and( + eq(core_users_deletions.status, "pending"), + lt(core_users_deletions.scheduledAt, now), + ); + + const [ + byStatus, + [oldest], + [next], + [erased], + [overdueCount], + attention, + [job], + ] = await Promise.all([ + db + .select({ status: core_users_deletions.status, total: count() }) + .from(core_users_deletions) + .where(open) + .groupBy(core_users_deletions.status), + db + .select({ at: min(core_users_deletions.createdAt) }) + .from(core_users_deletions) + .where(open), + db + .select({ at: min(core_users_deletions.scheduledAt) }) + .from(core_users_deletions) + .where( + and( + eq(core_users_deletions.status, "pending"), + gte(core_users_deletions.scheduledAt, now), + ), + ), + db + .select({ total: count() }) + .from(core_users_deletions) + .where( + and( + eq(core_users_deletions.status, "completed"), + gte( + core_users_deletions.completedAt, + new Date(now.getTime() - 30 * DAY_MS), + ), + ), + ), + db.select({ total: count() }).from(core_users_deletions).where(overdue), + db + .select({ + attempts: core_users_deletions.attempts, + id: core_users_deletions.id, + lastError: core_users_deletions.lastError, + scheduledAt: core_users_deletions.scheduledAt, + status: core_users_deletions.status, + userId: core_users.id, + userName: core_users.name, + }) + .from(core_users_deletions) + .leftJoin(core_users, eq(core_users.id, core_users_deletions.userId)) + .where(and(open, lt(core_users_deletions.scheduledAt, now))) + .orderBy(asc(core_users_deletions.scheduledAt)) + .limit(ATTENTION_LIMIT), + db + .select({ lastRun: core_cron.lastRun }) + .from(core_cron) + .where( + and( + eq(core_cron.pluginId, manifest.id), + eq(core_cron.name, accountDeletionCron.name), + ), + ) + .limit(1), + ]); + + const lastRun = job?.lastRun ?? null; + + return c.json( + { + attention: attention + .filter(row => row.status === "pending" || row.status === "failed") + .map(row => ({ + attempts: row.attempts, + id: row.id, + lastError: row.lastError, + scheduledAt: row.scheduledAt, + status: + row.status === "failed" + ? ("failed" as const) + : ("pending" as const), + user: + row.userId !== null && row.userName !== null + ? { id: row.userId, name: row.userName } + : null, + })) + .sort( + (a, b) => + Number(b.status === "failed") - Number(a.status === "failed"), + ), + deadlineDays: ACCOUNT_DELETION_DEADLINE_DAYS, + erasedLast30Days: erased?.total ?? 0, + failed: byStatus.find(row => row.status === "failed")?.total ?? 0, + job: { + lastRun, + nextRun: getNextCronRunDate(accountDeletionCron.schedule, lastRun), + }, + nextScheduledAt: next?.at ?? null, + oldestOpenAt: oldest?.at ?? null, + overdue: overdueCount?.total ?? 0, + pending: byStatus.find(row => row.status === "pending")?.total ?? 0, + }, + 200, + ); + }, +}); diff --git a/packages/api/src/modules/admin/users/routes/deletions.route.ts b/packages/api/src/modules/admin/users/routes/deletions.route.ts new file mode 100644 index 000000000..3fd1ff4d4 --- /dev/null +++ b/packages/api/src/modules/admin/users/routes/deletions.route.ts @@ -0,0 +1,313 @@ +import { z } from "@hono/zod-openapi"; +import { and, eq, exists, ilike, inArray, or, sql } from "drizzle-orm"; +import { alias } from "drizzle-orm/pg-core"; + +import { buildRoute } from "@/builders"; +import { + ACCOUNT_DELETION_SOURCES, + ACCOUNT_DELETION_STATUSES, + core_users_deletions, +} from "@/database/account-deletions"; +import { core_users } from "@/database/users"; +import { eraseAccount } from "@/lib/account-deletion/erase"; +import { cancelAccountDeletion } from "@/lib/account-deletion/requests"; +import { containsLikePattern } from "@/lib/api/like-pattern"; +import { writeAuditLogBestEffort } from "@/lib/audit/write"; +import { coreStaffPermissions } from "@/lib/core-staff-permissions"; +import { + withPagination, + zodPaginationPageInfo, + zodPaginationQuery, +} from "@/lib/with-pagination"; + +const requester = alias(core_users, "deletion_requester"); + +/** The known values of a comma-separated query parameter. */ +const pickListed = ( + raw: string | undefined, + known: readonly T[], +): T[] => + (raw?.split(",") ?? []).filter((value): value is T => + (known as readonly string[]).includes(value), + ); + +const zodDeletionId = z.object({ + deletionId: z + .string() + .regex(/^[1-9]\d{0,9}$/) + .openapi({ example: "1" }), +}); + +const notFound = { + content: { + "application/json": { schema: z.object({ error: z.string() }) }, + }, + description: "No such request in a state that allows this", +}; + +export const listAccountDeletionsAdminRoute = buildRoute({ + adminStaffPermission: coreStaffPermissions.admin.users.canView, + route: { + method: "get", + description: + "Account deletion requests: pending ones with their due date, failed ones with the reason, completed ones as proof of erasure. Filter by `status` and `source` (comma-separated) and `search` by name, email, #id or DR-0042 (Admin only)", + path: "/account-deletions", + request: { + query: zodPaginationQuery.extend({ + order: z.enum(["asc", "desc"]).optional(), + orderBy: z.enum(["createdAt", "scheduledAt"]).optional(), + search: z.string().max(100).optional(), + source: z.string().max(32).optional(), + status: z.string().max(64).optional(), + }), + }, + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + edges: z.array( + z.object({ + id: z.number(), + erasedUserId: z.number(), + user: z + .object({ + id: z.number(), + name: z.string(), + nameCode: z.string(), + }) + .nullable(), + requestedBy: z + .object({ id: z.number(), name: z.string() }) + .nullable(), + source: z.enum(ACCOUNT_DELETION_SOURCES), + status: z.enum(ACCOUNT_DELETION_STATUSES), + scheduledAt: z.date(), + createdAt: z.date(), + completedAt: z.date().nullable(), + cancelledAt: z.date().nullable(), + attempts: z.number(), + lastError: z.string().nullable(), + filesDeleted: z.number(), + filesKept: z.number(), + }), + ), + pageInfo: zodPaginationPageInfo, + }), + }, + }, + description: "Account deletion requests", + }, + }, + }, + handler: async c => { + const query = c.req.valid("query"); + const statuses = pickListed(query.status, ACCOUNT_DELETION_STATUSES); + const sources = pickListed(query.source, ACCOUNT_DELETION_SOURCES); + const term = query.search?.trim() ?? ""; + const ref = /^(?:dr-?)?0*(\d{1,9})$/i.exec(term.replace(/^#/, "")); + const pattern = containsLikePattern(term); + + const data = await withPagination({ + params: { query: { ...query, search: undefined } }, + where: and( + statuses.length + ? inArray(core_users_deletions.status, statuses) + : undefined, + sources.length + ? inArray(core_users_deletions.source, sources) + : undefined, + term + ? or( + exists( + c + .get("db") + .select({ one: sql`1` }) + .from(core_users) + .where( + and( + eq(core_users.id, core_users_deletions.userId), + or( + ilike(core_users.name, pattern), + ilike(core_users.nameCode, pattern), + ilike(core_users.email, pattern), + ), + ), + ), + ), + ref + ? or( + eq(core_users_deletions.id, Number(ref[1])), + eq(core_users_deletions.erasedUserId, Number(ref[1])), + ) + : undefined, + ) + : undefined, + ), + primaryCursor: core_users_deletions.id, + query: async ({ cursorSelection, limit, offset, where, orderBy }) => + await c + .get("db") + .select({ + ...cursorSelection, + id: core_users_deletions.id, + erasedUserId: core_users_deletions.erasedUserId, + userId: core_users.id, + userName: core_users.name, + userNameCode: core_users.nameCode, + requestedById: requester.id, + requestedByName: requester.name, + source: core_users_deletions.source, + status: core_users_deletions.status, + scheduledAt: core_users_deletions.scheduledAt, + createdAt: core_users_deletions.createdAt, + completedAt: core_users_deletions.completedAt, + cancelledAt: core_users_deletions.cancelledAt, + attempts: core_users_deletions.attempts, + lastError: core_users_deletions.lastError, + filesDeleted: core_users_deletions.filesDeleted, + filesKept: core_users_deletions.filesKept, + }) + .from(core_users_deletions) + .leftJoin(core_users, eq(core_users.id, core_users_deletions.userId)) + .leftJoin( + requester, + eq(requester.id, core_users_deletions.requestedById), + ) + .where(where) + .orderBy(orderBy) + .limit(limit) + .offset(offset), + table: core_users_deletions, + orderBy: { + column: core_users_deletions[query.orderBy ?? "createdAt"], + order: query.order ?? "desc", + }, + c, + }); + + return c.json( + { + pageInfo: data.pageInfo, + edges: data.edges.map( + ({ + requestedById, + requestedByName, + userId, + userName, + userNameCode, + ...row + }) => ({ + ...row, + user: + userId !== null && userName !== null && userNameCode !== null + ? { id: userId, name: userName, nameCode: userNameCode } + : null, + requestedBy: + requestedById !== null && requestedByName !== null + ? { id: requestedById, name: requestedByName } + : null, + }), + ), + }, + 200, + ); + }, +}); + +export const retryAccountDeletionAdminRoute = buildRoute({ + adminStaffPermission: coreStaffPermissions.admin.users.canDelete, + route: { + method: "post", + description: + "Run a failed or pending account erasure again now (Admin only)", + path: "/account-deletions/{deletionId}/retry", + request: { params: zodDeletionId }, + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ status: z.enum(["completed", "failed"]) }), + }, + }, + description: "The erasure ran", + }, + 403: { description: "Access Denied" }, + 404: notFound, + }, + }, + handler: async c => { + const deletionId = Number(c.req.valid("param").deletionId); + + const [row] = await c + .get("db") + .update(core_users_deletions) + .set({ attempts: 0, scheduledAt: new Date(), status: "pending" }) + .where( + and( + eq(core_users_deletions.id, deletionId), + inArray(core_users_deletions.status, ["failed", "pending"]), + ), + ) + .returning({ + status: core_users_deletions.status, + userId: core_users_deletions.userId, + }); + + if (!row?.userId) { + return c.json({ error: "No account is waiting for this request" }, 404); + } + + const result = await eraseAccount(c, { + deletionId, + userId: row.userId, + }); + + return c.json( + { status: result.status === "failed" ? "failed" : "completed" }, + 200, + ); + }, +}); + +export const cancelAccountDeletionAdminRoute = buildRoute({ + adminStaffPermission: coreStaffPermissions.admin.users.canDelete, + route: { + method: "delete", + description: + "Cancel a pending account deletion; the account stays (Admin only)", + path: "/account-deletions/{deletionId}", + request: { params: zodDeletionId }, + responses: { + 200: { description: "Deletion cancelled" }, + 403: { description: "Access Denied" }, + 404: notFound, + }, + }, + handler: async c => { + const deletionId = Number(c.req.valid("param").deletionId); + + const [row] = await c + .get("db") + .select({ userId: core_users_deletions.userId }) + .from(core_users_deletions) + .where( + and( + eq(core_users_deletions.id, deletionId), + eq(core_users_deletions.status, "pending"), + ), + ) + .limit(1); + + if (!row?.userId || !(await cancelAccountDeletion(c, row.userId))) { + return c.json({ error: "No pending request" }, 404); + } + + await writeAuditLogBestEffort(c, { + action: "user.deletion_cancelled", + target: { id: row.userId, type: "user" }, + }); + + return c.body(null, 200); + }, +}); diff --git a/packages/api/src/modules/admin/users/routes/list.route.ts b/packages/api/src/modules/admin/users/routes/list.route.ts index 6b613860e..4e13a8956 100644 --- a/packages/api/src/modules/admin/users/routes/list.route.ts +++ b/packages/api/src/modules/admin/users/routes/list.route.ts @@ -1,11 +1,15 @@ +import type { AnyPgColumn } from "drizzle-orm/pg-core"; + import { z } from "@hono/zod-openapi"; -import { eq, inArray } from "drizzle-orm"; +import { and, eq, exists, inArray, sql } from "drizzle-orm"; import { alias } from "drizzle-orm/pg-core"; import { buildRoute } from "@/builders"; +import { core_users_deletions } from "@/database/account-deletions"; import { core_files } from "@/database/files"; import { core_roles } from "@/database/roles"; import { core_users, core_users_secondary_roles } from "@/database/users"; +import { OPEN_ACCOUNT_DELETION_STATUSES } from "@/lib/account-deletion/requests"; import { coreStaffPermissions } from "@/lib/core-staff-permissions"; import { resolveRoleNames } from "@/lib/resolve-role-names"; import { storageUrlOf } from "@/lib/storage-url"; @@ -17,6 +21,10 @@ import { const avatarFile = alias(core_files, "user_avatar_file"); +/** One column of the user's newest open deletion request, as a scalar subquery. */ +const openDeletion = (column: AnyPgColumn) => + sql`select ${column} from ${core_users_deletions} where ${core_users_deletions.userId} = ${core_users.id} and ${core_users_deletions.status} in ('pending', 'failed') order by ${core_users_deletions.createdAt} desc limit 1`; + export const listUsersAdminRoute = buildRoute({ adminStaffPermission: coreStaffPermissions.admin.users.canView, route: { @@ -29,6 +37,8 @@ export const listUsersAdminRoute = buildRoute({ orderBy: z.enum(["name", "createdAt"]).optional(), roleId: z.string().optional(), search: z.string().optional(), + /** Comma-separated: `pending`, `failed` - members with such an open deletion request. */ + deletion: z.string().optional(), }), }, responses: { @@ -74,6 +84,13 @@ export const listUsersAdminRoute = buildRoute({ ), birthday: z.date().nullable(), language: z.string(), + /** The open deletion request, if any. */ + deletion: z + .object({ + scheduledAt: z.date(), + status: z.enum(OPEN_ACCOUNT_DELETION_STATUSES), + }) + .nullable(), }), ), pageInfo: zodPaginationPageInfo, @@ -90,12 +107,32 @@ export const listUsersAdminRoute = buildRoute({ .filter(Boolean) .map(id => Number(id)) .filter(id => !Number.isNaN(id)); + const deletionStatuses = (query.deletion?.split(",") ?? []).filter( + (status): status is (typeof OPEN_ACCOUNT_DELETION_STATUSES)[number] => + (OPEN_ACCOUNT_DELETION_STATUSES as readonly string[]).includes(status), + ); const data = await withPagination({ params: { query, }, search: [core_users.name, core_users.email, core_users.nameCode], - where: roleIds.length ? inArray(core_users.roleId, roleIds) : undefined, + where: and( + roleIds.length ? inArray(core_users.roleId, roleIds) : undefined, + deletionStatuses.length + ? exists( + c + .get("db") + .select({ one: sql`1` }) + .from(core_users_deletions) + .where( + and( + eq(core_users_deletions.userId, core_users.id), + inArray(core_users_deletions.status, deletionStatuses), + ), + ), + ) + : undefined, + ), primaryCursor: core_users.id, query: async ({ cursorSelection, limit, offset, where, orderBy }) => await c @@ -116,6 +153,13 @@ export const listUsersAdminRoute = buildRoute({ birthday: core_users.birthday, language: core_users.language, avatarKey: avatarFile.key, + deletionStatus: sql< + null | string + >`(${openDeletion(core_users_deletions.status)})`, + deletionScheduledAt: + sql`(${openDeletion(core_users_deletions.scheduledAt)})`.mapWith( + core_users_deletions.scheduledAt, + ), }) .from(core_users) .leftJoin(core_roles, eq(core_roles.id, core_users.roleId)) @@ -164,8 +208,20 @@ export const listUsersAdminRoute = buildRoute({ return c.json({ pageInfo: data.pageInfo, edges: data.edges.map( - ({ avatarKey, roleColor, rolePrefix, ...user }) => ({ + ({ + avatarKey, + deletionScheduledAt, + deletionStatus, + roleColor, + rolePrefix, + ...user + }) => ({ ...user, + deletion: + deletionScheduledAt && + (deletionStatus === "pending" || deletionStatus === "failed") + ? { scheduledAt: deletionScheduledAt, status: deletionStatus } + : null, avatarUrl: storageUrlOf(c, avatarKey), role: { id: user.roleId, diff --git a/packages/api/src/modules/admin/users/routes/show.route.ts b/packages/api/src/modules/admin/users/routes/show.route.ts index bee09022d..afa1bb148 100644 --- a/packages/api/src/modules/admin/users/routes/show.route.ts +++ b/packages/api/src/modules/admin/users/routes/show.route.ts @@ -1,6 +1,7 @@ import { z } from "@hono/zod-openapi"; import { buildRoute } from "@/builders"; +import { findOpenAccountDeletion } from "@/lib/account-deletion/requests"; import { isStaff } from "@/lib/check-staff-permission"; import { coreStaffPermissions } from "@/lib/core-staff-permissions"; import { resolveUserRoles, userRoleSchema } from "@/lib/resolve-user-roles"; @@ -46,6 +47,17 @@ export const showUserAdminRoute = buildRoute({ timeZone: z.string().nullable(), isStaff: z.boolean(), imagePolicy: zodUserImagePolicy, + /** The open deletion request: pending, or failed and waiting for a retry. */ + pendingDeletion: z + .object({ + attempts: z.number(), + id: z.number(), + lastError: z.string().nullable(), + scheduledAt: z.date(), + source: z.enum(["user", "admin"]), + status: z.enum(["pending", "failed"]), + }) + .nullable(), }), }, }, @@ -82,18 +94,30 @@ export const showUserAdminRoute = buildRoute({ return c.json({ error: "User not found" }, 404); } - const [roles, adminStaff, moderatorStaff, imagePolicy] = await Promise.all([ - resolveUserRoles(c, user), - isStaff(c, { type: "admin", userId: user.id }), - isStaff(c, { type: "moderator", userId: user.id }), - resolveUserImagePolicy(c, user, { ignoreAllow: true }), - ]); + const [roles, adminStaff, moderatorStaff, imagePolicy, pendingDeletion] = + await Promise.all([ + resolveUserRoles(c, user), + isStaff(c, { type: "admin", userId: user.id }), + isStaff(c, { type: "moderator", userId: user.id }), + resolveUserImagePolicy(c, user, { ignoreAllow: true }), + findOpenAccountDeletion(c, user.id), + ]); return c.json( { ...user, imagePolicy, isStaff: adminStaff || moderatorStaff, + pendingDeletion: pendingDeletion + ? { + attempts: pendingDeletion.attempts, + id: pendingDeletion.id, + lastError: pendingDeletion.lastError, + scheduledAt: pendingDeletion.scheduledAt, + source: pendingDeletion.source, + status: pendingDeletion.status, + } + : null, ...roles, }, 200, diff --git a/packages/api/src/modules/admin/users/users.module.ts b/packages/api/src/modules/admin/users/users.module.ts index 0a9e3e9c8..dd4eaff00 100644 --- a/packages/api/src/modules/admin/users/users.module.ts +++ b/packages/api/src/modules/admin/users/users.module.ts @@ -1,6 +1,13 @@ import { buildModule } from "@/builders"; import { createUserAdminRoute } from "./routes/create.route"; +import { deleteUserAdminRoute } from "./routes/delete.route"; +import { accountDeletionsSummaryAdminRoute } from "./routes/deletions-summary.route"; +import { + cancelAccountDeletionAdminRoute, + listAccountDeletionsAdminRoute, + retryAccountDeletionAdminRoute, +} from "./routes/deletions.route"; import { listUserDevicesAdminRoute } from "./routes/devices.route"; import { deleteUserImageAdminRoute } from "./routes/image-delete.route"; import { uploadUserImageAdminRoute } from "./routes/image-upload.route"; @@ -25,6 +32,10 @@ import { verifyEmailUserAdminRoute } from "./routes/verify-email.route"; export const usersAdminModule = buildModule({ name: "users", routes: [ + accountDeletionsSummaryAdminRoute, + listAccountDeletionsAdminRoute, + retryAccountDeletionAdminRoute, + cancelAccountDeletionAdminRoute, listUsersAdminRoute, createUserAdminRoute, showUserAdminRoute, @@ -46,5 +57,6 @@ export const usersAdminModule = buildModule({ updateUserNotificationPreferencesAdminRoute, uploadUserImageAdminRoute, deleteUserImageAdminRoute, + deleteUserAdminRoute, ], }); diff --git a/packages/api/src/modules/cron/cron.module.ts b/packages/api/src/modules/cron/cron.module.ts index ae006e2d0..eb1a1d304 100644 --- a/packages/api/src/modules/cron/cron.module.ts +++ b/packages/api/src/modules/cron/cron.module.ts @@ -1,12 +1,20 @@ import { buildModule } from "@/builders"; +import { accountDeletionCron } from "./cron/account-deletion.cron"; import { auditRetentionCron } from "./cron/audit-retention.cron"; import { checkUpdatesCron } from "./cron/check-updates.cron"; import { cleanCron } from "./cron/clean.cron"; +import { ipRetentionCron } from "./cron/ip-retention.cron"; import { runCronRoute } from "./routes/run.route"; export const cronModule = buildModule({ name: "cron", routes: [runCronRoute], - cronJobs: [cleanCron, checkUpdatesCron, auditRetentionCron], + cronJobs: [ + cleanCron, + checkUpdatesCron, + auditRetentionCron, + accountDeletionCron, + ipRetentionCron, + ], }); diff --git a/packages/api/src/modules/cron/cron/account-deletion.cron.ts b/packages/api/src/modules/cron/cron/account-deletion.cron.ts new file mode 100644 index 000000000..74dfee967 --- /dev/null +++ b/packages/api/src/modules/cron/cron/account-deletion.cron.ts @@ -0,0 +1,12 @@ +import { processDueAccountDeletions } from "@/lib/account-deletion/erase"; +import { buildCron } from "@/lib/cron"; + +export const accountDeletionCron = buildCron({ + name: "account-deletion", + description: + "Erase accounts whose deletion grace period is over (users.accountDeletion.graceDays in the API config)", + schedule: "25 * * * *", + handler: async c => { + await processDueAccountDeletions(c); + }, +}); diff --git a/packages/api/src/modules/cron/cron/ip-retention.cron.ts b/packages/api/src/modules/cron/cron/ip-retention.cron.ts new file mode 100644 index 000000000..05e41ec73 --- /dev/null +++ b/packages/api/src/modules/cron/cron/ip-retention.cron.ts @@ -0,0 +1,14 @@ +import { pruneIpAddresses } from "@/lib/account-deletion/ip-retention"; +import { buildCron } from "@/lib/cron"; + +export const ipRetentionCron = buildCron({ + name: "ip-retention", + description: + "Forget IP addresses older than users.ipRetentionDays in the API config: delete old debug logs and clear stored IPs", + schedule: "50 3 * * *", + handler: async c => { + await pruneIpAddresses(c.get("db"), { + retentionDays: c.get("core").privacy.ipRetentionDays, + }); + }, +}); diff --git a/packages/api/src/modules/users/passkeys/routes/admin-sign-in-verify.route.ts b/packages/api/src/modules/users/passkeys/routes/admin-sign-in-verify.route.ts index a8911726a..a2665119d 100644 --- a/packages/api/src/modules/users/passkeys/routes/admin-sign-in-verify.route.ts +++ b/packages/api/src/modules/users/passkeys/routes/admin-sign-in-verify.route.ts @@ -1,6 +1,7 @@ import { z } from "@hono/zod-openapi"; import { buildRoute } from "@/builders"; +import { assertNoAccountDeletion } from "@/lib/account-deletion/sign-in-hold"; import { isStaff } from "@/lib/check-staff-permission"; import { PasskeyError, PasskeyModel } from "@/models/passkey"; import { SessionAdminModel } from "@/models/session-admin"; @@ -52,6 +53,7 @@ export const passkeyAdminSignInVerifyRoute = buildRoute({ if (!(await isStaff(c, { live: true, type: "admin", userId }))) { throw new PasskeyError("not_staff", 403); } + await assertNoAccountDeletion(c, userId); await new SessionAdminModel(c).createSessionByUserId(userId); return c.json({ id: userId }, 201); diff --git a/packages/api/src/modules/users/passkeys/routes/authentication-verify.route.ts b/packages/api/src/modules/users/passkeys/routes/authentication-verify.route.ts index ab7f20ac3..86e6c1bdb 100644 --- a/packages/api/src/modules/users/passkeys/routes/authentication-verify.route.ts +++ b/packages/api/src/modules/users/passkeys/routes/authentication-verify.route.ts @@ -3,6 +3,10 @@ import { eq } from "drizzle-orm"; import { buildRoute } from "@/builders"; import { core_users } from "@/database/users"; +import { + holdSignInForAccountDeletion, + zodAccountDeletionHold, +} from "@/lib/account-deletion/sign-in-hold"; import { EMAIL_NOT_VERIFIED, mustVerifyEmail, @@ -14,6 +18,7 @@ import { passkeyFailure } from "../lib/failure"; import { PASSKEY_ERROR_RESPONSES, zodPasskeyAuthenticationResponseSchema, + zodPasskeyErrorSchema, } from "../passkeys.schema"; export const passkeyAuthenticationVerifyRoute = buildRoute({ @@ -44,6 +49,15 @@ export const passkeyAuthenticationVerifyRoute = buildRoute({ description: "Signed in", }, ...PASSKEY_ERROR_RESPONSES, + 403: { + content: { + "application/json": { + schema: z.union([zodPasskeyErrorSchema, zodAccountDeletionHold]), + }, + }, + description: + "The passkey could not be verified or the email is not confirmed yet. For an account scheduled for deletion: `{ error: 'account_deletion_pending', scheduledAt, token }`, and no session starts until `POST /sign_in/cancel-deletion` confirms with that token", + }, }, }, handler: async c => { @@ -64,6 +78,9 @@ export const passkeyAuthenticationVerifyRoute = buildRoute({ throw new PasskeyError(EMAIL_NOT_VERIFIED, 403); } + const hold = await holdSignInForAccountDeletion(c, userId); + if (hold) return c.json(hold, 403); + await new SessionModel(c).createSessionByUserId(userId); return c.json({ id: userId }, 201); diff --git a/packages/api/src/modules/users/routes/account-deletion.route.ts b/packages/api/src/modules/users/routes/account-deletion.route.ts new file mode 100644 index 000000000..7257f9bc5 --- /dev/null +++ b/packages/api/src/modules/users/routes/account-deletion.route.ts @@ -0,0 +1,221 @@ +import { z } from "@hono/zod-openapi"; +import { eq } from "drizzle-orm"; +import { HTTPException } from "hono/http-exception"; + +import { buildRoute } from "@/builders"; +import { ACCOUNT_DELETION_SOURCES } from "@/database/account-deletions"; +import { core_users } from "@/database/users"; +import { + cancelAccountDeletion, + canDeleteOwnAccount, + findOpenAccountDeletion, + scheduleAccountDeletion, +} from "@/lib/account-deletion/requests"; +import { isStaff } from "@/lib/check-staff-permission"; +import { PasswordModel } from "@/models/password"; +import { SessionModel } from "@/models/session"; + +import { USER_PASSWORD_MAX_LENGTH } from "../lib/credential-limits"; + +/** How recent a sign-in must be to delete an account that has no password. */ +export const ACCOUNT_DELETION_RECENT_AUTH_MS = 15 * 60_000; + +const zodPendingDeletion = z + .object({ + createdAt: z.date(), + scheduledAt: z.date(), + source: z.enum(ACCOUNT_DELETION_SOURCES), + }) + .nullable(); + +const zodError = z.object({ + error: z.enum([ + "invalid_password", + "not_allowed", + "password_required", + "reauthentication_required", + "staff_account", + ]), +}); + +const requireUser = (user: null | { id: number; roleId: number }) => { + if (!user) throw new HTTPException(401, { message: "Unauthorized" }); + + return user; +}; + +export const accountDeletionStatusRoute = buildRoute({ + route: { + method: "get", + description: + "The signed-in member's pending account deletion, and what deleting the account requires.", + path: "/me/account-deletion", + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + /** `false` when one of the member's roles turns self-deletion off. */ + allowed: z.boolean(), + graceDays: z.number().int(), + hasPassword: z.boolean(), + pending: zodPendingDeletion, + staff: z.boolean(), + }), + }, + }, + description: "Account deletion status", + }, + 401: { description: "Unauthorized" }, + }, + }, + handler: async c => { + const user = requireUser(c.get("user")); + + const [[row], pending, staff, allowed] = await Promise.all([ + c + .get("db") + .select({ password: core_users.password }) + .from(core_users) + .where(eq(core_users.id, user.id)) + .limit(1), + findOpenAccountDeletion(c, user.id), + isStaff(c, { live: true, type: "admin", userId: user.id }), + canDeleteOwnAccount(c, user), + ]); + + return c.json( + { + allowed, + graceDays: c.get("core").privacy.deletionGraceDays, + hasPassword: !!row?.password, + pending: pending + ? { + createdAt: pending.createdAt, + scheduledAt: pending.scheduledAt, + source: pending.source, + } + : null, + staff, + }, + 200, + ); + }, +}); + +export const requestAccountDeletionRoute = buildRoute({ + route: { + method: "post", + description: + "Schedules the signed-in member's account for deletion after the grace period (`users.accountDeletion.graceDays`). Requires the password, or a sign-in in the last 15 minutes for an account without one. Signs the account out everywhere and emails how to cancel. Refused for AdminCP staff and for members of a role without `allowDeleteAccount`.", + path: "/me/account-deletion", + request: { + body: { + required: true, + content: { + "application/json": { + schema: z.object({ + password: z + .string() + .max(USER_PASSWORD_MAX_LENGTH) + .optional() + .openapi({ example: "Test123!" }), + }), + }, + }, + }, + }, + responses: { + 201: { + content: { + "application/json": { + schema: z.object({ scheduledAt: z.date() }), + }, + }, + description: "Deletion scheduled", + }, + 400: { + content: { "application/json": { schema: zodError } }, + description: "Wrong or missing password", + }, + 401: { description: "Unauthorized" }, + 403: { + content: { "application/json": { schema: zodError } }, + description: + "The account has no password and the sign-in is not recent, it belongs to AdminCP staff, or a role does not allow deleting the account", + }, + }, + }, + handler: async c => { + const user = requireUser(c.get("user")); + const { password } = c.req.valid("json"); + + if (await isStaff(c, { live: true, type: "admin", userId: user.id })) { + return c.json({ error: "staff_account" as const }, 403); + } + if (!(await canDeleteOwnAccount(c, user))) { + return c.json({ error: "not_allowed" as const }, 403); + } + + const [row] = await c + .get("db") + .select({ password: core_users.password }) + .from(core_users) + .where(eq(core_users.id, user.id)) + .limit(1); + + const passwords = new PasswordModel(); + if (row?.password) { + if (!password) { + return c.json({ error: "password_required" as const }, 400); + } + if (!(await passwords.verifyPassword(password, row.password))) { + return c.json({ error: "invalid_password" as const }, 400); + } + } else { + const signedInAt = await new SessionModel(c).getSessionCreatedAt(); + if ( + signedInAt === null || + Date.now() - signedInAt.getTime() > ACCOUNT_DELETION_RECENT_AUTH_MS + ) { + return c.json({ error: "reauthentication_required" as const }, 403); + } + } + + const deletion = await scheduleAccountDeletion(c, { + requestedById: user.id, + source: "user", + userId: user.id, + }); + + return c.json({ scheduledAt: deletion.scheduledAt }, 201); + }, +}); + +export const cancelAccountDeletionRoute = buildRoute({ + route: { + method: "delete", + description: + "Cancels the signed-in member's pending account deletion; the account stays as it was.", + path: "/me/account-deletion", + responses: { + 200: { description: "Deletion cancelled" }, + 401: { description: "Unauthorized" }, + 404: { + content: { + "application/json": { schema: z.object({ error: z.string() }) }, + }, + description: "No deletion is pending", + }, + }, + }, + handler: async c => { + const user = requireUser(c.get("user")); + + if (!(await cancelAccountDeletion(c, user.id))) { + return c.json({ error: "No deletion is pending" }, 404); + } + + return c.body(null, 200); + }, +}); diff --git a/packages/api/src/modules/users/routes/cancel-deletion-sign-in.route.ts b/packages/api/src/modules/users/routes/cancel-deletion-sign-in.route.ts new file mode 100644 index 000000000..e5894c10e --- /dev/null +++ b/packages/api/src/modules/users/routes/cancel-deletion-sign-in.route.ts @@ -0,0 +1,55 @@ +import { z } from "zod"; + +import { buildRoute } from "@/builders"; +import { releaseAccountDeletionHold } from "@/lib/account-deletion/sign-in-hold"; +import { SessionModel } from "@/models/session"; + +export const zodCancelDeletionSignInSchema = z.object({ + token: z.string().min(16).max(2048), +}); + +export const cancelDeletionSignInRoute = buildRoute({ + route: { + method: "post", + description: + "Finish a sign-in that was held because the account is scheduled for deletion: cancels the deletion and starts a normal session. `token` is the one a sign-in answered with alongside `account_deletion_pending`; it lasts 10 minutes and works once.", + path: "/sign_in/cancel-deletion", + request: { + body: { + required: true, + content: { + "application/json": { schema: zodCancelDeletionSignInSchema }, + }, + }, + }, + responses: { + 201: { + content: { + "application/json": { schema: z.object({ id: z.number() }) }, + }, + description: "Deletion cancelled and user signed in", + }, + 400: { + content: { + "application/json": { + schema: z.object({ error: z.literal("invalid_hold") }), + }, + }, + description: + "The token is invalid, expired, already used, or the deletion is no longer pending", + }, + }, + }, + handler: async c => { + const { token } = c.req.valid("json"); + const userId = await releaseAccountDeletionHold(c, token); + + if (userId === null) { + return c.json({ error: "invalid_hold" as const }, 400); + } + + await new SessionModel(c).createSessionByUserId(userId); + + return c.json({ id: userId }, 201); + }, +}); diff --git a/packages/api/src/modules/users/routes/password-sign-in.test.ts b/packages/api/src/modules/users/routes/password-sign-in.test.ts index 8a38afdaf..e0e143bec 100644 --- a/packages/api/src/modules/users/routes/password-sign-in.test.ts +++ b/packages/api/src/modules/users/routes/password-sign-in.test.ts @@ -39,6 +39,7 @@ const fakeDb = () => { const chain = { from: () => chain, limit: () => chain, + orderBy: () => chain, then: async (onFulfilled: (value: typeof rows) => unknown) => await Promise.resolve(onFulfilled(rows)), where: () => chain, @@ -160,7 +161,7 @@ describe("authorization.password on (the default)", () => { const response = await app.request("/sign_in", post(CREDENTIALS)); expect(response.status).toBe(201); - expect(selects).toHaveBeenCalledTimes(2); + expect(selects).toHaveBeenCalledTimes(3); expect(createSession).toHaveBeenCalledWith(1); }); }); diff --git a/packages/api/src/modules/users/routes/personal-data.route.ts b/packages/api/src/modules/users/routes/personal-data.route.ts new file mode 100644 index 000000000..36d426657 --- /dev/null +++ b/packages/api/src/modules/users/routes/personal-data.route.ts @@ -0,0 +1,42 @@ +import { z } from "@hono/zod-openapi"; +import { HTTPException } from "hono/http-exception"; + +import { buildRoute } from "@/builders"; + +export const personalDataExportRoute = buildRoute({ + route: { + method: "get", + description: + "Everything the site stores about the signed-in member, from core and every plugin's `personalData.export` (GDPR Art. 15 and 20), as JSON keyed by plugin id.", + path: "/me/personal-data", + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + exportedAt: z.date(), + plugins: z.record(z.string(), z.record(z.string(), z.unknown())), + userId: z.number().int(), + }), + }, + }, + description: "The member's data", + }, + 401: { description: "Unauthorized" }, + }, + }, + handler: async c => { + const user = c.get("user"); + if (!user) throw new HTTPException(401, { message: "Unauthorized" }); + + const plugins: Record> = {}; + for (const entry of c.get("core").personalData) { + if (!entry.export) continue; + plugins[entry.pluginId] = await entry.export({ c, userId: user.id }); + } + + c.header("Cache-Control", "no-store"); + + return c.json({ exportedAt: new Date(), plugins, userId: user.id }, 200); + }, +}); diff --git a/packages/api/src/modules/users/routes/profile.route.ts b/packages/api/src/modules/users/routes/profile.route.ts index b21605ddd..be64fe578 100644 --- a/packages/api/src/modules/users/routes/profile.route.ts +++ b/packages/api/src/modules/users/routes/profile.route.ts @@ -3,6 +3,7 @@ import { eq } from "drizzle-orm"; import { buildRoute } from "@/builders"; import { core_users } from "@/database/users"; +import { findOpenAccountDeletion } from "@/lib/account-deletion/requests"; import { resolveUserRoles, userRoleSchema } from "@/lib/resolve-user-roles"; import { publicFullNameOf } from "@/lib/user-personal-information"; import { UserModel } from "@/models/user"; @@ -59,6 +60,13 @@ export const profileRoute = buildRoute({ return c.json({ error: "User not found" }, 404); } + if ( + c.get("user")?.id !== user.id && + (await findOpenAccountDeletion(c, user.id)) + ) { + return c.json({ error: "User not found" }, 404); + } + const roles = await resolveUserRoles(c, user); const [standing] = await c .get("db") diff --git a/packages/api/src/modules/users/routes/sign-in.route.ts b/packages/api/src/modules/users/routes/sign-in.route.ts index 4e9005bf7..1f1704351 100644 --- a/packages/api/src/modules/users/routes/sign-in.route.ts +++ b/packages/api/src/modules/users/routes/sign-in.route.ts @@ -7,6 +7,11 @@ import { z } from "zod"; import { buildRoute } from "@/builders"; import { core_admin_sessions } from "@/database/admins"; import { core_sessions } from "@/database/sessions"; +import { + assertNoAccountDeletion, + holdSignInForAccountDeletion, + zodAccountDeletionHold, +} from "@/lib/account-deletion/sign-in-hold"; import { deleteAuthCookie } from "@/lib/auth-cookie"; import { assertPasswordSignInEnabled } from "@/lib/password-sign-in"; import { hashSessionToken } from "@/lib/session-token"; @@ -81,11 +86,14 @@ export const signInRoute = buildRoute({ 403: { content: { "application/json": { - schema: z.object({ error: z.literal(EMAIL_NOT_VERIFIED) }), + schema: z.union([ + z.object({ error: z.literal(EMAIL_NOT_VERIFIED) }), + zodAccountDeletionHold, + ]), }, }, description: - "Access Denied. Wrong credentials answer with no body; a correct password for an account whose email is not confirmed yet answers `{ error: 'email_not_verified' }`.", + "Access Denied. Wrong credentials answer with no body; a correct password for an account whose email is not confirmed yet answers `{ error: 'email_not_verified' }`; for an account scheduled for deletion it answers `{ error: 'account_deletion_pending', scheduledAt, token }` and no session starts until `POST /sign_in/cancel-deletion` confirms with that token. An AdminCP sign-in of such an account answers with no body.", }, 201: { content: { @@ -109,6 +117,7 @@ export const signInRoute = buildRoute({ }); if (isAdmin) { + await assertNoAccountDeletion(c, data.id); const { token } = await new SessionAdminModel(c).createSessionByUserId( data.id, ); @@ -121,6 +130,9 @@ export const signInRoute = buildRoute({ return c.json({ error: EMAIL_NOT_VERIFIED } as const, 403); } + const hold = await holdSignInForAccountDeletion(c, data.id); + if (hold) return c.json(hold, 403); + const { token } = await new SessionModel(c).createSessionByUserId(data.id); await revokeIfPasswordChanged(c, data, { admin: false, token }); diff --git a/packages/api/src/modules/users/sso/routes/callback.route.ts b/packages/api/src/modules/users/sso/routes/callback.route.ts index 03c1721a8..06e279223 100644 --- a/packages/api/src/modules/users/sso/routes/callback.route.ts +++ b/packages/api/src/modules/users/sso/routes/callback.route.ts @@ -1,6 +1,10 @@ import { z } from "zod"; import { buildRoute } from "@/builders"; +import { + holdSignInForAccountDeletion, + zodAccountDeletionHold, +} from "@/lib/account-deletion/sign-in-hold"; import { SessionModel } from "@/models/session"; import { SSOModel } from "@/models/sso"; @@ -49,6 +53,13 @@ export const callbackRoute = buildRoute({ description: "The state is unknown, expired, already used, from another browser or for another provider", }, + 403: { + content: { + "application/json": { schema: zodAccountDeletionHold }, + }, + description: + "The account is scheduled for deletion. No session starts until `POST /sign_in/cancel-deletion` confirms with `token`", + }, 409: { content: { "application/json": { @@ -105,6 +116,9 @@ export const callbackRoute = buildRoute({ ); } + const hold = await holdSignInForAccountDeletion(c, outcome.userId); + if (hold) return c.json(hold, 403); + await new SessionModel(c).createSessionByUserId(outcome.userId); return c.json({ id: outcome.userId }, 200); diff --git a/packages/api/src/modules/users/sso/routes/callback.test.ts b/packages/api/src/modules/users/sso/routes/callback.test.ts index ba3831b78..1d1e3c9d8 100644 --- a/packages/api/src/modules/users/sso/routes/callback.test.ts +++ b/packages/api/src/modules/users/sso/routes/callback.test.ts @@ -56,6 +56,7 @@ const fakeDb = (accounts: Account[]) => { }, innerJoin: () => chain, limit: () => chain, + orderBy: () => chain, then: async (onFulfilled: (value: unknown) => unknown) => await Promise.resolve( onFulfilled( diff --git a/packages/api/src/modules/users/sso/routes/link.route.ts b/packages/api/src/modules/users/sso/routes/link.route.ts index e18a3d322..017fdf089 100644 --- a/packages/api/src/modules/users/sso/routes/link.route.ts +++ b/packages/api/src/modules/users/sso/routes/link.route.ts @@ -1,6 +1,10 @@ import { z } from "zod"; import { buildRoute } from "@/builders"; +import { + holdSignInForAccountDeletion, + zodAccountDeletionHold, +} from "@/lib/account-deletion/sign-in-hold"; import { assertPasswordSignInEnabled } from "@/lib/password-sign-in"; import { SessionModel } from "@/models/session"; import { SSOModel } from "@/models/sso"; @@ -50,7 +54,11 @@ export const linkRoute = buildRoute({ description: "The link token is invalid or has expired", }, 403: { - description: "Wrong password", + content: { + "application/json": { schema: zodAccountDeletionHold }, + }, + description: + "Wrong password (no body). For an account scheduled for deletion the identity is linked but no session starts: `{ error: 'account_deletion_pending', scheduledAt, token }` until `POST /sign_in/cancel-deletion` confirms with that token", }, 409: { description: "The provider account is already linked to another user", @@ -66,6 +74,9 @@ export const linkRoute = buildRoute({ providerId, token, }); + const hold = await holdSignInForAccountDeletion(c, userId); + if (hold) return c.json(hold, 403); + await new SessionModel(c).createSessionByUserId(userId); return c.json({ id: userId }, 201); diff --git a/packages/api/src/modules/users/sso/routes/pending-confirm.route.ts b/packages/api/src/modules/users/sso/routes/pending-confirm.route.ts index b40d49942..84c2be527 100644 --- a/packages/api/src/modules/users/sso/routes/pending-confirm.route.ts +++ b/packages/api/src/modules/users/sso/routes/pending-confirm.route.ts @@ -1,6 +1,10 @@ import { z } from "zod"; import { buildRoute } from "@/builders"; +import { + holdSignInForAccountDeletion, + zodAccountDeletionHold, +} from "@/lib/account-deletion/sign-in-hold"; import { SessionModel } from "@/models/session"; import { SsoEmailCompletionModel } from "@/models/sso-email-completion"; @@ -41,6 +45,13 @@ export const ssoPendingConfirmRoute = buildRoute({ description: "`invalid_pending`: no pending sign-in in this browser (another browser, or expired). `invalid_link`: the link expired, was replaced or was already used", }, + 403: { + content: { + "application/json": { schema: zodAccountDeletionHold }, + }, + description: + "The account is scheduled for deletion. No session starts until `POST /sign_in/cancel-deletion` confirms with `token`", + }, 409: { content: { "application/json": { @@ -81,6 +92,9 @@ export const ssoPendingConfirmRoute = buildRoute({ ); } + const hold = await holdSignInForAccountDeletion(c, outcome.userId); + if (hold) return c.json(hold, 403); + await new SessionModel(c).createSessionByUserId(outcome.userId); return c.json({ id: outcome.userId }, 200); diff --git a/packages/api/src/modules/users/users.module.ts b/packages/api/src/modules/users/users.module.ts index e911e59ea..4a10d7b97 100644 --- a/packages/api/src/modules/users/users.module.ts +++ b/packages/api/src/modules/users/users.module.ts @@ -3,10 +3,17 @@ import { buildModule } from "@/builders"; import { userFilesModule } from "./files/files.module"; import { userImagesModule } from "./images/images.module"; import { passkeysUserModule } from "./passkeys/passkeys.module"; +import { + accountDeletionStatusRoute, + cancelAccountDeletionRoute, + requestAccountDeletionRoute, +} from "./routes/account-deletion.route"; +import { cancelDeletionSignInRoute } from "./routes/cancel-deletion-sign-in.route"; import { changePasswordRoute } from "./routes/change-password.route"; import { listDevicesRoute } from "./routes/devices.route"; import { mePolicyRoute } from "./routes/me-policy.route"; import { permissionsRoute } from "./routes/permissions.route"; +import { personalDataExportRoute } from "./routes/personal-data.route"; import { presenceBatchRoute } from "./routes/presence-batch.route"; import { presenceHeartbeatRoute } from "./routes/presence-heartbeat.route"; import { presenceRoute } from "./routes/presence.route"; @@ -30,6 +37,7 @@ export const usersModule = buildModule({ routes: [ sessionRoute, signInRoute, + cancelDeletionSignInRoute, signOutRoute, signUpRoute, resetPasswordRoute, @@ -44,6 +52,10 @@ export const usersModule = buildModule({ updateMeRoute, updateMyTimeZoneRoute, updateMyPrivacyRoute, + accountDeletionStatusRoute, + requestAccountDeletionRoute, + cancelAccountDeletionRoute, + personalDataExportRoute, presenceHeartbeatRoute, presenceBatchRoute, presenceRoute, diff --git a/packages/api/src/plugin.ts b/packages/api/src/plugin.ts index fbbb7fce2..b5bddbc28 100644 --- a/packages/api/src/plugin.ts +++ b/packages/api/src/plugin.ts @@ -17,6 +17,7 @@ import { paymentEventDefinitions } from "./events/payments"; import { reactionEventDefinitions } from "./events/reactions"; import { roleEventDefinitions } from "./events/roles"; import { userEventDefinitions } from "./events/users"; +import { corePersonalData } from "./lib/account-deletion/core-personal-data"; import { altGenerateAiAction, altTranslateAiAction, @@ -80,6 +81,7 @@ export const newBuildPluginApiCore = buildApiPlugin({ searchModule, ], permissionStaff: coreStaffPermissions, + personalData: corePersonalData, }); export type VitNodeApiPlugin = ApiPluginContract; diff --git a/packages/api/src/vitnode.config.ts b/packages/api/src/vitnode.config.ts index 2a3df5066..9767c6470 100644 --- a/packages/api/src/vitnode.config.ts +++ b/packages/api/src/vitnode.config.ts @@ -257,6 +257,23 @@ export interface VitNodeApiConfig { }; /** Member profile settings. */ users?: { + /** Members deleting their own account (GDPR Art. 17). */ + accountDeletion?: { + /** + * Days between a member's request and the erasure, during which they can + * sign in and cancel it. `0` erases on the next hourly run. Whole days, + * at most `30` so the request is handled within the month GDPR allows. + * Defaults to `14`. + */ + graceDays?: number; + }; + /** + * How many days IP addresses are kept: debug logs older than this are + * deleted, and the IP is cleared from Activity Logs entries and from the + * sign-up IP of accounts. A daily job does it. `0` keeps them. Defaults to + * `180`. + */ + ipRetentionDays?: number; /** * Which personal-information fields this install offers. Every field is on * unless it is set to `false`, and turning one off hides it from the diff --git a/packages/vitnode/src/components/danger-zone.tsx b/packages/vitnode/src/components/danger-zone.tsx new file mode 100644 index 000000000..e3d4058ac --- /dev/null +++ b/packages/vitnode/src/components/danger-zone.tsx @@ -0,0 +1,89 @@ +import { cn } from "cn"; +import { TriangleAlertIcon } from "lucide-react"; +import React from "react"; + +/** + * A red-tinted section for irreversible actions, such as deleting an account, + * framed like the settings groups beside it. Put each action in a + * {@link DangerZoneItem}; other children need their own padding. + * + * @example + * ```tsx + * + * + * + * + * + * ``` + */ +export const DangerZone = ({ + children, + className, + description, + headingLevel = 2, + title, +}: { + children: React.ReactNode; + className?: string; + description?: React.ReactNode; + /** The heading's level in the page outline. Defaults to `2`. */ + headingLevel?: 2 | 3; + title: React.ReactNode; +}) => { + const titleId = React.useId(); + const Heading = headingLevel === 2 ? "h2" : "h3"; + + return ( +
+
+ + + {description ? ( +

+ {description} +

+ ) : null} +
+
+ {children} +
+
+ ); +}; + +/** One irreversible action in a {@link DangerZone}: what it does, and its controls. */ +export const DangerZoneItem = ({ + children, + description, + title, +}: { + /** The action's controls, beside the text when the zone is wide enough. */ + children?: React.ReactNode; + description?: React.ReactNode; + title: React.ReactNode; +}) => ( +
+
+

{title}

+ {description ? ( +
+ {description} +
+ ) : null} +
+ {children ? ( +
{children}
+ ) : null} +
+); diff --git a/packages/vitnode/src/components/ui/label.tsx b/packages/vitnode/src/components/ui/label.tsx index f8c87ba8c..10c2af0d4 100644 --- a/packages/vitnode/src/components/ui/label.tsx +++ b/packages/vitnode/src/components/ui/label.tsx @@ -6,7 +6,7 @@ function Label({ className, ...props }: React.ComponentProps<"label">) { return (