diff --git a/CHANGELOG.md b/CHANGELOG.md index 7df0ba6e20..bcf49f68ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1801,6 +1801,22 @@ Each item below is described in full under Security, Added, Changed or Fixed; th sub-corpus of the api-contract conformance corpus, in the generated lane of all five ports, and by `tph-sibling-credential` in `secret-fields/tph/` for the shared-column case. +- **A credential is never a generated grid column, initial sort or filter preset.** The generated + forms skipped a credential (a field that declares a `view.password`), but the grids did not: a + `layout.dataGrid` whose `@columns` named one, or that listed no `@columns` at all, emitted a column + for it in the TanStack `.columns.tsx` and the Angular grid component, and a + `@defaultSortField` naming one became the grid's initial sort in the grid const, the grid hook and + the Angular grid config. The column is now dropped and the initial sort resolves to none, in every + generated tier; on a single-table (TPH) base's polymorphic grid a subtype-only column, and a column any + subtype marks as a credential, counts too. The runtime grid builder (`buildGrid()` in + `@metaobjectsdev/runtime-web`) drops a credential the same way, but it sees only the field's own + `view.password`, not a TPH sibling's mark, because it has no model root. A `@filter` preset over a credential, at any depth of its + `and` / `or`, now fails `meta gen` naming the layout and the field rather than being emitted, because + the server refuses that filter on every request and dropping the clause would silently change which + rows the grid shows: remove the clause. The agent UI page marks a credential as excluded from the form + and leaves it out of a grid's columns and default sort. Regenerate a grid over a model with a + credential; the generated `.meta` descriptor is unchanged. + - **A numeric key is read only from canonical decimal text, in the TypeScript, Java and Python ObjectManagers.** A path parameter or ref string for an integer, long, decimal, double or float primary key went through the language's own number parser, which reads `0x1`, `1e0`, `0b1`, `+1`, diff --git a/agent-context/skills/metaobjects-runtime-ui/references/tanstack.md b/agent-context/skills/metaobjects-runtime-ui/references/tanstack.md index 38d66c0000..d87d07ce36 100644 --- a/agent-context/skills/metaobjects-runtime-ui/references/tanstack.md +++ b/agent-context/skills/metaobjects-runtime-ui/references/tanstack.md @@ -108,7 +108,7 @@ So the minimum to get a grid is a `layout.dataGrid` on the entity: // ...fields... { "layout.dataGrid": { "name": "default", - "@columns": ["name", "email", "createdAt"], // ordered; omit for every field + "@columns": ["name", "email", "createdAt"], // ordered; omit for every field but a credential "@pageSize": 25, "@defaultSortField": "createdAt", "@defaultSortOrder": "desc" diff --git a/client/web/packages/runtime-web/src/grid-from-metadata.ts b/client/web/packages/runtime-web/src/grid-from-metadata.ts index 3cd5c351f8..1d4610b6a9 100644 --- a/client/web/packages/runtime-web/src/grid-from-metadata.ts +++ b/client/web/packages/runtime-web/src/grid-from-metadata.ts @@ -28,6 +28,7 @@ import { LAYOUT_DATA_GRID_ATTR_FILTERABLE, FIELD_ATTR_SORTABLE_DEFAULT_ORDER, DOC_ATTR_TITLE, + VIEW_SUBTYPE_PASSWORD, } from "@metaobjectsdev/metadata/constants"; import type { GridConfig } from "./fetcher.js"; @@ -62,6 +63,13 @@ function firstView(field: MetaFieldRead): MetaViewRead | undefined { return field.views()[0]; } +// A credential (a field declaring or inheriting `view.password`) is never a grid column or +// initial sort: the server's filter and sort allowlists refuse it. A TPH sibling subtype's +// credential mark on a shared column is not visible here without a model root. +function isCredential(field: MetaFieldRead): boolean { + return field.views().some((v) => v.subType === VIEW_SUBTYPE_PASSWORD); +} + function header(field: MetaFieldRead): string { // DOC_ATTR_TITLE, not the literal "label". `@label` is registered by NO provider in // any port — `@title` is the documentation commonAttr chartered as the display label @@ -130,11 +138,13 @@ export function buildGrid(meta: MetaRead, gridName?: string): MetaGrid { const columns: MetaColumn[] = names .map((n) => fieldsByName.get(n)) - .filter((f): f is MetaFieldRead => f !== undefined) + .filter((f): f is MetaFieldRead => f !== undefined && !isCredential(f)) .map((f) => ({ field: f.name, header: header(f), viewKind: viewKind(f) })); const pageSizeAttr = layout?.attr(LAYOUT_DATA_GRID_ATTR_PAGE_SIZE); - const sortField = layout?.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD); + const sortFieldAttr = layout?.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD); + const sortFieldMeta = typeof sortFieldAttr === "string" ? fieldsByName.get(sortFieldAttr) : undefined; + const sortField = sortFieldMeta !== undefined && isCredential(sortFieldMeta) ? undefined : sortFieldAttr; const sortOrder = layout?.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER); const config: GridConfig = { diff --git a/client/web/packages/runtime-web/test/grid-from-metadata.test.ts b/client/web/packages/runtime-web/test/grid-from-metadata.test.ts index a1986e7580..49f75106ae 100644 --- a/client/web/packages/runtime-web/test/grid-from-metadata.test.ts +++ b/client/web/packages/runtime-web/test/grid-from-metadata.test.ts @@ -192,4 +192,40 @@ describe("a declared @title reaches the column header", () => { const { columns } = buildGrid(obj); expect(columns.find((c) => c.field === "firstName")?.header).toBe("Given Name"); }); + describe("credential fields (view.password)", () => { + const withPin = (grid: unknown) => SUBSCRIBER([ + { "field.string": { name: "pinHash", children: [{ "view.password": {} }] } }, + grid, + ]); + + test("no @columns: credential is not a column", async () => { + const meta = await loadObject(withPin({ "layout.dataGrid": { name: "default" } }), "Subscriber"); + const { columns } = buildGrid(meta); + expect(columns.map((c) => c.field)).toEqual(["id", "firstName", "subscribed", "status"]); + }); + + test("@columns naming the credential: credential is dropped", async () => { + const meta = await loadObject( + withPin({ "layout.dataGrid": { name: "default", "@columns": ["firstName", "pinHash"] } }), + "Subscriber", + ); + expect(buildGrid(meta).columns.map((c) => c.field)).toEqual(["firstName"]); + }); + + test("@defaultSortField naming the credential gives no initial sort", async () => { + const meta = await loadObject( + withPin({ "layout.dataGrid": { name: "default", "@defaultSortField": "pinHash" } }), + "Subscriber", + ); + expect(buildGrid(meta).config.defaultSort).toBeUndefined(); + }); + + test("@defaultSortField naming an ordinary field still sorts", async () => { + const meta = await loadObject( + withPin({ "layout.dataGrid": { name: "default", "@defaultSortField": "firstName" } }), + "Subscriber", + ); + expect(buildGrid(meta).config.defaultSort).toEqual({ field: "firstName", order: "asc" }); + }); + }); }); diff --git a/docs/features/api-contract.md b/docs/features/api-contract.md index df2c2f35d9..5a415be800 100644 --- a/docs/features/api-contract.md +++ b/docs/features/api-contract.md @@ -625,6 +625,13 @@ set (`@mutability: writeOnce` on PATCH, the TPH discriminator, `@autoSet: onCrea a generated edit form submits every field it was given, so a `400` would fail every save. A required field that is also ignored can never be created through the API, so mark such a field optional. +The generated TypeScript client tier follows the same marks. The React and Angular forms render no control +for a credential or a `@formExclude` field. The TanStack and Angular grids never emit a column for a +credential, even when a `layout.dataGrid`'s `@columns` names it, and a `@defaultSortField` naming one gives +the grid no initial sort. A `@filter` preset over a credential fails `meta gen`, because the server would +refuse that filter on every request. On a single-table (TPH) base's grid, a column that any subtype marks as +a credential counts. The agent UI page (`agent/ui.md`) lists a grid's columns and default sort on the same terms. + The same rule covers every key a client never sets, in every port, on the plain and the TPH per-subtype routes: @@ -689,6 +696,10 @@ and its order leaks it): the allowlist is built without it, so a request that na the allowlist does not hold (`400` `invalid_filter_field` or `invalid_sort`, naming the field). On a single-table (TPH) hierarchy the mark holds for the shared column: a column one subtype marks as a credential is on no allowlist of the base or of any subtype. To return a credential from a route, hand-write that route; the generated one will not. Generated forms and the api docs omit both kinds of field as well. +**Known limit:** a credential (`view.password`) declared on a value-object member is not listed, checked or +stripped. Only an entity's top-level fields count, and stripping does not recurse into nested objects. Declare +credentials as top-level entity fields. + A served report is covered too. A report column is derived from its `@of` field, and a derived column keeps that field's credential mark, so a report that groups by a credential (or takes its `min` or `max`) never returns the column, its `report-export` output has no column for it, and it is neither filterable nor sortable diff --git a/docs/features/metadata-driven-runtime.md b/docs/features/metadata-driven-runtime.md index 1827566544..4851c47102 100644 --- a/docs/features/metadata-driven-runtime.md +++ b/docs/features/metadata-driven-runtime.md @@ -83,7 +83,8 @@ What each component takes from the model: | `view.textarea` `@rows` | | a textarea | | `@required`, `@maxLength`, `validator.numeric` `@min`/`@max`, `@default` | | required marks, input limits, starting values | | `relationship.*` with `@cardinality: many` | | the related rows listed beside the row being edited | -| `view.password`, `@formExclude` | | no control: no request may set the field | +| `view.password` | no column, and no first sort; a TPH sibling's credential mark on a shared column is not seen here | no control: no request may set the field | +| `@formExclude` | | no control: no request may set the field | ## Run it diff --git a/docs/ports/typescript-client.md b/docs/ports/typescript-client.md index 76c4ffb776..2c83702378 100644 --- a/docs/ports/typescript-client.md +++ b/docs/ports/typescript-client.md @@ -322,7 +322,8 @@ on `Author`): - `Columns` — array of TanStack `ColumnDef`, one per column key, each carrying `meta.view` (resolved from the field's `view.*` child) for the renderer registry. Omit `@columns` and every - field on the entity becomes a column. + field on the entity becomes a column, except a credential (`view.password`), which is never a column + ([api-contract.md](../features/api-contract.md#credentials-and-excluded-fields)). - `Grid` — the config const carrying `{ name, pageSize, defaultSort?, filterable }` — shape declared as `GridConfig` in `@metaobjectsdev/runtime-web`. diff --git a/examples/advanced-modeling/codegen/templates/filter-shared.ts b/examples/advanced-modeling/codegen/templates/filter-shared.ts index 9e6f5f2253..b4a5863a9a 100644 --- a/examples/advanced-modeling/codegen/templates/filter-shared.ts +++ b/examples/advanced-modeling/codegen/templates/filter-shared.ts @@ -116,7 +116,11 @@ export interface GridDefaultSort { * disagree: the endpoint returns the field's declared order while the grid that * queries it renders the opposite. * - * Returns undefined when the layout names no field — a grid with no initial sort. + * Returns undefined when the layout names no field — a grid with no initial sort — and when + * the field it names is a credential (`credentialFieldNames`): the sort allowlist never holds + * one, so the endpoint would refuse the grid's very first request, and the order of a secret + * leaks it. Pass `root` (the loaded model) so a column a TPH sibling declares as a credential + * counts too. * * The field lookup cannot miss on a LOADED model: `validateDataGridSortFields` * refuses `@defaultSortField` naming a field the entity does not have @@ -130,10 +134,12 @@ export interface GridDefaultSort { export function resolveGridDefaultSort( entity: MetaObject, layout: MetaData, + root?: MetaRoot, ): GridDefaultSort | undefined { // ADR-0039: resolving — a layout may inherit its grid attrs via extends. const fieldName = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD); if (typeof fieldName !== "string" || fieldName === "") return undefined; + if (credentialFieldNames(entity, root).has(fieldName)) return undefined; const declared = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER); if (declared === "asc" || declared === "desc") return { field: fieldName, order: declared }; diff --git a/examples/showcase/codegen/templates/filter-shared.ts b/examples/showcase/codegen/templates/filter-shared.ts index 9e6f5f2253..b4a5863a9a 100644 --- a/examples/showcase/codegen/templates/filter-shared.ts +++ b/examples/showcase/codegen/templates/filter-shared.ts @@ -116,7 +116,11 @@ export interface GridDefaultSort { * disagree: the endpoint returns the field's declared order while the grid that * queries it renders the opposite. * - * Returns undefined when the layout names no field — a grid with no initial sort. + * Returns undefined when the layout names no field — a grid with no initial sort — and when + * the field it names is a credential (`credentialFieldNames`): the sort allowlist never holds + * one, so the endpoint would refuse the grid's very first request, and the order of a secret + * leaks it. Pass `root` (the loaded model) so a column a TPH sibling declares as a credential + * counts too. * * The field lookup cannot miss on a LOADED model: `validateDataGridSortFields` * refuses `@defaultSortField` naming a field the entity does not have @@ -130,10 +134,12 @@ export interface GridDefaultSort { export function resolveGridDefaultSort( entity: MetaObject, layout: MetaData, + root?: MetaRoot, ): GridDefaultSort | undefined { // ADR-0039: resolving — a layout may inherit its grid attrs via extends. const fieldName = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD); if (typeof fieldName !== "string" || fieldName === "") return undefined; + if (credentialFieldNames(entity, root).has(fieldName)) return undefined; const declared = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER); if (declared === "asc" || declared === "desc") return { field: fieldName, order: declared }; diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-runtime-ui/references/tanstack.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-runtime-ui/references/tanstack.md index 38d66c0000..d87d07ce36 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-runtime-ui/references/tanstack.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-runtime-ui/references/tanstack.md @@ -108,7 +108,7 @@ So the minimum to get a grid is a `layout.dataGrid` on the entity: // ...fields... { "layout.dataGrid": { "name": "default", - "@columns": ["name", "email", "createdAt"], // ordered; omit for every field + "@columns": ["name", "email", "createdAt"], // ordered; omit for every field but a credential "@pageSize": 25, "@defaultSortField": "createdAt", "@defaultSortOrder": "desc" diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-runtime-ui/references/tanstack.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-runtime-ui/references/tanstack.md index 38d66c0000..d87d07ce36 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-runtime-ui/references/tanstack.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-runtime-ui/references/tanstack.md @@ -108,7 +108,7 @@ So the minimum to get a grid is a `layout.dataGrid` on the entity: // ...fields... { "layout.dataGrid": { "name": "default", - "@columns": ["name", "email", "createdAt"], // ordered; omit for every field + "@columns": ["name", "email", "createdAt"], // ordered; omit for every field but a credential "@pageSize": 25, "@defaultSortField": "createdAt", "@defaultSortOrder": "desc" diff --git a/server/typescript/packages/codegen-ts-angular/src/templates/grid-file.ts b/server/typescript/packages/codegen-ts-angular/src/templates/grid-file.ts index 88cda58e74..eb7e15474a 100644 --- a/server/typescript/packages/codegen-ts-angular/src/templates/grid-file.ts +++ b/server/typescript/packages/codegen-ts-angular/src/templates/grid-file.ts @@ -4,7 +4,7 @@ // header + meta.view) but in Angular-native shape (EntityGridColumn[]). import { code, imp } from "@metaobjectsdev/codegen-ts"; -import type { MetaField, MetaObject } from "@metaobjectsdev/metadata"; +import type { MetaField, MetaObject, MetaRoot } from "@metaobjectsdev/metadata"; import { LAYOUT_SUBTYPE_DATA_GRID, LAYOUT_DATA_GRID_ATTR_PAGE_SIZE, @@ -20,6 +20,7 @@ import { viewForContext, VIEW_CONTEXT_GRID, resolveGridDefaultSort, + credentialFieldNames, type GridDefaultSort, effectivePackage, } from "@metaobjectsdev/codegen-ts"; @@ -70,8 +71,9 @@ function fieldLabel(field: MetaField): string { return humanize(field.name); } -function extractGrids(entity: MetaObject): GridSpec[] { +function extractGrids(entity: MetaObject, root: MetaRoot): GridSpec[] { const fieldsByName = new Map(entity.fields().map((f) => [f.name, f] as const)); + const credentials = credentialFieldNames(entity, root); const out: GridSpec[] = []; for (const layout of entity.layouts()) { if (layout.subType !== LAYOUT_SUBTYPE_DATA_GRID) continue; @@ -83,6 +85,9 @@ function extractGrids(entity: MetaObject): GridSpec[] { const columns: ColumnSpec[] = columnNames.flatMap((name) => { const f = fieldsByName.get(name); if (!f) return []; + // A credential (a `view.password` on any declaration of the column) is never a column, + // even when @columns names it — the same rule as the TanStack tier and the generated forms. + if (credentials.has(name)) return []; const viewKind = fieldViewKind(f); // #355 — `view.hidden` means "not rendered"; drop the column rather than emit one // that prints the value. Same rule as the TanStack tier, which renders the same @@ -90,7 +95,8 @@ function extractGrids(entity: MetaObject): GridSpec[] { if (viewKind === VIEW_SUBTYPE_HIDDEN) return []; return [{ id: name, header: fieldLabel(f), viewKind }]; }); - const defaultSort = resolveGridDefaultSort(entity, layout); + // A @defaultSortField naming a credential resolves to no initial sort. + const defaultSort = resolveGridDefaultSort(entity, layout, root); const grid: GridSpec = { name: layout.name || "default", pageSize: (layout.attr(LAYOUT_DATA_GRID_ATTR_PAGE_SIZE) as number | undefined) ?? 25, @@ -110,7 +116,7 @@ function renderColumnLiteral(col: ColumnSpec): string { export function renderGridFile(entity: MetaObject, ctx: RenderContext): string { const entityName = entity.name; const lcEntity = entityName.charAt(0).toLowerCase() + entityName.slice(1); - const grids = extractGrids(entity); + const grids = extractGrids(entity, ctx.loadedRoot); const ComponentSym = imp("Component@@angular/core"); const signalSym = imp("signal@@angular/core"); diff --git a/server/typescript/packages/codegen-ts-angular/test/credential-grid-column.test.ts b/server/typescript/packages/codegen-ts-angular/test/credential-grid-column.test.ts new file mode 100644 index 0000000000..5d2117ada7 --- /dev/null +++ b/server/typescript/packages/codegen-ts-angular/test/credential-grid-column.test.ts @@ -0,0 +1,74 @@ +// A credential (a field that declares `view.password`) is never an Angular grid column or +// initial sort — the same rule as the TanStack tier and the generated forms. The server never +// returns its value and keeps it off the sort and filter allowlists. + +import { describe, test, expect } from "bun:test"; +import { angularGridFile } from "../src/index.js"; +import { makeRenderContext, buildPkMap, buildRelationMap } from "@metaobjectsdev/codegen-ts"; +import type { GenContext } from "@metaobjectsdev/codegen-ts"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; + +async function render(grid: Record): Promise { + const json = JSON.stringify({ + "metadata.root": { + children: [{ + "object.entity": { + name: "Account", + children: [ + { "source.rdb": { "@table": "account" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + { "field.string": { name: "email", "@filterable": true } }, + { + "field.string": { + name: "pinHash", "@filterable": true, "@sortable": true, + children: [{ "view.password": {} }], + }, + }, + { "layout.dataGrid": { name: "default", ...grid } }, + ], + }, + }], + }, + }); + const { root, errors } = await new MetaDataLoader({ strict: true }) + .load([new InMemoryStringSource(json, { id: "account.json" })]); + expect(errors.map((e) => e.message)).toEqual([]); + const renderContext = makeRenderContext({ + dialect: "sqlite", loadedRoot: root, outDir: "/tmp", + dbImport: "../db", extStyle: "none", + pkMap: buildPkMap(root), relationMap: buildRelationMap(root), + }); + const ctx: GenContext = { + entities: root.objects(), + loadedRoot: root, + matches: () => true, + config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" }, + renderContext, + warn: () => {}, + }; + const files = await angularGridFile().generate(ctx); + const file = files.find((f) => f.path.includes("Account")); + if (file === undefined) throw new Error(`no grid emitted; got ${files.map((f) => f.path).join(", ")}`); + return file.content; +} + +describe("a credential is not an Angular grid column", () => { + test("dropped when @columns names it explicitly", async () => { + const out = await render({ "@columns": ["email", "pinHash"] }); + expect(out).toContain('id: "email"'); + expect(out).not.toContain("pinHash"); + }); + + test("dropped when @columns is omitted and every field becomes a column", async () => { + const out = await render({}); + expect(out).toContain('id: "email"'); + expect(out).not.toContain("pinHash"); + }); + + test("a @defaultSortField naming it gives no initial sort", async () => { + const out = await render({ "@columns": ["email"], "@defaultSortField": "pinHash" }); + expect(out).not.toContain("defaultSort"); + expect(out).not.toContain("pinHash"); + }); +}); diff --git a/server/typescript/packages/codegen-ts-tanstack/README.md b/server/typescript/packages/codegen-ts-tanstack/README.md index 59fd837681..10d958eec3 100644 --- a/server/typescript/packages/codegen-ts-tanstack/README.md +++ b/server/typescript/packages/codegen-ts-tanstack/README.md @@ -10,7 +10,7 @@ TanStack codegen for MetaObjects. Provides `tanstackQuery()` (per-entity `Columns` + `Grid` pair from `tanstackGrid()` and a `useGrid()` from `tanstackGridHook()`. +`@columns` is an ordered list; omit it to get every field except a credential (`view.password`), which is never a column. Each `layout.dataGrid` yields a `Columns` + `Grid` pair from `tanstackGrid()` and a `useGrid()` from `tanstackGridHook()`. ### M:N collection hooks (FR-018) diff --git a/server/typescript/packages/codegen-ts-tanstack/src/templates/columns-file.ts b/server/typescript/packages/codegen-ts-tanstack/src/templates/columns-file.ts index 93170f240c..c382293968 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/templates/columns-file.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/templates/columns-file.ts @@ -1,5 +1,5 @@ import { code, imp, joinCode, type Code } from "@metaobjectsdev/codegen-ts/engine"; -import type { MetaObject, MetaField } from "@metaobjectsdev/metadata"; +import type { MetaObject, MetaField, MetaRoot } from "@metaobjectsdev/metadata"; import { LAYOUT_SUBTYPE_DATA_GRID, LAYOUT_DATA_GRID_ATTR_PAGE_SIZE, @@ -8,6 +8,8 @@ import { LAYOUT_DATA_GRID_ATTR_COLUMNS, OBJECT_ATTR_DISCRIMINATOR, VIEW_SUBTYPE_HIDDEN, + FILTER_COMPOSE_AND, + FILTER_COMPOSE_OR, } from "@metaobjectsdev/metadata"; import type { RenderContext } from "@metaobjectsdev/codegen-ts/engine"; import { @@ -18,8 +20,10 @@ import { VIEW_CONTEXT_GRID, effectivePackage, flatSurfaceFields, + tphHierarchy, } from "@metaobjectsdev/codegen-ts/engine"; import { + credentialFieldNames, isSortableField, resolveGridDefaultSort, type GridDefaultSort, @@ -90,6 +94,35 @@ function fieldLabel(field: MetaField): string { return humanize(field.name); } +/** + * Every column name a credential occupies anywhere in `entity`'s single table: a TPH base's + * polymorphic grid folds in subtype-only columns, so the marks of every subtype count, not only + * the base's own (`credentialFieldNames` answers for one object's own columns). + */ +function gridCredentialNames(entity: MetaObject, root: MetaRoot): ReadonlySet { + return new Set(tphHierarchy(entity, root).flatMap((o) => [...credentialFieldNames(o, root)])); +} + +/** + * The first credential a grid's `@filter` preset names, at any depth of its `and` / `or` + * composition, or undefined when it names none. + */ +function credentialInFilter(filter: Record, credentials: ReadonlySet): string | undefined { + for (const [key, clause] of Object.entries(filter)) { + if (key === FILTER_COMPOSE_AND || key === FILTER_COMPOSE_OR) { + if (!Array.isArray(clause)) continue; + for (const sub of clause) { + if (typeof sub !== "object" || sub === null || Array.isArray(sub)) continue; + const found = credentialInFilter(sub as Record, credentials); + if (found !== undefined) return found; + } + continue; + } + if (credentials.has(key)) return key; + } + return undefined; +} + /** * Extract grid specs from an entity's dataGrid layouts, resolving column * metadata against the entity's field list. @@ -98,7 +131,7 @@ function fieldLabel(field: MetaField): string { * fall back to all fields on the entity (pre-E-T2 behaviour, kept for * backwards compat with metadata not yet migrated by E-T4). */ -function extractGrids(entity: MetaObject, tph?: TphGridInfo): GridSpec[] { +function extractGrids(entity: MetaObject, root: MetaRoot, tph?: TphGridInfo): GridSpec[] { // fields() and layouts() are both effective (own + inherited via extends:/super:). // For a TPH base, also index the subtype-only fields so they can be folded // into the polymorphic grid's column set. @@ -106,6 +139,8 @@ function extractGrids(entity: MetaObject, tph?: TphGridInfo): GridSpec[] { [...flatSurfaceFields(entity), ...(tph?.subtypeFields ?? [])].map((f) => [f.name, f] as const), ); + const credentials = gridCredentialNames(entity, root); + const grids: GridSpec[] = []; for (const layout of entity.layouts()) { if (layout.subType !== LAYOUT_SUBTYPE_DATA_GRID) continue; @@ -131,6 +166,11 @@ function extractGrids(entity: MetaObject, tph?: TphGridInfo): GridSpec[] { const columns: ColumnSpec[] = columnNames.flatMap((name) => { const field = fieldsByName.get(name); if (!field) return []; // columns ref that doesn't exist on entity; defensive skip + // A credential (a `view.password` on any declaration of the column) is never a column, + // even when @columns names it: the generated API never returns its value, and a header + // would offer a sort and a filter the server's allowlists refuse. Same rule as the + // generated forms, which skip it. + if (credentials.has(name)) return []; const viewKind = fieldViewKind(field); // #355 — `view.hidden` is registered as "Not rendered; carried but not shown", and // the generated FORM has always honoured that (an ). The grid @@ -160,7 +200,8 @@ function extractGrids(entity: MetaObject, tph?: TphGridInfo): GridSpec[] { }); // ADR-0039: resolving — dataGrid layout attrs may be inherited via extends. - const defaultSort = resolveGridDefaultSort(entity, layout); + // A @defaultSortField naming a credential resolves to no initial sort. + const defaultSort = resolveGridDefaultSort(entity, layout, root); const filterAttr = layout.attr(LAYOUT_DATA_GRID_ATTR_FILTER); const grid: GridSpec = { @@ -171,7 +212,19 @@ function extractGrids(entity: MetaObject, tph?: TphGridInfo): GridSpec[] { }; if (defaultSort !== undefined) grid.defaultSort = defaultSort; if (typeof filterAttr === "object" && filterAttr !== null && !Array.isArray(filterAttr)) { - grid.filter = filterAttr as Record; + const filter = filterAttr as Record; + // A preset filter over a credential is refused, not rewritten. The server's filter + // allowlist never holds a credential, so the grid's every request would answer 400; and + // dropping the clause would silently change which rows the grid shows. + const credential = credentialInFilter(filter, credentials); + if (credential !== undefined) { + throw new Error( + `dataGrid layout "${grid.name}" on entity "${entity.name}" has @filter over credential ` + + `field "${credential}" (it declares a view.password). A credential is never filterable: ` + + "remove the clause from @filter.", + ); + } + grid.filter = filter; } grids.push(grid); } @@ -206,7 +259,7 @@ export function renderColumnsFile(entity: MetaObject, ctx: RenderContext): strin subtypeFields: collectTphSubtypeFields(entity, ctx.loadedRoot), } : undefined; - const grids = extractGrids(entity, tph); + const grids = extractGrids(entity, ctx.loadedRoot, tph); const ColumnDefSym = imp("t:ColumnDef@@tanstack/react-table"); diff --git a/server/typescript/packages/codegen-ts-tanstack/src/templates/grid-hook-file.ts b/server/typescript/packages/codegen-ts-tanstack/src/templates/grid-hook-file.ts index 1b73bd095e..4584cd3011 100644 --- a/server/typescript/packages/codegen-ts-tanstack/src/templates/grid-hook-file.ts +++ b/server/typescript/packages/codegen-ts-tanstack/src/templates/grid-hook-file.ts @@ -9,7 +9,7 @@ // import { code, imp, joinCode, type Code } from "@metaobjectsdev/codegen-ts/engine"; -import type { MetaObject, MetaLayout } from "@metaobjectsdev/metadata"; +import type { MetaObject, MetaLayout, MetaRoot } from "@metaobjectsdev/metadata"; import { LAYOUT_SUBTYPE_DATA_GRID } from "@metaobjectsdev/metadata"; import type { RenderContext } from "@metaobjectsdev/codegen-ts/engine"; @@ -43,7 +43,7 @@ interface GridSpec { defaultSort?: GridDefaultSort | undefined; } -function extractGrids(entity: MetaObject): GridSpec[] { +function extractGrids(entity: MetaObject, root: MetaRoot): GridSpec[] { const out: GridSpec[] = []; for (const l of entity.layouts() as MetaLayout[]) { if (l.subType !== LAYOUT_SUBTYPE_DATA_GRID) continue; @@ -51,7 +51,8 @@ function extractGrids(entity: MetaObject): GridSpec[] { name: l.name || "default", pageSize: l.pageSize ?? 25, hasFilterPreset: l.filter !== undefined, - defaultSort: resolveGridDefaultSort(entity, l), + // A @defaultSortField naming a credential resolves to no initial sort, as in the grid const. + defaultSort: resolveGridDefaultSort(entity, l, root), }); } return out; @@ -64,7 +65,7 @@ function capitalize(s: string): string { export function renderGridHookFile(entity: MetaObject, ctx: RenderContext): string { const entityName = entity.name; const lcEntity = entityName.charAt(0).toLowerCase() + entityName.slice(1); - const grids = extractGrids(entity); + const grids = extractGrids(entity, ctx.loadedRoot); if (grids.length === 0) return ""; diff --git a/server/typescript/packages/codegen-ts-tanstack/test/credential-grid-column.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/credential-grid-column.test.ts new file mode 100644 index 0000000000..5a124c66f6 --- /dev/null +++ b/server/typescript/packages/codegen-ts-tanstack/test/credential-grid-column.test.ts @@ -0,0 +1,153 @@ +// A credential (a field that declares `view.password`) is never a grid column, sort or filter. +// +// The generated forms skip a credential, and the server keeps it out of every response and off +// the filter and sort allowlists. The grid did neither: a dataGrid whose `@columns` named one +// emitted a column for it (a header, a cell, a sortable flag), a `@defaultSortField` naming one +// became the grid's initial sort, and a `@filter` preset over one was emitted verbatim. Each of +// those is a request the server refuses, and the column advertises a secret the API never sends. + +import { describe, test, expect } from "bun:test"; +import { renderColumnsFile } from "../src/templates/columns-file.js"; +import { renderGridHookFile } from "../src/templates/grid-hook-file.js"; +import { makeRenderContext, buildPkMap, buildRelationMap } from "@metaobjectsdev/codegen-ts"; +import { MetaDataLoader, InMemoryStringSource, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; + +const PASSWORD = { "view.password": {} }; + +async function load(children: unknown[]): Promise { + const json = JSON.stringify({ "metadata.root": { package: "demo", children } }); + const { root, errors } = await new MetaDataLoader({ strict: true }) + .load([new InMemoryStringSource(json, { id: "credential-grid.json" })]); + expect(errors.map((e) => e.message)).toEqual([]); + return root; +} + +function ctxFor(root: MetaRoot) { + return makeRenderContext({ + dialect: "sqlite", loadedRoot: root, outDir: "/tmp", + dbImport: "../db", extStyle: "none", + pkMap: buildPkMap(root), relationMap: buildRelationMap(root), + }); +} + +function find(root: MetaRoot, name: string): MetaObject { + const obj = root.objects().find((o) => o.name === name); + if (obj === undefined) throw new Error(`no object ${name}`); + return obj; +} + +/** An Account whose `pinHash` is a credential the model ALSO marks filterable and sortable. */ +function account(grid: Record): unknown[] { + return [{ + "object.entity": { + name: "Account", + children: [ + { "source.rdb": { "@table": "account" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + { "field.string": { name: "email", "@filterable": true } }, + { "field.string": { name: "pinHash", "@filterable": true, "@sortable": true, children: [PASSWORD] } }, + { "layout.dataGrid": { name: "default", ...grid } }, + ], + }, + }]; +} + +describe("a credential is not a TanStack grid column", () => { + test("dropped when @columns names it explicitly", async () => { + const root = await load(account({ "@columns": ["email", "pinHash"] })); + const out = renderColumnsFile(find(root, "Account"), ctxFor(root)); + expect(out).toContain('id: "email"'); + expect(out).not.toContain("pinHash"); + }); + + test("dropped when @columns is omitted and every field becomes a column", async () => { + const root = await load(account({})); + const out = renderColumnsFile(find(root, "Account"), ctxFor(root)); + expect(out).toContain('id: "email"'); + expect(out).not.toContain("pinHash"); + }); + + test("a @defaultSortField naming it gives no initial sort, in the grid const and the hook", async () => { + const root = await load(account({ "@columns": ["email"], "@defaultSortField": "pinHash" })); + const entity = find(root, "Account"); + const columns = renderColumnsFile(entity, ctxFor(root)); + expect(columns).not.toContain("defaultSort"); + expect(columns).not.toContain("pinHash"); + const hook = renderGridHookFile(entity, ctxFor(root)); + expect(hook).toContain("useState([])"); + expect(hook).not.toContain("pinHash"); + }); + + test("a @filter preset over it is refused, not emitted", async () => { + const root = await load(account({ "@columns": ["email"], "@filter": { pinHash: { eq: "x" } } })); + expect(() => renderColumnsFile(find(root, "Account"), ctxFor(root))).toThrow( + /@filter over credential field "pinHash"/, + ); + }); + + test("a @filter preset naming it inside an or-composition is refused too", async () => { + const root = await load( + account({ "@columns": ["email"], "@filter": { or: [{ email: { eq: "a" } }, { pinHash: { eq: "x" } }] } }), + ); + expect(() => renderColumnsFile(find(root, "Account"), ctxFor(root))).toThrow(/"pinHash"/); + }); + + test("a @filter preset over other fields is still emitted", async () => { + const root = await load(account({ "@columns": ["email"], "@filter": { email: { eq: "a" } } })); + const out = renderColumnsFile(find(root, "Account"), ctxFor(root)); + expect(out).toContain("accountDefaultFilter"); + }); +}); + +describe("a credential is not a column of a TPH base's polymorphic grid", () => { + // `pin` is a subtype-only column, folded into the base grid. `code` is a column two + // subtypes share, and only ONE declares it a credential: one physical column, so it is a + // credential on every row, the same rule the generated routes apply. + async function loadTph(): Promise { + return load([ + { + "object.entity": { + name: "Auth", + "@discriminator": "type", + children: [ + { "source.rdb": { "@table": "auths" } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "id", "@fields": "id", "@generation": "increment" } }, + { "layout.dataGrid": { name: "default", "@columns": ["type", "id", "pin", "code"] } }, + ], + }, + }, + { + "object.entity": { + name: "BridgeAuth", + extends: "Auth", + "@discriminatorValue": "Bridge", + children: [ + { "field.int": { name: "quantity" } }, + { "field.string": { name: "pin", children: [PASSWORD] } }, + { "field.string": { name: "code" } }, + ], + }, + }, + { + "object.entity": { + name: "CouponAuth", + extends: "Auth", + "@discriminatorValue": "Coupon", + children: [{ "field.string": { name: "code", children: [PASSWORD] } }], + }, + }, + ]); + } + + test("a subtype-only credential and a sibling-marked shared column are both dropped", async () => { + const root = await loadTph(); + const out = renderColumnsFile(find(root, "Auth"), ctxFor(root)); + expect(out).toContain('id: "type"'); + expect(out).toContain('id: "quantity"'); + expect(out).not.toContain('"pin"'); + expect(out).not.toContain('"code"'); + }); +}); diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-ui-page.ts b/server/typescript/packages/codegen-ts/src/generators/agent-ui-page.ts index ef9bf5b4d1..ac8228d4cb 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-ui-page.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-ui-page.ts @@ -42,7 +42,7 @@ import type { MetaData, MetaObject, MetaRoot } from "@metaobjectsdev/metadata"; import { flatSurfaceFields } from "../flattened.js"; import { GENERATED_HEADER } from "../constants.js"; import { generatableObjects, isReport } from "../source-detect.js"; -import { hasGeneratedForm, restPath, servedPath, servesClientHooks } from "../api-surface.js"; +import { hasGeneratedForm, isCredentialField, restPath, servedPath, servesClientHooks, tphHierarchy } from "../api-surface.js"; import { buildEntityUiDescriptor, type UiFieldDescriptor, @@ -183,19 +183,24 @@ export function hasUiSurface(obj: MetaObject): boolean { return servesClientHooks(obj); } -function gridSection(obj: MetaObject, grid: MetaData): string[] { +function gridSection(obj: MetaObject, grid: MetaData, root: MetaRoot): string[] { const out: string[] = []; out.push(`**Grid \`${grid.name}\`**`); out.push(""); + // A credential is never a grid column, even when @columns names it — the generated grids + // drop it, so the page does not list it. A TPH base grid folds in every subtype's columns, so + // a credential on any member of the hierarchy counts (the rule the tanstack grid uses). + const credentials = new Set(tphHierarchy(obj, root).flatMap((o) => [...credentialFieldNames(o, root)])); const columns = grid.attr(LAYOUT_DATA_GRID_ATTR_COLUMNS); - if (Array.isArray(columns) && columns.length > 0) { - out.push(`- columns: ${columns.map((c) => `\`${String(c)}\``).join(", ")}`); + const shown = Array.isArray(columns) ? columns.map(String).filter((c) => !credentials.has(c)) : []; + if (shown.length > 0) { + out.push(`- columns: ${shown.map((c) => `\`${c}\``).join(", ")}`); } // The RESOLVED sort, through the same call the grid const and grid hook use — a // page that read the two attrs itself would print no direction for a grid whose // direction comes from the named field's @sortableDefaultOrder, i.e. would teach // an agent the opposite of what the generated grid does. - const defaultSort = resolveGridDefaultSort(obj, grid); + const defaultSort = resolveGridDefaultSort(obj, grid, root); if (defaultSort !== undefined) { out.push(`- default sort: \`${defaultSort.field}:${defaultSort.order}\``); } @@ -264,7 +269,8 @@ export function renderAgentUiPage(root: MetaRoot, apiPrefix = ""): string { controlCell(f), htmlTypeCell(f), f.rules.map(ruleText).join(" · "), - node === undefined ? "" : flag(node.attr(FIELD_ATTR_FORM_EXCLUDE)), + // The generated forms skip a credential exactly as they skip @formExclude. + node === undefined ? "" : flag(node.attr(FIELD_ATTR_FORM_EXCLUDE) === true || isCredentialField(node)), node === undefined ? "" : flag(isFilterableField(node) && !credentials.has(f.name)), node === undefined ? "" : flag(isSortableField(node) && !credentials.has(f.name)), ]; @@ -296,7 +302,7 @@ export function renderAgentUiPage(root: MetaRoot, apiPrefix = ""): string { } for (const grid of dataGrids(obj)) { out.push(""); - out.push(...gridSection(obj, grid)); + out.push(...gridSection(obj, grid, root)); } out.push(""); } diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index 85c5a9d9d2..ebeaf31954 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -176,6 +176,7 @@ export { declaredSortDefaultOrder, sortDefaultOrder, resolveGridDefaultSort, + credentialFieldNames, } from "./templates/filter-shared.js"; export type { SortOrder, GridDefaultSort } from "./templates/filter-shared.js"; diff --git a/server/typescript/packages/codegen-ts/src/templates/filter-shared.ts b/server/typescript/packages/codegen-ts/src/templates/filter-shared.ts index 44e9c7688e..bd31cc5977 100644 --- a/server/typescript/packages/codegen-ts/src/templates/filter-shared.ts +++ b/server/typescript/packages/codegen-ts/src/templates/filter-shared.ts @@ -116,7 +116,11 @@ export interface GridDefaultSort { * disagree: the endpoint returns the field's declared order while the grid that * queries it renders the opposite. * - * Returns undefined when the layout names no field — a grid with no initial sort. + * Returns undefined when the layout names no field — a grid with no initial sort — and when + * the field it names is a credential (`credentialFieldNames`): the sort allowlist never holds + * one, so the endpoint would refuse the grid's very first request, and the order of a secret + * leaks it. Pass `root` (the loaded model) so a column a TPH sibling declares as a credential + * counts too. * * The field lookup cannot miss on a LOADED model: `validateDataGridSortFields` * refuses `@defaultSortField` naming a field the entity does not have @@ -130,10 +134,12 @@ export interface GridDefaultSort { export function resolveGridDefaultSort( entity: MetaObject, layout: MetaData, + root?: MetaRoot, ): GridDefaultSort | undefined { // ADR-0039: resolving — a layout may inherit its grid attrs via extends. const fieldName = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD); if (typeof fieldName !== "string" || fieldName === "") return undefined; + if (credentialFieldNames(entity, root).has(fieldName)) return undefined; const declared = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER); if (declared === "asc" || declared === "desc") return { field: fieldName, order: declared }; diff --git a/server/typescript/packages/codegen-ts/test/agent-ui-credential.test.ts b/server/typescript/packages/codegen-ts/test/agent-ui-credential.test.ts new file mode 100644 index 0000000000..fe368d4181 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/agent-ui-credential.test.ts @@ -0,0 +1,106 @@ +// agent/ui.md describes what the generated forms and grids ARE, so a credential (a field that +// declares `view.password`) is described the way they treat it: excluded from the form, never a +// grid column, never the grid's initial sort, and neither filterable nor sortable. + +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { renderAgentUiPage } from "../src/generators/agent-ui-page.js"; + +async function page(): Promise { + const model = { + "metadata.root": { + children: [{ + "object.entity": { + name: "Account", + children: [ + { "source.rdb": { "@table": "account" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + { "field.string": { name: "email", "@filterable": true } }, + { + "field.string": { + name: "pinHash", "@filterable": true, "@sortable": true, + children: [{ "view.password": {} }], + }, + }, + { + "layout.dataGrid": { + name: "default", "@columns": ["email", "pinHash"], "@defaultSortField": "pinHash", + }, + }, + ], + }, + }], + }, + }; + const res = await new MetaDataLoader({ strict: true }).load([ + new InMemoryStringSource(JSON.stringify(model), { id: "meta.json", format: "json" }), + ]); + expect(res.errors).toEqual([]); + return renderAgentUiPage(res.root); +} + +describe("agent/ui.md describes a credential as the generated UI treats it", () => { + test("its field row is marked excluded, and neither filterable nor sortable", async () => { + const row = (await page()).split("\n").find((l) => l.startsWith("| `pinHash`")); + expect(row).toBeDefined(); + const cells = row!.split("|").map((c) => c.trim()); + // | Field | Label | Control | HTML type | Rules | Excluded | Filter | Sort | + expect(cells.slice(6, 9)).toEqual(["yes", "", ""]); + }); + + test("the grid section lists no credential column and no default sort on it", async () => { + const out = await page(); + expect(out).toContain("- columns: `email`"); + expect(out).not.toContain("`email`, `pinHash`"); + expect(out).not.toContain("default sort"); + }); + + // Oracle: the generated TanStack grid (credential-grid-column.test.ts) drops these same + // columns from the TPH base grid. A page that lists them contradicts the generated code. + test("a TPH base grid lists neither a subtype-only credential nor a sibling-marked shared column", async () => { + const PASSWORD = { "view.password": {} }; + const model = { + "metadata.root": { + children: [ + { + "object.entity": { + name: "Auth", + "@discriminator": "type", + children: [ + { "source.rdb": { "@table": "auths" } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "id", "@fields": "id", "@generation": "increment" } }, + { "layout.dataGrid": { name: "default", "@columns": ["type", "id", "pin", "code"] } }, + ], + }, + }, + { + "object.entity": { + name: "BridgeAuth", extends: "Auth", "@discriminatorValue": "Bridge", + children: [ + { "field.string": { name: "pin", children: [PASSWORD] } }, + { "field.string": { name: "code" } }, + ], + }, + }, + { + "object.entity": { + name: "CouponAuth", extends: "Auth", "@discriminatorValue": "Coupon", + children: [{ "field.string": { name: "code", children: [PASSWORD] } }], + }, + }, + ], + }, + }; + const res = await new MetaDataLoader({ strict: true }).load([ + new InMemoryStringSource(JSON.stringify(model), { id: "meta.json", format: "json" }), + ]); + expect(res.errors).toEqual([]); + const out = renderAgentUiPage(res.root); + expect(out).toContain("- columns: `type`, `id`"); + expect(out).not.toContain("`pin`, `code`"); + expect(out).not.toMatch(/- columns:.*`(pin|code)`/); + }); +}); diff --git a/server/typescript/packages/test-generators/src/templates/filter-shared.ts b/server/typescript/packages/test-generators/src/templates/filter-shared.ts index 9e6f5f2253..b4a5863a9a 100644 --- a/server/typescript/packages/test-generators/src/templates/filter-shared.ts +++ b/server/typescript/packages/test-generators/src/templates/filter-shared.ts @@ -116,7 +116,11 @@ export interface GridDefaultSort { * disagree: the endpoint returns the field's declared order while the grid that * queries it renders the opposite. * - * Returns undefined when the layout names no field — a grid with no initial sort. + * Returns undefined when the layout names no field — a grid with no initial sort — and when + * the field it names is a credential (`credentialFieldNames`): the sort allowlist never holds + * one, so the endpoint would refuse the grid's very first request, and the order of a secret + * leaks it. Pass `root` (the loaded model) so a column a TPH sibling declares as a credential + * counts too. * * The field lookup cannot miss on a LOADED model: `validateDataGridSortFields` * refuses `@defaultSortField` naming a field the entity does not have @@ -130,10 +134,12 @@ export interface GridDefaultSort { export function resolveGridDefaultSort( entity: MetaObject, layout: MetaData, + root?: MetaRoot, ): GridDefaultSort | undefined { // ADR-0039: resolving — a layout may inherit its grid attrs via extends. const fieldName = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD); if (typeof fieldName !== "string" || fieldName === "") return undefined; + if (credentialFieldNames(entity, root).has(fieldName)) return undefined; const declared = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER); if (declared === "asc" || declared === "desc") return { field: fieldName, order: declared };