@rebasepro/server 0.9.1-canary.7dddf96 → 0.9.1-canary.a57c262

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,19 @@
1
+ import { CollectionConfig } from "@rebasepro/types";
2
+ /**
3
+ * Reject a write naming a field the collection does not have.
4
+ *
5
+ * Unknown keys used to travel all the way into the INSERT, where Postgres
6
+ * rejected them — so a typo came back as `column "titel" does not exist`,
7
+ * phrased by the database, from a stack the caller cannot see, and only if the
8
+ * column really was absent. It is a request problem and belongs in a 400.
9
+ *
10
+ * What counts as known:
11
+ * - a declared property (for an introspected BaaS collection these *are* the
12
+ * columns, so the set is exact);
13
+ * - the foreign-key column behind an owning relation, which callers may write
14
+ * directly instead of through the relation property;
15
+ * - nothing else. `id` in particular is not automatically known — see below.
16
+ */
17
+ export declare function assertKnownWriteFields(values: Record<string, unknown>, collection: CollectionConfig, options?: {
18
+ rowIndex?: number;
19
+ }): void;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Warn when the auth collection hangs data callbacks that auth will not fire.
3
+ *
4
+ * Creating a user through the auth subsystem — registration, OAuth, the admin
5
+ * user routes — writes to the user store directly, because that path owns
6
+ * password hashing, identity rows and its own transaction. It deliberately does
7
+ * not go through the collection save pipeline: a `beforeSave` able to rewrite
8
+ * `password_hash` on its way to the database is a footgun, not a feature, and
9
+ * the auth hooks (`afterUserCreate`, `beforeUserCreate`, …) exist to hang
10
+ * behaviour off those events with the right contract.
11
+ *
12
+ * The cost is a reasonable expectation quietly not being met: someone puts
13
+ * "send the welcome email" in `afterSave` on their users collection, tests it
14
+ * by creating a user in the admin, and it works — because *that* is a
15
+ * collection write. Then a real signup does nothing at all. Which is why this
16
+ * is said at boot, naming the callbacks that will not run.
17
+ */
18
+ export declare function warnOnAuthCollectionDataCallbacks(collection?: {
19
+ slug?: string;
20
+ callbacks?: Record<string, unknown>;
21
+ }): void;
@@ -28,7 +28,10 @@ export type { AuthModuleConfig, CookieAuthConfig } from "./routes";
28
28
  export { mountMagicLinkRoutes } from "./magic-link-routes";
29
29
  export { createResetPasswordRoute } from "./reset-password-admin";
30
30
  export type { ResetPasswordRouteConfig } from "./reset-password-admin";
31
- export { createRateLimiter, defaultAuthLimiter, strictAuthLimiter, createApiKeyRateLimiter, apiKeyKeyGenerator } from "./rate-limiter";
31
+ export { createRateLimiter, defaultAuthLimiter, strictAuthLimiter, createApiKeyRateLimiter, createDataRateLimiter, apiKeyKeyGenerator } from "./rate-limiter";
32
+ export type { DataRateLimitConfig } from "./rate-limiter";
33
+ export { MemoryRateLimitStore } from "./rate-limit-store";
34
+ export type { RateLimitStore, RateLimitDecision } from "./rate-limit-store";
32
35
  export { createApiKeyStore, createApiKeyRoutes, isApiKeyToken, validateApiKey, httpMethodToOperation, isOperationAllowed } from "./api-keys";
33
36
  export type { ApiKey, ApiKeyMasked, ApiKeyPermission, ApiKeyWithSecret, CreateApiKeyRequest, UpdateApiKeyRequest, ApiKeyStore, ApiKeyOperation } from "./api-keys";
34
37
  export { createBuiltinAuthAdapter } from "./builtin-auth-adapter";
@@ -38,7 +38,18 @@ export declare function getAccessTokenExpiryMs(): number;
38
38
  */
39
39
  export declare function getAccessTokenExpiry(): number;
40
40
  /**
41
- * Verify and decode an access token
41
+ * Verify and decode an access token.
42
+ *
43
+ * Every token this server issues is signed with the same secret, so what a
44
+ * token *is* comes from its claims, not from its signature. A download token
45
+ * ({@link generateDownloadToken}) is therefore a validly-signed string that
46
+ * must never authenticate anybody: it is scoped to one file path and handed out
47
+ * in URLs, which is a far weaker thing to hold than a session.
48
+ *
49
+ * Today it is rejected below for want of an id — but only by luck, since
50
+ * nothing stops a future download token from carrying one. So the purpose is
51
+ * checked explicitly: a token minted for reading a file is not a token for
52
+ * being a user.
42
53
  */
