@rdlabo/workers-hono-kit 0.9.2 → 0.9.4

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/README.md CHANGED
@@ -79,6 +79,7 @@ npm install ai ai-gateway-provider # createAiGatewayProvider
79
79
  | `normalizeTrailingSlash(request)` | Strip trailing slash(es) from the request URL before routing (Express/Nest parity). Does **not** 301-redirect — preserves POST/PUT/DELETE bodies. |
80
80
  | `HTTP_ERROR_PHRASES` | `{ 400, 401, 403, 404 }` → standard `error` field phrases. |
81
81
  | `createAuthMiddleware(options)` / `AuthMiddlewareOptions` | Factory for a Firebase-token auth middleware: reads the token header, verifies, resolves the DB user id, and stashes the result on the context. Omit `resolveUserId` for a token-only (login) guard. |
82
+ | `createIdentityAuthFailureBody()` / `createLegacyIdentityAuthFailureBody()` / `createAuthFailureBody(scope, code, message)` / `AuthFailureScope` | Stable wire contract for distinguishing a lost global identity (`identity`) from recent-login (`reauthentication`) and feature credential (`credential`) failures. The legacy helper tags products whose installed clients still require auth failure as `403`. |
82
83
  | `perfLog(options?)` / `PerfLogOptions` / `AnalyticsEngineDatasetLike` | Middleware that records one per-request latency data point (`t_app`, colo, cold/warm, route, status) and emits it to **Workers Logs** (`console.log`) and/or **Workers Analytics Engine** (`writeDataPoint`). Lets you measure low-traffic Workers without a live `wrangler tail`. |
83
84
  | `createMaintenanceMiddleware(options)` / `createMaintenanceWaitHandler(options)` / `isMaintenanceEnabled(env)` / `MAINTENANCE_CODE` / `MAINTENANCE_WAIT_PATH` | Fleet maintenance short-circuit: when enabled (`MAINTENANCE=1`), every non-allowlisted request returns `503` + `{ statusCode, message, code: 'MAINTENANCE' }` **before** container/DB. Pair with `GET /public/maintenance/wait` SSE (`event: ping` / `event: ended`) so clients can auto-dismiss a lock UI. Mount after `cors`, before `containerMiddleware`. |
84
85
  | `ErrorReporter` / `ErrorReportContext` | Types for a `reportError`-style unhandled-error reporter (e.g. wired to Sentry), paired with `createHttpErrorHandler`'s `onUnhandledError`. |
@@ -209,7 +210,8 @@ client-generated UUID in `local_id` and keep `server_id` null until the server c
209
210
  | Export | Description |
210
211
  | --- | --- |
211
212
  | `defineRestDbMethodConverter(converter)` | Type a product-owned, pure `MethodScheme ↔ TableScheme` converter without hiding HTTP or persistence side effects. |
212
- | `RestDbMethodConverter` | Product-owned converter contract. Its table scheme requires every represented table and column, including optional nullable/default keys from `$inferInsert`. |
213
+ | `RestDbMethodConverter` | Product-owned converter contract. Select and insert bundles may differ; every represented table and column remains required. |
214
+ | `CompleteRestDbTableScheme` | Compile-time lock requiring every represented table key and row column. |
213
215
  | `toReplicaIsoDatetime(value)` | `Date` / datetime string → canonical UTC ISO-8601 wire value. |
214
216
  | `toReplicaDateOnly(value)` | `Date` / date string / `null` → canonical `YYYY-MM-DD` / `null`. |
215
217
  | `replicaTimestampMs(value)` | Replica datetime → epoch milliseconds for legacy DTOs. |
