Skip to content

Commit 01ab401

Browse files
committed
feat(rest): serve a user's assigned-work count and bulk hand-over (WIP)
Claude-Session: https://claude.ai/code/session_01Utp6CZavYYLh5k5r6jhgCF Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0aabb9d commit 01ab401

5 files changed

Lines changed: 197 additions & 2 deletions

File tree

‎packages/core/src/security/user-assigned-work.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,11 +132,22 @@ export function userAssignedWorkFields(
132132
*/
133133
export interface UserWorkEngine {
134134
getConfigs(): Record<string, unknown>;
135+
/** A disabled package's object serves no data door, so it holds no work to count. */
136+
readonly registry?: { isObjectPackageDisabled?(name: string): boolean };
135137
count(object: string, query?: any): Promise<number>;
136138
find(object: string, query?: any): Promise<any[]>;
137139
update(object: string, data: any, options?: any): Promise<unknown>;
138140
}
139141

142+
/** The registered objects a data door serves: a disabled package's are left out. */
143+
function servedObjects(engine: UserWorkEngine): unknown[] {
144+
const disabled = engine.registry?.isObjectPackageDisabled?.bind(engine.registry);
145+
return Object.values(engine.getConfigs() ?? {}).filter((obj) => {
146+
const name = (obj as ObjectLike | undefined)?.name;
147+
return !(disabled && typeof name === 'string' && disabled(name) === true);
148+
});
149+
}
150+
140151
/** The filter that matches the records a field holds `userId` in. */
141152
function holdsUser(ref: UserAssignedWorkField, userId: string): Record<string, unknown> {
142153
return { [ref.field]: ref.multiple ? { $contains: userId } : userId };
@@ -169,7 +180,7 @@ export async function countUserAssignedWork(
169180
userId: string,
170181
context: unknown,
171182
): Promise<UserAssignedWorkSummary> {
172-
const { fields, truncated } = userAssignedWorkFields(Object.values(engine.getConfigs() ?? {}));
183+
const { fields, truncated } = userAssignedWorkFields(servedObjects(engine));
173184
const objects: UserAssignedWorkCount[] = [];
174185
const unreadable = new Set<string>();
175186
let total = 0;
@@ -275,7 +286,7 @@ export async function transferUserAssignedWork(
275286
}
276287

277288
const only = options.objects && options.objects.length > 0 ? new Set(options.objects) : undefined;
278-
const { fields } = userAssignedWorkFields(Object.values(engine.getConfigs() ?? {}));
289+
const { fields } = userAssignedWorkFields(servedObjects(engine));
279290
const refs = fields.filter((ref) => !ref.multiple && (!only || only.has(ref.object)));
280291
let budget = options.rowCap ?? USER_WORK_TRANSFER_ROW_CAP;
281292
const objects: UserWorkTransferOutcome[] = [];

‎packages/rest/src/rest-route-ledger.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,11 @@ export const REST_ROUTE_LEDGER: readonly RestRouteLedgerEntry[] = [
437437
note: 'duplicate mount with the dispatcher /security domain' },
438438
{ route: 'POST /api/v1/security/suggested-bindings/:id/reopen', family: 'security', source: 'route-manager', disposition: 'sdk', client: 'security.suggestedBindings.reopen',
439439
note: 'duplicate mount with the dispatcher /security domain' },
440+
// ── a user's assigned work (#30205) ───────────────────────────────────────
441+
{ route: 'GET /api/v1/security/users/:id/assigned-work', family: 'user-work', source: 'route-manager', disposition: 'gap',
442+
note: 'new with the server half; the SDK method lands with the Setup ban dialog (the ui half)' },
443+
{ route: 'POST /api/v1/security/users/:id/assigned-work/transfer', family: 'user-work', source: 'route-manager', disposition: 'gap',
444+
note: 'new with the server half; the SDK method lands with the Setup ban dialog (the ui half)' },
440445
// RETIRED (ADR-0131 cutover): `POST /api/v1/security/permission-sets/:id/
441446
// discard-overlay` left with the "Discard Overlay" Setup action. No door
442447
// creates an environment overlay of a packaged permission set any more, and

‎packages/rest/src/rest-server-registrar-files.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,9 @@ export const REST_SERVER_META_ROUTE_FILES: readonly RestServerRegistrarFile[] =
123123
// moved slice; like the per-item writes it goes through the inner method's per-item
124124
// registrar, handed over in its scope.
125125
'meta-app-bundle-routes.ts',
126+
// [#30205] A user's assigned work: the counts and the hand-over. New, not a moved
127+
// slice; it registers on the route manager itself, from a host literal.
128+
'user-work-routes.ts',
126129
];
127130

128131
/**

‎packages/rest/src/rest-server.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,8 @@ import {
337337
type SecurityExplainRouteHost,
338338
type SecurityRouteHost,
339339
} from './security-routes.js';
340+
// [#30205] A user's assigned work: the per-object counts and the bounded hand-over.
341+
import { registerUserWorkEndpoints, type UserWorkRouteHost } from './user-work-routes.js';
340342
// [#23050 slice 7] The discovery and OpenAPI routes' bodies moved to one module — see its header.
341343
import {
342344
registerDiscoveryEndpoints,
@@ -4959,6 +4961,7 @@ export class RestServer {
49594961
this.registerAnalyticsEndpoints(bp);
49604962
this.registerSecurityEndpoints(bp);
49614963
this.registerSecurityExplainEndpoints(bp);
4964+
this.registerUserWorkEndpoints(bp);
49624965
// Data-action routes (e.g. GET /data/:object/export, POST
49634966
// /data/:object/import) use static-literal action segments that
49644967
// MUST be registered BEFORE the greedy GET /data/:object/:id
@@ -6178,6 +6181,35 @@ export class RestServer {
61786181
* business) and returns 501 when no security service exposing `explain`
61796182
* is mounted (a deployment without `@objectstack/plugin-security`).
61806183
*/
6184+
private registerUserWorkEndpoints(basePath: string): void {
6185+
// [#30205] The body lives in `user-work-routes.ts`. This literal hands it
6186+
// every member it reads (see `UserWorkRouteHost`); the engine provider
6187+
// FIELD goes as a getter, read when a handler reads it.
6188+
const readObjectQLProvider = () => this.objectQLProvider;
6189+
const host: UserWorkRouteHost = {
6190+
routeManager: this.routeManager,
6191+
get objectQLProvider() { return readObjectQLProvider(); },
6192+
resolveRequestEnvironmentId: (...a) => this.resolveRequestEnvironmentId(...a),
6193+
resolveExecCtx: (...a) => this.resolveExecCtx(...a),
6194+
enforceAuth: (...a) => this.enforceAuth(...a),
6195+
};
6196+
registerUserWorkEndpoints.call(host, basePath);
6197+
}
6198+
6199+
/**
6200+
* [#30205] Register a user's assigned-work routes:
6201+
*
6202+
* GET {basePath}/security/users/:id/assigned-work
6203+
* POST {basePath}/security/users/:id/assigned-work/transfer body: { toUserId, objects? }
6204+
*
6205+
* The first answers, per object and user field, how many records hold the
6206+
* user (the owner field and every app user field), counted as the caller
6207+
* can read them. The second hands up to 500 of those records to another
6208+
* active user per call, each as an ordinary update under the caller's
6209+
* context, and answers what moved, what failed and how many remain.
6210+
* Neither touches the ban. `@objectstack/core`'s `user-assigned-work.ts`
6211+
* holds the rules.
6212+
*/
61816213
private registerSecurityExplainEndpoints(basePath: string): void {
61826214
// [#23050 slice 6] The body moved to `security-routes.ts`. This literal
61836215
// hands it every member it reads — the list IS its dependency on this
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
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

Comments
 (0)