diff --git a/API/openapi.yaml b/API/openapi.yaml index c70f2071..627f64af 100644 --- a/API/openapi.yaml +++ b/API/openapi.yaml @@ -9561,8 +9561,11 @@ paths: /auth/delete-account: get: tags: [Auth] - summary: Open the first-party global account-deletion form + summary: Open the global or product account-deletion form operationId: accountDeletionForm + parameters: + - { in: query, name: product, schema: { type: string }, description: Registered product policy identifier } + - { in: query, name: action, schema: { type: string, enum: [rejoin] }, description: Fresh product registration after completed erasure } responses: '200': description: Account deletion request form. @@ -9585,6 +9588,8 @@ paths: additionalProperties: false required: [email] properties: + product: { type: string } + rejoin: { type: boolean } email: type: string format: email @@ -9608,7 +9613,7 @@ paths: tags: [Auth] summary: Confirm a deletion request using a mailbox code and any enrolled authenticator operationId: confirmAccountDeletion - description: Requires the browser cookie issued by start. A successful request is queued for administrative review. + description: Requires the browser cookie issued by start. A global request enters administrative review. A product request returns its current impact for separate confirmation. requestBody: required: true content: @@ -9618,9 +9623,12 @@ paths: additionalProperties: false required: [challengeId, code] properties: + product: { type: string } + rejoin: { type: boolean } challengeId: type: string format: uuid + password: { type: string, format: password, description: Optional independent UOA password for managed product accounts } code: type: string pattern: '^[0-9]{6}$' @@ -9629,18 +9637,143 @@ paths: pattern: '^[0-9]{6}$' responses: '200': - description: Confirmed request saved. No session is issued. + description: Global request accepted or product preview returned. content: application/json: schema: - type: object - required: [submitted] - properties: - submitted: - type: boolean - enum: [true] + oneOf: + - { type: object, required: [submitted], properties: { submitted: { type: boolean, enum: [true] } } } + - { type: object, required: [digest, impact], properties: { digest: { type: string }, impact: { type: object } } } '401': description: The browser proof, mailbox code or required authenticator code could not be verified. + /auth/delete-account/product/{id}: + get: + tags: [Auth] + summary: Read the enabled product name and retention disclosure + parameters: + - { in: path, name: id, required: true, schema: { type: string } } + responses: + '200': { description: Product name and deletion disclosure } + '404': { description: Unknown or disabled product } + /auth/delete-account/submit-product: + post: + tags: [Auth] + summary: Confirm the exact product preview with the original browser cookie + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + required: [product, challengeId, digest] + properties: + product: { type: string } + challengeId: { type: string, format: uuid } + digest: { type: string, pattern: '^[a-f0-9]{64}$' } + rejoin: { type: boolean } + container: + type: object + required: [scope, id] + properties: + scope: { type: string, enum: [TEAM, ORGANISATION] } + id: { type: string } + responses: + '200': { description: Receipt identifier and completion flag } + '401': { description: Missing or stale proof } + '409': { description: Refresh the preview or check the original request } + /auth/delete-account/receipt/{id}: + get: + tags: [Auth] + summary: Check an opaque deletion receipt after sign-out + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + '200': { description: Plain text progress or completion } + '404': { description: Receipt unavailable } + /domain/product-participation: + get: + security: [{ domainHashBearer: [] }] + summary: Check the current product participation generation before accepting a saved session or sync write + parameters: + - { in: query, name: domain, required: true, schema: { type: string } } + - { in: query, name: subject, required: true, schema: { type: string } } + responses: + '200': { description: 'Product identifier, active flag and generation. Independently authenticate the subject.' } + /domain/product-erasure-jobs: + get: + security: [{ domainHashBearer: [] }] + summary: Pull pending personal erasure work for the authenticated backend + parameters: + - { in: query, name: domain, required: true, schema: { type: string } } + - { in: query, name: after, schema: { type: string, format: uuid } } + responses: + '200': { description: Up to 100 assigned jobs and a next cursor } + /domain/product-erasure-jobs/{id}/acknowledge: + post: + security: [{ domainHashBearer: [] }] + summary: Acknowledge committed product data cleanup + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: query, name: domain, required: true, schema: { type: string } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [revision, outcome] + properties: + revision: { type: integer, minimum: 1 } + outcome: { type: string, enum: [PURGED, RETAINED_EVIDENCE] } + responses: + '200': { description: Acknowledgement recorded or exact replay accepted } + '409': { description: Conflicting acknowledgement } + /internal/admin/product-erasure: + get: + tags: [Internal Admin] + security: [{ adminBearer: [] }] + summary: List registered policies and outstanding work + responses: + '200': { description: Policies and outstanding jobs } + post: + tags: [Internal Admin] + security: [{ adminBearer: [] }] + summary: Save a product policy using its current revision + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [id, revision, name, mode, enabled, disclosure, domains, nativeApps, settings] + properties: + id: { type: string } + revision: { type: integer, minimum: 0 } + name: { type: string } + mode: { type: string, enum: [PERSONAL, ORGANISATION] } + enabled: { type: boolean } + disclosure: { type: string } + domains: { type: array, items: { type: string } } + nativeApps: { type: array, items: { type: string } } + settings: { type: array, items: { type: string } } + responses: + '200': { description: Saved policy and revision } + /internal/admin/product-erasure/{id}/container: + post: + tags: [Internal Admin] + security: [{ adminBearer: [] }] + summary: Review the exact requested container after checking external dependencies + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/json: + schema: { type: object, required: [decision], properties: { decision: { type: string, enum: [approve, preserve] } } } + responses: + '200': { description: Decision recorded } + '409': { description: Scope changed or review already closed } /internal/admin/users: post: tags: [Internal Admin] diff --git a/API/prisma/migrations/20261120100000_product_erasure/migration.sql b/API/prisma/migrations/20261120100000_product_erasure/migration.sql new file mode 100644 index 00000000..5fa573fb --- /dev/null +++ b/API/prisma/migrations/20261120100000_product_erasure/migration.sql @@ -0,0 +1,84 @@ +BEGIN; +ALTER TABLE verification_tokens ADD COLUMN product_preview_digest text, ADD COLUMN product_factor_digest text, ADD COLUMN product_receipt_id text, ADD COLUMN product_selection text; +CREATE TABLE product_erasure_policies ( + id text PRIMARY KEY, name text NOT NULL, mode text NOT NULL CHECK (mode IN ('PERSONAL','ORGANISATION')), + enabled boolean NOT NULL DEFAULT false, revision integer NOT NULL DEFAULT 1, + closed_bootstrap_domains text[] NOT NULL DEFAULT ARRAY[]::text[], + disclosure text NOT NULL, domains text[] NOT NULL, native_apps text[] NOT NULL, settings text[] NOT NULL +); +CREATE TABLE product_erasure_jobs ( + id text PRIMARY KEY, policy_id text NOT NULL REFERENCES product_erasure_policies(id) ON DELETE RESTRICT, + container_preserved boolean NOT NULL DEFAULT false, requested_container jsonb, container_job_id text REFERENCES entity_deletion_jobs(id) ON DELETE RESTRICT, + rejoined_subject text, rejoined_at timestamp(3), notice_due_at timestamp(3) DEFAULT CURRENT_TIMESTAMP, + subject text NOT NULL, revision integer NOT NULL, impact jsonb NOT NULL, + created_at timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, completed_at timestamp(3), + UNIQUE(subject, policy_id) +); +CREATE INDEX product_erasure_generation_idx ON product_erasure_jobs(policy_id, rejoined_subject, rejoined_at); +CREATE INDEX product_erasure_notice_idx ON product_erasure_jobs(notice_due_at) WHERE completed_at IS NOT NULL; +CREATE TABLE product_erasure_receipts ( + job_id text NOT NULL REFERENCES product_erasure_jobs(id) ON DELETE CASCADE, domain_id text NOT NULL, + acknowledged_at timestamp(3), outcome text CHECK (outcome IN ('PURGED','RETAINED_EVIDENCE')), + PRIMARY KEY(job_id, domain_id) +); +CREATE INDEX product_erasure_receipts_domain_id_acknowledged_at_idx ON product_erasure_receipts(domain_id, acknowledged_at); +-- Once every participant has acknowledged, the receipt and admission fence only +-- need the product, subject, revision, outcome and dates. +CREATE FUNCTION scrub_completed_product_erasure() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + NEW.impact := '{}'::jsonb; + NEW.requested_container := NULL; + RETURN NEW; +END $$; +CREATE TRIGGER scrub_completed_product_erasure BEFORE INSERT OR UPDATE ON product_erasure_jobs +FOR EACH ROW WHEN (NEW.completed_at IS NOT NULL) EXECUTE FUNCTION scrub_completed_product_erasure(); + +-- Requests, inventories and acknowledgements are visible only through the admin connection. +ALTER TABLE product_erasure_policies ENABLE ROW LEVEL SECURITY; +ALTER TABLE product_erasure_jobs ENABLE ROW LEVEL SECURITY; +ALTER TABLE product_erasure_receipts ENABLE ROW LEVEL SECURITY; + +-- Tenant transactions get a denial bit, never an enumerable request or writable authority row. +CREATE FUNCTION product_erasure_admission(person text, client_domain text, native_app text) +RETURNS TABLE(denied boolean, bootstrap_closed boolean) LANGUAGE sql STABLE SECURITY DEFINER AS $$ + SELECT EXISTS (SELECT 1 FROM product_erasure_jobs j + JOIN product_erasure_policies p ON p.id=j.policy_id + WHERE j.subject=person AND (client_domain=ANY(p.domains) OR native_app=ANY(p.native_apps))), + EXISTS (SELECT 1 FROM product_erasure_policies WHERE client_domain=ANY(closed_bootstrap_domains)) +$$; + +DO $$ BEGIN + EXECUTE format('ALTER FUNCTION %I.product_erasure_admission(text,text,text) SET search_path = pg_catalog,%I,pg_temp', current_schema(), current_schema()); +END $$; + +REVOKE ALL ON product_erasure_jobs,product_erasure_receipts,product_erasure_policies FROM uoa_app; +GRANT SELECT,INSERT,UPDATE,DELETE ON product_erasure_jobs,product_erasure_receipts,product_erasure_policies TO uoa_admin; +REVOKE ALL ON FUNCTION product_erasure_admission(text,text,text) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION product_erasure_admission(text,text,text) TO uoa_app,uoa_admin; + +CREATE FUNCTION complete_product_container_erasure() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + UPDATE product_erasure_jobs j SET completed_at=CURRENT_TIMESTAMP + WHERE j.container_job_id=NEW.id AND j.completed_at IS NULL AND NOT EXISTS + (SELECT 1 FROM product_erasure_receipts r WHERE r.job_id=j.id AND r.acknowledged_at IS NULL); + RETURN NEW; +END $$; +CREATE TRIGGER complete_product_container_erasure AFTER UPDATE OF status ON entity_deletion_jobs +FOR EACH ROW WHEN (NEW.status='COMPLETE' AND OLD.status IS DISTINCT FROM NEW.status) EXECUTE FUNCTION complete_product_container_erasure(); +-- All products may normally write shared settings. A stale sync from a different +-- client must also respect the erasure of an inventoried product key. +CREATE FUNCTION refuse_erased_product_setting() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM product_erasure_jobs j JOIN product_erasure_policies p ON p.id=j.policy_id + WHERE j.subject=NEW.user_id AND (NEW.namespace || '/' || NEW.key)=ANY(p.settings)) THEN + RAISE EXCEPTION 'PRODUCT_ACCOUNT_DELETED' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END $$; +DO $$ BEGIN + EXECUTE format('ALTER FUNCTION %I.refuse_erased_product_setting() SET search_path = pg_catalog,%I,pg_temp', current_schema(), current_schema()); +END $$; +CREATE TRIGGER refuse_erased_product_setting BEFORE INSERT OR UPDATE ON user_settings +FOR EACH ROW EXECUTE FUNCTION refuse_erased_product_setting(); +REVOKE ALL ON FUNCTION refuse_erased_product_setting() FROM PUBLIC; +COMMIT; diff --git a/API/prisma/schema.prisma b/API/prisma/schema.prisma index 6a4715c1..30b2ff6a 100644 --- a/API/prisma/schema.prisma +++ b/API/prisma/schema.prisma @@ -642,6 +642,10 @@ model AuthIdentity { } model VerificationToken { + productPreviewDigest String? @map("product_preview_digest") + productFactorDigest String? @map("product_factor_digest") + productReceiptId String? @map("product_receipt_id") + productSelection String? @map("product_selection") id String @id @default(cuid()) type VerificationTokenType email String @@ -6510,3 +6514,50 @@ model BillingBrowserCancellation { createdAt DateTime @default(now()) @map("created_at") @@map("billing_browser_cancellations") } + +model ProductErasurePolicy { + id String @id + name String + mode String + enabled Boolean @default(false) + revision Int @default(1) + disclosure String + domains String[] + nativeApps String[] @map("native_apps") + settings String[] + closedBootstrapDomains String[] @default([]) @map("closed_bootstrap_domains") + jobs ProductErasureJob[] + @@map("product_erasure_policies") +} + +model ProductErasureJob { + rejoinedSubject String? @map("rejoined_subject") + rejoinedAt DateTime? @map("rejoined_at") + noticeDueAt DateTime? @default(now()) @map("notice_due_at") + @@index([policyId, rejoinedSubject, rejoinedAt], map: "product_erasure_generation_idx") + id String @id @default(uuid()) + policyId String @map("policy_id") + containerJobId String? @map("container_job_id") + containerPreserved Boolean @default(false) @map("container_preserved") + requestedContainer Json? @map("requested_container") + subject String + revision Int + impact Json + createdAt DateTime @default(now()) @map("created_at") + completedAt DateTime? @map("completed_at") + policy ProductErasurePolicy @relation(fields: [policyId], references: [id], onDelete: Restrict) + receipts ProductErasureReceipt[] + @@unique([subject, policyId]) + @@map("product_erasure_jobs") +} + +model ProductErasureReceipt { + jobId String @map("job_id") + domainId String @map("domain_id") + acknowledgedAt DateTime? @map("acknowledged_at") + outcome String? + job ProductErasureJob @relation(fields: [jobId], references: [id], onDelete: Cascade) + @@id([jobId, domainId]) + @@index([domainId, acknowledgedAt]) + @@map("product_erasure_receipts") +} diff --git a/API/src/app.ts b/API/src/app.ts index 3801e0ba..7556f5e2 100644 --- a/API/src/app.ts +++ b/API/src/app.ts @@ -37,6 +37,7 @@ import { startMachineEventDelivery } from './services/machine-delivery.service.j import { pruneMachineBrowsers } from './services/machine-retention.service.js'; import { startEnterpriseRevocationDelivery } from './services/org-sso-delivery.service.js'; import { pruneEnterpriseRevocations } from './services/org-sso-revocation.service.js'; +import { startProductDeletionNotices } from './services/product-erasure-notification.service.js'; import { startEnterpriseMaintenance } from './services/enterprise-maintenance.service.js'; export async function createApp(): Promise { @@ -287,6 +288,8 @@ export async function createApp(): Promise { app.addHook('onClose', async () => machineDelivery.stop()); const enterpriseDelivery = startEnterpriseRevocationDelivery(app.log); app.addHook('onClose', async () => enterpriseDelivery.stop()); + const deletionNotices = startProductDeletionNotices(app.log); + app.addHook('onClose', async () => deletionNotices.stop()); const enterpriseMaintenance = startEnterpriseMaintenance(app.log); app.addHook('onClose', async () => enterpriseMaintenance.stop()); diff --git a/API/src/routes/auth/account-deletion-request.ts b/API/src/routes/auth/account-deletion-request.ts index c1aa286e..3f1fc075 100644 --- a/API/src/routes/auth/account-deletion-request.ts +++ b/API/src/routes/auth/account-deletion-request.ts @@ -1,3 +1,6 @@ +import { getAdminPrisma } from '../../db/prisma.js'; +import { ProductId } from '../../services/product-erasure-policy.service.js'; +import { enabledProduct } from '../../services/product-erasure.service.js'; import { randomBytes } from 'node:crypto'; import type { FastifyInstance } from 'fastify'; import { decodeJwt } from 'jose'; @@ -7,18 +10,19 @@ import { getPublicBaseUrl } from '../../config/env.js'; import { createKeyedRateLimiter, createRateLimiter } from '../../middleware/rate-limiter.js'; import { requireSameOriginBrowserRequest } from '../../middleware/same-origin-browser.js'; import { ACCOUNT_DELETION_PATH, ACCOUNT_DELETION_PROOF_SECONDS, confirmAccountDeletionRequest, - startAccountDeletionRequest } from '../../services/account-deletion-request.service.js'; + startAccountDeletionRequest, submitProductErasure } from '../../services/account-deletion-request.service.js'; import { readAdminConfigJwt } from '../../services/admin-auth-config.service.js'; import { renderAuthEntrypointHtml, sendAuthHtml } from '../../services/auth-ui.service.js'; import { validateConfigFields } from '../../services/config.service.js'; const cookieName = 'uoa_account_deletion'; -const Email = z.object({ email: z.string().trim().email().max(320) }).strict(); +const Email = z.object({ rejoin: z.boolean().optional(), product: ProductId.optional(), email: z.string().trim().email().max(320) }).strict(); const Confirm = z.object({ - challengeId: z.string().uuid(), + rejoin: z.boolean().optional(), product: ProductId.optional(), challengeId: z.string().uuid(), code: z.string().regex(/^\d{6}$/), + password: z.string().min(1).max(1024).optional(), twoFactorCode: z.string().regex(/^\d{6}$/).optional(), -}).strict(); +}).strict().refine(value => !value.password || Boolean(value.product)); const startLimit = createRateLimiter({ limit: 10, windowMs: 15 * 60_000, keyBuilder: request => `account-deletion-start:${request.ip}` }); const emailLimit = createKeyedRateLimiter({ limit: 3, windowMs: 15 * 60_000 }); @@ -36,12 +40,35 @@ export function registerAccountDeletionRequestRoutes(app: FastifyInstance): void return sendAuthHtml(reply, html); }); + app.get(`${root}/receipt/:id`, { preHandler: [confirmLimit] }, async (request, reply) => { + const { id } = z.object({ id: z.string().uuid() }).parse(request.params); + const job = await getAdminPrisma().productErasureJob.findUnique({ where: { id }, select: { completedAt: true, containerPreserved: true, + receipts: { where: { outcome: 'RETAINED_EVIDENCE' }, select: { outcome: true }, take: 1 } } }); + reply.header('Cache-Control', 'no-store').header('Referrer-Policy', 'no-referrer').header('X-Robots-Tag','noindex'); + if (!job) return reply.code(404).type('text/plain').send('Receipt unavailable'); + const status = job.completedAt ? 'Deletion complete.' : 'Deletion in progress. Keep this link to check the result.'; + const details = [status, job.containerPreserved && 'The requested workspace was preserved.', + job.receipts.length > 0 && 'Restricted evidence was retained.'].filter(Boolean); + return reply.type('text/plain; charset=utf-8').send(details.join(' ')); + }); + app.get(`${root}/product/:id`, async (request, reply) => { + const { id } = z.object({ id: ProductId }).parse(request.params); + const { name, disclosure } = await enabledProduct(getAdminPrisma(), id); + return reply.header('Cache-Control', 'no-store').send({ name, disclosure }); + }); + + app.post(`${root}/submit-product`, { preHandler: [requireSameOriginBrowserRequest, confirmLimit] }, async (request, reply) => { + reply.header('Cache-Control', 'no-store'); + const input = z.object({ product: ProductId, rejoin: z.boolean().optional(), challengeId: z.string().uuid(), digest: z.string().regex(/^[a-f0-9]{64}$/), + container: z.object({ scope: z.enum(['TEAM','ORGANISATION']), id: z.string().min(1).max(256) }).strict().optional() }).strict().parse(request.body); + return submitProductErasure({ ...input, browser: request.cookies[cookieName] }); + }); app.post(`${root}/start`, { preHandler: [requireSameOriginBrowserRequest, startLimit] }, async (request, reply) => { reply.header('Cache-Control', 'no-store'); - const { email } = Email.parse(request.body); + const { email, product, rejoin } = Email.parse(request.body); emailLimit(`account-deletion-email:${email.toLowerCase()}`); const browser = randomBytes(32).toString('base64url'); - const result = await startAccountDeletionRequest(email, browser); + const result = await startAccountDeletionRequest(email, browser, product, rejoin); reply.setCookie(cookieName, browser, { path: root, httpOnly: true, sameSite: 'strict', secure: new URL(getPublicBaseUrl()).protocol === 'https:', maxAge: ACCOUNT_DELETION_PROOF_SECONDS }); return result; @@ -50,7 +77,7 @@ export function registerAccountDeletionRequestRoutes(app: FastifyInstance): void app.post(`${root}/confirm`, { preHandler: [requireSameOriginBrowserRequest, confirmLimit] }, async (request, reply) => { reply.header('Cache-Control', 'no-store'); const result = await confirmAccountDeletionRequest({ ...Confirm.parse(request.body), browser: request.cookies[cookieName] }); - reply.clearCookie(cookieName, { path: root, httpOnly: true, sameSite: 'strict', + if ('submitted' in result) reply.clearCookie(cookieName, { path: root, httpOnly: true, sameSite: 'strict', secure: new URL(getPublicBaseUrl()).protocol === 'https:' }); return result; }); diff --git a/API/src/routes/domain/deletion-jobs.ts b/API/src/routes/domain/deletion-jobs.ts index d88df14b..d77dd453 100644 --- a/API/src/routes/domain/deletion-jobs.ts +++ b/API/src/routes/domain/deletion-jobs.ts @@ -1,3 +1,6 @@ +import { normalizeDomain } from '../../utils/domain.js'; +import { getAdminPrisma } from '../../db/prisma.js'; +import { acknowledgeProductErasure } from '../../services/product-erasure.service.js'; import type { FastifyInstance } from 'fastify'; import { z } from 'zod'; import { requireDomainHashAuthForDomainQuery } from '../../middleware/domain-hash-auth.js'; @@ -6,6 +9,30 @@ import { AppError } from '../../utils/errors.js'; export function registerProductDeletionJobs(app: FastifyInstance) { const options = { preHandler: [requireDomainHashAuthForDomainQuery] }; + app.get('/domain/product-participation', options, async (request, reply) => { + const { domain, subject } = z.object({ domain: z.string(), subject: z.string().min(1).max(256) }).parse(request.query); + const db = getAdminPrisma(); + const policy = await db.productErasurePolicy.findFirst({ where: { domains: { has: normalizeDomain(domain) } }, select: { id: true } }); + if (!policy) throw new AppError('NOT_FOUND', 404); + const job = await db.productErasureJob.findFirst({ where: { policyId: policy.id, OR: [{ subject }, { rejoinedSubject: subject }] }, + orderBy: { createdAt: 'desc' }, select: { id: true, rejoinedAt: true } }); + return reply.header('Cache-Control', 'no-store').send({ product: policy.id, active: !job || Boolean(job.rejoinedAt), generation: job?.id ?? 'initial' }); + }); + app.get('/domain/product-erasure-jobs', options, async request => { + if (!request.domainAuthClientDomainId) throw new AppError('UNAUTHORIZED', 401); + const { after } = z.object({ after: z.string().uuid().optional() }).parse(request.query); + const rows = await getAdminPrisma().productErasureReceipt.findMany({ where: { domainId: request.domainAuthClientDomainId, + acknowledgedAt: null, ...(after && { jobId: { gt: after } }) }, select: { job: { select: { id: true, revision: true, subject: true, policyId: true, impact: true } } }, + orderBy: { jobId: 'asc' }, take: 101 }); + return { data: rows.slice(0, 100).map(row => row.job), next: rows.length > 100 ? rows[99].job.id : null }; + }); + app.post('/domain/product-erasure-jobs/:id/acknowledge', options, async request => { + const { id } = z.object({ id: z.string().uuid() }).parse(request.params); + const { domain } = z.object({ domain: z.string() }).parse(request.query); + const body = z.object({ outcome: z.enum(['PURGED','RETAINED_EVIDENCE']), revision: z.number().int().positive() }).strict().parse(request.body); + if (!request.domainAuthClientId) throw new AppError('UNAUTHORIZED', 401); + return acknowledgeProductErasure({ ...body, id, domain, token: request.domainAuthClientId }); + }); app.get('/domain/deletion-jobs', options, async request => { if (!request.domainAuthClientDomainId) throw new AppError('UNAUTHORIZED', 401); return { data: await productDeletionJobs(request.domainAuthClientDomainId) }; diff --git a/API/src/routes/internal/admin/lifecycle.ts b/API/src/routes/internal/admin/lifecycle.ts index 164a35d5..c4db834d 100644 --- a/API/src/routes/internal/admin/lifecycle.ts +++ b/API/src/routes/internal/admin/lifecycle.ts @@ -1,3 +1,5 @@ +import { reviewContainer } from '../../../services/product-erasure-containers.service.js'; +import { ProductPolicyInput, saveProductErasurePolicy } from '../../../services/product-erasure-policy.service.js'; import type { FastifyInstance, FastifyRequest } from 'fastify'; import { z } from 'zod'; import { getAdminPrisma } from '../../../db/prisma.js'; @@ -17,6 +19,22 @@ function actor(request: FastifyRequest) { } export function registerInternalAdminLifecycle(app: FastifyInstance) { + app.get('/internal/admin/product-erasure', options, async request => { + const { after } = z.object({ after: z.string().uuid().optional() }).parse(request.query); + const db = getAdminPrisma(); + const rows = await db.productErasureJob.findMany({ where: { completedAt: null }, + orderBy: [{ createdAt: 'asc' }, { id: 'asc' }], take: 101, ...(after && { cursor: { id: after }, skip: 1 }), + select: { id: true, policyId: true, createdAt: true, containerJobId: true, requestedContainer: true, + receipts: { select: { domainId: true, acknowledgedAt: true } } } }); + return { policies: await db.productErasurePolicy.findMany({ orderBy: { id: 'asc' } }), + pending: rows.slice(0, 100), next: rows.length > 100 ? rows[99].id : null }; + }); + app.post('/internal/admin/product-erasure/:id/container', options, request => { + const { id } = z.object({ id: z.string().uuid() }).parse(request.params); + const { decision } = z.object({ decision: z.enum(['approve','preserve']) }).strict().parse(request.body); + return reviewContainer(id, decision, actor(request)); + }); + app.post('/internal/admin/product-erasure', options, request => saveProductErasurePolicy(ProductPolicyInput.parse(request.body), actor(request))); app.get('/internal/admin/lifecycle/templates', options, async () => ({ data: await getAdminPrisma().lifecycleReasonTemplate.findMany({ orderBy: [{ scope: 'asc' }, { title: 'asc' }] }) })); app.post('/internal/admin/lifecycle/templates', options, async request => { const body = z.object({ id: z.string().optional(), scope: Scope, title: z.string().trim().min(1).max(120), diff --git a/API/src/routes/root/index.ts b/API/src/routes/root/index.ts index 1f0291d1..f51e6937 100644 --- a/API/src/routes/root/index.ts +++ b/API/src/routes/root/index.ts @@ -82,7 +82,7 @@ export function registerRootRoute(app: FastifyInstance): void { personal_owner_membership: 'optional owner_subject in service assertion; exact-team ownerActive or owner_inactive', prepaid_delivery: '/apps/v1/nessie/phone-profile/call-proof/reserve', caller_id_authentication: false }, settings_events: { path: '/oauth/me/settings/:namespace/:key/events', transport: 'WebSocket', scope: 'settings.read', protocol_version: 1, recovery: 'snapshot on reconnect; version-fenced splice or replace deltas' }, - account_deletion: { form: '/auth/delete-account', start: '/auth/delete-account/start', confirm: '/auth/delete-account/confirm', + account_deletion: { product_form: '/auth/delete-account?product=', product_confirmation: '/auth/delete-account/submit-product', rejoin: '/auth/delete-account?product=&action=rejoin', participation: '/domain/product-participation', product_jobs: '/domain/product-erasure-jobs', form: '/auth/delete-account', start: '/auth/delete-account/start', confirm: '/auth/delete-account/confirm', authority: 'browser-bound mailbox proof and enrolled TOTP; queues a global account request for administrator review' }, native_apps: { admin: '/admin/apps', registration: '/oauth/register', public_identifier: 'app_id', client_secret_required: false }, enterprise_sso: { version: 1, settings: '/auth/organisation-access', diff --git a/API/src/routes/root/llm.ts b/API/src/routes/root/llm.ts index 4a20580c..0688e8a5 100644 --- a/API/src/routes/root/llm.ts +++ b/API/src/routes/root/llm.ts @@ -66,6 +66,7 @@ ${llmIntroMarkdown}\n## Admin activity and directory reads\nGET /internal/admin/ Organisation labels reserve one global namespace across founding domains. Existing ambiguous labels remain blocked without renames. Availability is advisory; database admission also covers concurrent creation and explicit address changes. Team labels remain scoped to their organisation. ## Account deletion requests +For product-only deletion, open /auth/delete-account?product=. Unknown or disabled products fail closed. The hosted proof is bound to the product and returns an impact preview. Confirm only the exact digest with /auth/delete-account/submit-product. Consumer backends poll /domain/product-erasure-jobs with their own registered domain bearer, remove personal product data across contexts, and acknowledge the assigned revision only after cleanup commits. Contexts describe shared organisation history, never permission to delete a container; only a separately issued entity deletion job authorizes that. Use the returned receipt for status after sign-out. For a deliberate fresh registration use the same form with action=rejoin after completion and the credential expiry window. Record /domain/product-participation's generation at fresh registration, and compare it on session use, provisioning and sync. Reject inactive participation and stale generations. A positive participation result conveys no identity or membership authority. Open /auth/delete-account in the system browser without app credentials or profile parameters. The first-party form verifies the account email and enrolled authenticator before queuing the request. No login session is issued. Platform superusers find verified requests in Admin → Users → Deletion requested and process them through the existing USER deletion preview and job. The account stays usable until the operator starts deletion. ## Team sessions without a browser\nA product holding a proof-bearing sign-in calls POST /auth/token with grant_type urn:unlikeotherai:params:oauth:grant-type:team-session, refresh_token, organization_id and team_id to get a separate session for another of the person's teams. The presented family is left untouched. UOA judges the target against the original sign-in (membership, product policy, 2FA, the organisation's sign-in policy) and the new proof never outlives that original. 403 INTERACTION_REQUIRED means sign in for that team; 401 INVALID_REFRESH_TOKEN means the sign-in ended. See /api team_session and Docs/Auth/enterprise-sso.md.\n\n## Directory change notifications\nUOA delivers reference-only person.changed webhooks using a dedicated per-product HMAC secret. Resolve affected ids through the existing GET /org/organisations/:orgId/teams/:teamId/members?subject_ids=&status=all&limit=100 API and original-assurance actor proof. GET /org/organisations/:orgId/teams/:teamId/people/:userId/avatar uses the same authority for the exact person picture, including people new to the product. See Docs/Auth/directory-webhooks.md.\n\n## Ledger runtime-key operators\nCurrent admin-domain SUPERUSER operators use Admin Billing > Product billing > selected product > Ledger runtime keys. GET /internal/admin/billing/ledger-runtime-keys returns only product/source/audience/prefix/id/time/revocation metadata. POST the same path with {product,source_domain,ledger_audience} issues a one-time secret bound to an active product, original config hostname and exact HTTPS Ledger origin. POST /internal/admin/billing/ledger-runtime-keys/:keyId/revoke revokes that exact key. All responses are no-store. The UI keeps plaintext only in the mounted dialog, outside storage, URLs and query caches, and clears it on close/navigation/sign-out. It never installs the key, creates a bootstrap credential or expands delegation permissions. Lost-response issuance may still have committed: inspect metadata and revoke unused keys before retrying.\n${llmBillingModesMarkdown} diff --git a/API/src/routes/root/schema.lifecycle.ts b/API/src/routes/root/schema.lifecycle.ts index d1a99a82..6acd25e4 100644 --- a/API/src/routes/root/schema.lifecycle.ts +++ b/API/src/routes/root/schema.lifecycle.ts @@ -3,9 +3,18 @@ import type { EndpointSchema } from './schema.js'; const accessStatusNotes = 'Optional diagnostics: AUTH_ACCESS_STATUS_ENABLED=true on the auth server is required. False/unset returns404 before config/client/mail/proof work, including outstanding proof redemption.'; export const lifecycleEndpoints: EndpointSchema[] = [ - { method: 'GET', path: '/auth/delete-account', description: 'Open the first-party global account-deletion request form', response: { 200: 'HTML; no-store' } }, - { method: 'POST', path: '/auth/delete-account/start', description: 'Send a neutral mailbox code and bind the ten-minute challenge to the current browser', auth: 'same-origin browser; rate limited', body: { email: 'account email' }, response: { challengeId: 'opaque UUID; HttpOnly SameSite=Strict cookie set' } }, - { method: 'POST', path: '/auth/delete-account/confirm', description: 'Verify and record a global account-deletion request for operator review', auth: 'same browser cookie, one-use mailbox code, enrolled TOTP and current credential epoch', body: { challengeId: 'UUID', code: 'six digits', twoFactorCode: 'six digits if enrolled' }, response: { submitted: 'true; no session issued' }, notes: 'A duplicate verified request preserves the existing queue time. Only the normal platform-admin deletion workflow can start erasure.' }, + { method: 'GET', path: '/auth/delete-account/product/:id', description: 'Read the enabled product name and retention disclosure for a hosted product deletion', response: { name: 'product name', disclosure: 'operator text' } }, + { method: 'POST', path: '/auth/delete-account/submit-product', auth: 'same-origin browser and verified product-bound mailbox challenge with enrolled TOTP', body: { rejoin: 'true only for explicit fresh registration', product: 'registered policy id', challengeId: 'UUID', digest: 'exact preview digest', container: 'optional exact previewed {scope,id}' }, description: 'Confirm the reviewed product footprint and obtain a status receipt', response: { receipt: 'opaque UUID', complete: 'boolean' } }, + { method: 'GET', path: '/auth/delete-account/receipt/:id', auth: 'opaque receipt capability', description: 'Read deletion progress without signing back in', response: { 200: 'plain text status only' } }, + { method: 'GET', path: '/internal/admin/product-erasure', auth: 'platform superuser', description: 'List product policies and outstanding deletion receipts' }, + { method: 'POST', path: '/internal/admin/product-erasure/:id/container', auth: 'current platform superuser and pending exact person consent', body: { decision: 'approve or preserve' }, description: 'Recheck membership and dependencies and start the exact requested entity cleanup, or preserve the container' }, + { method: 'POST', path: '/internal/admin/product-erasure', auth: 'platform superuser', body: { id: 'logical product identifier', revision: 'current revision, zero for new', mode: 'PERSONAL or ORGANISATION', name: 'product label', disclosure: 'retention, timing and billing disclosure', enabled: 'boolean', domains: 'registered backend domains', nativeApps: 'registered native identifiers', settings: 'exact namespace/key pairs' }, description: 'Create or revise a product account deletion policy' }, + { method: 'GET', path: '/domain/product-participation', auth: 'exact registered domain bearer', query: { domain: 'assigned domain', subject: 'independently authenticated UOA subject' }, description: 'Compare the saved product registration generation before accepting access or sync writes', response: { product: 'policy id', active: 'boolean', generation: 'initial or new registration id' } }, + { method: 'GET', path: '/domain/product-erasure-jobs', auth: 'exact registered domain bearer', query: { domain: 'assigned domain', after: 'optional next cursor' }, description: 'Pull pending product-person erasures for this backend only', response: { data: 'id, revision, subject, policyId, frozen impact' } }, + { method: 'POST', path: '/domain/product-erasure-jobs/:id/acknowledge', auth: 'exact registered domain bearer', query: { domain: 'assigned domain' }, body: { revision: 'exact issued revision', outcome: 'PURGED or RETAINED_EVIDENCE' }, description: 'Acknowledge committed product cleanup; exact retries are idempotent' }, + { method: 'GET', path: '/auth/delete-account', query: { action: 'optional rejoin for a new registration', product: 'optional exact product policy identifier' }, description: 'Open the first-party global or exact product account-deletion form', response: { 200: 'HTML; no-store' } }, + { method: 'POST', path: '/auth/delete-account/start', description: 'Send a neutral mailbox code and bind the ten-minute challenge to the current browser', auth: 'same-origin browser; rate limited', body: { email: 'account email', rejoin: 'optional true for fresh registration', product: 'optional product policy id' }, response: { challengeId: 'opaque UUID; HttpOnly SameSite=Strict cookie set' } }, + { method: 'POST', path: '/auth/delete-account/confirm', description: 'Verify and queue a global request, or return a bound product preview', auth: 'same browser cookie, one-use mailbox code, enrolled TOTP and current credential epoch', body: { password: 'optional independent UOA password for managed product accounts', rejoin: 'same action as start', product: 'same optional product policy id as start', challengeId: 'UUID', code: 'six digits', twoFactorCode: 'six digits if enrolled' }, response: { submitted: 'true for global requests', impact: 'product footprint for product requests', digest: 'product confirmation digest' }, notes: 'A duplicate verified request preserves the existing queue time. Global requests require platform-admin review. Product erasure requires a separate preview confirmation.' }, { method: 'POST', path: '/org/organisations/:orgId/teams/:teamId/archive', auth: 'registered domain bearer, verified config, fresh exact-team human assertion and live org teams.manage capability', query: { domain: 'registered product domain', config_url: 'signed product config URL' }, diff --git a/API/src/services/account-deletion-request.service.ts b/API/src/services/account-deletion-request.service.ts index 48decacd..17ac1675 100644 --- a/API/src/services/account-deletion-request.service.ts +++ b/API/src/services/account-deletion-request.service.ts @@ -1,3 +1,9 @@ +import { rejoinPreview, resumeProduct } from './product-rejoin.service.js'; +import { verifyPassword } from './password.service.js'; +import { assertMailboxCredentialAdmission } from './credential-admission.service.js'; +import { lockEnterpriseOutbox } from './org-sso-revocation.service.js'; +import { commitProductErasure, enabledProduct, productImpact } from './product-erasure.service.js'; +import { lockProductTeamPolicyExclusive } from './product-team-policy-lock.service.js'; import { randomInt, randomUUID, timingSafeEqual } from 'node:crypto'; import { getEnv, getPublicBaseUrl } from '../config/env.js'; @@ -29,13 +35,31 @@ function matchesHash(expected: string | null, actual: string) { && timingSafeEqual(Buffer.from(expected), Buffer.from(actual)); } -export async function startAccountDeletionRequest(email: string, browser: string) { +function factorDigest(id: string, user: { userKey: string | null; twoFaEnabled: boolean; twoFaSecret: string | null; passwordHash: string | null }, passwordVerified = false) { + return hashEmailToken(JSON.stringify([id, user.userKey, user.twoFaEnabled, user.twoFaSecret, passwordVerified, passwordVerified ? user.passwordHash : null]), getEnv().SHARED_SECRET); +} + +function requestUrl(product?: string, rejoin = false) { + const url = new URL(ACCOUNT_DELETION_PATH, getPublicBaseUrl()); + if (product) url.searchParams.set('product', product); + if (rejoin) { + if (!product) throw new AppError('BAD_REQUEST', 400); + url.searchParams.set('action', 'rejoin'); + } + return url.href; +} + +export async function startAccountDeletionRequest(email: string, browser: string, product?: string, rejoin = false) { const startedAt = Date.now(); const challengeId = randomUUID(); const code = randomInt(0, 1_000_000).toString().padStart(6, '0'); const identity = buildUserIdentity({ email, userScope: 'global' }); - const configUrl = new URL(ACCOUNT_DELETION_PATH, getPublicBaseUrl()).href; + const configUrl = requestUrl(product, rejoin); + const policy = product ? await enabledProduct(getAdminPrisma(), product) : null; const recipient = await getAdminPrisma().$transaction(async tx => { + // This form proves a global SSO identity. If the product has a distinct + // per-domain identity for this mailbox, never substitute the global subject. + if (policy?.domains.length && await tx.user.count({ where: { email: identity.email, domain: { in: policy.domains } } })) return null; const found = await tx.user.findUnique({ where: { userKey: identity.userKey }, select: { id: true } }); if (!found) return null; await lockRefreshSessionUser(found.id, { prisma: tx }); @@ -60,14 +84,14 @@ export async function startAccountDeletionRequest(email: string, browser: string // Use the same visible mail and response for addresses with no matching account. A code // for such an address is never backed by a challenge and cannot verify. await sendActionVerificationEmail({ to: recipient ?? identity.email, code, - domain: new URL(configUrl).hostname, description: 'Confirm an UnlikeOtherAI account deletion request' }) + domain: new URL(configUrl).hostname, description: rejoin ? `Confirm fresh registration for ${policy?.name}` : policy ? `Review deletion of your ${policy.name} product account` : 'Confirm an UnlikeOtherAI account deletion request' }) .catch(() => undefined); await new Promise(resolve => setTimeout(resolve, Math.max(0, 250 - (Date.now() - startedAt)))); return { challengeId }; } export async function confirmAccountDeletionRequest(input: { - challengeId: string; browser: string | undefined; code: string; twoFactorCode?: string; + challengeId: string; browser: string | undefined; code: string; twoFactorCode?: string; password?: string; product?: string; rejoin?: boolean; }) { const { browser, challengeId, code, twoFactorCode } = input; const failed = () => new AppError('UNAUTHORIZED', 401, 'AUTHENTICATION_FAILED'); @@ -79,7 +103,8 @@ export async function confirmAccountDeletionRequest(input: { const token = await tx.verificationToken.findUnique({ where: { id: challengeId } }); const user = await tx.user.findUnique({ where: { id: candidate.userId } }); const now = new Date(); - if (!token || token.type !== proofType || token.usedAt || token.expiresAt <= now || token.attemptCount >= 5 + const url = requestUrl(input.product, input.rejoin); + if (!token || token.configUrl !== url || token.type !== proofType || token.usedAt || token.expiresAt <= now || token.attemptCount >= 5 || !user?.email || user.domain !== null || user.userKey !== token.userKey || !eligibleStatuses.some(status => status === user.lifecycleStatus) || user.tokenVersion !== token.tokenVersion || !matchesHash(token.actionDigest, browserHash(token.id, browser))) return false; @@ -98,11 +123,54 @@ export async function confirmAccountDeletionRequest(input: { }, data: { twoFaLastAcceptedCounter: counter } }); if (consumed.count !== 1) return false; } + if (input.product) { + const policy = await enabledProduct(tx, input.product); + const passwordVerified = Boolean(input.password && user.passwordHash) && await verifyPassword(input.password ?? '', user.passwordHash); + if (input.password && !passwordVerified) return false; + if (!user.twoFaEnabled && !passwordVerified) await assertMailboxCredentialAdmission(user.id, tx); + const preview = input.rejoin ? await rejoinPreview(tx, user.id, policy) : await productImpact(tx, user.id, policy); + await tx.verificationToken.update({ where: { id: token.id }, data: { usedAt: now, productPreviewDigest: preview.digest, productFactorDigest: factorDigest(token.id, user, passwordVerified) } }); + return preview; + } await tx.verificationToken.update({ where: { id: token.id }, data: { usedAt: now } }); await tx.user.updateMany({ where: { id: user.id, accountDeletionRequestedAt: null }, data: { accountDeletionRequestedAt: now } }); return true; }); if (!confirmed) throw failed(); - return { submitted: true }; + return confirmed === true ? { submitted: true } : confirmed; +} + +export async function submitProductErasure(input: { product: string; challengeId: string; digest: string; rejoin?: boolean; container?: import('./product-erasure-containers.service.js').Container; browser?: string }) { + if (!input.browser) throw new AppError('UNAUTHORIZED', 401); + const browser = input.browser; + return getAdminPrisma().$transaction(async tx => { + await lockEnterpriseOutbox(tx); + await lockProductTeamPolicyExclusive(tx); + const token = await tx.verificationToken.findUnique({ where: { id: input.challengeId } }); + const url = requestUrl(input.product, input.rejoin); + if (!token?.userId || token.type !== proofType || token.configUrl !== url || !token.usedAt || + !matchesHash(token.actionDigest, browserHash(token.id, browser)) || token.productPreviewDigest !== input.digest) { + throw new AppError('UNAUTHORIZED', 401); + } + await lockRefreshSessionUser(token.userId, { prisma: tx }); + const user = await tx.user.findUnique({ where: { id: token.userId } }); + if (!user || !eligibleStatuses.some(s => s === user.lifecycleStatus) || user.tokenVersion !== token.tokenVersion || + token.expiresAt <= new Date()) throw new AppError('UNAUTHORIZED', 401); + const passwordVerified = Boolean(user.passwordHash) && matchesHash(token.productFactorDigest, factorDigest(token.id, user, true)); + if (!passwordVerified && !matchesHash(token.productFactorDigest, factorDigest(token.id, user))) throw new AppError('UNAUTHORIZED', 401); + if (!user.twoFaEnabled && !passwordVerified) await assertMailboxCredentialAdmission(user.id, tx); + if (input.rejoin && input.container) throw new AppError('BAD_REQUEST', 400); + const selection = JSON.stringify(input.container ? [input.container.scope, input.container.id] : []); + if (token.productReceiptId) { + if (token.productSelection !== selection) throw new AppError('BAD_REQUEST', 409, 'DELETION_RETRY_MISMATCH'); + const job = await tx.productErasureJob.findUniqueOrThrow({ where: { id: token.productReceiptId } }); + return { receipt: job.id, complete: Boolean(job.completedAt) }; + } + const policy = await enabledProduct(tx, input.product); + const result = input.rejoin ? await resumeProduct(tx, user.id, policy, input.digest) + : await commitProductErasure(tx, user.id, policy, input.digest, input.container); + await tx.verificationToken.update({ where: { id: token.id }, data: { productReceiptId: result.receipt, productSelection: selection } }); + return result; + }, { isolationLevel: 'Serializable' }); } diff --git a/API/src/services/billing-service-access.service.ts b/API/src/services/billing-service-access.service.ts index 6f71f80a..f70d35f2 100644 --- a/API/src/services/billing-service-access.service.ts +++ b/API/src/services/billing-service-access.service.ts @@ -3,6 +3,7 @@ import { createHash } from 'node:crypto'; import { getAdminPrisma } from '../db/prisma.js'; import { AppError } from '../utils/errors.js'; +import { assertProductParticipation } from './product-participation.service.js'; import { verifyBillingActor } from './billing-actor.service.js'; import type { BillingActorEndpoint } from './billing-actor-audience.service.js'; import type { VerifiedBillingAppKey } from './billing-app-key.service.js'; @@ -90,6 +91,10 @@ export async function confirmAuthenticatedDirectBillingServiceAccess( const confirmedAt = deps?.now?.() ?? new Date(); await prisma.$transaction( async (tx) => { + const issuer = new URL(params.credential.actorIssuer); + if (issuer.protocol === 'https:' && issuer.pathname === '/' && !issuer.port && !issuer.search && !issuer.hash) { + await assertProductParticipation(tx, request.userId, issuer.hostname); + } const [service, orgMember, team] = await Promise.all([ tx.billingService.findFirst({ where: { @@ -136,7 +141,9 @@ export async function confirmAuthenticatedDirectBillingServiceAccess( { prisma: tx, now: () => confirmedAt }, ); }, - { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead }, + // A concurrent product erasure reads and removes this same access record. + // Serializing both transactions prevents an in-flight confirmation from restoring it. + { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, ); } diff --git a/API/src/services/credential-route-registry.service.ts b/API/src/services/credential-route-registry.service.ts index cd379a3a..ae53ead1 100644 --- a/API/src/services/credential-route-registry.service.ts +++ b/API/src/services/credential-route-registry.service.ts @@ -1,3 +1,4 @@ +import { assertProductParticipation } from './product-participation.service.js'; import { assertCredentialArtifactProof, type CredentialArtifactSource } from './credential-artifact.service.js'; import { assertIndependentSourceStillAdmitted } from './credential-admission.service.js'; import type { Prisma, PrismaClient } from '@prisma/client'; @@ -36,13 +37,14 @@ export type CredentialSurface = keyof typeof credentialRouteRegistry; type Db = PrismaClient | Prisma.TransactionClient; export type CredentialAuthorityInput = { userId: string; clientDomain: string; credentialEpoch: number; orgId?: string | null; teamId?: string | null; - assuranceId?: string; assuranceReference?: string; authenticationEvidenceId?: string; method?: string; + nativeApp?: string; assuranceId?: string; assuranceReference?: string; authenticationEvidenceId?: string; method?: string; allowConsumedEvidence?: boolean; artifact?: CredentialArtifactSource; }; function denied(): never { throw new AppError('FORBIDDEN', 403, 'INDEPENDENT_REAUTH_REQUIRED'); } /** Invoke only after the artifact's signature/purpose/browser binding has been verified. */ export async function authorizeCredentialSurface(surface: CredentialSurface, input: CredentialAuthorityInput, db: Db) { + await assertProductParticipation(db, input.userId, input.clientDomain, input.nativeApp); const rule = credentialRouteRegistry[surface]; if (!rule) denied(); const familySource = Boolean(input.assuranceId || input.assuranceReference); if ((familySource && input.authenticationEvidenceId) || (familySource && rule.source === 'evidence') || diff --git a/API/src/services/domain-role.service.ts b/API/src/services/domain-role.service.ts index 265553af..1ae181e5 100644 --- a/API/src/services/domain-role.service.ts +++ b/API/src/services/domain-role.service.ts @@ -1,3 +1,4 @@ +import { assertProductParticipation } from './product-participation.service.js'; import type { DomainRole, PrismaClient, UserRole } from '@prisma/client'; import type { Prisma } from '@prisma/client'; @@ -64,6 +65,7 @@ export async function ensureDomainRoleForUser(params: { if (!domain) throw new AppError('BAD_REQUEST', 400); if (!params.userId) throw new AppError('BAD_REQUEST', 400); + const bootstrapClosed = await assertProductParticipation(prisma, params.userId, domain); const existing = await prisma.domainRole.findUnique({ where: { domain_userId: { domain, userId: params.userId } }, }); @@ -73,7 +75,7 @@ export async function ensureDomainRoleForUser(params: { where: { domain, role: 'SUPERUSER' }, select: { userId: true }, }); - const role: UserRole = existingSuperuser || params.allowBootstrap === false ? 'USER' : 'SUPERUSER'; + const role: UserRole = existingSuperuser || bootstrapClosed || params.allowBootstrap === false ? 'USER' : 'SUPERUSER'; return await prisma.domainRole.create({ data: { domain, userId: params.userId, role }, diff --git a/API/src/services/email.service.ts b/API/src/services/email.service.ts index 0c9f85e5..71cd5b21 100644 --- a/API/src/services/email.service.ts +++ b/API/src/services/email.service.ts @@ -44,6 +44,14 @@ export async function sendRegistrationVerificationEmail(params: { }); } +export async function sendProductDeletionEmail(to: string, product: string, receiptUrl: string): Promise { + const env = getEnv(); + await dispatchEmail({ to, from: env.EMAIL_FROM, replyTo: env.EMAIL_REPLY_TO, subject: 'Product account deletion complete', + text: 'Your account deletion for ' + product + ' has finished. You can check the result at ' + receiptUrl, + suppressContentLog: true, + }, { swallowFailures: false }); +} + export async function sendActionVerificationEmail(params: { to: string; code: string; domain: string; description: string; theme?: Partial; }): Promise { diff --git a/API/src/services/entity-deletion-job.service.ts b/API/src/services/entity-deletion-job.service.ts index addf77d5..7053c9f1 100644 --- a/API/src/services/entity-deletion-job.service.ts +++ b/API/src/services/entity-deletion-job.service.ts @@ -16,7 +16,7 @@ export async function getDeletionPreview(scope: LifecycleScope, id: string, mode return previewEntityDeletion(getAdminPrisma(), scope, id, mode); } -async function markDeleting(tx: PrismaClient, preview: DeletionPreview) { +export async function markDeleting(tx: PrismaClient, preview: DeletionPreview) { const data = { lifecycleStatus: 'DELETING' as const, lifecycleChangedAt: new Date() }; if (preview.scope === 'USER') { await protectLastAdmin(tx, preview.targetId); diff --git a/API/src/services/entity-deletion-preview.service.ts b/API/src/services/entity-deletion-preview.service.ts index 146968f9..b39c6a25 100644 --- a/API/src/services/entity-deletion-preview.service.ts +++ b/API/src/services/entity-deletion-preview.service.ts @@ -132,6 +132,9 @@ export async function previewEntityDeletion(tx: PrismaClient, scope: LifecycleSc blockers.push(...await activeBillingBlockers(tx, effectiveScope, effectiveTargetId)); for (const candidate of candidates.filter(c => c.eligible)) blockers.push(...await activeBillingBlockers(tx, 'USER', candidate.id)); if (scope === 'USER' && await tx.organisation.count({ where: { ownerId: id, lifecycleStatus: { not: 'DELETED' } } })) blockers.push('Transfer ownership of every retained organisation before deleting this account.'); + if (scope === 'USER' && await tx.productErasureJob.count({ where: { subject: id, completedAt: null } })) { + blockers.push('Finish pending product account erasure before removing its subject.'); + } const evidence = await retainedEvidence(tx, effectiveScope, effectiveTargetId); for (const teamId of teamIds.filter(teamId => effectiveScope !== 'TEAM' || teamId !== effectiveTargetId)) evidence.push(...await retainedEvidence(tx, 'TEAM', teamId)); for (const userId of candidateIds.filter(userId => effectiveScope !== 'USER' || userId !== effectiveTargetId)) evidence.push(...await retainedEvidence(tx, 'USER', userId)); diff --git a/API/src/services/entity-deletion-sweep.service.ts b/API/src/services/entity-deletion-sweep.service.ts index 36d20ab7..7abd43ae 100644 --- a/API/src/services/entity-deletion-sweep.service.ts +++ b/API/src/services/entity-deletion-sweep.service.ts @@ -16,6 +16,10 @@ export async function eraseOperationalIdentity(tx: PrismaClient, userId: string, if (await tx.organisation.count({ where: { ownerId: userId, lifecycleStatus: { not: 'DELETED' } } })) { throw new AppError('BAD_REQUEST', 409, 'OWNERSHIP_TRANSFER_REQUIRED'); } + if (await tx.productErasureJob.count({ where: { subject: userId, completedAt: null } })) { + throw new AppError('BAD_REQUEST', 409, 'PRODUCT_ERASURE_PENDING'); + } + await tx.productErasureJob.deleteMany({ where: { OR: [{ subject: userId }, { rejoinedSubject: userId }] } }); const email = user.email; if (mode === 'RETAIN_REFERENCE') { const domains = new Set([ diff --git a/API/src/services/machine-authority.service.ts b/API/src/services/machine-authority.service.ts index fb4f7deb..8abac589 100644 --- a/API/src/services/machine-authority.service.ts +++ b/API/src/services/machine-authority.service.ts @@ -1,3 +1,4 @@ +import { assertProductParticipation } from './product-participation.service.js'; import type { MachineAuthorization, MachineEnrollment, PrismaClient } from '@prisma/client'; import { getAdminPrisma } from '../db/prisma.js'; import { runInTransaction } from '../db/tenant-context.js'; @@ -74,6 +75,7 @@ export async function stopMachine(row: MachineEnrollment, status: string, reason /** This checks MACHINE authority. It never revalidates or changes a human refresh family. */ export async function machineAdmission(row: MachineEnrollment, auth: MachineAuthorization, credentialExpiresAt: Date, tx: MachineDb) { + await assertProductParticipation(tx, row.subject, row.clientDomain); const now = await machineClock(tx); let reason: MachineReasonCode | undefined; let status = 'revoked'; diff --git a/API/src/services/oauth/account.service.ts b/API/src/services/oauth/account.service.ts index bf72b083..2a791634 100644 --- a/API/src/services/oauth/account.service.ts +++ b/API/src/services/oauth/account.service.ts @@ -43,10 +43,11 @@ export async function authorizePublicAccount( surface: 'public_access' | 'kelpie_connect' | 'kelpie_pair' = 'public_access', ): Promise { await lockProductTeamPolicyShared(prisma); - if (!await getOAuthClient(account.clientId, prisma)) throw new AppError('UNAUTHORIZED', 401, 'AUTHENTICATION_FAILED'); + const client = await getOAuthClient(account.clientId, prisma); + if (!client) throw new AppError('UNAUTHORIZED', 401, 'AUTHENTICATION_FAILED'); await lockAndAssertAuthenticationEpoch(account, { prisma }); if (account.expiresAt <= Date.now() / 1000) throw new AppError('UNAUTHORIZED', 401, 'AUTHENTICATION_FAILED'); - await authorizeCredentialSurface(surface, { userId: account.userId, clientDomain: account.domain, + await authorizeCredentialSurface(surface, { userId: account.userId, clientDomain: account.domain, nativeApp: client.nativeApp?.identifier, credentialEpoch: account.credentialEpoch, assuranceId: account.assuranceId, authenticationEvidenceId: account.authenticationEvidenceId, allowConsumedEvidence: true, artifact: account.artifact }, prisma); const user = await prisma.user.findUnique({ where: { lifecycleStatus: 'ACTIVE', id: account.userId }, select: { twoFaEnabled: true } }); diff --git a/API/src/services/oauth/embedded-kelpie.service.ts b/API/src/services/oauth/embedded-kelpie.service.ts index 1b746637..78fc5a61 100644 --- a/API/src/services/oauth/embedded-kelpie.service.ts +++ b/API/src/services/oauth/embedded-kelpie.service.ts @@ -14,7 +14,7 @@ import { assertEmailDomainAllowedForLogin } from '../login-domain-policy.service import { lockSignaturePolicyForDecision } from '../signature-policy-lock.service.js'; import { evaluateSignaturePolicy } from '../signature-policy.service.js'; import { getAccessTokenPublicJwks, signEmbeddedKelpieToken } from './access-token.service.js'; -import { kelpieConnectResource, KELPIE_TICKET_TTL_SECONDS } from './kelpie-connect-policy.js'; +import { KELPIE_APP_ID, kelpieConnectResource, KELPIE_TICKET_TTL_SECONDS } from './kelpie-connect-policy.js'; const SCOPES = 'profile email settings.read settings.write kelpie.connect'; const Claims = z.object({ @@ -36,7 +36,7 @@ export async function authorizeEmbeddedKelpieAccount(account: EmbeddedKelpieAuth if (account.domain !== new URL(resource).host || account.exp <= Date.now() / 1000) reject(); await lockTokenIssuanceProductPolicy({ clientDomainId: account.client_domain_id, domain: account.domain }, { prisma: tx }); await lockAndAssertAuthenticationEpoch({ userId: account.sub, domain: account.domain, credentialEpoch: account.tv }, { prisma: tx }); - const binding = { userId: account.sub, clientDomain: account.domain, credentialEpoch: account.tv, + const binding = { nativeApp: KELPIE_APP_ID, userId: account.sub, clientDomain: account.domain, credentialEpoch: account.tv, orgId: account.org_id, teamId: account.team_id, assuranceId: account.assurance_id }; // Global profile/settings require independent original proof, including its live family and ancestors. await authorizeCredentialSurface('configured_access', binding, tx); diff --git a/API/src/services/oauth/native-refresh.service.ts b/API/src/services/oauth/native-refresh.service.ts index 9a81db1c..a89e6bb9 100644 --- a/API/src/services/oauth/native-refresh.service.ts +++ b/API/src/services/oauth/native-refresh.service.ts @@ -151,7 +151,7 @@ async function rotateNativeRefreshToken( const issuer = getPublicBaseUrl(); const source = await authorizeCredentialSurface('native_refresh', { userId: rotated.userId, - clientDomain: config.domain, credentialEpoch, assuranceId: rotated.assuranceId ?? undefined }, tx); + clientDomain: config.domain, nativeApp: client.nativeApp?.identifier, credentialEpoch, assuranceId: rotated.assuranceId ?? undefined }, tx); const ttlSeconds = publicCredentialTtl(accessTokenExpiresInSeconds(getEnv().ACCESS_TOKEN_TTL), source?.expiresAt); const accessToken = await signMcpAccessToken({ subject: rotated.userId, diff --git a/API/src/services/oauth/token-exchange.service.ts b/API/src/services/oauth/token-exchange.service.ts index 0dc5edaf..43b31e15 100644 --- a/API/src/services/oauth/token-exchange.service.ts +++ b/API/src/services/oauth/token-exchange.service.ts @@ -92,7 +92,7 @@ export async function exchangeOAuthCodeForAccessToken( }); const evidence = await authorizeCredentialSurface('public_authorization', { userId: consumed.userId, - clientDomain: params.domain, credentialEpoch: consumed.credentialEpoch, + clientDomain: params.domain, nativeApp: client.nativeApp?.identifier, credentialEpoch: consumed.credentialEpoch, authenticationEvidenceId: consumed.authenticationEvidenceId }, prisma); const refresh = isNativeRefreshClient(client) ? await issueNativeRefreshToken({ userId: consumed.userId, clientId: params.clientId, domain: params.domain, credentialEpoch: consumed.credentialEpoch, diff --git a/API/src/services/product-erasure-containers.service.ts b/API/src/services/product-erasure-containers.service.ts new file mode 100644 index 00000000..caf72752 --- /dev/null +++ b/API/src/services/product-erasure-containers.service.ts @@ -0,0 +1,106 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { normalizeDomain } from '../utils/domain.js'; +import { getEnv } from '../config/env.js'; +import { getAdminPrisma } from '../db/prisma.js'; +import { lockEnterpriseOutbox } from './org-sso-revocation.service.js'; +import { lockProductTeamPolicyExclusive } from './product-team-policy-lock.service.js'; +import { requireLifecycleActor, type LifecycleActor } from './internal-admin-lifecycle.service.js'; +import { lockRefreshSessionUser } from './refresh-session-lock.service.js'; +import { Prisma, type PrismaClient, type ProductErasurePolicy } from '@prisma/client'; +import { previewEntityDeletion } from './entity-deletion-preview.service.js'; +import { AppError } from '../utils/errors.js'; +import { markDeleting } from './entity-deletion-job.service.js'; + +export type Container = { scope: 'TEAM' | 'ORGANISATION'; id: string }; +export async function containerOptions(tx: Prisma.TransactionClient, subject: string, policy: ProductErasurePolicy) { + if (policy.mode !== 'ORGANISATION') return []; + const orgs = await tx.organisation.findMany({ + where: { domain: { in: policy.domains }, lifecycleStatus: 'ACTIVE', + members: { some: { userId: subject, status: 'ACTIVE' } } }, + select: { id: true, ownerId: true, name: true, allowedEmails: true, allowedEmailDomains: true, members: { where: { status: { not: 'REMOVED' } }, select: { userId: true } }, + teams: { select: { id: true, name: true, lifecycleStatus: true, allowedEmails: true, allowedEmailDomains: true, + members: { where: { status: { not: 'REMOVED' } }, select: { userId: true, status: true } } } }, + invites: { where: { acceptedAt: null, declinedAt: null, revokedAt: null, OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }] }, take: 1 }, + inviteLinks: { where: { revokedAt: null, expiresAt: { gt: new Date() } }, take: 1 } }, orderBy: { id: 'asc' }, + }); + const options: { scope: Container['scope']; id: string; name: string; digest: string; scopeDigest: string; teamIds: string[]; teamNames: string[]; retained: { reason: string; count: number }[] }[] = []; + for (const org of orgs) { + if (org.invites.length || org.inviteLinks.length || org.allowedEmails.length || org.allowedEmailDomains.length || + org.teams.some(team => team.allowedEmails.length || team.allowedEmailDomains.length)) continue; + // Directory provisioning can repopulate apparently empty teams. + if (await tx.orgSsoConnection.count({ where: { orgId: org.id } }) || await tx.organisationEmailDomain.count({ where: { orgId: org.id } })) continue; + const ownTeams = org.teams.filter(t => t.members.some(m => m.userId === subject)); + if (ownTeams.length > 1) continue; + const onlyPerson = org.ownerId === subject && org.members.every(m => m.userId === subject) && + org.teams.every(t => t.members.every(m => m.userId === subject)); + const targets: Container[] = onlyPerson ? [{ scope: 'ORGANISATION', id: org.id }] : + ownTeams.length === 1 && ownTeams[0].members.length === 1 && ownTeams[0].members[0].status === 'ACTIVE' && ownTeams[0].lifecycleStatus === 'ACTIVE' + ? [{ scope: 'TEAM', id: ownTeams[0].id }] : []; + for (const target of targets) { + const nativeDomain = normalizeDomain(getEnv().MCP_OAUTH_DOMAIN ?? ''); + if (nativeDomain) { + const clients = await tx.oAuthClient.findMany({ where: { nativeApp: { identifier: { in: policy.nativeApps } } }, select: { clientId: true } }); + const external = await tx.refreshToken.count({ where: { ...(target.scope === 'TEAM' ? { teamId: target.id } : { orgId: target.id }), + domain: nativeDomain, clientId: { notIn: clients.map(c => c.clientId) } } }); + if (external) continue; + } + const preview = await previewEntityDeletion(tx as PrismaClient, target.scope, target.id, 'ERASE_REFERENCE'); + if (preview.blockers.length || !preview.participants.length || preview.participants.some(p => !policy.domains.includes(p.domain)) || + preview.candidates.some(c => c.id !== subject)) continue; + const teams = org.teams.filter(t => preview.teamIds.includes(t.id)).sort((a,b) => a.id.localeCompare(b.id)); + const retained = preview.retainedEvidence.filter(e => e.scope !== 'USER').map(({ reason, count }) => ({ reason, count })); + // Erasing the product role can change orphan eligibility. No product request + // ever deletes those users. Freeze the actual container, recipients and evidence. + const scopeDigest = createHash('sha256').update(JSON.stringify([target, preview.name, teams.map(t => [t.id,t.name]), + preview.participants, retained])).digest('hex'); + options.push({ ...target, name: preview.name, digest: preview.digest, scopeDigest, teamIds: teams.map(t => t.id), teamNames: teams.map(t => t.name), retained }); + } + } + return options; +} + +// The product proof can never authorize a USER job or any orphan-account cascade. +async function beginOwnedContainerErasure(tx: Prisma.TransactionClient, target: Container, expectedDigest: string, subject: string) { + const db = tx as PrismaClient; + const preview = await previewEntityDeletion(db, target.scope, target.id, 'ERASE_REFERENCE'); + if (preview.digest !== expectedDigest || preview.blockers.length) throw new AppError('BAD_REQUEST', 409, 'DELETION_PREVIEW_CHANGED'); + preview.candidates = preview.candidates.map(c => ({ ...c, eligible: false, reasons: ['Product-only consent preserves the UOA identity'] })); + await markDeleting(db, preview); + const job = await tx.entityDeletionJob.create({ data: { scope: target.scope, targetId: target.id, + mode: preview.mode, actorUserId: subject, requestKey: randomUUID(), status: 'WAITING_FOR_PRODUCTS', + preview: preview as unknown as Prisma.InputJsonValue, + participants: { create: preview.participants.map(({ clientDomainId, domain }) => ({ clientDomainId, domain })) } } }); + return job.id; +} + +// Only a live platform administrator can promote the person's exact additional request +// into a shared-entity job, after reconciling dependencies outside UOA's inventory. +export async function reviewContainer(jobId: string, decision: 'approve' | 'preserve', actor: LifecycleActor) { + return getAdminPrisma().$transaction(async tx => { + await lockEnterpriseOutbox(tx); + await lockProductTeamPolicyExclusive(tx); + const actorEmail = await requireLifecycleActor(tx as PrismaClient, actor); + await tx.$queryRaw(Prisma.sql`SELECT id FROM product_erasure_jobs WHERE id=${jobId} FOR UPDATE`); + const job = await tx.productErasureJob.findUniqueOrThrow({ where: { id: jobId }, include: { policy: true } }); + const target = job.requestedContainer as (Container & { scopeDigest: string }) | null; + if (job.containerJobId || !target) throw new AppError('BAD_REQUEST', 409, 'CONTAINER_REVIEW_CLOSED'); + await lockRefreshSessionUser(job.subject, { prisma: tx }); + if (decision === 'approve') { + if (!job.policy.enabled || job.policy.revision !== job.revision) throw new AppError('BAD_REQUEST', 409, 'DELETION_POLICY_CHANGED'); + const row = await tx.user.findUnique({ where: { id: job.subject } }); + if (!row || row.lifecycleStatus !== 'ACTIVE' || (row.accountExpiresAt && row.accountExpiresAt <= new Date())) { + throw new AppError('BAD_REQUEST', 409, 'ACCOUNT_UNAVAILABLE'); + } + const options = await containerOptions(tx, job.subject, job.policy); + const current = options.find(c => c.scope === target.scope && c.id === target.id && c.scopeDigest === target.scopeDigest); + if (!current) throw new AppError('BAD_REQUEST', 409, 'DELETION_PREVIEW_CHANGED'); + const containerJobId = await beginOwnedContainerErasure(tx, current, current.digest, actor.userId); + await tx.productErasureJob.update({ where: { id: jobId }, data: { containerJobId } }); + } else { + const pending = await tx.productErasureReceipt.count({ where: { jobId, acknowledgedAt: null } }); + await tx.productErasureJob.update({ where: { id: jobId }, data: { requestedContainer: Prisma.DbNull, containerPreserved: true, completedAt: pending ? null : new Date() } }); + } + await tx.adminAuditLog.create({ data: { actorEmail, action: 'product.container_review', metadata: { jobId, decision, scope: target.scope, id: target.id } } }); + return { ok: true }; + }, { isolationLevel: 'Serializable', timeout: 15000 }); +} diff --git a/API/src/services/product-erasure-notification.service.ts b/API/src/services/product-erasure-notification.service.ts new file mode 100644 index 00000000..337570d0 --- /dev/null +++ b/API/src/services/product-erasure-notification.service.ts @@ -0,0 +1,51 @@ +import { getPublicBaseUrl } from '../config/env.js'; +import { getAdminPrisma } from '../db/prisma.js'; +import { sendProductDeletionEmail } from './email.service.js'; + +type Log = { warn: (fields: Record, message: string) => void }; + +// Claim a bounded batch. An expired claim retries delivery after failure or process restart. +export async function deliverProductDeletionNotices(log: Log) { + const db = getAdminPrisma(); + const now = new Date(); + const jobs = await db.productErasureJob.findMany({ + where: { completedAt: { not: null }, noticeDueAt: { lte: now } }, orderBy: { noticeDueAt: 'asc' }, take: 25, + select: { id: true, subject: true, rejoinedSubject: true, policy: { select: { name: true } } }, + }); + for (const job of jobs) { + const lease = new Date(Date.now() + 15 * 60_000); + const claimed = await db.productErasureJob.updateMany({ where: { id: job.id, noticeDueAt: { lte: now } }, data: { noticeDueAt: lease } }); + if (!claimed.count) continue; + const user = await db.user.findUnique({ where: { id: job.rejoinedSubject ?? job.subject }, select: { email: true } }); + try { + if (user?.email) { + const receiptUrl = new URL('/auth/delete-account/receipt/' + job.id, getPublicBaseUrl()).href; + await sendProductDeletionEmail(user.email, job.policy.name, receiptUrl); + } + await db.productErasureJob.updateMany({ where: { id: job.id, noticeDueAt: lease }, data: { noticeDueAt: null } }); + } catch { + log.warn({ code: 'PRODUCT_DELETION_NOTICE_PENDING' }, 'Product deletion completion email will retry'); + } + } +} + +export function startProductDeletionNotices(log: Log) { + let running: Promise | undefined; + let nextOverdueCheck = 0; + async function run() { + await deliverProductDeletionNotices(log); + if (Date.now() >= nextOverdueCheck) { + const pending = await getAdminPrisma().productErasureJob.count({ where: { completedAt: null, createdAt: { lt: new Date(Date.now() - 86400000) } } }); + if (pending) log.warn({ code: 'PRODUCT_ERASURE_PENDING', count: pending }, 'Product deletions awaiting action for more than one day in Admin Apps'); + nextOverdueCheck = Date.now() + 3600000; + } + } + function tick() { + running ??= run().catch(() => log.warn({ code: 'PRODUCT_DELETION_DELIVERY_UNAVAILABLE' }, 'Product deletion delivery will retry')) + .finally(() => { running = undefined; }); + } + const timer = setInterval(tick, 60_000); + timer.unref(); + tick(); + return { stop: async () => { clearInterval(timer); await running; } }; +} diff --git a/API/src/services/product-erasure-policy.service.ts b/API/src/services/product-erasure-policy.service.ts new file mode 100644 index 00000000..963cc8f9 --- /dev/null +++ b/API/src/services/product-erasure-policy.service.ts @@ -0,0 +1,51 @@ +import type { PrismaClient } from '@prisma/client'; +import { z } from 'zod'; +import { getAdminAuthDomain, getEnv } from '../config/env.js'; +import { getAdminPrisma } from '../db/prisma.js'; +import { normalizeDomain } from '../utils/domain.js'; +import { AppError } from '../utils/errors.js'; +import { requireLifecycleActor, type LifecycleActor } from './internal-admin-lifecycle.service.js'; +import { USER_SETTINGS_KEY_PATTERN, USER_SETTINGS_NAMESPACE_PATTERN } from './user-settings.service.js'; +import { lockProductTeamPolicyExclusive } from './product-team-policy-lock.service.js'; + +export const ProductId = z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/); +const inventory = (item: z.ZodString) => z.array(item).max(64).transform(items => [...new Set(items)].sort()); +export const ProductPolicyInput = z.object({ + id: ProductId, revision: z.number().int().nonnegative(), name: z.string().trim().min(1).max(100), + mode: z.enum(['PERSONAL', 'ORGANISATION']), enabled: z.boolean(), + disclosure: z.string().trim().min(1).max(2000), + domains: inventory(z.string().trim().toLowerCase().max(253)), + nativeApps: inventory(z.string().trim().min(1).max(255)), + settings: inventory(z.string().max(193)).refine(keys => keys.every(pair => { + const [namespace, key, extra] = pair.split('/'); + return Boolean(namespace && key && extra === undefined && USER_SETTINGS_NAMESPACE_PATTERN.test(namespace) && USER_SETTINGS_KEY_PATTERN.test(key)); + }), 'Expected a settings namespace/key'), +}).strict(); + +export async function saveProductErasurePolicy(input: z.infer, actor: LifecycleActor) { + return getAdminPrisma().$transaction(async tx => { + await lockProductTeamPolicyExclusive(tx); + const actorEmail = await requireLifecycleActor(tx as PrismaClient, actor); + const { id, revision, ...data } = input; + const previous = await tx.productErasurePolicy.findUnique({ where: { id } }); + if ((previous?.revision ?? 0) !== revision) throw new AppError('BAD_REQUEST', 409, 'DELETION_POLICY_CHANGED'); + if ((!data.domains.length && !data.nativeApps.length) || data.domains.includes(getAdminAuthDomain()) || + data.domains.includes(normalizeDomain(getEnv().MCP_OAUTH_DOMAIN ?? '')) || data.settings.some(key => key.startsWith('global/'))) { + throw new AppError('BAD_REQUEST', 400, 'INVALID_PRODUCT_INVENTORY'); + } + if (data.enabled && (await tx.clientDomain.count({ where: { domain: { in: data.domains }, status: 'active' } }) !== data.domains.length || + await tx.nativeApp.count({ where: { identifier: { in: data.nativeApps } } }) !== data.nativeApps.length)) { + throw new AppError('BAD_REQUEST', 400, 'UNREGISTERED_PRODUCT_CLIENT'); + } + if (await tx.productErasurePolicy.findFirst({ where: { id: { not: id }, OR: [ + { domains: { hasSome: data.domains } }, { nativeApps: { hasSome: data.nativeApps } }, { settings: { hasSome: data.settings } }, + ] } })) throw new AppError('BAD_REQUEST', 409, 'OVERLAPPING_PRODUCT_INVENTORY'); + if (previous && await tx.productErasureJob.count({ where: { policyId: id } }) && + (['domains','nativeApps','settings'] as const).some(k => JSON.stringify(previous[k]) !== JSON.stringify(data[k]))) { + throw new AppError('BAD_REQUEST', 409, 'DELETION_INVENTORY_IN_USE'); + } + const row = await tx.productErasurePolicy.upsert({ where: { id }, create: { id, ...data }, update: { ...data, revision: { increment: 1 } } }); + await tx.adminAuditLog.create({ data: { actorEmail, action: 'product.erasure_policy', metadata: { product: id, revision: row.revision } } }); + return row; + }); +} diff --git a/API/src/services/product-erasure.service.ts b/API/src/services/product-erasure.service.ts new file mode 100644 index 00000000..2220595e --- /dev/null +++ b/API/src/services/product-erasure.service.ts @@ -0,0 +1,118 @@ +import { containerOptions, type Container } from './product-erasure-containers.service.js'; +import { revokeEnterpriseScope } from './org-sso-revocation.service.js'; +import { createHash } from 'node:crypto'; +import { Prisma, type ProductErasurePolicy, type PrismaClient } from '@prisma/client'; +import { getAdminPrisma } from '../db/prisma.js'; +import { getAdminAuthDomain, getEnv } from '../config/env.js'; +import { normalizeDomain } from '../utils/domain.js'; +import { AppError } from '../utils/errors.js'; +import { verifyDomainAuthToken } from './domain-secret.service.js'; +import { lockProductTeamPolicyShared } from './product-team-policy-lock.service.js'; + +type Db = Prisma.TransactionClient; +export async function enabledProduct(db: Db, id: string) { + const policy = await db.productErasurePolicy.findUnique({ where: { id } }); + if (!policy?.enabled || policy.domains.includes(getAdminAuthDomain()) || + policy.domains.includes(normalizeDomain(getEnv().MCP_OAUTH_DOMAIN ?? ''))) throw new AppError('NOT_FOUND', 404, 'PRODUCT_ERASURE_UNAVAILABLE'); + return policy; +} + +// Include historical participation and suspended people. A shared product may see teams +// founded under a different domain, so origin domain alone cannot identify its footprint. +export async function productImpact(db: Db, subject: string, policy: ProductErasurePolicy) { + const accesses = await db.billingServiceAccess.findMany({ where: { userId: subject, + appKey: { actorIssuer: { in: policy.domains.map(domain => 'https://' + domain) } } }, select: { orgId: true } }); + const orgs = policy.mode === 'ORGANISATION' ? await db.organisation.findMany({ + where: { OR: [{ id: { in: accesses.map(a => a.orgId) } }, { domain: { in: policy.domains }, + OR: [{ ownerId: subject }, { members: { some: { userId: subject, status: { not: 'REMOVED' } } } }] }] }, + select: { id: true, name: true, ownerId: true, members: { where: { status: { not: 'REMOVED' } }, select: { userId: true } }, + invites: { where: { acceptedAt: null, declinedAt: null, revokedAt: null, OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }] }, select: { id: true }, take: 1 }, + inviteLinks: { where: { revokedAt: null, expiresAt: { gt: new Date() } }, select: { id: true }, take: 1 }, + teams: { orderBy: { id: 'asc' }, select: { id: true, name: true, + members: { where: { status: { not: 'REMOVED' } }, select: { userId: true } } } } }, + orderBy: { id: 'asc' }, + }) : []; + const contexts = orgs.filter(org => org.ownerId === subject || org.members.some(m => m.userId === subject)).map(org => { + const shared = Boolean(org.ownerId && org.ownerId !== subject) || org.invites.length > 0 || org.inviteLinks.length > 0 || + org.members.some(m => m.userId !== subject) || org.teams.some(t => t.members.some(m => m.userId !== subject)); + return { orgId: org.id, name: org.name, shared, teams: org.teams.filter(t => t.members.some(m => m.userId === subject)) + .map(t => ({ teamId: t.id, name: t.name, shared: t.members.some(m => m.userId !== subject) })) }; + }); + const containers = await containerOptions(db, subject, policy); + const impact = { containers, scope: 'PRODUCT_PERSON' as const, product: policy.id, name: policy.name, mode: policy.mode, + revision: policy.revision, disclosure: policy.disclosure, contexts, domains: policy.domains, settings: policy.settings }; + return { impact, digest: createHash('sha256').update(JSON.stringify([subject,impact])).digest('hex') }; +} + +export async function commitProductErasure(db: Db, subject: string, policy: ProductErasurePolicy, digest: string, container?: Container) { + const existing = await db.productErasureJob.findUnique({ where: { subject_policyId: { subject, policyId: policy.id } } }); + if (existing) { + const original = existing.requestedContainer as Container | null; + if (container && (container.id !== original?.id || container.scope !== original.scope)) { + throw new AppError('BAD_REQUEST', 409, 'DELETION_RETRY_MISMATCH'); + } + return { receipt: existing.id, complete: Boolean(existing.completedAt) }; + } + await db.$queryRaw(Prisma.sql`SELECT id FROM users WHERE id=${subject} FOR UPDATE`); + const preview = await productImpact(db, subject, policy); + if (digest !== preview.digest) throw new AppError('BAD_REQUEST', 409, 'DELETION_PREVIEW_CHANGED'); + const selected = container && preview.impact.containers.find(c => c.id === container.id && c.scope === container.scope); + if (container && !selected) throw new AppError('BAD_REQUEST', 409, 'DELETION_PREVIEW_CHANGED'); + const requestedContainer = selected ? { scope: selected.scope, id: selected.id, name: selected.name, scopeDigest: selected.scopeDigest, teamIds: selected.teamIds } : undefined; + const domains = await db.clientDomain.findMany({ where: { domain: { in: policy.domains }, status: 'active' }, select: { id: true } }); + if (domains.length !== policy.domains.length) throw new AppError('BAD_REQUEST', 409, 'DELETION_INVENTORY_UNAVAILABLE'); + const clients = await db.oAuthClient.findMany({ where: { nativeApp: { identifier: { in: policy.nativeApps } } }, select: { clientId: true } }); + const domain = { in: policy.domains }; + const clientIds = { in: clients.map(client => client.clientId) }; + await db.refreshToken.updateMany({ where: { userId: subject, revokedAt: null, OR: [{ domain }, { clientId: clientIds }] }, + data: { revokedAt: new Date() } }); + for (const clientDomain of policy.domains) { + await revokeEnterpriseScope({ clientDomain, scope: 'user', userId: subject, revision: policy.revision }, db); + } + await db.loginLog.deleteMany({ where: { userId: subject, domain } }); + const retiredRoles = await db.domainRole.findMany({ where: { userId: subject, domain, role: 'SUPERUSER' }, select: { domain: true } }); + const newlyClosed = retiredRoles.map(r => r.domain).filter(d => !policy.closedBootstrapDomains.includes(d)); + if (newlyClosed.length) await db.productErasurePolicy.update({ where: { id: policy.id }, data: { closedBootstrapDomains: { push: newlyClosed } } }); + await db.domainRole.deleteMany({ where: { userId: subject, domain } }); + await db.authenticationEvidence.updateMany({ where: { userId: subject, clientDomain: domain, revokedAt: null }, data: { revokedAt: new Date() } }); + await db.debugLoginGrant.deleteMany({ where: { userId: subject, domain } }); + await db.machineEnrollment.updateMany({ where: { subject, clientDomain: domain, status: { not: 'revoked' } }, + data: { status: 'revoked', reason: 'all_devices_revoked', sourceVersion: { increment: 1 } } }); + await db.verificationToken.deleteMany({ where: { userId: subject, domain, type: { not: 'ACCOUNT_DELETION' } } }); + await db.authorizationCode.deleteMany({ where: { userId: subject, OR: [{ domain }, { oauthClientId: clientIds }] } }); + await db.billingServiceAccess.deleteMany({ where: { userId: subject, + appKey: { actorIssuer: { in: policy.domains.map(d => 'https://' + d) } } } }); + for (const setting of policy.settings) { + const [namespace, key] = setting.split('/'); + await db.userSetting.deleteMany({ where: { userId: subject, namespace, key } }); + } + const job = await db.productErasureJob.create({ data: { subject, policyId: policy.id, revision: policy.revision, + requestedContainer, impact: { ...preview.impact, containers: [], contexts: preview.impact.contexts.map(c => ({ + orgId: c.orgId, shared: c.shared, teams: c.teams.map(t => ({ teamId: t.teamId, shared: t.shared })), + })) }, completedAt: domains.length ? null : new Date(), + receipts: { create: domains.map(d => ({ domainId: d.id })) } } }); + return { receipt: job.id, complete: Boolean(job.completedAt) }; +} + +export async function acknowledgeProductErasure(input: { id: string; revision: number; outcome: 'PURGED' | 'RETAINED_EVIDENCE'; + domain: string; token: string }) { + return getAdminPrisma().$transaction(async tx => { + await lockProductTeamPolicyShared(tx); + const auth = await verifyDomainAuthToken({ domain: input.domain, token: input.token }, { prisma: tx as PrismaClient }); + await tx.$queryRaw(Prisma.sql`SELECT id FROM entity_deletion_jobs WHERE id=( + SELECT container_job_id FROM product_erasure_jobs WHERE id=${input.id}) FOR UPDATE`); + await tx.$queryRaw(Prisma.sql`SELECT id FROM product_erasure_jobs WHERE id=${input.id} FOR UPDATE`); + const where = { jobId_domainId: { jobId: input.id, domainId: auth.clientDomainId } }; + const row = await tx.productErasureReceipt.findUnique({ where, include: { job: true } }); + if (!row || row.job.revision !== input.revision) throw new AppError('NOT_FOUND', 404); + if (row.acknowledgedAt && row.outcome !== input.outcome) throw new AppError('BAD_REQUEST', 409, 'DELETION_ACK_MISMATCH'); + if (!row.acknowledgedAt) { + await tx.productErasureReceipt.update({ where, data: { outcome: input.outcome, acknowledgedAt: new Date() } }); + const container = row.job.containerJobId && await tx.entityDeletionJob.findUniqueOrThrow({ where: { id: row.job.containerJobId } }); + if ((!row.job.requestedContainer || (container && container.status === 'COMPLETE')) && !await tx.productErasureReceipt.count({ where: { jobId: input.id, acknowledgedAt: null } })) { + await tx.productErasureJob.update({ where: { id: input.id }, data: { completedAt: new Date() } }); + } + } + return { ok: true }; + }); +} diff --git a/API/src/services/product-participation.service.ts b/API/src/services/product-participation.service.ts new file mode 100644 index 00000000..ea11783f --- /dev/null +++ b/API/src/services/product-participation.service.ts @@ -0,0 +1,14 @@ +import { Prisma } from '@prisma/client'; +import { getAdminAuthDomain, getEnv } from '../config/env.js'; +import { normalizeDomain } from '../utils/domain.js'; +import { AppError } from '../utils/errors.js'; + +export async function assertProductParticipation(db: Pick, subject: string, domain: string, nativeApp?: string) { + const env = getEnv(); + const clientDomain = normalizeDomain(domain); + const shared = clientDomain === getAdminAuthDomain(env) || clientDomain === normalizeDomain(env.MCP_OAUTH_DOMAIN ?? ''); + if (!env.DATABASE_URL || (shared && !nativeApp)) return false; + const rows = await db.$queryRaw<{ denied: boolean; bootstrap_closed: boolean }[]>(Prisma.sql`SELECT * FROM product_erasure_admission(${subject}, ${shared ? '' : clientDomain}, ${nativeApp ?? ''})`); + if (rows[0]?.denied !== false) throw new AppError('FORBIDDEN', 403, 'PRODUCT_ACCOUNT_DELETED'); + return rows[0].bootstrap_closed; +} diff --git a/API/src/services/product-rejoin.service.ts b/API/src/services/product-rejoin.service.ts new file mode 100644 index 00000000..b9458f1d --- /dev/null +++ b/API/src/services/product-rejoin.service.ts @@ -0,0 +1,34 @@ +import { createHash } from 'node:crypto'; +import { Prisma, type ProductErasurePolicy } from '@prisma/client'; +import { AppError } from '../utils/errors.js'; +import { isActiveUser } from './entity-lifecycle.service.js'; + +// Website and public OAuth access tokens have a maximum lifetime of 60 minutes. +// Allow the verifier's clock tolerance before admitting a new participation. +const oldCredentialWindow = 61 * 60_000; +export async function rejoinPreview(tx: Prisma.TransactionClient, subject: string, policy: ProductErasurePolicy) { + const job = await tx.productErasureJob.findUnique({ where: { subject_policyId: { subject, policyId: policy.id } } }); + if (!job?.completedAt || Date.now() < job.createdAt.getTime() + oldCredentialWindow) { + throw new AppError('BAD_REQUEST', 409, 'PRODUCT_REJOIN_NOT_READY'); + } + const digest = createHash('sha256').update(JSON.stringify(['rejoin', subject, job.id, policy.revision])).digest('hex'); + return { digest, impact: { name: policy.name, disclosure: 'Create fresh product access. Deleted data and prior privileges cannot be recovered.', + containers: [], contexts: [], mode: policy.mode } }; +} +export async function resumeProduct(tx: Prisma.TransactionClient, subject: string, policy: ProductErasurePolicy, digest: string) { + if ((await rejoinPreview(tx, subject, policy)).digest !== digest || !isActiveUser(await tx.user.findUnique({ where: { id: subject } }))) { + throw new AppError('UNAUTHORIZED', 401); + } + const job = await tx.productErasureJob.findUniqueOrThrow({ where: { subject_policyId: { subject, policyId: policy.id } } }); + // Clear any unfinished product login before lifting the fence. Other products' credentials, + // including native clients on the common public OAuth domain, retain their exact scope. + const clients = await tx.oAuthClient.findMany({ where: { nativeApp: { identifier: { in: policy.nativeApps } } }, select: { clientId: true } }); + const clientIds = { in: clients.map(c => c.clientId) }; + const domain = { in: policy.domains }; + await tx.authorizationCode.deleteMany({ where: { userId: subject, OR: [{ domain }, { oauthClientId: clientIds }] } }); + await tx.refreshToken.updateMany({ where: { userId: subject, OR: [{ domain }, { clientId: clientIds }], revokedAt: null }, data: { revokedAt: new Date() } }); + await tx.authenticationEvidence.updateMany({ where: { userId: subject, clientDomain: domain, revokedAt: null }, data: { revokedAt: new Date() } }); + await tx.verificationToken.deleteMany({ where: { userId: subject, domain, type: { not: 'ACCOUNT_DELETION' } } }); + await tx.productErasureJob.update({ where: { id: job.id }, data: { subject: 'closed:' + job.id, rejoinedSubject: subject, rejoinedAt: new Date(), requestedContainer: Prisma.DbNull, impact: {} } }); + return { receipt: job.id, complete: true }; +} diff --git a/API/tests/integration/product-erasure.test.ts b/API/tests/integration/product-erasure.test.ts new file mode 100644 index 00000000..e52b1762 --- /dev/null +++ b/API/tests/integration/product-erasure.test.ts @@ -0,0 +1,221 @@ +import { randomUUID } from 'node:crypto'; +import cookie from '@fastify/cookie'; +import Fastify from 'fastify'; +import { PrismaClient } from '@prisma/client'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { createRlsTestDb } from '../helpers/test-db.js'; +import { getAdminAuthDomain } from '../../src/config/env.js'; +import { saveProductErasurePolicy } from '../../src/services/product-erasure-policy.service.js'; +import { assertProductParticipation } from '../../src/services/product-participation.service.js'; +import { confirmAccountDeletionRequest, startAccountDeletionRequest, submitProductErasure } from '../../src/services/account-deletion-request.service.js'; +import { hashPassword } from '../../src/services/password.service.js'; +import { createAdminDomain } from '../../src/services/domain-secret.service.js'; +import { registerProductDeletionJobs } from '../../src/routes/domain/deletion-jobs.js'; +import { registerAccountDeletionRequestRoutes } from '../../src/routes/auth/account-deletion-request.js'; +import { deliverProductDeletionNotices } from '../../src/services/product-erasure-notification.service.js'; +import { ensureDomainRoleForUser } from '../../src/services/domain-role.service.js'; +import { executeEntityDeletion, productDeletionJobs, acknowledgeProductDeletion } from '../../src/services/entity-deletion-job.service.js'; +import { reviewContainer } from '../../src/services/product-erasure-containers.service.js'; +import { productImpact } from '../../src/services/product-erasure.service.js'; + +const store = vi.hoisted(() => ({ db: null as PrismaClient | null, mail: vi.fn(), notice: vi.fn() })); +vi.mock('../../src/db/prisma.js', () => ({ getAdminPrisma: () => store.db!, getPrisma: () => store.db! })); +vi.mock('../../src/services/email.service.js', () => ({ sendActionVerificationEmail: store.mail, sendProductDeletionEmail: store.notice })); +describe.skipIf(!process.env.DATABASE_URL)('product account erasure', () => { + let handle: NonNullable>>; + let db: PrismaClient; + let actor: { userId: string; tokenVersion: number }; + const http = Fastify(); + const credentials = new Map(); + let tenant: PrismaClient; + const browser = 'b'.repeat(43); + const person = () => { const email = randomUUID() + '@example.com'; return db.user.create({ data: { email, userKey: email } }); }; + beforeAll(async () => { + handle = (await createRlsTestDb())!; db = handle.prisma; store.db = db; + tenant = new PrismaClient({ datasourceUrl: handle.appDatabaseUrl }); + await http.register(cookie); + registerProductDeletionJobs(http); + registerAccountDeletionRequestRoutes(http); + store.mail.mockResolvedValue(undefined); + const admin = await person(); + await db.domainRole.create({ data: { userId: admin.id, domain: getAdminAuthDomain(), role: 'SUPERUSER' } }); + actor = { userId: admin.id, tokenVersion: admin.tokenVersion }; + }); + afterAll(async () => { await http.close(); await tenant?.$disconnect(); await handle?.cleanup(); }); + async function policy(mode: 'ORGANISATION'|'PERSONAL', settings: string[] = []) { + const id = 'p-' + randomUUID(); + const domain = id + '.example.com'; + const registered = await createAdminDomain({ domain, actorEmail: 'operator@example.test' }, { prisma: db }); + credentials.set(domain, registered.clientHash); + return saveProductErasurePolicy({ id, name: id, mode, revision: 0, domains: [domain], nativeApps: [], settings, + disclosure: 'Erase personal content. Retain signed invoices.', enabled: true }, actor); + } + async function verify(email: string, product: string, rejoin = false) { + const { challengeId } = await startAccountDeletionRequest(email, browser, product, rejoin); + const code = store.mail.mock.lastCall![0].code as string; + await expect(confirmAccountDeletionRequest({ challengeId, browser, code })).rejects.toThrow(); + const preview = await confirmAccountDeletionRequest({ challengeId, browser, code, product, rejoin }); + if (!('digest' in preview)) throw new Error('Expected product preview'); + return { challengeId, digest: preview.digest, product, browser, rejoin }; + } + it('fences one product, preserves the other account, binds consent to the policy revision and commits once', async () => { + const a = await policy('PERSONAL', ['game/save']), b = await policy('PERSONAL', ['other/save']); + const user = await person(); + for (const p of [a,b]) { + await db.domainRole.create({ data: { userId: user.id, domain: p.domains[0] } }); + await db.userSetting.create({ data: { userId: user.id, namespace: p.settings[0].split('/')[0], key: 'save', value: 'mine', sizeBytes: 4 } }); + } + const proof = await verify(user.email!, a.id); + await expect(submitProductErasure({ ...proof, product: b.id })).rejects.toThrow(); + await expect(submitProductErasure({ ...proof, browser: 'x'.repeat(43) })).rejects.toThrow(); + await saveProductErasurePolicy({ ...a, mode: 'PERSONAL', disclosure: 'Updated retention' }, actor); + await expect(submitProductErasure(proof)).rejects.toThrow('DELETION_PREVIEW_CHANGED'); + const fresh = await verify(user.email!, a.id); + const receipt = await submitProductErasure(fresh); + expect(receipt.complete).toBe(false); + expect(await submitProductErasure(fresh)).toEqual(receipt); + expect(await db.productErasureReceipt.count({ where: { jobId: receipt.receipt } })).toBe(1); + const values = await db.userSetting.findMany({ where: { userId: user.id } }); + expect(values.map(v => v.namespace)).toEqual(['other']); + await expect(assertProductParticipation(db, user.id, a.domains[0])).rejects.toThrow('PRODUCT_ACCOUNT_DELETED'); + await assertProductParticipation(db, user.id, b.domains[0]); + expect((await db.user.findUniqueOrThrow({ where: { id: user.id } })).tokenVersion).toBe(user.tokenVersion); + expect(await db.domainRole.count({ where: { domain: b.domains[0], userId: user.id } })).toBe(1); + }); + it('offers only the exclusive named container, rechecks joins and never authorizes global account deletion', async () => { + const p = await policy('ORGANISATION'), owner = await person(), other = await person(); + const org = await db.organisation.create({ data: { domain: p.domains[0], name: 'Studio', slug: randomUUID(), ownerId: owner.id } }); + const team = await db.team.create({ data: { orgId: org.id, name: 'Weekend', slug: randomUUID() } }); + await db.orgMember.create({ data: { orgId: org.id, userId: owner.id, role: 'owner' } }); + await db.teamMember.create({ data: { teamId: team.id, userId: owner.id } }); + const target = { scope: 'ORGANISATION' as const, id: org.id }; + expect((await productImpact(db, owner.id, p)).impact.containers).toEqual([expect.objectContaining(target)]); + const proof = await verify(owner.email!, p.id); + const receipt = await submitProductErasure({ ...proof, container: target }); + expect(await db.entityDeletionJob.count({ where: { targetId: org.id } })).toBe(0); + await db.orgMember.create({ data: { orgId: org.id, userId: other.id } }); + await expect(reviewContainer(receipt.receipt, 'approve', actor)).rejects.toThrow('DELETION_PREVIEW_CHANGED'); + expect((await productImpact(db, owner.id, p)).impact.containers).toEqual([expect.objectContaining({ scope: 'TEAM', id: team.id })]); + const sibling = await db.team.create({data:{orgId:org.id,name:'Colleagues',slug:randomUUID()}}); + const membership = await db.teamMember.create({data:{teamId:sibling.id,userId:owner.id}}); + expect((await productImpact(db, owner.id, p)).impact.containers).toEqual([]); + await db.teamMember.delete({where:{id:membership.id}}); + await db.teamMember.create({ data: { userId: other.id, teamId: team.id, status: 'DEACTIVATED' } }); + expect((await productImpact(db, owner.id, p)).impact.containers).toEqual([]); + await reviewContainer(receipt.receipt, 'preserve', actor); + expect((await http.inject('/auth/delete-account/receipt/' + receipt.receipt)).body).toContain('workspace was preserved'); + expect((await db.user.findUniqueOrThrow({ where: { id: owner.id } })).lifecycleStatus).toBe('ACTIVE'); + }); + it('delivers only to the assigned backend, verifies acknowledgements and admits a fresh registration without restoring privileges', async () => { + const p = await policy('PERSONAL'), other = await policy('PERSONAL'), user = await person(); + const domain = p.domains[0], unrelated = other.domains[0]; + await db.domainRole.create({ data: { userId: user.id, domain, role: 'SUPERUSER' } }); + const proof = await verify(user.email!, p.id); + const result = await submitProductErasure(proof); + await expect(assertProductParticipation(tenant, user.id, domain)).rejects.toThrow('PRODUCT_ACCOUNT_DELETED'); + expect(await assertProductParticipation(tenant, (await person()).id, domain)).toBe(true); + const feed = '/domain/product-erasure-jobs'; + const request = (route: string, who: string, payload?: {revision: number; outcome: string}) => + http.inject({ method: payload ? 'POST' : 'GET', url: route + '?domain=' + who, + headers: { authorization: 'Bearer ' + credentials.get(who) }, payload }); + expect((await request(feed, unrelated)).json().data).toEqual([]); + expect((await request(feed, domain)).json().data).toMatchObject([{ id: result.receipt, subject: user.id }]); + const ack = feed + '/' + result.receipt + '/acknowledge'; + expect((await request(ack, unrelated, { revision: 1, outcome: 'PURGED' })).statusCode).toBe(404); + expect((await request(ack, domain, { revision: 2, outcome: 'PURGED' })).statusCode).toBe(404); + for (let i=0; i<2; i++) expect((await request(ack, domain, { revision: 1, outcome: 'PURGED' })).statusCode).toBe(200); + expect((await request(ack, domain, { revision: 1, outcome: 'RETAINED_EVIDENCE' })).statusCode).toBe(409); + expect((await http.inject('/auth/delete-account/receipt/' + result.receipt)).body).toBe('Deletion complete.'); + expect((await request(feed, domain)).json().data).toEqual([]); + expect((await db.productErasureJob.findUniqueOrThrow({ where: { id: result.receipt } })).impact).toEqual({}); + const stateUrl = '/domain/product-participation?domain=' + domain + '&subject=' + user.id; + const access = () => http.inject({url: stateUrl, headers: {authorization: 'Bearer ' + credentials.get(domain)}}); + expect((await access()).json()).toMatchObject({active: false}); + const log = {warn: vi.fn()}; + await deliverProductDeletionNotices(log); + await deliverProductDeletionNotices(log); + expect(store.notice).toHaveBeenCalledOnce(); + expect(store.notice).toHaveBeenCalledWith(user.email, p.name, expect.stringContaining(result.receipt)); + await expect(verify(user.email!, p.id, true)).rejects.toThrow('PRODUCT_REJOIN_NOT_READY'); + await db.productErasureJob.update({ where: { id: result.receipt }, data: { createdAt: new Date(Date.now() - 62*60_000) } }); + const again = await verify(user.email!, p.id, true); + await expect(submitProductErasure({ ...again, rejoin: false })).rejects.toThrow(); + await submitProductErasure(again); + expect((await access()).json()).toMatchObject({active: true, generation: result.receipt}); + expect((await ensureDomainRoleForUser({ domain, userId: user.id, prisma: db })).role).toBe('USER'); + await submitProductErasure(proof); + await assertProductParticipation(tenant, user.id, domain); + }); + + it('requires an exact container job and both receipts before completing an exclusive organisation', async () => { + const p = await policy('ORGANISATION'), user = await person(); + const org = await db.organisation.create({data: { domain: p.domains[0], name: 'Private studio', slug: randomUUID(), ownerId: user.id }}); + await db.orgMember.create({data: { orgId: org.id, userId: user.id, role: 'owner' }}); + const proof = await verify(user.email!, p.id); + const result = await submitProductErasure({...proof, container: { scope: 'ORGANISATION', id: org.id }}); + await reviewContainer(result.receipt, 'approve', actor); + const domain = p.domains[0]; + const {id: clientDomainId} = await db.clientDomain.findUniqueOrThrow({where:{domain}}); + const [entity] = await productDeletionJobs(clientDomainId); + expect(entity).toMatchObject({ effectiveScope: 'ORGANISATION', effectiveTargetId: org.id, accountsToDelete: [] }); + await acknowledgeProductDeletion({ clientDomainId, jobId: entity.id, revision: entity.revision, outcome: 'PURGED', authority: { domain, token: credentials.get(domain)! } }); + await executeEntityDeletion(entity.id, actor); + expect(await db.organisation.findUnique({where:{id:org.id}})).toBeNull(); + expect((await db.productErasureJob.findUniqueOrThrow({where:{id:result.receipt}})).completedAt).toBeNull(); + const done = await http.inject({ method: 'POST', url: '/domain/product-erasure-jobs/' + result.receipt + '/acknowledge?domain=' + domain, + headers: { authorization: 'Bearer ' + credentials.get(domain) }, payload: {revision: 1, outcome:'PURGED'} }); + expect(done.statusCode).toBe(200); + expect((await db.productErasureJob.findUniqueOrThrow({where:{id:result.receipt}})).completedAt).toBeTruthy(); + expect((await db.user.findUniqueOrThrow({where:{id:user.id}})).lifecycleStatus).toBe('ACTIVE'); + }); + it('blocks only the mapped native app and prevents erased settings from returning through a second client', async () => { + const user = await person(), id = 'n-' + randomUUID(); + const app = await db.nativeApp.create({ data: { identifier: id, name: 'Game', redirectUris: ['game://callback'], scopes: ['openid'], + methods: ['google'], primaryColor: '#ffffff', backgroundColor: '#ffffff', textColor: '#111111' } }); + const key = 'native-' + randomUUID(); + await saveProductErasurePolicy({ id, name: 'Game', mode: 'PERSONAL', revision: 0, enabled: true, domains: [], nativeApps: [app.identifier], + settings: ['game/' + key], disclosure: 'Erase cloud saves' }, actor); + expect((await submitProductErasure(await verify(user.email!, id))).complete).toBe(true); + await expect(assertProductParticipation(tenant, user.id, 'common.example.test', id)).rejects.toThrow('PRODUCT_ACCOUNT_DELETED'); + await assertProductParticipation(tenant, user.id, 'common.example.test', 'different-app'); + await expect(db.userSetting.create({data: {userId:user.id,namespace:'game',key,value:'old save',sizeBytes:8}})).rejects.toThrow('PRODUCT_ACCOUNT_DELETED'); + }); + + it('requires an independent personal credential for managed mailboxes and invalidates a proof when the credential changes', async () => { + const p = await policy('PERSONAL'), domain = randomUUID()+'.example.test'; + const email = 'employee@'+domain, password = 'test-password-'+randomUUID(); + const user = await db.user.create({data:{ email, userKey:email, passwordHash: await hashPassword(password) }}); + const org = await db.organisation.create({data:{ domain:p.domains[0], name:'Test',slug:randomUUID(), ownerId:user.id }}); + await db.organisationEmailDomain.create({data:{clientDomain:p.domains[0],orgId:org.id,emailDomain:domain,challengeHash:randomUUID(),challengeExpiresAt:new Date(Date.now()+60000),verifiedAt:new Date()}}); + const {challengeId} = await startAccountDeletionRequest(email, browser, p.id); + const proof = {challengeId, browser, product:p.id, code: store.mail.mock.lastCall![0].code}; + await expect(confirmAccountDeletionRequest(proof)).rejects.toThrow('INDEPENDENT_REAUTH_REQUIRED'); + await expect(confirmAccountDeletionRequest({...proof,password:'incorrect'})).rejects.toThrow(); + const preview = await confirmAccountDeletionRequest({...proof,password}); + if (!('digest' in preview)) throw new Error('Expected preview'); + await db.user.update({where:{id:user.id},data:{passwordHash:null}}); + await expect(submitProductErasure({...proof,digest:preview.digest})).rejects.toThrow(); + expect(await db.productErasureJob.count({where:{subject:user.id}})).toBe(0); + }); + it('does not substitute a global subject for a same-mailbox per-domain account', async () => { + const p = await policy('PERSONAL'), global = await person(), email = global.email!; + await db.user.create({ data: { email, domain: p.domains[0], userKey: p.domains[0] + '|' + email } }); + const {challengeId} = await startAccountDeletionRequest(email, browser, p.id); + expect(await db.verificationToken.findUnique({where:{id:challengeId}})).toBeNull(); + expect(await db.productErasureJob.count({where:{subject:global.id}})).toBe(0); + }); + it('keeps a multi-backend receipt pending until every assigned backend commits its cleanup', async () => { + const first = await policy('PERSONAL'), user = await person(); + const extra = await createAdminDomain({domain: randomUUID() + '.example.test', actorEmail:'operator@example.test'}, {prisma:db}); + const policyRow = await saveProductErasurePolicy({...first, mode:'PERSONAL', domains:[...first.domains,extra.domain.domain]}, actor); + const result = await submitProductErasure(await verify(user.email!, first.id)); + const receipt = '/auth/delete-account/receipt/' + result.receipt; + const ack = (domain: string, token: string, outcome: string) => http.inject({ method: 'POST', + url: '/domain/product-erasure-jobs/' + result.receipt + '/acknowledge?domain=' + domain, + headers: { authorization: 'Bearer ' + token }, payload: { revision: policyRow.revision, outcome } }); + expect((await ack(first.domains[0], credentials.get(first.domains[0])!, 'PURGED')).statusCode).toBe(200); + expect((await http.inject(receipt)).body).toContain('Deletion in progress'); + expect((await ack(extra.domain.domain, extra.clientHash, 'RETAINED_EVIDENCE')).statusCode).toBe(200); + expect((await http.inject(receipt)).body).toBe('Deletion complete. Restricted evidence was retained.'); + }); +}); diff --git a/API/tests/setup.ts b/API/tests/setup.ts index ac3c1236..36426142 100644 --- a/API/tests/setup.ts +++ b/API/tests/setup.ts @@ -6,6 +6,14 @@ import { randomBytes } from 'node:crypto'; import { testConfigJwks } from './helpers/test-config.js'; +// Route and token unit fixtures inject partial Prisma clients. They represent products +// without erasure policies. Real Prisma clients (including transaction clients) use SQL. +vi.mock('../src/services/product-participation.service.js', async importOriginal => { + const actual = await importOriginal(); + return { assertProductParticipation: (...args: Parameters) => + !args[0].$queryRaw || vi.isMockFunction(args[0].$queryRaw) ? Promise.resolve(false) : actual.assertProductParticipation(...args) }; +}); + vi.mock('undici', async () => { const actual = await vi.importActual('undici'); diff --git a/API/tests/unit/billing-service-access.service.test.ts b/API/tests/unit/billing-service-access.service.test.ts index 5714620b..d6a3a127 100644 --- a/API/tests/unit/billing-service-access.service.test.ts +++ b/API/tests/unit/billing-service-access.service.test.ts @@ -90,7 +90,7 @@ describe('UOA-owned direct product access', () => { ); expect(transaction).toHaveBeenCalledWith( expect.any(Function), - expect.objectContaining({ isolationLevel: 'RepeatableRead' }), + expect.objectContaining({ isolationLevel: 'Serializable' }), ); }); diff --git a/Admin/e2e/fixtures.ts b/Admin/e2e/fixtures.ts index d714e888..1c0bb892 100644 --- a/Admin/e2e/fixtures.ts +++ b/Admin/e2e/fixtures.ts @@ -134,6 +134,7 @@ export async function installFixtures(page: Page) { const path = decodeURIComponent(url.pathname.replace('/internal/admin', '')); const json = (body: unknown, status = 200) => route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) }); + if (path === '/product-erasure' && req.method() === 'GET') return json({ policies: [], pending: [] }); if (path.startsWith('/lifecycle/')) return lifecycle.handle(route, path); const grantResponse = creditGrants.handle(req.method(), path, req.method() === 'POST' ? req.postDataJSON() : null); if (grantResponse) return json(grantResponse.body, grantResponse.status); diff --git a/Admin/e2e/product-erasure.e2e.ts b/Admin/e2e/product-erasure.e2e.ts new file mode 100644 index 00000000..d9d2582b --- /dev/null +++ b/Admin/e2e/product-erasure.e2e.ts @@ -0,0 +1,49 @@ +import { expect, test } from '@playwright/test'; +import { installFixtures } from './fixtures'; + +test('operator configures product deletion from Apps', async ({ page }, info) => { + await installFixtures(page); + let policies: Record[] = []; + await page.route('**/internal/admin/product-erasure', async route => { + if (route.request().method() === 'POST') { + const body = route.request().postDataJSON(); + expect(body.nativeApps).toEqual(['com.example.browser']); + expect(body.settings).toEqual(['browser/bookmarks']); + policies = [{ ...body, revision: 1 }]; + return route.fulfill({ json: policies[0] }); + } + return route.fulfill({ json: { policies, pending: [] } }); + }); + await page.goto('/apps'); + await page.getByRole('button', { name: 'Add product policy' }).click(); + await page.getByLabel('Product identifier', { exact: true }).fill('browser'); + await page.getByLabel('Product name', { exact: true }).fill('Example Browser'); + await page.getByLabel(/Registered native app identifiers/).fill('com.example.browser'); + await page.getByLabel(/Product-owned setting keys/).fill('browser/bookmarks'); + await page.getByLabel(/What is erased/).fill('Synced favourites are removed immediately. Browsing history stays on your device.'); + await page.getByLabel('Enable requests for this inventory').check(); + await page.getByRole('button', { name: 'Save policy' }).click(); + await expect(page.getByRole('link', { name: 'Deletion form' })).toHaveAttribute('href', '/auth/delete-account?product=browser'); + await page.screenshot({ path: info.outputPath('product-policies.png'), fullPage: true }); +}); + +test('operator can preserve a workspace when its dependency review changes', async ({ page }) => { + await installFixtures(page); + let pending = true; + await page.route('**/internal/admin/product-erasure', route => route.fulfill({ json: { policies: [], pending: pending ? [{ + id: 'example-job', policyId: 'studio', createdAt: '2026-11-20T09:00:00Z', + requestedContainer: { scope: 'TEAM', name: 'Weekend' }, receipts: [], + }] : [] } })); + await page.route('**/internal/admin/product-erasure/example-job/container', route => { + if (route.request().postDataJSON().decision === 'approve') return route.fulfill({ status: 409, json: { error: 'DELETION_PREVIEW_CHANGED' } }); + expect(route.request().postDataJSON().decision).toBe('preserve'); + pending = false; + return route.fulfill({ json: { ok: true } }); + }); + await page.goto('/apps'); + await page.getByRole('button', { name: 'Review Weekend' }).click(); + await page.getByRole('button', { name: 'Confirm container deletion' }).click(); + await expect(page.getByRole('alert')).toContainText('Could not apply the decision'); + await page.getByRole('button', { name: 'Preserve container' }).click(); + await expect(page.getByRole('heading', { name: 'Awaiting cleanup' })).toHaveCount(0); +}); diff --git a/Admin/e2e/product-erasure.flow.ts b/Admin/e2e/product-erasure.flow.ts new file mode 100644 index 00000000..2b587b15 --- /dev/null +++ b/Admin/e2e/product-erasure.flow.ts @@ -0,0 +1,34 @@ +import { expect, test } from '@playwright/test'; + +test('review product scope before confirming deletion', async ({ page }, info) => { + await page.addInitScript(() => { + Object.assign(window, { __UOA_CLIENT_CONFIG__: { + enabled_auth_methods: ['email_password', 'google'], allow_registration: false, language_config: 'en', + ui_theme: { colors: { bg: '#ffffff', surface: '#ffffff', text: '#111827', muted: '#475569', + primary: '#2563eb', primary_text: '#ffffff', border: '#e2e8f0', danger: '#dc2626', danger_text: '#ffffff' }, + radii: { card: '12px', input: '8px', button: '8px' }, density: 'comfortable', + typography: { font_family: 'sans-serif', base_text_size: 'md' }, button: { style: 'solid' }, + card: { style: 'bordered' }, logo: { url: '', alt: 'UnlikeOtherAI' } }, + }, __UOA_CONFIG_URL__: '' }); + }); + const policy = { name: 'Example Browser', disclosure: 'Synced favourites will be erased. Your local browsing history stays on this device.' }; + await page.route('**/auth/delete-account/product/browser', route => route.fulfill({ json: policy })); + await page.route('**/auth/delete-account/start', route => route.fulfill({ json: { challengeId: 'example' } })); + await page.route('**/auth/delete-account/confirm', route => route.fulfill({ json: { digest: 'example', + impact: { ...policy, mode: 'PERSONAL', contexts: [], containers: [] } } })); + await page.route('**/auth/delete-account/submit-product', route => { + expect(route.request().postDataJSON()).toMatchObject({ product: 'browser', digest: 'example', challengeId: 'example' }); + return route.fulfill({ json: { receipt: 'example-receipt', complete: true } }); + }); + await page.goto('/auth/delete-account?product=browser'); + await expect(page.getByRole('heading', { name: 'Delete your Example Browser account' })).toBeVisible(); + await page.getByLabel('Account email').fill('alex@example.test'); + await page.getByRole('button', { name: 'Send verification code' }).click(); + await page.getByLabel('Email verification code').fill('123456'); + await page.getByRole('button', { name: 'Review deletion' }).click(); + await expect(page.getByRole('link', { name: 'Delete my UnlikeOtherAI account everywhere' })).toHaveAttribute('href','/auth/delete-account'); + await page.screenshot({ path: info.outputPath('review-product.png'), fullPage: true }); + await page.getByRole('button', { name: 'Confirm permanent deletion' }).click(); + await expect(page.getByRole('status')).toContainText('Product account deletion complete'); + await expect(page.getByRole('link', { name: 'Check deletion status' })).toHaveAttribute('href','/auth/delete-account/receipt/example-receipt'); +}); diff --git a/Admin/playwright.auth.config.ts b/Admin/playwright.auth.config.ts index fa19381f..14dd2262 100644 --- a/Admin/playwright.auth.config.ts +++ b/Admin/playwright.auth.config.ts @@ -2,7 +2,7 @@ import { defineConfig, devices } from '@playwright/test'; // Reuse the workspace's browser runner to verify the separate Auth application. export default defineConfig({ - testDir: './e2e', testMatch: ['auth-lifecycle.flow.ts', 'kelpie-consent.flow.ts'], outputDir: './e2e/artifacts/auth', + testDir: './e2e', testMatch: ['auth-lifecycle.flow.ts', 'kelpie-consent.flow.ts', 'product-erasure.flow.ts'], outputDir: './e2e/artifacts/auth', workers: 1, retries: 0, timeout: 30_000, reporter: [['list']], use: { channel: process.env.PW_CHANNEL, baseURL: 'http://127.0.0.1:5275', trace: 'retain-on-failure' }, projects: [ diff --git a/Admin/src/features/admin/ProductErasureSettings.tsx b/Admin/src/features/admin/ProductErasureSettings.tsx new file mode 100644 index 00000000..d8a0d398 --- /dev/null +++ b/Admin/src/features/admin/ProductErasureSettings.tsx @@ -0,0 +1,84 @@ +import { useState } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { Button } from '../../components/ui/Button'; +import { Card } from '../../components/ui/Card'; +import { FieldShell, SelectField, TextField } from '../../components/ui/FormFields'; +import { ApiRequestError, createApiClient } from '../../services/api-client'; + +const path = '/internal/admin/product-erasure'; +const api = createApiClient(); +const empty = { id: '', name: '', domains: '', nativeApps: '', settings: '', disclosure: '', mode: 'PERSONAL', enabled: false, revision: 0 }; +type Form = typeof empty; +type Policy = Omit & { domains: string[]; nativeApps: string[]; settings: string[] }; +type Pending = { id: string; policyId: string; createdAt: string; requestedContainer?: { scope: string; name: string }; containerJobId?: string; receipts: { domainId: string; acknowledgedAt?: string }[] }; +const fields = [ + ['id', 'Product identifier'], ['name', 'Product name'], ['domains', 'Registered backend domains (comma separated)'], + ['nativeApps', 'Registered native app identifiers (comma separated)'], ['settings', 'Product-owned setting keys (namespace/key, comma separated)'], +] as const; +function list(value: string) { return value.split(',').map(v => v.trim()).filter(Boolean); } + +export function ProductErasureSettings() { + const [cursors, setCursors] = useState([]); + const after = cursors.at(-1); + const query = useQuery({ queryKey: ['admin', 'product-erasure', after], queryFn: () => + api.get<{ policies: Policy[]; pending: Pending[]; next?: string }>(after ? path + '?after=' + encodeURIComponent(after) : path) }); + const next = query.data?.next; + const [form, setForm] = useState
(empty); + const [review, setReview] = useState(); + const [editing, setEditing] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + function edit(policy?: Policy) { + setForm(policy ? { id: policy.id, revision: policy.revision, name: policy.name, mode: policy.mode, disclosure: policy.disclosure, enabled: policy.enabled, domains: policy.domains.join(', '), nativeApps: policy.nativeApps.join(', '), settings: policy.settings.join(', ') } : empty); + setEditing(true); setError(''); + } + async function decide(decision: 'approve' | 'preserve') { + if (!review) return; + setBusy(true); setError(''); + try { await api.post(path + '/' + review.id + '/container', { decision }); setReview(undefined); await query.refetch(); } + catch { setError('Could not apply the decision. Refresh the inventory and review again.'); } + finally { setBusy(false); } + } + async function save() { + setBusy(true); setError(''); + try { + await api.post(path, { ...form, domains: list(form.domains), nativeApps: list(form.nativeApps), settings: list(form.settings) }); + await query.refetch(); setEditing(false); + } catch (e) { setError(e instanceof ApiRequestError && e.code ? e.code.replaceAll('_',' ').toLowerCase() : 'Could not save the deletion policy.'); } + finally { setBusy(false); } + } + return +

Product account deletion

+ {query.isPending ?

Loading deletion policies…

: query.isError ? +

Could not load policies.

: <> + {query.data.policies.map(p =>
+ {p.enabled ? 'Enabled' : 'Disabled'} · Revision {p.revision} + {p.enabled && Deletion form}
)} + + {query.data.pending.length > 0 &&

Awaiting cleanup

    {query.data.pending.map(j =>
  • + {j.policyId} · {j.createdAt.slice(0,10)} · {j.receipts.filter(r => !r.acknowledgedAt).length} outstanding acknowledgements · {j.id} + {j.containerJobId ? Open container job : + j.requestedContainer && } + {j.receipts.some(r => !r.acknowledgedAt) &&

    Waiting for backend IDs {j.receipts.filter(r => !r.acknowledgedAt).map(r => r.domainId).join(', ')}

    } +
  • )}
} + {after && } + {next && } + } + {review &&

Review permanent deletion of {review.requestedContainer?.scope.toLowerCase()} {review.requestedContainer?.name}

+

Verify that all connected products are in the inventory and no other person or product depends on this workspace. Preserving the workspace allows personal erasure to finish.

+ + {error &&

{error}

}
} + {editing && { e.preventDefault(); void save(); }}> + {fields.map(([key, label]) => 0)} + onChange={e => setForm({ ...form, [key]: e.target.value })} />)} + setForm({ ...form, mode: e.target.value })}> + +