diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 21f160b268..82b178d4a2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -140,7 +140,9 @@ jobs: if [ "${{ matrix.app }}" = whiteboard ]; then node --test --test-shard="$SHARD" tests/*.test.js elif [ "$MODE" = affected ]; then - npx vitest run --changed "$BASE" --passWithNoTests --shard="$SHARD" + # --changed traces every test file's imports in one process; for + # spreadsheet's ~3,500 files that peaks just over Node's default heap. + NODE_OPTIONS=--max-old-space-size=8192 npx vitest run --changed "$BASE" --passWithNoTests --shard="$SHARD" else npx vitest run --passWithNoTests --shard="$SHARD" fi diff --git a/src/calendar/README.md b/src/calendar/README.md index 0a3c40f4d6..fae70fb063 100644 --- a/src/calendar/README.md +++ b/src/calendar/README.md @@ -232,17 +232,25 @@ Every invitation names its host. The .ics `ORGANIZER` is the signed-in account's email — what the guest's calendar shows as the organizer (Google Calendar files an event without one under `unknownorganizer@calendar.google.com`) and where their mail client's own RSVP -buttons answer. Puter withholds that address until the user allows the app to -read it, so a send that doesn't know it asks — on a press of **Email +buttons answer. A team account's email is its team's claim rather than an +address it proved, so Puter's `senderEmail` for it is its own +`@puter.email`, and invitations and booking confirmations name that +instead; the event keeps the account email, and the host's own booking notices +go to that email once confirmed, else to the sending address. Puter withholds +both addresses until the user allows the app to read their email, so a send that doesn't know it asks — on a press of **Email invitations**, never from the after-save send, which the editor has just asked for — and if there is still no address, nothing is sent and the toast says why. The email worker takes none of that on trust. It reads the sender's identity from their Puter session, never from the request: the mail's Reply-To is always the sender's own `@puter.email`, and an organizer that is neither -that mailbox nor the account's confirmed email is refused (`organizer_mismatch`) -— including when Puter shares no account email to compare against. A session -the worker cannot pin to a username sends nothing. +that mailbox, the session's `senderEmail`, nor the account's confirmed email is +refused (`organizer_mismatch`) +— including when Puter shares no account email to compare against. Older +accounts that were never asked to confirm their email hit this with their own +address; the refusal then carries `detail: 'email_unconfirmed'` and the app asks +them to confirm it at puter.com. A session the worker cannot pin to a username +sends nothing. **Cancelling.** Deleting an event whose guests were emailed asks one more question — **Send cancellation emails?** — because to those guests the event is diff --git a/src/calendar/src/js/booking.js b/src/calendar/src/js/booking.js index d6663d3f18..6f79af21a5 100644 --- a/src/calendar/src/js/booking.js +++ b/src/calendar/src/js/booking.js @@ -328,6 +328,8 @@ export function createBooking({ let lastPullAt = 0; let lastDigest = ''; let selfEmail = user && typeof user.email === 'string' ? user.email.trim().toLowerCase() : ''; + // The organizer shown to guests can differ from the local event's organizer. + let senderEmail = user && typeof user.senderEmail === 'string' ? user.senderEmail.trim().toLowerCase() : ''; const selfName = (user && typeof user.username === 'string' && user.username) || ''; // The host's profile picture as last resolved for publishing, and when that // was (see organizerPicture). @@ -1064,6 +1066,9 @@ export function createBooking({ if (fresh && typeof fresh.email === 'string' && fresh.email) { selfEmail = fresh.email.trim().toLowerCase(); } + if (fresh && typeof fresh.senderEmail === 'string' && fresh.senderEmail) { + senderEmail = fresh.senderEmail.trim().toLowerCase(); + } } const list = getPages(); @@ -1089,7 +1094,7 @@ export function createBooking({ pages: list, busy: computeBusy(store, horizon, now(), { alreadyKnown: workerKnows }), organizerName: displayName(), - organizerEmail: selfEmail, + organizerEmail: senderEmail || selfEmail, // Read only for the pages that publish it, and only as often as its TTL // allows — a host with no such page never requests their profile picture. organizerPicture: await organizerPicture(list.some((p) => p.avatar)), diff --git a/src/calendar/src/js/invites.js b/src/calendar/src/js/invites.js index 08fc3e3bc3..3e9164fe33 100644 --- a/src/calendar/src/js/invites.js +++ b/src/calendar/src/js/invites.js @@ -74,6 +74,10 @@ export const NO_HOST_EMAIL = export const ACCOUNT_NOT_VERIFIED = 'Sending email needs a Puter account with a confirmed email address. Create one or confirm yours, then send again.'; +/** The worker's answer when the host's address is their own, still-unconfirmed account email. */ +export const EMAIL_UNCONFIRMED = + 'Your Puter account email is not confirmed, so mail cannot be sent from it. Confirm it at puter.com, then send again.'; + /** A stored or reported address, or '' for anything that isn't one. */ function normalizeEmail(value) { return typeof value === 'string' ? value.trim().toLowerCase() : ''; @@ -261,7 +265,7 @@ export function createInvites({ // worker, and the platform takes 5–30s to bring one up. readyTimeoutMs = 120_000, }) { - // eventId -> { [email]: { at, v } } + // eventId -> { [email]: { at, v, organizerEmail? } } const sent = new Map(); // Who "I" am, for events that carry no organizer of their own: one saved // before organizers were stamped, or while my address was unknown (Puter @@ -269,6 +273,38 @@ export function createInvites({ // refusal rather than lose the edit). Boot's user object has the first word; // hostEmail() the last. let selfEmail = normalizeEmail(user && user.email); + // The address Puter says mail sent for me should use (whoami's senderEmail). + // A team account's is its own @puter.email: its email is the team's + // claim, which the email worker won't name as an organizer. Events keep + // selfEmail as their organizer; only outgoing mail is rewritten. + let sender = normalizeEmail(user && user.senderEmail); + let selfUnconfirmed = isUnconfirmed(user); + + function isUnconfirmed(account) { + return Boolean(account) && (account.email_confirmed === false || account.email_confirmed === 0); + } + + /** The organizer mail names: the one guests were already sent, else mine as `sender`. */ + function organizerForMail(ev) { + const address = normalizeEmail(ev.organizer?.email) || selfEmail; + const mine = !address || address === selfEmail; + const previous = Object.values(sent.get(ev.id) || {})[0]; + if (previous?.organizerEmail) return previous.organizerEmail; + // A log from before senderEmail mailed the event's own address, which an + // unconfirmed email can no longer send as. + if (previous && !(mine && selfUnconfirmed)) return address; + return sender && mine ? sender : address; + } + + function sentEvent(ev, address) { + const organizer = address ? { ...ev.organizer, email: address } : ev.organizer; + if (!address || !selfEmail || address === selfEmail) return { ...ev, organizer }; + const seen = new Set(); + const guests = (ev.guests || []) + .map((g) => (normalizeEmail(g.email) === selfEmail ? { ...g, email: address } : g)) + .filter((g) => !seen.has(normalizeEmail(g.email)) && seen.add(normalizeEmail(g.email))); + return { ...ev, organizer, guests }; + } /** * My address, resolving it if boot did not know it. A grant that landed since @@ -283,10 +319,11 @@ export function createInvites({ let email = ''; try { if (prompt) email = normalizeEmail(await requestEmail()); - else { - const fresh = await requestUser(); - email = normalizeEmail(fresh && fresh.email); - } + // senderEmail rides the same grant, so a fresh read also follows a prompt. + const fresh = !prompt || email ? await requestUser() : null; + if (!prompt) email = normalizeEmail(fresh && fresh.email); + if (fresh && fresh.senderEmail) sender = normalizeEmail(fresh.senderEmail); + if (fresh) selfUnconfirmed = isUnconfirmed(fresh); } catch { /* unresolved — the caller decides what an anonymous send is worth */ } @@ -443,7 +480,9 @@ export function createInvites({ // Resolve it before the plan is read (its digests include the address), or // refuse: an anonymous invitation files under an unknown organizer in the // guest's calendar and gives their RSVP buttons nobody to answer. - if (!ev.organizer && !(await hostEmail({ prompt }))) throw new Error(NO_HOST_EMAIL); + if (!selfEmail && !sender) await hostEmail({ prompt }); + const organizerEmail = organizerForMail(ev); + if (!organizerEmail) throw new Error(NO_HOST_EMAIL); const plan = planFor(item); const wanted = emails ? new Set(emails) : null; @@ -466,9 +505,7 @@ export function createInvites({ // an earlier email installed. let ics = ''; try { - const icsEvent = - ev.organizer || !selfEmail ? ev : { ...ev, organizer: { email: selfEmail } }; - ics = toICS([icsEvent], { + ics = toICS([sentEvent(ev, organizerEmail)], { method: 'REQUEST', tzid: localTz(), sequence: Math.max(0, (ev.updatedAt || 0) - 1577836800000) / 1000, @@ -501,7 +538,7 @@ export function createInvites({ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ - event: { id: ev.id, ...details }, + event: { id: ev.id, ...details, organizerEmail }, recipients: batch.recipients, kind: batch.kind, note, @@ -532,7 +569,7 @@ export function createInvites({ if (result.status !== 'sent' && result.status !== 'skipped') continue; const recipient = batch.recipients.find((r) => r.email === result.email); if (!recipient) continue; - log[result.email] = { at: result.at || Date.now(), v: recipient.version }; + log[result.email] = { at: result.at || Date.now(), v: recipient.version, organizerEmail }; } } // Record what DID go out even when a later batch failed, or a retry after @@ -666,7 +703,8 @@ export function createInvites({ // is picked up; nothing is asked for and nothing refused — this is the // guests' one chance to hear the event is off. const details = { ...snapshot.details }; - if (!details.organizerEmail) details.organizerEmail = await hostEmail(); + if (!selfEmail && !sender) await hostEmail(); + details.organizerEmail = organizerForMail(snapshot.event) || details.organizerEmail; // METHOD:CANCEL + STATUS:CANCELLED is the iTIP retraction of the METHOD: // REQUEST the invitation carried: same UID, and a SEQUENCE above every one @@ -674,9 +712,7 @@ export function createInvites({ // precedes this deletion; +1 clears even a delete in the same second. let ics = ''; try { - const ev = snapshot.event; - const icsEvent = ev.organizer || !selfEmail ? ev : { ...ev, organizer: { email: selfEmail } }; - ics = toICS([icsEvent], { + ics = toICS([sentEvent(snapshot.event, details.organizerEmail)], { method: 'CANCEL', // Withdrawing attendees must not declare the event itself cancelled // (RFC 5546 §3.2.5); ATTENDEE names only those being removed. @@ -785,6 +821,7 @@ export function createInvites({ return 'Sign in to Puter again to send the cancellation.'; } if (code === 'account_not_verified') return ACCOUNT_NOT_VERIFIED; + if (data && data.detail === 'email_unconfirmed') return EMAIL_UNCONFIRMED; if (status === 429 || code === 'daily_limit') { return "You've reached today's email limit. Try again tomorrow."; } @@ -873,6 +910,7 @@ export function createInvites({ } if (status === 404) return 'The invitation service is unavailable right now.'; if (code === 'account_not_verified') return ACCOUNT_NOT_VERIFIED; + if (data && data.detail === 'email_unconfirmed') return EMAIL_UNCONFIRMED; // The worker binds the mail's organizer to the signed-in account; a // mismatch means the session and this window disagree about who that is. if (status === 403 || code === 'organizer_mismatch') { diff --git a/src/calendar/src/js/mail-reply.js b/src/calendar/src/js/mail-reply.js index 9872f46c84..f9a98b8b2d 100644 --- a/src/calendar/src/js/mail-reply.js +++ b/src/calendar/src/js/mail-reply.js @@ -24,7 +24,7 @@ * dialog, and `sendReply` is reached solely through its "Send" button. */ import { toICS } from './ics.js'; -import { EMAIL_WORKER_URL, ACCOUNT_NOT_VERIFIED, digest, describeWhen } from './invites.js'; +import { EMAIL_WORKER_URL, ACCOUNT_NOT_VERIFIED, EMAIL_UNCONFIRMED, digest, describeWhen } from './invites.js'; import { getUser, requestUserEmail } from './auth.js'; import { isBlocked } from './offline.js'; import { toast as defaultToast } from './toast.js'; @@ -94,6 +94,7 @@ function replyFailureMessage(status, data) { if (status === 401 || code === 'sign_in_required') return 'Sign in to Puter again to send your reply.'; if (status === 429 || code === 'daily_limit') return "You've reached today's email limit. Try again tomorrow."; if (code === 'account_not_verified') return ACCOUNT_NOT_VERIFIED; + if (data && data.detail === 'email_unconfirmed') return EMAIL_UNCONFIRMED; if (status === 403 || code === 'attendee_mismatch') { return 'Sign in to Puter again — this reply would not be sent from your account.'; } @@ -129,29 +130,23 @@ export function createMailReply({ requestUser = getUser, requestEmail = requestUserEmail, }) { - let selfEmail = normalizeEmail(user && user.email); - let selfUsername = (user && user.username) || ''; + let account = user; async function resolveSelf() { - if (!selfEmail || !selfUsername) { + if (!account?.email || !account.username) { try { - const fresh = await requestUser(); - if (fresh) { - selfUsername = selfUsername || fresh.username || ''; - selfEmail = selfEmail || normalizeEmail(fresh.email); - } + account = (await requestUser()) || account; + if (!account?.email && await requestEmail()) account = (await requestUser()) || account; } catch { - /* unresolved — the caller decides what an anonymous reply is worth */ + /* The Puter mailbox can still answer without an email grant. */ } } - if (!selfEmail) { - try { - selfEmail = normalizeEmail(await requestEmail()); - } catch { - /* a refusal here just means no reply can be sent */ - } - } - return { email: selfEmail, username: selfUsername }; + const confirmed = account?.email_confirmed === true || account?.email_confirmed === 1; + return { + username: account?.username || '', + email: confirmed ? normalizeEmail(account.email) : '', + sender: normalizeEmail(account?.senderEmail), + }; } function available() { @@ -255,7 +250,8 @@ export function createMailReply({ const inviteAttendee = event.invite && typeof event.invite.attendee === 'string' ? normalizeEmail(event.invite.attendee) : ''; - const attendeeEmail = inviteAttendee || self.email || `${self.username}@puter.email`; + const mailbox = `${self.username.toLowerCase()}@puter.email`; + const attendeeEmail = inviteAttendee || self.sender || self.email || mailbox; const title = event.title || '(No title)'; const when = describeWhen(event, { hour12: store.getSettings().hour12 !== false }); diff --git a/src/calendar/src/js/rsvp-links.js b/src/calendar/src/js/rsvp-links.js index 2767f0d3b7..2356c6bd62 100644 --- a/src/calendar/src/js/rsvp-links.js +++ b/src/calendar/src/js/rsvp-links.js @@ -120,7 +120,9 @@ import { toast as defaultToast } from './toast.js'; // '30': forces each user's RSVP worker to redeploy onto the current runtime // (puter.js with email.sendTransactional); /admin/ping reports it as runtime. // '31': a guest's answer notifies the host through puter.notifications. -export const RSVP_WORKER_VERSION = '32'; +// '33': booking mail takes the host's addresses from the worker owner's session +// (senderEmail, else the confirmed email), not from the synced config. +export const RSVP_WORKER_VERSION = '33'; const CFG_KEY = 'cal:rsvp:cfg'; const LINKS_PREFIX = 'cal:rsvp:links:'; @@ -260,6 +262,7 @@ export function createRsvpLinks({ }) { let cfg = null; let selfEmail = user && typeof user.email === 'string' ? user.email.trim().toLowerCase() : ''; + let senderEmail = user?.senderEmail?.trim().toLowerCase() || ''; let started = false; let timer = null; let pollTimer = null; @@ -319,7 +322,7 @@ export function createRsvpLinks({ function linkableGuests(ev) { const organizerEmail = ev.organizer ? ev.organizer.email : selfEmail; return (Array.isArray(ev.guests) ? ev.guests : []).filter( - (g) => g.email && g.email !== organizerEmail && g.email !== selfEmail, + (g) => g.email && g.email !== organizerEmail && g.email !== selfEmail && g.email !== senderEmail, ); } @@ -355,9 +358,21 @@ export function createRsvpLinks({ localTz(), store.getSettings().hour12 !== false, guests.map((g) => [g.email, g.name || '']), + // Only when it differs, so every other host's stored digests still match. + ...(pageOrganizer(ev) !== accountOrganizer(ev) ? [pageOrganizer(ev)] : []), ]); } + function accountOrganizer(ev) { + return (ev.organizer && ev.organizer.email) || selfEmail; + } + + /** The organizer a guest page shows: mine as senderEmail, anyone else as is. */ + function pageOrganizer(ev) { + const address = accountOrganizer(ev); + return senderEmail && address === selfEmail ? senderEmail : address; + } + /* ---- Worker deployment ------------------------------------------------ */ function buildSource(secretHash) { @@ -646,7 +661,7 @@ export function createRsvpLinks({ // Already-member entries can slip through when this pull raced the // approval's own sync; they're settled, not pending. if (!email || seen.has(email)) continue; - if (members.has(email) || email === organizerEmail || email === selfEmail) continue; + if (members.has(email) || email === organizerEmail || email === selfEmail || email === senderEmail) continue; // Just dismissed here: a response computed before the dismissal reached // the worker must not resurrect the row. if (Date.now() - (dismissedSug.get(`${eventId}:${email}`) || -Infinity) < DISMISS_TOMBSTONE_MS) { @@ -756,7 +771,7 @@ export function createRsvpLinks({ // same policy as the email worker). meetingUrl: (ev.meeting && ev.meeting.url) || '', organizerName: (ev.organizer && ev.organizer.name) || '', - organizerEmail: (ev.organizer && ev.organizer.email) || selfEmail, + organizerEmail: pageOrganizer(ev), recurLabel: ev.recurrence ? describeRecurrence(ev.recurrence, ev.start) : '', expiresAt: computeExpiresAt(ev), tz: localTz(), @@ -816,6 +831,7 @@ export function createRsvpLinks({ const fresh = await Promise.resolve(requestUser()).catch(() => null); if (fresh && typeof fresh.email === 'string' && fresh.email) { selfEmail = fresh.email.trim().toLowerCase(); + senderEmail = fresh.senderEmail?.trim().toLowerCase() || ''; } } const hosted = store.getAllEvents().filter(isHosted); diff --git a/src/calendar/src/workers/email-worker.js b/src/calendar/src/workers/email-worker.js index 6850f391e9..07958eb29a 100644 --- a/src/calendar/src/workers/email-worker.js +++ b/src/calendar/src/workers/email-worker.js @@ -84,7 +84,11 @@ // '13': a session is not enough to send: the account must be a permanent one // whose email is not awaiting confirmation (403 account_not_verified). // A temporary account takes no signup, so anyone could mint one and mail. -const WORKER_VERSION = '13'; +// '14': the caller's whoami senderEmail (a team account's own puter.email +// address) counts as theirs; organizer_mismatch / attendee_mismatch carry +// detail 'email_unconfirmed' for the caller's own unconfirmed email. A +// REPLY's .ics must name the authorized attendee as its ATTENDEE. +const WORKER_VERSION = '14'; const SENT_PREFIX = 'mail:sent:'; const RATE_PREFIX = 'mail:rate:'; @@ -149,8 +153,8 @@ function usernameOf(value) { } /** - * Who the caller is, in the two addresses a mail may speak for them as — - * read from their Puter session and NEVER from the request body: + * Who the caller is, in the addresses a mail may speak for them as — read + * from their Puter session and NEVER from the request body: * * mailbox `@puter.email`, the address Puter itself gives the * account. It is every mail's Reply-To: derived here, so no request @@ -158,34 +162,47 @@ function usernameOf(value) { * email the account's own email, when the platform shares it (it is * withheld until the user lets the app read it) and has not marked * it unconfirmed — an address nobody proved they own names nobody. + * sender whoami's senderEmail: the address Puter says mail for the account + * should use (a team account's is its own puter.email address). * * Like the id (callerIdOf), the username is usually not sitting on the caller * object, so the caller's own Puter is asked. No username means no mailbox, * and the routes refuse to send rather than fall back to what the body says. */ async function callerAddressesOf(caller) { - if (!caller) return { mailbox: '', email: '' }; + if (!caller) return { mailbox: '', email: '', sender: '', unconfirmed: '' }; const p = caller.puter; - let username = usernameOf(caller.username) || usernameOf(p && p.username); - let email = typeof caller.email === 'string' ? lowerEmail(caller.email) : ''; - if (!username || !email) { - try { - const who = p && p.auth && typeof p.auth.getUser === 'function' ? await p.auth.getUser() : null; - if (who) { - username = username || usernameOf(who.username); - const unconfirmed = who.email_confirmed === false || who.email_confirmed === 0; - if (!email && !unconfirmed && typeof who.email === 'string') email = lowerEmail(who.email); - } - } catch { - /* an unreachable /whoami names nobody */ + let username = ''; + let email = ''; + // The account email when the platform marks it unconfirmed. Never vouched + // for; only lets a refusal say why. + let unconfirmed = ''; + let sender = ''; // only ever on whoami, so it is always asked + try { + const who = p && p.auth && typeof p.auth.getUser === 'function' ? await p.auth.getUser() : null; + if (who) { + username = usernameOf(who.username); + sender = lowerEmail(who.senderEmail); + if (who.email_confirmed === true || who.email_confirmed === 1) email = lowerEmail(who.email); + else unconfirmed = lowerEmail(who.email); } + } catch { + /* an unreachable /whoami names nobody */ } - return { mailbox: username ? `${username}@puter.email` : '', email }; + return { mailbox: username ? `${username}@puter.email` : '', email, sender, unconfirmed }; } /** Is `address` one of the caller's own (see callerAddressesOf)? */ function isCallerAddress(self, address) { - return Boolean(address) && (address === self.mailbox || address === self.email); + return Boolean(address) && (address === self.mailbox || address === self.email || address === self.sender); +} + +/** 403 for an address that is not the caller's. Older accounts were never asked + * to confirm their email, so their own address lands here too; `detail` tells + * the app to ask for a confirmation rather than a new sign-in. */ +function addressRefusal(error, self, address) { + const unconfirmed = Boolean(address) && address === self.unconfirmed; + return json(unconfirmed ? { error, detail: 'email_unconfirmed' } : { error }, 403); } /** @@ -391,10 +408,11 @@ function icsParamText(line) { return line; } -function icsProblem(ics, { method, organizerEmail, meetingLink }) { +function icsProblem(ics, { method, organizerEmail, attendeeEmail, meetingLink }) { // Unfold continuation lines (RFC 5545 §3.1) first — a folded "UR\r\n L:" // is a URL to every client — then read one property per line. const lines = ics.replace(/(?:\r\n|\r|\n)[ \t]/g, '').split(/\r\n|\r|\n/); + let sawAttendee = false; for (const line of lines) { const m = /^([A-Za-z0-9-]+)([;:])/.exec(line); if (!m) continue; @@ -410,11 +428,14 @@ function icsProblem(ics, { method, organizerEmail, meetingLink }) { } else if (name === 'ORGANIZER') { const address = icsValue(line).trim().replace(/^mailto:/i, '').toLowerCase(); if (!address || address !== organizerEmail) return 'organizer'; + } else if (name === 'ATTENDEE' && attendeeEmail) { + if (icsValue(line).trim().replace(/^mailto:/i, '').toLowerCase() !== attendeeEmail) return 'attendee'; + sawAttendee = true; } else if (ICS_URI_PROPS.has(name) || name.startsWith('X-')) { if (!meetingLink || icsValue(line).trim() !== meetingLink) return 'link'; } } - return ''; + return attendeeEmail && !sawAttendee ? 'attendee' : ''; } /** The invitation request, normalized — or { error } for a 400. The route @@ -459,10 +480,7 @@ function readRequest(body, forcedKind = '') { if (ics) { const problem = icsProblem(ics, { method: kind === 'cancel' ? 'CANCEL' : 'REQUEST', - // The address as the caller wrote it: the body prints only a - // well-formed one, but the file's ORGANIZER has to be the organizer - // the caller named, whatever shape that name is in. - organizerEmail: typeof ev.organizerEmail === 'string' ? ev.organizerEmail.trim().toLowerCase() : '', + organizerEmail: lowerEmail(ev.organizerEmail), // The event's link, whatever the message kind: a cancellation's file // still describes the event (the body just stops offering to join it). meetingLink: meetingUrl(ev.meetingUrl), @@ -819,10 +837,10 @@ async function deliver(ctx, forcedKind = '') { } const callerId = await callerIdOf(caller); if (!callerId) return json({ error: 'sign_in_required', detail: 'no_identity' }, 401); - const self = await callerAddressesOf(caller); - if (!self.mailbox) return json({ error: 'sign_in_required', detail: 'no_username' }, 401); const problem = await accountProblemOf(caller); if (problem) return accountRefusal(problem); + const self = await callerAddressesOf(caller); + if (!self.mailbox) return json({ error: 'sign_in_required', detail: 'no_username' }, 401); let body = null; try { @@ -841,7 +859,7 @@ async function deliver(ctx, forcedKind = '') { // for is refused, not waved through: "the platform did not say" is exactly // the case a forged organizer would arrive in. if (req.event.organizerEmail && !isCallerAddress(self, req.event.organizerEmail)) { - return json({ error: 'organizer_mismatch' }, 403); + return addressRefusal('organizer_mismatch', self, req.event.organizerEmail); } // Event cancellation digests are shared by all recipients, including across @@ -1009,7 +1027,7 @@ function readReplyRequest(body) { if (!ics) return { error: 'ics_required' }; // A REPLY carries no meeting link or RSVP link of its own — pass '' so ANY // URI-valued property (a forged Join link riding along) is refused. - const problem = icsProblem(ics, { method: 'REPLY', organizerEmail, meetingLink: '' }); + const problem = icsProblem(ics, { method: 'REPLY', organizerEmail, attendeeEmail, meetingLink: '' }); if (problem) return { error: 'invalid_ics', reason: problem }; return { @@ -1083,10 +1101,10 @@ async function deliverReply(ctx) { } const callerId = await callerIdOf(caller); if (!callerId) return json({ error: 'sign_in_required', detail: 'no_identity' }, 401); - const self = await callerAddressesOf(caller); - if (!self.mailbox) return json({ error: 'sign_in_required', detail: 'no_username' }, 401); const problem = await accountProblemOf(caller); if (problem) return accountRefusal(problem); + const self = await callerAddressesOf(caller); + if (!self.mailbox) return json({ error: 'sign_in_required', detail: 'no_username' }, 401); let body = null; try { @@ -1100,7 +1118,7 @@ async function deliverReply(ctx) { } if (!isCallerAddress(self, req.attendee.email)) { - return json({ error: 'attendee_mismatch' }, 403); + return addressRefusal('attendee_mismatch', self, req.attendee.email); } const kv = kvOf(ctx); diff --git a/src/calendar/src/workers/rsvp-worker.js b/src/calendar/src/workers/rsvp-worker.js index 14fc63685a..bba76ca322 100644 --- a/src/calendar/src/workers/rsvp-worker.js +++ b/src/calendar/src/workers/rsvp-worker.js @@ -938,7 +938,7 @@ function fmtWhen(s) { * POST /admin/booking/cancel host cancels; optionally emails the guest * * KV layout (booking half): - * bookw:cfg -> { pages, busy, organizerName, organizerEmail, + * bookw:cfg -> { pages, busy, organizerName, addressedMail, * organizerPicture, hour12, updatedAt } * bookw:bkg: -> the booking record (incl. tokenHash) * bookw:tok: -> { bookingId } @@ -1276,7 +1276,7 @@ function sanitizeBookingSync(body) { pages, busy: merged, organizerName: str(src.organizerName, 200).trim(), - organizerEmail: lowerEmail(src.organizerEmail), + addressedMail: Boolean(lowerEmail(src.organizerEmail)), organizerPicture: bookPicture(src.organizerPicture), hour12: src.hour12 !== false, updatedAt: Date.now(), @@ -1286,13 +1286,13 @@ function sanitizeBookingSync(body) { async function loadBookingCfg(kv) { const cfg = coerce(await kv.get(BOOK_CFG_KEY)); if (!cfg || typeof cfg !== 'object') { - return { pages: {}, busy: [], organizerName: '', organizerEmail: '', organizerPicture: '', hour12: true }; + return { pages: {}, busy: [], organizerName: '', addressedMail: false, organizerPicture: '', hour12: true }; } return { pages: cfg.pages && typeof cfg.pages === 'object' ? cfg.pages : {}, busy: Array.isArray(cfg.busy) ? cfg.busy : [], organizerName: typeof cfg.organizerName === 'string' ? cfg.organizerName : '', - organizerEmail: typeof cfg.organizerEmail === 'string' ? cfg.organizerEmail : '', + addressedMail: cfg.addressedMail ?? Boolean(cfg.organizerEmail), organizerPicture: typeof cfg.organizerPicture === 'string' ? cfg.organizerPicture : '', hour12: cfg.hour12 !== false, }; @@ -1759,10 +1759,28 @@ async function sendGuestConfirmMail(ctx, cfg, booking, token, origin) { }); } +/** + * The host's addresses, from the owner's session: `organizerEmail` names them + * to guests (senderEmail, else the confirmed email) and `hostEmail` takes their + * own notices (the confirmed email, else organizerEmail). A synced config only + * opts in to mail; an old one's organizer address is never used. + */ +async function bookingAddresses(ctx, cfg) { + if (!cfg.addressedMail) return { organizerEmail: '', hostEmail: '' }; + try { + const who = await bookOwner(ctx).puter.auth.getUser(); + const confirmed = who.email_confirmed === true || who.email_confirmed === 1 ? lowerEmail(who.email) : ''; + const organizerEmail = lowerEmail(who.senderEmail) || confirmed; + return { organizerEmail, hostEmail: confirmed || organizerEmail }; + } catch { + return { organizerEmail: '', hostEmail: '' }; + } +} + /** New-booking notice to the host (their calendar shows it on next open; this * is the "someone booked you" ping in between). */ async function sendHostBookedMail(ctx, cfg, page, booking) { - if (!cfg.organizerEmail) return false; + if (!cfg.hostEmail) return false; const when = bookWhen(booking, page.tz, cfg.hour12); const who = booking.name ? `${booking.name} (${booking.email})` : booking.email; const joinUrl = meetingLink(booking.meetingUrl); @@ -1793,12 +1811,12 @@ async function sendHostBookedMail(ctx, cfg, page, booking) { `

It will appear on your calendar the next time you open it.

` + bookFooterHtml() + ``; - return sendBookingMail(ctx, { to: cfg.organizerEmail, subject, text, html, replyTo: booking.email }); + return sendBookingMail(ctx, { to: cfg.hostEmail, subject, text, html, replyTo: booking.email }); } /** Cancellation notice to the host, including a receipt for their own cancellation. */ async function sendHostCancelMail(ctx, cfg, booking, cancelledBy) { - if (!cfg.organizerEmail) return false; + if (!cfg.hostEmail) return false; const who = booking.name ? `${booking.name} (${booking.email})` : booking.email; const hostWhen = bookWhen(booking, (cfg.pages[booking.pageId] || {}).tz || booking.tz, cfg.hour12); const hostCancelled = cancelledBy === 'host'; @@ -1807,7 +1825,7 @@ async function sendHostCancelMail(ctx, cfg, booking, cancelledBy) { ? `You cancelled the "${booking.pageTitle}" booking with ${who}.` : `${who} cancelled their "${booking.pageTitle}" booking.`; return sendBookingMail(ctx, { - to: cfg.organizerEmail, + to: cfg.hostEmail, subject: bookLine(`Cancelled: ${booking.name || booking.email} — ${hostWhen}`, 200), text: `${intro}\n\nWhen: ${hostWhen}${reason}\n\nThe time is open again, and the event will leave your calendar the next time you open it.`, html: @@ -2030,6 +2048,7 @@ router.post('/admin/booking/cancel', async (ctx) => { // pull happened to clean it up. emailed = await loadBookingCfg(kv) .then(async (cfg) => { + Object.assign(cfg, await bookingAddresses(ctx, cfg)); const guestEmailed = await sendCancelMail(ctx, cfg, booking, 'host', new URL(ctx.request.url).origin).catch(() => false); await sendHostCancelMail(ctx, cfg, booking, 'host').catch(() => false); return guestEmailed; @@ -2306,6 +2325,7 @@ router.post('/api/book/:page', async (ctx) => { // Mail is best-effort by design, and that has to include THROWING: the // booking is committed by now, so a formatting or transport surprise must // cost the announcement, not the guest's reply. + Object.assign(cfg, await bookingAddresses(ctx, cfg)); const emailedGuest = await sendGuestConfirmMail(ctx, cfg, booking, token, origin).catch(() => false); const emailedHost = await sendHostBookedMail(ctx, cfg, page, booking).catch(() => false); @@ -2342,6 +2362,7 @@ router.post('/api/booking/:token/cancel', async (ctx) => { await markBookingCancelled(kv, booking, 'guest', body.reason); // Same reasoning as the host route: the cancellation is already recorded, so // a mail failure must not answer 500 and tell the guest it didn't happen. + Object.assign(cfg, await bookingAddresses(ctx, cfg)); await sendCancelMail(ctx, cfg, booking, 'guest', new URL(ctx.request.url).origin).catch(() => false); return json({ ok: true, booking: guestBookingView(cfg, booking) }); }); diff --git a/src/calendar/tests/booking-worker.test.js b/src/calendar/tests/booking-worker.test.js index 3dc02b8e77..a50739b726 100644 --- a/src/calendar/tests/booking-worker.test.js +++ b/src/calendar/tests/booking-worker.test.js @@ -19,12 +19,12 @@ const DAY = 86_400_000; // availability computation in this file. const NOW = Date.UTC(2027, 0, 4, 0, 0, 0); -async function loadWorker({ email, authToken } = {}) { +async function loadWorker({ email, authToken, account = { email: 'host@example.com', email_confirmed: true } } = {}) { const source = RAW.replace('__RSVP_ADMIN_SECRET_HASH__', await sha256Hex(SECRET)) .replace('__RSVP_WORKER_VERSION__', 'test') .replace('__RSVP_PAGE_URL__', PAGE_URL); const kv = makeKv(); - const me = { puter: { kv, ...(email ? { email } : {}), ...(authToken ? { authToken } : {}) } }; + const me = { puter: { kv, auth: { getUser: async () => account }, ...(email ? { email } : {}), ...(authToken ? { authToken } : {}) } }; return instantiateWorker(source, { kv, me }); } @@ -1374,6 +1374,47 @@ describe('booking worker: emails (best-effort)', () => { expect(hostMail.html).toContain('

New booking

'); }); + it("names a team account's puter.email to guests from the owner session, ignoring synced addresses", async () => { + const send = vi.fn(async () => ({})); + const account = { senderEmail: 'host@puter.email', email: 'host@example.com', email_confirmed: true }; + const worker = await loadWorker({ email: { sendTransactional: send }, account }); + await syncBooking(worker, { organizerEmail: 'claim@example.com', notifyEmail: 'other@example.com' }); + const res = await book(worker, 'abcd1234', { start: Date.UTC(2027, 0, 4, 9) }); + expect((await res.json()).emailed).toEqual({ guest: true, host: true }); + const guestMail = send.mock.calls.find(([m]) => m.to === 'ada@example.com')[0]; + expect(guestMail.replyTo).toBe('host@puter.email'); + const ics = Buffer.from(guestMail.attachments[0].content, 'base64').toString('utf8'); + expect(ics).toContain('ORGANIZER;CN="Nariman":mailto:host@puter.email'); + expect(ics).not.toContain('claim@example.com'); + // The host's own notice goes to their confirmed email. + expect(send.mock.calls.find(([m]) => m.to === 'host@example.com')[0].subject).toContain('New booking'); + expect(send).toHaveBeenCalledTimes(2); + }); + + it("sends a team account's notices to its puter.email while its email is unconfirmed", async () => { + const send = vi.fn(async () => ({})); + const account = { senderEmail: 'host@puter.email', email: 'host@example.com', email_confirmed: false }; + const worker = await loadWorker({ email: { sendTransactional: send }, account }); + await syncBooking(worker); + await book(worker, 'abcd1234', { start: Date.UTC(2027, 0, 4, 9) }); + expect(send.mock.calls.find(([m]) => m.to === 'host@puter.email')[0].subject).toContain('New booking'); + expect(send.mock.calls.some(([m]) => m.to === 'host@example.com')).toBe(false); + }); + + it('keeps bookings working when a legacy config names an address the session withholds', async () => { + const send = vi.fn(async () => ({})); + const worker = await loadWorker({ email: { sendTransactional: send }, account: {} }); + await syncBooking(worker); + const cfg = worker.kv.map.get('bookw:cfg'); + delete cfg.addressedMail; + cfg.organizerEmail = 'legacy@example.com'; + const res = await book(worker, 'abcd1234', { start: Date.UTC(2027, 0, 4, 9) }); + expect((await res.json()).emailed).toEqual({ guest: true, host: false }); + const [message] = send.mock.calls[0]; + expect(message.replyTo).toBeUndefined(); + expect(Buffer.from(message.attachments[0].content, 'base64').toString()).toContain('METHOD:PUBLISH'); + }); + it('a failing mailer never fails the booking', async () => { const send = vi.fn(async () => { throw new Error('smtp down'); diff --git a/src/calendar/tests/booking.test.js b/src/calendar/tests/booking.test.js index bd189ef12a..e1dc310755 100644 --- a/src/calendar/tests/booking.test.js +++ b/src/calendar/tests/booking.test.js @@ -1780,3 +1780,30 @@ describe("booking: the host's public name", () => { expect(world.store.getSettings().bookingName).toBe(''); }); }); + +describe("booking: a team account's sending address", () => { + const cfgOf = (world) => workerOf(world).kv.map.get('bookw:cfg'); + + it('enables addressed mail while its own events keep the account email', async () => { + const world = makeWorld({ user: { ...HOST, senderEmail: 'nariman@puter.email' } }); + await world.store.load(); + await world.booking.start(); + const page = await world.booking.savePage({ title: 'Office hours', durationMin: 60, minNoticeMin: 0 }); + await settle(world.booking); + expect(cfgOf(world).addressedMail).toBe(true); + + const out = await guestBook(world, page.id, await firstSlot(world, page.id)); + await world.booking.refresh(); + await settle(world.booking); + expect(world.store.getEvent(out.booking.id).organizer).toEqual({ email: HOST.email }); + }); + + it('enables addressed mail for a confirmed account', async () => { + const world = makeWorld({ user: { ...HOST, senderEmail: HOST.email } }); + await world.store.load(); + await world.booking.start(); + await world.booking.savePage({ title: 'Office hours', durationMin: 60 }); + await settle(world.booking); + expect(cfgOf(world).addressedMail).toBe(true); + }); +}); diff --git a/src/calendar/tests/email-worker.test.js b/src/calendar/tests/email-worker.test.js index 96e3ca3733..4baa17b3a0 100644 --- a/src/calendar/tests/email-worker.test.js +++ b/src/calendar/tests/email-worker.test.js @@ -505,6 +505,15 @@ describe('email worker: the organizer must be the caller', () => { expect(world.sent).toHaveLength(0); }); + it('requires confirmation from whoami even when the caller also carries an email', async () => { + const world = loadWorker(); + for (const email_confirmed of [false, undefined]) { + const user = { ...CALLER, puter: { auth: { getUser: async () => ({ ...ACCOUNT, email_confirmed }) } } }; + expect((await post(world, payload(), { user })).status).toBe(403); + } + expect(world.sent).toHaveLength(0); + }); + it('does not vouch for an account email the platform marks unconfirmed', async () => { const world = loadWorker(); const unconfirmed = { @@ -517,9 +526,45 @@ describe('email worker: the organizer must be the caller', () => { }; const res = await post(world, withOrganizer('ceo@bank.example'), { user: unconfirmed }); expect(res.status).toBe(403); + expect(await res.json()).toEqual({ error: 'organizer_mismatch', detail: 'email_unconfirmed' }); expect(world.sent).toHaveLength(0); }); + it('says email_unconfirmed only for the caller\'s own unconfirmed address', async () => { + // An older account: never asked to confirm, so it may send, but not as its email. + const older = { + uuid: CALLER.uuid, + username: CALLER.username, + puter: { + ...CALLER.puter, + auth: { getUser: async () => ({ ...ACCOUNT, requires_email_confirmation: 0, email_confirmed: 0 }) }, + }, + }; + const own = await post(loadWorker(), payload(), { user: older }); + expect(own.status).toBe(403); + expect(await own.json()).toEqual({ error: 'organizer_mismatch', detail: 'email_unconfirmed' }); + + const other = await post(loadWorker(), withOrganizer('someone@else.example'), { user: older }); + expect(other.status).toBe(403); + expect(await other.json()).toEqual({ error: 'organizer_mismatch' }); + }); + + it("sends as the session's senderEmail, a team account's own address", async () => { + const seat = (senderEmail) => ({ + uuid: CALLER.uuid, + puter: { + ...CALLER.puter, + auth: { getUser: async () => ({ ...ACCOUNT, email_confirmed: 0, senderEmail }) }, + }, + }); + // Taken from whoami, not built from the username: another Puter mail domain still counts. + const ok = await post(loadWorker(), withOrganizer('host@puterstaging.email'), { user: seat('host@puterstaging.email') }); + expect(ok.status).toBe(200); + // The body cannot claim one the session does not. + const forged = await post(loadWorker(), withOrganizer('other@puterstaging.email'), { user: seat('host@puterstaging.email') }); + expect(forged.status).toBe(403); + }); + it("sets Reply-To to the caller's @puter.email, whatever the request says", async () => { const world = loadWorker(); const res = await post( @@ -532,6 +577,14 @@ describe('email worker: the organizer must be the caller', () => { expect(world.sent[0].replyTo).toBe('host@puter.email'); }); + it('builds the mailbox from whoami when the caller wrapper has a stale username', async () => { + const world = loadWorker(); + const user = { ...world.caller, username: 'stale' }; + const res = await post(world, withOrganizer('host@puter.email'), { user }); + expect(res.status).toBe(200); + expect(world.sent[0].replyTo).toBe('host@puter.email'); + }); + it('refuses to send for a session that cannot be pinned to a username', async () => { const world = loadWorker(); const nameless = { @@ -941,6 +994,7 @@ describe('email worker: the attachment is read before it is attached', () => { // Native RSVP buttons reply to ORGANIZER; a mail client shows it as the // sender of the invitation. const forged = (org) => `BEGIN:VCALENDAR\r\nMETHOD:REQUEST\r\nBEGIN:VEVENT\r\n${org}\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n`; + await refused('/invites', payload({ ics: forged('ORGANIZER:urn:uuid:1234'), event: { ...payload().event, organizerEmail: 'urn:uuid:1234' } })); await refused('/invites', payload({ ics: forged('ORGANIZER:mailto:ceo@victim.example') })); await refused('/invites', payload({ ics: forged('ORGANIZER;CN="Host":MAILTO:ceo@victim.example') })); // A quoted parameter cannot hide the real value. @@ -1054,10 +1108,10 @@ describe('email worker: replies (the /replies fallback for mail-received invitat const postReply = (world, body = replyPayload(), user = world.caller) => world.worker.call('POST', '/replies', { json: body, user }); - it('reports version 13 from /health', async () => { + it('reports version 14 from /health', async () => { const world = loadWorker(); const res = await world.worker.call('GET', '/health'); - expect((await res.json())).toMatchObject({ ok: true, version: '13' }); + expect((await res.json())).toMatchObject({ ok: true, version: '14' }); }); it('composes and sends a reply to the organizer, with no links anywhere', async () => { @@ -1081,7 +1135,7 @@ describe('email worker: replies (the /replies fallback for mail-received invitat const world = loadWorker(); const res = await postReply( world, - replyPayload({ attendee: { email: 'someoneelse@example.com', name: 'Nope' } }), + replyPayload({ attendee: { email: 'someoneelse@example.com', name: 'Nope' }, ics: replyIcs({ attendeeEmail: 'someoneelse@example.com' }) }), asUser('host@example.com'), ); expect(res.status).toBe(403); @@ -1115,6 +1169,15 @@ describe('email worker: replies (the /replies fallback for mail-received invitat expect((await res.json()).sent).toBe(1); }); + it('checks the reply attachment against the authenticated attendee', async () => { + const world = loadWorker(); + for (const ics of [replyIcs({ attendeeEmail: 'guest@example.com' }), replyIcs().replace(/^ATTENDEE[^\r\n]*/m, '')]) { + const res = await postReply(world, replyPayload({ ics })); + expect(await res.json()).toEqual({ error: 'invalid_ics', reason: 'attendee' }); + } + expect(world.sent).toHaveLength(0); + }); + it('refuses an .ics whose METHOD is not REPLY', async () => { const world = loadWorker(); const res = await postReply(world, replyPayload({ ics: replyIcs({ method: 'REQUEST' }) })); diff --git a/src/calendar/tests/invites.test.js b/src/calendar/tests/invites.test.js index e24d781b97..91bb07a33d 100644 --- a/src/calendar/tests/invites.test.js +++ b/src/calendar/tests/invites.test.js @@ -75,6 +75,8 @@ function makeWorld({ user = HOST, requestUser, requestEmail, + // Overrides on what the email worker's /whoami says of the caller. + workerAccount = null, } = {}) { const kv = makeKv(); const store = createStore(kv); @@ -120,9 +122,13 @@ function makeWorld({ user: { ...HOST, username: 'host', + // Live sessions carry only `puter`; an override reads the account from /whoami alone. + ...(workerAccount ? { email: undefined } : {}), puter: { authToken: 'caller-token', - auth: { getUser: async () => ({ ...HOST, username: 'host', is_temp: false, email_confirmed: true }) }, + auth: { + getUser: async () => ({ ...HOST, username: 'host', is_temp: false, email_confirmed: true, ...workerAccount }), + }, }, }, }); @@ -1324,6 +1330,114 @@ describe('invites: an invitation names its host', () => { return { world, event }; } + it("sends as a team account's senderEmail, its @puter.email", async () => { + // A team seat: its email is the team's claim, which the worker will not name. + const seat = { ...HOST, username: 'host', email_confirmed: 0, senderEmail: 'host@puter.email' }; + const world = makeWorld({ user: seat, workerAccount: { email_confirmed: 0, senderEmail: 'host@puter.email' } }); + await world.store.load(); + await world.rsvp.start(); + const event = await hostEvent(world.store); + await settle(world.rsvp); + await world.invites.start(); + + expect((await world.invites.send(event)).sent).toBe(1); + const [message] = world.mail; + expect(message.text).not.toContain(HOST.email); + const ics = Buffer.from(message.attachments[0].content, 'base64').toString('utf8'); + expect(ics).toContain('ORGANIZER;CN="Nariman":mailto:host@puter.email'); + expect(ics).toContain('ATTENDEE;PARTSTAT=ACCEPTED;RSVP=TRUE:mailto:host@puter.email'); + expect(ics).not.toContain(HOST.email); + // Only the mail changes: the stored organizer and the sent log stay as they were. + expect(world.store.getEvent(event.id).organizer.email).toBe(HOST.email); + expect(world.invites.planFor(event).pending).toHaveLength(0); + + const cancel = world.invites.cancellationFor(event); + await world.store.deleteEvent(event.id); + expect((await world.invites.sendCancellation(cancel)).sent).toBeGreaterThan(0); + const toAda = world.mail.slice(1).find((m) => m.to === 'ada@example.com'); + const cancelIcs = Buffer.from(toAda.attachments[0].content, 'base64').toString('utf8'); + expect(cancelIcs).toContain('mailto:host@puter.email'); + expect(cancelIcs).not.toContain(HOST.email); + }); + + it('resolves the sender after the editor stamps an event using a newly granted account email', async () => { + const granted = { ...HOST, senderEmail: 'host@puter.email', email_confirmed: false }; + const world = makeWorld({ user: NOBODY, requestUser: async () => granted, workerAccount: granted }); + await world.store.load(); + await world.rsvp.start(); + const event = await hostEvent(world.store); + await settle(world.rsvp); + await world.invites.start(); + expect((await world.invites.send(event, { prompt: false })).sent).toBe(1); + const ics = Buffer.from(world.mail[0].attachments[0].content, 'base64').toString(); + expect(ics).toContain('ORGANIZER;CN="Nariman":mailto:host@puter.email'); + }); + + it('keeps a previously mailed organizer for updates and cancellations from a legacy log', async () => { + const seat = { ...HOST, senderEmail: 'host@puter.email' }; + const world = makeWorld({ user: seat, workerAccount: seat }); + await world.store.load(); + await world.rsvp.start(); + const event = await hostEvent(world.store); + await settle(world.rsvp); + await world.kv.set(`cal:invite:${event.id}`, { 'ada@example.com': { at: 1, v: 'aaaa1111' } }); + await world.invites.start(); + + expect((await world.invites.send(event)).sent).toBe(1); + const cancel = world.invites.cancellationFor(event); + await world.store.deleteEvent(event.id); + await world.invites.sendCancellation(cancel); + const messages = world.mail.filter((m) => m.to === 'ada@example.com'); + expect(messages).toHaveLength(2); + for (const message of messages) { + const ics = Buffer.from(message.attachments[0].content, 'base64').toString('utf8'); + expect(ics).toContain(`ORGANIZER;CN="Nariman":mailto:${HOST.email}`); + } + }); + + it("moves a legacy log's unconfirmed organizer to the sender", async () => { + const seat = { ...HOST, senderEmail: 'host@puter.email', email_confirmed: false }; + const world = makeWorld({ user: seat, workerAccount: seat }); + await world.store.load(); + await world.rsvp.start(); + const event = await hostEvent(world.store); + await settle(world.rsvp); + await world.kv.set(`cal:invite:${event.id}`, { 'ada@example.com': { at: 1, v: 'aaaa1111' } }); + await world.invites.start(); + + expect((await world.invites.send(event)).sent).toBe(1); + const ics = Buffer.from(world.mail.find((m) => m.to === 'ada@example.com').attachments[0].content, 'base64').toString('utf8'); + expect(ics).toContain('ORGANIZER;CN="Nariman":mailto:host@puter.email'); + }); + + it('picks up senderEmail with the email grant a press asks for', async () => { + // Both ride the email grant: boot saw neither, the fresh read after the prompt sees both. + const seat = { uuid: HOST.uuid, username: 'host', email_confirmed: 0 }; + const granted = { ...seat, email: HOST.email, senderEmail: 'host@puter.email' }; + const requestEmail = vi.fn(async () => HOST.email); + const { world, event } = await anonymousWorld({ + user: seat, requestUser: async () => (requestEmail.mock.calls.length ? granted : seat), requestEmail, + workerAccount: { email_confirmed: 0, senderEmail: 'host@puter.email' }, + }); + expect((await world.invites.send(event)).sent).toBe(1); + expect(requestEmail).toHaveBeenCalledTimes(1); + const ics = Buffer.from(world.mail[0].attachments[0].content, 'base64').toString('utf8'); + expect(ics).toContain('ORGANIZER:mailto:host@puter.email'); + expect(ics).not.toContain(HOST.email); + }); + + it('sends as the account email when senderEmail is that same address', async () => { + const world = makeWorld({ user: { ...HOST, senderEmail: HOST.email } }); + await world.store.load(); + await world.rsvp.start(); + const event = await hostEvent(world.store); + await settle(world.rsvp); + await world.invites.start(); + expect((await world.invites.send(event)).sent).toBe(1); + const ics = Buffer.from(world.mail[0].attachments[0].content, 'base64').toString('utf8'); + expect(ics).toContain(`ORGANIZER;CN="Nariman":mailto:${HOST.email}`); + }); + it('refuses to mail an invitation it cannot sign', async () => { const requestEmail = vi.fn(async () => null); // asked, and refused const { world, event } = await anonymousWorld({ requestUser: async () => NOBODY, requestEmail }); diff --git a/src/calendar/tests/mail-reply.test.js b/src/calendar/tests/mail-reply.test.js index 98fb8bd25c..6c1a640d0e 100644 --- a/src/calendar/tests/mail-reply.test.js +++ b/src/calendar/tests/mail-reply.test.js @@ -37,7 +37,7 @@ function fakeStore() { } function fakeUser(overrides = {}) { - return { username: 'nariman', email: 'nariman@example.com', ...overrides }; + return { username: 'nariman', email: 'nariman@example.com', email_confirmed: true, ...overrides }; } function fakeEvent(overrides = {}) { @@ -323,6 +323,16 @@ describe('createMailReply: sendReply — .ics attendee/UID', () => { expect(ics).toContain('UID:ext-uid-123@google.com'); }); + it('answers as the team sender when the invitation did not record an attendee', async () => { + const p = fakePuter({ api: false }); + p.workers.exec.mockResolvedValue(workerOk()); + const mail = makeMail({ p, user: fakeUser({ senderEmail: 'nariman@puter.email' }) }); + await mail.sendReply(fakeEvent(), 'accepted'); + const body = JSON.parse(p.workers.exec.mock.calls[0][1].body); + expect(body.attendee.email).toBe('nariman@puter.email'); + expect(attendeeLinesOf(body.ics)[0]).toContain('mailto:nariman@puter.email'); + }); + it('falls back to the current account email, then @puter.email, when there is no invite.attendee', async () => { let captured = null; const send = vi.fn(async (payload) => { diff --git a/src/calendar/tests/rsvp-links.test.js b/src/calendar/tests/rsvp-links.test.js index 2ccb61ea21..d9b0b70fb4 100644 --- a/src/calendar/tests/rsvp-links.test.js +++ b/src/calendar/tests/rsvp-links.test.js @@ -263,6 +263,36 @@ describe('rsvp-links: guest answers round-trip', () => { expect(worker.instance.kv.map.has(`rsvpw:evt:${ev.id}`)).toBe(false); }); + it('uses the team sender on guest pages and excludes both host addresses from invitations', async () => { + const senderEmail = 'host@puter.email'; + const team = makeWorld({ user: { ...HOST, senderEmail } }); + await team.store.load(); + await team.rsvp.start(); + const ev = await hostEvent(team.store, { guests: [ + { email: HOST.email }, { email: senderEmail }, { email: 'ada@example.com' }, + ] }); + await settle(team.rsvp); + const links = team.rsvp.linksFor(ev.id); + expect(Object.keys(links)).toEqual(['ada@example.com']); + const worker = team.fakePuter.workersByUrl.get(new URL(links['ada@example.com']).origin); + expect(worker.instance.kv.map.get(`rsvpw:evt:${ev.id}`).snapshot.organizerEmail).toBe(senderEmail); + }); + + it("leaves a host's synced digests alone unless the shown organizer changes", async () => { + const start = Date.now() + 24 * HOUR; + const digestFor = async (user) => { + const w = makeWorld({ user }); + await w.store.load(); + await w.rsvp.start(); + const e = await hostEvent(w.store, { start, end: start + HOUR }); + await settle(w.rsvp); + return w.kv.map.get(`cal:rsvp:links:${e.id}`).digest; + }; + const plain = await digestFor(HOST); + expect(await digestFor({ ...HOST, senderEmail: HOST.email })).toBe(plain); + expect(await digestFor({ ...HOST, senderEmail: 'host@puter.email' })).not.toBe(plain); + }); + it('pushes detail edits (new time) to the worker snapshot', async () => { const moved = ev.start + 24 * HOUR; await world.store.saveEvent({ ...world.store.getEvent(ev.id), start: moved, end: moved + HOUR }); diff --git a/src/signatures/src/lib/emailer.js b/src/signatures/src/lib/emailer.js index acad594c15..41e0c11a6b 100644 --- a/src/signatures/src/lib/emailer.js +++ b/src/signatures/src/lib/emailer.js @@ -191,7 +191,6 @@ export function createEmailer({ id: doc.id, title: doc.title, ownerName: ownerName(doc), - ownerEmail: store.user?.email || '', pageCount: doc.pageCount, // Stated in the mail: a request with a deadline should say so, in // the sender's own clock AT the deadline (a clock change between @@ -292,7 +291,6 @@ export function createEmailer({ id: doc.id, title: doc.title, ownerName: ownerName(doc), - ownerEmail: email, pageCount: doc.pageCount, }, recipients: [{ email, version }], diff --git a/src/signatures/src/workers/email-worker.js b/src/signatures/src/workers/email-worker.js index 5f840c5fd6..71dde468cc 100644 --- a/src/signatures/src/workers/email-worker.js +++ b/src/signatures/src/workers/email-worker.js @@ -20,6 +20,9 @@ * cannon wearing the app's sending reputation, so it never does: * - no Puter session, no send. `user` is only populated for callers that * come through puter.workers.exec(); everyone else gets 401. + * - the sender's address (Reply-To, the "From" line) is read from their + * session, never from the request: whoami's senderEmail, which for a team + * account is its own puter.email address, else their confirmed email. * - the caller supplies a DOCUMENT, not an email. Subject and body are * composed here, so every message this worker can be made to send is a * signature request (or reminder, or completion notice) for that @@ -46,7 +49,8 @@ * Deploy with: npm run deploy:email-worker */ -const WORKER_VERSION = '3'; +// '4': the sender's address comes from their session (addressesOf), not the body. +const WORKER_VERSION = '4'; const SENT_PREFIX = 'mail:sent:'; const RATE_PREFIX = 'mail:rate:'; @@ -96,19 +100,21 @@ async function callerIdOf(caller) { } /** - * The caller's own email address, for kind 'owner'. Asking the platform beats - * trusting the request: a notice about your own document should only ever - * reach you. + * The caller's addresses, from their session. `sender` is what their mail names + * them by: whoami's senderEmail (a team account's own puter.email address), else + * their confirmed email. `inbox` takes their own notices: the confirmed email, + * else `sender`. '' names no address. */ -async function callerEmailOf(caller) { +async function addressesOf(caller) { const p = caller && caller.puter; - const direct = caller && (caller.email || (p && p.email && typeof p.email === 'string' ? p.email : '')); - if (typeof direct === 'string' && lowerEmail(direct)) return lowerEmail(direct); try { const who = p && p.auth && typeof p.auth.getUser === 'function' ? await p.auth.getUser() : null; - return lowerEmail(who && who.email); + if (!who) return { sender: '', inbox: '' }; + const confirmed = who.email_confirmed === true || who.email_confirmed === 1 ? lowerEmail(who.email) : ''; + const sender = lowerEmail(who.senderEmail) || confirmed; + return { sender, inbox: confirmed || sender }; } catch { - return ''; + return { sender: '', inbox: '' }; } } @@ -249,7 +255,7 @@ function readRequest(body) { id: doc.id, title: line(doc.title, 300) || '(Untitled document)', ownerName: line(doc.ownerName, 200), - ownerEmail: lowerEmail(doc.ownerEmail), + ownerEmail: '', // the caller's session decides (addressesOf) pageCount: Number.isInteger(doc.pageCount) && doc.pageCount > 0 ? doc.pageCount : 0, expiresAt: Number.isFinite(doc.expiresAt) && doc.expiresAt > 0 ? Math.round(doc.expiresAt) : 0, // The sender's clock at the deadline, minutes east of UTC, so the mail @@ -546,6 +552,8 @@ router.post('/send', async (ctx) => { } const req = readRequest(body); if (req.error) return json({ error: req.error }, 400); + const self = await addressesOf(caller); + req.doc.ownerEmail = self.sender; const kv = kvOf(ctx); const rateKey = await quotaKey(callerId); @@ -559,12 +567,11 @@ router.post('/send', async (ctx) => { let sent = 0; // An owner update is about the caller's own document and goes to the - // caller's own address: ask the platform who they are, and only fall back - // to the address in the request when it will not say. + // caller's verified address. let audience = req.recipients; if (req.kind === 'owner') { - const own = await callerEmailOf(caller); - audience = [{ ...req.recipients[0], email: own || req.recipients[0].email, name: '', signUrl: '' }]; + if (!self.inbox) return json({ error: 'owner_email_unavailable' }, 403); + audience = [{ ...req.recipients[0], email: self.inbox, name: '', signUrl: '' }]; } for (const signer of audience) { diff --git a/src/signatures/tests/email-worker.test.js b/src/signatures/tests/email-worker.test.js index 0c46768cf3..bb10a5e301 100644 --- a/src/signatures/tests/email-worker.test.js +++ b/src/signatures/tests/email-worker.test.js @@ -4,12 +4,16 @@ import { instantiateWorker, makeKv, sha256Hex } from './helpers/worker-harness.j const LINK = `https://doc-sign-abc12.puter.work/sign/${'a'.repeat(40)}`; -function makeCaller(sendImpl) { +// What whoami says of the caller: the worker takes their address from here. +const ACCOUNT = { uuid: 'user-1', email: 'alex@example.com', email_confirmed: true }; + +function makeCaller(sendImpl, account = ACCOUNT) { return { uuid: 'user-1', puter: { authToken: 'caller-token', email: { send: vi.fn(sendImpl || (async () => ({}))) }, + auth: { getUser: async () => account }, }, }; } @@ -68,6 +72,32 @@ describe('email worker', () => { expect(message.html).toContain(LINK); }); + it("names the sender by their session's address, whatever the request claims", async () => { + const forged = request({ doc: { ...request().doc, ownerEmail: 'ceo@bank.example' } }); + const send = async (account) => { + const o = makeOwner(); + const w = instantiateWorker(rawSource, { me: o.me }); + await w.call('POST', '/send', { json: forged, user: makeCaller(null, account) }); + return o.me.puter.email.send.mock.calls[0][0]; + }; + + const confirmed = await send(ACCOUNT); + expect(confirmed.replyTo).toBe('alex@example.com'); + expect(confirmed.text).toContain('From: Alex '); + expect(confirmed.text).not.toContain('ceo@bank.example'); + + // A team account sends as its own puter.email address. + const team = await send({ ...ACCOUNT, email_confirmed: 0, senderEmail: 'alex@puter.email' }); + expect(team.replyTo).toBe('alex@puter.email'); + expect(team.text).toContain('From: Alex '); + + // An unconfirmed email names nobody. + expect((await send({ email: ACCOUNT.email })).replyTo).toBeUndefined(); + const unconfirmed = await send({ ...ACCOUNT, email_confirmed: 0 }); + expect(unconfirmed.replyTo).toBeUndefined(); + expect(unconfirmed.text).not.toContain('alex@example.com'); + }); + it('sends one message per address in a request, whatever it is asked for', async () => { // Why sendBlockers refuses two signers sharing an address: the second one // is dropped here, and the sender would never learn they were not mailed. diff --git a/src/signatures/tests/ownernotify.test.js b/src/signatures/tests/ownernotify.test.js index 1921675df7..41b0c9b9ec 100644 --- a/src/signatures/tests/ownernotify.test.js +++ b/src/signatures/tests/ownernotify.test.js @@ -212,7 +212,7 @@ describe('email worker owner updates', () => { const caller = { uuid: 'u-1', - puter: { authToken: 'caller-token', auth: { getUser: async () => ({ uuid: 'u-1', email: 'owner@example.com' }) } }, + puter: { authToken: 'caller-token', auth: { getUser: async () => ({ uuid: 'u-1', email: 'owner@example.com', email_confirmed: true }) } }, }; const body = (over = {}) => ({ @@ -245,6 +245,21 @@ describe('email worker owner updates', () => { expect(sent[0].to).toBe('owner@example.com'); }); + it("sends a team account's notice to its confirmed email, else its puter.email", async () => { + const seat = (who) => ({ ...caller, puter: { ...caller.puter, auth: { getUser: async () => ({ uuid: caller.uuid, ...who }) } } }); + const team = { senderEmail: 'alex@puter.email', email: 'owner@example.com' }; + await worker.call('POST', '/send', { json: body(), user: seat({ ...team, email_confirmed: true }) }); + await worker.call('POST', '/send', { json: body(), user: seat({ ...team, email_confirmed: false }) }); + expect(sent.map((m) => m.to)).toEqual(['owner@example.com', 'alex@puter.email']); + }); + + it('refuses owner mail when the session withholds its address', async () => { + const user = { ...caller, puter: { ...caller.puter, auth: { getUser: async () => ({ uuid: caller.uuid }) } } }; + const res = await worker.call('POST', '/send', { json: body(), user }); + expect(res.status).toBe(403); + expect(sent).toHaveLength(0); + }); + it('refuses an owner update with no events', async () => { const res = await worker.call('POST', '/send', { json: body({ events: [] }), user: caller }); expect(res.status).toBe(400); diff --git a/src/spreadsheet/src/workers/email-worker.js b/src/spreadsheet/src/workers/email-worker.js index 7ad190f1e2..39f5bb0110 100644 --- a/src/spreadsheet/src/workers/email-worker.js +++ b/src/spreadsheet/src/workers/email-worker.js @@ -39,7 +39,9 @@ * Deploy with: npm run deploy:email-worker */ -const WORKER_VERSION = '1'; +// '2': Reply-To is the session's senderEmail (a team account's own +// puter.email address), else its email only once confirmed. +const WORKER_VERSION = '2'; const RATE_PREFIX = 'mail:rate:'; const MENTION_PREFIX = 'mail:mention:'; @@ -64,31 +66,43 @@ function callerOf(ctx) { return (ctx && (ctx.user || ctx.requestor)) || null; } -/** Who the caller is, from their own session: { id, username, email }. id '' when it cannot be told. */ +/** Who the caller is, from their own session: { id, username, replyTo }. id '' when it cannot be told. */ async function identityOf(caller) { - const out = { id: '', username: '', email: '' }; + const out = { id: '', username: '', replyTo: '' }; if (!caller) return out; const pick = (o) => { if (!o || typeof o !== 'object') return; const id = o.uuid || o.uid || o.user_uuid; if (!out.id && typeof id === 'string' && id) out.id = id; if (!out.username && typeof o.username === 'string' && o.username) out.username = o.username; - if (!out.email && typeof o.email === 'string') out.email = lowerEmail(o.email); }; pick(caller); pick(caller.puter); + // The reply address only ever comes from whoami, so it is always asked. const p = caller.puter; - if (!out.id || !out.username || !out.email) { - try { - pick(p && p.auth && typeof p.auth.getUser === 'function' ? await p.auth.getUser() : null); - } catch { - /* an unreachable whoami is not an identity */ - } + try { + const who = p && p.auth && typeof p.auth.getUser === 'function' ? await p.auth.getUser() : null; + pick(who); + out.replyTo = replyToOf(who); + } catch { + /* an unreachable whoami is not an identity */ } if (!out.id && out.username) out.id = out.username; return out; } +/** + * Where replies to the caller's mail go: whoami's senderEmail (a team account's + * is its own puter.email address, since its email is the team's claim), else + * the account email once confirmed. '' sends with no Reply-To. + */ +function replyToOf(who) { + if (!who || typeof who !== 'object') return ''; + const sender = lowerEmail(who.senderEmail); + if (sender) return sender; + return who.email_confirmed === true || who.email_confirmed === 1 ? lowerEmail(who.email) : ''; +} + function kvOf(ctx) { return ownerOf(ctx).puter.kv; } @@ -509,7 +523,7 @@ async function deliver(ctx, kind) { subject: message.subject, text: message.text, html: message.html, - replyTo: sender.email || undefined, + replyTo: sender.replyTo || undefined, attachments, })) || {}; if ((out.suppressed || []).includes(person.email)) { diff --git a/src/spreadsheet/tests/email-worker.test.js b/src/spreadsheet/tests/email-worker.test.js index c992689335..7e931c3a0e 100644 --- a/src/spreadsheet/tests/email-worker.test.js +++ b/src/spreadsheet/tests/email-worker.test.js @@ -18,7 +18,7 @@ describe('email worker: access and health', () => { it('answers /health without a session', async () => { const w = loadEmailWorker(); const res = await w.call('GET', '/health', { asUser: null }); - expect(res.data).toMatchObject({ ok: true, version: '1' }); + expect(res.data).toMatchObject({ ok: true, version: '2' }); }); it('refuses to send for a caller without a Puter session', async () => { @@ -37,6 +37,24 @@ describe('email worker: access and health', () => { }); }); +describe('email worker: where replies go', () => { + const replyToFor = async (caller) => { + const w = loadEmailWorker({ caller: { uuid: 'u-1', username: 'demo', ...caller } }); + expect((await w.call('POST', '/copies', { json: copy() })).status).toBe(200); + return w.sent[0].replyTo; + }; + + it("uses the session's senderEmail, a team account's own puter.email address", async () => { + expect(await replyToFor({ email: 'demo@example.com', email_confirmed: 0, senderEmail: 'demo@puter.email' })).toBe('demo@puter.email'); + }); + + it('uses the account email only once it is confirmed', async () => { + expect(await replyToFor({ email: 'demo@example.com', email_confirmed: true })).toBe('demo@example.com'); + expect(await replyToFor({ email: 'demo@example.com', email_confirmed: 0 })).toBeUndefined(); + expect(await replyToFor({ email: 'demo@example.com' })).toBeUndefined(); + }); +}); + describe('email worker: /copies', () => { it('sends one private message per recipient with the workbook attached, billed to the caller', async () => { const w = loadEmailWorker(); diff --git a/src/spreadsheet/tests/helpers/email-worker-harness.js b/src/spreadsheet/tests/helpers/email-worker-harness.js index d5d12ccc8c..cd33468ff7 100644 --- a/src/spreadsheet/tests/helpers/email-worker-harness.js +++ b/src/spreadsheet/tests/helpers/email-worker-harness.js @@ -24,7 +24,7 @@ export function makeKv() { } /** A worker with fake mailers on the owner and the caller; `outcome(message)` may return { failed, suppressed } or throw. */ -export function loadEmailWorker({ outcome = null, caller = { uuid: 'u-1', username: 'demo', email: 'demo@example.com' } } = {}) { +export function loadEmailWorker({ outcome = null, caller = { uuid: 'u-1', username: 'demo', email: 'demo@example.com', email_confirmed: true } } = {}) { const kv = makeKv(); const sent = []; const mailer = (via) => vi.fn(async (message) => {