@chidchanun/bcp 0.2.5 → 0.2.7

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.
@@ -0,0 +1,194 @@
1
+ # BCP Framework 0.2.6 — Authorization & Security v2
2
+
3
+ `0.2.6` expands the server authorization model and adds request-origin/CSRF protection primitives while preserving the existing Authentication Platform v2 and route model.
4
+
5
+ > Release state: unreleased development target until RC validation, tagging and npm publication complete.
6
+
7
+ ## Authorization primitives
8
+
9
+ `bcp/auth` now provides flat permission checks:
10
+
11
+ ```ts
12
+ hasPermission()
13
+ assertPermission()
14
+ getUserPermissions()
15
+ ```
16
+
17
+ Permission requirements accept one permission or multiple permissions with `any` / `all` matching.
18
+
19
+ The default user field is:
20
+
21
+ ```text
22
+ permissions
23
+ ```
24
+
25
+ Applications can select another field, such as `scopes`.
26
+
27
+ ## Permission route guards
28
+
29
+ Route guards can require permissions directly:
30
+
31
+ ```ts
32
+ requirePermission()
33
+ createPermissionGuard()
34
+ ```
35
+
36
+ Unauthenticated behavior remains consistent with `requireAuth()`. Authenticated users that fail the permission check receive `403 Forbidden` by default or can be redirected explicitly.
37
+
38
+ ## Policy authorization
39
+
40
+ Resource-aware application policies are now supported through:
41
+
42
+ ```ts
43
+ defineAuthorizationPolicy()
44
+ can()
45
+ cannot()
46
+ authorize()
47
+ AuthorizationError
48
+ ```
49
+
50
+ Policies receive a typed context containing:
51
+
52
+ ```ts
53
+ {
54
+ user,
55
+ resource,
56
+ data,
57
+ }
58
+ ```
59
+
60
+ Policies may be synchronous or asynchronous. `authorize()` throws a `403`-classified `AuthorizationError` when access is denied.
61
+
62
+ ## Same-origin protection
63
+
64
+ `bcp/server` adds request-origin validation for unsafe methods:
65
+
66
+ ```ts
67
+ isSafeHttpMethod()
68
+ isSameOriginRequest()
69
+ requireSameOriginRequest()
70
+ ```
71
+
72
+ The current request origin is always allowed. Additional origins may be listed explicitly.
73
+
74
+ For unsafe methods, BCP checks `Origin` first and then `Referer`. Missing origin information is rejected by default unless the application explicitly enables `allowMissingOrigin`.
75
+
76
+ Malformed, opaque, or unsupported origins are treated as denied instead of surfacing as server errors.
77
+
78
+ ## CSRF protection
79
+
80
+ Signed CSRF tokens are available through:
81
+
82
+ ```ts
83
+ createCsrfToken()
84
+ destroyCsrfToken()
85
+ verifyCsrfToken()
86
+ verifyCsrfRequest()
87
+ requireCsrfRequest()
88
+ ```
89
+
90
+ The default request header is:
91
+
92
+ ```text
93
+ X-BCP-CSRF
94
+ ```
95
+
96
+ The default cookie is:
97
+
98
+ ```text
99
+ bcp_csrf
100
+ ```
101
+
102
+ CSRF cookies are HttpOnly, SameSite=Lax by default, Secure in production, and use a two-hour default lifetime.
103
+
104
+ Token signing resolves secrets in this order:
105
+
106
+ ```text
107
+ explicit secret
108
+ BCP_CSRF_SECRET
109
+ BCP_SESSION_SECRET
110
+ ```
111
+
112
+ Secrets must contain at least 32 UTF-8 bytes.
113
+
114
+ `requireCsrfRequest()` combines same-origin validation and token validation for unsafe methods. GET, HEAD and OPTIONS do not require CSRF tokens.
115
+
116
+ ## Security error classification
117
+
118
+ `RequestSecurityError` reports status `403` and distinguishes:
119
+
120
+ ```text
121
+ INVALID_ORIGIN
122
+ INVALID_CSRF_TOKEN
123
+ ```
124
+
125
+ This allows API routes/actions to map request-security failures to application-specific error responses while retaining a stable security classification.
126
+
127
+ ## Compatibility
128
+
129
+ `0.2.6` does not intentionally remove existing public entrypoints or authentication behavior.
130
+
131
+ Existing APIs remain available:
132
+
133
+ ```text
134
+ auth()
135
+ login()
136
+ logout()
137
+ logoutAll()
138
+ rotateSession()
139
+ requireAuth()
140
+ requireGuest()
141
+ requireRole()
142
+ createAuthGuard()
143
+ createGuestGuard()
144
+ createRoleGuard()
145
+ ```
146
+
147
+ Stateless JWT-cookie authentication remains supported. Revocable stores introduced in `0.2.5` are unchanged.
148
+
149
+ ## Testing and packaging
150
+
151
+ The release adds unit coverage for:
152
+
153
+ - permission `any` / `all` matching,
154
+ - resource authorization policies,
155
+ - permission route guards,
156
+ - same-origin mutation validation,
157
+ - signed CSRF tokens,
158
+ - invalid CSRF token rejection,
159
+ - cross-origin request rejection.
160
+
161
+ Prepared npm package smoke coverage verifies that the `bcp/auth` and `bcp/server` public entrypoints include the Authorization & Security v2 APIs and implementation files.
162
+
163
+ ## Documentation
164
+
165
+ New guide:
166
+
167
+ ```text
168
+ docs/authorization-security.md
169
+ ```
170
+
171
+ Updated documentation contracts include:
172
+
173
+ ```text
174
+ docs/platform-manifest.json
175
+ docs/docs-web-manifest.json
176
+ docs/api-manifest.json
177
+ docs/api-reference.md
178
+ README.md
179
+ ```
180
+
181
+ ## Release validation
182
+
183
+ Before publishing:
184
+
185
+ ```bash
186
+ npm run typecheck
187
+ npm run test:unit
188
+ npm run test:integration
189
+ npm run test:e2e
190
+ npm run test:package
191
+ npm run rc:check
192
+ ```
193
+
194
+ The final `v0.2.6` Git tag must point to the exact commit that passed the complete RC sequence.
@@ -0,0 +1,205 @@
1
+ # BCP Framework 0.2.7 — Observability Platform v2
2
+
3
+ > Release state: unreleased until RC validation, tagging and npm publication complete.
4
+
5
+ BCP Framework `0.2.7` adds a dependency-free server observability platform while preserving the existing logging/runtime model.
6
+
7
+ ## Highlights
8
+
9
+ ### New `bcp/observability` entrypoint
10
+
11
+ ```ts
12
+ import {
13
+ createHealthRegistry,
14
+ createMetricsRegistry,
15
+ createMetricsResponse,
16
+ createRequestMetricsMiddleware,
17
+ } from "bcp/observability";
18
+ ```
19
+
20
+ The entrypoint is server-only and uses the same browser boundary as other server runtime APIs.
21
+
22
+ ### Metrics registry
23
+
24
+ Applications can create process-local:
25
+
26
+ - counters,
27
+ - gauges,
28
+ - histograms.
29
+
30
+ Example:
31
+
32
+ ```ts
33
+ const metrics =
34
+ createMetricsRegistry();
35
+
36
+ const requests =
37
+ metrics.counter(
38
+ "app_requests_total",
39
+ {
40
+ labelNames: [
41
+ "method",
42
+ ],
43
+ }
44
+ );
45
+
46
+ requests.inc(
47
+ 1,
48
+ {
49
+ method: "GET",
50
+ }
51
+ );
52
+ ```
53
+
54
+ Metric definitions validate names, labels and number values. Re-registering the same metric with an incompatible type, label set or histogram buckets fails explicitly.
55
+
56
+ ### Prometheus text output
57
+
58
+ ```ts
59
+ return createMetricsResponse(
60
+ metrics
61
+ );
62
+ ```
63
+
64
+ The generated response uses Prometheus-compatible text exposition metadata and `Cache-Control: no-store`.
65
+
66
+ ### HTTP request metrics middleware
67
+
68
+ ```ts
69
+ const requestMetrics =
70
+ createRequestMetricsMiddleware(
71
+ metrics
72
+ );
73
+ ```
74
+
75
+ Default metrics:
76
+
77
+ ```text
78
+ bcp_http_requests_total
79
+ bcp_http_request_duration_seconds
80
+ ```
81
+
82
+ Default labels:
83
+
84
+ ```text
85
+ method
86
+ status
87
+ ```
88
+
89
+ Raw URL paths are intentionally not included by default to avoid unbounded metric cardinality.
90
+
91
+ ### Health and readiness checks
92
+
93
+ ```ts
94
+ const health =
95
+ createHealthRegistry();
96
+
97
+ health.register(
98
+ "database",
99
+ async () => {
100
+ await db.query(
101
+ "SELECT 1"
102
+ );
103
+
104
+ return true;
105
+ }
106
+ );
107
+ ```
108
+
109
+ Health responses use:
110
+
111
+ ```text
112
+ 200 healthy
113
+ 503 unhealthy
114
+ ```
115
+
116
+ Checks run independently and include duration metadata.
117
+
118
+ ### Health timeouts
119
+
120
+ Each health check has a default timeout of 5 seconds and may configure its own timeout.
121
+
122
+ Thrown or timed-out checks become unhealthy report items rather than rejecting the whole health operation.
123
+
124
+ ## Public APIs
125
+
126
+ ### Metrics
127
+
128
+ ```text
129
+ createMetricsRegistry()
130
+ createMetricsResponse()
131
+ createRequestMetricsMiddleware()
132
+ ```
133
+
134
+ Metric interfaces:
135
+
136
+ ```text
137
+ CounterMetric
138
+ GaugeMetric
139
+ HistogramMetric
140
+ MetricsRegistry
141
+ MetricLabels
142
+ MetricDefinitionOptions
143
+ HistogramOptions
144
+ RequestMetricsOptions
145
+ ```
146
+
147
+ ### Health
148
+
149
+ ```text
150
+ createHealthRegistry()
151
+ ```
152
+
153
+ Health interfaces:
154
+
155
+ ```text
156
+ HealthRegistry
157
+ HealthCheck
158
+ HealthCheckResult
159
+ HealthCheckOptions
160
+ HealthReport
161
+ HealthCheckReportItem
162
+ ```
163
+
164
+ ## Compatibility
165
+
166
+ `0.2.7` has no intentional breaking changes from `0.2.6`.
167
+
168
+ Existing applications do not need to create a metrics or health registry. The new platform is opt-in.
169
+
170
+ Existing structured logging through `bcp/server` remains unchanged.
171
+
172
+ ## Operational notes
173
+
174
+ Metrics are process-local. Multi-process and multi-container deployments should expose/scrape metrics for each instance or aggregate through deployment infrastructure.
175
+
176
+ The built-in platform does not provide distributed aggregation or an OpenTelemetry exporter in this release.
177
+
178
+ Health check error details may contain operational information. Applications should decide whether health endpoints are publicly accessible and avoid returning secrets from custom check details.
179
+
180
+ Metrics endpoints should normally be protected by an internal network, reverse proxy or application authorization boundary when operational data is sensitive.
181
+
182
+ ## Validation coverage
183
+
184
+ `0.2.7` adds unit and prepared-package checks for:
185
+
186
+ - counter accumulation,
187
+ - gauge set/increment/decrement,
188
+ - histogram bucket/count output,
189
+ - Prometheus response metadata,
190
+ - incompatible metric registration,
191
+ - request status/method timing metrics,
192
+ - no raw path labels in default request metrics,
193
+ - healthy/unhealthy reports,
194
+ - HTTP 503 readiness behavior,
195
+ - health check timeout handling,
196
+ - `bcp/observability` npm export availability,
197
+ - documentation/platform/API manifest parity.
198
+
199
+ ## Documentation
200
+
201
+ See:
202
+
203
+ - [Observability Platform v2](../observability.md)
204
+ - [Logging](../development-logging.md)
205
+ - [API Reference](../api-reference.md)
package/docs/security.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Security
2
2
 
