Skip to content

Commit 65430b8

Browse files
committed
Pin save URLs to real origin, prevent base href redirection
1 parent 1d2239e commit 65430b8

9 files changed

Lines changed: 199 additions & 23 deletions

‎README.md‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,10 @@ To load a full preset, use the CDN loader with `?preset=standard`:
6767
| edit-mode-helpers | 6.8KB | Admin-only functionality: [viewmode:disabled], [editmode:resource], [editmode:onclick] |
6868
| option-visibility | 9.2KB | Dynamic show/hide based on ancestor state with option:attribute="value" |
6969
| persist | 5KB | Persist input/select/textarea values to the DOM with [persist] attribute |
70-
| save-core | 15.4KB | Basic save function only - hyperclay.savePage() |
70+
| save-core | 16.6KB | Basic save function only - hyperclay.savePage() |
7171
| save-system | 19.8KB | CMD+S, [trigger-save] button, savestatus attribute |
7272
| save-toast | 1KB | Toast notifications for save events |
73-
| snapshot | 13.3KB | Source of truth for page state - captures DOM snapshots for save and sync |
73+
| snapshot | 14.3KB | Source of truth for page state - captures DOM snapshots for save and sync |
7474
| unsaved-warning | 1.3KB | Warn before leaving page with unsaved changes |
7575

7676
### Custom Attributes (HTML enhancements)
@@ -153,27 +153,27 @@ To load a full preset, use the CDN loader with `?preset=standard`:
153153

154154
## Presets
155155

156-
### Minimal (~74KB)
156+
### Minimal (~76.2KB)
157157
Essential features for basic editing
158158

159159
**Modules:** `save-core`, `snapshot`, `save-system`, `edit-mode-helpers`, `toast`, `save-toast`, `export-to-window`, `view-mode-excludes-edit-modules`
160160

161-
### Standard (~123KB)
161+
### Standard (~125.2KB)
162162
Standard feature set for most use cases
163163

164164
**Modules:** `save-core`, `snapshot`, `save-system`, `unsaved-warning`, `edit-mode-helpers`, `persist`, `option-visibility`, `event-attrs`, `dom-helpers`, `data`, `data-loss-panel`, `toast`, `save-toast`, `export-to-window`, `view-mode-excludes-edit-modules`
165165

166-
### CMS (~326.7KB)
166+
### CMS (~328.9KB)
167167
Visual CMS editing for rules-tag pages: hypercms sidebar, undo, drag-reorder, save
168168

169169
**Modules:** `save-core`, `snapshot`, `save-system`, `unsaved-warning`, `toast`, `save-toast`, `mutation`, `hypercms`, `sortable`, `undo`, `quickcrop`, `data-loss-panel`, `export-to-window`, `view-mode-excludes-edit-modules`
170170

171-
### Smooth Sailing (~654.1KB)
171+
### Smooth Sailing (~656.3KB)
172172
Everything, without gotchas
173173

174174
**Modules:** `save-core`, `save-system`, `unsaved-warning`, `save-toast`, `edit-mode-helpers`, `persist`, `snapshot`, `option-visibility`, `edit-mode`, `event-attrs`, `ajax-elements`, `sortable`, `movable`, `dom-helpers`, `input-helpers`, `onaftersave`, `save-freeze`, `dialogs`, `quickcrop`, `toast`, `the-modal`, `data-loss-panel`, `mutation`, `nearest`, `cookie`, `throttle`, `debounce`, `dom-ready`, `window-load`, `all-js`, `style-injection`, `form-data`, `hypercms`, `richclay`, `undo`, `data`, `upgrade`, `slugify`, `copy-to-clipboard`, `query-params`, `behavior-collector`, `send-message`, `file-upload`, `live-sync`, `refetch-on-save`, `export-to-window`, `view-mode-excludes-edit-modules`
175175

176-
### Everything (~768.1KB)
176+
### Everything (~770.3KB)
177177
All available features
178178

