@rebasepro/server 0.9.1-canary.a57c262 → 0.9.1-canary.a8dbf1c

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.
Files changed (33) hide show
  1. package/dist/api/rest/api-generator.d.ts +9 -0
  2. package/dist/api/types.d.ts +2 -2
  3. package/dist/auth/admin-users-route.d.ts +3 -3
  4. package/dist/auth/api-keys/api-key-middleware.d.ts +60 -1
  5. package/dist/auth/api-keys/api-key-permission-guard.d.ts +33 -0
  6. package/dist/auth/api-keys/api-key-types.d.ts +21 -8
  7. package/dist/auth/api-keys/index.d.ts +2 -2
  8. package/dist/auth/auth-hooks.d.ts +7 -7
  9. package/dist/auth/interfaces.d.ts +28 -28
  10. package/dist/auth/jwt.d.ts +8 -3
  11. package/dist/auth/magic-link-routes.d.ts +2 -2
  12. package/dist/auth/mfa-routes.d.ts +1 -1
  13. package/dist/auth/middleware.d.ts +3 -3
  14. package/dist/auth/rate-limiter.d.ts +16 -2
  15. package/dist/auth/reset-password-admin.d.ts +1 -1
  16. package/dist/auth/session-routes.d.ts +2 -2
  17. package/dist/cron/cron-store.d.ts +18 -0
  18. package/dist/env.d.ts +3 -0
  19. package/dist/index.es.js +1457 -371
  20. package/dist/index.es.js.map +1 -1
  21. package/dist/init.d.ts +21 -0
  22. package/dist/{jwt-BJzQOa8a.js → jwt-B3zjddCa.js} +5 -5
  23. package/dist/{jwt-BJzQOa8a.js.map → jwt-B3zjddCa.js.map} +1 -1
  24. package/dist/{openapi-generator-Z9oYWLf_.js → openapi-generator-DqSIwNLV.js} +8 -2
  25. package/dist/openapi-generator-DqSIwNLV.js.map +1 -0
  26. package/dist/src-CsHhSKbi.js.map +1 -1
  27. package/dist/storage/LocalStorageController.d.ts +19 -2
  28. package/dist/storage/routes.d.ts +8 -1
  29. package/dist/storage/tus-handler.d.ts +21 -1
  30. package/dist/storage/types.d.ts +33 -0
  31. package/dist/utils/sql.d.ts +2 -2
  32. package/package.json +7 -6
  33. package/dist/openapi-generator-Z9oYWLf_.js.map +0 -1
