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
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 13 additions & 5 deletions src/calendar/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<username>@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 `<username>@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
Expand Down
7 changes: 6 additions & 1 deletion src/calendar/src/js/booking.js
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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();
Expand All @@ -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)),
Expand Down
68 changes: 53 additions & 15 deletions src/calendar/src/js/invites.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() : '';
Expand Down Expand Up @@ -261,14 +265,46 @@ 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
// withholds it until the user grants `email:read`, and modal.js saves on a
// 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 <username>@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
Expand All @@ -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 */
}
Expand Down Expand Up @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -666,17 +703,16 @@ 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
// an invitation ever used — those derive from updatedAt, which necessarily
// 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.
Expand Down Expand Up @@ -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.";
}
Expand Down Expand Up @@ -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') {
Expand Down
34 changes: 15 additions & 19 deletions src/calendar/src/js/mail-reply.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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.';
}
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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 });
Expand Down
24 changes: 20 additions & 4 deletions src/calendar/src/js/rsvp-links.js
Original file line number Diff line number Diff line change
Expand Up @@ -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:';
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
);
}

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading