create-stitchkit 0.6.16 → 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.
- package/CHANGELOG.md +24 -0
- package/examples/repository/packages/frontend/src/app/[locale]/page.tsx +2 -0
- package/examples/repository/packages/frontend/src/app/[locale]/starter-page.tsx +12 -8
- package/examples/repository/project.json +9 -0
- package/package.json +2 -2
- package/template/README.md +7 -0
- package/template/_env.example +5 -0
- package/template/bun.lock +2 -2
- package/template/docs/ADMIN_MOCK.md +38 -0
- package/template/package.json +2 -1
- package/template/packages/backend/src/index.ts +2 -1
- package/template/packages/backend/src/surface.ts +7 -6
- package/template/packages/backend/src/trusted-origins.test.ts +40 -0
- package/template/packages/backend/src/trusted-origins.ts +21 -0
- package/template/packages/config/src/variables.ts +16 -1
- package/template/packages/frontend/next.config.ts +10 -1
- package/template/packages/frontend/src/app/[locale]/admin/[[...section]]/page.dev.tsx +21 -0
- package/template/packages/frontend/src/app/[locale]/page.tsx +2 -1
- package/template/packages/frontend/src/app/[locale]/starter-page.tsx +12 -8
- package/template/packages/frontend/src/app/api/[...path]/route.ts +2 -37
- package/template/packages/frontend/src/app/sitemap.ts +4 -1
- package/template/packages/frontend/src/env.ts +11 -1
- package/template/packages/frontend/src/features/admin/admin-data.ts +13 -0
- package/template/packages/frontend/src/features/admin/admin-sections.ts +78 -0
- package/template/packages/frontend/src/features/admin/admin-workspace.test.tsx +59 -0
- package/template/packages/frontend/src/features/admin/admin-workspace.tsx +127 -0
- package/template/packages/frontend/src/features/admin/fixture/admin-fixture.ts +35 -0
- package/template/packages/frontend/src/lib/api-proxy.test.ts +131 -0
- package/template/packages/frontend/src/lib/api-proxy.ts +89 -0
- package/template/packages/frontend/src/proxy.ts +12 -1
- package/template/project.json +9 -0
- package/template/scripts/acceptance-local.ts +8 -1
- package/template/scripts/fixture-boundary.test.ts +34 -0
- package/template/scripts/fixture-boundary.ts +25 -0
- package/template/scripts/service-surfaces-closed.ts +13 -0
- package/template/scripts/web-surface-smoke.ts +33 -0
|
@@ -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
|
-
|
|
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*'] };
|
package/template/project.json
CHANGED
|
@@ -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,
|
|
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');
|