@terreno/admin-backend 58.0.0-beta.1 → 58.0.0-beta.3
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 +93 -0
- package/package.json +11 -4
- package/.claude/CLAUDE.local.md +0 -223
- package/.cursor/rules/00-root.mdc +0 -357
- package/.github/copilot-instructions.md +0 -352
- package/AGENTS.md +0 -358
- package/biome.jsonc +0 -21
- package/bunfig.toml +0 -16
- package/e2e/smoke.ts +0 -246
- package/tsconfig.json +0 -18
- package/tsconfig.typecheck.json +0 -18
package/AGENTS.md
DELETED
|
@@ -1,358 +0,0 @@
|
|
|
1
|
-
# Terreno
|
|
2
|
-
|
|
3
|
-
Terreno is Django/Rails for TypeScript — with universal app support.
|
|
4
|
-
|
|
5
|
-
Terreno is Django/Rails for TypeScript — a batteries-included, full-stack
|
|
6
|
-
framework where the undifferentiated 80% of an app is already written. On the
|
|
7
|
-
backend you get Mongoose models, auto-generated REST APIs, permissions, an admin
|
|
8
|
-
panel, authentication, and an AI service. On the frontend you get one universal
|
|
9
|
-
app — a single React Native codebase that ships to iOS, Android, and web. It is
|
|
10
|
-
built to be driven by AI coding agents from the first prompt to a production
|
|
11
|
-
deploy.
|
|
12
|
-
|
|
13
|
-
- Batteries included — auth, CRUD APIs, admin, permissions, AI, realtime,
|
|
14
|
-
feature flags, and consent are already built, so your code is business logic.
|
|
15
|
-
- Universal by default — one React Native codebase ships to iOS, Android, and
|
|
16
|
-
web. Not a web framework with a mobile bolt-on.
|
|
17
|
-
- AI-native — agents are a first-class client of the framework, not an
|
|
18
|
-
afterthought.
|
|
19
|
-
|
|
20
|
-
## Packages
|
|
21
|
-
|
|
22
|
-
- **api/** - REST API framework built on Express/Mongoose (`@terreno/api`)
|
|
23
|
-
- **ui/** - React Native UI component library (`@terreno/ui`)
|
|
24
|
-
- **syncdb/** - Frontend data layer: local-first collections, request client + generated API hooks, auth session, flags (`@terreno/syncdb`)
|
|
25
|
-
- **admin-backend/** - Admin panel backend plugin for @terreno/api (`@terreno/admin-backend`)
|
|
26
|
-
- **admin-frontend/** - Admin panel frontend screens for @terreno/api backends (`@terreno/admin-frontend`)
|
|
27
|
-
- **mcp-server/** - MCP server for AI assistant integration (`@terreno/mcp`, bins `terreno-mcp` / `terreno-mcp-local`)
|
|
28
|
-
- **demo/** - Demo app for showcasing and testing UI components
|
|
29
|
-
- **example-frontend/** - Example Expo app demonstrating full stack usage
|
|
30
|
-
- **example-backend/** - Example Express backend using @terreno/api
|
|
31
|
-
|
|
32
|
-
## Development
|
|
33
|
-
|
|
34
|
-
Uses [Bun](https://bun.sh/) as the package manager.
|
|
35
|
-
|
|
36
|
-
```bash
|
|
37
|
-
bun install # Install dependencies
|
|
38
|
-
bun run compile # Compile all packages
|
|
39
|
-
bun run lint # Lint all packages
|
|
40
|
-
bun run lint:fix # Fix lint issues
|
|
41
|
-
bun run test # Run tests in api and ui
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
### Package-specific commands
|
|
45
|
-
|
|
46
|
-
```bash
|
|
47
|
-
bun run api:test # Test API package
|
|
48
|
-
bun run ui:test # Test UI package
|
|
49
|
-
bun run demo:start # Start demo app
|
|
50
|
-
bun run frontend:web # Start frontend example
|
|
51
|
-
bun run backend:dev # Start backend example
|
|
52
|
-
bun run mcp:build # Build MCP server
|
|
53
|
-
bun run mcp:start # Start MCP server
|
|
54
|
-
bun run admin-backend:compile # Compile admin backend
|
|
55
|
-
bun run admin-frontend:compile # Compile admin frontend
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
## How the Packages Work Together
|
|
59
|
-
|
|
60
|
-
The three core packages form a complete full-stack framework:
|
|
61
|
-
|
|
62
|
-
```
|
|
63
|
-
BACKEND
|
|
64
|
-
@terreno/api
|
|
65
|
-
- Mongoose models with modelRouter -> CRUD endpoints
|
|
66
|
-
- Built-in auth (JWT + Passport)
|
|
67
|
-
- Automatic OpenAPI spec generation
|
|
68
|
-
|
|
|
69
|
-
/openapi.json
|
|
70
|
-
|
|
|
71
|
-
terreno-syncdb-codegen
|
|
72
|
-
|
|
|
73
|
-
FRONTEND
|
|
74
|
-
@terreno/syncdb
|
|
75
|
-
- Generated request hooks + local-first collection hooks
|
|
76
|
-
- SessionProvider / useSession (Better Auth or JWT)
|
|
77
|
-
- Shared auth provider with refresh on 401
|
|
78
|
-
+
|
|
79
|
-
@terreno/ui
|
|
80
|
-
- React Native components (Box, Button, TextField, etc.)
|
|
81
|
-
- TerrenoProvider for theming
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
### Integration Flow
|
|
85
|
-
|
|
86
|
-
1. **Backend (api)**: Define Mongoose models, use `modelRouter` to create CRUD endpoints with permissions
|
|
87
|
-
2. **OpenAPI Generation**: `setupServer` automatically generates `/openapi.json`
|
|
88
|
-
3. **SDK Codegen**: Frontend runs `bun run sdk` (`terreno-syncdb-codegen --api-out` → `store/apiSdk.ts`) and `bun run sync-sdk` (→ `store/syncDbSdk.ts`)
|
|
89
|
-
4. **Frontend (syncdb + ui)**: Use `useQuery` / `useMutate` for synced collections and generated hooks for other routes. `@terreno/rtk` and Redux were removed in Terreno 58.
|
|
90
|
-
|
|
91
|
-
## Example Apps (Keep These Updated!)
|
|
92
|
-
|
|
93
|
-
The `example-frontend/` and `example-backend/` directories serve as both documentation and integration tests. When adding features to api, ui, or syncdb:
|
|
94
|
-
|
|
95
|
-
1. **Add examples** demonstrating new features
|
|
96
|
-
2. **Update SDK** after backend changes: `cd example-frontend && bun run sdk`
|
|
97
|
-
3. **Verify integration** by running both examples together
|
|
98
|
-
|
|
99
|
-
### Running the Full Stack
|
|
100
|
-
|
|
101
|
-
```bash
|
|
102
|
-
# Terminal 1: Start backend
|
|
103
|
-
bun run backend:dev
|
|
104
|
-
|
|
105
|
-
# Terminal 2: Start frontend
|
|
106
|
-
bun run frontend:web
|
|
107
|
-
```
|
|
108
|
-
|
|
109
|
-
## Code Style
|
|
110
|
-
|
|
111
|
-
### TypeScript/JavaScript
|
|
112
|
-
- Use ES module syntax and TypeScript for all code
|
|
113
|
-
- Prefer interfaces over types; avoid enums, use maps
|
|
114
|
-
- Prefer const arrow functions over `function` keyword
|
|
115
|
-
- Use descriptive variable names with auxiliary verbs (e.g., `isLoading`)
|
|
116
|
-
- Use camelCase directories (e.g., `components/authWizard`)
|
|
117
|
-
- Favor named exports
|
|
118
|
-
- Use the RORO pattern (Receive an Object, Return an Object)
|
|
119
|
-
|
|
120
|
-
### Dates and Time
|
|
121
|
-
- Always use Luxon instead of Date or dayjs
|
|
122
|
-
|
|
123
|
-
### Error Handling
|
|
124
|
-
- Check error conditions at start of functions and return early
|
|
125
|
-
- Limit nested if statements
|
|
126
|
-
- Use multiline syntax with curly braces for all conditionals
|
|
127
|
-
|
|
128
|
-
### Testing
|
|
129
|
-
- Use bun test with expect for testing
|
|
130
|
-
|
|
131
|
-
### Logging
|
|
132
|
-
- Frontend: Use `console.info`, `console.debug`, `console.warn`, or `console.error` for permanent logs
|
|
133
|
-
- Backend: Use `logger.info/warn/error/debug` for permanent logs
|
|
134
|
-
- Use `console.log` only for debugging (to be removed)
|
|
135
|
-
|
|
136
|
-
### Development Practices
|
|
137
|
-
- Don't apologize for errors: fix them
|
|
138
|
-
- Prioritize modularity, DRY, performance, and security
|
|
139
|
-
- Focus on readability over performance
|
|
140
|
-
- Write complete, functional code without TODOs when possible
|
|
141
|
-
- Comments should describe purpose, not effect
|
|
142
|
-
|
|
143
|
-
## Package Reference
|
|
144
|
-
|
|
145
|
-
### @terreno/api
|
|
146
|
-
|
|
147
|
-
REST API framework providing:
|
|
148
|
-
|
|
149
|
-
- **modelRouter**: Auto-generates CRUD endpoints for Mongoose models
|
|
150
|
-
- **Permissions**: `IsAuthenticated`, `IsOwner`, `IsAdmin`, `IsAuthenticatedOrReadOnly`
|
|
151
|
-
- **Query Filters**: `OwnerQueryFilter` for filtering list queries by owner
|
|
152
|
-
- **setupServer**: Express server setup with auth, OpenAPI, and middleware
|
|
153
|
-
- **APIError**: Standardized error handling
|
|
154
|
-
- **logger**: Winston-based logging
|
|
155
|
-
|
|
156
|
-
Key imports:
|
|
157
|
-
```typescript
|
|
158
|
-
import {
|
|
159
|
-
modelRouter,
|
|
160
|
-
setupServer,
|
|
161
|
-
Permissions,
|
|
162
|
-
OwnerQueryFilter,
|
|
163
|
-
APIError,
|
|
164
|
-
logger,
|
|
165
|
-
asyncHandler,
|
|
166
|
-
authenticateMiddleware,
|
|
167
|
-
} from "@terreno/api";
|
|
168
|
-
```
|
|
169
|
-
|
|
170
|
-
#### modelRouter Usage
|
|
171
|
-
|
|
172
|
-
```typescript
|
|
173
|
-
import {modelRouter, modelRouterOptions, Permissions} from "@terreno/api";
|
|
174
|
-
|
|
175
|
-
const router = modelRouter(YourModel, {
|
|
176
|
-
permissions: {
|
|
177
|
-
list: [Permissions.IsAuthenticated],
|
|
178
|
-
create: [Permissions.IsAuthenticated],
|
|
179
|
-
read: [Permissions.IsOwner],
|
|
180
|
-
update: [Permissions.IsOwner],
|
|
181
|
-
delete: [], // Disabled
|
|
182
|
-
},
|
|
183
|
-
sort: "-created",
|
|
184
|
-
queryFields: ["_id", "type", "name"],
|
|
185
|
-
});
|
|
186
|
-
```
|
|
187
|
-
|
|
188
|
-
#### Custom Routes
|
|
189
|
-
|
|
190
|
-
For non-CRUD endpoints, use the OpenAPI builder:
|
|
191
|
-
|
|
192
|
-
```typescript
|
|
193
|
-
import {asyncHandler, authenticateMiddleware, createOpenApiBuilder} from "@terreno/api";
|
|
194
|
-
|
|
195
|
-
router.get("/yourRoute/:id", [
|
|
196
|
-
authenticateMiddleware(),
|
|
197
|
-
createOpenApiBuilder(options)
|
|
198
|
-
.withTags(["yourTag"])
|
|
199
|
-
.withSummary("Brief summary")
|
|
200
|
-
.withPathParameter("id", {type: "string"})
|
|
201
|
-
.withResponse(200, {data: {type: "object"}})
|
|
202
|
-
.build(),
|
|
203
|
-
], asyncHandler(async (req, res) => {
|
|
204
|
-
return res.json({data: result});
|
|
205
|
-
}));
|
|
206
|
-
```
|
|
207
|
-
|
|
208
|
-
#### API Conventions
|
|
209
|
-
|
|
210
|
-
- Throw `APIError` with appropriate status codes: `throw new APIError({status: 400, title: "Message"})`
|
|
211
|
-
- Do not use `Model.findOne` - use `Model.findExactlyOne` or `Model.findOneOrThrow`
|
|
212
|
-
- Define statics/methods by direct assignment: `schema.methods = {bar() {}}`
|
|
213
|
-
- All model types live in `src/modelInterfaces.ts`
|
|
214
|
-
- In routes: `req.user` is `UserDocument | undefined`
|
|
215
|
-
- In @terreno/api callbacks: cast with `const user = u as unknown as UserDocument`
|
|
216
|
-
|
|
217
|
-
### @terreno/ui
|
|
218
|
-
|
|
219
|
-
React Native UI component library (a large component library):
|
|
220
|
-
|
|
221
|
-
- **Layout**: Box, Page, ListDetailLayout, SplitPage, Card
|
|
222
|
-
- **Forms**: TextField, SelectField, DateTimeField, CheckBox
|
|
223
|
-
- **Display**: Text, Heading, Badge, DataTable
|
|
224
|
-
- **Actions**: Button, IconButton, Link
|
|
225
|
-
- **Feedback**: Spinner, Modal, Toast
|
|
226
|
-
- **Theming**: TerrenoProvider, useTheme
|
|
227
|
-
|
|
228
|
-
Key imports:
|
|
229
|
-
```typescript
|
|
230
|
-
import {
|
|
231
|
-
Box,
|
|
232
|
-
Button,
|
|
233
|
-
Card,
|
|
234
|
-
Page,
|
|
235
|
-
Text,
|
|
236
|
-
TextField,
|
|
237
|
-
TerrenoProvider,
|
|
238
|
-
} from "@terreno/ui";
|
|
239
|
-
```
|
|
240
|
-
|
|
241
|
-
#### UI Component Examples
|
|
242
|
-
|
|
243
|
-
Layout with Box:
|
|
244
|
-
```typescript
|
|
245
|
-
<Box direction="row" padding={4} gap={2} alignItems="center">
|
|
246
|
-
<Text>Content</Text>
|
|
247
|
-
<Button text="Action" />
|
|
248
|
-
</Box>
|
|
249
|
-
```
|
|
250
|
-
|
|
251
|
-
Buttons:
|
|
252
|
-
```typescript
|
|
253
|
-
<Button
|
|
254
|
-
text="Submit"
|
|
255
|
-
variant="primary" // 'primary' | 'secondary' | 'outline' | 'ghost'
|
|
256
|
-
onClick={handleSubmit}
|
|
257
|
-
loading={isLoading}
|
|
258
|
-
iconName="check"
|
|
259
|
-
/>
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
Forms:
|
|
263
|
-
```typescript
|
|
264
|
-
<TextField
|
|
265
|
-
label="Email"
|
|
266
|
-
value={email}
|
|
267
|
-
onChangeText={setEmail}
|
|
268
|
-
error={emailError}
|
|
269
|
-
helperText="Enter a valid email"
|
|
270
|
-
/>
|
|
271
|
-
```
|
|
272
|
-
|
|
273
|
-
Modals:
|
|
274
|
-
```typescript
|
|
275
|
-
<Modal
|
|
276
|
-
title="Confirm Action"
|
|
277
|
-
visible={isVisible}
|
|
278
|
-
primaryButtonText="Confirm"
|
|
279
|
-
secondaryButtonText="Cancel"
|
|
280
|
-
onDismiss={() => setIsVisible(false)}
|
|
281
|
-
onPrimaryAction={handleConfirm}
|
|
282
|
-
>
|
|
283
|
-
<Text>Are you sure?</Text>
|
|
284
|
-
</Modal>
|
|
285
|
-
```
|
|
286
|
-
|
|
287
|
-
#### UI Common Pitfalls
|
|
288
|
-
|
|
289
|
-
- Don't use inline styles when theme values are available
|
|
290
|
-
- Don't use raw `View`/`Text` when `Box`/@terreno/ui `Text` are available
|
|
291
|
-
- Don't forget loading and error states
|
|
292
|
-
- Don't use `style` prop when equivalent props exist (`padding`, `margin`)
|
|
293
|
-
- Never modify generated `store/apiSdk.ts` or `store/syncDbSdk.ts` manually
|
|
294
|
-
|
|
295
|
-
### @terreno/syncdb
|
|
296
|
-
|
|
297
|
-
Frontend data, request, and session layer:
|
|
298
|
-
|
|
299
|
-
- **createSyncDb** + `useQuery` / `useMutate`: Local-first collection CRUD
|
|
300
|
-
- **createApiClient** + generated `store/apiSdk.ts` hooks: Every non-synced route
|
|
301
|
-
- **SessionProvider** / **useSession**: Better Auth (or `jwtAuthAdapter`) session state
|
|
302
|
-
|
|
303
|
-
Key imports:
|
|
304
|
-
```typescript
|
|
305
|
-
import {createApiClient} from "@terreno/syncdb/api";
|
|
306
|
-
import {SessionProvider, useSession} from "@terreno/syncdb/auth";
|
|
307
|
-
import {useMutate, useQuery} from "@terreno/syncdb/react";
|
|
308
|
-
```
|
|
309
|
-
|
|
310
|
-
Always use generated SDK hooks or syncdb hooks - never use `axios` or `fetch` directly:
|
|
311
|
-
|
|
312
|
-
```typescript
|
|
313
|
-
// Correct
|
|
314
|
-
import {useGetYourRouteQuery} from "@/store/apiSdk";
|
|
315
|
-
const {data, isLoading, error} = useGetYourRouteQuery({id: "value"});
|
|
316
|
-
|
|
317
|
-
// Wrong - don't use axios directly
|
|
318
|
-
// const result = await axios.get("/api/yourRoute/value");
|
|
319
|
-
```
|
|
320
|
-
|
|
321
|
-
## React Best Practices (Frontend Packages)
|
|
322
|
-
|
|
323
|
-
- Use functional components with `React.FC` type
|
|
324
|
-
- Import hooks directly: `import {useEffect, useMemo} from 'react'`
|
|
325
|
-
- Always provide return types for functions
|
|
326
|
-
- Add explanatory comment above each `useEffect`
|
|
327
|
-
- Wrap callbacks in `useCallback`
|
|
328
|
-
- Prefer const arrow functions
|
|
329
|
-
- Use inline styles over `StyleSheet.create`
|
|
330
|
-
- Use Luxon for date operations
|
|
331
|
-
- Place static content and interfaces at beginning of file
|
|
332
|
-
- Minimize `use client`, `useEffect`, and `setState`
|
|
333
|
-
- Always support React-Native Web
|
|
334
|
-
|
|
335
|
-
## CI/CD Workflows
|
|
336
|
-
|
|
337
|
-
### Required Secret Validation
|
|
338
|
-
|
|
339
|
-
GitHub Actions workflows that use secrets or environment variables must validate all required variables are set before using them. Add a validation step early in the job that fails fast with a clear error message listing any missing variables.
|
|
340
|
-
|
|
341
|
-
```yaml
|
|
342
|
-
- name: Validate required secrets
|
|
343
|
-
run: |
|
|
344
|
-
missing=()
|
|
345
|
-
if [ -z "$VAR_NAME" ]; then missing+=("VAR_NAME"); fi
|
|
346
|
-
if [ ${#missing[@]} -ne 0 ]; then
|
|
347
|
-
echo "::error::Missing required secrets: ${missing[*]}"
|
|
348
|
-
exit 1
|
|
349
|
-
fi
|
|
350
|
-
```
|
|
351
|
-
|
|
352
|
-
## @terreno/admin-backend — tests
|
|
353
|
-
|
|
354
|
-
`bunfig.toml` preloads [`src/tests/testEnv.ts`](./src/tests/testEnv.ts) (sets `TERRENO_TEST_USE_MEMORY_MONGO`) then [`api/src/tests/bunSetup.ts`](../api/src/tests/bunSetup.ts), which starts **mongodb-memory-server** and connects Mongoose (no local `mongod` required). To use a real MongoDB instead, remove or edit `testEnv.ts`, or set `TERRENO_TEST_MONGODB_URI` before running tests. Set `BUN_TEST_DISABLE_DB=true` to skip DB hooks entirely.
|
|
355
|
-
|
|
356
|
-
## Dependency Management
|
|
357
|
-
|
|
358
|
-
Uses [Bun Catalogs](https://bun.sh/docs/install/catalogs) - shared versions defined in root `package.json` under `catalog`. Reference with `catalog:` in workspace packages.
|
package/biome.jsonc
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
|
|
3
|
-
"extends": ["../biome.jsonc"],
|
|
4
|
-
"files": {
|
|
5
|
-
"includes": [
|
|
6
|
-
"package.json",
|
|
7
|
-
"src/**/*.ts",
|
|
8
|
-
"src/**/*.tsx",
|
|
9
|
-
"e2e/**/*.ts",
|
|
10
|
-
"!!**/node_modules",
|
|
11
|
-
"!!node_modules",
|
|
12
|
-
"!!**/dist",
|
|
13
|
-
"!!dist",
|
|
14
|
-
"!!**/build",
|
|
15
|
-
"!!build",
|
|
16
|
-
"!!**/coverage",
|
|
17
|
-
"!!coverage"
|
|
18
|
-
]
|
|
19
|
-
},
|
|
20
|
-
"root": true
|
|
21
|
-
}
|
package/bunfig.toml
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
[test]
|
|
2
|
-
preload = ["./src/tests/bunSetup.ts"]
|
|
3
|
-
root = "./src"
|
|
4
|
-
coveragePathIgnorePatterns = [
|
|
5
|
-
"**/*.test.ts",
|
|
6
|
-
"**/tests/**",
|
|
7
|
-
# Sibling workspace packages are compiled into `dist/` for this package's CI run;
|
|
8
|
-
# they carry their own coverage gates.
|
|
9
|
-
"../**",
|
|
10
|
-
"dist/**",
|
|
11
|
-
"**/node_modules/**",
|
|
12
|
-
]
|
|
13
|
-
# Enforced by scripts/check-coverage.ts; Bun parses this key but does not
|
|
14
|
-
# fail the run when coverage is below threshold. See
|
|
15
|
-
# https://github.com/oven-sh/bun/issues/7367 and https://github.com/oven-sh/bun/pull/27933.
|
|
16
|
-
coverageThreshold = { line = 95, function = 95 }
|
package/e2e/smoke.ts
DELETED
|
@@ -1,246 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Real-process smoke for @terreno/admin-backend. Run `bun e2e/smoke.ts` after `bun run compile`.
|
|
3
|
-
*
|
|
4
|
-
* The smoke re-runs this file with `serve` as a child process: a minimal TerrenoApp from the
|
|
5
|
-
* compiled `@terreno/api` with one `modelRouter` model that declares `admin:`, and the compiled
|
|
6
|
-
* `AdminApp`, on a free port, against `smokeMongoUri()`. The child seeds one admin user, because
|
|
7
|
-
* signup never grants admin. The parent then checks over real HTTP that the admin reads the admin
|
|
8
|
-
* config and lists the model's documents, and that a signed-up non-admin is denied both. Exits
|
|
9
|
-
* non-zero on the first failed check.
|
|
10
|
-
*/
|
|
11
|
-
import {
|
|
12
|
-
freePort,
|
|
13
|
-
type SpawnedProcess,
|
|
14
|
-
smokeMongoUri,
|
|
15
|
-
spawnUntilReady,
|
|
16
|
-
stopSmokeMongo,
|
|
17
|
-
} from "@terreno/test";
|
|
18
|
-
import type express from "express";
|
|
19
|
-
import {DateTime} from "luxon";
|
|
20
|
-
import type {Schema} from "mongoose";
|
|
21
|
-
|
|
22
|
-
const SERVE_ARG = "serve";
|
|
23
|
-
const PASSWORD = "admin-backend-smoke-password-1";
|
|
24
|
-
const WIDGET_DISPLAY_NAME = "Smoke widgets";
|
|
25
|
-
/** AdminApp mounts a model at `basePath` + its modelRouter path; the app also serves `/widgets`. */
|
|
26
|
-
const ADMIN_WIDGETS_PATH = "/admin/widgets";
|
|
27
|
-
|
|
28
|
-
interface AdminConfigModel {
|
|
29
|
-
displayName: string;
|
|
30
|
-
name: string;
|
|
31
|
-
routePath: string;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
interface SmokeWidget {
|
|
35
|
-
_id: string;
|
|
36
|
-
name: string;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Child: the compiled API with auth, one admin-enabled model, the compiled AdminApp, and a health
|
|
41
|
-
* plugin. Both packages are imported here, not at the top, so the parent process never loads
|
|
42
|
-
* them.
|
|
43
|
-
*/
|
|
44
|
-
const serve = async (): Promise<void> => {
|
|
45
|
-
const {createdUpdatedPlugin, logger, modelRouter, Permissions, TerrenoApp} = await import(
|
|
46
|
-
"@terreno/api"
|
|
47
|
-
);
|
|
48
|
-
const {AdminApp} = await import("@terreno/admin-backend");
|
|
49
|
-
const {default: mongoose} = await import("mongoose");
|
|
50
|
-
const {default: passportLocalMongoose} = await import("passport-local-mongoose");
|
|
51
|
-
|
|
52
|
-
const userSchema = new mongoose.Schema({
|
|
53
|
-
admin: {default: false, description: "Whether the user is an admin", type: Boolean},
|
|
54
|
-
email: {description: "Sign-in email", type: String},
|
|
55
|
-
name: {description: "Display name", type: String},
|
|
56
|
-
});
|
|
57
|
-
userSchema.plugin(passportLocalMongoose as unknown as (schema: Schema, options: object) => void, {
|
|
58
|
-
usernameCaseInsensitive: true,
|
|
59
|
-
usernameField: "email",
|
|
60
|
-
});
|
|
61
|
-
userSchema.plugin(createdUpdatedPlugin);
|
|
62
|
-
const User = mongoose.model("User", userSchema);
|
|
63
|
-
|
|
64
|
-
const widgetSchema = new mongoose.Schema({
|
|
65
|
-
name: {description: "Widget name", required: true, type: String},
|
|
66
|
-
});
|
|
67
|
-
widgetSchema.plugin(createdUpdatedPlugin);
|
|
68
|
-
const Widget = mongoose.model("Widget", widgetSchema);
|
|
69
|
-
|
|
70
|
-
const widgetRouter = modelRouter("/widgets", Widget, {
|
|
71
|
-
admin: {displayName: WIDGET_DISPLAY_NAME, listFields: ["name", "created"]},
|
|
72
|
-
permissions: {
|
|
73
|
-
create: [Permissions.IsAdmin],
|
|
74
|
-
delete: [Permissions.IsAdmin],
|
|
75
|
-
list: [Permissions.IsAdmin],
|
|
76
|
-
read: [Permissions.IsAdmin],
|
|
77
|
-
update: [Permissions.IsAdmin],
|
|
78
|
-
},
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
const healthPlugin = {
|
|
82
|
-
register: (app: express.Application): void => {
|
|
83
|
-
app.get("/health", (_req, res) => {
|
|
84
|
-
res.json({healthy: mongoose.connection.readyState === 1});
|
|
85
|
-
});
|
|
86
|
-
},
|
|
87
|
-
};
|
|
88
|
-
|
|
89
|
-
await mongoose.connect(process.env.MONGO_URI as string);
|
|
90
|
-
await (
|
|
91
|
-
User as unknown as {register: (user: object, password: string) => Promise<unknown>}
|
|
92
|
-
).register(
|
|
93
|
-
{admin: true, email: process.env.SMOKE_ADMIN_EMAIL, name: "Smoke admin"},
|
|
94
|
-
process.env.SMOKE_ADMIN_PASSWORD as string
|
|
95
|
-
);
|
|
96
|
-
await Widget.create({name: process.env.SMOKE_WIDGET_NAME});
|
|
97
|
-
|
|
98
|
-
const app = new TerrenoApp({
|
|
99
|
-
loggingOptions: {logRequests: false},
|
|
100
|
-
userModel: User as unknown as ConstructorParameters<typeof TerrenoApp>[0]["userModel"],
|
|
101
|
-
})
|
|
102
|
-
.register(widgetRouter)
|
|
103
|
-
.register(new AdminApp({}))
|
|
104
|
-
.register(healthPlugin);
|
|
105
|
-
app.start();
|
|
106
|
-
await app.whenReady();
|
|
107
|
-
logger.info(`[adminBackendSmoke] serving on port ${process.env.PORT}`);
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
const expectStatus = async (res: Response, status: number, step: string): Promise<unknown> => {
|
|
111
|
-
const body = await res.text();
|
|
112
|
-
if (res.status !== status) {
|
|
113
|
-
throw new Error(`${step}: expected ${status}, got ${res.status}: ${body}`);
|
|
114
|
-
}
|
|
115
|
-
return body ? JSON.parse(body) : undefined;
|
|
116
|
-
};
|
|
117
|
-
|
|
118
|
-
const bearer = (token: string): Record<string, string> => ({
|
|
119
|
-
Authorization: `Bearer ${token}`,
|
|
120
|
-
"Content-Type": "application/json",
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
const signIn = async (
|
|
124
|
-
baseUrl: string,
|
|
125
|
-
route: "login" | "signup",
|
|
126
|
-
email: string
|
|
127
|
-
): Promise<string> => {
|
|
128
|
-
const res = (await expectStatus(
|
|
129
|
-
await fetch(`${baseUrl}/auth/${route}`, {
|
|
130
|
-
body: JSON.stringify({email, password: PASSWORD}),
|
|
131
|
-
headers: {"Content-Type": "application/json"},
|
|
132
|
-
method: "POST",
|
|
133
|
-
}),
|
|
134
|
-
200,
|
|
135
|
-
`POST /auth/${route}`
|
|
136
|
-
)) as {data: {token: string}};
|
|
137
|
-
return res.data.token;
|
|
138
|
-
};
|
|
139
|
-
|
|
140
|
-
/** Parent: boots the child and walks the admin read path and the non-admin denial over HTTP. */
|
|
141
|
-
const run = async (): Promise<void> => {
|
|
142
|
-
const startedAt = DateTime.now();
|
|
143
|
-
const runId = startedAt.toMillis();
|
|
144
|
-
const adminEmail = `admin-backend-smoke-admin-${runId}@example.com`;
|
|
145
|
-
const widgetName = `Smoke widget ${runId}`;
|
|
146
|
-
const port = await freePort();
|
|
147
|
-
const baseUrl = `http://127.0.0.1:${port}`;
|
|
148
|
-
let server: SpawnedProcess | undefined;
|
|
149
|
-
|
|
150
|
-
try {
|
|
151
|
-
server = await spawnUntilReady({
|
|
152
|
-
cmd: [process.execPath, __filename, SERVE_ARG],
|
|
153
|
-
env: {
|
|
154
|
-
MONGO_URI: await smokeMongoUri({databaseName: "adminBackendSmoke"}),
|
|
155
|
-
PORT: String(port),
|
|
156
|
-
REFRESH_TOKEN_SECRET: "admin-backend-smoke-refresh-secret",
|
|
157
|
-
SESSION_SECRET: "admin-backend-smoke-session-secret",
|
|
158
|
-
SMOKE_ADMIN_EMAIL: adminEmail,
|
|
159
|
-
SMOKE_ADMIN_PASSWORD: PASSWORD,
|
|
160
|
-
SMOKE_WIDGET_NAME: widgetName,
|
|
161
|
-
TOKEN_ISSUER: "admin-backend-smoke",
|
|
162
|
-
TOKEN_SECRET: "admin-backend-smoke-token-secret",
|
|
163
|
-
},
|
|
164
|
-
timeoutMs: 30000,
|
|
165
|
-
url: `${baseUrl}/health`,
|
|
166
|
-
});
|
|
167
|
-
|
|
168
|
-
const adminToken = await signIn(baseUrl, "login", adminEmail);
|
|
169
|
-
console.info("✅ POST /auth/login signs in the seeded admin");
|
|
170
|
-
|
|
171
|
-
const config = (await expectStatus(
|
|
172
|
-
await fetch(`${baseUrl}/admin/config`, {headers: bearer(adminToken)}),
|
|
173
|
-
200,
|
|
174
|
-
"GET /admin/config as admin"
|
|
175
|
-
)) as {models: AdminConfigModel[]};
|
|
176
|
-
const widgetModel = config.models.find((model) => model.displayName === WIDGET_DISPLAY_NAME);
|
|
177
|
-
if (!widgetModel) {
|
|
178
|
-
throw new Error(
|
|
179
|
-
`GET /admin/config: the "${WIDGET_DISPLAY_NAME}" model is missing: ${JSON.stringify(config.models)}`
|
|
180
|
-
);
|
|
181
|
-
}
|
|
182
|
-
if (widgetModel.routePath !== ADMIN_WIDGETS_PATH) {
|
|
183
|
-
throw new Error(
|
|
184
|
-
`GET /admin/config: expected routePath ${ADMIN_WIDGETS_PATH}, got ${widgetModel.routePath}`
|
|
185
|
-
);
|
|
186
|
-
}
|
|
187
|
-
console.info(`✅ GET /admin/config lists the ${widgetModel.name} model`);
|
|
188
|
-
|
|
189
|
-
const list = (await expectStatus(
|
|
190
|
-
await fetch(`${baseUrl}${ADMIN_WIDGETS_PATH}`, {headers: bearer(adminToken)}),
|
|
191
|
-
200,
|
|
192
|
-
`GET ${ADMIN_WIDGETS_PATH} as admin`
|
|
193
|
-
)) as {data: SmokeWidget[]};
|
|
194
|
-
if (!list.data.some((widget) => widget.name === widgetName)) {
|
|
195
|
-
throw new Error(
|
|
196
|
-
`GET ${ADMIN_WIDGETS_PATH}: the seeded widget is missing: ${JSON.stringify(list.data)}`
|
|
197
|
-
);
|
|
198
|
-
}
|
|
199
|
-
console.info(`✅ GET ${ADMIN_WIDGETS_PATH} lists the seeded widget`);
|
|
200
|
-
|
|
201
|
-
const userToken = await signIn(
|
|
202
|
-
baseUrl,
|
|
203
|
-
"signup",
|
|
204
|
-
`admin-backend-smoke-user-${runId}@example.com`
|
|
205
|
-
);
|
|
206
|
-
console.info("✅ POST /auth/signup signs in a non-admin user");
|
|
207
|
-
|
|
208
|
-
await expectStatus(
|
|
209
|
-
await fetch(`${baseUrl}/admin/config`, {headers: bearer(userToken)}),
|
|
210
|
-
403,
|
|
211
|
-
"GET /admin/config as non-admin"
|
|
212
|
-
);
|
|
213
|
-
console.info("✅ GET /admin/config returns 403 for the non-admin");
|
|
214
|
-
|
|
215
|
-
// modelRouter answers a permission denial on a CRUD route with 405, not 403.
|
|
216
|
-
await expectStatus(
|
|
217
|
-
await fetch(`${baseUrl}${ADMIN_WIDGETS_PATH}`, {headers: bearer(userToken)}),
|
|
218
|
-
405,
|
|
219
|
-
`GET ${ADMIN_WIDGETS_PATH} as non-admin`
|
|
220
|
-
);
|
|
221
|
-
console.info(`✅ GET ${ADMIN_WIDGETS_PATH} returns 405 for the non-admin`);
|
|
222
|
-
} catch (error: unknown) {
|
|
223
|
-
if (server) {
|
|
224
|
-
console.error(`--- server output ---\n${server.output()}`);
|
|
225
|
-
}
|
|
226
|
-
throw error;
|
|
227
|
-
} finally {
|
|
228
|
-
await server?.stop();
|
|
229
|
-
await stopSmokeMongo();
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
console.info(`admin-backend smoke passed in ${DateTime.now().diff(startedAt).toMillis()} ms`);
|
|
233
|
-
};
|
|
234
|
-
|
|
235
|
-
const main = process.argv[2] === SERVE_ARG ? serve : run;
|
|
236
|
-
main().then(
|
|
237
|
-
() => {
|
|
238
|
-
if (main === run) {
|
|
239
|
-
process.exit(0);
|
|
240
|
-
}
|
|
241
|
-
},
|
|
242
|
-
(error: unknown) => {
|
|
243
|
-
console.error(`❌ ${error instanceof Error ? error.message : String(error)}`);
|
|
244
|
-
process.exit(1);
|
|
245
|
-
}
|
|
246
|
-
);
|
package/tsconfig.json
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"declaration": true,
|
|
4
|
-
"isolatedModules": true,
|
|
5
|
-
"lib": ["es2023"],
|
|
6
|
-
"module": "nodenext",
|
|
7
|
-
"noImplicitAny": false,
|
|
8
|
-
"noImplicitReturns": true,
|
|
9
|
-
"outDir": "./dist",
|
|
10
|
-
"rootDir": "./src",
|
|
11
|
-
"skipLibCheck": true,
|
|
12
|
-
"strict": true,
|
|
13
|
-
"target": "es2023",
|
|
14
|
-
"types": ["node"]
|
|
15
|
-
},
|
|
16
|
-
"exclude": ["node_modules", "**/*.test.ts"],
|
|
17
|
-
"include": ["src"]
|
|
18
|
-
}
|
package/tsconfig.typecheck.json
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"extends": "./tsconfig.json",
|
|
3
|
-
"compilerOptions": {
|
|
4
|
-
"noEmit": true,
|
|
5
|
-
"composite": false,
|
|
6
|
-
"incremental": false,
|
|
7
|
-
"declaration": false,
|
|
8
|
-
"declarationMap": false,
|
|
9
|
-
"types": [
|
|
10
|
-
"node",
|
|
11
|
-
"bun"
|
|
12
|
-
]
|
|
13
|
-
},
|
|
14
|
-
"exclude": [
|
|
15
|
-
"node_modules",
|
|
16
|
-
"dist"
|
|
17
|
-
]
|
|
18
|
-
}
|