From 4b656010c3970402c4277f473cc0e57515bff05f Mon Sep 17 00:00:00 2001 From: Daniel Salazar Date: Sun, 29 Nov 2026 17:10:48 -0700 Subject: [PATCH 1/2] feat(auth): whoami names the address to send mail as (senderEmail) senderEmail is the address an app should use when it sends mail in the user's name. A team seat's email is set by its team, so a seat sends as its @puter.email mailbox; any other account sends as its email once confirmed. It ships only with the email itself, so an app without the email grant neither sees it nor triggers the seat read. --- extensions/whoami.test.ts | 149 +++++++++++++++++++- extensions/whoami.ts | 52 ++++++- src/docs/src/Objects/user.md | 4 + src/docs/src/changelog.md | 4 + src/puter-js/src/modules/Auth.js | 4 + src/puter-js/tests/api/suites/auth.suite.ts | 5 + 6 files changed, 212 insertions(+), 6 deletions(-) diff --git a/extensions/whoami.test.ts b/extensions/whoami.test.ts index ced50c2637..6d504dd6a0 100644 --- a/extensions/whoami.test.ts +++ b/extensions/whoami.test.ts @@ -4,7 +4,11 @@ import { v4 as uuidv4 } from 'uuid'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { makeActor, type Actor } from '../src/backend/core/actor.ts'; import { runWithContext } from '../src/backend/core/context.ts'; -import { configContainer } from '../src/backend/exports.ts'; +import { + configContainer, + servicesContainers, + storesContainers, +} from '../src/backend/exports.ts'; import { PuterServer } from '../src/backend/server.ts'; import { setupTestServer } from '../src/backend/testUtil.ts'; import { handleWhoami } from './whoami.ts'; @@ -133,6 +137,145 @@ describe('whoami extension — handleWhoami', () => { }); }); + describe('the address mail is sent as', () => { + // The handler reads stores through extension.import, which resolves + // against the containers rather than the server's copy. + const stubSeats = (ids: unknown[]) => + installSeatStub( + { + stores: storesContainers, + services: servicesContainers, + } as never, + ids as number[], + ); + const teamStore = () => + storesContainers.team as NonNullable; + + const seed = (fields: { email_confirmed?: boolean } = {}) => { + const slug = Math.random().toString(36).slice(2, 8); + return server.stores.user.create({ + username: `WSend_${slug}`, + uuid: uuidv4(), + password: 'hashedpw', + email: `${slug}@example.com`, + ...fields, + }); + }; + + const whoamiAs = async (actor: Actor) => { + const { res, captured } = makeRes(); + await runWithContext({ actor }, () => handleWhoami(makeReq(), res)); + return captured.body as Record; + }; + + const userActor = (user: { uuid: string; id: unknown }) => + makeActor({ user: { uuid: user.uuid, id: user.id as number } }); + + const appActorWithEmail = async (user: { + uuid: string; + id: unknown; + }) => { + const app = await ( + server.stores.app.create as unknown as ( + fields: Record, + opts: { ownerUserId: number }, + ) => Promise<{ uid: string; id: number }> + )( + { + name: `ws-${uuidv4()}`, + title: 'Sender', + index_url: `https://${uuidv4()}.example/`, + }, + { ownerUserId: user.id as number }, + ); + const actor = makeActor({ + user: { uuid: user.uuid, id: user.id as number }, + app: { uid: app.uid, id: app.id }, + }); + return { + actor, + grant: () => + server.services.permission.grantUserAppPermission( + userActor(user), + app.uid, + `user:${user.uuid}:email:read`, + ), + }; + }; + + const withTeams = async (run: () => Promise): Promise => { + const before = configContainer.teams_enabled; + configContainer.teams_enabled = true; + try { + return await run(); + } finally { + configContainer.teams_enabled = before; + } + }; + + it("is a seat's own Puter mailbox, whatever its email", async () => { + const seat = await seed({ email_confirmed: true }); + stubSeats([seat.id]); + const body = await withTeams(() => whoamiAs(userActor(seat))); + expect(body.senderEmail).toBe( + `${seat.username.toLowerCase()}@puter.email`, + ); + expect(body.email).toBe(seat.email); + }); + + it("is any other account's email once confirmed, and absent before", async () => { + const confirmed = await seed({ email_confirmed: true }); + const unconfirmed = await seed(); + stubSeats([]); + await withTeams(async () => { + expect((await whoamiAs(userActor(confirmed))).senderEmail).toBe( + confirmed.email, + ); + expect( + await whoamiAs(userActor(unconfirmed)), + ).not.toHaveProperty('senderEmail'); + }); + }); + + it('treats nobody as a seat where teams is off', async () => { + const seat = await seed(); + stubSeats([seat.id]); + expect(await whoamiAs(userActor(seat))).not.toHaveProperty( + 'senderEmail', + ); + }); + + it('reaches an app with the email grant, and only then reads the seat', async () => { + const seat = await seed(); + stubSeats([seat.id]); + const lookup = vi.spyOn(teamStore(), 'getOrgSeat'); + const { actor, grant } = await appActorWithEmail(seat); + + const before = await withTeams(() => whoamiAs(actor)); + expect(before).not.toHaveProperty('senderEmail'); + expect(lookup).not.toHaveBeenCalled(); + + await grant(); + const after = await withTeams(() => whoamiAs(actor)); + expect(after.senderEmail).toBe( + `${seat.username.toLowerCase()}@puter.email`, + ); + // Still not the seat's team. + expect(after).not.toHaveProperty('team'); + }); + + it('is left out when the seat cannot be read', async () => { + const user = await seed({ email_confirmed: true }); + stubSeats([]); + vi.spyOn(teamStore(), 'getOrgSeat').mockRejectedValue( + new Error('cache down'), + ); + const body = await withTeams(() => whoamiAs(userActor(user))); + expect(body).not.toHaveProperty('senderEmail'); + expect(body.email).toBe(user.email); + }); + }); + it('returns 401 when no actor is on the context', async () => { const { res, captured } = makeRes(); @@ -186,9 +329,7 @@ describe('whoami extension — handleWhoami', () => { const whoamiAs = async (actor: Actor) => { const { res, captured } = makeRes(); - await runWithContext({ actor }, () => - handleWhoami(makeReq(), res), - ); + await runWithContext({ actor }, () => handleWhoami(makeReq(), res)); return captured; }; diff --git a/extensions/whoami.ts b/extensions/whoami.ts index d8cff93887..a754638d71 100644 --- a/extensions/whoami.ts +++ b/extensions/whoami.ts @@ -1,5 +1,7 @@ import { Context } from '@heyputer/backend/src/core'; +import type { OrgSeatRow } from '@heyputer/backend/src/core/teams.js'; import { extension } from '@heyputer/backend/src/extensions'; +import { puterEmailAddressesOf } from '@heyputer/backend/src/services/email/mailbox.js'; import { buildUserDetails, scrubSensitive, @@ -25,6 +27,35 @@ const APP_VISIBLE_LISTENER_KEYS: ReadonlySet = new Set([ 'paid_storage', ]); +/** + * The account's team seat; null when teams is off, undefined when the read + * failed. + */ +const readOrgSeat = async ( + userId: number, +): Promise => { + if (extension.config.teams_enabled !== true || !stores.team) return null; + try { + return await stores.team.getOrgSeat(userId); + } catch { + return undefined; + } +}; + +/** + * The address mail sent in the account's name should use. A seat's email is its + * team's claim, so a seat sends as its own Puter mailbox; any other account as + * its email, once confirmed. + */ +const senderEmailOf = ( + user: UserRow, + emailConfirmed: boolean, + seat: OrgSeatRow | null, +): string | null => { + if (seat) return puterEmailAddressesOf(user.username)[0]; + return emailConfirmed && user.email ? user.email : null; +}; + export const handleWhoami = async ( req: Request, res: Response, @@ -48,6 +79,12 @@ export const handleWhoami = async ( }; // Started beside the row read: the actor carries the row's uuid. const emailCheck = isUser ? null : canReadEmail(actor.user.uuid); + // senderEmail ships with the email, so an app's seat read waits on that + // grant; most app calls hold none and never make it. + const userId = actor.user.id; + const seatRead = emailCheck + ? emailCheck.then((readable) => (readable ? readOrgSeat(userId) : null)) + : readOrgSeat(userId); // Token auth loaded this request's row already; `hasPassword` marks an // actor built from it. const user = @@ -59,11 +96,20 @@ export const handleWhoami = async ( return; } + const seat = await seatRead; const details = await buildUserDetails( user, { config: extension.config, clients, stores, services }, - { isUser }, + { isUser, ...(isUser && seat !== undefined ? { orgSeat: seat } : {}) }, ); + if (seat !== undefined) { + const senderEmail = senderEmailOf( + user, + Boolean(details.email_confirmed), + seat, + ); + if (senderEmail) details.senderEmail = senderEmail; + } details.human_readable_age = user.timestamp ? timeago.format(new Date(user.timestamp as string)) : null; @@ -76,6 +122,7 @@ export const handleWhoami = async ( if (!emailReadable) { delete details.email; delete details.unconfirmed_email; + delete details.senderEmail; } delete details.human_readable_age; delete details.created_ts; @@ -114,7 +161,8 @@ export const handleWhoami = async ( } const subscription = details.subscription as - { offering?: Record } | undefined; + | { offering?: Record } + | undefined; if (subscription?.offering) { delete subscription.offering.group; delete subscription.offering.benefits; diff --git a/src/docs/src/Objects/user.md b/src/docs/src/Objects/user.md index 2a171c946a..89379fd00e 100644 --- a/src/docs/src/Objects/user.md +++ b/src/docs/src/Objects/user.md @@ -51,6 +51,10 @@ A string containing the user's referral code. A boolean value indicating whether the user's account needs email confirmation. +#### `senderEmail` (String) + +The email address to use when your app sends mail for the user, such as the Reply-To of a message. For an account a team created, it's the user's Puter mail address, `@puter.email`. For any other account, it's the user's email address once they've confirmed it. It's missing when there's no address to use. Apps get it only after the user gives them access to their email with [`puter.perms.request('email')`](/Perms/request/). + #### `subscribed` (Boolean) A boolean value indicating whether the user is subscribed. diff --git a/src/docs/src/changelog.md b/src/docs/src/changelog.md index d3d91ffea2..9610ceac3a 100644 --- a/src/docs/src/changelog.md +++ b/src/docs/src/changelog.md @@ -2,6 +2,10 @@ New features, changes, and fixes in Puter.js and the Puter APIs, grouped by day, newest first. +## November 29, 2026 + +- Added the `senderEmail` field to the [`User`](/Objects/user/) object from [`puter.auth.getUser()`](/Auth/getUser/). It's the email address to use when your app sends mail for the user. For an account a team created, it's the user's Puter mail address. + ## November 26, 2026 - Changed Puter.js on a website to open the [`puter.auth.signIn()`](/Auth/signIn/) window when a call is rejected with `phone_verification_required` or `card_verification_required` because the user's account has a verification pending. The call is retried once the user completes it, and rejects with the same error if the user closes the window. diff --git a/src/puter-js/src/modules/Auth.js b/src/puter-js/src/modules/Auth.js index b54a4c4339..85a4c16913 100644 --- a/src/puter-js/src/modules/Auth.js +++ b/src/puter-js/src/modules/Auth.js @@ -27,6 +27,10 @@ import { ancestorsAllowGuiEmbed, canFrameGuiEmbed, showPopupFrame } from '../lib * @property {string} [referral_code] The user's referral code. * @property {boolean | number} [requires_email_confirmation] Whether the user's * account needs email confirmation. + * @property {string} [senderEmail] The address to use when your app sends mail + * for the user. An account a team created uses its Puter mail address, and + * any other account its email once confirmed. Apps get it only with access + * to the user's email. * @property {boolean} [subscribed] Whether the user is subscribed. */ diff --git a/src/puter-js/tests/api/suites/auth.suite.ts b/src/puter-js/tests/api/suites/auth.suite.ts index 313857d799..d8ede04af3 100644 --- a/src/puter-js/tests/api/suites/auth.suite.ts +++ b/src/puter-js/tests/api/suites/auth.suite.ts @@ -178,6 +178,11 @@ export default suite('auth', { t.assert.equal(user.username, t.env.users.user.username); }, + 'getUser names no senderEmail for an account without an email': async (t) => { + const user = await t.puter.auth.getUser(); + t.assert.equal(user.senderEmail, undefined); + }, + 'whoami matches getUser': async (t) => { const whoami = await t.puter.auth.whoami(); const user = await t.puter.auth.getUser(); From 4a7d04e799d4f8bf97c4d1ef7c7642b65608d82d Mon Sep 17 00:00:00 2001 From: Daniel Salazar Date: Sun, 29 Nov 2026 17:33:33 -0700 Subject: [PATCH 2/2] fix(auth): senderEmail follows the stored confirmation and the loaded row's grant - senderEmail uses the account's stored email_confirmed, not the displayed flag, which is forced on for admin. - The email grant and the seat read both key on the loaded row. - A user session's seat read is shared with buildUserDetails and runs beside the other detail reads; a failed read leaves senderEmail out. - Teams on without a team store names no sender. - Bench: whoami with an app token for a passwordless account. --- extensions/whoami.test.ts | 89 ++++++++++++++++++- extensions/whoami.ts | 56 ++++++------ .../core/http/middleware/authProbe.bench.ts | 18 ++++ src/backend/util/userDetails.ts | 6 +- 4 files changed, 134 insertions(+), 35 deletions(-) diff --git a/extensions/whoami.test.ts b/extensions/whoami.test.ts index 6d504dd6a0..42815c2d04 100644 --- a/extensions/whoami.test.ts +++ b/extensions/whoami.test.ts @@ -151,7 +151,13 @@ describe('whoami extension — handleWhoami', () => { const teamStore = () => storesContainers.team as NonNullable; - const seed = (fields: { email_confirmed?: boolean } = {}) => { + const seed = ( + fields: { + email_confirmed?: boolean; + password?: string | null; + username?: string; + } = {}, + ) => { const slug = Math.random().toString(36).slice(2, 8); return server.stores.user.create({ username: `WSend_${slug}`, @@ -237,6 +243,46 @@ describe('whoami extension — handleWhoami', () => { }); }); + it("omits an admin's unconfirmed email as a sender", async () => { + const admin = await seed({ + username: 'admin', + email_confirmed: false, + }); + const body = await whoamiAs(userActor(admin)); + expect(body.email_confirmed).toBe(true); + expect(body).not.toHaveProperty('senderEmail'); + }); + + it('omits the sender when teams is enabled without a seat store', async () => { + const user = await seed({ email_confirmed: true }); + expect(storesContainers.team).toBeUndefined(); + const body = await withTeams(() => whoamiAs(userActor(user))); + expect(body).not.toHaveProperty('senderEmail'); + }); + + it('reads the linked provider while the seat lookup is pending', async () => { + const user = await seed({ password: null }); + stubSeats([]); + const pending = Promise.withResolvers(); + vi.spyOn(teamStore(), 'getOrgSeat').mockReturnValue( + pending.promise, + ); + const provider = vi.spyOn( + servicesContainers.oidc, + 'getLinkedProviderForUser', + ); + const response = withTeams(() => whoamiAs(userActor(user))); + try { + await vi.waitFor(() => + expect(provider).toHaveBeenCalledWith(user.id), + ); + } finally { + pending.resolve(null); + await response; + provider.mockRestore(); + } + }); + it('treats nobody as a seat where teams is off', async () => { const seat = await seed(); stubSeats([seat.id]); @@ -264,15 +310,50 @@ describe('whoami extension — handleWhoami', () => { expect(after).not.toHaveProperty('team'); }); + it('uses the loaded row for both the grant and seat lookup', async () => { + const seat = await seed({ email_confirmed: true }); + const other = await seed(); + stubSeats([seat.id]); + const lookup = vi.spyOn(teamStore(), 'getOrgSeat'); + const { actor } = await appActorWithEmail(seat); + const check = vi + .spyOn(servicesContainers.permission, 'check') + .mockImplementation( + async (_actor, key) => + key === `user:${seat.uuid}:email:read`, + ); + try { + await withTeams(async () => { + const denied = await whoamiAs({ + ...actor, + user: { uuid: seat.uuid, id: other.id }, + }); + expect(denied).not.toHaveProperty('email'); + expect(denied).not.toHaveProperty('senderEmail'); + expect(lookup).not.toHaveBeenCalled(); + const permitted = await whoamiAs({ + ...actor, + user: { uuid: other.uuid, id: seat.id }, + }); + expect(permitted.senderEmail).toBe( + `${seat.username.toLowerCase()}@puter.email`, + ); + }); + } finally { + check.mockRestore(); + } + }); + it('is left out when the seat cannot be read', async () => { const user = await seed({ email_confirmed: true }); stubSeats([]); - vi.spyOn(teamStore(), 'getOrgSeat').mockRejectedValue( - new Error('cache down'), - ); + const lookup = vi + .spyOn(teamStore(), 'getOrgSeat') + .mockRejectedValue(new Error('cache down')); const body = await withTeams(() => whoamiAs(userActor(user))); expect(body).not.toHaveProperty('senderEmail'); expect(body.email).toBe(user.email); + expect(lookup).toHaveBeenCalledTimes(1); }); }); diff --git a/extensions/whoami.ts b/extensions/whoami.ts index a754638d71..530dc805ea 100644 --- a/extensions/whoami.ts +++ b/extensions/whoami.ts @@ -34,10 +34,11 @@ const APP_VISIBLE_LISTENER_KEYS: ReadonlySet = new Set([ const readOrgSeat = async ( userId: number, ): Promise => { - if (extension.config.teams_enabled !== true || !stores.team) return null; + if (extension.config.teams_enabled !== true) return null; try { - return await stores.team.getOrgSeat(userId); - } catch { + return await stores.team?.getOrgSeat(userId); + } catch (error) { + console.warn('[whoami] team lookup failed:', error); return undefined; } }; @@ -49,11 +50,10 @@ const readOrgSeat = async ( */ const senderEmailOf = ( user: UserRow, - emailConfirmed: boolean, seat: OrgSeatRow | null, ): string | null => { if (seat) return puterEmailAddressesOf(user.username)[0]; - return emailConfirmed && user.email ? user.email : null; + return user.email_confirmed && user.email ? user.email : null; }; export const handleWhoami = async ( @@ -78,13 +78,10 @@ export const handleWhoami = async ( } }; // Started beside the row read: the actor carries the row's uuid. - const emailCheck = isUser ? null : canReadEmail(actor.user.uuid); - // senderEmail ships with the email, so an app's seat read waits on that - // grant; most app calls hold none and never make it. - const userId = actor.user.id; - const seatRead = emailCheck - ? emailCheck.then((readable) => (readable ? readOrgSeat(userId) : null)) - : readOrgSeat(userId); + const emailCheck = isUser + ? Promise.resolve(true) + : canReadEmail(actor.user.uuid); + const userSeat = isUser ? readOrgSeat(actor.user.id) : null; // Token auth loaded this request's row already; `hasPassword` marks an // actor built from it. const user = @@ -96,18 +93,25 @@ export const handleWhoami = async ( return; } - const seat = await seatRead; - const details = await buildUserDetails( - user, - { config: extension.config, clients, stores, services }, - { isUser, ...(isUser && seat !== undefined ? { orgSeat: seat } : {}) }, - ); - if (seat !== undefined) { - const senderEmail = senderEmailOf( - user, - Boolean(details.email_confirmed), - seat, + const emailReadable = + isUser || user.uuid === actor.user.uuid + ? emailCheck + : canReadEmail(user.uuid); + const seatRead = + userSeat ?? + emailReadable.then((readable) => + readable ? readOrgSeat(user.id) : undefined, ); + const [details, seat] = await Promise.all([ + buildUserDetails( + user, + { config: extension.config, clients, stores, services }, + { isUser, orgSeat: userSeat ?? undefined }, + ), + seatRead, + ]); + if (seat !== undefined) { + const senderEmail = senderEmailOf(user, seat); if (senderEmail) details.senderEmail = senderEmail; } details.human_readable_age = user.timestamp @@ -116,13 +120,9 @@ export const handleWhoami = async ( // Strip sensitive fields for app actors if (!isUser) { - const emailReadable = await (user.uuid === actor.user.uuid - ? emailCheck - : canReadEmail(user.uuid)); - if (!emailReadable) { + if (!(await emailReadable)) { delete details.email; delete details.unconfirmed_email; - delete details.senderEmail; } delete details.human_readable_age; delete details.created_ts; diff --git a/src/backend/core/http/middleware/authProbe.bench.ts b/src/backend/core/http/middleware/authProbe.bench.ts index 3ff5d4c954..dca2f73405 100644 --- a/src/backend/core/http/middleware/authProbe.bench.ts +++ b/src/backend/core/http/middleware/authProbe.bench.ts @@ -4,6 +4,7 @@ import { makeActor } from '../../actor.js'; describe('auth', () => { let appToken = ''; + let passwordlessAppToken = ''; const seed = async (env: BenchEnv) => { const owner = await env.server.stores.user.getByUsername( @@ -21,6 +22,16 @@ describe('auth', () => { makeActor({ user: owner! }), app.uid, ); + const passwordless = await env.server.stores.user.create({ + username: 'auth-bench-passwordless', + uuid: crypto.randomUUID(), + password: null, + email: 'auth-bench@example.com', + }); + passwordlessAppToken = await env.server.services.auth.getUserAppToken( + makeActor({ user: passwordless }), + app.uid, + ); }; const env = useBenchEnv({ seed }); @@ -41,6 +52,13 @@ describe('auth', () => { await env.request('/whoami', { token: appToken }); }); + env.scenario( + 'whoami with an app token for a passwordless account', + async () => { + await env.request('/whoami', { token: passwordlessAppToken }); + }, + ); + env.scenario('log in with a password', async () => { const { username, password } = env.users.other; const response = await fetch(new URL('/login', env.origin), { diff --git a/src/backend/util/userDetails.ts b/src/backend/util/userDetails.ts index 62c1bb6f55..6d4c28eaf0 100644 --- a/src/backend/util/userDetails.ts +++ b/src/backend/util/userDetails.ts @@ -176,8 +176,8 @@ export async function buildUserDetails( deps: UserDetailsDeps, opts: { isUser: boolean; - /** The account's team seat when the caller already read it. */ - orgSeat?: OrgSeatRow | null; + /** The account's team seat when the caller already started the lookup. */ + orgSeat?: OrgSeatRow | null | Promise; }, ): Promise> { const { config, clients, stores, services } = deps; @@ -259,8 +259,8 @@ export async function buildUserDetails( // The team that pays for the account; every seat restriction keys on it. const orgSeat = async () => { if (!isUser || config.teams_enabled !== true) return null; - if (opts.orgSeat !== undefined) return { seat: opts.orgSeat }; try { + if (opts.orgSeat !== undefined) return { seat: await opts.orgSeat }; return { seat: await stores.team?.getOrgSeat(user.id) }; } catch (error) { return { error };