@luckystack/core 0.1.0
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 +14 -0
- package/CLAUDE.md +210 -0
- package/LICENSE +21 -0
- package/README.md +93 -0
- package/dist/apiTypeStubs.d.ts +7 -0
- package/dist/apiTypeStubs.js +1 -0
- package/dist/apiTypeStubs.js.map +1 -0
- package/dist/client.d.ts +236 -0
- package/dist/client.js +1344 -0
- package/dist/client.js.map +1 -0
- package/dist/eslint/index.d.ts +10 -0
- package/dist/eslint/index.js +436 -0
- package/dist/eslint/index.js.map +1 -0
- package/dist/index.d.ts +1128 -0
- package/dist/index.js +2619 -0
- package/dist/index.js.map +1 -0
- package/dist/pageRouteValidation-CxZJVwZh.d.ts +665 -0
- package/docs/app-bootstrap.md +419 -0
- package/docs/config-registry.md +350 -0
- package/docs/csrf-config.md +88 -0
- package/docs/error-tracker-registry.md +174 -0
- package/docs/hooks.md +298 -0
- package/docs/rate-limit-strategy.md +170 -0
- package/docs/redis-adapter.md +111 -0
- package/docs/session-types.md +180 -0
- package/docs/socket-bootstrap.md +366 -0
- package/package.json +91 -0
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
# Config Registry
|
|
2
|
+
|
|
3
|
+
> Deep specs for project / deploy / services / avatar / paths config slots. Source: `packages/core/src/`. Bijgewerkt: 2026-05-20.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
The config registries are the single source of truth for runtime project configuration. They follow a uniform pattern:
|
|
8
|
+
|
|
9
|
+
1. A consumer's boot entry calls `registerXConfig({...})` once before any framework code reads a value.
|
|
10
|
+
2. Framework code reads at call time via `getXConfig()` (never at module load) so the registration timing is flexible.
|
|
11
|
+
3. Boolean `isXConfigRegistered()` helpers exist for code paths that must fail closed when the consumer forgot to register.
|
|
12
|
+
|
|
13
|
+
Four independent slots live in this topic:
|
|
14
|
+
|
|
15
|
+
- **Project config** — runtime tunables (rate limits, session policy, HTTP, auth, sockets, paths). Deep-merged over `DEFAULT_PROJECT_CONFIG` so consumers only supply the keys they want to override.
|
|
16
|
+
- **Deploy config** — multi-env topology consumed by `@luckystack/router` (resources, environments, routing, development).
|
|
17
|
+
- **Services config** — service + preset definitions consumed by the router / preset loader.
|
|
18
|
+
- **Avatar config** — disk formats + cache header for `serveAvatar`.
|
|
19
|
+
|
|
20
|
+
Path getters (`getSrcDir`, `getGeneratedApiDocsPath`, …) resolve project-relative paths against `ROOT_DIR` (auto-detected workspace root) and read `getProjectConfig().paths.*` at call time.
|
|
21
|
+
|
|
22
|
+
## API Reference — Project Config
|
|
23
|
+
|
|
24
|
+
### `registerProjectConfig(config: ProjectConfigInput): void`
|
|
25
|
+
|
|
26
|
+
**Signature:**
|
|
27
|
+
```typescript
|
|
28
|
+
export const registerProjectConfig = (config: ProjectConfigInput): void
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
**Parameters:**
|
|
32
|
+
| Name | Type | Required | Description |
|
|
33
|
+
|---|---|---|---|
|
|
34
|
+
| `config` | `ProjectConfigInput` (deep-partial of `ProjectConfig`) | yes | Only the keys to override. Missing keys fall back to `DEFAULT_PROJECT_CONFIG`. |
|
|
35
|
+
|
|
36
|
+
**Returns:** `void`
|
|
37
|
+
|
|
38
|
+
**Behavior:**
|
|
39
|
+
- Deep-merges `config` over `DEFAULT_PROJECT_CONFIG` (plain-object branches recurse; primitives + arrays are replaced wholesale).
|
|
40
|
+
- Sets the registration flag so `isProjectConfigRegistered()` returns true.
|
|
41
|
+
- Replaces (last-write-wins) on repeated calls — the latest call is the active config.
|
|
42
|
+
|
|
43
|
+
**Errors / Edge cases:**
|
|
44
|
+
- `undefined` keys in the override are skipped (treated as "no override").
|
|
45
|
+
- Arrays are NOT merged element-wise — passing `cors.allowedOrigins: ['x']` replaces the default `[]` array.
|
|
46
|
+
- Calling after framework hot paths already ran is allowed but the values only take effect on subsequent reads (everything reads call-time).
|
|
47
|
+
|
|
48
|
+
**Example:**
|
|
49
|
+
```typescript
|
|
50
|
+
import { registerProjectConfig } from '@luckystack/core';
|
|
51
|
+
|
|
52
|
+
registerProjectConfig({
|
|
53
|
+
defaultLanguage: 'en',
|
|
54
|
+
session: { expiryDays: 30 },
|
|
55
|
+
http: {
|
|
56
|
+
cors: {
|
|
57
|
+
allowedOrigins: ['https://app.example.com'],
|
|
58
|
+
allowLocalhost: false,
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### `getProjectConfig(): ProjectConfig`
|
|
65
|
+
|
|
66
|
+
**Signature:**
|
|
67
|
+
```typescript
|
|
68
|
+
export const getProjectConfig = (): ProjectConfig
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**Returns:** The active fully-merged `ProjectConfig`.
|
|
72
|
+
|
|
73
|
+
**Behavior:**
|
|
74
|
+
- Returns the currently merged config object (reference-stable until the next `registerProjectConfig`).
|
|
75
|
+
- Returns `DEFAULT_PROJECT_CONFIG` when nothing was registered yet.
|
|
76
|
+
|
|
77
|
+
**Example:**
|
|
78
|
+
```typescript
|
|
79
|
+
import { getProjectConfig } from '@luckystack/core';
|
|
80
|
+
|
|
81
|
+
const { http, rateLimiting } = getProjectConfig();
|
|
82
|
+
const cookieName = http.sessionCookieName;
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### `getProjectName(): string`
|
|
86
|
+
|
|
87
|
+
**Signature:**
|
|
88
|
+
```typescript
|
|
89
|
+
export const getProjectName = (): string
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
**Returns:** The active project namespace (used as Redis key prefix for session, password reset, rate limits, OAuth state, etc.).
|
|
93
|
+
|
|
94
|
+
**Behavior:** Resolves in this order (first non-empty wins):
|
|
95
|
+
1. `projectConfig.session.projectName`
|
|
96
|
+
2. `process.env.PROJECT_NAME`
|
|
97
|
+
3. literal `'luckystack'`
|
|
98
|
+
|
|
99
|
+
**Example:**
|
|
100
|
+
```typescript
|
|
101
|
+
import { getProjectName } from '@luckystack/core';
|
|
102
|
+
|
|
103
|
+
const key = `${getProjectName()}-session:${token}`;
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### `isProjectConfigRegistered(): boolean`
|
|
107
|
+
|
|
108
|
+
**Signature:**
|
|
109
|
+
```typescript
|
|
110
|
+
export const isProjectConfigRegistered = (): boolean
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
**Returns:** `true` only after `registerProjectConfig` has been called at least once.
|
|
114
|
+
|
|
115
|
+
**Behavior:**
|
|
116
|
+
- Pure boot-time guard — does not throw.
|
|
117
|
+
- Framework packages use this for "did the installer forget to register?" warnings without crashing tests/CLI contexts.
|
|
118
|
+
|
|
119
|
+
### `DEFAULT_PROJECT_CONFIG: ProjectConfig`
|
|
120
|
+
|
|
121
|
+
Exported so consumers can spread + override structurally:
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
import { DEFAULT_PROJECT_CONFIG, registerProjectConfig } from '@luckystack/core';
|
|
125
|
+
|
|
126
|
+
registerProjectConfig({
|
|
127
|
+
...DEFAULT_PROJECT_CONFIG,
|
|
128
|
+
defaultLanguage: 'nl',
|
|
129
|
+
});
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Notable defaults (verbatim from `projectConfig.ts`):
|
|
133
|
+
|
|
134
|
+
| Key | Default |
|
|
135
|
+
|---|---|
|
|
136
|
+
| `rateLimiting.enabled` | `true` |
|
|
137
|
+
| `rateLimiting.store` | `'memory'` |
|
|
138
|
+
| `rateLimiting.defaultApiLimit` | `60` |
|
|
139
|
+
| `rateLimiting.defaultIpLimit` | `100` |
|
|
140
|
+
| `rateLimiting.windowMs` | `60_000` |
|
|
141
|
+
| `session.expiryDays` | `7` |
|
|
142
|
+
| `session.perBrowser` | `'single'` |
|
|
143
|
+
| `session.perUser` | `'single'` |
|
|
144
|
+
| `session.onConflict` | `'revokeOld'` |
|
|
145
|
+
| `session.notifyOldDeviceOnRevoke` | `true` |
|
|
146
|
+
| `http.sessionCookieName` | `'token'` |
|
|
147
|
+
| `http.sessionCookieSameSite` | `'Strict'` |
|
|
148
|
+
| `http.requestBodyMaxBytes` | `1048576` |
|
|
149
|
+
| `http.healthEndpoint` | `'/_health'` |
|
|
150
|
+
| `http.liveEndpoint` | `'/livez'` |
|
|
151
|
+
| `http.readyEndpoint` | `'/readyz'` |
|
|
152
|
+
| `http.cors.credentials` | `true` |
|
|
153
|
+
| `http.cors.allowedOrigins` | `[]` |
|
|
154
|
+
| `http.cors.allowLocalhost` | `false` |
|
|
155
|
+
| `auth.bcryptRounds` | `10` |
|
|
156
|
+
| `auth.providerAccountStrategy` | `'per-provider'` |
|
|
157
|
+
| `auth.forgotPassword` | `'disabled'` |
|
|
158
|
+
| `auth.passwordResetTtlSeconds` | `3600` |
|
|
159
|
+
| `socket.maxHttpBufferSize` | `5 * 1024 * 1024` |
|
|
160
|
+
| `socket.pingTimeout` | `20_000` |
|
|
161
|
+
| `socket.pingInterval` | `25_000` |
|
|
162
|
+
| `sync.fanoutYieldEvery` | `100` |
|
|
163
|
+
| `sync.fanoutYieldMs` | `1` |
|
|
164
|
+
| `offlineQueue.maxSize` | `200` |
|
|
165
|
+
| `offlineQueue.maxAgeMs` | `3_600_000` |
|
|
166
|
+
| `offlineQueue.dropPolicy` | `'drop-oldest'` |
|
|
167
|
+
| `dev.hotReloadDebounceMs` | `120` |
|
|
168
|
+
| `defaultLanguage` | `'en'` |
|
|
169
|
+
| `defaultTheme` | `'light'` |
|
|
170
|
+
|
|
171
|
+
## API Reference — Deploy Config
|
|
172
|
+
|
|
173
|
+
### `registerDeployConfig(config: DeployConfigShape): DeployConfigShape`
|
|
174
|
+
|
|
175
|
+
**Signature:**
|
|
176
|
+
```typescript
|
|
177
|
+
export const registerDeployConfig = (config: DeployConfigShape): DeployConfigShape
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
**Parameters:**
|
|
181
|
+
| Name | Type | Required | Description |
|
|
182
|
+
|---|---|---|---|
|
|
183
|
+
| `config` | `DeployConfigShape` | yes | Deploy topology object — `{ resources, environments?, routing?, development? }`. |
|
|
184
|
+
|
|
185
|
+
**Returns:** The stored config (same reference passed in).
|
|
186
|
+
|
|
187
|
+
**Behavior:**
|
|
188
|
+
- Stores the provided config wholesale (no deep-merge, unlike `registerProjectConfig`).
|
|
189
|
+
- Sets `isDeployConfigRegistered()` to `true`.
|
|
190
|
+
|
|
191
|
+
**Example:**
|
|
192
|
+
```typescript
|
|
193
|
+
import { registerDeployConfig } from '@luckystack/core';
|
|
194
|
+
|
|
195
|
+
registerDeployConfig({
|
|
196
|
+
resources: {
|
|
197
|
+
redis: { type: 'redis', urlEnvKey: 'REDIS_URL', synchronizedEnvKeys: ['SESSION_SECRET'] },
|
|
198
|
+
mongo: { type: 'mongo', urlEnvKey: 'MONGO_URL' },
|
|
199
|
+
},
|
|
200
|
+
environments: {
|
|
201
|
+
production: { redis: 'redis', mongo: 'mongo', bindings: {} },
|
|
202
|
+
},
|
|
203
|
+
routing: { strictBootHandshake: true },
|
|
204
|
+
});
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### `getDeployConfig(): DeployConfigShape`
|
|
208
|
+
|
|
209
|
+
Returns the registered deploy config, or `{ resources: {} }` when nothing was registered. Never throws.
|
|
210
|
+
|
|
211
|
+
### `isDeployConfigRegistered(): boolean`
|
|
212
|
+
|
|
213
|
+
Non-throwing guard. Used by router / boot probes that need a real registration before behaving differently from the empty default.
|
|
214
|
+
|
|
215
|
+
## API Reference — Services Config
|
|
216
|
+
|
|
217
|
+
### `registerServicesConfig(config: ServicesConfigShape): ServicesConfigShape`
|
|
218
|
+
|
|
219
|
+
**Signature:**
|
|
220
|
+
```typescript
|
|
221
|
+
export const registerServicesConfig = (config: ServicesConfigShape): ServicesConfigShape
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
**Parameters:**
|
|
225
|
+
| Name | Type | Required | Description |
|
|
226
|
+
|---|---|---|---|
|
|
227
|
+
| `config` | `ServicesConfigShape` | yes | `{ services, presets }` — services define folder sources, presets bundle multiple services into one artifact. |
|
|
228
|
+
|
|
229
|
+
**Returns:** The stored config.
|
|
230
|
+
|
|
231
|
+
**Behavior:**
|
|
232
|
+
- Stores the config (last-write-wins).
|
|
233
|
+
- Side-effect pattern: the consumer's `services.config.ts` is expected to call this on module import.
|
|
234
|
+
|
|
235
|
+
### `getServicesConfig(): ServicesConfigShape`
|
|
236
|
+
|
|
237
|
+
**Throws** `Error` when no services config has been registered. Message includes guidance to import `services.config.ts` as a side-effect.
|
|
238
|
+
|
|
239
|
+
### `isServicesConfigRegistered(): boolean`
|
|
240
|
+
|
|
241
|
+
Non-throwing guard for code that wants to fall back instead of crashing.
|
|
242
|
+
|
|
243
|
+
## API Reference — Avatar Config
|
|
244
|
+
|
|
245
|
+
### `registerAvatarConfig(config: AvatarConfigInput): void`
|
|
246
|
+
|
|
247
|
+
**Signature:**
|
|
248
|
+
```typescript
|
|
249
|
+
export const registerAvatarConfig = (config: AvatarConfigInput): void
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
**Parameters:**
|
|
253
|
+
| Name | Type | Required | Description |
|
|
254
|
+
|---|---|---|---|
|
|
255
|
+
| `config.formats` | `{ extension: string; contentType: string }[]` | no | Disk formats checked in order; first existing file wins. |
|
|
256
|
+
| `config.cacheControl` | `string` | no | `Cache-Control` header. Default `'public, max-age=86400'`. |
|
|
257
|
+
|
|
258
|
+
**Behavior:**
|
|
259
|
+
- Empty `formats` array is treated as "use default" (keeps the built-in `[{ extension: 'webp', contentType: 'image/webp' }]`).
|
|
260
|
+
- Missing `cacheControl` keeps the default.
|
|
261
|
+
|
|
262
|
+
**Example:**
|
|
263
|
+
```typescript
|
|
264
|
+
import { registerAvatarConfig } from '@luckystack/core';
|
|
265
|
+
|
|
266
|
+
registerAvatarConfig({
|
|
267
|
+
formats: [
|
|
268
|
+
{ extension: 'webp', contentType: 'image/webp' },
|
|
269
|
+
{ extension: 'png', contentType: 'image/png' },
|
|
270
|
+
],
|
|
271
|
+
cacheControl: 'public, max-age=604800',
|
|
272
|
+
});
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
### `getAvatarConfig(): AvatarConfig`
|
|
276
|
+
|
|
277
|
+
Returns the active avatar config (defaults applied).
|
|
278
|
+
|
|
279
|
+
### `DEFAULT_AVATAR_CONFIG: AvatarConfig`
|
|
280
|
+
|
|
281
|
+
```typescript
|
|
282
|
+
{
|
|
283
|
+
formats: [{ extension: 'webp', contentType: 'image/webp' }],
|
|
284
|
+
cacheControl: 'public, max-age=86400',
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
## API Reference — Paths
|
|
289
|
+
|
|
290
|
+
`paths.ts` exports lazy getters that resolve `projectConfig.paths.*` against `ROOT_DIR`. Read at call time so a late `registerProjectConfig({ paths: {...} })` still wins.
|
|
291
|
+
|
|
292
|
+
| Function | Returns | Reads from |
|
|
293
|
+
|---|---|---|
|
|
294
|
+
| `getSrcDir()` | absolute path | `paths.srcDir` |
|
|
295
|
+
| `getServerDir()` | absolute path | `paths.serverDir` |
|
|
296
|
+
| `getSharedDir()` | absolute path | `paths.sharedDir` |
|
|
297
|
+
| `getUploadsDir()` | absolute path | `paths.uploadsDir` |
|
|
298
|
+
| `getPublicDir()` | absolute path | `paths.publicDir` |
|
|
299
|
+
| `getServerFunctionsDir()` | absolute path | `paths.serverFunctionsDir` |
|
|
300
|
+
| `getGeneratedSocketTypesPath()` | absolute path | `paths.generatedSocketTypes` |
|
|
301
|
+
| `getGeneratedApiSchemasPath()` | absolute path | `paths.generatedApiSchemas` |
|
|
302
|
+
| `getGeneratedApiDocsPath()` | absolute path | `paths.generatedApiDocs` |
|
|
303
|
+
| `resolveFromRoot(...segments: string[])` | absolute path | `ROOT_DIR` + joined segments |
|
|
304
|
+
|
|
305
|
+
`ROOT_DIR` is auto-detected by walking up from `process.cwd()` (then `__dirname`) and stopping at the first directory containing `package.json` plus either `tsconfig.json` or `tsconfig.server.json`. Falls back to `process.cwd()` when no marker is found.
|
|
306
|
+
|
|
307
|
+
Deprecated module-level constants exist for backwards compatibility (`SRC_DIR`, `SERVER_DIR`, `SHARED_DIR`, `UPLOADS_DIR`, `PUBLIC_DIR`, `SERVER_FUNCTIONS_DIR`, `GENERATED_SOCKET_TYPES_PATH`, `GENERATED_API_SCHEMAS_PATH`, `GENERATED_API_DOCS_PATH`). These resolve at module load and ignore later `registerProjectConfig` overrides — prefer the getters for new code.
|
|
308
|
+
|
|
309
|
+
## Config keys (top-level `ProjectConfig`)
|
|
310
|
+
|
|
311
|
+
| Key | Type | Default | Description |
|
|
312
|
+
|---|---|---|---|
|
|
313
|
+
| `app.publicUrl` | `string` | `''` | Absolute origin of the deployment; consumed by OAuth callbacks and transactional email links. |
|
|
314
|
+
| `logging.*` | flags | all `false` | Dev-only logging toggles. |
|
|
315
|
+
| `rateLimiting.enabled` | `boolean` | `true` | Kill-switch — when `false`, every check short-circuits to allowed. |
|
|
316
|
+
| `rateLimiting.store` | `'memory' \| 'redis'` | `'memory'` | Backend for the default strategy. |
|
|
317
|
+
| `rateLimiting.windowMs` | `number` | `60000` | Default sliding window. |
|
|
318
|
+
| `session.basedToken` | `boolean` | `false` | When `true`, tokens are stored in sessionStorage + handshake auth instead of cookies. |
|
|
319
|
+
| `session.expiryDays` | `number` | `7` | Session TTL. |
|
|
320
|
+
| `session.perBrowser` | `'single' \| 'multiple'` | `'single'` | Whether a single browser may hold multiple parallel logins. |
|
|
321
|
+
| `session.perUser` | `'single' \| 'multiple'` | `'single'` | Whether a single user may be logged in on multiple devices concurrently. |
|
|
322
|
+
| `session.maxConcurrentPerUser` | `number \| null` | `null` | Cap when `perUser === 'multiple'`. |
|
|
323
|
+
| `session.onConflict` | `'revokeOld' \| 'rejectNew'` | `'revokeOld'` | Policy when the cap is hit. |
|
|
324
|
+
| `session.projectName` | `string` | `''` | Explicit Redis prefix; empty means fall back to `PROJECT_NAME` env. |
|
|
325
|
+
| `http.sessionCookieName` | `string` | `'token'` | Cookie name read by `extractTokenFromSocket` / `extractTokenFromRequest`. |
|
|
326
|
+
| `http.requestBodyMaxBytes` | `number` | `1048576` | Hard cap enforced by `getParams`. |
|
|
327
|
+
| `http.healthEndpoint` | `string` | `'/_health'` | Router boot-handshake endpoint. |
|
|
328
|
+
| `http.cors.allowedOrigins` | `string[] \| (origin: string) => boolean` | `[]` | Static allowlist or sync resolver. |
|
|
329
|
+
| `http.cors.allowLocalhost` | `boolean` | `false` | Convenience flag for dev. |
|
|
330
|
+
| `auth.bcryptRounds` | `number` | `10` | Hash cost factor. |
|
|
331
|
+
| `auth.passwordPolicy.*` | rules | various | Credentials policy. |
|
|
332
|
+
| `auth.forgotPassword` | `'framework' \| 'custom' \| 'disabled'` | `'disabled'` | Reset-flow ownership. |
|
|
333
|
+
| `socket.maxHttpBufferSize` | `number` | `5MB` | Per-message ceiling. |
|
|
334
|
+
| `sync.fanoutYieldEvery` | `number` | `100` | Recipients between event-loop yields. |
|
|
335
|
+
| `offlineQueue.dropPolicy` | `'drop-oldest' \| 'drop-newest' \| 'reject'` | `'drop-oldest'` | Default eviction when full. |
|
|
336
|
+
| `dev.hotReloadDebounceMs` | `number` | `120` | File-watcher debounce. |
|
|
337
|
+
| `paths.*` | paths | see defaults table | Project filesystem layout. |
|
|
338
|
+
| `defaultLanguage` | `string` | `'en'` | Initial language for new sessions. |
|
|
339
|
+
| `socketActivityBroadcaster` | `boolean` | `false` | Enable presence broadcasts. |
|
|
340
|
+
| `socketStatusIndicator` | `boolean` | `false` | Show the floating socket-status badge. |
|
|
341
|
+
| `loginRedirectUrl` | `string` | `'/'` | Post-login destination. |
|
|
342
|
+
|
|
343
|
+
See `packages/core/src/projectConfig.ts` for the full type definitions of `LoggingConfig`, `RateLimitingConfig`, `SessionConfig`, `HttpConfig`, `CorsConfig`, `SecurityHeadersConfig`, `AuthConfig`, `PasswordPolicyConfig`, `SocketConfig`, `SyncConfig`, `SyncStreamThrottleConfig`, `OfflineQueueConfig`, `DevConfig`, and `PathsConfig`.
|
|
344
|
+
|
|
345
|
+
## Related
|
|
346
|
+
|
|
347
|
+
- Function INDEX: `packages/core/CLAUDE.md`
|
|
348
|
+
- Architecture: `docs/ARCHITECTURE_PACKAGING.md`, `docs/ARCHITECTURE_ROUTING.md`
|
|
349
|
+
- README: `packages/core/README.md`
|
|
350
|
+
- Source: `packages/core/src/projectConfig.ts`, `deployConfigRegistry.ts`, `servicesConfigRegistry.ts`, `avatarConfig.ts`, `paths.ts`
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# CSRF Config
|
|
2
|
+
|
|
3
|
+
> Customise the framework's CSRF cookie name, header name, token length and cookie options without forking `@luckystack/server`. Source: `packages/core/src/csrfConfig.ts`. Bijgewerkt: 2026-05-21.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
LuckyStack's CSRF defense is double-submit: on first session write, the login package mints a per-session token; the server reads it from the session record on every state-changing request and compares it against the value the browser sends in a request header. Consumers who need to integrate with an external framework expectation (legacy `x-xsrf-token`, a custom auth gateway that rewrites cookies, FIPS-grade token length) override the defaults via `registerCsrfConfig({ ... })`.
|
|
8
|
+
|
|
9
|
+
| Setting | Default | Where it is consumed |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| `cookieName` | `'csrf-token'` | Reserved for future cookie-issued tokens (current double-submit uses session record). |
|
|
12
|
+
| `headerName` | `'x-csrf-token'` | Server: `csrfMiddleware.ts` reads `req.headers[headerName]`. Client: `httpFetch` attaches `headerName` on state-changing requests. |
|
|
13
|
+
| `tokenLength` | `32` (bytes) | Session mint in `packages/login/src/session.ts` (`randomBytes(tokenLength).toString('hex')`). |
|
|
14
|
+
| `cookieOptions.sameSite` | `'lax'` | Cookie attributes if/when the framework migrates to cookie-issued tokens. |
|
|
15
|
+
| `cookieOptions.secure` | `true` | Same. |
|
|
16
|
+
| `cookieOptions.httpOnly` | `false` | MUST be false for CSRF cookies — clients need to read the value. |
|
|
17
|
+
| `cookieOptions.path` | `'/'` | Same. |
|
|
18
|
+
| `cookieOptions.maxAgeMs` | `86_400_000` (1 day) | Same. |
|
|
19
|
+
|
|
20
|
+
## API Reference
|
|
21
|
+
|
|
22
|
+
### `registerCsrfConfig(input: Partial<CsrfConfig>): void`
|
|
23
|
+
|
|
24
|
+
**Signature:**
|
|
25
|
+
```typescript
|
|
26
|
+
export interface CsrfConfig {
|
|
27
|
+
cookieName: string;
|
|
28
|
+
headerName: string;
|
|
29
|
+
tokenLength: number;
|
|
30
|
+
cookieOptions: CsrfCookieOptions;
|
|
31
|
+
}
|
|
32
|
+
export const registerCsrfConfig = (input: Partial<CsrfConfig>): void
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
**Behavior:** Shallow-merges `input` over the current config. `cookieOptions` is deep-merged so a partial override of `sameSite` does not clobber `path` / `maxAgeMs`. Last-write-wins.
|
|
36
|
+
|
|
37
|
+
**Example — rename the header for an external gateway:**
|
|
38
|
+
```typescript
|
|
39
|
+
import { registerCsrfConfig } from '@luckystack/core';
|
|
40
|
+
|
|
41
|
+
registerCsrfConfig({
|
|
42
|
+
headerName: 'x-xsrf-token',
|
|
43
|
+
});
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
**Example — FIPS-grade token length + strict same-site:**
|
|
47
|
+
```typescript
|
|
48
|
+
import { registerCsrfConfig } from '@luckystack/core';
|
|
49
|
+
|
|
50
|
+
registerCsrfConfig({
|
|
51
|
+
tokenLength: 64,
|
|
52
|
+
cookieOptions: { sameSite: 'strict' },
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### `getCsrfConfig(): CsrfConfig`
|
|
57
|
+
|
|
58
|
+
Read the active config at call time. Framework code uses this — never read at module load.
|
|
59
|
+
|
|
60
|
+
### `DEFAULT_CSRF_CONFIG: CsrfConfig`
|
|
61
|
+
|
|
62
|
+
Exported so consumers can spread + override structurally:
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
import { DEFAULT_CSRF_CONFIG, registerCsrfConfig } from '@luckystack/core';
|
|
66
|
+
|
|
67
|
+
registerCsrfConfig({
|
|
68
|
+
...DEFAULT_CSRF_CONFIG,
|
|
69
|
+
headerName: 'x-app-csrf',
|
|
70
|
+
});
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### `resetCsrfConfigForTests(): void`
|
|
74
|
+
|
|
75
|
+
Test-only helper. Restore defaults between scenarios. Not part of the runtime contract.
|
|
76
|
+
|
|
77
|
+
## What this does NOT change
|
|
78
|
+
|
|
79
|
+
- The double-submit comparison logic itself (`csrfSession.csrfToken === provided`).
|
|
80
|
+
- Token-mode session behaviour — token-mode sessions skip CSRF entirely (cross-origin requests don't auto-attach `sessionStorage`).
|
|
81
|
+
- The framework's HTTP route paths (`GET /auth/csrf` is still the issuing endpoint).
|
|
82
|
+
- The `csrfMismatch` hook fan-out — payload shape and timing are unchanged.
|
|
83
|
+
|
|
84
|
+
## Related
|
|
85
|
+
|
|
86
|
+
- Function INDEX: `packages/core/CLAUDE.md`
|
|
87
|
+
- Source: `packages/core/src/csrfConfig.ts`, `packages/core/src/csrf.ts`, `packages/server/src/httpRoutes/csrfMiddleware.ts`, `packages/login/src/session.ts`
|
|
88
|
+
- Architecture: `docs/ARCHITECTURE_EXTENSION_POINTS.md`, `packages/server/docs/security-defaults.md`
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# Error Tracker Registry
|
|
2
|
+
|
|
3
|
+
> Deep specs for the backend-agnostic error tracker registry + legacy Sentry slot. Source: `packages/core/src/errorTrackerRegistry.ts`, `sentrySetup.ts`. Bijgewerkt: 2026-05-20.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
The error tracker registry is the seam between framework code (which never imports a specific observability backend) and adapters for Sentry / Datadog / PostHog / etc. The slot lives in `@luckystack/core`; adapter implementations ship in `@luckystack/error-tracking`. Multiple adapters can be active at once via `registerErrorTrackers([...])` — every event fans out to all of them, and per-adapter errors are swallowed so one buggy tracker can't break the chain.
|
|
8
|
+
|
|
9
|
+
The legacy `initSharedSentry(instance)` + `captureException` / `captureMessage` / `setSentryUser` / `startSpan` API predates the multi-adapter registry. It is kept for backwards compatibility and dual-fans events through both the legacy slot AND any adapters registered with the new API, so a project can migrate incrementally.
|
|
10
|
+
|
|
11
|
+
`startSpanAcrossTrackers` deliberately invokes only the first adapter that supports `startSpan` — spans don't fan out cleanly because they're nested execution scopes.
|
|
12
|
+
|
|
13
|
+
## Types
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
export interface ErrorTrackerContext {
|
|
17
|
+
[key: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ErrorTrackerUser {
|
|
21
|
+
id?: string;
|
|
22
|
+
email?: string;
|
|
23
|
+
username?: string;
|
|
24
|
+
[key: string]: unknown;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ErrorTrackerEvent {
|
|
28
|
+
forwarded: boolean;
|
|
29
|
+
kind: 'exception' | 'message';
|
|
30
|
+
payload: Record<string, unknown>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type SpanResult<T> = T;
|
|
34
|
+
|
|
35
|
+
export interface ErrorTracker {
|
|
36
|
+
name: string;
|
|
37
|
+
captureException: (error: unknown, context?: ErrorTrackerContext) => void;
|
|
38
|
+
captureMessage: (
|
|
39
|
+
message: string,
|
|
40
|
+
level: 'info' | 'warning' | 'error' | 'fatal',
|
|
41
|
+
context?: ErrorTrackerContext,
|
|
42
|
+
) => void;
|
|
43
|
+
setUser: (user: ErrorTrackerUser | null) => void;
|
|
44
|
+
setContext?: (key: string, context: ErrorTrackerContext | null) => void;
|
|
45
|
+
startSpan?: <T>(name: string, op: string, fn: () => T) => T;
|
|
46
|
+
recordMetric?: (name: string, value: number, tags?: Record<string, string>) => void;
|
|
47
|
+
beforeSend?: (event: ErrorTrackerEvent) => ErrorTrackerEvent | null;
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`SpanResult<T>` is an alias for `T` — the conditional unwrap collapsed in both branches and `tsup`'s dts emit choked on the widening. Kept as an exported alias so adapter authors can still annotate intent.
|
|
52
|
+
|
|
53
|
+
## API Reference — Multi-Adapter Registry
|
|
54
|
+
|
|
55
|
+
### `registerErrorTracker(tracker: ErrorTracker): void`
|
|
56
|
+
|
|
57
|
+
**Behavior:** Replaces the active list with `[tracker]`. Use this for single-tracker setups.
|
|
58
|
+
|
|
59
|
+
### `registerErrorTrackers(trackers: ErrorTracker[]): void`
|
|
60
|
+
|
|
61
|
+
**Behavior:** Replaces the active list with a copy of the input array (`[...trackers]`). Use for multi-backend setups (Sentry + Datadog, etc.).
|
|
62
|
+
|
|
63
|
+
### `getActiveErrorTrackers(): ErrorTracker[]`
|
|
64
|
+
|
|
65
|
+
Returns the current array (the internal reference — treat as read-only).
|
|
66
|
+
|
|
67
|
+
### `captureExceptionAcrossTrackers(error, context?): void`
|
|
68
|
+
|
|
69
|
+
**Behavior:** For each active tracker, calls `tracker.captureException(error, context)` inside a per-tracker `try / catch` that silently swallows failures.
|
|
70
|
+
|
|
71
|
+
### `captureMessageAcrossTrackers(message, level, context?): void`
|
|
72
|
+
|
|
73
|
+
Same fan-out shape as `captureExceptionAcrossTrackers` for messages.
|
|
74
|
+
|
|
75
|
+
### `setErrorTrackerUser(user: ErrorTrackerUser | null): void`
|
|
76
|
+
|
|
77
|
+
Calls `tracker.setUser(user)` on every active tracker (errors swallowed).
|
|
78
|
+
|
|
79
|
+
### `recordMetricAcrossTrackers(name, value, tags?): void`
|
|
80
|
+
|
|
81
|
+
**Behavior:** Skips trackers that don't define `recordMetric`. Errors are swallowed.
|
|
82
|
+
|
|
83
|
+
### `startSpanAcrossTrackers<T>(name, op, fn): T`
|
|
84
|
+
|
|
85
|
+
**Behavior:**
|
|
86
|
+
- Finds the first tracker with a `startSpan` method.
|
|
87
|
+
- If found, returns `tracker.startSpan(name, op, fn)` cast to `T`.
|
|
88
|
+
- If none exist, returns `fn()` directly (no instrumentation).
|
|
89
|
+
|
|
90
|
+
**Why not fan-out:** Spans are nested execution scopes — invoking multiple `startSpan` implementations would nest each other and produce confusing traces.
|
|
91
|
+
|
|
92
|
+
### Example — register multiple adapters
|
|
93
|
+
|
|
94
|
+
```typescript
|
|
95
|
+
import { registerErrorTrackers, type ErrorTracker } from '@luckystack/core';
|
|
96
|
+
|
|
97
|
+
const sentryAdapter: ErrorTracker = { /* ... */ };
|
|
98
|
+
const datadogAdapter: ErrorTracker = { /* ... */ };
|
|
99
|
+
|
|
100
|
+
registerErrorTrackers([sentryAdapter, datadogAdapter]);
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## API Reference — Legacy Sentry Slot
|
|
104
|
+
|
|
105
|
+
### `initSharedSentry(instance: SentryInstance): void`
|
|
106
|
+
|
|
107
|
+
**Signature:**
|
|
108
|
+
```typescript
|
|
109
|
+
interface SentryInstance {
|
|
110
|
+
captureException: (exception: unknown, ...args: unknown[]) => string;
|
|
111
|
+
captureMessage: (message: string, ...args: unknown[]) => string;
|
|
112
|
+
setUser: (user: unknown) => void;
|
|
113
|
+
setContext: (key: string, context: unknown) => void;
|
|
114
|
+
startInactiveSpan?: (context: unknown) => unknown;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export const initSharedSentry = (instance: SentryInstance): void
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
**Behavior:** Stores the Sentry SDK instance in a module-level slot. New code should `registerErrorTracker(...)` from `@luckystack/error-tracking` instead.
|
|
121
|
+
|
|
122
|
+
### `captureException(error, context?): void`
|
|
123
|
+
|
|
124
|
+
**Behavior:**
|
|
125
|
+
- When the legacy Sentry slot is populated, calls `sentry.captureException(error, { extra: context })` (or no second arg when no context).
|
|
126
|
+
- ALSO calls `captureExceptionAcrossTrackers(error, context)` so any modern adapters receive the same event.
|
|
127
|
+
|
|
128
|
+
**Concurrency note:** Context is passed inline via the hint-shaped second argument so contexts don't leak across concurrent captures. The previous implementation used `sentry.setContext('additional', context)` which was process-global and leaked under concurrent captures.
|
|
129
|
+
|
|
130
|
+
### `captureMessage(message, level?, context?): void`
|
|
131
|
+
|
|
132
|
+
**Behavior:** Mirror of `captureException` for messages. Level defaults to `'info'`.
|
|
133
|
+
|
|
134
|
+
### `setSentryUser(user): void`
|
|
135
|
+
|
|
136
|
+
Calls `sentry?.setUser(user)` and fans out via `setErrorTrackerUser(user)`.
|
|
137
|
+
|
|
138
|
+
### `startSpan(name, op): unknown`
|
|
139
|
+
|
|
140
|
+
**Behavior:**
|
|
141
|
+
- If `sentry?.startInactiveSpan` exists, returns `sentry.startInactiveSpan({ name, op })`.
|
|
142
|
+
- Otherwise falls back to `startSpanAcrossTrackers(name, op, () => undefined)` — useful when the project uses an adapter-only setup that supports spans.
|
|
143
|
+
|
|
144
|
+
## Edge cases
|
|
145
|
+
|
|
146
|
+
- All multi-adapter fan-out paths swallow per-tracker errors. There is no way to surface them — by design, since framework hot paths (`tryCatch`, hook dispatch) must never crash because of a misbehaving tracker.
|
|
147
|
+
- `registerErrorTracker` and `registerErrorTrackers` replace the active list — call once at boot. There is no `unregister` API.
|
|
148
|
+
- `beforeSend` and `forwarded` on `ErrorTrackerEvent` are advisory for adapter authors. Core does not call `beforeSend` itself; the adapter implementation is expected to honor it.
|
|
149
|
+
|
|
150
|
+
## Example — minimal custom adapter
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
import { registerErrorTracker, type ErrorTracker } from '@luckystack/core';
|
|
154
|
+
|
|
155
|
+
const stdoutAdapter: ErrorTracker = {
|
|
156
|
+
name: 'stdout',
|
|
157
|
+
captureException: (error, context) => {
|
|
158
|
+
console.error('exception:', error, context);
|
|
159
|
+
},
|
|
160
|
+
captureMessage: (message, level, context) => {
|
|
161
|
+
console.log(`[${level}] ${message}`, context);
|
|
162
|
+
},
|
|
163
|
+
setUser: () => { /* no-op */ },
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
registerErrorTracker(stdoutAdapter);
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Related
|
|
170
|
+
|
|
171
|
+
- Function INDEX: `packages/core/CLAUDE.md`
|
|
172
|
+
- Architecture: `docs/ARCHITECTURE_EXTENSION_POINTS.md`
|
|
173
|
+
- README: `packages/core/README.md`, `packages/error-tracking/README.md`
|
|
174
|
+
- Source: `packages/core/src/errorTrackerRegistry.ts`, `sentrySetup.ts`
|