From fa327e3ff38b22067275b00ba01f4ed4e6dcc29e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 09:32:58 +0000 Subject: [PATCH 01/10] fix(spec, core, plugin-security, plugin-approvals, plugin-audit, service-analytics): platform refusals carry a userMessage in the caller's language The 404 RECORD_NOT_FOUND, the 403 unreadable-query-field refusal (all four producers), the 403 DELEGATION_SCOPE_VIOLATION and the per-row 409 RECORD_LOCKED now mark the end user's sentence as userMessage, rendered from three new keys of the shared operation-message catalog (en, zh-CN, ja-JP, es-ES) in the request locale, else the workspace default. Code, status and message are unchanged. Claude-Session: https://claude.ai/code/session_01ADHkmPhCxzY1uTqhToLhkv Co-authored-by: Claude --- .../34699-platform-refusal-user-message.md | 25 ++ packages/core/src/index.ts | 4 + .../src/security/own-row-delete-routes.ts | 4 +- .../src/utils/operation-user-message.test.ts | 53 ++++ .../core/src/utils/operation-user-message.ts | 38 +++ packages/core/src/utils/record-not-found.ts | 15 +- .../src/protocol-batch-data.ts | 4 +- .../src/protocol-data-crud.ts | 4 +- .../src/protocol-data-writes.ts | 4 +- .../src/engine-delete-and-aggregate.ts | 2 +- .../objectql/src/engine-field-write-lock.ts | 2 +- packages/objectql/src/engine-update.ts | 2 +- .../plugin-approvals/src/lifecycle-hooks.ts | 13 +- .../src/payload-predicate-guard.test.ts | 14 ++ .../src/payload-predicate-guard.ts | 12 +- .../record-lock-user-facing-message.test.ts | 5 + .../src/activity-predicate-guard.test.ts | 15 ++ .../src/parent-field-query-guard.ts | 7 +- .../src/platform-refusal-user-message.test.ts | 231 ++++++++++++++++++ .../src/security-plugin-authz-middleware.ts | 38 ++- packages/rest/src/data-action-routes.ts | 2 +- packages/rest/src/record-page-routes.ts | 4 +- packages/runtime/src/action-execution.ts | 6 +- .../field-read-admission-gate.test.ts | 16 ++ .../src/field-read-admission.ts | 14 +- .../service-print/src/print-service.ts | 4 +- .../spec/src/system/operation-message.test.ts | 48 ++++ packages/spec/src/system/operation-message.ts | 37 +++ 28 files changed, 587 insertions(+), 36 deletions(-) create mode 100644 .changeset/34699-platform-refusal-user-message.md create mode 100644 packages/core/src/utils/operation-user-message.test.ts create mode 100644 packages/core/src/utils/operation-user-message.ts create mode 100644 packages/plugins/plugin-security/src/platform-refusal-user-message.test.ts diff --git a/.changeset/34699-platform-refusal-user-message.md b/.changeset/34699-platform-refusal-user-message.md new file mode 100644 index 00000000000..9cc457bf1ee --- /dev/null +++ b/.changeset/34699-platform-refusal-user-message.md @@ -0,0 +1,25 @@ +--- +"@objectstack/spec": patch +"@objectstack/core": patch +"@objectstack/plugin-security": patch +"@objectstack/plugin-approvals": patch +"@objectstack/plugin-audit": patch +"@objectstack/service-analytics": patch +"@objectstack/objectql": patch +"@objectstack/metadata-protocol": patch +"@objectstack/runtime": patch +"@objectstack/rest": patch +"@objectstack/service-print": patch +--- + +Clause-②: no +Metadata-protocol: none + +Four refusals the platform writes now carry a `userMessage` in the caller's language (the request locale, else the workspace default), beside a code, status and `message` that do not change. Before this a zh-CN user read each of them in English. + +- `404 RECORD_NOT_FOUND`: "This record does not exist, or you do not have access to it." (`record_not_found`). It names no id and no API name, and it says both causes because the by-id doors answer an unreadable id exactly as a missing one. +- `403 PERMISSION_DENIED` for a query that filters, sorts or groups by a field the caller may not read (`query_field_not_readable`), from all four producers of that refusal: plugin-security, the approval snapshot guard, the audit parent-field guard and analytics. It names no field. The aggregate refusal is unchanged. +- `403 DELEGATION_SCOPE_VIOLATION`, a delegated administrator's write outside their own scope (`delegation_scope_violation`). The gate's reason stays in `message`. +- `409 RECORD_LOCKED` from an approval's record lock: the localized sentence is now also the `userMessage`, without the `RECORD_LOCKED: ` prefix. The bound refusals that name an API name for the developer mark none. + +The three sentences are new keys of the shared operation-message catalog (`BUILTIN_OPERATION_MESSAGES`, in `en`, `zh-CN`, `ja-JP` and `es-ES`), so a deployment can override them under `errors.` where the producer holds an i18n service. `@objectstack/core` exports `operationUserMessage(messageKey, caller)` for producers that hold none, and `recordNotFoundError` takes the caller as an optional third argument. diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b9344790bdb..b3cc71bb6f6 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -221,6 +221,10 @@ export * from './utils/metadata-activation-store.js'; // with. `@objectstack/metadata-protocol` re-exports it from its original home. export * from './utils/record-not-found.js'; +// [#34699] A catalog sentence in the caller's language, for the `userMessage` a +// producer that holds no `i18n` service marks beside its developer `message`. +export * from './utils/operation-user-message.js'; + // The one `OBJECT_NOT_FOUND` envelope: the data door's object-existence gate // and the engine's in-process verbs refuse a name the registry does not // resolve with it (one name space for both doors). diff --git a/packages/core/src/security/own-row-delete-routes.ts b/packages/core/src/security/own-row-delete-routes.ts index 48a5ae731c4..38356bd606f 100644 --- a/packages/core/src/security/own-row-delete-routes.ts +++ b/packages/core/src/security/own-row-delete-routes.ts @@ -216,7 +216,7 @@ export async function removeOwnRow( | Record | null | undefined; - if (!row) throw recordNotFoundError(door.object, id); + if (!row) throw recordNotFoundError(door.object, id, context); // Step 6: the structural check, and the only thing that admits the write below. if (row[door.ownerField] !== callerId) throw notYourRowError(door, id); @@ -230,7 +230,7 @@ export async function removeOwnRow( } as ExecutionContext, }); // The driver's own "nothing matched": the row went between the read and here. - if (removed === false || removed === 0) throw recordNotFoundError(door.object, id); + if (removed === false || removed === 0) throw recordNotFoundError(door.object, id, context); } async function handleRemoveOwnRow( diff --git a/packages/core/src/utils/operation-user-message.test.ts b/packages/core/src/utils/operation-user-message.test.ts new file mode 100644 index 00000000000..ce052401bb7 --- /dev/null +++ b/packages/core/src/utils/operation-user-message.test.ts @@ -0,0 +1,53 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { operationUserMessage } from './operation-user-message.js'; +import { recordNotFoundError } from './record-not-found.js'; + +/** + * [#34699] The catalog sentence a producer with no `i18n` service marks as a + * refusal's `userMessage`, and the not-found that marks one. + */ +describe('operationUserMessage — the caller ladder', () => { + const ZH = BUILTIN_OPERATION_MESSAGES['zh-CN'].record_not_found; + const EN = BUILTIN_OPERATION_MESSAGES.en.record_not_found; + + it('the request locale first', () => { + expect(operationUserMessage('record_not_found', { locale: 'zh-CN', workspaceLocale: 'en' })).toBe(ZH); + }); + + it('a request locale the catalog does not carry falls to the workspace default', () => { + expect(operationUserMessage('record_not_found', { locale: 'xx-YY', workspaceLocale: 'zh-CN' })).toBe(ZH); + }); + + it('a base language reaches its regional catalog (zh → zh-CN)', () => { + expect(operationUserMessage('record_not_found', { locale: 'zh' })).toBe(ZH); + }); + + it('no caller, or no rung the catalog carries: en', () => { + expect(operationUserMessage('record_not_found')).toBe(EN); + expect(operationUserMessage('record_not_found', null)).toBe(EN); + expect(operationUserMessage('record_not_found', { locale: 'xx-YY', workspaceLocale: '' })).toBe(EN); + }); +}); + +describe('recordNotFoundError — the userMessage beside an unchanged envelope', () => { + it('keeps code, status, object and the developer message byte for byte', () => { + const err = recordNotFoundError('account', 'acc_1', { locale: 'zh-CN' }) as Error & Record; + expect([err.code, err.status, err.object]).toEqual(['RECORD_NOT_FOUND', 404, 'account']); + expect(err.message).toBe('Record acc_1 not found in account'); + }); + + it("marks the sentence in the caller's language, naming no id and no API name", () => { + const err = recordNotFoundError('account', 'acc_1', { locale: 'zh-CN' }) as Error & { userMessage?: string }; + expect(err.userMessage).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_not_found); + expect(err.userMessage).not.toContain('acc_1'); + expect(err.userMessage).not.toContain('account'); + }); + + it('with no caller, the English sentence', () => { + const err = recordNotFoundError('account', 'acc_1') as Error & { userMessage?: string }; + expect(err.userMessage).toBe(BUILTIN_OPERATION_MESSAGES.en.record_not_found); + }); +}); diff --git a/packages/core/src/utils/operation-user-message.ts b/packages/core/src/utils/operation-user-message.ts new file mode 100644 index 00000000000..2324338e530 --- /dev/null +++ b/packages/core/src/utils/operation-user-message.ts @@ -0,0 +1,38 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { BUILTIN_OPERATION_MESSAGES, renderOperationMessage, resolveBundleLocale } from '@objectstack/spec/system'; + +/** + * [#34699] Whose language a refusal's `userMessage` is in: the operation's + * execution context, or any value carrying its two locale fields. + */ +export interface UserMessageCaller { + /** The request's own locale (`ExecutionContext.locale`). */ + readonly locale?: string; + /** The workspace default (`ExecutionContext.workspaceLocale`), the ladder's second rung. */ + readonly workspaceLocale?: string; +} + +/** + * [#34699] A placeholder-free sentence of the shared operation-message catalog + * (`BUILTIN_OPERATION_MESSAGES`, `@objectstack/spec/system`) in the caller's + * language: the `userMessage` a producer marks beside a developer `message`. + * + * The locale is the first rung of the caller's ladder the built-in catalog + * carries — the request's locale, then the workspace default — the ladder + * plugin-security's refusals use, so a request in a language the catalog has + * no text in falls to the workspace default before `en`. Absent both, `en`. + * + * For producers that hold no `i18n` service: no deployment `errors.` + * override is consulted. A producer that holds one renders through + * `renderOperationMessage` with its `translate` instead. + */ +export function operationUserMessage(messageKey: string, caller?: UserMessageCaller | null): string { + const locale = [caller?.locale, caller?.workspaceLocale].find( + (candidate): candidate is string => + typeof candidate === 'string' && + candidate.length > 0 && + resolveBundleLocale(BUILTIN_OPERATION_MESSAGES, candidate) !== undefined, + ); + return renderOperationMessage({ messageKey }, { locale }); +} diff --git a/packages/core/src/utils/record-not-found.ts b/packages/core/src/utils/record-not-found.ts index 510ef198987..181259c0438 100644 --- a/packages/core/src/utils/record-not-found.ts +++ b/packages/core/src/utils/record-not-found.ts @@ -1,5 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +import { operationUserMessage, type UserMessageCaller } from './operation-user-message.js'; + /** * [#4435] The 404 a single-record operation answers when the id names no row. * @@ -51,14 +53,25 @@ * This is the same move `engineCanRollBack` made for the same reason — a fact * two layers must agree on lives in the layer beneath both, not in a copy each. */ -export function recordNotFoundError(object: string, id: string | number): Error { +export function recordNotFoundError( + object: string, + id: string | number, + caller?: UserMessageCaller | null, +): Error { const err = new Error(`Record ${id} not found in ${object}`) as Error & { code?: string; status?: number; object?: string; + userMessage?: string; }; err.code = 'RECORD_NOT_FOUND'; err.status = 404; err.object = object; + // [#34699] The end user's half, beside the developer sentence above (which + // keeps its id and API name byte for byte). The by-id doors answer an id + // the caller cannot read exactly as an id naming no row (ruling of record + // 5985885287), so `record_not_found` says both and decides neither; it + // names no id and no API name (#7414). + err.userMessage = operationUserMessage('record_not_found', caller); return err; } diff --git a/packages/metadata-protocol/src/protocol-batch-data.ts b/packages/metadata-protocol/src/protocol-batch-data.ts index d5ef4f2469f..b1aff11d2e8 100644 --- a/packages/metadata-protocol/src/protocol-batch-data.ts +++ b/packages/metadata-protocol/src/protocol-batch-data.ts @@ -589,7 +589,7 @@ async function runBatchDataRows( // that answers with the deleted row is not turned into a // spurious 404. const deleted = await this.engine.delete(object, { where: { id: record.id }, ...ctxOpt } as any).catch((e: unknown) => landedDespiteStaleSummary(e, atomic, object)); - if (deleted === false) throw recordNotFoundError(object, record.id); + if (deleted === false) throw recordNotFoundError(object, record.id, context); // [#19433] The SECOND half of this site, and the THIRD and // last of the by-id delete doors to learn it — the // single-record face (commit f9e16d856) and `deleteManyData` (#19412) @@ -1109,7 +1109,7 @@ export async function runDeleteManyLoop( const deleted = await this.engine.delete(object, { where: { id }, ...ctxOpt } as any).catch((e: unknown) => landedDespiteStaleSummary(e, atomic, object)); // `id` is `unknown` to this helper only because the caller's // fail-closed `isScalarId` guard is what proves it scalar. - if (deleted === false) throw recordNotFoundError(object, id as string | number); + if (deleted === false) throw recordNotFoundError(object, id as string | number, context); // [#19412] The SECOND half of the same site. The paragraph above // fixed "no match"; this is "matched, and deliberately NOT // removed" — and until now `success` was still a LITERAL for diff --git a/packages/metadata-protocol/src/protocol-data-crud.ts b/packages/metadata-protocol/src/protocol-data-crud.ts index ce6ddbe08d6..b9351aa7d10 100644 --- a/packages/metadata-protocol/src/protocol-data-crud.ts +++ b/packages/metadata-protocol/src/protocol-data-crud.ts @@ -900,7 +900,7 @@ export class ProtocolDataCrudFacet { ), }; } - throw recordNotFoundError(request.object, request.id); + throw recordNotFoundError(request.object, request.id, request.context); } /** The body of `ObjectStackProtocolImplementation#cloneData`; the method's docblock there is its contract. */ @@ -944,7 +944,7 @@ export class ProtocolDataCrudFacet { request.object, { where: { id: request.id }, ...ctxOpt }, ); - if (!source) throw recordNotFoundError(request.object, request.id); + if (!source) throw recordNotFoundError(request.object, request.id, ctx); // Copy the source, then strip the columns the engine owns so the insert // path re-derives them rather than carrying the source's values over. diff --git a/packages/metadata-protocol/src/protocol-data-writes.ts b/packages/metadata-protocol/src/protocol-data-writes.ts index 7ec5e430979..b70e05e3389 100644 --- a/packages/metadata-protocol/src/protocol-data-writes.ts +++ b/packages/metadata-protocol/src/protocol-data-writes.ts @@ -234,7 +234,7 @@ export async function updateData(host: Pick = { [field]: Object.prototype.hasOwnProperty.call(prior, field) ? prior[field] : null }; const parent = hasParentScopedReadonlyWhenInPayload(schema as never, payload) diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 28044fb359b..1a9d70ce720 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -827,7 +827,7 @@ export class UpdateFacet { // Scope: the BY-ID branch only. A `multi: true` predicate update // that matches zero rows is legitimately "0 rows affected", not a // missing record — same line both siblings draw. - if (!priorRecord) throw recordNotFoundError(object, id); + if (!priorRecord) throw recordNotFoundError(object, id, opCtx.context); // Never fabricate: a row that is not there leaves `previous` // UNBOUND rather than `{}`/`null`, so a condition reading it // faults loudly instead of answering for a record nobody read diff --git a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts index 5219d2f54d5..1519530e337 100644 --- a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts +++ b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts @@ -213,10 +213,18 @@ const PENDING_LOCK_LIMIT = 1_000; */ const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const; -function lockedError(message: string): never { +/** + * `userMessage` [#34699] is passed only by the per-row lock, whose sentence is + * the end user's (`recordLockRefusal`): a client that shows `userMessage` then + * shows it without the `RECORD_LOCKED: ` prefix `message` keeps. The bound and + * unanswerable-intersection refusals name the object's API name for the + * developer who scoped the write, so they mark none. + */ +function lockedError(message: string, userMessage?: string): never { const err: any = new Error(`RECORD_LOCKED: ${message}`); err.code = 'RECORD_LOCKED'; err.statusCode = 409; + if (userMessage !== undefined) err.userMessage = userMessage; throw err; } @@ -704,7 +712,8 @@ export function bindApprovalLockHook( `[approvals] update refused RECORD_LOCKED: record '${recordId}' of '${object}' ` + `is held by pending approval request '${String(pending?.id ?? '')}'`, ); - lockedError(recordLockRefusal(objectLabel, recordTitleOf(schema, asServed, recordId), locale, translate)); + const sentence = recordLockRefusal(objectLabel, recordTitleOf(schema, asServed, recordId), locale, translate); + lockedError(sentence, sentence); } }, { packageId: APPROVALS_HOOK_PACKAGE, priority: 50 }); diff --git a/packages/plugins/plugin-approvals/src/payload-predicate-guard.test.ts b/packages/plugins/plugin-approvals/src/payload-predicate-guard.test.ts index 451d2a4c04b..f54a2288246 100644 --- a/packages/plugins/plugin-approvals/src/payload-predicate-guard.test.ts +++ b/packages/plugins/plugin-approvals/src/payload-predicate-guard.test.ts @@ -28,6 +28,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import type { EngineAggregateOptions, EngineQueryOptions } from '@objectstack/spec/data'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; import { ApprovalsServicePlugin } from './approvals-plugin.js'; import { SysApprovalRequest } from './sys-approval-request.object.js'; import { SysApprovalApprover } from './sys-approval-approver.object.js'; @@ -219,6 +220,19 @@ describe('[#21154] a query over the approval snapshot by a reader withheld a sub }); } + it("[#34699] the predicate refusal carries the user's half in the caller's language; the aggregate words mark none", async () => { + const zhReader = { ...MASKED_READER, locale: 'zh-CN' } as Ctx; + let thrown: any = null; + try { await find(zhReader, contains(V.masked)); } catch (err) { thrown = err; } + expect([thrown?.code, thrown?.status]).toEqual(['PERMISSION_DENIED', 403]); + expect(firstSentence(String(thrown.message))).toBe(predicateWords); + expect(thrown.userMessage).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].query_field_not_readable); + let grouped403: any = null; + try { await grouped(zhReader); } catch (err) { grouped403 = err; } + expect(firstSentence(String(grouped403?.message))).toBe(aggregateWords); + expect(grouped403.userMessage).toBeUndefined(); + }); + it('a filter that pins no subject object is refused for a reader withheld a field of any object a snapshot can concern', async () => { for (const reader of [MASKED_READER, UNSERVED_READER]) { await expectRefused(find(reader, contains(V.masked, null)), predicateWords); diff --git a/packages/plugins/plugin-approvals/src/payload-predicate-guard.ts b/packages/plugins/plugin-approvals/src/payload-predicate-guard.ts index 31155ff2ddf..7eb89d8bfbc 100644 --- a/packages/plugins/plugin-approvals/src/payload-predicate-guard.ts +++ b/packages/plugins/plugin-approvals/src/payload-predicate-guard.ts @@ -65,6 +65,7 @@ * programmatic calls are not judged, as for the redaction. */ +import { operationUserMessage, type UserMessageCaller } from '@objectstack/core'; import { FieldReferenceSchema } from '@objectstack/spec/data'; import { resolveReadableSnapshotFields, type FieldVisibilitySource } from './payload-redaction.js'; import { APPROVAL_REQUEST_OBJECT, type MiddlewareEngine } from './payload-redaction-middleware.js'; @@ -245,6 +246,7 @@ export type SnapshotQueryRefusal = Error & { object: string; fields: string[]; details: { object: string; fields: string[]; reason: string }; + userMessage?: string; }; const REMEDY = @@ -253,7 +255,11 @@ const REMEDY = 'object named by equality on object_name, or every object when it names none.'; /** The refusal, in the engine's words for the role the column is named in. */ -export function snapshotQueryRefusal(operation: string, named: NamedSnapshotColumn): SnapshotQueryRefusal { +export function snapshotQueryRefusal( + operation: string, + named: NamedSnapshotColumn, + caller?: UserMessageCaller | null, +): SnapshotQueryRefusal { const object = APPROVAL_REQUEST_OBJECT; const fields = [SNAPSHOT_COLUMN]; const message = operation === 'aggregate' && named.aggregate @@ -269,6 +275,8 @@ export function snapshotQueryRefusal(operation: string, named: NamedSnapshotColu err.object = object; err.fields = fields; err.details = { object, fields: [...fields], reason: 'field_predicate_denied' }; + // [#34699] The user's half of the predicate refusal, naming no field. + if (!(operation === 'aggregate' && named.aggregate)) err.userMessage = operationUserMessage('query_field_not_readable', caller); return err; } @@ -303,7 +311,7 @@ export function bindSnapshotPredicateGuard( }); refuse = true; } - if (refuse) throw snapshotQueryRefusal(opCtx.operation, named); + if (refuse) throw snapshotQueryRefusal(opCtx.operation, named, opCtx.context); return next(); }, { object: APPROVAL_REQUEST_OBJECT }); } diff --git a/packages/plugins/plugin-approvals/src/record-lock-user-facing-message.test.ts b/packages/plugins/plugin-approvals/src/record-lock-user-facing-message.test.ts index 2a705a30fb3..75f50d4e015 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-user-facing-message.test.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-user-facing-message.test.ts @@ -228,6 +228,8 @@ describe('[#18153] CONTROL — the operator-facing refusals are untouched', () = ); expect(thrown.code).toBe('RECORD_LOCKED'); expect(thrown.statusCode).toBe(409); + // [#34699] An operator-facing sentence (it names the API name) is not marked for the end user. + expect(thrown.userMessage).toBeUndefined(); }); it('the predicate cap refusal still names the object', async () => { @@ -356,6 +358,8 @@ describe('[#34060] the per-row refusal is worded in the writer\'s locale', () => expect(thrown.message).toContain('商机「Acme renewal」'); expect(thrown.message).not.toContain(TAIL_EN); expect(thrown.message).not.toContain(opportunityId); + // [#34699] The same sentence is marked for the end user, without the wire prefix. + expect(thrown.userMessage).toBe(ZH.record_locked.replace('{{object}}', '商机').replace('{{title}}', 'Acme renewal')); }); it('zh-CN, a record with no title: the label-only sentence, still in Chinese', async () => { @@ -387,6 +391,7 @@ describe('[#34060] the per-row refusal is worded in the writer\'s locale', () => await rig(() => i18n); const thrown = await refusalIn(undefined, 'opportunity', opportunityId); expect(thrown.message).toBe(`RECORD_LOCKED: Opportunity 'Acme renewal' ${TAIL_EN}`); + expect(thrown.userMessage).toBe(`Opportunity 'Acme renewal' ${TAIL_EN}`); }); it('no i18n service: the built-in catalog still answers zh-CN, with the declared label', async () => { diff --git a/packages/plugins/plugin-audit/src/activity-predicate-guard.test.ts b/packages/plugins/plugin-audit/src/activity-predicate-guard.test.ts index 361986ec82d..03ce80735e1 100644 --- a/packages/plugins/plugin-audit/src/activity-predicate-guard.test.ts +++ b/packages/plugins/plugin-audit/src/activity-predicate-guard.test.ts @@ -34,6 +34,7 @@ import { ObjectKernel } from '@objectstack/core'; import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; import type { EngineAggregateOptions, EngineQueryOptions } from '@objectstack/spec/data'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; import { AuditPlugin } from './audit-plugin.js'; import { redactActivityRows } from './activity-field-redaction.js'; @@ -251,6 +252,20 @@ describe('[#21154] a query over the activity text by a reader withheld a parent expect((await find(SYS, { object_name: OPEN_PARENT, summary: { $contains: V.open2 } })).length).toBeGreaterThan(0); }); + it("[#34699] the predicate refusal carries the user's half in the caller's language; the aggregate words mark none", async () => { + const c = READER_CASES[0].cases[0]; + const zh = { ...MASKED_READER, locale: 'zh-CN' } as Ctx; + let thrown: any = null; + try { await find(zh, contains(c, c.stored)); } catch (err) { thrown = err; } + expect([thrown?.code, thrown?.status]).toEqual(['PERMISSION_DENIED', 403]); + expect(firstSentence(String(thrown.message))).toBe(predicateWords([c.column])); + expect(thrown.userMessage).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].query_field_not_readable); + let aggregate403: any = null; + try { await grouped(zh, c); } catch (err) { aggregate403 = err; } + expect(firstSentence(String(aggregate403?.message))).toBe(aggregateWords([c.column])); + expect(aggregate403.userMessage).toBeUndefined(); + }); + // ── one block per class ───────────────────────────────────────────────── for (const reader of READER_CASES) { diff --git a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts index 7d9f238e8ad..fa57b631a44 100644 --- a/packages/plugins/plugin-audit/src/parent-field-query-guard.ts +++ b/packages/plugins/plugin-audit/src/parent-field-query-guard.ts @@ -117,6 +117,7 @@ * read gate and the redaction. */ +import { operationUserMessage, type UserMessageCaller } from '@objectstack/core'; import { sideCopyColumnsOf } from './side-copy-columns.js'; import { FieldReferenceSchema } from '@objectstack/spec/data'; import { ACTIVITY_STAMPED_COLUMNS } from './activity-changed-fields.js'; @@ -374,6 +375,7 @@ export type ParentFieldQueryRefusal = Error & { object: string; fields: string[]; details: { object: string; fields: string[]; reason: string }; + userMessage?: string; }; /** @@ -386,6 +388,7 @@ export function parentFieldQueryRefusal( guard: ParentFieldQueryGuard, operation: string, named: NamedValueBearingColumns, + caller?: UserMessageCaller | null, ): ParentFieldQueryRefusal { const aggregateRole = operation === 'aggregate' && named.aggregate.length > 0; const fields = aggregateRole ? named.aggregate : [...new Set([...named.predicate, ...named.aggregate])]; @@ -402,6 +405,8 @@ export function parentFieldQueryRefusal( err.object = guard.object; err.fields = [...fields]; err.details = { object: guard.object, fields: [...fields], reason: 'field_predicate_denied' }; + // [#34699] The user's half of the predicate refusal, naming no field. + if (!aggregateRole) err.userMessage = operationUserMessage('query_field_not_readable', caller); return err; } @@ -440,7 +445,7 @@ function installParentFieldQueryGuard( ); refuse = true; } - if (refuse) throw parentFieldQueryRefusal(guard, ctx.operation, named); + if (refuse) throw parentFieldQueryRefusal(guard, ctx.operation, named, ctx.context); return next(); }, { object: guard.object }, diff --git a/packages/plugins/plugin-security/src/platform-refusal-user-message.test.ts b/packages/plugins/plugin-security/src/platform-refusal-user-message.test.ts new file mode 100644 index 00000000000..80891da27fd --- /dev/null +++ b/packages/plugins/plugin-security/src/platform-refusal-user-message.test.ts @@ -0,0 +1,231 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34699] Three refusals the platform writes carry the end user's half as + * `userMessage`, in the caller's language (the request locale, else the + * workspace default), beside a `code`, status and `message` that do not move: + * + * - the filter-oracle guard (`403 PERMISSION_DENIED`): a query that filters, + * sorts or groups by a field the caller may not read → + * `query_field_not_readable`, naming no field; + * - the by-id write gate's not-found (`404 RECORD_NOT_FOUND`) → + * `record_not_found`, naming no id and no API name; + * - the delegated-administration scope refusal + * (`403 DELEGATION_SCOPE_VIOLATION`) → `delegation_scope_violation`. + * + * Before this, a zh-CN user read each of them in English. The console shows a + * refusal's `userMessage` in place of its `message` (`readEnvelopeFailureText` + * in `ui/packages/app-shell/src/utils/apiErrorEnvelope.ts`), and `mapDataError` + * relays it to the REST body — asserted below on the real classifier. + * + * Measured with the real security layer on a real `ObjectQL` over a real + * `SqlDriver`, through the engine's own reads and writes. The delegated gate's + * own verdicts are pinned in `delegated-admin-gate.test.ts`; here a stub gate + * throws the gate's real error class, because what is under test is the + * middleware that answers it. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysUser } from '@objectstack/platform-objects/identity'; +import { PermissionSetSchema, type PermissionSet } from '@objectstack/spec/security'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +import { mapDataError } from '@objectstack/types'; +import { SecurityPlugin } from './security-plugin.js'; +import { DelegationScopeViolationError } from './errors.js'; +import { wireEngineSecuritySource } from './engine-security-source.testkit.js'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const SYS = { context: { isSystem: true, userId: 'usr_system', tenantId: DEFAULT_ORGANIZATION_ID } } as never; +const READER = 'usr_reader'; + +const CRUD = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; +const SET: PermissionSet = PermissionSetSchema.parse({ + name: 'pru_member', + label: 'Member', + objects: { '*': CRUD }, + fields: { 'pru_deal.margin': { readable: false, editable: false } }, +}); +const SETS = [SET]; + +const callerOf = (locale?: string, workspaceLocale?: string) => ({ + userId: READER, positions: [], permissions: [SET.name], posture: 'MEMBER', tenantId: DEFAULT_ORGANIZATION_ID, + ...(locale ? { locale } : {}), + ...(workspaceLocale ? { workspaceLocale } : {}), +}); + +const text = (name: string) => ({ name, type: 'text' }); +const OBJECTS = [ + SysUser, + { + name: 'pru_deal', label: 'Deal', sharingModel: 'public_read_write', + fields: { name: text('name'), margin: { name: 'margin', type: 'number' } }, + }, + // The object the stub delegated gate refuses every write on. + { name: 'pru_grant', label: 'Grant', sharingModel: 'public_read_write', fields: { name: text('name') } }, +]; + +const ZH = BUILTIN_OPERATION_MESSAGES['zh-CN']; +const EN = BUILTIN_OPERATION_MESSAGES.en; + +let engine: ObjectQL; + +beforeAll(async () => { + engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never, + true, + ); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.platform-refusal-user-message', + name: 'Platform refusals carry a userMessage in the caller language', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: OBJECTS, + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine as never); + + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? SETS.find((s) => s.name === name) : engine.getSchema(name)) ?? null, + list: async () => SETS, + }, + sharing: { canEdit: async () => true }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + hook: () => undefined, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'pru_member' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + // The stub: the real gate for every object but `pru_grant`, whose every + // write it refuses as a delegated administrator's out-of-scope write. + const host = plugin as unknown as { delegatedAdminGate: { assert(opCtx: any): Promise } | null }; + const realGate = host.delegatedAdminGate; + host.delegatedAdminGate = { + assert: async (opCtx: any) => { + if (opCtx.object === 'pru_grant' && !opCtx.context?.isSystem) { + throw new DelegationScopeViolationError( + "[Security] Outside your delegated scope: delegated 'insert' on pru_grant rejected — business unit 'bu_west' is outside the delegated subtree.", + { operation: opCtx.operation, object: opCtx.object }, + ); + } + await realGate?.assert(opCtx); + }, + }; + wireEngineSecuritySource(engine, () => plugin); + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); + + await engine.insert('sys_user', [{ id: READER, name: READER, email: `${READER}@pru.test` }], SYS); + await engine.insert('pru_deal', [{ id: 'deal_1', name: 'deal', margin: 12 }], SYS); +}); + +afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } +}); + +/** The refusal an operation threw; a failure when it was admitted. */ +async function refusal(run: Promise): Promise { + try { + await run; + } catch (e) { + return e; + } + throw new Error('expected the operation to be refused'); +} + +describe('the filter-oracle guard: a query on a field the caller may not read', () => { + const find = (caller: unknown) => + refusal(engine.find('pru_deal', { where: { margin: 12 }, context: { ...(caller as object) } } as never)); + + it('zh-CN: the Chinese sentence, naming no field; code, status and message unchanged', async () => { + const e = await find(callerOf('zh-CN')); + expect(e.code).toBe('PERMISSION_DENIED'); + expect(e.statusCode ?? e.status).toBe(403); + expect(String(e.message)).toMatch(/^\[Security\] Access denied: query on 'pru_deal' references field\(s\) not readable by the caller: margin\./); + expect(e.userMessage).toBe(ZH.query_field_not_readable); + expect(e.userMessage).not.toContain('margin'); + }); + + it('a request locale the catalog does not carry falls to the workspace default, then en', async () => { + expect((await find(callerOf('xx-YY', 'zh-CN'))).userMessage).toBe(ZH.query_field_not_readable); + expect((await find(callerOf())).userMessage).toBe(EN.query_field_not_readable); + }); + + it('the REST classifier relays it to the body', async () => { + const mapped = mapDataError(await find(callerOf('zh-CN'))) as { status: number; body: Record }; + expect(mapped.status).toBe(403); + expect(mapped.body.userMessage).toBe(ZH.query_field_not_readable); + }); + + it('CONTROL: a query on readable fields is admitted', async () => { + const rows = await engine.find('pru_deal', { where: { name: 'deal' }, context: callerOf('zh-CN') } as never); + expect(rows.length).toBe(1); + }); +}); + +describe('the by-id write on an id naming no row', () => { + it('update, zh-CN: 404 RECORD_NOT_FOUND carrying the Chinese sentence, naming no id', async () => { + const e = await refusal( + engine.update('pru_deal', { name: 'x' }, { where: { id: 'deal_missing' }, context: callerOf('zh-CN') } as never), + ); + expect([e.code, e.status]).toEqual(['RECORD_NOT_FOUND', 404]); + expect(e.message).toBe('Record deal_missing not found in pru_deal'); + expect(e.userMessage).toBe(ZH.record_not_found); + expect(e.userMessage).not.toContain('deal_missing'); + }); + + it('delete, workspace default zh-CN: the Chinese sentence', async () => { + const e = await refusal( + engine.delete('pru_deal', { where: { id: 'deal_missing' }, context: callerOf(undefined, 'zh-CN') } as never), + ); + expect([e.code, e.status]).toEqual(['RECORD_NOT_FOUND', 404]); + expect(e.userMessage).toBe(ZH.record_not_found); + }); + + it('the REST classifier relays it to the body', async () => { + const e = await refusal( + engine.update('pru_deal', { name: 'x' }, { where: { id: 'deal_missing' }, context: callerOf('zh-CN') } as never), + ); + const mapped = mapDataError(e) as { status: number; body: Record }; + expect(mapped.status).toBe(404); + expect(mapped.body.userMessage).toBe(ZH.record_not_found); + }); +}); + +describe('the delegated-administration scope refusal', () => { + const insert = (caller: unknown) => + refusal(engine.insert('pru_grant', { name: 'g' }, { context: { ...(caller as object) } } as never)); + + it('zh-CN: the Chinese sentence beside the gate reason, which does not move', async () => { + const e = await insert(callerOf('zh-CN')); + expect([e.code, e.status]).toEqual(['DELEGATION_SCOPE_VIOLATION', 403]); + expect(String(e.message)).toMatch(/^\[Security\] Outside your delegated scope: /); + expect(e.userMessage).toBe(ZH.delegation_scope_violation); + expect(e.userMessage).not.toContain('bu_west'); + }); + + it('no locale: the English sentence', async () => { + expect((await insert(callerOf())).userMessage).toBe(EN.delegation_scope_violation); + }); + + it('the REST classifier relays it to the body with its own code', async () => { + const mapped = mapDataError(await insert(callerOf('zh-CN'))) as { status: number; body: Record }; + expect(mapped.status).toBe(403); + expect(mapped.body.code).toBe('DELEGATION_SCOPE_VIOLATION'); + expect(mapped.body.userMessage).toBe(ZH.delegation_scope_violation); + }); +}); diff --git a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts index 509b1570f1b..551da8920a5 100644 --- a/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts +++ b/packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts @@ -130,7 +130,7 @@ import { type UnresolvedPostureCause, } from './unresolved-posture.js'; import { assertReadableQueryFields } from './predicate-guard.js'; -import { PermissionDeniedError, MaskedValueWriteError } from './errors.js'; +import { DelegationScopeViolationError, PermissionDeniedError, MaskedValueWriteError } from './errors.js'; import { masterGateRefusalUserCopyOf, type MasterQuestion } from './security-plugin-cbp-write-gate.js'; import { QUEUE_FIELD, @@ -277,8 +277,9 @@ function denialLocaleOf( /** * The catalog keys this middleware renders. The first three are the `message` * of the gates #7414 / #7451 localized; the rest are the `userMessage` of the - * owner-anchor, queue, field-write and master-detail write refusals - * ({@link withUserMessage}); the last two are the list rules `field_edit_denied`'s `{{fields}}` is spelled by + * owner-anchor, queue, field-write and master-detail write refusals, the + * unreadable-query-field refusal and the delegated-administration scope + * refusal ({@link withUserMessage}); the last two are the list rules `field_edit_denied`'s `{{fields}}` is spelled by * ({@link labelList}). */ type UserFacingDenialKey = @@ -296,6 +297,8 @@ type UserFacingDenialKey = | 'master_record_edit_denied_opaque' | 'master_record_read_denied' | 'master_record_read_denied_opaque' + | 'query_field_not_readable' + | 'delegation_scope_violation' | 'field_label_quoted' | 'field_label_list_separator'; @@ -513,7 +516,7 @@ async function readDoorAnswerForGateRefusal( throw readRefusal; } if (row == null && isUnreadableAddressedRowRefusal(refusal)) { - return recordNotFoundError(opCtx.object, addressedId as string | number); + return recordNotFoundError(opCtx.object, addressedId as string | number, opCtx.context); } return refusal; } @@ -818,7 +821,17 @@ export function registerAuthzMiddleware( try { await this.delegatedAdminGate.assert(opCtx); } catch (refusal) { - throw await readDoorAnswerForGateRefusal.call(this, opCtx, refusal, nestedInOperation); + const answer = await readDoorAnswerForGateRefusal.call(this, opCtx, refusal, nestedInOperation); + // [#34699] The scope refusal's `message` is the gate's reason, in + // English and in API names; the user's half rides `userMessage`. + if (answer instanceof DelegationScopeViolationError) { + (answer as DelegationScopeViolationError & { userMessage?: string }).userMessage = userFacingDenialMessage( + ctx, + 'delegation_scope_violation', + denialLocalesOf(opCtx.context), + ); + } + throw answer; } } @@ -1464,7 +1477,7 @@ export function registerAuthzMiddleware( addressedId !== undefined && (await this.callerCannotReadAddressedRow(opCtx, addressedId)) ) { - throw recordNotFoundError(opCtx.object, addressedId as string | number); + throw recordNotFoundError(opCtx.object, addressedId as string | number, opCtx.context); } if (!visible) { // [#7451] The refusal an ordinary business user is most likely to @@ -1519,7 +1532,7 @@ export function registerAuthzMiddleware( // step: a caller whose read is refused makes the caller-context // re-read throw for every id, and the record-level 403 is one answer // for all of them.) - throw recordNotFoundError(opCtx.object, addressedId as string | number); + throw recordNotFoundError(opCtx.object, addressedId as string | number, opCtx.context); } } } @@ -2618,7 +2631,16 @@ export function registerAuthzMiddleware( opCtx.operation === 'update' || opCtx.operation === 'delete' ? { where: opCtx.options?.where } : (opCtx.ast as unknown as Record); - assertReadableQueryFields(guardTarget, guardPerms, opCtx.object); + try { + assertReadableQueryFields(guardTarget, guardPerms, opCtx.object); + } catch (e) { + // [#34699] The guard's `message` names the hidden fields' API names + // for a developer; the user's half names none of them. + if (e instanceof PermissionDeniedError) { + throw withUserMessage(e, userFacingDenialMessage(ctx, 'query_field_not_readable', denialLocalesOf(opCtx.context))); + } + throw e; + } } } diff --git a/packages/rest/src/data-action-routes.ts b/packages/rest/src/data-action-routes.ts index 43f96c02133..d4a59740fdf 100644 --- a/packages/rest/src/data-action-routes.ts +++ b/packages/rest/src/data-action-routes.ts @@ -596,7 +596,7 @@ export function registerDataActionEndpoints(this: DataActionRouteHost, basePath: const access = await security.getRecordFieldAccess(object, id, context); // The row went away (or out of the caller's sight) after the // read above: the read path's own no-row answer. - if (access === null) throw recordNotFoundError(object, id); + if (access === null) throw recordNotFoundError(object, id, context); if (access === undefined) { sendEnvelopeError( res, 501, 'NOT_IMPLEMENTED', diff --git a/packages/rest/src/record-page-routes.ts b/packages/rest/src/record-page-routes.ts index dc7c3413b85..7af60815f6f 100644 --- a/packages/rest/src/record-page-routes.ts +++ b/packages/rest/src/record-page-routes.ts @@ -243,7 +243,7 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath: ...scope, } satisfies ServerScopedDataRequest); const record = got?.record ?? got; - if (!record || typeof record !== 'object') throw recordNotFoundError(object, id); + if (!record || typeof record !== 'object') throw recordNotFoundError(object, id, context); const answerRelated = async (entry: NonNullable[number], index: number) => { const head = { object: entry.object, field: entry.field }; @@ -415,7 +415,7 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath: return { error: { code: 'NOT_IMPLEMENTED', status: 501, message: 'The record field projection is not available on this deployment.' } }; } const access = await security.getRecordFieldAccess(object, id, context); - if (access === null) throw recordNotFoundError(object, id); + if (access === null) throw recordNotFoundError(object, id, context); if (access === undefined) { return { error: { code: 'NOT_IMPLEMENTED', status: 501, message: `The record field projection has no answer for '${object}'.` } }; } diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index c4970815025..313e33355eb 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -698,7 +698,7 @@ export async function callData(deps: ActionExecutionDeps, // answered 200 or 404 depending only on whether the deployment // registered the protocol slot — a difference the caller cannot see // and never asked for. - if (!match) throw recordNotFoundError(params.object, params.id); + if (!match) throw recordNotFoundError(params.object, params.id, executionContext); return { object: params.object, id: params.id, record: match }; } throw { statusCode: 503, message: 'Data service not available' }; @@ -747,7 +747,7 @@ export async function callData(deps: ActionExecutionDeps, // all read `.status` → `.statusCode` → 500). A caller mistake was // reported as an internal fault and taken to the error reporter // with it. - if (!existing) throw recordNotFoundError(params.object, params.id); + if (!existing) throw recordNotFoundError(params.object, params.id, executionContext); // [#28782] The create arm's carrier, for an update that landed. let stale: SummaryRecomputeRefusal | undefined; await ql.update(params.object, params.data, findOpts({ where: { id: params.id } })) @@ -823,7 +823,7 @@ export async function callData(deps: ActionExecutionDeps, if (all && (all as any).value) all = (all as any).value; if (!all) all = []; const existing = (all as any[]).find((i: any) => i.id === params.id); - if (!existing) throw recordNotFoundError(params.object, params.id); + if (!existing) throw recordNotFoundError(params.object, params.id, executionContext); // [#28782] The create arm's carrier, for a delete that landed. let stale: SummaryRecomputeRefusal | undefined; await ql.delete(params.object, findOpts({ where: { id: params.id } })) diff --git a/packages/services/service-analytics/src/__tests__/field-read-admission-gate.test.ts b/packages/services/service-analytics/src/__tests__/field-read-admission-gate.test.ts index a6bcd2135a2..17370488388 100644 --- a/packages/services/service-analytics/src/__tests__/field-read-admission-gate.test.ts +++ b/packages/services/service-analytics/src/__tests__/field-read-admission-gate.test.ts @@ -28,6 +28,7 @@ import { describe, it, expect, vi } from 'vitest'; import { DatasetSchema } from '@objectstack/spec/ui'; import { CubeSchema, type Cube } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; import { AnalyticsService } from '../analytics-service.js'; import { AnalyticsServicePlugin } from '../plugin.js'; @@ -199,6 +200,21 @@ describe('[#20917] analytics — the field-level read gate at the door', () => { for (const call of getReadableFields.mock.calls) expect(call[1]).toBe(CALLER); }); + it("[#34699] a predicate refusal carries the user's half in the caller's language; an aggregate refusal marks none", async () => { + const { service } = makeService({ capabilities, getReadableFields: readable }); + const zh = { ...CALLER, locale: 'zh-CN' } as ExecutionContext; + const predicate = await service + .query({ cube: LEDGER, measures: ['count'], where: { hidden_text: 'x1' } } as never, zh) + .then(() => null, (e: unknown) => e as Record); + expect(predicate).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(predicate?.userMessage).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].query_field_not_readable); + const aggregate = await service + .query({ cube: LEDGER, measures: ['count'], dimensions: ['hidden_text'] } as never, zh) + .then(() => null, (e: unknown) => e as Record); + expect(String(aggregate?.message)).toBe(aggregateSentence(LEDGER, ['hidden_text'])); + expect(aggregate?.userMessage).toBeUndefined(); + }); + it('a query naming no field asks the reader nothing', async () => { const getReadableFields = vi.fn(readable); const { service } = makeService({ capabilities, getReadableFields }); diff --git a/packages/services/service-analytics/src/field-read-admission.ts b/packages/services/service-analytics/src/field-read-admission.ts index d5487153555..042585a0432 100644 --- a/packages/services/service-analytics/src/field-read-admission.ts +++ b/packages/services/service-analytics/src/field-read-admission.ts @@ -89,6 +89,7 @@ * security service, where `/data` has no field-level security either. */ +import { operationUserMessage, type UserMessageCaller } from '@objectstack/core'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { StandardErrorCode } from '@objectstack/spec/api'; import { readAdmissionUnresolvedError } from './read-admission.js'; @@ -179,7 +180,7 @@ interface AdmissionLogger { warn(message: string): void; } -type FieldRefusal = Error & { code?: string; status?: number; object?: string; fields?: string[] }; +type FieldRefusal = Error & { code?: string; status?: number; object?: string; fields?: string[]; userMessage?: string }; /** * The refusal, in the ADR-0112 envelope — `PERMISSION_DENIED` / 403 — and in @@ -189,7 +190,12 @@ type FieldRefusal = Error & { code?: string; status?: number; object?: string; f * refused, each the field the member resolved to: the names the engine's * refusal carries for the same query. */ -export function fieldReadDeniedError(object: string, fields: readonly string[], role: FieldReadRole): Error { +export function fieldReadDeniedError( + object: string, + fields: readonly string[], + role: FieldReadRole, + caller?: UserMessageCaller | null, +): Error { const message = role === 'aggregate' ? `[Security] Field read denied: not permitted to aggregate [${fields.join(', ')}] on '${object}'` : `[Security] Access denied: query on '${object}' references field(s) not readable by the caller: ` @@ -200,6 +206,8 @@ export function fieldReadDeniedError(object: string, fields: readonly string[], err.status = 403; err.object = object; err.fields = [...fields]; + // [#34699] The user's half of the predicate refusal, naming no field. + if (role !== 'aggregate') err.userMessage = operationUserMessage('query_field_not_readable', caller); return err; } @@ -312,7 +320,7 @@ export async function assertNamedFieldsReadable( `(user ${String((context as { userId?: unknown } | undefined)?.userId ?? 'unknown')}) — ` + `the verdict the engine reaches for the same fields`, ); - throw fieldReadDeniedError(object, refused, role); + throw fieldReadDeniedError(object, refused, role, context); } } } diff --git a/packages/services/service-print/src/print-service.ts b/packages/services/service-print/src/print-service.ts index 61966c7d5b3..5a0d33a9616 100644 --- a/packages/services/service-print/src/print-service.ts +++ b/packages/services/service-print/src/print-service.ts @@ -411,10 +411,10 @@ export class PrintService implements IPrintService { } catch (err) { // A read the caller is refused answers exactly as a record that does not // exist: never a 403 that tells the two apart. - if ((err as { status?: unknown })?.status === 403) throw recordNotFoundError(req.object, req.recordId); + if ((err as { status?: unknown })?.status === 403) throw recordNotFoundError(req.object, req.recordId, context); throw err; } - if (!row) throw recordNotFoundError(req.object, req.recordId); + if (!row) throw recordNotFoundError(req.object, req.recordId, context); } private refuseUnlessFilesEnabled(engine: PrintEngine, object: string): void { diff --git a/packages/spec/src/system/operation-message.test.ts b/packages/spec/src/system/operation-message.test.ts index 5c04b2d7356..ad9afd22a70 100644 --- a/packages/spec/src/system/operation-message.test.ts +++ b/packages/spec/src/system/operation-message.test.ts @@ -676,3 +676,51 @@ describe('operation message catalog — the record-lock refusal', () => { .toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].record_locked.replace('{{object}}', '商机').replace('{{title}}', () => title)); }); }); + +/** + * #34699 — the user's half of three platform refusals whose `message` stays the + * developer sentence: the by-id not-found, the filter-oracle guard and the + * delegated-administration scope refusal. + */ +describe('operation message catalog — not found, unreadable query field, delegated scope', () => { + const KEYS = ['record_not_found', 'query_field_not_readable', 'delegation_scope_violation'] as const; + + it('every locale defines all three, placeholder-free', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of KEYS) { + expect(catalog[key], `${locale} defines ${key}`).toBeTypeOf('string'); + expect(catalog[key].match(/\{\{\w+\}\}/g) ?? [], `${locale}.${key}`).toEqual([]); + } + } + }); + + it('names no wire code, API vocabulary or authorization mechanism — in every locale', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of KEYS) { + expect(catalog[key], `${locale}.${key}`).not.toMatch(/RECORD_NOT_FOUND|PERMISSION_DENIED|DELEGATION_SCOPE|adminScope|\[Security\]|_id\b|filter oracle/); + } + } + }); + + it('renders the caller locale, and falls back to en for a locale the catalog does not carry', () => { + expect(renderOperationMessage({ messageKey: 'record_not_found' }, { locale: 'zh-CN' })).toBe('该记录不存在,或您无权访问它。'); + expect(renderOperationMessage({ messageKey: 'query_field_not_readable' }, { locale: 'zh' })) + .toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].query_field_not_readable); + expect(renderOperationMessage({ messageKey: 'delegation_scope_violation' }, { locale: 'de-DE' })) + .toBe(BUILTIN_OPERATION_MESSAGES.en.delegation_scope_violation); + }); + + it('each says something different from every other key, in every locale', () => { + for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) { + for (const key of KEYS) { + const others = Object.entries(catalog).filter(([k]) => k !== key).map(([, v]) => v); + expect(others, `${locale}.${key}`).not.toContain(catalog[key]); + } + } + }); + + it('a deployment translation override wins, under the shared `errors.` address', () => { + const translate = (k: string) => (k === operationMessageTranslationKey('record_not_found') ? '记录不见了' : k); + expect(renderOperationMessage({ messageKey: 'record_not_found' }, { locale: 'zh-CN', translate })).toBe('记录不见了'); + }); +}); diff --git a/packages/spec/src/system/operation-message.ts b/packages/spec/src/system/operation-message.ts index ea6236466af..cec269ef2aa 100644 --- a/packages/spec/src/system/operation-message.ts +++ b/packages/spec/src/system/operation-message.ts @@ -289,6 +289,25 @@ export function operationMessageTranslationKey(messageKey: string): string { * * Their English is byte-identical to the fixed sentence the hook answered * before it was localized. + * + * Three keys are the `userMessage` of refusals whose `message` stays the + * developer sentence (code, status and `message` unchanged). None takes a + * placeholder, re-derived per site: + * + * - `record_not_found` — `404 RECORD_NOT_FOUND` from `recordNotFoundError` + * (`@objectstack/core`). The by-id doors answer an id the caller cannot + * read exactly as an id naming no row (ruling of record 5985885287), so + * the sentence says both and tells the user neither. The only nameable + * facts at the throw site are the object's API name and the row's id, + * the #7414 vocabulary that must not reach a toast. + * - `query_field_not_readable` — plugin-security's `403 PERMISSION_DENIED` + * for a query that filters, sorts, groups or aggregates by a field the + * caller may not read (the filter-oracle guard). The fields are the ones + * the caller may not see, so the sentence names none of them. + * - `delegation_scope_violation` — `403 DELEGATION_SCOPE_VIOLATION`, a + * delegated administrator's write outside their own `adminScope`. The + * reason in `message` names business units and permission sets by their + * API names and ids; the user's half names none of them. */ export const BUILTIN_OPERATION_MESSAGES: Record> = { en: { @@ -345,6 +364,11 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'This {{object}} is locked while an approval is in progress, and cannot be edited until that approval is complete', record_locked_opaque: 'This record is locked while an approval is in progress, and cannot be edited until that approval is complete', + record_not_found: 'This record does not exist, or you do not have access to it.', + query_field_not_readable: + 'This request filters, sorts or groups by a field you do not have access to. Remove that condition and try again, or contact your administrator if you need access.', + delegation_scope_violation: + 'This change is outside the scope you were delegated to administer. Contact your administrator if it needs to be made.', }, 'zh-CN': { permission_denied: '您没有执行此操作的权限,如需访问请联系管理员。', @@ -380,6 +404,9 @@ export const BUILTIN_OPERATION_MESSAGES: Record> record_locked_unlabeled: '「{{title}}」正在审批中,已被锁定,审批完成前无法编辑', record_locked_untitled: '该{{object}}正在审批中,已被锁定,审批完成前无法编辑', record_locked_opaque: '该记录正在审批中,已被锁定,审批完成前无法编辑', + record_not_found: '该记录不存在,或您无权访问它。', + query_field_not_readable: '当前请求按您无权查看的字段筛选、排序或分组,请去掉该条件后重试,或联系管理员。', + delegation_scope_violation: '此更改超出了您被委派管理的范围,如需更改请联系管理员。', }, 'ja-JP': { permission_denied: 'この操作を実行する権限がありません。アクセスが必要な場合は管理者にお問い合わせください。', @@ -430,6 +457,11 @@ export const BUILTIN_OPERATION_MESSAGES: Record> record_locked_unlabeled: '「{{title}}」は承認処理中のためロックされています。承認が完了するまで編集できません', record_locked_untitled: 'この{{object}}は承認処理中のためロックされています。承認が完了するまで編集できません', record_locked_opaque: 'このレコードは承認処理中のためロックされています。承認が完了するまで編集できません', + record_not_found: 'このレコードは存在しないか、アクセスする権限がありません。', + query_field_not_readable: + 'この要求は、閲覧権限のない項目で絞り込み、並べ替え、またはグループ化しています。その条件を削除して再試行するか、アクセスが必要な場合は管理者にお問い合わせください。', + delegation_scope_violation: + 'この変更は、管理を委任された範囲を超えています。変更が必要な場合は管理者にお問い合わせください。', }, 'es-ES': { permission_denied: @@ -485,6 +517,11 @@ export const BUILTIN_OPERATION_MESSAGES: Record> 'Este registro de {{object}} está bloqueado mientras hay una aprobación en curso y no se puede editar hasta que esa aprobación finalice', record_locked_opaque: 'Este registro está bloqueado mientras hay una aprobación en curso y no se puede editar hasta que esa aprobación finalice', + record_not_found: 'Este registro no existe o no tiene acceso a él.', + query_field_not_readable: + 'Esta solicitud filtra, ordena o agrupa por un campo al que no tiene acceso. Quite esa condición e inténtelo de nuevo, o póngase en contacto con su administrador si necesita acceso.', + delegation_scope_violation: + 'Este cambio está fuera del ámbito que se le ha delegado para administrar. Póngase en contacto con su administrador si es necesario realizarlo.', }, }; From 21b00160862021d9aa713efa5191b3ac09df2110 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:20:04 +0000 Subject: [PATCH 02/10] test: pin the not-found userMessage where batch rows and routes quote it Tests that pin the exact shape of a not-found row now expect the end user's sentence beside code, message and status. The REST field-access route test builds the read path's not-found with the real producer, and the runtime CONTROL for an unmarked row moves to a write naming an undeclared field, since a missing id is now marked. Claude-Session: https://claude.ai/code/session_01ADHkmPhCxzY1uTqhToLhkv Co-authored-by: Claude --- .../src/protocol.batch-row-driver-text.test.ts | 1 + .../src/protocol.batch-row-http-status.test.ts | 1 + .../record-lock-batch-row-status.integration.test.ts | 10 +++++++--- packages/rest/src/record-field-access-route.test.ts | 7 ++++--- ...tch-row-http-status-real-driver.integration.test.ts | 1 + .../duplicate-record-user-message-doors-33790.test.ts | 5 ++++- 6 files changed, 18 insertions(+), 7 deletions(-) diff --git a/packages/metadata-protocol/src/protocol.batch-row-driver-text.test.ts b/packages/metadata-protocol/src/protocol.batch-row-driver-text.test.ts index 9a16abb0bc2..7ebad688908 100644 --- a/packages/metadata-protocol/src/protocol.batch-row-driver-text.test.ts +++ b/packages/metadata-protocol/src/protocol.batch-row-driver-text.test.ts @@ -290,6 +290,7 @@ describe('[#8502] section 2 — the authored population survives, in all THREE d const res: any = await protocol.deleteManyData({ object: 'leave_request', ids: ['ghost'] }); expect(res.results[0].errors[0]).toEqual({ code: 'RECORD_NOT_FOUND', message: 'Record ghost not found in leave_request', httpStatus: 404, + userMessage: 'This record does not exist, or you do not have access to it.', }); }); diff --git a/packages/metadata-protocol/src/protocol.batch-row-http-status.test.ts b/packages/metadata-protocol/src/protocol.batch-row-http-status.test.ts index 8184d9290ae..94916b195ff 100644 --- a/packages/metadata-protocol/src/protocol.batch-row-http-status.test.ts +++ b/packages/metadata-protocol/src/protocol.batch-row-http-status.test.ts @@ -291,6 +291,7 @@ describe('[#8570] section 2 — the rows that already carried a status are untou const del: any = await protocol.deleteManyData({ object: 'leave_request', ids: ['ghost'] }); expect(del.results[0].errors[0]).toEqual({ code: 'RECORD_NOT_FOUND', message: 'Record ghost not found in leave_request', httpStatus: 404, + userMessage: 'This record does not exist, or you do not have access to it.', }); }); }); diff --git a/packages/plugins/plugin-approvals/src/record-lock-batch-row-status.integration.test.ts b/packages/plugins/plugin-approvals/src/record-lock-batch-row-status.integration.test.ts index 3b82b1d7a78..7f6ad716cf3 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-batch-row-status.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-batch-row-status.integration.test.ts @@ -140,6 +140,8 @@ describe('[#8570] a locked record\'s batch row carries the 409 the hook declared // side of it is what this file exists for and is unmoved. message: "RECORD_LOCKED: Opportunity 'Deal' is locked while an approval is in progress, and cannot be edited until that approval is complete", httpStatus: 409, + // [#34699] The same sentence, marked for the end user, without the wire prefix. + userMessage: "Opportunity 'Deal' is locked while an approval is in progress, and cannot be edited until that approval is complete", }); // The same row, read as the CARD reads it: no internal identifier in the // user-visible body (#18153). The object is named by its LABEL @@ -169,7 +171,8 @@ describe('[#8570] a locked record\'s batch row carries the 409 the hook declared expect(thrown.code).toBe('RECORD_LOCKED'); expect(thrown.statusCode).toBe(409); expect(thrown.status).toBeUndefined(); - expect(Object.getOwnPropertyNames(thrown)).toEqual(['stack', 'message', 'code', 'statusCode']); + // [#34699] `userMessage` is the end user's sentence; it declares no status. + expect(Object.getOwnPropertyNames(thrown)).toEqual(['stack', 'message', 'code', 'statusCode', 'userMessage']); // The production recogniser, on the real throw — and the field the row's // limb reads, which is what separates a declared refusal from a fault. expect(resolveThrownHttpError(thrown).declaredStatus).toBe(409); @@ -209,18 +212,19 @@ describe('[#8570] a locked record\'s batch row carries the 409 the hook declared }; const zh = BUILTIN_OPERATION_MESSAGES['zh-CN'].record_locked .replace('{{object}}', 'Opportunity').replace('{{title}}', 'Deal'); - expect(await rowIn('zh-CN')).toEqual({ code: 'RECORD_LOCKED', message: `RECORD_LOCKED: ${zh}`, httpStatus: 409 }); + expect(await rowIn('zh-CN')).toEqual({ code: 'RECORD_LOCKED', message: `RECORD_LOCKED: ${zh}`, httpStatus: 409, userMessage: zh }); expect(await rowIn('en-US')).toEqual({ code: 'RECORD_LOCKED', message: "RECORD_LOCKED: Opportunity 'Deal' is locked while an approval is in progress, and cannot be edited until that approval is complete", httpStatus: 409, + userMessage: "Opportunity 'Deal' is locked while an approval is in progress, and cannot be edited until that approval is complete", }); const upsert: any = await protocol.batchData({ object: 'opportunity', request: { operation: 'upsert', records: [{ id: lockedId, data: { amount: 999 } }] }, context: { userId: 'u_writer', positions: [], permissions: [], locale: 'zh-CN' }, }); - expect(upsert.results[0].errors[0]).toEqual({ code: 'RECORD_LOCKED', message: `RECORD_LOCKED: ${zh}`, httpStatus: 409 }); + expect(upsert.results[0].errors[0]).toEqual({ code: 'RECORD_LOCKED', message: `RECORD_LOCKED: ${zh}`, httpStatus: 409, userMessage: zh }); expect((await engine.findOne('opportunity', { where: { id: lockedId } }))?.amount).toBe(100); }); diff --git a/packages/rest/src/record-field-access-route.test.ts b/packages/rest/src/record-field-access-route.test.ts index cef83eaaa2d..d5bac7fe9a7 100644 --- a/packages/rest/src/record-field-access-route.test.ts +++ b/packages/rest/src/record-field-access-route.test.ts @@ -25,6 +25,7 @@ import { describe, it, expect, vi } from 'vitest'; import { RestServer } from './rest-server.js'; import { RECORD_FIELD_ACCESS_PARAMS } from './data-action-routes.js'; import { unknownQueryParamMessage } from './query-allowlist.js'; +import { recordNotFoundError } from '@objectstack/core'; const TASK = { name: 'task', @@ -85,9 +86,9 @@ function boot(opts: { getData?: () => Promise; security?: unknown } = { return { getData, call }; } -const recordNotFound = () => Object.assign(new Error('Record r1 not found in task'), { - code: 'RECORD_NOT_FOUND', status: 404, object: 'task', -}); +// The read path's own not-found, as the GET record read throws it (it carries +// the end user's sentence as `userMessage`, in the caller's language). +const recordNotFound = () => recordNotFoundError('task', 'r1', CTX); describe('[#26594] GET /data/:object/:id/field-access', () => { it("relays the service's projection of this record, asked with the caller's object, record and context", async () => { diff --git a/packages/runtime/src/batch-row-http-status-real-driver.integration.test.ts b/packages/runtime/src/batch-row-http-status-real-driver.integration.test.ts index d1ab41f0da5..945c0d2e560 100644 --- a/packages/runtime/src/batch-row-http-status-real-driver.integration.test.ts +++ b/packages/runtime/src/batch-row-http-status-real-driver.integration.test.ts @@ -261,6 +261,7 @@ describe('[#8570] a batch row carries the status its producer DECLARED — real const res: any = await protocol.deleteManyData({ object: 'hs_task', ids: ['ghost'] }); expect(res.results[0].errors[0]).toEqual({ code: 'RECORD_NOT_FOUND', message: 'Record ghost not found in hs_task', httpStatus: 404, + userMessage: 'This record does not exist, or you do not have access to it.', }); }); }); diff --git a/packages/runtime/src/duplicate-record-user-message-doors-33790.test.ts b/packages/runtime/src/duplicate-record-user-message-doors-33790.test.ts index d5d34c6a65b..b0bdcf3f080 100644 --- a/packages/runtime/src/duplicate-record-user-message-doors-33790.test.ts +++ b/packages/runtime/src/duplicate-record-user-message-doors-33790.test.ts @@ -273,8 +273,11 @@ describe.each([ describe('CONTROL', () => { it('a row error whose producer marked nothing carries no `userMessage`', async () => { + // A write naming a field the object does not declare: its producer marks + // nothing. (An id naming no row is no longer this population: the + // not-found refusal marks the end user's sentence since #34699.) const { body } = await call('zh-CN', 'POST', `/data/${OBJECT}/updateMany`, { - records: [{ id: 'no_such_record', data: { plant: 'P9' } }], + records: [{ id: r2, data: { no_such_field: 'x' } }], }); const row = body.results?.[0]; From f3d1774be27d28533096345e8ed6cd87f781518e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:03:31 +0000 Subject: [PATCH 03/10] test: pay the dynamic loads of edited protocol and route tests at collection The three test files edited for the not-found userMessage reach a source that imports a dependency inside a function body; each now loads it at module top, as check:test-source-alias asks of a file a change edits. Claude-Session: https://claude.ai/code/session_01ADHkmPhCxzY1uTqhToLhkv Co-authored-by: Claude --- .../src/protocol.batch-row-driver-text.test.ts | 3 +++ .../src/protocol.batch-row-http-status.test.ts | 3 +++ packages/rest/src/record-field-access-route.test.ts | 3 +++ 3 files changed, 9 insertions(+) diff --git a/packages/metadata-protocol/src/protocol.batch-row-driver-text.test.ts b/packages/metadata-protocol/src/protocol.batch-row-driver-text.test.ts index 7ebad688908..1cb4f7b00f2 100644 --- a/packages/metadata-protocol/src/protocol.batch-row-driver-text.test.ts +++ b/packages/metadata-protocol/src/protocol.batch-row-driver-text.test.ts @@ -69,6 +69,9 @@ import { describe, it, expect, vi } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { resolveThrownHttpError, validationFailureDetails } from '@objectstack/types'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Paid at collection, not inside a case's clock (check:test-source-alias): +// the source under test loads it dynamically. +import '@objectstack/lint'; const SCHEMA = { name: 'leave_request', diff --git a/packages/metadata-protocol/src/protocol.batch-row-http-status.test.ts b/packages/metadata-protocol/src/protocol.batch-row-http-status.test.ts index 94916b195ff..1cdc022972c 100644 --- a/packages/metadata-protocol/src/protocol.batch-row-http-status.test.ts +++ b/packages/metadata-protocol/src/protocol.batch-row-http-status.test.ts @@ -61,6 +61,9 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { resolveThrownHttpError } from '@objectstack/types'; import { ErrorCode } from '@objectstack/spec/api'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Paid at collection, not inside a case's clock (check:test-source-alias): +// the source under test loads it dynamically. +import '@objectstack/lint'; const SCHEMA = { name: 'leave_request', diff --git a/packages/rest/src/record-field-access-route.test.ts b/packages/rest/src/record-field-access-route.test.ts index d5bac7fe9a7..f20144626e4 100644 --- a/packages/rest/src/record-field-access-route.test.ts +++ b/packages/rest/src/record-field-access-route.test.ts @@ -26,6 +26,9 @@ import { RestServer } from './rest-server.js'; import { RECORD_FIELD_ACCESS_PARAMS } from './data-action-routes.js'; import { unknownQueryParamMessage } from './query-allowlist.js'; import { recordNotFoundError } from '@objectstack/core'; +// Paid at collection, not inside a case's clock (check:test-source-alias): +// the source under test loads it dynamically. +import '@objectstack/objectql'; const TASK = { name: 'task', From f8ef82d7bbd0d610d519b39e2776c386bb67a5bd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:08:04 +0000 Subject: [PATCH 04/10] docs: the not-found body examples carry the end user's sentence The flat RECORD_NOT_FOUND body now includes userMessage in the caller's language; the two pages that print that body show it. Claude-Session: https://claude.ai/code/session_01ADHkmPhCxzY1uTqhToLhkv Co-authored-by: Claude --- content/docs/protocol/kernel/error-handling.mdx | 6 ++++-- content/docs/protocol/kernel/http-protocol.mdx | 8 ++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/content/docs/protocol/kernel/error-handling.mdx b/content/docs/protocol/kernel/error-handling.mdx index 5ca8341cc77..a6eace4e9f0 100644 --- a/content/docs/protocol/kernel/error-handling.mdx +++ b/content/docs/protocol/kernel/error-handling.mdx @@ -684,14 +684,16 @@ resource is named in `message`. **The `/data` door answers a different code.** A record missing from a CRUD route is -`RECORD_NOT_FOUND` in the flat envelope, with the object as a top-level sibling — see +`RECORD_NOT_FOUND` in the flat envelope, with the object as a top-level sibling and the +end user's sentence on `userMessage`, in the caller's language — see [HTTP API](/docs/protocol/kernel/http-protocol): ```json { "error": "Record acc_999 not found in account", "code": "RECORD_NOT_FOUND", - "object": "account" + "object": "account", + "userMessage": "This record does not exist, or you do not have access to it." } ``` diff --git a/content/docs/protocol/kernel/http-protocol.mdx b/content/docs/protocol/kernel/http-protocol.mdx index 92ad999521a..7a248865abb 100644 --- a/content/docs/protocol/kernel/http-protocol.mdx +++ b/content/docs/protocol/kernel/http-protocol.mdx @@ -583,12 +583,16 @@ A single-record read returns a `GetDataResponse`: the `object` name, the record **Not Found (HTTP 404):** REST error responses use a flat envelope: a top-level `error` message string and -a string `code`, plus optional context fields (`object`, per-field `fields`): +a string `code`, plus optional context fields (`object`, per-field `fields`). +`userMessage` is the sentence for the end user, in the caller's language (the +request locale, else the workspace default, else English); it reads the same +whether the row is missing or hidden from the caller: ```json { "error": "Record acc_999 not found in account", "code": "RECORD_NOT_FOUND", - "object": "account" + "object": "account", + "userMessage": "This record does not exist, or you do not have access to it." } ``` From 1fce1406e2c1f8b2d1374553785b85b003e94bc3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 11:36:07 +0000 Subject: [PATCH 05/10] fix(core): take any context object as the userMessage caller An interface of two optional fields is a weak type: TypeScript refuses a context that declares neither (hook and middleware contexts, test callers) for it. The caller is now typed `object` and its two locale fields are read defensively, which the ladder already did. Claude-Session: https://claude.ai/code/session_01ADHkmPhCxzY1uTqhToLhkv Co-authored-by: Claude --- .../core/src/utils/operation-user-message.ts | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/packages/core/src/utils/operation-user-message.ts b/packages/core/src/utils/operation-user-message.ts index 2324338e530..3fee01f1f74 100644 --- a/packages/core/src/utils/operation-user-message.ts +++ b/packages/core/src/utils/operation-user-message.ts @@ -4,13 +4,21 @@ import { BUILTIN_OPERATION_MESSAGES, renderOperationMessage, resolveBundleLocale /** * [#34699] Whose language a refusal's `userMessage` is in: the operation's - * execution context, or any value carrying its two locale fields. + * execution context, or any object carrying its two locale fields — + * `locale` (the request's own, `ExecutionContext.locale`) and + * `workspaceLocale` (the workspace default, the ladder's second rung). + * + * Typed `object`, not an interface of two optional fields: the contexts that + * reach producers (engine, hook and middleware contexts, test callers) mostly + * declare neither field, and TypeScript refuses such a value for an all-optional + * type it shares no property with. The fields are read defensively instead: a + * rung that is not a non-empty string the catalog carries is skipped. */ -export interface UserMessageCaller { - /** The request's own locale (`ExecutionContext.locale`). */ - readonly locale?: string; - /** The workspace default (`ExecutionContext.workspaceLocale`), the ladder's second rung. */ - readonly workspaceLocale?: string; +export type UserMessageCaller = object; + +interface CallerLocales { + readonly locale?: unknown; + readonly workspaceLocale?: unknown; } /** @@ -28,7 +36,8 @@ export interface UserMessageCaller { * `renderOperationMessage` with its `translate` instead. */ export function operationUserMessage(messageKey: string, caller?: UserMessageCaller | null): string { - const locale = [caller?.locale, caller?.workspaceLocale].find( + const rungs = caller as CallerLocales | null | undefined; + const locale = [rungs?.locale, rungs?.workspaceLocale].find( (candidate): candidate is string => typeof candidate === 'string' && candidate.length > 0 && From d50700b3468c39cc4a5dd8871f050c1e673e97bb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 12:23:14 +0000 Subject: [PATCH 06/10] test(mcp): the not-found envelope carries the English end-user sentence The MCP data doors relay a declared userMessage; with no caller locale in reach the not-found refusal's is the English one. The metadata door carries no userMessage channel, so its sites keep the three-field answer. Claude-Session: https://claude.ai/code/session_01ADHkmPhCxzY1uTqhToLhkv Co-authored-by: Claude --- packages/mcp/src/mcp-coded-refusal.test.ts | 7 ++++++- packages/mcp/src/stdio-data-bridge.not-found.test.ts | 9 ++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/mcp/src/mcp-coded-refusal.test.ts b/packages/mcp/src/mcp-coded-refusal.test.ts index 8bdf964def3..e091b7a493a 100644 --- a/packages/mcp/src/mcp-coded-refusal.test.ts +++ b/packages/mcp/src/mcp-coded-refusal.test.ts @@ -197,7 +197,12 @@ describe('MCP tools over HTTP /mcp: a coded refusal carries its code (#23509)', expect(result.isError).toBe(true); expect(result.content).toHaveLength(1); expect(JSON.parse(result.content[0].text)).toEqual({ - error: { code: 'RECORD_NOT_FOUND', message: 'Record t9 not found in task', status: 404 }, + error: { + code: 'RECORD_NOT_FOUND', message: 'Record t9 not found in task', status: 404, + // The end user's sentence the producer marks (#34699): no caller here, so + // English. The metadata door's answer carries no `userMessage` channel. + ...(site.metaDoor ? {} : { userMessage: 'This record does not exist, or you do not have access to it.' }), + }, }); }); diff --git a/packages/mcp/src/stdio-data-bridge.not-found.test.ts b/packages/mcp/src/stdio-data-bridge.not-found.test.ts index ac250ab7896..203524a58a8 100644 --- a/packages/mcp/src/stdio-data-bridge.not-found.test.ts +++ b/packages/mcp/src/stdio-data-bridge.not-found.test.ts @@ -209,7 +209,14 @@ async function getRecordOverHttp(objectName: string, recordId: string) { /** The coded envelope `get_record` answers a miss with, as both doors put it on the wire. */ function notFoundWire(object: string, id: string) { - return { error: { code: 'RECORD_NOT_FOUND', message: `Record ${id} not found in ${object}`, status: 404 } }; + // `userMessage`: the end user's sentence the producer marks (#34699). The stdio + // bridge passes no caller locale, so it is the English one. + return { + error: { + code: 'RECORD_NOT_FOUND', message: `Record ${id} not found in ${object}`, status: 404, + userMessage: 'This record does not exist, or you do not have access to it.', + }, + }; } describe('stdio get_record answers a missing or hidden id with the coded RECORD_NOT_FOUND / 404', () => { From 843d86af946fd286f9ba3120897bc2e97a99e5fe Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:09:45 +0000 Subject: [PATCH 07/10] fix(runtime, metadata-protocol): the action, flow-start and bulk not-found refusals answer in the caller's language refuseDeniedSubjectLoad, refuseDeniedSubjectLoadBeforeDispatch and the bulk faces' assertRecordExists take the caller's execution context, and every caller that holds one passes it, so their RECORD_NOT_FOUND userMessage follows the request locale, then workspaceLocale, then en, as the data door's own miss does. code, status and message do not move. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- .../src/protocol-batch-data.ts | 4 +- .../src/protocol-record-reads.ts | 7 ++- .../protocol.bulk-record-not-found.test.ts | 58 +++++++++++++++++++ packages/metadata-protocol/src/protocol.ts | 7 ++- packages/runtime/src/action-dispatch.ts | 2 +- packages/runtime/src/action-execution.ts | 23 ++++++-- .../src/flow-start-record-admission.test.ts | 46 +++++++++++++++ 7 files changed, 132 insertions(+), 15 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-batch-data.ts b/packages/metadata-protocol/src/protocol-batch-data.ts index b1aff11d2e8..58d2df65bac 100644 --- a/packages/metadata-protocol/src/protocol-batch-data.ts +++ b/packages/metadata-protocol/src/protocol-batch-data.ts @@ -465,7 +465,7 @@ async function runBatchDataRows( // not-found gate ahead of every hook), so a refused row // reads the same whether or not its id names a record — // see `assertRecordExists`. - if (updated == null) await this.assertRecordExists(object, record.id); + if (updated == null) await this.assertRecordExists(object, record.id, context); omitInternalFieldsFromWriteResponse(batchSchema, updated); // [#7823] results.push({ id: record.id, success: true, data: updated, index, ...(dropped.length > 0 ? { droppedFields: dropped } : {}) }); succeeded++; @@ -959,7 +959,7 @@ export async function runUpdateManyLoop( // refusals, then its not-found gate ahead of every hook), so a // refused row reads the same whether or not its id names a // record — see `assertRecordExists`. - if (updated == null) await this.assertRecordExists(object, record.id); + if (updated == null) await this.assertRecordExists(object, record.id, context); omitInternalFieldsFromWriteResponse(updateManySchema, updated); // [#7823] results.push({ id: record.id, success: true, data: updated, index, ...(dropped.length > 0 ? { droppedFields: dropped } : {}) }); succeeded++; diff --git a/packages/metadata-protocol/src/protocol-record-reads.ts b/packages/metadata-protocol/src/protocol-record-reads.ts index 78150561999..a6a6eb636f6 100644 --- a/packages/metadata-protocol/src/protocol-record-reads.ts +++ b/packages/metadata-protocol/src/protocol-record-reads.ts @@ -52,7 +52,7 @@ import type { ObjectStackProtocolImplementation } from './protocol.js'; import { ConcurrentUpdateError, MalformedVersionTokenError, canonicalVersionInstant } from './protocol.js'; -import { recordNotFoundError } from '@objectstack/core'; +import { recordNotFoundError, type UserMessageCaller } from '@objectstack/core'; import { collectInternalWriteResponseFields, omitInternalFieldsFromWriteResponse } from './write-response-internal-fields.js'; import { isMissingTableError } from '@objectstack/metadata/errors'; import { canServeApiOperation, resolveSearchFieldResolution } from '@objectstack/spec/data'; @@ -199,9 +199,10 @@ export function omitInternalWriteFields( /** The body of `ObjectStackProtocolImplementation#assertRecordExists`; the method's docblock there is its contract. */ export async function assertRecordExists( this: Pick, - object: string, id: string): Promise { + object: string, id: string, caller?: UserMessageCaller | null): Promise { const current = await this.probeRecord(object, id); - if (!current) throw recordNotFoundError(object, id); + // [#34699] `caller` decides only the language of the refusal's `userMessage`. + if (!current) throw recordNotFoundError(object, id, caller); } /** The body of `ObjectStackProtocolImplementation#assertVersionOf`; the method's docblock there is its contract. */ diff --git a/packages/metadata-protocol/src/protocol.bulk-record-not-found.test.ts b/packages/metadata-protocol/src/protocol.bulk-record-not-found.test.ts index 7fe242d7cee..70b6f6d5c7c 100644 --- a/packages/metadata-protocol/src/protocol.bulk-record-not-found.test.ts +++ b/packages/metadata-protocol/src/protocol.bulk-record-not-found.test.ts @@ -41,6 +41,7 @@ import { describe, it, expect, vi } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { recordNotFoundError } from '@objectstack/core'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; import { ObjectStackProtocolImplementation } from './protocol.js'; const SCHEMA = { @@ -739,3 +740,60 @@ describe('an update by id answers the same refusal whether or not the id exists, expectRecordNotFoundRow(many.results[0], 'definitely_missing'); }); }); + +/** + * [#34699] The bulk faces' own existence check (`assertRecordExists`, asked + * only when the engine's update resolved a `null` readback instead of + * refusing the row itself) answers in the row's caller's language: the row's + * write context is handed to the refusal, so its `userMessage` follows the + * request `locale`, then `workspaceLocale`, then `en`. + */ +describe('[#34699] the bulk faces\' existence check answers in the caller\'s language', () => { + const ZH = BUILTIN_OPERATION_MESSAGES['zh-CN'].record_not_found; + const EN = BUILTIN_OPERATION_MESSAGES.en.record_not_found; + + /** An engine that resolves `null` for an id naming no row instead of refusing it: the arm the check exists for. */ + function makeResolvingEngine() { + const t = makeStoreEngine(); + t.engine.update = vi.fn(async (_object: string, data: any, options?: any) => { + assertEngineUpdateDispatch(data, options); + return t.rows.get(options?.where?.id) ?? null; + }); + return t; + } + + it('updateManyData and batchData update: a zh-CN caller\'s missing row carries the zh-CN sentence', async () => { + const t = makeResolvingEngine(); + const p = new ObjectStackProtocolImplementation(t.engine); + const context = { userId: 'u1', locale: 'zh-CN' }; + + const many: any = await p.updateManyData({ + object: 'showcase_task', records: [{ id: 'definitely_missing', data: { progress: 1 } }], context, + } as any); + const batch: any = await p.batchData({ + object: 'showcase_task', + request: { operation: 'update', records: [{ id: 'definitely_missing', data: { progress: 1 } }] }, + context, + } as any); + + for (const row of [many.results[0], batch.results[0]]) { + expectRecordNotFoundRow(row, 'definitely_missing'); + expect(row.errors[0].userMessage).toBe(ZH); + } + // The check was the one that answered: the engine resolved, the probe read. + expect(t.findOne).toHaveBeenCalled(); + }); + + it('CONTROL: the same row for a caller with no locale carries the English sentence', async () => { + expect(ZH).not.toBe(EN); + const t = makeResolvingEngine(); + const p = new ObjectStackProtocolImplementation(t.engine); + + const many: any = await p.updateManyData({ + object: 'showcase_task', records: [{ id: 'definitely_missing', data: { progress: 1 } }], context: { userId: 'u1' }, + } as any); + + expectRecordNotFoundRow(many.results[0], 'definitely_missing'); + expect(many.results[0].errors[0].userMessage).toBe(EN); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 4187322317f..95bae864d9f 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -6,7 +6,7 @@ import type { MetadataProtocol, PackageProtocol, } from '@objectstack/spec/api'; -import { IDataEngine, recordNotFoundError } from '@objectstack/core'; +import { IDataEngine, recordNotFoundError, type UserMessageCaller } from '@objectstack/core'; import { resolveThrownHttpError } from '@objectstack/types'; import { resolveQueryReadLimits } from '@objectstack/types'; import { type TenancyPosture } from '@objectstack/spec/security'; @@ -5341,12 +5341,13 @@ export class ObjectStackProtocolImplementation implements * context carries no explicit `transaction`, so the probe rides the same * connection as the writes it guards. */ - private assertRecordExists(object: string, id: string): Promise { + private assertRecordExists(object: string, id: string, caller?: UserMessageCaller | null): Promise { // [#25467 cut 4] The body moved to `protocol-record-reads.ts` (see `RecordReadHost`). + // [#34699] `caller` is the row's write context: the language of the refusal's `userMessage`. const host: ThisParameterType = { probeRecord: (...a) => this.probeRecord(...a), }; - return assertRecordExists.call(host, object, id); + return assertRecordExists.call(host, object, id, caller); } /** diff --git a/packages/runtime/src/action-dispatch.ts b/packages/runtime/src/action-dispatch.ts index 802f6d67fba..860b4af436b 100644 --- a/packages/runtime/src/action-dispatch.ts +++ b/packages/runtime/src/action-dispatch.ts @@ -698,7 +698,7 @@ async function dispatchAdmittedAction( // implementation of the rule (#16370), ahead of everything that builds // a trusted context. [#28657] Except ahead of an api forward that needs // nothing from the row: its target authorizes the caller itself. - actionExec.refuseDeniedSubjectLoadBeforeDispatch(actionDef, objectName, recordId, subject); + actionExec.refuseDeniedSubjectLoadBeforeDispatch(actionDef, objectName, recordId, subject, ec); // ── api forward (#27506) ── a same-origin `type: 'api'` action is // forwarded IN-PROCESS to its declared `target` with the caller's own diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 61cee77dae7..d9aad0e2798 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -56,6 +56,7 @@ import { markAppAutomationElevation } from '@objectstack/core'; // Managing API keys is a signed-in-session act: the one rule this door's // per-object gate asks beside the exposure decision, shared with `RestServer`. import { apiKeyManagementCredentialRefusal } from '@objectstack/core'; +import type { UserMessageCaller } from '@objectstack/core'; import { PackageScopedNameRefusedError, packageScopedHolderSource, @@ -3397,10 +3398,10 @@ export async function refuseDeniedSubjectBeforeHandOff( const { objectName, recordId, subject, ec, envId } = wiring; if (isDeclarativeUpdateAction(action)) { if (subject.recordLoadDenied) await refuseUngrantedDeclarativeUpdate(deps, requestContext, objectName, ec, envId); - refuseDeniedSubjectLoad(objectName, recordId, subject); + refuseDeniedSubjectLoad(objectName, recordId, subject, ec); return; } - refuseDeniedSubjectLoadBeforeDispatch(action, objectName, recordId, subject); + refuseDeniedSubjectLoadBeforeDispatch(action, objectName, recordId, subject, ec); } export function summarizeAction( @@ -4231,18 +4232,26 @@ export function actionRecordLoadSignal(load: ActionSubjectRecordLoad): { recordL * refusal that distinguished the two would make this door the existence oracle * every other door declines to be. #15079 argued it; this consumes the argument * rather than reopening it. + * + * [#34699] `caller` is whose language the envelope's `userMessage` is in (the + * request's `locale`, then its `workspaceLocale`, then `en`): every door that + * holds the caller's execution context passes it, so the action and flow-start + * doors answer the sentence the data door answers for the same miss. It + * changes the language only — the sentence is one text for a hidden row and a + * missing one, so no door becomes an existence oracle through it. */ export function refuseDeniedSubjectLoad( objectName: string, recordId: string | undefined, subject: ActionSubjectRecordLoad, + caller?: UserMessageCaller | null, ): void { if (!subject.recordLoadDenied) return; // The producer never attempts a load without a `recordId`, so the verdict // cannot be `true` without one. The `??` names the id in the envelope; it is // ⛔ NOT a second condition — a guard whose extra clause can switch it off is // the inert-guard shape this whole seam exists to remove. - throw recordNotFoundError(objectName, recordId ?? ''); + throw recordNotFoundError(objectName, recordId ?? '', caller); } /** @@ -4368,9 +4377,11 @@ export function refuseDeniedSubjectLoadBeforeDispatch( objectName: string, recordId: string | undefined, subject: ActionSubjectRecordLoad, + // [#34699] The caller whose language the refusal's `userMessage` is in. + caller?: UserMessageCaller | null, ): void { if (subject.recordLoadDenied && forwardsOnDeniedSubjectLoad(action)) return; - refuseDeniedSubjectLoad(objectName, recordId, subject); + refuseDeniedSubjectLoad(objectName, recordId, subject, caller); } /** @@ -4526,7 +4537,7 @@ export async function refuseUnreadableFlowStartRecords( const once = `${objectName}\u0000${recordId}`; if (loaded.has(once)) return; const subject = await loadActionSubjectRecord(objectName, recordId, () => readRecord(objectName, recordId)); - refuseDeniedSubjectLoad(objectName, recordId, subject); + refuseDeniedSubjectLoad(objectName, recordId, subject, executionContext); loaded.add(once); }; const named = start.recordKeys.filter(([, value]) => isNamedStartValue(value)); @@ -4805,7 +4816,7 @@ export async function executeDeclarativeUpdateAction( if (subject.recordLoadDenied) { await refuseUngrantedDeclarativeUpdate(_deps, wiring.requestContext, objectName, ec, envId); } - refuseDeniedSubjectLoad(objectName, recordId, subject); + refuseDeniedSubjectLoad(objectName, recordId, subject, ec); // ── contract point 2: ONE data-plane update, AS THE CALLER ─────────────── // ⛔ `ec`, never `buildActionExecutionContext(ec)`. See the docblock — this diff --git a/packages/runtime/src/flow-start-record-admission.test.ts b/packages/runtime/src/flow-start-record-admission.test.ts index fa383735ad4..dfe2eca40cf 100644 --- a/packages/runtime/src/flow-start-record-admission.test.ts +++ b/packages/runtime/src/flow-start-record-admission.test.ts @@ -38,6 +38,7 @@ import { callData, invokeBusinessAction } from './action-execution.js'; import { buildEndpointExecutionContext, executeEndpointTarget } from './endpoint-executor.js'; import { ApiEndpointSchema } from '@objectstack/spec/api'; import type { ApiEndpointMatch } from '@objectstack/spec/contracts'; +import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; const OBJECT = 'crm_case'; const MEMBER = 'usr_member'; @@ -422,3 +423,48 @@ describe('the trigger route and the action door answer one refusal for one row', expect(envelopeOf(viaTrigger, UNREADABLE)).toMatchObject({ status: 404, code: 'RECORD_NOT_FOUND' }); }); }); + +// ─────────────────────────────────────────────────────────────────────────── +// 5. The refusal's end-user sentence is in the caller's language +// ─────────────────────────────────────────────────────────────────────────── + +/** + * [#34699] The not-found refusal of the action door's subject load and of the + * flow-start door's row admission carries `userMessage` in the CALLER's + * language (the request `locale`, then `workspaceLocale`, then `en`), as the + * data door's own miss does. Both doors hold the caller's execution context + * and hand it to the refusal; `code`, status and `message` do not move. + */ +describe('[#34699] the not-found refusal speaks the caller\'s language at the action and flow-start doors', () => { + const ZH = BUILTIN_OPERATION_MESSAGES['zh-CN'].record_not_found; + const EN = BUILTIN_OPERATION_MESSAGES.en.record_not_found; + const zhCaller = () => ({ ...ec(MEMBER), locale: 'zh-CN' }); + + it('the action door (`POST /actions`), a routed row the zh-CN caller cannot read: the zh-CN sentence', async () => { + const res = await boot(zhCaller()).actions(`/${OBJECT}/${FLOW_ACTION.name}/${UNREADABLE}`); + + expect(statusOf(res)).toBe(404); + expect(errorOf(res).code).toBe('RECORD_NOT_FOUND'); + expect(errorOf(res).userMessage).toBe(ZH); + // The operator half keeps its id and API name. + expect(errorOf(res).message).toBe(`Record ${UNREADABLE} not found in ${OBJECT}`); + }); + + it('the flow-start door (`POST /automation/:name/trigger`), a row key the zh-CN caller cannot read: the zh-CN sentence', async () => { + const h = boot(zhCaller()); + const res = await h.dispatch('POST', `/automation/${ELEVATED_SCREEN}/trigger`, { recordId: UNREADABLE, objectName: OBJECT }); + + expect(statusOf(res)).toBe(404); + expect(errorOf(res).code).toBe('RECORD_NOT_FOUND'); + expect(errorOf(res).userMessage).toBe(ZH); + expect(h.automation.execute).not.toHaveBeenCalled(); + }); + + it('CONTROL: the same start by a caller with no locale answers the English sentence, so the language is the caller\'s', async () => { + expect(ZH).not.toBe(EN); + const res = await boot(ec(MEMBER)).dispatch('POST', `/automation/${ELEVATED_SCREEN}/trigger`, { recordId: UNREADABLE, objectName: OBJECT }); + + expect(statusOf(res)).toBe(404); + expect(errorOf(res).userMessage).toBe(EN); + }); +}); From 5ea3c15d15fdbfbf523ffad0376cf94213572414 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:19:24 +0000 Subject: [PATCH 08/10] =?UTF-8?q?chore(changeset):=20declare=20Clause-?= =?UTF-8?q?=E2=91=A1=20yes=20(widening)=20and=20name=20the=20widened=20exp?= =?UTF-8?q?orts=20and=20catalog=20keys?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- .changeset/34699-platform-refusal-user-message.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/34699-platform-refusal-user-message.md b/.changeset/34699-platform-refusal-user-message.md index 9cc457bf1ee..e45d681843c 100644 --- a/.changeset/34699-platform-refusal-user-message.md +++ b/.changeset/34699-platform-refusal-user-message.md @@ -12,7 +12,7 @@ "@objectstack/service-print": patch --- -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none Four refusals the platform writes now carry a `userMessage` in the caller's language (the request locale, else the workspace default), beside a code, status and `message` that do not change. Before this a zh-CN user read each of them in English. @@ -22,4 +22,4 @@ Four refusals the platform writes now carry a `userMessage` in the caller's lang - `403 DELEGATION_SCOPE_VIOLATION`, a delegated administrator's write outside their own scope (`delegation_scope_violation`). The gate's reason stays in `message`. - `409 RECORD_LOCKED` from an approval's record lock: the localized sentence is now also the `userMessage`, without the `RECORD_LOCKED: ` prefix. The bound refusals that name an API name for the developer mark none. -The three sentences are new keys of the shared operation-message catalog (`BUILTIN_OPERATION_MESSAGES`, in `en`, `zh-CN`, `ja-JP` and `es-ES`), so a deployment can override them under `errors.` where the producer holds an i18n service. `@objectstack/core` exports `operationUserMessage(messageKey, caller)` for producers that hold none, and `recordNotFoundError` takes the caller as an optional third argument. +The three sentences are new keys of the shared operation-message catalog (`BUILTIN_OPERATION_MESSAGES`, in `en`, `zh-CN`, `ja-JP` and `es-ES`), so a deployment can override them under `errors.` where the producer holds an i18n service. The widening: `@objectstack/spec` adds the catalog keys `record_not_found`, `query_field_not_readable` and `delegation_scope_violation`; `@objectstack/core` exports `operationUserMessage(messageKey, caller)` and its caller type `UserMessageCaller` for producers that hold no i18n service, and `recordNotFoundError` takes the caller as an optional third argument. Every door that holds the caller's execution context passes it, the action door's subject load, the flow-start door's row admission and the bulk update faces' existence check included, so the same miss reads in the same language at the data, action and flow-start doors. From 1130a716e03ac4a5d701a143b5e821b892f9e104 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:31:27 +0000 Subject: [PATCH 09/10] test: pay the dynamically loaded dependency at collection in the two new pin files check:test-source-alias asks each edited test file whose source under test loads a workspace dependency inside a function body to load it at module top. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- .../src/protocol.bulk-record-not-found.test.ts | 3 +++ packages/runtime/src/flow-start-record-admission.test.ts | 3 +++ 2 files changed, 6 insertions(+) diff --git a/packages/metadata-protocol/src/protocol.bulk-record-not-found.test.ts b/packages/metadata-protocol/src/protocol.bulk-record-not-found.test.ts index 70b6f6d5c7c..ccc9955ef6a 100644 --- a/packages/metadata-protocol/src/protocol.bulk-record-not-found.test.ts +++ b/packages/metadata-protocol/src/protocol.bulk-record-not-found.test.ts @@ -43,6 +43,9 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { recordNotFoundError } from '@objectstack/core'; import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// Paid at collection, not inside a case's clock (check:test-source-alias): +// the source under test loads it dynamically. +import '@objectstack/lint'; const SCHEMA = { name: 'showcase_task', diff --git a/packages/runtime/src/flow-start-record-admission.test.ts b/packages/runtime/src/flow-start-record-admission.test.ts index dfe2eca40cf..6e300e6a4d2 100644 --- a/packages/runtime/src/flow-start-record-admission.test.ts +++ b/packages/runtime/src/flow-start-record-admission.test.ts @@ -39,6 +39,9 @@ import { buildEndpointExecutionContext, executeEndpointTarget } from './endpoint import { ApiEndpointSchema } from '@objectstack/spec/api'; import type { ApiEndpointMatch } from '@objectstack/spec/contracts'; import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system'; +// Paid at collection, not inside a case's clock (check:test-source-alias): +// the source under test loads it dynamically. +import '@objectstack/metadata'; const OBJECT = 'crm_case'; const MEMBER = 'usr_member'; From d0668d12a8e6ec3a02a2efd20560e87fa6f90cba Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:08:04 +0000 Subject: [PATCH 10/10] style(metadata-protocol): add no line to protocol.ts for the caller param protocol.ts sits under a facade line ceiling of 11705 (ruling 6897467376), and an open sibling PR takes the remaining headroom. Drop the delegation-side comment; the facet body in protocol-record-reads.ts already says what `caller` decides. No behaviour change. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX --- packages/metadata-protocol/src/protocol.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 5eb04f8feaa..3c332b834ab 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -5361,7 +5361,6 @@ export class ObjectStackProtocolImplementation implements */ private assertRecordExists(object: string, id: string, caller?: UserMessageCaller | null): Promise { // [#25467 cut 4] The body moved to `protocol-record-reads.ts` (see `RecordReadHost`). - // [#34699] `caller` is the row's write context: the language of the refusal's `userMessage`. const host: ThisParameterType = { probeRecord: (...a) => this.probeRecord(...a), };