@panomc/sdk 1.0.0-dev.9 → 2.0.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/api/routes.core.json +3702 -0
  2. package/bin/api/__tests__/api-compat.test.mjs +97 -0
  3. package/bin/api/__tests__/check-paths.test.mjs +113 -0
  4. package/bin/api/__tests__/cli.test.mjs +44 -0
  5. package/bin/api/__tests__/extract-routes.test.mjs +132 -0
  6. package/bin/api/__tests__/fixtures/core-new/Pano/api/paths.old-new.json +82 -0
  7. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/error/NotExists.kt +10 -0
  8. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/model/Bases.kt +21 -0
  9. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/GetSiteInfoAPI.kt +19 -0
  10. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/auth/HostSsoAPI.kt +10 -0
  11. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/panel/PanelAddonsAPI.kt +28 -0
  12. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/plugins/GetPluginUiZipAPI.kt +9 -0
  13. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/template/IndexTemplate.kt +9 -0
  14. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/error/NotExists.kt +10 -0
  15. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/model/Bases.kt +21 -0
  16. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/GetSiteInfoAPI.kt +19 -0
  17. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/auth/HostSsoAPI.kt +10 -0
  18. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/panel/PanelAddonsAPI.kt +28 -0
  19. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/plugins/GetPluginUiZipAPI.kt +9 -0
  20. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/template/IndexTemplate.kt +9 -0
  21. package/bin/api/__tests__/fixtures/plugin-new/api/paths.old-new.json +66 -0
  22. package/bin/api/__tests__/fixtures/plugin-new/build.gradle.kts +42 -0
  23. package/bin/api/__tests__/fixtures/plugin-new/gradle.properties +4 -0
  24. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/base/DemoApis.kt +13 -0
  25. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/error/Errors.kt +16 -0
  26. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/error/Plain.kt +4 -0
  27. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/GetThingsAPI.kt +16 -0
  28. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/PanelThingAPI.kt +11 -0
  29. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/ValidatedAPI.kt +18 -0
  30. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/WebhookAPI.kt +23 -0
  31. package/bin/api/__tests__/fixtures/plugin-new/src/panel/Things.js +4 -0
  32. package/bin/api/__tests__/fixtures/plugin-new/src/theme/Logo.svelte +9 -0
  33. package/bin/api/__tests__/fixtures/plugin-new/src/theme/api.js +29 -0
  34. package/bin/api/__tests__/fixtures/plugin-old/build.gradle.kts +22 -0
  35. package/bin/api/__tests__/fixtures/plugin-old/gradle.properties +4 -0
  36. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/base/DemoApis.kt +13 -0
  37. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/error/Errors.kt +16 -0
  38. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/error/Plain.kt +4 -0
  39. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/GetThingsAPI.kt +16 -0
  40. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/PanelThingAPI.kt +11 -0
  41. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/ValidatedAPI.kt +18 -0
  42. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/WebhookAPI.kt +23 -0
  43. package/bin/api/__tests__/fixtures/plugin-old/src/panel/Things.js +4 -0
  44. package/bin/api/__tests__/fixtures/plugin-old/src/theme/Logo.svelte +9 -0
  45. package/bin/api/__tests__/fixtures/plugin-old/src/theme/api.js +29 -0
  46. package/bin/api/__tests__/fixtures/refusals/gradle.properties +1 -0
  47. package/bin/api/__tests__/fixtures/refusals/src/main/kotlin/x/Bad.kt +39 -0
  48. package/bin/api/__tests__/fixtures/unresolved/src/main/kotlin/x/Orphan.kt +19 -0
  49. package/bin/api/__tests__/helpers.mjs +48 -0
  50. package/bin/api/__tests__/migrate-v1.test.mjs +377 -0
  51. package/bin/api/__tests__/openapi-snapshot.test.mjs +120 -0
  52. package/bin/api/api-compat.mjs +204 -0
  53. package/bin/api/check-paths.mjs +135 -0
  54. package/bin/api/cli.mjs +83 -0
  55. package/bin/api/extract-routes.mjs +129 -0
  56. package/bin/api/js-scan.mjs +337 -0
  57. package/bin/api/kotlin.mjs +366 -0
  58. package/bin/api/migrate-v1.mjs +330 -0
  59. package/bin/api/openapi-snapshot.mjs +112 -0
  60. package/bin/api/project.mjs +172 -0
  61. package/bin/api/rename-table.mjs +66 -0
  62. package/bin/api/util.mjs +194 -0
  63. package/bin/pano-api.js +5 -0
  64. package/build/plugin-api-rollup.js +46 -0
  65. package/core/css/pano-tokens.css +225 -0
  66. package/core/favicon/apple-touch-icon.png +0 -0
  67. package/core/favicon/favicon-96x96.png +0 -0
  68. package/core/favicon/favicon.ico +0 -0
  69. package/core/favicon/favicon.svg +1 -0
  70. package/core/favicon/site.webmanifest +21 -0
  71. package/core/favicon/web-app-manifest-192x192.png +0 -0
  72. package/core/favicon/web-app-manifest-512x512.png +0 -0
  73. package/core/favicon_old/android-icon-144x144.png +0 -0
  74. package/core/favicon_old/android-icon-192x192.png +0 -0
  75. package/core/favicon_old/android-icon-36x36.png +0 -0
  76. package/core/favicon_old/android-icon-48x48.png +0 -0
  77. package/core/favicon_old/android-icon-72x72.png +0 -0
  78. package/core/favicon_old/android-icon-96x96.png +0 -0
  79. package/core/favicon_old/apple-icon-114x114.png +0 -0
  80. package/core/favicon_old/apple-icon-120x120.png +0 -0
  81. package/core/favicon_old/apple-icon-144x144.png +0 -0
  82. package/core/favicon_old/apple-icon-152x152.png +0 -0
  83. package/core/favicon_old/apple-icon-180x180.png +0 -0
  84. package/core/favicon_old/apple-icon-57x57.png +0 -0
  85. package/core/favicon_old/apple-icon-60x60.png +0 -0
  86. package/core/favicon_old/apple-icon-72x72.png +0 -0
  87. package/core/favicon_old/apple-icon-76x76.png +0 -0
  88. package/core/favicon_old/apple-icon-precomposed.png +0 -0
  89. package/core/favicon_old/apple-icon.png +0 -0
  90. package/core/favicon_old/browserconfig.xml +11 -0
  91. package/core/favicon_old/favicon-16x16.png +0 -0
  92. package/core/favicon_old/favicon-32x32.png +0 -0
  93. package/core/favicon_old/favicon-96x96.png +0 -0
  94. package/core/favicon_old/favicon.ico +0 -0
  95. package/core/favicon_old/manifest.json +41 -0
  96. package/core/favicon_old/ms-icon-144x144.png +0 -0
  97. package/core/favicon_old/ms-icon-150x150.png +0 -0
  98. package/core/favicon_old/ms-icon-310x310.png +0 -0
  99. package/core/favicon_old/ms-icon-70x70.png +0 -0
  100. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.eot +0 -0
  101. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.svg +483 -0
  102. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.ttf +0 -0
  103. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff +0 -0
  104. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff2 +0 -0
  105. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.eot +0 -0
  106. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.svg +486 -0
  107. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.ttf +0 -0
  108. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff +0 -0
  109. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff2 +0 -0
  110. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.eot +0 -0
  111. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.svg +484 -0
  112. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.ttf +0 -0
  113. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff +0 -0
  114. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff2 +0 -0
  115. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.eot +0 -0
  116. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.svg +486 -0
  117. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.ttf +0 -0
  118. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff +0 -0
  119. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff2 +0 -0
  120. package/core/js/ControllerRegistry.js +421 -0
  121. package/core/js/NotificationManager.js +62 -0
  122. package/core/js/PluginAPI.js +39 -0
  123. package/core/js/PluginManager.js +851 -0
  124. package/core/js/RouteMatcher.js +142 -0
  125. package/core/js/__tests__/ControllerRegistry.test.js +378 -0
  126. package/core/js/__tests__/NotificationManager.test.js +57 -0
  127. package/core/js/__tests__/PluginAPI.test.js +25 -0
  128. package/core/js/__tests__/RouteMatcher.test.js +33 -0
  129. package/core/js/__tests__/accessClient.test.js +582 -0
  130. package/core/js/__tests__/api.util.v1.test.js +336 -0
  131. package/core/js/__tests__/appStores.test.js +47 -0
  132. package/core/js/__tests__/devBounce.test.js +28 -0
  133. package/core/js/__tests__/html.util.test.js +18 -0
  134. package/core/js/__tests__/pluginFolder.util.test.js +106 -0
  135. package/core/js/__tests__/pluginPackage.test.js +134 -0
  136. package/core/js/__tests__/pluginUiZip.test.js +47 -0
  137. package/core/js/__tests__/sdkLevel.test.js +34 -0
  138. package/core/js/api.util.js +433 -0
  139. package/core/js/appStores.js +93 -0
  140. package/core/js/basePath.js +10 -0
  141. package/core/js/html.util.js +26 -0
  142. package/core/js/pluginFolder.util.js +95 -0
  143. package/core/js/tooltip.util.js +59 -0
  144. package/core/js/variables.js +95 -0
  145. package/core/js/version.util.js +100 -0
  146. package/core/scss/_pano-tokens.scss +51 -0
  147. package/core/scss/custom-bootstrap.scss +210 -0
  148. package/core/scss/fonts.scss +85 -0
  149. package/core/scss/main.scss +389 -0
  150. package/core/scss/themes.scss +122 -0
  151. package/package.json +63 -11
  152. package/src/__tests__/controllers.test.js +220 -0
  153. package/src/__tests__/views.spike.test.js +472 -0
  154. package/src/components/{index.js → panel.js} +9 -7
  155. package/src/components/theme.js +18 -0
  156. package/src/controllers.js +127 -0
  157. package/src/index.js +1 -1
  158. package/src/runtime-specifiers.js +88 -0
  159. package/src/svelte.js +3 -2
  160. package/src/types.js +5 -3
  161. package/src/utils/api.js +42 -1
  162. package/src/utils/auth.js +8 -0
  163. package/src/utils/component.js +4 -2
  164. package/src/utils/route.js +16 -0
  165. package/src/utils/text.js +8 -0
  166. package/src/views.js +29 -0
