From 7253f9e02df0ac02c9577b0f9789a41495bf0814 Mon Sep 17 00:00:00 2001 From: David McKay Date: Thu, 3 Dec 2026 09:31:00 -0800 Subject: [PATCH 1/2] Mobile push: tests that hold registration to once per organization, one at a time, and waiting out a 429 The stand-in for expo-notifications now does what 58.1 does on a phone: asking for the Expo push token without a device token asks the phone for one, and the phone tells every push token listener the token it gave, changed or not. Against the code before the fix these fail: hundreds of registrations in 300ms where there should be two. Also: signing in refused as too many says it couldn't reach OpenBot, and a refresh refused as too many keeps the refresh token. --- .../tests/isolated/push-everywhere.check.ts | 207 +++++++++++++++--- mobile/tests/oauth.test.ts | 3 +- .../rate-limited-sign-in.check.ts | 104 +++++++++ 3 files changed, 286 insertions(+), 28 deletions(-) create mode 100644 mobile/tests/with-packages/rate-limited-sign-in.check.ts diff --git a/mobile/tests/isolated/push-everywhere.check.ts b/mobile/tests/isolated/push-everywhere.check.ts index 8d15061571..64bf7f252e 100644 --- a/mobile/tests/isolated/push-everywhere.check.ts +++ b/mobile/tests/isolated/push-everywhere.check.ts @@ -3,15 +3,31 @@ * and again when they come to work in another one or the push token changes. The generated client and the mutator run * for real against a stand-in deployment; Expo's push library, the secure store and the device are the platform, so * they are stood in for with what a phone that has notifications on gives. + * + * The stand-in for expo-notifications does what 58.1's does on a phone. Asking for the Expo push token without a device + * token asks the phone for one (getDevicePushTokenAsync), and the phone then tells every push token listener the token + * it gave, changed or not: iOS's PushTokenModule sends `onDevicePushToken` from `didRegister` each time, and Android's + * calls `onNewToken` after every fetch. Build 7 asked again from inside its listener, which told the listener again: + * about 10,000 registrations a minute, until the deployment's rate limit shut the phone out. */ -import { afterAll, beforeEach, expect, mock, test } from "bun:test"; +import { afterAll, afterEach, beforeEach, expect, mock, test } from "bun:test"; import appConfig from "../../app.config"; /** Each device registration that reached the server: `organization device token`. */ const registered: string[] = []; +/** Every registration the phone sent, answered or refused. */ +let attempts = 0; +/** Registrations the server is answering at once, and the most it ever was. */ +let inFlight = 0; +let mostInFlight = 0; +/** How long the server takes to answer a registration. */ +let answerAfterMs = 0; let organizations = ["org_work", "org_home"]; /** Organizations that refuse to register the phone (push turned off there). */ let refusing: string[] = []; +/** Registrations still to be refused as too many, as the deployment's rate limit does, and the Retry-After it sends. */ +let rateLimited = 0; +let retryAfter: string | undefined; const server = Bun.serve({ hostname: "127.0.0.1", @@ -35,30 +51,68 @@ const server = Bun.serve({ url.pathname, ); if (device && request.method === "PUT") { - const organization = device[1] as string; - if (refusing.includes(organization)) - return Response.json( - { detail: "Push is off here.", code: "FORBIDDEN" }, - { - status: 403, - headers: { "content-type": "application/problem+json" }, - }, - ); - const { token } = (await request.json()) as { token: string }; - registered.push(`${organization} ${device[2]} ${token}`); - return Response.json({ id: device[2], token, platform: "android" }); + attempts++; + inFlight++; + mostInFlight = Math.max(mostInFlight, inFlight); + try { + if (answerAfterMs) + await new Promise((resolve) => setTimeout(resolve, answerAfterMs)); + if (rateLimited > 0) { + rateLimited--; + // The rate limit's own page, not the API's problem. + return new Response("Too many requests", { + status: 429, + headers: { + "content-type": "text/html", + ...(retryAfter ? { "retry-after": retryAfter } : {}), + }, + }); + } + const organization = device[1] as string; + if (refusing.includes(organization)) + return Response.json( + { detail: "Push is off here.", code: "FORBIDDEN" }, + { + status: 403, + headers: { "content-type": "application/problem+json" }, + }, + ); + const { token } = (await request.json()) as { token: string }; + registered.push(`${organization} ${device[2]} ${token}`); + return Response.json({ id: device[2], token, platform: "android" }); + } finally { + inFlight--; + } } return Response.json({ detail: "Not found." }, { status: 404 }); }, }); -let pushToken = "ExponentPushToken[first]"; +type DevicePushToken = { type: "android"; data: string }; +/** The token the phone's push service gives now. */ +let deviceToken = "first"; +/** How many times the phone was asked for its device token. */ +let deviceTokenAsks = 0; let permission = "granted"; /** How many times the phone asked the person for permission. */ let askedPermission = 0; -const tokenListeners = new Set<() => void>(); +const tokenListeners = new Set<(token: DevicePushToken) => void>(); const secure = new Map([["openbot-device-id", "phone_1"]]); +/** The phone's push service telling the app its token, as Expo's TokenEmitter hands it to every listener. */ +function tellListeners(data: string) { + for (const listener of [...tokenListeners]) + listener({ type: "android", data }); +} +async function getDevicePushTokenAsync(): Promise { + deviceTokenAsks++; + const data = deviceToken; + // Told to every listener as well as answered, every time, whether the token changed or not: a native event, so it + // comes on a later turn of the event loop. + setTimeout(() => tellListeners(data), 0); + return { type: "android", data }; +} + mock.module("../../src/auth", () => ({ serverUrl: `http://127.0.0.1:${server.port}`, authClient: { @@ -100,29 +154,57 @@ mock.module("expo-notifications", () => ({ askedPermission++; return { status: permission }; }, - getExpoPushTokenAsync: async () => ({ data: pushToken }), - addPushTokenListener: (listener: () => void) => { + getDevicePushTokenAsync, + // As 58.1's: the device token it is given, else the phone's, asked for (which tells every listener). + getExpoPushTokenAsync: async ( + options: { devicePushToken?: DevicePushToken } = {}, + ) => { + const device = options.devicePushToken ?? (await getDevicePushTokenAsync()); + return { type: "expo", data: `ExponentPushToken[${device.data}]` }; + }, + addPushTokenListener: (listener: (token: DevicePushToken) => void) => { tokenListeners.add(listener); return { remove: () => tokenListeners.delete(listener) }; }, })); -const { setSignedInPerson, chooseOrganization } = await import("../../src/api"); +const { setSignedInPerson, chooseOrganization, rereadOrganizations } = + await import("../../src/api"); const { keepPushRegistered, registerPush } = await import( "../../src/notifications" ); /** Lets the registrations a listener started reach the server. */ -const settle = () => new Promise((resolve) => setTimeout(resolve, 50)); +const settle = (ms = 100) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** What the last test started, stopped after it, so a test that fails leaves nothing running into the next. */ +let running: (() => void) | undefined; +function keep() { + running = keepPushRegistered(); + return running; +} -beforeEach(() => { +beforeEach(async () => { registered.length = 0; + attempts = 0; + inFlight = 0; + mostInFlight = 0; + answerAfterMs = 0; organizations = ["org_work", "org_home"]; refusing = []; - pushToken = "ExponentPushToken[first]"; + rateLimited = 0; + retryAfter = undefined; + deviceToken = "first"; + deviceTokenAsks = 0; permission = "granted"; askedPermission = 0; setSignedInPerson("ada"); + // The phone reads the person's organizations once for a sign-in: read again, so a test's own list is the one used. + await rereadOrganizations(); +}); +afterEach(() => { + running?.(); + running = undefined; }); afterAll(() => { server.stop(true); @@ -142,42 +224,113 @@ test("an organization with push off doesn't keep the others from reaching the ph expect(registered).toEqual(["org_work phone_1 ExponentPushToken[first]"]); }); +test("signed in, the phone registers once in each organization, though Expo tells the app the token it just asked for", async () => { + keep(); + await settle(300); + // Build 7 registered again on every telling: thousands here, not two. + expect(registered.sort()).toEqual([ + "org_home phone_1 ExponentPushToken[first]", + "org_work phone_1 ExponentPushToken[first]", + ]); + expect(deviceTokenAsks).toBe(1); +}); + test("signed in, the phone registers now, again when Expo changes its token, and again on moving organization; stopping ends it", async () => { - const stop = keepPushRegistered(); + const stop = keep(); await settle(); expect(registered.length).toBe(2); registered.length = 0; - pushToken = "ExponentPushToken[second]"; - for (const listener of tokenListeners) listener(); + deviceToken = "second"; + tellListeners("second"); await settle(); expect(registered.sort()).toEqual([ "org_home phone_1 ExponentPushToken[second]", "org_work phone_1 ExponentPushToken[second]", ]); + // Registered with the token Expo handed over, never asking the phone again (which would tell the listener again). + expect(deviceTokenAsks).toBe(1); + // Told the same token again, there is nothing new to register. registered.length = 0; + tellListeners("second"); + await settle(); + expect(registered).toEqual([]); + organizations = ["org_work", "org_home", "org_new"]; await chooseOrganization("org_home"); await settle(); expect(registered.map((each) => each.split(" ")[0]).sort()).toContain( "org_new", ); + expect(deviceTokenAsks).toBe(1); stop(); expect(tokenListeners.size).toBe(0); registered.length = 0; - for (const listener of tokenListeners) listener(); + tellListeners("third"); await chooseOrganization("org_work"); await settle(); expect(registered).toEqual([]); }); +test("one registration runs at a time: whatever comes during it makes one more, with the newest token", async () => { + answerAfterMs = 40; + keep(); + await settle(20); + // Ten changes of token and a move, all while the first registration is still going. + for (let each = 1; each <= 10; each++) { + deviceToken = `token_${each}`; + tellListeners(deviceToken); + } + await chooseOrganization("org_home"); + await settle(600); + expect(mostInFlight).toBe(1); + expect(registered.sort()).toEqual([ + "org_home phone_1 ExponentPushToken[first]", + "org_home phone_1 ExponentPushToken[token_10]", + "org_work phone_1 ExponentPushToken[first]", + "org_work phone_1 ExponentPushToken[token_10]", + ]); +}); + +test("refused as too many, the phone waits out Retry-After before it registers again", async () => { + rateLimited = 1; + retryAfter = "1"; + keep(); + await settle(200); + // Refused once, and the other organizations aren't tried: the limit is on the phone, not on the organization. + expect(attempts).toBe(1); + expect(registered).toEqual([]); + + // A new token while it waits is kept for later, not sent now. + deviceToken = "second"; + tellListeners("second"); + await settle(500); + expect(attempts).toBe(1); + + await settle(700); + expect(registered.sort()).toEqual([ + "org_home phone_1 ExponentPushToken[second]", + "org_work phone_1 ExponentPushToken[second]", + ]); + expect(attempts).toBe(3); +}); + +test("refused as too many with no Retry-After, the phone still waits before it registers again", async () => { + rateLimited = 100; + keep(); + await settle(200); + tellListeners("second"); + await chooseOrganization("org_home"); + await settle(800); + expect(attempts).toBe(1); +}); + test("a phone the person didn't turn notifications on for is left alone, and never asked", async () => { permission = "undetermined"; - const stop = keepPushRegistered(); + keep(); await settle(); - stop(); expect(registered).toEqual([]); expect(askedPermission).toBe(0); }); diff --git a/mobile/tests/oauth.test.ts b/mobile/tests/oauth.test.ts index 4bbc4f262b..0a6137cbcb 100644 --- a/mobile/tests/oauth.test.ts +++ b/mobile/tests/oauth.test.ts @@ -196,9 +196,10 @@ test("a token answer gives the access token, the new refresh token and how long expect(() => readGrant({ refresh_token: "obr_2" })).toThrow(SignInError); }); -test("a refused refresh ends the sign-in; a server that is down does not", () => { +test("a refused refresh ends the sign-in; a server that is down, or a rate limit, does not", () => { expect(signInEnded(400)).toBe(true); expect(signInEnded(401)).toBe(true); + expect(signInEnded(429)).toBe(false); expect(signInEnded(500)).toBe(false); expect(signInEnded(503)).toBe(false); }); diff --git a/mobile/tests/with-packages/rate-limited-sign-in.check.ts b/mobile/tests/with-packages/rate-limited-sign-in.check.ts new file mode 100644 index 0000000000..a6af9ce37d --- /dev/null +++ b/mobile/tests/with-packages/rate-limited-sign-in.check.ts @@ -0,0 +1,104 @@ +/** + * Refused as too many requests (429), sign-in says it couldn't reach OpenBot, and keeps the sign-in it has (src/auth.ts). + * A rate limit is not a server too old to sign the app in: build 7, shut out by the deployment's rate limit, told the + * person to ask an admin to update OpenBot. And a refresh refused as too many is not the sign-in being over: the + * refresh token is kept, and tried again later. + * + * Sign-in runs as on the phone, against a stand-in OpenBot that answers 429 the way the deployment's rate limit does: + * its own page, not the API's problem. + */ + +import { afterAll, beforeEach, expect, mock, test } from "bun:test"; +import { createHash, randomBytes } from "node:crypto"; +import appConfig from "../../app.config"; + +/** Whether the stand-in OpenBot is refusing everything as too many. */ +let limited = true; + +const tooMany = () => + new Response("Too many requests", { + status: 429, + headers: { "content-type": "text/html", "retry-after": "60" }, + }); +const server = Bun.serve({ + port: 0, + async fetch(request) { + if (limited) return tooMany(); + const url = new URL(request.url); + if (url.pathname === "/.well-known/oauth-authorization-server/api/auth") + return Response.json({ + authorization_endpoint: `${origin}/api/auth/oauth2/authorize`, + token_endpoint: `${origin}/api/auth/oauth2/token`, + scopes_supported: ["offline_access"], + code_challenge_methods_supported: ["S256"], + }); + // The token endpoint alone is limited: the refresh below is refused as too many. + if (url.pathname === "/api/auth/oauth2/token") return tooMany(); + return new Response(null, { status: 404 }); + }, +}); +const origin = `http://127.0.0.1:${server.port}`; +afterAll(() => { + server.stop(true); +}); + +/** The phone's secure store. */ +const secure = new Map(); + +mock.module("expo-secure-store", () => ({ + getItemAsync: async (key: string) => secure.get(key) ?? null, + setItemAsync: async (key: string, value: string) => { + secure.set(key, value); + }, + deleteItemAsync: async (key: string) => { + secure.delete(key); + }, +})); +mock.module("expo-crypto", () => ({ + getRandomBytes: (size: number) => new Uint8Array(randomBytes(size)), + digestStringAsync: async (_algorithm: string, value: string) => + createHash("sha256").update(value).digest("base64"), + CryptoDigestAlgorithm: { SHA256: "SHA-256" }, + CryptoEncoding: { BASE64: "base64" }, + randomUUID: () => crypto.randomUUID(), +})); +mock.module("expo-web-browser", () => ({ + openAuthSessionAsync: async () => ({ type: "cancel" }), +})); +mock.module("expo-constants", () => ({ + default: { expoConfig: appConfig }, +})); + +process.env.EXPO_PUBLIC_SERVER_URL = origin; +(globalThis as { __DEV__?: boolean }).__DEV__ = true; +const { authClient, signIn } = await import("../../src/auth"); +const { SERVER_TOO_OLD } = await import("../../src/oauth"); + +/** Where auth.ts keeps this OpenBot's refresh token. */ +const REFRESH_TOKEN_KEY = `openbot-127.0.0.1-${server.port}-refresh-token`; + +beforeEach(() => { + secure.clear(); + limited = true; +}); + +test("refused as too many, signing in says it couldn't reach OpenBot, never that OpenBot needs updating", async () => { + const failure = await signIn().then( + () => undefined, + (error: unknown) => error, + ); + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toBe( + "Couldn't reach OpenBot. Try again in a moment.", + ); + expect((failure as Error).message).not.toBe(SERVER_TOO_OLD); +}); + +test("a refresh refused as too many keeps the sign-in", async () => { + limited = false; + secure.set(REFRESH_TOKEN_KEY, "refresh_kept"); + await expect(authClient.getAccessToken()).rejects.toThrow( + "Couldn't reach OpenBot. Try again in a moment.", + ); + expect(secure.get(REFRESH_TOKEN_KEY)).toBe("refresh_kept"); +}); From 84f10acac73db35dc4f946feafcf914fde825fc7 Mon Sep 17 00:00:00 2001 From: David McKay Date: Thu, 3 Dec 2026 09:31:08 -0800 Subject: [PATCH 2/2] Mobile push: stop the token listener registering in a loop, one registration at a time, and wait out a 429 Asking expo-notifications for the Expo push token without a device token asks the phone for one, and the phone then tells every push token listener. The listener asked again, so it told itself again: build 7 sent about 10,000 device registrations a minute until the rate limit blocked the phone. The listener now registers with the token it is handed and never asks the phone for one. A token already registered registers nothing. One registration runs at a time, and whatever asks during it makes one more after it, with the newest token. Refused as too many, the phone waits out Retry-After, or a wait that doubles from 30 seconds, before it tries again. Sign-in refused as too many now says it couldn't reach OpenBot, not that OpenBot needs updating, and a refresh refused as too many no longer ends the sign-in. --- mobile/src/api/request.ts | 20 +++++- mobile/src/auth.ts | 4 +- mobile/src/notifications.ts | 137 +++++++++++++++++++++++++++++++++--- mobile/src/oauth.ts | 5 +- 4 files changed, 152 insertions(+), 14 deletions(-) diff --git a/mobile/src/api/request.ts b/mobile/src/api/request.ts index bf08379c2d..3e09a28a30 100644 --- a/mobile/src/api/request.ts +++ b/mobile/src/api/request.ts @@ -41,8 +41,9 @@ import { } from "./generated/organizations/organizations"; /** - * A refusal from the server, with its status and the API's problem code when it gave one, and whether a refusal of - * this app as too old was for a security problem. + * A refusal from the server, with its status and the API's problem code when it gave one, whether a refusal of this + * app as too old was for a security problem, and how long the server asked to be left alone (its Retry-After, in + * milliseconds) when it said. */ export class ApiError extends Error { constructor( @@ -50,12 +51,25 @@ export class ApiError extends Error { readonly status: number, readonly code?: string, readonly security = false, + readonly retryAfterMs?: number, ) { super(message); this.name = "ApiError"; } } +/** A Retry-After header in milliseconds from now: seconds, or a date (RFC 9110). Undefined when there is none to read. */ +function readRetryAfter( + value: string | null, + now = Date.now(), +): number | undefined { + if (!value) return undefined; + const trimmed = value.trim(); + if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1000; + const date = Date.parse(trimmed); + return Number.isNaN(date) ? undefined : Math.max(0, date - now); +} + /** * The organization every request is in: the one the signed-in person is working in. A generated call is given this in * place of an id, and the request below fills in the id from the person's own organizations, read once for each sign-in @@ -416,6 +430,8 @@ export async function apiRequest( said ?? `Request failed (${response.status}).`, response.status, code, + false, + readRetryAfter(response.headers.get("retry-after")), ); } return body as T; diff --git a/mobile/src/auth.ts b/mobile/src/auth.ts index 6cc23d117c..3ec619443e 100644 --- a/mobile/src/auth.ts +++ b/mobile/src/auth.ts @@ -104,7 +104,9 @@ function loadMetadata(): Promise { } catch { throw new SignInError(UNREACHABLE); } - if (response.status >= 500) throw new SignInError(UNREACHABLE); + // Refused as too many (the deployment's rate limit) is not a server too old: it is one to try again in a moment. + if (response.status >= 500 || response.status === 429) + throw new SignInError(UNREACHABLE); if (!response.ok) throw new SignInError(SERVER_TOO_OLD); return readMetadata(await response.json().catch(() => null), __DEV__); })(); diff --git a/mobile/src/notifications.ts b/mobile/src/notifications.ts index 54afa231e4..aa5a0244c1 100644 --- a/mobile/src/notifications.ts +++ b/mobile/src/notifications.ts @@ -14,7 +14,26 @@ import { import { deleteDevice, registerDevice } from "./api/generated/devices/devices"; const key = "openbot-device-id"; -export async function registerPush() { + +/** A device push token as one string, to tell whether Expo handed over a token the phone has already registered. */ +const tokenKey = (device: Notifications.DevicePushToken) => + typeof device.data === "string" ? device.data : JSON.stringify(device.data); + +/** The device push token this phone last registered with, while the app runs. */ +let registeredDevice: Notifications.DevicePushToken | undefined; + +/** + * Register the phone for push, in every organization the person is in. With the device push token Expo handed to a + * push token listener (`devicePushToken`), that token is registered; without one, the phone is asked for its token. + * + * Asking the phone for its token tells every push token listener the token it gave, changed or not (expo-notifications' + * native PushTokenModule sends `onDevicePushToken` after each fetch, on iOS and Android). So a listener passes the token + * it was handed, and is never the one that asks: build 7 asked from inside its listener, which told the listener again, + * and registered some 10,000 times a minute until the deployment's rate limit shut the phone out. + */ +export async function registerPush( + devicePushToken?: Notifications.DevicePushToken, +) { if (!Device.isDevice) throw new Error( "Register push notifications on a physical device using a signed development build.", @@ -38,8 +57,11 @@ export async function registerPush() { permission = await Notifications.requestPermissionsAsync(); if (permission.status !== "granted") throw new Error("Notification permission was not granted."); + const device = + devicePushToken ?? (await Notifications.getDevicePushTokenAsync()); const { data: token } = await Notifications.getExpoPushTokenAsync({ projectId, + devicePushToken: device, }); let id = await SecureStore.getItemAsync(key); if (!id) { @@ -49,22 +71,28 @@ export async function registerPush() { // Registered under the id this install made, in every organization the person is in, so a Bot in any of them can // reach the phone, and sign-out takes it off each (unregisterPush). Sent again, a token Expo has changed replaces // the old one rather than adding a second phone. - const device = { token, projectId, platform: Platform.OS }; + const registration = { token, projectId, platform: Platform.OS }; const held = await organizationsHeld(); const where = held.length > 0 ? held.map((each) => each.id) : [ORGANIZATION_ID]; const failures: unknown[] = []; for (const organization of where) { try { - await registerDevice(organization, ME, id, device); + await registerDevice(organization, ME, id, registration); } catch (error) { + // Refused as too many: the limit is on the phone, so the other organizations would be refused too. + if (tooMany(error)) throw error; failures.push(error); } } // Registered nowhere: say why. Refused by some organizations only (one that turned push off), the rest still reach it. if (failures.length === where.length) throw failures[0]; + registeredDevice = device; return id; } + +const tooMany = (error: unknown): error is ApiError => + error instanceof ApiError && error.status === 429; /** * Whether this phone gets push notifications: the person allowed them, and the app registered the * phone (it keeps the id it registered under until sign-out takes it off). @@ -80,21 +108,112 @@ export async function pushTurnedOn(): Promise { * notifications on for: a push token Expo changed since replaces the old one, and a phone the server * dropped (Expo said it stopped taking them) is registered again. Never asks for permission. */ -export async function renewPush(): Promise { - if (await pushTurnedOn()) await registerPush(); +export async function renewPush( + devicePushToken?: Notifications.DevicePushToken, +): Promise { + if (await pushTurnedOn()) await registerPush(devicePushToken); } +/** + * A registration asked for: with the newest token Expo handed over, if one asked; whether anything but a token asked + * (`always`: a start or a move registers even with the token already registered); and whether to ask the phone for its + * token rather than use the one last registered (`fresh`: a start, so a token changed while the app was closed is sent). + */ +type Wanted = { + device?: Notifications.DevicePushToken; + always: boolean; + fresh: boolean; +}; +/** Two asks as one: the newer token, and every reason either had. */ +const together = (older: Wanted, newer: Wanted): Wanted => ({ + device: newer.device ?? older.device, + always: older.always || newer.always, + fresh: older.fresh || newer.fresh, +}); + +/** Refused as too many with no Retry-After, the first wait; it doubles with each refusal in a row, up to the longest. */ +const FIRST_WAIT_MS = 30_000; +const LONGEST_WAIT_MS = 30 * 60_000; + /** * Keep the phone registered while somebody is signed in: now, each time they come to work in another organization * (one they just joined is registered in too), and each time the phone's push token changes. Never asks for * permission: a phone the person didn't turn notifications on for is left alone. Returns how to stop. + * + * One registration runs at a time. Whatever asks for one while it runs (a move, a token) makes one more after it, with + * the newest token, however many asked. Told a token the phone has already registered (Expo tells the listener the + * token each time the phone is asked for it), it registers nothing. Refused as too many, it waits out the server's + * Retry-After, or a wait that doubles with each refusal, then tries once more. */ export function keepPushRegistered(): () => void { - const renew = () => void renewPush().catch(() => {}); - renew(); - const leaveMoves = onOrganizationMoved(renew); - const tokens = Notifications.addPushTokenListener(renew); + let stopped = false; + let running = false; + /** The registration asked for next, everything that asked for it since the last one started taken together. */ + let next: Wanted | undefined; + let waitUntil = 0; + let refusals = 0; + let timer: ReturnType | undefined; + + const ask = (wanted: Wanted) => { + if (stopped) return; + next = next ? together(next, wanted) : wanted; + void run(); + }; + + async function run(): Promise { + if (running || stopped || !next) return; + const wait = waitUntil - Date.now(); + if (wait > 0) { + timer ??= setTimeout(() => { + timer = undefined; + void run(); + }, wait); + return; + } + const now = next; + next = undefined; + // Only told the token it already has: nothing to register. + if ( + !now.always && + now.device && + registeredDevice && + tokenKey(now.device) === tokenKey(registeredDevice) + ) + return; + running = true; + try { + // A move registers with the token already known, so the phone isn't asked for it (and the listener told) again. + await renewPush(now.device ?? (now.fresh ? undefined : registeredDevice)); + refusals = 0; + } catch (error) { + if (tooMany(error)) { + refusals += 1; + const backOff = Math.min( + FIRST_WAIT_MS * 2 ** (refusals - 1), + LONGEST_WAIT_MS, + ); + waitUntil = + Date.now() + Math.min(error.retryAfterMs ?? backOff, LONGEST_WAIT_MS); + // Tried again once the wait is over, with whatever asked in the meantime. + next = next ? together(now, next) : now; + } + // Any other failure is left until something asks again, as before. + } finally { + running = false; + } + void run(); + } + + ask({ always: true, fresh: true }); + const leaveMoves = onOrganizationMoved(() => + ask({ always: true, fresh: false }), + ); + const tokens = Notifications.addPushTokenListener((device) => + ask({ device, always: false, fresh: false }), + ); return () => { + stopped = true; + if (timer) clearTimeout(timer); leaveMoves(); tokens.remove(); }; diff --git a/mobile/src/oauth.ts b/mobile/src/oauth.ts index ba3ae223d9..88480380a4 100644 --- a/mobile/src/oauth.ts +++ b/mobile/src/oauth.ts @@ -255,8 +255,9 @@ export function readGrant(body: unknown): Grant { /** * Whether a refused token request means the sign-in is over (the refresh token was revoked, used twice, or its owner - * removed), as opposed to the server being unreachable or failing for a while, when the sign-in may still be good. + * removed), as opposed to the server being unreachable, failing for a while, or refusing too many requests (429), when + * the sign-in may still be good. */ export function signInEnded(status: number): boolean { - return status >= 400 && status < 500; + return status >= 400 && status < 500 && status !== 429; }