@galaxy-stack/blackhole-cli 2.0.12 → 2.0.14

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.
@@ -5,555 +5,123 @@ description: >
5
5
  (@galaxy-stack/orbit-*), a NestJS-style framework optimized for the Bun
6
6
  runtime. Use when creating modules, controllers, providers, GraphQL APIs,
7
7
  microservices, or when migrating from NestJS to Orbit.
8
- version: 0.2.0
8
+ version: 1.1.0
9
+ # The companion server is installed separately and the harness validates every call against the
10
+ # schema it declares, so this skill states the version its documented call shapes need. 0.4.0
11
+ # declared orbit_knowledge_read { id } as required and had no symbol argument, which rejected the
12
+ # { symbol } and { section } shapes taught below.
13
+ requires:
14
+ orbit: ">=0.4.1"
9
15
  ---
10
16
 
11
17
  # Orbit Framework Skill
12
18
 
13
- Orbit is a NestJS-style backend framework for Bun. Concept mapping from NestJS:
14
- `@nestjs/common` → `@galaxy-stack/orbit-core`; `class-validator` DTOs → Zod +
15
- `orbit-validation`; `@nestjs/graphql` → `orbit-graphql`; `@nestjs/microservices`
16
- → `orbit-microservices` + transport packages; `@nestjs/swagger` → `orbit-swagger`.
19
+ Orbit is a NestJS-style backend framework for Bun. Concept mapping:
20
+ `@nestjs/common` → `@galaxy-stack/orbit-core` (decorators for controllers, DI and modules)
21
+ plus `@galaxy-stack/orbit-common` (parameter/method decorators, guards, pipes, filters, exceptions);
22
+ `class-validator` DTOs → Zod + `orbit-validation`; `@nestjs/graphql` → `orbit-graphql`;
23
+ `@nestjs/microservices` → `orbit-microservices` + transport packages; `@nestjs/swagger` → `orbit-swagger`.
24
+
25
+ This file is the always-on rulebook: the rules that are **not derivable from a declaration** and the
26
+ routing to everything that is. It is deliberately short. The API inventory, the wiring recipes and the
27
+ traps live in the companion MCP server (`@galaxy-stack/orbit-mcp`) and are fetched on demand.
28
+
29
+ ## Ground truth
30
+
31
+ 1. `orbit_knowledge_topics` lists every topic; `orbit_knowledge_read` takes `{ id }`,
32
+ `{ id, section }` or `{ symbol }`. The `api-surface` topic is **generated from the
33
+ installed declarations** — it carries every export of every `@galaxy-stack/orbit-*` package with its
34
+ real signature, interface members and class methods, one section per package.
35
+ 2. Never open `node_modules/**/*.d.ts` to re-derive a signature the generated surface already has,
36
+ and never read the package READMEs — they contradict their own types (see the `pitfalls` topic).
37
+ 3. If a symbol or signature is genuinely missing, say so in the final report as a knowledge gap instead of
38
+ silently re-deriving it. The gap is the bug.
39
+
40
+ ## Where the detail lives
41
+
42
+ | Need | Call |
43
+ |---|---|
44
+ | What a package exports, with signatures | `{ id: "api-surface", section: "orbit-core" }` (one section per package) |
45
+ | One symbol only | `{ symbol: "ThrottlerGuard" }` — names the package and shows the declaration |
46
+ | Which versions this project installs vs the ones the surface was generated from | `orbit_environment` (one call, no `package.json` reading) |
47
+ | A verified wiring recipe | `orbit_recipe { task: "throttle-per-route" \| "migrations" \| "database-wiring" \| "security-baseline" \| "filters" \| "middleware" \| "zod-validation" }` |
48
+ | Request pipeline contracts | `{ section: "pipeline" }` (guards, pipes, interceptors, filters) |
49
+ | Application surface, CORS, static files, middleware | `{ section: "application" }` / `{ section: "middleware" }` |
50
+ | Database install, wiring, migrations | `{ section: "database" }` / `{ section: "install" }` / `{ section: "migrations" }` |
51
+ | Patterns: module, controller, DI, GraphQL, validation, testing, microservices | topics `module-pattern`, `controller-pattern`, `di-pattern`, `graphql-pattern`, `validation-pattern`, `testing-pattern`, `microservices-pattern`, `package-map` |
52
+ | Runtime traps and version-specific bugs | topic `pitfalls` |
53
+ | Names that do NOT exist (stop searching) | topic `absent` |
54
+ | Security hardening checklist | topic `security-checklist` |
55
+
56
+ Section aliases (`throttler`, `database`, `security`, `migrations`, `versions`,
57
+ `exports` …) resolve across topics, so `{ section: "throttler" }` works with or without an `id`.
17
58
 
18
59
  ## Project rules
19
60
 
20
- 1. Runtime is Bun. Use `bun` instead of `node`/`npm`/`pnpm` for all commands:
21
- `bun install`, `bun run dev` (a developer server for a human, never a check),
22
- `bun test`.
61
+ 1. Runtime is Bun. Use `bun`, not `node`/`npm`/`pnpm`: `bun install`, `bun test`,
62
+ `bun run dev` (a developer server for a human, never a verification step).
23
63
  2. Entry point: `OrbitFactory.create(AppModule)` then `app.listen(3000)`.
