Skip to content

Commit 80b6dee

Browse files
committed
Handle stale hosts and defend response parsing
1 parent 45f6aae commit 80b6dee

8 files changed

Lines changed: 182 additions & 6 deletions
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @jest-environment jsdom
3+
*
4+
* Scenario: a host too old to save to does not get to look editable.
5+
*
6+
* HTML Clay 1.8.0 and earlier send the pre-rename save token AND set the owner cookie
7+
* on every document serve. This library reads one token name, so it finds none, and the
8+
* cookie alone would hand the page full edit mode. Every save from that page posts to
9+
* the bare route, which that host does not have, so it 404s. An editable page that
10+
* keeps nothing is worse than a read-only one.
11+
*
12+
* Its own file: the module decides at import and jest caches it per file.
13+
*/
14+
15+
test('the old token beats the owner cookie, and edit mode stays off', async () => {
16+
document.cookie = 'isAdminOfCurrentResource=true';
17+
document.documentElement.setAttribute('htmlclaytoken', 'tok-old');
18+
jest.spyOn(console, 'warn').mockImplementation(() => {});
19+
20+
const mod = await import('../src/core/isAdminOfCurrentResource.js');
21+
22+
expect(mod.isEditMode).toBe(false);
23+
// The cookie is still there and still true: this is the rung being overruled, not
24+
// absent. Without the stale check the same page reports edit mode on.
25+
expect(mod.isOwner).toBe(true);
26+
});

‎__tests__/save-coalescing.test.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ function response() {
4242
status: 200,
4343
statusText: 'OK',
4444
json: async () => ({ msg: 'Saved' }),
45+
text: async () => JSON.stringify({ msg: 'Saved' }),
4546
};
4647
}
4748