43
54
  export declare function verifyAccessToken(token: string): AccessTokenPayload | null;
44
55
  /**
@@ -150,6 +150,27 @@ export declare const queryTokenAuth: MiddlewareHandler<HonoEnv>;
150
150
  * untouched, so they still require a valid token.
151
151
  */
152
152
  export declare const publicObjectAuth: MiddlewareHandler<HonoEnv>;
153
+ /**
154
+ * Helper to match paths for scoped file tokens.
155
+ * Matches exact paths or prefixes (exact folder prefixes or ending with /).
156
+ *
157
+ * The traversal check is defence in depth, not the load-bearing defence.
158
+ *
159
+ * A prefix comparison is a lie for any path containing `..`: `user1/../user2/x`
160
+ * starts with `user1/`, so a token scoped to `user1/` would authorize reading
161
+ * user2's file — and the storage controller would not object, because its own
162
+ * guard stops a path escaping the *bucket*, and that one resolves to `user2/x`,
163
+ * comfortably inside it. The grant is what would be escaped, and this is the
164
+ * only layer that knows what was granted.
165
+ *
166
+ * Nothing arrives here in that shape today: the URL parser resolves `..` (and
167
+ * `%2e%2e`, which the WHATWG spec treats as a dot for normalization) before
168
+ * Hono routes the request, so this comparison already runs on a resolved path.
169
+ * But that is a guarantee of the runtime rather than of this code, and it is
170
+ * one line to not depend on it. The same rule already guards the public-object
171
+ * path — see `isPublicStoragePath`.
172
+ */
173
+ export declare function isPathMatch(requested: string, allowed: string): boolean;
153
174
  /**
154
175
  * Middleware that authenticates file-serving routes using scoped download tokens.
155
176
  * It enforces that only scoped "file-read" tokens can access "/file/*" and "?token=" query params.
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Where a rate limiter keeps its counts.
3
+ *
4
+ * Split out from the limiter itself because the two have different lifetimes:
5
+ * the policy (how many, how often, keyed by what) is a property of the route,
6
+ * and the storage is a property of the deployment. One process behind one
7
+ * proxy is happy with a Map; several replicas behind a load balancer are not,
8
+ * because a limit of 200 enforced independently by four of them is a limit of
9
+ * 800.
10
+ */
11
+ export interface RateLimitDecision {
12
+ allowed: boolean;
13
+ /** Requests left in the current window. Zero when `allowed` is false. */
14
+ remaining: number;
15
+ /** How long until the oldest hit falls out of the window. */
16
+ retryAfterMs: number;
17
+ }
18
+ export interface RateLimitStore {
19
+ /**
20
+ * Record a hit against `key` and say whether it is allowed.
21
+ *
22
+ * Called once per request, so it must not be chatty. Implementations are
23
+ * expected to be atomic per key: two concurrent hits must not both read a
24
+ * count of `limit - 1` and both be allowed.
25
+ */
26
+ hit(key: string, windowMs: number, limit: number): Promise<RateLimitDecision>;
27
+ /** Release timers/connections. Tests need this; servers rarely do. */
28
+ dispose?(): void;
29
+ }
30
+ /**
31
+ * The default store: a sliding window in this process's memory.
32
+ *
33
+ * Sliding rather than fixed: a fixed window lets a caller spend its whole
34
+ * allowance in the last second of one window and again in the first second of
35
+ * the next, which is twice the limit over an instant. Timestamps outside the
36
+ * window are dropped on read, and swept periodically so an idle key does not
37
+ * pin its array forever.
38
+ *
39
+ * Per-process, so N replicas enforce N times the limit between them. That is
40
+ * the honest reason {@link RateLimitStore} exists.
41
+ */
42
+ export declare class MemoryRateLimitStore implements RateLimitStore {
43
+ private store;
44
+ private cleanupInterval?;
45
+ constructor(sweepMs?: number);
46
+ hit(key: string, windowMs: number, limit: number): Promise<RateLimitDecision>;
47
+ private sweep;
48
+ dispose(): void;
49
+ }
@@ -1,5 +1,12 @@
1
1
  import { MiddlewareHandler } from "hono";
2
2
  import { HonoEnv } from "../api/types";
