Skip to content

Commit ae9c134

Browse files
fix(storage): the upload-link page speaks the request's language, and its refusals read as page copy (#32891)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DKMkvWZdqZ8XFcrT6arhCKt)_ Refs #32712 (item a) Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:代理用 `create_upload_link` 发给用户的上传页面,现在按请求的语言显示(浏览器 `Accept-Language`,没有时用工作区默认语言,再没有就是英文),平台语言表上的 11 种语言都有译文;上传后页面显示的拒绝原因(记录被审批锁定、字段只读、文件太大等)也改成页面自己的、同一语言的句子,由服务器放在 `error.userMessage` 里返回。 - 为什么改:中文部署里用户打开链接看到的是整页英文;审批锁定的拒绝还带着 `RECORD_LOCKED:` 前缀和记录标题,只读字段的拒绝直接写出对象和字段的 API 名,和页面「不点名记录、字段」的设计(#30892)相冲突。 - 风险与回滚:只动上传链接这一对 GET/PUT 门和它的页面;`error.code`、成功响应体不变,`error.message` 仍是诊断用英文(只去掉生产者自己的代码前缀,与 `/api/v1/data` 一致);工作区默认语言经平台唯一的 `resolveLocalizationContext` 读取,读不到就用英文。回滚即 revert 本 PR。 - 先看:`packages/services/service-storage/src/upload-link-copy.ts`(译文表与「拒绝码到页面句子」的映射)、`storage-routes.ts`(`uploadLinkCopyFor` 的语言顺序与 `relayUploadLinkRefusal`)、`upload-link-page.ts`(页面与脚本读 `userMessage`)。 - 两分钟验证:`pnpm --filter @objectstack/service-storage exec vitest run src/record-file-access.integration.test.ts src/upload-link-copy.test.ts -t "#32712"`,预期 13 passed。 - 需要你做的:无,席位落地。 ## What changes One package, `@objectstack/service-storage`. No new export, error code, route, query parameter or wire field: `userMessage` is the existing optional member of the error envelope (`ApiErrorSchema.userMessage`). - **The page's language (`storage-routes.ts`, `storage-service-plugin.ts`).** Both upload-link doors pick the language once per request: the request's `Accept-Language` (read with the platform's `preferredLocaleFromHeader`), else the workspace default for the signed-in caller, else English. The workspace default is the `localization` settings for the caller's organization and user, read through `resolveLocalizationContext`, the resolver every authenticated door's execution context uses; `composeStorageRoutes` binds it, so the plugin's mount and the host door (`mountStorageRoutes`) both get it. A default that cannot be read is no default. The doors still read no query parameter, so `?locale` is not a source here. - **The sentences (`upload-link-copy.ts`, new).** Every sentence the page shows, for each language on the platform locale table (`PLATFORM_LOCALES`), keyed and read like Setup's storage test answer (`storage-test-copy.ts`). The two now share one reader, `copy-locale.ts` (moved out of `storage-test-copy.ts`; `storageTestCopyLocaleOf` keeps its name and answers). The expiry is written with `Intl.DateTimeFormat` in the page's language, still in UTC and saying so. - **The page (`upload-link-page.ts`).** The page's `lang` and `dir` attributes follow the language (`ar` is right-to-left). The script's status lines arrive as a JSON literal escaped for an inline script. After an upload it shows `error.userMessage`, or the page's own "the upload failed" when the answer carries none; it no longer shows `error.message`. - **The refusals (`relayUploadLinkRefusal` and the PUT door's own refusals).** Each refusal now carries `userMessage`: a text the producer itself marked for the user (`declaredUserMessage`), verbatim; else the page's sentence for the code (`AUTH_REQUIRED`, `RESOURCE_NOT_FOUND`, `PAYLOAD_TOO_LARGE`, `ERR_FILE_CONSTRAINT`, `PERMISSION_DENIED`, `FIELD_NOT_ACCESSIBLE`, `RECORD_LOCKED`, `RECORD_NOT_FOUND`, any `503`); else the producer's text behind a localized "the upload was refused" lead-in. None of the page's sentences names a record, object or field. `error.message` keeps the producer's wording with its own code prefix stripped by `withoutDeclaredCodePrefix`, the `/api/v1/data` door's rule, so the record lock's `RECORD_LOCKED: …` no longer leads it. - **Route ledger notes** for the two doors say so. ## Why The card (#32712, triage 6822323217): a zh-CN deployment hands out an English-only page; ruling C on #32440 (program #32654) has text addressed to a person composed by its producer in the request's language. Note 6830733775 (contract review of PR #32779, N1) adds the refusals the page shows since #32734: the lock refusal reached the page with its code prefix and the record's title, and the read-only refusal named object and field by API name. ## Acceptance notes - Out of scope, untouched: naming the record and the field on the page (the #30892 privacy choice; needs a maintainer ruling). This PR removes no ruling: the page's own sentences name nothing, as its header always said. The refusals that used to carry a record title or `object.field` were the exception, and now read as page copy. - The fallback limb shows the producer's text verbatim behind a localized lead-in, so a refusal the page has no sentence for (an app's validation rule, `VALIDATION_FAILED`) keeps telling the person why, in the producer's language. A producer that marks its own `userMessage` is shown as written. - The `GET` door's `401 AUTH_REQUIRED` is still the JSON envelope a browser shows raw (it now carries a localized `userMessage` too). Turning it into a page is not this card. - `storage-test-copy.ts` changes only by delegating to the shared reader; its exports and answers are the same (`storage-test-locale.test.ts` green). - Step 0 on `main` `c04aa295`: the page took no request input, and neither upload-link door read `Accept-Language`, `?locale` or a settings value (`grep -ci "accept-language|locale"` over `storage-routes.ts` and `upload-link-page.ts`: 0 and 0). Rendered, the picker page was `lang="en"`, "Upload a file … It stops working at Thu, 12 Nov 2026 22:00:00 GMT." whatever the request or the workspace said. ## Tests - `record-file-access.integration.test.ts`, new `#32712` block, through the real routes on the real plugin (sqlite `:memory:`), with a `settings` service answering the workspace's `localization.locale` and announcing changes: the picker page in zh-CN (lang, every sentence, the expiry, no record/object/field/user named); workspace default when the request names no language, the request's language winning over it, English with neither; the unusable page and the PUT's unusable and sign-in refusals; the record lock and the `readonlyWhen` refusal (the page's sentence, no `RECORD_LOCKED` prefix, nothing named); the upload limit in the workspace default with the link still usable; the page script's status lines in zh-CN showing the door's `userMessage`. - Existing pins updated: the lock refusal's `message` no longer starts with `RECORD_LOCKED`; the page shows `userMessage`, and an answer with none shows "The upload failed." rather than the diagnostic. - `upload-link-copy.test.ts`, new: every platform locale has every sentence; no non-English entry repeats an English sentence; English unchanged; locale reading (aliases, regions, fallback); each code's sentence; the expiry format. ## Verification All readings on head `4f6a91d1d8` (branch tip after one `git merge origin/main`; the merge brought two `ui/` commits and nothing under `packages/services/`), after a whole-tree `turbo run build`. <details><summary>Tests</summary> - `pnpm --filter @objectstack/service-storage test`: 79 files, 1484 tests passed (taken on `6324ca39`+tests, before the `main` merge, which touched no storage path). - `pnpm --filter @objectstack/service-storage typecheck` (tsc, scripts tsconfig, `check:test-typecheck`): exit 0. - Focused: `vitest run src/record-file-access.integration.test.ts src/upload-link-copy.test.ts -t "#32712"`: 13 passed. </details> <details><summary>Ablations (each through `scripts/ablation-replace.mjs`: anchor hit 1 to 0, blob restored equal to HEAD, `git diff HEAD` empty)</summary> The suite imports `src/` directly, so no rebuild sits between mutation and run. - A1, `relayUploadLinkRefusal` keeps the producer's prefix (`withoutDeclaredCodePrefix(e.message, err)` replaced by `e.message`): 2 red, the lock refusal's `message` starts `RECORD_LOCKED` (the #32734 pin and the new #32712 pin). - A2, the relay sends the producer's text as `userMessage` (`uploadLinkRefusalText(…)` replaced by `message`): 4 red (unusable/sign-in, lock, read-only, upload limit). - A3, the workspace default wins over the request's language: 6 red. - A4, the page script shows `error.message` instead of `error.userMessage`: 2 red. </details> <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --ran`: "75 derived famil(ies) accounted for — 75 run, 0 NOT-MEASURED". Every family exited 0. Two (`check:dual-build-cjs-loads`, `check:i18n`) exited 3 on a first pass before the whole-tree build, and 0 after it on this head. - `pnpm lint` (`eslint . --no-inline-config`): exit 0. - The run record is in the project files as `server-seat5/32712/gates-ran-4f6a91d1.txt`. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cy5JYAeZEX9ESoQ1Uc)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cy5JYAeZEX9ESoQ1Uc <!-- signed: domain:server#5 · os-elon-musk · session_016WV4cy5JYAeZEX9ESoQ1Uc --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 25ee507 commit ae9c134

10 files changed

Lines changed: 1001 additions & 97 deletions
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/service-storage': patch
3+
---
4+
5+
fix(storage): the upload-link page speaks the request's language, and its refusals read as page copy
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The page a `create_upload_link` link opens was English in every deployment. It is now written in the request's language: the browser's `Accept-Language`, else the workspace default (the `localization` settings), else English. Every language on the platform locale table is served, with `<html lang>`, the writing direction and the link's expiry (still UTC, and saying so) in that language.
11+
12+
The refusals the page shows after an upload are page copy too. The `PUT /api/v1/storage/upload-links/:token` door now answers each refusal with `error.userMessage`, written in the page's language, and the page shows that text (or its own "the upload failed" when an answer carries none). The sentence names no record, object or field, like the rest of the page: the record-lock refusal no longer reaches the person as `RECORD_LOCKED: …` with the record's title, and the read-only refusal no longer names the object and field by API name. `error.code` and the success body are unchanged. `error.message` keeps its diagnostic wording, with a producer's own code prefix stripped the way the `/api/v1/data` door strips it.
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The language this package writes a sentence in, read from a caller's
5+
* locale code. One reader for every table of product sentences the package
6+
* serves: Setup → Storage → 测试连接 (`storage-test-copy.ts`) and [#32712] the
7+
* upload-link page (`upload-link-copy.ts`), so the two cannot disagree about
8+
* which language a code names.
9+
*
10+
* The keys are the platform locale table's languages
11+
* (`@objectstack/spec/system` `PLATFORM_LOCALES`), the first four under the
12+
* older codes this package served them by (`zh-CN`, `ja-JP`, `es-ES`). The
13+
* caller's code is read through the table's own reader, `platformLocaleTagOf`,
14+
* so a stored alias (`zh-TW`, `pt`, `en-US`) and a table tag (`zh-Hans`, `ja`)
15+
* both find their key. A code the table does not name is shortened one subtag
16+
* at a time (RFC 4647 lookup: `fr-CA` → `fr`, `zh-Hant-TW` → `zh-Hant`);
17+
* nothing left ⇒ `undefined`, which every table answers in English.
18+
*/
19+
20+
import { platformLocaleTagOf, type PlatformLocaleTag } from '@objectstack/spec/system';
21+
22+
/** A table's keys: the platform locale table's languages, the first four under their older codes. */
23+
export type CopyLocale =
24+
'en' | 'zh-CN' | 'zh-Hant' | 'es-ES' | 'ar' | 'fr' | 'pt-BR' | 'ru' | 'de' | 'ja-JP' | 'ko';
25+
26+
/** Each platform locale table tag → the key that serves it. */
27+
const KEY_BY_TABLE_TAG: Record<PlatformLocaleTag, CopyLocale> = {
28+
en: 'en',
29+
'zh-Hans': 'zh-CN',
30+
'zh-Hant': 'zh-Hant',
31+
es: 'es-ES',
32+
ar: 'ar',
33+
fr: 'fr',
34+
'pt-BR': 'pt-BR',
35+
ru: 'ru',
36+
de: 'de',
37+
ja: 'ja-JP',
38+
ko: 'ko',
39+
};
40+
41+
/** The key that serves a caller's code, or `undefined` (⇒ English). */
42+
export function copyLocaleOf(locale: string | undefined): CopyLocale | undefined {
43+
if (!locale) return undefined;
44+
const subtags = locale.split('-');
45+
for (let n = subtags.length; n > 0; n -= 1) {
46+
const tag = platformLocaleTagOf(subtags.slice(0, n).join('-'));
47+
if (tag) return KEY_BY_TABLE_TAG[tag];
48+
}
49+
return undefined;
50+
}

‎packages/services/service-storage/src/record-file-access.integration.test.ts‎

Lines changed: 182 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@
3131
* whose `getRecordLock` answers for the claims in `locked`, and a
3232
* `beforeUpdate` hook refusing an edit of one as the record-lock hook does
3333
* (`RECORD_LOCKED`, its status declared as `statusCode: 409`).
34+
*
35+
* #32712 — the page, and the refusals it shows, in the request's language:
36+
* `Accept-Language`, else the workspace default, else English. The workspace
37+
* default is the fixture's `settings` service, answering the `localization`
38+
* namespace's `locale` from `workspaceLocale` and announcing a change to it
39+
* as the real service does (`subscribe`), so the one resolver's cache drops
40+
* the earlier answer.
3441
*/
3542

3643
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest';
@@ -48,6 +55,7 @@ import type { FileAttachmentService } from './file-attachment-service.js';
4855
import { installDefaultOrganization, DEFAULT_ORGANIZATION_ID } from './default-organization.testkit.js';
4956
import { UPLOAD_LINK_TTL_SECONDS } from './record-file-access.js';
5057
import { UPLOAD_LINK_UNUSABLE_MESSAGE } from './upload-link-wire.js';
58+
import { UPLOAD_LINK_COPY } from './upload-link-copy.js';
5159

5260
const BASE = '/api/v1/storage';
5361
const SYS = { isSystem: true };
@@ -81,6 +89,13 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o
8189
const ids: Record<string, string> = {};
8290
/** [#32734] The claims a pending approval locks. */
8391
const locked = new Set<string>();
92+
/** [#32712] The workspace's default locale, as the `localization` settings answer it; none unless a case sets one. */
93+
let workspaceLocale: string | undefined;
94+
const localizationChanged: Array<() => void> = [];
95+
const setWorkspaceLocale = (locale: string | undefined) => {
96+
workspaceLocale = locale;
97+
for (const fn of localizationChanged) fn();
98+
};
8499

85100
beforeAll(async () => {
86101
rootDir = join(tmpdir(), `os-30892-${Date.now()}-${Math.random().toString(36).slice(2)}`);
@@ -145,6 +160,18 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o
145160
},
146161
});
147162

163+
// [#32712] The settings service's `localization` namespace, as the one
164+
// localization resolver reads it: a grouped read, and a change announced.
165+
ctx.registerService('settings', {
166+
get: async (ns: string, key: string) =>
167+
ns === 'localization' && key === 'locale' && workspaceLocale ? { value: workspaceLocale } : undefined,
168+
getMany: async (ns: string) =>
169+
ns === 'localization' && workspaceLocale ? { locale: { value: workspaceLocale } } : {},
170+
subscribe: (ns: string, fn: () => void) => {
171+
if (ns === 'localization') localizationChanged.push(fn);
172+
},
173+
});
174+
148175
// [#32734] The approvals service's record-anchored lock answer: for a
149176
// caller who reads the record, whether a pending approval locks it.
150177
ctx.registerService('approvals', {
@@ -667,22 +694,173 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o
667694
expect(put._status, JSON.stringify(put._json)).toBe(409);
668695
expect(put._json.error).toMatchObject({ code: 'RECORD_LOCKED' });
669696
expect(put._json.error.message).toContain('locked while an approval is in progress');
697+
// [#32712] The producer's code prefix is off the text; `code` carries the token.
698+
expect(put._json.error.message).not.toMatch(/^RECORD_LOCKED/);
670699
expect((await claim(id)).policy ?? null).toBeNull();
671700
expect(await filesNamed('locked-claim.pdf')).toEqual([]);
672701
} finally {
673702
locked.delete(id);
674703
}
675704
});
676705

677-
it('the page says attached only for an answer naming the stored file; a refusal shows its reason', async () => {
706+
it('the page says attached only for an answer naming the stored file; a refusal shows the text written for its user', async () => {
678707
const grant = await files.createUploadLinkAs('claim', ids.claimB, { field: 'policy' }, OWNER as never);
679708
const html = String((await openLink(tokenOf(grant.path)))._sent);
680709
expect(await pageSays(html, { ok: true, body: { success: true, data: { fileId: 'f1', size: 3, field: 'policy' } } }))
681710
.toBe('Done. The file was attached; you can close this page.');
682711
expect(await pageSays(html, { ok: true, body: { success: true, data: {} } })).toBe('The upload failed.');
683-
const reason = 'Nothing was attached: claim.invoices is read-only on this record in its current state, so it cannot take a file.';
684-
expect(await pageSays(html, { ok: false, body: { success: false, error: { code: 'FIELD_NOT_ACCESSIBLE', message: reason } } }))
685-
.toBe(reason);
712+
const reason = 'Nothing was attached: the field this link was made for is read-only on this record, so it cannot take a file.';
713+
const diagnostic = 'Nothing was attached: claim.invoices is read-only on this record in its current state, so it cannot take a file.';
714+
expect(await pageSays(html, {
715+
ok: false,
716+
body: { success: false, error: { code: 'FIELD_NOT_ACCESSIBLE', message: diagnostic, userMessage: reason } },
717+
})).toBe(reason);
718+
// [#32712] An answer carrying no text for its user shows the page's own sentence, never the diagnostic.
719+
expect(await pageSays(html, { ok: false, body: { success: false, error: { code: 'INTERNAL', message: 'Upload failed' } } }))
720+
.toBe('The upload failed.');
721+
});
722+
});
723+
724+
describe('#32712 — the page and its refusals in the request\'s language', () => {
725+
const zh = UPLOAD_LINK_COPY['zh-CN'];
726+
const en = UPLOAD_LINK_COPY.en;
727+
const ZH = { 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8' };
728+
const openLinkIn = (token: string, headers: Record<string, string>, user: string | null = OWNER.userId) =>
729+
call('GET', `${BASE}/upload-links/:token`, { params: { token }, headers: { ...headers, ...sessionOf(user) } });
730+
const draftClaim = async (name: string) =>
731+
(await engine.insert('claim', { name, owner: OWNER.userId, status: 'draft', organization_id: ORG }, { context: SYS } as never)).id as string;
732+
733+
afterEach(() => setWorkspaceLocale(undefined));
734+
735+
/** The page's visible copy: no record, object, field or user named, whatever the language. */
736+
const expectNamesNothing = (text: string, recordId: string) => {
737+
for (const named of [recordId, 'claim', 'policy', 'invoices', OWNER.userId]) expect(text).not.toContain(named);
738+
};
739+
740+
it('serves the picker page in the request\'s language: lang, every sentence, the expiry', async () => {
741+
const grant = await files.createUploadLinkAs('claim', ids.claimB, { field: 'policy' }, OWNER as never);
742+
const page = await openLinkIn(tokenOf(grant.path), ZH);
743+
expect(page._status).toBe(200);
744+
const html = String(page._sent);
745+
expect(html).toContain('<html lang="zh-CN" dir="ltr">');
746+
expect(html).toContain(`<title>${zh.pageTitle}</title>`);
747+
for (const sentence of [zh.wanted('field'), zh.once, zh.fileLabel, zh.send]) expect(html).toContain(sentence);
748+
// The expiry, written the Chinese way and named as UTC.
749+
expect(html).toMatch(/链接将于 \d{4}年\d{1,2}月\d{1,2}日 UTC \d{2}:\d{2} 失效。/);
750+
for (const english of ['Upload a file', 'A file was asked for', 'This link works once', 'It stops working']) {
751+
expect(html).not.toContain(english);
752+
}
753+
expectNamesNothing(html, ids.claimB);
754+
});
755+
756+
it('with no language of its own, the request gets the workspace default; a language it names wins over the default', async () => {
757+
setWorkspaceLocale('zh-CN');
758+
const grant = await files.createUploadLinkAs('claim', ids.claimB, { attachments: true }, OWNER as never);
759+
const token = tokenOf(grant.path);
760+
const byDefault = String((await openLinkIn(token, {}))._sent);
761+
expect(byDefault).toContain('<html lang="zh-CN" dir="ltr">');
762+
expect(byDefault).toContain(zh.wanted('attachments'));
763+
const asked = String((await openLinkIn(token, { 'accept-language': 'en-US,en;q=0.9' }))._sent);
764+
expect(asked).toContain('<html lang="en" dir="ltr">');
765+
expect(asked).toContain(en.wanted('attachments'));
766+
// No default and no language asked: English, as every page was before.
767+
setWorkspaceLocale(undefined);
768+
expect(String((await openLinkIn(token, {}))._sent)).toContain('<html lang="en" dir="ltr">');
769+
});
770+
771+
it('the unusable-link page, and the PUT\'s unusable and sign-in refusals, speak the request\'s language', async () => {
772+
const page = await openLinkIn('not-a-token', ZH);
773+
expect(page._status).toBe(404);
774+
expect(String(page._sent)).toContain(`<h1>${zh.unusableHeading}</h1><p>${zh.unusable}</p>`);
775+
const put = await call('PUT', `${BASE}/upload-links/:token`, {
776+
params: { token: 'not-a-token' }, headers: { ...ZH, ...sessionOf(OWNER.userId) }, rawBody: async () => Buffer.from('x'),
777+
});
778+
expect(put._status).toBe(404);
779+
// `message` keeps its diagnostic wording; `userMessage` is the page's.
780+
expect(put._json.error).toMatchObject({ code: 'RESOURCE_NOT_FOUND', message: UPLOAD_LINK_UNUSABLE_MESSAGE, userMessage: zh.unusable });
781+
const anonymous = await call('PUT', `${BASE}/upload-links/:token`, {
782+
params: { token: 'not-a-token' }, headers: ZH, rawBody: async () => Buffer.from('x'),
783+
});
784+
expect(anonymous._status).toBe(401);
785+
expect(anonymous._json.error).toMatchObject({ code: 'AUTH_REQUIRED', userMessage: zh.signInRequired });
786+
});
787+
788+
it('a record locked after minting: the PUT answers the page\'s lock sentence, with no code prefix and no record named', async () => {
789+
const id = await draftClaim('locked, zh');
790+
const grantZh = await files.createUploadLinkAs('claim', id, { field: 'policy' }, OWNER as never);
791+
const grantEn = await files.createUploadLinkAs('claim', id, { field: 'policy' }, OWNER as never);
792+
locked.add(id);
793+
try {
794+
const put = await useLink(tokenOf(grantZh.path), Buffer.from('locked'), ZH);
795+
expect(put._status, JSON.stringify(put._json)).toBe(409);
796+
expect(put._json.error).toMatchObject({ code: 'RECORD_LOCKED', userMessage: zh.recordLocked });
797+
expect(put._json.error.message).not.toMatch(/^RECORD_LOCKED/);
798+
expectNamesNothing(put._json.error.userMessage, id);
799+
const putEn = await useLink(tokenOf(grantEn.path), Buffer.from('locked'));
800+
expect(putEn._json.error).toMatchObject({ code: 'RECORD_LOCKED', userMessage: en.recordLocked });
801+
expect(putEn._json.error.userMessage).not.toMatch(/RECORD_LOCKED/);
802+
expectNamesNothing(putEn._json.error.userMessage, id);
803+
} finally {
804+
locked.delete(id);
805+
}
806+
});
807+
808+
it('a field read-only once its readonlyWhen holds: the page\'s sentence, naming neither object nor field', async () => {
809+
const id = await draftClaim('approved, zh');
810+
const grant = await files.createUploadLinkAs('claim', id, { field: 'invoices' }, OWNER as never);
811+
await engine.update('claim', { status: 'approved' }, { where: { id }, context: SYS } as never);
812+
const put = await useLink(tokenOf(grant.path), Buffer.from('late invoice'), ZH);
813+
expect(put._status, JSON.stringify(put._json)).toBe(403);
814+
expect(put._json.error).toMatchObject({ code: 'FIELD_NOT_ACCESSIBLE', userMessage: zh.fieldReadOnly });
815+
expectNamesNothing(put._json.error.userMessage, id);
816+
});
817+
818+
it('over the upload limit: the page\'s sentence in the workspace default, the link still usable', async () => {
819+
setWorkspaceLocale('zh-CN');
820+
const grant = await files.createUploadLinkAs('claim', ids.claimB, { attachments: true }, OWNER as never);
821+
const token = tokenOf(grant.path);
822+
storage.setLimitsSnapshot({ maxUploadMb: { value: 1, authored: true } } as never);
823+
try {
824+
const declared = await useLink(token, Buffer.alloc(10, 7), { 'content-length': String(MIB + 1) });
825+
expect(declared._status).toBe(413);
826+
expect(declared._json.error).toMatchObject({ code: 'PAYLOAD_TOO_LARGE', userMessage: zh.tooLarge });
827+
const read = await useLink(token, Buffer.alloc(MIB + 1, 7));
828+
expect(read._status).toBe(413);
829+
expect(read._json.error).toMatchObject({ code: 'PAYLOAD_TOO_LARGE', userMessage: zh.tooLarge });
830+
expect((await useLink(token, Buffer.alloc(16, 7)))._status).toBe(200);
831+
} finally {
832+
storage.setLimitsSnapshot({} as never);
833+
}
834+
});
835+
836+
it('the page\'s script writes its status lines in its language and shows the refusal the door wrote', async () => {
837+
const grant = await files.createUploadLinkAs('claim', ids.claimB, { field: 'policy' }, OWNER as never);
838+
const html = String((await openLinkIn(tokenOf(grant.path), ZH))._sent);
839+
const script = /<script nonce="[^"]+">([\s\S]*?)<\/script>/.exec(html)?.[1] ?? '';
840+
const says = async (answer: { ok: boolean; body: unknown }) => {
841+
const handlers: Record<string, () => void> = {};
842+
const el = (id: string) => ({
843+
id, disabled: id === 'send', textContent: '',
844+
files: id === 'file' ? [{ name: 'scan.pdf', type: 'application/pdf' }] : undefined,
845+
addEventListener: (event: string, fn: () => void) => { handlers[`${id}:${event}`] = fn; },
846+
});
847+
const els: Record<string, ReturnType<typeof el>> = { file: el('file'), send: el('send'), status: el('status') };
848+
runInNewContext(script, {
849+
document: { getElementById: (id: string) => els[id] },
850+
location: { pathname: '/api/v1/storage/upload-links/t' },
851+
fetch: async () => ({ ok: answer.ok, json: async () => answer.body }),
852+
});
853+
handlers['send:click']!();
854+
const uploading = els.status.textContent;
855+
for (let i = 0; i < 5; i++) await new Promise((r) => setImmediate(r));
856+
return { uploading, after: els.status.textContent };
857+
};
858+
const done = await says({ ok: true, body: { success: true, data: { fileId: 'f1', size: 3, field: 'policy' } } });
859+
expect(done).toEqual({ uploading: zh.uploading, after: zh.attached });
860+
expect((await says({ ok: false, body: { success: false, error: { code: 'INTERNAL', message: 'Upload failed' } } })).after)
861+
.toBe(zh.failed);
862+
expect((await says({ ok: false, body: { success: false, error: { code: 'RECORD_LOCKED', message: 'x', userMessage: zh.recordLocked } } })).after)
863+
.toBe(zh.recordLocked);
686864
});
687865
});
688866
});

0 commit comments

Comments
 (0)