|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { |
| 4 | + ANONYMOUS_DENY_CODE, |
| 5 | + ANONYMOUS_DENY_MESSAGE, |
| 6 | + ANONYMOUS_DENY_STATUS, |
| 7 | + evaluateAuthGate, |
| 8 | + isApiKeyLifecycleRefusalError, |
| 9 | + isAuthzStoreUnavailableError, |
| 10 | + resolveRequestExecutionContext, |
| 11 | + shouldDenyAnonymous, |
| 12 | + type RequestAuthService, |
| 13 | + type TenancyServiceResolver, |
| 14 | +} from '@objectstack/core'; |
| 15 | +import type { ErrorCode } from '@objectstack/spec/api'; |
| 16 | +import type { IHttpRequest, IHttpResponse, IHttpServer } from '@objectstack/spec/contracts'; |
| 17 | +import type { ExecutionContext } from '@objectstack/spec/kernel'; |
| 18 | +import { sendError, sendOk, sendServerFault } from '@objectstack/types'; |
| 19 | +import { SharingRulesNotRunningError, type ShareableObject } from './shareable-objects.js'; |
| 20 | + |
| 21 | +/** |
| 22 | + * The shareable-objects door: `GET /api/v1/sharing/shareable-objects`. It |
| 23 | + * answers the objects a sharing rule can take effect on, for Setup's |
| 24 | + * sharing-rule object picker (`shareable-objects.ts` says which objects and in |
| 25 | + * what order). It reads and never writes. |
| 26 | + * |
| 27 | + * ## Why plugin-sharing mounts it |
| 28 | + * |
| 29 | + * The sharing-rule administration routes (`/api/v1/sharing/rules*`) are |
| 30 | + * `@objectstack/rest`'s, served over the `sharingRules` service through a spec |
| 31 | + * contract. A list there would need a new member on that contract; this door |
| 32 | + * is the plugin's own, read straight off the `SharingRuleService` the plugin |
| 33 | + * constructs, at a path no other package serves. It reaches for the |
| 34 | + * `http.server` service and registers on `IHttpServer`, as the share-link |
| 35 | + * family does; `sharing-route-ledger.ts` records it. |
| 36 | + * |
| 37 | + * ## Who may ask — the sharing-rule administrators |
| 38 | + * |
| 39 | + * In order, before anything is read: |
| 40 | + * |
| 41 | + * 1. **The caller**, resolved by the platform's one request-to-context |
| 42 | + * composition (`resolveRequestExecutionContext`) from the request's session |
| 43 | + * or API key. A permission store that cannot be read answers its own |
| 44 | + * `SERVICE_UNAVAILABLE` / `503`, and an API key its lifecycle refuses its |
| 45 | + * own `403` and code: both relayed as declared, never folded into a denial. |
| 46 | + * 2. **A held sign-in** (ADR-0069: an expired password, enforced MFA not yet |
| 47 | + * enrolled): `403` with the authentication policy's own code. |
| 48 | + * 3. **Anonymous** — the platform's one anonymous floor (ADR-0056 D2): |
| 49 | + * `UNAUTHENTICATED` / `401`. |
| 50 | + * 4. **The request**: the route takes no query parameter, and a request that |
| 51 | + * carries one is refused `VALIDATION_ERROR` / `400` naming it (AGENTS.md, |
| 52 | + * route rule 5: the closed set here is empty), never ignored. |
| 53 | + * 5. **The administrator**: the sharing-rule surface's own admission |
| 54 | + * (`SharingRuleService.listShareableObjects` asks the check every verb of |
| 55 | + * that surface asks, ADR-0111 D6). A caller it refuses is answered |
| 56 | + * `PERMISSION_DENIED` / `403` with its sentence, so the list names nothing |
| 57 | + * the caller could not author a rule on. |
| 58 | + * |
| 59 | + * ## What the door answers |
| 60 | + * |
| 61 | + * - **Success:** `200` with `{ objects }` (`ShareableObject[]`), business |
| 62 | + * objects first. |
| 63 | + * - **Sharing rules not running on this kernel** (`enforce: false`, or the |
| 64 | + * rule subsystem did not start): `501` / `NOT_IMPLEMENTED`, the answer the |
| 65 | + * REST sharing-rule routes give for the same state. |
| 66 | + * - **An engine that cannot enumerate its objects** is a fault: `500` / |
| 67 | + * `INTERNAL_ERROR` with this door's sentence and the error in the fault log. |
| 68 | + * An empty list would read as "no object can take a rule", so it is never |
| 69 | + * served in place of the answer. |
| 70 | + */ |
| 71 | + |
| 72 | +/** The route the door is mounted at. */ |
| 73 | +export const SHAREABLE_OBJECTS_ROUTE = '/api/v1/sharing/shareable-objects'; |
| 74 | + |
| 75 | +/** What the door is composed over — every service read when a request arrives. */ |
| 76 | +export interface ShareableObjectsRoutesDeps { |
| 77 | + /** The data engine the caller's grants are read through; `undefined` when none is registered. */ |
| 78 | + getEngine(): unknown; |
| 79 | + /** The auth service the caller's session is read through; `undefined` when none is registered. */ |
| 80 | + getAuth(): RequestAuthService | undefined; |
| 81 | + /** How this door reaches the `tenancy` service; `undefined` on a host with no async service accessor. */ |
| 82 | + tenancy: TenancyServiceResolver | undefined; |
| 83 | + /** |
| 84 | + * The list, admitted for `context` — `SharingRuleService.listShareableObjects`. |
| 85 | + * Throws `PERMISSION_DENIED: …` for a caller the sharing-rule surface refuses, |
| 86 | + * and {@link SharingRulesNotRunningError} when no rule service runs. |
| 87 | + */ |
| 88 | + listShareableObjects(context: ExecutionContext): ShareableObject[]; |
| 89 | +} |
| 90 | + |
| 91 | +/** Mount the door on `http`. Nothing on `deps` is called until a request arrives. */ |
| 92 | +export function registerShareableObjectsRoutes(http: IHttpServer, deps: ShareableObjectsRoutesDeps): void { |
| 93 | + http.get(SHAREABLE_OBJECTS_ROUTE, (req, res) => handleShareableObjects(req, res, deps)); |
| 94 | +} |
| 95 | + |
| 96 | +/** The sharing-rule surface's refusal idiom (`PERMISSION_DENIED: <sentence>`), read once. */ |
| 97 | +const PERMISSION_DENIED_PREFIX = /^PERMISSION_DENIED:\s*/; |
| 98 | + |
| 99 | +async function handleShareableObjects( |
| 100 | + req: IHttpRequest, |
| 101 | + res: IHttpResponse, |
| 102 | + deps: ShareableObjectsRoutesDeps, |
| 103 | +): Promise<void> { |
| 104 | + // ① The caller. |
| 105 | + let context: ExecutionContext | undefined; |
| 106 | + try { |
| 107 | + context = await resolveCaller(req, deps); |
| 108 | + } catch (err) { |
| 109 | + if (isAuthzStoreUnavailableError(err) || isApiKeyLifecycleRefusalError(err)) { |
| 110 | + sendError(res, err.status, err.code, err.message); |
| 111 | + return; |
| 112 | + } |
| 113 | + sendServerFault(res, 500, 'INTERNAL_ERROR', 'The caller of this request could not be resolved.', err, { |
| 114 | + method: 'GET', |
| 115 | + path: SHAREABLE_OBJECTS_ROUTE, |
| 116 | + }); |
| 117 | + return; |
| 118 | + } |
| 119 | + |
| 120 | + // ② A held sign-in. |
| 121 | + const gate = evaluateAuthGate(context, ''); |
| 122 | + if (gate) { |
| 123 | + sendError(res, 403, gate.code as ErrorCode, gate.message); |
| 124 | + return; |
| 125 | + } |
| 126 | + |
| 127 | + // ③ Anonymous. |
| 128 | + if (!context || shouldDenyAnonymous({ userId: context.userId, method: req.method })) { |
| 129 | + sendError(res, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE); |
| 130 | + return; |
| 131 | + } |
| 132 | + |
| 133 | + // ④ The request: the closed query set is empty. |
| 134 | + const query = Object.keys(req.query ?? {}); |
| 135 | + if (query.length > 0) { |
| 136 | + sendError( |
| 137 | + res, |
| 138 | + 400, |
| 139 | + 'VALIDATION_ERROR', |
| 140 | + `The shareable objects list takes no query parameter, and this request carries ${query.map((q) => `'${q}'`).join(', ')}. ` + |
| 141 | + 'Ask for the list with no parameters: it always answers every object a sharing rule can take effect on.', |
| 142 | + ); |
| 143 | + return; |
| 144 | + } |
| 145 | + |
| 146 | + // ⑤ The administrator, then the list. |
| 147 | + let objects: ShareableObject[]; |
| 148 | + try { |
| 149 | + objects = deps.listShareableObjects(context); |
| 150 | + } catch (err) { |
| 151 | + const message = err instanceof Error ? err.message : String(err); |
| 152 | + if (err instanceof SharingRulesNotRunningError) { |
| 153 | + sendError(res, 501, 'NOT_IMPLEMENTED', message); |
| 154 | + return; |
| 155 | + } |
| 156 | + if (PERMISSION_DENIED_PREFIX.test(message)) { |
| 157 | + sendError(res, 403, 'PERMISSION_DENIED', message.replace(PERMISSION_DENIED_PREFIX, '')); |
| 158 | + return; |
| 159 | + } |
| 160 | + sendServerFault(res, 500, 'INTERNAL_ERROR', 'The objects a sharing rule can take effect on could not be listed.', err, { |
| 161 | + method: 'GET', |
| 162 | + path: SHAREABLE_OBJECTS_ROUTE, |
| 163 | + }); |
| 164 | + return; |
| 165 | + } |
| 166 | + sendOk(res, { objects }); |
| 167 | +} |
| 168 | + |
| 169 | +/** |
| 170 | + * Resolve the caller through the one composition. This door's differences, as |
| 171 | + * its named parameters: anonymous fails closed (the door answers its floor); |
| 172 | + * the held-sign-in posture is the one the resolver decided for the credential |
| 173 | + * that admitted the caller; an API key admits its owner with no session read; |
| 174 | + * no locale, bearer or OAuth token is carried — the list is the same in every |
| 175 | + * language, and nothing downstream acts as the caller. |
| 176 | + */ |
| 177 | +async function resolveCaller(req: IHttpRequest, deps: ShareableObjectsRoutesDeps): Promise<ExecutionContext | undefined> { |
| 178 | + const headers = new Headers(); |
| 179 | + for (const [name, value] of Object.entries(req.headers ?? {})) { |
| 180 | + if (value == null) continue; |
| 181 | + headers.set(name, Array.isArray(value) ? value.join(',') : String(value)); |
| 182 | + } |
| 183 | + return await resolveRequestExecutionContext({ |
| 184 | + headers, |
| 185 | + ql: deps.getEngine(), |
| 186 | + authService: deps.getAuth(), |
| 187 | + tenancy: deps.tenancy, |
| 188 | + anonymous: 'fail-closed', |
| 189 | + authGate: 'resolved', |
| 190 | + credentials: 'api-key-and-session', |
| 191 | + sessionApi: 'optional', |
| 192 | + session: 'request', |
| 193 | + localization: 'withhold', |
| 194 | + requestLocale: undefined, |
| 195 | + accessToken: 'withhold', |
| 196 | + oauth: undefined, |
| 197 | + onAdmission: undefined, |
| 198 | + }); |
| 199 | +} |
0 commit comments