create-stitchkit 0.6.17 → 0.6.19

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 (80) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/cli.js +62 -27
  3. package/examples/repository/packages/frontend/src/app/[locale]/page.tsx +2 -0
  4. package/examples/repository/packages/frontend/src/app/[locale]/starter-page.tsx +12 -8
  5. package/examples/repository/project.json +9 -0
  6. package/package.json +10 -9
  7. package/template/README.md +7 -0
  8. package/template/_env.example +5 -0
  9. package/template/biome.json +4 -1
  10. package/template/bun.lock +303 -301
  11. package/template/docs/ADMIN_MOCK.md +38 -0
  12. package/template/e2e/starter.spec.ts +2 -2
  13. package/template/package.json +17 -16
  14. package/template/packages/backend/package.json +6 -6
  15. package/template/packages/backend/src/cleanup.ts +4 -7
  16. package/template/packages/backend/src/index.ts +2 -1
  17. package/template/packages/backend/src/surface-manifest.test.ts +3 -3
  18. package/template/packages/backend/src/surface.ts +7 -6
  19. package/template/packages/backend/src/trusted-origins.test.ts +40 -0
  20. package/template/packages/backend/src/trusted-origins.ts +21 -0
  21. package/template/packages/config/package.json +3 -3
  22. package/template/packages/config/src/shutdown.ts +3 -4
  23. package/template/packages/config/src/variables.ts +21 -9
  24. package/template/packages/db/package.json +4 -4
  25. package/template/packages/frontend/next.config.ts +10 -1
  26. package/template/packages/frontend/package.json +29 -29
  27. package/template/packages/frontend/scripts/serve.ts +4 -4
  28. package/template/packages/frontend/src/app/[locale]/admin/[[...section]]/page.dev.tsx +21 -0
  29. package/template/packages/frontend/src/app/[locale]/page.tsx +2 -1
  30. package/template/packages/frontend/src/app/[locale]/starter-page.tsx +12 -8
  31. package/template/packages/frontend/src/app/api/[...path]/route.ts +2 -37
  32. package/template/packages/frontend/src/app/sitemap.ts +4 -1
  33. package/template/packages/frontend/src/components/ui/toaster.tsx +2 -2
  34. package/template/packages/frontend/src/env.ts +12 -3
  35. package/template/packages/frontend/src/features/admin/admin-data.ts +13 -0
  36. package/template/packages/frontend/src/features/admin/admin-sections.ts +78 -0
  37. package/template/packages/frontend/src/features/admin/admin-workspace.test.tsx +59 -0
  38. package/template/packages/frontend/src/features/admin/admin-workspace.tsx +127 -0
  39. package/template/packages/frontend/src/features/admin/fixture/admin-fixture.ts +35 -0
  40. package/template/packages/frontend/src/lib/api-proxy.test.ts +131 -0
  41. package/template/packages/frontend/src/lib/api-proxy.ts +89 -0
  42. package/template/packages/frontend/src/lib/query-client.test.ts +1 -1
  43. package/template/packages/frontend/src/lib/query-client.ts +2 -3
  44. package/template/packages/frontend/src/lib/seo/cache-by-origin.ts +2 -2
  45. package/template/packages/frontend/src/lib/seo/request-origin.ts +5 -5
  46. package/template/packages/frontend/src/proxy.ts +12 -1
  47. package/template/packages/shared/package.json +2 -2
  48. package/template/packages/shared/src/contracts/board.ts +1 -3
  49. package/template/packages/shared/src/contracts/system.ts +1 -3
  50. package/template/project.json +9 -0
  51. package/template/scripts/acceptance-database.test.ts +4 -4
  52. package/template/scripts/acceptance-database.ts +4 -6
  53. package/template/scripts/acceptance-local.ts +14 -9
  54. package/template/scripts/build-stamp.test.ts +3 -5
  55. package/template/scripts/build-stamp.ts +8 -11
  56. package/template/scripts/check-authored.test.ts +16 -1
  57. package/template/scripts/check-authored.ts +7 -6
  58. package/template/scripts/client-boundary.test.ts +26 -8
  59. package/template/scripts/client-boundary.ts +30 -27
  60. package/template/scripts/declaration.test.ts +5 -7
  61. package/template/scripts/declaration.ts +14 -19
  62. package/template/scripts/deployment-preflight.ts +2 -3
  63. package/template/scripts/dev.ts +6 -8
  64. package/template/scripts/fixture-boundary.test.ts +34 -0
  65. package/template/scripts/fixture-boundary.ts +25 -0
  66. package/template/scripts/guide-paths.ts +2 -4
  67. package/template/scripts/readiness.ts +4 -5
  68. package/template/scripts/release-steps.test.ts +2 -4
  69. package/template/scripts/release-steps.ts +2 -2
  70. package/template/scripts/runtime-smoke.test.ts +6 -7
  71. package/template/scripts/serve-mode.test.ts +2 -2
  72. package/template/scripts/service-surfaces-closed.ts +13 -0
  73. package/template/scripts/shutdown-budget.fixture.ts +3 -5
  74. package/template/scripts/shutdown-budget.test.ts +4 -8
  75. package/template/scripts/supervision-signal.test.ts +1 -1
  76. package/template/scripts/web-surface-smoke.ts +38 -8
  77. package/templates/agent/biome.json +4 -1
  78. package/templates/agent/package.json +11 -7
  79. package/templates/telegram-bot/biome.json +4 -1
  80. package/templates/telegram-bot/package.json +8 -4
