create-stitchkit 0.6.17 → 0.6.18

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 (35) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/examples/repository/packages/frontend/src/app/[locale]/page.tsx +2 -0
  3. package/examples/repository/packages/frontend/src/app/[locale]/starter-page.tsx +12 -8
  4. package/examples/repository/project.json +9 -0
  5. package/package.json +2 -2
  6. package/template/README.md +7 -0
  7. package/template/_env.example +5 -0
  8. package/template/docs/ADMIN_MOCK.md +38 -0
  9. package/template/package.json +1 -0
  10. package/template/packages/backend/src/index.ts +2 -1
  11. package/template/packages/backend/src/surface.ts +7 -6
  12. package/template/packages/backend/src/trusted-origins.test.ts +40 -0
  13. package/template/packages/backend/src/trusted-origins.ts +21 -0
  14. package/template/packages/config/src/variables.ts +16 -1
  15. package/template/packages/frontend/next.config.ts +10 -1
  16. package/template/packages/frontend/src/app/[locale]/admin/[[...section]]/page.dev.tsx +21 -0
  17. package/template/packages/frontend/src/app/[locale]/page.tsx +2 -1
  18. package/template/packages/frontend/src/app/[locale]/starter-page.tsx +12 -8
  19. package/template/packages/frontend/src/app/api/[...path]/route.ts +2 -37
  20. package/template/packages/frontend/src/app/sitemap.ts +4 -1
  21. package/template/packages/frontend/src/env.ts +11 -1
  22. package/template/packages/frontend/src/features/admin/admin-data.ts +13 -0
  23. package/template/packages/frontend/src/features/admin/admin-sections.ts +78 -0
  24. package/template/packages/frontend/src/features/admin/admin-workspace.test.tsx +59 -0
  25. package/template/packages/frontend/src/features/admin/admin-workspace.tsx +127 -0
  26. package/template/packages/frontend/src/features/admin/fixture/admin-fixture.ts +35 -0
  27. package/template/packages/frontend/src/lib/api-proxy.test.ts +131 -0
  28. package/template/packages/frontend/src/lib/api-proxy.ts +89 -0
  29. package/template/packages/frontend/src/proxy.ts +12 -1
  30. package/template/project.json +9 -0
  31. package/template/scripts/acceptance-local.ts +8 -1
  32. package/template/scripts/fixture-boundary.test.ts +34 -0
  33. package/template/scripts/fixture-boundary.ts +25 -0
  34. package/template/scripts/service-surfaces-closed.ts +13 -0
  35. package/template/scripts/web-surface-smoke.ts +33 -0
package/CHANGELOG.md CHANGED
@@ -12,6 +12,21 @@ step is overwritten by the next release.
12
12
 
13
13
  ## [Unreleased]
14
14
 
15
+ ## [0.6.18] - 2026-11-02
16
+
17
+ ### Added
18
+
19
+ - `/en/admin`: an admin panel on fixture for development, with sections, roles, a table and a dialog, and no
20
+ database. A production build drops it and its rows, which `bun run acceptance:local` proves on the built
21
+ files. [`docs/ADMIN_MOCK.md`](template/docs/ADMIN_MOCK.md) holds its addresses and the way off fixture.
22
+
23
+ ### Fixed
24
+
25
+ - The web role's `/api` forwarding keeps a session and a download: `cookie`, `origin`, each `set-cookie`,
26
+ `content-disposition`, `content-length` and `location` now pass.
27
+ - The component catalogue and `/openapi.json` answer 404 in production unless the deployment sets
28
+ `SERVICE_SURFACES=open`. `bun run acceptance:local` proves both answers on one artifact.
29
+
15
30
  ## [0.6.17] - 2026-10-20
16
31
 
17
32
  ### Changed
@@ -2,6 +2,7 @@ import { appDeclaration } from '@app/config/declaration';
2
2
  import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
3
3
  import type { Metadata } from 'next';
4
4
  import { getTranslations } from 'next-intl/server';
5
+ import { catalogueIsOpen } from '@/env';
5
6
  import { LocaleSchema } from '@/i18n/locales';
6
7
  import { publicRealtimeOrigin } from '@/lib/api/place';
7
8
  import { useRepository } from '@/lib/api/queries';
