import { randomUUID } from 'node:crypto'; import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import * as util from 'node:util'; import { BridgeError } from './bridge.mjs'; const phonePattern = /^\+[1-9]\d{7,14}$/; const clientId = 'photon-cli'; const dashboard = process.env.PHOTON_DASHBOARD_HOST || 'https://app.photon.codes'; const spectrum = process.env.PHOTON_SPECTRUM_HOST || 'https://spectrum.photon.codes'; export async function readPairing(path) { let pairing; try { pairing = JSON.parse(await readFile(path, 'utf8')); } catch (error) { if (error.code === 'ENOENT') return null; throw new BridgeError('Unable to read Photon pairing'); } if ( !pairing || typeof pairing.projectId !== 'string' || !pairing.projectId || typeof pairing.projectSecret !== 'string' || !pairing.projectSecret || !phonePattern.test(pairing.recipient) || typeof pairing.session !== 'string' || !pairing.session || (pairing.assignedNumber !== null && !phonePattern.test(pairing.assignedNumber)) ) { throw new BridgeError('Invalid Photon pairing'); } return pairing; } async function savePairing(home, pairing) { await mkdir(home, { recursive: true, mode: 0o700 }); const temporary = join(home, `.photon-${randomUUID()}.json`); try { await writeFile(temporary, JSON.stringify(pairing) + '\n', { mode: 0o600, flag: 'wx', }); await rename(temporary, join(home, 'photon.json')); } finally { await rm(temporary, { force: true }); } } async function request( host, path, { method = 'GET', authorization, body } = {}, ) { const url = new URL(path, host); if ( url.protocol !== 'https:' && !( url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) ) ) { throw new BridgeError('Photon API requires HTTPS'); } const headers = {}; if (authorization) headers.Authorization = authorization; if (body !== undefined) headers['Content-Type'] = 'application/json'; let response; try { response = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: 'error', signal: AbortSignal.timeout(10000), }); } catch { throw new BridgeError('Unable to reach Photon API'); } const data = await response.json().catch(() => null); return { response, data }; } async function jsonRequest(host, path, options, action) { const { response, data } = await request(host, path, options); if (!response.ok || !data || data.succeed === false || data.error) { throw new BridgeError(`Photon ${action} failed (HTTP ${response.status})`); } return data.data ?? data; } function projectOptions(pairing) { const secret = Buffer.from( `${pairing.projectId}:${pairing.projectSecret}`, ).toString('base64'); return { authorization: `Basic ${secret}` }; } function projectPath(pairing, suffix) { return `/projects/${encodeURIComponent(pairing.projectId)}/${suffix}`; } function phone(value) { const normalized = typeof value === 'string' ? value.replace(/[^+\d]/g, '') : ''; return phonePattern.test(normalized) ? normalized : null; } function optedIn(user) { return Boolean(user?.meta?.opt_in); } async function lookupUser(pairing) { const result = await jsonRequest( spectrum, projectPath(pairing, 'users/'), projectOptions(pairing), 'user lookup', ); const users = Array.isArray(result) ? result : (result.users ?? result.items); if (!Array.isArray(users)) { throw new BridgeError('Photon returned an invalid user list'); } const matches = users.filter( (user) => phone(user?.phoneNumber) === pairing.recipient, ); return matches.find(optedIn) ?? matches[0]; } async function createUser(pairing) { const result = await jsonRequest( spectrum, projectPath(pairing, 'users/'), { ...projectOptions(pairing), method: 'POST', body: { type: 'shared', phoneNumber: pairing.recipient }, }, 'user registration', ); return result.user ?? result; } function publicPairing( pairing, user, assignedNumber = phone(user?.assignedPhoneNumber), ) { return { session: pairing.session, recipient: pairing.recipient, assignedNumber: assignedNumber ?? pairing.assignedNumber, optedIn: optedIn(user), }; } async function deviceLogin() { const code = await jsonRequest( dashboard, '/api/auth/device/code', { method: 'POST', body: { client_id: clientId, scope: 'openid profile email' }, }, 'device login', ); if ( typeof code.device_code !== 'string' || typeof code.user_code !== 'string' ) { throw new BridgeError('Photon returned an invalid device code'); } const verification = new URL( code.verification_uri_complete || code.verification_uri, ); if (verification.origin !== new URL(dashboard).origin) { throw new BridgeError('Photon returned an unexpected verification URL'); } console.error( `Open ${verification.href} and approve code ${code.user_code}.`, ); const deadline = performance.now() + (Number(code.expires_in) || 300) * 1000; let interval = Math.max(1, Number(code.interval) || 5) * 1000; const body = { client_id: clientId, device_code: code.device_code, grant_type: 'urn:ietf:params:oauth:grant-type:device_code', }; while (performance.now() + interval < deadline) { await delay(interval); const { response, data } = await request( dashboard, '/api/auth/device/token', { method: 'POST', body }, ); if (response.ok) { return verifyDashboardToken(data, response.headers.get('set-auth-token')); } if (response.status === 429) { interval += 10000; continue; } const error = data?.error ?? data?.message; if (error === 'slow_down') interval += 5000; else if (error !== 'authorization_pending') { throw new BridgeError( `Photon device approval failed (HTTP ${response.status})`, ); } } throw new BridgeError('Photon device login timed out'); } async function verifyDashboardToken(data, headerToken) { const candidates = [ data?.access_token, data?.accessToken, data?.session?.access_token, data?.data?.access_token, data?.data?.accessToken, headerToken, ]; const tokens = new Set( candidates .filter((value) => typeof value === 'string') .map((value) => value .trim() .replace(/^Bearer\s+/i, '') .trim(), ) .filter(Boolean), ); for (const token of tokens) { const authorization = `Bearer ${token}`; const options = { authorization }; const session = await request(dashboard, '/api/auth/get-session', options); const user = session.data?.user ?? session.data?.data?.user; if ( !session.response.ok || !user || typeof user !== 'object' || !Object.keys(user).length ) { continue; } const projects = await request(dashboard, '/api/projects/', options); const listing = projects.data; if ( !projects.response.ok || !listing || listing.succeed === false || listing.error ) { continue; } const result = listing.data ?? listing; const items = Array.isArray(result) ? result : (result.projects ?? result.items); if (Array.isArray(items)) return { authorization, items }; } throw new BridgeError( 'Photon device login returned no token authorized to manage projects', ); } async function createProject(home, recipient, session) { const { authorization, items } = await deviceLogin(); // Existing projects may already be sending for another gateway. if (items.some((project) => project?.name?.toLowerCase() === 'albedo')) { throw new BridgeError( 'An Albedo project exists. Supply its PHOTON_PROJECT_ID and PHOTON_PROJECT_SECRET', ); } const project = await jsonRequest( dashboard, '/api/projects', { method: 'POST', authorization, body: { name: 'Albedo', location: 'United States', template: false, observability: false, }, }, 'project creation', ); if (typeof project.id !== 'string' || !project.id) { throw new BridgeError('Photon returned no new project ID'); } const credentials = await jsonRequest( dashboard, `/api/projects/${encodeURIComponent(project.id)}/regenerate-secret`, { method: 'POST', authorization, body: {} }, 'new project credential creation', ); if ( typeof credentials.projectSecret !== 'string' || !credentials.projectSecret ) { throw new BridgeError('Photon returned no new project secret'); } const pairing = { projectId: project.id, projectSecret: credentials.projectSecret, recipient, session, assignedNumber: null, }; // Save the new secret before any operation that could fail during setup. await savePairing(home, pairing); return pairing; } async function readProjectCredentials(path) { if (typeof util.parseEnv !== 'function') { throw new BridgeError( 'Reading --env-file requires the packaged helper or Node 20.12 or newer', ); } let values; try { values = util.parseEnv(await readFile(path, 'utf8')); } catch { throw new BridgeError('Unable to read the credentials file'); } if (!values.PHOTON_PROJECT_ID || !values.PHOTON_PROJECT_SECRET) { throw new BridgeError( 'The credentials file must contain PHOTON_PROJECT_ID and PHOTON_PROJECT_SECRET', ); } return { projectId: values.PHOTON_PROJECT_ID, projectSecret: values.PHOTON_PROJECT_SECRET, }; } async function setup(home, { session, phone: recipient, 'env-file': envFile }) { if (!session || !phonePattern.test(recipient)) { throw new BridgeError( 'Photon setup requires --session and an E.164 --phone', ); } const previous = envFile ? null : await readPairing(join(home, 'photon.json')); const { PHOTON_PROJECT_ID: projectId, PHOTON_PROJECT_SECRET: projectSecret } = process.env; if (!envFile && Boolean(projectId) !== Boolean(projectSecret)) { throw new BridgeError( 'Configure both PHOTON_PROJECT_ID and PHOTON_PROJECT_SECRET', ); } const project = envFile ? await readProjectCredentials(envFile) : projectId ? { projectId, projectSecret } : (previous ?? (await createProject(home, recipient, session))); const sameContact = previous?.projectId === project.projectId && previous.recipient === recipient; const pairing = { ...project, recipient, session, assignedNumber: sameContact ? previous.assignedNumber : null, }; let user = await lookupUser(pairing); if (!user && !envFile) user = await createUser(pairing); const status = publicPairing(pairing, user); if (envFile && (!user || !status.assignedNumber)) { throw new BridgeError( 'This phone has no assigned iMessage number in the Photon project', ); } await savePairing(home, { ...pairing, assignedNumber: status.assignedNumber, }); return status; } export async function manage(command, args) { const { values } = util.parseArgs({ args, options: { home: { type: 'string' }, ...(command === 'setup' && { session: { type: 'string' }, phone: { type: 'string' }, 'env-file': { type: 'string' }, }), }, }); if (!values.home) throw new BridgeError('Photon setup and status require --home'); if (command === 'setup') return setup(values.home, values); const pairing = await readPairing(join(values.home, 'photon.json')); return pairing && publicPairing(pairing, await lookupUser(pairing)); } export async function managedConnection(pairing) { const user = await lookupUser(pairing); const assignedNumber = phone(user?.assignedPhoneNumber) ?? pairing.assignedNumber; async function issueToken() { return jsonRequest( spectrum, projectPath(pairing, 'imessage/tokens'), { ...projectOptions(pairing), method: 'POST', }, 'iMessage authentication', ); } const initial = await issueToken(); const dedicated = initial.type === 'dedicated'; const shared = initial.type === 'shared'; if (!dedicated && !shared) throw new BridgeError('Photon returned an invalid iMessage plan'); const instance = dedicated && Object.keys(initial.numbers ?? {}).find( (id) => phone(initial.numbers[id]) === assignedNumber, ); if ( dedicated && (!assignedNumber || !instance || !/^[a-z0-9-]+$/i.test(instance)) ) { throw new BridgeError( 'The paired contact has no assigned dedicated Photon line', ); } const extract = (credentials) => { const token = dedicated ? credentials.auth?.[instance] : credentials.token; if ( credentials.type !== initial.type || typeof token !== 'string' || !token ) { throw new BridgeError( 'Photon returned no token for the assigned iMessage line', ); } const lifetimeMs = Number(credentials.expiresIn) * 1000; if (!Number.isFinite(lifetimeMs) || lifetimeMs <= 0) { throw new BridgeError( 'Photon returned an invalid iMessage token lifetime', ); } return { token, refreshAt: performance.now() + lifetimeMs - Math.min(lifetimeMs / 10, 30000), }; }; let cached = extract(initial); let refresh; return { address: dedicated ? `${instance}.imsg.photon.codes:443` : process.env.SPECTRUM_IMESSAGE_ADDRESS || 'imessage.spectrum.photon.codes:443', assignedNumber, // Shared Spectrum projects synthesize the DM GUID without calling CreateChat. directChat: shared ? `any;-;${pairing.recipient}` : null, token: async () => { if (performance.now() < cached.refreshAt) return cached.token; refresh ??= issueToken() .then(extract) .then((result) => { cached = result; return cached.token; }) .finally(() => { refresh = undefined; }); return refresh; }, }; }