‎__tests__/save-htmlclay-endpoint.test.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ describe('savePage — htmlclay endpoint routing', () => {
3232
Promise.resolve({
3333
ok: true,
3434
json: () => Promise.resolve({ msg: 'Saved', msgType: 'success' }),
35+
text: () => Promise.resolve(JSON.stringify({ msg: 'Saved', msgType: 'success' })),
3536
})
3637
);
3738
document.documentElement.removeAttribute('savetoken');
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/**
2+
* @jest-environment jsdom
3+
*
4+
* The HTTP status is authoritative, and the body may not be the host's at all.
5+
*
6+
* A proxy, tunnel or captive portal answers with an HTML error page. Parsing that as
7+
* JSON first turned a plain "502 Bad Gateway" into "Unexpected token '<'", which names
8+
* the parser rather than the thing that went wrong, and sent whoever hit it looking in
9+
* the wrong place. The mirror case is a 200 with an empty body: json() rejects, so a
10+
* save that had actually landed was reported as failed.
11+
*
12+
* clayjs has read the body as text and parsed it defensively for a while
13+
* (src/core/save-core.js). This is the same shape, brought across.
14+
*/
15+
16+
jest.mock('../src/core/isAdminOfCurrentResource.js', () => ({ isEditMode: true }));
17+
18+
jest.mock('../src/core/snapshot.js', () => ({
19+
captureForSave: jest.fn(() => '<html>captured</html>'),
20+
isCodeMirrorPage: jest.fn(() => false),
21+
getCodeMirrorContents: jest.fn(() => ''),
22+
beforeSave: jest.fn(),
23+
getPageContents: jest.fn(),
24+
onSnapshot: jest.fn(),
25+
onPrepareForSave: jest.fn(),
26+
}));
27+
28+
import { savePage } from '../src/core/savePageCore.js';
29+
30+
const respond = (fields) => {
31+
global.fetch = jest.fn(() => Promise.resolve(fields));
32+
};
33+
34+
let logged;
35+
36+
beforeEach(() => {
37+
logged = jest.spyOn(console, 'error').mockImplementation(() => {});
38+
});
39+
40+
afterEach(() => {
41+
jest.clearAllMocks();
42+
});
43+
44+
test("an intermediary's HTML error page reports the status, not a parse error", async () => {
45+
respond({
46+
ok: false,
47+
status: 502,
48+
statusText: 'Bad Gateway',
49+
text: () => Promise.resolve('<!DOCTYPE html><html><body>502 Bad Gateway</body></html>'),
50+
});
51+
52+
await savePage();
53+
54+
const err = logged.mock.calls[0][1];
55+
expect(err.message).toContain('502');
56+
expect(err.message).not.toContain('JSON');
57+
expect(err.message).not.toContain('Unexpected token');
58+
});
59+
60+
test('a 2xx with an empty body is a save that landed, not a failure', async () => {
61+
respond({ ok: true, status: 200, statusText: 'OK', text: () => Promise.resolve('') });
62+
63+
const result = await savePage();
64+
65+
expect(logged).not.toHaveBeenCalled();
66+
expect(result.msgType).toBe('success');
67+
});
68+
69+
// The host's own error message still wins when it sent one. Tolerating a body that is
70+
// not ours must not mean ignoring the body that is.
71+
test("the host's own message is preferred over the bare status", async () => {
72+
respond({
73+
ok: false,
74+
status: 403,
75+
statusText: 'Forbidden',
76+
text: () => Promise.resolve(JSON.stringify({ msg: 'You do not own this page' })),
77+
});
78+
79+
await savePage();
80+
81+
expect(logged.mock.calls[0][1].message).toBe('You do not own this page');
82+
});

‎src/core/host-attrs.js‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,21 @@ export function saveToken() {
5656
warnAboutLegacyToken();
5757
return null;
5858
}
59+
60+
/**
61+
* True when this response carries ONLY the pre-rename save token.
62+
*
63+
* That combination means the host is older than the rename and cannot be saved to by
64+
* this library: it sends the old name, which is no longer read, and it sets the owner
65+
* cookie, so nothing else on the page would notice. Edit mode consults this so the page
66+
* does not offer editing it cannot keep.
67+
*
68+
* @returns {boolean}
69+
*/
70+
export function servedStaleToken() {
71+
if (typeof document === "undefined") return false;
72+
if (saveToken() !== null) return false;
73+
return LEGACY_SAVE_TOKEN_ATTRS.some(
74+
(attr) => document.documentElement.getAttribute(attr)
75+
);
76+
}

‎src/core/isAdminOfCurrentResource.js‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import cookie from "../utilities/cookie.js";
22
import query from "../string-utilities/query.js";
3+
import { servedStaleToken } from "./host-attrs.js";
34

45
// Edit-mode precedence: an explicit ?editmode=true|false URL param wins, then an
56
// opt-in window.__hyperclayEditMode global, then the platform's
@@ -11,11 +12,26 @@ const forcedEditMode =
1112
? Boolean(window.__hyperclayEditMode)
1213
: null;
1314

15+
// A host older than the save-token rename takes edit mode off the table, above the
16+
// global and the cookie. Such a host sends the pre-rename token, which this library no
17+
// longer reads, AND sets the owner cookie, so without this the page opens fully
18+
// editable and every save 404s against a route that host does not have. An editable
19+
// page that keeps nothing is worse than a read-only one.
20+
//
21+
// Only an explicit ?editmode=true outranks it: that is a person asking for it on this
22+
// load, not a decision baked into a document by an author who could not have known.
23+
//
24+
// The on-page half of this lives in clayjs (core/stale-host-notice.js). Here it stays a
25+
// console line plus this: the documents that reach a token-minting host through THIS
26+
// library are the tail of a library being retired, and a new UI surface in it would
27+
// itself be frozen into every page still loading it.
1428
const isEditMode = query.editmode
1529
? query.editmode === "true" // takes precedence over the global and cookie
16-
: forcedEditMode != null
17-
? forcedEditMode
18-
: Boolean(cookie.get("isAdminOfCurrentResource"));
30+
: servedStaleToken()
31+
? false
32+
: forcedEditMode != null
33+
? forcedEditMode
34+
: Boolean(cookie.get("isAdminOfCurrentResource"));
1935

2036
const isOwner = Boolean(cookie.get("isAdminOfCurrentResource"));
2137

‎src/core/savePageCore.js‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,21 @@ export function savePage(callback = () => {}) {
275275
fetch(target.url, fetchOptions)
276276
.then(res => {
277277
clearTimeout(timeoutId);
278-
return res.json().then(data => {
278+
// The body is read as text and parsed defensively BEFORE the status is
279+
// consulted, which is what clayjs already does. Calling res.json() first made a
280+
// 200 with an empty body report a failure over a save that had landed, and
281+
// turned an intermediary's HTML error page into "Unexpected token '<'" instead
282+
// of the status that actually came back. The status is what is authoritative;
283+
// the body may not even be the host's.
284+
return res.text().then(text => {
285+
let data = {};
286+
if (text) {
287+
try {
288+
data = JSON.parse(text);
289+
} catch (err) {
290+
if (res.ok) throw new Error('Server sent a response that was not JSON');
291+
}
292+
}
279293
if (!res.ok) {
280294
throw new Error(data.msg || data.error || `HTTP ${res.status}: ${res.statusText}`);
281295
}
@@ -393,7 +407,21 @@ export function saveHtml(html, callback = () => {}, { replacesDocument = false }
393407
fetch(target.url, fetchOptions)
394408
.then(res => {
395409
clearTimeout(timeoutId);
396-
return res.json().then(data => {
410+
// The body is read as text and parsed defensively BEFORE the status is
411+
// consulted, which is what clayjs already does. Calling res.json() first made a
412+
// 200 with an empty body report a failure over a save that had landed, and
413+
// turned an intermediary's HTML error page into "Unexpected token '<'" instead
414+
// of the status that actually came back. The status is what is authoritative;
415+
// the body may not even be the host's.
416+
return res.text().then(text => {
417+
let data = {};
418+
if (text) {
419+
try {
420+
data = JSON.parse(text);
421+
} catch (err) {
422+
if (res.ok) throw new Error('Server sent a response that was not JSON');
423+
}
424+
}
397425
if (!res.ok) {
398426
throw new Error(data.msg || data.error || `HTTP ${res.status}: ${res.statusText}`);
399427
}

‎src/core/snapshot.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,11 @@ export function serializeForSync(clone) {
303303
// truncate the broadcast.
304304
const shell = bareRoot.outerHTML;
305305
const endTag = `</${bareRoot.localName}>`;
306-
return shell.slice(0, shell.length - endTag.length) + clone.innerHTML + endTag;
306+
// The doctype, so this artifact is a complete document like every other one this
307+
// module produces. Spec section 2 asks for that, and it costs nothing on the wire:
308+
// a receiver parses the string and morphs documentElement against documentElement,
309+
// so the prologue is consumed by the parser and never reaches the morph.
310+
return "<!DOCTYPE html>" + shell.slice(0, shell.length - endTag.length) + clone.innerHTML + endTag;
307311
}
308312

309313
/**

0 commit comments

Comments
 (0)