diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f497efa06..e885bf842a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **Delete your account from OpenBot Mobile.** Account, then Delete account: type your email address + and "delete my account". The account goes in 14 days, or at once with Delete now, as in the web + app. A sign-in older than ten minutes is asked for again first. Somebody who signs in again before + the account goes sees when it goes and can cancel. An organization that stops the deletion has a + way on from the phone: the only owner of one can delete it there, by typing its name, and an owner + beside others can leave it. The App Store asks that an account can be deleted in the app it can + be made in. - **OpenBot Mobile follows a change of organization at once.** After you picked another organization in Account, Chats and the other screens went on showing the one before for up to ten seconds, so an organization with conversations could read "No chats yet". Every screen now reads again the moment diff --git a/mobile/app/(tabs)/(account)/account.tsx b/mobile/app/(tabs)/(account)/account.tsx index 46e154782d..ed9dc872a0 100644 --- a/mobile/app/(tabs)/(account)/account.tsx +++ b/mobile/app/(tabs)/(account)/account.tsx @@ -2,6 +2,7 @@ import { router } from "expo-router"; import { useCallback, useEffect, useState } from "react"; import { View } from "react-native"; import { chooseOrganization, organizationChoices } from "../../../src/api"; +import { getAccountDeletion } from "../../../src/api/generated/people/people"; import { authClient, serverUrl } from "../../../src/auth"; import { Icon, @@ -18,6 +19,7 @@ import { IconBuilding, IconCheck, IconLogout, + IconTrash, } from "../../../src/icons"; import { pushTurnedOn, @@ -47,6 +49,10 @@ export default function Account() { const organizations = useLoad(loadOrganizations, Boolean(session), { keep: true, }); + // Deleting the account is offered where this OpenBot has it: one that answers where the deletion stands. + // The person's own too, so the line stays while it is read again. + const loadDeletion = useCallback(() => getAccountDeletion(), []); + const deletion = useLoad(loadDeletion, Boolean(session), { keep: true }); async function act(name: string, work: () => Promise) { setBusy(name); setError(""); @@ -165,6 +171,15 @@ export default function Account() { }) } /> + {deletion.data ? ( + router.push("/delete-account")} + /> + ) : null} ); diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx index 07d429abb3..efda1414d5 100644 --- a/mobile/app/_layout.tsx +++ b/mobile/app/_layout.tsx @@ -13,6 +13,7 @@ import { GestureHandlerRootView } from "react-native-gesture-handler"; import { KeyboardProvider } from "react-native-keyboard-controller"; import { setSignedInPerson } from "../src/api"; import { authClient } from "../src/auth"; +import { DeletionGate, useDeletionGate } from "../src/deletion-gate"; import { withSecurityFloor } from "../src/floor-gate"; import { announceGallery } from "../src/gallery/announce"; import { NO_HEADER_LEFT, useHeaderOptions } from "../src/header"; @@ -96,6 +97,8 @@ function Layout() { const signedIn = Boolean(session); // Whether a signed-in person has setting up to finish (the terms, onboarding, their AI): src/setup-gate.tsx. const setup = useSetupGate(signedIn, session?.user.id); + // Whether the person's account is scheduled to be deleted: then only that is shown (src/deletion-gate.tsx). + const deletion = useDeletionGate(signedIn); // Once set up, the cards this app draws are announced, as the web app does on load: src/gallery/announce.ts. const setUp = signedIn && setup.facts !== null && setup.step === null; useEffect(() => { @@ -193,6 +196,22 @@ function Layout() { name="connections" options={{ title: "Connections" }} /> + + {/* Only the way back to an app's screen after its sign-in page: never seen, so no header flashes. */} {/* Finishing setting up, over the app until it is done; Update OpenBot over that. */} + {/* An account scheduled to be deleted: when it goes and how to cancel, over everything but an update. */} + void check()} /> ); diff --git a/mobile/app/delete-account.tsx b/mobile/app/delete-account.tsx new file mode 100644 index 0000000000..3157e0800f --- /dev/null +++ b/mobile/app/delete-account.tsx @@ -0,0 +1,292 @@ +import { router, Stack, useFocusEffect } from "expo-router"; +import { Button } from "heroui-native/button"; +import { Input } from "heroui-native/input"; +import { Label } from "heroui-native/label"; +import { TextField } from "heroui-native/text-field"; +import { useCallback, useState } from "react"; +import { Alert, View } from "react-native"; +import { + blockerWayOn, + blockerWords, + DELETE_PHRASE, + DELETION_WAIT_DAYS, + refusalKind, + scheduledSentence, + typedRight, +} from "../src/account-deletion"; +import type { AccountDeletionBlocker } from "../src/api/generated/model"; +import { removeOrganizationMember } from "../src/api/generated/organizations/organizations"; +import { + getAccountDeletion, + requestAccountDeletion, +} from "../src/api/generated/people/people"; +import { authClient, signIn } from "../src/auth"; +import { + Notice, + Row, + Rows, + Screen, + ScrollScreen, + Section, + SheetTitle, + Text, +} from "../src/components"; +import { IconBuilding } from "../src/icons"; +import { useLoad } from "../src/use-load"; + +const TITLE = "Delete account"; + +/** One line of what is deleted or kept. */ +function Line({ children }: { children: string }) { + return ( + + • + {children} + + ); +} + +/** + * Deleting the person's own account, started here in the app, as the App Store asks of an app people can make + * an account in. The same step as the web app's (Settings, Delete my account), in its words. + * + * The person types their email address and the phrase. The account goes in 14 days, or at once with Delete now. + * OpenBot signs them out everywhere when it takes the request, so the app forgets its sign-in and says when the + * account goes. Signing in again before then shows only that, and a way to cancel (src/deletion-gate.tsx). + * + * OpenBot takes the request only from a sign-in of the last ten minutes. An older one is refused, and Sign in + * again opens the sign-in once more, which makes a new one. An organization the person still has to hand over + * stops the deletion, and each is listed with what to do about it. + */ +export default function DeleteAccount() { + const { data: session } = authClient.useSession(); + const loadStanding = useCallback(() => getAccountDeletion(), []); + const standing = useLoad(loadStanding, Boolean(session)); + const [typedEmail, setTypedEmail] = useState(""); + const [typedPhrase, setTypedPhrase] = useState(""); + const [busy, setBusy] = useState<"" | "later" | "now" | "sign-in" | "leave">( + "", + ); + const [error, setError] = useState(""); + const [signInAgain, setSignInAgain] = useState(false); + + // Back from deleting an organization that stopped it: the list is read again, and has one less. + const { refresh: readStanding } = standing; + useFocusEffect( + useCallback(() => { + void readStanding(); + }, [readStanding]), + ); + + const blockers = standing.data?.blockers ?? []; + const ready = + typedRight(session?.user.email, typedEmail, typedPhrase) && !busy; + + async function remove(immediate: boolean) { + setBusy(immediate ? "now" : "later"); + setError(""); + setSignInAgain(false); + try { + const scheduled = await requestAccountDeletion({ + confirmEmail: typedEmail.trim(), + confirmPhrase: typedPhrase.trim(), + ...(immediate ? { immediate: true } : {}), + }); + // OpenBot has ended this sign-in with the request: the phone forgets it, and the sign-in screen is next. + await authClient.signedOutByOpenBot(); + Alert.alert(scheduledSentence(scheduled.deleteAfter, immediate)); + } catch (failure) { + const kind = refusalKind(failure); + // What stops it is read again, and the list takes the form's place. + if (kind === "blocked") await standing.refresh(); + setSignInAgain(kind === "sign-in-again"); + setError( + failure instanceof Error + ? failure.message + : "Couldn't delete your account. Try again.", + ); + } finally { + setBusy(""); + } + } + + /** What a tap on an organization that stops the deletion does: the way on from it, where the phone has one. */ + function wayOn(blocker: AccountDeletionBlocker): (() => void) | undefined { + const way = blockerWayOn(blocker); + if (way === "delete") + return () => + router.push({ + pathname: "/delete-organization", + params: { + id: blocker.organizationId, + name: blocker.organizationName, + }, + }); + if (way === "leave") + return () => + Alert.alert( + `Leave ${blocker.organizationName}?`, + "You stop being a member. What you made there stays there.", + [ + { text: "Cancel", style: "cancel" }, + { + text: "Leave", + style: "destructive", + onPress: () => void leave(blocker), + }, + ], + ); + return undefined; + } + + async function leave(blocker: AccountDeletionBlocker) { + setBusy("leave"); + setError(""); + try { + await removeOrganizationMember(blocker.organizationId, "me"); + await standing.refresh(); + } catch (failure) { + setError( + failure instanceof Error + ? failure.message + : "Couldn't leave the organization. Try again.", + ); + } finally { + setBusy(""); + } + } + + async function again() { + setBusy("sign-in"); + try { + // A new sign-in, though the browser remembers the person: the one OpenBot counts as recent. + if (await signIn({ fresh: true })) { + setError(""); + setSignInAgain(false); + } + } catch (failure) { + setError( + failure instanceof Error + ? failure.message + : "Sign-in didn't finish. Try again.", + ); + } finally { + setBusy(""); + } + } + + return ( + + + + + void again()} + > + {busy === "sign-in" ? "Opening sign-in…" : "Sign in again"} + + ) : undefined + } + /> + {blockers.length > 0 ? ( + // A sentence, not a section's label: a label is one line, and this one doesn't fit one. + + + Before you can delete your account, sort out these organizations. + + + {blockers.map((blocker) => { + const onPress = wayOn(blocker); + return ( + + ); + })} + + + ) : ( + <> + + {`Your account is deleted in ${DELETION_WAIT_DAYS} days. Sign in before then to cancel. Delete now deletes it straight away, and you can't undo it.`} + +
+ + + Your conversations, memory, Bots, skills and routines that are + only yours. + + Your saved logins, connections and computer. + +
+
+ + + Messages you sent in organizations you share with others. They + show as from Deleted user. + + + Security log entries, for 180 days, without your name or + email. + + +
+ + + + + + + + + + + + + + )} +
+
+ ); +} diff --git a/mobile/app/delete-organization.tsx b/mobile/app/delete-organization.tsx new file mode 100644 index 0000000000..fc2c130325 --- /dev/null +++ b/mobile/app/delete-organization.tsx @@ -0,0 +1,90 @@ +import { router, Stack, useLocalSearchParams } from "expo-router"; +import { Button } from "heroui-native/button"; +import { Input } from "heroui-native/input"; +import { Label } from "heroui-native/label"; +import { TextField } from "heroui-native/text-field"; +import { useState } from "react"; +import { typedOrganizationName } from "../src/account-deletion"; +import { deleteOrganization } from "../src/api/generated/organizations/organizations"; +import { + Notice, + Screen, + ScrollScreen, + SheetTitle, + Text, +} from "../src/components"; + +const TITLE = "Delete organization"; + +/** + * Deleting an organization the person is the only owner of, opened from the list of what stops their account + * being deleted (./delete-account.tsx). Without it that list had no way on from the phone. + * + * The web app's step (Organization settings, Delete), in its words: everything in the organization goes for + * everybody, so the person types its name first. OpenBot decides whether it can go, and its refusal is shown as + * it says it: a person's own organization, and the one that comes with OpenBot, stay. + */ +export default function DeleteOrganization() { + const { id, name } = useLocalSearchParams<{ id: string; name: string }>(); + const [typed, setTyped] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const ready = Boolean(id) && typedOrganizationName(name ?? "", typed); + + async function remove() { + if (!id) return; + setBusy(true); + setError(""); + try { + await deleteOrganization(id); + // Back to the list of what stops the account being deleted, which reads again and has one less. + router.back(); + } catch (failure) { + setError( + failure instanceof Error + ? failure.message + : "Couldn't delete the organization. Try again.", + ); + } finally { + setBusy(false); + } + } + + return ( + + + + + + {`Delete ${name ?? "this organization"}?`} + + Its Bots, conversations and computers are deleted for everyone. + Members keep their accounts and their other organizations. You can't + undo it. + + + To keep the organization, make someone else an owner first. You do + that in OpenBot in a browser, in the organization's settings. + + + + + + + + + ); +} diff --git a/mobile/src/account-deletion.ts b/mobile/src/account-deletion.ts new file mode 100644 index 0000000000..dfac1be8c9 --- /dev/null +++ b/mobile/src/account-deletion.ts @@ -0,0 +1,130 @@ +/** + * Deleting the person's own account from the phone: what they type to confirm, how OpenBot's refusals are read, + * and the words for each. + * + * The API does the deleting (`requestAccountDeletion`, api/openapi.yaml). The account goes 14 days after the + * person asks, or at once. From the moment they ask they are signed out everywhere, and signing in again shows + * only when the account goes and a way to cancel (./deletion-gate.tsx). + * + * Imports nothing that needs a phone, so it can be tested. + */ +import type { AccountDeletionBlocker } from "./api/generated/model"; + +/** The words the person types, as the API matches them: without regard to case or the spaces around them. */ +export const DELETE_PHRASE = "delete my account"; +/** How long the account waits before it is deleted, unless the person says now. */ +export const DELETION_WAIT_DAYS = 14; + +/** The API's codes for the refusals this app answers with something other than the sentence it sent. */ +const REAUTHENTICATE = "REAUTHENTICATE"; +const ACCOUNT_DELETION_BLOCKED = "ACCOUNT_DELETION_BLOCKED"; + +const same = (typed: string, wanted: string) => + typed.trim().toLowerCase() === wanted.trim().toLowerCase(); + +/** + * Whether what the person typed is what the API will take: their own email address and the phrase. The button + * waits for it, so a slip is caught before anything is sent. The API checks again, and its answer is the one + * that counts. + */ +export function typedRight( + email: string | undefined, + typedEmail: string, + typedPhrase: string, +): boolean { + return ( + Boolean(email) && + same(typedEmail, email ?? "") && + same(typedPhrase, DELETE_PHRASE) + ); +} + +/** + * Whether a deletion is scheduled. A state this app doesn't know reads as scheduled, as the API says to read + * one: the person is then shown when the account goes and how to cancel, which is right for any state but none. + */ +export function deletionScheduled(status: string | undefined): boolean { + return status !== undefined && status !== "none"; +} + +/** + * What a refused deletion needs next. + * + * - `sign-in-again`: the sign-in is older than ten minutes. The person signs in again, then asks again. + * - `blocked`: an organization stops it. The screen reads again what stops it, and lists each. + * - `other`: the sentence OpenBot sent says it all. + */ +export type RefusalKind = "sign-in-again" | "blocked" | "other"; + +export function refusalKind(error: unknown): RefusalKind { + const code = + typeof error === "object" && error !== null + ? (error as { code?: unknown }).code + : undefined; + if (code === REAUTHENTICATE) return "sign-in-again"; + if (code === ACCOUNT_DELETION_BLOCKED) return "blocked"; + return "other"; +} + +/** + * What the person does about an organization that stops the deletion, in the web app's words. A reason this app + * doesn't know reads as the one that is always enough: leaving the organization. + */ +export function blockerWords(blocker: AccountDeletionBlocker): string { + if (blocker.reason === "only_owner") + return "You're its only owner: make someone else an owner, or delete the organization."; + if (blocker.reason === "only_admin") + return "You're its only admin: make someone else an admin."; + return "Leave this organization first."; +} + +/** + * What the phone offers for an organization that stops the deletion, so nobody is left on a list with no way on. + * + * - `delete`: the person is its only owner. The phone can delete it. Making someone else an owner is done in + * OpenBot in a browser, and the screen says so. + * - `leave`: the person is an owner beside others, and leaves. So does a reason this app doesn't know, which the + * API says to read as having to leave. + * - `none`: the person is its only admin where there is no owner. Somebody else has to be made an admin, which + * the phone has no screen for. + */ +export type BlockerWayOn = "delete" | "leave" | "none"; + +export function blockerWayOn(blocker: AccountDeletionBlocker): BlockerWayOn { + if (blocker.reason === "only_owner") return "delete"; + if (blocker.reason === "only_admin") return "none"; + return "leave"; +} + +/** Whether what the person typed is the organization's name, which deleting it waits for, as the web app does. */ +export function typedOrganizationName(name: string, typed: string): boolean { + return Boolean(name.trim()) && typed.trim() === name.trim(); +} + +/** The day an account goes, as a person reads a date: "December 14", with the year when it is another one. */ +export function deletionDay( + deleteAfter: string | undefined, + now = new Date(), +): string | undefined { + if (!deleteAfter) return undefined; + const day = new Date(deleteAfter); + if (Number.isNaN(day.getTime())) return undefined; + return day.toLocaleDateString(undefined, { + month: "long", + day: "numeric", + ...(day.getFullYear() === now.getFullYear() ? {} : { year: "numeric" }), + }); +} + +/** What the person is told once the deletion is scheduled, before the app goes back to the sign-in screen. */ +export function scheduledSentence( + deleteAfter: string | undefined, + immediate: boolean, + now = new Date(), +): string { + if (immediate) return "Your account is being deleted."; + const day = deletionDay(deleteAfter, now); + return day + ? `Your account will be deleted on ${day}. Sign in before then to cancel.` + : "Your account will be deleted. Sign in before then to cancel."; +} diff --git a/mobile/src/auth.ts b/mobile/src/auth.ts index bfb49bd75a..5d20b710c3 100644 --- a/mobile/src/auth.ts +++ b/mobile/src/auth.ts @@ -284,8 +284,12 @@ const snapshot = () => state; * Sign in to OpenBot in the system browser's sign-in session. Resolves false when the person closed the browser, and * throws a {@link SignInError} in the person's words when the sign-in was refused or didn't finish. */ -export async function signIn(): Promise { +export async function signIn( + options: { fresh?: boolean } = {}, +): Promise { const found = await loadMetadata(); + // Signing in again replaces the sign-in this phone holds: the old one is ended at OpenBot once the new one is kept. + const replaced = options.fresh ? await storedRefreshToken() : null; const verifier = base64Url(Crypto.getRandomBytes(32)); const nonce = base64Url(Crypto.getRandomBytes(16)); const challenge = base64ToBase64Url( @@ -296,7 +300,11 @@ export async function signIn(): Promise { ), ); const result = await WebBrowser.openAuthSessionAsync( - authorizationUrl(found, { state: nonce, challenge }), + authorizationUrl(found, { + state: nonce, + challenge, + ...(options.fresh ? { fresh: true } : {}), + }), REDIRECT_URI, BROWSER_OPTIONS, ); @@ -313,6 +321,8 @@ export async function signIn(): Promise { // Without a refresh token the person would be asked again within the hour. if (!answer.grant.refreshToken) throw new SignInError(SERVER_TOO_OLD); await keep(answer.grant); + if (replaced && replaced !== answer.grant.refreshToken) + void revoke(found.revocationEndpoint, [[replaced, "refresh_token"]]); publish({ ...state, isPending: true }); await readSession(); if (!state.data) throw state.error ?? new SignInError(NOT_FINISHED); @@ -330,6 +340,14 @@ async function signOut(): Promise { const revocation = await loadMetadata() .then((found) => found.revocationEndpoint) .catch(() => undefined); + await revoke(revocation, tokens); +} + +/** End tokens at OpenBot, where it can be reached. A token it can't be told about ends by itself. */ +async function revoke( + revocation: string | undefined, + tokens: [string, string][], +): Promise { if (!revocation) return; await Promise.all( tokens.map(([value, hint]) => @@ -359,6 +377,14 @@ export const authClient = { getAccessToken, refreshAfterRefusal, signOut, + /** + * Forget this phone's sign-in without telling OpenBot, which has already ended it: what follows a request to + * delete the account, which signs the person out everywhere. + */ + async signedOutByOpenBot(): Promise { + await forget(); + publish({ data: null, isPending: false, error: null }); + }, }; /** diff --git a/mobile/src/deletion-gate.tsx b/mobile/src/deletion-gate.tsx new file mode 100644 index 0000000000..abf2ffb38f --- /dev/null +++ b/mobile/src/deletion-gate.tsx @@ -0,0 +1,122 @@ +/** + * What a person sees who signs in while their account is scheduled to be deleted: when it goes, and a way to + * cancel. Nothing else, because OpenBot answers nothing else for them until they cancel (every other request is + * refused as ACCOUNT_PENDING_DELETION), so no screen behind this could load. + * + * Asked once for each sign-in. An OpenBot from before account deletion has nothing at that address, and the app + * goes on as it always did. + */ +import { Button } from "heroui-native/button"; +import { useCallback, useEffect, useState } from "react"; +import { View } from "react-native"; +import { deletionDay, deletionScheduled } from "./account-deletion"; +import { + cancelAccountDeletion, + getAccountDeletion, +} from "./api/generated/people/people"; +import { authClient } from "./auth"; +import { Notice, Text } from "./components"; + +export type DeletionGateState = { + /** When the account goes, once OpenBot has said it is scheduled. Undefined while it isn't. */ + scheduled: { deleteAfter?: string } | undefined; + busy: "" | "cancel" | "sign-out"; + error: string; + cancel: () => void; + signOut: () => void; +}; + +export function useDeletionGate(signedIn: boolean): DeletionGateState { + const [scheduled, setScheduled] = useState<{ deleteAfter?: string }>(); + const [busy, setBusy] = useState<"" | "cancel" | "sign-out">(""); + const [error, setError] = useState(""); + useEffect(() => { + if (!signedIn) { + setScheduled(undefined); + setError(""); + return; + } + let current = true; + getAccountDeletion() + .then((standing) => { + if (!current) return; + setScheduled( + deletionScheduled(standing.status) + ? { + ...(standing.deleteAfter + ? { deleteAfter: standing.deleteAfter } + : {}), + } + : undefined, + ); + }) + // No answer is no deletion: an OpenBot without the address, or one that can't be reached, shows the app. + .catch(() => {}); + return () => { + current = false; + }; + }, [signedIn]); + + const act = useCallback( + (name: "cancel" | "sign-out", work: () => Promise) => { + setBusy(name); + setError(""); + void work() + .catch((failure) => { + setError( + failure instanceof Error + ? failure.message + : "Couldn't do that. Try again.", + ); + }) + .finally(() => setBusy("")); + }, + [], + ); + const cancel = useCallback( + () => + act("cancel", async () => { + await cancelAccountDeletion(); + setScheduled(undefined); + }), + [act], + ); + const signOut = useCallback( + () => act("sign-out", () => authClient.signOut()), + [act], + ); + return { scheduled, busy, error, cancel, signOut }; +} + +export function DeletionGate({ gate }: { gate: DeletionGateState }) { + if (!gate.scheduled) return null; + const day = deletionDay(gate.scheduled.deleteAfter); + return ( + + + + {day + ? `Your account will be deleted on ${day}.` + : "Your account will be deleted."} + + Cancel the deletion to use OpenBot again. + + + + + + + + ); +} diff --git a/mobile/src/oauth.ts b/mobile/src/oauth.ts index 732ebc89df..01f5fb65b1 100644 --- a/mobile/src/oauth.ts +++ b/mobile/src/oauth.ts @@ -125,10 +125,18 @@ export function base64ToBase64Url(base64: string): string { return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } -/** The address the browser opens to sign in. */ +/** + * The address the browser opens to sign in. `fresh` asks OpenBot to sign the person in again though the browser + * still remembers them (OpenID Connect's `prompt=login`): what deleting the account needs, which takes only a + * sign-in from the last ten minutes. + */ export function authorizationUrl( metadata: Metadata, - { state, challenge }: { state: string; challenge: string }, + { + state, + challenge, + fresh, + }: { state: string; challenge: string; fresh?: boolean }, ): string { const url = new URL(metadata.authorizationEndpoint); url.searchParams.set("response_type", "code"); @@ -138,6 +146,7 @@ export function authorizationUrl( url.searchParams.set("state", state); url.searchParams.set("code_challenge", challenge); url.searchParams.set("code_challenge_method", "S256"); + if (fresh) url.searchParams.set("prompt", "login"); return url.href; } diff --git a/mobile/tests/account-deletion.test.ts b/mobile/tests/account-deletion.test.ts new file mode 100644 index 0000000000..68142092b4 --- /dev/null +++ b/mobile/tests/account-deletion.test.ts @@ -0,0 +1,161 @@ +/** + * Deleting the person's own account from the phone (src/account-deletion.ts): what they type, how OpenBot's + * refusals are read, and the words for each. And the sign-in asked for again before it (src/oauth.ts). + */ + +import { expect, test } from "bun:test"; +import { + blockerWayOn, + blockerWords, + DELETE_PHRASE, + DELETION_WAIT_DAYS, + deletionDay, + deletionScheduled, + refusalKind, + scheduledSentence, + typedOrganizationName, + typedRight, +} from "../src/account-deletion"; +import { authorizationUrl, readMetadata } from "../src/oauth"; + +const EMAIL = "dana@acme.com"; + +/** A refusal as the app's API client throws it (src/api/request.ts): OpenBot's sentence, with its code. */ +const refused = (message: string, code: string) => + Object.assign(new Error(message), { code }); + +test("the button waits for the person's own email address and the phrase", () => { + expect(typedRight(EMAIL, EMAIL, DELETE_PHRASE)).toBe(true); + expect(typedRight(EMAIL, "", DELETE_PHRASE)).toBe(false); + expect(typedRight(EMAIL, EMAIL, "")).toBe(false); + expect(typedRight(EMAIL, "sam@acme.com", DELETE_PHRASE)).toBe(false); + expect(typedRight(EMAIL, EMAIL, "delete account")).toBe(false); +}); + +test("what is typed is matched as the API matches it: without regard to case or the spaces around it", () => { + expect(typedRight(EMAIL, " Dana@Acme.com ", " Delete My Account ")).toBe( + true, + ); +}); + +test("a sign-in that names no email address can't confirm", () => { + expect(typedRight(undefined, "", DELETE_PHRASE)).toBe(false); + expect(typedRight("", "", DELETE_PHRASE)).toBe(false); +}); + +test("the wait is the API's 14 days", () => { + expect(DELETION_WAIT_DAYS).toBe(14); + expect(DELETE_PHRASE).toBe("delete my account"); +}); + +test("a deletion is scheduled for any state but none, a state from a later OpenBot included", () => { + expect(deletionScheduled("none")).toBe(false); + expect(deletionScheduled(undefined)).toBe(false); + expect(deletionScheduled("scheduled")).toBe(true); + expect(deletionScheduled("deleting")).toBe(true); +}); + +test("a refusal is read by the API's code", () => { + expect(refusalKind(refused("Sign in again.", "REAUTHENTICATE"))).toBe( + "sign-in-again", + ); + expect( + refusalKind(refused("An organization.", "ACCOUNT_DELETION_BLOCKED")), + ).toBe("blocked"); + expect( + refusalKind(refused("Not your email.", "ACCOUNT_DELETION_NOT_CONFIRMED")), + ).toBe("other"); + expect(refusalKind(new Error("offline"))).toBe("other"); + expect(refusalKind(null)).toBe("other"); +}); + +test("an organization that stops the deletion says what to do, and an unknown reason says to leave", () => { + const blocker = (reason: string) => ({ + organizationId: "o1", + organizationName: "Acme", + reason, + }); + expect(blockerWords(blocker("only_owner"))).toBe( + "You're its only owner: make someone else an owner, or delete the organization.", + ); + expect(blockerWords(blocker("only_admin"))).toBe( + "You're its only admin: make someone else an admin.", + ); + expect(blockerWords(blocker("owner_must_leave"))).toBe( + "Leave this organization first.", + ); + expect(blockerWords(blocker("a_reason_from_later"))).toBe( + "Leave this organization first.", + ); +}); + +test("the day the account goes reads as a date, with the year only when it is another one", () => { + const now = new Date("2026-11-30T12:00:00Z"); + expect(deletionDay("2026-12-14T12:00:00Z", now)).toMatch(/14/); + expect(deletionDay("2026-12-14T12:00:00Z", now)).not.toMatch(/2026/); + expect(deletionDay("2027-01-03T12:00:00Z", now)).toMatch(/2027/); + expect(deletionDay(undefined, now)).toBeUndefined(); + expect(deletionDay("not a date", now)).toBeUndefined(); +}); + +test("the person is told when the account goes, or that it is going now", () => { + const now = new Date("2026-11-30T12:00:00Z"); + expect(scheduledSentence("2026-12-14T12:00:00Z", false, now)).toMatch( + /^Your account will be deleted on .*14.*\. Sign in before then to cancel\.$/, + ); + expect(scheduledSentence(undefined, false, now)).toBe( + "Your account will be deleted. Sign in before then to cancel.", + ); + expect(scheduledSentence("2026-11-30T12:00:00Z", true, now)).toBe( + "Your account is being deleted.", + ); +}); + +test("signing in again asks OpenBot for a new sign-in, and an ordinary sign-in doesn't", () => { + const metadata = readMetadata( + { + issuer: "https://my.open.bot/api/auth", + authorization_endpoint: "https://my.open.bot/api/auth/oauth2/authorize", + token_endpoint: "https://api.open.bot/api/auth/oauth2/token", + scopes_supported: ["people:read", "people:write", "offline_access"], + code_challenge_methods_supported: ["S256"], + grant_types_supported: ["authorization_code", "refresh_token"], + response_types_supported: ["code"], + }, + false, + ); + const ordinary = new URL( + authorizationUrl(metadata, { state: "s", challenge: "c" }), + ); + expect(ordinary.searchParams.has("prompt")).toBe(false); + const fresh = new URL( + authorizationUrl(metadata, { state: "s", challenge: "c", fresh: true }), + ); + expect(fresh.searchParams.get("prompt")).toBe("login"); + // Everything else is the same request. + fresh.searchParams.delete("prompt"); + expect(fresh.href).toBe(ordinary.href); +}); + +test("each organization that stops the deletion has a way on from the phone, where there is one", () => { + const blocker = (reason: string) => ({ + organizationId: "o1", + organizationName: "Acme", + reason, + }); + // The only owner deletes it here, or hands it over in a browser. + expect(blockerWayOn(blocker("only_owner"))).toBe("delete"); + // An owner beside others leaves, and so does a reason from a later OpenBot. + expect(blockerWayOn(blocker("owner_must_leave"))).toBe("leave"); + expect(blockerWayOn(blocker("a_reason_from_later"))).toBe("leave"); + // Making someone else an admin has no screen on the phone. + expect(blockerWayOn(blocker("only_admin"))).toBe("none"); +}); + +test("deleting an organization waits for its name, typed as it is written", () => { + expect(typedOrganizationName("HillClimbing", "HillClimbing")).toBe(true); + expect(typedOrganizationName("HillClimbing", " HillClimbing ")).toBe(true); + expect(typedOrganizationName("HillClimbing", "hillclimbing")).toBe(false); + expect(typedOrganizationName("HillClimbing", "")).toBe(false); + expect(typedOrganizationName("", "")).toBe(false); +});