@stonyx/orm 0.3.2-beta.153 → 0.3.2-beta.155

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/dist/main.js CHANGED
@@ -38,6 +38,51 @@ export default class Orm {
38
38
  views = {};
39
39
  transforms = { ...baseTransforms };
40
40
  warnings = new Set();
41
+ /**
42
+ * Model name -> the `access` predicate of the access class that CLAIMS that
43
+ * model (abofs/stonyx-orm#202).
44
+ *
45
+ * Not "that model's own predicate". One access class may claim many models
46
+ * -- `GlobalAccess` in this repo's fixtures declares five, and `models = '*'`
47
+ * claims every model in the store -- and it declares ONE `access` method, so
48
+ * the same function object is registered under every one of those keys.
49
+ * `getAccess('owner') === getAccess('animal')` is `true` there. The
50
+ * one-to-one guarantee below is key -> function, never function -> model,
51
+ * and a caller must not read a resolved predicate as being animal-specific.
52
+ * What makes the ANSWER model-specific is the context the caller passes and
53
+ * the predicate actually reading it -- see {@link Orm#getAccess}.
54
+ *
55
+ * NAMED FOR WHAT IT HOLDS. It was `accessFiles` through review, inherited
56
+ * from the function-local in `setup-rest-server.ts` where the values came
57
+ * straight out of `forEachFileImport` and "files" was defensible. The values
58
+ * are `AccessFunction`s, and the sibling public registries on this class
59
+ * (`models`, `serializers`, `views`, `transforms`) are all plural nouns of
60
+ * the thing held. Renamed here because #202 is the last moment it is free.
61
+ *
62
+ * Populated by `setup-rest-server.ts` at boot, from the access classes under
63
+ * `config.orm.paths.access`, BEFORE any route is mounted -- so it is complete
64
+ * and reachable before the first request can be served. The mapping is
65
+ * one-to-one by construction: setup-rest-server throws if two access classes
66
+ * claim the same model.
67
+ *
68
+ * Keys are model names as declared and stored (kebab-case, e.g.
69
+ * `'phone-number'`), NOT pluralised or mount-prefixed route names.
70
+ *
71
+ * WHY THIS EXISTS AS A FIELD. It used to be a function-local in
72
+ * setup-rest-server that was discarded when that function returned, so at
73
+ * request time there was no way to get from a model name to that model's
74
+ * predicate at all. Each `OrmRequest` held only its OWN model's predicate.
75
+ * That made cross-model authorization -- asking model X's predicate about a
76
+ * request routed to model Y -- inexpressible, which is the capability
77
+ * abofs/stonyx-orm#196 and abofs/stonyx-orm#207 are built on.
78
+ *
79
+ * Empty when the REST server is disabled, and PARTIAL when one access file
80
+ * failed to load (`setup-rest-server.ts` catches, warns and assigns whatever
81
+ * it had). So a missing key does NOT mean the model has no access class.
82
+ * Prefer {@link Orm#getAccess} over indexing this directly -- it is guarded
83
+ * against the prototype chain and this is not.
84
+ */
85
+ accessFunctions = {};
41
86
  options;
42
87
  sqlDb;
43
88
  db;
@@ -145,6 +190,80 @@ export default class Orm {
145
190
  Orm.ready = await Promise.all(promises);
146
191
  Orm.initialized = true;
147
192
  }
193
+ /**
194
+ * Resolve the `access` predicate registered for a model name
195
+ * (abofs/stonyx-orm#202).
196
+ *
197
+ * This is the supported way to reach another model's predicate while
198
+ * servicing a request routed to a different model. Call it with the model
199
+ * name and invoke the result with the live request and an explicit context
200
+ * naming THAT model:
201
+ *
202
+ * ```js
203
+ * const predicate = Orm.instance.getAccess('animal');
204
+ * if (!predicate) return deny;
205
+ * const verdict = predicate(request, { model: 'animal', operation: 'read' });
206
+ * ```
207
+ *
208
+ * WHAT IT RESOLVES. The predicate of the access CLASS that claims the model,
209
+ * which is not necessarily specific to it: one class may claim many models
210
+ * and declares one `access` method, so
211
+ * `getAccess('owner') === getAccess('animal')` is `true` against this repo's
212
+ * fixture. See {@link Orm#accessFunctions}.
213
+ *
214
+ * `undefined` means NO PREDICATE COULD BE RESOLVED for that name. That
215
+ * includes a model whose access class failed to LOAD -- `setup-rest-server`
216
+ * catches, warns and publishes the partial map -- so it is not the same claim
217
+ * as "this model is unrestricted". Treat it as DENY, the same way
218
+ * `AccessContext.operation === undefined` is treated.
219
+ *
220
+ * PASSING THE CONTEXT MAKES A MODEL-CORRECT ANSWER POSSIBLE. It does not, on
221
+ * its own, make the answer model-correct: the resolved predicate has to READ
222
+ * the context. Measured against this repo's shipped access class on a request
223
+ * express dispatched to `GET /owners/angela`, asked about ANIMALS:
224
+ *
225
+ * ```
226
+ * getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
227
+ * -> record => record.id !== 'angela' && record.id !== 'restricted'
228
+ * ```
229
+ *
230
+ * The OWNERS filter, which returns `true` for animal 21 -- the record hidden
231
+ * on every animal surface. Under a mount that predicate recognises neither
232
+ * way it falls through to `['read', 'create', 'update', 'delete']`, a full
233
+ * CRUD grant. Either way: context supplied, answer not the animal answer,
234
+ * wrong in the GRANTING direction, because that predicate is arity-1 and
235
+ * identifies its collection from the request. AC9 asserts the first case on a
236
+ * live dispatch.
237
+ *
238
+ * Every predicate in this repo and in every consumer tree is arity-1 today,
239
+ * and there is no supported way for the caller to tell which kind it got; the
240
+ * boot-time arity warning that would surface it is abofs/stonyx-orm#213. Pass
241
+ * the context, and do not treat a resolved predicate's answer as
242
+ * model-specific until that predicate reads it.
243
+ *
244
+ * OWN PROPERTIES ONLY. A bare `this.accessFunctions[modelName]` walks the
245
+ * prototype chain, so `getAccess('constructor')` resolved `Object` and
246
+ * `getAccess('toString')` resolved `Object.prototype.toString` -- both
247
+ * callable, and the documented `predicate?.(request, ctx)` pattern then
248
+ * returned a TRUTHY value (`Object(request)` is the request), bypassing the
249
+ * `undefined`-means-deny contract entirely. Nothing in the ORM calls
250
+ * `getAccess` yet, so it was not exploitable as shipped -- but #207 takes the
251
+ * model name from the REQUEST BODY (`data.relationships.<key>.data.type`),
252
+ * which would have made a one-field body an authorization bypass. Guarded
253
+ * here at the read point rather than by constructing the map with a null
254
+ * prototype, because the field is public and reassignable and the guard has
255
+ * to hold whatever object it is holding.
256
+ *
257
+ * @param modelName - Model name as declared and stored (kebab-case).
258
+ * @returns The predicate, or `undefined` when no predicate could be resolved
259
+ * for that name. `undefined` is NOT "this model is unrestricted" -- see the
260
+ * note above. Treat it as deny.
261
+ */
262
+ getAccess(modelName) {
263
+ if (!Object.hasOwn(this.accessFunctions, modelName))
264
+ return undefined;
265
+ return this.accessFunctions[modelName];
266
+ }
148
267
  async startup() {
149
268
  if (this.sqlDb)
150
269
  await this.sqlDb.startup();
@@ -1,7 +1,7 @@
1
1
  import Orm, { store } from '@stonyx/orm';
2
2
  import OrmRecord from './record.js';
3
3
  import { getGlobalRegistry, getPendingRegistry, getPendingBelongsToRegistry, getBelongsToRegistry, getHasManyRegistry } from './relationships.js';
4
- import { isOrmRecord } from './utils.js';
4
+ import { isOrmRecord, maxNumericId, NO_FREE_ID_ERROR } from './utils.js';
5
5
  const defaultOptions = {
6
6
  isDbRecord: false,
7
7
  serialize: true,
@@ -153,17 +153,58 @@ export function updateRecord(record, rawData, userOptions = {}) {
153
153
  }
154
154
  }
155
155
  /**
156
- * gets the next available id based on last record entry.
156
+ * gets the next available id, based on the HIGHEST id present.
157
157
  *
158
158
  * In MySQL mode with numeric IDs, assigns a temporary pending ID.
159
159
  * MySQL's AUTO_INCREMENT provides the real ID after INSERT.
160
+ *
161
+ * ---------------------------------------------------------------------------
162
+ * WAS: `Array.from(storeMap.values()).at(-1).id + 1` — the LAST INSERTED id,
163
+ * not the maximum (abofs/stonyx-orm#203). The store is a Map, so insertion
164
+ * order stops being ascending the moment a record is deleted and recreated, a
165
+ * db.json is written out of order, a directory-mode store is read back in file
166
+ * order, or a caller POSTs a high id and then a low one. After that, every
167
+ * server-assigned id is one that is ALREADY TAKEN — and `createRecord`'s
168
+ * last-entry-wins branch then overwrites that record IN PLACE and answers 200.
169
+ * No error, no 409, and the store's size does not change. That is the whole
170
+ * defect, and it is reachable from a create with NO id at all, which is the
171
+ * most ordinary write a consumer performs.
172
+ *
173
+ * Covered by test/unit/assign-record-id-test.ts. Note for anyone changing this
174
+ * function: before that file existed, the whole suite scored 951/0 both on the
175
+ * defect and on a naive `Math.max` fix that introduced a second one. A green
176
+ * suite is not evidence here; those assertions are.
177
+ * ---------------------------------------------------------------------------
160
178
  */
161
179
  function assignRecordId(modelName, rawData) {
162
- if (rawData.id)
180
+ // PRESENCE, not truthiness. `0` is a legal value for an `attr('number')` id,
181
+ // and `if (rawData.id) return` silently reassigned it, handing the caller back
182
+ // a different record than the one it named (#203).
183
+ //
184
+ // `''` is deliberately NOT honoured here and this is not an oversight: it is
185
+ // the one string that means "no id". `parseInt('')` is `NaN`, a record CAN be
186
+ // held under the key `NaN`, and orm-request.ts's body-id normalisation relies
187
+ // on `''` staying absent — otherwise `POST {"id":""}` answers 409 against a
188
+ // record it never named.
189
+ //
190
+ // WHAT WIDENING THIS TO `!== undefined` ACTUALLY DOES, measured rather than
191
+ // asserted: `{id: ''}` early-returns, `parseInt('')` NaNs it, and the record
192
+ // lands on the store's `NaN` slot and OVERWRITES whatever is there — #203's
193
+ // own defect class. It does NOT turn access-filter-enforcement-test.ts
194
+ // assertion 44 red; an earlier revision of this comment claimed it did, which
195
+ // converted an unknown into a false assurance. AC6's BOUNDARY assertions are
196
+ // what catch it, and they only do so because they seed the `NaN` slot first.
197
+ if (rawData.id || rawData.id === 0)
163
198
  return;
164
199
  // In SQL mode with numeric IDs, defer to database auto-increment.
165
200
  // Use unique negative integers — they survive the number transform (parseInt preserves negatives)
166
201
  // and avoid NaN store-key collisions that string pending IDs caused.
202
+ //
203
+ // This early return is ABOVE the max computation on purpose: a pending
204
+ // negative must never be a candidate for, or be perturbed by, the max path.
205
+ // Pinned directly (AC5.3) rather than by asserting the max is unaffected —
206
+ // that assertion could not have failed, because nothing negative ever reaches
207
+ // the code below.
167
208
  if (Orm.instance?.sqlDb && !isStringIdModel(modelName)) {
168
209
  rawData.id = -(++pendingIdCounter);
169
210
  rawData.__pendingSqlId = true;
@@ -173,13 +214,197 @@ function assignRecordId(modelName, rawData) {
173
214
  if (!storeMap)
174
215
  throw new Error(`Cannot assign record ID: model "${modelName}" not found in store`);
175
216
  const modelStore = Array.from(storeMap.values()).filter(isOrmRecord);
176
- const lastRecord = modelStore.at(-1);
177
- rawData.id = lastRecord ? lastRecord.id + 1 : 1;
217
+ // ONE COPY of the max-numeric-id reduce, in src/utils.ts. There were three
218
+ // (here, StandaloneDB.create, and the #203 test helper) and `docs/
219
+ // improvements.md`'s WET Code category prescribes the extraction. What that
220
+ // helper must NOT be is `Math.max(...ids)`; the reason is measured and it is
221
+ // documented at the helper rather than duplicated here. Pinned by AC2.
222
+ const maxId = maxNumericId(modelStore);
223
+ // THE OCCUPANCY CHECK RUNS ON THE LANDING KEY, NOT ON THE RAW CANDIDATE, and
224
+ // the difference is a silent data loss rather than a nicety.
225
+ //
226
+ // `createRecord` looks the record up under `rawData.id` (:50) but WRITES it
227
+ // under `record.id` (:69) — the value after the model's declared id transform
228
+ // has run inside `serialize`. When the transform is not the identity those two
229
+ // differ, so a guard written as `storeMap.has(rawData.id)` checks a key the
230
+ // record will never occupy, misses an occupied slot and overwrites it —
231
+ // measured on an `uppercase`-id model: the guard checks `owner-1`, the record
232
+ // lands under `OWNER-1`, store size unchanged, no error. That is
233
+ // abofs/stonyx-orm#205's lookup-key/landing-key divergence reappearing inside
234
+ // #203's own fix, which is why AC4 exists and why `rawData.id` is set to the
235
+ // LANDING key below.
236
+ //
237
+ // THE SCOPE OF THAT CLAIM, stated rather than implied. Setting `rawData.id` to
238
+ // the landing key makes :50 and :69 agree for every IDEMPOTENT id transform —
239
+ // `number`, `float`, `string`, `passthrough`, `uppercase`, `trim`. It does NOT
240
+ // make them agree for `date` or `timestamp`: `transforms.date` returns a NEW
241
+ // object every call and a `Map` keys by identity, so `storeMap.has(landingKey)`
242
+ // is always `false` there and the occupancy check is vacuous. `dev` is broken
243
+ // for those types too — this is not a regression — but no comment here may
244
+ // claim a property it was not measured to have (#212 § AC5).
245
+ //
246
+ // Resolved ONCE, outside the walk: `getIdType` instantiates the model class,
247
+ // so resolving it per candidate would put a model construction on every
248
+ // iteration of a loop that exists to walk past occupied slots.
249
+ const toStoreKey = storeKeyDeriver(modelName);
250
+ // DOES THIS MODEL FILE ITS RECORDS UNDER STRING KEYS? Decided by RUNNING the
251
+ // model's own id transform once, not by matching a type NAME against a list:
252
+ // `Orm.instance.transforms` (main.ts:70) is a public, MUTABLE instance
253
+ // property, so any enumeration of "the string-ish types" written here would be
254
+ // wrong the moment a consumer registers one.
255
+ const stringKeyed = typeof toStoreKey(maxId + 1) === 'string';
256
+ // THE CANDIDATE FOR A STRING-KEYED MODEL IS NOT A BARE NUMBER, and this is
257
+ // abofs/stonyx-orm#209 — which is REOPENED — not aesthetics.
258
+ //
259
+ // `orm-request.ts`'s `coerceId` (:322) resolves a NUMERIC-LOOKING string to a
260
+ // NUMBER on every id-bearing surface, while a model declaring
261
+ // `id = attr('string')` files under the STRING key. So a server-assigned `'1'`
262
+ // produces a record that is created and then NOT ADDRESSABLE. Measured over
263
+ // the route, owner store `{'1': ...}`:
264
+ //
265
+ // GET /owners/1 -> 404 (the record exists)
266
+ // DELETE /owners/1 -> 404
267
+ // GET /owners/owner-1 -> 200
268
+ //
269
+ // and `_withHooks` (:1185) hands an after-`create` hook
270
+ // `context.record === undefined` for the same reason. `dev` assigned `'bob1'`,
271
+ // which is not numeric-looking, so `dev` has neither problem: a bare-number
272
+ // candidate would move #209 from "a caller supplied a numeric-looking id" onto
273
+ // the DEFAULT path for every server-assigned create on every string-id model.
274
+ // Prefixing with the model name keeps #209's population exactly as narrow as
275
+ // it already was, without touching the one shared coercion or the assertion
276
+ // that pins #209 open. Pinned by AC3.
277
+ const toCandidate = stringKeyed
278
+ ? (value) => `${modelName}-${value}`
279
+ : (value) => value;
280
+ // `maxId + 1` is the id AC1 pins: strictly greater than every numeric key
281
+ // present. IT IS NOT ALWAYS AVAILABLE, and that gap was a live denial of
282
+ // service. Float64 has no integer successor at or above 2^53, so
283
+ // `maxId + 1 === maxId` for every `maxId >= 9007199254740992` and `+ 1` inside
284
+ // the walk is a NO-OP there. One record filed under that key — which an
285
+ // unauthenticated `POST {"id":9007199254740992}` puts there, and which reaches
286
+ // even a filter-protected collection through has-many.ts:65 (#207), a channel
287
+ // GATE 0 does not cover — made the walk unable to advance, so it exhausted its
288
+ // budget and threw on EVERY subsequent server-assigned create, permanently,
289
+ // until that record was deleted. Measured over the route: 200, then 500 for
290
+ // every no-id create. `dev` answers 200.
291
+ //
292
+ // So a store holding one adversarial record must not disable its collection.
293
+ // When "above the max" is not a usable strategy the walk RESTARTS FROM 1: the
294
+ // store holds at most `size` keys, so one of `1 .. size + 1` is always free
295
+ // under an injective id transform. Pinned by AC7.
296
+ const start = maxId + 1;
297
+ let landingKey = firstFreeKey(storeMap, toStoreKey, toCandidate, start);
298
+ // THE RESTART, and it is the whole of the ceiling fix. Killing mutation:
299
+ // delete this block -> AC7 goes red (the route answers 409 instead of the
300
+ // created resource).
301
+ if (landingKey === NO_FREE_KEY && start !== 1) {
302
+ landingKey = firstFreeKey(storeMap, toStoreKey, toCandidate, 1);
303
+ }
304
+ if (landingKey === NO_FREE_KEY) {
305
+ // Reachable only with a NON-INJECTIVE id transform — see `firstFreeKey`.
306
+ // `createHandler` matches this message and answers 409 rather than letting it
307
+ // reach express's default handler, which serialises a stack trace with
308
+ // absolute install paths outside NODE_ENV=production (the hazard
309
+ // orm-request.ts:553-558 exists to name). Pinned by AC8.
310
+ throw new Error(`${NO_FREE_ID_ERROR} for model "${modelName}"`);
311
+ }
312
+ rawData.id = landingKey;
178
313
  }
179
- function isStringIdModel(modelName) {
180
- const modelClass = Orm.instance.getRecordClasses(modelName).modelClass;
314
+ // Returned instead of a key so that "no key" cannot be confused with a transform
315
+ // that legitimately produced `undefined` or `null`.
316
+ const NO_FREE_KEY = Symbol('no free store key');
317
+ /**
318
+ * The first store key at or above `start` that no record occupies, walking
319
+ * candidate ids upward, or `NO_FREE_KEY` if the walk cannot reach one.
320
+ */
321
+ function firstFreeKey(storeMap, toStoreKey, toCandidate, start) {
322
+ let candidate = start;
323
+ let landingKey = toStoreKey(toCandidate(candidate));
324
+ let attempts = 0;
325
+ while (storeMap.has(landingKey)) {
326
+ // THE BOUND IS EXACTLY TIGHT, not conservative: this walk tries
327
+ // `storeMap.size + 1` DISTINCT candidates against at most `storeMap.size`
328
+ // occupied keys, so under an injective `toStoreKey` it provably cannot fire.
329
+ // Under a non-injective one it provably terminates — and that is a reachable
330
+ // consumer state rather than a hypothesis: `transforms.boolean`
331
+ // (transforms.ts:4) collapses every candidate onto `true`/`false`, and
332
+ // `Orm.instance.transforms` (main.ts:70) is public and MUTABLE, so a consumer
333
+ // can register an arbitrary non-injective transform and name it as an id
334
+ // type. Without this, a no-id create spins forever inside a synchronous store
335
+ // walk and pins a worker, which is worse than either collision policy. Its
336
+ // EXISTENCE and its THRESHOLD are both pinned by AC8: deleting it makes AC8
337
+ // HANG rather than fail, and weakening it to fire on the first collision
338
+ // makes AC8.1 red.
339
+ if (++attempts > storeMap.size)
340
+ return NO_FREE_KEY;
341
+ // NOTE FOR ANYONE ADDING A SECOND EXIT HERE. A `candidate + 1 === candidate`
342
+ // float-saturation check was written, measured, and REMOVED: with the
343
+ // restart-from-1 above in place, deleting the saturation check leaves the
344
+ // whole suite green, because the budget reaches the same `NO_FREE_KEY` one
345
+ // pass later and the restart still answers. An unkillable guard in a change
346
+ // whose deliverable is falsifiable coverage is exactly what this story exists
347
+ // to stop shipping. `+ 1` being a no-op at 2^53 costs `size` extra `Map.has`
348
+ // calls on that one path and changes no outcome.
349
+ candidate += 1;
350
+ landingKey = toStoreKey(toCandidate(candidate));
351
+ }
352
+ return landingKey;
353
+ }
354
+ /**
355
+ * Returns the derivation that maps an id VALUE to the store KEY a record
356
+ * carrying it will actually be filed under — the model's declared id transform,
357
+ * the same one `serialize` runs at createRecord:68 before the `.set` at :69.
358
+ */
359
+ function storeKeyDeriver(modelName) {
360
+ const idType = getIdType(modelName);
361
+ const transform = idType ? Orm.instance?.transforms?.[idType] : undefined;
362
+ // SURVIVOR, RETAINED, with its reachability condition stated rather than left
363
+ // silent — `docs/project-structure.md` § "unkillable code reads as coverage and
364
+ // is not" is the standing rule and it applies outside orm-request.ts too.
365
+ //
366
+ // No mutation in this repo can kill this branch, and that is STRUCTURAL rather
367
+ // than an untested gap: `Model` declares `id = attr('number')` (model.ts:15) so
368
+ // every registered model has an id type; `ModelProperty` refuses a type with no
369
+ // registered transform (model-property.ts:4) so a declared type always
370
+ // resolves; and `getIdType` can therefore only return `undefined` when
371
+ // `getRecordClasses` yields no `modelClass` — in which case `createRecord`
372
+ // throws at :62 a few lines later regardless, so no record is ever filed
373
+ // through this branch.
374
+ //
375
+ // BECOMES REACHABLE if a model can be declared without an `id` property, if a
376
+ // store map can exist for a model with no registered class, or if
377
+ // `createRecord` stops constructing the model class. Kept rather than deleted
378
+ // because the alternative on that path is a `transform is not a function`
379
+ // TypeError, and because identity is exactly what `createRecord` would file
380
+ // under when no transform exists — the two agree, which is the property AC4 is
381
+ // about.
382
+ if (typeof transform !== 'function')
383
+ return value => value;
384
+ return value => {
385
+ try {
386
+ return transform(value);
387
+ }
388
+ catch {
389
+ // `uppercase` and `trim` (transforms.ts:11-12) call a string method on the
390
+ // value directly, so a NUMERIC candidate throws `value?.toUpperCase is not
391
+ // a function`. On `dev` they never saw one — `lastRecord.id + 1` on a
392
+ // string id is a string — so feeding them a number here would regress a
393
+ // legal, registered id type into an uncaught 500. The retry feeds the
394
+ // string form, which is the shape an id actually arrives in off a JSON body
395
+ // or a URL param. A transform that throws on BOTH shapes still propagates.
396
+ // Pinned by AC9.
397
+ return transform(String(value));
398
+ }
399
+ };
400
+ }
401
+ function getIdType(modelName) {
402
+ const modelClass = Orm.instance?.getRecordClasses(modelName).modelClass;
181
403
  if (!modelClass)
182
- return false;
404
+ return undefined;
183
405
  const model = new modelClass(modelName);
184
- return model.id?.type === 'string';
406
+ return model.id?.type;
407
+ }
408
+ function isStringIdModel(modelName) {
409
+ return getIdType(modelName) === 'string';
185
410
  }
@@ -2,6 +2,124 @@
2
2
  * REST request handling and access enforcement for @stonyx/orm.
3
3
  *
4
4
  * ---------------------------------------------------------------------------
5
+ * THE `access()` CONTRACT: `access(request, { model, operation })`
6
+ * ---------------------------------------------------------------------------
7
+ * `auth()` calls your predicate with TWO arguments. The second is the access
8
+ * CONTEXT -- the structural facts about the request, which the framework
9
+ * already holds and which you should read INSTEAD of parsing anything:
10
+ *
11
+ * context.model The model this route was mounted for, as a model name:
12
+ * kebab-case, exactly as declared under
13
+ * `config.orm.paths.model` and keyed in the store --
14
+ * `'owner'`, `'animal'`, `'phone-number'`. NOT the
15
+ * pluralised, dasherized, mount-prefixed ROUTE name. It is
16
+ * read from the OrmRequest instance, fixed at mount time,
17
+ * and no request can influence it.
18
+ *
19
+ * context.operation The operation being authorised. Exactly one of the four
20
+ * verbs `'read'`, `'create'`, `'update'`, `'delete'` --
21
+ * no second vocabulary ON THIS PATH, and never an HTTP
22
+ * method name like `'GET'`. These are the same four
23
+ * strings the permission-array return shape is written in
24
+ * (`['read', 'create']`), because both come from the one
25
+ * `methodAccessMap` below.
26
+ *
27
+ * NOT the hook vocabulary. `HookContext.operation`
28
+ * (`src/hooks.ts`, documented under "Hook Context Object"
29
+ * in the README) carries `'list' | 'get' | 'create' |
30
+ * 'update' | 'delete'` on an identically-named key of an
31
+ * identically-shaped context object, and the access
32
+ * vocabulary collapses `list` and `get` into `'read'`. For
33
+ * one `GET /animals/1` a hook sees `'get'` and `access()`
34
+ * sees `'read'`, so a predicate cannot tell a collection
35
+ * read from a record read. `AccessOperation` makes
36
+ * `operation === 'get'` a compile error for a TypeScript
37
+ * consumer, because a predicate that stops matching falls
38
+ * through to the permission array -- the misreading is
39
+ * fail-open shaped.
40
+ *
41
+ * `undefined` when the dispatched method has no entry in
42
+ * that map. Express delivers `HEAD` to the `GET` handler,
43
+ * so this is reachable. It is left undefined rather than
44
+ * defaulted on purpose -- a fabricated `'read'` would turn
45
+ * an unclassified request into an authorised one. Treat
46
+ * `undefined` as "not classified" and deny.
47
+ *
48
+ * So a consumer writes `if (model === 'owner' && operation === 'read')`. There
49
+ * is no string to parse, no variant to miss, and no way to fail open through a
50
+ * URL shape nobody anticipated.
51
+ *
52
+ * WHAT THE CONTEXT DOES NOT TELL YOU: WHICH SURFACE. It names the model and
53
+ * the verb, not the route. Measured over the live router, six surfaces produce
54
+ * one identical context:
55
+ *
56
+ * GET /owners { model: 'owner', operation: 'read' }
57
+ * GET /owners/gina { model: 'owner', operation: 'read' }
58
+ * GET /owners/gina/pets { model: 'owner', operation: 'read' }
59
+ * GET /owners/gina/relationships/pets { model: 'owner', operation: 'read' }
60
+ * GET /owners/archived { model: 'owner', operation: 'read' }
61
+ * GET /owners/gina?include=pets { model: 'owner', operation: 'read' }
62
+ *
63
+ * So a rule that depends on the SUB-PATH still needs `request.path` -- which is
64
+ * mount-relative and query-free, and is the one read of argument one the
65
+ * warning below sanctions. This repo's own fixture has such a rule: its
66
+ * `/archived` deny cannot be expressed from the context alone, and a predicate
67
+ * migrated to context-only would silently drop it, turning a deny into an
68
+ * allow. The related-resource and `?include=` surfaces serve ANOTHER model's
69
+ * records under `model: 'owner'`, and the context gives no signal of that
70
+ * (abofs/stonyx-orm#196).
71
+ *
72
+ * `record` IS NOT IN THIS CONTEXT, deliberately. `auth()` runs after route
73
+ * matching but BEFORE any handler executes (`@stonyx/rest-server`
74
+ * `src/request.ts:58-60`), so nothing has been fetched yet -- supplying a
75
+ * record would force a pre-fetch on every request, a second store hit and an
76
+ * ordering change in the middle of an authorization path. It is also
77
+ * unnecessary: the FUNCTION return shape already is the per-record hook. Return
78
+ * `(record) => boolean` and the handlers apply it to every record the request
79
+ * touches. Auth-time and record-time are separate decision points.
80
+ *
81
+ * THE SECOND ARGUMENT IS ADDITIVE. JavaScript ignores extra arguments, so an
82
+ * existing `access(request)` predicate keeps working exactly as before. The
83
+ * warning immediately below is therefore still live: `request` is still
84
+ * argument ONE, and reading it is still how predicates fail open.
85
+ *
86
+ * To reach ANOTHER model's predicate -- e.g. to check an animal while servicing
87
+ * an owners route -- use the boot-time registry:
88
+ *
89
+ * const predicate = Orm.instance.getAccess('animal');
90
+ * if (!predicate) return deny;
91
+ * const verdict = predicate(request, { model: 'animal', operation: 'read' });
92
+ *
93
+ * `undefined` means NO PREDICATE COULD BE RESOLVED for that name -- which
94
+ * includes the case where the model has an access class that failed to load,
95
+ * because `setup-rest-server.ts` catches a load failure, warns, and publishes
96
+ * whatever partial map it had. It does NOT mean the model is unrestricted.
97
+ * Treat it as DENY, the same way `operation === undefined` is treated above.
98
+ *
99
+ * PASSING THE CONTEXT MAKES A MODEL-CORRECT ANSWER POSSIBLE. It does not make
100
+ * the answer model-correct on its own -- the resolved predicate has to READ it.
101
+ * Measured against this repo's own shipped access class, on a request express
102
+ * dispatched to `GET /owners/angela`, asked about ANIMALS:
103
+ *
104
+ * getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
105
+ * -> record => record.id !== 'angela' && record.id !== 'restricted'
106
+ *
107
+ * That is the OWNERS filter, and it returns `true` for animal 21 -- the record
108
+ * hidden on every animal surface. Under a mount that predicate recognises
109
+ * neither way it is worse: it falls through to
110
+ * `['read', 'create', 'update', 'delete']`, a full CRUD grant. Either way the
111
+ * context was supplied and the answer is not the animal answer, and it is wrong
112
+ * in the GRANTING direction, because that predicate is arity-1 and identifies
113
+ * its collection from the request. (The first of these is asserted on a live
114
+ * dispatch by AC9 in test/integration/orm-test.ts.)
115
+ *
116
+ * Every predicate in this repo and in every consumer tree is arity-1 on the day
117
+ * this ships, and the caller has no supported way to tell which kind it got --
118
+ * the boot-time arity warning that would surface it is abofs/stonyx-orm#213.
119
+ * So: pass the context, and do not treat a resolved predicate's answer as
120
+ * model-specific until that predicate has been migrated to read the context.
121
+ *
122
+ * ---------------------------------------------------------------------------
5
123
  * DO NOT RECONSTRUCT THE REQUEST PATH INSIDE `access()`.
6
124
  * ---------------------------------------------------------------------------
7
125
  * `auth()` below hands your `access(request)` a raw transport artifact and asks
@@ -59,6 +177,7 @@
59
177
  * See `### Known limitations` in README.
60
178
  */
61
179
  import { Request } from '@stonyx/rest-server';
180
+ import type { AccessFunction } from './types/orm-types.js';
62
181
  interface OrmRequest$ extends Request {
63
182
  protocol?: string;
64
183
  method: string;
@@ -73,13 +192,12 @@ interface OrmRequest$ extends Request {
73
192
  };
74
193
  get(header: string): string;
75
194
  }
76
- type AccessMethod = string | boolean | string[] | ((record: unknown) => boolean);
77
195
  type HandlerFn = (request: OrmRequest$, state: {
78
196
  [key: string]: unknown;
79
197
  }) => unknown | Promise<unknown>;
80
198
  export default class OrmRequest extends Request {
81
199
  model: string;
82
- access: (request: unknown) => AccessMethod;
200
+ access: AccessFunction;
83
201
  handlers: {
84
202
  [key: string]: {
85
203
  [key: string]: HandlerFn;
@@ -87,7 +205,7 @@ export default class OrmRequest extends Request {
87
205
  };
88
206
  constructor({ model, access }: {
89
207
  model: string;
90
- access: (request: unknown) => AccessMethod;
208
+ access: AccessFunction;
91
209
  });
92
210
  private _withHooks;
93
211
  private _generateRelationshipRoutes;