lambder 3.8.1 → 4.0.1
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 +79 -14
- package/dist/{LambderCaller.d.ts → client/LambderCaller.d.ts} +30 -12
- package/dist/{LambderCaller.js → client/LambderCaller.js} +21 -12
- package/dist/{LambderMSW.d.ts → client/LambderMSW.d.ts} +1 -1
- package/dist/client.d.ts +16 -0
- package/dist/client.js +17 -0
- package/dist/{Lambder.d.ts → core/Lambder.d.ts} +45 -20
- package/dist/{Lambder.js → core/Lambder.js} +28 -13
- package/dist/{LambderContext.d.ts → core/LambderContext.d.ts} +9 -3
- package/dist/{LambderContext.js → core/LambderContext.js} +1 -0
- package/dist/{LambderPublicFiles.js → core/LambderPublicFiles.js} +1 -1
- package/dist/{LambderResponse.js → core/LambderResponse.js} +1 -1
- package/dist/{LambderResponseBuilder.d.ts → core/LambderResponseBuilder.d.ts} +3 -15
- package/dist/{LambderResponseBuilder.js → core/LambderResponseBuilder.js} +2 -2
- package/dist/{LambderTemplatingEngine.d.ts → core/LambderTemplatingEngine.d.ts} +1 -1
- package/dist/{LambderTemplatingEngine.js → core/LambderTemplatingEngine.js} +2 -2
- package/dist/index.d.ts +36 -35
- package/dist/index.js +21 -20
- package/dist/policies/LambderApiGuards.d.ts +221 -0
- package/dist/policies/LambderApiGuards.js +79 -0
- package/dist/policies/LambderApiIdempotency.d.ts +58 -0
- package/dist/policies/LambderApiIdempotency.js +215 -0
- package/dist/policies/LambderApiPolicies.d.ts +40 -0
- package/dist/policies/LambderApiPolicies.js +47 -0
- package/dist/policies/LambderApiRateLimits.d.ts +90 -0
- package/dist/policies/LambderApiRateLimits.js +77 -0
- package/dist/{LambderSessionController.d.ts → session/LambderSessionController.d.ts} +2 -1
- package/dist/{LambderSessionController.js → session/LambderSessionController.js} +16 -11
- package/dist/{LambderSessionManager.d.ts → session/LambderSessionManager.d.ts} +38 -4
- package/dist/{LambderSessionManager.js → session/LambderSessionManager.js} +49 -16
- package/dist/{LambderApiContract.d.ts → shared/LambderApiContract.d.ts} +14 -0
- package/dist/{LambderApiError.d.ts → shared/LambderApiError.d.ts} +1 -1
- package/dist/{LambderDdbCache.js → stores/LambderDdbCache.js} +7 -38
- package/dist/stores/LambderDdbCompression.d.ts +3 -0
- package/dist/stores/LambderDdbCompression.js +39 -0
- package/dist/{LambderDdbIdempotency.d.ts → stores/LambderDdbIdempotency.d.ts} +41 -12
- package/dist/{LambderDdbIdempotency.js → stores/LambderDdbIdempotency.js} +100 -11
- package/dist/{LambderDdbRateLimiter.js → stores/LambderDdbRateLimiter.js} +5 -1
- package/dist/testing.d.ts +9 -0
- package/dist/testing.js +8 -0
- package/package.json +19 -1
- package/dist/LambderApiPolicies.d.ts +0 -212
- package/dist/LambderApiPolicies.js +0 -228
- /package/dist/{LambderMSW.js → client/LambderMSW.js} +0 -0
- /package/dist/{LambderCors.d.ts → core/LambderCors.d.ts} +0 -0
- /package/dist/{LambderCors.js → core/LambderCors.js} +0 -0
- /package/dist/{LambderPublicFiles.d.ts → core/LambderPublicFiles.d.ts} +0 -0
- /package/dist/{LambderResolver.d.ts → core/LambderResolver.d.ts} +0 -0
- /package/dist/{LambderResolver.js → core/LambderResolver.js} +0 -0
- /package/dist/{LambderResponse.d.ts → core/LambderResponse.d.ts} +0 -0
- /package/dist/{LambderRouting.d.ts → core/LambderRouting.d.ts} +0 -0
- /package/dist/{LambderRouting.js → core/LambderRouting.js} +0 -0
- /package/dist/{LambderApiContract.js → shared/LambderApiContract.js} +0 -0
- /package/dist/{LambderApiError.js → shared/LambderApiError.js} +0 -0
- /package/dist/{LambderHtml.d.ts → shared/LambderHtml.d.ts} +0 -0
- /package/dist/{LambderHtml.js → shared/LambderHtml.js} +0 -0
- /package/dist/{LambderI18n.d.ts → shared/LambderI18n.d.ts} +0 -0
- /package/dist/{LambderI18n.js → shared/LambderI18n.js} +0 -0
- /package/dist/{node-polyfills.d.ts → shared/node-polyfills.d.ts} +0 -0
- /package/dist/{node-polyfills.js → shared/node-polyfills.js} +0 -0
- /package/dist/{LambderDdbCache.d.ts → stores/LambderDdbCache.d.ts} +0 -0
- /package/dist/{LambderDdbRateLimiter.d.ts → stores/LambderDdbRateLimiter.d.ts} +0 -0
|
@@ -1,212 +0,0 @@
|
|
|
1
|
-
import type { z } from "zod";
|
|
2
|
-
import type { LambderRenderContext } from "./LambderContext.js";
|
|
3
|
-
import type LambderResolver from "./LambderResolver.js";
|
|
4
|
-
import type { LambderRateLimitPolicy, LambderDdbRateLimiter } from "./LambderDdbRateLimiter.js";
|
|
5
|
-
import type { LambderDdbIdempotency } from "./LambderDdbIdempotency.js";
|
|
6
|
-
import { LambderResponse } from "./LambderResponse.js";
|
|
7
|
-
/**
|
|
8
|
-
* A custom rate-limit key. `apiInput` names the fields of the API's OWN
|
|
9
|
-
* payload the key derives from: the slice is validated against the raw
|
|
10
|
-
* payload before `handler` runs (failures answer the standard 422 validation
|
|
11
|
-
* shape) and the handler receives it typed. Referencing the policy from an
|
|
12
|
-
* API whose input schema does not carry those fields is a compile error, so
|
|
13
|
-
* the API's schema stays the single owner of the field. Build with
|
|
14
|
-
* lambderRateLimitKey() so the handler's payload type follows `apiInput`.
|
|
15
|
-
*/
|
|
16
|
-
export type LambderRateLimitKeyFn<TInput extends z.ZodTypeAny = z.ZodTypeAny> = {
|
|
17
|
-
apiInput: TInput;
|
|
18
|
-
handler: (ctx: LambderRenderContext, payload: z.output<TInput>) => string | Promise<string>;
|
|
19
|
-
} | {
|
|
20
|
-
apiInput?: undefined;
|
|
21
|
-
handler: (ctx: LambderRenderContext, payload: undefined) => string | Promise<string>;
|
|
22
|
-
};
|
|
23
|
-
/**
|
|
24
|
-
* Builder that ties the handler's payload type to the `apiInput` schema
|
|
25
|
-
* inside one literal. Returns the exact union member so type extraction can
|
|
26
|
-
* see the schema.
|
|
27
|
-
*/
|
|
28
|
-
export declare function lambderRateLimitKey<TInput extends z.ZodTypeAny>(key: {
|
|
29
|
-
apiInput: TInput;
|
|
30
|
-
handler: (ctx: LambderRenderContext, payload: z.output<TInput>) => string | Promise<string>;
|
|
31
|
-
}): {
|
|
32
|
-
apiInput: TInput;
|
|
33
|
-
handler: (ctx: LambderRenderContext, payload: z.output<TInput>) => string | Promise<string>;
|
|
34
|
-
};
|
|
35
|
-
export declare function lambderRateLimitKey(key: {
|
|
36
|
-
handler: (ctx: LambderRenderContext, payload: undefined) => string | Promise<string>;
|
|
37
|
-
}): {
|
|
38
|
-
apiInput?: undefined;
|
|
39
|
-
handler: (ctx: LambderRenderContext, payload: undefined) => string | Promise<string>;
|
|
40
|
-
};
|
|
41
|
-
/** What one rate-limit counter tracks: the client IP, the session identity, or a custom payload-derived key. */
|
|
42
|
-
export type LambderRateLimitPer = "ip" | "session" | LambderRateLimitKeyFn<any>;
|
|
43
|
-
/** A named rate-limit policy: fixed windows plus the key one counter tracks. */
|
|
44
|
-
export type LambderApiRateLimitPolicyConfig = LambderRateLimitPolicy & {
|
|
45
|
-
per: LambderRateLimitPer;
|
|
46
|
-
/** Envelope errorMessage for refused requests. Default: a generic too-many-requests message. */
|
|
47
|
-
errorMessage?: any;
|
|
48
|
-
};
|
|
49
|
-
export type LambderApiRateLimitsConfig<TPolicies extends Record<string, LambderApiRateLimitPolicyConfig>> = {
|
|
50
|
-
/** Your limiter instance; its table, keyPrefix and failOpen apply as configured on it. */
|
|
51
|
-
limiter: LambderDdbRateLimiter;
|
|
52
|
-
/** Named policies referenced (typed) from addApi/addSessionApi. */
|
|
53
|
-
policies: TPolicies;
|
|
54
|
-
};
|
|
55
|
-
export type LambderApiIdempotencyConfig = {
|
|
56
|
-
/** Your idempotency store instance; may share the rate limiter's table (distinct key prefix). */
|
|
57
|
-
store: LambderDdbIdempotency;
|
|
58
|
-
/** Seconds a stored response replays for. Default: 86400 (24h). Per-API override: idempotency: { ttlSeconds }. */
|
|
59
|
-
defaultTtlSeconds?: number;
|
|
60
|
-
/** Skip idempotency (execute normally) when DynamoDB errors, instead of failing the request. Default: true. */
|
|
61
|
-
failOpen?: boolean;
|
|
62
|
-
};
|
|
63
|
-
/**
|
|
64
|
-
* A named guard, run before the API's own input validation. Two modes:
|
|
65
|
-
*
|
|
66
|
-
* - `apiInput`: the guard checks fields of the API's OWN payload. The slice
|
|
67
|
-
* is validated against the raw payload before `handler` runs and handed to
|
|
68
|
-
* it typed. The API's input schema stays the owner of those fields:
|
|
69
|
-
* declaring the guard on an API whose schema does not carry them is a
|
|
70
|
-
* compile error.
|
|
71
|
-
* - `guardInput`: the guard has its own value the client sends SEPARATELY,
|
|
72
|
-
* outside the API payload, via the caller's options.guardInputs[name].
|
|
73
|
-
* The requirement lands on the API's contract (`guardInputs`), so the
|
|
74
|
-
* typed caller refuses to compile a call that does not send it. The API
|
|
75
|
-
* payload and handler never see the value.
|
|
76
|
-
*
|
|
77
|
-
* Either way a validation failure answers the standard 422 shape, and the
|
|
78
|
-
* handler refuses by throwing (typically refuse()/LambderApiError). Build
|
|
79
|
-
* with lambderGuard() so the handler's payload type follows the schema.
|
|
80
|
-
*/
|
|
81
|
-
export type LambderApiGuard<TInput extends z.ZodTypeAny = z.ZodTypeAny> = {
|
|
82
|
-
apiInput: TInput;
|
|
83
|
-
guardInput?: undefined;
|
|
84
|
-
handler: (ctx: LambderRenderContext, payload: z.output<TInput>, res: LambderResolver) => void | Promise<void>;
|
|
85
|
-
} | {
|
|
86
|
-
guardInput: TInput;
|
|
87
|
-
apiInput?: undefined;
|
|
88
|
-
handler: (ctx: LambderRenderContext, payload: z.output<TInput>, res: LambderResolver) => void | Promise<void>;
|
|
89
|
-
} | {
|
|
90
|
-
apiInput?: undefined;
|
|
91
|
-
guardInput?: undefined;
|
|
92
|
-
handler: (ctx: LambderRenderContext, payload: undefined, res: LambderResolver) => void | Promise<void>;
|
|
93
|
-
};
|
|
94
|
-
/**
|
|
95
|
-
* Builder that ties the handler's payload type to the schema inside one
|
|
96
|
-
* literal. Returns the exact union member so mode/type extraction works.
|
|
97
|
-
*/
|
|
98
|
-
export declare function lambderGuard<TInput extends z.ZodTypeAny>(guard: {
|
|
99
|
-
apiInput: TInput;
|
|
100
|
-
handler: (ctx: LambderRenderContext, payload: z.output<TInput>, res: LambderResolver) => void | Promise<void>;
|
|
101
|
-
}): {
|
|
102
|
-
apiInput: TInput;
|
|
103
|
-
guardInput?: undefined;
|
|
104
|
-
handler: (ctx: LambderRenderContext, payload: z.output<TInput>, res: LambderResolver) => void | Promise<void>;
|
|
105
|
-
};
|
|
106
|
-
export declare function lambderGuard<TInput extends z.ZodTypeAny>(guard: {
|
|
107
|
-
guardInput: TInput;
|
|
108
|
-
handler: (ctx: LambderRenderContext, payload: z.output<TInput>, res: LambderResolver) => void | Promise<void>;
|
|
109
|
-
}): {
|
|
110
|
-
guardInput: TInput;
|
|
111
|
-
apiInput?: undefined;
|
|
112
|
-
handler: (ctx: LambderRenderContext, payload: z.output<TInput>, res: LambderResolver) => void | Promise<void>;
|
|
113
|
-
};
|
|
114
|
-
export declare function lambderGuard(guard: {
|
|
115
|
-
handler: (ctx: LambderRenderContext, payload: undefined, res: LambderResolver) => void | Promise<void>;
|
|
116
|
-
}): {
|
|
117
|
-
apiInput?: undefined;
|
|
118
|
-
guardInput?: undefined;
|
|
119
|
-
handler: (ctx: LambderRenderContext, payload: undefined, res: LambderResolver) => void | Promise<void>;
|
|
120
|
-
};
|
|
121
|
-
/** Per-guard metadata carried on the Lambder instance: mode plus payload type. */
|
|
122
|
-
export type LambderGuardMeta<G> = G extends {
|
|
123
|
-
apiInput: infer S extends z.ZodTypeAny;
|
|
124
|
-
} ? {
|
|
125
|
-
apiInput: z.output<S>;
|
|
126
|
-
} : G extends {
|
|
127
|
-
guardInput: infer S extends z.ZodTypeAny;
|
|
128
|
-
} ? {
|
|
129
|
-
guardInput: z.output<S>;
|
|
130
|
-
} : {};
|
|
131
|
-
export type LambderGuardMetaMap<TGuards> = {
|
|
132
|
-
[K in keyof TGuards]: LambderGuardMeta<TGuards[K]>;
|
|
133
|
-
};
|
|
134
|
-
type NamesIn<TOpt> = TOpt extends readonly (infer N extends string)[] ? N : TOpt extends string ? TOpt : never;
|
|
135
|
-
/** Guard names an API may declare: apiInput-mode guards only when the API's payload carries their fields. */
|
|
136
|
-
export type LambderAllowedGuardNames<TGuards, TPayload> = {
|
|
137
|
-
[K in keyof TGuards]: TGuards[K] extends {
|
|
138
|
-
apiInput: infer R;
|
|
139
|
-
} ? (TPayload extends R ? K : never) : K;
|
|
140
|
-
}[keyof TGuards] & string;
|
|
141
|
-
/**
|
|
142
|
-
* Policy names an API may reference: session-keyed policies only on session
|
|
143
|
-
* APIs, and apiInput-keyed policies only when the API's payload carries the
|
|
144
|
-
* key's fields.
|
|
145
|
-
*/
|
|
146
|
-
export type LambderAllowedPolicyNames<TPolicies, TPayload, TIncludeSession extends boolean> = {
|
|
147
|
-
[K in keyof TPolicies]: TPolicies[K] extends {
|
|
148
|
-
per: "session";
|
|
149
|
-
} ? (TIncludeSession extends true ? K : never) : TPolicies[K] extends {
|
|
150
|
-
per: {
|
|
151
|
-
apiInput: infer S extends z.ZodTypeAny;
|
|
152
|
-
};
|
|
153
|
-
} ? (TPayload extends z.output<S> ? K : never) : K;
|
|
154
|
-
}[keyof TPolicies] & string;
|
|
155
|
-
type GuardInputsEntries<TGuards, TOpt> = {
|
|
156
|
-
[K in Extract<NamesIn<TOpt>, keyof TGuards> as TGuards[K] extends {
|
|
157
|
-
guardInput: any;
|
|
158
|
-
} ? K : never]: TGuards[K] extends {
|
|
159
|
-
guardInput: infer V;
|
|
160
|
-
} ? V : never;
|
|
161
|
-
};
|
|
162
|
-
/** The guardInputs map an API's contract requires clients to send; never when no declared guard uses guardInput mode. */
|
|
163
|
-
export type LambderGuardInputsOf<TGuards, TOpt> = keyof GuardInputsEntries<TGuards, TOpt> extends never ? never : GuardInputsEntries<TGuards, TOpt>;
|
|
164
|
-
/**
|
|
165
|
-
* Runtime side of the declarative API options: holds what the enable/define
|
|
166
|
-
* calls declared, asserts registrations against it at startup, and executes
|
|
167
|
-
* rate limits, guards, and idempotency around handlers at request time.
|
|
168
|
-
* Internal to Lambder; apps interact through enableApiRateLimits(),
|
|
169
|
-
* enableApiIdempotency(), defineApiGuards() and the per-API options.
|
|
170
|
-
*/
|
|
171
|
-
export declare class LambderApiPolicyEngine {
|
|
172
|
-
private limiter;
|
|
173
|
-
private rateLimitPolicies;
|
|
174
|
-
private guards;
|
|
175
|
-
private idempotencyStore;
|
|
176
|
-
private idempotencyDefaultTtlSeconds;
|
|
177
|
-
private idempotencyFailOpen;
|
|
178
|
-
setRateLimits(config: LambderApiRateLimitsConfig<Record<string, LambderApiRateLimitPolicyConfig>>): void;
|
|
179
|
-
addGuards(guards: Record<string, LambderApiGuard<any>>): void;
|
|
180
|
-
setIdempotency(config: LambderApiIdempotencyConfig): void;
|
|
181
|
-
/** Startup validation of one API registration's declarative options. */
|
|
182
|
-
assertRegistration(apiName: string, mode: "public" | "session", options: {
|
|
183
|
-
rateLimit?: string | readonly string[];
|
|
184
|
-
guards?: string | readonly string[];
|
|
185
|
-
idempotency?: unknown;
|
|
186
|
-
}): void;
|
|
187
|
-
/** Rate limits then guards, in declared order. Refusals throw (LambderApiError or a guard's own throw). */
|
|
188
|
-
runPreflight(apiName: string, ctx: LambderRenderContext, resolver: LambderResolver, options: {
|
|
189
|
-
rateLimit?: string | readonly string[];
|
|
190
|
-
guards?: string | readonly string[];
|
|
191
|
-
}): Promise<void>;
|
|
192
|
-
/**
|
|
193
|
-
* Validate a preflight input slice (an apiInput slice of the raw payload,
|
|
194
|
-
* or a guardInput value from the raw guardInputs map). Runs before the
|
|
195
|
-
* API's own validation; failures answer the same 422 shape as regular
|
|
196
|
-
* input validation.
|
|
197
|
-
*/
|
|
198
|
-
private parseSlice;
|
|
199
|
-
private resolveRateLimitKey;
|
|
200
|
-
/**
|
|
201
|
-
* Idempotency wrapper around validation-passed handler execution. Without
|
|
202
|
-
* a client idempotencyKey the handler just runs; with one, the scope
|
|
203
|
-
* (identity + api + key) is claimed atomically: duplicates of an
|
|
204
|
-
* in-flight original refuse with 409, replays of a completed one return
|
|
205
|
-
* the stored response verbatim, and a crashed original releases its claim
|
|
206
|
-
* so a retry actually retries.
|
|
207
|
-
*/
|
|
208
|
-
withIdempotency(apiName: string, ctx: LambderRenderContext, config: boolean | {
|
|
209
|
-
ttlSeconds?: number;
|
|
210
|
-
}, exec: () => Promise<LambderResponse>): Promise<LambderResponse>;
|
|
211
|
-
}
|
|
212
|
-
export {};
|
|
@@ -1,228 +0,0 @@
|
|
|
1
|
-
import { LambderApiError } from "./LambderApiError.js";
|
|
2
|
-
import { LambderResponse } from "./LambderResponse.js";
|
|
3
|
-
/** A crashed original must not block retries forever: pending claims expire on their own. */
|
|
4
|
-
const IDEMPOTENCY_PENDING_TTL_SECONDS = 300;
|
|
5
|
-
/** Responses above this size skip replay storage (DynamoDB item limit is 400KB). */
|
|
6
|
-
const IDEMPOTENCY_MAX_STORED_BODY_BYTES = 350_000;
|
|
7
|
-
const RATE_LIMIT_WINDOW_KEYS = ["perMin", "per10Min", "perHour", "perDay", "perWeek", "perMonth"];
|
|
8
|
-
export function lambderRateLimitKey(key) { return key; }
|
|
9
|
-
export function lambderGuard(guard) { return guard; }
|
|
10
|
-
const toList = (value) => value === undefined ? [] : typeof value === "string" ? [value] : value;
|
|
11
|
-
/**
|
|
12
|
-
* Runtime side of the declarative API options: holds what the enable/define
|
|
13
|
-
* calls declared, asserts registrations against it at startup, and executes
|
|
14
|
-
* rate limits, guards, and idempotency around handlers at request time.
|
|
15
|
-
* Internal to Lambder; apps interact through enableApiRateLimits(),
|
|
16
|
-
* enableApiIdempotency(), defineApiGuards() and the per-API options.
|
|
17
|
-
*/
|
|
18
|
-
export class LambderApiPolicyEngine {
|
|
19
|
-
limiter = null;
|
|
20
|
-
rateLimitPolicies = {};
|
|
21
|
-
guards = {};
|
|
22
|
-
idempotencyStore = null;
|
|
23
|
-
idempotencyDefaultTtlSeconds = 24 * 3600;
|
|
24
|
-
idempotencyFailOpen = true;
|
|
25
|
-
setRateLimits(config) {
|
|
26
|
-
if (this.limiter)
|
|
27
|
-
throw new Error("Lambder: enableApiRateLimits() was already called.");
|
|
28
|
-
for (const [name, policy] of Object.entries(config.policies)) {
|
|
29
|
-
const per = policy.per;
|
|
30
|
-
if (!per || (per !== "ip" && per !== "session" && typeof per.handler !== "function")) {
|
|
31
|
-
throw new Error(`Lambder: rate-limit policy "${name}" needs per: "ip", "session", or a { apiInput?, handler } key.`);
|
|
32
|
-
}
|
|
33
|
-
if (!RATE_LIMIT_WINDOW_KEYS.some((key) => policy[key])) {
|
|
34
|
-
throw new Error(`Lambder: rate-limit policy "${name}" declares no window (${RATE_LIMIT_WINDOW_KEYS.join("/")}).`);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
this.limiter = config.limiter;
|
|
38
|
-
this.rateLimitPolicies = { ...config.policies };
|
|
39
|
-
}
|
|
40
|
-
addGuards(guards) {
|
|
41
|
-
for (const [name, guardDef] of Object.entries(guards)) {
|
|
42
|
-
if (this.guards[name])
|
|
43
|
-
throw new Error(`Lambder: guard "${name}" is already defined.`);
|
|
44
|
-
if (typeof guardDef?.handler !== "function")
|
|
45
|
-
throw new Error(`Lambder: guard "${name}" has no handler function.`);
|
|
46
|
-
if (guardDef.apiInput && guardDef.guardInput)
|
|
47
|
-
throw new Error(`Lambder: guard "${name}" declares both apiInput and guardInput; pick one.`);
|
|
48
|
-
this.guards[name] = guardDef;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
setIdempotency(config) {
|
|
52
|
-
if (this.idempotencyStore)
|
|
53
|
-
throw new Error("Lambder: enableApiIdempotency() was already called.");
|
|
54
|
-
this.idempotencyStore = config.store;
|
|
55
|
-
this.idempotencyDefaultTtlSeconds = config.defaultTtlSeconds ?? 24 * 3600;
|
|
56
|
-
this.idempotencyFailOpen = config.failOpen ?? true;
|
|
57
|
-
}
|
|
58
|
-
/** Startup validation of one API registration's declarative options. */
|
|
59
|
-
assertRegistration(apiName, mode, options) {
|
|
60
|
-
for (const name of toList(options.rateLimit)) {
|
|
61
|
-
const policy = this.rateLimitPolicies[name];
|
|
62
|
-
if (!policy) {
|
|
63
|
-
throw new Error(`Lambder: API "${apiName}" references unknown rate-limit policy "${name}". Declare it via enableApiRateLimits() before registering the API.`);
|
|
64
|
-
}
|
|
65
|
-
if (policy.per === "session" && mode !== "session") {
|
|
66
|
-
throw new Error(`Lambder: API "${apiName}" uses rate-limit policy "${name}" (per "session"), which requires addSessionApi.`);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
for (const name of toList(options.guards)) {
|
|
70
|
-
if (!this.guards[name]) {
|
|
71
|
-
throw new Error(`Lambder: API "${apiName}" references unknown guard "${name}". Define it via defineApiGuards() before registering the API.`);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
if (options.idempotency !== undefined && !this.idempotencyStore) {
|
|
75
|
-
throw new Error(`Lambder: API "${apiName}" declares idempotency but enableApiIdempotency() was not called first.`);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
/** Rate limits then guards, in declared order. Refusals throw (LambderApiError or a guard's own throw). */
|
|
79
|
-
async runPreflight(apiName, ctx, resolver, options) {
|
|
80
|
-
for (const name of toList(options.rateLimit)) {
|
|
81
|
-
const policy = this.rateLimitPolicies[name];
|
|
82
|
-
if (!policy || !this.limiter)
|
|
83
|
-
throw new Error(`Lambder: rate-limit policy "${name}" is not configured.`);
|
|
84
|
-
const key = await this.resolveRateLimitKey(ctx, resolver, policy.per);
|
|
85
|
-
const limited = await this.limiter.isRateLimited(`api|${apiName}|${name}|${key}`, policy);
|
|
86
|
-
if (limited) {
|
|
87
|
-
throw new LambderApiError(`Rate limited: "${apiName}" exceeded policy "${name}".`, {
|
|
88
|
-
errorMessage: policy.errorMessage ?? "Too many requests. Please try again later.",
|
|
89
|
-
statusCode: 429,
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
for (const name of toList(options.guards)) {
|
|
94
|
-
const guardDef = this.guards[name];
|
|
95
|
-
if (!guardDef)
|
|
96
|
-
throw new Error(`Lambder: guard "${name}" is not configured.`);
|
|
97
|
-
const post = ctx.post;
|
|
98
|
-
let payload;
|
|
99
|
-
if (guardDef.apiInput) {
|
|
100
|
-
payload = this.parseSlice(guardDef.apiInput, post?.payload, resolver);
|
|
101
|
-
}
|
|
102
|
-
else if (guardDef.guardInput) {
|
|
103
|
-
payload = this.parseSlice(guardDef.guardInput, post?.guardInputs?.[name], resolver);
|
|
104
|
-
}
|
|
105
|
-
await guardDef.handler(ctx, payload, resolver);
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
|
-
* Validate a preflight input slice (an apiInput slice of the raw payload,
|
|
110
|
-
* or a guardInput value from the raw guardInputs map). Runs before the
|
|
111
|
-
* API's own validation; failures answer the same 422 shape as regular
|
|
112
|
-
* input validation.
|
|
113
|
-
*/
|
|
114
|
-
parseSlice(input, value, resolver) {
|
|
115
|
-
const parsed = input.safeParse(value);
|
|
116
|
-
if (!parsed.success) {
|
|
117
|
-
throw resolver.json({ error: "Input validation failed", zodError: parsed.error }, { statusCode: 422 });
|
|
118
|
-
}
|
|
119
|
-
return parsed.data;
|
|
120
|
-
}
|
|
121
|
-
async resolveRateLimitKey(ctx, resolver, per) {
|
|
122
|
-
if (per === "ip")
|
|
123
|
-
return `ip:${ctx.ip}`;
|
|
124
|
-
if (per === "session") {
|
|
125
|
-
const sessionKey = ctx.session?.sessionKey;
|
|
126
|
-
if (!sessionKey)
|
|
127
|
-
throw new Error('Lambder: rate-limit per "session" evaluated without a session on the context.');
|
|
128
|
-
return `session:${sessionKey}`;
|
|
129
|
-
}
|
|
130
|
-
const payload = per.apiInput
|
|
131
|
-
? this.parseSlice(per.apiInput, ctx.post?.payload, resolver)
|
|
132
|
-
: undefined;
|
|
133
|
-
return `custom:${await per.handler(ctx, payload)}`;
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* Idempotency wrapper around validation-passed handler execution. Without
|
|
137
|
-
* a client idempotencyKey the handler just runs; with one, the scope
|
|
138
|
-
* (identity + api + key) is claimed atomically: duplicates of an
|
|
139
|
-
* in-flight original refuse with 409, replays of a completed one return
|
|
140
|
-
* the stored response verbatim, and a crashed original releases its claim
|
|
141
|
-
* so a retry actually retries.
|
|
142
|
-
*/
|
|
143
|
-
async withIdempotency(apiName, ctx, config, exec) {
|
|
144
|
-
const store = this.idempotencyStore;
|
|
145
|
-
const rawKey = ctx.post?.idempotencyKey;
|
|
146
|
-
if (!store || rawKey === undefined || rawKey === null)
|
|
147
|
-
return await exec();
|
|
148
|
-
if (typeof rawKey !== "string" || rawKey.length < 1 || rawKey.length > 200) {
|
|
149
|
-
throw new LambderApiError("Invalid idempotency key.", { statusCode: 400 });
|
|
150
|
-
}
|
|
151
|
-
const ttlSeconds = (typeof config === "object" ? config.ttlSeconds : undefined) ?? this.idempotencyDefaultTtlSeconds;
|
|
152
|
-
// Scoped per identity so clients cannot collide with or poison each other's keys.
|
|
153
|
-
const sessionKey = ctx.session?.sessionKey;
|
|
154
|
-
const scopeKey = `${sessionKey ? `s:${sessionKey}` : `ip:${ctx.ip}`}|${apiName}|${rawKey}`;
|
|
155
|
-
let begun;
|
|
156
|
-
try {
|
|
157
|
-
begun = await store.begin(scopeKey, { pendingTtlSeconds: IDEMPOTENCY_PENDING_TTL_SECONDS });
|
|
158
|
-
}
|
|
159
|
-
catch (err) {
|
|
160
|
-
if (this.idempotencyFailOpen)
|
|
161
|
-
return await exec();
|
|
162
|
-
throw err;
|
|
163
|
-
}
|
|
164
|
-
if (begun.state === "pending") {
|
|
165
|
-
throw new LambderApiError(`Duplicate request for "${apiName}": the original is still processing.`, {
|
|
166
|
-
statusCode: 409,
|
|
167
|
-
errorMessage: "This request is already being processed.",
|
|
168
|
-
});
|
|
169
|
-
}
|
|
170
|
-
if (begun.state === "done") {
|
|
171
|
-
return new LambderResponse({
|
|
172
|
-
statusCode: begun.statusCode,
|
|
173
|
-
headers: begun.contentType ? { "Content-Type": begun.contentType } : {},
|
|
174
|
-
body: begun.body,
|
|
175
|
-
});
|
|
176
|
-
}
|
|
177
|
-
const ownerToken = begun.ownerToken;
|
|
178
|
-
// Store the response for replays when it qualifies, release the claim
|
|
179
|
-
// otherwise. Settle failures only surface when failing closed.
|
|
180
|
-
const settleClaim = async (response) => {
|
|
181
|
-
const cacheable = response.statusCode < 500
|
|
182
|
-
&& typeof response.body === "string"
|
|
183
|
-
&& !response.isBodyBase64
|
|
184
|
-
&& response.body.length <= IDEMPOTENCY_MAX_STORED_BODY_BYTES;
|
|
185
|
-
try {
|
|
186
|
-
if (cacheable) {
|
|
187
|
-
await store.complete(scopeKey, ownerToken, {
|
|
188
|
-
statusCode: response.statusCode,
|
|
189
|
-
contentType: response.getHeader("Content-Type")?.[0] ?? null,
|
|
190
|
-
body: response.body,
|
|
191
|
-
ttlSeconds,
|
|
192
|
-
});
|
|
193
|
-
}
|
|
194
|
-
else {
|
|
195
|
-
await store.abandon(scopeKey, ownerToken);
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
catch (storeErr) {
|
|
199
|
-
if (!this.idempotencyFailOpen)
|
|
200
|
-
throw storeErr;
|
|
201
|
-
}
|
|
202
|
-
};
|
|
203
|
-
try {
|
|
204
|
-
const response = await exec();
|
|
205
|
-
await settleClaim(response);
|
|
206
|
-
return response;
|
|
207
|
-
}
|
|
208
|
-
catch (err) {
|
|
209
|
-
// A thrown LambderResponse IS the response (res.die.*, throw
|
|
210
|
-
// res.api(...)): settle the claim like a returned one so its side
|
|
211
|
-
// effect replays, then rethrow so the pipeline emits it.
|
|
212
|
-
if (err instanceof LambderResponse) {
|
|
213
|
-
await settleClaim(err);
|
|
214
|
-
throw err;
|
|
215
|
-
}
|
|
216
|
-
// A real crash (or a refusal like LambderApiError) releases the
|
|
217
|
-
// claim so a retry actually retries.
|
|
218
|
-
try {
|
|
219
|
-
await store.abandon(scopeKey, ownerToken);
|
|
220
|
-
}
|
|
221
|
-
catch (cleanupErr) {
|
|
222
|
-
if (!this.idempotencyFailOpen)
|
|
223
|
-
throw cleanupErr;
|
|
224
|
-
}
|
|
225
|
-
throw err;
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|