@jskit-ai/crud-core 0.2.22 → 0.2.24

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/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A CRUD list asked over HTTP for two or more values of a filter that takes several (`recordIdMany`, `enumMany`, and the list's `id`) answers the rows matching any of them, where it answered 400 (`@jskit-ai/resource-crud-core` reads the comma-separated value the route makes of them). The list's `id` passes the undeclared-key check, which a test proves.
6
+ - **Breaking.** A CRUD list refuses a query key its route does not take with a 400 coded `crud.query.undeclaredKeys`, naming the key and the keys the list takes. Fastify's validation dropped an undeclared key without a word, so `?filter[status]=open` on a list that declares no `status` filter answered every row as if it were unfiltered. Upgrading: declare the filter in the feature's `listFilterQueryValidator` and the resource's searchSchema, or stop sending it.
7
+ - Every CRUD list takes `id`, one record id or a list of them (`filter[id]` over JSON:API), and answers only those records within the caller's scope, so a client reads the records behind ids it already holds, such as a lookup's selected values past the loaded page, in one request.
8
+ - Depends on json-rest-api 3.1.3 exactly (from 3.1.2), from the registry with its published integrity: a write checks each linked target type with one read of the targets' ids (their minimal records only for a target resource with a `checkPermissions` hook), which also takes the shared lock on the belongs-to and polymorphic targets it stores, before `beforeSchemaValidate` rather than after the `beforeDataCall` hooks; in a system context a belongs-to its declared foreign key protects is left to that key, so a missing target there fails with the database's foreign key error instead of `not_found`. json-rest-api now asks for json-rest-schema ^1.0.20.
5
9
  - Depends on json-rest-api 3.1.2 exactly (from 3.1.1), from the registry with its published integrity: json-rest-api bounds a blob field itself too (`maxBytes` required, a blob answered only where `fields` names it, at most 16 MiB of named blobs per read, none in an include, `queryAll` or HTTP response, many-row write statements chunked by blob bytes, and the MySQL/MariaDB column type chosen by `maxBytes`), its `contains`, `startsWith` and `endsWith` filters match `%`, `_` and `\` literally on every database, a relationship write checks and locks each related type's targets in one query, and an AnyAPI many-to-many read costs its own link rows instead of growing with the square of them.
6
10
  - A patch naming a linked record that does not exist (a `lookup` field's id with no such row) is refused as that record missing, the error json-rest-api raises with its `resourceType` and `resourceId`, where the CRUD service answered `404 Document not found.` as if the patched record itself were missing. View, patch and delete still answer the 404 (or null for delete) for their own record missing or out of scope.
7
11
  - A CRUD contract whose `includeFields` lists a link of the included record as a field is refused at boot, at every depth, with an error that names the form to use: a belongs-to field by its key (`"locationId"`) or its relationship (`"location"`), or a collection relation. A JSON:API document answers a link under the record's relationships, never among its attributes, so such an entry never showed and the included record read as if it had no link, which emptied an app's board grouped by it. List it as `{ location: [] }`, which answers the linked id, with the fields to show of the linked record inside it. `CrudContractsProvider` checks every registered contract when it seals the registry at boot, once every feature owns its tables, against the table resources `runtime.resources` answers; a level whose table no feature owns is left alone.
package/locales/en.json CHANGED
@@ -9,7 +9,8 @@
9
9
  "fieldsInvalid": "fields expects an object such as {example}.",
10
10
  "fieldsByTypeInvalid": "fields expects an object keyed by JSON:API resource type, such as {example}.",
11
11
  "fieldsKeysInvalid": "fields keys must be JSON:API resource types. Allowed keys: {allowedTypes}.",
12
- "fieldsKeysInvalidWithAliases": "fields keys must be JSON:API resource types. Allowed keys: {allowedTypes}. Relationship aliases are invalid keys; {aliasGuidance}."
12
+ "fieldsKeysInvalidWithAliases": "fields keys must be JSON:API resource types. Allowed keys: {allowedTypes}. Relationship aliases are invalid keys; {aliasGuidance}.",
13
+ "undeclaredKeys": "This list does not take {unknown}: an undeclared query key would be dropped, and the list would answer as if it had not been sent. It takes {known}. To filter on a field, add it to the feature's listFilterQueryValidator and the resource's searchSchema; to search, send filter[q] and give the resource searchSchema.q."
13
14
  }
14
15
  }
15
16
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/crud-core",
3
- "version": "0.2.22",
3
+ "version": "0.2.24",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.0.0"
@@ -20,10 +20,10 @@
20
20
  "./locales/en.json": "./locales/en.json"
21
21
  },
22
22
  "dependencies": {
23
- "@jskit-ai/resource-core": "0.1.208",
24
- "@jskit-ai/resource-crud-core": "0.1.208",
25
- "json-rest-api": "3.1.2",
26
- "json-rest-schema": "^1.0.17"
23
+ "@jskit-ai/resource-core": "0.1.209",
24
+ "@jskit-ai/resource-crud-core": "0.1.210",
25
+ "json-rest-api": "3.1.3",
26
+ "json-rest-schema": "^1.0.20"
27
27
  },
28
28
  "description": "Shared server-side CRUD service, repository, route, and query helpers.",
29
29
  "jskit": {
@@ -49,8 +49,8 @@
49
49
  }
50
50
  },
51
51
  "peerDependencies": {
52
- "@jskit-ai/http-runtime": "0.2.17",
53
- "@jskit-ai/kernel": "0.2.17",
54
- "@jskit-ai/resource-runtime": "0.2.19"
52
+ "@jskit-ai/http-runtime": "0.2.18",
53
+ "@jskit-ai/kernel": "0.2.18",
54
+ "@jskit-ai/resource-runtime": "0.2.21"
55
55
  }
56
56
  }
@@ -9,9 +9,9 @@
9
9
  "./shared": "./src/shared/index.js"
10
10
  },
11
11
  "dependencies": {
12
- "@jskit-ai/crud-core": "0.2.22",
13
- "@jskit-ai/resource-core": "0.1.208",
14
- "@jskit-ai/resource-crud-core": "0.1.208"
12
+ "@jskit-ai/crud-core": "0.2.24",
13
+ "@jskit-ai/resource-core": "0.1.209",
14
+ "@jskit-ai/resource-crud-core": "0.1.210"
15
15
  },
16
16
  "jskit": {
17
17
  "kind": "runtime",
@@ -2,6 +2,7 @@ import { normalizeSurfaceId } from "@jskit-ai/kernel/shared/surface/registry";
2
2
  import { resolveScopedApiBasePath } from "@jskit-ai/kernel/shared/surface";
3
3
  import { checkRouteVisibility } from "@jskit-ai/kernel/shared/support/visibility";
4
4
  import { composeSchemaDefinitions } from "@jskit-ai/kernel/shared/validators";
5
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
5
6
  import { createCrudJsonApiRouteContracts } from "../routeContracts.js";
6
7
  import { buildCrudCustomActionId } from "./customActionId.js";
7
8
 
@@ -18,6 +19,35 @@ function buildScopeInput(scopeInput, request) {
18
19
  return result;
19
20
  }
20
21
 
22
+ /**
23
+ * Refuses a list request that names a query key its route does not take. Fastify's validation drops an undeclared
24
+ * query key without a word, so a filter the list does not know (`filter[status]`) would answer every row, as if it
25
+ * were never sent: the keys the request names that validation left out of request.query are the undeclared ones.
26
+ * @param {{ url?: string, query?: object, routeOptions?: { schema?: { querystring?: { properties?: object } } } }} request
27
+ */
28
+ function refuseUndeclaredListQuery(request) {
29
+ const url = String(request.url || "");
30
+ const start = url.indexOf("?");
31
+ if (start < 0) {
32
+ return;
33
+ }
34
+ const taken = new Set(Object.keys(request.query || {}));
35
+ const unknown = [...new Set(new URLSearchParams(url.slice(start + 1)).keys())].filter((key) => key && !taken.has(key));
36
+ if (unknown.length < 1) {
37
+ return;
38
+ }
39
+ const querystring = request.routeOptions?.schema?.querystring || {};
40
+ // A sparse fieldset key is taken by pattern, one per JSON:API type: `fields[<type>]`.
41
+ const patterns = Object.keys(querystring.patternProperties || {}).map((pattern) => (pattern.startsWith("^fields") ? "fields[<type>]" : pattern));
42
+ const known = [...Object.keys(querystring.properties || {}), ...patterns].join(", ") || "none";
43
+ const params = { unknown: unknown.join(", "), known };
44
+ throw new AppError(400,
45
+ `This list does not take ${params.unknown}: an undeclared query key would be dropped, and the list would answer as ` +
46
+ `if it had not been sent. It takes ${known}. To filter on a field, add it to the feature's listFilterQueryValidator ` +
47
+ "and the resource's searchSchema; to search, send filter[q] and give the resource searchSchema.q.",
48
+ { code: "crud.query.undeclaredKeys", params });
49
+ }
50
+
21
51
  function buildCustomActionInput(scopeInput, route, request) {
22
52
  const scopedInput = buildScopeInput(scopeInput, request);
23
53
  if (route.input) {
@@ -153,6 +183,7 @@ function createCrudJsonApiRoutes({
153
183
  ...paramsContract()
154
184
  },
155
185
  async function (request, reply) {
186
+ refuseUndeclaredListQuery(request);
156
187
  const response = await request.executeAction({
157
188
  actionId: actionId("list"),
158
189
  input: {
@@ -4,7 +4,12 @@ import {
4
4
  } from "@jskit-ai/kernel/shared/validators";
5
5
  import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
6
6
  import { resolveCrudParentFilterKeys } from "@jskit-ai/resource-crud-core/shared/crudLookup";
7
+ import {
8
+ CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY,
9
+ defineCrudListFilters
10
+ } from "@jskit-ai/resource-crud-core/shared/crudListFilters";
7
11
  import { resolveJsonApiFieldsetContract } from "./jsonApiResourceContract.js";
12
+ import { buildFilterQuerySchemaDefinition } from "./listFilterTypes.js";
8
13
 
9
14
  const listSearchQueryValidator = Object.freeze({
10
15
  schema: createSchema({
@@ -16,6 +21,12 @@ const listSearchQueryValidator = Object.freeze({
16
21
  mode: "patch"
17
22
  });
18
23
 
24
+ // `id`, one record id or a list of them, narrows a list to those rows (the handle's own id filter), so a picker
25
+ // reads the selected values its loaded page lacks in one request instead of showing their raw ids.
26
+ const listRecordIdsQueryValidator = buildFilterQuerySchemaDefinition(Object.values(defineCrudListFilters({
27
+ id: { type: CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY, label: "Id" }
28
+ })));
29
+
19
30
  const lookupIncludeQueryValidator = Object.freeze({
20
31
  schema: createSchema({
21
32
  include: {
@@ -191,7 +202,7 @@ function createCrudParentFilterQueryValidator(resource = {}) {
191
202
  }
192
203
 
193
204
  /**
194
- * The query schemas of a CRUD list: cursor, search, parent filters, list filters, include and fieldsets.
205
+ * The query schemas of a CRUD list: cursor, search, record ids, parent filters, list filters, include and fieldsets.
195
206
  * @param {object} [options]
196
207
  * @param {object} [options.resource]
197
208
  * @param {object | null} [options.listFilterQueryValidator]
@@ -217,6 +228,7 @@ function createStandardCrudListQueryValidators({
217
228
  orderBy: resource.resource?.defaultSort
218
229
  }),
219
230
  searchQueryValidator,
231
+ listRecordIdsQueryValidator,
220
232
  createCrudParentFilterQueryValidator(resource),
221
233
  ...(resolvedListFilterQueryValidator
222
234
  ? [resolvedListFilterQueryValidator]
@@ -240,6 +252,7 @@ export {
240
252
  createCrudCursorPaginationQueryValidator,
241
253
  createJsonApiFieldsetsQueryValidator,
242
254
  listSearchQueryValidator,
255
+ listRecordIdsQueryValidator,
243
256
  lookupIncludeQueryValidator,
244
257
  jsonApiFieldsetsQueryValidator,
245
258
  createCrudParentFilterQueryValidator,
@@ -96,6 +96,19 @@ test("the list action keeps answering a larger limit with one capped page", asyn
96
96
  assert.equal(next.value.data[0].attributes.title, "Note 21");
97
97
  });
98
98
 
99
+ test("the list action narrows to the record ids it names, so a picker reads its selected values past the first page", async (t) => {
100
+ const { actionsFor } = await createFixture(t);
101
+ const [list] = actionsFor({ operations: ["list"] });
102
+
103
+ const many = await list.execute({ id: ["240", "3"] }, WORKSPACE_ONE);
104
+ assert.deepEqual(many.value.data.map((record) => record.attributes.title).sort(), ["Note 240", "Note 3"]);
105
+ const one = await list.execute({ id: "245" }, WORKSPACE_ONE);
106
+ assert.deepEqual(one.value.data.map((record) => record.attributes.title), ["Note 245"]);
107
+ // Another workspace's ids stay out of scope.
108
+ const elsewhere = await list.execute({ id: "245" }, Object.freeze({ scopeValues: Object.freeze({ workspaceId: "2" }) }));
109
+ assert.deepEqual(elsewhere.value.data, []);
110
+ });
111
+
99
112
  test("a column the contract does not name is neither returned nor accepted", async (t) => {
100
113
  const { knex, actionsFor } = await createFixture(t);
101
114
  const [list, view, create, update] = actionsFor({ operations: ["list", "view", "create", "update"] });
@@ -8,6 +8,7 @@ import {
8
8
  import { compileRouteValidator } from "@jskit-ai/kernel/_testable";
9
9
  import {
10
10
  listSearchQueryValidator,
11
+ listRecordIdsQueryValidator,
11
12
  lookupIncludeQueryValidator,
12
13
  createCrudCursorPaginationQueryValidator,
13
14
  createJsonApiFieldsetsQueryValidator,
@@ -66,6 +67,17 @@ test("listSearchQueryValidator normalizes q", async () => {
66
67
  });
67
68
  });
68
69
 
70
+ test("listRecordIdsQueryValidator takes one record id or a list of them as a list", () => {
71
+ assert.deepEqual(validateSchemaPayload(listRecordIdsQueryValidator, { id: "7" }, { phase: "input" }), { id: ["7"] });
72
+ assert.deepEqual(
73
+ validateSchemaPayload(listRecordIdsQueryValidator, { id: ["7", "12"] }, { phase: "input" }),
74
+ { id: ["7", "12"] }
75
+ );
76
+ assert.throws(() => validateSchemaPayload(listRecordIdsQueryValidator, { id: "seven" }, { phase: "input" }));
77
+ const compiled = compileRouteValidator({ query: listRecordIdsQueryValidator });
78
+ assert.deepEqual(compiled.schema.querystring.required || [], []);
79
+ });
80
+
69
81
  test("listSearchQueryValidator keeps q optional when merged with pagination query validator", () => {
70
82
  const compiled = compileRouteValidator({
71
83
  query: composeSchemaDefinition(cursorPaginationQueryValidator, listSearchQueryValidator)
@@ -297,7 +309,7 @@ test("standard CRUD query validator groups remain plain and extensible", () => {
297
309
  );
298
310
  assert.deepEqual(
299
311
  Object.keys(listQueryValidator.schema.getFieldDefinitions()).sort(),
300
- ["archived", "currentness", "cursor", "fields", "include", "limit", "q"]
312
+ ["archived", "currentness", "cursor", "fields", "id", "include", "limit", "q"]
301
313
  );
302
314
 
303
315
  const viewQueryValidator = composeSchemaDefinition(
@@ -0,0 +1,94 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import Fastify from "fastify";
4
+ import { catalogMessage, formatMessage, messageKeyForCode, mergeCatalogs } from "@jskit-ai/kernel/shared/i18n";
5
+ import kernelEnglish from "@jskit-ai/kernel/locales/en.json" with { type: "json" };
6
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
7
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
8
+ import { returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
9
+ import { createRouter } from "../../kernel/server/http/lib/router.js";
10
+ import { registerRoutes } from "../../kernel/server/http/lib/routeRegistration.js";
11
+ import { registerApiErrorHandler } from "../../kernel/server/http/errorHandling.js";
12
+ import crudEnglish from "../locales/en.json" with { type: "json" };
13
+ import { registerCrudJsonApiRoutes } from "../src/server/jsonApiModule/routes.js";
14
+ import { crudJsonApiRouteOptions } from "./support/crudJsonApiActionOptions.js";
15
+
16
+ const notes = defineCrudContract(defineTableResource({
17
+ name: "notes",
18
+ tableName: "notes",
19
+ ownership: "public",
20
+ schema: { title: { type: "string", required: true } }
21
+ }), {
22
+ namespace: "notes",
23
+ apiAccess: "public",
24
+ operations: ["list", "view"],
25
+ fields: { title: { output: "required" } }
26
+ });
27
+
28
+ async function listApp(t) {
29
+ const router = createRouter();
30
+ registerCrudJsonApiRoutes(router, crudJsonApiRouteOptions({
31
+ namespace: "notes",
32
+ resource: notes,
33
+ relativePath: "/notes",
34
+ surface: "app",
35
+ ownershipFilter: "public",
36
+ access: "public",
37
+ operations: ["list"]
38
+ }));
39
+ const app = Fastify();
40
+ t.after(() => app.close());
41
+ registerApiErrorHandler(app);
42
+ const listed = [];
43
+ registerRoutes(app, {
44
+ routes: router.list(),
45
+ actions: {
46
+ getDefinition: () => ({ kind: "action" }),
47
+ async execute({ input }) {
48
+ listed.push(input);
49
+ return returnJsonApiDocument({ data: [] });
50
+ }
51
+ }
52
+ });
53
+ return { app, listed };
54
+ }
55
+
56
+ test("a CRUD list refuses a query key it does not take, which Fastify's validation would drop unseen", async (t) => {
57
+ const { app, listed } = await listApp(t);
58
+
59
+ const searched = await app.inject({ method: "GET", url: "/api/notes?filter%5Bq%5D=Ada" });
60
+ assert.equal(searched.statusCode, 200, searched.body);
61
+ assert.deepEqual(listed, [{ q: "Ada" }]);
62
+
63
+ // Every key JSKIT's list composables send is taken: the page, its cursor, the search, include and a sparse fieldset.
64
+ const paged = await app.inject({
65
+ method: "GET",
66
+ url: "/api/notes?page%5Blimit%5D=20&page%5Bcursor%5D=5&filter%5Bq%5D=Ada&include=author&fields%5Bnotes%5D=title"
67
+ });
68
+ assert.equal(paged.statusCode, 200, paged.body);
69
+ assert.equal(listed.length, 2);
70
+
71
+ // Before, both answered every row: validation dropped the filter and the list never saw it.
72
+ for (const url of ["/api/notes?filter%5Bstatus%5D=open", "/api/notes?filter%5Bq%5D=Ada&status=open"]) {
73
+ const response = await app.inject({ method: "GET", url });
74
+ assert.equal(response.statusCode, 400, url);
75
+ const [error] = response.json().errors;
76
+ assert.equal(error.code, "crud.query.undeclaredKeys", url);
77
+ assert.match(error.title, /does not take (filter\[status\]|status):/u, url);
78
+ assert.match(error.title, /It takes .*filter\[q\].*fields\[<type>\]/u, url);
79
+ // The client shows the code's sentence in the user's language: the English sent is the catalog's.
80
+ const english = mergeCatalogs(kernelEnglish, crudEnglish);
81
+ assert.equal(formatMessage(catalogMessage(english, messageKeyForCode(error.code)), error.meta.params), error.title, url);
82
+ }
83
+ assert.equal(listed.length, 2);
84
+ });
85
+
86
+ test("a CRUD list takes filter[id], one record id or several, which a lookup sends to label the values it holds", async (t) => {
87
+ const { app, listed } = await listApp(t);
88
+
89
+ for (const url of ["/api/notes?filter%5Bid%5D=7", "/api/notes?filter%5Bid%5D=7&filter%5Bid%5D=12&page%5Blimit%5D=20"]) {
90
+ const response = await app.inject({ method: "GET", url });
91
+ assert.equal(response.statusCode, 200, `${url}: ${response.body}`);
92
+ }
93
+ assert.deepEqual(listed.map((input) => input.id), [["7"], ["7", "12"]]);
94
+ });