@@ -254,6 +256,20 @@ type CreateTables = {
254
256
  The converter then cannot demand or manufacture `id`; the server adds the generated id to the
255
257
  confirmed response before it is stored as `server_id`.
256
258
 
259
+ When a write needs authenticated ownership or scope that is intentionally absent from the public
260
+ REST body, use separate select/insert bundles and an explicit write context. The original
261
+ two-generic form remains valid.
262
+
263
+ ```ts
264
+ defineRestDbMethodConverter<Method, SelectTables, InsertTables, { userId: number }>({
265
+ toMethodScheme: ({ foods, allergens }) => composeFood(foods, allergens),
266
+ toTableScheme: (method, { userId }) => ({
267
+ foods: [{ userId, name: method.name, memo: method.memo ?? null }],
268
+ allergens: method.allergens.map((value) => ({ value })),
269
+ }),
270
+ });
271
+ ```
272
+
257
273
  ```ts
258
274
  replicaNowIso(() => new Date('2026-07-23T10:00:00Z')); // '2026-07-23T10:00:00.000Z'
259
275
  toReplicaIsoDatetime('2026-07-23T19:00:00+09:00'); // '2026-07-23T10:00:00.000Z'
@@ -461,7 +477,7 @@ verify/resolver, context-variable names, and failure mode.
461
477
  `setContext` is type-checked against your `Variables`.
462
478
 
463
479
  ```ts
464
- import { createAuthMiddleware } from '@rdlabo/workers-hono-kit';
480
+ import { createAuthMiddleware, createIdentityAuthFailureBody } from '@rdlabo/workers-hono-kit';
465
481
 
466
482
  // AuthGuard: verify + resolve (and provision) the DB user id.
467
483
  const userAuth = createAuthMiddleware<AppEnv, UserRecord, number>({
@@ -473,16 +489,28 @@ const userAuth = createAuthMiddleware<AppEnv, UserRecord, number>({
473
489
  c.set('userId', userId);
474
490
  c.set('appInfo', appInfo);
475
491
  },
492
+ onFailure: (_error, context) =>
493
+ context.json(createIdentityAuthFailureBody(), 401),
476
494
  });
477
495
 
478
496
  // TokenGuard (login): verify only — omit resolveUserId. Override the failure if needed.
479
497
  const tokenAuth = createAuthMiddleware<AppEnv, UserRecord>({
480
498
  verify: (token) => container.firebase.verifyIdToken(token),
481
499
  setContext: (c, { verified }) => c.set('userRecord', verified),
482
- onFailure: (_e, c) => c.json({ message: 'Unauthorized', statusCode: 401 }, 401),
500
+ onFailure: (_e, c) => c.json(createIdentityAuthFailureBody(), 401),
483
501
  });
484
502
  ```
485
503
 
504
+ Authentication failures use three explicit scopes. Only `identity` permits a client to purge its
505
+ global authenticated session, offline replica boundary, and outbox. `reauthentication` means the
506
+ identity remains valid but a recent sign-in is required; `credential` belongs to a domain feature
507
+ such as a public booking token. New APIs use `401`; products with installed clients that historically
508
+ interpret auth failure as `403` use `createLegacyIdentityAuthFailureBody()` until that compatibility
509
+ contract can be retired. An untagged `403` is an authenticated permission/business denial and must
510
+ not be used as a global-session invalidation signal. Domain-specific `code` values remain product-owned.
511
+ `createAuthMiddleware` retains its historical untagged `403` default for source/runtime compatibility;
512
+ the tagged identity contract is an explicit `onFailure` opt-in as shown above.
513
+
486
514
  ### Latency instrumentation (`perfLog`)
487
515
 
488
516
  Records one data point per request — `t_app` (time inside the app), `colo`, `cold`/`warm`, matched
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Describes which credential boundary caused an authentication failure.
3
+ *
4
+ * Only `identity` means that the application's global authenticated identity is
5
+ * no longer usable. `reauthentication` keeps the identity but requires a recent
6
+ * sign-in, while `credential` is limited to a delegated/domain credential.
7
+ */
8
+ export declare const AUTH_FAILURE_SCOPES: {
9
+ readonly identity: "identity";
10
+ readonly reauthentication: "reauthentication";
11
+ readonly credential: "credential";
12
+ };
13
+ export type AuthFailureScope = (typeof AUTH_FAILURE_SCOPES)[keyof typeof AUTH_FAILURE_SCOPES];
14
+ export declare const AUTH_IDENTITY_INVALID_CODE = "AUTH_IDENTITY_INVALID";
15
+ export interface AuthFailureBody<TScope extends AuthFailureScope = AuthFailureScope, TCode extends string = string, TStatus extends 401 | 403 = 401> {
16
+ statusCode: TStatus;
17
+ message: string;
18
+ code: TCode;
19
+ authFailureScope: TScope;
20
+ }
21
+ /**
22
+ * Creates the stable wire body for an authentication failure.
23
+ *
24
+ * Domain-specific codes remain owned by each application. The scope is the
25
+ * shared lifecycle contract consumed by clients deciding which local state may
26
+ * be invalidated.
27
+ */
28
+ export declare const createAuthFailureBody: <TScope extends AuthFailureScope, TCode extends string>(authFailureScope: TScope, code: TCode, message: string) => AuthFailureBody<TScope, TCode>;
29
+ export declare const createIdentityAuthFailureBody: (message?: string) => AuthFailureBody<"identity", typeof AUTH_IDENTITY_INVALID_CODE>;
30
+ /**
31
+ * Creates an explicitly tagged identity failure with the historical HTTP 403
32
+ * status used by some deployed products.
33
+ *
34
+ * New APIs should use {@link createIdentityAuthFailureBody}. This helper exists
35
+ * for servers that must remain compatible with installed clients whose auth
36
+ * interceptor recognizes the legacy 403 response.
37
+ */
38
+ export declare const createLegacyIdentityAuthFailureBody: (message?: string) => AuthFailureBody<"identity", typeof AUTH_IDENTITY_INVALID_CODE, 403>;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Describes which credential boundary caused an authentication failure.
3
+ *
4
+ * Only `identity` means that the application's global authenticated identity is
5
+ * no longer usable. `reauthentication` keeps the identity but requires a recent
6
+ * sign-in, while `credential` is limited to a delegated/domain credential.
7
+ */
8
+ export const AUTH_FAILURE_SCOPES = {
9
+ identity: 'identity',
10
+ reauthentication: 'reauthentication',
11
+ credential: 'credential',
12
+ };
13
+ export const AUTH_IDENTITY_INVALID_CODE = 'AUTH_IDENTITY_INVALID';
14
+ /**
15
+ * Creates the stable wire body for an authentication failure.
16
+ *
17
+ * Domain-specific codes remain owned by each application. The scope is the
18
+ * shared lifecycle contract consumed by clients deciding which local state may
19
+ * be invalidated.
20
+ */
21
+ export const createAuthFailureBody = (authFailureScope, code, message) => ({
22
+ statusCode: 401,
23
+ message,
24
+ code,
25
+ authFailureScope,
26
+ });
27
+ export const createIdentityAuthFailureBody = (message = 'Unauthorized') => createAuthFailureBody(AUTH_FAILURE_SCOPES.identity, AUTH_IDENTITY_INVALID_CODE, message);
28
+ /**
29
+ * Creates an explicitly tagged identity failure with the historical HTTP 403
30
+ * status used by some deployed products.
31
+ *
32
+ * New APIs should use {@link createIdentityAuthFailureBody}. This helper exists
33
+ * for servers that must remain compatible with installed clients whose auth
34
+ * interceptor recognizes the legacy 403 response.
35
+ */
36
+ export const createLegacyIdentityAuthFailureBody = (message = 'Forbidden resource') => ({
37
+ statusCode: 403,
38
+ message,
39
+ code: AUTH_IDENTITY_INVALID_CODE,
40
+ authFailureScope: AUTH_FAILURE_SCOPES.identity,
41
+ });
package/dist/index.d.ts CHANGED
@@ -47,6 +47,8 @@ export { defaultDefer, createWaitUntilDefer } from './http/defer.js';
47
47
  export type { DeferExecutor } from './http/defer.js';
48
48
  export { createSentryErrorReporter } from './http/http-error.js';
49
49
  export type { SentryExceptionReporterLike } from './http/http-error.js';
50
+ export { AUTH_FAILURE_SCOPES, AUTH_IDENTITY_INVALID_CODE, createAuthFailureBody, createIdentityAuthFailureBody, createLegacyIdentityAuthFailureBody, } from './http/auth-failure.js';
51
+ export type { AuthFailureBody, AuthFailureScope } from './http/auth-failure.js';
50
52
  export { canonicalJson, createIdempotencyInput, IdempotencyConflictError, IdempotencyInFlightError, IdempotencyKeyValidationError, IdempotencyPayloadValidationError, runIdempotentMutation, sha256CanonicalJson, withIdempotencyHttpErrors, } from './idempotency/idempotency.js';
51
53
  export type { CreateIdempotencyInputOptions, IdempotencyInput, IdempotencyReservation, IdempotencyScope, IdempotencyScopeValue, IdempotentMutationStore, } from './idempotency/idempotency.js';
52
54
  export { acknowledgeHibernationWebSocketClose, broadcastHibernationWebSockets, closeHibernationWebSocket, configureHibernationAutoResponse, upgradeHibernationWebSocket, } from './realtime/hibernation.js';
package/dist/index.js CHANGED
@@ -35,6 +35,7 @@ export { createAppErrorHandler } from './http/app-error-handler.js';
35
35
  export { normalizeTrailingSlash } from './http/trailing-slash.js';
36
36
  export { defaultDefer, createWaitUntilDefer } from './http/defer.js';
37
37
  export { createSentryErrorReporter } from './http/http-error.js';
38
+ export { AUTH_FAILURE_SCOPES, AUTH_IDENTITY_INVALID_CODE, createAuthFailureBody, createIdentityAuthFailureBody, createLegacyIdentityAuthFailureBody, } from './http/auth-failure.js';
38
39
  // idempotency
39
40
  export { canonicalJson, createIdempotencyInput, IdempotencyConflictError, IdempotencyInFlightError, IdempotencyKeyValidationError, IdempotencyPayloadValidationError, runIdempotentMutation, sha256CanonicalJson, withIdempotencyHttpErrors, } from './idempotency/idempotency.js';
40
41
  // realtime
@@ -9,6 +9,6 @@
9
9
  export { fromTinyIntFlag, replicaTimestampMs, toReplicaDateOnly, toReplicaIsoDatetime, toTinyIntFlag } from './wire.js';
10
10
  export { replicaNowIso } from './clock.js';
11
11
  export { defineRestDbMethodConverter } from './rest-db-method-converter.js';
12
- export type { RestDbMethodConverter } from './rest-db-method-converter.js';
12
+ export type { CompleteRestDbTableScheme, RestDbMethodConverter } from './rest-db-method-converter.js';
13
13
  export { decodeOfflineSnapshotCursor, encodeOfflineSnapshotCursor } from './snapshot-cursor.js';
14
14
  export type { OfflineSnapshotCursor } from './snapshot-cursor.js';
@@ -17,7 +17,7 @@ type CompleteDbTableValue<TValue> = TValue extends (infer TRow)[] ? TRow extends
17
17
  * intentionally does not own a generated column must exclude it from its
18
18
  * product-owned scheme first, for example `Omit<InsertRow, 'id'>`.
19
19
  */
20
- type CompleteRestDbTableScheme<TTableScheme extends object> = {
20
+ export type CompleteRestDbTableScheme<TTableScheme extends object> = {
21
21
  [TTableName in keyof TTableScheme]-?: CompleteDbTableValue<TTableScheme[TTableName]>;
22
22
  };
23
23
  /**
@@ -28,9 +28,9 @@ type CompleteRestDbTableScheme<TTableScheme extends object> = {
28
28
  * `$inferInsert` type marks them optional. Nullability does not make a column
29
29
  * optional in the conversion contract.
30
30
  */
31
- export interface RestDbMethodConverter<TMethodScheme, TTableScheme extends object> {
32
- toMethodScheme(tableScheme: Readonly<CompleteRestDbTableScheme<TTableScheme>>): TMethodScheme;
33
- toTableScheme(methodScheme: Readonly<TMethodScheme>): CompleteRestDbTableScheme<TTableScheme>;
31
+ export interface RestDbMethodConverter<TMethodScheme, TSelectTableScheme extends object, TInsertTableScheme extends object = TSelectTableScheme, TWriteContext = never> {
32
+ toMethodScheme(tableScheme: Readonly<CompleteRestDbTableScheme<TSelectTableScheme>>): TMethodScheme;
33
+ toTableScheme(methodScheme: Readonly<TMethodScheme>, ...context: [TWriteContext] extends [never] ? [] : [context: Readonly<TWriteContext>]): CompleteRestDbTableScheme<TInsertTableScheme>;
34
34
  }
35
35
  /**
36
36
  * Define a product-specific REST ↔ DB converter with contextual return types.
@@ -38,5 +38,5 @@ export interface RestDbMethodConverter<TMethodScheme, TTableScheme extends objec
38
38
  * This is intentionally an identity function: conversion remains explicit,
39
39
  * synchronous, and free of hidden persistence or HTTP side effects.
40
40
  */
41
- export declare function defineRestDbMethodConverter<TMethodScheme, TTableScheme extends object>(converter: RestDbMethodConverter<TMethodScheme, TTableScheme>): RestDbMethodConverter<TMethodScheme, TTableScheme>;
41
+ export declare function defineRestDbMethodConverter<TMethodScheme, TSelectTableScheme extends object, TInsertTableScheme extends object = TSelectTableScheme, TWriteContext = never>(converter: RestDbMethodConverter<TMethodScheme, TSelectTableScheme, TInsertTableScheme, TWriteContext>): RestDbMethodConverter<TMethodScheme, TSelectTableScheme, TInsertTableScheme, TWriteContext>;
42
42
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rdlabo/workers-hono-kit",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"