import crypto from 'node:crypto';
const base64url = (buffer: Buffer) => buffer.toString('base64url');
app.post('/connect', requireUser, async (req, res) => {
const codeVerifier = base64url(crypto.randomBytes(32));
const codeChallenge = base64url(
crypto.createHash('sha256').update(codeVerifier).digest(),
);
const state = base64url(crypto.randomBytes(16));
// A follow-up push names a consent this patient already has
const followUp = await ownedConsent(req.user.id, req.body.consentId);
if (followUp === null) return res.sendStatus(404);
// Every push sends the patient's latest opt-in time
const optIn = await db.flexpaConsent.findLatest(req.user.id);
// Missing or close to a year old: show your consent screen again
if (!optIn || Date.now() - Date.parse(optIn.consentedAt) > REASK_AFTER_MS) {
return res.redirect(303, '/consent');
}
const { consentedAt } = optIn;
const push = await pushToFlexpa({
// Patient answers first, so the server-owned fields below always win
...pickAnswers(req.body.answers), // from answersFor() above
...(followUp ? { flexpa_consent_id: followUp.consentId } : {}),
state,
code_challenge: codeChallenge,
flexpa_external_id: req.user.id,
flexpa_consented_at: consentedAt,
});
// Kept in this browser's session, one entry per state, checked on return
req.session.flexpa = pruneExpired(req.session.flexpa ?? {});
req.session.flexpa[state] = {
userId: req.user.id,
consentId: push.consent_id,
codeVerifier,
createdAt: Date.now(),
};
// Send this same browser on to Flexpa
res.redirect(303, push.authorize_url);
});
// No consentId sent: undefined, a first consent. Otherwise the stored row,
// only if it is this user's and not revoked. Anything else is null: reject
// the request, never fall back to a new consent. Set revokedAt when you
// revoke the consent or a patient returns with consent_revoked.
async function ownedConsent(userId: string, consentId: unknown) {
if (consentId === undefined) return undefined;
if (typeof consentId !== 'string') return null;
return db.flexpaTokens.findFirst({ where: { consentId, userId, revokedAt: null } });
}
type SavedPush = {
userId: string;
consentId: string;
codeVerifier: string;
createdAt: number;
};
const ANSWER_KEYS = [
'flexpa_organization_id',
'flexpa_endpoint_id',
'flexpa_line_of_business',
'flexpa_state',
] as const;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
// Keep only the PushAnswers fields the browser may set, and only strings
function pickAnswers(input: unknown): PushAnswers {
const answers: PushAnswers = {};
if (!isRecord(input)) return answers;
for (const key of ANSWER_KEYS) {
const value = Object.hasOwn(input, key) ? input[key] : undefined;
if (typeof value === 'string') answers[key] = value;
}
return answers;
}
// Longer than Flexpa's 30-minute visit limit, so a late return still matches
const SAVED_FOR_MS = 60 * 60 * 1000;
const REASK_AFTER_MS = 330 * 24 * 60 * 60 * 1000; // about 11 months, before Flexpa's one-year limit
// Drop saved entries older than SAVED_FOR_MS, and keep only the newest 4
// so the new one makes 5 and a cookie session stays small
function pruneExpired(saved: Record<string, SavedPush>) {
return Object.fromEntries(
Object.entries(saved)
.filter(([, entry]) => Date.now() - entry.createdAt < SAVED_FOR_MS)
.sort(([, a], [, b]) => b.createdAt - a.createdAt)
.slice(0, 4),
);
}