SmartfolioBackend / scripts /e2e /p9-interview.mjs
ibrahimgulbutt's picture
deploy: structured country targeting for campaign matching
da3259f
Raw History Blame Contribute Delete
6.62 kB
/**
* P9 gate - the interview invitation, end to end against the live API.
*
* Covers the security shape of an invite link, which is the part that would
* hurt most if it were wrong: a link is a credential that starts an interview
* attributed to a named person, so the token says WHICH invitation and the JWT
* says WHO, and neither alone is enough.
*
* BACKEND_LOG=... node scripts/e2e/p9-interview.mjs
*/
import {
api, sql, sqlOne, section, check, info, summary,
createVerifiedUser, uniqueEmail, makeAdmin, inviteTokenFromLog,
} from './lib.mjs';
const JD = `Senior Frontend Engineer. You will own the React and TypeScript
interface layer, lead the design system and hold the performance budget. Remote,
with a four-hour overlap centred on CET.`;
async function main() {
section('setup');
const adminEmail = uniqueEmail('interview-admin');
const admin = await createVerifiedUser({ name: 'Interview Admin', email: adminEmail });
makeAdmin(adminEmail);
const created = await api('/admin/campaigns', {
method: 'POST',
token: admin.accessToken,
body: {
title: 'Senior Frontend Engineer',
company: 'Northwind Labs',
jobDescription: JD,
interviewDeadline: new Date(Date.now() + 10 * 86400000).toISOString(),
},
});
const campaign = created.body;
await api(`/admin/campaigns/${campaign.id}`, {
method: 'PATCH',
token: admin.accessToken,
body: { status: 'collecting' },
});
check('campaign ready', Boolean(campaign?.id), campaign?.slug);
const candidate = await createVerifiedUser({
name: 'Invited Candidate',
email: uniqueEmail('invited'),
});
const other = await createVerifiedUser({
name: 'Someone Else',
email: uniqueEmail('someone-else'),
});
await api(`/campaigns/public/${campaign.slug}/claim`, {
method: 'POST',
token: candidate.accessToken,
body: {},
});
const candidateId = sqlOne(
`select id from campaign_candidates where "campaignId" = '${campaign.id}' and "userId" = '${candidate.userId}'`,
);
check('candidate applied', Boolean(candidateId));
section('issuing an invitation');
await api(`/admin/campaigns/${campaign.id}/shortlist`, {
method: 'POST',
token: admin.accessToken,
body: { candidateIds: [candidateId] },
});
const invited = await api(`/admin/campaigns/${campaign.id}/invite`, {
method: 'POST',
token: admin.accessToken,
body: { candidateIds: [candidateId] },
});
check('invite sent', invited.body?.sent === 1, JSON.stringify(invited.body));
const token = inviteTokenFromLog(candidate.email);
check('the link was emailed', Boolean(token), token ? token.slice(0, 10) + '…' : 'not found');
section('the link resolves for anyone holding it');
// Deliberately public: an expired link must be able to say "expired" rather
// than bouncing someone to a login screen that explains nothing.
const resolved = await api(`/campaigns/invite/${token}`);
check('200 without a token', resolved.status === 200, 'got ' + resolved.status);
check('names the role', resolved.body?.campaign?.title === 'Senior Frontend Engineer');
check('carries the JD the interview is generated from',
String(resolved.body?.campaign?.jobDescription || '').includes('design system'));
check('but does not leak the candidate email',
!JSON.stringify(resolved.body).includes('@smartfolio.test'),
JSON.stringify(resolved.body).slice(0, 120));
section('completing it needs BOTH the token and the right account');
const sessionId = await seedInterviewSession(candidate.userId, campaign.jobDescription ?? JD);
const noAuth = await api(`/campaigns/invite/${token}/complete`, {
method: 'POST',
body: { interviewSessionId: sessionId },
});
check('401 with the token but no login', noAuth.status === 401, 'got ' + noAuth.status);
const wrongPerson = await api(`/campaigns/invite/${token}/complete`, {
method: 'POST',
token: other.accessToken,
body: { interviewSessionId: sessionId },
});
check(
'403 for someone else holding a forwarded link',
wrongPerson.status === 403,
'got ' + wrongPerson.status,
);
const done = await api(`/campaigns/invite/${token}/complete`, {
method: 'POST',
token: candidate.accessToken,
body: { interviewSessionId: sessionId },
});
check('201 for the invited candidate', done.status === 201, 'got ' + done.status);
check('status advanced to completed', done.body?.status === 'completed', done.body?.status);
const row = sql(
`select status, "interviewSessionId", "completedAt" is not null from campaign_candidates where id = '${candidateId}'`,
)[0];
check('written to the database', row?.[0] === 'completed', row?.[0]);
check('with the session linked', row?.[1] === sessionId, row?.[1]);
check('and a completion time', row?.[2] === 't');
section('a spent invitation cannot be reused');
const reused = await api(`/campaigns/invite/${token}`);
check('410 Gone once completed', reused.status === 410, 'got ' + reused.status);
section('attending an interview protects against auto-suspension');
// The three-strikes rule counts submissions with no interview attended. This
// candidate has now attended one, so submitting them onward must not pause
// their account.
await api(`/admin/campaigns/${campaign.id}/submit`, {
method: 'POST',
token: admin.accessToken,
body: { candidateIds: [candidateId] },
});
check(
'still looking after being submitted',
sqlOne(`select availability from "user" where id = '${candidate.userId}'`) === 'looking',
);
info('interview sessions linked to campaigns: ' +
sqlOne('select count(*) from campaign_candidates where "interviewSessionId" is not null'));
summary('P9 interview invitation');
}
/**
* A finished interview session, inserted directly.
*
* Generating a real one needs an LLM round trip and several minutes of answers;
* what this gate is testing is the LINK between a session and an invitation, and
* that link does not care how the session was produced. The interview itself is
* covered by its own suite.
*/
async function seedInterviewSession(userId, jobDescription) {
const id = sqlOne(
`insert into interview_sessions ("userId", "jobDescription", "lengthTier", questions, "followUps", "overallScore", "submittedAt") ` +
`values ('${userId}', ${quote(jobDescription)}, 'quick', '[]'::jsonb, '[]'::jsonb, 72.5, now()) returning id`,
);
return id;
}
const quote = (value) => "'" + String(value).replace(/'/g, "''") + "'";
main().catch((e) => {
console.error(e);
process.exitCode = 1;
});