@@ -1,4 +1,5 @@
1
1
  import { env } from '@/env';
2
+ import { forwardToApi } from '@/lib/api-proxy';
2
3
 
3
4
  /**
4
5
  * The default shape: the browser talks to its OWN origin, and the web role
@@ -19,14 +20,6 @@ import { env } from '@/env';
19
20
  */
20
21
  export const dynamic = 'force-dynamic';
21
22
 
22
- const FORWARDED_REQUEST_HEADERS = [
23
- 'accept',
24
- 'accept-language',
25
- 'content-type',
26
- 'authorization',
27
- ];
28
- const FORWARDED_RESPONSE_HEADERS = ['content-type', 'cache-control', 'etag'];
29
-
30
23
  async function forward(request: Request): Promise<Response> {
31
24
  const apiUrl = env.INTERNAL_API_URL;
32
25
  if (!apiUrl) {
@@ -36,35 +29,7 @@ async function forward(request: Request): Promise<Response> {
36
29
  { status: 503 },
37
30
  );
38
31
  }
39
- const incoming = new URL(request.url);
40
- // Rebuilt from the incoming pathname rather than from the matched segments,
41
- // so an encoded segment reaches the API role exactly as it arrived.
42
- const target = new URL(`${incoming.pathname}${incoming.search}`, apiUrl);
43
-
44
- const headers = new Headers();
45
- for (const name of FORWARDED_REQUEST_HEADERS) {
46
- const value = request.headers.get(name);
47
- if (value !== null) headers.set(name, value);
48
- }
49
-
50
- // Buffered rather than streamed: forwarding a stream needs the non-standard
51
- // `duplex` init that this project's types do not carry, and every payload
52
- // this contract accepts is a small JSON document.
53
- const hasBody = request.method !== 'GET' && request.method !== 'HEAD';
54
- const response = await fetch(target, {
55
- method: request.method,
56
- headers,
57
- body: hasBody ? await request.arrayBuffer() : undefined,
58
- // A redirect is the API role's answer, not something to resolve here.
59
- redirect: 'manual',
60
- });
61
-
62
- const responseHeaders = new Headers();
63
- for (const name of FORWARDED_RESPONSE_HEADERS) {
64
- const value = response.headers.get(name);
65
- if (value !== null) responseHeaders.set(name, value);
66
- }
67
- return new Response(response.body, { status: response.status, headers: responseHeaders });
32
+ return await forwardToApi(request, apiUrl);
68
33
  }
69
34
 
70
35
  export const GET = forward;
@@ -1,4 +1,5 @@
1
1
  import type { MetadataRoute } from 'next';
2
+ import { catalogueIsOpen } from '@/env';
2
3
  import { sitemapForOrigin } from '@/lib/seo/metadata';
3
4
  import { requestOrigin } from '@/lib/seo/request-origin';
4
5
 
@@ -6,5 +7,7 @@ import { requestOrigin } from '@/lib/seo/request-origin';
6
7
  // this response is served on, and that is not known until the request arrives.
7
8
  // The entries themselves are built once per origin, not once per request.
8
9
  export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
9
- return sitemapForOrigin(await requestOrigin());
10
+ const entries = await sitemapForOrigin(await requestOrigin());
11
+ if (catalogueIsOpen()) return entries;
12
+ return entries.filter((entry) => !new URL(entry.url).pathname.includes('/ui/'));
10
13
  }