3
- BCP Framework applies a security gateway in both development and standalone production modes.
3
+ BCP Framework applies a security gateway in both development and standalone production modes and exposes server-side mutation protection primitives through `bcp/server`.
4
4
 
5
5
  ## Default response headers
6
6
 
@@ -40,6 +40,58 @@ server: {
40
40
 
41
41
  Requests exceeding the limit are rejected by the outer gateway with HTTP 413 before reaching the API handler.
42
42
 
43
+ ## Same-origin mutation protection — 0.2.6+
44
+
45
+ Cookie-authenticated unsafe requests can validate their browser origin:
46
+
47
+ ```ts
48
+ import {
49
+ requireSameOriginRequest,
50
+ } from "bcp/server";
51
+
52
+ await requireSameOriginRequest();
53
+ ```
54
+
55
+ BCP validates `Origin` first and falls back to `Referer`. GET, HEAD and OPTIONS are treated as safe methods. Unsafe methods without origin information are rejected by default.
56
+
57
+ Additional trusted origins can be configured per check with `allowedOrigins`.
58
+
59
+ Malformed, opaque or unsupported origins are denied instead of surfacing as server errors.
60
+
61
+ ## CSRF protection — 0.2.6+
62
+
63
+ BCP also exposes signed CSRF tokens:
64
+
65
+ ```ts
66
+ import {
67
+ createCsrfToken,
68
+ requireCsrfRequest,
69
+ } from "bcp/server";
70
+
71
+ const token =
72
+ await createCsrfToken();
73
+
74
+ // Render the token through a trusted application response,
75
+ // then submit it with the mutation.
76
+
77
+ await requireCsrfRequest({
78
+ token: submittedToken,
79
+ });
80
+ ```
81
+
82
+ Default header/cookie:
83
+
84
+ ```text
85
+ X-BCP-CSRF
86
+ bcp_csrf
87
+ ```
88
+
89
+ Token signing uses `BCP_CSRF_SECRET` when configured and otherwise falls back to `BCP_SESSION_SECRET`. Secrets must contain at least 32 UTF-8 bytes.
90
+
91
+ `requireCsrfRequest()` combines same-origin validation and CSRF token verification for unsafe methods.
92
+
93
+ Read more: [Authorization & Security v2](authorization-security.md).
94
+
43
95
  ## Static assets
44
96
 
45
97
  Public asset resolution decodes the URL, rejects null bytes, resolves the candidate beneath `public/`, resolves filesystem symlinks and verifies the final real path remains inside the public directory. This prevents path and symlink traversal from escaping the public root.
@@ -55,3 +107,5 @@ Security config values reject carriage return, line feed and null bytes to preve
55
107
  ## Deployment note
56
108
 
57
109
  The security gateway is the outer production layer, so security headers and body limits also apply to response-cache hits, middleware responses, static assets and error responses.
110
+
111
+ Authorization, same-origin checks and CSRF validation remain request-handler/guard responsibilities and should be enforced wherever a mutation or protected operation occurs.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chidchanun/bcp",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "BCP Framework - a React full-stack framework with file-based routing, SSR, APIs, middleware, islands, caching and standalone production builds.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -62,6 +62,11 @@
62
62
  "browser": "./packages/client/src/server-only.browser.mjs",
63
63
  "default": "./packages/client/src/auth.ts"
64
64
  },
