|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#30205] A banned user's open work: how much of it there is, and one |
| 5 | + * optional bulk hand-over to someone else. |
| 6 | + * |
| 7 | + * Banning a user signs them out and keeps them out, but the records they own |
| 8 | + * and the records assigned to them stay where they were, and nobody is told. |
| 9 | + * This module answers the two questions an administrator has at that moment — |
| 10 | + * "how many records does this person hold?" and "hand them to someone" — and |
| 11 | + * the predicate the write path uses to stop new work landing on a banned user. |
| 12 | + * |
| 13 | + * ## Which records count |
| 14 | + * |
| 15 | + * Every business object's user reference: a field whose target is |
| 16 | + * {@link USER_OBJECT} (a `user` field, or a `lookup` to it). That includes the |
| 17 | + * platform's `owner_id`, which is itself a lookup to the user object, and the |
| 18 | + * app's own fields such as an `assignee`. Left out, on purpose: |
| 19 | + * |
| 20 | + * - `readonly` and `system` fields: `created_by` / `updated_by` record who did |
| 21 | + * something, not who holds the work, and moving them would rewrite history. |
| 22 | + * - platform tables (`sys_*`) and `managedBy` objects: `sys_user_permission_set.user_id` |
| 23 | + * is a grant, not work, and moving it would move the person's permissions. |
| 24 | + * - a column the platform registers but provisions no storage for (an injected |
| 25 | + * anchor on a federated object, `unprovisionedInjectedColumns`). |
| 26 | + * |
| 27 | + * A multi-valued user field is counted (any member names the user) but never |
| 28 | + * transferred: replacing one member of a list is a different edit from |
| 29 | + * reassigning a record, and the answer says `transferable: false`. |
| 30 | + * |
| 31 | + * ## Whose reads and writes |
| 32 | + * |
| 33 | + * The CALLER's. Every count and every row read runs under the caller's own |
| 34 | + * context, so RBAC, row-level security and sharing decide what is counted — |
| 35 | + * "across the objects the administrator can read" — and an object the caller |
| 36 | + * cannot read is named in `unreadable` instead of being reported as zero. |
| 37 | + * Every transfer write is an ordinary `update` under the same context, so |
| 38 | + * sharing, validation rules and hooks apply to each row as they would to a |
| 39 | + * hand edit, and a row the caller may not change is reported as a failure. |
| 40 | + * Nothing here elevates except reading the TARGET user's ban state, which is |
| 41 | + * a fact about the user and not about the caller's visibility (see |
| 42 | + * {@link isUserBanInForce}). |
| 43 | + * |
| 44 | + * ## Bounded, repeatable, never in the ban's way |
| 45 | + * |
| 46 | + * At most {@link USER_ASSIGNED_WORK_FIELD_CAP} (object, field) pairs are |
| 47 | + * counted, and the answer says `truncated` past that. One transfer call moves |
| 48 | + * at most {@link USER_WORK_TRANSFER_ROW_CAP} rows and answers how many still |
| 49 | + * name the user (`remaining`), so a caller repeats it until that is zero. The |
| 50 | + * ban itself neither waits for nor depends on any of this: a ban can be urgent. |
| 51 | + */ |
| 52 | + |
| 53 | +import { referenceTargetOf, unprovisionedInjectedColumns } from '@objectstack/spec/data'; |
| 54 | + |
| 55 | +/** The platform user object every user reference targets. */ |
| 56 | +const USER_OBJECT = 'sys_user'; |
| 57 | + |
| 58 | +/** At most this many (object, field) pairs are counted in one answer. */ |
| 59 | +export const USER_ASSIGNED_WORK_FIELD_CAP = 200; |
| 60 | + |
| 61 | +/** At most this many rows are moved by one transfer call. */ |
| 62 | +export const USER_WORK_TRANSFER_ROW_CAP = 500; |
| 63 | + |
| 64 | +/** At most this many failed rows are described per (object, field) pair. */ |
| 65 | +export const USER_WORK_FAILURE_SAMPLE = 10; |
| 66 | + |
| 67 | +/** |
| 68 | + * Is this user row's ban in force? |
| 69 | + * |
| 70 | + * `banned` is `true` and the ban has no expiry, or one still in the future. |
| 71 | + * better-auth leaves `banned` true past `ban_expires` until the user's next |
| 72 | + * sign-in clears it, and such a user CAN sign in again, so an expired ban is |
| 73 | + * not in force. A row that is not an object, or has no `banned: true`, is not |
| 74 | + * banned. |
| 75 | + */ |
| 76 | +export function isUserBanInForce(row: unknown, now: number = Date.now()): boolean { |
| 77 | + if (!row || typeof row !== 'object') return false; |
| 78 | + const { banned, ban_expires: expires } = row as { banned?: unknown; ban_expires?: unknown }; |
| 79 | + if (banned !== true) return false; |
| 80 | + if (expires === null || expires === undefined || expires === '') return true; |
| 81 | + const at = expires instanceof Date ? expires.getTime() : new Date(expires as string | number).getTime(); |
| 82 | + // An expiry that does not parse cannot prove the ban lifted. |
| 83 | + if (Number.isNaN(at)) return true; |
| 84 | + return at > now; |
| 85 | +} |
| 86 | + |
| 87 | +/** One user reference a record can hold work through. */ |
| 88 | +export interface UserAssignedWorkField { |
| 89 | + object: string; |
| 90 | + field: string; |
| 91 | + /** A multi-valued user field: counted, never transferred. */ |
| 92 | + multiple: boolean; |
| 93 | +} |
| 94 | + |
| 95 | +interface ObjectLike { |
| 96 | + name?: unknown; |
| 97 | + managedBy?: unknown; |
| 98 | + fields?: unknown; |
| 99 | +} |
| 100 | + |
| 101 | +/** |
| 102 | + * The user references the records of `objects` hold work through, in |
| 103 | + * declaration order, and whether the cap cut the list short. |
| 104 | + */ |
| 105 | +export function userAssignedWorkFields( |
| 106 | + objects: Iterable<unknown>, |
| 107 | + cap: number = USER_ASSIGNED_WORK_FIELD_CAP, |
| 108 | +): { fields: UserAssignedWorkField[]; truncated: boolean } { |
| 109 | + const fields: UserAssignedWorkField[] = []; |
| 110 | + for (const candidate of objects) { |
| 111 | + const obj = candidate as ObjectLike; |
| 112 | + const name = typeof obj?.name === 'string' ? obj.name : undefined; |
| 113 | + if (!name || name.startsWith('sys_')) continue; |
| 114 | + if (obj.managedBy !== undefined && obj.managedBy !== null) continue; |
| 115 | + if (!obj.fields || typeof obj.fields !== 'object') continue; |
| 116 | + const phantom = new Set(unprovisionedInjectedColumns(obj as any)); |
| 117 | + for (const [field, def] of Object.entries(obj.fields as Record<string, unknown>)) { |
| 118 | + if (phantom.has(field)) continue; |
| 119 | + if (referenceTargetOf(def) !== USER_OBJECT) continue; |
| 120 | + const d = def as { readonly?: unknown; system?: unknown; multiple?: unknown }; |
| 121 | + if (d.readonly === true || d.system === true) continue; |
| 122 | + if (fields.length >= cap) return { fields, truncated: true }; |
| 123 | + fields.push({ object: name, field, multiple: d.multiple === true }); |
| 124 | + } |
| 125 | + } |
| 126 | + return { fields, truncated: false }; |
| 127 | +} |
| 128 | + |
| 129 | +/** |
| 130 | + * The slice of the data engine this module reads and writes through — the |
| 131 | + * engine's own public methods, so every call takes the ordinary path. |
| 132 | + */ |
| 133 | +export interface UserWorkEngine { |
| 134 | + getConfigs(): Record<string, unknown>; |
| 135 | + count(object: string, query?: any): Promise<number>; |
| 136 | + find(object: string, query?: any): Promise<any[]>; |
| 137 | + update(object: string, data: any, options?: any): Promise<unknown>; |
| 138 | +} |
| 139 | + |
| 140 | +/** The filter that matches the records a field holds `userId` in. */ |
| 141 | +function holdsUser(ref: UserAssignedWorkField, userId: string): Record<string, unknown> { |
| 142 | + return { [ref.field]: ref.multiple ? { $contains: userId } : userId }; |
| 143 | +} |
| 144 | + |
| 145 | +/** One (object, field) pair's count. */ |
| 146 | +export interface UserAssignedWorkCount { |
| 147 | + object: string; |
| 148 | + field: string; |
| 149 | + count: number; |
| 150 | + transferable: boolean; |
| 151 | +} |
| 152 | + |
| 153 | +/** What {@link countUserAssignedWork} answers. */ |
| 154 | +export interface UserAssignedWorkSummary { |
| 155 | + userId: string; |
| 156 | + /** Every pair with at least one record, in declaration order. */ |
| 157 | + objects: UserAssignedWorkCount[]; |
| 158 | + /** The sum of `objects[].count`: record-field holdings, not distinct records. */ |
| 159 | + total: number; |
| 160 | + /** More pairs exist than were counted. */ |
| 161 | + truncated: boolean; |
| 162 | + /** Objects whose count the caller's read refused or could not run. */ |
| 163 | + unreadable: string[]; |
| 164 | +} |
| 165 | + |
| 166 | +/** Per-pair counts of the records that hold `userId`, read as the caller. */ |
| 167 | +export async function countUserAssignedWork( |
| 168 | + engine: UserWorkEngine, |
| 169 | + userId: string, |
| 170 | + context: unknown, |
| 171 | +): Promise<UserAssignedWorkSummary> { |
| 172 | + const { fields, truncated } = userAssignedWorkFields(Object.values(engine.getConfigs() ?? {})); |
| 173 | + const objects: UserAssignedWorkCount[] = []; |
| 174 | + const unreadable = new Set<string>(); |
| 175 | + let total = 0; |
| 176 | + for (const ref of fields) { |
| 177 | + if (unreadable.has(ref.object)) continue; |
| 178 | + let count: number; |
| 179 | + try { |
| 180 | + count = await engine.count(ref.object, { where: holdsUser(ref, userId), context }); |
| 181 | + } catch { |
| 182 | + unreadable.add(ref.object); |
| 183 | + continue; |
| 184 | + } |
| 185 | + if (!(count > 0)) continue; |
| 186 | + objects.push({ object: ref.object, field: ref.field, count, transferable: !ref.multiple }); |
| 187 | + total += count; |
| 188 | + } |
| 189 | + return { userId, objects, total, truncated, unreadable: [...unreadable] }; |
| 190 | +} |
| 191 | + |
| 192 | +/** A refusal of the transfer as a whole, before any row moves. */ |
| 193 | +export class UserWorkTransferRefusal extends Error { |
| 194 | + constructor( |
| 195 | + readonly status: number, |
| 196 | + readonly code: 'VALIDATION_ERROR' | 'RESOURCE_NOT_FOUND', |
| 197 | + message: string, |
| 198 | + readonly field?: { field: string; code: 'reference_not_found' | 'reference_user_banned' }, |
| 199 | + ) { |
| 200 | + super(message); |
| 201 | + this.name = 'UserWorkTransferRefusal'; |
| 202 | + } |
| 203 | +} |
| 204 | + |
| 205 | +/** One row a transfer could not move. */ |
| 206 | +export interface UserWorkTransferFailure { |
| 207 | + id: string; |
| 208 | + code: string; |
| 209 | + message: string; |
| 210 | +} |
| 211 | + |
| 212 | +/** One (object, field) pair's transfer outcome. */ |
| 213 | +export interface UserWorkTransferOutcome { |
| 214 | + object: string; |
| 215 | + field: string; |
| 216 | + updated: number; |
| 217 | + failed: number; |
| 218 | + /** The first {@link USER_WORK_FAILURE_SAMPLE} failures. */ |
| 219 | + failures: UserWorkTransferFailure[]; |
| 220 | +} |
| 221 | + |
| 222 | +/** What {@link transferUserAssignedWork} answers. */ |
| 223 | +export interface UserWorkTransferReport { |
| 224 | + fromUserId: string; |
| 225 | + toUserId: string; |
| 226 | + objects: UserWorkTransferOutcome[]; |
| 227 | + updated: number; |
| 228 | + failed: number; |
| 229 | + /** Records the caller can read that still hold the user in a transferable field. */ |
| 230 | + remaining: number; |
| 231 | +} |
| 232 | + |
| 233 | +function failureOf(id: unknown, err: unknown): UserWorkTransferFailure { |
| 234 | + const e = err as { code?: unknown; message?: unknown } | null; |
| 235 | + return { |
| 236 | + id: String(id), |
| 237 | + code: typeof e?.code === 'string' && e.code.length > 0 ? e.code : 'UPDATE_FAILED', |
| 238 | + message: String(e?.message ?? err).slice(0, 500), |
| 239 | + }; |
| 240 | +} |
| 241 | + |
| 242 | +/** |
| 243 | + * Move up to {@link USER_WORK_TRANSFER_ROW_CAP} records from `fromUserId` to |
| 244 | + * `toUserId`, field by field, each as an ordinary update under the caller's |
| 245 | + * context. `objects`, when given, limits the transfer to those object names. |
| 246 | + * |
| 247 | + * Refuses before any write when the target is the source, names no user, or |
| 248 | + * names a user whose ban is in force ({@link UserWorkTransferRefusal}). |
| 249 | + */ |
| 250 | +export async function transferUserAssignedWork( |
| 251 | + engine: UserWorkEngine, |
| 252 | + fromUserId: string, |
| 253 | + toUserId: string, |
| 254 | + context: unknown, |
| 255 | + options: { objects?: readonly string[]; rowCap?: number } = {}, |
| 256 | +): Promise<UserWorkTransferReport> { |
| 257 | + if (fromUserId === toUserId) { |
| 258 | + throw new UserWorkTransferRefusal(400, 'VALIDATION_ERROR', 'toUserId must name a different user than the one whose work is transferred'); |
| 259 | + } |
| 260 | + // The target's existence and ban state are facts about the user, read the |
| 261 | + // way the write path's reference check reads them: past the caller's row |
| 262 | + // visibility, inside the caller's tenant. |
| 263 | + const elevated = { ...((context as object | undefined) ?? {}), isSystem: true }; |
| 264 | + const [target] = await engine.find(USER_OBJECT, { |
| 265 | + where: { id: toUserId }, |
| 266 | + fields: ['id', 'banned', 'ban_expires'], |
| 267 | + limit: 1, |
| 268 | + context: elevated, |
| 269 | + }); |
| 270 | + if (!target) { |
| 271 | + throw new UserWorkTransferRefusal(404, 'RESOURCE_NOT_FOUND', `No user has id "${toUserId}"`, { field: 'toUserId', code: 'reference_not_found' }); |
| 272 | + } |
| 273 | + if (isUserBanInForce(target)) { |
| 274 | + throw new UserWorkTransferRefusal(400, 'VALIDATION_ERROR', `User "${toUserId}" is banned and cannot be assigned new records; pick an active user`, { field: 'toUserId', code: 'reference_user_banned' }); |
| 275 | + } |
| 276 | + |
| 277 | + const only = options.objects && options.objects.length > 0 ? new Set(options.objects) : undefined; |
| 278 | + const { fields } = userAssignedWorkFields(Object.values(engine.getConfigs() ?? {})); |
| 279 | + const refs = fields.filter((ref) => !ref.multiple && (!only || only.has(ref.object))); |
| 280 | + let budget = options.rowCap ?? USER_WORK_TRANSFER_ROW_CAP; |
| 281 | + const objects: UserWorkTransferOutcome[] = []; |
| 282 | + let updated = 0; |
| 283 | + let failed = 0; |
| 284 | + let remaining = 0; |
| 285 | + for (const ref of refs) { |
| 286 | + let rows: any[] = []; |
| 287 | + if (budget > 0) { |
| 288 | + try { |
| 289 | + rows = await engine.find(ref.object, { where: holdsUser(ref, fromUserId), fields: ['id'], limit: budget, context }); |
| 290 | + } catch { |
| 291 | + // An object the caller cannot read holds nothing this caller can move. |
| 292 | + continue; |
| 293 | + } |
| 294 | + } |
| 295 | + const outcome: UserWorkTransferOutcome = { object: ref.object, field: ref.field, updated: 0, failed: 0, failures: [] }; |
| 296 | + for (const row of Array.isArray(rows) ? rows : []) { |
| 297 | + if (row?.id === undefined || row?.id === null) continue; |
| 298 | + budget -= 1; |
| 299 | + try { |
| 300 | + await engine.update(ref.object, { [ref.field]: toUserId }, { where: { id: row.id }, context }); |
| 301 | + outcome.updated += 1; |
| 302 | + } catch (err) { |
| 303 | + outcome.failed += 1; |
| 304 | + if (outcome.failures.length < USER_WORK_FAILURE_SAMPLE) outcome.failures.push(failureOf(row.id, err)); |
| 305 | + } |
| 306 | + } |
| 307 | + try { |
| 308 | + remaining += await engine.count(ref.object, { where: holdsUser(ref, fromUserId), context }); |
| 309 | + } catch { |
| 310 | + // Counted as unknown: the rows moved above are reported either way. |
| 311 | + } |
| 312 | + if (outcome.updated > 0 || outcome.failed > 0) objects.push(outcome); |
| 313 | + updated += outcome.updated; |
| 314 | + failed += outcome.failed; |
| 315 | + } |
| 316 | + return { fromUserId, toUserId, objects, updated, failed, remaining }; |
| 317 | +} |
0 commit comments