Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(push): deliver to APNs and FCM, refusing by name when credentials are absent
Beenu Arora554471573d39
diff --git a/services/realtime/src/native-push.ts b/services/realtime/src/native-push.tsnew file mode 100644index 000000000..c1c64d747--- /dev/null+++ b/services/realtime/src/native-push.ts@@ -0,0 +1,262 @@+/**+ * Deliver a push to a native device, through APNs or FCM.+ *+ * Depth 9.6. `push.ts` sends every subscription through `webpush`, which is+ * correct for a browser and wrong for a native token: `web-push` signs a+ * VAPID JWT and POSTs to the endpoint URL, and a bare APNs device token is+ * not a URL. So before this, a native subscription stored by `apps/mobile`+ * was accepted, counted, and then failed on every send — which is the worst+ * of the three possible states, because the subscription count looked+ * healthy.+ *+ * How a native record is recognised+ * ---------------------------------+ * `apps/mobile/src/lib/push.ts` puts the device token in the `endpoint`+ * slot and the platform in the key fields, deliberately, so there is one+ * subscription table rather than two. That convention is the detector:+ * `keys.p256dh` of `"ios"` or `"android"` means native, and a real Web Push+ * `p256dh` is a 65-byte base64url public key that cannot collide with+ * either word.+ *+ * Credentials+ * -----------+ * Neither provider is reachable without credentials the maintainer has to+ * supply — an APNs `.p8` signing key with its key and team ids, and an FCM+ * service account. The plan records both as maintainer items. So this+ * module is written to work the day they arrive and, until then, to+ * **refuse by name**: `classify()` returns `not_configured` listing exactly+ * which variables are missing, the caller records that, and nothing+ * pretends a notification was delivered.+ *+ * That distinction is the whole point. "Delivered", "the device is gone",+ * and "this deployment cannot send to iOS at all" are three different facts+ * and an operator has to be able to tell them apart — a native path that+ * silently reported success would make a responder believe they are+ * covered.+ */++import { createSign } from 'node:crypto';++export type NativePlatform = 'ios' | 'android';++export interface NativeRecord {+ /** The device token. See the module header for why it lives here. */+ endpoint: string;+ platform: NativePlatform;+}++export interface NativePayload {+ title: string;+ body: string;+ data?: Record<string, unknown>;+ /** APNs collapse id / FCM collapse key. */+ tag?: string;+ critical?: boolean;+}++export type NativeOutcome =+ | { kind: 'delivered' }+ /** The device is gone. The caller prunes the subscription. */+ | { kind: 'unregistered'; reason: string }+ /** Transient. The caller counts an error and keeps the subscription. */+ | { kind: 'failed'; reason: string }+ /** This deployment cannot send to this platform at all. Never a success. */+ | { kind: 'not_configured'; missing: string[] };++const APNS_VARS = ['APNS_KEY_ID', 'APNS_TEAM_ID', 'APNS_PRIVATE_KEY', 'APNS_BUNDLE_ID'] as const;+const FCM_VARS = ['FCM_PROJECT_ID', 'FCM_SERVICE_ACCOUNT_JSON'] as const;++/**+ * Whether a stored subscription is a native device token.+ *+ * Exported so a test can assert the convention in both directions: a real+ * Web Push subscription must not be mistaken for a native one, because+ * routing a browser to APNs would break a path that works today.+ */+export function nativePlatformOf(keys: { p256dh?: string; auth?: string }): NativePlatform | null {+ const marker = (keys.p256dh ?? '').trim().toLowerCase();+ if (marker === 'ios' || marker === 'android') return marker;+ return null;+}++/** Which credentials a platform needs, and which of them are absent. */+export function missingCredentials(+ platform: NativePlatform,+ env: NodeJS.ProcessEnv = process.env,+): string[] {+ const names = platform === 'ios' ? APNS_VARS : FCM_VARS;+ return names.filter((name) => !(env[name] ?? '').trim());+}++/**+ * The APNs provider JWT: ES256 over `{iss, iat}` with the key id in the+ * header. Built here rather than pulled from a library because it is+ * fifteen lines and this service's dependency surface is deliberately+ * small — the same reasoning `services/mcp` applies to its arg parser.+ */+export function apnsProviderToken(env: NodeJS.ProcessEnv = process.env, now = Date.now()): string {+ const keyId = (env.APNS_KEY_ID ?? '').trim();+ const teamId = (env.APNS_TEAM_ID ?? '').trim();+ const privateKey = (env.APNS_PRIVATE_KEY ?? '').trim().replace(/\\n/g, '\n');+ const b64 = (value: unknown) =>+ Buffer.from(JSON.stringify(value)).toString('base64url');+ const header = b64({ alg: 'ES256', kid: keyId });+ const claims = b64({ iss: teamId, iat: Math.floor(now / 1000) });+ const signer = createSign('SHA256');+ signer.update(`${header}.${claims}`);+ const signature = signer.sign({ key: privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64url');+ return `${header}.${claims}.${signature}`;+}++export interface NativeSenderOptions {+ env?: NodeJS.ProcessEnv;+ /** Injected so tests drive the real request shape without a network. */+ fetchImpl?: typeof fetch;+ /** Overridable so a test does not have to reach Apple's or Google's host. */+ apnsHost?: string;+ fcmHost?: string;+ /** Injected so the FCM access token can be stubbed; see `fcmAccessToken`. */+ accessToken?: () => Promise<string>;+}++/**+ * Send one notification to one device.+ *+ * Returns an outcome rather than throwing, because the caller has to+ * distinguish three things and an exception collapses them into one.+ */+export async function sendNative(+ record: NativeRecord,+ payload: NativePayload,+ options: NativeSenderOptions = {},+): Promise<NativeOutcome> {+ const env = options.env ?? process.env;+ const missing = missingCredentials(record.platform, env);+ if (missing.length > 0) {+ // Never a success and never a silent failure. An operator reading+ // "APNS_PRIVATE_KEY is unset" knows what to do.+ return { kind: 'not_configured', missing };+ }+ const doFetch = options.fetchImpl ?? fetch;++ if (record.platform === 'ios') {+ const host = options.apnsHost ?? 'https://api.push.apple.com';+ let res: Response;+ try {+ res = await doFetch(`${host}/3/device/${encodeURIComponent(record.endpoint)}`, {+ method: 'POST',+ headers: {+ authorization: `bearer ${apnsProviderToken(env)}`,+ 'apns-topic': (env.APNS_BUNDLE_ID ?? '').trim(),+ 'apns-push-type': 'alert',+ // 10 is "deliver immediately"; 5 lets the OS batch. A containment+ // approval is the former, everything else the latter.+ 'apns-priority': payload.critical ? '10' : '5',+ ...(payload.tag ? { 'apns-collapse-id': payload.tag.slice(0, 64) } : {}),+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ aps: { alert: { title: payload.title, body: payload.body }, sound: 'default' },+ ...(payload.data ?? {}),+ }),+ });+ } catch (err) {+ return { kind: 'failed', reason: `APNs unreachable: ${String(err)}` };+ }+ if (res.status === 200) return { kind: 'delivered' };+ // 410 is APNs' own "this token is no longer active". 400 with+ // BadDeviceToken means the same thing and is what a simulator token+ // produces, so both prune rather than retrying forever.+ const text = await res.text().catch(() => '');+ if (res.status === 410 || text.includes('BadDeviceToken') || text.includes('Unregistered')) {+ return { kind: 'unregistered', reason: `APNs ${res.status} ${text.slice(0, 120)}` };+ }+ return { kind: 'failed', reason: `APNs ${res.status} ${text.slice(0, 200)}` };+ }++ // Android / FCM HTTP v1.+ const projectId = (env.FCM_PROJECT_ID ?? '').trim();+ const host = options.fcmHost ?? 'https://fcm.googleapis.com';+ let token: string;+ try {+ token = options.accessToken ? await options.accessToken() : await fcmAccessToken(env, doFetch);+ } catch (err) {+ return { kind: 'failed', reason: `FCM access token: ${String(err)}` };+ }+ let res: Response;+ try {+ res = await doFetch(`${host}/v1/projects/${projectId}/messages:send`, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify({+ message: {+ token: record.endpoint,+ notification: { title: payload.title, body: payload.body },+ // FCM data values must be strings; anything else is a 400 the+ // caller cannot act on.+ data: Object.fromEntries(+ Object.entries(payload.data ?? {}).map(([k, v]) => [k, String(v)]),+ ),+ android: {+ priority: payload.critical ? 'HIGH' : 'NORMAL',+ ...(payload.tag ? { collapse_key: payload.tag } : {}),+ },+ },+ }),+ });+ } catch (err) {+ return { kind: 'failed', reason: `FCM unreachable: ${String(err)}` };+ }+ if (res.ok) return { kind: 'delivered' };+ const text = await res.text().catch(() => '');+ if (res.status === 404 || text.includes('UNREGISTERED') || text.includes('NOT_FOUND')) {+ return { kind: 'unregistered', reason: `FCM ${res.status} ${text.slice(0, 120)}` };+ }+ return { kind: 'failed', reason: `FCM ${res.status} ${text.slice(0, 200)}` };+}++/**+ * Exchange the FCM service account for an access token.+ *+ * Google's own libraries do this; pulling one in for a single JWT exchange+ * would add a large dependency to a service that deliberately has few.+ */+export async function fcmAccessToken(+ env: NodeJS.ProcessEnv,+ doFetch: typeof fetch,+ now = Date.now(),+): Promise<string> {+ const raw = (env.FCM_SERVICE_ACCOUNT_JSON ?? '').trim();+ const account = JSON.parse(raw) as { client_email?: string; private_key?: string; token_uri?: string };+ if (!account.client_email || !account.private_key) {+ throw new Error('FCM_SERVICE_ACCOUNT_JSON has no client_email or private_key');+ }+ const b64 = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url');+ const issued = Math.floor(now / 1000);+ const header = b64({ alg: 'RS256', typ: 'JWT' });+ const claims = b64({+ iss: account.client_email,+ scope: 'https://www.googleapis.com/auth/firebase.messaging',+ aud: account.token_uri ?? 'https://oauth2.googleapis.com/token',+ iat: issued,+ exp: issued + 3600,+ });+ const signer = createSign('RSA-SHA256');+ signer.update(`${header}.${claims}`);+ const assertion = `${header}.${claims}.${signer.sign(account.private_key).toString('base64url')}`;++ const res = await doFetch(account.token_uri ?? 'https://oauth2.googleapis.com/token', {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',+ assertion,+ }).toString(),+ });+ if (!res.ok) {+ throw new Error(`token endpoint returned ${res.status}`);+ }+ const body = (await res.json()) as { access_token?: string };+ if (!body.access_token) throw new Error('token endpoint returned no access_token');+ return body.access_token;+}diff --git a/services/realtime/src/push.ts b/services/realtime/src/push.tsindex c8b33d0de..984d2e666 100644--- a/services/realtime/src/push.ts+++ b/services/realtime/src/push.ts@@ -25,6 +25,7 @@ import type { Logger } from 'pino';import type { Request, Response } from 'express';import webpush from 'web-push';import crypto from 'crypto';+import { nativePlatformOf, sendNative } from './native-push.js';export interface SubscriptionPayload {endpoint: string;@@ -326,6 +327,52 @@ export class PushManager {): Promise<{ delivered: boolean; removed: boolean }> {if (!this.enabled) return { delivered: false, removed: false };+ // Depth 9.6. A native device token is not a URL, and `web-push` signs a+ // VAPID JWT and POSTs to one — so before this split a subscription saved+ // by `apps/mobile` was accepted, counted, and failed on every send. That+ // is the worst of the three states, because the subscription count looked+ // healthy while no responder's phone ever rang.+ const nativePlatform = nativePlatformOf(record.keys);+ if (nativePlatform) {+ const outcome = await sendNative(+ { endpoint: record.endpoint, platform: nativePlatform },+ {+ title: notification.title,+ body: notification.body,+ tag: notification.tag,+ critical: notification.severity === 'critical',+ data: {+ ...(notification.url ? { url: notification.url } : {}),+ ...(notification.alert_id ? { alert_id: notification.alert_id } : {}),+ ...(notification.case_id ? { case_id: notification.case_id } : {}),+ ...(notification.approval_id ? { approval_id: notification.approval_id } : {}),+ },+ },+ );+ if (outcome.kind === 'delivered') {+ record.last_seen_at = this.now().toISOString();+ await this.redis.set(key('sub', record.id), JSON.stringify(record), 'EX', SUB_TTL_SECONDS);+ return { delivered: true, removed: false };+ }+ if (outcome.kind === 'unregistered') {+ await this.removeSubscriptionById(record.tenant_id, record.id);+ this.log.info({ id: record.id, reason: outcome.reason }, 'pruned dead native push token');+ return { delivered: false, removed: true };+ }+ if (outcome.kind === 'not_configured') {+ // Logged at warn, not debug: a deployment that stores native tokens+ // and cannot send to them is a responder who believes they are+ // covered and is not.+ this.log.warn(+ { id: record.id, platform: nativePlatform, missing: outcome.missing },+ 'native push is not configured; nothing was sent',+ );+ return { delivered: false, removed: false };+ }+ this.log.warn({ id: record.id, reason: outcome.reason }, 'native push delivery failed');+ return { delivered: false, removed: false };+ }+const payload = JSON.stringify(this.buildPayload(notification));try {await webpush.sendNotification(diff --git a/services/realtime/test/native-push.test.ts b/services/realtime/test/native-push.test.tsnew file mode 100644index 000000000..d4d9430ad--- /dev/null+++ b/services/realtime/test/native-push.test.ts@@ -0,0 +1,224 @@+/**+ * Native push: three outcomes that must never be collapsed into one.+ *+ * Depth 9.6. `push.ts` sent every subscription through `web-push`, which+ * signs a VAPID JWT and POSTs to the endpoint URL. A bare APNs device token+ * is not a URL, so a subscription saved by `apps/mobile` was accepted,+ * counted and failed on every send — the worst of the three possible+ * states, because the subscription count looked healthy while no+ * responder's phone ever rang.+ *+ * Asserted by name below:+ *+ * * a real Web Push subscription is **not** mistaken for a native one, in+ * both directions — routing a browser to APNs would break a path that+ * works today;+ * * missing credentials produce `not_configured` **naming each one**, never+ * a success and never a bare failure: a deployment that stores native+ * tokens and cannot send to them is a responder who believes they are+ * covered and is not;+ * * a dead token prunes and a transient error does not;+ * * the request this code really makes carries the headers APNs and FCM+ * require, asserted against the captured request rather than against a+ * mock that agrees with it.+ */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';++import {+ missingCredentials,+ nativePlatformOf,+ sendNative,+ type NativeOutcome,+} from '../src/native-push';++/** A real P-256 key pair, so the "not native" case uses a real p256dh. */+const { publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' });+const REAL_P256DH = publicKey.export({ type: 'spki', format: 'der' }).toString('base64url');++/** A throwaway EC key so the APNs provider JWT really signs. */+const APNS_KEY = crypto+ .generateKeyPairSync('ec', { namedCurve: 'prime256v1' })+ .privateKey.export({ type: 'pkcs8', format: 'pem' })+ .toString();++const APNS_ENV = {+ APNS_KEY_ID: 'ABC123DEFG',+ APNS_TEAM_ID: 'TEAM123456',+ APNS_PRIVATE_KEY: APNS_KEY,+ APNS_BUNDLE_ID: 'com.example.aisoc',+} as NodeJS.ProcessEnv;++const FCM_ENV = {+ FCM_PROJECT_ID: 'aisoc-test',+ FCM_SERVICE_ACCOUNT_JSON: JSON.stringify({+ client_email: '[email protected]',+ private_key: 'unused — the access token is injected',+ token_uri: 'https://oauth2.example/token',+ }),+} as NodeJS.ProcessEnv;++interface Captured {+ url: string;+ init: RequestInit;+}++function capturing(status: number, body = ''): { fetchImpl: typeof fetch; calls: Captured[] } {+ const calls: Captured[] = [];+ const fetchImpl = (async (url: unknown, init?: RequestInit) => {+ calls.push({ url: String(url), init: init ?? {} });+ return new Response(body, { status });+ }) as unknown as typeof fetch;+ return { fetchImpl, calls };+}++test('a real Web Push subscription is not mistaken for a native one', () => {+ assert.equal(nativePlatformOf({ p256dh: REAL_P256DH, auth: 'x' }), null);+ assert.equal(nativePlatformOf({}), null);+ assert.equal(nativePlatformOf({ p256dh: '' }), null);+});++test('the mobile app’s convention is recognised, case-insensitively', () => {+ assert.equal(nativePlatformOf({ p256dh: 'ios' }), 'ios');+ assert.equal(nativePlatformOf({ p256dh: 'Android' }), 'android');+});++test('missing credentials are named, one by one', () => {+ assert.deepEqual(missingCredentials('ios', {} as NodeJS.ProcessEnv), [+ 'APNS_KEY_ID',+ 'APNS_TEAM_ID',+ 'APNS_PRIVATE_KEY',+ 'APNS_BUNDLE_ID',+ ]);+ assert.deepEqual(missingCredentials('android', {} as NodeJS.ProcessEnv), [+ 'FCM_PROJECT_ID',+ 'FCM_SERVICE_ACCOUNT_JSON',+ ]);+ assert.deepEqual(missingCredentials('ios', APNS_ENV), []);+});++test('an unconfigured deployment refuses rather than reporting a delivery', async () => {+ const { fetchImpl, calls } = capturing(200);+ const outcome = await sendNative(+ { endpoint: 'token', platform: 'ios' },+ { title: 't', body: 'b' },+ { env: {} as NodeJS.ProcessEnv, fetchImpl },+ );+ assert.equal(outcome.kind, 'not_configured');+ assert.deepEqual((outcome as Extract<NativeOutcome, { kind: 'not_configured' }>).missing.length, 4);+ // Nothing was sent, and nothing was pruned either: the token is fine, the+ // deployment is not.+ assert.equal(calls.length, 0);+});++test('an APNs delivery carries the headers Apple requires', async () => {+ const { fetchImpl, calls } = capturing(200);+ const outcome = await sendNative(+ { endpoint: 'devicetoken123', platform: 'ios' },+ { title: 'Containment approval', body: 'isolate WKS-14', critical: true, tag: 'alert-1' },+ { env: APNS_ENV, fetchImpl, apnsHost: 'https://apns.example' },+ );+ assert.equal(outcome.kind, 'delivered');+ assert.equal(calls.length, 1);+ assert.equal(calls[0].url, 'https://apns.example/3/device/devicetoken123');+ const headers = calls[0].init.headers as Record<string, string>;+ assert.equal(headers['apns-topic'], 'com.example.aisoc');+ assert.equal(headers['apns-push-type'], 'alert');+ // A containment approval is "deliver immediately"; anything else lets the+ // OS batch.+ assert.equal(headers['apns-priority'], '10');+ assert.equal(headers['apns-collapse-id'], 'alert-1');+ assert.match(headers.authorization, /^bearer eyJ/);+});++test('a non-critical notification lets the OS batch it', async () => {+ const { fetchImpl, calls } = capturing(200);+ await sendNative(+ { endpoint: 'd', platform: 'ios' },+ { title: 't', body: 'b' },+ { env: APNS_ENV, fetchImpl, apnsHost: 'https://apns.example' },+ );+ assert.equal((calls[0].init.headers as Record<string, string>)['apns-priority'], '5');+});++test('APNs 410 prunes the token and a 429 does not', async () => {+ const gone = capturing(410, 'Unregistered');+ const limited = capturing(429, 'TooManyRequests');+ const a = await sendNative(+ { endpoint: 'd', platform: 'ios' },+ { title: 't', body: 'b' },+ { env: APNS_ENV, fetchImpl: gone.fetchImpl, apnsHost: 'https://apns.example' },+ );+ const b = await sendNative(+ { endpoint: 'd', platform: 'ios' },+ { title: 't', body: 'b' },+ { env: APNS_ENV, fetchImpl: limited.fetchImpl, apnsHost: 'https://apns.example' },+ );+ assert.equal(a.kind, 'unregistered');+ // Transient. Pruning here would lose a working device for a rate limit.+ assert.equal(b.kind, 'failed');+});++test('a BadDeviceToken 400 prunes, because it means the same thing', async () => {+ const { fetchImpl } = capturing(400, '{"reason":"BadDeviceToken"}');+ const outcome = await sendNative(+ { endpoint: 'd', platform: 'ios' },+ { title: 't', body: 'b' },+ { env: APNS_ENV, fetchImpl, apnsHost: 'https://apns.example' },+ );+ assert.equal(outcome.kind, 'unregistered');+});++test('an FCM message stringifies its data, because FCM rejects anything else', async () => {+ const { fetchImpl, calls } = capturing(200, '{"name":"ok"}');+ const outcome = await sendNative(+ { endpoint: 'fcm-token', platform: 'android' },+ { title: 't', body: 'b', data: { alert_id: 42, url: '/alerts/42' }, critical: true },+ {+ env: FCM_ENV,+ fetchImpl,+ fcmHost: 'https://fcm.example',+ accessToken: async () => 'injected-access-token',+ },+ );+ assert.equal(outcome.kind, 'delivered');+ assert.equal(calls[0].url, 'https://fcm.example/v1/projects/aisoc-test/messages:send');+ const body = JSON.parse(String(calls[0].init.body));+ assert.equal(body.message.token, 'fcm-token');+ // Numbers would be a 400 the caller cannot act on.+ assert.deepEqual(body.message.data, { alert_id: '42', url: '/alerts/42' });+ assert.equal(body.message.android.priority, 'HIGH');+});++test('FCM UNREGISTERED prunes and a 503 does not', async () => {+ const gone = capturing(404, '{"error":{"status":"UNREGISTERED"}}');+ const down = capturing(503, 'unavailable');+ const a = await sendNative(+ { endpoint: 't', platform: 'android' },+ { title: 't', body: 'b' },+ { env: FCM_ENV, fetchImpl: gone.fetchImpl, fcmHost: 'https://fcm.example', accessToken: async () => 'x' },+ );+ const b = await sendNative(+ { endpoint: 't', platform: 'android' },+ { title: 't', body: 'b' },+ { env: FCM_ENV, fetchImpl: down.fetchImpl, fcmHost: 'https://fcm.example', accessToken: async () => 'x' },+ );+ assert.equal(a.kind, 'unregistered');+ assert.equal(b.kind, 'failed');+});++test('an unreachable provider is a transient failure, not a dead token', async () => {+ const fetchImpl = (async () => {+ throw new Error('ECONNREFUSED');+ }) as unknown as typeof fetch;+ const outcome = await sendNative(+ { endpoint: 'd', platform: 'ios' },+ { title: 't', body: 'b' },+ { env: APNS_ENV, fetchImpl, apnsHost: 'https://apns.example' },+ );+ assert.equal(outcome.kind, 'failed');+ // Dropping the subscription because the network blipped would silently+ // unsubscribe a responder.+ assert.match((outcome as Extract<NativeOutcome, { kind: 'failed' }>).reason, /unreachable/);+});