From c371f0445e6f94c9ed09f72eae05c36d6fa7d7a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 17:16:45 +0000 Subject: [PATCH] fix(lint): connector, permission-set and form-view advisories carry a user sentence in every platform locale Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L9qibwqZc5F1URP3eghRix --- .changeset/32842-advisory-user-text.md | 22 ++ packages/lint/src/authoring-rules.ts | 6 + ...ser-text.connector-permission-form.test.ts | 351 ++++++++++++++++++ packages/lint/src/finding-user-text.ts | 8 + .../src/lint-connector-credential-literals.ts | 12 + ...connector-credential-literals.user-text.ts | 254 +++++++++++++ .../lint/src/validate-predicate-path-refs.ts | 21 +- .../validate-predicate-path-refs.user-text.ts | 91 +++++ .../validate-retired-permission-residue.ts | 8 + ...te-retired-permission-residue.user-text.ts | 73 ++++ 10 files changed, 842 insertions(+), 4 deletions(-) create mode 100644 .changeset/32842-advisory-user-text.md create mode 100644 packages/lint/src/finding-user-text.connector-permission-form.test.ts create mode 100644 packages/lint/src/lint-connector-credential-literals.user-text.ts create mode 100644 packages/lint/src/validate-predicate-path-refs.user-text.ts create mode 100644 packages/lint/src/validate-retired-permission-residue.user-text.ts diff --git a/.changeset/32842-advisory-user-text.md b/.changeset/32842-advisory-user-text.md new file mode 100644 index 00000000000..8532156b299 --- /dev/null +++ b/.changeset/32842-advisory-user-text.md @@ -0,0 +1,22 @@ +--- +'@objectstack/lint': patch +--- + +fix(lint): the connector, permission-set and form-view advisories a save returns carry a user sentence in every platform locale + +Clause-②: no +Metadata-protocol: none + +Three advisory rule ids that the save door returns now carry `userTextParams` (the connector, permission set, object, view and entry names their user sentence interpolates) and have a sentence in all eleven platform locales, each in a `*.user-text.ts` catalog beside its rule and merged into the one catalog `findingUserMessage` renders from: + +- `connector-credential-literal` (connector write), in four arms: a credential in a header, in an MCP server's environment variable, in `credentialEnv`, and a stdio MCP server whose credential reaches nothing. The sentence names the connector and the header or variable the credential sits under, and never the credential itself. +- `permission-retired-lifecycle-residue` (permission write): names the permission set, the object and the retired key. +- `predicate-rhs-path-shaped`, its advisory bare-word arm (view write): names the form view, the word and the operator, and gives both readings with the supported spelling of each (the quoted word, or the field on the left compared with a quoted value). + +Rule ids, `message` and `hint` are unchanged, and the refusal arm of `predicate-rhs-path-shaped` (a dotted path on the right) carries no params, so it renders no user sentence. The `lintConnectorCredentialLiterals` and `validateRetiredPermissionResidue` registry entries now keep `userTextParams` when they re-map their findings, so the publish gate's advisories carry them. Because the finding objects now carry `userTextParams`, `os validate --json` and `os build --json` show that key on these findings in `warnings`. + +The other seven advisory ids in these rule files get no sentence, because the save door never returns them: + +- `agent-authoring-withdrawn`, `default-agent-outside-roster`, `default-agent-legacy-alias` and `mapping-connector-source-unknown`: reference-integrity suite members on its default `flow` write type. An agent, app or mapping write dispatches none of them, and a flow write's snapshot carries no agents, apps or mappings. +- `ai-skill-tool-unresolved`: the same, and kept off the door on purpose by ruling 5791822697 (ADR-0109 Decision §3): a per-write snapshot cannot resolve a skill's tools truthfully. +- `security-external-owner-unmapped` and `sharing-rule-object-not-shareable`: their registry entries run on the command line only. diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index fbc21007134..9968f378733 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -2078,6 +2078,9 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ path: f.path, message: f.message, hint: f.hint, + // The user sentence's names ride through the re-map, so the save door + // can render this advisory in the request's language. + ...(f.userTextParams !== undefined ? { userTextParams: f.userTextParams } : {}), })), }, // The spec-liveness loop on the author side: a property the ledger marks @@ -2199,6 +2202,9 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ path: f.path, message: f.message, hint: f.hint, + // The user sentence's names ride through the re-map, so the save door + // can render this advisory in the request's language. + ...(f.userTextParams !== undefined ? { userTextParams: f.userTextParams } : {}), })), }, // A format like `{plan_no}{000}` makes the referenced field part of the diff --git a/packages/lint/src/finding-user-text.connector-permission-form.test.ts b/packages/lint/src/finding-user-text.connector-permission-form.test.ts new file mode 100644 index 00000000000..f9de69a8d5c --- /dev/null +++ b/packages/lint/src/finding-user-text.connector-permission-form.test.ts @@ -0,0 +1,351 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The connector, permission-set and form-view advisories' user-facing + * sentences in the request's language (ruling record 6819749037, the pattern + * `finding-user-text.test.ts` pins for the security-posture rule): the + * connector credential rule's catalog (`lint-connector-credential-literals.user-text.ts`), + * the retired permission key rule's (`validate-retired-permission-residue.user-text.ts`) + * and the form predicate rule's (`validate-predicate-path-refs.user-text.ts`), + * each rendered from the rule's REAL findings in every platform locale, and + * carried out of the publish door. + * + * Of the ten advisory ids in the AI agent and tool, connector, mapping and + * sharing rule files, these three are the ones the publish door returns; the + * other seven are named below, with the reason each never reaches it. + */ + +import { describe, it, expect } from 'vitest'; +import { RuntimeAuthoringIssueSchema } from '@objectstack/spec/api'; +import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system'; +import { FINDING_USER_TEXT_CATALOG, findingUserMessage } from './finding-user-text.js'; +import { CONNECTOR_CREDENTIAL_LITERALS_USER_TEXT } from './lint-connector-credential-literals.user-text.js'; +import { RETIRED_PERMISSION_RESIDUE_USER_TEXT } from './validate-retired-permission-residue.user-text.js'; +import { PREDICATE_PATH_REFS_USER_TEXT } from './validate-predicate-path-refs.user-text.js'; +import { CONNECTOR_CREDENTIAL_LITERAL, lintConnectorCredentialLiterals } from './lint-connector-credential-literals.js'; +import { + PERMISSION_RETIRED_LIFECYCLE_RESIDUE, + validateRetiredPermissionResidue, +} from './validate-retired-permission-residue.js'; +import { PREDICATE_RHS_PATH_SHAPED, validatePredicatePathRefs } from './validate-predicate-path-refs.js'; +import { + AGENT_AUTHORING_WITHDRAWN, + DEFAULT_AGENT_LEGACY_ALIAS, + DEFAULT_AGENT_OUTSIDE_ROSTER, +} from './validate-ai-agent-authoring.js'; +import { AI_SKILL_TOOL_UNRESOLVED } from './validate-ai-tool-references.js'; +import { MAPPING_CONNECTOR_SOURCE_UNKNOWN } from './validate-mapping-connector-source.js'; +import { SECURITY_EXTERNAL_OWNER_UNMAPPED } from './validate-external-owner-sharing.js'; +import { SHARING_RULE_OBJECT_NOT_SHAREABLE } from './validate-sharing-rule-enforceability.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; + +type AnyRec = Record; + +/** The advisory ids of these rule files the publish door returns, one catalog each. */ +const CATALOGS = [ + { catalog: CONNECTOR_CREDENTIAL_LITERALS_USER_TEXT, rules: [CONNECTOR_CREDENTIAL_LITERAL] }, + { catalog: RETIRED_PERMISSION_RESIDUE_USER_TEXT, rules: [PERMISSION_RETIRED_LIFECYCLE_RESIDUE] }, + { catalog: PREDICATE_PATH_REFS_USER_TEXT, rules: [PREDICATE_RHS_PATH_SHAPED] }, +] as const; + +// ── Fixtures ──────────────────────────────────────────────────────────────── + +/** Probe sentinels shaped like credentials. ⛔ None may reach a param or a sentence. */ +const SECRET = { + header: 'Bearer probe-header-sentinel', + env: 'Bearer probe-env-sentinel', + credentialEnv: 'probe7sentinel3value9token5x', +} as const; + +const restConnector = { + name: 'acme_billing', + label: 'Acme Billing', + type: 'api', + provider: 'rest', + providerConfig: { + baseUrl: 'https://api.acme.invalid/v1', + defaultHeaders: { Authorization: SECRET.header, Accept: 'application/json' }, + }, +}; + +/** A stdio `mcp` entry with the transport keys and `auth` it is given. */ +const stdioConnector = (transport: AnyRec, auth?: AnyRec): AnyRec => ({ + name: 'acme_repo_tools', + label: 'Acme Repo Tools', + type: 'api', + provider: 'mcp', + providerConfig: { transport: { kind: 'stdio', command: 'repo-mcp-server', ...transport } }, + ...(auth ? { auth } : {}), +}); + +const envConnector = stdioConnector({ env: { MCP_UPSTREAM: SECRET.env, LOG_LEVEL: 'info' } }); +const credentialEnvConnector = stdioConnector( + { credentialEnv: SECRET.credentialEnv }, + { type: 'bearer', credentialRef: 'ACME_REPO_TOKEN' }, +); +const stdioAuthConnector = stdioConnector({ env: { LOG_LEVEL: 'info' } }, { type: 'bearer', credentialRef: 'ACME_REPO_TOKEN' }); + +const permissionSet = (key: 'allowRestore' | 'allowPurge') => ({ + name: 'acme_support_agent', + label: 'Support Agent', + objects: { acme_ticket: { allowRead: true, allowEdit: true, [key]: false } }, +}); + +/** A schema-bound form view: its predicates resolve against `FieldSchema`. */ +const formView = (visibleWhen: string) => ({ + name: 'acme_field_editor', + label: 'Field editor', + form: { + data: { provider: 'schema', schemaId: 'field' }, + sections: [{ label: 'Main', fields: [{ field: 'name', visibleWhen }] }], + }, +}); + +type Finding = { rule: string; severity: string; userTextParams?: Record }; +type Case = { + label: string; + rule: string; + stack: AnyRec; + params: Record; + run: (stack: AnyRec) => readonly Finding[]; +}; + +/** + * One stack per advisory push site the publish door reaches, with the params + * each finding must carry: the connector rule's three sites (the map-entry site + * in both its header and env positions, the credentialEnv site and the stdio + * auth site), the permission site for both retired keys, and the bare-word arm + * of the predicate rule. + */ +const CASES: readonly Case[] = [ + { + label: 'connector header holding a credential', + rule: CONNECTOR_CREDENTIAL_LITERAL, + stack: { connectors: [restConnector] }, + params: { connector: 'acme_billing', name: 'Authorization', position: 'header' }, + run: (s) => lintConnectorCredentialLiterals(s), + }, + { + label: 'MCP server environment variable holding a credential', + rule: CONNECTOR_CREDENTIAL_LITERAL, + stack: { connectors: [envConnector] }, + params: { connector: 'acme_repo_tools', name: 'MCP_UPSTREAM', position: 'env' }, + run: (s) => lintConnectorCredentialLiterals(s), + }, + { + label: 'credentialEnv holding a credential instead of a variable name', + rule: CONNECTOR_CREDENTIAL_LITERAL, + stack: { connectors: [credentialEnvConnector] }, + params: { connector: 'acme_repo_tools', position: 'credential-env' }, + run: (s) => lintConnectorCredentialLiterals(s), + }, + { + label: 'stdio MCP server whose credential reaches nothing', + rule: CONNECTOR_CREDENTIAL_LITERAL, + stack: { connectors: [stdioAuthConnector] }, + params: { connector: 'acme_repo_tools', position: 'stdio-auth' }, + run: (s) => lintConnectorCredentialLiterals(s), + }, + { + label: 'permission set writing the retired allowRestore default', + rule: PERMISSION_RETIRED_LIFECYCLE_RESIDUE, + stack: { permissions: [permissionSet('allowRestore')] }, + params: { permissionSet: 'acme_support_agent', object: 'acme_ticket', key: 'allowRestore' }, + run: (s) => validateRetiredPermissionResidue(s), + }, + { + label: 'permission set writing the retired allowPurge default', + rule: PERMISSION_RETIRED_LIFECYCLE_RESIDUE, + stack: { permissions: [permissionSet('allowPurge')] }, + params: { permissionSet: 'acme_support_agent', object: 'acme_ticket', key: 'allowPurge' }, + run: (s) => validateRetiredPermissionResidue(s), + }, + { + label: 'form predicate comparing with an unquoted word', + rule: PREDICATE_RHS_PATH_SHAPED, + stack: { views: [formView('data.type == active')] }, + params: { view: 'acme_field_editor', word: 'active', op: '==' }, + run: (s) => validatePredicatePathRefs(s), + }, +]; + +/** The one finding of `rule` the case's stack produces. */ +const findingOf = (c: Case) => { + const found = c.run(c.stack).filter((f) => f.rule === c.rule); + expect(found, `${c.label}: exactly one ${c.rule} finding`).toHaveLength(1); + return found[0]!; +}; + +/** The params that are NAMES the sentence must show (not the arm selector). */ +const namesOf = (params: Record): string[] => + Object.entries(params).filter(([key]) => key !== 'position').map(([, value]) => value); + +describe('connector, permission and form advisories user text · the catalogs', () => { + it.each(CATALOGS.map((c) => [c.rules.join(', '), c] as const))( + 'the catalog of %s holds a sentence for exactly its door-reaching ids, in every platform locale', + (_label, { catalog, rules }) => { + expect(Object.keys(catalog).sort()).toEqual([...rules].sort()); + for (const [rule, entry] of Object.entries(catalog)) { + expect(Object.keys(entry).sort(), rule).toEqual([...PLATFORM_LOCALE_TAGS].sort()); + } + }, + ); + + it('all three are merged into the one finding catalog the door renders from', () => { + for (const { catalog, rules } of CATALOGS) { + for (const rule of rules) expect(FINDING_USER_TEXT_CATALOG[rule], rule).toBe(catalog[rule]); + } + }); + + it('keeps every rule id stable: the catalogs are keyed by the ids the findings already carry', () => { + expect(CATALOGS.flatMap((c) => c.rules)).toEqual([ + 'connector-credential-literal', + 'permission-retired-lifecycle-residue', + 'predicate-rhs-path-shaped', + ]); + }); + + it('the advisory ids the door never returns have no sentence here, and stay on the English message', () => { + for (const rule of [ + // Reference-integrity suite members on its frozen `flow` default: an + // agent, app, skill or mapping write dispatches none of them, and a flow + // write's snapshot carries no agents, apps, skills or mappings. The skill + // one stays off the door by ruling 5791822697 (ADR-0109 Decision §3). + AGENT_AUTHORING_WITHDRAWN, + DEFAULT_AGENT_OUTSIDE_ROSTER, + DEFAULT_AGENT_LEGACY_ALIAS, + AI_SKILL_TOOL_UNRESOLVED, + MAPPING_CONNECTOR_SOURCE_UNKNOWN, + // CLI-only registry entries. + SECURITY_EXTERNAL_OWNER_UNMAPPED, + SHARING_RULE_OBJECT_NOT_SHAREABLE, + ]) { + expect(FINDING_USER_TEXT_CATALOG[rule], rule).toBeUndefined(); + } + }); +}); + +describe('connector, permission and form advisories user text · rendered from the rules\' real findings', () => { + it.each(CASES.map((c) => [c.label, c] as const))('%s: carries its params and renders in every platform locale', (_label, c) => { + const finding = findingOf(c); + expect(finding.severity).toBe('warning'); + expect(finding.userTextParams).toEqual(c.params); + + const english = findingUserMessage(finding, ['en'])!; + for (const tag of PLATFORM_LOCALE_TAGS) { + const text = findingUserMessage(finding, [tag]); + expect(text, `${c.rule} · ${tag}`).toBeTruthy(); + expect(text, `${c.rule} · ${tag}`).not.toMatch(/undefined|\$\{/); + for (const name of namesOf(c.params)) expect(text, `${c.rule} · ${tag} names ${name}`).toContain(name); + // A real translation, not the English floor standing in for it. + if (tag !== 'en') expect(text, `${c.rule} · ${tag}`).not.toBe(english); + } + }); + + it('never carries the credential itself: not in the params, not in any locale\'s sentence', () => { + for (const c of CASES.filter((x) => x.rule === CONNECTOR_CREDENTIAL_LITERAL)) { + const finding = findingOf(c); + for (const secret of Object.values(SECRET)) { + expect(JSON.stringify(finding.userTextParams), c.label).not.toContain(secret); + for (const tag of PLATFORM_LOCALE_TAGS) { + expect(findingUserMessage(finding, [tag]), `${c.label} · ${tag}`).not.toContain(secret); + } + } + } + }); + + it('renders the four connector arms apart in every platform locale', () => { + const findings = CASES.filter((c) => c.rule === CONNECTOR_CREDENTIAL_LITERAL).map(findingOf); + expect(findings).toHaveLength(4); + for (const tag of PLATFORM_LOCALE_TAGS) { + // Same names, so only the position tells the arms apart. + const texts = findings.map((f) => + findingUserMessage({ ...f, userTextParams: { ...f.userTextParams!, connector: 'c', name: 'n' } }, [tag])); + expect(new Set(texts).size, tag).toBe(4); + } + }); + + it('names both readings of the unquoted word, with the supported spelling of each, in every platform locale', () => { + // The rule cannot tell which reading the author meant, so the sentence must + // not pick one, and must never put the root in front of the word where it + // stands: `== data.active` is the path-on-the-right this rule refuses. + for (const op of ['==', '!='] as const) { + const [finding] = validatePredicatePathRefs({ views: [formView(`data.type ${op} pending`)] }) + .filter((f) => f.rule === PREDICATE_RHS_PATH_SHAPED); + expect(finding!.userTextParams).toEqual({ view: 'acme_field_editor', word: 'pending', op }); + for (const tag of PLATFORM_LOCALE_TAGS) { + const text = findingUserMessage(finding!, [tag])!; + expect(text, `${op} · ${tag}: the text reading`).toContain(`${op} 'pending'`); + expect(text, `${op} · ${tag}: the field reading`).toContain("data.pending == 'yes'"); + expect(text, `${op} · ${tag}: never the root in place`).not.toContain(`${op} data.pending`); + } + } + }); + + it('renders the connector and permission sentences in zh-Hans and en with the names they carry', () => { + const header = findingOf(CASES[0]!); + expect(findingUserMessage(header, ['zh-CN'])).toContain('连接器“acme_billing”的请求头“Authorization”'); + expect(findingUserMessage(header, ['zh-CN'])).toContain('请将它保存到连接器凭据'); + expect(findingUserMessage(header, ['en-US'])).toContain( + 'Connector "acme_billing" has a credential written directly into its header "Authorization"', + ); + const residue = findingOf(CASES[4]!); + expect(findingUserMessage(residue, ['zh-CN'])).toContain('权限集“acme_support_agent”仍为对象“acme_ticket”设置了“allowRestore: false”'); + }); + + it('gives no sentence where the finding is not advice the door returns', () => { + // The dotted arm of the same id refuses the write: no params. + const dotted = validatePredicatePathRefs({ views: [formView('data.type == data.label')] }) + .filter((f) => f.rule === PREDICATE_RHS_PATH_SHAPED); + expect(dotted.map((f) => f.severity)).toEqual(['error']); + expect(dotted[0]!.userTextParams).toBeUndefined(); + }); +}); + +describe('connector, permission and form advisories user text · from the runtime gate to the wire field', () => { + /** The element the save door's `advisories[]` carries, with the sentence it renders. */ + const issueOf = (advisory: { rule: string; path: string; where: string; message: string; hint: string; severity: string; userTextParams?: Record }, locales: string[]) => + RuntimeAuthoringIssueSchema.parse({ + rule: advisory.rule, + path: advisory.path, + where: advisory.where, + message: advisory.message, + hint: advisory.hint, + severity: advisory.severity, + userMessage: findingUserMessage(advisory, locales), + }); + + it('a connector write\'s credential advisory carries its params through the registry adapter', () => { + const result = runRuntimeAuthoringRules({ type: 'connector', item: restConnector, context: { objects: [] } }); + const advisory = result.advisories.find((f) => f.rule === CONNECTOR_CREDENTIAL_LITERAL); + expect(advisory, JSON.stringify(result.advisories)).toBeDefined(); + expect(advisory!.userTextParams).toEqual({ connector: 'acme_billing', name: 'Authorization', position: 'header' }); + + const issue = issueOf(advisory!, ['de-DE', 'en']); + expect(issue.rule).toBe('connector-credential-literal'); + expect(issue.userMessage).toContain('Der Connector „acme_billing“'); + expect(issue.userMessage).not.toContain(SECRET.header); + expect(issue.message).toBe(advisory!.message); + }); + + it('a permission write\'s retired-key advisory carries its params through the registry adapter', () => { + const result = runRuntimeAuthoringRules({ type: 'permission', item: permissionSet('allowPurge'), context: { objects: [] } }); + const advisory = result.advisories.find((f) => f.rule === PERMISSION_RETIRED_LIFECYCLE_RESIDUE); + expect(advisory, JSON.stringify(result.advisories)).toBeDefined(); + expect(advisory!.userTextParams).toEqual({ permissionSet: 'acme_support_agent', object: 'acme_ticket', key: 'allowPurge' }); + + const issue = issueOf(advisory!, ['ja-JP']); + expect(issue.userMessage).toContain('権限セット「acme_support_agent」は、オブジェクト「acme_ticket」に対してまだ「allowPurge: false」'); + }); + + it('a view write\'s unquoted-word advisory renders a valid userMessage', () => { + const result = runRuntimeAuthoringRules({ type: 'view', item: formView('data.type == active'), context: { objects: [] } }); + const advisory = result.advisories.find((f) => f.rule === PREDICATE_RHS_PATH_SHAPED); + expect(advisory, JSON.stringify(result.advisories)).toBeDefined(); + expect(advisory!.userTextParams).toEqual({ view: 'acme_field_editor', word: 'active', op: '==' }); + + const issue = issueOf(advisory!, ['fr-FR']); + expect(issue.userMessage).toContain('formulaire « acme_field_editor »'); + expect(issue.userMessage).toContain("== 'active'"); + }); +}); diff --git a/packages/lint/src/finding-user-text.ts b/packages/lint/src/finding-user-text.ts index c1ebb94add1..b8afe25b059 100644 --- a/packages/lint/src/finding-user-text.ts +++ b/packages/lint/src/finding-user-text.ts @@ -62,6 +62,9 @@ import { READONLY_FLOW_WRITES_USER_TEXT } from './validate-readonly-flow-writes. import { FLOW_CREDENTIAL_LITERALS_USER_TEXT } from './lint-flow-credential-literals.user-text.js'; import { WIDGET_BINDINGS_USER_TEXT } from './validate-widget-bindings.user-text.js'; import { CHART_BINDINGS_USER_TEXT } from './validate-chart-bindings.user-text.js'; +import { CONNECTOR_CREDENTIAL_LITERALS_USER_TEXT } from './lint-connector-credential-literals.user-text.js'; +import { RETIRED_PERMISSION_RESIDUE_USER_TEXT } from './validate-retired-permission-residue.user-text.js'; +import { PREDICATE_PATH_REFS_USER_TEXT } from './validate-predicate-path-refs.user-text.js'; /** * The names a finding's user sentence interpolates — object, field and @@ -173,6 +176,11 @@ export const FINDING_USER_TEXT_CATALOG: UserTextCatalog = mergeUserTextCatalogs( // The dashboard writes: widget and chart binding advisories. WIDGET_BINDINGS_USER_TEXT, CHART_BINDINGS_USER_TEXT, + // The connector, permission and form-view writes: the connector credential, + // retired permission key and form predicate advisories. + CONNECTOR_CREDENTIAL_LITERALS_USER_TEXT, + RETIRED_PERMISSION_RESIDUE_USER_TEXT, + PREDICATE_PATH_REFS_USER_TEXT, ); /** diff --git a/packages/lint/src/lint-connector-credential-literals.ts b/packages/lint/src/lint-connector-credential-literals.ts index bc16db93d2d..7cae1ee67d1 100644 --- a/packages/lint/src/lint-connector-credential-literals.ts +++ b/packages/lint/src/lint-connector-credential-literals.ts @@ -70,6 +70,7 @@ import { isCredentialShapedLiteral, isCredentialShapedName } from './credential-literal.js'; import { recordsOf } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; type AnyRec = Record; @@ -88,6 +89,14 @@ export interface ConnectorCredentialLiteralFinding { path: string; message: string; hint: string; + /** + * The names this finding's user sentence interpolates + * (`lint-connector-credential-literals.user-text.ts`): the connector, the + * entry's NAME when the finding is about a map entry, and its position + * (`header` · `env` · `credential-env` · `stdio-auth`). ⛔ Never the value, + * for the module note's reason; see `AuthoringFinding.userTextParams`. + */ + userTextParams?: UserTextParams; } /** @@ -194,6 +203,7 @@ export function lintConnectorCredentialLiterals(stack: AnyRec): ConnectorCredent // `os explain connector-credential-literal`. message: `${judged.entry} '${key}' in ${label} holds a credential-shaped literal, ${KEPT}; ${steer}`, hint: judged.entry === 'env' ? ENV_ROUTE : HEADER_ROUTE, + userTextParams: { connector: name, name: key, position: judged.entry }, }); } } @@ -213,6 +223,7 @@ export function lintConnectorCredentialLiterals(stack: AnyRec): ConnectorCredent 'providerConfig.transport.credentialEnv reads as a credential, not a variable name, and is served on ' + 'every metadata read; put the secret behind `auth.credentialRef` and name its variable here', hint: CREDENTIAL_ENV_ROUTE, + userTextParams: { connector: name, position: 'credential-env' }, }); } @@ -234,6 +245,7 @@ export function lintConnectorCredentialLiterals(stack: AnyRec): ConnectorCredent `auth '${auth.type}' reaches nothing: a stdio transport passes the resolved credential to the server only ` + 'in the variable `transport.credentialEnv` names, and this entry names none', hint: STDIO_AUTH_UNPLACED_ROUTE, + userTextParams: { connector: name, position: 'stdio-auth' }, }); } }); diff --git a/packages/lint/src/lint-connector-credential-literals.user-text.ts b/packages/lint/src/lint-connector-credential-literals.user-text.ts new file mode 100644 index 00000000000..d8429107963 --- /dev/null +++ b/packages/lint/src/lint-connector-credential-literals.user-text.ts @@ -0,0 +1,254 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `lint-connector-credential-literals.ts`'s + * advisory finding (`connector-credential-literal`), in every platform locale + * (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The finding mechanism + * and the locale ladder are `finding-user-text.ts`'s; this file is the rule's + * own half of it, kept beside the rule so its wording and its translations + * change together. + * + * Who reads it: the person who saved a connector in Studio, in their own + * language, once the save door composes `RuntimeAuthoringIssueSchema.userMessage` + * from it. It says where the credential sits, why that is the wrong place, and + * where it belongs instead: Connector credentials, the console's own page name + * (`connectorCredentials.title`, `ui/packages/i18n`). + * + * Params, set at the three push sites in `lint-connector-credential-literals.ts`: + * `connector`, `position` and, for a map entry, `name` (the header or + * environment variable the value sits under). `position` picks the arm: + * `header` and `env` (a literal in one of the four maps), `credential-env` (a + * credential typed into `transport.credentialEnv`) and `stdio-auth` (a stdio + * MCP server whose credential reaches nothing). ⛔ Never the value itself, for + * the rule's module-note reason: the sentence travels into the save response. + * + * `finding-user-text.connector-permission-form.test.ts` renders it from the rule's + * real findings in every platform locale, one per arm. + */ + +import type { UserTextCatalog, UserTextParams, UserTextTemplate } from './finding-user-text.js'; +import { CONNECTOR_CREDENTIAL_LITERAL } from './lint-connector-credential-literals.js'; + +type Arm = 'header' | 'env' | 'credential-env' | 'stdio-auth'; +type Arms = Readonly>; + +const armOf = (p: UserTextParams): Arm => + p.position === 'env' || p.position === 'credential-env' || p.position === 'stdio-auth' ? p.position : 'header'; + +const byArm = (arms: Arms): UserTextTemplate => (p) => arms[armOf(p)](p); + +export const CONNECTOR_CREDENTIAL_LITERALS_USER_TEXT: UserTextCatalog = Object.freeze({ + [CONNECTOR_CREDENTIAL_LITERAL]: { + en: byArm({ + header: (p) => + `Connector "${p.connector}" has a credential written directly into its header "${p.name}", so the ` + + `credential is stored in the connector's metadata rather than in Connector credentials. Save it in ` + + `Connector credentials and remove the header: the connector then sends the stored credential for you.`, + env: (p) => + `Connector "${p.connector}" has a credential written directly into the environment variable "${p.name}" ` + + `of its MCP server, so the credential is stored in the connector's metadata rather than in Connector ` + + `credentials. Save it in Connector credentials, put the variable's name in "credentialEnv" and remove the ` + + `entry: the connector then passes the stored credential to the server for you.`, + 'credential-env': (p) => + `Connector "${p.connector}" has a credential in "credentialEnv", which should hold only the name of an ` + + `environment variable and is shown to everyone who can read the connector. Save the credential in ` + + `Connector credentials and put the variable's name in "credentialEnv" instead.`, + 'stdio-auth': (p) => + `Connector "${p.connector}" has a credential set, but its MCP server never receives it: a server that runs ` + + `as a local process gets the credential only through the environment variable named in "credentialEnv", ` + + `and none is named. Put the name of the variable the server reads in "credentialEnv", or remove the ` + + `credential if the server needs none.`, + }), + 'zh-Hans': byArm({ + header: (p) => + `连接器“${p.connector}”的请求头“${p.name}”中直接写入了凭据,因此该凭据保存在连接器的元数据里,而不是连接器凭据中。` + + `请将它保存到连接器凭据,并删除该请求头:连接器会自动发送已保存的凭据。`, + env: (p) => + `连接器“${p.connector}”的 MCP 服务器环境变量“${p.name}”中直接写入了凭据,因此该凭据保存在连接器的元数据里,` + + `而不是连接器凭据中。请将它保存到连接器凭据,在“credentialEnv”中填写该变量名,并删除这一项:` + + `连接器会自动把已保存的凭据传给服务器。`, + 'credential-env': (p) => + `连接器“${p.connector}”在“credentialEnv”中写入了凭据。该项只应填写环境变量的名称,并且所有能读取该连接器的人都能看到它。` + + `请将凭据保存到连接器凭据,并改为在“credentialEnv”中填写变量名。`, + 'stdio-auth': (p) => + `连接器“${p.connector}”设置了凭据,但它的 MCP 服务器永远收不到:以本地进程运行的服务器只能通过“credentialEnv”` + + `指定的环境变量获得凭据,而这里没有指定。请在“credentialEnv”中填写服务器读取的变量名;如果服务器不需要凭据,请删除该凭据。`, + }), + 'zh-Hant': byArm({ + header: (p) => + `聯結器「${p.connector}」的請求標頭「${p.name}」中直接寫入了憑據,因此該憑據儲存在聯結器的中繼資料裡,而不是聯結器憑據中。` + + `請將它儲存到聯結器憑據,並刪除該請求標頭:聯結器會自動傳送已儲存的憑據。`, + env: (p) => + `聯結器「${p.connector}」的 MCP 伺服器環境變數「${p.name}」中直接寫入了憑據,因此該憑據儲存在聯結器的中繼資料裡,` + + `而不是聯結器憑據中。請將它儲存到聯結器憑據,在「credentialEnv」中填寫該變數名稱,並刪除這一項:` + + `聯結器會自動把已儲存的憑據傳給伺服器。`, + 'credential-env': (p) => + `聯結器「${p.connector}」在「credentialEnv」中寫入了憑據。該項只應填寫環境變數的名稱,而且所有能讀取該聯結器的人都看得到它。` + + `請將憑據儲存到聯結器憑據,並改為在「credentialEnv」中填寫變數名稱。`, + 'stdio-auth': (p) => + `聯結器「${p.connector}」設定了憑據,但它的 MCP 伺服器永遠收不到:以本機處理程序執行的伺服器只能透過「credentialEnv」` + + `指定的環境變數取得憑據,而這裡沒有指定。請在「credentialEnv」中填寫伺服器讀取的變數名稱;如果伺服器不需要憑據,請刪除該憑據。`, + }), + es: byArm({ + header: (p) => + `El conector "${p.connector}" tiene una credencial escrita directamente en su encabezado "${p.name}", así ` + + `que la credencial se guarda en los metadatos del conector y no en Credenciales de conectores. Guárdela en ` + + `Credenciales de conectores y elimine el encabezado: el conector enviará la credencial guardada por usted.`, + env: (p) => + `El conector "${p.connector}" tiene una credencial escrita directamente en la variable de entorno ` + + `"${p.name}" de su servidor MCP, así que la credencial se guarda en los metadatos del conector y no en ` + + `Credenciales de conectores. Guárdela en Credenciales de conectores, escriba el nombre de la variable en ` + + `"credentialEnv" y elimine la entrada: el conector pasará la credencial guardada al servidor por usted.`, + 'credential-env': (p) => + `El conector "${p.connector}" tiene una credencial en "credentialEnv", que solo debe contener el nombre de ` + + `una variable de entorno y que ve cualquiera que pueda leer el conector. Guarde la credencial en ` + + `Credenciales de conectores y escriba en "credentialEnv" el nombre de la variable.`, + 'stdio-auth': (p) => + `El conector "${p.connector}" tiene una credencial configurada, pero su servidor MCP nunca la recibe: un ` + + `servidor que se ejecuta como proceso local solo obtiene la credencial mediante la variable de entorno ` + + `indicada en "credentialEnv", y no se indica ninguna. Escriba en "credentialEnv" el nombre de la variable ` + + `que lee el servidor, o elimine la credencial si el servidor no la necesita.`, + }), + ar: byArm({ + header: (p) => + `يحتوي الموصل "${p.connector}" على بيانات اعتماد مكتوبة مباشرة في الترويسة "${p.name}"، لذا تُخزَّن ` + + `بيانات الاعتماد في البيانات الوصفية للموصل بدلًا من بيانات اعتماد الموصلات. احفظها في بيانات اعتماد ` + + `الموصلات واحذف الترويسة: سيرسل الموصل بيانات الاعتماد المحفوظة نيابةً عنك.`, + env: (p) => + `يحتوي الموصل "${p.connector}" على بيانات اعتماد مكتوبة مباشرة في متغير البيئة "${p.name}" لخادم MCP ` + + `الخاص به، لذا تُخزَّن بيانات الاعتماد في البيانات الوصفية للموصل بدلًا من بيانات اعتماد الموصلات. ` + + `احفظها في بيانات اعتماد الموصلات، واكتب اسم المتغير في "credentialEnv"، واحذف هذا الإدخال: سيمرّر ` + + `الموصل بيانات الاعتماد المحفوظة إلى الخادم نيابةً عنك.`, + 'credential-env': (p) => + `يحتوي الموصل "${p.connector}" على بيانات اعتماد في "credentialEnv"، وهو حقل يجب أن يحمل اسم متغير بيئة ` + + `فقط ويراه كل من يستطيع قراءة الموصل. احفظ بيانات الاعتماد في بيانات اعتماد الموصلات واكتب اسم المتغير ` + + `في "credentialEnv" بدلًا منها.`, + 'stdio-auth': (p) => + `للموصل "${p.connector}" بيانات اعتماد مضبوطة، لكن خادم MCP الخاص به لا يتلقاها أبدًا: الخادم الذي يعمل ` + + `كعملية محلية لا يحصل على بيانات الاعتماد إلا عبر متغير البيئة المسمّى في "credentialEnv"، ولم يُسمَّ ` + + `أي متغير. اكتب في "credentialEnv" اسم المتغير الذي يقرؤه الخادم، أو احذف بيانات الاعتماد إذا كان ` + + `الخادم لا يحتاج إليها.`, + }), + fr: byArm({ + header: (p) => + `Le connecteur « ${p.connector} » contient un identifiant secret écrit directement dans son en-tête ` + + `« ${p.name} » : il est donc stocké dans les métadonnées du connecteur et non dans Identifiants des ` + + `connecteurs. Enregistrez-le dans Identifiants des connecteurs et supprimez l’en-tête : le connecteur ` + + `enverra lui-même l’identifiant enregistré.`, + env: (p) => + `Le connecteur « ${p.connector} » contient un identifiant secret écrit directement dans la variable ` + + `d’environnement « ${p.name} » de son serveur MCP : il est donc stocké dans les métadonnées du connecteur ` + + `et non dans Identifiants des connecteurs. Enregistrez-le dans Identifiants des connecteurs, indiquez le ` + + `nom de la variable dans « credentialEnv » et supprimez l’entrée : le connecteur transmettra lui-même ` + + `l’identifiant enregistré au serveur.`, + 'credential-env': (p) => + `Le connecteur « ${p.connector} » contient un identifiant secret dans « credentialEnv », qui ne doit ` + + `contenir que le nom d’une variable d’environnement et que voit toute personne pouvant lire le connecteur. ` + + `Enregistrez l’identifiant dans Identifiants des connecteurs et indiquez plutôt le nom de la variable dans ` + + `« credentialEnv ».`, + 'stdio-auth': (p) => + `Le connecteur « ${p.connector} » a un identifiant configuré, mais son serveur MCP ne le reçoit jamais : un ` + + `serveur exécuté comme processus local ne reçoit l’identifiant que par la variable d’environnement nommée ` + + `dans « credentialEnv », et aucune n’est nommée. Indiquez dans « credentialEnv » le nom de la variable que ` + + `lit le serveur, ou supprimez l’identifiant si le serveur n’en a pas besoin.`, + }), + 'pt-BR': byArm({ + header: (p) => + `O conector "${p.connector}" tem uma credencial escrita diretamente no cabeçalho "${p.name}", então a ` + + `credencial fica guardada nos metadados do conector e não em Credenciais de conectores. Guarde-a em ` + + `Credenciais de conectores e remova o cabeçalho: o conector envia a credencial guardada por você.`, + env: (p) => + `O conector "${p.connector}" tem uma credencial escrita diretamente na variável de ambiente "${p.name}" do ` + + `seu servidor MCP, então a credencial fica guardada nos metadados do conector e não em Credenciais de ` + + `conectores. Guarde-a em Credenciais de conectores, coloque o nome da variável em "credentialEnv" e remova ` + + `a entrada: o conector passa a credencial guardada ao servidor por você.`, + 'credential-env': (p) => + `O conector "${p.connector}" tem uma credencial em "credentialEnv", que deve conter apenas o nome de uma ` + + `variável de ambiente e é visível para qualquer pessoa que possa ler o conector. Guarde a credencial em ` + + `Credenciais de conectores e coloque em "credentialEnv" o nome da variável.`, + 'stdio-auth': (p) => + `O conector "${p.connector}" tem uma credencial configurada, mas o servidor MCP dele nunca a recebe: um ` + + `servidor executado como processo local só recebe a credencial pela variável de ambiente indicada em ` + + `"credentialEnv", e nenhuma foi indicada. Coloque em "credentialEnv" o nome da variável que o servidor lê, ` + + `ou remova a credencial se o servidor não precisar dela.`, + }), + ru: byArm({ + header: (p) => + `В заголовок «${p.name}» коннектора «${p.connector}» учётные данные записаны напрямую, поэтому они ` + + `хранятся в метаданных коннектора, а не в разделе «Учётные данные коннекторов». Сохраните их в разделе ` + + `«Учётные данные коннекторов» и удалите заголовок: коннектор сам будет отправлять сохранённые учётные данные.`, + env: (p) => + `В переменную окружения «${p.name}» MCP-сервера коннектора «${p.connector}» учётные данные записаны ` + + `напрямую, поэтому они хранятся в метаданных коннектора, а не в разделе «Учётные данные коннекторов». ` + + `Сохраните их в разделе «Учётные данные коннекторов», укажите имя переменной в «credentialEnv» и удалите ` + + `эту запись: коннектор сам передаст сохранённые учётные данные серверу.`, + 'credential-env': (p) => + `В поле «credentialEnv» коннектора «${p.connector}» записаны учётные данные, хотя это поле должно содержать ` + + `только имя переменной окружения и его видит каждый, кто может читать коннектор. Сохраните учётные данные ` + + `в разделе «Учётные данные коннекторов», а в «credentialEnv» укажите имя переменной.`, + 'stdio-auth': (p) => + `У коннектора «${p.connector}» заданы учётные данные, но его MCP-сервер их никогда не получает: сервер, ` + + `работающий как локальный процесс, получает учётные данные только через переменную окружения, указанную в ` + + `«credentialEnv», а она не указана. Укажите в «credentialEnv» имя переменной, которую читает сервер, или ` + + `удалите учётные данные, если они серверу не нужны.`, + }), + de: byArm({ + header: (p) => + `Der Connector „${p.connector}“ enthält Zugangsdaten, die direkt in seinen Header „${p.name}“ geschrieben ` + + `sind. Sie werden daher in den Metadaten des Connectors gespeichert statt unter Connector-Zugangsdaten. ` + + `Speichern Sie sie unter Connector-Zugangsdaten, und entfernen Sie den Header: Der Connector sendet die ` + + `gespeicherten Zugangsdaten dann selbst.`, + env: (p) => + `Der Connector „${p.connector}“ enthält Zugangsdaten, die direkt in die Umgebungsvariable „${p.name}“ ` + + `seines MCP-Servers geschrieben sind. Sie werden daher in den Metadaten des Connectors gespeichert statt ` + + `unter Connector-Zugangsdaten. Speichern Sie sie unter Connector-Zugangsdaten, tragen Sie den Namen der ` + + `Variable in „credentialEnv“ ein, und entfernen Sie den Eintrag: Der Connector übergibt die gespeicherten ` + + `Zugangsdaten dann selbst an den Server.`, + 'credential-env': (p) => + `Der Connector „${p.connector}“ enthält Zugangsdaten in „credentialEnv“. Dieses Feld darf nur den Namen ` + + `einer Umgebungsvariable enthalten und ist für jeden sichtbar, der den Connector lesen darf. Speichern Sie ` + + `die Zugangsdaten unter Connector-Zugangsdaten, und tragen Sie stattdessen den Namen der Variable in ` + + `„credentialEnv“ ein.`, + 'stdio-auth': (p) => + `Für den Connector „${p.connector}“ sind Zugangsdaten festgelegt, aber sein MCP-Server erhält sie nie: Ein ` + + `Server, der als lokaler Prozess läuft, erhält Zugangsdaten nur über die in „credentialEnv“ genannte ` + + `Umgebungsvariable, und es ist keine genannt. Tragen Sie in „credentialEnv“ den Namen der Variable ein, die ` + + `der Server liest, oder entfernen Sie die Zugangsdaten, wenn der Server keine braucht.`, + }), + ja: byArm({ + header: (p) => + `コネクタ「${p.connector}」のヘッダー「${p.name}」に認証情報が直接書き込まれているため、認証情報がコネクタ認証情報ではなく` + + `コネクタのメタデータに保存されています。コネクタ認証情報に保存し、このヘッダーを削除してください。` + + `保存した認証情報はコネクタが自動的に送信します。`, + env: (p) => + `コネクタ「${p.connector}」の MCP サーバーの環境変数「${p.name}」に認証情報が直接書き込まれているため、` + + `認証情報がコネクタ認証情報ではなくコネクタのメタデータに保存されています。コネクタ認証情報に保存し、` + + `「credentialEnv」に変数名を指定して、このエントリを削除してください。保存した認証情報はコネクタが自動的にサーバーへ渡します。`, + 'credential-env': (p) => + `コネクタ「${p.connector}」の「credentialEnv」に認証情報が書き込まれています。この項目には環境変数の名前だけを指定するもので、` + + `コネクタを読み取れる人なら誰でも見ることができます。認証情報はコネクタ認証情報に保存し、「credentialEnv」には変数名を指定してください。`, + 'stdio-auth': (p) => + `コネクタ「${p.connector}」には認証情報が設定されていますが、MCP サーバーには渡されません。ローカルプロセスとして動くサーバーは` + + `「credentialEnv」で指定された環境変数からしか認証情報を受け取れず、その指定がないためです。` + + `「credentialEnv」にサーバーが読み取る変数名を指定するか、サーバーに認証情報が不要なら削除してください。`, + }), + ko: byArm({ + header: (p) => + `커넥터 "${p.connector}"의 헤더 "${p.name}"에 자격 증명이 직접 작성되어 있어, 자격 증명이 커넥터 자격 증명이 아니라 ` + + `커넥터의 메타데이터에 저장되어 있습니다. 커넥터 자격 증명에 저장하고 이 헤더를 삭제하세요. 저장된 자격 증명은 ` + + `커넥터가 대신 보냅니다.`, + env: (p) => + `커넥터 "${p.connector}"의 MCP 서버 환경 변수 "${p.name}"에 자격 증명이 직접 작성되어 있어, 자격 증명이 커넥터 ` + + `자격 증명이 아니라 커넥터의 메타데이터에 저장되어 있습니다. 커넥터 자격 증명에 저장하고, "credentialEnv"에 변수 ` + + `이름을 적은 뒤 이 항목을 삭제하세요. 저장된 자격 증명은 커넥터가 대신 서버에 전달합니다.`, + 'credential-env': (p) => + `커넥터 "${p.connector}"의 "credentialEnv"에 자격 증명이 작성되어 있습니다. 이 항목에는 환경 변수의 이름만 적어야 ` + + `하며, 커넥터를 읽을 수 있는 사람은 누구나 볼 수 있습니다. 자격 증명은 커넥터 자격 증명에 저장하고, ` + + `"credentialEnv"에는 변수 이름을 적으세요.`, + 'stdio-auth': (p) => + `커넥터 "${p.connector}"에 자격 증명이 설정되어 있지만 MCP 서버는 이를 받지 못합니다. 로컬 프로세스로 실행되는 ` + + `서버는 "credentialEnv"에 지정된 환경 변수로만 자격 증명을 받는데, 지정된 변수가 없습니다. "credentialEnv"에 ` + + `서버가 읽는 변수 이름을 적거나, 서버에 자격 증명이 필요 없다면 삭제하세요.`, + }), + }, +}); diff --git a/packages/lint/src/validate-predicate-path-refs.ts b/packages/lint/src/validate-predicate-path-refs.ts index b1a534df145..bd2a70c367a 100644 --- a/packages/lint/src/validate-predicate-path-refs.ts +++ b/packages/lint/src/validate-predicate-path-refs.ts @@ -250,6 +250,7 @@ import { schemaIdOf, } from './predicate-rhs-position.js'; import { formViewSites } from './view-walk.js'; +import type { UserTextParams } from './finding-user-text.js'; export const PREDICATE_PATH_UNRESOLVED = 'predicate-path-unresolved'; export const PREDICATE_PATH_UNROOTED = 'predicate-path-unrooted'; @@ -279,6 +280,14 @@ export interface PredicatePathFinding { message: string; /** How to fix it. */ hint: string; + /** + * The names this finding's user sentence interpolates + * (`validate-predicate-path-refs.user-text.ts`): the view, the unquoted word + * and the operator. Set on the advisory bare-word arm of + * {@link PREDICATE_RHS_PATH_SHAPED} only, the one finding of this rule the + * publish door returns as advice; see `AuthoringFinding.userTextParams`. + */ + userTextParams?: UserTextParams; } /** Options for {@link validatePredicatePathRefs}. */ @@ -628,6 +637,7 @@ function checkPredicate( where: string, path: string, findings: PredicatePathFinding[], + view: string, ): void { const ast = parseCelToAst(source); // Not parseable through the canonical front end — `visibility-predicate-syntax` @@ -743,6 +753,8 @@ function checkPredicate( + `LEFT with a literal on the right (two paths cannot be compared here)` : `If you meant the text, quote it: \`${op} '${text}'\` (what it does today); if you meant the ` + `field, write \`${ROOT}.${text} == 'yes'\` with the path on the LEFT. Do NOT simply add the root in place`, + // The advisory arm's user sentence; the dotted arm refuses the write. + ...(dotted ? {} : { userTextParams: { view, word: text, op } }), }); } } @@ -754,6 +766,7 @@ function walkFields( base: string, findings: PredicatePathFinding[], depth: number, + view: string, ): void { if (!Array.isArray(entries) || depth > 12) return; for (let i = 0; i < entries.length; i++) { @@ -763,7 +776,7 @@ function walkFields( for (const key of PREDICATE_KEYS) { const source = predicateSource(entry[key]); if (source !== undefined && source.trim()) { - checkPredicate(source, scope, where, `${path}.${key}`, findings); + checkPredicate(source, scope, where, `${path}.${key}`, findings, view); break; // canonical-first: `visibleWhen` wins when both are present } } @@ -772,7 +785,7 @@ function walkFields( // than judged against the parent scope, which would report every sub-field. if (Array.isArray(entry.fields) && entry.fields.length > 0 && typeof entry.field === 'string') { const row = scope === undefined ? undefined : rowScopeOf(scope, entry.field); - walkFields(entry.fields, row, where, `${path}.fields`, findings, depth + 1); + walkFields(entry.fields, row, where, `${path}.fields`, findings, depth + 1, view); } } } @@ -848,11 +861,11 @@ export function validatePredicatePathRefs( for (const key of PREDICATE_KEYS) { const source = predicateSource(section[key]); if (source !== undefined && source.trim()) { - checkPredicate(source, root, where, `${sectionPath}.${key}`, findings); + checkPredicate(source, root, where, `${sectionPath}.${key}`, findings, viewName); break; } } - walkFields(section.fields, root, where, `${sectionPath}.fields`, findings, 0); + walkFields(section.fields, root, where, `${sectionPath}.fields`, findings, 0, viewName); } } } diff --git a/packages/lint/src/validate-predicate-path-refs.user-text.ts b/packages/lint/src/validate-predicate-path-refs.user-text.ts new file mode 100644 index 00000000000..bbccea9873a --- /dev/null +++ b/packages/lint/src/validate-predicate-path-refs.user-text.ts @@ -0,0 +1,91 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `validate-predicate-path-refs.ts`'s one advisory + * finding: the bare-word arm of `predicate-rhs-path-shaped`, in every platform + * locale (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The finding + * mechanism and the locale ladder are `finding-user-text.ts`'s; this file is + * the rule's own half of it, kept beside the rule so its wording and its + * translations change together. The dotted arm of the same id refuses the + * write (`error`) and has no sentence here. + * + * Who reads it: the person who saved a schema-bound form view in Studio, in + * their own language, once the save door composes + * `RuntimeAuthoringIssueSchema.userMessage` from it. + * + * ⛔ Which reading the author meant is not decided (the rule's module note, + * §One position, one prescription), so the sentence names BOTH readings and + * the supported spelling of each: the quoted word (`== 'active'`, what the + * form does today) or the field on the LEFT of a comparison with a quoted + * value (`data.active == 'yes'`). It never tells the user to put the root in + * front of the word where it stands: `== data.active` is a path on the right, + * the arm this same rule refuses. + * + * Params, set at the push site in `validate-predicate-path-refs.ts`: `view` + * (the view's name), `word` (the unquoted word) and `op` (`==` or `!=`). + * + * `finding-user-text.connector-permission-form.test.ts` renders it from the rule's + * real findings in every platform locale and pins both readings in each. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { PREDICATE_RHS_PATH_SHAPED } from './validate-predicate-path-refs.js'; + +export const PREDICATE_PATH_REFS_USER_TEXT: UserTextCatalog = Object.freeze({ + [PREDICATE_RHS_PATH_SHAPED]: { + en: (p) => + `A visibility condition in form "${p.view}" compares with the unquoted word ${p.word} after ${p.op}. Today it ` + + `is read as the text "${p.word}", but that spelling is not supported and will stop working. If you meant the ` + + `text, put it in quotes: ${p.op} '${p.word}'. If you meant a field of the record, put the field on the left and ` + + `compare it with a quoted value, for example data.${p.word} == 'yes'.`, + 'zh-Hans': (p) => + `表单“${p.view}”中的显示条件在 ${p.op} 后面与未加引号的单词 ${p.word} 比较。目前它被当作文本“${p.word}”读取,` + + `但这种写法不受支持,将来会失效。如果指的是这段文本,请加上引号:${p.op} '${p.word}'。如果指的是记录中的字段,` + + `请把字段放在左边,并与带引号的值比较,例如 data.${p.word} == 'yes'。`, + 'zh-Hant': (p) => + `表單「${p.view}」中的顯示條件在 ${p.op} 後面與未加引號的單字 ${p.word} 比較。目前它被當作文字「${p.word}」讀取,` + + `但這種寫法不受支援,將來會失效。如果指的是這段文字,請加上引號:${p.op} '${p.word}'。如果指的是記錄中的欄位,` + + `請把欄位放在左邊,並與加上引號的值比較,例如 data.${p.word} == 'yes'。`, + es: (p) => + `Una condición de visibilidad del formulario "${p.view}" compara con la palabra sin comillas ${p.word} después ` + + `de ${p.op}. Hoy se lee como el texto "${p.word}", pero esa escritura no está admitida y dejará de funcionar. ` + + `Si se refería al texto, póngalo entre comillas: ${p.op} '${p.word}'. Si se refería a un campo del registro, ` + + `ponga el campo a la izquierda y compárelo con un valor entre comillas, por ejemplo data.${p.word} == 'yes'.`, + ar: (p) => + `يقارن شرط ظهور في النموذج "${p.view}" بالكلمة غير المحاطة بعلامتي اقتباس ${p.word} بعد ${p.op}. تُقرأ ` + + `اليوم على أنها النص "${p.word}"، لكن هذه الكتابة غير مدعومة وستتوقف عن العمل. إذا كنت تقصد النص، فضعه بين ` + + `علامتي اقتباس: ${p.op} '${p.word}'. وإذا كنت تقصد حقلًا من السجل، فضع الحقل على اليسار وقارنه بقيمة بين ` + + `علامتي اقتباس، مثل data.${p.word} == 'yes'.`, + fr: (p) => + `Une condition de visibilité du formulaire « ${p.view} » compare avec le mot sans guillemets ${p.word} après ` + + `${p.op}. Aujourd’hui, il est lu comme le texte « ${p.word} », mais cette écriture n’est pas prise en charge et ` + + `cessera de fonctionner. Si vous visiez le texte, mettez-le entre guillemets : ${p.op} '${p.word}'. Si vous ` + + `visiez un champ de l’enregistrement, placez le champ à gauche et comparez-le à une valeur entre guillemets, ` + + `par exemple data.${p.word} == 'yes'.`, + 'pt-BR': (p) => + `Uma condição de visibilidade do formulário "${p.view}" compara com a palavra sem aspas ${p.word} depois de ` + + `${p.op}. Hoje ela é lida como o texto "${p.word}", mas essa escrita não é suportada e vai parar de funcionar. ` + + `Se você quis dizer o texto, coloque-o entre aspas: ${p.op} '${p.word}'. Se quis dizer um campo do registro, ` + + `coloque o campo à esquerda e compare-o com um valor entre aspas, por exemplo data.${p.word} == 'yes'.`, + ru: (p) => + `Условие видимости в форме «${p.view}» сравнивает со словом без кавычек ${p.word} после ${p.op}. Сейчас оно ` + + `читается как текст «${p.word}», но такая запись не поддерживается и перестанет работать. Если имелся в виду ` + + `текст, возьмите его в кавычки: ${p.op} '${p.word}'. Если имелось в виду поле записи, поставьте поле слева и ` + + `сравните его со значением в кавычках, например data.${p.word} == 'yes'.`, + de: (p) => + `Eine Sichtbarkeitsbedingung im Formular „${p.view}“ vergleicht nach ${p.op} mit dem Wort ${p.word} ohne ` + + `Anführungszeichen. Heute wird es als der Text „${p.word}“ gelesen, aber diese Schreibweise wird nicht ` + + `unterstützt und wird nicht mehr funktionieren. Wenn Sie den Text meinen, setzen Sie ihn in ` + + `Anführungszeichen: ${p.op} '${p.word}'. Wenn Sie ein Feld des Datensatzes meinen, setzen Sie das Feld nach ` + + `links und vergleichen Sie es mit einem Wert in Anführungszeichen, zum Beispiel data.${p.word} == 'yes'.`, + ja: (p) => + `フォーム「${p.view}」の表示条件が、${p.op} の後ろで引用符のない単語 ${p.word} と比較しています。現在はテキスト「${p.word}」として` + + `読み取られますが、この書き方はサポートされておらず、今後動作しなくなります。テキストのつもりなら引用符で囲んでください: ` + + `${p.op} '${p.word}'。レコードの項目のつもりなら、項目を左側に置き、引用符で囲んだ値と比較してください。例: data.${p.word} == 'yes'。`, + ko: (p) => + `폼 "${p.view}"의 표시 조건이 ${p.op} 뒤에서 따옴표 없는 단어 ${p.word}와(과) 비교합니다. 지금은 텍스트 ` + + `"${p.word}"(으)로 읽히지만, 이 표기는 지원되지 않으며 앞으로 동작하지 않게 됩니다. 텍스트를 의도했다면 따옴표로 ` + + `감싸세요: ${p.op} '${p.word}'. 레코드의 필드를 의도했다면 필드를 왼쪽에 두고 따옴표로 감싼 값과 비교하세요. ` + + `예: data.${p.word} == 'yes'.`, + }, +}); diff --git a/packages/lint/src/validate-retired-permission-residue.ts b/packages/lint/src/validate-retired-permission-residue.ts index 1905f6332fd..8b3deacbdac 100644 --- a/packages/lint/src/validate-retired-permission-residue.ts +++ b/packages/lint/src/validate-retired-permission-residue.ts @@ -62,6 +62,7 @@ import { ObjectPermissionSchema } from '@objectstack/spec/security'; import { recordsOf } from './object-graph.js'; +import type { UserTextParams } from './finding-user-text.js'; type AnyRec = Record; @@ -73,6 +74,12 @@ export interface RetiredPermissionResidueFinding { hint: string; rule: string; severity: 'warning'; + /** + * The names this finding's user sentence interpolates + * (`validate-retired-permission-residue.user-text.ts`): the permission set, + * the object and the retired key. See `AuthoringFinding.userTextParams`. + */ + userTextParams?: UserTextParams; } export const PERMISSION_RETIRED_LIFECYCLE_RESIDUE = 'permission-retired-lifecycle-residue'; @@ -169,6 +176,7 @@ export function validateRetiredPermissionResidue(stack: AnyRec): RetiredPermissi `sets \`${key}: ${JSON.stringify(residue)}\`, the retired default of a key removed in ` + '@objectstack/spec 17, which the parse strips in silence, so this line grants nothing', hint: retiredKeyRemedy(prescription), + userTextParams: { permissionSet: setName, object: objectName, key }, }); } } diff --git a/packages/lint/src/validate-retired-permission-residue.user-text.ts b/packages/lint/src/validate-retired-permission-residue.user-text.ts new file mode 100644 index 00000000000..04c07ffc8f9 --- /dev/null +++ b/packages/lint/src/validate-retired-permission-residue.user-text.ts @@ -0,0 +1,73 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The user-facing sentence of `validate-retired-permission-residue.ts`'s + * advisory finding (`permission-retired-lifecycle-residue`), in every platform + * locale (`PLATFORM_LOCALE_TAGS`, `@objectstack/spec/system`). The finding + * mechanism and the locale ladder are `finding-user-text.ts`'s; this file is + * the rule's own half of it, kept beside the rule so its wording and its + * translations change together. + * + * Who reads it: the person who saved a permission set in Studio, in their own + * language, once the save door composes `RuntimeAuthoringIssueSchema.userMessage` + * from it. It says the line grants nothing, to delete it, and where restoring + * and purging deleted records is granted now: the recycle bin, the console's + * own name for it (`recycleBin.title`, `ui/packages/i18n`). + * + * Params, set at the push site in `validate-retired-permission-residue.ts`: + * `permissionSet`, `object` and `key` (`allowRestore` or `allowPurge`, written + * as the author wrote it; the residue value is always `false`). + * + * `finding-user-text.connector-permission-form.test.ts` renders it from the rule's + * real findings in every platform locale. + */ + +import type { UserTextCatalog } from './finding-user-text.js'; +import { PERMISSION_RETIRED_LIFECYCLE_RESIDUE } from './validate-retired-permission-residue.js'; + +export const RETIRED_PERMISSION_RESIDUE_USER_TEXT: UserTextCatalog = Object.freeze({ + [PERMISSION_RETIRED_LIFECYCLE_RESIDUE]: { + en: (p) => + `Permission set "${p.permissionSet}" still sets "${p.key}: false" for object "${p.object}". That setting was ` + + `removed and is now ignored, so this line grants nothing. Delete it: who can restore or purge deleted records ` + + `is now granted through the recycle bin.`, + 'zh-Hans': (p) => + `权限集“${p.permissionSet}”仍为对象“${p.object}”设置了“${p.key}: false”。该设置已被移除,现在会被忽略,因此这一行不授予任何权限。` + + `请删除它:谁可以恢复或彻底删除已删除的记录,现在通过回收站授予。`, + 'zh-Hant': (p) => + `權限集「${p.permissionSet}」仍為物件「${p.object}」設定了「${p.key}: false」。該設定已被移除,現在會被忽略,因此這一行不授予任何權限。` + + `請刪除它:誰可以還原或永久刪除已刪除的記錄,現在透過回收站授予。`, + es: (p) => + `El conjunto de permisos "${p.permissionSet}" todavía establece "${p.key}: false" para el objeto ` + + `"${p.object}". Esa opción se eliminó y ahora se ignora, así que esta línea no concede nada. Elimínela: ` + + `quién puede restaurar o purgar registros eliminados se concede ahora mediante la papelera.`, + ar: (p) => + `لا تزال مجموعة الأذونات "${p.permissionSet}" تضبط "${p.key}: false" للكائن "${p.object}". أُزيل هذا ` + + `الإعداد ويُتجاهل الآن، لذا لا يمنح هذا السطر أي شيء. احذفه: من يمكنه استعادة السجلات المحذوفة أو حذفها ` + + `نهائيًا يُمنح الآن عبر سلة المحذوفات.`, + fr: (p) => + `L’ensemble d’autorisations « ${p.permissionSet} » définit encore « ${p.key}: false » pour l’objet ` + + `« ${p.object} ». Ce paramètre a été supprimé et il est désormais ignoré : cette ligne n’accorde donc rien. ` + + `Supprimez-la : le droit de restaurer ou de purger les enregistrements supprimés s’accorde désormais via la corbeille.`, + 'pt-BR': (p) => + `O conjunto de permissões "${p.permissionSet}" ainda define "${p.key}: false" para o objeto "${p.object}". ` + + `Essa configuração foi removida e agora é ignorada, então esta linha não concede nada. Exclua-a: quem pode ` + + `restaurar ou expurgar registros excluídos agora é concedido pela lixeira.`, + ru: (p) => + `Набор разрешений «${p.permissionSet}» всё ещё задаёт «${p.key}: false» для объекта «${p.object}». Эта ` + + `настройка удалена и теперь игнорируется, поэтому строка ничего не даёт. Удалите её: право восстанавливать ` + + `или окончательно удалять удалённые записи теперь выдаётся через корзину.`, + de: (p) => + `Der Berechtigungssatz „${p.permissionSet}“ setzt für das Objekt „${p.object}“ noch „${p.key}: false“. ` + + `Diese Einstellung wurde entfernt und wird jetzt ignoriert, daher gewährt diese Zeile nichts. Löschen Sie ` + + `sie: Wer gelöschte Datensätze wiederherstellen oder endgültig löschen darf, wird jetzt über den Papierkorb gewährt.`, + ja: (p) => + `権限セット「${p.permissionSet}」は、オブジェクト「${p.object}」に対してまだ「${p.key}: false」を設定しています。` + + `この設定は削除され、現在は無視されるため、この行は何も付与しません。この行を削除してください。` + + `削除済みレコードを復元または完全に削除できるユーザーは、現在はごみ箱で付与します。`, + ko: (p) => + `권한 집합 "${p.permissionSet}"이(가) 개체 "${p.object}"에 대해 아직 "${p.key}: false"를 설정하고 있습니다. ` + + `이 설정은 제거되어 이제 무시되므로, 이 줄은 아무 권한도 부여하지 않습니다. 이 줄을 삭제하세요. 삭제된 ` + + `레코드를 복원하거나 영구 삭제할 수 있는 사람은 이제 휴지통을 통해 부여됩니다.`, + }, +});