Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Vision8 * File : server/src/push.ts9 * Module : server10 * Repository : https://git.spboucher.ai/maclustr-vision11 * Project Website : https://camera.spboucher.ai12 * Created : 2026-11-3013 * Last Modified : 2026-11-3014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Notifications Apple (APNs, HTTP/2, jeton fournisseur ES256). La clé d'équipe est un fichier 0600 hors dépôt ;43// sans elle, les notifications sont simplement inactives (et l'API le dit). Aucune image ni vidéo n'est jointe.44import crypto from 'node:crypto';45import fs from 'node:fs';46import http2 from 'node:http2';47import path from 'node:path';48import type { Config } from './config.ts';49import type { DB } from './db.ts';50import { logger } from './log.ts';5152const log = logger('push');53export const APNS_TOPIC = 'ai.spboucher.maclustrvision';5455type Creds = { keyId: string; teamId: string; key: crypto.KeyObject };56let creds: Creds | null | undefined;57let jwt: { value: string; at: number } | null = null;5859/** Lit ~/.config/maclustr-vision/apns.json : { "keyId", "teamId", "keyFile" } (clé .p8 dans le même dossier). */60export function loadApns(cfg: Config): Creds | null {61 if (creds !== undefined) return creds;62 try {63 const meta = JSON.parse(fs.readFileSync(path.join(cfg.configDir, 'apns.json'), 'utf8'));64 const file = path.join(cfg.configDir, path.basename(String(meta.keyFile)));65 if ((fs.statSync(file).mode & 0o077) !== 0) throw new Error('clé APNs : mode 0600 requis');66 creds = { keyId: String(meta.keyId), teamId: String(meta.teamId), key: crypto.createPrivateKey(fs.readFileSync(file)) };67 } catch (e: any) {68 if (e?.code !== 'ENOENT') log.warn('APNs non configuré', { err: String(e?.message || e) });69 creds = null;70 }71 return creds;72}73export const apnsConfigured = (cfg: Config) => !!loadApns(cfg);7475function token(c: Creds): string {76 const now = Math.floor(Date.now() / 1000);77 if (jwt && now - jwt.at < 40 * 60) return jwt.value;78 const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString('base64url');79 const head = `${b64({ alg: 'ES256', kid: c.keyId })}.${b64({ iss: c.teamId, iat: now })}`;80 const sig = crypto.sign('sha256', Buffer.from(head), { key: c.key, dsaEncoding: 'ieee-p1363' }).toString('base64url');81 jwt = { value: `${head}.${sig}`, at: now };82 return jwt.value;83}8485export type PushMessage = { title: string; body: string; kind: 'motion' | 'system' | 'test'; cameraId?: string | null; tsMs: number; eventId?: number | null; collapseId?: string };86type Result = { token: string; status: number; reason: string };8788function sendBatch(c: Creds, host: string, tokens: string[], msg: PushMessage): Promise<Result[]> {89 return new Promise((resolve) => {90 const results: Result[] = [];91 if (!tokens.length) return resolve(results);92 const client = http2.connect(`https://${host}`);93 const finish = () => {94 try {95 client.close();96 } catch {97 /* rien */98 }99 resolve(results);100 };101 const guard = setTimeout(finish, 15000);102 client.on('error', (e) => {103 log.warn('connexion APNs', { host, err: String(e?.message || e) });104 clearTimeout(guard);105 for (const t of tokens) if (!results.find((r) => r.token === t)) results.push({ token: t, status: 0, reason: 'connexion' });106 finish();107 });108 const payload = JSON.stringify({109 aps: { alert: { title: msg.title, body: msg.body }, sound: 'default', 'thread-id': msg.cameraId || 'systeme', category: msg.kind === 'motion' ? 'MOTION' : 'SYSTEM' },110 kind: msg.kind,111 cameraId: msg.cameraId ?? null,112 tsMs: msg.tsMs,113 eventId: msg.eventId ?? null,114 });115 let pending = tokens.length;116 for (const t of tokens) {117 const headers: Record<string, string> = {118 ':method': 'POST',119 ':path': `/3/device/${t}`,120 authorization: `bearer ${token(c)}`,121 'apns-topic': APNS_TOPIC,122 'apns-push-type': 'alert',123 'apns-priority': '10',124 'apns-expiration': String(Math.floor(Date.now() / 1000) + 3600),125 };126 if (msg.collapseId) headers['apns-collapse-id'] = msg.collapseId.slice(0, 64);127 const req = client.request(headers);128 let status = 0;129 let body = '';130 req.on('response', (h) => (status = Number(h[':status'])));131 req.on('data', (d) => (body += d));132 req.on('error', () => {});133 req.on('close', () => {134 let reason = '';135 try {136 reason = body ? JSON.parse(body).reason || '' : '';137 } catch {138 /* rien */139 }140 results.push({ token: t, status, reason });141 if (--pending === 0) {142 clearTimeout(guard);143 finish();144 }145 });146 req.end(payload);147 }148 });149}150151/** Envoie à tous les appareils concernés ; retire les jetons que Apple déclare invalides. Ne journalise jamais un jeton entier. */152export async function sendPush(cfg: Config, db: DB, msg: PushMessage, filter: { sessionId?: string } = {}): Promise<{ sent: number; failed: number }> {153 const c = loadApns(cfg);154 if (!c) return { sent: 0, failed: 0 };155 const col = msg.kind === 'motion' ? 'motion = 1' : msg.kind === 'system' ? 'system = 1' : '1 = 1';156 const rows = (filter.sessionId157 ? db.prepare(`SELECT d.token, d.environment FROM push_devices d JOIN sessions s ON s.id = d.session_id WHERE s.revoked_ms IS NULL AND s.expires_ms > ? AND d.session_id = ? AND ${col}`).all(Date.now(), filter.sessionId)158 : db.prepare(`SELECT d.token, d.environment FROM push_devices d JOIN sessions s ON s.id = d.session_id WHERE s.revoked_ms IS NULL AND s.expires_ms > ? AND ${col}`).all(Date.now())) as { token: string; environment: string }[];159 let sent = 0;160 let failed = 0;161 for (const [env, host] of [['production', 'api.push.apple.com'], ['sandbox', 'api.sandbox.push.apple.com']] as const) {162 const tokens = rows.filter((r) => r.environment === env).map((r) => r.token);163 for (const r of await sendBatch(c, host, tokens, msg)) {164 if (r.status === 200) {165 sent++;166 db.prepare('UPDATE push_devices SET last_sent_ms = ?, failures = 0 WHERE token = ?').run(Date.now(), r.token);167 } else {168 failed++;169 log.warn('notification refusée', { env, status: r.status, reason: r.reason, device: r.token.slice(0, 8) + '…' });170 if (r.status === 410 || r.reason === 'BadDeviceToken' || r.reason === 'Unregistered' || r.reason === 'DeviceTokenNotForTopic') db.prepare('DELETE FROM push_devices WHERE token = ?').run(r.token);171 else db.prepare('UPDATE push_devices SET failures = failures + 1 WHERE token = ?').run(r.token);172 }173 }174 }175 return { sent, failed };176}177