Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions mobile/src/api/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,21 +41,35 @@ 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(
message: string,
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
Expand Down Expand Up @@ -416,6 +430,8 @@ export async function apiRequest<T>(
said ?? `Request failed (${response.status}).`,
response.status,
code,
false,
readRetryAfter(response.headers.get("retry-after")),
);
}
return body as T;
Expand Down
4 changes: 3 additions & 1 deletion mobile/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ function loadMetadata(): Promise<Metadata> {
} 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__);
})();
Expand Down
137 changes: 128 additions & 9 deletions mobile/src/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand All @@ -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) {
Expand All @@ -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).
Expand All @@ -80,21 +108,112 @@ export async function pushTurnedOn(): Promise<boolean> {
* 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<void> {
if (await pushTurnedOn()) await registerPush();
export async function renewPush(
devicePushToken?: Notifications.DevicePushToken,
): Promise<void> {
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<typeof setTimeout> | undefined;

const ask = (wanted: Wanted) => {
if (stopped) return;
next = next ? together(next, wanted) : wanted;
void run();
};

async function run(): Promise<void> {
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();
};
Expand Down
5 changes: 3 additions & 2 deletions mobile/src/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Loading
Loading