24
- 3. Every feature is a `@Module({ controllers, providers, exports })` class.
25
- 4. Providers are `@Injectable()` classes injected via constructor.
26
- 5. Validate all external input with Zod schemas through ValidationPipe.
27
- 6. Tests run with `bun test`; e2e tests boot a real HTTP server: `OrbitFactory.create(AppModule, { port: 0 })` → `app.listen(0)` → `fetch(\`http://127.0.0.1:${app.port}/…\`)` — `OrbitApplication` has no public `handle()`.
28
-
29
- ## API map (what each package exports)
30
-
31
- This map is the surface agents used to re-derive by opening `node_modules/**/*.d.ts`.
32
- Read it first; if something is missing here, say so in the final report instead of
33
- silently re-reading declarations.
34
-
35
- **`@galaxy-stack/orbit-core`**
36
- - App: `OrbitFactory.create(AppModule, options?)` → `OrbitApplication` (`app.listen()`,
37
- `app.port`). `OrbitApplicationOptions`: `port`, `hostname`, `logger`, `cors`,
38
- `security` (secure response headers **on by default**; `false` disables).
39
- Aliases `BunFactory`/`GalaxyFactory`.
40
- - DI/modules: `Module`, `Injectable`, `Inject`, `Optional`, `forwardRef`, `Container`,
41
- `Scope`, provider shapes (`ClassProvider`, `ValueProvider`, `FactoryProvider`).
42
- - Controllers: `Controller`, `Get|Post|Put|Patch|Delete|Head|Options|All`, `HttpMethod`.
43
- - Versioning: `versioningManager.configure({ type: 'uri'|'header'|'media'|'custom', … })`,
44
- `Version`, `VERSION_NEUTRAL`. There is no `app.setGlobalPrefix`.
45
- - Config: `ConfigModule`, `registerAs`, `ConfigService`, tokens `CONFIG_OPTIONS`,
46
- `CONFIGURATION_TOKEN`, `CONFIGURATION_SERVICE_TOKEN`.
47
- - Cluster/telemetry: `ClusterManager`, `isPrimaryProcess`, `isWorkerProcess`,
48
- `notifyReady`, `onShutdown`; `onRequestTelemetry`, `emitRequestTelemetry`.
49
-
50
- **`@galaxy-stack/orbit-common`**
51
- - Parameters: `Body`, `Query`, `Param`, `Headers`, `Req`/`Request`, `Res`/`Response`,
52
- `Ip`, `Session`, `UploadedFile`, `UploadedFiles`.
53
- - Guards/pipes/interceptors/filters: `UseGuards`, `UsePipes`, `UseInterceptors`,
54
- `CanActivate`, `PipeTransform`, `CallHandler`, `OrbitInterceptor`, `Catch`,
55
- `UseFilters`, `ExceptionFilter`, `ArgumentsHost`.
56
- - Response: `HttpCode`, `Header`, `Redirect`, `Render`.
57
- - Transforms: `Transform`, `ToInt`, `ToFloat`, `ToBoolean`, `ToDate`, `ToLowerCase`,
58
- `ToUpperCase`, `Trim`, `ToArray`, `DefaultValue`.
59
- - Exceptions: `HttpException` plus `BadRequest|Unauthorized|Forbidden|NotFound|
60
- MethodNotAllowed|NotAcceptable|Conflict|Gone|PayloadTooLarge|UnsupportedMediaType|
61
- UnprocessableEntity|InternalServerError|NotImplemented|BadGateway|ServiceUnavailable|
62
- GatewayTimeout` + `Exception`.
63
- - Secure headers: `buildSecureHeaders`, `applySecureHeaderRecord`, `withSecureHeaders`.
64
-
65
- **`@galaxy-stack/orbit-database`**
66
- - `DatabaseModule.forRoot({ type: 'sqlite'|'postgres'|'mysql'|'libsql'|'mongodb', url?, host?,
67
- port?, database?, pool?, logging?, isGlobal? })`, `forRootAsync({ useFactory, inject,
68
- imports, isGlobal })`, and `forFeature(entities, tableMapping: Map<entity, table>)` —
69
- note the second argument.
70
- - Decorators: `Entity(options|'table')`, `Column(options)`, `PrimaryKey`,
71
- `PrimaryGeneratedColumn('increment'|'uuid')`, `InjectRepository(Entity)`, `Transactional`.
72
- - Data source: `createDataSource(options)` / `BunDataSource`; tokens `DATABASE_OPTIONS`,
73
- `DATA_SOURCE`.
74
- - Repositories: extend `BaseRepository<T>` (or `DrizzleRepository`) and provide
75
- `db`/`table`; implement `findAll/findOne(id)/findBy(where)/create/update(id, patch)/
76
- delete(id)`; helpers `getTableName/getPrimaryKey/getColumns`.
77
-
78
- **`@galaxy-stack/orbit-security`**
79
- - `SecurityModule.forRoot({ helmet?, csrf?, isGlobal? })` / `forRootAsync({ useFactory,
80
- inject, imports, isGlobal })`; tokens `HELMET_MIDDLEWARE`, `CSRF_MIDDLEWARE`,
81
- `CRYPTO_UTILS`, `SECURITY_MODULE_OPTIONS`.
82
- - Rate limiting: `rateLimit(options?)` (sliding window), `tokenBucket(options?)`.
83
- - Sanitizing: `escapeHtml`, `sanitizeHtml`, `detectSqlInjection`, `detectXss`,
84
- `sanitizeString`, `sanitizeObject`, `SanitizationPipe`, `XssPipe`, `SqlInjectionPipe`.
85
- - API keys: `ApiKeyManager`, `createApiKeyManager({ prefix, length, charset, expiresIn,
86
- hashAlgorithm })`, `ApiKeyRotationScheduler`. Crypto helpers: `CryptoUtils`.
87
-
88
- **`@galaxy-stack/orbit-throttler`**
89
- - `ThrottlerModule.forRoot(options)` / `forRootAsync`; tokens `THROTTLER_OPTIONS`,
90
- `THROTTLER_GUARD`, `THROTTLER_STORAGE`; `ThrottlerGuard` rejects with
91
- `ThrottlerException`; storage `ThrottlerMemoryStorage` / `ThrottlerRedisStorage`;
92
- decorators `Throttle(limit, ttl)` and `SkipThrottle(skip?)`.
93
-
94
- ### Validation: which package ships the pipe, and why a route can answer 201 instead of 400
95
-
96
- - **Check `package.json` before writing validation.** `@galaxy-stack/orbit-core` ships
97
- `ZodValidationPipe` and `createZodDto`; `@galaxy-stack/orbit-validation` is a **separate
98
- package** that a project may not have installed at all (measured: a GymFlow backend had only
99
- orbit-core and orbit-common, while the agent documented itself against orbit-validation).
100
- - `@UsePipes` lives in **orbit-common** and stores pipes under the metadata key
101
- `"orbit:pipes"`; `orbit-core`'s pipeline reads the **same key**, so a pipe registered with
102
- `@UsePipes` is wired correctly — the key is not the usual suspect.
103
- - Both `ZodValidationPipe` (orbit-core) and a hand-written body pipe throw
104
- `BadRequestException("Validation failed: …")`, which the pipeline maps to **400**.
105
- - **Measured failure worth knowing**: in one backend, `PUT /members/:id` guarded by a small
106
- hand-written `PipeTransform` returned 400 as expected, while `POST /members` guarded by
107
- orbit-core's `ZodValidationPipe` answered **201** for a body the schema rejects
108
- (`name: "A"`, `email: "khong-phai-email"`). So the core pipe was not invoked on that route.
109
- - When a route answers 201 for a body the schema rejects, check in this order: (1) the pipe is
110
- attached to the **method** and the handler really reads `@Body()`, (2) the schema is strict
111
- enough for the payload, (3) add a `console.log` inside `transform` to prove the pipe runs,
112
- and (4) prefer a small `PipeTransform` that validates only `metadata.type === "body"`
113
- (that is the shape that works) instead of relying on the framework pipe.
114
-
115
- ### Request pipeline contracts (guards, pipes, interceptors, filters)
116
-
117
- These are the exact interfaces the pipeline passes around (from
118
- `orbit-core/dist/pipeline/execution-pipeline.d.ts`, re-exported by `orbit-common`):
119
-
120
- ```ts
121
- interface ExecutionContext {
122
- getRequest<T = any>(): T;
123
- getResponse<T = any>(): T;
124
- getHandler(): Function;
125
- getClass(): Type;
126
- switchToHttp(): HttpArgumentsHost; // { getRequest<T>(): T; getResponse<T>(): T }
127
- }
128
- interface CanActivate { canActivate(context: ExecutionContext): boolean | Promise<boolean>; }
129
- interface PipeTransform<T = any, R = any> { transform(value: T, metadata: ArgumentMetadata): R | Promise<R>; }
130
- interface CallHandler<T = any> { handle(): Promise<T>; }
131
- interface GalaxyInterceptor<T = any, R = any> { intercept(context: ExecutionContext, next: CallHandler<T>): Promise<R> | R; }
132
- interface ExceptionFilter<T = any> { catch(exception: T, context: ExecutionContext): any; }
133
- interface ArgumentMetadata { type: 'body' | 'query' | 'param' | 'custom'; metatype?: Type; data?: string; }
134
- ```
135
-
136
- - The pipeline hands an **`ExecutionContext`** to guards, interceptors and filters — not a
137
- Nest `ArgumentsHost`. There is **no `getArgs()`, `getArgByIndex()` or `switchToRpc()`**; read the
138
- request/response with `context.getRequest()` / `context.getResponse()` (or
139
- `context.switchToHttp().getResponse()`), and the handler/class with `getHandler()` / `getClass()`.
140
- - A filter's `catch(exception, context)` **returns whatever becomes the response** (status/body are
141
- derived from what you return, e.g. `new Response(JSON.stringify({ error }), { status: 429 })` for a
142
- `ThrottlerException`).
143
- - Registration: `@UseGuards/@UsePipes/@UseInterceptors/@UseFilters` on the handler or controller, or
144
- provider-level classes; `ExecutionPipeline` resolves them per controller and caches the metadata.
145
-
146
- ### Installing and wiring the database layer
147
-
148
- `orbit new` does **not** install a database layer. When a task needs one, add both
149
- packages — `drizzle-orm` is a **peer dependency** (>=0.29) of `orbit-database@0.1.x` and
150
- nothing works without it:
151
-
152
- ```sh
153
- bun add @galaxy-stack/orbit-database drizzle-orm
154
- ```
155
-
156
- Two legitimate shapes:
157
-
158
- - **orbit-database + Drizzle** — `@Entity`/`@Column`, `DatabaseModule.forRoot/forFeature`,
159
- `DrizzleRepository`, `@Transactional`.
160
- - **Plain `bun:sqlite`** — `import { Database } from 'bun:sqlite'` behind a token provider
161
- plus SQL migrations; no peer dependency. Pick one deliberately and say which in the report.
162
-
163
- Complete orbit-database wiring, matching the declarations:
164
-
165
- ```ts
166
- // tables.ts — Drizzle tables come from drizzle-orm; the entity decorators point at them
167
- import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core';
168
- export const membersTable = sqliteTable('members', {
169
- id: integer('id').primaryKey({ autoIncrement: true }),
170
- name: text('name').notNull(),
171
- });
172
-
173
- // member.entity.ts
174
- @Entity('members')
175
- export class Member {
176
- @PrimaryGeneratedColumn('increment') id!: number;
177
- @Column() name!: string;
178
- }
179
-
180
- // members.module.ts
181
- @Module({
182
- imports: [DatabaseModule.forFeature([Member], new Map([[Member, membersTable]]))],
183
- controllers: [MembersController],
184
- providers: [
185
- MembersService,
186
- { provide: MemberRepository, useFactory: (db: any) => new MemberRepository(db, membersTable), inject: [DATA_SOURCE] },
187
- ],
188
- })
189
- export class MembersModule {}
190
-
191
- // member.repository.ts — DrizzleRepository(db, table, entityClass)
192
- export class MemberRepository extends DrizzleRepository<Member> {
193
- constructor(db: any, table: any) { super(db, table, Member); }
194
- }
195
- ```
196
-
197
- App module: `DatabaseModule.forRoot({ type: 'sqlite', database: './app.db' })` (`database`, not
198
- `url`, for SQLite; `:memory:` works for tests).
199
-
200
- ### Scaffolding: use the installed binaries, never `bunx …@latest`
201
-
202
- `orbit` (from `@galaxy-stack/orbit-cli`) and `nebula` (from `@galaxy-stack/nebula-cli`) are
203
- installed in this environment — on `PATH`, otherwise at `~/.bun/bin/orbit`. Run them
204
- directly:
205
-
206
- ```sh
207
- orbit new gymflow-backend --directory backend
208
- nebula init --yes --theme violet
209
- nebula add button card badge
210
- ```
211
-
212
- Do **not** run `bunx @galaxy-stack/orbit-cli@latest …`: bunx re-resolves the package from the
213
- registry on every call, and when the registry is slow it stalls on "Resolving dependencies"
214
- for minutes (measured: 180s, then 300s, then 480s inside a single step, which burned most of
215
- that step's budget). If a binary is really missing, prefer `bunx --offline` (the local cache)
216
- or a pinned version (`bunx @galaxy-stack/orbit-cli@0.1.13`) with a generous timeout.
217
-
218
- ### Compiled against
219
-
220
- This map was compiled from the declarations of the versions these projects install:
221
- orbit-core@0.2.3, orbit-common@0.1.15, orbit-database@0.1.10, orbit-security@0.1.10,
222
- orbit-throttler@0.1.10. `read_file` on a package's `package.json` is still how the
223
- installed version is confirmed; if it differs from that list, trust the installed
224
- declarations for the delta and say so in the final report instead of re-reading
225
- everything.
226
-
227
- ### Rate limiting and throttling recipes
228
-
229
- - App-level limiter (no guard): `const limiter = rateLimit({ windowMs: 60_000, maxRequests: 100 })`
230
- then mount `limiter.createMiddleware()` through the middleware machinery
231
- (`consumer.apply(limiter.createMiddleware()).forRoutes('*')` or `app.use(...)`).
232
- `SlidingWindowRateLimiter` exposes `increment(key): boolean`, `getInfo(key)`, `reset(key)`,
233
- `destroy()`; `tokenBucket()` returns a `TokenBucketRateLimiter` with `consume(key, tokens?)`.
234
- - Route-level throttling: `ThrottlerModule.forRoot({ ttl: 60, limit: 100 })` (`ttl` and `limit`
235
- are required) plus `@UseGuards(ThrottlerGuard)` on the controller and `@Throttle(limit, ttl)` /
236
- `@SkipThrottle()` per handler.
237
- - `ThrottlerGuard` rejects with `ThrottlerException`, a plain `Error`: add a
238
- `@Catch(ThrottlerException)` filter that returns **429**, or the client sees a 500.
239
- - Custom throttler storage implements `ThrottlerStorage { increment(key, ttl), get(key), reset(key) }`;
240
- memory storage is the default and `ThrottlerRedisStorage` targets Redis.
241
-
242
- ### Signatures agents used to need a `.d.ts` read for
243
-
244
- - Exceptions (`orbit-common`): `new BadRequestException(message?: string | Record<string, unknown>)`
245
- and the same shape for the other `*Exception` subclasses; base `HttpException(response, status)`.
246
- - Validation: `ValidationPipe` and `ZodValidationPipe` implement `PipeTransform`; a custom pipe
247
- receives `ArgumentMetadata = { type: 'body' | 'query' | 'param' | 'custom', metatype?: Type, data?: string }`.
248
- - Parameter decorators (`orbit-common/decorators/params.decorator`): `@Body()`, `@Query('key'?)`,
249
- `@Param('key'?)`, `@Headers('key'?)`, `@Req()`/`@Res()`, `@Ip()`, `@Session()`,
250
- `@UploadedFile()`/`@UploadedFiles()`; metadata via `getParamMetadata`.
251
- - Transforms: `Transform(fn, { toClassOnly?, toPlainOnly?, groups? })`, `ToInt()`, `ToFloat()`,
252
- `ToBoolean()`, `ToDate()`, `Trim()`, `ToArray()`, `DefaultValue(value)`, `ToLowerCase()`, `ToUpperCase()`.
253
- - Security: `SecurityModule.forRoot({ helmet?: HelmetOptions | false, csrf?: CsrfOptions | false, isGlobal? })`;
254
- `CsrfOptions = { cookie?, ignoreMethods?, getToken?, sessionKey? }` — give `getToken(req)` when API
255
- clients cannot carry cookies; `HelmetOptions.contentSecurityPolicy` and `crossOriginEmbedderPolicy`
256
- accept `boolean | options`.
257
- - Rate limiting: `rateLimit({ windowMs?, maxRequests?, keyGenerator?, message?, statusCode?, headers?,
258
- skipFailedRequests?, skipSuccessfulRequests?, onLimitReached? })`; `tokenBucket(...)` takes the same
259
- options with burst semantics.
260
- - Throttler: `ThrottlerModule.forRoot({ ttl, limit, ignoreUserAgents?, skipIf?, getTracker? })` — `ttl` and
261
- `limit` are **required**; `Throttle(limit, ttl)`, `SkipThrottle(skip?)`, `ThrottleOptions = { limit?, ttl? }`;
262
- storage record `{ totalHits, expiresAt, isBlocked, timeToExpire }`; `ThrottlerGuard` rejects with
263
- `ThrottlerException`, which is a plain `Error` — map it to **429** with a `@Catch(ThrottlerException)`
264
- filter or the client sees a 500.
265
- ### Database wiring — the concrete pattern (this is why `orbit-database` was read 7× per step)
266
-
267
- - SQLite lives in `database`, not `url`: `DatabaseModule.forRoot({ type: 'sqlite', database: './app.db' })`
268
- (`':memory:'` is accepted). `url` is for postgres/mysql/libsql/mongodb.
269
- - Feature module: `DatabaseModule.forFeature([Member], new Map([[Member, 'members']]))` — entities
270
- plus the entity→table map; the second argument is required.
271
- - Entities: `@Entity('members')`, `@PrimaryGeneratedColumn('increment' | 'uuid')`, `@Column({ nullable?: boolean, ... })`.
272
- - Repositories: prefer the concrete `DrizzleRepository<T>` — `new DrizzleRepository(db, table, Member)` —
273
- over hand-implementing `BaseRepository<T>`. The base declares `findAll()`, `findOne(id)`,
274
- `findBy(where)`, `create(entity)`, `update(id, patch)`, `delete(id)` **and `count(where?)`** as abstract;
275
- `DrizzleRepository` also exposes `getQueryBuilder()`, `getRawDb()` and `getTable()`.
276
- - Transactions: `@Transactional()` on a service method wraps the repository calls inside it.
277
- - Data source: `createDataSource(options)` / `BunDataSource`; inject it with the `DATA_SOURCE` token
278
- when you need the raw handle instead of a repository.
279
- ### Security and throttling wiring — trust the declarations, not the package READMEs
280
-
281
- Two shipped READMEs contradict their own exported types (verified against the installed
282
- `orbit-security` / `orbit-throttler` on 2026-09-29), which is what made agent runs read both the
283
- README and the declarations and still stay unsure:
284
-
285
- - `orbit-security/README.md` shows `csrf: { enabled, tokenKey, cookieName }`, but `CsrfOptions` is
286
- `{ cookie?: { name?, path?, httpOnly?, secure?, sameSite?, maxAge? }, ignoreMethods?, getToken?, sessionKey? }`.
287
- There is no `enabled` flag — omit `csrf` to disable it — and the cookie name lives in `cookie.name`.
288
- Use `getToken(req)` when API clients cannot carry cookies.
289
- - `orbit-throttler/README.md` shows `new RedisThrottlerStorage(...)` (the class is `ThrottlerRedisStorage`)
290
- and a `throttlers: [...]` list, but `ThrottlerModuleOptions` extends `ThrottlerOptions` with only
291
- `storage?` and `errorMessage?`, and `ttl`/`limit` are required. Custom storage implements
292
- `ThrottlerStorage { increment(key, ttl), get(key), reset(key) }`.
293
-
294
- ```ts
295
- @Module({
296
- imports: [
297
- SecurityModule.forRoot({
298
- helmet: { contentSecurityPolicy: { directives: { defaultSrc: ["'self'"] } }, frameguard: { action: 'deny' } },
299
- csrf: { cookie: { name: 'XSRF-TOKEN', httpOnly: true, sameSite: 'lax' }, ignoreMethods: ['GET', 'HEAD'] },
300
- }),
301
- ThrottlerModule.forRoot({ ttl: 60, limit: 100, storage: new ThrottlerMemoryStorage() }),
302
- ],
303
- })
304
- export class AppModule {}
305
-
306
- export class ApiKeyGuard implements CanActivate {
307
- canActivate(context: any): boolean | Promise<boolean> { /* read the header, compare, throw UnauthorizedException */ }
308
- }
309
-
310
- @Catch(ThrottlerException)
311
- export class ThrottleFilter implements ExceptionFilter<ThrottlerException> {
312
- catch(exception: ThrottlerException, host: ArgumentsHost) { /* respond 429 */ }
313
- }
314
- ```
315
-
316
- - Guards: `@UseGuards(ApiKeyGuard)` (class or instance); `CanActivate.canActivate(context)` returns
317
- `boolean | Promise<boolean>`; filters: `@UseFilters(ThrottleFilter)` with `ExceptionFilter.catch`.
318
- Mapping `ThrottlerException` (a plain `Error`) to 429 needs exactly this filter, otherwise the
319
- client sees a 500.
320
- - Middleware: a module class implements `configure(consumer: MiddlewareConsumer)`; then
321
- `consumer.apply(HelmetMiddleware).forRoutes('*')`, narrowed with `.exclude(...)`.
322
- `RouteInfoOrController = string | { path, method? } | Type | (...)`.
323
- ### Middleware, CORS and static serving
324
-
325
- - A module registers middleware by implementing `NestModule`:
326
- `configure(consumer: MiddlewareConsumer): void | Promise<void>` then
327
- `consumer.apply(HelmetMiddleware).forRoutes('*')`, narrowed with `.exclude(...)`. `apply` accepts
328
- `Middleware = MiddlewareFunction | MiddlewareClass | GalaxyMiddleware`.
329
- - A middleware class implements `GalaxyMiddleware` (alias `OrbitMiddleware`):
330
- `use(request: Request, next: () => Promise<Response>): Promise<Response>`; a plain function of the
331
- same shape works too.
332
- - `CorsOptions = { origin?: string | string[] | boolean | ((origin: string) => boolean), methods?,
333
- allowedHeaders?, exposedHeaders?, credentials?, maxAge?, preflightContinue?, optionsSuccessStatus? }`,
334
- passed through `OrbitFactory.create(AppModule, { cors: { ... } })` (`cors: true` uses defaults).
335
- - `StaticServeOptions = { root, prefix?, index?, dotFiles?: 'allow' | 'deny' | 'ignore', maxAge?,
336
- immutable?, etag?, lastModified?, cacheMaxSize?, cacheTtl?, cacheDebug? }`.
337
- ### Application API and global registration
338
-
339
- `OrbitApplication` (returned by `OrbitFactory.create`) exposes exactly this public surface:
340
- `use(middleware, { forRoutes?, exclude? })`, `enableCors(options?: CorsOptions)`,
341
- `useStaticAssets(options: Partial<StaticServeOptions>)`, `listen(port?)`, `close(signal?)`,
342
- `enableShutdownHooks()`, `onShutdown(callback)`, `getContainer()`, `getServer()`, `getRoutes()`,
343
- `setRoutes()`, `setModules()`, `setMiddlewareConfigurations()`.
344
-
345
- There is **no** `useGlobalPipes`, `useGlobalGuards` or `useGlobalFilters` — do not go looking for one.
346
- Apply `@UsePipes` / `@UseGuards` / `@UseFilters` on the controller (or a shared base controller),
347
- or register the pipe/guard/filter class in the module's `providers`. CORS and static assets are
348
- app-level calls (`enableCors`, `useStaticAssets`) rather than module imports.
349
- **Versions, not APIs.** To confirm which version is installed, `read_file` on that
350
- package's `package.json` is allowed and cheap. The map above was compiled from the installed
351
- declarations of orbit-core, orbit-common, orbit-database, orbit-security and orbit-throttler,
352
- plus the application surface — treat it as ground truth rather than re-reading `node_modules/**/*.d.ts`
353
- to double-check it. Reading a package's `index.d.ts` should be unnecessary now. If a signature looks
354
- wrong or is missing, note it in the final report (one line) so the map can be corrected; that is
355
- cheaper and more useful than re-deriving the declarations on every run.
356
-
357
- ## Validation (Zod)
358
-
359
- `@galaxy-stack/orbit-validation` re-exports the pipe types that `orbit-core`
360
- already ships. Zod v4 is what the CLI installs, and both pipes accept v4 and v3
361
- error shapes.
362
-
363
- - Simple single-parameter handler — bind the schema to the pipe:
364
-
365
- ```ts
366
- import { Controller, Post, ZodValidationPipe } from '@galaxy-stack/orbit-core';
367
- import { Body, UsePipes } from '@galaxy-stack/orbit-common';
368
- import { z } from 'zod';
369
-
370
- const CreateMemberSchema = z.object({ name: z.string().min(2), email: z.string().email() });
371
-
372
- @Controller('members')
373
- export class MembersController {
374
- @Post()
375
- @UsePipes(new ZodValidationPipe(CreateMemberSchema))
376
- create(@Body() dto: z.infer<typeof CreateMemberSchema>) { return this.members.create(dto); }
377
- }
378
- ```
379
-
380
- - **Do not** write `@Body(new ZodValidationPipe(...))`: `@Body` only accepts a
381
- field name (`@Body('name')`), not a pipe.
382
- - `@UsePipes` is **method/class level** and runs for every argument of the
383
- method. When a handler mixes a validated body with `@Param`/`@Query` strings,
384
- write one small scoped pipe that checks `metadata.type`:
385
-
386
- ```ts
387
- import { BadRequestException, type PipeTransform } from '@galaxy-stack/orbit-core';
388
- import { type ArgumentMetadata } from '@galaxy-stack/orbit-common';
389
-
390
- class BodyOnlyPipe implements PipeTransform {
391
- constructor(private readonly schema: { safeParse(v: unknown): any }) {}
392
- transform(value: unknown, metadata: ArgumentMetadata) {
393
- if (metadata.type !== 'body') return value; // leave params alone
394
- const result = this.schema.safeParse(value);
395
- if (!result.success) {
396
- const issues = result.error?.issues ?? result.error?.errors ?? [];
397
- throw new BadRequestException('Validation failed: ' +
398
- issues.map((i: any) => `${i.path?.join('.') || 'value'}: ${i.message}`).join('; '));
399
- }
400
- return result.data;
401
- }
402
- }
403
- ```
404
-
405
- - `createZodDto(schema)` + a class-level `ValidationPipe` is **not reliable on
406
- Bun**: it reads the parameter metatype from `design:paramtypes`, which Bun's
407
- transpiler does not emit, so validation silently does not run. Prefer
408
- `ZodValidationPipe` (or the scoped pipe above).
409
- - Validation errors surface as `400 Bad Request`; unknown ids use
410
- `NotFoundException` for `404`.
411
-
412
- ## Editing files
413
-
414
- Use `edit_file` with a unique `oldText`/`newText` pair; add surrounding lines when the match is ambiguous. The edit precondition hash is optional — omit it and rely on the oldText match. Never reuse a content hash from an earlier turn or from compacted context; re-read the file if you need its current state.
415
-
416
- ## Scaffolding and dependency wiring
417
-
418
- Use the Orbit CLI; do not hand-wire modules or add framework packages manually:
419
-
420
- - New project: `bunx @galaxy-stack/orbit-cli new <app>` (or the installed `orbit new`) scaffolds the app and installs dependencies.
421
- - New component: `orbit generate <type> <name>` (aliases `orbit g co|s|mo|gu|pi|in|mi|f|res`) creates the file **and updates `@Module` imports automatically**. `orbit g resource <name>` generates a full CRUD resource.
422
- - Only add packages when the CLI does not cover the case: `bun add @galaxy-stack/orbit-*`. Never edit `package.json`/lockfiles by hand to add a package, and never copy `orbit` sources out of `node_modules`.
423
-
424
- The companion MCP server (`@galaxy-stack/orbit-mcp`) is for searching knowledge and reviewing code. Its `orbit_scaffold_*` tools only **return** generated content; they do not write files or update module imports. To apply scaffolding in the workspace, use the CLI (or write the returned files deliberately).
425
-
426
- ## Security baseline (non-negotiable for production code)
427
-
428
- - `SecurityModule.forRoot({ helmet: true, csrf: true })` — OWASP headers + CSRF.
429
- - `ThrottlerModule` for rate limiting on auth and write routes.
430
- - GraphQL: `introspection: false` in production; `security: { maxDepth: 10,
431
- maxComplexity: 1000, maxAliases: 30 }`; playground disabled in production.
432
- - Never log secrets; redact before logging.
433
- - Sanitize any stored HTML with the orbit-security Sanitizer.
434
-
435
- ## Module template
436
-
437
- ```ts
438
- import { Module } from '@galaxy-stack/orbit-core';
439
-
440
- @Module({
441
- controllers: [UserController],
442
- providers: [UserService],
443
- exports: [UserService],
444
- })
445
- export class UserModule {}
446
- ```
447
-
448
- ## Controller template
449
-
450
- ```ts
451
- import { Controller, Get, Post } from '@galaxy-stack/orbit-core';
452
- import { Body, Param, HttpCode, UseGuards } from '@galaxy-stack/orbit-common';
453
-
454
- @Controller('users')
455
- export class UserController {
456
- constructor(private readonly users: UserService) {}
457
-
458
- @Get(':id')
459
- find(@Param('id') id: string) { return this.users.find(id); }
460
-
461
- @Post()
462
- @HttpCode(201)
463
- @UseGuards(JwtAuthGuard)
464
- create(@Body() body: CreateUserDto) { return this.users.create(body); }
465
- }
466
- ```
467
-
468
- > **Import sources matter.** Route/method decorators (`Controller`, `Get`, `Post`,
469
- > `Put`, `Patch`, `Delete`, `Module`, `Injectable`) and the app factory
470
- > (`OrbitFactory`) come from `@galaxy-stack/orbit-core`. Parameter decorators
471
- > (`Body`, `Param`, `Query`, `Headers`, `Req`, `Res`), method decorators
472
- > (`HttpCode`, `Header`, `UsePipes`, `UseGuards`, `UseInterceptors`, `Catch`) and
473
- > the `Transform`/`ToInt`/`Trim` helpers come from `@galaxy-stack/orbit-common`.
474
- > Importing a `Body`/`Param` from `orbit-core` throws
475
- > `Export named 'Body' not found` at runtime.
476
-
477
- ## Route prefixing and versioning
478
-
479
- - A route prefix belongs to the controller path: `@Controller('api/v1/members')`.
480
- Orbit has **no** `app.setGlobalPrefix(...)` — that API is NestJS, not Orbit.
481
- Do not search `node_modules` for it; a missing global-prefix helper means the
482
- prefix goes on each controller (or on a shared base path constant).
483
- - Versioned APIs use the built-in manager, exported from `@galaxy-stack/orbit-core`
484
- (root entry re-exports `./versioning/versioning`):
485
-
486
- ```ts
487
- import { Version, VERSION_NEUTRAL, versioningManager } from '@galaxy-stack/orbit-core';
488
-
489
- // once at bootstrap, before app.listen()
490
- versioningManager.configure({ type: 'uri', defaultVersion: '1', prefix: 'v' });
491
-
492
- @Controller('members')
493
- export class MemberController {
494
- @Get() @Version('1') list() {}
495
- @Get('health') @Version(VERSION_NEUTRAL) health() {}
496
- }
497
- ```
498
-
499
- `type` is `'uri' | 'header' | 'media' | 'custom'`; `prefix: false` turns the URI
500
- segment off; `header`/`key`/`extractor` tune the non-URI strategies.
501
- - Checking the installed API version: `read_file` on a specific
502
- `package.json`, `README.md` or `*.d.ts` inside `node_modules` is allowed.
503
- Grep/glob across the whole dependency tree is refused by the host — read the one
504
- declaration file instead of scanning the package.
505
-
506
- ## GraphQL template
507
-
508
- ```ts
509
- import { Resolver, Query, Mutation, Args } from '@galaxy-stack/orbit-graphql';
510
-
511
- @Resolver()
512
- export class UserResolver {
513
- @Query(() => [User])
514
- users() { return this.userService.list(); }
515
-
516
- @Mutation(() => User)
517
- createUser(@Args('input') input: CreateUserInput) {
518
- return this.userService.create(input);
519
- }
520
- }
521
- ```
522
-
523
- Module wiring with security limits:
524
-
525
- ```ts
526
- GraphQLModule.forRoot({
527
- autoSchemaFile: true,
528
- introspection: process.env.NODE_ENV !== 'production',
529
- security: { maxDepth: 10, maxComplexity: 1000, maxAliases: 30 },
530
- resolvers: [UserResolver],
531
- })
532
- ```
64
+ 3. Every feature is a `@Module({ controllers, providers, exports })` class; providers are
65
+ `@Injectable()` classes injected through the constructor.
66
+ 4. Validate every external input with a Zod schema through a pipe; see `{ section: "zod-validation" }`.
67
+ 5. `orbit new` installs no database layer. Pick a shape deliberately (orbit-database + Drizzle, or
68
+ `bun:sqlite` + Drizzle behind your own provider) and say which in the report.
69
+ 6. Prefixing belongs to the controller path (`@Controller('api/v1/members')`); Orbit has no
70
+ `app.setGlobalPrefix()`.
71
+
72
+ ## Rules a declaration will not tell you
73
+
74
+ - **Import sources.** Route decorators and `ZodValidationPipe` come from `orbit-core`; parameter and
75
+ method decorators (`Body`, `Param`, `Query`, `Headers`, `HttpCode`, `UsePipes`,
76
+ `UseGuards`, `UseInterceptors`, `Catch`, `UseFilters`), `NotFoundException` and the
77
+ exception classes come from `orbit-common`. Importing them from core throws at runtime.
78
+ - **`@Body` takes a field name, never a pipe.** Put `@UsePipes(new ZodValidationPipe(schema))` at
79
+ method level; a method-level pipe runs for every argument, so scope it by `metadata.type === 'body'`
80
+ when the handler also takes `@Param` / `@Query` strings.
81
+ - **On orbit-core ≤ 0.2.3, `@HttpCode(n)` masks failure statuses** (the build does
82
+ `status: httpCode || response.status`, so a rejected body still answers 201). Keep `@HttpCode` off
83
+ any handler that can fail and return an explicit `Response` instead. Details: topic `pitfalls`.
84
+ - **Two `ExceptionFilter` interfaces exist.** The runtime hands an `ExecutionContext`
85
+ (`getRequest()` / `getResponse()` / `getHandler()` / `getClass()`); the one in
86
+ `orbit-common` typed against a Nest `ArgumentsHost` disagrees with the runtime. Type the second
87
+ parameter `any` and use only those four methods. A filter's return value becomes the response.
88
+ - **No global registration.** There is no `useGlobalPipes`, `useGlobalGuards` or
89
+ `useGlobalFilters`. Decorate a shared abstract base controller — class-level decorators are
90
+ inherited through the prototype chain, so you edit one file instead of every controller.
91
+ - **Throttling is one import.** `ThrottlerModule.forRoot()` is `global: true` and already provides
92
+ `ThrottlerGuard`; `ThrottlerException` is a plain `Error` that the pipeline maps to 500,
93
+ so add one `@Catch(ThrottlerException)` filter that answers 429. `@Throttle(limit, ttl)` — limit
94
+ first, `ttl` in seconds.
95
+ - **Close what you open.** Any script or probe that boots the app or opens the database must close the
96
+ handle and call `process.exit()`, or the command waits until its timeout.
97
+ - **Do not run `bunx @galaxy-stack/orbit-cli@latest`.** `bunx` re-resolves from the registry on
98
+ every call and stalls for minutes. The `orbit` and `nebula` binaries are already on `PATH`.
99
+ - **The scaffold tools return text.** `orbit_scaffold_module` / `orbit_scaffold_graphql` never write
100
+ files, and the module scaffold wires no database on purpose.
101
+
102
+ ## Security baseline
103
+
104
+ - `SecurityModule.forRoot({ helmet: {}, csrf: { ignoreMethods: ['GET', 'HEAD'] } })` — OWASP headers plus CSRF.
105
+ `helmet`/`csrf` take an options object or `false`; `{ helmet: true }` is a type error, never a shortcut.
106
+ - Rate limiting on auth and write routes: `orbit_recipe { task: "throttle-per-route" }`.
107
+ - GraphQL: introspection off in production, `security: { maxDepth: 10, maxComplexity: 1000, maxAliases: 30 }`.
108
+ - Never log secrets; sanitize any stored HTML with the `orbit-security` sanitizer.
109
+ - Full checklist: topic `security-checklist`.
533
110
 
534
111
  ## Verification checklist (run before declaring done)
535
112
 
536
- 1. `validate_project` passes for the packages you touched (it runs the declared
537
- `bun test`/build scripts).
538
- 2. A dev server is not a verification step. `bun run dev` never exits, produces no
539
- completion evidence, and the logs or probe files it leaves behind are
540
- unreviewed writes that invalidate the validation they were meant to support.
541
- Start one only when the task explicitly asks to exercise a running app —
542
- through the bounded session capability — and stop it before the final
543
- validation.
544
- 3. Mutating routes have validation + auth.
545
- 4. GraphQL module has security limits when used.
546
- 5. No secrets in source; config comes from ConfigModule/env.
113
+ 1. `validate_project` passes for the packages you touched.
114
+ 2. A dev server is not verification evidence. When the task explicitly asks to exercise a running app,
115
+ start it detached with `run_command` (log outside the workspace), probe it with a bounded
116
+ `curl` loop, and stop it before the final validation. This catalog has **no**
117
+ `manage_session` / preview / browser tool — do not spend turns searching for one.
118
+ 3. Mutating routes have validation and auth; rate limiting where it matters.
119
+ 4. GraphQL modules have security limits; no secrets in source.
547
120
 
548
- ## Deeper reference
121
+ ## Companion MCP server
549
122
 
550
- Run the companion MCP server (`@galaxy-stack/orbit-mcp`) for searchable
551
- knowledge, scaffolding tools, and a security review tool:
123
+ `@galaxy-stack/orbit-mcp` (stdio). Every project on this stack should have it connected:
552
124
 
553
125
  ```json
554
- {
555
- "mcpServers": {
556
- "orbit": { "command": "bunx", "args": ["@galaxy-stack/orbit-mcp"] }
557
- }
558
- }
126
+ { "mcpServers": { "orbit": { "command": "npx", "args": ["-y", "@galaxy-stack/orbit-mcp"] } } }
559
127
  ```