3
+ import { RateLimitStore } from "./rate-limit-store";
4
+ /**
5
+ * Sliding-window rate limiting for Hono.
6
+ *
7
+ * The counting lives in a {@link RateLimitStore} — in this process's memory by
8
+ * default, which is a per-replica limit and says so. See `rate-limit-store.ts`.
9
+ */
3
10
  interface RateLimiterOptions {
4
11
  /** Time window in milliseconds (default: 15 minutes) */
5
12
  windowMs?: number;
@@ -9,13 +16,22 @@ interface RateLimiterOptions {
9
16
  keyGenerator?: (c: Parameters<MiddlewareHandler<HonoEnv>>[0]) => string;
10
17
  /** Custom message for rate limit responses */
11
18
  message?: string;
19
+ /**
20
+ * Where to keep the counts. Defaults to a private in-memory store — pass a
21
+ * shared one to have several limiters (or several processes) agree.
22
+ */
23
+ store?: RateLimitStore;
24
+ /**
25
+ * Per-request limit override, for buckets whose allowance is data rather
26
+ * than config (an API key's own `rate_limit`). Returning `undefined` uses
27
+ * `limit`; returning `null` skips the limiter for this request.
28
+ */
29
+ resolveLimit?: (c: Parameters<MiddlewareHandler<HonoEnv>>[0]) => number | null | undefined;
12
30
  }
13
31
  /**
14
32
  * Create a rate-limiting middleware.
15
33
  *
16
- * Uses a sliding window algorithm: only timestamps within the last
17
- * `windowMs` milliseconds are counted. Old entries are garbage-collected
18
- * every `windowMs` to prevent unbounded memory growth.
34
+ * Uses a sliding window: only hits within the last `windowMs` are counted.
19
35
  */
20
36
  export declare function createRateLimiter(options?: RateLimiterOptions): MiddlewareHandler<HonoEnv>;
21
37
  /**
@@ -36,12 +52,44 @@ export declare const strictAuthLimiter: MiddlewareHandler<HonoEnv>;
36
52
  * via an API key.
37
53
  */
38
54
  export declare function apiKeyKeyGenerator(c: Parameters<MiddlewareHandler<HonoEnv>>[0]): string;
55
+ /** How the data API's limits are apportioned. All fields optional. */
56
+ export interface DataRateLimitConfig {
57
+ /** Turn the whole thing off — for a deployment whose proxy already does it. */
58
+ enabled?: boolean;
59
+ windowMs?: number;
60
+ /** Fallback for an API key with no `rate_limit` of its own. Default 1000. */
61
+ apiKey?: number;
62
+ /** Per signed-in user. Default 1000. */
63
+ user?: number;
64
+ /** Per IP, for requests with no principal at all. Default 300. */
65
+ anonymous?: number;
66
+ /** Share counts across replicas. Defaults to this process's memory. */
67
+ store?: RateLimitStore;
68
+ }
69
+ /**
70
+ * Rate limiting for the data API.
71
+ *
72
+ * Every request is in exactly one bucket, resolved most-specific first: an API
73
+ * key by its id, a signed-in user by their uid, anyone else by IP. Previously
74
+ * only the first of those was limited at all — the middleware returned early
75
+ * for any request without an API key — so JWT and anonymous traffic to
76
+ * `/api/data/*` was unbounded, which is most of the traffic a BaaS gets.
77
+ *
78
+ * Per bucket, not per route: the point is to bound what one caller costs, and
79
+ * they can spend it wherever they like.
80
+ *
81
+ * The defaults are deliberately loose. This is a floor against a runaway client
82
+ * or a naive scraper, not a quota — a deployment that wants real quotas should
83
+ * set them, and one that already has a proxy doing this should pass
84
+ * `enabled: false` rather than pay for it twice.
85
+ */
86
+ export declare function createDataRateLimiter(config?: DataRateLimitConfig): MiddlewareHandler<HonoEnv>;
39
87
  /**
40
88
  * Create a rate limiter specifically for API key requests.
41
89
  *
42
- * When a request is authenticated via an API key that has a `rate_limit`
43
- * configured, this limiter enforces per-key limits using the key's ID
44
- * as the rate limit bucket.
90
+ * @deprecated Use {@link createDataRateLimiter}, which limits signed-in users
91
+ * and anonymous callers too. This one skips every request that is not
92
+ * API-key-authenticated, which was most of them.
45
93
  *
46
94
  * @param defaultLimit - Fallback limit when the key has no `rate_limit` set.
47
95
  * @param windowMs - Time window in milliseconds (default: 15 minutes).