179179
Includes all available modules across all categories.

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ jest.mock('../src/core/snapshot.js', () => ({
2424

2525
import { savePage } from '../src/core/savePageCore.js';
2626

27+
const pathOf = (url) => new URL(url, 'http://localhost').pathname;
28+
2729
describe('savePage — htmlclay endpoint routing', () => {
2830
beforeEach(() => {
2931
global.fetch = jest.fn(() =>
@@ -48,7 +50,7 @@ describe('savePage — htmlclay endpoint routing', () => {
4850

4951
expect(global.fetch).toHaveBeenCalledTimes(1);
5052
const [url, opts] = global.fetch.mock.calls[0];
51-
expect(url).toBe('/_/save/TOK123');
53+
expect(pathOf(url)).toBe('/_/save/TOK123');
5254
expect(opts.body).toBe('<html>captured</html>');
5355
expect(opts.headers['Content-Type']).toBeUndefined();
5456
expect(result).toEqual({ msg: 'Saved', msgType: 'success' });
@@ -58,6 +60,6 @@ describe('savePage — htmlclay endpoint routing', () => {
5860
await savePage();
5961

6062
expect(global.fetch).toHaveBeenCalledTimes(1);
61-
expect(global.fetch.mock.calls[0][0]).toBe('/_/save');
63+
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save');
6264
});
6365
});

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

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ jest.mock('../src/core/snapshot.js', () => ({
2929
import { savePage, saveHtml } from '../src/core/savePageCore.js';
3030
import { SAVE_TOKEN_ATTRS, HOST_TOKEN_ATTRS } from '../src/utilities/root-attrs.js';
3131

32+
const pathOf = (url) => new URL(url, 'http://localhost').pathname;
33+
3234
const ALL_NAMES = ['savetoken', 'htmlclaytoken', 'htmlclayid'];
3335

3436
function clearTokens() {
@@ -56,15 +58,15 @@ describe('save token resolution', () => {
5658

5759
await savePage();
5860

59-
expect(global.fetch.mock.calls[0][0]).toBe('/_/save/SPEC123');
61+
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save/SPEC123');
6062
});
6163

6264
test('still posts to /_/save/{token} under the original htmlclaytoken name', async () => {
6365
document.documentElement.setAttribute('htmlclaytoken', 'OLD123');
6466

6567
await savePage();
6668

67-
expect(global.fetch.mock.calls[0][0]).toBe('/_/save/OLD123');
69+
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save/OLD123');
6870
});
6971

7072
test('prefers savetoken when a host serves both spellings', async () => {
@@ -73,7 +75,7 @@ describe('save token resolution', () => {
7375

7476
await savePage();
7577

76-
expect(global.fetch.mock.calls[0][0]).toBe('/_/save/SPEC123');
78+
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save/SPEC123');
7779
});
7880

7981
test('falls through an empty savetoken to the older spelling', async () => {
@@ -82,13 +84,13 @@ describe('save token resolution', () => {
8284

8385
await savePage();
8486

85-
expect(global.fetch.mock.calls[0][0]).toBe('/_/save/OLD123');
87+
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save/OLD123');
8688
});
8789

8890
test('posts to the bare /_/save when the host minted no token', async () => {
8991
await savePage();
9092

91-
expect(global.fetch.mock.calls[0][0]).toBe('/_/save');
93+
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save');
9294
});
9395

9496
// saveHtml is the other entry point onto the same lane. The two used to call one
@@ -99,7 +101,7 @@ describe('save token resolution', () => {
99101

100102
await saveHtml('<html>direct</html>');
101103

102-
expect(global.fetch.mock.calls[0][0]).toBe('/_/save/SPEC123');
104+
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save/SPEC123');
103105
});
104106
});
105107

@@ -165,7 +167,7 @@ describe('the token list holds nothing but tokens', () => {
165167

166168
await savePage();
167169

168-
expect(global.fetch.mock.calls[0][0]).toBe('/_/save');
170+
expect(pathOf(global.fetch.mock.calls[0][0])).toBe('/_/save');
169171
});
170172

171173
// The morph-protection list may grow past the token list, but the two must never
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* @jest-environment jsdom
3+
* @jest-environment-options {"url": "file:///tmp/exported-app.html"}
4+
*
5+
* Pinning the save URL to the origin must not throw on a document opened from
6+
* disk.
7+
*
8+
* `window.location.origin` is the STRING "null" on a file:// document, not the
9+
* value null, and `new URL(path, "null")` raises a TypeError. Building the URL
10+
* happens before fetch and outside the promise chain, so an unguarded pin would
11+
* throw synchronously out of a save whose contract says it never rejects.
12+
*
13+
* This is not a hypothetical environment. Downloading an app as a standalone HTML
14+
* file is a headline feature, so a document running from disk is ordinary. There
15+
* is no origin to pin to and no host to save to there, which is exactly why the
16+
* relative path is the right answer rather than a fallback that papers over a bug.
17+
*/
18+
19+
jest.mock('../src/core/isAdminOfCurrentResource.js', () => ({
20+
isEditMode: true,
21+
}));
22+
23+
jest.mock('../src/core/snapshot.js', () => ({
24+
captureForSave: jest.fn(() => '<html>captured</html>'),
25+
isCodeMirrorPage: jest.fn(() => false),
26+
getCodeMirrorContents: jest.fn(() => ''),
27+
beforeSave: jest.fn(),
28+
getPageContents: jest.fn(),
29+
onSnapshot: jest.fn(),
30+
onPrepareForSave: jest.fn(),
31+
}));
32+
33+
import { savePage } from '../src/core/savePageCore.js';
34+
35+
describe('a document opened from disk', () => {
36+
beforeEach(() => {
37+
global.fetch = jest.fn(() =>
38+
Promise.resolve({
39+
ok: true,
40+
json: () => Promise.resolve({ msg: 'Saved', msgType: 'success' }),
41+
})
42+
);
43+
document.documentElement.removeAttribute('savetoken');
44+
});
45+
46+
afterEach(() => {
47+
jest.clearAllMocks();
48+
document.documentElement.removeAttribute('savetoken');
49+
});
50+
51+
// The precondition. If this ever stops holding, the tests below stop testing
52+
// anything and would pass against an unguarded pin.
53+
test('reports the string "null" as its origin, which is what breaks new URL()', () => {
54+
expect(window.location.origin).toBe('null');
55+
// Not toThrow(TypeError): jsdom's URL comes from another realm, so the error
56+
// it raises is not this realm's TypeError even though a browser's is.
57+
expect(() => new URL('/_/save/TOK', window.location.origin)).toThrow();
58+
});
59+
60+
test('a token save resolves without throwing and keeps the relative path', async () => {
61+
document.documentElement.setAttribute('savetoken', 'TOK');
62+
63+
await expect(savePage()).resolves.toBeDefined();
64+
65+
expect(global.fetch.mock.calls[0][0]).toBe('/_/save/TOK');
66+
});
67+
68+
test('a tokenless save resolves without throwing', async () => {
69+
await expect(savePage()).resolves.toBeDefined();
70+
71+
expect(global.fetch.mock.calls[0][0]).toBe('/_/save');
72+
});
73+
});

‎__tests__/save-url-origin.test.js‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* @jest-environment jsdom
3+
*
4+
* The save URL is pinned to the real origin, so an authored <base href> cannot
5+
* redirect a save.
6+
*
7+
* fetch resolves a relative URL against the DOCUMENT's base URL, which `<base
8+
* href>` sets. A malleable document is arbitrary author HTML that gets forked and
9+
* shared, so a root-relative save path let a document send its own save, and the
10+
* per-document token sitting in that path, to an origin the document chose.
11+
*
12+
* The companion file save-url-file-origin.test.js covers the other half: pinning
13+
* must not throw on a document that has no real origin.
14+
*/
15+
16+
jest.mock('../src/core/isAdminOfCurrentResource.js', () => ({
17+
isEditMode: true,
18+
}));
19+
20+
jest.mock('../src/core/snapshot.js', () => ({
21+
captureForSave: jest.fn(() => '<html>captured</html>'),
22+
isCodeMirrorPage: jest.fn(() => false),
23+
getCodeMirrorContents: jest.fn(() => ''),
24+
beforeSave: jest.fn(),
25+
getPageContents: jest.fn(),
26+
onSnapshot: jest.fn(),
27+
onPrepareForSave: jest.fn(),
28+
}));
29+
30+
import { savePage } from '../src/core/savePageCore.js';
31+
32+
const ORIGIN = window.location.origin;
33+
34+
describe('an authored <base href> cannot move the save', () => {
35+
beforeEach(() => {
36+
global.fetch = jest.fn(() =>
37+
Promise.resolve({
38+
ok: true,
39+
json: () => Promise.resolve({ msg: 'Saved', msgType: 'success' }),
40+
})
41+
);
42+
document.head.innerHTML = '<base href="https://evil.example/">';
43+
document.documentElement.removeAttribute('savetoken');
44+
});
45+
46+
afterEach(() => {
47+
jest.clearAllMocks();
48+
document.head.innerHTML = '';
49+
document.documentElement.removeAttribute('savetoken');
50+
});
51+
52+
test('the base tag really does move a relative URL, which is why this matters', () => {
53+
expect(document.baseURI).toBe('https://evil.example/');
54+
expect(new URL('/_/save/TOK', document.baseURI).href)
55+
.toBe('https://evil.example/_/save/TOK');
56+
});
57+
58+
test('a token save still goes to the real origin', async () => {
59+
document.documentElement.setAttribute('savetoken', 'SECRET-TOKEN');
60+
61+
await savePage();
62+
63+
const url = global.fetch.mock.calls[0][0];
64+
expect(url).toBe(`${ORIGIN}/_/save/SECRET-TOKEN`);
65+
expect(url).not.toContain('evil.example');
66+
});
67+
68+
test('a tokenless save is pinned too', async () => {
69+
await savePage();
70+
71+
expect(global.fetch.mock.calls[0][0]).toBe(`${ORIGIN}/_/save`);
72+
});
73+
});

‎module-dependency-graph.generated.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@
253253
"save-core": {
254254
"name": "save-core",
255255
"category": "core",
256-
"size": 15.4,
256+
"size": 16.6,
257257
"isEditModeOnly": true,
258258
"files": [
259259
"core/savePageCore.js"
@@ -359,7 +359,7 @@
359359
"snapshot": {
360360
"name": "snapshot",
361361
"category": "core",
362-
"size": 13.3,
362+
"size": 14.3,
363363
"isEditModeOnly": true,
364364
"files": [
365365
"core/snapshot.js"

‎src/core/savePageCore.js‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,34 @@ export function whenSaveIdle() {
111111
function saveTarget() {
112112
const token = saveToken();
113113
return token
114-
? { url: `${saveEndpoint}/${token}`, credentials: 'omit' }
115-
: { url: saveEndpoint, credentials: 'same-origin' };
114+
? { url: resolveSaveUrl(`${saveEndpoint}/${token}`), credentials: 'omit' }
115+
: { url: resolveSaveUrl(saveEndpoint), credentials: 'same-origin' };
116+
}
117+
118+
/**
119+
* The absolute URL a save goes to.
120+
*
121+
* A relative path is resolved by fetch against the DOCUMENT's base URL, which
122+
* `<base href>` sets and the author of a malleable document controls. Left
123+
* relative, a `<base href="https://elsewhere.example/">` sends the document and
124+
* the per-document token in the path to an origin the document picked. Pinning to
125+
* the real origin is the whole fix.
126+
*
127+
* The guard is not defensive noise. `window.location.origin` is the STRING "null"
128+
* on a file:// document, and `new URL(path, "null")` throws a TypeError, which
129+
* would escape synchronously into a save whose promise is contracted never to
130+
* reject. Documents opened from disk are a first-class case (an exported app is
131+
* just a file), and there is no origin to pin to and no host to save to there
132+
* anyway, so the relative path is both the honest answer and the one that cannot
133+
* throw.
134+
*
135+
* @param {string} path - Root-relative save path
136+
* @returns {string}
137+
*/
138+
function resolveSaveUrl(path) {
139+
const origin = window.location.origin;
140+
if (!origin || origin === 'null') return path;
141+
return new URL(path, origin).href;
116142
}
117143

118144
// =============================================================================

‎src/vendor/hyper-html-api-upgrade.vendor.js‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)