@stonyx/orm 0.3.2-alpha.7 → 0.3.2-alpha.71

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.
Files changed (63) hide show
  1. package/README.md +968 -11
  2. package/config/environment.js +8 -0
  3. package/dist/access-verdict.d.ts +59 -0
  4. package/dist/access-verdict.js +222 -0
  5. package/dist/commands.js +34 -0
  6. package/dist/dynamodb/connection.d.ts +31 -0
  7. package/dist/dynamodb/connection.js +28 -0
  8. package/dist/dynamodb/dynamodb-db.d.ts +142 -0
  9. package/dist/dynamodb/dynamodb-db.js +596 -0
  10. package/dist/dynamodb/operation-builder.d.ts +76 -0
  11. package/dist/dynamodb/operation-builder.js +116 -0
  12. package/dist/dynamodb/type-map.d.ts +31 -0
  13. package/dist/dynamodb/type-map.js +48 -0
  14. package/dist/index.d.ts +3 -0
  15. package/dist/index.js +8 -0
  16. package/dist/main.d.ts +116 -0
  17. package/dist/main.js +129 -0
  18. package/dist/manage-record.js +268 -12
  19. package/dist/mysql/connection.d.ts +1 -0
  20. package/dist/mysql/mysql-db.d.ts +8 -0
  21. package/dist/mysql/mysql-db.js +44 -10
  22. package/dist/orm-request.d.ts +216 -3
  23. package/dist/orm-request.js +924 -55
  24. package/dist/postgres/connection.d.ts +1 -0
  25. package/dist/postgres/connection.js +8 -6
  26. package/dist/postgres/postgres-db.d.ts +8 -0
  27. package/dist/postgres/postgres-db.js +44 -10
  28. package/dist/record.d.ts +16 -0
  29. package/dist/record.js +62 -6
  30. package/dist/relationships.js +1 -1
  31. package/dist/serializer.js +38 -2
  32. package/dist/setup-rest-server.js +51 -5
  33. package/dist/standalone-db.js +17 -5
  34. package/dist/store.d.ts +13 -1
  35. package/dist/store.js +65 -6
  36. package/dist/types/orm-types.d.ts +139 -0
  37. package/dist/utils.d.ts +44 -0
  38. package/dist/utils.js +47 -0
  39. package/package.json +16 -7
  40. package/src/access-verdict.ts +248 -0
  41. package/src/commands.ts +43 -0
  42. package/src/dynamodb/connection.ts +50 -0
  43. package/src/dynamodb/dynamodb-db.ts +811 -0
  44. package/src/dynamodb/operation-builder.ts +202 -0
  45. package/src/dynamodb/type-map.ts +54 -0
  46. package/src/index.ts +10 -0
  47. package/src/main.ts +133 -0
  48. package/src/manage-record.ts +294 -18
  49. package/src/mysql/connection.ts +1 -0
  50. package/src/mysql/mysql-db.ts +44 -12
  51. package/src/orm-request.ts +944 -56
  52. package/src/postgres/connection.ts +10 -6
  53. package/src/postgres/postgres-db.ts +44 -12
  54. package/src/record.ts +82 -6
  55. package/src/relationships.ts +1 -1
  56. package/src/serializer.ts +39 -2
  57. package/src/setup-rest-server.ts +59 -6
  58. package/src/standalone-db.ts +17 -6
  59. package/src/store.ts +68 -6
  60. package/src/types/orm-types.ts +146 -1
  61. package/src/types/stonyx-rest-server.d.ts +14 -1
  62. package/src/types/stonyx.d.ts +7 -1
  63. package/src/utils.ts +50 -0