@@ -39,6 +40,7 @@ export default async function Page({ params }: { params: Promise<{ locale: strin
39
40
  applicationDescription={appDeclaration.identity.description[appLocale]}
40
41
  heroTitle={t('heroTitle')}
41
42
  catalogueLabel={t('ui')}
43
+ catalogueOpen={catalogueIsOpen()}
42
44
  locale={appLocale}
43
45
  realtimeOrigin={publicRealtimeOrigin()}
44
46
  />
@@ -16,6 +16,7 @@ interface StarterPageProps {
16
16
  applicationDescription: string;
17
17
  heroTitle: string;
18
18
  catalogueLabel: string;
19
+ catalogueOpen: boolean;
19
20
  realtimeOrigin?: string;
20
21
  locale: AppLocale;
21
22
  }
@@ -64,6 +65,7 @@ export async function StarterPage({
64
65
  applicationDescription,
65
66
  heroTitle,
66
67
  catalogueLabel,
68
+ catalogueOpen,
67
69
  realtimeOrigin,
68
70
  locale,
69
71
  }: StarterPageProps) {
@@ -90,14 +92,16 @@ export async function StarterPage({
90
92
  <div className='flex items-center gap-2'>
91
93
  <LanguageSwitcher />
92
94
  <ThemeToggle />
93
- <Link
94
- aria-label={catalogueLabel}
95
- className={cn(buttonVariants({ variant: 'outline', size: 'sm' }))}
96
- href='/ui'
97
- >
98
- <span className='hidden sm:inline'>{catalogueLabel}</span>
99
- <IconArrowUpRight />
100
- </Link>
95
+ {catalogueOpen ? (
96
+ <Link
97
+ aria-label={catalogueLabel}
98
+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }))}
99
+ href='/ui'
100
+ >
101
+ <span className='hidden sm:inline'>{catalogueLabel}</span>
102
+ <IconArrowUpRight />
103
+ </Link>
104
+ ) : null}
101
105
  </div>
102
106
  </header>
103
107
 
@@ -184,6 +184,15 @@
184
184
  "shape": "url",
185
185
  "required": false
186
186
  },
187
+ {
188
+ "name": "SERVICE_SURFACES",
189
+ "shape": "enum",
190
+ "required": false,
191
+ "members": [
192
+ "open",
193
+ "closed"
194
+ ]
195
+ },
187
196
  {
188
197
  "name": "TRUSTED_HOSTS",
189
198
  "shape": "string",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-stitchkit",
3
- "version": "0.6.17",
3
+ "version": "0.6.18",
4
4
  "description": "Create a production-shaped Stitchkit application",
5
5
  "license": "MIT",
6
6
  "author": "Max Listov <maxlistov@gmail.com>",
@@ -84,7 +84,7 @@
84
84
  "@types/react": "^19.3.0",
85
85
  "ai": "^7.0.111",
86
86
  "react": "^19.3.0",
87
- "stitchkit": "0.111.3",
87
+ "stitchkit": "0.117.0",
88
88
  "typescript": "^7.0.2"
89
89
  },
90
90
  "engines": {
@@ -45,6 +45,8 @@ database migrations you add and launches:
45
45
 
46
46
  - Web: <http://localhost:3210>
47
47
  - UI catalogue: <http://localhost:3210/en/ui>
48
+ - Admin panel on fixture, development only: <http://localhost:3210/en/admin>
49
+ ([how to take it off fixture](docs/ADMIN_MOCK.md))
48
50
  - API: <http://localhost:3211>
49
51
  - OpenAPI: <http://localhost:3211/openapi.json>
50
52
  - MCP: <http://localhost:3211/mcp>
@@ -84,6 +86,9 @@ server-delivered address, a client built on first use (hence the parentheses),
84
86
  an ordering requirement relative to `<Providers>`, and `CORS_ORIGIN` on the API
85
87
  role.
86
88
 
89
+ In production the catalogue and `/openapi.json` answer 404 unless the deployment
90
+ sets `SERVICE_SURFACES=open`; `bun run acceptance:local` proves both answers.
91
+
87
92
  The `/en/ui` catalogue is isolated under
88
93
  `packages/frontend/src/app/[locale]/ui` and can be removed as one directory;
89
94
  reusable primitives remain in `components/ui`. It renders the complete
@@ -131,6 +136,8 @@ runtime:smoke` / `bun run e2e` directly. `runtime:smoke` asks the web role to
131
136
  answer as two of the addresses `PUBLIC_WEB_HOSTS` claims, to prove one artifact
132
137
  serves many; a deployment claiming fewer than two addresses besides the one
133
138
  being dialled is told exactly what to add rather than failing on a refused host.
139
+ Both read the catalogue or `/openapi.json`, so that deployment needs
140
+ `SERVICE_SURFACES=open` while they run.
134
141
 
135
142
  ## Requirements
136
143
 
@@ -23,6 +23,11 @@ SMOKE_WEB_ORIGIN=http://127.0.0.1:3210
23
23
  PUBLIC_WEB_HOSTS=127.0.0.1:3210
24
24
  LOG_FORMAT=pretty
25
25
 
26
+ # `/en/ui` and `/openapi.json` answer 404 in production and stay open otherwise.
27
+ # `open` keeps them on a production deployment that wants them; leave it unset
28
+ # anywhere else.
29
+ # SERVICE_SURFACES=open
30
+
26
31
  # The web role reaches the API role internally, and forwards the browser's
27
32
  # same-origin `/api/…` calls to it (packages/frontend/src/app/api/[...path]).
28
33
  INTERNAL_API_URL=http://127.0.0.1:3211
@@ -0,0 +1,38 @@
1
+ # The admin panel on fixture
2
+
3
+ `/en/admin` shows the shape of a future admin panel before any of its API exists: sections, roles, tables
4
+ and dialogs, on invented rows and with no database. A customer sees the system and answers questions
5
+ about it before the first migration.
6
+
7
+ It exists in development only. Its route is `app/[locale]/admin/[[...section]]/page.dev.tsx`, and `.dev.tsx`
8
+ is a page extension of the development server alone (`next.config.ts`), so a production build has no such
9
+ route: the address answers 404 and the rows are not in the artifact.
10
+ `bun run acceptance:local` proves that on the built files (`scripts/fixture-boundary.ts`).
11
+
12
+ ## Addresses
13
+
14
+ | Address | Section | Read | Write | Status |
15
+ |---|---|---|---|---|
16
+ | `/admin` | Records | `records.read` | `records.write` | `mock` |
17
+ | `/admin/people` | People | `people.read` | `people.write` | `mock` |
18
+
19
+ `features/admin/admin-sections.ts` is the source of this table. Keep them in step.
20
+
21
+ ## Changing it
22
+
23
+ Rename the sections and the columns of `AdminRow` to your domain, in `admin-sections.ts`, `admin-data.ts`
24
+ and `fixture/admin-fixture.ts`. `adminPermissions` must decide every role against every operation, and the
25
+ role buttons in the sidebar switch between them for a demonstration only: they prove nothing to a server.
26
+
27
+ ## Taking a section off fixture
28
+
29
+ 1. Build the vertical slice by [`ADDING_A_FEATURE.md`](ADDING_A_FEATURE.md), answering `AdminRow`.
30
+ 2. Enforce the same operation on the server, with `adminPermissions` moved to `packages/shared` so both sides
31
+ read one matrix.
32
+ 3. Set the section's `status` to `live`, supply its rows from the API, and rename the route to `page.tsx`, which
33
+ production builds. Keep a section that is still `mock` behind a page of its own in `page.dev.tsx`.
34
+ 4. Delete its rows from the fixture.
35
+
36
+ When no section is `mock`, delete `features/admin/fixture/`, `scripts/fixture-boundary.ts` and its acceptance
37
+ step. If the panel is not wanted at all, delete `features/admin` and
38
+ `app/[locale]/admin` as two directories, with the same script and step.
@@ -33,6 +33,7 @@
33
33
  "cli": "bun packages/backend/src/cli.ts",
34
34
  "tools": "bun packages/backend/src/tools.ts",
35
35
  "runtime:smoke": "bun scripts/runtime-smoke.ts",
36
+ "surfaces:closed": "bun scripts/service-surfaces-closed.ts",
36
37
  "surface:snapshot": "bun scripts/surface-snapshot.ts",
37
38
  "e2e": "playwright test",
38
39
  "acceptance:local": "bun scripts/acceptance-local.ts",
@@ -1,5 +1,6 @@
1
1
  import { env } from '@app/config';
2
2
  import { apiRole, appDeclaration } from '@app/config/declaration';
3
+ import { serviceSurfacesAreOpen } from '@app/config/variables';
3
4
  import { wrapInRequestContext } from 'stitchkit/observability';
4
5
  import {
5
6
  bindProcessSignals,
@@ -44,7 +45,7 @@ async function main(): Promise<void> {
44
45
  logging: { format: env.LOG_FORMAT },
45
46
  socket,
46
47
  rawRoutes: [
47
- openApiRoute('/openapi.json', openApi),
48
+ ...(serviceSurfacesAreOpen(env) ? [openApiRoute('/openapi.json', openApi)] : []),
48
49
  createMcpHttpRoute({ path: '/mcp', handler: mcp }),
49
50
  {
50
51
  method: 'GET',
@@ -4,6 +4,7 @@ import { type BoardRuntime, openBoard } from './lib/board';
4
4
  import { bindLive } from './lib/live';
5
5
  import { createBoardService } from './transport/board-service';
6
6
  import { createSystemService } from './transport/system-service';
7
+ import { trustedBrowserAuthorities } from './trusted-origins';
7
8
 
8
9
  /**
9
10
  * The fence this deployment answers behind, or nothing.
@@ -13,15 +14,15 @@ import { createSystemService } from './transport/system-service';
13
14
  * Unset means no fence, which is honest for a checkout on a laptop and wrong for
14
15
  * anything a network can reach.
15
16
  *
16
- * The browser origin is the one already declared for CORS. They answer different
17
- * questions — CORS says what a page may *read*, the fence says which authority
18
- * this server agreed to *answer on* — but a deployment that names a cross-origin
19
- * browser has named it once, and asking twice is asking for two answers that
20
- * disagree.
17
+ * The browser origins are the ones already declared, for CORS and for the web
18
+ * role. They answer different questions — CORS says what a page may *read*, the
19
+ * fence says which authority this server agreed to *answer on* — but a deployment
20
+ * that names its browser has named it once, and asking twice is asking for two
21
+ * answers that disagree.
21
22
  */
22
23
  function createFence(): TrustFence | undefined {
23
24
  if (!env.TRUSTED_HOSTS) return undefined;
24
- const browserOrigin = env.CORS_ORIGIN ? [new URL(env.CORS_ORIGIN).host] : [];
25
+ const browserOrigin = trustedBrowserAuthorities(env);
25
26
  return createTrustFence({
26
27
  trustedHosts: env.TRUSTED_HOSTS.split(',').map((entry) => entry.trim()),
27
28
  ...(browserOrigin.length > 0 && { trustedOrigins: browserOrigin }),
@@ -0,0 +1,40 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { createTrustFence } from 'stitchkit/server';
3
+ import { trustedBrowserAuthorities } from './trusted-origins';
4
+
5
+ function proxied(origin: string): Request {
6
+ return new Request('http://127.0.0.1:3211/api/board', {
7
+ method: 'POST',
8
+ headers: { host: '127.0.0.1:3211', origin },
9
+ });
10
+ }
11
+
12
+ describe('a fenced API role behind the web role', () => {
13
+ const fence = createTrustFence({
14
+ trustedHosts: ['127.0.0.1:3211'],
15
+ trustedOrigins: trustedBrowserAuthorities({
16
+ PUBLIC_WEB_HOSTS: 'app.example, www.app.example:8443',
17
+ }),
18
+ });
19
+
20
+ test('admits a browser on an address the deployment claims', () => {
21
+ expect(fence.check(proxied('https://app.example'), 'http')).toBeUndefined();
22
+ expect(fence.check(proxied('https://www.app.example:8443'), 'http')).toBeUndefined();
23
+ });
24
+
25
+ test('refuses a page anywhere else', () => {
26
+ expect(fence.check(proxied('https://evil.example'), 'http')?.reason).toBe(
27
+ 'origin-mismatch',
28
+ );
29
+ });
30
+
31
+ test('names each declared host once', () => {
32
+ expect(
33
+ trustedBrowserAuthorities({
34
+ CORS_ORIGIN: 'https://app.example',
35
+ PUBLIC_WEB_ORIGIN: 'https://app.example',
36
+ PUBLIC_WEB_HOSTS: 'app.example,other.example',
37
+ }),
38
+ ).toEqual(['app.example', 'other.example']);
39
+ });
40
+ });
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The browser origins a fenced API role admits, all of them already declared.
3
+ *
4
+ * A browser on the web role's own address reaches this role through the `/api`
5
+ * forwarding, so its request arrives with that address as `Origin` and the
6
+ * internal one as `Host`. Those disagree by construction, and only the public
7
+ * hosts the deployment claims can tell it from a forged page.
8
+ */
9
+ export function trustedBrowserAuthorities(env: {
10
+ CORS_ORIGIN?: string | undefined;
11
+ PUBLIC_WEB_ORIGIN?: string | undefined;
12
+ PUBLIC_WEB_HOSTS?: string | undefined;
13
+ }): string[] {
14
+ const authorities = [
15
+ ...[env.CORS_ORIGIN, env.PUBLIC_WEB_ORIGIN].flatMap((origin) =>
16
+ origin ? [new URL(origin).host] : [],
17
+ ),
18
+ ...(env.PUBLIC_WEB_HOSTS ?? '').split(',').map((host) => host.trim()),
19
+ ];
20
+ return [...new Set(authorities.filter((host) => host !== ''))];
21
+ }
@@ -17,8 +17,22 @@ import { featureServerSchema } from './features';
17
17
  * Defaults, coercion and error messages live here and only here. The
18
18
  * declaration carries names and shapes; it deliberately carries no values.
19
19
  */
20
+ /** The one reading of `SERVICE_SURFACES`, for both roles. */
21
+ export function serviceSurfacesAreOpen(env: {
22
+ NODE_ENV?: string | undefined;
23
+ SERVICE_SURFACES?: 'open' | 'closed' | undefined;
24
+ }): boolean {
25
+ return env.SERVICE_SURFACES ? env.SERVICE_SURFACES === 'open' : env.NODE_ENV !== 'production';
26
+ }
27
+
20
28
  const baseVariables = {
21
29
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
30
+ /**
31
+ * The component catalogue and `/openapi.json`: they describe how this
32
+ * application is built, so production answers 404 for them unless it says
33
+ * `open`, which is what a deployment under acceptance does.
34
+ */
35
+ SERVICE_SURFACES: z.enum(['open', 'closed']).optional(),
22
36
  DATABASE_URL: z.url(),
23
37
  // Loopback by default — exposing the app to the network is an explicit
24
38
  // opt-in (`BIND_HOST=0.0.0.0`), never something a forgotten edit causes.
@@ -86,7 +100,8 @@ const baseVariables = {
86
100
  * and the realtime handshake, which never reaches a lifecycle hook on either
87
101
  * runtime. Unset and there is no fence, which is honest for a local checkout
88
102
  * and wrong for anything reachable from a network — a fence cannot invent the
89
- * list of names it should answer to.
103
+ * list of names it should answer to. A browser reaching this role through the
104
+ * web role is admitted by its address in `PUBLIC_WEB_HOSTS` or `PUBLIC_WEB_ORIGIN`.
90
105
  */
91
106
  TRUSTED_HOSTS: z.string().min(1).optional(),
92
107
  };
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import type { NextConfig } from 'next';
3
+ import { PHASE_DEVELOPMENT_SERVER } from 'next/constants';
3
4
  import createNextIntlPlugin from 'next-intl/plugin';
4
5
 
5
6
  const config: NextConfig = {
@@ -16,4 +17,12 @@ const config: NextConfig = {
16
17
  images: { remotePatterns: [] },
17
18
  };
18
19
 
19
- export default createNextIntlPlugin()(config);
20
+ /**
21
+ * A `page.dev.tsx` exists for the development server alone, so what it imports
22
+ * is absent from a production build rather than guarded inside it.
23
+ */
24
+ export default function nextConfig(phase: string): NextConfig {
25
+ const pageExtensions =
26
+ phase === PHASE_DEVELOPMENT_SERVER ? ['dev.tsx', 'tsx', 'ts'] : ['tsx', 'ts'];
27
+ return createNextIntlPlugin()({ ...config, pageExtensions });
28
+ }
@@ -0,0 +1,21 @@
1
+ import { notFound } from 'next/navigation';
2
+ import { sectionAt } from '@/features/admin/admin-sections';
3
+ import { AdminWorkspace } from '@/features/admin/admin-workspace';
4
+ import { adminFixture } from '@/features/admin/fixture/admin-fixture';
5
+
6
+ /**
7
+ * `.dev.tsx` is a page extension of the development server only (`next.config.ts`),
8
+ * so a production build has no such route and nothing here enters its graph.
9
+ * `scripts/fixture-boundary.ts` proves that on the built files. Once a section
10
+ * reads the API, name this file `page.tsx` and drop the fixture import.
11
+ */
12
+ export default async function AdminPage({
13
+ params,
14
+ }: {
15
+ params: Promise<{ section?: string[] }>;
16
+ }) {
17
+ const { section: segments = [] } = await params;
18
+ const section = segments.length > 1 ? undefined : sectionAt(segments[0]);
19
+ if (!section) notFound();
20
+ return <AdminWorkspace section={section} data={adminFixture} />;
21
+ }
@@ -1,7 +1,7 @@
1
1
  import { appIdentity } from '@app/config/app-identity';
2
2
  import type { Metadata } from 'next';
3
3
  import { getTranslations } from 'next-intl/server';
4
- import { env } from '@/env';
4
+ import { catalogueIsOpen, env } from '@/env';
5
5
  import { LocaleSchema } from '@/i18n/locales';
6
6
  import { createPageMetadata } from '@/lib/seo/metadata';
7
7
  import { StarterPage } from './starter-page';
@@ -28,6 +28,7 @@ export default async function Page({ params }: { params: Promise<{ locale: strin
28
28
  applicationDescription={appIdentity.description[appLocale]}
29
29
  heroTitle={t('heroTitle')}
30
30
  catalogueLabel={t('ui')}
31
+ catalogueOpen={catalogueIsOpen()}
31
32
  locale={appLocale}
32
33
  realtimeOrigin={env.PUBLIC_REALTIME_ORIGIN}
33
34
  />
@@ -15,6 +15,7 @@ interface StarterPageProps {
15
15
  applicationDescription: string;
16
16
  heroTitle: string;
17
17
  catalogueLabel: string;
18
+ catalogueOpen: boolean;
18
19
  realtimeOrigin?: string;
19
20
  locale: AppLocale;
20
21
  }
@@ -63,6 +64,7 @@ export async function StarterPage({
63
64
  applicationDescription,
64
65
  heroTitle,
65
66
  catalogueLabel,
67
+ catalogueOpen,
66
68
  realtimeOrigin,
67
69
  locale,
68
70
  }: StarterPageProps) {
@@ -89,14 +91,16 @@ export async function StarterPage({
89
91
  <div className='flex items-center gap-2'>
90
92
  <LanguageSwitcher />
91
93
  <ThemeToggle />
92
- <Link
93
- aria-label={catalogueLabel}
94
- className={cn(buttonVariants({ variant: 'outline', size: 'sm' }))}
95
- href='/ui'
96
- >
97
- <span className='hidden sm:inline'>{catalogueLabel}</span>
98
- <IconArrowUpRight />
99
- </Link>
94
+ {catalogueOpen ? (
95
+ <Link
96
+ aria-label={catalogueLabel}
97
+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }))}
98
+ href='/ui'
99
+ >
100
+ <span className='hidden sm:inline'>{catalogueLabel}</span>
101
+ <IconArrowUpRight />
102
+ </Link>
103
+ ) : null}
100
104
  </div>
101
105
  </header>
102
106
 
@@ -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
  }
@@ -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
 
@@ -26,6 +26,7 @@ export const env = createEnv({
26
26
  INTERNAL_API_URL: applicationVariables.INTERNAL_API_URL,
27
27
  PUBLIC_API_ORIGIN: applicationVariables.PUBLIC_API_ORIGIN,
28
28
  PUBLIC_REALTIME_ORIGIN: applicationVariables.PUBLIC_REALTIME_ORIGIN,
29
+ SERVICE_SURFACES: applicationVariables.SERVICE_SURFACES,
29
30
  },
30
31
  runtimeEnv: {
31
32
  BIND_HOST: process.env.BIND_HOST,
@@ -35,6 +36,15 @@ export const env = createEnv({
35
36
  INTERNAL_API_URL: process.env.INTERNAL_API_URL,
36
37
  PUBLIC_API_ORIGIN: process.env.PUBLIC_API_ORIGIN,
37
38
  PUBLIC_REALTIME_ORIGIN: process.env.PUBLIC_REALTIME_ORIGIN,
39
+ SERVICE_SURFACES: process.env.SERVICE_SURFACES,
38
40
  },
39
41
  emptyStringAsUndefined: true,
40
42
  });
43
+
44
+ /** Read per request: a build runs without the deployment's environment. */
45
+ export function catalogueIsOpen(): boolean {
46
+ return serviceSurfacesAreOpen({
47
+ NODE_ENV: process.env.NODE_ENV,
48
+ SERVICE_SURFACES: env.SERVICE_SURFACES,
49
+ });
50
+ }
@@ -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
+ }
@@ -1,6 +1,17 @@
1
+ import { type NextRequest, NextResponse } from 'next/server';
1
2
  import createMiddleware from 'next-intl/middleware';
3
+ import { catalogueIsOpen } from './env';
2
4
  import { routing } from './i18n/routing';
3
5
 
4
- export default createMiddleware(routing);
6
+ const localized = createMiddleware(routing);
7
+ const CATALOGUE = new RegExp(`^/(?:${routing.locales.join('|')})/ui(?:/|$)`);
8
+
9
+ /** Decided at the door, per request, so one check covers every page of the catalogue. */
10
+ export default function proxy(request: NextRequest): NextResponse {
11
+ if (CATALOGUE.test(request.nextUrl.pathname) && !catalogueIsOpen()) {
12
+ return new NextResponse(null, { status: 404 });
13
+ }
14
+ return localized(request);
15
+ }
5
16
 
6
17
  export const config = { matcher: ['/', '/(en|ru)/:path*'] };
@@ -164,6 +164,15 @@
164
164
  "shape": "url",
165
165
  "required": false
166
166
  },
167
+ {
168
+ "name": "SERVICE_SURFACES",
169
+ "shape": "enum",
170
+ "required": false,
171
+ "members": [
172
+ "open",
173
+ "closed"
174
+ ]
175
+ },
167
176
  {
168
177
  "name": "TRUSTED_HOSTS",
169
178
  "shape": "string",
@@ -78,6 +78,9 @@ for (const [name, value] of Object.entries(base)) {
78
78
  delete environment.ACCEPTANCE_DATABASE_URL;
79
79
  Object.assign(environment, {
80
80
  NODE_ENV: 'production',
81
+ // The gates read the catalogue and the OpenAPI document; the closed default is
82
+ // proved after them, on the same artifact.
83
+ SERVICE_SURFACES: 'open',
81
84
  // The one address every role, every migration and every gate here will see.
82
85
  DATABASE_URL: acceptanceDatabaseUrl,
83
86
  PM2_HOME: home,
@@ -106,8 +109,12 @@ try {
106
109
  await awaitRolesAnswering(declaredRoleReadiness(appDeclaration, environment));
107
110
  await run(['bun', 'run', 'runtime:smoke'], environment);
108
111
  await run(['bun', 'run', 'e2e'], environment);
112
+ const closed = { ...environment, SERVICE_SURFACES: 'closed' };
113
+ await run(['pm2', 'restart', 'ecosystem.config.cjs', '--update-env'], closed);
114
+ await awaitRolesAnswering(declaredRoleReadiness(appDeclaration, closed));
115
+ await run(['bun', 'run', 'surfaces:closed'], closed);
109
116
  console.log(
110
- `Local acceptance passed: ${appDeclaration.roles.map((role) => role.name).join(' and ')} answered on ephemeral ports, and both runtime gates are green`,
117
+ `Local acceptance passed: ${appDeclaration.roles.map((role) => role.name).join(' and ')} answered on ephemeral ports, both runtime gates are green, and the service surfaces close`,
111
118
  );
112
119
  } catch (error) {
113
120
  failure = { error };
@@ -0,0 +1,34 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { assertNoFixtureInBuild } from './fixture-boundary';
6
+
7
+ async function buildWith(content: string | undefined): Promise<string> {
8
+ const root = await mkdtemp(join(tmpdir(), 'fixture-boundary-'));
9
+ if (content !== undefined) {
10
+ await mkdir(join(root, '.next/server/app'), { recursive: true });
11
+ await writeFile(join(root, '.next/server/app/page.js'), content);
12
+ }
13
+ return root;
14
+ }
15
+
16
+ describe('assertNoFixtureInBuild', () => {
17
+ test('a clean build passes', async () => {
18
+ const root = await buildWith('export const page = 1');
19
+ await assertNoFixtureInBuild(root);
20
+ await rm(root, { recursive: true });
21
+ });
22
+
23
+ test('a build that carries the fixture is named', async () => {
24
+ const root = await buildWith('const m = "stitchkit-admin-fixture"');
25
+ await expect(assertNoFixtureInBuild(root)).rejects.toThrow('.next/server/app/page.js');
26
+ await rm(root, { recursive: true });
27
+ });
28
+
29
+ test('a build with no files is not a clean build', async () => {
30
+ const root = await buildWith(undefined);
31
+ await expect(assertNoFixtureInBuild(root)).rejects.toThrow('no built files');
32
+ await rm(root, { recursive: true });
33
+ });
34
+ });
@@ -0,0 +1,25 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { Glob } from 'bun';
4
+
5
+ /** The prefix of every row id in `features/admin/fixture`: data, so a bundler cannot drop it. */
6
+ const FIXTURE_MARKER = 'stitchkit-admin-fixture';
7
+
8
+ /**
9
+ * The fixture has to be absent from what a deployment serves, and only the built
10
+ * files can say so: a guard in the source proves intent, and a bundler that keeps
11
+ * the branch would still ship the rows. A build with no files is a wrong build,
12
+ * not a clean one.
13
+ */
14
+ export async function assertNoFixtureInBuild(webRoot: string): Promise<void> {
15
+ const root = join(webRoot, '.next');
16
+ if (!existsSync(root)) throw new Error(`${root} holds no built files to inspect`);
17
+ let inspected = 0;
18
+ for await (const path of new Glob('{server,static}/**/*.{js,map,json,html,rsc}').scan(root)) {
19
+ inspected += 1;
20
+ if ((await Bun.file(join(root, path)).text()).includes(FIXTURE_MARKER)) {
21
+ throw new Error(`.next/${path} carries the admin fixture`);
22
+ }
23
+ }
24
+ if (inspected === 0) throw new Error(`${root} holds no built files to inspect`);
25
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * What a production deployment does not show, checked on a running one with
3
+ * `SERVICE_SURFACES=closed` and on the files it was built from.
4
+ */
5
+ import { join, resolve } from 'node:path';
6
+ import { assertNoFixtureInBuild } from './fixture-boundary';
7
+ import { loadToolingEnv } from './tooling-env';
8
+ import { assertServiceSurfacesClosed } from './web-surface-smoke';
9
+
10
+ const toolingEnv = loadToolingEnv();
11
+ await assertServiceSurfacesClosed(toolingEnv.SMOKE_WEB_ORIGIN, toolingEnv.SMOKE_API_ORIGIN);
12
+ await assertNoFixtureInBuild(join(resolve(import.meta.dir, '..'), 'packages/frontend'));
13
+ console.log('Service surfaces are closed, and the build carries no fixture');
@@ -39,6 +39,39 @@ export async function assertPublicWebSurface(webOrigin: string): Promise<void> {
39
39
  }
40
40
  }
41
41
 
42
+ /** The paths a production deployment hides, with what still has to answer beside them. */
43
+ export async function assertServiceSurfacesClosed(
44
+ webOrigin: string,
45
+ apiOrigin: string,
46
+ ): Promise<void> {
47
+ const home = await dial(publicUrl(webOrigin, '/en'));
48
+ if (home.status !== 200) throw new Error(`GET /en returned ${home.status}`);
49
+ const health = await dial(publicUrl(apiOrigin, '/health'));
50
+ if (health.status !== 200)
51
+ throw new Error(`GET ${apiOrigin}/health returned ${health.status}`);
52
+ const closed = [
53
+ ...[
54
+ '/ui',
55
+ '/starter',
56
+ '/en/ui',
57
+ '/en/ui/components',
58
+ '/ru/ui/themes',
59
+ '/en/admin',
60
+ '/en/admin/people',
61
+ '/openapi.json',
62
+ ].map((path) => publicUrl(webOrigin, path)),
63
+ publicUrl(apiOrigin, '/openapi.json'),
64
+ ];
65
+ for (const url of closed) {
66
+ const response = await dial(url);
67
+ if (response.status !== 404) throw new Error(`GET ${url} returned ${response.status}`);
68
+ }
69
+ const sitemap = await dial(publicUrl(webOrigin, SITEMAP_PATH));
70
+ if ((await sitemap.text()).includes('/ui/')) {
71
+ throw new Error(`GET ${SITEMAP_PATH} still lists the closed catalogue`);
72
+ }
73
+ }
74
+
42
75
  /** What the deployment has been told about the addresses it serves. */
43
76
  export interface PublicHostPolicy {
44
77
  /** `PUBLIC_WEB_ORIGIN` — a single public address, stated outright. */