99/**
1010 * Ratchet — a request that sends the session cookie (`credentials: 'include'`)
1111 * goes through the console's authenticated fetch, never the bare global
12- * `fetch`, in app-shell and the console.
12+ * `fetch`, in the console and in every `ui/packages/*` source tree (app-shell,
13+ * and since objectstack#37225 the renderer packages beside it).
1314 *
1415 * The defect this closes: a bare `fetch('/api/…', { credentials: 'include' })`
1516 * carries the session cookie and nothing else. A session held by its bearer
2728 * fallback of `??` / `||`), and `sharedGetJson` without its transport argument
2829 * (its default is the global `fetch`), when the init it is handed — written
2930 * inline, or a `const` of this file named as the argument — carries
30- * `credentials: 'include'`. The URL is not judged: a request to another origin
31- * that must not see the bearer is an allow-list row with that reason.
31+ * `credentials: 'include'`. The URL is not judged there : a request to another
32+ * origin that must not see the bearer is an allow-list row with that reason.
3233 *
33- * If this fails on a new call: route it through `createAuthenticatedFetch`
34- * (`{ sameOriginOnly: true }` when the URL is author-written and may name
35- * another host). If the call must stay bare, add a row to {@link ALLOWED} with
36- * the reason. If it fails on a row: a row whose count went down is shrunk or
37- * deleted in the same change. ⛔ Never raise a count to make room.
34+ * Also bare (objectstack#37225): the global `fetch` on a written `/api/` path
35+ * with NO init, or an inline init that names no `credentials` — the default
36+ * `same-origin` credentials send the cookie alone just the same. Here the URL is
37+ * the only evidence the request is the server's, so it has to be written out.
38+ *
39+ * The renderer packages (`components`, `fields`, `plugin-*`, …) do not import
40+ * `@object-ui/auth`: their channel is the host's authenticated fetch, handed
41+ * down as `SchemaRendererProvider`'s `apiFetch` (the console's is
42+ * `createAuthenticatedFetch({ sameOriginOnly: true })`), read straight off
43+ * `SchemaRendererContext` and falling back to the global `fetch` only in a host
44+ * that mounts none. App-shell and the console build `createAuthenticatedFetch`
45+ * per call.
46+ *
47+ * If this fails on a new call: route it through the host's `apiFetch` (a
48+ * renderer package) or `createAuthenticatedFetch` (app-shell, the console;
49+ * `{ sameOriginOnly: true }` when the URL is author-written and may name another
50+ * host). If the call must stay bare, add a row to {@link ALLOWED} with the
51+ * reason. If it fails on a row: a row whose count went down is shrunk or deleted
52+ * in the same change. ⛔ Never raise a count to make room.
3853 */
3954
4055import { describe , it , expect } from 'vitest' ;
41- import { readdirSync , readFileSync } from 'node:fs' ;
56+ import { existsSync , readdirSync , readFileSync } from 'node:fs' ;
4257import path from 'node:path' ;
4358import { fileURLToPath } from 'node:url' ;
4459import ts from 'typescript' ;
4560
4661const HERE = path . dirname ( fileURLToPath ( import . meta. url ) ) ;
4762/** `ui/packages/app-shell/src` */
4863const APP_SHELL_SRC = HERE ;
64+ /** `ui/packages`, whose every package's `src` is scanned. */
65+ const PACKAGES_ROOT = path . resolve ( HERE , '../..' ) ;
4966/** `ui/apps/console/src` */
5067const CONSOLE_SRC = path . resolve ( HERE , '../../../apps/console/src' ) ;
51- /** Both trees' paths are written relative to `ui/`. */
68+ /** Every tree's paths are written relative to `ui/`. */
5269const UI_ROOT = path . resolve ( HERE , '../../..' ) ;
5370
71+ /**
72+ * The renderer packages objectstack#37225 named: each must be read, so a scan
73+ * that silently lost one of them fails here rather than passing over it.
74+ */
75+ const RENDERER_PACKAGES = [
76+ 'components' ,
77+ 'fields' ,
78+ 'permissions' ,
79+ 'plugin-charts' ,
80+ 'plugin-chatbot' ,
81+ 'plugin-dashboard' ,
82+ 'plugin-detail' ,
83+ 'plugin-grid' ,
84+ 'plugin-report' ,
85+ ] as const ;
86+
5487/**
5588 * The bare cookie-only calls left, per file, with the reason each stays.
5689 * SHRINK-ONLY: a row's count only goes down, a row only goes away.
5790 */
5891const ALLOWED : Readonly < Record < string , { count : number ; reason : string } > > = {
59- 'apps/console/src/LocalizationFetchProvider.tsx' : {
60- count : 1 ,
61- reason :
62- 'the boot read of `/api/v1/auth/me/localization`, shared in flight with the language seed and the early ' +
63- 'request `index.html` sends, by a key built from this init; a session it cannot see reads ' +
64- '`authenticated: false` and falls back to the browser language rather than failing. Its transport is its own decision.' ,
65- } ,
6692 'apps/console/src/components/FormPage.tsx' : {
6793 count : 1 ,
6894 reason : 'the channel is the bare global fetch on the PUBLIC form route on purpose; the internal route hands the authenticated fetch.' ,
@@ -121,6 +147,16 @@ const ALLOWED: Readonly<Record<string, { count: number; reason: string }>> = {
121147 count : 1 ,
122148 reason : 'the test request of an `api` action preview, sent to the author-written target; its transport is not decided here.' ,
123149 } ,
150+ 'packages/auth/src/LoginForm.tsx' : {
151+ count : 1 ,
152+ reason : 'the SSO sign-in request, sent before a session, and so a bearer, exists.' ,
153+ } ,
154+ 'packages/permissions/src/MePermissionsProvider.tsx' : {
155+ count : 1 ,
156+ reason :
157+ 'the fallback of the injected `fetcher` (`fetcher ?? fetch`): the console hands its authenticated fetch ' +
158+ '(`AppContent`), and a host that hands none has only the cookie. The package depends on `@object-ui/types` alone.' ,
159+ } ,
124160} ;
125161
126162const GLOBAL_FETCH = new Set ( [ 'fetch' , 'window.fetch' , 'globalThis.fetch' , 'self.fetch' ] ) ;
@@ -165,6 +201,33 @@ function isGlobalFetchCallee(callee: ts.Expression, sf: ts.SourceFile): boolean
165201 return false ;
166202}
167203
204+ /** A URL written out as a literal, read only for whether it names an `/api/` path. */
205+ function namesApiPath ( node : ts . Expression | undefined ) : boolean {
206+ if ( ! node ) return false ;
207+ const n = unwrap ( node ) ;
208+ if ( ts . isStringLiteralLike ( n ) ) return n . text . includes ( '/api/' ) ;
209+ if ( ts . isTemplateExpression ( n ) ) {
210+ return [ n . head . text , ...n . templateSpans . map ( ( span ) => span . literal . text ) ] . some ( ( part ) => part . includes ( '/api/' ) ) ;
211+ }
212+ return false ;
213+ }
214+
215+ /** No init, or an inline one with no `credentials` key: the default `same-origin`, the cookie alone. */
216+ function defaultsCredentials ( init : ts . Expression | undefined ) : boolean {
217+ if ( ! init ) return true ;
218+ const n = unwrap ( init ) ;
219+ return (
220+ ts . isObjectLiteralExpression ( n ) &&
221+ ! n . properties . some (
222+ ( p ) =>
223+ ts . isSpreadAssignment ( p ) ||
224+ ( ( ts . isPropertyAssignment ( p ) || ts . isShorthandPropertyAssignment ( p ) ) &&
225+ ( ts . isIdentifier ( p . name ) || ts . isStringLiteral ( p . name ) ) &&
226+ p . name . text === 'credentials' ) ,
227+ )
228+ ) ;
229+ }
230+
168231/** The bare cookie-only calls in one source text, as `line :: call` strings. */
169232function bareCookieOnlyCalls ( fileName : string , text : string ) : string [ ] {
170233 const sf = ts . createSourceFile (
@@ -194,6 +257,7 @@ function bareCookieOnlyCalls(fileName: string, text: string): string[] {
194257 if ( ts . isCallExpression ( n ) ) {
195258 const bare =
196259 ( isGlobalFetchCallee ( n . expression , sf ) && initIncludes ( n . arguments [ 1 ] ) ) ||
260+ ( isGlobalFetchCallee ( n . expression , sf ) && namesApiPath ( n . arguments [ 0 ] ) && defaultsCredentials ( n . arguments [ 1 ] ) ) ||
197261 ( unwrap ( n . expression ) . getText ( sf ) === 'sharedGetJson' && n . arguments . length < 3 && initIncludes ( n . arguments [ 1 ] ) ) ;
198262 if ( bare ) {
199263 const line = sf . getLineAndCharacterOfPosition ( n . getStart ( sf ) ) . line + 1 ;
@@ -220,19 +284,40 @@ function sourceFiles(root: string): string[] {
220284 return out ;
221285}
222286
287+ /** Every `ui/packages/<name>/src` that exists, by package directory name. */
288+ function packageSourceRoots ( ) : Map < string , string > {
289+ const roots = new Map < string , string > ( ) ;
290+ for ( const entry of readdirSync ( PACKAGES_ROOT , { withFileTypes : true } ) ) {
291+ if ( ! entry . isDirectory ( ) ) continue ;
292+ const src = path . join ( PACKAGES_ROOT , entry . name , 'src' ) ;
293+ if ( existsSync ( src ) ) roots . set ( entry . name , src ) ;
294+ }
295+ return roots ;
296+ }
297+
298+ let scanned : Map < string , string [ ] > | undefined ;
299+
300+ /** The whole scan, once per run: two cases read it. */
223301function scan ( ) : Map < string , string [ ] > {
302+ if ( scanned ) return scanned ;
224303 const found = new Map < string , string [ ] > ( ) ;
225- for ( const file of [ ...sourceFiles ( APP_SHELL_SRC ) , ...sourceFiles ( CONSOLE_SRC ) ] ) {
304+ const files = [ ...[ ...packageSourceRoots ( ) . values ( ) ] . flatMap ( sourceFiles ) , ...sourceFiles ( CONSOLE_SRC ) ] ;
305+ for ( const file of files ) {
226306 const calls = bareCookieOnlyCalls ( file , readFileSync ( file , 'utf8' ) ) ;
227307 if ( calls . length ) found . set ( path . relative ( UI_ROOT , file ) . split ( path . sep ) . join ( '/' ) , calls ) ;
228308 }
309+ scanned = found ;
229310 return found ;
230311}
231312
232- describe ( 'cookie-only same-server fetch ratchet (app-shell + console)' , ( ) => {
233- it ( 'reads both trees (guards a broken scan path)' , ( ) => {
313+ describe ( 'cookie-only same-server fetch ratchet (every ui package + console)' , ( ) => {
314+ it ( 'reads every tree (guards a broken scan path)' , ( ) => {
234315 expect ( sourceFiles ( APP_SHELL_SRC ) . length ) . toBeGreaterThan ( 500 ) ;
235316 expect ( sourceFiles ( CONSOLE_SRC ) . length ) . toBeGreaterThan ( 100 ) ;
317+ const roots = packageSourceRoots ( ) ;
318+ expect ( roots . size ) . toBeGreaterThan ( 30 ) ;
319+ const unread = RENDERER_PACKAGES . filter ( ( name ) => ! roots . has ( name ) || sourceFiles ( roots . get ( name ) ! ) . length === 0 ) ;
320+ expect ( unread ) . toEqual ( [ ] ) ;
236321 } ) ;
237322
238323 it ( 'the detector sees every bare spelling, and none of the authenticated ones' , ( ) => {
@@ -249,7 +334,16 @@ describe('cookie-only same-server fetch ratchet (app-shell + console)', () => {
249334 [ "await (apiFetch ?? createAuthenticatedFetch())('/api/v1/x', { credentials: 'include' });" , 0 ] ,
250335 [ "await sharedGetJson(u, { credentials: 'include' }, authFetch);" , 0 ] ,
251336 [ "await fetch('https://cdn.example.com/a.json', { credentials: 'omit' });" , 0 ] ,
252- [ "await fetch('/api/v1/x');" , 0 ] ,
337+ // No init, or no `credentials`, on a written `/api/` path: the cookie alone (objectstack#37225).
338+ [ "await fetch('/api/v1/x');" , 1 ] ,
339+ [ 'await fetch(`/api/v1/objects/${name}/fields`);' , 1 ] ,
340+ [ "await window.fetch(`${base}/api/v1/x`, { method: 'POST', headers: h });" , 1 ] ,
341+ [ "await fetch('/api/v1/x', { credentials: 'same-origin' });" , 0 ] ,
342+ [ "await fetch('/api/v1/x', { ...init });" , 0 ] ,
343+ [ "await fetch(url);" , 0 ] ,
344+ [ "await fetch('https://cdn.example.com/a.json');" , 0 ] ,
345+ [ "await authFetch('/api/v1/x');" , 0 ] ,
346+ [ "await doFetch(`/api/v1/objects/${name}/fields`);" , 0 ] ,
253347 ] ;
254348 for ( const [ code , expected ] of cases ) {
255349 // Inside an async function: at a script's top level `await (x)(…)` parses as a call of `await`.
0 commit comments