|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#30205] The assigned-work routes: a user's open work, counted, and handed |
| 5 | + * over in bulk — what an administrator needs when they ban someone. |
| 6 | + * |
| 7 | + * GET {basePath}/security/users/:id/assigned-work per-object counts |
| 8 | + * POST {basePath}/security/users/:id/assigned-work/transfer one bounded hand-over |
| 9 | + * |
| 10 | + * The rules (which records count, whose reads and writes, the caps) live in |
| 11 | + * `@objectstack/core`'s `user-assigned-work.ts`; this module only serves them. |
| 12 | + * Both routes run as the CALLER: the counts are what the caller can read, and |
| 13 | + * each moved row is an ordinary update under the caller's context, so neither |
| 14 | + * route needs a gate of its own beyond an authenticated caller — a caller who |
| 15 | + * could not read or edit a record by hand cannot count or move it here either. |
| 16 | + * |
| 17 | + * Neither route touches the ban. A ban is urgent and stands alone |
| 18 | + * (`POST /api/v1/auth/admin/ban-user`); these routes are the optional step |
| 19 | + * beside it. |
| 20 | + * |
| 21 | + * Both declare their CLOSED query-parameter set — none — on the day they land |
| 22 | + * (AGENTS.md, route rule 5), and the transfer body is closed as well: an |
| 23 | + * unknown key is a `400`, never a silently ignored option. |
| 24 | + * |
| 25 | + * ## How the body reaches the class |
| 26 | + * |
| 27 | + * The shape the `rest-server.ts` split set (`data-action-routes.ts`' header |
| 28 | + * carries the reasoning): the class keeps a private registrar method that hands |
| 29 | + * this body one host literal of exactly the members it reads, methods as |
| 30 | + * closures and the `objectQLProvider` field as a getter, read at request time. |
| 31 | + */ |
| 32 | + |
| 33 | +import { sendError, sendServerFault } from '@objectstack/types'; |
| 34 | +import { |
| 35 | + countUserAssignedWork, |
| 36 | + transferUserAssignedWork, |
| 37 | + UserWorkTransferRefusal, |
| 38 | + type UserWorkEngine, |
| 39 | +} from '@objectstack/core'; |
| 40 | +import { refuseUnknownQueryParams } from './query-allowlist.js'; |
| 41 | +import { wiredEngineOrLoud, type RestServer } from './rest-server.js'; |
| 42 | + |
| 43 | +/** The `RestServer` members {@link registerUserWorkEndpoints} reads — every one of them, and no other. */ |
| 44 | +export interface UserWorkRouteHost { |
| 45 | + readonly routeManager: RestServer['routeManager']; |
| 46 | + readonly objectQLProvider: RestServer['objectQLProvider']; |
| 47 | + resolveRequestEnvironmentId: RestServer['resolveRequestEnvironmentId']; |
| 48 | + resolveExecCtx: RestServer['resolveExecCtx']; |
| 49 | + enforceAuth: RestServer['enforceAuth']; |
| 50 | +} |
| 51 | + |
| 52 | +/** Neither route reads a query parameter. */ |
| 53 | +export const USER_WORK_QUERY_PARAMS: readonly string[] = []; |
| 54 | + |
| 55 | +/** The keys a transfer body may carry. */ |
| 56 | +const TRANSFER_BODY_KEYS = new Set(['toUserId', 'objects']); |
| 57 | + |
| 58 | +/** |
| 59 | + * Register the assigned-work routes — `RestServer#registerUserWorkEndpoints`' |
| 60 | + * body, called by that method with the server as `this`. |
| 61 | + */ |
| 62 | +export function registerUserWorkEndpoints(this: UserWorkRouteHost, basePath: string): void { |
| 63 | + const isScoped = basePath.includes('/environments/:environmentId'); |
| 64 | + |
| 65 | + /** The request's engine, `undefined` when none is wired; an outage throws. */ |
| 66 | + const resolveEngine = async (environmentId: string | undefined, req: any): Promise<UserWorkEngine | undefined> => |
| 67 | + wiredEngineOrLoud( |
| 68 | + Boolean(this.objectQLProvider), |
| 69 | + async () => this.objectQLProvider!(await this.resolveRequestEnvironmentId(environmentId, req)), |
| 70 | + ) as Promise<UserWorkEngine | undefined>; |
| 71 | + |
| 72 | + const userIdOf = (req: any): string | undefined => { |
| 73 | + const id = req.params?.id; |
| 74 | + return typeof id === 'string' && id.length > 0 ? id : undefined; |
| 75 | + }; |
| 76 | + |
| 77 | + this.routeManager.register({ |
| 78 | + method: 'GET', |
| 79 | + path: `${basePath}/security/users/:id/assigned-work`, |
| 80 | + handler: async (req: any, res: any) => { |
| 81 | + try { |
| 82 | + const environmentId = isScoped ? req.params?.environmentId : undefined; |
| 83 | + const context = await this.resolveExecCtx(environmentId, req); |
| 84 | + if (this.enforceAuth(req, res, context)) return; |
| 85 | + if (refuseUnknownQueryParams(req, res, USER_WORK_QUERY_PARAMS)) return; |
| 86 | + const userId = userIdOf(req); |
| 87 | + if (!userId) return sendError(res, 400, 'VALIDATION_ERROR', 'The user id is required'); |
| 88 | + const engine = await resolveEngine(environmentId, req); |
| 89 | + if (!engine) return sendError(res, 501, 'NOT_IMPLEMENTED', 'No data engine is configured on this deployment'); |
| 90 | + const summary = await countUserAssignedWork(engine, userId, context); |
| 91 | + return res.json({ success: true, data: summary }); |
| 92 | + } catch (err) { |
| 93 | + return sendServerFault(res, 500, 'INTERNAL_ERROR', 'Counting the user\'s assigned work failed', err); |
| 94 | + } |
| 95 | + }, |
| 96 | + metadata: { summary: 'Count the records a user owns or is assigned, per object, as the caller can read them' }, |
| 97 | + }); |
| 98 | + |
| 99 | + this.routeManager.register({ |
| 100 | + method: 'POST', |
| 101 | + path: `${basePath}/security/users/:id/assigned-work/transfer`, |
| 102 | + handler: async (req: any, res: any) => { |
| 103 | + try { |
| 104 | + const environmentId = isScoped ? req.params?.environmentId : undefined; |
| 105 | + const context = await this.resolveExecCtx(environmentId, req); |
| 106 | + if (this.enforceAuth(req, res, context)) return; |
| 107 | + if (refuseUnknownQueryParams(req, res, USER_WORK_QUERY_PARAMS)) return; |
| 108 | + const userId = userIdOf(req); |
| 109 | + if (!userId) return sendError(res, 400, 'VALIDATION_ERROR', 'The user id is required'); |
| 110 | + const body = req.body; |
| 111 | + if (!body || typeof body !== 'object' || Array.isArray(body)) { |
| 112 | + return sendError(res, 400, 'VALIDATION_ERROR', 'The body must be an object: { toUserId, objects? }'); |
| 113 | + } |
| 114 | + const unknown = Object.keys(body).filter((k) => !TRANSFER_BODY_KEYS.has(k)); |
| 115 | + if (unknown.length > 0) { |
| 116 | + return sendError(res, 400, 'VALIDATION_ERROR', `Unknown body key(s): ${unknown.join(', ')}. A transfer takes toUserId and, optionally, objects`); |
| 117 | + } |
| 118 | + const toUserId = body.toUserId; |
| 119 | + if (typeof toUserId !== 'string' || toUserId.length === 0) { |
| 120 | + return sendError(res, 400, 'VALIDATION_ERROR', 'toUserId is required: the id of the active user who takes over the records'); |
| 121 | + } |
| 122 | + const objects = body.objects; |
| 123 | + if (objects !== undefined |
| 124 | + && !(Array.isArray(objects) && objects.every((o: unknown) => typeof o === 'string' && o.length > 0))) { |
| 125 | + return sendError(res, 400, 'VALIDATION_ERROR', 'objects, when given, must be a list of object names'); |
| 126 | + } |
| 127 | + const engine = await resolveEngine(environmentId, req); |
| 128 | + if (!engine) return sendError(res, 501, 'NOT_IMPLEMENTED', 'No data engine is configured on this deployment'); |
| 129 | + try { |
| 130 | + const report = await transferUserAssignedWork(engine, userId, toUserId, context, { objects }); |
| 131 | + return res.json({ success: true, data: report }); |
| 132 | + } catch (err) { |
| 133 | + if (!(err instanceof UserWorkTransferRefusal)) throw err; |
| 134 | + return sendError(res, err.status, err.code, err.message, err.field ? { |
| 135 | + details: { fields: [{ field: err.field.field, code: err.field.code, message: err.message }] }, |
| 136 | + } : undefined); |
| 137 | + } |
| 138 | + } catch (err) { |
| 139 | + return sendServerFault(res, 500, 'INTERNAL_ERROR', 'Transferring the user\'s assigned work failed', err); |
| 140 | + } |
| 141 | + }, |
| 142 | + metadata: { summary: 'Hand a user\'s owned and assigned records to another active user, as the caller, in bounded batches' }, |
| 143 | + }); |
| 144 | +} |
0 commit comments