Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | 2x 2x 2x 2x 2x 2x 5x 5x 5x 1x 4x 4x 5x 67x 67x 1x 66x 1x 65x 65x 65x 2x 63x 1x 62x 1x 1x 61x 61x 1x 1x 60x 60x 60x 1x 1x 1x 59x 59x 1x 58x 58x 4x 4x 2x 2x 2x 6x 5x 1x 1x 4x 4x 3x 1x 1x 2x 1x 1x 1x 7x 7x 1x 6x 2x 4x 3x 1x 1x 4x 4x 4x 2x 2x 2x | // Sharing flats: the logic behind the server functions in functions.ts, with
// its dependencies passed in so Workers tests can drive it (openspec:
// sharing).
import { PROPERTY_LIMIT } from '#/features/properties/properties.server'
import type { PropertyRepository } from '#/features/properties/property.repository.server'
import type { AlertReason, FieldReason } from '#/lib/reasons'
import type { Locale } from '#/paraglide/runtime.js'
import type { PropertyRole } from '#/server/db/schema'
import { EmailError, type SendEmail } from '#/server/email/email'
import type { Logger } from '#/server/log/log'
import type { LimitResult, LimitRule } from '#/server/platform/limits.server'
import { INVITATION_VALID_DAYS, invitationEmail } from './invitation-email'
import type {
PendingInvitation,
ReceivedInvitation,
SharingRepository,
} from './sharing.repository.server'
export interface SharingDeps {
/** The signed-in user. */
user: { id: string; email: string; name: string }
sharing: SharingRepository
properties: PropertyRepository
sendEmail: SendEmail
log: Logger
now: () => Date
consumeLimit: (key: string, rule: LimitRule) => Promise<LimitResult>
/** The inviter's language, for an invitee without an account. */
locale: Locale
/** The app's origin, for the link in the invitation email. */
appUrl: string
}
/** Spec: "Limiting invitations". */
export const INVITATION_LIMITS = {
pendingPerProperty: 10,
perUserPerDay: { windowSeconds: 24 * 60 * 60, max: 20 },
} as const
const DAY_MS = 24 * 60 * 60 * 1000
const EMAIL_REASONS = {
quota: 'invitation_email_quota',
rate_limited: 'email_busy',
rejected: 'invitation_email_failed',
unavailable: 'invitation_email_failed',
} as const satisfies Record<EmailError['failure'], AlertReason>
interface Failure<R extends FieldReason | AlertReason = AlertReason> {
ok: false
reason: R
}
const propertyNotFound = {
ok: false,
reason: 'property_not_found',
} as const satisfies Failure
const ownerOnly = {
ok: false,
reason: 'sharing_owner_only',
} as const satisfies Failure
const invitationNotFound = {
ok: false,
reason: 'invitation_not_found',
} as const satisfies Failure
export interface SharingView {
property: { id: string; streetAddress: string }
/** The signed-in user's role. */
role: PropertyRole
people: {
userId: string
name: string
role: PropertyRole
since: Date
isYou: boolean
}[]
invitations: PendingInvitation[]
}
/** The flat's Sharing page: who has access and who is invited. */
export async function getSharing(
deps: SharingDeps,
propertyId: string,
): Promise<({ ok: true } & SharingView) | typeof propertyNotFound> {
const property = await deps.properties.findForUser(deps.user.id, propertyId)
const role = await deps.sharing.roleOf(deps.user.id, propertyId)
if (!property || !role) {
return propertyNotFound
}
const [people, invitations] = await Promise.all([
deps.sharing.listPeople(propertyId),
deps.sharing.listPending(propertyId, deps.now()),
])
return {
ok: true,
property: { id: property.id, streetAddress: property.streetAddress },
role,
people: people.map((p) => ({ ...p, isYou: p.userId === deps.user.id })),
invitations,
}
}
/** `email` is already validated and normalised (schemas.ts). */
export async function inviteToProperty(
deps: SharingDeps,
propertyId: string,
email: string,
): Promise<
| { ok: true; id: string }
| Failure<
| AlertReason
| Extract<
FieldReason,
'invitation_already_member' | 'invitation_already_pending'
>
>
> {
const role = await deps.sharing.roleOf(deps.user.id, propertyId)
if (!role) {
return propertyNotFound
}
if (role !== 'owner') {
return ownerOnly
}
const now = deps.now()
// One query whether or not the address has an account (design decision 5).
const recipient = await deps.sharing.findRecipient(propertyId, email)
if (recipient.hasAccess) {
return { ok: false, reason: 'invitation_already_member' }
}
if (await deps.sharing.isPending(propertyId, email, now)) {
return { ok: false, reason: 'invitation_already_pending' }
}
if (
(await deps.sharing.countPending(propertyId, now)) >=
INVITATION_LIMITS.pendingPerProperty
) {
deps.log.warn('sharing.invitation_limit_reached', { limit: 'property' })
return { ok: false, reason: 'invitation_limit_reached' }
}
// Counted before sending, so a failed send uses a slot too: retrying while
// Resend fails can't spend the free plan's 100 emails a day.
const daily = await deps.consumeLimit(
`invite-user:${deps.user.id}`,
INVITATION_LIMITS.perUserPerDay,
)
if (!daily.allowed) {
deps.log.warn('sharing.invitation_limit_reached', { limit: 'daily' })
return { ok: false, reason: 'invitation_daily_limit_reached' }
}
// Sent before it is saved, so a failed send leaves no invitation.
const id = crypto.randomUUID()
try {
await deps.sendEmail(
invitationEmail({
to: email,
inviterName: deps.user.name || deps.user.email,
inviterEmail: deps.user.email,
appUrl: deps.appUrl,
locale: recipient.locale ?? deps.locale,
invitationId: id,
}),
)
} catch (error) {
Eif (error instanceof EmailError) {
deps.log.error(
'sharing.invitation_email_failed',
{ failure: error.failure },
error,
)
return { ok: false, reason: EMAIL_REASONS[error.failure] }
}
throw error
}
const saved = await deps.sharing.invite({
id,
propertyId,
email,
invitedBy: deps.user.id,
now,
expiresAt: new Date(now.getTime() + INVITATION_VALID_DAYS * DAY_MS),
})
if (!saved) {
// Another invitation to the address was saved after the isPending check
// (two tabs, two owners). Its email went out too; the button in both
// leads to the app, where the saved one is waiting.
return { ok: false, reason: 'invitation_already_pending' }
}
deps.log.info('sharing.invitation_sent', { propertyId, invitationId: id })
return { ok: true, id }
}
export async function cancelInvitation(
deps: SharingDeps,
invitationId: string,
): Promise<{ ok: true } | typeof invitationNotFound> {
const propertyId = await deps.sharing.cancel(deps.user.id, invitationId)
if (propertyId === undefined) {
return invitationNotFound
}
deps.log.info('sharing.invitation_cancelled', { propertyId, invitationId })
return { ok: true }
}
/** The signed-in user's pending invitations, for the flats list. */
export function listMyInvitations(
deps: SharingDeps,
): Promise<ReceivedInvitation[]> {
return deps.sharing.listForInvitee(deps.user.email, deps.now())
}
/**
* Accepts an invitation for the signed-in user's own address. Counts toward
* the flat limit like adding a flat (the count and the insert are separate
* statements, as there).
*/
export async function acceptInvitation(
deps: SharingDeps,
invitationId: string,
): Promise<
| { ok: true; propertyId: string }
| typeof invitationNotFound
| Failure<'property_limit_reached'>
> {
if ((await deps.properties.countForUser(deps.user.id)) >= PROPERTY_LIMIT) {
deps.log.warn('property.limit_reached', { limit: PROPERTY_LIMIT })
return { ok: false, reason: 'property_limit_reached' }
}
const propertyId = await deps.sharing.accept(
deps.user.id,
deps.user.email,
invitationId,
deps.now(),
)
if (propertyId === undefined) {
return invitationNotFound
}
deps.log.info('sharing.invitation_accepted', { propertyId, invitationId })
return { ok: true, propertyId }
}
export async function declineInvitation(
deps: SharingDeps,
invitationId: string,
): Promise<{ ok: true } | typeof invitationNotFound> {
if (!(await deps.sharing.decline(deps.user.email, invitationId))) {
return invitationNotFound
}
deps.log.info('sharing.invitation_declined', { invitationId })
return { ok: true }
}
/** The owner removes a member's access. */
export async function removeAccess(
deps: SharingDeps,
propertyId: string,
userId: string,
): Promise<{ ok: true } | typeof propertyNotFound | typeof ownerOnly> {
const role = await deps.sharing.roleOf(deps.user.id, propertyId)
if (!role) {
return propertyNotFound
}
if (role !== 'owner') {
return ownerOnly
}
if (!(await deps.sharing.removeMember(deps.user.id, propertyId, userId))) {
// Already gone (left, or removed in another tab): the outcome the owner
// asked for. An owner's own access can't be removed.
return (await deps.sharing.roleOf(userId, propertyId))
? ownerOnly
: { ok: true }
}
deps.log.info('sharing.access_removed', {
propertyId,
removedUserId: userId,
})
return { ok: true }
}
/** A member leaves a flat. The owner can't. */
export async function leaveProperty(
deps: SharingDeps,
propertyId: string,
): Promise<{ ok: true } | typeof propertyNotFound | typeof ownerOnly> {
const role = await deps.sharing.roleOf(deps.user.id, propertyId)
Iif (!role) {
return propertyNotFound
}
if (
role !== 'member' ||
!(await deps.sharing.leave(deps.user.id, propertyId))
) {
return ownerOnly
}
deps.log.info('sharing.property_left', { propertyId })
return { ok: true }
}
|