@@ -0,0 +1,582 @@
1
+ import { afterAll, afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
2
+ import { readable, writable } from 'svelte/store';
3
+
4
+ // TC-61 (doc 05 sections 3.1, 4, 6, slice 10): what an engine front-end sends to Pano.
5
+ // - handleFetch of the engine hooks: key and client-IP headers, no Origin, no visitor-visit special case
6
+ // - ApiUtil: X-CSRF-Token from the page session, GET /auth/csrf once when the session has none
7
+ // - siteRealtime: POST /auth/ws-ticket, then the socket opens with ?ticket=
8
+
9
+ const BACKEND = 'http://127.0.0.1:8088/api';
10
+ const state = { apiUrl: BACKEND, browser: false };
11
+ const pageStore = writable({ data: {} });
12
+
13
+ function mockHost() {
14
+ mock.module('$lib/variables.js', () => ({
15
+ get API_URL() {
16
+ return state.apiUrl;
17
+ },
18
+ CSRF_HEADER: 'X-CSRF-Token',
19
+ }));
20
+ mock.module('$app/env', () => ({
21
+ dev: false,
22
+ get browser() {
23
+ return state.browser;
24
+ },
25
+ }));
26
+ mock.module('../appStores.js', () => ({ page: pageStore }));
27
+ mock.module('$app/paths', () => ({ base: '' }));
28
+ mock.module('$lib/Store.js', () => ({ initialized: writable(true) }));
29
+ mock.module('$lib/components/ToastContainer.svelte', () => ({ show: async () => {} }));
30
+ }
31
+
32
+ mockHost();
33
+
34
+ // Bun snapshots a mock factory's values, so a change is applied by registering the mock again.
35
+ function setHost(next) {
36
+ Object.assign(state, next);
37
+ mockHost();
38
+ }
39
+
40
+ const apiMod = await import('../api.util.js');
41
+ const { default: ApiUtil, resetFetchedCsrfToken } = apiMod;
42
+
43
+ // hooks-server.js and siteRealtime.js reach ApiUtil through the engine's own specifier.
44
+ mock.module('$pano/lib/api.util', () => apiMod);
45
+ mock.module('$pano/lib/api.util.js', () => apiMod);
46
+
47
+ const { createThemeHooks } = await import('../../../../theme-core/src/kit/hooks-server.js');
48
+ const { updateApiUrl } = await import('../../../../theme-core/src/lib/variables.js');
49
+ const realtime = await import('../../../../theme-core/src/lib/siteRealtime.js');
50
+
51
+ updateApiUrl(BACKEND);
52
+
53
+ const { handleFetch } = createThemeHooks({ internalLibsHash: 'test', runtimeShimsHash: 'test' });
54
+
55
+ const realFetch = globalThis.fetch;
56
+ const realLog = console.log;
57
+ const realKey = process.env.PANO_FRONTEND_KEY;
58
+
59
+ const json = (body, status = 200) =>
60
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
61
+
62
+ beforeEach(() => {
63
+ setHost({ apiUrl: BACKEND, browser: false });
64
+ pageStore.set({ data: {} });
65
+ resetFetchedCsrfToken();
66
+ delete process.env.PANO_FRONTEND_KEY;
67
+ console.log = () => {};
68
+ });
69
+
70
+ afterEach(() => {
71
+ globalThis.fetch = realFetch;
72
+ console.log = realLog;
73
+ });
74
+
75
+ afterAll(() => {
76
+ if (realKey === undefined) delete process.env.PANO_FRONTEND_KEY;
77
+ else process.env.PANO_FRONTEND_KEY = realKey;
78
+ });
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // A stub Pano and a stand-in for SvelteKit's event.fetch
82
+ // ---------------------------------------------------------------------------
83
+
84
+ /**
85
+ * The parts of Pano these tests lean on: the key and IP headers it records, the CSRF rule of doc 05 section 4
86
+ * (a cookie session without the header is refused on a mutation), `/auth/csrf` and `/auth/ws-ticket`.
87
+ */
88
+ function stubPano({ session = 'sess-1', csrfToken = 'csrf-1' } = {}) {
89
+ const seen = [];
90
+
91
+ const handler = async (request) => {
92
+ const url = new URL(request.url);
93
+ const cookie = request.headers.get('cookie') ?? '';
94
+ const loggedIn = cookie.includes(`pano_auth_token=${session}`);
95
+ const entry = {
96
+ method: request.method,
97
+ path: url.pathname,
98
+ key: request.headers.get('X-Pano-Frontend-Key'),
99
+ ip: request.headers.get('X-Pano-Client-Ip'),
100
+ origin: request.headers.get('Origin'),
101
+ forwardedFor: request.headers.get('X-Forwarded-For'),
102
+ csrf: request.headers.get('X-CSRF-Token'),
103
+ cookie,
104
+ };
105
+ seen.push(entry);
106
+
107
+ if (url.pathname === '/api/v1/auth/csrf') {
108
+ return loggedIn ? json({ csrfToken }) : json({ error: { code: 'UNAUTHORIZED' } }, 401);
109
+ }
110
+ if (url.pathname === '/api/v1/auth/login') return json({ csrfToken });
111
+ if (url.pathname === '/api/v1/auth/ws-ticket') {
112
+ if (!loggedIn) return json({ error: { code: 'UNAUTHORIZED' } }, 401);
113
+ return entry.csrf === csrfToken
114
+ ? json({ ticket: 'ticket-1', expiresIn: 30 })
115
+ : json({ error: { code: 'INVALID_CSRF_TOKEN' } }, 403);
116
+ }
117
+
118
+ const unsafe = !['GET', 'HEAD', 'OPTIONS'].includes(request.method);
119
+ if (unsafe && loggedIn && entry.csrf !== csrfToken) {
120
+ return json({ error: { code: 'INVALID_CSRF_TOKEN' } }, 403);
121
+ }
122
+ return json({ ok: true });
123
+ };
124
+
125
+ handler.seen = seen;
126
+ return handler;
127
+ }
128
+
129
+ /** @returns {any} a SvelteKit RequestEvent with the parts handleFetch reads */
130
+ function eventFor({ headers = {}, peer = '10.0.0.7' } = {}) {
131
+ return {
132
+ url: new URL('https://site.test/profile'),
133
+ request: new Request('https://site.test/profile', { headers }),
134
+ getClientAddress: () => peer,
135
+ };
136
+ }
137
+
138
+ /** event.fetch: resolves against the page origin, runs handleFetch, ends at the stub. */
139
+ function eventFetch(event, backend) {
140
+ return (input, init) => {
141
+ // Backend calls go through the runtime's own fetch, not the hook's (78d89b5): the stub stands behind both.
142
+ globalThis.fetch = (request) => backend(request);
143
+
144
+ return handleFetch({
145
+ event,
146
+ request: new Request(new URL(String(input), event.url).href, init),
147
+ fetch: (request) => backend(request),
148
+ });
149
+ };
150
+ }
151
+
152
+ // ---------------------------------------------------------------------------
153
+ // handleFetch
154
+ // ---------------------------------------------------------------------------
155
+
156
+ describe('handleFetch: key and client-IP headers', () => {
157
+ test('with a key: both headers, the cookie, and no Origin', async () => {
158
+ process.env.PANO_FRONTEND_KEY = 'pfk_secret';
159
+ const backend = stubPano();
160
+ const event = eventFor({ headers: { cookie: 'pano_auth_token=sess-1', 'x-forwarded-for': '203.0.113.9' } });
161
+
162
+ const response = await eventFetch(event, backend)('/api/v1/posts');
163
+ expect(response.status).toBe(200);
164
+
165
+ const [seen] = backend.seen;
166
+ expect(seen.key).toBe('pfk_secret');
167
+ expect(seen.ip).toBe('203.0.113.9');
168
+ expect(seen.origin).toBeNull();
169
+ expect(seen.cookie).toBe('pano_auth_token=sess-1');
170
+ expect(seen.path).toBe('/api/v1/posts');
171
+ });
172
+
173
+ test('an absolute backend URL gets the same treatment', async () => {
174
+ process.env.PANO_FRONTEND_KEY = 'pfk_secret';
175
+ const backend = stubPano();
176
+ const event = eventFor({ headers: { 'x-forwarded-for': '203.0.113.9' } });
177
+ globalThis.fetch = (request) => backend(request);
178
+
179
+ await handleFetch({
180
+ event,
181
+ request: new Request(`${BACKEND}/v1/posts`),
182
+ fetch: (request) => backend(request),
183
+ });
184
+
185
+ expect(backend.seen[0].key).toBe('pfk_secret');
186
+ expect(backend.seen[0].ip).toBe('203.0.113.9');
187
+ expect(backend.seen[0].origin).toBeNull();
188
+ });
189
+
190
+ test('the IP is the X-Forwarded-For value, never cf-connecting-ip', async () => {
191
+ process.env.PANO_FRONTEND_KEY = 'pfk_secret';
192
+ const backend = stubPano();
193
+ const event = eventFor({ headers: { 'x-forwarded-for': '203.0.113.9', 'cf-connecting-ip': '198.51.100.1' } });
194
+
195
+ await eventFetch(event, backend)('/api/v1/posts');
196
+
197
+ expect(backend.seen[0].ip).toBe('203.0.113.9');
198
+ });
199
+
200
+ test('without X-Forwarded-For the socket peer is the visitor', async () => {
201
+ process.env.PANO_FRONTEND_KEY = 'pfk_secret';
202
+ const backend = stubPano();
203
+ const event = eventFor({ headers: { 'cf-connecting-ip': '198.51.100.1' }, peer: '192.0.2.44' });
204
+
205
+ await eventFetch(event, backend)('/api/v1/posts');
206
+
207
+ expect(backend.seen[0].ip).toBe('192.0.2.44');
208
+ });
209
+
210
+ test('no resolvable address: the key is sent, the IP header is left out, never empty', async () => {
211
+ process.env.PANO_FRONTEND_KEY = 'pfk_secret';
212
+ const backend = stubPano();
213
+ const event = eventFor();
214
+ event.getClientAddress = () => {
215
+ throw new Error('no address');
216
+ };
217
+
218
+ await eventFetch(event, backend)('/api/v1/posts');
219
+
220
+ expect(backend.seen[0].key).toBe('pfk_secret');
221
+ expect(backend.seen[0].ip).toBeNull();
222
+ });
223
+
224
+ test('without a key neither header is sent, and an empty key counts as unset', async () => {
225
+ const backend = stubPano();
226
+ const event = eventFor({ headers: { 'x-forwarded-for': '203.0.113.9' } });
227
+
228
+ await eventFetch(event, backend)('/api/v1/posts');
229
+ process.env.PANO_FRONTEND_KEY = ' ';
230
+ await eventFetch(event, backend)('/api/v1/posts');
231
+
232
+ for (const seen of backend.seen) {
233
+ expect(seen.key).toBeNull();
234
+ expect(seen.ip).toBeNull();
235
+ expect(seen.origin).toBeNull();
236
+ }
237
+ expect(backend.seen).toHaveLength(2);
238
+ });
239
+
240
+ test('a request to another host carries no key, no IP and no cookie', async () => {
241
+ process.env.PANO_FRONTEND_KEY = 'pfk_secret';
242
+ const sent = [];
243
+ const event = eventFor({ headers: { cookie: 'pano_auth_token=sess-1', 'x-forwarded-for': '203.0.113.9' } });
244
+
245
+ await handleFetch({
246
+ event,
247
+ request: new Request('https://api.example.org/v1/thing'),
248
+ fetch: async (request) => {
249
+ sent.push(request);
250
+ return json({});
251
+ },
252
+ });
253
+
254
+ expect(sent[0].headers.get('X-Pano-Frontend-Key')).toBeNull();
255
+ expect(sent[0].headers.get('X-Pano-Client-Ip')).toBeNull();
256
+ expect(sent[0].headers.get('cookie')).toBeNull();
257
+ });
258
+
259
+ test('visitor-visit gets no X-Forwarded-For special case', async () => {
260
+ const backend = stubPano();
261
+ const event = eventFor({ headers: { 'x-forwarded-for': '203.0.113.9' } });
262
+
263
+ await eventFetch(event, backend)('/api/v1/visitor-visit', { method: 'POST' });
264
+
265
+ expect(backend.seen[0].forwardedFor).toBeNull();
266
+ });
267
+ });
268
+
269
+ // ---------------------------------------------------------------------------
270
+ // SSR through ApiUtil
271
+ // ---------------------------------------------------------------------------
272
+
273
+ describe('SSR requests through ApiUtil', () => {
274
+ test('a login made during SSR carries the visitor IP', async () => {
275
+ process.env.PANO_FRONTEND_KEY = 'pfk_secret';
276
+ const backend = stubPano();
277
+ const event = eventFor({ headers: { 'x-forwarded-for': '203.0.113.9' }, peer: '127.0.0.1' });
278
+ event.fetch = eventFetch(event, backend);
279
+
280
+ const result = await ApiUtil.post({
281
+ path: '/auth/login',
282
+ body: { usernameOrEmail: 'steve', password: 'pw' },
283
+ request: event,
284
+ });
285
+
286
+ expect(result.csrfToken).toBe('csrf-1');
287
+ const login = backend.seen.find((s) => s.path === '/api/v1/auth/login');
288
+ expect(login.ip).toBe('203.0.113.9');
289
+ expect(login.key).toBe('pfk_secret');
290
+ expect(login.origin).toBeNull();
291
+ });
292
+
293
+ test('30 logged-in navigations stay 200 (visitor-visit with and without a session token)', async () => {
294
+ process.env.PANO_FRONTEND_KEY = 'pfk_secret';
295
+ const backend = stubPano();
296
+ const statuses = [];
297
+ const recording = async (request) => {
298
+ const response = await backend(request);
299
+ statuses.push(response.status);
300
+ return response;
301
+ };
302
+
303
+ for (let i = 0; i < 30; i++) {
304
+ const event = eventFor({
305
+ headers: { cookie: 'pano_auth_token=sess-1', 'x-forwarded-for': `203.0.113.${i + 1}` },
306
+ });
307
+ event.fetch = eventFetch(event, recording);
308
+
309
+ const credentials = await ApiUtil.get({ path: '/auth/credentials', request: event });
310
+ // even rounds pass the cookie's token, odd rounds rely on GET /auth/csrf
311
+ const visit = await ApiUtil.post({
312
+ path: '/visitor-visit',
313
+ request: event,
314
+ csrfToken: i % 2 === 0 ? 'csrf-1' : undefined,
315
+ });
316
+
317
+ expect(credentials.error).toBeUndefined();
318
+ expect(visit.error).toBeUndefined();
319
+ }
320
+
321
+ expect(statuses.length).toBeGreaterThanOrEqual(60);
322
+ expect(statuses.every((status) => status === 200)).toBe(true);
323
+ expect(backend.seen.filter((s) => s.path === '/api/v1/visitor-visit').every((s) => s.csrf === 'csrf-1')).toBe(true);
324
+ // each visit carries its own visitor
325
+ expect(backend.seen.find((s) => s.path === '/api/v1/visitor-visit' && s.ip === '203.0.113.30')).toBeDefined();
326
+ });
327
+ });
328
+
329
+ // ---------------------------------------------------------------------------
330
+ // ApiUtil: CSRF header and GET /auth/csrf
331
+ // ---------------------------------------------------------------------------
332
+
333
+ /** A global fetch that records the call and answers by path. */
334
+ function browserFetch(answer) {
335
+ const calls = [];
336
+ globalThis.fetch = async (url, init = {}) => {
337
+ const call = { url: String(url), method: init.method ?? 'GET', headers: { ...(init.headers ?? {}) } };
338
+ calls.push(call);
339
+ return answer(call);
340
+ };
341
+ return calls;
342
+ }
343
+
344
+ const isCsrfCall = (call) => call.url.endsWith('/auth/csrf');
345
+
346
+ describe('ApiUtil CSRF header', () => {
347
+ test('sends the page session token and does not ask /auth/csrf', async () => {
348
+ setHost({ browser: true });
349
+ pageStore.set({ data: { session: { csrfToken: 'from-page' } } });
350
+ const calls = browserFetch(() => json({ ok: true }));
351
+
352
+ await ApiUtil.post({ path: '/posts', body: {} });
353
+
354
+ expect(calls).toHaveLength(1);
355
+ expect(calls[0].headers['X-CSRF-Token']).toBe('from-page');
356
+ });
357
+
358
+ test('a mutation without a session token calls GET /auth/csrf once and then reuses the token', async () => {
359
+ setHost({ browser: true });
360
+ const calls = browserFetch((call) => (isCsrfCall(call) ? json({ csrfToken: 'fetched' }) : json({ ok: true })));
361
+
362
+ await ApiUtil.post({ path: '/posts', body: {} });
363
+ await ApiUtil.put({ path: '/posts/1', body: {} });
364
+ await ApiUtil.delete({ path: '/posts/1' });
365
+
366
+ const csrfCalls = calls.filter(isCsrfCall);
367
+ expect(csrfCalls).toHaveLength(1);
368
+ expect(csrfCalls[0].url).toBe('/api/v1/auth/csrf');
369
+ expect(csrfCalls[0].method).toBe('GET');
370
+
371
+ const mutations = calls.filter((call) => !isCsrfCall(call));
372
+ expect(mutations).toHaveLength(3);
373
+ for (const mutation of mutations) expect(mutation.headers['X-CSRF-Token']).toBe('fetched');
374
+ // the token was in hand before the first mutation was sent
375
+ expect(calls[0].url).toBe('/api/v1/auth/csrf');
376
+ });
377
+
378
+ test('concurrent mutations share one /auth/csrf call', async () => {
379
+ setHost({ browser: true });
380
+ const calls = browserFetch((call) => (isCsrfCall(call) ? json({ csrfToken: 'fetched' }) : json({ ok: true })));
381
+
382
+ await Promise.all([
383
+ ApiUtil.post({ path: '/a', body: {} }),
384
+ ApiUtil.post({ path: '/b', body: {} }),
385
+ ApiUtil.post({ path: '/c', body: {} }),
386
+ ]);
387
+
388
+ expect(calls.filter(isCsrfCall)).toHaveLength(1);
389
+ });
390
+
391
+ test('a read never calls /auth/csrf', async () => {
392
+ setHost({ browser: true });
393
+ const calls = browserFetch(() => json({ ok: true }));
394
+
395
+ await ApiUtil.get({ path: '/posts' });
396
+
397
+ expect(calls.some(isCsrfCall)).toBe(false);
398
+ });
399
+
400
+ test('a Bearer call never calls /auth/csrf', async () => {
401
+ setHost({ browser: true });
402
+ const calls = browserFetch(() => json({ ok: true }));
403
+
404
+ await ApiUtil.post({ path: '/cart/items', body: {}, token: 'eyJ.site.token' });
405
+
406
+ expect(calls.some(isCsrfCall)).toBe(false);
407
+ expect(calls[0].headers['X-CSRF-Token']).toBeUndefined();
408
+ expect(calls[0].headers.Authorization).toBe('Bearer eyJ.site.token');
409
+ });
410
+
411
+ test('an anonymous visitor (401) sends no header, the mutation still goes out, and 401 is asked once', async () => {
412
+ setHost({ browser: true });
413
+ const calls = browserFetch((call) =>
414
+ isCsrfCall(call) ? json({ error: { code: 'UNAUTHORIZED' } }, 401) : json({ ok: true }),
415
+ );
416
+
417
+ const first = await ApiUtil.post({ path: '/auth/login', body: { usernameOrEmail: 'a', password: 'b' } });
418
+ const second = await ApiUtil.post({ path: '/auth/login', body: { usernameOrEmail: 'a', password: 'b' } });
419
+
420
+ expect(first.ok).toBe(true);
421
+ expect(second.ok).toBe(true);
422
+ const logins = calls.filter((call) => !isCsrfCall(call));
423
+ expect(logins).toHaveLength(2);
424
+ for (const login of logins) expect(login.headers['X-CSRF-Token']).toBeUndefined();
425
+ expect(calls.filter(isCsrfCall)).toHaveLength(1);
426
+ });
427
+
428
+ test('a token answer of null (Bearer session) means no header', async () => {
429
+ setHost({ browser: true });
430
+ const calls = browserFetch((call) => (isCsrfCall(call) ? json({ csrfToken: null }) : json({ ok: true })));
431
+
432
+ await ApiUtil.post({ path: '/posts', body: {} });
433
+
434
+ expect(calls.find((call) => !isCsrfCall(call)).headers['X-CSRF-Token']).toBeUndefined();
435
+ });
436
+
437
+ test('a refused request drops the cached token so the next mutation asks again', async () => {
438
+ setHost({ browser: true });
439
+ let issued = 0;
440
+ const calls = browserFetch((call) => {
441
+ if (isCsrfCall(call)) return json({ csrfToken: `token-${++issued}` });
442
+ return call.headers['X-CSRF-Token'] === 'token-1' ? json({ error: { code: 'INVALID_CSRF_TOKEN' } }, 403) : json({ ok: true });
443
+ });
444
+
445
+ const refused = await ApiUtil.post({ path: '/posts', body: {} });
446
+ const retried = await ApiUtil.post({ path: '/posts', body: {} });
447
+
448
+ expect(refused.error.code).toBe('INVALID_CSRF_TOKEN');
449
+ expect(retried.ok).toBe(true);
450
+ expect(calls.filter(isCsrfCall)).toHaveLength(2);
451
+ });
452
+
453
+ test('on the server nothing is cached between callers', async () => {
454
+ const seenCookies = [];
455
+ const makeRequest = (cookie, token) => ({
456
+ fetch: async (url, init = {}) => {
457
+ if (String(url).endsWith('/auth/csrf')) return json({ csrfToken: token });
458
+ seenCookies.push({ cookie, csrf: init.headers['X-CSRF-Token'] });
459
+ return json({ ok: true });
460
+ },
461
+ });
462
+
463
+ await ApiUtil.post({ path: '/posts', body: {}, request: makeRequest('a', 'token-a') });
464
+ await ApiUtil.post({ path: '/posts', body: {}, request: makeRequest('b', 'token-b') });
465
+
466
+ expect(seenCookies).toEqual([
467
+ { cookie: 'a', csrf: 'token-a' },
468
+ { cookie: 'b', csrf: 'token-b' },
469
+ ]);
470
+ });
471
+ });
472
+
473
+ // ---------------------------------------------------------------------------
474
+ // siteRealtime: ticket, then socket
475
+ // ---------------------------------------------------------------------------
476
+
477
+ class FakeSocket {
478
+ static CONNECTING = 0;
479
+ static OPEN = 1;
480
+ static CLOSING = 2;
481
+ static CLOSED = 3;
482
+ static instances = [];
483
+
484
+ constructor(url) {
485
+ this.url = url;
486
+ this.readyState = FakeSocket.CONNECTING;
487
+ FakeSocket.instances.push(this);
488
+ }
489
+
490
+ send() {}
491
+
492
+ close() {
493
+ this.readyState = FakeSocket.CLOSED;
494
+ }
495
+ }
496
+
497
+ async function until(check, label) {
498
+ for (let i = 0; i < 100; i++) {
499
+ if (check()) return;
500
+ await new Promise((resolve) => setTimeout(resolve, 10));
501
+ }
502
+ throw new Error(`timed out waiting for ${label}`);
503
+ }
504
+
505
+ describe('siteRealtime WebSocket ticket', () => {
506
+ const realWebSocket = globalThis.WebSocket;
507
+ const hadWindow = 'window' in globalThis;
508
+ const realWindow = globalThis.window;
509
+
510
+ beforeEach(() => {
511
+ FakeSocket.instances = [];
512
+ globalThis.WebSocket = FakeSocket;
513
+ globalThis.window = { location: { origin: 'https://site.test' } };
514
+ setHost({ browser: true });
515
+ pageStore.set({ data: { session: { csrfToken: 'csrf-1' } } });
516
+ });
517
+
518
+ afterEach(() => {
519
+ realtime.setSiteNotificationsSubscription(false);
520
+ globalThis.WebSocket = realWebSocket;
521
+ if (hadWindow) globalThis.window = realWindow;
522
+ else delete globalThis.window;
523
+ });
524
+
525
+ test('fetches POST /auth/ws-ticket with the CSRF header and connects with ?ticket=', async () => {
526
+ const calls = browserFetch((call) =>
527
+ call.url.endsWith('/auth/ws-ticket') ? json({ ticket: 'ticket-9', expiresIn: 30 }) : json({ ok: true }),
528
+ );
529
+
530
+ realtime.setSiteNotificationsSubscription(true);
531
+ await until(() => FakeSocket.instances.length === 1, 'the socket');
532
+
533
+ const [ticketCall] = calls;
534
+ expect(ticketCall.url).toBe('/api/v1/auth/ws-ticket');
535
+ expect(ticketCall.method).toBe('POST');
536
+ expect(ticketCall.headers['X-CSRF-Token']).toBe('csrf-1');
537
+ expect(FakeSocket.instances[0].url).toBe('wss://site.test/api/v1/ws?ticket=ticket-9');
538
+ });
539
+
540
+ test('a second subscribe while the ticket is in flight opens one socket', async () => {
541
+ browserFetch((call) =>
542
+ call.url.endsWith('/auth/ws-ticket') ? json({ ticket: 'ticket-9', expiresIn: 30 }) : json({ ok: true }),
543
+ );
544
+
545
+ realtime.setSiteNotificationsSubscription(true);
546
+ realtime.setSiteNotificationsSubscription(true);
547
+ await until(() => FakeSocket.instances.length >= 1, 'the socket');
548
+ await new Promise((resolve) => setTimeout(resolve, 50));
549
+
550
+ expect(FakeSocket.instances).toHaveLength(1);
551
+ });
552
+
553
+ test('switching off while the ticket is in flight opens no socket', async () => {
554
+ let release;
555
+ browserFetch(
556
+ (call) =>
557
+ new Promise((resolve) => {
558
+ release = () => resolve(json({ ticket: 'ticket-9', expiresIn: 30 }));
559
+ if (!call.url.endsWith('/auth/ws-ticket')) resolve(json({ ok: true }));
560
+ }),
561
+ );
562
+
563
+ realtime.setSiteNotificationsSubscription(true);
564
+ await until(() => typeof release === 'function', 'the ticket request');
565
+ realtime.setSiteNotificationsSubscription(false);
566
+ release();
567
+ await new Promise((resolve) => setTimeout(resolve, 50));
568
+
569
+ expect(FakeSocket.instances).toHaveLength(0);
570
+ });
571
+
572
+ test('a refused ticket for a logged-out visitor stops the loop without a socket', async () => {
573
+ const calls = browserFetch((call) => json({ error: { code: 'UNAUTHORIZED' } }, 401));
574
+
575
+ realtime.setSiteNotificationsSubscription(true);
576
+ await until(() => calls.some((call) => call.url.endsWith('/notifications/quick')), 'the auth probe');
577
+ await new Promise((resolve) => setTimeout(resolve, 1200));
578
+
579
+ expect(FakeSocket.instances).toHaveLength(0);
580
+ expect(calls.filter((call) => call.url.endsWith('/auth/ws-ticket'))).toHaveLength(1);
581
+ });
582
+ });