Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .changeset/34699-platform-refusal-user-message.md
Original file line number Diff line number Diff line change
@@ -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-②: 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.

- `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.<key>` 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.
6 changes: 4 additions & 2 deletions content/docs/protocol/kernel/error-handling.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -684,14 +684,16 @@ resource is named in `message`.

<Callout type="info">
**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."
}
```

Expand Down
8 changes: 6 additions & 2 deletions content/docs/protocol/kernel/http-protocol.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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."
}
```

Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/security/own-row-delete-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ export async function removeOwnRow(
| Record<string, unknown>
| 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);
Expand All @@ -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(
Expand Down
53 changes: 53 additions & 0 deletions packages/core/src/utils/operation-user-message.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;
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);
});
});
47 changes: 47 additions & 0 deletions packages/core/src/utils/operation-user-message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// 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 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 type UserMessageCaller = object;

interface CallerLocales {
readonly locale?: unknown;
readonly workspaceLocale?: unknown;
}

/**
* [#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.<key>`
* 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 rungs = caller as CallerLocales | null | undefined;
const locale = [rungs?.locale, rungs?.workspaceLocale].find(
(candidate): candidate is string =>
typeof candidate === 'string' &&
candidate.length > 0 &&
resolveBundleLocale(BUILTIN_OPERATION_MESSAGES, candidate) !== undefined,
);
return renderOperationMessage({ messageKey }, { locale });
}
15 changes: 14 additions & 1 deletion packages/core/src/utils/record-not-found.ts
Original file line number Diff line number Diff line change
@@ -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.
*
Expand Down Expand Up @@ -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;
}
7 changes: 6 additions & 1 deletion packages/mcp/src/mcp-coded-refusal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.' }),
},
});
});

Expand Down
9 changes: 8 additions & 1 deletion packages/mcp/src/stdio-data-bridge.not-found.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
8 changes: 4 additions & 4 deletions packages/metadata-protocol/src/protocol-batch-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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++;
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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++;
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions packages/metadata-protocol/src/protocol-data-crud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions packages/metadata-protocol/src/protocol-data-writes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ export async function updateData(host: Pick<ProtocolHost, 'assertObjectRegistere
// {@link probeRecord}. ObjectQL refuses a row that is not there
// itself, so this reads only on a `null` readback.
if (result == null && !(await host.probeRecord(request.object, request.id))) {
throw recordNotFoundError(request.object, request.id);
throw recordNotFoundError(request.object, request.id, request.context);
}
// [#7823] The PATCH 200 body is the surface #7728's fourth measurement
// caught: a client revoking a `sys_api_key` (apiMethods keeps `update`
Expand Down Expand Up @@ -286,7 +286,7 @@ export async function deleteData(host: Pick<ProtocolHost, 'assertObjectRegistere
// an `undefined` from an off-contract implementation — is not a
// POSITIVE not-found signal, and inventing a 404 out of it would break
// deletes against third-party drivers rather than report honestly.
if (deleted === false) throw recordNotFoundError(request.object, request.id);
if (deleted === false) throw recordNotFoundError(request.object, request.id, request.context);
// The same measurement, one outcome over: `success` was still a
// LITERAL for every answer that was not the contract's `false`, so a
// row that MATCHED and was deliberately NOT removed reported a
Expand Down
7 changes: 4 additions & 3 deletions packages/metadata-protocol/src/protocol-record-reads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<RecordReadHost, 'probeRecord'>,
object: string, id: string): Promise<void> {
object: string, id: string, caller?: UserMessageCaller | null): Promise<void> {
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. */
Expand Down
Loading
Loading