65
+ "./observability": {
66
+ "types": "./packages/client/src/observability.ts",
67
+ "browser": "./packages/client/src/server-only.browser.mjs",
68
+ "default": "./packages/client/src/observability.ts"
69
+ },
65
70
  "./server": {
66
71
  "types": "./packages/client/src/server.ts",
67
72
  "browser": "./packages/client/src/server-only.browser.mjs",
@@ -28,6 +28,7 @@ const SERVER_ONLY_IMPORTS =
28
28
  "bcp/server-only",
29
29
  "bcp/database",
30
30
  "bcp/auth",
31
+ "bcp/observability",
31
32
  ]);
32
33
 
33
34
  export function validateClientBoundaries(
@@ -24,13 +24,32 @@ export {
24
24
  type MemoryAuthSessionStore,
25
25
  } from "../../server/src/auth-session-store.js";
26
26
 
27
+ export {
28
+ assertPermission,
29
+ authorize,
30
+ can,
31
+ cannot,
32
+ defineAuthorizationPolicy,
33
+ getUserPermissions,
34
+ hasPermission,
35
+ AuthorizationError,
36
+
37
+ type AuthorizationContext,
38
+ type AuthorizationMatch,
39
+ type AuthorizationPolicy,
40
+ type PermissionCheckOptions,
41
+ type PermissionRequirement,
42
+ } from "../../server/src/authorization.js";
43
+
27
44
  export {
28
45
  createAuthGuard,
29
46
  createGuestGuard,
47
+ createPermissionGuard,
30
48
  createRoleGuard,
31
49
  getGuardAuth,
32
50
  requireAuth,
33
51
  requireGuest,
52
+ requirePermission,
34
53
  requireRole,
35
54
 
36
55
  type AuthGuardData,
@@ -40,6 +59,7 @@ export {
40
59
  type GuestGuardResult,
41
60
  type RequireAuthOptions,
42
61
  type RequireGuestOptions,
62
+ type RequirePermissionOptions,
43
63
  type RequireRoleOptions,
44
64
  type RequiredRole,
45
65
  } from "../../server/src/auth-guard.js";
@@ -0,0 +1,22 @@
1
+ export {
2
+ createHealthRegistry,
3
+ createMetricsRegistry,
4
+ createMetricsResponse,
5
+ createRequestMetricsMiddleware,
6
+
7
+ type CounterMetric,
8
+ type GaugeMetric,
9
+ type HealthCheck,
10
+ type HealthCheckOptions,
11
+ type HealthCheckReportItem,
12
+ type HealthCheckResult,
13
+ type HealthRegistry,
14
+ type HealthReport,
15
+ type HistogramMetric,
16
+ type HistogramOptions,
17
+ type MetricDefinitionOptions,
18
+ type MetricLabels,
19
+ type MetricLabelValue,
20
+ type MetricsRegistry,
21
+ type RequestMetricsOptions,
22
+ } from "../../server/src/observability.js";
@@ -15,6 +15,22 @@ export {
15
15
  type ResponseCookieOptions,
16
16
  } from "../../server/src/request-context.js";
17
17
 
18
+ export {
19
+ createCsrfToken,
20
+ destroyCsrfToken,
21
+ isSafeHttpMethod,
22
+ isSameOriginRequest,
23
+ requireCsrfRequest,
24
+ requireSameOriginRequest,
25
+ verifyCsrfRequest,
26
+ verifyCsrfToken,
27
+ RequestSecurityError,
28
+
29
+ type CsrfTokenOptions,
30
+ type SameOriginOptions,
31
+ type VerifyCsrfRequestOptions,
32
+ } from "../../server/src/request-security.js";
33
+
18
34
  export {
19
35
  attachRequestId,
20
36
  createLogger,