@@ -24,6 +24,15 @@ export declare class RestApiGenerator {
24
24
  * No-ops if the request is not authenticated via an API key.
25
25
  */
26
26
  private enforceApiKeyPermission;
27
+ /**
28
+ * API key permission check for nested paths. The operation targets the
29
+ * LAST collection in the path (e.g. "posts" for /authors/1/posts), so
30
+ * that is the slug the key must hold permission for — checking the
31
+ * parent instead would let a key scoped to "authors" write "posts".
32
+ * `parseSubPath` always yields a collectionPath ending in a collection
33
+ * slug, never an id.
34
+ */
35
+ private enforceSubcollectionApiKeyPermission;
27
36
  /**
28
37
  * Get the request-scoped driver. Throws if none is set — never falls
29
38
  * back to the unscoped `this.driver` to avoid bypassing RLS/auth.
@@ -1,5 +1,5 @@
1
1
  import { VectorSearchParams, LogicalCondition, FilterValues } from "@rebasepro/types";
2
- import { AuthResult } from "../auth/middleware";
2
+ import type { AuthResult } from "../auth/middleware";
3
3
  import { DataDriver } from "@rebasepro/types";
4
4
  import type { ApiKeyMasked } from "../auth/api-keys/api-key-types";
5
5
  /**
@@ -9,7 +9,7 @@ import type { ApiKeyMasked } from "../auth/api-keys/api-key-types";
9
9
  export type HonoEnv = {
10
10
  Variables: {
11
11
  user?: AuthResult | {
12
- userId?: string;
12
+ uid?: string;
13
13
  roles?: string[];
14
14
  };
15
15
  driver?: DataDriver;
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * Mounts:
5
5
  * GET /users
6
- * GET /users/:userId
6
+ * GET /users/:uid
7
7
  * POST /users
8
- * PUT /users/:userId
9
- * DELETE /users/:userId
8
+ * PUT /users/:uid
9
+ * DELETE /users/:uid
10
10
  * POST /bootstrap
11
11
  */
12
12
  import { Hono } from "hono";
@@ -10,9 +10,18 @@
10
10
  * 4. Sets `c.set("user", ...)` and `c.set("apiKey", ...)` for downstream use
11
11
  * 5. Scopes the DataDriver via `withAuth()` using the API key's service identity
12
12
  *
13
+ * Authorization is double-gated for API keys: the key's own permission list
14
+ * (checked by the REST generator) is one ceiling, and Postgres RLS is another,
15
+ * independent one — `withAuth()` runs API-key requests as the restricted
16
+ * `rebase_user` role like any other caller. An `admin` key passes RLS via the
17
+ * injected `default_admin` policies; a non-admin key (roles `["service"]`,
18
+ * uid `api-key:<id>`) only sees rows that a policy explicitly grants to the
19
+ * `service` role or to the public. Owner-style policies
20
+ * (`owner_id = auth.uid()`) never match an API key's synthetic uid.
21
+ *
13
22
  * @module
14
23
  */
15
- import type { Context } from "hono";
24
+ import type { Context, MiddlewareHandler } from "hono";
16
25
  import type { DataDriver } from "@rebasepro/types";
17
26
  import type { HonoEnv } from "../../api/types";
18
27
  import type { ApiKeyStore } from "./api-key-store";
@@ -37,3 +46,53 @@ export interface ApiKeyAuthOptions {
37
46
  * `createAuthMiddleware()` when a `rk_` prefixed token is detected.
38
47
  */
39
48
  export declare function validateApiKey(c: Context<HonoEnv>, token: string, options: ApiKeyAuthOptions): Promise<Response | true>;
49
+ /**
50
+ * Permission guard for API-key requests to the storage router.
51
+ *
52
+ * Storage previously did not accept API keys at all (`rk_` tokens were
53
+ * misparsed as JWTs and 401'd). Now that the pre-auth middleware
54
+ * authenticates them, this guard decides what they may do: the key needs a
55
+ * `"storage"` permission entry (or the global `"*"` wildcard) covering the
56
+ * operation derived from the HTTP method. Requests not authenticated via an
57
+ * API key pass through to the storage router's own auth gates.
58
+ *
59
+ * TUS resumable-upload routes (`/tus`, `/tus/:id`) are classified as `write`
60
+ * for EVERY method: the protocol's offset check is a GET and its cancel is a
61
+ * DELETE, but both are steps of an upload — a write-scoped key must be able
62
+ * to complete (and abort) its own resumable upload without also holding
63
+ * `read`/`delete` on stored objects.
64
+ */
65
+ export declare function createStorageApiKeyGuard(): MiddlewareHandler<HonoEnv>;
66
+ /**
67
+ * Permission guard for API-key requests to the custom-functions router.
68
+ *
69
+ * The collection permission guard lives in the REST generator and never sees
70
+ * function routes, so before this middleware existed ANY valid API key —
71
+ * however narrowly scoped — could invoke every custom function. This guard
72
+ * closes that: API-key requests must hold a `"functions"`/`"functions/<name>"`
73
+ * permission entry (or the global `"*"` wildcard) for the derived operation.
74
+ *
75
+ * Non-API-key requests (JWT, service key, anonymous) pass through untouched —
76
+ * functions decide their own auth for those, as before.
77
+ *
78
+ * @param mountPrefix - The path the functions router is mounted at
79
+ * (e.g. `/api/functions`), used to extract the function
80
+ * name from the request path.
81
+ */
82
+ export declare function createFunctionApiKeyGuard(mountPrefix: string): MiddlewareHandler<HonoEnv>;
83
+ /**
84
+ * Standalone pre-auth middleware for `rk_` bearer tokens.
85
+ *
86
+ * Routers whose auth gate is JWT-based (`requireAuth` / `createRequireAuth` —
87
+ * the admin surfaces: admin users/roles, api-keys management, cron, backups,
88
+ * logs, schema editor) don't know about API keys. Mounting this middleware in
89
+ * front of them authenticates `rk_` tokens and populates the request context;
90
+ * the downstream gates then see the already-resolved user and apply their
91
+ * role checks (`requireAdmin`) as usual — so an `admin: true` key passes and
92
+ * a non-admin key is rejected with 403.
93
+ *
94
+ * Requests without an `rk_` bearer token pass through untouched. An invalid,
95
+ * revoked, or expired `rk_` token is rejected here (401) rather than falling
96
+ * through to be misparsed as a JWT.
97
+ */
98
+ export declare function createApiKeyPreAuth(options: ApiKeyAuthOptions): MiddlewareHandler<HonoEnv>;
@@ -30,3 +30,36 @@ export declare function httpMethodToOperation(method: string): ApiKeyOperation;
30
30
  * @returns `true` if the operation is permitted.
31
31
  */
32
32
  export declare function isOperationAllowed(permissions: ApiKeyPermission[], collection: string, operation: ApiKeyOperation): boolean;
33
+ /**
34
+ * Check whether the given permissions array allows a storage operation.
35
+ *
36
+ * Storage, like functions, lives outside the collection namespace: an entry
37
+ * with collection `"storage"` grants storage access for the listed
38
+ * operations (GET routes → `read`, upload/folder/tus → `write`,
39
+ * DELETE routes → `delete`), and the global `"*"` wildcard also matches.
40
+ * A collection-scoped key gets no storage access at all.
41
+ *
42
+ * Matching is exactly {@link isOperationAllowed} with `"storage"` as the
43
+ * resource name — delegated so the semantics can never drift.
44
+ */
45
+ export declare function isStorageAllowed(permissions: ApiKeyPermission[], operation: ApiKeyOperation): boolean;
46
+ /**
47
+ * Check whether the given permissions array allows invoking a custom function.
48
+ *
49
+ * Functions live outside the collection namespace, so they have their own
50
+ * resource names in the permission list:
51
+ *
52
+ * - `{ collection: "functions", ... }` grants every function
53
+ * - `{ collection: "functions/<name>", ... }` grants a single function
54
+ * - the global `"*"` wildcard (full-access keys) also matches
55
+ *
56
+ * The operation is derived from the HTTP method as usual (GET → read,
57
+ * POST/PUT/PATCH → write, DELETE → delete). The functions index route is
58
+ * checked as `functionName === ""`, which only the `"functions"` and `"*"`
59
+ * entries can grant.
60
+ *
61
+ * A collection-scoped key (e.g. read-only on `events`) therefore can NOT
62
+ * invoke functions — before this guard existed, any valid key could call
63
+ * every function.
64
+ */
65
+ export declare function isFunctionAllowed(permissions: ApiKeyPermission[], functionName: string, operation: ApiKeyOperation): boolean;
@@ -10,10 +10,13 @@
10
10
  /**
11
11
  * A single permission entry scoping an API key to a collection and set of operations.
12
12
  *
13
- * Use `"*"` as the collection value to grant access to all collections.
13
+ * Use `"*"` as the collection value to grant access to all collections
14
+ * (and all custom functions). Custom functions are addressed with the
15
+ * `functions` namespace: `"functions"` grants every function,
16
+ * `"functions/<name>"` grants a single one.
14
17
  */
15
18
  export interface ApiKeyPermission {
16
- /** Collection slug, or `"*"` for all collections. */
19
+ /** Collection slug, `"functions"`/`"functions/<name>"`, or `"*"` for everything. */
17
20
  collection: string;
18
21
  /** Allowed operations on the collection. */
19
22
  operations: ("read" | "write" | "delete")[];
@@ -30,9 +33,19 @@ export interface ApiKey {
30
33
  /** SHA-256 hash of the full plaintext key. */
31
34
  key_hash: string;
32
35
  permissions: ApiKeyPermission[];
33
- /** When true, the key is granted the `admin` role (access to admin routes). */
36
+ /**
37
+ * When true, the key is granted the `admin` role: it passes the
38
+ * admin-gated routes (users, roles, cron, backups, logs, API keys) and
39
+ * the RLS `default_admin` policies. Non-admin keys carry only the
40
+ * `service` role — RLS grants them nothing unless a collection policy
41
+ * explicitly names that role.
42
+ */
34
43
  admin: boolean;
35
- /** Requests per 15-minute window. `null` means unlimited. */
44
+ /**
45
+ * Requests per 15-minute window. `null` means "no per-key override" —
46
+ * the data rate limiter then applies its default API-key limit
47
+ * (1000/window unless configured otherwise), not unlimited.
48
+ */
36
49
  rate_limit: number | null;
37
50
  created_by: string;
38
51
  created_at: string;
@@ -50,7 +63,7 @@ export interface ApiKeyMasked {
50
63
  name: string;
51
64
  key_prefix: string;
52
65
  permissions: ApiKeyPermission[];
53
- /** When true, the key is granted the `admin` role (access to admin routes). */
66
+ /** When true, the key is granted the `admin` role (admin routes + RLS `default_admin` policies). */
54
67
  admin: boolean;
55
68
  rate_limit: number | null;
56
69
  created_by: string;
@@ -66,9 +79,9 @@ export interface ApiKeyMasked {
66
79
  export interface CreateApiKeyRequest {
67
80
  name: string;
68
81
  permissions: ApiKeyPermission[];
69
- /** When true, grants the `admin` role — allows access to admin routes. */
82
+ /** When true, grants the `admin` role (admin routes + RLS `default_admin` policies). */
70
83
  admin?: boolean;
71
- /** Requests per 15-minute window. Omit or `null` for unlimited. */
84
+ /** Requests per 15-minute window. Omit or `null` to use the server default (1000/window). */
72
85
  rate_limit?: number | null;
73
86
  /** ISO-8601 expiration timestamp. Omit for no expiration. */
74
87
  expires_at?: string | null;
@@ -80,7 +93,7 @@ export interface CreateApiKeyRequest {
80
93
  export interface UpdateApiKeyRequest {
81
94
  name?: string;
82
95
  permissions?: ApiKeyPermission[];
83
- /** When true, grants the `admin` role — allows access to admin routes. */
96
+ /** When true, grants the `admin` role (admin routes + RLS `default_admin` policies). */
84
97
  admin?: boolean;
85
98
  rate_limit?: number | null;
86
99
  expires_at?: string | null;
@@ -9,9 +9,9 @@
9
9
  export type { ApiKey, ApiKeyMasked, ApiKeyPermission, ApiKeyWithSecret, CreateApiKeyRequest, UpdateApiKeyRequest } from "./api-key-types";
10
10
  export { createApiKeyStore } from "./api-key-store";
11
11
  export type { ApiKeyStore } from "./api-key-store";
12
- export { isApiKeyToken, validateApiKey } from "./api-key-middleware";
12
+ export { isApiKeyToken, validateApiKey, createApiKeyPreAuth, createFunctionApiKeyGuard, createStorageApiKeyGuard } from "./api-key-middleware";
13
13
  export type { ApiKeyAuthOptions } from "./api-key-middleware";
14
- export { httpMethodToOperation, isOperationAllowed } from "./api-key-permission-guard";
14
+ export { httpMethodToOperation, isOperationAllowed, isFunctionAllowed, isStorageAllowed } from "./api-key-permission-guard";
15
15
  export type { ApiKeyOperation } from "./api-key-permission-guard";
16
16
  export { createApiKeyRoutes } from "./api-key-routes";
17
17
  export type { ApiKeyRouteOptions } from "./api-key-routes";
@@ -135,7 +135,7 @@ export interface AuthHooks {
135
135
  *
136
136
  * This is fire-and-forget — errors are logged but do not fail the request.
137
137
  */
138
- afterLogout?(userId: string): Promise<void>;
138
+ afterLogout?(uid: string): Promise<void>;
139
139
  /**
140
140
  * Called after successful MFA verification.
141
141
  *
@@ -143,12 +143,12 @@ export interface AuthHooks {
143
143
  *
144
144
  * This is fire-and-forget — errors are logged but do not fail the request.
145
145
  */
146
- onMfaVerified?(userId: string, factorId: string): Promise<void>;
146
+ onMfaVerified?(uid: string, factorId: string): Promise<void>;
147
147
  /**
148
148
  * Customize JWT access token claims before signing.
149
149
  *
150
150
  * Return the modified claims object. The returned claims are merged
151
- * into the JWT payload alongside standard claims (userId, roles).
151
+ * into the JWT payload alongside standard claims (uid, roles).
152
152
  *
153
153
  * @param claims - The default claims that would be included.
154
154
  * @param user - The authenticated user data.
@@ -178,14 +178,14 @@ export interface AuthHooks {
178
178
  *
179
179
  * This is fire-and-forget — errors are logged but do not fail the request.
180
180
  */
181
- onPasswordReset?(userId: string): Promise<void>;
181
+ onPasswordReset?(uid: string): Promise<void>;
182
182
  /**
183
183
  * Called before a user is deleted.
184
184
  *
185
185
  * Throw an error to prevent deletion (e.g. for users with active
186
186
  * subscriptions, pending transactions, etc.).
187
187
  */
188
- beforeUserDelete?(userId: string): Promise<void>;
188
+ beforeUserDelete?(uid: string): Promise<void>;
189
189
  /**
190
190
  * Called after a user is deleted.
191
191
  *
@@ -193,7 +193,7 @@ export interface AuthHooks {
193
193
  *
194
194
  * This is fire-and-forget — errors are logged but do not fail the request.
195
195
  */
196
- afterUserDelete?(userId: string): Promise<void>;
196
+ afterUserDelete?(uid: string): Promise<void>;
197
197
  /**
198
198
  * Optional hook to customize or override the default user creation flow via the admin panel/REST API.
199
199
  * When provided, this replaces the built-in password generation, hashing, and invitation email logic.
@@ -212,7 +212,7 @@ export interface AuthHooks {
212
212
  * Optional hook to customize or override the default password reset flow via the admin panel.
213
213
  * When provided, this replaces the built-in password reset token generation, hashing, and email logic.
214
214
  */
215
- onAdminResetPassword?(userId: string, ctx: {
215
+ onAdminResetPassword?(uid: string, ctx: {
216
216
  authRepo: AuthRepository;
217
217
  emailService?: EmailService;
218
218
  emailConfig?: EmailConfig;
@@ -40,7 +40,7 @@ export interface CreateUserData {
40
40
  */
41
41
  export interface UserIdentityData {
42
42
  id: string;
43
- userId: string;
43
+ uid: string;
44
44
  provider: string;
45
45
  providerId: string;
46
46
  profileData?: Record<string, unknown> | null;
@@ -113,7 +113,7 @@ export interface CreateRoleData {
113
113
  */
114
114
  export interface RefreshTokenInfo {
115
115
  id: string;
116
- userId: string;
116
+ uid: string;
117
117
  tokenHash: string;
118
118
  expiresAt: Date;
119
119
  createdAt: Date;
@@ -124,14 +124,14 @@ export interface RefreshTokenInfo {
124
124
  * Password reset token info
125
125
  */
126
126
  export interface PasswordResetTokenInfo {
127
- userId: string;
127
+ uid: string;
128
128
  expiresAt: Date;
129
129
  }
130
130
  /**
131
131
  * Magic link token info
132
132
  */
133
133
  export interface MagicLinkTokenInfo {
134
- userId: string;
134
+ uid: string;
135
135
  expiresAt: Date;
136
136
  }
137
137
  /**
@@ -185,11 +185,11 @@ export interface UserRepository {
185
185
  /**
186
186
  * Get all identities linked to a user
187
187
  */
188
- getUserIdentities(userId: string): Promise<UserIdentityData[]>;
188
+ getUserIdentities(uid: string): Promise<UserIdentityData[]>;
189
189
  /**
190
190
  * Link a new OAuth identity to a user
191
191
  */
192
- linkUserIdentity(userId: string, provider: string, providerId: string, profileData?: Record<string, unknown>): Promise<void>;
192
+ linkUserIdentity(uid: string, provider: string, providerId: string, profileData?: Record<string, unknown>): Promise<void>;
193
193
  /**
194
194
  * Update a user
195
195
  */
@@ -225,23 +225,23 @@ export interface UserRepository {
225
225
  /**
226
226
  * Get roles for a user
227
227
  */
228
- getUserRoles(userId: string): Promise<RoleData[]>;
228
+ getUserRoles(uid: string): Promise<RoleData[]>;
229
229
  /**
230
230
  * Get role IDs for a user
231
231
  */
232
- getUserRoleIds(userId: string): Promise<string[]>;
232
+ getUserRoleIds(uid: string): Promise<string[]>;
233
233
  /**
234
234
  * Set roles for a user (replaces existing roles)
235
235
  */
236
- setUserRoles(userId: string, roleIds: string[]): Promise<void>;
236
+ setUserRoles(uid: string, roleIds: string[]): Promise<void>;
237
237
  /**
238
238
  * Assign a specific role to a new user
239
239
  */
240
- assignDefaultRole(userId: string, roleId: string): Promise<void>;
240
+ assignDefaultRole(uid: string, roleId: string): Promise<void>;
241
241
  /**
242
242
  * Get user with their roles
243
243
  */
244
- getUserWithRoles(userId: string): Promise<{
244
+ getUserWithRoles(uid: string): Promise<{
245
245
  user: UserData;
246
246
  roles: RoleData[];
247
247
  } | null>;
@@ -280,7 +280,7 @@ export interface TokenRepository {
280
280
  /**
281
281
  * Create a new refresh token
282
282
  */
283
- createRefreshToken(userId: string, tokenHash: string, expiresAt: Date, userAgent?: string, ipAddress?: string): Promise<void>;
283
+ createRefreshToken(uid: string, tokenHash: string, expiresAt: Date, userAgent?: string, ipAddress?: string): Promise<void>;
284
284
  /**
285
285
  * Find a refresh token by hash
286
286
  */
@@ -292,19 +292,19 @@ export interface TokenRepository {
292
292
  /**
293
293
  * Delete all refresh tokens for a user
294
294
  */
295
- deleteAllRefreshTokensForUser(userId: string): Promise<void>;
295
+ deleteAllRefreshTokensForUser(uid: string): Promise<void>;
296
296
  /**
297
297
  * List all refresh tokens for a user
298
298
  */
299
- listRefreshTokensForUser(userId: string): Promise<RefreshTokenInfo[]>;
299
+ listRefreshTokensForUser(uid: string): Promise<RefreshTokenInfo[]>;
300
300
  /**
301
301
  * Delete a specific refresh token by its primary key ID
302
302
  */
303
- deleteRefreshTokenById(id: string, userId: string): Promise<void>;
303
+ deleteRefreshTokenById(id: string, uid: string): Promise<void>;
304
304
  /**
305
305
  * Create a password reset token
306
306
  */
307
- createPasswordResetToken(userId: string, tokenHash: string, expiresAt: Date): Promise<void>;
307
+ createPasswordResetToken(uid: string, tokenHash: string, expiresAt: Date): Promise<void>;
308
308
  /**
309
309
  * Find a valid (not expired, not used) password reset token by hash
310
310
  */
@@ -316,7 +316,7 @@ export interface TokenRepository {
316
316
  /**
317
317
  * Delete all password reset tokens for a user
318
318
  */
319
- deleteAllPasswordResetTokensForUser(userId: string): Promise<void>;
319
+ deleteAllPasswordResetTokensForUser(uid: string): Promise<void>;
320
320
  /**
321
321
  * Clean up expired tokens
322
322
  */
@@ -324,7 +324,7 @@ export interface TokenRepository {
324
324
  /**
325
325
  * Create a magic link token
326
326
  */
327
- createMagicLinkToken(userId: string, tokenHash: string, expiresAt: Date): Promise<void>;
327
+ createMagicLinkToken(uid: string, tokenHash: string, expiresAt: Date): Promise<void>;
328
328
  /**
329
329
  * Find a valid (not expired, not used) magic link token by hash
330
330
  */
@@ -339,7 +339,7 @@ export interface TokenRepository {
339
339
  */
340
340
  export interface MfaFactor {
341
341
  id: string;
342
- userId: string;
342
+ uid: string;
343
343
  factorType: "totp";
344
344
  friendlyName?: string;
345
345
  verified: boolean;
@@ -361,7 +361,7 @@ export interface MfaChallengeInfo {
361
361
  */
362
362
  export interface RecoveryCode {
363
363
  id: string;
364
- userId: string;
364
+ uid: string;
365
365
  usedAt?: Date;
366
366
  }
367
367
  /**
@@ -372,11 +372,11 @@ export interface MfaRepository {
372
372
  /**
373
373
  * Create a new MFA factor for a user
374
374
  */
375
- createMfaFactor(userId: string, factorType: "totp", secretEncrypted: string, friendlyName?: string): Promise<MfaFactor>;
375
+ createMfaFactor(uid: string, factorType: "totp", secretEncrypted: string, friendlyName?: string): Promise<MfaFactor>;
376
376
  /**
377
377
  * Get all MFA factors for a user
378
378
  */
379
- getMfaFactors(userId: string): Promise<MfaFactor[]>;
379
+ getMfaFactors(uid: string): Promise<MfaFactor[]>;
380
380
  /**
381
381
  * Get a specific MFA factor by ID
382
382
  */
@@ -390,7 +390,7 @@ export interface MfaRepository {
390
390
  /**
391
391
  * Delete an MFA factor
392
392
  */
393
- deleteMfaFactor(factorId: string, userId: string): Promise<void>;
393
+ deleteMfaFactor(factorId: string, uid: string): Promise<void>;
394
394
  /**
395
395
  * Create an MFA challenge
396
396
  */
@@ -406,23 +406,23 @@ export interface MfaRepository {
406
406
  /**
407
407
  * Create recovery codes for a user
408
408
  */
409
- createRecoveryCodes(userId: string, codeHashes: string[]): Promise<void>;
409
+ createRecoveryCodes(uid: string, codeHashes: string[]): Promise<void>;
410
410
  /**
411
411
  * Use a recovery code (mark as used)
412
412
  */
413
- useRecoveryCode(userId: string, codeHash: string): Promise<boolean>;
413
+ useRecoveryCode(uid: string, codeHash: string): Promise<boolean>;
414
414
  /**
415
415
  * Get unused recovery code count for a user
416
416
  */
417
- getUnusedRecoveryCodeCount(userId: string): Promise<number>;
417
+ getUnusedRecoveryCodeCount(uid: string): Promise<number>;
418
418
  /**
419
419
  * Delete all recovery codes for a user
420
420
  */
421
- deleteAllRecoveryCodes(userId: string): Promise<void>;
421
+ deleteAllRecoveryCodes(uid: string): Promise<void>;
422
422
  /**
423
423
  * Check if a user has any verified MFA factors
424
424
  */
425
- hasVerifiedMfaFactors(userId: string): Promise<boolean>;
425
+ hasVerifiedMfaFactors(uid: string): Promise<boolean>;
426
426
  }
427
427
  /**
428
428
  * Combined auth repository interface for convenience
@@ -4,9 +4,14 @@ export interface JwtConfig {
4
4
  refreshExpiresIn?: string;
5
5
  }
6
6
  export interface AccessTokenPayload {
7
- userId: string;
7
+ /**
8
+ * The user's id — the same spelling the domain model, the auth adapters and
9
+ * the RLS layer (`auth.uid()`) all use. Tokens minted before this rename
10
+ * carry `uid` instead, and older external IdPs may send `sub`;
11
+ * {@link verifyAccessToken} accepts all three and normalises to this.
12
+ */
13
+ uid: string;
8
14
  roles: string[];
9
- uid?: string;
10
15
  /** Authentication Assurance Level: aal1 = password/oauth, aal2 = MFA verified */
11
16
  aal?: "aal1" | "aal2";
12
17
  /** Email claim from the JWT, if present */
@@ -28,7 +33,7 @@ export declare function configureJwt(config: JwtConfig): void;
28
33
  /**
29
34
  * Generate an access token (short-lived, 1 hour by default)
30
35
  */
31
- export declare function generateAccessToken(userId: string, roles: string[], aal?: "aal1" | "aal2", customClaims?: Record<string, unknown>): string;
36
+ export declare function generateAccessToken(uid: string, roles: string[], aal?: "aal1" | "aal2", customClaims?: Record<string, unknown>): string;
32
37
  /**
33
38
  * Get the expiration time of an access token in milliseconds from now
34
39
  */
@@ -23,10 +23,10 @@ export declare function mountMagicLinkRoutes(deps: {
23
23
  isAnonymous?: boolean;
24
24
  metadata?: Record<string, unknown> | null;
25
25
  }, roleIds: string[], accessToken: string, refreshToken: string, providerId: string) => unknown;
26
- createSessionAndTokens: (userId: string, userAgent: string, ipAddress: string) => Promise<{
26
+ createSessionAndTokens: (uid: string, userAgent: string, ipAddress: string) => Promise<{
27
27
  roleIds: string[];
28
28
  accessToken: string;
29
29
  refreshToken: string;
30
30
  }>;
31
- applyTransformHook: (response: AuthResponsePayload, method: TransformAuthResponseContext["method"], request: Request, userId: string) => Promise<AuthResponsePayload>;
31
+ applyTransformHook: (response: AuthResponsePayload, method: TransformAuthResponseContext["method"], request: Request, uid: string) => Promise<AuthResponsePayload>;
32
32
  }): void;
@@ -4,4 +4,4 @@ import { HonoEnv } from "../api/types";
4
4
  import type { AuthModuleConfig } from "./routes";
5
5
  import { resolveAuthHooks } from "./auth-hooks";
6
6
  import type { AuthResponsePayload, TransformAuthResponseContext } from "@rebasepro/types";
7
- export declare function mountMfaRoutes(router: Hono<HonoEnv>, config: AuthModuleConfig, ops: ReturnType<typeof resolveAuthHooks>, parseBody: <T>(schema: z.ZodSchema<T>, body: unknown) => T, applyTransformHook?: (response: AuthResponsePayload, method: TransformAuthResponseContext["method"], request: Request, userId: string) => Promise<AuthResponsePayload>): void;
7
+ export declare function mountMfaRoutes(router: Hono<HonoEnv>, config: AuthModuleConfig, ops: ReturnType<typeof resolveAuthHooks>, parseBody: <T>(schema: z.ZodSchema<T>, body: unknown) => T, applyTransformHook?: (response: AuthResponsePayload, method: TransformAuthResponseContext["method"], request: Request, uid: string) => Promise<AuthResponsePayload>): void;
@@ -1,17 +1,17 @@
1
1
  import { MiddlewareHandler, Context } from "hono";
2
2
  import { DataDriver } from "@rebasepro/types";
3
3
  import { AccessTokenPayload } from "./jwt";
4
- import { HonoEnv } from "../api/types";
4
+ import type { HonoEnv } from "../api/types";
5
5
  import type { ApiKeyStore } from "./api-keys/api-key-store";
6
6
  /**
7
7
  * Result from a custom auth validator.
8
8
  * - `false`/`null`/`undefined` = not authenticated
9
9
  * - `true` = authenticated as default user
10
- * - object with `userId` or `uid` = authenticated with user info
10
+ * - object with `uid` (or legacy `userId`) = authenticated with user info
11
11
  */
12
12
  export type AuthResult = boolean | null | undefined | {
13
- userId?: string;
14
13
  uid?: string;
14
+ userId?: string;
15
15
  roles?: string[];
16
16
  [key: string]: unknown;
17
17
  };
@@ -27,6 +27,16 @@ interface RateLimiterOptions {
27
27
  * `limit`; returning `null` skips the limiter for this request.
28
28
  */
29
29
  resolveLimit?: (c: Parameters<MiddlewareHandler<HonoEnv>>[0]) => number | null | undefined;
30
+ /**
31
+ * Number of trusted reverse-proxy hops in front of this server. Each hop
32
+ * appends the address it saw to `X-Forwarded-For`, so the real client IP is
33
+ * the Nth entry from the right. Anything further left is client-supplied and
34
+ * ignored — which is what stops a caller spoofing `X-Forwarded-For` to
35
+ * rotate rate-limit keys. Defaults to `TRUSTED_PROXY_HOPS` (env) or `1`.
36
+ * Set to `0` when the server is exposed directly (no proxy): `X-Forwarded-For`
37
+ * is then ignored entirely in favour of `X-Real-IP`.
38
+ */
39
+ trustedProxyHops?: number;
30
40
  }
31
41
  /**
32
42
  * Create a rate-limiting middleware.
@@ -61,8 +71,12 @@ export interface DataRateLimitConfig {
61
71
  apiKey?: number;
62
72
  /** Per signed-in user. Default 1000. */
63
73
  user?: number;
64
- /** Per IP, for requests with no principal at all. Default 300. */
65
- anonymous?: number;
74
+ /**
75
+ * Per IP, for requests with no principal at all. Default 300.
76
+ * `null` disables the anonymous bucket entirely — used for routers whose
77
+ * anonymous traffic must not be throttled (public webhook functions).
78
+ */
79
+ anonymous?: number | null;
66
80
  /** Share counts across replicas. Defaults to this process's memory. */
67
81
  store?: RateLimitStore;
68
82
  }
@@ -24,6 +24,6 @@ export interface ResetPasswordRouteConfig {
24
24
  /**
25
25
  * Create a standalone admin route for resetting user passwords.
26
26
  *
27
- * Mounts: POST /users/:userId/reset-password
27
+ * Mounts: POST /users/:uid/reset-password
28
28
  */
29
29
  export declare function createResetPasswordRoute(config: ResetPasswordRouteConfig): Hono<HonoEnv>;
@@ -18,12 +18,12 @@ interface SessionRoutesConfig {
18
18
  isAnonymous?: boolean;
19
19
  metadata?: Record<string, unknown> | null;
20
20
  }, roleIds: string[], accessToken: string, refreshToken: string, providerId: string) => unknown;
21
- createSessionAndTokens: (userId: string, userAgent: string, ipAddress: string) => Promise<{
21
+ createSessionAndTokens: (uid: string, userAgent: string, ipAddress: string) => Promise<{
22
22
  roleIds: string[];
23
23
  accessToken: string;
24
24
  refreshToken: string;
25
25
  }>;
26
- applyTransformHook: (response: AuthResponsePayload, method: TransformAuthResponseContext["method"], request: Request, userId: string) => Promise<AuthResponsePayload>;
26
+ applyTransformHook: (response: AuthResponsePayload, method: TransformAuthResponseContext["method"], request: Request, uid: string) => Promise<AuthResponsePayload>;
27
27
  }
28
28
  export declare function mountSessionRoutes(opts: SessionRoutesConfig): void;
29
29
  export {};
@@ -28,5 +28,23 @@ export interface CronStore {
28
28
  totalFailures: number;
29
29
  lastRunAt?: string;
30
30
  }>>;
31
+ /**
32
+ * Atomically claim a scheduled run slot for a job.
33
+ *
34
+ * `slot` is the *scheduled* fire time (ISO string) derived from the cron
35
+ * expression — deterministic across instances regardless of timer drift,
36
+ * so all instances contend on the same (jobId, slot) key. Exactly one
37
+ * caller wins the insert against the unique constraint and executes;
38
+ * the rest skip.
39
+ *
40
+ * Fails open (returns true) on unexpected store errors, so a broken
41
+ * claims table degrades to uncoordinated execution rather than silently
42
+ * never running jobs.
43
+ *
44
+ * Optional so custom stores written against the pre-claims interface
45
+ * keep working — the scheduler treats a missing implementation as
46
+ * uncoordinated (always run).
47
+ */
48
+ tryClaimRun?(jobId: string, slot: string): Promise<boolean>;
31
49
  }
32
50
  export declare function createCronStore(driver: DataDriver): CronStore | undefined;
package/dist/env.d.ts CHANGED
@@ -55,6 +55,9 @@ declare const rebaseEnvSchema: z.ZodObject<{
55
55
  true: "true";
56
56
  false: "false";
57
57
  }>>, z.ZodTransform<boolean, "" | "true" | "false" | undefined>>;
58
+ GCS_BUCKET: z.ZodOptional<z.ZodString>;
59
+ GCS_PROJECT_ID: z.ZodOptional<z.ZodString>;
60
+ GCS_KEY_FILENAME: z.ZodOptional<z.ZodString>;
58
61
  }, z.core.$strip>;
59
62
  /** Inferred type of the validated environment. */
60
63
  export type RebaseEnv = z.infer<typeof rebaseEnvSchema>;