@@ -38,9 +38,9 @@ export const toast = {
38
38
  };
39
39
 
40
40
  export function Toaster() {
41
- // No explicit type argument: since @wrksz/themes 1.2 the parameter describes
41
+ // No explicit type argument: the parameter describes
42
42
  // the MAP, not the value, and it infers `const` — so naming the value union
43
- // here made the result every member of `string` instead of narrowing it.
43
+ // here would widen the result to `string` instead of preserving the literals.
44
44
  const theme = useThemeValue({
45
45
  light: 'light',
46
46
  dark: 'dark',
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { applicationVariables } from '@app/config/variables';
2
+ import { applicationVariables, serviceSurfacesAreOpen } from '@app/config/variables';
3
3
  import { createEnv } from '@t3-oss/env-nextjs';
4
4
  import { config } from 'dotenv';
5
5
 
@@ -11,8 +11,7 @@ config({ path: path.resolve(process.cwd(), '../../.env'), quiet: true });
11
11
  *
12
12
  * There is deliberately NO `client` block. A `NEXT_PUBLIC_` variable is
13
13
  * substituted at BUILD time, so declaring one freezes a value of the place into
14
- * the artifact — the built server chunk once carried
15
- * `NEXT_PUBLIC_API_URL:"http://…"` as a literal while a plain `WEB_PORT` stayed
14
+ * the artifact: `NEXT_PUBLIC_API_URL:"http://…"` becomes a literal while a plain `WEB_PORT` stays
16
15
  * a runtime read. Anything the browser needs is either relative (so it needs no
17
16
  * address at all), derived from the request, or read on the server and handed
18
17
  * down per request — never compiled in.
@@ -26,6 +25,7 @@ export const env = createEnv({
26
25
  INTERNAL_API_URL: applicationVariables.INTERNAL_API_URL,
27
26
  PUBLIC_API_ORIGIN: applicationVariables.PUBLIC_API_ORIGIN,
28
27
  PUBLIC_REALTIME_ORIGIN: applicationVariables.PUBLIC_REALTIME_ORIGIN,
28
+ SERVICE_SURFACES: applicationVariables.SERVICE_SURFACES,
29
29
  },
30
30
  runtimeEnv: {
31
31
  BIND_HOST: process.env.BIND_HOST,
@@ -35,6 +35,15 @@ export const env = createEnv({
35
35
  INTERNAL_API_URL: process.env.INTERNAL_API_URL,
36
36
  PUBLIC_API_ORIGIN: process.env.PUBLIC_API_ORIGIN,
37
37
  PUBLIC_REALTIME_ORIGIN: process.env.PUBLIC_REALTIME_ORIGIN,
38
+ SERVICE_SURFACES: process.env.SERVICE_SURFACES,
38
39
  },
39
40
  emptyStringAsUndefined: true,
40
41
  });
42
+
43
+ /** Read per request: a build runs without the deployment's environment. */
44
+ export function catalogueIsOpen(): boolean {
45
+ return serviceSurfacesAreOpen({
46
+ NODE_ENV: process.env.NODE_ENV,
47
+ SERVICE_SURFACES: env.SERVICE_SURFACES,
48
+ });
49
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * What the panel renders, with nothing about where it comes from. A section's
3
+ * fixture and its API answer have this one shape, so moving a section to the API
4
+ * changes what supplies the rows and no component.
5
+ */
6
+ export interface AdminRow {
7
+ id: string;
8
+ title: string;
9
+ owner: string;
10
+ state: 'active' | 'paused';
11
+ }
12
+
13
+ export type AdminData = Readonly<Record<string, readonly AdminRow[]>>;
@@ -0,0 +1,78 @@
1
+ import { definePermissionMatrix } from 'stitchkit/primitives';
2
+
3
+ /**
4
+ * The admin panel as data: what sections exist, where they live, who may do what
5
+ * and whether a section still runs on fixture. `docs/ADMIN_MOCK.md` is this table
6
+ * for a reader, and a section leaves it for real by turning `live`.
7
+ */
8
+ export const adminPermissions = definePermissionMatrix({
9
+ roles: ['owner', 'manager', 'viewer'],
10
+ operations: ['records.read', 'records.write', 'people.read', 'people.write'],
11
+ grants: {
12
+ owner: {
13
+ 'records.read': true,
14
+ 'records.write': true,
15
+ 'people.read': true,
16
+ 'people.write': true,
17
+ },
18
+ manager: {
19
+ 'records.read': true,
20
+ 'records.write': true,
21
+ 'people.read': true,
22
+ 'people.write': false,
23
+ },
24
+ viewer: {
25
+ 'records.read': true,
26
+ 'records.write': false,
27
+ 'people.read': false,
28
+ 'people.write': false,
29
+ },
30
+ },
31
+ });
32
+
33
+ export type AdminRole = (typeof adminPermissions.definition.roles)[number];
34
+ export type AdminOperation = (typeof adminPermissions.definition.operations)[number];
35
+
36
+ export interface AdminSection {
37
+ id: string;
38
+ /** Under `/admin`; the first section is also the panel's own address. */
39
+ path: string;
40
+ label: string;
41
+ read: AdminOperation;
42
+ write: AdminOperation;
43
+ /** `mock` reads `fixture/`; `live` reads the API. */
44
+ status: 'mock' | 'live';
45
+ }
46
+
47
+ export const adminSections: readonly AdminSection[] = [
48
+ {
49
+ id: 'records',
50
+ path: '/admin',
51
+ label: 'Records',
52
+ read: 'records.read',
53
+ write: 'records.write',
54
+ status: 'mock',
55
+ },
56
+ {
57
+ id: 'people',
58
+ path: '/admin/people',
59
+ label: 'People',
60
+ read: 'people.read',
61
+ write: 'people.write',
62
+ status: 'mock',
63
+ },
64
+ ];
65
+
66
+ export function sectionAt(segment: string | undefined): AdminSection | undefined {
67
+ const path = segment === undefined ? '/admin' : `/admin/${segment}`;
68
+ return adminSections.find((section) => section.path === path);
69
+ }
70
+
71
+ export function sectionsFor(role: AdminRole): readonly AdminSection[] {
72
+ return adminSections.filter((section) => adminPermissions.allows(role, section.read));
73
+ }
74
+
75
+ /** By id: a section that crossed from a server component is a copy. */
76
+ export function canOpen(role: AdminRole, section: AdminSection): boolean {
77
+ return sectionsFor(role).some(({ id }) => id === section.id);
78
+ }
@@ -0,0 +1,59 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { renderToStaticMarkup } from 'react-dom/server';
3
+ import {
4
+ adminPermissions,
5
+ adminSections,
6
+ canOpen,
7
+ sectionAt,
8
+ sectionsFor,
9
+ } from './admin-sections';
10
+ import { AdminSectionView } from './admin-workspace';
11
+ import { adminFixture } from './fixture/admin-fixture';
12
+
13
+ function rendered(sectionId: string, role: 'owner' | 'manager' | 'viewer'): string {
14
+ const section = adminSections.find(({ id }) => id === sectionId);
15
+ if (!section) throw new Error(`no section ${sectionId}`);
16
+ return renderToStaticMarkup(
17
+ <AdminSectionView section={section} rows={adminFixture[section.id] ?? []} role={role} />,
18
+ );
19
+ }
20
+
21
+ describe('the admin panel on fixture', () => {
22
+ test('a section renders its rows from the fixture alone, with no database', () => {
23
+ const page = rendered('records', 'owner');
24
+ expect(page).toContain('First record');
25
+ expect(page).toContain('Fixture');
26
+ expect(page).toContain('Edit');
27
+ });
28
+
29
+ test('a role without the write operation has no action', () => {
30
+ expect(rendered('records', 'viewer')).not.toContain('Edit');
31
+ expect(rendered('people', 'manager')).not.toContain('Edit');
32
+ });
33
+
34
+ test('a role sees only the sections it may read', () => {
35
+ expect(sectionsFor('viewer').map(({ id }) => id)).toEqual(['records']);
36
+ expect(sectionsFor('owner').map(({ id }) => id)).toEqual(['records', 'people']);
37
+ });
38
+
39
+ test('a section that crossed from the server opens like the original', () => {
40
+ const copy = structuredClone(sectionAt('people'));
41
+ if (!copy) throw new Error('no people section');
42
+ expect(canOpen('owner', copy)).toBe(true);
43
+ expect(canOpen('viewer', copy)).toBe(false);
44
+ });
45
+
46
+ test('every section has its fixture, and every operation it names exists', () => {
47
+ for (const section of adminSections) {
48
+ expect(adminFixture[section.id]?.length).toBeGreaterThan(0);
49
+ expect(adminPermissions.check('owner', section.read).outcome).toBe('allowed');
50
+ expect(adminPermissions.check('owner', section.write).outcome).toBe('allowed');
51
+ }
52
+ });
53
+
54
+ test('an address resolves to one section or to none', () => {
55
+ expect(sectionAt(undefined)?.id).toBe('records');
56
+ expect(sectionAt('people')?.id).toBe('people');
57
+ expect(sectionAt('missing')).toBeUndefined();
58
+ });
59
+ });
@@ -0,0 +1,127 @@
1
+ 'use client';
2
+
3
+ import { IconFileText, IconUsers } from '@tabler/icons-react';
4
+ import { useState } from 'react';
5
+ import {
6
+ AdaptiveModal,
7
+ Badge,
8
+ Button,
9
+ Field,
10
+ Input,
11
+ Sidebar,
12
+ Table,
13
+ TableBody,
14
+ TableCell,
15
+ TableHead,
16
+ TableHeader,
17
+ TableRow,
18
+ } from '@/components/ui';
19
+ import type { AdminData, AdminRow } from './admin-data';
20
+ import {
21
+ type AdminRole,
22
+ type AdminSection,
23
+ adminPermissions,
24
+ canOpen,
25
+ sectionsFor,
26
+ } from './admin-sections';
27
+
28
+ const ICONS: Record<string, typeof IconFileText> = { records: IconFileText, people: IconUsers };
29
+
30
+ /** One section's table and its edit dialog. A role without `write` sees no action. */
31
+ export function AdminSectionView({
32
+ section,
33
+ rows,
34
+ role,
35
+ }: {
36
+ section: AdminSection;
37
+ rows: readonly AdminRow[];
38
+ role: AdminRole;
39
+ }) {
40
+ const [editing, setEditing] = useState<AdminRow | undefined>();
41
+ const canWrite = adminPermissions.allows(role, section.write);
42
+ return (
43
+ <section className='min-w-0'>
44
+ <div className='mb-6 flex items-center justify-between gap-4'>
45
+ <h1 className='text-2xl font-medium'>{section.label}</h1>
46
+ {section.status === 'mock' ? <Badge variant='warning'>Fixture</Badge> : null}
47
+ </div>
48
+ <Table>
49
+ <TableHeader>
50
+ <TableRow>
51
+ <TableHead>Title</TableHead>
52
+ <TableHead>Owner</TableHead>
53
+ <TableHead>State</TableHead>
54
+ {canWrite ? <TableHead /> : null}
55
+ </TableRow>
56
+ </TableHeader>
57
+ <TableBody>
58
+ {rows.map((row) => (
59
+ <TableRow key={row.id}>
60
+ <TableCell>{row.title}</TableCell>
61
+ <TableCell>{row.owner}</TableCell>
62
+ <TableCell>{row.state}</TableCell>
63
+ {canWrite ? (
64
+ <TableCell className='text-right'>
65
+ <Button size='sm' variant='outline' onClick={() => setEditing(row)}>
66
+ Edit
67
+ </Button>
68
+ </TableCell>
69
+ ) : null}
70
+ </TableRow>
71
+ ))}
72
+ </TableBody>
73
+ </Table>
74
+ <AdaptiveModal
75
+ isOpen={editing !== undefined}
76
+ onClose={() => setEditing(undefined)}
77
+ title={editing?.title ?? ''}
78
+ footer={<Button onClick={() => setEditing(undefined)}>Close</Button>}
79
+ >
80
+ <div className='px-4 pb-2'>
81
+ <Field label='Title' htmlFor='admin-row-title'>
82
+ <Input id='admin-row-title' defaultValue={editing?.title} key={editing?.id} />
83
+ </Field>
84
+ </div>
85
+ </AdaptiveModal>
86
+ </section>
87
+ );
88
+ }
89
+
90
+ export function AdminWorkspace({ section, data }: { section: AdminSection; data: AdminData }) {
91
+ const [role, setRole] = useState<AdminRole>('owner');
92
+ const visible = sectionsFor(role);
93
+ return (
94
+ <div className='relative flex min-h-dvh bg-background'>
95
+ <Sidebar
96
+ logo='Admin'
97
+ mobileBreakpoint='md'
98
+ navigation={visible.map(({ id, label, path }) => ({
99
+ name: label,
100
+ href: path,
101
+ icon: ICONS[id] ?? IconFileText,
102
+ }))}
103
+ footer={
104
+ <div className='flex flex-wrap gap-1 p-2'>
105
+ {adminPermissions.definition.roles.map((name) => (
106
+ <Button
107
+ key={name}
108
+ size='sm'
109
+ variant={name === role ? 'primary' : 'ghost'}
110
+ onClick={() => setRole(name)}
111
+ >
112
+ {name}
113
+ </Button>
114
+ ))}
115
+ </div>
116
+ }
117
+ />
118
+ <main className='min-w-0 flex-1 p-5 md:p-8'>
119
+ {canOpen(role, section) ? (
120
+ <AdminSectionView section={section} rows={data[section.id] ?? []} role={role} />
121
+ ) : (
122
+ <p className='text-muted-foreground'>This role cannot open {section.label}.</p>
123
+ )}
124
+ </main>
125
+ </div>
126
+ );
127
+ }
@@ -0,0 +1,35 @@
1
+ import type { AdminData } from '../admin-data';
2
+
3
+ /**
4
+ * Invented rows, for showing the panel before its API exists. This directory is
5
+ * reached only from the development-only `page.dev.tsx`. Their ids are what
6
+ * `scripts/fixture-boundary.ts` looks for in a production build: keep the prefix
7
+ * on rows you add, or that check has nothing to find.
8
+ */
9
+ export const adminFixture: AdminData = {
10
+ records: [
11
+ {
12
+ id: 'stitchkit-admin-fixture-r-1',
13
+ title: 'First record',
14
+ owner: 'Anna',
15
+ state: 'active',
16
+ },
17
+ {
18
+ id: 'stitchkit-admin-fixture-r-2',
19
+ title: 'Second record',
20
+ owner: 'Boris',
21
+ state: 'active',
22
+ },
23
+ {
24
+ id: 'stitchkit-admin-fixture-r-3',
25
+ title: 'Third record',
26
+ owner: 'Anna',
27
+ state: 'paused',
28
+ },
29
+ ],
30
+ people: [
31
+ { id: 'stitchkit-admin-fixture-p-1', title: 'Anna', owner: 'owner', state: 'active' },
32
+ { id: 'stitchkit-admin-fixture-p-2', title: 'Boris', owner: 'manager', state: 'active' },
33
+ { id: 'stitchkit-admin-fixture-p-3', title: 'Vera', owner: 'viewer', state: 'paused' },
34
+ ],
35
+ };
@@ -0,0 +1,131 @@
1
+ import { afterAll, describe, expect, test } from 'bun:test';
2
+ import { forwardToApi } from './api-proxy';
3
+
4
+ const FILE_NAME = 'Счёт №7.xlsx';
5
+ const FILE = new TextEncoder().encode('файл с именем');
6
+ const DISPOSITION = `attachment; filename*=UTF-8''${encodeURIComponent(FILE_NAME)}`;
7
+ const seen = { cookie: '', origin: '', host: '' };
8
+
9
+ const api: Bun.Server<undefined> = Bun.serve({
10
+ port: 0,
11
+ hostname: '127.0.0.1',
12
+ fetch(request): Response {
13
+ const { pathname } = new URL(request.url);
14
+ seen.cookie = request.headers.get('cookie') ?? '';
15
+ seen.origin = request.headers.get('origin') ?? '';
16
+ seen.host = request.headers.get('x-internal') ?? '';
17
+ if (pathname === '/api/login') {
18
+ const headers = new Headers();
19
+ headers.append(
20
+ 'set-cookie',
21
+ 'session=a; HttpOnly; Expires=Wed, 21 Oct 2037 07:28:00 GMT',
22
+ );
23
+ headers.append('set-cookie', 'csrf=b; Path=/');
24
+ return new Response(null, { status: 204, headers });
25
+ }
26
+ if (pathname === '/api/file') {
27
+ return new Response(FILE, {
28
+ headers: {
29
+ 'content-type': 'application/octet-stream',
30
+ 'content-disposition': DISPOSITION,
31
+ 'content-length': String(FILE.byteLength),
32
+ },
33
+ });
34
+ }
35
+ if (pathname === '/api/gzip') {
36
+ return new Response(Bun.gzipSync(new TextEncoder().encode('{"ok":true}')), {
37
+ headers: { 'content-encoding': 'gzip', 'content-type': 'application/json' },
38
+ });
39
+ }
40
+ if (pathname === '/api/absolute') {
41
+ return new Response(null, {
42
+ status: 302,
43
+ headers: { location: `http://127.0.0.1:${api.port}/next?step=2` },
44
+ });
45
+ }
46
+ if (pathname === '/api/outside') {
47
+ return new Response(null, {
48
+ status: 302,
49
+ headers: { location: 'https://provider.example/login' },
50
+ });
51
+ }
52
+ if (pathname === '/api/echo') {
53
+ return new Response(request.body, {
54
+ headers: {
55
+ 'retry-after': '7',
56
+ 'www-authenticate': 'Bearer',
57
+ 'accept-ranges': 'bytes',
58
+ 'content-range': `bytes 0-1/${request.headers.get('range') ?? ''}`,
59
+ },
60
+ });
61
+ }
62
+ return new Response(null, { status: 302, headers: { location: '/elsewhere' } });
63
+ },
64
+ });
65
+ const apiUrl = `http://127.0.0.1:${api.port}`;
66
+ afterAll(() => api.stop(true));
67
+
68
+ function through(path: string, init?: RequestInit): Promise<Response> {
69
+ return forwardToApi(new Request(`http://web.test${path}`, init), apiUrl);
70
+ }
71
+
72
+ describe('the web role forwarding to the API role', () => {
73
+ test('a session reaches the API with its origin', async () => {
74
+ await through('/api/me', {
75
+ headers: {
76
+ cookie: 'session=a',
77
+ origin: 'http://web.test',
78
+ 'x-internal': 'not-forwarded',
79
+ },
80
+ });
81
+ expect(seen).toEqual({ cookie: 'session=a', origin: 'http://web.test', host: '' });
82
+ });
83
+
84
+ test('every cookie comes back as a header of its own', async () => {
85
+ const response = await through('/api/login', { method: 'POST' });
86
+ expect(response.headers.getSetCookie()).toEqual([
87
+ 'session=a; HttpOnly; Expires=Wed, 21 Oct 2037 07:28:00 GMT',
88
+ 'csrf=b; Path=/',
89
+ ]);
90
+ });
91
+
92
+ test('a download keeps a Cyrillic name, its length and its bytes', async () => {
93
+ const response = await through('/api/file');
94
+ expect(response.headers.get('content-disposition')).toBe(DISPOSITION);
95
+ expect(response.headers.get('content-length')).toBe(String(FILE.byteLength));
96
+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(FILE);
97
+ });
98
+
99
+ test('a compressed answer does not carry the length of its compressed form', async () => {
100
+ const response = await through('/api/gzip');
101
+ expect(response.headers.get('content-length')).toBeNull();
102
+ expect(await response.json()).toEqual({ ok: true });
103
+ });
104
+
105
+ test('an upload streams through, and a refusal keeps what it tells the client', async () => {
106
+ const body = new Uint8Array(3_000_000).fill(7);
107
+ const response = await through('/api/echo', {
108
+ method: 'POST',
109
+ body,
110
+ headers: { range: 'bytes=0-1' },
111
+ });
112
+ expect((await response.arrayBuffer()).byteLength).toBe(body.byteLength);
113
+ expect(response.headers.get('retry-after')).toBe('7');
114
+ expect(response.headers.get('www-authenticate')).toBe('Bearer');
115
+ expect(response.headers.get('accept-ranges')).toBe('bytes');
116
+ expect(response.headers.get('content-range')).toBe('bytes 0-1/bytes=0-1');
117
+ });
118
+
119
+ test('a redirect names no internal address', async () => {
120
+ const internal = await through('/api/absolute');
121
+ expect(internal.headers.get('location')).toBe('/next?step=2');
122
+ const outside = await through('/api/outside');
123
+ expect(outside.headers.get('location')).toBe('https://provider.example/login');
124
+ });
125
+
126
+ test('a redirect keeps its target', async () => {
127
+ const response = await through('/api/moved');
128
+ expect(response.status).toBe(302);
129
+ expect(response.headers.get('location')).toBe('/elsewhere');
130
+ });
131
+ });
@@ -0,0 +1,89 @@
1
+ /**
2
+ * What crosses the web role on the way to the API role.
3
+ *
4
+ * An allow-list on purpose: the web role is not a transparent proxy, and a
5
+ * header nobody named stays out. Each name below is what some path of the API
6
+ * needs. `cookie` and `origin` carry a session and its CSRF check, `set-cookie`
7
+ * opens that session, `content-disposition`, `content-length` and the range and
8
+ * validator pairs make a file a resumable download with its name, and
9
+ * `retry-after` and `www-authenticate` are what a refusal tells its client.
10
+ */
11
+ const FORWARDED_REQUEST_HEADERS = [
12
+ 'accept',
13
+ 'accept-language',
14
+ 'content-type',
15
+ 'authorization',
16
+ 'cookie',
17
+ 'origin',
18
+ 'range',
19
+ 'if-none-match',
20
+ 'if-modified-since',
21
+ ];
22
+ const FORWARDED_RESPONSE_HEADERS = [
23
+ 'content-type',
24
+ 'cache-control',
25
+ 'etag',
26
+ 'last-modified',
27
+ 'content-disposition',
28
+ 'content-range',
29
+ 'accept-ranges',
30
+ 'retry-after',
31
+ 'www-authenticate',
32
+ 'x-request-id',
33
+ ];
34
+
35
+ /** The browser has never heard of the internal address, and a bad header is not this role's. */
36
+ function publicLocation(location: string, apiUrl: string): string {
37
+ if (!URL.canParse(location, apiUrl)) return location;
38
+ const redirect = new URL(location, apiUrl);
39
+ return redirect.origin === new URL(apiUrl).origin
40
+ ? `${redirect.pathname}${redirect.search}${redirect.hash}`
41
+ : location;
42
+ }
43
+
44
+ export async function forwardToApi(request: Request, apiUrl: string): Promise<Response> {
45
+ const incoming = new URL(request.url);
46
+ // Rebuilt from the incoming pathname rather than from the matched segments,
47
+ // so an encoded segment reaches the API role exactly as it arrived.
48
+ const target = new URL(`${incoming.pathname}${incoming.search}`, apiUrl);
49
+
50
+ const headers = new Headers();
51
+ for (const name of FORWARDED_REQUEST_HEADERS) {
52
+ const value = request.headers.get(name);
53
+ if (value !== null) headers.set(name, value);
54
+ }
55
+
56
+ // Streamed, so an upload is not held in this role. `duplex` is required with a
57
+ // stream body and absent from the DOM's `RequestInit`. The signal ends the API
58
+ // role's work, a stream included, when the browser goes away.
59
+ const init: RequestInit & { duplex?: 'half' } = {
60
+ method: request.method,
61
+ headers,
62
+ signal: request.signal,
63
+ // A redirect is the API role's answer, not something to resolve here.
64
+ redirect: 'manual',
65
+ };
66
+ if (request.body) {
67
+ init.body = request.body;
68
+ init.duplex = 'half';
69
+ }
70
+ const response = await fetch(target, init);
71
+
72
+ const responseHeaders = new Headers();
73
+ for (const name of FORWARDED_RESPONSE_HEADERS) {
74
+ const value = response.headers.get(name);
75
+ if (value !== null) responseHeaders.set(name, value);
76
+ }
77
+ const location = response.headers.get('location');
78
+ if (location !== null) responseHeaders.set('location', publicLocation(location, apiUrl));
79
+ // One header per cookie: joined by a comma they stop being cookies.
80
+ for (const cookie of response.headers.getSetCookie()) {
81
+ responseHeaders.append('set-cookie', cookie);
82
+ }
83
+ // `fetch` has already decoded a compressed body, so its length is not this one.
84
+ const length = response.headers.get('content-length');
85
+ if (length !== null && !response.headers.has('content-encoding')) {
86
+ responseHeaders.set('content-length', length);
87
+ }
88
+ return new Response(response.body, { status: response.status, headers: responseHeaders });
89
+ }
@@ -23,7 +23,7 @@ describe('query dehydration policy', () => {
23
23
 
24
24
  test('retries a server failure once and never retries a mutation', () => {
25
25
  // Asserted through the decision, not through the literal: the policy is a
26
- // predicate now, and `retry === 1` would pass for a client that retries an
26
+ // predicate, and `retry === 1` would pass for a client that retries an
27
27
  // unauthorized request too.
28
28
  const defaults = getQueryClient().getDefaultOptions();
29
29
  const retry = defaults.queries?.retry;