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
9 changes: 9 additions & 0 deletions mobile-push-relay/src/copy.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,12 @@
// the caller or the app. It names no command, session, prompt or file.
export const NOTIFICATION_TITLE = 'OX needs your approval';
export const NOTIFICATION_BODY = 'Open OX to review this request.';

// Session copy is fixed per kind and matches the stateless APNs worker
// (`mobile-push-worker/src/worker.js`), so both delivery paths show the same
// words for the same event.
export const SESSION_COPY = Object.freeze({
finished: Object.freeze({ title: 'OX finished a session', body: 'Open OX to see the result.' }),
goal_reached: Object.freeze({ title: 'OX reached its goal', body: 'Open OX to see the result.' }),
failed: Object.freeze({ title: 'An OX session failed', body: 'Open OX to see what happened.' }),
});
68 changes: 46 additions & 22 deletions mobile-push-relay/src/fcm/adapter.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NOTIFICATION_BODY, NOTIFICATION_TITLE } from '../copy.js';
import { NOTIFICATION_BODY, NOTIFICATION_TITLE, SESSION_COPY } from '../copy.js';
import { InvalidInputError, TransportError } from '../errors.js';
import { readApprovalRequest } from '../input.js';
import { readApprovalRequest, readSessionRequest } from '../input.js';
import { delivered, expired, invalidRequest, invalidToken, providerAuth, transient } from '../outcome.js';
import {
FCM_AUTH_REASONS,
Expand All @@ -16,6 +16,8 @@ const MAX_TTL_SECONDS = 2_419_200;
const ACCESS_TOKEN_SKEW_MS = 60_000;
/** Never wait past the moment the alert stops being useful. */
export const FCM_REQUEST_TIMEOUT_MS = 10_000;
/** The tap action the pilot APK registers for every FCM alert. */
const CLICK_ACTION = 'dev.ox.mobile.action.APPROVAL';

const KNOWN_WORDS = new Set([
...FCM_INVALID_TOKEN_REASONS,
Expand All @@ -37,7 +39,38 @@ export function buildFcmMessage({ routingToken, approvalRef, pairingHint, ttlSec
priority: 'high',
ttl: `${ttlSeconds}s`,
notification: {
click_action: 'dev.ox.mobile.action.APPROVAL',
click_action: CLICK_ACTION,
proxy: 'DENY',
},
},
},
};
}

/**
* The session copy is fixed per known kind. Its data names the kind, the
* reference suffix a tap looks up and the required pairing hint. It carries no
* approval reference and nothing supplied by the host.
*/
function buildFcmSessionMessage({
routingToken,
kind,
sessionRef,
pairingHint,
ttlSeconds,
targetField = 'token',
}) {
const { title, body } = SESSION_COPY[kind];
return {
message: {
[targetField === 'fid' ? 'fid' : 'token']: routingToken,
notification: { title, body },
data: { kind, session_ref: sessionRef, pairing_hint: pairingHint },
android: {
priority: 'high',
ttl: `${ttlSeconds}s`,
notification: {
click_action: CLICK_ACTION,
proxy: 'DENY',
},
},
Expand Down Expand Up @@ -87,23 +120,17 @@ export class FcmPushAdapter {
this.#now = now;
}

/**
* @param {{ routingToken: string, approvalRef: string, expiresAt: Date|number, pairingHint?: string }} request
*/
async send(request) {
const parsed = readApprovalRequest(request);
if (parsed.expiresAtMs <= this.#now()) return expired('fcm');
const session = request !== null && typeof request === 'object' && Object.hasOwn(request, 'kind');
const { expiresAtMs, ...fields } = session ? readSessionRequest(request) : readApprovalRequest(request);
const message = { ...fields, targetField: this.#targetField };
const build = session ? buildFcmSessionMessage : buildFcmMessage;
if (expiresAtMs <= this.#now()) return expired('fcm');

// The ttl string only shrinks with the real value, so this probe is an
// upper bound: an oversized payload is refused before a credential is
// fetched for a send that could never happen.
const message = {
routingToken: parsed.routingToken,
approvalRef: parsed.approvalRef,
pairingHint: parsed.pairingHint,
targetField: this.#targetField,
};
const upperBound = JSON.stringify(buildFcmMessage({ ...message, ttlSeconds: MAX_TTL_SECONDS }));
const upperBound = JSON.stringify(build({ ...message, ttlSeconds: MAX_TTL_SECONDS }));
if (Buffer.byteLength(upperBound) > MAX_PAYLOAD_BYTES) {
return invalidRequest('fcm', 'payload_too_large');
}
Expand All @@ -114,15 +141,12 @@ export class FcmPushAdapter {
// Getting an access token can mean a network refresh, so the expiry is
// checked again before anything is sent or timed.
const nowMs = this.#now();
if (parsed.expiresAtMs <= nowMs) return expired('fcm');
if (expiresAtMs <= nowMs) return expired('fcm');

const ttlSeconds = Math.min(
MAX_TTL_SECONDS,
Math.floor((parsed.expiresAtMs - nowMs) / 1000),
);
const body = JSON.stringify(buildFcmMessage({ ...message, ttlSeconds }));
const ttlSeconds = Math.min(MAX_TTL_SECONDS, Math.floor((expiresAtMs - nowMs) / 1000));
const body = JSON.stringify(build({ ...message, ttlSeconds }));

const timeoutMs = Math.min(FCM_REQUEST_TIMEOUT_MS, parsed.expiresAtMs - nowMs);
const timeoutMs = Math.min(FCM_REQUEST_TIMEOUT_MS, expiresAtMs - nowMs);

let response;
try {
Expand Down
71 changes: 63 additions & 8 deletions mobile-push-relay/src/input.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { SESSION_COPY } from './copy.js';
import { InvalidInputError } from './errors.js';
import { EVENT_REF_PATTERN, PROVIDER_TOKEN_PATTERN, isCanonicalBase64Url32 } from './values.js';
import {
EVENT_REF_PATTERN,
PROVIDER_TOKEN_PATTERN,
isCanonicalBase64Url32,
sessionRefSuffix,
} from './values.js';

const FIELDS = new Set(['routingToken', 'approvalRef', 'expiresAt', 'pairingHint']);
const SESSION_FIELDS = new Set(['routingToken', 'kind', 'eventRef', 'expiresAt', 'pairingHint']);

/**
* Validate the only input an adapter accepts: where to deliver, which opaque
Expand Down Expand Up @@ -31,6 +38,60 @@ export function readApprovalRequest(input) {
throw new InvalidInputError('pairingHint');
}

return Object.freeze({
routingToken,
approvalRef,
expiresAtMs: readExpiresAtMs(expiresAt),
...(pairingHint === undefined ? {} : { pairingHint }),
});
}

/**
* Validate the only input a session adapter accepts: where to deliver, which
* known session kind, the host-minted `s1_` reference, when delivery stops
* being useful and the required pairing hint. A session notification carries
* no approval reference and no caller-supplied copy; unknown fields are
* rejected before an access token or transport is touched.
*
* @param {unknown} input
* @returns {{
* routingToken: string,
* kind: 'finished'|'failed'|'goal_reached',
* sessionRef: string,
* expiresAtMs: number,
* pairingHint: string,
* }}
*/
export function readSessionRequest(input) {
if (input === null || typeof input !== 'object' || Array.isArray(input)) {
throw new InvalidInputError('session request');
}
for (const field of Object.keys(input)) {
// The field name itself is caller input and is never repeated back.
if (!SESSION_FIELDS.has(field)) throw new InvalidInputError('field');
}

const { routingToken, kind, eventRef, expiresAt, pairingHint } = input;
if (typeof routingToken !== 'string' || !PROVIDER_TOKEN_PATTERN.test(routingToken)) {
throw new InvalidInputError('routingToken');
}
if (typeof kind !== 'string' || !Object.hasOwn(SESSION_COPY, kind)) {
throw new InvalidInputError('kind');
}
const sessionRef = sessionRefSuffix(eventRef);
if (sessionRef === undefined) throw new InvalidInputError('eventRef');
if (!isCanonicalBase64Url32(pairingHint)) throw new InvalidInputError('pairingHint');

return Object.freeze({
routingToken,
kind,
sessionRef,
expiresAtMs: readExpiresAtMs(expiresAt),
pairingHint,
});
}

function readExpiresAtMs(expiresAt) {
let expiresAtMs;
if (expiresAt instanceof Date) {
expiresAtMs = expiresAt.getTime();
Expand All @@ -40,11 +101,5 @@ export function readApprovalRequest(input) {
throw new InvalidInputError('expiresAt');
}
if (!Number.isSafeInteger(expiresAtMs)) throw new InvalidInputError('expiresAt');

return Object.freeze({
routingToken,
approvalRef,
expiresAtMs,
...(pairingHint === undefined ? {} : { pairingHint }),
});
return expiresAtMs;
}
14 changes: 14 additions & 0 deletions mobile-push-relay/src/values.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,17 @@ export function isCanonicalBase64Url32(value) {
return typeof value === 'string' && value.length === 43 &&
Buffer.from(value, 'base64url').toString('base64url') === value;
}

/** A session alert reference is `s1_` plus one canonical 32-byte base64url value. */
export const SESSION_REF_PREFIX = 's1_';

/**
* The canonical 43-character suffix of a session event reference, or
* `undefined` when the value is not exactly `s1_` followed by one canonical
* 32-byte base64url digest.
*/
export function sessionRefSuffix(value) {
if (typeof value !== 'string' || !value.startsWith(SESSION_REF_PREFIX)) return undefined;
const suffix = value.slice(SESSION_REF_PREFIX.length);
return isCanonicalBase64Url32(suffix) ? suffix : undefined;
}
Loading