diff --git a/backend/src/app.ts b/backend/src/app.ts index 725cf0d..b6e7005 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -1,3 +1,7 @@ +import { photoCacheControl } from './storage/photoCache.js'; +import { canUpdateWorkspaceSettings, subscriptionAllowsWrite } from './workspaceAccess.js'; +import { buildWorkspaceInviteEmail } from './emails/workspaceInviteEmail.js'; +import { exportFlock } from './repositories/flockExportRepository.js'; import { unassignedBirdMatchSchema, claimBirdSchema } from './birdMembershipSchemas.js'; import { hasUnassignedBird, removeBirdFromFlock, claimUnassignedBird } from './repositories/birdMembershipRepository.js'; import { behaviorTypeSchema, behaviorOccurrenceSchema, behaviorRangeSchema } from './behaviorSchemas.js'; @@ -986,14 +990,6 @@ const normalizeWorkspaceMembershipList = async (userId: string) => const isAdminUser = (user: UserRow) => adminEmails.has(normalizeEmail(user.email)); -const subscriptionAllowsWrite = (workspace: WorkspaceRow) => { - if (workspace.workspace_type === 'rescue') { - return workspace.rescue_verification_status === 'approved'; - } - - return workspace.subscription_status === 'active' || workspace.subscription_status === 'trialing'; -}; - const mapStripeSubscriptionStatus = (status: Stripe.Subscription.Status): SubscriptionStatus => { if (status === 'active' || status === 'trialing' || status === 'past_due' || status === 'canceled' || status === 'unpaid') { return status; @@ -2214,11 +2210,6 @@ const writeBirdTimelineEvent = async ({ } }; -const isBillingOnlyWorkspaceUpdate = ( - workspace: WorkspaceRow, - payload: z.infer, -) => workspace.workspace_type === 'standard' && payload.workspaceType === 'standard' && payload.name === workspace.name; - app.get('/api/health', (_req: Request, res: Response) => { res.json({ ok: true }); }); @@ -2964,6 +2955,40 @@ app.post('/api/workspaces', requireAuth, requireSessionAuth, async (req: Request } }); +app.get('/api/workspace/export', requireAuth, requireSessionAuth, async (req: Request, res: Response, next: NextFunction) => { + try { + const parsed = z.object({ birdId: z.string().uuid().optional() }).safeParse(req.query); + if (!parsed.success) { + res.status(400).json({ error: 'Invalid bird selection.' }); + return; + } + const { birdId } = parsed.data; + const data = await exportFlock(req.auth!.workspace.id, birdId); + if (birdId && data.birds.length === 0) { + res.status(404).json({ error: 'Bird not found in this flock.' }); + return; + } + for (const bird of data.birds) { + if (bird.photo_object_key) { + const config = getS3ImageStorageConfig(); + if (!config) throw new Error('Image storage is not configured. Unable to export flock photos.'); + const response = await fetch(getSignedS3ObjectUrl({ config, objectKey: bird.photo_object_key, expiresInSeconds: 300 }), { + signal: AbortSignal.timeout(30_000), + }); + if (!response.ok) throw new Error('Unable to export a flock photo. Please try again.'); + const contentType = bird.photo_content_type || response.headers.get('content-type') || 'application/octet-stream'; + bird.photo_data_url = `data:${contentType};base64,${Buffer.from(await response.arrayBuffer()).toString('base64')}`; + } + delete bird.photo_object_key; + } + res.setHeader('Cache-Control', 'no-store'); + res.attachment(`flockpal-${birdId ? `bird-${birdId}` : `flock-${req.auth!.workspace.id}`}-${new Date().toISOString().slice(0, 10)}.json`); + res.json(data); + } catch (error) { + next(error); + } +}); + app.get('/api/workspace', requireAuth, async (req: Request, res: Response) => { res.json({ workspace: normalizeWorkspace(req.auth!.workspace) }); }); @@ -2981,10 +3006,7 @@ app.put('/api/workspace', requireAuth, requireSessionAuth, requireWorkspaceRole( const billingPlan = resolveBillingPlan(parsed.data.workspaceType, parsed.data.billingPlan ?? currentWorkspace.billing_plan); const billingInterval = parsed.data.workspaceType === 'rescue' ? 'monthly' : (parsed.data.billingInterval ?? currentWorkspace.billing_interval); const isConvertingToRescue = currentWorkspace.workspace_type !== 'rescue' && parsed.data.workspaceType === 'rescue'; - const canUpdateWorkspace = - isAdminUser(req.auth!.user) || - subscriptionAllowsWrite(currentWorkspace) || - isBillingOnlyWorkspaceUpdate(currentWorkspace, parsed.data); + const canUpdateWorkspace = canUpdateWorkspaceSettings(currentWorkspace, parsed.data, isAdminUser(req.auth!.user)); if (!canUpdateWorkspace) { res.status(402).json({ @@ -3130,6 +3152,37 @@ app.get('/api/workspace/members', requireAuth, async (req: Request, res: Respons } }); +const sendWorkspaceInvitation = async (auth: AuthContext, member: WorkspaceMemberRow) => { + if (!mailTransport) return { sent: false, message: 'Access is saved, but email delivery is not configured. Share the sign-in instructions directly.' }; + try { + const result = await mailTransport.sendMail({ + from: smtpFromName ? `"${smtpFromName}" <${smtpFromEmail}>` : smtpFromEmail, + to: member.invite_email, + ...await buildWorkspaceInviteEmail({ + name: member.name, email: member.invite_email, inviterName: auth.user.name, + flockName: auth.workspace.name, role: member.role, frontendUrl: frontendBaseUrl, + }), + }); + if (!result.accepted?.length) throw new Error('Invitation email was not accepted.'); + return { sent: true, message: 'Invitation email sent. Access is ready when they sign in with the invited email address.' }; + } catch { + return { sent: false, message: 'Access is saved, but the invitation email could not be sent. Use Resend invitation to try again.' }; + } +}; + +app.post('/api/workspace/members/:memberId/invitation', requireAuth, requireSessionAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant']), async (req: Request, res: Response, next: NextFunction) => { + try { + const member = (await listWorkspaceMembers(req.auth!.workspace.id)).find((entry) => entry.id === req.params.memberId); + if (!member) { + res.status(404).json({ error: 'Flock member not found.' }); + return; + } + const invitation = await sendWorkspaceInvitation(req.auth!, member); + await writeAuditLog(req.auth!, 'workspace_member.invitation_resent', 'workspace_member', member.id, member.name, { sent: invitation.sent }); + res.json({ invitation }); + } catch (error) { next(error); } +}); + app.post('/api/workspace/members', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant']), async (req: Request, res: Response, next: NextFunction) => { const parsed = workspaceMemberSchema.safeParse(req.body); @@ -3153,7 +3206,8 @@ app.post('/api/workspace/members', requireAuth, requireWriteAccess, requireWorks inviteEmail: member!.invite_email, role: member!.role, }); - res.status(201).json({ member: normalizeWorkspaceMember(member!) }); + const invitation = await sendWorkspaceInvitation(req.auth!, member!); + res.status(201).json({ member: normalizeWorkspaceMember(member!), invitation }); } catch (error) { next(error); } @@ -3443,6 +3497,8 @@ app.post( ); app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: NextFunction) => { + // Invalid tokens, missing photos and upstream failures must never be cached. + res.setHeader('Cache-Control', 'no-store'); try { const token = typeof req.query.token === 'string' ? req.query.token : ''; const photoAccess = verifyBirdPhotoAccessToken(token); @@ -3472,9 +3528,8 @@ app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: Ne expiresInSeconds: 5 * 60, }); - res.setHeader('Cache-Control', 'private, max-age=900'); - if (photoDeliveryMode === 'redirect') { + res.setHeader('Cache-Control', photoCacheControl('redirect', photoAccess.expiresAt)); res.redirect(302, signedUrl); return; } @@ -3490,6 +3545,7 @@ app.get('/api/birds/:birdId/photo', async (req: Request, res: Response, next: Ne const contentLength = imageResponse.headers.get('content-length'); const imageBuffer = Buffer.from(await imageResponse.arrayBuffer()); + res.setHeader('Cache-Control', photoCacheControl('proxy', photoAccess.expiresAt)); res.setHeader('Content-Type', contentType); if (contentLength) { @@ -3963,7 +4019,7 @@ app.put('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceR } }); -app.delete('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant', 'caregiver']), async (req: Request, res: Response, next: NextFunction) => { +app.delete('/api/birds/:birdId', requireAuth, requireWriteAccess, requireWorkspaceRole(['owner', 'assistant']), async (req: Request, res: Response, next: NextFunction) => { try { const bird = await getBirdById(req.params.birdId, req.auth!.workspace.id); diff --git a/backend/src/docs/openapi.test.ts b/backend/src/docs/openapi.test.ts index 5db4644..9aa6404 100644 --- a/backend/src/docs/openapi.test.ts +++ b/backend/src/docs/openapi.test.ts @@ -115,3 +115,20 @@ test('Swagger UI, initialization, assets and specification are served locally wi assert.equal(redirect.status, 301); assert.equal(redirect.headers.get('location'), '/api/docs/'); }); + +test('bird removal is restricted to owners and assistants in the API and its documentation', () => { + const route = ast.statements.find((statement) => + ts.isExpressionStatement(statement) && ts.isCallExpression(statement.expression) && + statement.expression.expression.getText(ast) === 'app.delete' && + statement.expression.arguments[0]?.getText(ast) === "'/api/birds/:birdId'" + ); + assert.ok(route && ts.isExpressionStatement(route) && ts.isCallExpression(route.expression)); + const guard = route.expression.arguments.find((arg) => + ts.isCallExpression(arg) && arg.expression.getText(ast) === 'requireWorkspaceRole' + ); + assert.ok(guard && ts.isCallExpression(guard)); + assert.equal(guard.arguments[0].getText(ast), "['owner', 'assistant']"); + const description = customerOpenApi.paths['/birds/{birdId}']!.delete!.description!; + assert.match(description, /Allowed roles: owner, assistant\./); + assert.doesNotMatch(description, /caregiver/); +}); diff --git a/backend/src/docs/openapi.ts b/backend/src/docs/openapi.ts index 902d52d..0142519 100644 --- a/backend/src/docs/openapi.ts +++ b/backend/src/docs/openapi.ts @@ -63,7 +63,7 @@ const one = (name: string, model: z.ZodTypeAny) => z.object({ [name]: model }); const many = (name: string, model: z.ZodTypeAny) => one(name, z.array(model)); endpoint({ method: 'get', path: '/workspace', summary: 'Get the token’s workspace', tag: 'Workspace', response: one('workspace', models.workspaceResponse) }); endpoint({ method: 'get', path: '/workspace/members', summary: 'List workspace members', tag: 'Workspace', response: many('members', models.memberResponse) }); -endpoint({ method: 'post', path: '/workspace/members', summary: 'Add or update a workspace member', tag: 'Workspace', body: registry.register('MemberInput', workspaceMemberSchema), response: one('member', models.memberResponse), roles: ['owner', 'assistant'] }); +endpoint({ method: 'post', path: '/workspace/members', summary: 'Add or update a workspace member', tag: 'Workspace', body: registry.register('MemberInput', workspaceMemberSchema), response: z.object({ member: models.memberResponse, invitation: z.object({ sent: z.boolean(), message: z.string() }) }), roles: ['owner', 'assistant'], description: 'Saves access and attempts to send a branded invitation email. Check invitation.sent for email submission status; access remains saved if email delivery fails.' }); endpoint({ method: 'put', path: '/workspace/members/{memberId}', summary: 'Change a member’s role', tag: 'Workspace', body: z.object({ role: workspaceRoleSchema }), response: one('member', models.memberResponse), roles: ['owner', 'assistant'], errors: [404], description: 'Only the billing owner can promote collaborators to owner. Additional protections apply to changing your own or the billing owner’s membership.' }); endpoint({ method: 'delete', path: '/workspace/members/{memberId}', summary: 'Remove a workspace member', tag: 'Workspace', roles: ['owner', 'assistant'], errors: [404], description: 'Protected memberships cannot be removed.' }); endpoint({ method: 'get', path: '/notes', summary: 'List flock notes', tag: 'Notes', response: many('notes', models.noteResponse) }); @@ -77,7 +77,7 @@ const birdInput = registry.register('BirdInput', birdSchema); const birdDescription = 'motivators and demotivators each allow up to three non-empty lines. hatchDay takes precedence over the legacy dateOfBirth field. photoDataUrl accepts an image data URL or HTTP(S) URL; returned photo links may expire.'; endpoint({ method: 'post', path: '/birds', summary: 'Create a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [409], description: birdDescription, example: { name: 'Yoda', species: 'African grey' } }); endpoint({ method: 'put', path: '/birds/{birdId}', summary: 'Update a bird', tag: 'Birds', body: birdInput, response: one('bird', models.birdResponse), errors: [404, 409], description: `Submit the full editable profile: omitted optional fields may be cleared or reset. ${birdDescription}` }); -endpoint({ method: 'delete', path: '/birds/{birdId}', summary: 'Remove a bird from its flock', tag: 'Birds', errors: [404, 409], description: 'Unassigns the bird without deleting its profile, photo, or care history. Bird-specific notes follow the bird; flock-wide notes and workspace audit logs stay in the old flock. Public sharing is disabled and pending transfers are revoked. An exact band ID match can later bring the bird and its history into a flock.' }); +endpoint({ method: 'delete', path: '/birds/{birdId}', summary: 'Remove a bird from its flock', roles: ['owner', 'assistant'], tag: 'Birds', errors: [404, 409], description: 'Unassigns the bird without deleting its profile, photo, or care history. Bird-specific notes follow the bird; flock-wide notes and workspace audit logs stay in the old flock. Public sharing is disabled and pending transfers are revoked. An exact band ID match can later bring the bird and its history into a flock.' }); endpoint({ method: 'get', path: '/birds/{birdId}/timeline', summary: 'List bird timeline events', tag: 'Birds', response: many('events', models.timelineResponse), errors: [404] }); for (const resource of [ { path: 'weights', single: 'weight', plural: 'weights', id: 'weightId', tag: 'Weights', input: weightSchema, model: models.weightResponse }, diff --git a/backend/src/emails/workspaceInviteEmail.test.ts b/backend/src/emails/workspaceInviteEmail.test.ts new file mode 100644 index 0000000..c8305ae --- /dev/null +++ b/backend/src/emails/workspaceInviteEmail.test.ts @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { buildWorkspaceInviteEmail } from './workspaceInviteEmail.js'; + +const input = { name: '', email: 'pat@example.test', inviterName: 'Alex & Sam', flockName: '', role: 'caregiver' as const, frontendUrl: 'https://flockpal.test/' }; + +test('invitation uses branded layout, escaped copy, and email-specific sign-in instructions', async () => { + const mail = await buildWorkspaceInviteEmail(input); + assert.match(String(mail.html), /<Pat>/); + assert.match(String(mail.html), /Alex & Sam/); + assert.match(String(mail.html), /<Rescue>/); + assert.match(String(mail.html), /cid:flockpal-logo/); + assert.equal(mail.attachments?.length, 1); + assert.match(mail.text, /Sign in to FlockPal using pat@example.test/); + assert.match(mail.text, /cannot remove birds/); + assert.match(mail.text, /flock switcher/); + assert.match(String(mail.html), /href="https:\/\/flockpal.test\/"/); +}); + +test('invitation describes each assigned role and prevents multiline subjects', async () => { + for (const role of ['viewer', 'caregiver', 'assistant', 'owner'] as const) { + const mail = await buildWorkspaceInviteEmail({ ...input, role, flockName: 'Rescue\r\nFlock' }); + assert.doesNotMatch(mail.subject, /[\r\n]/); + assert.ok(mail.text.includes(role.charAt(0).toUpperCase() + role.slice(1))); + if (role === 'viewer') assert.match(mail.text, /cannot edit records/); + if (role === 'assistant') assert.match(mail.text, /remove and transfer birds/); + if (role === 'owner') assert.match(mail.text, /does not change the billing owner/); + } +}); diff --git a/backend/src/emails/workspaceInviteEmail.ts b/backend/src/emails/workspaceInviteEmail.ts new file mode 100644 index 0000000..9a176f9 --- /dev/null +++ b/backend/src/emails/workspaceInviteEmail.ts @@ -0,0 +1,26 @@ +import { buildEmailLayout, escapeHtml } from './emailLayout.js'; +import type { WorkspaceRole } from '../types.js'; + +const permissions: Record = { + viewer: 'You can view all birds and care histories, and export flock data. You cannot edit records.', + caregiver: 'You can view and export flock data, add and edit birds, log daily care, and delete supported care records. You cannot remove birds or manage sharing, billing, or transfers.', + assistant: 'You can manage birds and care records, remove and transfer birds, manage collaborators, flock settings and billing, and view the audit log.', + owner: 'You have full flock control, including bird removal, transfers, sharing, billing management, memorializing birds, and deleting an empty flock. This does not change the billing owner.', +}; + +export const buildWorkspaceInviteEmail = async ({ name, email, inviterName, flockName, role, frontendUrl }: { + name: string; email: string; inviterName: string; flockName: string; role: WorkspaceRole; frontendUrl: string; +}) => { + const roleLabel = role.charAt(0).toUpperCase() + role.slice(1); + const instructions = `Sign in to FlockPal using ${email}. If you do not have an account, use that email to get started. After signing in, choose ${flockName} in the flock switcher in the navigation or Settings → Flock profile. If you are already signed in and the flock is missing, sign out and sign back in.`; + return { + subject: `You’re invited to ${flockName.replace(/[\r\n]+/g, ' ')} on FlockPal`, + text: `Hi ${name},\n\n${inviterName} has invited you to ${flockName} as a ${roleLabel}.\n\n${permissions[role]}\n\n${instructions}\n\nOpen FlockPal: ${frontendUrl}\n\nIf you were not expecting this invitation, you can ignore this email.`, + ...await buildEmailLayout({ + eyebrow: 'Shared flock invitation', headline: `You’re invited to ${flockName}`, + contentHtml: `

Hi ${escapeHtml(name)},

${escapeHtml(inviterName)} has invited you to ${escapeHtml(flockName)} as a ${roleLabel}.

${escapeHtml(permissions[role])}

${escapeHtml(instructions)}

`, + action: { url: frontendUrl, label: 'Open FlockPal' }, + footer: 'If you were not expecting this invitation, you can ignore this email.', + }), + }; +}; diff --git a/backend/src/repositories/flockExportRepository.test.ts b/backend/src/repositories/flockExportRepository.test.ts new file mode 100644 index 0000000..87ef41e --- /dev/null +++ b/backend/src/repositories/flockExportRepository.test.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { exportFlock } from './flockExportRepository.js'; +import { mockDb } from '../test/mockDb.js'; + +test('export scopes every history to the selected flock without date or memorial filters', async () => { + const data = { formatVersion: 1, birds: [], workspace: { id: 42, name: 'Flock' } }; + const { calls } = mockDb({ rows: [{ data }] }); + assert.deepEqual(await exportFlock(42), data); + assert.equal(calls.length, 1); + const { text, params } = calls[0]; + assert.deepEqual(params, [42, null]); + assert.match(text, /SELECT \* FROM birds WHERE workspace_id = \$1/); + for (const table of ['weight_records', 'vet_visits', 'medications', 'medication_administrations', 'behavior_occurrences', 'bird_timeline_events']) { + assert.ok(text.includes(`FROM ${table} r JOIN flock_birds b ON b.id = r.bird_id`)); + } + assert.match(text, /FROM flock_notes n WHERE n.workspace_id = \$1/); + assert.doesNotMatch(text, /LIMIT|memorialized_at IS NULL|INTERVAL/); + assert.doesNotMatch(text, /auth_sessions|integration_tokens|stripe|magic_link/); +}); + +test('single member export restricts profiles, notes, and behavior types to the selected bird', async () => { + const birdId = 'd0ab1d12-7859-4a64-a354-dd58bf738b94'; + const data = { birds: [{ id: birdId }] }; + const { calls } = mockDb({ rows: [{ data }] }); + assert.deepEqual(await exportFlock(42, birdId), data); + assert.deepEqual(calls[0].params, [42, birdId]); + assert.ok(calls[0].text.includes('workspace_id = $1 AND ($2::uuid IS NULL OR id = $2)')); + assert.ok(calls[0].text.includes('AND ($2::uuid IS NULL OR n.bird_id IN (SELECT id FROM flock_birds))')); + assert.ok(calls[0].text.includes('WHERE ($2::uuid IS NULL AND (t.is_default OR t.workspace_id = $1)) OR EXISTS')); +}); diff --git a/backend/src/repositories/flockExportRepository.ts b/backend/src/repositories/flockExportRepository.ts new file mode 100644 index 0000000..4b9a3c0 --- /dev/null +++ b/backend/src/repositories/flockExportRepository.ts @@ -0,0 +1,48 @@ +import { db } from '../db/client.js'; + +type ExportBird = Record & { + photo_object_key?: string | null; + photo_content_type?: string | null; + photo_data_url?: string | null; +}; + +export type FlockExport = { + formatVersion: number; + exportedAt: string; + workspace: { id: number; name: string }; + birds: ExportBird[]; + [key: string]: unknown; +}; + +// A single statement provides a consistent snapshot, including all dates and memorialized birds. +export const exportFlock = async (workspaceId: number, birdId?: string): Promise => { + const birdTables = { + weights: 'weight_records', + vetVisits: 'vet_visits', + medications: 'medications', + medicationAdministrations: 'medication_administrations', + behaviors: 'behavior_occurrences', + timeline: 'bird_timeline_events', + }; + const histories = Object.entries(birdTables).map(([key, table]) => + `'${key}', (SELECT COALESCE(jsonb_agg(to_jsonb(r) ORDER BY r.id), '[]'::jsonb) + FROM ${table} r JOIN flock_birds b ON b.id = r.bird_id)` + ); + const result = await db.query<{ data: FlockExport }>(` + WITH flock_birds AS (SELECT * FROM birds WHERE workspace_id = $1 AND ($2::uuid IS NULL OR id = $2)) + SELECT jsonb_build_object( + 'formatVersion', 1, + 'exportedAt', CURRENT_TIMESTAMP, + 'workspace', (SELECT jsonb_build_object('id', id, 'name', name) FROM workspaces WHERE id = $1), + 'birds', (SELECT COALESCE(jsonb_agg(to_jsonb(b) ORDER BY b.id), '[]'::jsonb) FROM flock_birds b), + 'notes', (SELECT COALESCE(jsonb_agg(to_jsonb(n) ORDER BY n.id), '[]'::jsonb) + FROM flock_notes n WHERE n.workspace_id = $1 + AND ($2::uuid IS NULL OR n.bird_id IN (SELECT id FROM flock_birds))), + 'behaviorTypes', (SELECT COALESCE(jsonb_agg(to_jsonb(t) - 'workspace_id' ORDER BY t.id), '[]'::jsonb) + FROM behavior_types t WHERE ($2::uuid IS NULL AND (t.is_default OR t.workspace_id = $1)) OR EXISTS ( + SELECT 1 FROM behavior_occurrences o JOIN flock_birds b ON b.id = o.bird_id + WHERE o.behavior_type_id = t.id)), + ${histories.join(',\n')} + ) AS data`, [workspaceId, birdId ?? null]); + return result.rows[0].data; +}; diff --git a/backend/src/storage/photoCache.test.ts b/backend/src/storage/photoCache.test.ts new file mode 100644 index 0000000..5571bb9 --- /dev/null +++ b/backend/src/storage/photoCache.test.ts @@ -0,0 +1,13 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { photoCacheControl } from './photoCache.js'; + +test('storage redirects cannot be cached beyond the signed destination lifetime', () => { + assert.equal(photoCacheControl('redirect', 1900, 1000), 'no-store'); +}); + +test('proxy caching is bounded by the remaining app token lifetime', () => { + assert.equal(photoCacheControl('proxy', 1900, 1000), 'private, max-age=900, must-revalidate'); + assert.equal(photoCacheControl('proxy', 1050, 1000), 'private, max-age=50, must-revalidate'); + assert.equal(photoCacheControl('proxy', 999, 1000), 'private, max-age=0, must-revalidate'); +}); diff --git a/backend/src/storage/photoCache.ts b/backend/src/storage/photoCache.ts new file mode 100644 index 0000000..cfdec00 --- /dev/null +++ b/backend/src/storage/photoCache.ts @@ -0,0 +1,4 @@ +// Never cache a redirect to a signed storage URL: its lifetime is independent of +// the app token. Successful proxy responses cannot outlive the app token. +export const photoCacheControl = (mode: 'proxy' | 'redirect', expiresAt: number, now = Math.floor(Date.now() / 1000)) => + mode === 'redirect' ? 'no-store' : `private, max-age=${Math.max(0, Math.min(900, expiresAt - now))}, must-revalidate`; diff --git a/backend/src/test/workspaceAccess.test.ts b/backend/src/test/workspaceAccess.test.ts new file mode 100644 index 0000000..aa41220 --- /dev/null +++ b/backend/src/test/workspaceAccess.test.ts @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { canUpdateWorkspaceSettings, subscriptionAllowsWrite } from '../workspaceAccess.js'; +import type { WorkspaceRow } from '../types.js'; + +type Access = Pick; +const household: Access = { name: 'Our flock', workspace_type: 'standard', subscription_status: 'none', rescue_verification_status: 'not_required' }; + +test('unsubscribed households can request rescue verification, including a new flock name', () => { + for (const subscription_status of ['none', 'past_due', 'canceled', 'unpaid', 'active', 'trialing'] as const) { + assert.equal(canUpdateWorkspaceSettings({ ...household, subscription_status }, { name: 'Our rescue', workspaceType: 'rescue' }, false), true); + } +}); + +test('conversion does not make unverified rescues writable, even with an active subscription', () => { + for (const rescue_verification_status of ['pending', 'rejected', 'not_required'] as const) { + const rescue: Access = { ...household, workspace_type: 'rescue', subscription_status: 'active', rescue_verification_status }; + assert.equal(subscriptionAllowsWrite(rescue), false); + assert.equal(canUpdateWorkspaceSettings(rescue, { name: rescue.name, workspaceType: 'rescue' }, false), false); + } + assert.equal(subscriptionAllowsWrite({ ...household, workspace_type: 'rescue', rescue_verification_status: 'approved' }), true); +}); + +test('household edits remain subscription gated while billing recovery and admin access still work', () => { + assert.equal(subscriptionAllowsWrite(household), false); + assert.equal(canUpdateWorkspaceSettings(household, { name: 'Renamed', workspaceType: 'standard' }, false), false); + assert.equal(canUpdateWorkspaceSettings(household, { name: household.name, workspaceType: 'standard' }, false), true); + assert.equal(canUpdateWorkspaceSettings(household, { name: 'Renamed', workspaceType: 'standard' }, true), true); + assert.equal(subscriptionAllowsWrite({ ...household, subscription_status: 'active' }), true); +}); diff --git a/backend/src/workspaceAccess.ts b/backend/src/workspaceAccess.ts new file mode 100644 index 0000000..022b273 --- /dev/null +++ b/backend/src/workspaceAccess.ts @@ -0,0 +1,22 @@ +import type { WorkspaceRow, WorkspaceType } from './types.js'; + +type WorkspaceAccess = Pick; + +export const subscriptionAllowsWrite = (workspace: WorkspaceAccess) => { + if (workspace.workspace_type === 'rescue') { + return workspace.rescue_verification_status === 'approved'; + } + return workspace.subscription_status === 'active' || workspace.subscription_status === 'trialing'; +}; + +export const canUpdateWorkspaceSettings = ( + workspace: WorkspaceAccess, + payload: { name: string; workspaceType: WorkspaceType }, + isAdmin: boolean, +) => { + // Requesting rescue verification must not require buying a household subscription. + // The route still validates onboarding and the repository marks the rescue pending. + const requestingRescue = workspace.workspace_type === 'standard' && payload.workspaceType === 'rescue'; + const billingOnly = workspace.workspace_type === 'standard' && payload.workspaceType === 'standard' && payload.name === workspace.name; + return isAdmin || subscriptionAllowsWrite(workspace) || requestingRescue || billingOnly; +}; diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 5dd7289..9683a4e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,3 +1,5 @@ +import { usePhotoRefresh } from './usePhotoRefresh'; +import { FlockSwitcher } from './FlockSwitcher'; import { combineLocationOwnerMarkers } from './birdTimeline'; import { BehaviorJournal } from './BehaviorJournal'; import { useEffect, useMemo, useState, type CSSProperties, type Dispatch, type SetStateAction } from 'react'; @@ -1799,6 +1801,20 @@ const formatRescueVerificationStatus = (status: RescueVerificationStatus) => { return 'Pending verification'; }; +const workspaceRoleDescriptions: Record = { + viewer: 'Can view every bird and their care history, and download flock or individual bird exports. Cannot edit birds or care records.', + caregiver: 'Can view and export, add and edit birds, record daily care, and delete supported care records. Cannot remove birds from the flock or manage sharing, billing, or bird transfers.', + assistant: 'Can do everything a Caregiver can, plus remove birds from the flock, manage collaborators, flock settings and billing, transfer birds, and view the audit log. Cannot memorialize birds or delete the flock.', + owner: 'Can do everything an Assistant can, plus memorialize birds, manage memorial reminders, and delete an empty flock. Owner access does not change the billing owner.', +}; + +const workspaceRoleLabels: Record = { + viewer: 'Viewer — view and export', + caregiver: 'Caregiver — birds and daily care', + assistant: 'Assistant — flock management', + owner: 'Owner — full flock control', +}; + const formatWorkspaceRole = (role: WorkspaceRole) => { if (role === 'owner') { return 'Owner'; @@ -2172,6 +2188,9 @@ function App() { const [birdImportPreview, setBirdImportPreview] = useState(null); const [birdImportFileName, setBirdImportFileName] = useState(''); + const [exportBirdId, setExportBirdId] = useState(''); + const [exportingFlock, setExportingFlock] = useState(false); + const [flockExportError, setFlockExportError] = useState(''); const [birdImportNotice, setBirdImportNotice] = useState(''); const [importingBirds, setImportingBirds] = useState(false); const [memorializeBirdForm, setMemorializeBirdForm] = useState(emptyMemorializeBirdForm); @@ -2183,6 +2202,8 @@ function App() { const [savingWorkspace, setSavingWorkspace] = useState(false); const [cancelingRescueRequest, setCancelingRescueRequest] = useState(false); const [billingRedirecting, setBillingRedirecting] = useState(false); + const [invitationNotice, setInvitationNotice] = useState<{ sent: boolean; message: string } | null>(null); + const [resendingInvitationId, setResendingInvitationId] = useState(null); const [savingWorkspaceMember, setSavingWorkspaceMember] = useState(false); const [creatingWorkspace, setCreatingWorkspace] = useState(false); const [deletingWorkspace, setDeletingWorkspace] = useState(false); @@ -2264,6 +2285,27 @@ function App() { const [expandedSettingsSection, setExpandedSettingsSection] = useState(null); const flockBirds = useMemo(() => sortBirdsByName([...birds, ...memorializedBirds]), [birds, memorializedBirds]); + const handlePhotoError = usePhotoRefresh({ + apiBaseUrl, token: authToken, workspaceId: workspace?.id, publicProfileCode, + fallback: defaultBirdPhoto, + onPhotos: (photos) => { + const urls = new Map(photos.map((photo) => [photo.id, photo.photoDataUrl])); + const update = (current: Bird[]) => current.map((bird) => urls.has(bird.id) + ? { ...bird, photoDataUrl: urls.get(bird.id) ?? null } : bird); + setBirds(update); + setMemorializedBirds(update); + setPublicProfile((current) => current && urls.has(current.id) + ? { ...current, photoDataUrl: urls.get(current.id) ?? null } : current); + // Renew the editor preview only if it still matches the saved photo. + // Never replace an uploaded/cropped photo or a deliberate removal. + const editingBird = [...birds, ...memorializedBirds].find((bird) => bird.id === editingBirdId); + if (editingBird && urls.has(editingBirdId)) { + setBirdForm((current) => current.photoDataUrl === editingBird.photoDataUrl + ? { ...current, photoDataUrl: urls.get(editingBirdId) ?? '' } : current); + } + }, + }); + const selectedBird = useMemo( () => flockBirds.find((bird) => bird.id === selectedBirdId) ?? null, [flockBirds, selectedBirdId], @@ -3389,7 +3431,7 @@ function App() { }; const handleWorkspaceSwitch = async (workspaceId: number, nextActivePage: AppPage = 'overview') => { - if (!authToken || workspaceId === workspace?.id) { + if (!authToken || switchingWorkspaceId !== null || workspaceId === workspace?.id) { return; } @@ -3841,6 +3883,34 @@ function App() { } }; + useEffect(() => { + setExportBirdId(''); + setFlockExportError(''); + setInvitationNotice(null); + }, [workspace?.id]); + + const handleFlockExport = async () => { + if (exportingFlock) return; + setExportingFlock(true); + setFlockExportError(''); + try { + const response = await apiFetch(`/workspace/export${exportBirdId ? `?birdId=${encodeURIComponent(exportBirdId)}` : ''}`, authToken); + if (!response.ok) throw new Error(await readErrorMessage(response, 'Unable to export flock data.')); + const url = URL.createObjectURL(await response.blob()); + const link = document.createElement('a'); + link.href = url; + link.download = `flockpal-${exportBirdId ? `bird-${exportBirdId}` : `flock-${workspace?.id ?? 'export'}`}-${new Date().toISOString().slice(0, 10)}.json`; + document.body.appendChild(link); + link.click(); + link.remove(); + window.setTimeout(() => URL.revokeObjectURL(url), 60_000); + } catch (exportError) { + setFlockExportError(exportError instanceof Error ? exportError.message : 'Unable to export flock data.'); + } finally { + setExportingFlock(false); + } + }; + const handleBirdImportSubmit = async () => { if (!birdImportPreview || birdImportPreview.errors.length || importingBirds) { return; @@ -4594,7 +4664,7 @@ function App() { }; const handleRemoveBird = async () => { - if (!selectedBird || deletingBird) { + if (!selectedBird || deletingBird || !['owner', 'assistant'].includes(activeMembership?.role ?? '')) { return; } @@ -5506,6 +5576,7 @@ function App() { const handleWorkspaceMemberSubmit = async (event: React.FormEvent) => { event.preventDefault(); setError(''); + setInvitationNotice(null); setSavingWorkspaceMember(true); try { @@ -5519,7 +5590,7 @@ function App() { throw new Error(await readErrorMessage(response, 'Unable to add rescue team member.')); } - const data = (await readJsonSafely<{ member?: WorkspaceMember }>(response)) ?? {}; + const data = (await readJsonSafely<{ member?: WorkspaceMember; invitation?: { sent: boolean; message: string } }>(response)) ?? {}; if (!data.member) { throw new Error('Unable to add rescue team member.'); @@ -5540,6 +5611,7 @@ function App() { return current.map((member) => (member.id === nextMember.id ? nextMember : member)); }); setWorkspaceMemberForm(emptyWorkspaceMemberForm); + setInvitationNotice(data.invitation ?? null); } catch (memberError) { setError(memberError instanceof Error ? memberError.message : 'Unable to add rescue team member.'); } finally { @@ -5547,6 +5619,21 @@ function App() { } }; + const handleResendInvitation = async (memberId: string) => { + setResendingInvitationId(memberId); + setInvitationNotice(null); + try { + const response = await apiFetch(`/workspace/members/${memberId}/invitation`, authToken, { method: 'POST' }); + if (!response.ok) throw new Error(await readErrorMessage(response, 'Unable to resend invitation.')); + const data = await response.json() as { invitation: { sent: boolean; message: string } }; + setInvitationNotice(data.invitation); + } catch (error) { + setInvitationNotice({ sent: false, message: error instanceof Error ? error.message : 'Unable to resend invitation.' }); + } finally { + setResendingInvitationId(null); + } + }; + const handleUpdateWorkspaceMemberRole = async (memberId: string, role: WorkspaceRole) => { setError(''); setUpdatingWorkspaceMemberId(memberId); @@ -5633,7 +5720,7 @@ function App() { if (shouldShowPublicProfilePage) { return ( -
+
FlockPal @@ -5830,7 +5917,7 @@ function App() { if (loading) { return ( -
+

Loading flock data...

@@ -5941,12 +6028,21 @@ function App() { ); return ( -
+
FlockPal
-

Removing only takes this bird out of your flock. Its profile, photo, notes, and care history are retained and can be brought into a flock later using its exact band ID.

+

Only Owners and Assistants can remove birds. Removing only takes this bird out of your flock. Its profile, photo, notes, and care history are retained and can be brought into a flock later using its exact band ID.

-
@@ -8512,9 +8588,26 @@ function App() { {expandedSettingsSection === 'collaborators' ? ( <>

- Invite other people to help manage this flock. Rescue flocks support teams, and household flocks can also support - co-caregivers without changing who owns the billing. + Give someone access to this flock using their email address. Their role applies to every bird in this flock, + including memorialized birds. Every role can download flock data. Sharing access does not change the billing owner.

+
+ Compare shared flock roles +
+ {(['viewer', 'caregiver', 'assistant', 'owner'] as const).map((role) => ( +
+ {workspaceRoleLabels[role]} +

{workspaceRoleDescriptions[role]}

+
+ ))} +
+

+ Memorialized bird records remain read-only. Editing also depends on the flock’s subscription or rescue verification status. +

+
+ {invitationNotice ? ( +

{invitationNotice.message}

+ ) : null}
+

+ {workspaceRoleDescriptions[workspaceMemberForm.role]} +

@@ -8583,6 +8680,7 @@ function App() { Role +

+ {workspaceRoleDescriptions[member.role]} +

+ {['owner', 'assistant'].includes(activeMembership?.role ?? '') ? ( + + ) : null} + + {flockExportError ?

{flockExportError}

: null} +

Bulk import

Import the first worksheet from an Excel file. Use one row per weight entry and repeat the Bird Name for rows that belong to the same profile. diff --git a/frontend/src/FlockSwitcher.tsx b/frontend/src/FlockSwitcher.tsx new file mode 100644 index 0000000..6cfa200 --- /dev/null +++ b/frontend/src/FlockSwitcher.tsx @@ -0,0 +1,68 @@ +import { useEffect, useRef, useState } from 'react'; + +type FlockEntry = { workspace: { id: number; name: string }; membership: { role: string } }; +const roleName = (role: string) => role.charAt(0).toUpperCase() + role.slice(1); + +export function FlockSwitcher({ entries, currentId, switching, disabled, onSwitch }: { + entries: FlockEntry[]; currentId?: number; switching: boolean; disabled: boolean; onSwitch: (id: number) => void; +}) { + const [open, setOpen] = useState(false); + const container = useRef(null); + const trigger = useRef(null); + const current = entries.find((entry) => entry.workspace.id === currentId); + + useEffect(() => { setOpen(false); }, [currentId, disabled]); + useEffect(() => { + if (!open) return; + const closeOutside = (event: PointerEvent) => { + if (!container.current?.contains(event.target as Node)) setOpen(false); + }; + document.addEventListener('pointerdown', closeOutside); + return () => document.removeEventListener('pointerdown', closeOutside); + }, [open]); + + return ( +

{ if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false); }} + onKeyDown={(event) => { + if (event.key === 'Escape' && open) { + event.preventDefault(); + setOpen(false); + trigger.current?.focus(); + } + }}> + Current flock + + {switching ? 'Switching flocks…' : ''} + {open ? ( +
+

Switch flock

+ {[ + { label: 'My flocks', items: entries.filter((entry) => entry.membership.role === 'owner') }, + { label: 'Shared with me', items: entries.filter((entry) => entry.membership.role !== 'owner') }, + ].filter((group) => group.items.length).map((group) => ( +
+

{group.label}

+ {group.items.map((entry) => ( + + ))} +
+ ))} +
+ ) : null} +
+ ); +} diff --git a/frontend/src/index.css b/frontend/src/index.css index 1b96c7b..3adad7c 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -216,6 +216,7 @@ textarea { } .side-rail { + z-index: 30; position: sticky; top: 2rem; display: grid; @@ -856,33 +857,77 @@ textarea { .workspace-switcher { display: grid; - gap: 0.9rem; + gap: 0.45rem; + min-width: 0; + padding-bottom: 1rem; + border-bottom: 1px solid rgba(39, 105, 179, 0.16); } -.workspace-switcher-item small { +.workspace-switcher-label { color: var(--muted); + font-size: 0.78rem; + font-weight: 700; + letter-spacing: 0.06em; + text-transform: uppercase; } -.workspace-switcher-list { - display: grid; - gap: 0.75rem; -} +.workspace-switcher { position: relative; } -.workspace-switcher-item { +.flock-switcher-trigger { + display: flex; + align-items: center; + gap: 0.7rem; width: 100%; + min-width: 0; + padding: 0.8rem; + color: var(--ink); text-align: left; - border: 1px solid rgba(39, 105, 179, 0.12); - border-radius: 18px; - padding: 0.85rem 0.95rem; - background: rgba(255, 255, 255, 0.58); - display: grid; - gap: 0.2rem; + background: rgba(255, 255, 255, 0.65); + border: 1px solid var(--panel-border); + border-radius: 16px; + box-shadow: 0 3px 10px rgba(53, 90, 66, 0.05); } -.workspace-switcher-item.active { - background: linear-gradient(135deg, rgba(203, 58, 53, 0.16), rgba(39, 105, 179, 0.18)); - border-color: rgba(39, 105, 179, 0.24); +.flock-switcher-trigger:hover:not(:disabled) { background: #fffaf0; border-color: var(--accent-green); } +.flock-switcher-trigger:focus-visible, .flock-switcher-option:focus-visible { outline: 2px solid var(--accent-green); outline-offset: 3px; } +.flock-switcher-avatar { + display: grid; + place-items: center; + flex: 0 0 36px; + height: 36px; + border-radius: 11px; + background: #e1eee2; + color: #276b48; + font-weight: 800; } +.flock-switcher-copy { display: grid; gap: 0.15rem; min-width: 0; flex: 1; } +.flock-switcher-copy strong { font-size: 0.95rem; line-height: 1.35; overflow-wrap: anywhere; } +.flock-switcher-copy small { color: var(--muted); font-size: 0.76rem; font-weight: 400; } +.flock-switcher-chevron { flex-shrink: 0; color: var(--muted); } +.flock-switcher-chevron.is-open { transform: rotate(180deg); } +.flock-switcher-status:empty { display: none; } +.flock-switcher-status { color: var(--muted); font-size: 0.78rem; } +.flock-switcher-options { + position: absolute; + top: calc(100% - 0.5rem); + left: 0; + z-index: 50; + width: max(100%, 280px); + max-width: calc(100vw - 3rem); + max-height: min(420px, 60dvh); + overflow-y: auto; + padding: 0.65rem; + border: 1px solid var(--panel-border); + border-radius: 18px; + background: #fffaf1; + box-shadow: 0 18px 45px rgba(35, 65, 45, 0.2); +} +.flock-switcher-heading { margin: 0; padding: 0.35rem 0.5rem 0.6rem; font-size: 0.9rem; font-weight: 700; } +.flock-switcher-group + .flock-switcher-group { border-top: 1px solid var(--panel-border); margin-top: 0.5rem; padding-top: 0.35rem; } +.flock-switcher-group > p { margin: 0; padding: 0.4rem 0.5rem; color: var(--muted); font-size: 0.72rem; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; } +.flock-switcher-option { display: flex; align-items: center; gap: 0.7rem; width: 100%; min-height: 54px; padding: 0.65rem; border: 0; border-radius: 11px; background: transparent; color: var(--ink); text-align: left; } +.flock-switcher-option:hover, .flock-switcher-option[aria-current="true"] { background: #e8f1e7; } +.flock-switcher-check { color: #276b48; font-weight: 800; } .integration-token-secret { gap: 0.75rem; @@ -2623,25 +2668,12 @@ label { .workspace-switcher { grid-column: 1 / -1; - gap: 0.5rem; + gap: 0.4rem; + padding-bottom: 0.65rem; } - .workspace-switcher-list { - display: flex; - gap: 0.45rem; - overflow-x: auto; - padding-bottom: 0.1rem; - } - .workspace-switcher-item { - min-width: 160px; - padding: 0.55rem 0.7rem; - border-radius: 14px; - } - .workspace-switcher-item small { - display: none; - } } @media (max-width: 720px) { @@ -2787,17 +2819,7 @@ label { gap: 0.4rem; } - .workspace-switcher-list { - margin: 0 -0.2rem; - padding: 0 0.2rem 0.2rem; - } - .workspace-switcher-item { - min-width: min(180px, 78vw); - padding: 0.5rem 0.65rem; - border-radius: 999px; - font-size: 0.86rem; - } .top-alert-notification { gap: 0.65rem; diff --git a/frontend/src/photoRefresh.ts b/frontend/src/photoRefresh.ts new file mode 100644 index 0000000..f8dc9a1 --- /dev/null +++ b/frontend/src/photoRefresh.ts @@ -0,0 +1,36 @@ +export type PhotoRecord = { id: string; photoDataUrl: string | null }; +export const PHOTO_REFRESH_INTERVAL_MS = 5 * 60_000; + +// One request for all mounted photos; throttle failures without blocking later recovery. +export function createPhotoRefresher({ load, apply, now = Date.now }: { + load: (signal: AbortSignal) => Promise; + apply: (photos: PhotoRecord[]) => void; + now?: () => number; +}) { + const controller = new AbortController(); + let inFlight = false; + let lastAttempt = -Infinity; + return { + async refresh() { + if (controller.signal.aborted || inFlight || now() - lastAttempt < 30_000) return; + inFlight = true; + lastAttempt = now(); + try { + const photos = await load(controller.signal); + if (!controller.signal.aborted) apply(photos); + } catch { + // Keep existing photos on transient failures; retry on the next focus/timer/error. + } finally { + inFlight = false; + } + }, + dispose() { controller.abort(); }, + }; +} + +export function isExpiringPhotoUrl(src: string) { + try { + const url = new URL(src, window.location.href); + return /\/birds\/[^/]+\/photo$/.test(url.pathname) && url.searchParams.has('token'); + } catch { return false; } +} diff --git a/frontend/src/usePhotoRefresh.ts b/frontend/src/usePhotoRefresh.ts new file mode 100644 index 0000000..bd9033e --- /dev/null +++ b/frontend/src/usePhotoRefresh.ts @@ -0,0 +1,50 @@ +import { useEffect, useRef, type SyntheticEvent } from 'react'; +import { createPhotoRefresher, isExpiringPhotoUrl, PHOTO_REFRESH_INTERVAL_MS, type PhotoRecord } from './photoRefresh'; + +export function usePhotoRefresh({ apiBaseUrl, token, workspaceId, publicProfileCode, onPhotos, fallback }: { + apiBaseUrl: string; token: string; workspaceId?: number; publicProfileCode: string; + onPhotos: (photos: PhotoRecord[]) => void; fallback: string; +}) { + const apply = useRef(onPhotos); + apply.current = onPhotos; + const refresh = useRef<(() => Promise) | null>(null); + useEffect(() => { + if (!publicProfileCode && (!token || !workspaceId)) return; + const refresher = createPhotoRefresher({ + load: async (signal) => { + const path = publicProfileCode ? `/public/birds/${encodeURIComponent(publicProfileCode)}` : '/birds'; + const response = await fetch(`${apiBaseUrl}${path}`, { + signal, cache: 'no-store', + headers: publicProfileCode ? {} : { Authorization: `Bearer ${token}` }, + }); + if (!response.ok) throw new Error('Unable to refresh photos.'); + const data = await response.json(); + return publicProfileCode ? (data.bird ? [data.bird] : []) : [...(data.birds ?? []), ...(data.memorializedBirds ?? [])]; + }, + apply: (photos) => apply.current(photos), + }); + refresh.current = refresher.refresh; + const onResume = () => { if (document.visibilityState === 'visible') void refresher.refresh(); }; + const timer = window.setInterval(onResume, PHOTO_REFRESH_INTERVAL_MS); + window.addEventListener('focus', onResume); + window.addEventListener('online', onResume); + document.addEventListener('visibilitychange', onResume); + return () => { + refresher.dispose(); + refresh.current = null; + window.clearInterval(timer); + window.removeEventListener('focus', onResume); + window.removeEventListener('online', onResume); + document.removeEventListener('visibilitychange', onResume); + }; + }, [apiBaseUrl, token, workspaceId, publicProfileCode]); + + return (event: SyntheticEvent) => { + const image = event.target; + if (!(image instanceof Element)) return; + const attribute = image.localName === 'img' ? 'src' : image.localName === 'image' ? 'href' : null; + if (!attribute || !isExpiringPhotoUrl(image.getAttribute(attribute) ?? '')) return; + image.setAttribute(attribute, fallback); + void refresh.current?.(); + }; +} diff --git a/frontend/test/photoRefresh.test.ts b/frontend/test/photoRefresh.test.ts new file mode 100644 index 0000000..f44fb38 --- /dev/null +++ b/frontend/test/photoRefresh.test.ts @@ -0,0 +1,60 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createPhotoRefresher } from '../src/photoRefresh.ts'; + +test('simultaneous image errors share a refresh, then can renew again after cooldown', async () => { + let now = 0; + let calls = 0; + let finish!: (photos: { id: string; photoDataUrl: string }[]) => void; + const applied: unknown[] = []; + const refresher = createPhotoRefresher({ + now: () => now, + load: async () => { calls++; return new Promise((resolve) => { finish = resolve; }); }, + apply: (photos) => applied.push(photos), + }); + const first = refresher.refresh(); + await refresher.refresh(); + assert.equal(calls, 1); + finish([{ id: 'bird', photoDataUrl: 'renewed' }]); + await first; + assert.equal(applied.length, 1); + await refresher.refresh(); + assert.equal(calls, 1); + now = 30_000; + const next = refresher.refresh(); + finish([]); + await next; + assert.equal(calls, 2); +}); + +test('logout or flock switching aborts requests and discards stale photo responses', async () => { + let finish!: (photos: { id: string; photoDataUrl: string }[]) => void; + let signal!: AbortSignal; + let applied = false; + const refresher = createPhotoRefresher({ + load: async (requestSignal) => { signal = requestSignal; return new Promise((resolve) => { finish = resolve; }); }, + apply: () => { applied = true; }, + }); + const pending = refresher.refresh(); + refresher.dispose(); + finish([{ id: 'old-flock-bird', photoDataUrl: 'stale' }]); + await pending; + assert.equal(signal.aborted, true); + assert.equal(applied, false); +}); + +test('a failed refresh can recover on a later timer, focus, or reconnect', async () => { + let now = 0; + let attempts = 0; + let applied = false; + const refresher = createPhotoRefresher({ + now: () => now, + load: async () => { if (++attempts === 1) throw new Error('offline'); return []; }, + apply: () => { applied = true; }, + }); + await refresher.refresh(); + assert.equal(applied, false); + now = 30_000; + await refresher.refresh(); + assert.equal(applied, true); +});