@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
package/dist/orm-request.js
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.
|
|
@@ -219,6 +267,7 @@ import { getBeforeHooks, getAfterHooks } from './hooks.js';
|
|
|
219
267
|
import config from 'stonyx/config';
|
|
220
268
|
import log from 'stonyx/log';
|
|
221
269
|
import { isOrmRecord, NO_FREE_ID_ERROR } from './utils.js';
|
|
270
|
+
import { interpretAccess, createLinkageFilter } from './access-verdict.js';
|
|
222
271
|
const methodAccessMap = {
|
|
223
272
|
GET: 'read',
|
|
224
273
|
POST: 'create',
|
|
@@ -388,6 +437,13 @@ function buildResponse(data, includeParam, recordOrRecords, options = {}) {
|
|
|
388
437
|
return response;
|
|
389
438
|
const includedRecords = collectIncludedRecords(recordOrRecords, includes);
|
|
390
439
|
if (includedRecords.length > 0) {
|
|
440
|
+
// NO `linkage` ARGUMENT, deliberately, and abofs/stonyx-orm#235 owns adding
|
|
441
|
+
// one. Until it does, a PERMITTED record here emits the full pre-#234
|
|
442
|
+
// document: `GET /animals/1?include=owner` filters the primary document's
|
|
443
|
+
// `owner.data` to `null` and then names `owner:angela` in `included`.
|
|
444
|
+
// Whether a resource reaches this array at all is a different question
|
|
445
|
+
// (membership, abofs/stonyx-orm#233) and closing that one does not close
|
|
446
|
+
// this one.
|
|
391
447
|
response.included = includedRecords.map(record => record.toJSON?.({ baseUrl }));
|
|
392
448
|
}
|
|
393
449
|
return response;
|
|
@@ -561,7 +617,13 @@ export default class OrmRequest extends Request {
|
|
|
561
617
|
if (queryFilterPredicate)
|
|
562
618
|
recordsToReturn = recordsToReturn.filter(queryFilterPredicate);
|
|
563
619
|
const baseUrl = getBaseUrl(request);
|
|
564
|
-
|
|
620
|
+
// ONE filter per REQUEST, not one per record: it carries the per-type
|
|
621
|
+
// verdict cache and the per-(type, id) decision cache, and both are
|
|
622
|
+
// worthless if it is rebuilt inside the map. Measured on this exact
|
|
623
|
+
// surface with no `include=`: 48 linkage entries collapse to 7 distinct
|
|
624
|
+
// (type, id) pairs.
|
|
625
|
+
const linkage = createLinkageFilter(request);
|
|
626
|
+
const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl, linkage }));
|
|
565
627
|
return buildResponse(data, request.query?.include, recordsToReturn, {
|
|
566
628
|
links: { self: `${baseUrl}/${pluralizedModel}` },
|
|
567
629
|
baseUrl
|
|
@@ -579,7 +641,24 @@ export default class OrmRequest extends Request {
|
|
|
579
641
|
const fieldsMap = parseFields(request.query);
|
|
580
642
|
const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
|
|
581
643
|
const baseUrl = getBaseUrl(request);
|
|
582
|
-
|
|
644
|
+
const linkage = createLinkageFilter(request);
|
|
645
|
+
// `buildResponse` is deliberately NOT given the linkage filter, and the
|
|
646
|
+
// residual that leaves is NOT the one #233 owns. Two different questions:
|
|
647
|
+
//
|
|
648
|
+
// - WHETHER A RESOURCE APPEARS in `included` at all is MEMBERSHIP ->
|
|
649
|
+
// abofs/stonyx-orm#233.
|
|
650
|
+
// - What a record already IN `included` may NAME is LINKAGE -- the same
|
|
651
|
+
// question #234 answers for the primary document -- and it is
|
|
652
|
+
// abofs/stonyx-orm#235, which also owns createHandler/updateHandler.
|
|
653
|
+
//
|
|
654
|
+
// The residual, stated so the next reader does not have to derive it:
|
|
655
|
+
// `buildResponse` calls `record.toJSON?.({ baseUrl })` with no `linkage`
|
|
656
|
+
// argument, so a PERMITTED record in `included` emits the full pre-#234
|
|
657
|
+
// document. Measured: `GET /animals/1?include=owner` returns
|
|
658
|
+
// `owner.data: null` on the primary document and `owner:angela` in
|
|
659
|
+
// `included`. One query parameter deep. Only the PRIMARY document's
|
|
660
|
+
// linkage is filtered here.
|
|
661
|
+
return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl, linkage }), request.query?.include, record, {
|
|
583
662
|
links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}` },
|
|
584
663
|
baseUrl
|
|
585
664
|
});
|
|
@@ -1166,15 +1245,21 @@ export default class OrmRequest extends Request {
|
|
|
1166
1245
|
return 404;
|
|
1167
1246
|
const relatedData = record.__relationships[relationshipName];
|
|
1168
1247
|
const baseUrl = getBaseUrl(request);
|
|
1248
|
+
// LINKAGE ONLY. This filter decides which ids the emitted documents may
|
|
1249
|
+
// NAME in their own `relationships.*.data`; it does NOT decide whether
|
|
1250
|
+
// the related records themselves are served -- that is the parent-only
|
|
1251
|
+
// filtering this route has done since #190, and widening it to the
|
|
1252
|
+
// related record is abofs/stonyx-orm#196.
|
|
1253
|
+
const linkage = createLinkageFilter(request);
|
|
1169
1254
|
let data;
|
|
1170
1255
|
if (info.isArray) {
|
|
1171
1256
|
// hasMany - return array
|
|
1172
1257
|
const related = Array.isArray(relatedData) ? relatedData.filter(isOrmRecord) : [];
|
|
1173
|
-
data = related.map(r => r.toJSON?.({ baseUrl }));
|
|
1258
|
+
data = related.map(r => r.toJSON?.({ baseUrl, linkage }));
|
|
1174
1259
|
}
|
|
1175
1260
|
else {
|
|
1176
1261
|
// belongsTo - return single or null
|
|
1177
|
-
data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl }) : null;
|
|
1262
|
+
data = isOrmRecord(relatedData) ? relatedData.toJSON?.({ baseUrl, linkage }) : null;
|
|
1178
1263
|
}
|
|
1179
1264
|
return {
|
|
1180
1265
|
links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}/${dasherizedName}` },
|
|
@@ -1269,10 +1354,53 @@ export default class OrmRequest extends Request {
|
|
|
1269
1354
|
// src/types/orm-types.ts. Nothing is fetched at this point and adding a
|
|
1270
1355
|
// lookup here would put a store read in the middle of an authorization
|
|
1271
1356
|
// path. The function return shape below IS the per-record hook.
|
|
1357
|
+
//
|
|
1358
|
+
// -------------------------------------------------------------------------
|
|
1359
|
+
// #236 -- `recordId`, the DECODED route-parameter id, for the same reason.
|
|
1360
|
+
//
|
|
1361
|
+
// WHICH RECORD is the third structural fact the framework already holds and
|
|
1362
|
+
// the consumer was left to re-derive, and re-deriving it failed OPEN. The
|
|
1363
|
+
// documented sample compared `request.path` -- the RAW, undecoded pathname
|
|
1364
|
+
// -- against a literal `/archived`, while the router DECODES `:id`. So
|
|
1365
|
+
// `GET /owners/%61rchived` walked past the deny and was dispatched as the
|
|
1366
|
+
// record `archived`: 200 with the record in full, and DELETE answered 204
|
|
1367
|
+
// with the record destroyed, unauthenticated. Four spellings measured, all
|
|
1368
|
+
// four through; 255 non-canonical spellings of that 8-character id decode
|
|
1369
|
+
// to the same key, so this was never a deny-list of one.
|
|
1370
|
+
//
|
|
1371
|
+
// TWO CONSUMER-SIDE NORMALISATIONS WERE MEASURED WRONG IN OPPOSITE
|
|
1372
|
+
// DIRECTIONS, which is the argument for doing it once, here.
|
|
1373
|
+
// `.toLowerCase()` case-folds a route-parameter VALUE on the axis that
|
|
1374
|
+
// governs literal SEGMENTS: with a distinct owner seeded at `ARCHIVED`,
|
|
1375
|
+
// `GET /owners/ARCHIVED` was a false DENY on the wrong record and
|
|
1376
|
+
// `GET /owners/%41RCHIVED` a false ALLOW on that same one.
|
|
1377
|
+
// `decodeURIComponent(request.path)` decodes THEN splits while the router
|
|
1378
|
+
// splits THEN decodes, so it over-denied `/owners/archived%2fx` -- 403 for
|
|
1379
|
+
// a genuinely distinct record. Failing closed there was luck, not design.
|
|
1380
|
+
//
|
|
1381
|
+
// `getId(request.params)` AND NOT `request.params.id`, for exactly the
|
|
1382
|
+
// reason `operation` is a `methodAccessMap` lookup: it is the SAME single
|
|
1383
|
+
// coercion the store lookup one layer down performs, so the predicate and
|
|
1384
|
+
// the dispatch cannot disagree about which record a request addresses.
|
|
1385
|
+
// The raw string would reintroduce that divergence on hex-shaped ids --
|
|
1386
|
+
// `GET /animals/0x2391` looks up record `9105`.
|
|
1387
|
+
//
|
|
1388
|
+
// NOTHING HERE PARSES THE REQUEST TARGET EITHER. `request.params` is what
|
|
1389
|
+
// the router matched, so a mount prefix, an absolute-form target, a query
|
|
1390
|
+
// string or a case-varied mount cannot move this value -- the same
|
|
1391
|
+
// guarantee `model` carries, by the same means.
|
|
1392
|
+
//
|
|
1393
|
+
// `null` and not `undefined` on a collection route, so the KEY IS ALWAYS
|
|
1394
|
+
// PRESENT -- the rule `operation`'s own docblock already establishes. A
|
|
1395
|
+
// context reaching a predicate WITHOUT the key therefore did not come from
|
|
1396
|
+
// here; it was hand-assembled by a caller resolving the predicate through
|
|
1397
|
+
// `Orm.instance.getAccess()`, and that absence stays deniable only because
|
|
1398
|
+
// `auth()` never produces it.
|
|
1272
1399
|
// -------------------------------------------------------------------------
|
|
1273
1400
|
const context = {
|
|
1274
1401
|
model: this.model,
|
|
1275
1402
|
operation: methodAccessMap[request.method],
|
|
1403
|
+
recordId: request.params && 'id' in request.params ? getId(request.params) : null,
|
|
1276
1404
|
};
|
|
1277
1405
|
let access;
|
|
1278
1406
|
try {
|
|
@@ -1285,26 +1413,23 @@ export default class OrmRequest extends Request {
|
|
|
1285
1413
|
log.error?.(`[@stonyx/orm] access() threw for model "${this.model}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
|
|
1286
1414
|
return 403; // Forbidden
|
|
1287
1415
|
}
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
//
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
// granted DELETE. A bare string is one permission, not a grant of all four.
|
|
1300
|
-
const permitted = typeof access === 'string' ? [access] : access;
|
|
1301
|
-
// Anything that is not a permission array by this point -- an object, a
|
|
1302
|
-
// number, a Symbol -- is a consumer mistake, and the only safe reading of a
|
|
1303
|
-
// shape the contract does not define is a denial. Fail CLOSED.
|
|
1304
|
-
if (!Array.isArray(permitted))
|
|
1305
|
-
return 403;
|
|
1306
|
-
if (!permitted.includes(methodAccessMap[request.method]))
|
|
1416
|
+
// THE READING OF THE RETURN SHAPE LIVES IN ONE PLACE (#234).
|
|
1417
|
+
//
|
|
1418
|
+
// It used to be inline here, and it was the only copy, which was fine while
|
|
1419
|
+
// `auth()` was the only thing that had to ask. It is not any more: the
|
|
1420
|
+
// linkage path has to ask model X's predicate about model X's records while
|
|
1421
|
+
// servicing a request routed to model Y, and a second inline copy of these
|
|
1422
|
+
// six branches would be a second authorization vocabulary -- one that can
|
|
1423
|
+
// drift, and that reviewers would have to notice had drifted. The branch
|
|
1424
|
+
// order in `interpretAccess` is this block, moved, not rewritten.
|
|
1425
|
+
const verdict = interpretAccess(access, methodAccessMap[request.method]);
|
|
1426
|
+
if (!verdict.granted)
|
|
1307
1427
|
return 403;
|
|
1428
|
+
// The function return shape is the per-record hook, and `state` is the
|
|
1429
|
+
// whole transport for it: @stonyx/rest-server memoises one state object per
|
|
1430
|
+
// request and hands the same one to `auth()` and to the handler.
|
|
1431
|
+
if (verdict.filter)
|
|
1432
|
+
state.filter = verdict.filter;
|
|
1308
1433
|
return undefined;
|
|
1309
1434
|
}
|
|
1310
1435
|
}
|
package/dist/record.d.ts
CHANGED
|
@@ -1,7 +1,23 @@
|
|
|
1
1
|
import type Serializer from './serializer.js';
|
|
2
|
+
import type { LinkageFilter } from './types/orm-types.js';
|
|
2
3
|
interface ToJSONOptions {
|
|
3
4
|
fields?: Set<string>;
|
|
4
5
|
baseUrl?: string;
|
|
6
|
+
/**
|
|
7
|
+
* An ALREADY-RESOLVED linkage decision, supplied by a caller that holds the
|
|
8
|
+
* request (abofs/stonyx-orm#234). Returning `false` for a related record
|
|
9
|
+
* drops that record's `{ type, id }` from `relationships.*.data`.
|
|
10
|
+
*
|
|
11
|
+
* This method APPLIES a verdict; it never RESOLVES one -- see
|
|
12
|
+
* `src/access-verdict.ts` for the two measured reasons it cannot. ABSENT is
|
|
13
|
+
* the default and the default is TODAY'S DOCUMENT, unchanged, because
|
|
14
|
+
* `toJSON` is also the `JSON.stringify` hook and an implicit caller has no
|
|
15
|
+
* syntactic place to pass this (abofs/stonyx-orm#230).
|
|
16
|
+
*
|
|
17
|
+
* ABSENT and UNUSABLE are read differently, and the difference is a security
|
|
18
|
+
* decision -- see the three-way reading at the call site below.
|
|
19
|
+
*/
|
|
20
|
+
linkage?: LinkageFilter;
|
|
5
21
|
}
|
|
6
22
|
interface SerializeOptions {
|
|
7
23
|
update?: boolean;
|
package/dist/record.js
CHANGED
|
@@ -1,7 +1,26 @@
|
|
|
1
1
|
import { store } from '@stonyx/orm';
|
|
2
|
+
import log from 'stonyx/log';
|
|
2
3
|
import { getComputedProperties } from "./serializer.js";
|
|
3
4
|
import { camelCaseToKebabCase } from '@stonyx/utils/string';
|
|
4
5
|
import { getPluralName } from './plural-registry.js';
|
|
6
|
+
/**
|
|
7
|
+
* Name a non-boolean `linkage` return for the one log line that reports it.
|
|
8
|
+
*
|
|
9
|
+
* A thenable is called out BY NAME because it is the shape a consumer produces
|
|
10
|
+
* by accident -- an `async` resolver, or one that returns the promise of an
|
|
11
|
+
* authorization lookup -- and the one whose truthiness silently GRANTED every
|
|
12
|
+
* relationship before the ANSWER was checked (abofs/stonyx-orm#234).
|
|
13
|
+
*/
|
|
14
|
+
function describeNonVerdict(verdict) {
|
|
15
|
+
if (verdict === null)
|
|
16
|
+
return 'null';
|
|
17
|
+
if (Array.isArray(verdict))
|
|
18
|
+
return 'an array';
|
|
19
|
+
if ((typeof verdict === 'object' || typeof verdict === 'function')
|
|
20
|
+
&& typeof verdict.then === 'function')
|
|
21
|
+
return 'a Promise (or other thenable)';
|
|
22
|
+
return `a value of type ${typeof verdict}`;
|
|
23
|
+
}
|
|
5
24
|
export default class Record {
|
|
6
25
|
/** @private */
|
|
7
26
|
__data = {};
|
|
@@ -65,7 +84,13 @@ export default class Record {
|
|
|
65
84
|
toJSON(options = {}) {
|
|
66
85
|
if (!this.__serialized)
|
|
67
86
|
throw new Error('Record must be serialized before being converted to JSON');
|
|
68
|
-
|
|
87
|
+
// DESTRUCTURED FROM A VALUE THAT IS NOT ALWAYS AN OBJECT. `toJSON` is the
|
|
88
|
+
// ECMAScript serialization hook, so `JSON.stringify({ data: record })`
|
|
89
|
+
// arrives here as `toJSON('data')` -- a STRING in the options slot.
|
|
90
|
+
// Destructuring a string yields `undefined` for every key, which is exactly
|
|
91
|
+
// the no-argument default, so the implicit path keeps working and keeps
|
|
92
|
+
// emitting today's document (abofs/stonyx-orm#230).
|
|
93
|
+
const { fields, baseUrl, linkage } = options;
|
|
69
94
|
const { __data: data } = this;
|
|
70
95
|
const modelName = this.__model.__name;
|
|
71
96
|
const pluralizedModelName = getPluralName(modelName);
|
|
@@ -84,12 +109,133 @@ export default class Record {
|
|
|
84
109
|
continue;
|
|
85
110
|
attributes[key] = getter.call(this);
|
|
86
111
|
}
|
|
112
|
+
// `linkage` is a PUBLIC option -- it is on `OrmRecord.toJSON`
|
|
113
|
+
// (src/types/orm-types.ts) and the README tells consumers to pass one -- so
|
|
114
|
+
// it arrives from outside this package, may be ANY value, and whatever it
|
|
115
|
+
// is, it gets INVOKED here. That makes this the trust boundary, and it was
|
|
116
|
+
// the LAX side of one: the internal `createLinkageFilter` coerces and
|
|
117
|
+
// try/catches the consumer predicate it wraps, while this -- the site that
|
|
118
|
+
// consumes the PUBLIC option -- did neither.
|
|
119
|
+
//
|
|
120
|
+
// THREE QUESTIONS. Every wrong answer below was measured, on a two-
|
|
121
|
+
// relationship record, emitting the full pre-#234 document or throwing out
|
|
122
|
+
// of `JSON.stringify`.
|
|
123
|
+
//
|
|
124
|
+
// 1. IS IT SUPPLIED? ABSENT (`undefined`) means no verdict was supplied:
|
|
125
|
+
// emit today's document. Load-bearing and asserted (AC5/AC5b) --
|
|
126
|
+
// `toJSON` is also the `JSON.stringify` hook, so the implicit caller
|
|
127
|
+
// arrives as `toJSON('data')`, a STRING, which destructures to
|
|
128
|
+
// `undefined` here (abofs/stonyx-orm#230).
|
|
129
|
+
//
|
|
130
|
+
// 2. IS ITS SHAPE USABLE? `[object Function]` only, because
|
|
131
|
+
// `typeof x === 'function'` is NOT the question "can this answer a
|
|
132
|
+
// synchronous boolean".
|
|
133
|
+
//
|
|
134
|
+
// A NON-FUNCTION denies. Reading it as absent is what `!linkage ||`
|
|
135
|
+
// did, and a resolver returning `null` because it could not resolve a
|
|
136
|
+
// session is the natural shape of that value and the fail-closed
|
|
137
|
+
// INTENT -- measured, `toJSON({ linkage: null })` emitted the full
|
|
138
|
+
// pre-#234 linkage with no signal, byte-identical to unpatched dev.
|
|
139
|
+
//
|
|
140
|
+
// AN `AsyncFunction`, `GeneratorFunction` or `AsyncGeneratorFunction`
|
|
141
|
+
// denies for that SAME reason, one branch over -- and a `typeof`-only
|
|
142
|
+
// check left the whole defect standing there. `async (type, r) =>
|
|
143
|
+
// false` returns a PROMISE, a promise is TRUTHY, so every relationship
|
|
144
|
+
// was emitted in full with ZERO log, again byte-identical to unpatched
|
|
145
|
+
// dev. An awaited authorization lookup is at least as natural a
|
|
146
|
+
// resolver as a nullish one -- the README's own Consumer Contracts
|
|
147
|
+
// section points consumers at queue payloads and websocket frames,
|
|
148
|
+
// where lookups are routinely awaited -- and it landed on the GRANT
|
|
149
|
+
// side of the same branch the `null` reading closed.
|
|
150
|
+
//
|
|
151
|
+
// 3. IS ITS ANSWER A VERDICT? It must BE a boolean, not merely coerce to
|
|
152
|
+
// one. `Boolean(...)` -- the coercion `createLinkageFilter` applies to
|
|
153
|
+
// a consumer `access()` predicate, whose truthy contract predates this
|
|
154
|
+
// option and is deliberately NOT changed -- is not enough here, and
|
|
155
|
+
// was measured not to be: with `Boolean(...)` plus a try/catch in
|
|
156
|
+
// place, `async () => false`, `function* () {}`,
|
|
157
|
+
// `() => Promise.resolve(false)`, `() => ({})` and `() => 'no'` ALL
|
|
158
|
+
// still emitted the full pre-#234 linkage with no log, because
|
|
159
|
+
// truthiness is what they already had. A non-boolean is a resolver
|
|
160
|
+
// that did not answer, and the only safe reading of a non-answer is a
|
|
161
|
+
// denial.
|
|
162
|
+
//
|
|
163
|
+
// AND IT NEVER THROWS -- which is now true rather than only written down.
|
|
164
|
+
// A throw here escapes the enclosing `JSON.stringify` and takes
|
|
165
|
+
// `console.log` and `Orm.db.save()`'s neighbours with it, a far worse
|
|
166
|
+
// failure mode than a status. `class Klass {}`, `Klass.bind(null)` and any
|
|
167
|
+
// predicate that dereferences something undefined were all measured raising
|
|
168
|
+
// out of the `stringify`; all three are caught and denied.
|
|
169
|
+
//
|
|
170
|
+
// Logged once per DOCUMENT, not once per relationship key or per related
|
|
171
|
+
// record: an emptied relationship is deliberately indistinguishable from a
|
|
172
|
+
// genuinely empty one on the wire, so the log is the ONLY signal a consumer
|
|
173
|
+
// whose resolver quietly returned `null`, or a promise, will ever get.
|
|
174
|
+
const linkageSupplied = linkage !== undefined;
|
|
175
|
+
// Read the tag DEFENSIVELY. `Object.prototype.toString` consults
|
|
176
|
+
// `Symbol.toStringTag`, so a Proxy with a throwing `get` trap would throw
|
|
177
|
+
// out of the validation whose entire job is that nothing throws.
|
|
178
|
+
let linkageShape = 'a non-function';
|
|
179
|
+
if (typeof linkage === 'function') {
|
|
180
|
+
try {
|
|
181
|
+
linkageShape = Object.prototype.toString.call(linkage);
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
linkageShape = '[object Unreadable]';
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const linkageUsable = linkageShape === '[object Function]';
|
|
188
|
+
let linkageReported = false;
|
|
189
|
+
const denyAllLinkage = (reason) => {
|
|
190
|
+
if (linkageReported)
|
|
191
|
+
return;
|
|
192
|
+
linkageReported = true;
|
|
193
|
+
log.error?.(`[@stonyx/orm] toJSON() received an unusable \`linkage\` option -- ${reason}, so ALL relationship linkage on this \`${modelName}\` document is denied.`);
|
|
194
|
+
};
|
|
195
|
+
if (linkageSupplied && !linkageUsable) {
|
|
196
|
+
denyAllLinkage(typeof linkage !== 'function'
|
|
197
|
+
? `it is of type ${linkage === null ? 'null' : typeof linkage} and it must be a function`
|
|
198
|
+
: `it is ${linkageShape} and it must be a SYNCHRONOUS function -- \`toJSON\` is the \`JSON.stringify\` hook and cannot await a verdict`);
|
|
199
|
+
}
|
|
200
|
+
const linkageVerdict = !linkageSupplied
|
|
201
|
+
? undefined
|
|
202
|
+
: linkageUsable ? linkage : () => false;
|
|
203
|
+
// Applied per related record, alongside the existing `__model` liveness
|
|
204
|
+
// check, and producing exactly the shapes that check already produces: a
|
|
205
|
+
// dropped hasMany member leaves `data: []`, a dropped belongsTo leaves
|
|
206
|
+
// `data: null`. Both already ship -- a genuinely-empty hasMany emits
|
|
207
|
+
// `data: []` with links, and a cleaned belongsTo emits `data: null` -- so a
|
|
208
|
+
// filtered relationship is BYTE-IDENTICAL to an empty one and there is no
|
|
209
|
+
// new wire shape and no oracle.
|
|
210
|
+
const isLinkable = (r) => {
|
|
211
|
+
if (!linkageVerdict)
|
|
212
|
+
return true;
|
|
213
|
+
try {
|
|
214
|
+
const verdict = linkageVerdict(r.__model.__name, r);
|
|
215
|
+
if (typeof verdict === 'boolean')
|
|
216
|
+
return verdict;
|
|
217
|
+
denyAllLinkage(`it answered with ${describeNonVerdict(verdict)} rather than a boolean`);
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
// Building the report is itself a throw site -- `throw Symbol('x')`
|
|
221
|
+
// makes `String(error)` throw, and a getter on `.message` can throw --
|
|
222
|
+
// and a throw from the reporter would escape the catch that exists so
|
|
223
|
+
// that nothing escapes.
|
|
224
|
+
let detail = 'a value that could not be described';
|
|
225
|
+
try {
|
|
226
|
+
detail = error instanceof Error ? error.message : String(error);
|
|
227
|
+
}
|
|
228
|
+
catch { /* keep the fallback -- the denial matters, the text does not */ }
|
|
229
|
+
denyAllLinkage(`it threw (${detail})`);
|
|
230
|
+
}
|
|
231
|
+
return false;
|
|
232
|
+
};
|
|
87
233
|
for (const [key, childRecord] of Object.entries(this.__relationships)) {
|
|
88
234
|
if (fields && !fields.has(key))
|
|
89
235
|
continue;
|
|
90
236
|
const relationshipData = Array.isArray(childRecord)
|
|
91
|
-
? childRecord.filter((r) => r?.__model).map((r) => ({ type: r.__model.__name, id: r.id }))
|
|
92
|
-
: (childRecord && childRecord.__model) ? { type: childRecord.__model.__name, id: childRecord.id } : null;
|
|
237
|
+
? childRecord.filter((r) => r?.__model).filter(isLinkable).map((r) => ({ type: r.__model.__name, id: r.id }))
|
|
238
|
+
: (childRecord && childRecord.__model && isLinkable(childRecord)) ? { type: childRecord.__model.__name, id: childRecord.id } : null;
|
|
93
239
|
// Dasherize the key for URL paths (e.g., accessLinks -> access-links)
|
|
94
240
|
const dasherizedKey = camelCaseToKebabCase(key);
|
|
95
241
|
relationships[dasherizedKey] = { data: relationshipData };
|
|
@@ -87,9 +87,18 @@ export interface OrmRecord {
|
|
|
87
87
|
__pendingSqlId?: boolean;
|
|
88
88
|
};
|
|
89
89
|
__relationships: Record<string, unknown>;
|
|
90
|
+
/**
|
|
91
|
+
* `linkage` is an ALREADY-RESOLVED decision supplied by a caller that holds
|
|
92
|
+
* the request (abofs/stonyx-orm#234): return `false` for a related record and
|
|
93
|
+
* its `{ type, id }` is dropped from `relationships.*.data`. Omitting it is
|
|
94
|
+
* the default, and the default is the pre-#234 document unchanged -- this
|
|
95
|
+
* method is also the `JSON.stringify` hook, so an implicit caller has no
|
|
96
|
+
* syntactic place to pass it (abofs/stonyx-orm#230).
|
|
97
|
+
*/
|
|
90
98
|
toJSON?(options?: {
|
|
91
99
|
fields?: Set<string>;
|
|
92
100
|
baseUrl?: string;
|
|
101
|
+
linkage?: LinkageFilter;
|
|
93
102
|
}): Record<string, unknown>;
|
|
94
103
|
[key: string]: unknown;
|
|
95
104
|
}
|
|
@@ -242,6 +251,101 @@ export interface AccessContext {
|
|
|
242
251
|
* from one that classified the request and found nothing.
|
|
243
252
|
*/
|
|
244
253
|
operation: AccessOperation | undefined;
|
|
254
|
+
/**
|
|
255
|
+
* The record this route was addressed to, as the store key -- or `null` on a
|
|
256
|
+
* collection route, which is addressed to no record (abofs/stonyx-orm#236).
|
|
257
|
+
*
|
|
258
|
+
* IT IS ALREADY DECODED, AND THAT IS THE WHOLE POINT. Express decodes route
|
|
259
|
+
* PARAMETERS while leaving `request.path` raw, so a consumer comparing
|
|
260
|
+
* `request.path` against a literal compares an undecoded string against a
|
|
261
|
+
* decoded dispatch. `GET /owners/%61rchived` reached such a comparison as
|
|
262
|
+
* `/%61rchived`, walked past a `/archived` deny, and was dispatched as the
|
|
263
|
+
* record `archived` -- 200 with the record in full, and `DELETE` destroyed
|
|
264
|
+
* it, unauthenticated. 255 non-canonical spellings of an 8-character id
|
|
265
|
+
* decode to the same key, so a deny-list of spellings is the wrong shape.
|
|
266
|
+
*
|
|
267
|
+
* SO DO NOT NORMALISE THIS, AND DO NOT NORMALISE ANYTHING ELSE INSTEAD:
|
|
268
|
+
*
|
|
269
|
+
* - Do NOT decode it. Express decodes exactly ONCE, which is what a route
|
|
270
|
+
* parameter means. `GET /owners/%2561rchived` is the legitimate id
|
|
271
|
+
* `%61rchived`, not a second-order spelling of `archived`; a predicate that
|
|
272
|
+
* decoded until stable would deny a record it was never asked about.
|
|
273
|
+
* - Do NOT case-fold it. A record id is a VALUE, not a literal route segment,
|
|
274
|
+
* and express's `case sensitive routing` governs literal segments only.
|
|
275
|
+
* With a distinct owner seeded at `ARCHIVED`, `.toLowerCase()` was measured
|
|
276
|
+
* wrong in BOTH directions at once: `GET /owners/ARCHIVED` 403 (a false
|
|
277
|
+
* deny, on the wrong record) and `GET /owners/%41RCHIVED` 200 (a false
|
|
278
|
+
* allow, on that same record).
|
|
279
|
+
* - Do NOT derive it from `request.path` or the request target. Decoding the
|
|
280
|
+
* whole path decodes THEN splits, while the router splits THEN decodes, so
|
|
281
|
+
* `/owners/archived%2fx` -- a genuinely distinct record whose id is
|
|
282
|
+
* `archived/x` -- was measured over-denied 403.
|
|
283
|
+
*
|
|
284
|
+
* IT IS `getId(request.params)`, BYTE FOR BYTE -- the same single coercion
|
|
285
|
+
* the store lookup uses, exactly as `operation` is the same `methodAccessMap`
|
|
286
|
+
* lookup the permission-array branch uses. The predicate and the dispatch
|
|
287
|
+
* therefore cannot disagree about which record a request addresses. Handing
|
|
288
|
+
* over the raw `request.params.id` instead would reintroduce that divergence
|
|
289
|
+
* on hex-shaped ids: `GET /animals/0x2391` looks up record `9105`.
|
|
290
|
+
*
|
|
291
|
+
* It inherits abofs/stonyx-orm#209 along with that coercion -- on a model
|
|
292
|
+
* declaring `id = attr('string')`, `'9107'` arrives here as the number
|
|
293
|
+
* `9107`. That is consistency WITH THE LOOKUP, which is the property this key
|
|
294
|
+
* exists to buy; it is not a defect to repair here.
|
|
295
|
+
*
|
|
296
|
+
* `null`, not `undefined`, on a collection route -- and the KEY IS ALWAYS
|
|
297
|
+
* PRESENT, the same rule `operation` states above. `auth()` always sets it,
|
|
298
|
+
* so a context arriving WITHOUT the key did not come from `auth()`: it was
|
|
299
|
+
* hand-assembled by a caller resolving the predicate through
|
|
300
|
+
* `Orm.instance.getAccess()`. That absence stays a distinguishable, deniable
|
|
301
|
+
* signal only because the framework never produces it.
|
|
302
|
+
*
|
|
303
|
+
* IT DISAGREES WITH THE HOOK VOCABULARY, AND NOT ONLY ON THE ABSENCE
|
|
304
|
+
* SPELLING. `HookContext.recordId` (`src/hooks.ts`) is an identically-named
|
|
305
|
+
* key on an identically-shaped context object, which is the exact
|
|
306
|
+
* configuration that makes `operation` fail-open shaped -- a hook sees
|
|
307
|
+
* `'get'` where `access()` sees `'read'`. An earlier revision of THIS
|
|
308
|
+
* docblock asserted the opposite ("here they AGREE... they differ in ONE way
|
|
309
|
+
* and it is the absence spelling"). That was measured false, in the fail-open
|
|
310
|
+
* direction, and it is corrected here rather than deleted.
|
|
311
|
+
*
|
|
312
|
+
* MEASURED over the live dispatch, before-hooks registered for all five
|
|
313
|
+
* operations on one model:
|
|
314
|
+
*
|
|
315
|
+
* before:list key ABSENT ('recordId' in context === false)
|
|
316
|
+
* before:get key ABSENT params={"id":"visible1"}
|
|
317
|
+
* before:create key ABSENT
|
|
318
|
+
* before:update key ABSENT params={"id":"visible2"}
|
|
319
|
+
* before:delete recordId="visible3"
|
|
320
|
+
* after:delete recordId="visible3"
|
|
321
|
+
*
|
|
322
|
+
* `_withHooks` assigns `context.recordId` at exactly TWO sites in
|
|
323
|
+
* `src/orm-request.ts`, and BOTH sit inside an `operation === 'delete'`
|
|
324
|
+
* branch. So the two keys differ in COVERAGE, on four of five operations: on
|
|
325
|
+
* a hook context the key is absent for get, list, create and update, while
|
|
326
|
+
* this key is present on every route `auth()` classifies. The absence
|
|
327
|
+
* spelling is the smaller half of the difference, not the whole of it.
|
|
328
|
+
*
|
|
329
|
+
* AND THAT INVERTS THE ARGUMENT ABOVE WHEN IT IS READ ACROSS THE TWO. Here,
|
|
330
|
+
* a missing `recordId` means "did not come from `auth()`" and is deniable.
|
|
331
|
+
* On a hook context it means "this is a get / list / create / update" -- an
|
|
332
|
+
* ordinary request. A consumer who writes the hook-side half of the same
|
|
333
|
+
* rule --
|
|
334
|
+
*
|
|
335
|
+
* beforeHook('update', 'owner', ctx => ctx.recordId === 'archived' ? 403 : undefined)
|
|
336
|
+
*
|
|
337
|
+
* -- gets a deny that NEVER FIRES: measured, `PATCH /owners/visible2` -> 200,
|
|
338
|
+
* with `ctx.recordId === undefined` while the addressed record sits in
|
|
339
|
+
* `ctx.params`. The hook side is abofs/stonyx-orm#242 and is deliberately not
|
|
340
|
+
* repaired here. A predicate must not read `undefined` here as "collection",
|
|
341
|
+
* and nothing in this contract makes it safe to read the two keys as one key.
|
|
342
|
+
*
|
|
343
|
+
* IT NAMES WHICH RECORD, NOT WHICH SURFACE. `GET /owners/gina`,
|
|
344
|
+
* `GET /owners/gina/pets` and `GET /owners/gina/relationships/pets` all
|
|
345
|
+
* carry `recordId: 'gina'`; the related-resource gap is abofs/stonyx-orm#196
|
|
346
|
+
* and is untouched by this key.
|
|
347
|
+
*/
|
|
348
|
+
recordId: string | number | null;
|
|
245
349
|
}
|
|
246
350
|
/**
|
|
247
351
|
* A consumer `access()` predicate.
|
|
@@ -263,3 +367,21 @@ export interface AccessContext {
|
|
|
263
367
|
* context gets `TS2554: Expected 2 arguments, but got 1`.
|
|
264
368
|
*/
|
|
265
369
|
export type AccessFunction = (request: unknown, context: AccessContext) => AccessMethod;
|
|
370
|
+
/**
|
|
371
|
+
* A resolved, request-scoped linkage decision: may `record` of model `type` be
|
|
372
|
+
* NAMED, by id, inside another model's document (abofs/stonyx-orm#234)?
|
|
373
|
+
*
|
|
374
|
+
* Arity is `(type, record)` and not `(type, id)` because the per-record filter
|
|
375
|
+
* a consumer returns is handed the RECORD -- this repo's own fixture reads
|
|
376
|
+
* `record.owner?.id`, not just `record.id`. The `(type, id)` pair is the CACHE
|
|
377
|
+
* key inside `createLinkageFilter`, not the input.
|
|
378
|
+
*
|
|
379
|
+
* DECLARED HERE, with the rest of the access vocabulary, and imported by every
|
|
380
|
+
* site that names it. It had three structurally-identical hand-written copies
|
|
381
|
+
* (`access-verdict.ts`, `record.ts`, `OrmRecord.toJSON` below) bridged to each
|
|
382
|
+
* other by nothing, so a drift in nullability or a widening of `type` would
|
|
383
|
+
* have landed on one and not the others -- which is the same "second,
|
|
384
|
+
* unreviewed vocabulary" failure `src/access-verdict.ts` exists to prevent, one
|
|
385
|
+
* level up in the type system.
|
|
386
|
+
*/
|
|
387
|
+
export type LinkageFilter = (type: string, record: unknown) => boolean;
|