@stonyx/orm 0.3.2-beta.156 → 0.3.2-beta.158
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +321 -47
- package/dist/access-verdict.d.ts +85 -0
- package/dist/access-verdict.js +284 -0
- package/dist/hooks.d.ts +15 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +8 -0
- package/dist/orm-request.d.ts +48 -0
- package/dist/orm-request.js +148 -23
- package/dist/record.d.ts +16 -0
- package/dist/record.js +149 -3
- package/dist/types/orm-types.d.ts +122 -0
- package/package.json +1 -1
- package/src/access-verdict.ts +312 -0
- package/src/hooks.ts +15 -1
- package/src/index.ts +9 -0
- package/src/orm-request.ts +152 -22
- package/src/record.ts +176 -3
- package/src/types/orm-types.ts +124 -1
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shared access-verdict primitive (abofs/stonyx-orm#234).
|
|
3
|
+
*
|
|
4
|
+
* ---------------------------------------------------------------------------
|
|
5
|
+
* WHY THIS FILE EXISTS: ONE INTERPRETER, NOT TWO
|
|
6
|
+
* ---------------------------------------------------------------------------
|
|
7
|
+
* A consumer `access()` may return six differently-shaped things -- `false`, a
|
|
8
|
+
* bare permission string, a permission array, `true`, a per-record function, or
|
|
9
|
+
* something the contract does not define at all -- and the reading of each one
|
|
10
|
+
* is a security decision. `auth()` has held that reading inline since #190.
|
|
11
|
+
* Every surface that needs to ask "may this caller see model X's record?" needs
|
|
12
|
+
* the SAME reading, or the second copy becomes an unreviewed second
|
|
13
|
+
* authorization vocabulary that answers differently about the same value.
|
|
14
|
+
*
|
|
15
|
+
* So `interpretAccess` is extracted here and `auth()` now calls it. It is the
|
|
16
|
+
* only place a return shape is classified, and abofs/stonyx-orm#232 and #233
|
|
17
|
+
* rebase onto it rather than re-deriving it.
|
|
18
|
+
*
|
|
19
|
+
* ---------------------------------------------------------------------------
|
|
20
|
+
* WHAT A LINKAGE FILTER IS, AND WHY THE CALLER BUILDS IT
|
|
21
|
+
* ---------------------------------------------------------------------------
|
|
22
|
+
* `Record.toJSON()` APPLIES a verdict; it never RESOLVES one. That is not a
|
|
23
|
+
* style choice, it is forced, and it was measured before it was decided:
|
|
24
|
+
*
|
|
25
|
+
* INPUT: origin/dev @ c5f7907, unpatched -> 967 pass / 0 fail
|
|
26
|
+
* INPUT: same + fail-closed resolution INSIDE toJSON() -> 964 pass / 3 fail
|
|
27
|
+
*
|
|
28
|
+
* and all three reds were over-denial of PERMITTED records, not the leak. Two
|
|
29
|
+
* independent reasons:
|
|
30
|
+
*
|
|
31
|
+
* 1. `toJSON()` has no request. The shipped, documented sample reads
|
|
32
|
+
* `request.path` for its `/archived` sub-path rule -- the one read of
|
|
33
|
+
* argument one the README sanctions -- and fail-closes when it is absent.
|
|
34
|
+
* Measured against the live registry:
|
|
35
|
+
*
|
|
36
|
+
* getAccess('owner')(undefined, { model:'owner', operation:'read' }) -> false
|
|
37
|
+
* getAccess('animal')(undefined,{ model:'animal', operation:'read' }) -> [Function]
|
|
38
|
+
*
|
|
39
|
+
* Same predicate object, two models, two different degradation modes,
|
|
40
|
+
* chosen by the consumer. Without a request there is no trustworthy
|
|
41
|
+
* answer to get.
|
|
42
|
+
*
|
|
43
|
+
* 2. `toJSON` is also the `JSON.stringify` hook, so `JSON.stringify({data:
|
|
44
|
+
* record})` calls `record.toJSON('data')` -- a STRING in the options slot.
|
|
45
|
+
* An implicit caller has no syntactic place to pass anything
|
|
46
|
+
* (abofs/stonyx-orm#230). The no-argument document must therefore stay
|
|
47
|
+
* byte-identical to what shipped, which also rules out fail-closed by
|
|
48
|
+
* default: `Orm.instance.accessFunctions` is `{}` in any process that
|
|
49
|
+
* never ran `setup-rest-server` (CLI, SQL-only, unit tests), so a
|
|
50
|
+
* fail-closed default would empty every relationship on every document in
|
|
51
|
+
* processes that have no REST surface to protect.
|
|
52
|
+
*
|
|
53
|
+
* The caller -- which still holds the request -- resolves the predicate,
|
|
54
|
+
* interprets it here, caches the answer, and hands `toJSON()` an already-decided
|
|
55
|
+
* `(type, record) => boolean`.
|
|
56
|
+
*/
|
|
57
|
+
import Orm from '@stonyx/orm';
|
|
58
|
+
import log from 'stonyx/log';
|
|
59
|
+
import type { AccessMethod, AccessOperation, LinkageFilter } from './types/orm-types.js';
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The classified reading of one `access()` return value.
|
|
63
|
+
*
|
|
64
|
+
* `granted: false` is a total denial. `granted: true` with no `filter` is an
|
|
65
|
+
* unconditional grant. `granted: true` WITH a filter means "grant, subject to
|
|
66
|
+
* this per-record predicate" -- the function return shape, which is the
|
|
67
|
+
* per-record hook `AccessContext` deliberately does not provide.
|
|
68
|
+
*/
|
|
69
|
+
export interface AccessVerdict {
|
|
70
|
+
granted: boolean;
|
|
71
|
+
filter?: (record: unknown) => boolean;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const DENIED: AccessVerdict = Object.freeze({ granted: false });
|
|
75
|
+
const GRANTED: AccessVerdict = Object.freeze({ granted: true });
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Classify one `access()` return value. Extracted verbatim from `auth()`, which
|
|
79
|
+
* now calls this; the branch ORDER is load-bearing and is preserved exactly.
|
|
80
|
+
*
|
|
81
|
+
* `operation` is the verb being authorised. `undefined` -- reachable, because
|
|
82
|
+
* express delivers HEAD to the GET handler and `methodAccessMap` has no entry
|
|
83
|
+
* for it -- falls through `permitted.includes(undefined)` to a denial, which is
|
|
84
|
+
* the same answer `auth()` gave before the extraction.
|
|
85
|
+
*/
|
|
86
|
+
export function interpretAccess(access: AccessMethod, operation: AccessOperation | undefined): AccessVerdict {
|
|
87
|
+
if (!access) return DENIED;
|
|
88
|
+
|
|
89
|
+
// The function return shape IS the per-record hook. Grant the request and
|
|
90
|
+
// carry the predicate; the caller applies it per record.
|
|
91
|
+
if (typeof access === 'function') return { granted: true, filter: access as (record: unknown) => boolean };
|
|
92
|
+
|
|
93
|
+
if (access === true) return GRANTED;
|
|
94
|
+
|
|
95
|
+
// `AccessMethod` declares `string` legal and it fell through every branch
|
|
96
|
+
// above. A bare string is ONE permission, not a grant of all four -- reading
|
|
97
|
+
// it as a full grant is what once let `return 'read'` authorise DELETE.
|
|
98
|
+
const permitted = typeof access === 'string' ? [access] : access;
|
|
99
|
+
|
|
100
|
+
// Anything that is not a permission array by this point -- an object, a
|
|
101
|
+
// number, a Symbol -- is a consumer mistake, and the only safe reading of a
|
|
102
|
+
// shape the contract does not define is a denial. Fail CLOSED.
|
|
103
|
+
if (!Array.isArray(permitted)) return DENIED;
|
|
104
|
+
if (!permitted.includes(operation as string)) return DENIED;
|
|
105
|
+
|
|
106
|
+
return GRANTED;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Resolve model `type`'s verdict for a read, against the live `request`.
|
|
111
|
+
*
|
|
112
|
+
* Fails closed on both ambiguous inputs:
|
|
113
|
+
*
|
|
114
|
+
* - `getAccess(type)` -> `undefined`. That is NOT "this model is
|
|
115
|
+
* unrestricted". `setup-rest-server` catches an access-class load failure,
|
|
116
|
+
* warns, and publishes whatever PARTIAL map it had, so `undefined` covers
|
|
117
|
+
* both "no access class claims this model" and "the class that claims it
|
|
118
|
+
* failed to load" -- and the caller cannot tell them apart. Deny.
|
|
119
|
+
* - the predicate THROWS. Same reading `auth()` and `isDenied` already use:
|
|
120
|
+
* a throw is a denial, logged, never a 500 and never a grant.
|
|
121
|
+
*
|
|
122
|
+
* NOTE ON CROSS-MODEL ASKS -- READ THIS BEFORE REBASING #232 OR #233 ONTO IT.
|
|
123
|
+
* The predicate is asked about `type` while the request in hand was dispatched
|
|
124
|
+
* to a DIFFERENT model's route. This function makes another model's class
|
|
125
|
+
* REACHABLE and asks it the model-correct question (`{ model: type }`); whether
|
|
126
|
+
* the ANSWER is model-correct is the CONSUMER's, because only a predicate that
|
|
127
|
+
* READS `context.model` can give one. Since #222 this repo's fixture does. A
|
|
128
|
+
* consumer's arity-1 predicate does not, and there is no supported way to tell
|
|
129
|
+
* which kind was resolved (the boot-time arity warning is
|
|
130
|
+
* abofs/stonyx-orm#213/#221, unshipped).
|
|
131
|
+
*
|
|
132
|
+
* BOTH DEGRADATION DIRECTIONS ARE REACHABLE, AND THE SECOND ONE GRANTS. This is
|
|
133
|
+
* measured, not reasoned:
|
|
134
|
+
*
|
|
135
|
+
* - CLOSED. The migrated fixture's surviving `request.path` read means asking
|
|
136
|
+
* the OWNER predicate on a request dispatched to `GET /animals/archived`
|
|
137
|
+
* returns a bare `false` -- a whole-request deny bleeding across models,
|
|
138
|
+
* treated here as "deny this linkage", not as an error. That over-denies a
|
|
139
|
+
* PERMITTED record.
|
|
140
|
+
* - OPEN. An arity-1 predicate -- the shape `setup-rest-server.ts:15-18`
|
|
141
|
+
* still declares valid and the README calls the default in every consumer
|
|
142
|
+
* tree -- identifies its collection from the request, so asked about
|
|
143
|
+
* `owner` on a request dispatched to `/animals` it answers about ANIMALS.
|
|
144
|
+
* Measured against this repo's own fixture with `reg.owner` replaced by an
|
|
145
|
+
* arity-1 predicate that hides angela on `/owners`:
|
|
146
|
+
*
|
|
147
|
+
* GET /owners -> ["gina","michael","bob"] angela hidden, correctly
|
|
148
|
+
* GET /animals -> owners named: [angela, ...] LEAK
|
|
149
|
+
* GET /animals/1 -> owner.data {"type":"owner","id":"angela"}
|
|
150
|
+
*
|
|
151
|
+
* That is byte-for-byte the abofs/stonyx-orm#234 defect, on the surface
|
|
152
|
+
* #234 was filed for, AFTER this fix. It is not a regression -- dev
|
|
153
|
+
* published the same id unconditionally -- and this file cannot close it,
|
|
154
|
+
* because the arity signal is #213/#221. Do NOT write, here or anywhere
|
|
155
|
+
* else, that the cross-model ask degrades closed. The standing rule this
|
|
156
|
+
* paragraph is held to is in docs/project-structure.md.
|
|
157
|
+
*/
|
|
158
|
+
function resolveVerdict(request: unknown, type: string): AccessVerdict {
|
|
159
|
+
const predicate = Orm.instance?.getAccess?.(type);
|
|
160
|
+
if (typeof predicate !== 'function') return DENIED;
|
|
161
|
+
|
|
162
|
+
let access: AccessMethod;
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
// `recordId: null`, AND NOT `request.params.id`. THE TEMPTING WRONG ANSWER
|
|
166
|
+
// IS RIGHT THERE, so this is pinned by assertion as well as by comment --
|
|
167
|
+
// test/unit/linkage-verdict-test.ts, `#234 + #241 -- recordId is null`.
|
|
168
|
+
//
|
|
169
|
+
// `AccessContext.recordId` (src/types/orm-types.ts, abofs/stonyx-orm#236 /
|
|
170
|
+
// #241) means "the record THIS ROUTE WAS ADDRESSED TO, as the store key of
|
|
171
|
+
// the model being authorised", and `null` means "addressed to no record".
|
|
172
|
+
// The id sitting on the request in hand names the PRIMARY record, which
|
|
173
|
+
// belongs to a DIFFERENT model -- `GET /owners/gina` carries
|
|
174
|
+
// `params.id === 'gina'`, and the ask being made HERE is about `animal` or
|
|
175
|
+
// `trait`. Filling this in from the request would hand the related model's
|
|
176
|
+
// predicate an id belonging to another model, which is byte-for-byte the
|
|
177
|
+
// cross-model confusion abofs/stonyx-orm#202 introduced this context to
|
|
178
|
+
// eliminate: the predicate would compare an owner's id against its own
|
|
179
|
+
// records and answer a question nobody asked. There is no record of THIS
|
|
180
|
+
// model addressed by this request, so `null` is the honest value -- the
|
|
181
|
+
// same spelling `auth()` uses for a collection route.
|
|
182
|
+
//
|
|
183
|
+
// NOR ANY RECORD'S OWN ID, WHICH IS THE SECOND-MOST TEMPTING ANSWER. This
|
|
184
|
+
// verdict is resolved ONCE PER TYPE and cached in `byType` below, before
|
|
185
|
+
// any record has been looked at; there is no per-record `AccessContext`
|
|
186
|
+
// built anywhere on this path. Seeding it from the first record of a type
|
|
187
|
+
// would let that record's identity answer for every later record of the
|
|
188
|
+
// same type -- the same "one record's verdict answers for another" defect
|
|
189
|
+
// the `decisions` raw-key argument below exists to prevent, just one level
|
|
190
|
+
// coarser. And it is unnecessary: `AccessContext` deliberately carries no
|
|
191
|
+
// `record` because auth-time and record-time are separate decision points,
|
|
192
|
+
// and the per-record point already receives the WHOLE record, id included,
|
|
193
|
+
// through `verdict.filter(record)`. A predicate that wants a record's id
|
|
194
|
+
// has the contract's own channel for it.
|
|
195
|
+
access = predicate(request, { model: type, operation: 'read', recordId: null });
|
|
196
|
+
} catch (error) {
|
|
197
|
+
log.error?.(`[@stonyx/orm] access() threw while resolving linkage for model "${type}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
|
|
198
|
+
|
|
199
|
+
return DENIED;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return interpretAccess(access, 'read');
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Build a request-scoped linkage filter.
|
|
207
|
+
*
|
|
208
|
+
* TWO CACHES, AND BOTH ARE LOAD-BEARING RATHER THAN AN OPTIMISATION:
|
|
209
|
+
*
|
|
210
|
+
* - one verdict per TYPE. Resolving means CALLING the consumer's `access()`,
|
|
211
|
+
* which is arbitrary code with arbitrary cost and which the module has
|
|
212
|
+
* already had to guard for throwing.
|
|
213
|
+
* - one decision per `(type, id)`. `included` is deduplicated by
|
|
214
|
+
* `buildResponse`; LINKAGE is not deduplicated at all, so it re-asks once
|
|
215
|
+
* per record. Measured on a bare `GET /animals` with no `include=`:
|
|
216
|
+
* 48 linkage entries -> 7 distinct `(type, id)` pairs (owner 20, trait 28),
|
|
217
|
+
* a 6.9x reduction and 41 predicate calls saved.
|
|
218
|
+
*
|
|
219
|
+
* The `(type, id)` cache is a `Map` per type keyed on the RAW id, not on a
|
|
220
|
+
* template-string composite. `Map` compares with SameValueZero, so the numeric
|
|
221
|
+
* id `1` and the string id `'1'` stay DISTINCT, where `` `${type}:${id}` `` --
|
|
222
|
+
* or a bare `String(id)` -- collapses them onto one entry and answers the second
|
|
223
|
+
* record with the first record's verdict.
|
|
224
|
+
*
|
|
225
|
+
* WHAT THAT DOES AND DOES NOT PROTECT. It cannot cross MODELS. `decisions` is
|
|
226
|
+
* already partitioned per type by `byType`, so a composite key inside a per-type
|
|
227
|
+
* map is one-to-one with the raw one and no owner's verdict could ever answer
|
|
228
|
+
* for an animal -- the claim that once stood here. The real exposure is narrower
|
|
229
|
+
* and entirely WITHIN one model: two records of the same type whose ids differ
|
|
230
|
+
* only by JavaScript type, which a per-record predicate may legitimately answer
|
|
231
|
+
* differently about (an id read off a JSON body is a string; the same id
|
|
232
|
+
* assigned by the server is a number). Pinned by unit assertion, because this
|
|
233
|
+
* fixture cannot produce the collision on its own -- `owner` ids are strings and
|
|
234
|
+
* `animal` ids are numbers.
|
|
235
|
+
*
|
|
236
|
+
* SCOPE IS ONE REQUEST. The filter closes over the request and must not outlive
|
|
237
|
+
* it -- a verdict cached across requests would answer a second caller with the
|
|
238
|
+
* first caller's authorization.
|
|
239
|
+
*
|
|
240
|
+
* A REQUEST IS REQUIRED, AND ITS ABSENCE IS CHECKED HERE RATHER THAN DELEGATED.
|
|
241
|
+
* This function is EXPORTED (src/index.ts), and the README's Consumer Contracts
|
|
242
|
+
* section points consumers at exactly the contexts that have no live request --
|
|
243
|
+
* a queue payload, a websocket frame, a custom route. Without one there is no
|
|
244
|
+
* caller to authorise against, and this file's header already says so: the
|
|
245
|
+
* shipped sample reads `request.path` and fail-closes when it is absent, so
|
|
246
|
+
* `getAccess('owner')(undefined, ...)` is `false`, while
|
|
247
|
+
* `getAccess('animal')(undefined, ...)` returns a per-record predicate and
|
|
248
|
+
* GRANTS. Measured on this repo's own fixture before this guard existed:
|
|
249
|
+
*
|
|
250
|
+
* createLinkageFilter(undefined | null | {} | 'x' | 0)
|
|
251
|
+
* -> owner=false animal=TRUE trait=TRUE category=TRUE phone-number=TRUE
|
|
252
|
+
*
|
|
253
|
+
* Four of five claimed models granted, with no log, because whether an absent
|
|
254
|
+
* request fails closed was left ENTIRELY to consumer predicates -- and a
|
|
255
|
+
* predicate that ignores its request cannot fail closed on one that is missing.
|
|
256
|
+
* A nullish or primitive `request` therefore denies every model outright and
|
|
257
|
+
* says so once, at construction, so the signal exists even for a caller that
|
|
258
|
+
* goes on to serialize nothing.
|
|
259
|
+
*
|
|
260
|
+
* WHAT THIS CANNOT CHECK: `{}` is an object and passes. There is no request
|
|
261
|
+
* contract this module owns -- `auth()` reads `.method`, the shipped sample
|
|
262
|
+
* reads `.path`, a consumer's reads whatever it likes -- so anything past
|
|
263
|
+
* "is it an object" would be this module inventing a shape for someone else's
|
|
264
|
+
* framework. The residual is documented in the README under Consumer Contracts.
|
|
265
|
+
*/
|
|
266
|
+
export function createLinkageFilter(request: unknown): LinkageFilter {
|
|
267
|
+
if (typeof request !== 'object' || request === null) {
|
|
268
|
+
log.error?.(`[@stonyx/orm] createLinkageFilter() was called with no request (received ${request === null ? 'null' : typeof request}) -- there is no caller to authorise against, so ALL relationship linkage it is asked about is denied.`);
|
|
269
|
+
|
|
270
|
+
return function isLinkable(_type: string, _record: unknown): boolean {
|
|
271
|
+
return false;
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const byType = new Map<string, { verdict: AccessVerdict; decisions: Map<unknown, boolean> }>();
|
|
276
|
+
|
|
277
|
+
return function isLinkable(type: string, record: unknown): boolean {
|
|
278
|
+
let entry = byType.get(type);
|
|
279
|
+
|
|
280
|
+
if (!entry) {
|
|
281
|
+
entry = { verdict: resolveVerdict(request, type), decisions: new Map() };
|
|
282
|
+
byType.set(type, entry);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const { verdict, decisions } = entry;
|
|
286
|
+
|
|
287
|
+
if (!verdict.granted) return false;
|
|
288
|
+
if (!verdict.filter) return true;
|
|
289
|
+
|
|
290
|
+
const id = (record as { id?: unknown } | null)?.id;
|
|
291
|
+
const cached = decisions.get(id);
|
|
292
|
+
if (cached !== undefined) return cached;
|
|
293
|
+
|
|
294
|
+
let allowed: boolean;
|
|
295
|
+
|
|
296
|
+
try {
|
|
297
|
+
allowed = Boolean(verdict.filter(record));
|
|
298
|
+
} catch (error) {
|
|
299
|
+
// A predicate that throws is a denial -- the same reading `isDenied` uses
|
|
300
|
+
// one layer down. Logged, because a predicate that throws on every record
|
|
301
|
+
// empties every relationship and, silently, that is indistinguishable
|
|
302
|
+
// from a database with no relationships in it.
|
|
303
|
+
log.error?.(`[@stonyx/orm] access filter threw while filtering linkage for model "${type}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
|
|
304
|
+
|
|
305
|
+
allowed = false;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
decisions.set(id, allowed);
|
|
309
|
+
|
|
310
|
+
return allowed;
|
|
311
|
+
};
|
|
312
|
+
}
|
package/src/hooks.ts
CHANGED
|
@@ -37,7 +37,21 @@ export interface HookContext {
|
|
|
37
37
|
state?: Record<string, unknown>;
|
|
38
38
|
/** Previous record state (available in update hooks). */
|
|
39
39
|
oldState?: unknown;
|
|
40
|
-
/**
|
|
40
|
+
/**
|
|
41
|
+
* Target record ID for single-record operations.
|
|
42
|
+
*
|
|
43
|
+
* SET ONLY UNDER `delete`. `_withHooks` assigns this key in the two
|
|
44
|
+
* `operation === 'delete'` branches and nowhere else, so on `get`, `list`,
|
|
45
|
+
* `create` and `update` the key is ABSENT -- not `undefined`-valued, absent.
|
|
46
|
+
* A hook rule written as `ctx.recordId === '<id>'` never fires on an update;
|
|
47
|
+
* the addressed id is in `ctx.params`. Tracked as abofs/stonyx-orm#242.
|
|
48
|
+
*
|
|
49
|
+
* @see AccessContext.recordId in ./types/orm-types.ts -- an identically-named
|
|
50
|
+
* key on an identically-shaped context object, and NOT interchangeable with
|
|
51
|
+
* this one: it is present on every route `auth()` classifies, and spells
|
|
52
|
+
* absence as `null` rather than `undefined`. They differ in coverage on four
|
|
53
|
+
* of five operations, not only in the absence spelling.
|
|
54
|
+
*/
|
|
41
55
|
recordId?: string | number;
|
|
42
56
|
/** Response data (available in after hooks). */
|
|
43
57
|
response?: unknown;
|
package/src/index.ts
CHANGED
|
@@ -28,6 +28,15 @@ export { default } from './main.js';
|
|
|
28
28
|
export { store, relationships } from './main.js';
|
|
29
29
|
export type { PersistErrorDetail } from './main.js';
|
|
30
30
|
export type { AccessContext, AccessFunction, AccessMethod, AccessOperation } from './types/orm-types.js'; // access() contract (#202)
|
|
31
|
+
export type { LinkageFilter } from './types/orm-types.js'; // linkage verdict contract (#234)
|
|
32
|
+
// The request-scoped linkage-verdict factory (#234). PUBLIC on purpose: the
|
|
33
|
+
// README tells a consumer serializing a `Record` outside the REST layer to pass
|
|
34
|
+
// their own resolved `linkage` option, and without an exported factory the only
|
|
35
|
+
// way to follow that advice is to write a SECOND reading of `access()` in
|
|
36
|
+
// consumer code -- the exact "unreviewed second authorization vocabulary" that
|
|
37
|
+
// src/access-verdict.ts exists to prevent, reproduced where no reviewer sees it
|
|
38
|
+
// drift. Give them the one interpreter instead of an invitation to fork it.
|
|
39
|
+
export { createLinkageFilter } from './access-verdict.js';
|
|
31
40
|
export { Model, View, Serializer }; // base classes
|
|
32
41
|
export { attr, belongsTo, hasMany, createRecord, updateRecord }; // helpers
|
|
33
42
|
export { count, avg, sum, min, max }; // aggregate helpers
|
package/src/orm-request.ts
CHANGED
|
@@ -69,6 +69,15 @@
|
|
|
69
69
|
* records under `model: 'owner'`, and the context gives no signal of that
|
|
70
70
|
* (abofs/stonyx-orm#196).
|
|
71
71
|
*
|
|
72
|
+
* SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237, AND KEPT FOR THE
|
|
73
|
+
* CONSTRAINT IT STATES RATHER THAN AS A DESCRIPTION OF THE CODE. The context
|
|
74
|
+
* now also carries `recordId` -- the DECODED route-parameter id, see
|
|
75
|
+
* `AccessContext.recordId` in ./types/orm-types.ts -- so the fixture's
|
|
76
|
+
* `/archived` deny IS expressible from the context alone, and the shipped
|
|
77
|
+
* sample no longer reads `request.path` at all. Retiring this wording WITH the
|
|
78
|
+
* measurement that retires it, rather than by deletion, is
|
|
79
|
+
* abofs/stonyx-orm#238.
|
|
80
|
+
*
|
|
72
81
|
* `record` IS NOT IN THIS CONTEXT, deliberately. `auth()` runs after route
|
|
73
82
|
* matching but BEFORE any handler executes (`@stonyx/rest-server`
|
|
74
83
|
* `src/request.ts:58-60`), so nothing has been fetched yet -- supplying a
|
|
@@ -158,6 +167,11 @@
|
|
|
158
167
|
* `/archived` SUB-PATH rule is still a string match, and abofs/stonyx-orm#228 is
|
|
159
168
|
* a sixth spelling that gets past it.
|
|
160
169
|
*
|
|
170
|
+
* SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237: the `/archived` rule is
|
|
171
|
+
* no longer a string match against the request target -- it compares the
|
|
172
|
+
* decoded `recordId` the framework supplies -- and abofs/stonyx-orm#228 is
|
|
173
|
+
* CLOSED. Retirement of this wording: abofs/stonyx-orm#238.
|
|
174
|
+
*
|
|
161
175
|
* An intermediate revision of the sample read `request.baseUrl` -- the mount
|
|
162
176
|
* Express ACTUALLY MATCHED. That closed all five variants (no query string,
|
|
163
177
|
* not mount-relative, unaffected by absolute-form, already carrying the
|
|
@@ -173,12 +187,26 @@
|
|
|
173
187
|
* does not decode, so `GET /owners/%61rchived` steps past it. See the
|
|
174
188
|
* normalisation paragraph below and abofs/stonyx-orm#228.
|
|
175
189
|
*
|
|
190
|
+
* SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237. Variant 3 lived in that
|
|
191
|
+
* one string comparison, and the comparison is gone: the sample compares the
|
|
192
|
+
* decoded `recordId`. Left standing rather than edited because the same
|
|
193
|
+
* "variant 3 survives" wording sits at four sites -- this header, README.md
|
|
194
|
+
* twice, and test/sample/access/global-access.ts -- three of which SHIP, so
|
|
195
|
+
* retiring one of four leaves the shipped copies contradicting each other.
|
|
196
|
+
* Retiring all four WITH their measurement is abofs/stonyx-orm#238.
|
|
197
|
+
*
|
|
176
198
|
* ONE READ OF ARGUMENT ONE SURVIVES, AND IT MUST: `request.path`. It is
|
|
177
199
|
* mount-relative and query-free, and it is for rules that distinguish SUB-PATHS
|
|
178
200
|
* beneath the mount. The context names which model and which verb, NOT which
|
|
179
201
|
* route, so the sample's `/archived` deny cannot be expressed from the context
|
|
180
202
|
* alone and a context-ONLY rewrite would silently turn that deny into an allow.
|
|
181
203
|
*
|
|
204
|
+
* SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237: NO read of argument one
|
|
205
|
+
* survives in the shipped sample. `recordId` names WHICH RECORD the route was
|
|
206
|
+
* addressed to, so the `/archived` deny is expressible from the context alone
|
|
207
|
+
* -- and it still must not be dropped; expressible is not optional. Retirement
|
|
208
|
+
* of this wording: abofs/stonyx-orm#238.
|
|
209
|
+
*
|
|
182
210
|
* NORMALISE THE WAY THE ROUTER DOES, AND CASE-FOLDING ALONE IS NOT THAT. The
|
|
183
211
|
* sample lower-cases before comparing, because a matcher stricter than the
|
|
184
212
|
* case-insensitive router can be stepped around. That closes the case gap only.
|
|
@@ -188,6 +216,20 @@
|
|
|
188
216
|
* sample and is tracked as abofs/stonyx-orm#228; the `.toLowerCase()` is not a
|
|
189
217
|
* complete normalisation recipe. Compare record ids at their real case.
|
|
190
218
|
*
|
|
219
|
+
* DO NOT FOLLOW THE PARAGRAPH ABOVE. SUPERSEDED 2026-09-01 BY
|
|
220
|
+
* abofs/stonyx-orm#236/#237, and flagged here rather than merely dated because
|
|
221
|
+
* it is an INSTRUCTION, not a stale observation. `.toLowerCase()` on the access
|
|
222
|
+
* path was measured WRONG IN BOTH DIRECTIONS AT ONCE: with a distinct owner
|
|
223
|
+
* seeded at `ARCHIVED`, `GET /owners/ARCHIVED` was a false DENY on the wrong
|
|
224
|
+
* record and `GET /owners/%41RCHIVED` a false ALLOW on that same record. A
|
|
225
|
+
* record id is a VALUE, not a literal route segment, and express's
|
|
226
|
+
* `case sensitive routing` governs literal segments only. Compare
|
|
227
|
+
* `context.recordId` AS IT ARRIVES: do not case-fold it, do not decode it, do
|
|
228
|
+
* not derive it from `request.path`. `AccessContext.recordId` in
|
|
229
|
+
* ./types/orm-types.ts is the contract and says "Do NOT case-fold it"; the same
|
|
230
|
+
* published tarball ships both files, and THIS paragraph is the one that is
|
|
231
|
+
* wrong. Retiring it WITH its measurement is abofs/stonyx-orm#238.
|
|
232
|
+
*
|
|
191
233
|
* `?? ''` is not a defence. It converts an absent request target into an empty
|
|
192
234
|
* string, which matches no collection, which falls through to the permission
|
|
193
235
|
* array -- a total grant. An input you cannot identify must DENY, and that
|
|
@@ -196,6 +238,12 @@
|
|
|
196
238
|
* argument one. The sample returns `false` for an absent `model` AND for an
|
|
197
239
|
* absent or non-string `request.path`, rather than falling through either way.
|
|
198
240
|
*
|
|
241
|
+
* SUPERSEDED 2026-09-01 BY abofs/stonyx-orm#236/#237 as to WHAT is guarded --
|
|
242
|
+
* the principle is unchanged. The sample no longer reads `request.path`, so it
|
|
243
|
+
* returns `false` for an absent `model` AND for an absent `recordId`
|
|
244
|
+
* (`undefined`, the one spelling `auth()` never produces). Retirement of this
|
|
245
|
+
* wording: abofs/stonyx-orm#238.
|
|
246
|
+
*
|
|
199
247
|
* THE REAL FIX IS abofs/stonyx-orm#202: `access()` should receive the model,
|
|
200
248
|
* the operation and the record. Prefer the array shape (`['read']`) or `false`
|
|
201
249
|
* until #202 lands; the function shape is what requires any matching at all.
|
|
@@ -221,6 +269,7 @@ import config from 'stonyx/config';
|
|
|
221
269
|
import log from 'stonyx/log';
|
|
222
270
|
import type { OrmRecord, AccessContext, AccessFunction, AccessMethod, AccessOperation } from './types/orm-types.js';
|
|
223
271
|
import { isOrmRecord, NO_FREE_ID_ERROR } from './utils.js';
|
|
272
|
+
import { interpretAccess, createLinkageFilter } from './access-verdict.js';
|
|
224
273
|
|
|
225
274
|
interface OrmRequest$ extends Request {
|
|
226
275
|
protocol?: string;
|
|
@@ -433,6 +482,13 @@ function buildResponse(
|
|
|
433
482
|
|
|
434
483
|
const includedRecords = collectIncludedRecords(recordOrRecords, includes);
|
|
435
484
|
if (includedRecords.length > 0) {
|
|
485
|
+
// NO `linkage` ARGUMENT, deliberately, and abofs/stonyx-orm#235 owns adding
|
|
486
|
+
// one. Until it does, a PERMITTED record here emits the full pre-#234
|
|
487
|
+
// document: `GET /animals/1?include=owner` filters the primary document's
|
|
488
|
+
// `owner.data` to `null` and then names `owner:angela` in `included`.
|
|
489
|
+
// Whether a resource reaches this array at all is a different question
|
|
490
|
+
// (membership, abofs/stonyx-orm#233) and closing that one does not close
|
|
491
|
+
// this one.
|
|
436
492
|
response.included = includedRecords.map(record => record.toJSON?.({ baseUrl }));
|
|
437
493
|
}
|
|
438
494
|
|
|
@@ -633,7 +689,14 @@ export default class OrmRequest extends Request {
|
|
|
633
689
|
if (queryFilterPredicate) recordsToReturn = recordsToReturn.filter(queryFilterPredicate as (record: OrmRecord) => boolean);
|
|
634
690
|
|
|
635
691
|
const baseUrl = getBaseUrl(request);
|
|
636
|
-
|
|
692
|
+
|
|
693
|
+
// ONE filter per REQUEST, not one per record: it carries the per-type
|
|
694
|
+
// verdict cache and the per-(type, id) decision cache, and both are
|
|
695
|
+
// worthless if it is rebuilt inside the map. Measured on this exact
|
|
696
|
+
// surface with no `include=`: 48 linkage entries collapse to 7 distinct
|
|
697
|
+
// (type, id) pairs.
|
|
698
|
+
const linkage = createLinkageFilter(request);
|
|
699
|
+
const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl, linkage }));
|
|
637
700
|
|
|
638
701
|
return buildResponse(data, request.query?.include, recordsToReturn, {
|
|
639
702
|
links: { self: `${baseUrl}/${pluralizedModel}` },
|
|
@@ -653,7 +716,25 @@ export default class OrmRequest extends Request {
|
|
|
653
716
|
const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
|
|
654
717
|
|
|
655
718
|
const baseUrl = getBaseUrl(request);
|
|
656
|
-
|
|
719
|
+
const linkage = createLinkageFilter(request);
|
|
720
|
+
|
|
721
|
+
// `buildResponse` is deliberately NOT given the linkage filter, and the
|
|
722
|
+
// residual that leaves is NOT the one #233 owns. Two different questions:
|
|
723
|
+
//
|
|
724
|
+
// - WHETHER A RESOURCE APPEARS in `included` at all is MEMBERSHIP ->
|
|
725
|
+
// abofs/stonyx-orm#233.
|
|
726
|
+
// - What a record already IN `included` may NAME is LINKAGE -- the same
|
|
727
|
+
// question #234 answers for the primary document -- and it is
|
|
728
|
+
// abofs/stonyx-orm#235, which also owns createHandler/updateHandler.
|
|
729
|
+
//
|
|
730
|
+
// The residual, stated so the next reader does not have to derive it:
|
|
731
|
+
// `buildResponse` calls `record.toJSON?.({ baseUrl })` with no `linkage`
|
|
732
|
+
// argument, so a PERMITTED record in `included` emits the full pre-#234
|
|
733
|
+
// document. Measured: `GET /animals/1?include=owner` returns
|
|
734
|
+
// `owner.data: null` on the primary document and `owner:angela` in
|
|
735
|
+
// `included`. One query parameter deep. Only the PRIMARY document's
|
|
736
|
+
// linkage is filtered here.
|
|
737
|
+
return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl, linkage }), request.query?.include, record, {
|
|
657
738
|
links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}` },
|
|
658
739
|
baseUrl
|
|
659
740
|
});
|
|
@@ -1283,14 +1364,21 @@ export default class OrmRequest extends Request {
|
|
|
1283
1364
|
const relatedData = record.__relationships[relationshipName];
|
|
1284
1365
|
const baseUrl = getBaseUrl(request);
|
|
1285
1366
|
|
|
1367
|
+
// LINKAGE ONLY. This filter decides which ids the emitted documents may
|
|
1368
|
+
// NAME in their own `relationships.*.data`; it does NOT decide whether
|
|
1369
|
+
// the related records themselves are served -- that is the parent-only
|
|
1370
|
+
// filtering this route has done since #190, and widening it to the
|
|
1371
|
+
// related record is abofs/stonyx-orm#196.
|
|
1372
|
+
const linkage = createLinkageFilter(request);
|
|
1373
|
+
|
|
1286
1374
|
let data: unknown;
|
|
1287
1375
|
if (info.isArray) {
|
|
1288
1376
|
// hasMany - return array
|
|
1289
1377
|
const related = Array.isArray(relatedData) ? relatedData.filter(isOrmRecord) : [];
|
|
1290
|
-
data = related.map(r => r.toJSON?.({ baseUrl }));
|
|
1378
|
+
data = related.map(r => r.toJSON?.({ baseUrl, linkage }));
|
|
1291
1379
|
} else {
|
|
1292
1380
|
// belongsTo - return single or null
|
|
1293
|
-
data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl }) : null;
|
|
1381
|
+
data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl, linkage }) : null;
|
|
1294
1382
|
}
|
|
1295
1383
|
|
|
1296
1384
|
return {
|
|
@@ -1389,10 +1477,53 @@ export default class OrmRequest extends Request {
|
|
|
1389
1477
|
// src/types/orm-types.ts. Nothing is fetched at this point and adding a
|
|
1390
1478
|
// lookup here would put a store read in the middle of an authorization
|
|
1391
1479
|
// path. The function return shape below IS the per-record hook.
|
|
1480
|
+
//
|
|
1481
|
+
// -------------------------------------------------------------------------
|
|
1482
|
+
// #236 -- `recordId`, the DECODED route-parameter id, for the same reason.
|
|
1483
|
+
//
|
|
1484
|
+
// WHICH RECORD is the third structural fact the framework already holds and
|
|
1485
|
+
// the consumer was left to re-derive, and re-deriving it failed OPEN. The
|
|
1486
|
+
// documented sample compared `request.path` -- the RAW, undecoded pathname
|
|
1487
|
+
// -- against a literal `/archived`, while the router DECODES `:id`. So
|
|
1488
|
+
// `GET /owners/%61rchived` walked past the deny and was dispatched as the
|
|
1489
|
+
// record `archived`: 200 with the record in full, and DELETE answered 204
|
|
1490
|
+
// with the record destroyed, unauthenticated. Four spellings measured, all
|
|
1491
|
+
// four through; 255 non-canonical spellings of that 8-character id decode
|
|
1492
|
+
// to the same key, so this was never a deny-list of one.
|
|
1493
|
+
//
|
|
1494
|
+
// TWO CONSUMER-SIDE NORMALISATIONS WERE MEASURED WRONG IN OPPOSITE
|
|
1495
|
+
// DIRECTIONS, which is the argument for doing it once, here.
|
|
1496
|
+
// `.toLowerCase()` case-folds a route-parameter VALUE on the axis that
|
|
1497
|
+
// governs literal SEGMENTS: with a distinct owner seeded at `ARCHIVED`,
|
|
1498
|
+
// `GET /owners/ARCHIVED` was a false DENY on the wrong record and
|
|
1499
|
+
// `GET /owners/%41RCHIVED` a false ALLOW on that same one.
|
|
1500
|
+
// `decodeURIComponent(request.path)` decodes THEN splits while the router
|
|
1501
|
+
// splits THEN decodes, so it over-denied `/owners/archived%2fx` -- 403 for
|
|
1502
|
+
// a genuinely distinct record. Failing closed there was luck, not design.
|
|
1503
|
+
//
|
|
1504
|
+
// `getId(request.params)` AND NOT `request.params.id`, for exactly the
|
|
1505
|
+
// reason `operation` is a `methodAccessMap` lookup: it is the SAME single
|
|
1506
|
+
// coercion the store lookup one layer down performs, so the predicate and
|
|
1507
|
+
// the dispatch cannot disagree about which record a request addresses.
|
|
1508
|
+
// The raw string would reintroduce that divergence on hex-shaped ids --
|
|
1509
|
+
// `GET /animals/0x2391` looks up record `9105`.
|
|
1510
|
+
//
|
|
1511
|
+
// NOTHING HERE PARSES THE REQUEST TARGET EITHER. `request.params` is what
|
|
1512
|
+
// the router matched, so a mount prefix, an absolute-form target, a query
|
|
1513
|
+
// string or a case-varied mount cannot move this value -- the same
|
|
1514
|
+
// guarantee `model` carries, by the same means.
|
|
1515
|
+
//
|
|
1516
|
+
// `null` and not `undefined` on a collection route, so the KEY IS ALWAYS
|
|
1517
|
+
// PRESENT -- the rule `operation`'s own docblock already establishes. A
|
|
1518
|
+
// context reaching a predicate WITHOUT the key therefore did not come from
|
|
1519
|
+
// here; it was hand-assembled by a caller resolving the predicate through
|
|
1520
|
+
// `Orm.instance.getAccess()`, and that absence stays deniable only because
|
|
1521
|
+
// `auth()` never produces it.
|
|
1392
1522
|
// -------------------------------------------------------------------------
|
|
1393
1523
|
const context: AccessContext = {
|
|
1394
1524
|
model: this.model,
|
|
1395
1525
|
operation: methodAccessMap[request.method],
|
|
1526
|
+
recordId: request.params && 'id' in request.params ? getId(request.params) : null,
|
|
1396
1527
|
};
|
|
1397
1528
|
|
|
1398
1529
|
let access: AccessMethod;
|
|
@@ -1407,24 +1538,23 @@ export default class OrmRequest extends Request {
|
|
|
1407
1538
|
return 403; // Forbidden
|
|
1408
1539
|
}
|
|
1409
1540
|
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
//
|
|
1418
|
-
//
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
//
|
|
1424
|
-
//
|
|
1425
|
-
//
|
|
1426
|
-
if (
|
|
1427
|
-
if (!permitted.includes(methodAccessMap[request.method])) return 403;
|
|
1541
|
+
// THE READING OF THE RETURN SHAPE LIVES IN ONE PLACE (#234).
|
|
1542
|
+
//
|
|
1543
|
+
// It used to be inline here, and it was the only copy, which was fine while
|
|
1544
|
+
// `auth()` was the only thing that had to ask. It is not any more: the
|
|
1545
|
+
// linkage path has to ask model X's predicate about model X's records while
|
|
1546
|
+
// servicing a request routed to model Y, and a second inline copy of these
|
|
1547
|
+
// six branches would be a second authorization vocabulary -- one that can
|
|
1548
|
+
// drift, and that reviewers would have to notice had drifted. The branch
|
|
1549
|
+
// order in `interpretAccess` is this block, moved, not rewritten.
|
|
1550
|
+
const verdict = interpretAccess(access, methodAccessMap[request.method]);
|
|
1551
|
+
|
|
1552
|
+
if (!verdict.granted) return 403;
|
|
1553
|
+
|
|
1554
|
+
// The function return shape is the per-record hook, and `state` is the
|
|
1555
|
+
// whole transport for it: @stonyx/rest-server memoises one state object per
|
|
1556
|
+
// request and hands the same one to `auth()` and to the handler.
|
|
1557
|
+
if (verdict.filter) state.filter = verdict.filter;
|
|
1428
1558
|
|
|
1429
1559
|
return undefined;
|
|
1430
1560
|
}
|