diff --git a/backend/e2e/podcast-guest-form.spec.js b/backend/e2e/podcast-guest-form.spec.js index 9a138bda..fd4867f7 100644 --- a/backend/e2e/podcast-guest-form.spec.js +++ b/backend/e2e/podcast-guest-form.spec.js @@ -26,6 +26,7 @@ test.describe("podcast guest materials form", () => { server = await startOwnedTestServer({ environment: { DTC_CACHE_ROOT: createDocsCacheRoot("podcast-guest-form"), + E2E_SEED_PODCAST_TEMPLATE: "1", }, }); }); @@ -105,8 +106,8 @@ test.describe("podcast guest materials form", () => { // Episodes release strictly in number order: the first test's S25E9 is // on this same server two weeks out, so S25E8 releases the week before. const episode = await api("/api/podcast-episodes", { - season: 26, - episode: 1, + season: 25, + episode: 8, releaseAssignmentStatus: "provisional", releaseDate: releaseFriday(7), title: "Guest form alias e2e", @@ -139,4 +140,207 @@ test.describe("podcast guest materials form", () => { expect(anonBody.code).toBe("access_code_required"); expect(anonBody.error).not.toMatch(/sponsor/i); }); + + test("staff sees two tabs (Guest intake / Internal Team & Host) across desktop and phone; guest never sees internal data", async ({ + browser, + page, + }) => { + test.setTimeout(60_000); + const episode = await api("/api/podcast-episodes", { + season: 26, + episode: 2, + releaseAssignmentStatus: "provisional", + releaseDate: releaseFriday(21), + title: "Two-tab podcast e2e", + guests: [{ name: "Two-Tab Guest" }], + status: "booked", + }); + const { doc } = await api("/api/sponsor-docs", { + cardId: episode.id, + template: "podcast", + content: { + guestName: "Two-Tab Guest, Staff Engineer", + introduction: "Guest public bio for intro.", + topicsToCover: "Distributed systems & evals", + topicsToAvoid: "Confidential client contracts", + linkedinUrl: "https://example.test/linkedin", + coldOpen: "SECRET_COLD_OPEN_HOOK", + introScript: "SECRET_INTRO_SCRIPT", + interviewQuestions: "SECRET_Q1_ARCHITECTURE\nSECRET_Q2_TRADEOFFS", + closingScript: "SECRET_CLOSING_SCRIPT", + goal: "SECRET_EPISODE_GOAL", + audience: "SECRET_TARGET_AUDIENCE", + keyMessages: "SECRET_KEY_MESSAGES", + sourceLinks: "https://example.test/secret-research-source", + keyInsights: "SECRET_CLAIM_LEDGER_INSIGHT", + openQuestions: "SECRET_OPEN_ANGLE", + hostNotes: "SECRET_HOST_TIMING_NOTE", + }, + }); + + // 1. Staff desktop view: sees two tabs, Host view + Edit prep & research, and saves internal changes + await page.setViewportSize({ width: 1280, height: 900 }); + await page.goto(`${server.baseURL}/podcast-docs/${doc.id}`); + await expect(page.locator('[data-podcast-tab="guest"]')).toBeVisible(); + await expect(page.locator('[data-podcast-tab="internal"]')).toBeVisible(); + await expect(page.locator('[data-podcast-panel="guest"]')).toBeVisible(); + await expect(page.locator("#sponsor-field-interviewQuestions")).toHaveCount(0); + + await page.locator('[data-podcast-tab="internal"]').click(); + await expect(page.locator('[data-podcast-panel="internal"]')).toBeVisible(); + await expect(page.locator('[data-podcast-questions-view="readonly"]')).toBeVisible(); + await expect(page.locator('[data-podcast-host-block="coldOpen"]')).toContainText("SECRET_COLD_OPEN_HOOK"); + await expect(page.locator('[data-podcast-host-block="interviewQuestions"]')).toContainText("SECRET_Q1_ARCHITECTURE"); + await expect(page.locator('[data-podcast-host-block="topicsToAvoid"]')).toContainText("Confidential client contracts"); + await expect(page.locator('[data-podcast-host-block="hostNotes"]')).toContainText("SECRET_HOST_TIMING_NOTE"); + await expect(page.locator("[data-podcast-host-qna]")).toBeVisible(); + + await page.locator('[data-podcast-internal-mode="edit"]').click(); + await expect(page.locator("#sponsor-field-interviewQuestions")).toBeVisible(); + await expect(page.locator("#sponsor-field-sourceLinks")).toBeVisible(); + await page.locator("#sponsor-field-hostNotes").fill("SECRET_HOST_TIMING_NOTE_UPDATED"); + await page.locator('[data-sponsor-action="save-draft"]').click(); + await expect(page.locator("[data-sponsor-feedback]")).toContainText("Saved draft"); + + // 2. Staff phone view (390px): zero horizontal overflow on both tabs + await page.setViewportSize({ width: 390, height: 844 }); + const internalOverflow = await page.evaluate(() => ({ + scrollWidth: document.documentElement.scrollWidth, + clientWidth: document.documentElement.clientWidth, + })); + expect(internalOverflow.scrollWidth).toBeLessThanOrEqual(internalOverflow.clientWidth); + + await page.locator('[data-podcast-internal-mode="host"]').click(); + const hostOverflow = await page.evaluate(() => ({ + scrollWidth: document.documentElement.scrollWidth, + clientWidth: document.documentElement.clientWidth, + })); + expect(hostOverflow.scrollWidth).toBeLessThanOrEqual(hostOverflow.clientWidth); + + // 3. Anonymous guest browser context with valid ?code= (even requesting ?tab=internal&view=questions): + // never sees tabs, never sees View questions, never receives any internal content. + const guestContext = await browser.newContext({ + extraHTTPHeaders: { "x-sponsor-doc-anonymous": "true" }, + viewport: { width: 390, height: 844 }, + }); + try { + const guestPage = await guestContext.newPage(); + await guestPage.goto( + `${server.baseURL}/podcast-docs/${doc.id}?code=${encodeURIComponent(doc.accessCode)}&tab=internal&view=questions`, + ); + await expect(guestPage.locator('[data-sponsor-view="editor"]')).toBeVisible(); + await expect(guestPage.locator('[data-podcast-tab]')).toHaveCount(0); + await expect(guestPage.locator('[data-sponsor-action="toggle-questions-view"]')).toHaveCount(0); + await expect(guestPage.locator("[data-sponsor-export]")).toHaveCount(0); + await expect(guestPage.locator("#sponsor-field-guestName")).toHaveValue("Two-Tab Guest, Staff Engineer"); + const guestDomText = await guestPage.locator("body").innerText(); + for (const secretMarker of [ + "SECRET_COLD_OPEN_HOOK", + "SECRET_INTRO_SCRIPT", + "SECRET_Q1_ARCHITECTURE", + "SECRET_CLOSING_SCRIPT", + "SECRET_EPISODE_GOAL", + "SECRET_CLAIM_LEDGER_INSIGHT", + "SECRET_HOST_TIMING_NOTE", + ]) { + expect(guestDomText).not.toContain(secretMarker); + } + const guestOverflow = await guestPage.evaluate(() => ({ + scrollWidth: document.documentElement.scrollWidth, + clientWidth: document.documentElement.clientWidth, + })); + expect(guestOverflow.scrollWidth).toBeLessThanOrEqual(guestOverflow.clientWidth); + } finally { + await guestContext.close(); + } + + // 4. Anonymous guest API & export negative check + const anonDocRes = await fetch( + `${server.baseURL}/api/sponsor-docs/${doc.id}?code=${encodeURIComponent(doc.accessCode)}&tab=internal&view=questions`, + { headers: { "x-sponsor-doc-anonymous": "true" } }, + ); + expect(anonDocRes.status).toBe(200); + const anonDocBody = await anonDocRes.text(); + expect(anonDocBody).not.toMatch(/SECRET_/); + const anonDocJson = JSON.parse(anonDocBody).doc; + expect(anonDocJson.viewerRole).toBe("sponsor"); + expect(anonDocJson.hostContext).toBeUndefined(); + expect(anonDocJson.emailDelivery).toBeUndefined(); + + const anonExportRes = await fetch( + `${server.baseURL}/api/sponsor-docs/${doc.id}/export?format=markdown&code=${encodeURIComponent(doc.accessCode)}`, + { headers: { "x-sponsor-doc-anonymous": "true" } }, + ); + expect(anonExportRes.status).toBe(200); + expect(await anonExportRes.text()).not.toMatch(/SECRET_/); + }); + + test("confirmed podcast recording time collapses into one compact line with Change toggle", async ({ + browser, + }) => { + test.setTimeout(60_000); + const episode = await api("/api/podcast-episodes", { + season: 26, + episode: 3, + releaseAssignmentStatus: "provisional", + releaseDate: releaseFriday(28), + recordingDate: "2026-12-15", + title: "Confirmed slot compact e2e", + guests: [{ name: "Confirmed Guest" }], + status: "booked", + }); + const createdCard = await api(`/api/podcast-episodes/${episode.id}/card`, {}); + const cardId = createdCard.card?.id || createdCard.episode?.cardId; + expect(cardId).toBeTruthy(); + const timeRes = await fetch(`${server.baseURL}/api/cards/${cardId}/time`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + at: "2026-12-15 18:00", + guestEmails: ["confirmed-guest@example.test"], + }), + }); + const timePayload = await timeRes.json(); + expect(timePayload.card?.eventTime?.startIso, JSON.stringify(timePayload)).toBeTruthy(); + const { doc } = await api("/api/sponsor-docs", { + cardId, + template: "podcast", + content: { guestName: "Confirmed Guest" }, + }); + + const guestContext = await browser.newContext({ + extraHTTPHeaders: { "x-sponsor-doc-anonymous": "true" }, + viewport: { width: 1280, height: 900 }, + }); + try { + const guestPage = await guestContext.newPage(); + await guestPage.goto( + `${server.baseURL}/podcast-docs/${doc.id}?code=${encodeURIComponent(doc.accessCode)}`, + ); + const summary = guestPage.locator('[data-podcast-recording-summary="confirmed"]'); + await expect(summary).toBeVisible(); + await expect(summary).toContainText("Confirmed"); + await expect(summary).toContainText("18:00"); + await expect(guestPage.locator('[data-podcast-action="change-recording-time"]')).toBeVisible(); + await expect(guestPage.locator('[data-sponsor-radios="slotChoice"]')).toHaveCount(0); + await expect(guestPage.locator('[data-podcast-slot-picker="open"]')).toHaveCount(0); + + await guestPage.locator('[data-podcast-action="change-recording-time"]').click(); + await expect(guestPage.locator('[data-podcast-slot-picker="open"]')).toBeVisible(); + await expect(guestPage.locator('[data-sponsor-radios="slotChoice"]')).toBeVisible(); + + await guestPage.setViewportSize({ width: 390, height: 844 }); + const expandedOverflow = await guestPage.evaluate(() => ({ + scrollWidth: document.documentElement.scrollWidth, + clientWidth: document.documentElement.clientWidth, + })); + expect(expandedOverflow.scrollWidth).toBeLessThanOrEqual(expandedOverflow.clientWidth); + + await guestPage.locator('[data-podcast-action="cancel-recording-time"]').click(); + await expect(guestPage.locator('[data-podcast-slot-picker="open"]')).toHaveCount(0); + await expect(guestPage.locator('[data-sponsor-radios="slotChoice"]')).toHaveCount(0); + } finally { + await guestContext.close(); + } + }); }); diff --git a/backend/src/docs/frontend-assets.json b/backend/src/docs/frontend-assets.json index 31a67bb7..47a844cd 100644 --- a/backend/src/docs/frontend-assets.json +++ b/backend/src/docs/frontend-assets.json @@ -171,6 +171,7 @@ "src/surfaces/operations/sponsor-doc-event-time.js", "src/surfaces/operations/sponsor-doc-gate.js", "src/surfaces/operations/sponsor-doc-guest-schedule.js", + "src/surfaces/operations/sponsor-doc-podcast.js", "src/surfaces/operations/sponsor-doc-radio.js", "src/surfaces/operations/sponsor-doc-select.js", "src/surfaces/operations/sponsor-docs.js", diff --git a/backend/src/routes/sponsorDocs.ts b/backend/src/routes/sponsorDocs.ts index d2eba039..d97706b2 100644 --- a/backend/src/routes/sponsorDocs.ts +++ b/backend/src/routes/sponsorDocs.ts @@ -318,6 +318,7 @@ export function isAnonymousSponsorDocAsset(method: string, path: string): boolea || path === '/src/surfaces/operations/sponsor-doc-email-card.js' || path === '/src/surfaces/operations/sponsor-doc-event-time.js' || path === '/src/surfaces/operations/sponsor-doc-guest-schedule.js' + || path === '/src/surfaces/operations/sponsor-doc-podcast.js' || path === '/src/styles/sponsor-docs.css' || path.startsWith('/src/dakit/') ); @@ -458,6 +459,30 @@ async function buildDocResponsePayload( // A form remains readable when the private email template is offline. } } + let hostContext: + | { + cardId: string | null; + sponsored: boolean; + qna: Card['qna'] | null; + } + | undefined; + if (doc.template === 'podcast') { + let ownerCard: Card | null = null; + try { + ownerCard = doc.cardId ? await getCardConsistent(client, doc.cardId) : null; + if (!ownerCard && doc.cardId) { + const ep = await getPodcastEpisode(client, doc.cardId); + if (ep?.cardId) ownerCard = await getCardConsistent(client, ep.cardId); + } + } catch { + // Keep the document readable when host context lookup fails. + } + hostContext = { + cardId: ownerCard?.id || null, + sponsored: ownerCard?.sponsored === true, + qna: ownerCard?.qna || null, + }; + } return { ...doc, viewerRole: 'staff' as const, @@ -467,12 +492,14 @@ async function buildDocResponsePayload( accessCode, emailDraft, markdownExport, + ...(hostContext ? { hostContext } : {}), }; } const speakerDoc = { ...doc, content: speakerContentView(doc.template, doc.content) }; + const { emailDelivery: _omittedEmailDelivery, ...safeSpeakerDoc } = speakerDoc; return { - ...speakerDoc, + ...safeSpeakerDoc, viewerRole: 'sponsor' as const, templateDefinition: speakerTemplateView(templateDefinition), docUrl, diff --git a/backend/src/sponsorDocs/templates.ts b/backend/src/sponsorDocs/templates.ts index 5f674464..74860712 100644 --- a/backend/src/sponsorDocs/templates.ts +++ b/backend/src/sponsorDocs/templates.ts @@ -48,6 +48,8 @@ export interface SponsorDocSectionDefinition { collapsible?: boolean; /** Staff-only: never shown to, exported for, or writable by the speaker. */ internal?: boolean; + /** Which tab of a two-tab doc renders this section. */ + tab?: 'guest' | 'internal'; fields: SponsorDocFieldDefinition[]; } @@ -595,6 +597,7 @@ export const SPONSOR_DOC_TEMPLATES: Record): Record { - const internalKeys = new Set(SPONSOR_DOC_TEMPLATES[key].sections - .filter((section) => section.internal) + const publicKeys = new Set(SPONSOR_DOC_TEMPLATES[key].sections + .filter((section) => !section.internal) .flatMap((section) => section.fields.map((field) => field.key))); - return Object.fromEntries(Object.entries(content || {}).filter(([k]) => !internalKeys.has(k))); + return Object.fromEntries(Object.entries(content || {}).filter(([k]) => publicKeys.has(k))); } export class SponsorDocValidationError extends Error { @@ -1608,16 +1626,22 @@ export function renderSponsorDocMarkdownExport(doc: SponsorDocExportInput): stri '### Actionable First Step & Resources', valOrPlaceholder(c.actionableTakeaway), ); - if (c.interviewQuestions?.trim() || c.goal?.trim() || c.audience?.trim() || c.keyMessages?.trim() || c.coldOpen?.trim() || c.introScript?.trim() || c.closingScript?.trim()) { - lines.push('', '## 6) Episode Plan & Questions'); - if (c.goal?.trim()) lines.push('', '### Episode Goal', c.goal.trim()); - if (c.audience?.trim()) lines.push('', `**Target Audience:** ${c.audience.trim()}`); - if (c.keyMessages?.trim()) lines.push('', '### Key Messages / Takeaways', c.keyMessages.trim()); + if (c.sponsorNotes?.trim()) { + lines.push('', '---', '', '## Notes from the Guest', '', c.sponsorNotes.trim()); + } + if (c.coldOpen?.trim() || c.introScript?.trim() || c.interviewQuestions?.trim() || c.closingScript?.trim()) { + lines.push('', '## Run Sheet & Interview Questions'); if (c.coldOpen?.trim()) lines.push('', '### Cold Open', c.coldOpen.trim()); if (c.introScript?.trim()) lines.push('', '### Intro Script', c.introScript.trim()); if (c.interviewQuestions?.trim()) lines.push('', '### Interview Questions', c.interviewQuestions.trim()); if (c.closingScript?.trim()) lines.push('', '### Closing Script', c.closingScript.trim()); } + if (c.goal?.trim() || c.audience?.trim() || c.keyMessages?.trim()) { + lines.push('', '## Event Description & Episode Plan'); + if (c.goal?.trim()) lines.push('', '### Episode Goal', c.goal.trim()); + if (c.audience?.trim()) lines.push('', `**Target Audience:** ${c.audience.trim()}`); + if (c.keyMessages?.trim()) lines.push('', '### Key Messages / Takeaways', c.keyMessages.trim()); + } if (c.sourceLinks?.trim() || c.keyInsights?.trim() || c.openQuestions?.trim() || c.hostNotes?.trim()) { lines.push('', '## Internal Research & Host Notes (Staff Only)'); if (c.sourceLinks?.trim()) lines.push('', '### Research Sources', c.sourceLinks.trim()); @@ -1708,9 +1732,10 @@ export function renderSponsorDocMarkdownExport(doc: SponsorDocExportInput): stri ); } - if (c.sponsorNotes?.trim()) { - const notesHeading = doc.template === 'podcast' ? '## Notes from the Guest' - : (doc.template === 'workshop' || doc.template === 'webinar') ? '## Notes from the Speaker' : '## Notes from Sponsor'; + if (doc.template !== 'podcast' && c.sponsorNotes?.trim()) { + const notesHeading = (doc.template === 'workshop' || doc.template === 'webinar') + ? '## Notes from the Speaker' + : '## Notes from Sponsor'; lines.push( '', '---', diff --git a/backend/tests/podcast-guest-form.test.ts b/backend/tests/podcast-guest-form.test.ts index b2791304..9a3e7c07 100644 --- a/backend/tests/podcast-guest-form.test.ts +++ b/backend/tests/podcast-guest-form.test.ts @@ -7,6 +7,8 @@ import { hydratePodcastGuestSlotOptions, humanizePodcastSlotChoice, renderSponsorDocMarkdownExport, + speakerContentView, + speakerTemplateView, } from '../src/sponsorDocs/templates'; describe('podcast guest form (radio slot picker + topics; email stays one slot)', () => { @@ -21,9 +23,22 @@ describe('podcast guest form (radio slot picker + topics; email stays one slot)' 'social-links', 'detailed-questions', 'notes', - 'episode-plan', + 'run-sheet', + 'episode-brief', 'internal-research', ]); + const guestSections = template.sections.slice(0, 6); + const internalSections = template.sections.slice(6); + assert.ok(guestSections.every((section) => section.tab === 'guest' && !section.internal)); + assert.ok(internalSections.every((section) => section.tab === 'internal' && section.internal === true && !section.collapsible)); + assert.deepEqual( + internalSections.map((section) => section.fields.map((field) => field.key)), + [ + ['coldOpen', 'introScript', 'interviewQuestions', 'closingScript'], + ['goal', 'audience', 'keyMessages'], + ['sourceLinks', 'keyInsights', 'openQuestions', 'hostNotes'], + ], + ); const fields = template.sections.flatMap((section) => section.fields); const keys = fields.map((field) => field.key); assert.ok(keys.includes('slotChoice')); @@ -194,4 +209,98 @@ describe('podcast guest form (radio slot picker + topics; email stays one slot)' assert.ok(exported.includes('- **Sponsor**: Acme')); assert.ok(exported.includes('## Notes from Sponsor')); }); + + it('speakerTemplateView and speakerContentView strictly isolate podcast guest views and exports', () => { + const template = getSponsorDocTemplate('podcast'); + const speakerTemplate = speakerTemplateView(template); + assert.deepEqual( + speakerTemplate.sections.map((section) => section.id), + ['scheduling', 'who-you-are', 'topics', 'social-links', 'detailed-questions', 'notes'], + ); + assert.ok(speakerTemplate.sections.every((section) => !section.internal && section.tab === 'guest')); + + const fullContent: Record = { + proposedSlotLabel: 'Tue 3 Nov · 12:30–13:30 Berlin', + slotChoice: 'confirm_proposed', + guestTimezone: 'Europe/Berlin', + guestName: 'Jane Doe', + introduction: 'Principal Data Engineer', + photoUrl: 'https://example.test/jane.jpg', + currentFocus: 'Streaming pipelines', + topicsToCover: 'Flink, Kafka', + topicsToAvoid: 'Internal pricing', + linkedinUrl: 'https://linkedin.com/in/janedoe', + twitterUrl: 'https://x.com/janedoe', + githubUrl: 'https://github.com/janedoe', + websiteUrl: 'https://janedoe.example', + preparationMaterials: 'https://janedoe.example/post', + hookAndPainPoint: 'Why batch breaks', + keyInsightsAndMilestones: 'Moved to streaming in 2025', + actionableTakeaway: 'Start with idempotency', + sponsorNotes: 'Happy to answer live questions', + coldOpen: 'SECRET-COLD-OPEN', + introScript: 'SECRET-INTRO-SCRIPT', + interviewQuestions: 'SECRET-INTERVIEW-QUESTIONS', + closingScript: 'SECRET-CLOSING-SCRIPT', + goal: 'SECRET-GOAL', + audience: 'SECRET-AUDIENCE', + keyMessages: 'SECRET-KEY-MESSAGES', + sourceLinks: 'SECRET-SOURCE-LINKS', + keyInsights: 'SECRET-KEY-INSIGHTS', + openQuestions: 'SECRET-OPEN-QUESTIONS', + hostNotes: 'SECRET-HOST-NOTES', + strayUnknownKey: 'STRAY-UNKNOWN-VALUE', + }; + + const guestContent = speakerContentView('podcast', fullContent); + assert.equal(guestContent.guestName, 'Jane Doe'); + assert.equal(guestContent.topicsToCover, 'Flink, Kafka'); + assert.equal(guestContent.sponsorNotes, 'Happy to answer live questions'); + for (const secretKey of [ + 'coldOpen', + 'introScript', + 'interviewQuestions', + 'closingScript', + 'goal', + 'audience', + 'keyMessages', + 'sourceLinks', + 'keyInsights', + 'openQuestions', + 'hostNotes', + 'strayUnknownKey', + ]) { + assert.equal(Object.hasOwn(guestContent, secretKey), false, `expected ${secretKey} to be stripped`); + } + + const baseDoc = { + id: 'doc-iso', + title: 'Podcast — Materials from the Guest', + template: 'podcast' as const, + sponsorName: 'Jane Doe', + status: 'draft' as const, + lastEditedAt: '2026-11-21T00:00:00.000Z', + lastEditedBy: 'staff' as const, + }; + + const guestExport = renderSponsorDocMarkdownExport({ ...baseDoc, content: guestContent }); + assert.ok(guestExport.includes('## Notes from the Guest')); + assert.ok(!guestExport.includes('## Run Sheet & Interview Questions')); + assert.ok(!guestExport.includes('## Event Description & Episode Plan')); + assert.ok(!guestExport.includes('## Internal Research & Host Notes (Staff Only)')); + assert.ok(!guestExport.includes('SECRET-')); + + const staffExport = renderSponsorDocMarkdownExport({ ...baseDoc, content: fullContent }); + const notesIdx = staffExport.indexOf('## Notes from the Guest'); + const runSheetIdx = staffExport.indexOf('## Run Sheet & Interview Questions'); + const briefIdx = staffExport.indexOf('## Event Description & Episode Plan'); + const researchIdx = staffExport.indexOf('## Internal Research & Host Notes (Staff Only)'); + assert.ok(notesIdx > 0); + assert.ok(runSheetIdx > notesIdx); + assert.ok(briefIdx > runSheetIdx); + assert.ok(researchIdx > briefIdx); + assert.ok(staffExport.includes('SECRET-COLD-OPEN')); + assert.ok(staffExport.includes('SECRET-GOAL')); + assert.ok(staffExport.includes('SECRET-HOST-NOTES')); + }); }); diff --git a/backend/tests/sponsor-docs.test.ts b/backend/tests/sponsor-docs.test.ts index a2e57e4e..dd424b5b 100644 --- a/backend/tests/sponsor-docs.test.ts +++ b/backend/tests/sponsor-docs.test.ts @@ -8,12 +8,13 @@ import { sponsorDocKey } from '../src/db/sponsorDocs'; import { getClient } from '../src/db/client'; import { createTables, startLocal, stopLocal } from '../scripts/local-dynamodb'; -import { createCard } from '../src/db/cards'; +import { createCard, updateCard } from '../src/db/cards'; import { createTask, getTask } from '../src/db/tasks'; import { createPodcastEpisode } from '../src/db/podcastEpisodes'; import { createUser } from '../src/db/users'; import { humanBearer } from './helpers/human-bearer'; -import { getSponsorDoc, updateSponsorDoc } from '../src/db/sponsorDocs'; +import { getSponsorDoc, setSponsorDocEmailDelivery, updateSponsorDoc } from '../src/db/sponsorDocs'; +import { isAnonymousSponsorDocAsset } from '../src/routes/sponsorDocs'; import { setSponsorDocEmailDepsForTests } from '../src/sponsorDocs/emailDelivery'; import { NEWSLETTER_SPONSOR_EMAIL_TEMPLATE_ID, @@ -1032,13 +1033,27 @@ describe('Sponsor Content Docs API (/api/sponsor-docs)', () => { assert.ok(staffExport.body.includes('Rehearse Tuesday')); }); - it('keeps podcast research and host run sheets out of guest views and exports', async () => { + it('keeps podcast run sheet, episode brief, research, and hostContext isolated from guests while serving them to staff', async () => { + assert.equal(isAnonymousSponsorDocAsset('GET', '/src/surfaces/operations/sponsor-doc-podcast.js'), true); + const card = await createCard(client, { ...templateLink(), title: '[Podcast] 2026-12-03 - Jane Doe', anchorDate: '2026-12-03', people: ['Jane Doe'], }); + const qna = { + roomId: 'room-podcast-1', + slug: 'jane-doe-podcast', + url: 'https://qna.dtcdev.click/r/jane-doe-podcast', + presentUrl: 'https://qna.dtcdev.click/admin/rooms/room-podcast-1/present', + createdAt: '2026-11-21T10:00:00.000Z', + }; + await updateCard(client, card.id, { + expectedVersion: card.version, + patch: { sponsored: true, qna }, + }); + const episode = await createPodcastEpisode(client, { title: 'Shipping ML features', guests: [{ name: 'Jane Doe' }], @@ -1046,43 +1061,152 @@ describe('Sponsor Content Docs API (/api/sponsor-docs)', () => { recordingDate: '2026-12-03', cardId: card.id, }); + const internalFields: Record = { + coldOpen: 'PRIVATE-COLD-OPEN', + introScript: 'PRIVATE-INTRO-SCRIPT', + interviewQuestions: 'PRIVATE-INTERVIEW-QUESTIONS', + closingScript: 'PRIVATE-CLOSING-SCRIPT', + goal: 'PRIVATE-EPISODE-GOAL', + audience: 'PRIVATE-TARGET-AUDIENCE', + keyMessages: 'PRIVATE-KEY-MESSAGES', + sourceLinks: 'PRIVATE-RESEARCH-SOURCE', + keyInsights: 'PRIVATE-RESEARCH-FINDING', + openQuestions: 'PRIVATE-OPEN-QUESTIONS', + hostNotes: 'PRIVATE-RUN-SHEET-NOTE', + }; const createRes = await staffReq('POST', '/api/sponsor-docs', { cardId: episode.id, template: 'podcast', content: { guestName: 'Jane Doe', - interviewQuestions: 'SHARED-INTERVIEW-QUESTIONS', - sourceLinks: 'PRIVATE-RESEARCH-SOURCE', - keyInsights: 'PRIVATE-RESEARCH-FINDING', - openQuestions: 'PRIVATE-OPEN-QUESTIONS', - hostNotes: 'PRIVATE-RUN-SHEET-NOTE', + introduction: 'Staff data engineer building ML platforms', + topicsToCover: 'Feature stores, latency budgets', + topicsToAvoid: 'Unannounced roadmap', + ...internalFields, }, }); assert.equal(createRes.statusCode, 201, createRes.body); const { doc } = JSON.parse(createRes.body); + await setSponsorDocEmailDelivery(client, doc.id, { + state: 'sent', + from: 'orin@datatalks.club', + to: 'jane@example.test', + subject: 'Your podcast form', + }); + + for (const reqOpts of [ + { codeHeader: doc.accessCode, query: { tab: 'internal', view: 'questions' } }, + { query: { code: doc.accessCode, tab: 'internal', view: 'questions' } }, + ]) { + const guestRes = await anonReq('GET', `/api/sponsor-docs/${doc.id}`, reqOpts); + assert.equal(guestRes.statusCode, 200, guestRes.body); + const guestDoc = JSON.parse(guestRes.body).doc; + assert.equal(guestDoc.viewerRole, 'sponsor'); + assert.equal(guestDoc.content.guestName, 'Jane Doe'); + assert.equal(guestDoc.content.topicsToCover, 'Feature stores, latency budgets'); + assert.equal(guestDoc.templateDefinition.sections.filter((s: { internal?: boolean }) => s.internal).length, 0); + for (const key of Object.keys(internalFields)) { + assert.equal(guestDoc.content[key], undefined, `guest must not receive ${key}`); + assert.equal(Object.hasOwn(guestDoc.content, key), false); + } + assert.equal(guestDoc.hostContext, undefined); + assert.equal(guestDoc.emailDelivery, undefined); + assert.equal(guestDoc.accessCode, undefined); + assert.equal(guestDoc.shareUrl, undefined); + assert.equal(guestDoc.emailDraft, undefined); + assert.doesNotMatch(guestDoc.markdownExport, /PRIVATE-/); + } - const guestRes = await anonReq('GET', `/api/sponsor-docs/${doc.id}`, { codeHeader: doc.accessCode }); - assert.equal(guestRes.statusCode, 200, guestRes.body); - const guestDoc = JSON.parse(guestRes.body).doc; - assert.equal(guestDoc.content.interviewQuestions, 'SHARED-INTERVIEW-QUESTIONS'); - assert.equal(guestDoc.content.sourceLinks, undefined); - assert.equal(guestDoc.content.hostNotes, undefined); + for (const format of ['markdown', 'json', 'txt'] as const) { + const guestExport = await anonReq('GET', `/api/sponsor-docs/${doc.id}/export`, { + codeHeader: doc.accessCode, + query: { format }, + }); + assert.equal(guestExport.statusCode, 200, guestExport.body); + const exportedText = format === 'json' ? JSON.parse(guestExport.body).markdown : guestExport.body; + assert.ok(exportedText.includes('Feature stores, latency budgets')); + for (const value of Object.values(internalFields)) { + assert.ok(!exportedText.includes(value), `${format} export leaked ${value}`); + } + } - const guestExport = await anonReq('GET', `/api/sponsor-docs/${doc.id}/export`, { + const { fromBuffer } = await import('yauzl'); + const guestDocx = await anonReq('GET', `/api/sponsor-docs/${doc.id}/export`, { codeHeader: doc.accessCode, - query: { format: 'markdown' }, + query: { format: 'docx' }, }); - assert.equal(guestExport.statusCode, 200, guestExport.body); - assert.ok(guestExport.body.includes('SHARED-INTERVIEW-QUESTIONS')); - assert.ok(!guestExport.body.includes('PRIVATE-RESEARCH-SOURCE')); - assert.ok(!guestExport.body.includes('PRIVATE-RUN-SHEET-NOTE')); + assert.equal(guestDocx.statusCode, 200, guestDocx.body); + const docxXml = await new Promise((resolve, reject) => + fromBuffer(Buffer.from(guestDocx.body, 'base64'), { lazyEntries: true }, (error, zip) => { + if (error || !zip) return reject(error); + zip.on('error', reject); + zip.on('entry', (entry) => { + if (entry.fileName !== 'word/document.xml') return zip.readEntry(); + zip.openReadStream(entry, (streamError, stream) => { + if (streamError || !stream) return reject(streamError); + const chunks: Buffer[] = []; + stream.on('data', (chunk) => chunks.push(chunk)); + stream.on('error', reject); + stream.on('end', () => { + zip.close(); + resolve(Buffer.concat(chunks).toString('utf8')); + }); + }); + }); + zip.readEntry(); + }), + ); + assert.ok(docxXml.includes('Feature stores, latency budgets')); + for (const value of Object.values(internalFields)) { + assert.ok(!docxXml.includes(value), `docx export leaked ${value}`); + } + + const guestPut = await anonReq('PUT', `/api/sponsor-docs/${doc.id}`, { + codeHeader: doc.accessCode, + body: { + content: { + currentFocus: 'GUEST-UPDATE', + interviewQuestions: 'HIJACK', + coldOpen: 'HIJACK', + hostNotes: 'HIJACK', + sourceLinks: 'HIJACK', + }, + }, + }); + assert.equal(guestPut.statusCode, 200, guestPut.body); + const guestPutDoc = JSON.parse(guestPut.body).doc; + assert.equal(guestPutDoc.content.currentFocus, 'GUEST-UPDATE'); + assert.equal(guestPutDoc.emailDelivery, undefined); + assert.equal(guestPutDoc.hostContext, undefined); + for (const key of Object.keys(internalFields)) { + assert.equal(guestPutDoc.content[key], undefined); + } + + const storedAfterGuestPut = await getSponsorDoc(client, doc.id); + for (const [key, value] of Object.entries(internalFields)) { + assert.equal(storedAfterGuestPut?.content[key], value, `guest PUT overwrote ${key}`); + } const staffRes = await staffReq('GET', `/api/sponsor-docs/${doc.id}`); assert.equal(staffRes.statusCode, 200, staffRes.body); const staffDoc = JSON.parse(staffRes.body).doc; - assert.equal(staffDoc.content.sourceLinks, 'PRIVATE-RESEARCH-SOURCE'); - assert.equal(staffDoc.content.hostNotes, 'PRIVATE-RUN-SHEET-NOTE'); - assert.ok(staffDoc.markdownExport.includes('PRIVATE-RESEARCH-SOURCE')); + assert.equal(staffDoc.viewerRole, 'staff'); + assert.equal(staffDoc.templateDefinition.sections.length, 9); + const staffInternalSections = staffDoc.templateDefinition.sections.filter( + (s: { tab?: string; internal?: boolean }) => s.tab === 'internal' && s.internal === true, + ); + assert.equal(staffInternalSections.length, 3); + assert.equal(staffDoc.content.currentFocus, 'GUEST-UPDATE'); + for (const [key, value] of Object.entries(internalFields)) { + assert.equal(staffDoc.content[key], value); + assert.ok(staffDoc.markdownExport.includes(value), `staff markdownExport missing ${key}`); + } + assert.deepEqual(staffDoc.hostContext, { + cardId: card.id, + sponsored: true, + qna, + }); + assert.equal(staffDoc.emailDelivery?.state, 'sent'); }); it('rejects switching a webinar form to the workshop type: documents stay inside the card format', async () => { diff --git a/frontend/src/sponsor-doc.html b/frontend/src/sponsor-doc.html index 9d687571..3688af7b 100644 --- a/frontend/src/sponsor-doc.html +++ b/frontend/src/sponsor-doc.html @@ -22,6 +22,7 @@
+