@@ -1,4 +1,218 @@
1
+ /**
2
+ * REST request handling and access enforcement for @stonyx/orm.
3
+ *
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 an ARITY-1 predicate, on a request express dispatched to
102
+ * `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. (Asserted on a live dispatch by AC9 in
114
+ * test/integration/orm-test.ts, against a deliberately arity-1 predicate.)
115
+ *
116
+ * This repo's own sample access class has since been MIGRATED to read the
117
+ * context (abofs/stonyx-orm#222), so `getAccess('animal')` here now answers
118
+ * with the animal filter. That is not true of a consumer tree: an arity-1
119
+ * predicate keeps working -- the second argument is additive -- and the caller
120
+ * has no supported way to tell which kind it got. The boot-time arity warning
121
+ * that surfaces one is abofs/stonyx-orm#221.
122
+ * So: pass the context, and do not treat a resolved predicate's answer as
123
+ * model-specific until that predicate has been migrated to read the context.
124
+ *
125
+ * ---------------------------------------------------------------------------
126
+ * DO NOT RECONSTRUCT THE REQUEST PATH INSIDE `access()`.
127
+ * ---------------------------------------------------------------------------
128
+ * You do not have to. `auth()` below hands your predicate the ACCESS CONTEXT as
129
+ * argument two, and `context.model` already names the collection -- see the
130
+ * contract section above. Argument ONE is still the raw transport artifact, and
131
+ * everything from here to the end of this banner is the record of what happened
132
+ * when predicates worked the collection out from it. IT IS HISTORY, NOT
133
+ * GUIDANCE: do not write any of it into a new predicate. Every attempt to
134
+ * identify the collection by parsing the request target has failed OPEN. Five
135
+ * distinct variants of the same three-line example have now been found, each
136
+ * after the previous was fixed, by five different people:
137
+ *
138
+ * 1. `request.url` is mount-relative under `RestServer.mountRoute`, so a
139
+ * prefix match against it is ALWAYS false.
140
+ * 2. `request.originalUrl` carries the query string, so an anchored equality
141
+ * check misses `/owners?filter[age]=30`.
142
+ * 3. The router is a bare `express()` (`caseSensitive: false`) while a
143
+ * hand-written matcher is case-SENSITIVE, so `GET /OwNeRs/angela` walks
144
+ * past it. Router-side: abofs/stonyx-rest-server#47.
145
+ * 4. Under a configured `ORM_REST_ROUTE` a hard-coded `/owners` matches
146
+ * nothing -- environment-specifically, which is worse.
147
+ * 5. HTTP/1.1 permits an ABSOLUTE-FORM request-target. Express routes on
148
+ * `parseurl(req).pathname`, but `originalUrl` is the raw target, so
149
+ * `GET http://anything.example/owners/angela` reaches the handler with
150
+ * `originalUrl === 'http://anything.example/owners/angela'`. A `/owners`
151
+ * prefix match is false, `access()` falls through to whatever it returns
152
+ * last, and the record comes back in full. It walks past a hard
153
+ * `return false` deny the same way.
154
+ *
155
+ * The fix is not a sixth rule, and it is not a better string to match. It is to
156
+ * stop identifying the collection at all: read `context.model`. That is a claim
157
+ * about IDENTIFYING THE COLLECTION, not about the sample as a whole -- the
158
+ * `/archived` SUB-PATH rule is still a string match, and abofs/stonyx-orm#228 is
159
+ * a sixth spelling that gets past it.
160
+ *
161
+ * An intermediate revision of the sample read `request.baseUrl` -- the mount
162
+ * Express ACTUALLY MATCHED. That closed all five variants (no query string,
163
+ * not mount-relative, unaffected by absolute-form, already carrying the
164
+ * configured `ORM_REST_ROUTE` prefix), but it was a transport artifact
165
+ * standing in for a structural fact and the sample no longer does it.
166
+ * `context.model` IS the structural fact, so variants 1, 2, 4 and 5 are
167
+ * unconstructible against a migrated predicate rather than handled.
168
+ *
169
+ * VARIANT 3 SURVIVES, and is deliberately not in that list. It is the general
170
+ * shape "a hand-written matcher normalises differently from the router", and a
171
+ * migrated predicate still runs one string comparison for any SUB-PATH rule --
172
+ * in the shipped sample, the `/archived` deny. That comparison folds case but
173
+ * does not decode, so `GET /owners/%61rchived` steps past it. See the
174
+ * normalisation paragraph below and abofs/stonyx-orm#228.
175
+ *
176
+ * ONE READ OF ARGUMENT ONE SURVIVES, AND IT MUST: `request.path`. It is
177
+ * mount-relative and query-free, and it is for rules that distinguish SUB-PATHS
178
+ * beneath the mount. The context names which model and which verb, NOT which
179
+ * route, so the sample's `/archived` deny cannot be expressed from the context
180
+ * alone and a context-ONLY rewrite would silently turn that deny into an allow.
181
+ *
182
+ * NORMALISE THE WAY THE ROUTER DOES, AND CASE-FOLDING ALONE IS NOT THAT. The
183
+ * sample lower-cases before comparing, because a matcher stricter than the
184
+ * case-insensitive router can be stepped around. That closes the case gap only.
185
+ * Express sets `request.path` from the RAW, UNDECODED pathname while the router
186
+ * DECODES `:id`, so `GET /owners/%61rchived` reaches a `path === '/archived'`
187
+ * comparison as `/%61rchived` and walks past the deny. That gap is live in the
188
+ * sample and is tracked as abofs/stonyx-orm#228; the `.toLowerCase()` is not a
189
+ * complete normalisation recipe. Compare record ids at their real case.
190
+ *
191
+ * `?? ''` is not a defence. It converts an absent request target into an empty
192
+ * string, which matches no collection, which falls through to the permission
193
+ * array -- a total grant. An input you cannot identify must DENY, and that
194
+ * applies to BOTH arguments: since #202 the guard and the read can sit on
195
+ * different objects, and a guard on argument two does not protect a read of
196
+ * argument one. The sample returns `false` for an absent `model` AND for an
197
+ * absent or non-string `request.path`, rather than falling through either way.
198
+ *
199
+ * THE REAL FIX IS abofs/stonyx-orm#202: `access()` should receive the model,
200
+ * the operation and the record. Prefer the array shape (`['read']`) or `false`
201
+ * until #202 lands; the function shape is what requires any matching at all.
202
+ *
203
+ * The enforcement gates in this file (GATE 0/1/2, the create rollback, the
204
+ * per-handler `isDenied` re-checks) are correct independently of that -- they
205
+ * enforce whatever predicate you return. The stopgap is the part where YOU have
206
+ * to work out which predicate to return.
207
+ *
208
+ * AND A PREDICATE IS NOT A GUARANTEE THAT A HIDDEN RECORD CANNOT BE MODIFIED.
209
+ * It is evaluated against the record the route is ADDRESSED TO, on that model
210
+ * only. A write to a DIFFERENT collection can still re-parent a hidden record
211
+ * and de-hide it -- abofs/stonyx-orm#207, which is blocked on #202 and #196.
212
+ * See `### Known limitations` in README.
213
+ */
1
214
  import { Request } from '@stonyx/rest-server';
215
+ import type { AccessFunction } from './types/orm-types.js';
2
216
  interface OrmRequest$ extends Request {
3
217
  protocol?: string;
4
218
  method: string;
@@ -13,13 +227,12 @@ interface OrmRequest$ extends Request {
13
227
  };
14
228
  get(header: string): string;
15
229
  }
16
- type AccessMethod = string | boolean | string[] | ((record: unknown) => boolean);
17
230
  type HandlerFn = (request: OrmRequest$, state: {
18
231
  [key: string]: unknown;
19
232
  }) => unknown | Promise<unknown>;
20
233
  export default class OrmRequest extends Request {
21
234
  model: string;
22
- access: (request: unknown) => AccessMethod;
235
+ access: AccessFunction;
23
236
  handlers: {
24
237
  [key: string]: {
25
238
  [key: string]: HandlerFn;
@@ -27,7 +240,7 @@ export default class OrmRequest extends Request {
27
240
  };
28
241
  constructor({ model, access }: {
29
242
  model: string;
30
- access: (request: unknown) => AccessMethod;
243
+ access: AccessFunction;
31
244
  });
32
245
  private _withHooks;
33
246
  private _generateRelationshipRoutes;