Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions backend/e2e/podcast-guest-form.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,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: 25,
episode: 8,
season: 26,
episode: 1,
releaseAssignmentStatus: "provisional",
releaseDate: releaseFriday(7),
title: "Guest form alias e2e",
Expand All @@ -121,6 +121,7 @@ test.describe("podcast guest materials form", () => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto(`${server.baseURL}/sponsor-docs/${doc.id}?code=${encodeURIComponent(doc.accessCode)}`);
await expect(page.locator('[data-sponsor-view="editor"]')).toBeVisible();
expect(page.url()).toContain(`/podcast-docs/${doc.id}`);
const aliasGuestRegions = page.locator(
".sponsor-doc-meta, .sponsor-doc-form-card, [data-sponsor-export]",
);
Expand Down
26 changes: 26 additions & 0 deletions backend/src/calendar/cardInvite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { recordTemplateTypes } from '../cards/cardTitlePattern';
import { deleteHoldGoogleEvents, fetchGoogleEvent, findGoneGoogleEvents, mergeHoldGoogleResults, syncLumaCalendarEvents, syncSilentGoogleCopies, type HoldGoogleDeps, type HoldGoogleResult } from './holdGoogleSync';
import { lumaUrlForEventCard } from './lumaEvents';
import { PUBLIC_DTC_EVENTS_CALENDAR, resolveHoldGoogleCalendars } from './dapierBroker';
import { decryptSponsorDocAccessCode, getSponsorDocWithAuthMaterial } from '../db/sponsorDocs';

/** AISHL workshops are scheduled by the AISHL site event, which sends its own invite and Zoom. */
const AISHL_TEMPLATE_TYPE = 'aishl-workshop';
Expand Down Expand Up @@ -79,6 +80,30 @@ export function cardGuestDocument(card: Card): string | undefined {
catch { throw new CardInviteInputError('The Card guest document must be an HTTPS URL.'); }
}

/**
* Append `?code=...` to a `/podcast-docs/<id>` URL when the document has a
* decryptable access code so both the guest and Alexey can open it from the
* calendar invite without looking up the code.
*/
export async function resolveGuestDocumentUrlWithCode(
client: DynamoDBDocumentClient,
rawUrl: string | undefined,
): Promise<string | undefined> {
if (!rawUrl) return rawUrl;
const match = /^https:\/\/[^/]+\/podcast-docs\/([^/?#]+)\/?$/.exec(rawUrl.trim());
if (!match) return rawUrl;
const docId = decodeURIComponent(match[1]);
try {
const loaded = await getSponsorDocWithAuthMaterial(client, docId);
if (!loaded) return rawUrl;
const accessCode = decryptSponsorDocAccessCode(docId, loaded.accessCodeCiphertext);
if (!accessCode) return rawUrl;
return `${rawUrl.replace(/\/$/, '')}?code=${encodeURIComponent(accessCode)}`;
} catch {
return rawUrl;
}
}

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
export function parseCardGuests(raw: unknown): string[] {
if (!Array.isArray(raw) || !raw.length || raw.length > 20) throw new Error('guestEmails must contain 1 to 20 guest email addresses');
Expand Down Expand Up @@ -298,6 +323,7 @@ export async function syncCardInvite(
const cardDocument = cardGuestDocument(card);
documentUrl = (cardDocument && DATAOPS_GUEST_DOC.test(cardDocument) ? cardDocument : undefined)
|| parseHoldDocumentUrl(linkedHold?.documentUrl) || cardDocument;
documentUrl = await resolveGuestDocumentUrlWithCode(client, documentUrl);
} catch { throw new CardInviteInputError('The guest document must be an HTTPS URL.'); }
invite = {
...buildGuestInvite({
Expand Down
11 changes: 10 additions & 1 deletion backend/src/cards/recordCardLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,16 @@ function projected(card: Card, templateIdByType: Map<string, string>): Card {
export async function summarizeCard(
client: DynamoDBDocumentClient,
card: Card,
): Promise<CardSummary> {
): Promise<CardSummary & { podcastDocUrl?: string }> {
const view = projected(card, await getTemplateIdByType(client));
const podcastLink = (card.cardLinks || []).find((l) => /\/podcast-docs\/[^/?#]+/.test(String(l.url || '')));
let podcastDocUrl = podcastLink?.url ? String(podcastLink.url).trim() : undefined;
if (!podcastDocUrl) {
const { listSponsorDocSummariesByCardId } = await import('../db/sponsorDocs');
const docs = await listSponsorDocSummariesByCardId(client, card.id);
const podDoc = docs.find((d) => d.template === 'podcast');
if (podDoc) podcastDocUrl = `/podcast-docs/${encodeURIComponent(podDoc.id)}`;
}
return {
id: card.id,
title: String(view.title || ''),
Expand All @@ -52,6 +60,7 @@ export async function summarizeCard(
anchorDate: view.anchorDate || null,
taskCount: card.taskCount,
openTaskCount: card.openTaskCount,
...(podcastDocUrl ? { podcastDocUrl } : {}),
};
}

Expand Down
7 changes: 5 additions & 2 deletions backend/src/events/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
cardGuests,
closeCardInviteTasks,
parseCardGuests,
resolveGuestDocumentUrlWithCode,
resolvePodcastCardInviteTitle,
} from '../calendar/cardInvite';
import { GuestInviteValidationError, isPodcastTemplateType, type GuestInvite } from '../calendar/guestInvite';
Expand Down Expand Up @@ -782,10 +783,11 @@ async function runTransition(
(card.people?.length
? card.people.join(', ')
: episode?.guests?.map((g) => g.name).join(', ') || current?.renderValues?.guestNames || '');
const documentUrl =
const rawDocUrl =
input.documentUrl !== undefined
? input.documentUrl
: current?.renderValues?.documentUrl || cardGuestDocument(card) || '';
const documentUrl = (await resolveGuestDocumentUrlWithCode(client, rawDocUrl)) || '';

let time = input.time;
let proposalDate = input.date || current?.date || card.anchorDate;
Expand Down Expand Up @@ -857,10 +859,11 @@ async function runTransition(
(card.people?.length
? card.people.join(', ')
: episode?.guests?.map((g) => g.name).join(', ') || '');
const documentUrl =
const rawDocUrl =
input.documentUrl !== undefined
? input.documentUrl
: current.renderValues.documentUrl || cardGuestDocument(card) || '';
const documentUrl = (await resolveGuestDocumentUrlWithCode(client, rawDocUrl)) || '';
command = {
transition: 'update',
operationKey,
Expand Down
5 changes: 4 additions & 1 deletion backend/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ import { handleInvoiceReader } from './auth/invoiceReader';
import { handleKnowledgePublisher } from './auth/knowledgePublisher';
import { isScopedTokenRequestAllowed } from './auth/tokenScopes';
import { getApiToken, projectApiToken } from './db/apiTokens';
import { handleSponsorDocRoutes, isAnonymousSponsorDocRequest } from './routes/sponsorDocs';
import { handleSponsorDocRoutes, isAnonymousSponsorDocRequest, redirectLegacySponsorDocPath } from './routes/sponsorDocs';
import { handleClientErrorRoute, isClientErrorReport } from './routes/clientErrors';
import { handleEmailTemplateRoutes } from './routes/emailTemplates';
import { handleApiTokenRoutes } from './routes/apiTokens';
Expand Down Expand Up @@ -203,6 +203,9 @@ async function route(event: LambdaEvent, client: DynamoDBDocumentClient): Promis
if (publisherResponse) return publisherResponse;
}

const legacyDocRedirect = await redirectLegacySponsorDocPath(event, client);
if (legacyDocRedirect) return legacyDocRedirect;

// ── Single-origin portal layer (docs domain, flag-gated) ─────
// When the docs domain is enabled, the portal serves the frontend, the docs
// content API, and `/content/*`, and enforces the opaque browser session. A verified portal
Expand Down
3 changes: 3 additions & 0 deletions backend/src/routes/cards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -777,6 +777,9 @@ async function handleSingle(
'sourceDocIds', 'artifactRefs', 'intakeRefs',
'people', 'sponsor', 'secondarySponsors', 'issueNumber', 'sponsored',
];
if (body.sponsored !== undefined && typeof body.sponsored !== 'boolean') {
return json(400, { error: 'sponsored must be a boolean' });
}
if (body.anchorDate !== undefined && body.anchorDate !== null
&& (typeof body.anchorDate !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(body.anchorDate))) {
return json(400, { error: 'Invalid anchorDate format, expected YYYY-MM-DD' });
Expand Down
86 changes: 64 additions & 22 deletions backend/src/routes/sponsorDocs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ import { FileStorageError } from '../storage';
import { savePublicImage } from '../publicImages';
import { extractMultipartImageBuffer, publicImagePayload } from './publicImages';
import {
LEGACY_PODCAST_DOC_TEMPLATES,
SPONSOR_DOC_CREATABLE_TEMPLATE_KEYS,
SPONSOR_DOC_TEMPLATES,
SponsorDocValidationError,
getSponsorDocTemplate,
Expand Down Expand Up @@ -174,7 +176,41 @@ function requestIp(event: LambdaEvent): string {
export function sponsorDocPathForTemplate(template: string | null | undefined): string {
if (template === 'webinar') return '/webinar-docs';
if (template === 'workshop') return '/workshop-docs';
return template === 'podcast' ? '/podcast-docs' : '/sponsor-docs';
if (template === 'podcast' || String(template || '').startsWith('podcast-')) return '/podcast-docs';
return '/sponsor-docs';
}

/**
* Redirect legacy `/sponsor-docs/:id` requests for podcast/webinar/workshop
* documents to their canonical `/podcast-docs/:id` (or webinar/workshop) URL,
* preserving query parameters (e.g. `?code=...`).
*/
export async function redirectLegacySponsorDocPath(
event: LambdaEvent,
client: DynamoDBDocumentClient,
): Promise<LambdaResponse | null> {
if ((event.httpMethod || 'GET').toUpperCase() !== 'GET') return null;
const match = /^\/sponsor-docs\/([^/?#]+)\/?$/.exec(event.path || '');
if (!match) return null;
const docId = decodeURIComponent(match[1]);
const loaded = await getSponsorDocWithAuthMaterial(client, docId);
if (!loaded) return null;
const canonicalPrefix = sponsorDocPathForTemplate(loaded.doc.template);
if (canonicalPrefix === '/sponsor-docs') return null;
const rawQuery = event.queryStringParameters && Object.keys(event.queryStringParameters).length > 0
? `?${new URLSearchParams(
Object.entries(event.queryStringParameters).filter((e): e is [string, string] => typeof e[1] === 'string'),
).toString()}`
: '';
return {
statusCode: 302,
headers: {
Location: `${canonicalPrefix}/${encodeURIComponent(docId)}${rawQuery}`,
'Cache-Control': 'no-store',
'Referrer-Policy': 'no-referrer',
},
body: '',
};
}

export function sponsorDocPortalBaseUrl(event: LambdaEvent): string {
Expand Down Expand Up @@ -522,7 +558,9 @@ export async function handleSponsorDocRoutes(
if (m === 'GET' && /^\/templates\/?$/.test(suffix)) {
const actor = await resolveInteractiveActor(client, event, 'work-read');
if (!actor.ok) return actor.response;
return json(200, { templates: Object.values(SPONSOR_DOC_TEMPLATES) });
return json(200, {
templates: SPONSOR_DOC_CREATABLE_TEMPLATE_KEYS.map((key) => SPONSOR_DOC_TEMPLATES[key]),
});
}

// Collection: GET /api/sponsor-docs, POST /api/sponsor-docs
Expand Down Expand Up @@ -619,9 +657,9 @@ export async function handleSponsorDocRoutes(
let template: SponsorDocTemplateKey;
if (body.template !== undefined && body.template !== null && String(body.template).trim() !== '') {
const requested = String(body.template).trim();
if (!isSponsorDocTemplateKey(requested)) {
if (!isSponsorDocTemplateKey(requested) || LEGACY_PODCAST_DOC_TEMPLATES.includes(requested)) {
return json(400, {
error: `Invalid template "${requested}". Must be one of: newsletter-main, newsletter-secondary, newsletter-standalone, webinar, podcast, podcast-guest-research, podcast-run-sheet, podcast-episode-brief`,
error: `Invalid template "${requested}". Must be one of: ${SPONSOR_DOC_CREATABLE_TEMPLATE_KEYS.join(', ')}`,
code: 'invalid_template',
});
}
Expand All @@ -648,23 +686,13 @@ export async function handleSponsorDocRoutes(
template = 'newsletter-main';
}

// Guest research and host run sheets start only after the date is
// confirmed (a recording date on the owning episode). The guest
// materials doc and the episode brief stay available before confirm.
if (template === 'podcast-guest-research' || template === 'podcast-run-sheet') {
const datedOwner = existingEpisode?.recordingDate
? existingEpisode
: existingCard
? (await listPodcastEpisodes(client)).find(
(episode) => episode.cardId === existingCard.id && episode.recordingDate,
)
: undefined;
if (!datedOwner) {
return json(422, {
error: 'Guest research and run sheets start only after the date is confirmed: set the episode recording date first (dataops podcast update <episode-id> --recording-date YYYY-MM-DD).',
code: 'date_not_confirmed',
});
}
// Event cards (podcast, webinar, workshop) never create sponsor-docs.
const cardType = existingCard ? (cardTemplateType(existingCard, templateIdByType) || '') : '';
if ((existingEpisode || ['podcast', 'webinar', 'workshop'].includes(cardType)) && template.startsWith('newsletter-')) {
return json(422, {
error: 'Event cards (podcast, webinar, workshop) do not use sponsorship documents.',
code: 'event_card_no_sponsor_docs',
});
}

// An event Card carries only its format's documents: a workshop
Expand All @@ -685,6 +713,20 @@ export async function handleSponsorDocRoutes(
return json(422, { error: 'Link this event document to a Card first.', code: 'event_card_required' });
}

// Enforce max ONE podcast document per podcast card.
const ownerForCheck = existingCard?.id || existingIssue?.id || existingEpisode?.id || '';
if (template === 'podcast' && ownerForCheck) {
const existingDocs = await listSponsorDocSummariesByCardId(client, ownerForCheck);
const existingPodcastDoc = existingDocs.find((d) => d.template === 'podcast');
if (existingPodcastDoc) {
return json(409, {
error: `This podcast card already has a guest document (${existingPodcastDoc.id}). Only one podcast document is allowed per card.`,
code: 'podcast_doc_already_exists',
existingDocId: existingPodcastDoc.id,
});
}
}

const publicationDate = typeof body.publicationDate === 'string' && body.publicationDate.trim()
? body.publicationDate.trim()
: existingIssue?.publicationDate
Expand Down Expand Up @@ -1072,7 +1114,7 @@ export async function handleSponsorDocRoutes(

const access = await resolveStaffOrSponsorAccess(client, event, 'work-write', body);
if (access.isStaff) {
if (body.template !== undefined && !isSponsorDocTemplateKey(body.template)) {
if (body.template !== undefined && (!isSponsorDocTemplateKey(body.template) || LEGACY_PODCAST_DOC_TEMPLATES.includes(body.template))) {
return json(400, { error: 'Unknown template', code: 'invalid_template' });
}
const loaded = await getSponsorDocWithAuthMaterial(client, docId);
Expand Down
Loading